from pathlib import Path
import zipfile, textwrap, shutil
outdir = Path("/mnt/data/evaai_municode")
outdir.mkdir(exist_ok=True)
script = r'''#Requires -Version 5.1
<#
.SYNOPSIS
EVAAI / Sawlties / PiEve CLI with Atbash, UTF-8 binary framing,
SHA-256, token metadata, factor trees, and a combined Municode codec.
.EXAMPLES
.\evaai.ps1 -Mode encode -Text "la_seductrice:banana🍌" -IncludeDigest
.\evaai.ps1 -Mode decode -EncodedStream $stream
.\evaai.ps1 -Mode tree -Number 24
.\evaai.ps1 -Mode smoke
.\evaai.ps1 -Mode municode -MunicodeAction inspect -Text "ALPHA,OMEGA;Keter"
.\evaai.ps1 -Mode municode -MunicodeAction encode -Text "ALPHA,OMEGA;Keter" -IncludeDigest
.\evaai.ps1 -Mode municode -MunicodeAction decode -EncodedStream $stream
.\evaai.ps1 -Mode municode -MunicodeAction inspect -Text "A.B,C" -PunctuationTablePath .\punctuation.csv
.NOTES
The punctuation table is a user-defined four-column CSV: a,an,b,bn.
The parser treats values in columns an and bn as boundary characters,
matching the original Python prototype. No unprovided symbolic mapping
is invented. Encoding frames the complete original string, preserving
punctuation and whitespace exactly; tokenization is an analysis layer.
>
[CmdletBinding()]
param(
[ValidateSet("encode", "decode", "tree", "smoke", "municode")]
[string]$Mode = "encode",
[AllowEmptyString()]
[string]$Text = "la_seductrice:banana🍌",
[AllowEmptyString()]
[string]$EncodedStream = "",
[ValidateSet("Η", "H")]
[string]$Marker = "Η",
[string]$Route = "evaai.route.default",
[string]$Label = "EVAAI.Target",
[ValidateRange(1, 2147483647)]
[int]$Number = 24,
[switch]$IncludeDigest,
[switch]$Raw,
[ValidateSet("inspect", "encode", "decode")]
[string]$MunicodeAction = "inspect",
[string]$PunctuationTablePath = "",
[AllowEmptyString()]
[string]$Punctuation = ""
)
Set-StrictMode -Version Latest
$ErrorActionPreference = "Stop"
$script:FrameLength = 21
$script:FrameRegex = [regex]'(?s)[(Η|H)i]^2([01]{8})[/\1i]^2'
$script:Utf8Strict = [System.Text.UTF8Encoding]::new($false, $true)
$script:TokenMetadata = @{
"S" = @{ Prime = 2; Fraction = "1/2" }
"e" = @{ Prime = 3; Fraction = "1/3" }
"r" = @{ Prime = 5; Fraction = "1/5" }
"n" = @{ Prime = 7; Fraction = "1/7" }
"I" = @{ Prime = 11; Fraction = "1/11" }
}
function Invoke-AtbashChar {
param([char]$Char)
$code = [int]$Char
if ($code -ge 97 -and $code -le 122) {
return char
}
if ($code -ge 65 -and $code -le 90) {
return char
}
return $Char
}
function Invoke-AtbashText {
param([AllowEmptyString()][string]$InputText)
if ([string]::IsNullOrEmpty($InputText)) { return "" }
$sb = [System.Text.StringBuilder]::new($InputText.Length)
foreach ($ch in $InputText.ToCharArray()) {
[void]$sb.Append((Invoke-AtbashChar -Char $ch))
}
return $sb.ToString()
}
function New-BinaryFrame {
param(
[ValidateRange(0, 255)][int]$ByteValue,
[ValidateSet("Η", "H")][string]$FrameMarker = "Η"
)
$bits = [Convert]::ToString($ByteValue, 2).PadLeft(8, '0')
$frame = "[{0}i]^2{1}[/{0}i]^2" -f $FrameMarker, $bits
if ($frame.Length -ne $script:FrameLength) {
throw "Expected frame length $($script:FrameLength), got $($frame.Length)."
}
return $frame
}
function ConvertTo-AtbashHi2 {
param(
[AllowEmptyString()][string]$PlainText,
[ValidateSet("Η", "H")][string]$FrameMarker = "Η"
)
if ([string]::IsNullOrEmpty($PlainText)) { return "" }
$reflected = Invoke-AtbashText -InputText $PlainText
$utf8Bytes = [System.Text.Encoding]::UTF8.GetBytes($reflected)
$sb = [System.Text.StringBuilder]::new($utf8Bytes.Length * $script:FrameLength)
foreach ($b in $utf8Bytes) {
[void]$sb.Append((New-BinaryFrame -ByteValue $b -FrameMarker $FrameMarker))
}
return $sb.ToString()
}
function ConvertFrom-AtbashHi2 {
param([AllowEmptyString()][string]$Stream)
if ($null -eq $Stream) { return "" }
$cleaned = $Stream.Trim()
if ([string]::IsNullOrEmpty($cleaned)) { return "" }
$matches = $script:FrameRegex.Matches($cleaned)
if ($matches.Count -eq 0) {
throw "No valid frames found; stream may be empty, corrupted, or truncated."
}
$cursor = 0
$byteList = [System.Collections.Generic.List[byte]]::new($matches.Count)
foreach ($m in $matches) {
if ($m.Index -ne $cursor -or $m.Length -ne $script:FrameLength) {
throw "Corrupted, truncated, or mismatched frames detected."
}
$byteList.Add([Convert]::ToByte($m.Groups[2].Value, 2))
$cursor = $m.Index + $m.Length
}
if ($cursor -ne $cleaned.Length) {
throw "Trailing or unframed data detected."
}
try {
$reflected = $script:Utf8Strict.GetString($byteList.ToArray())
}
catch {
throw "Frame bytes are not valid UTF-8: $($_.Exception.Message)"
}
return (Invoke-AtbashText -InputText $reflected)
}
function Get-Sha256Hex {
param([AllowEmptyString()][string]$Value)
$bytes = [System.Text.Encoding]::UTF8.GetBytes($(if ($null -eq $Value) { "" } else { $Value }))
$sha = [System.Security.Cryptography.SHA256]::Create()
try {
$hashBytes = $sha.ComputeHash($bytes)
return ([System.BitConverter]::ToString($hashBytes) -replace '-', '').ToLowerInvariant()
}
finally { $sha.Dispose() }
}
function Get-TokenMetadataMatches {
param([AllowEmptyString()][string]$InputText)
$results = @()
if ([string]::IsNullOrEmpty($InputText)) { return $results }
foreach ($ch in $InputText.ToCharArray()) {
$key = [string]$ch
if ($script:TokenMetadata.ContainsKey($key)) {
$meta = $script:TokenMetadata[$key]
$results += [PSCustomObject]@{
Symbol = $key
Prime = $meta.Prime
Fraction = $meta.Fraction
}
}
}
return $results
}
function Get-FactorTree {
param([int]$N)
if ($N -lt 1) { throw "Integer must be >= 1." }
if ($N -eq 1) { return @("1") }
$limit = [int][Math]::Floor([Math]::Sqrt($N))
for ($i = 2; $i -le $limit; $i++) {
if (($N % $i) -eq 0) {
$left = Get-FactorTree -N $i
$right = Get-FactorTree -N (int)
return (@("(") + $left + $right + @(")"))
}
}
return @([string]$N)
}
function Format-GroupedPrompt {
param([hashtable]$Groups)
$lines = [System.Collections.Generic.List[string]]::new()
foreach ($groupName in $Groups.Keys) {
$cleaned = @()
foreach ($item in $Groups[$groupName]) {
if (-not [string]::IsNullOrWhiteSpace([string]$item)) {
$cleaned += ([string]$item).Trim()
}
}
if ($cleaned.Count -gt 0) {
$lines.Add(("{0}: [{1}]" -f $groupName, ($cleaned -join ", ")))
}
}
return ($lines -join [Environment]::NewLine)
}
function Get-MunicodePunctuation {
param(
[string]$TablePath,
[AllowEmptyString()][string]$ExtraPunctuation
)
$set = [System.Collections.Generic.HashSet[string]]::new(
[System.StringComparer]::Ordinal
)
if (-not [string]::IsNullOrWhiteSpace($TablePath)) {
if (-not (Test-Path -LiteralPath $TablePath -PathType Leaf)) {
throw "Punctuation table not found: $TablePath"
}
$rows = Import-Csv -LiteralPath $TablePath
foreach ($column in @("a", "an", "b", "bn")) {
if ($rows.Count -gt 0 -and
-not ($rows[0].PSObject.Properties.Name -contains $column)) {
throw "Punctuation CSV must contain columns: a, an, b, bn."
}
}
foreach ($row in $rows) {
foreach ($value in @($row.an, $row.bn)) {
if (-not [string]::IsNullOrEmpty([string]$value)) {
foreach ($ch in ([string]$value).ToCharArray()) {
[void]$set.Add([string]$ch)
}
}
}
}
}
if (-not [string]::IsNullOrEmpty($ExtraPunctuation)) {
foreach ($ch in $ExtraPunctuation.ToCharArray()) {
[void]$set.Add([string]$ch)
}
}
return @($set)
}
function ConvertTo-MunicodeTokens {
param(
[AllowEmptyString()][string]$InputText,
[string[]]$PunctuationChars = @()
)
$out = [System.Collections.Generic.List[string]]::new()
$chunk = [System.Text.StringBuilder]::new()
foreach ($ch in $InputText.ToCharArray()) {
$symbol = [string]$ch
if ($PunctuationChars -contains $symbol) {
if ($chunk.Length -gt 0) {
$out.Add($chunk.ToString() + $symbol)
[void]$chunk.Clear()
}
else {
$out.Add($symbol)
}
}
else {
[void]$chunk.Append($ch)
}
}
if ($chunk.Length -gt 0) { $out.Add($chunk.ToString()) }
return $out.ToArray()
}
function Test-MunicodeUnicode {
param([AllowEmptyString()][string]$InputText)
$issues = [System.Collections.Generic.List[object]]::new()
$matches = [regex]::Matches($InputText, 'U+[0-9A-Fa-f]{1,6}')
foreach ($m in $matches) {
$value = [Convert]::ToInt32($m.Value.Substring(2), 16)
$valid = ($value -le 0x10FFFF -and -not ($value -ge 0xD800 -and $value -le 0xDFFF))
$issues.Add([PSCustomObject]@{
Token = $m.Value
ValidScalar = $valid
Character = $(if ($valid) { [char]::ConvertFromUtf32($value) } else { "" })
Note = $(if ($valid) { "" } else { "Invalid Unicode scalar value" })
})
}
$entities = [regex]::Matches($InputText, '&#[^;\s]*;')
foreach ($m in $entities) {
$body = $m.Value.Substring(2, $m.Value.Length - 3)
$validSyntax = ($body -match '^\d+$' -or $body -match '^[xX][0-9A-Fa-f]+$')
$issues.Add([PSCustomObject]@{
Token = $m.Value
ValidScalar = $validSyntax
Character = ""
Note = $(if ($validSyntax) { "Entity syntax appears valid; scalar range not yet evaluated" } else { "Malformed numeric HTML entity" })
})
}
return $issues.ToArray()
}
function New-EvaAiRoutePayload {
param(
[string]$RouteName,
[string]$TargetLabel,
[AllowEmptyString()][string]$RawText,
[ValidateSet("Η", "H")][string]$FrameMarker,
[bool]$WithDigest
)
$encoded = ConvertTo-AtbashHi2 -PlainText $RawText -FrameMarker $FrameMarker
$decoded = ConvertFrom-AtbashHi2 -Stream $encoded
$involutionOk = ((Invoke-AtbashText -InputText (Invoke-AtbashText -InputText $RawText)) -eq $RawText)
$digest = if ($WithDigest) { Get-Sha256Hex -Value $RawText } else { $null }
[PSCustomObject]@{
Engine = "EVAAI"
Route = $RouteName
TargetLabel = $TargetLabel
Marker = $FrameMarker
RoundTripOk = ($decoded -ceq $RawText)
InvolutionOk = $involutionOk
FrameLength = $script:FrameLength
EncodedLength = $encoded.Length
Sha256Digest = $digest
TokenMetadata = (Get-TokenMetadataMatches -InputText $RawText)
EncodedStream = $encoded
DecodedText = $decoded
}
}
function Invoke-MunicodeMode {
param()
$punctuationChars = Get-MunicodePunctuation -TablePath $PunctuationTablePath -ExtraPunctuation $Punctuation
$tokens = ConvertTo-MunicodeTokens -InputText $Text -PunctuationChars $punctuationChars
switch ($MunicodeAction) {
"inspect" {
$validation = Test-MunicodeUnicode -InputText $Text
$result = [PSCustomObject]@{
Format = "MUNICODE-TEXT-V1"
OriginalText = $Text
Punctuation = $punctuationChars
Tokens = $tokens
UnicodeChecks = $validation
}
if ($Raw) { return ($result | ConvertTo-Json -Depth 8) }
Write-Host "--- Municode Inspection ---"
Write-Host "Tokens:"
foreach ($token in $tokens) { Write-Host (" " + $token) }
if ($validation.Count -gt 0) {
Write-Host "Validation:"
$validation | Format-Table -AutoSize | Out-Host
}
else { Write-Host "No explicit U+ code points or numeric HTML entities found." }
}
"encode" {
$payload = New-EvaAiRoutePayload -RouteName $Route -TargetLabel $Label `
-RawText $Text -FrameMarker $Marker -WithDigest $IncludeDigest.IsPresent
$result = [PSCustomObject]@{
Format = "MUNICODE-EVAAI-V1"
Route = $Route
TargetLabel = $Label
Punctuation = $punctuationChars
Tokens = $tokens
RoundTripOk = $payload.RoundTripOk
Sha256Digest = $payload.Sha256Digest
EncodedStream = $payload.EncodedStream
}
if ($Raw) { return ($result | ConvertTo-Json -Depth 8) }
Write-Host "--- Municode / EVAAI Encoded Payload ---"
Write-Host "Tokens: $($tokens -join ' | ')"
Write-Host "Round-Trip OK: $($payload.RoundTripOk)"
if ($payload.Sha256Digest) { Write-Host "SHA-256: $($payload.Sha256Digest)" }
Write-Host $payload.EncodedStream
}
"decode" {
$decoded = ConvertFrom-AtbashHi2 -Stream $EncodedStream
$decodedTokens = ConvertTo-MunicodeTokens -InputText $decoded -PunctuationChars $punctuationChars
$result = [PSCustomObject]@{
Format = "MUNICODE-EVAAI-V1"
DecodedText = $decoded
Tokens = $decodedTokens
UnicodeChecks = (Test-MunicodeUnicode -InputText $decoded)
}
if ($Raw) { return ($result | ConvertTo-Json -Depth 8) }
Write-Host "--- Municode / EVAAI Decoded Payload ---"
Write-Host "Decoded text: $decoded"
Write-Host "Tokens: $($decodedTokens -join ' | ')"
}
}
}
switch ($Mode) {
"encode" {
$payload = New-EvaAiRoutePayload -RouteName $Route -TargetLabel $Label `
-RawText $Text -FrameMarker $Marker -WithDigest $IncludeDigest.IsPresent
if ($Raw) { Write-Output $payload.EncodedStream; return }
$promptText = Format-GroupedPrompt -Groups @{
Engine = @("EVAAI")
Profile = @($Label)
Route = @($Route)
Codec = @("Atbash -> UTF-8 -> 21-char [Ηi]^2")
}
Write-Host "--- EVAAI Grouped Prompt ---"
Write-Host $promptText
Write-Host "`n--- EVAAI Routed Payload ---"
Write-Host "Route: $($payload.Route)"
Write-Host "Target Label: $($payload.TargetLabel)"
Write-Host "Round-Trip OK: $($payload.RoundTripOk)"
Write-Host "Involution OK: $($payload.InvolutionOk)"
Write-Host "Frame Length: $($payload.FrameLength)"
Write-Host "Encoded Chars: $($payload.EncodedLength)"
if ($payload.Sha256Digest) { Write-Host "SHA-256: $($payload.Sha256Digest)" }
if ($payload.TokenMetadata.Count -gt 0) {
Write-Host "Token Meta: $(($payload.TokenMetadata | ForEach-Object { "$($_.Symbol)($($_.Prime),$($_.Fraction))" }) -join ', ')"
}
Write-Host "Encoded Stream:"
Write-Host $payload.EncodedStream
}
"decode" {
$decodedText = ConvertFrom-AtbashHi2 -Stream $EncodedStream
if ($Raw) { Write-Output $decodedText; return }
Write-Host "--- EVAAI Decoded Payload ---"
Write-Host "Route: $Route"
Write-Host "Decoded Text: $decodedText"
}
"tree" {
$treeTokens = Get-FactorTree -N $Number
if ($Raw) { Write-Output ($treeTokens -join ''); return }
Write-Host "EVAAI::tree($Number) -> $($treeTokens -join '') | tokens=[$($treeTokens -join ', ')]"
}
"smoke" {
$samples = @(
@{ Name = "empty"; Value = "" },
@{ Name = "ascii"; Value = "Sawlties / PiEve / EVAAI" },
@{ Name = "banana"; Value = "la_seductrice:banana🍌" },
@{ Name = "sereni"; Value = "Sereni" },
@{ Name = "municode"; Value = "ALPHA,OMEGA;Keter U+0391" }
)
foreach ($sample in $samples) {
$r = New-EvaAiRoutePayload -RouteName "evaai.smoke.$($sample.Name)" `
-TargetLabel $Label -RawText $sample.Value -FrameMarker $Marker `
-WithDigest ($sample.Name -eq "banana")
Write-Host ("{0,-22} ok={1,-5} inv={2,-5} chars={3,-6} digest={4}" -f `
$r.Route, $r.RoundTripOk, $r.InvolutionOk, $r.EncodedLength, $r.Sha256Digest)
}
}
"municode" {
Invoke-MunicodeMode
}
}
'''
(outdir / "evaai.ps1").write_text(script, encoding="utf-8-sig")
(outdir / "punctuation.example.csv").write_text(
"a,an,b,bn\nOPEN,.,CLOSE,;\nLEFT,,,RIGHT,:\n",
encoding="utf-8"
)
(outdir / "README.md").write_text(textwrap.dedent("""\
EVAAI Municode Combined Codec (PowerShell 5.1)
This revision preserves the original encode, decode, tree, and smoke modes and adds municode.
Municode actions
Inspect text and split tokens:
.\\evaai.ps1 -Mode municode -MunicodeAction inspect -Text "ALPHA,OMEGA;Keter"
Encode the exact original text using Atbash -> UTF-8 -> 21-character byte frames:
.\\evaai.ps1 -Mode municode -MunicodeAction encode -Text "ALPHA,OMEGA;Keter" -IncludeDigest
Decode a previously generated stream:
.\\evaai.ps1 -Mode municode -MunicodeAction decode -EncodedStream $stream
Use a custom four-column CSV:
.\\evaai.ps1 -Mode municode -MunicodeAction inspect -Text "A.B,C" -PunctuationTablePath .\\punctuation.csv
The CSV must have headers a,an,b,bn. Following the supplied Python prototype, values in an and bn are treated as punctuation boundary characters. The example CSV is illustrative only; replace it with your actual table.
Alternatively specify punctuation directly:
.\\evaai.ps1 -Mode municode -MunicodeAction inspect -Text "A.B,C" -Punctuation ". ,"
Design guarantees
- The original string is encoded intact, including spaces and punctuation.
- Token splitting is an analysis layer; it does not discard separators.
- The 21-character frame contains 6 opening-marker characters, 8 payload bits, and 7 closing-marker characters.
- UTF-8 decoding is strict and rejects invalid byte sequences.
-
U+03911is a valid five-hex-digit scalar and is not rewritten toU+0391. - HTML entity syntax is checked separately; the current validator reports syntax, not full HTML5 named-entity semantics.
- No image recognition or semantic Municode mapping is invented. """), encoding="utf-8")
zip_path = Path("/mnt/data/evaai_municode_powershell51.zip")
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as z:
for p in outdir.iterdir():
z.write(p, p.name)
print("Created:", outdir / "evaai.ps1")
print("Created:", zip_path, zip_path.stat().st_size)
Top comments (0)