Compare commits

...
10 Commits
Author SHA1 Message Date
OthmanAdi f01a88a12b release: v3.20.2
Hermes plugin 0.2.2: the launch-directory notice for the Hermes 0.21.3
first-turn TERMINAL_CWD rewrite, the /pwf-status and /pwf diagnostics,
and PWF_PLAN_ROOT honored by the slash commands (#272).

Parity set bumped to 3.20.2 with scripts/bump-version.py. CHANGELOG,
CONTRIBUTORS.md (@ericshunhinglee-cloud), README releases row,
CITATION.cff date.
2026-09-19 09:59:30 +02:00
OthmanAdi 9a3843b31d docs(hermes): describe the Hermes 0.21.3 working-directory rewrite and the pin
Adds the section on the first-turn TERMINAL_CWD rewrite: the mechanism,
what was reproduced with the 0.21.0 source, what the plugin says since
v3.20.2, the PWF_PLAN_ROOT pin for project-scoped CLI sessions, the
shell-hook route as the unaffected alternative, and the home-directory
inverse risk (#272).
2026-09-19 09:57:44 +02:00
OthmanAdi 1528b31d7f fix(hermes): name the launch directory plan when the host re-homes the working directory
On Hermes 0.21.3 the first turn of a CLI session rewrites the
process-global TERMINAL_CWD to the home directory (agent/relay_runtime.py
imports gateway/run.py lazily, whose import-time bridge applies the
Path.home() fallback), so resolve_agent_cwd() names HOME, the hooks find
no plan there and inject nothing. The rewrite runs before the first
plugin hook, so the plugin cannot recover the root and does not guess.

pre_llm_call now injects one line naming the resolved directory, the
launch directory that holds a plan, and the PWF_PLAN_ROOT pin instead of
returning nothing. CLI only; silent for hermes -w worktree sessions
(TERMINAL_CWD at <repo>/.worktrees/<name> without a chdir is intended),
for a launch directory without planning state, and for a launch
directory whose session isolation refuses the session.

/pwf and /pwf-status honor PWF_PLAN_ROOT like the hooks and report a pin
that does not resolve instead of acting in the directory Hermes named.
/pwf-status prints the same line under "No planning files found", and
/pwf appends it when the plan it created went somewhere other than a
launch directory that already holds one.

Fixes #272. Upstream: NousResearch/hermes-agent#86411, #95577.
2026-09-19 09:57:38 +02:00
OthmanAdi faf1a15a7d release: v3.20.1 2026-09-18 17:32:57 +02:00
OthmanAdi c05821a1cf fix(init): bind the attest selectors in slug mode only, clear them in root mode
Binding PWF_PLAN_ROOT for the attestation call in both modes (#265) made
root-mode --autonomous and --gated plans unattested on the shell and the
PowerShell route: the attester only falls back to the legacy ./task_plan.md
when no selector is set and refuses the root plan under an explicit pin,
while init still reported the plan as attested and every hook then refused
to inject it. Slug mode keeps the binding from #265 (PWF_PLAN_ROOT and
PLAN_ID name the plan just created); root mode now clears both selectors,
which also stops an inherited PLAN_ID from redirecting the shell attester
to a sibling slug plan, as the PowerShell twin already did (#261).

Regression tests cover root-mode attestation for --autonomous and --gated
with and without an inherited PWF_PLAN_ROOT and PLAN_ID, on both routes.
2026-09-18 17:32:57 +02:00
kuei51307-hub 52572e3301 docs(hermes): clarify multiple-plan selection 2026-09-18 17:32:09 +02:00
kuei51307-hub 1df6f5808b fix(hermes): require selector for multiple plans 2026-09-18 17:32:09 +02:00
TayfurYldz d03002bcee fix: normalize multiline plan slugs 2026-09-18 17:31:54 +02:00
TayfurYldz 1bea197584 fix: bind init attestation to current project 2026-09-18 17:31:38 +02:00
Shaun Lin e33359977c fix(catchup): skip malformed OpenCode parts 2026-09-18 17:31:18 +02:00
66 changed files with 961 additions and 186 deletions
+1 -1
View File
@@ -28,7 +28,7 @@ hooks:
- type: command
command: "SH=\"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\"; [ -f \"$SH\" ] || SH=$(ls \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\" 2>/dev/null | head -1); [ -n \"$SH\" ] && [ -f \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
# Planning with Files
@@ -350,16 +350,23 @@ if ($Mode -ne "") {
# (c) auto-attest (attestation default-on in v3 modes, security strand rec 1).
# attest-plan.ps1 intentionally refuses non-Windows hosts because its secure
# no-follow implementation uses Win32 handles. On Unix, use the POSIX
# attester instead. Bind slug mode to the plan we just created so an
# inherited PLAN_ID cannot redirect attestation to another plan.
# attester instead. Slug mode binds PWF_PLAN_ROOT and PLAN_ID to the plan
# we just created so an inherited pin or slug cannot redirect attestation
# to another project or plan (#261, #237). Root mode clears both instead:
# the attester only falls back to the legacy ./task_plan.md when no
# selector is set, and a bound pin would make it refuse the root plan.
$PlanFilePwf = Join-Path $PlanDirPwf "task_plan.md"
if (Test-Path -LiteralPath $PlanFilePwf) {
$HadPlanId = Test-Path Env:PLAN_ID
$PreviousPlanId = $env:PLAN_ID
$HadPlanRoot = Test-Path Env:PWF_PLAN_ROOT
$PreviousPlanRoot = $env:PWF_PLAN_ROOT
try {
if ($UsePlanDir) {
$env:PWF_PLAN_ROOT = (Get-Location).Path
$env:PLAN_ID = $PlanId
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
@@ -384,6 +391,11 @@ if ($Mode -ne "") {
} else {
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
if ($HadPlanRoot) {
$env:PWF_PLAN_ROOT = $PreviousPlanRoot
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
}
}
}
@@ -103,6 +103,7 @@ slugify() {
# Lowercase, non-alphanumerics → '-', collapse repeats, trim leading/trailing '-'
printf '%s' "$1" \
| tr '[:upper:]' '[:lower:]' \
| tr '\r\n' '--' \
| sed -e 's/[^a-z0-9]/-/g' -e 's/-\{2,\}/-/g' -e 's/^-//' -e 's/-$//' \
| cut -c1-40
}
@@ -202,12 +203,20 @@ apply_v3_mode() {
# (c) auto-attest the plan (attestation default-on in v3 modes, security
# strand rec 1). attest-plan.sh resolves the same way init-session just
# pinned things: in slug mode PLAN_ID points at this plan dir; in legacy
# mode it is empty and the script falls back to ./task_plan.md at root.
# Run from the project root (CWD here) so both resolutions land.
# pinned things. Slug mode binds both selectors to the plan that was
# just created, so an inherited PWF_PLAN_ROOT or PLAN_ID cannot
# redirect attestation to another project or plan (#261, #237). Root
# mode clears both instead: the attester only falls back to the legacy
# ./task_plan.md when no selector is set, and a bound pin would make it
# refuse the root plan. Run from the project root (CWD here) so both
# resolutions land.
_attest="${SCRIPT_DIR}/attest-plan.sh"
if [ -f "${_attest}" ] && [ -f "${_mode_plan}" ]; then
PLAN_ID="${PLAN_ID:-}" sh "${_attest}" >/dev/null 2>&1 || true
if [ "$SLUG_MODE" -eq 1 ]; then
PWF_PLAN_ROOT="$PWD" PLAN_ID="${PLAN_ID}" sh "${_attest}" >/dev/null 2>&1 || true
else
PWF_PLAN_ROOT="" PLAN_ID="" sh "${_attest}" >/dev/null 2>&1 || true
fi
fi
}
@@ -474,7 +474,7 @@ def _format_opencode_part(data: Dict[str, Any], session_id: str) -> Optional[Dic
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ or {}
input_ = input_ if isinstance(input_, dict) else {}
outcome = _opencode_state_annotation(state)
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
@@ -577,6 +577,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
+1 -1
View File
@@ -10,7 +10,7 @@
"name": "planning-with-files",
"source": "./",
"description": "Persistent project planning files with lifecycle hooks that inject selected plan context. Automatic recovery uses project files only. Explicit catchup modes may read same-project local session records to emit aggregate counts or bounded nonce-framed excerpts. Optional gated mode can request continuation on capable hosts and never runs commands declared in Markdown. No network upload path. Installs across 60+ agents.",
"version": "3.20.0"
"version": "3.20.2"
}
]
}
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planning-with-files",
"version": "3.20.0",
"version": "3.20.2",
"description": "Persistent project planning files with lifecycle hooks that inject selected plan context. Automatic recovery uses project files only. Explicit catchup modes may read same-project local session records to emit aggregate counts or bounded nonce-framed excerpts. Optional gated mode can request continuation on capable hosts and never runs commands declared in Markdown. No network upload path. Works across 60+ agents and includes Arabic, German, Spanish, Simplified Chinese, and Traditional Chinese.",
"author": {
"name": "OthmanAdi",
@@ -36,7 +36,7 @@ hooks:
- type: command
command: "SH=\"\"; for c in \"${PWF_SCRIPT_DIR}/skill-hook.sh\" \"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\" \"${CODEBUDDY_PLUGIN_ROOT}/scripts/skill-hook.sh\" \"$HOME/.codebuddy/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\"; do [ -f \"$c\" ] && { SH=\"$c\"; break; }; done; [ -n \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
@@ -350,16 +350,23 @@ if ($Mode -ne "") {
# (c) auto-attest (attestation default-on in v3 modes, security strand rec 1).
# attest-plan.ps1 intentionally refuses non-Windows hosts because its secure
# no-follow implementation uses Win32 handles. On Unix, use the POSIX
# attester instead. Bind slug mode to the plan we just created so an
# inherited PLAN_ID cannot redirect attestation to another plan.
# attester instead. Slug mode binds PWF_PLAN_ROOT and PLAN_ID to the plan
# we just created so an inherited pin or slug cannot redirect attestation
# to another project or plan (#261, #237). Root mode clears both instead:
# the attester only falls back to the legacy ./task_plan.md when no
# selector is set, and a bound pin would make it refuse the root plan.
$PlanFilePwf = Join-Path $PlanDirPwf "task_plan.md"
if (Test-Path -LiteralPath $PlanFilePwf) {
$HadPlanId = Test-Path Env:PLAN_ID
$PreviousPlanId = $env:PLAN_ID
$HadPlanRoot = Test-Path Env:PWF_PLAN_ROOT
$PreviousPlanRoot = $env:PWF_PLAN_ROOT
try {
if ($UsePlanDir) {
$env:PWF_PLAN_ROOT = (Get-Location).Path
$env:PLAN_ID = $PlanId
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
@@ -384,6 +391,11 @@ if ($Mode -ne "") {
} else {
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
if ($HadPlanRoot) {
$env:PWF_PLAN_ROOT = $PreviousPlanRoot
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
}
}
}
@@ -103,6 +103,7 @@ slugify() {
# Lowercase, non-alphanumerics → '-', collapse repeats, trim leading/trailing '-'
printf '%s' "$1" \
| tr '[:upper:]' '[:lower:]' \
| tr '\r\n' '--' \
| sed -e 's/[^a-z0-9]/-/g' -e 's/-\{2,\}/-/g' -e 's/^-//' -e 's/-$//' \
| cut -c1-40
}
@@ -202,12 +203,20 @@ apply_v3_mode() {
# (c) auto-attest the plan (attestation default-on in v3 modes, security
# strand rec 1). attest-plan.sh resolves the same way init-session just
# pinned things: in slug mode PLAN_ID points at this plan dir; in legacy
# mode it is empty and the script falls back to ./task_plan.md at root.
# Run from the project root (CWD here) so both resolutions land.
# pinned things. Slug mode binds both selectors to the plan that was
# just created, so an inherited PWF_PLAN_ROOT or PLAN_ID cannot
# redirect attestation to another project or plan (#261, #237). Root
# mode clears both instead: the attester only falls back to the legacy
# ./task_plan.md when no selector is set, and a bound pin would make it
# refuse the root plan. Run from the project root (CWD here) so both
# resolutions land.
_attest="${SCRIPT_DIR}/attest-plan.sh"
if [ -f "${_attest}" ] && [ -f "${_mode_plan}" ]; then
PLAN_ID="${PLAN_ID:-}" sh "${_attest}" >/dev/null 2>&1 || true
if [ "$SLUG_MODE" -eq 1 ]; then
PWF_PLAN_ROOT="$PWD" PLAN_ID="${PLAN_ID}" sh "${_attest}" >/dev/null 2>&1 || true
else
PWF_PLAN_ROOT="" PLAN_ID="" sh "${_attest}" >/dev/null 2>&1 || true
fi
fi
}
@@ -474,7 +474,7 @@ def _format_opencode_part(data: Dict[str, Any], session_id: str) -> Optional[Dic
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ or {}
input_ = input_ if isinstance(input_, dict) else {}
outcome = _opencode_state_annotation(state)
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
@@ -577,6 +577,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planning-with-files",
"version": "3.20.0",
"version": "3.20.2",
"description": "Persistent project planning for Codex. Opt-in lifecycle hooks inject selected plan context; automatic recovery uses project files only. Explicit catchup modes may read same-project local session records to emit aggregate counts or bounded nonce-framed excerpts. Optional gated mode can request continuation on capable hosts and never runs Markdown-declared commands. No network upload path.",
"author": {
"name": "OthmanAdi",
+1 -1
View File
@@ -36,7 +36,7 @@ hooks:
- type: command
command: "SH=\"\"; for c in \"${PWF_SCRIPT_DIR}/skill-hook.sh\" \"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\" \"$HOME/.codex/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\"; do [ -f \"$c\" ] && { SH=\"$c\"; break; }; done; [ -n \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
@@ -350,16 +350,23 @@ if ($Mode -ne "") {
# (c) auto-attest (attestation default-on in v3 modes, security strand rec 1).
# attest-plan.ps1 intentionally refuses non-Windows hosts because its secure
# no-follow implementation uses Win32 handles. On Unix, use the POSIX
# attester instead. Bind slug mode to the plan we just created so an
# inherited PLAN_ID cannot redirect attestation to another plan.
# attester instead. Slug mode binds PWF_PLAN_ROOT and PLAN_ID to the plan
# we just created so an inherited pin or slug cannot redirect attestation
# to another project or plan (#261, #237). Root mode clears both instead:
# the attester only falls back to the legacy ./task_plan.md when no
# selector is set, and a bound pin would make it refuse the root plan.
$PlanFilePwf = Join-Path $PlanDirPwf "task_plan.md"
if (Test-Path -LiteralPath $PlanFilePwf) {
$HadPlanId = Test-Path Env:PLAN_ID
$PreviousPlanId = $env:PLAN_ID
$HadPlanRoot = Test-Path Env:PWF_PLAN_ROOT
$PreviousPlanRoot = $env:PWF_PLAN_ROOT
try {
if ($UsePlanDir) {
$env:PWF_PLAN_ROOT = (Get-Location).Path
$env:PLAN_ID = $PlanId
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
@@ -384,6 +391,11 @@ if ($Mode -ne "") {
} else {
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
if ($HadPlanRoot) {
$env:PWF_PLAN_ROOT = $PreviousPlanRoot
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
}
}
}
@@ -103,6 +103,7 @@ slugify() {
# Lowercase, non-alphanumerics → '-', collapse repeats, trim leading/trailing '-'
printf '%s' "$1" \
| tr '[:upper:]' '[:lower:]' \
| tr '\r\n' '--' \
| sed -e 's/[^a-z0-9]/-/g' -e 's/-\{2,\}/-/g' -e 's/^-//' -e 's/-$//' \
| cut -c1-40
}
@@ -202,12 +203,20 @@ apply_v3_mode() {
# (c) auto-attest the plan (attestation default-on in v3 modes, security
# strand rec 1). attest-plan.sh resolves the same way init-session just
# pinned things: in slug mode PLAN_ID points at this plan dir; in legacy
# mode it is empty and the script falls back to ./task_plan.md at root.
# Run from the project root (CWD here) so both resolutions land.
# pinned things. Slug mode binds both selectors to the plan that was
# just created, so an inherited PWF_PLAN_ROOT or PLAN_ID cannot
# redirect attestation to another project or plan (#261, #237). Root
# mode clears both instead: the attester only falls back to the legacy
# ./task_plan.md when no selector is set, and a bound pin would make it
# refuse the root plan. Run from the project root (CWD here) so both
# resolutions land.
_attest="${SCRIPT_DIR}/attest-plan.sh"
if [ -f "${_attest}" ] && [ -f "${_mode_plan}" ]; then
PLAN_ID="${PLAN_ID:-}" sh "${_attest}" >/dev/null 2>&1 || true
if [ "$SLUG_MODE" -eq 1 ]; then
PWF_PLAN_ROOT="$PWD" PLAN_ID="${PLAN_ID}" sh "${_attest}" >/dev/null 2>&1 || true
else
PWF_PLAN_ROOT="" PLAN_ID="" sh "${_attest}" >/dev/null 2>&1 || true
fi
fi
}
@@ -474,7 +474,7 @@ def _format_opencode_part(data: Dict[str, Any], session_id: str) -> Optional[Dic
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ or {}
input_ = input_ if isinstance(input_, dict) else {}
outcome = _opencode_state_annotation(state)
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
@@ -577,6 +577,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
@@ -350,16 +350,23 @@ if ($Mode -ne "") {
# (c) auto-attest (attestation default-on in v3 modes, security strand rec 1).
# attest-plan.ps1 intentionally refuses non-Windows hosts because its secure
# no-follow implementation uses Win32 handles. On Unix, use the POSIX
# attester instead. Bind slug mode to the plan we just created so an
# inherited PLAN_ID cannot redirect attestation to another plan.
# attester instead. Slug mode binds PWF_PLAN_ROOT and PLAN_ID to the plan
# we just created so an inherited pin or slug cannot redirect attestation
# to another project or plan (#261, #237). Root mode clears both instead:
# the attester only falls back to the legacy ./task_plan.md when no
# selector is set, and a bound pin would make it refuse the root plan.
$PlanFilePwf = Join-Path $PlanDirPwf "task_plan.md"
if (Test-Path -LiteralPath $PlanFilePwf) {
$HadPlanId = Test-Path Env:PLAN_ID
$PreviousPlanId = $env:PLAN_ID
$HadPlanRoot = Test-Path Env:PWF_PLAN_ROOT
$PreviousPlanRoot = $env:PWF_PLAN_ROOT
try {
if ($UsePlanDir) {
$env:PWF_PLAN_ROOT = (Get-Location).Path
$env:PLAN_ID = $PlanId
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
@@ -384,6 +391,11 @@ if ($Mode -ne "") {
} else {
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
if ($HadPlanRoot) {
$env:PWF_PLAN_ROOT = $PreviousPlanRoot
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
}
}
}
@@ -103,6 +103,7 @@ slugify() {
# Lowercase, non-alphanumerics → '-', collapse repeats, trim leading/trailing '-'
printf '%s' "$1" \
| tr '[:upper:]' '[:lower:]' \
| tr '\r\n' '--' \
| sed -e 's/[^a-z0-9]/-/g' -e 's/-\{2,\}/-/g' -e 's/^-//' -e 's/-$//' \
| cut -c1-40
}
@@ -202,12 +203,20 @@ apply_v3_mode() {
# (c) auto-attest the plan (attestation default-on in v3 modes, security
# strand rec 1). attest-plan.sh resolves the same way init-session just
# pinned things: in slug mode PLAN_ID points at this plan dir; in legacy
# mode it is empty and the script falls back to ./task_plan.md at root.
# Run from the project root (CWD here) so both resolutions land.
# pinned things. Slug mode binds both selectors to the plan that was
# just created, so an inherited PWF_PLAN_ROOT or PLAN_ID cannot
# redirect attestation to another project or plan (#261, #237). Root
# mode clears both instead: the attester only falls back to the legacy
# ./task_plan.md when no selector is set, and a bound pin would make it
# refuse the root plan. Run from the project root (CWD here) so both
# resolutions land.
_attest="${SCRIPT_DIR}/attest-plan.sh"
if [ -f "${_attest}" ] && [ -f "${_mode_plan}" ]; then
PLAN_ID="${PLAN_ID:-}" sh "${_attest}" >/dev/null 2>&1 || true
if [ "$SLUG_MODE" -eq 1 ]; then
PWF_PLAN_ROOT="$PWD" PLAN_ID="${PLAN_ID}" sh "${_attest}" >/dev/null 2>&1 || true
else
PWF_PLAN_ROOT="" PLAN_ID="" sh "${_attest}" >/dev/null 2>&1 || true
fi
fi
}
@@ -474,7 +474,7 @@ def _format_opencode_part(data: Dict[str, Any], session_id: str) -> Optional[Dic
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ or {}
input_ = input_ if isinstance(input_, dict) else {}
outcome = _opencode_state_annotation(state)
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
@@ -577,6 +577,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
+1 -1
View File
@@ -36,7 +36,7 @@ hooks:
- type: command
command: "SH=\"\"; for c in \"${PWF_SCRIPT_DIR}/skill-hook.sh\" \"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\" \"$HOME/.cursor/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\"; do [ -f \"$c\" ] && { SH=\"$c\"; break; }; done; [ -n \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
@@ -350,16 +350,23 @@ if ($Mode -ne "") {
# (c) auto-attest (attestation default-on in v3 modes, security strand rec 1).
# attest-plan.ps1 intentionally refuses non-Windows hosts because its secure
# no-follow implementation uses Win32 handles. On Unix, use the POSIX
# attester instead. Bind slug mode to the plan we just created so an
# inherited PLAN_ID cannot redirect attestation to another plan.
# attester instead. Slug mode binds PWF_PLAN_ROOT and PLAN_ID to the plan
# we just created so an inherited pin or slug cannot redirect attestation
# to another project or plan (#261, #237). Root mode clears both instead:
# the attester only falls back to the legacy ./task_plan.md when no
# selector is set, and a bound pin would make it refuse the root plan.
$PlanFilePwf = Join-Path $PlanDirPwf "task_plan.md"
if (Test-Path -LiteralPath $PlanFilePwf) {
$HadPlanId = Test-Path Env:PLAN_ID
$PreviousPlanId = $env:PLAN_ID
$HadPlanRoot = Test-Path Env:PWF_PLAN_ROOT
$PreviousPlanRoot = $env:PWF_PLAN_ROOT
try {
if ($UsePlanDir) {
$env:PWF_PLAN_ROOT = (Get-Location).Path
$env:PLAN_ID = $PlanId
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
@@ -384,6 +391,11 @@ if ($Mode -ne "") {
} else {
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
if ($HadPlanRoot) {
$env:PWF_PLAN_ROOT = $PreviousPlanRoot
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
}
}
}
@@ -103,6 +103,7 @@ slugify() {
# Lowercase, non-alphanumerics → '-', collapse repeats, trim leading/trailing '-'
printf '%s' "$1" \
| tr '[:upper:]' '[:lower:]' \
| tr '\r\n' '--' \
| sed -e 's/[^a-z0-9]/-/g' -e 's/-\{2,\}/-/g' -e 's/^-//' -e 's/-$//' \
| cut -c1-40
}
@@ -202,12 +203,20 @@ apply_v3_mode() {
# (c) auto-attest the plan (attestation default-on in v3 modes, security
# strand rec 1). attest-plan.sh resolves the same way init-session just
# pinned things: in slug mode PLAN_ID points at this plan dir; in legacy
# mode it is empty and the script falls back to ./task_plan.md at root.
# Run from the project root (CWD here) so both resolutions land.
# pinned things. Slug mode binds both selectors to the plan that was
# just created, so an inherited PWF_PLAN_ROOT or PLAN_ID cannot
# redirect attestation to another project or plan (#261, #237). Root
# mode clears both instead: the attester only falls back to the legacy
# ./task_plan.md when no selector is set, and a bound pin would make it
# refuse the root plan. Run from the project root (CWD here) so both
# resolutions land.
_attest="${SCRIPT_DIR}/attest-plan.sh"
if [ -f "${_attest}" ] && [ -f "${_mode_plan}" ]; then
PLAN_ID="${PLAN_ID:-}" sh "${_attest}" >/dev/null 2>&1 || true
if [ "$SLUG_MODE" -eq 1 ]; then
PWF_PLAN_ROOT="$PWD" PLAN_ID="${PLAN_ID}" sh "${_attest}" >/dev/null 2>&1 || true
else
PWF_PLAN_ROOT="" PLAN_ID="" sh "${_attest}" >/dev/null 2>&1 || true
fi
fi
}
@@ -474,7 +474,7 @@ def _format_opencode_part(data: Dict[str, Any], session_id: str) -> Optional[Dic
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ or {}
input_ = input_ if isinstance(input_, dict) else {}
outcome = _opencode_state_annotation(state)
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
@@ -577,6 +577,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
+1 -1
View File
@@ -36,7 +36,7 @@ hooks:
- type: command
command: "SH=\"\"; for c in \"${PWF_SCRIPT_DIR}/skill-hook.sh\" \"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\" \"$HOME/.factory/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\"; do [ -f \"$c\" ] && { SH=\"$c\"; break; }; done; [ -n \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
# Planning with Files
@@ -350,16 +350,23 @@ if ($Mode -ne "") {
# (c) auto-attest (attestation default-on in v3 modes, security strand rec 1).
# attest-plan.ps1 intentionally refuses non-Windows hosts because its secure
# no-follow implementation uses Win32 handles. On Unix, use the POSIX
# attester instead. Bind slug mode to the plan we just created so an
# inherited PLAN_ID cannot redirect attestation to another plan.
# attester instead. Slug mode binds PWF_PLAN_ROOT and PLAN_ID to the plan
# we just created so an inherited pin or slug cannot redirect attestation
# to another project or plan (#261, #237). Root mode clears both instead:
# the attester only falls back to the legacy ./task_plan.md when no
# selector is set, and a bound pin would make it refuse the root plan.
$PlanFilePwf = Join-Path $PlanDirPwf "task_plan.md"
if (Test-Path -LiteralPath $PlanFilePwf) {
$HadPlanId = Test-Path Env:PLAN_ID
$PreviousPlanId = $env:PLAN_ID
$HadPlanRoot = Test-Path Env:PWF_PLAN_ROOT
$PreviousPlanRoot = $env:PWF_PLAN_ROOT
try {
if ($UsePlanDir) {
$env:PWF_PLAN_ROOT = (Get-Location).Path
$env:PLAN_ID = $PlanId
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
@@ -384,6 +391,11 @@ if ($Mode -ne "") {
} else {
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
if ($HadPlanRoot) {
$env:PWF_PLAN_ROOT = $PreviousPlanRoot
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
}
}
}
@@ -103,6 +103,7 @@ slugify() {
# Lowercase, non-alphanumerics → '-', collapse repeats, trim leading/trailing '-'
printf '%s' "$1" \
| tr '[:upper:]' '[:lower:]' \
| tr '\r\n' '--' \
| sed -e 's/[^a-z0-9]/-/g' -e 's/-\{2,\}/-/g' -e 's/^-//' -e 's/-$//' \
| cut -c1-40
}
@@ -202,12 +203,20 @@ apply_v3_mode() {
# (c) auto-attest the plan (attestation default-on in v3 modes, security
# strand rec 1). attest-plan.sh resolves the same way init-session just
# pinned things: in slug mode PLAN_ID points at this plan dir; in legacy
# mode it is empty and the script falls back to ./task_plan.md at root.
# Run from the project root (CWD here) so both resolutions land.
# pinned things. Slug mode binds both selectors to the plan that was
# just created, so an inherited PWF_PLAN_ROOT or PLAN_ID cannot
# redirect attestation to another project or plan (#261, #237). Root
# mode clears both instead: the attester only falls back to the legacy
# ./task_plan.md when no selector is set, and a bound pin would make it
# refuse the root plan. Run from the project root (CWD here) so both
# resolutions land.
_attest="${SCRIPT_DIR}/attest-plan.sh"
if [ -f "${_attest}" ] && [ -f "${_mode_plan}" ]; then
PLAN_ID="${PLAN_ID:-}" sh "${_attest}" >/dev/null 2>&1 || true
if [ "$SLUG_MODE" -eq 1 ]; then
PWF_PLAN_ROOT="$PWD" PLAN_ID="${PLAN_ID}" sh "${_attest}" >/dev/null 2>&1 || true
else
PWF_PLAN_ROOT="" PLAN_ID="" sh "${_attest}" >/dev/null 2>&1 || true
fi
fi
}
@@ -474,7 +474,7 @@ def _format_opencode_part(data: Dict[str, Any], session_id: str) -> Optional[Dic
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ or {}
input_ = input_ if isinstance(input_, dict) else {}
outcome = _opencode_state_annotation(state)
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
@@ -577,6 +577,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
@@ -350,16 +350,23 @@ if ($Mode -ne "") {
# (c) auto-attest (attestation default-on in v3 modes, security strand rec 1).
# attest-plan.ps1 intentionally refuses non-Windows hosts because its secure
# no-follow implementation uses Win32 handles. On Unix, use the POSIX
# attester instead. Bind slug mode to the plan we just created so an
# inherited PLAN_ID cannot redirect attestation to another plan.
# attester instead. Slug mode binds PWF_PLAN_ROOT and PLAN_ID to the plan
# we just created so an inherited pin or slug cannot redirect attestation
# to another project or plan (#261, #237). Root mode clears both instead:
# the attester only falls back to the legacy ./task_plan.md when no
# selector is set, and a bound pin would make it refuse the root plan.
$PlanFilePwf = Join-Path $PlanDirPwf "task_plan.md"
if (Test-Path -LiteralPath $PlanFilePwf) {
$HadPlanId = Test-Path Env:PLAN_ID
$PreviousPlanId = $env:PLAN_ID
$HadPlanRoot = Test-Path Env:PWF_PLAN_ROOT
$PreviousPlanRoot = $env:PWF_PLAN_ROOT
try {
if ($UsePlanDir) {
$env:PWF_PLAN_ROOT = (Get-Location).Path
$env:PLAN_ID = $PlanId
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
@@ -384,6 +391,11 @@ if ($Mode -ne "") {
} else {
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
if ($HadPlanRoot) {
$env:PWF_PLAN_ROOT = $PreviousPlanRoot
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
}
}
}
@@ -103,6 +103,7 @@ slugify() {
# Lowercase, non-alphanumerics → '-', collapse repeats, trim leading/trailing '-'
printf '%s' "$1" \
| tr '[:upper:]' '[:lower:]' \
| tr '\r\n' '--' \
| sed -e 's/[^a-z0-9]/-/g' -e 's/-\{2,\}/-/g' -e 's/^-//' -e 's/-$//' \
| cut -c1-40
}
@@ -202,12 +203,20 @@ apply_v3_mode() {
# (c) auto-attest the plan (attestation default-on in v3 modes, security
# strand rec 1). attest-plan.sh resolves the same way init-session just
# pinned things: in slug mode PLAN_ID points at this plan dir; in legacy
# mode it is empty and the script falls back to ./task_plan.md at root.
# Run from the project root (CWD here) so both resolutions land.
# pinned things. Slug mode binds both selectors to the plan that was
# just created, so an inherited PWF_PLAN_ROOT or PLAN_ID cannot
# redirect attestation to another project or plan (#261, #237). Root
# mode clears both instead: the attester only falls back to the legacy
# ./task_plan.md when no selector is set, and a bound pin would make it
# refuse the root plan. Run from the project root (CWD here) so both
# resolutions land.
_attest="${SCRIPT_DIR}/attest-plan.sh"
if [ -f "${_attest}" ] && [ -f "${_mode_plan}" ]; then
PLAN_ID="${PLAN_ID:-}" sh "${_attest}" >/dev/null 2>&1 || true
if [ "$SLUG_MODE" -eq 1 ]; then
PWF_PLAN_ROOT="$PWD" PLAN_ID="${PLAN_ID}" sh "${_attest}" >/dev/null 2>&1 || true
else
PWF_PLAN_ROOT="" PLAN_ID="" sh "${_attest}" >/dev/null 2>&1 || true
fi
fi
}
@@ -474,7 +474,7 @@ def _format_opencode_part(data: Dict[str, Any], session_id: str) -> Optional[Dic
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ or {}
input_ = input_ if isinstance(input_, dict) else {}
outcome = _opencode_state_annotation(state)
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
@@ -577,6 +577,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
@@ -1,12 +1,21 @@
from __future__ import annotations
import importlib
import json
import os
import shlex
from pathlib import Path
from typing import Any
from .hooks import post_tool_call, pre_llm_call, pre_verify
from .paths import normalize_cwd, plugin_skill_dir
from .hooks import (
WORKTREES_DIR_NAME,
launch_dir_has_planning_state,
launch_dir_notice,
post_tool_call,
pre_llm_call,
pre_verify,
)
from .paths import effective_project_root, normalize_cwd, plan_root_is_pinned, plugin_skill_dir
from .tools import (
planning_with_files_check_complete,
planning_with_files_init,
@@ -14,10 +23,25 @@ from .tools import (
)
SLASH_COMMANDS = ("pwf", "pwf-status", "plan-status")
BROKEN_PIN_MESSAGE = (
"planning-with-files: PWF_PLAN_ROOT is set but does not resolve to an absolute, "
"existing directory; nothing done."
)
def _command_cwd() -> Path:
"""Project directory for a slash command: the Hermes session cwd, else the process cwd."""
def _command_cwd() -> Path | None:
"""Project directory for a slash command.
The PWF_PLAN_ROOT pin wins, exactly as it does for the hooks, and a broken
pin returns None instead of a fallback (issue #272: on Hermes 0.21.3 the
session cwd can name the home directory, and a pinned operator must not
get a plan created or reported there). Without a pin: the Hermes session
cwd, else the process cwd. A command handler receives only its arguments,
no platform or session, so the CLI-only launch-directory rule of the hooks
cannot be applied here; the pin is the documented answer for commands.
"""
if plan_root_is_pinned():
return effective_project_root(normalize_cwd())
try:
from agent.runtime_cwd import resolve_agent_cwd
@@ -81,6 +105,8 @@ def pwf_command(raw_args: str = "") -> str:
name_parts.append(token)
index += 1
project_dir = _command_cwd()
if project_dir is None:
return BROKEN_PIN_MESSAGE
result = json.loads(
planning_with_files_init(
template=template, cwd=str(project_dir), name=" ".join(name_parts), mode=mode
@@ -97,14 +123,61 @@ def pwf_command(raw_args: str = "") -> str:
if result.get("attestation"):
lines.append(f" attested: sha256 {result['attestation'][:12]}...")
lines.append(" next: read task_plan.md, findings.md and progress.md, then fill in the goal and phases.")
if not plan_root_is_pinned():
# Issue #272: the plan just went where Hermes pointed while the launch
# directory already holds one; say so instead of leaving two plans apart.
hint = _launch_dir_hint(project_dir)
if hint:
lines.append(hint)
return "\n".join(lines)
def status_command(raw_args: str = "") -> str:
"""/pwf-status and /plan-status: compact planning state for the current project."""
project_dir = _command_cwd()
if project_dir is None:
return BROKEN_PIN_MESSAGE
payload = json.loads(planning_with_files_status(cwd=str(project_dir)))
return _format_status(payload)
report = _format_status(payload)
if not payload.get("exists") and not plan_root_is_pinned():
hint = _launch_dir_hint(project_dir)
if hint:
report = "\n".join((report, hint))
return report
def _session_cwd_is_pinned() -> bool:
"""True when Hermes pinned this context's cwd per session (``agent.runtime_cwd._SESSION_CWD``).
A pinned context runs in a multi-session backend whose process cwd is the
backend's start directory, not a launch directory, so the hint would
compare the wrong things. Prompt turns on the TUI and Desktop carry the
pin; their plugin command dispatch does not, so this is a best-effort
exemption. Read-only inspection; any failure counts as not pinned.
"""
try:
value = importlib.import_module("agent.runtime_cwd")._SESSION_CWD.get()
except Exception: # noqa: BLE001 - a host without the pin keeps the hint
return False
return isinstance(value, str) and bool(value.strip())
def _launch_dir_hint(project_dir: Path) -> str:
"""Issue #272 diagnostic for the slash commands: name the launch directory's plan.
Read-only and platform-blind (a command handler has no platform), so it is
a hint under the report, never a refusal. Worktree sessions and sessions
whose cwd Hermes pinned per session are exempt.
"""
if WORKTREES_DIR_NAME in project_dir.parts or _session_cwd_is_pinned():
return ""
try:
launch = normalize_cwd(os.getcwd())
if not launch.is_dir() or launch == project_dir or not launch_dir_has_planning_state(launch):
return ""
except (OSError, RuntimeError, ValueError):
return ""
return launch_dir_notice(project_dir, launch)
def _register_commands(ctx: Any) -> None:
+73 -58
View File
@@ -9,27 +9,22 @@ from .constants import PROGRESS_TAIL_LINES, READ_PREVIEW_LINES
from .context_frame import frame_bytes, read_regular_bytes, select_lines, verified_frame
from .hook_state import add_reminder, pop_reminders, state_key
from .paths import (
MULTIPLE_PLANS_NOTICE,
ambiguity_notice,
attestation_path_for,
effective_project_root,
multiple_plans_require_selector,
normalize_cwd,
plan_id_for,
plan_root_is_pinned,
resolve_plan,
resolve_plan_dir,
slug_is_valid,
)
from .planning_files import evaluate_gate, normalize_wall_clock
ATTACH_LEGACY = "legacy" # no .planning/sessions directory: single-session setup
ATTACH_ATTACHED = "attached" # sessions directory armed and this session holds a sentinel
ATTACH_DETACHED = "detached" # sessions directory armed, no sentinel (or unsafe directory)
SESSION_PLAN_BINDING_NOTICE = (
"[planning-with-files] Multiple plans are available while session isolation "
"is armed. Set PLAN_ID=<slug> for this session; nothing injected."
)
def _runtime_project_dir(kwargs: dict[str, Any]) -> Path | None:
"""Resolve the active Hermes project, never a cached import-time cwd.
@@ -59,6 +54,66 @@ def _runtime_project_dir(kwargs: dict[str, Any]) -> Path | None:
return effective_project_root(project)
WORKTREES_DIR_NAME = ".worktrees" # hermes -w and /worktree new place trees at <repo>/.worktrees/<name>
def launch_dir_has_planning_state(launch: Path) -> bool:
"""True when the process launch directory holds a plan, or several plans.
A plan with a nested-root conflict still counts (``explicit=True`` skips
only that check), because the question here is whether the directory the
session was started in carries planning state at all.
"""
return (
resolve_plan(launch, explicit=True)[0] is not None
or multiple_plans_require_selector(launch)
)
def launch_dir_notice(project_dir: Path, launch: Path) -> str:
"""The once-per-turn line for issue #272; the resolved root and the launch directory differ."""
return (
f"[planning-with-files] Hermes resolved {project_dir} as the working directory, "
f"but the launch directory {launch} holds a plan. Nothing injected. "
f"Pin the thread with PWF_PLAN_ROOT={launch}."
)
def _launch_dir_notice(project_dir: Path, kwargs: dict[str, Any]) -> str | None:
"""Issue #272: the resolved root holds no plan while the launch directory does.
Hermes 0.21.3 rewrites the process-global TERMINAL_CWD during the first
turn of a CLI session (``agent/relay_runtime.py`` imports ``gateway/run.py``
lazily; its import-time bridge applies the ``Path.home()`` fallback), so
``resolve_agent_cwd`` names the home directory while ``os.getcwd()`` still
names the directory the session was started in (upstream hermes-agent
#86411 and #95577). The rewrite runs before the first hook, so the adapter
cannot recover the root on its own and never switches to the launch
directory: it says why nothing was injected and names the pin.
Silent by design: platforms other than the CLI (their process cwd is not a
launch directory), Hermes worktree sessions (``hermes -w`` points
TERMINAL_CWD at ``<repo>/.worktrees/<name>`` without a chdir, which is the
intended split), a launch directory without planning state, and a launch
directory whose session isolation refuses this session anyway.
"""
if str(kwargs.get("platform", "")).strip().lower() != "cli":
return None
if WORKTREES_DIR_NAME in project_dir.parts:
return None
try:
launch = normalize_cwd(os.getcwd())
if not launch.is_dir() or launch == project_dir:
return None
if _session_attachment(launch, _session_id(kwargs)) == ATTACH_DETACHED:
return None
if not launch_dir_has_planning_state(launch):
return None
except (OSError, RuntimeError, ValueError):
return None
return launch_dir_notice(project_dir, launch)
def _session_attachment(project_dir: Path, session_id: str) -> str:
"""Opt-in isolation state once a project creates its sessions directory."""
sessions_dir = project_dir / ".planning" / "sessions"
@@ -84,50 +139,6 @@ def _session_attachment(project_dir: Path, session_id: str) -> str:
return ATTACH_DETACHED
def _is_live_plan_file(path: Path) -> bool:
try:
info = path.lstat()
except OSError:
return False
attrs = getattr(info, "st_file_attributes", 0)
return (
stat.S_ISREG(info.st_mode)
and not stat.S_ISLNK(info.st_mode)
and not attrs & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
)
def _session_plan_requires_binding(project_dir: Path) -> bool:
"""True when an attached session must select a same-root plan by PLAN_ID."""
if os.environ.get("PLAN_ID", "").strip():
return False
candidates = 1 if _is_live_plan_file(project_dir / "task_plan.md") else 0
planning_dir = project_dir / ".planning"
try:
children = planning_dir.iterdir()
for child in children:
if not slug_is_valid(child.name):
continue
try:
info = child.lstat()
except OSError:
continue
attrs = getattr(info, "st_file_attributes", 0)
if (
not stat.S_ISDIR(info.st_mode)
or stat.S_ISLNK(info.st_mode)
or attrs & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
):
continue
if _is_live_plan_file(child / "task_plan.md"):
candidates += 1
if candidates > 1:
return True
except (OSError, RuntimeError):
return True
return False
def _resolve_plan(project_dir: Path, *, explicit: bool = False) -> tuple[Path | None, list[str]]:
"""Active plan directory whose task_plan.md is a regular file, plus nested conflicts."""
plan_dir, conflicts = resolve_plan(project_dir, explicit=explicit)
@@ -148,7 +159,7 @@ def _session_id(kwargs: dict[str, Any]) -> str:
def _locate(
kwargs: dict[str, Any],
) -> tuple[Path | None, Path | None, list[str], str, bool]:
"""Shared front half: project, plan, conflicts, session id, binding refusal.
"""Shared front half: project, plan, conflicts, session id, selector refusal.
PWF_PLAN_ROOT selects the effective project root. PLAN_ID selects a plan
within it. A session attachment is admission only and never skips either
@@ -161,7 +172,7 @@ def _locate(
attachment = _session_attachment(project_dir, session_id)
if attachment == ATTACH_DETACHED:
return project_dir, None, [], session_id, False
if attachment == ATTACH_ATTACHED and _session_plan_requires_binding(project_dir):
if multiple_plans_require_selector(project_dir):
return project_dir, None, [], session_id, True
explicit = plan_root_is_pinned()
plan_dir, conflicts = _resolve_plan(project_dir, explicit=explicit)
@@ -213,16 +224,20 @@ def build_user_prompt_context(project_dir: Path, plan_dir: Path | None = None) -
def pre_llm_call(**kwargs: Any) -> dict[str, str] | None:
project_dir, plan_dir, conflicts, session_id, binding_required = _locate(kwargs)
project_dir, plan_dir, conflicts, session_id, selector_required = _locate(kwargs)
if project_dir is None:
return None
if plan_dir is None:
# The refusal holds in every hook; the notice is turn-scoped, so only
# this once-per-turn hook says why (same split as inject-plan.sh).
if binding_required:
return {"context": SESSION_PLAN_BINDING_NOTICE}
if selector_required:
return {"context": MULTIPLE_PLANS_NOTICE}
if conflicts:
return {"context": ambiguity_notice(conflicts)}
if not plan_root_is_pinned():
notice = _launch_dir_notice(project_dir, kwargs)
if notice:
return {"context": notice}
return None
user_message = str(kwargs.get("user_message", ""))
reminder_messages = pop_reminders(project_dir, session_id)
@@ -252,7 +267,7 @@ def post_tool_call(**kwargs: Any) -> None:
return None
else:
return None
project_dir, plan_dir, _conflicts, session_id, _binding_required = _locate(kwargs)
project_dir, plan_dir, _conflicts, session_id, _selector_required = _locate(kwargs)
if project_dir is None or plan_dir is None:
return None
message = "[planning-with-files] Update progress.md with what you just did. If a phase is now complete, update task_plan.md status."
@@ -269,7 +284,7 @@ def pre_verify(**kwargs: Any) -> dict[str, str] | None:
plan without the ``gate`` token stays advisory and this hook returns None,
so legacy and autonomous plans never hold a turn open.
"""
project_dir, plan_dir, _conflicts, _session_id, _binding_required = _locate(kwargs)
project_dir, plan_dir, _conflicts, _session_id, _selector_required = _locate(kwargs)
if project_dir is None or plan_dir is None:
return None
try:
+64 -7
View File
@@ -12,6 +12,11 @@ SKILL_DIR_NAME = "planning-with-files"
# underscore. Rejects traversal, separators, and whitespace by construction.
_SLUG_RE = re.compile(r"^[A-Za-z0-9_][A-Za-z0-9._-]*$")
_REPARSE_ATTR = getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0x400)
MULTIPLE_PLANS_NOTICE = (
"[planning-with-files] Multiple plans are available. "
"Set PLAN_ID=<slug> for this session; nothing injected."
)
MULTIPLE_PLANS_MESSAGE = "Multiple plans are available. Set PLAN_ID=<slug> to select one."
def has_skill_assets(candidate: Path) -> bool:
@@ -136,6 +141,16 @@ def _is_regular_file(path: Path) -> bool:
return stat.S_ISREG(info.st_mode)
def _is_real_dir(path: Path) -> bool:
try:
info = path.lstat()
except OSError:
return False
if stat.S_ISLNK(info.st_mode) or getattr(info, "st_file_attributes", 0) & _REPARSE_ATTR:
return False
return stat.S_ISDIR(info.st_mode)
def slug_is_valid(slug: str) -> bool:
return bool(slug) and _SLUG_RE.match(slug) is not None
@@ -197,6 +212,39 @@ def _read_active_pointer(planning_root: Path) -> str:
return lines[0] if len(lines) == 1 else ""
def count_selectable_plans(project_dir: Path) -> int:
"""Count plans exactly as inject-plan.sh does before guessing a selection.
A legacy root plan counts only after session isolation is armed. Every
contained valid slug directory with a regular task_plan.md counts. The
caller only needs to distinguish zero/one from "more than one", so stop at
two.
"""
planning_root = project_dir / ".planning"
count = 0
if _is_real_dir(planning_root / "sessions") and _is_regular_file(project_dir / "task_plan.md"):
count = 1
try:
entries = list(planning_root.iterdir())
except OSError:
return count
for entry in entries:
if not slug_is_valid(entry.name):
continue
if _slug_plan_dir(planning_root, entry.name) is None:
continue
count += 1
if count > 1:
break
return count
def multiple_plans_require_selector(project_dir: Path, *, plan_id: str | None = None) -> bool:
"""True when shared pointer/mtime guesses cannot identify this session's plan."""
requested = plan_id if plan_id is not None else os.environ.get("PLAN_ID", "").strip()
return not requested and count_selectable_plans(project_dir) > 1
def nested_live_plans(root: Path) -> list[str]:
"""Direct children whose own .planning holds a live plan (<slug>/task_plan.md).
@@ -236,17 +284,20 @@ def resolve_plan(
) -> tuple[Path | None, list[str]]:
"""Resolve the active plan directory; return it with any nested conflicts.
Precedence mirrors resolve-plan-dir.sh: an explicit plan id (the PLAN_ID
environment variable when not passed), then .planning/.active_plan, then
the newest .planning/<slug>/task_plan.md by modification time, then the
legacy root task_plan.md. Slugs are validated and the chosen directory
must stay inside .planning (no symlink or junction escape).
Precedence mirrors resolve-plan-dir.sh: a non-empty explicit plan id (the
PLAN_ID environment variable when not passed) is binding. Without one,
more than one selectable same-root plan is refused; otherwise resolution
continues through .planning/.active_plan, the newest
.planning/<slug>/task_plan.md by modification time, then the legacy root
task_plan.md. Slugs are validated and the chosen directory must stay
inside .planning (no symlink or junction escape).
A cwd guess (pointer, newest, or legacy root) is refused when a direct
child of the root carries its own live plan (issue #212): the result is
``(None, [child names])`` so the caller can say why. ``explicit`` marks a
selection that skips that check, exactly as inject-plan.sh does for a
``PWF_PLAN_ROOT`` pin or a ``PLAN_ID`` slug.
project-root selection that skips only that nested-root check, exactly as
inject-plan.sh does for a valid ``PWF_PLAN_ROOT`` pin. It never selects one
of several same-root plans; that still requires ``PLAN_ID``.
"""
planning_root = project_dir / ".planning"
requested = plan_id if plan_id is not None else os.environ.get("PLAN_ID", "").strip()
@@ -271,6 +322,12 @@ def resolve_plan(
return explicit_dir, []
return None, []
# A shared .active_plan pointer or directory mtime cannot identify which
# same-root task this session owns. PWF_PLAN_ROOT selects the project, not
# one of its plans, so even an explicit root pin does not lift this refusal.
if count_selectable_plans(project_dir) > 1:
return None, []
chosen: Path | None = None
if planning_root.is_dir() and not _is_link_or_reparse(planning_root):
pointed = _read_active_pointer(planning_root)
@@ -9,7 +9,9 @@ from typing import Any
from .constants import PLANNING_FILES, PLAN_PREVIEW_LINES, PROGRESS_TAIL_LINES
from .paths import (
MULTIPLE_PLANS_MESSAGE,
attestation_path_for,
multiple_plans_require_selector,
plan_id_for,
resolve_plan_dir,
resolve_skill_dir,
@@ -425,9 +427,14 @@ def evaluate_gate(project_dir: Path, plan_dir: Path) -> str | None:
def summarize_status(project_dir: Path) -> dict[str, Any]:
plan_dir = resolve_plan_dir(project_dir)
if plan_dir is None:
message = (
MULTIPLE_PLANS_MESSAGE
if multiple_plans_require_selector(project_dir)
else "No planning files found. Run planning_with_files_init first."
)
return {
"exists": False,
"message": "No planning files found. Run planning_with_files_init first.",
"message": message,
"project_dir": str(project_dir),
"files": {
"task_plan.md": False,
@@ -1,5 +1,5 @@
name: planning-with-files
version: 0.2.1
version: 0.2.2
description: Hermes adapter for persistent project planning and selected context injection. Resolves root and .planning/<slug> plans, injects the attested plan each turn, reminds after writes, and registers /pwf and /pwf-status. Optional gated mode can request continuation only through the Hermes pre_verify hook, bounded by agent.max_verify_nudges; legacy plans stay advisory. Explicit catchup modes read same-project local session records for aggregate counts or bounded replay. No network upload path.
author: planning-with-files contributors
provides_tools:
+13 -2
View File
@@ -3,7 +3,14 @@ import shutil
import subprocess
from pathlib import Path
from .paths import normalize_cwd, plan_id_for, resolve_plan_dir, resolve_skill_dir
from .paths import (
MULTIPLE_PLANS_MESSAGE,
multiple_plans_require_selector,
normalize_cwd,
plan_id_for,
resolve_plan_dir,
resolve_skill_dir,
)
from .planning_files import init_plan, phase_counts, summarize_status
@@ -49,7 +56,11 @@ def planning_with_files_check_complete(cwd: str = "") -> str:
return json.dumps(
{
"ok": False,
"error": "No task_plan.md found. Run planning_with_files_init first.",
"error": (
MULTIPLE_PLANS_MESSAGE
if multiple_plans_require_selector(project_dir)
else "No task_plan.md found. Run planning_with_files_init first."
),
"skill_root": str(skill_root),
"complete": False,
},
+1 -1
View File
@@ -2,7 +2,7 @@
name: planning-with-files
description: "Persistent file-based planning for multi-step AI-agent work. Keeps task_plan.md, findings.md, and progress.md on disk; lifecycle hooks inject selected project planning context. Automatic recovery reads project planning files only. Explicit session-catchup.py --metadata reads same-project local agent session records and emits aggregate counts only; --replay may emit bounded nonce-framed excerpts. Optional gated mode can request continuation only when the host supports it and never runs commands declared in Markdown. The skill has no network upload path. Use for research or work needing 5+ tool calls."
metadata:
version: "3.20.0"
version: "3.20.2"
hermes:
tags: [planning, long-running-tasks, context-engineering, workflow]
---
@@ -36,7 +36,7 @@ hooks:
- type: command
command: "SH=\"\"; for c in \"${PWF_SCRIPT_DIR}/skill-hook.sh\" \"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\" \"$HOME/.mastracode/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\"; do [ -f \"$c\" ] && { SH=\"$c\"; break; }; done; [ -n \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
@@ -36,7 +36,7 @@ hooks:
- type: command
command: "SH=\"\"; for c in \"${PWF_SCRIPT_DIR}/skill-hook.sh\" \"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\" \"$HOME/.config/opencode/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.opencode/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\"; do [ -f \"$c\" ] && { SH=\"$c\"; break; }; done; [ -n \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
@@ -403,7 +403,8 @@ def _format_opencode_part(data: Dict[str, Any], session_id: str) -> Optional[Dic
if ptype == 'tool':
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ if isinstance(input_, dict) else {}
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
return {'session': short, 'summary': f"Tool {tool}: {fp}"}
@@ -505,6 +506,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "planning-with-files",
"version": "3.20.0",
"version": "3.20.2",
"description": "Persistent project planning with selected context injection. Automatic recovery uses project files only; explicit catchup modes read same-project local session records for aggregate counts or bounded replay. The host-aware gate never runs Markdown-declared commands. No network upload path. Ships the skill plus a Pi Coding Agent extension.",
"keywords": [
"pi-package",
@@ -350,16 +350,23 @@ if ($Mode -ne "") {
# (c) auto-attest (attestation default-on in v3 modes, security strand rec 1).
# attest-plan.ps1 intentionally refuses non-Windows hosts because its secure
# no-follow implementation uses Win32 handles. On Unix, use the POSIX
# attester instead. Bind slug mode to the plan we just created so an
# inherited PLAN_ID cannot redirect attestation to another plan.
# attester instead. Slug mode binds PWF_PLAN_ROOT and PLAN_ID to the plan
# we just created so an inherited pin or slug cannot redirect attestation
# to another project or plan (#261, #237). Root mode clears both instead:
# the attester only falls back to the legacy ./task_plan.md when no
# selector is set, and a bound pin would make it refuse the root plan.
$PlanFilePwf = Join-Path $PlanDirPwf "task_plan.md"
if (Test-Path -LiteralPath $PlanFilePwf) {
$HadPlanId = Test-Path Env:PLAN_ID
$PreviousPlanId = $env:PLAN_ID
$HadPlanRoot = Test-Path Env:PWF_PLAN_ROOT
$PreviousPlanRoot = $env:PWF_PLAN_ROOT
try {
if ($UsePlanDir) {
$env:PWF_PLAN_ROOT = (Get-Location).Path
$env:PLAN_ID = $PlanId
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
@@ -384,6 +391,11 @@ if ($Mode -ne "") {
} else {
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
if ($HadPlanRoot) {
$env:PWF_PLAN_ROOT = $PreviousPlanRoot
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
}
}
}
@@ -103,6 +103,7 @@ slugify() {
# Lowercase, non-alphanumerics → '-', collapse repeats, trim leading/trailing '-'
printf '%s' "$1" \
| tr '[:upper:]' '[:lower:]' \
| tr '\r\n' '--' \
| sed -e 's/[^a-z0-9]/-/g' -e 's/-\{2,\}/-/g' -e 's/^-//' -e 's/-$//' \
| cut -c1-40
}
@@ -202,12 +203,20 @@ apply_v3_mode() {
# (c) auto-attest the plan (attestation default-on in v3 modes, security
# strand rec 1). attest-plan.sh resolves the same way init-session just
# pinned things: in slug mode PLAN_ID points at this plan dir; in legacy
# mode it is empty and the script falls back to ./task_plan.md at root.
# Run from the project root (CWD here) so both resolutions land.
# pinned things. Slug mode binds both selectors to the plan that was
# just created, so an inherited PWF_PLAN_ROOT or PLAN_ID cannot
# redirect attestation to another project or plan (#261, #237). Root
# mode clears both instead: the attester only falls back to the legacy
# ./task_plan.md when no selector is set, and a bound pin would make it
# refuse the root plan. Run from the project root (CWD here) so both
# resolutions land.
_attest="${SCRIPT_DIR}/attest-plan.sh"
if [ -f "${_attest}" ] && [ -f "${_mode_plan}" ]; then
PLAN_ID="${PLAN_ID:-}" sh "${_attest}" >/dev/null 2>&1 || true
if [ "$SLUG_MODE" -eq 1 ]; then
PWF_PLAN_ROOT="$PWD" PLAN_ID="${PLAN_ID}" sh "${_attest}" >/dev/null 2>&1 || true
else
PWF_PLAN_ROOT="" PLAN_ID="" sh "${_attest}" >/dev/null 2>&1 || true
fi
fi
}
@@ -474,7 +474,7 @@ def _format_opencode_part(data: Dict[str, Any], session_id: str) -> Optional[Dic
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ or {}
input_ = input_ if isinstance(input_, dict) else {}
outcome = _opencode_state_annotation(state)
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
@@ -577,6 +577,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
+27
View File
@@ -4,6 +4,33 @@ All notable changes to this project will be documented in this file.
## [Unreleased]
## [3.20.2] - 2026-09-19
### Fixed
- Hermes plugin: on Hermes 0.21.3 the host rewrites the process-global `TERMINAL_CWD` to the home directory during the first turn of a CLI session (`agent/relay_runtime.py` imports `gateway/run.py` lazily, and that module's import-time bridge applies the `Path.home()` fallback for an empty or placeholder `terminal.cwd`), so `resolve_agent_cwd()` named the home directory, the hooks found no plan there and injected nothing, with no signal that the plan in the launch directory had been skipped. The rewrite runs before the first plugin hook, so the plugin cannot recover the root on its own and does not guess: when the resolved directory holds no plan and the launch directory of a CLI session does, `pre_llm_call` now injects one line naming both directories and the `PWF_PLAN_ROOT` pin instead of returning nothing, `/pwf-status` prints the same line under `No planning files found.`, `/pwf` appends it when the plan it created went somewhere other than a launch directory that already holds one, and `/pwf` and `/pwf-status` honor `PWF_PLAN_ROOT` like the hooks and report a pin that does not resolve instead of creating or reading a plan in the directory Hermes named. The line stays silent outside the CLI, in `hermes -w` worktree sessions (`TERMINAL_CWD` at `<repo>/.worktrees/<name>` without a chdir is the intended split), for a launch directory without planning state, and for a launch directory whose session isolation refuses the session. Upstream: NousResearch/hermes-agent#86411 and #95577 (#272).
### Changed
- `docs/hermes.md` documents the Hermes 0.21.3 working-directory rewrite, what was reproduced with the 0.21.0 source, the pin for project-scoped CLI sessions, and the shell-hook route as the unaffected alternative.
### Thanks
- @ericshunhinglee-cloud, for the report with the setter stack trace, the on-the-wire token evidence and the upstream cross-references in #272.
## [3.20.1] - 2026-09-18
### Fixed
- `init-session.sh`: a plan name containing a newline created `.planning/<date>-line-one<newline>line-two/`, then the selector rejected the id and init exited 1 with the directory left behind. `slugify` now maps CR and LF to `-` before the `sed` step, so the slug is a single line as in the PowerShell twin (#257).
- Both initializers bound `PLAN_ID` for the attestation call but not `PWF_PLAN_ROOT`, so a pin inherited from another project redirected or silently blocked the attestation of the plan that was just created. `init-session.sh` and `init-session.ps1` now bind `PWF_PLAN_ROOT` and `PLAN_ID` to the plan just created around the attest call in slug mode and restore the inherited values afterwards. Root mode clears both selectors for that call instead, because the attester only falls back to the legacy `./task_plan.md` when no selector is set; this also stops an inherited `PLAN_ID` from redirecting the shell attester to a sibling slug plan, as the PowerShell twin already did. Root-mode attestation for `--autonomous` and `--gated` now has regression tests on both routes (#261).
- `session-catchup.py`, OpenCode adapter: a part row whose `state` or `state.input` is not an object raised `AttributeError`, and a row whose `data` column is not valid JSON made SQLite raise `malformed JSON` for the whole session. Malformed shapes are treated as empty input and non-JSON rows are filtered with `json_valid(data)`; healthy rows in the same session are still reported. Applies to every copy that carries the adapter (#258).
- Hermes plugin: with two or more named plans under `.planning/` and no `PLAN_ID`, the plugin resolved the shared pointer or the newest plan by modification time, so two Hermes sessions on two plans in one project could be injected with each other's plan. The plugin now applies the v3.17.1 rule: `pre_llm_call` emits the one-line `Multiple plans are available` notice once per turn and injects nothing, `post_tool_call` and `pre_verify` stay quiet, and `/pwf-status`, `planning_with_files_status` and `planning_with_files_check_complete` report the missing selector. One named plan, a root plan, a `PLAN_ID` pin and the nested-root safeguards behave as before; `PWF_PLAN_ROOT` pins the project root and does not select one of several same-root plans (#264).
### Changed
- `docs/hermes.md` describes the Hermes selection rule as shipped.
### Thanks
- @ShaunLinTW, for the malformed-row guards in the OpenCode catchup adapter and their regression tests in #263.
- @TayfurYldz, for the single-line shell slug in #266 and the project-bound attestation with shell and PowerShell regressions in #265.
- @kuei51307-hub, for porting the several-plans rule into the Hermes plugin in #267.
## [3.20.0] - 2026-09-17
### Added
+2 -2
View File
@@ -7,8 +7,8 @@ authors:
- family-names: Adi
given-names: Ahmad Othman Ammar
alias: OthmanAdi
version: "3.20.0"
date-released: "2026-09-17"
version: "3.20.2"
date-released: "2026-09-19"
license: MIT
url: "https://github.com/OthmanAdi/planning-with-files"
repository-code: "https://github.com/OthmanAdi/planning-with-files"
+13 -4
View File
@@ -106,16 +106,25 @@ These amazing people have contributed code, documentation, or significant improv
### Other Contributors
- **[Shaun Lin](https://github.com/ShaunLinTW)**, [PR #245](https://github.com/OthmanAdi/planning-with-files/pull/245), [PR #247](https://github.com/OthmanAdi/planning-with-files/pull/247)
- **[@ericshunhinglee-cloud](https://github.com/ericshunhinglee-cloud)**, [Issue #272](https://github.com/OthmanAdi/planning-with-files/issues/272)
- Reported and traced the Hermes 0.21.3 first-turn `TERMINAL_CWD` rewrite that made the Hermes plugin resolve the home directory as the project root, with a setter stack trace, on-the-wire token evidence and the upstream cross-references.
- **[Shaun Lin](https://github.com/ShaunLinTW)**, [PR #245](https://github.com/OthmanAdi/planning-with-files/pull/245), [PR #247](https://github.com/OthmanAdi/planning-with-files/pull/247), [PR #263](https://github.com/OthmanAdi/planning-with-files/pull/263)
- Isolated Python calls in the Codex, Gemini, and GitHub Copilot shell adapters and added regression coverage for project-local import shadowing.
- Added named-plan slug mode to the PowerShell initializer with root-mode policy inheritance, host-aware attestation, and Windows PowerShell regression coverage.
- Made the OpenCode session catchup adapter skip malformed part rows instead of raising, with regression coverage for the string-state and invalid-JSON shapes.
- **[@kuei51307-hub](https://github.com/kuei51307-hub)**, [PR #243](https://github.com/OthmanAdi/planning-with-files/pull/243), [PR #244](https://github.com/OthmanAdi/planning-with-files/pull/244), [PR #248](https://github.com/OthmanAdi/planning-with-files/pull/248), [PR #249](https://github.com/OthmanAdi/planning-with-files/pull/249), [PR #251](https://github.com/OthmanAdi/planning-with-files/pull/251)
- **[@TayfurYldz](https://github.com/TayfurYldz)**, [PR #265](https://github.com/OthmanAdi/planning-with-files/pull/265), [PR #266](https://github.com/OthmanAdi/planning-with-files/pull/266)
- Bound `PWF_PLAN_ROOT` to the current project around the attestation call in both initializers so an inherited pin cannot redirect attestation, with shell and PowerShell regressions.
- Made the shell slugifier single-line so a plan name with an embedded newline no longer creates an unusable plan directory.
- **[@kuei51307-hub](https://github.com/kuei51307-hub)**, [PR #243](https://github.com/OthmanAdi/planning-with-files/pull/243), [PR #244](https://github.com/OthmanAdi/planning-with-files/pull/244), [PR #248](https://github.com/OthmanAdi/planning-with-files/pull/248), [PR #249](https://github.com/OthmanAdi/planning-with-files/pull/249), [PR #251](https://github.com/OthmanAdi/planning-with-files/pull/251), [PR #267](https://github.com/OthmanAdi/planning-with-files/pull/267)
- Fixed active-plan display and listing for UTF-8 BOM-prefixed pointers, with regression coverage across the synchronized shell helpers.
- Made IDE sync verification report missing canonical sources, with subprocess tests for read-only verification and unchanged sync behavior.
- Bounded session catchup to exact planning filenames across the canonical scanners and the Hermes, MastraCode, and OpenCode adapters, with lookalike regression coverage.
- Replaced the shell initializer's active-pointer write with the selector's contained atomic update and added hardlink, symlink, and junction regressions.
- Routed Cursor's native PowerShell hooks through the shared plan resolver so named plans are injected on Windows, and made the resolver's `PWF_PLAN_ROOT` check run on Windows PowerShell 5.1.
- Ported the several-plans rule into the Hermes plugin so two or more named plans without `PLAN_ID` get the selector notice instead of a pointer or timestamp guess.
- **[@Dphoshoba](https://github.com/Dphoshoba)**, [PR #242](https://github.com/OthmanAdi/planning-with-files/pull/242)
- Proposed and implemented named-plan listing with phase counts and a shared active-pointer marker.
@@ -440,6 +449,6 @@ If you've contributed and don't see your name here, please open an issue! We wan
---
**Total Contributors:** 63+ and growing!
**Total Contributors:** 65+ and growing!
*Last updated: 2026-09-17*
*Last updated: 2026-09-19*
+2
View File
@@ -347,6 +347,8 @@ One hook fire measures 289ms wall-clock since the v3.6.0 optimization, down from
| Version | Highlights |
|---------|------------|
| **v3.20.2** | Hermes plugin: Hermes 0.21.3 re-homes `TERMINAL_CWD` to the home directory on the first CLI turn, so the plan in the launch directory was skipped silently. The first turn now says why nothing was injected and names the `PWF_PLAN_ROOT` pin, `/pwf-status` and `/pwf` print the same diagnostic, and the slash commands honor the pin (#272, reported by @ericshunhinglee-cloud). |
| **v3.20.1** | Fixes four maintainer-filed issues from the v3.19.0 and v3.20.0 cycles: newline-safe shell slugs (#257, PR #266 by @TayfurYldz), attestation bound to the current project when `PWF_PLAN_ROOT` is inherited (#261, PR #265 by @TayfurYldz), malformed OpenCode part rows skipped by session catchup (#258, PR #263 by @ShaunLinTW), and the several-plans rule in the Hermes plugin (#264, PR #267 by @kuei51307-hub). |
| **v3.20.0** | **DeepSeek Harness becomes a first-class host** (closes #252, reported by @loarland): the native Cordis plugin `dsh-planning-with-files` injects the plan on every prompt and after compaction, reminds after writes, holds the turn boundary in gated mode, and registers `/pwf`, `/pwf-status` and the `pwf_*` tools; `dsh plugin --profile web add dsh-planning-with-files`. Cursor's native PowerShell hooks resolve named plans (PR #251 by @kuei51307-hub, item 9 of #250); the PowerShell resolver and attester run on Windows PowerShell 5.1 with a pin and in bracketed project paths; the OpenCode and DSH plugins require `PLAN_ID` for several named plans (the #240 rule); the README is shorter (one 3-file pattern block, a first-class hosts table, one commands collapsible). |
| **v3.19.0** | Adds PowerShell named-plan slug mode (#247), anchors session catchup only on exact planning filenames across every shipped copy (#248), and replaces active-plan pointers through the selectors with planning-root containment in both initializers (#249). |
| **v3.18.3** | Silences completed-plan notices in shared Stop gates and Codex while preserving explicit reports and gate safeguards. |
+18 -4
View File
@@ -1,6 +1,6 @@
# Hermes Agent Setup
planning-with-files treats [Hermes Agent](https://github.com/NousResearch/hermes-agent) by Nous Research as a first-class host: the Hermes CLI, the Hermes TUI and gateway sessions, and the Hermes Desktop app all run the same adapter. Everything on this page was verified against the Hermes v0.19.1 source and a live Hermes install on Windows; the POSIX paths follow Hermes' own defaults.
planning-with-files treats [Hermes Agent](https://github.com/NousResearch/hermes-agent) by Nous Research as a first-class host: the Hermes CLI, the Hermes TUI and gateway sessions, and the Hermes Desktop app all run the same adapter. Everything on this page was verified against the Hermes v0.19.1 source and a live Hermes install on Windows; the Hermes 0.21.3 working-directory rewrite described below was reproduced with the 0.21.0 source. The POSIX paths follow Hermes' own defaults.
The adapter has two parts:
@@ -13,11 +13,11 @@ The adapter has two parts:
|---|---|
| Tools | `planning_with_files_init` (root plan, or `.planning/YYYY-MM-DD-<slug>/` when given a name; `mode: autonomous` or `gated` writes the v3 markers and attests the plan), `planning_with_files_status`, `planning_with_files_check_complete` |
| Slash commands | `/pwf [--autonomous\|--gated] [--template analytics] [plan name]`, `/pwf-status`, `/plan-status` |
| `pre_llm_call` | Injects the active plan at the start of every turn: the framed head of `task_plan.md`, the normalized tail of `progress.md`, and a pointer to `findings.md`. Resolves `PLAN_ID`, then `.planning/.active_plan`, then the newest `.planning/<slug>/task_plan.md`, then the legacy root file, with the same slug validation and containment rules as `resolve-plan-dir.sh` and the same nested-root ambiguity rule as `inject-plan.sh` (a live plan in a direct child project refuses a cwd guess; a `PWF_PLAN_ROOT` pin, an attached session or `PLAN_ID` skips that check; the refusal is announced once per turn) |
| `pre_llm_call` | Injects the active plan at the start of every turn: the framed head of `task_plan.md`, the normalized tail of `progress.md`, and a pointer to `findings.md`. A non-empty `PLAN_ID` binds one named plan. Without it, one selectable plan may resolve through `.planning/.active_plan`, the newest named plan, or the legacy root; two or more selectable same-root plans are ambiguous and get the one-line `Multiple plans are available` notice instead of plan content. A shared pointer or timestamp never binds a Hermes session. The same slug validation, containment checks and nested-root ambiguity rule as `inject-plan.sh` apply: `PWF_PLAN_ROOT` pins only the project root, an attached session only admits that session, and neither chooses one of several same-root plans |
| `post_tool_call` | After `write_file` and `patch`, queues a reminder to update `progress.md` and the phase status; delivered with the next injection |
| `pre_verify` | The completion gate in gated mode: while an `in_progress` phase remains, the plugin asks Hermes to keep going instead of finishing the turn. Legacy and autonomous plans are never held |
| Attestation | Autonomous and gated plans inject only when `.attestation` (slug) or `.plan-attestation` (root) matches the SHA-256 of `task_plan.md`; a tampered or unattested v3 plan is refused with a `context blocked` line |
| Opt-outs and pins | `PLANNING_DISABLED=1` silences every hook for the invocation; `PWF_PLAN_ROOT=<absolute path>` pins the project root and fails closed when the pin does not resolve; `PWF_GATE_CAP` caps consecutive gate blocks (default 20) |
| Opt-outs and pins | `PLANNING_DISABLED=1` silences every hook for the invocation; `PWF_PLAN_ROOT=<absolute path>` pins the project root and fails closed when the pin does not resolve, but does not replace `PLAN_ID` when that root has several selectable plans; `PWF_GATE_CAP` caps consecutive gate blocks (default 20) |
The plugin is self-contained: plan resolution, injection, attestation checks, the gate and `/pwf` initialization run in Python, so nothing depends on `sh`, `bash` or PowerShell being present. The completion check tool prefers the bundled `check-complete.sh` when `sh` exists and evaluates the plan in Python otherwise.
@@ -76,6 +76,20 @@ Hermes Desktop runs the same backend (`hermes serve`) and therefore the same plu
- The hub does not deliver the PowerShell scripts; nothing in the adapter needs them.
- Short-name paths (`C:\Users\OASRVA~1\...`) in `HERMES_HOME` make `hermes skills install` fail its subpath check. Use the long form.
## Hermes 0.21.3: the working directory can move to the home directory on the first turn
Reported on Hermes 0.21.3 ([#272](https://github.com/OthmanAdi/planning-with-files/issues/272)): during the first turn of a CLI session, `agent/relay_runtime.py` imports `gateway/run.py` lazily, and that module's import-time bridge sets the process-global `TERMINAL_CWD` to the home directory when the variable is empty or a placeholder (`terminal.cwd: "."`). `agent.runtime_cwd.resolve_agent_cwd()`, the documented single source of truth the plugin reads, then names the home directory instead of the one the session was started in, while `os.getcwd()` still names the launch directory. The rewrite runs before the first plugin hook of the session, so no hook ever sees the launch directory. Hermes' own project-context discovery and its terminal tool follow the same rewritten value. Upstream reports: [hermes-agent#86411](https://github.com/NousResearch/hermes-agent/issues/86411) (an explicit `terminal.cwd` re-asserted mid-turn) and [hermes-agent#95577](https://github.com/NousResearch/hermes-agent/issues/95577) (one-shot sessions anchored at the home directory).
What was reproduced here: the bridge in the Hermes 0.21.0 source, driven with the real `resolve_agent_cwd()` and an empty `TERMINAL_CWD`, the state the report shows at the first turn on 0.21.3. What empties the variable on that install is not established: the upstream `cli.py` at the reported commit still exports `TERMINAL_CWD=os.getcwd()` for the local backend when `cli` is imported, and skips that export only when `_HERMES_GATEWAY=1` is inherited from the environment. With the variable exported, only an explicit `terminal.cwd` in `config.yaml` triggers the rewrite (#86411). The plugin keys off the observed condition, not off a version.
What the plugin does since v3.20.2:
- The failure is no longer silent. When the resolved directory holds no plan and the launch directory of a CLI session does, `pre_llm_call` injects one line instead of nothing: `[planning-with-files] Hermes resolved <dir> as the working directory, but the launch directory <project> holds a plan. Nothing injected. Pin the thread with PWF_PLAN_ROOT=<project>.` The plugin never switches to the launch directory on its own: Hermes' terminal and file tools follow the rewritten directory too, so which root the session should use is the operator's call. The line is CLI-only (other surfaces have no launch directory), and it stays silent for `hermes -w` worktree sessions (Hermes points `TERMINAL_CWD` at `<repo>/.worktrees/<name>` without a chdir, by design), for a launch directory without planning state, and for a launch directory whose session isolation refuses this session anyway.
- `/pwf-status` prints the same line under `No planning files found.` when the launch directory holds a plan, so the diagnostic command tells you what the hooks see, and `/pwf` appends it when the plan it just created went somewhere other than a launch directory that already holds one. Both stay silent for worktree sessions and for contexts whose working directory Hermes has pinned per session at command time; the TUI and Desktop dispatch plugin commands outside that context, where `/pwf-status` has always reported the backend's directory rather than the session's.
- `/pwf` and `/pwf-status` honor `PWF_PLAN_ROOT` exactly like the hooks. A pin that does not resolve is reported instead of creating or reading a plan in whatever directory Hermes named. Without a pin the slash commands follow the Hermes working directory (a command handler receives only its arguments, no platform), so on an affected host an unpinned `/pwf name` creates the plan under the home directory and prints that path; the `planning_with_files_init` tool uses the process working directory instead.
On an affected host, start project-scoped CLI sessions with the pin until the upstream fix lands: `PWF_PLAN_ROOT=/abs/path/to/project hermes chat` (PowerShell: `$env:PWF_PLAN_ROOT = "C:\path\to\project"`). The pin fails closed when the path does not resolve. The shell-hook route below reads the process working directory and is not affected. The pin restores the plan injection only; the agent's terminal and file tools keep following the rewritten directory (`hermes chat --in <project>` does not change that on an affected build), so ask the model to work with absolute paths. Keep planning files out of your home directory: on an affected host a `~/.planning/` or `~/task_plan.md` would be resolved by every session started anywhere.
## Usage
- `/pwf` creates `task_plan.md`, `findings.md` and `progress.md` in the project root. `/pwf Night run` creates an isolated `.planning/YYYY-MM-DD-night-run/` plan and points `.planning/.active_plan` at it. `/pwf --gated Night run` also writes `.mode`, `.nonce`, resets the gate counter and attests the plan, mirroring `init-session.sh --gated`.
@@ -125,7 +139,7 @@ Hermes asks for consent on first use (`hermes hooks list` shows the allowlist st
python -m pytest tests/test_hermes_adapter.py tests/test_hermes_first_class.py -q
```
`tests/test_hermes_first_class.py` covers slug resolution, the `PWF_PLAN_ROOT` pin, the ambiguity rule, `PLANNING_DISABLED`, slug attestation, the `pre_verify` gate (block, counter, stall, cap), `/pwf` and `/pwf-status`, bundled-skill registration, the Python completion fallback and the shell-hook bridge.
`tests/test_hermes_first_class.py` covers slug resolution, the `PWF_PLAN_ROOT` pin, the ambiguity rule, `PLANNING_DISABLED`, slug attestation, the `pre_verify` gate (block, counter, stall, cap), `/pwf` and `/pwf-status`, bundled-skill registration, the Python completion fallback, the shell-hook bridge, and the Hermes 0.21.3 working-directory cases of #272 (the launch-directory notice and where it stays silent, the `/pwf-status` hint, the pinned slash commands).
## Integration Notes
+14 -2
View File
@@ -350,16 +350,23 @@ if ($Mode -ne "") {
# (c) auto-attest (attestation default-on in v3 modes, security strand rec 1).
# attest-plan.ps1 intentionally refuses non-Windows hosts because its secure
# no-follow implementation uses Win32 handles. On Unix, use the POSIX
# attester instead. Bind slug mode to the plan we just created so an
# inherited PLAN_ID cannot redirect attestation to another plan.
# attester instead. Slug mode binds PWF_PLAN_ROOT and PLAN_ID to the plan
# we just created so an inherited pin or slug cannot redirect attestation
# to another project or plan (#261, #237). Root mode clears both instead:
# the attester only falls back to the legacy ./task_plan.md when no
# selector is set, and a bound pin would make it refuse the root plan.
$PlanFilePwf = Join-Path $PlanDirPwf "task_plan.md"
if (Test-Path -LiteralPath $PlanFilePwf) {
$HadPlanId = Test-Path Env:PLAN_ID
$PreviousPlanId = $env:PLAN_ID
$HadPlanRoot = Test-Path Env:PWF_PLAN_ROOT
$PreviousPlanRoot = $env:PWF_PLAN_ROOT
try {
if ($UsePlanDir) {
$env:PWF_PLAN_ROOT = (Get-Location).Path
$env:PLAN_ID = $PlanId
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
@@ -384,6 +391,11 @@ if ($Mode -ne "") {
} else {
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
if ($HadPlanRoot) {
$env:PWF_PLAN_ROOT = $PreviousPlanRoot
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
}
}
}
+13 -4
View File
@@ -103,6 +103,7 @@ slugify() {
# Lowercase, non-alphanumerics → '-', collapse repeats, trim leading/trailing '-'
printf '%s' "$1" \
| tr '[:upper:]' '[:lower:]' \
| tr '\r\n' '--' \
| sed -e 's/[^a-z0-9]/-/g' -e 's/-\{2,\}/-/g' -e 's/^-//' -e 's/-$//' \
| cut -c1-40
}
@@ -202,12 +203,20 @@ apply_v3_mode() {
# (c) auto-attest the plan (attestation default-on in v3 modes, security
# strand rec 1). attest-plan.sh resolves the same way init-session just
# pinned things: in slug mode PLAN_ID points at this plan dir; in legacy
# mode it is empty and the script falls back to ./task_plan.md at root.
# Run from the project root (CWD here) so both resolutions land.
# pinned things. Slug mode binds both selectors to the plan that was
# just created, so an inherited PWF_PLAN_ROOT or PLAN_ID cannot
# redirect attestation to another project or plan (#261, #237). Root
# mode clears both instead: the attester only falls back to the legacy
# ./task_plan.md when no selector is set, and a bound pin would make it
# refuse the root plan. Run from the project root (CWD here) so both
# resolutions land.
_attest="${SCRIPT_DIR}/attest-plan.sh"
if [ -f "${_attest}" ] && [ -f "${_mode_plan}" ]; then
PLAN_ID="${PLAN_ID:-}" sh "${_attest}" >/dev/null 2>&1 || true
if [ "$SLUG_MODE" -eq 1 ]; then
PWF_PLAN_ROOT="$PWD" PLAN_ID="${PLAN_ID}" sh "${_attest}" >/dev/null 2>&1 || true
else
PWF_PLAN_ROOT="" PLAN_ID="" sh "${_attest}" >/dev/null 2>&1 || true
fi
fi
}
+3 -1
View File
@@ -487,7 +487,8 @@ def _format_opencode_part(data: Dict, session_id: str) -> Optional[Dict]:
if ptype == 'tool':
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ if isinstance(input_, dict) else {}
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
return {'session': short, 'summary': f"Tool {tool}: {fp}"}
@@ -595,6 +596,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
+1 -1
View File
@@ -36,7 +36,7 @@ hooks:
- type: command
command: "SH=\"\"; for c in \"${PWF_SCRIPT_DIR}/skill-hook.sh\" \"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files-ar/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\"; do [ -f \"$c\" ] && { SH=\"$c\"; break; }; done; [ -n \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
# نظام تخطيط الملفات
+1 -1
View File
@@ -36,7 +36,7 @@ hooks:
- type: command
command: "SH=\"\"; for c in \"${PWF_SCRIPT_DIR}/skill-hook.sh\" \"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files-de/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\"; do [ -f \"$c\" ] && { SH=\"$c\"; break; }; done; [ -n \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
# Dateiplanungssystem
+1 -1
View File
@@ -36,7 +36,7 @@ hooks:
- type: command
command: "SH=\"\"; for c in \"${PWF_SCRIPT_DIR}/skill-hook.sh\" \"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files-es/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\"; do [ -f \"$c\" ] && { SH=\"$c\"; break; }; done; [ -n \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
# Sistema de Planificación con Archivos
+1 -1
View File
@@ -37,7 +37,7 @@ hooks:
command: "SH=\"\"; for c in \"${PWF_SCRIPT_DIR}/skill-hook.sh\" \"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files-zh/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\"; do [ -f \"$c\" ] && { SH=\"$c\"; break; }; done; [ -n \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
@@ -465,7 +465,7 @@ def _format_opencode_part(data: Dict[str, Any], session_id: str) -> Optional[Dic
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ or {}
input_ = input_ if isinstance(input_, dict) else {}
outcome = _opencode_state_annotation(state)
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
@@ -561,6 +561,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
+1 -1
View File
@@ -37,7 +37,7 @@ hooks:
command: "SH=\"\"; for c in \"${PWF_SCRIPT_DIR}/skill-hook.sh\" \"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files-zht/scripts/skill-hook.sh\" \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\"; do [ -f \"$c\" ] && { SH=\"$c\"; break; }; done; [ -n \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
+1 -1
View File
@@ -28,7 +28,7 @@ hooks:
- type: command
command: "[ -n \"${CLAUDE_PLUGIN_ROOT:-}\" ] && exit 0; SH=\"${CLAUDE_SKILL_DIR}/scripts/skill-hook.sh\"; [ -f \"$SH\" ] || SH=$(ls \"$HOME/.claude/skills/planning-with-files/scripts/skill-hook.sh\" \"$HOME/.claude/plugins/marketplaces/planning-with-files/scripts/skill-hook.sh\" 2>/dev/null | head -1); [ -n \"$SH\" ] && [ -f \"$SH\" ] && sh \"$SH\" --event=precompact; exit 0"
metadata:
version: "3.20.0"
version: "3.20.2"
---
# Planning with Files
@@ -350,16 +350,23 @@ if ($Mode -ne "") {
# (c) auto-attest (attestation default-on in v3 modes, security strand rec 1).
# attest-plan.ps1 intentionally refuses non-Windows hosts because its secure
# no-follow implementation uses Win32 handles. On Unix, use the POSIX
# attester instead. Bind slug mode to the plan we just created so an
# inherited PLAN_ID cannot redirect attestation to another plan.
# attester instead. Slug mode binds PWF_PLAN_ROOT and PLAN_ID to the plan
# we just created so an inherited pin or slug cannot redirect attestation
# to another project or plan (#261, #237). Root mode clears both instead:
# the attester only falls back to the legacy ./task_plan.md when no
# selector is set, and a bound pin would make it refuse the root plan.
$PlanFilePwf = Join-Path $PlanDirPwf "task_plan.md"
if (Test-Path -LiteralPath $PlanFilePwf) {
$HadPlanId = Test-Path Env:PLAN_ID
$PreviousPlanId = $env:PLAN_ID
$HadPlanRoot = Test-Path Env:PWF_PLAN_ROOT
$PreviousPlanRoot = $env:PWF_PLAN_ROOT
try {
if ($UsePlanDir) {
$env:PWF_PLAN_ROOT = (Get-Location).Path
$env:PLAN_ID = $PlanId
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
@@ -384,6 +391,11 @@ if ($Mode -ne "") {
} else {
Remove-Item Env:PLAN_ID -ErrorAction SilentlyContinue
}
if ($HadPlanRoot) {
$env:PWF_PLAN_ROOT = $PreviousPlanRoot
} else {
Remove-Item Env:PWF_PLAN_ROOT -ErrorAction SilentlyContinue
}
}
}
@@ -103,6 +103,7 @@ slugify() {
# Lowercase, non-alphanumerics → '-', collapse repeats, trim leading/trailing '-'
printf '%s' "$1" \
| tr '[:upper:]' '[:lower:]' \
| tr '\r\n' '--' \
| sed -e 's/[^a-z0-9]/-/g' -e 's/-\{2,\}/-/g' -e 's/^-//' -e 's/-$//' \
| cut -c1-40
}
@@ -202,12 +203,20 @@ apply_v3_mode() {
# (c) auto-attest the plan (attestation default-on in v3 modes, security
# strand rec 1). attest-plan.sh resolves the same way init-session just
# pinned things: in slug mode PLAN_ID points at this plan dir; in legacy
# mode it is empty and the script falls back to ./task_plan.md at root.
# Run from the project root (CWD here) so both resolutions land.
# pinned things. Slug mode binds both selectors to the plan that was
# just created, so an inherited PWF_PLAN_ROOT or PLAN_ID cannot
# redirect attestation to another project or plan (#261, #237). Root
# mode clears both instead: the attester only falls back to the legacy
# ./task_plan.md when no selector is set, and a bound pin would make it
# refuse the root plan. Run from the project root (CWD here) so both
# resolutions land.
_attest="${SCRIPT_DIR}/attest-plan.sh"
if [ -f "${_attest}" ] && [ -f "${_mode_plan}" ]; then
PLAN_ID="${PLAN_ID:-}" sh "${_attest}" >/dev/null 2>&1 || true
if [ "$SLUG_MODE" -eq 1 ]; then
PWF_PLAN_ROOT="$PWD" PLAN_ID="${PLAN_ID}" sh "${_attest}" >/dev/null 2>&1 || true
else
PWF_PLAN_ROOT="" PLAN_ID="" sh "${_attest}" >/dev/null 2>&1 || true
fi
fi
}
@@ -474,7 +474,7 @@ def _format_opencode_part(data: Dict[str, Any], session_id: str) -> Optional[Dic
tool = (data.get('tool') or '').lower()
state = data.get('state') or {}
input_ = state.get('input') if isinstance(state, dict) else None
input_ = input_ or {}
input_ = input_ if isinstance(input_, dict) else {}
outcome = _opencode_state_annotation(state)
if tool in ('write', 'edit'):
fp = input_.get('filePath', '')
@@ -577,6 +577,7 @@ def opencode_catchup(project_path: str, mode: str = 'no-history') -> None:
"""
SELECT time_created, data FROM part
WHERE session_id = ?
AND json_valid(data)
AND json_extract(data, '$.type') = 'tool'
AND lower(json_extract(data, '$.tool')) IN ('write', 'edit', 'patch')
AND (
+190 -12
View File
@@ -200,13 +200,14 @@ class HermesFirstClassTests(unittest.TestCase):
os.environ["PLAN_ID"] = ""
self.assertEqual(active, paths_module.resolve_plan_dir(root))
def test_newest_slug_by_mtime_when_no_pointer(self) -> None:
def test_single_slug_discovers_without_pointer_but_multiple_require_selector(self) -> None:
with self._workspace() as root:
older = self._slug_plan(root, "2026-08-01-old")
newer = self._slug_plan(root, "2026-09-01-new")
past = time.time() - 3600
os.utime(older / "task_plan.md", (past, past))
self.assertEqual(newer, paths_module.resolve_plan_dir(root))
self.assertEqual(older, paths_module.resolve_plan_dir(root))
self._slug_plan(root, "2026-09-01-new")
self.assertIsNone(paths_module.resolve_plan_dir(root))
os.environ["PLAN_ID"] = "2026-08-01-old"
self.assertEqual(older, paths_module.resolve_plan_dir(root))
@@ -337,7 +338,7 @@ class HermesFirstClassTests(unittest.TestCase):
self.assertEqual(alpha.name, "plan-a")
self.assertEqual(beta.name, "plan-b")
def test_armed_single_plan_and_legacy_multiple_plans_keep_resolution(self) -> None:
def test_single_plan_resolves_but_legacy_multiple_plans_require_plan_id(self) -> None:
with self._workspace() as root:
self._slug_plan(root, "plan-a", text="# PLAN-A\n", pointer=True)
os.chdir(root)
@@ -353,7 +354,14 @@ class HermesFirstClassTests(unittest.TestCase):
self._slug_plan(root, "plan-b", text="# PLAN-B\n", pointer=True)
legacy = self._pre_llm("unattached")
assert legacy is not None
self.assertIn("PLAN-B", legacy["context"])
self.assertIn("Multiple plans are available", legacy["context"])
self.assertIn("Set PLAN_ID=<slug>", legacy["context"])
self.assertNotIn("PLAN-A", legacy["context"])
self.assertNotIn("PLAN-B", legacy["context"])
os.environ["PLAN_ID"] = "plan-b"
selected = self._pre_llm("unattached")
assert selected is not None
self.assertIn("PLAN-B", selected["context"])
def test_armed_root_and_slug_plans_require_a_plan_id(self) -> None:
with self._workspace() as root:
@@ -421,12 +429,9 @@ class HermesFirstClassTests(unittest.TestCase):
self.assertIn("PLAN-A", result["context"])
self.assertNotIn("Set PLAN_ID=<slug>", result["context"])
def test_active_plan_pointer_tolerates_a_utf8_bom(self) -> None:
def test_active_plan_pointer_tolerates_a_utf8_bom_with_single_plan(self) -> None:
with self._workspace() as root:
older = self._slug_plan(root, "2026-08-01-aaa")
self._slug_plan(root, "2026-09-01-zzz")
past = time.time() - 3600
os.utime(older / "task_plan.md", (past, past))
(root / ".planning" / ".active_plan").write_bytes(b"\xef\xbb\xbf2026-08-01-aaa\r\n")
self.assertEqual(older, paths_module.resolve_plan_dir(root))
@@ -547,17 +552,22 @@ class HermesFirstClassTests(unittest.TestCase):
self._slug_plan(root, "2026-09-01-parent", text="# PARENT\n", pointer=True)
self.assertTrue(shell_injects(root, {}))
self.assertIsNotNone(paths_module.resolve_plan_dir(root))
# 2. empty nested .planning: both still inject
# 2. a second same-root plan without PLAN_ID: both refuse
second = self._slug_plan(root, "2026-09-02-second", text="# SECOND\n")
self.assertFalse(shell_injects(root, {}))
self.assertIsNone(paths_module.resolve_plan_dir(root))
shutil.rmtree(second)
# 3. empty nested .planning: both still inject
(root / "svc" / ".planning").mkdir(parents=True)
self.assertTrue(shell_injects(root, {}))
self.assertIsNotNone(paths_module.resolve_plan_dir(root))
# 3. live nested plan: both refuse
# 4. live nested plan: both refuse
live = root / "svc" / ".planning" / "2026-09-01-child"
live.mkdir()
(live / "task_plan.md").write_text("# CHILD\n", encoding="utf-8")
self.assertFalse(shell_injects(root, {}))
self.assertIsNone(paths_module.resolve_plan_dir(root))
# 4. explicit PLAN_ID and a PWF_PLAN_ROOT pin: both inject again
# 5. explicit PLAN_ID and a PWF_PLAN_ROOT pin: both inject again
self.assertTrue(shell_injects(root, {"PLAN_ID": "2026-09-01-parent"}))
self.assertIsNotNone(paths_module.resolve_plan_dir(root, plan_id="2026-09-01-parent"))
self.assertTrue(shell_injects(root, {"PWF_PLAN_ROOT": str(root)}))
@@ -573,6 +583,154 @@ class HermesFirstClassTests(unittest.TestCase):
hooks_module.post_tool_call(tool_name="write_file", session_id="s1", args={"path": "a", "content": "b"})
self.assertEqual([], hook_state_module.pop_reminders(root, "s1"))
# -- issue #272: the host re-homes the process-global cwd ------------------
def _hermes_reports(self, directory: Path) -> None:
"""Point the stubbed resolve_agent_cwd at *directory* (what TERMINAL_CWD would say)."""
sys.modules["agent.runtime_cwd"].resolve_agent_cwd = lambda: directory # type: ignore[attr-defined]
def _first_turn(self, session: str, platform: str = "cli"):
return hooks_module.pre_llm_call(user_message="hi", is_first_turn=True, session_id=session, platform=platform)
def test_rehomed_cli_session_gets_the_pin_notice_instead_of_silence(self) -> None:
with self._workspace() as tmp:
root = tmp / "project"
home = tmp / "home"
root.mkdir()
home.mkdir()
self._slug_plan(root, "2026-09-19-run", pointer=True)
os.chdir(root)
# Hermes 0.21.3: the first turn already reports the home directory
self._hermes_reports(home)
payload = self._first_turn("s1")
assert payload is not None
notice = payload["context"]
self.assertTrue(notice.startswith("[planning-with-files] Hermes resolved "), notice)
self.assertIn(str(home), notice)
self.assertIn(f"launch directory {root} holds a plan", notice)
self.assertIn("Nothing injected", notice)
self.assertIn(f"PWF_PLAN_ROOT={root}", notice)
self.assertNotIn("Build the adapter", notice)
# the notice is turn-scoped: the other hooks stay quiet, like the ambiguity notice
hooks_module.post_tool_call(tool_name="write_file", session_id="s1", args={"path": "a", "content": "b"})
self.assertEqual([], hook_state_module.pop_reminders(root, "s1"))
self.assertEqual([], hook_state_module.pop_reminders(home, "s1"))
self.assertIsNone(self._pre_verify("s1"))
# following the notice restores the plan; the pin also silences the notice
os.environ["PWF_PLAN_ROOT"] = str(root)
pinned = self._first_turn("s1")
assert pinned is not None
self.assertIn("Build the adapter", pinned["context"])
self.assertNotIn("Hermes resolved", pinned["context"])
os.environ.pop("PWF_PLAN_ROOT")
# a host that reports the launch directory is unchanged: plan, no notice
self._hermes_reports(root)
healthy = self._first_turn("s2")
assert healthy is not None
self.assertIn("Build the adapter", healthy["context"])
self.assertNotIn("Hermes resolved", healthy["context"])
# two selectable plans at the launch directory still count as "holds a plan"
self._hermes_reports(home)
self._slug_plan(root, "2026-09-19-other")
several = self._first_turn("s3")
assert several is not None
self.assertIn("holds a plan", several["context"])
def test_pin_notice_stays_silent_where_it_would_mislead(self) -> None:
with self._workspace() as tmp:
root = tmp / "project"
home = tmp / "home"
root.mkdir()
home.mkdir()
self._slug_plan(root, "2026-09-19-run", pointer=True)
os.chdir(root)
self._hermes_reports(home)
# only the CLI has a launch directory: gateway, TUI and Desktop sessions stay silent
for platform in ("telegram", "tui", "desktop", ""):
self.assertIsNone(self._first_turn("s9", platform), platform)
# PLANNING_DISABLED still silences everything
os.environ["PLANNING_DISABLED"] = "1"
self.assertIsNone(self._first_turn("s1"))
os.environ.pop("PLANNING_DISABLED")
# a launch directory without planning state: silent, as before
os.chdir(home)
self.assertIsNone(self._first_turn("s4"))
os.chdir(root)
# hermes -w: TERMINAL_CWD names <repo>/.worktrees/<name> without a chdir, by design
worktree = root / ".worktrees" / "hermes-abc123"
worktree.mkdir(parents=True)
self._hermes_reports(worktree)
self.assertIsNone(self._first_turn("s5"))
# a launch directory whose session isolation refuses this session: the pin would not help
self._hermes_reports(home)
(root / ".planning" / "sessions").mkdir()
self.assertIsNone(self._first_turn("s6"))
key = hook_state_module.state_key(root, "s6")
(root / ".planning" / "sessions" / f"{key}.attached").write_text("attached\n", encoding="ascii")
attached = self._first_turn("s6")
assert attached is not None
self.assertIn("holds a plan", attached["context"])
def test_slash_commands_honor_the_plan_root_pin(self) -> None:
with self._workspace() as tmp:
home = tmp / "home"
project = tmp / "project"
home.mkdir()
project.mkdir()
self._slug_plan(project, "2026-09-19-run", mode="autonomous gate", attest=True, pointer=True)
os.chdir(home)
self._hermes_reports(home)
self.assertEqual("No planning files found. Run planning_with_files_init first.", plugin.status_command(""))
os.environ["PWF_PLAN_ROOT"] = str(project)
self.assertIn("2026-09-19-run", plugin.status_command(""))
created = plugin.pwf_command("--gated Second Run")
self.assertIn("gated mode", created)
self.assertEqual(1, len(list((project / ".planning").glob("*-second-run"))))
self.assertFalse((home / ".planning").exists())
os.environ["PWF_PLAN_ROOT"] = str(tmp / "missing")
self.assertEqual(plugin.BROKEN_PIN_MESSAGE, plugin.status_command(""))
self.assertEqual(plugin.BROKEN_PIN_MESSAGE, plugin.pwf_command("--gated Third Run"))
self.assertFalse((home / ".planning").exists())
self.assertFalse((home / "task_plan.md").exists())
def test_status_command_names_the_launch_directory_plan(self) -> None:
with self._workspace() as tmp:
home = tmp / "home"
project = tmp / "project"
home.mkdir()
project.mkdir()
self._slug_plan(project, "2026-09-19-run", pointer=True)
os.chdir(project)
self._hermes_reports(home)
report = plugin.status_command("")
self.assertTrue(report.startswith("No planning files found."), report)
self.assertIn(f"launch directory {project} holds a plan", report)
self.assertIn(f"PWF_PLAN_ROOT={project}", report)
# the hint is diagnostic only: a plan found where Hermes points needs none
self._hermes_reports(project)
self.assertNotIn("Hermes resolved", plugin.status_command(""))
# worktree sessions are exempt, and the pin replaces the hint
worktree = project / ".worktrees" / "hermes-abc123"
worktree.mkdir(parents=True)
self._hermes_reports(worktree)
self.assertEqual("No planning files found. Run planning_with_files_init first.", plugin.status_command(""))
self._hermes_reports(home)
# a TUI or Desktop context pins its cwd per session: the process cwd is no launch directory
runtime = sys.modules["agent.runtime_cwd"]
runtime._SESSION_CWD = types.SimpleNamespace(get=lambda: str(home)) # type: ignore[attr-defined]
self.assertEqual("No planning files found. Run planning_with_files_init first.", plugin.status_command(""))
runtime._SESSION_CWD = types.SimpleNamespace(get=lambda: "") # type: ignore[attr-defined]
self.assertIn("holds a plan", plugin.status_command(""))
del runtime._SESSION_CWD
# /pwf follows the Hermes directory and says where the plan went and what was skipped
created = plugin.pwf_command("Second Run")
self.assertIn(f"directory: {home / '.planning'}", created)
self.assertIn(f"launch directory {project} holds a plan", created)
self.assertEqual(1, len(list((home / ".planning").glob("*-second-run"))))
os.environ["PWF_PLAN_ROOT"] = str(project)
self.assertIn("2026-09-19-run", plugin.status_command(""))
self.assertNotIn("Hermes resolved", plugin.pwf_command("Third Run"))
# -- injection ------------------------------------------------------------
def test_slug_plan_injection_names_plan_and_reads_slug_attestation(self) -> None:
@@ -685,6 +843,26 @@ class HermesFirstClassTests(unittest.TestCase):
self.assertEqual("2026-09-01-run", result["plan_id"])
self.assertIn("ALL PHASES COMPLETE", result["stdout"])
def test_status_and_check_complete_require_selector_for_multiple_plans(self) -> None:
with self._workspace() as root:
self._slug_plan(root, "plan-a", text=COMPLETE_PLAN, pointer=True)
self._slug_plan(root, "plan-b", text=COMPLETE_PLAN)
status = json.loads(tools_module.planning_with_files_status(cwd=str(root)))
self.assertFalse(status["exists"])
self.assertIn("Multiple plans are available", status["message"])
self.assertIn("Set PLAN_ID=<slug>", status["message"])
complete = json.loads(tools_module.planning_with_files_check_complete(cwd=str(root)))
self.assertFalse(complete["ok"])
self.assertFalse(complete["complete"])
self.assertIn("Multiple plans are available", complete["error"])
os.environ["PLAN_ID"] = "plan-a"
selected = json.loads(tools_module.planning_with_files_status(cwd=str(root)))
self.assertTrue(selected["exists"])
self.assertEqual("plan-a", selected["plan_id"])
# -- registration and slash commands -------------------------------------
def test_register_wires_hooks_commands_and_bundled_skill(self) -> None:
+59
View File
@@ -68,6 +68,23 @@ class AutonomousModeTests(InitModesTestBase):
attest = (plan_dir / ".attestation").read_text(encoding="utf-8").strip()
self.assertRegex(attest, r"^[0-9a-f]{64}$", "attestation must be a sha256 hex digest")
def test_autonomous_attests_current_project_despite_inherited_plan_root(self) -> None:
with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as other_tmp:
root = Path(tmp)
other = Path(other_tmp)
env = os.environ.copy()
env.pop("PLAN_ID", None)
env["PWF_PLAN_ROOT"] = str(other)
result = subprocess.run(
["sh", str(INIT_SH), "--autonomous", "Pinned Elsewhere"],
cwd=str(root), text=True, encoding="utf-8", capture_output=True,
env=env, check=False,
)
self.assertEqual(0, result.returncode, result.stderr)
plan_dir = self.only_plan_dir(root)
self.assertTrue((plan_dir / ".attestation").is_file())
self.assertFalse((other / ".plan-attestation").exists())
def test_autonomous_resets_stop_blocks_to_zero(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
@@ -149,6 +166,48 @@ class AutonomousLegacyRootModeTests(InitModesTestBase):
)
self.assertEqual("0", (root / ".stop_blocks").read_text(encoding="utf-8").strip())
def test_autonomous_in_legacy_root_attests_the_root_plan(self) -> None:
# Root mode attests ./task_plan.md through the attester's legacy
# fallback, which only runs when no selector is set. Binding
# PWF_PLAN_ROOT for the attest call (as slug mode does) would make the
# attester refuse the root plan and leave the v3 markers unattested.
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
result = self.run_init(root, "--autonomous")
self.assertEqual(0, result.returncode, result.stderr)
self.assertTrue((root / ".plan-attestation").is_file(), "root mode must attest ./task_plan.md")
attest = (root / ".plan-attestation").read_text(encoding="utf-8").strip()
self.assertRegex(attest, r"^[0-9a-f]{64}$")
def test_gated_in_legacy_root_attests_the_root_plan(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
result = self.run_init(root, "--gated")
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual("autonomous gate", (root / ".mode").read_text(encoding="utf-8").strip())
self.assertTrue((root / ".plan-attestation").is_file(), "gated root mode must attest ./task_plan.md")
def test_autonomous_in_legacy_root_ignores_inherited_pin_and_plan_id(self) -> None:
# An inherited PWF_PLAN_ROOT (another project) or PLAN_ID (a sibling
# slug plan) must neither redirect root-mode attestation elsewhere nor
# block it: the root plan just written is the one attested.
with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as other_tmp:
root = Path(tmp)
other = Path(other_tmp)
(other / "task_plan.md").write_text("# Other project\n", encoding="utf-8")
env = os.environ.copy()
env["PWF_PLAN_ROOT"] = str(other)
env["PLAN_ID"] = "2026-01-01-sibling"
result = subprocess.run(
["sh", str(INIT_SH), "--autonomous"],
cwd=str(root), text=True, encoding="utf-8", capture_output=True,
env=env, check=False,
)
self.assertEqual(0, result.returncode, result.stderr)
self.assertTrue((root / ".plan-attestation").is_file())
self.assertFalse((other / ".plan-attestation").exists())
self.assertFalse((root / ".planning").exists())
if __name__ == "__main__":
unittest.main()
@@ -143,6 +143,51 @@ class InitSessionPowerShellSlugTests(unittest.TestCase):
)
self.assertTrue((plan_dir / ".attestation").is_file())
def test_named_autonomous_plan_attests_current_project_despite_stale_plan_root(self) -> None:
with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as other_tmp:
root = Path(tmp)
other = Path(other_tmp)
env = child_env()
env["PWF_PLAN_ROOT"] = str(other)
result = subprocess.run(
[POWERSHELL, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(INIT_PS1), "-Autonomous", "Bound Root"],
cwd=str(root), text=True, encoding="utf-8-sig", capture_output=True,
env=env, check=False,
)
self.assertEqual(0, result.returncode, result.stderr)
plan_dir = root / ".planning" / f"{date.today().isoformat()}-bound-root"
self.assertTrue((plan_dir / ".attestation").is_file())
def test_root_autonomous_plan_attests_the_root_plan(self) -> None:
# Root mode attests the root task_plan.md through the attester's legacy
# fallback, which only runs when no selector is set; binding
# PWF_PLAN_ROOT here (as slug mode does) makes the attester refuse it.
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
result = self.run_init(root, "-Autonomous")
self.assertEqual(0, result.returncode, result.stderr)
self.assertFalse((root / ".planning").exists())
self.assertEqual("autonomous", (root / ".mode").read_text(encoding="utf-8").strip())
self.assertTrue((root / ".plan-attestation").is_file(), "root mode must attest task_plan.md")
def test_root_gated_plan_attests_the_root_plan_despite_inherited_pin_and_plan_id(self) -> None:
with tempfile.TemporaryDirectory() as tmp, tempfile.TemporaryDirectory() as other_tmp:
root = Path(tmp)
other = Path(other_tmp)
(other / "task_plan.md").write_text("# Other project\n", encoding="utf-8")
env = child_env()
env["PWF_PLAN_ROOT"] = str(other)
env["PLAN_ID"] = "2026-01-01-sibling"
result = subprocess.run(
[POWERSHELL, "-NoProfile", "-ExecutionPolicy", "Bypass", "-File", str(INIT_PS1), "-Gated"],
cwd=str(root), text=True, encoding="utf-8-sig", capture_output=True,
env=env, check=False,
)
self.assertEqual(0, result.returncode, result.stderr)
self.assertEqual("autonomous gate", (root / ".mode").read_text(encoding="utf-8").strip())
self.assertTrue((root / ".plan-attestation").is_file())
self.assertFalse((other / ".plan-attestation").exists())
def test_named_autonomous_plan_attests_new_plan_despite_stale_plan_id(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
+12
View File
@@ -56,6 +56,18 @@ class InitSessionSlugTests(unittest.TestCase):
active = (root / ".planning" / ".active_plan").read_text(encoding="utf-8").strip()
self.assertEqual(active, f"{today}-backend-refactor")
def test_slug_embedded_newline_creates_single_line_plan_id(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
result = self.run_init(root, "line one\nline two")
self.assertEqual(0, result.returncode, result.stderr)
today = date.today().isoformat()
expected = root / ".planning" / f"{today}-line-one-line-two"
self.assertTrue(expected.is_dir(), f"got {[p.name for p in (root / '.planning').iterdir()]}")
plan_dirs = [p for p in (root / ".planning").iterdir() if p.is_dir()]
self.assertEqual([expected], plan_dirs)
self.assertNotIn("\n", plan_dirs[0].name)
def test_slug_sanitizes_unsafe_chars(self) -> None:
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
+42
View File
@@ -88,6 +88,13 @@ class OpenCodeSchemaSeed:
)
self.conn.commit()
def add_raw_part(self, part_id: str, sid: str, time_created: int, data: str) -> None:
self.conn.execute(
"INSERT INTO part (id, session_id, time_created, data) VALUES (?, ?, ?, ?)",
(part_id, sid, time_created, data),
)
self.conn.commit()
def close(self) -> None:
self.conn.close()
@@ -154,6 +161,41 @@ class OpenCodeCatchupTests(unittest.TestCase):
self.assertNotIn("ses_old", output)
self.assertIn("Tool edit", output, "follow-up edit after plan write should appear in catchup")
def test_malformed_tool_shapes_are_skipped_without_hiding_healthy_parts(self) -> None:
self.seed.add_part(
"prt_bad_state",
"ses_old",
1_000_012,
{"type": "tool", "tool": "edit", "state": "broken"},
)
self.seed.add_part(
"prt_bad_input",
"ses_old",
1_000_015,
{
"type": "tool",
"tool": "edit",
"state": {"input": "broken"},
},
)
buf = StringIO()
with redirect_stdout(buf):
self.module.opencode_catchup(str(self.project_dir), mode="replay")
self.assertIn("SESSION CATCHUP DETECTED (IDE: opencode)", buf.getvalue())
self.assertIn("Tool edit", buf.getvalue())
def test_invalid_json_part_is_skipped_without_hiding_healthy_parts(self) -> None:
self.seed.add_raw_part("prt_bad_json", "ses_old", 1_000_005, "not json")
buf = StringIO()
with redirect_stdout(buf):
self.module.opencode_catchup(str(self.project_dir), mode="replay")
self.assertIn("SESSION CATCHUP DETECTED (IDE: opencode)", buf.getvalue())
self.assertIn("Tool edit", buf.getvalue())
def test_metadata_mode_excludes_session_tool_and_path_bytes(self) -> None:
buf = StringIO()
with redirect_stdout(buf):