Files
othmanadi__planning-with-files/scripts/ledger-append.ps1
T
OthmanAdi 3749f86ac3 fix: bind explicit plan selectors, floor slug modes on the project root, and classify doctor output on the data frame
Three defects reported by Raymond Manaloto (@sortakool), each reproduced on
Windows with Git Bash before any code changed. Two of them let a session work
on a plan nobody selected; the third made the diagnostic that should have
caught them report PASS.

closes #237: an explicit PLAN_ID was a hint, not a binding

resolve_from_env returned 1 both when no selector was set and when the selector
was rejected, so a PLAN_ID of valid slug shape naming no directory fell through
to .active_plan and then to newest-by-mtime. attest-plan.sh locked that other
plan at rc=0 and injection followed it. The guard in attest-plan.sh written for
exactly this case was unreachable, because the resolver never returned empty.
commands/plan-attest.md has promised the opposite since v3.9.0.

A non-empty PLAN_ID now resolves or stops, for every rejection reason: slug
shape (traversal included), naming no directory, or failing containment. An
empty value still means unset, which init-session.sh depends on. The rule went
into every resolver, because they disagreed otherwise: resolve-plan-dir.sh,
resolve-plan-dir.ps1, the inline resolver inside inject-plan.sh, and the
Hermes, OpenCode and Pi plugin resolvers. v3.14.0 had made the two plugin
resolvers fall through to match the shell; that parity was right and its target
was wrong.

Fixing the resolver alone would have moved the bug rather than removed it, so
every consumer was audited. check-complete.sh would have read the root plan's
completion state, which decides whether an autonomous run may stop.
ledger-summary.sh feeds phase counts into autonomous turns. phase-status.sh and
ledger-append.sh write into the directory they pick. The five Codex hooks call
the resolver directly and each fell through to the legacy root, stop.sh and
pre-compact.sh included. All of them now stop on a rejected selector, and the
once-per-turn routes print a notice, because a fail-closed path with no stated
cause would trade a wrong-plan bug for a silent one.

closes #238: a slug plan with no .mode bypassed the project's root .mode

A project makes attestation mandatory by committing a root .mode, a reviewed
project setting. inject-plan.sh read the slug's .mode and never the root's, and
init-session.sh writes no .mode unless --autonomous or --gated was passed, so
init-session.sh <name>, which /plan runs, produced a plan with no attestation
requirement and full injection. The policy was a flag the agent chose at plan
creation.

The root .mode is now a floor. Strictness-raising tokens count from either
file, so a slug may raise and never lower; the one strictness-lowering token,
plan-guard-off, needs the root's agreement. The same floor applies to the
completion gate in check-complete.sh and check-complete.ps1, which read .mode
the same way and had the same bypass, and to the Hermes and OpenCode plugins.
init-session.sh seeds a new slug from the root .mode so the effective policy is
visible in the plan directory, not only in the resolver. With no root .mode
present the effective token set is exactly the slug's, so existing projects are
unchanged.

closes #236: plan-doctor.sh reported PASS on a fully dark-hooks state

The injection check substring-matched five control strings against output that
carries the plan body verbatim inside the BEGIN-PWF-DATA fences. A plan whose
phase line read "fix the false PLAN TAMPERED warning in plan-doctor" reported a
hash mismatch while correctly attested. Worse, the PWF_PLAN_ROOT arm matched a
literal that is not a substring of what inject-plan.sh emits, so the arm was
dead code and execution fell to the success arm: PWF_PLAN_ROOT=/nonexistent
printed "PASS injection: emits plan context (123 bytes)" while nothing was
injected, counting the refusal notice's own bytes as plan context. The file's
own comment four lines above already warned against exactly that.

Classification now branches on the frame. Every refusal path exits before
frame_file runs, so a frame proves injection happened and unframed output is by
construction a notice. The default arm warns, so a reworded or translated
banner degrades noisily instead of silently. The stale literal is corrected
against the emitting echo.

Tests: Python suite 653 to 696, OpenCode Vitest 28 to 34. New files
test_plan_selector_binding.py, test_root_mode_floor.py and
test_plan_doctor_classification.py; new arms in test_resolver_parity.py,
test_resolve_plan_dir.py, test_resolver_plan_root_pin.py and
test_hermes_first_class.py. Five existing tests asserted the fall-through and
were rewritten to assert the refusal, keeping their original security
assertion. Each suite carries a control arm: two first drafts passed on
fixtures that could not have failed, a gate assertion over a plan with every
phase complete and a parallel-write-guard assertion over a plan with nothing
checked to lose.
2026-09-03 00:23:03 +02:00

190 lines
6.7 KiB
PowerShell

#requires -Version 5.0
<#
.SYNOPSIS
Append one structured entry to the run-ledger (PowerShell mirror, v3).
.DESCRIPTION
The run-ledger is the machine layer of progress tracking: an append-only
JSON-lines file per agent under the active plan dir. Workers append here;
the orchestrator owns progress.md and task_plan.md. See architecture C3.
Plan-dir resolution (matches resolve-plan-dir.ps1):
1. $env:PLAN_ID -> .\.planning\$PLAN_ID\
2. .\.planning\.active_plan
3. Newest .\.planning\<dir>\ by LastWriteTime
4. Legacy: project root (ledger lands beside .\task_plan.md)
Writes ONE JSON line to <plan-dir>\ledger-<agent>.jsonl. tick = 1 + max tick
across ALL ledger-*.jsonl in the plan dir so concurrent agents share a
monotonic counter.
.PARAMETER Event
One of: progress phase_complete error gate_block attest note.
.PARAMETER Summary
Free text, truncated to 200 chars, newlines stripped.
.PARAMETER Agent
Ledger owner (default "main"); sanitized to [A-Za-z0-9_-].
.PARAMETER Phase
Phase number/name this entry concerns.
.PARAMETER Files
Comma-separated file list recorded as a JSON array.
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $true, Position = 0)]
[string] $Event,
[Parameter(Mandatory = $true, Position = 1)]
[string] $Summary,
[string] $Agent = "main",
[string] $Phase = "",
[string] $Files = ""
)
$ErrorActionPreference = "Stop"
$validEvents = @("progress", "phase_complete", "error", "gate_block", "attest", "note")
function Resolve-PlanDir {
$planRoot = Join-Path (Get-Location) ".planning"
# A set PLAN_ID is a BINDING, not a hint (issue #237). This script WRITES
# ledger rows into the directory it picks, so falling through to
# .active_plan, newest-by-mtime and finally the cwd after a mistyped pin
# files another plan's run history.
if ($env:PLAN_ID) {
$candidate = Join-Path $planRoot $env:PLAN_ID
if (Test-Path -LiteralPath $candidate -PathType Container) { return $candidate }
return $null
}
$activePointer = Join-Path $planRoot ".active_plan"
if (Test-Path -LiteralPath $activePointer) {
$planId = (Get-Content -LiteralPath $activePointer -Raw).Trim()
if ($planId) {
$candidate = Join-Path $planRoot $planId
if (Test-Path -LiteralPath $candidate -PathType Container) { return $candidate }
}
}
if (Test-Path -LiteralPath $planRoot -PathType Container) {
$newest = Get-ChildItem -LiteralPath $planRoot -Directory -ErrorAction SilentlyContinue |
Where-Object { -not $_.Name.StartsWith(".") } |
Where-Object { Test-Path -LiteralPath (Join-Path $_.FullName "task_plan.md") } |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
if ($newest) { return $newest.FullName }
}
# Legacy single-file mode: ledger lives beside .\task_plan.md at root.
return (Get-Location).Path
}
function ConvertTo-JsonString {
param([string] $Value)
$sb = New-Object System.Text.StringBuilder
foreach ($ch in $Value.ToCharArray()) {
switch ($ch) {
'"' { [void]$sb.Append('\"') }
'\' { [void]$sb.Append('\\') }
"`n" { [void]$sb.Append(' ') }
"`r" { [void]$sb.Append(' ') }
"`t" { [void]$sb.Append(' ') }
default {
if ([int]$ch -lt 32) {
[void]$sb.Append(' ')
} else {
[void]$sb.Append($ch)
}
}
}
}
return $sb.ToString()
}
function Get-MaxTick {
param([string] $Dir)
$max = 0
$pattern = '"tick"\s*:\s*(\d+)'
Get-ChildItem -LiteralPath $Dir -Filter "ledger-*.jsonl" -File -ErrorAction SilentlyContinue | ForEach-Object {
foreach ($line in (Get-Content -LiteralPath $_.FullName -ErrorAction SilentlyContinue)) {
$m = [regex]::Match($line, $pattern)
if ($m.Success) {
$t = [int]$m.Groups[1].Value
if ($t -gt $max) { $max = $t }
}
}
}
return $max
}
# Validate event against the allowlist.
if ($validEvents -notcontains $Event) {
Write-Error ("[ledger] invalid event '" + $Event + "' (allowed: " + ($validEvents -join ' ') + ")")
exit 2
}
# Sanitize agent name to [A-Za-z0-9_-]; empty result falls back to "main".
$agentClean = ($Agent -replace '[^A-Za-z0-9_-]', '')
if (-not $agentClean) { $agentClean = "main" }
# Truncate summary to the 200-character budget before escaping, matching the
# sh twin. .NET Substring counts characters, never bytes, so multibyte input
# cannot be clipped mid-codepoint here and no UTF-8 tail repair is needed.
if ($Summary.Length -gt 200) { $Summary = $Summary.Substring(0, 200) }
$planDir = Resolve-PlanDir
if (-not $planDir) {
Write-Error "[ledger-append] An explicit PLAN_ID did not resolve to a plan directory; nothing was written and no other plan was substituted."
exit 1
}
$ledgerFile = Join-Path $planDir ("ledger-" + $agentClean + ".jsonl")
$lockFile = Join-Path $planDir ".ledger_lock"
$ts = [DateTime]::UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ")
# Build the files JSON array from the comma-separated list.
$filesJson = "[]"
if ($Files) {
$parts = $Files.Split(",") | Where-Object { $_ -ne "" }
$escaped = $parts | ForEach-Object { '"' + (ConvertTo-JsonString $_) + '"' }
$filesJson = "[" + ($escaped -join ",") + "]"
}
$summaryEsc = ConvertTo-JsonString $Summary
$phaseEsc = ConvertTo-JsonString $Phase
# Acquire an exclusive lock on a sidecar so concurrent appenders do not pick
# the same tick number, then compute tick and append inside the locked window.
# Atomic append of a single <4KB line is the real guarantee; the lock just
# serializes the read-tick / write-line pair.
$fs = $null
$acquired = $false
for ($i = 0; $i -lt 50 -and -not $acquired; $i++) {
try {
$fs = [System.IO.File]::Open($lockFile, [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None)
$acquired = $true
} catch {
Start-Sleep -Milliseconds 100
}
}
try {
$tick = (Get-MaxTick $planDir) + 1
$line = '{"tick":' + $tick + ',"ts":"' + $ts + '","agent":"' + $agentClean + '","phase":"' + $phaseEsc + '","event":"' + $Event + '","summary":"' + $summaryEsc + '","files":' + $filesJson + '}'
Add-Content -LiteralPath $ledgerFile -Value $line -Encoding utf8
} finally {
if ($fs) { $fs.Close(); $fs.Dispose() }
if (Test-Path -LiteralPath $lockFile) { Remove-Item -LiteralPath $lockFile -Force -ErrorAction SilentlyContinue }
}
Write-Output ("[ledger] tick " + $tick + " -> " + $ledgerFile + " (event=" + $Event + " agent=" + $agentClean + ")")
exit 0