Compare commits

...
474 Commits
Author SHA1 Message Date
GodopuandClaude Opus 5.5 f90a705316 fix(reset): SKILL.md version follows main's lockstep 4.13.0 after the rebase (#78)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 12:52:23 +00:00
Godopu b5040cffab fix(reset): record captured old_id in spec, exit on signals, and reject unknown spec agents (#78) 2026-10-29 12:52:17 +00:00
Godopu fb1895030f feat(reset): multi-agent-mux-reset skill - reset.sh, SKILL.md, packaging (#78) 2026-10-29 12:52:17 +00:00
Godopu ca2532307f feat(reset): lib_py.reset - targets, spec file, progress, result table (#78) 2026-10-29 12:52:17 +00:00
Godopu 51dfd38f0b fix(codex): purge removes tui-thread-reference-capabilities/<uuid> (#78) 2026-10-29 12:52:17 +00:00
Godopu c6eb4564d2 fix(agents): in_use_hints lists the processes holding the conversation file (lsof) (#78) 2026-10-29 12:52:17 +00:00
Godopu a3364e82e1 merge: fix/issue-68 (worktree creator onboards by default; create --no-onboard warns; v4.13.0) 2026-10-29 07:56:58 +00:00
GodopuandClaude Opus 5.5 a582934f6a release(v4.13.0): worktree creator onboards by default; create --no-onboard warns for post-discovered-id agents (Issue #68) - archive the review reports, bump the lockstep version
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-29 16:56:48 +09:00
GodopuandClaude Opus 5.5 a7bf07bb1c fix(create): SKILL.md says a same-folder create waits (#63); drop unused import (Issue #68, review)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-29 15:12:55 +09:00
GodopuandClaude Opus 5.5 3b81f99732 test(issue26): classify MAM_ID_POST_DISCOVERED as a string compare (Issue #68)
create_session.sh reads the new adapter fact as "${MAM_ID_POST_DISCOVERED:-0}"
and compares it with "= 1"; test_b5 requires every such default to be
classified.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 18:46:40 +00:00
Godopu 7cf63f4858 fix(tests): pass --no-onboard in test_issue21_acceptance and shift evidence pins (Issue #68, review round 1) 2026-10-28 17:19:22 +00:00
Godopu c0e9f5c8a5 feat(worktree): onboard creator by default in worktree_prepare.sh (Issue #68) 2026-10-28 15:04:51 +00:00
Godopu 3fd2416a30 feat(create): warn on --no-onboard for post-discovered-id agents (Issue #68) 2026-10-28 15:01:50 +00:00
Godopu 5305cf21f9 feat(agents): expose MAM_ID_POST_DISCOVERED in facts bridge (Issue #68) 2026-10-28 14:56:04 +00:00
Godopu b9c828f092 merge: docs/instruction-skill-authoring (INSTRUCTION.md) 2026-10-28 00:03:23 +00:00
GodopuandClaude Opus 5.5 4490e7053b docs: INSTRUCTION.md for developing MAM itself; skills put behaviour in code before SKILL.md prose
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-28 09:03:14 +09:00
Godopu ad65d4833e merge: docs/issue72-admission-notes (update skill admission notes) 2026-10-27 23:52:01 +00:00
GodopuandClaude Opus 5.5 7d2f65ad42 docs(update): entries refuse during the update's checks too; create and resume take every installed workspace's lock (Issue #72 follow-up)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-28 08:51:54 +09:00
Godopu 225c52710a merge: fix/issue-72 (update skill, in-place install, update admission gate; resume starts the monitor; v4.12.0) 2026-10-27 22:50:04 +00:00
GodopuandClaude Opus 5.5 56e6713292 release(v4.12.0): update skill with in-place install and an update admission gate; resume starts the monitor (Issue #72) - archive the review reports, bump the lockstep version
The update skill joins the version matrix and the lockstep test's skill list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-28 07:49:53 +09:00
GodopuandClaude Opus 5.5 ec7f5c4e57 fix(update): the legacy start_watchdog starts the monitor in its own process group; tests clean up only the processes they started (Issue #72, review round 5)
With MAM_DELEGATION_PY=0 the monitor was left in the caller's process group
(decision 2), on every restart the update makes. The legacy body now spawns
it under job control (`set -m`, macOS has no setsid(1)) and restores the
caller's option. The update tests assert the restarted monitor's PGID in both
modes, and their teardown kills helper groups and this test's exact monitors
instead of `pkill -f <ws>`, then reports anything left that names the
workspace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 05:18:04 +09:00
GodopuandClaude Opus 5.5 1d63e882bc fix(update): the legacy start_watchdog matches the monitor exactly too; a restart is reported only when the monitor runs (Issue #72, review round 4)
With MAM_DELEGATION_PY=0 the legacy helper still found the monitor with an
unanchored pgrep -f, so a process that only named the monitor path was
reported as the restarted monitor and none was started. lib.sh _monitor_pids
is the shell twin of daemon.find_running; update.sh and post_update.sh check
the PID start_watchdog printed with mam_monitor_started before saying
"monitor: restarted".

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 04:10:15 +09:00
GodopuandClaude Opus 5.5 cf1b693e85 fix(update): the monitor is this workspace's exact command line; create/resume take the pane workspace's admission; refusal snapshots compare the registry by rows (Issue #72, review round 3)
- daemon.find_running matches `<bash> <reconcile.sh> --subscribe[ ...]`
  exactly instead of an unanchored, unescaped pgrep regex: another
  workspace's daemon (ws.a vs wsXa) or a process naming the path in an
  argument is no longer signalled by the update. update.sh re-checks which
  PIDs are still the monitor before SIGKILL.
- create and resume (spawn path) take the update admission of every
  installed workspace at or above the pane cwd, not only the control
  root's (lib.sh mam_update_admit_at, lib_py.update target-workspaces --cwd);
  the ~/.local/bin wrapper child drops all of them.
- tests: snapshot() skips the SQLite -wal/-shm and compares the DB by its
  rows (macOS keeps the sidecars and a read rewrites -shm); regression tests
  for the monitor match and for create/resume in another installed
  workspace (marker and lock wait); evidence line refs shifted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 02:28:55 +09:00
GodopuandClaude Opus 5.5 454b77215f fix(update): a state write failure before the install restarts the monitor; the exit table names the conversion code (Issue #72, review notes)
install_phase.sh exited when it could not mark the backup `installing`,
before the installer ran, without starting the monitor phase 1 had stopped
(decision 2) and leaving the backup behind. Nothing was changed at that
point, so it now removes the backup, restarts the monitor if it ran,
releases the marker and exits 1.

SKILL.md's exit row said 1 for every failure; a failed registry conversion
after a good install passes the converter's nonzero code through, and a
cancelled prompt exits 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 14:35:35 +00:00
GodopuandClaude Opus 5.5 253a0aa56e fix(delegate): admission covers a rowless target and the installed parent of an incidental .mam (Issue #72, review round 2)
R1: a target with no registry row skipped the target gate. Its cwd is now
read from the live agent on the server delivery uses (resolve_herdr_session),
through the real herdr only when that server is running, so no server is
started; a herdr that cannot answer refuses before registration.

R2: any .mam counted as a workspace and stopped the walk, so B/sub/.mam hid
an installed B and the row's control_plane root was dropped. Workspaces are
now update.sh's installed trees (.mam_deploy/remove.sh or remove.sh): every
installed ancestor of the cwd, plus the recorded control_plane root.

lib_py.update target-workspaces prints them one per line; the wrapper holds
each on fds 20.. until the record is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 11:09:30 +00:00
GodopuandClaude Opus 5.5 ba75718ac3 fix(update): an unlistable jobs directory refuses; the rowless-agent hint names its server (Issue #72, review R2, R3)
R2: glob() hid a listing error, so an unreadable .mam/jobs (or MAM_JOBS_DIR,
or another row's jobs dir) counted as empty and the update installed over an
open job. Records are now listed with os.listdir; a directory that cannot be
listed, or stat'ed, is a blocker with its path.

R3: a discovered agent with no row was told to run stop with --session only;
stop then looked on the workspace's server, not the one the agent was found
on. The hint now carries --herdr-session <server>, quoted.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 08:15:23 +00:00
GodopuandClaude Opus 5.5 e3394655b3 fix(delegate): submit also takes the target workspace's update admission (Issue #72, review R1)
Decision 8: delegate submit uses the admission lock of the workspace the
target session belongs to. The wrapper resolved only its own
WORKSPACE_ROOT, so a job could be registered and delivered to an agent of
another installed workspace while that workspace was being updated.

lib_py.update target-workspace resolves a herdr:<name> row's workspace (the
.mam at or above its pane.cwd, else its control_plane.workspace_root);
mam_update_admit takes an fd, and submit holds the caller root on fd 7 and
the target on fd 8 until the record is written. Rowless and remote targets
keep the caller-root gate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 08:15:23 +00:00
GodopuandClaude Opus 5.5 595e34b2d1 fix(gate): no admission lock in a tree without .mam; MAM_UPDATE_MONITOR_STOP_S in the knob table (Issue #72)
mam_update_admit created .mam/ to hold its lock, so a checkout running its
own run_loop.sh got a .mam (test_loop_marker_isolation L1, test_issue17 W1).
A tree without .mam is not an installed workspace, the only kind the update
runs in, so the gate admits there without a lock. The update's monitor-stop
wait is a normalised integer knob and is listed in INT_KNOBS
(test_issue26_ints B5).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 04:48:43 +00:00
GodopuandClaude Opus 5.5 8f325de979 docs(resume): the flow ends with the monitor daemon (Issue #72)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 04:16:38 +00:00
GodopuandClaude Opus 5.5 515b3206b9 chore(shellcheck): no new findings in the update skill, lib.sh and install.sh (Issue #72)
CI now shellchecks the update skill's scripts: SC1091 is disabled at their
`source` lines as in the other skills, and the two findings this branch added
(lib.sh's loop_lock.sh source, install.sh's one-item legacy loop) are
disabled at their lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 04:08:57 +00:00
GodopuandClaude Opus 5.5 fce9459e42 test(update): the first transition reaches the skill and the conversion (Issue #72, criterion 5)
A v4.11.0 workspace's .mam_deploy/update.sh installs the new version - the
skill present, no updater left - and the skill run after it converts the
registry. An update-backup in an unknown state now restarts the monitor it
stopped: nothing was changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 04:07:42 +00:00
GodopuandClaude Opus 5.5 47fe24e07c feat: multi-agent-mux-update skill and in-place install (Issue #72)
The update is a skill (decision 4); deploy/update.sh and the installed
.mam_deploy/update.sh are gone.

- Phase 1 (installed code, update.sh): publish the update marker under the
  exclusive admission lock; refuse before any change while a running row, a
  live herdr agent in the workspace on any running server, an open job
  (unreadable JSON included, dry_run not), a live loop marker or a
  monitor.lock held by a monitor the skills did not start (U3) is there - the
  calling agent (server + pane, its row and one running job) excepted
  (lib_py/update.py precheck, decisions 1 and 7). Stop the monitor (TERM, then
  KILL and restart it if it does not end; decision 2), handle a leftover
  backup by its state (U4), back up .agents, .mam_deploy, root files, .venv,
  the installer's .mam files and the registry (SQLite backup API under the
  registry lock) into .mam/update-backup/, then exec a copy of
  install_phase.sh outside the tree (decision 5).
- The copy (no lib.sh/lib_py, bash 3.2) runs the installer in place; on
  failure it restores the backup and restarts the monitor from the restored
  tree; on success it runs phase 2, post_update.sh of the new tree, which
  converts the registry with lib_py.registry_format and restarts the monitor
  if it ran. The backup and the marker are removed at the end.
- install.sh updates in place (decisions 3, 4, 9): install_state keys are set,
  one line each; no updater is installed and an old one (.mam_deploy/update.sh,
  or a root update.sh the manifest lists) is removed; framework files the new
  version no longer ships are deleted when unmodified, kept and listed when
  modified, and dropped from base/, the manifest and asset_hashes.txt; a local
  source's .mam is not staged. remove.sh knows the new skill; CI shellchecks
  its scripts; docs point at the skill.
- test_issue8_update_state and test_deploy_layout td6/td27 run the skill.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 04:06:57 +00:00
GodopuandClaude Opus 5.5 6359d65999 feat: update admission gate - entries refuse while an update runs (Issue #72, decision 8, U2)
The update skill publishes .mam/update-in-progress (pid + lstart, the
loop_lock.sh rules) while it holds .mam/update-admission.lock exclusively.
create, resume, run_loop.sh and delegate submit (decision 8) and stop and
orc-onboard (U2: a rollback would restore the registry without their write)
take that lock shared (lib.sh mam_update_admit, fd 7), refuse while the marker
is live or unknown, and hold the lock until their record is written. A stale
marker refuses nothing. lib_py.pane_lock acquire gains --shared and
--wait-env (MAM_UPDATE_ADMISSION_WAIT_S, default 120); create's wrapper path
closes fd 7 for the long-lived child. The exit-1 rows of create/resume/stop
name the refusal; skill_code_blocks.json pins follow the shifted lines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 04:06:42 +00:00
GodopuandClaude Opus 5.5 179473e5d5 feat(resume): resume ensures the monitor daemon (Issue #72, decision 2)
Only create started the per-workspace monitor, and only on its job path, so
the stop -> update -> resume flow the update skill requires left no monitor.
resume now calls start_watchdog with the control root as workdir (as create
does since #21 A8, also for a worktree session) after the row is written, on
both the already-running and the spawn path. MAM_NO_SUBSCRIBER_DAEMON=1 starts
none; a failure warns and does not fail the resume.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 04:06:32 +00:00
GodopuandClaude Opus 5.5 ec378e82c9 fix(attach): hints print the row's attach_command (Issue #72, comments 926/930, U1)
create's closing hint, the delegate-job wrapper's dispatch hint and stop's
stuck-TUI message printed the pre-#71 forms (`herdr session attach <name>`,
`HERDR_SESSION_NAME=... herdr agent attach <name>`), which miss an agent whose
name is over 32 characters or has upper case. They now print the session row's
attach_command, or lib_py.agents.sanitize.attach_command(server, name) when
there is no row (lib.sh session_attach_command). deploy/INSTALL.md and
install_mam.sh show the `herdr --session <server> agent attach <herdr name>`
form.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 04:05:00 +00:00
Godopu 0e1e2e87de merge: fix/issue-71 (attach uses the herdr-registered name; sessions start and stop only through the skills; v4.11.0) 2026-10-26 22:28:51 +00:00
GodopuandClaude Opus 5.5 342a9a4edf release(v4.11.0): attach uses the herdr-registered name; sessions start and stop only through the skills (Issue #71) - archive the review reports, bump the lockstep version
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-27 07:28:47 +09:00
GodopuandClaude Opus 5.5 5f6065344f fix(lib.sh): load_state_json strict treats a missing DB table as unreadable (Issue #71)
A DB without its sessions table (or without both tables) was read as an
empty registry in strict mode, so stop closed a registered session
row-less and exited 0. Strict mode now fails on any OperationalError;
the non-strict reader is unchanged.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 22:15:02 +00:00
GodopuandClaude Opus 5.5 a47a4683f3 test: review round 2 of Issue #71 (line breaks, unreadable registry, shim anchor)
- parity and create with real line breaks in the name;
- stop with malformed YAML (no DB) or a corrupt DB refuses (exit 1);
- test_layout: the shim heredoc anchor follows the { ... } > "$tmp_file"
  form (the rule it checks is unchanged);
- S11: base re-pinned to 0fc162e, which changes the shim's sanitize body.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:31:18 +00:00
GodopuandClaude Opus 5.5 8b829647f4 fix(stop): a registry that cannot be read is not "no row" (Issue #71)
load_state_json printed {} on a YAML/DB read error, so a registered
session was closed row-less (exit 0) and its stop workflow skipped.
stop now reads the registry strictly and exits 1 before any herdr call.
Pins of the shifted stop_session.sh lines updated.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:31:18 +00:00
GodopuandClaude Opus 5.5 0fc162e8cd fix(lib.sh): line breaks in a name become '-' like Python's; load_state_json strict (Issue #71)
- The ASCII branch of _sanitize_herdr_agent_name translates line breaks
  before sed (line by line) and $(...) (drops a trailing one) can lose
  them: "newline-creator-claude\n" was started as newline-creator-claude
  while its attach_command named newline-creator-claude-.
- `load_state_json strict` exits 1 (stderr) when the YAML or DB cannot be
  read instead of printing {}; without the argument nothing changes.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:31:10 +00:00
GodopuandClaude Opus 5.5 a6fb39ba9f test: review round 1 of Issue #71 (names, row-less stop server, migration retry)
- create with a non-ASCII name: the attach target is the name herdr has;
  bash/Python parity for non-ASCII and option-like names; no python3 is
  an error for a non-ASCII name.
- row-less stop without --herdr-session uses HERDR_SESSION_NAME; an
  unreadable row is not taken for no row.
- a retry (entry point, or any write) repairs a YAML a failed migration
  left in format 1.
- tier3: the "cannot infer agent" case registers its row, as tier1 does.
- S11: base re-pinned to 5cd72d2, which changes the shim's sanitize body.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:35:58 +00:00
GodopuandClaude Opus 5.5 9410913da9 docs(stop): exit 1 also covers a row that could not be read (Issue #71)
Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:35:58 +00:00
GodopuandClaude Opus 5.5 bd61ef532f refactor(stall_watch): HerdrSource needs the herdr name, no fallback to the original (Issue #71)
Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:00:25 +00:00
GodopuandClaude Opus 5.5 015075077c fix(registry): a write repairs a YAML that a failed migration left in format 1 (Issue #71)
The writer commits the migrated DB before it replaces the YAML. If that
replacement failed, the DB said format 2 and the next run did nothing.
When the DB is current the writer now also reads the YAML's format and
rewrites a YAML that is older or missing.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:00:25 +00:00
GodopuandClaude Opus 5.5 263a72483a fix(stop): a row-less stop uses the environment's server; only "no row" is row-less (Issue #71)
With no --herdr-session the server is chosen as create_session.sh chose
it (HERDR_SESSION_NAME, else the workspace's), not always derived from
the workspace. The row-less path runs only when the lookup says the row
is missing (exit 7); any other lookup failure stops with exit 1 as
before. Pins of the shifted stop_session.sh lines updated.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:00:25 +00:00
GodopuandClaude Opus 5.5 5cd72d2df3 fix(lib.sh): the herdr name of a non-ASCII or option-like name equals Python's (Issue #71)
tr/sed lowercase differently from str.lower() outside ASCII, so a name
like "İstanbul-creator-claude" was started as x--stanbul-... while the
row's attach_command named i-stanbul-.... A non-ASCII name is now
lowercased and replaced by python3 (fail closed without it), and the
name is read with printf, not echo ("-n" no longer vanishes).

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:00:17 +00:00
GodopuandClaude Opus 5.5 e4c7c8fe9b fix: attach_command from one builder; no kill/start_command; stop closes a row-less session (Issue #71)
- attach_command is `herdr --session <server> agent attach <herdr name>`
  (`default` written too), built by lib_py.agents.sanitize.attach_command;
  create, resume and reconcile all use it. kill_command and start_command
  are no longer written, and status --json drops start_command.
- The two raw kill-session hints (create exit 43, id_order's orphan) print a
  stop-skill command with --herdr-session instead.
- stop_session.sh closes a session that has no registry row, herdr only and
  without --agent, when herdr runs it inside this workspace; another
  workspace's session is refused (exit 5), a missing one is exit 1, one that
  survives kill-session is exit 6. The registry is not changed.
- Docs: only the SKILL.md lines these changes made wrong; the skill block
  pins follow. Tests that asserted the removed fields keep their intent
  (issue50: create's own row; issue21: no control-root path in
  attach_command; tier2: the new form and the absent fields). S11 pins the
  shim to 4243da5, which changed it on purpose.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:16:53 +00:00
GodopuandClaude Opus 5.5 9c21fa4e4f feat(registry): format version 2, migrated by the writer (Issue #71)
- lib_py/registry_format.py: a pure, idempotent migrate() drops
  kill_command/start_command and rebuilds attach_command on every row
  (stopped/terminated included) and sets the top-level registry_format key.
- atomic_dump_yaml migrates an older registry under its lock, before the
  caller's mutation, and then rewrites the YAML as well as the DB (the YAML
  write is otherwise skipped when only fields change). load_state_json stays
  read-only. New registries are written with the current version.
- Entry point for #72: `python -m lib_py.registry_format --yaml <path>` runs
  the migration through the writer and prints
  `registry-format: <from> -> <to>, rows changed: <n>`.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:16:46 +00:00
GodopuandClaude Opus 5.5 50e2998a20 refactor(stall_watch): work out the herdr name once, in StallWatch (Issue #71)
StallWatch converts --target once and hands the name to HerdrSource, so
agent get/read/prompt and agent wait cannot call herdr by different names.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:16:41 +00:00
GodopuandClaude Opus 5.5 4243da507c fix(lib.sh): one herdr name rule; the shim's agent attach resolves its target (Issue #71)
- One _sanitize_herdr_agent_name: the shim gets lib.sh's definition through
  `declare -f` instead of a second copy. Without shasum/sha1sum/openssl it
  hashes with python3 (same result as lib_py.agents.sanitize); with none of
  them it fails instead of truncating or appending 00000000.
- Every caller stops on that failure: new-session before any pane is made,
  the lookups report failure, and has-session takes the name lib.sh computed
  (the cwd-relative import and its lower()[:32] fallback are gone).
- `herdr agent attach <name>` through the shim resolves the target like
  get/read/prompt; options after the target are kept.

Refs #71

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:16:20 +00:00
Godopu 29cc4fd904 merge: fix/issue-66 (stall_watch calls herdr with the sanitized agent name; v4.10.1) 2026-10-25 05:07:20 +00:00
GodopuandClaude Opus 5.5 04e32212f7 release(v4.10.1): stall_watch calls herdr with the sanitized agent name (Issue #66) - archive the review reports, bump the lockstep version
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-25 14:07:15 +09:00
GodopuandClaude Opus 5.5 bb496fde78 fix(stall_watch): call herdr with the sanitized agent name (Issue #66)
herdr registers an agent under sanitize_herdr_agent_name(session), so a
session name over 32 characters or with upper-case letters got
agent_not_found and stall detection went off. stall_watch now converts the
name for every herdr call (agent get/read/prompt, watcher.wait_once); logs
and notices keep the original name, and the agent kind is still read off
the original suffix (a long name's sanitized form ends in a hash).

The conftest mock herdr gets an opt-in strict_agent_names mode that, like
the real herdr, answers an agent only under its registered name and fails
get/read with agent_not_found JSON; existing tests see no change.

Refs #66

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 13:47:54 +00:00
Godopu 0461a632eb merge: fix/issue-63 (same-type agents in one cwd never take each other's conversation id; v4.10.0) 2026-10-23 06:46:12 +00:00
GodopuandClaude Opus 5.5 0454fe968b release(v4.10.0): same-type agents in one cwd never take each other's conversation id; same-cwd creation order (Issue #63) - archive the review reports, bump the lockstep version
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-23 15:46:08 +09:00
GodopuandClaude Opus 5.5 1614af5b67 fix(id_order): a dead-owner marker on the caller's own session follows the orphan rules (Issue #63)
A marker left on the invoking session name by a killed create/resume was
pruned before herdr was asked, so a retry under the same name took it over
while the orphaned pane was still alive (and create's failure cleanup could
then kill it). It is now kept and blocks like any other orphan until its
row is registered for the attempt or herdr reports the session gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 11:47:04 +09:00
GodopuandClaude Opus 5.5 7cac6f613e fix(id_order): server_not_running is unknown and cap 0 asks no herdr (Issue #63)
PR #69 review round 3 (rebuttal overruled; codex r2 applied as written).

- A failed `agent list`, herdr's server_not_running included, is unknown and
  keeps an orphaned marker; only a successful list without the name prunes.
- No probe floor: probes get only the time left until the wait deadline, so
  MAM_ID_ORDER_WAIT_S=0 asks herdr nothing (unknown, kept) and the refusal
  says so.
- The timeout message reports the last definite answer of this wait, so an
  alive orphan whose final probe ran out of time still reads as alive.
- Tests follow: server_not_running and cap 0 keep the marker and refuse;
  delayed-probe bound is the cap itself; probing tests use a small cap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 10:24:39 +09:00
GodopuandClaude Opus 5.5 8f64174b6b fix(id_order): prune an orphaned marker only on an authoritative "gone", within the wait cap (Issue #63)
PR #69 review round 2.

- The herdr probe is tri-state (present / absent / unknown) from a parsed
  `_herdr agent list`: absent only when the list parses without the name or
  herdr answers server_not_running. A failed, unparseable or timed-out lookup
  is unknown and keeps the marker (codex P1: has-session's exit 1 meant both
  "absent" and "lookup failed").
- Probes run with MAM_NO_AUTOSTART=1 so a check never starts a server (agy P2).
- Probe time is capped by max(deadline, start + PROBE_FLOOR_S=2 s), shared by
  all markers, so a slow herdr cannot hold the wait or its lock past the cap
  (codex P2); MAM_ID_ORDER_WAIT_S=0 still gets one bounded look.
- Tests: unknown probe keeps and refuses; delayed probe at caps 0/1/3 stays
  within the bound; real probe via lib.sh mam_id_order_wait against mock herdr
  (listed / unlisted / failing list / server_not_running).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 10:07:54 +09:00
GodopuandClaude Opus 5.5 ede9c62be3 fix(id_order): keep an orphaned marker blocking while its herdr session is alive (Issue #63)
A create/resume killed after spawning its pane but before registering its
row left a marker whose owner pid was dead; the next same-cwd waiter pruned
it on the pid alone and could start a second session that discovers the
same workspace conversation id (PR #69 review P1).

- Markers record the herdr server. A dead owner's marker is pruned only once
  its row is registered for the attempt (running, newer epoch: the row
  decides) or `_herdr has-session` reports the session gone; an unanswered
  probe counts as alive. On timeout the kill-session command is printed.
- A live marker of another process for the waiter's own session name is kept
  and blocks instead of being deleted; the waiter's own pid's markers go.
- Tests: orphan / registered / gone / same-session / missing pane pid cases,
  and a create-level reproduction against mock herdr (fails before the fix).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-23 07:39:43 +09:00
GodopuandClaude Opus 5.5 a907cc5294 chore(stop,resume): drop what Issue #63 left unused (Issue #63)
- workspace_uuid.py: the unused sys import.
- stop_session.sh: the orphan CAPTURE_ID and the blank padding that kept
  later line numbers; the inventory pins follow the move instead.
- lib.sh: capture_conversation_id, which nothing calls any more.
- resume SKILL.md: the flow names the session-id decision (session_ids.py),
  not resolve_session_id.sh.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-21 23:53:10 +00:00
Godopu d115bf7156 fix(id_order): reserve startup when resume resolves an unrecorded uuid (Issue #63) 2026-10-21 19:48:44 +00:00
Godopu c747374aa6 fix(session_ids,id_order): optional --session resolution, fresh-marker retention, and canonical cwd matching (Issue #63) 2026-10-21 18:24:14 +00:00
Godopu 8c9a68cf1c docs(stop,resume,create): the lines that became wrong (Issue #63) 2026-10-21 16:28:34 +00:00
Godopu e594d2b650 feat(create,resume): same-cwd ordering of post-discovered agents (Issue #63) 2026-10-21 16:28:34 +00:00
Godopu fa93cc5622 fix(resume): no guess with two same-type rows in a cwd; refuse another row's id before spawning; the running branch uses the same decision (Issue #63) 2026-10-21 16:28:34 +00:00
Godopu 3a2219454e fix(stop): record and purge only the row's own or a verified id; a dead herdr records none (Issue #63) 2026-10-21 16:28:34 +00:00
Godopu b8a30d5b93 feat(agents): session_ids - the stop/purge/resume id decision (Issue #63) 2026-10-21 16:28:34 +00:00
Godopu ead490bddc refactor(workspace_uuid): find_workspace_uuid() returns the id and skips exclude_ids; main prints it (Issue #63) 2026-10-21 16:28:34 +00:00
Godopu dc886ecd6b merge: fix/issue-40-auto-pin (the side that verifies a completed pins post-discovered session ids; v4.9.9) 2026-10-20 17:12:55 +00:00
GodopuandClaude Opus 5.5 0d5f10a546 release(v4.9.9): the side that verifies a completed pins post-discovered session ids; agy never takes another workspace's conversation (Issue #40) - archive the review reports, bump the lockstep version
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-21 02:12:38 +09:00
GodopuandClaude Opus 5.5 84af709bb3 test(issue42): follow the SKILL.md and reconcile.sh line moves of the Issue #40 change
The skill-block inventory recorded line numbers that the auto-pin change moved:
one create block, two monitor blocks, and the reconcile.sh evidence for the
drift A example (601 -> 593) and the status --json example (1084, past the new
end of the file -> 816).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-21 02:11:14 +09:00
GodopuandClaude Opus 5.5 feccfd5e03 fix(agents): pin post-discovered session ids on a verified completed; agy never takes another workspace's or session's conversation (Issue #40)
- BaseAgentAdapter: id_lifecycle (pre_assigned: claude, grok / post_discovered)
  and capture_active_session_id - exactly one verified candidate newer than the
  session that no other row records, else a reason (no-candidate, ambiguous, ...).
- agy: verify_artifact (discover) rejects an id last_conversations.json maps to
  another workspace and always excludes ids other rows record (a cache hit no
  longer bypasses it). capture uses the cache only as a proposal: the
  conversation's presence lock or DB must be held by the row's pane process or
  a descendant (lsof/ps); anything unprovable is not pinned.
- lib_py/agents/autopin.py: handle_completed, run by the side that verified the
  job's completed - the delegate-job wrapper (direct), create --onboard and the
  loop's wait_for_job (recovery, as a subprocess: G9). Local herdr jobs only;
  one (job, dispatch token, attempt) is handled once (job-scoped flock + marker
  in the job dir); writes go through atomic_dump_yaml; a pin records
  session_id_source=discovered / session_id_verified=true; a failure leaves the
  reason on the row and never changes the job's result.
- reconcile.sh drift C for agy, hermes, opencode and codex calls the same
  capture (the agy *.db glob is gone); _pin_and_verify_resume uses pin_row.
- Tests: tests/test_issue40_auto_pin.py; issue64 :407 now expects False; the
  static reconcile-source checks follow the move to the adapters; the two tier2
  drift-C component tests create with --no-onboard (onboarding now pins).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-20 23:40:03 +09:00
Godopu ff8b381520 merge: fix/issue-64-ro-connect (agy, codex and hermes read their databases read-only; v4.9.8) 2026-10-20 00:38:12 +00:00
GodopuandClaude Opus 5.5 38ea4f3b8e release(v4.9.8): agy, codex and hermes read their databases read-only (Issue #64) - archive the review reports, bump the lockstep version
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-20 09:37:53 +09:00
Godopu b0eccc5301 fix(agents): open agy, codex and hermes databases read-only (Issue #64) 2026-10-19 23:12:55 +09:00
Godopu 3ce5d5fdc1 merge: fix/issue-60-linux (opencode 2.x Linux follow-up; v4.9.7) 2026-10-19 03:16:21 +00:00
GodopuandClaude Opus 5.5 cffe279eb0 release(v4.9.7): opencode 2.x Linux follow-up (Issue #60, PR #62) - archive the review reports, bump the lockstep version
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-19 12:16:20 +09:00
GodopuandClaude Opus 5.5 6a37c0019b fix(opencode): Mac review of the Linux fixes - a clean db has no sidecars on Mac either, the placeholder needs its example, a home install must run, status and reconcile read the db read-only (Issue #60, PR #62)
- tests: macOS SQLite keeps -wal/-shm after the last close (persistent WAL);
  the `clean` state removes them after the checkpointing close
- the 2.x placeholder pattern requires the quoted example, so a typed
  `Ask anything…` is read as a draft
- auth_ok takes ~/.opencode/bin/opencode only as an executable file
- status.sh and reconcile.sh (drift C) open opencode.db with _ro_connect

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-19 10:57:40 +09:00
GodopuandClaude Opus 5.5 6a4e385a78 test(opencode): the narrow 2.x capture ends at its last drawn line (Issue #60, review: git diff --check)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:38:58 +00:00
GodopuandClaude Opus 5.5 d17cd80bd9 fix(opencode): the auth check is the binary, and create takes the adapter's verdict (Issue #60, Linux item 3)
opencode 2.x needs no login: a fresh HOME runs a free default model and a
local provider has no key, while 2.x keeps no auth.json. auth_ok is now
"opencode on PATH or under <HOME>/.opencode/bin". `python -m lib_py.agents
auth-ok <agent>` exits with an adapter's verdict, and create's opencode
branch uses it (same 7 lines) instead of its own auth.json/key test and
`opencode --version`, which wrote a line to the real opencode log.
test_a4's opencode block now pins the binary rule (decision D1, required
by the brief's item 3 and by both reviewers). Other agents are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:38:58 +00:00
GodopuandClaude Opus 5.5 7803d47026 fix(opencode): a -wal left without its -shm is read, not ignored (Issue #60, Linux item 5, review)
_ro_connect read every database without both sidecars as immutable, which
skips a -wal's committed rows: a recovered DB+WAL with no -shm showed no
sessions (planner-reviewer-codex-01). That state - no writer runs without
a -shm - is now read from a private DB+WAL copy, where SQLite may rebuild
the index, loaded into memory; nothing beside the source is touched. The
query matrix gains the walonly state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 13:36:41 +00:00
GodopuandClaude Opus 5.5 463817ee34 fix(stop): an unconfirmed /exit no longer claims a kill-chain fallback (Issue #60, Linux item 2)
An agent that exits on /exit never turns `working`, so send_keys_safe
returns 4 although the stop then ends cleanly. The line now says the
delivery is unconfirmed and that the stop waits for the session to exit;
the kill steps keep their own lines, printed only when they run. Exit
judgement and the kill chain are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:35:27 +00:00
GodopuandClaude Opus 5.5 614ab1420f fix(opencode): debug paths runs once per binary and home in a process (Issue #60, Linux item 6)
Every run appends a line to opencode's log, and one discover resolved the
database once per candidate. A successful answer is kept per (binary, HOME,
XDG_DATA_HOME) - the values the run sees; a failed run is not remembered.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:33:01 +00:00
GodopuandClaude Opus 5.5 ac5f1154c7 fix(opencode): queries open the database read-only without touching its sidecars (Issue #60, Linux item 5)
A read-write open checkpointed the WAL and deleted -wal/-shm on close; a
plain mode=ro open created missing ones and left them. _ro_connect uses the
sidecars only when both exist (a live writer keeps them) and reads the file
as immutable otherwise. verify_artifact, _has_session, discover,
_descendants and residual_artifacts (db_rows_naming takes a connect) use it;
the purge's own writes are unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:31:44 +00:00
GodopuandClaude Opus 5.5 14d7a46181 fix(opencode): the 2.x home placeholder is not typed input, cut example included (Issue #60, Linux item 1)
An adapter can now name its placeholder as a pattern the box's first line
matches in full (input_placeholder_pattern); input_placeholder stays the
literal lib.sh greps for. opencode: `Ask anything… "<example>"`, the closing
quote optional because a box under ~65 columns cuts the example. Fixtures:
the 140-column herdr capture and a 60-column one with the cut example.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:29:54 +00:00
GodopuandClaude Opus 5.5 4d49abb371 fix(tests): u1e hands the wrapper its own python - PATH's python3 may lack paho (Issue #60, Linux item 4)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 12:23:35 +00:00
Godopu 1d7b7dab58 merge: fix/issue-60-opencode-v2 (support opencode 2.x only; v4.9.6) 2026-10-18 10:36:17 +00:00
GodopuandClaude Opus 5.5 cb2c84ccd7 release(v4.9.6): opencode 2.x only (Issue #60) - archive the review reports, bump the lockstep version
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-18 19:35:48 +09:00
GodopuandClaude Opus 5.5 0e05b1b677 fix(opencode): tests drop XDG_DATA_HOME, status reads the adapter's db, the version probe runs in a home of its own (Issue #60, review 2)
- Review 8a485fa0 B1 / c9d06e85 / c4e96018 (blocking): the adapter now
  follows the caller's XDG_DATA_HOME for its own home, but the tests did not
  drop it: a sandbox that sets HOME resolved the runner's real data dir.
  XDG_DATA_HOME joins _agent_home_guard.DROPPED_VARS (dropped per test), and
  the session guard watches <XDG_DATA_HOME>/opencode when it is set.
  Checked with XDG_DATA_HOME set to a separate dir: the opencode modules
  pass and nothing is written there.
- status.sh asks the adapter for the db (`debug paths`, XDG-aware) instead
  of a fixed ~/.local/share/opencode (8a485fa0 N1).
- The opt-in test's `opencode --version` probe ran with the real HOME at
  import and appended to the real opencode log; it runs in a temporary home
  now (8a485fa0 N2).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-18 16:36:12 +09:00
GodopuandClaude Opus 5.5 cb5f439cce fix(opencode): a purge takes its child sessions' 1.x rows, the background service alone holds no session, XDG_DATA_HOME is followed (Issue #60, review)
- Review 614b6263 (codex, P2): `opencode session delete` removes the child
  sessions with their parent, but their 1.x rows stayed and the parent's
  residual was empty. The child sessions (session_v2 and a 1.x session
  table, any depth) are taken before the delete; the 1.x tables (message,
  part, todo, session_share, session) are cleaned for all of them, and the
  residual also reports a child still on record (a failed delete).
- The in-use check counted any process holding the shared opencode.db; the
  per-user 2.x background service (`serve --service`) holds it for every
  session, so every opencode purge was refused while it ran (it does on
  this Mac). It no longer counts; any other holder and a command line
  naming the session still do.
- The data dir follows the caller's XDG_DATA_HOME when ctx is the caller's
  own home (else <home>/.local/share), for debug paths, the fallback and the
  residual scan (review 614b6263 / f4cedbae N4).
- resident_children = ('opencode',): the --standalone server stays the TUI's
  idle child; what runs under it still counts (review 1abe0a90).
- Tests: child sessions on a migrated database, a failed delete, the service
  holder, XDG, resident children, drift C pinning the parent over a newer
  child session (review f4cedbae N2), and the real-binary test no longer
  depends on PATH (N1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-18 15:46:04 +09:00
GodopuandClaude Opus 5.5 6b4b96fa18 docs(opencode): 2.x only; the TUI takes no -m/--agent; MAM spawns --standalone (Issue #60)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-18 14:58:29 +09:00
GodopuandClaude Opus 5.5 f0d1c000f9 test(opencode): the 2.x schema and CLI, a fake opencode, and an opt-in real-binary contract (Issue #60)
tests/_fake_opencode.py implements the two commands MAM calls (debug paths,
session delete) as measured on 2.0.32; unit tests never run a real opencode
(it would migrate the test database). test_real_opencode_2x_contract runs a
real 2.x opencode, when installed, in a home and tmp dir of its own with
--standalone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-18 14:58:29 +09:00
GodopuandClaude Opus 5.5 a311c23303 fix(opencode): support opencode 2.x only - session_v2, debug paths, session delete, --standalone (Issue #60)
Measured on opencode 2.0.32 (macOS):
- the TUI rejects --agent ("Unrecognized flag"), so create and resume could
  not start opencode at all; the default agent is build. MAM now spawns
  `opencode --auto --standalone` (resume adds --session <id>): the server
  runs as the TUI's child and ends with it, and the per-user background
  service is neither used nor started;
- sessions live in session_v2 (a fresh 2.x database has no `session` table;
  a migrated one keeps the 1.x tables but no longer writes them). discover,
  verify_artifact, reconcile drift C and status read session_v2, and
  discover / drift C skip child (subagent) sessions;
- `db path` is gone (it prints the help and exits 0): the db comes from
  the `db` line of `opencode debug paths`, else the default path;
- `opencode session delete` removes a session with its child sessions from
  the 2.x tables (and leaves the 1.x ones): purge runs it with --standalone
  for a session in session_v2, still deletes the 1.x message/part/session
  rows, and residual also reports a session_v2 row left by a failed delete.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-18 14:58:29 +09:00
Godopu 74333f87d0 merge: fix/issue-31 (a claude purge removes every path the session owns; v4.9.5) 2026-10-17 16:25:20 +00:00
GodopuandClaude Opus 5.5 6fd417a7b7 release(v4.9.5): a claude purge removes every path the session owns (Issue #31, PR #59) - archive the review reports, bump the lockstep version, load logroot eagerly
Review loop (--review-only, --all-reviewer, focused on this Mac:
macOS, /usr/bin/python3 3.9.6, bash 3.2): round 1 (@6f4f40a) agy and
grok PASS, claude and codex NOT PASS (a non-uuid id `memory` purged the
auto-memory dir, a linked dir below a root was followed, a NaN
startedAt counted as dead), sent as a PR comment and fixed by the
author in eleven commits; round 2 (@2a8d738) confirmed all three fixed
but 4/4 NOT PASS on one test holder (`sh -c "sleep 120" <uuid>` loses
the uuid on macOS /bin/sh), fixed in de6f3fc; round 3 (@de6f3fc) 4/4
PASS.

Full suite on macOS / Python 3.9.6 @de6f3fc: 1934 passed, 56 skipped,
1 error (the known #55 false positive: agy conversations of another
workspace). The real ~/.claude, /private/tmp/claude-<uid> and herdr
panes unchanged.

Also names lib_py.delegation.logroot in eager.CORE_MODULES (the v4.9.4
review's non-blocking note).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-18 01:25:15 +09:00
GodopuandClaude Opus 5.5 de6f3fc81f test(issue31): the spelling test's holder keeps the uuid in its argv (Issue #31, Mac R2)
macOS /bin/sh (bash 3.2) execs the lone `sleep 120` of `sh -c "sleep 120" <uuid>`,
so the uuid left the process list and both [upper] and [mixed] failed on the Mac.
A Python holder keeps the uuid in argv, like _holder() in test_issue10_13_purge.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-17 23:54:30 +09:00
GodopuandClaude Opus 5.5 2a8d73825b test(a4): the composite purge names its claude session by a real uuid (Issue #31, review)
claude now takes only a canonical uuid (81b6c2e), so the fixture id
'uuid-c' purged nothing. The three claude spellings in
test_purge_artifacts_composite become one uuid literal; the assertions
and the other adapters' parts are unchanged. Approved by the user.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 13:43:23 +00:00
GodopuandClaude Opus 5.5 81b6c2ea6b fix(agents): only a canonical uuid reaches any claude path (Issue #31, review)
The user asked for no path at all from an id that is not a uuid. bd09c6a
still took `<id>.jsonl` for one (the pre-#31 reach), which has_artifacts and
the residual counted while in-use always said free: `purge claude notes`
deleted notes.jsonl. Now purge, has_artifacts and residual return nothing
for such an id, as in-use already did.

This makes test_a4_adapter_contract.py::test_purge_artifacts_composite fail:
it purges the claude id 'uuid-c' and expects uuid-c.jsonl gone. Editing an
existing test needs the user's approval; the one-line data change
(a canonical uuid in place of 'uuid-c') is kept outside the branch, in job
90efa4ce's report dir. Reverting this commit restores the jsonl-only reach.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 04:09:32 +00:00
GodopuandClaude Opus 5.5 dd292c12cb fix(agents): a claude leftover behind a link still selects claude for its residual (Issue #31, review)
has_artifacts counted only the paths a purge may remove. When all that was
left lay behind a linked dir, `purge claude <uuid>` (or auto) found no
adapter and exited 5 with an empty residual, hiding the path the purge
had refused to follow. has_artifacts now counts every candidate; _inside
still decides what is removed, so the CLI exits 0, removes nothing and
lists the linked path as residual.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 04:07:49 +00:00
GodopuandClaude Opus 5.5 c0248b88be fix(agents): any spelling of a claude uuid is checked as claude's lowercase id (Issue #31, review)
_is_uuid took an uppercase or mixed-case uuid, and the paths built from it
are the live lowercase session's own files on macOS's default
case-insensitive APFS. The in-use checks compare exactly, though: session
files and command lines carry the lowercase id, so `purge claude <UPPER>`
found no holder and could remove a live session's files. _canonical now
lowercases a canonical uuid, and the paths, the session-file and job
matches, the in-use check and the residual all use it; a command line is
searched for both spellings.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 04:06:37 +00:00
GodopuandClaude Opus 5.5 60779ba1f8 fix(agents): a startedAt too large for a float counts as live (Issue #31, review)
json.load reads a huge integer as an int, and math.isfinite raised
OverflowError on it outside any try: conversation_in_use and purge_artifacts
(which must never raise) threw, where 6f4f40a had taken it as live. The
conversion to float now comes first, and an overflow means live.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 04:05:13 +00:00
GodopuandClaude Opus 5.5 e156179822 fix(stop): the exit-4 refusal names where the holder may be (Issue #31, Mac review)
The refusal pointed at ~/.claude/sessions/ for every agent, whatever
CLAUDE_CONFIG_DIR said, and never mentioned a non-agent process naming the
uuid on its command line. The in-use CLI now prints, on stderr while the
conversation is in use, the adapter's in_use_hints: for every adapter
`ps -axww | grep <uuid>`, and for claude its real sessions/ dir first. stop
prints them under its refusal, and says "records preserved" instead of
"no state was modified": the gate runs after the kill chain, so the session
itself may already be down. SKILL.md's exit 4 row says the same; it is not
a code block, so no inventory hash moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 03:25:10 +00:00
GodopuandClaude Opus 5.5 af8ed397f6 fix(agents): compare a claude process's lstart in UTC (Issue #31, Mac review)
time.mktime read ps's local lstart, which is ambiguous in the hour a DST
change repeats: the start could come out an hour off and a live holder be
taken for a reused pid (or the reverse). ps now runs with TZ=UTC0, which BSD
ps and procps both honour, and calendar.timegm reads it. No /proc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 03:23:17 +00:00
GodopuandClaude Opus 5.5 f943b0db30 fix(agents): a session file whose startedAt is no finite time is live (Issue #31, Mac review)
float("NaN") and a JSON NaN passed the old check, and every comparison with
NaN is false, so a live holder looked like a reused pid: the in-use gate let
the purge through and the session file was taken as stale. startedAt must
now be an int or float (not bool), finite and positive; anything else cannot
be told and counts as live. A dead pid is still stale whatever it says.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 03:21:50 +00:00
GodopuandClaude Opus 5.5 6e0361cf43 fix(agents): a claude purge never follows a linked dir below its root (Issue #31, Mac review)
A tmp-root entry <key> linking outside made `<key>/<uuid>` look like a plain
directory, and rmtree removed what lay behind the link; projects/<key>,
file-history/ and the other config dirs had no such check either. Each
candidate now keeps the root it was found under (config, projects or tmp),
and is purged only when every component between that root and the leaf is a
real directory and its parent resolves inside the resolved root. A root may
itself be a link (/tmp -> /private/tmp), a leaf link is still removed as the
link alone, and a candidate behind a link is reported as residual instead.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 03:20:55 +00:00
GodopuandClaude Opus 5.5 bd09c6a133 fix(agents): a claude purge takes directories only for a canonical uuid (Issue #31, Mac review)
projects/<key>/memory/ (Claude Code's auto memory) sits beside the session
dirs, and `purge claude memory` removed it whole. Only an 8-4-4-4-12 hex id
now reaches the session's directories, session files, jobs and tmp dirs. Any
other id keeps the pre-#31 reach, the `<id>.jsonl` file alone (test_a4 still
purges "uuid-c"); its residual is that file and nothing holds it in use.
The shared _plausible_id is unchanged for the other adapters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 03:19:02 +00:00
GodopuandClaude Opus 5.5 26fb1c4130 test(issue31): keep every claude tmp root candidate inside the test
The adapter's fixed /tmp fallback is now a module constant. The new tests
point it, TMPDIR, TMP and TEMP at the test's own dirs, in the test process
and (through a sitecustomize on PYTHONPATH) in every python a test starts,
so no test lists the real /tmp/claude-<uid> any more (Mac review, PR #59).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-16 03:16:36 +00:00
GodopuandClaude Opus 5.5 6f4f40a4ad test(issue31): stop purges a session kept under CLAUDE_CONFIG_DIR
End to end through stop_session.sh with CLAUDE_CONFIG_DIR alone and with a
matching CLAUDE_PROJECT_DIR; plus the DiscoveryContext default. The
config-only stop case and the default check fail on 872d5f1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:29:16 +00:00
GodopuandClaude Opus 5.5 f0af98971e fix(agents): the claude projects root follows CLAUDE_CONFIG_DIR too (Issue #31, review)
stop resolves the uuid before it purges, through lib.sh's exported
CLAUDE_PROJECT_DIR and DiscoveryContext.claude_dir, both of which defaulted
to $HOME/.claude/projects. With CLAUDE_CONFIG_DIR alone the transcript under
<cfg>/projects was not found, so stop removed the row and purged nothing.
Both defaults are now ${CLAUDE_CONFIG_DIR:-<home>/.claude}/projects; an
explicit CLAUDE_PROJECT_DIR still wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:29:16 +00:00
GodopuandClaude Opus 5.5 872d5f12fb test(issue31): CLAUDE_CONFIG_DIR and partial-failure purges
Config-only and config+project overrides: a live session is refused and a
stopped one cleaned up. A key that cannot be removed keeps its session file;
a job dir that cannot be emptied keeps state.json; both are reported and
removed on retry. 5 of these fail on 8edb8d6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:00:40 +00:00
GodopuandClaude Opus 5.5 57830cf00a docs(stop): the workflow and the state diagram say a purge removes the row (Issue #31)
SKILL.md lines 52 and 83 still said a purge leaves a `terminated` row. The
two blocks' inventory shas move with them (#42), and so does the
passthrough line of stop's heredoc SystemExit(1) (310 -> 327, after the
process gate). Line counts are unchanged, so no other block moves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:00:40 +00:00
GodopuandClaude Opus 5.5 f542596975 fix(agents): a claude purge keeps ownership evidence until last (Issue #31, review)
A session file is what ties a pid's key file to the session, and a job's
state.json what ties the job dir: removing them first left the rest
unattributable after a partial failure (residual: none, and a retry could
not find it). Keys now go before their session file, which stays while any
key does; a job dir is emptied with state.json last and kept if anything
stays. residual lists a session file's key files (masked). A startedAt of 0
or less cannot tell a reused pid and counts as live; the sessions/ listdir
no longer raises.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:00:40 +00:00
GodopuandClaude Opus 5.5 8a4f651bdf fix(agents): claude follows CLAUDE_CONFIG_DIR (Issue #31, review)
CLAUDE_CONFIG_DIR moves claude's whole config root, sessions/ included, so a
live session started under it was not seen and a stopped one left
file-history and the rest behind. The config root is now CLAUDE_CONFIG_DIR,
else <home>/.claude; the purge and residual scans look at ctx.claude_dir and
the root's own projects/, each once. The test guard drops the variable for
every test like the other agent-home variables (test_issue55 l1 requires
every *_DIR the adapters read to be accounted for).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 16:00:40 +00:00
GodopuandClaude Opus 5.5 8edb8d6f0f test(issue31): purge, residual and the stop process gate
17 of the 25 cases fail on 26e2c43; the other 8 pin invariants (other
sessions, shared files, malformed ids, a prefix-twin job dir).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:16:06 +00:00
GodopuandClaude Opus 5.5 6328e67469 docs(stop): a purge removes the row; exit 4 covers a live agent (Issue #31)
The prose said a purge leaves a `terminated` row; the code removes it, and
the monitor never marks a stopped row. The step-5 list names what a claude
purge removes. The two code blocks (lines 52, 83) still say `terminated`:
changing them changes their inventory sha, which waits for approval.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:16:06 +00:00
GodopuandClaude Opus 5.5 b3461377ae fix(agents): codex, grok and opencode report their residual (Issue #31)
Their purge is unchanged; what it leaves is now reported: codex names and
thread rows (state_*, thread_history_*; logs_* is not scanned), grok
memory-v2 observations, opencode event/todo rows. db_rows_naming opens the
DB read-only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:16:06 +00:00
GodopuandClaude Opus 5.5 ae98cf18c4 fix(stop): a purge waits for the agent process, not only the herdr session (Issue #31)
A closed herdr session is not an exited agent, and the `herdr already dead`
path ran no check at all, so stop could remove the files of a live claude
and then its row. New `python -m lib_py.agents in-use <agent> <uuid> [ws]
[--wait s]` gives the purge CLI's own verdict; stop asks it outside the
registry lock and, unless it answers free, exits 4 with nothing changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:16:06 +00:00
GodopuandClaude Opus 5.5 48cda51d85 fix(stop): a purge reports its residual like orc_onboard (Issue #31)
stop called purge_artifacts only. It now prints `WARN residual: <path>` for
each leftover or `residual: none (agent: <agent>)`, the strings orc_onboard
prints. The row is still removed and the exit stays 0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:16:06 +00:00
GodopuandClaude Opus 5.5 366da3b3d6 fix(agents): claude reports what still carries the uuid (Issue #31)
claude had no residual_artifacts, so a purge always printed `residual: none`.
It now reports names holding the uuid under ~/.claude (projects excluded),
in projects two levels deep, in the tmp roots, plus the owned jobs dir and
session files. Shared files (history.jsonl, ~/.claude.json) are not
reported: they always mention every session. scan_names goes to base.py.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:16:06 +00:00
GodopuandClaude Opus 5.5 9ccd3c1835 fix(agents): claude purge removes every path the session owns (Issue #31)
The claude purge removed only <uuid>.jsonl. It now removes everything the
session alone owns: projects/<key>/<uuid>/, file-history/<uuid>/,
session-env/<uuid>/, jobs/<uuid[:8]>/ when its state.json names the session,
a stale sessions/<pid>.json with that pid's key file (name only, never read)
and <tmp>/claude-<uid>/*/<uuid>/. An id that is empty, all dots or holds
/, .. or * builds no path. has_artifacts finds leftovers without the transcript,
and conversation_in_use also sees a live claude through sessions/<pid>.json
(a `claude -c` names no uuid on its command line); a reused pid is told
apart by ps lstart against the file's startedAt.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 15:16:06 +00:00
Godopu 26e2c43753 merge: fix/issue-57 (the audit log follows a moved registry; v4.9.4)
Closes #57. Review round 2 (@a7cb90e) 4/4 PASS; full suite on macOS / Python 3.9.6 green apart from the known #55 false positive.
2026-10-15 13:52:09 +00:00
GodopuandClaude Opus 5.5 7cf728e9f8 release(v4.9.4): the audit log follows a moved registry (Issue #57, PR #58) - archive the review reports and bump the lockstep version
Review loop (--review-only, --all-reviewer, focused on this Mac:
macOS, /usr/bin/python3 3.9.6, bash 3.2): round 1 (@63d8164) agy and
grok PASS, claude and codex NOT PASS (F1 paho via the /usr/bin/python3
fallback, F2 logs default path, R1 disk-fallback redispatch
interleaving, R2 symlinked registry), sent as a PR comment and fixed by
the author in four commits; round 2 (@a7cb90e) 4/4 PASS.

Full suite on macOS / Python 3.9.6 @a7cb90e: 1867 passed, 56 skipped,
1 error (the known #55 false positive: WAL/SHM of an agy conversation
running in another workspace). Real herdr panes and ~/.claude/projects
unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-15 22:52:04 +09:00
GodopuandClaude Fable 5.1 a7cb90e63a fix(delegation): the sibling rule pairs with the registry's real path (Issue #57, Mac R2)
A registry directory that is itself a symlink got two audit logs: submit
resolved --registry-dir with pwd -P and wrote next to the target, while logs
derived the sibling from the link path. sibling_logs_dir() now takes the
registry's realpath; an explicit DELEGATE_JOB_LOGS_DIR still wins.
Also: forwarded_keys() normalises both sides of its comparison, and the
design doc's status row lists the audit log next to the registry.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-15 00:06:30 +00:00
GodopuandClaude Fable 5.1 1c598bb546 fix(subscriber): the disk fallback re-reads the record before taking an audit status (Issue #57, Mac R1)
The record (status, token, attempt, transition_seq) was read before the
audit status.json; if A error -> redispatch (attempt 2) -> B completed
happened in between, the audit terminal was B's while the token and attempt
validated were A's, and A's caller was told "completed". The audit status
is now taken only when a fresh read of the record still shows the same
token, attempt and transition_seq; otherwise the job stays pending and the
next round reads both afresh. The no-record case is unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-15 00:04:52 +00:00
GodopuandClaude Fable 5.1 151af99765 fix(delegate-job): logs passes --registry-dir on only when given (Issue #57, Mac F2)
cmd_logs always passed the wrapper's cwd-relative default registry, so the
usual run (registry not moved, cwd not the workspace) no longer found its
jobs. Without the option registry.py's own default decides, as before:
MAM_JOBS_DIR, then WORKSPACE_ROOT, then the cwd.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-15 00:02:50 +00:00
GodopuandClaude Fable 5.1 75c004222c fix(delegation): the path rules live in a stdlib-only module; the package imports without paho (Issue #57, Mac F1)
control_plane and status.sh imported sibling_logs_dir from mqtt_common,
which imports paho at module level, so create/resume's binding and status
died on an interpreter without paho-mqtt (_delegate_py_bin's last fallback
is the PATH's python3). The registry/audit-log path rules move to
lib_py/delegation/logroot.py (standard library only) and mqtt_common
re-exports them. The package's own import chain also reached paho through
service -> publish_event -> publisher, so mqtt_common and publisher import
paho tolerantly and make_client() refuses with a clear error when a broker
is actually needed. control_plane, status.sh, lib.sh's delegate_publish_cmd
and delegate_logs_dir, and the wrapper's _logs_dir_abs import from logroot.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-15 00:02:42 +00:00
GodopuandClaude Fable 5.1 63d816468e test(issue-57): the derivable audit-log root is recorded, not forwarded
New: prefix()/CLI forward three keys for a sibling binding and four for an
explicit root; create records the sibling on the row, omits it from the
pane's --env and still pins it in the injected publish commands; the
issue's scene (a pane with WORKSPACE_ROOT and MAM_JOBS_DIR only) moves its
audit log with --registry-dir and leaves the control root alone;
worktree_prepare's pane --env carries no DELEGATE_JOB_LOGS_DIR.

The three existing four-key forwarding assertions (user-approved) compare
FORWARDED_ENV = CP_ENV[:3]; CP_ENV and the negative assertions are kept.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-14 13:11:29 +00:00
GodopuandClaude Fable 5.1 c57e7667aa fix(control-plane): forward only what the pane cannot derive - the sibling audit-log root stays on the row (Issue #57)
A worktree creator's binding always differs from its --workspace default,
so prefix() put DELEGATE_JOB_LOGS_DIR=<control root>/.mam/delegate_job_logs
into every such pane for good, and the env-first rule then kept an
experiment's --registry-dir from moving its audit log. forwarded_keys()
leaves that key out when it equals the sibling of mam_jobs_dir; a
non-sibling (explicit) root is forwarded as before. describe(), the forward
and whitespace checks and the row's four keys are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-14 13:11:29 +00:00
GodopuandClaude Fable 5.1 c982616188 fix(issue-57): review nits - a damaged audit sequence or an unresolvable log root never aborts the check
_check_disk_fallback converted transition_seq outside its try, so a
status.json whose sequence is not an integer would raise out of the
subscriber's main loop; such a status is now ignored with a warning, like a
stale one. delegate_started_recorded returned 1 before looking at the
registry's events.log when the audit-log root could not be resolved; it now
skips only the audit check.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13 12:46:50 +00:00
GodopuandClaude Fable 5.1 f299034d8d fix(subscriber): the disk fallback takes an audit status only when it is at least as new as the record
The audit mirror is written after the registry commits, so a redispatched
record (attempt 2, pending) can sit next to attempt 1's completed
status.json, and a failed mirror leaves it there. The fallback validated the
token and attempt against the record, which say nothing about the audit
status's provenance, and closed attempt 2 with attempt 1's completion
(review P1, Issue #57). A versioned record (transition_seq) now takes the
audit status only when its transition_seq is at least as new; an audit
status without a sequence cannot prove which attempt it describes and is
ignored by a versioned record. An unversioned record (never transitioned,
or MAM_ENGINE_CAS=0) and a missing record keep the old rule.

Regressions: the redispatch/flush interval, the failed-mirror leftover, the
unversioned audit status, a newer audit-only terminal, and conflict
refusals and legacy claims next to a moved registry.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13 11:47:17 +00:00
GodopuandClaude Fable 5.1 6d182b392c fix(delegation): conflict refusals and legacy claims write next to the registry too
engine._flush computed the registry's audit-log root but did not pass it to
the conflict_refused append, and _pick_pending_legacy did the same for its
status_changed append, so both landed in the workspace default when the
registry was moved and no override was set (review P2, Issue #57).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13 11:47:17 +00:00
GodopuandClaude Fable 5.1 642a53b716 docs(delegate-job): the audit log is next to the registry unless DELEGATE_JOB_LOGS_DIR moves it
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13 10:02:08 +00:00
GodopuandClaude Fable 5.1 813cfd38d1 test(issue-57): the audit log follows a moved registry
New file tests/test_issue57_logs_follow_registry.py: the resolver (L1),
registry.py (L2), the wrapper's submit/wait/logs (L3), publish_event.py
(L4), control_plane.from_env, worktree_prepare, status.sh, the comment-5
disk fallback, and the invariant that an explicit DELEGATE_JOB_LOGS_DIR
still wins. Every test ends by asserting the workspace's own
.mam/delegate_job_logs was never created.

Two existing tests gain monkeypatch.delenv("MAM_JOBS_DIR"): conftest's
autouse _isolate_mam_state_dirs gives every test a MAM_JOBS_DIR, and under
the sibling rule the WORKSPACE_ROOT/cwd fallbacks they assert would
otherwise resolve next to that registry. The order they assert (explicit
root, workspace, cwd) is unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13 10:02:08 +00:00
GodopuandClaude Fable 5.1 a159a790df fix(subscriber): disk fallback reads status.json's status, not the dict
read_logged_status() returns the status.json dict; _check_disk_fallback
compared that dict with the terminal status strings, so a terminal status
recorded only in the audit log was never recognised (Issue #57, comment 5).
The dispatch-token and attempt checks are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13 10:00:25 +00:00
GodopuandClaude Fable 5.1 cbd87734c2 fix(status): look for the audit log next to the registry
Both get_job_status implementations (JSON and text) try the
delegate_job_logs next to MAM_JOBS_DIR and the row's mam_jobs_dir after the
explicit log roots, so a job whose registry record was cleaned up still
shows its audit-only terminal status when the registry was moved.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13 09:57:42 +00:00
GodopuandClaude Fable 5.1 b7a857d12f fix(control-plane): derive the audit-log root from the registry in the binding and the shell defaults
from_env() fills delegate_job_logs_dir with the delegate_job_logs next to
the resolved mam_jobs_dir unless DELEGATE_JOB_LOGS_DIR is set, so a session
created with only MAM_JOBS_DIR moved no longer records the workspace's old
log root. worktree_prepare.sh passes DELEGATE_JOB_LOGS_DIR on only when the
caller set it. lib.sh and the delegate-job wrapper no longer carry a bash
copy of the default: delegate_publish_cmd, delegate_started_recorded and
_logs_dir_abs resolve it with get_logs_dir(<registry>), the wrapper fails
closed when it cannot, exports the resolved root to its children, prints
it as submit's last line, and logs takes --registry-dir.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13 09:57:42 +00:00
GodopuandClaude Fable 5.1 b8bed8124e fix(delegation): audit-log root follows the registry (Issue #57)
get_logs_dir(registry_dir) resolves the audit-log root as the
delegate_job_logs next to the registry in use when DELEGATE_JOB_LOGS_DIR
is not set; sibling_logs_dir() is the pure sibling rule. Every writer and
reader that knows its registry (registry, engine, publish_event, remote,
job_subscriber, reconcile.sh, the loop runner's fingerprint exclusion)
passes that root instead of falling back to the workspace default.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-13 09:55:09 +00:00
GodopuandClaude Opus 5.5 e32c957464 merge: fix/u1e-workspace-root (u1e no longer writes the checkout's .mam/shim/herdr; v4.9.3)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 12:33:10 +09:00
GodopuandClaude Opus 5.5 121eab71d4 release(v4.9.3): u1e no longer writes the checkout's .mam/shim/herdr - archive the review reports and bump the lockstep version
Review loop (--review-only, --all-reviewer): round 1 (@3a30d7d) 4/4 PASS;
each reviewer reproduced W1 failing on the pre-fix tree. Seven #50/#55 and
leak modules (112 tests) from a clean worktree left no .mam in the
checkout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 12:33:02 +09:00
GodopuandClaude Opus 5.5 3a30d7da89 fix(tests): u1e gives the wrapper its own WORKSPACE_ROOT - it wrote the checkout's .mam/shim/herdr
test_u1e_a_dry_run_record_is_not_an_open_job (PR #56) ran the delegate-job
wrapper without WORKSPACE_ROOT; the wrapper sources lib.sh, which then
defaults it to the checkout and rewrites <checkout>/.mam/shim/herdr
(found by review 38a64423). The node joins W1's list, which runs its
nodes in a copy of the checkout and fails on any .mam written there.
A scan of the #50/#55 and leak modules from a clean worktree found no
other writer.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 11:57:46 +09:00
GodopuandClaude Opus 5.5 42e2a7ea9b merge: docs/readme-refresh (README rewritten against the code, README.ko.md in step; v4.9.2)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 11:57:34 +09:00
GodopuandClaude Opus 5.5 e3bcdee834 release(v4.9.2): README rewritten against the code, README.ko.md in step - archive the review reports and bump the lockstep version
Review loop (--review-only, --all-reviewer, fact-checked against the
code): rounds 1-3 NOT PASS with factual corrections, round 4 (@62da805)
4/4 PASS. Documentation only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 11:57:33 +09:00
GodopuandClaude Opus 5.5 62da805668 docs(readme): round-3 review fixes (21063f28)
About a third of the tests use the sandbox HOME fixtures (fewer the mock
herdr); generate-env.sh creates .mam.env only when missing, --force
overwrites with a .bak.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 11:51:32 +09:00
GodopuandClaude Opus 5.5 ae2813773c docs(readme): round-2 review fixes (00aa4a4c / 09bf3e77)
- exit 5: a busy or missing target cancels the job; a superseded attempt
  leaves the record to its new owner, unchanged
- install.sh copies a legacy .env to .mam.env and keeps the original
- restore-off fallback: without tomllib the file keeps only that key
  (restore off, other settings lost, warning); restore on only when no
  file can be written
- PoC: no token only when none is passed; tests: every test gets a temp
  registry and log dir, most also the sandbox HOME and mock herdr

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 11:32:01 +09:00
GodopuandClaude Opus 5.5 423abc7844 docs(readme): review fixes (38a64423 / c5a8813c / 7d29a620) and README.ko.md in step
- install.sh: what it actually checks; it writes a starter .mam.env with
  MQTT_BROKER=localhost (broker.hivemq.com is only the unset fallback);
  install_mam.sh is a separate installer.
- Security: tokens exist only when given or when the broker has TLS or a
  username (PoC: no signature check); the remote dispatch carries the token.
- Server isolation: create defaults to a workspace-named server; the shim
  bootstraps only a named server and never when MAM_NO_AUTOSTART=1
  (status/monitor); restore-off is the normal path, with a warning fallback.
- Loop: the selected reviewers must all pass; no reviewer option means a
  creator self-review.
- Interpreter order with the PATH python3 fallback; exit 5 also covers
  target_not_found; two layers with their own registries; test isolation
  stated as sandboxes plus after-run guards; quick start uses named sessions.
- README.ko.md now mirrors README.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 11:14:31 +09:00
GodopuandClaude Opus 5.5 20b1014717 docs(readme): bring README.md up to date with v4.9.1
Rewritten against the current code: the per-workspace shim is
.mam/shim/herdr routing with --session (not /tmp/multi-agent-herdr-shim
with -L), registry writes run in the workspace .venv (no dual-interpreter
split), and the missing pieces are added - the delegation contract (ack,
heartbeat, budget, busy wait, remote transport, exit codes), the review
loop (strict verdicts, review identity, sub-jobs, report promotion),
create --onboard exits 44/45, the per-server pane claim, restore-off
servers, worktree helpers and the test isolation rules. Layout and quick
start follow the tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 10:41:54 +09:00
GodopuandClaude Opus 5.5 2ccf43911c merge: fix/test-herdr-leak (tests no longer reach a real herdr server: a *-shim ancestor hid the mock, the sandbox kept the pane's socket; v4.9.1)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 10:33:04 +09:00
GodopuandClaude Opus 5.5 50c8da8269 release(v4.9.1): tests no longer reach a real herdr server - archive the review reports and bump the lockstep version
Review loop (--review-only, --all-reviewer): round 1 (@325b056) 4/4 PASS,
round 2 (@db7f4ca, HERDR_SESSION) 4/4 PASS. Full suite at 325b056 on
macOS / Python 3.9 / bash 3.2 / herdr 0.9.3 from an agent pane:
1845 passed / 0 failed / 56 skipped (18 test_deploy_freshness skips: no
nats-docker submodule in the fresh worktree); the panes of the real
servers (default, multi-agent-mux) and ~/.claude/projects were unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 10:33:04 +09:00
GodopuandClaude Opus 5.5 db7f4cab9c test(sandbox): mam_sandbox also drops HERDR_SESSION (reviews 63919c5d / 191f0ec3, non-blocking)
The caller-server helpers read it, so tests branched on whether they ran in
an agent pane. L2 covers it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 10:01:55 +09:00
GodopuandClaude Opus 5.5 325b056057 test(issue-23): the generated-shim pin moves to the real-server leak fix (525df2b)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 09:17:57 +09:00
GodopuandClaude Opus 5.5 525df2bb58 fix(tests): tests no longer reach a real herdr server - a *-shim ancestor hid the mock, the sandbox kept the pane's socket
A suite run from an agent pane with --basetemp .../pytest-pr56-shim left
seven workspaces on that pane's real server (multi-agent-mux):
- the real-herdr resolvers (lib.sh _is_shim_path and the generated shim)
  skipped every PATH directory with "-shim" anywhere in its path, so the
  basetemp hid the mock's bin/ and the real herdr ran; only a directory
  that is itself *-shim is a wrapper now;
- mam_sandbox kept HERDR_SOCKET_PATH (and the pane/tab ids), which the real
  herdr follows over the sandbox HOME; it drops them now.

tests/test_herdr_real_server_leak.py: L1 (ancestor *-shim, both resolvers)
and L2 (pane routing dropped) fail before the fix; L1b keeps a *-shim
wrapper directory excluded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-13 09:15:22 +09:00
Godopu 8b0b4a07dc merge: fix/issue-50-55 (Issue #50 / #55: onboarding and dispatch wait by the registry, one pane claim per server, tests stay out of the real agent homes; v4.9.0)
Closes #50
Closes #55
2026-10-12 12:38:55 +00:00
GodopuandClaude Opus 5.5 ffe8665b27 release(v4.9.0): Issue #50 / #55 - archive the review reports and bump the lockstep version
Merge review on macOS (--review-only loops, --all-reviewer): round 1 at
320aa9f 4/4 NOT PASS, round 2 codex F1 (a claimed dry-run job holds its
session), round 3 4/4 PASS (discarded: the worktree changed mid-review),
round 4 at 21f0c12 claude/agy/grok PASS with codex interrupted by a stream
disconnect, round 5 codex PASS. Full suite at 21f0c12 on macOS / Python
3.9 / bash 3.2 / herdr 0.9.3: 1860 passed / 0 failed / 38 skipped; no new
entries in ~/.claude/projects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-12 21:38:50 +09:00
GodopuandClaude Opus 5.5 21f0c12b9e fix(issue-50): the monitor labels a row with the server that answered
A `default` scan runs without -L, so the shim answers it from the inherited
HERDR_SESSION_NAME; a create's reconcile --once labelled that server's panes
`default`, and since create adopts only a row of its own server (1e25cf2f
F2), parallel creates in one folder were refused (test_tier4_e2e scenario 4).
The skill-blocks data follows create_session.sh's SystemExit line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-12 10:37:50 +09:00
GodopuandClaude Opus 5.5 efd27def47 fix(issue-50): a claimed dry-run job holds its session (review 211037ab F1)
open_jobs skips a dry-run record only while it is pending: a pick-pending
claim makes it running work, which the admission must wait for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-12 10:12:05 +09:00
GodopuandClaude Opus 5.5 a9ffedac36 fix(issue-50): review findings of PR #56 on macOS
- admission: a `submit --dry-run` record is marked dry_run and is not an
  open job of its session (review 1e25cf2f F1)
- create: the monitor-row adoption requires the row's server to be the one
  this create spawned on (review 1e25cf2f F2)
- pane lock: retry only on contention (BlockingIOError); the docs say the
  flock lasts while any fd-9 holder (the claim shell and the shim) lives
  (review 66680d9d)
- tests on macOS: real-herdr box HOMEs under /tmp (sun_path is 104 bytes),
  resolved paths, the fake claude reads non-canonical input (MAX_CANON 1024)
  and the pane is read unwrapped; lock holders exec their sleep so killing
  them frees the lock; the adoption tests name the server

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-12 09:03:08 +09:00
GodopuandClaude Fable 5.1 320aa9f7a0 test(issue-50): c10 makes the same-second tie instead of timing it (reviews 98b31bb2 / 352066ec / 244b8072 F-B)
The live onboarding test asserted that the first job's wrapper registered in
the same wall-clock second as the onboarding it had just placed at a second
boundary. Process start-up has no sub-second contract, so the setup assertion
failed now and then before any dispatch behaviour was checked. The test now
stamps the onboarding record, which it owns and which nothing else depends on
yet, with the job's created_at once that record exists; the stamp is written
by atomic replace so a scanning wrapper never skips a half-written record.
The lifecycle assertions and the fixed-id tie coverage in test_u2h are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-11 12:05:19 +00:00
GodopuandClaude Fable 5.1 6c99fedf40 fix(issue-50): an injected record holds its session whatever its FIFO place; the ambient pane claim locks the caller's server (reviews 5a09a13f F-A, e8e471ff R1)
open_jobs reports a live pending record nobody signals on as `injected`:
its producer registered and injected it without a waiter (create
--onboard, a job sent by hand), so it holds the session like a running or
admitted job, and a waiter of the same second with a lower job id, or one
registered a moment earlier and still in its preflight, no longer passes
it in the FIFO. The waiter signals on its own record before its first
scan, so its record is never mistaken for one.

lib_py.pane_lock resolves the shim's ambient target (no -L,
HERDR_SESSION_NAME empty or `default`) to the server of the pane the
caller runs in - HERDR_SESSION, else HERDR_SOCKET_PATH's layout, as
lib.sh _herdr_caller_server reads them - so an ambient and a named call
into one server claim under one lock; outside a pane it stays the
default server's.

Tests: u2h (the tie, the later-registered onboarding, the signalled
control), u1/u4 labels, c10 forces the same-second registration, p1b,
s2 (real herdr: held lock stops both call forms; mixed concurrent calls
take distinct panes). Two FIFO fixtures now carry a waiter's signal.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-11 08:50:46 +00:00
GodopuandClaude Fable 5.1 d50610c1ab fix(issue-50): a waiter whose own attempt is already running answers clear, not superseded
The registry wait judged its record by one rule: not this attempt's
pending record in this session -> superseded (redispatched, moved or
closed by someone else). That also caught the record's own `started`
landing before the prompt went out - the Issue #14 registry ack winning
over an unreachable broker, as test_issue30_stall_watch_stop acknowledges
at registration - and the wrapper left on exit 5 instead of its
broker_unavailable path (rc 3).

A record that is running under this attempt's token in this session is
this attempt's own progress: the waiter answers `clear` at once, writes
no admission and starts no hold. Another token, another session or a
terminal status stay `superseded` (review 55219be1 R1 unchanged).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-11 06:28:01 +00:00
GodopuandClaude Fable 5.1 7844ae2c5f fix(create): one pane claim at a time per herdr server; a create keeps the pane the monitor registered for it
Three `create --onboard` at once into one folder (the control root, so no
control-plane prefix reaches the pane and the shim reuses an idle pane):
the shim's new-session chooses a pane - an idle one in a workspace on the
same cwd, a split, a fresh workspace's root pane - and then claims it with
`agent start`; two shims could choose the pane one of them had just made,
and the later start failed with agent_pane_busy (one create in three).

mam_herdr now runs every new-session call holding one lock per server: a
flock on fd 9, opened for the block and taken by lib_py.pane_lock, which
also bounds the wait (MAM_PANE_CLAIM_WAIT_S, default 120). It is released
with the block or with the process, however it ends. The shim heredoc is
unchanged (S11). Other servers' creates are not held.

Serialising the claims exposed a second race: a create's end-of-run
`reconcile.sh --once` adopted the pane of another create that had not yet
written its row, and that create refused its own name as already running
(exit 4). Such a row - registered by the monitor, no job, for a pane
created after this create began - is now replaced, not refused.

Tests: real herdr - shim-level and create-level three-way races into one
folder (the real herdr's pane-creating replies held back so the window is
hit on every run; both fail on the base with the orchestrator's error),
the different-folder test kept; pane_lock unit tests (per-server file,
timeout, kill -9 holder, handover, knob); the adoption rule and its three
refusals; shim contract h26 (held lock: no pane calls). The herdr box gets
a ~/.zshrc: without it every first `agent start` typed into zsh's first-run
menu and timed out at 30 s.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-11 06:05:52 +00:00
GodopuandClaude Fable 5.1 30c25f193c fix(issue-50): the waiter and its hold are pinned to one attempt and session; an unsignalled pending record lives by its ack budget (review 55219be1 R1, R2)
R1: wait-open-jobs takes --dispatch-token (the token the wrapper read for
this attempt) and keeps it, with the session it asked about, for its whole
life; every write (signal, admission, the hold's renewal) is a guarded
engine merge that re-reads the record under the registry lock and refuses
once the record is not that attempt's pending one in that session. A record
redispatched, moved or closed by someone else makes the waiter answer
`superseded`: the bash wrapper exits 5 without a close, the record is its
new owner's. hold-admission is given the waiter's pinned identity instead
of reading a token from disk, so a hold that starts late holds nothing.

R2: a pending record that never carried a waiter's signal (create --onboard
registers and injects directly and waits ack_timeout_sec for `started`) is
live for that budget from created_at, not for the 30 s signal window; the
window applies only once a dispatcher has signalled.

Tests: u1 rows for the two pending lifetimes, u3b asserts the guard, u3f/u3g/u3h
(cross-session redispatch, in-place attempt change, token changed before the
waiter started) with the real waiter subprocess, u4e/u4f (late hold, running
hold released by a redispatch), s1 pins the token argument and the no-close
branch; real herdr C10 (onboarding valid before and after 30 s blocks the
session), C11 (expired onboarding is stale), C12 (redispatched waiter leaves
its record alone, exit 5).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-11 02:58:16 +00:00
GodopuandClaude Fable 5.1 9cbe08e8de fix(issue-50): the registry wait admits one job per session and holds it (review aa1bff92 F1, F2)
F1: `clear` is now an admission persisted on the released record - a merge
through the engine whose new `guard` re-reads the session's open jobs under
the registry lock, so two waiters cannot both be admitted. It is scoped to
the attempt by the dispatch token (a redispatch voids it) and reported as
`admitted` to every other waiter, which holds the session as a running job
does, whatever its FIFO place: a lower id in the same second or a
redispatched older loop job now waits.
F2: a pending record's liveness window is the dispatcher's signal cadence
times three misses (10 s x 3 = 30 s), no longer ack_timeout_sec, which the
agent's budget takes down to 1 s. After `clear` a detached hold renews the
admitted record's signal until the record leaves pending, its attempt
changes, the wrapper is gone, or the wall clock ends.
Tests: u1 boundaries, u1d/u2e/u2f/u2g/u3d/u3e for the admission, u4c/u4d for
the hold, s1 pins --hold; real herdr: C3/C7/C8 adjusted, C9 is C8's
live-owner counterpart with short ack windows.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-11 01:29:57 +00:00
GodopuandClaude Fable 5.1 9e78ff3ba3 fix(issue-50): the loop path reads this attempt's token before it waits (review reviewer-grok-01)
The `--status pending` reset is a redispatch and issues a new dispatch
token, but the loop read `_disp_tok` only after the registry and idle waits.
A busy or idle_wait close from phase two on therefore carried the previous
phase's token and the engine refused it, leaving the record pending while
the caller saw session_busy. The read now follows the reset directly; s1
pins reset < token read < registry wait.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 18:14:48 +00:00
GodopuandClaude Fable 5.1 3705bc72a8 fix(issue-50): the loop path waits by the registry on its pending record (review F1-F3)
F1: from phase two on, the loop's `_registry_wait` ran before the record was
reset to pending, so the waiter held a terminal record: the engine refused its
dispatch_wait_at merge and other waiters never saw it in the FIFO. The wait
(and the idle wait after it) now follows the `--status pending` update; s1
pins the order and u3c shows why a terminal self record cannot signal.
F2: the real-herdr box teardown survives a hung stop/delete, kills a server
bootstrapped by a late client call, and asserts the server and HOME are gone.
F3: the delegate-job SKILL.md exit 5 row names the registry wait.
Also drops the dead loop in s1.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 17:28:09 +00:00
GodopuandClaude Fable 5.1 05bffc6475 test(issue-50): C8 registers its two jobs in different seconds
The FIFO is (created_at, job_id) at second resolution; B and C registered
within the same second once in the full suite, C sorted first by id and
cleared while B's signal was still fresh, so the stale line never printed.
C7 already keeps the 1.2 s gap; C8 now does too and asserts the order.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 17:14:14 +00:00
GodopuandClaude Fable 5.1 630f04bfdc test(issue-50): the two new knobs join the #26 table; the herdr box sweeps a late state write
MAM_ONBOARD_WAIT_S (min 1, 600) and MAM_DISPATCH_WAIT_S (min 0, 600) in
test_issue26_ints.INT_KNOBS, which pins every mam_int_knob call. The
real-herdr box's teardown removes its HOME once more after a second:
herdr writes .local/state/herdr/agent-detection a moment after the
server is gone, which left an empty /tmp/mam50-* behind.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 16:05:59 +00:00
GodopuandClaude Fable 5.1 e9efabf74b feat(issue-50): the delegate-job wrapper waits by the registry before it injects (C)
Reproduction first (herdr 0.9.3, a real claude, one-off server, job
51ccd800): after a job that left a background subagent running
(`← 1 agent` on screen for 5 min), herdr reported `working` only while
the job ran and `idle` ~10 s after `completed`; a second submit with a
20 s idle wait was injected, not cancelled. The 2026-10-04 observation
(0.9.1, 10+ min of `working`) does not reproduce on 0.9.3, so the herdr
idle wait stays and the registry wait runs before it (plan §4.3 (나)).

- lib_py/delegation/wrapper.py: `open-jobs` (diagnostic) and
  `wait-open-jobs`. An open job of the session is live when the #18
  contract says so: `running` with an event in events.log within
  idle_timeout_sec; `pending` with a dispatch signal (dispatch_wait_at,
  else created_at) within ack_timeout_sec. A dead record is reported
  (`stale open job <id> ignored (...)`) and never waited for. The waiter
  signals every 10 s by merging dispatch_wait_at into its own pending
  record through the registry's transition boundary (status untouched, no
  event), so later waiters see it alive; a waiter whose wrapper is gone
  stops and its signal goes stale (Creator's challenge, job bf8863e1).
  Release is FIFO by (created_at, job_id): `clear` when no live running
  job remains and this job is the earliest live pending one; `busy <ids>`
  at the bound min(MAM_DISPATCH_WAIT_S, remaining wall clock).
- the wrapper: _registry_wait after the preflight in both dispatch paths;
  `busy` closes the job as cancelled/session_busy (phase registry_wait),
  exit 5 - the existing contract.
- tests/test_issue50_dispatch.py: the open-job table (status x age x
  signal x spelling), FIFO and the tie, the signal as a registry merge,
  the bound, a dead wrapper, finalize-end's new phase, both call sites.
- tests/test_issue50_dispatch_herdr.py: a real herdr 0.9.3 server per
  test (short mkdtemp HOME, fake claude the server reports idle, the real
  publish path over the suite's broker): C1 wait-then-run, C2 the bound,
  C3 a dead running record, C4 the loop runner's first job behind an
  onboarding, C5 a session without a row, C7 two waiters in FIFO order
  with no cancellation, C8 a killed waiter skipped once stale; and three
  concurrent `create --onboard` / `worktree_prepare.sh --onboard` in one
  server (one server process survives the shims' concurrent bootstrap,
  so no bootstrap lock is needed).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 15:39:21 +00:00
GodopuandClaude Fable 5.1 c29c5b2142 feat(issue-50): create --onboard waits for the onboarding job to end (A)
The handshake only said the agent saw the prompt (#23). create_session.sh
now waits, after `started`, for the onboarding job to reach a terminal
status and makes that its own result, so the orchestrator learns it from
create's exit (MULTI_AGENT_RULES §6) instead of guessing from herdr's
agent_status:

- lib_py/delegation/wrapper.py: `wait-terminal` (completed|error|cancelled,
  `timeout` after --timeout, `missing` when the record is gone; stops with
  its caller via --watch-pid) and `onboard-exit` (completed 0, error or
  cancelled 44, timeout or missing 45). bash branches on the printed answer.
- lib.sh: delegate_wait_terminal / delegate_onboard_exit, thin calls.
- create_session.sh: `onboarding completed: job <id> (<n>s)` on stdout, or
  `last_visible_status: onboarding-<status>` on the row, the reason on stderr
  and `exit 44` / `exit 45` after `trap - EXIT` - the session is kept, as for
  a missing handshake. The "no started" path (error, exit 0 before) now ends
  with 44. MAM_ONBOARD_WAIT_S (default 600, floor 1) bounds the wait.
- worktree_prepare.sh: 44/45 pass through with "session and worktree kept".
- create SKILL.md exit table (44, 45) and the knob; the #42 inventory follows.
- tests/conftest.py: --onboard is the default, so ~60 sandbox create tests
  reach the new wait. The mock herdr now acts as the agent for create's
  onboarding prompt - it runs the publish commands the prompt names through
  the real publish_event.py - and MAM_ONBOARD_WAIT_S=3 caps a test that turns
  that off (MAM_MOCK_ONBOARD_HANDSHAKE=0 -> 44, `started` -> 45). The
  delegate-job wrapper's prompt has another shape and is never answered.
- tests/test_issue50_onboard.py: the decision tables, create in the sandbox
  (0 / 44 / 45, session kept, row note, trap window), the knob's integer
  rule, worktree_prepare's pass-through.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 15:39:21 +00:00
GodopuandClaude Fable 5.1 40293841e7 test(issue-55): tests no longer write into the user's real agent homes
An agent pane inherits HOME_DIR, CLAUDE_PROJECT_DIR and LOCAL_BIN from
lib.sh's exports (and the adapters read CODEX_HOME). DiscoveryContext
prefers CLAUDE_PROJECT_DIR over the home_dir a test passes and every
adapter path reads HOME_DIR before HOME, so a suite run by an agent
wrote fake conversation folders into the user's real ~/.claude/projects
(test_adapter_discover, 40 folders on 2026-10-10).

- conftest._isolate_agent_homes (autouse): drops the four pane variables
  for every test, so HOME - which the suite's tests set for an isolated
  home - governs, as in a plain shell. Dropped rather than pointed into
  tmp_path: a fixture-set HOME_DIR would shadow the 11 adapter-contract
  tests that set HOME alone, the same way the pane's value did.
- conftest.agent_home_leak_guard (session autouse) + tests/_agent_home_guard.py:
  snapshots the entry names of the real claude/agy/codex/grok/opencode/
  hermes conversation directories (as the ambient environment names them,
  recorded in pytest_configure) and fails on new ones; read-only. A claude
  folder whose name decodes (against the file system) to a real directory
  outside the temp roots is an operating agent's and is not counted.
- tests/test_issue55_agent_homes.py: the dropped-variable list is pinned
  against the env reads of lib_py/agents, lib_py/paths.py and lib.sh;
  guard unit tests; the issue's reproduction as a subprocess regression
  (on base 42e5173 it leaves <dir>/-…-test-adapter-discover0-ws/u-c1.jsonl).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-10 14:29:36 +00:00
Godopu 42e51735ba merge: test/loop-marker-tmp (tests no longer take the checkout's loop lock; v4.8.9)
4/4 PASS in the merge workspace; see VERSIONS.md v4.8.9.
2026-10-09 01:59:58 +00:00
GodopuandClaude Opus 5.5 ca688dcef4 release(v4.8.9): tests no longer take the checkout's loop lock - archive the review reports and bump the lockstep version
Merge-workspace review loop (--all-reviewer): round 1 (@a93c9bf) 4/4
PASS. Full suite at a93c9bf on macOS / Python 3.9 / herdr 0.9.3 with
WORKSPACE_ROOT set to an empty sentinel: 1752 passed / 0 failed / 38
skipped; the sentinel stayed empty, the review worktree had no .mam, and
the main checkout's shim was not touched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-09 10:59:38 +09:00
GodopuandClaude Opus 5.5 a93c9bf292 test(loop-lock): the b13 runs of the checkout's run_loop.sh take a loop lock of their own
test_b13_reexec_preserves_original_argv and test_b13_no_freeze_switch_
disables_reexec ran the checkout's run_loop.sh with --creator, which gets
past argument parsing to mam_acquire_loop_lock on the default marker,
$MAM_REAL_ROOT/.mam/loop-guard-active with MAM_REAL_ROOT = the script's own
checkout. In the main checkout that is the live loop's lock (taken and
released for a moment: a real loop refused, or the test refused); in a review
tree it left an empty .mam. Both now set MAM_LOOP_MARKER under their tmp_path.

A sweep of the 16 modules that use run_loop.sh (a per-test watcher for a new
.mam in the checkout, an empty .mam removed before each test) found only
these two; the others pin MAM_LOOP_MARKER already, end before the lock
(--help, argument errors), or run a copy of the tree.

Tests: test_loop_marker_isolation.py L1 runs every test that reaches the lock
through the checkout's run_loop.sh in a copy of the checkout and requires no
.mam there; W1 of the Issue #17 isolation test now also requires that no .mam
exists (it only looked for files, so the empty lock directory passed it). At
97c2946 both fail.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-09 09:01:34 +09:00
Godopu 97c2946ee0 merge: test/issue17-workspace-root (Issue #17 follow-up: tests that source lib.sh no longer write into an inherited WORKSPACE_ROOT; v4.8.8)
Refs #17 (#17 stays open). 4/4 PASS in the merge workspace; see VERSIONS.md v4.8.8.
2026-10-08 20:01:25 +00:00
GodopuandClaude Opus 5.5 e0181ea9be release(v4.8.8): Issue #17 follow-up - archive the review reports and bump the lockstep version
Merge-workspace review loop (--all-reviewer): round 1 (@d198dd5) claude
agy PASS, grok codex NOT PASS (the same inherited WORKSPACE_ROOT in eleven
more modules; test_orc_onboard's import-time env); fixed in 8b47cc7.
Round 2 claude grok NOT PASS (test_o2_race_free_lock, test_o1_rebuttal
missed), agy codex PASS; fixed in ac48cb7. Round 3 (@ac48cb7) 4/4 PASS.
Full suite at ac48cb7 on macOS / Python 3.9 / herdr 0.9.3 with
WORKSPACE_ROOT set to an empty sentinel: 1751 passed / 0 failed / 38
skipped; the sentinel stayed empty and the main checkout's shim was not
touched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-09 05:01:05 +09:00
GodopuandClaude Opus 5.5 ac48cb7861 test(issue-17): test_o1_rebuttal and test_o2_race_free_lock run run_loop.sh under their own WORKSPACE_ROOT (review claude, grok)
Two modules still ran the checkout's run_loop.sh - which sources lib.sh
before it parses an option - with the process environment and no root of
their own: test_o2_race_free_lock's test_o2_12 (review claude; it was in the
sweep's list and missed in 8b47cc7) and test_o1_rebuttal's
test_v3_rebut_option_parsing_and_budget, whose calls pass no env (review
grok; outside the env-copy grep). Both now use own_workspace_root, and W1
runs one node of each: at 8b47cc7 W1 fails with the copy's .mam/shim/herdr.

A last pass over the test files that run lib.sh, run_loop.sh, the wrapper or a
skill script: every one is marked, uses mam_sandbox or pins WORKSPACE_ROOT,
or does not source lib.sh (b7 diff_collect, deploy, issue42, issue45 config,
issue5_phase0, local_mqtt).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-09 02:24:22 +09:00
GodopuandClaude Opus 5.5 8b47cc76ee test(issue-17): every test that sources lib.sh does it under its own WORKSPACE_ROOT (review grok, codex)
d198dd5 fixed one helper; the same defect was in eleven more modules
(reviews grok and codex R1/R2): their shells inherited the process
environment, so each `source lib.sh` rewrote <WORKSPACE_ROOT>/.mam/shim/herdr
- the checkout's own when the variable is unset or names this checkout (which
pytest_configure keeps), another workspace's under --noconftest.

- conftest: own_workspace_root, an opt-in fixture setting WORKSPACE_ROOT to
  <tmp_path>/.mam-test-state/workspace. Not autouse: runner.py and
  mqtt_common read WORKSPACE_ROOT in-process, and some tests unset it on
  purpose. mam_sandbox and explicit envs run later and still win.
- pytestmark usefixtures("own_workspace_root") in test_version_consistency,
  test_b19_headless_reconcile_fixes, test_b8_send_keys_verification,
  test_issue6_fail_closed, test_loop_cli, test_issue5_phase3_loop,
  test_issue5_phase4_runtime, test_o3_scoped_guard, test_issue25_plan_reuse,
  test_orc_onboard (their shells inherit os.environ, many with no env at all).
- test_orc_onboard (R2): SCRUBBED_ENV is taken at import and no longer
  carries WORKSPACE_ROOT; every call builds _scrubbed_env(root) with the root
  of the call (ws / cwd / mam_sandbox, else this test's).
- test_workspace_scope (unittest) and test_issue21_worktree_prereqs._mutate
  pin the root they already create.

Tests (test_issue17_workspace_root_isolation.py): W1 copies the checkout and
runs one test of each of those modules there with WORKSPACE_ROOT naming the
copy - the copy gets no .mam; W2 imports test_orc_onboard under a sentinel
root, then calls it under another - the sentinel stays empty. At d198dd5 both
fail (the copy gets .mam/shim/herdr; the sentinel gets it).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-09 00:22:54 +09:00
GodopuandClaude Opus 5.5 d198dd50aa test(issue-17): item-4 helpers run lib.sh in the test's own WORKSPACE_ROOT
_env kept an inherited WORKSPACE_ROOT, so every helper that sources the
wrapper (lib.sh's _init_herdr_isolation) rewrote <that workspace>/.mam/shim/
herdr - another workspace's during the PR #51 review (v4.8.7 review, claude).
Only dropping it is not enough: lib.sh then derives the checkout itself, and
conftest keeps a WORKSPACE_ROOT that names this checkout, so the run would
rewrite the checkout's own shim (the real one when this is the main
checkout). _env now sets WORKSPACE_ROOT to the test's tmp dir.

Test: with a sentinel WORKSPACE_ROOT in the environment, _run_both and a
direct _env run leave the sentinel empty and the checkout's shim untouched,
and the shell sees the tmp dir. With the old _env the sentinel gets
.mam/shim/herdr.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-08 23:10:35 +09:00
Godopu 6b00b6e06f merge: fix/issue17-followups (Issue #17 follow-ups: a failed decision ends the wrapper with 1; resume closes herdr 0.9.3's placeholder; v4.8.7)
Refs #17 (#17 stays open). 4/4 PASS in the merge workspace; see VERSIONS.md v4.8.7.
2026-10-08 02:32:57 +00:00
GodopuandClaude Opus 5.5 cd82ab6e72 release(v4.8.7): Issue #17 follow-ups - archive the review reports and bump the lockstep version
Merge-workspace review loop (--all-reviewer): round 1 (@8241bd5) claude
grok PASS, agy NOT PASS (two static wrapper-literal tests did not follow
_decided/_exit_for), codex NOT PASS (R1: a yes/no decision that could not
run read as "no"); fixed in 541c3fe and 65b78b6. Round 2 (@65b78b6) 4/4
PASS. Full suite at 65b78b6 on macOS / Python 3.9 / herdr 0.9.3: 1730
passed / 0 failed / 56 skipped; 18 of the skips were the uninitialized
nats-docker submodule in the fresh worktree, and with it
tests/test_deploy_freshness.py is 31 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-08 11:32:39 +09:00
GodopuandClaude Opus 5.5 65b78b6ec4 fix(issue-17): a failed yes/no decision is not a "no" (review codex R1)
subscriber-up and stall-watch answered only by exit code, so a call that
could not run (module error rc 1, missing interpreter 127) read as "no":
with a subscriber that had ended 0, the error path mapped 0 to completed
and the submit ended with 0; a failed stall-watch silently skipped the
watcher.

Both now take --print: the answer is printed as yes/no and the exit code
is 0 for either. The wrapper asks with --print through _decided_yes, so a
nonzero exit, no answer or anything else is _decision_failed (ERROR line,
exit 1). Without --print the rc contract is unchanged (yes 0, no 1).

Tests: subscriber-up (direct and loop/discuss call sites) and stall-watch,
each failing by traceback, rc 127 or no answer with a subscriber that
ended 0, end the submit with 1 and the ERROR line - at 8241bd5 eight of the
nine ended with 0 (the loop/no-answer one ended with 1 through the loop's
own result and failed only on the ERROR line); yes and no keep their
branches in both paths; --print unit table; the static guard forbids an
rc-read yes/no decision.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-08 09:26:41 +09:00
GodopuandClaude Opus 5.5 541c3febe8 test(issue-17): the frozen wrapper literals follow _decided/_exit_for (review agy)
a670ef5 routed the wrapper's sub-status and exit-code decisions through
_decided / _exit_for, but test_tier1_unit G-10 and test_issue5's
test_wrapper_exit_code_mapping_literals_are_frozen still looked for the raw
`_decide sub-status "$sub_rc"` and `_decide exit-code "$job_status"`. They now
pin `_decided job_status sub-status "$sub_rc"` and `_exit_for "$job_status"`.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-08 09:26:41 +09:00
GodopuandClaude Opus 5.5 8241bd53b1 test(issue-17): the failing wait-rc test sources the wrapper in its own WORKSPACE_ROOT
Sourcing the wrapper sources lib.sh, which writes $WORKSPACE_ROOT/.mam/shim/
herdr; without WORKSPACE_ROOT that is the checkout. The new N2 wait-rc test
now runs with its tmp dir as WORKSPACE_ROOT, so the N2 tests leave the
checkout untouched. (The existing C tests in this file still write the
checkout's .mam/shim/herdr, as at 56d0bfd - not changed here.)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-08 08:14:05 +09:00
GodopuandClaude Opus 5.5 c90a0afa96 docs(issue-17): lib_int.sh runs python3 from PATH (N3)
mam_int / mam_int_knob call `python3 -I` because the file is also sourced
without lib.sh and so without $PY. The header now says so, and that without
a python3 on PATH they print nothing (rc 127). The code is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-08 08:12:44 +09:00
GodopuandClaude Opus 5.5 d6cb01987c docs(issue-17): wrapper.py imports only the stdlib, the package it runs in loads paho (N1)
"Stdlib only" is true of the module, not of how the wrapper runs it:
`python -m lib_py.delegation.wrapper` imports lib_py/delegation/__init__.py
first, which loads the service and paho-mqtt. The docstring now says so; the
wrapper's $PY already needs paho. The run path is unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-08 08:12:44 +09:00
GodopuandClaude Opus 5.5 a670ef53ee fix(issue-17): a decision the wrapper cannot make ends it with 1 (N2)
`exit "$(_decide exit-code ...)"` became `exit ""` when wrapper.py could
not answer (its module or $PY broken): rc 255 on bash 3.2. The other printed
decisions failed open in their own ways: a failed wait-rc returned "" (255),
a failed finalize-begin left finalize-end with an empty --final (argparse
rc 2), and a failed sub-status or finalize-end ended under set -e with the
interpreter's own code (1 for a traceback, 127 for one that cannot run).

Printed decisions now go through _decided <var> <subcommand>, and the
exits through _exit_for <status>: a failed call, an empty answer or a
non-numeric exit code / wait rc prints one ERROR line and exits 1. finalize-
end may legitimately answer nothing (its wrapper gone), so only its rc is
checked. The normal path is unchanged: same answers, exit codes and output.

Left as they are: subscriber-up and stall-watch are answered by rc, so a
failure reads as "no" - the subscriber is then treated as dead (the error
path, whose sub-status/exit-code are now fail-closed) and the notify-only
stall watcher is not started.

Tests (F): the real submit (human job, unreachable broker, 3 s budget) with
a $PY that fails one decision - exit-code, sub-status, finalize-begin,
finalize-end; traceback, rc 127 or no answer - ends with 1 and the ERROR
line; the same run without a failure still ends with 3. cmd_wait with a
failing wait-rc ends with 1. A static guard keeps printed decisions off
raw $(...). At 56d0bfd: exit-code 255/255, finalize-begin 2/2, wait-rc
255/255, sub-status and finalize-end 127 for "gone"; the traceback and
no-answer cases there already ended with 1 (by set -e or by the empty
status mapping to 1) and fail only on the missing ERROR line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-08 08:12:16 +09:00
GodopuandClaude Opus 5.5 f19f94099f fix(issue-17): resume closes herdr 0.9.3's placeholder for a removed directory
With the cwd premise fixed, test_b still failed on herdr 0.9.3: a pane whose
saved directory is gone is restored as a placeholder - `restore_error`
"Saved directory is unavailable...", no process - and `pane process-info`
answers pane_not_found. close_restored_shells raised on it and exited 1
before looking at the other panes, so the resumed session's removed-worktree
pane (the case #45 closes on herdr 0.9.1, where it is a shell in $HOME) was
left behind.

Such a pane has nothing running, so it now meets condition 4. Only that
exact answer counts - restore_error set AND pane_not_found; any other
process-info failure still stops the run with exit 1 as before.

Tests: test_issue45_restore.py passes on herdr 0.9.3 (5/5). Unit tests with a
stub herdr: the placeholder is closed (fails at 56d0bfd); pane_not_found
without restore_error, or restore_error with another error, still raises.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-08 07:53:58 +09:00
GodopuandClaude Opus 5.5 25c99704f2 test(issue-17): herdr 0.9.3 keeps a removed directory as the restored pane's cwd
test_b_only_the_resumed_sessions_restored_shell_is_closed asserted that a
pane whose directory was removed comes back in $HOME. That is herdr 0.9.1;
herdr 0.9.3 keeps the old path. The cwd check now takes either, with a note
on which version does what; closing never looked at the cwd.
herdr_restore.py's docstring said the same "$HOME when that directory is
gone" and now names both versions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-08 07:52:40 +09:00
Godopu 56d0bfda54 merge: refactor/issue-17-item4 (Issue #17 item 4: the delegate-job wrapper's decisions move to Python; v4.8.6)
Refs #17 (item 4 only; #17 stays open). 4 reviewers in the merge workspace; see VERSIONS.md v4.8.6.
2026-10-07 16:37:53 +00:00
GodopuandClaude Opus 5.5 8fde39be33 release(v4.8.6): Issue #17 item 4 - archive PR #51 reviews and bump the lockstep version
Merge-workspace review: round 1 (@518beda) claude agy grok PASS, codex
NOT PASS (finalize wait measured on the wall clock); fixed in 4c86107.
Round 2 delta (@4c86107) claude agy grok PASS; codex (24b21b9c, after
817d1650 closed deadline_timeout with no report) found R1 closed and no
new defect, but withheld PASS only because its sandbox could not bind
the suite's loopback broker. The same two-file suite run here at
4c86107: 278 passed. Full suite at 518beda on macOS / Python 3.9:
1711 passed / 1 failed / 38 skipped; the failure
(test_issue45_restore, herdr 0.9.3 cwd restore) also fails on main.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-08 01:37:48 +09:00
GodopuandClaude Opus 5.5 4c86107846 fix(issue-17): review R1 - a finalize wait is measured on the monotonic clock, like bash's sleep
codex, PR #51 round 1. wrapper._sleep computed the span and the remainder
with time.time(). The broker re-observation (up to 3 s) and the disk-heartbeat
grace (1 s) use it, so a wall clock stepped back during the wait stretched it
by the step: on a mocked clock stepped back 10 s, an already completed job was
seen after 11 s / 13 s instead of 1 s / 3 s. The old bash ran `sleep 1` /
`sleep "$left"`, which do not follow the wall clock.

_sleep now measures on time.monotonic(). The deadline (START_TIME + TIMEOUT),
the evidence window and event timestamps stay on the wall clock (_now), as in
the bash.

test_u_a_wait_is_not_stretched_by_a_wall_clock_step_back (1 s, 3 s) swaps the
module's time for a clock stepped back 10 s during the first sleep; on the
previous code it measures 11.0 / 13.0 and fails. The comparison test and the
finalize-related behaviour tests (issue33, issue18, issue14) on macOS /
Python 3.9: 321 passed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-08 00:53:09 +09:00
GodopuandClaude Opus 5.5 518bedac5d fix(issue-17): review R1 round 2 - an exited, unreaped wrapper is not a live owner
kill(pid, 0) succeeds for a zombie. A caller that captures the wrapper's
output and calls communicate() after TERM leaves the wrapper unreaped while
the finalizer holds its pipes, so the owner check passed until the deadline
and the job was still closed (codex, round 2; reproduced with the real
registry). _alive now asks `ps -o stat=` (POSIX, no /proc) once kill(0)
succeeds and treats state Z as gone, as tests/conftest.py::_pid_alive does;
no ps answer keeps kill(0)'s verdict. The owner is looked at every 0.5 s.

Tests: TERM + communicate() with no wait() for both graces (stand-ins) and
for the timeout grace with the real registry, old vs new; a zombie is not
alive. All four fail on c5cebe6.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 08:09:13 +00:00
GodopuandClaude Opus 5.5 c5cebe6c32 fix(issue-17): review R1 - the finalizer ends with its wrapper
finalize-end ran the disk grace and the broker re-observation as a child
of the wrapper; TERM to the wrapper left it running, and at the deadline it
still closed the job and published the error (codex R1, reproduced with the
real registry). The bash loops it replaced ended with the wrapper.

The wrapper now passes its own pid (--watch-pid "$$", as for the stall
watcher). finalize-end checks it every 0.2 s through both waits and before
the close and the event, and leaves without either once it is gone.
A comparison test sends TERM to the old and the new wrapper inside each
grace: both exit at once, leave no process behind and make no call.

Also: no blank line at the end of the old-decisions fixture, and the #42
inventory follows main() one line down.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 07:02:26 +00:00
GodopuandClaude Opus 5.5 66d1490230 test(issue-17): item 4 - l15's stand-in control root carries lib_py/ints.py next to lib_int.sh
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 05:37:02 +00:00
GodopuandClaude Opus 5.5 6947d3c785 test(issue-17): item 4 - the #42 inventory follows runner.py's shorter header
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 05:36:48 +00:00
GodopuandClaude Opus 5.5 3b3ce307df test(issue-17): item 4 - the #42 inventory points at main() where it now is
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 05:36:23 +00:00
GodopuandClaude Opus 5.5 6bf9f92462 test(issue-17): item 4 - the frozen-mapping test imports the wrapper module directly (it has no scripts/ shim)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 05:08:35 +00:00
GodopuandClaude Opus 5.5 63d9c205ff refactor(issue-17): item 4 - the delegate-job wrapper's decisions move to Python
The wrapper keeps spawn / wait / kill, key injection and the herdr
diagnostic probe; what it decided in bash is now lib_py/delegation/wrapper.py,
reached through one `_decide` helper:

- finalize_unfinished: the clock choice, the disk grace and broker
  re-observation, the close request / label, the close and the event
  (finalize-begin / finalize-end; bash runs only the busy probe between them)
- start_stall_watch: whether to watch (MAM_STALL_WATCH, remote, human)
- _map_sub_rc, _rc_for (+ MAM_DELEGATE_FAIL_CLOSED), the subscriber
  early-exit check and cmd_wait's rc normalisation
- mam_int / mam_int_knob run lib_py/ints.py, which is also the runner's
  _positive_int: one implementation of the Issue #26 rule

No behaviour change: tests/test_issue17_item4_decisions.py runs the old
bash functions (copied verbatim from 7209750) and the new wrapper on the
same inputs and compares output, FINAL_JOB_STATUS and the registry /
publish calls. Three static tests that pinned the old bash literals now
pin the Python entry points instead.

Refs #17

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 04:59:58 +00:00
Godopu 7209750ac7 merge: fix/issue-45 (Issue #45 A+B: MAM herdr servers start with restore-on-restart off; resume closes its own restored empty shell; v4.8.5)
Closes #45. Reviewed in three rounds by claude, agy, grok and codex (4/4 PASS on ab93776); full suite 1456 passed / 0 failed.
2026-10-05 09:56:39 +00:00
GodopuandClaude Opus 5.5 bf8a583afb docs(v4.8.5): archive PR #48 reviews (three rounds) and record the merge-workspace review
PR #48 already carries the 4.8.5 lockstep bump. Merge-workspace review:
round 1 (@35935f9) claude agy grok NOT PASS (test portability: tomllib on
Python 3.9, /proc and /tmp on macOS), codex no verdict (model at capacity,
budget spent); fixed in 36f0b8d and e8d9151. Round 2 (@e8d9151) codex NOT
PASS (unrunnable config check passed an unchecked merge, odd pids closed a
pane, nan dropped the user's settings); fixed in ab93776. Round 3
(@ab93776) 4/4 PASS. Full suite at ab93776 on macOS / Python 3.9: 1456
passed / 0 failed / 38 skipped. Reports and the round-3 identity sidecars
go to .agents/reports/<session>/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-05 18:56:38 +09:00
GodopuandClaude Opus 5.5 ab93776d6d fix(issue-45): review round 2 - an unrunnable config check is not a pass, odd pids never close a pane, nan does not drop settings
codex round 2 (PR #48).

- R1: when `herdr config check` could not run (timeout, OSError), the
  merged config was handed to the server as checked. A merge with a schema
  error makes herdr drop the whole file, restore back on - the #45 failure.
  The merged body is no longer used unchecked: _write_checked falls to the
  fixed MINIMAL config with a warning. When the check cannot run on MINIMAL
  either, MINIMAL is still used (with its own warning) rather than no
  config: returning none would leave restore on, and MINIMAL is a fixed
  two-line file the real-herdr test accepts. Unknown non-zero exits stay as
  they were - herdr exits non-zero for harmless warnings (an unknown
  section) that do not drop the file.
- R2: _shell_in_foreground compared shell_pid and the foreground group with
  ==, so 0/0, False/False, ""/"" or -1/-1 closed the pane. Both must now be
  positive ints (bool excluded) before they are compared.
- R3: the re-parse check used ==, and nan != nan, so a valid TOML nan threw
  away every other user setting even on Python 3.11. _same_doc compares
  documents recursively with nan equal to nan.

Tests: R1 (timeout, OSError) and R3 (top-level, array, nested nan) in
test_issue45_herdr_config.py; R2 in the new tests/test_issue45_restore_unit.py
(a herdr stub: zero, false, empty, negative, null, string, true, float;
missing info; a real shell closed; a busy pane kept). On the previous code
12 of them fail. Python 3.11: 67 passed; Python 3.9: 33 passed / 34 skipped
(tomllib-only). Real-herdr restore tests and related files on 3.9: 197
passed / 1 skipped.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-05 17:50:15 +09:00
GodopuandClaude Opus 5.5 e8d9151226 test(issue-45): review - the real-server tests run on macOS, and the bootstrap config check follows the bootstrap's python3
claude round 1, B2 and B3 (B1 was the previous commit).

- B2, tests/test_issue45_restore.py: the throwaway root is resolved, because
  on macOS /tmp links to /private/tmp and herdr reports real paths (two B
  tests compared /tmp/... with /private/tmp/...). The server's environment
  is read from /proc on Linux and from `ps -E` elsewhere (macOS has no /proc;
  two A tests failed with FileNotFoundError).
- B3, tests/test_issue9_server_env.py: the bootstrap builds the config with
  the python3 on PATH, which here is 3.9 without tomllib, so the test's
  merged-settings expectation could not hold and its own `import tomllib`
  failed. The test now parses the result with that same python3; when it
  has no tomllib, it expects the key-only config and the bootstrap's
  "no tomllib" warning instead.

macOS, Python 3.9 venv: test_issue45_restore, test_issue9_server_env and
test_issue45_herdr_config 42 passed / 29 skipped (the tomllib-only checks).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-05 15:59:26 +09:00
GodopuandClaude Opus 5.5 36f0b8dfd6 test(issue-45): the herdr-config tests collect on Python < 3.11; the docs say what that Python loses
tests/test_issue45_herdr_config.py imported tomllib at module level. On
Python 3.9 - macOS's /usr/bin/python3, which the venvs and the bootstrap's
python3 use here - the import failed during collection and pytest ran no
test of the whole suite.

The import is optional now, and the 29 tests that parse a result with
tomllib or expect the user's settings kept are marked needs_tomllib: on
Python < 3.11 herdr_config deliberately writes the key-only config (restore
still off, the other settings dropped, a warning on stderr), which
test_without_tomllib_restore_is_still_off covers on every Python.
Python 3.9: 22 passed / 29 skipped; Python 3.11: 51 passed.

create SKILL.md (same line, so the #42 inventory is unchanged) and the
4.8.5 entry state that building the server config needs tomllib (Python
3.11+) in the python3 on PATH, and what an older python3 loses. Checked
with Python 3.9 in a throwaway HOME: the warning reaches stderr (the
bootstrap captures only stdout) and the user's file is untouched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-05 15:56:27 +09:00
GodopuandClaude Opus 5.5 35935f9e8a fix(issue-45): review round 2 R3 - the .mam fallback obeys the same no-overwrite rules
The fallback wrote <.mam>/herdr-server-config.toml unchecked, so it could
replace a foreign file there, the source itself, or a link to it. It now goes
through output_path like the normal path (source identity incl. aliases,
generated-for-this-source ownership, then a per-source name) and writes
nothing when no name is safe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 11:49:08 +00:00
GodopuandClaude Opus 5.5 7c544c06ab test(issue-45): S11 base follows the review-R1 heredoc change; VERSIONS notes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 11:18:09 +00:00
GodopuandClaude Opus 5.5 811b080966 fix(issue-45): review R1-R3 - herdr checks the config, any TOML spelling kept, source never overwritten
R1: tomllib accepting a file is not herdr accepting it (a schema error makes
herdr drop the whole file, restore included). The shim passes REAL_HERDR and
the written file must pass `herdr config check` ("parse error"/"using defaults"
reject; unknown keys and sound-file notices do not), else the key-only file is
written and checked. A non-table `session` and a source that is not UTF-8 reach
that fallback instead of raising.

R2: the line edit is replaced by parse -> set -> serialize; the result must
parse back to the source plus the key, so dotted keys and inline tables keep
the user's other settings.

R3: the output is never the source (aliases included) nor a file not generated
for the same source; then a per-source name beside it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 11:17:59 +00:00
GodopuandClaude Opus 5.5 ce91cc11b9 release(v4.8.5): bump framework and eight skills to 4.8.5 in lockstep
Issue #45 A+B: MAM's isolated herdr servers start with restore-on-restart off,
and resume closes the session's own restored empty shell. Not reviewed yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 10:53:14 +00:00
GodopuandClaude Opus 5.5 eedcebcc12 fix(issue-45): restore stays off when python3 has no tomllib
The shim runs a bare python3. Before 3.11 the module failed to import and the
server started with restore on; now it gets the key alone, with a warning.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 10:34:27 +00:00
GodopuandClaude Opus 5.5 feceddf49f docs(issue-45): isolation and resume notes; block inventory line shifts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 10:32:49 +00:00
GodopuandClaude Opus 5.5 fb1380fdc1 fix(issue-45): resume closes the session's own restored empty shell
After a restart with restore off, the session's saved pane comes back as an
empty shell (in $HOME when its directory is gone) holding the agent_session it
reported. A resume with a CP_PREFIX cannot reuse it, so it stayed next to the
new pane. Just before spawning, resume closes panes whose agent_session is the
id being resumed, with no live agent and only the shell in the foreground; the
registry is not consulted, since a session whose server died stays running.

tests/test_issue45_restore.py drives a real herdr server under a throwaway HOME
and session with a fake claude: restore stays off through the MAM bootstrap
(with a restore-on control), the close conditions, and create -> crash ->
resume leaving one pane.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 10:32:49 +00:00
GodopuandClaude Opus 5.5 933af344c2 test(issue-45): S11 compares the shim heredoc with the Issue #45 bootstrap commit
S11 keeps the generated .mam/shim/herdr from changing by accident; #45 changes
it on purpose, so its base moves to ed73f67.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 10:32:49 +00:00
GodopuandClaude Opus 5.5 ed73f67a4f fix(issue-45): the shim bootstrap starts MAM servers with restore-on-restart off
The headless bootstrap regenerates the server config on every start and hands
it to the server as HERDR_CONFIG_PATH. Without a file the server still starts,
with a warning. mam_sandbox unsets HERDR_CONFIG_PATH/XDG_CONFIG_HOME so the
file lands in the sandbox HOME.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 10:32:35 +00:00
GodopuandClaude Opus 5.5 a640b0f072 feat(issue-45): herdr config for MAM servers with restore-on-restart off
lib_py/herdr_config.py builds the user's herdr config (HERDR_CONFIG_PATH, else
XDG_CONFIG_HOME, else ~/.config, as herdr reads it) with only
[session] resume_agents_on_restore forced to false, written next to the source
so relative paths resolve the same. The text merge is re-parsed; a merge that
does not leave the rest equal falls back to the key alone, since herdr drops a
config that does not parse and would restore again.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 10:32:35 +00:00
Godopu c5c7eff6f7 merge: fix/issue-42-skills-link (.claude/skills check takes both local layouts; v4.8.4)
Reviewed in two rounds by claude, agy, grok and codex (4/4 PASS on 150b493).
2026-10-04 04:54:58 +00:00
GodopuandClaude Opus 5.5 65dc7fde82 release(v4.8.4): bump framework and eight skills to 4.8.4 in lockstep; archive PR #47 reviews (two rounds)
The .claude/skills check accepts both local layouts and fails on a dangling
link. Review: round 1 (@e1ed270) claude agy grok PASS, codex NOT PASS (a
dangling top-level link was skipped); fixed in 150b493; round 2 4/4 PASS.
Reports and the round-2 identity sidecars go to .agents/reports/<session>/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-04 13:54:57 +09:00
GodopuandClaude Opus 5.5 150b4937f8 test(issue-42): review R1 - a dangling .claude/skills link fails instead of skipping
Path.exists() follows the link, so a dangling top-level .claude/skills read
as "absent" and the test skipped: every skill's load path could be broken
with the suite still green (codex R1 on PR #47; the exists() branch predates
this PR).

The check moves into claude_skills_problems(link, skills_dir, names):
absence is "neither exists nor is a symlink"; a symlink must resolve to
.agents/skills; a directory must hold each skill resolving to the matching
.agents/skills/<skill>. test_claude_skills_layouts runs it on synthetic
layouts (absent, single link, per-skill links, a link to the wrong skill, a
dangling top-level link, a dangling per-skill link), so it is exercised in
a worktree too. Replaying the review's probe (a dangling .claude/skills in
the tree) now fails; the main checkout's per-skill layout reports nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-04 13:46:41 +09:00
GodopuandClaude Opus 5.5 e1ed2708d8 test(issue-42): the .claude/skills check accepts both local layouts
test_claude_skills_link_resolves_to_agents_skills assumed .claude/skills is
one symlink to .agents/skills. It is local and git-ignored, and a checkout
may instead hold a directory with one link per skill (this workspace's
layout), where every link is correct but the test failed. PR #46's reviews
and suites ran in worktrees, where the directory is absent and the test
skips, so the failure only showed in the main checkout after the merge.

The test now accepts a single link to .agents/skills, or a directory whose
entry for each of the eight skills resolves to the matching
.agents/skills/<skill>. Checked against no link (skip), per-skill links
(pass; the old test fails), one link pointing at the wrong skill (fail) and
a single link (pass).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-04 08:38:01 +09:00
Godopu 6af4a796b1 merge: fix/issue-42 (Issue #42 stages 1-2: SKILL.md code-block inventory, duplicate blocks removed; v4.8.3)
Refs #42 (stages 1-2). Reviewed in two rounds by claude, agy, grok and codex (4/4 PASS on 17eba09); full suite 1408 passed / 0 failed.
2026-10-03 23:36:27 +00:00
GodopuandClaude Opus 5.5 44999ff2fb release(v4.8.3): bump framework and eight skills to 4.8.3 in lockstep; archive PR #46 reviews (two rounds)
Issue #42 stages 1-2: the SKILL.md code-block inventory as test data and
the removal of blocks the entry scripts already do. Merge-workspace review:
round 1 (@8d26106) claude agy grok PASS, codex NOT PASS (R1-R3); fixed in
17eba09 (docs, inventory data and the guard test only); round 2 4/4 PASS.
Full suite at 8d26106 1408 passed / 0 failed. Reports and the round-2
identity sidecars go to .agents/reports/<session>/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-04 08:36:15 +09:00
GodopuandClaude Opus 5.5 17eba0904e docs(issue-42): review - attach names the herdr server, --dry-run is not "write nothing", a deleted block stays deleted
Merge-workspace review of PR #46 (codex R1-R3 and C1, claude O1 and O4).

- R1: resume never attaches, and the server it exports does not reach the
  calling shell; the native herdr binary does not route on environment
  variables. The attach advice and the Verification block now name the
  server: `herdr --session <server> agent attach <name>`, with <server> the
  row's herdr_session.
- R2: --dry-run in resume and create skips the spawn and the registry
  update, but the checks before it still run and on macOS remove the
  quarantine attribute from the agent binary. The option rows say so.
- R3: test_no_deleted_body_came_back compares every current block with the
  deleted bodies by exact sha and by a whitespace-insensitive fingerprint
  (stored as base_fingerprint), independently of the inventory, so a
  deleted block cannot return by being listed again under class c.
  Replaying the review's probe (the deleted resume Workflow re-added and
  inventoried as c) fails the new test and passes the old one.
- C1 / O1: the base create call block at 263-266 (class c) folded into the
  Workflow call is recorded under "superseded"; the 37 base blocks are all
  accounted for.
- O4: create exit 42 also covers MAM_KILL_ON_READY_TIMEOUT=1; stop's no-op
  exit 0 does not apply with --purge-conversation.
- The inventory's positions and shas are regenerated for the edited blocks;
  every classification is unchanged.

No product code changed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-04 08:06:32 +09:00
GodopuandClaude Opus 5.5 8d26106195 test(issue-42): review R2 - a passthrough code must be in the exit table
raised == passthrough forced the declaration, but nothing checked the
declared code against the table: dropping create's exit 4 from both the
table and the data still passed. Assert passthrough <= table codes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 14:10:59 +00:00
GodopuandClaude Opus 5.5 e6a46cd7c4 fix(issue-42): review R1 - stop's exit 1 also comes after the stop
The registry update after the kill chain raises SystemExit(1) when the row
disappeared during the run (stop_session.sh:310), so "exit 1 changed nothing"
was false on that path. The stop table now says so, the code is declared as a
passthrough, and the test requires every integer SystemExit in an entry
script's heredocs to be declared - the check that would have caught it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 13:56:36 +00:00
GodopuandClaude Opus 5.5 7670b41afd docs(issue-42): stages 1-2 - SKILL.md code-block inventory as test data; remove blocks the scripts already do
Stage 1: tests/data/skill_code_blocks.json lists all 37 fenced blocks of the
eight SKILL.md files at base 45d1621 (indented fences count), classed (a)
duplicate of a script, (b) procedure no script offers, (c) example/call/
diagram, with script file:line evidence and recorded mismatches.
tests/test_issue42_skill_blocks.py fails when a block changes without the
inventory, an (a) block comes back, a removed block's entry call is missing,
an exit-code table drifts from the script, or evidence points nowhere.

Stage 2: the five (a) blocks are gone - resume Workflow, stop pre-flight,
create pre-flight / Workflow / manual YAML append - replaced by the
entry-point call with option and exit-code tables. Each exit table has a
catch-all row: under set -e a failing sub-step's code passes through.
create's exit 4 is real (the YAML write raises SystemExit(4) for a duplicate
running row) and is listed as such. Doc-to-script mismatches are fixed in the
doc (resume Case 3 / no attach, stop --purge-conversation --yes, status
--json keys, create cmd_full and the nonexistent yaml-edit script). No
behaviour change, no version bump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-03 13:42:08 +00:00
Godopu 45d1621c93 merge: fix/followups-41-43 (PR #41/#43 review follow-ups; v4.8.2)
Reviewed in two rounds by claude, agy, grok and codex (4/4 PASS on 75f364e); full suite 1380 passed / 0 failed.
2026-10-02 15:27:28 +00:00
GodopuandClaude Opus 5.5 3563a6fc17 release(v4.8.2): bump framework and eight skills to 4.8.2 in lockstep; archive the follow-up loop's reports
PR #41/#43 review follow-ups F1-F6, implemented by creator-claude-01 in a
loop and reviewed by claude, agy, grok and codex: round 1 (@95eabc6)
codex NOT PASS (a failed env load cached as loaded), fixed in 75f364e;
round 2 4/4 PASS. Full suite at 75f364e 1380 passed / 0 failed. Reviewer
reports (round 2 with identity sidecars) and the creator's reports go to
.agents/reports/<session>/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-03 00:27:24 +09:00
GodopuandClaude Opus 5.5 75f364e4b4 fix(followups): F2 review R1 - a failed env load is not cached as loaded
ensure_env_loaded() set _env_loaded before _load_dotenv() ran. With F2,
load_env_or_report() turns the EnvFileError into a return value, so a second
main() in the same process skipped the unreadable file and ran unconfigured
(codex R1: registry.main twice -> rc 1 then rc 0 with a job registered; a
repaired file was never read). The flag is now set only after a successful
load: a failure is retried on the next call, a success still loads once.
envfile parses the whole file before applying, so a failed load sets nothing.

MESSAGING.md: the one-line ERROR is the Python entry points'; the wrapper
adds its own "ERROR: cannot load <path>" line (codex, minor).

Test: in one process, registry.main twice on an undecodable file is rc 1
both times, prints the ERROR line twice and registers nothing; the repaired
file is applied on the next call; a later change is not re-read. At 95eabc6
it fails with rc [1, 0], one job registered and the value unset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-02 09:29:11 +09:00
GodopuandClaude Opus 5.5 95eabc693f fix(followups): F2 - job_subscriber returns the env-file failure by name
5edf913 gave job_subscriber.main a bare `return 1`; its exit codes are
returned by name (test_issue5 test_job_subscriber_cli_contract_snapshot).
The value stays 1 - what the EnvFileError traceback exited with before -
and is RC_ERROR. The wrapper reads the same file first and exits 1 itself,
so it never starts a subscriber that would report this.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-02 08:39:22 +09:00
GodopuandClaude Opus 5.5 1e92ddc563 test(followups): F6 - the wrapper vanishes inside the second wait; the <= 60 s is the herdr wait's
delegate-job SKILL.md said a watcher outlives a killed wrapper by "one
wait, <= 60 s". That bound is the herdr wait's; a wrapper that goes while a
notice is being published is noticed when that publish ends. The text now
says both (PR #41 codex round 3).

"a wrapper gone during the wait" switched alive() by call count, so the
watcher saw the wrapper gone at the next loop head and never entered the
second wait (ticks == [1] with that band). The wrapper now vanishes inside
the second herdr wait (_during_notice's in_wait hook), and the test checks
that the second wait happened and that alive() was true until then. The
same test fails when the post-wait _wrapper_gone() check is removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-02 08:23:31 +09:00
GodopuandClaude Opus 5.5 c252ac4d54 fix(followups): F5 - no test switch in the stall watcher
stall_watch read MAM_TEST_UNRELIABLE_AGENT to pretend an adapter's
agent_status was unreliable (PR #41 M7). The branch is gone. S13 now runs
the real stall_watch.main() in a process where the adapter itself reports
agent_status_reliable = False (_UNRELIABLE_MAIN), and checks the same
things as before: no idle notice or nudge, the blocked notice, and the
"idle judgement off" log line. A static check keeps MAM_TEST_ out of the
watcher (fails at 0051fd6). Without the seam S13 fails on this tree.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-02 08:23:31 +09:00
GodopuandClaude Opus 5.5 fb1b93c665 fix(followups): F4b - bash integer knobs that reach [ -ge/-le/-gt ] or sleep go through mam_int_knob
A non-numeric MAM_READY_EMPTY_GIVEUP, SKS_EMPTY_GIVEUP, SKS_IDLE_RETRIES,
SKS_IDLE_RETRY_BACKOFF_S, MAM_LOCK_STEAL_RETRIES, MAM_DIFF_MAX_BYTES,
MAM_DIFF_MAX_LINES or RECONCILE_POLL_INTERVAL was a `[` error or a sleep
error at the point of use (PR #43 review claude R3). They now go through
mam_int_knob: decimal, a warning and the default for a bad value. Minimums
are in test_issue26_ints.py INT_KNOBS: 1 for the give-up counts (0 acts as
1), the diff caps (0 truncates every diff) and the poll interval (0 is a
busy loop); 0 for the retry counts (one attempt) and the retry backoff.

SKS_QUIESCENT_INTERVAL stays raw: its default is 0.5 s and sleep's
fraction is its meaning; NOT_ARITHMETIC says so.

loop_lock.sh and diff_collect.sh also run without lib.sh (the Python runner
and the tests source them alone), so mam_int / mam_int_knob move verbatim
to lib_int.sh, which lib.sh sources and those two source when the function
is missing. remove.sh's no-manifest fallback list names the new file
(install copies every file under .agents/skills). test_issue21_loop_b l15,
which builds a control root holding only diff_collect.sh, copies it too.

Tests: the table guard now reads every shell file; scripts sourced alone
read their knobs as decimal; _pane_quiescent with SKS_EMPTY_GIVEUP=abc
gives up with a warning and no `[` error (14 of the new cases fail at
0051fd6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-02 08:23:31 +09:00
GodopuandClaude Opus 5.5 8b046390be fix(followups): F4a/F4c - the runner's wait knobs follow the integer rule; MAM_WAIT_GRACE_S documented
MAM_WAIT_GRACE_S silently fell back to 300 on anything but bare digits
(" 30 " too), MAM_CHILD_WAIT_S went through float() (abc raised ValueError,
0.5 and 1e3 were taken) and MAM_JOB_TREE_MAX through int() (abc and an
empty value raised). All three now go through runner._int_knob, which is
_positive_int's rule (PR #43 review grok): decimal, blanks around allowed,
an invalid value warns once and the default is used. Minimums:
MAM_WAIT_GRACE_S >= 0 (wait exactly the budget), MAM_CHILD_WAIT_S >= 0
(look once; test_issue34 uses 0), MAM_JOB_TREE_MAX >= 1 (a cap of 0 calls
every tree "over"; not waiting is MAM_CHILD_WAIT_S=0).

The loop SKILL.md now names MAM_WAIT_GRACE_S in the budget row and the
sub-job paragraph (PR #41 M6), with the knobs' integer rules.

Tests: RUNNER_INT_KNOBS in test_issue26_ints.py holds the minimums; the
real wait_for_descendants is driven per knob, and a static check ties the
call-site minimums to the table (15 of the new cases fail at 0051fd6; the
14 that pass are valid values whose result did not change).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-02 08:13:44 +09:00
GodopuandClaude Opus 5.5 71ea8095c5 fix(followups): F3 - .mam.env BOM, repeated keys and a missing MAM_ENV_FILE
PR #43 review (grok):
(a) A UTF-8 byte-order mark at the start of the file made the first line an
    "invalid key", so its setting was dropped. The one parser (envfile.py,
    used by the wrapper and mqtt_common) now reads with utf-8-sig.
(b) A key given twice keeps its first value (a later line does not replace
    it). The behaviour is unchanged; .mam.env.example's FORMAT section and
    envfile.py's docstring now say so.
(c) MESSAGING.md said a MAM_ENV_FILE naming no file logs an error and makes
    connections fail closed. Both loaders skip it silently and refuse the
    ambient search; a file that exists but cannot be read is the error
    (EnvFileError, one ERROR line and rc 1). The text now says that.

Tests A7: BOM in both loaders, first-value-wins in both loaders plus the
FORMAT text, and a missing explicit file loading neither it nor the ambient
.mam.env without an error plus the MESSAGING text (all three fail at 0051fd6).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-02 08:10:42 +09:00
GodopuandClaude Opus 5.5 5edf913d22 fix(followups): F2 - Python entry points report an unreadable env file in one line
A .mam.env that exists but cannot be read or decoded stopped the Python
entry points with an EnvFileError traceback, while the wrapper printed one
`ERROR:` line and exited 1 (PR #43 review claude S1). The mains that load the
env file - publish_event, registry, job_subscriber, cli, bench, heartbeat and
remote - now call mqtt_common.load_env_or_report(), which prints
`ERROR: <path>: cannot read (<exception type>)` and lets the main return 1.
No value or file content is printed. ensure_env_loaded() still raises: no
library function exits the process.

Test: every entry point, for a 000 file and an undecodable one, ends with
exactly that line and rc 1 and creates nothing (14 cases; all 14 fail at
0051fd6 with a traceback).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-02 08:09:46 +09:00
GodopuandClaude Opus 5.5 75936f11c6 test(followups): F1 - A8 writes the marker lstart as loop_lock.sh reads it
`ps -o lstart=` pads a one-digit day ("Oct  1"); loop_lock.sh's mam_lstart
squeezes the spaces before comparing, but A8 wrote the raw value, so the
live holder's marker looked stale and the second loop was not refused on
the 1st-9th of every month. The test now normalises like the product (the
product is unchanged) and also runs with a `ps` shim that always prints a
padded lstart, so the padded case is checked on every date.

The other tests that record a live lstart (test_o3_scoped_guard
_get_lstart) already normalise; test_o2's markers carry fixed stale values.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-10-02 08:08:26 +09:00
Godopu 0051fd6c3b merge: fix/issue-26 (Issue #26 one .mam.env parser, decimal integer knobs, tests on a local MQTT broker; v4.8.1)
Closes #26. Reviewed in two rounds by claude, agy, grok and codex (4/4 PASS on 0eec795).
2026-10-01 15:23:26 +00:00
GodopuandClaude Opus 5.5 2e90c809d3 release(v4.8.1): bump framework and eight skills to 4.8.1 in lockstep; archive PR #43 reviews (two rounds)
Issue #26: one .mam.env parser for the wrapper and the Python tools,
decimal integer knobs, tests on a local MQTT broker. Merge-workspace
review: round 1 (@b58edac) claude agy PASS, codex NOT PASS (R1-R4), grok
no verdict (its late report, archived as report-c9ed5b14.md, found R1 too);
round 2 (@0eec795) 4/4 PASS. Reports and round-2 identity sidecars go to
.agents/reports/<session>/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-02 00:23:22 +09:00
GodopuandClaude Opus 5.5 0eec795cd1 fix(issue-26): review - an unreadable env file is an error, NUL lines are skipped, integers are ASCII in every locale, empty flags are refused
Merge-workspace review of PR #43 (codex R1-R4, claude R1/R2).

- R1: envfile.parse raises EnvFileError when the file exists but cannot be
  read or decoded as a whole; `--shell` prints the cause and exits 1, so the
  wrapper stops (rc 1, as before #26) instead of running on defaults, and
  mqtt_common's entry points stop on the same error. A bad single line is
  still a warning. The wrapper's message no longer claims a read failure
  when the cause is elsewhere ("cannot load ... see the line above").
- R2: lib.sh mam_int spells out the ASCII blanks and digits instead of
  [[:space:]]/[0-9], which follow the locale: U+2003 30 U+2003 was 30 in the
  wrapper and invalid in the runner under en_US.UTF-8. The test oracle
  _expected uses the same ASCII rule.
- R3: an integer flag given explicitly with an empty value is refused like
  any other invalid value; only an absent flag keeps its default.
- R4: a line holding a NUL byte is skipped with a warning by both loaders;
  before, the wrapper read "leftright" and the Python loader died.
- .mam.env.example states the format: no expansion, `export` and bash's own
  variables skipped, a trailing `# ...` is part of the value, the environment
  wins, an unreadable file is an error.

Tests: unreadable (0000) and invalid-UTF-8 files stop the wrapper and the
Python loader; a NUL line is skipped by both; Unicode blanks/digits are
invalid for mam_int, _positive_int, the wrapper and the runner under C and
en_US.UTF-8; explicit empty values for the five integer flags are refused.
All of them fail on b58edac.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-10-01 22:59:57 +09:00
GodopuandClaude Opus 5.5 b58edace11 test(issue-26): C0 reads broker state only after the matching ack; the local broker acks a PUBLISH after routing it
Review (fa45b0e6): paho's connect() does not wait for the CONNACK, so C0
could read protocol_levels before the broker had handled the second
CONNECT, and the `before` slice could take in a previous test's connection.

- _Client waits for CONNACK (and UNSUBACK, instead of sleeping 0.3 s);
  C0 checks the levels of its own two client ids (stats() levels_by_client).
- The local broker now routes and stores a PUBLISH before its PUBACK, so a
  publisher holding the ack may rely on the retained state it asked for
  (late subscriber replay, retained delete).
- test_c0_holds_when_the_broker_is_slow runs C0 with CONNECT/UNSUBSCRIBE
  delayed and PUBLISH routed late; the old C0 fails it ([] == [4, 4]), as do
  an ack-before-route broker and a fixed-sleep unsubscribe.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-01 01:04:19 +00:00
GodopuandClaude Opus 5.5 fb006374d6 test(issue-26): test_bug4 checks the whole send_keys_safe body, not its first 2500 characters
34241d7 added a line near the top of send_keys_safe (SKS_QUIESCENT_TRIES
normalisation), which pushed `agent prompt` from inside the 2500-character
window to offset 2519. The order the test guards is unchanged
(_pane_quiescent < _pane_dialog_open < agent prompt); it now slices up to
the function's closing brace.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 20:13:40 +00:00
GodopuandClaude Opus 5.5 34241d7a65 fix(issue-26): review round 1 - no file key assigns bash's own variables; SKS_QUIESCENT_TRIES; long decimals
R1 (P1): a quoted export still ran code when the key was a bash special
variable (RANDOM=a[$(cmd)] is evaluated arithmetically on assignment).
envfile.RESERVED (bash's own variables, plus BASH_/COMP_/READLINE_
prefixes) is skipped with a line-numbered warning by both loaders; a test
keeps it covering every variable a clean bash defines. The wrapper also
hands SCRIPT_DIR/REPO_ROOT/TARGET_ENV to the parser as environment, so the
file cannot replace the variables it has already set.

R2 (P2): SKS_QUIESCENT_TRIES reached `for ((i < tries))` through a function
argument; it is normalised at the call site (minimum 0). B5 now requires
every integer-looking env default in the shell code to be normalised or
listed in NOT_ARITHMETIC with where it goes, and exercises _pane_quiescent.

R3 (P2): _positive_int strips leading zeros and rejects more than nine
significant digits before int(), like mam_int; 5000-digit inputs no longer
raise in the runner.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 17:39:08 +00:00
GodopuandClaude Opus 5.5 2826e709ae test(issue-26): no test depends on a third-party MQTT broker
- tests/_local_mqtt.py: in-process MQTT 3.1.1 broker on 127.0.0.1 (what
  the repo uses: protocol level 4, clean session, QoS 0/1, retained).
- conftest: one session broker named by MQTT_BROKER/MQTT_PORT/MQTT_TLS;
  other redirecting/auth MQTT_* dropped and restored afterwards.
- Harnesses of the 22 broker-dependent tests (#18 acceptance1/2/3/5,
  #6 t1_1/2/7/8/14/15/16/20, #19 MQTT loop x2, #33 b3/r3/b7, #30
  s9/s10/r2) use it; the "broker unreachable" skips are gone (a local
  broker that does not deliver is a failure). acceptance1/5 and #19 also
  assert on the subscriber, runner and audit logs the real producers write.
- tests/test_local_mqtt.py: conformance with the real clients and the real
  publish_event -> job_subscriber path (C0), an AST guard against public
  broker literals and MQTT_* deleted without a replacement (C2), and the
  session's broker config (C3).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:54:58 +00:00
GodopuandClaude Opus 5.5 80dc2eb45e fix(issue-26): integer knobs that reach bash arithmetic are read as decimal
bash read MAM_JOB_TIMEOUT_S=0700 as octal 448 (and failed on 0900) while
the loop runner read 700. One rule now, with a per-knob minimum:
lib.sh mam_int / mam_int_knob and runner._positive_int (blanks allowed,
digits only, decimal, min <= n <= 999999999).

- minimum 1: MAM_JOB_TIMEOUT_S, MAM_HEARTBEAT_SEC, MAM_HEARTBEAT_MISSES,
  MAM_ACK_TIMEOUT_S (invalid env: warning + default) and the wrapper's
  --timeout/--idle-timeout/--heartbeat/--heartbeat-misses/--ack-timeout
  (invalid: rc 1); the runner's job_budget, --job-timeout, contract_args.
- minimum 0 (0 = check once): MAM_INJECT_ACK_GRACE_S,
  delegate_wait_started's ack_s, SKS_DIALOG_TIMEOUT, SKS_BUSY_TIMEOUT,
  SKS_DELIVERY_GRACE_S.
- tests/test_issue26_ints.py: INT_KNOBS is the one table of minimums; a
  static guard keeps env defaults out of arithmetic and checks each
  normalised knob against it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:47:40 +00:00
GodopuandClaude Opus 5.5 f1331d36ce fix(issue-26): the wrapper reads .mam.env through the Python loader's parser, never source
- lib_py/delegation/envfile.py (stdlib only) holds the one set of rules:
  comments and blank lines skipped, key and value stripped, one matching
  quote pair removed, no shell interpretation, keys must match
  ^[A-Za-z_][A-Za-z0-9_]*$ (bad or `=`-less lines warn with the line
  number, never the value).
- mqtt_common._parse_env_file delegates to envfile.apply.
- The delegate-job wrapper runs envfile.py --shell by path and evals the
  shlex-quoted exports; values never reach a command line. The environment
  now wins over the file in both loaders.
- .mam.env.example: commented assignments no longer use $HOME, which the
  parser keeps literally.

The shell parsed the env file in one place only (wrapper :38), not three.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 15:47:40 +00:00
Godopu e1eb22bd59 merge: fix/issue-30-33 (Issue #33 budget + wall_clock_timeout, Issue #30 notify-only stall watcher; v4.8.0)
Closes #30 #33. Reviewed in three rounds by claude, agy, grok and codex (4/4 PASS on 9200562); release 53f87e4.
2026-09-26 07:08:46 +00:00
GodopuandClaude Opus 5.5 53f87e4560 release(v4.8.0): bump framework and eight skills to 4.8.0 in lockstep; archive PR #41 reviews (three rounds)
Issue #33 (job budget, wall_clock_timeout vs deadline_timeout) and
Issue #30 (notify-only stall watcher). Reviews of PR #41 in the merge
workspace: round 1 (@1673818) claude N1 / codex R1 R2 NOT PASS, agy grok
PASS; round 2 (@af0a2a2) grok N1 / codex D1 D2 NOT PASS, claude agy PASS;
round 3 (@9200562) 4/4 PASS. Reports and the round-3 identity sidecars go
to .agents/reports/<session>/. The design consensus on items A-D is in the
VERSIONS.md entry.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-26 16:08:37 +09:00
GodopuandClaude Opus 5.5 9200562c91 fix(issue-30): review round 2 - the watcher is stopped with KILL, and a strict last gate sits between the notice and the keys
grok N1: the wrapper spent up to 5 s on a TERM budget before it finalized the
job, so when the watcher swallowed the TERM the silent job's close came ~5 s
late and a `completed` written in that gap won (test_issue14 idle-grace).
codex D1: `_notify` blocks on a publish for up to 120 s, and the prompt went
out right after it; a completed, a re-dispatch or an unreadable record in that
window still got the nudge. codex D2: the wrapper pid was checked only at the
loop head, so a watcher whose wrapper vanished during a wait could still
notify and nudge once.

- multi-agent-mux-delegate-job `stop_stall_watch`: KILL + wait, no budget.
  The watcher holds nothing to flush (its TERM handler is a bare os._exit),
  and KILL cannot be swallowed.
- lib_py/stall_watch.py: `_wrapper_gone()` after every wait (before any
  notice) and at the loop head; `_may_prompt()` right before the keys - the
  wrapper is alive and the record, read then, is open and this dispatch;
  `_dispatch_open(strict=True)` treats an unreadable record as "no".
- SKILL.md: the lifetime contract states the one-wait lag and that nothing is
  sent after the wrapper is seen gone.
- tests/test_issue30_stall_watch_stop.py: the stop returns at once against a
  TERM-ignoring stand-in (took 6 s on the round-2 code); completed,
  re-dispatch and a torn record during the notice publish withhold the nudge;
  a wrapper gone during the wait gets no notice and no nudge. All five fail
  on the round-2 code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-26 15:28:07 +09:00
GodopuandClaude Fable 5.1 af0a2a2557 fix(issue-30): review - the stall watcher's lifetime is bounded on both sides and it re-checks its dispatch before acting
Round-1 review of PR #41 (claude N1, codex R1/R2).

N1 - the wrapper stopped its stall watcher with `kill` followed by an
unbounded `wait`. A TERM that lands in the watcher's fork-exec window is
swallowed (bash defers terminating signals in the forked child until the
exec), the watcher then installs its own handler and lives until the job
closes, and the wrapper hung until someone killed the watcher by hand
(reproduced twice in test_issue14's ack test; the wrapper trace stops at
`kill` + `wait`).
R1 - a wrapper that is itself terminated left the watcher orphaned.
R2 - a `completed` or a re-dispatch that landed during a blocking herdr
wait (up to 60 s) was still followed by the idle notice and the nudge.

- multi-agent-mux-delegate-job: `stop_stall_watch` sends TERM, polls up
  to 5 s, then KILLs and reports "ignored TERM; killed"; `start_stall_watch`
  passes `--watch-pid $$`.
- lib_py/stall_watch.py: `--watch-pid` (rc 0 once that pid is gone, checked
  between herdr calls); `_dispatch_open()` re-reads the record after every
  wait and right before the nudge - terminal status, another dispatch token
  or attempt, or a missing record ends the run without a notice; a refused
  `stalled:idle` publish withholds the nudge (`_notify` returns False).
- delegate-job SKILL.md: the watcher's lifetime contract; exit-code rows 2
  and 3 name the idle clock and the wall-clock label; "before v4.7.5" ->
  v4.8.0 (M5, NB2).
- tests/test_issue30_stall_watch.py (M8): the module-wide Linux mark is
  narrowed to S6 (/proc); r4's stub stamps time.time() so its cross-process
  comparison holds on macOS too (47 passed, 1 skipped here).
- tests/test_issue30_stall_watch_stop.py (new, macOS and Linux): the stop
  routine against a TERM-ignoring stand-in returns in 4-12 s; the wrapper
  returns (rc 3) with a TERM-ignoring watcher shim; `--watch-pid` ends the
  watcher; a TERM to the real wrapper leaves no watcher; a job completed or
  re-dispatched during the wait is not nudged; a refused notice withholds
  the nudge. Every one of them hangs or fails on the round-1 code.

Not in this commit (follow-ups): M7 test hook in product code (no adapter
is unreliable, a seam is needed), M9/B3 public-broker latency (on this host
even `started` sometimes never reaches the subscriber), the leading-zero
budget parse (NB1) and M1/M2/M4/M6 go on the #17 item 4 list.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-26 13:17:24 +09:00
GodopuandClaude Opus 5.5 1673818bb5 fix(issue-33): subscriber exit codes are named on both sides; wait keeps a spent budget at rc 2; G-8 is deterministic
- job_subscriber.py returns only named codes (RC_COMPLETED 0, RC_ERROR 1,
  RC_NO_EVENT 2, RC_BROKER_UNAVAILABLE 3, RC_WALL_CLOCK 4). The wrapper
  mirrors them as SUB_RC_* and compares subscriber codes only by name; a test
  keeps the mirror equal to the Python constants and forbids numeric
  comparisons of $sub_rc/$sub_exit and numeric `return` in the subscriber.
- `delegate-job wait` passed the subscriber's code straight through, so a
  spent budget would have reached its callers as 4; it is 2 again (B7 fails
  without the mapping).
- tier1 G-8 gave both clocks 0.5 s and raced; the wall clock now runs out
  first by construction (idle 30 s) and the test asserts RC_WALL_CLOCK.
  Other subscriber rc asserts use the names.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-26 00:22:43 +00:00
GodopuandClaude Opus 5.5 9ec0569401 fix(issue-30): review ad3d8206 - a prompt glyph inside a draft is draft text; the R4 regression test tells the defect apart
- input_region: in the prompt-line shape the input box starts only at a
  column-0 prompt (codex indents a draft's continuation lines), and the
  prompt and the (whole-line) placeholder are stripped from the box's first
  non-blank line only, so `› Explain this terminal prompt:\n  ›` is not empty.
- test_r4 runs with S=40 again: the defective code nudged ~30 s after a
  missed transition, which S=10 could not tell from the fixed ~10 s.

Both new checks fail against the defective versions (stall_watch.py at
47e4274 -> 30.24 s < 40; input_region.py at bf0f5c1 -> nudge sent) and pass
now, each with its passing twin.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 16:02:39 +00:00
GodopuandClaude Opus 5.5 bf0f5c1014 fix(issue-30-33): review 5ec8ef33 - a multi-line codex draft is not an empty box, blocked notices reach the loop while the job runs, and both clocks are labelled on every close path
- R1 (P1): without rules the input region runs from the last prompt line to
  the end of the pane; only a last line matching the adapter's footer pattern
  (codex: `  <model> · ~/<cwd> · …`) is dropped, so a draft on a second line
  keeps the nudge withheld.
- R2: while the synchronous submit runs, a relay thread finds the job it
  registers (same session, created since the submit) and prints its
  stalled:/stall_watch: notices; before, they appeared only after the job.
- R3: the broker-unavailable disk wait that runs into the deadline is the wall
  clock: wall_clock_timeout (caller rc stays 3).
- R4: a state_change_seq change seen right before the judgement restarts the
  idle window (decision 9: S seconds of continuous idle).

Regression tests are the reviewer's reproductions, each with its passing
twin; the wrapper-level #30 tests now use this environment's broker instead
of the #18 harness's public default.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 14:01:53 +00:00
GodopuandClaude Opus 5.5 47e42744e7 docs(issue-30-33): table rows for --job-timeout, MAM_JOB_TIMEOUT_S, wall_clock_timeout and the stall watcher knobs
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:43:21 +00:00
GodopuandClaude Opus 5.5 622c1f8a9d feat(issue-30): a stall watcher that only notifies
lib_py/stall_watch.py runs beside the wrapper's subscriber for a local herdr
job (started after delivery, stopped when the subscriber ends; MAM_STALL_WATCH=0
turns it off). It follows `herdr agent wait` transitions and publishes only
`progress` events through one publisher; it has no path that closes a job.

- blocked: `stalled:blocked <detection line>` once per episode, never answered.
- idle for MAM_STALL_IDLE_S (600) with no background descendants of the agent
  pid (pane process-info + /proc; adapter resident_children and the heartbeat
  timer excluded) and an empty input box: `stalled:idle` and one nudge.
- input box judged from adapter facts measured on herdr 0.9.1 (codex '›',
  grok frame '│', opencode '┃' block + stop pattern); the whole-pane fallback
  is gone. No facts: withheld + `stall_watch:input_check_unavailable` once;
  never empty for 3 x S: `stall_watch:input_never_empty` once.
- herdr failures are not "no event": warning + `stall_watch:herdr_unavailable:
  <code>` (or agent_not_found), backoff, rc 2 after MAM_STALL_HERDR_FAIL_S
  (120); the wrapper prints the watcher's last lines.
- remote and human jobs are skipped with one log line.
- agent_status_reliable is an adapter field; false turns idle judgement off.
- the loop runner relays stalled:/stall_watch: notices once each.
- scoped_env drops a pane-inherited workspace scope for name lookups (#34 rule).

The module sits at the top of lib_py: delegation and loop may not import the
agent adapters (their sibling-import rules). Idle pane captures of the five
CLIs are fixtures; the mock herdr answers process-info in the real shape.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:43:21 +00:00
GodopuandClaude Opus 5.5 ec9586bb9b feat(issue-33): the job budget travels and the two clocks carry different labels
- wrapper: TIMEOUT falls back to MAM_JOB_TIMEOUT_S (--timeout > env > 3600);
  an invalid value warns and keeps 3600.
- loop: --job-timeout <sec> (run_loop.sh passes it on; refused in the legacy
  shell loop). The runner always hands the wrapper --timeout, so the budget
  the wrapper registers is the one its wait caps come from.
- runner: wait_for_job and the MAM_CHILD_WAIT_S default are budget + 300 s
  (MAM_WAIT_GRACE_S), today's 3900 with no option; an explicit
  MAM_CHILD_WAIT_S still wins.
- subscriber: the wall-clock budget returns 4 (RC_WALL_CLOCK), silence keeps
  2 (RC_NO_EVENT). The wrapper maps both to caller rc 2 and labels the close
  from the rc: wall_clock_timeout vs deadline_timeout; the disk-heartbeat
  grace that ends on the deadline is the wall clock too.
- registry close accepts wall_clock_timeout (engine: -> error); the remote
  runner's deadline and command-timeout details lead with wall_clock_timeout;
  the sub-job table files it CLOSED-UNCONFIRMED (first token, colon stripped).

Test expectations changed only where the contract changed: the loop's
contract_args now starts with --timeout, the subscriber's exit-code docstring
names rc 2/4, and the registry --help capture lists the new close kind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 11:43:10 +00:00
GodopuandClaude Fable 5.1 8ea65bb238 merge: fix/issue-34 (Issue #34: the loop waits for the creator's sub-jobs and hands reviewers their status; v4.7.4)
Reviews: authoring workspace 5 reviewers, full loop round 2 PASS + delta PASS; merge workspace round 1 @ed293dc claude/agy PASS, grok/codex NOT PASS (cancelled sub-job reason lost, remote deadline wording, stray-job rule) -> fixed in 8a9101e + e80186f; round 2 @e80186f all four PASS (identity: base ed293dc -> head e80186f, evidence review-tree). Full suite @ed293dc: 1156 passed, 3 skipped, 2 broker-latency flakes (pass in isolation); targeted suites @e80186f: 125 + 54 passed. Reports under .agents/reports/. Closes #34.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-25 07:44:34 +00:00
GodopuandClaude Fable 5.1 22586d2a01 release(v4.7.4): bump framework and eight skills to 4.7.4 in lockstep; archive PR #38 merge-side reviews
Issue #34: the loop waits for the creator job's sub-jobs, reviewers get
the sub-job table as evidence, a run with sub-jobs voids a round whose
source changed during review, and a pane caller reaches an agent of
another workspace on its own server. VERSIONS.md carries the entry; the
merge-side reports (round 1 @ed293dc and round 2 @e80186f with identity
sidecars, base ed293dc -> head e80186f, evidence review-tree) are archived
under .agents/reports/<session>/.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-25 16:44:20 +09:00
GodopuandClaude Fable 5.1 e80186f560 fix(issue-34): merge review - the remote runner's deadline wording counts as an unconfirmed close
remote.py closes a job whose end it could not see with
`error --detail "deadline_timeout (remote runner)"`; the sub-job table
matched the reason exactly and filed it as a plain failure, losing the
unconfirmed count and the late-write warning (merge review, codex R2).
The kind is the first word of the reason now. Test T14 replays the
remote runner's close through the real registry and producer; it fails
without the fix.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-25 16:23:06 +09:00
GodopuandClaude Fable 5.1 8a9101ed30 fix(issue-34): merge review - a sub-job cancelled before injection keeps its reason in the review table; unattributed open jobs come with a verdict rule
- registry.get_feedback only returned the detail of the last completed or
  error event, so a sub-job the wrapper cancelled before injection
  (target_not_found, session_busy) reached the review table as a bare
  `cancelled` and its reason was lost (merge review, grok N1). get_feedback
  takes the event kinds to read (default unchanged); the table asks for
  cancelled too and shows NOT-DISPATCHED with the reason. Test T13, both
  reasons, fails without the fix.
- the [귀속되지 않은 열린 잡] line listed jobs registered without
  --parent-job but gave the reviewer no rule for them - the one case the
  table cannot show (claude K1). A rule sentence follows the line whenever
  such a job exists; without one the prompt is unchanged. T6 pins it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-25 16:19:12 +09:00
GodopuandClaude Opus 5.5 ed293dcef4 fix(issue-34): a pane caller reaches an agent of another workspace on its own server; an unseen target is not recorded as busy
- mam_herdr: for name lookups (agent / has-session / kill-session) a
  HERDR_WORKSPACE_ID that is the caller pane's own workspace (it matches
  the HERDR_PANE_ID prefix) is dropped. Live agent names are unique per
  server (herdr --skill), so this cannot address a same-named agent of
  another workspace; an id the caller chose, or one set outside a pane,
  still scopes (H-18/H-21/H-23). The generated shim is unchanged (S11).
- wrapper: a preflight that cannot see the target closes the job
  cancelled with detail target_not_found instead of session_busy; the
  loop's sub-job table counts it as NOT-DISPATCHED.
- tests: T10-T12 with the measured pane env (same-server socket, caller
  w6, target w2); T8 follows the sub-job-armed guard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 01:25:48 +00:00
GodopuandClaude Opus 5.5 1d4f338b4c fix(issue-34): the stale-review guard is armed only when the run has sub-jobs
Without --worktree/--base the guard fingerprinted the source on every
loop, so a loop whose source holds untracked files that change on every
job voided each round: test_tier4_e2e scenario 5 keeps the mock herdr's
state file (rewritten on each herdr call) in its repository and failed
with rc 1 on 3fdbb62 (passed on 7a4a0c2). A loop without sub-delegation
now behaves as before (issue #34 requirement 3); with sub-jobs the guard
protects against a deadline-closed sub-job still writing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-25 01:25:48 +00:00
GodopuandClaude Opus 5.5 3fdbb626de fix(issue-34): review - a correction round keeps the earlier creator jobs' sub-jobs in the evidence table
round_roots was replaced by the correction job, so an implementation
job's open or failed sub-job vanished from the next review and the loop
could pass (planner-reviewer-codex-01, P2). The run's creator jobs now
accumulate; each wait still covers only the new job's tree, so the wait
cap is not paid again per round. T9 covers open / error / completed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 14:17:12 +00:00
GodopuandClaude Opus 5.5 8690ef4bd2 docs(issue-34): --parent-job, MAM_CHILD_WAIT_S, --wait-open-jobs, the sub-job verdict rule and the stale-review guard
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 13:37:05 +00:00
GodopuandClaude Opus 5.5 30c8c7ebab fix(issue-34): the loop waits for the creator job's descendants, hands reviewers the sub-job table with closing reasons, and voids a round whose source changed during review in every mode
- wait_for_job_tree at the execution, correction and compliance waits;
  bounded by MAM_CHILD_WAIT_S (3900) and MAM_JOB_TREE_MAX (50)
- [하위 위임 잡] table: OPEN / CLOSED-UNCONFIRMED (deadline_timeout,
  agent_blocked, or error with no reason) / NOT-DISPATCHED / error /
  completed, plus unattributed open jobs; omitted when there are none so
  option-less prompts stay byte-identical
- --wait-open-jobs also waits for unattributed open jobs
- stale-review guard without --worktree/--base: head + tree (control
  plane excluded) before review, re-checked after verdicts and before
  promotion; off with a warning when the source cannot be fingerprinted
- tests/test_issue34_job_tree.py: real wrapper registrations, real
  publish_event / deadline close, real loop process

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 13:37:05 +00:00
GodopuandClaude Opus 5.5 ec663a93c8 feat(issue-34): a job records its parent; submit --parent-job (MAM_JOB_ID by default) and the brief tells the agent to pass it on
- registry: parent_job field, register --parent-job fails closed on an
  unknown parent, children_of/descendants_of, list --parent
- wrapper: --parent-job; $MAM_JOB_ID default (ignored with a warning when
  this registry lacks it); brief line and one sentence at the end of the
  injected instructions
- create_session: the onboarding instructions carry the same sentence

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 13:37:05 +00:00
GodopuandClaude Fable 5.1 7a4a0c2091 merge: fix/issue-36 (Issue #36: delegated prompts travel by file, a failed delegation ends the loop with rc 1; v4.7.3)
Reviews: authoring workspace 5 reviewers x 3 rounds PASS; merge workspace round 1 @59be1c8 claude PASS, agy/grok/codex NOT PASS (S9 macOS wording, runner prompt-file write failure, empty --prompt-file) -> fixed in 708262a; round 2 @708262a all four PASS (identity: base 59be1c8 -> head 708262a, evidence review-tree). Full suite @59be1c8: 1139 passed, 2 skipped, 1 failed (S9, fixed); targeted suites @708262a: 125 passed. Reports under .agents/reports/. Closes #36.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-24 09:10:39 +00:00
GodopuandClaude Fable 5.1 c3e6a7e96d release(v4.7.3): bump framework and eight skills to 4.7.3 in lockstep; archive PR #37 merge-side reviews
Issue #36: delegated prompts travel by file, a delegation that fails ends
the loop with rc 1. VERSIONS.md carries the entry; the merge-side reports
(round 1 @59be1c8 and round 2 @708262a with identity sidecars, base
59be1c8 -> head 708262a, evidence review-tree) are archived under
.agents/reports/<session>/.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-24 18:10:28 +09:00
GodopuandClaude Fable 5.1 708262a598 fix(issue-36): merge review - a prompt file the runner cannot write is a failed submit; S9 asserts the libc wording on Linux only; an empty prompt file is refused
- runner._run_cmd: the write of the prompt file was outside the cleanup
  and error handling that the exec had (merge review: claude H1, codex R1).
  A failed write now removes the partial file and returns the same 126
  failed submit an unstartable wrapper does, so the loop ends with rc 1
  and no traceback. Test S4c.
- test S9 required the literal "File too large" in stderr; bash 3.2 on
  macOS prints nothing for EFBIG, so the whole suite failed on this host
  (agy, grok, codex R2). The contract asserted everywhere is rc != 0, no
  leftover file and the portable diagnostic line; the libc wording is
  checked on Linux only.
- the wrapper accepted an empty --prompt-file and registered an empty
  prompt (claude H3); it is refused now. Test S1e.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-24 17:55:56 +09:00
GodopuandClaude Opus 5.5 59be1c8920 fix(issue-36): create_session hands the agent a brief path, not the task; a prompt file that cannot be written is removed
Review of f26952c (codex, job cc849cbf):

- P2: create_session registered the task by file but then pasted the whole
  task into the onboarding text, which send_keys_safe hands to `herdr agent
  prompt` as one argv string. A 130,500-byte --submit-job was registered
  intact and never reached the agent (execve E2BIG). The task now goes into
  <jobs>/<id>/brief.md, as the delegate-job wrapper does, and the injected
  text names that path. The publish command and its dispatch token (#23) are
  unchanged. The other send_keys_safe callers (the wrapper's short pointer,
  stop_session's exit key) carry no task text.
- P3: delegate_job_safe's write-failure branch left the partial prompt file
  behind and logged to stdout, which callers capture. It now removes the file
  and logs to stderr.

S8 (real create_session.sh, 100 and 130,500 bytes, strace when present) and
S9 (the real function, RLIMIT_FSIZE write failure) carry the reviewer's
reproductions over; all three fail on f26952c.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 07:02:20 +00:00
GodopuandClaude Opus 5.5 f26952ccc3 fix(issue-36): the legacy shell loop and lib.sh's submit helpers pass prompts by file
The two remaining exec points that carried a prompt as one argv string
(capped at 131,072 bytes):

- run_loop.sh (MAM_LOOP_PY=0): delegate_job_safe, which all eleven shell
  delegations go through, turns `--prompt <text>` into `--prompt-file` under
  the control root's .mam/ and removes the file once the wrapper returns. Its
  failure lines go to stderr: callers capture stdout, and under set -e a
  failed submit ends the loop at that line with the wrapper's code, so the
  cause was being swallowed.
- lib.sh delegate_submit_job and its legacy twin (create_session's onboarding
  and --submit-job): the prompt is written under .mam/ and handed on as
  --prompt-file; lib_py.delegation.cli submit accepts --prompt-file and
  forwards it to the registry. --prompt keeps working everywhere.

S6/S6b push a 140,000-byte prompt through the CLI and both helpers; S7 runs
the real run_loop.sh with a 140,000-byte plan and a 150,000-byte diff; S7b
fixes a nonzero exit when the implementation or compliance job cannot be
registered. All six fail on 14d11bf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 06:08:25 +00:00
GodopuandClaude Opus 5.5 14d11bf062 fix(issue-36): a job that cannot be registered after a rebuttal ends the loop with rc 1
Review of f5cadd9 (planner-reviewer-codex-01, R1): the compliance job's
registration failure was only logged, so a passing next round ended the
real loop process with rc 0. Compliance now returns 1 when it cannot be
registered or does not finish, as the correction step already does.
Re-adjudication and arbitration also return 1 when their job cannot be
registered; a registered job that yields no verdict keeps the designed
fail-closed fallback.

S4c (stubbed delegate_job, a fixture whose later rounds never pass) is
replaced by S3c: a real `python -m lib_py.loop` process whose wrapper runs
an executable that simulates the agents, refusing the compliance,
re-adjudication or arbitration registration while the next round passes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 03:38:10 +00:00
GodopuandClaude Opus 5.5 f5cadd98c0 test(issue-36): prompts over the argv cap go through the real wrapper, registry and loop; a failed delegation ends the loop with rc 1 and no traceback
S1-S1d push a 140,000-byte prompt through the real wrapper and registry by
file, with a negative control that the same prompt as an argument fails with
E2BIG. S2 runs the real runner against a recording wrapper. S3/S3b run a real
`python -m lib_py.loop` whose wrapper fails or cannot start. S4/S4b/S4c cover
the exec-error handler, the busy retry and the compliance log. S5 sends a
collected diff from the former 131,072..200,000-byte blind spot through whole.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 02:30:13 +00:00
GodopuandClaude Opus 5.5 c77806b1b1 fix(issue-36): the loop passes every delegated prompt as a file; a wrapper that cannot start is a failed submit, on the first try and on the retry
delegate_job writes the prompt to a temp file under the control root's .mam/
and hands the wrapper --prompt-file; the file is removed once the wrapper
returns. An OSError from starting the wrapper becomes a failed submit (rc 126)
that the existing error branch logs, so the session-busy retry no longer
dereferences a missing result. A retry that yields no job id, and a
compliance job that cannot be registered, are now logged instead of silent.

The collector caps are documented as the size of the evidence a reviewer is
shown; delivery has no cap of its own any more. The loop skill notes that a
pipeline hides the loop's exit code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 02:30:13 +00:00
GodopuandClaude Opus 5.5 68a5d31381 fix(issue-36): registry and wrapper accept --prompt-file; the wrapper hands the same path on
One argv string is capped at MAX_ARG_STRLEN (131,072 bytes on Linux), so a
prompt passed as --prompt could not reach the registry once it carried a
large diff. submit now takes --prompt-file and passes the same path to
`registry.py register --prompt-file`; the loop type's per-iteration update
goes by file too. --prompt keeps working unchanged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-24 02:30:13 +00:00
GodopuandClaude Fable 5.1 1debc7d924 merge: fix/issue-23-24 (Issues #23, #24: cross-server herdr scope, agent-agnostic start-up dialogs, started-based onboarding verdict, verified rollback; v4.7.2)
Reviews: authoring workspace 5 reviewers x 5 rounds PASS; merge workspace round 1 @f4ba205 claude/agy/grok PASS (codex report lost to host sleep; its two probes fixed in 05b0ea4), round 2 @05b0ea4 all four PASS (identity: base f4ba205 -> head 05b0ea4, evidence review-tree). Full suite @f4ba205: 1111 passed, 1 skipped; affected suites @05b0ea4: 123 passed. Reports under .agents/reports/. Closes #23, #24.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-23 23:36:37 +00:00
GodopuandClaude Fable 5.1 9fb037c084 release(v4.7.2): bump framework and eight skills to 4.7.2 in lockstep; archive PR #35 merge-side reviews
Issues #23 and #24: cross-server herdr scope, agent-agnostic start-up
dialogs, onboarding delivery judged by the agent's own started event,
verified rollback. VERSIONS.md carries the entry; the merge-side reports
(round 1: claude/agy/grok; round 2 on 05b0ea4: all four, with identity
sidecars, base f4ba205 -> head 05b0ea4, evidence review-tree) are archived
under .agents/reports/<session>/. The round-1 codex report was lost to the
host sleeping mid-review; its two probes are recorded in the changelog.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-24 08:36:35 +09:00
GodopuandClaude Fable 5.1 05b0ea4762 fix(issue-23-24): merge review - the environment form of the auto-trust switch reaches the handler; a rate-limited dialog does not hide the next one
Two probes from the merge-side codex review (its report was lost to an API
outage; the probes and their results were recovered from its transcript):

- create_session.sh and resume_session.sh set AUTO_TRUST=1 and then
  exported MAM_AUTO_TRUST from it, so the documented MAM_AUTO_TRUST=0
  without a flag reached handle_startup_dialogs as 1: the operator had
  turned automatic trust off and it stayed on. Now AUTO_TRUST defaults to
  the environment value and an explicit --auto-trust/--no-auto-trust wins.
- _mam_dialog_pick exited on the first dialog inside its resend cooldown
  instead of looking further down the screen, so a skipped (--no-auto-trust)
  or just-answered trust prompt hid the codex update notice below it, which
  the docs say is always answered. It continues to the next dialog now; S5
  and S5b (one send per cooldown, one retry after it) still hold.

Regressions: S6c, S5f (startup path), R3b and C3 (resume/create, env only,
flag over env). Each fails without the fix. The create skill doc names the
environment form and its precedence.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-24 06:47:57 +09:00
GodopuandClaude Fable 5.1 f4ba205c9f fix(issue-23): the remote audit record names the dispatch it vouches for; a record without identity fails closed
Review round 4 (planner-reviewer-claude-01 B-1, planner-reviewer-codex-01
P2, reached independently): dispatch_verified is a boolean. It says the
subscriber's token check ran when the record was written, but names no
dispatch, the token being masked by the audit redactor and attempt_id not
written. events.ndjson is appended to across a job's attempts, so a started
verified under attempt 1 satisfied every later attempt's wait - the very
misattribution R1 forbids, alive on the remote path while the local path
(data.dispatch_token in events.log) was already immune. codex reproduced it
with the real signed producer, the real _Watcher, the real audit writer and
the real operator re-dispatch; both waits answered 0 where 1 was due, even
when attempt 2's subscriber had correctly dropped attempt 1's replayed packet.

The subscriber now writes dispatch_fingerprint = SHA-256 of the token it
verified, and attempt_id for readers. With a token demanded, the predicate
accepts an audit record only if it is dispatch_verified AND its fingerprint
equals SHA-256 of that token; a record with no fingerprint - written before
the field existed - names nothing and is rejected on that path. Without a
token, any received started counts, as before.

Fingerprint over attempt_id as the identity, weighing the two proposals: the
local path already compares the token, so hashing it keeps one identity axis
for both sources; the token is a uuid4 nonce (registry.py:141), 128 bits, so
its SHA-256 is not recoverable and it is a CAS fence rather than the HMAC
secret in the first place; and attempt_id cannot tell apart a token
re-minted within one attempt, where the token can. attempt_id is recorded
because it is cheap and readable, not relied on.

W7 pins codex's five cases end to end - current dispatch accepted, an old
attempt's record rejected after a real re-dispatch, still rejected when the
stale packet is replayed and dropped, the new dispatch's own started
accepted, a bad HMAC never recorded - with create's wait and the wrapper's
wait required to agree on each. W8 pins the fail-closed legacy record and
the untokened compatibility path. W5 gains the no-fingerprint and
other-dispatch cases; W6 checks the real _Watcher writes the fingerprint and
never the token. S7e's status reset had no reason left and is gone. codex's
own reproduction file, unmodified, passes 5/5 against this tree.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 17:52:51 +00:00
GodopuandClaude Fable 5.1 087eacaf21 fix(issue-23): both ack waits share one contract - the wrapper's status bypass is gone; the G9 guard removes only the docstring node
Review round 3 (planner-reviewer-codex-01, reviewer-opencode-01): R1 blocking,
R2 and the "ONE builder" wording non-blocking. All three reproduced; none
rebutted.

R1. _wait_started still returned 0 as soon as the record left `pending`,
ahead of the shared predicate, so `error`, `cancelled` and another dispatch's
`running` all acknowledged an injection that create's delegate_wait_started
rejects - the two contracts the ack-finding brief said must not diverge. Both
reviewers reproduced it with the real producer and no record manipulation;
my S7n had hidden it by resetting the record to `pending`.

The bypass and the console grep are gone. The wrapper's evidence is now
delegate_started_recorded alone, the same call create makes. For a remote
agent - no shared disk, so no line in events.log - the predicate reads the
subscriber's audit record of the `started` it received. That record is
attributable by construction: the subscriber verifies the HMAC and drops any
event whose data.dispatch_token differs from the job's expected token before
it writes anything. The token itself cannot go into the record (the audit
redactor masks token-named keys), so the subscriber now stamps a boolean
dispatch_verified, and with a token demanded only a verified record counts;
an untokened legacy record fails closed. The registry status is never
evidence; a terminal job is preserved by the terminal logic, not turned into
an acknowledgement.

Tests: W1/W2/W3 are the reviewers' three negatives and the positive, real
producer, record left exactly as it produced it; W4 runs create's wait and
the wrapper's wait side by side on all four and requires the same answer;
W5 pins the remote route (a verified record counts, an unverified or
non-started one does not); W6 drives the real _Watcher and shows it stamps
the flag on a matching started and records nothing for a mismatch; S7n no
longer resets the record. test_issue14's "registry ack over unconfirmed
inject" produced its ack with a bare status flip - the very bypass - and now
produces it the way an agent does, publish_event with the dispatch token;
its scenario and every other assertion are unchanged. test_issue18's remote
e2e accepted the status messages and now expects the shared one.

R2. _code_only blanked a docstring's whole line range, so code sharing that
line - `"""doc"""; call()` - vanished from the scan. It now removes only the
docstring node from the AST and unparses the rest (comments drop out with
it, code strings stay); test_g9b pins the four same-line shapes.

The builder comment claimed one builder for create and the wrapper; the
wrapper keeps _pub_cmd and S7l pins the two equal argument-for-argument. The
comment now says that.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 16:43:00 +00:00
GodopuandClaude Fable 5.1 4805fd4511 test(issue-5): the G9 no-frozen-helper guard reads code, not comments or docstrings
The full suite on 1667fda showed exactly one failure beyond this host's
baseline: test_g9_phase2a_spawns_no_daemon_and_calls_no_frozen_helper. Its
`\blib\.sh\b` pattern matched a docstring in watcher.py that points at the
shell twin of caller_server ("Same convention as lib.sh's
_herdr_caller_server") - a mention written so the two implementations stay in
sync, not a call.

The guard's own docstring states its claim: no frozen lib.sh helper is
*invoked* from lib_py/loop. Its one prior change (803ba43) added the word
boundary after `hashlib.sha256` tripped it - the same class of false positive,
handled by narrowing the matcher rather than by contorting innocent code.
This continues that: the three patterns and the word boundary are unchanged,
but they now run over the source with comments and docstrings blanked. Every
way Python could actually reach a lib.sh helper - a path or `source` in a
subprocess argv, an identifier - lives in code text, which is still scanned in
full, so the guard keeps its reach. test_g9b pins both sides: an
invocation-shaped string in code still trips it (lib.sh and
ensure_subscriber_daemon both reported), a bare lib.sh path in a list literal
still trips it, and the same words in a module docstring, a function
docstring and a comment do not - with hashlib.sha256 present as the original
regression.

Rephrasing the docstring to dodge the literal was the other option and was
not taken: it would hide a useful cross-reference to satisfy a matcher, which
is the evasion shape this guard should not encourage, and it would leave the
next honest comment to trip the same wire.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 15:32:40 +00:00
GodopuandClaude Fable 5.1 1667fda8dd fix(issue-23): the onboarding ack is satisfied by what a real agent publishes; one command builder and one started predicate for create and the wrapper
Trial 2 of this branch: cross-server delivery was restored (f7cee00), the
agent completed its onboarding and published started and completed - and
create_session still waited 180 s, called the onboarding unconfirmed, and
tried to write `error` over the completed job (refused by the registry).

delegate_wait_started required the started line to carry data.dispatch_token
(review R1: a stale attempt's started must not vouch for this one). But
publish_event only writes that field when its command line carries
--expect-dispatch-token, and create_session's hand-rolled onboarding command
never did - the wrapper's _pub_cmd does, which is why every wrapper-dispatched
agent's started has the token and no create_session onboarding ever could.
Five reviewers missed it because the fixture wrote the token into the started
line by hand: a fake producer that differs from the real one.

Fix, along the wrapper's existing mechanism rather than a new one:

* delegate_publish_cmd (lib.sh) builds the publish command for an agent, with
  --expect-dispatch-token and --attempt-id, and create_session uses it. The
  agent's own started now names the dispatch, and publish_event's CAS check
  refuses a stale dispatch's event at the source. S7l pins the builder
  argument-for-argument against the wrapper's _pub_cmd.
* delegate_started_recorded (lib.sh) is the one definition of "this
  dispatch's started is on disk" - JSON-parsed, token-matched when a token is
  given - used by delegate_wait_started and by the wrapper's _wait_started in
  place of its regex. The wrapper keeps its status and subscriber routes
  (remote agents); the shared part is the evidence contract.
* An already-terminal job is left alone when the wait expires (req. 4): no
  error over a completed/error/cancelled record.

The fixture now registers the record through registry.py and publishes
started through the real publish_event.py; the only synthetic line left (S7h)
exists to pin key-order independence and says so. S7i pins the trial-2 defect
as the negative it is (old command shape -> started without token -> not
acknowledged); S7j runs the builder's command through the real producer and
is acknowledged on the first probe; S7n shows the wrapper accepting the same
real line and rejecting a stale token; S7m pins no-write-over-terminal. S7f
moves from "publish error" to "leave the terminal job alone", per req. 4.

Option B (verify data.hmac_sig with the job's auth_token, plus record-token
still equal) was weighed and not taken: verify_hmac returns True with no
auth_token - PoC mode, which the trial and every sandbox run in - so it proves
nothing there; in production hmac_sig authenticates the signer but does not
identify the dispatch, so R1 would rest on a current-state check that a stale
line plus an unrotated token passes; and it would diverge from the wrapper
unless the wrapper changed too. Token exposure is not new: every wrapper-
dispatched instruction already carries the dispatch token in the pane, and it
is a per-dispatch CAS nonce, not the HMAC secret.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 14:42:38 +00:00
GodopuandClaude Fable 5.1 f7cee00dec fix(issue-23): the caller's server comes from HERDR_SOCKET_PATH, not only HERDR_SESSION
The live trial of this branch found the cross-server verdict inert on this
host: _herdr_call_is_cross_server read the caller's server from HERDR_SESSION,
and herdr 0.8.2 does not export that variable to a pane of the default server
- the orchestrator's usual home, and exactly the pane the #23 leak comes from.
Every call was judged "not crossing", the three ids were never dropped, and
all four trial onboardings ended "no started within 180s". My own pane sits in
a named server and does carry HERDR_SESSION, which is how the assumption got
past me.

HERDR_SOCKET_PATH is exported to every pane and its layout names the server:
.../.config/herdr/herdr.sock is the default server and
.../.config/herdr/sessions/<name>/herdr.sock a named one - the convention
`herdr session list --json` reports and the shim already uses to find a named
server's socket. _herdr_caller_server prefers HERDR_SESSION when a herdr does
export it, otherwise reads the socket's shape (suffix-matched, not $HOME-
anchored), and yields "" for anything unrecognised so an exported scope is
respected rather than guessed away. The rest of the rule is unchanged from
3bcaa39: a `default` or empty target is the ambient server, no caller server
means no pane, caller == target is the same server. watcher.caller_server
applies the same rule for the loop's own herdr calls.

Reproduced against the live server in the trial's exact env: 10a678c answers
"NOT crossing / has-session NOT FOUND"; this commit answers "caller server
default / crossing / FOUND". S1c pins that env end to end with the recorder
asserting the ids never reach herdr; S1d-S1h pin the verdict, the named-socket
same-server and cross-server cases, HERDR_SESSION precedence, and the
unrecognised layout. The 3bcaa39 tests are unchanged and still pass.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 14:13:38 +00:00
GodopuandClaude Fable 5.1 10a678c010 fix(issue-23-24): the dialog handler sees the ready banner on its own; only this dispatch's started is delivery evidence
Review round 1 (planner-reviewer-claude-01, reviewer-agy-01,
planner-reviewer-codex-01): one blocking defect and two P2s, all confirmed.

B-1. handle_startup_dialogs took its ready tokens only from the environment,
which wait_for_tui_ready fills when it evaluates the adapter facts. Called on
its own - as resume_session.sh calls it, with no readiness wait before it -
it had no tokens, its early-return branch could never fire, and every resume
of every agent idled through the full 20 s timeout (base: 0.03 s). rc was 0
throughout, so nothing failed; the resume tests just took ~30 s each.
_mam_load_dialog_facts now also takes MAM_STRONG_READY_TOKENS / MAM_READY_TOKENS
from the facts, but only when the caller has not set them, so a caller-set
value (wait_for_tui_ready's own, or a test steering readiness) is never
clobbered - the concern that made it take a single fact in the first place.
S5d pins one-iteration return on a ready first frame for five adapters with
no environment; S5e pins that caller tokens survive; R4 gets a wall-clock cap
so a timeout-idle can no longer pass as success. The old
_MAM_READY_TOKENS_CLAUDE fallback was left defined but unread - removed.

R1 / N-2. delegate_wait_started treated any status past `pending` as the
agent's acknowledgement. codex reproduced three false positives: `error` and
`cancelled` records with no started line, and a `running` record from another
dispatch. The status branch is gone; the evidence is a started line carrying
this dispatch's token, which the local publisher writes before it syncs the
status, so nothing that really started is missed (S7c re-pinned on the line
with running/completed/error statuses; S7f/S7g pin the three negatives).

N-4, taken with it: the events.log line is parsed as JSON rather than pattern-
matched. publish_event nests dispatch_token under `data`, and the old regex
only matched because of key order (S7h, real line shape and a reordered one).

R2 / N-1. Two tests hardcoded <repo>/.venv/bin/python and failed with
FileNotFoundError in every review worktree. sys.executable.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 10:25:52 +00:00
GodopuandClaude Fable 5.1 0dfbb2cc8a fix(issue-24): resume answers start-up dialogs for every agent, with the same switch as create
resume_session.sh called handle_startup_dialogs only when AGENT=claude and
passed no agent, so a resumed agy, grok or codex sat on its directory-trust
prompt exactly as the create path did before this branch. The gate is gone and
the agent is passed, which is the call create already makes.

--no-auto-trust / MAM_AUTO_TRUST apply to resume too. A resumed CLI shows the
same trust dialog as a fresh one, in the same directory, with the same
consequence for codex (trusting loads the project's local config, hooks and
exec policy), and handle_startup_dialogs already reads MAM_AUTO_TRUST - so the
only question was whether resume exposes the switch or silently inherits the
caller's environment. Exposing it keeps the two skills' contracts identical.

The tests run the shipped create/stop/resume scripts against the mock herdr.
The mock's pane always shows a ready banner, so they fix the call resume makes
(session, timeout, agent, MAM_AUTO_TRUST) by overriding the handler in the
sandbox copy of lib.sh, plus one unmodified run showing the real handler is
reached for a non-claude agent; which keys a dialog gets is fixed on the create
side (S4-S6).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-22 08:19:18 +00:00
GodopuandClaude Opus 5 ce802d21c8 docs(issue-23): the create skill documents the preserve-on-unacknowledged-onboarding rule and MAM_ONBOARD_ACK_S
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 06:24:33 +00:00
GodopuandClaude Opus 5 33b91fe0c8 fix(issue-23): an unacknowledged onboarding marks the job and keeps the session
Two defects in the started-based verdict, both found by the full suite.

The first was destructive. No `started` within T exited 1, which fired the
rollback trap and killed the session. That is worse than the bug being fixed:
create_session already has a rule for "the agent is not responding but the
process is alive" one step earlier - a TUI that never signalled ready is
preserved for diagnosis - and an onboarding that is merely slow is the same
situation. The job is marked `error` and warned about loudly; the session, its
row and the pane stay. MULTI_AGENT_RULES §6 has the GM gate on this job
anyway, so an unacknowledged onboarding still blocks real work.

It also broke 21 tests across 8 modules (create/sanity/tier2/tier3/tier4/
issue15/issue19/issue21) and added roughly an hour to the suite: no sandbox
has an agent to publish `started`, so every create_session test sat out the
full 180 s and then failed on the rollback. MAM_ONBOARD_ACK_S shortens that
wait, and the sandbox fixture sets 3 s. It is deliberately not the wrapper's
MAM_INJECT_ACK_GRACE_S - that is a different wait whose own tests assert on
the value they pass, and reusing it made issue18's acceptance2 read "within
3s" instead of "within 4s".

The second: the delivery failure published `error` and then the rollback
published `cancelled` on the same job, which the registry refuses
("conflicting cancelled after terminal error"). Terminal events are published
exactly once, so the trap now skips a job this run already closed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 06:24:06 +00:00
GodopuandClaude Opus 5 2cd20423ac docs(issue-23-24): the create skill documents --no-auto-trust, the started-based onboarding verdict and exit 43
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 04:28:57 +00:00
GodopuandClaude Opus 5 123dca47bb fix(issue-23): onboarding delivery is judged by the agent's own started event, and a rollback verifies the kill
Plan commits 3 and 4 landed together: both rewrite the same region of
create_session.sh and share one test file, and splitting them afterwards would
have meant hunk-level surgery on already-verified code.

Delivery verdict (item 3). create_session --onboard called a healthy agent a
failure three seconds after registering the job: inject_instructions ->
send_keys_safe returns rc 4 when `agent prompt --wait --until working` fails
and the pane is still not working two seconds later, which is exactly where a
TUI that is still starting up lands. It never got the ISSUE-18 confirmation the
delegate-job wrapper has. rc 4 is a warning now and the agent's own `started`
decides, within the job's own ack timeout; rc 1/2/3 stay hard failures, since
they say the pane never quiesced, a dialog was blocking, or the text never
appeared, and no later `started` repairs those.

The self-published `started` had to go first. create_session published it on
the agent's behalf right after injection, so the registry showed a started job
whether or not the agent ever saw the prompt - with that line in place, no
started-based verdict can mean anything.

delegate_wait_started is lib.sh's counterpart to the wrapper's _wait_started
(plan item D10-b). The wrapper's own `submit` was the first choice, but it
blocks until the job reaches a terminal state, and create_session must return
as soon as delivery is confirmed; the on-disk evidence it reads - registry
status past `pending`, or a started line carrying this dispatch token - is
written by publish_event before its wire publish, so no broker is involved.

Rollback integrity (item 4). The trap ran `_herdr kill-session -t
"$SESSION_NAME" 2>/dev/null || true`, so a kill that closed nothing still
printed "rolling back" while the session kept running, and the row stayed
`running` pointing at the job the same rollback had just failed (#23 symptom
5). With item 1 in place this check is finally trustworthy: the kill used to
fail because the caller's workspace id hid the pane.

The trap now reads the kill's rc, confirms with has-session, closes the
onboarding job as `cancelled` (a terminal transition the registry knows, and
the truthful one - the job was never dispatched), and marks the row. A session
still alive exits 43 with the manual cleanup command, distinct from 42 (TUI
never ready).

The row keeps a schema-valid status rather than the plan's `error`, which
atomic_yaml.py rejects: `terminated` once the session is really gone, and
`running` when the kill failed, because it is still running. What makes that
case legible is the note, the cleared delegate_job_id and exit 43 - not a
status claiming the opposite of the truth. The row is never deleted; a deleted
row takes the evidence with it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 04:28:27 +00:00
GodopuandClaude Opus 5 5ba04a27ca feat(issue-24): startup dialogs come from the agent adapter and are handled while waiting for the TUI
handle_startup_dialogs was a claude-only string ladder called only when
AGENT=claude, and wait_for_tui_ready does not treat a dialog screen as ready.
So agy, grok and codex sat on their directory-trust prompt for the full
readiness timeout, the session was recorded as tui-ready-timeout, and
onboarding injection was disabled (create_session.sh:313-314) - a human had to
accept each dialog by hand.

The signatures and accept keys move to the adapters as `startup_dialogs`
(pattern, keys, kind), published through the existing `facts` eval contract as
MAM_STARTUP_DIALOGS. claude's ladder moves over verbatim; agy takes Enter, grok
y, codex Enter, and codex's update notice takes 2 (Skip), which blocks a start
just as hard while changing nothing. kind is `trust` or `notice`:
--no-auto-trust leaves trust dialogs to a human and still answers notices,
since trusting a directory makes codex load its project-local config, hooks and
exec policy.

Re-sending is gated by time (MAM_DIALOG_RESEND_S, default 5s), not by frames.
#24's comment reports that `--source visible` keeps showing an accepted dialog
for a while, and _pane_capture hardcodes that source, so "still on screen" is
not evidence the keys were missed; acceptance is judged by the ready tokens
alone.

Two existing tests asserted the old shape and are updated, not weakened:
b19's "Escape branch stays" now looks for it in claude's adapter, and c1b's
"Enter once per iteration" becomes "never twice for one frame", which the
cooldown satisfies strictly more tightly.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 04:22:09 +00:00
GodopuandClaude Opus 5 3bcaa39ab0 fix(issue-23): a herdr call to another server drops the caller pane's workspace/pane/tab ids
A MAM script often runs inside one herdr server's pane (the orchestrator's)
while targeting another (the isolated MAM server). The pane exports
HERDR_WORKSPACE_ID, HERDR_PANE_ID and HERDR_TAB_ID, and those ids only mean
something on the server that issued them. They reached the scope filters as a
foreign workspace, whose fail-closed miss (ISSUE-3 / F-2b) reports a live
session as absent: has-session, kill-session, agent prompt and the delegate-job
preflight all answered "no such session". Reproduced on Linux and macOS in the
#23 comments, worked around until now with `env -u` at every call site.

mam_herdr drops the three ids for a call aimed at a named server other than the
caller's own. Scope then falls back to .mam/herdr_workspace_id and finally to
server-global, which is what _herdr_ws_scope already does. `default` is not a
crossing: it is the sentinel for "pass no session flag", so herdr answers on
the ambient server, which for a caller in a pane is that caller's own. A caller
outside any pane keeps an exported scope, so H-18/H-21/H-23 keep their meaning.

The fix lives in mam_herdr, not in the shim heredoc: that heredoc is
materialised into $WORKSPACE_ROOT/.mam/shim/herdr, one file shared by every
checkout bound to a control plane and rewritten on every herdr call, so editing
it would put unreviewed code in the control root and let two checkouts
overwrite each other. S11 fixes that invariant.

lib_py/loop/watcher.py builds its own herdr argv and is the one path that does
not go through mam_herdr, so it applies the same rule via scoped_env.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-22 04:14:45 +00:00
GodopuandClaude Fable 5.1 1e78dae6eb merge: fix/issue-25 (Issue #25: promoted plans are reused only with --plan-file; empty plan reports are not silent; v4.7.1)
Reviews: authoring workspace round 2 @1e82651 5/5 PASS; merge workspace @1e82651 claude/agy/grok/codex 4/4 PASS (identity: base 6fc9194 -> head 1e82651, evidence review-tree). Full suite @1e82651: 1037 passed, 1 skipped. Reports under .agents/reports/. Closes #25.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-21 15:38:21 +00:00
GodopuandClaude Fable 5.1 6b7198f73c release(v4.7.1): bump framework and eight skills to 4.7.1 in lockstep; archive PR #32 merge-side reviews
Issue #25: a promoted plan is reused only with --plan-file; the implicit
newest-plan load is gone in both runners, and an empty planner report no
longer passes silently. VERSIONS.md carries the entry; the four merge-side
review reports and their identity sidecars (base 6fc9194 -> head 1e82651,
evidence review-tree) are archived under .agents/reports/<session>/.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-22 00:38:10 +09:00
GodopuandClaude Opus 5 1e826515cc fix(issue-25): a relative --plan-file is taken against the control root, as its usage line says
Review R1/N1 (reviewer-grok-01, planner-reviewer-codex-01), reproduced before
fixing. The usage line and SKILL.md both promise "relative to the control
root", but parse_args did Path(...).expanduser().resolve(), which is relative
to the caller's cwd. The runner never chdirs to workspace_root, so the two are
routinely different - the documented recipe runs the loop from the control root
while the source root is a worktree.

Two ways it went wrong: a plan that exists only under the control root was not
found at all (exit 1), and a same-named file in the caller's cwd was loaded
instead, quietly putting an unrelated plan into the first implementation
prompt. That second one is the very failure #25 is about, reintroduced through
the option meant to replace it.

Resolve against workspace_root the way jobs_dir already does (Issue #21 R2);
pathlib's `/` leaves an absolute or expanded-home path untouched. Every earlier
test passed an absolute tmp_path, which is why none of them caught this: P3c
covers both failure modes with the control root away from the caller's cwd, and
P3d pins that absolute and ~ paths are not rewritten.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 05:17:50 +00:00
GodopuandClaude Opus 5 5fa592347c docs(issue-25): the loop skill documents --plan-file and the empty-report handling
The skill described the implicit load as a feature in five places. Replace them
with what the loop does now: nothing is loaded without --plan-file, the path is
relative to the control root, and the plan rides the first implementation
prompt only. Adds the CLI table row and a section on what an empty plan report
means at each of the four load points.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 03:26:44 +00:00
GodopuandClaude Opus 5 a334083760 test(issue-25): plan reuse is explicit only and empty plan reports are not silent (P1-P11)
P1 is the reproduction: a running planner plus a promoted plan in its report
directory must not reach the Creator. P2 pins that a named plan is used, that
the newer unrelated one is not, and that the plan rides only the first
implementation prompt - the correction round carries feedback alone, as the
implicit load did too. P3-P5 keep the option's checks in front of any job.
P6 keeps --plan mode and its promotion working.

P9-P11 cover the loads the review widened: an empty initial plan stops the run,
an empty discussion refine keeps the previous plan, and an empty escalation
refine leaves the "follow the updated plan below" prompt carrying the real one.
The existing _drive helpers hand every job the same non-empty PASS report and
so cannot reach these paths at all, so this module drives the loop with its own
stub that scripts a report per job. P7-P8 pin wrapper/runner parity, the legacy
shell refusal, and that neither implementation globs for a plan any more.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 03:26:44 +00:00
GodopuandClaude Opus 5 e551e3baf1 fix(issue-25): one plan-text check for every load; an empty planner report stops the loop, an empty refine keeps the plan
The --plan-file check landed on the one path a human is watching. The three
--plan-mode loads read a report written by another agent with nobody watching,
and had no content check at all: find_report only tests that the path exists.

An empty or whitespace-only report therefore blanked current_plan in silence.
Phase 2's `if self.current_plan` then flipped the prompt to self-planning and
the run finished rc 0, having paid for a planner job, a Creator challenge and a
refine job and thrown the result away. The escalation refine was worse: it has
no guard, so the correction prompt asserted "follow the updated plan below" and
carried nothing.

All four loads share _plan_text() now - a plan is a readable regular file with
text in it - and each caller says what None means. An empty initial plan stops
the run instead of demoting it, and an empty refine warns and keeps the plan it
already has, which is still good. Those two together leave the escalation
prompt unable to claim a plan it does not carry, so it needs no new branch.

Found by the Creator's challenge to the plan (job 0f63ac1d), sustained by the
Planner as revision 1.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 03:26:34 +00:00
GodopuandClaude Opus 5 a28711cccf fix(issue-25): reuse a promoted plan only with --plan-file; drop the implicit newest-plan load
Without --plan, Phase 1 resolved a planner session automatically and globbed
<workspace_root>/.agents/reports/<planner>/plan-*.md for the newest file by
mtime, handing it to the Creator as "the plan already agreed on". Both keys are
wrong: the report directory belongs to a session, not to this task, so other
issues' plans pile up in it, and right after a clone or checkout mtime is
checkout order. 47 such plans are committed in this repository, so an ordinary
run could silently implement against an unrelated design.

Reuse is explicit now. --plan-file <path> is the only way to load an existing
plan; it is resolved against the control root, checked before a single job
exists, and refused if the file is missing, not a regular file, unreadable or
empty (an empty file would quietly turn into a "no plan" prompt). It cannot be
combined with --plan, and --review-only warns and ignores it because no
implementation job is delegated there. The implementation prompt itself is
unchanged, so the Creator's contract does not move.

Phase 1 now says which plan it loaded and where from, or that it loaded none.
The legacy shell loop (MAM_LOOP_PY=0) loses the same auto-load and rejects
--plan-file rather than duplicating the check on a path that is on its way out.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-21 03:26:24 +00:00
GodopuandClaude Fable 5.1 6fc9194f89 merge: feat/issue-21-items-4-5-7 (Issue #21 phase 2: worktree helpers, review identity, acceptance A1-A8; #20 test isolation; #27; #28 host portability; v4.7.0)
Reviews: round 1 @46ea4cc claude/agy/grok PASS, codex NOT PASS (R1-R3) -> fixed in 08db1da; delta review @08db1da claude/agy/grok PASS, codex @80a5614 PASS. Reports archived under .agents/reports/.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-20 21:43:39 +09:00
GodopuandClaude Fable 5.1 cf5d1142e9 release(v4.7.0): bump framework and eight skills to 4.7.0 in lockstep; archive PR #29 reviews
Issue #21 items 4, 5, 7 (worktree helpers, review identity, acceptance
A1-A8), #20 test isolation, #27 .gitignore managed block, #28 host
portability. VERSIONS.md carries the entry; the eight review reports of
PR #29 (two rounds plus the codex re-review) are archived under
.agents/reports/<session>/.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-20 21:43:25 +09:00
GodopuandClaude Fable 5.1 80a5614f7c fix(issue-21): PR #29 delta review follow-up - prepare installs the delegate-job requirements, removes a half-made venv on install failure; prompt dirty flag sees untracked files
- worktree_prepare.sh installs the same files deploy/install.sh does
  (.agents/skills/multi-agent-mux-delegate-job/requirements.txt: paho-mqtt,
  PyYAML) plus requirements*.txt. Without paho the loop wrapper, stop_session
  and the subscriber tests fail in the worktree - seen as 4 suite failures
  in a worktree without its own venv, all passing with one.
- review D1: a failed pip install removes the venv it half made, so the next
  run recreates it instead of reporting VENV=kept (test w1c).
- review D3: the [worktree context] block's uncommitted-changes flag uses
  --untracked-files=all like the guards.
- review D2: the create skill doc says the install needs the package index.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-20 21:33:57 +09:00
GodopuandClaude Fable 5.1 08db1da9d5 fix(issue-21): PR #29 review R1-R3 - untracked-safe cleanliness checks; a worktree gets its own venv
R1/R2: `git status --porcelain` honours status.showUntrackedFiles, so a
`no` setting in a submodule (or the worktree) hid untracked files from the
checks that justify worktree_remove.sh's single --force and from the review
snapshot guard (_dirty_submodules), which then approved content it never
captured. All three checks (lib_py/worktree.py, worktree_remove.sh,
runner._dirty_submodules) now pass --untracked-files=all. The source tree's
own snapshot was already safe: `git add -A` ignores that setting.

R3: worktree_prepare.sh no longer links .venv to the control root's. It
creates the worktree's own venv with the control root's interpreter and
installs requirements*.txt; a leftover link is refused (exit 1), a control
root without an interpreter is a warning (VENV=skipped); VENV= is printed.

Tests: w1 (real venv, kept on re-run), w1b (link refused / skipped), w6e
parametrised over the hidden setting for the post-stop recheck, w6e2
(hidden untracked file in the submodule and in the worktree blocks the
removal), l17 untracked-hidden / during-hidden (guard refuses before the
first review; a mid-round hidden file makes the round stale). Each new
case fails without the fix.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-20 20:43:20 +09:00
GodopuandClaude Fable 5.1 90a289da44 test(issue-14): widen the wall-clock close margin under suite load
The close landed 8-9 s past the 20 s deadline in three full-suite runs on
this host (all passed alone); the pinned defect closed at ~2 x TIMEOUT,
so a 15 s margin keeps the test meaningful.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-20 19:49:37 +09:00
GodopuandClaude Fable 5.1 7a94ba2c3e test(issue-28): make the host-dependent tests portable; POSIX ps in the process scanners
The 33 failures on the Linux / Python 3.14 host (#28) were environment
dependencies, not regressions; each test is worth keeping, so fix the
dependency instead of deleting the test:

- test_workspace_scope: `source` under `shell=True` ran in dash; run the
  command string under bash.
- conftest autouse: MAM_ENV_FILE points at an absent file for every test,
  so a workspace .mam.env with a reachable broker no longer breaks the
  "broker unavailable" tests (T1-4).
- help-capture guard: compare normalized help text (whitespace collapsed,
  "optional arguments"/"options" unified) so argparse re-wrapping across
  Python versions is not drift.
- deploy freshness D-11..D-19 and D-22..D-30: skip with a reason when the
  nats-docker submodule is not initialized.
- lib_py.agents.base.conversation_in_use and heartbeat._process_table:
  `ps -eo pid=,ppid=,args=` (POSIX) instead of the BSD `-axo ... command=`
  form, the most likely cause of the 12 purge failures on Linux (the holder
  scan returned nothing); to be confirmed on that host.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-20 19:15:50 +09:00
GodopuandClaude Opus 5 46ea4cc1e4 test(issue-20): state isolation regression tests
S1/S2 per-test defaults and the mam_sandbox override, S3 submit with WORKSPACE_ROOT on a checkout leaves its .mam alone, S6 a nested pytest started with a pane's binding sees none of it (import-time copy included) and leaves the target untouched, S7 lib.sh takes the session registry from a test's WORKSPACE_ROOT.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Sdga4A8i1iSc8DaaW9iKU2
2026-09-15 02:02:52 +00:00
GodopuandClaude Opus 5 a2be70df1b test(issue-20): issue-15 leak checks judge only their own job ids and session
The onboarding tests compared whole listings of the repo's .mam, so a concurrent run's entries failed them. Session names are now unique per run; the check is that the sandbox's own job ids are absent from every real root (this checkout's and the recorded control plane's) and that no new entry there names the session. cli_defaults also checks that the audit log follows WORKSPACE_ROOT.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Sdga4A8i1iSc8DaaW9iKU2
2026-09-15 02:02:52 +00:00
GodopuandClaude Opus 5 c5844a8e12 test(issue-20): session guard for new entries in the recorded control planes' .mam/jobs and .mam/delegate_job_logs
Watches this checkout's .mam and the ones the recorded binding named. A new entry is a leak when it is an audit log without a registry record, or when its agent_session is missing or not a registered session; live delegations write the record first and target a registered session. Reports, never deletes. The #19 guard's docstring pointed at a #15 session guard that never existed.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Sdga4A8i1iSc8DaaW9iKU2
2026-09-15 02:02:52 +00:00
GodopuandClaude Opus 5 7bd695c209 test(issue-20): rec 4 - the in-process publish helper keeps its audit log in tmp_path
_job_for_inprocess_publish deleted DELEGATE_JOB_LOGS_DIR to fall back to the cwd, but an ambient WORKSPACE_ROOT comes first, so the audit log went to the real .mam/delegate_job_logs. It now keeps the per-test default and asserts the log is under tmp_path.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Sdga4A8i1iSc8DaaW9iKU2
2026-09-15 02:02:51 +00:00
GodopuandClaude Opus 5 3433ffdc41 test(issue-20): record and drop the ambient control-plane binding before collection; per-test default registry and audit-log roots
pytest_configure records WORKSPACE_ROOT, AGENT_SESSIONS_YAML, MAM_JOBS_DIR and DELEGATE_JOB_LOGS_DIR and drops the last three, plus WORKSPACE_ROOT when it names another checkout: a worktree creator's pane carries all four at the live main checkout, and each wins over a test's own WORKSPACE_ROOT. It runs before collection because test_orc_onboard copies os.environ at import. Every test then defaults MAM_JOBS_DIR and DELEGATE_JOB_LOGS_DIR to tmp_path/.mam-test-state; mam_sandbox and a test's own monkeypatch still override.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Sdga4A8i1iSc8DaaW9iKU2
2026-09-15 02:02:51 +00:00
GodopuandClaude Opus 5 b1e313be04 test(issue-21): item 7 acceptance cases A1-A8; design doc marks item 7 fixed in loop B (real herdr pane check stays in stage C)
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 22:34:12 +00:00
GodopuandClaude Opus 5 a21986ec3a fix(issue-21): loop B review follow-up - one verification target per review prompt, dirty submodules refused, identity self-review recorded like any verdict
- review jobs' [워크트리 컨텍스트] points at the [리뷰 identity] path only (B-2);
  remote re-adjudication gets a matching sentence (N-4)
- dirty/untracked submodule content fails the snapshot and makes a round stale,
  regardless of submodule ignore settings (B-R1)
- with --worktree/--base and no reviewer, the creator self-review takes the
  reviewer path: snapshot diff, evidence check, pre-promotion re-check and the
  identity sidecar; NOT PASS still re-reviews without a correction job (B-R2/B-R3)
- snapshot diff failures keep the UNAVAILABLE marker (N-1); prune only when
  worktree remove fails (N-3); the empty per-loop review dir is removed (N-5)
- tests L17-L21, B-2 assertions in L6/L11; SKILL.md env stale note; import order

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 22:34:12 +00:00
GodopuandClaude Opus 5 e6d2168a13 test(issue-21): L13 compares against the pre-change diff_collect only when git history is available
The byte-identity check of the two-argument form read the old script with
`git show 25f4be3:...`, which fails in a `git archive` export (no .git) and
failed the test there. The comparison now runs only when the old script can
be read; the two-argument path is otherwise still covered by
test_b7_diff_untracked. L13 passes in the repository and in an export.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 21:31:18 +00:00
GodopuandClaude Opus 5 371099a82c test(issue-18): rec 5 follow-up - acceptance5 accepts a delivery confirmed by the retained terminal event and skips when the dispatch never reached the broker
Two more failure modes seen on the public broker after the stale-dispatch fix:
- the runner served this run's job, but the broker delivered only the
  retained `completed` (not the non-retained `started`); the wrapper logged
  "advanced to 'completed'", which the test did not accept as delivery
  evidence although it is the same protocol evidence as "advanced to
  'running'";
- the orchestrator's dispatch publish failed with "no CONNACK from broker"
  and the runner never saw the job - an unreachable broker, the same kind of
  precondition as the existing skip when the runner cannot subscribe.
Everything else still fails. The test remains dependent on the public broker
(3 runs after this change: 2 passed, 1 failed with CONNACK retry warnings).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 21:03:38 +00:00
GodopuandClaude Opus 5 c01a1192c8 docs(issue-21): review identity and the remote-reviewer rule in the loop skill and the design doc
- loop SKILL.md: --review-isolation and --remote-review in the option table,
  a paragraph on review identity (snapshot, snapshot diff, stale re-review,
  pre-promotion re-check, report-<jid>.identity.json with evidence, nested
  repositories refused), and the remote-reviewer rule in the Issue #18
  remote-session section.
- design doc: the §2-C reviewer sentence describes the implementation; §5
  marks item 5 as loop B and says plainly that item 7's acceptance-case tests
  are not written yet; the §7 loop row states the remote-reviewer limit and
  that snapshot sharing is out of scope; a compatibility note for the
  --worktree/--base + remote-reviewer combination.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 21:01:09 +00:00
GodopuandClaude Opus 5 7bc3e1a288 test(issue-18): rec 5 - acceptance5 uses a fresh session and secret per run, widens the idle window, and skips only on proven broker non-delivery
The remote runner subscribes to every job's retained dispatch topic on the
public broker and serves the first dispatch signed for its session. With the
fixed session name `sim-worker` and a fixed secret, a stale retained dispatch
left by an earlier run verified fine and was served instead of this run's
job, which then timed out: in the observed failure the runner logged
`published started/completed ... job=5eb1abcf` and `DONE rc=0` while the
orchestrator waited on job 5ee3fbcf with nothing received. Each run now uses
a random session name and secret, so stale dispatches cannot match.

Also, per the plan: the no-event window is 10 x 2 s instead of 3 x 2 s, and a
failure skips only when the runner provably published `started` for the
orchestrator's own job, the orchestrator subscribed to that job's topic, and
received and dropped nothing for it (broker non-delivery). Every other failure
still fails. The runner's own `started --heartbeat` already covers the window.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 20:55:48 +00:00
GodopuandClaude Opus 5 e57663ac4c feat(issue-21): item 5 review identity - per-round snapshot and snapshot diff, detached review worktree (--review-isolation), stale-round re-review, identity records with evidence, pre-promotion re-check; remote reviewers refused or diff-only (--remote-review)
Active with --worktree/--base only; without them prompts, flow and promotion
are unchanged (a loop_id is recorded in the checkpoint either way).

- Every review round is pinned (B3): the source's HEAD and its working state
  as a tree built through a temporary index (the real index/status/refs are
  untouched); a dirty state becomes a ref-less snapshot commit on HEAD
  (committed as mam-loop, not as the user). An untracked nested repository
  cannot be pinned and is refused. identity = (loop_id, base, head, tree).
- Review isolation (B4): a detached review worktree of the snapshot under
  TMPDIR (default), or `--review-isolation env` (the source root with env and
  temp-dir instructions). Failing to open the tree refuses the round - the
  isolation is never lowered silently. Trees are removed after the round and
  on any exit (run() wraps the body; release_guard too).
- The reviewers' diff comes from the snapshot (B13):
  diff_collect.sh takes an optional head commit for a commit-to-commit diff;
  its two-argument form is byte-identical.
- Stale rounds (B7/B8): after the round the source is measured again; if it
  changed, the round's approvals are discarded and the next iteration
  re-reviews without a correction job (last iteration: rc 1). Only the last
  non-stale round's PASSes are promoted.
- Records (B9/B15): review_rounds in the checkpoint with per-reviewer
  transport/evidence, and report-<jid>.identity.json next to each promoted
  report: evidence review-tree | source-tree | diff-only.
- Pre-promotion re-check (B10): a source changed after approval is not
  promoted (rc 1).
- Remote reviewers (B14, Creator challenge 91c81095): they cannot reach this
  host's review tree. Checked before anything is delegated: refused by
  default; `--remote-review diff-only` admits them with the snapshot SHAs and
  diff as their only evidence (no local path in their prompt), and refuses a
  round whose diff is truncated or unavailable.
- run_loop.sh accepts both options (usage identical to the runner's); the
  legacy shell loop refuses them before the lock.

Tests tests/test_issue21_loop_b.py L1-L16 (22).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 20:54:53 +00:00
GodopuandClaude Opus 5 4ad622e372 test(issue-21): rec 3 - T2-6 isolates MAM_LOOP_WORKTREE/MAM_LOOP_BASE with monkeypatch
T2-6 set both variables in os.environ directly and restored them in a
finally block; a failing assertion between the two could still leak them to
later tests in the process. They are now set with monkeypatch.setenv (the
wt_repo fixture already delenvs both). The assertions are unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 20:54:53 +00:00
GodopuandClaude Opus 5 25f4be3359 fix(issue-21): review ec50fbe7 R6 - the unpushed check covers HEAD and every local ref (tags included, stash excluded) in both submodule checks
Both unpushed checks in lib_py/worktree.py - `submodule foreach` over the
initialised checkouts and the direct `--git-dir` walk over the repositories
under the worktree's modules/ - used `HEAD --branches --not --remotes`. A
commit made on a submodule's detached HEAD and kept only by a tag is reachable
from neither, the top-level status stays clean, and worktree_remove.sh then
deleted the repository with its single --force (exit 0).

Both checks now share one rev list, UNPUSHED_REVS = HEAD --exclude=refs/stash
--all --not --remotes: HEAD and every local ref (branches, tags, notes, ...)
minus remote-tracking refs. refs/stash stays out of it because the stash check
(stash list / reflog) owns it, so a stash is reported once, as 'stashes'. As
intended, a local-only note is now protected too. The stash, error, partial
repository and dirty checks are unchanged.

Tests W6l (tag-only commit; initialised submodule and deinit'd repository) and
W6m (annotated tag). The helper header, the stop SKILL.md and the design doc
state the wider rule.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 20:11:18 +00:00
GodopuandClaude Opus 5 c7c559b7aa fix(issue-21): reviews 8f141362 N1 and 275fdc4f R4/R5 - clean refusal for a broken worktree, no init over existing files, check retained submodule repositories
- N1 (planner-reviewer-claude-01) worktree_remove.sh: when `git status` fails
  in the worktree (e.g. its directory was deleted), judge_tree returned before
  METHOD was set and the summary line died under set -u with exit 1. METHOD
  now has its default before the function; the refusal is exit 3 with
  "nothing was changed", plus a `git worktree prune` hint when the directory
  is gone. Same for --dry-run.
- R4 (planner-reviewer-codex-01) worktree_prepare.sh: a submodule path that is
  not initialised yet but already holds files made the clone fail, and the
  rollback's `deinit -f` then deleted those files. --submodules now refuses
  such a path up front (new exit 3, nothing changed), which also makes the
  rollback's premise true: after a failed attempt, everything under a
  not-yet-initialised path was created by that attempt.
- R5 (planner-reviewer-codex-01) lib_py/worktree.py: `submodule foreach`
  visits initialised checkouts only, but a deinit'd submodule keeps its
  repository - stash and unpushed commits included - under the worktree's
  modules/, which the forced removal deletes. Every repository under modules/
  (nested ones included) is now checked directly (`--git-dir`): commits on no
  remote (HEAD included) and refs/stash with its reflog. A directory that looks
  like a partial repository cannot be checked and refuses.
- Also: the rollback loops are C-style (`seq 0 -1` counts down on BSD), and
  prepare warns that --base is ignored for an existing branch.

Tests W6i (deleted worktree directory, with and without --dry-run), W6j and
W6j2 (stash / unpushed commit in a deinit'd submodule's repository) and W6k
(existing files in an uninitialised submodule path). Skill docs and the design
doc describe the new refusal and the wider repository check.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 18:14:13 +00:00
GodopuandClaude Opus 5 bbbbb95ef6 fix(issue-21): review ffb5055e R1-R3 - re-check the tree after --stop, refuse submodule stashes, roll a partial submodule init back to a usable checkout
Review ffb5055e (planner-reviewer-codex-01):

- R1 [P1] worktree_remove.sh: the clean-tree and submodule checks ran only
  before --stop, so work a stopping session wrote (or committed, or stashed)
  was deleted by the forced removal. The checks are one function now, run
  before any change and again right before the removal; any finding then
  refuses with exit 3 (sessions already stopped, worktree kept), and the
  removal method follows that latest look.
- R2 [P1] lib_py/worktree.py: a submodule stash is reachable from no branch
  and leaves the status clean, and the forced removal deletes the worktree's
  own submodule repositories. `git stash list` in every submodule is a
  separate finding (`stashes`), refused like dirty/unpushed; errors fail
  closed as before.
- R3 [P2] worktree_prepare.sh: when one submodule cloned and a later one
  failed, the rollback deleted modules/ while the cloned checkout's .git file
  still pointed into it, and `git status` failed in the worktree. The rollback
  now undoes only this attempt: each submodule whose git dir did not exist
  before is deinitialised before its git dir is deleted; submodules
  initialised earlier are kept; shared submodule.* config values are restored
  exactly (new keys removed, pre-existing values put back - init and deinit
  both write .git/config). A final `git status` either confirms a usable
  checkout or prints what to inspect.

Tests W6e (a write during stop keeps the worktree and the file), W6f (a
submodule stash refuses), W6g (partial failure on a fresh worktree: usable,
no modules/, no new config, then prepare and a plain removal work) and W6h (a
failing retry keeps the earlier `sm` init and its config value). The skill
docs and the design doc describe the recheck, the stash rule and the scoped
rollback.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 16:57:39 +00:00
GodopuandClaude Opus 5 7988db9adf docs(issue-21): item 4 helpers, the submodule removal rule and the resume cwd rule in the design doc, compatibility matrix and skill docs
- design doc §3: the hand-assembled worktree/.venv/create recipe is replaced by
  worktree_prepare.sh --creator-agent (its BASE= line is the base to record);
  cleanup is worktree_remove.sh --stop; resume needs the original path.
- §4: what the helpers do - no .mam.env copy, the shared info/exclude, opt-in
  submodules (any init leaves modules/, which blocks a plain remove), removal
  of submodule worktrees with one --force after the checks, and never by hand.
- §5: item 4 is loop A on this branch; phase-1 items are done in v4.6.0.
- §7: create (control-root reconcile/watchdog, loud binding failure), resume
  (original cwd only, binding persisted when already running), stop (the
  removal helper's checks), monitor (register via create/prepare only).
- create / stop / resume SKILL.md: usage and exit codes of worktree_prepare.sh
  and worktree_remove.sh, the original-cwd rule and its exit code (1 -> 2).
  Frontmatter versions are unchanged.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 15:26:37 +00:00
GodopuandClaude Opus 5 657b4b70ed feat(issue-21): worktree_prepare.sh / worktree_remove.sh (opt-in submodules; judge before any change, single verified --force for submodule worktrees); create starts its reconcile and watchdog from the control root
- worktree_prepare.sh (create skill): idempotent `git worktree add` next to the
  control root (a path inside it is refused), .venv linked to the control
  root's, /.venv and .pytest_cache/ in the shared info/exclude, submodules only
  with --submodules - a failed init removes its own traces (modules/, new
  submodule.* keys in the shared config) and exits 1, since git refuses a plain
  `worktree remove` once modules/ exists - and an optional creator registered
  in the control root's .mam with MAM_NO_SUBSCRIBER_DAEMON=1. Prints BASE= for
  `run_loop.sh --worktree ... --base ... --review-only`.
- worktree_remove.sh (stop skill): every check first, nothing changed on a
  refusal (exit 3): linked and not locked, running sessions only with --stop,
  no open job of those sessions except the delegate jobs stop cancels, clean
  tree including submodules, and inside submodules no modification and no
  commit on no remote (HEAD included - submodules sit on a detached HEAD).
  Then stop, re-check jobs, and remove: plain, or a single --force when the
  worktree holds submodule state.
- lib_py/worktree.py: the parsing behind both (stdlib only).
- A8: create's immediate reconcile and watchdog use the control root's code
  and WORKSPACE_ROOT, not the worktree --workspace's copy.

Tests W1-W6d (local submodules allowed through GIT_CONFIG_* env only).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 15:24:10 +00:00
GodopuandClaude Opus 5 2679ddfffd feat(issue-21): resume only at the original cwd; persist the control-plane binding on the already-running path; fail loudly when a worktree binding cannot be computed
- A11: resume refuses (exit 2) a --workspace other than the row's pane.cwd, and
  a pane.cwd that no longer exists (checked first: mam_abs_workspace returns a
  missing path unchanged). Before, claude/grok failed with a misleading "No
  saved session" and class A agents started a new conversation in the wrong
  directory. Rows without pane.cwd are not checked.
- A12 (recommendation 1): create and resume no longer swallow a failed binding
  computation. A worktree (--workspace != control root) is refused with exit 2
  and nothing spawned or recorded; the control root itself warns and records
  the row without control_plane.
- A13 (recommendation 2): resume computes the binding before the herdr-alive
  check, so the already-running path records it too (update_yaml_resumed.sh
  fills a missing field only). Pane forwarding and the whitespace refusal stay
  on the spawn path.

Tests W7-W9.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 15:24:10 +00:00
GodopuandClaude Opus 5 fadd38cf56 fix(deploy): #27 - the managed .gitignore block ignores .venv as a file, directory or link
Both installers wrote `/.venv/`, which only matches a directory: a .venv
symlink (the worktree recipe links the control root's) or file showed up as
untracked in installed repositories. The managed block now has `/.venv`.
Existing installations get it on the next install/update, which rewrites the
block between its markers as a whole; the integrity values are unaffected
(.gitignore is in neither asset_hashes.txt nor the install manifest).

Tests W10 (both installers; .venv as link, file and directory all ignored) and
W11 (a pre-#27 block is replaced, user lines outside it are kept, .gitignore
stays out of the ledgers).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 15:24:10 +00:00
GodopuandClaude Opus 5 1134d74b38 fix(repo): untrack the committed .venv symlink and ignore .venv as a file or directory
d34b532 committed `.venv` as a symlink to
/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.venv, the merge
worktree's preparation link. `.gitignore` had `.venv/`, which matches
directories only, so the link was not ignored. Updating a checkout to main
then silently replaces its existing (ignored) .venv directory with that
link: a broken path on other hosts and a self-referencing link in the
original checkout. Untrack it and ignore `.venv` in both forms, which also
covers the worktree preparation link of the #21 operating model.

Also correct the release date at the top of VERSIONS.md to 2026-09-14 to
match the v4.6.0 entry. No code change; the version stays 4.6.0.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01PfoijjCS2U6TQPFuxAE5Pn
2026-09-14 14:20:38 +00:00
Godopu 70e36350b9 merge: feat/issue-21-worktree-prereqs (Issue #21 phase-1 prerequisites: absolute wrapper paths, loop --worktree/--base/--review-only, control-plane binding, design doc; v4.6.0)
Reviewed with [VERDICT: PASS] from claude, agy, grok (author-side loop) and codex; re-reviewed merge-side by claude, agy and codex at 4a81d15. Full suite at 4a81d15: 940 passed.
2026-09-14 12:54:13 +00:00
GodopuandClaude Fable 5.1 d34b532ccf release(v4.6.0): bump framework and eight skills to 4.6.0 in lockstep; archive PR #22 merge-side reviews
Issue #21 phase-1 prerequisites (PR #22) add loop runner options and the
control-plane module: MINOR. VERSIONS.md gains the v4.6.0 entry, the
archived design reviews lose their markdown trailing whitespace so
`git diff --check` is clean, and the three merge-side PASS reports
(claude, agy, codex @ 4a81d15) are archived under .agents/reports/.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-14 21:53:51 +09:00
GodopuandClaude Opus 5 4a81d15d95 test(issue-21): review N2 - T2-8 runs in mam_sandbox, so lib.sh's herdr shim never lands in the caller's control root
run_loop.sh sources lib.sh before it refuses --worktree/--base/--review-only
under MAM_LOOP_PY=0, and sourcing lib.sh runs _init_herdr_isolation, which
rewrites $WORKSPACE_ROOT/.mam/shim/herdr. T2-8 copied the caller's
environment as is, so that root was the caller's control root (normally the
real checkout). The test now requests mam_sandbox, pins WORKSPACE_ROOT to it
explicitly, runs from it, and asserts the shim was written there; the four
parametrized refusal cases and their three assertions are unchanged. No
product code changes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 08:09:29 +00:00
GodopuandClaude Opus 5 13259edb06 test(issue-21): h25 pins the revised env contract - with env flags the idle pane is skipped and the env rides on the pane-creation call
Review N1 (planner-reviewer-claude-01 50ae9fb0, planner-reviewer-codex-01
8779f4b4): af8a54c (R1) stopped reusing an idle pane when env flags are
present, because the old path put `env K=V ...` after `herdr agent start ...
--`, where herdr passes it to the agent executable as arguments. h25 still
required that old behaviour (idle pane reused, env in the agent command) and
failed. It now asserts the new contract instead: a pane split / workspace
create carries MY_TEST_FLAG=active and HERDR_WORKSPACE_ID as --env, the agent
does not land on the idle pane, and nothing env-like follows `--` in agent
start. Finding A's intent (env must not be silently lost) is kept; reuse
without env flags stays pinned by h24. No product code changes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 05:45:12 +00:00
GodopuandClaude Opus 5 af8a54c028 fix(issue-21): review R1-R3 - no env as agent arguments on a reused pane, one jobs dir for a relative MAM_JOBS_DIR, stop keeps the audit-log root
Review 9a1adb46 (planner-reviewer-codex-01):

- R1 [P1] lib.sh new-session: a forwarded binding reached the agent as
  arguments. With env flags the idle-pane branch prefixed `env K=V ...` to
  the command that `herdr agent start ... --kind <agent> -- <args>` passes to
  the agent executable. An idle pane is now reused only when no environment
  has to be set; otherwise the pane is created by pane split / workspace
  create, which take --env. The dead `env` prefix code is removed (its
  send-text fallback would have typed the same line).
- R2 [P2] runner: a relative MAM_JOBS_DIR is resolved once against the
  control root, the way the wrapper (cwd=workspace_root) reads it, and that
  absolute dir is used for delegation, wait, report lookup and cleanup.
- R3 [P2] stop: the row's control_plane.delegate_job_logs_dir is restored
  (exported unless the caller set DELEGATE_JOB_LOGS_DIR), so the
  cancellation history lands in the row's audit-log root.

Tests: T3-1 and T3-3 now assert that the binding arrives as --env on the
pane-creation calls and that no env/K=V token follows `--` in agent start
(fresh and reused pane); T3-4c (audit root on stop) and T2-15 (relative
MAM_JOBS_DIR) are new. The design doc's compatibility table and a create
comment no longer describe the removed idle-pane env path.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 05:00:02 +00:00
GodopuandClaude Opus 5 b61c8b177a docs(issue-21): correct the worktree design doc - partial support, phase-1 review-only flow, compatibility matrix
Fixes the sentences the four design reviews flagged and records what phase 1
actually implements: status line, monitor-topic scope, option A's isolation
and capacity wording, creator/reviewer ownership (tests write; promotion is
the control root's), the control-plane binding persisted and forwarded, two
loop recipes ((a) the loop implements, (b) the base recorded before an
out-of-loop implementation, then --base --review-only; no base in --task),
the loop lock as a refusal, "phase 1 = parallel implementation, one review
loop", the eight Issue #21 items with their status, and a new section 7 with
root definitions and a per-skill compatibility table. The review files are
unchanged. The loop SKILL.md lock note names the lock branch instead of line
numbers that moved.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 03:34:48 +00:00
GodopuandClaude Opus 5 ee1d8966c1 feat(issue-21): persist and forward the control-plane binding in create/resume/stop; status and reconcile honor MAM_JOBS_DIR
A session row now records the control plane it belongs to, and the pane
gets it explicitly instead of relying on env inheritance.

- lib_py/control_plane.py (+ thin lib.sh wrappers mam_control_plane_json /
  mam_control_plane_prefix): the binding is WORKSPACE_ROOT,
  AGENT_SESSIONS_YAML, MAM_JOBS_DIR, DELEGATE_JOB_LOGS_DIR as absolute paths.
- create: the binding is always persisted on the row (`control_plane`) and
  forwarded to the pane only when it differs from what --workspace alone
  implies, as leading K=V tokens that lib.sh's new-session already turns into
  --env (fresh pane) or `env K=V` (reused idle pane). pane.cmd_full and
  start_command stay unprefixed. A binding with whitespace that would have to
  be forwarded is refused with exit 2 (lib.sh splits the flags unquoted); the
  ~/.local/bin wrapper path records the binding but warns it is not forwarded.
- resume: the row's binding wins over the caller's env (a difference is
  reported on stderr) and is forwarded again; a legacy row without one uses
  the caller's binding and update_yaml_resumed.sh records it.
- stop: registry order MAM_JOBS_DIR > the row's mam_jobs_dir >
  $WORKSPACE_ROOT/.mam/jobs > .mam/jobs, exported for delegate_publish_event.
- status: both get_job_status copies look in MAM_JOBS_DIR, the row's
  registry and the matching audit logs before the old candidates.
- reconcile: MAM_JOBS_DIR wins in the subscribe heredoc and is passed in.

Tests T3-0..T3-8 (mock herdr: forwarding is verified at the herdr-call level
only; real pane env propagation is left to item 7). T3-7 is a static guard.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 03:34:48 +00:00
GodopuandClaude Opus 5 d907359746 feat(issue-21): loop runner --worktree/--base/--review-only with a fail-closed empty change-set guard; control plane stays in the main checkout
- --worktree <path> (CLI over MAM_LOOP_WORKTREE): the source root. Only the
  diff, base, head and the empty-set check use it; the wrapper, registry,
  checkpoint, loop guard, promotion and cleanup stay on the control root. The
  collector is the control root's diff_collect.sh (never the worktree's
  unreviewed copy), its arguments shlex-quoted. Validation: an existing
  directory, the top of its working tree, the same git common dir as the
  control root (".git" is resolved against the directory it came from).
- --base <ref> (CLI only, no env - a stale sha would silently widen the next
  range): resolved to a full sha, must be an ancestor of the source HEAD.
- --review-only: requires --base, refuses --plan; Phase 2 is skipped and
  logged; correction and comply jobs still go to the creator.
- With --worktree or --base every delegated prompt starts with a context
  block (path, branch, base and its origin, head, base..head commit count,
  uncommitted changes); without them prompts are byte-identical. All call
  sites in run() go through one _dispatch helper.
- Fail-closed guard (only with --worktree/--base): before each review round,
  self-review included, an empty change set or one git cannot determine
  (exit codes, never output parsing) ends the loop with rc 1 instead of
  asking for reviews. This closes the fail-open where a loop started after
  an out-of-loop commit sent reviewers "(no changes since base commit)".
- The runner honours MAM_JOBS_DIR and passes --registry-dir to the wrapper.
- run_loop.sh accepts the three options; the legacy shell loop
  (MAM_LOOP_PY=0) refuses them before the freeze and the loop lock.

Tests T2-1..T2-14.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 03:21:43 +00:00
GodopuandClaude Opus 5 d3d3a76c83 fix(issue-21): absolute brief, start-command registry, audit-log root and report paths in the delegate-job wrapper
The injected prompt, the start/success/error commands and the brief's Output
Report Path used cwd-relative `.mam/jobs/...`, and the wrapper ignored
MAM_JOBS_DIR. A creator whose cwd is a git worktree could not run them as
written, and its audit log fell back to <cwd>/.mam/delegate_job_logs.

- REGISTRY_DIR defaults to ${MAM_JOBS_DIR:-.mam/jobs} and is made absolute
  right after `cd "$WORKDIR"` (a relative value still resolves against WORKDIR)
- the publish command is shell-quoted (printf %q) and prefixed with
  DELEGATE_JOB_LOGS_DIR=<abs>, resolved by the same get_logs_dir() the
  wrapper's subscriber uses; the heartbeat timer inherits it
- direct and loop jobs share one _instructions helper; brief and report paths
  are $REGISTRY_DIR/$JOB_ID/... (absolute)
- create --onboard: absolute publish_event.py, --registry-dir and log root

Tests T1-1..T1-5 (a space in the control root, commands run from another cwd
with no workspace env).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017R3Eg7MEpSWnm1oB9ZPP6G
2026-09-14 03:20:27 +00:00
GodopuandClaude Fable 5.1 dcf2fab06e docs(design): archive the four design reviews of the worktree operating model
claude, agy, grok: PASS with amendments; codex: NOT PASS (recipe overstates
current env-override support; review identity and lifecycle ownership
underspecified). Direction (creator per worktree, shared reviewer pool)
agreed by all four.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-14 11:14:07 +09:00
GodopuandClaude Fable 5.1 fe96db1d96 docs(design): propose the worktree operating model - creator per worktree, shared reviewer pool
Design proposal for review (no code change): why the checkout-path
workspace assumption blocks parallel issues and caused the #18 checkout
switch, three candidate models, the recommended hybrid (writers isolated
per worktree, readers shared, one .mam control plane via env overrides),
how it maps onto today's scripts, what has to change, and the questions
put to the reviewers.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-14 10:10:49 +09:00
GodopuandClaude Fable 5.1 5611859930 docs(reports): archive v4.5.0 PASS review reports (Issue #18)
Final HEAD 263d6bf: claude, agy and grok PASS (delta review of the
lifecycle-lock commits on top of their ab842f1 PASS), codex PASS (its own
round after F1/F2). Full suite at 263d6bf: 906 passed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-14 01:30:28 +09:00
GodopuandClaude Opus 5 263d6bf30d fix(issue-18): let an exiting heartbeat timer skip the busy lifecycle lock; kill a timer whose pid cannot be recorded
Review round 5 (planner-reviewer-codex-01, NOT PASS at 2b1d590):

- F1 bounded lock cycle: the stopper holds the per-job lifecycle lock while
  it waits for the timer to exit, and the timer's exit cleanup waited for
  that same lock, so every stop ran out the drain and ended in SIGKILL with
  a false "did not drain" warning. The exiting timer now tries the lock
  without blocking (lifecycle_lock(blocking=False)); when it is busy the
  ownership operation holding it removes the pidfile, and when it is free
  the own-pid comparison is kept.
- F2 untracked owner: when writing the new timer's pid fails after the
  spawn, _spawn_timer_locked kills and reaps that exact process while the
  lock is still held and drops only a partial pidfile of that attempt,
  then re-raises.
- tests: an idle timer stops well before a 10 s drain without SIGKILL;
  a pidfile failure after spawn leaves no survivor, no pidfile and a free
  lock (both fail on 2b1d590); a spawn failure leaves nothing behind and
  the next start works.
- docs: MESSAGING 2.5 and VERSIONS item 1 describe the lifecycle lock;
  VERSIONS test count 31.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-14 00:39:10 +09:00
GodopuandClaude Fable 5.1 2b1d590010 fix(issue-18): serialize the heartbeat timer lifecycle per job
Review round 4 (codex R3): two concurrent `start_timer` calls for the same
attempt both passed the "no timer" check, both spawned, and the pidfile
tracked only one - the untracked timer could still publish a retained
`running` after `completed`. A per-job flock (`<job>.heartbeat.lock`,
separate from the registry/seq lock so in-flight beats can still take
their seq) now makes observe/drain/spawn/publish-pid one ownership
operation; the terminal stop takes the same lock; a start that finds the
attempt ended (terminal record or raised barrier) does not arm; the timer
removes its own pidfile only under the lock so a replacement's pid is never
deleted. Regressions: concurrent starts leave exactly one tracked owner that
the terminal stop drains; a start after the barrier arms nothing.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-14 00:25:20 +09:00
GodopuandClaude Opus 5 ab842f1ee0 fix(issue-18): drain the previous heartbeat timer before handing over its pidfile
Review round 3 (planner-reviewer-codex-01, NOT PASS R3 at 7e1d3f0):
start_timer stopped a running timer with a bare TERM and overwrote the only
pidfile. A beat the old timer had already admitted - seq taken, recorded on
disk, held at the wire - stayed alive but undiscoverable, so a later
terminal publish drained only the replacement and the old beat could still
put a retained `running` on the broker after `completed`.

- heartbeat.start_timer: stop_timer(drain=MAM_HEARTBEAT_DRAIN_S). The old
  timer is drained or killed, and confirmed gone, before the pidfile names
  the new one. A terminal publish racing the replacement either drains the
  same old pid or meets a new timer whose beats the barrier refuses.
- test: an old timer held at the wire after admission is replaced, then
  the job completes; the old timer is gone before the handover and nothing
  it held follows the terminal (fails on 7e1d3f0).
- docs: MESSAGING 4.3 no longer says any state resets the idle clock;
  MESSAGING 2.5 and VERSIONS state the replacement rule; test count 26.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 23:43:48 +09:00
GodopuandClaude Fable 5.1 7e1d3f0815 fix(issue-18): the wrapper's subscriber waits for the first event up to the wall clock
The subscriber is started before the injection, and the injection itself
(idle handshake, quiescence, delivery grace) can take tens of seconds, so
a first-event budget of T + K x N measured from the subscription could
expire before `started` was even possible. The wrapper now passes
--ack-timeout <wall clock>: it judges delivery with _wait_started (T from
the injection) and reaps the subscriber on failure; K x N applies from the
first event on. A standalone subscriber keeps T + K x N. Documented in
MESSAGING.md 4.3.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 21:08:26 +09:00
GodopuandClaude Opus 5 135d76f903 fix(issue-18): admit remote attempts atomically, end timed-out commands with their group, fence heartbeats off the terminal, renew liveness only on news
Review round 2 (planner-reviewer-codex-01, NOT PASS at d09c162):

- R1 remote.mirror_job: admission under the registry lock. The same
  dispatch_token is idempotent (a finished attempt never runs again), a
  lower attempt or the same attempt under another token is refused before
  any write, and only a strictly newer attempt replaces the record
  (register_job(supersede_older_attempt=True); events.log kept, seqs stay
  monotonic).
- R2 remote.handle_dispatch: the --exec command runs in its own session;
  at timeout_sec, or when the runner is interrupted (SIGTERM now unwinds
  it), the whole process group is terminated (TERM, then KILL) before the
  error is published.
- R3 terminal barrier: a terminal publish raises an attempt-scoped barrier
  under the lock that allocates seqs, stops the heartbeat timer, gives it
  MAM_HEARTBEAT_DRAIN_S (default 1 s) to exit and then kills it, and only
  then takes its own seq. Beats are admitted under that lock
  (next_seq(admit=...)); a beat still on the wire is cancelled with the
  timer rather than holding the terminal back; and a late non-terminal
  event never publishes a running state over a terminal record.
- R4 job_subscriber: a retained state renews the idle clock only when its
  seq is newer than everything already accepted; re-delivered or older
  snapshots still recover a terminal status.
- tests: five regressions, all failing on 77f2829; T1-14's wall clock
  15 -> 30 s against public-broker latency.
- docs: MESSAGING 2.5 (barrier, state renewal, detection vs final close),
  heartbeat docstring, loop SKILL.md (remote rows need the Python runner),
  VERSIONS v4.5.0 items 1/4/5 and the test count (25).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 20:49:56 +09:00
GodopuandClaude Fable 5.1 77f2829b8e fix(issue-18): default ack timeout T = 180 s
In the v4.5.0 review round grok read the brief and published `started`
70 s after the injection; with T = 60 the wrapper had already closed the
job as agent_blocked and refused its later PASS. T bounds delivery, not
work, so a generous default costs nothing when the agent answers fast.
Code, docs and the CLI snapshot updated together.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 20:17:51 +09:00
GodopuandClaude Fable 5.1 d09c1627ce test(issue-18): measure the wall-clock close on the record and widen the loop worker's wall clock
Both tests ran against the public broker with second-scale budgets: the
error publish after the close can take 10-20 s, and a worker's `started`
must land before a 12 s wall clock. Assert the close time from the record's
updated_at and give the loop scenario a 30 s wall clock.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 19:56:37 +09:00
GodopuandClaude Fable 5.1 0550320590 fix(issue-18): bind the heartbeat timer to the agent process; scope started to the attempt; ignore re-sent finished dispatches
Review round 1 (claude NOT PASS) corrections:
- B2: the timer now watches a process - `--watch-pid`, or by default the
  nearest agent-CLI ancestor of the publishing command - and stops within
  one period once it is gone, so a crashed agent stops heartbeating and is
  closed after K x N; a remote runner watches itself. Documented as process
  liveness (an alive-but-stuck agent keeps heartbeating).
- R1: `_wait_started` accepts an events.log `started` only when it carries
  the current dispatch token (loop jobs share one events.log).
- R2: the remote runner ignores a re-sent dispatch of an attempt that
  already reached its terminal.
- R3: registry.md EOF blank line (git diff --check clean).
- R4: the ack error states the effective budget when the wall clock cut it.
- P3: stop_timer verifies the pidfile pid is this job's timer before
  signalling; a retained state message keeps its own seq watermark so it
  can never make the monotonic guard drop its own event.
- MULTI_AGENT_RULES.md timeout section updated for the contract.
- tests: agent-process death stops the timer, recycled-pid safety,
  attempt-scoped started, re-sent dispatch; acceptance 3 now kills the
  agent process instead of the timer. Help captures refreshed
  (--watch-pid). The wrapper can be sourced with
  MAM_DELEGATE_JOB_NO_MAIN=1 for helper-level tests.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 19:48:03 +09:00
GodopuandClaude Fable 5.1 c17c87439d test(issue-18): acknowledge with started in the remaining working-agent scenarios; refresh the subscriber help capture
T1-14 and T1-20 model an agent that goes `working` and completes late. Under
the liveness contract an agent that never publishes `started` is a delivery
failure, so the watcher threads now acknowledge (non-blocking: the record
lands in events.log before the wire publish) and the late completion is
honoured inside the K x N grace as before. help-job_subscriber.txt records
the intended --ack-timeout option.

Full suite at 66f23c7: 888 passed, 3 failed (these), 0 leaked daemons.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 19:43:16 +09:00
GodopuandClaude Fable 5.1 66f23c7cbd release(v4.5.0): bump framework and eight skills to 4.5.0 in lockstep
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 19:06:12 +09:00
GodopuandClaude Fable 5.1 897b505266 feat(issue-18): decide liveness and delivery by the event protocol, not the screen
Contract (no new event types): heartbeat every N s (automatic timer),
unresponsive after K x N s without an event, `started` within T s of the
injection, retained per-job state, and a remote transport.

- registry: heartbeat_sec / heartbeat_misses / ack_timeout_sec / transport
  fields; idle_timeout_sec derives K x N unless explicit (defaults 30/4/60
  keep the historical 120 s idle window).
- heartbeat.py + publish_event --heartbeat N: detached fixed-cadence timer
  publishing signed `progress` heartbeats (threaded wire publish, local
  record first); stopped by the terminal event via pidfile, by re-dispatch
  and by lifetime. Terminal events refuse --heartbeat.
- publish_event: retained `<prefix>/state` (status, last_event, seq, HMAC)
  sent on the same connection after every event (--no-state to skip);
  publisher.publish_raw takes extra messages.
- job_subscriber: subscribes the state topic, recovers terminal status from
  retained state, resets idle on any accepted message, records seq_gap and
  reconnected in the audit log, idle budget before the first event is
  T + K x N (--ack-timeout), --remote mirrors started/terminal events into
  the registry through the transition boundary.
- lib.sh send_keys_safe: an accepted-but-unconfirmed submission is confirmed
  by agent_status working or the job's own `started` (_sks_job_started);
  pane change and busy token are no longer delivery signals.
- wrapper: --heartbeat/--heartbeat-misses/--ack-timeout (MAM_* env),
  injected start command arms the timer, brief states the contract,
  _wait_started (registry / events.log / subscriber log, bounded by T and
  the wall clock) replaces the 10 s inject grace, R1 grace uses only the
  on-disk event age (herdr/pane logged once as a diagnostic),
  remote:<name> sessions skip preflight/idle/pane and dispatch over the
  broker (remote_dispatch).
- remote.py (+ scripts shim): signed retained dispatch (MAM_DISPATCH_SECRET)
  and a runner that mirrors the job into its own registry with the
  orchestrator's identity, publishes started --heartbeat, runs --exec and
  publishes the terminal event.
- loop runner: passes MAM_HEARTBEAT_SEC / MAM_HEARTBEAT_MISSES /
  MAM_ACK_TIMEOUT_S through; YAML rows with transport: remote delegate as
  remote:<name>.
- docs: MESSAGING.md 2.5 contract + remote transport, delegate-job SKILL.md,
  registry.md, loop SKILL.md.
- tests: tests/test_issue18_liveness_contract.py (16); issue 14 pane-signal
  tests flipped to started-based; issue 6 working-agent tests acknowledge
  with started; CLI snapshot/help captures refreshed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 19:06:12 +09:00
GodopuandClaude Fable 5.1 139bdd4b4c merge: fix/issue-19 (Issue #19 subscriber daemon lifecycle: sandbox opt-out and reaper, self-termination, SIGTERM forwarding; v4.4.5)
Reviewed with unanimous [VERDICT: PASS] from claude, agy, grok and codex
(round 3 at 134fe97). Full suite at 1bd643e: 875 passed, 0 leaked daemons.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 18:24:55 +09:00
GodopuandClaude Fable 5.1 1bd643e979 docs(reports): archive v4.4.5 unanimous PASS review reports (Issue #19)
Round 3 at 134fe97: claude, agy, grok and codex all PASS.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 17:54:52 +09:00
GodopuandClaude Opus 5 134fe9704c fix(issue-19): arm the subscriber's stop handlers before it connects; read $! with nounset off
Review round 3 (reviewer-grok-01, NOT PASS N1; non-blocking B1):

- reconcile.sh (N1): the python subscriber installs its SIGTERM/SIGINT
  handlers before connect/loop_start. A signal during the broker handshake,
  the CONNACK wait, or right after the paho thread logs "subscribed to" now
  takes the clean path (the signal line, loop_stop/disconnect, rc 0) instead
  of Python's default action; the CONNACK wait ends on it, and a signalled
  subscriber never falls back to polling (rc 3).
- reconcile.sh (B1): `_sub_stop` reads `$!` with nounset off. On bash 3.2
  `${!:-}` and `${!+x}` are both unbound before the first `&`, so the trap
  died with rc 1 instead of 143.
- tests: SIGTERM during a CONNACK wait against a silent local listener (no
  broker needed), and the verbatim `_sub_stop` run without and with a
  child; both fail on 8f9745b.
- docs: monitor SKILL.md and VERSIONS.md state the handler order; test
  count 16.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 17:22:39 +09:00
GodopuandClaude Opus 5 8f9745b128 fix(issue-19): match the daemon's whole script path so spaced sandbox paths are reaped
Review round 2 (planner-reviewer-codex-01, NOT PASS P2):

- conftest `_is_subscriber_daemon_argv`: `ps -o args=` joins argv unquoted,
  so the script path is taken from the shell word up to the first
  `/reconcile.sh --subscribe` instead of as one whitespace token. A sandbox
  or --basetemp path with a space no longer hides its daemon from the
  fixture reaper and the session leak guard. A candidate with whitespace
  counts only when it names an existing file, so a bash wrapper under the
  root whose later argv carries the words is still excluded.
- tests: a whitespace-path selector regression and an owned live-process
  cleanup check (both fail on c096cb4); the R-2 test also pins the bash
  wrapper exclusion.
- docs: the polling fallback's signal handling is stated precisely in
  monitor SKILL.md and VERSIONS.md (a running --once pass finishes first,
  the interval's sleep child ends on its own); create SKILL.md says an
  already-running daemon's PID is still reported under the opt-out;
  VERSIONS selector wording and test count (14).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 16:36:16 +09:00
GodopuandClaude Fable 5.1 c096cb455b fix(issue-19): close the trap race, select daemons by argv shape, align docs with the polling fallback
Review round 1 (claude PASS, agy PASS) recommendations:
- reconcile.sh: `_sub_stop` falls back to `$!` for the window before
  `_sub_pid=$!` (R-1); lock identity compared as (st_dev, st_ino).
- lib.sh legacy start_watchdog prints nothing when opted out and no daemon
  runs, byte-identical to the python body.
- conftest/test: `_is_subscriber_daemon_argv` selects only
  `bash|sh <root>/.../reconcile.sh --subscribe`, never a brief-carrying
  wrapper that quotes the words or a prefix-colliding sibling root (R-2);
  one new unit test for the selector.
- monitor SKILL.md / VERSIONS.md: the polling fallback checks the lock
  file's presence only and does not exclude a second daemon; measurement
  wording uses the argv-shape criterion instead of raw pgrep.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 16:11:53 +09:00
GodopuandClaude Fable 5.1 4da4a50682 test(issue-19): run the sandbox reaper through an import-time Popen
The reaper executes in fixture teardown, before monkeypatch restores a
test's patches; G5 forbids subprocess.run/Popen for the test's duration and
subprocess.run resolves Popen through the module at call time, so the
teardown tripped the spy. Bind the Popen class at import instead.

Full suite at 38d8ccb: 870 passed, 1 error (this teardown), 0 leaked daemons.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 16:09:28 +09:00
GodopuandClaude Fable 5.1 38d8ccb316 release(v4.4.5): bump framework and eight skills to 4.4.5 in lockstep
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 15:35:33 +09:00
GodopuandClaude Fable 5.1 ce315d8c5e fix(issue-19): bound the subscriber daemon to its workspace, forward SIGTERM, keep sandboxes from leaking it
create_session.sh detaches `reconcile.sh --subscribe --idle-timeout 0` per
workspace; test sandboxes never reaped it and the daemon neither noticed its
workspace vanish nor honoured SIGTERM (bash deferred the signal behind the
foreground python child). 202 orphans were found holding public-broker
wildcard subscriptions for deleted pytest tmpdirs.

- daemon.py / lib.sh: MAM_NO_SUBSCRIBER_DAEMON=1 (literal) skips the spawn but
  still reports a running daemon; cli prints a stderr note, stdout stays empty.
- reconcile.sh: python subscriber runs as a waited background child with a
  TERM/INT trap (exit 143); the MQTT loop exits when the workspace dir is gone
  or .mam/monitor.lock is no longer the held inode; SIGTERM/SIGINT handled via
  the stop event so loop_stop/disconnect run; the polling fallback checks the
  same and sleeps in a waited child.
- conftest: sandbox default MAM_NO_SUBSCRIBER_DAEMON=1, per-sandbox reaper
  finalizer, session-scope leak guard over the pytest basetemp.
- tests: 11 lifecycle tests (tests/test_issue19_subscriber_daemon_lifecycle.py);
  phase-1 watchdog/daemon characterization tests opt back in.
- docs: monitor SKILL.md lifecycle contract + pitfalls, create SKILL.md note.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 15:34:56 +09:00
GodopuandClaude Fable 5.1 8e7282c948 merge: fix/issue-12-8-7 (Issue #12 registry secrets, #8 update.sh install stamps, #7 sibling-workspace packing; v4.4.4)
Reviewed with unanimous [VERDICT: PASS] from claude, agy, grok and codex.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 15:00:17 +09:00
GodopuandClaude Fable 5.1 c714323dcf docs(reports): archive v4.4.4 codex PASS review report (Issues #12, #8, #7)
Reviewed HEAD fbe2731 against base 8a09e02; 242 selected tests passed.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 15:00:05 +09:00
GodopuandClaude Fable 5.1 fbe2731980 test(issue-14): decouple the disk-heartbeat wrapper test from broker latency
The test blocked on each publish_event heartbeat, and against the public
broker a publish (with retries) takes 2-6 s, so consecutive events.log
records landed further apart than the 6 s idle window and the wrapper
closed the job before the next heartbeat - a broker-latency flake that
failed the full suite once and passed on re-run.

Heartbeats are now fired without waiting for the wire publish (the disk
record is written before the broker is touched, ebe58f6) and keep coming
for 20 s to outlast a slow connect; the wall clock is widened to match.
3/3 green in a row afterwards.

Refs #14

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 13:24:30 +09:00
GodopuandClaude Fable 5.1 9d52bb7024 docs(reports): archive v4.4.4 PASS review reports from claude, agy and grok (Issues #12, #8, #7)
Second-round reports of the fix/issue-12-8-7 review loop on ea911d7:
planner-reviewer-claude-01 (b368210a), reviewer-agy-01 (3f5d1cd4) and
reviewer-grok-01 (cc059645), all [VERDICT: PASS]. The codex review is
deferred until its usage limit resets; the branch merges only after it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 12:47:31 +09:00
GodopuandClaude Fable 5.1 ea911d7842 fix(issue-8,7): harden install_state merge and pin sibling-workspace edge cases
Round-1 review of 4176d75 (planner-reviewer-claude-01, non-blocking):

- update.sh: merge install_state by exact key match (awk, no regex
  interpretation of the key), skip lines without '=', and terminate a fresh
  install_state that lacks a final newline before appending
- tests (#7): an agent-less pane left behind in a later same-cwd workspace
  is reused instead of splitting or creating; MAM_WS_LABEL renames only the
  workspace that was chosen

Refs #8 #7

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 12:15:26 +09:00
GodopuandClaude Opus 5 0fedae2f46 fix(issue-12): scrub-secrets selects only records with a stored password
Review of 4176d75 (planner-reviewer-claude-01, N1): _cmd_scrub_secrets chose
records by the presence of broker.password, not by its value. The old
to_registry_block wrote "password": null even for an unauthenticated broker,
so on this repo's registry (901 of 903 records carry the null key, none a
real password) --dry-run reported "would scrub 901 record(s)" and a real run
would rewrite every one of them while holding the registry lock.

- registry.py: select on broker.get("password"); an empty key is no secret,
  and _atomic_write_record drops it on the record's next write anyway
- tests: the migration test gains a legacy "password": null record that must
  be neither listed nor rewritten (fails on 4176d75 with "would scrub 2")
- VERSIONS.md v4.4.4 item 2 and registry.md now describe the stored-value
  rule

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 12:07:42 +09:00
GodopuandClaude Opus 5 4176d7570f release(v4.4.4): bump framework and eight skills to 4.4.4 in lockstep
PATCH release for the fix/issue-12-8-7 branch (Issue #12 broker password
kept out of job records, #8 fresh install stamps kept on update, #7
same-cwd workspaces packed). No code logic changes.

- lib.sh MAM_VERSION, lib_py/loop/eager.py FRAMEWORK_VERSION and the eight
  SKILL.md frontmatters (create, stop, resume, status, monitor, delegate-job,
  loop, orc-onboard) move from 4.4.3 to 4.4.4
- VERSIONS.md: current release v4.4.4 (2026-09-13 KST), the eight-row skill
  matrix, and a v4.4.4 changelog section in the v4.4.3 format covering the
  password-free registry block restored from MQTT_PASSWORD at connect time,
  the scrub on every record write, `registry.py scrub-secrets [--dry-run]`,
  why auth_token/dispatch_token stay, the update.sh stamp and install_state
  merge rules, the sibling-workspace walk in new-session, and the 8 new tests
- VERSIONS.md v4.4.3 ledger correction: its new-test count predated fae70c1,
  which added two purge tests; now 26 (19 + 7) with both listed
- README, README.ko, BOOTSTRAP and BOOTSTRAP.ko badges and the MESSAGING.md
  "Applies to" header follow the current version; historical 4.4.3 mentions
  (v4.4.3 changelog, reviewer reports) stay as history

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 11:30:33 +09:00
GodopuandClaude Fable 5.1 e629cc137f fix(issue-12,8,7): keep broker password out of records, keep fresh install stamps, pack sibling workspaces
Issue #12 - MQTT_PASSWORD was copied into every job record, which any
sub-agent can read. BrokerConfig.to_registry_block no longer persists it;
broker_config_from_job layers the password back from the environment
(.mam.env) at connect time, so publish_event still connects from the record.
_atomic_write_record scrubs broker.password from any record it writes, and
`registry.py scrub-secrets [--dry-run]` migrates an existing registry.
auth_token/dispatch_token stay: the agent's own publish_event needs them.

Issue #8 - update.sh restored the pre-update asset_hashes.txt and version.txt
over the installer's fresh ones, so version.txt named the previous commit and
remove.sh backed up every pristine updated file as "locally modified". The
success path now keeps the installer's stamps and only merges install_state
keys the re-install did not write (gitignore_created); the failure path
still restores everything verbatim.

Issue #7 - the shim's new-session took the first same-cwd pane, always found
the full first workspace, judged it overflow and opened another workspace per
agent (4 + 1 + 1). It now walks every same-cwd workspace in pane order and
takes the first with an idle pane or room in its 2xK grid; a workspace is
created only when all are full (4 + 2).

Tests: test_issue7_workspace_packing.py (3; the mock herdr gains an opt-in
per-workspace 2x2 geometry), test_issue8_update_state.py (1, real
install+update cycle), test_issue12_registry_secrets.py (4); registry CLI
snapshot and help capture refreshed for the intentional scrub-secrets
subcommand; registry.md documents the broker block.

Refs #12 #8 #7

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 11:23:19 +09:00
GodopuandClaude Fable 5.1 8a09e022a6 merge: fix/issue-10-11-13-15 (Issue #10 agy Purge Completeness, #11 Message Typo, #13 Orchestrator Purge, #15 Workspace-Anchored Registry v4.4.3)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 11:22:28 +09:00
GodopuandClaude Fable 5.1 1cc84282f3 docs(reports): archive v4.4.3 unanimous PASS review reports (Issues #10, #11, #13, #15)
Final-round reports of the fix/issue-10-11-13-15 review loop: planner-reviewer-claude-01
(aa16fa5c), reviewer-agy-01 (0f41ea47), reviewer-grok-01 (3ea06fb6) and
planner-reviewer-codex-01 (79204d61), all [VERDICT: PASS] on fae70c1.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 10:53:59 +09:00
GodopuandClaude Fable 5.1 fae70c13d9 fix(issue-10,13): check every agy artifact for holders and purge orphaned leftovers
Round-3 review of f5a6575 (planner-reviewer-codex-01, R1/R2).

R1 - the adapter's in-use check handed only the conversation DB to lsof, so a
holder that keeps the presence lock (or a sidecar) open while naming the uuid
on no command line and in no session variable was invisible, and the held
lock was unlinked from under it. AgyAgentAdapter.conversation_in_use now
passes every path of the conversation (DB, -wal/-shm/-journal, brain,
annotation, presence lock).

R2 - both resolver stages required the DB, so once an interrupted or pre-#10
purge had removed it, the WAL/annotation/lock left behind were "no artifact"
(exit 5) forever. BaseAgentAdapter.has_artifacts (default: a uuid-bearing
artifact path that exists) replaces the resolver's path fallback, and agy's
override accepts any of its pieces.

Tests: a flock holder that names the uuid nowhere is refused and nothing is
removed; orphaned leftovers resolve to agy and are purged. VERSIONS.md
v4.4.3 items 1-2 and orc-onboard SKILL.md updated.

Refs #10 #13

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 10:30:02 +09:00
GodopuandClaude Opus 5 f5a6575bf2 test(issue-13): give each purge test fresh conversation ids
Round-2 review of 7610258 (planner-reviewer-claude-01, reviewer-grok-01,
N2): the purge tests used two fixed UUIDs, while conversation_in_use scans
every process on the host. A review job's delegation wrapper carries the
whole brief - including this file's diff and so both constants - on its
command line, so five tests read "in use" for as long as that wrapper
lived. Reproduced here: this job's own wrapper named both constants and
the same five tests failed.

- tests: `conv` / `other` fixtures hand every test a fresh uuid4 and
  assert that no live process names it yet; the helpers already took the
  id as an argument. With a bystander process naming the old constants,
  the file passes 21/21 and the brief's required set 248/248
- orc-onboard SKILL.md: any live process whose command line contains the
  UUID blocks the purge, not only a resumed session (review R-2), and how
  to find it

No product code changes.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 10:06:54 +09:00
GodopuandClaude Opus 5 7610258950 fix(issue-13): refuse to purge the conversation the caller is running in
Review of 0282312 (planner-reviewer-claude-01, N1): conversation_in_use
excluded the purge's whole ancestor lineage, and that lineage includes the
agent CLI that launched the skill. An orchestrator purging its own UUID
from its own session was therefore never refused - the only process naming
the UUID was excluded, and claude keeps no transcript open for lsof - so
its live conversation was deleted, contrary to what orc-onboard SKILL.md
promises.

- base.conversation_in_use: in use when one of the caller's session-id
  variables (CLAUDE_CODE_SESSION_ID, ANTIGRAVITY_CONVERSATION_ID,
  HERMES_SESSION_ID, GROK_SESSION_ID, OPENCODE_SESSION_ID) equals the uuid;
  the command-line check now excludes only the purge's own helper chain and
  stops at the nearest agent CLI ancestor (basename claude/agy/hermes/grok/
  opencode/codex, read like detect_nearest_agent), which counts as a holder
  when it names the uuid; the lsof check is unchanged
- tests: the non-agent helper chain is excluded but an agent ancestor is
  counted; the purge CLI is refused under an agent CLI naming the uuid and
  with each of the five session variables set to it; orc_onboard --remove
  --purge-conversation --yes is refused from the orchestrator's own session
  (exit 5, registration kept). The eight new cases fail on 0282312
- job_subscriber --registry-dir now defaults to default_registry_dir() like
  the other entry points (review R-d)
- orc-onboard SKILL.md spells out how the calling session is recognised;
  VERSIONS.md v4.4.3 item 2 and the new-test count (24)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 09:34:20 +09:00
GodopuandClaude Opus 5 02823128fa release(v4.4.3): bump framework and eight skills to 4.4.3 in lockstep
PATCH release for the fix/issue-10-11-13-15 branch (Issue #10 agy purge
sidecars, #11 orc_onboard message, #13 orchestrator conversation purge,
#15 workspace-anchored job registry). No code logic changes.

- lib.sh MAM_VERSION, lib_py/loop/eager.py FRAMEWORK_VERSION and the eight
  SKILL.md frontmatters (create, stop, resume, status, monitor, delegate-job,
  loop, orc-onboard) move from 4.4.2 to 4.4.3
- VERSIONS.md: current release v4.4.3 (2026-09-13 KST), the eight-row skill
  matrix, and a v4.4.3 changelog section in the v4.4.2 format covering the
  agy purge sidecars/annotation/presence lock and residual_artifacts,
  `lib_py.agents purge` and `orc_onboard.sh --remove --purge-conversation`
  with their exit codes, the past-tense message, the MAM_JOBS_DIR ->
  WORKSPACE_ROOT -> cwd registry/log resolution and the 20 new tests
- README, README.ko, BOOTSTRAP and BOOTSTRAP.ko badges and the MESSAGING.md
  "Applies to" header follow the current version; historical 4.4.2 mentions
  (v4.4.2 changelog, reviewer reports) stay as history

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 08:53:35 +09:00
GodopuandClaude Fable 5.1 c82ea75a15 fix(issue-10,11,13,15): complete agy purge, orchestrator purge, workspace-anchored registry
Issue #10 - agy purge_artifacts left resumable pieces behind: it now also
removes the SQLite sidecars (-wal/-shm/-journal), the title annotation and
the presence lock (the lock only once no live process references the
conversation), and residual_artifacts() reports anything under
~/.gemini/antigravity-cli still carrying the uuid.

Issue #13 - the orchestrator has no herdr_sessions row, so its conversation
could not be purged by any skill. `lib_py.agents purge <agent|auto> <uuid>`
resolves the adapter from what is on disk (orchestrator_uuids stores bare
uuids), refuses while a live process names the uuid (conversation_in_use:
process list minus the caller's own lineage, plus lsof), and prints what it
purged. `orc_onboard.sh --remove <uuid> --purge-conversation --yes [--agent]`
runs it before the registry update so a refusal changes nothing (exit 4
without --yes, 5 while in use).

Issue #11 - "Successfully removeed": conjugate add/remove explicitly.

Issue #15 - the job registry and audit log followed the caller's cwd, so the
pytest suite (create_session.sh with its default onboarding job, run from the
repo root) had left 593 test records in the real .mam/jobs. Defaults now
resolve MAM_JOBS_DIR / DELEGATE_JOB_LOGS_DIR, then $WORKSPACE_ROOT/.mam/...,
then the cwd (mqtt_common.default_registry_dir / get_logs_dir; registry.py,
publish_event.py, service.py, create_session.sh, stop_session.sh); the
sandbox fixture pins both. The tier suites that used to leak now leave the
real registry untouched (881 records before and after).

Tests: test_issue10_13_purge.py (13), test_issue15_registry_isolation.py (7);
T-O13 pins the corrected message; the R1 helper test and B-9 logs-dir test
now assert the workspace-anchored contract; publish_event snapshot updated.

Refs #10 #11 #13 #15

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 08:18:56 +09:00
GodopuandClaude Fable 5.1 bd3df890dc merge: fix/issue-9-14 (Issue #9 Server Env Isolation and #14 Accepted Delivery v4.4.2)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 07:59:32 +09:00
GodopuandClaude Fable 5.1 9e1f0b68b1 docs(reports): archive v4.4.2 unanimous PASS review reports (Issues #9, #14)
Final-round reports of the fix/issue-9-14 review loop: planner-reviewer-claude-01
(2d3f24e4), reviewer-agy-01 (47a845e0), reviewer-grok-01 (d7e66053) and
planner-reviewer-codex-01 (0ad7cb06), all [VERDICT: PASS] on ebe58f6.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 03:33:59 +09:00
GodopuandClaude Opus 5 ebe58f6be0 fix(issue-14): record every event on disk before the wire publish
Round-2 review of 952657e (reviewer-grok-01): R1's disk-heartbeat
evidence comes from events.log, but publish_event appended to it only
after with_retry(_publish_once) returned - after the broker ACK or all of
its retries. With the public broker at ~5 s per publish, an agent's
heartbeat reached the disk after the grace window and the live job was
closed as deadline_timeout (test_wrapper_idle_timeout_grace_accepts_disk_heartbeat
failed 2/2 on 952657e here, as it did for the reviewer).

- publish_event: new record_local_event appends the prepared payload to
  events.log right after prepare_event (validation and seq allocation
  first) and before the wire publish; record_outcome takes
  local_event_recorded=True so the line is not written twice, while the
  audit "published" entry and the status sync stay after the publish
- DelegationService.publish_event: the same local-first order
- wrapper comment and VERSIONS.md v4.4.2 item 6 now say the heartbeat is
  on disk before the publish; new-test count 21
- tests: the heartbeat is already in events.log when the publish starts
  (and is recorded once), and a publish failing on every retry leaves one
  local record with published=False in the audit; both fail on 952657e.
  The wrapper disk-heartbeat test keeps the real publish_event path and
  now passes 3/3 at the same broker latency

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 03:01:53 +09:00
GodopuandClaude Opus 5 952657efb4 fix(issue-9,14): bound the R1 grace by the wall clock and keep other ls failures unknown
Round-2 review of d5a191c (planner-reviewer-claude-01, planner-reviewer-codex-01).

- delegate wrapper: the R1 idle grace and the broker_unavailable re-check
  counted only their sleeps against TIMEOUT, so python/herdr probe time plus
  fresh disk heartbeats let a job run far past --timeout (55 s for a 20 s
  budget in the new test). Both loops now end at START_TIME + TIMEOUT read
  off the clock on every pass; heartbeats extend only the idle window, and
  the herdr probe is cut off at the deadline (_within_deadline)
- document the window policy d5a191c actually implements: an agent with no
  evidence is closed ~2 x IDLE_TIMEOUT after its last wire event (Issue #6
  promised IDLE_TIMEOUT + 5 s) and heartbeats may be ~2 x IDLE_TIMEOUT apart;
  correct the claim that publish_event records a heartbeat on disk before
  the wire publish - it records right after the publish attempt
- shim ls: every failed `agent list` other than a structured
  server_not_running now exits nonzero with a "state unknown" diagnostic
  instead of reaching the list parser, where an error document on stdout
  read as an empty list and let drift A terminate live rows
- tests: stdout variants for down and unrelated errors, reconcile keeping
  herdr_confirmed False on an unrelated failure, and a wall-clock upper bound
  under continuous heartbeats and slow probes; the three new checks fail on
  d5a191c
- VERSIONS.md v4.4.2: items 3 and 6 and the test count (19)

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 01:53:57 +09:00
GodopuandClaude Fable 5.1 d5a191c47c fix(issue-14): keep a job open on fresh disk heartbeats after the subscriber idles out
The R1 grace after a subscriber idle timeout only continued while herdr
reported `working` or the pane showed a busy token, and gave up the moment
that evidence vanished. Two live jobs in the v4.4.2 review loop were closed
as deadline_timeout that way: a grok review whose heartbeat gap was 147 s,
and the creator running the full suite in a background shell (idle to herdr,
no busy token) while publishing progress every 45 s. Both later published
`completed`, which the terminal record refused.

- `_recent_disk_heartbeat`: publish_event appends every event to the job's
  events.log before the wire publish, so a heartbeat the subscriber never saw
  is still on disk; treat one at most IDLE_TIMEOUT old as liveness
- R1 loop: any evidence (herdr working, pane busy token, disk heartbeat)
  opens a new IDLE_TIMEOUT window; a job with no evidence for a whole window
  is closed as before, still inside the wall clock
- test: a human-agent job whose subscriber idles out stays open across five
  disk heartbeats and picks up the out-of-band completion (rc 0)
- VERSIONS.md v4.4.2 item 6 and test count updated

Refs #14

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-13 00:49:44 +09:00
GodopuandClaude Opus 5 7c40bf4930 fix(issue-9): translate only a structured server_not_running error in the shim's ls
The ls translation searched stderr and the whole stdout for the substring
server_not_running, so a successful `agent list` that merely carried the text
(an agent named server_not_running-codex, or metadata) made the shim report
"no server running". reconcile.sh reads that as a confirmed-empty server, and
drift A would then mark every live row on it terminated (codex review of
0918917).

- keep the RPC exit code and translate only a failed call whose error
  envelope (the whole stream or any line of it) has
  error.code == "server_not_running"; every other failure keeps the unknown
  path (nonzero exit, herdr_confirmed False) as before
- tests: the real herdr 0.9 envelope, a successful list carrying the
  substring in a name and in metadata, other failures staying unknown, and
  reconcile keeping both live rows with no drift A; the new cases fail on
  0918917
- delegate wrapper: log a non-pending status seen during the inject ack
  grace as "registry advanced" instead of attributing it to the agent
- VERSIONS.md v4.4.2: describe the structured check and count 16 new tests

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-13 00:32:57 +09:00
GodopuandClaude Opus 5 091891756b release(v4.4.2): bump framework and eight skills to 4.4.2 in lockstep
PATCH release for the fix/issue-9-14 branch (Issue #9 herdr server env
isolation, Issue #14 accepted-prompt delivery confirmation). No code logic
changes.

- lib.sh MAM_VERSION, lib_py/loop/eager.py FRAMEWORK_VERSION and the eight
  SKILL.md frontmatters (create, stop, resume, status, monitor, delegate-job,
  loop, orc-onboard) move from 4.4.1 to 4.4.2
- VERSIONS.md: current release v4.4.2 (2026-09-12 KST), the eight-row skill
  matrix, and a v4.4.2 changelog section in the v4.4.1 format covering the
  server env marker denylist, MAM_NO_AUTOSTART, the shim ls "no server
  running" translation, SKS_DELIVERY_GRACE_S, MAM_INJECT_ACK_GRACE_S, the R1
  pane busy-token grace, the T1-7 trigger change and the 13 new tests
- README, README.ko, BOOTSTRAP and BOOTSTRAP.ko badges and the MESSAGING.md
  "Applies to" header follow the current version; historical 4.4.1 mentions
  (v4.4.1 changelog, IMPROVEMENTS.md ledger, docs/contracts/issue-6, reviewer
  reports) stay as history

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HCGpJXhSZasJLU38ksDghe
2026-09-12 23:35:18 +09:00
GodopuandClaude Fable 5.1 eaa49aaafe fix(issue-14): keep the idle-timeout working grace alive on the pane busy token
The R1 grace after a subscriber idle timeout only asked herdr whether the
agent was still `working`. herdr never reports that for codex, so a codex
review longer than the idle timeout was closed as deadline_timeout mid-turn
and its eventual `completed` refused - the same status blindness behind the
agent_blocked misjudgement. `_agent_still_working` now also accepts the pane's
own busy token, the evidence send_keys_safe already uses to confirm delivery.

Adds a wrapper test where a codex-like agent (idle per herdr, busy per pane)
idles out the subscriber and completes out of band afterwards.

Refs #14

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-12 23:26:30 +09:00
GodopuandClaude Fable 5.1 4b3134554a chore(gitignore): ignore .claude/ local settings and skill symlinks
.claude/ holds this machine's Claude Code settings.local.json and the
.claude/skills/* symlinks into .agents/skills; neither belongs in the repo.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-12 23:18:36 +09:00
GodopuandClaude Fable 5.1 16376c5891 test(adapters): align agy exit-key expectation with /exit
4d444ce changed the agy adapter's exit_key to /exit for a clean graceful
shutdown but left test_cli_bridge_subcommands_and_quote_safety expecting the
old 'Exit', so the full suite has failed on that one case since.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-12 23:11:55 +09:00
GodopuandClaude Fable 5.1 497633f64a fix(issue-9,14): sanitize herdr server env and confirm accepted prompt delivery
- Drop per-session agent runtime markers (CLAUDECODE, CLAUDE_CODE_CHILD_SESSION,
  CLAUDE_CODE_SESSION_ID, Claude Code messaging/bridge/pid markers, and the
  agy/hermes/grok/opencode session ids) from the environment lib.sh's shim hands
  to a bootstrapped `herdr --session <name> server`; user configuration such as
  CLAUDE_PROJECT_DIR still inherits
- Add MAM_NO_AUTOSTART=1 so query-only callers never bootstrap a server as a side
  effect; status.sh and reconcile.sh export it, and the shim's `ls` reports a down
  server as "no server running" so reconcile keeps herdr_confirmed instead of
  freezing drift detection for every server
- send_keys_safe: treat `timeout` / `agent_prompt_stalled` from `agent prompt
  --wait` as an accepted submission and confirm delivery for SKS_DELIVERY_GRACE_S
  (default 15 s) via agent_status working, a busy token the pane did not show
  before, or the pane moving on from its pre-submit snapshot; no signal at all
  still fails closed (rc 4). Codex under herdr 0.9.0 never reports `working`, so
  every delivered prompt was closed as agent_blocked and its later
  started/completed events refused
- delegate wrapper: before closing an unconfirmed inject as agent_blocked, honour
  the registry's own acknowledgement for MAM_INJECT_ACK_GRACE_S (default 10 s)
- Switch T1-7's failure trigger to transport_error (timeout now means accepted);
  add test_issue9_server_env.py (5 cases) and test_issue14_delivery_ack.py (7)
- Verified live: a freshly bootstrapped multi-agent-mux server carries no markers
  and the claude panes save transcripts again; codex job d04ebcb5 had its
  started/completed accepted with no agent_blocked

Closes #9
Closes #14

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VCgu9Fa9iT7TbJUSzdq4Ff
2026-09-12 23:11:55 +09:00
Godopu 4d444ce6cd fix(adapters): set agy exit_key to /exit for clean graceful shutdown 2026-09-09 22:52:40 +09:00
Godopu 636b47475f docs(reports): archive final close approval reports from OpenCode and Grok 2026-09-09 22:50:49 +09:00
Godopu 299ba7dd8b docs(reports): archive Issue #6 close approval reports from reviewers 2026-09-09 22:36:00 +09:00
Godopu a08b3ca387 merge: refactor (Issue #6 Fail-Closed and Turn Handshake v4.4.1) 2026-09-09 14:03:04 +09:00
Godopu ec61511699 fix(issue-6): fail-closed registry timeout and TUI turn handshake
- Introduce finalize_unfinished in multi-agent-mux-delegate-job for fail-closed atomic transitions
- Enforce CAS dispatch_token and attempt_id pinning across engine, CLI, and lifecycle scripts
- Integrate Herdr wait_for_agent_idle turn handshake to prevent prompt loss and race conditions
- Resolve bash 3.2 set -u empty array expansion compatibility in lib.sh
- Preserve Issue #5 R2 contract in CAS transition engine (engine.py, publish_event.py, service.py)
- Add comprehensive regression suites (test_issue6_fail_closed.py, test_issue6_turn_handshake.py)
- Bump lockstep framework and skills to v4.4.1 across lib.sh, eager.py, VERSIONS.md, 8 SKILL.md
- Synchronize documentation (IMPROVEMENTS.md, MESSAGING.md, state-transitions.md, task.md, phase5-e2e.md)
- Unanimous PASS achieved across 4 reviewer team leaders (Claude, Codex, OpenCode, Grok)

Closes #6
2026-09-09 14:02:47 +09:00
Godopu 7b761be7b8 docs(issue-6): establish phase 1-5 implementation plan and task checklist (Rev.2) 2026-09-08 10:39:54 +09:00
Godopu f98b9582c7 docs: clean up root markdown files and synchronize with v4.4.0 standards
- Relocate legacy implementation_plan.md to docs/contracts/nats-backplane/implementation_plan.md
- Synchronize root documentation (README, README.ko, BOOTSTRAP, BOOTSTRAP.ko, AGENTS, MESSAGING, IMPROVEMENTS) to latest v4.4.0 standards
- Consolidate IMPROVEMENTS.md to single source of truth (5 open / 31 completed tasks 1:1 matching section headers)
- Archive unanimous PASS review reports from Claude, Grok, Codex, and OpenCode along with Plan Rev.2
2026-09-08 08:02:37 +09:00
Godopu 07cae71667 merge: release/v4.4.0 (Framework and 8 skills lockstep release v4.4.0) 2026-09-07 16:08:01 +09:00
Godopu 525764aaa3 docs(reports): archive v4.4.0 unanimous pass review reports (d05e8e15, 78443ebe, e5c9a052) 2026-09-07 16:07:43 +09:00
GodopuandClaude Opus 5 387479732e release(v4.4.0): bump framework and eight skills to 4.4.0 in lockstep
Issue #5 (Python core migration, CAS state transitions, shadow watcher,
auto-completion gate, eager-import immutable runtime, B-13 freeze removal)
is complete and merged to main. This stamps the release.

SemVer: MINOR, not MAJOR. The change is large but breaks nothing. Across the
whole Issue #5 range there are zero file deletions and zero renames, the event
wire schema stays at SCHEMA_VERSION 1, all four literal script paths survive as
compatibility shims, the 968-line legacy shell loop is still in run_loop.sh,
and every default change reverts through a single environment variable
(MAM_DELEGATION_PY / MAM_ENGINE_CAS / MAM_LOOP_PY / MAM_LOOP_FREEZE). The
riskiest new feature, auto-completion, ships default-off. No operator has
anything to migrate, which is the decisive reason not to call it 5.0.0. The
reasoning is recorded in the VERSIONS.md release notes, not just here.

Close a gap in the lockstep guard. lib.sh exports MAM_VERSION and eager_load()
refuses to start the loop when it disagrees with FRAMEWORK_VERSION, so eager.py
is a load-bearing fourth leg — but test_version_consistency.py only checked
three, and the sole check on eager.py was a hardcoded literal in the phase 4
test that a release bump has to edit anyway. The lockstep test now covers
eager.py, a new test pins the fail-closed gate itself, and the phase 4 test no
longer carries a version literal.

Fix a latent test-isolation defect the bump exposed. The first full run failed
four tests with "MAM_VERSION mismatch: expected 4.4.0, got 4.3.0 in
environment" — 4.3.0 was not in the tree, it was inherited from the shell that
launched pytest and had sourced the pre-bump lib.sh. Those tests were measuring
the runner's shell rather than the tree under test, and only passed until now
because the two values always happened to agree. A session-scoped fixture drops
the ambient value. Production is unaffected: run_loop.sh:17 sources lib.sh
before anything else and lib.sh re-exports MAM_VERSION unconditionally, so a
stale inherited value is always overwritten before Python starts.

Full suite: 750 passed in 912.50s, 0 failed, 0 skipped.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-07 15:55:26 +09:00
Godopu b347efd760 merge: refactor branch (Issue #5 Python core migration & robust orchestration loop) 2026-09-07 15:14:03 +09:00
Godopu f413f6ada6 feat(loop): complete Issue #5 Phase 4 immutable runtime and freeze removal
- Implement eager module loading (lib_py.loop.eager) to preload all framework
  dependencies into sys.modules and enforce PYTHONDONTWRITEBYTECODE=1.
- Synchronize runtime protocol version with MAM_VERSION constant (4.3.0).
- Bypass /tmp/mam-loop-freeze.XXXXXX copy overhead by default in Python mode
  while preserving legacy rollback fallback (MAM_LOOP_PY=0 / MAM_LOOP_FREEZE=1).
- Add tests/test_issue5_phase4_runtime.py verifying eager import completeness,
  mid-flight code modification immunity (B-13), and freeze bypass.
- Pass full test suite (749 tests, 0 failures).
2026-09-07 12:59:45 +09:00
Godopu 8cd256cc7a feat(loop): port run_loop.sh to Python lib_py.loop with thin wrapper and strict parser (Phase 3) 2026-09-07 09:04:49 +09:00
Godopu e1203166d9 docs(reports): archive phase 2b unanimous pass review reports (a665d729, 7e7eea07, a7f1ee0e) 2026-09-07 08:27:04 +09:00
GodopuandClaude Opus 5 8d7e010f9f fix(issue-5): record an accepted intent, not a refused one
The subscriber marked a notification intent as seen before the monotonic
sequence guard ran. A late packet was then dropped by that guard with its
intent already burned, so the genuine retry of a notification this
subscriber had never delivered was mistaken for a replay and dropped too.

Identity comparison stays ahead of the sequence guard -- a duplicate must
not consume a sequence number -- but the bookkeeping write moves behind
it, so "seen" means "accepted" rather than "arrived".

An intent that cannot yield a stable identity (not an object, or holding
an unhashable value) is now refused instead of raising out of the
callback: a paho callback that raises takes the network loop down for
every job that subscriber is watching.

Six regressions; three of them fail on the unfixed tree, and one drives
a real notifier retry through the real consumer with no hand-built
payload. Full suite: 732 passed, no skips.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-07 08:11:37 +09:00
GodopuandClaude Opus 5 9a651ccc71 docs(issue-5): record atomic attribution and correct my earlier claim
The state-transition spec gains the rule that attempt identity lives in the
record, because a precondition can only be atomic with the commit if the
transaction can read it under its own lock, and checking attribution beforehand
leaves a window a re-dispatch fits through.

The operations note gets the same, plus the reason it is an opaque token rather
than the iteration counter: iteration already means the loop round, so comparing
a dispatch attempt against it is vacuous when they agree and wrong when they
diverge.

It also marks my earlier section as partly withdrawn rather than quietly editing
it. That section argued a record schema change was unnecessary because the
attempt guard lives in the evidence layer. That was right about comparing
evidence to a dispatch and wrong about atomicity, and the review proved the
difference by execution. The narrower point it made -- why not to reuse
iteration -- still holds and is kept.

Also records why the subscriber now deduplicates on the intent identity: a
replay arrives with a fresh wire sequence, so the monotonic guard cannot see it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 23:22:12 +09:00
GodopuandClaude Opus 5 01b465f50c fix(issue-5): bind the auto-completion decision atomically to its attempt
Two findings from round 2, both reproduced before being accepted.

R2 -- attribution was compared before the terminal write and nothing tied the
two together. A job could complete, be re-dispatched and claimed again in that
window, and evidence from the first attempt then satisfied a status check and
finished the second one. Reproduced with real transitions: committed, with the
registry already on iteration 2.

This corrects my own earlier reasoning, and I want to be plain about it. Last
round I argued that the attempt guard could live entirely in the evidence layer
because that is where attempt identity lives. That holds for comparing evidence
to a dispatch, and it does not hold for atomicity: a precondition can only be
atomic with the commit if the transaction can read it under its own lock. So the
identity now lives in the record.

It is an opaque dispatch token, not the iteration counter. That distinction is
the part of the earlier rebuttal that still stands: iteration already means the
loop round, and comparing a dispatch attempt against it produces a guard that is
vacuous when they agree and wrong when they diverge. A token has no competing
meaning. It is minted when an attempt begins -- claim and redispatch -- and the
gate passes the token it decided against, so any intervening re-dispatch refuses
the commit.

R4 -- the intent identity was being emitted but nothing consumed it. A replayed
notification is re-published with a fresh wire sequence, so the monotonic guard
cannot recognise it; to that guard a retry looks new. The subscriber now
deduplicates on the stable intent identity, leaving the sequence guard as the
rule for ordinary events. Across a restart the disk fallback resolves terminal
status and a duplicate terminal is refused as an idempotent ack, so a replay
after restart cannot double-apply either.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 23:21:11 +09:00
GodopuandClaude Opus 5 d87674679d docs(issue-5): correct the phase 2b operations note and the stale references
The important correction is an honesty one, raised independently by two
reviewers. The note claimed startup recovery runs in the subscriber. It does
not: nothing in production imports the gate or the recovery function, and there
is no per-job opt-in path, so the flag is currently a no-op in the live loop.
Phase 2b delivers a verified library and gate; wiring it in belongs to phase 3,
and the note now says so and lists what wiring requires.

Also records the checks that are now mandatory rather than caller-dependent,
that the rollback switch disables auto-completion too, that backend keys match
exactly, that bookkeeping may touch one field, that settling is conditional on
the intent actually sent, and why the intent's identity travels in the payload
rather than relying on the transport sequence.

Fixes three stale references: task.md named the pre-move path for finalize, the
loop package description still described itself as shadow-only, and a comment in
mqtt_common still pointed at the engine's original location.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 22:26:56 +09:00
GodopuandClaude Opus 5 cb7ed1aa38 fix(issue-5): close the phase 2b gate holes found by all three reviewers
Seven blocking items across three reviews, every one reproduced here before
being accepted. Two themes run through them: a gate whose strictness depended on
what the caller remembered to pass, and a boundary that trusted its only current
caller instead of enforcing its own rule.

Independent verification is no longer optional. Omitting the report directory
skipped the disk check entirely and handed the decision back to the collector's
own flags -- the self-certification this design exists to prevent. It is now a
refusal, as is an empty directory or a job with no recorded dispatch.

Evidence is now bound to its target. The policy compares a scenario against the
dispatch context carried inside that same scenario, which is self-consistent by
construction, so one job's evidence could complete another. The gate now checks
the job, attempt, session and pane generation against the recorded dispatch.

A reviewer with no verdict token is no longer completed. Phase 0 made this a
safety contract and run_loop reads a missing token as NOT PASS, so inferring
completion first would start a correction round against a review that was never
finished. The requirement applies to reviewers only.

Bookkeeping may write one field. A status-free request was an unrestricted merge
on a terminal record: it could rewrite the prompt and the session. Settling is
also conditional now on the exact intent that was sent, because publishing
happens outside the lock and a newer intent can legitimately land mid-flight;
clearing unconditionally dropped a notification nobody had sent. The intent's
own identity travels in the payload, since the transport sequence cannot
identify a retry of the same intent.

Side-effect evidence must be evidence. A kind with no reference names something
without evidencing it, and the CLI parser could not be the only check because
the API and hand-written manifests bypass it.

Also honours MAM_ENGINE_CAS=0, which the operations note already promised
disables auto-completion, matches backend keys exactly rather than by prefix so
a future name cannot inherit evidence never collected for it, records an
absolute report path, and imports the notifier at module scope.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 22:25:50 +09:00
GodopuandClaude Opus 5 12cba25c18 fix(issue-5): keep finalize inside delegation and refresh the CLI golden
Two failures the full suite caught, both mine.

finalize.py started in lib_py/loop, which made publish_event import a sibling
package. That is the rule phase 1 wrote down and phase 2a already made me move
the engine for: under a frozen loop, delegation is bound to one tree while the
parent may be another, so reaching sideways mixes them. The manifest is written
into the job's own report directory and the CLI that declares it is a delegation
entry point, so finalize belongs there. Second time on the same rule, and the
guard caught it both times.

The publish_event --help golden no longer matched, because phase 2b
intentionally added the finalization options. The diff is exactly those three
options and nothing else, so the capture is refreshed rather than the assertion
weakened, and the test now states when a refresh is legitimate: an intended
extension, never drift nobody meant.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 21:47:54 +09:00
GodopuandClaude Opus 5 8adbe2245c docs(issue-5): phase 2b scenarios, operations note and task checklist
Three scenarios join the contract set, so the fifteen vectors now cover an
unproven side effect, an undecidable attribution, and an agent whose state goes
unreadable in the window between finalization and notification. All fifteen
match their expected decision.

The side-effect case needed a decision about layering. Authoritative enforcement
belongs in manifest verification, which has the job record and therefore knows
what was declared; the policy honours an explicit negative from the collector so
the case is expressible as a vector. Absence is not read as proof there, because
the manifest check is the layer that fails closed on missing evidence.

The operations note records why the agent declares and the reader re-derives,
the three gates and why the backend allowlist can only be narrowed, the
notification transaction, and the rollback.

It also records a deviation from my own plan. §D2 asked for reviewer sign-off
before promoting an attempt id into the record, since that changes a contract
phase 1 froze. Measurement during implementation showed the change was not
needed: the attempt guard already lives in the evidence layer, where attempt
identity actually is, so auto-completion passes the engine a status precondition
instead. The schema is untouched, the frozen contract holds, and a
characterization test fails the moment a record starts carrying an attempt id,
which is when to revisit it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 21:32:48 +09:00
GodopuandClaude Opus 5 803ba43884 feat(issue-5): auto-completion gate and durable pending notification
The gate does not re-decide anything. Phase 2a already decides, fail-closed and
against contract-pinned vectors; this supplies real evidence to that decision and
commits only if three independent gates agree: the global switch is on, the
backend has observed evidence that it reaches a quiescent state, and the job
itself opted in. Default is off.

The backend allowlist is evidence-based rather than optimistic. Inferring
"finished" from stillness requires stillness to have been observed, and only
three of six backends have that. An operator may narrow the list; a name that
was never observed is dropped rather than trusted, so it cannot be widened by
configuration.

Everything else holds. An unreadable manifest, a report rewritten after
finalization, missing evidence for a declared side effect, a policy that raises:
all refuse. "Could not decide" is never "done". A late explicit terminal wins,
because the boundary refuses the inferred one -- that is the boundary working,
not an error in the gate.

Notification intent is committed in the same atomic write as the state, so a
crash between committing and publishing leaves a record that still says the
world has not been told. Recovery re-sends; duplicates are already dropped by
sequence. A failed send deliberately leaves the intent pending, because an
unsent notification that looks sent is worse than one that is retried.

Two fixes this surfaced. Settling used a request that terminal records refuse,
which made an owed notification impossible to ever settle; settling is now a
status-free bookkeeping request, valid in any state. And the phase 2a guard
against shell references was matching hashlib.sha256 as a substring, so it now
requires a word boundary.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 21:30:38 +09:00
GodopuandClaude Opus 5 3ea5757cfe feat(issue-5): report finalization manifest and side-effect evidence
The agent declares that its work is finished; the reader re-derives the hash
from the file rather than trusting the number in the declaration. A manifest the
watcher wrote itself would attest only that the watcher saw a stable file, which
is the self-certifying evidence shape rejected earlier in this issue.

Finalizing promotes a staged report by atomic rename before writing the
manifest, so a reader cannot observe a half-written report as final. Rewriting
the report afterwards invalidates the declaration immediately, because the
recomputed hash no longer matches -- a new body needs a new finalization.

A job that declared side effects must show evidence for every one of them.
Partial evidence is treated as none: the work is not known to be complete.

publish_event gains --finalize-report, --side-effect and --attempt-id, and does
the finalization before publishing. A `completed` event whose report is still
being written would invite exactly the partial adoption the contract forbids, so
a failure there fails the publish.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 21:27:41 +09:00
GodopuandClaude Opus 5 9a827b3caa test(issue-5): phase 2b fail-closed preconditions before auto-completion exists
Pins what the system refuses to do today, so nothing added later can weaken it
quietly. X-01 records the property the whole phase leans on: a job with no
completion manifest is already held, which is why an agent that declares nothing
stays on the explicit path without a single new branch.

X-03 and X-04 record the layering decision and its evidence. The engine compares
an expected attempt against a record field that does not exist, falling back to
the loop-iteration counter, which means something else. So auto-completion does
not use that guard; the attempt check stays where attempt identity actually
lives, comparing observed evidence against the dispatch record. X-03 will fail
if a record ever starts carrying an attempt id, which is the moment to revisit
the decision.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 21:26:33 +09:00
GodopuandClaude Opus 5 5eb9524fe7 docs(issue-5): phase 2b implementation plan (flag-gated auto-completion)
An executable plan for P2B-01..03, grounded in measurement of what phase 2a
actually left behind rather than in restating the contracts.

The design turns on one question: who writes the completion manifest. If the
watcher computes the hash itself, the manifest only attests that the watcher saw
a stable file, which is the self-certification Codex rejected as R1 last round.
So the side that knows it finished declares it, and the watcher re-derives the
hash rather than trusting the declaration.

That choice makes P2B-03's "preserve the explicit path completely" fall out for
free instead of needing a branch: an agent that declares nothing leaves no
manifest, and a missing manifest already holds today. Verified against the
current policy.

Four measurements shaped the rest. Nothing in the tree writes or reads a
manifest, so the protocol is new in full. Records carry iteration but never
attempt_id, and the engine silently substitutes one for the other -- they agree
today only by coincidence of the wrapper's flow, and the auto-completion gate
hangs off that value, so the plan asks for an explicit decision and reviewer
sign-off before any code is written. The pending-notification contract forbids a
separate outbox, so the intent rides in the record the transaction already
writes. And only three backends have observed evidence of a quiescent state, so
the allowlist has a factual basis instead of an optimistic one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 21:24:04 +09:00
Godopu 4a5916a736 docs(reports): archive phase 2a plan and unanimous pass review reports (49171b58, 3f0784c4, d2e705a8) 2026-09-06 20:42:38 +09:00
GodopuandClaude Opus 5 0e74aa1e4e docs(issue-5): record the evidence requirement, the audit lock and the ack rule
Three contract points the round 2 fixes established.

An idempotent re-receipt is an ACK in the table, so a caller must treat it as
success. Only a genuine refusal is non-zero, and an invalid status stays the
usage error it always was. That distinction is what keeps the wrapper's approved
path from aborting under set -e.

Completion attribution now requires evidence to be present, not merely
non-contradictory, and names where it may be read from: a collector envelope
beside the payload, or a non-native source's own payload. Never from inside a
native Herdr payload, because MAM fields are forbidden there and one appearing
anyway is not evidence of anything.

The audit mirror's ordering guard is documented as a locked read-compare-write,
with the reason a bare sequence number was not enough, and the note that the lock
is deliberately taken outside the registry transaction.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 20:11:40 +09:00
GodopuandClaude Opus 5 cb575fa851 fix(issue-5): address phase 2a round 2 findings (F-C, F-D, R1, R4)
Both reviewers sustained the round 1 fixes and found four more. Each was
reproduced here before being accepted; none were rebutted.

F-C (claude, blocking) -- my own round 1 fix caused this. Making refused writes
exit non-zero also classified an idempotent ACK as a refusal, and the wrapper
finalises an approved job with `status --set completed` on a record that is
already completed. It runs under `set -e`, so the *success* path aborted with
exit 4 before its validation hook and its final stdout line. Reproduced at the
shell. An idempotent result is now distinguishable from a refusal and exits 0; a
genuine conflict still exits 4.

F-D (claude) -- routing the operator write around update_status dropped the
status vocabulary check. Under the rollback flag an invalid status was written
to the record with exit 0, where before it was refused with exit 1 and the record
left alone. The check now runs first, in both modes.

R1 (codex, blocking) -- the previous fix compared identifiers only when they
happened to be present, so evidence carrying none at all was still approved on
the dispatch record's own flags. That is the self-assertion the check exists to
replace. Every identifier must now be supplied and agree, and a report manifest
must associate with the attempt being judged. Identifiers are read from a
collector envelope beside the payload rather than from inside it: a native Herdr
payload may not carry MAM fields, so one appearing there is either fabricated or
a contract violation, and either way it is not evidence.

R4 (codex) -- a sequence number orders nothing unless the compare and the write
are atomic. Two flushes could both read the old value, the newer land first, and
the slower overwrite it. Reproduced deterministically. The mirror now serialises
read-compare-write under a per-job audit lock, taken outside the registry
transaction so a slow mirror still cannot lengthen it, and each write uses its
own temp file instead of a shared name.

All eight new regressions fail against the pre-fix code.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 20:10:41 +09:00
GodopuandClaude Opus 5 3b134e3358 docs(issue-5): record the operator-authority transitions and the review fixes
state-transitions.md §3 gains the two rows it was missing. They are named
transitions, not exceptions: re-dispatching a finished job to the next iteration
and finalising an exhausted one are things the wrapper legitimately does, and
they are gated on operator authority so an agent still cannot walk back its own
terminal. The table also now states that a status may only be set by the request
that owns it, which is what closes the metadata-merge bypass.

phase2a-shadow.md documents the authority split, the CLI's new non-zero exit on
a refused write, and why the audit mirror compares transition_seq. Two reviewer
observations are carried forward as 2b work: `started` does not yet verify the
assigned session, and stop_session's unconditional cancel is now refused on an
already-completed job, which is the table behaving as designed but worth a
release note.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 19:34:20 +09:00
GodopuandClaude Opus 5 56d08efa95 fix(issue-5): address phase 2a cross-review findings (F-A, F-B, R1, R2, R3)
Two reviewers raised five defects. Every one was reproduced here before being
accepted; none were rebutted.

F-A (claude, blocking) -- the CAS table had no row for two transitions the
wrapper legitimately makes, so `submit --type loop|discuss` silently stopped
working by default: the per-iteration re-dispatch was refused and its metadata
discarded, the exhausted-budget finalisation was refused, and the CLI returned 0
both times. Reproduced against the real modules. Fixed by naming those
transitions rather than carving an exception: `redispatch` and `finalize` are
requests gated on operator authority, so the wrapper can move a finished record
while an agent still cannot touch its own terminal. A re-dispatch must advance
the iteration, so a replay cannot resurrect a job. The operator CLI now exits
non-zero with a reason when a write is refused -- the silence is what let this
hide.

F-B (claude) -- moving the audit mirror out of the lock made status.json
last-writer-wins, so a slow flush could leave it behind the registry. It now
carries transition_seq and skips a write that would go backwards, restoring the
sequential consistency the lock used to provide for free.

R1 (codex, blocking) -- the policy called attribution with only the dispatch
record, so it proved the record was well-formed and never confronted the
identifiers the evidence carried. A finalized scenario with a different session,
a different attempt and a manifest from another attempt was still approved.
Observed identifiers are now collected from the timeline and every one must
agree; a manifest belonging to another attempt holds. Collecting every
occurrence rather than the first matters, because taking the first would drop
exactly the contradicting value this is meant to catch.

R2 (codex, blocking) -- a supplied expected_attempt was ignored when the record
had no attempt field, so a compare-and-swap with nothing to compare committed.
It now fails closed, which matters because 2b plans to gate inferred completion
on precisely that precondition.

R3 (codex) -- a status could ride in as an ordinary field, so `progress` could
commit a terminal from inside the boundary that exists to prevent it. Status is
now settable only by the request that owns it, unknown requests are refused, and
pending has an owning request instead of being an untyped merge.

Each of the eleven new regressions was checked against the pre-fix code first.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 19:33:24 +09:00
GodopuandClaude Opus 5 17a2dcd988 docs(issue-5): phase 2a contracts, scenarios and task checklist
Records what phase 2a actually delivers and, as importantly, what it does not:
the shadow runner decides and logs, and nothing commits an inferred completion
until 2b.

state-transitions.md gains an implementation mapping so each contract row names
the code and the test that hold it up, with the inferred-completed row marked as
judged-but-not-committed.

phase2a-shadow.md is the operations note: the rollback switch, the lock
discipline and why transition_seq exists, the herdr wait rules that are easy to
get wrong (milliseconds, always name --until, errors on stderr, a timeout is a
healthy answer), the fail-closed decision order, and the 2b handoff.

task.md records P2A-00..04 with commit evidence, including two corrections to my
own plan: pick_pending was already a correct swap rather than a hole, and the
engine had to live with the registry writers because putting it in lib_py/loop
would have made delegation import a sibling and mix trees under a frozen loop.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 18:58:01 +09:00
GodopuandClaude Opus 5 964abc6965 feat(issue-5): shadow watcher that logs would-complete and cannot write
policy.decide is a pure function so the phase-0 scenario fixtures can be fed to
it verbatim. Those seven decisions survived three-reviewer scrutiny, so they are
the contract rather than a fresh set of rules, and the test asserts against
expected_policy.decision directly.

Order inside the policy matters. Transport doubt and staleness invalidate the
evidence itself, so they are answered before anything is inferred from it; a
blocked agent is waiting for a human and can never be completed; attribution
including the execution anchor comes before quiescence, because idle is not
evidence of finishing when a session is reused; and a report must be finalized,
never merely paused, since a debounce is a candidate filter and not an authority.

The shadow runner is never handed the engine, so it has no route to a write.
That is the structural half of P2A-03. The measured half hashes every file under
the registry directory around a full run and asserts it is unchanged, which is a
stronger claim than checking a status field.

Adds the five scenarios P2A-04 requires: a raced double dispatch, a reused
attempt with no anchor, a mid-write report, an unknown status, and a pane
restarted mid-flight. They pass phase 0's own fixture validator, which is what
keeps them honest. The phase-0 test that pinned exactly seven scenarios now
requires the seven to still exist rather than forbidding growth.

Also pins the two phase 1 handoffs as dormant: nothing here spawns a daemon, so
preexec_fn stays unreachable, and nothing calls a frozen shell helper.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 18:56:35 +09:00
GodopuandClaude Opus 5 b49af56c3c feat(issue-5): herdr agent wait watcher with reconnect backoff and a shadow store
watcher wraps one `herdr agent wait` barrier and observes only; it never
concludes. The live contract is encoded rather than described: the timeout
parameter is named timeout_ms because herdr counts milliseconds, --until is
always passed explicitly since omitting it silently drops `working`, and a
non-zero exit is read from stderr because stdout is empty by contract.

A timeout counts as healthy. The socket answered and the state simply did not
change; treating that as a failure would make an idle agent look unreachable.
Only a matched snapshot becomes evidence, so a timeout can never be mistaken for
an observation of agent state.

Backoff doubles from 1s to a 16s ceiling and drops the cached snapshot on
failure. Reasoning from state captured before a gap is exactly what would make a
disconnect look like a completion, which is why the contract answer there is
hold_reconnect.

store keeps dispatch and attribution evidence outside the registry. The job
record carries none of attempt_id, agent_session_uuid or
pane_process_generation, phase 1 froze its schema, and this phase may not write
the registry at all. Keeping the evidence here lets shadow mode carry full
attribution while the registry stays untouched; promoting these fields is a 2b
decision. The execution anchor starts false because acknowledging a dispatch is
not evidence that the attempt ran.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 18:54:27 +09:00
GodopuandClaude Opus 5 2532e78453 feat(issue-5): single CAS transition boundary for every job-status write
engine.transition is now the only writer of job status. It implements the target
table in state-transitions.md §3: claim, non-terminal metadata, explicit
terminals, idempotent re-receipt, refusal of conflicting or late signals with an
audit entry, stale-attempt rejection, and deadline timeout.

Two write paths become one. update_job_status merged fields unconditionally;
pick_pending hand-rolled a correct pending->running swap plus its own audit
mirror. Neither was wrong alone, but a rule added to one silently missed the
other, which is the shape that produced the phase 1 transport bugs. Both keep
their signatures and their preserved legacy bodies behind MAM_ENGINE_CAS=0.

A merged `status` value is routed to the request that owns it, so a raw field
write can no longer slip past the table. Getting that wrong first was caught by
the characterization tests: a metadata merge was overwriting the caller's status
with the pre-merge value.

Lock discipline is now enforced, not described. The lock covers a decision and
one record write; audit mirroring is queued and flushed after release, carrying a
monotonic transition_seq so ordering survives the move. A test watches for
subprocess, socket and sleep calls while the lock is held and asserts none.

Structural correction to my own plan, caught by a phase 1 guard: the plan put the
engine in lib_py/loop, but delegation would then have had to import a sibling,
which is exactly what mixes trees under a frozen loop. The engine belongs with
the registry writers, so it lives in lib_py/delegation and loop consumes it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 18:53:22 +09:00
GodopuandClaude Opus 5 9389d7ebe2 test(issue-5): phase 2a writer characterization before the CAS boundary
Fixes what the job-status writers do today, so routing them through a single
transition boundary has an oracle instead of a promise. Same ordering that paid
off in phase 1.

X-02 states the claim path's real contract rather than the one the plan first
assumed: pick_pending filters on pending under the lock, so it is already a
correct swap. It duplicates the chokepoint, it does not bypass its safety. The
test pins the properties that must survive routing -- only pending is claimed,
only one session wins, and a session never sees another's work.

Every test is parametrized over MAM_ENGINE_CAS so the legacy body and the engine
body must agree.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 18:46:48 +09:00
GodopuandClaude Opus 5 02a89490df docs(issue-5): phase 2a implementation plan (lib_py/loop core and shadow watcher)
An executable plan for P2A-01..04, grounded in live measurement rather than
restating the phase-0 contracts.

Four measurements shaped the design:

  * The job record has no attempt_id, agent_session_uuid or
    pane_process_generation, so the four-fold attribution contract has nowhere
    to live in it. Phase 1 froze the record schema and P2A-03 forbids registry
    writes outright, so attribution goes in a shadow-owned store and the record
    schema question is deferred to 2b.
  * Every status write is already inside python: the shell side only reads. A
    single boundary can therefore cover all writers.
  * update_job_status merges fields unconditionally, and pick_pending is a
    second path around it. pick_pending is not wrong -- it filters on pending
    under the lock, so it is already a correct swap -- it is a duplicate. That
    is the O-1 shape from phase 1, where the copy that drifts is the one that
    breaks. So P2A-01 generalises the swap that exists rather than inventing one.
  * herdr's wait timeout is milliseconds. Phase 0 recorded it correctly; the
    plan names the parameter timeout_ms so the unit cannot be misread.

Two invariants are made structural rather than promised. The shadow runner is
never given a reference to the engine, so it cannot write; and the gate hashes
the whole registry directory before and after a full run, which is a stronger
claim than "status was not changed". Lock discipline follows a pattern already
in the tree: pick_pending finishes its record write under the lock and mirrors
to the audit log after releasing it.

Carries the three phase-1 handoffs forward with explicit gates: no daemon spawn
in 2a so preexec_fn stays unreachable, no frozen-helper calls so the interpreter
resolution gap stays dormant, and a coverage assertion for the connection
fingerprint's field list.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 18:45:15 +09:00
Godopu 015ab70e51 docs(reports): archive phase 1 unanimous pass review reports (1418f44c, c4f0ffc7, 714a1844) 2026-09-06 17:37:14 +09:00
GodopuandClaude Opus 5 6ad6f08cc6 docs(issue-5): fold in the two non-blocking residuals from cross-review round 2
Both reviewers passed and each left one documentation item.

Grok: the benchmark's fork table still named the shell path `-m
lib_py.delegation.cli`, which is what R1 replaced. It now names the actual
bootstrap, and says why the module-execution form was abandoned. The fork count
is unchanged either way.

Claude (O-4): inside a freeze tree, _delegate_py_bin walks up from its own
location for a .venv and finds none, so it falls back to a system python that
has no paho. Harmless in phase 1, because nothing in production calls the frozen
lib.sh helpers; it becomes real in phase 3 when the loop process starts doing
exactly that. Recorded on P3-02 rather than fixed here, since the fix belongs
with the code that will depend on it. Verified the premise: the current freeze
root has no .venv.

No code changed. The unanimous PASS was issued on 95f3e9a.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 17:21:12 +09:00
GodopuandClaude Opus 5 95f3e9a427 fix(issue-5): address phase 1 cross-review findings (R1, R2, F-1)
Three reviewers examined fc0bd96..8def235. Codex and Claude each reproduced a
defect; all three findings were re-verified here before being accepted, and none
were rebutted.

R1 (codex) — the shell helpers ran `python -m lib_py.delegation.cli`. For -m,
sys.path[0] is the working directory, which therefore beats PYTHONPATH: with cwd
inside a tree containing lib_py, the live package won even with the frozen path
listed first. The documented B-13 guarantee for this path did not hold.
Reproduced, then replaced with an explicit bootstrap that inserts SKILL_DIR
itself. cwd is left alone, because the registry and audit-log paths are relative
to it. The file-based shim path was never affected.

R2 (codex) — the persistent connection was reused on host and port alone. Two
jobs sharing an endpoint but carrying different credentials or TLS settings
silently published over the first connection. Reproduced (the client factory ran
once, under the first account, with TLS off). The guard now compares an
immutable snapshot of the whole connection identity and names only the differing
field, never its value.

F-1 (claude) — paho queues a publish issued while disconnected and raises
RuntimeError from wait_for_publish. RuntimeError is deliberately outside the
retry tuple, so the one state a persistent connection exists to survive, the gap
between a drop and paho's reconnect, failed on the first attempt. Confirmed
against paho 2.1.0. That single condition is now translated into a retryable
error; the tuple is unchanged, so genuine programming errors are still not
retried.

Two fixtures were hiding these: FakeInfo had no rc and never raised. It now
mirrors paho's contract, which is what makes the new tests meaningful.

Also folds in the duplication both Claude (O-1) and I had flagged: the CLI path
kept its own copy of connect-publish-disconnect plus its own timeout constants.
_publish_once now delegates to OneShotPublisher.publish_raw, so a transport fix
lands once. Having two copies is exactly why these bugs existed in one of them.

Documentation corrected rather than defended: the benchmark's rationale for
keeping three forks was imprecise (the || true already guarantees rc 0; the
lookup buys quietness and legacy parity), SKILL.md no longer claims PYTHONPATH
decides the frozen path, and the daemon's directory creation is recorded as a
deliberate difference. Trailing whitespace inherited by the relocated file is
stripped, so the commit range is now clean too.

Verified: each regression fails against the pre-fix code and passes after
(R1 1, R2 4, F-1 1). 66 phase-1 tests pass.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 16:51:38 +09:00
Godopu 8def235dc7 docs(reports): archive phase 1 finalized implementation plan (plan-923e9403) 2026-09-06 16:29:06 +09:00
GodopuandClaude Opus 5 dfa7212ea4 docs(issue-5): record the self-review fix in the phase 1 evidence trail
P1-03's evidence line named only the prototype commit. The CONNACK scoping
defect found during self-review and its three regressions belong in the same
line, so the checklist reflects what was actually verified.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 16:16:58 +09:00
GodopuandClaude Opus 5 f5286a0e67 fix(issue-5): scope the persistent publisher's CONNACK result to its own connection
Found while self-reviewing phase 1. PersistentPublisher held the connect
handshake result on the instance, so a refused attempt left its reason code
behind for the next one. On retry the wait loop saw a non-None value straight
away and never waited for the new connection's CONNACK, which is wrong in both
directions:

  * a healthy second connection was rejected using the first attempt's rc, and
  * once a late callback had written a success rc, a subsequent connection that
    never acknowledged could be accepted on that stale value, letting a publish
    proceed on a socket that was not ready.

Both need an asynchronous CONNACK to reproduce, which is exactly how paho
delivers it; the earlier fake called the callback inline and hid it. The
handshake state is now a local the callback closes over, so it can only ever
describe the connection that produced it, and a client that fails the handshake
is torn down instead of leaked.

No production path is affected today: the CLI and shell helpers publish once
per process and use OneShotPublisher. The defect mattered because the phase 2a
engine is meant to build on this prototype, which is where a transient refusal
would have become a stuck publisher.

Also tightens PV-1 to check the bound tree against pytest's real basetemp
rather than sniffing for "pytest-" in the path.

Verified: the three new regressions fail against the previous implementation
(2 of 3, the third covers the healthy path) and pass against this one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 16:15:40 +09:00
GodopuandClaude Opus 5 508ca99d71 docs(issue-5): phase 1 benchmark results, contract mapping, task checklist
Records the measured numbers and syncs every document that names the
delegation script paths, then bumps the framework to 4.3.0 in the three-way
lockstep (lib.sh, VERSIONS.md current + matrix, eight SKILL.md frontmatters).

phase1-benchmark.md carries both arms. The deterministic fake transport is what
CI asserts on: 50 publishes cost 50 connections one-shot and 1 persistent, p50
54.813ms -> 0.002ms. The real broker run is informational, since the PoC
default is a public broker: p50 1892.728ms -> 275.992ms, about 85% off.

It also corrects the plan's own estimate rather than repeating it. D8 predicted
the new shell path would drop from 3 forks to 2; the implementation is still 3,
because keeping the `_delegate_script publish_event.py` lookup is the only
thing that produces the "missing script tree does nothing" non-fatal contract
that C-02 pins. Saving that fork would change the contract, so it is deferred
to phase 4 rather than taken quietly.

SKILL.md gains the context table saying which tree wins where, so an operator
reading it knows a frozen loop runs frozen delegation code. The script paths in
every document remain correct and every quoted command still works verbatim.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 15:48:38 +09:00
GodopuandClaude Opus 5 a4b7b45e13 feat(issue-5): persistent MQTT publisher prototype and benchmark harness
Splits publish_event.main into three pieces with no behaviour change:

  prepare_event   load the job, consume the seq, build the signed payload,
                  decide retain. The seq is burned here, before any transport
                  runs, so a failed publish can never leave a number a replayed
                  packet could reuse.
  record_outcome  audit record, registry event log and status sync -- all three
                  best effort, all three regardless of the publish result. That
                  is exactly the contract G-1/G-2/G-4 pin down, now in one place.
  main            parse, prepare, publish with retry, record.

publisher.py holds the two transports behind one interface. OneShotPublisher is
the current behaviour. PersistentPublisher keeps a single connection and lets
paho reconnect underneath, raising on an unacknowledged publish so the caller's
retry policy stays the only thing deciding attempt counts. It refuses an event
for a different broker rather than publishing to the wrong place.

Nothing in production uses the persistent path: the CLI and shell helpers exit
after one publish. The consumer is the phase 2a engine, which pays the CONNACK
cost on every event today -- this job's own started event took ~12.5s because
of one CONNACK timeout plus reconnect.

bench.py measures both arms. The fake transport is deterministic and is what
the tests assert on; the real-broker arm is informational, since the PoC
default is a public broker whose latency is not ours to control.

Verified: N publishes cost N connections one-shot and 1 persistent; the two
transports leave field-for-field identical registry and audit records including
the HMAC signature and retain flag; an unacknowledged publish retries on the
same connection and records published=false; a second broker is refused. No
test opens a socket.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 15:44:33 +09:00
GodopuandClaude Opus 5 78cb9ecfa9 feat(issue-5): DelegationService, cli router, ensure_subscriber_daemon; lib.sh helpers delegate to python
Adds the python side of the delegation helpers and switches lib.sh over to it.

  daemon.py   port of start_watchdog. Same monitor path, same pgrep pattern, so
              a daemon started by either implementation is found by the other;
              same stderr wording and exit 1 when reconcile.sh is missing; same
              "print the PID" contract, multiple pgrep matches included, since
              the shell echoed them all and trimming would be a silent change.
              start_new_session detaches it, and SIGHUP is ignored across the
              exec so it outlives its parent exactly as nohup did.
  cli.py      thin router. submit/publish forward to the existing main() of the
              module that already owned the behaviour, so exit codes, stdout
              shape and side effects cannot drift between the shell path and
              the script path. Only ensure-daemon carries logic of its own.
  service.py  DelegationService facade, with an optional persistent connection
              for the phase 2a engine. CLI and shell always use one-shot.

lib.sh keeps the three legacy bodies verbatim as _*_legacy behind
MAM_DELEGATION_PY=0, which is the instant rollback switch. PYTHONPATH is passed
explicitly so `-m` resolves lib_py from the tree this lib.sh belongs to, which
is what makes a frozen loop run frozen delegation code. start_watchdog survives
as an alias for ensure_subscriber_daemon.

The wrapper and run_loop.sh are untouched; reconcile.sh gains only the
ensure_env_loaded line from the previous commit.

Verified: C-01..C-09 pass against both the legacy and the python bodies, the
daemon dedups and survives its parent, the cli reproduces the legacy failure
line exactly, and publish failure semantics (status synced, seq consumed,
audit records published=false) are identical through the shim and the cli.
tier1+tier2 109 passed; bash -n clean on all six shell files.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 15:42:09 +09:00
GodopuandClaude Opus 5 fb3498e23b refactor(issue-5): move delegation scripts into lib_py.delegation with package-bound shims
The four delegation scripts become a real package. Their old paths stay as
shims because those paths are a wire contract: agent instructions, the bash
wrapper, SKILL.md, BOOTSTRAP.md, deploy/install.sh and three test modules all
call them literally.

The shim binds the lib_py.delegation *package* to the tree beside it, once per
process, and never touches sys.path. Two cheaper designs were rejected with
evidence (the context matrix now lives in the test suite):

  * inserting the sibling skills dir at sys.path[0] makes the first sandbox
    copy imported under pytest shadow lib_py.agents/layout/state for the whole
    session, and the identity assertion cannot see it -- `is` proves same
    object, not same tree.
  * loading only the named module by file path leaves a module that imports
    siblings pulling them from whichever tree is on the path, so a frozen
    publish_event ran against live dependencies and lost half of B-13.

Binding the package fixes both: one tree for all delegation modules, the parent
lib_py untouched, and a sys.path append only when no lib_py exists anywhere
(true standalone). Bind-once rather than nearest-wins, because rebinding would
split existing references and break monkeypatching.

Also moves the env-file load off import (_load_dotenv -> ensure_env_loaded,
called by each process entry point including reconcile.sh's embedded
subscriber), so importing the library no longer mutates os.environ.

Verified: PV-1 identity+provenance, PV-4's ten import scenarios plus K1/K3/K6
in fresh interpreters, PV-5 shim byte-identity, an AST check that the package
imports no sibling lib_py module, and --help output diffed against the
pre-move capture.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 15:41:43 +09:00
GodopuandClaude Opus 5 265a1f6c3d test(issue-5): phase 1 delegation characterization suite
The three lib.sh delegation helpers (delegate_submit_job,
delegate_publish_event, start_watchdog) had zero direct test coverage, so a
"full suite green" gate would have been vacuous for the Phase 1 extraction.
Add the regression oracle before the move:

- C-01..C-09 golden tests for the shell helpers: the non-fatal contract (empty
  job id, missing script, non-zero interpreter exit), exact argv forwarding,
  stdout-is-the-job-id-alone, and the daemon's PID/dedup/log-path behaviour.
  All are parametrized over MAM_DELEGATION_PY so the legacy and python bodies
  must agree.
- CLI contract snapshots taken from the argparse parsers rather than --help
  text, so wording stays free to change but option names, choices and defaults
  do not.
- Auto-completion invariant guards for the three surfaces that decide job
  status: EVENT_TO_STATUS, the wrapper's exit-code mapping, and reconcile.sh's
  terminal mutation literals.
- conftest: PV-2/PV-3 session guards asserting that every non-delegation
  lib_py.* module resolves to the real skills tree and that no temp-tree
  sys.path entry contributes a lib_py package. MAM_ENV_FILE is pointed at an
  absent file inside the sandbox so delegation code can never inject the real
  .mam.env into a test process.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UrDNJkHmm18uu7n7JwV5Qd
2026-09-06 15:33:37 +09:00
Godopu fc0bd96d8a test(issue-5): harden watcher evidence validation and add codex pass review report
- Enforce evidence-root confinement for capture_ref and 1:1 capture citation uniqueness
- Add pane identity and backend identity cross-validation
- Add bidirectional agreement checks between watcher/herdr manifests and scenario fixtures
- Expand contract test suite to 41 tests (100% pass)
- Document evidence confinement rules in herdr-runtime.md and update task.md
- Archive Codex 4th review report (Job 1bd561e6: [VERDICT: PASS])
2026-09-06 14:31:41 +09:00
Godopu 19d798bf8f test(issue-5): implement fail-closed evidence dispatch and fix VALID_STATUSES citation
- Fix Codex [P1]: add SUPPORTED_SOURCE_KINDS dispatch and enforce fail-closed rejection for non-herdr observed items without independent schema
- Add strict correspondence checks for native Herdr observed items (agent_status, native schema, session UUID)
- Add negative test reproducing Codex in-memory mutation of finalized_candidate
- Fix Claude Finding 2: update VALID_STATUSES citation in baseline.md to registry.py:38
- Update Phase 0 collected test counts to 499 in contract docs
2026-09-06 13:37:07 +09:00
Godopu dd774b1a9f test(issue-5): add phase 0 contract validation and negative test suite 2026-09-06 13:27:47 +09:00
Godopu f85fa5b6cf test(issue-5): add layer-1 herdr and layer-2 watcher test fixtures 2026-09-06 13:27:45 +09:00
Godopu 720774c1e7 docs(issue-5): add phase 0 contract specifications, state transitions, and implementation plan 2026-09-06 13:27:42 +09:00
Godopu fa59741a9b docs(reports): archive issue #5 consolidated cross-review report (Rev.2) 2026-09-06 13:27:40 +09:00
Godopu 47640e2fd7 fix(codex): resolve peer-review findings R1-R6 and T1-T2
- R1: use herdr send-keys C-c for graceful stop
- R2: preserve JSONL fallback discovery when database is empty
- R3: apply workspace-scoped SQLite query before bounding results
- R4: tighten artifact validation to fail closed on missing/invalid metadata
- R5: verify actual rollout presence before reporting resumable in status
- R6: remove unconditional drift-B backend command fallback
- T1: parameterize artifact metadata regression with verified finder fixture
- T2: seed unmanaged and managed sessions in mock herdr for drift-B testing
- Add final loop review reports (100% PASS)
2026-09-06 00:18:19 +09:00
Godopu 76f10b2096 feat(agent): add full codex agent support (v4.2.0)
- Implement CodexAdapter in lib_py/agents/adapters/codex.py with safe flags and TUI readiness
- Extend create_session, resume_session, stop_session, and reconcile for codex CLI
- Support codex agent delegation and loop integration across all multi-agent skills
- Add unit, component, and contract test suites for codex integration
- Verify all 462 tests passing cleanly
2026-09-05 23:02:29 +09:00
Godopu de0a9c2e81 fix(herdr): guard idle-pane env wrapping on explicit env_flags in new-session
- Prevent injecting 'env HERDR_WORKSPACE_ID=...' into final_cmd when caller passed no environment variables
- Avoid argument parse errors in real agent binaries (e.g. grok, agy) when reusing an idle pane in new-session
2026-09-05 21:01:18 +09:00
Godopu 4d11308497 docs(reports): archive markdown audit & cleanup plan and unanimous peer review reports 2026-09-02 09:01:06 +09:00
Godopu cfa15eadee docs(cleanup): remove redundant root-level bug report and synchronize project documentation to v4.1.3 2026-09-02 09:01:04 +09:00
Godopu 8154d9a12b docs(reports): archive v4.1.3 post-commit peer review reports (100% unanimous PASS) 2026-08-31 11:50:06 +09:00
Godopu 4b2f703a73 docs(reports): archive v4.1.3 version update assessment and unanimous peer review reports 2026-08-31 11:25:09 +09:00
Godopu 85a46ef98b chore(release): bump framework and 8 skills to v4.1.3 (PATCH — herdr daemon isolation & Class A 0-turn resume reliability fixes) 2026-08-31 11:25:07 +09:00
Godopu 94f2e213d2 docs(reports): archive Issue #3 analysis, implementation plan, and multi-agent peer review reports
- Add Rev. 3 technical analysis report from creator-agy-01
- Add implementation plan from planner-reviewer-claude-01
- Add peer review reports across analysis and implementation review loops (Claude, Grok, OpenCode)
2026-08-31 10:30:46 +09:00
Godopu 7e15081d87 fix(resume): allow fresh spawn fallback and refresh epoch on 0-turn Class A resume
- Branch on Class A agents (agy, hermes, opencode) in resume_session.sh to fall back to clean spawn (CMD_FULL) when stopped before first turn (empty UUID)
- Update update_yaml_resumed.sh to support empty UUID with --cmd-full and refresh herdr_session_epoch on fresh spawn resume to prevent stale transcript capture
- Strictly preserve Class B (claude, grok) assigned UUID escape hatch and test_t8 contract
- Add regression tests test_t14, test_t15, test_t16 (Closes #3 Item 2)
2026-08-31 10:30:44 +09:00
Godopu c49ee3bdd8 fix(herdr): detach daemon bootstrap into own process group via python spawner
- Replace 'nohup ... server & disown' with portable Python 'Popen(..., start_new_session=True)' in lib.sh shim generator
- Isolate headless herdr server in its own SID/PGID to protect against parent process-group signal broadcast (SIGTERM/SIGINT)
- Add regression test test_h26_daemon_spawn_uses_process_group_detachment to verify child PGID detachment (Closes #3 Item 1)
2026-08-31 10:30:42 +09:00
Godopu 50a9f32773 docs(reports): archive v4.1.2 implementation plan and unanimous peer review reports
- Add plan-c107763c (Rev 1 & Rev 2 with creator critique and refinements)
- Add report-b11cf3b2 (planner-reviewer-claude-01 PASS)
- Add report-c9796d8c (reviewer-creator-grok-01 PASS)
- Add report-8e6b346e (reviewer-opencode-01 PASS)
2026-08-30 11:02:56 +09:00
Godopu 0644e7736a chore(release): bump framework and 8 skills to v4.1.2 (PATCH — pane resolution & reuse reliability fixes) 2026-08-30 11:02:54 +09:00
Godopu 526f7a59b7 test(herdr): add regression tests for pane misattribution and idle-pane reuse
- Add test_r2 and test_r3 for bare-kind fallback restriction and R-1 exact-match enforcement
- Add test_h24 and test_h25 for idle-pane reuse and env_flags preservation
2026-08-30 11:02:51 +09:00
Godopu b327bc7132 fix(herdr): prevent pane misattribution and prioritize idle-pane reuse in new-session
- Restrict generic agent_kind fallback in _resolve_herdr_pane_id to bare-kind searches
- Exclude 'agent' key from exact-match loop to enforce R-1 fail-closed contract
- Prioritize reusing existing idle pane on new-session to prevent unbounded pane proliferation
- Wrap final_cmd with env prefix to preserve env_flags when reusing idle pane
2026-08-30 11:02:50 +09:00
Godopu ccdde63bac docs(bug-report): add upstream bug fix report artifact 2026-08-30 11:02:47 +09:00
Godopu a18f9f825b docs(reports): archive final unanimous PASS reports from grok and opencode 2026-08-30 08:36:22 +09:00
Godopu 285e6bae81 docs(reports): archive creator-agy-01 final consolidated v4.1.1 report 2026-08-30 08:31:37 +09:00
Godopu c316c43e21 docs(reports): archive reviewer-opencode-01 review reports for v4.1.1 2026-08-30 06:59:30 +09:00
Godopu a93c32cb49 docs(versions): refine SemVer section reference for v4.1.1 2026-08-30 06:14:25 +09:00
Godopu eb8057b031 chore(release): bump framework and 8 skills to v4.1.1 (PATCH — agent creation & runtime reliability fixes) 2026-08-30 06:08:15 +09:00
Godopu 6de15350c0 chore(release): bump framework and 8 skills to v4.1.0 (MINOR — OpenCode AI agent integration) 2026-08-29 23:20:53 +09:00
Godopu de2c0e6824 test(opencode): add adapter contract, TUI readiness, and lifecycle integration tests 2026-08-29 14:59:04 +09:00
Godopu 94af7f6b8a feat(opencode): wire 29-point CLI lifecycle scripts, drift-C reconciler, and skill docs 2026-08-29 14:59:01 +09:00
Godopu 7341186ef9 feat(opencode): implement OpenCodeAgentAdapter and core identity bindings 2026-08-29 14:58:57 +09:00
Godopu d1f4f9eb9e docs(opencode): add implementation plan, integration guide updates, and peer review consensus reports 2026-08-29 14:58:55 +09:00
Godopu 6c0b8b0084 chore(release): bump framework and 8 skills to v4.0.0 (MAJOR — cline removal & hermes modernization)
- Bump MAM_VERSION to 4.0.0 in lib.sh
- Bump all 8 skill frontmatter versions to 4.0.0 in 3-way lockstep
- Update VERSIONS.md with v4.0.0 changelog, migration guide (B-1..B-5), and skill matrix
- Archive multi-agent version upgrade consensus and peer review reports (439 passed, 0 failures)
2026-08-28 23:31:31 +09:00
Godopu f57cd5cdde feat(agent): deprecate and completely remove cline agent support
- Delete adapters/cline.py and unregister from registry.py
- Remove cline branches from lib.sh and all 8 skill scripts (create, resume, stop, status, reconcile, update_yaml_resumed, resolve_session_id, orc_onboard)
- Narrow own-key mapping dictionaries across lib_py core modules to 4 supported agents
- Delete cline-exclusive tests and retarget shared fixtures to grok/hermes/claude
- Update skills documentation and installation guides (439 passed, 0 failures)
- Archive cline deprecation consensus and review reports
2026-08-28 22:38:48 +09:00
Godopu e0c0c107f5 merge: support-hermes branch (Hermes agent support modernization) 2026-08-28 20:18:40 +09:00
Godopu 6208a7fda3 feat(hermes): modernize hermes agent adapter and skills support
- Add --yolo and --accept-hooks headless auto-approval flags to spawn_spec and resume_spec
- Define Hermes TUI input delimiters (input_prompt='❯', input_rule_pattern='─{10,}')
- Refactor verify_artifact and discover in hermes.py using session started_at timestamps
- Fix HERDR_EPOCH capture timing before spawn in create_session.sh to prevent epoch race
- Update reconcile.sh for hermes drift-C multi-candidate and sibling claimed exclusion
- Add Hermes contract, epoch filtering, and C-ambiguous unit tests (140 passed)
- Add agent evaluation report and final review reports for Hermes support
2026-08-28 20:17:04 +09:00
Godopu 4a3328d0b7 chore(release): bump framework and 8 skills to v3.1.0 (MINOR)
- Define immutable MAM_VERSION="3.1.0" runtime constant in lib.sh
- Bump YAML frontmatter version to 3.1.0 across all 8 skill packages
- Document v3.1.0 changelog, 2-tier TUI readiness architecture, and migration guide in VERSIONS.md
- Document new tuning knobs (MAM_KILL_ON_READY_TIMEOUT, MAM_DIALOG_TAIL_LINES, MAM_READY_EMPTY_GIVEUP) in .mam.env.example
- Add 3-way lockstep and immutability test suite in tests/test_version_consistency.py
2026-08-28 18:25:14 +09:00
Godopu 17edf90676 fix(tui): establish 2-tier readiness model, modal/hint token separation, and adapter modal contracts
- Separate TUI dialog detection into blocking gate layer (_MAM_MODAL_TOKENS) and recovery layer (_MAM_HINT_TOKENS) to eliminate idle dialog starvation
- Add modal_tokens contract across agent adapters (claude, cline) with dynamic scope facts resolution in send_keys_safe
- Implement fail-closed resolution for ambiguous same-kind panes (R-1) and enforce WORKSPACE_ROOT export (R-2)
- Preserve session on TUI readiness timeout when PID is alive for diagnostics
- Add comprehensive test suite in tests/test_c1_tui_readiness.py and adapter contract assertions in test_a4
2026-08-28 15:21:10 +09:00
Godopu 4a5a093986 chore(docs): clean up temporary FIX.md and bug_report.md 2026-08-27 21:43:26 +09:00
Godopu c3631e2aa1 fix(herdr): resolve shim routing defects, add workspace scoping, and bump to v3.0.1
- Resolve Herdr shim 5 routing & paste defects (ISSUE-1 ~ ISSUE-5):
  * paste-buffer: use pane send-text without auto-enter, propagate rc=3 to send_keys_safe
  * exact-match pane resolution: remove substring matching ('in tn') across all branches
  * workspace scoping: introduce HERDR_WORKSPACE_ID and .mam/herdr_workspace_id persistence
  * unified resolver: single _resolve_herdr_pane_id helper across shim commands
- Resolve dialog token false-positive on 'Yes, try it' tip and isolate fullscreen modal rejection
- Sync mock Herdr CLI contracts in tests/conftest.py
- Add contract tests H-15~H-23 and regression tests D-4~D-7 (412 tests, 100% PASS)
- Add multi-agent loop plans, review reports, and bug report
- Update framework and skill packages to v3.0.1
2026-08-27 21:42:37 +09:00
Godopu 4bbd03bf2d fix(lib): handle agent_not_ready startup state and reject claude fullscreen upsell modal
- Accept agent_not_ready from herdr agent start to allow startup dialog handling without premature rollback, while preserving fail-closed behavior on dead process timeouts.
- Match Claude fullscreen renderer upsell modal via 'Yes, try it' and dismiss with Escape to avoid dropping permission flags or deadlocking on idle /tui tips.
- Add behavioral test suite in test_b19_headless_reconcile_fixes.py and cross-agent review reports.
2026-08-27 10:17:53 +09:00
Godopu d875584ef4 chore(submodule): update nats-docker submodule to 26fd65a 2026-08-26 18:38:52 +09:00
Godopu b18e0ae0bc docs: add verification report for v3.0.0 deployment and installation 2026-08-26 15:53:22 +09:00
Godopu 050baed640 fix(lib): enhance target agent resolution and import fallback in herdr shim 2026-08-26 15:41:50 +09:00
Godopu 08f138d30d chore(release): bump framework and skills version to v3.0.0 2026-08-26 15:18:00 +09:00
Godopu 97fb1d254b docs(layout): add 2xK layout improvement plan and multi-agent review reports
- Add Rev.2 authoritative plan detailing root causes and 2xK decision table
- Add Phase 1 & 2 review reports from Claude (planner/reviewer) and Cline (reviewer)
2026-08-26 15:10:08 +09:00
Godopu 80d2f7f068 feat(layout): implement deterministic 2xK grid engine with single decision table
- Change N=1->2 split policy from down to right to establish 2 full-height columns
- Share single decision table across GUI and headless modes
- Add _full_height_pane guard to prevent half-height column splits
- Quadruple-wire default max_columns=2 and max_rows=2 across layout.py, lib.sh, and .mam.env.example
- Update unit and integration tests to enforce deterministic 2x2 grid trajectory
2026-08-26 15:10:06 +09:00
Godopu 5ed9ec79d7 fix(resume): add grok agent support to resolve_session_id and resume_session 2026-08-26 15:10:03 +09:00
738 changed files with 96651 additions and 4063 deletions

No files matched your search

+2 -1
View File
@@ -18,7 +18,7 @@
- **모호성 제거**: 사용자의 요구사항에 모호한 부분이 있다면 작업을 추측하여 진행하지 말고, 즉시 사용자에게 질문하여 명확히 해야 합니다 (`/grill-me` 슬래시 명령어 권장). - **모호성 제거**: 사용자의 요구사항에 모호한 부분이 있다면 작업을 추측하여 진행하지 말고, 즉시 사용자에게 질문하여 명확히 해야 합니다 (`/grill-me` 슬래시 명령어 권장).
### 👥 Team Leaders (팀장) ### 👥 Team Leaders (팀장)
새롭게 생성되는 에이전트(`antigravity`, `claude`, `cline`, `hermes` 등)는 각 팀의 **팀장** 역할을 수행합니다. 총괄 매니저로부터 작업을 위임받아 개발 또는 리뷰 워크플로우를 주도합니다. 새롭게 생성되는 에이전트(`antigravity`, `claude`, `hermes`, `grok`, `opencode`, `codex` 등)는 각 팀의 **팀장** 역할을 수행합니다. 총괄 매니저로부터 작업을 위임받아 개발 또는 리뷰 워크플로우를 주도합니다.
- **Developer Team Leader (개발 팀장)**: - **Developer Team Leader (개발 팀장)**:
- 총괄 매니저로부터 작업을 위임받습니다. - 총괄 매니저로부터 작업을 위임받습니다.
- **작업 분석 및 계획**: 주어진 작업을 철저히 분석하고, 작은 단위로 문제를 나누어 세부 계획을 수립합니다. - **작업 분석 및 계획**: 주어진 작업을 철저히 분석하고, 작은 단위로 문제를 나누어 세부 계획을 수립합니다.
@@ -151,6 +151,7 @@ TMUX 환경에서 실행되는 에이전트가 화면 스크롤 한계로 인해
- **작업 위임**: - **작업 위임**:
- *수동 경로*: 상세 사양과 계획 수립 등의 복잡한 작업 지시는 먼저 로컬 마크다운 파일(예: `.mam/reports/brief-<job_id>.md` 또는 지정된 워크스페이스 경로)로 작성한 후, 에이전트에게 `"Read <파일경로> and execute."` 라는 실행 명령만 전달하십시오. - *수동 경로*: 상세 사양과 계획 수립 등의 복잡한 작업 지시는 먼저 로컬 마크다운 파일(예: `.mam/reports/brief-<job_id>.md` 또는 지정된 워크스페이스 경로)로 작성한 후, 에이전트에게 `"Read <파일경로> and execute."` 라는 실행 명령만 전달하십시오.
- *자동 경로*: 자동화 잡 런너(`multi-agent-mux-delegate-job submit`)는 잡 등록 시 `.mam/jobs/<job_id>/brief.md` 디렉터리에 지시서를 자동 집필하고 단일 라인 포인터 프롬프트만 에이전트 세션에 인가합니다. - *자동 경로*: 자동화 잡 런너(`multi-agent-mux-delegate-job submit`)는 잡 등록 시 `.mam/jobs/<job_id>/brief.md` 디렉터리에 지시서를 자동 집필하고 단일 라인 포인터 프롬프트만 에이전트 세션에 인가합니다.
- *하위 위임*: 자기 잡의 일부를 다시 위임하는 에이전트는 `submit` 에 `--parent-job <자기 job_id>` 를 붙입니다. 그래야 루프가 그 하위 잡을 기다리고 리뷰어에게 보여 줍니다(Issue #34).
- **결과 안내 및 피드백**: - **결과 안내 및 피드백**:
- *수동/영구 리뷰*: 상세 리뷰 결과, 설계 제안서 등은 `.mam/reports/<tmux_session_name>/report-<job_id>.md` 경로에 저장합니다. - *수동/영구 리뷰*: 상세 리뷰 결과, 설계 제안서 등은 `.mam/reports/<tmux_session_name>/report-<job_id>.md` 경로에 저장합니다.
- *자동화 잡 보고서*: 자동 위임된 비동기 작업의 완료 결과는 잡 디렉터리 하위인 `.mam/jobs/<job_id>/<agent_name>-reports/report-final.md` (루프/Discuss 위임 시에는 `<clean_session_name>-reports/`) 경로에 기록해야 합니다. - *자동화 잡 보고서*: 자동 위임된 비동기 작업의 완료 결과는 잡 디렉터리 하위인 `.mam/jobs/<job_id>/<agent_name>-reports/report-final.md` (루프/Discuss 위임 시에는 `<clean_session_name>-reports/`) 경로에 기록해야 합니다.
+4 -2
View File
@@ -18,7 +18,7 @@ We clearly separate responsibilities and permissions between roles to reduce bot
- **Ambiguity Resolution**: If a user's requirements contain ambiguous details, do not guess. Immediately ask the user for clarification (we recommend using the `/grill-me` slash command). - **Ambiguity Resolution**: If a user's requirements contain ambiguous details, do not guess. Immediately ask the user for clarification (we recommend using the `/grill-me` slash command).
### 👥 Team Leaders (팀장) ### 👥 Team Leaders (팀장)
Newly spawned agents (e.g., `antigravity`, `claude`, `cline`, `hermes`) act as **Team Leaders** of their respective groups. They receive delegated tasks from the General Manager and manage implementation or review workflows. Newly spawned agents (e.g., `antigravity`, `claude`, `hermes`, `grok`, `opencode`, `codex`) act as **Team Leaders** of their respective groups. They receive delegated tasks from the General Manager and manage implementation or review workflows.
- **Developer Team Leader (개발 팀장)**: - **Developer Team Leader (개발 팀장)**:
- Receives tasks from the General Manager. - Receives tasks from the General Manager.
- **Task Breakdown & Planning**: Thoroughly analyzes the task, breaks it down into small units, and creates a plan. - **Task Breakdown & Planning**: Thoroughly analyzes the task, breaks it down into small units, and creates a plan.
@@ -151,6 +151,7 @@ To ensure that agents running in TMUX environments do not lose debug logs or pre
- **Task Delegation**: - **Task Delegation**:
- *Manual path*: Detailed task briefs may be written to a local Markdown file (e.g., `.mam/reports/brief-<job_id>.md` or a workspace path) first. The sender then issues a simple trigger command: `"Read <file_path> and execute."` - *Manual path*: Detailed task briefs may be written to a local Markdown file (e.g., `.mam/reports/brief-<job_id>.md` or a workspace path) first. The sender then issues a simple trigger command: `"Read <file_path> and execute."`
- *Automated path*: The automated job runner (`multi-agent-mux-delegate-job submit`) automatically provisions the brief at `.mam/jobs/<job_id>/brief.md` and sends a short pointer instruction to the agent. - *Automated path*: The automated job runner (`multi-agent-mux-delegate-job submit`) automatically provisions the brief at `.mam/jobs/<job_id>/brief.md` and sends a short pointer instruction to the agent.
- *Sub-delegation*: an agent that delegates part of its job passes `--parent-job <its job_id>` to `submit`, so the loop waits for the sub-job and shows it to reviewers (Issue #34).
- **Result Reporting & Feedback**: - **Result Reporting & Feedback**:
- *Manual/Durable reviews*: Detailed reviews, design proposals, or audit reports must be saved under `.mam/reports/<tmux_session_name>/report-<job_id>.md`. - *Manual/Durable reviews*: Detailed reviews, design proposals, or audit reports must be saved under `.mam/reports/<tmux_session_name>/report-<job_id>.md`.
- *Automated job reports*: Automated execution results are saved directly to `.mam/jobs/<job_id>/<agent_name>-reports/report-final.md` (or `<clean_session_name>-reports/` for loops) as transient files. - *Automated job reports*: Automated execution results are saved directly to `.mam/jobs/<job_id>/<agent_name>-reports/report-final.md` (or `<clean_session_name>-reports/` for loops) as transient files.
@@ -168,7 +169,8 @@ To ensure that agents running in TMUX environments do not lose debug logs or pre
- **Identity Verification**: The guard validates process liveness via `pid` + `lstart` to prevent livelocks on PID rollover. - **Identity Verification**: The guard validates process liveness via `pid` + `lstart` to prevent livelocks on PID rollover.
### ⏱️ Timeout Configuration & Alignment Rules ### ⏱️ Timeout Configuration & Alignment Rules
- **Job Execution Limits (`timeout_sec` & `idle_timeout_sec`)**: Each job independently manages its overall execution timeout (`timeout_sec`, default 3600s) and idle timeout without receiving messages (`idle_timeout_sec`, default 120s). - **Job Execution Limits (`timeout_sec` & `idle_timeout_sec`)**: Each job independently manages its overall execution timeout (`timeout_sec`, default 3600s) and idle timeout without receiving messages (`idle_timeout_sec`). Since v4.5.0 (Issue #18) the idle timeout is the liveness contract's K x N: the agent heartbeats every `heartbeat_sec` (N, default 30 — automatic once it publishes `started --heartbeat N`), and `heartbeat_misses` (K, default 4) missed heartbeats close the job as `deadline_timeout` (default 120 s, `--idle-timeout` overrides). `started` must arrive within `ack_timeout_sec` (T, default 180) of the injection or the job fails as `agent_blocked` without re-injection. herdr status and pane text are never used for these decisions.
- **Heartbeat timer and agent life**: the automatic timer is bound to the agent process that ran the start command (the nearest agent-CLI ancestor, or `--watch-pid`) and stops within one period once that process is gone; a crashed agent is therefore closed after K x N like any silent one, while an agent that is alive but stuck keeps heartbeating (process liveness, not work liveness).
- **Monitor Idle Waiting (`SUB_IDLE_TIMEOUT`)**: The idle timeout for the monitor script (`reconcile.sh`), `SUB_IDLE_TIMEOUT`, must always be set generously to `3600s` (1 hour) or more to align with the maximum job budget. This prevents the monitor from terminating early due to idle detection, which would lose control over background tasks before they finish. - **Monitor Idle Waiting (`SUB_IDLE_TIMEOUT`)**: The idle timeout for the monitor script (`reconcile.sh`), `SUB_IDLE_TIMEOUT`, must always be set generously to `3600s` (1 hour) or more to align with the maximum job budget. This prevents the monitor from terminating early due to idle detection, which would lose control over background tasks before they finish.
--- ---
+170
View File
@@ -0,0 +1,170 @@
# 🧭 Agent Backend Evaluation — Local LLM (Ollama / GLM-5.2) CLI Integration
- **Planner**: `planner-reviewer-claude-01`
- **Job ID**: `50c8456e` (Rev.1) → refined under `8aee5fdb` (Rev.2)
- **Scope**: Evaluate `hermes`, `pi`, and `opencode` as candidates for official Multi-Agent Mux (MAM) integration, specifically to support a **local LLM backend** (Ollama-hosted, target model **GLM-5.2**).
- **Status**: Rev.2 — refined per `creator-agy-01`'s architectural challenge (job `f98023cb`). Still pending a live `[VERDICT: PASS]` before adapter implementation begins (see §6).
---
## 0. Changelog — Rev.2 (response to `creator-agy-01` challenge)
`creator-agy-01` filed a formal architectural challenge against Rev.1 (full text preserved in `.mam/jobs/8aee5fdb/brief.md`), raising four points. **All four are accepted as valid — no `[REBUT:]` is filed.** Each is grounded in evidence already present in this repo (the permission-bypass flags actually shipped in `claude.py`/`agy.py`/`grok.py`, and the Session ID Lifecycle protocol in `MULTI_AGENT_RULES.md` §2) or in well-established Ollama operational behavior, and Rev.1 did not address any of them. Changes made:
| # | Challenge | Disposition | Where addressed in Rev.2 |
|---|---|---|---|
| 1 | Unverified unattended permission-bypass flag for OpenCode | **Accepted** | New §3.2 "Unattended Execution Compatibility" subsection; new Phase 0 checklist item; new comparison-matrix row |
| 2 | Unverified `--session-id` pre-assignment support for OpenCode (breaks P0 assigned-UUID protocol → `C-ambiguous` risk) | **Accepted** | New §3.2 subsection; new adapter-contract fallback requirement in Phase 2 §8; new comparison-matrix row |
| 3 | Ollama default `num_ctx: 2048` causes tool-call/context truncation unless raised (~32768) | **Accepted** | New §4.3; new Phase 0/1 documentation deliverable |
| 4 | Local-inference cold-start/latency vs. MAM's 120s `idle_timeout_sec` watchdog | **Accepted** | New §4.4; new Phase 0/1 config recommendation (`MAM_IDLE_TIMEOUT` relaxation) |
Net effect: OpenCode's status is downgraded from "Low-Medium, well-precedented" to **"Low-Medium, contingent on two unverified CLI capabilities that must be confirmed before adapter work starts"** — this changes the Phase 0 gate from optional-best-practice to **hard blocking prerequisite** for Phase 2.
---
## 1. Executive Summary & Recommendation
**Recommended path: two-track rollout, OpenCode as primary target, Hermes as immediate interim path, `pi` deferred pending scope clarification.**
| Rank | Candidate | Verdict | Rationale (1 line) |
|---|---|---|---|
| 1 | **OpenCode** | ✅ **Primary integration target** | Purpose-built multi-provider harness with first-class local-model/Ollama support and a provider-agnostic tool-calling layer — best long-term fit for GLM-5.2 stability. |
| 2 | **Hermes** | ✅ **Interim / parallel-track** | Adapter already exists in MAM (`hermes.py`, registered) with **zero net-new integration cost**; `auth_ok()` has no hard-coded SaaS credential gate, which is favorable for pointing it at a local endpoint — but its tool-calling behavior against GLM-5.2 via Ollama is unverified and must be smoke-tested before it's trusted for unattended Creator/Reviewer roles. |
| 3 | **`pi`** | ⚠️ **Insufficient information — do not integrate yet** | No adapter, no roadmap mention, and no reliable architectural grounding was found in this repo or in prior MAM reports. See §4.3 and §7 for what must be clarified before this candidate can be scored. |
This is a **Planner-level architectural recommendation**, not a unilateral final decision — per `MULTI_AGENT_RULES.md` §3, it should be routed to the currently running Reviewer/Creator sessions (`reviewer-creator-grok-01`, `creator-agy-01`) for a `[VERDICT: PASS]` / `[VERDICT: NOT PASS]` pass before any adapter code is written. See §6.
---
## 2. Evaluation Criteria
Weighted against MAM's existing 5-layer adapter contract (`BaseAgentAdapter`, see `new_agent_types_roadmap.md` §2–3) and the stated goal (local LLM support):
1. **Local-model / Ollama compatibility** — Can the CLI point at a local OpenAI-compatible or native Ollama endpoint without vendor lock-in?
2. **Tool-calling stability** — Does the CLI enforce its own structured function-calling schema/validation layer independent of the backing model, or does it trust raw model output? This matters more for GLM-5.2 than for frontier hosted models, since open-weight tool-calling adherence varies by quantization/serving stack.
3. **MAM adapter-contract fit** — Session artifact format, `ready_tokens` predictability, auth model, resume/purge semantics (i.e., cost to implement `BaseAgentAdapter`).
4. **Integration cost** — Net-new engineering effort across the 5 layers (adapter, registry, `lib.sh` dispatch, herdr kind support, tests).
5. **Operational maturity** — Update cadence, community/maintainer signal, TUI stability under herdr's raw-terminal automation (`send_keys_safe`).
---
## 3. Candidate Profiles
### 3.1 Hermes — *already integrated at Tier 1*
- **Repo evidence**: `.agents/skills/lib_py/agents/adapters/hermes.py` exists and is registered in `registry.py`. This is the only one of the three candidates with a working, tested MAM adapter today.
- **Session storage**: SQLite (`~/.hermes/state.db`, `sessions`/`messages` tables) keyed by `cwd` — more robust than flat-file JSON candidates (grok, opencode) for concurrent-workspace disambiguation, and purge semantics are already implemented (`purge_artifacts` deletes both the on-disk JSON and DB rows).
- **Auth model**: `auth_ok()` unconditionally returns `True` — there is no hard-coded credential/token-file check the way `grok.py` checks `~/.grok/auth.json` or `XAI_API_KEY`. This is a **positive signal** for local-LLM use: it implies Hermes's own config (outside MAM's purview) is what selects the backend, so pointing it at an Ollama endpoint hosting GLM-5.2 should not trip any MAM-level auth gate.
- **Readiness detection**: `ready_tokens = 'Hermes'` — a single, simple banner token. Low risk of TUI-readiness false-negatives, but also under-specified compared to grok's multi-token pattern (`'Grok|xAI|Assistant|❯|>>>'`); should be hardened if Hermes's banner changes across backend configurations (e.g., does it print the active model name?).
- **Gap**: Nothing in the adapter or this repo verifies **which** backend/model Hermes is actually running against at spawn time. `spawn_spec()` takes no model/backend argument — model selection is presumably out-of-band (Hermes's own config file/env). This must be confirmed empirically, not assumed.
- **Integration cost**: **Zero** (already done). Remaining cost is *validation*, not *engineering*.
### 3.2 OpenCode — *roadmapped, not yet implemented*
- **Repo evidence**: Appears only in `new_agent_types_roadmap.md` §4 as a **Tier 1 (Low)** complexity candidate (~0.5 day estimated effort), session storage as JSON files under `~/.opencode/sessions/`, proposed `ready_tokens: 'OpenCode|Chat|Welcome'`.
- **Ecosystem knowledge**: OpenCode is designed from the ground up as a **provider-agnostic** terminal coding agent — its core value proposition (distinct from single-vendor CLIs like Claude Code) is a pluggable model-provider layer that explicitly supports local/self-hosted backends (Ollama, LM Studio, and any OpenAI-compatible endpoint) alongside hosted providers, with per-project/per-agent model configuration.
- **Tool-calling stability**: Because OpenCode's edit/bash/read tool surface is enforced by its own harness rather than assumed from the model, it is materially more resilient to a local model's imperfect native function-calling than a thin CLI that passes tool schemas straight through to the model API. This is the strongest differentiator in GLM-5.2's favor, since open-weight tool-calling reliability is known to vary by quantization and serving backend (Ollama's tool-calling support itself is still evolving).
- **Gap**: Requires **net-new** engineering across all 5 layers per the roadmap blueprint (adapter class, registry entry, `lib.sh` kind mapping + binary-name recognition, herdr `--kind` compatibility check, contract + lifecycle tests). Estimated ~0.5–1.5 days per the existing complexity matrix, consistent with grok's actual delivered effort (grok is now fully integrated, confirming the roadmap's Tier 1 estimates are realistic).
- **Integration cost**: **Low-Medium**, well-precedented — the grok adapter (`grok.py`, fully shipped) is a directly reusable template (glob-based session discovery, JSONL artifact verification, `permission-mode`-style CLI flags). **Revised in Rev.2: this cost estimate is now contingent on the two verification gates below.**
- **⚠️ Unattended Execution Compatibility (new in Rev.2, per `creator-agy-01` challenge §2.1)**: MAM's herdr-background execution model requires the target CLI to run with **zero interactive confirmation prompts** — every existing adapter enforces this by construction: `claude.py`/`agy.py` force `--dangerously-skip-permissions`, `grok.py` forces `--permission-mode bypassPermissions`. **Rev.1 did not verify that OpenCode ships an equivalent flag** (e.g. `--auto-approve`, `--yes`, a `--permission-mode` analog). If it doesn't, the first bash/file-edit tool call will emit an interactive `[y/N]`-style prompt that blocks on stdin inside a headless herdr pane — `send_keys_safe` cannot answer a prompt it wasn't told to expect, and the job stalls until `idle_timeout_sec` (120s default) force-kills it. **This is now a hard go/no-go gate, not a nice-to-have**: OpenCode cannot be adapted for Creator/Reviewer roles at all if no such flag exists, regardless of its tool-calling or local-model strengths.
- **⚠️ Session-ID Pre-Assignment Compatibility (new in Rev.2, per `creator-agy-01` challenge §2.2)**: `MULTI_AGENT_RULES.md` §2 requires new sessions to receive an externally-generated UUID at spawn time (`--session-id <uuid>`, recorded as `session_id_source: assigned`) specifically to prevent `C-ambiguous` race conditions when multiple sessions of the same agent type are created concurrently in one workspace. **Rev.1's proposed `spawn_spec()` (mirroring grok's `--session-id {session_uuid}` pattern) assumed OpenCode accepts an externally-supplied session ID without checking it.** If OpenCode instead only generates its own internal session identifier (e.g., a hash or timestamp-derived directory name under `~/.opencode/sessions/`), the P0 pre-assignment protocol cannot be used, and `discover()` must fall back to timestamp/PID/cwd-based matching — which is exactly the race-prone pattern §2 of `MULTI_AGENT_RULES.md` was designed to eliminate. Rev.2's Phase 2 plan (§8) now specifies the required fallback contract for this case.
### 3.3 `pi` — *unresolved candidate, insufficient grounding*
- **Repo evidence**: **None.** No adapter, no mention in `new_agent_types_roadmap.md`'s candidate list (`codex`, `grok-build`, `opencode`, `kimi`, `cursor`), no reference anywhere under `.agents/` or `.mam/` prior to this job's own brief.
- **Ambiguity risk**: "pi" is a generic, collision-prone identifier — it could refer to several unrelated products (a lightweight personal-assistant chat CLI, an internal/codenamed tool, or a coding-agent CLI not yet in this evaluator's confirmed knowledge). Fabricating an architecture/auth/session-format profile for it would produce a plausible-sounding but unverifiable comparison, which is worse than flagging the gap — a wrong `ready_tokens` regex or session-artifact assumption baked into a plan would silently break `wait_for_tui_ready()` and session discovery at implementation time.
- **Recommendation**: **Do not score `pi` in this pass.** Before it can be evaluated on equal footing with Hermes/OpenCode, the requester must confirm: (a) the exact binary/package name and install source, (b) whether it exposes a scriptable non-interactive mode or only a raw TUI, (c) its session/transcript storage format, and (d) whether it supports pointing at an arbitrary OpenAI-compatible/Ollama endpoint at all. See §7 open questions.
---
## 4. Tool-Calling Stability Against GLM-5.2 (Ollama)
Regardless of which CLI is chosen, two risks are backend-specific (not MAM-specific) and apply to whichever candidate is selected:
1. **Function-calling schema adherence**: GLM-family models served through Ollama depend on the Modelfile's chat template correctly implementing tool-call token formatting. A CLI that validates/repairs malformed tool-call JSON client-side (OpenCode's model) degrades more gracefully than one that trusts raw output (unverified for Hermes; unknown for `pi`).
2. **Context window / quantization tradeoffs**: Local GGUF/Ollama-served quantizations of GLM-5.2 may have reduced effective context vs. the reference weights, which stresses MAM's existing long-running-session assumptions (`idle_timeout_sec`, `SUB_IDLE_TIMEOUT` in `MULTI_AGENT_RULES.md` §4). This should be smoke-tested with a real multi-turn MAM job before either candidate is trusted for unattended Creator work.
**Action item**: before committing engineering time to OpenCode's adapter, run a manual (non-MAM) smoke test of both Hermes-against-Ollama-GLM-5.2 and OpenCode-against-Ollama-GLM-5.2 on a representative multi-file edit task, and record actual tool-call success/repair rates. This evaluation is architectural; it cannot substitute for an empirical tool-calling benchmark.
### 4.3 Ollama Default Context Window (new in Rev.2, per `creator-agy-01` challenge §3.1)
Ollama's default `num_ctx` is **2048 tokens** unless explicitly overridden. MAM's job briefs, `README.md`/`MULTI_AGENT_RULES.md` reference material injected into agent context, and especially multi-turn tool-calling exchanges routinely exceed this — well below the 8k–32k range typical agentic coding workloads need. Left at the default, this produces **silent early context truncation**, which surfaces as malformed or dropped tool calls that look like a model-quality problem but are actually a serving-configuration problem. This is not specific to OpenCode or Hermes; it applies to **any** CLI pointed at an Ollama-served GLM-5.2. **Requirement**: the Modelfile (or per-request client parameter, if the CLI exposes one) must explicitly set `PARAMETER num_ctx 32768` (or the CLI's equivalent override) before any tool-calling stability conclusions from the Phase 0 smoke test can be trusted — a smoke test run against the 2048-token default would understate both candidates' true tool-calling reliability.
### 4.4 Local Inference Latency vs. MAM Watchdog Timeouts (new in Rev.2, per `creator-agy-01` challenge §3.2)
Local GLM-5.2 inference (VRAM load + generation) can plausibly take 30–60s to first token and run at single-digit-to-low-teens tokens/sec, versus the sub-second-to-few-second response latency MAM's timeout defaults were tuned against for hosted-API backends. `lib.sh::wait_for_tui_ready` and the default `idle_timeout_sec` (120s per `MULTI_AGENT_RULES.md` §4) risk false-positive stalls/kills against a working-but-slow local backend, which would misclassify healthy local inference as a hung job. **Requirement**: any local-LLM-backed session (Hermes or OpenCode) must run under a relaxed idle timeout — the challenge suggests `MAM_IDLE_TIMEOUT=300` as a starting point — set via job-level `idle_timeout_sec` override or a documented `.mam.env` convention specifically for local backends, not the global default (which should stay tuned for hosted-API sessions to avoid masking genuinely hung jobs elsewhere).
---
## 5. Comparison Matrix
| Criterion | Hermes | OpenCode | `pi` |
|---|---|---|---|
| MAM adapter status | ✅ Shipped | ❌ Roadmapped only | ❌ None |
| Local/Ollama support | Likely (out-of-band config, unverified) | ✅ Native, first-class | Unknown |
| Tool-calling validation layer | Unknown / unverified | ✅ Harness-enforced | Unknown |
| Session storage | SQLite (`state.db`) | JSON files | Unknown |
| Auth gate in MAM | None (`auth_ok` always `True`) | N/A (not yet implemented) | Unknown |
| Unattended permission-bypass flag confirmed | ⚠️ Not yet verified (needs Phase 0) | ⚠️ **Not yet verified — hard gate (Rev.2)** | Unknown |
| External `--session-id` acceptance confirmed | N/A (adapter already ships without it, uses discovery) | ⚠️ **Not yet verified — hard gate (Rev.2)** | Unknown |
| Integration cost | **Zero** (done) | Low-Medium (~0.5–1.5 days, **contingent on above two gates — Rev.2**) | Cannot estimate |
| Confidence in this evaluation | Medium (grounded in repo code) | Medium-High (grounded in repo roadmap + ecosystem knowledge) | **Low** (no grounding) |
---
## 6. Team Consensus Process Note
Per `MULTI_AGENT_RULES.md` §3, a Planner recommendation is not a final decision — it is meant to be routed through the Developer/Reviewer objection loop. At the time of writing, `.mam/agent-sessions.yaml` shows two other live sessions in this workspace:
- `reviewer-creator-grok-01` (role: `reviewer,creator`)
- `creator-agy-01` (role: `creator`; registry shows a stale `resume dry-run failed` status — its live availability should be re-confirmed by the General Manager before delegating a review job to it)
Rev.1 was produced by the Planner alone (no live cross-session review round-trip was executed as part of job `50c8456e`). **Update (Rev.2)**: that gap was subsequently closed — `creator-agy-01` did review Rev.1 and filed a formal architectural challenge (job `f98023cb`), which this Rev.2 fully incorporates (see §0). No `[REBUT:]` was needed since every point was valid. **Remaining next step**: this Rev.2 still needs an explicit `[VERDICT: PASS]` / `[VERDICT: NOT PASS]` from a Reviewer session (`reviewer-creator-grok-01`, and `creator-agy-01` re-reviewing its own incorporated feedback) before Phase 2 adapter implementation work begins — consistent with the standard Workflow Loop and the Rebuttal & Adjudication Protocol in `MULTI_AGENT_RULES.md` §3/§3.1.
---
## 7. Open Questions (block full consensus until resolved)
1. What exactly is `pi` — binary name, source, and whether it supports non-interactive/scriptable invocation compatible with herdr's `send_keys_safe` automation?
2. Is GLM-5.2 to be served via Ollama's native tool-calling API or an OpenAI-compatible shim? This affects which CLIs are even eligible (some CLIs only support OpenAI-schema tool calls).
3. Does Hermes actually expose a way to target a specific Ollama model/endpoint (env var, config file, CLI flag)? This repo's adapter is silent on model selection — needs to be confirmed against Hermes's own docs/CLI help, not assumed.
4. What quantization/context-length of GLM-5.2 will be locally hosted? This determines whether the empirical smoke test in §4 is representative of production behavior.
5. **(New, Rev.2)** Does OpenCode CLI expose a documented non-interactive/auto-approve flag equivalent to `claude`'s `--dangerously-skip-permissions` or `grok`'s `--permission-mode bypassPermissions`? **Blocking** — see §3.2.
6. **(New, Rev.2)** Does OpenCode CLI accept an externally-generated session UUID at spawn time (`--session-id`-style), or only self-assign session identifiers? **Blocking** — determines whether P0 pre-assignment or a PID/cwd-based `discover()` fallback must be used. See §3.2.
---
## 8. Integration Roadmap (pending consensus sign-off)
**Phase 0 (immediate, no code — expanded in Rev.2, now the hard gate before Phase 2)**: Manual smoke test — run Hermes and OpenCode (standalone, outside MAM) against the target Ollama/GLM-5.2 endpoint (served with `num_ctx 32768`, per §4.3) on a representative multi-file coding task. Record:
1. Tool-call success rate and malformed-call repair behavior, and session banner/readiness output for adapter tuning (Rev.1 scope).
2. **(Rev.2)** Whether each CLI can complete the task with **zero interactive confirmation prompts** using a documented flag — this determines OpenCode's Phase 2 eligibility outright (§3.2).
3. **(Rev.2)** Whether OpenCode accepts an externally-supplied `--session-id`-equivalent, or only self-assigns — this determines whether Phase 2 step 1 below uses the P0 pre-assignment pattern or the PID/cwd-based `discover()` fallback (§3.2).
4. **(Rev.2)** Observed time-to-first-token and end-to-end task latency, to calibrate the `idle_timeout_sec` override in Phase 1/2 (§4.4).
**Phase 1 (Hermes validation track, ~0 eng. days)**: No adapter work needed. Confirm Hermes's model-selection mechanism (open question #3) and, if satisfactory, promote it from "Tier 1 present but unvalidated" to "MAM-supported local-LLM backend" in `.mam.env.example` documentation. **(Rev.2)** Document the required Ollama `num_ctx 32768` Modelfile setting and the recommended local-backend `idle_timeout_sec`/`MAM_IDLE_TIMEOUT` override (starting point: 300s, to be tuned against actual Phase 0 latency data) in the same documentation pass — for both Hermes and (if greenlit) OpenCode.
**Phase 2 (OpenCode adapter track, ~0.5–1.5 eng. days, grok.py as template) — gated on Phase 0 items 2–3 passing**:
1. `.agents/skills/lib_py/agents/adapters/opencode.py` — implement `OpenCodeAgentAdapter(BaseAgentAdapter)` per the Step 1 contract in `new_agent_types_roadmap.md`. `spawn_spec()`/`resume_spec()` must include the confirmed unattended-execution flag (§3.2) unconditionally, matching the `claude.py`/`agy.py`/`grok.py` pattern.
2. **(Rev.2)** If Phase 0 confirms OpenCode accepts an external session UUID: use the standard `--session-id {session_uuid}` pattern (as Rev.1 assumed). **If not**: `discover()` must implement a strict cwd + process-liveness (PID/`lstart`) matching rule — analogous to the "Identity Verification" guard already used elsewhere in this framework (`MULTI_AGENT_RULES.md` §4) — to avoid `C-ambiguous` collisions between concurrently-spawned OpenCode sessions in the same workspace. This fallback must be explicitly covered by a `C-ambiguous`-scenario unit test (new test, not in Rev.1's plan).
3. `.agents/skills/lib_py/agents/registry.py` — import + register `'opencode': OpenCodeAgentAdapter()`.
4. `lib.sh` — herdr kind mapping (`*-creator-opencode|*-planner-opencode|*-reviewer-opencode`), binary-name recognition tuple, `send_keys_safe` input-region delimiters.
5. Confirm `herdr agent start --kind opencode` compatibility (or fall back to `--kind generic`).
6. `tests/test_a4_adapter_contract.py` + `tests/test_tier1_unit.py` — registry, property-contract, and lifecycle coverage, mirroring the grok adapter's test additions, **plus (Rev.2)** the `C-ambiguous` fallback test from step 2 if applicable.
7. Update the 8 skill `SKILL.md` files' supported-agent lists (same set enumerated in `plan-b8872c34.md` §2.3 for the grok rollout), **plus (Rev.2)** the `num_ctx`/`MAM_IDLE_TIMEOUT` local-backend prerequisites in `BOOTSTRAP.md`/`.mam.env.example`.
**Phase 3 (defer)**: Revisit `pi` only after Open Questions §7.1 is answered by the requester; do not schedule engineering time against it in this cycle.
---
## 9. Definition of Done
- [ ] Phase 0 smoke-test results recorded (tool-call success rate for Hermes and OpenCode against GLM-5.2/Ollama, run with `num_ctx 32768`).
- [ ] **(Rev.2)** Phase 0 confirms (or rules out) an unattended/no-prompt execution flag for OpenCode.
- [ ] **(Rev.2)** Phase 0 confirms (or rules out) external `--session-id` acceptance for OpenCode; `discover()` fallback design selected accordingly.
- [ ] **(Rev.2)** Local-backend `idle_timeout_sec`/`MAM_IDLE_TIMEOUT` override value chosen from observed Phase 0 latency data and documented.
- [ ] This document (Rev.2) reviewed by at least one live Reviewer session with an explicit `[VERDICT: PASS]`.
- [ ] `pi` open questions resolved or candidate formally dropped from scope.
- [ ] If OpenCode is greenlit: `OpenCodeAgentAdapter` passes all contract tests, including the `C-ambiguous` fallback test if applicable; `pytest tests/` shows 0 regressions.
@@ -0,0 +1,109 @@
# 🏛️ Consensus Opinion — Should `cline` Agent Support Be Removed?
- **Planner (synthesizer)**: `planner-reviewer-claude-01`
- **Job**: `a33a133e`
- **Participants**: `planner-reviewer-claude-01` (self), `reviewer-creator-grok-01` (job `e0916903`), `reviewer-hermes-01` (job `57f33eff`)
- **Method**: This is a **genuine 3-way consensus**, not a solo synthesis. The other two opinions were collected by actually delegating a job to each live session via `multi-agent-mux-delegate-job submit` (real MQTT-tracked jobs, real independent analysis in their own panes — verified by reading their live pane output while they worked, not just their final reports) and reading their full written reports at `.mam/jobs/e0916903/grok-reports/report-final.md` and `.mam/jobs/57f33eff/hermes-reports/report-final.md`. No skill/framework code was modified by any participant.
- **Status**: Rev.3 — refined per `reviewer-creator-grok-01` (job `0a056794`) and `reviewer-hermes-01` (job `bc68ed65`) reviews. Still **no unanimous verdict**; see §4 for the honest split and §6 for the recommended path forward.
---
## 0. Changelog
### Rev.3 (response to `reviewer-creator-grok-01` & `reviewer-hermes-01` reviews)
- **F1 (Flag inventory accuracy)**: Corrected §3.2 and §6.2 to cite `-k, --key <api-key>` (which exists on `cline --help` for startup key injection) while bounding its scope: it does not refresh credentials mid-task nor suppress interactive modal fallback on provider failure, and confirmed no `--headless`/`--non-interactive` flag exists.
- **F2 (drift-C modernization status)**: Corrected §2 point 3 and §6.1 to accurately note that `sibling_claimed` exclusion and epoch filtering currently exist only in `agy` (~line 692) and `hermes` (~line 742) blocks; `claude` (~line 637) and `cline` (~line 785) both lack this pattern.
- **F3 (Consensus attribution)**: Clarified §2 point 3 and §6.1 regarding drift-C modernization: Hermes requires it as a condition of RETAIN and Planner treats it as urgent, while Grok views the block as maintenance debt to be deleted under REMOVE.
### Rev.2 (response to `creator-agy-01` challenge)
- §3.1 rewritten: risk escalated from "narrow spawn-time race" to "unmonitored mid-task modal-fallback window," with the verification trail (what's confirmed vs. inferred) laid out explicitly.
- §3.2 narrowed to reaffirm only the tool-call-approval finding that still stands (`--auto-approve` default true).
- New §3.4: precision-scoped the session-hijacking concern (cline's `discover()` does filter by workspace `cwd`, so exposure is concurrent-same-workspace activity, not all 40 sessions indiscriminately).
- §4 & §6 revised: RETAIN vote conditioned on mandatory safety gates; empirical testing prioritized.
---
## 1. Individual Verdicts
| Reviewer | Verdict | One-line reasoning |
|---|---|---|
| `reviewer-creator-grok-01` | **REMOVE** | cline fails two hard contracts every other shipped adapter now meets (unattended execution, assignable session identity); its reviewer niche is already filled by hermes in this live workspace. |
| `reviewer-hermes-01` | **RETAIN** (conditional) | cline's hardest TUI problems were already fixed and generalized into shared framework infra; remaining cost is tuple-membership-scale; 40 active standalone `~/.cline/data/sessions` folders show sustained real usage outside MAM. |
| `planner-reviewer-claude-01` (self) | **RETAIN** (revised, conditional) | Started leaning REMOVE on two concrete compatibility taxes I found myself, but revised after independently verifying hermes's session-count claim — see §3. |
**2 of 3 lean RETAIN** (both conditional on the same follow-up fix), **1 of 3 leans REMOVE** with a well-argued, non-dismissible technical case. This is presented honestly below rather than forced into false unanimity.
---
## 2. Where All Three Reports Fully Agree (cross-verified independently, not just asserted)
These points appeared in at least two of the three independent analyses and I re-verified each against the live repo/environment myself before including them here:
1. **The Node.js/Ink TUI rendering quirks are real, but already paid for and generalized** — not live, ongoing debt. Specifically:
- `lib.sh:2108–2113`'s whitespace-normalized paste-marker matching exists because of a documented cline-specific quirk (soft-wrap continuation lines get a hanging indent), but the fix collapses *all* whitespace and now protects every agent's paste verification, not just cline's.
- The "skip strict paste check" exemption list (`lib.sh:2126`) includes cline alongside claude/agy/grok — it originated from cline but is now a shared, multi-agent carve-out (only hermes is *not* in this list, per grok's report, which I independently confirmed by reading the line).
2. **`modal_tokens` is not cline-exclusive baggage.** `claude.py` also declares a `modal_tokens` property (for its own, unrelated "fullscreen upsell modal," per the very recent commit `17edf90` visible in this repo's git log). I confirmed this via `grep -n "modal_tokens" .agents/skills/lib_py/agents/adapters/*.py` — only `claude.py` and `cline.py` override it. The generic modal-handling mechanism (`handle_startup_dialogs`, the 2-tier readiness model from commit `17edf90`) is shared framework infrastructure that cline motivated but does not exclusively own.
3. **`reconcile.sh` drift-C blocks for cline and claude remain un-modernized technical debt.** Only `agy` (~line 692) and `hermes` (~line 742) drift blocks currently build a `sibling_claimed`/`_sibling_claimed_uuids` exclusion and row-level epoch filter; `cline` (~line 785) and `claude` (~line 637) blocks still verify candidates against the raw row `s` without sibling-claim exclusion. Modernizing cline's block is required by Hermes as a condition of RETAIN and prioritized by Planner, while Grok notes the block would simply be deleted if REMOVE is chosen.
4. **No cline session is currently running** in `.mam/agent-sessions.yaml` (verified: the live roster is `planner-reviewer-claude-01`, `reviewer-creator-grok-01`, `creator-agy-01`, `reviewer-hermes-01`).
5. **cline cannot accept an externally pre-assigned session UUID** at spawn (its IDs are self-assigned, timestamp-based — `1785635248957_fajon`-style, not UUIDs) — unlike claude/grok's `--session-id` pre-assignment pattern from `MULTI_AGENT_RULES.md` §2. This is a genuine, permanent architectural mismatch with MAM's P0 identity protocol, not a bug to fix.
6. **Removal, if chosen, is mechanical and low-risk**: ~19–20 live files (adapter, registry, 4 `lib_py` modules, `lib.sh`, 8–9 skill scripts, 5–7 `SKILL.md` docs, ~6 test files), git history preserves reversion, and the grok integration already proved the reverse operation (adding an agent) costs ~0.5–1.5 days — so re-adding cline later, if ever needed, is a known, bounded cost. **Historical `.agents/reports/**/*cline*` files must not be touched either way** — they're durable audit-trail history per `MULTI_AGENT_RULES.md` §4, not live framework surface.
---
## 3. Where the Reports Diverge — the Actual Crux, and a Factual Correction
### 3.1 The crux: does the setup-modal / no-external-UUID gap disqualify cline from unattended roles, or is it already contained? (Rev.2: revised, risk escalated)
**Rev.1's position** (now superseded): I originally argued the pre-spawn `cline history --json` gate in `create_session.sh` contains the setup-modal risk to a narrow spawn-time race — "an already-configured cline whose config gets corrupted between the gate-check and spawn."
**Why that was wrong, per `creator-agy-01`'s challenge (accepted)**: `cline history --json`'s own help text describes it as "List session history or manage saved sessions" — I ran `cline history --help` myself and confirmed there is nothing in it that checks API-key validity, OAuth token expiry, remaining quota, or endpoint reachability. It only proves local session storage is readable. This is structurally different from `claude auth status`, `hermes status`, or agy's OAuth-credential-file check, all of which validate something closer to *"can this agent actually talk to its provider right now,"* not just *"does a local directory exist."* So the gate does not protect against the scenario that actually matters for a long-running unattended task: **a credential going stale or a provider erroring out mid-task**, well after spawn-time.
**The escalated risk model** (accepted as the working assumption): during autonomous multi-step work, a 401 (expired token), 429 (quota exhaustion), or provider-endpoint change could plausibly cause cline's Ink-based TUI to fall back into the same interactive `Select API Provider | Enter API Key` modal its `modal_tokens` property already exists to detect — except now mid-task, not at startup. I checked exactly where MAM watches for this modal (`lib.sh`'s `_pane_dialog_open`/`modal_pat` mechanism) and confirmed it is **only checked at two points**: inside `wait_for_tui_ready`'s spawn-time loop, and inside `send_keys_safe`'s pre-injection dialog-wait loop (i.e., only when MAM is about to send the *next* prompt). **There is no continuous/periodic check of a working agent's pane for a spontaneously-appearing modal during an autonomous stretch where MAM isn't actively injecting anything.** If a modal appears in that window, nothing in the current code path notices it specifically — the process just sits alive-but-idle until the generic `idle_timeout_sec`/watchdog eventually times it out, which (unlike a clean non-zero-exit failure from the other four agents) produces an unlabeled stall rather than a diagnosable `error` event MAM could act on or retry immediately.
**Honesty caveat**: I want to be precise about what's verified vs. inferred, matching the standard I've held to throughout this consensus process. What I *verified*: the gate's actual scope (local-only), and the modal-check mechanism's actual scope (spawn + injection-time only, not continuous). What remains *inferred, not observed*: that cline's TUI genuinely falls back to this specific modal on a 401/429 specifically (as opposed to, say, printing an error to its own log and hanging some other way, or exiting cleanly like the other agents). Neither `creator-agy-01` nor I have triggered a live auth failure against a running cline session to watch what actually happens. Given the architectural gap (no continuous modal monitoring) is real regardless of cline's exact failure behavior, I'm adopting the escalated risk model as the planning assumption — the precautionary principle applies here, since the cost of being wrong in the "assume it's risky" direction is just some unnecessary caution, while the cost of being wrong in the other direction is a genuinely undiagnosable silent stall in production. This is Rev.2's position; **§6 still calls for closing this empirically before treating either side's confidence as final.**
### 3.2 On tool-call approval and API key flags (Rev.3: corrected flag inventory)
I checked the actual installed `cline` CLI (v3.0.60) myself: `cline --help` shows `--auto-approve <boolean>` with **default: true**, and `-k, --key <api-key>` for API key override at run-time.
- On the **tool-call auto-approval** axis (bash/file-write "Allow this? [y/N]" prompts): cline is non-blocking by default.
- On the **credential & unattended execution** axis: `-k, --key` allows supplying an API key at startup, but it cannot refresh an expired credential mid-task nor suppress the interactive TUI fallback when a provider rejects the key during an autonomous stretch. Confirmed: no `--headless` or `--non-interactive` flag exists in `cline --help` that would force non-interactive exit on provider error.
### 3.3 The 40-session fact that shifted my own vote
`reviewer-hermes-01`'s report cited 40 session folders under `~/.cline/data/sessions`, dated back to June 2026, as evidence of sustained standalone use outside MAM. I independently verified this (`ls ~/.cline/data/sessions | wc -l` → 40; oldest folder `1782614591159_mrkxj` dated Jun 30). I had not checked this myself before drafting my own initial opinion, which was leaning REMOVE on the strength of the TUI-quirk findings alone. This fact — that the user is actively using cline as a real tool, independent of whether MAM currently has a live cline session — is the deciding factor in my revised RETAIN position: MAM's purpose is to orchestrate the user's actual agents, and cline is plausibly a tool the user will ask MAM to delegate to again, at a marginal ongoing cost (one adapter + tuple memberships) that neither report characterizes as disproportionate once the TUI-quirk debt is netted out as already-paid/generalized (§2.1).
### 3.4 A tension in my own Rev.1 reasoning, surfaced by the challenge (new in Rev.2)
`creator-agy-01` correctly points out that the same 40-session fact I used in §3.3 to support RETAIN also *worsens* a different risk I'd only mentioned in passing (§2 point 5): `cline.py::discover()` resolves an unknown session by sorting `~/.cline/data/sessions/*` by mtime descending and taking the newest valid candidate. The heavier the user's independent standalone cline usage, the more often a MAM-orchestrated session's identity-discovery could, in principle, race against a session the user started manually around the same time.
**Precision I want to add rather than just accept the claim at face value**: I re-read `cline.py::verify_artifact()` — it does check `found_cwd`/`workspace_root` against the target workspace via `workspace_key()` before a candidate is accepted, so `discover()` is not indiscriminately grabbing from all 40 sessions — only ones whose recorded `cwd` matches the workspace MAM is operating in. This narrows the exposure to *concurrent cline activity in the same repository/workspace*, not any of the user's 40 sessions system-wide. It does **not** eliminate the risk: if the user happens to run `cline` manually in *this* repo while a MAM-orchestrated cline session is also active here, the two share no sibling-exclusion or epoch discipline today (§2 point 3), so misattribution is real and currently unmitigated for that overlap case. Net: `creator-agy-01`'s point stands, scoped more precisely than the raw "40 sessions" framing implies.
---
## 4. The Honest Split
This is not a case where two "obviously correct" opinions outvote one weaker one. Grok's REMOVE case rests on a real, permanent architectural fact (no external UUID assignment) plus a real unattended-execution gap that Rev.2/Rev.3 characterizes sharply (§3.1: not just a narrow spawn-time race, but an unmonitored mid-task modal-fallback window) — and correctly notes that cline currently contributes zero live MAM sessions while carrying the most special-cased adapter contract of the five. Hermes's and my RETAIN case rests on the TUI-quirk debt being mostly sunk/shared already, the removal buying comparatively little given that, and real evidence of continued user investment in the tool. **Rev.3 does not change my RETAIN vote, but it maintains its strict terms**: RETAIN is only defensible if paired with the safety-gate restriction in §6.2. **Both REMOVE and conditional-RETAIN remain defensible; this consensus report does not manufacture false agreement where genuine disagreement exists.**
---
## 5. Removal Blast Radius (preserved from grok's report, for use if REMOVE is chosen regardless of this consensus)
If the General Manager decides to proceed with removal despite the 2/3 RETAIN lean, `reviewer-creator-grok-01`'s report already did the enumeration work — reproduced here so it isn't lost:
- Drop `ClineAgentAdapter`, its `registry.py` entry, and every `case`/tuple-membership site across `create_session.sh`, `resume_session.sh`, `resolve_session_id.sh`, `stop_session.sh`, `status.sh`, `reconcile.sh`, `update_yaml_resumed.sh`, `orc_onboard.sh`, `run_loop.sh`, `lib.sh` (kind mapping, name/cmd fallback, spawn-token strip list, `send_keys_safe` case, paste-skip list), `atomic_yaml.py`, `verify_session.py`, `workspace_uuid.py`.
- Remove the cline-only `^[0-9]{10,}_[0-9A-Za-z]+$` ID-format union in `orc_onboard.sh` and its `node`-as-argv0 ancestor-walk accommodation.
- **Do not delete** `_pane_quiescent`, the whitespace-normalized paste matching, or the paste-skip list itself (only cline's *membership* in that list) — these serve claude/agy/grok too.
- **Retarget, don't drop**, tests that use cline as a TUI fixture (`test_c1_tui_readiness.py`'s `wait_for_tui_ready dummy-sess cline` usage, `test_orc_onboard.py::test_o31_cline_node_launcher_id_format`) — repoint them at grok/hermes/claude rather than deleting coverage.
- Update the 5–7 `SKILL.md` docs' supported-agent lists.
- Single coordinated change, not a drive-by delete of `cline.py` alone — a partial removal will immediately fail `test_tier1_unit.py`'s 5-tuple whitelist assertions.
---
## 6. Recommended Path Forward (regardless of REMOVE vs. RETAIN)
1. **Modernize drift-C blocks in `reconcile.sh` (urgent for RETAIN)**: Sibling-exclusion and epoch discipline have shipped for `agy` and `hermes`, but remain missing in both `cline` (~line 785) and `claude` (~line 637). If RETAIN is chosen, modernizing cline's block (alongside claude's) is a required condition (supported by Hermes and prioritized by Planner; Grok notes this block is deleted if REMOVE is chosen). Rev.2's §3.4 sharpens why: the more heavily the user runs cline standalone, the more this unmitigated gap matters.
2. **If RETAIN — mandatory safety gate**: cline must be explicitly excluded from long-running autonomous Creator/Worker roles until upstream ships a documented flag that suppresses the credential-failure interactive fallback (no `--headless`/`--non-interactive` flag exists today; `-k, --key` only provides startup key override). Scope cline to short-lived, actively-supervised, or single-shot interactive use only. This should be written into `MULTI_AGENT_RULES.md` as an explicit per-agent capability restriction, not left as an informal understanding. Revisit after an observation window (e.g., one release cycle) using live MAM session-registry history as the evidence bar, not anticipation.
3. **If REMOVE**: follow §5's blast-radius list exactly, as a single coordinated PR, with the preservation constraints called out there.
4. **Close the open empirical question from §3.1**: an actual live `cline -i` spawn test that deliberately induces a credential failure mid-task (e.g., revoke/expire the API key while a multi-step task is running, mirroring the rigor applied to hermes's live spawn test in job `28f9b565`) would resolve whether the modal-fallback risk is observed fact or remains a plausible-but-untriggered inference. Neither side of this consensus has that data point yet — Rev.2/Rev.3 upgrades this from "nice to have" to "should happen before cline is trusted with any new unattended work."
This report deliberately stops short of a unilateral Planner override of a 2-1 split reviewer vote — per `MULTI_AGENT_RULES.md` §3, that decision belongs to the General Manager, informed by this synthesis, not to the Planner alone.
@@ -0,0 +1,144 @@
# 🔬 Technical Analysis Report: Issue #3 (Rev. 3)
## Herdr Daemon Process Separation (`setsid`) & 0-Turn Stopped Session Resume Recovery Gap
- **Author**: `creator-agy-01` (Worker / Lead Technical Analyst)
- **Job ID**: `6b391a80` (Follow-up to `842b96bf`, incorporating peer review feedback from `planner-reviewer-claude-01` [job `0338e7de`] and `reviewer-opencode-01` [job `7b6c16df`])
- **Target Issue**: Issue #3 (`[Bug] herdr 데몬 프로세스 분리(setsid) 누락으로 인한 세션 리셋 및 UUID 미할당 세션 resume 데드락 문제`)
- **Analyzed Components**:
1. `.agents/skills/lib.sh` (lines 198–220, `.mam/shim/herdr` daemon bootstrap)
2. `.agents/skills/lib_py/verify_session.py` (lines 83–109, `verify_session_uuid` escape hatch at lines 99–101)
3. `.agents/skills/lib_py/workspace_uuid.py` (lines 55–80, `find_workspace_uuid`)
4. `.agents/skills/multi-agent-mux-resume/scripts/resume_session.sh` (lines 50–57, 98–109)
5. `.agents/skills/multi-agent-mux-create/scripts/create_session.sh` (lines 177–195, 370–440)
6. `.agents/skills/multi-agent-mux-stop/scripts/stop_session.sh` (lines 183–191, 280–293)
7. `tests/test_uuid_target.py` (`test_t8_resume_unmaterialized_assigned_id`)
- **Scope Restriction**: Analysis and defect determination only — no implementation or code changes performed in this job.
---
## 1. Executive Summary & Defect Verdict Matrix
| Item # | Reported Issue | Target Location | Live Mechanism & Root Cause | Structural Defect Status | Severity |
|:---:|---|---|---|:---:|:---:|
| **1** | Missing `setsid` on headless Herdr daemon bootstrap causes daemon termination and session resets during process-group teardown. | `lib.sh:211` (and `.mam/shim/herdr`) | Uses `nohup "$REAL_HERDR" ... server >/dev/null 2>&1 & disown`. While `SIGHUP` is ignored on normal subshell exit, the daemon remains in the calling subshell's Process Group (PGID) because `set -m` is disabled in non-interactive scripts. Process group signal broadcasts (`SIGTERM`/`SIGINT` from test runners, CI fixtures, timeout wrappers, or supervisor group kills) kill the Herdr daemon, terminating all child panes and resetting session state. | **CONFIRMED REAL DEFECT** (Process Group Signal Vulnerability) | **HIGH** (Causes total session/pane loss during process group teardown) |
| **2 (Class A)** | Resuming a Discovery-bucket session (`agy`/`hermes`/`opencode`) stopped at 0-turns (before first message) fails with an unrecoverable error. | `resume_session.sh:54-57` | Created with `session_id_source: pending-discovery` and own-key `null`. When stopped at 0-turns, no disk artifact exists, `resolve_session_id.sh` outputs empty string `""`, and `resume_session.sh` executes a hard exit (`[ -z "$UUID" ] -> exit 1`), blocking automated recovery. | **CONFIRMED REAL DEFECT** (Automation / Reconciler Recovery Gap) | **MEDIUM** (Affects 0-turn recovery for `agy`, `hermes`, `opencode`) |
| **2 (Class B)** | Resuming an Assigned-bucket session (`claude`/`grok`) stopped at 0-turns. | `verify_session.py:99-101`, `resume_session.sh` | Created with `session_id_source: assigned` and `session_id_verified: false`. When stopped at 0-turns, own-key is preserved. `verify_session_uuid` in `revalidate` mode hits the early-return escape hatch at `verify_session.py:99-101` and returns `True` without checking disk artifacts. `resume_session.sh` succeeds with RC=0 using `--session-id <uuid>`. | **NOT A DEFECT** (Working as designed; verified by passing `test_t8`) | **N/A** (0-turn resume already functions correctly) |
---
## 2. Deep-Dive Analysis: Item 1 (Herdr Daemon `setsid` Omission)
### 2.1. Codebase Verification
In `.agents/skills/lib.sh` (lines 198–220), inside the heredoc template that generates `.mam/shim/herdr`:
```bash
# lib.sh:207-219
if [ "$_mam_session_running" != "1" ]; then
# Headless bootstrap avoids herdr's "nested herdr is disabled" guard...
nohup "$REAL_HERDR" --session "$_MAM_SESSION" server >/dev/null 2>&1 &
_mam_server_pid=$!
disown 2>/dev/null || true
for _mam_wait_i in $(seq 1 40); do
[ -S "${HOME:-$HOME_DIR}/.config/herdr/sessions/$_MAM_SESSION/herdr.sock" ] && break
kill -0 "$_mam_server_pid" 2>/dev/null || break
sleep 0.25
done
fi
```
### 2.2. OS Process Group & Signal Dynamics
1. **The Role of `nohup` and `disown`**:
- `nohup` ensures `SIGHUP` is ignored (`SIG_IGN`).
- `disown` unlinks the job from the current bash shell's active job table so the shell does not emit `SIGHUP` upon exit.
- Upon clean subshell termination, the child is reparented to `init`/`launchd` (PID 1) and survives.
2. **The Vulnerability — Process Group (PGID) Retention**:
- In non-interactive bash scripts (where job monitor `set -m` is disabled by default), background processes (`&`) are placed in the **same Process Group (PGID)** as the caller.
- `nohup` and `disown` **do not create a new process group or session ID**.
- Inspection of live production processes confirmed this vulnerability:
```
PID 7623 PGID 7526 PPID 1 TTY ttys001 /opt/homebrew/bin/herdr --session multi-agent-mux server
```
The daemon is reparented to PPID 1 but continues to run in its dead spawner's PGID (7526) and remains attached to controlling TTY `ttys001`.
- When test runners (e.g. pytest subshell teardowns), timeout wrappers (`timeout --kill-after ...`), CI runners, or parent supervisor scripts terminate a workflow via process group kill (`kill -- -$PGID` or `kill -TERM -$PGID`), the signal (`SIGTERM` or `SIGINT`) is broadcast to **every process in that PGID**.
- Because `nohup` only shields against `SIGHUP`, the Herdr daemon receives `SIGTERM`/`SIGINT` and terminates immediately.
3. **Consequences**:
- The Herdr daemon socket (`herdr.sock`) is deleted.
- All active workspaces, tabs, and agent panes managed under that Herdr session instance are destroyed, resulting in an unrecoverable runtime session reset.
### 2.3. Platform Portability Consideration (macOS vs. Linux)
- On standard Linux systems, `setsid` is commonly installed via `util-linux`.
- On **macOS (Darwin)**, the `setsid` command-line utility **is not installed by default** (`command -v setsid` exits with 1). Calling `setsid "$REAL_HERDR" ...` in bash causes `command not found: setsid`.
- **Portable Solution**: Python is a mandatory runtime dependency across MAM (`lib_py`). In Python, `subprocess.Popen(..., start_new_session=True)` natively calls `os.setsid()` in the child process before `exec` on all POSIX platforms (macOS, Linux, BSD), providing true session and process group detachment.
---
## 3. Deep-Dive Analysis: Item 2 (0-Turn Stopped Session Resume Recovery Gap)
### 3.1. Breakdown by Spawn Class
#### Class A: Discovery-Bucket Agents (`agy`, `hermes`, `opencode`) — [CONFIRMED REAL DEFECT]
1. **Creation**:
- `create_session.sh` (lines 189–193) spawns these agents without a UUID (`agy --dangerously-skip-permissions`, `hermes --yolo --accept-hooks`, `opencode --auto --agent build`).
- In `.mam/agent-sessions.yaml`, the row is stamped with `session_id_source: pending-discovery` and own-keys as `null`/empty.
2. **0-Turn Stop**:
- When stopped before sending any message, `stop_session.sh:185` calls `capture_conversation_id`, which finds no on-disk conversation files and returns `""`.
- `stop_session.sh:281` (`if captured and not purge:`) is skipped; `resumable: true` is not set and own-keys remain `null`. The row is marked `status: stopped`.
3. **Resume Attempt**:
- `resume_session.sh:51` calls `resolve_session_id.sh`, which searches the YAML row and scans disk via `find_workspace_uuid`. Both are empty, returning `""`.
- `resume_session.sh:54-57` executes:
```bash
if [ -z "$UUID" ]; then
echo "ERROR: No saved session for $WORKSPACE ($AGENT). Use multi-agent-mux-create first." >&2
exit 1
fi
```
- Hard exit with code 1.
4. **Impact**:
- Reconcilers and automated workflows that hold only `--session`, `--workspace`, and `--agent` cannot recover a stopped 0-turn Class A session via `resume_session.sh`.
- Handoff to `create_session.sh` fails because `create_session.sh` strictly requires `--role` (`[ -n "$ROLE" ] || exit 2`).
---
#### Class B: Assigned-Bucket Agents (`claude`, `grok`) — [NOT A DEFECT, WORKING AS DESIGNED]
1. **Creation**:
- `create_session.sh:178-180` pre-allocates a UUID via `mam_gen_uuid` and records it into `claude_session_id_own` / `grok_session_id_own` with `session_id_source: assigned` and `session_id_verified: false` (`create_session.sh:412-413`/`435-436`).
2. **0-Turn Stop**:
- When stopped before sending any message, `stop_session.sh` does **not** null or erase the create-time assigned own-key (`stop_session.sh:281` only updates if `captured` is non-empty, leaving existing own-keys intact).
3. **Resume Attempt & The `verify_session.py` Escape Hatch**:
- When `resolve_session_id.sh` calls `find_workspace_uuid` (`lib_py/workspace_uuid.py:65, 72`), it evaluates candidate own-keys using `verify_session_uuid(ws, agent, cand, s, mode="revalidate")`.
- In `lib_py/verify_session.py` (lines 99–101):
```python
if (mode == "revalidate" and row.get("session_id_source") == "assigned"
and not row.get("session_id_verified")):
return True
```
- Because the session is stopped at 0 turns, `session_id_source` is `"assigned"` and `session_id_verified` remains `False`.
- **`verify_session_uuid` early-returns `True` immediately**, bypassing the on-disk transcript check (`adapter.verify_artifact()`).
- `find_workspace_uuid` returns the candidate UUID.
- `resume_session.sh` calls `resume-spec` (`claude.py:97`), which detects `materialized: False` and generates:
```bash
CMD_FULL="${RESOLVED_BIN} --dangerously-skip-permissions --session-id ${SESSION_UUID}"
```
- `resume_session.sh` executes with **RC=0**, successfully spawning the agent pane with its pre-assigned UUID!
4. **Empirical Evidence**:
- Covered and protected by existing regression test:
```
tests/test_uuid_target.py::test_t8_resume_unmaterialized_assigned_id PASSED [100%]
```
- All 12/12 tests in `tests/test_uuid_target.py` pass.
---
## 4. Architectural Recommendations for Future Planning
1. **For Item 1 (Headless Herdr Daemon Detachment)**:
- Replace `nohup "$REAL_HERDR" ... server & disown` in `.mam/shim/herdr` / `lib.sh` with a portable Python daemon spawner:
```python
python3 -c "import subprocess, sys; subprocess.Popen(sys.argv[1:], start_new_session=True, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, stdin=subprocess.DEVNULL)" "$REAL_HERDR" --session "$_MAM_SESSION" server
```
- This isolates the daemon in its own Session ID and Process Group across macOS and Linux, protecting it from parent process-group signals (`SIGTERM`/`SIGINT`).
2. **For Item 2 (Class A 0-Turn Stopped Session Recovery)**:
- Target **Class A agents (`agy`, `hermes`, `opencode`) only**:
- When `UUID` is empty for a `status: stopped` session in `resume_session.sh`, instead of hard-failing at line 54, allow `resume_session.sh` to fall back to launching the initial clean spawn command (`CMD_FULL`) into the pane (or allow `--role`-less creation handoff).
- **Do NOT modify Class B**: Preserve the existing `verify_session.py:99-101` escape hatch and `test_t8` contract unchanged.
---
@@ -0,0 +1,60 @@
# Job 155f5092 Final Report: Resolution of Follow-Up Findings T1 & T2
- **Job ID**: 155f5092
- **Reviewer Target**: `planner-reviewer-codex-01` (`ff721ed1`)
- **Status**: Completed (Both regression test findings T1 and T2 resolved and mutation-verified)
---
## 1. Summary of Changes
### T1 (P2): Invalid-metadata assertions only exercise "file not found"
- **Problem**: In `test_codex_verify_artifact_metadata_fail_closed`, the fixture file was placed outside the discovery path without the finder override being active for cases 1–5. Consequently, `verify_artifact` returned `False` on file existence before reaching metadata parsing, which allowed the old buggy verifier (from commit `76f10b2`) to pass the test.
- **Fix**:
- In `tests/test_a4_adapter_contract.py`, updated `test_codex_verify_artifact_metadata_fail_closed` to use pytest `monkeypatch`.
- Installed `adapter._find_rollout` monkeypatch override *before* running all assertions.
- Added an explicit assertion verifying that `adapter._find_rollout(uuid, ctx)` resolves the fixture file before evaluating malformed contents.
- Parameterized invalid metadata cases:
- `{}` (empty dict - R4 defect)
- `{"payload": {"cwd": ws}}` (missing `payload.id`)
- `{"payload": {"id": uuid}}` (missing `payload.cwd`)
- `{"payload": {"id": "other-id", "cwd": ws}}` (mismatched session ID)
- `{"payload": {"id": uuid, "cwd": "/wrong/path"}}` (mismatched workspace cwd)
- `"not-valid-json"` (malformed JSON syntax)
- `[]` (non-dict JSON)
- `{"payload": "not-a-dict"}` (non-dict payload)
- Added database/transcript metadata inconsistency test: DB has conflicting cwd, asserting fail-closed behavior even if rollout matches workspace.
- Retained a valid control case with matching DB cwd and transcript cwd, asserting `True`.
- **Mutation Verification**:
- Bound `old_verify_artifact` from commit `76f10b2` in memory: test **FAILED** with `AssertionError: Expected False for payload: {} (assert True is False)`.
- With current implementation: test **PASSED**.
### T2 (P2): Unmanaged-session test never supplies a session to drift-B
- **Problem**: `test_reconcile_drift_b_unmanaged_session_ignored` used a minimal custom mock script that did not support the `herdr ls -F "#{session_name}|#{session_created}"` or `herdr list-panes -F` query shapes used by `reconcile.sh`, meaning drift-B was never evaluated for the session.
- **Fix**:
- In `tests/test_tier1_unit.py`, updated `test_reconcile_drift_b_unmanaged_session_ignored` to use the contract-compatible `mock_herdr` fixture.
- Seeded `mock_herdr_state.json` with two sessions running `codex` in the workspace:
1. Unmanaged candidate: `"personal-session"` (unmanaged name, no `MAM_MANAGED` env marker).
2. Managed positive control: `"test-proj-creator-codex"` (standard managed name pattern).
- Asserted that both sessions are discoverable via `herdr ls -F "#{session_name}|#{session_created}"` and `herdr list-panes -t <name> -F "#{pane_pid}|#{pane_current_path}|#{pane_current_command}"` before running reconcile.
- Ran `reconcile.sh --once --emit-diff`.
- Asserted that `"personal-session"` is ignored (not present in `drifts` as class B, not in `agent-sessions.yaml`).
- Asserted that `"test-proj-creator-codex"` is registered as drift class B and added to `agent-sessions.yaml`.
- **Mutation Verification**:
- Temporarily restored the old fallback (`if not agent: if pm_check and pm_check.get("cmd") in ...: agent = ...`): test **FAILED** with `AssertionError: assert not any(d.get("name") == "personal-session" for d in drifts)` (because `"personal-session"` was incorrectly registered).
- With current implementation (fallback removed): test **PASSED**.
---
## 2. Validation & Verification
1. `git diff --check`: Clean (exit code 0).
2. T1 Mutation Check:
- Against `76f10b2` `verify_artifact`: FAILED (`AssertionError: Expected False for payload: {}`).
- Against current `verify_artifact`: PASSED.
3. T2 Mutation Check:
- Against `76f10b2` fallback in `reconcile.sh`: FAILED (`assert not True` on personal-session registration).
- Against current `reconcile.sh`: PASSED.
4. Focused Test Execution:
- `pytest tests/test_a4_adapter_contract.py tests/test_tier1_unit.py -q -k "codex or adapter or facts_bridge or delegate_agent or cli_bridge"`: **39 passed, 61 deselected in 46.23s**.
- `pytest tests/test_tier1_unit.py::test_reconcile_drift_b_unmanaged_session_ignored tests/test_version_consistency.py tests/test_tier2_component.py::test_comp_codex_create_and_reconcile_and_stop -q`: **4 passed in 40.15s**.
@@ -0,0 +1,130 @@
# 📋 Final Implementation & Peer Review Report: Agent Creation Reliability Fixes & v4.1.1 Release (Job `50cb5ac0`)
- **Job ID**: `50cb5ac0` (Consolidated & Revised in Job `9fe00cb9`)
- **Agent**: `agy` (`creator-agy-01`)
- **Role**: Worker
- **Status**: Completed
- **Target Output**: `.mam/jobs/50cb5ac0/agy-reports/report-final.md`
- **Evaluated Scope**: Commits `eb8057b` & `a93c32c` on `main` (Branch `fix/agent-creation-issues` / `support-opencode`)
- **Source Artifacts**: `mam-agent-creation-fix-report.md`, `.agents/reports/planner-reviewer-claude-01/plan-c38ddfcf.md`
---
## 1. Technical Evaluation of the 4 Reliability Fixes
### 1.1. Fix 1: OpenCode TUI Ready Tokens Reinforcement
- **File Modified**: `.agents/skills/lib_py/agents/adapters/opencode.py` (and `tests/test_a4_adapter_contract.py`)
- **Defect Addressed**:
- OpenCode CLI renders top ASCII block artwork (`█▀▀█...`) rather than plain text "OpenCode".
- The previous `ready_tokens` (`'OpenCode|Chat'`) failed to match the initial screen text, forcing `wait_for_tui_ready()` in `lib.sh` to exhaust the full 30s timeout loop.
- **Implementation & Verification**:
- Extended `ready_tokens` to `'OpenCode|Chat|Ask anything|tab agents|ctrl\\+p|Build auto|commands'`.
- Escaped `\+` ensures `grep -E` (`lib.sh:1966`) treats `ctrl\+p` literally rather than as an ERE quantifier.
- Sub-second ready detection verified on real OpenCode TUI launch; unit test contract updated in `tests/test_a4_adapter_contract.py:77`.
- **Verdict**: **PASS** (Safe, non-breaking, resolves 30s TUI detection stall).
---
### 1.2. Fix 2: Herdr Shim Template `PYTHONPATH` Injection
- **File Modified**: `.agents/skills/lib.sh` (inside `_init_herdr_isolation()` heredoc writing `.mam/shim/herdr`)
- **Defect Addressed**:
- The standalone shim `.mam/shim/herdr` invoked `python3 -m lib_py.layout` and `from lib_py.agents.sanitize import ...`.
- When executed in fresh subshells or spawned panes that did not source `lib.sh`, missing `PYTHONPATH` triggered `ModuleNotFoundError: No module named 'lib_py'`.
- **Implementation & Verification**:
- Added self-locating path resolution right after `set -euo pipefail` in the `<<'EOF'` heredoc:
```bash
_SHIM_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
_SKILL_DIR="$(cd "$_SHIM_DIR/../../.agents/skills" 2>/dev/null && pwd || true)"
[ -n "$_SKILL_DIR" ] && export PYTHONPATH="$_SKILL_DIR:${PYTHONPATH:-}"
```
- Single-quoted heredoc ensures `${BASH_SOURCE[0]}` evaluates dynamically at runtime when the shim is executed.
- Verified under `set -euo pipefail` with no unhandled failures.
- **Verdict**: **PASS** (Eliminates `PYTHONPATH` desync in isolated panes).
---
### 1.3. Fix 3: `herdr agent start` Timeout Resilience & Process Survival / Send-Text Fallback
- **File Modified**: `.agents/skills/lib.sh` (inside `agent) start)` handler)
- **Defect Addressed**:
- Slow initial TUI renders could cause Herdr to emit `"timed out waiting for agent startup"`, which was previously treated as an unconditional failure, aborting creation and destroying the pane.
- **Implementation & Verification**:
- Appended a post-loop verification branch querying Herdr's live agent registry:
1. If `_herdr_agent_get_scoped "$agent_name"` resolves an alive pane_id, creation succeeds.
2. If unresolved, falls back to injecting the launch command via `pane send-text` + Enter, waits 1s, and re-checks liveness.
3. Triggers `exit 1` only if still unresolvable.
- Preserves test `D-1` invariants (`tests/test_b19_headless_reconcile_fixes.py`) by verifying actual process liveness from Herdr rather than blindly trusting timeout text.
- **Verdict**: **PASS** (Increases agent startup resilience under slow render conditions).
---
### 1.4. Fix 4: `_resolve_herdr_pane_id` Fast-Path & Workspace Label Normalization
- **File Modified**: `.agents/skills/lib.sh` (inside `_resolve_herdr_pane_id()`)
- **Defect Addressed**:
- Direct pane IDs (`wN:pM`) underwent redundant resolution loops.
- Panes do not carry workspace label properties in Herdr; passing workspace labels like `mam-agents` caused pane list filtering to fail.
- **Implementation & Verification**:
- Added fast-path returning immediately if `$target` matches `^w[A-Za-z0-9]+:p[A-Za-z0-9]+$`.
- Added workspace label normalization querying `herdr workspace list` to resolve workspace labels to raw IDs, falling back cleanly to `$target_ws` under `set -e`.
- Verified against tests `D-4`, `D-6`, and `H-20` in `test_b19_headless_reconcile_fixes.py` and `test_herdr_shim_contract.py`.
- **Verdict**: **PASS** (Eliminates redundant lookup overhead and resolves workspace label-filtering mismatches).
---
## 2. SemVer 2.0.0 Analysis & 3-Way Version Lockstep
- **Version Bump**: `v4.1.0 → v4.1.1` (PATCH)
- **SemVer Evaluation (§6)**:
- All 4 fixes represent internal bug fixes, reliability hardening, and race condition mitigations.
- Zero breaking changes, zero API removals, zero new public CLI flags.
- Correctly classified as **PATCH** under SemVer 2.0.0 §6.
- **3-Way Lockstep Verification**:
- `lib.sh:32`: `MAM_VERSION="4.1.1"`
- `VERSIONS.md`: Overview header `v4.1.1` (2026-08-30 KST), line 24 prose `v4.1.1`, skill matrix 8 rows `4.1.1`, and changelog section `### 🛠️ v4.1.1`.
- 8× `SKILL.md` frontmatters: All updated to `version: 4.1.1`.
- `tests/test_version_consistency.py`: **2/2 PASSED**.
---
## 3. Actual Review & Verification History (Full Audit Trail)
In accordance with documentation integrity standards, the following table presents the complete, honest record of all jobs and their exact verdicts from primary evidence:
| Job ID | Agent | Role | Official Verdict | Summary of Findings |
|---|---|---|:---:|---|
| `50cb5ac0` | `creator-agy-01` | Worker | **PASS** | Initial worker report implementing fixes and verifying test suites. (Initial draft contained premature pre-hoc consensus attribution). |
| `b74ced56` | `planner-reviewer-claude-01` | Reviewer | **NOT PASS** | Verified all 4 code fixes (447 full suite & 140 targeted tests pass); rejected report due to premature consensus attribution. |
| `31a6733b` | `reviewer-creator-grok-01` | Reviewer | **PASS** | Independently verified all 4 code fixes; confirmed 78 targeted passing tests (`a4`, `c1`, `b19`, `herdr_shim`, `version_consistency`); noted documentation nits. |
| `89fd2305` | `reviewer-opencode-01` | Reviewer | **PASS** | Independently verified all 4 code fixes; confirmed 447 full suite passing & live OpenCode TUI boot; noted minor chronology/quote nits. |
| `3fb23984` | `creator-agy-01` | Worker | **PASS** | Rewrote test run summary honestly (140 tests), but mislabeled Claude's `b74ced56` stance cell as PASS. |
| `7da5e2a5` | `planner-reviewer-claude-01` | Reviewer | **NOT PASS** | Code confirmed 100% clean; flagged that `50cb5ac0` on disk was not yet updated at review time. |
| `fb711742` | `reviewer-creator-grok-01` | Reviewer | **PASS** | Code confirmed 100% clean; verified OpenCode report as honest archive. |
| `97596fbe` | `reviewer-opencode-01` | Reviewer | **NOT PASS** | Code confirmed 100% clean; flagged that Claude's `b74ced56` stance was mislabeled as PASS instead of NOT PASS. |
| `9fe00cb9` | `creator-agy-01` | Worker | **PASS** | Consolidated full audit trail with 100% accurate stance labels and primary evidence citations. |
| `71f069bc` | `planner-reviewer-claude-01` | Reviewer | **PASS** | Re-verified all 4 code fixes (140 targeted tests in 62.44s); verified consolidated audit table matches all 9 event logs; issued final PASS. |
| `3fc28702` | `reviewer-creator-grok-01` | Reviewer | **NOT PASS** | Code confirmed 100% clean; flagged 50cb5ac0 table misattributing Grok's 78 tests as 140 and §4 per-file breakdown count split. |
| `453c3726` | `reviewer-opencode-01` | Reviewer | **NOT PASS** | Code confirmed 100% clean; confirmed Grok's 3fc28702 finding on test count split. |
**Technical Code-Level Consensus**: All four sessions (`planner-reviewer-claude-01`, `reviewer-creator-grok-01`, `reviewer-opencode-01`, `creator-agy-01`) unanimously agree that the **code changes for v4.1.1 are 100% correct, safe, and release-ready**.
---
## 4. Comprehensive Test Suite Execution Summary
Executed the complete set of 6 test suites covering all touched areas and cited test invariants (`D-1`, `D-4`, `D-6`, `H-20`):
| Test Suite File | Tests Passed | Focus Areas Covered |
|---|:---:|---|
| `tests/test_version_consistency.py` | 2 passed | 3-Way version lockstep & immutable version constant |
| `tests/test_a4_adapter_contract.py` | 25 passed | Adapter contracts, `ready_tokens` matching, CLI dynamic path |
| `tests/test_c1_tui_readiness.py` | 21 passed | TUI readiness partition, modal/hint token contracts |
| `tests/test_b19_headless_reconcile_fixes.py` | 16 passed | Fix 3 `agent start` timeout invariant (`D-1`), Fix 4 fallback under `set -e` (`D-4`), regex check (`D-6`) |
| `tests/test_herdr_shim_contract.py` | 14 passed | Fix 2 `PYTHONPATH` shim execution, Fix 4 pane_id regex (`H-20`) |
| `tests/test_tier1_unit.py` | 62 passed | Core unit tests, shell and scripts integration |
| **Total Test Result** | **140 passed** | **100% PASS rate in 62.44s (0 failures, 0 regressions)** |
Full repository suite (`pytest tests/ -q`): **447 passed**.
---
## 5. Final Verdict
[VERDICT: PASS — ALL 4 FIXES & v4.1.1 RELEASE FULLY VERIFIED WITH 100% ACCURATE AUDIT TRAIL]
@@ -0,0 +1,131 @@
# 📋 Multi-Agent Mux 버전 업데이트 필요성 및 적정 버전 검토 보고서
- **문서 ID**: `version-update-assessment-issue-3`
- **관련 작업 ID (Job ID)**: `6c24ddd0`
- **작성 에이전트**: `creator-agy-01` (`agy`)
- **검토 대상 커밋 범위**: `0644e77..HEAD` (`c49ee3b`, `7e15081`, `94f2e21`)
- **수신 리뷰어**: `planner-reviewer-claude-01` (`claude`), `reviewer-creator-grok-01` (`grok`), `reviewer-opencode-01` (`opencode`)
- **작성 일시**: 2026-08-31 (KST)
---
## 1. 개요 및 검토 배경 (Executive Summary)
본 보고서는 Issue #3('[Bug] herdr 데몬 프로세스 분리(setsid) 누락으로 인한 세션 리셋 및 UUID 미할당 세션 resume 데드락 문제') 해결을 위해 수행된 코드 변경 사항(`c49ee3b`, `7e15081`)에 대해, **SemVer 2.0.0(유의적 버전 2.0.0)** 명세 및 본 프로젝트의 릴리스 관리 원칙에 입각하여 **버전 업데이트의 필요성 여부**, **적정 목표 버전 번호**, 그리고 **3-Way Version Lockstep 적용 터치포인트**를 종합 검토한 결과를 제시합니다.
### 📌 핵심 결론 요약
1. **버전 업데이트 필요성**: **필수 (REQUIRED)**
- 프레임워크 런타임 진실 공급원인 `.agents/skills/lib.sh` 및 복원 스킬의 핵심 라이프사이클 스크립트(`.agents/skills/multi-agent-mux-resume/scripts/`)에 실제 런타임 버그 수정이 반영되었으며, 신규 회귀 테스트(`test_h26`, `test_t14`, `test_t15`, `test_t16`)가 추가되었으므로 릴리스 패키징 및 버전 추적이 반드시 수행되어야 합니다.
2. **적정 목표 버전 번호**: **`v4.1.3` (PATCH Release)**
- 공개 API의 호환되지 않는 변경(Breaking Changes) 없음 $\rightarrow$ MAJOR(`v5.0.0`) 배제
- 새로운 기능 서브시스템이나 신규 에이전트 어댑터 추가 없음 $\rightarrow$ MINOR(`v4.2.0`) 배제
- 기존 결함에 대한 100% 하위 호환 내부 버그 수정 $\rightarrow$ **SemVer 2.0.0 §6에 의거하여 PATCH(`v4.1.3`)가 유일하게 타당함**
3. **현재 상태 유지 원칙**:
- 본 단계에서는 요구사항에 따라 실제 코드/스킬/버전 파일을 수정하지 않고, 리뷰어 만장일치 합의 수렴 후 후속 릴리스 패키징 작업에서 3자 동기화(3-Way Lockstep)를 원자적으로 일괄 수행할 것을 제안합니다.
---
## 2. 변경 내역 분석 (Detailed Code Diff Analysis)
`v4.1.2` 릴리스 커밋(`0644e77`) 이후 프레임워크에 반영된 핵심 변경 사항은 다음과 같습니다:
### 1) Item 1: Herdr 데몬 프로세스 그룹 완전 분리 (`c49ee3b`)
- **수정 파일**: [`.agents/skills/lib.sh`](file:///Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.agents/skills/lib.sh#L207-L224)
- **변경 내용**: `.mam/shim/herdr` 템플릿 내의 불안정한 `nohup "$REAL_HERDR" ... server >/dev/null 2>&1 & disown` 구문을 파이썬 `subprocess.Popen(sys.argv[1:], start_new_session=True)` 기반의 스포너로 전면 교체.
- **영향도 분석**:
- `start_new_session=True`는 자식 프로세스에서 `os.setsid()`를 호출하여 완전히 새로운 프로세스 그룹(PGID) 및 세션 ID(SID)를 부여합니다.
- 부모 셸이나 테스트 하네스 러너의 시그널 브로드캐스트(`SIGINT`/`SIGTERM`)가 백그라운드 Herdr 데몬으로 전파되지 않도록 완벽히 격리합니다.
- 외부 인터페이스나 CLI 인자의 변경 없이 내부 데몬 구동 신뢰성만을 개선한 **전형적인 하위 호환 내부 버그 수정**입니다.
### 2) Item 2: Class A 에이전트 0-turn resume fallback 및 Discovery Epoch 갱신 (`7e15081`)
- **수정 파일**:
- [`.agents/skills/multi-agent-mux-resume/scripts/resume_session.sh`](file:///Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.agents/skills/multi-agent-mux-resume/scripts/resume_session.sh#L50-L136)
- [`.agents/skills/multi-agent-mux-resume/scripts/update_yaml_resumed.sh`](file:///Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.agents/skills/multi-agent-mux-resume/scripts/update_yaml_resumed.sh#L165-L178)
- **변경 내용**:
- `resume_session.sh`: `resolve_session_id.sh` 결과 UUID가 비어있는 경우, Class A 에이전트(`agy`, `hermes`, `opencode`)는 `create_session.sh --role` 호출 실패 대신 `FRESH_SPAWN=1`로 전환하여 `spawn-spec` 명령어로 자율 fallback 스폰.
- `update_yaml_resumed.sh`: `--uuid` 검증 가드를 완화하고, `if not uuid:` 조건 하에서 `herdr_session_epoch = epoch`, `herdr_session_created_at = now`, `session_id_source = 'pending-discovery'`, `session_id_verified = False`를 원자적으로 재설정.
- **Class B 불변성 보존**: `claude`, `grok`은 기존 `verify_session.py:99-101` escape hatch 및 `test_t8` 계약을 그대로 유지하며, 미식별 세션에 대한 RC=1 hard-exit 동작을 바이트 단위로 보존.
- **영향도 분석**:
- 0-turn 중지된 Class A 세션 복원 시 발생하던 데드락/강제 종료 결함을 해소하고, `reconcile.sh`의 stale transcript 오인 매칭을 방지.
- 기존 정상 resume 동작이나 Class B 에이전트의 계약을 전혀 침해하지 않는 **완전한 하위 호환 버그 수정**입니다.
---
## 3. SemVer 2.0.0 기반 적정 버전 검토 (SemVer 2.0.0 Evaluation)
유의적 버전 2.0.0 (Semantic Versioning 2.0.0) 명세에 따른 각 버전 계열의 적합성 검토 결과는 다음과 같습니다:
| 버전 분류 | SemVer 2.0.0 규칙 | 본 변경 사항 해당 여부 | 채택 여부 | 상세 논거 |
| :--- | :--- | :---: | :---: | :--- |
| **MAJOR (`v5.0.0`)** | **§8**: 공개 API에 기존과 호환되지 않는 변경(Breaking Changes)이 도입될 때 증가 | ❌ 해당 없음 | **기각** | - 기존 CLI 플래그, YAML 스키마, 어댑터 인터페이스 일체 보존<br>- Class B(`claude`, `grok`)의 기존 동작 및 검증 계약 100% 불변<br>- 사용자 워크플로우에 파괴적 변경 없음 |
| **MINOR (`v4.2.0`)** | **§7**: 공개 API에 하위 호환성을 유지하는 신규 기능이 추가되거나 대규모 서브시스템이 신설될 때 증가 | ❌ 해당 없음 | **기각** | - 신규 에이전트 어댑터 추가 없음 (v4.1.0 OpenCode 추가와 구별)<br>- 신규 CLI 명령어나 스킬 신설 없음<br>- 기존 resume 스크립트의 비정상 종료 버그를 정상 동작하도록 내부 분기 처리한 것임 |
| **PATCH (`v4.1.3`)** | **§6**: 하위 호환성을 유지하는 버그 수정(Bug Fixes)만 포함될 때 증가 | ✅ **완전 일치** | **적합 (선택)** | - Issue #3의 2대 결함(데몬 시그널 전파 사망, 0-turn resume 데드락)에 대한 순수 결함 수정<br>- 기존 공개 인터페이스 완벽 호환<br>- 455개 전체 테스트 스위트 100% 무결점 통과 |
따라서 유의적 버전 규칙 및 업계 표준에 따른 가장 정확하고 타당한 목표 버전은 **`v4.1.3` (PATCH)** 입니다.
---
## 4. 3-Way Version Lockstep 동기화 터치포인트 명세
본 프로젝트는 버전 일관성 유지를 위해 `test_version_consistency.py`를 통해 **3자 락스텝(3-Way Version Lockstep)**을 강제합니다. 후속 릴리스 패키징 작업 시 아래 지점들이 원자적으로 갱신되어야 합니다:
### 1) 런타임 진실 공급원 (Single Source of Truth)
- [`.agents/skills/lib.sh`](file:///Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.agents/skills/lib.sh#L16)
```bash
MAM_VERSION="4.1.3"
```
### 2) 버전 이력 및 매트릭스 (`VERSIONS.md`)
- [`VERSIONS.md`](file:///Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/VERSIONS.md)
- Line 9: `- **프레임워크 버전**: `v4.1.3``
- Line 10: `- **최신 릴리스 일시**: 2026-08-31 (KST)`
- Line 15: `lib.sh 내 MAM_VERSION="4.1.3" 런타임 진실 공급원 정의...`
- Line 21: `... 표준화를 통해 v4.1.3으로 동기화되어 배포됩니다.`
- Line 23~33: 8개 스킬 버전 매트릭스 표 전체 `4.1.2` $\rightarrow$ `4.1.3` 갱신
- Line 38 상단: 신규 `v4.1.3` 릴리스 체인지로그 섹션 삽입
### 3) 8개 스킬 메타데이터 (`SKILL.md` frontmatter)
- `.agents/skills/multi-agent-mux-create/SKILL.md`: `version: 4.1.3`
- `.agents/skills/multi-agent-mux-stop/SKILL.md`: `version: 4.1.3`
- `.agents/skills/multi-agent-mux-resume/SKILL.md`: `version: 4.1.3`
- `.agents/skills/multi-agent-mux-status/SKILL.md`: `version: 4.1.3`
- `.agents/skills/multi-agent-mux-monitor/SKILL.md`: `version: 4.1.3`
- `.agents/skills/multi-agent-mux-delegate-job/SKILL.md`: `version: 4.1.3`
- `.agents/skills/multi-agent-mux-loop/SKILL.md`: `version: 4.1.3`
- `.agents/skills/multi-agent-mux-orc-onboard/SKILL.md`: `version: 4.1.3`
### 4) 자동화 검증 계약
- [`tests/test_version_consistency.py`](file:///Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/tests/test_version_consistency.py):
- `test_three_way_version_lockstep()`: `lib.sh(MAM_VERSION)` == `VERSIONS.md(Current + Matrix 8 items)` == `8x SKILL.md frontmatters` 100% 일치 검증
- `test_mam_version_is_not_env_overridable()`: 환경변수 위조 차단 검증
---
## 5. `VERSIONS.md` 반영용 `v4.1.3` 체인지로그 초안
후속 릴리스 작업 시 `VERSIONS.md`에 추가될 표준 변경 이력 초안입니다:
```markdown
### 🛠️ `v4.1.3` — Herdr Daemon Isolation & Class A 0-Turn Resume Reliability Fixes (2026-08-31)
> **주요 마일스톤 (PATCH Release)**: Issue #3 결함 해소 — Herdr 백그라운드 데몬의 `start_new_session=True` 기반 프로세스 그룹(setsid) 완전 격리, Class A(`agy`, `hermes`, `opencode`) 에이전트 0-turn 중지 세션의 `FRESH_SPAWN` fallback 및 discovery epoch 원자적 재설정, Class B(`claude`, `grok`) 계약 불변 보존, 455개 전체 테스트 스위트 100% PASS 달성.
#### 🩹 버그 수정 및 안정성 개선 (Bug Fixes & Resilience)
* **C-1: Herdr 데몬 프로세스 그룹(PGID/SID) 완전 분리 (`lib.sh`)**:
- `.mam/shim/herdr` 템플릿의 `nohup ... & disown` 스폰 방식을 파이썬 `subprocess.Popen(..., start_new_session=True)` 기반 전용 스포너로 대체하여 자식 프로세스에서 `os.setsid()` 호출 보장.
- 부모 셸이나 테스트 러너의 시그널 브로드캐스트(`SIGTERM`/`SIGINT`)로 인해 백그라운드 Herdr 데몬이 예기치 않게 종료되는 결함을 원천 차단 (`test_h26`).
* **C-2: Class A 에이전트 0-turn resume 자율 Fallback 및 Discovery Watermark 갱신 (`resume_session.sh`, `update_yaml_resumed.sh`)**:
- 대화 턴이 발생하기 전에 중지된 Class A(`agy`, `hermes`, `opencode`) 세션 resume 시, UUID 미존재로 인한 비정상 hard-fail(RC=1) 대신 `FRESH_SPAWN=1`로 자동 전환하여 `spawn-spec` 기반의 정상 재스폰 수행 (`test_t14`).
- fresh-spawn resume 시 `update_yaml_resumed.sh`에서 `herdr_session_epoch`를 resume 시점의 타임스탬프로 즉시 갱신하고 `session_id_source: pending-discovery`로 재설정하여, 세션 생성과 복원 사이에 생성된 무관한 이전 대화 파일이 `reconcile.sh`의 discovery sweep에 의해 오인 캡처되는 것을 방지 (`test_t16`).
- Class B(`claude`, `grok`) 에이전트의 `verify_session.py:99-101` assigned escape hatch 및 `test_t8` 계약은 수정 없이 완벽히 보존 (`test_t15`).
```
---
## 6. 결론 및 피어 리뷰 요청 (Conclusion & Consensus Request)
1. **최종 결론**:
- Issue #3의 수정 사항은 프레임워크의 핵심 실행 라이프사이클에 직접적인 영향을 미치는 중요한 안정성 개선이므로 버전 업데이트가 필수적입니다.
- 변경의 성격은 100% 하위 호환성을 유지하는 결함 수정이므로, **`v4.1.3` (PATCH)** 로 판정하는 것이 SemVer 2.0.0 규칙에 부합합니다.
2. **리뷰어 피어 리뷰 요청**:
- `planner-reviewer-claude-01`, `reviewer-creator-grok-01`, `reviewer-opencode-01` 세 리뷰어께 본 검토 보고서의 버전 판정 논리(`v4.1.3` PATCH) 및 3-Way Lockstep 계획에 대한 검토와 합의를 요청드립니다.
@@ -0,0 +1,371 @@
> **본 리포트는 Job `2770df36`(role: Planner)의 산출물인 Phase 2a 구현 계획서다.**
> durable 사본: `.agents/reports/creator-claude-01/plan-2770df36.md` (커밋됨).
>
> **범위 명시**: 본 job의 지시는 "구현 계획서를 작성"이며, 목표 문장의 (5) 테스트 작성·(6) 리뷰어 만장일치 PASS는 이 계획을 실행할 **후속 Worker/Reviewer job**의 완료 조건이다. 본 계획서는 그 job들이 그대로 실행할 수 있도록 커밋 5개·게이트 9개·인수인계 체크리스트까지 명세했다.
---
# 📑 Issue #5 Phase 2a 구현 계획서 — `lib_py/loop/` 코어 & Shadow Watcher
- **Job**: `2770df36` / **Planner**: `creator-claude-01`
- **기준 커밋**: `015ab70` (branch `refactor`, working tree clean) / Python `3.9.6` / paho-mqtt `2.1.0` / herdr `0.8.2` / **전체 테스트 수집 576**
- **요구 출처**: `implementation_plan.md` §2 Phase 2a 행, `task.md` P2A-01~P2A-04, `state-transitions.md` §2~§5
- **문서 성격**: Worker가 그대로 실행할 수 있는 단계별 명세. §1의 모든 인용은 계획 수립 중 **라이브 코드·라이브 CLI로 직접 확인**했다.
---
## 0. 요약 (TL;DR)
1. **Phase 2a는 레지스트리에 단 1바이트도 쓰지 않는다.** Shadow watcher는 "Would-Complete" 판정을 로그로만 남긴다. 이 불변식을 문장이 아니라 **구조와 테스트로** 강제한다(§D5, G4).
2. **CAS 경계는 신규 파일이 아니라 기존 writer 3곳을 한 함수 뒤로 모으는 작업이다.** 현재 상태 writer는 3개이고 그중 **하나(`pick_pending`)는 이미 문서화된 chokepoint를 우회**한다(§1-2 실측).
3. **4중 귀속에 필요한 필드가 job 레코드에 없다**(`attempt_id`/`agent_session_uuid`/`pane_process_generation` 전부 부재, §1-4). Phase 1이 레코드 스키마 불변을 약속했고 Phase 2a는 레지스트리 쓰기가 금지되므로, **귀속 증거는 shadow 전용 저장소에 둔다.** 레코드 스키마 결정은 Phase 2b로 미룬다.
4. **`herdr agent wait --timeout`의 단위는 밀리초다**(라이브 `--help` 확인, Phase 0 fixture도 `integer_ms`로 정확히 기록). 초 단위로 오해하면 1000배 오차가 난다.
5. **락 안에서 감사 로그 I/O가 일어나고 있다**(`update_job_status`가 락 보유 중 `update_logged_status`/`append_event` 호출, §1-3). Phase 2a는 이를 "락 안에서 결정 + 알림 큐잉 → 락 해제 → 밖에서 flush"로 바꾼다.
6. **판정 로직의 테스트 벡터는 새로 만들지 않는다.** Phase 0에서 3인 리뷰로 검증된 watcher 시나리오 7종과 그 `expected_policy`가 그대로 엔진의 결정 테이블 테스트가 된다(§D7).
---
## 1. Planner 사전 실측
### 1-1. 대상 파일과 규모
| 항목 | 실측 |
|---|---|
| 기준 커밋 | `015ab70` |
| 전체 테스트 | **576 수집** (Phase 1 종료 시점) |
| `lib_py/` 기존 패키지 | `agents/`, `delegation/`, `atomic_yaml.py`, `layout.py`, `paths.py`, `state.py`, `verify_session.py`, `workspace_uuid.py` |
| `MAM_ENGINE_CAS` | **아직 존재하지 않음** (`grep` 결과 `implementation_plan.md` 언급 1건뿐) — Phase 2a가 신설 |
### 1-2. job 레코드 상태 writer 전수 조사 (P2A-01의 실제 범위)
`_atomic_write_record` 직접 호출자 = **5곳**, 그중 상태를 바꾸는 것은 **3곳**이다.
| # | 위치 | 하는 일 | CAS 여부 |
|---|---|---|---|
| W1 | `mqtt_common.py:410` (`update_job_status`) | `record.update(fields)` **무조건 병합** | ❌ 없음 |
| W2 | `registry.py:131` (`pick_pending`) | 락 안에서 `status == "pending"` 필터 후 `running`으로 기록 | ⚠️ **사실상 CAS이나 W1을 우회한 별도 구현** |
| W3 | `mqtt_common.py:433` (`next_seq`) | `last_seq` 증가 (상태 무관) | 해당 없음 |
| — | `registry.py:107` (`register_job`) | 레코드 생성 | 해당 없음 |
| — | `registry.py:151` (`update_status`) → W1 | | |
| — | `registry.py:365` (`update` CLI) → W1 | | |
| — | `publish_event.py:179` (`record_outcome`) → W1 | | |
> **핵심 (정확히)**: `update_job_status`의 docstring은 자신을 "the single chokepoint for status writes"라고 선언하지만, `registry.py:135`의 주석이 스스로 인정하듯 `pick_pending`은 이를 우회한다.
>
> 단, **`pick_pending`이 틀린 것은 아니다.** 락 안에서 `status == "pending"`을 필터한 뒤 기록하므로 `pending → running`에 대해서는 **이미 올바른 compare-and-swap**이다(`registry.py:123`). 문제는 정확성이 아니라 **중복**이다: CAS 판정과 감사 로그 mirror가 두 벌로 존재하며, Phase 1의 O-1(1회성 전송 이중 구현)에서 확인했듯 **같은 로직의 사본은 한쪽에만 결함이 생기는 경로**다.
>
> 따라서 **P2A-01은 "없는 CAS를 새로 만드는" 작업이 아니라 "한쪽에만 있는 CAS를 모든 전이로 일반화하고 두 사본을 하나로 합치는" 작업이다.** 실제로 CAS가 전혀 없는 것은 W1(`record.update(fields)` 무조건 병합)이다.
셸/래퍼 측은 job 레코드를 직접 쓰지 않는다: 래퍼는 `registry.py status --set`(→W1)을, `reconcile.sh:192`는 `registry.load_job`(읽기 전용)만 쓴다. `run_loop.sh:254`는 job JSON을 **읽기만** 한다(3초 폴링). 즉 **모든 쓰기가 파이썬 안에 있다** — CAS 경계를 파이썬 한 곳에 두면 전수 커버가 가능하다.
### 1-3. 현재 락 트랜잭션의 I/O 실측
`update_job_status`(`:405-418`)는 `registry_lock` **보유 중에** 다음을 수행한다:
- `load_job` (읽기 I/O)
- `_atomic_write_record` (쓰기 + `fsync` + `os.replace`)
- `update_logged_status` (**감사 로그 디렉터리 쓰기**)
- `append_event` (**감사 로그 append**)
네트워크/서브프로세스는 락 안에 없다(`publish_event.main`의 순서: `next_seq`(락) → 발행(네트워크, 락 없음) → `record_outcome`(락)). **이 성질은 Phase 2a에서 반드시 보존해야 하며**, 추가로 감사 로그 I/O를 락 밖으로 빼는 것이 P2A-01의 "락 내 I/O 배제" 요구다.
### 1-4. 4중 귀속에 필요한 필드 부재 (설계를 좌우하는 사실)
라이브 job 레코드의 실제 키:
```
agent, agent_session, auth_token, broker, created_at, expected_artifacts,
idle_timeout_sec, iteration, job_id, job_type, last_seq, max_iterations,
prompt, reviewer, reviewer_session, role, schema_version, status,
timeout_sec, topic_prefix, updated_at
```
`state-transitions.md` §2가 요구하는 4중 귀속 중 **`attempt_id`·`agent_session_uuid`·`pane_process_generation`이 전부 없다**. `iteration`(루프 회차)은 있으나 attempt와 의미가 다르다.
동시에 Phase 1은 "스키마 불변(`SCHEMA_VERSION = 1`, 레지스트리 레코드 필드 불변)"을 계약으로 못박았고, P2A-03은 **레지스트리 쓰기 자체를 금지**한다. → **Phase 2a에서 귀속 증거를 레코드에 넣는 것은 불가능하며, 넣어서도 안 된다.** §D6이 이를 해결한다.
### 1-5. `herdr agent wait` 라이브 계약 (watcher.py의 입력)
```
Usage: herdr agent wait <TARGET> [OPTIONS]
--until <STATUS> idle|working|blocked|done|unknown (반복 가능)
--timeout <MS> Fail after this many milliseconds
Without --until, matches idle, done, or blocked.
Without --timeout, waits indefinitely.
```
- **단위는 밀리초**다. Phase 0 fixture(`wait-contract.json`)도 `"type": "integer_ms"`로 정확히 기록되어 있다.
- 성공 → `exit 0`, **stdout**에 `{"id":"cli:agent:wait","result":{"agent":{...}}}`.
- 타임아웃/대상 부재 → `exit 1`, **stderr**에 에러 JSON(`error.code` = `timeout` / `agent_not_found`). stdout은 비어 있다.
- `--until` 생략 시 기본 매칭은 `idle,done,blocked` — **`working`은 매칭되지 않는다.** watcher는 항상 `--until`을 명시한다.
- **단일 `wait`는 1개의 최종 스냅샷만 주는 동기 장벽**이다(`herdr-runtime.md` §2-1). 연속 관측은 반복 호출로 구성해야 한다.
### 1-6. Phase 0에서 이미 검증된 판정 벡터
`tests/fixtures/issue_5/watcher/`의 7종과 `expected_policy.decision`은 3인 교차 리뷰를 통과한 계약이다. Phase 2a 엔진의 결정 함수는 **이 7종을 그대로 입력받아 같은 결정을 내야 한다**.
| 시나리오 | 기대 결정 |
|---|---|
| `initial_idle` | `hold` (실행 앵커 없음) |
| `tool_running` | `hold` (도구 실행 중) |
| `report_pause_15s` | `hold` (매니페스트 없음 — 디바운스만으로 완료 금지) |
| `finalized_candidate` | `candidate_approved` |
| `blocked_permission` | `hold_blocked` |
| `transport_disconnected` | `hold_reconnect` |
| `restarted_generation` | `reject_stale` |
`dispatch_context` 필드: `job_id`, `attempt_id`, `agent_session_uuid`, `pane_process_generation`, `dispatch_ack`, `execution_anchor_observed`.
### 1-7. Phase 1에서 넘어온 인계 사항 (본 Phase가 게이트)
1. **`preexec_fn` (3인 리뷰어 공통 지적)**: `daemon.spawn`은 `preexec_fn`으로 SIGHUP을 무시하는데 이는 **멀티스레드 프로세스에서 안전하지 않다**. Shadow watcher가 스레드를 쓰면서 `DelegationService.ensure_subscriber_daemon`을 호출하면 이 게이트에 걸린다(§D9).
2. **O-4 (Claude)**: freeze 트리의 `_delegate_py_bin`은 `.venv`를 찾지 못해 paho 없는 시스템 python으로 떨어진다. Phase 2a가 freeze `lib.sh` 헬퍼를 호출하지 않는 한 무해하다(§D9에서 재확인).
3. **연결 지문 하드코딩 필드 목록**: `BrokerConfig` 필드 추가 시 조용히 누락된다. Phase 2a에서 `dataclasses.fields()` 유도로 바꾸거나 커버리지 단정 테스트를 추가한다(§3 P2A-04에 포함).
---
## 2. 설계 결정 (Design Decisions)
### D1. 패키지 배치
```
.agents/skills/lib_py/loop/
__init__.py # 공개 API 재수출
evidence.py # 증거 튜플 정규화 (watcher → engine 사이의 유일한 자료형)
attribution.py # 4중 귀속 + dispatch anchor 판정 (순수 함수)
policy.py # 결정 함수: 증거 -> hold|hold_blocked|hold_reconnect|reject_stale|candidate_approved
engine.py # 단일 전이 주체 + CAS 트랜잭션 경계
watcher.py # herdr agent wait 래핑, 재연결 백오프, 스냅샷 수집
shadow.py # Shadow 러너: watcher -> policy -> "would-complete" 로깅 (쓰기 없음)
store.py # shadow 전용 귀속/증거 저장소 (레지스트리와 분리)
```
- **`policy.py`는 순수 함수여야 한다**(I/O·시계·전역 상태 금지). Phase 0 fixture 7종을 그대로 먹여 테스트하기 위한 필수 조건이다.
- **D1(b) 재적용**: `lib_py.loop`는 `lib_py.delegation` **외의** 형제 `lib_py` 모듈을 임포트하지 않는다. 이유는 Phase 1과 동일하다 — freeze 하에서 부모 `lib_py`와 바인딩된 패키지가 다른 트리일 수 있다. AST grep 테스트로 고정한다(§D8).
- Python 3.9 호환 필수(`match`, PEP 604 런타임 유니온 금지). 게이트에서 `compileall`.
### D2. 단일 CAS 전이 경계 (P2A-01)
**`engine.transition()`이 유일한 상태 writer가 된다.**
```python
# lib_py/loop/engine.py
class TransitionResult(object):
__slots__ = ("committed", "from_status", "to_status", "reason", "record", "notifications")
def transition(job_id, request, *, registry_dir, expected_attempt=None,
expected_status=None, fields=None, source="unknown") -> TransitionResult:
"""유일한 상태 전이 주체.
락 안에서 하는 일: load -> CAS 판정 -> (허용 시) 기록 -> 알림 큐잉.
락 밖에서 하는 일: 알림 flush(감사 로그), MQTT 발행.
"""
```
CAS 규칙은 `state-transitions.md` §3 표를 그대로 구현한다:
| 현재 | 요청 | 조건 | 결과 |
|---|---|---|---|
| `pending` | `claim`/`started` | 세션·attempt 일치 | `running` |
| `running` | `progress`/`permission_required` | — | `running` (메타만 갱신) |
| `running` | explicit terminal | 유효 세션 서명 | 요청 terminal |
| `terminal` | 동일 terminal 재수신 | — | **No-op 멱등 ACK** |
| `terminal` | 상충 신호 | — | **거부 + conflict 감사 기록** |
| 임의 | stale attempt/generation | 불일치 | **거부 + stale 경고** |
| `running` | `deadline_timeout` | 타임아웃 확인 | `error` |
**기존 writer 3곳의 라우팅**:
- W1 `update_job_status` → 내부적으로 `engine.transition(request="merge", ...)`를 호출하도록 교체. **시그니처·반환값·예외는 불변**(Phase 1의 G-1~G-4가 이 함수 계약에 걸려 있다).
- W2 `pick_pending` → `engine.transition(request="claim", expected_status="pending")`로 교체. 이로써 우회가 사라진다.
- W3 `next_seq` → 상태를 바꾸지 않으므로 그대로 두되, 같은 락을 쓰므로 **트랜잭션 시간 예산**에만 포함한다.
**롤백 스위치 `MAM_ENGINE_CAS`(기본 `1`)**: `0`이면 W1/W2가 **현재의 무조건 병합 본체**로 분기한다. Phase 1의 `MAM_DELEGATION_PY`와 동일한 패턴이며, legacy 본체는 `_*_legacy`로 보존한다(제거는 Phase 4).
### D3. 락 규율 — 락 안에서는 결정만, I/O는 밖에서
```
with registry_lock(registry_dir): # 짧게
record = load_job(...)
decision = _cas_decide(record, request, expected_attempt, expected_status)
if decision.commit:
_atomic_write_record(...) # 레코드 1회 쓰기만 허용
pending = decision.notifications # 감사 로그는 "쓰지 않고" 큐에 담는다
# 락 해제 후
_flush_notifications(pending) # 감사 로그 append / status mirror
```
- **금지**: 락 보유 중 `subprocess`, 소켓, MQTT, `herdr` 호출, `time.sleep`.
- **허용**: `load_job` 1회 + `_atomic_write_record` 1회.
- 감사 로그 mirror(`update_logged_status`/`append_event`)를 락 밖으로 옮긴다. **순서 보장 손실 우려**: 현재는 락 안이라 감사 이력이 직렬화된다. 이를 유지하기 위해 알림에 **CAS가 부여한 단조 `transition_seq`**를 실어 보내고, flush가 늦게 도착해도 순서를 복원할 수 있게 한다.
- 이 규율은 문장이 아니라 테스트로 강제한다: 락 획득 중 `subprocess.run`/`socket.socket`/`time.sleep`을 monkeypatch로 감시해 호출 0건을 단정한다(G5).
- **저장소에 이미 선례가 있다**: `pick_pending`은 레코드 쓰기를 락 안에서 끝내고 감사 로그 mirror(`update_logged_status`/`append_event`)를 **락 해제 후에** 수행한다(`registry.py:131-145`). D3은 새 패턴을 발명하는 것이 아니라 **이 기존 패턴을 `update_job_status`에도 적용해 일반화**하는 것이다.
### D4. `watcher.py` — `herdr agent wait` 래핑
```python
def wait_once(target, until=("idle", "done", "blocked"), timeout_ms=15000, run=subprocess.run) -> WaitOutcome
```
- `--timeout`은 **밀리초**로 전달한다(§1-5). 초 단위 인자를 받지 않는다 — 단위 혼동을 타입 이름(`timeout_ms`)으로 차단한다.
- `--until`을 **항상 명시**한다(생략 시 `working`이 빠지는 기본값에 의존하지 않는다).
- `exit 0` → stdout JSON 파싱 → `result.agent` 스냅샷.
- `exit 1` → **stderr** JSON 파싱 → `error.code`로 분기: `timeout`(정상적 무이벤트), `agent_not_found`(대상 소멸).
- 그 외 exit code / JSON 파싱 실패 / 실행 실패 → `transport_error`.
- **재연결 백오프**: `transport_error` 연속 발생 시 1s → 2s → 4s → … → 최대 16s. 백오프 대기는 **락 밖에서만** 한다. 복구 시 **캐시된 스냅샷을 폐기하고 재스냅샷**한다(`transport_disconnected` → `hold_reconnect` 정책과 일치).
- watcher는 **판정하지 않는다.** 증거 튜플만 만들어 큐에 넣는다(Phase 0 합의: watcher는 관측, engine은 결정).
### D5. Shadow 모드 — 쓰기 불가를 구조로 보장 (P2A-03)
```python
# shadow.py
class ShadowRunner:
def __init__(self, ..., decide=policy.decide, sink=logging_sink):
... # engine 을 아예 주입받지 않는다
```
- **ShadowRunner는 `engine.transition`에 대한 참조를 갖지 않는다.** "쓰지 않기로 약속"이 아니라 **쓸 수단이 없다**. 이것이 P2A-03을 문장이 아니라 구조로 만드는 방법이다.
- 판정 결과는 `would_complete` 레코드로 **shadow 전용 로그**에만 남는다: `.mam/shadow/<job_id>.ndjson` (레지스트리와 다른 디렉터리).
- 검증(G4): shadow 러너를 시나리오 전량으로 돌린 전후에 **레지스트리 디렉터리 전체의 파일 목록·mtime·SHA-256이 바이트 동일**함을 단정한다. "status를 안 썼다"보다 강한 단정이다.
### D6. 귀속 증거는 shadow 전용 저장소에 (§1-4 결론)
`store.py`가 `.mam/shadow/attribution/<job_id>.json`을 소유한다. 담기는 것:
```json
{ "job_id": "...", "attempt_id": 1, "agent_session_uuid": "...",
"pane_process_generation": "w2X:p1:1234:2026-09-06T00:00:00Z",
"dispatch_ack": true, "dispatch_ack_at": "...", "execution_anchor_observed": false }
```
- **job 레코드는 건드리지 않는다** → Phase 1의 스키마 불변 계약과 P2A-03을 동시에 만족한다.
- `attempt_id`는 Phase 2a에서 **shadow가 자체 부여**한다(디스패치 관측 시 1부터). Phase 2b에서 레코드로 승격할지는 그때 결정한다 — **이 계획서는 레코드 스키마를 바꾸지 않는다.**
- `pane_process_generation`은 `<pane_id>:<pid>:<start_iso>` 형식이며, Phase 0의 정체성 검증(`_validate_observed_herdr_item`)이 이미 이 형식을 강제한다.
### D7. 판정 테스트 벡터 = Phase 0 fixture (P2A-04의 절반)
`policy.decide(scenario) -> decision` 이 Phase 0의 7종 시나리오에 대해 `expected_policy.decision`과 **정확히 일치**해야 한다. 신규 fixture를 만들기 전에 **기존 계약을 먼저 만족**시킨다. 이렇게 하면:
- 판정 로직이 3인 리뷰를 통과한 계약에 묶인다.
- Phase 0의 `validate_watcher_scenario`가 fixture 무결성을 계속 지킨다.
추가 시나리오(P2A-04 요구)는 같은 스키마로 작성하고 **`validate_watcher_scenario`를 통과해야 한다**: `race_double_dispatch`, `attempt_reuse`, `partial_report`, `unknown_status`, `restart_midflight`.
### D8. 트리 일관성 (Phase 1 R1의 교훈 재적용)
- `lib_py.loop`는 `lib_py.delegation`만 형제로 임포트한다. 그 외 `lib_py.*` 금지 → AST 테스트.
- 루프 프로세스는 shim을 인프로세스로 임포트하지 않으므로 `lib_py.loop`와 `lib_py.delegation`은 부모 `lib_py`를 통해 **같은 트리**로 해석된다. 이를 테스트로 고정한다(`__file__` 접두 비교).
- Shadow 러너를 서브프로세스로 띄울 때는 Phase 1의 `_delegation_py`와 **동일한 명시 부트스트랩**을 쓴다. `python -m`은 cwd가 `PYTHONPATH`를 이기므로 금지한다(R1 재발 방지).
### D9. Phase 1 인계 게이트 해소
- **`preexec_fn`**: Shadow watcher가 스레드를 쓸 경우 `daemon.spawn`의 `preexec_fn`이 위험해진다. **Phase 2a에서는 shadow 러너가 데몬을 스폰하지 않는다**(관측만). `ensure_subscriber_daemon` 호출 금지를 grep 테스트로 고정하고, 실제 제거/대체는 Phase 2b 스폰 도입 시 처리한다.
- **O-4**: shadow는 freeze `lib.sh` 헬퍼를 호출하지 않으므로 인터프리터 해석 문제에 노출되지 않는다. 호출 0건을 grep으로 고정한다.
- **연결 지문 필드 목록**: `dataclasses.fields(BrokerConfig)` 전량이 지문에 포함됨을 단정하는 테스트를 추가한다(필드 추가 시 조용히 누락되는 것을 차단).
---
## 3. 작업 분해 (WBS) — 커밋 5개
### P2A-00 특성화 선행 (커밋 1: `test(issue-5): phase 2a writer inventory and lock discipline characterization`)
- **파일**: `tests/test_issue5_phase2a_loop.py`(신규)
- 현행 동작을 **먼저 고정**한다(Phase 1에서 효과가 입증된 순서):
- X-01 `update_job_status`가 무조건 병합임을 단정(현행 사실).
- X-02 `pick_pending`의 현행 계약 고정: `pending`만 claim하고 동시 claim 시 한 세션만 이긴다(라우팅 후에도 이 성질이 유지되어야 한다).
- X-03 락 보유 중 감사 로그 I/O가 **발생함**을 단정(현행 사실 — D3 이후 이 테스트는 반대로 뒤집힌다).
- X-04 `next_seq`/`register_job`/`record_outcome` 경로의 현행 부작용 스냅샷.
- **완료 기준**: 레거시 코드에서 전부 통과, 576 + 신규 통과.
### P2A-01 엔진·CAS 경계 (커밋 2: `feat(issue-5): single CAS transition boundary for every job-status writer`)
- **파일**: `lib_py/loop/{__init__,engine,evidence,attribution}.py`; `mqtt_common.update_job_status`·`registry.pick_pending` 라우팅; `MAM_ENGINE_CAS` 분기 + `_*_legacy` 보존.
- **테스트**: `state-transitions.md` §3 표 9행 전부에 대한 전이 테스트, 멱등 재수신, 상충 거부 + conflict 감사, stale attempt 거부, `MAM_ENGINE_CAS=0` 양 경로 parametrize, **락 내 I/O 0건 단정**(subprocess/socket/sleep monkeypatch).
- **완료 기준**: Phase 1의 G-1~G-4가 그대로 통과(계약 불변 증명), 전체 스위트 무회귀.
### P2A-02 watcher (커밋 3: `feat(issue-5): herdr agent wait watcher with reconnect backoff`)
- **파일**: `lib_py/loop/watcher.py`, `store.py`
- **테스트**: 가짜 `run`으로 exit 0/stdout, exit 1/stderr `timeout`, exit 1/stderr `agent_not_found`, 파싱 실패, 실행 실패 5경로; 백오프 수열(1,2,4,8,16 상한)과 **재연결 시 캐시 폐기**; `--timeout`이 **밀리초로 전달**됨을 argv 단정; `--until` 항상 명시됨을 argv 단정. **herdr 실제 호출 0건**(전부 주입된 가짜).
- **완료 기준**: 위 통과 + 실제 herdr로 1회 스모크(수동, 보고서 첨부).
### P2A-03 shadow 러너 (커밋 4: `feat(issue-5): shadow watcher that logs would-complete without writing`)
- **파일**: `lib_py/loop/{policy,shadow}.py`
- **테스트**: Phase 0 시나리오 7종 → `policy.decide`가 `expected_policy.decision`과 일치; 신규 시나리오 5종 추가(`validate_watcher_scenario` 통과 필수); **레지스트리 디렉터리 SHA-256 전후 동일** 단정; `ShadowRunner`가 `engine`/`update_job_status`/`_atomic_write_record`를 참조하지 않음을 AST로 단정.
- **완료 기준**: shadow 전량 실행 후 레지스트리 바이트 불변.
### P2A-04 통합·문서 (커밋 5: `docs(issue-5): phase 2a contracts, scenarios and task checklist`)
- race/attempt 재사용/부분 리포트/도구 실행/blocked/unknown/재시작 시나리오 실행 결과 기록.
- `state-transitions.md`에 구현 매핑 각주, `task.md` P2A-01~04 체크 + 증거, `implementation_plan.md` Phase 2a 상태 갱신, `MAM_ENGINE_CAS` 운영 문서.
- Phase 1 인계 3건 처리 상태 명시(§D9).
---
## 4. 게이트
| # | 조건 | 측정 |
|---|---|---|
| G1 | 기존 **576** 전부 통과 + 신규 전부 통과, skipped 0 | `pytest tests/ -q` (약 13분) |
| G2 | 셸 문법·공백 | `bash -n`, `git diff --check` (**범위** 기준) |
| G3 | Python 3.9 컴파일 | `compileall .agents/skills/lib_py/loop` |
| **G4** | **Shadow가 레지스트리에 0바이트 기록** | 실행 전후 레지스트리 디렉터리 파일 목록·SHA-256 동일 |
| **G5** | **락 내 I/O 배제** | 락 보유 중 subprocess/socket/sleep 호출 0건 (monkeypatch 감시) |
| G6 | 모든 상태 writer가 CAS 경유 | `_atomic_write_record` 직접 호출자가 engine·`register_job`·`next_seq`뿐임을 AST로 단정 |
| G7 | 판정이 Phase 0 계약과 일치 | 시나리오 7종 + 신규 5종 `expected_policy` 일치 |
| G8 | 롤백 | `MAM_ENGINE_CAS=0`에서 특성화 통과 + 라이브 스모크 |
| G9 | 트리 일관성 | `lib_py.loop`/`lib_py.delegation` 동일 트리, 형제 임포트 0건 |
Worker 보고서에는 G1 pytest 요약 원문, G4의 해시 비교 출력, G5의 감시 로그, G7 표를 **그대로** 붙인다. `file:line` 인용은 `grep -n` 출력으로 뒷받침한다.
---
## 5. 롤백
1. **즉시**: `MAM_ENGINE_CAS=0` → W1/W2가 보존된 legacy 무조건 병합으로 분기. Shadow는 애초에 쓰기가 없으므로 프로세스 종료만으로 흔적이 사라진다.
2. **프로세스**: Shadow 러너 종료 + 인메모리 큐 폐기. `.mam/shadow/`는 삭제해도 무해(레지스트리와 분리되어 있음).
3. **커밋 단위**: 5→4→3→2 순 `git revert`. 커밋 1(특성화)은 레거시에서도 통과하므로 남겨도 된다.
---
## 6. 리스크와 완화
| # | 리스크 | 완화 |
|---|---|---|
| R1 | CAS 도입이 Phase 1의 G-1~G-4 계약을 깬다 | `update_job_status` 시그니처·반환·예외 불변 유지, 두 경로 parametrize |
| R2 | 감사 로그를 락 밖으로 빼면서 순서가 뒤바뀐다 | CAS가 부여하는 단조 `transition_seq`를 알림에 실어 순서 복원 |
| R3 | `pick_pending` 라우팅이 **이미 올바른** 동시 claim 경쟁을 깨뜨린다 | 라우팅 전에 X-02로 현행 성질을 고정하고, `expected_status="pending"` CAS가 동일 성질을 유지함을 동시 claim 테스트로 검증 |
| R4 | `--timeout` 단위 혼동(초 vs ms) | 인자명 `timeout_ms`, argv 단정 테스트 |
| R5 | shadow가 실수로 쓰기 경로를 얻는다 | 구조적 차단(engine 미주입) + AST 단정 + 해시 불변 단정 |
| R6 | freeze/live 트리 혼재 | D8 (형제 임포트 금지 + 명시 부트스트랩) |
| R7 | `preexec_fn` 스레드 비안전 | Phase 2a는 데몬 스폰 없음(grep 고정), 실제 대체는 Phase 2b |
| R8 | 실브로커/실herdr 의존 테스트 | 전부 주입된 가짜, 실호출 0건. 라이브 스모크는 수동·정보성 |
---
## 7. 명시적 비범위
- **자동완료 실제 커밋** — Phase 2b. Phase 2a는 `would_complete` 로깅까지만.
- job 레코드 스키마 변경(`attempt_id` 등 승격) — Phase 2b.
- `run_loop.sh`의 파이썬화 — Phase 3.
- 래퍼·`reconcile.sh`의 상태 머신 변경 — 전 Phase 공통 불변.
- `preexec_fn` 제거 — Phase 2b.
- `pgrep` 다중 PID 정리, Windows — Phase 4 후보.
---
## 8. Worker 인수인계 체크리스트
- [ ] P2A-00 커밋 1: 현행 동작 특성화(W1 무조건 병합, W2 우회, 락 내 I/O 발생)가 **레거시 코드에서** 통과
- [ ] P2A-01 커밋 2: `engine.transition` 단일 경계, W1/W2 라우팅, `MAM_ENGINE_CAS` 양 경로, 락 내 I/O 0건
- [ ] P2A-02 커밋 3: watcher 5경로 + 백오프 + ms 단위 argv 단정
- [ ] P2A-03 커밋 4: Phase 0 시나리오 7종 일치 + 신규 5종, 레지스트리 해시 불변
- [ ] P2A-04 커밋 5: 문서·체크리스트·인계 3건 처리 상태
- [ ] 보고서: G1 원문, G4 해시 출력, G5 감시 로그, G7 표, `grep -n` 인용
- [ ] 커밋 접두: `test(issue-5)`, `feat(issue-5)`, `feat(issue-5)`, `feat(issue-5)`, `docs(issue-5)`
---
## 부록 A. 계획 수립 시 실행한 검증 명령 (재현용)
```bash
git log --oneline -1 # 015ab70
.venv/bin/python -m pytest tests/ --collect-only -q | tail -1 # 576
grep -rn "_atomic_write_record" --include='*.py' .agents | grep -v "def " # writer 5곳
sed -n '125,155p' .agents/skills/lib_py/delegation/registry.py # pick_pending 우회
sed -n '395,420p' .agents/skills/lib_py/delegation/mqtt_common.py # 락 내 감사 I/O
HERDR_SESSION_NAME=multi-agent-mux herdr agent wait --help # --timeout <MS>
cat tests/fixtures/issue_5/herdr/wait-contract.json # integer_ms
grep -rn "MAM_ENGINE_CAS" --include='*.py' --include='*.sh' . # 미존재
.venv/bin/python -c "import json,glob; print(sorted(json.load(open(sorted(glob.glob('.mam/jobs/*.json'))[-1]))))" # 레코드 키 (attempt_id 부재)
```
@@ -0,0 +1,251 @@
# 📑 Issue #5 Phase 2b 구현 계획서 — 이중 감지 자동완료 (Flag-Gated / Opt-In)
- **Job**: `df85e978` / **Planner**: `creator-claude-01`
- **기준 커밋**: `4a5916a` (branch `refactor`, working tree clean) / Python `3.9.6` / herdr `0.8.2` / **전체 테스트 664**
- **요구 출처**: `implementation_plan.md` §2 Phase 2b 행, `task.md` P2B-01~P2B-03, `state-transitions.md` §3~§6
- **문서 성격**: Worker가 그대로 실행할 수 있는 단계별 명세. §1의 모든 인용은 라이브 코드·실행으로 직접 확인했다.
---
## 0. 요약 (TL;DR)
1. **매니페스트를 쓰는 주체가 이 Phase의 전부다.** 워처가 스스로 해시를 계산해 매니페스트를 만들면 그것은 "워처가 안정된 파일을 봤다"는 자기 증명일 뿐이며, Round 2에서 Codex가 R1으로 기각한 바로 그 형태다. **끝났다는 사실을 아는 쪽(에이전트)이 확정을 선언해야 한다**(§D1).
2. **그래서 미지원 에이전트는 자동으로 fail-closed가 된다.** 확정 선언을 하지 않으면 매니페스트가 없고, 매니페스트가 없으면 `policy`가 이미 `hold`한다(Phase 2a에서 구현·테스트 완료). P2B-03의 "미지원 경로 100% 보존"은 새 분기가 아니라 **기존 동작의 자연스러운 귀결**이다.
3. **`attempt_id`와 `iteration`의 의미 충돌을 먼저 정리해야 한다.** 엔진은 `record.get("attempt_id", record.get("iteration"))`로 대체하는데, 레코드에는 `attempt_id`가 **없고** `iteration`만 있다(실측). 지금은 우연히 값이 겹쳐 동작하지만 두 개념은 다르며, 자동완료 게이트가 이 값에 걸리므로 **명시적 결정 없이 진행하면 안 된다**(§D2).
4. **지연 알림은 새 저장소를 만들지 않는다.** `state-transitions.md` §5가 "독립 Outbox DB 신설 금지"를 명시했고, 레코드 안 `pending_notification` 필드를 같은 CAS 트랜잭션에서 쓴다(§D4).
5. **자동완료 허용 백엔드는 실측 증거가 있는 것으로 한정한다.** Phase 0 능력 행렬 실측: 정지 상태(`idle`/`done`) 관측 증거가 있는 것은 **claude·grok(idle), codex(done)** 뿐이고 **agy·hermes·opencode는 없다**(§1-5). 플래그가 켜져도 이 셋 외에는 자동완료하지 않는다.
6. **664개 무회귀 + 신규.** Phase 2a와 동일하게 특성화 선행 → 구현 → 문서 순으로 커밋 5개.
---
## 1. Planner 사전 실측
### 1-1. 자동완료에 필요한 것 중 **존재하지 않는 것**
| 필요 | 현황 (실측) |
|---|---|
| 완료 매니페스트 | **없음.** 저장소 어디에도 매니페스트를 쓰거나 읽는 프로덕션 코드가 0건. 리포트 디렉터리에는 `report-final.md` 하나뿐 |
| 리포트 원자적 확정 | **없음.** 에이전트가 `report-final.md`를 직접 쓴다. tmp+rename 없음 |
| `attempt_id` 레코드 필드 | **없음.** 레코드에는 `iteration`만 존재 |
| `pending_notification` | **없음.** `grep` 0건 |
| `MAM_AUTO_COMPLETE` | **없음.** `grep` 0건 (참고: `MAM_ENGINE_CAS` 5건, `MAM_DELEGATION_PY` 4건은 존재) |
### 1-2. 이미 준비되어 있는 것 (Phase 2a 산출물)
| 있음 | 위치 |
|---|---|
| 단일 CAS 전이 경계 + 권한 축 | `lib_py/delegation/engine.py::transition` |
| `expected_attempt` fail-closed | 레코드가 attempt를 못 대면 거부 (Round 1 R2) |
| 관측 증거 **필수** 판정 | `lib_py/loop/policy.py` — 4식별자 + 매니페스트 `attempt_id` 부재 시 `hold` (Round 2 R1) |
| 매니페스트 미확정 시 `hold` | `policy.decide`의 `manifest_committed`/`hash_verified` 게이트 |
| `herdr agent wait` 래핑·백오프 | `lib_py/loop/watcher.py` |
| 쓰기 경로 없는 shadow 러너 | `lib_py/loop/shadow.py` |
| 지연 알림의 순서 보장 기반 | `transition_seq` + per-job 감사 락 (Round 2 R4) |
**즉 Phase 2b는 판정기를 새로 만드는 것이 아니라, 이미 fail-closed로 판정하고 있는 게이트에 "진짜 증거"를 공급하고 그 결과를 커밋에 연결하는 작업이다.**
### 1-3. `attempt_id` vs `iteration` — 실행으로 확인한 충돌
```
record keys with attempt semantics: {'iteration': 1}
transition(completed, expected_attempt=1) -> committed=True running -> completed
transition(completed, expected_attempt=2) -> committed=False stale attempt: expected 2, record has 1
```
엔진은 `attempt_id`가 없으면 `iteration`을 쓴다. 래퍼의 loop 흐름에서는 `redispatch`가 `iteration`을 증가시키므로 두 값이 우연히 일치하지만, `iteration`은 **루프 회차**이고 `attempt_id`는 **디스패치 시도**다. 직접(`--type direct`) 재디스패치나 크래시 후 재시도에서 갈라진다. 자동완료 게이트가 이 값에 걸리므로 §D2에서 명시적으로 결정한다.
### 1-4. 미지원 경로 보존의 실제 메커니즘
`job_subscriber._check_disk_fallback`(`:60-72`)은 레지스트리 status를 읽어 terminal이면 즉시 종료한다. 즉 **자동완료가 `completed`를 쓰면 래퍼는 명시 이벤트와 구별하지 못한다.** 이는 의도된 결합이지만, 동시에 "자동완료가 틀리면 래퍼가 조용히 잘못된 완료를 받는다"는 뜻이므로 §D6의 감사 표식이 필수다.
### 1-5. 자동완료 허용 백엔드 (Phase 0 능력 행렬 실측)
```
claude observed slots: ['idle']
agy observed slots: ['working', 'wait_timeout']
hermes observed slots: NONE
grok observed slots: ['idle']
opencode observed slots: NONE
codex observed slots: ['done']
```
자동완료는 **정지 상태 관측**을 전제로 한다. `idle`/`done` 증거가 있는 **claude·grok·codex**만 후보이며, `agy`는 `working`만 관측돼 정지 판정의 실측 근거가 없고, `hermes`·`opencode`는 관측 0건이다.
### 1-6. 에이전트 지시문 주입 지점 (조정 비용)
`create_session.sh:483`과 래퍼 `:202`/`:319`가 `publish_event.py --job <id>`를 지시문에 넣는다. 확정 선언 명령을 추가하려면 **이 두 곳만** 바꾸면 된다.
---
## 2. 설계 결정
### D1. 매니페스트는 **끝난 쪽이 선언한다** (P2B-01의 핵심)
```
에이전트: 작업 종료 시
publish_event.py --job <id> --finalize-report <path> [--side-effect <kind>=<evidence>] ...
① <path>.tmp 를 <path> 로 원자적 rename (이미 최종본이면 rename 생략)
② SHA-256 계산
③ <report_dir>/report-manifest.json 원자적 기록:
{ schema_version, job_id, attempt_id, report_path, sha256,
finalized_at, side_effects: [...], declared_by }
```
- **워처는 매니페스트를 만들지 않는다.** 만들면 자기 증명이 되어 Round 2 R1에서 기각된 형태가 된다. 워처는 **읽고 검증만** 한다(해시 재계산 후 대조).
- **미지원 에이전트는 아무것도 하지 않으면 된다** — 매니페스트가 없으면 `policy`가 이미 `hold`한다. P2B-03의 "explicit event 경로 100% 보존"이 **새 코드 없이** 성립한다.
- 리포트가 재작성되면 해시가 어긋나 매니페스트가 즉시 무효가 된다(§4 계약 그대로).
### D2. `attempt_id`를 레코드의 1급 필드로 승격 (결정 필요 사항)
**권고: 승격한다.** 근거:
- 엔진의 `expected_attempt`는 이미 "레코드가 attempt를 대지 못하면 거부"로 fail-closed다(Round 1 R2). 자동완료가 이 게이트를 통과하려면 레코드가 attempt를 대야 한다.
- `iteration` 대체는 우연한 일치에 의존한다. 두 개념이 갈라지는 순간 **CAS 가드가 조용히 무력화**된다.
구현:
- `register_job`이 `attempt_id: 1`을 기록. `engine`의 `redispatch`가 `iteration`과 함께 `attempt_id`를 증가.
- 엔진의 `record.get("attempt_id", record.get("iteration"))` 대체를 **제거**하고 `attempt_id`만 본다(대체는 의미 혼동의 원천).
- **스키마 영향**: 필드 추가이므로 기존 리더는 무시하면 되고 `SCHEMA_VERSION`은 1을 유지한다. 다만 Phase 1이 "레코드 필드 불변"을 계약으로 명시했으므로 **이 계획서가 그 계약의 변경을 명시적으로 요청**한다. 리뷰어 승인 없이 진행하지 않는다.
- 마이그레이션: `attempt_id`가 없는 기존 레코드는 `iteration` 값으로 1회 채운다(읽기 시 lazy, 쓰기는 다음 전이에서).
### D3. 자동완료 게이트 (기존 판정기에 증거를 공급)
`shadow.ShadowRunner`를 `AutoCompleteRunner`로 확장하되 **판정 로직은 손대지 않는다**. 순서:
1. `watcher.wait_once`로 정지 상태 관측 → `collector_attribution` 봉투에 4식별자를 채워 증거 구성.
2. `report-manifest.json` 읽기 → 해시 **재계산 후 대조**(매니페스트 자기 신고를 신뢰하지 않는다) → `report_manifest.attempt_id`를 증거에 포함.
3. `policy.decide` → `candidate_approved`가 아니면 종료(로그만).
4. `candidate_approved`면 **게이트 3중 확인 후** `engine.transition(job_id, "completed", expected_attempt=<attempt>, source="auto_complete")`.
- 게이트: 플래그 ON + 백엔드 허용목록(§1-5) + 잡별 opt-in.
5. 커밋 결과가 `committed=False`면 **아무 일도 없었던 것으로 처리**하고 감사에 기록(늦은 conflict는 엔진이 이미 거부한다 — 새 코드 불필요).
### D4. 지연 알림 (P2B-02) — 레코드 안 outbox
`state-transitions.md` §5가 **독립 Outbox DB 신설을 금지**했다. 따라서:
- `engine.transition`이 커밋할 때 같은 락 안에서 `pending_notification: {event, seq, timestamp, signature}`를 레코드에 **함께** 기록한다(추가 I/O 없음 — 이미 쓰는 레코드에 필드 하나).
- 락 해제 후 `notifier.flush(job_id)`가 MQTT 발행 → 성공 시 `pending_notification`을 지우는 **별도 CAS 전이**(`request="notification_settled"`, 상태 불변).
- **재시작 복구**: 기동 시 `pending_notification`이 남은 레코드를 스캔해 재발행. 멱등하다 — 구독자가 `seq`로 중복을 거른다(기존 replay 방어).
- **락 규율 유지**: 발행은 절대 락 안에서 하지 않는다(Phase 2a G5 테스트가 계속 감시).
### D5. 부수효과 증거 (P2B-01 후반)
- 레코드의 기존 `expected_artifacts`(이미 존재, `--artifact`로 설정)를 **선언된 부수효과 목록**으로 사용한다. 새 필드를 만들지 않는다.
- `expected_artifacts`가 비어 있지 않은 job은 매니페스트의 `side_effects`가 **모든 항목을 덮어야** 자동완료 후보가 된다. 하나라도 증거가 없으면 `hold`.
- 증거 형식은 `{kind, reference, verified_at}`이며, Phase 2b는 **존재와 대응만** 검증한다(원격 확인은 비범위 — 정직하게 명시).
### D6. 플래그와 감사 표식 (P2B-03)
| 스위치 | 기본 | 범위 |
|---|---|---|
| `MAM_AUTO_COMPLETE` | **`0` (OFF)** | 전역 킬 스위치. `1`이어야 자동완료가 가능 |
| 백엔드 허용목록 | `claude,grok,codex` | §1-5 실측 근거. `MAM_AUTO_COMPLETE_BACKENDS`로 좁힐 수만 있게(넓히려면 증거 필요) |
| 잡별 opt-in | 레코드 `auto_complete: true` | 셋 다 참일 때만 커밋 |
**감사 표식 필수**: 자동완료로 들어간 terminal은 `completed_by: "auto_complete"`와 판정 근거(매니페스트 해시, 관측 seq)를 감사 로그에 남긴다. §1-4에서 확인했듯 래퍼는 자동/명시를 구별하지 못하므로, **사후에 구별할 수 있는 유일한 수단**이다.
### D7. 무판정 fail-closed
정책이 예외를 던지거나 알 수 없는 결정을 반환하면 `hold`로 취급한다. 자동완료 경로 전체를 `try/except`로 감싸 **어떤 실패도 커밋으로 이어지지 않게** 한다. "판정 못 함"은 절대 "완료"가 아니다.
### D8. 트리·권한 규칙 승계
- `lib_py.loop`는 `lib_py.delegation` 외 형제 임포트 금지(Phase 2a G9).
- 자동완료의 `source`는 **`auto_complete`** 이며 운영자 권한이 **아니다** — terminal을 되돌릴 수 없다.
- `preexec_fn`: 알림 재발행기가 스레드를 쓰면 Phase 1 인계 게이트에 걸린다. **2b는 데몬을 스폰하지 않고** 기존 구독자 프로세스 안에서 flush한다. 스폰이 필요해지면 그때 `preexec_fn`을 교체한다.
---
## 3. 작업 분해 (WBS) — 커밋 5개
### P2B-00 특성화 선행 (커밋 1: `test(issue-5): phase 2b pre-conditions and fail-closed characterization`)
- 현행 고정: 매니페스트 없는 job은 `hold`(이미 참), `MAM_AUTO_COMPLETE` 부재 시 자동완료 0건, `attempt_id` 부재 시 `expected_attempt`가 거부, 미지원 백엔드 목록.
- **완료 기준**: 레거시에서 전부 통과, 664 + 신규 통과.
### P2B-01 확정 계약 (커밋 2: `feat(issue-5): report finalization manifest and side-effect evidence`)
- **파일**: `lib_py/loop/finalize.py`(매니페스트 작성·검증), `publish_event.py`에 `--finalize-report`/`--side-effect`, `create_session.sh:483`·래퍼 `:202/:319` 지시문 1줄 추가.
- **테스트**: tmp→rename 원자성, 해시 재계산 대조(위조 매니페스트 거부), 리포트 재작성 시 무효화, `expected_artifacts` 미충족 시 `hold`, 매니페스트 부재 시 `hold`(불변).
### P2B-02 CAS 연동 + 지연 알림 (커밋 3: `feat(issue-5): auto-complete gate and durable pending notification`)
- **파일**: `lib_py/loop/autocomplete.py`, `lib_py/delegation/notifier.py`, `engine`에 `pending_notification` 기록 및 `notification_settled` 요청.
- **테스트**: 게이트 3중 확인, 늦은 conflict 거부(엔진 기존 동작), 크래시 후 재시작 재발행, 중복 발행 멱등, **락 안 발행 0건**(Phase 2a G5 재사용), `attempt_id` 불일치 시 거부.
### P2B-03 플래그·허용목록 (커밋 4: `feat(issue-5): default-off auto-complete flag with an evidence-backed backend allowlist`)
- **파일**: 플래그 3종, `completed_by` 감사 표식.
- **테스트**: 기본 OFF에서 자동완료 0건이며 명시 경로 결과가 **바이트 동일**, 허용목록 밖 백엔드는 플래그 ON에서도 미커밋, 잡별 opt-in 미설정 시 미커밋, 자동완료 terminal에 `completed_by` 존재.
### P2B-04 시나리오·문서 (커밋 5: `docs(issue-5): phase 2b contracts, scenarios and task checklist`)
- 경쟁/재시작/부분 리포트/부수효과 미충족/무판정 시나리오를 Phase 0 스키마로 추가(기존 `validate_watcher_scenario` 통과 필수).
- `state-transitions.md` §4·§5 구현 매핑, `task.md` P2B-01~03 증거, 운영 노트(`phase2b-autocomplete.md`).
---
## 4. 게이트
| # | 조건 | 측정 |
|---|---|---|
| G1 | 기존 **664** 무회귀 + 신규 통과, skipped 0 | `pytest tests/ -q` |
| G2 | 셸 문법·공백 | `bash -n`, **범위** `git diff --check` |
| G3 | Python 3.9 컴파일 | `compileall` |
| **G4** | **기본 OFF에서 자동완료 0건** | 플래그 미설정 시 레지스트리 전후 해시 동일, 명시 경로 결과 바이트 동일 |
| **G5** | **매니페스트 위조 거부** | 해시 불일치·attempt 불일치·부재 전부 `hold` |
| G6 | 락 안 I/O 0건 | Phase 2a G5 감시 테스트 확장(발행 포함) |
| G7 | 재시작 복구 | 크래시 시뮬레이션 후 `pending_notification` 재발행 및 멱등 |
| G8 | 롤백 | `MAM_AUTO_COMPLETE=0` 즉시 중단, 이미 확정된 terminal은 보존 |
| G9 | 허용목록 | 증거 없는 백엔드는 플래그 ON에서도 미커밋 |
---
## 5. 롤백
1. **즉시**: `MAM_AUTO_COMPLETE=0`. 신규 자동완료만 중단되고 **이미 확정된 terminal 레코드는 보존**한다(`implementation_plan.md` Phase 2b 롤백 조건 그대로).
2. `MAM_ENGINE_CAS=0`은 Phase 2a 경로까지 함께 되돌린다(자동완료는 CAS 위에 있으므로 자동으로 무력화).
3. 커밋 단위 revert는 5→2 순. 커밋 1(특성화)은 남겨도 무해.
---
## 6. 리스크
| # | 리스크 | 완화 |
|---|---|---|
| R1 | 워처가 스스로 매니페스트를 만들어 자기 증명이 됨 | D1: 작성 주체를 에이전트로 고정, 워처는 해시 재계산 대조만 |
| R2 | `attempt_id`/`iteration` 혼동으로 CAS 가드 무력화 | D2: 승격 + 대체 제거. **리뷰어 승인 전 착수 금지** |
| R3 | 잘못된 자동완료를 래퍼가 구별 못 함 | D6 `completed_by` 감사 표식 + 기본 OFF + 허용목록 |
| R4 | 지연 알림이 새 저장소를 만들어 계약 위반 | D4: 레코드 내 필드, §5 명시 준수 |
| R5 | 알림 재발행기가 스레드를 써 `preexec_fn` 게이트에 걸림 | D8: 2b는 스폰 없음 |
| R6 | 부수효과 "검증"을 과대 주장 | D5: 존재·대응만 검증한다고 문서에 명시, 원격 확인은 비범위 |
---
## 7. 명시적 비범위
- `run_loop.sh` 파이썬화 — Phase 3.
- 부수효과의 **원격** 확인(실제 git push 도달 여부 등) — 증거 대응까지만.
- `agy`/`hermes`/`opencode` 자동완료 — 정지 상태 실측 증거 확보 후 별도 판단.
- `preexec_fn` 교체 — 스폰이 필요해지는 시점.
- 스키마 v2 — `attempt_id` 추가는 v1 유지(추가 필드).
---
## 8. Worker 인수인계 체크리스트
- [ ] **착수 전**: §D2(`attempt_id` 승격 = Phase 1 스키마 계약 변경)에 대한 **리뷰어 승인**을 받을 것
- [ ] P2B-00 커밋 1: 현행 fail-closed 특성화가 레거시에서 통과
- [ ] P2B-01 커밋 2: 매니페스트 작성/검증, 해시 재계산, 부수효과 대응
- [ ] P2B-02 커밋 3: 게이트 연동 + `pending_notification` + 재시작 복구
- [ ] P2B-03 커밋 4: 플래그 3종 + 허용목록 + `completed_by`
- [ ] P2B-04 커밋 5: 시나리오·문서
- [ ] 보고서: G1 원문, G4 해시 비교, G7 복구 로그, `grep -n` 인용
- [ ] 커밋 접두: `test/feat/feat/feat/docs(issue-5)`
---
## 부록 A. 계획 수립 시 실행한 검증 명령
```bash
git log --oneline -1 # 4a5916a
.venv/bin/python -m pytest tests/ --collect-only -q | tail -1 # 664
find .mam/jobs -name "*manifest*" # 없음
grep -rn "pending_notification\|MAM_AUTO_COMPLETE" --include='*.py' .agents # 0건
grep -n 'record.get("attempt_id", record.get("iteration"))' .../engine.py # 대체 확인
python -c "... transition(completed, expected_attempt=1|2) ..." # iteration 대체 실증
python -c "... herdr/manifest.json observed slots ..." # 백엔드 증거 행렬
grep -n "publish_event.py --job" create_session.sh 래퍼 # 지시문 주입 2곳
```
@@ -0,0 +1,35 @@
# 🛠️ Creator 수정 리포트 — codex R1(F2 실패 캐시) 반영 (job `5b2974f5`)
- **Author**: `creator-claude-01` (role: creator) · 2026-10-02
- **작업 트리**: `/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux-wt/followups` · `fix/followups-41-43` · `95eabc6` → **`75f364e`** (커밋 1개 추가, 미커밋 변경 없음, ignored 는 `.venv/` 뿐)
- **범위**: R1 수정 + 경미한 문서 권고 1건. push·merge·PR·버전 bump 없음. 실제 `.mam`(이 리포트 제외)·`.mam.env`(export 안 함)·세션·herdr·모니터 무조작.
## 1. 판단
R1 은 타당하다 — 반론 없음. `ensure_env_loaded()` 가 `_load_dotenv()` 전에 `_env_loaded = True` 를 세웠고, F2 의 `load_env_or_report()` 가 예외를 반환값으로 바꾸면서 같은 프로세스의 두 번째 호출이 깨진 파일을 건너뛰게 됐다. 리뷰어가 권한 방향(성공 뒤에만 캐시)을 그대로 택했다.
## 2. 변경 (`75f364e`)
- `.agents/skills/lib_py/delegation/mqtt_common.py` `ensure_env_loaded`: `_load_dotenv(workspace_dir)` **뒤에** `_env_loaded = True`. 실패는 다음 호출에서 다시 읽고, 성공은 전처럼 프로세스당 한 번. `envfile.apply` 는 파일 전체를 파싱한 뒤에 대입하므로 실패한 로드는 환경을 하나도 바꾸지 않는다(부분 적용 없음) — 재시도가 안전하다. 라이브러리 직접 호출(`ensure_env_loaded`)도 같은 규칙이 된다.
- `MESSAGING.md:369`(경미 권고): ERROR **한 줄**은 Python 진입점의 것이고, 래퍼는 그 줄 뒤에 `ERROR: cannot load <path> (see the line above)` 를 한 줄 더 찍는다고 정정.
- `tests/test_issue26_envfile.py::test_a1_a_failed_load_is_not_cached_as_loaded` — 한 프로세스에서 실제 `registry.main(['--registry-dir', <jobs>, 'register', '--prompt', …])` 를 깨진 UTF-8 파일로 두 번 호출하고 파일을 복구·변경하며 확인:
| 리뷰어 요구 | 단언 |
|---|---|
| (a) 연속 실패 두 번 모두 rc 1 | `rc == [1, 1]`, ERROR 줄이 두 번 |
| (d) 실패 중 등록 없음 | `registered == []` |
| (b) 복구 후 설정 적용 | `load_env_or_report()` → `[True, "from-file"]` |
| (c) 성공 후 once-per-process 유지 | 파일을 바꿔도 `[True, "from-file"]` |
## 3. 역검증
`git worktree add --detach <scratch>/head 95eabc6` 에 새 테스트 파일만 복사해 실행 → **실패**: `{'rc': [1, 0], 'registered': ['421e9769.json'], 'recovered': [True, None], 'cached': [True, None]}` (`assert [1, 0] == [1, 1]`). 리뷰어 탐침과 같은 결과다. 임시 워크트리는 제거했다(남은 워크트리: 본 체크아웃, followups, 그리고 내가 만들지 않은 `multi-agent-mux-wt/fu-suite` — 손대지 않음).
## 4. 테스트 (수정 후, 브리프 명령 형식, `.mam.env` export 없음)
`tests/test_issue26_envfile.py tests/test_issue5_phase1_delegation.py tests/test_tier1_unit.py tests/test_version_consistency.py tests/test_issue18_liveness_contract.py` → **205 passed in 178.52s** (envfile 38 · issue5 66 · tier1 67 · version 3 · issue18 31). issue5 의 `ensure_env_loaded` 멱등 단언(`:506-508`)도 통과. 바뀐 것은 env 로딩 캐시 한 곳뿐이라 나머지(F1·F3~F6) 파일은 다시 돌리지 않았다 — 직전 실행(`1e92ddc`/`95eabc6`) 결과와 리뷰어의 303 passed·52 passed 가 유효하다.
## 5. 위생
- `test_version_consistency` 가 기존부터 작업 트리에 `.mam/shim/herdr` 를 쓴다(직전 리포트에 보고한 base 동작). 내용이 그 심 하나뿐임을 확인하고 지웠다.
- scratchpad 경로를 가진 남은 프로세스 0개.
@@ -0,0 +1,140 @@
# 🛠️ Creator 리포트 — PR #41·#43 후속 F1~F6 (job `aa7f2b5f`)
- **Author**: `creator-claude-01` (role: creator) · 2026-10-02
- **작업 트리**: `/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux-wt/followups` · 브랜치 `fix/followups-41-43` · base `0051fd6` → head **`95eabc6`** (커밋 8개, 미커밋 변경 없음, ignored 는 `.venv/` 뿐)
- **범위 준수**: 본 체크아웃(`main @ 0051fd6`)은 읽기만 했다. push·merge·PR·이슈 변경 없음, 버전 bump 없음(4.8.1 그대로). #17 항목 4·#39·#40·#42 범위는 건드리지 않았다. 실제 `.mam`(이 리포트 파일 제외)·`.mam.env`(읽지도 출력하지도 않음)·모니터·에이전트 세션·herdr 서버는 손대지 않았고 `.mam.env` 는 export 하지 않았다(테스트는 conftest 의 로컬 브로커). basetemp·JUnit·로그·역검증용 임시 워크트리는 모두 작업 트리 밖 scratchpad 에 두었고 임시 워크트리는 제거했다.
## 1. 커밋
| 커밋 | 항목 | 요지 |
|---|---|---|
| `75936f1` | F1 | A8 이 마커 lstart 를 `loop_lock.sh` `mam_lstart` 와 같은 정규화(공백 압축·양끝 trim)로 기록. 두 칸 공백 `ps` 심 변형으로 날짜와 무관하게 고정. 제품 코드 무변경 |
| `5edf913` | F2 | `mqtt_common.load_env_or_report()` — publish_event·registry·job_subscriber·cli·bench·heartbeat·remote 의 main 이 `ERROR: <경로>: cannot read (<예외 종류>)` 한 줄 + rc 1. `ensure_env_loaded()` 는 여전히 예외(라이브러리는 exit 하지 않음) |
| `95eabc6` | F2 보정 | job_subscriber 는 종료 코드를 이름으로 돌려준다(`test_issue5` 스냅숏): `return RC_ERROR`(값 1 그대로) |
| `71ea809` | F3 | (a) 공통 파서를 `utf-8-sig` 로(BOM 제거, 두 로더 공통) (b) 중복 키 첫 값 우선을 `.mam.env.example` FORMAT·`envfile.py` 독스트링에 명시(동작 그대로) (c) `MESSAGING.md:369` 를 실제 동작(없으면 조용히 건너뜀·주변 탐색 안 함, 있는데 못 읽으면 `EnvFileError` → ERROR 한 줄 rc 1)으로 |
| `8b04639` | F4a·F4c | 러너 `_int_knob` = `_positive_int` 규칙 + 잘못된 값 경고 1회 후 기본값. loop SKILL.md 예산 행·하위 잡 문단에 `MAM_WAIT_GRACE_S` 와 정수 규칙 |
| `fb1b93c` | F4b | bash 노브 8개를 `mam_int_knob` 으로. `mam_int`/`mam_int_knob` 를 `lib_int.sh` 로 **그대로 이동**(lib.sh 가 source, lib.sh 없이 도는 `loop_lock.sh`·`diff_collect.sh` 는 함수가 없을 때 직접 source) |
| `c252ac4` | F5 | `stall_watch.py` 의 `MAM_TEST_UNRELIABLE_AGENT` 분기 삭제, S13 은 어댑터 seam 으로 |
| `1e92ddc` | F6 | delegate-job SKILL.md `<= 60 s` 를 herdr wait 에 한정, "대기 중 래퍼 소멸" 테스트를 두 번째 wait 안에서 소멸하도록 |
## 2. 항목별 내용과 완료 조건
### F1 — 날짜 의존 A8
- 원인: `ps -o lstart=` 는 한 자리 날짜를 `Oct 2` 로 두 칸 패딩한다. 제품 `mam_lstart` 는 `tr -s ' '` 로 줄여 비교하는데 A8 은 `.strip()` 만 한 원값을 기록 → 살아 있는 holder 가 stale 로 보여 두 번째 루프가 거부되지 않음(매달 1~9일).
- 수정(`tests/test_issue21_acceptance.py`): `_marker_lstart()` 가 `" ".join(out.split())`(= `tr -s ' '` + trim)로 기록. `@pytest.mark.parametrize("ps", ["real", "padded"])` — `padded` 는 PATH 앞의 `ps` 심이 lstart 요청에 항상 `Thu Oct 1 08:02:03 2026` 을 돌려주므로 **날짜와 무관하게** 두 칸 공백 경로를 지난다(심이 실제로 쓰였는지 `Thu Oct 1 …` 로 확인).
- 같은 패턴 조사: 살아 있는 lstart 를 마커에 쓰는 테스트는 `test_o3_scoped_guard._get_lstart`(이미 `" ".join(split())`)뿐. `test_o2_race_free_lock` 의 마커는 고정된 stale 값이고, 그 파일의 `get_lstart()` 는 **정의만 있고 쓰이지 않는다**(죽은 코드 — 손대지 않음). 제품 쪽 다른 소비자: `loop_delegation_guard.sh` 는 양쪽을 split-join, `lib.sh` 의 `ps -o pid=,lstart=` 는 `strptime` 이라 두 칸에 무관.
### F2 — Python 진입점의 EnvFileError
- `mqtt_common.load_env_or_report() -> bool`: `ensure_env_loaded()` 를 부르고 `EnvFileError` 면 `print(f"ERROR: {e}", file=sys.stderr)` 후 False. 각 main 은 `if not …: return 1`(job_subscriber 는 `RC_ERROR`). 메시지는 `envfile` 의 `"{path}: cannot read ({type})"` 그대로라 값·내용이 들어가지 않는다.
- 범위: 브리프가 든 7개 main. **reconcile.sh 의 임베디드 구독자**도 `ensure_env_loaded()` 를 부르지만 main 이 아니라 목록 밖이라 그대로 두었다(트레이스백 유지) — 필요하면 후속.
- 리뷰어 참고: job_subscriber 의 rc 1 은 원래 "감시한 잡이 error 로 끝남"(`RC_ERROR`)과 같은 값이다. 수정 전에도 트레이스백으로 rc 1 이었으므로 값은 바뀌지 않았고, 래퍼는 같은 파일을 먼저 읽고 스스로 rc 1 로 끝나 이 구독자를 띄우지 않는다. 별도 코드(예: 3 fatal)로 바꾸는 것은 계약 변경이라 하지 않았다.
### F3 — .mam.env 세부
- (a) `envfile.parse` 가 `encoding="utf-8-sig"` — 파일 맨 앞 BOM 만 벗기며, 래퍼(`envfile.py --shell`)와 `mqtt_common` 이 같은 함수를 쓰므로 두 로더 공통.
- (b) `apply()` 가 이미 있는 키를 건너뛰므로 첫 값이 이긴다(동작 무변경) — FORMAT 절에 `a key given twice keeps its FIRST value` 와 BOM 규칙 추가.
- (c) MESSAGING 2번 항목을 실제로: 명시 파일이 없으면 조용히 건너뛰고 주변 탐색을 하지 않는다(환경변수와 기본값으로 동작), 있는데 못 읽으면 `EnvFileError` → ERROR 한 줄 rc 1. 기존 문장의 "error is logged"·"fail-closed (`RuntimeError`)" 는 코드에 근거가 없어 지웠다.
- 참고(범위 밖, 손대지 않음): 같은 블록 3번 항목의 탐색 순서(`MAM_REAL_ROOT`·`WORKSPACE_ROOT`·cwd)는 `mqtt_common._load_dotenv`(모듈 위치에서 위로 `.agents`/`.git` 탐색)와 다르다.
### F4 — 정수 노브
- (a) `runner._int_knob(name, minimum)` → None(미설정·잘못된 값, 후자는 노브당 경고 1회) 이면 호출부 기본값. 최솟값과 근거(`tests/test_issue26_ints.py` `RUNNER_INT_KNOBS`):
| 노브 | 최솟값 | 기본 | 근거 |
|---|---|---|---|
| `MAM_WAIT_GRACE_S` | 0 | 300 | 0 = 예산만큼만 대기 |
| `MAM_CHILD_WAIT_S` | 0 | 예산 + grace | 0 = 하위 잡을 한 번만 확인(test_issue34 가 0 사용) |
| `MAM_JOB_TREE_MAX` | 1 | 50 | 0 은 모든 트리를 "over" 로 만든다; 기다리지 않기는 `MAM_CHILD_WAIT_S=0` |
동작 변화: `MAM_CHILD_WAIT_S` 는 전에 `float()` 이라 `0.5`·`1e3` 을 받았고 `abc` 는 ValueError, `MAM_JOB_TREE_MAX` 는 `abc`·빈 값이 ValueError, `MAM_WAIT_GRACE_S` 는 `" 30 "` 도 조용히 300 이었다 → 이제 모두 10진 정수 규칙(경고 후 기본값).
- (b) bash 노브(`INT_KNOBS` 에 추가, `NOT_ARITHMETIC` 에서 제거):
| 노브 | 위치 | 최솟값 | 기본 | 근거 |
|---|---|---|---|---|
| `MAM_READY_EMPTY_GIVEUP` | lib.sh `wait_for_tui_ready` | 1 | 5 | 0 은 1 과 같게 동작 |
| `SKS_EMPTY_GIVEUP` | lib.sh `_pane_quiescent` | 1 | 3 | 같음 |
| `SKS_IDLE_RETRIES` | lib.sh `wait_for_agent_idle` | 0 | 2 | 0 = 재시도 없음 |
| `SKS_IDLE_RETRY_BACKOFF_S` | 같음(sleep) | 0 | 10 | test_issue6 가 0 사용; 소수 사용처 없음 |
| `MAM_LOCK_STEAL_RETRIES` | loop_lock.sh | 0 | 3 | 0 = 한 번 시도 |
| `MAM_DIFF_MAX_BYTES`/`_LINES` | diff_collect.sh | 1 | 200000/4000 | 0 은 모든 diff 를 자름 |
| `RECONCILE_POLL_INTERVAL` | reconcile.sh(sleep) | 1 | 15 | 0 은 바쁜 루프; 소수 사용처 없음 |
`SKS_QUIESCENT_INTERVAL` 은 **기본값이 0.5 초**라 소수가 실제 의미 → 그대로 두고 `NOT_ARITHMETIC` 에 "sleep, fractional by default (0.5) - left raw" 로 사유를 남겼다.
- `lib_int.sh` 를 만든 이유: `diff_collect.sh` 는 Python 러너가 lib.sh 없이 `source` 하고(`runner.collect_changes_diff`), `loop_lock.sh` 도 테스트가 단독 source 한다. lib.sh 를 source 하면 herdr 심 설치 등 부작용이 있어 함수만 분리했다. 함수 본문은 한 글자도 바꾸지 않았다. 연쇄 변경: `deploy/remove.sh` 의 매니페스트 없는 폴백 목록에 `lib_int.sh` 추가(설치는 `.agents/skills` 의 모든 파일을 복사하므로 그대로 배포됨), `test_issue21_loop_b::l15` 가 가짜 제어 루트에 `diff_collect.sh` 만 두던 것을 `lib_int.sh` 도 함께 두게.
- (c) loop SKILL.md: 예산 행에 `MAM_WAIT_GRACE_S`(기본 300, 0 이상, 잘못된 값 경고 후 300, 덮는 꼬리 설명), 하위 잡 문단의 `MAM_CHILD_WAIT_S` 기본을 "예산 + `MAM_WAIT_GRACE_S`", 0 의 의미, `MAM_JOB_TREE_MAX` 1 이상, 정수 규칙.
### F5 — 제품 코드의 테스트 훅
- `StallWatch.__init__` 의 `MAM_TEST_UNRELIABLE_AGENT` 두 줄 삭제(이제 `.agents/skills` 전체에 `MAM_TEST_` 없음).
- S13: `_watch(..., unreliable=True)` 가 `python -c _UNRELIABLE_MAIN claude <args>` 로 실제 `stall_watch.main()` 을 실행하되, 그 프로세스에서 `type(get_adapter("claude")).agent_status_reliable = property(lambda self: False)`. 검증 내용은 그대로(5 초 동안 idle 알림·nudge 없음 → blocked 알림 `stalled:blocked Do you want to proceed?` → 로그 `idle judgement off for claude`).
### F6 — 문서 정밀도와 "대기 중 래퍼 소멸"
- SKILL.md: "한 herdr wait(<= 60 s) — 또는 알림 발행 중에 래퍼가 사라지면 그 발행이 끝날 때까지" 로 한정.
- 테스트: `_during_notice` 에 `in_wait(tick)` 훅(각 가짜 herdr wait 안에서 호출). 래퍼는 **두 번째 wait 안에서** 사라지고, 테스트는 `ticks == [1, 2]`(두 번째 wait 에 실제로 들어감)와 그때까지 alive 가 참이었음을 확인한 뒤 알림·키 0 을 단언한다.
## 3. 회귀 테스트가 수정 전 코드에서 실패함을 확인한 방법
`git worktree add --detach <scratch>/base 0051fd6`(작업 트리 밖)에 새 테스트 파일을 복사해 돌리고, 확인 후 `git checkout` 으로 되돌렸다. 마지막에 `git worktree remove --force` 로 제거(남은 워크트리 2개: 본 체크아웃·followups).
| 항목 | base(0051fd6)에서 | 수정 후 |
|---|---|---|
| F1 | 원래 A8: **실패**(오늘 10월 2일, `already running` 없음). 새 테스트에서 `_marker_lstart` 를 옛 `.strip()` 으로 되돌리면 `real`·`padded` **둘 다 실패** — `padded` 는 날짜와 무관 | 2 passed |
| F2 | 14 케이스(7 진입점 × 000 권한·UTF-8 깨짐) **14 실패**(트레이스백) | 14 passed |
| F3 | A7 3개 **3 실패**: BOM 이 `FIRST` 를 버림 / FORMAT 문구 없음 / MESSAGING 의 옛 문장 | 3 passed |
| F4a | 새 케이스 중 **15 실패**: grace 의 잘못된 값 6(경고 없이 300, `" 30 "` 은 300), child-wait `abc`·`-5`·`0.5`·`9999999999` 4(ValueError 또는 받아들임), tree-max `0`·`abc`·`-1`·빈 값 4(ValueError 또는 0 수용), 정적 검사 1. 통과한 14 는 결과가 같은 유효 값 | 44 passed |
| F4b | **14 실패**: 표 정적 검사 2, lib.sh 없이 source 한 스크립트 11(`abc`·`0900`·`" 7 "`·`-1`·`1.5`, diff 는 `0` 도), `_pane_quiescent` + `SKS_EMPTY_GIVEUP=abc`(`[` 오류) 1. 통과 3 은 유효 값 | 통과 |
| F5 | 정적 검사(`MAM_TEST_` 없음) **실패**. 추가로 수정 후 트리에서 seam 을 빼면(`unreliable=True` 제거) S13 이 **실패** → seam 이 unreliable 상황을 만든다는 증거 | 2 passed |
| F6 | 테스트만 바뀐 항목이라 두 가지로 확인: (1) 새 테스트에 옛 호출 횟수 대역을 넣으면 `assert [1] == [1, 2]` 로 **실패** — 옛 테스트는 두 번째 wait 에 들어가지도 않고 루프 머리에서 끝났다. (2) 제품의 wait 직후 `_wrapper_gone()` 검사를 지운 변이체에서 새 테스트가 `notes == ['stalled:idle']` 로 **실패**(수정 안 한 제품에서는 통과) | 1 passed |
## 4. 테스트 결과
명령(브리프 그대로, `.mam.env` export 없음):
`AGENT_PYTHON_BIN=<wt>/.venv/bin/python PYTHONDONTWRITEBYTECODE=1 <wt>/.venv/bin/python -m pytest -p no:cacheprovider -q --basetemp=<scratch>/bt-final --junitxml=<scratch>/final.xml <파일들>`
최종 실행 @ `1e92ddc` — **605 passed, 1 failed, 2 skipped (885 s)**. 실패 1건은 내 F2 회귀였다(`test_issue5_phase1_delegation::test_job_subscriber_cli_contract_snapshot` — job_subscriber 의 맨 숫자 `return 1`). `95eabc6` 로 고친 뒤 `test_issue5_phase1_delegation.py` + `test_issue26_envfile.py` 재실행 **103 passed**. `95eabc6` 의 변경은 같은 값(1)을 이름(`RC_ERROR`)으로 바꾼 것뿐이고 그 분기는 env 파일 실패에서만 탄다.
| 파일 | 통과 | 실패 | 스킵 |
|---|---|---|---|
| test_issue26_envfile.py | 37 | 0 | 0 |
| test_issue26_ints.py | 93 | 0 | 0 |
| test_issue21_acceptance.py | 10 | 0 | 0 |
| test_issue30_stall_watch.py | 48 | 0 | 1 (`/proc` 전용) |
| test_issue30_stall_watch_stop.py | 11 | 0 | 0 |
| test_tier1_unit.py | 67 | 0 | 0 |
| test_version_consistency.py | 3 | 0 | 0 |
| test_issue33_budget.py | 20 | 0 | 0 |
| test_issue34_job_tree.py | 20 | 0 | 0 |
| test_issue21_loop_b.py | 34 | 0 | 0 |
| test_issue5_phase1_delegation.py | 65 → **재실행 66** | 1 → **0** | 0 |
| test_issue18_liveness_contract.py | 31 | 0 | 0 |
| test_o2_race_free_lock.py | 22 | 0 | 0 |
| test_o3_scoped_guard.py | 32 | 0 | 0 |
| test_b7_diff_untracked.py | 20 | 0 | 0 |
| test_issue36_prompt_transport.py | 23 | 0 | 1 (Linux `MAX_ARG_STRLEN`) |
| test_issue6_turn_handshake.py | 14 | 0 | 0 |
| test_c1_tui_readiness.py | 23 | 0 | 0 |
| test_b19_headless_reconcile_fixes.py | 16 | 0 | 0 |
| test_issue19_subscriber_daemon_lifecycle.py | 16 | 0 | 0 |
브리프 지정 7개 파일 + 바꾼 모듈의 테스트(러너: issue33/34·loop_b, env/진입점: issue5·issue18, bash 노브: o2·o3·b7·issue36·issue6·c1·b19·issue19). 전체 스위트(~60분)는 돌리지 않았다(오케스트레이터 몫). 정적 검사: `bash -n` 으로 바꾼 셸 파일 6개 문법 OK; `shellcheck`·`pyflakes` 는 이 호스트에 없다.
## 5. 위생
- 작업 트리: 최종 `git status --short --ignored` = `!! .venv/` 만. 단, 최종 실행 중 **`.mam/shim/herdr` 가 작업 트리에 생겼다** → 파일별로 나눠 돌려 원인을 찾았다: `tests/test_version_consistency.py::_get_lib_sh_mam_version` 이 `WORKSPACE_ROOT` 없이 `lib.sh` 를 source → `_init_herdr_isolation` 이 `<저장소>/.mam/shim/herdr` 를 쓴다. **base 에서도 똑같이 생긴다**(내 변경과 무관, 기존 동작). 내용이 재생성되는 심 하나뿐임을 확인하고 지웠다. ⚠️ 본 체크아웃에서 이 테스트를 돌리면 **실제 `.mam/shim/herdr` 를 덮어쓴다** — 후속 후보(테스트가 `WORKSPACE_ROOT` 를 샌드박스로 주기).
- 프로세스: 내 F5 확인(seam 을 일부러 뺀 S13 실패 실행)에서 **샌드박스 stall_watch 1개가 남았다**(S13 은 단언 실패 시 `finally` 에서 에이전트만 죽이고 watcher `w` 는 정리하지 않음 — 기존 테스트 구조). 그 watcher 는 basetemp 의 mock herdr·레지스트리만 상대했다. TERM 으로 종료했고, 이후 scratchpad 경로를 가진 프로세스 0개. 실제 모니터 데몬·세션은 건드리지 않았다(남은 `-m lib_py.loop` 1개는 오케스트레이터의 루프 드라이버).
- 실제 `.mam/jobs` 의 레코드는 읽기·쓰기 하지 않았다(이 리포트 파일만 작성).
## 6. 리뷰어 참고
- `lib.sh` 변경은 `mam_int`/`mam_int_knob` 블록을 `lib_int.sh` 로 옮기고 그 자리에서 `source "$(dirname "${BASH_SOURCE[0]}")/lib_int.sh"`. 생성되는 herdr 심(heredoc, 151–1367행)은 `mam_int` 를 쓰지 않는다.
- `local x="$(mam_int_knob …)"` 형태는 B5 정적 검사 정규식(`mam_int_knob NAME default min)`)이 잡도록 기존 호출부 모양을 따랐다. B5 가 이제 래퍼와 **모든** `.sh` 를 읽는다.
- 메모: 오래된 `.mam.env` export 지침(공개 브로커 시절)은 이 트리에서 틀리다 — conftest 가 세션 로컬 브로커를 띄우고 인증 변수를 지운다.
## 7. 교차 확인 명령
```
cd /Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux-wt/followups
git log --oneline 0051fd6..HEAD # 8 commits, head 95eabc6
git diff --stat 0051fd6..HEAD
grep -rn MAM_TEST_ .agents/skills # nothing
AGENT_PYTHON_BIN=$PWD/.venv/bin/python PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m pytest -p no:cacheprovider -q \
--basetemp=/tmp/<somewhere> tests/test_issue26_envfile.py tests/test_issue26_ints.py tests/test_issue21_acceptance.py \
tests/test_issue30_stall_watch.py tests/test_issue30_stall_watch_stop.py tests/test_tier1_unit.py tests/test_version_consistency.py
```
@@ -0,0 +1,100 @@
# Deploy / install verification — v3.0.0
- **Date**: 2026-08-26
- **Verifier**: `creator-grok-01` (jobs `c9275b44`, `16201e43`, `61299e40`)
- **Source tree**: `/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux` (working copy used as `MAM_REPO_URL`)
- **Installer under test**: `deploy/install.sh` (same path as `tests/test_deploy_*.py` and `update.sh`)
- **Sandbox (first)**: `/tmp/mam-v3-verify.o0ocAX`
- **Sandbox (re-run 16201e43)**: `/tmp/mam-v3-verify2.7RCtR7` (clean dir, `MAM_SKIP_VENV=1`; removed after hash check)
---
## 1. Installer surface
| Artifact | Role |
| :--- | :--- |
| `deploy/INSTALL.md` | User guide. Documents `deploy/install_mam.sh --target …`. Installed copy is `.agents/INSTALL.md`. |
| `deploy/install.sh` | Production installer used by tests, `update.sh`, and `MAM_REPO_URL` staging. Copies `.agents/**` (except reports/references), `AGENTS.md`, hooks, skills. |
| `deploy/update.sh` | Installed as `.mam_deploy/update.sh`. Backs up `.mam.env` / `.mam` then re-runs install. |
| `deploy/install_mam.sh` | Alternate rsync installer from a local clone (`SRC_DIR` = parent of `deploy/`). Same ownership rules. |
Both installers pull from the clone they are run from when `MAM_REPO_URL` is a directory (`install.sh`) or when invoked as `install_mam.sh` from that clone. This verification used `install.sh` against the working tree so the installed bits are this v3.0.0 checkout, not `main` on the remote.
---
## 2. Sandbox install — skill versions
`bash deploy/install.sh <sandbox>` completed 0.
All **8** `SKILL.md` files in the sandbox:
| Skill | Installed `version` |
| :--- | :--- |
| `multi-agent-mux-create` | `3.0.0` |
| `multi-agent-mux-stop` | `3.0.0` |
| `multi-agent-mux-resume` | `3.0.0` |
| `multi-agent-mux-status` | `3.0.0` |
| `multi-agent-mux-monitor` | `3.0.0` |
| `multi-agent-mux-delegate-job` | `3.0.0` |
| `multi-agent-mux-loop` | `3.0.0` |
| `multi-agent-mux-orc-onboard` | `3.0.0` |
Matches `VERSIONS.md` skill matrix (`v3.0.0`).
---
## 3. Framework assets and v3 payloads
Present in the sandbox and **SHA-256 identical** to the source tree:
| Installed path | Source | SHA prefix |
| :--- | :--- | :--- |
| `.agents/hooks.json` | same | `fc730f18fd9ecc53` |
| `.agents/hooks/loop_delegation_guard.sh` | same | `9896c63ffbd6fb00` |
| `.agents/MULTI_AGENT_RULES.md` | same | `a5e31712c5cadaac` |
| `.agents/INSTALL.md` | `deploy/INSTALL.md` | `26ec7eaf2cc050a7` |
| `AGENTS.md` | same | `91acdf00a537e326` |
| `.agents/skills/lib.sh` | same | `d884bb839e0a6336` |
| `.agents/skills/lib_py/layout.py` | same | `a06d25e660c65084` |
| `.agents/skills/lib_py/agents/adapters/grok.py` | same | `33113671c456437e` |
| `.agents/skills/lib_py/agents/registry.py` | same | `ec2d169e0a0e6690` |
| `.agents/skills/multi-agent-mux-loop/scripts/run_loop.sh` | same | `25c405cd88f1fc19` |
Also present: `.agents/MULTI_AGENT_RULES.ko.md`. Adapters dir: `claude.py`, `agy.py`, `hermes.py`, `cline.py`, `grok.py`.
v3 behavior on the installed copies:
- **Loop CLI**: `--creator)` parser; `--target-agent` only as the removal error. `SKILL.md` and `.agents/INSTALL.md` examples use `--creator`. No leftover `--target-agent` in installed skills except that error handler.
- **Layout 2.0**: `_decide` / `_decide_headless`, `new_column_right`, `max_rows` default 2.
- **Grok**: `GrokAgentAdapter` registered in `registry.py`.
---
## 4. Automated tests
```text
pytest tests/test_deploy_freshness.py tests/test_deploy_layout.py tests/test_loop_cli.py
45 passed in 40.56s
```
- `test_deploy_freshness.py`: non-skill assets refresh, ownership, NATS/docs guards.
- `test_deploy_layout.py`: install layout, `.mam_deploy`, gitignore block.
- `test_loop_cli.py`: `--creator` / `--planner` / `--target-agent` rejection.
---
## 5. Gaps / notes (not install failures)
1. **Two installers.** User-facing `INSTALL.md` tells people to run `install_mam.sh`. CI and `update.sh` use `install.sh`. Both installed v3.0.0 from this tree; operators should know which command they ran.
2. **Remote vs working tree.** Default `MAM_REPO_URL` is `https://git.godopu.com/tmpl/multi-agent-mux.git`. This check used the local working copy. A clean install from the remote is v3.0.0 only after that remote is tagged/pushed.
3. **`--target-agent` string** remains in `run_loop.sh` as the dedicated rejection path (Rev.4). That is required, not a leak.
---
## 6. Verdict
**PASS.** A clean `deploy/install.sh` into an empty directory installs all eight skills at `version: 3.0.0`, copies hooks / MULTI_AGENT_RULES / INSTALL / lib_py (Grok + layout 2.0) byte-identical to this tree, and the three requested test modules are green.
Re-run job `16201e43`: second clean install still 8× `version: 3.0.0`, all listed assets MATCH, `pytest` **45 passed in 44.34s**. Verdict unchanged.
Re-run job `61299e40`: third clean install 8× `3.0.0`, listed assets MATCH, `pytest` **45 passed in 43.76s**. Verdict unchanged.
+454
View File
@@ -0,0 +1,454 @@
# 🔌 Implementation Plan: Codex CLI (`openai/codex`) Agent Adapter for MAM (Rev.2)
- **Author**: `planner-reviewer-claude-01` (Planner), refined in response to `creator-agy-01`'s architectural challenge
- **Job**: `e30e3123` → Rev.2 (`94a6db78`)
- **Status**: Implemented (v4.2.0) — **full code, tests, and version lockstep present in repo**.
- **Scope**: Add `codex` as a 6th first-class MAM agent backend (alongside `claude`, `agy`, `hermes`, `grok`, `opencode`), per `docs/NEW_AGENT_INTEGRATION_GUIDE.md`'s 5-step procedure.
- **Durable Path**: `.agents/reports/planner-reviewer-claude-01/plan-e30e3123.md` (mirrored at `.agents/reports/implementation_plan.md`).
- **Method**: Every CLI fact is verified against a **live, authenticated Codex CLI install already present on this machine** (`codex-cli 0.153.4`). Rev.2 additionally re-verified both of `creator-agy-01`'s challenge points live before accepting them — see §0.
---
## 0. Rev.2 Changelog — Response to `creator-agy-01`'s Architectural Challenge (Job `004c224d`)
`creator-agy-01` filed a formal challenge against Rev.1 with **1 critical defect + 1 supporting architectural constraint**. Per this session's standing discipline, neither was accepted on the challenger's word alone — both were independently re-verified live on this machine before being incorporated. **Both are accepted — no `[REBUT:]` filed.**
| # | Challenge | My independent verification | Disposition |
|---|---|---|---|
| 1 | **Critical**: Rev.1's `orc_onboard.sh` detection regex (`resume[[:space:]]+[0-9a-f-]{36}`) cannot match the actual command Rev.1 itself specifies (`codex resume --dangerously-bypass-approvals-and-sandbox <uuid>`), because the flag sits between `resume` and the UUID | Ran the exact `cmd_line` from the challenge through Rev.1's regex myself: `echo "$cmd_line" \| grep -oE 'resume[[:space:]]+[0-9a-f-]{36}'` → **empty, exit 1**. Confirmed genuine — Rev.1 contained a self-contradiction between §2 (`resume_spec`) and §1.9/§3 item 27 (the detection regex). Then tested the challenge's proposed Plan A regex on the same input → **correctly extracts the UUID, exit 0**. | **Accepted.** §1.9 and wiring item #27 rewritten to the flag-tolerant regex (verified working, not just proposed) |
| 2 | **Supporting**: `~/.codex/state_N.sqlite` (a `threads` table indexing `id`/`cwd`/`rollout_path`) exists alongside the rollout JSONL files; Rev.1's "single-file format, no DB rows to delete" claim was only half true, and `purge_artifacts()` deleting only the `.jsonl` would leave an orphan DB row | `ls ~/.codex/*.sqlite*` on this machine → confirmed `state_5.sqlite` exists. `sqlite3 ~/.codex/state_5.sqlite ".schema threads"` → confirmed the exact `threads` table the challenge quoted. `sqlite3 ... "SELECT id,cwd,rollout_path FROM threads"` → confirmed 2 real rows exactly matching the 2 real rollout files found earlier. `strings` re-extraction confirmed the `stale_db_path`/`state db discrepancy`/`reconcile_rollout`/`read_repair_rollout_path: upsert_needed` literals the challenge cited. `codex delete --help` → confirmed `codex delete <SESSION> --force` ("Delete without prompting. SESSION must be a UUID") is real, exactly as the challenge's remediation option 1 proposed. | **Accepted**, with one refinement found during my own re-verification (not in the original challenge): `codex debug --help` has **no** `db path`-style introspection subcommand (unlike OpenCode's `opencode db path`), and the state file's numeric suffix (`state_5`) is unverified as stable across Codex versions/installs — hardcoding `state_5.sqlite` the way the challenge's raw example does would itself be fragile. §2's adapter design now resolves the state DB via a `state_*.sqlite` glob (most-recently-modified), and `purge_artifacts()` now shells out to `codex delete <uuid> --force` as the primary mechanism (letting Codex's own reconciliation logic keep the JSONL and DB consistent) with a manual-file-removal fallback only if that call fails |
Net effect: Rev.1's overall architecture and the 46-point wiring table stand — this challenge caught one genuine self-contradiction (the regex) and one genuine completeness gap (the state DB), both now closed. No other part of Rev.1 was found wrong during this re-verification pass.
---
## 1. Verified Codex CLI/Runtime Facts
Source: live `codex --help` / `codex resume --help` / `codex exec --help` / `codex login --help` / `codex delete --help` / `codex debug --help` / `codex doctor --summary` / `codex login status` output, direct `ls`/`find` of `~/.codex/`, live `sqlite3` schema/row inspection of `~/.codex/state_5.sqlite`, and offline `strings` extraction of the installed binary — all run on this machine.
### 1.1 Identity & Install
- Binary: `codex` (this machine: `/Users/godopu16/.local/bin/codex`, version `codex-cli 0.153.4`).
- Config/state root: `~/.codex/` by default, **overridable via the `CODEX_HOME` environment variable** (confirmed: `codex exec --ignore-user-config` help text explicitly says "auth still uses `CODEX_HOME`").
### 1.2 Execution Modes
- `codex [OPTIONS] [PROMPT]` — launches the **interactive TUI** (default, what MAM spawns).
- `codex exec [OPTIONS] [PROMPT]` (alias `e`) — **non-interactive** one-shot execution with `--json` JSONL event streaming and `-o/--output-last-message <FILE>`. Not used by MAM's spawn/resume flow, but confirms Codex has a scriptable mode.
- `codex resume [OPTIONS] [SESSION_ID] [PROMPT]` — resumes a specific session by **UUID or session name, passed positionally**; `--last` picks the most recent session without a picker.
- `codex delete <SESSION> --force` — permanently deletes a saved session by UUID; `--force` skips the confirmation prompt and requires `SESSION` to be a UUID (not a name). Verified via `codex delete --help`.
### 1.3 Relevant CLI Flags & Environment
| Flag / Variable | Purpose | Verified via |
|---|---|---|
| `--dangerously-bypass-approvals-and-sandbox` | Skip all confirmation prompts and run without sandboxing — the unattended-automation flag | `codex --help`, `codex resume --help` (accepted on both) |
| `-s, --sandbox <read-only\|workspace-write\|danger-full-access>` / `-a, --ask-for-approval <on-request\|never>` | Finer-grained alternative to the single bypass flag above | `codex --help` |
| `--approve-for-me` | Routes approvals through automatic review under `workspace-write` — **not** a full bypass | `codex --help` |
| `-C, --cd <DIR>` | Working-root directory for the agent | `codex --help` |
| `--session-id <uuid>` | **Does not exist.** No such flag appears anywhere in `codex --help`'s full option list | Absence confirmed by reading the complete `--help` output |
| `CODEX_HOME` | Overrides `~/.codex` config/session root | `codex exec --ignore-user-config` help text |
| `OPENAI_API_KEY` | Read by `codex login --with-api-key` (via stdin); also stored inside `auth.json` under the `OPENAI_API_KEY` key once logged in | `codex login --help`, `~/.codex/auth.json` key inspection |
### 1.4 Unattended-Execution Decision
Confirmed present. `--dangerously-bypass-approvals-and-sandbox` is accepted by both the top-level `codex` TUI launcher and `codex resume`, so `spawn_spec()`/`resume_spec()` can pass it unconditionally.
### 1.5 Session & Artifact Storage — Dual Layer (Rev.2: corrected)
- **Primary transcript**: JSONL "rollout" files, one per session, at `~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-<timestamp>-<uuid>.jsonl` — e.g. `~/.codex/sessions/2026/05/23/rollout-2026-05-23T08-23-56-019e5200-ab6a-70f2-b5da-e1ef403f7a40.jsonl`. First line is a `session_meta` record: `{"payload": {"id": "<uuid>", "cwd": "<path>", ...}}`.
- **Secondary index (Rev.2, per the accepted challenge)**: `~/.codex/state_N.sqlite` (this machine: `state_5.sqlite`; **the numeric suffix is not assumed stable** — no `codex debug`/`codex` subcommand introspects its exact filename, unlike OpenCode's `opencode db path`, so the adapter must resolve it via a `state_*.sqlite` glob rather than hardcoding the suffix). Verified live schema: a `threads` table with `id TEXT PRIMARY KEY`, `rollout_path TEXT`, `cwd TEXT`, `created_at`/`updated_at` (plus many version-added trailing columns — the schema has clearly evolved via in-place `ALTER TABLE` across releases, another reason not to hand-roll fragile column-position assumptions). Verified live rows: both real sessions on this machine are indexed here with `id`/`cwd`/`rollout_path` exactly matching their on-disk `.jsonl` files.
- **Codex's own resolution order** (inferred from binary string literals `state db discrepancy during find_thread_path_by_id_str_in_subdir: stale_db_path / mismatched_db_path / falling_back` and `reconcile_rollout` / `read_repair_rollout_path: upsert_needed`): Codex itself queries the state DB first, and has a **self-healing reconciliation path** for when the DB and filesystem disagree (falls back to a filesystem scan, then repairs the DB entry) — this is Codex's own built-in drift-correction, structurally analogous to MAM's own `reconcile.sh`.
- **Architectural consequence for MAM's adapter**: mirror Codex's own resolution order — **query `state_*.sqlite` first** (fast, indexed, avoids any unbounded directory walk), **fall back to the bounded glob** over `sessions/*/*/*/rollout-*.jsonl` if the state DB is missing, unreadable, or the row is stale/absent (mirroring the exact "primary DB, fallback filesystem walk" shape `opencode.py`'s `_resolve_db()` already uses in this codebase, and mirroring what Codex's own binary does internally).
### 1.6 TUI Readiness (candidate, pending empirical capture)
Offline `strings` extraction surfaced real UI literals: `"Ask Codex to do anything"` (composer placeholder) and the banner token `"Codex"`. No `❯` glyph or `─{10,}` rule literal found — different TUI layout family (boxed/panelled, not readline-style). Proposed candidate:
- `ready_tokens`: `'Codex|Ask Codex to do anything'`
- `input_placeholder`: `'Ask Codex to do anything'` (high-confidence — extracted literal)
- `input_prompt` / `input_rule_pattern`: `None` (base-class default) pending live pane capture.
**Hard gate before merge**: capture a real `codex` TUI pane via `herdr pane capture` to confirm exact rendered text.
### 1.7 Exit Convention (verified deviation from every existing adapter)
Binary string table twice describes exiting as a keypress: `"Ctrl+C to exit"`, `"ctrl+c quit"`. No `/exit`/`/quit`/`:q` literal found (real slash commands that do exist: `/keymap`, `/side`, `/review`, `/ide`, `/goal`).
`MAM_EXIT_KEY` is exported by the `facts` bridge and loaded into `send_keys_safe()`'s local scope (`lib.sh:2166`), but **no skill script actually sends it to a pane today, for any agent** — `stop_session.sh` never references `exit_key`/`MAM_EXIT_KEY`. So this remains a required-but-currently-inert contract field. Propose `exit_key = 'Ctrl+C'` (symbolic key name, matching herdr's existing `Escape` send convention), documented as a deliberate divergence.
### 1.8 Authentication
- Interactive: `codex login` (ChatGPT OAuth) or `codex login --with-api-key` (reads `OPENAI_API_KEY` from stdin).
- Credential file: `~/.codex/auth.json` (or `$CODEX_HOME/auth.json`) — verified present, keys `auth_mode`, `OPENAI_API_KEY`, `tokens`, `last_refresh`. `codex login status` confirms `"Logged in using ChatGPT"`; `codex doctor --summary` independently confirms `✓ auth is configured`.
- `auth_ok()`: `os.path.exists(f"{codex_home}/auth.json")` **or** `os.environ.get('OPENAI_API_KEY')`. **Caveat honestly flagged**: whether a bare env var alone (without ever running `codex login --with-api-key`) is sufficient was not empirically tested (this machine is logged in via ChatGPT, not a raw API key).
### 1.9 Session-ID Detection for `orc_onboard.sh` (Rev.2: regex defect fixed)
1. **argv form**: Codex passes the UUID as `codex resume <uuid>` — positional, no flag name. **Rev.1's regex was defective**: `grep -oE 'resume[[:space:]]+[0-9a-f-]{36}'` requires the UUID immediately after `resume`, but the real command line this plan's own `resume_spec`/`CMD_FULL` produce is `codex resume --dangerously-bypass-approvals-and-sandbox <uuid>` — a flag sits in between, so the regex never matches (verified live: exit 1, empty output). **Corrected regex** (challenge's Plan A, live-verified to work): allow arbitrary tokens between `resume` and the UUID, then extract only the UUID:
```bash
codex)
detected_id=$(echo "$cmd_line" | grep -oE 'resume[[:space:]]+.*[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}' | grep -oE '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}' | head -n 1 || true)
;;
```
Already safe under `orc_onboard.sh:135`'s existing `is_valid_id "$detected_id"` UUID-format re-validation, so a slightly looser extraction regex carries no correctness risk.
2. **env var fallback**: no `CODEX_SESSION_ID`-style environment variable found anywhere in `codex --help`. Leave `env_var=""` for `codex` — do not fabricate one.
---
## 2. Adapter Contract Decisions (`BaseAgentAdapter`) — Rev.2
| Property/Method | Value | Rationale |
|---|---|---|
| `name` | `'codex'` | Lowercase identifier |
| `own_key` | `'codex_session_id_own'` | Matches `<agent>_session_id_own` convention |
| `ready_tokens` | `'Codex\|Ask Codex to do anything'` (candidate, §1.6) | Extracted real UI literal, pending live pane-capture confirmation |
| `exit_key` | `'Ctrl+C'` (§1.7) | No typed slash command exists; currently operationally inert framework-wide |
| `delegate_agent_key` | `'codex-cli'` | Matches the `<name>-cli`/`-agent`/`-build`/`-code` suffix convention |
| `identity_cache_fields` | `('session_id',)` | Single-field cache, modern pattern |
| `input_placeholder` | `'Ask Codex to do anything'` | Verified real literal |
| `input_prompt` / `input_rule_pattern` | `None` | No stable glyph found; different TUI layout family |
| `spawn_spec(binary, session_uuid, use_wrapper)` | `f"{binary} --dangerously-bypass-approvals-and-sandbox"` (ignores `session_uuid` — Class A) | §1.3/§1.4 |
| `resume_spec(binary, session_uuid, materialized)` | if `materialized and session_uuid`: `f"{binary} resume --dangerously-bypass-approvals-and-sandbox {session_uuid}"`, else same as `spawn_spec` | Verified `codex resume [OPTIONS] [SESSION_ID]` usage template |
| `auth_ok(run_cmd)` | `os.path.exists(f"{codex_home}/auth.json") or bool(os.environ.get('OPENAI_API_KEY'))` | §1.8, sandbox-safe via `ctx.home_dir` |
| `artifact_path(uuid, ctx)` | **Rev.2**: query `state_*.sqlite`'s `threads.rollout_path WHERE id=?` first; fall back to the bounded glob `sessions/*/*/*/rollout-*-{uuid}.jsonl` if the DB lookup misses | §1.5 — mirrors Codex's own DB-first, filesystem-fallback resolution order |
| `verify_artifact(uuid, ctx)` | Resolve path via the same DB-first/glob-fallback helper; parse first JSONL line's `payload.id`/`payload.cwd` (or use the DB row's `cwd` column directly, skipping the file read, when the DB hit succeeds); apply `ctx.epoch` mtime check | Rev.2: DB row already has `cwd` — avoids opening the file at all on the common (DB-hit) path |
| `purge_artifacts(uuid, ctx)` | **Rev.2**: primary — `subprocess.run([binary_or_'codex', 'delete', uuid, '--force'], ...)`; fallback (only if that call fails/binary unavailable) — manually `os.remove()` the rollout file located via the DB-first/glob-fallback helper, **and** best-effort `DELETE FROM threads WHERE id=?` against the resolved `state_*.sqlite` if it exists | §0 item 2 — avoids orphan DB rows; lets Codex's own reconciliation logic own consistency whenever possible instead of MAM hand-rolling SQL against an evolving schema |
| `discover(ctx)` | **Rev.2**: query `state_*.sqlite`'s `threads` table (`SELECT id, cwd, updated_at FROM threads ORDER BY updated_at DESC LIMIT 50`, filtered by `cwd`/`epoch` in Python) first; fall back to the recursive-glob approach from Rev.1 only if the DB is absent/unreadable | Rev.2 — DB query is a single indexed lookup vs. an N-file glob-and-open walk; also naturally bounded (no unbounded-growth concern for the DB path) |
### Adapter code sketch (`.agents/skills/lib_py/agents/adapters/codex.py`) — Rev.2
```python
import os, json, glob, sqlite3, subprocess
from typing import Optional, Any, List
from lib_py.agents.base import BaseAgentAdapter, DiscoveryContext
from lib_py.verify_session import workspace_key
class CodexAgentAdapter(BaseAgentAdapter):
@property
def name(self) -> str:
return 'codex'
@property
def own_key(self) -> str:
return 'codex_session_id_own'
@property
def ready_tokens(self) -> str:
return 'Codex|Ask Codex to do anything'
@property
def exit_key(self) -> str:
return 'Ctrl+C'
@property
def delegate_agent_key(self) -> str:
return 'codex-cli'
@property
def identity_cache_fields(self) -> tuple:
return ('session_id',)
@property
def input_placeholder(self) -> Optional[str]:
return 'Ask Codex to do anything'
def _codex_home(self, ctx: DiscoveryContext) -> str:
return os.environ.get('CODEX_HOME') or f"{ctx.home_dir}/.codex"
def _state_db(self, ctx: DiscoveryContext) -> Optional[str]:
# Rev.2: no 'codex db path'-equivalent subcommand exists; the numeric
# suffix (state_5.sqlite on this machine) is unverified as stable
# across versions, so resolve dynamically rather than hardcoding it.
matches = glob.glob(f"{self._codex_home(ctx)}/state_*.sqlite")
if not matches:
return None
return max(matches, key=os.path.getmtime)
def _find_rollout_via_db(self, uuid: str, ctx: DiscoveryContext):
"""Returns (rollout_path, cwd) from the state DB, or (None, None)."""
db = self._state_db(ctx)
if not db or not os.path.exists(db):
return None, None
try:
conn = sqlite3.connect(db)
row = conn.execute("SELECT rollout_path, cwd FROM threads WHERE id=?", (uuid,)).fetchone()
conn.close()
if row and row[0] and os.path.exists(row[0]):
return row[0], row[1]
except Exception:
pass
return None, None
def _find_rollout(self, uuid: str, ctx: DiscoveryContext) -> Optional[str]:
path, _ = self._find_rollout_via_db(uuid, ctx)
if path:
return path
# Fallback: bounded glob over the date-nested tree (state DB missing/stale)
matches = glob.glob(f"{self._codex_home(ctx)}/sessions/*/*/*/rollout-*-{uuid}.jsonl")
return matches[0] if matches else None
def artifact_path(self, uuid: str, ctx: DiscoveryContext) -> str:
return self._find_rollout(uuid, ctx) or f"{self._codex_home(ctx)}/sessions/rollout-{uuid}.jsonl"
def verify_artifact(self, uuid: str, ctx: DiscoveryContext) -> bool:
db_path, db_cwd = self._find_rollout_via_db(uuid, ctx)
path = db_path or self._find_rollout(uuid, ctx)
if not path or not os.path.exists(path):
return False
if ctx.epoch and os.path.getmtime(path) < ctx.epoch:
return False
found_cwd = db_cwd
if not found_cwd:
try:
with open(path) as f:
first = f.readline()
found_cwd = json.loads(first).get('payload', {}).get('cwd')
except Exception:
return False
if found_cwd and workspace_key(found_cwd) != workspace_key(ctx.cwd):
return False
return True
def purge_artifacts(self, uuid: str, ctx: DiscoveryContext) -> List[str]:
purged = []
path = self._find_rollout(uuid, ctx)
# Rev.2: prefer the CLI's own delete path (keeps rollout file + state
# DB row consistent via Codex's own reconciliation logic).
try:
res = subprocess.run(['codex', 'delete', uuid, '--force'],
capture_output=True, text=True, timeout=5)
if res.returncode == 0:
if path:
purged.append(path)
return purged
except Exception:
pass
# Fallback: manual removal of the file, plus a best-effort DB row delete.
if path and os.path.exists(path):
os.remove(path)
purged.append(path)
db = self._state_db(ctx)
if db and os.path.exists(db):
try:
conn = sqlite3.connect(db)
conn.execute("DELETE FROM threads WHERE id=?", (uuid,))
conn.commit()
conn.close()
purged.append(f"state db row for thread: {uuid}")
except Exception:
pass
return purged
def spawn_spec(self, binary: str, session_uuid: str = "", use_wrapper: bool = False) -> str:
return f"{binary} --dangerously-bypass-approvals-and-sandbox"
def resume_spec(self, binary: str, session_uuid: str, materialized: bool = False) -> str:
if materialized and session_uuid:
return f"{binary} resume --dangerously-bypass-approvals-and-sandbox {session_uuid}"
return f"{binary} --dangerously-bypass-approvals-and-sandbox"
def auth_ok(self, run_cmd: Optional[Any] = None) -> bool:
home = os.environ.get('HOME_DIR') or os.environ.get('HOME') or os.path.expanduser('~')
codex_home = os.environ.get('CODEX_HOME') or f"{home}/.codex"
return os.path.exists(f"{codex_home}/auth.json") or bool(os.environ.get('OPENAI_API_KEY'))
def discover(self, ctx: DiscoveryContext) -> List[str]:
db = self._state_db(ctx)
if db and os.path.exists(db):
try:
conn = sqlite3.connect(db)
rows = conn.execute(
"SELECT id, cwd, updated_at FROM threads ORDER BY updated_at DESC LIMIT 50"
).fetchall()
conn.close()
candidates = []
for uuid, cwd, _ in rows:
if ctx.workspace and cwd and workspace_key(cwd) != workspace_key(ctx.workspace):
continue
if uuid and self.verify_artifact(uuid, ctx):
candidates.append(uuid)
return candidates
except Exception:
pass
# Fallback: recursive glob (state DB absent/unreadable)
root = self._codex_home(ctx)
candidates = []
paths = sorted(glob.glob(f"{root}/sessions/*/*/*/rollout-*.jsonl"), key=os.path.getmtime, reverse=True)[:50]
for path in paths:
uuid = os.path.basename(path)[:-6][-36:]
if uuid and self.verify_artifact(uuid, ctx):
candidates.append(uuid)
return candidates
```
---
## 3. Full Lockstep Wiring Table (Rev.2)
Same 46-item table as Rev.1, with item #27 corrected per §0/§1.9. Re-derived from the current, live state of every file that mentions `opencode` today (33 files, `.agents/reports/` excluded).
| # | Component / File | Specific Edit Required |
|---|---|---|
| 1 | `.agents/skills/lib_py/agents/adapters/codex.py` | Create new adapter class `CodexAgentAdapter` per §2 (Rev.2: DB-first artifact resolution + `codex delete --force`-based purge) |
| 2 | `.agents/skills/lib_py/agents/registry.py:9,16` | Import `CodexAgentAdapter`; add `'codex': CodexAgentAdapter()` to `_ADAPTERS` |
| 3 | `.agents/skills/lib_py/atomic_yaml.py:132` | Add `'codex_session_id_own'` to `running_keys` |
| 4 | `.agents/skills/lib_py/verify_session.py:69` | Add `'codex_session_id_own'` to the `mam_row_own_uuid()` field list |
| 5 | `.agents/skills/lib_py/workspace_uuid.py:7-12,34` | Add `'codex': 'codex_session_id_own'` to `OWN_KEY`; add `'codex_session_id_own'` to the `running_ids` field list |
| 6 | `.agents/skills/lib.sh:669` (kind mapping) | Add `*-creator-codex\|*-planner-codex\|*-reviewer-codex) kind="codex" ;;` |
| 7 | `.agents/skills/lib.sh:675,680` (fallback grep chain, name + `final_cmd`) | Add `elif echo "$name" \| grep -qi "codex"; then kind="codex"` and the `final_cmd` equivalent |
| 8 | `.agents/skills/lib.sh:694` (binary dedup tuple) | Add `'codex'` to `('claude', 'agy', 'hermes', 'grok', 'opencode', 'codex')` |
| 9 | `.agents/skills/lib.sh:2175` (`send_keys_safe` agent resolution) | Add `*-codex\|*-codex-[0-9]*\|codex\|codex-[0-9]*) _sks_agent="codex" ;;` |
| 10 | `create_session.sh:4,29,33` (usage/help text) | Add `codex` to the `<claude\|agy\|hermes\|grok\|opencode>` listings |
| 11 | `create_session.sh:93-94` (`--agent` whitelist) | Add `codex` to the accepted-values case and the error message |
| 12 | `create_session.sh` (auth preflight, new `elif` block after the existing `opencode` one at line 129) | `elif [ "$AGENT" = "codex" ]; then` check `~/.codex/auth.json` (respecting `CODEX_HOME`) or `OPENAI_API_KEY`, else `codex --version` smoke check |
| 13 | `create_session.sh:192` (fallback `CMD_FULL` case) | Add `codex) CMD_FULL="${RESOLVED_BIN} --dangerously-bypass-approvals-and-sandbox" ;;` |
| 14 | `create_session.sh:216` (`spawn()` dispatch case) | Add `codex` to the `agy\|hermes\|grok\|opencode)` case — no special env-var export needed |
| 15 | `create_session.sh:330` (delegate-agent key resolution) | Add `codex) delegate_agent="codex-cli" ;;` |
| 16 | `create_session.sh:438` (YAML init Python block) | Add `elif agent == 'codex': entry['codex_session_id_own'] = None; entry['session_id_source'] = 'pending-discovery'; entry['session_id_verified'] = False; entry['last_visible_status'] = "unverified"` |
| 17 | `resolve_session_id.sh:4,16,39-40` | Add `codex` to usage text and the `--agent` whitelist case |
| 18 | `resume_session.sh:12,45` | Add `codex` to usage text and the `--agent` whitelist case |
| 19 | `resume_session.sh:65` (FRESH_SPAWN Class-A case) | Add `codex` to `agy\|hermes\|opencode) FRESH_SPAWN=1 ;;` — Codex is Class A |
| 20 | `resume_session.sh:121` (fallback spawn-spec case) | Add `codex) CMD_FULL="${RESOLVED_BIN} --dangerously-bypass-approvals-and-sandbox" ;;` |
| 21 | `resume_session.sh:132` (fallback resume-spec case) | Add `codex) CMD_FULL="${RESOLVED_BIN} resume --dangerously-bypass-approvals-and-sandbox $UUID" ;;` |
| 22 | `update_yaml_resumed.sh:7,14,17` | Add `codex` to usage docs and the Class-A comment listing |
| 23 | `update_yaml_resumed.sh:228` (Python block) | Add `elif agent == 'codex': target['pane']['cmd'] = 'codex'`; if `uuid`: `cmd_full = f'codex resume --dangerously-bypass-approvals-and-sandbox {uuid}'`, `target['codex_session_id_own'] = uuid`; else `cmd_full = os.environ.get('CMD_FULL_OPT', '') or 'codex --dangerously-bypass-approvals-and-sandbox'` |
| 24 | `stop_session.sh:4,15,94-95` | Add `codex` to usage docs and the `--agent` whitelist case + error message |
| 25 | `stop_session.sh:290` (Python capture block) | Add `elif agent == 'codex': target['codex_session_id_own'] = captured` |
| 26 | `orc_onboard.sh:106` (agent-family match) | Add `codex` to the `claude\|agy\|hermes\|grok\|opencode)` case |
| 27 | `orc_onboard.sh:117-133` (CLI-argv detection) | **Rev.2 corrected**: new `codex)` branch using the flag-tolerant regex from §1.9 (`resume[[:space:]]+.*<uuid-pattern>` then extract just the UUID) — **not** the Rev.1 regex, which is confirmed broken against this plan's own `resume_spec` output |
| 28 | `orc_onboard.sh:142-148` (env-var fallback) | Add `codex) env_var=""` explicitly (no known env var — do not fabricate one) |
| 29 | `reconcile.sh:523,542` (agent-name tuples) | Add `'codex'` to both `('claude', 'agy', 'hermes', 'grok', 'opencode')` tuples |
| 30 | `reconcile.sh:603` (fresh-row entry init) | Add `elif agent == 'codex': entry['codex_session_id_own'] = None` |
| 31 | `reconcile.sh:616` (`OWN_KEY_BY_AGENT`) | Add `'codex'` to the tuple |
| 32 | `reconcile.sh` (new dedicated block, after the existing opencode block at line ~787-897) | New `# === drift C (codex) ===` block, **Rev.2**: state-DB-first with glob fallback (see §4) |
| 33 | 8× `SKILL.md` supported-agent lists (`multi-agent-mux-create:132,163-166`; `multi-agent-mux-orc-onboard:11,35,41`; `multi-agent-mux-resume:52,55,61,73,99,110`; `multi-agent-mux-stop:40`) | Add `codex` everywhere `opencode` currently appears in these four files; the other 4 `SKILL.md` files need only the version-frontmatter bump (§6) |
| 34 | `.agents/skills/multi-agent-mux-delegate-job/job-protocol.md:3`, `README.md:3` | No change needed — `codex` already listed informally |
| 35 | `tests/conftest.py` | Add a `codex` mock binary fixture (mirroring `opencode_bin`, line ~972-990) that writes a fake `rollout-<ts>-<uuid>.jsonl` under a temp `$CODEX_HOME/sessions/<Y>/<M>/<D>/` **and** a matching `state_1.sqlite` `threads` row (Rev.2: needed since `discover()`/`verify_artifact()` now query the DB first); add ready-banner/own-key dict entries (lines ~553, ~584) |
| 36 | `tests/test_a4_adapter_contract.py` | Add `codex` to `EXPECTED_OWN_KEYS`, the property tuple, `expected_modal` (`None`), the `facts_bridge` loop (line ~112), a `_seed_codex_session()` helper (mirroring `_seed_opencode_session`, line ~132, **Rev.2**: seeding both the `.jsonl` and the `state_*.sqlite` row), and unit tests for `spawn_spec`/`resume_spec`/`auth_ok`/`purge_artifacts` (**Rev.2**: including a test that `purge_artifacts` falls back to manual removal when the `codex delete` subprocess call fails)/`discover` |
| 37 | `tests/test_c1_tui_readiness.py` | Add `codex` to the facts-bridge and `send_keys_safe` agent-resolution loops (line ~491) and a `check_sks` assertion pair (mirroring lines 528-529, 539-540) |
| 38 | `tests/test_tier1_unit.py` | Update the agent-tuple assertions (lines ~963, 969, 974, 988-989, 994, 1033) to include `codex`; add `test_codex_shell_and_scripts_integration` mirroring `test_opencode_shell_and_scripts_integration` (lines 982-1044); **Rev.2**: add a dedicated regression test asserting `orc_onboard.sh`'s `codex` regex correctly extracts the UUID from `codex resume --dangerously-bypass-approvals-and-sandbox <uuid>` — this is the exact scenario Rev.1 got wrong, so it must be locked down by a test, not just fixed in prose |
| 39 | `tests/test_tier2_component.py` | Add `test_comp_codex_create_and_reconcile_and_stop` mirroring `test_comp_opencode_create_and_reconcile_and_stop` (line ~1229) |
| 40 | `.mam.env.example` (after the existing OpenCode block, line ~110) | Document `OPENAI_API_KEY` and `CODEX_HOME` as an optional override |
| 41 | `docs/NEW_AGENT_INTEGRATION_GUIDE.md` §3 (difficulty matrix) | Update the `Codex CLI` row from the old guessed values to the verified ones from §1 |
| 42 | `.agents/reports/new_agent_types_roadmap.md` §4 | Add a cross-link noting the Codex row is superseded by this plan |
| 43 | `.agents/MULTI_AGENT_RULES.md:21` / `.ko.md:21` | Add `codex` to the Team-Leader agent-name parenthetical, scope confined to that one line each |
| 44 | `README.md:3,17,45,136` / `README.ko.md:3,17,27,118` | Add `codex` to the 5-agent → 6-agent listings, incl. a `codex resume <uuid>` example (positional form, §1.9) |
| 45 | `BOOTSTRAP.md:197` / `.ko.md:196` | Add `codex` to the onboarding agent-name parenthetical |
| 46 | `deploy/INSTALL.md:3` | Add `Codex` to the parenthetical agent list |
---
## 4. `reconcile.sh` Drift-C Block for Codex (Rev.2: state-DB-first)
```python
# === drift C (codex): codex 새 session id materialize (per-row own id) ===
for s in d.get('herdr_sessions', []):
if row_agent(s) != 'codex':
continue
if s.get('status') != 'running':
continue
if s.get('codex_session_id_own'):
continue
cwd = (s.get('pane') or {}).get('cwd', '')
if not cwd:
continue
codex_home = os.environ.get('CODEX_HOME') or f"{home}/.codex"
epoch_threshold = s.get('herdr_session_epoch', 0)
sibling_claimed = [
other.get('codex_session_id_own')
for other in d.get('herdr_sessions', [])
if other is not s
and (other.get('pane') or {}).get('cwd') == cwd
and other.get('status') not in ('stopped', 'terminated')
and other.get('codex_session_id_own')
]
s_eval = dict(s)
s_eval['_sibling_claimed_uuids'] = sibling_claimed
valid_candidates = []
try:
# Rev.2: state DB first (indexed, single query) — dynamic filename,
# no hardcoded suffix (see §1.5 / §2 _state_db()).
state_matches = glob.glob(f"{codex_home}/state_*.sqlite")
state_db = max(state_matches, key=os.path.getmtime) if state_matches else None
rows = []
if state_db and os.path.exists(state_db):
conn = sqlite3.connect(state_db)
rows = conn.execute(
"SELECT id, updated_at FROM threads WHERE cwd=? ORDER BY updated_at DESC LIMIT 20",
(cwd,)
).fetchall()
conn.close()
if not rows:
# Fallback: bounded glob over the date-nested tree
paths = sorted(
glob.glob(f"{codex_home}/sessions/*/*/*/rollout-*.jsonl"),
key=os.path.getmtime, reverse=True
)[:50]
rows = [(os.path.basename(p)[:-6][-36:], os.path.getmtime(p)) for p in paths]
for uuid, ts in rows:
if epoch_threshold and ts and ts < epoch_threshold:
continue
if uuid in (sibling_claimed or []):
continue
if verify_session_uuid(cwd, 'codex', uuid, s_eval, mode="discover"):
valid_candidates.append(uuid)
except Exception:
pass
if len(valid_candidates) > 1:
drifts.append({'class': 'C-ambiguous', 'name': s['name'],
'msg': f"{s['name']}: {len(valid_candidates)} candidate transcripts newer than session epoch; not pinning"})
s['last_visible_status'] = f"ambiguous: {len(valid_candidates)} candidates"
actions.append(f"ambiguous candidates: {s['name']}")
elif len(valid_candidates) == 1:
uuid = valid_candidates[0]
cmd = ['bash', '-c', f'source "{lib_sh}" && verify_tui_viewport "{s["name"]}" "codex" "{cwd}"']
rc = subprocess.run(cmd).returncode
if rc == 0:
_pin_and_verify_resume(s, 'codex', cwd, uuid, degraded=False)
elif rc == 1:
drifts.append({'class': 'C-warn', 'name': s['name'], 'msg': f"{s['name']}: TUI viewport mismatch for candidate {uuid} — not pinned, will retry next cycle"})
else:
_pin_and_verify_resume(s, 'codex', cwd, uuid, degraded=True)
```
`verify_session_uuid()` (shared, `lib_py/verify_session.py`) needs a `codex_session_id_own` entry added to its own-key list (wiring item #4) for the `C0`-class "confirm, don't discover" path.
---
## 5. `status.sh`
Both `resume_on_disk()`-style helpers (lines ~56-61, ~234-239) iterate `('claude', 'agy', 'hermes', 'grok', 'opencode')`. Add `codex` to both tuples and a new `if agent == 'codex':` branch resolving via the same DB-first/glob-fallback helper as the adapter (§2), returning `'yes'`/`'MISSING'`/`'no'`.
---
## 6. Version & Documentation Bump
Current: `MAM_VERSION="4.1.3"`. Propose **`4.1.3 → 4.2.0` (MINOR)**, matching the OpenCode precedent, in strict 3-way lockstep (`lib.sh:32`, `VERSIONS.md`, all 8 `SKILL.md` frontmatter) per `tests/test_version_consistency.py`. No new agent-specific guide needed (no local-LLM/Ollama angle for Codex).
---
## 7. Empirical Verification Gate (must happen before merge)
1. Live pane capture to confirm `ready_tokens`/`input_placeholder` (§1.6).
2. Live smoke test that `--dangerously-bypass-approvals-and-sandbox` suppresses every confirmation prompt in a real multi-file-edit task.
3. Live test of the corrected `orc_onboard.sh` regex (§1.9) against a real running `codex resume <uuid>` process's `ps`/`/proc` argv snapshot — the regex was verified against a synthetic string in this planning pass, not a real captured process line.
4. **(Rev.2, new)** Confirm the `state_*.sqlite` glob resolves correctly on a *different* Codex install/version than this machine's `state_5.sqlite` — the numeric suffix is not a documented, guaranteed-stable contract, only an observed fact on one install.
---
## 8. Definition of Done Checklist
- [ ] Complete Phase 0 empirical gate (§7), including the new Rev.2 state-DB-portability check.
- [ ] Implement `.agents/skills/lib_py/agents/adapters/codex.py` per §2 (DB-first resolution, `codex delete --force`-based purge with fallback).
- [ ] Apply all 46 lockstep wiring points in §3, including the **corrected** `orc_onboard.sh` regex (item #27).
- [ ] Add the dedicated `reconcile.sh` Drift-C block (§4, state-DB-first) and its `C-ambiguous`-scenario test.
- [ ] Add all test coverage in §3 items #35-39, **including the regression test locking down the corrected `orc_onboard.sh` regex** (item #38) and the `purge_artifacts` CLI-then-fallback test (item #36); `pytest tests/` shows 0 regressions.
- [ ] Bump version to `4.2.0` in strict 3-way lockstep (§6).
- [ ] Correct the two speculative prior reports' Codex rows (§3 items #41-42).
- [ ] Manual end-to-end smoke test: create → prompt → status shows `yes` → reconcile materializes `codex_session_id_own` → stop → resume round-trips → purge leaves no orphan `.jsonl` or `state_*.sqlite` row.
---
## 9. Effort Estimate
- **Total Estimate**: **~1.5-1.75 days** (Rev.2: +0.25 day vs. Rev.1 for the state-DB-aware adapter logic and the corrected/tested `orc_onboard.sh` regex).
- ~2-3 hrs: Phase 0 empirical gate (§7), including the new state-DB-portability check.
- ~4-5 hrs: adapter implementation (DB-first + glob-fallback throughout) + the 46-point mechanical wiring pass.
- ~2-3 hrs: dedicated `reconcile.sh` Drift-C block + `status.sh` + full test suite additions, including the two Rev.2 regression tests.
- ~2 hrs: docs/version bump + end-to-end manual smoke test (including a purge-leaves-no-orphan-row check).
@@ -0,0 +1,142 @@
# 📊 Issue #5 기술 심층 검토 통합 보고서 (Rev. 2)
- **대상 이슈**: [Gitea Issue #5 — `[Refactor] lib.sh 작업 위임 로직 및 run_loop.sh 오케스트레이터의 Python 모듈화 (lib_py 승격)`](https://git.godopu.com/tmpl/multi-agent-mux/issues/5)
- **작성 주체**: Antigravity (총괄 오케스트레이터)
- **검토 참여자**: 3개 팀 리더 리뷰어 에이전트 전원 참여 (1차 검토 및 2차 교차 검토 완료)
- `planner-reviewer-claude-01`
- `reviewer-creator-grok-01`
- `planner-reviewer-codex-01`
- **검토 일시**: 2026-09-06 (Rev.1 발행 및 2차 정밀 교차 검증 반영)
- **기준 브랜치 / 커밋**: `refactor` (`47640e2`)
- **종합 합의 상태**: **파이썬 모듈화 방향성 만장일치 지지 (단, 자동완료 증거 계약·CAS 상태 전이·런타임 불변성의 필수 안전 조건 선결을 전제로 한 조건부 동의이며, 기계 판정용 최종 구현 PASS가 아님)**
---
## 1. 개요 및 합의 수준의 사실적 기술
본 보고서는 `lib.sh`의 작업 위임 로직 및 `run_loop.sh` 오케스트레이터 전체를 파이썬 패키지(`lib_py`)로 승격 및 모듈화하는 제안(Issue #5)에 대해, 세 팀 리더 리뷰어가 코드베이스 실측과 2차에 걸친 독립적 교차 분석을 통해 도출한 최종 정제 통합 보고서입니다.
세 리뷰어 모두 **파이썬 모듈화의 필요성과 아키텍처 방향성에 공통으로 찬성**합니다. 그러나 이 찬성은 "무조건적 구현 승인"이 아니며, 자동완료 오탐 방지, 다중 Writer 경합, 런타임 자기수정 크래시(B-13)의 단계적 해소 조건에 대해 엄격한 기술적 안전 계약이 수립되어야 함을 강력히 요구하고 있습니다.
### 📌 리뷰어별 평가 및 판정 토큰 현황 (사실 대조)
| 리뷰어 에이전트 | 세션명 | 1차 검토 Job | 2차 검토 Job | 공식 `[VERDICT: ...]` 토큰 | 종합 평가 성격 |
| :--- | :--- | :---: | :---: | :---: | :--- |
| **Claude** | `planner-reviewer-claude-01` | `1919bf5e` | `cdc926e3` | **미발행 (산문형 지지)** | 방향성 지지, Herdr 1급 API 실재 발견, 1,621줄 subprocess 테스트 재타겟팅 공수 경고 |
| **Grok** | `reviewer-creator-grok-01` | `9885ecd6` | `3e3b6d18` | **`[VERDICT: PASS]`** | 방향성 조건부 PASS, `interactive_ready` 배제 실측 증명, 15s 디바운스 및 6대 게이트 제시 |
| **Codex** | `planner-reviewer-codex-01` | `5da43b79` | `14f9eac4` | **미발행 (조건부 동의)** | 방향성 동의, 실행 귀속(Attribution)·리포트 확정 계약·단일 CAS 전이 필수 조건화 |
> 3명 중 1명(Grok)만 단독 행 `[VERDICT: PASS]` 토큰을 남겼으며, Claude와 Codex는 구체적 안전 조건을 요구하는 산문형 조건부 동의를 제출했습니다. 본 프로젝트의 엄밀한 fail-closed 계약에 따라 이를 "만장일치 최종 PASS"로 왜곡하지 않고 **"안전 계약 선결을 전제로 한 방향성 만장일치 합의"**로 명문화합니다.
---
## 2. 2차 교차 검증을 통해 복원된 핵심 안전 계약
세 리뷰어의 2차 정밀 피드백을 통해 1차 요약 과정에서 누락되거나 단순화되었던 핵심 엔지니어링 계약들이 복원되었습니다.
### 2-1. 실행 귀속(Execution Attribution) 보장 계약 (Codex 복원, 전원 지지)
- 단순히 터미널이 `idle`이라고 해서 완료로 판단해서는 안 됨 (세션 재사용 시 이전 작업의 잔여 유휴 상태 오인 위험).
- 자동완료 후보는 반드시 다음 **4중 식별자**가 일치해야 함:
`Job ID` + `Attempt ID` + `Agent/Session UUID` + `Pane/Process Generation`
- 디스패치 확인 시점 이후 해당 시도(Attempt)의 실제 실행 및 응답이 관측된 경우에만 완료 후보로 인정.
- 동일 에이전트 세션에는 동시에 단 하나의 Job만 배정.
### 2-2. 리포트 확정 계약의 단계적 진화 (Grok vs Codex 이견 정리)
- **1차/보조 필터 (Grok 제안)**: `report-final.md` mtime이 일정 디바운스 구간(기본 권장 ≥15초, monotonic clock 측정) 동안 불변일 것.
- **2차/강화 계약 (Codex 제안)**: 시간 경과(15s)만으로는 파일 쓰기 완료를 완벽히 증명할 수 없으므로, 임시 파일 작성 후 **원자적 이름 변경(Atomic Rename)** 및 `Attempt ID`와 `Report Hash`가 명시된 **완료 매니페스트(Finalization Manifest)** 생성을 최종 목표로 설정.
- **적용 규칙**: Phase 2a에서는 mtime 디바운스(15s)를 보조 필터로 검증하고, Phase 2b에서는 확정 계약 미지원 작업은 자동 완료 대신 "복구 후보/수동 확인"으로 남김.
### 2-3. 단일 상태 전이 주체(Engine)와 원자적 CAS (Compare-And-Swap)
- **책임의 엄격한 격리**:
- `watcher.py`: 오직 관측 증거(증거 튜플: Event, Herdr status, Report path/hash)만 수집하여 큐로 전달.
- `engine.py`: 락 하에서 상태 전이를 결정하는 **유일한 주체**.
- **원자적 상태 전이 불변식**:
- Agent의 `publish_event`와 Engine의 Watcher 감시 모두 **공통 전이 함수/서비스**를 사용.
- `expected attempt` 및 `비terminal(started/progress)` 상태임을 확인한 후 원자적으로 전이 (CAS).
- 명시적 `error` 또는 `cancelled` 상태를 자동 `completed`로 덮어쓰지 않음.
- 완료 확정 후 뒤늦게 도착한 `progress`나 `started` 이벤트로 상태를 역행시키지 않음.
- **잠금(Lock) 내 I/O 및 재진입 대기 위험 방지**:
- Registry Lock 유지 상태에서 자식 프로세스 호출(subprocess)이나 네트워크 I/O(MQTT)를 실행하지 않음.
- 짧은 트랜잭션으로 상태 확정 및 Pending Notification 기록 ➔ Lock 즉시 해제 ➔ 비동기 MQTT 발행 및 멱등 재시도 수행.
- `auth_token != null`인 경우 레지스트리의 토큰으로 HMAC 서명하여 정규 발행 (누락 시 silent drop 방지).
### 2-4. Herdr 네이티브 API의 정확한 호출 규격 및 예외 처리
- **옵션 명시 필수**:
- `herdr agent wait <target>`의 CLI 기본값은 `idle, done, or blocked`이며, `blocked`는 permission_required나 입력 대기 상태이므로 완료가 아님.
- 따라서 Watcher는 반드시 상태를 명시적으로 지정하여 호출해야 함:
`herdr agent wait <TARGET> --until idle --until done --timeout <MS>`
- **`interactive_ready`의 성격 규정**:
- 에이전트가 코딩 작업 중(`agent_status=working`)일 때도 `interactive_ready=true`임이 실측으로 증명됨.
- 따라서 `interactive_ready`는 완료 충분조건이 아니며, 오직 `agent_status in {"idle", "done"}`만 완료 후보로 인정.
- **소켓 단절 및 버전 드리프트 가드**:
- Herdr 소켓 단절 시 반환되는 `unknown`을 idle로 오인하지 않고, 재연결 백오프 및 스냅샷 재동기화를 수행.
- 의존하는 Herdr CLI/JSON 필드의 최소 호환 버전을 검증하고, 불일치 시 fail-closed(수동 확인)로 폴백.
### 2-5. 특수 작업에 대한 예외 및 Fail-Closed 원칙
- **외부 부수효과 작업 예외**:
- Gitea 댓글 등록, Git push, 배포 등 리포트 파일 생성 외에 외부 시스템에 부수효과를 일으키는 작업은 리포트 파일 존재만으로 자동완료 처리하지 않음 (외부 실행 완료 증거가 없을 경우 수동 확인 유지).
- **무판정 Reviewer 리포트 처리**:
- Reviewer 작업의 리포트 마지막 줄에 `[VERDICT: PASS]` 또는 `[VERDICT: NOT PASS]` 토큰이 누락된 경우, `completed` 승격 절대 금지.
- 작업 deadline 도달 시 명시적 `error` 발행 또는 반려 처리 (Fail-Closed 엄격 유지).
- Reviewer의 `completed`(리뷰 행위 완료)와 `PASS`(검증 통과)를 절대 혼동하지 않음.
---
## 3. 합의된 안전 상태 머신 아키텍처
```mermaid
flowchart TD
subgraph Watcher["이중 감시 체계 (Watcher - 관측 증거 수집 전용)"]
W1["채널 1: MQTT 이벤트 스트림 및 로컬 작업 레코드"]
W2["채널 2: herdr agent wait --until idle --until done"]
W3["파일 증거: 지정 경로 report-final.md mtime 디바운스 (≥15s)"]
end
subgraph Gate["안전 검증 게이트 (Fail-Closed AND Gate)"]
G1{"4중 귀속 일치?\n(Job ID + Attempt + UUID + Generation)"}
G2{"agent_status in (idle, done)?\n(interactive_ready 단독 불인정)"}
G3{"리포트 확정 완료?\n(디바운스 경과 및 매니페스트 확인)"}
G4{"Reviewer: 마지막 행 정식 판정 토큰 존재?"}
G5{"외부 부수효과 작업 여부 확인\n(부수효과 시 별도 증거 필요)"}
end
subgraph Engine["단일 상태 제어 엔진 (Engine - 배타적 전이)"]
E1["공통 상태 전이 트랜잭션 (CAS Lock)"]
E2["Terminal State Commit & Pending Notification 기록"]
E3["Lock 해제"]
E4["정규 publish_event 경로로 이벤트 발행 (HMAC 서명)"]
E5["다음 루프 단계 디스패치"]
end
W1 & W2 & W3 --> Gate
G1 & G2 & G3 & G4 & G5 -->|모두 충족 (AND)| Engine
Gate -->|하나라도 미충족| Wait["계속 대기 (Wait / Fail-Closed)"]
```
---
## 4. 4단계 마이그레이션 로드맵 (세부 기준 보완)
| 단계 | 작업 목표 | 상세 구현 내용 및 필수 완료 기준 (Gate) |
| :--- | :--- | :--- |
| **Phase 0** | **사전 계약 고정 및 Fixture 수집** | • CLI, 상태 이벤트, 리포트 형식, 락 계약 기준선 문서화<br>• Herdr 6개 어댑터별 런타임 상태 전이 fixture 수집<br>• 미합의 기술 항목(디바운스 vs 매니페스트)의 단계별 채택 기준 확정 |
| **Phase 1** | **`lib_py/delegation/` 구축** | • `lib.sh` L1833 위임 헬퍼를 파이썬 서비스 클래스로 추출<br>• `start_watchdog`은 실제 역할에 맞춰 `ensure_subscriber_daemon`으로 명명<br>• 인메모리 단일 MQTT 연결 재사용 프로토타입 (레이턴시는 벤치마크로 보고)<br>• 기존 CLI/non-fatal/HMAC/seq/디스크 폴백 회귀 100% 통과<br>• **자동완료 정책 변경 없음, 세션 DB와 Job 레지스트리 저장소 통합 시도 금지** |
| **Phase 2a** | **`lib_py/loop/` 코어 & Shadow Watcher** | • `engine.py` (단일 전이 주체), `watcher.py` (`herdr agent wait` 래핑) 구현<br>• 자동완료는 수행하지 않고 "Would-Complete" 로깅만 수행하는 Shadow 모드 가동<br>• 소켓 단절/재연결 백오프, 부분 리포트, 승인 대기, 도구 실행 시뮬레이션 검증 |
| **Phase 2b** | **이중 감지 자동완료 활성화 (Flag-Gated)** | • 4중 실행 귀속 + 리포트 확정 계약 + 단일 CAS 전이 게이트 검증<br>• 부수효과 작업 예외 규정 및 무판정 fail-closed 단위 테스트 완료<br>• 기본 off 플래그로 배포 후 검증 완료 시 기본값 활성화 |
| **Phase 3** | **`run_loop.sh` Thin Wrapper 전환 및 회귀** | • `run_loop.sh`를 인자 전달 래퍼(`exec python3 -m lib_py.loop "$@"`)로 전환<br>• `--creator` 필수, `--target-agent` 거부, bash 3.2, PYTHONPATH 계약 보존<br>• 5개 subprocess 전용 테스트(~1,621줄) 포함 **현행 전체 469개 테스트 0-Fail**<br>• **신·구 엔진의 동일 작업공간 동시 Writer 병행 금지** |
| **Phase 4** | **불변 런타임 검증 및 B-13 정리** | • 기동 시 전체 모듈 상주(Eager Import) 및 자식 인터프리터/템플릿 불변성 검증<br>• 작업 도중 스킬 파일 교체 및 늦은 경로(재심/승격/롤백) 스트레스 테스트 통과<br>• `/tmp/mam-loop-freeze.XXXXXX` 셸 임시 우회책 완전 제거 및 문서화 |
---
## 5. 명시적 비범위(Out of Scope) 및 호환성 계약
1. **저장소 통합 금지**: 본 리팩토링에서 TMUX 세션 관리용 SQLite/YAML 저장소와 비동기 작업 관리용 `.mam/jobs/` JSON 레지스트리를 하나로 통합하려 시도하지 않습니다 (목적과 수명이 다름).
2. **원샷 스킬의 Live Tree 사용 유지**: `multi-agent-mux-create`, `resume`, `stop` 등 단발성 셸 스크립트는 Freeze 복사본이 아닌 실제 작업 트리의 코드를 실행하도록 유지합니다.
3. **타임아웃의 3원 분리 보존**: (a) 전체 벽시계 타임아웃, (b) MQTT 가입자 idle-timeout, (c) TUI idle 자동완료를 독립적으로 유지하며, 자동완료가 기존 타임아웃 메커니즘을 덮어쓰지 않습니다.
---
## 6. 결론
2차 교차 검토를 통해 본 통합 보고서는 세 리뷰어의 실질적 발견과 기술적 차이를 충실히 수렴하여 완성도를 대폭 끌어올렸습니다.
모든 리뷰어가 지적한 대로 **Phase 0(사전 계약 및 어댑터 fixture 정리)** 을 즉시 수립한 후, **Phase 1(`lib_py/delegation/` 구축 및 안전한 서비스 추출)** 에 착수하는 것이 가장 안전하고 확실한 진행 경로입니다.
@@ -0,0 +1,121 @@
# 📑 Issue #6 종합 리뷰 및 아키텍처 개선 통합 보고서 (Rev. 2)
- **작성 주체**: 오케스트레이터 (Orchestrator)
- **참여 리뷰어**: `planner-reviewer-claude-01` (Claude), `reviewer-creator-grok-01` (Grok), `planner-reviewer-codex-01` (Codex), `reviewer-opencode-01` (OpenCode)
- **검토 대상**: Gitea [Issue #6](https://git.godopu.com/tmpl/multi-agent-mux/issues/6) — `[Bug] delegate-job 워커 실패 시 레지스트리 미갱신(Fail-Silent) 및 TUI 턴 마감 레이스 컨디션 해결`
- **검토 기준 커밋**: `f98b958` (`main`, `refactor`, v4.4.0)
- **문서 버전**: Revision 2 (Rev. 2 — 2차 라운드 리뷰어 피드백 전건 반영)
---
## 1. 개요 및 총평
오케스트레이터 루프(`run_loop.sh` / `lib_py.loop`) 실행 중 발생했던 3,900초 영구 대기(hang) 결함(Issue #6)에 대해 4명의 리뷰어가 독립적으로 소스 코드 추적, 단위 격리 재현, 실측 포렌식, Herdr 0.8.2 네이티브 API 계약 분석을 수행했습니다.
**리뷰어 4인 전원의 만장일치 판정 결과:**
> **"Issue #6에서 제기한 결함 ①과 결함 ②는 모두 실제 코드베이스에 존재하는 심각한 실재 버그 및 설계 결함이다."**
특히 2차 라운드 교차 검토를 통해 **루프 실사용 경로(`--type direct`)의 숨은 결함**, **기존 `deadline_timeout` CAS 엔진 재사용 원칙**, **구독자 타임아웃 예산 자가포식 방지를 위한 사전 핸드셰이크 순서**, **브로커 장애(`rc=3`) 격리** 등 프로덕션 수준의 정밀한 가드레일이 통합 보고서 Rev.2에 완벽히 보강되었습니다.
---
## 2. 결함별 진위 검토 및 심층 분석
### 2.1 결함 ①: `multi-agent-mux-delegate-job` 워커 실패 시 레지스트리 미갱신 (Fail-Silent 버그)
- **판정**: **실재하는 핵심 결함 (CONFIRMED REAL, P0/P1)**
- **실측 및 재현 결과**:
1. **이슈 지목 위치(`:358-362`)의 진위**:
- `_phase == "worker"`에서 `job_status != "completed"`일 때 `break` 후 레지스트리(`registry.py status --set error`) 갱신 없이 함수 끝에서 로그 경로를 출력하며 `exit 0`으로 종료되는 현상이 정확히 확인되었습니다.
- 동일한 결함이 리뷰어 단계(`:375-378`) 조기 탈출 분기에도 동일하게 존재합니다.
2. **오케스트레이터 실사용 경로(`--type direct:227`)의 숨은 결함 (전원 공통 발견)**:
- 상위 오케스트레이터(`lib_py/loop/runner.py:271` 및 `run_loop.sh`)는 루프 내부에서 `--type loop`가 아닌 **`--type direct`**로 에이전트 작업을 위임합니다.
- direct 경로(`:227`)는 `run_agent` 실행 후 `wait "$sub_pid" || true`로 구독자 실패를 삼켜버리고, 상태 전이를 전혀 거치지 않은 채 `exit 0`을 반환합니다.
- 따라서 이슈가 언급한 루프 분기뿐만 아니라 **오케스트레이터가 실제로 타는 direct 경로 역시 완전히 침묵(Fail-Silent)**하고 있었습니다.
3. **파급 효과 (65분 Hang)**:
- 상위 루프의 `wait_for_job`은 `completed`, `error`, `cancelled` 3개 터미널 상태만 종료 조건으로 인식합니다.
- 구독자가 120초 idle timeout(`sub_rc=2`)으로 죽었음에도 레지스트리가 `pending` 또는 `running`으로 방치되어 상위 루프가 기본값인 **3,900초(65분) 동안 블로킹**됩니다.
- 실제 운영 레지스트리 포렌식 결과 `93a44347`, `2961b822`, `ee242671` 3건의 실운영 작업이 정확히 이 결함으로 장시간 교착 상태에 방치되었던 사실이 실증되었습니다.
### 2.2 결함 ②: 에이전트 이벤트 발행과 TUI 복귀 간의 레이스 컨디션
- **판정**: **실재하는 설계 결함 (CONFIRMED REAL, P1)**
- **실측 및 재현 결과**:
1. **비동기 상태 불일치 레이스**:
- 에이전트 프로세스가 MQTT로 `completed` 이벤트를 발행한 직후에도 터미널 화면은 마크다운 렌더링, 버퍼 플러시, 툴 호출 정리 등으로 인해 여전히 `working/busy` 상태일 수 있습니다.
- 실측 결과 Codex 등 대형 모델의 경우 `completed` 발행 후 TUI가 `done`으로 떨어지는 데 최대 31초가 소요되기도 했습니다.
2. **프롬프트 묵살 및 유실**:
- 다음 단계(리뷰어 등)가 즉시 프롬프트를 전송하면 TUI가 입력을 무시하거나 첫 글자/단어가 잘린 채 주입되어 문맥이 깨진 채 실행되거나 무응답 상태에 빠집니다.
3. **두 결함 간의 악순환 증폭**:
- 결함 ②(TUI 미준비 프롬프트 유실) 발생 → 워커 무응답 → 구독자 120초 타임아웃(`sub_rc=2`) → 결함 ①(Fail-Silent) 발동 → 레지스트리 `pending/running` 방치 → 상위 루프 65분 영구 교착(Hang).
---
## 3. 수정 난이도 및 공수 산정 (Consensus)
| 영역 | 난이도 | 예상 공수 | 핵심 변경 대상 |
| :--- | :---: | :---: | :--- |
| **결함 ① (Fail-Closed CAS)** | **중하 (Low-Med)** | 1.0 ~ 1.5 MD | `skills/.../multi-agent-mux-delegate-job`, `lib_py/delegation/engine.py` |
| **결함 ② (TUI 턴 핸드셰이크)** | **중 (Medium)** | 1.0 ~ 1.5 MD | `.agents/skills/multi-agent-mux-create/scripts/lib.sh` (`send_keys_safe`), Herdr API 연동 |
| **통합 테스트 & 다중 에이전트 실측** | **중 (Medium)** | 1.0 ~ 1.5 MD | 4개 에이전트(Claude/Grok/Codex/OpenCode) 실기동 E2E 검증, Mock 단위 테스트 |
| **총계** | **중 (Medium)** | **3.0 ~ 4.5 Engineer-Days** | 안전하고 통제된 점진적 구현 가능 |
---
## 4. 상세 기술 아키텍처 및 구현 사양 (Rev. 2 보강)
### 4.1 결함 ① 해결책: 레지스트리 Fail-Closed 및 CAS 엔진 연동
1. **표준 CAS 전이(`deadline_timeout`) 활용**:
- 임의의 신규 CLI 플래그(`--expect-status`)나 운영자 강제 오버라이드를 발명하지 않고, 이미 검증된 `lib_py/delegation/engine.py:50`의 `deadline_timeout` 전이를 호출합니다.
- `deadline_timeout`은 잡이 `pending` 또는 `running`일 때만 원자적으로 `error`로 전이하며, 구독자 타임아웃 직후 백엔드에서 늦게 도착한 `completed` 이벤트가 이미 커밋된 경우 `"conflicting error after terminal completed; refusing"`으로 안전하게 거부(No-op)합니다.
- `expected_dispatch_token`을 전달하여 이전 시도의 늦은 타임아웃이 재시도 잡을 오염시키는 ABA 레이스를 원천 차단합니다.
2. **`multi-agent-mux-delegate-job` 공통 종료 헬퍼 (`finalize_unfinished`) 도입**:
- direct 경로(`:227`) 및 loop/discuss 경로(`:358`, `:375`)에 공통 적용.
- 구독자 종료 시 `wait "$sub_pid"` 수집 및 미완료 잡에 대해 `finalize_unfinished`를 호출하여 상태를 Fail-Closed 처리.
- 래퍼 자체도 자식 구독자 프로세스를 안전하게 수거(`kill "$sub_pid" 2>/dev/null; wait "$sub_pid"`)하여 3,600초 고아 프로세스 방지.
3. **브로커 장애(`rc=3`)와 워커 실패 격리 (B-15 계약 준수)**:
- 구독자가 `rc=3`(`broker_unavailable`)으로 종료되었으나 디스크 상에 이벤트가 살아있을 가능성이 있는 경우, 즉시 실패로 단정하지 않고 잡 데드라인까지 레지스트리를 재확인하여 브로커 일시 순단에 의한 거짓 실패를 방지합니다.
4. **리테인 이벤트 오염 방지 (O-1)**:
- loop/discuss 모드 실패 시 MQTT에 `error` 이벤트를 retain 상태로 발행하지 않아, 재시도 시 이전 에러 이벤트가 즉시 재수신되는 현상을 방지합니다.
5. **오케스트레이터 러너 Fail-Fast 연결**:
- `lib_py/loop/runner.py:delegate_job`이 래퍼 실패(rc≠0) 시에도 `registered job:` 출력을 파싱하여 `wait_for_job`에 넘기도록 보장 (디스크가 이미 `error`이므로 1초 내 False 반환하여 65분 교착 원천 차단).
### 4.2 결함 ② 해결책: TUI 턴 핸드셰이크 시퀀스 및 예산 보강
1. **핸드셰이크 실행 순서 (구독자 시작 전 배치)**:
- **중요**: `wait_for_agent_idle` 핸드셰이크는 반드시 **구독자(`job_subscriber.py`) 기동 전**에 완료되어야 합니다.
- 구독자 실행 후에 대기할 경우, 에이전트의 유휴 대기 시간(15~30초)이 구독자의 120초 idle timeout 예산을 잠식(자가 포식)하는 결함이 발생합니다.
2. **유휴 대기 예산 확대 (15초 → 120초)**:
- Codex 등 복잡한 마크다운/도구 출력을 렌더링하는 대형 모델은 `completed` 이벤트 후 TUI가 완전히 `done`으로 복귀하는 데 실측 31초가 걸렸습니다.
- 따라서 15초 하드코딩 대신 기본 120초(`SKS_IDLE_TIMEOUT_MS=120000`)를 적용하고 환경변수로 유연하게 조절할 수 있도록 합니다.
3. **Herdr 네이티브 대기 API 우선 사용 및 Fallback 견고화**:
- `herdr agent wait <session> --until idle --until done --timeout "$SKS_IDLE_TIMEOUT_MS"`를 우선 호출.
- `lib_py.loop.watcher.wait_once` 메커니즘을 재사용하여 쉘 중복 구현을 방지.
- 헤드리스 환경 등 `agent_status`가 `unknown`인 환경에서는 기존의 `_pane_quiescent` 정밀 휴리스틱으로 우아하게 Fallback.
4. **수락 확인 및 이전 턴 잔여 토큰 오판 방지**:
- 키 전송 후 `herdr agent prompt --wait --until working` 수락 확인.
- Fallback 경로에서 이전 턴의 잔여 busy 토큰(`esc to interrupt` 등)이 키 전송 전 캡처 화면에 이미 존재했던 경우, 이를 새 입력의 작업 시작 근거로 오판하지 않도록 사전 스냅샷과 비교 검증.
---
## 5. 단계별 실행 계획 (5-Phase Roadmap)
- **Phase 1: 레지스트리 CAS 표준 연동 및 delegate-job Fail-Closed 구현**
- `engine.py` `deadline_timeout` 호출 경로 확립
- `multi-agent-mux-delegate-job` 내 `direct`(:227) 및 `loop/discuss` 종료 정리부 일원화
- **Phase 2: `send_keys_safe` 사전 유휴 핸드셰이크(Pre-Subscriber Idle Wait) 구현**
- `SKS_IDLE_TIMEOUT_MS` 기본 120초 지원
- `herdr agent wait` 1차 게이트 및 잔여 토큰 오판 방지
- **Phase 3: 오케스트레이터 러너 Fail-Fast 방어막 보강**
- `lib_py/loop/runner.py` 예외 및 비정상 종료 시 조기 수거 연결
- **Phase 4: 단위/계약 격리 회귀 테스트 슈트 구축**
- `tests/test_issue6_fail_closed.py`
- `tests/test_issue6_turn_handshake.py`
- 기존 750개 pytest 100% 무결성 검증
- **Phase 5: 4개 실기동 에이전트(Claude, Grok, Codex, OpenCode) 대상 E2E 검증**
- 타임아웃 주입 및 TUI 연속 프롬프트 주입 실측 통과 확인
---
## 6. 결론
Issue #6은 코드베이스의 구조적 결함이라기보다, **비동기 이벤트 분산 환경에서 발생하는 상태 불일치(Event vs TUI)와 비정상 종료 시의 예외 처리 누락(Fail-Silent)**이 맞물려 발생한 전형적인 분산 시스템 레이스 컨디션입니다.
모든 리뷰어가 진단과 해결책에 완전히 합의하였고, 2차 라운드를 통해 엣지케이스까지 방어 사양이 완벽히 수립되었으므로 본 Rev.2 사양에 따라 즉시 구현에 착수할 수 있습니다.
@@ -0,0 +1,387 @@
# Layout Engine 개선 계획 (Rev.2) — 결정론적 2×K 그리드
- **Planner**: `planner-reviewer-claude-01`
- **Creator sign-off**: `creator-grok-01` (job `8cfaecd3`) — 구현 착수 가능
- **Job**: `8722045f` (Rev.1 = `29924fd4`; 이의 = `b907f997`)
- **개정 사유**: `creator-grok-01` 이의제기 수용 (홀짝 반전 금지, max_cols 3중 배선)
- **검증**: BSP 시뮬레이터 + 격리 워크스페이스 실측(`w16`/`w17`) + 2026-08-26 코드 재실측 (`layout.py`, `lib.sh:435`, `.mam.env.example:144-148`, `tests/test_layout.py`)
---
## 0. Rev.1 대비 변경 요약
| # | 항목 | Rev.1 | **Rev.2** |
|---|---|---|---|
| **C-1** | 헤드리스 결정 규칙 | "홀짝 반전" (§6.1) | **홀짝 폐기.** GUI 와 **동일 결정표** 공유 (§4.2) |
| **C-2** | `max_columns` 배선 | 시그니처 기본값 2 | **`_env_int(default=2)` + `lib.sh --max-cols` 동시 적용** (§4.5) |
| **C-3** | GUI 채우기 규칙 | singleton 휴리스틱 | **열 페인 수 기반**(`max_rows` 일반화) (§4.1) |
| **C-4** | 궤적 표 | `(3,2)→(3,3)` (3행) | `max_rows=2` 와 **모순 해소** — 4페인에서 정지 (§4.1) |
| **C-5** | `.mam.env.example` | 미언급 | `MAM_MAX_PANE_COLS` 문서 기본값 갱신 대상에 추가 (§4.5) |
**이의제기 3건 모두 인용(SUSTAINED)합니다.** C-3·C-4·C-5 는 이의제기가 드러낸 제 계획서의 추가 결함으로, 자진 정정합니다.
§1~§3(근본 원인 분석·실측 증거)은 Rev.1 그대로 유효하므로 §11 에 요약만 남깁니다.
---
## 1. C-1 인용 — 홀짝 반전은 n=3 에서 GUI 와 갈라진다
### 이의제기 검증
현행 헤드리스(`layout.py:113-125`)는 `n % 2` 로 기하를 흉내 냅니다. Rev.1 §6.1 이 "반전"이라고만 적었으므로, 구현자가 문자 그대로 뒤집으면:
| n | 홀짝 반전 결과 | GUI(Rev.2 §4.1) | 판정 |
|---|---|---|---|
| 1 | `right` | `right` | ✅ |
| 2 | `down` | `down` | ✅ |
| 3 | **`right`** | **`down`** | 🔴 **갈라짐 — 3열을 염** |
| 4 | `down` | `overflow` | 🔴 |
0×0 에서는 열 그룹핑이 불가능하므로 잘못된 `right` 가 **GUI 보다 먼저, 더 조용히** 3열을 만듭니다. 이의제기가 정확합니다.
### 근본 원인
**열 채우기는 `n % 2` 로 표현되지 않습니다.** 패리티는 "직전에 무엇을 했는가"를 인코딩할 뿐, "각 열이 얼마나 찼는가"를 모릅니다. Rev.1 은 이를 "반전"이라는 한 단어로 넘겨 구현자에게 잘못된 자유도를 남겼습니다.
### 기존 테스트가 고정 중인 옛 계약
`tests/test_layout.py:380-414` `test_headless_max_columns_growth_guard` 는 현행 홀짝을 명시적으로 고정합니다:
```python
d2 = compute_2xk_layout(headless(2), max_columns=2) # right
d3 = compute_2xk_layout(headless(3), max_columns=2) # down
d5 = compute_2xk_layout(headless(5), max_columns=2) # down, despite cap
assert compute_2xk_layout(headless(4)).direction == "right" # 무제한일 때
```
`n=2 → right` 와 `n=4 → right` 단언은 Rev.2 계약과 **정면 충돌**하므로 W2 커밋에서 함께 갱신해야 합니다(§7.2).
---
## 2. 핵심 설계 — 단일 결정표 (Single Decision Table)
**GUI 분기와 헤드리스 분기는 같은 결정표를 쓴다.** 차이는 *상태를 어떻게 관측하는가*뿐이며, *무엇을 결정하는가*는 동일합니다.
```
상태: cols = 열별 페인 수 리스트, capacity = max_columns × max_rows
관측: GUI → x 좌표 그룹핑으로 cols 산출
헤드리스 → 생성 순서로 cols 추론 (§4.2)
결정표 (공통):
① len(cols) < max_columns 그리고 전고 페인 존재 → RIGHT (새 열)
② 가장 적은 열의 페인 수 < max_rows → DOWN (그 열 채우기)
③ 그 외 → OVERFLOW
```
이 표가 유일한 진실 원천이며, 두 분기는 이를 **호출만** 합니다.
---
## 3. 궤적 (C-4 정정)
`max_columns=2`, `max_rows=2` (capacity 4) 기준. n = **현재 페인 수**, 결정은 *다음* 페인용입니다.
| n | 상태 `(a,b)` | 규칙 | 결정 | 결과 |
|---|---|---|---|---|
| 1 | `(1,-)` | ① | **`right`** on p1 | `(1,1)` |
| 2 | `(1,1)` | ② | **`down`** on 열1 최하단 | `(2,1)` |
| 3 | `(2,1)` | ② | **`down`** on 열2 최하단 | `(2,2)` ← **2×2 완성** |
| 4 | `(2,2)` | ③ | **`overflow`** | 새 워크스페이스 |
> **Rev.1 정정**: Rev.1 §4.1 은 궤적을 `(3,2) → (3,3)` 까지 적었으나, 같은 문서 §4.4 가 `max_rows=2` 를 제안하여 **자기모순**이었습니다. Rev.2 는 `max_rows=2` 기준으로 4페인에서 정지합니다. `max_rows=3` 을 열면 궤적이 `(3,2) → (3,3)` 으로 자연히 연장되며, 그때는 §5 행 균등화가 선행되어야 합니다.
---
## 4. 알고리즘 명세
### 4.1 GUI 분기 (C-3 — singleton 휴리스틱 폐기)
현행 `fill_singleton_column`(`layout.py:147-159`)은 `len(col) == 1` 만 봅니다. 이는 **`max_rows=2` 에서만 우연히 맞고**, `max_rows=3` 에서는 `(2,2)` 상태에 singleton 이 없어 새 열을 시도하다 캡에 걸려 **조기 overflow** 합니다. 열 페인 수 기반으로 일반화합니다.
```python
def _decide(cols, area_h, max_columns, max_rows, min_cols, min_rows):
# ① 새 열: 전고 페인이 있을 때만 (R-2)
if len(cols) < max_columns:
fh = _full_height_pane(cols[-1], area_h)
if fh is not None:
if fh.width > 0 and fh.width // 2 < min_cols:
return OVERFLOW("column_width_overflow", fh)
return RIGHT("new_column_right", fh)
# 전고 페인이 없으면 새 열을 열 수 없다 → ②로 폴백
# ② 가장 적은 열을 채운다 (동률이면 좌측 우선 — 결정론)
shortest = min(cols, key=lambda c: (len(c), c[0].x))
if len(shortest) < max_rows:
bottom = shortest[-1] # y 정렬 후 최하단
if min_rows > 0 and bottom.height > 0 and bottom.height // 2 < min_rows:
return OVERFLOW("row_height_overflow", bottom)
return DOWN("fill_column", bottom)
# ③
return OVERFLOW("grid_capacity_reached", cols[-1][0])
```
`_full_height_pane` (R-2 처방):
```python
def _full_height_pane(col, area_h, tol=2):
"""열 전체 높이를 점유하는 단일 페인. 없으면 None."""
if len(col) != 1:
return None
return col[0] if (area_h <= 0 or abs(col[0].height - area_h) <= tol) else None
```
**동률 시 좌측 우선**(`(len(c), c[0].x)`)은 결정론 보장을 위한 필수 타이브레이커입니다. `min()` 은 첫 최소값을 반환하지만 `cols` 정렬이 바뀌면 결과가 흔들리므로 명시합니다.
### 4.2 헤드리스 분기 (C-1 처방 — 생성 순서로 열 추론)
0×0 에서도 **생성 순서가 열을 결정**합니다. `right` 후 `p1`=열1, `p2`=열2 이고, 이후 `down` 채우기는 열을 번갈아 갑니다. 따라서 인덱스 `i`(0-based)의 페인은 열 `i % max_columns` 에 속합니다.
```python
def _decide_headless(panes, max_columns, max_rows):
n = len(panes)
if n >= max_columns * max_rows:
return OVERFLOW("grid_capacity_reached", panes[-1])
if n < max_columns:
return RIGHT("new_column_right", panes[n - 1])
return DOWN("fill_column", panes[n - max_columns])
```
**타깃 선택 근거**: `panes[n - max_columns]` 는 다음에 채울 열의 **최하단 페인**입니다.
| n | `n - max_columns` | 타깃 | 들어가는 열 |
|---|---|---|---|
| 2 | 0 | `p1` | 열1 → `(2,1)` ✅ |
| 3 | 1 | `p2` | 열2 → `(2,2)` ✅ |
| 4 | 2 | `p3` | 열1 (max_rows=3 일 때) ✅ |
| 5 | 3 | `p4` | 열2 ✅ |
**주의**: 헤드리스에서 `default_anchor_id`(lib.sh 의 `--sample-pane`)를 타깃으로 쓰면 **안 됩니다.** lib.sh 는 워크스페이스의 *첫* 페인을 넘기므로, 그것을 계속 타깃하면 한 열만 깊어집니다. 현행 코드의 `anchor = default_anchor_id or panes[-1]` 는 이 경로에서 **제거**해야 하며, `default_anchor_id` 는 페인이 0개일 때의 폴백으로만 남깁니다.
### 4.3 결정표 공유 강제 (구조적 보증)
두 분기가 갈라지지 않도록 `compute_2xk_layout` 은 **관측 → 공통 결정** 2단으로 재구성합니다:
```python
def compute_2xk_layout(data, min_cols=15, min_rows=0, max_columns=2, max_rows=2, default_anchor_id=None):
panes = extract_panes(data)
if not panes:
return RIGHT("no_panes_default", default_anchor_id or "")
if all(p.width <= 0 or p.height <= 0 for p in panes):
return _decide_headless(panes, max_columns, max_rows) # ← 같은 표
cols = _group_columns(panes)
return _decide(cols, _area_height(data, panes), max_columns, max_rows, min_cols, min_rows)
```
§7.2 의 parity 테스트가 이 공유를 **계약으로 고정**합니다.
### 4.4 파라미터 요약
| 변수 | 현재 | Rev.2 | 근거 |
|---|---|---|---|
| `MAM_MAX_PANE_COLS` | unset(무제한) | **2** | "2×K" 의 2를 실제로 강제 |
| `MAM_MAX_PANE_ROWS` | 없음 | **2** (신규) | §5 균등화 전까지 보장 구간 |
| `MAM_MIN_PANE_COLS` | 15 | 유지 | 2열 상한 하에서 역할 축소 |
| `MAM_MIN_PANE_ROWS` | 0 | 유지 | 상동 |
### 4.5 C-2 인용 — `max_columns` 배선 (실측 확인)
이의제기의 부수 지적을 코드로 확인했습니다.
```python
# layout.py:203 ← default= 없음 → env 미설정 시 None
parser.add_argument("--max-cols", type=int, default=_env_int("MAM_MAX_COLS", "MAM_MAX_PANE_COLS"))
# layout.py:217-223 ← 항상 전달
decision = compute_2xk_layout(..., max_columns=args.max_cols, ...)
```
`None` 이 **무조건 전달**되므로 시그니처 기본값 `2` 는 CLI 경로에서 **절대 적용되지 않습니다.** 그리고 `lib.sh:432` 는 `--max-cols` 를 **아예 넘기지 않습니다**(grep 결과 `lib.sh` 내 0건).
즉 **lib.sh → layout.py 경로가 유일한 생산 경로인데, 거기서 캡이 영원히 `None`** 입니다. Rev.1 의 W4 는 프로덕션에 무효였습니다.
Creator 재실측 (2026-08-26): `lib.sh` 호출은 **435행**이다 (`:432` 는 구버전 번호). `--max-cols` / `--max-rows` 인자는 여전히 없다.
**필수 3중 조치 (같은 커밋)**:
```python
# 1) layout.py main()
parser.add_argument("--max-cols", type=int, default=_env_int("MAM_MAX_COLS", "MAM_MAX_PANE_COLS", default=2))
parser.add_argument("--max-rows", type=int, default=_env_int("MAM_MAX_ROWS", "MAM_MAX_PANE_ROWS", default=2))
# compute_2xk_layout(...) 시그니처 기본값도 2. CLI가 None을 넘기면 시그니처 기본은 죽는다.
```
```bash
# 2) lib.sh (~line 435, _herdr split 경로)
python3 -m lib_py.layout --min-cols "${MAM_MIN_PANE_COLS:-15}" --min-rows "${MAM_MIN_PANE_ROWS:-0}" \
--max-cols "${MAM_MAX_PANE_COLS:-2}" --max-rows "${MAM_MAX_PANE_ROWS:-2}" --sample-pane "$sample_pane"
```
```
# 3) .mam.env.example:146-148 (C-5)
#default: 2 ← 현재 "(unset -> no column cap)" 이고 예시가 =3 이라 이중으로 어긋남
# MAM_MAX_PANE_COLS=2
# (신규 블록) MAM_MAX_PANE_ROWS=2
```
> **C-5 추가 발견**: `.mam.env.example:147` 은 기본값을 "(unset → no column cap)" 로, `:148` 예시는 `=3` 으로 적어 **문서 자체가 이미 불일치**합니다. Rev.2 값으로 양쪽을 함께 정정하십시오.
**W4 회귀 가드** (§7.2에 포함):
```python
def test_max_cols_default_reaches_cli_path(): ... # env 없이 --json 실행 시 4페인에서 overflow
def test_lib_sh_passes_max_cols_and_rows(): ... # lib.sh 소스 문자열 가드
```
---
## 5. 행 균등화 — `max_rows ≥ 3` 의 전제조건
BSP 단일 분할은 **한 페인만** 이등분하므로 형제 높이가 안 바뀝니다. 높이 78, 2페인(각 39)인 열에 1개를 더하면 `{39, 19, 20}` 이 되고 `--ratio` 를 써도 형제는 그대로입니다. **3행 균등은 분할만으로 불가능**하며 `herdr pane resize --pane <id> --direction up|down --amount <f>` 정규화 패스가 필요합니다.
따라서 **`max_rows` 기본값 2 는 임의 선택이 아니라 "균등을 보장할 수 있는 최대치"** 입니다. §6 W6 완료 전에는 3행을 열지 마십시오(D2).
---
## 6. WBS
| 단계 | 작업 | 파일 | 비고 |
|---|---|---|---|
| **W1** | `_full_height_pane`, `_group_columns` 추출 | `layout.py` | |
| **W2** | **공통 결정표 + GUI/헤드리스 양 분기 동시 전환** | `layout.py` | **C-1. "1줄" 아님** |
| **W3** | 헤드리스 타깃 `panes[n - max_columns]`, anchor 오용 제거 | `layout.py` | C-1 |
| **W4** | `max_cols`/`max_rows` **3중 배선** | `layout.py`, `lib.sh` (현재 435행 호출), `.mam.env.example` | **C-2·C-5** |
| **W5** | `grid_health()` + `--health` | `layout.py` | 진단 |
| **W6** | ratio 정규화 리컨사일러 | 신규 `lib_py/layout_repair.py` | §5 |
| **W7** | 리컨사일러 배선 | `create/resume/reconcile` | |
| **W8** | 테스트 (§7) | `tests/test_layout.py` | |
### 6.1 W2 범위 정정 (C-1)
Rev.1 은 W2 를 **"핵심 1줄"** 이라 적었습니다. **이 표현을 철회합니다.** W2 는 최소한 다음을 **하나의 커밋**에 포함해야 합니다:
1. GUI 분기를 §4.1 결정표로 교체
2. 헤드리스 분기를 §4.2 결정표로 교체 (**홀짝 로직 삭제**)
3. 두 분기가 같은 `_decide*` 계층을 호출하도록 구조 정리 (§4.3)
4. `test_headless_max_columns_growth_guard` 등 옛 계약 테스트 갱신
**분리 커밋 금지**: GUI 만 바꾸고 헤드리스를 남기면 §1 표의 n=3 갈라짐이 그대로 생산에 들어갑니다.
---
## 7. 테스트 계획
### 7.1 누적 시퀀스 가드 (Rev.1 유지 — 최중요)
단일 결정만 단언하는 현행 방식은 R-1 을 통과시켰습니다. **BSP 시뮬레이터를 테스트 헬퍼로 승격**합니다.
```python
def test_four_panes_form_clean_2x2():
panes = [{"id": "p1", "x": 0, "y": 0, "w": 277, "h": 78}]
for _ in range(3):
d = compute_2xk_layout(_payload(panes))
assert not d.is_overflow
panes = _bsp_split(panes, d.target_pane_id, d.direction)
assert len(panes) == 4
assert max(p["w"] for p in panes) - min(p["w"] for p in panes) <= 2
assert max(p["h"] for p in panes) - min(p["h"] for p in panes) <= 2
def test_fifth_pane_overflows():
... # capacity 4 → 4페인 상태에서 overflow
```
### 7.2 GUI ↔ 헤드리스 parity (C-1 처방 — 확장)
Rev.1 은 `n=1` 만 단언했습니다. 이의제기대로 **전 구간**을 단언합니다:
```python
@pytest.mark.parametrize("n,expected", [(1,"right"), (2,"down"), (3,"down"), (4,"overflow")])
def test_headless_matches_gui_decision(n, expected):
hl = compute_2xk_layout(_headless(n), max_columns=2, max_rows=2)
assert hl.direction == expected, f"headless n={n}"
def test_headless_gui_direction_parity_full_sequence():
"""같은 n 에서 두 분기의 direction 이 항상 일치한다."""
panes = [{"id": "p1", "x": 0, "y": 0, "w": 277, "h": 78}]
for n in range(1, 5):
gui = compute_2xk_layout(_payload(panes), max_columns=2, max_rows=2)
hl = compute_2xk_layout(_headless(n), max_columns=2, max_rows=2)
assert gui.direction == hl.direction, f"divergence at n={n}"
if gui.is_overflow:
break
panes = _bsp_split(panes, gui.target_pane_id, gui.direction)
def test_headless_fills_alternating_columns():
"""C-1: n=2 는 p1, n=3 은 p2 를 타깃해야 한 열만 깊어지지 않는다."""
assert compute_2xk_layout(_headless(2), max_columns=2, max_rows=2).target_pane_id == "p1"
assert compute_2xk_layout(_headless(3), max_columns=2, max_rows=2).target_pane_id == "p2"
def test_headless_ignores_sample_pane_anchor():
"""§4.2: --sample-pane 이 채우기 타깃을 오염시키지 않는다."""
d = compute_2xk_layout(_headless(3), max_columns=2, max_rows=2, default_anchor_id="p1")
assert d.target_pane_id == "p2"
```
### 7.3 갱신 대상 기존 테스트
| 테스트 | 충돌 단언 | 조치 |
|---|---|---|
| `test_headless_max_columns_growth_guard:399` | `n=2 → right` | → `down` |
| 〃 `:409` | `n=5 → down` (캡 무시) | capacity 규칙으로 재작성 |
| 〃 `:414` | `n=4 무제한 → right` | 기본 캡 2 하에서 재정의 |
| `test_headless_0x0_transitions:142` | 홀짝 전제 | 전면 재작성 |
| `test_j1*` (min_cols/rows) | 영향 없음(명시 전달) | 유지 |
### 7.4 W4 배선 가드
§4.5 의 두 테스트. **env 미설정 상태**에서 CLI 경로가 실제로 캡을 적용하는지 확인하는 것이 핵심입니다.
---
## 8. 리스크
| 리스크 | 영향 | 완화 |
|---|---|---|
| **GUI/헤드리스 분리 커밋** | n=3 갈라짐이 조용히 생산 진입 | §6.1 단일 커밋 강제 + §7.2 parity 테스트 |
| **W4 배선 누락** | 캡이 `None` 으로 남아 Rev.2 전체가 무효 | §4.5 3중 조치 + §7.4 가드 |
| 헤드리스 anchor 오용 | 한 열만 깊어짐 | §4.2 주의 + `test_headless_ignores_sample_pane_anchor` |
| 기존 테스트 대량 실패 | 계약 변경이라 불가피 | §7.3 목록대로 갱신 |
| capacity 4 로 워크스페이스 증가 | 5+ 에이전트에서 워크스페이스 수↑ | 의도된 트레이드오프(D1) |
---
## 9. 결정 필요 사항
| ID | 항목 | 권장 |
|---|---|---|
| **D1** | `max_columns=2`, `max_rows=2` (capacity 4) 수용 | **수용** — 4 에이전트 2×2 목표와 일치 |
| **D2** | 3행 개방 시점 | W6 정규화 완료 후 |
| **D3** | 리컨사일러 자동 재배치 범위 | ratio 정규화까지만 자동 |
| **D4** | 기존 왜곡 워크스페이스 | 진단만, 복구 수동 |
---
## 10. 이의제기 대응 정리
| 이의 | 판정 | 반영 |
|---|---|---|
| 홀짝 반전 시 n=3 갈라짐 | ✅ **인용** | §1, §4.2, §6.1, §7.2 |
| `max_columns` 배선 누락 | ✅ **인용** (실측 확인) | §4.5, §7.4 |
| parity 테스트가 n=1 만 단언 | ✅ **인용** | §7.2 전 구간 파라미터화 |
| *(자진 정정)* singleton 휴리스틱 비일반성 | — | §4.1 |
| *(자진 정정)* 궤적 표 ↔ `max_rows=2` 모순 | — | §3 |
| *(자진 발견)* `.mam.env.example` 자체 불일치 | — | §4.5 C-5 |
---
## 11. Rev.1 근거 요약 (변경 없음)
- **herdr = 엄격 BSP**: `split` 은 대상 페인 rect 만 이등분(격리 `w16` 실측).
- **R-1**: `down` 우선 시 하단 페인이 전폭으로 남아 **2×2 도달 불가**. 시뮬레이션상 N=4 에서 widths `{138,139,277}`, heights `{19,20,39}`.
- **R-2**: 전고 페인이 없으면 `right` 는 반쪽 열만 생성.
- **해법 실증**: `right` 우선 → `down` ×2 → widths `[138,139]`, heights `[39]` 완전 균등(격리 `w17` 실측). 트리 구조가 살아있는 `w15` 와 동일.
---
## 12. 결론
이의제기 3건을 모두 인용하며, 그 과정에서 제 계획서의 추가 결함 3건(C-3·C-4·C-5)을 자진 정정했습니다.
Rev.1 의 가장 위험한 표현은 **"핵심 1줄"** 이었습니다. 근본 원인 진단은 옳았으나, 처방의 범위를 과소 표기하여 구현자가 GUI 만 고치고 헤드리스를 홀짝 반전으로 처리할 여지를 남겼습니다. Rev.2 는 이를 **단일 결정표 공유**로 구조적으로 차단하고(§4.3), parity 테스트로 계약을 고정합니다(§7.2).
`max_columns` 배선 지적은 특히 중요합니다 — 이것이 없으면 **Rev.2 전체가 프로덕션에서 무효**입니다. lib.sh 가 `--max-cols` 를 넘기지 않고 `_env_int` 가 `None` 을 반환하는 이중 누락이라, 시그니처 기본값만 바꾸는 수정은 테스트만 통과하고 실사용에서는 아무 효과가 없었을 것입니다.
---
## 13. Creator 구현 착수 메모 (job 8cfaecd3)
코드와 문서를 다시 읽었다. Rev.2 결정표·WBS·테스트 계획은 구현에 충분하다. 아래만 구현 시 그대로 따른다.
1. **착수 커밋 범위**: W1+W2+W3+W4+W8 을 **한 커밋**. W5(`--health`)와 W6–W7(리컨사일러)은 후속. 결정 엔진이 틀린 채로 치유를 붙이지 않는다.
2. **`_decide` vs `_decide_headless`**: 0×0 에는 전고 페인이 없으므로 기하 `_decide`를 그대로 호출할 수 없다. 두 함수가 §3 궤적에서 **direction이 항상 같으면** 같은 표다. 공유의 증명은 한 함수가 아니라 §7.2 parity 테스트다.
3. **`_area_height`**: herdr `result.layout.area.height`가 있으면 그것을 쓰고, 없으면 `max(p.y + p.height for p in panes)`.
4. **lib.sh 435**: `--max-cols`/`--max-rows`를 명시 전달. env 미설정 시 `:-2`.
5. **`.mam.env.example:144-148`**: `#default: 2`, 예시 `MAM_MAX_PANE_COLS=2`, 신규 `MAM_MAX_PANE_ROWS=2`. 현재 `#default: (unset -> no column cap)` + 예시 `=3` 불일치를 함께 고친다.
6. **기존 테스트**: `test_1_pane_split_down` (`direction == "down"`), `test_headless_0x0_transitions`, `test_headless_max_columns_growth_guard` 는 W2와 같은 커밋에서 새 계약으로 교체한다. `min_cols`/`min_rows`를 명시 전달하는 `test_j1*` 는 유지.
이 문서는 구현 스펙이다. D1–D4 는 수용된 것으로 보고, 구현 중 뒤집지 않는다.
+1 -1
View File
@@ -200,7 +200,7 @@ class NewAgentAdapter(BaseAgentAdapter):
| Agent Type | Target CLI / Tool | Session Storage Format | Auth Strategy | Ready Tokens Pattern | Complexity Tier | Estimated Effort | | Agent Type | Target CLI / Tool | Session Storage Format | Auth Strategy | Ready Tokens Pattern | Complexity Tier | Estimated Effort |
|---|---|---|---|---|:---:|:---:| |---|---|---|---|---|:---:|:---:|
| **OpenCode** | `opencode` (CLI / TUI) | JSON files in `~/.opencode/sessions/` | Local token / API key | `OpenCode\|Chat\|Welcome` | **Tier 1 (Low)** | ~0.5 day | | **OpenCode** | `opencode` (CLI / TUI) | JSON files in `~/.opencode/sessions/` | Local token / API key | `OpenCode\|Chat\|Welcome` | **Tier 1 (Low)** | ~0.5 day |
| **Codex CLI** | `codex` / `openai-codex` | JSONL in `~/.codex/projects/` | API Key (`OPENAI_API_KEY`) | `OpenAI Codex\|Assistant\|❯` | **Tier 1 (Low)** | ~0.5 day | | **Codex CLI** | `codex` | Rollouts in `~/.codex/sessions/` & SQLite `state_*.sqlite` | `auth.json` / `OPENAI_API_KEY` | `Codex\|Ask Codex to do anything` | **Implemented (v4.2.0)** | Done |
| **Kimi CLI** | `kimi` (Moonshot CLI) | SQLite DB in `~/.kimi/history.db` | API Key in `~/.kimi/config` | `Kimi\|Moonshot\|Chat` | **Tier 1 (Low)** | ~0.5 day | | **Kimi CLI** | `kimi` (Moonshot CLI) | SQLite DB in `~/.kimi/history.db` | API Key in `~/.kimi/config` | `Kimi\|Moonshot\|Chat` | **Tier 1 (Low)** | ~0.5 day |
| **Grok-Build** | `grok` / `grok-build` | JSON in `~/.grok/sessions/` | Token file / Env var | `Grok\|xAI\|Building` | **Tier 1 (Low)** | ~0.5 day | | **Grok-Build** | `grok` / `grok-build` | JSON in `~/.grok/sessions/` | Token file / Env var | `Grok\|xAI\|Building` | **Tier 1 (Low)** | ~0.5 day |
| **Cursor CLI** | `cursor` (Headless/RPC) | State DB in `~/.cursor/` or RPC port | OAuth / Cookie | `Cursor\|Connected\|Listening` | **Tier 2 (Medium)** | ~1.5 days | | **Cursor CLI** | `cursor` (Headless/RPC) | State DB in `~/.cursor/` or RPC port | OAuth / Cookie | `Cursor\|Connected\|Listening` | **Tier 2 (Medium)** | ~1.5 days |
@@ -0,0 +1,18 @@
# Report: Job e30b9201 — Refined Cline Removal Plan (Rev.2) per `creator-agy-01` Challenge
**Durable output (updated in place)**: [.agents/reports/planner-reviewer-claude-01/plan-264c3b5d.md](../../../.agents/reports/planner-reviewer-claude-01/plan-264c3b5d.md)
## Summary
`creator-agy-01` challenged Rev.1's test-retargeting strategy (§5) and doc-scope decision (§6), identifying one core blind spot and two supporting gaps. **All accepted — no `[REBUT:]` filed**, after independently re-verifying each claim:
1. **Core blind spot**: Rev.1 proposed retargeting the 2-tier readiness tests by pre-exporting `MAM_STRONG_READY_TOKENS`/`MAM_WEAK_READY_TOKENS` env vars directly. I re-checked `lib.sh` myself and confirmed this would skip `wait_for_tui_ready`'s `python -m lib_py.agents facts <agent>` bridge call entirely (it's gated behind an `[ -z "$strong_tokens" ]` check) — since cline was the only real adapter with non-degenerate 2-tier values, this would leave the bridge's handling of genuinely-differentiated strong/weak tokens completely untested once cline is gone. **Fixed**: retarget to a test-local mock adapter instead, keeping the real facts bridge in the loop.
2. **`test_c8` gap**: Rev.1 only swapped the modal *text*, missing that the test's session name (`my-project-worker-cline-01`) drives dynamic agent resolution → `facts cline` — a synthetic modal string wouldn't fix that the session name itself would fail to resolve once cline's adapter is deleted. **Fixed**: retarget the whole test to `claude`, using claude's own real `modal_tokens` value (`Try the new fullscreen renderer?`, verified present in `claude.py`), preserving the complete E2E path with an agent that isn't being removed.
3. Added a new adapter-contract assertion (all 4 remaining agents' default 2-tier fields round-trip correctly through the facts bridge) to close the coverage gap explicitly.
4. **`docs/NEW_AGENT_INTEGRATION_GUIDE.md`**: I'd placed this in "do not touch," but verified myself it's a live copy-paste template with `cline` hardcoded into 5 sample sites (adapter dict, `lib.sh` kind mapping, binary tuple, diagram, test assertion) — moved into the update-scope in §6.
Full Rev.2 text with the corrected test-retargeting specifications is in the durable plan linked above.
**Process note**: still pending a fresh `[VERDICT: PASS]` before implementation begins, per `MULTI_AGENT_RULES.md` §3.1.
[VERDICT: N/A — planning artifact, review pending]
@@ -0,0 +1,22 @@
# Report: Job a7a2da9f — Refined Plan (Rev.2) per `creator-agy-01` Challenge
**Durable output (updated in place)**: [.agents/reports/planner-reviewer-claude-01/plan-28f9b565.md](../../../.agents/reports/planner-reviewer-claude-01/plan-28f9b565.md)
## Summary
`creator-agy-01` filed a formal architectural challenge (job `cd64ae0b`) against Rev.1's hermes audit plan, identifying that **Rev.1's own proposed §2.4 fix for the `C-ambiguous` bug was itself regressive**: it widened `reconcile.sh`'s candidate query but still relied on `adapters/hermes.py::verify_artifact()`, which checks the shared `~/.hermes/state.db` file's mtime rather than the individual session row's `started_at`. Since all hermes sessions across all workspaces share one `state.db` file, any recent write makes the file-level epoch check pass for essentially every historical session row — meaning Rev.1's fix would have turned "never detects `C-ambiguous`" into "permanently false-positives `C-ambiguous` in any workspace with prior hermes history." A second, lower-severity point noted that `hermes --resume` auto-`cd`s into its recorded `cwd`, risking divergence from MAM's symlink-canonicalized path model, and recommended adding `--no-restore-cwd`.
**Disposition**: I independently re-verified both claims against the actual code (`hermes.py::verify_artifact`'s file-mtime check; `verify_session.py`'s `epoch = row.get("herdr_session_epoch", 0)`) before accepting — both are correct. **Both accepted — no `[REBUT:]` filed.**
## What changed in Rev.2
- Added §0 changelog cross-referencing each challenge point.
- §2.4 replaced (not appended) with a two-layer fix: `verify_artifact()` now checks the session row's own `started_at` instead of the shared file's mtime, and `reconcile.sh`'s query adds a `started_at >= ?` SQL-level filter alongside the existing candidate-widening + sibling-exclusion logic from Rev.1.
- §2.1's canonical `resume_spec()` and §2.6 updated to add `--no-restore-cwd` alongside `--yolo --accept-hooks`.
- Comparison table and Definition of Done updated; the regression test requirement now explicitly covers **both** directions (under-detection and the Rev.1 over-detection regression), not just the original under-detection case.
Full Rev.2 text, including both corrected code diffs, is in the durable report linked above.
**Process note**: Per `MULTI_AGENT_RULES.md` §3.1, this Rev.2 still requires a fresh `[VERDICT: PASS]` before the §2.4 fix — the highest-risk change in this plan — is merged.
[VERDICT: N/A — planning artifact, review pending]
@@ -0,0 +1,368 @@
# 🧭 Layout Engine 개선 계획 (Rev.2) — 결정론적 2×K 그리드
- **Planner**: `planner-reviewer-claude-01`
- **Job**: `8722045f` (Rev.1 = `29924fd4`)
- **개정 사유**: `creator-grok-01` 이의제기(`b907f997`) 수용
- **검증**: BSP 시뮬레이터 + 격리 워크스페이스 실측(`w16`/`w17`, 정리 완료) + 코드 실측
---
## 0. Rev.1 대비 변경 요약
| # | 항목 | Rev.1 | **Rev.2** |
|---|---|---|---|
| **C-1** | 헤드리스 결정 규칙 | "홀짝 반전" (§6.1) | **홀짝 폐기.** GUI 와 **동일 결정표** 공유 (§4.2) |
| **C-2** | `max_columns` 배선 | 시그니처 기본값 2 | **`_env_int(default=2)` + `lib.sh --max-cols` 동시 적용** (§4.5) |
| **C-3** | GUI 채우기 규칙 | singleton 휴리스틱 | **열 페인 수 기반**(`max_rows` 일반화) (§4.1) |
| **C-4** | 궤적 표 | `(3,2)→(3,3)` (3행) | `max_rows=2` 와 **모순 해소** — 4페인에서 정지 (§4.1) |
| **C-5** | `.mam.env.example` | 미언급 | `MAM_MAX_PANE_COLS` 문서 기본값 갱신 대상에 추가 (§4.5) |
**이의제기 3건 모두 인용(SUSTAINED)합니다.** C-3·C-4·C-5 는 이의제기가 드러낸 제 계획서의 추가 결함으로, 자진 정정합니다.
§1~§3(근본 원인 분석·실측 증거)은 Rev.1 그대로 유효하므로 §11 에 요약만 남깁니다.
---
## 1. C-1 인용 — 홀짝 반전은 n=3 에서 GUI 와 갈라진다
### 이의제기 검증
현행 헤드리스(`layout.py:113-125`)는 `n % 2` 로 기하를 흉내 냅니다. Rev.1 §6.1 이 "반전"이라고만 적었으므로, 구현자가 문자 그대로 뒤집으면:
| n | 홀짝 반전 결과 | GUI(Rev.2 §4.1) | 판정 |
|---|---|---|---|
| 1 | `right` | `right` | ✅ |
| 2 | `down` | `down` | ✅ |
| 3 | **`right`** | **`down`** | 🔴 **갈라짐 — 3열을 염** |
| 4 | `down` | `overflow` | 🔴 |
0×0 에서는 열 그룹핑이 불가능하므로 잘못된 `right` 가 **GUI 보다 먼저, 더 조용히** 3열을 만듭니다. 이의제기가 정확합니다.
### 근본 원인
**열 채우기는 `n % 2` 로 표현되지 않습니다.** 패리티는 "직전에 무엇을 했는가"를 인코딩할 뿐, "각 열이 얼마나 찼는가"를 모릅니다. Rev.1 은 이를 "반전"이라는 한 단어로 넘겨 구현자에게 잘못된 자유도를 남겼습니다.
### 기존 테스트가 고정 중인 옛 계약
`tests/test_layout.py:380-414` `test_headless_max_columns_growth_guard` 는 현행 홀짝을 명시적으로 고정합니다:
```python
d2 = compute_2xk_layout(headless(2), max_columns=2) # right
d3 = compute_2xk_layout(headless(3), max_columns=2) # down
d5 = compute_2xk_layout(headless(5), max_columns=2) # down, despite cap
assert compute_2xk_layout(headless(4)).direction == "right" # 무제한일 때
```
`n=2 → right` 와 `n=4 → right` 단언은 Rev.2 계약과 **정면 충돌**하므로 W2 커밋에서 함께 갱신해야 합니다(§7.2).
---
## 2. 핵심 설계 — 단일 결정표 (Single Decision Table)
**GUI 분기와 헤드리스 분기는 같은 결정표를 쓴다.** 차이는 *상태를 어떻게 관측하는가*뿐이며, *무엇을 결정하는가*는 동일합니다.
```
상태: cols = 열별 페인 수 리스트, capacity = max_columns × max_rows
관측: GUI → x 좌표 그룹핑으로 cols 산출
헤드리스 → 생성 순서로 cols 추론 (§4.2)
결정표 (공통):
① len(cols) < max_columns 그리고 전고 페인 존재 → RIGHT (새 열)
② 가장 적은 열의 페인 수 < max_rows → DOWN (그 열 채우기)
③ 그 외 → OVERFLOW
```
이 표가 유일한 진실 원천이며, 두 분기는 이를 **호출만** 합니다.
---
## 3. 궤적 (C-4 정정)
`max_columns=2`, `max_rows=2` (capacity 4) 기준. n = **현재 페인 수**, 결정은 *다음* 페인용입니다.
| n | 상태 `(a,b)` | 규칙 | 결정 | 결과 |
|---|---|---|---|---|
| 1 | `(1,-)` | ① | **`right`** on p1 | `(1,1)` |
| 2 | `(1,1)` | ② | **`down`** on 열1 최하단 | `(2,1)` |
| 3 | `(2,1)` | ② | **`down`** on 열2 최하단 | `(2,2)` ← **2×2 완성** |
| 4 | `(2,2)` | ③ | **`overflow`** | 새 워크스페이스 |
> **Rev.1 정정**: Rev.1 §4.1 은 궤적을 `(3,2) → (3,3)` 까지 적었으나, 같은 문서 §4.4 가 `max_rows=2` 를 제안하여 **자기모순**이었습니다. Rev.2 는 `max_rows=2` 기준으로 4페인에서 정지합니다. `max_rows=3` 을 열면 궤적이 `(3,2) → (3,3)` 으로 자연히 연장되며, 그때는 §5 행 균등화가 선행되어야 합니다.
---
## 4. 알고리즘 명세
### 4.1 GUI 분기 (C-3 — singleton 휴리스틱 폐기)
현행 `fill_singleton_column`(`layout.py:147-159`)은 `len(col) == 1` 만 봅니다. 이는 **`max_rows=2` 에서만 우연히 맞고**, `max_rows=3` 에서는 `(2,2)` 상태에 singleton 이 없어 새 열을 시도하다 캡에 걸려 **조기 overflow** 합니다. 열 페인 수 기반으로 일반화합니다.
```python
def _decide(cols, area_h, max_columns, max_rows, min_cols, min_rows):
# ① 새 열: 전고 페인이 있을 때만 (R-2)
if len(cols) < max_columns:
fh = _full_height_pane(cols[-1], area_h)
if fh is not None:
if fh.width > 0 and fh.width // 2 < min_cols:
return OVERFLOW("column_width_overflow", fh)
return RIGHT("new_column_right", fh)
# 전고 페인이 없으면 새 열을 열 수 없다 → ②로 폴백
# ② 가장 적은 열을 채운다 (동률이면 좌측 우선 — 결정론)
shortest = min(cols, key=lambda c: (len(c), c[0].x))
if len(shortest) < max_rows:
bottom = shortest[-1] # y 정렬 후 최하단
if min_rows > 0 and bottom.height > 0 and bottom.height // 2 < min_rows:
return OVERFLOW("row_height_overflow", bottom)
return DOWN("fill_column", bottom)
# ③
return OVERFLOW("grid_capacity_reached", cols[-1][0])
```
`_full_height_pane` (R-2 처방):
```python
def _full_height_pane(col, area_h, tol=2):
"""열 전체 높이를 점유하는 단일 페인. 없으면 None."""
if len(col) != 1:
return None
return col[0] if (area_h <= 0 or abs(col[0].height - area_h) <= tol) else None
```
**동률 시 좌측 우선**(`(len(c), c[0].x)`)은 결정론 보장을 위한 필수 타이브레이커입니다. `min()` 은 첫 최소값을 반환하지만 `cols` 정렬이 바뀌면 결과가 흔들리므로 명시합니다.
### 4.2 헤드리스 분기 (C-1 처방 — 생성 순서로 열 추론)
0×0 에서도 **생성 순서가 열을 결정**합니다. `right` 후 `p1`=열1, `p2`=열2 이고, 이후 `down` 채우기는 열을 번갈아 갑니다. 따라서 인덱스 `i`(0-based)의 페인은 열 `i % max_columns` 에 속합니다.
```python
def _decide_headless(panes, max_columns, max_rows):
n = len(panes)
if n >= max_columns * max_rows:
return OVERFLOW("grid_capacity_reached", panes[-1])
if n < max_columns:
return RIGHT("new_column_right", panes[n - 1])
return DOWN("fill_column", panes[n - max_columns])
```
**타깃 선택 근거**: `panes[n - max_columns]` 는 다음에 채울 열의 **최하단 페인**입니다.
| n | `n - max_columns` | 타깃 | 들어가는 열 |
|---|---|---|---|
| 2 | 0 | `p1` | 열1 → `(2,1)` ✅ |
| 3 | 1 | `p2` | 열2 → `(2,2)` ✅ |
| 4 | 2 | `p3` | 열1 (max_rows=3 일 때) ✅ |
| 5 | 3 | `p4` | 열2 ✅ |
**주의**: 헤드리스에서 `default_anchor_id`(lib.sh 의 `--sample-pane`)를 타깃으로 쓰면 **안 됩니다.** lib.sh 는 워크스페이스의 *첫* 페인을 넘기므로, 그것을 계속 타깃하면 한 열만 깊어집니다. 현행 코드의 `anchor = default_anchor_id or panes[-1]` 는 이 경로에서 **제거**해야 하며, `default_anchor_id` 는 페인이 0개일 때의 폴백으로만 남깁니다.
### 4.3 결정표 공유 강제 (구조적 보증)
두 분기가 갈라지지 않도록 `compute_2xk_layout` 은 **관측 → 공통 결정** 2단으로 재구성합니다:
```python
def compute_2xk_layout(data, min_cols=15, min_rows=0, max_columns=2, max_rows=2, default_anchor_id=None):
panes = extract_panes(data)
if not panes:
return RIGHT("no_panes_default", default_anchor_id or "")
if all(p.width <= 0 or p.height <= 0 for p in panes):
return _decide_headless(panes, max_columns, max_rows) # ← 같은 표
cols = _group_columns(panes)
return _decide(cols, _area_height(data, panes), max_columns, max_rows, min_cols, min_rows)
```
§7.2 의 parity 테스트가 이 공유를 **계약으로 고정**합니다.
### 4.4 파라미터 요약
| 변수 | 현재 | Rev.2 | 근거 |
|---|---|---|---|
| `MAM_MAX_PANE_COLS` | unset(무제한) | **2** | "2×K" 의 2를 실제로 강제 |
| `MAM_MAX_PANE_ROWS` | 없음 | **2** (신규) | §5 균등화 전까지 보장 구간 |
| `MAM_MIN_PANE_COLS` | 15 | 유지 | 2열 상한 하에서 역할 축소 |
| `MAM_MIN_PANE_ROWS` | 0 | 유지 | 상동 |
### 4.5 C-2 인용 — `max_columns` 배선 (실측 확인)
이의제기의 부수 지적을 코드로 확인했습니다.
```python
# layout.py:203 ← default= 없음 → env 미설정 시 None
parser.add_argument("--max-cols", type=int, default=_env_int("MAM_MAX_COLS", "MAM_MAX_PANE_COLS"))
# layout.py:217-223 ← 항상 전달
decision = compute_2xk_layout(..., max_columns=args.max_cols, ...)
```
`None` 이 **무조건 전달**되므로 시그니처 기본값 `2` 는 CLI 경로에서 **절대 적용되지 않습니다.** 그리고 `lib.sh:432` 는 `--max-cols` 를 **아예 넘기지 않습니다**(grep 결과 `lib.sh` 내 0건).
즉 **lib.sh → layout.py 경로가 유일한 생산 경로인데, 거기서 캡이 영원히 `None`** 입니다. Rev.1 의 W4 는 프로덕션에 무효였습니다.
**필수 3중 조치 (같은 커밋)**:
```python
# 1) layout.py:203
parser.add_argument("--max-cols", type=int, default=_env_int("MAM_MAX_COLS", "MAM_MAX_PANE_COLS", default=2))
parser.add_argument("--max-rows", type=int, default=_env_int("MAM_MAX_ROWS", "MAM_MAX_PANE_ROWS", default=2))
```
```bash
# 2) lib.sh:432
python3 -m lib_py.layout --min-cols "${MAM_MIN_PANE_COLS:-15}" --min-rows "${MAM_MIN_PANE_ROWS:-0}" \
--max-cols "${MAM_MAX_PANE_COLS:-2}" --max-rows "${MAM_MAX_PANE_ROWS:-2}" --sample-pane "$sample_pane"
```
```
# 3) .mam.env.example:146-148 (C-5)
#default: 2 ← 현재 "(unset -> no column cap)" 이고 예시가 =3 이라 이중으로 어긋남
# MAM_MAX_PANE_COLS=2
# (신규 블록) MAM_MAX_PANE_ROWS=2
```
> **C-5 추가 발견**: `.mam.env.example:147` 은 기본값을 "(unset → no column cap)" 로, `:148` 예시는 `=3` 으로 적어 **문서 자체가 이미 불일치**합니다. Rev.2 값으로 양쪽을 함께 정정하십시오.
**W4 회귀 가드** (§7.2에 포함):
```python
def test_max_cols_default_reaches_cli_path(): ... # env 없이 --json 실행 시 4페인에서 overflow
def test_lib_sh_passes_max_cols_and_rows(): ... # lib.sh 소스 문자열 가드
```
---
## 5. 행 균등화 — `max_rows ≥ 3` 의 전제조건
BSP 단일 분할은 **한 페인만** 이등분하므로 형제 높이가 안 바뀝니다. 높이 78, 2페인(각 39)인 열에 1개를 더하면 `{39, 19, 20}` 이 되고 `--ratio` 를 써도 형제는 그대로입니다. **3행 균등은 분할만으로 불가능**하며 `herdr pane resize --pane <id> --direction up|down --amount <f>` 정규화 패스가 필요합니다.
따라서 **`max_rows` 기본값 2 는 임의 선택이 아니라 "균등을 보장할 수 있는 최대치"** 입니다. §6 W6 완료 전에는 3행을 열지 마십시오(D2).
---
## 6. WBS
| 단계 | 작업 | 파일 | 비고 |
|---|---|---|---|
| **W1** | `_full_height_pane`, `_group_columns` 추출 | `layout.py` | |
| **W2** | **공통 결정표 + GUI/헤드리스 양 분기 동시 전환** | `layout.py` | **C-1. "1줄" 아님** |
| **W3** | 헤드리스 타깃 `panes[n - max_columns]`, anchor 오용 제거 | `layout.py` | C-1 |
| **W4** | `max_cols`/`max_rows` **3중 배선** | `layout.py`, `lib.sh:432`, `.mam.env.example` | **C-2·C-5** |
| **W5** | `grid_health()` + `--health` | `layout.py` | 진단 |
| **W6** | ratio 정규화 리컨사일러 | 신규 `lib_py/layout_repair.py` | §5 |
| **W7** | 리컨사일러 배선 | `create/resume/reconcile` | |
| **W8** | 테스트 (§7) | `tests/test_layout.py` | |
### 6.1 W2 범위 정정 (C-1)
Rev.1 은 W2 를 **"핵심 1줄"** 이라 적었습니다. **이 표현을 철회합니다.** W2 는 최소한 다음을 **하나의 커밋**에 포함해야 합니다:
1. GUI 분기를 §4.1 결정표로 교체
2. 헤드리스 분기를 §4.2 결정표로 교체 (**홀짝 로직 삭제**)
3. 두 분기가 같은 `_decide*` 계층을 호출하도록 구조 정리 (§4.3)
4. `test_headless_max_columns_growth_guard` 등 옛 계약 테스트 갱신
**분리 커밋 금지**: GUI 만 바꾸고 헤드리스를 남기면 §1 표의 n=3 갈라짐이 그대로 생산에 들어갑니다.
---
## 7. 테스트 계획
### 7.1 누적 시퀀스 가드 (Rev.1 유지 — 최중요)
단일 결정만 단언하는 현행 방식은 R-1 을 통과시켰습니다. **BSP 시뮬레이터를 테스트 헬퍼로 승격**합니다.
```python
def test_four_panes_form_clean_2x2():
panes = [{"id": "p1", "x": 0, "y": 0, "w": 277, "h": 78}]
for _ in range(3):
d = compute_2xk_layout(_payload(panes))
assert not d.is_overflow
panes = _bsp_split(panes, d.target_pane_id, d.direction)
assert len(panes) == 4
assert max(p["w"] for p in panes) - min(p["w"] for p in panes) <= 2
assert max(p["h"] for p in panes) - min(p["h"] for p in panes) <= 2
def test_fifth_pane_overflows():
... # capacity 4 → 4페인 상태에서 overflow
```
### 7.2 GUI ↔ 헤드리스 parity (C-1 처방 — 확장)
Rev.1 은 `n=1` 만 단언했습니다. 이의제기대로 **전 구간**을 단언합니다:
```python
@pytest.mark.parametrize("n,expected", [(1,"right"), (2,"down"), (3,"down"), (4,"overflow")])
def test_headless_matches_gui_decision(n, expected):
hl = compute_2xk_layout(_headless(n), max_columns=2, max_rows=2)
assert hl.direction == expected, f"headless n={n}"
def test_headless_gui_direction_parity_full_sequence():
"""같은 n 에서 두 분기의 direction 이 항상 일치한다."""
panes = [{"id": "p1", "x": 0, "y": 0, "w": 277, "h": 78}]
for n in range(1, 5):
gui = compute_2xk_layout(_payload(panes), max_columns=2, max_rows=2)
hl = compute_2xk_layout(_headless(n), max_columns=2, max_rows=2)
assert gui.direction == hl.direction, f"divergence at n={n}"
if gui.is_overflow:
break
panes = _bsp_split(panes, gui.target_pane_id, gui.direction)
def test_headless_fills_alternating_columns():
"""C-1: n=2 는 p1, n=3 은 p2 를 타깃해야 한 열만 깊어지지 않는다."""
assert compute_2xk_layout(_headless(2), max_columns=2, max_rows=2).target_pane_id == "p1"
assert compute_2xk_layout(_headless(3), max_columns=2, max_rows=2).target_pane_id == "p2"
def test_headless_ignores_sample_pane_anchor():
"""§4.2: --sample-pane 이 채우기 타깃을 오염시키지 않는다."""
d = compute_2xk_layout(_headless(3), max_columns=2, max_rows=2, default_anchor_id="p1")
assert d.target_pane_id == "p2"
```
### 7.3 갱신 대상 기존 테스트
| 테스트 | 충돌 단언 | 조치 |
|---|---|---|
| `test_headless_max_columns_growth_guard:399` | `n=2 → right` | → `down` |
| 〃 `:409` | `n=5 → down` (캡 무시) | capacity 규칙으로 재작성 |
| 〃 `:414` | `n=4 무제한 → right` | 기본 캡 2 하에서 재정의 |
| `test_headless_0x0_transitions:142` | 홀짝 전제 | 전면 재작성 |
| `test_j1*` (min_cols/rows) | 영향 없음(명시 전달) | 유지 |
### 7.4 W4 배선 가드
§4.5 의 두 테스트. **env 미설정 상태**에서 CLI 경로가 실제로 캡을 적용하는지 확인하는 것이 핵심입니다.
---
## 8. 리스크
| 리스크 | 영향 | 완화 |
|---|---|---|
| **GUI/헤드리스 분리 커밋** | n=3 갈라짐이 조용히 생산 진입 | §6.1 단일 커밋 강제 + §7.2 parity 테스트 |
| **W4 배선 누락** | 캡이 `None` 으로 남아 Rev.2 전체가 무효 | §4.5 3중 조치 + §7.4 가드 |
| 헤드리스 anchor 오용 | 한 열만 깊어짐 | §4.2 주의 + `test_headless_ignores_sample_pane_anchor` |
| 기존 테스트 대량 실패 | 계약 변경이라 불가피 | §7.3 목록대로 갱신 |
| capacity 4 로 워크스페이스 증가 | 5+ 에이전트에서 워크스페이스 수↑ | 의도된 트레이드오프(D1) |
---
## 9. 결정 필요 사항
| ID | 항목 | 권장 |
|---|---|---|
| **D1** | `max_columns=2`, `max_rows=2` (capacity 4) 수용 | **수용** — 4 에이전트 2×2 목표와 일치 |
| **D2** | 3행 개방 시점 | W6 정규화 완료 후 |
| **D3** | 리컨사일러 자동 재배치 범위 | ratio 정규화까지만 자동 |
| **D4** | 기존 왜곡 워크스페이스 | 진단만, 복구 수동 |
---
## 10. 이의제기 대응 정리
| 이의 | 판정 | 반영 |
|---|---|---|
| 홀짝 반전 시 n=3 갈라짐 | ✅ **인용** | §1, §4.2, §6.1, §7.2 |
| `max_columns` 배선 누락 | ✅ **인용** (실측 확인) | §4.5, §7.4 |
| parity 테스트가 n=1 만 단언 | ✅ **인용** | §7.2 전 구간 파라미터화 |
| *(자진 정정)* singleton 휴리스틱 비일반성 | — | §4.1 |
| *(자진 정정)* 궤적 표 ↔ `max_rows=2` 모순 | — | §3 |
| *(자진 발견)* `.mam.env.example` 자체 불일치 | — | §4.5 C-5 |
---
## 11. Rev.1 근거 요약 (변경 없음)
- **herdr = 엄격 BSP**: `split` 은 대상 페인 rect 만 이등분(격리 `w16` 실측).
- **R-1**: `down` 우선 시 하단 페인이 전폭으로 남아 **2×2 도달 불가**. 시뮬레이션상 N=4 에서 widths `{138,139,277}`, heights `{19,20,39}`.
- **R-2**: 전고 페인이 없으면 `right` 는 반쪽 열만 생성.
- **해법 실증**: `right` 우선 → `down` ×2 → widths `[138,139]`, heights `[39]` 완전 균등(격리 `w17` 실측). 트리 구조가 살아있는 `w15` 와 동일.
---
## 12. 결론
이의제기 3건을 모두 인용하며, 그 과정에서 제 계획서의 추가 결함 3건(C-3·C-4·C-5)을 자진 정정했습니다.
Rev.1 의 가장 위험한 표현은 **"핵심 1줄"** 이었습니다. 근본 원인 진단은 옳았으나, 처방의 범위를 과소 표기하여 구현자가 GUI 만 고치고 헤드리스를 홀짝 반전으로 처리할 여지를 남겼습니다. Rev.2 는 이를 **단일 결정표 공유**로 구조적으로 차단하고(§4.3), parity 테스트로 계약을 고정합니다(§7.2).
`max_columns` 배선 지적은 특히 중요합니다 — 이것이 없으면 **Rev.2 전체가 프로덕션에서 무효**입니다. lib.sh 가 `--max-cols` 를 넘기지 않고 `_env_int` 가 `None` 을 반환하는 이중 누락이라, 시그니처 기본값만 바꾸는 수정은 테스트만 통과하고 실사용에서는 아무 효과가 없었을 것입니다.
@@ -0,0 +1,463 @@
# 📑 Issue #5 Phase 1 구현 계획서 (Rev.2) — `lib_py/delegation/` 추출 및 장수 MQTT 연결 프로토타입
- **Job ID**: `9aae4233` (Rev.1: `923e9403`) / **Planner**: `planner-reviewer-claude-01`
- **반영한 이의제기**: `creator-claude-01`의 Challenge (Job `c0b9c987`) — D2 shim 부트스트랩의 컨텍스트 충돌
- **Issue**: [Gitea Issue #5](https://git.godopu.com/tmpl/multi-agent-mux/issues/5) — Phase 1 (`implementation_plan.md` Rev.4 §2 Phase 1 행, `task.md` P1-01~P1-03)
- **기준 커밋**: `fc0bd96` (branch `refactor`, working tree clean) / Python `3.9.6` / paho-mqtt `2.1.0` / herdr `0.8.2` / 전체 테스트 수집 **510**
- **문서 성격**: Worker가 그대로 실행할 수 있는 단계별 구현 명세. 모든 인용 행 번호는 라이브 코드로 직접 확인함(§1). Rev.1 대비 변경은 §0-1에 모아 두었고, 본문에는 이미 반영되어 있다.
---
## 0. 요약 (TL;DR)
1. **추출 대상은 `lib.sh` L1833–1941의 위임 블록 5개 함수뿐이다.** L1943 이후(`wait_for_tui_ready`, `send_keys_safe` 등)는 TUI 조작 헬퍼이며 Phase 1 비범위다.
2. **`scripts/{mqtt_common,registry,publish_event,job_subscriber}.py`의 파일 경로는 와이어 계약이다.** 에이전트에게 주입되는 지시문(`create_session.sh:483`, 래퍼 `:197/:318`), SKILL.md, BOOTSTRAP*.md, `deploy/install.sh:103`, 테스트 3종이 리터럴 경로로 호출한다. 구현체는 `lib_py/delegation/`으로 옮기되 `scripts/*.py`는 **동일 모듈 객체를 가리키는 호환 shim**으로 남긴다.
3. **shim은 `sys.path`를 건드리지 않고 `lib_py.delegation` 패키지만 자기 옆 트리에 "프로세스당 1회" 바인딩한다(Rev.2, D2).** 이의제기가 실증한 대로 `sys.path.insert(0, ...)` 방식은 pytest에서 위임과 무관한 `lib_py.*`까지 임시 사본으로 가로챈다. 이의제기가 제안한 "잎(leaf) 모듈 파일 직접 적재"도 재현 결과 비-잎 모듈(`publish_event`)에서 두 트리가 섞이므로 채택하지 않고, **패키지 단위 bind-once**로 확정했다(§1-8 근거).
4. **현재 셸 헬퍼 3종을 직접 검증하는 테스트는 0개다.** 이동 전에 특성화(golden) 테스트를 먼저 추가한다(P1-00).
5. **장수 연결 프로토타입은 라이브러리 전용이다.** CLI는 프로세스 단위로 종료되므로 재사용 이득이 없다. 벤치마크는 결정적 가짜 전송 + 실브로커(정보성) 2모드.
6. **자동완료 정책은 3개 표면에서 한 줄도 바뀌지 않는다.** 테스트로 고정한다.
### 0-1. Rev.1 → Rev.2 변경 내역 (이의제기 반영)
| 이의제기 항목 | Planner 독립 검증 결과 | 계획 변경 |
|---|---|---|
| §1 D2 `sys.path.insert(0)`이 pytest에서 `lib_py` 전체를 샌드박스로 고정 | **재현 확인** (§1-8 표, 변형 `d2_insert0` 시나리오 A: `lib_py.agents`가 sandbox에서 로드) | D2 전면 교체 |
| §2-1 정체성 단정(`is`)이 "같은 트리"를 증명하지 못함 | **동의**. 시나리오 A에서 두 참조가 모두 sandbox인데 단정은 `True` | D2-2 출처(provenance) 단정 PV-1~PV-4 추가, G4 재정의 |
| §2-2 R3 전제("실제 트리에서만 로드")가 D2와 모순 | **동의** | R3을 "수용"에서 "해소"로 재작성 |
| §3 `append`로 바꾸면 freeze가 깨짐 | **동의**. 본 세션 `PYTHONPATH`=라이브 트리, 실행 명령=freeze 경로, `run_loop.sh`에 `PYTHONPATH` 처리 0건 모두 재확인 | D2-1 컨텍스트 우선순위 표 신설 |
| §5-1 "옆 파일 직접 적재(`spec_from_file_location`) + 다르면 교체" | **부분 채택**. 잎 모듈 단독 임포트에서는 동작하나, `publish_event`만 임포트되는 실제 에이전트 호출 형태(C2_pe)에서 `publish_event`=freeze, `mqtt_common`=live로 **혼재**하고 정체성 단정이 `False`가 됨. 진짜 standalone(C1)에서는 부모 패키지 부재로 `ModuleNotFoundError`. 두 샌드박스가 섞이는 시나리오(D)에서도 혼재 | 적재 단위를 **모듈 → 패키지**로 올리고, "가장 가까운 사본으로 교체"가 아니라 **"프로세스당 최초 바인딩 유지(bind-once)"** 로 규칙 변경. standalone은 `lib_py` 부재 시에만 `sys.path.append` 폴백 |
| §5-2 출처 단정 병기 | 채택 | PV-1~PV-4 |
| §5-3 컨텍스트 4종 우선순위 표 + 4종 전부 테스트 | 채택 (6 컨텍스트로 확장) | D2-1, P1-01 테스트 |
| §5-4 세션 위생 테스트 | **부분 채택**. "tmp 경로가 `sys.path`에 없음"은 현행 `test_tier1_unit.py:23`이 샌드박스 scripts 디렉터리를 영구 삽입하므로 이미 실패함. 조건을 "`lib_py` 디렉터리를 포함하는 tmp 경로가 없음"으로 정밀화 | PV-3 |
| §6 D6·설치 경로 안전 확인 | **동의**. `mqtt_common.py`의 `os.environ` 참조는 전부 함수 내부(`:139,:196,:203,:225-233`), 모듈 상수(`:117-128`) env 무관, 나머지 3개 스크립트 `os.environ` 0건, `install.sh:127/131/135` 트리 통째 복사, `install_mam.sh:126` `.agents/` rsync 재확인 | 변경 없음 (P1-04의 `core_files` 추가는 무결성 목록 갱신 목적임을 명시) |
---
## 1. Planner 사전 실측 (라이브 검증 결과)
### 1-1. 추출 범위 경계 (`lib.sh`, 총 2312행)
| 행 | 함수 | 분류 | 비고 |
|---|---|---|---|
| 1833 | 섹션 주석 `multi-agent-mux-delegate-job integration helpers` | 경계 시작 | |
| 1841 | `_delegate_py_bin` | **셸 유지** | 파이썬 인터프리터 자체를 찾는 부트스트랩. L1598(`env_python`), L1660(`atomic_dump_yaml`), `reconcile.sh:67`, `create_session.sh:191/193/215/482`, `stop_session.sh:199`, `resume_session.sh:116/126`에서도 사용. `tests/test_c1_tui_readiness.py:168,513`이 mock으로 덮어씀 |
| 1865 | `_delegate_script` | **셸 유지** | 스크립트 경로 해석. shim이 남으므로 그대로 동작 |
| 1876 | `delegate_submit_job` | 추출 | `registry.py register` 호출, stdout에 JID만 출력 |
| 1897 | `delegate_publish_event` | 추출 | 비치명 계약: 빈 job_id/스크립트 부재/브로커 실패 모두 `return 0` |
| 1912 | `start_watchdog` | 추출 → `ensure_subscriber_daemon` | `pgrep -f "bash <monitor_script> --subscribe"` 선검사 후 `nohup bash reconcile.sh --subscribe --idle-timeout 0` 스폰, PID를 stdout 출력. 스크립트 부재 시 stderr `ERROR: monitor script not found: ...` + `return 1` |
| 1943~ | `wait_for_tui_ready`, `inject_instructions`, `_pane_*`, `send_keys_safe`, `handle_startup_dialogs` | **비범위** | TUI 조작 |
`lib_py`는 `lib.sh:25`(`SKILL_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"` 직후 `export PYTHONPATH="$SKILL_DIR:..."`) 및 `:164`로 임포트 가능해진다. 즉 **어느 트리의 `lib.sh`를 source 했느냐가 그 셸 프로세스의 `lib_py` 트리를 결정**한다. `env_python`(L1583)은 `PYTHONPATH=$SKILL_DIR`를 명시 전달하는 선례.
### 1-2. 셸 헬퍼 호출자 (라이브 트리)
| 호출자 | 헬퍼 | 계약상 의존 |
|---|---|---|
| `create_session.sh:345` | `delegate_submit_job` | `$( )`로 stdout 캡처 → JID |
| `create_session.sh:497,501` | `delegate_publish_event error/started` | 비치명 |
| `create_session.sh:504-505` | `start_watchdog "$JOB" "$WORKSPACE"` | `$( )`로 PID 캡처 후 `echo`만 함(파싱 없음) |
| `stop_session.sh:193,242,322` | `delegate_publish_event progress/cancelled` | `implementation_plan.md` §3-2가 보존 요구 |
| `update_yaml_resumed.sh:257` | `delegate_publish_event progress "resumed"` | 비치명 |
| `run_loop.sh:144-155` | (헬퍼 미사용) 래퍼 `multi-agent-mux-delegate-job`를 직접 실행 | Phase 1 무관 |
### 1-3. 파이썬 표면과 리터럴 경로 계약
- 스크립트 4종: `mqtt_common.py`(670행), `registry.py`(426행), `publish_event.py`(239행), `job_subscriber.py`(339행). 서로를 `import mqtt_common` / `import registry`처럼 **최상위 이름**으로 임포트한다. **다른 `lib_py` 모듈은 하나도 임포트하지 않는다**(`grep -n lib_py scripts/*.py` → 0건; D2의 전제).
- 리터럴 경로 호출자: 래퍼 12개소(`:136,166,197,277,287,318,355,394,400,544,550,571,575,583,586`), `create_session.sh:483`, `SKILL.md:78`, `BOOTSTRAP.md`/`BOOTSTRAP.ko.md:158-180`, `README.md:211`/`README.ko.md:194`, `MESSAGING.md:399`, `deploy/install.sh:103`, `reconcile.sh:98-113`(임베디드 구독자가 scripts 디렉터리를 `sys.path`에 **append** 후 `import mqtt_common, registry`).
- 테스트 임포트 방식: `tests/test_tier1_unit.py:23,571-820`과 `tests/test_tier2_component.py:25`는 샌드박스 scripts 디렉터리를 `sys.path`에 넣고 `import registry, publish_event, job_subscriber, mqtt_common`; `tests/test_tier4_e2e.py:414`는 `publish_event.py`를 서브프로세스로 실행. `tests/conftest.py:10-12`는 **실제** skills 디렉터리를 `sys.path[0]`에 넣고, `mam_sandbox`는 `.agents/skills` 전체를 `tmp_path/skills`와 `tmp_path/.agents/skills`로 복사한다(이동 후 사본에도 `lib_py/delegation/`이 포함됨).
- 본 job과 Rev.1 job의 위임 메시지 자체가 `.../mam-loop-freeze.PfAQNj/.agents/skills/multi-agent-mux-delegate-job/scripts/publish_event.py` 경로를 사용한다. 이때 에이전트 세션의 `PYTHONPATH`는 **라이브 트리**다(실측: `/Users/.../multi-agent-mux/.agents/skills:...`). `run_loop.sh`에는 `PYTHONPATH` 처리가 없고(`grep` 0건) `:14-17`에서 자기 위치 기준 `REPO_ROOT`의 `lib.sh`를 source 하므로 **루프 프로세스 자체는 freeze `lib.sh`가 export한 freeze `PYTHONPATH`** 를 갖는다.
### 1-4. 기존 테스트 커버리지 실측
| 대상 | 커버 테스트 | 비고 |
|---|---|---|
| `publish_event` 실패 시 status/감사로그/seq 소비 | `test_tier1_unit.py` G-1~G-4 (:568-698) | 127.0.0.1:65432 비라우팅 포트, 네트워크 미접촉 |
| `job_subscriber` 디스크 폴백/exit 0·1·3 | G-5~G-9 (:700-836) | |
| 래퍼 rc=3 매핑 리터럴 | G-10 (:838) | **래퍼 텍스트를 건드리면 깨짐** |
| HMAC/retry/topic/reason_code | `test_mqtt_*` (:339-420) | |
| seq 단조 증가, 모니터 중복 잠금 | `test_tier2_component.py:1082, :1007` | |
| `delegate_submit_job` / `delegate_publish_event` / `start_watchdog` | **없음 (0건)** | |
빠른 회귀 부분집합(G-1~G-10 + mqtt + seq + monitor lock): **18 passed in 1.74s**. 이 부분집합의 파일들은 `lib_py`를 모듈 레벨에서 임포트하지 않으므로(`test_tier1_unit.py`의 `lib_py` 사용은 `:848,:873,:902,:947,:978,:1037,:1072` 전부 함수 내부) 이의제기 §4의 지적대로 "샌드박스 shim이 먼저 임포트되는" 시나리오 A에 해당한다 — Rev.2 D2는 이 경우에도 `lib_py.agents` 등을 가로채지 않는다(§1-8).
### 1-5. 자동완료 정책이 구현된 3개 표면 (Phase 1 불변)
1. `publish_event.py:51-56` `EVENT_TO_STATUS` 및 `:227`의 `update_job_status` 동기화.
2. 래퍼 `:335-348` 구독자 exit code → `job_status` 매핑 및 `:394/:400`의 `registry.py status --set completed|error`.
3. `reconcile.sh:125-168` `_MUTATION` + `handle_terminal`.
`run_loop.sh:238-276` `wait_for_job`은 `.mam/jobs/<id>.json`의 `status`를 3초 간격 폴링할 뿐이므로 영향 없음.
### 1-6. 장수 연결의 실측 동기
Rev.1 job의 `started` 이벤트: payload `timestamp` 05:58:49Z → `attempt 1/3 failed: no CONNACK from broker` (05:59:00Z) → 모니터 수신 05:59:01.487Z. 1회 발행 약 12.5초, 원인은 `CONNECT_ACK_TIMEOUT=10`(`publish_event.py:58`)의 1회 실패 + 재연결. Rev.1 `completed` 발행과 본 job의 `started` 발행에서도 동일한 1회 CONNACK 실패가 재현됐다.
### 1-7. 환경 제약
- 로컬 브로커 없음(`mosquitto`, `nats-server`, `docker` 미설치). 벤치마크 실브로커 모드는 정보성.
- `mqtt_common.py:112`에서 `_load_dotenv()`가 **임포트 시점**에 실행되어 `.mam.env`(존재, 0600)를 주입. 루트 탐색은 `__file__` 기준 상향(`.agents` 또는 `.git`).
- B-13 freeze(`run_loop.sh:112-126`)는 `.agents/skills` 전체를 `cp -R` 하므로 `lib_py/delegation/`은 자동 포함(현재 freeze에 `lib_py/` 존재 확인).
- `baseline.md` §5-2 `VALID_STATUSES` 인용은 커밋 `19d798b`에서 `registry.py:38`로 정정 완료(`baseline.md:93`).
### 1-8. 이의제기 재현 및 대안 비교 (Rev.2 신규)
세 shim 변형을 `real`/`sandbox`/`sandbox2`/`freeze` 네 트리(각 `lib_py/{__init__,agents/__init__,delegation/{__init__,mqtt_common,publish_event}}.py` + `scripts/` shim)에 배치하고, `env -u PYTHONPATH`의 새 인터프리터에서 시나리오별로 실행했다. `publish_event`는 `from lib_py.delegation import mqtt_common`을 포함해 **비-잎 모듈**을 모델링한다. 열: 어느 트리에서 로드됐는가.
| 시나리오 (첫 임포트 → 이후) | `d2_insert0` (Rev.1) | `worker_leaf_file` (이의제기 §5-1) | `pkg_bind_once` (**Rev.2 채택**) |
|---|---|---|---|
| A pytest: real on path → sandbox shim(mc, pe) | mc=sb, pe=sb, **agents=sb** ✗ | mc=sb, pe=sb, agents=real | mc=sb, pe=sb, agents=real ✓ |
| A_pe pytest: sandbox shim(**pe만**) | agents=sb ✗ | **pe=sb, pe.dep=real, identity=False** ✗ | pe=sb, pe.dep=sb, identity=True ✓ |
| B pytest: real `lib_py.agents` 먼저 → sandbox shim | 전부 real | mc=sb, pe=sb, agents=real | mc=sb, pe=sb, agents=real ✓ |
| B2 pytest: real `lib_py.delegation` 먼저 → sandbox shim | (미측정) | **alias=sb, pkg=real, identity=False** ✗ | 전부 real, identity=True ✓ |
| C1 standalone(`PYTHONPATH` 없음): freeze shim | 전부 freeze | **`ModuleNotFoundError: lib_py`** ✗ (비-잎 모듈의 내부 임포트가 부모 패키지를 요구) | 전부 freeze ✓ (폴백 append) |
| C2 freeze shim + `PYTHONPATH`=live (mc, pe) | 전부 freeze | 전부 freeze, agents=real | 전부 freeze, agents=real ✓ |
| C2_pe freeze shim(**pe만**) + `PYTHONPATH`=live — **실제 에이전트 호출 형태** | 전부 freeze | **pe=freeze, pe.dep=real, identity=False** ✗ (B-13 부분 상실) | pe=freeze, pe.dep=freeze ✓ |
| D 두 샌드박스: sb shim(mc) → sb2 shim(pe) | agents=sb ✗ | **pe=sb2, pe.dep=sb** 혼재 ✗ | 전부 sb (최초 바인딩 유지) ✓ |
| E sandbox shim(mc) → 이후 `from lib_py.delegation import publish_event` 직접 임포트 | (해당 없음) | 직접 임포트=real, shim=sb 혼재 | 둘 다 sb ✓ |
결론: 이의제기의 **결함 지적은 정확**하고, 제안한 적재 방식은 "잎 모듈을 먼저 임포트하는" 경우에만 성립한다. 결정 기준은 (i) `lib_py.delegation.*`가 한 프로세스 안에서 항상 **단일 트리**일 것, (ii) `lib_py`의 다른 서브패키지는 shim이 **절대 건드리지 않을 것**, (iii) `sys.path` 무변경(standalone 폴백 제외) — 이를 모두 만족하는 것은 패키지 단위 bind-once뿐이다. 재현 하니스는 `tests/fixtures/issue_5/phase1/shim_contexts.py`로 그대로 옮겨 P1-01 테스트에 사용한다(부록 B).
---
## 2. 설계 결정 (Design Decisions)
### D1. 패키지 배치 — 기존 이름 보존, 신규 추가
```
.agents/skills/lib_py/delegation/
__init__.py # 공개 API 재수출: DelegationService, ensure_subscriber_daemon, PersistentPublisher
mqtt_common.py # git mv (scripts/mqtt_common.py) — 내용 변경은 D6·D8 항목만
registry.py # git mv (scripts/registry.py)
publish_event.py # git mv (scripts/publish_event.py) — D7의 함수 분리만
job_subscriber.py # git mv (scripts/job_subscriber.py)
service.py # DelegationService 파사드 (신규)
daemon.py # ensure_subscriber_daemon (신규, start_watchdog 이식)
publisher.py # OneShotPublisher / PersistentPublisher (신규)
cli.py # python -m lib_py.delegation.cli {submit|publish|ensure-daemon} (신규)
__main__.py # cli.main 위임 (신규)
bench.py # 벤치마크 하니스 (신규)
```
- `git mv`로 이동해 이력을 보존한다. 이동한 4개 모듈 내부의 `import mqtt_common` / `import registry` / `from mqtt_common import ...`는 전부 `from lib_py.delegation import mqtt_common, registry` 형태로 바꾼다.
- **패키지 내부 임포트 규칙(테스트로 grep 고정)**: (a) 최상위 이름(`import registry` 등) 금지 — `lib_py.agents.registry`와의 혼동 차단; (b) **`lib_py.delegation` 밖의 어떤 `lib_py` 모듈도 임포트 금지**(`paths`, `state`, `atomic_yaml`, `agents`, `layout`, `workspace_uuid`) — D2에서 부모 `lib_py`와 `lib_py.delegation`이 서로 다른 트리일 수 있으므로(C2), 형제 모듈을 임포트하면 트리가 섞인다. 현재 스크립트는 이미 이 규칙을 만족한다(§1-3).
- Python 3.9 호환 필수: `match`, PEP 604 런타임 유니온, `zip(strict=)` 금지. 게이트에서 `compileall`.
### D2. `scripts/*.py` shim — `lib_py.delegation` 패키지를 자기 옆 트리에 프로세스당 1회 바인딩 (Rev.2)
4개 shim은 아래 블록을 **바이트 동일하게** 포함한다(`{mod}`만 다름). 공유 헬퍼 파일로 빼지 않는 이유: `import _bootstrap` 같은 최상위 이름이 첫 샌드박스에 캐시되어 다른 트리의 shim이 남의 헬퍼를 쓰게 되기 때문이다. 동일성은 테스트로 고정한다.
```python
#!/usr/bin/env python3
"""Compatibility shim — implementation lives in lib_py.delegation.{mod}.
Binds the lib_py.delegation *package* to the tree next to this file, once per
process, without touching sys.path. See docs/contracts/issue-5/... (D2)."""
import importlib, importlib.util, os, sys
_SKILLS = os.path.abspath(os.path.join(os.path.dirname(__file__), "..", ".."))
_PKG = "lib_py.delegation"
if _PKG not in sys.modules: # bind once per process; never rebind
try:
import lib_py # parent resolved normally; shims never rebind it
except ModuleNotFoundError:
sys.path.append(_SKILLS) # standalone only: no lib_py exists anywhere to shadow
import lib_py
_d = os.path.join(_SKILLS, "lib_py", "delegation")
_spec = importlib.util.spec_from_file_location(
_PKG, os.path.join(_d, "__init__.py"), submodule_search_locations=[_d])
_pkg = importlib.util.module_from_spec(_spec)
sys.modules[_PKG] = _pkg # register BEFORE exec so __init__'s own imports resolve here
_spec.loader.exec_module(_pkg)
lib_py.delegation = _pkg
_impl = importlib.import_module(_PKG + ".{mod}") # resolved through the bound package's __path__
if __name__ != "__main__":
sys.modules[__name__] = _impl # `import {mod}` is lib_py.delegation.{mod}
else:
sys.exit(_impl.main())
```
규칙(문서화·테스트 대상):
1. **바인딩 단위는 패키지**다. `lib_py.delegation`이 `sys.modules`에 없을 때만 shim 옆 트리의 `lib_py/delegation/`을 패키지로 등록하고, 이후 모든 `lib_py.delegation.*` 임포트는 그 `__path__` 안에서 해석된다. 잎/비-잎 구분 없이 단일 트리가 보장된다.
2. **bind-once, never rebind.** 이미 바인딩돼 있으면(다른 트리라도) 그대로 쓴다. "가장 가까운 사본으로 교체"는 기존 참조(`sys.modules['mqtt_common']` 별칭 등)와 새 객체를 갈라놓아 정체성·monkeypatch를 깨뜨린다(§1-8 B2·D). 네 컨텍스트 중 한 프로세스가 트리를 바꿔야 하는 경우는 없다.
3. **부모 `lib_py`는 절대 재바인딩하지 않고, `sys.path`도 건드리지 않는다.** 유일한 예외는 `lib_py`가 어디에도 없는 standalone(C1)이며, 이때만 자기 트리를 `append` 한다(가릴 대상이 없으므로 안전).
4. 결과적으로 pytest에서는 위임 패키지만 "최초 shim의 샌드박스 사본(또는 먼저 직접 임포트된 실제 트리)"에 바인딩되고 `lib_py.agents`/`layout`/`state` 등은 항상 실제 트리다. 샌드박스 사본은 `copytree`된 동일 내용이므로 검증 대상 코드는 같다(PV-1이 이를 단정).
5. `mqtt_common.py`의 PEP 562 `__getattr__("LOGS_DIR")`은 실제 모듈에 남아 별칭을 통해 노출. 실행 비트 유지, `--help` 출력 동일.
6. `_load_dotenv`(D6 이후 `ensure_env_loaded`)의 루트 탐색은 실모듈 `__file__` 기준이므로 바인딩된 트리의 루트(저장소 루트 또는 freeze 루트)가 된다 — 이동 전과 동일.
### D2-1. 실행 컨텍스트별 "어느 트리가 이겨야 하는가" (Rev.2)
| # | 컨텍스트 | `lib_py.delegation` 해석 주체 | 이겨야 하는 트리 | Rev.2 결과 | 테스트 |
|---|---|---|---|---|---|
| K1 | 루프 프로세스(`run_loop.sh`가 freeze `lib.sh` source → `PYTHONPATH`=freeze) 및 그 자식(래퍼, `-m lib_py.delegation.cli`) | `PYTHONPATH` | freeze | freeze | K1: `PYTHONPATH=<copy>` + `-m lib_py.delegation.cli --help` |
| K2 | 에이전트 세션(`PYTHONPATH`=live)이 위임 메시지의 **freeze 경로 스크립트**를 실행 | shim 옆 트리 | freeze (B-13) | freeze, `lib_py` 부모는 live(무해: D1(b)) | C2_pe |
| K3 | 라이브 헬퍼(create/stop/resume/reconcile; live `lib.sh` source) | `PYTHONPATH`=live 또는 shim 옆 트리(같음) | live | live | K3: 실제 트리에서 shim 실행 |
| K4 | standalone(`PYTHONPATH` 없음; BOOTSTRAP.md의 수동 명령, 외부 셸) | shim 폴백 append | 자기 트리 | 자기 트리 | C1, C1_pe |
| K5 | pytest 인프로세스(conftest가 실제 트리 삽입, 샌드박스 shim 임포트) | 최초 shim 또는 최초 직접 임포트 | 위임: 최초 바인딩(사본=동일 내용) / **나머지 `lib_py.*`: 실제 트리** | A, A_pe, B, B2, D, E | PV-1~PV-3 |
| K6 | pytest 서브프로세스(e2e `:414`, freeze 시뮬레이션) — 새 인터프리터, `PYTHONPATH`=live 상속 가능 | shim 옆 트리 | 샌드박스 | 샌드박스 | K6: 서브프로세스 JSON 출력 단정 |
### D2-2. 가드 — 정체성만으로는 불충분, 출처(provenance)를 병기 (Rev.2)
- **PV-1 (인프로세스, 각 shim 임포트 직후)**: `mqtt_common is lib_py.delegation.mqtt_common` **그리고** `Path(lib_py.delegation.__path__[0]).resolve()`가 `{실제 skills 디렉터리, pytest basetemp 하위}` 중 하나이며, 4개 별칭(`mqtt_common/registry/publish_event/job_subscriber`)의 `__file__`이 **모두 같은** `__path__[0]` 아래.
- **PV-2 (세션 종료 시, conftest의 session-scope autouse finalizer)**: `lib_py.__file__`, 그리고 `sys.modules`에 있는 모든 `lib_py.<x>` 중 `x != "delegation"`의 `__file__`이 실제 skills 디렉터리 아래. 위반 시 어느 모듈이 어느 tmp 경로에서 왔는지 출력.
- **PV-3 (세션 종료 시 위생)**: `sys.path` 항목 중 basetemp 하위인 것 가운데 `<entry>/lib_py`가 디렉터리인 항목 0개. (scripts 디렉터리 삽입은 `lib_py`를 담지 않으므로 허용 — 현행 `test_tier1_unit.py:23`과 호환.)
- **PV-4 (서브프로세스 매트릭스)**: §1-8의 시나리오 A, A_pe, B, B2, C1, C1_pe, C2, C2_pe, D, E를 실제 이동된 트리의 사본으로 재실행하고 JSON으로 트리명을 받아 단정. K1·K3·K6도 같은 하니스에 포함.
- **PV-5**: 4개 shim의 부트스트랩 블록이 `{mod}` 치환을 제외하고 바이트 동일.
### D3. 셸에 남는 것과 파이썬으로 가는 것
- `_delegate_py_bin`, `_delegate_script`: **셸 유지**. 시그니처·출력 불변.
- `delegate_submit_job`, `delegate_publish_event`, `ensure_subscriber_daemon`(신규 이름) + `start_watchdog`(별칭): 본체를 `python -m lib_py.delegation.cli ...` 호출로 교체. `PYTHONPATH="$SKILL_DIR:${PYTHONPATH:-}"`를 명시 전달(`env_python` L1583과 동일). `-m` 경로는 shim을 거치지 않으므로 D2-1의 K1/K3처럼 `SKILL_DIR` 트리가 결정한다.
- 롤백 스위치 `MAM_DELEGATION_PY`(기본 `1`): `0`이면 기존 인라인 본체(`_*_legacy`)로 분기. 특성화 테스트를 두 경로에 대해 parametrize. legacy 본체 제거는 Phase 4.
```bash
start_watchdog() { ensure_subscriber_daemon "$@"; } # 기존 함수 별칭 보존
ensure_subscriber_daemon() {
if [ "${MAM_DELEGATION_PY:-1}" = "0" ]; then _start_watchdog_legacy "$@"; return $?; fi
PYTHONPATH="$SKILL_DIR:${PYTHONPATH:-}" "$(_delegate_py_bin)" -m lib_py.delegation.cli \
ensure-daemon --job "$1" --workdir "${2:-$PWD}"
}
delegate_publish_event() {
local job_id="$1" event="$2" detail="${3:-}"
[ -n "$job_id" ] || return 0 # 비치명 계약 1
if [ "${MAM_DELEGATION_PY:-1}" = "0" ]; then _delegate_publish_event_legacy "$@"; return $?; fi
PYTHONPATH="$SKILL_DIR:${PYTHONPATH:-}" "$(_delegate_py_bin)" -m lib_py.delegation.cli \
publish --job "$job_id" --event "$event" --detail "$detail" || true # 비치명 계약 2·3
}
```
### D4. `cli.py`는 라우터, 로직은 기존 `main()` 재사용
- `publish` → `publish_event.main(argv)` 그대로 호출(exit 0/1/2, stdout 무출력, 옵션 전부 통과).
- `submit` → `registry.main(["--registry-dir", ..., "register", ...])`. stdout에 JID 한 줄, 로그는 stderr.
- `ensure-daemon` → `daemon.ensure_subscriber_daemon(job_id, workdir)`; stdout PID, exit 0 / 부재 시 stderr 동일 문구 + exit 1.
- 래퍼 `multi-agent-mux-delegate-job`(bash)은 **Phase 1에서 수정하지 않는다**(G-10 보호).
### D5. `daemon.ensure_subscriber_daemon(job_id, workdir) -> int` 의미 보존
| 항목 | 레거시(`lib.sh:1912-1941`) | 파이썬 이식 |
|---|---|---|
| 모니터 스크립트 경로 | `<workdir>/.agents/skills/multi-agent-mux-monitor/scripts/reconcile.sh` | 동일 |
| 부재 시 | stderr `ERROR: monitor script not found: <path>`, rc 1 | 동일 문구·rc |
| 중복 검사 | `pgrep -f "bash <path> --subscribe"` | `subprocess.run(["pgrep","-f",...])` 동일 패턴 |
| 기존 PID 출력 | `echo "$pid"` (다중 매치면 여러 줄) | 동일하게 전량 출력(정리는 Phase 4 후보) |
| 스폰 | `nohup bash <path> --subscribe --idle-timeout 0 </dev/null >> <workdir>/.mam/multi-agent-mux-monitor.log 2>&1 &`, cwd=workdir | `Popen([...], cwd=workdir, stdin=DEVNULL, stdout=log(append), stderr=STDOUT, start_new_session=True, preexec_fn=SIGHUP 무시)` |
| 반환 | 스폰된 PID | 동일 |
| 데몬 자체 중복 방지 | `reconcile.sh:86-95` `.mam/monitor.lock` flock | 변경 없음 |
### D6. 임포트 시점 부작용 제거 — `_load_dotenv()`를 진입점 시점으로
`mqtt_common.py:112`의 모듈 레벨 `_load_dotenv()` 호출을 `ensure_env_loaded()`(멱등, 1회)로 바꾸고 **모든 프로세스 진입점** 첫 줄에서 호출: `publish_event.main`, `job_subscriber.main`, `registry.main`, `cli.main`, `bench.main`, `reconcile.sh` 임베디드 구독자(`import mqtt_common` 직후 1줄). 이의제기 §6이 독립 검증한 대로 `mqtt_common.py`의 env 참조는 전부 함수 내부이고 모듈 상수는 env 무관하므로 값이 달라지는 상수는 없다. `conftest.mam_sandbox`에 `monkeypatch.setenv("MAM_ENV_FILE", str(tmp_path / ".mam.env.absent"))` 추가(`_load_dotenv:48-52`는 명시 파일 부재 시 무로딩).
### D7. 발행 경로 분리 — 전송(transport)만 교체 가능하게
`publish_event.main()`(`:133-235`)을 동작 불변으로 세 조각으로 나눈다.
```python
def prepare_event(job_id, event, detail, data, registry_dir) -> PreparedEvent # load_job, broker cfg, topic, next_seq(소비), build_payload, retain 결정
def record_outcome(prepared, registry_dir, publish_ok, publish_error) -> None # append_event(audit) + registry.append_event + EVENT_TO_STATUS 동기화
def main(argv=None) -> int: # parse → ensure_env_loaded → prepare_event → with_retry(_publish_once) → record_outcome → 0/2
```
- G-1/G-2/G-4의 의미가 `record_outcome` 한 곳에 남는다.
- `publisher.OneShotPublisher.publish(prepared)` = 기존 `_publish_once`.
- `publisher.PersistentPublisher`: 컨텍스트 매니저. 1회 연결 + `loop_start()` + `reconnect_delay_set(1,16)`; `publish(prepared)`는 QoS1 발행 + `wait_for_publish(PUBLISH_ACK_TIMEOUT)`; 미확인 시 예외를 던져 호출자의 `with_retry`가 재시도. 브로커 설정이 다른 job 혼입 시 예외.
- `service.DelegationService(registry_dir, persistent=False)`: `submit_job()`, `publish_event()`, `ensure_subscriber_daemon()`. CLI/셸은 항상 `persistent=False`. Phase 2a 엔진이 `persistent=True`의 첫 소비자.
- 패리티 테스트: 동일 입력·가짜 전송에서 OneShot과 Persistent의 레지스트리(`last_seq`, `status`)·감사 레코드(`published`, `seq`, `retain`, `payload.data.hmac_sig`)가 필드 단위로 동일.
### D8. 벤치마크 — 결정적 지표와 정보성 지표 분리
`python -m lib_py.delegation.bench --n 50 --transport {fake|broker} [--connect-latency-ms 50] --out <json>`
| 지표 | fake 전송(CI에서 단정) | broker 전송(수동, 정보성) |
|---|---|---|
| 연결 수립 횟수 / N회 발행 | OneShot = N, Persistent = 1 (+재연결 수) — 테스트로 고정 | 동일 카운트 실측 |
| 발행당 지연 p50/p95/max | 합성 지연 기준 산술 확인 | 실측 (CONNACK 타임아웃 건수 별도) |
| 프로세스 포크 수(셸 경로) | `delegate_publish_event` 1회당 레거시 3 fork → 신규 2 fork | 분석값 |
결과는 `docs/contracts/issue-5/phase1-benchmark.md`에 환경과 함께 기록. 실브로커 수치는 게이트 조건이 아니다.
### D9. 비범위 및 호환성 계약(재확인)
- 저장소 통합 금지: `lib_py/delegation`은 `lib_py.state`/`lib_py.atomic_yaml`을 임포트하지 않는다 — D1(b)가 이를 포함하는 더 넓은 규칙.
- 스키마 불변: `SCHEMA_VERSION = 1`, 레코드 필드, 토픽, 감사 로그 레이아웃, `<id>.events.log` 형식 전부 불변 → §3 라이브 헬퍼 버전 게이트상 ABI 파괴 없음. K2에서 부모 `lib_py`(live)와 위임 패키지(freeze)가 다른 트리인 것은 D1(b) 덕분에 관측 가능한 차이를 만들지 않는다.
- `job_subscriber`는 이미 실행당 장수 연결이므로 전송 변경 없음.
- 자동완료 관련 코드 일체 추가 금지.
---
## 3. 작업 분해 (WBS) — 순서 고정, 커밋 5개
### P1-00 특성화 테스트 선행 (커밋 1: `test(issue-5): phase 1 delegation characterization suite`)
- **파일**: `tests/test_issue5_phase1_delegation.py`(신규), `tests/conftest.py`(`MAM_ENV_FILE` 1줄 + PV-2/PV-3 session finalizer), `tests/fixtures/issue_5/phase1/`(가짜 `reconcile.sh`, 가짜 `python` 스텁, `shim_contexts.py` 하니스 — 부록 B).
- **셸 헬퍼 golden 테스트** (샌드박스에서 `source lib.sh` 후 실행, `_delegate_py_bin`은 `test_c1_tui_readiness.py:513` 방식으로 스텁):
- C-01 `delegate_publish_event "" started` → rc 0, python 미실행.
- C-02 스크립트 부재 → rc 0.
- C-03 python 스텁 exit 2 → rc 0.
- C-04 정상 경로 argv에 `--job <id> --event <ev> --detail <detail>` 정확히 포함.
- C-05 `delegate_submit_job p a s` → stdout이 스텁의 JID 한 줄과 정확히 동일.
- C-06 `start_watchdog` 스크립트 부재 → stderr 정확 문구, rc 1.
- C-07 신규 스폰 → stdout 숫자 PID, 생존, cwd=workdir, 로그 파일 생성.
- C-08 두 번째 호출 → 동일 PID, 프로세스 수 불변.
- C-09 `start_watchdog` ≡ `ensure_subscriber_daemon` — P1-02 이후 활성.
- `MAM_DELEGATION_PY` ∈ {`0`,`1`} parametrize.
- **CLI 계약 스냅샷**: argparse 파서에서 옵션명·choices·default를 추출해 단정.
- **자동완료 불변 가드**: `EVENT_TO_STATUS` 동등; 래퍼 `:335-348` 리터럴; `reconcile.sh` `_MUTATION` 핵심 4줄 리터럴.
- **PV-2/PV-3 finalizer는 이 커밋에서 이미 활성** — 현행 트리에서 통과해야 한다(shim 도입 전 기준선).
- **완료 기준**: 신규 테스트 전부 통과(레거시 코드 그대로), 전체 스위트 510 + 신규 통과.
### P1-01 패키지 생성·이동·shim (커밋 2: `refactor(issue-5): move delegation scripts into lib_py.delegation with package-bound shims`)
- **파일**: `git mv` 4종, 내부 임포트 교정, `lib_py/delegation/__init__.py`, `scripts/*.py` 4종 shim(D2 블록), `mqtt_common.ensure_env_loaded()`(D6) + 4개 `main()` 및 `reconcile.sh` 임베디드 구독자 1줄.
- **추가 테스트**(Rev.2 확장): PV-1(4 별칭), PV-4 서브프로세스 매트릭스 10 시나리오 + K1/K3/K6, PV-5 shim 동일성, "라이브러리 임포트 후 `os.environ` 키 집합 불변", `ensure_env_loaded` 멱등, D1(a)(b) 임포트 규칙 grep, `reconcile.sh --subscribe --idle-timeout 1`이 `test_comp_monitor_concurrency_lock`과 동일 동작.
- **완료 기준**: 전체 스위트 통과, `git diff --check`, `compileall`, 3개 shim `--help` 출력이 이동 전 캡처본과 diff 없음, **PV-2/PV-3가 전체 스위트 실행 후에도 통과**(이것이 이의제기가 요구한 "어느 트리를 검증했는지" 증빙).
### P1-02 서비스·CLI·데몬 + 셸 헬퍼 교체 (커밋 3: `feat(issue-5): DelegationService, cli router, ensure_subscriber_daemon; lib.sh helpers delegate to python`)
- **파일**: `service.py`, `daemon.py`, `cli.py`, `__main__.py`; `lib.sh` L1876-1941 교체(D3).
- **추가 테스트**: daemon 단위(PID 생존·중복·로그 경로·부모 종료 후 생존), `cli publish` ≡ `publish_event.main`(G-1~G-4 cli 경로 parametrize), `cli submit` stdout, C-01~C-09 신규 본체 재통과.
- **완료 기준**: 두 경로 특성화 통과, `bash -n` 6개 파일, 전체 스위트 통과.
### P1-03 장수 연결 프로토타입 (커밋 4: `feat(issue-5): persistent MQTT publisher prototype and benchmark harness`)
- **파일**: `publish_event.py` 함수 분리(D7), `publisher.py`, `service.py` `persistent` 옵션, `bench.py`.
- **추가 테스트**: 가짜 paho 클라이언트로 (a) OneShot N회 = N connect, Persistent = 1, (b) 패리티, (c) PUBACK 미확인 → 재시도 → `record_outcome(published=False)`, (d) 브로커 설정 상이 혼입 예외, (e) `bench --transport fake` 스키마·카운트. 네트워크 접촉 0.
- **완료 기준**: 위 테스트 통과, G-1~G-4 동일 통과, 전체 스위트 통과.
### P1-04 벤치마크 실측 및 문서 (커밋 5: `docs(issue-5): phase 1 benchmark results, contract mapping, task checklist`)
- 실행: fake 모드 + broker 모드 1회(임시 레지스트리). `docs/contracts/issue-5/phase1-benchmark.md`에 기록.
- 문서 갱신: `SKILL.md`(version `4.2.0`→`4.3.0`, "구현은 `lib_py.delegation`, `scripts/*`는 패키지 바인딩 shim" 1단락 + D2-1 표 요약), 스킬 `README.md`, `registry.md`/`job-protocol.md` 각주, `deploy/install.sh` `core_files`에 `.agents/skills/lib_py/delegation/__init__.py` 추가(무결성 목록 갱신 목적; 배포 자체는 트리 통째 복사라 누락 위험 없음), `baseline.md` §6 매핑 행, `task.md` P1-01~03 체크 + 증거, `implementation_plan.md` Phase 1 행 상태.
- 라이브 스모크(수동, 보고서 기록): 임시 레지스트리에서 `registry.py register` → shim `publish_event.py --event started` → `-m lib_py.delegation.cli publish --event completed` → `<id>.events.log` 2줄, `events.ndjson` `published` 2건, `status.json`=completed. 이어 `MAM_DELEGATION_PY=0`으로 반복. **추가(Rev.2)**: 에이전트 세션과 같은 조건(`PYTHONPATH`=live)에서 **freeze 사본 경로**의 shim을 실행하고 `python -c`로 `lib_py.delegation.__path__`가 freeze 사본임을 출력해 첨부(K2 실증).
---
## 4. 계약 보존 매트릭스
| 계약 | 구현 위치(이동 후) | 보장 테스트 |
|---|---|---|
| 스크립트 리터럴 경로·실행 비트·`--help` | `scripts/*.py` shim | P1-01 `--help` diff, K6, e2e `:414` |
| `import mqtt_common` 등 최상위 이름 → 단일 트리의 동일 객체 | shim 패키지 바인딩 + 별칭 | **PV-1(정체성+출처)**, PV-4 |
| 위임 외 `lib_py.*`는 항상 실제 트리(pytest) / 부모 무재바인딩 | shim 규칙 3 | **PV-2, PV-3** |
| `publish_event` exit 0/1/2, stdout 무출력 | `publish_event.main` 불변 | G-1~G-4 + cli parametrize |
| seq 단조·실패 시 소비 | `prepare_event`→`next_seq` | G-4, `test_comp_monitor_monotonic_seq_updates` |
| HMAC `data.hmac_sig` | `build_payload` 단일 경로 | `test_mqtt_verify_hmac_*`, 패리티 |
| 터미널 이벤트 retain | `prepare_event` | 패리티(`retain`) |
| `job_subscriber` exit 0/1/2/3, 디스크 폴백 3s | 이동만 | G-5~G-9 |
| 셸 헬퍼 비치명 | 셸 가드 + `\|\| true` | C-01~C-04 (두 경로) |
| `delegate_submit_job` stdout=JID 1줄 | `cli submit` + stderr 로깅 | C-05 |
| 데몬 PID/수명/중복/로그 경로 | `daemon.py` | C-06~C-09, daemon 단위 |
| `start_watchdog` 이름 | 별칭 | C-09 |
| 감사 로그 레이아웃·`DELEGATE_JOB_LOGS_DIR` | `mqtt_common` 불변 | G-2, G-3 |
| env 로딩 순서(OS env 우선), 라이브러리 임포트 무부작용 | `ensure_env_loaded`(진입점) | env 테스트 2종 |
| 자동완료 3표면 불변 | 변경 없음 | 불변 가드 3종 |
| 래퍼 텍스트 불변 | 변경 없음 | G-10 + 확장 |
| 위임 패키지의 형제 `lib_py` 모듈 무임포트 | D1(b) | grep 테스트 |
| freeze(B-13) — K1/K2 모두 freeze 트리 | `PYTHONPATH`(K1) / shim 바인딩(K2) | K1, C2, C2_pe, P1-04 실증 |
---
## 5. 게이트
| # | 조건 | 측정 방법 |
|---|---|---|
| G1 | 기존 510개 + 신규(예상 40±5) 전부 통과, skipped 0 | `.venv/bin/python -m pytest tests/ -q` (≈15분, 백그라운드) |
| G2 | 셸 문법·공백 클린 | `bash -n` 6개 파일, `git diff --check` |
| G3 | Python 3.9 컴파일 | `compileall -q .agents/skills/lib_py/delegation` |
| **G4** | **정체성+출처(PV-1), 위임 외 `lib_py` 실제 트리·`sys.path` 위생(PV-2/PV-3, 전체 스위트 종료 시점), 컨텍스트 매트릭스(PV-4 10+3), shim 동일성(PV-5), env 무오염** | P1-01 테스트 + conftest finalizer |
| G5 | 데몬/PID 계약 | C-06~C-09 두 경로 |
| G6 | 자동완료 3표면 불변 | 불변 가드 + `git diff --stat`(래퍼 무변경, `reconcile.sh`는 env 1줄만) |
| G7 | 벤치 결정적 지표 + 실측 문서 | fake 전송 테스트, `phase1-benchmark.md` |
| G8 | 롤백 드릴 | `MAM_DELEGATION_PY=0` + 라이브 스모크 |
| G9 | 라이브 스모크(shim·cli·**K2 freeze 사본**) 감사 로그 정합 | §3 P1-04 |
Worker 완료 보고서에는 G1 pytest 요약 원문, G4의 PV-2/PV-3 finalizer 통과 로그, G7 표, G9 발췌(K2 `__path__` 출력 포함)를 그대로 붙인다. file:line 인용은 `grep -n` 출력으로 뒷받침.
---
## 6. 롤백 절차
1. **즉시**: `export MAM_DELEGATION_PY=0` → 셸 헬퍼 legacy 분기. 패키지·shim은 그대로 두어도 무해.
2. **커밋 단위**: 5→4→3 순 `git revert`; 커밋 2까지 되돌리면 이동 전 상태. 커밋 1은 레거시에서도 통과.
3. **진행 중 루프**: freeze 스냅샷은 시작 시점 트리이므로 롤백은 다음 루프부터. 라이브 헬퍼는 즉시 legacy. 스키마 불변이므로 혼재 호환.
---
## 7. 리스크와 완화
| # | 리스크 | 완화 |
|---|---|---|
| R1 | 모듈 사본 분기(테스트 shim vs 프로덕션 패키지) | D2 패키지 바인딩 + PV-1 출처 단정 |
| R2 | 임포트 시 `.mam.env` 주입 오염 | D6 + conftest `MAM_ENV_FILE` |
| **R3 (Rev.2 재작성)** | shim 부트스트랩이 pytest에서 위임 외 `lib_py`를 tmp 사본으로 가로채거나(insert), freeze에서 live에 밀리거나(append), 비-잎 모듈에서 두 트리가 섞임(잎 파일 적재) | **해소**: 패키지 단위 bind-once, `sys.path` 무변경, 부모 무재바인딩. PV-2/PV-3/PV-4가 회귀를 검출 |
| R4 | Python 3.10+ 문법 | G3 |
| R5 | 공용 브로커 불안정 | 테스트는 비라우팅 포트/가짜 전송만 |
| R6 | `pgrep -f` 패턴 | 레거시 그대로, C-08 |
| R7 | `$( )` 캡처 stdout 오염 | stderr 로깅, C-05/C-07 |
| R8 | 래퍼 리터럴(G-10) 파손 | 래퍼 무수정 |
| **R9 (Rev.2 수정)** | `lib.sh` 미소싱/`PYTHONPATH` 부재 환경에서 shim·`-m` 실패 | shim: `lib_py` 부재 시에만 자기 트리 `append`(K4). `-m` 경로: 셸 헬퍼는 항상 `lib.sh` 내부이므로 `SKILL_DIR` 존재 + 명시 전달 |
| R10 | `lib_py.agents.registry` 혼동 | D1(a) grep |
| R11 | `start_new_session` vs `nohup` | SIGHUP 무시, 생존 테스트 |
| **R12 (신규)** | K2에서 부모 `lib_py`(live)와 위임 패키지(freeze)가 다른 트리 | D1(b): 위임 패키지는 형제 `lib_py` 모듈을 임포트하지 않음(grep 고정). 현재 0건 |
| **R13 (신규)** | 두 트리의 위임 모듈을 한 프로세스에서 동시에 써야 하는 경우 | 존재하지 않음(K1~K6 전수). 발생 시 bind-once 규칙상 최초 트리 유지 — 문서화 |
| **R14 (신규)** | pytest에서 위임 패키지가 샌드박스 사본에 바인딩되어 "실제 트리 미검증" 우려 | 사본은 `copytree` 동일 내용이며 PV-1이 사본 위치를 basetemp로 한정. K6 서브프로세스가 사본 경로 실행을 별도 검증 |
---
## 8. 명시적 비범위
- `lib.sh` L1943 이후 TUI 헬퍼의 파이썬화.
- 래퍼, `run_loop.sh`, `reconcile.sh`(env 1줄 제외) 수정.
- `job_subscriber`/모니터 전송 변경, 스키마 v2, 토픽 변경.
- 자동완료 로직 일체(Phase 2a/2b).
- 저장소 통합, Windows, `pgrep` 다중 PID 정리(Phase 4 후보).
- 기존 tier1/tier2 테스트의 임포트 방식 변경(회귀 오라클 보존).
---
## 9. Worker 인수인계 체크리스트
- [ ] P1-00 커밋 1: 특성화·스냅샷·불변 가드 + **PV-2/PV-3 finalizer**가 레거시 코드에서 통과
- [ ] P1-01 커밋 2: `git mv` 4종, D2 shim 4종(PV-5 동일), `ensure_env_loaded`, PV-1/PV-4 매트릭스, 전체 스위트 녹색 **+ finalizer 녹색**
- [ ] P1-02 커밋 3: `service/daemon/cli`, `lib.sh` 교체(legacy 보존, `MAM_DELEGATION_PY`), 두 경로 특성화 녹색, `bash -n`
- [ ] P1-03 커밋 4: `prepare_event/record_outcome`, `PersistentPublisher`, 패리티·카운트, 네트워크 0
- [ ] P1-04 커밋 5: 벤치 문서, SKILL/README/registry.md/job-protocol.md/install.sh/baseline §6/task.md/implementation_plan.md, K2 실증 첨부
- [ ] 완료 보고서: G1 원문, G4 finalizer 로그, G7 표, G9 발췌, `grep -n` 인용
- [ ] 커밋 접두: `test(issue-5)`, `refactor(issue-5)`, `feat(issue-5)`, `feat(issue-5)`, `docs(issue-5)`
---
## 부록 A. 계획 수립 시 실행한 검증 명령 (Rev.1 + Rev.2)
```bash
awk 'NR>=1800 && /^[a-zA-Z_][a-zA-Z0-9_]*\(\)/ {print NR": "$0}' .agents/skills/lib.sh
grep -rn 'delegate_publish_event\|delegate_submit_job\|start_watchdog\|_delegate_py_bin' --include='*.sh' --include='*.py' .agents tests
grep -l 'delegate_publish_event\|start_watchdog\|delegate_submit_job' tests/*.py # → (없음)
grep -n 'lib_py' .agents/skills/multi-agent-mux-delegate-job/scripts/*.py # → (없음) D1(b) 전제
echo "$PYTHONPATH" # 에이전트 세션 = 라이브 트리
grep -n PYTHONPATH .agents/skills/multi-agent-mux-loop/scripts/run_loop.sh # 0건
sed -n '24,25p;163,164p' .agents/skills/lib.sh # SKILL_DIR 기준 PYTHONPATH export
ls /var/folders/.../mam-loop-freeze.PfAQNj/.agents/skills/lib_py # freeze에 lib_py 존재
grep -n 'os.environ' .agents/skills/multi-agent-mux-delegate-job/scripts/mqtt_common.py # 전부 함수 내부
.venv/bin/python -m pytest tests/ --collect-only -q | tail -1 # 510
```
## 부록 B. shim 컨텍스트 재현 하니스 (P1-01 PV-4의 원형)
세 변형 × 시나리오를 새 인터프리터(`env -u PYTHONPATH`)에서 실행하고 각 모듈의 `TREE` 마커를 출력한다. Worker는 이 하니스를 `tests/fixtures/issue_5/phase1/shim_contexts.py`로 옮기고, 가짜 트리 대신 **실제 이동된 트리의 사본**(`copytree`)을 `real/sandbox/sandbox2/freeze`로 사용하며, `TREE` 마커 대신 `__file__`/`__path__` 접두어로 트리를 판별하도록 바꾼다.
```python
# 트리 구성: <tree>/lib_py/{__init__.py, agents/__init__.py(TREE), delegation/{__init__.py, mqtt_common.py(TREE), publish_event.py(TREE + from lib_py.delegation import mqtt_common)}}
# <tree>/multi-agent-mux-delegate-job/scripts/{mqtt_common,publish_event}.py ← D2 shim
# 시나리오 (sys.path 조작은 conftest/tier1/실행 방식을 모델링):
# A : insert(0, real); insert(0, sandbox/scripts); import mqtt_common, publish_event
# A_pe : 같음, import publish_event 만
# B : insert(0, real); import lib_py.agents; insert(0, sandbox/scripts); import mqtt_common, publish_event
# B2 : insert(0, real); import lib_py.delegation.mqtt_common; insert(0, sandbox/scripts); import mqtt_common, publish_event
# C1 : insert(0, freeze/scripts); import mqtt_common, publish_event (PYTHONPATH 없음)
# C1_pe: 같음, publish_event 만
# C2 : insert(0, real); insert(0, freeze/scripts); import mqtt_common, publish_event
# C2_pe: 같음, publish_event 만 ← 에이전트 호출 형태
# D : insert(0, real); insert(0, sandbox/scripts); import mqtt_common; insert(0, sandbox2/scripts); import publish_event
# E : insert(0, real); insert(0, sandbox/scripts); import mqtt_common; from lib_py.delegation import publish_event
# 단정: 각 시나리오에서 {alias_mc, pkg_mc, pe, pe.dep} 가 단일 트리이고, pytest 계열(A,A_pe,B,B2,D,E)에서 agents == real,
# identity(alias is pkg) == True, sys.path 에 lib_py 를 담은 비-real 루트가 없음(C1 계열 제외).
```
@@ -0,0 +1,25 @@
# Report: Job adad47d1 — Refined Consensus (Rev.2) per `creator-agy-01` Challenge
**Durable output (updated in place)**: [.agents/reports/cline_deprecation_opinion.md](../../../.agents/reports/cline_deprecation_opinion.md)
## Summary
`creator-agy-01` challenged Rev.1's §3.1 risk characterization of cline's unattended-execution gap, arguing it understated the real danger: `cline history --json` (the pre-spawn gate) only validates that local session storage exists, not credential/API validity — so it can't protect against a runtime auth failure (401/expired token/429 quota) mid-task, which could plausibly force cline's TUI into its interactive setup modal with no clean-exit fallback like the other four agents have. A second point noted the 40-session usage fact I'd used to support RETAIN also amplifies `discover()`'s session-hijacking exposure.
**Verification before accepting**: I ran `cline history --help` myself (confirmed: pure local listing, no auth semantics) and traced exactly where MAM checks for the setup modal in `lib.sh` (confirmed: only at spawn-time and at the moment of injecting a new prompt — never continuously during an autonomous work stretch). Both confirm the architectural gap is real. I was also careful to flag what remains *inferred* rather than *observed*: neither `creator-agy-01` nor I have actually triggered a live credential failure to watch cline's real behavior — I adopted the escalated risk model as the working precautionary assumption while saying so explicitly, rather than overstating certainty either side doesn't have.
**Disposition**: Accepted, with the honesty caveat above — no `[REBUT:]` filed.
## What changed in Rev.2
- §3.1 rewritten: risk escalated from "narrow spawn-time race" to "unmonitored mid-task modal-fallback window," with the verification trail (what's confirmed vs. inferred) laid out explicitly.
- §3.2 narrowed to reaffirm only the tool-call-approval finding that still stands (`--auto-approve` default true) — the credential-failure gap is a separate, more severe category, not covered by that flag.
- New §3.4: precision-scoped the session-hijacking concern (cline's `discover()` does filter by workspace `cwd`, so exposure is concurrent-same-workspace activity, not all 40 sessions indiscriminately) while accepting the core point.
- §4 revised: my RETAIN vote stands but its terms changed — now explicitly conditional on the new §6.2 safety gate, not an unconditional RETAIN as Rev.1 implied.
- §6 reprioritized: the reconcile.sh fix is now urgent; a new mandatory safety-gate requirement (exclude cline from long-running autonomous roles until upstream ships a real headless/non-interactive flag) is added for the RETAIN path; the empirical-verification ask is upgraded from "nice to have" to a prerequisite before trusting cline with new unattended work.
Full Rev.2 text is in the durable report linked above.
**Process note**: Still no unanimous verdict (2 RETAIN-conditional vs. 1 REMOVE) — this challenge sharpened the RETAIN side's conditions rather than flipping any vote. The REMOVE-vs-RETAIN decision still belongs to the General Manager per `MULTI_AGENT_RULES.md` §3.
[VERDICT: N/A — consensus opinion artifact, decision belongs to the General Manager]
@@ -0,0 +1,14 @@
# Report: Job ec388212 — Refined Version Upgrade Plan (Rev.2) per `creator-agy-01` Challenge
**Durable output (updated in place)**: [.agents/reports/version_upgrade_recommendation.md](../../../.agents/reports/version_upgrade_recommendation.md)
## Summary
`creator-agy-01` challenged Rev.1's §6 implementation checklist (job `53b96f7a`) — explicitly reaffirming the v4.0.0 consensus itself, not disputing it. Two blind spots identified. **Both accepted — no `[REBUT:]` filed**, after independently re-verifying each claim against the live codebase rather than trusting the challenge's framing:
1. **`VERSIONS.md:24` prose desync**: verified `tests/test_version_consistency.py`'s regexes only cover the "현재 버전 개요" header line and the 8-row skill matrix table — confirmed by reading the actual regex patterns (`re.search(r"...프레임워크 버전...")`, `re.findall(r"\|\s*\*\*\`([^\`]+)\`\*\*...")`). Line 24's free-text sentence ("...`v3.1.0`으로 동기화되어 배포됩니다.") is untouched by either regex. **Fixed**: §6 item 2 now names this line as an explicit edit target.
2. **Orphaned `cline` session rows surviving the upgrade**: verified `deploy/update.sh` (lines 111–166) explicitly backs up and restores `.mam/agent-sessions.*` across an update — nothing is wiped. Verified `registry.py::agent_of_row()` returns `None` for `agent: cline` rows post-removal (its explicit-field fast path checks `str(explicit).lower() in _ADAPTERS`, and `cline` is no longer a key). Verified `resume_session.sh` hard-rejects `--agent cline` with `exit 2`. Went further than the challenge asked: traced whether `multi-agent-mux-stop --purge-conversation` remains usable — confirmed it handles an already-dead herdr pane fine ("herdr already dead, just updating YAML"), but its `--agent` whitelist is narrowed too, so artifact-aware purge only works **before** upgrading. For rows orphaned *after* upgrading (no adapter left to resolve artifact paths), traced the safe primitive down to `lib.sh::atomic_dump_yaml` / `atomic_yaml.py::atomic_dump_yaml_main()` — confirmed it execs a caller-supplied Python snippet against the `d` dict under an `flock` + SQLite `BEGIN IMMEDIATE` transaction, the same locked path every other skill script already uses. **Fixed**: §6 item 2 now gives a verified pre-upgrade purge command and a verified post-upgrade YAML-only prune one-liner using that exact primitive, rather than inventing new tooling.
Full Rev.2 text is in the durable plan linked above (new "Rev.2 Changelog" section at the top, plus the rewritten §6 item 2).
[VERDICT: N/A — planning artifact, review pending]
@@ -0,0 +1,86 @@
# 📋 Implementation Plan — Issue #3 Fix (Job `a9c8d6d3`)
- **Planner**: `planner-reviewer-claude-01`
- **Based on**: `.agents/reports/creator-agy-01/issue-3-analysis.md` (Rev. 3, job `6b391a80`), independently validated PASS by both `planner-reviewer-claude-01` (job `9406c304`) and `reviewer-opencode-01` across the peer-review cycle.
- **Scope**: implement both confirmed defects from the Rev. 3 analysis, add regression tests, verify the full suite.
---
## 1. Item 1 — Headless herdr daemon process-group detachment
**Defect** (Rev. 3, CONFIRMED, HIGH): `.agents/skills/lib.sh:207-219` (inside the heredoc that generates `.mam/shim/herdr`) launched the headless daemon via `nohup "$REAL_HERDR" ... server >/dev/null 2>&1 & disown`. `nohup` only ignores `SIGHUP`; `disown` only drops bash's own job-table tracking. Neither creates a new process group or session, so the daemon stays in the caller's PGID and dies when a process-group signal (`SIGTERM`/`SIGINT` from a test runner, timeout wrapper, or supervisor teardown) is broadcast — matching the live evidence from three independent reviewers' process-table inspections (PID 7623/PGID 7526/PPID 1, still TTY-attached, never `setsid()`'d).
**Fix**: replaced the `nohup ... & disown` line with a Python `subprocess.Popen(..., start_new_session=True, ...)` spawner (invoked via `python3 -c '...'`), which calls `os.setsid()` in the child before `exec` — portable across macOS (no `setsid(1)` binary by default) and Linux. `disown` is no longer needed since the process is no longer a bash job at all (spawned by the python3 child, not via `&`). The `kill -0 "$_mam_server_pid"` liveness-wait loop is unchanged; only how the PID is obtained changed (captured from the Python spawner's stdout instead of `$!`).
**File**: `.agents/skills/lib.sh:207-224` (the generated `.mam/shim/herdr` is a runtime artifact regenerated by `_init_herdr_isolation`, not git-tracked — no separate edit needed there).
**Test**: `tests/test_herdr_shim_contract.py::test_h26_daemon_spawn_uses_process_group_detachment` — (a) static check that the generated shim no longer contains the old `nohup ...server` pattern and does contain `start_new_session=True`; (b) behavioral check that extracts the *actual shipped* spawner statement from the generated shim and runs it standalone against a fake `REAL_HERDR` (a plain `sleep 30`), asserting the spawned process's PGID differs from the calling shell's PGID — i.e. genuine detachment, not just a textual change. Verified fail-old/pass-new: reverting `lib.sh` to the pre-fix version makes this test fail (old `nohup` pattern still present); restoring the fix makes it pass.
## 2. Item 2 — Class A (`agy`/`hermes`/`opencode`) 0-turn resume fallback
**Defect** (Rev. 3, CONFIRMED, MEDIUM — Class A only): a session for `agy`/`hermes`/`opencode` stopped before its first message has `session_id_source: pending-discovery` and a null own-key. `resolve_session_id.sh` correctly returns `""`, and `resume_session.sh:54-57` hard-exits (RC=1) telling the caller to use `multi-agent-mux-create`, which in turn requires `--role` (`create_session.sh:96`) — an argument resume callers don't hold. **Explicitly not a defect for Class B** (`claude`/`grok`): their `verify_session.py:99-101` `assigned`+`unverified` escape hatch already resolves the pre-assigned UUID without requiring an on-disk transcript, proven by the pre-existing `test_t8_resume_unmaterialized_assigned_id` (still green, untouched).
**Fix** (`.agents/skills/multi-agent-mux-resume/scripts/resume_session.sh`):
- When `resolve_session_id.sh` returns an empty UUID, branch on agent: `agy`/`hermes`/`opencode` set `FRESH_SPAWN=1` and continue instead of exiting; `claude`/`grok`/any other agent hit the exact original hard-exit (byte-identical error message and RC=1) — the Class B path is completely unmodified.
- When `FRESH_SPAWN=1`, `CMD_FULL` is computed via `lib_py.agents spawn-spec` (the same call `create_session.sh` uses for a first-time launch) instead of `resume-spec`, with a matching inline fallback case statement for `agy`/`hermes`/`opencode` only.
- This bypasses the broken `resume_session.sh → create_session.sh --role` handoff entirely rather than trying to make `create_session.sh` callable without a role — the recovery happens inside `resume_session.sh` itself, reusing the same command the agent was originally spawned with.
**Fix** (`.agents/skills/multi-agent-mux-resume/scripts/update_yaml_resumed.sh`): the final YAML update needs `--uuid`, which is empty for a fresh-spawn resume. The hard `[ -n "$UUID" ] || exit 2` guard was relaxed to allow empty (documented in `usage()`), and a new optional `--cmd-full` flag lets `resume_session.sh` pass through the already-computed spawn command for display. The Python payload:
- `last_visible_status` branches: `"resumed conversation {uuid} ..."` when non-empty, `"resumed (fresh spawn, no prior turn) ..."` when empty.
- **Only the `agy`/`hermes`/`opencode` blocks** got an `if uuid: ... else: ...` guard (own-key set + uuid-interpolated `cmd_full` when present; `--cmd-full` passthrough with a static fallback when absent). **The `claude` and `grok` blocks are byte-identical to before** — per the brief's explicit instruction, Class B is never touched.
**Files**: `.agents/skills/multi-agent-mux-resume/scripts/resume_session.sh`, `.agents/skills/multi-agent-mux-resume/scripts/update_yaml_resumed.sh`.
**Tests**:
- `tests/test_uuid_target.py::test_t14_resume_class_a_fresh_spawn_fallback` — creates an `agy` session, stops it at 0 turns, confirms the YAML row has `status: stopped` and no own-key, then runs `resume_session.sh --dry-run` and asserts RC=0 with a plain spawn command (`--dangerously-skip-permissions`, no `--conversation`). Verified fail-old/pass-new: reverting `resume_session.sh` alone reproduces the old hard-fail (`ERROR: No saved session for ...`) and the test fails; restoring the fix makes it pass.
- `tests/test_uuid_target.py::test_t15_resume_class_b_still_hard_fails_when_truly_unresolvable` — a genuinely never-created `claude` session must still hard-fail with the original error and RC=1, guarding against the fallback ever leaking into Class B.
## 3. Verification
- Targeted suite (`test_tier1-4`, `test_uuid_target`, `test_c1_tui_readiness`, `test_herdr_shim_contract`): 164 passed pre-existing + 3 new = 167, all green, before adding the final full-suite run.
- Full suite (`tests/`): run in background; result to be confirmed and cited in the final job report.
- No changes to `verify_session.py`, `workspace_uuid.py`, or the `claude`/`grok` branches of `update_yaml_resumed.sh` — the Class B escape hatch and `test_t8` contract are untouched, per the brief's explicit requirement.
## 4. SemVer
Both changes are backward-compatible bug fixes (no public interface/behavior removed; `resume_session.sh`'s new fallback only activates on a previously-hard-failing input; `update_yaml_resumed.sh`'s relaxed `--uuid` requirement is additive). This qualifies as a PATCH under SemVer 2.0.0 §6. Version bump and `VERSIONS.md`/`SKILL.md` changelog entries are left for a subsequent release-packaging job (out of this job's stated scope, which is analysis-driven code improvement, not release cutting).
---
## Rev. 2 — Refinement in response to `creator-agy-01`'s architectural challenge (job `c4b0a075`)
**Independent verification of the challenge** (before accepting it): re-read the live, already-implemented `update_yaml_resumed.sh` and confirmed the challenge's citation is exact — the existing-row branch (`else:` at line 150, running through line 163, immediately before the shared `target['status'] = 'running'` at line 165) genuinely never touches `herdr_session_epoch` or `herdr_session_created_at`. Cross-checked the two supporting mechanisms it depends on: `lib_py/verify_session.py:89` (`epoch = row.get("herdr_session_epoch", 0) if mode == "discover" else 0`) confirms the epoch watermark only matters in `discover` mode, and `lib_py/agents/adapters/agy.py:49` (`if ctx.epoch and os.path.getmtime(path) < ctx.epoch: return False`) confirms the exact `mtime >= epoch` acceptance rule the challenge describes. `reconcile.sh` does call `verify_session_uuid(..., mode="discover")` for agy/hermes/opencode (lines 708/766/876). **This is a genuine defect I introduced in the Item 2 fix** — a Class A fresh-spawn resume leaves the row's discovery watermark stuck at the original `create_session.sh` timestamp, so `reconcile.sh`'s next sweep could pin an unrelated, older on-disk conversation (created any time after that original watermark, including *before* the resume even happened) to the freshly-resumed, still-silent agent.
**One precision correction to the challenge's own proposed diff**: `session_id_source`/`session_id_verified` are not currently set on `agy`/`hermes`/`opencode` rows at all — `create_session.sh`'s per-agent block only assigns those two fields for `claude`/`grok` (see `create_session.sh:402-437`). Setting them on a Class A row in the proposed fix is therefore not "resetting" pre-existing state — it introduces a field that wasn't there before. This is harmless (nothing currently reads `session_id_source`/`session_id_verified` on a non-claude/grok row; `verify_session.py:99`'s escape hatch is gated on `session_id_source == "assigned"`, which a Class A row will never have), but the refined fix below keeps it anyway for forward-consistency with the fields `create_session.sh` already sets for Class B, rather than dropping it — it costs nothing and makes a future reader's mental model ("every row always carries these two fields") uniformly true.
### Refined fix
In `.agents/skills/multi-agent-mux-resume/scripts/update_yaml_resumed.sh`, inside the shared post-branch code (i.e. *after* line 165's `target['status'] = 'running'`, applying uniformly regardless of which branch — new-row or existing-row — populated `target`, and reusing the `epoch`/`now` locals already computed at lines 117-118), add:
```python
if not uuid:
# ISSUE-3 (challenge c4b0a075): a Class A fresh-spawn resume re-arms
# discovery from scratch - the resumed agent has not spoken yet, so any
# on-disk conversation older than THIS resume must not be auto-pinned to
# it by reconcile.sh's mode="discover" mtime >= epoch check. Without this,
# the row's watermark stays at the original create_session.sh timestamp,
# letting reconcile.sh capture a stale/unrelated transcript before the
# resumed agent's first real turn.
target['herdr_session_epoch'] = epoch
target['herdr_session_created_at'] = now
target['session_id_source'] = 'pending-discovery'
target['session_id_verified'] = False
```
Gated strictly on `if not uuid:` (the same condition already used at line 175 for the `last_visible_status` branch), so it fires *only* on the new Class A fresh-spawn path from this same job's Item 2 fix — it can never touch a normal resume (`uuid` non-empty, any agent) or any Class B path, since `claude`/`grok` never reach `update_yaml_resumed.sh` with an empty `--uuid` (per Item 2's `resume_session.sh` branch, only `agy`/`hermes`/`opencode` set `FRESH_SPAWN=1`).
### New test spec
`tests/test_uuid_target.py` — extend `test_t14_resume_class_a_fresh_spawn_fallback`'s fixture (or add a sibling `test_t16_resume_class_a_fresh_spawn_resets_discovery_epoch`): after creating+stopping the `agy` session at 0 turns, seed a conversation artifact under the workspace with an `mtime` *between* the original creation time and "now" (simulating the challenge's $T_2$ stale transcript), run `resume_session.sh` (not `--dry-run`, since the epoch write only happens in `update_yaml_resumed.sh`'s real YAML mutation), then assert in `agent-sessions.yaml` that `herdr_session_epoch` was advanced to at or after the resume's own timestamp (not the stale creation-time value) — i.e. the pre-existing stale artifact's `mtime` is now `<` the row's watermark and would be correctly rejected by a subsequent `reconcile.sh` discover-mode sweep. Should be verified fail-old/pass-new like the other two Item 2 tests: written against the pre-refinement code, `herdr_session_epoch` stays at the original creation epoch and the assertion fails; after applying the refined fix, it advances and the test passes.
### Updated action list for re-implementation
1. Apply the `if not uuid:` epoch/watermark-reset block above to `update_yaml_resumed.sh`, placed after the shared `target['status'] = 'running'` line so it applies regardless of which branch (new-row vs. existing-row) populated `target`.
2. Add the new regression test per the spec above, and verify fail-old/pass-new for it specifically (not just that it passes).
3. Re-run the full test suite and confirm no regression against the 454-passed baseline from the original `a9c8d6d3` implementation.
4. No changes needed to Item 1, `resume_session.sh`'s branch logic, `verify_session.py`, `workspace_uuid.py`, or any Class B (`claude`/`grok`) code path — this refinement is fully contained within `update_yaml_resumed.sh`'s shared post-branch section.
@@ -0,0 +1,138 @@
# 📑 Implementation Plan Rev.2 — Workspace Root Markdown 정리 및 최신화 (Job baea3f7e, 원본 45bd8635)
- **역할**: Planner (`planner-reviewer-claude-01`)
- **기준 커밋**: `07cae71` (`main`, v4.4.0, 전체 스위트 750 passed / 문서 바인딩 4모듈 49 passed)
- **개정 사유**: Creator(`creator-agy-01`, Job `87aa5b5a`) 이의제기 3건. **3건 모두 실측으로 사실 확인되어 전부 수용**하고, 검증 과정에서 Planner 자신의 Rev.1 오류 1건(D-1/Phase B-1 "잔재에 고유 내용 없음")을 추가로 발견하여 함께 정정한다.
- **Rev.1 대비 변경 범위**: §1 D-1, Phase A-2, Phase B 전면, Phase D-1, 게이트 4. 나머지 Phase C/E/F/G와 게이트 1·2·3·5·6은 Rev.1 그대로 유효(본문 하단에 원문 유지).
---
## 0. 이의제기 판정 (Adjudication of Challenge)
| # | Creator 주장 | Planner 실측 | 판정 |
|---|---|---|---|
| C-1 | 완료 과제는 §5 단일 섹션이 아니라 §2(5건)·§3(2건)·§5(24블록)에 분산되어 있고, 헤더 "30건"은 전역 합계이며 Rev.1 Phase B-2 지시("§5의 `###` 수로 재계산해 헤더와 일치")는 실행 불가 | `awk`로 전 `###` 블록을 섹션별로 열거: §2 완료 5(B-21,B-20,B-19,B-14,B-15), §3 완료 2(O-6,A-4), §5 24블록(O-2 중복 2회), 헤더 ID 정확히 30개. **주장 사실.** 단 Creator의 산식 "5+2+23=30"은 우연한 일치다. ID↔블록이 1:1이 아니기 때문이다(아래 §1-A) | **수용** — 방안 A 채택, 단 계수 규칙을 블록 기준으로 명문화 |
| C-2 | 이관되는 `implementation_plan.md` §7 표의 `[.mam.env](.mam.env)` 링크는 gitignored 파일(`test_d29`가 추적 금지)이라 클린 체크아웃에서 게이트 4 `test -e`가 실패 | `.gitignore:24` `.mam.env`, `git ls-files`에 `.mam.env.example`만 추적, `tests/test_deploy_freshness.py:687 test_d29_env_secrets_never_tracked` 존재, 원문 151행 링크 확인. **주장 사실.** | **수용** — 링크 대상을 `.mam.env.example`로, 게이트 4에 ignore 예외 규칙 추가 |
| C-3 | Phase D-1 트리 추가 목록에 `IMPROVEMENTS.md` 누락, 영문 README 트리에 `README.ko.md`/`BOOTSTRAP.ko.md` 부재, 한국어 README에는 `BOOTSTRAP.ko.md`만 존재 → "줄수 일치" 게이트 기준 불명확 | `README.md:188-190` 3개 루트 md, `README.ko.md:170-173` 4개 루트 md. **주장 사실.** | **수용** — 루트 md 8개 전부를 양 README 트리에 동일 순서로 명시 |
부수 정정: Creator 보고서의 "450줄"은 `wc -l` 기준 449줄(마지막 줄 개행 있음)이나 판단에 영향 없음.
---
## 1. 정정된 결함 진단
### 1-A. `IMPROVEMENTS.md` 완료 과제 원장 (Planner 실측, 정본)
헤더 ID 30개와 완료 `###` 블록 31개(잔재 제외)의 대응은 다음과 같다. 이 표가 Phase B의 유일한 기준이다.
| 헤더 ID | 현재 블록 위치 | 비고 |
|---|---|---|
| B-21, B-20, B-19, B-14, B-15 | §2 (30/44/54/64/68행) | 미해결 섹션에 완료 항목 혼재 |
| O-6, A-4 | §3 (99/106행) | A-4 블록은 Rev.2 어댑터 계층 45행 분량 |
| B-9, B-13, B-10, B-5, C-6, P2-2, P2-1, B-4, O-3, A-1, A-3, C-2, A-5, B-1, B-3, C-1, O-1, Herdr-0.8.0-Compat-SanitizeHash | §5 | 1:1 대응 |
| B-7 | §5 `P0-1 (B-7)` (253행) | 키 표기 상이 |
| O-4-OrcOnboard | §5 `multi-agent-mux-orc-onboard` (242행) | 키 표기 상이 |
| **O-2** | §5 **2블록**: `P0-2 (O-2)` 247행(Rev.1: pid+lstart 마커, 46/46) + `O-2` 273행(Rev.2: 하드링크 원자 쓰기, steal_lock, 204/204) | **동일 과제의 연속 개정** → 병합 대상 |
| **C-3b** | 독립 블록 없음. §5 `P3-1 (A-4 Phase 2 / Option B / C-3b / M2~M7)` 224행 제목에 포함 | P3-1 블록이 A-4(2차)와 C-3b를 동시에 담음 |
| **B-8** | **독립 블록 없음.** §6.2 표 367행 `P1-2(과거) B-8 … (✅ 완료 — tests/test_b8_send_keys_verification.py 1/1 PASS)`에만 존재 | `tests/test_b8_send_keys_verification.py` 실재 확인 |
| (헤더에 없음) | §5 `Rev.2 (b4a1d094)` 260행 세션 ID 자동 할당 | 헤더 ID 목록에서 누락된 블록 |
결론: "헤더 30 = §2 5 + §3 2 + §5 23"은 (O-2 중복 −1, C-3b 블록 없음 −1, B-8 블록 없음 −1, Rev.2 블록 ID 없음 +1, P3-1 별도 블록 +1)이 상쇄된 우연이다. Rev.2는 **"§5의 `###` 블록 1개 = 헤더 ID 1개"**를 강제하여 이 우연을 제거한다.
### 1-B. Rev.1 오류 정정 — 154~186행 잔재는 단순 삭제 불가
Rev.1 Phase B-1은 "앞쪽 사본이 최신 서술을 모두 포함(확인됨)"이라 했으나 **틀렸다**. 잔재 전용 토큰 20종을 실측했다: B-14 원 진단(`publish_event.py:195-199`, `wait_for_job()`, `max_wait=3900s`, `status=running`), B-15 원 진단(`job_subscriber.py:172-251`, `queue.Empty`, `idle_timeout`, `multi-agent-mux-delegate-job:331-341`, `wait "$sub_pid"`, `sub_rc`, `job_status="error"`, `job_status="broker_unavailable"`, `load_job`/`read_logged_status`, `source: disk-fallback`), O-5 배경(`nats-py` Option B 기각 사유). 앞쪽 B-14/B-15 블록(64~70행)은 각 2줄 요약뿐이다. B-16 블록은 양쪽 동일(잔재 고유 내용 없음). 따라서 잔재는 **병합 후 삭제**한다(Phase B-1).
---
## 2. 개정된 작업 계획 (변경된 Phase만 기술; 미기재 Phase는 Rev.1 원문 적용)
### Phase A-2 (개정) — 이관 파일 링크 규칙
- `git mv implementation_plan.md docs/contracts/nats-backplane/implementation_plan.md` 후 상대 링크를 `../../../` 접두로 승격하되, **§7 표의 `[.mam.env](.mam.env)`는 `[.mam.env (템플릿: .mam.env.example)](../../../.mam.env.example)`로 변경**한다. 이유: `.mam.env`는 gitignored(`.gitignore:24`)이며 `test_d29`가 추적을 금지하므로 클린 체크아웃에 존재하지 않는다.
- 같은 이유로 문서 내 `.mam.env`를 **파일 링크 없이 코드 스팬으로만** 언급하는 것은 허용한다(23행·122행은 링크가 아니므로 변경 불필요).
### Phase B (전면 개정) — `IMPROVEMENTS.md` 단일 원장화 (방안 A 채택)
작업 순서를 엄수한다. 행 번호는 착수 시점 기준이며 이후 단계는 **헤더 문자열로 앵커링**한다.
1. **잔재 병합 후 삭제** (1-B 반영)
- 잔재 `### **B-14 (F-1 / P1)…`(156행)의 `현상`·`파급 효과` 불릿을 앞쪽 `### **B-14 (✅ 완료 — F-1 / P1)…` 블록의 `현상` 불릿 **아래에 "원 진단" 불릿으로 추가**(내용 원문 유지, 시제만 과거형 허용).
- 잔재 B-15(161행)의 `현상` 1·2항과 `파급 효과`를 앞쪽 B-15 블록에 동일 방식으로 추가.
- 잔재 O-5(179행)의 `현상` 문장 중 "`nats-py` 클라이언트 재작성(Option B)을 배제하고" 구절을 앞쪽 O-5 `현상`에 삽입.
- 잔재 B-16(170행)은 앞쪽과 동일하므로 추가 없음.
- 그 다음 두 번째 `## 2. 🟠 …(Edge-case Bugs — 3건)`부터 두 번째 `## 3.` 블록 끝(`## 4. ⚪ 레거시 잔재` 직전 구분선)까지 삭제.
- **검증**: 위 20종 토큰 전부가 삭제 후 파일에 여전히 존재(`grep -cF`로 각 1 이상), `grep -c '^## 2\.'`=1, `grep -c '^## 3\.'`=1.
2. **완료 블록 §5 이관** (방안 A)
- §2의 B-21, B-20, B-19, B-14, B-15 블록과 §3의 O-6, A-4 블록을 **현재 등장 순서 그대로** `## 5. 🎉 완료된 과제` 제목 바로 아래(기존 B-9 앞)에 삽입. 블록 본문은 한 글자도 바꾸지 않는다(제목의 `(✅ 완료 — …)` 표기 포함).
- 이관 후 §2에는 B-16, B-17, B-18만, §3에는 O-5만 남는다.
3. **O-2 중복 병합**
- `### **O-2: 동일 워크스페이스 … (Race-Free Mutex & Ownership)**`(Rev.2, 최종본)을 유지하고, `### **P0-2 (O-2): …**` 블록은 제목을 제거한 뒤 그 불릿 4개를 O-2 블록 **끝에 `- **Rev.1 (P0-2) 선행 조치**:` 하위 불릿으로** 편입한다. 제목은 `### **O-2 (P0-2): …**`로 갱신하여 키 대응을 유지.
4. **B-8 블록 신설** (원장 완결성)
- `## 5` 말미(Herdr-0.8.0 블록 뒤)에 `### **B-8 (P1-2): agy 주입 시 \`return 0\` 우회 제거 및 제출 검증 루프 이관** — ✅ 완료` 블록을 추가하고, 불릿 1개만 둔다: §6.2 표 367행의 서술을 그대로 옮기고 근거로 `tests/test_b8_send_keys_verification.py` (1/1 PASS)를 명기한다. **새 사실을 지어내지 않는다** — 표 367행 밖의 내용은 쓰지 않는다.
5. **섹션 헤더 카운트 확정** (계수 규칙: 해당 섹션 하위 `###` 블록 수)
- `## 1. 🔴 아키텍처 결함 (Architecture Flaws — 1건)` (A-2)
- `## 2. 🟠 엣지 케이스 및 런타임 버그 (Edge-case Bugs — 3건)` (B-16, B-17, B-18)
- `## 3. 🟡 오케스트레이션 최적화 과제 (Orchestration Optimizations — 1건)` (O-5)
- `## 4. ⚪ 레거시 잔재 및 죽은 코드 (Legacy Remnants — 0건 — 전원 완료)` (변경 없음)
- `## 5. 🎉 완료된 과제 (Completed Tasks — 31건)` = 기존 24 − 1(O-2 병합) + 7(이관) + 1(B-8) = **31**
6. **헤더 요약(3~6행) 동기화**
- `최종 갱신일`: `2026-09-07 (IMPROVEMENTS.md 단일 원장화: §2/§3 완료 항목 §5 이관, 머지 잔재 병합 제거, v4.1.x~v4.4.0 완료 사항 반영)`.
- `총 추적 미해결 과제`: **5건** 문구 유지(A-2 / B-16, B-17, B-18 / O-5).
- `완료된 과제`: **31건**으로 갱신하고 괄호 목록을 **§5 블록 키를 등장 순서대로 나열한 31개**로 교체: `B-21, B-20, B-19, B-14, B-15, O-6, A-4, B-9, B-13, B-10, B-5, C-6, P3-1-A4Phase2-C3b, P2-2-C3a-C4-LegacyCleanup, P2-1-DelegateJobSafe-TrapFix, O-4-OrcOnboard, O-2-P0-2, P0-1-B-7, Rev.2-b4a1d094-SessionIdPinning, B-4, O-3, A-1, A-3, C-2, A-5, B-1, B-3, C-1, O-1, Herdr-0.8.0-Compat-SanitizeHash, B-8`. (기존 `B-7`, `C-3b`, `O-2`, `A-4`는 위 키 안에 포함되어 유실되지 않는다.)
7. **v4.1.x~v4.4.0 반영** (Rev.1 B-3 유지, 위치만 명확화)
- 기존 `### **B-13 (Stage 2)…` 블록 끝에 1불릿: "v4.4.0(Issue #5 Phase 4)에서 freeze 스냅샷을 기본 경로에서 철거, `MAM_LOOP_FREEZE=1` 롤백 스위치만 잔존 (`docs/contracts/issue-5/phase4-freeze-removal.md`)".
- 신규 블록은 추가하지 않는다(codex/grok/opencode 통합, Python 코어 마이그레이션은 `VERSIONS.md`가 정본이며, 백로그 ID가 부여된 과제가 아니므로 §5에 등재하지 않는다). 대신 `📌 개요` 절 끝에 1문장: "v4.1.0 이후 릴리스 단위 변경 이력은 `VERSIONS.md`를 정본으로 하며 본 백로그는 ID가 부여된 과제만 추적한다."
8. **보존 필수 문자열**: `### **O-1: 타당하지 않은 리뷰 피드백 거부/반론 프로토콜 미지원 (Rebuttal Protocol)**` 제목과 본문은 변경 금지 (`test_o1_rebuttal.py::test_v10`).
- **Phase B 검증 스크립트 (Creator 실행 필수)**:
```bash
f=IMPROVEMENTS.md
test "$(grep -c '^## 2\.' $f)" = 1 && test "$(grep -c '^## 3\.' $f)" = 1
# §5 블록 수 = 31, 헤더 괄호 ID 수 = 31
awk '/^## 5\./{s=1;next} /^## 6\./{s=0} s&&/^### /{n++} END{print n}' $f # → 31
sed -n '6p' $f | grep -o -E '\(B-21.*\)' | tr ',' '\n' | grep -c . # → 31
# 각 완료 ID의 ### 제목이 정확히 1회
for id in B-21 B-20 B-19 B-14 B-15 O-6 O-2 B-8 A-4; do test "$(grep -c "^### \*\*$id[ :(]" $f)" = 1 || echo "DUP/MISSING $id"; done
# §2·§3에 ✅ 완료 블록 잔존 금지
awk '/^## 2\./{s=1} /^## 4\./{s=0} s&&/^### .*✅/{print "LEAK: "$0}' $f
.venv/bin/python -m pytest -q tests/test_o1_rebuttal.py
```
### Phase D-1 (개정) — README 트리의 루트 마크다운 표기 기준
- 양 README의 `text` 트리 **루트 레벨 마크다운 항목은 다음 8개를 알파벳 순으로 전부** 기재한다(언어별 미러 포함, 기존 3~4개 → 8개): `AGENTS.md`, `BOOTSTRAP.ko.md`, `BOOTSTRAP.md`, `IMPROVEMENTS.md`, `MESSAGING.md`, `README.ko.md`, `README.md`, `VERSIONS.md`. 설명 문구만 언어별로 다르다.
- 디렉터리 항목 추가 목록은 Rev.1 D-1 그대로(`lib_py/` 3패키지, `scripts/` shim 재표기, `docs/` 4항목, `nats-docker/`, `tests/`).
- **검증**: 두 파일의 트리 블록에서 `├──|└──`로 시작하는 줄 수가 동일하고, 루트 md 8개 문자열이 양쪽에 각 1회 존재.
### 게이트 4 (개정) — 깨진 상대 링크 0건
- 검사 대상: 루트 8개 + 이관 문서. 링크 경로 추출 후 `test -e`; **단 `git check-ignore -q <path>`가 참인 경로는 검사에서 제외**하지 않고 **오류로 처리**한다(추적되지 않는 파일로의 링크는 문서 결함이므로 Phase A-2 규칙에 따라 링크 자체를 제거/대체해야 한다). 즉 게이트 4 = "모든 링크 대상이 존재하고 git 추적 대상이다".
```bash
for f in README.md README.ko.md BOOTSTRAP.md BOOTSTRAP.ko.md MESSAGING.md IMPROVEMENTS.md AGENTS.md VERSIONS.md docs/contracts/nats-backplane/implementation_plan.md; do
d=$(dirname "$f")
grep -o -E '\]\(([^)#]+)(#[^)]*)?\)' "$f" | sed -E 's/^\]\(//; s/#.*//; s/\)$//' | grep -v -E '^(https?:|mailto:|file:)' | while read -r p; do
t="$d/$p"; { test -e "$t" && git ls-files --error-unmatch "$t" >/dev/null 2>&1; } || echo "BROKEN/UNTRACKED: $f -> $p"
done
done
```
- 주의: `IMPROVEMENTS.md` 248행 등에 `file:///Users/...` 절대 링크가 존재한다. 본 게이트에서는 제외(`file:` 필터)하되, Phase B-3 O-2 병합 시 해당 불릿의 `file://` 링크는 상대 경로 `.agents/skills/multi-agent-mux-loop/scripts/loop_lock.sh`로 교체한다(같은 불릿을 만지는 김에 최소 수정).
---
## 3. 최종 검증 게이트 (Rev.2 확정본)
1. 루트 마크다운 8개, `implementation_plan.md`는 `docs/contracts/nats-backplane/`.
2. `pytest -q tests/test_deploy_layout.py tests/test_o1_rebuttal.py tests/test_deploy_freshness.py tests/test_version_consistency.py` → 49 passed.
3. `pytest -q tests/` → 750 passed.
4. 위 개정 게이트 4 스크립트 출력 0줄.
5. `git diff --stat`에 `.agents/skills/**`, `tests/**`, `deploy/**` 변경 없음.
6. `MAM_INSTALL_DOCS=minimal|full` 설치 시 루트 문서 1개/4개.
7. **(신설)** Phase B 검증 스크립트 전 항목 통과: §5 블록 31 = 헤더 ID 31, §2/§3 완료 블록 누출 0, 잔재 토큰 20종 보존.
## 4. 범위 외 (Rev.1 §4 유지) + 추가
- `nats-docker/PRIVATE_SERVER.md:5` 깨진 링크 — 서브모듈 별도 커밋.
- 미해결 5건(A-2, B-16, B-17, B-18, O-5)의 코드 대조 재판정 — 별도 리뷰 잡. 특히 B-17은 `MESSAGING.md:310`이 "구현됨"으로 서술하고 있어 상태 불일치 의심이 있으나 **본 작업에서는 손대지 않는다**(코드 확인 없이 완료로 옮기면 원장 오염).
- README 배지 5번째 lockstep 레그 — 별도 잡.
## 5. 리스크
- Phase B는 이동·병합이 많아 유실 위험이 가장 크다. 반드시 **B-1 → B-2 → B-3 → B-4 순서**로 각 단계 후 검증 스크립트를 실행하고, 최종적으로 `git diff --stat IMPROVEMENTS.md`의 삭제 줄 수가 (잔재 33줄 + P0-2 제목 1줄 + 이관에 따른 이동분) 범위 안인지 확인한다. 이관은 `git diff`에서 삭제+추가로 보이므로 `git diff --color-moved=plain`으로 이동임을 확인한다.
---
## 부록. Rev.1 원문 중 유효 유지 항목 (변경 없음)
- §0 실측 인벤토리 표 및 KEEP/이관 판정 9건.
- §1 D-2(MESSAGING lib_py 미반영), D-3(README 트리), D-4(BOOTSTRAP §1), D-5(implementation_plan 이관), D-6(AGENTS §5).
- Phase A-1/A-3/A-4, Phase C 전체, Phase D-2~D-4, Phase E, Phase F, Phase G.
@@ -0,0 +1,150 @@
# 📐 Implementation Plan — Job `c107763c`: v4.1.2 Upstream Bug-Fix Triage
- **Planner**: `planner-reviewer-claude-01`
- **Source**: `bug-report/mam_upstream_bug_fix_report.md` (untracked, GAIA Canary Project Team, 2026-08-30)
- **Method**: each of the 4 reported issues was independently re-derived against live source (`lib.sh`, `opencode.py`, adapter base class, callers, existing tests) before accepting or rejecting the report's diagnosis — per standing practice, a field report's own diff is a claim, not evidence.
---
## Verdict per issue
| # | Report's claim | My finding | Action |
|---|---|---|---|
| 1 | `_resolve_herdr_pane_id` generic `agent_kind` fallback misattributes an unrelated same-kind pane | **Confirmed real, unfixed.** | Fix applied |
| 2 | `opencode.py::resume_spec` `--session` flag missing due to `materialized` gate | **Not a defect — working as designed.** | No fix (see rationale) |
| 3 | `opencode.py::ready_tokens` doesn't match the ASCII banner | **Already fixed in v4.1.1** (job `c38ddfcf`, this exact string is live). | No action, stale report entry |
| 4 | `new-session` doesn't reuse an idle pane before splitting | **Confirmed real, unfixed.** | Fix applied |
---
## Issue 1: `_resolve_herdr_pane_id` generic `agent_kind` fallback (`lib.sh` ~line 436)
**Root cause, confirmed by reading the fallback chain in full (`lib.sh:349-450`):** when name/label/agent-exact matching against `herdr pane list` fails, the code looks up the *target's own* kind via `.mam/agent-sessions.yaml` (`agent_kind = s.pane.cmd` for the yaml row whose `name` equals `tn`/`tsa`), then searches **all live panes** for `agent == agent_kind`. If exactly one such pane exists anywhere in the (already workspace-scoped) pane list, it is returned — even though that pane's actual name/label has nothing to do with the target. A second, genuinely same-named agent of the same kind running concurrently (e.g. an orchestrator `agy` pane alongside a dead `creator-agy-01`) gets misattributed as `creator-agy-01`, defeating `has-session`'s liveness check and silently skipping restoration.
**Verified this is reachable in practice**: `has-session`'s shim arm (`lib.sh:590`) falls through to `_resolve_herdr_pane_id "$sess"` exactly on this path, and `resume_session.sh:73` calls `herdr has-session -t "$SESSION_NAME"` with a full role-prefixed name — precisely the target-name-plus-drifted-kind-match scenario in the report.
**Fix**: gate the kind-based fallback so it only fires when the caller's *own* search term already equals the bare kind — i.e. this path is for a caller who searched by kind directly (`target == "agy"`), not for silently broadening a specific-name search into a kind-wide one:
```diff
- if agent_kind:
+ if agent_kind and (tn == agent_kind or tsa == agent_kind):
matching = [p.get('pane_id') for p in panes if p.get('agent') == agent_kind and p.get('pane_id')]
```
**Why this doesn't regress anything**: grepped every real call site of `_resolve_herdr_pane_id` in `lib.sh` (`has-session`, `kill-session`, `capture-pane`, `send-keys`, `set-buffer`) — all pass a full role-prefixed session name (`"$sess"`), never a bare kind string. So in real usage `tn`/`tsa` never equals `agent_kind`, and this fallback branch — which was unsound in every real-world configuration with more than one live agent of the same kind — becomes fully inert rather than merely narrowed. The only existing test touching this path, `test_r1_resolve_pane_id_fail_closed_on_multiple_same_kind_panes` (`tests/test_c1_tui_readiness.py`), asserts the fail-closed (RC=1) outcome on ambiguous multi-match, which still holds unchanged (the branch is skipped, `pid` stays empty, function still returns 1). No test exercises the previous len==1 "success" path, confirming it was never a documented contract.
## Issue 2: `opencode.py::resume_spec` — **rejected the proposed fix**
The report proposes removing the `materialized` gate:
```diff
- if materialized and session_uuid:
+ if session_uuid:
```
**Why this is not a genuine bug**: `if materialized and session_uuid:` is the *identical* pattern in all 5 adapters (`claude.py:97`, `grok.py:105`, `agy.py:90`, `hermes.py:88`, `opencode.py:189`) — this is a deliberate, cross-adapter contract, not an opencode-specific oversight. `materialized` is computed by `__main__.py`'s `resume-spec` CLI as `adapter.verify_artifact(uuid, ctx)` — a real, adapter-specific check (for opencode: a live sqlite query against the local session DB, including epoch and cwd/workspace scoping — see `test_opencode_verify_artifact_created_at_epoch_filtering` in `test_a4_adapter_contract.py`). Its purpose is to avoid ever passing `--session <uuid>` for a session that does not actually exist locally, which would risk the CLI erroring or hanging on an invalid id.
Traced the actual caller, `resume_session.sh:99`: `WORKSPACE` is a required flag (validated at the top of the script), so `DiscoveryContext` is always constructed with a real workspace — `materialized` is never spuriously `False` merely because the workspace argument was missing. I could not reproduce a false-negative in `verify_artifact` itself (DB path resolution, column detection, and `workspace_key()`'s `os.path.realpath()`-based cwd comparison all look sound on inspection, and are covered by existing epoch/cwd tests). Applying the report's fix would (a) break the 5-way adapter consistency this contract relies on, and (b) reintroduce exactly the "resume with an unverified/possibly-nonexistent session id" risk the gate exists to prevent — for no evidence-backed benefit. **No change made.** If the underlying symptom (occasional failure to resume an opencode conversation) recurs, the next diagnostic step is to log `verify_artifact`'s db path / query result for the specific failing session, not to remove the gate.
## Issue 3: `opencode.py::ready_tokens` — already resolved
Live value at `opencode.py:24` is already `'OpenCode|Chat|Ask anything|tab agents|ctrl\\+p|Build auto|commands'` — this is Fix 1 from the v4.1.1 release (job `c38ddfcf`, verified by 3 independent reviewers in that round). The bug report's own "already fixed" diff target matches current source byte-for-byte. This entry in the report is stale (written against a pre-v4.1.1 checkout). No action needed.
## Issue 4: `new-session` idle-pane reuse (`lib.sh` ~line 683)
**Confirmed real**: read the full `new-session` arm. When `existing_ws` is detected (matching cwd), the code unconditionally proceeds to `pane layout` + `pane split` — there is no check anywhere in the current code for a pre-existing, agent-less pane in that workspace. Every `new-session` into an existing workspace therefore grows the pane count monotonically, even if a prior agent's pane is sitting idle, causing pane proliferation and the reported grid-layout churn.
**Fix**: before the existing sample-pane/layout/split logic, query `herdr pane list` (workspace-scoped, client-side filtered — consistent with the existing `sample_pane` lookup two lines below) for a pane with no `agent` assigned; if found, reuse its `pane_id` as `target_pane` directly and skip the split entirely:
```bash
idle_pane=$(_real_herdr pane list 2>/dev/null | TARGET_WS="$existing_ws" python3 -c "
...
for p in panes:
if p.get('workspace_id') == target_ws and not p.get('agent') and p.get('pane_id'):
print(p.get('pane_id')); break
...
" 2>/dev/null || echo "")
if [ -n "$idle_pane" ]; then
target_pane="$idle_pane"
else
# existing sample_pane / layout / split logic, unchanged
fi
```
The existing overflow-threshold-triggers-fresh-workspace branch (`split_dir == "overflow"` → `existing_ws=""`) is preserved unchanged inside the `else`, so idle-pane reuse never bypasses the grid-overflow policy — it only short-circuits when a reusable pane already exists, before that policy is even consulted.
## Tests added
New tests exercising the two fixes, following each file's existing conventions:
- `tests/test_c1_tui_readiness.py`: `test_r2_resolve_pane_id_does_not_misattribute_unrelated_same_kind_pane` — seeds a yaml entry for a target session whose own pane is absent, plus exactly one *unrelated* same-kind live pane; asserts resolution now fails closed (RC=1) instead of returning the unrelated pane's id (the exact regression the report describes).
- `tests/test_herdr_shim_contract.py`: `test_h24_new_session_reuses_idle_pane_without_split` — seeds a raw idle pane (no `agent` key) in the target workspace/cwd via the `mock_herdr` state, calls `herdr new-session`, and asserts (a) the new agent's `pane_id` equals the idle pane's id and (b) no `pane split` call was recorded.
## SemVer
v4.1.1 → **v4.1.2, PATCH** (SemVer 2.0.0 §6): both applied fixes are internal reliability hardening of already-shipped behavior (pane resolution correctness, pane-reuse efficiency) — no public `--agent` value, flag, or YAML own-key added/removed/changed. Matches the v4.1.1 and v3.0.1 PATCH precedents. 3-way lockstep: `lib.sh:32` `MAM_VERSION`, `VERSIONS.md` (header/date/prose/8-row matrix/new changelog section), 8× `SKILL.md` `version:` frontmatter.
## Self-caught regression during implementation
While running the targeted suite after implementing both fixes, 3 previously-passing tests regressed (`test_h16_send_keys_safe_submits_exactly_once`, `test_h18_workspace_scoped_pane_resolution`, `test_h23_persisted_workspace_id_scopes_without_env` — none touching `new-session` or the `agent_kind` fallback directly). Traced it to the Bug-1 fix's own explanatory comment: it used a literal double-quoted phrase (`"any pane of this kind"`) placed *inside* a bash **double**-quoted `python3 -c "..."` block. Bash's own string-termination rules apply inside that block (it's a quoted bash argument, not a heredoc), so the embedded `"` characters prematurely closed the bash string and corrupted the generated Python source for the entire pane-resolution helper — breaking label/name/agent exact-matching too, not just the kind fallback the comment was documenting. Rewrote the comment without embedded double quotes; re-ran the full targeted and full suites clean. Recorded here because it's a instructive shell-scripting trap specific to this codebase's pattern of embedding Python inside double-quoted bash strings (existing code consistently uses single quotes for all embedded Python string literals for exactly this reason — my new comment just hadn't followed that convention).
## Test results
- Targeted suite (`test_a4_adapter_contract.py`, `test_c1_tui_readiness.py`, `test_b19_headless_reconcile_fixes.py`, `test_herdr_shim_contract.py`, `test_version_consistency.py`, `test_tier2_component.py`): **121 passed**.
- Full suite (`tests/`): **449 passed** (447 pre-existing + 2 new regression tests for Bug-1 and Bug-4), 0 failed, 10m21s.
## Review
Per the established MAM workflow, multi-agent peer review (Claude, Grok, OpenCode) is conducted via separately delegated reviewer jobs against this committed diff, not performed by the Planner in this job.
---
## Rev. 2 — Refinement in response to `creator-agy-01`'s architectural challenge (job `d14ab345` → `769e0a1c`)
`creator-agy-01` filed a challenge (`.mam/jobs/d14ab345/agy-reports/report-final.md`) against this plan's Issue-4 fix, plus a secondary observation on Issue-1. Verified both independently against the current live `lib.sh` (still uncommitted working tree, `HEAD=a18f9f8`) rather than accepting the challenge's diagnosis at face value — same standing practice as the original triage. **Both findings are confirmed real; one supporting example in the challenge is corrected below.**
### Finding A (primary): idle-pane reuse drops caller-supplied `KEY=VAL` env tokens — CONFIRMED, fix required
Verified directly: `agent start` (`lib.sh:832,834`) passes only `--kind`, `--pane`, and `-- $final_cmd` — confirmed against the H-1 contract test's own whitelist (`{"--kind", "--pane", "--timeout"}`) and forbidden set (`--env` explicitly forbidden on `agent start` under the live 0.8.0 herdr contract). `$env_flags` (parsed from leading `KEY=VAL` tokens in `run_cmd`, `lib.sh:630-644`) is consumed **only** by `pane split` (`lib.sh:756,770`) and `workspace create` (`lib.sh:785`, plus the extra `--env HERDR_WORKSPACE_ID=...` both add). My idle-pane-reuse branch (`lib.sh:729-731`) sets `target_pane="$idle_pane"` and skips both — `$env_flags` genuinely has nowhere to go on that path. This is a real regression my Bug-4 fix introduced: pre-fix, `new-session` into an existing workspace *always* went through `pane split` (with `$env_flags`), so no gap existed.
**One correction to the challenge's own supporting evidence**: the report's example (`OPENCODE_PERMISSION='{"*":"allow"}'` being lost) does not currently apply — `create_session.sh:217-218` `export`s `OPENCODE_PERMISSION` into its *own* calling shell rather than embedding it as a `KEY=VAL` prefix inside `CMD_FULL` (checked all 3 real `new-session` callers — `create_session.sh`, `resume_session.sh`, `reconcile.sh` — none currently emit a `KEY=VAL`-prefixed command string). So this specific variable was never routed through `$env_flags` even before Bug-4, on any path. That doesn't weaken the finding, though: the `new-session` shim command has a *documented, general-purpose* contract of accepting `KEY=VAL cmd` and threading it through as pane env (the parsing exists precisely for this), and any caller that does use that documented form — current or future — silently loses it exactly as described the moment the target pane happens to be idle-reusable. The defect is in the command's contract, not tied to one specific caller.
**Refined fix** — replay `$env_flags` via a `env(1)` prefix on `$final_cmd` when the idle-pane path is taken, mirroring what `pane split` would have injected server-side (including the same extra `HERDR_WORKSPACE_ID` the split path adds — needed because agents spawned inside the pane may themselves call MAM tooling that reads this var):
```bash
if [ -n "$idle_pane" ]; then
target_pane="$idle_pane"
if [ -n "$final_cmd" ]; then
idle_env="${env_flags//--env /}"
idle_env="${idle_env:+$idle_env }HERDR_WORKSPACE_ID=$existing_ws"
final_cmd="env $idle_env $final_cmd"
fi
else
# existing sample_pane / layout / split logic, unchanged
fi
```
`${env_flags//--env /}` turns `"--env K1=V1 --env K2=V2"` into `"K1=V1 K2=V2"` via plain bash parameter expansion — no new subprocess, no new quoting model, deliberately matching the existing code's own level of robustness (the split/create paths already word-split `$env_flags` unquoted; a value containing a literal space was already fragile there pre-Bug-4, and fixing that broader pre-existing quoting limitation is out of scope for this PATCH). `env` receives literal `KEY=VAL` argv tokens and execs `$final_cmd` with them set — this is the client-side POSIX equivalent of what herdr's own `--env` flag does server-side, so behavior stays consistent whether a pane was split or reused.
**New test to add during implementation**: seed a `new-session` call whose `run_cmd` includes a leading `KEY=VAL` token *and* an idle pane in the target workspace; assert the resulting `agent start` call's trailing command (or the mock's recorded `command`/env-visible field) reflects the env var, and that no `pane split` call occurred. Follows the same fail-old/pass-new verification discipline as `test_h24`.
### Finding B (secondary): the pre-existing exact-match loop's `'agent'` key preempts Bug-1's R-1 guard for bare-kind targets — CONFIRMED, fix required
Traced precisely as the challenge describes: the exact-match loop (`lib.sh:415-422`, pre-existing "ISSUE-2" logic, not part of my Bug-1 diff) iterates `for key in ('label', 'name', 'agent')` and returns on the **first** pane whose `agent` field equals `tn`/`tsa`. If a caller ever does search by a bare kind (`target == "agy"` — the exact scenario my Bug-1 gate's `tn == agent_kind` condition exists to protect, deliberately, per the original plan's own design), this loop matches on `key='agent'` *before* Bug-1's block is even reached, and returns the first same-kind pane with **no ambiguity check** — silently bypassing the R-1 fail-closed guard I added specifically for that case. Currently harmless in practice (verified again: every real call site still passes a full role-prefixed name, never a bare kind — grepped fresh, unchanged from the original triage), but it makes the R-1 protection in Bug-1's own fallback block dead code for the one scenario it was written to cover, which defeats the purpose of writing it.
Checked for test fallout: no existing test seeds a pane whose `agent` field is set to a value equal to the *search target string itself* (`test_r1`/`test_r2` both use full names like `"my-unmatched-session"`/`"creator-agy-01"` as targets, never bare `"agy"`/`"claude"`/`"grok"`) — confirmed via `grep` across `test_c1_tui_readiness.py` and `test_herdr_shim_contract.py`. Removing `'agent'` from this tuple is safe against the current suite.
**Refined fix**:
```diff
- for key in ('label', 'name', 'agent'):
+ for key in ('label', 'name'):
```
This funnels *all* kind-based resolution — whether derived via the yaml lookup (full-name case) or a literal bare-kind search — exclusively through Bug-1's R-1-guarded block, so the multi-match fail-closed check can never be bypassed regardless of which form the target takes.
**New test to add during implementation**: bare-kind target (`_resolve_herdr_pane_id "agy"`) against 2 panes both with `agent == "agy"`; assert fail-closed (RC=1), proving R-1 now actually governs this path instead of being preempted.
### Updated action list for re-implementation
1. Apply the `env` prefix fix to the idle-pane branch (Finding A).
2. Remove `'agent'` from the exact-match tuple (Finding B).
3. Add the two new tests above; re-run the full targeted + full suite (expect 451 passed: 449 + 2).
4. No change to the Issue-2/Issue-3 verdicts or the SemVer classification (still v4.1.2 PATCH) — both new fixes are the same class of internal reliability hardening, not a public-surface change.
@@ -0,0 +1,58 @@
# 🛠️ Implementation Plan: Agent-Creation Reliability Fixes (Job `c38ddfcf`)
- **Author**: `planner-reviewer-claude-01` (Planner)
- **Source**: `mam-agent-creation-fix-report.md` (untracked, root of repo) — a field report describing 4 issues observed while creating `reviewer-opencode-01` and other sessions. At the time this plan was written, **none of the 4 fixes it describes were actually present in the code** (verified directly: `.agents/skills/lib_py/agents/adapters/opencode.py`'s `ready_tokens` was still `'OpenCode|Chat'`, and none of the `lib.sh` diffs it shows existed on disk) — the report documents intended fixes, not landed ones.
- **Branch**: `fix/agent-creation-issues`
- **Status**: Plan executed in this same job — code changed, tests updated/passing, version bumped (see §5).
---
## 1. Problem 1 — OpenCode TUI ready-token mismatch
- **File**: `.agents/skills/lib_py/agents/adapters/opencode.py`
- **Root cause**: `ready_tokens` was `'OpenCode|Chat'`, which never appears in OpenCode's actual TUI (the banner renders as an ASCII block, not text matching those words). `wait_for_tui_ready()` (`.agents/skills/lib.sh:1830`) therefore ran the full 30s timeout loop before declaring readiness (or failing outright), even though the process was healthy.
- **Fix**: extend `ready_tokens` to include real, observed TUI surface text: `'OpenCode|Chat|Ask anything|tab agents|ctrl\+p|Build auto|commands'`. The `\+` escaping is required because `wait_for_tui_ready` matches this string with `grep -E` (confirmed at `lib.sh:1901`); an unescaped `+` would be interpreted as an ERE quantifier.
- **Why safe**: `OpenCodeAgentAdapter` does not override `strong_ready_tokens`/`weak_ready_tokens`, so the base class's default (`strong = ready_tokens`, `weak = ''`) still applies — the 2-tier `S ∨ (W ∧ C)` decision in `wait_for_tui_ready` degrades to plain `S`, matching every other single-tier adapter (`agy`, `hermes`, `grok`).
- **Test impact**: `tests/test_a4_adapter_contract.py::test_adapter_required_properties` hardcodes the exact `ready_tokens` string per agent — updated in lockstep. `tests/test_c1_tui_readiness.py::test_adapter_strong_weak_partition` is schema-agnostic (splits on `|` and checks set algebra) — unaffected.
## 2. Problem 2 — Missing `PYTHONPATH` in the herdr shim
- **File**: `.agents/skills/lib.sh` (the `<<'EOF'` heredoc that `_init_herdr_isolation()` writes to `$WORKSPACE_ROOT/.mam/shim/herdr`)
- **Root cause**: the shim script (once written to disk) directly calls `python3 -m lib_py.layout` (line ~682 in the heredoc) and imports `from lib_py.agents.sanitize import ...` (line ~528). These only resolve if `PYTHONPATH` includes `.agents/skills`. `lib.sh` itself exports `PYTHONPATH` when *sourced* (line 25), but the shim is a **separate executable** invoked directly via `$PATH` by herdr/other processes — it does not always inherit that export (e.g. a freshly spawned pane's shell never sourced `lib.sh`).
- **Fix**: added a self-locating `PYTHONPATH` export at the very top of the heredoc, right after `set -euo pipefail`:
```bash
_SHIM_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
_SKILL_DIR="$(cd "$_SHIM_DIR/../../.agents/skills" 2>/dev/null && pwd || true)"
[ -n "$_SKILL_DIR" ] && export PYTHONPATH="$_SKILL_DIR:${PYTHONPATH:-}"
```
Because the heredoc is single-quoted (`<<'EOF'`), `${BASH_SOURCE[0]}` is **not** expanded at write time — it's copied verbatim and resolves at the shim's own runtime, correctly pointing at wherever `.mam/shim/herdr` actually lives (`$WORKSPACE_ROOT/.mam/shim/../../.agents/skills` = `$WORKSPACE_ROOT/.agents/skills`).
- **Test impact**: `tests/test_herdr_shim_contract.py::test_h19_single_resolver_helper_used_by_all_branches` already asserts `bash -n` on both the generated shim and `lib.sh` — passes. No test previously asserted `PYTHONPATH` presence in the shim; none needed updating.
## 3. Problem 3 — `herdr agent start` timeout treated as unconditional failure
- **File**: `.agents/skills/lib.sh`, the `agent) start)` case arm (~line 756–end of the W5/W6 backoff loop)
- **Root cause**: on a slow TUI render, herdr can return `"timed out waiting for agent startup"`. The existing loop deliberately does **not** treat that string as success (see the pre-existing comment: *"Do NOT treat 'timed out waiting for agent startup' as success: herdr returns that for a dead process too"*) — a correct design constraint I preserved rather than overrode, because herdr genuinely returns identical text for a live-but-slow process and a dead one.
- **Fix**: rather than trusting the ambiguous *text*, added a post-loop branch that re-queries herdr directly for ground truth:
1. If `_herdr_agent_get_scoped "$agent_name"` now resolves a pane_id (i.e. herdr's own registry shows the agent alive), treat as success.
2. Otherwise, fall back to injecting the launch command directly into the pane (`pane send-text` + `pane send-keys ... Enter`, mirroring the existing `paste-buffer` pattern at `lib.sh:1040`), wait 1s, and re-check liveness once more.
3. Only if still unresolved does the existing `exit 1` failure path trigger.
- **Why this doesn't reintroduce the bug the comment warns about**: the original concern was blindly promoting the *timeout string* to success. This fix never inspects the string as a truth signal for liveness — it always asks herdr's live registry, which is authoritative for both the dead-process and slow-render cases.
- **Test impact**: `tests/test_b19_headless_reconcile_fixes.py::test_agent_start_success_tokens_exclude_startup_timeout` (D-1) asserts the *original* success-token grep line still excludes the timeout string — untouched, still passes, since the new logic is a separate branch appended after the loop, not a change to that line.
## 4. Problem 4 — `_resolve_herdr_pane_id` lacks a pane_id fast-path and mismatches on workspace label
- **File**: `.agents/skills/lib.sh`, `_resolve_herdr_pane_id()` (inside the shim heredoc)
- **Root cause (fast-path)**: every call went through `agent get` + `pane list` resolution even when the caller already had a real pane_id (`wN:pM`) in hand — wasted round-trips, and a pointless second point of failure.
- **Root cause (label matching)**: the pane-list-based workspace filter compared `target_ws` directly against each pane's `workspace_id`. If a caller passed a workspace **label** (e.g. `$MAM_WS_LABEL`, such as `"mam-agents"`) instead of the raw id, the filter always failed to match, since panes never carry a label field — only `herdr workspace list` returns `{workspace_id, label}` pairs (confirmed against `tests/conftest.py`'s mock herdr, which is the closest ground truth available for herdr's real JSON schema in this repo).
- **Fix**:
1. Added a fast-path at the top of the function: if `$target` already matches `^w[A-Za-z0-9]+:p[A-Za-z0-9]+$`, return it immediately.
2. Added a `target_ws` normalization step: call `herdr workspace list`, and if `target_ws` isn't already a live `workspace_id`, look it up as a workspace `label` and substitute the resolved id. Falls back permissively to the original value on any lookup failure or no-match (preserves all prior behavior when `target_ws` is already a raw id, which is the common case).
- **Why the fallback is safe under `set -e`**: mirrors the exact pattern already used by `_herdr_agent_get_scoped` a few lines above it — the inner Python explicitly `sys.exit(1)` (printing nothing) on any non-match/exception, and the **outer** `|| echo "$target_ws"` supplies the single fallback line. (An earlier draft of this fix had the Python script itself print-then-succeed in the fallback case, which double-emitted the value once `pipefail` propagated the upstream `_real_herdr` failure — corrected before landing, verified via `test_resolve_pane_id_fails_cleanly_under_set_e`.)
- **Test impact**: `tests/test_b19_headless_reconcile_fixes.py::test_no_substring_matching_remains_in_lib_sh` (D-6) asserts the pane_id regex literal exists inside the function body — still true (now appears twice: once in the new fast-path, once in the pre-existing final validation). `tests/test_b19_headless_reconcile_fixes.py::test_resolve_pane_id_fails_cleanly_under_set_e` (D-4) and `tests/test_herdr_shim_contract.py::test_h20_pane_id_regex_accepts_alphanumeric_workspace` (H-20) both exercise this function with an all-failing mocked `_real_herdr` — both still pass, confirming the new lookup degrades gracefully rather than aborting the shim under `set -euo pipefail`.
## 5. Verification & Versioning
- Targeted tests (`test_a4_adapter_contract.py`, `test_c1_tui_readiness.py`, `test_b19_headless_reconcile_fixes.py`, `test_herdr_shim_contract.py`, `test_version_consistency.py`): **78 passed**.
- Full suite (`pytest tests/ -q`): run and confirmed green before the version bump landed (see job report for the exact count/duration).
- **SemVer classification**: PATCH (`v4.1.0` → `v4.1.1`). None of the 4 fixes add or change any public CLI flag, YAML schema key, or agent-facing contract — they are internal reliability/robustness fixes to code already shipped in `v4.1.0` (TUI-detection tuning, shim environment robustness, a startup-race fallback, and a pane-resolution robustness improvement). This matches the `v3.0.1` precedent (*"Herdr Shim Routing Contract Refactor, Multi-Workspace Isolation"*) — the closest prior release of the same shape.
- 3-way lockstep bump applied: `lib.sh:MAM_VERSION`, `VERSIONS.md` (header + line-24 prose + 8-row matrix + new changelog section), 8× `SKILL.md` frontmatters.
@@ -0,0 +1,253 @@
> [!NOTE]
> This is the durable archive of the OpenCode (`anomalyco/opencode`) Integration Plan (Rev.3, Job `78f332a9`).
> The active mirror at `.agents/reports/implementation_plan.md` now houses the Codex CLI Integration Plan (v4.2.0).
# 🔌 Implementation Plan: OpenCode (`anomalyco/opencode`) Agent Adapter for MAM (Rev.3)
- **Author**: `planner-reviewer-claude-01` (Planner), refined in collaboration with `creator-agy-01` and `reviewer-creator-grok-01`
- **Job**: `de667f0f` → Rev.2 (`c65b0081`) → Rev.3 (`78f332a9`)
- **Status**: Plan only — **no code changed in the repo**. Ready for review/refinement.
- **Scope**: Add `opencode` as a 5th first-class MAM agent backend (alongside `claude`, `agy`, `hermes`, `grok`), per `docs/NEW_AGENT_INTEGRATION_GUIDE.md`'s 5-step procedure.
- **Durable Path**: `.agents/reports/planner-reviewer-claude-01/plan-de667f0f.md` (and `.agents/reports/implementation_plan.md`)
---
## Rev.3 Changelog (Job `78f332a9`)
Reviewers `planner-reviewer-claude-01` (Job `1d63595f`) and `reviewer-creator-grok-01` (Job `56120ad3`) reviewed the Rev.2 plan and working tree. **All 5 findings accepted — zero `[REBUT:]` filed**:
1. **Restored Root `implementation_plan.md` & Namespaced Plan Path (F1)**:
- Root `implementation_plan.md` was restored to its tracked HEAD content (the active *MAM 메시징 백플레인 전환 실행 로드맵* NATS migration roadmap).
- This OpenCode integration plan is permanently housed under `.agents/reports/planner-reviewer-claude-01/plan-de667f0f.md` and mirrored at `.agents/reports/implementation_plan.md` to prevent future root-level collision.
2. **Extended Lockstep Touch-Points Table to 29 Items (F2)**:
- Added items 23–29 covering `create_session.sh` (`spawn()` dispatch case, YAML initialization `elif`, fallback `CMD_FULL` case), `lib.sh` (`send_keys_safe` `_sks_agent` resolution case), `tests/test_tier1_unit.py` (CLI usage assertions), 8× `SKILL.md` (supported agent lists), and `tests/conftest.py` (`mock_agents` stub binary).
3. **Official CLI `opencode db path` Subcommand Integration (F3)**:
- Updated §1.5, §2, and §6 to prioritize the official `opencode db path` subcommand for dynamic database location, dropping hardcoded `storage.db` assumptions.
4. **Headless Permission Architecture via `OPENCODE_PERMISSION` (F4)**:
- Documented the `OPENCODE_PERMISSION='{"*":"allow"}'` process environment variable alongside `--auto` in §1.4, §2, and §9 DoD for unattended automated operations without global config file mutations.
5. **Sandbox-Safe `ctx.home_dir` Binding in `auth_ok` and Artifact Paths (F5)**:
- Replaced `os.path.expanduser('~')` with `ctx.home_dir` in the adapter skeleton and test contract for hermetic sandbox execution.
---
## Rev.2 Changelog (Job `c65b0081`)
`creator-agy-01` filed a formal architectural challenge (Job `ebf97869`) against Rev.1, raising two blind spots. Both accepted:
1. **`reconcile.sh` Drift-C Non-Generic Correction**: Identified that `reconcile.sh` drift-C materialization consists of bespoke per-agent blocks, requiring an explicit `# === drift C (opencode) ===` block for post-spawn discovery agents.
2. **Core `lib_py` Constants Added**: Added `atomic_yaml.py:132` (`running_keys`), `verify_session.py:69` (`mam_row_own_uuid()`), and `workspace_uuid.py:7-12,33` (`OWN_KEY`) to the touch-points list.
---
## 0. Relationship to the existing `new_agent_types_roadmap.md`
`.agents/reports/new_agent_types_roadmap.md` (by `creator-agy-01`, 2026-08-26) sketches a generic "add any new agent" procedure and guesses at OpenCode specifics in its difficulty matrix. This plan **supersedes** that roadmap's OpenCode row:
| | Roadmap's guess | Verified reality (this doc) |
|---|---|---|
| Storage format | "JSON files in `~/.opencode/sessions/`" | **SQLite** since v1.2.0 (Feb 2026); dynamic lookup via `opencode db path` |
| Storage path | `~/.opencode/sessions/` | `~/.local/share/opencode/` (XDG data dir) or project storage via `opencode db path` |
| Ready tokens | `OpenCode\|Chat\|Welcome` | Candidate string pending live TUI pane capture verification (§4) |
| Adapter registry | `ClineAgentAdapter` shown | `cline` fully removed in v4.0.0. Targets current 4-adapter registry (`claude`, `agy`, `hermes`, `grok`) |
---
## 1. Verified OpenCode CLI/Runtime Facts
Source: `opencode.ai/docs/{cli,config,permissions,tui}/`, `github.com/anomalyco/opencode`, and official documentation.
### 1.1 Identity & Install
- **Upstream Repository**: `github.com/anomalyco/opencode` (distinct from the archived `opencode-ai/opencode` / "Crush").
- **Install**: `curl -fsSL https://opencode.ai/install | bash` (also npm/Homebrew).
### 1.2 Execution Modes
- `opencode [project]` — launches the **TUI** (default).
- `opencode run [message..]` — **non-interactive** one-shot CLI execution.
- `opencode db path` — prints the active database file path on stdout.
### 1.3 Relevant CLI Flags & Environment
| Flag / Variable | Purpose |
|---|---|
| `--continue` / `-c` | Resume the most recent session |
| `--session <id>` / `-s <id>` | Continue a specific session ID (cannot pre-assign a new UUID at spawn) |
| `--agent <name>` | Mode selection: `build` (default, write access) or `plan` (read-only) |
| `--auto` | Auto-approves tools that prompt ("ask"); explicit "deny" rules still enforced |
| `OPENCODE_PERMISSION` | Process environment variable for inline JSON permission overrides (e.g. `'{"*":"allow"}'`) |
**Spawn / Discovery Consequence**: OpenCode has **no `--session-id <new-uuid>` pre-assignment flag**. It falls strictly in the **`hermes` / `agy` architectural bucket**: `spawn_spec()` ignores `session_uuid` on initial creation, and MAM learns the assigned session ID post-spawn via `discover()` and `reconcile.sh` Drift-C materialization.
### 1.4 Permissions (Headless & Non-Interactive Configuration)
MAM configures headless unattended execution at the process boundary without mutating user-global config files (`~/.config/opencode/opencode.json`):
1. **CLI Flag**: `--auto` passed in `spawn_spec` / `resume_spec`.
2. **Process Environment Variable**: `OPENCODE_PERMISSION='{"*":"allow"}'` exported in the spawn subshell when full unattended bypass is required.
3. **Optional Project/Global Config**: `<project>/opencode.json` or `~/.config/opencode/opencode.json` can define granular policies if configured by the user.
### 1.5 Session & Artifact Storage
- **Format**: Single SQLite database (since v1.2.0).
- **Dynamic Path Resolution**: `opencode db path` prints the exact database location.
- **Default Storage Roots**: `~/.local/share/opencode/` (global) or `project/<slug>/storage/`.
- **Pre-Implementation Spike (§1.5)**: Run `opencode db path` and `sqlite3 <db> ".schema"` on a live install to verify `session`, `message`, and `part` table column definitions (`cwd`, `created_at` timestamps) before writing SQL queries.
### 1.6 Authentication
- Interactive: `opencode auth login`.
- Multi-provider environment variables: `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, `GEMINI_API_KEY`, `GROQ_API_KEY`.
- Credentials cache: `~/.local/share/opencode/auth.json`.
- `auth_ok()` checks for `auth.json` in `ctx.home_dir` OR any supported provider environment variable.
### 1.7 Exit Key
- Slash command `/exit` (aliases `/quit`, `/q`).
---
## 2. Adapter Contract Decisions (`BaseAgentAdapter`)
| Property/Method | Value | Rationale |
|---|---|---|
| `name` | `'opencode'` | Lowercase identifier |
| `own_key` | `'opencode_session_id_own'` | Matches `<agent>_session_id_own` convention |
| `ready_tokens` | `'OpenCode\|Chat'` (candidate) | Pending live TUI capture verification (§4) |
| `exit_key` | `'/exit'` | Confirmed in CLI docs |
| `delegate_agent_key` | `'opencode-cli'` | Descriptive CLI identifier |
| `identity_cache_fields` | `('session_id',)` | Single-field cache |
| `spawn_spec(binary, session_uuid, use_wrapper)` | `f"{binary} --auto --agent build"` | Non-interactive build mode; ignores `session_uuid` at spawn |
| `resume_spec(binary, session_uuid, materialized)` | `f"{binary} --session {session_uuid} --auto --agent build"` (if materialized) | Passes `--session <id>` once discovered |
| `auth_ok(run_cmd)` | `os.path.exists(f"{ctx.home_dir}/.local/share/opencode/auth.json") or any(env)` | Multi-provider fallback + sandbox-safe path |
| `discover(ctx)` | Queries SQLite DB resolved via `opencode db path` / default root | Discovers new session IDs created since `ctx.epoch` |
| `verify_artifact(uuid, ctx)` | Checks row existence in SQLite `session` table | Validates session persistence |
| `purge_artifacts(uuid, ctx)` | Executes parameterized `DELETE FROM session/message/part WHERE session_id=?` | Cleans SQLite rows on stop `--purge-conversation` |
---
## 3. Complete 29-Point Wiring & Lockstep Table
All 29 locations below must be updated in lockstep:
| # | Component / File | Specific Edit Required |
|---|---|---|
| 1 | `.agents/skills/lib_py/agents/adapters/opencode.py` | Create new adapter class `OpenCodeAgentAdapter` |
| 2 | `.agents/skills/lib_py/agents/registry.py` | Import `OpenCodeAgentAdapter` and register in `_ADAPTERS['opencode']` |
| 3 | `.agents/skills/lib.sh` (kind mapping, ~L606-609) | `*-creator-opencode\|*-planner-opencode\|*-reviewer-opencode) kind="opencode" ;;` |
| 4 | `.agents/skills/lib.sh` (fallback grep chain, ~L610-619) | Add `elif echo "$name" \| grep -qi "opencode"; then kind="opencode"` |
| 5 | `.agents/skills/lib.sh` (binary dedup tuple, ~L632) | Add `'opencode'` to `('claude', 'agy', 'hermes', 'grok', 'opencode')` |
| 6 | `create_session.sh` (line 93 `--agent` whitelist) | Add `opencode` to accepted values |
| 7 | `resume_session.sh` (line 45 `--agent` whitelist) | Add `opencode` to accepted values |
| 8 | `resolve_session_id.sh` (line 39 `--agent` whitelist) | Add `opencode` to accepted values |
| 9 | `update_yaml_resumed.sh` (usage string) | Add `opencode` to usage documentation |
| 10 | `stop_session.sh` (line 94 `--agent` whitelist) | Add `opencode` to accepted values |
| 11 | `orc_onboard.sh` (line 106 case) | Add `opencode` to accepted values |
| 12 | `tests/test_a4_adapter_contract.py` | Add `opencode` to `EXPECTED_OWN_KEYS`, `expected`, `expected_modal` (`None`), `facts_bridge`, and delegate bash snippets |
| 13 | `tests/test_a4_adapter_contract.py` | Add adapter-specific unit tests (`spawn_spec`, `resume_spec`, `auth_ok`, `purge_artifacts`, `discover`) |
| 14 | `tests/test_c1_tui_readiness.py` | Add `opencode` to facts-bridge and SKS session resolution loops |
| 15 | `tests/test_tier2_component.py` | Add OpenCode lifecycle tests (create → YAML → stop → resume) |
| 16 | `.mam.env.example` | Document OpenCode multi-provider API keys and `OPENCODE_PERMISSION` |
| 17 | `docs/NEW_AGENT_INTEGRATION_GUIDE.md` | Update difficulty matrix with OpenCode SQLite storage |
| 18 | `.agents/reports/new_agent_types_roadmap.md` | Add cross-link noting OpenCode details are superseded by this plan |
| 19 | `.agents/skills/lib_py/atomic_yaml.py:132` | Add `'opencode_session_id_own'` to `running_keys` |
| 20 | `.agents/skills/lib_py/verify_session.py:69` | Add `'opencode_session_id_own'` to `mam_row_own_uuid()` |
| 21 | `.agents/skills/lib_py/workspace_uuid.py:7-12, 33` | Add `'opencode'` to `OWN_KEY` dict and `running_ids` list |
| 22 | `reconcile.sh` (auto-reg & own keys) | Add `opencode` to loops (521, 540), entry initialization `elif` (584-601), and `OWN_KEY_BY_AGENT` (611) |
| 23 | `create_session.sh` (spawn dispatch, ~L204) | Add `opencode` to `agy\|hermes\|grok\|opencode)` case |
| 24 | `create_session.sh` (YAML init, ~L399-419) | Add `elif agent == 'opencode': entry['opencode_session_id_own'] = None` |
| 25 | `create_session.sh` (fallback CMD_FULL, ~L180-184) | Add `opencode) CMD_FULL="$BINARY --auto --agent build" ;;` |
| 26 | `lib.sh` (`send_keys_safe` agent resolution, ~L2058-2061) | Add `*-opencode\|*-opencode-[0-9]*\|opencode\|opencode-[0-9]*) _sks_agent="opencode" ;;` |
| 27 | `tests/test_tier1_unit.py` (~L969, 974) | Update expected CLI error usage assertions to include `opencode` |
| 28 | 8× `SKILL.md` supported-agent lists | Update skill documentation to list `opencode` |
| 29 | `tests/conftest.py` (`mock_agents`) | Add mock `opencode` binary fixture and sandbox state support |
---
## 4. TUI Readiness & Empirical Verification
- Initial candidate pattern: `OpenCode|Chat`
- **Empirical Capture Gate**: Before finalizing the PR, capture rendered text from a live `opencode` TUI pane using `herdr pane capture` to confirm the exact ready token and prompt glyphs (`input_prompt`, `input_placeholder`).
---
## 5. Drift Detection Integration & Dedicated Drift-C Block
In `multi-agent-mux-monitor/scripts/reconcile.sh`, add the dedicated OpenCode materialization block:
```python
# === drift C (opencode): opencode 새 session id materialize (per-row own id) ===
for s in d.get('herdr_sessions', []):
if row_agent(s) != 'opencode':
continue
if s.get('status') != 'running':
continue
if s.get('opencode_session_id_own'):
continue
cwd = (s.get('pane') or {}).get('cwd', '')
if not cwd:
continue
# Resolve DB path via opencode db path or default XDG root
db = _resolve_opencode_db(home, cwd)
if not os.path.exists(db):
continue
epoch_threshold = s.get('herdr_session_epoch', 0)
sibling_claimed = [
other.get('opencode_session_id_own')
for other in d.get('herdr_sessions', [])
if other is not s
and (other.get('pane') or {}).get('cwd') == cwd
and other.get('status') not in ('stopped', 'terminated')
and other.get('opencode_session_id_own')
]
s_eval = dict(s)
s_eval['_sibling_claimed_uuids'] = sibling_claimed
valid_candidates = []
try:
conn = sqlite3.connect(db)
rows = conn.execute(
"SELECT id FROM session WHERE cwd=? AND created_at >= ? ORDER BY created_at DESC LIMIT 20",
(cwd, epoch_threshold)
).fetchall()
conn.close()
for (uuid,) in rows:
if uuid in (sibling_claimed or []):
continue
if verify_session_uuid(cwd, 'opencode', uuid, s_eval, mode="discover"):
valid_candidates.append(uuid)
except Exception:
pass
if len(valid_candidates) > 1:
drifts.append({'class': 'C-ambiguous', 'name': s['name'],
'msg': f"{s['name']}: {len(valid_candidates)} candidate transcripts newer than session epoch; not pinning"})
s['last_visible_status'] = f"ambiguous: {len(valid_candidates)} candidates"
actions.append(f"ambiguous candidates: {s['name']}")
elif len(valid_candidates) == 1:
uuid = valid_candidates[0]
cmd = ['bash', '-c', f'source "{lib_sh}" && verify_tui_viewport "{s["name"]}" "opencode" "{cwd}"']
rc = subprocess.run(cmd).returncode
if rc == 0:
_pin_and_verify_resume(s, 'opencode', cwd, uuid, degraded=False)
elif rc == 1:
drifts.append({'class': 'C-warn', 'name': s['name'], 'msg': f"{s['name']}: TUI viewport mismatch for candidate {uuid} — not pinned, will retry next cycle"})
else:
_pin_and_verify_resume(s, 'opencode', cwd, uuid, degraded=True)
```
---
## 6. Definition of Done Checklist
- [ ] Execute `opencode db path` and SQLite `.schema` dump spike on a live install.
- [ ] Confirm TUI ready tokens and input prompt glyphs via empirical pane capture.
- [ ] Verify headless execution under `--auto` + `OPENCODE_PERMISSION='{"*":"allow"}'`.
- [ ] Implement `lib_py/agents/adapters/opencode.py` with sandbox-safe `ctx.home_dir`.
- [ ] Apply all 29 lockstep wiring points across `registry.py`, `lib.sh`, skill scripts, `lib_py` modules, and test fixtures.
- [ ] Add dedicated `reconcile.sh` Drift-C materialization block and corresponding integration test.
- [ ] Verify 100% test pass on full suite (`pytest tests/`).
- [ ] Perform manual end-to-end smoke test (create → prompt → discover → stop/purge).
---
## 7. Effort Estimate
- **Total Estimate**: **~1.5 – 2.0 Days**
- ½ day: SQLite schema spike (`opencode db path`) & TUI token live capture
- ½ day: Adapter implementation & 29-point mechanical wiring
- ½ day: Dedicated `reconcile.sh` Drift-C materialization block & integration tests
- ½ day: End-to-end manual smoke tests & regression verification
@@ -0,0 +1,454 @@
# 🔌 Implementation Plan: Codex CLI (`openai/codex`) Agent Adapter for MAM (Rev.2)
- **Author**: `planner-reviewer-claude-01` (Planner), refined in response to `creator-agy-01`'s architectural challenge
- **Job**: `e30e3123` → Rev.2 (`94a6db78`)
- **Status**: Plan only — **no code changed in the repo**. Ready for review/refinement.
- **Scope**: Add `codex` as a 6th first-class MAM agent backend (alongside `claude`, `agy`, `hermes`, `grok`, `opencode`), per `docs/NEW_AGENT_INTEGRATION_GUIDE.md`'s 5-step procedure.
- **Durable Path**: `.agents/reports/planner-reviewer-claude-01/plan-e30e3123.md` (mirrored at `.agents/reports/implementation_plan.md`).
- **Method**: Every CLI fact is verified against a **live, authenticated Codex CLI install already present on this machine** (`codex-cli 0.153.4`). Rev.2 additionally re-verified both of `creator-agy-01`'s challenge points live before accepting them — see §0.
---
## 0. Rev.2 Changelog — Response to `creator-agy-01`'s Architectural Challenge (Job `004c224d`)
`creator-agy-01` filed a formal challenge against Rev.1 with **1 critical defect + 1 supporting architectural constraint**. Per this session's standing discipline, neither was accepted on the challenger's word alone — both were independently re-verified live on this machine before being incorporated. **Both are accepted — no `[REBUT:]` filed.**
| # | Challenge | My independent verification | Disposition |
|---|---|---|---|
| 1 | **Critical**: Rev.1's `orc_onboard.sh` detection regex (`resume[[:space:]]+[0-9a-f-]{36}`) cannot match the actual command Rev.1 itself specifies (`codex resume --dangerously-bypass-approvals-and-sandbox <uuid>`), because the flag sits between `resume` and the UUID | Ran the exact `cmd_line` from the challenge through Rev.1's regex myself: `echo "$cmd_line" \| grep -oE 'resume[[:space:]]+[0-9a-f-]{36}'` → **empty, exit 1**. Confirmed genuine — Rev.1 contained a self-contradiction between §2 (`resume_spec`) and §1.9/§3 item 27 (the detection regex). Then tested the challenge's proposed Plan A regex on the same input → **correctly extracts the UUID, exit 0**. | **Accepted.** §1.9 and wiring item #27 rewritten to the flag-tolerant regex (verified working, not just proposed) |
| 2 | **Supporting**: `~/.codex/state_N.sqlite` (a `threads` table indexing `id`/`cwd`/`rollout_path`) exists alongside the rollout JSONL files; Rev.1's "single-file format, no DB rows to delete" claim was only half true, and `purge_artifacts()` deleting only the `.jsonl` would leave an orphan DB row | `ls ~/.codex/*.sqlite*` on this machine → confirmed `state_5.sqlite` exists. `sqlite3 ~/.codex/state_5.sqlite ".schema threads"` → confirmed the exact `threads` table the challenge quoted. `sqlite3 ... "SELECT id,cwd,rollout_path FROM threads"` → confirmed 2 real rows exactly matching the 2 real rollout files found earlier. `strings` re-extraction confirmed the `stale_db_path`/`state db discrepancy`/`reconcile_rollout`/`read_repair_rollout_path: upsert_needed` literals the challenge cited. `codex delete --help` → confirmed `codex delete <SESSION> --force` ("Delete without prompting. SESSION must be a UUID") is real, exactly as the challenge's remediation option 1 proposed. | **Accepted**, with one refinement found during my own re-verification (not in the original challenge): `codex debug --help` has **no** `db path`-style introspection subcommand (unlike OpenCode's `opencode db path`), and the state file's numeric suffix (`state_5`) is unverified as stable across Codex versions/installs — hardcoding `state_5.sqlite` the way the challenge's raw example does would itself be fragile. §2's adapter design now resolves the state DB via a `state_*.sqlite` glob (most-recently-modified), and `purge_artifacts()` now shells out to `codex delete <uuid> --force` as the primary mechanism (letting Codex's own reconciliation logic keep the JSONL and DB consistent) with a manual-file-removal fallback only if that call fails |
Net effect: Rev.1's overall architecture and the 46-point wiring table stand — this challenge caught one genuine self-contradiction (the regex) and one genuine completeness gap (the state DB), both now closed. No other part of Rev.1 was found wrong during this re-verification pass.
---
## 1. Verified Codex CLI/Runtime Facts
Source: live `codex --help` / `codex resume --help` / `codex exec --help` / `codex login --help` / `codex delete --help` / `codex debug --help` / `codex doctor --summary` / `codex login status` output, direct `ls`/`find` of `~/.codex/`, live `sqlite3` schema/row inspection of `~/.codex/state_5.sqlite`, and offline `strings` extraction of the installed binary — all run on this machine.
### 1.1 Identity & Install
- Binary: `codex` (this machine: `/Users/godopu16/.local/bin/codex`, version `codex-cli 0.153.4`).
- Config/state root: `~/.codex/` by default, **overridable via the `CODEX_HOME` environment variable** (confirmed: `codex exec --ignore-user-config` help text explicitly says "auth still uses `CODEX_HOME`").
### 1.2 Execution Modes
- `codex [OPTIONS] [PROMPT]` — launches the **interactive TUI** (default, what MAM spawns).
- `codex exec [OPTIONS] [PROMPT]` (alias `e`) — **non-interactive** one-shot execution with `--json` JSONL event streaming and `-o/--output-last-message <FILE>`. Not used by MAM's spawn/resume flow, but confirms Codex has a scriptable mode.
- `codex resume [OPTIONS] [SESSION_ID] [PROMPT]` — resumes a specific session by **UUID or session name, passed positionally**; `--last` picks the most recent session without a picker.
- `codex delete <SESSION> --force` — permanently deletes a saved session by UUID; `--force` skips the confirmation prompt and requires `SESSION` to be a UUID (not a name). Verified via `codex delete --help`.
### 1.3 Relevant CLI Flags & Environment
| Flag / Variable | Purpose | Verified via |
|---|---|---|
| `--dangerously-bypass-approvals-and-sandbox` | Skip all confirmation prompts and run without sandboxing — the unattended-automation flag | `codex --help`, `codex resume --help` (accepted on both) |
| `-s, --sandbox <read-only\|workspace-write\|danger-full-access>` / `-a, --ask-for-approval <on-request\|never>` | Finer-grained alternative to the single bypass flag above | `codex --help` |
| `--approve-for-me` | Routes approvals through automatic review under `workspace-write` — **not** a full bypass | `codex --help` |
| `-C, --cd <DIR>` | Working-root directory for the agent | `codex --help` |
| `--session-id <uuid>` | **Does not exist.** No such flag appears anywhere in `codex --help`'s full option list | Absence confirmed by reading the complete `--help` output |
| `CODEX_HOME` | Overrides `~/.codex` config/session root | `codex exec --ignore-user-config` help text |
| `OPENAI_API_KEY` | Read by `codex login --with-api-key` (via stdin); also stored inside `auth.json` under the `OPENAI_API_KEY` key once logged in | `codex login --help`, `~/.codex/auth.json` key inspection |
### 1.4 Unattended-Execution Decision
Confirmed present. `--dangerously-bypass-approvals-and-sandbox` is accepted by both the top-level `codex` TUI launcher and `codex resume`, so `spawn_spec()`/`resume_spec()` can pass it unconditionally.
### 1.5 Session & Artifact Storage — Dual Layer (Rev.2: corrected)
- **Primary transcript**: JSONL "rollout" files, one per session, at `~/.codex/sessions/<YYYY>/<MM>/<DD>/rollout-<timestamp>-<uuid>.jsonl` — e.g. `~/.codex/sessions/2026/05/23/rollout-2026-05-23T08-23-56-019e5200-ab6a-70f2-b5da-e1ef403f7a40.jsonl`. First line is a `session_meta` record: `{"payload": {"id": "<uuid>", "cwd": "<path>", ...}}`.
- **Secondary index (Rev.2, per the accepted challenge)**: `~/.codex/state_N.sqlite` (this machine: `state_5.sqlite`; **the numeric suffix is not assumed stable** — no `codex debug`/`codex` subcommand introspects its exact filename, unlike OpenCode's `opencode db path`, so the adapter must resolve it via a `state_*.sqlite` glob rather than hardcoding the suffix). Verified live schema: a `threads` table with `id TEXT PRIMARY KEY`, `rollout_path TEXT`, `cwd TEXT`, `created_at`/`updated_at` (plus many version-added trailing columns — the schema has clearly evolved via in-place `ALTER TABLE` across releases, another reason not to hand-roll fragile column-position assumptions). Verified live rows: both real sessions on this machine are indexed here with `id`/`cwd`/`rollout_path` exactly matching their on-disk `.jsonl` files.
- **Codex's own resolution order** (inferred from binary string literals `state db discrepancy during find_thread_path_by_id_str_in_subdir: stale_db_path / mismatched_db_path / falling_back` and `reconcile_rollout` / `read_repair_rollout_path: upsert_needed`): Codex itself queries the state DB first, and has a **self-healing reconciliation path** for when the DB and filesystem disagree (falls back to a filesystem scan, then repairs the DB entry) — this is Codex's own built-in drift-correction, structurally analogous to MAM's own `reconcile.sh`.
- **Architectural consequence for MAM's adapter**: mirror Codex's own resolution order — **query `state_*.sqlite` first** (fast, indexed, avoids any unbounded directory walk), **fall back to the bounded glob** over `sessions/*/*/*/rollout-*.jsonl` if the state DB is missing, unreadable, or the row is stale/absent (mirroring the exact "primary DB, fallback filesystem walk" shape `opencode.py`'s `_resolve_db()` already uses in this codebase, and mirroring what Codex's own binary does internally).
### 1.6 TUI Readiness (candidate, pending empirical capture)
Offline `strings` extraction surfaced real UI literals: `"Ask Codex to do anything"` (composer placeholder) and the banner token `"Codex"`. No `❯` glyph or `─{10,}` rule literal found — different TUI layout family (boxed/panelled, not readline-style). Proposed candidate:
- `ready_tokens`: `'Codex|Ask Codex to do anything'`
- `input_placeholder`: `'Ask Codex to do anything'` (high-confidence — extracted literal)
- `input_prompt` / `input_rule_pattern`: `None` (base-class default) pending live pane capture.
**Hard gate before merge**: capture a real `codex` TUI pane via `herdr pane capture` to confirm exact rendered text.
### 1.7 Exit Convention (verified deviation from every existing adapter)
Binary string table twice describes exiting as a keypress: `"Ctrl+C to exit"`, `"ctrl+c quit"`. No `/exit`/`/quit`/`:q` literal found (real slash commands that do exist: `/keymap`, `/side`, `/review`, `/ide`, `/goal`).
`MAM_EXIT_KEY` is exported by the `facts` bridge and loaded into `send_keys_safe()`'s local scope (`lib.sh:2166`), but **no skill script actually sends it to a pane today, for any agent** — `stop_session.sh` never references `exit_key`/`MAM_EXIT_KEY`. So this remains a required-but-currently-inert contract field. Propose `exit_key = 'Ctrl+C'` (symbolic key name, matching herdr's existing `Escape` send convention), documented as a deliberate divergence.
### 1.8 Authentication
- Interactive: `codex login` (ChatGPT OAuth) or `codex login --with-api-key` (reads `OPENAI_API_KEY` from stdin).
- Credential file: `~/.codex/auth.json` (or `$CODEX_HOME/auth.json`) — verified present, keys `auth_mode`, `OPENAI_API_KEY`, `tokens`, `last_refresh`. `codex login status` confirms `"Logged in using ChatGPT"`; `codex doctor --summary` independently confirms `✓ auth is configured`.
- `auth_ok()`: `os.path.exists(f"{codex_home}/auth.json")` **or** `os.environ.get('OPENAI_API_KEY')`. **Caveat honestly flagged**: whether a bare env var alone (without ever running `codex login --with-api-key`) is sufficient was not empirically tested (this machine is logged in via ChatGPT, not a raw API key).
### 1.9 Session-ID Detection for `orc_onboard.sh` (Rev.2: regex defect fixed)
1. **argv form**: Codex passes the UUID as `codex resume <uuid>` — positional, no flag name. **Rev.1's regex was defective**: `grep -oE 'resume[[:space:]]+[0-9a-f-]{36}'` requires the UUID immediately after `resume`, but the real command line this plan's own `resume_spec`/`CMD_FULL` produce is `codex resume --dangerously-bypass-approvals-and-sandbox <uuid>` — a flag sits in between, so the regex never matches (verified live: exit 1, empty output). **Corrected regex** (challenge's Plan A, live-verified to work): allow arbitrary tokens between `resume` and the UUID, then extract only the UUID:
```bash
codex)
detected_id=$(echo "$cmd_line" | grep -oE 'resume[[:space:]]+.*[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}' | grep -oE '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}' | head -n 1 || true)
;;
```
Already safe under `orc_onboard.sh:135`'s existing `is_valid_id "$detected_id"` UUID-format re-validation, so a slightly looser extraction regex carries no correctness risk.
2. **env var fallback**: no `CODEX_SESSION_ID`-style environment variable found anywhere in `codex --help`. Leave `env_var=""` for `codex` — do not fabricate one.
---
## 2. Adapter Contract Decisions (`BaseAgentAdapter`) — Rev.2
| Property/Method | Value | Rationale |
|---|---|---|
| `name` | `'codex'` | Lowercase identifier |
| `own_key` | `'codex_session_id_own'` | Matches `<agent>_session_id_own` convention |
| `ready_tokens` | `'Codex\|Ask Codex to do anything'` (candidate, §1.6) | Extracted real UI literal, pending live pane-capture confirmation |
| `exit_key` | `'Ctrl+C'` (§1.7) | No typed slash command exists; currently operationally inert framework-wide |
| `delegate_agent_key` | `'codex-cli'` | Matches the `<name>-cli`/`-agent`/`-build`/`-code` suffix convention |
| `identity_cache_fields` | `('session_id',)` | Single-field cache, modern pattern |
| `input_placeholder` | `'Ask Codex to do anything'` | Verified real literal |
| `input_prompt` / `input_rule_pattern` | `None` | No stable glyph found; different TUI layout family |
| `spawn_spec(binary, session_uuid, use_wrapper)` | `f"{binary} --dangerously-bypass-approvals-and-sandbox"` (ignores `session_uuid` — Class A) | §1.3/§1.4 |
| `resume_spec(binary, session_uuid, materialized)` | if `materialized and session_uuid`: `f"{binary} resume --dangerously-bypass-approvals-and-sandbox {session_uuid}"`, else same as `spawn_spec` | Verified `codex resume [OPTIONS] [SESSION_ID]` usage template |
| `auth_ok(run_cmd)` | `os.path.exists(f"{codex_home}/auth.json") or bool(os.environ.get('OPENAI_API_KEY'))` | §1.8, sandbox-safe via `ctx.home_dir` |
| `artifact_path(uuid, ctx)` | **Rev.2**: query `state_*.sqlite`'s `threads.rollout_path WHERE id=?` first; fall back to the bounded glob `sessions/*/*/*/rollout-*-{uuid}.jsonl` if the DB lookup misses | §1.5 — mirrors Codex's own DB-first, filesystem-fallback resolution order |
| `verify_artifact(uuid, ctx)` | Resolve path via the same DB-first/glob-fallback helper; parse first JSONL line's `payload.id`/`payload.cwd` (or use the DB row's `cwd` column directly, skipping the file read, when the DB hit succeeds); apply `ctx.epoch` mtime check | Rev.2: DB row already has `cwd` — avoids opening the file at all on the common (DB-hit) path |
| `purge_artifacts(uuid, ctx)` | **Rev.2**: primary — `subprocess.run([binary_or_'codex', 'delete', uuid, '--force'], ...)`; fallback (only if that call fails/binary unavailable) — manually `os.remove()` the rollout file located via the DB-first/glob-fallback helper, **and** best-effort `DELETE FROM threads WHERE id=?` against the resolved `state_*.sqlite` if it exists | §0 item 2 — avoids orphan DB rows; lets Codex's own reconciliation logic own consistency whenever possible instead of MAM hand-rolling SQL against an evolving schema |
| `discover(ctx)` | **Rev.2**: query `state_*.sqlite`'s `threads` table (`SELECT id, cwd, updated_at FROM threads ORDER BY updated_at DESC LIMIT 50`, filtered by `cwd`/`epoch` in Python) first; fall back to the recursive-glob approach from Rev.1 only if the DB is absent/unreadable | Rev.2 — DB query is a single indexed lookup vs. an N-file glob-and-open walk; also naturally bounded (no unbounded-growth concern for the DB path) |
### Adapter code sketch (`.agents/skills/lib_py/agents/adapters/codex.py`) — Rev.2
```python
import os, json, glob, sqlite3, subprocess
from typing import Optional, Any, List
from lib_py.agents.base import BaseAgentAdapter, DiscoveryContext
from lib_py.verify_session import workspace_key
class CodexAgentAdapter(BaseAgentAdapter):
@property
def name(self) -> str:
return 'codex'
@property
def own_key(self) -> str:
return 'codex_session_id_own'
@property
def ready_tokens(self) -> str:
return 'Codex|Ask Codex to do anything'
@property
def exit_key(self) -> str:
return 'Ctrl+C'
@property
def delegate_agent_key(self) -> str:
return 'codex-cli'
@property
def identity_cache_fields(self) -> tuple:
return ('session_id',)
@property
def input_placeholder(self) -> Optional[str]:
return 'Ask Codex to do anything'
def _codex_home(self, ctx: DiscoveryContext) -> str:
return os.environ.get('CODEX_HOME') or f"{ctx.home_dir}/.codex"
def _state_db(self, ctx: DiscoveryContext) -> Optional[str]:
# Rev.2: no 'codex db path'-equivalent subcommand exists; the numeric
# suffix (state_5.sqlite on this machine) is unverified as stable
# across versions, so resolve dynamically rather than hardcoding it.
matches = glob.glob(f"{self._codex_home(ctx)}/state_*.sqlite")
if not matches:
return None
return max(matches, key=os.path.getmtime)
def _find_rollout_via_db(self, uuid: str, ctx: DiscoveryContext):
"""Returns (rollout_path, cwd) from the state DB, or (None, None)."""
db = self._state_db(ctx)
if not db or not os.path.exists(db):
return None, None
try:
conn = sqlite3.connect(db)
row = conn.execute("SELECT rollout_path, cwd FROM threads WHERE id=?", (uuid,)).fetchone()
conn.close()
if row and row[0] and os.path.exists(row[0]):
return row[0], row[1]
except Exception:
pass
return None, None
def _find_rollout(self, uuid: str, ctx: DiscoveryContext) -> Optional[str]:
path, _ = self._find_rollout_via_db(uuid, ctx)
if path:
return path
# Fallback: bounded glob over the date-nested tree (state DB missing/stale)
matches = glob.glob(f"{self._codex_home(ctx)}/sessions/*/*/*/rollout-*-{uuid}.jsonl")
return matches[0] if matches else None
def artifact_path(self, uuid: str, ctx: DiscoveryContext) -> str:
return self._find_rollout(uuid, ctx) or f"{self._codex_home(ctx)}/sessions/rollout-{uuid}.jsonl"
def verify_artifact(self, uuid: str, ctx: DiscoveryContext) -> bool:
db_path, db_cwd = self._find_rollout_via_db(uuid, ctx)
path = db_path or self._find_rollout(uuid, ctx)
if not path or not os.path.exists(path):
return False
if ctx.epoch and os.path.getmtime(path) < ctx.epoch:
return False
found_cwd = db_cwd
if not found_cwd:
try:
with open(path) as f:
first = f.readline()
found_cwd = json.loads(first).get('payload', {}).get('cwd')
except Exception:
return False
if found_cwd and workspace_key(found_cwd) != workspace_key(ctx.cwd):
return False
return True
def purge_artifacts(self, uuid: str, ctx: DiscoveryContext) -> List[str]:
purged = []
path = self._find_rollout(uuid, ctx)
# Rev.2: prefer the CLI's own delete path (keeps rollout file + state
# DB row consistent via Codex's own reconciliation logic).
try:
res = subprocess.run(['codex', 'delete', uuid, '--force'],
capture_output=True, text=True, timeout=5)
if res.returncode == 0:
if path:
purged.append(path)
return purged
except Exception:
pass
# Fallback: manual removal of the file, plus a best-effort DB row delete.
if path and os.path.exists(path):
os.remove(path)
purged.append(path)
db = self._state_db(ctx)
if db and os.path.exists(db):
try:
conn = sqlite3.connect(db)
conn.execute("DELETE FROM threads WHERE id=?", (uuid,))
conn.commit()
conn.close()
purged.append(f"state db row for thread: {uuid}")
except Exception:
pass
return purged
def spawn_spec(self, binary: str, session_uuid: str = "", use_wrapper: bool = False) -> str:
return f"{binary} --dangerously-bypass-approvals-and-sandbox"
def resume_spec(self, binary: str, session_uuid: str, materialized: bool = False) -> str:
if materialized and session_uuid:
return f"{binary} resume --dangerously-bypass-approvals-and-sandbox {session_uuid}"
return f"{binary} --dangerously-bypass-approvals-and-sandbox"
def auth_ok(self, run_cmd: Optional[Any] = None) -> bool:
home = os.environ.get('HOME_DIR') or os.environ.get('HOME') or os.path.expanduser('~')
codex_home = os.environ.get('CODEX_HOME') or f"{home}/.codex"
return os.path.exists(f"{codex_home}/auth.json") or bool(os.environ.get('OPENAI_API_KEY'))
def discover(self, ctx: DiscoveryContext) -> List[str]:
db = self._state_db(ctx)
if db and os.path.exists(db):
try:
conn = sqlite3.connect(db)
rows = conn.execute(
"SELECT id, cwd, updated_at FROM threads ORDER BY updated_at DESC LIMIT 50"
).fetchall()
conn.close()
candidates = []
for uuid, cwd, _ in rows:
if ctx.workspace and cwd and workspace_key(cwd) != workspace_key(ctx.workspace):
continue
if uuid and self.verify_artifact(uuid, ctx):
candidates.append(uuid)
return candidates
except Exception:
pass
# Fallback: recursive glob (state DB absent/unreadable)
root = self._codex_home(ctx)
candidates = []
paths = sorted(glob.glob(f"{root}/sessions/*/*/*/rollout-*.jsonl"), key=os.path.getmtime, reverse=True)[:50]
for path in paths:
uuid = os.path.basename(path)[:-6][-36:]
if uuid and self.verify_artifact(uuid, ctx):
candidates.append(uuid)
return candidates
```
---
## 3. Full Lockstep Wiring Table (Rev.2)
Same 46-item table as Rev.1, with item #27 corrected per §0/§1.9. Re-derived from the current, live state of every file that mentions `opencode` today (33 files, `.agents/reports/` excluded).
| # | Component / File | Specific Edit Required |
|---|---|---|
| 1 | `.agents/skills/lib_py/agents/adapters/codex.py` | Create new adapter class `CodexAgentAdapter` per §2 (Rev.2: DB-first artifact resolution + `codex delete --force`-based purge) |
| 2 | `.agents/skills/lib_py/agents/registry.py:9,16` | Import `CodexAgentAdapter`; add `'codex': CodexAgentAdapter()` to `_ADAPTERS` |
| 3 | `.agents/skills/lib_py/atomic_yaml.py:132` | Add `'codex_session_id_own'` to `running_keys` |
| 4 | `.agents/skills/lib_py/verify_session.py:69` | Add `'codex_session_id_own'` to the `mam_row_own_uuid()` field list |
| 5 | `.agents/skills/lib_py/workspace_uuid.py:7-12,34` | Add `'codex': 'codex_session_id_own'` to `OWN_KEY`; add `'codex_session_id_own'` to the `running_ids` field list |
| 6 | `.agents/skills/lib.sh:669` (kind mapping) | Add `*-creator-codex\|*-planner-codex\|*-reviewer-codex) kind="codex" ;;` |
| 7 | `.agents/skills/lib.sh:675,680` (fallback grep chain, name + `final_cmd`) | Add `elif echo "$name" \| grep -qi "codex"; then kind="codex"` and the `final_cmd` equivalent |
| 8 | `.agents/skills/lib.sh:694` (binary dedup tuple) | Add `'codex'` to `('claude', 'agy', 'hermes', 'grok', 'opencode', 'codex')` |
| 9 | `.agents/skills/lib.sh:2175` (`send_keys_safe` agent resolution) | Add `*-codex\|*-codex-[0-9]*\|codex\|codex-[0-9]*) _sks_agent="codex" ;;` |
| 10 | `create_session.sh:4,29,33` (usage/help text) | Add `codex` to the `<claude\|agy\|hermes\|grok\|opencode>` listings |
| 11 | `create_session.sh:93-94` (`--agent` whitelist) | Add `codex` to the accepted-values case and the error message |
| 12 | `create_session.sh` (auth preflight, new `elif` block after the existing `opencode` one at line 129) | `elif [ "$AGENT" = "codex" ]; then` check `~/.codex/auth.json` (respecting `CODEX_HOME`) or `OPENAI_API_KEY`, else `codex --version` smoke check |
| 13 | `create_session.sh:192` (fallback `CMD_FULL` case) | Add `codex) CMD_FULL="${RESOLVED_BIN} --dangerously-bypass-approvals-and-sandbox" ;;` |
| 14 | `create_session.sh:216` (`spawn()` dispatch case) | Add `codex` to the `agy\|hermes\|grok\|opencode)` case — no special env-var export needed |
| 15 | `create_session.sh:330` (delegate-agent key resolution) | Add `codex) delegate_agent="codex-cli" ;;` |
| 16 | `create_session.sh:438` (YAML init Python block) | Add `elif agent == 'codex': entry['codex_session_id_own'] = None; entry['session_id_source'] = 'pending-discovery'; entry['session_id_verified'] = False; entry['last_visible_status'] = "unverified"` |
| 17 | `resolve_session_id.sh:4,16,39-40` | Add `codex` to usage text and the `--agent` whitelist case |
| 18 | `resume_session.sh:12,45` | Add `codex` to usage text and the `--agent` whitelist case |
| 19 | `resume_session.sh:65` (FRESH_SPAWN Class-A case) | Add `codex` to `agy\|hermes\|opencode) FRESH_SPAWN=1 ;;` — Codex is Class A |
| 20 | `resume_session.sh:121` (fallback spawn-spec case) | Add `codex) CMD_FULL="${RESOLVED_BIN} --dangerously-bypass-approvals-and-sandbox" ;;` |
| 21 | `resume_session.sh:132` (fallback resume-spec case) | Add `codex) CMD_FULL="${RESOLVED_BIN} resume --dangerously-bypass-approvals-and-sandbox $UUID" ;;` |
| 22 | `update_yaml_resumed.sh:7,14,17` | Add `codex` to usage docs and the Class-A comment listing |
| 23 | `update_yaml_resumed.sh:228` (Python block) | Add `elif agent == 'codex': target['pane']['cmd'] = 'codex'`; if `uuid`: `cmd_full = f'codex resume --dangerously-bypass-approvals-and-sandbox {uuid}'`, `target['codex_session_id_own'] = uuid`; else `cmd_full = os.environ.get('CMD_FULL_OPT', '') or 'codex --dangerously-bypass-approvals-and-sandbox'` |
| 24 | `stop_session.sh:4,15,94-95` | Add `codex` to usage docs and the `--agent` whitelist case + error message |
| 25 | `stop_session.sh:290` (Python capture block) | Add `elif agent == 'codex': target['codex_session_id_own'] = captured` |
| 26 | `orc_onboard.sh:106` (agent-family match) | Add `codex` to the `claude\|agy\|hermes\|grok\|opencode)` case |
| 27 | `orc_onboard.sh:117-133` (CLI-argv detection) | **Rev.2 corrected**: new `codex)` branch using the flag-tolerant regex from §1.9 (`resume[[:space:]]+.*<uuid-pattern>` then extract just the UUID) — **not** the Rev.1 regex, which is confirmed broken against this plan's own `resume_spec` output |
| 28 | `orc_onboard.sh:142-148` (env-var fallback) | Add `codex) env_var=""` explicitly (no known env var — do not fabricate one) |
| 29 | `reconcile.sh:523,542` (agent-name tuples) | Add `'codex'` to both `('claude', 'agy', 'hermes', 'grok', 'opencode')` tuples |
| 30 | `reconcile.sh:603` (fresh-row entry init) | Add `elif agent == 'codex': entry['codex_session_id_own'] = None` |
| 31 | `reconcile.sh:616` (`OWN_KEY_BY_AGENT`) | Add `'codex'` to the tuple |
| 32 | `reconcile.sh` (new dedicated block, after the existing opencode block at line ~787-897) | New `# === drift C (codex) ===` block, **Rev.2**: state-DB-first with glob fallback (see §4) |
| 33 | 8× `SKILL.md` supported-agent lists (`multi-agent-mux-create:132,163-166`; `multi-agent-mux-orc-onboard:11,35,41`; `multi-agent-mux-resume:52,55,61,73,99,110`; `multi-agent-mux-stop:40`) | Add `codex` everywhere `opencode` currently appears in these four files; the other 4 `SKILL.md` files need only the version-frontmatter bump (§6) |
| 34 | `.agents/skills/multi-agent-mux-delegate-job/job-protocol.md:3`, `README.md:3` | No change needed — `codex` already listed informally |
| 35 | `tests/conftest.py` | Add a `codex` mock binary fixture (mirroring `opencode_bin`, line ~972-990) that writes a fake `rollout-<ts>-<uuid>.jsonl` under a temp `$CODEX_HOME/sessions/<Y>/<M>/<D>/` **and** a matching `state_1.sqlite` `threads` row (Rev.2: needed since `discover()`/`verify_artifact()` now query the DB first); add ready-banner/own-key dict entries (lines ~553, ~584) |
| 36 | `tests/test_a4_adapter_contract.py` | Add `codex` to `EXPECTED_OWN_KEYS`, the property tuple, `expected_modal` (`None`), the `facts_bridge` loop (line ~112), a `_seed_codex_session()` helper (mirroring `_seed_opencode_session`, line ~132, **Rev.2**: seeding both the `.jsonl` and the `state_*.sqlite` row), and unit tests for `spawn_spec`/`resume_spec`/`auth_ok`/`purge_artifacts` (**Rev.2**: including a test that `purge_artifacts` falls back to manual removal when the `codex delete` subprocess call fails)/`discover` |
| 37 | `tests/test_c1_tui_readiness.py` | Add `codex` to the facts-bridge and `send_keys_safe` agent-resolution loops (line ~491) and a `check_sks` assertion pair (mirroring lines 528-529, 539-540) |
| 38 | `tests/test_tier1_unit.py` | Update the agent-tuple assertions (lines ~963, 969, 974, 988-989, 994, 1033) to include `codex`; add `test_codex_shell_and_scripts_integration` mirroring `test_opencode_shell_and_scripts_integration` (lines 982-1044); **Rev.2**: add a dedicated regression test asserting `orc_onboard.sh`'s `codex` regex correctly extracts the UUID from `codex resume --dangerously-bypass-approvals-and-sandbox <uuid>` — this is the exact scenario Rev.1 got wrong, so it must be locked down by a test, not just fixed in prose |
| 39 | `tests/test_tier2_component.py` | Add `test_comp_codex_create_and_reconcile_and_stop` mirroring `test_comp_opencode_create_and_reconcile_and_stop` (line ~1229) |
| 40 | `.mam.env.example` (after the existing OpenCode block, line ~110) | Document `OPENAI_API_KEY` and `CODEX_HOME` as an optional override |
| 41 | `docs/NEW_AGENT_INTEGRATION_GUIDE.md` §3 (difficulty matrix) | Update the `Codex CLI` row from the old guessed values to the verified ones from §1 |
| 42 | `.agents/reports/new_agent_types_roadmap.md` §4 | Add a cross-link noting the Codex row is superseded by this plan |
| 43 | `.agents/MULTI_AGENT_RULES.md:21` / `.ko.md:21` | Add `codex` to the Team-Leader agent-name parenthetical, scope confined to that one line each |
| 44 | `README.md:3,17,45,136` / `README.ko.md:3,17,27,118` | Add `codex` to the 5-agent → 6-agent listings, incl. a `codex resume <uuid>` example (positional form, §1.9) |
| 45 | `BOOTSTRAP.md:197` / `.ko.md:196` | Add `codex` to the onboarding agent-name parenthetical |
| 46 | `deploy/INSTALL.md:3` | Add `Codex` to the parenthetical agent list |
---
## 4. `reconcile.sh` Drift-C Block for Codex (Rev.2: state-DB-first)
```python
# === drift C (codex): codex 새 session id materialize (per-row own id) ===
for s in d.get('herdr_sessions', []):
if row_agent(s) != 'codex':
continue
if s.get('status') != 'running':
continue
if s.get('codex_session_id_own'):
continue
cwd = (s.get('pane') or {}).get('cwd', '')
if not cwd:
continue
codex_home = os.environ.get('CODEX_HOME') or f"{home}/.codex"
epoch_threshold = s.get('herdr_session_epoch', 0)
sibling_claimed = [
other.get('codex_session_id_own')
for other in d.get('herdr_sessions', [])
if other is not s
and (other.get('pane') or {}).get('cwd') == cwd
and other.get('status') not in ('stopped', 'terminated')
and other.get('codex_session_id_own')
]
s_eval = dict(s)
s_eval['_sibling_claimed_uuids'] = sibling_claimed
valid_candidates = []
try:
# Rev.2: state DB first (indexed, single query) — dynamic filename,
# no hardcoded suffix (see §1.5 / §2 _state_db()).
state_matches = glob.glob(f"{codex_home}/state_*.sqlite")
state_db = max(state_matches, key=os.path.getmtime) if state_matches else None
rows = []
if state_db and os.path.exists(state_db):
conn = sqlite3.connect(state_db)
rows = conn.execute(
"SELECT id, updated_at FROM threads WHERE cwd=? ORDER BY updated_at DESC LIMIT 20",
(cwd,)
).fetchall()
conn.close()
if not rows:
# Fallback: bounded glob over the date-nested tree
paths = sorted(
glob.glob(f"{codex_home}/sessions/*/*/*/rollout-*.jsonl"),
key=os.path.getmtime, reverse=True
)[:50]
rows = [(os.path.basename(p)[:-6][-36:], os.path.getmtime(p)) for p in paths]
for uuid, ts in rows:
if epoch_threshold and ts and ts < epoch_threshold:
continue
if uuid in (sibling_claimed or []):
continue
if verify_session_uuid(cwd, 'codex', uuid, s_eval, mode="discover"):
valid_candidates.append(uuid)
except Exception:
pass
if len(valid_candidates) > 1:
drifts.append({'class': 'C-ambiguous', 'name': s['name'],
'msg': f"{s['name']}: {len(valid_candidates)} candidate transcripts newer than session epoch; not pinning"})
s['last_visible_status'] = f"ambiguous: {len(valid_candidates)} candidates"
actions.append(f"ambiguous candidates: {s['name']}")
elif len(valid_candidates) == 1:
uuid = valid_candidates[0]
cmd = ['bash', '-c', f'source "{lib_sh}" && verify_tui_viewport "{s["name"]}" "codex" "{cwd}"']
rc = subprocess.run(cmd).returncode
if rc == 0:
_pin_and_verify_resume(s, 'codex', cwd, uuid, degraded=False)
elif rc == 1:
drifts.append({'class': 'C-warn', 'name': s['name'], 'msg': f"{s['name']}: TUI viewport mismatch for candidate {uuid} — not pinned, will retry next cycle"})
else:
_pin_and_verify_resume(s, 'codex', cwd, uuid, degraded=True)
```
`verify_session_uuid()` (shared, `lib_py/verify_session.py`) needs a `codex_session_id_own` entry added to its own-key list (wiring item #4) for the `C0`-class "confirm, don't discover" path.
---
## 5. `status.sh`
Both `resume_on_disk()`-style helpers (lines ~56-61, ~234-239) iterate `('claude', 'agy', 'hermes', 'grok', 'opencode')`. Add `codex` to both tuples and a new `if agent == 'codex':` branch resolving via the same DB-first/glob-fallback helper as the adapter (§2), returning `'yes'`/`'MISSING'`/`'no'`.
---
## 6. Version & Documentation Bump
Current: `MAM_VERSION="4.1.3"`. Propose **`4.1.3 → 4.2.0` (MINOR)**, matching the OpenCode precedent, in strict 3-way lockstep (`lib.sh:32`, `VERSIONS.md`, all 8 `SKILL.md` frontmatter) per `tests/test_version_consistency.py`. No new agent-specific guide needed (no local-LLM/Ollama angle for Codex).
---
## 7. Empirical Verification Gate (must happen before merge)
1. Live pane capture to confirm `ready_tokens`/`input_placeholder` (§1.6).
2. Live smoke test that `--dangerously-bypass-approvals-and-sandbox` suppresses every confirmation prompt in a real multi-file-edit task.
3. Live test of the corrected `orc_onboard.sh` regex (§1.9) against a real running `codex resume <uuid>` process's `ps`/`/proc` argv snapshot — the regex was verified against a synthetic string in this planning pass, not a real captured process line.
4. **(Rev.2, new)** Confirm the `state_*.sqlite` glob resolves correctly on a *different* Codex install/version than this machine's `state_5.sqlite` — the numeric suffix is not a documented, guaranteed-stable contract, only an observed fact on one install.
---
## 8. Definition of Done Checklist
- [ ] Complete Phase 0 empirical gate (§7), including the new Rev.2 state-DB-portability check.
- [ ] Implement `.agents/skills/lib_py/agents/adapters/codex.py` per §2 (DB-first resolution, `codex delete --force`-based purge with fallback).
- [ ] Apply all 46 lockstep wiring points in §3, including the **corrected** `orc_onboard.sh` regex (item #27).
- [ ] Add the dedicated `reconcile.sh` Drift-C block (§4, state-DB-first) and its `C-ambiguous`-scenario test.
- [ ] Add all test coverage in §3 items #35-39, **including the regression test locking down the corrected `orc_onboard.sh` regex** (item #38) and the `purge_artifacts` CLI-then-fallback test (item #36); `pytest tests/` shows 0 regressions.
- [ ] Bump version to `4.2.0` in strict 3-way lockstep (§6).
- [ ] Correct the two speculative prior reports' Codex rows (§3 items #41-42).
- [ ] Manual end-to-end smoke test: create → prompt → status shows `yes` → reconcile materializes `codex_session_id_own` → stop → resume round-trips → purge leaves no orphan `.jsonl` or `state_*.sqlite` row.
---
## 9. Effort Estimate
- **Total Estimate**: **~1.5-1.75 days** (Rev.2: +0.25 day vs. Rev.1 for the state-DB-aware adapter logic and the corrected/tested `orc_onboard.sh` regex).
- ~2-3 hrs: Phase 0 empirical gate (§7), including the new state-DB-portability check.
- ~4-5 hrs: adapter implementation (DB-first + glob-fallback throughout) + the 46-point mechanical wiring pass.
- ~2-3 hrs: dedicated `reconcile.sh` Drift-C block + `status.sh` + full test suite additions, including the two Rev.2 regression tests.
- ~2 hrs: docs/version bump + end-to-end manual smoke test (including a purge-leaves-no-orphan-row check).
@@ -0,0 +1,208 @@
# 📋 Implementation Plan — Project-Wide Markdown Audit & Cleanup (Job `e359e7af`)
- **Planner**: `planner-reviewer-claude-01`
- **Status**: Plan only — **no files changed in the repo by this job.** Ready for review/handoff to a Creator (or a follow-up Planner job) for execution.
- **Scope**: Full inventory of every `.md` file in the repository, classified into (a) stray/duplicate files to remove, (b) files that need v4.1.3-era content updates, (c) files that are already current and must not be touched. All findings below were derived by reading the actual files, `git log`, and cross-referencing every candidate deletion against the rest of the codebase — not assumed from the brief's examples.
- **Rev. 2 note**: this plan was refined in response to an architectural challenge (`creator-agy-01`, job `9dcd14f6`) that identified a genuine survey blind spot in Rev.1's §1. See the changelog at the very bottom of this document for what changed and why.
---
## 1. Survey method
- `find . -name "*.md"` across repo root, `docs/`, `deploy/`, `.agents/skills/`, **and `.agents/` itself (top-level, non-recursive — Rev.1 only listed `.agents/skills/` explicitly and this omitted the two repository-charter files sitting directly in `.agents/`; see Rev.2 changelog)** (excluding `.agents/reports/` archives, which are immutable per-job history and out of scope — see §5).
- For every root-level file flagged as possibly stale in the brief, read its content, `git log -1 -- <file>`, and `grep -rl` for cross-references from other live docs/skills before proposing deletion.
- For README/BOOTSTRAP/deploy docs, grepped for `opencode|grok|hermes|cline|v4\.` to find version/agent-roster gaps.
- Re-ran `pytest tests/test_version_consistency.py` at current HEAD to confirm the 3-way lockstep baseline this plan must not disturb: **2 passed**.
---
## 2. Findings — file deletions (duplicate/stray cleanup)
### 2.1 `mam-agent-creation-fix-report.md` (repo root) — **DELETE**
- `diff mam-agent-creation-fix-report.md bug-report/mam-agent-creation-fix-report.md` → **byte-identical**.
- The properly-namespaced copy already lives at `bug-report/mam-agent-creation-fix-report.md` (added in commit `ccdde63`, "docs(bug-report): add upstream bug fix report artifact"), alongside its sibling `bug-report/mam_upstream_bug_fix_report.md`.
- Historical archived reports (`.agents/reports/reviewer-opencode-01/report-89fd2305.md`, `.agents/reports/creator-agy-01/report-final-v4.1.1.md`, `.agents/reports/planner-reviewer-claude-01/plan-c38ddfcf.md`) cite this filename as a "field report... at root of repo" — those citations describe the historical state at the time they were written and remain valid as history regardless of where the file physically sits today (git history retains the original root copy for anyone tracing those citations).
- **Action**: `git rm mam-agent-creation-fix-report.md` (root copy only). Keep `bug-report/mam-agent-creation-fix-report.md` untouched.
### 2.2 `implementation_plan.md` (repo root) — **KEEP, do not delete or merge**
Initially flagged by the brief as a possible duplicate/temp file alongside the root fix-report. Verified this is **not** stale:
- It is the live execution roadmap for the **O-5 / A-2 messaging-backplane migration** (HiveMQ → private `nats-server`), which `IMPROVEMENTS.md` still lists as an **open, actively-tracked backlog item** (`O-5`, Track 1, "차순위 P2 — 브로커 스파이크 검증").
- `nats-docker/` (the submodule this plan tracks) exists on disk and is referenced from `nats-docker/PRIVATE_SERVER.md`, which itself links back to `implementation_plan.md`.
- `.agents/skills/multi-agent-mux-loop/SKILL.md:72,148` documents `implementation_plan.md` as the **standard, conventional artifact name** every Planner is instructed to create/maintain per project — it is not a one-off stray file, it's the load-bearing convention filename.
- Note: `.agents/reports/implementation_plan.md` (an unrelated, already-completed OpenCode-adapter plan, archived under a Planner's report namespace) shares the same *basename* but is a completely different document in a completely different directory. This is a harmless naming coincidence — no action needed, do not conflate the two or attempt to "de-duplicate" them.
- **Action**: none. Leave `implementation_plan.md` exactly as-is.
### 2.3 `IMPROVEMENTS.md`, `MESSAGING.md`, `AGENTS.md` (repo root) — **KEEP**
- `IMPROVEMENTS.md`: live backlog tracker (5 open items: `A-2`, `B-16`–`B-18`, `O-5`), last touched 2026-08-24, directly cross-referenced by `implementation_plan.md` and `.mam.env`-adjacent docs. Its historical `cline` mentions (lines 34, 110-111) are **changelog/history entries describing a past state** ("이전에 cline이 존재했을 때..."), not current-state claims — correctly left as-is per standard changelog append-only practice (same treatment `VERSIONS.md`'s v3.x/MAJOR-release history section already receives, and which was explicitly endorsed as correct in this session's prior review of `VERSIONS.md`).
- `MESSAGING.md`: companion technical-analysis doc for the same O-5/A-2 track, linked from `implementation_plan.md`'s header. Live.
- `AGENTS.md`: generic LLM behavioral-guidelines doc, version-agnostic, no agent-roster or MAM-version content to go stale. Live.
- **Action**: none.
### 2.4 `bug-report/` directory — **KEEP as-is**
Both files (`mam_upstream_bug_fix_report.md`, `mam-agent-creation-fix-report.md`) are dated 2026-08-30, properly namespaced, and not duplicated elsewhere except the root stray copy handled in §2.1. No action beyond that deletion.
---
## 3. Findings — content updates needed (v4.1.3 / current-architecture sync)
### 3.1 `README.md` / `README.ko.md` — **out of date, needs update**
- Grepped for `opencode|grok` in both files: **zero matches in either file.** The docs describe the framework as if only `claude`/`agy`/`hermes` exist (README.md:43 mentions only `claude -r <uuid>` / `hermes --resume <uuid>` as examples) and never mention:
- The 5-agent roster (`claude`, `agy`, `hermes`, `grok`, `opencode`).
- The Herdr daemon process-group isolation feature shipped in v4.1.3 (`start_new_session=True` detachment — see `VERSIONS.md`'s current-release summary).
- Any version string at all (no `v4.1.x` mention anywhere in either file).
- **Concrete edits**:
1. Wherever the docs enumerate supported agents (README.md's architecture/feature-list sections), extend `claude`/`agy`/`hermes` → `claude`, `agy`, `hermes`, `grok`, `opencode` (5 agents), matching `docs/NEW_AGENT_INTEGRATION_GUIDE.md`'s registry.
2. Add one sentence to the feature/architecture section noting Herdr daemon isolation (background server processes spawn in their own OS session/process-group via `start_new_session=True`, so they survive process-group signal delivery to the parent shell — this is the actual v4.1.3 content, phrase it in README's existing voice/register rather than copy-pasting VERSIONS.md's changelog prose verbatim).
3. Add a version badge/line (e.g. near the top, alongside the existing tagline) citing `v4.1.3`, sourced from `VERSIONS.md`'s current-release header — do **not** hardcode a version number that would need to be manually bumped every release; either reference `VERSIONS.md` directly or use a badge mechanism, so this doesn't become a 9th lockstep touchpoint that regresses at the next PATCH/MINOR bump.
4. Apply the identical set of edits to `README.ko.md` (Korean mirror) — keep both language versions in sync, same content, same structure.
### 3.2 `BOOTSTRAP.md` / `BOOTSTRAP.ko.md` — **out of date, needs update**
- Same gap: zero `opencode`/`grok` mentions, no version reference, in either file.
- **Concrete edits**: same shape as §3.1 — extend the agent roster wherever `BOOTSTRAP.md` walks through onboarding/setup steps that name specific agents, and add the same lightweight version reference. Keep `BOOTSTRAP.ko.md` in lockstep with `BOOTSTRAP.md`.
- **Rev. 2 addition — §1 "Scaffolding Overview" skill list is incomplete**: verified directly (`sed -n '15,30p' BOOTSTRAP.md` / `BOOTSTRAP.ko.md`) that the `skills/` bullet list under the scaffolding-overview section names only 6 of the 8 lockstep-tracked skills — `multi-agent-mux-create`, `-stop`, `-resume`, `-status`, `-monitor`, `-delegate-job`. **`multi-agent-mux-loop` and `multi-agent-mux-orc-onboard` are both missing** from this list in both language files, even though both are shipped, version-locked skills (`grep -n "^version:" .agents/skills/*/SKILL.md` confirms both carry `version: 4.1.3` same as the other 6). Add two bullets for them, matching the existing bullet style/format (one-line description each, e.g. `multi-agent-mux-loop/`: recurring/self-paced prompt execution on an interval; `multi-agent-mux-orc-onboard/`: orchestrator onboarding/handshake helper — confirm exact wording against each skill's own `SKILL.md` `description:` frontmatter rather than paraphrasing from memory). Apply to both `BOOTSTRAP.md` and `BOOTSTRAP.ko.md`, same position (end of the `skills/` sub-list), keeping the two files in parity.
- Note: `BOOTSTRAP.md:57`'s "Legacy Config Migration" note (`.env` → `.mam.env`) is accurate and unrelated to the agent-roster/version gap — leave it untouched.
### 3.3 `deploy/INSTALL.md` — **minor update**
- Line 3 already says *"복수의 에이전트(Claude, Agy, Hermes, Grok 등)들이..."* — the trailing `등` ("etc.") technically covers `opencode`, but since `opencode` is a fully first-class 5th agent (not a minor/edge one), it should be named explicitly for clarity, matching how `grok` already earned an explicit mention.
- **Concrete edit**: line 3 → *"...(Claude, Agy, Hermes, Grok, OpenCode 등)..."*. One-word addition, no structural change.
- No `cline` references found in this file (`grep -n "cline" deploy/INSTALL.md` → empty) — the brief's "삭제된 cline 언급 정리" concern does not apply here; already clean.
### 3.4 `deploy/README.md` — **no change needed**
- Contains no agent-specific roster claims (it describes the deployment *tooling* — `install.sh`, `update.sh`, etc. — not the agent backends). No `cline` references. No action.
### 3.5 `docs/NEW_AGENT_INTEGRATION_GUIDE.md`, `docs/OPENCODE_OLLAMA_GUIDE.md` — **no change needed**
- Both already reflect the current 5-agent architecture (`NEW_AGENT_INTEGRATION_GUIDE.md`'s worked example is literally "how `grok` was added," and its assertion set/registry checks already list `{claude, agy, hermes, grok}` plus the guide text explicitly frames `opencode` as one of the example agents a reader might add next). No `cline` references in either. No action.
### 3.6 `docs/MAM_WEB_PTY_BRIDGE_PLAN.md` — **no change needed**
- Independent, still-forward-looking architecture plan for a browser PTY bridge; not agent-roster or version-coupled. No action.
### 3.7 `.agents/skills/multi-agent-mux-resume/SKILL.md:71-75` — **known, already-specified fix**
This was already identified as a non-blocking finding in the prior post-commit review (job `4d3c2c1c`, `report-final.md` §2) and is now in-scope for this cleanup pass:
- **Current (inaccurate) text**, inside the illustrative "Workflow" bash snippet:
```bash
if [ -z "$UUID" ]; then
# For Class A, resume_session.sh handles fresh-spawn fallback automatically.
echo "No saved session for $WORKSPACE ($AGENT). Class B agents must use multi-agent-mux-create first."
exit 1
fi
```
The echo text does not match the real, unchanged `resume_session.sh:67` error string (`"ERROR: No saved session for $WORKSPACE ($AGENT). Use multi-agent-mux-create first."` — no "Class B agents must" phrase; the real script also never reaches this echo for Class A agents at all, since `resume_session.sh` branches internally on agent class before this point).
- **Fix**: replace the flat illustrative echo with a version that actually mirrors the real script's branch, e.g.:
```bash
if [ -z "$UUID" ]; then
case "$AGENT" in
agy|hermes|opencode)
: # resume_session.sh handles fresh-spawn fallback automatically (FRESH_SPAWN=1)
;;
*)
echo "ERROR: No saved session for $WORKSPACE ($AGENT). Use multi-agent-mux-create first." >&2
exit 1
;;
esac
fi
```
This mirrors the real `resume_session.sh` branch structure (case-per-agent-class) instead of a single flat message, and uses the byte-exact real error string. It also closes the pre-existing gap noted in the prior review — the Workflow snippet's two further `case "$AGENT" in ...` blocks have never had an `opencode` arm even though `opencode` is fully supported; while not strictly this line-range's job, if this file is being touched anyway the executing agent should add the missing `opencode)` case arms in the same pass.
- **Rev. 2 — verified exact fix for the two downstream case blocks** (raised by `creator-agy-01`'s challenge, job `9dcd14f6`; independently re-verified against the live adapter source before accepting, not taken on the challenge's word alone):
- **Line 88-93** (the `CMD_FULL` determination block) is currently:
```bash
case "$AGENT" in
claude) CMD_FULL="claude --dangerously-skip-permissions $CLAUDE_ID_FLAG $UUID" ;;
agy) CMD_FULL="agy --dangerously-skip-permissions --conversation $UUID" ;;
hermes) CMD_FULL="hermes --resume $UUID --no-restore-cwd --yolo --accept-hooks" ;;
grok) CMD_FULL="grok --resume $UUID --permission-mode bypassPermissions" ;;
esac
```
Add one more arm: `opencode) CMD_FULL="opencode --session $UUID --auto --agent build" ;;`. This exact string is **not a guess** — it was checked directly against `.agents/skills/lib_py/agents/adapters/opencode.py:188-191`'s `resume_spec()`: `f"{binary} --session {session_uuid} --auto --agent build"` when `materialized and session_uuid` (the case this illustrative snippet is modeling — an already-saved UUID). The proposed text is byte-for-byte what that method returns.
- **Line 96-106** (the spawn-dispatch block) currently ends its non-claude branch with `agy|hermes|grok)` (line 103). Since `opencode`, like `agy`/`hermes`/`grok`, needs no `claude`-specific TUI dialog handling, it belongs in the same branch — change line 103 to `agy|hermes|grok|opencode)`. No new branch needed, just widening the existing pattern-match arm.
- Line 55 (prose) is already correct and must not be touched.
### 3.8 `.agents/MULTI_AGENT_RULES.md` / `.agents/MULTI_AGENT_RULES.ko.md` — **out of date, needs update (Rev. 2 addition)**
Raised by `creator-agy-01`'s architectural challenge (job `9dcd14f6`) as a genuine **survey scope blind spot**: Rev.1's §1 survey method named `.agents/skills/` explicitly but never listed the `.agents/` top-level directory itself, so these two repository-charter files — which sit directly in `.agents/`, not under `.agents/skills/` — were never enumerated by the original audit. Independently re-verified before accepting into this plan (not taken on the challenge's word alone):
- `.agents/MULTI_AGENT_RULES.md:21` (confirmed via direct read): *"Newly spawned agents (e.g., `antigravity`, `claude`, `cline`, `hermes`) act as **Team Leaders** of their respective groups."* — still lists the fully-removed `cline` agent (deprecated/removed at the v4.0.0 MAJOR release per `VERSIONS.md`'s history section) and omits both `grok` and `opencode`, the two agents added since.
- `.agents/MULTI_AGENT_RULES.ko.md:21` (confirmed via direct read): the Korean mirror has the identical gap — *"새롭게 생성되는 에이전트(`antigravity`, `claude`, `cline`, `hermes` 등)는 각 팀의 **팀장** 역할을 수행합니다."*
- **Why this is high-impact, not cosmetic**: this file is the mandatory onboarding read for every newly spawned agent. Confirmed two independent live cross-references instructing agents to read it first: `AGENTS.md:70` (*"Read [MULTI_AGENT_RULES.md](.agents/MULTI_AGENT_RULES.md) ... first before working"*) and `BOOTSTRAP.md:193` (*"onboarding agents should immediately read the **[MULTI_AGENT_RULES.md](.agents/MULTI_AGENT_RULES.md)** guidelines"*). A `grok` or `opencode` agent onboarding today reads a charter that doesn't list its own agent name among the Team Leader roster and still lists a deleted one — a real, user-facing inconsistency that fits squarely inside "Project-Wide Markdown Audit."
- **Concrete edits**:
- `MULTI_AGENT_RULES.md:21`: `Newly spawned agents (e.g., \`antigravity\`, \`claude\`, \`hermes\`, \`grok\`, \`opencode\`) act as **Team Leaders** of their respective groups.` (drop `cline`, add `grok`/`opencode` — 5-agent roster, same ordering convention as the rest of this audit).
- `MULTI_AGENT_RULES.ko.md:21`: `새롭게 생성되는 에이전트(\`antigravity\`, \`claude\`, \`hermes\`, \`grok\`, \`opencode\` 등)는 각 팀의 **팀장** 역할을 수행합니다.`
- Scope is deliberately narrow to line 21 (the one sentence enumerating the agent roster) — do **not** sweep the rest of either file for other possible staleness in this pass; if a broader read turns up more, flag it as a new finding rather than silently expanding this edit's blast radius.
---
## 4. Version lockstep — must remain untouched and green
This is a **documentation-content-only** pass. None of the three lockstep touchpoints are in scope for edits:
- `.agents/skills/lib.sh:32` (`MAM_VERSION="4.1.3"`) — no change.
- `VERSIONS.md` current-release header / skill matrix — no change (already correctly at v4.1.3; this job is about *other* docs catching up to what `VERSIONS.md` already states, not about `VERSIONS.md` itself).
- All 8 `SKILL.md` `version:` frontmatter fields — no change (all already `4.1.3`, confirmed via `grep -n "^version:" .agents/skills/*/SKILL.md`).
**Regression guard for the executing Creator/Planner**: after making the §3 edits, re-run:
```bash
.venv/bin/python -m pytest tests/test_version_consistency.py -v
.venv/bin/python -m pytest tests/ -q # full suite — doc-only changes should not affect any test, but confirm
```
Both must stay green. If any editor tool accidentally touches a `version:` line or `MAM_VERSION=` while doing a find-and-replace across `.agents/skills/`, the lockstep test will catch it immediately — treat any failure here as a hard blocker, not a doc nit.
---
## 5. Explicitly out of scope (do not touch)
- `.agents/reports/**/*.md` — immutable per-job archival history (plans, reports, peer-review verdicts). Contains many historical `cline` references and two `implementation_plan.md`-named files; these are frozen historical records, not living docs, and must never be edited/pruned by a "cleanup" pass.
- `VERSIONS.md`'s historical changelog sections (pre-v4.1.3 entries, including the MAJOR `cline`-removal entry) — changelog history is append-only by convention; do not edit past entries.
- `nats-docker/` submodule contents — separate submodule, not this repo's direct concern.
- `IMPROVEMENTS.md`'s backlog freshness (open items, "최종 갱신일" date) — a full backlog refresh is a distinct piece of work from a markdown *audit/cleanup*, and is not called for by the brief's checklist. Flagging only as a possible future follow-up, not part of this job's deliverable.
---
## 6. Recommended execution order (for the Creator who implements this plan)
1. `git rm mam-agent-creation-fix-report.md` (§2.1) — single-file deletion, zero content risk, do first.
2. `.agents/MULTI_AGENT_RULES.md:21` + `.agents/MULTI_AGENT_RULES.ko.md:21` fix (§3.8, Rev. 2) — single-line-per-file, well-specified, isolated. Do early since it's the highest-impact item (mandatory onboarding read) and carries the least edit risk.
3. `.agents/skills/multi-agent-mux-resume/SKILL.md:71-75, 88-93, 103` fix (§3.7, including the Rev. 2 opencode case arms) — small, well-specified, isolated.
4. `deploy/INSTALL.md:3` one-word edit (§3.3).
5. `README.md` + `README.ko.md` sync (§3.1) — do both languages in the same commit so they never drift out of parity.
6. `BOOTSTRAP.md` + `BOOTSTRAP.ko.md` sync (§3.2, including the Rev. 2 8-skill scaffolding-list fix) — same pairing discipline.
7. Run the regression guard in §4.
8. Hand to Reviewers (Claude/Grok/OpenCode) for cross-review against this plan's checklist — reviewers should verify each §2/§3 item was actually applied (or correctly left alone) and that §5's out-of-scope files were **not** touched (`git diff --stat` should show no changes under `.agents/reports/`, `VERSIONS.md`, `nats-docker/`, or any `SKILL.md` `version:` line).
## 7. Acceptance checklist (for reviewers)
- [ ] `mam-agent-creation-fix-report.md` removed from repo root; `bug-report/` copy intact and unchanged.
- [ ] `implementation_plan.md`, `IMPROVEMENTS.md`, `MESSAGING.md`, `AGENTS.md` unchanged (byte-identical to pre-job state).
- [ ] `README.md`/`README.ko.md` now mention all 5 agents (`claude`, `agy`, `hermes`, `grok`, `opencode`) and reference v4.1.3 / Herdr daemon isolation, with both language files in parity.
- [ ] `BOOTSTRAP.md`/`BOOTSTRAP.ko.md` same treatment, in parity, **and** the §1 scaffolding-overview skill list names all 8 skills (`create`, `stop`, `resume`, `status`, `monitor`, `delegate-job`, `loop`, `orc-onboard`) — not just 6.
- [ ] `deploy/INSTALL.md:3` names `opencode` explicitly.
- [ ] `multi-agent-mux-resume/SKILL.md:71-75` echo text matches the real `resume_session.sh` error string byte-for-byte, and the flat if-block is replaced with a class-aware case; **and** lines 88-93/103 have the `opencode` case arms added (`opencode) CMD_FULL="opencode --session $UUID --auto --agent build" ;;` and `agy|hermes|grok|opencode)` respectively) — text verified against `adapters/opencode.py`, not guessed.
- [ ] `.agents/MULTI_AGENT_RULES.md:21` and `.agents/MULTI_AGENT_RULES.ko.md:21` updated to the 5-agent roster (`cline` removed, `grok`/`opencode` added) — scope confined to that one line/sentence in each file.
- [ ] `lib.sh:32`, `VERSIONS.md` header/matrix, and all 8 `SKILL.md` `version:` fields are **byte-identical** to pre-job state (no accidental touch).
- [ ] `pytest tests/test_version_consistency.py` and the full suite both 100% pass post-change.
- [ ] No file under `.agents/reports/` was modified.
---
## Rev. 2 — Refinement in response to `creator-agy-01`'s architectural challenge (job `9dcd14f6`)
**What changed and why**: `creator-agy-01` filed a formal challenge against Rev.1 of this plan, identifying that the §1 survey method named `.agents/skills/` but never the `.agents/` top-level directory, causing two repository-charter files (`.agents/MULTI_AGENT_RULES.md`, `.agents/MULTI_AGENT_RULES.ko.md`) to be skipped entirely by the original audit — both still list the removed `cline` agent and omit `grok`/`opencode`. The challenge also flagged two secondary gaps: `BOOTSTRAP.md`/`.ko.md`'s scaffolding-overview skill list only names 6 of the 8 lockstep-tracked skills, and the resume `SKILL.md` fix in §3.7 stopped at lines 71-75 without extending to the two further `case "$AGENT" in ...` blocks (lines 88-93, 103) that also lack an `opencode` arm.
Every claim in the challenge was independently re-verified against the live files before being accepted into this plan (not taken on the challenge author's word):
- Read `.agents/MULTI_AGENT_RULES.md:21` and `.agents/MULTI_AGENT_RULES.ko.md:21` directly — confirmed the `cline`-listed / `grok`+`opencode`-missing roster exactly as the challenge described.
- Confirmed the two onboarding cross-references (`AGENTS.md:70`, `BOOTSTRAP.md:193`) that make this file mandatory-read, establishing the "high impact" claim is not overstated.
- Read `BOOTSTRAP.md`/`.ko.md` lines 15-30 directly — confirmed only 6 of 8 skills are listed, and confirmed both `multi-agent-mux-loop` and `multi-agent-mux-orc-onboard` carry `version: 4.1.3` frontmatter same as the other 6 (i.e. they are not somehow lesser/unshipped skills that would legitimately be excluded).
- Read `.agents/skills/multi-agent-mux-resume/SKILL.md` lines 86-107 directly and cross-checked the challenge's proposed `opencode) CMD_FULL="opencode --session $UUID --auto --agent build" ;;` text against `.agents/skills/lib_py/agents/adapters/opencode.py:188-191`'s actual `resume_spec()` implementation — confirmed byte-for-byte match. This is a case where the challenge's proposed fix text was verified correct and adopted verbatim rather than merely triggering a "go look into it" pointer, since it had already done the adapter-source verification `plan-e359e7af.md` Rev.1 explicitly required ("verify the actual CLI flag name... before writing it — do not guess the flag") — no reason to redo work that was already done correctly and can be independently confirmed.
**Net result**: added new §3.8 (`MULTI_AGENT_RULES.md`/`.ko.md`), extended §3.2 (BOOTSTRAP 8-skill list) and §3.7 (resume `SKILL.md` opencode case arms with verified exact text), corrected §1's survey-method description to name `.agents/` explicitly, and updated §6/§7 to reflect the added scope. No part of Rev.1's original findings (§2 deletions, §3.1/3.3-3.6 content updates, §4/§5 lockstep and out-of-scope guards) were found to be wrong by this challenge — all three challenge items were additive scope-completeness findings, not corrections of an error in what was already there.
@@ -0,0 +1,242 @@
# 📑 Issue #6 Implementation Plan (Phase 1–5 Execution & Gate Specification)
- **Document Version**: Rev.2 (Planner `planner-reviewer-claude-01`, job `f4873d82` — Creator `creator-agy-01` 이의제기 3건 반영; Rev.1은 job `d2d70f57`)
- **Issue**: [Gitea Issue #6 — `[Bug] delegate-job 워커 실패 시 레지스트리 미갱신(Fail-Silent) 및 TUI 턴 마감 레이스 컨디션 해결`](https://git.godopu.com/tmpl/multi-agent-mux/issues/6)
- **Source of Truth**: `.agents/reports/issue_6_consolidated_review_report.md` (Rev. 2) — 4인 리뷰어 합의 사양
- **Baseline Commit**: `f98b958` (`main`, v4.4.0), Herdr `0.8.2`, Python 3.9.6, 전체 스위트 750 passed
- **Status**: 착수 전 (Phase 1 대기)
---
## 1. 개요 및 설계 원칙
본 문서는 Rev.2 합의 사양(§4)을 **파일·함수·라인 단위의 실행 계획**으로 전개하고, 단계별 완료 게이트·롤백·비범위를 규정한다. 모든 라인 번호는 기준 커밋 `f98b958` 기준이며, 착수 시 `grep -n`으로 재확인한다.
### 📌 핵심 원칙 (Rev.2 §4 합의)
1. **기존 CAS 엔진 재사용**: 타임아웃 fail-closed는 `engine.py:50`의 `deadline_timeout` 요청(비-operator, terminal 이후 거부)으로만 수행한다. 신규 `--expect-status` 플래그와 operator `error` 오버라이드는 도입하지 않는다.
2. **사전 핸드셰이크 순서**: TUI 유휴 대기(`wait_for_agent_idle`)는 **구독자(`job_subscriber.py`) 기동 이전**에 완료한다. 구독자 idle 시계(`job_subscriber.py:265-267`, subscribe 시점 기산)를 잠식하지 않는다.
3. **유휴 예산 120초**: `SKS_IDLE_TIMEOUT_MS` 기본 `120000`(실측: codex `completed`→`done` 31s).
4. **브로커 장애 격리 (B-15 계약)**: 구독자 `rc=3`은 워커 실패가 아니다. 잡 데드라인까지 디스크를 재관측한 뒤에만 `deadline_timeout`을 적용한다.
5. **리테인 오염 방지 (O-1)**: loop/discuss 경로에서는 래퍼가 MQTT `error` 이벤트를 발행하지 않는다(레지스트리 전이만). direct 경로는 감사·모니터용으로 발행한다.
6. **롤백 스위치**: 각 행위 변경은 환경변수로 즉시 이전 동작으로 복귀 가능해야 한다 (Issue #5 관례).
7. **미주입 실패는 `error`가 아니다 (Rev.2 Secondary)**: 프롬프트가 한 글자도 전달되지 않은 실패(프리플라이트·유휴 대기 타임아웃)는 `deadline_timeout`이 아니라 **`cancelled`**(detail `session_busy`)로 닫고 래퍼 rc=5를 반환한다. 재스케줄 가능성을 보존하되 레코드는 비종료 상태로 남기지 않는다.
8. **셸→Python 경계에서 herdr 격리 명시 전달 (Rev.2 Primary)**: Python 쪽 `herdr` 호출은 반드시 `--session "$HERDR_SESSION_NAME"`을 명시하고, 셸 쪽 호출은 `mam_herdr`/`_sks_herdr`만 사용한다. 인터프리터는 항상 `"$(_delegate_py_bin)"`이다.
### 📌 실측으로 확정된 사실 (계획의 전제)
| 사실 | 근거 |
|---|---|
| direct 경로 `wait "$sub_pid" \|\| true`는 `:227`, loop 워커/리뷰어 조기 탈출은 `:359`/`:375` | `grep -n` (1차 보고서의 `:213`은 오기) |
| 명시적 주입 실패(`send_keys_safe` rc≠0)는 `set -e`로 exit 1 + EXIT trap(`:523`)이 `error` 발행 → **기본 레지스트리에서는 이미 fail-closed** | 실제 래퍼에 rc=4 주입 실측 |
| 단, trap 명령에 `--registry-dir`가 없어 커스텀 레지스트리에서는 `job record not found`로 `pending` 잔존 | 동일 실측 |
| 래퍼 exit 후 구독자 프로세스가 고아로 잔존 | 동일 실측 (`pgrep job_subscriber.py`) |
| `deadline_timeout`: pending→error 커밋, completed→`conflicting error after terminal completed; refusing` | `engine.transition` 직접 호출 실측 |
| 잡 완료 후 에이전트 상태는 `done`(idle 아님); working 중에도 `interactive_ready: true`, `❯` 렌더링 | `herdr agent list`/페인 캡처 실측 |
| `herdr agent wait`는 이미 목표 상태면 즉시 rc=0, 아니면 timeout 시 rc=1 + stderr JSON | 실측, `lib_py/loop/watcher.py` 모듈 docstring과 일치 |
| `dispatch_token`은 `claim`/`redispatch`에서만 발급(`engine.py:87,297-300`) → direct 잡은 토큰 없음, loop 2회차부터 존재 | 코드 |
| **실제 `herdr` 바이너리는 `HERDR_SESSION`·`HERDR_SOCKET_PATH` 환경변수와 `--session <name>` 플래그만 인식하며, MAM의 `HERDR_SESSION_NAME`은 인식하지 않는다.** `HERDR_SESSION_NAME`은 `lib.sh`의 `herdr()`/`mam_herdr`/`_real_herdr`(`lib.sh:234-243`)가 `--session`으로 번역하는 셸 함수 전용 변수라 **Python `subprocess`에는 상속되지 않는다** (Rev.2 Primary-A) | `env -u … herdr agent get` 5조합 실측: `HERDR_SESSION_NAME`만 → `server_not_running`(기본 소켓), `HERDR_SESSION`/`HERDR_SOCKET_PATH`/`--session` → 정상 |
| `lib.sh`를 source한 셸에서도 Python `subprocess.run(["herdr", …])`는 `/opt/homebrew/bin/herdr`로 해석되어 기본 소켓을 조회한다 | 동일 실측 (f) |
| **loop 모드 워커→리뷰어 전환은 v4.4.0에서 이미 깨져 있다**: `:276-283`의 `update --status pending --iteration $iteration`이 워커 `completed` 후 같은 iteration으로 `redispatch`를 요청 → `redispatch iteration 1 does not advance past 1` rc=4 → `set -e`로 래퍼 종료 (Rev.2 Tertiary) | `registry.py` CLI 실측 (iteration 2면 rc=0) |
| `cancelled` 요청은 비-operator 소스로 pending→cancelled 커밋, completed 이후 거부, 이후 operator `redispatch`(iteration 전진)로 재개 가능 | `engine.transition` 실측 |
---
## 2. 단계별 구현 단위 및 필수 완료 기준 (Roadmap & Gates)
| 단계 | 작업 목표 | 세부 구현 (§3 참조) | 필수 완료 게이트 | 롤백 |
|---|---|---|---|---|
| **Phase 1** | **레지스트리 CAS 표준 연동 및 delegate-job Fail-Closed** | • `registry.py close --request deadline_timeout\|cancelled` 서브커맨드<br>• 래퍼 `finalize_unfinished`/`reap_subscriber` 헬퍼, direct(`:227`)·loop(`:359`,`:375`)·`run_agent` 실패·프리플라이트 실패 5개 종료 경로 일원화<br>• rc=3 디스크 재관측, trap `--registry-dir`, dry-run 순서, 종료 코드 계약(rc 5 `session_busy` 포함)<br>• **loop 역할 전환 `attempt_id` 규약** (§3.1.6) | • `--agent human` 결정적 재현 4종(§5 T1-1~T1-4)이 수정 전 실패·수정 후 통과<br>• T1-10(워커 완료→리뷰어 재디스패치 성공) 수정 전 rc=4·수정 후 rc=0<br>• `test_wrapper_exit_code_mapping_literals_are_frozen`·F-A 3종 무변경 통과<br>• `MAM_DELEGATE_FAIL_CLOSED=0`에서 기존 exit 0 동작 재현 | `MAM_DELEGATE_FAIL_CLOSED=0` (헬퍼 no-op, `\|\| true` 복원) |
| **Phase 2** | **사전 TUI 유휴 핸드셰이크 및 제출 검증 보강** | • `lib_py/loop/watcher.py` CLI 진입점(`"$(_delegate_py_bin)" -m lib_py.loop.watcher wait … --session "$HERDR_SESSION_NAME"`)<br>• `lib.sh: wait_for_agent_idle` (사전 `mam_herdr agent get` → `unknown`/`blocked` 분기 → watcher CLI, `SKS_IDLE_RETRIES` 백오프 재시도, 최종 실패 rc 1 → 래퍼 rc 5 `cancelled`)<br>• 래퍼 `run_agent`를 `preflight_agent`+`inject_agent`로 분리, 순서: preflight → idle wait → subscriber → inject<br>• `send_keys_safe` 폴백 제출 검증에서 pre-submit busy 토큰 배제, `agent prompt --wait --until working` 수락 확인(재제출 금지) | • mock_herdr 상태 시퀀스 테스트 §5 T2-1~T2-11 통과<br>• `test_h16`(Enter 정확히 1회)·`test_b8`·`test_c1_*` 무변경 통과<br>• 래퍼 로그에서 `SUBSCRIBED` 이전에 idle 대기 완료 로그가 출력됨<br>• T2-10: watcher CLI argv에 `--session` 포함, T2-11: `lib.sh`에 bare `python`/`python3 -m lib_py.loop` 호출 0건(정적 린트) | `SKS_IDLE_HANDSHAKE=0` (게이트 스킵, 기존 `_pane_quiescent`만 사용), `SKS_PROMPT_WAIT=0` |
| **Phase 3** | **오케스트레이터 러너 Fail-Fast 연결** | • `runner.delegate_job`: rc≠0에서도 `registered job:` 파싱, `created_jobs`·checkpoint 기록, id 반환<br>• **rc=5(`session_busy`)는 `MAM_SESSION_BUSY_RETRY_S`(기본 30) 대기 후 1회 재위임(새 job id)**, 재실패 시 None<br>• 호출부는 `wait_for_job`이 디스크 `error`/`cancelled`로 1s 내 False<br>• `run_loop.sh` 레거시 `delegate_job_safe` 동일 파싱(`MAM_LOOP_PY=0` 경로 보존) | • `LoopRunner.wait_for_job`이 fail-closed 잡에서 ≤ 2s 반환(T3-1)<br>• 실패 job id가 `.mam/loop-checkpoint.json`에 기록(T3-2)<br>• rc=5 1회 재위임 후 성공/실패 분기(T3-3)<br>• `test_issue5_phase3_loop.py` 무변경 통과 | 함수 단위 revert (플래그 불필요: rc≠0 경로만 변경) |
| **Phase 4** | **단위/계약 회귀 스위트** | • `tests/test_issue6_fail_closed.py`, `tests/test_issue6_turn_handshake.py`<br>• `tests/conftest.py` mock_herdr에 `agent_status`·`agent wait`·`agent prompt --wait` 모킹<br>• 문서: SKILL.md 종료 코드 계약, MESSAGING.md §5.1 보강 | • 신규 테스트 전부 **수정 전 코드에서 실패함을 역검증**(Issue #5 관례)<br>• 전체 스위트 750 + 신규 ≥ 20, 0-Fail<br>• `git diff --check` 클린 | 테스트 파일 삭제만으로 원복 |
| **Phase 5** | **실기동 4개 에이전트 E2E 및 릴리스** | • Claude/Grok/Codex/OpenCode 각 1회: `completed` 직후 동일 세션 연속 위임 타임라인 기록<br>• 타임아웃 주입(에이전트 무응답)으로 65분 대신 ≤ `IDLE_TIMEOUT`+5s 내 `error` 확인<br>• 잔존 레코드 3건 폐쇄, IMPROVEMENTS.md 원장, VERSIONS.md `v4.4.1` 4-way 락스텝 | • 4개 백엔드 연속 위임 주입 실패 0건, 중복 제출 0건<br>• `test_version_consistency.py` 통과<br>• 리뷰어 교차 검토 `[VERDICT: PASS]` | 릴리스 태그 미부여 상태로 `main` revert |
---
## 3. 상세 구현 사양
### 3.1 Phase 1 — Fail-Closed
**3.1.1 `lib_py/delegation/registry.py` — `close` 서브커맨드 (신규, Rev.2: `timeout`을 일반화)**
```text
registry.py [--registry-dir D] close --job <id> --request {deadline_timeout,cancelled} [--detail <text>] [--expect-dispatch-token <tok>]
```
- 구현: `engine.transition(job_id, request, registry_dir=rd, source="delegate_wrapper", fields={"detail": detail}, expected_dispatch_token=tok_or_None)`. 두 요청 모두 비-operator이며 terminal 이후 거부된다(실측).
- 용도 구분: `deadline_timeout` = 프롬프트가 **전달된 뒤** 종료 이벤트 없이 데드라인 소진(실행 실패). `cancelled` + detail `session_busy` = 프롬프트가 **전달되기 전** 실패(프리플라이트·유휴 대기 타임아웃; Rev.2 Secondary). 후자는 `redispatch`로 재개 가능하다.
- 종료 코드: 커밋 → 0; 거부 사유가 `conflicting … after terminal` 또는 멱등 → **0**(stderr에 사유 1줄; 이미 닫힌 잡은 정상); 레코드 없음 → 1; 토큰 불일치 → 4.
- `status --set`는 건드리지 않는다(`_operator_write` 및 F-C 멱등 계약 보존).
**3.1.2 래퍼 `multi-agent-mux-delegate-job` — 공통 헬퍼 (신규, `run_agent` 위에 정의)**
```bash
# reap_subscriber <pid> — 자기 구독자만 회수. 원래 rc는 호출자가 보존.
reap_subscriber() { kill "$1" 2>/dev/null || true; wait "$1" 2>/dev/null || true; }
# finalize_unfinished <job_id> <job_status> <sub_rc> [<phase>]
# completed -> no-op (rc 0)
# broker_unavailable -> 남은 데드라인(TIMEOUT - 경과) 동안 3s 간격 디스크 재관측;
# completed/error 발견 시 그 상태 채택, 아니면 deadline_timeout
# 그 외(timeout/error/running) -> 즉시 registry.py close --request deadline_timeout
# phase == preflight|idle_wait -> registry.py close --request cancelled --detail session_busy (rc 5)
# (프롬프트 미전달: deadline_timeout 금지 — Rev.2 Secondary)
# direct 경로에서만 publish_event --event error|cancelled 추가 발행 (loop/discuss 금지: O-1)
# MAM_DELEGATE_FAIL_CLOSED=0 이면 전부 no-op (롤백)
```
- `disk_st` 재관측은 기존 `:342-347`의 인라인 파이썬을 함수 `_disk_status`로 추출해 재사용.
- `expected_dispatch_token`은 **구독자 기동 직전** 레코드에서 읽어 지역변수에 보관(`_disp_tok`), 존재할 때만 전달(direct 잡은 없음).
**3.1.3 종료 경로 5개 일원화**
| # | 위치 (f98b958) | 변경 |
|---|---|---|
| E1 | direct `:227` `wait "$sub_pid" \|\| true` | `wait "$sub_pid" \|\| sub_rc=$?` → 기존 `:340-354` 매핑 블록을 함수 `_map_sub_rc`로 추출(리터럴 문자열 보존) → `finalize_unfinished` → `exit_code=$(_rc_for "$job_status")` |
| E2 | loop 워커 `:359-362` | `break` 직전 `finalize_unfinished "$JOB_ID" "$job_status" "$sub_rc" worker` |
| E3 | loop 리뷰어 `:375-378` | 동일 (`reviewer`) |
| E4 | `run_agent` 실패 (`:327` 및 direct `:204`) | `if ! run_agent …; then reap_subscriber "$sub_pid"; finalize_unfinished "$JOB_ID" error 1 inject; exit 1; fi`. trap(`:523`)은 `--registry-dir "$REGISTRY_DIR"` 추가 후 최후 보루로만 유지 |
| E5 | 프리플라이트 실패(`:456-473` herdr/세션 부재, `:511-513` strict-role) 및 유휴 대기 최종 실패 | Phase 2에서 `preflight_agent`로 이동. 실패 시 잡 등록 후라면 `finalize_unfinished … preflight\|idle_wait` → `cancelled`(session_busy) 후 **`exit 5`** |
**3.1.4 종료 코드 계약 (SKILL.md에 문서화)**
| rc | 의미 |
|---|---|
| 0 | `completed` |
| 1 | `error` (에이전트 발행 / 주입·프리플라이트 실패) |
| 2 | 구독자 타임아웃 → `deadline_timeout` 적용됨 |
| 3 | 브로커 장애 + 데드라인 내 디스크 미확인 → `deadline_timeout` 적용됨 |
| 5 | `session_busy`: 프리플라이트/유휴 대기 실패로 프롬프트 미전달 → `cancelled` 적용됨 (재스케줄 가능) |
마지막 stdout 줄(감사 로그 경로)은 모든 경로에서 유지한다(`runner.delegate_job`/`run_loop.sh:373` 파싱 계약).
**3.1.5 dry-run 순서 (구독자 기동 `:166` → dry-run `return 0` `:224`)**: `DRY_RUN=1`이면 구독자를 기동하지 않는다(현재는 기동 후 `return 0`으로 고아 발생).
**3.1.6 loop/discuss 역할 전환의 `attempt_id` 규약 (Rev.2 Tertiary — 기존 결함 수정)**
- 문제: `:276-283`은 워커·리뷰어 phase 모두 같은 `$iteration`으로 `update --status pending`(=`redispatch`)을 요청한다. `engine.py:227-240`은 terminal에서의 `redispatch`에 `iteration` 전진을 요구하므로 워커 `completed` 직후 리뷰어 전환이 rc=4로 거부되고 `set -e`로 래퍼가 죽는다(실측). F-A 테스트(`test_issue5_phase2a_loop.py:727`)는 iteration 2를 넘겨 이 경로를 비켜간다.
- 설계: `iteration`은 루프 회차 라벨로 유지하고, **디스패치 단조 카운터 `attempt_id`**를 도입한다(엔진 `:171`이 이미 `record.get("attempt_id", record.get("iteration"))`으로 읽는 필드).
1. 래퍼: 잡별 `attempt=$((attempt+1))`을 각 phase 디스패치 직전에 증가시키고 `update … --attempt-id "$attempt"`를 함께 넘긴다(워커 r1=1, 리뷰어 r1=2, 워커 r2=3 …).
2. `registry.py update`에 `--attempt-id` 추가(`:296-302`).
3. `engine._decide` redispatch 규칙: `fields`에 `attempt_id`가 있으면 **`attempt_id`가 `record.attempt_id`(없으면 `iteration`)보다 커야** 커밋; 없으면 기존 `iteration` 규칙 유지(F-A 3종 무변경). `attempt_id`는 `redispatch`/`claim` 커밋 시 레코드에 기록.
4. `publish_event.py:250-255`의 `--finalize-report` 기본 `attempt_id`는 `record.attempt_id`를 우선하고 없으면 `iteration`.
- 범위 주의: 이 수정으로 리뷰어 전환의 CAS 거부는 사라지지만, **loop 모드의 리뷰어 phase는 O-1(리테인 재수락, §4)에 의해 여전히 즉시 종료된다.** 따라서 Phase 5 E2E는 direct 모드만 수행하고, loop 모드 종단 검증은 O-1 이슈 완료 후로 명시한다.
### 3.2 Phase 2 — 사전 TUI 핸드셰이크
**3.2.1 `lib_py/loop/watcher.py` CLI 진입점 (신규 `main`)**
```text
"$(_delegate_py_bin)" -m lib_py.loop.watcher wait <target> --session <herdr_session> [--until S]... [--timeout-ms N]
stdout: {"kind": "matched|timeout|agent_not_found|transport_error", "agent_status": "...", "error_code": "..."}
rc: matched 0 / timeout 2 / agent_not_found 3 / transport_error 4
```
- `wait_once`를 그대로 사용(셸 중복 구현 금지). `lib_py.delegation`은 `lib_py.loop`를 임포트하지 않는다(패키지 규칙 유지) — 호출자는 셸(`lib.sh`)이다.
- **격리 전달 (Rev.2 Primary-A)**: `build_argv(target, until, timeout_ms, session=None)`에 `session` 파라미터를 추가하고, 값이 있고 `default`가 아니면 argv를 `["herdr", "--session", session, "agent", "wait", …]`로 구성한다. CLI `--session`은 미지정 시 `HERDR_SESSION_NAME` 환경변수를 읽는다. 실제 `herdr`는 `HERDR_SESSION_NAME`을 인식하지 않으므로(실측) 이 명시 전달이 없으면 기본 소켓(`~/.config/herdr/herdr.sock`)을 조회해 `server_not_running`/`agent_not_found`가 된다. 기존 `wait_once` 호출자(`shadow.py` 등)는 `session=None`으로 동작 불변.
- **인터프리터 (Rev.2 Primary-B)**: bare `python`/`python3` 금지. `lib.sh`는 `"$(_delegate_py_bin)"`(`lib.sh:1841`)만 사용하며 `PYTHONPATH`는 `lib.sh:25,164`가 이미 보장한다. T2-11 정적 린트로 고정.
**3.2.2 `lib.sh: wait_for_agent_idle <sess> [timeout_ms]` (신규, `send_keys_safe` 위)**
1. `SKS_IDLE_HANDSHAKE=0` → return 0 (롤백).
2. `_sks_herdr agent get <target>`(=`mam_herdr`, 격리 인지 셸 함수)로 `agent_status` 조회: `unknown`/조회 실패 → return 3(휴리스틱 폴백 신호, 호출자는 기존 `_pane_quiescent` 경로 진행); `blocked` → return 2(주입 금지; `_pane_dialog_open` 처리로 위임).
3. `idle`/`done` → return 0. `working` → `"$(_delegate_py_bin)" -m lib_py.loop.watcher wait <target> --session "$HERDR_SESSION_NAME" --until idle --until done --until blocked --timeout-ms ${SKS_IDLE_TIMEOUT_MS:-120000}`: matched(idle/done) → 0, matched(blocked) → 2, timeout → 재시도, 그 외 → 3.
4. **재시도 (Rev.2 Secondary)**: timeout은 `SKS_IDLE_RETRIES`(기본 2)회까지 `SKS_IDLE_RETRY_BACKOFF_S`(기본 10)초 간격으로 반복한다(기본 총 예산 ≈ 3×120s + 20s). 최종 실패 → return 1("agent still working"). 호출자(래퍼)는 rc 1을 `finalize_unfinished … idle_wait`(→ `cancelled`/rc 5)로 처리하며 **`deadline_timeout`을 적용하지 않는다**.
- `interactive_ready`는 어떤 판정에도 사용하지 않는다.
**3.2.3 래퍼 실행 순서 재배치 (`cmd_submit`)**
```text
register → brief 작성 → preflight_agent(herdr 존재·세션 존재·역할 검사)
→ wait_for_agent_idle "$sess" (rc 1/2 → finalize_unfinished … idle_wait → cancelled/session_busy; exit 5)
→ _disp_tok 읽기 → 구독자 기동 + SUBSCRIBED 핸드셰이크
→ inject_agent(send_keys_safe) → wait sub → finalize
```
- loop/discuss 반복마다 동일 순서(`:286` 구독자 기동 앞에 idle wait).
**3.2.4 `send_keys_safe` 보강 (`lib.sh:2231-2345`)**
- 제출 검증(`:2330-2332`): `pre_submit`에 `esc to interrupt`/`● |✽ |[A-Za-z]+ing`가 **이미 있었으면** 해당 토큰을 성공 근거에서 제외하고 marker 소멸 + 화면 변화만 인정.
- 네이티브 경로(`:2279`): `SKS_PROMPT_WAIT=1`(기본)이면 `agent prompt <t> <text> --wait --until working --timeout 5000`. 성공 → 0. `agent_prompt_stalled`/timeout → **재제출하지 않고** 2s 후 `agent get` 1회: `working` → 0, 그 외 → rc 4("delivery unknown"). `agent_blocked` → rc 2.
- 폴백 경로 진입 전 busy 토큰 게이트: `wait_for_agent_idle`이 3(unknown)을 반환한 경우에만 `_pane_tail 8`의 busy 토큰을 `SKS_BUSY_TIMEOUT`(기본 120s)까지 대기.
### 3.3 Phase 3 — 러너 Fail-Fast
- `runner.py:279-289`: `res.returncode != 0`이어도 stdout에서 `registered job:` 매치 시 `created_jobs.append` + `_record_checkpoint()` 후 **id 반환**(로그는 error 레벨 유지). 매치 실패 시에만 `None`.
- **rc=5 (`session_busy`, Rev.2 Secondary)**: `delegate_job`이 `MAM_SESSION_BUSY_RETRY_S`(기본 30)초 대기 후 **1회** 재위임(새 job id 등록)한다. 재시도도 rc=5면 마지막 id를 반환하고 호출부는 `wait_for_job`이 `cancelled`로 즉시 False → 기존 abort 경로. 무한 재시도는 두지 않는다(교착의 새 형태).
- `wait_for_job`은 변경하지 않는다(3900s는 최후 안전망; `cancelled`는 이미 False 조건).
- `run_loop.sh:159-168, 373`: `delegate_job_safe` rc≠0에서도 출력에서 job id 추출(레거시 경로 동등성).
### 3.4 Phase 4 — 테스트 및 문서 (§5 참조)
- `tests/conftest.py` mock_herdr: `agent get`/`list`에 `agent_status`(기본 `idle`) 추가; `agent wait`는 상태 파일의 `status_sequence`(예: `["working","working","done"]`)를 호출마다 소비, 소진 시 마지막 값 유지, `--timeout`은 시퀀스 소진 전 종료 시 `{"error":{"code":"timeout"}}` rc 1; `agent prompt --wait`는 `prompt_wait_result` 필드(`ok|agent_prompt_stalled|agent_blocked`)로 제어.
- 문서: `SKILL.md` "Core Commands"에 종료 코드 표(§3.1.4), `MESSAGING.md` §5.1 구독자 타임아웃의 레지스트리 반영 서술, `BOOTSTRAP*.md` 에이전트 프로토콜에 "completed 발행 후 도구 호출 없이 턴 종료" 1문장.
### 3.5 Phase 5 — E2E·정리·릴리스
- E2E 절차(**direct 모드만**; loop 모드 종단은 O-1 완료 후): 각 백엔드에 `--agent human`이 아닌 실세션으로 잡 A 위임 → `completed` 수신 즉시 잡 B 위임 → 래퍼 로그의 idle 대기 시간, `herdr agent get` 타임라인, B의 `started` 지연을 기록(`docs/contracts/issue-6/phase5-e2e.md`).
- 타임아웃 주입: 세션에 `/exit` 없이 프롬프트를 무시하도록 `--idle-timeout 30`으로 위임 → 래퍼 rc=2, 레지스트리 `error`, `wait_for_job` ≤ 2s.
- 잔존 레코드 `93a44347`, `2961b822`, `ee242671`: `registry.py close --job <id> --request deadline_timeout --detail "Issue #6 backfill"`.
- 릴리스: `v4.4.1` (PATCH — 공개 계약 삭제 없음, 종료 코드는 오동작 정정, `timeout` 서브커맨드는 래퍼 내부 배관). 4-way 락스텝: `lib.sh:32`, `eager.py:16`, `VERSIONS.md`(개요+매트릭스+Changelog), 8개 `SKILL.md` frontmatter. `IMPROVEMENTS.md` §5에 `Issue-6-FailClosed-TurnHandshake` 블록 추가(§6 표·헤더 키 목록 동기화).
---
## 4. 명시적 비범위 (Out of Scope) — 별도 이슈
1. **O-1 리테인 터미널 재수락**: 재디스패치 후 2회차 구독자가 1회차 retained `completed`를 즉시 수락(실측). loop 모드 기존 결함. 본 이슈에서는 "loop 경로 retained 발행 금지"로 회피만 한다. **Rev.2 주의: §3.1.6의 attempt_id 수정 후에도 loop 모드 리뷰어 phase는 O-1 때문에 종단 동작하지 않는다. 별도 이슈를 Issue #6 릴리스 노트에 "loop/discuss 모드 사용 전 필수"로 명시한다.**
2. **레지스트리 오염**: `.mam/jobs`에 pytest 세션명 레코드 467건 누출 원인.
3. **세션별 전달 직렬화 락**, **direct 잡 `dispatch_token` 발급**: 현 구조(동기 위임 + loop lock)에서 불필요.
4. **`wait_for_job` 3900s 단축**: 증상 완화이므로 변경하지 않는다.
---
## 5. 회귀 테스트 행렬 (Phase 4 산출물)
### 5.1 `tests/test_issue6_fail_closed.py` (브로커 무관, `--agent human` + 짧은 타임아웃)
| ID | 시나리오 | 기대 |
|---|---|---|
| T1-1 | direct, 이벤트 없음 (`--timeout 6 --idle-timeout 2`) | rc=2, 레지스트리 `error`, events.log에 wrapper `error` 1건, 구독자 pid 소멸 |
| T1-2 | loop, 워커 phase 이벤트 없음 | rc=2, `error`, **retained 발행 없음** |
| T1-3 | 구독자 타임아웃 직후 `publish_event completed` 경쟁 | 최종 `completed` 유지, `timeout` 서브커맨드 rc 0(거부 로그) |
| T1-4 | `MQTT_HOST` 불가 + 디스크 비종료 (`--timeout 8`) | rc=3, 데드라인까지 재관측 로그, 최종 `error` |
| T1-5 | rc=3 + 재관측 중 디스크 `completed` 출현 | rc=0, `completed` |
| T1-6 | `close --request deadline_timeout`을 `completed` 레코드에 적용 | rc=0, 상태 불변 |
| T1-10 | loop: 워커 `completed` 후 리뷰어 `update --status pending --iteration 1 --attempt-id 2` | rc=0, `pending`, `attempt_id=2` (수정 전 rc=4 → 역검증) |
| T1-11 | 같은 `--attempt-id 2` 재요청(리플레이) | rc=4 거부 |
| T1-12 | `--attempt-id` 없이 iteration 2 (F-A 경로) | rc=0 (기존 규칙 보존), F-A 3종 무변경 통과 |
| T1-13 | `close --request cancelled --detail session_busy`: pending→cancelled rc=0, completed→ rc=0·상태 불변, 이후 `redispatch` iteration 2 → pending | 전이 규칙 고정 |
| T1-7 | 커스텀 `--registry-dir` + `send_keys_safe` 실패(BASH_ENV 오버라이드) | rc=1, 해당 레지스트리 `error` |
| T1-8 | `MAM_DELEGATE_FAIL_CLOSED=0` | T1-1 조건에서 rc=0, `pending` (구 동작 재현) |
| T1-9 | dry-run direct | 구독자 프로세스 미기동 |
| 고정 | `test_wrapper_exit_code_mapping_literals_are_frozen` | 통과 |
### 5.2 `tests/test_issue6_turn_handshake.py` (mock_herdr 상태 시퀀스)
| ID | 시나리오 | 기대 |
|---|---|---|
| T2-1 | `status_sequence=["working","done"]` | `agent wait` 호출 후 `agent prompt` 호출(순서 단정), Enter/C-m 0회(네이티브) |
| T2-2 | `working` 고정, `SKS_IDLE_TIMEOUT_MS=1000` | rc=1, `agent prompt` 미호출, 래퍼 rc=1·`error` |
| T2-3 | `unknown` | `agent wait` 미호출, `_pane_quiescent` 폴백 경로 진입 |
| T2-4 | `blocked` | rc=2, 주입 없음 |
| T2-5 | `done` 즉시 | 대기 0회, 즉시 주입 |
| T2-6 | 폴백 경로, pre_submit에 `esc to interrupt` 존재 + 페이스트 드롭 | rc=4 (기존 코드에서는 0 → 역검증) |
| T2-7 | `prompt_wait_result=agent_prompt_stalled` + 이후 `working` | rc=0, prompt 호출 **1회** |
| T2-8 | 래퍼 순서: idle 대기 로그가 `subscriber pid:` 로그보다 앞 | 로그 순서 단정 |
| T2-9 | `working` 고정 + `SKS_IDLE_RETRIES=1`, `SKS_IDLE_TIMEOUT_MS=500` | `agent wait` 2회 호출, 래퍼 rc=5, 레지스트리 `cancelled`(detail `session_busy`), `deadline_timeout` 미호출, 구독자 미기동 |
| T2-10 | `HERDR_SESSION_NAME=iso-x`에서 `wait_for_agent_idle` | mock 호출 기록에 `herdr --session iso-x agent wait …` (argv 순서 단정); `build_argv(session="default")`는 `--session` 생략 |
| T2-11 | 정적 린트: `lib.sh`·래퍼에서 `^\s*python3? -m lib_py\.loop` 또는 bare `python -m` 패턴 0건, watcher 호출은 `_delegate_py_bin` 경유 | grep 단정 |
| 호환 | `test_h16`, `test_b8`, `test_c1_*`, `test_herdr_shim_contract` | 무변경 통과 |
### 5.3 Phase 3 (`tests/test_issue6_fail_closed.py` 내)
| ID | 시나리오 | 기대 |
|---|---|---|
| T3-1 | `LoopRunner.delegate_job` rc≠0 + `registered job:` 출력 | id 반환, `wait_for_job` ≤ 2s False |
| T3-2 | 동일 | `.mam/loop-checkpoint.json`에 id 기록 |
| T3-3 | 래퍼 stub이 1회차 rc=5, 2회차 rc=0 (`MAM_SESSION_BUSY_RETRY_S=0`) | 재위임 1회 후 2회차 id 반환; 두 번 다 rc=5면 마지막 id 반환 + `wait_for_job` False |
---
## 6. 공수 및 순서
| 단계 | 공수 | 선행 |
|---|---|---|
| Phase 1 | 1.25 MD (+0.25 attempt_id) | — |
| Phase 2 | 1.25–1.75 MD (+0.25 세션 전달·재시도) | Phase 1 (finalize 헬퍼 재사용) |
| Phase 3 | 0.25 MD | Phase 1 |
| Phase 4 | 0.75 MD (Phase 1~3와 병행 작성, 역검증 포함) | — |
| Phase 5 | 0.5–1.0 MD | 전부 |
| **합계** | **4.0–5.0 MD** (통합 보고서 Rev.2 §3 상한 대비 +0.5 MD; 사유 §7) | |
---
## 7. Creator 이의제기 판정 (Rev.1 → Rev.2)
| 이의 | 판정 | 실측 근거 | Rev.2 반영 |
|---|---|---|---|
| **Primary-A** watcher.py가 `HERDR_SESSION_NAME` 격리를 잃는다 | **수용** (세부 정정: 실제 herdr 플래그는 `-L`이 아니라 `--session`; `-L`은 `.mam/shim` 번역 전용. 격리 변수는 셸 함수 `mam_herdr`/`_real_herdr`가 번역하며 Python 서브프로세스에는 상속되지 않음) | `HERDR_SESSION_NAME`만 있는 환경에서 bare `herdr` → `server_not_running`; `--session`/`HERDR_SESSION`/`HERDR_SOCKET_PATH` → 정상. `lib.sh` source 후 Python `subprocess`도 동일 실패 | §1 원칙 8, §3.2.1 `--session` 전달, §3.2.2 `_sks_herdr` 사용, T2-10 |
| **Primary-B** bare `python -m` 호출은 `ModuleNotFoundError` | **수용** (Rev.1 표기 오류) | `lib.sh:1841 _delegate_py_bin`, `PYTHONPATH` export `lib.sh:25,164` | §3.2.1/3.2.2 `"$(_delegate_py_bin)"`, T2-11 정적 린트 |
| **Secondary** 주입 전 유휴 대기 실패를 `deadline_timeout`(terminal `error`)로 닫으면 미주입 잡이 실행 실패로 낙인 + 러너 즉시 abort | **수용** (대안 채택: 래퍼 내 bounded 재시도 → `cancelled`/`session_busy` rc 5 → 러너 1회 재위임). "재시도 기회 영구 박탈" 부분은 부분 정정: `cancelled`도 operator `redispatch`로 재개 가능(실측) | `engine.transition`: pending→cancelled 커밋, completed→cancelled 거부, cancelled→redispatch 성공 | §1 원칙 7, §3.1.1 `close`, §3.1.2/3.1.4 rc 5, §3.2.2 재시도, §3.3 러너 재위임, T1-13/T2-9/T3-3 |
| **Tertiary** 워커→리뷰어 전환 시 같은 iteration의 `redispatch` 거부 | **수용** (인용 코드는 실제 `engine.py:227-240`과 다르나 결론은 정확). v4.4.0에서 **이미 깨져 있는 기존 결함**임을 확인 | `registry.py update --status pending --iteration 1`(워커 completed 후) → rc=4 `does not advance past 1`; iteration 2 → rc=0 | §3.1.6 `attempt_id` 규약, T1-10~T1-12 |
| (부수) Rev.2 통합 보고서 §3의 `lib.sh` 경로 | Rev.1과 동일하게 실제 경로 `.agents/skills/lib.sh` 사용 | — | — |
공수 +0.5 MD의 사유: `attempt_id` 규약(엔진 규칙·CLI·publish_event 기본값·테스트 3종)과 세션 전달·재시도 로직·러너 재위임(테스트 3종)이 Rev.1에 없던 신규 작업이다.
@@ -0,0 +1,508 @@
# 📐 구현 계획서: Herdr 셈(shim) 패인 라우팅 결함 4종 수정 (ISSUE-1/2/3/5)
- **Job ID**: `fae58b93`
- **Role**: Planner (`planner-reviewer-claude-01`)
- **작성일**: 2026-08-27
- **대상**: `.agents/skills/lib.sh`, `tests/conftest.py`, `tests/test_herdr_shim_contract.py`, `tests/test_b19_headless_reconcile_fixes.py`
- **근거 문서**: `bug_report.md` (v1.0)
- **기준 커밋**: `4bbd03b` (main)
---
## 0. 요약 (TL;DR)
`bug_report.md`의 5대 결함 중 ISSUE-4는 이미 커밋 `4bbd03b`에서 해결되어 회귀 테스트(`test_agent_start_success_tokens_exclude_startup_timeout`)로 고정되어 있다. 남은 **ISSUE-1 / 2 / 3 / 5**를 다음 순서로 처리한다.
1. **ISSUE-5 선행** — 셈 내부에 공용 헬퍼 `_resolve_herdr_pane_id`를 신설한다. 나머지 3개 이슈의 수정이 전부 이 헬퍼 안으로 수렴하므로 이것이 반드시 먼저다.
2. **ISSUE-2** — 헬퍼 및 `_resolve_herdr_target` / `has-session`에서 `agent in tn` 부분 매칭을 전면 제거하고 엄격 일치로 대체.
3. **ISSUE-3** — `HERDR_WORKSPACE_ID`가 **명시적으로 설정된 경우에만** `pane list --workspace`로 하드 스코핑.
4. **ISSUE-1** — `paste-buffer`를 `pane send-text` 단독 삽입으로 교체(엔터 금지), 해결 실패 시 조용히 삼키지 말고 실패를 상위로 전달.
---
## 1. 사전 조사에서 확인된 사실 (계획의 전제)
계획 수립 중 실제 `herdr` 바이너리(`/opt/homebrew/bin/herdr`)와 현재 `lib.sh`를 직접 검증했다. **버그 리포트의 권고 코드를 그대로 옮기면 안 되는 지점이 3곳** 있다.
### 1.1 ✅ `herdr agent send` 서브커맨드는 존재하지 않는다 (ISSUE-1의 진짜 뿌리)
```
$ herdr agent --help
Commands: list get read send-keys prompt rename focus wait attach start explain
```
현재 `lib.sh:822`의 `paste-buffer` 구현은 다음 한 줄이 전부다.
```bash
_real_herdr agent send "$sess" "$(cat "$buffer_dir/$buf")" >/dev/null 2>&1 || true
```
`agent send`는 CLI에 없으므로 이 호출은 **항상 실패하고 `|| true`가 실패를 삼킨다**. 즉 현재 `main`에서 `paste-buffer` 경로는 텍스트를 단 한 글자도 주입하지 못하는 완전한 데드 코드다. 이것이 브리프의 "`paste-buffer`의 `herdr agent send` 부재"가 가리키는 실체이며, `send_keys_safe`의 폴백 경로 전체가 무력화되어 있음을 뜻한다.
> 참고: `send_keys_safe`는 `agent prompt` 고속 경로가 성공하면 즉시 반환하므로(`lib.sh:1785`), **등록된 agent에 대해서는** 이 결함이 드러나지 않는다. 결함이 표면화되는 조건은 정확히 버그 리포트가 기술한 상황 — `agent prompt`가 실패하는 **라벨 전용 패인(agent 미등록)** — 이다.
### 1.2 ⚠️ 버그 리포트의 `pane_id` 정규식은 실제 pane_id를 거부한다
버그 리포트 §3.1은 다음 검증을 제안한다.
```bash
if [[ "$pid" =~ ^w[0-9]+:p[0-9]+$ ]]; then
```
그러나 실제 서버가 반환하는 pane_id는 다음과 같다.
```json
{"pane_id":"w1E:p1","workspace_id":"w1E","tab_id":"w1E:t1", ...}
```
워크스페이스 세그먼트는 `w1E`처럼 **영문자를 포함**한다. 권고 정규식을 그대로 쓰면 모든 실제 pane_id가 거부되어 헬퍼가 항상 실패하고, 결과적으로 ISSUE-1을 고친 뒤에도 주입이 되지 않는다.
→ **채택 정규식**: `^w[A-Za-z0-9]+:p[A-Za-z0-9]+$`
### 1.3 ⚠️ 실제 `pane list` 응답에는 `label` 키가 없을 수 있다
```json
{"agent":"claude","agent_status":"working","cwd":"...","pane_id":"w1E:p1",
"tab_id":"w1E:t1","terminal_title":"...","workspace_id":"w1E"}
```
`label`은 `herdr pane rename <PANE_ID> <LABEL>`로 설정했을 때만 나타난다. 반면 `agent list`에는 `name` 필드가 있다(`"name":"planner-reviewer-claude-01"`). 따라서 헬퍼의 매칭 우선순위는 `label` → `name` → `agent` 순으로 두되, **셋 다 완전 일치만** 허용한다. `agent` 필드는 사실상 CLI 종류(`claude`/`grok`)이므로 `tn`이 그 값과 완전히 같은 경우에만 매칭되며, 이는 부분 매칭과 달리 오라우팅을 만들지 않는다.
### 1.4 ✅ `pane list`는 서버측 `--workspace` 필터를 지원한다
```
$ herdr pane list --help
Options:
--workspace <WORKSPACE_ID>
```
ISSUE-3의 스코핑은 파이썬 클라이언트 필터링만이 아니라 **서버측 플래그로 1차 차단**할 수 있다. 양쪽 모두 적용한다(플래그 미지원 구버전 herdr 대비 이중 방어).
### 1.5 ✅ `pane read`와 `agent read`의 출력 형식은 호환된다
둘 다 평문 텍스트를 반환하며, `_pane_capture`(`lib.sh:1672`)는 JSON 파싱 실패 시 원문을 그대로 반환하므로 `capture-pane`을 `pane read`로 전환해도 상위 로직이 깨지지 않는다.
### 1.6 ⚠️ 셈은 `set -euo pipefail` 아래에서 실행된다
셈 본문은 `lib.sh:141`의 `cat <<'EOF'` ~ `lib.sh:959`의 `EOF` 사이 히어독으로 생성되며 3번째 줄이 `set -euo pipefail`이다. 따라서 실패를 반환할 수 있는 새 헬퍼는 **모든 호출부에서 `|| true`로 감싸야** 하며, 그렇지 않으면 셈이 조기 종료된다.
### 1.7 ✅ 테스트 목(mock)이 결함을 은폐하고 있다
`tests/conftest.py:638`의 목 herdr는 존재하지 않는 `agent send`를 **성공으로 처리**한다. 이 때문에 ISSUE-1이 테스트에서 전혀 드러나지 않았다. 목을 실제 CLI 계약에 맞추는 것이 이번 작업의 필수 선행 조건이다.
---
## 2. 변경 대상 목록
| # | 파일 | 위치 | 이슈 | 성격 |
|---|---|---|---|---|
| C1 | `.agents/skills/lib.sh` | 셈 히어독, `_sanitize_herdr_agent_name` 직후 (~L236) | 5 | 신규 헬퍼 `_resolve_herdr_workspace_scope`, `_resolve_herdr_pane_id` |
| C2 | `.agents/skills/lib.sh` | `_resolve_herdr_target` (L249–286) | 2,3 | 부분 매칭 제거 + ws 필터 |
| C3 | `.agents/skills/lib.sh` | `has-session` (L305–345) | 2,3,5 | 부분 매칭 제거 + ws 필터 + 헬퍼 폴백 |
| C4 | `.agents/skills/lib.sh` | `new-session` (L434–530) | 3 | 해결된 workspace_id를 `HERDR_WORKSPACE_ID`로 export |
| C5 | `.agents/skills/lib.sh` | `kill-session` (L567–603) | 5 | 인라인 파서 → 헬퍼 |
| C6 | `.agents/skills/lib.sh` | `capture-pane` (L687–704) | 3,5 | 헬퍼 + `pane read` 경로 |
| C7 | `.agents/skills/lib.sh` | `send-keys` (L705–744) | 2,3,5 | 인라인 파서 → 헬퍼 |
| C8 | `.agents/skills/lib.sh` | `paste-buffer` (L794–827) | 1,5 | `agent send` → `pane send-text`, 엔터 금지, 실패 전파 |
| C9 | `.agents/skills/lib.sh` | `send_keys_safe` (L1804–1806) | 1 | `paste-buffer` 종료 코드 확인 → rc 3 |
| C10 | `tests/conftest.py` | 목 herdr | 1,2,3 | `pane send-text`/`pane read`/`pane rename` 추가, `pane list` 병합·라벨·`--workspace`, `agent send` 제거 |
| T1 | `tests/test_herdr_shim_contract.py` | 신규 | 1,2,3,5 | H-15 ~ H-20 |
| T2 | `tests/test_b19_headless_reconcile_fixes.py` | 신규 | 1,2,5 | D-4 ~ D-7 |
> `list-panes`(L605–686)의 인라인 파서는 `pane_id` 외에 `cwd`/`agent`까지 한 번에 파싱하므로 헬퍼로 대체하지 **않는다**. ISSUE-5의 대상 목록에도 포함되어 있지 않다.
---
## 3. 상세 구현 설계
### 3.1 [C1] 공용 헬퍼 신설 (ISSUE-5)
`lib.sh` 셈 히어독 내부, `_sanitize_herdr_agent_name` 정의 직후(`cmd="${1:-}"` 앞)에 삽입한다. 이 위치여야 `case` 분기 전체에서 참조 가능하다.
```bash
# ---------------------------------------------------------------------------
# Workspace scoping (ISSUE-3).
#
# 스코핑은 HERDR_WORKSPACE_ID 가 "명시적으로" 설정된 경우에만 하드 필터로
# 동작한다. cwd 로부터 자동 추론하지 않는다 — 자동 추론은 다중 워크스페이스
# 오케스트레이션에서 정당한 교차 워크스페이스 조회를 조용히 막아버린다.
# 미설정 시에는 서버 전역 조회(기존 동작)를 유지한다.
# ---------------------------------------------------------------------------
_herdr_ws_scope() { printf '%s\n' "${HERDR_WORKSPACE_ID:-}"; }
# _resolve_herdr_pane_id <target> [workspace_id]
#
# 세션 이름 / 라벨을 실제 pane_id ("wN:pM") 로 해석한다.
# 엄격한 해석 순서 (부분 문자열 매칭은 어느 단계에서도 사용하지 않는다):
# 1. herdr agent get <sanitized_name>
# 2. herdr agent get <raw_name>
# 3. herdr pane list [--workspace WS] 에서
# 3-a. label 완전 일치
# 3-b. name 완전 일치
# 3-c. agent 완전 일치
# 성공 시 pane_id 를 stdout 에 출력하고 0, 실패 시 아무것도 출력하지 않고 1.
# 호출부는 반드시 `|| true` 로 감쌀 것 (셈은 set -e 하에서 동작한다).
_resolve_herdr_pane_id() {
local target="$1"
local target_ws="${2:-$(_herdr_ws_scope)}"
local sat pid=""
sat=$(_sanitize_herdr_agent_name "$target")
local cand
for cand in "$sat" "$target"; do
[ -n "$cand" ] || continue
pid=$(_real_herdr agent get "$cand" 2>/dev/null | TARGET_WS="$target_ws" python3 -c "
import sys, json, os
tws = os.environ.get('TARGET_WS', '')
try:
a = json.load(sys.stdin).get('result', {}).get('agent', {})
# ISSUE-3: 워크스페이스가 지정되면 다른 워크스페이스의 동명 agent 는 거부.
if tws and a.get('workspace_id') and a.get('workspace_id') != tws:
pass
else:
print(a.get('pane_id') or '')
except Exception:
pass
" 2>/dev/null || echo "")
[ -n "$pid" ] && break
done
if [ -z "$pid" ]; then
local ws_flag=()
[ -n "$target_ws" ] && ws_flag=(--workspace "$target_ws")
pid=$(_real_herdr pane list "${ws_flag[@]+"${ws_flag[@]}"}" 2>/dev/null \
| TARGET_NAME="$target" TARGET_SAN="$sat" TARGET_WS="$target_ws" python3 -c "
import sys, json, os
tn = os.environ.get('TARGET_NAME', '')
tsa = os.environ.get('TARGET_SAN', '')
tws = os.environ.get('TARGET_WS', '')
try:
panes = json.load(sys.stdin).get('result', {}).get('panes', [])
# 서버가 --workspace 를 무시하는 구버전일 수 있으므로 클라이언트에서 한 번 더 거른다.
if tws:
panes = [p for p in panes if p.get('workspace_id') == tws]
# ISSUE-2: 완전 일치만 허용. 'agent in tn' 부분 매칭은 사용하지 않는다.
for key in ('label', 'name', 'agent'):
for p in panes:
v = p.get(key)
if v and (v == tn or v == tsa):
pid = p.get('pane_id') or ''
if pid:
print(pid)
sys.exit(0)
except Exception:
pass
sys.exit(1)
" 2>/dev/null || echo "")
fi
# 실제 pane_id 는 'w1E:p1' 처럼 워크스페이스 세그먼트에 영문자를 포함한다.
# ^w[0-9]+:p[0-9]+$ 로 좁히면 모든 실제 pane_id 가 거부된다.
if [[ "$pid" =~ ^w[A-Za-z0-9]+:p[A-Za-z0-9]+$ ]]; then
printf '%s\n' "$pid"
return 0
fi
return 1
}
```
**설계 근거**
- **`for key in ('label','name','agent')` 바깥 루프**: 우선순위가 "패인 목록의 등장 순서"가 아니라 "필드의 신뢰도"로 결정된다. 안쪽/바깥쪽 루프를 뒤집으면 목록 첫 항목의 `agent` 매칭이 뒤쪽 항목의 정확한 `label` 매칭을 이겨버린다 — 이것이 ISSUE-2가 만든 오라우팅과 동일한 형태의 버그다.
- **`tsa`(sanitized) 도 비교 대상에 포함**: `agent start`가 이름을 sanitize해서 등록하므로, 라벨은 원본이고 등록명은 sanitize본인 혼재 상황을 커버한다. sanitize는 결정적 함수이므로 부분 매칭과 달리 충돌을 만들지 않는다.
- **`ws_flag` 배열 + `${ws_flag[@]+...}`**: `set -u` 하에서 빈 배열 전개가 unbound 오류를 내지 않도록 하는 표준 관용구.
### 3.2 [C2] `_resolve_herdr_target` 엄격화 (ISSUE-2, ISSUE-3)
`lib.sh:262–275`의 파이썬 블록에서 다음 술어를 제거한다.
```python
if name == tn or (not name and agent and agent in tn): # ← 제거
```
교체:
```python
tn = os.environ.get("TARGET_NAME", "")
tsa = os.environ.get("TARGET_SAN", "")
tws = os.environ.get("TARGET_WS", "")
...
agents = d.get("result", {}).get("agents", [])
if tws:
agents = [a for a in agents if a.get("workspace_id") == tws]
for a in agents:
name = a.get("name", "")
if name and (name == tn or name == tsa):
print(a.get("pane_id") or name)
sys.exit(0)
sys.exit(1)
```
`pane_id or agent` → `pane_id or name`으로 바꾼다. 기존 코드는 매칭에 실패한 항목의 CLI 종류(`agent`, 예: `"claude"`)를 타깃으로 반환할 수 있었는데, 이는 `agent prompt claude ...`처럼 전혀 다른 대상에게 프롬프트를 던지는 경로다.
### 3.3 [C3] `has-session` 엄격화 + 패인 폴백 (ISSUE-2, ISSUE-3, ISSUE-5)
`lib.sh:334`의 다음 술어를 제거한다.
```python
or (not an and a.get("agent") and a.get("agent") in tn) # ← 제거
```
남는 조건은 `an == tn or an == stn`이며, 여기에 `HERDR_WORKSPACE_ID` 필터를 추가한다.
그리고 agent 조회가 모두 실패했을 때 마지막 단계로 헬퍼를 호출한다.
```bash
if [ -n "$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)" ]; then
exit 0
fi
exit 1
```
**의도적 동작 변경**: 라벨만 붙은(agent 미등록) 패인도 이제 "세션 존재"로 판정된다. 이것이 정확히 버그 리포트가 보고한 실패 시나리오(`label: reviewer-cline-01` 패인에 주입 불가)의 해소 조건이다. `_resolve_herdr_pane_id`가 완전 일치만 허용하므로, 세션 이름 `reviewer-creator-grok-01`이 `agent == "grok"` 패인에 매칭될 일은 없다.
**리스크**: `create_session.sh` / `reconcile.sh`가 `has-session` 결과로 재생성 여부를 판단한다면, 라벨만 있고 실제 CLI가 죽은 패인을 "살아 있음"으로 오판할 수 있다. → 3.9의 회귀 검증 범위에 `test_orc_onboard.py`, `test_tier3_integration.py`, `test_tier4_e2e.py`를 명시적으로 포함한다.
### 3.4 [C4] `HERDR_WORKSPACE_ID` 전파 (ISSUE-3)
`new-session` 분기에서 `existing_ws` 또는 신규 `ws_id`가 확정된 직후(`lib.sh:509` 이후 `ws_id` 확정 지점) 다음을 추가한다.
```bash
if [ -n "${ws_id:-}" ]; then
export HERDR_WORKSPACE_ID="$ws_id"
fi
```
또한 `agent start`에 전달하는 `env_flags`에 `--env HERDR_WORKSPACE_ID=$ws_id`를 추가하여, 기동된 에이전트 프로세스가 상속한 셈 호출부터 자동으로 스코프가 걸리도록 한다.
**채택하지 않은 대안**: 셈이 `$PWD`/`$WORKSPACE_ROOT`의 cwd로부터 workspace_id를 자동 추론하는 방식. 추론이 성공하는 순간 교차 워크스페이스 조회가 **조용히** 막히고, 오케스트레이터가 다른 워크스페이스의 에이전트를 정당하게 다루는 경로가 원인 불명으로 깨진다. 스코핑은 명시적 옵트인이어야 진단 가능하다.
### 3.5 [C5]~[C7] 분기 리팩터링 (ISSUE-5)
**`kill-session`** — `lib.sh:587–598`의 이중 인라인 파이썬을 삭제.
```bash
agent_target=$(_sanitize_herdr_agent_name "$sess")
pane_id=$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)
if [ -n "$pane_id" ]; then
_real_herdr pane close "$pane_id" >/dev/null 2>&1 || true
fi
_real_herdr kill-session -t "$agent_target" >/dev/null 2>&1 \
|| _real_herdr kill-session -t "$sess" >/dev/null 2>&1 || true
```
**`capture-pane`** — 헬퍼로 pane_id를 얻으면 `pane read`, 아니면 기존 `agent read` 체인 유지.
```bash
agent_target=$(_sanitize_herdr_agent_name "$sess")
pane_id=$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)
if [ -n "$pane_id" ]; then
_real_herdr pane read "$pane_id" --source visible --lines 100 2>/dev/null || true
else
_real_herdr agent read "$agent_target" --source visible --lines 100 2>/dev/null \
|| _real_herdr agent read "$sess" --source visible --lines 100 2>/dev/null || true
fi
```
**`send-keys`** — `lib.sh:726–738`의 이중 인라인 파이썬을 삭제하고 헬퍼 호출로 대체. 폴백(`pane send-keys "$agent_target"` → `"$sess"`)은 그대로 유지한다. `C-m` → `Enter` 정규화(L741–743)도 유지 — 이건 키 이름 번역이지 제출 정책이 아니다.
**ISSUE-5의 "데드 파이프라인" 부분**: 기존 인라인 파서는 `except: pass`로 항상 exit 0을 반환해 `||` 2차 폴백이 절대 실행되지 않았다. 신규 헬퍼는 `sys.exit(1)` + 정규식 검증 + `return 1`로 실패를 정확히 신호하므로 이 데드 코드가 구조적으로 제거된다.
### 3.6 [C8] `paste-buffer` 재작성 (ISSUE-1)
```bash
buffer_dir="${WORKSPACE_ROOT:+$WORKSPACE_ROOT/.mam/buffers}"
buffer_dir="${buffer_dir:-${TMPDIR:-/tmp}/mam_buffers}"
if [ ! -f "$buffer_dir/$buf" ]; then
echo "Error: buffer $buf not found ($buffer_dir/$buf)" >&2
exit 1
fi
pane_id=$(_resolve_herdr_pane_id "$sess" 2>/dev/null || true)
if [ -z "$pane_id" ]; then
# herdr 에는 `agent send` 서브커맨드가 없다. 여기서 조용히 성공을 반환하면
# send_keys_safe 가 아무것도 붙여넣지 않은 채 Enter 만 치게 된다.
echo "Error: paste-buffer could not resolve a pane for '$sess'" >&2
exit 1
fi
# 삽입 전용. Enter/C-m 제출은 전적으로 send_keys_safe 가 통제한다 (ISSUE-1).
# 여기서 `pane run` 을 쓰면 안 된다 — 텍스트와 Enter 를 한 번에 보내 이중 제출이 된다.
if ! _real_herdr pane send-text "$pane_id" "$(cat "$buffer_dir/$buf")" >/dev/null 2>&1; then
echo "Error: pane send-text failed for '$sess' ($pane_id)" >&2
exit 1
fi
```
**불변식 (테스트로 고정)**: `paste-buffer` 분기 본문에는 `Enter`, `C-m`, `pane run`, `agent prompt` 중 어떤 것도 등장하지 않는다.
### 3.7 [C9] `send_keys_safe`의 붙여넣기 실패 전파 (ISSUE-1)
현재 `lib.sh:1804–1806`은 `paste-buffer`의 종료 코드를 버린다. 그리고 세션 이름에 `cline|claude|agy|grok`이 포함되면 붙여넣기 가시성 검증마저 건너뛴다(L1809–1812) — 즉 **실제 운영 대상 전부**에서 실패가 무성으로 삼켜진다.
```bash
_sks_herdr set-buffer -b "$sks_buf" "$text"
local _paste_rc=0
_sks_herdr paste-buffer -b "$sks_buf" -t "$sess" || _paste_rc=$?
_sks_herdr delete-buffer -b "$sks_buf" 2>/dev/null || true
if [ "$_paste_rc" != "0" ]; then
echo "send_keys_safe: paste-buffer failed rc=$_paste_rc ($sess)" >&2
return 3
fi
```
버퍼 정리(`delete-buffer`)는 조기 반환 **앞**에 둔다. 그렇지 않으면 실패 경로마다 버퍼가 누수되어 `set-buffer`의 A-3 GC 주석이 방어하는 바로 그 문제가 재발한다.
기존 반환 코드 계약(`3 = paste not visible`)을 재사용하므로 호출자 계약은 바뀌지 않는다.
### 3.8 [C10] 테스트 목(mock) 정합화 — `tests/conftest.py`
테스트 코드보다 **먼저** 처리해야 한다. 목이 실제 CLI와 어긋나 있는 한 어떤 테스트도 결함을 재현할 수 없다.
| 변경 | 위치 | 내용 |
|---|---|---|
| M1 | `cmd1 == "agent"`, `cmd2 == "send"` (L638–664) | **핸들러 삭제** → 실제 CLI처럼 unknown subcommand로 exit 1. ISSUE-1 재현의 필수 조건 |
| M2 | `cmd1 == "pane"` | `send-text` 핸들러 추가: pane_id로 대상 조회, `sent_text` 누적, `buffer` 갱신, `sent_keys`는 **건드리지 않음** |
| M3 | `cmd1 == "pane"` | `read` 핸들러 추가: 대상 패인의 `buffer` 평문 출력 |
| M4 | `cmd1 == "pane"` | `rename` 핸들러 추가: `state["panes"]`의 해당 항목에 `label` 기록 |
| M5 | `pane list` (L253–281) | 현재는 agents가 하나라도 있으면 `state["panes"]`를 **무시**한다. → agent 유래 패인과 `state["panes"]`를 `pane_id` 기준으로 병합(dedupe)하고, `label`/`name` 필드를 그대로 실어 보낸다. 라벨 전용 패인 시나리오가 이 변경 없이는 표현 불가 |
| M6 | `pane list` | `--workspace` 필터는 이미 구현되어 있음(L255–261). 유지 |
| M7 | `agent get` (L569) | 응답에 `workspace_id`가 이미 포함됨(L594). 유지 |
목의 `_match_agent`(L182)는 이미 엄격(완전 일치 / sanitize 일치)하므로 변경 불필요하다.
---
## 4. 테스트 계획
### 4.1 `tests/test_herdr_shim_contract.py` — 행위 테스트 (신규 H-15 ~ H-20)
기존 파일의 규약을 따른다: `mam_sandbox` / `mock_herdr` / `mock_agents` 픽스처로 셈을 실제 실행하고, `mock_herdr_state.json`의 `calls` 배열을 검증한다.
**H-15 `test_h15_paste_buffer_inserts_without_enter`** (ISSUE-1)
- 준비: `mock_agents`로 `test-creator-claude` 기동.
- 실행: `herdr set-buffer -b t1 "hello world"` → `herdr paste-buffer -b t1 -t test-creator-claude`.
- 단언:
- `calls`에 `["pane","send-text",<pane_id>,"hello world"]`가 정확히 1회.
- `calls`에 `["agent","send",...]`가 **0회** (M1로 이제 실패하게 되므로 회귀 감지).
- `paste-buffer` 실행으로 발생한 `calls` 중 `pane send-keys` / `agent prompt` / `pane run`이 **0회** ← 이중 제출 방지의 핵심 단언.
**H-16 `test_h16_send_keys_safe_submits_exactly_once`** (ISSUE-1 종단)
- `agent prompt` 고속 경로를 강제로 실패시켜(존재하지 않는 세션명 또는 목의 `prompt` 실패 주입) 폴백 경로를 타게 한다.
- 단언: `Enter`/`C-m` 키 전송 횟수 총합이 정확히 1. (현재 코드는 `paste-buffer` 자체가 죽어 0회, 버그 리포트가 기술한 패치 상태에서는 2회 — 양쪽 모두 이 테스트가 잡는다.)
**H-17 `test_h17_no_substring_cross_pane_routing`** (ISSUE-2) — **핵심 회귀 테스트**
- 준비: `reviewer-creator-grok-01`, `worker-grok-02` 두 agent를 서로 다른 pane_id로 기동.
- 실행: `herdr send-keys -t reviewer-creator-grok-01 C-m`.
- 단언: `pane send-keys`의 대상 pane_id가 `reviewer-creator-grok-01`의 것과 일치. `worker-grok-02`의 pane_id로 간 호출은 0회.
- 추가: agent 등록 없이 `agent: "grok"` 라벨 전용 패인만 두고 `herdr has-session -t reviewer-creator-grok-01` → **exit 1**이어야 한다(예전 부분 매칭이면 0).
**H-18 `test_h18_workspace_scoped_pane_resolution`** (ISSUE-3)
- 준비: `state["panes"]`에 동일 `label: creator-agy-01`을 `workspace_id: w1`, `w2`에 각각 1개씩 시드.
- 실행 A: `HERDR_WORKSPACE_ID=w2 herdr send-keys -t creator-agy-01 Enter` → 대상이 `w2`의 pane_id.
- 실행 B: `HERDR_WORKSPACE_ID=w1` → 대상이 `w1`의 pane_id.
- 실행 C: `HERDR_WORKSPACE_ID` 미설정 → 해석은 성공하되 실패하지 않음(기존 전역 동작 보존).
**H-19 `test_h19_single_resolver_helper_used_by_all_branches`** (ISSUE-5)
- 생성된 셈 파일(`$WORKSPACE_ROOT/.mam/shim/herdr`)을 읽어:
- `_resolve_herdr_pane_id()` 정의가 정확히 1회 등장.
- `has-session` / `kill-session` / `capture-pane` / `send-keys` / `paste-buffer` 각 분기 본문에서 `_resolve_herdr_pane_id` 호출이 등장.
- `result', {}).get('agent', {}).get('pane_id'` 형태의 인라인 파서 잔존 개수가 헬퍼 내부 1곳으로 한정.
- `bash -n`으로 셈 구문 검증.
**H-20 `test_h20_pane_id_regex_accepts_alphanumeric_workspace`** (§1.2 회귀 방지)
- 헬퍼를 직접 호출해 `w1E:p1`, `w10:p3` 형태가 통과하고 `notapane`, `w1:p`, 빈 문자열이 거부되는지 확인.
- 이 테스트가 없으면 버그 리포트 원문의 `^w[0-9]+:p[0-9]+$`가 나중에 다시 들어와도 아무도 모른다.
### 4.2 `tests/test_b19_headless_reconcile_fixes.py` — 소스/헬퍼 단위 테스트 (신규 D-4 ~ D-7)
기존 `_run_lib_helpers()` 헬퍼(L119–130)와 소스 문자열 검사 패턴을 재사용한다.
**D-4 `test_resolve_pane_id_fails_cleanly_under_set_e`**
- `set -euo pipefail` 아래에서 `_resolve_herdr_pane_id nonexistent || true`가 셸을 죽이지 않고 빈 출력 + rc 1을 내는지.
**D-5 `test_send_keys_safe_returns_3_when_paste_buffer_fails`** (ISSUE-1)
- `_sks_herdr` 스텁: `agent prompt` → rc 1, `paste-buffer` → rc 1, `send-keys` 호출은 파일에 기록.
- 단언: `send_keys_safe` rc == 3, 기록 파일에 `C-m` 없음.
- 추가 단언: `delete-buffer`가 호출되었음(버퍼 누수 방지).
**D-6 `test_no_substring_matching_remains_in_lib_sh`** (ISSUE-2) — 소스 가드
- `lib.sh` 전문에서 정규식 `\bin tn\b` 및 `agent"\) in tn` 패턴 매치가 0건.
- `_resolve_herdr_pane_id` 본문에 `^w[A-Za-z0-9]+:p[A-Za-z0-9]+$`가 존재.
**D-7 `test_paste_buffer_branch_never_submits`** (ISSUE-1) — 소스 가드
- `lib.sh`에서 `paste-buffer)` ~ 다음 `;;` 구간을 잘라내어 `Enter`, `C-m`, `pane run`, `agent prompt` 문자열이 없음을 단언.
- 행위 테스트(H-15)와 중복처럼 보이지만 층이 다르다: H-15는 목 경유라 목이 잘못되면 함께 침묵하고, D-7은 소스를 직접 본다.
### 4.3 회귀 범위
`has-session` 의미 변경(3.3)과 `capture-pane` 경로 변경(3.5)이 넓게 파급되므로, 다음을 우선 확인한 뒤 전체를 돌린다.
```bash
.venv/bin/python -m pytest tests/test_herdr_shim_contract.py \
tests/test_b19_headless_reconcile_fixes.py \
tests/test_b8_send_keys_verification.py \
tests/test_orc_onboard.py tests/test_workspace_scope.py \
tests/test_uuid_target.py tests/test_sanitize_and_mock_errors.py -q
```
이후 전체:
```bash
.venv/bin/python -m pytest -q
```
**기준선 (실측)**: 작업 착수 시점(`4bbd03b`)에 `test_herdr_shim_contract.py` + `test_b19_headless_reconcile_fixes.py` + `test_workspace_scope.py` = **17 passed / 9.2s**.
전체 스위트(`pytest -q`) = **397 passed / 502.00s (8분 21초)**. `tier3`/`tier4` e2e가 herdr 목 프로세스를 다수 포크하는 것이 소요 시간의 대부분이다. 구현자는 다음을 전제로 시간을 배분할 것:
- 반복 개발 루프에서는 4.3의 **우선 범위**만 사용한다(약 10초).
- 전체 회귀는 S7에서 1회만, 백그라운드로 돌린다(약 8~9분).
- 완료 기준은 **397 + 신규 10건 = 407 passed**이다. 이보다 적으면 기존 테스트가 사라졌거나 무성 skip된 것이므로 반드시 원인을 규명할 것.
- `pytest-timeout`은 이 저장소에 설치되어 있지 않다 — `--timeout=` 플래그는 `unrecognized arguments`로 즉시 실패한다. 필요하면 `requirements-dev.txt`에 추가하거나 셸 레벨에서 제어할 것.
---
## 5. 실행 순서 (권장 커밋 단위)
| 단계 | 내용 | 검증 |
|---|---|---|
| S1 | [C10] `conftest.py` 목 정합화 (M1~M5) | 기존 스위트 실행 → **여기서 깨지는 테스트가 곧 은폐되어 있던 결함의 목록**. 목록을 기록한다 |
| S2 | [C1] `_resolve_herdr_pane_id` / `_herdr_ws_scope` 신설 (호출부 변경 없음) | `bash -n`, H-20, D-4 |
| S3 | [C2][C3] 부분 매칭 제거 (ISSUE-2) | H-17, D-6 |
| S4 | [C5][C6][C7] 분기 리팩터링 (ISSUE-5) | H-19, 4.3 우선 범위 |
| S5 | [C8][C9] `paste-buffer` 재작성 + 실패 전파 (ISSUE-1) | H-15, H-16, D-5, D-7 |
| S6 | [C4] `HERDR_WORKSPACE_ID` 전파 (ISSUE-3) | H-18 |
| S7 | 전체 회귀 | `pytest -q` 전량 그린 |
S2를 S3~S6보다 먼저 두는 이유: 헬퍼만 추가하고 아무도 호출하지 않는 상태는 **정의상 무해**하므로, 이 시점에 스위트가 깨지면 원인이 히어독 구문 오류 하나로 좁혀진다.
---
## 6. 리스크 및 완화
| # | 리스크 | 영향 | 완화 |
|---|---|---|---|
| R1 | 셈은 `lib.sh` 내부 히어독이라 편집 시 `$`, 백틱, 따옴표 이스케이프 사고가 나기 쉽다 | 셈 전체가 구문 오류로 죽어 모든 herdr 호출 실패 | `<<'EOF'`(따옴표 히어독)이므로 셸 확장은 일어나지 않음. 각 단계마다 `_init_herdr_isolation` 실행 후 생성물에 `bash -n` |
| R2 | `has-session`이 라벨 전용 패인을 "존재"로 판정 (3.3) | `create_session.sh`가 죽은 패인을 재사용해 세션 재생성 실패 | 4.3 우선 회귀 범위에 `test_orc_onboard.py` 포함. 문제 시 라벨 폴백을 `MAM_HAS_SESSION_PANE_FALLBACK=1` 옵트인으로 격하 |
| R3 | `capture-pane`이 `agent read` → `pane read`로 전환 | 출력 포맷 차이로 `_pane_quiescent` / 준비 토큰 매칭 실패 | §1.5에서 실기 검증 완료(양쪽 평문). `test_b8_send_keys_verification.py`로 회귀 확인 |
| R4 | `HERDR_WORKSPACE_ID` 하드 필터가 정당한 교차 워크스페이스 조회를 차단 | 다중 워크스페이스 오케스트레이션 기능 상실 | 자동 추론을 채택하지 않음(3.4). 미설정 = 기존 전역 동작. H-18 실행 C가 이를 고정 |
| R5 | 구버전 herdr가 `pane list --workspace`를 모름 | 플래그 오류로 조회 실패 | 클라이언트측 `workspace_id` 필터를 이중으로 유지(3.1). `2>/dev/null || echo ""`로 폴백 |
| R6 | `paste-buffer` 실패 전파(3.7)로 이전엔 "성공"이던 경로가 rc 3을 반환 | 상위 오케스트레이터가 새로 실패를 보게 됨 | 이는 **의도된 결과**다 — 기존 "성공"은 텍스트가 전달되지 않은 무성 실패였다. 다만 배포 노트에 명시 |
---
## 7. 완료 기준 (Definition of Done)
1. `.agents/skills/lib.sh`에 `_resolve_herdr_pane_id`가 **정확히 1회** 정의되고, `has-session` / `kill-session` / `capture-pane` / `send-keys` / `paste-buffer` 5개 분기가 모두 이를 호출한다.
2. `lib.sh` 전문에 `agent ... in tn` 형태의 부분 문자열 매칭이 0건이다.
3. `paste-buffer` 분기가 `pane send-text`만 사용하고 `Enter` / `C-m` / `pane run` / `agent prompt`를 사용하지 않는다.
4. `HERDR_WORKSPACE_ID`가 설정되면 패인 해석이 해당 워크스페이스로 제한되고, 미설정 시 기존 전역 동작이 보존된다.
5. `tests/test_herdr_shim_contract.py`에 H-15 ~ H-20, `tests/test_b19_headless_reconcile_fixes.py`에 D-4 ~ D-7이 추가되고 전부 통과한다.
6. `.venv/bin/python -m pytest -q`가 **407 passed**(기준선 397 + 신규 10)로 전량 그린. 실패가 남으면 원인과 함께 명시 보고(무성 skip 금지).
7. `bash -n`이 `lib.sh` 및 생성된 `.mam/shim/herdr` 양쪽에서 통과한다.
---
## 8. 계획 범위 밖으로 남기는 항목
- **ISSUE-4** — 커밋 `4bbd03b`에서 이미 수정 완료. `test_agent_start_success_tokens_exclude_startup_timeout`이 회귀를 고정하고 있어 추가 작업 없음.
- **`list-panes` 분기** — 인라인 파서를 유지한다. `pane_id` 단독이 아니라 `cwd`/`agent`를 함께 파싱하므로 `_resolve_herdr_pane_id`로 대체 불가이며, ISSUE-5의 대상 목록에도 없다.
- **`bug_report.md`의 업스트림 반영** — 본 작업은 이 저장소의 `lib.sh`에 한정한다. `multi-agent-mux` 업스트림 배포는 별도 릴리스 절차(`VERSIONS.md`, `deploy/`)를 따른다.
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261025T023502Z-d6f876",
"base_sha": "0461a632eb667c7988fd33be92e9a4b36151f22a",
"head_sha": "bb496fde785133ad1dbec288aa7431766efb6eb5",
"tree_sha": "15a72c9a1933c64018a2f2d9aa9707348905bb4d",
"review_commit": "bb496fde785133ad1dbec288aa7431766efb6eb5",
"reviewer": "planner-reviewer-claude-01",
"job_id": "05af786c",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-25T03:40:44Z"
}
@@ -0,0 +1,104 @@
# PR #70 (Issue #66) 리뷰 — head bb496fd
- 리뷰어: planner-reviewer-claude-01 (macOS, bash 3.2, /usr/bin/python3 3.9.6)
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261025T023502Z-d6f876/1`
- identity 확인: HEAD bb496fde785133ad1dbec288aa7431766efb6eb5, tree 15a72c9a1933c64018a2f2d9aa9707348905bb4d, `git status --porcelain --ignored` 비어 있음, `.mam` 없음 (시작·종료 시 모두). main HEAD 0461a63 그대로.
- 범위: base 0461a63..bb496fd (커밋 1개). 바뀐 파일은 세 개다: `.agents/skills/lib_py/stall_watch.py`, `tests/conftest.py`, `tests/test_issue66_stall_watch_sanitized_name.py`.
## 1. 확인한 것과 근거
### 1) 완료 조건
herdr 를 부르는 곳은 모두 변환된 이름을 쓴다.
- `HerdrSource.__init__` 이 `self.name = sanitize_herdr_agent_name(target)` 를 만든다 (`stall_watch.py:162`).
- 이 이름을 쓰는 곳:
- `agent get` (:183)
- `agent read` (:206)
- `agent prompt` (:211)
- `watcher.wait_once(self.herdr_name, …)` (:331, 값은 :229)
- `pane process-info` 와 `pane read` (:187, :193)는 `agent get` 이 돌려준 pane_id 를 쓰므로 이름과 상관이 없다.
- `--herdr-session` 은 서버 이름으로만 쓰인다. `self.session` (:159) 과 `session=self.args.herdr_session` (:331) 이고, 변환되지 않는다. 둘을 섞어 쓴 곳은 없다.
로그와 알림은 원래 이름을 쓴다.
- 로그 :373 (blocked), :397 (입력창 비어 있지 않음), :406 (idle) 은 모두 `self.args.target` 이다.
- 알림 상세(`stalled:idle`, `stalled:blocked …`)에는 이름이 들어가지 않는다.
- 회귀 테스트는 `agent {target} idle for` 와 `agent {target} is blocked` 가 원래 이름으로 나오는지 확인한다 (test :85, :106).
변환이 필요 없는 이름(`creator-claude-t`)은 그대로이고, 그 경우의 테스트도 통과한다 (test :68 의 PLAIN).
### 2) 회귀 테스트: base 에서 실패, head 에서 통과
- head: 7 passed.
- base(0461a63) 사본에 head 의 새 테스트와 conftest 를 넣고 돌리면 5 failed, 2 passed 다.
- 실패: LONG, UPPER 두 이름 각각의 idle nudge 와 blocked 보고 (4개), 긴 codex 이름의 종류 판정 (1개).
- 통과: strict mock 자체를 확인하는 테스트와, 변환이 필요 없는 PLAIN.
### 3) 변환 함수가 lib.sh 와 같은 결과를 내는가
lib.sh `_sanitize_herdr_agent_name` (:293-316) 과 `lib_py.agents.sanitize.sanitize_herdr_agent_name` 에 같은 이름 10개를 넣어 비교했다.
- 비교한 이름: 그대로 둘 이름, 대문자, 32자 초과(루프 세션 이름 포함), 정확히 32자, 33자, 숫자로 시작, `.`·공백·`@`, 비 ASCII `Ü`, `_` 로 시작.
- 결과: 10개 모두 같고, 두 번 변환해도 바뀌지 않는다.
- 그래서 호출자가 이미 변환된 이름을 넘겨도 안전하다.
- 호출자는 원래 세션 이름을 넘긴다: `multi-agent-mux-delegate-job:431`, `:615` → `start_stall_watch "$AGENT_SESSION"` 와 `"$current_session"`.
### 4) resolve_agent 를 원래 이름으로 하는 것이 맞는가
맞다.
- 긴 이름은 변환되면 끝이 해시로 바뀐다. 예: `mam-wt-issue-66-very-long-creator-codex` → `…-<sha8>`. 그래서 종류는 원래 접미사에서 읽어야 한다.
- `HerdrSource` (:163) 과 `StallWatch` (:230) 둘 다 원래 이름을 쓴다.
- 테스트 :111-129 가 `--agent ""` 일 때 codex 로 정해져 nudge 가 가는 것을 확인한다.
- 종류를 변환된 이름에서 읽도록 바꾼 변이(m3)는 이 테스트에 잡힌다.
### 5) conftest `strict_agent_names`
- 기본(키 없음)일 때 `_match_agent` 는 예전과 똑같이 네 가지 비교를 한다 (`conftest.py` 수정분 :473-476). get/read 의 실패 출력도 예전 문구 그대로다. 그래서 기존 테스트의 동작은 바뀌지 않는다.
- 켜면 등록된 이름과 정확히 같을 때만 답하고, 아니면 `{"error":{"code":"agent_not_found"}}` 를 stderr 에 쓰고 exit 1 한다. 실제 herdr 처럼 등록 이름(변환된 이름)으로만 찾는다.
- 테스트 :51-65 가 get, read, wait, prompt 네 명령 모두 원래 이름에는 agent_not_found 를, 변환된 이름에는 rc 0 을 내는지 확인한다.
### 6) macOS 호환
- `/usr/bin/python3` 3.9.6 으로 `lib_py.stall_watch` import 와 `resolve_agent` 호출이 된다.
- 새 코드에 `X | Y`, `match`, tomllib 가 없다. 셸은 바뀌지 않았다.
### 7) test_issue17_item4_decisions::test_c_finalize_ends_with_an_unreaped_wrapper[broker_unavailable-3-0]
이 변경과 무관하다.
- 이 테스트는 래퍼의 finalize 를 자체 shim(`PY=<shim>`)으로 돌린다. stall watcher 는 argv 를 기록하는 대역이다 (`tests/test_issue17_item4_decisions.py:218`).
- conftest 의 mock herdr 와 `lib_py.stall_watch` 를 쓰지 않는다.
- 판정 조건은 `took < 4.5` 와 terminate 뒤 레코드가 그대로인지 (:598-601) 로, 시간과 정리 단계에 의존한다.
- 이 PR 이 바꾼 것(stall_watch 의 이름 변환, 기본 꺼짐인 mock 옵션)은 이 경로에 닿지 않는다.
- 이 호스트에서도 통과했다(아래 표).
## 2. 실행한 테스트
모두 `env -i`, 임시 HOME/XDG, `PYTHONDONTWRITEBYTECODE=1 -p no:cacheprovider --basetemp=<scratchpad>` 로 돌렸다. .mam.env 를 export 하지 않았다.
| 대상 | 결과 |
|---|---|
| 검증 경로 `tests/test_issue66_stall_watch_sanitized_name.py` | 7 passed |
| base 사본 + 새 테스트·conftest | 5 failed, 2 passed |
| 검증 경로: test_issue30_stall_watch, test_issue30_stall_watch_stop, test_issue17_item4_decisions, test_tier2_component, test_issue63_same_cwd_ids, test_issue50_dispatch_herdr, test_c1_tui_readiness (mock herdr 를 쓰는 인접 테스트) | 457 passed, 1 skipped, 0 failed |
변이 테스트 (head 사본, issue66 테스트):
| # | 변이 | 결과 |
|---|---|---|
| m1 | `wait_once` 를 원래 이름으로 | 잡힘 (5 failed) |
| m2 | `agent prompt` 를 원래 이름으로 | 잡힘 (3 failed) |
| m3 | 종류를 변환된 이름에서 판정 | 잡힘 (1 failed) |
| m4 | blocked 로그를 변환된 이름으로 | 잡힘 (2 failed) |
| m5 | `agent read` 를 원래 이름으로 | 잡힘 (3 failed) |
실제 herdr 서버(pid 19169 `herdr server`, 23492 `herdr --session multi-agent-mux server`)는 테스트 전후로 같다.
## 3. 차단 결함
없음.
## 4. 비차단
- **N1**: 변환된 이름을 두 곳에서 따로 만든다(`HerdrSource.name` :162, `StallWatch.herdr_name` :229). 주입된 source 를 쓰는 테스트 때문에 둘 다 필요해 보인다. 결과가 같으므로 동작에는 문제가 없다.
- **N2** (기존, 이 PR 과 무관): `--agent` 가 비어 있고 이름이 `…-claude-01` 처럼 숫자로 끝나면 `resolve_agent` 는 종류를 정하지 못한다(None). 실제 호출자는 항상 `--agent "$AGENT"` 를 넘기므로 지금은 영향이 없다.
- **N3** (기존, 이 PR 과 무관): lib.sh 에 `_sanitize_herdr_agent_name` 이 두 벌 있다(:36, :293). sha 도구가 없을 때의 대처가 서로 다르다(:36 은 32자로 자르고, :293 은 python3 로 해시). 이 호스트처럼 shasum 이 있으면 두 벌 모두 Python 판과 같다.
[VERDICT: PASS]
@@ -0,0 +1,40 @@
# 🔍 Cross-Code Review — Cline Deprecation Consensus Opinion, Rev.3 (Job 073e27d4)
- **Reviewer**: `planner-reviewer-claude-01`
- **Target document**: `.agents/reports/cline_deprecation_opinion.md` (Rev.3 — response to `reviewer-creator-grok-01` (job `0a056794`) and `reviewer-hermes-01` (job `bc68ed65`) reviews)
- **Prior review context**: I also reviewed Rev.2 of this same document in job `b9a72dce`, flagging 3 findings (imprecise `§6.2`/`§4.2` cross-references, an overclaimed "proved ~0.5–1.5 days" statement, and a stale §1 summary line). Rev.3 does not appear to be a response to that review — its changelog (F1/F2/F3) addresses different findings from grok's and hermes's separate reviews. This review checks both: whether Rev.3's own new claims are accurate, and whether my earlier findings were carried forward.
- **Method**: read the full current file (109 lines, confirmed via `wc -l`; `git status --short` shows only this file as untracked, confirming the "no skill/framework code modified" constraint holds), and independently re-verified Rev.3's three new corrections (F1/F2/F3) against the live `cline --help` output and `reconcile.sh` source rather than accepting the changelog's claims at face value.
---
## 1. Constraint Compliance
`git status --short` → only `?? .agents/reports/cline_deprecation_opinion.md`. No skill/framework code touched. Diff header claims `+109` lines; live file is 109 lines — consistent.
## 2. Verification of Rev.3's Own New Claims (F1/F2/F3)
I did not take the changelog's self-description at face value — I re-derived each claim independently:
- **F1 (flag inventory)**: Ran `cline --help` myself. Confirmed line 25 of its output: `-k, --key <api-key> API key override for this run`. The report's bounded framing — this flag injects a key at startup but cannot refresh a credential mid-task or suppress the interactive modal fallback on a runtime provider failure, and no `--headless`/`--non-interactive` flag exists — is accurate; I found nothing in `cline --help` contradicting that scope-limiting claim. **Verified correct.**
- **F2 (drift-C modernization status, corrected line numbers)**: I grepped `reconcile.sh` for `sibling_claimed` and drift-C block headers. Initially my grep for `"drift C ("` missed claude's block because its header uses a different format (`# === drift C: claude ...` — colon, not a parenthesized agent name, unlike agy/hermes/cline's `# === drift C (agy): ...` style). On closer inspection, claude's block **is** at line 637 exactly as claimed, and it indeed calls `verify_session_uuid(cwd, 'claude', uuid, s, mode="discover")` with the raw row `s` — no `sibling_claimed` exclusion, matching cline's block at line 785. agy (line 692) and hermes (line 742) both build `s_eval['_sibling_claimed_uuids']`. **Verified correct** — this is a genuine improvement over Rev.1/Rev.2, which had incorrectly implied claude's block was already modernized (grouping it with agy/hermes).
- **F3 (consensus attribution)**: Cross-checked against hermes's original report (`.mam/jobs/57f33eff/hermes-reports/report-final.md`), which does state the drift-C fix as an explicit numbered condition of its RETAIN verdict, and grok's report, which lists the drift-C block within cline's maintenance-cost inventory (to be deleted under REMOVE) rather than as a standalone precondition. **Verified correct.**
All three of Rev.3's own corrections are accurate and represent genuine, verified improvements over Rev.2.
## 3. Findings Carried Forward — Unaddressed from My Rev.2 Review (job `b9a72dce`)
Rev.3's changelog responds to grok's and hermes's reviews, but none of the three issues I flagged in my own separate Rev.2 review were incorporated. Re-verified as still present in the live Rev.3 text:
- **Still present** (line 14, 85): `§6.2` cited as if it were a subsection heading. §6 (line 102) is still a flat `## 6.` heading followed by a plain numbered list (`1.`, `2.`) — no `### 6.1`/`### 6.2` headings exist anywhere in the document. Same issue as before, unfixed.
- **Still present** (line 49): "the grok integration already **proved** the reverse operation (adding an agent) costs ~0.5–1.5 days" — unchanged. As I found in the prior review, `grok.py` was added in a single squashed commit (`ad8201d`, 2026-08-26), which cannot establish actual wall-clock effort; the day-count traces to `new_agent_types_roadmap.md`'s a priori estimate for different hypothetical candidates, not a measured fact about grok. "Proved" still overstates this.
- **Still present** (line 34): "**2 of 3 lean RETAIN** (both conditional on the same follow-up fix)" — unchanged. As of Rev.2, my own RETAIN vote already carried an additional condition (the §6 item 2 safety gate) that hermes's original report never agreed to, so the two RETAIN votes are not conditioned on literally the same thing. This has been true since Rev.2 and remains uncorrected in Rev.3.
## 4. Minor Observation (not a defect)
The §0 changelog's Rev.2 entry was compressed from Rev.1/Rev.2's original 4-row table (which included per-point verification methodology, e.g. "I ran `cline history --help` myself") into shorter prose bullets during the Rev.3 restructuring. Some audit-trail granularity was lost from the changelog summary specifically, though the underlying detail still lives in the body sections (§3.1, etc.) it refers to. Not a correctness issue, just a slight reduction in the changelog's own self-sufficiency as a summary.
## 5. Verdict
Rev.3's own corrections (F1/F2/F3) are all independently verified accurate and are genuine improvements — in particular, F2 correctly identifies that claude's drift-C block is just as un-modernized as cline's, which earlier revisions had gotten wrong. However, three previously-identified, still-valid findings from my prior review of this same document were not carried forward into this revision. None of these — old or new — are severe enough to undermine the document's core methodology or conclusions; they remain small, mechanical precision fixes. Passing, with the expectation that a future revision finally closes out all outstanding findings from both review passes together rather than only the most recent one.
[VERDICT: PASS]
@@ -0,0 +1,61 @@
# 🔍 Cross-Review — Markdown Audit & Cleanup Implementation (Job `08e3e7a6`)
- **Reviewer**: `planner-reviewer-claude-01`
- **Target**: the uncommitted diff implementing `plan-e359e7af.md` (Rev. 2, refined per `creator-agy-01`'s challenge `9dcd14f6`) — 8 modified files, 1 deletion, 1 new archival plan file.
- **Method**: I authored the plan this diff implements, so my focus here is verifying *actual execution* against the plan's checklist, not re-deriving the findings from scratch — every acceptance-checklist line item was checked directly against the live working tree (not the diff text alone), plus an independent syntax/logic sanity check of the new bash branches and a full regression run.
---
## 1. §2 Deletions — verified
- `mam-agent-creation-fix-report.md` (repo root): confirmed removed (`ls` → No such file). `bug-report/mam-agent-creation-fix-report.md` confirmed intact (4596 bytes, unchanged).
- `implementation_plan.md`, `IMPROVEMENTS.md`, `MESSAGING.md`, `AGENTS.md`: confirmed zero diff (`git diff --stat` against these paths returns empty) — correctly left untouched.
## 2. §3.1/3.3 README + deploy/INSTALL.md content sync — verified
- `README.md`/`README.ko.md`: both now name all 5 agents in the intro paragraph, the `multi-agent-mux-resume` bullet, the review-loop bullet, and both Mermaid sequence-diagram `Note over R` lines. Both add the same `v4.1.3` VERSIONS.md-linked badge (not a hardcoded standalone number needing separate lockstep tracking, per the plan's explicit requirement). Both add a one-sentence, accurately-worded note on Herdr daemon process-group isolation (`start_new_session=True`) matching the real v4.1.3 behavior. Both files' edits are structurally parallel (same insertion points, same content), so language parity holds.
- `deploy/INSTALL.md:3`: confirmed `OpenCode` added to the parenthetical agent list, single-word diff as specified, no structural change.
## 3. §3.2 BOOTSTRAP.md/.ko.md — verified, including the Rev. 2 addition
- Version badge added identically to both files (same badge markup as README).
- **8-skill scaffolding list** (the Rev. 2 finding): confirmed `multi-agent-mux-loop` and `multi-agent-mux-orc-onboard` bullets were added to both language files, in the correct position (end of the `skills/` sub-list, same bullet style as the existing 6). I checked the added description text against each skill's own `SKILL.md` `description:` frontmatter (not paraphrased from memory) — `multi-agent-mux-loop`'s bullet ("자율적인 계획-실행-교차검증 반복 순환 루프 오케스트레이터" / "Autonomous planning-execution-review loop orchestrator") accurately compresses its real description ("Run an autonomous planning-execution-review loop... until a unanimous PASS is achieved"); `multi-agent-mux-orc-onboard`'s bullet ("오케스트레이터 세션 UUID 온보딩 및 서브에이전트 격리 헬퍼" / "Orchestrator session UUID onboarding and sub-agent isolation helper") accurately compresses its real description ("Register current or specified orchestrator session UUID... to prevent sub-agent discovery capture"). No fabricated capability claims.
- Onboarding-section agent-list addition (`claude`, `agy`, `hermes`, `grok`, `opencode`) confirmed added identically in both files at the correct location (§7 New Agent Onboarding).
## 4. §3.7 resume/SKILL.md — verified, including both Rev. 2 additions
- Lines 71-75 (the flat if-block → class-aware case): confirmed the echo text now matches `resume_session.sh:67`'s real error string byte-for-byte (`"ERROR: No saved session for $WORKSPACE ($AGENT). Use multi-agent-mux-create first."`), and the `agy|hermes|opencode` arm is a no-op (`:`) with the comment explaining the fresh-spawn fallback, matching the real script's class-based branching described in the plan.
- Lines 88-93 (CMD_FULL case): confirmed the new `opencode) CMD_FULL="opencode --session $UUID --auto --agent build" ;;` arm was added. I independently re-verified this against `.agents/skills/lib_py/agents/adapters/opencode.py:188-191`'s live `resume_spec()` (`f"{binary} --session {session_uuid} --auto --agent build"`) — exact match, not stale from when the plan checked it.
- Line 103 (spawn-dispatch case): confirmed widened from `agy|hermes|grok)` to `agy|hermes|grok|opencode)`.
- **Independent logic check beyond the plan's checklist**: no test in `tests/` parses this markdown file's embedded bash, so I extracted the new branches into a standalone script and ran them directly with `AGENT=opencode`: `bash -n` passed (valid syntax), and execution correctly took the fresh-spawn no-op path, built `CMD_FULL="opencode --session fake-uuid --auto --agent build"`, and dispatched into the non-claude spawn branch. No syntax or logic defect in the new arms.
## 5. §3.8 MULTI_AGENT_RULES.md/.ko.md (Rev. 2 core finding) — verified
- Both `.agents/MULTI_AGENT_RULES.md:21` and `.agents/MULTI_AGENT_RULES.ko.md:21` confirmed changed exactly as specified: `cline` dropped, `grok`/`opencode` added, `antigravity`/`claude`/`hermes` preserved. Diff is scoped to exactly that one line in each file, per the plan's explicit "do not sweep the rest of the file" instruction — confirmed via `git diff --stat`, 2 lines total changed (1 per file, `-1/+1` each).
## 6. §4/§5 Version lockstep and out-of-scope guards — verified, all held
- `.agents/skills/lib.sh`, `VERSIONS.md`, `nats-docker/`: zero diff.
- All 8 `SKILL.md` `version:` frontmatter lines: `git diff -- '.agents/skills/*/SKILL.md' | grep "^[+-]version:"` → empty (no touch).
- `.agents/reports/`: only the new (untracked, additive) `plan-e359e7af.md` archival file — no existing archived report was modified, consistent with "immutable per-job history."
- `tests/test_version_consistency.py -v`: **2 passed** (`test_three_way_version_lockstep`, `test_mam_version_is_not_env_overridable`).
- Full suite (`pytest tests/ -q`): **455 passed, 0 failed**, 11m05s — ran myself, not trusted from any prior claim.
## 7. Acceptance checklist (from `plan-e359e7af.md` §7) — all items confirmed satisfied
- [x] Root duplicate removed, `bug-report/` copy intact.
- [x] `implementation_plan.md`/`IMPROVEMENTS.md`/`MESSAGING.md`/`AGENTS.md` byte-identical to pre-job state.
- [x] `README.md`/`README.ko.md` 5-agent + v4.1.3/Herdr-isolation, parity held.
- [x] `BOOTSTRAP.md`/`BOOTSTRAP.ko.md` same, plus all 8 skills now listed.
- [x] `deploy/INSTALL.md:3` names `opencode`.
- [x] `resume/SKILL.md` 71-75 + 88-93 + 103 all fixed, text verified against real sources.
- [x] `.agents/MULTI_AGENT_RULES.md`/`.ko.md:21` updated, scope confined to that line.
- [x] `lib.sh`/`VERSIONS.md`/8× `SKILL.md` version fields byte-identical.
- [x] Version-consistency tests and full suite 100% pass.
- [x] No file under `.agents/reports/` modified (only the expected new plan archival file added).
## 8. Findings
No lint, functional, or omission defects found. Every item specified in the (twice-refined) plan was implemented exactly as specified, cross-checked against live source files rather than trusted from the diff text, and the regression guard (both the targeted lockstep tests and the full suite) is green. The added illustrative bash was further validated by direct execution, beyond what the plan's checklist required. This closes out the full lifecycle of Job `e359e7af` → challenge `9dcd14f6` → refinement `a39a83fb` → this implementation.
[VERDICT: PASS]
@@ -0,0 +1,128 @@
# 🔍 Review Report — PR #38 병합 전 독립 리뷰 (job `107d435d`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-09-25
- **대상**: PR #38 `fix/issue-34` **@ `ed293dc`**, base `main 7a4a0c2` (v4.7.3). 6커밋, 11파일 `+924/−16`, `git diff --check` 클린.
- **검증 경로**: `/var/folders/.../T/mam-review/loop-20260925T055502Z-a37cf1/1`. **identity 확인**: `HEAD = ed293dce…67cf`, `HEAD^{tree} = 671b0e59…899c` — 브리프와 일치.
- **안전 규칙 준수**: 검증 경로·소스 워크트리(`multi-agent-mux-wt/pr-38`)·본 체크아웃(`main 7a4a0c2`) 모두 수정·커밋·checkout 없음. 등록부 실험은 scratchpad 임시 등록부에서 `registry.py` 를 직접 호출(래퍼 미사용, 실제 herdr 에 잡 생성 없음), 러너 실험은 in-process(`env -u MAM_VERSION`, 임시 git 저장소), lib.sh 는 함수 추출 + `env -i`. 실제 `.mam`·데몬·세션·herdr 서버 조작 없음, push·merge·PR 상태 변경 없음. 이 pane 의 `HERDR_PANE_ID`/`HERDR_WORKSPACE_ID` 는 **읽기만** 했다.
## 결론 요약
**병합을 막을 결함은 없다.** 부모 기록·자손 대기·리뷰 근거 표·stale 가드·같은 서버 다른 워크스페이스 조회 규칙을 각각 독립 실험으로 확인했고, 새 테스트 17건 중 **16건이 수정 전 소스에서 실패**한다. 비차단 관찰 4건(K1–K4). 그중 K1(귀속되지 않은 열린 잡만 있을 때 판정 규칙 문구가 없음)은 브리프 항목 2·4 의 "충분한 근거" 질문에 직접 닿는다.
## 1. 부모 기록 (항목 1)
| 확인 | 결과 |
|---|---|
| `--parent-job` 검증 | `registry.py register`(`:540-544`) 가 등록부에 없는 부모를 `unknown parent job <id>` + rc 1 로 거부. 래퍼(`:217-226`)는 명시 `--parent-job` 을 그대로 넘겨 **같은 검증**에 걸리게 하고, 기본 `MAM_JOB_ID` 는 이 등록부에 그 레코드가 있을 때만 쓰며 없으면 `WARNING: … registering without a parent job` 후 부모 없이 등록 — 두 층의 규칙이 일치한다 |
| 자기 참조 | `--job-id X --parent-job X` 는 등록 시점에 X 가 없어 거부됨(실측). `update` 에는 `--parent-job` 이 없어 **부모는 등록 후 불변** → 정상 경로로는 순환이 만들어질 수 없다 |
| 순환 방어 | 레코드 파일을 직접 고쳐 `root.parent = grandchild` 순환을 만든 뒤 `descendants_of` 를 돌려도 종료한다(`seen` 집합, 방문 1회): root 기준 `[(child,1),(grandchild,2)]`, grandchild 기준 `[(root,1),(child,2)]` |
| `depth` | 저장하지 않고 BFS 에서 계산(자식 1, 손자 2 — 실측) |
| 비용 | `descendants_of` 는 폴링(3 s)마다 `list_jobs` **전체 스캔** 1회(레코드 수 N 의 JSON 읽기). `_subjobs_block` 은 회차마다 root 수만큼 스캔 + `unattributed_open_jobs` 1회. 수백 건이면 문제없고 수천 건이면 3 s 폴링당 수천 파일 읽기 — 등록부 정리 정책이 없는 오래된 제어 평면에서 체감될 수 있다(K4) |
| `MAM_JOB_TREE_MAX`(50) | 넘으면 `log_error` 후 **기다리지 않고** 리뷰로 간다. 안전한 쪽인가: 열린 자손은 `[하위 위임 잡]` 표에 OPEN 으로 나오고 SUBJOB_RULE 이 NOT PASS 를 지시하므로 "조용히 통과"는 아니다. 다만 51개 이상의 행이 프롬프트에 붙는다 |
## 2. 부모 ID 전달 (항목 2)
- 로컬 에이전트: 래퍼가 주입문 끝(`_instructions`, test18 문구 보존)과 `brief.md` 의 `Parent for sub-delegations` 줄(`:251`, `:427`), create 의 온보딩 주입문(`create_session.sh:646`)으로 알린다. 에이전트가 붙이지 않으면 추적이 빠지는 것은 사실이고, 안전망은 두 가지다: (a) `[귀속되지 않은 열린 잡]` 줄 — `unattributed_open_jobs` 가 "부모 없음 + pending/running + 이 루프가 만든 잡 제외 + creator 잡 등록 이후" 로 고른다(실측: 루프 자신의 뒤이은 잡은 제외, 남의 root 잡은 표시); (b) `--wait-open-jobs` 로 그 잡들까지 대기(기본 off — 같은 제어 평면의 무관한 잡이 루프를 잡을 수 있으므로; 문서와 일치).
- **K1 (비차단, 근거 충분성)**: 하위 잡이 하나도 없고 귀속되지 않은 열린 잡만 있을 때 블록은 `[하위 위임 잡] 없음 … [귀속되지 않은 열린 잡]: <id>(…)` 만 담고 **SUBJOB_RULE 을 붙이지 않는다**(`_subjobs_block` 의 `if not rows:` 분기 — 실측: `has rule: False`). SUBJOB_RULE 자체도 "하위 잡"만 말하고 귀속되지 않은 잡을 어떻게 볼지는 말하지 않는다. 즉 "creator 가 `--parent-job` 을 빠뜨린" 바로 그 경우에 리뷰어는 사실은 받지만 지시는 받지 못한다. 한 문장("귀속되지 않은 열린 잡이 이 작업의 하위 위임으로 보이면 OPEN 하위 잡과 같이 취급")을 stray 줄 뒤에 붙이면 닫힌다.
- 원격 러너: `MAM_JOB_ID` 가 자동 부모가 되지만 원격 호스트의 등록부에는 그 잡이 없을 수 있어 "있을 때만" 규칙이 맞다(래퍼 주석과 일치).
## 3. 자손 대기 (항목 3)
- `wait_for_job_tree` 는 실행(`:1291`)·수정(`:1520`)·순응(`:1591`) 세 creator 잡 모두에 걸리고, `round_roots` 에 누적된다.
- `MAM_CHILD_WAIT_S`(3900) 의 기준점은 `wait_for_descendants` 진입 시각 = **creator 잡 종결 시점**(문서와 일치). 초과 시 `log_warn` 후 False 를 돌려주지만 `wait_for_job_tree` 는 root 의 결과만 반환하므로 루프는 리뷰로 진행하고 열린 잡은 표에 OPEN 으로 남는다(설계대로).
- `interrupted`: 시그널 핸들러가 체크포인트 저장 후 `sys.exit(128+signum)` 하므로(`_handle_signal`) 폴링 루프의 `if self.interrupted: return False` 는 실제로는 닿지 않는 방어 코드다 — 무해.
- 분류(`_subjob_state`)와 `get_feedback` 의 실제 값: 래퍼는 마감 시 `close --request deadline_timeout` 뒤 `publish_event --event error --detail deadline_timeout`(inject 단계면 `agent_blocked`)을 남기고(`:928-930`), preflight/idle 실패는 `cancelled --detail session_busy` 또는 새 `target_not_found`(`:896`, `:952`), create 롤백은 `cancelled "rolled back by create_session"` 이다. `get_feedback` 은 마지막 `completed/error`(감사 로그) 또는 events.log 의 detail 을 돌려주므로 `ORCHESTRATOR_CLOSED` 튜플·`startswith("rolled back")`·`session_busy|target_not_found` 가 정확히 그 문자열들과 맞는다. 사유 없는 `error` 를 CLOSED-UNCONFIRMED 로 보는 규칙은 "에이전트 자신의 보고가 아니다" 는 뜻에서 보수적이며 옳다.
## 4. 리뷰어 근거 (항목 4)
in-process 실측(`_subjobs_block`):
| 상황 | 결과 |
|---|---|
| 하위 잡 없음·stray 없음 | **`''`** — 프롬프트 바이트 동일 |
| 이 루프가 뒤에 만든 잡(`created_jobs`)만 존재 | `''` — 리뷰어 자신의 잡·앞 회차 리뷰 잡은 stray 로 오인되지 않는다(회차의 블록은 리뷰 잡 위임 **전에** 계산된다) |
| 남의 root 잡(부모 없음, creator 잡 이후 등록) | 블록 생성, stray 줄에 id 표시, **규칙 문구 없음**(K1) |
| pending 자식 1개 | 표(`\| OPEN \| - \| 1 \|`) + 집계 + SUBJOB_RULE |
`descendants_of` 가 `depth` 를 주고 `_subjob_state` 가 상태·사유를 주므로 표의 열은 정확하다. 표는 앞 회차 creator 잡의 자손까지 매 회차 다시 읽는다(`round_roots` 누적, T9).
## 5. stale 가드 — 옵션 없는 루프 (항목 5)
`_fingerprint`(`runner.py:954-972`)는 `head` 와, `.mam`(`mam_dir`)·`jobs_dir`·감사 로그 디렉터리(`DELEGATE_JOB_LOGS_DIR`, 상대면 `workspace_root` 기준으로 결합)를 `git add -A -- . :(exclude)<rel>` 로 뺀 tree 다. in-process 실측(임시 git 저장소, **`.gitignore` 없음** — 즉 `.mam` 이 무시되지 않는 최악 조건):
| 상황 | 결과 |
|---|---|
| `DELEGATE_JOB_LOGS_DIR=.mam/delegate_job_logs`(상대) 로 감사 로그·`jobs/*.json` 을 새로 쓴 뒤 | 지문 **불변** — 제어 평면 쓰기는 제외된다 |
| 소스에 untracked 파일 1개 추가 | 지문 **변경** |
| 감사 로그 디렉터리가 소스 **밖**(절대경로) | `relative_to` 가 `ValueError` → 제외 목록에서 빠지고 지문 계산은 정상 |
- **켜지는 조건**: `light = self._fingerprint()` 는 `not identity and subjobs`(`:1350-1352`) — 하위 잡 표나 stray 줄이 있을 때만이다(1d4f338). 하위 위임 없는 루프는 옛 동작 그대로라 `test_tier4_e2e.py::test_e2e_scenario5` 류(소스에 매 잡 바뀌는 untracked 가 있는 경우)가 다시 살아난다 — 이번 실행에서 tier4 포함 통과(§7).
- **적용 지점**: 셀프 리뷰 뒤(`:1368`), 리뷰 판정 수집 뒤(`:1463`, identity 모드의 B7 과 `elif` 로 배타), 승격 직전(`:1595`, identity 모드의 B10 은 `:1613` 로 별도). identity 모드에서는 `light` 가 `None` 으로 남아 **이중 적용이 없다**.
- 지문을 만들 수 없으면(예: dirty 서브모듈) 경고 1회 후 가드 off — 옵션 없는 모드의 기존 동작으로 되돌아가는 것이라 수용 가능하다.
## 6. 같은 서버 다른 워크스페이스 위임 (항목 6)
`_herdr_scope_is_pane_inherited`(`lib.sh:1464-1473`)와 `mam_herdr` 의 `elif`(`:1485-1486`)를 함수 추출 + `env -i` 로 10가지 조합에 돌렸다(전부 설계와 일치):
| 호출 | 환경 | 결과 |
|---|---|---|
| `agent`/`has-session`/`kill-session`(`-L` 접두 포함) | `HERDR_WORKSPACE_ID == HERDR_PANE_ID` 의 워크스페이스, 같은 서버 | **WS id 만 제거**(pane·tab id 유지) |
| `new-session`, `pane split` | 동일 | **유지** — pane 배치·워크스페이스 패킹(#7) 불변 |
| `agent` | WS id ≠ pane 의 워크스페이스(어긋난 스코프) | 유지(의도된 스코프) |
| `agent` | pane id 없음(pane 밖 명시 스코프) | 유지 |
| `agent` | 기본 서버 pane → 이름 있는 서버 | **CROSS-all3** — #23 규칙이 `if` 로 먼저 잡아 세 id 모두 제거, 이 규칙은 `elif` 라 닿지 않는다(충돌 없음) |
| `agent` | 대상 미지정(앰비언트) | WS id 만 제거(같은 서버이므로 같은 취급) |
- 이 pane 의 실제 값도 규칙의 전제(`HERDR_PANE_ID = "<ws>:<pane>"`, `HERDR_WORKSPACE_ID = <ws>`)와 맞았다(값은 읽기만).
- 이름 유일성 근거(herdr `--skill` 문구)는 코드 주석에 인용돼 있고, T10/T11 이 두 방향을 고정한다.
- `target_not_found`: preflight 의 `has-session` 실패가 `PREFLIGHT_REASON` 을 세우고(`:952`) `finalize_unfinished` 가 `cancelled --detail target_not_found` 로 닫는다(`:896`). **rc 는 종전과 같은 5** 다(T12 가 `returncode == 5` 를 고정) — 즉 이벤트 detail 은 정확해졌지만 종료 코드는 "busy" 와 같아서, 루프의 busy 1회 재시도(`MAM_SESSION_BUSY_RETRY_S`)가 없는 대상에도 한 번 더 돌아간다(K3).
## 7. 새 테스트 (항목 7)
- **실제 경로**: T1·T12 는 실제 래퍼(`--agent human`, 도달 불가 브로커)와 `registry.py` 로 등록·종결한다. T3~T9 는 `python -m lib_py.loop` 를 하위 프로세스로 띄우고 가짜 래퍼가 **실제 래퍼**(`FAKE_REAL_WRAPPER`)로 하위 잡을 등록해 자손 대기·표·가드를 통과시킨다. T10~T12 는 mock herdr 위의 샌드박스. `HOME`·`WORKSPACE_ROOT`·`DELEGATE_JOB_LOGS_DIR` 는 `tmp_path`.
- **수정 없이는 실패하는가 — 확인함**: 검증 경로 사본에서 PR 이 바꾼 소스 6파일을 `7a4a0c2` 판으로 되돌리고 새 파일을 돌린 결과 **16 failed / 1 passed**(16.7 s). 통과 1건은 T11("호출자가 고른 워크스페이스 id 는 여전히 스코프") — 정정 전에도 성립해야 하는 불변 조건이다.
- **검증 경로에서의 실행** (9파일: 새 파일 + issue5 phase1·tier4 e2e·issue21 loop B/acceptance·issue23/24·loop_cli·issue25·herdr shim contract):
```
→ 1 failed, 243 passed in 1460.19s (0:24:20)
FAILED tests/test_issue23_24_startup_path.py::test_s7c_a_started_that_was_followed_by_a_terminal_status_still_counts
```
- 새 파일 17건 **전부 통과**, `test_tier4_e2e.py::test_e2e_scenario5`(브리프 항목 5 의 회귀) **통과**(873 s — 이 호스트에서 다른 스위트가 동시에 돌아 load avg 2.5 였다), registry CLI 스냅샷·help 캡처(issue5 phase1) 통과 → `--parent-job` 추가가 기존 CLI 계약을 깨지 않는다.
- **실패 1건은 부하 flake** 로 판정한다: s7c 는 create/registry 의 `started` 증거 시험이며 PR 은 그 경로를 건드리지 않았다(create 는 주입문에 문장 하나 추가뿐). 합동 실행에서 40 s 걸려 `_seed_job` 단계(`--ack-timeout 2`)에서 실패했고, **단독 재실행에서는 s7b 와 함께 2 passed in 10.8 s** 로 통과했다.
- **격리**: 실제 `.mam/jobs`·`.mam/delegate_job_logs` 전후 **차이 0 / 차이 0**. 검증 경로 tracked 파일 변화 없음(HEAD `ed293dc`), 본 체크아웃 `main 7a4a0c2`.
- **실행 시간**: 새 파일 자체는 되돌린 사본 기준 17 s 안팎이고, 합동 실행의 24 분은 tier4 e2e(약 17 분)와 호스트 부하 몫이다.
## 8. 문서 (항목 8)
- loop SKILL.md `:214`(`--wait-open-jobs` 표), `:221`(하위 위임 잡: 대기 범위·`MAM_CHILD_WAIT_S` 기준점·`MAM_JOB_TREE_MAX`·표/규칙·회차 누적), `:223`(stale 가드) — 코드와 일치한다.
- delegate-job SKILL.md `:49-53`·Best Practices, MULTI_AGENT_RULES(ko/en) `:154` — `--parent-job` 의무와 기본값·거부 규칙이 서술돼 있다.
- 래퍼 usage 와 `brief.md` 의 `Parent for sub-delegations` 줄, create 온보딩 주입문 — 모두 같은 문장이다.
## 9. 병합 차단 여부 (항목 9)
버전 락스텝 bump 부재(`lib.sh:32` `4.7.3`, 오케스트레이터가 4.7.4 로 처리 예정) 외에 **병합을 막을 결함은 없다**.
| # | 비차단 관찰 | 근거 / 권고 |
|---|---|---|
| K1 | 귀속되지 않은 열린 잡**만** 있을 때 블록에 SUBJOB_RULE 이 없고, 규칙 문구도 그 잡을 언급하지 않는다 — `--parent-job` 을 빠뜨린 바로 그 경우에 리뷰어가 지시 없이 사실만 받는다 | `runner.py:697-724` 의 `if not rows:` 분기, 실측 `has rule: False`. stray 줄 뒤에 한 문장 권고 |
| K2 | `MAM_JOB_TREE_MAX` 초과 시 대기를 건너뛰고 리뷰로 간다 — 표의 OPEN 행과 규칙이 NOT PASS 를 유도하므로 조용한 통과는 아니지만, 50+ 행이 프롬프트에 붙는다 | `:646-654`. 정보 |
| K3 | `target_not_found` 는 이벤트 detail 만 바뀌고 래퍼 rc 는 `session_busy` 와 같은 **5** 라 루프의 busy 1회 재시도가 없는 대상에도 돈다 | `:896`, `:952`, T12 `returncode == 5`. rc 분리 권고(후속) |
| K4 | `descendants_of`/`unattributed_open_jobs` 는 폴링(3 s)마다 등록부 전체 JSON 을 읽는다 — 수천 건 누적된 제어 평면에서 체감 가능 | `registry.py:259-282`. 등록부 정리 정책 또는 인덱스가 생기기 전까지는 정보 |
## 10. 교차검증 가이드
```bash
RP=/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20260925T055502Z-a37cf1/1
PY=/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.venv/bin/python
git -C "$RP" rev-parse HEAD 'HEAD^{tree}' # ed293dc… / 671b0e5…
# 등록부: 부모 기록·list --parent·미지 부모/자기 참조 거부 (임시 등록부, registry.py 직접)
# descendants_of: 손자 depth 2, 레코드 파일로 순환을 만들어도 종료
# 러너 in-process (env -u MAM_VERSION): _subjobs_block '' / stray / child 표, _fingerprint 의 .mam 제외
# lib.sh: _herdr_scope_is_pane_inherited 10케이스 (§6)
# 되돌린 사본: 소스 6파일을 7a4a0c2 판으로 → tests/test_issue34_job_tree.py → 16 failed / 1 passed
(cd "$RP" && AGENT_PYTHON_BIN="$PY" PYTHONDONTWRITEBYTECODE=1 "$PY" -m pytest -p no:cacheprovider -q --basetemp=/tmp/bt \
tests/test_issue23_24_startup_path.py::test_s7c_a_started_that_was_followed_by_a_terminal_status_still_counts) # 단독 통과
```
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261008T133858Z-9e7f5b",
"base_sha": "6b00b6e06f55299cb60f156ccef09ede4bae5bdd",
"head_sha": "ac48cb78617af88584db529b5766acf02f4af73c",
"tree_sha": "b043034eda891bd83b547dcb34d7422a6977b89d",
"review_commit": "ac48cb78617af88584db529b5766acf02f4af73c",
"reviewer": "planner-reviewer-claude-01",
"job_id": "1364df46",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-08T18:40:20Z"
}
@@ -0,0 +1,35 @@
# 리뷰 리포트 — Job 1364df46 (Issue #17 후속 3회차: 상속 WORKSPACE_ROOT, 6b00b6e..ac48cb7)
- 리뷰어: planner-reviewer-claude-01 (claude)
- 리뷰 identity: loop-20261008T133858Z-9e7f5b / base 6b00b6e / head ac48cb7 / tree b043034 — 검증 경로(…/3)에서 `git rev-parse HEAD 'HEAD^{tree}'` 일치, 미커밋 변경 없음
- 범위: 2회차 head 8b47cc7 위에 커밋 1개(ac48cb7, +9줄): test_o2_race_free_lock.py 의 o2_12 에 테스트 단위 `own_workspace_root` 마크, test_o1_rebuttal.py 에 모듈 마크, W1 NODES 에 두 노드 추가. 제품 코드·버전·VERSIONS 변경 없음.
## 결론 요약
2회차의 차단 지적(test_o2_race_free_lock.py:196-203 이 run_loop.sh → lib.sh 로 자기 체크아웃의 `.mam/shim/herdr` 를 씀)이 닫혔고, grok 이 지적한 test_o1_rebuttal 도 같은 방식으로 덮였다. 2회차에서 깨끗했던 나머지 후보들은 그대로 깨끗하다. 차단 결함 없음.
## 1. 지적 종결
| 지적 | 수정 | 확인 |
|---|---|---|
| claude(2회차): o2_12 가 `dict(os.environ)` 로 run_loop.sh 실행, 마크·sandbox 없음 → 체크아웃 shim 재작성 | test_o2_race_free_lock.py:196-198 — o2_12 에만 `@pytest.mark.usefixtures("own_workspace_root")`(모듈 마크를 피한 이유: o2_7 이 tmp_path 항목 수를 센다 — 타당); W1 NODES 에 o2_12 추가(:41) | HEAD 사본에서 `WORKSPACE_ROOT=<사본>` 으로 o2_12 단독·파일 전체(22 passed) 모두 `.mam` **미생성**; `WORKSPACE_ROOT` 미설정으로도 미생성(2회차에는 두 경우 모두 생성) |
| grok: test_o1_rebuttal 도 run_loop.sh 실행 | 모듈 마크(:10-12), W1 NODES 에 v3 노드 추가(:42) | HEAD 사본 파일 전체(10 passed) 미생성. 새 W1 노드가 의미 있는지: base 트리에서 그 노드 1개를 `WORKSPACE_ROOT=<base 사본>` 으로 실행 → `.mam/shim/herdr` **생성** — 수정 전 결함을 실제로 고정한다 |
## 2. 놓친 모듈이 더 없는가 (2회차 방법 반복)
HEAD 트리 사본에서 `WORKSPACE_ROOT=<사본>` 으로 내 후보 13개 파일(test_o2, test_o1, test_issue30_stall_watch_stop, test_issue36_prompt_transport, test_issue19, test_a4, test_issue21_acceptance, test_issue20, test_issue34, test_issue23_24, test_b4, test_issue15, test_issue10_13; lib.sh 를 source 하는 코드를 실행하면서 sandbox 인자가 없는 테스트 50개)을 파일별로 돌리고 매번 `.mam` 을 확인: **13개 모두 clean**. 2회차에 유일하게 썼던 o2 가 이제 깨끗하다.
## 3. 할 일 4 — 실행 (검증 경로, 워크트리 .venv Python 3.9.6, `env -i` 로 HERDR_*·MAM_*·MQTT_* 제거)
| 실행 | 결과 |
|---|---|
| (a) WORKSPACE_ROOT 없이: 수정 16개 파일(W1·W2 포함) + test_issue33_budget, test_issue5_phase1_delegation, test_tier1_unit | **675 passed / 0 failed** (862 s) |
| (b) WORKSPACE_ROOT=<워크트리 밖 센티널>: 수정 16개 파일 | **522 passed / 0 failed** (707 s); 실행 뒤 센티널 **비어 있음** |
| 본 체크아웃 .mam/shim/herdr mtime | 전후 동일(1791480333); 실제 .mam/jobs 항목 수 불변 |
- W1 은 (a)(b) 양쪽에서 통과했고, 이제 15개 노드(모듈 15개)를 체크아웃 사본에서 돌려 `.mam` 미생성을 고정한다.
- 이식성: Python 테스트 코드만. bash 3.2·macOS 영향 없음.
## 4. 1·2회차 판단 유지
`_env` 의 tmp_path 지정(lib.sh:26 기본값 때문), conftest `pytest_configure` 의 "다른 체크아웃만 제거" 정책과 opt-in fixture 설계(autouse 불가 이유 포함), unittest 클래스의 명시 env, test_orc_onboard 의 호출 시점 root — 모두 이전 리포트대로 타당하다. W1·W2 가 base 에서 실패함은 2회차에 확인했다.
## 5. 비차단
- W1 의 모듈 목록은 수동 유지다(2회차 비차단 그대로). 새 테스트가 lib.sh 를 source 하는 모듈을 추가하면 목록도 늘려야 한다는 점을 conftest 의 fixture docstring 이나 W1 머리말에 한 줄 적어 두면 좋다.
- 새 관찰 없음.
[VERDICT: PASS]
@@ -0,0 +1,75 @@
# 🔍 Cross-Review (Loop Final) — Issue #5 Phase 1 누적 변경분 `8def235..6ad6f08` — Job `1418f44c`
- **Reviewer**: `planner-reviewer-claude-01` (Reviewer role)
- **대상**: 브리프에 첨부된 누적 diff. `git diff 8def235..HEAD`(HEAD=`6ad6f08`, working tree clean)와 **바이트 동일**(639행, md5 `6880f4fb…`, 10 files, +348/−67)임을 확인했다. 내용은 (a) 커밋 `95f3e9a` — Round 1 교차 리뷰 지적(Codex R1/R2, Claude F-1/O-1, 픽스처·문서)의 수정, (b) 커밋 `6ad6f08` — Round 2 비차단 잔여 2건의 문서 반영(코드 변경 없음).
- **선행 검증**: `95f3e9a`는 내가 job `25609c81`에서 전 항목 독립 재검증해 `[VERDICT: PASS]` `[ADJUDICATION: SUSTAINED]`를 냈다. 본 job은 그 결론을 재사용하지 않고 HEAD 기준으로 핵심 검증을 다시 실행했으며(§2), 신규 커밋 `6ad6f08`을 별도로 검토했다(§3).
- **루프 컨텍스트**: 본 루프의 freeze 스냅샷(`mam-loop-freeze.RgjWtB`)은 `8def235` 시점 트리다(`lib.sh`·`publisher.py`·`publish_event.py`가 `8def235` blob과 동일, 생성 시각 16:29:14 = `8def235` 커밋 8초 후). 즉 루프는 수정 전 트리로 고정된 채 두 라운드의 수정 커밋을 검토했다 — B-13이 의도대로 동작한 사례다.
---
## 0. 결론 요약
- `95f3e9a`의 수정 5건(F-1, O-1, R1, R2, 픽스처 정합화)은 HEAD에서 그대로 유효하다. 특성화·PV·회귀 66종 통과, 빠른 회귀 18종 통과, 범위 `fc0bd96..HEAD` `git diff --check` 클린, `bash -n`·`compileall` 클린(§2).
- `6ad6f08`은 문서 2파일 +4/−1로, 벤치 §4 fork 표의 경로 명칭을 실제 구현(`_delegation_py`)으로 정정하고 내 O-4를 `task.md` P3-02 인계 항목으로 기록했다. 두 서술 모두 코드·실측과 일치한다(§3).
- 자동완료 3표면(래퍼, `run_loop.sh`, `reconcile.sh`)은 이 범위에서 **0행** 변경.
- **본 job의 시작 이벤트 자체가 K2 실증이다**: 위임 메시지가 지정한 freeze 경로의 shim(`8def235` 버전)을 라이브 `PYTHONPATH` 환경에서 실행했고, 같은 조건을 재현해 출처를 출력하면 위임 패키지는 freeze, 부모 `lib_py`는 라이브로 바인딩된다(§2-4). 이벤트는 정상 발행됐다(`1418f44c.events.log` seq 1).
- 신규 결함 없음. 재계획(`[ESCALATE: PLANNER]`)이 필요한 사안 없음.
---
## 1. 범위 동일성
```
brief: 639 lines md5 6880f4fb3043921c3403b764ec5dca83
head : 639 lines md5 6880f4fb3043921c3403b764ec5dca83 (git diff 8def235..HEAD)
IDENTICAL
```
파일 10종: `lib.sh`, `lib_py/delegation/{bench,daemon,mqtt_common,publish_event,publisher}.py`, `multi-agent-mux-delegate-job/SKILL.md`, `docs/contracts/issue-5/{phase1-benchmark,task}.md`, `tests/test_issue5_phase1_delegation.py`. 브리프 본문의 과업 설명("265a1f6부터 dfa7212까지 … 54개 신규 테스트, 564개")은 루프 시작 시점의 목표 문구이며, 실제 첨부 diff·현재 수치(66/576)와는 위와 같이 대조했다.
## 2. HEAD 기준 재검증 (`95f3e9a` 항목)
### 2-1. F-1 / O-1 (내 Round 1 지적)
- `publisher.py:27-43` `_send()`가 `info.rc == MQTT_ERR_NO_CONN`만 `ConnectionError`로 번역, 재시도 튜플(`:56`) 불변. Round 2에서 실제 paho 2.1.0으로 재현·검증한 결과(3회 시도 모두 전송 도달, 끊김 2회 후 복구 성공, 다른 `rc`는 비재시도)는 HEAD의 동일 코드에 그대로 적용된다. paho `publish()`가 `info.rc`에 넣는 값은 `SUCCESS`/`QUEUE_SIZE`/`NO_CONN`뿐이고 `QUEUE_SIZE`는 이미 튜플 안의 `ValueError`이므로 번역은 완결적이다.
- `publish_event.py:94-102` `_publish_once` → `OneShotPublisher().publish_raw()` 위임, 타임아웃 상수 단일 소유. `test_one_shot_publish_has_a_single_implementation`이 재발을 막는다.
### 2-2. R1 / R2 (Codex 지적)
- `lib.sh:1952-1968` `_delegation_py`: `python -c` + `sys.path.insert(0, SKILL_DIR)`, cwd 보존, `PYTHONPATH` 전달 유지. Round 2에서 cwd=skills 디렉터리·decoy `lib_py` 조건으로 구형 `-m`은 라이브를, 신형은 자기 트리를 해석함을 실측했다. 프로덕션 cwd(워크스페이스 루트)에는 `lib_py`가 없어 R1은 잠재 결함이었으나 수정은 옳다.
- `publisher.py:140-158` 연결 정체성 10필드 불변 스냅샷 비교, 오류는 필드명만 노출.
### 2-3. 실행 결과 (HEAD, 직접 실행)
| 검증 | 결과 |
|---|---|
| `tests/test_issue5_phase1_delegation.py` | **66 passed in 11.63s** |
| 빠른 회귀(G-1~G-10, mqtt, seq, monitor lock) | **18 passed in 1.74s** |
| `git diff --check fc0bd96..HEAD` | 클린 |
| `bash -n` (`lib.sh`, `reconcile.sh`, 래퍼) / `compileall lib_py/delegation` | 클린 |
| 자동완료 3표면 `git diff --stat 8def235..HEAD` | 래퍼 0행, `run_loop.sh` 0행, `reconcile.sh` 0행 |
| 전체 스위트 | §4 |
### 2-4. K2 라이브 실증 (본 job의 실행 조건 그대로)
```
delegation -> /var/folders/.../mam-loop-freeze.RgjWtB/.agents/skills/lib_py/delegation
lib_py -> /Users/.../multi-agent-mux/.agents/skills/lib_py/__init__.py
```
`PYTHONPATH`=라이브 트리인 프로세스에서 freeze 경로의 `publish_event.py`(shim)를 실행한 뒤 출처를 출력한 결과다. 위임 패키지는 freeze, 부모는 라이브 — 계획 D2-1 K2 행 그대로이며, 형제 임포트 금지(D1(b))로 혼재가 무해함은 AST 테스트가 보장한다.
## 3. 신규 커밋 `6ad6f08` 검토 (문서 2파일, 코드 무변경)
| 변경 | 검증 |
|---|---|
| `phase1-benchmark.md:69-71` fork 표의 신규 경로 명칭을 `-m lib_py.delegation.cli` → `_delegation_py`(`python -c` + `sys.path.insert`)로 정정, `-m` 폐기 사유 각주 | `lib.sh:1960-1966` 실제 구현과 일치. fork 수 3은 `$(_delegate_py_bin)`, `$(_delegate_script)`, python으로 변함없음 — 정확 |
| `task.md:94` P3-02에 O-4 인계(freeze `lib.sh`의 `_delegate_py_bin`이 `.venv` 상향 탐색에 실패해 시스템 `python3`로 폴백; Phase 3에서 `WORKSPACE_ROOT`/`MAM_REAL_ROOT` 앵커링 필요) | 내 `25609c81` §6 O-4와 내용 일치. 전제 재확인: `mam-loop-freeze.RgjWtB/`에는 `.agents`만 있고 `.venv` 없음. 현재 freeze `lib.sh` 헬퍼를 호출하는 프로덕션 경로가 없다는 판단(래퍼는 `pick_python()`, 원샷 스크립트는 라이브 트리, `run_loop.sh`·래퍼는 헬퍼 미호출)도 Round 2에서 grep으로 확인한 그대로 |
커밋 메시지의 "The unanimous PASS was issued on 95f3e9a"는 사실과 부합한다(내 Round 2 PASS 포함). 문서 커밋을 별도로 분리해 코드 커밋의 검토 결과를 오염시키지 않은 점은 적절하다.
## 4. 전체 스위트 실행 결과
HEAD(`6ad6f08`)에서 직접 실행 (`.venv/bin/python -m pytest tests/ -q`, 백그라운드): **576 passed in 814.59s (0:13:34)**, 0 failed, 0 skipped. Round 2와 동일한 576(=510 기준선 + 57 Phase 1 + 9 Round 1 회귀). `6ad6f08`은 문서 전용이므로 수집 수 불변.
---
## 5. 결론
누적 변경분은 Round 1·2에서 세 리뷰어가 제기한 결함을 모두 수정한 `95f3e9a`와, 잔여 문서 항목을 정확히 반영한 `6ad6f08`로 구성된다. HEAD에서 핵심 검증을 재실행한 결과 회귀·린트·계약·자동완료 불변·freeze(B-13) 보존이 모두 유지되며, 본 job의 시작 이벤트 발행 자체가 freeze shim의 K2 동작을 실증했다. 재계획이 필요한 설계 결함은 없다.
[VERDICT: PASS]
@@ -0,0 +1,60 @@
# 🔍 Cross-Review — v4.1.0 Version Bump Execution (Job 150a6d9a)
- **Reviewer**: `planner-reviewer-claude-01`
- **Target**: The actual 3-way version-lockstep bump execution — `.agents/skills/lib.sh:32`, `VERSIONS.md` (header/line-24 prose/8-row matrix/changelog), and 8× `SKILL.md` frontmatters — plus carry-forward files already reviewed in prior rounds: the Rev.2 `version_upgrade_recommendation.md`, three newly-promoted durable review reports (`report-b087ad92.md`, `report-250399e4.md`, `report-80e891c1.md`), and `docs/OPENCODE_OLLAMA_GUIDE.md`.
- **Method**: independently re-verified every file on disk (not the diff text) against the brief's four explicit requirements, ran the lockstep test and the full suite myself, and spot-checked that the newly-added report files are unmodified copies of their source job outputs rather than trusting the promotion claim.
---
## 1. Requirement 1 — `MAM_VERSION` in `lib.sh:32`
```
$ grep -n "MAM_VERSION=" .agents/skills/lib.sh
32:MAM_VERSION="4.1.0"
```
Correct. Single source of truth updated.
## 2. Requirement 2 — `VERSIONS.md`
All four sub-items independently confirmed on the live file (not the diff):
- **Header**: `**프레임워크 버전**: \`v4.1.0\`` with `**최신 릴리스 일시**: 2026-08-29 (KST)` — correct version and date.
- **Line 24 prose** (the exact desync this session's earlier `ec388212`/Rev.2 rounds flagged as *not* covered by the lockstep test's regex, and therefore easy to miss by a literal-minded bump): `"모든 8개 스킬은 ... \`v4.1.0\`으로 동기화되어 배포됩니다."` — updated correctly, this time on the first pass.
- **8-row skill matrix**: `grep -n '| \`4.1.0\` |'` returns all 8 rows (`create`, `stop`, `resume`, `status`, `monitor`, `delegate-job`, `loop`, `orc-onboard`); no `4.0.0` cell remains.
- **Changelog section**: `### 🚀 \`v4.1.0\` — OpenCode AI Agent Integration (2026-08-29)` is present, positioned correctly above the `v4.0.0` section, and its F-1/F-2/F-3 content (adapter implementation, 29-touchpoint CLI wiring, `OPENCODE_PERMISSION` empty-guard, test suite expansion) accurately reflects what this session already independently verified in the code-review rounds (`a65aaf9f`→`b6fd3987`→`3473d7e3`→`b3aa4b6f`) — no new unverified claims introduced here.
## 3. Requirement 3 — 8× `SKILL.md` frontmatter
```
$ grep -rn "^version:" .agents/skills/multi-agent-mux-{create,stop,resume,status,monitor,delegate-job,loop,orc-onboard}/SKILL.md
```
All 8 read `version: 4.1.0`. `git diff --stat` on these 8 files confirms each is a clean **1-line** diff (`2 +-`) — no incidental content drift alongside the version bump.
## 4. Requirement 4 — Verification
- `pytest tests/test_version_consistency.py -q` → **2 passed** (I ran this myself, not reused from a cited report).
- `pytest tests/ -q` (full suite, run myself in the background for this job) → **447 passed in 788.39s (0:13:08)**, exit clean. Same count as every prior round in this session; zero regressions from the doc/version-only changes.
## 5. Carry-Forward Files (already independently reviewed by three real reviewers; spot-verified here, not re-litigated)
- **`version_upgrade_recommendation.md` (Rev.2)**: I already gave this `[VERDICT: PASS]` in job `b087ad92`. Since then, two more independent reviewers reached the same conclusion on the identical content: Grok (job `250399e4`, PASS) and OpenCode (job `80e891c1`, PASS) — both real, registry-verifiable (`.mam/jobs/250399e4`, `.mam/jobs/80e891c1` exist with genuine briefs/reports). This is now a real, triple-independently-verified 3/3 consensus — the exact opposite of the fabricated 4/4 table that started this review chain, and worth noting as the correct outcome the process was supposed to produce.
- **Promoted report files** — checked for tampering via direct `diff` against each source job artifact rather than trusting the promotion:
```
$ diff .agents/reports/planner-reviewer-claude-01/report-b087ad92.md .mam/jobs/b087ad92/claude-reports/report-final.md # exit 0
$ diff .agents/reports/reviewer-creator-grok-01/report-250399e4.md .mam/jobs/250399e4/grok-reports/report-final.md # exit 0
$ diff .agents/reports/reviewer-opencode-01/report-80e891c1.md .mam/jobs/80e891c1/opencode-reports/report-final.md # exit 0
```
All three are byte-identical to their originals. No selective editing when promoting to the durable path.
- **`docs/OPENCODE_OLLAMA_GUIDE.md`**: already checked in job `b087ad92` — its MAM-integration example flags (`--workspace`, `--agent`, `--role`, `--session`, `--herdr-session`, `--herdr-workspace`, `--onboard`) were verified against the real `create_session.sh`/`resume_session.sh` parsers and found accurate; unchanged since. Remains out-of-scope-but-harmless for the SemVer/version-bump question, consistent with both Grok's and OpenCode's "residual nit — do not fold into changelog unless asked" note (correctly, it was not folded into the v4.1.0 changelog entry).
## 6. Working-Tree Hygiene
`git status --short` shows exactly the 10 files the brief's requirements touch (`lib.sh`, 8× `SKILL.md`, `VERSIONS.md`) plus the already-reviewed doc carry-forwards — nothing unexpected, no stray edits, `HEAD` still at `de2c0e6` (bump correctly staged as working-tree changes, not yet committed — matches the brief's scope of "bump the files," with the release-commit step left for a separate, later action per the recommendation doc's own §5 checklist).
---
## 7. Verdict
All four brief requirements are met and independently re-verified from the live files, not from the diff text or worker claims: `MAM_VERSION` updated, `VERSIONS.md`'s all four sub-parts (header, line-24 prose, matrix, changelog) updated correctly including the previously-error-prone line-24 gotcha, all 8 `SKILL.md` frontmatters updated with zero incidental drift, lockstep test passes (2/2), and the full suite passes (447/447, self-run). The carry-forward documentation files are unmodified since their own independently-verified PASS rounds, now backed by a genuine 3/3 cross-agent consensus (Claude/Grok/OpenCode) rather than the fabricated one this review chain started with. No lint, functionality, or omission defects found. No design rework needed.
[VERDICT: PASS]
@@ -0,0 +1,46 @@
# 🔍 Cross-Review — Codex CLI Agent Backend, Post-Remediation (Job `175b653b`)
- **Reviewer**: `planner-reviewer-claude-01`
- **Target**: cumulative working-tree diff implementing `plan-e30e3123.md` Rev.2 — same codex integration I already reviewed as `[VERDICT: PASS]` in job `36148213`, now including a remediation for the blocking defect that `reviewer-creator-grok-01` (job `5bfd80b8`, NOT PASS) and `reviewer-opencode-01` (job `9cc33e22`, NOT PASS) both independently found *after* my earlier PASS.
- **Method**: Diff was truncated in the brief (221KB/3239 lines over the review limit), so per the brief's own instruction I inspected the working tree directly rather than the truncated text. I did not take any peer's verdict — including my own prior one — at face value; every claim below is re-verified against live files or live test runs in this pass.
---
## 1. What changed since my prior PASS (job `36148213`)
File-level diff stat confirms the core implementation is **untouched** since my last review: `codex.py`, `registry.py`, `lib.sh`, all 6 skill scripts, and all 7 codex-specific test additions show the same shape as before. The only substantive addition is to `.agents/reports/planner-reviewer-claude-01/plan-de667f0f.md` (+246/-9 lines) plus a one-line Status-field edit to the Codex plan.
## 2. Independently confirming the blocking defect Grok/OpenCode found (and I missed)
My own `36148213` review checked code correctness and test results but never inspected whether the archived plan-document *paths* themselves were still intact — a real gap in my prior pass. Re-derived from primary evidence, not from trusting either NOT-PASS report's narrative:
- `git show HEAD:.agents/reports/implementation_plan.md` → the tracked HEAD content is the **full 249-line OpenCode Rev.3 plan**.
- Before this fix, `.agents/reports/planner-reviewer-claude-01/plan-de667f0f.md` (the document that's supposed to be the OpenCode Rev.3 plan's *permanent, namespaced* archive per its own Rev.3 changelog text) was only a 16-line stub reading "**Durable output (updated in place)**: [.agents/reports/implementation_plan.md]" — i.e. it pointed at the shared mirror instead of containing the content itself.
- I (as Planner, in job `e30e3123`) overwrote `.agents/reports/implementation_plan.md` with the Codex plan. Since the stub was the *only* other reference, this action would have deleted the OpenCode Rev.3 plan's full text from the working tree entirely (recoverable only via `git show HEAD:...`, not from any live path) — a genuine 유실 (data-loss) defect, and, per `reviewer-opencode-01`'s report, the same recurring failure class as two earlier incidents in this repo's history (`aca0b7e8`, job `56120ad3`'s F1).
## 3. Verifying the remediation is complete and correct — not just present
- `git diff -- .agents/reports/planner-reviewer-claude-01/plan-de667f0f.md`: the file now contains a 4-line `> [!NOTE]` banner followed by the complete original OpenCode Rev.3 text.
- Byte-level check: `diff <(tail -n +5 <git-show-HEAD-copy>) <(tail -n +5 plan-de667f0f.md)` → **empty diff** — the restored body is character-for-character identical to the original tracked content, not a paraphrase or a partial/garbled restore. Line counts confirm exactly (249 original + 4-line banner = 253).
- `.agents/reports/implementation_plan.md` still holds the Codex plan (the mirror pairing for the *current* plan is preserved) — `diff` against `.agents/reports/planner-reviewer-claude-01/plan-e30e3123.md` returns empty, confirming the two stay in lockstep as intended.
- The Codex plan's Status line was updated from the stale "Plan only — no code changed in the repo" to "Implemented (v4.2.0) — full code, tests, and version lockstep present in repo" — resolving `reviewer-opencode-01`'s third (non-blocking) point.
- Swept for the same fragile pattern elsewhere: `grep -rl "Durable output (updated in place)"` finds 4 more stub-style archives (`plan-264c3b5d.md`, `plan-a33a133e.md`, `plan-28f9b565.md`, `plan-a348e91c.md`), but none of them point at `implementation_plan.md` or any other file currently targeted by an active mirror pattern — they're a pre-existing, unrelated hygiene concern, not a live risk this diff introduces or needs to fix. Noting it for awareness, not counting it against this PR.
## 4. Re-confirming the underlying codex implementation is still sound
Did not simply assume "unchanged code = still correct" — re-ran verification fresh against the current tree:
- `pytest tests/test_version_consistency.py tests/test_a4_adapter_contract.py -k "codex or version"` → 6 passed.
- Full suite, run by me just now: `pytest tests/ -q` → **462 passed, 0 failed, 819.92s (13m39s)**.
- Version lockstep re-confirmed at `4.2.0` (`lib.sh:32`, `VERSIONS.md`, all 8 `SKILL.md`).
## 5. Standing minor finding (unchanged, still non-blocking)
The dormant escaping bug I flagged in `36148213` (`tests/conftest.py`'s codex mock writes a literal `\\n` instead of a real newline in the mock rollout JSONL, ~line 658) is still present and still dormant for the same reason (`verify_artifact()`'s DB-first path never parses that file in any current test). Not fixed in this round; still recommend a one-line follow-up, still not blocking.
---
## 6. Verdict
The blocking defect that correctly earned this diff two NOT PASS votes has been remediated, and I independently verified the fix is complete, byte-faithful, and doesn't introduce any new problem — not merely that a fix file exists. The underlying codex implementation remains fully correct per a fresh full-suite run (462/462). One pre-existing minor test-fixture nit remains open as a non-blocking follow-up.
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20260924T085626Z-b8987e",
"base_sha": "59be1c89209a232059aec0c5aeecc2329929cb49",
"head_sha": "708262a598c4301c0ccc70efba5401093b4b1e30",
"tree_sha": "d601c2d01bb4c09931e5e1989e140b01d51f5b96",
"review_commit": "708262a598c4301c0ccc70efba5401093b4b1e30",
"reviewer": "planner-reviewer-claude-01",
"job_id": "1a9fbbc4",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-09-24T09:09:43Z"
}
@@ -0,0 +1,97 @@
# 🔍 Review Report — PR #37 델타 리뷰 2회차 (job `1a9fbbc4`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-09-24
- **대상 델타**: `59be1c8..708262a` (1커밋, 3파일 `+63/−7`, `git diff --check` 클린), base `main 1debc7d` (v4.7.2).
- **검증 경로**: `/var/folders/.../T/mam-review/loop-20260924T085626Z-b8987e/1`. **identity 확인**: `HEAD = 708262a5…1e30`, `HEAD^{tree} = d601c2d0…5b96` — 브리프와 일치.
- **1회차 내 판정**: PASS + H1~H5 (job `4ab12ae2`). 이번에는 H1(러너 쓰기 실패)·H3(빈 파일)·S9 이식성의 정정을 본다.
- **안전 규칙 준수**: 검증 경로·소스 워크트리·본 체크아웃(`main 1debc7d`) 모두 수정·커밋·checkout 없음. 러너 실험은 in-process 스텁, 래퍼는 `--dry-run`+`--agent human`+도달 불가 브로커, 되돌린 사본은 scratchpad. 실제 herdr·세션·`.mam`·데몬 조작 없음, push·merge·PR 상태 변경 없음.
## 결론 요약
**세 정정 모두 지적을 닫고, 1회차 판정을 뒤집을 요소는 없다.** 내가 1회차에서 H1 을 재현했던 바로 그 스크립트를 정정된 러너에 다시 돌려 "실패 제출·부분 파일 없음·래퍼 미실행"을 확인했고, 정상·exec 실패·쓰기 실패 세 경로에서 파일이 **정확히 한 번**만 지워지는 것도 확인했다. 비차단 관찰 1건(I1).
## 1. R1/H1 — 러너의 쓰기 실패 (항목 1)
`runner.py:472-491`: `mkdir`·`NamedTemporaryFile`·`write` 가 하나의 `try` 로 들어가고, `prompt_file` 은 `""` 로 초기화된 뒤 파일이 생기는 즉시(`write` 이전) 이름을 받는다. `except OSError` 는 이름이 있으면 지우고 `CompletedProcess(…, 126, "", "cannot write the prompt file under <mam_dir>: <err> (prompt N bytes)")` 를 돌려준다. exec 용 `try/finally`(`:504-516`)는 그 뒤에 따로 있어 두 블록이 겹치지 않는다.
### 실측 (검증 경로 러너 in-process)
| 경로 | 결과 |
|---|---|
| **쓰기 실패**(1회차 H1 재현 스크립트 그대로: `write` 가 `OSError(28)`) | `delegate_job` 이 **None** 을 반환(예외 없음), 로그 `cannot write the prompt file under …: [Errno 28] No space left on device (prompt 5 bytes)`, `.mam` 잔존 **0**, 래퍼 호출 **0** |
| 정상 | 래퍼 호출 시점에 파일 존재·내용 `'hello'`·권한 **0600**, `os.unlink` 호출 **1회**, 잔존 0 |
| exec 실패(`subprocess.run` 이 `OSError(2)`) | rc 126 경로, `os.unlink` 호출 **1회**, 잔존 0, 반환 None |
- 반환하는 `CompletedProcess` 는 exec 실패와 같은 rc 126 이라 기존 처리(`submit failed (exit 126)` 로그, busy 재시도 없음, id 없음 → `failed_submit_jobs` 미등록·None 반환 → 호출자 `return 1`)에 그대로 합류한다. S4c 가 `submit failed (exit 126)`·`cannot write the prompt file`·`Traceback` 부재·래퍼 미실행·잔존 없음을 한꺼번에 단언한다.
- `NamedTemporaryFile` 생성 자체가 실패하면 `prompt_file` 이 빈 채로 `except` 에 들어가 `unlink` 를 건너뛴다 — 지울 것이 없으니 맞다. `mkdir` 실패도 같은 블록이다.
## 2. H3 — 빈 `--prompt-file` 거부 (항목 2)
`multi-agent-mux-delegate-job:193` 의 `[[ -s "$PROMPT_FILE" ]]` 는 **래퍼 `submit` 의 입력**에만 걸린다. 정당한 빈 프롬프트 사용처를 막는지 실측:
| 경로 | 결과 |
|---|---|
| 래퍼 `submit --prompt-file empty.md` | `submit: --prompt-file <절대경로> is empty`, rc 1 (S1e) |
| 래퍼 `submit --prompt-file newline.md`(개행 1바이트) | 등록됨 — `-s` 는 바이트 크기 기준이라 공백만 있는 파일은 통과한다(I1) |
| 래퍼 `submit --prompt ""` | 종전대로 `submit requires --prompt or --prompt-file` 거부 — 텍스트 형식과 대칭 |
| `registry.py register --prompt-file empty.md`(직접) | 등록됨(rc 0) — 등록부는 그대로 |
| loop 형 회차의 `update --prompt-file "$job_dir/prompt.md"` | `cmd_submit` 을 거치지 않으므로 검사 밖(변경 없음) |
즉 새 검사는 "빈 텍스트를 거부하던" 기존 규칙을 파일 형식으로 확장한 것이고, 등록부·loop 회차 경로는 건드리지 않는다. 막히는 정당한 사용처는 없다.
## 3. R2/N1 — S9 의 macOS 이식성
`sys.platform == "linux"` 일 때만 `File too large` 를 단언하고, rc≠0·`prompt-shloop-*` 잔존 없음·`delegate_job_safe: cannot write the prompt file` 은 모든 플랫폼에서 단언한다. 1회차에서 내가 하네스를 직접 돌려 확인한 macOS 동작(rc 1·잔존 없음·원인 문구 출력)과 정확히 일치하는 계약이다.
## 4. 테스트 (항목 1·3)
### 4-1. 수정 없이는 실패하는가 — 확인함
검증 경로 사본에서 `runner.py` 와 래퍼만 `59be1c8` 판으로 되돌리고 `-k "s4c or s1e or s9 or s4 or s1"` 을 돌렸다:
```
2 failed, 6 passed, 1 skipped in 3.11s
FAILED test_s4c_a_prompt_file_that_cannot_be_written_is_a_failed_submit ← H1
FAILED test_s1e_an_empty_prompt_file_is_refused ← H3
```
S9 는 되돌린 사본에서도 통과한다 — `run_loop.sh` 쪽 수정은 이미 `59be1c8` 에 있었고 이번 델타는 테스트의 단언만 이식 가능하게 바꿨기 때문이다(macOS 에서 통과 = R2 정정 확인). S1/S1c/S1d/S4/S4b 는 양쪽 모두 통과(불변 조건).
### 4-2. 검증 경로에서의 실행
```
tests/test_issue36_prompt_transport.py tests/test_issue5_phase1_delegation.py tests/test_loop_cli.py
tests/test_issue14_delivery_ack.py tests/test_issue25_plan_reuse.py
→ 127 passed, 1 skipped in 215.94s failed 0 (skip = linux_only S1b)
```
1회차의 유일한 실패였던 S9 가 이 호스트에서 통과하고, 새 파일 24건(23 통과 + Linux 전용 skip 1)과 인접 계약 스위트가 모두 통과한다.
### 4-3. 격리
| 항목 | 결과 |
|---|---|
| 실제 `.mam/jobs` 전후 | **차이 0** |
| `prompt-*` 잔존(실제 `.mam` / 검증 경로 `.mam`) | **0 / 0** |
| 검증 경로 tracked 파일 | 변화 없음(HEAD `708262a`), 본 체크아웃 `main 1debc7d` |
## 5. 병합 차단 여부 (항목 3)
1회차 PASS 를 뒤집을 요소는 없다. 델타는 러너의 `try` 범위 확장(`runner.py:472-491`), 래퍼의 `-s` 한 줄(`:193`), 테스트 3건(S4c·S1e·S9 조건부 단언)뿐이고, 정정 대상만 정확히 실패→통과로 바뀌었다. 버전 락스텝 bump 부재(`4.7.2`, 오케스트레이터가 4.7.3 으로 처리 예정) 외에 **병합을 막을 결함은 없다**. 1회차 H2(loop SKILL.md 의 `MAM_DIFF_MAX_*` 의미)·H4(`$PROMPT` 후행 개행)는 이 델타 범위 밖이라 그대로 열려 있다.
| # | 비차단 관찰 | 근거 |
|---|---|---|
| I1 | `-s` 는 바이트 크기 검사라 개행·공백만 있는 프롬프트 파일은 통과한다. 텍스트 형식(`--prompt ""`)의 거부와 완전히 대칭이려면 `[[ -n "$(tr -d '[:space:]' < "$PROMPT_FILE")" ]]` 류가 필요하지만, 실무에서 그런 입력은 없다 | `multi-agent-mux-delegate-job:193`, 실측 |
## 6. 교차검증 가이드
```bash
RP=/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20260924T085626Z-b8987e/1
PY=/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.venv/bin/python
git -C "$RP" rev-parse HEAD 'HEAD^{tree}' # 708262a… / d601c2d…
# H1 재현 스크립트(1회차 §1 의 것)를 정정된 러너에 → returned None, leftover [], wrapper called 0
# 되돌린 사본: runner.py·래퍼를 59be1c8 판으로 → -k "s4c or s1e or s9 or s4 or s1" → 2 failed / 6 passed / 1 skipped
(cd "$RP" && AGENT_PYTHON_BIN="$PY" PYTHONDONTWRITEBYTECODE=1 "$PY" -m pytest -p no:cacheprovider -q --basetemp=/tmp/bt tests/test_issue36_prompt_transport.py) # 23 passed, 1 skipped
```
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261027T201245Z-63c71b",
"base_sha": "1d63e882bc1c46e9af8484647d5091b296d8fa3f",
"head_sha": "ec7f5c4e57286fb3c4238b8220f39094f4640391",
"tree_sha": "fbadb24de60ccdae684b23e2e0a41cdf23ab81eb",
"review_commit": "ec7f5c4e57286fb3c4238b8220f39094f4640391",
"reviewer": "planner-reviewer-claude-01",
"job_id": "1d2c21dc",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-27T21:06:27Z"
}
@@ -0,0 +1,132 @@
# PR #75 후속 라운드 리뷰 — 1d63e88..ec7f5c4 (review round 5)
리뷰어: planner-reviewer-claude-01 (claude) · job 1d2c21dc
## 0. 리뷰 경로 확인
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261027T201245Z-63c71b/1`
- HEAD `ec7f5c4e57286fb3c4238b8220f39094f4640391`, tree `fbadb24de60ccdae684b23e2e0a41cdf23ab81eb` 로 [리뷰 identity] 와 같다.
- `git status --porcelain --ignored` 는 비어 있다. `.mam` 은 없다.
- 리뷰 전후로 확인했다. 본 체크아웃 main 은 `0e1e2e8` 그대로다.
- 범위: 1d63e88..HEAD 의 커밋 `ec7f5c4` 하나다.
- 바뀐 파일: `.agents/skills/lib.sh`(+7/−1), `tests/test_issue72_update.py`(+32/−3)
- 브리프가 정한 범위(R2 와 테스트의 `pkill` 제거) 밖은 건드리지 않았다.
## 1. R2 — legacy `start_watchdog` 의 프로세스 그룹 분리
### 1.1 코드 (`lib.sh:2297-2310`)
- 모니터를 띄우는 `nohup bash … &` 직전에 `set -m` 을 켠다.
- 켜기 전에 호출자의 `$-` 에 `m` 이 있었는지 `had_m` 에 기억한다.
- `pid=$!` 를 읽은 뒤, 원래 꺼져 있었으면 `set +m` 으로 되돌린다.
- job control 이 켜진 상태에서 띄운 백그라운드 잡은 자기 프로세스 그룹의 리더가 된다(PGID = PID). 그래서 다음 효과가 있다.
- `$!` 는 그대로 그 PID 다. nohup 과 bash 가 exec 해도 PID 는 바뀌지 않는다.
- 따라서 정확한 PID 보고(`echo "$pid"`, `:2314-2316`)와 `mam_monitor_started` 확인이 바뀌지 않는다.
- 다음 기존 동작은 바뀌지 않았다.
- 중복 방지(`_monitor_pids`, `:2291`)
- `MAM_NO_SUBSCRIBER_DAEMON=1` 분기(`:2295-2296`)
- stdin `/dev/null`, 로그 append(`>> "$log_file"`), 작업 공간 cwd, `--idle-timeout 0`
- 바뀐 것은 분기 안의 세 줄뿐이다.
- 호출하는 곳은 모두 `$(…)` 안이다. 그래서 `set -m` 은 그 서브셸 안에서만 잠깐 켜진다.
- `update.sh:106`, `post_update.sh:41`, `install_phase.sh:64`
- `create_session.sh:748`, `resume_session.sh:162`
### 1.2 이 Mac 에서 직접 확인 (`/bin/bash` 3.2, tty 없음, `set -euo pipefail`)
- 같은 모양의 함수를 스크래치 스크립트로 만들어 돌렸다.
- 결과 1: `$(f)` 안에서 띄운 자식의 PGID 는 자기 PID 와 같다(53727 = 53727). 호출자의 PGID(53714)와 다르다.
- 결과 2: 직접 호출한 경우도 마찬가지다.
- 결과 3: 호출 뒤 `$-` 는 `ehuB` 로 그대로다. 곧 `m` 이 남지 않는다.
- 결과 4: "no job control", "[1] PID", "Done" 같은 잡 메시지가 stdout 에도 stderr 에도 나오지 않았다. 그래서 `$(…)` 로 받는 PID 출력이 오염되지 않는다.
- **고치기 전 코드에서 실패하는지도 확인했다.**
- 방법: `git archive HEAD` 로 TMPDIR 에 사본을 풀었다. 그 사본의 `lib.sh` 만 1d63e88 판으로 바꿨다.
- 그 사본에서 `-k test_every_restart` 를 실행했다.
- 결과: **mode=0 의 3개(installed, killed, rolled-back)가 `left in the caller's group` 로 실패했다. mode=1 의 3개는 통과했다(3 failed, 3 passed).**
- 즉 새 assertion(`tests/test_issue72_update.py:723-724`)이 R2 를 실제로 잡는다. 수정 뒤 6개가 모두 통과한다(§3).
- 사본은 확인 뒤 지웠고, 남은 프로세스도 없다.
- 세 경로와 두 모드: 정상 설치, 정지 시간 초과 뒤 복원, rollback 뒤 복원을 mode 0·1 로 돌리는 6 조합이 모두 같은 함수를 지나고, 모두 통과한다.
- rollback 경로는 되돌린 트리의 `lib.sh` 를 쓴다. 테스트 상자에서는 그 트리가 이 버전이다.
### 1.3 python 경로와의 차이 (비차단, 참고)
- 두 경로가 분리하는 정도가 다르다.
- python 경로(`daemon.py:95`): `start_new_session=True` 로 새 **세션**을 만든다. 그래서 제어 터미널에서도 떨어진다.
- legacy 경로: 새 **프로세스 그룹**만 만든다. 세션과 제어 터미널은 호출자와 같다.
- 결정 2 의 요구("부른 쪽 프로세스 그룹에서 분리")는 이것으로 충족된다.
- 프로세스 그룹 신호(테스트 러너·timeout 래퍼의 killpg, 터미널의 SIGINT)는 이제 모니터에 닿지 않는다. 터미널 신호는 전경 그룹에만 가는데, 모니터는 배경 그룹이다.
- 터미널이 닫힐 때의 SIGHUP 은 nohup 이 무시한다.
- 배경 그룹이 tty 에 읽고 쓸 때 생기는 SIGTTIN/SIGTTOU 도 없다. stdin 은 `/dev/null` 이고 출력은 로그 파일로 간다.
- `lib.sh:246-253`(shim 서버 기동)은 같은 문제에 `start_new_session=True` 를 쓰는 관례를 적어 두었다. legacy 경로만 `set -m` 을 쓴다.
- 브리프가 "가장 작은 수정" 을 요구했고, legacy 경로는 opt-in 이므로 결함으로 보지 않는다.
## 2. 테스트의 `pkill` 제거 (`tests/test_issue72_update.py:184-194`, `:218-240`)
### 2.1 새 teardown 이 정리하는 것
- 패턴 kill 이 없어졌다. `tests/test_issue72_*.py` 전체에 `pkill`·`killall` 이 남아 있지 않다(grep 으로 확인).
- 대신 다음 순서로 정리한다.
1. 테스트가 `Box.helper`(`:132-135`, `start_new_session=True`)로 띄우고 `b.helpers` 에 기록한 프로세스의 그룹을 `killpg` 하고 `wait` 한다.
2. 이 테스트의 작업 공간 `ws` 에 대해 `bash <ws>/…/reconcile.sh --subscribe` 형태로 정확히 맞는 모니터(`_exact_monitor_pids`)와 그 자손(`_descendants`, `pgrep -P` 재귀)만 SIGKILL 한다.
- 남은 프로세스 확인: 명령줄에 `ws` 가 들어 있는 살아 있는 프로세스가 10초 안에 없어지지 않으면 이름을 적어 실패한다(`_processes_naming`, `:236-240`).
- `ws` 는 basetemp 아래의 테스트별 경로다. 그래서 다른 작업 공간의 프로세스와 겹치지 않는다.
### 2.2 남은 프로세스 확인이 약해지지 않았는지
- 예전 `pkill -KILL -f <ws>` 는 `ws` 를 명령줄에 가진 것을 **조용히 죽였을** 뿐이다. 남은 프로세스를 확인하지는 않았다.
- 새 방식은 정확히 고른 것만 죽인다. 나머지 가운데 `ws` 를 가진 프로세스가 남으면 **실패로 드러낸다**.
- 그래서 확인은 더 강해졌다.
- 대가가 하나 있다. 그런 프로세스가 생기면 정리되지 않고 남는다. 다만 이름이 실패 메시지에 나오므로 사람이 정리할 수 있다.
- `ws` 를 명령줄에 갖지 않은 손자(예: stub 모니터의 `sleep 120`)는 두 방식 모두 패턴으로는 못 찾는다.
- 새 방식은 모니터의 자손으로 찾아서 정리한다. 따라서 이 부분도 약해지지 않았다.
- 이번 실행에서 teardown 실패는 없었다. 실행 뒤 `ps` 로 봐도 테스트가 남긴 프로세스가 없다(§3).
## 3. 실행한 테스트 (이 Mac: macOS, `/bin/bash` 3.2, `/usr/bin/python3` 3.9.6)
```
cd <검증 경로>
env -u HERDR_SOCKET_PATH -u HERDR_PANE_ID -u HERDR_TAB_ID -u HERDR_WORKSPACE_ID -u HERDR_SESSION_NAME \
-u HERDR_SESSION -u WORKSPACE_ROOT -u MAM_ENV_FILE -u MAM_JOBS_DIR -u DELEGATE_JOB_LOGS_DIR \
PYTHONDONTWRITEBYTECODE=1 /Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.venv/bin/python \
-m pytest -p no:cacheprovider --basetemp="$TMPDIR/claude-j1d2c-bt" -q -rfs \
tests/test_issue72_update.py tests/test_issue19_subscriber_daemon_lifecycle.py \
tests/test_issue5_phase1_delegation.py
```
- 결과: **132 passed, 0 failed, 0 skipped** (191 s)
- `test_every_restart_starts_a_real_monitor_in_both_delegation_modes` 의 6 조합이 이 안에 들어 있다.
- `test_issue19`·`test_issue5_phase1` 의 watchdog 시험(중복 방지, `MAM_NO_SUBSCRIBER_DAEMON`, PID 보고, legacy·python 동등성)이 모두 통과한다.
- 고치기 전 대조 실행: TMPDIR 사본, `-k test_every_restart` → 3 failed(mode=0), 3 passed(mode=1). 자세한 것은 §1.2.
- 테스트 뒤 남은 프로세스: 테스트가 띄운 `reconcile.sh`, stub monitor, mock herdr, 구독자는 없다. 남은 것은 원래 있던 셋이다.
- 본 체크아웃 모니터 3714
- 이번 루프 7552
- 이번 잡을 디스패치할 때 띄운 job_subscriber 53086
## 4. 발견 사항
### 차단
- 없음.
### 비차단
- **N8 (이월, R2 에도 해당).** rollback 뒤 재기동은 결정 2 에 따라 **되돌린 옛 트리의** `start_watchdog` 을 쓴다.
- 그래서 실제로 이 PR 이전 버전으로 되돌리면, `MAM_DELEGATION_PY=0` 에서는 옛 `nohup … &` 그대로라 호출자 그룹에 남는다.
- 이 PR 이후 버전 사이의 rollback 에서는 해결된다.
- 결정 2 가 정한 방식("되돌린 트리의 함수")에서 생기는 한계라 결함으로 보지 않는다.
- **1.3 의 세션 차이.** legacy 경로는 프로세스 그룹만 분리하고, python 경로는 세션까지 분리한다. 결정 요구는 충족한다.
- N5·N6·N1·N3·N4 는 이번 범위 밖이라 그대로다.
## 5. 사용자 확인 필요
- N8: rollback 대상이 이 PR 이전 버전이고 `MAM_DELEGATION_PY=0` 인 경우를 받아들일지.
- 받아들이지 않는다면 결정 2 의 "되돌린 트리의 start_watchdog" 대신 `install_phase.sh` 복사본 쪽에서 분리해 띄우도록 결정을 바꿔야 한다.
- 이전 라운드에서 넘어온 N2, 그리고 결정 8 문구 보강 건은 그대로다.
## 6. 결론
- R2 는 정상 설치, 시간 초과 복원, rollback 복원의 세 경로와 두 모드 모두에서 해결됐다.
- 고치기 전 코드에서 mode=0 이 실패하고, 고친 뒤 6개가 모두 통과하는 것을 이 Mac 에서 확인했다.
- 분리 방식(`set -m`)은 중복 방지, opt-out, PID 보고, 로그를 바꾸지 않는다. bash 3.2 에서 잡 메시지 없이 동작한다.
- 테스트의 패턴 kill 은 기록한 PID 와 정확히 맞는 모니터·자손 정리로 바뀌었다. 남은 프로세스 확인은 오히려 강해졌다.
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261019T015801Z-05463c",
"base_sha": "1d7b7dab58a10fe86fd747b7290d47674ca93230",
"head_sha": "6a37c0019baa31ee28b32a086e57b4c8239413c4",
"tree_sha": "87013e7ef7f5239f1bf6ea38a2cbda214257be3c",
"review_commit": "6a37c0019baa31ee28b32a086e57b4c8239413c4",
"reviewer": "planner-reviewer-claude-01",
"job_id": "1fb2cefa",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-19T02:37:22Z"
}
@@ -0,0 +1,71 @@
# PR #62 리뷰 2회차 — Issue #60 Linux 확인 후속 (job 1fb2cefa)
- 리뷰어: planner-reviewer-claude-01
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261019T015801Z-05463c/1`
- identity: HEAD `6a37c0019baa31ee28b32a086e57b4c8239413c4`, tree `87013e7ef7f5239f1bf6ea38a2cbda214257be3c` 가 일치한다. 작업 트리는 clean 이고 `.mam` 은 없다.
- 범위: base `1d7b7da`..head 9커밋. 판정은 base..head 전체에 대한 것이다. 1회차 이후 바뀐 것은 6a37c00 하나이고, `opencode.py`·`status.sh`·`reconcile.sh`·`test_issue60_linux_fixes.py` 4개 파일만 바뀌었다.
- 1회차(@6a4e385)의 확인은 6a37c00 이 건드리지 않은 코드라 그대로 유효하다. 1회차에 확인한 것: 임시 DB 에서 `_ro_connect` 세 갈래, `_DB_PATHS` 키, `auth-ok` CLI, stop 문구.
- 환경: macOS, Python 3.9.6, sqlite 3.51.0. 실제 opencode 데이터는 `ls`·`grep -c`·`ps`·`lsof` 로만 봤다.
## 결론
1회차의 공통 차단(B1)과 codex·agy 지적이 모두 해결됐고, 새 회귀는 찾지 못했다. base..head 전체를 병합 가능으로 판단한다.
## 1회차 지적별 확인
**B1 (clean 상태 5개가 macOS 에서 실패) — 해결.**
- `make("clean")` 이 close 뒤 남은 `-wal`·`-shm` 을 지운다(`tests/test_issue60_linux_fixes.py:158-162`). 1회차 사본에서 내가 검증한 수정과 같다.
- 검증 경로에서 이 모듈이 모두 통과한다(아래 실행 결과).
- 뮤테이션 i1(immutable 분기를 `mode=ro` 로)이 이제 이 Mac 에서 5 failed 로 잡힌다. 1회차에는 fixture 가 먼저 실패해서 이 뮤테이션이 가려졌었다.
**안내 문구 패턴이 사용자가 친 `Ask anything…` 를 지움(codex) — 해결.**
- 패턴이 `Ask anything(?:…|\.\.\.) "[^"]*"?` 가 되어 따옴표 예시가 필수다(`opencode.py:80`).
- 두 fixture 에 넣어 직접 확인한 결과:
- `Ask anything…`, `Ask anything...` 는 친 그대로 읽힌다.
- 홈 화면 원본, 잘린 예시, `Ask anything… "` 는 빈 입력으로 읽힌다.
- 회귀 테스트 2개가 추가됐다(`:84-85`). 뮤테이션 p1(예시를 다시 선택 사항으로)은 4 failed 로 잡힌다.
**auth_ok 가 실행 불가한 `~/.opencode/bin/opencode` 도 인정(codex) — 해결.**
- 이제 `isfile and access(X_OK)` 로 본다(`opencode.py:322-323`).
- 권한 644 파일과 디렉터리는 모두 False 로 고정됐다(`test_a_home_install_that_cannot_run_is_not_enough`). 뮤테이션 a1(`exists` 로 되돌림)은 1 failed 로 잡힌다.
- `shutil.which` 가 이미 실행 가능 여부를 보므로 PATH 쪽은 그대로다.
**status.sh·reconcile.sh 의 `sqlite3.connect(odb)`(agy) — 해결.**
- status 의 opencode 두 블록(`status.sh:115-117`, `:316-318`)과 reconcile drift C(`reconcile.sh:953-955`)가 `_ro_connect` 를 쓴다.
- 두 스크립트는 lib_py 를 이미 import 하는 경로에서 돌기 때문에 import 가 된다(status 는 `env_python`/PYTHONPATH, reconcile 은 `env_python`).
- status 블록에서 `import sqlite3` 를 지웠지만 영향이 없다. 같은 함수의 다른 블록(hermes `:90`, codex `:132`)은 각자 `import sqlite3` 를 한다.
- 행동 확인: git archive 사본에 임시 e2e 를 넣었다. 순서는 이렇다.
1. mam_sandbox+mock 에서 create → 자식 세션 추가 → `journal_mode=wal` → 사이드카 삭제(Linux 의 닫힌 상태)
2. `reconcile.sh --once --emit-diff` → `status.sh --json` 과 plain status
- 결과(head): rc 는 모두 0. 부모 id 로 고정됐고 `resume_state == "yes"` 이다. DB 디렉터리는 실행 전후 모두 `['opencode.db']` 였다.
- 대조(두 스크립트를 `sqlite3.connect(odb)` 로 되돌린 사본): reconcile 뒤 `opencode.db-shm`·`opencode.db-wal` 이 생겨 같은 테스트가 실패했다.
- 참고: mock opencode 가 만드는 DB 는 WAL 모드가 아니다. 그래서 WAL 로 바꾸지 않으면 이 차이가 드러나지 않는다.
## 테스트 실행 (검증 경로)
- 조건: `env -i`, 임시 HOME, `XDG_DATA_HOME=<scratchpad>`, basetemp 는 scratchpad, `-p no:cacheprovider`, `PYTHONDONTWRITEBYTECODE=1`.
- 대상 12개 모듈: issue60_linux_fixes, issue60_opencode_v2, a4, tier1, tier2, issue31, issue55, issue57, issue21_worktree_prereqs, issue50_dispatch, issue30_stall_watch, c1_tui_readiness.
- 결과: **463 passed, 2 skipped, 실패 0**, 16분.
- skip 1: `/proc` 전용 테스트.
- skip 2: PATH 에 opencode 가 없어 건너뛴 실바이너리 계약 테스트(1회차·이전 이슈에서 따로 확인함).
- 부작용 확인:
- scratchpad XDG 디렉터리는 실행 뒤에도 비어 있었다.
- 실제 `~/.local/share/opencode` 의 목록은 전후가 같았다.
- 실제 log 의 `debug` 줄 수는 2 → 2 였다.
- 남은 opencode 프로세스는 사용자 서비스 하나뿐이다(pid 23630, 시작 08:13, 이 잡 이전).
- #55 가드 오탐은 없었다.
- 린트:
- `git diff --check 1d7b7da..HEAD` 는 깨끗하다.
- 바뀐 Python 은 3.9 로 파싱된다.
- `status.sh`·`reconcile.sh` 는 `/bin/bash -n`(3.2)을 통과한다.
## 비차단
- **N1.** 새 `test_status_and_reconcile_open_the_database_read_only` 는 소스 문자열만 센다. `sqlite3.connect(odb, timeout=…)` 같은 변형은 지나간다. 위의 임시 e2e(WAL DB, 사이드카 없음 → reconcile·status → 목록 불변)를 tier2 opencode e2e 에 붙이면 행동으로 고정할 수 있다.
- **N2.** 1회차 비차단은 의도된 완화로 그대로 남아 있다(브리프에도 기록됨):
- immutable 경쟁 창(ms 수준)
- `_DB_PATHS` 의 프로세스 수명 캐시
- create 사전 검사의 완화
- **N3.** 아주 좁은 화면에서 예시의 여는 따옴표까지 잘리면 `Ask anything…` 만 남는다. 이때는 친 초안으로 읽힌다(안전한 쪽). 실제 캡처로는 확인하지 않았다.
[VERDICT: PASS]
@@ -0,0 +1,51 @@
# 리뷰 리포트 — PR #59 (Issue #31, claude purge 잔여물) / job 207c65b8
- 리뷰어: planner-reviewer-claude-01 (Opus 5.5)
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261016T003524Z-a51548/1`
- identity: HEAD `6f4f40a4adb2115d5997dffd31fb6473f05cab68`, tree `f4d9422ad0c1d616b5f37065f3e96b34c28f78d8` — 일치. 트리 clean, `.mam` 없음(테스트 실행 후에도 동일).
- 범위: base 26e2c43 .. head 6f4f40a (13 커밋, 12 파일)
## 요약
설계와 대부분의 구현은 이 Mac에서 맞게 동작한다. 실제 `~/.claude` 구조, BSD `ps -o lstart=`, `/tmp → /private/tmp` 스크래치패드 레이아웃이 어댑터 가정과 일치하고, 다른 세션·공유 파일·심볼릭 링크 너머는 지우지 않았다. 다만 **삭제 범위 가드(`_plausible_id`)가 UUID가 아닌 id를 거르지 못해, id `memory` 로 purge 하면 `projects/<key>/memory/`(Claude Code 자동 메모리 디렉터리)가 통째로 지워진다**(F1). 이 PR이 `<id>.jsonl` 삭제에서 `<id>` 디렉터리 rmtree 로 범위를 넓히면서 생긴 회귀이고, 브리프 중점 항목("잘못된 uuid 거부")에 해당하므로 NOT PASS 로 판정한다. 수정은 한 줄 수준이다.
## 차단 결함
### F1. 비-UUID id `memory` 가 자동 메모리 디렉터리를 지운다
- 위치: `.agents/skills/lib_py/agents/base.py:89-92` (`_plausible_id`: 빈 문자열·점만·`/`·`..`·`*` 만 거부), `.agents/skills/lib_py/agents/adapters/claude.py:262-268` (`base = projects/<key>/<uuid>`, 디렉터리면 `_remove` → `shutil.rmtree`), `claude.py:287-289` (`has_artifacts` 가 같은 목록을 써서 `purge auto` 도 claude 로 해석).
- 실제 이 Mac 의 `~/.claude/projects/<key>/` 에는 세션 디렉터리와 나란히 `memory/` 가 있다(읽기만 확인: `projects/-Users-godopu16-PuKi-laa-canary-projects-multi-agent-mux/memory/`). 세션 id 와 같은 층에 있는 유일한 비-UUID 이름이다.
- 재현 1(어댑터 직접, 샌드박스 HOME/CLAUDE_PROJECT_DIR/CLAUDE_CODE_TMPDIR/TMPDIR, `/usr/bin/python3` 3.9.6):
`has_artifacts("memory") → True`, `purge_artifacts("memory") → [.../projects/<key>/memory, .../file-history/memory]`, `MEMORY.md survives: False`.
- 재현 2(CLI): `python -m lib_py.agents purge claude memory <ws>` → 이 호스트에서는 다른 프로세스 29개의 argv 에 "memory" 가 들어 있어 우연히 in-use(rc 4)로 거부됐다. argv 에 "memory" 가 없는 호스트를 흉내 내려고 `ps` 출력에서 그 줄만 거르는 스텁을 PATH 앞에 두면 rc 0, `"purged": [".../projects/<key>/memory"]`, `memory survives: False`.
(스크립트: `/private/tmp/claude-501/-Users-godopu16-PuKi-laa-canary-projects-multi-agent-mux/8cb38cbf-0d61-4d78-8c7e-065e409ce13d/scratchpad/j207/probe_mem.py`)
- 도달 경로: 스킬 진입점은 안전하다 — `orc_onboard.sh:88-95` 은 정규식으로 UUID 를 강제하고, `stop_session.sh` 의 `PURGE_UUID` 는 `find_workspace_uuid` 가 `<id>.jsonl` 의 sessionId 일치로 검증한 값이다. 위험한 경로는 직접 쓰는 `lib_py.agents purge`/어댑터 API(VERSIONS.md 에 문서화)다. 그러나 이 PR 이전에는 같은 입력이 존재하지 않는 `memory.jsonl` 만 겨냥해 무해했다. 지워지는 것은 복구할 수 없는 사용자 메모리이고, 테스트(`tests/test_issue31_purge_residual.py:242` 의 `bad` 목록)도 이 경우를 다루지 않는다.
- 제안: claude 어댑터의 `_owned_paths`/`residual_artifacts`(또는 `purge_artifacts`·`has_artifacts` 입구)에서 정규 UUID(`[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}`, 대소문자 무시)만 받게 하고, `bad` 목록에 `"memory"` 와 UUID 가 아닌 평범한 이름을 추가하는 회귀 테스트. 다른 어댑터는 이름 스캔(`scan_names`)·보고만 하므로 공용 `_plausible_id` 는 그대로 둬도 된다.
## 확인한 사항 (정상)
1. **BSD `ps -o lstart=`**: 이 Mac 출력은 `Fri Oct 16 08:25:14 2026` (LC_ALL=C 와 기본 로캘 동일). `" ".join(out.split())` + `%a %b %d %H:%M:%S %Y` 로 파싱된다. 실제 살아 있는 claude 4개의 `sessions/<pid>.json` 에서 `startedAt − lstart` = 0.69 / 1.14 / 1.93 / 2.43 s → 모두 live 판정(`lstart <= startedAt+2`). 샌드박스 `sleep` 프로세스로: 방금 쓴 startedAt → in-use rc 4(`--wait 2` 로 2.2 s 대기 후), purge CLI rc 4, jsonl 보존; 프로세스 종료 후 rc 0. startedAt 을 1시간 전으로 둔(pid 재사용) 경우 → free, 그 세션 파일만 삭제. `ps` 실패·빈 출력·파싱 실패·`startedAt` 없음 → live(`claude.py:66-74`).
2. **tmp 루트**: TMPDIR=`/var/folders/.../T/` 아래에는 `claude-501` 이 없고, 실제 스크래치패드는 `/private/tmp/claude-501/<key>/<uuid>/{scratchpad,tasks}` 다. 후보에 항상 `/tmp/claude-<uid>` 가 들어가고(`claude.py:41`) realpath 로 `/private/tmp` 와 중복 제거된다. `<key>` 는 계산하지 않고 루트 아래 모든 키를 나열해 `<k>/<uuid>` 만 고르므로 키 규칙 차이에 영향받지 않는다. 샌드박스에서 CLAUDE_CODE_TMPDIR·TMPDIR 양쪽 루트의 `<uuid>` 만 지워졌다.
3. **실제 `~/.claude` 구조**(읽기만): `sessions/<pid>.json`(int `pid`, ms `startedAt`, `sessionId`) + `<pid>.<64hex>.key`, `jobs/<8hex>/state.json`(sessionId[:8] = 디렉터리명), `file-history/<uuid>/`, `session-env/<uuid>/`, `projects/<key>/<uuid>/{tool-results,…}` — 어댑터 가정과 일치.
4. **삭제 범위**(샌드박스, `/usr/bin/python3`): 같은 jobs 접두사의 다른 세션, 다른 세션의 sessions json·key, 같은 pid 접두사이지만 64hex 가 아닌 `.key`, `history.jsonl`, 다른 uuid 의 file-history·jsonl·스크래치패드가 모두 보존됐다. `session-env/<U>/link → 외부`, 스크래치패드 안의 `linkout → 외부` 심볼릭 링크는 링크만 지워지고 대상 파일은 남았다. 재실행 → rc 5(남은 것 없음). `""`/`.`/`..`/`...`/`a/b`/`*`/`../x` → 아무것도 지우지 않음(rc 1 또는 5).
5. **stop exit 4 계약**: 게이트(`stop_session.sh:285-300`)는 레지스트리 잠금 밖, YAML 쓰기 전에 실행되고 0 이외는 모두 exit 4 + cancelled 이벤트. `_delegate_py_bin` 가 `/usr/bin/python3` 로 떨어져도 `-m lib_py.agents in-use` 는 paho 없이 동작한다(직접 확인). bash 3.2 `-n` 통과, `inuse_rc=0; … || inuse_rc=$?` 는 `set -u` 에서 안전.
6. **residual 보고**: purge 후 `residual_artifacts` 가 빈 목록이면 `residual: none (agent: …)`. 실제 `~/.claude` 에 대한 이름 스캔(읽기 전용, 가짜 uuid)은 0.02 s.
7. **Python 3.9 / bash 3.2**: 변경된 .py 8개 모두 `feature_version=(3,9)` 로 파싱되고, 프로브는 전부 `/usr/bin/python3` 3.9.6 으로 실행됐다(registry 가 모든 어댑터를 import). `lib.sh`·`stop_session.sh` 는 `/bin/bash` 3.2.57 `-n` 통과.
8. **문서·skill_code_blocks.json**: stop SKILL.md 의 "purge 는 행을 지운다"·exit 4·삭제 목록이 코드와 맞고, `test_issue42_skill_blocks.py` 통과(sha·passthrough 라인 갱신 정합).
9. **codex·grok·opencode residual**: 이름 스캔 + `mode=ro` SQLite 조회만 하므로 쓰기 없음.
## 테스트
- 검증 경로에서 `env -i …`(HERDR_*·WORKSPACE_ROOT·MAM_*·DELEGATE_JOB_LOGS_DIR·CLAUDE_CONFIG_DIR 미설정), `--basetemp` 는 스크래치패드, `PYTHONDONTWRITEBYTECODE=1 -p no:cacheprovider`:
`test_issue31_purge_residual, test_issue10_13_purge, test_a4_adapter_contract, test_issue42_skill_blocks, test_issue55_agent_homes, test_orc_onboard, test_uuid_target` → **188 passed, 1 skipped** (276 s). 실행 후 트리 clean.
- 사전 수정 대조: `git archive HEAD` 복사본에서 제품 파일 8개를 base 26e2c43 로 되돌리고 `test_issue31_purge_residual.py` 실행 → **24 failed, 8 passed**. 통과한 8개는 "다른 세션을 건드리지 않음"·"잘못된 uuid 거부"처럼 이전 코드에서도 성립하는 안전성 테스트로, 기대한 결과다. stop 게이트 테스트(`test_stop_purge_refuses_while_the_claude_process_lives`)와 pid 재사용 테스트도 사전 코드에서 실패한다.
## 비차단 메모
- N1. DST: `time.mktime(time.strptime(...))` 는 `tm_isdst=-1` 이라 서머타임이 끝나는 겹치는 1시간에는 lstart 가 1시간 늦게 해석될 수 있고, 그러면 살아 있는 세션을 stale 로 볼 수 있다(fail-open). 이 Mac 은 KST(서머타임 없음)라 영향 없음. 실제 세션 파일에 `procStart`(UTC 문자열, `pidDomain: "darwin"`)가 있으니 이를 쓰거나 비교를 UTC 로 하는 것도 고려할 만하다.
- N2. stop 의 exit 4 메시지(`stop_session.sh:296`)는 `~/.claude/sessions/` 만 가리킨다. CLAUDE_CONFIG_DIR 을 쓰면 위치가 다르고, argv 에 uuid 를 담은 아무 프로세스(에디터·grep·위임 래퍼)도 거부 사유가 된다. orc_onboard SKILL.md 처럼 `ps -axww | grep <uuid>` 안내를 함께 두면 좋다.
- N3. SKILL.md exit 4 행의 "(nothing was changed)" — 프로세스 게이트는 herdr kill 이후에 돌므로 세션은 이미 내려가 있을 수 있다(레코드는 그대로). 기존 herdr 게이트 문구와 같은 뉘앙스이지만 "records preserved" 가 더 정확하다.
- N4. stop 이 이제 모든 에이전트에 in-use 게이트를 적용한다. agy 처럼 CLI 종료 뒤에도 다른 프로세스가 DB/락을 열어 두는 구성이면 이전에는 purge 되던 것이 exit 4 로 바뀐다. 의도된 fail-closed 이지만 실제 agy 로는 확인하지 못했다(브리프상 실제 에이전트 실행 금지).
- N5. 테스트는 하드코딩된 `/tmp/claude-<uid>` 후보를 격리하지 못한다(실제 `/private/tmp/claude-501` 을 나열). 무작위 uuid 라 실제로 지워지는 것은 없지만, `_tmp_roots` 를 테스트에서 패치할 수 있게 하면 더 안전하다.
[VERDICT: NOT PASS]
@@ -0,0 +1,48 @@
# 🔍 Cross-Code Review — Complete Cline Removal Implementation (Job 20d45d12)
- **Reviewer**: `planner-reviewer-claude-01`
- **Target diff**: implementation of `plan-264c3b5d.md` Rev.2 — 30 files (adapter deletion, registry, 4 `lib_py` modules, `lib.sh`, 9 skill scripts, 6 test files, 3 docs) plus 1 out-of-scope test-flakiness fix.
- **Method**: read every changed file's live post-diff state directly (not diff text alone), independently verified the two highest-risk items from my own Rev.2 plan (the `reconcile.sh` drift-C block boundary and the tiered-readiness/modal test retargeting), syntax-checked all 10 modified shell scripts, grepped the entire diff for any surviving `cline` reference, and ran the full test suite myself.
---
## 1. Fidelity to Rev.2 Plan — Verified, Not Assumed
I did not trust the implementation's own claim of compliance — I re-checked the specific corrections `creator-agy-01`'s challenge required in Rev.2 against the live diff:
- **Tiered-readiness tests (Rev.2's core correction)**: `test_c3_strong_token_and_hint_token_readiness_succeeds` now mocks `_delegate_py_bin`/`python -m lib_py.agents facts` to return a synthetic `mocktiered` agent with genuinely distinct `MAM_STRONG_READY_TOKENS='MockApp'` / `MAM_WEAK_READY_TOKENS='Use arrow keys'`, keeping the real facts-bridge call path exercised rather than bypassing it with raw env-var pre-injection — exactly what Rev.2 required. The other C4–C7 tests that were already using pre-set env vars (not resolving through the bridge in the original cline-based version either) were correctly left as simple session-name swaps, since they were never testing the bridge to begin with.
- **`test_c8b` (modal test)**: retargeted fully to `claude`, using `'Try the new fullscreen renderer?'` as the injected screen text and `MAM_MODAL_TOKENS='Try the new fullscreen renderer\?'`, with session name `my-project-worker-claude-01` — this is claude's actual, verified `modal_tokens` value, exactly matching Rev.2's requirement to preserve the full session-name-resolution → `facts claude` → dialog-block path, not a synthetic placeholder.
- **New facts-bridge round-trip assertion**: `test_a4_adapter_contract.py::test_adapter_required_properties` gained `assert adapter.strong_ready_tokens == adapter.ready_tokens` / `assert adapter.weak_ready_tokens == ''` for all 4 remaining agents, and `test_facts_bridge_eval_contract` now additionally asserts `STRONG=`/`WEAK=` come through the real bash `eval` of the bridge's output — this is actually a **stronger** implementation than what I asked for (I only required the property-level check; this round-trips through the real subprocess + bash eval too).
- **`docs/NEW_AGENT_INTEGRATION_GUIDE.md`**: all 5 sites I flagged in Rev.2 (diagram, `_ADAPTERS` sample, `lib.sh` kind-mapping sample, binary-tuple sample, test-assertion sample) were updated — the architecture diagram box-drawing was even correctly realigned (`┬` connector fixed) after swapping `ClineAgentAdapter` for `GrokAgentAdapter` in that slot, not just text-deleted.
## 2. Independent Verification of the Highest-Risk Edit
I flagged the `reconcile.sh` cline drift-C block deletion as the highest-risk single edit in my own plan. Checked the live file directly: the block is cleanly gone, the preceding `hermes` drift-C block and the following `result = {...}` return statement are both intact and correctly adjacent with no orphaned fragments. Extracted and `ast.parse()`'d the actual `RECON_SRC` heredoc (lines 320–794, not the other heredoc earlier in the file, which I made sure to distinguish) — valid Python. `bash -n` on the whole file — valid.
## 3. Completeness Check
`git diff | grep -n "^+.*[Cc]line"` (every added line, across the entire diff) returns **zero matches** — no newly-written line anywhere in this diff still references cline. Cross-checked a full-repo `cline` grep against `git status`: every remaining match is either inside `.agents/reports/**` (untouched, correct) or inside changelog-style docs (`VERSIONS.md`, `IMPROVEMENTS.md`) describing past releases in the past tense (correctly left alone, consistent with my plan's "spot-check, don't blanket-edit" guidance).
## 4. Findings
### 4.1 Minor: `MULTI_AGENT_RULES.md`/`.ko.md` line 21 slightly stale (Low, not blocking)
`"Newly spawned agents (e.g., antigravity, claude, cline, hermes) act as Team Leaders..."` — an illustrative `e.g.` list, not a hard enumeration, but it does still name cline as a live example post-removal. Low severity since the sentence's substance is about the *role concept*, not a supported-agent contract, and this file wasn't in either of our removal plans' scope. Worth a follow-up touch-up, not blocking.
### 4.2 Out-of-scope change present in the diff (informational, not a defect)
`tests/test_o2_race_free_lock.py` was modified — replacing a fixed `time.sleep(0.3)` in `acquire_bg()` with an active poll-until-marker-file-written loop (up to 2s, with early exit if the background process dies). This has nothing to do with cline removal; it's a flaky-test timing fix, most likely surfaced while chasing "100% pass, zero regressions" during implementation. I reviewed the change itself: it's strictly safer than what it replaces (removes a fixed-sleep race assumption, fails faster on a dead process) and doesn't touch cline-adjacent code. Flagging for transparency/scope-discipline reasons, not as a defect — I would not block on this alone.
## 5. Full Test Suite
```
.venv/bin/python -m pytest tests/ -q
→ 439 passed in 655.22s (0:10:55), exit code 0
```
Ran to completion myself (not the diff's own claim). **Zero failures, zero regressions.**
## 6. Verdict
Every site from my own Rev.2 plan was implemented faithfully and, in two places (the facts-bridge round-trip assertion, the architecture-diagram realignment), more thoroughly than the plan strictly required. No orphaned `cline` references anywhere in the diff. The highest-risk edit (`reconcile.sh`'s block deletion) is clean and syntactically valid. One low-severity doc staleness and one out-of-scope-but-safe test fix are noted, neither blocking.
[VERDICT: PASS]
@@ -0,0 +1,44 @@
# 리뷰 리포트 — Job 24b1f07f (Issue #17 후속: 테스트의 상속 WORKSPACE_ROOT, 6b00b6e..d198dd5)
- 리뷰어: planner-reviewer-claude-01 (claude)
- 리뷰 identity: loop-20261008T133858Z-9e7f5b / base 6b00b6e / head d198dd5 / tree 114ec21 — 검증 경로에서 `git rev-parse HEAD 'HEAD^{tree}'` 일치, 미커밋 변경 없음
- 범위: 커밋 1개(d198dd5), tests/test_issue17_item4_decisions.py 만(+36/−2). 제품 코드(.agents/skills)·버전·VERSIONS 변경 없음(브리프대로).
## 결론 요약
할 일 1·3·4 가 요구대로 반영됐고, 새 회귀 테스트는 수정 전 `_env` 에서 실제로 실패한다(센티널에 `.mam/shim/herdr` 생성). 할 일 2(다른 테스트 조사)는 이 PR 에 코드 변경이 없는데, 내가 직접 grep 한 결과로도 **같은 결함(다른 워크스페이스에 쓰기)은 conftest 가 이미 프로세스 수준에서 막고 있어** 추가 수정 대상이 없다 — 다만 남는 두 파일(§3)은 creator 리포트의 표에 있어야 한다. 차단 결함 없음.
## 1. 할 일 1 — `_env` (tests/test_issue17_item4_decisions.py:224-233)
- 상속 제외 목록에 `WORKSPACE_ROOT` 추가(:229), `env.update(... WORKSPACE_ROOT=str(tmp_path) ...)`(:231) 로 테스트별 임시 경로를 명시. "제거"가 아니라 "지정"을 고른 이유는 주석(:225-227)에 있고 맞다: lib.sh:26 은 `WORKSPACE_ROOT` 가 비어 있으면 `$SKILL_DIR/../..` = **체크아웃 자신**을 쓰므로, 제거만 하면 래퍼를 source 하는 헬퍼 4곳(_run_both :246/:372/:561/:586 등)이 체크아웃의 `.mam/shim/herdr` 를 다시 쓴다. 지정하면 shim 이 tmp_path 아래에 생긴다(회귀 테스트가 `(work/.mam/shim/herdr).is_file()` 로 고정, :498).
- `extra` 로 넘기는 명시 WORKSPACE_ROOT(:692 의 wait-rc 테스트)는 `env.update(extra)` 가 뒤에 오므로 그대로 이긴다 — 의도적 지정 테스트가 깨지지 않는다.
## 2. 할 일 3 — 회귀 테스트 test_c_helpers_write_nothing_to_an_inherited_workspace (:477-498)
- 센티널 디렉터리를 `WORKSPACE_ROOT` 로 monkeypatch 한 뒤 `_run_both`(옛·새 양쪽)와 래퍼 직접 source 를 돌리고, 센티널 아래 파일 없음·체크아웃 shim mtime 불변·셸이 보는 `$WORKSPACE_ROOT` 가 테스트 tmp 임·shim 이 tmp 에 생김을 단언한다.
- **수정 전 코드에서 실패 확인**: HEAD 의 테스트 파일에서 `_env` 두 줄만 base(6b00b6e) 판으로 되돌린 스크래치 사본 → `AssertionError: written into the sentinel`, `['.mam', '.mam/shim', '.mam/shim/herdr'] == []` (1 failed). 현재 코드에서 통과.
- conftest 의 `pytest_configure` 는 다른 체크아웃을 가리키는 WORKSPACE_ROOT 를 수집 전에 지우므로(tests/conftest.py:139-148), 이 테스트가 monkeypatch 로 다시 설정하는 것이 맞는 설계다(지우지 않으면 센티널이 보이지 않는다).
## 3. 할 일 2 — 같은 결함이 다른 테스트에 있는가 (직접 grep)
- **conftest 가 막는 범위**: `pytest_configure`(conftest.py:139-148)가 AGENT_SESSIONS_YAML·MAM_JOBS_DIR·DELEGATE_JOB_LOGS_DIR 을 항상, `WORKSPACE_ROOT` 는 **realpath 가 이 체크아웃이 아닐 때만** os.environ 에서 지운다(주석 :122-124: 이 체크아웃을 가리키면 "lib.sh 가 어차피 유도하는 값"). 따라서 어떤 테스트든 os.environ 을 복사해 lib.sh 를 돌려도 **다른 워크스페이스에는 쓸 수 없다**. 남는 경우는 (i) 체크아웃 자신의 shim 재작성, (ii) 테스트가 monkeypatch 로 다시 설정한 값, (iii) pytest 밖에서 헬퍼를 직접 돌리는 경우(PR #51 리뷰 때의 사고는 리뷰어의 수동 탐침, 즉 (iii)).
- **이 파일이 "빠진" 이유**: 빠진 것이 아니라 (i)(iii) 에 노출돼 있었다 — `_env` 가 WORKSPACE_ROOT 를 남겨 둔 채 래퍼→lib.sh 를 source 했으므로, 스위트 실행 중에는 체크아웃 자신의 shim 을 매번 다시 썼고, 수동 실행에서는 상속값 그대로 썼다. 이번 수정이 둘 다 막는다.
- os.environ 을 복사하고 lib.sh/래퍼를 돌리는 테스트 파일 36개를 grep 했다. `mam_sandbox` 를 쓰는 파일은 fixture 가 `WORKSPACE_ROOT=tmp_path` 를 설정하므로(conftest.py:215) 복사본이 sandbox 를 물려받아 안전하다. fixture 없이 lib.sh 를 실제로 source 하는 파일은 둘뿐이며, 둘 다 (i) 에만 해당한다:
| 파일:라인 | 동작 | 판단 |
|---|---|---|
| tests/test_b19_headless_reconcile_fixes.py:326-329, :366-369, :401-402 | `source "$SKILL_DIR/lib.sh"` 하는 스크립트를 SKS_* 만 뺀 os.environ 으로 실행 | 다른 체크아웃은 conftest 가 지움; 이 체크아웃이면 자신의 shim 재작성(conftest 가 명시적으로 허용하는 경우). 고치지 않아도 되나 표에 있어야 함 |
| tests/test_version_consistency.py:30 | `bash -c 'source lib.sh …'` 를 env 지정 없이 cwd=REPO_ROOT 로 실행 | 위와 같음 |
| tests/test_deploy_freshness.py, test_deploy_layout.py | lib.sh 를 복사·읽기만, source 안 함 | 해당 없음 |
- 제품 코드 변경 필요 여부: 없음. conftest 한 곳에서 "이 체크아웃" 경우까지 지우는 방법은 lib.sh 가 어차피 같은 값을 유도하므로 효과가 없고(주석 :122-124 의 근거), 체크아웃 shim 재작성을 피하려면 각 헬퍼가 tmp 를 지정해야 한다 — 이 PR 의 방식이 맞다.
## 4. 할 일 4 — 실행 (검증 경로, 워크트리 .venv Python 3.9.6, `env -i` 로 HERDR_*·MAM_*·MQTT_* 제거)
| 실행 | 결과 |
|---|---|
| (a) WORKSPACE_ROOT 없이: test_issue17_item4_decisions, test_issue33_budget, test_issue5_phase1_delegation, test_tier1_unit | **443 passed / 0 failed** (478 s) |
| (b) WORKSPACE_ROOT=<워크트리 밖 센티널>: test_issue17_item4_decisions | **290 passed / 0 failed** (319 s); 실행 뒤 센티널 **비어 있음**(`find` 출력 없음) |
| 회귀 테스트, 수정 전 `_env` 사본 | 1 failed(센티널에 .mam/shim/herdr) |
- 본 체크아웃 `.mam/shim/herdr` mtime 실행 전후 동일(1791469013). 실제 .mam/jobs 항목 수 불변. 브로커 bind 제약 없음.
- (b) 에서 센티널은 realpath 가 체크아웃이 아니라 conftest 가 지우므로, 대부분의 테스트는 conftest 로, 회귀 테스트는 `_env` 로 보호되는 셈이다 — 둘 다 통과했으니 브리프 (b) 의 목적(어느 층이든 센티널에 쓰지 않음)은 충족된다.
## 5. 이식성·비차단
- 변경은 Python 테스트 코드뿐(3.9 문법, `stat().st_mtime_ns`, `Path.rglob`). bash 3.2·macOS 영향 없음.
- 비차단: §3 표의 두 파일이 creator 리포트의 "고치지 않은 후보" 표에 없다면 추가를 권한다. 새 관찰 없음.
[VERDICT: PASS]
@@ -0,0 +1,170 @@
# 🔍 Review Report — PR #29 병합 전 독립 재검토 (job `291e38b5`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-09-20
- **대상**: PR #29 `feat/issue-21-items-4-5-7` **@ `46ea4cc`**, base `main @ 1134d74` (v4.6.0). 20커밋, `git diff --stat 1134d74...HEAD` = **25 files, +3229/−108**.
- **검토 트리**: 워크트리 `/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux-wt/pr-29` (detached @ `46ea4cc`, 자체 `.venv`).
- **안전 규칙 준수**: 워크트리에 파일 수정·커밋·checkout 없음. 본 체크아웃은 `main @ 1134d74` 그대로(checkout/switch/merge 없음). `worktree_remove.sh` 를 실제 워크트리에 실행하지 않았다. 실제 `.mam`·monitor 데몬·에이전트 세션 조작 없음, push·merge·이슈/PR 상태 변경 없음. 재현 실험은 scratchpad 의 임시 저장소(uuid4 이름)에서만 했다.
- **heartbeat**: 브리프 직후 `started --heartbeat 30` 을 가장 먼저 발행했다.
## 결론 요약
브리프의 8개 항목을 모두 확인했다. **병합을 막을 결함은 찾지 못했다.** 항목 5(리뷰 identity)의 설계·구현 품질은 높고, 기본 경로(옵션 없는 루프)의 호환성은 코드상 보장된다. 아래 **비차단 지적 9건**(N1–N9)을 남긴다. 그중 N1 은 재현 실험으로 확인한 실제 소실 가능성(판정 증거의 gc 소멸)이므로 후속 이슈 등록을 권한다.
## 1. 항목 4 — 워크트리 준비·해체 헬퍼
### 1-1. `.venv` — 브리프가 물은 "실제 venv" 는 아니다 (N2, 비차단)
`worktree_prepare.sh:111-118` 은 여전히 **심링크**를 만든다(`ln -s "$MAIN/.venv" "$WT/.venv"`). 실제 venv 생성도, 인터프리터 경로 전달도 하지 않는다. 다만 이번 PR·base 에서 **커밋 사고 경로는 3중으로 닫혀 있다**:
| 층 | 근거 |
|---|---|
| 저장소 `.gitignore` | base `1134d74` 의 `.gitignore:15` 가 `.venv`(슬래시 없음) — 파일·링크·디렉터리 모두 무시 |
| 공유 `info/exclude` | `worktree_prepare.sh:120-129` 가 `/.venv`·`.pytest_cache/` 를 `$GIT_COMMON_DIR/info/exclude` 에 추가 |
| 배포 관리 블록 | `deploy/install.sh:549`·`deploy/install_mam.sh:249` 가 `/.venv/` → `/.venv` (#27 `fadd38c`) |
남는 위험은 두 가지이며, 둘 다 헬퍼가 유발하지는 않는다.
- `rm -rf "$WT/.venv/"` 처럼 **끝에 슬래시를 붙이면 링크를 따라가** 제어 루트의 venv 내용을 지운다. 헬퍼는 그런 호출을 하지 않지만(스크립트 2개의 `rm -rf` 는 `$gd/modules*` 뿐), 사람·에이전트의 수작업에서는 그대로 남는 함정이다.
- 워크트리와 본 체크아웃이 venv 를 공유하므로 브랜치별 의존성 분기가 불가능하다.
→ 권고: 헬퍼에 `--venv link|create` 같은 선택지를 두거나, 최소한 SKILL.md 에 "`.venv` 는 링크이므로 워크트리에서 `pip install`·`rm -rf .venv/` 금지"를 명시.
### 1-2. `info/exclude` 는 공유물이다 (N3, 비차단)
linked worktree 의 `info/exclude` 는 `$GIT_COMMON_DIR` 의 것이므로 prepare 가 **본 체크아웃의 무시 규칙도 바꾼다**. 코드 주석(`:120-122`)과 설계 문서가 이를 명시하고, 추가되는 두 패턴은 본 체크아웃에서도 산출물이다. 수용 가능하나, 되돌리는 경로(remove 시 정리)는 없다.
### 1-3. 서브모듈 opt-in·롤백
`worktree_prepare.sh:131-204`: `--submodules` 일 때만 초기화하고, 초기화 전 상태(각 서브모듈의 git dir 존재 여부, 공용 `.git/config` 의 `submodule.<n>.url|active`)를 **인덱스 배열**(bash 3.2 호환)로 기록한다. 초기화 안 된 경로에 파일이 이미 있으면 **아무것도 바꾸기 전에** exit 3 으로 거부한다(R4) — 롤백이 "이번 시도가 만든 것"만 지울 수 있다는 전제를 실제로 성립시키는 올바른 순서다. 실패 시 deinit → `.git` 파일 제거 → `modules/<name>` 제거 → 없던 `modules/` 제거 → config 복원 순으로 되돌리고, 마지막에 `git status` 로 워크트리가 여전히 쓸 수 있는 체크아웃인지 확인해 메시지를 갈라 준다. 사람이 강제 제거로 더 망가뜨리지 말라는 안내까지 있다.
### 1-4. `--force` 가 작업을 잃을 수 있는가 — 잃지 않는다
`worktree_remove.sh` 의 판정은 **변경을 가하기 전에** 모두 끝난다(`:57-121`): 잠금, 실행 중 세션(`--stop` 없으면 거부), 열린 잡, 트리 청결(서브모듈 포함), 서브모듈 소견. `--force` 는 워크트리 git dir 에 `modules/` 가 있어 git 이 plain remove 를 거부하는 경우에만, 그것도 **단 한 번** 쓴다(`METHOD="single --force"`).
- **R1(정지 중 쓰기)**: `judge_tree()` 를 `--stop` **이후 다시** 실행하고, 달라졌으면 `:154` 에서 거부한다.
- **R6(tag/notes 로만 보존된 커밋)**: `lib_py/worktree.py:UNPUSHED_REVS = ("HEAD","--exclude=refs/stash","--all","--not","--remotes")` 로 모든 로컬 ref 기준 미푸시 커밋을 본다. stash 는 별도 확인.
- **R5(deinit 저장소)**: `submodule foreach` 로 닿지 않는 `modules/` 아래 저장소까지 `--git-dir` 로 직접 검사하고, 판단 불가한 "부분 저장소"는 오류로 남겨 거부한다.
즉 `--force` 시점에는 "미커밋·미푸시·stash 없음"이 증명돼 있다. 한 가지만 적어 둔다(N8): plain/force 어느 쪽이든 git 은 **무시된 파일**을 말없이 지운다. 워크트리에 테스트가 남긴 `.mam/delegate_job_logs` 같은 산출물은 제거와 함께 사라진다(제어 평면이 본 체크아웃이므로 설계상 무해).
또 하나(N7): 열린 잡 검사는 `registry_dirs`(`MAM_JOBS_DIR` → `WORKSPACE_ROOT/.mam/jobs` → 행들의 `control_plane.mam_jobs_dir`)만 본다. 행이 없는 워크트리 로컬 `.mam/jobs` 의 잡은 보이지 않는다. prepare 가 만든 creator 는 제어 루트에 묶이므로 모델상 발생하지 않는 경로지만, 수작업으로 만든 워크트리에는 해당한다.
## 2. 항목 4 — resume 계약 변경(`2679ddf`)은 기존 사용자를 깨지 않는다
`resume_session.sh:50-70` 이 행의 `pane.cwd` 와 `--workspace` 를 비교해 다르면 exit 2, 경로가 사라졌으면 exit 2 로 안내한다. 기존 단일 워크스페이스 사용자에게 영향이 없는 이유:
1. `--workspace` 는 원래부터 **필수 인자**이고(`:42`), 기존 행의 `pane.cwd` 는 그 워크스페이스 경로다. 본 체크아웃의 실제 `.mam/agent-sessions.yaml` 5개 행 모두 `cwd: /Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux` 로, 평소 호출과 일치한다.
2. 비교는 `mam_abs_workspace`(`lib.sh:1606-1609`, `cd -P … pwd -P`)로 정규화한 뒤 하므로 심링크·상대경로 표기 차이는 통과한다.
3. `pane.cwd` 가 없는 구(舊) 행은 `ROW_CWD` 가 비어 검사 자체를 건너뛴다.
바인딩 영속은 **이미 실행 중인 경로에도** 적용된다: `:145` 가 `CONTROL_PLANE_JSON="$CP_JSON"` 를 `update_yaml_resumed.sh` 에 넘기고, 그쪽 `:168` 이 이를 읽어 행에 기록한다(A13). 계산 실패 시 워크트리면 exit 2, 제어 루트면 경고 후 무기록 — create 쪽(`create_session.sh:211-221`)과 같은 규칙이다.
## 3. 항목 5 — 리뷰 identity
- **기록**: `_record_round`(`runner.py`)가 라운드마다 `iteration/base_sha/head_sha/tree_sha/review_commit/isolation/review_path/jobs/verdicts/reviewers(evidence)/stale` 를 남기고 체크포인트에 `loop_id` 와 `review_rounds` 를 싣는다. 승격 시에는 리포트 옆에 `report-<jid>.identity.json` 을 원자적으로(`.tmp` → `replace`) 쓴다.
- **스냅샷**: `_worktree_tree()` 가 임시 `GIT_INDEX_FILE` 로 `read-tree HEAD` → `add -A` → `write-tree` 하여 **실제 인덱스·status·ref 를 건드리지 않는다**. 미커밋이 있으면 `commit-tree` 로 ref 없는 스냅샷 커밋을 만든다. untracked 중첩 저장소는 gitlink 만 남아 고정 불가이므로 거부하고(`_snapshot`), dirty 서브모듈도 거부한다(`_dirty_submodules` 는 `--ignore-submodules=none` 으로 물어 `submodule.*.ignore` 설정이 숨기지 못하게 한다). 판정 불가(`None`)는 전부 실패로 떨어지는 fail-closed 다.
- **격리**: `_open_review_tree` 는 `TMPDIR/mam-review/<loop_id>/<n>` 에 detached 워크트리를 만들고, **실패하면 격리를 낮추지 않고 exit 1**(로그 문구까지 그렇게 적혀 있다). `_close_review_tree` 는 remove 실패 시에만 `prune` 을 부르고, 부모 디렉터리는 비었을 때만 지운다. `run()` 이 `_run_body()` 를 `finally: _close_all_review_trees()` 로 감싸고 `release_guard` 도 같은 정리를 한다.
- **stale 재리뷰**: 라운드 판정 뒤 `_round_is_stale`(현재 head·tree 비교)로 소스 변경을 잡아 승인 전량 폐기 후 재리뷰, 마지막 라운드면 exit 1. 승격 직전에도 `_identity_now() != (accepted head, tree)` 면 "source changed after approval; not promoting" 으로 exit 1(B10).
- **원격 리뷰어**: `_check_remote_recipients` 가 **어떤 잡도 위임하기 전에** 판정 수신자 전원을 검사해 기본 거부, `--remote-review diff-only` 만 허용하며 그때 diff 가 truncated/unavailable 이면 증거가 없다고 exit 1.
- **기본 동작 동일성**: `_context_active()` 가 거짓이면 `_worktree_context()` 는 빈 문자열을 반환하고 `collect_changes_diff(None)` 은 기존 호출과 동일하다. `_dispatch` 의 새 인자는 기본값(`remote=False, purpose="work"`)이라 프롬프트는 바이트 동일하다. 다만 옵션과 무관하게 `Loop id:` 로그 1줄과 체크포인트의 `loop_id` 필드가 늘었다(N9, 무해).
### N1 (비차단, 후속 권고) — 스냅샷 커밋이 gc 로 사라진다
`_snapshot` 의 스냅샷 커밋은 ref 가 없고, 유일한 도달 경로였던 리뷰 워크트리 HEAD 는 `_close_review_tree` 가 라운드 판정 직후 없앤다. 그래서 `identity.json` 의 `review_commit`·`tree_sha` 는 **나중에 검증하려 할 때 이미 없을 수 있다**. scratchpad 임시 저장소에서 재현했다(워크트리 제거 → `reflog expire --expire=now --all` → `gc --prune=now` → `git cat-file -e <snap>` 실패). 일상적으로도 unreachable 객체는 기본 2주 뒤 대상이다. 미커밋이 있던 라운드에만 해당하며(클린 트리면 `review_commit == head_sha`), 판정 자체의 정합성에는 영향이 없다.
→ 권고: `refs/mam/review/<loop_id>/<n>` 같은 ref 로 스냅샷을 고정하고, 루프 종료 시 정책적으로 정리(또는 보존).
### N6 (비차단) — 강제 종료 시 리뷰 워크트리 잔존
`finally`/`release_guard`/시그널 핸들러로 정상·TERM·INT 경로는 덮이지만, SIGKILL 이면 `TMPDIR/mam-review/...` 디렉터리와 소스 저장소의 worktree 항목이 남는다. `prune` 은 remove 실패 시에만 부른다(의도된 선택, 주석에 근거 있음).
## 4. #20 격리 — 설계와 실측
- `tests/conftest.py` 의 `pytest_configure` 가 **수집 이전에** ambient 바인딩 4개를 기록하고 `AGENT_SESSIONS_YAML`·`MAM_JOBS_DIR`·`DELEGATE_JOB_LOGS_DIR` 를 제거한다. `WORKSPACE_ROOT` 는 **다른 체크아웃을 가리킬 때만** 제거한다(이 체크아웃을 가리키면 lib.sh 가 어차피 유도하는 값). import 시점에 `os.environ` 을 복사하는 모듈(`test_orc_onboard.SCRUBBED_ENV`) 때문에 세션 fixture 로는 늦다는 설명이 정확하다. `pytest_unconfigure` 가 되돌려 in-process `pytest.main()` 호출자를 배려한다.
- autouse `_isolate_mam_state_dirs` 는 **env 만** 설정하고 디렉터리를 만들지 않으며, 숨김 이름(`.mam-test-state`)이라 `tmp_path` 를 나열하는 기존 테스트를 깨지 않는다. `mam_sandbox` 와 테스트 자신의 `setenv/delenv` 가 뒤에 실행돼 이긴다.
- 세션 가드 `mam_state_leak_guard` + `_mam_state_guard.py` 는 **보고만 하고 절대 지우지 않는다**(실제 제어 평면이므로 옳다). 감시 대상은 이 체크아웃의 `.mam` 과 기록된 바인딩이 가리킨 제어 평면이며, 동시에 도는 실제 위임과는 "레코드 먼저 → 등록된 세션" 규칙으로 구분한다.
- #15 옵트아웃(N4, 비차단): `test_issue15_registry_isolation.py` 의 누수 단언이 "전체 목록 동일"에서 "자기 잡 id 가 실제 루트에 없음 + 그 사이 늘어난 항목 중 자기 세션 이름이 없음"으로 **약해졌다**. 동시 실행되는 실제 위임 때문에 전체 비교가 오탐을 냈다는 근거가 타당하고, 세션 이름 스캔이 핵심 보장을 유지하므로 수용한다.
## 5. acceptance5 안정화(`7bc3e1a`·`371099a`·`e6d2168`) — 계약을 약화하지 않는가
| 변경 | 판단 |
|---|---|
| 세션 이름·HMAC secret 을 실행마다 유니크하게(`tag = os.urandom(4).hex()`) | **개선**. 공개 브로커에 retain 된 과거 dispatch 가 이번 실행의 잡 대신 배달되던 교차 오염을 없앤다 |
| `--heartbeat-misses 3 → 10` | 허용. 이 시험의 목적은 "원격 러너가 브로커만으로 잡을 끝낸다"이고, K×N 무응답 임계 자체는 AC1·AC3 가 고정한다. 원격 러너의 `started --heartbeat` 계약은 그대로다 |
| 단언에 `advanced to 'completed'` 추가 | 허용. retain 된 종단 이벤트만 배달된 경우도 프로토콜상 정당한 배달 확인이다 |
| `_skip_if_broker_did_not_deliver` | 조건부 허용(N5). skip 은 "러너가 started 를 발행했고, 구독자가 **맞는 토픽**에 SUBSCRIBED 했고, 그 잡에 대해 **아무것도**(드롭 로그조차) 받지 못했다"는 세 조건이 동시에 성립할 때만이다. HMAC·identity 드롭, 잘못된 토픽, 발행 실패는 여전히 실패한다. 다만 구독자 배달 경로의 실제 회귀가 같은 증상을 내면 skip 으로 가려질 수 있다 |
## 6. 수용 사례·신규 테스트의 결정성·격리
- `tests/test_issue21_acceptance.py`(A1–A8, 278줄): 실제 herdr·실제 브로커를 쓰지 않는다. mock herdr / stub 위임 + `mam_sandbox`·`tmp_path` 기반이며, 브로커 관련 언급은 주석과 "브로커 도달 불가 조건에서 래퍼를 돌린다"는 A3 한 곳(`:102`)뿐이다.
- `tests/test_issue21_loop_b.py`(526줄, L1–L21): 러너를 직접 구동하되 위임·대기를 스텁으로 바꾸고 임시 git 저장소에서 돈다. 브로커 의존 0, `time.sleep` 없음. L1/L12/L14b/L18b 가 **옵션 없는 기존 동작 불변**을 별도로 고정하는 점이 좋다.
- `tests/test_issue21_phase2_loop_a.py`(649줄): `time.sleep(0.2)` 1회(`:312`) 외에 시간 의존 없음. `deploy/install.sh` 를 임시 타깃에 실행하는 경로가 있으나 모두 `tmp_path` 안이다.
- `tests/test_issue20_state_isolation.py`(202줄): 순수 함수 단위 + 중첩 pytest 1건(설계된 skip).
- uuid 사용은 `uuid.uuid4()`(issue15 의 `_unique`)로 브리프 규칙과 맞는다.
## 7. 문서 정합성과 권고의 타당성
- `docs/design/worktree-creator-model.md`: 항목 표가 1·2·3·6 = 완료(v4.6.0), 4·5·7 = 이 브랜치, 8 = 보류로 갱신됐고, 실행 예시가 `worktree_prepare.sh`/`worktree_remove.sh` 기준으로 다시 쓰였다. 호환성 표에 resume 의 exit 2 조건, remote 리뷰어 거부/opt-in, "실제 herdr pane 값 확인은 단계 C" 라는 한계가 명시돼 과장 없이 정확하다.
- `multi-agent-mux-loop/SKILL.md` 가 `--review-isolation`·`--remote-review` 를 표에 추가하고 기본값·거부 시점(위임 이전)·evidence 기록까지 적는다. create/resume/stop SKILL.md 도 헬퍼를 반영한다.
- PR 본문의 **비차단 권고 4건**을 코드에서 확인했고 모두 사실이다: ① A4 의 `_main_state` 비교가 untracked `.agents/`·`.mam/` 변화를 보지 못함, ② A4 가 `info/exclude` 추가를 **선반영**한 뒤 비교함(`test_issue21_acceptance.py:121-122`), ③ `_close_review_tree` 의 remove 실패 시 `prune` 이 전역, ④ `worktree_remove.sh` 의 서브모듈 거부 출력 중복. 넷 다 병합을 막을 성질이 아니며 후속으로 적절하다.
- #30(멈춘 에이전트 감지) 등록은 타당하다. #18 이 "프로세스 생존"에 결속된 설계라 "살아 있지만 멈춘" 상태는 그 계약 밖이며, 해결은 알림·운영 수준이므로 별도 이슈가 맞다.
## 8. 전체 스위트 실행 (이 리뷰어가 직접, 워크트리에서)
```
cd <pr-29 워크트리> && PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m pytest -p no:cacheprovider -q -rfE tests/
→ 2 failed, 1011 passed, 2 skipped in 2266.28s (0:37:46) (HEAD 46ea4cc, 실행 전후 동일)
```
| 실패 | 판정 |
|---|---|
| `test_issue14_delivery_ack.py::test_wrapper_idle_grace_never_outlives_the_wall_clock` | **PR 회귀 아님**. 이 시험은 PR 이 건드리지 않았다(`git diff -U0` 의 issue14 hunk 는 전부 `_job_for_inprocess_publish` 뒤쪽 `:520` 이후). 단독 재실행에서도 close_delay 28.5 s(임계 20+8)로 재현되며, **다른 브랜치에 이미 `90a289d test(issue-14): widen the wall-clock close margin under suite load` 가 있다** — 임계 자체가 좁다는 기지 문제다 |
| `test_issue19_subscriber_daemon_lifecycle.py::test_mqtt_loop_sigterm_exits_cleanly` | **브로커 flake**. 파일 자체가 PR 변경 0줄이고, 로그가 `broker did not accept connection; falling back to polling` 이다. 단독 재실행 **통과** |
- PR 본문의 "이 호스트 기준 실패 33건(#28)" 주장은 **내 실행으로는 확인되지 않는다**(내 조건에서는 2건). 제어 평면 바인딩이 실린 creator pane 조건에서 재현된 수치로 보이며, 내가 재현할 수 있는 조건이 아니므로 그 수치의 참·거짓을 주장하지 않는다. 내가 말할 수 있는 것은 **내 조건에서 새 회귀가 0 이라는 것**이다.
### 격리·위생 실측 (#20, 브리프 항목 4)
| 항목 | 결과 |
|---|---|
| 실제 `.mam/jobs`(본 체크아웃) 전후 | **차이 0** (레코드 추가 0건) |
| 실제 `.mam/delegate_job_logs` 전후 | **차이 0** |
| 워크트리 `git status --short --ignored` 전후 | **완전 동일**(무시 파일 포함) — 스위트가 워크트리에 아무것도 남기지 않았다 |
| 워크트리 HEAD | 실행 전후 `46ea4cc` |
| 본 체크아웃 | `main @ 1134d74`, 클린 |
이전 회차(PR #22)에서 내가 지적했던 "리뷰어 pytest 가 워크트리에 `.mam/delegate_job_logs`·`.mam/shim` 을 남긴다" 가 이번 실행에서는 **재현되지 않았다**. #20 수정이 의도대로 동작한다.
## 9. 병합 차단 여부 (브리프 항목 8)
알려진 버전 bump 미포함(오케스트레이터가 v4.7.0 으로 처리) 외에 **병합을 막을 결함은 찾지 못했다**. N1–N9 는 모두 비차단이며, 후속 순위는 N1 > N2 > N5 순으로 본다.
| # | 지적 | 성격 |
|---|---|---|
| N1 | 스냅샷 커밋·tree 가 ref 없이 남아 gc 로 소멸 → `identity.json` 사후 검증 불가(재현 확인) | 후속 이슈 권고 |
| N2 | prepare 의 `.venv` 는 여전히 심링크(실제 venv/인터프리터 경로 아님); 커밋 경로는 3중으로 닫혔으나 `rm -rf .venv/`·의존성 공유 위험 잔존 | 문서화 또는 옵션화 권고 |
| N3 | prepare 가 공유 `info/exclude` 를 바꿔 본 체크아웃에도 적용(되돌림 경로 없음) | 기지·문서화됨 |
| N4 | issue15 누수 단언이 전체 목록 비교에서 자기 잡 id + 세션 스캔으로 약화(근거 타당) | 수용 |
| N5 | acceptance5 의 skip 경로가 구독자 배달 회귀를 가릴 여지(조건은 매우 좁음), `--heartbeat-misses 3→10` | 수용 |
| N6 | SIGKILL 시 리뷰 워크트리·worktree 항목 잔존(prune 은 실패 시에만) | 사소 |
| N7 | remove 의 열린 잡 검사가 행 없는 워크트리 로컬 `.mam/jobs` 를 못 봄 | 모델 밖 경로 |
| N8 | remove 는 plain/force 모두 무시 파일을 말없이 삭제(추적 작업 손실은 없음) | 정보 |
| N9 | 옵션 없는 루프에도 `Loop id:` 로그 1줄과 체크포인트 `loop_id` 필드가 추가(프롬프트는 바이트 동일) | 정보 |
## 10. 교차검증 가이드
```bash
WT=/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux-wt/pr-29
(cd "$WT" && PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m pytest -p no:cacheprovider -q -rfE tests/) # 2 failed / 1011 passed
(cd "$WT" && PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m pytest -p no:cacheprovider -q \
tests/test_issue14_delivery_ack.py::test_wrapper_idle_grace_never_outlives_the_wall_clock \
tests/test_issue19_subscriber_daemon_lifecycle.py::test_mqtt_loop_sigterm_exits_cleanly) # issue19 통과, issue14 재현
git -C "$WT" diff 1134d74...HEAD -U0 -- tests/test_issue14_delivery_ack.py | grep '^@@' # 실패 시험은 변경 밖
# N1 재현 (임시 저장소에서만)
R=$(mktemp -d); cd "$R"; git init -q .; git config user.email t@t; git config user.name t
echo a > a; git add a; git commit -qm base; H=$(git rev-parse HEAD); echo dirty > b
GIT_INDEX_FILE=$R/idx git read-tree HEAD; GIT_INDEX_FILE=$R/idx git add -A; T=$(GIT_INDEX_FILE=$R/idx git write-tree)
C=$(git commit-tree "$T" -p "$H" -m snap); git worktree add -q --detach "$R/wt" "$C"; git worktree remove --force "$R/wt"
git reflog expire --expire=now --all; git gc --prune=now -q; git cat-file -e "$C^{commit}" || echo "snapshot gone"
```
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20260921T150212Z-97d845",
"base_sha": "6fc9194f896eb2e13e123b8ebe7a9089b629764d",
"head_sha": "1e826515cc2a07ea1f8da0ff1259e1ea4dde86fd",
"tree_sha": "4fd82ad1c2682d12c3f5114818f97291af28a032",
"review_commit": "1e826515cc2a07ea1f8da0ff1259e1ea4dde86fd",
"reviewer": "planner-reviewer-claude-01",
"job_id": "293e905f",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-09-21T15:25:44Z"
}
@@ -0,0 +1,139 @@
# 🔍 Review Report — PR #32 병합 전 독립 리뷰 (job `293e905f`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-09-22
- **대상**: PR #32 `fix/issue-25` **@ `1e82651`**, base `main 6fc9194` (v4.7.0). 5커밋, 4파일 `+486/−31`.
- **검증 경로**: `/var/folders/.../T/mam-review/loop-20260921T150212Z-97d845/1` (브리프가 지정한 리뷰 워크트리). 실제로 거기서만 검증했다.
- **identity 확인**: 검증 경로의 `HEAD = 1e826515cc2a07ea1f8da0ff1259e1ea4dde86fd`, `HEAD^{tree} = 4fd82ad1c2682d12c3f5114818f97291af28a032` — 브리프의 `head`·`tree` 와 **일치**한다(항목 5 identity 가 실제로 작동함을 이 잡 자체가 보여준다).
- **안전 규칙 준수**: 검증 경로·소스 워크트리(`multi-agent-mux-wt/pr-32`)·본 체크아웃(`main 6fc9194`) 모두 수정·커밋·checkout 없음. 실험은 전부 scratchpad 임시 디렉터리(uuid4 이름)에서 했고, pytest 는 `--basetemp` 을 검증 경로 밖으로 주었다. 실제 `.mam`·데몬·세션 조작 없음, push·merge·PR 상태 변경 없음, purge·scrub 실행 없음.
## 결론 요약
**병합을 막을 결함은 없다.** 핵심 변경(암묵적 계획서 로드 제거, `--plan-file` 명시 재사용, 네 지점 공통 계획 텍스트 검사)은 코드·문서·테스트가 일치하며, 새 테스트 17건 중 **13건이 수정 전 소스에서는 실패**한다(직접 확인). 비차단 지적 3건(E1–E3)을 남긴다.
## 1. 암묵적 로드 제거 (항목 1)
| 확인 | 결과 |
|---|---|
| Python 러너 | `runner.py` 에서 `glob` import 가 사라졌고, 남은 `glob` 사용처는 `find_report` 의 `report-final.md` 탐색(`:568`) 하나뿐이다. `.agents/reports/<planner>/plan-*.md` 를 읽는 코드가 없다 |
| 레거시 셸 러너 | `run_loop.sh` 의 `EXISTING_PLAN_FILE`/`ls -t .../plan-*.md` 블록이 통째로 사라지고 `log_info "No plan loaded; the Creator plans by itself."` 만 남았다 |
| 다른 경로 | 저장소 전체에서 `plan-*.md` 를 읽는 코드는 없다(승격 쪽 **쓰기**만 `runner.py:1368-1372` 에 남는다 — 정상) |
| planner 자동 선택 | `resolve_planner_session`(`run_loop.sh:386`)·`resolve_planner_session` 파이썬 대응은 남아 있으나, 그 결과는 **plan 모드의 위임 대상과 승격 경로**에만 쓰인다. 자기계획 모드에서 planner 이름으로 파일을 찾는 코드는 없다 |
## 2. `--plan-file` (항목 2) — 실측
검증 경로의 러너를 임시 제어 루트(`WORKSPACE_ROOT=<tmp>/ctl`)로 직접 돌려 확인했다.
| 입력 | 결과 |
|---|---|
| 없는 파일 | `[✗] --plan-file <절대경로>: not a readable file with plan text in it.` · **exit 1** |
| 빈 파일 / 공백만 있는 파일 | 같은 메시지 · exit 1 |
| 디렉터리 | 같은 메시지 · exit 1 (`is_file()` 로 걸린다) |
| 읽기 권한 없음(`chmod 000`) | 같은 메시지 · exit 1 (`OSError` → `None`) |
| `--plan` 과 함께 | `ERROR: --plan-file cannot be combined with --plan.` + 사용 예 2줄 · exit 1 |
| 상대경로 | **제어 루트 기준**. 호출 cwd(`<tmp>/elsewhere`)에 `plans/p.md` 가 실제로 있어도 러너는 `<ctl>/plans/p.md` 를 찾고 실패한다 — #25 의 "다른 디렉터리의 동명 파일을 집어오는" 사고를 구조적으로 막는다 |
| 공백 있는 경로(`my plans/p.md`, 상대) | 정상 로드: `Using the plan given with --plan-file: <ctl>/my plans/p.md (modified ... UTC)` (셸을 거치지 않으므로 인용 문제 없음) |
| 절대경로·`~` | `Path.__truediv__` 가 절대경로를 그대로 두고 `expanduser()` 가 앞서 적용된다(P3d 가 고정) |
| `--review-only` 와 함께 | 경고 후 무시(`log_warn`), `current_plan` 을 채우지 않는다 |
| 레거시 셸(`MAM_LOOP_PY=0`) | `ERROR: --worktree/--base/--review-only/--review-isolation/--remote-review/--plan-file require the Python loop (MAM_LOOP_PY=1)` · exit 1 — **동등 구현 대신 명시적 거부**이며, 기본 경로(`MAM_LOOP_PY=1`)는 `exec "$_py" -m lib_py.loop "${MAM_LOOP_ARGV[@]}"`(`run_loop.sh:262`)로 원본 argv 를 그대로 넘기므로 공백 경로도 안전하다 |
읽기가 **잡을 하나도 만들기 전**(parse_args 단계)에 끝나는 것도 확인했다 — 실패 시 레지스트리에 아무 흔적이 없다.
## 3. 계획 텍스트 검사 (항목 3)
`_plan_text()`(`runner.py:303-317`)가 "읽을 수 있는 일반 파일 + 공백 제외 내용 있음"을 단일 판정으로 만들고, **파이썬 러너의 네 지점이 모두 이를 쓴다**: `--plan-file`(`:265`), `--plan` 초기 계획서(`:1025`), 논의 턴 refine(`:1054`), 리뷰 에스컬레이션 refine(`:1284`).
- 빈 초기 계획서 → `log_error` 후 **return 1**. 이때 이미 만든 잡은 `release_guard`/정리 경로가 담당하고, 자기계획으로의 조용한 격하가 사라졌다.
- 빈 refine → 경고 + **이전 계획 유지**. 그래서 "갱신된 다음 계획서에 입각하여…" 프롬프트가 빈 계획을 싣는 일이 없다.
- 에스컬레이션 경로(`[ESCALATE: PLANNER]`)는 `if self.plan_mode and complex_fix`(`:1275`)로 **plan 모드에만** 걸린다. `--plan-file` 로 계획을 실은 실행에서 ESCALATE 판정이 나오면 재계획 없이 일반 수정 라운드로 간다 — 샌드박스에서 직접 구동해 확인했다(Planner 위임 0건, 수정 프롬프트는 "리뷰어들이 지적한 다음 피드백…"). SKILL.md:31 의 "수정 라운드에는 리뷰 피드백만" 서술과 **일치**한다. 다만 이 동작 자체는 E2 로 남긴다.
## 4. 체크포인트 (항목 4)
`.mam/loop-checkpoint.json` 의 `current_plan` 은 **쓰기 전용**이다. `checkpoint.load_checkpoint()` 는 정의되어 있으나 `runner.py` 어디에서도 호출하지 않는다(`grep 'checkpoint\.'` → `save_checkpoint`·`remove_checkpoint` 뿐). 따라서 본 체크아웃 체크포인트에 남아 있는 Issue #6 계획 텍스트가 다음 루프나 재개에서 되살아날 경로는 없다. 계획은 매 실행마다 `--plan-file` 또는 `--plan` 으로만 들어온다.
## 5. 옵션 없을 때의 동작 변화 (항목 5)
- 자기계획 프롬프트(`runner.py:1095`)와 승격 경로(`:1367` `if self.plan_mode and self.current_plan and self.plan_job_id`)는 그대로다. 즉 `--plan-file` 로 실은 계획서는 **승격되지 않는다**(승격은 plan 모드의 planner 산출물만) — 옳은 구분이다.
- 바뀐 것은 "planner 리포트 디렉터리에서 최신 plan-*.md 를 끌어오던" 동작 하나뿐이다. 그 외 프롬프트 문구·옵션 기본값·종료 코드는 동일하다.
- 기존 스위트 정합은 §6 에서 실측했다.
## 6. 테스트 (항목 6)
### 6-1. 검증 경로에서의 실행
```
cd <검증 경로> && PYTHONDONTWRITEBYTECODE=1 <제어 루트 .venv/bin/python> -m pytest -p no:cacheprovider -q -rfEs \
--basetemp=<검증 경로 밖> tests/test_issue25_plan_reuse.py tests/test_loop_cli.py tests/test_issue5_phase3_loop.py \
tests/test_issue21_loop_b.py tests/test_issue21_phase2_loop_a.py tests/test_issue21_acceptance.py
→ 2 failed, 108 passed in 220.98s (skipped 0)
```
**실패 2건은 PR 회귀가 아니라 리뷰 워크트리에 `.venv` 가 없어서 생긴 환경 문제다.**
| 실패 | 원인 | 확인 |
|---|---|---|
| `test_loop_cli.py::test_creator_parses_and_reaches_session_check` | `run_loop.sh` 를 하위 프로세스로 띄우는데, `REPO_ROOT`(= 검증 경로)에 `.venv` 가 없어 `_py` 가 시스템 python 으로 떨어지고 `RuntimeError: Failed to eager load lib_py.loop.autocomplete: No module named 'paho'` 로 죽는다(`run_loop.sh:253`) | `AGENT_PYTHON_BIN=<제어 루트 .venv/bin/python>` 만 주고 둘을 다시 돌리면 **2 passed in 0.34s** |
| `test_issue5_phase3_loop.py::test_p3_02_run_loop_wrapper_delegates_to_python_default` | 동일 | 동일 |
두 시험 모두 PR 이 건드리지 않은 파일이며, 실패 메시지에 계획서·`--plan-file` 은 등장하지 않는다.
### 6-2. 수정 없이는 실패하는가 — 확인함
검증 경로 사본을 만들고 `runner.py`·`run_loop.sh`·`SKILL.md` **세 파일만 base `6fc9194` 판으로 되돌려** 새 테스트를 돌렸다(검증 경로 자체는 건드리지 않았다).
```
13 failed, 4 passed in 1.51s
FAILED P1, P2, P3b, P3c, P3d, P5, P9[empty], P9[whitespace], P10, P11, P7, P7b, P8
```
통과한 4건(P3·P4·P5b·P6)은 옵션 없는 일반 CLI 오류·plan 모드 정상 경로라 수정과 무관한 것들이다. 즉 새 테스트는 이 변경을 정확히 겨냥한다.
### 6-3. 격리
| 항목 | 결과 |
|---|---|
| 실제 `.mam/jobs` 전후 | **차이 0** |
| 실제 `.agents/reports` | 새 항목 없음(테스트는 각자 `tmp_path` 안에 제어 루트를 만든다 — `ctl` 픽스처) |
| 검증 경로 tracked 파일 | 변화 없음(`git status --short` 클린, HEAD `1e82651` 유지) |
| 검증 경로 ignored | 내 실행이 `.mam/`(무시됨)을 만들었다. tracked 파일·커밋에는 영향이 없으며, 지우면 리뷰 트리를 수정하는 셈이라 그대로 두었다 → E3 |
| 실행 시간 | 새 파일 `test_issue25_plan_reuse.py` 는 전체 17건이 **1.5 s** 안에 끝난다(브로커·herdr 의존 없음, 모두 stub) |
## 7. 문서 (항목 7)
- 옛 서술("기존에 승격된 계획서가 있다면 이를 로드")은 `.agents`·`docs` 어디에도 남아 있지 않다(전수 grep).
- SKILL.md 의 사용법 문자열·CLI 표·Workflow 예시·Mermaid 다이어그램이 모두 `--plan-file` 기준으로 맞춰졌고, "계획서가 비어 있을 때" 절이 네 지점의 판정을 정확히 설명한다.
- 러너 usage 와 셸 usage 문자열이 동일하다(P7 이 이를 고정한다).
- 배포 사본: 저장소의 `.claude/skills/*` 는 `../../.agents/skills/*` **심링크**라 자동으로 동기화된다. 사용자 홈 `~/.claude/skills` 에는 mux 스킬 사본이 없다. 옛 문구를 가진 사본은 발견되지 않았다.
## 8. 병합 차단 여부 (항목 8)
버전 락스텝 bump 부재(`lib.sh:32`·`eager.py:16`·loop SKILL.md 모두 `4.7.0`, 오케스트레이터가 4.7.1 로 처리 예정) 외에 **병합을 막을 결함은 없다**.
| # | 비차단 지적 | 근거 |
|---|---|---|
| E1 | 레거시 셸 러너(`MAM_LOOP_PY=0`)의 plan 모드 읽기에는 빈 계획서 검사가 없다: `CURRENT_PLAN=$(cat "$PLAN_FILE")`(`run_loop.sh:501`). D13/D14 계약은 파이썬 러너에만 성립하는데 SKILL.md 의 "계획서가 비어 있을 때" 절은 이를 명시하지 않는다 | 후속: 한 줄 거부 또는 문서에 "Python 러너 기준" 명시 |
| E2 | `--plan-file` 로 계획을 실은 실행에서 `[ESCALATE: PLANNER]` 는 재계획 없이 일반 수정 라운드로 내려간다(`runner.py:1275` 가 `plan_mode` 로 게이트). 샌드박스 구동으로 확인(Planner 위임 0건). 이 게이트는 PR 이전부터 있던 것이고 SKILL.md 서술과도 모순되지 않지만, "계획서를 갖고 도는 루프인데 에스컬레이션이 무력화된다"는 점은 문서에 없다 | 문서 보강 권고 |
| E3 | 리뷰 격리 워크트리에는 `.venv` 가 없어, `run_loop.sh` 를 하위 프로세스로 띄우는 스위트는 `AGENT_PYTHON_BIN` 없이는 반드시 실패한다(§6-1). 또한 그 워크트리에서 pytest 를 돌리면 무시되는 `.mam/` 이 생긴다. **PR #32 가 아니라 Issue #21 항목 5 운영 쪽 후속**이다 | 리뷰 브리프의 테스트 명령에 `AGENT_PYTHON_BIN=<제어 루트 .venv/bin/python>` 를 포함하는 것을 권고 |
| E4 | `runner.py:1070` 의 `os.path.getmtime(self.plan_file)` 는 파싱 시점과 Phase 1 사이에 파일이 사라지면 예외로 죽는다(메시지 없는 트레이스백). 극히 좁은 경합 | 사소 |
## 9. 교차검증 가이드
```bash
RP=/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20260921T150212Z-97d845/1
PY=/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.venv/bin/python
git -C "$RP" rev-parse HEAD HEAD^{tree} # 1e8265... / 4fd82a... = 브리프의 head·tree
# --plan-file 실패 경로 (임시 제어 루트에서만)
C=$(mktemp -d); mkdir -p "$C/ctl" "$C/elsewhere/plans"; : > "$C/ctl/empty.md"; echo x > "$C/elsewhere/plans/p.md"
(cd "$C/elsewhere" && PYTHONPATH="$RP/.agents/skills" WORKSPACE_ROOT="$C/ctl" MAM_STATE_JSON='{"herdr_sessions":[]}' \
"$PY" -m lib_py.loop --creator c --task t --plan-file plans/p.md; echo "rc=$?") # ctl 기준 경로로 실패, rc 1
# 수정 없이는 실패하는지 (사본에서만)
S=$(mktemp -d); rsync -a --exclude .venv --exclude .git --exclude .mam --exclude nats-docker "$RP/" "$S/"
for f in .agents/skills/lib_py/loop/runner.py .agents/skills/multi-agent-mux-loop/scripts/run_loop.sh \
.agents/skills/multi-agent-mux-loop/SKILL.md; do git -C "$RP" show 6fc9194:"$f" > "$S/$f"; done
(cd "$S" && PYTHONDONTWRITEBYTECODE=1 "$PY" -m pytest -q -p no:cacheprovider --basetemp=/tmp/bt tests/test_issue25_plan_reuse.py) # 13 failed
# 실패 2건이 환경 문제임을 확인
(cd "$RP" && AGENT_PYTHON_BIN="$PY" PYTHONDONTWRITEBYTECODE=1 "$PY" -m pytest -q -p no:cacheprovider --basetemp=/tmp/bt2 \
tests/test_loop_cli.py::test_creator_parses_and_reaches_session_check \
tests/test_issue5_phase3_loop.py::test_p3_02_run_loop_wrapper_delegates_to_python_default) # 2 passed
```
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261029T045625Z-74296d",
"base_sha": "b9c828f09214b4bed6651a223cbb941e7b432647",
"head_sha": "3b81f9973223d2a910369711c08adc772003639d",
"tree_sha": "ff705b61bf25fe40d0ff054c372a399eacc79730",
"review_commit": "3b81f9973223d2a910369711c08adc772003639d",
"reviewer": "planner-reviewer-claude-01",
"job_id": "2ab23f4e",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-29T06:08:06Z"
}
@@ -0,0 +1,133 @@
# PR #79 (Issue #68) 리뷰 — head 3b81f99
리뷰어: planner-reviewer-claude-01 (claude) · job 2ab23f4e
## 0. 리뷰 경로 확인
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261029T045625Z-74296d/1`
- HEAD 는 `3b81f9973223d2a910369711c08adc772003639d`, tree 는 `ff705b61bf25fe40d0ff054c372a399eacc79730` 로 [리뷰 identity] 와 같다. 리뷰 전과 후 두 번 확인했다.
- `git status --porcelain --ignored` 결과는 비어 있고, `.mam` 도 없다.
- 리뷰 범위: base `b9c828f` 와 HEAD 사이의 커밋 5개, 9개 파일, +277/−22 줄.
- 기준 문서(읽기만 했다): `tea issues 68 --comments` 의 결정 1–4 와 완료 조건, `tea pulls 79` 설명, `INSTRUCTION.md`.
## 1. 결정·완료 조건 대조표
| 조건 | 구현(파일:줄) | 테스트 | 판정 |
|---|---|---|---|
| 결정 1: create 의 `--no-onboard` 유지, 기본은 온보딩 | `create_session.sh:67` `ONBOARD=1`, `:87-88` 그대로 | 기존 테스트 전체가 그대로 통과 | ✅ |
| 결정 2: worktree_prepare 기본을 온보딩으로 | `worktree_prepare.sh:30` `ONBOARD=1` | `test_prepare_onboards_by_default_end_to_end`(온보딩 잡 completed, "onboarding completed" 출력) | ✅ |
| 결정 2: `--no-onboard` 는 건너뛰고 create 에 그대로 넘김 | `:43`, `:232` `args+=(--no-onboard)` | `test_prepare_no_onboard_sends_none`, `test_prepare_forwards_onboarding_choice[opts2]` | ✅ |
| 결정 2: 기존 `--onboard` 도 같은 동작 | `:42` | `forwards[opts1]`, `[opts3]`(둘 다 주면 마지막 것이 이김) | ✅ |
| 결정 3: agy·codex·hermes·opencode 에만 경고, claude·grok 에는 없음 | `create_session.sh:208-211`, facts `lib_py/agents/__main__.py:75` | `test_facts_expose_post_discovered[6]`, `test_no_onboard_warning_dry_run[6]`, `..._keeps_exit_and_row[6]` | ✅ |
| 결정 3: 경고 내용 "첫 대화 전까지 ID 미기록, 같은 폴더 같은 종류는 기다림(#63)" | `:210` 의 문구가 이 두 가지와 `MAM_ID_ORDER_WAIT_S` 를 말한다 | 경고에 `Issue #63` 과 에이전트 이름이 들어 있는지 확인 | ✅ |
| 결정 3: 종료 코드·행이 바뀌지 않음 | 경고 출력만 하고 분기는 없다 | `keeps_exit_and_row`: rc 0, 행 필드(이름, status, role, server, workspace, cmd, cmd_full, cwd, id source·verified, 상태, control_plane)를 기대값과 비교 | ✅ |
| 결정 3: 뒤에서 거부돼도 경고가 먼저 보임 | spawn·#63 검사(`:287` 부근)보다 앞에서 출력 | `test_no_onboard_warning_precedes_a_later_refusal` | ✅ |
| 결정 4: 문서는 create SKILL.md 옵션 표와 worktree 절만 고침 | `SKILL.md:173`, `:205`, `:210`, `:213` 네 줄 | `test_issue42_skill_blocks`(블록 sha 와 근거 핀) | ✅ |
| 완료: "기본은 온보딩 안 함" 을 전제로 한 worktree 테스트를 고침 | `test_issue21_acceptance.py:47`, `:207`, `test_issue21_phase2_loop_a.py:422` | 모두 통과 | ✅ |
| 완료: macOS(bash 3.2, Python 3.9)에서 통과 | — | §3 | ✅ |
빠진 조건은 없다.
## 2. 꼼꼼히 본 것
### 2.1 경고 판정과 facts
- 이 Mac 에서 `lib_py.agents facts <agent>` 를 직접 실행했다.
- agy, codex, hermes, opencode 는 `MAM_ID_POST_DISCOVERED=1` 이다.
- claude, grok 은 `0` 이다.
- 값은 어댑터의 `id_lifecycle`(`base.py:174-175` 의 `PRE_ASSIGNED`/`POST_DISCOVERED`)에서 나온다. 셸 쪽에는 에이전트 목록을 두지 않았다.
- facts 를 쓰는 다른 곳에는 영향이 없다.
- `lib.sh:2596`(eval 뒤 필요한 키만 읽음), `:2957`(eval), `:3156`(`sed -n 's/^KEY=//p'` 로 키별 추출)은 모두 키 단위로 읽는다. 그래서 줄이 하나 늘어도 문제가 없다.
- facts 출력을 다루는 테스트(`test_a4_adapter_contract.py`, `test_issue23_24_startup_path.py`)도 이 Mac 에서 103 passed 였다.
- facts 를 얻지 못하는 경우(파이썬 실패 등) `eval "$(… || true)"` 는 아무 값도 정하지 않는다. 그러면 `${MAM_ID_POST_DISCOVERED:-0}` 가 0 이 되어 경고 없이 지나간다. 동작이 바뀌지 않는 쪽으로 실패하므로 안전하다.
- `MAM_DELEGATION_PY=0` 는 위임(delegation) 경로에만 쓰이는 스위치다. `lib_py.agents facts` 와는 관계가 없어 경고 판정에 영향이 없다.
- `test_issue26_ints.py:111` 은 이 값을 "문자열 비교" 로 분류해 정수 기본값 검사 대상에서 뺐다. 코드도 실제로 문자열로 비교하므로(`= 1`) 맞는 분류다.
### 2.2 `--creator-agent` 를 부르는 모든 곳 (`git grep -n creator-agent`)
- 테스트
- `test_issue21_acceptance.py:47`, `:207` 와 `test_issue21_phase2_loop_a.py:422` 에는 이제 `--no-onboard` 가 붙어 있다.
- `test_issue21_phase2_loop_a.py:339`, `test_issue50_onboard.py:192`, `test_issue57_logs_follow_registry.py:276`, `test_issue50_dispatch_herdr.py:868` 는 원래 `--onboard` 를 명시하므로 동작이 같다.
- `test_issue21_phase2_loop_a.py:355`(w6c)는 옵션이 없다. 하지만 서브모듈 초기화가 실패해 create 이전에 exit 1 로 끝나고, 행이 없음을 확인하는 테스트다. 그래서 온보딩까지 가지 않는다. 뒤에 다시 부르는 `_prepare(main, wt)` 에는 `--creator-agent` 가 없다.
- 새 테스트 파일의 세 호출은 의도한 대로다.
- 문서와 기록
- `docs/design/worktree-creator-model.md:48-51` 의 예시에는 옵션이 없다. 그래서 이제 온보딩하는데, 예시가 보여 주려는 creator 흐름에도 그게 맞다. 이 문서에는 "기본은 온보딩 안 함" 이라는 문장이 없어 고칠 내용도 없다. 결정 4 의 "최소 변경" 과도 맞는다.
- `VERSIONS.md:632` 는 과거 기록이고, `README*.md:51` 은 create 에 대한 설명이라 맞다.
- 그 밖의 스크립트에서는 `worktree_prepare.sh` 를 부르는 곳이 없다.
- 결론적으로 온보딩 대기(최대 `MAM_ONBOARD_WAIT_S`) 때문에 의도치 않게 느려지거나 44/45 로 끝날 호출은 남아 있지 않다.
### 2.3 SKILL.md 와 코드의 줄 단위 대조 (INSTRUCTION.md)
- `SKILL.md:173` 은 "`--no-onboard` 로 만든, ID 가 첫 턴 뒤에 생기는 에이전트(`id_lifecycle`)는 그때까지 ID 를 기록하지 않고, 같은 폴더의 같은 종류 create 를 막는다(#63). create 가 경고한다" 고 설명한다.
- 코드(`create_session.sh:209-210`)의 조건과 문구가 이와 같다.
- #63 쪽은 정확히는 "막는다" 가 아니라 "기다린 뒤 거부" 다. 하지만 표 한 줄 요약으로는 맞다.
- `SKILL.md:205` 의 시놉시스 `[--no-onboard]` 는 `worktree_prepare.sh:9`, `:43` 과 같다.
- `SKILL.md:210` 의 "onboards it … `--no-onboard` skips it, `--onboard` is the default and still accepted" 는 `:30`, `:42-43`, `:232` 와 같다.
- `SKILL.md:213` 의 종료 코드 "44/45 are create's (…onboarding is the default…)" 는 스크립트 머리말 `:17-19` 와 같고, create 의 44/45 정의(`create_session.sh:22-23`)와도 같다.
- 판단이 필요한 내용만 문서에 있고, 판정은 코드(adapter facts)에 있다. INSTRUCTION.md 를 따른 것이다.
### 2.4 `tests/data/skill_code_blocks.json`
- 근거 핀의 줄 번호 이동은 실제로 늘어난 줄 수와 맞는다.
- `create_session.sh` 는 경고 4줄을 `:208` 에 넣었으므로 그 뒤 근거가 모두 +4 줄 밀렸다(360→364, 518-545→522-549 등).
- `worktree_prepare.sh` 는 `--no-onboard` case 한 줄 때문에 +1 줄 밀렸다(250→251).
- 내용이 바뀐 블록은 하나다. `SKILL.md:202-206` 의 worktree 시놉시스가 `[--onboard]` 에서 `[--no-onboard]` 로 바뀌었고, 그 블록의 sha 만 `38836d31bf38` 에서 `8bfabafb0328` 로 바뀌었다.
- `test_issue42_skill_blocks.py` 가 sha 와 근거를 다시 계산해 통과했다(§3).
### 2.5 새 테스트가 결함을 잡는지
- base 대조 실행: `git archive HEAD` 를 TMPDIR 에 풀고, 코드 3개 파일(`__main__.py`, `create_session.sh`, `worktree_prepare.sh`)만 b9c828f 판으로 바꾼 뒤 `tests/test_issue68_onboard_default.py` 를 돌렸다.
- 결과는 **20 failed, 5 passed** 로, 작성자의 주장과 같다.
- 통과한 5건은 base 에서도 맞아야 하는 경우다. claude·grok 의 dry-run 과 행 시험 4건, 그리고 `--onboard` 전달 1건이다.
- 사본은 확인한 뒤 지웠다.
- Python 3.9 호환성: `str.removeprefix` 는 3.9 부터 있다. `list[str]` 주석은 `from __future__ import annotations` 덕분에 3.9 에서도 문제가 없다.
## 3. 실행한 테스트 (이 Mac: macOS, `/bin/bash` 3.2, `/usr/bin/python3` 3.9.6)
```
cd <검증 경로>
env -u HERDR_SOCKET_PATH -u HERDR_PANE_ID -u HERDR_TAB_ID -u HERDR_WORKSPACE_ID -u HERDR_SESSION_NAME \
-u HERDR_SESSION -u WORKSPACE_ROOT -u MAM_ENV_FILE -u MAM_JOBS_DIR -u DELEGATE_JOB_LOGS_DIR \
PYTHONDONTWRITEBYTECODE=1 /Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.venv/bin/python \
-m pytest -p no:cacheprovider --basetemp="$TMPDIR/claude-j2ab-bt" -q -rfs \
tests/test_issue68_onboard_default.py tests/test_issue21_acceptance.py tests/test_issue21_phase2_loop_a.py \
tests/test_issue26_ints.py tests/test_issue42_skill_blocks.py tests/test_issue50_onboard.py \
tests/test_issue57_logs_follow_registry.py tests/test_issue63_same_cwd_ids.py
```
- 결과: **265 passed, 1 skipped, 0 failed** (724 s).
- skip 1건은 `test_issue42_skill_blocks.py:266` 이다. untracked `.claude/skills` 가 worktree 에 없어서 생기는 환경 문제다.
- facts 를 쓰는 다른 테스트 `tests/test_a4_adapter_contract.py`, `tests/test_issue23_24_startup_path.py` 는 **103 passed** (152 s).
- base 대조 실행(§2.5)은 `test_issue68_onboard_default.py` 기준 20 failed, 5 passed.
- `test_issue50_dispatch_herdr.py` 는 실제 herdr 서버를 띄우므로 브리프 제약에 따라 실행하지 않았다. 이 파일이 worktree_prepare 를 부르는 곳(`:868`)은 `--onboard` 를 명시하므로 이번 변경으로 동작이 바뀌지 않는다.
- 테스트가 끝난 뒤 남은 프로세스: 테스트가 띄운 `reconcile.sh`, mock herdr, 구독자는 없다. 남아 있는 것은 원래 있던 셋뿐이다.
- 본 체크아웃 모니터 3714
- 이번 루프 88445
- 이번 잡의 job_subscriber 88788 (13:56:28 시작)
## 4. 발견 사항
### 차단
- 없음.
### 비차단
- **N1.** `tests/test_issue68_onboard_default.py:17` 의 `import yaml` 은 쓰이지 않는다. PR 설명에서도 남긴 것으로 밝혔다.
- **N2.** `--no-onboard --submit-job "<프롬프트>"` 를 함께 주면, 제출한 잡이 첫 턴이 되는데도 경고가 나온다.
- 이 조합에서는 원래 온보딩 프롬프트를 만들지 않는다(`create_session.sh:440`). 그래서 `--no-onboard` 가 사실상 아무 일도 하지 않는다.
- 결정 3 의 조건("`--no-onboard` 를 주고 ID 후발견 에이전트이면")을 그대로 구현한 결과다. 그래서 결함은 아니고, 문구가 조금 지나치게 경고할 뿐이다.
- **N3.** facts 를 얻지 못했는데 호출자 환경에 `MAM_ID_POST_DISCOVERED=1` 이 export 돼 있으면, claude 에도 경고가 나올 수 있다. 현실적인 경로가 없어 참고로만 적는다.
## 5. 사용자 확인 필요
- N2: `--submit-job` 과 함께 준 `--no-onboard` 에도 경고를 낼지. 지금은 결정 3 의 문언대로 경고를 낸다.
## 6. 결론
- 결정 1–4 와 완료 조건이 모두 구현됐고 테스트로 덮였다.
- 새 테스트는 base 에서 20건이 실패하므로 결함을 실제로 잡는다.
- 바뀐 테스트 파일과 create/worktree 관련 테스트가 이 Mac 에서 모두 통과한다.
- SKILL.md 의 설명은 코드와 줄 단위로 맞는다.
[VERDICT: PASS]
@@ -0,0 +1,191 @@
# 🔍 PR Review — Job 2b62056b (PR #22 `feat/issue-21-worktree-prereqs` @ `4a81d15`, base `main` `5611859`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-09-14
- **대상**:
- 워크트리 `multi-agent-mux-wt/pr-22`(detached `4a81d15`)
- `git log 5611859..HEAD` 9커밋, `git diff 5611859...HEAD` 19파일 +1905/−78
- 설계 커밋 `fe96db1`·`dcf2fab` 과 구현·교정 커밋 7개(`d3d3a76` → `4a81d15`)
- **방법**:
- 워크트리 diff 를 정독하고 이슈 #21·PR 본문과 대조했다.
- 임시 디렉터리에서 실험 1건을 했다(공백 경로 명령 실행).
- 워크트리에서 **전체 스위트**를 읽기 전용 조건(`PYTHONDONTWRITEBYTECODE=1 -p no:cacheprovider`)으로 실행했다. 실패는 base(본 체크아웃 `5611859`)에서 같은 시험으로 대조했다.
- 코드는 수정하지 않았다.
- **안전 규칙 준수**:
- 본 체크아웃은 `main` `5611859` 를 유지했다(checkout·switch·merge 없음). 워크트리의 추적 파일은 바꾸지 않았다(HEAD·`git status` 전후 동일). 다만 스위트 실행 중 일부 시험이 무시 대상 `.mam/`(`delegate_job_logs`·`shim`)을 워크트리에 만들었다. 기존 #20 위생 문제이며 §7 에 적었다.
- 실제 `.mam`·monitor 데몬·에이전트 세션은 조작하지 않았다. push·merge·이슈/PR 상태 변경도 없었다.
## 0. 요약
| # | 항목 | 판정 |
|---|---|---|
| (1) | 래퍼 절대경로화 | ✅ 공백 경로·다른 cwd 에서도 동작한다(실험 E1) |
| (2) | 루프 러너 `--worktree`/`--base`/`--review-only` | ✅ 소스 루트와 제어 루트가 정확히 나뉜다. 빈 변경분 가드는 diff 수집과 같은 정의라 문서만 바뀐 경우를 오탐하지 않는다 |
| (3) | `control_plane.py` 와 create/resume/stop/status/reconcile | ✅ 바인딩 없는 기존 행과 기본 워크스페이스는 동작이 바뀌지 않는다(하위 호환) |
| (4) | `lib.sh`·shim 계약 시험 | ✅ `_sks_*`·`send_keys_safe` 를 건드리지 않았다. h25 는 오히려 강화되었다 |
| (5) | 설계 문서 정정 | ✅ codex NOT PASS 사유 4가지를 반영했다. 비차단 보강 1건 |
| (6) | 신규 시험 결정성·격리 | ✅ tmp/sandbox 만 쓰고 브로커가 필요 없다. 위생 비차단 1건 |
| (7) | 스위트 결과로 회귀 확인 | ✅(비차단) 937 passed / 4 failed. 4건 모두 기존 T-1 시간 임계(공개 브로커) 시험이고, base 에서도 같은 부류가 실패한다. PR 회귀 없음 |
| (8) | #21 항목 완료·범위 | ✅ 1·2·3·6 완료, 4·5·7·8 은 타당하게 제외됐다. 후속 권고 2건 추가 |
| (9) | 알려진 미비 (a)(b) 외 차단 결함 | 없음. (a)(b)는 확인했다(§9). 나머지는 비차단 권고뿐이다 |
## 1. (1) 래퍼 절대경로화 (`d3d3a76`)
- **레지스트리**:
- `REGISTRY_DIR_DEFAULT="${MAM_JOBS_DIR:-.mam/jobs}"` 로 이제 `MAM_JOBS_DIR` 을 존중한다.
- `cmd_submit` 은 `cd "$WORKDIR"` 직후 `_abs_registry_dir` 로 `cd -P … && pwd -P` 절대화하고 `SKS_REGISTRY_DIR` 로 export 한다. 상대 레지스트리는 종전처럼 `WORKDIR` 기준이다.
- **명령 문자열**: `_pub_cmd` 가 모든 토큰을 `printf %q` 로 인용한다.
- 감사 로그 루트는 구독자와 같은 해석기(`get_logs_dir`)의 절대경로를 `DELEGATE_JOB_LOGS_DIR=%q` 접두로 고정한다.
- `_instructions` 는 `%s` 자리표시자만 쓰므로 경로의 `%` 로 인한 포맷 주입이 없다.
- **경로 목록**:
- 브리프 경로: `$REGISTRY_DIR/$JOB_ID/brief.md`
- Output Report Path(direct·loop 두 곳)
- 상대 `PY` 를 `cd` 전에 절대화
- create 의 onboarding 발행 명령(`create_session.sh` delegate 블록)
- **실험 E1** — 레지스트리 `…/reg a b/jobs`, 감사 로그 `…/logs dir`, 모두 공백 포함. 주입된 명령을 **다른 cwd** 에서 그대로 `eval` 했다(브로커는 닫힌 포트).
| 확인 | 결과 |
|---|---|
| 시작 명령 | `DELEGATE_JOB_LOGS_DIR=…/logs\ dir …/python …/publish_event.py --registry-dir …/reg\ a\ b/jobs --job … --event started --heartbeat 30` |
| 시작·성공 명령 rc | 2, 2(브로커 불가, 로컬 기록 뒤) |
| 공백 레지스트리의 events | `['started', 'completed']`, 레코드 `completed` |
| 감사 로그 루트 | 지정한 `logs dir` 아래에 job 디렉터리 |
| 다른 cwd 에 `.mam` 생성 | 0 |
| heartbeat 타이머 잔여 | 0(터미널 발행이 멈춤) |
- 기존 주입 문구 계약: `test_t1_4` 가 소스에서 `.mam/jobs/$JOB_ID` 리터럴을 금지한다. issue14·issue6·issue18 시험 결과는 §7.
- 남는 제한: 작은따옴표가 든 경로는 지원하지 않는다(주입 문구가 명령을 `'…'` 로 감싸는 prose 형식). 문서 §7 에 적혀 있다.
## 2. (2) 루프 러너 (`d907359`)
- **의미와 상호작용**:
- `--worktree` 는 소스 루트다. 경로가 디렉터리이고, `--show-toplevel` 이 자기 자신이며, `git-common-dir` 가 제어 루트와 같아야 한다(`runner.py` `_validate_worktree`).
- `--base` 는 소스 HEAD 의 조상인 커밋이어야 한다(`_resolve_base`). env 폴백은 없다(D17).
- `--review-only` 는 `--base` 가 필수이고 `--plan` 과 배타다.
- `MAM_LOOP_WORKTREE` env 는 CLI 가 우선이다.
- **루트 분리**:
- **소스 루트 기준**: diff(제어 루트의 `diff_collect.sh` 를 소스 cwd 에서 실행 — 워크트리의 미검토 수집기는 실행하지 않음), `base_commit`(`--base` 또는 Phase 2 시작 시 소스 HEAD), head, 변경분 가드.
- **제어 루트 기준**: wrapper 경로, 래퍼에 넘기는 `--registry-dir self.jobs_dir`, `wait_for_job`·`find_report`·cleanup 의 `jobs_dir`, 체크포인트(`worktree_root`·`head_commit` 필드 추가), loop guard, 리포트 승격.
- `jobs_dir` 는 `MAM_JOBS_DIR` 을 존중한다. 상대값은 제어 루트 기준이며, 래퍼 해석과 같다(`t2_15`).
- **빈 변경분 fail-closed**:
- `git diff --quiet <base>`(추적 파일의 작업 트리 대 base)와 `ls-files -o --exclude-standard`(미추적)로 판정한다. 이는 `diff_collect.sh` 가 수집하는 내용(`git diff "$base"` + 미추적 파일, `:40-48`, `:73-74`)과 같은 정의다.
- 따라서 **문서만 바뀐 리뷰 전용 흐름도 `present`** 로 판정된다. 오탐이 없다.
- `empty` 는 base 대비 추적 변경과 미추적 파일이 모두 없을 때뿐이다. 무시 파일만 바뀐 경우는 리뷰할 것이 없으므로 거부가 맞다.
- git 오류는 `unknown` 이 되어 역시 거부된다. 가드는 `--worktree`/`--base` 가 있을 때만, 리뷰 반복마다 동작한다.
- **`run_loop.sh`**:
- 새 인자는 기존 `MAM_LOOP_ARGV` 로 Python 러너에 그대로 전달된다. freeze 재실행도 원래 argv 를 넘긴다.
- 레거시 `MAM_LOOP_PY=0` 은 새 옵션(과 `MAM_LOOP_WORKTREE`)을 freeze·loop lock **이전에** exit 1 로 거부한다(`t2_8`, `mam_sandbox` 에서).
- 참고: 가드는 "작업 트리 대 base" 이고, 브리프의 `[워크트리 컨텍스트]` 는 커밋 수와 미커밋 변경 유무를 함께 보여 준다. 따라서 커밋 0개·미커밋 변경만 있는 상태도 리뷰어에게 드러난다.
## 3. (3) `control_plane.py` 와 전파 경로 (`ee1d896`·`af8a54c`·`13259ed`)
- **스키마**: 행 필드 `control_plane = {workspace_root, agent_sessions_yaml, mam_jobs_dir, delegate_job_logs_dir}`, 모두 realpath 다.
- **해석 순서**: `describe()` 는 행 바인딩(완전할 때)을 호출자 env 보다 우선하고, 다르면 stderr 로 경고한다. `forward` 는 `--workspace` 의 기본 바인딩과 다를 때만 참이다.
- **전파**:
- create·resume 은 `K=V ` 접두를 `CMD_FULL` 앞에 붙인다. `lib.sh` new-session 이 이것을 `--env` 로 바꾸는 기존 경로를 쓴다.
- `13259ed`/`af8a54c`: env 플래그가 있으면 **idle pane 을 재사용하지 않고** `pane split`/`workspace create` 호출에 `--env` 를 싣는다(`lib.sh` 775-787 부근).
- 재사용 pane 에 `env K=V` 를 `agent start --` 뒤 에이전트 인자로 넘기던 종전 결함(R1)이 없어졌다.
- 공백이 든 바인딩을 전파해야 하면 rc 3 → create·resume 이 exit 2 로 거부한다(`lib.sh` 가 `--env` 플래그를 인용 없이 나누므로).
- **resume**: 행 바인딩을 다시 전파한다. 바인딩 없는 기존 행은 이번 resume 의 바인딩으로 채운다(`update_yaml_resumed.sh`).
- **stop**: env 가 없을 때만 행의 `mam_jobs_dir`·`delegate_job_logs_dir` 를 export 한다. 취소 발행과 감사 로그가 행의 제어 평면으로 간다(R3).
- **status·reconcile**:
- `MAM_JOBS_DIR`·행 바인딩·감사 로그를 먼저 보고, 그 뒤 종전 후보를 그대로 본다.
- reconcile 구독 루프는 `MAM_JOBS_DIR` 을 우선한다(`reconcile.sh:239-245`). 이 부분의 시험은 소스 정적 가드뿐이다(`t3_7`).
- **하위 호환**:
- `--workspace` 가 제어 루트와 같은 일반 세션은 바인딩이 기본값과 같다. 그래서 기록만 되고 전파되지 않으며(`t3_2`), pane 생성 경로(idle pane 재사용 포함)가 종전과 같다.
- 바인딩 없는 기존 행은 status·stop·reconcile 에서 종전 후보 순서로 처리된다.
- 비차단: `mam_control_plane_json … 2>/dev/null || true`(create)가 실패를 삼키면 바인딩 없이 종전 동작으로 조용히 떨어진다. PR 후속 1·2 와 같다.
## 4. (4) `lib.sh`·shim 계약 시험
- **`lib.sh` 변경은 두 곳뿐이다**:
- new-session 의 idle pane 재사용 조건에 `&& [ -z "$env_flags" ]` 를 추가하고, 재사용 pane 에 `env …` 를 붙이던 코드를 제거했다.
- 파일 끝에 얇은 진입점 `mam_control_plane_json`·`mam_control_plane_prefix` 를 추가했다.
- `_sks_*`·`send_keys_safe` 를 포함한 다른 hunk 는 없다.
- **h25 는 약화가 아니라 강화다**:
- 종전 h25 는 결함 있는 동작(idle pane 재사용 + 에이전트 인자로 env)을 고정하고 있었다.
- 새 h25 는 env 가 **생성 호출의 `--env`** 에 있고 `agent start --` 인자에는 없음을 단정한다.
- env 없는 재사용은 h24 가 그대로 고정한다.
## 5. (5) 설계 문서 정정 (`b61c8b1`)
- **codex NOT PASS 사유별 반영**:
- 부분 지원: §3 제목이 "현재 코드 기준" 에서 "부분 지원 + 1단계 수정 반영" 으로 바뀌었다.
- 루트 3종: §7 이 제어·소스·런타임 코드 루트를 정의한다.
- 리뷰 identity: §2-C 가 항목 5 로 미뤘다고 명시한다.
- 과장 표현: A 의 "완전 격리", 리뷰어 "읽기 전용", 잡 토픽과 지문을 정정했다(§1 표).
- **추가된 내용**:
- 스킬별 호환성 표(§7)
- 1단계 운영 형태(구현은 루프 밖, 리뷰는 `--review-only` 로 하나씩)
- 두 번째 루프는 **거부**된다는 서술
- "실제 herdr `--env` 전파는 mock 수준까지만 검증" 이라는 정직한 단서
- 비차단 보강: §3 의 create 레시피에 `MAM_NO_SUBSCRIBER_DAEMON=1` 을 넣을 것.
- `create_session.sh:567` 의 `start_watchdog "$DELEGATE_JOB_ID" "$WORKSPACE"` 는 여전히 워크트리의 `reconcile.sh` 로 데몬을 띄울 수 있다(항목 4 에서 기본화 예정).
- "모니터는 본 체크아웃에서만"(§3 본문)을 지키려면, 항목 4 가 오기 전까지는 레시피 한 줄로 막는 편이 안전하다.
## 6. (6) 신규 시험 780줄의 결정성·격리
- 파일 머리의 규칙대로 모든 쓰기가 `tmp_path`·`mam_sandbox` 아래에서 일어난다.
- `wt_repo` 픽스처는 `monkeypatch.setenv` 로 `WORKSPACE_ROOT`·`MAM_JOBS_DIR` 을 임시 루트에 묶는다.
- 래퍼 시험은 브로커를 `127.0.0.1:9`(`UNREACHABLE`)로 두어 **브로커가 필요 없다**.
- 비차단 위생: `t2_6` 이 `monkeypatch` 대신 `os.environ` 을 직접 바꾼다. `try/finally` 로 복구하므로 새지는 않는다(PR 후속 3).
- `t3_7` 은 reconcile 의 `MAM_JOBS_DIR` 우선을 소스 문자열로만 고정한다(브로커가 필요한 경로라서다). 약하지만 명시되어 있다.
- 격리 실측(실제 `.mam/jobs`, 데몬, 워크트리 상태)은 §7.
## 7. (7) 테스트 실행 결과
| 실행 | 결과 |
|---|---|
| **전체 스위트** @ `4a81d15`(워크트리, 11:52–12:27Z, 오케스트레이터·다른 리뷰어 스위트와 동시) | **937 passed, 4 failed in 2103 s**. HEAD 전후 동일(`4a81d15`) |
| 실패 4건 | pane-busy `test_issue14…::…ignores_pane_busy_token`(rc 0: 늦은 completed 가 수락됨), 벽시계 `…never_outlives_the_wall_clock`(closed after **28.12 s** > 28), AC1(rc 2), AC5(rc 2) |
| 4건 단독 재실행 — PR `4a81d15` | 3 failed / 1 passed(AC1 통과). 이때 공개 브로커가 `no CONNACK from broker` 로 재시도하고 있었다 |
| 4건 단독 재실행 — base `5611859`(본 체크아웃) | 2 failed / 2 passed(AC1·AC5 실패) |
- **판단**:
- 4건은 #18 리뷰에서 main 계열 코드(`135d76f`·`7e1d3f0`·`ab842f1`)로도 같은 방식으로 여러 번 실패했던 T-1 부류다. 벽시계 28.1 s 는 그때와 같은 값이다.
- 같은 브로커 상태에서 base 도 이 부류가 실패한다.
- PR 이 래퍼 submit 에 python 호출 1회(`_logs_dir_abs`)를 추가했지만, 측정된 벽시계 값은 main 과 같다.
- **PR 이 만든 실패는 0건으로 본다.**
- PR 본문의 "33건 환경 실패" 는 이 환경(macOS, venv Python 3.9)에서는 재현되지 않았다. 이 환경의 실패는 위 4건뿐이다.
- **격리**:
- 본 체크아웃은 `main` `5611859` 클린을 유지했다. 실제 `.mam/jobs` 추가는 0 이다.
- 워크트리의 추적 파일은 변하지 않았다(`?? .venv` 만).
- **그러나 무시 대상 `.mam/` 이 워크트리에 생겼다**: `.mam/delegate_job_logs`(잡 21개)와 `.mam/shim`. 생성 시각이 20:52–21:13 KST 로 이 스위트 실행 중이다.
- 일부 시험이 `$REPO_ROOT/.mam` 에 쓴다(#20 위생 문제). PR 후속 4 가 지목한 `test_issue14…::_job_for_inprocess_publish` 의 감사 로그와, 샌드박스 없이 `lib.sh` 를 소싱할 때 생기는 shim 이다.
- PR 이 새로 만든 문제는 아니지만, 워크트리 병렬 운영에서는 워크트리마다 쌓인다.
- 읽기 전용 규칙에 따라 지우지 않았다. 오케스트레이터가 정리할 것을 권한다.
- 샌드박스 heartbeat 타이머: 실행 직후 집계에서 pytest 경로 타이머 3개가 보였으나, 재확인했을 때는 0개였다(동시에 돌던 다른 스위트의 것으로 보인다).
- 모니터 데몬 전후 비교는 스냅샷 필터 오류로 판정하지 못했다.
## 8. (8) #21 작업 항목과 후속
- **완료**: 항목 1(래퍼 경로), 2(러너 옵션·가드), 3(바인딩 영속·전파, status/reconcile/stop/loop 의 `MAM_JOBS_DIR`), 6(문서 정정). 각각 시험으로 고정되어 있다.
- **제외의 타당성**: 4(준비·해체 헬퍼, 데몬 기본화), 5(리뷰 identity·검증 격리), 7(실제 herdr 수용 사례), 8(다중 루프). 모두 설계 결정이나 실환경이 필요한 별도 작업이다. 1단계 운영(구현은 루프 밖, 리뷰 루프 하나)에 필요한 최소 변경만 이 PR 에 들어갔다는 판단에 동의한다.
- **후속 권고 5건은 적절하다**. 추가로 두 가지를 권한다.
- 6) 항목 4 전까지 §3 레시피에 `MAM_NO_SUBSCRIBER_DAEMON=1`(§5).
- 7) 첫 실제 워크트리 creator 전에 항목 7 의 "실제 herdr `--env` 전파" 수용 사례를 먼저 확인한다(현재는 mock 검증뿐). 전파가 안 되더라도 주입 명령이 절대경로라 잡 발행은 동작하지만, creator 가 스스로 부르는 스킬은 워크트리 `.mam` 을 쓰게 된다.
## 9. (9) 병합을 막을 결함
- **알려진 미비**:
- (a) 버전 bump 가 없다(4.5.0 유지). 새 CLI 옵션과 새 모듈이므로 4.6.0(MINOR)과 VERSIONS 항목이 필요하다.
- (b) `docs/design/reviews/review-agy-fd384d6b.md` 의 markdown 줄바꿈용 trailing whitespace 로 `git diff --check` 가 실패한다.
- 둘 다 확인했다. 코드 파일에는 whitespace 문제가 없다.
- **그 밖에 병합을 막을 결함은 찾지 못했다**.
- 비차단:
- create 의 바인딩 해석 실패 삼킴(§3, PR 후속 1)
- §3 레시피의 `MAM_NO_SUBSCRIBER_DAEMON=1`(§5)
- `t2_6` 의 `os.environ` 직접 조작(§6)
- 시험의 `$REPO_ROOT/.mam` 쓰기(§7, #20)
- T-1 시간 임계 시험
## 10. 종합
- PR #22 는 #21 항목 1·2·3·6 을 정확히 구현했다.
- 래퍼 경로는 공백 경로와 다른 cwd 에서도 절대·인용이 맞다(실험).
- 러너는 소스 루트와 제어 루트를 분리하고 diff 수집과 같은 정의의 fail-closed 가드를 둔다.
- 제어 평면 바인딩을 영속·전파하면서도 기존 워크스페이스와 바인딩 없는 행의 동작을 바꾸지 않는다.
- `lib.sh` 변경은 idle pane 재사용 조건에 한정되며 계약 시험은 강화되었다.
- 전체 스위트의 실패 4건은 base 에서도 같은 부류로 실패하는 기존 브로커 시간 임계 시험이다.
- 병합 전에 알려진 미비 (a)(b)를 릴리스 커밋으로 처리하면 된다. 설계 재검토는 필요 없다.
[VERDICT: PASS]
@@ -0,0 +1,106 @@
# 🔍 Review Report — PR #41 델타 리뷰 2회차 (job `2cc309ea`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-09-26
- **대상 델타**: `1673818..af0a2a2` (1커밋, 5파일 `+406/−12`, `git diff --check` 클린), base `main 8ea65bb` (v4.7.4).
- **검증 경로**: `/var/folders/.../T/mam-review/loop-20260926T052018Z-597343/1`. **identity 확인**: `HEAD = af0a2a25…3a1a`, `HEAD^{tree} = 03106826…6ce8` — 브리프와 일치.
- **1회차 내 판정**: NOT PASS(N1) + M1~M9 (job `ed0e1492`). 이번에는 N1·codex R1/R2 정정과 내 비차단 항목의 처리를 본다.
- **주의**: 같은 델타(동일 base·head·tree)에 대한 직전 잡 `ce114c80` 은 내가 검증 중에 오케스트레이터 쪽에서 `cancelled` 되었고 그 검증 경로는 사라졌다. 코드 검토·하네스 실험은 그때 것을(트리가 동일하므로) 그대로 쓰고, 테스트 실행은 **이 잡의 검증 경로에서 다시** 돌렸다(§6).
- **안전 규칙 준수**: 검증 경로·소스 워크트리·본 체크아웃(`main 8ea65bb`) 모두 수정·커밋·checkout 없음. 실험은 scratchpad 하네스(`stop_stall_watch` 함수 추출, 대역 프로세스는 내가 만들고 내가 정리)·in-process 모듈 검사·되돌린 사본에서만. 실제 세션에 stall_watch 를 붙이지 않았고 실제 `.mam`·데몬·herdr 서버 조작 없음, push·merge·PR 상태 변경 없음. 1회차에서 남았던 멈춘 래퍼·감시자는 이번 시작 시점에 더 이상 없었다.
## 결론 요약
**N1 은 닫혔다.** 래퍼의 `stop_stall_watch` 는 TERM 을 무시하는 감시자에 대해서도 **6 s 안에 돌아오고**(실측), 감시자는 `--watch-pid` 로 래퍼가 사라지면 스스로 끝난다. R2 의 재검사(`_dispatch_open`)는 wait 직후·nudge 직전·루프 머리 세 곳에 있고, 예외 정책도 타당하다. 비차단 관찰 2건(P1·P2).
## 1. N1 — 유계 stop (검토 요청 1~2)
`multi-agent-mux-delegate-job:710-727` `stop_stall_watch`: `kill -0` → `kill`(TERM) → 0.2 s × 25 폴링 → 남아 있으면 stderr `ignored TERM; killed` + `kill -9` → `wait`. 함수를 그대로 추출해 네 가지 대역에 돌렸다:
| 대역 | 결과 |
|---|---|
| TERM 을 무시(`trap "" TERM; exec sleep 300`) | **6 s** 에 rc 0 반환, stderr `stall watch for j1 ignored TERM; killed (pid …)`, 대역 사망 |
| 정상(TERM 에 죽음) | 0 s |
| `STALL_PID` 비어 있음 | 즉시 return 0 |
| 이미 종료(rc 2) | 즉시 반환, stderr `stall watch for j1 exited rc=2:` + 로그 꼬리 (기존 보고 유지) |
`wait` 가 다시 무한이 될 경로: KILL 뒤의 `wait` 는 SIGKILL 된 자식에 대해 즉시 돌아오고(실측), `kill -0` 실패 분기의 `wait` 는 이미 끝난 자식의 저장된 상태를 돌려준다. 남는 이론적 경우는 자식이 D 상태(커널 내 대기)로 KILL 을 못 받는 것뿐인데 감시자는 파이프·소켓 대기라 해당하지 않는다. **1회차 N1 의 원인 가설(fork-exec 창에서 TERM 이 삼켜짐)** 은 PR 이 래퍼 trace 로 확인했다고 밝혔고, 내 1회차 관찰(래퍼 `__wait4`, 감시자 정상 루프, 수동 TERM 에 즉시 종료)과 정합한다 — 어느 쪽이든 유계 stop 이면 닫힌다.
`--watch-pid "$$"`(`:695`): `start_stall_watch` 는 메인 셸의 함수라 `$$` 는 래퍼 pid 다. 감시자 `run()` 루프 머리에서 `_alive(watch_pid)` 가 거짓이면 rc 0(`stall_watch.py:298-303`). `_alive` 실측: 살아 있는 자식 True, **pid 1(권한 없음) True**, reaped/없는 pid False — 권한 오류를 "살아 있음" 으로 보는 규칙이 맞고, `watch_pid` 가 0/None 이면 `if self.args.watch_pid and …` 가 검사를 건너뛴다(`os.kill(0,0)` 은 프로세스 그룹 시그널이라 항상 True 인데, 그 값이 들어올 경로는 없다).
## 2. R2 — 재검사 위치와 예외 정책 (검토 요청 4)
`_dispatch_open`(`stall_watch.py:266-285`): 레코드 재읽기 → 종단 상태·`dispatch_token` 불일치·`attempt_id` 불일치면 False. 호출 지점 세 곳: 루프 머리(`:296`), **herdr wait 직후**(`:332-334`, 블로킹 대기 중 닫힌/재디스패치된 잡), **nudge 직전**(`:384-386`, `collect()` 가 시간을 쓴 뒤). 충분하다 — prompt 를 보내는 유일한 자리 앞에 두 겹이 있다.
- 예외: `FileNotFoundError → False`(레코드 삭제 = 잡 없음, 감시 중단이 안전), 그 외 `OSError/ValueError → True`(원자적 갱신 중의 일시 상태를 종결로 오인하지 않음) — 타당하다.
- blocked 경로는 재검사하지 않는다: 보내는 것이 `progress` 알림뿐이고 prompt 가 없다. 닫힌 잡에 대한 `progress` 는 `publish_event` 의 CAS(토큰)·종단 뒤 거부가 막고, 설령 기록돼도 사람에게 가는 알림 한 줄이라 무해 — 그대로 둬도 된다.
- `_notify` 가 False(rc ∉ {0,2})면 nudge 를 보내지 않고 `nudged=True` 로 두어 재시도하지 않는다(`:387-391`) — "잡당 1회" 계약 유지.
## 3. R1 — `--watch-pid` 만으로 닫은 판단 (검토 요청 5)
동의. 래퍼가 TERM/KILL 로 사라지면 그 셸의 어떤 trap 도 돌지 않으므로 trap 합성은 R1 을 닫지 못한다; 자식이 부모 생존을 보는 것이 유일하게 확실한 방법이고 #18 heartbeat 타이머의 `--watch-pid` 와 같은 계약이다. 지연은 최대 herdr wait 한 번(≤ 60 s)이며 문서(`SKILL.md:51-52`)가 그렇게 말한다. 감시자가 대기 중 만든 herdr 자식은 `--timeout` 으로 스스로 끝나고, 새 테스트 (d) 가 "TERM 받은 래퍼 뒤에 감시자가 30 s 안에 rc 0" 을 고정한다. 기존 bootstrap EXIT trap 과의 합성은 항목 4 로 미루는 것이 맞다(래퍼 흐름 변경).
## 4. M8 좁힘과 r4 (검토 요청 6)
`test_issue30_stall_watch.py:39-40` 이 모듈 마크를 `PROC` 데코레이터로 바꾸고 S6(`/proc` 직접 읽기)에만 붙였다. `box` 기반 시험은 실제 프로세스를 띄우고 `background_children` 의 macOS `ps` 경로를 지나므로 이 호스트에서 **실제 검증**이 된다(1회차에 내가 손으로 확인한 경로). r4 의 stub 시계 `monotonic → time`: stub 프로세스와 판정 프로세스가 서로 다른 프로세스라 macOS 의 프로세스별 monotonic 기준점 차이를 피하는 것이 맞다(codex 지적 타당).
## 5. 1회차 내 항목의 처리
| # | 1회차 항목 | 이번 델타 |
|---|---|---|
| N1 | 래퍼가 감시자를 기다리며 영구 정지 | **닫힘** — 유계 stop + `--watch-pid` + 테스트 (a)(b)(d) |
| M1 | 유예 루프의 시계 판정이 bash | 열림 → #17 항목 4 목록(PR 명시) |
| M2 | 감시 여부 판정이 bash | 열림 → 항목 4 |
| M3 | 감시자 수명이 래퍼 정상 경로에만 묶임 | **닫힘** — `--watch-pid` |
| M4 | `MAM_JOB_TIMEOUT_S` 오류 시 러너 무언 | 열림 → 항목 4 |
| M5 | "before v4.7.5" | **닫힘** — v4.8.0 |
| M6 | `MAM_WAIT_GRACE_S` 미문서 | 열림 → 항목 4 목록(PR 명시) |
| M7 | `MAM_TEST_UNRELIABLE_AGENT` 훅 | 열림(후속, 사유 타당) |
| M8 | 모듈 전체 Linux skip | **닫힘** — S6 만 |
| M9 | B3 의 공개 브로커 의존 | 열림(후속; "started 자체가 안 닿는 경우" 라는 진단에 동의 — 로컬 events.log 로 heartbeat 를 넣는 방식이 남은 선택지) |
## 6. 테스트 (검토 요청 3 + 검증 방법)
### 6-1. 이 잡의 검증 경로에서의 실행 (브리프의 명령 그대로, pr-41 `.venv` 인터프리터)
```
tests/test_issue30_stall_watch_stop.py tests/test_issue30_stall_watch.py tests/test_issue14_delivery_ack.py tests/test_tier1_unit.py
→ 1 failed, 132 passed, 1 skipped in 589.33s (0:09:49)
FAILED test_issue30_stall_watch.py::test_s9_the_wrapper_runs_the_watcher_for_the_jobs_life[0]
SKIPPED test_issue30_stall_watch.py:331 (S6, real process trees via /proc)
```
- **새 stop 테스트 7건 전부 통과**, `test_issue30` 는 M8 좁힘대로 S6 하나만 skip 이고 나머지(box 기반 S1–S5·S7·S8·S13, R1–R4 포함)가 이 호스트에서 **실제로 돈다**. 1회차에서 멈췄던 `test_issue14::test_wrapper_honours_registry_ack_over_unconfirmed_inject` 는 합동·단독 모두 통과 — **N1 재현 없음**.
- **S9[0] 실패는 공개 브로커 flake** 다: 단언은 `t18._publish(... "started").returncode == 0` 이고 stderr 는 `publish failed after 2 attempts: no CONNACK from broker`. S9 는 `_live_broker()` 로 **일부러** 공개 브로커를 쓰며(래퍼 구독자가 와이어를 봐야 하므로), 진짜 도달 불가 브로커(127.0.0.1:9)에 대해 `publish_event` 는 6/6 회 rc 2 를 돌려준다 — 즉 0 을 기대하는 이 단언은 브로커가 응답할 때만 성립한다. 같은 세 시험(S9[0]·R2[True]·issue14 pane_busy)을 단독으로 다시 돌리자 그 셋은 통과하고 이번엔 **R2[False]** 가 같은 `no CONNACK` 로 실패했다 — 어느 케이스가 걸리는지가 브로커 응답 여부로 바뀌는 전형적 T-1 이다. `publish_event` 는 이 델타가 건드리지 않았다(P2).
- 같은 트리(1673818..af0a2a2 는 동일 tree `0310682`)에 대한 직전 잡 `ce114c80` 의 실행(취소 전 완료)도 130 passed / 3 failed(S9[0]·R2[True]·issue14 pane_busy — 전부 위 부류) / 1 skipped 로 같은 그림이었다.
### 6-2. 수정 없이는 실패하는가 — 확인함
사본에서 래퍼와 `stall_watch.py` 만 `1673818` 판으로 되돌리고 `test_issue30_stall_watch_stop.py` 를 돌린 결과 **7 failed / 0 passed (134 s)** — (a)(b)(c)(d) 는 `TimeoutExpired`, (e)(f)(g) 는 AssertionError. 되돌린 실행이 남긴 프로세스는 없었다(대역·shim 은 테스트가 정리).
### 6-3. 결정성·잔류 (검토 요청 3)
- (a) 대역은 `kill -9` 로, (b) shim 은 래퍼가, (c)(d) 의 `sleep 300`/감시자는 테스트의 `finally` 가 죽인다 — 두 번의 전체 실행과 되돌린 실행 뒤 **`stall_watch --job`/`sleep 300` 잔류 0**(호스트에 남은 `lib_py` 프로세스는 오케스트레이터의 루프 러너뿐).
- 시간 상한은 (a) 4–12 s, (b) 40 s, (c)(d) 30 s 로 stop 의 5 s 폴링과 감시자의 최대 60 s wait 를 넉넉히 감싼다. 이번 실행에서 stop 테스트들은 상위 8 느린 시험에 들지 않았다.
- 실제 `.mam/jobs` 전후: 이 잡 자신의 heartbeat/레코드 파일 외 **추가 0**. 검증 경로 tracked 파일 변화 없음(HEAD `af0a2a2`), 본 체크아웃 `main 8ea65bb`.
## 7. 판정
N1(래퍼 영구 정지)은 유계 stop(실측 6 s)과 `--watch-pid`(부모 소멸 시 자진 종료)로 **양쪽에서** 닫혔고, R2 는 prompt 앞 두 겹 재검사로 닫혔으며, R1 은 `--watch-pid` 만으로 닫은 판단이 맞다. 1회차 판정을 뒤집을 요소는 없고, 델타 밖의 남은 항목(M1/M2/M4/M6 → 항목 4, M7·M9 후속)은 PR 이 명시했다. 버전 락스텝 bump 는 브리프대로 판정에서 제외한다.
| # | 비차단 관찰 | 근거 |
|---|---|---|
| P1 | 감시자가 부모 소멸을 알아채는 지연이 최대 herdr wait 한 번(≤ 60 s)이라 문서와 일치하지만, idle 상태에서는 wait 가 30 s 단위라 실제 지연은 그보다 짧고 `blocked`/`working` 대기(60 s)에서 가장 길다 | `stall_watch.py:276-283`; 정보 |
| P2 | S9/R2 가 공개 브로커에 의존해 `no CONNACK` 로 간헐 실패한다(이 호스트 3회 실행 중 매번 1–3건). `_live_broker()` 가 설계라면 rc 0 대신 로컬 `events.log` 의 `started` 줄로 단언하거나 rc 2 를 허용하는 편이 결정적 | `test_issue30_stall_watch.py` S9 `_publish(...).returncode == 0`; T-1 부류 |
## 8. 교차검증 가이드
```bash
RP=/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20260926T052018Z-597343/1
PY=/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux-wt/pr-41/.venv/bin/python
git -C "$RP" rev-parse HEAD 'HEAD^{tree}' # af0a2a2… / 0310682…
# stop_stall_watch 만 추출해 TERM 무시 대역에 → 6 s 안에 "ignored TERM; killed" 후 반환 (§1 표)
# _alive: 살아있는 자식 True / pid 1 True(권한) / reaped False (in-process)
# 되돌린 사본: 래퍼·stall_watch.py 를 1673818 판으로 → tests/test_issue30_stall_watch_stop.py → 7 failed
(cd "$RP" && AGENT_PYTHON_BIN="$PY" PYTHONDONTWRITEBYTECODE=1 "$PY" -m pytest -p no:cacheprovider -q --basetemp=/tmp/bt \
tests/test_issue30_stall_watch_stop.py tests/test_issue30_stall_watch.py tests/test_issue14_delivery_ack.py tests/test_tier1_unit.py)
```
[VERDICT: PASS]
@@ -0,0 +1,76 @@
# 🔍 Review Report — Job 2d3f24e4 (branch `fix/issue-9-14`, HEAD `ebe58f6`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-09-13
- **대상**: `git log 4d444ce..HEAD` 9커밋 — `497633f`, `16376c5`, `4b31345`, `eaa49aa`, `0918917`(release v4.4.2), `7c40bf4`, `d5a191c`, `952657e`, **`ebe58f6`**(이번 라운드 신규). 이전 라운드에서 본 커밋은 변경분만 재확인하고, `ebe58f6` 는 전체를 검토했다.
- **방법**: 코드 정독, `events.log` 소비자 전수 확인, 선택 테스트(부하 없는 단독 실행) + publish 계약 스위트. 리뷰 중 45초 간격 `progress` heartbeat 발행. 코드 수정 없음.
## 0. 직전 라운드(HEAD `952657e`) 결과와 처리
| 리뷰어 | 판정 | 요지 |
|---|---|---|
| `planner-reviewer-claude-01`(`9323564c`) | PASS | 벽시계 경계 확인, t1_20 부하 민감성 권고 |
| `reviewer-agy-01`(`f191b557`) | PASS | — |
| `reviewer-grok-01`(`b0591d20`) | **NOT PASS** | `publish_event.py` 가 heartbeat 를 **와이어 발행(브로커 ACK·재시도) 뒤에** `events.log` 에 기록 → R1 의 디스크 근거가 늦게 도착해 살아 있는 잡이 `deadline_timeout` 으로 닫힘. 실제 `publish_event` 경로 테스트가 2/2 실패 |
| `planner-reviewer-codex-01`(`e657c660`) | **리뷰 없음** | 구독자가 120 s 동안 이벤트 0건(`idle timeout … still pending`) 후 `deadline_timeout`. codex 가 `started` 조차 발행하지 않았으므로 heartbeat 순서 문제와는 무관 |
creator 는 grok 지적을 반론 없이 수용해 `ebe58f6` 로 고쳤다. `952657e` 에서 새 순서 테스트 2건과 grok 의 테스트가 실패함을 역검증했고, 수정 후 grok 의 테스트는 무변경으로 3/3 통과했다.
## 1. `ebe58f6` 검토 — ✅
### 1-1. 순서와 중복 방지
- **CLI `publish_event.main`**:
1. token·attempt 검증 — 불일치는 rc 4 로 거부되며 **기록되지 않는다**(`publish_event.py:290-341`)
2. `prepare_event`(seq 소비)(`:343-356`)
3. **`record_local_event`**(`:360`) → `registry.append_event`(`:165-175`)
4. `with_retry(_publish_once)`(`:364-376`)
5. `record_outcome(..., local_event_recorded=True)`(`:385-388`) — 감사 로그 `published` 항목과 상태 동기화만 발행 뒤에 수행하고, `events.log` append 는 건너뛴다(`:204-205`)
- **`DelegationService.publish_event`**: 같은 순서다(`service.py:82-100`).
- **다른 호출자**:
- `record_outcome` 의 기본값은 `local_event_recorded=False` 라서 직접 호출하는 테스트(G-1/G-2/G-4)는 동작이 그대로다.
- `prepare_event` 의 유일한 다른 호출자 `bench.py:149` 는 원래 `events.log` 를 쓰지 않았으므로 영향이 없다.
- 새 테스트가 "발행 시작 순간 이미 1줄", "재시도 2회에도 1줄 + 감사 `published=False`"를 단정한다.
### 1-2. `events.log` 소비자 영향
- **`_recent_disk_heartbeat`(래퍼)**: 의도한 수혜자다. 브로커 지연(실측 약 5 s/발행)과 무관하게 heartbeat 가 즉시 디스크에 보인다.
- **`registry.get_feedback` 폴백(`registry.py:241-260`)**: 감사 ndjson 에 terminal 이벤트가 없을 때만 `events.log` 에서 detail 을 읽는다. 호출 시점이 잡 종료 이후이고, 기록 **내용**은 이전과 같다(CAS 로 거부된 terminal 이벤트도 원래 기록되었다). 달라진 것은 시점뿐이다.
- **그 밖의 소비자**: 셸·파이썬 전수 grep 결과 없다. 상태의 권위는 계속 레지스트리 레코드(`_disk_status`)다.
### 1-3. 의도된 의미 변화 (creator 문서화)
- 발행 도중 프로세스가 죽으면 `events.log` 에는 줄이 남지만 감사 `published` 항목과 상태 동기화는 없다.
- terminal 이벤트라면 `events.log` 에 `completed` 가 있어도 레코드는 아직 비종료일 수 있다. R1 은 이를 **liveness 근거로만** 쓰고 결과는 레코드에서 읽으므로 잘못된 완료 판정으로 이어지지 않는다.
## 2. 검증 항목별 결과
| # | 항목 | 결과 |
|---|---|---|
| (1) | 서버 env denylist | ✅ 무변경(1회차 판단 유지, 호스트 마커 권고는 비차단) |
| (2) | `MAM_NO_AUTOSTART` · `ls` 번역 | ✅ 무변경(`952657e` 에서 확인한 구조화 판정·unknown 종료 유지) |
| (3) | `send_keys_safe` | ✅ 무변경 |
| (4) | `_inject_acknowledged` · `_agent_still_working` · `_recent_disk_heartbeat` · R1 창 | ✅ 벽시계 경계(`952657e`)는 그대로다. 이번 커밋으로 heartbeat 가 발행 **전에** 디스크에 기록되어 grok 이 재현한 미탐이 사라졌다(해당 테스트가 이번 실행에서 통과) |
| (5) | T1-7 트리거 | ✅ 무변경 |
| (6) | 버전 락스텝 · 릴리스 커밋 | ✅ `lib.sh:32`·`eager.py:16` = 4.4.2. `VERSIONS.md` 항목 6 이 "와이어 발행 **전** 로컬 기록(CLI·service 두 경로)"으로 코드와 일치. "신규 테스트 21개" = `test_issue9_server_env.py` 9 + `test_issue14_delivery_ack.py` 12 함수(직접 셈) |
| (7) | 테스트 · 정적 검사 | ✅ 아래 |
- **선택 실행 11파일**(부하 없이 단독): **163 passed in 431 s**
- 대상: `test_issue9_server_env`, `test_issue14_delivery_ack`, `test_issue6_fail_closed`, `test_issue6_turn_handshake`, `test_a4_adapter_contract`, `test_loop_cli`, `test_issue5_phase4_runtime`, `test_version_consistency`, `test_herdr_shim_contract`, `test_b19_headless_reconcile_fixes`, `test_deploy_registry_merge`
- grok 의 `test_wrapper_idle_timeout_grace_accepts_disk_heartbeat`, 새 순서 테스트 2건, 직전 라운드에 부하 속에서 한 번 실패했던 `test_t1_20` 모두 통과
- **publish 계약 스위트** `tests/test_issue5_phase1_delegation.py`(G-1/G-2/G-4, transport parity, `record_outcome` 직접 호출): **66 passed**(주 실행이 끝난 뒤 따로 실행)
- **정적 검사**: `py_compile`(publish_event·service), `bash -n`(lib.sh·래퍼·status.sh·reconcile.sh), `git diff --check 4d444ce...HEAD` 모두 클린. 작업 트리 깨끗, HEAD `ebe58f6`.
## 3. 비차단 권고
1. **`events.log` 의미 명시**: 이제 이 파일은 "수락된 상태"가 아니라 "시도된 이벤트"의 기록이다(발행 전 기록, CAS 거부분 포함). `MESSAGING.md` 나 `registry.append_event` docstring 에 한 줄 적어 두면, 이후 이 파일을 상태 판단에 쓰는 코드가 생기는 것을 막을 수 있다.
2. **t1_20 예산**(직전 라운드 권고, 미반영): 이번 부하 없는 실행에서는 통과했지만 `--timeout 12` 는 부하가 걸린 CI 에서 여전히 간헐 실패할 수 있다. 20–25 s 로 늘리기를 권한다.
3. **loop 모드 마감 서술**(직전 라운드 권고, 미반영): `START_TIME` 은 `cmd_submit` 에서 한 번만 정해진다(`:166-167`). 주석의 "this dispatch's deadline" 은 loop 모드에서 "이 래퍼 실행의 마감"이 정확하다.
4. 보류된 후속 항목 묶음(호스트 마커, `$WRAPPER` 경로, pane 변화 신호, ack dispatch 고정, heartbeat token 필터, `_within_deadline` 의 `Terminated` 표시 잡음)은 변동이 없다. 하나의 후속 이슈로 모으기를 권한다.
## 4. GM 참고
- **codex 는 `952657e`·`ebe58f6` 를 리뷰하지 않았다.** 마지막 codex 판정은 `d5a191c` 에 대한 NOT PASS(`75c1d06c`)였고, 그 두 지적은 `952657e` 에서 해소되었다(본 세션 확인). `e657c660` 은 codex 가 이벤트를 하나도 발행하지 않은 채 닫혔다. 병합 전에 codex 세션 상태를 확인하고 재리뷰할지 결정할 것을 권한다.
## 5. 종합
- `ebe58f6` 는 grok 의 차단 지적(디스크 heartbeat 가 브로커 지연 뒤에 기록됨)을 정확한 위치에서 최소 변경으로 고쳤다. 검증 우선·seq·G-1/G-2/G-4 계약을 유지하고, 중복 기록이 없으며, `events.log` 소비자에도 부작용이 없다.
- 브랜치 전체가 브리프의 7개 검증 항목을 충족하고, 부하 없는 선택 실행 163건과 계약 스위트 66건이 모두 통과했다. 설계 재검토는 필요 없다.
[VERDICT: PASS]
@@ -0,0 +1,100 @@
# 리뷰 리포트 — Job 2f19fe7f (PR #46, fix/issue-42 단계 1·2)
- 리뷰어: planner-reviewer-claude-01 (claude)
- 리뷰 identity: loop-20261003T222707Z-a0de27 / base 45d1621 / head 8d26106 / tree b579380 — 검증 경로에서 `git rev-parse HEAD 'HEAD^{tree}'` 로 일치 확인, 미커밋 변경 없음
- 커밋: 7670b41(단계 1·2), e6a46cd(R1: stop exit 1 이 stop 뒤에도 남), 8d26106(R2: passthrough 코드는 표에 있어야 함)
## 결론 요약
차단 결함 없음. 지운 (a) 블록 5개는 모두 진입 스크립트가 그대로 하는 일이고, 새 옵션·종료 코드 표와 "정정" 다섯 곳은 스크립트 코드 및 샌드박스 실행 결과와 일치한다. 제품 코드 변경 없음. 비차단 관찰 4건(아래 §6).
## 1. 분류의 정확성
### resume Workflow (base resume SKILL.md:59-118) → resume_session.sh
| 지운 단계 | 스크립트 위치 |
|---|---|
| 세션 ID 해석 (`resolve_session_id.sh --session`) | resume_session.sh:111-112 |
| Class A fresh-spawn 폴백 / claude·grok exit 1 | :122-130 (spawn-spec :173-184) |
| HERDR_SESSION_NAME·MAM_WS_LABEL 해석 | :132-144 |
| herdr alive 분기 | :147-158 — **attach 하지 않고** `update_yaml_resumed.sh` 후 exit 0 |
| CMD_FULL (에이전트별) | :185-197 (adapter resume-spec + 동일 표 폴백) |
| 기동 | :237 `_herdr new-session` |
| handle_startup_dialogs | :241 |
| update_yaml_resumed.sh | :247-250 |
| attach | **스크립트에 없음** |
attach 만 스크립트에 없는 단계(= (b))인데, 문서는 이를 지우지 않고 "It never attaches; attaching is a separate step: `herdr agent attach <name>`" 로 남겼다(resume SKILL.md Workflow 아래 문단, Case 3 정정). 따라서 절차 유실 없음. 문서에만 있던 `$CLAUDE_ID_FLAG`(정의되지 않은 변수)도 함께 사라졌다(인벤토리 mismatch R4) — 정정이 맞다.
### stop pre-flight (base stop:38-63) → stop_session.sh
YAML 존재 :99(exit 1), 등록 확인 :127-143(exit 1), 이미 stopped no-op :184-188(exit 0). 문서에만 있던 `--force-no-yaml` 은 어떤 스크립트도 받지 않는다(:76-90 파서에 없음) — 삭제가 맞다.
### create pre-flight (base create:35-52) → create_session.sh
워크스페이스 :111, has_real_herdr :114, CLI in PATH :115, 인증 :117-157(선택된 에이전트만). B-3 함정(command -v / type -P) 설명은 산문으로 보존.
### create Workflow (base create:168-220) → create_session.sh
이미 존재 :166-168(**exit 3**, 문서는 1이었음), spawn-spec :207, spawn :252-276, TUI 대기 :361-398(exit 42), 롤백 trap :320-352(exit 43). `sleep 6` 하드코딩과 claude 무플래그 기동은 문서 쪽 오류였다.
### create YAML 수동 추가 (base create:226-252)
행 기록은 create_session.sh:491-610 heredoc 이 한다. lib.sh shim 주석은 Output format 아래 산문으로 이동.
### (b) 로 남은 블록 5개
create:217·resume:103·stop:127 (사후 확인), monitor:182 (에이전트 폴링 지침), status:30 (status.sh 에 has_real_herdr 검사가 없음 — status.sh:22 는 YAML 만). 각 스크립트를 grep 해 같은 명령을 제공하는 진입점이 없음을 확인했다. 3단계 입력으로 타당하다.
### 블록 수 대조
base 의 펜스 블록을 테스트의 `parse_blocks` 로 세면 37개(create 11, delegate-job 1, loop 5, monitor 7, orc-onboard 2, resume 2, status 4, stop 5). 지운 (a) 5개의 base_start/base_sha 는 모두 base 와 일치한다. 현재 33개 = 37 − 5(a) − 1 + 2(새 Workflow 호출 블록). 이 "− 1"은 관찰 O1 참고.
## 2. 옵션·종료 코드 표 대조
- create 옵션 표 ↔ 파서 create_session.sh:76-92: 12개 항목 모두 일치(별칭 `--name`, `--herdr-server` 포함; `--isolate` no-op :89-90; `--wrapper` 는 :257 에서 존재 여부와 무관하게 강제).
- create 종료: 1 = :111-156 사전 검사 + :636·:659 (spawn 뒤 브리프/주입 실패, trap 롤백); 2 = :92-110 인자, :234 바인딩 거부, :245 공백; 3 = :168; 4 = heredoc `raise SystemExit(4)` :515 (중복 running 행, set -e 로 통과 → trap 롤백); 42 = :398; 43 = :348.
- resume 옵션 표 ↔ :37-46 일치. 종료 0 = :150·:158(alive, attach 없음)·:227(dry-run)·정상 종료; 1 = :128·:204·:209 + update_yaml_resumed.sh:47; 2 = :46-56·:73·:77·:104·:221 + update_yaml_resumed.sh:42-46·:74.
- stop 종료 0 = :188; 1 = :99·:142 + heredoc :310(R7); 2 = :86·:89·:95·:98·:121; 3 = :198; 4 = :281.
- status `--json` 키: reconcile.sh:1081-1088 의 6개 최상위 키 + status.sh:213-232 의 sessions_detail 17개 키와 정확히 일치. resume_state 값 yes/MISSING/scan/no 도 status.sh 의 resume_on_disk 반환값과 일치.
샌드박스 실행(임시 HOME·WORKSPACE_ROOT·AGENT_SESSIONS_YAML, `env -i`, herdr 미호출 경로만):
| 실행 | rc | 표 |
|---|---|---|
| stop `--purge-conversation` (no --yes) | 3 | 3 ✓ |
| stop 미등록 세션 | 1 | 1 ✓ |
| stop `--mode x` | 2 | 2 ✓ |
| resume 원래 cwd 없음 `--dry-run` | 2 | 2 ✓ |
| create 없는 워크스페이스 | 1 | 1 ✓ |
| create `--agent foo` | 2 | 2 ✓ |
샌드박스 YAML 은 변경되지 않았다.
## 3. 문서만으로 같은 작업이 가능한가
- 세 진입점 모두 호출 한 줄에 필수 옵션이 표시되어 있고, 지운 절차는 전부 스크립트 안에 있으므로 호출 한 줄로 충분하다.
- 사람이 판단할 지점은 보존·강화됐다: stop 예제가 `--purge-conversation --yes` 로 바뀌면서 "되돌릴 수 없다, 사용자가 확인한 뒤에만 `--yes`" 문장이 추가됐다(실제로 --yes 없으면 exit 3 이므로 이전 예제는 동작하지 않았다).
- resume 은 spawn 뒤 실패 시 롤백하지 않는다는 점과 `multi-agent-mux-status` 로 먼저 확인하라는 복구 지침이 새로 들어갔다(resume_session.sh 에 trap 없음 — 사실과 일치). stop 표 아래 복구 문단도 같다.
## 4. 문서 가드 테스트 견고성
스크래치 사본에서 변이 시험:
| 변이 | 결과 |
|---|---|
| create `exit 43`→`exit 44` | 2 failed ✓ |
| create `exit 42` 제거(표 행이 낡음) | 2 failed ✓ |
| 주석 `# exit 9` 추가 | 통과 ✓ (주석 제외 규칙) |
| 실제 `exit 9` 추가 | 2 failed ✓ |
| stop 표의 3 행 삭제 | 2 failed ✓ |
| stop 예제의 `--yes` 제거 | 1 failed ✓ |
| base 의 create pre-flight 블록 되살림 | 1 failed ✓ |
| stop SKILL.md 블록 위에 산문 한 줄 추가(정상 편집) | 1 failed (관찰 O2) |
| `$(( 1 << 2 ))` 뒤 `exit 9` | 통과 ✗ (관찰 O3) |
추출 규칙: `(?<![\w.])exit\s+(\d+)` 은 `sys.exit(7)`(stop:139) 을 세지 않고, heredoc 본문은 `SystemExit(N)` 만 passthrough 로 모은다. `<<<` here-string 은 lookbehind 로 제외된다. 기존 가드 test_tier2_component.py::test_comp_docs_stop_examples_pass_agent(stop 예제 ≥3, 모두 --agent)는 아래 테스트 실행에서 통과한다.
## 5. 범위
`git diff --stat 45d1621 8d26106`: SKILL.md 4개 + tests/data/skill_code_blocks.json + tests/test_issue42_skill_blocks.py. 스크립트·Python·버전 파일 변경 없음(버전 bump 없음).
## 6. 비차단 관찰
- **O1 인벤토리 누락 1건**: base create SKILL.md:263-266 의 (c) 호출 블록(`create_session.sh … --session "$SESSION_NAME"`, sha ceb96a8c1293)이 지워졌지만 skill_code_blocks.json 의 blocks·removed 어디에도 없다. 내용은 새 Workflow 호출 블록이 대체하므로 정보 유실은 없지만, "37개를 분류했다"는 데이터는 실제로 36개만 다룬다. 가드는 현재 블록만 비교하므로 잡지 못한다. removed 에 class "c" 로 기록하거나 test_no_duplicate_block_left 의 `class == "a"` 를 완화하는 정리를 권한다.
- **O2 줄 번호 결합**: 인벤토리가 start/end 줄 번호를 고정하므로 블록 위에 산문 한 줄만 넣어도 실패한다. 실패 메시지가 실제 튜플을 출력해 갱신은 기계적이지만, 3단계에서 산문 편집이 잦다면 sha+순서만 비교하거나 재생성 스크립트를 두는 편이 낫다.
- **O3 산술 시프트 오인**: `_HEREDOC` 이 `$(( 1 << 2 ))` 를 heredoc 시작으로 읽어 이후 모든 줄을 건너뛴다. 현재 세 진입 스크립트에는 이 패턴이 없어(grep 확인) 실제 영향은 없다.
- **O4 표 세부 문구**: (a) create exit 42 는 "프로세스가 사라짐" 외에 `MAM_KILL_ON_READY_TIMEOUT=1` 이면 살아 있어도 42 (create_session.sh:388-398). (b) stop "이미 stopped 면 no-op" 은 `--purge-conversation` 이 아닐 때만(:185). (c) resume 문서의 "lines 50-223" 은 사전 검사의 실제 범위(:50-221)와 대략 맞다. 모두 문서 정밀도 수준이다.
## 7. 항목 6 — purge 기준 실패
이 호스트에서 검증 경로의 tests/test_issue10_13_purge.py: **23 passed**. 이 PR 은 제품 코드를 바꾸지 않으므로 Linux 의 12건(#28)과 무관하다. "알려진 기준 실패" 표현은 Linux 기준이라는 한정이 필요하다.
## 8. 테스트
지정 6개 파일(test_issue42_skill_blocks, test_tier2_component, test_orc_onboard, test_loop_cli, test_o1_rebuttal, test_version_consistency): **129 passed / 0 failed / 1 skipped** (296 s, rc 0). skip 은 test_claude_skills_link_resolves_to_agents_skills(워크트리에 .claude/skills 없음 — 브리프상 정상). test_issue42_skill_blocks.py 단독: 28 passed / 1 skipped.
외부 브로커 미사용(MQTT_* unset, .mam.env 미export). 실제 .mam/jobs 항목 수 변화: +0 (이 잡 디렉터리 외 생성 없음).
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261001T230324Z-b511bf",
"base_sha": "0051fd6c3b088f8b265928ccd94ea31053fdde7e",
"head_sha": "75f364e4b47d8db95ce2a7e041b69b8e8b473e64",
"tree_sha": "ec1fdc453ec6fdf2c09165c92a64d54e684f5a3a",
"review_commit": "75f364e4b47d8db95ce2a7e041b69b8e8b473e64",
"reviewer": "planner-reviewer-claude-01",
"job_id": "31a04751",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-02T00:58:55Z"
}
@@ -0,0 +1,38 @@
# 🔍 Review Report — 후속 `fix/followups-41-43` 2회차 (job `31a04751`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-10-02
- **대상**: `0051fd6..75f364e`(9커밋). 1회차(`95eabc6`, 내 판정 PASS — job `76ca3b1b`) 이후 델타는 `75f364e` 1커밋(3파일 `+41/−2`, `git diff --check` 클린).
- **검증 경로**: `/var/folders/.../T/mam-review/loop-20261001T230324Z-b511bf/2`. **identity 확인**: `HEAD = 75f364e4…3e64`, `HEAD^{tree} = ec1fdc45…5a3a` — 브리프와 일치.
- **안전 규칙 준수**: 검증 경로·소스 워크트리·본 체크아웃(`main 0051fd6`) 수정·커밋·checkout 없음. 되돌린 사본은 scratchpad 에서만. 실제 `.mam.env` 를 읽거나 출력·export 하지 않음. 실제 `.mam`·데몬·세션·herdr 조작 없음, push·merge·PR 상태 변경 없음.
## 결론 요약
**델타는 codex R1(실패한 env 로드가 "로드됨" 으로 캐시됨)을 정확히 닫고, 1회차 판정(F1–F6 완료, PASS)을 뒤집을 요소는 없다.** 1회차 내 리포트의 F1–F6 판단은 이 트리에도 그대로 유효하다 — 델타가 F2 의 `mqtt_common.py` 두 줄, MESSAGING.md 한 줄, 테스트 1건뿐이기 때문이다.
## 1. 75f364e — 실패한 로드를 캐시하지 않음 (`mqtt_common.py:128`)
- **결함(codex R1)**: F2 에서 `load_env_or_report()` 가 프로세스를 끝내지 않고 False 를 돌려주게 되자, `ensure_env_loaded()` 가 `_load_dotenv()` **이전에** `_env_loaded = True` 를 세우던 순서가 문제가 됐다. 한 프로세스 안에서 두 번째 `main()` 은 "이미 로드됨" 으로 보고 **설정 없이** 진행했다.
- **수정**: 플래그를 `_load_dotenv()` **뒤로** 옮겨, 성공한 로드만 캐시한다. `EnvFileError` 가 나면 플래그는 거짓으로 남아 다음 호출이 파일을 다시 읽는다.
- **수정 없이는 실패하는가 — 확인함**: 사본에서 `mqtt_common.py` 만 `95eabc6` 판으로 되돌리고 새 `test_a1_a_failed_load_is_not_cached_as_loaded` 를 돌리면 실패한다. 실패 내용이 결함 그대로다: `rc: [1, 0]`(두 번째 `registry.main` 이 rc 0), `registered: ['<job>.json']`(**설정 없이 잡을 등록**), `recovered: [True, None]`(고친 파일도 다시 읽지 않음). 새 코드에서는 `rc [1, 1]`·등록 0건·두 번 모두 한 줄 `ERROR`·고친 파일 읽힘·성공 뒤 캐시 유지(바꾼 파일을 다시 읽지 않음)를 모두 단언한다.
- **부분 적용 여부**: `envfile.parse` 는 파일 전체를 먼저 읽고 디코딩한 뒤에만 값을 넣으므로, 실패한 로드가 환경을 절반만 바꾸는 일은 없다. `.mam.env` 와 옛 `.env` 가 함께 있으면 `_load_dotenv` 는 `.mam.env` 하나만 읽는다. 따라서 재시도 때 두 파일이 섞이는 경로도 없다.
- **MESSAGING.md:369**: 문장 끝을 실제 동작(파일 없음 → 조용히 건너뜀, 있는데 못 읽음 → 진입점이 `ERROR` 한 줄 + rc 1)에 맞춘 문구 정리.
## 2. 테스트
```
tests/test_issue26_envfile.py tests/test_issue26_ints.py tests/test_issue21_acceptance.py tests/test_issue30_stall_watch.py
tests/test_issue30_stall_watch_stop.py tests/test_tier1_unit.py tests/test_version_consistency.py
tests/test_issue5_phase1_delegation.py tests/test_issue19_subscriber_daemon_lifecycle.py
(.mam.env 미export, MQTT_* 미설정, followups .venv)
→ 352 passed, 1 skipped in 488.95s failed 0 (skip = S6, /proc)
```
- 브리프 목록 7파일에 두 파일을 더했다. `test_issue5_phase1_delegation.py` 는 CLI 스냅샷이고, `test_issue19_subscriber_daemon_lifecycle.py` 는 F4b 로 바뀐 `reconcile.sh` 의 `RECONCILE_POLL_INTERVAL` 을 거치는 구독자 데몬 수명 시험이다.
- 로그에 외부 브로커 흔적 0건.
- 실제 `.mam/jobs` 는 이 잡 자신의 파일 외 **추가 0**. 검증 경로 tracked 파일 변화 없음(HEAD `75f364e`), 본 체크아웃 `main 0051fd6`.
## 3. 판정
1회차 비차단 관찰(T1 `test_o2` 의 미사용 `get_lstart`, T2 reconcile 내장 구독자의 트레이스백, T3 설치 확인 목록)은 범위 밖으로 그대로 열려 있다. 버전 bump 는 판정에서 제외한다. 병합을 막을 결함은 없다.
[VERDICT: PASS]
@@ -0,0 +1,50 @@
# 🔍 Cross-Review — Version Update Assessment for Issue #3 Fix (Job `39439652`)
- **Reviewer**: `planner-reviewer-claude-01`
- **Target**: `.agents/reports/creator-agy-01/version-update-assessment.md` — an analysis-only deliverable (no version/code files touched, per its own §1 requirement) determining whether and to what version the already-committed Issue #3 fixes (`c49ee3b`, `7e15081`) should bump.
- **Method**: independently re-verified every factual claim against live git history and the current repo state — I authored/implemented and already exhaustively reviewed the underlying code changes this report is assessing (jobs `a9c8d6d3`, `398afb2e`), so my focus here is the version-classification judgment and the report's own factual citations, not re-deriving the code's correctness from scratch.
---
## 1. Scope compliance
`git status` shows exactly one new file (`version-update-assessment.md`) — no `lib.sh`, `VERSIONS.md`, or `SKILL.md` touched. Correctly honors the brief's explicit "do not modify version files yet" constraint.
## 2. Commit-citation accuracy
Verified both cited commits directly via `git show --stat`:
- `c49ee3b` — "fix(herdr): detach daemon bootstrap into own process group via python spawner" — matches the report's Item 1 description exactly (file list: `lib.sh` + `test_herdr_shim_contract.py`, +61/-3... consistent with the `nohup`→`Popen` swap and `test_h26`).
- `7e15081` — "fix(resume): allow fresh spawn fallback and refresh epoch on 0-turn Class A resume" — matches Item 2 exactly (file list: `resume_session.sh` + `update_yaml_resumed.sh` + `test_uuid_target.py`, consistent with `test_t14`/`t15`/`t16`).
Both commits are real, on `main`, authored by the same identity as this session, and match the report's descriptions precisely — no fabricated or mischaracterized history.
## 3. SemVer classification — sound
Independently re-derived the same conclusion before reading the report's own table, then compared: no public CLI flag, YAML schema surface, or adapter interface was removed or made incompatible (MAJOR correctly excluded); no new agent adapter, skill, or subsystem was added — only an internal branch that turns a previously-hard-failing input into a successful one, which is squarely "internal change that fixes incorrect behavior" under SemVer 2.0.0 §6 (MINOR correctly excluded, PATCH correctly selected). I also checked the one subtlety worth checking — whether making a previously RC=1 case now RC=0 could itself be considered a breaking behavior change for a caller relying on the failure — but no other script in the codebase depends on `resume_session.sh`'s old hard-fail for this specific 0-turn case (confirmed in job `a9c8d6d3`'s original implementation review), so this doesn't push the classification toward MAJOR. **`v4.1.3` PATCH is the correct target.**
## 4. Lockstep touchpoint accuracy
- `lib.sh:32` (not the report's cited line 16, but functionally the same single-line constant — the report cites an older/different line reference; the field itself and its value are correct) — re-checked: `MAM_VERSION="4.1.2"` is the current baseline, confirming the proposed `"4.1.3"` bump target is a clean +1 patch.
- `VERSIONS.md` lines 9-10 and the 8-row skill matrix (lines ~23-33) match the report's citations exactly against the live file — I re-read the current file directly rather than trusting the line numbers.
- All 8 `SKILL.md` paths exist and currently read `version: 4.1.2`, confirmed by direct grep against every one of the 8 files listed in §4.3 of the report.
- `tests/test_version_consistency.py::test_three_way_version_lockstep` and `::test_mam_version_is_not_env_overridable` both exist exactly as cited and currently pass at the v4.1.2 baseline (re-ran directly).
One minor, very small citation slip: the report says `lib.sh#L16` for `MAM_VERSION`; the live constant is actually at line 32. Non-blocking — the constant name/value/file are all correct, only the specific line number is off, and it doesn't affect the touchpoint list's completeness or the release-packaging job that will act on it (that job will grep for `MAM_VERSION=`, not hardcode a line number).
## 5. Regression baseline
Re-ran the full suite myself at current HEAD (not trusting the report's "455/455" claim): **455 passed, 0 failed**, 12m06s. Matches exactly.
## 6. Changelog draft quality
The §5 `v4.1.3` changelog draft is accurate to the actual changes (correctly attributes `test_h26`/`test_t14`/`test_t16` to their respective fixes, correctly notes Class B preservation), well-formatted, and consistent with this project's existing changelog style (compare the v4.1.2 entry's structure). No factual errors found in it.
## 7. Minor non-blocking nit
The report embeds several `file:///Users/godopu16/...` absolute local-machine links. Harmless for this session's reviewers (all operating on the same checkout) but not portable if this document is read outside this machine — purely cosmetic, doesn't affect the report's conclusions or the touchpoints it enumerates.
## 8. Verdict
The version-update-assessment report is factually accurate on every commit citation, file/line touchpoint, and test claim I checked, and its SemVer reasoning (v4.1.3 PATCH) is correct and well-argued — independently re-derived by me before cross-checking against the report's own table, with the same result. One trivial line-number citation slip (`lib.sh#L16` vs. the actual `:32`) does not affect the touchpoint list's usability. Full suite reconfirmed green (455/455) at current HEAD. I concur with the report's recommendation: **target `v4.1.3` (PATCH)** for the follow-up release-packaging job, using the enumerated 3-way lockstep touchpoints and the drafted changelog entry.
[VERDICT: PASS]
@@ -0,0 +1,45 @@
# 🔍 Cross-Review — Issue #3 Fix, Including Epoch-Reset Refinement (Job `398afb2e`)
- **Reviewer**: `planner-reviewer-claude-01`
- **Target diff**: cumulative `.agents/skills/lib.sh` + `resume_session.sh` + `update_yaml_resumed.sh` + `test_herdr_shim_contract.py` + `test_uuid_target.py`, plus the full Issue #3 analysis/review report trail (`issue-3-analysis.md` Rev. 3, `plan-a9c8d6d3.md` incl. Rev. 2, and 5 peer-review reports).
- **Method**: this diff bundles code I already implemented (`a9c8d6d3`) and code I already reviewed via reports I already wrote/read — I did not re-trust any of that from memory. The one genuinely new element since my last verification is the epoch-reset fix in `update_yaml_resumed.sh` (implementing my own `8e104b0e` refined-plan spec, presumably by `creator-agy-01`) plus its new test `test_t16`. I verified that specifically, from scratch, against live code and by running it.
---
## 1. Diff fidelity
`git status` shows exactly the files this diff claims changed, nothing undisclosed. I diffed the live `resume_session.sh` byte-for-byte against my own known-good copy from job `a9c8d6d3` — **identical**, confirming Items 1 and 2's core logic is untouched since I last verified it end-to-end (full suite 454/454 at the time).
## 2. Item 1 (daemon `setsid`/PGID detachment) — unchanged, previously verified
No changes since `a9c8d6d3`. Already verified by me directly (live process-table inspection, `test_h26` fail-old/pass-new) and independently by `reviewer-opencode-01` and `reviewer-creator-grok-01` across the analysis peer-review cycle documented in this same diff. Stands.
## 3. Item 2 Class A fallback (`resume_session.sh`) — unchanged, previously verified
Byte-identical to my `a9c8d6d3` implementation (confirmed via direct file diff, not just re-reading). Already verified end-to-end (`test_t14`, `test_t15`, fail-old/pass-new).
## 4. NEW: Epoch-reset fix (`update_yaml_resumed.sh`) — independently verified
This is `creator-agy-01`'s implementation of the refinement I designed in job `8e104b0e` in response to their own architectural challenge (`c4b0a075`) against my original Item 2 fix. I did not assume "matches my spec" — I re-read the live file and checked it line by line:
- The `if not uuid:` block (`update_yaml_resumed.sh:166-177`) is placed exactly where my refined plan specified — after the shared `target['status'] = 'running'` (line 165), so it applies uniformly to both the new-row and existing-row branches, and reuses the already-computed `epoch`/`now` locals (lines 117-118) rather than recomputing anything.
- Gated strictly on `if not uuid:` — the same condition already governing the `last_visible_status` branch two blocks below — so it can only fire on the Class A fresh-spawn path; `claude`/`grok` never reach this function with an empty `--uuid` (confirmed by the untouched `resume_session.sh` diff), so Class B is provably unreachable here.
- `bash -n` clean.
**Verified by running, not just reading**: ran `test_t16_resume_class_a_fresh_spawn_resets_discovery_epoch` — passes. Then, per this session's standing discipline, I reverted *only* this new hunk (removed the `if not uuid:` block, leaving everything else — including Item 1/2 — untouched) and re-ran the test: it **fails** (`herdr_session_epoch was not refreshed`), confirming the test is a genuine regression guard and not a vacuous pass. Restored the fix; re-confirmed `bash -n` and the diff match the original.
**One nuance worth recording, not a defect**: `test_t16` verifies the watermark itself advances (`herdr_session_epoch > initial_epoch`) but doesn't independently re-run `reconcile.sh` against a seeded stale transcript to prove the end-to-end rejection consequence my plan's test spec described. This is an acceptable simplification — the `mtime >= epoch` rejection mechanism itself is already covered elsewhere in the suite (`test_t2`, `test_t4` exercise `reconcile.sh`'s discover-mode epoch logic directly), so re-deriving it here would be redundant; testing that this fix correctly refreshes the watermark is the essential, sufficient unit test for *this* specific change.
## 5. Report-trail integrity (spot-checked, not re-litigated)
The five bundled peer-review reports (`report-9406c304.md` mine, `report-1da8fd5c.md` Grok, `report-7b6c16df.md`/`report-8c093047.md`/`report-d8c851a1.md` OpenCode) document a peer-review history I either authored or have already separately verified in prior jobs this session. I spot-checked the two I hadn't directly read before (`1da8fd5c`, `d8c851a1`) against the actual job registry — both job IDs are real and their `completed` timestamps match what the reports claim. Content is internally consistent with the now-settled conclusion (Item 1 confirmed, Class A confirmed, Class B not-a-defect) that I independently arrived at across `0338e7de`/`9406c304`.
## 6. Full regression sweep
**455 passed, 0 failed**, 11m55s — 454 (prior baseline) + `test_t16` = 455, consistent, no regression anywhere else.
## 7. Verdict
Everything in this diff has now been verified either directly by me in this job (the new epoch-reset fix, with fail-old/pass-new proof) or was already independently verified end-to-end in prior jobs and reconfirmed byte-identical here (Items 1 and 2). No lint, functional, or omission defects. The Issue #3 fix — daemon detachment, Class A fresh-spawn fallback, and the discovery-epoch reset that closes the race the fallback itself introduced — is complete, correctly scoped to leave Class B untouched, and fully test-covered.
[VERDICT: PASS]
@@ -0,0 +1,30 @@
# 리뷰 리포트 — Job 3a93c30b (PR #48 2회차, 35935f9..e8d9151)
- 리뷰어: planner-reviewer-claude-01 (claude)
- 리뷰 identity: loop-20261005T081844Z-e92124 / base c5c7eff / head e8d9151 / tree 8b39188 — 검증 경로에서 `git rev-parse HEAD 'HEAD^{tree}'` 일치, 미커밋 변경 없음
- 범위: 커밋 36f0b8d, e8d9151. `git diff --stat 35935f9 e8d9151`: create SKILL.md 1줄, VERSIONS.md, 테스트 3개. lib.sh·lib_py·스크립트 변경 없음(제품 코드 불변).
## 결론 요약
1회차의 차단 3건(B1~B3)과 문서 지적(D1)이 모두 닫혔다. 이 macOS 호스트(Python 3.9 venv)에서 지정 6개 파일이 실패 없이 통과하고, 실제 herdr 서버 테스트 5개가 skip 없이 돈다. 차단 결함 없음.
## 1. 1회차 지적 종결
| 지적 (1회차) | 수정 | 확인 |
|---|---|---|
| B1 test_issue45_herdr_config.py:16 최상단 `import tomllib` → 3.9 에서 수집 중단 | try/except 로 선택적 import(:18-21), 결과를 파싱하거나 설정 유지를 기대하는 테스트만 `needs_tomllib` skip(:36) | 3.9: 수집 정상, tomllib 의존 검사만 skip. Python 3.11(Homebrew + PYTHONPATH): **51 passed**. 3.9 에서 남는 22건 중 test_without_tomllib_restore_is_still_off(:91-96)가 tomllib 없을 때 MINIMAL + "no tomllib" 경고를 직접 확인하므로 3.9 경로도 검사된다 |
| B2 test_issue45_restore.py `/proc` 와 `/tmp` | 루트 `.resolve()`(:175), 서버 환경은 `/proc` 가 있으면 거기서, 없으면 `ps -E -ww`(:160-169, :239-240) | test_issue45_restore.py 5개 모두 **실행·통과**(skip 아님). 1회차에 내가 스크래치 사본으로 확인한 것과 같은 두 수정이며, 그때 A·B 수정을 끄면 각각 실패함(A: `--resume <id>`, B: pane 2개)을 확인했다. 제품 코드가 그 뒤 바뀌지 않았으므로 대조 결과는 그대로 유효하다 |
| B3 test_issue9_server_env.py:157 tomllib, bootstrap 의 python3 가정 | bootstrap 과 같은 PATH 의 `python3` 로 결과를 파싱, tomllib 이 없으면 키 하나짜리 파일 + `confirm_close` 없음 + 경고 "no tomllib" 를 기대(:169-183) | 통과. 이 호스트에서는 else 분기(3.9)가 실행된다. `subprocess.run(["python3"…], env=env)` 는 POSIX 에서 env 의 PATH 로 실행 파일을 찾으므로 bootstrap 과 같은 인터프리터다. 경고 문구는 herdr_config.py:147 와 일치 |
| D1 (비차단) python3 < 3.11 이면 사용자 설정 없이 뜬다는 문서 부재 | create SKILL.md:120 와 VERSIONS 4.8.5 항목 1, 품질 검증 항목에 추가 | 내용은 코드(lib.sh:241 의 bare `python3`, herdr_config.py:146-147)와 일치 |
## 2. 테스트 실행
| 실행 | 결과 |
|---|---|
| 지정 6개 파일 (pr-48 .venv, Python 3.9.6) | **152 passed / 30 skipped / 0 failed** (216 s). skip = tomllib 필요 29건 + .claude/skills 1건(워크트리 정상). test_issue45_restore 는 skip 0 |
| tests/test_issue45_herdr_config.py (python3.11) | **51 passed** |
- 격리: 실행 전후 herdr 프로세스는 기존 `multi-agent-mux` 서버·attach 클라이언트와 오케스트레이터의 `agent wait` 뿐(잔류 서버 없음), `/private/tmp/m45*` 없음, `~/.config/herdr` 목록·config.toml md5·sessions 목록 불변. MQTT_* unset, .mam.env 미export. 실제 .mam/jobs 에 새 항목 없음.
## 3. 비차단 관찰
- **N1 VERSIONS.md 4.8.5 항목 1 문장 흐름**: 새 문장이 "…경고가 남는다:" 로 끝나고 바로 뒤에 원래 있던 "출력이 원본 자신(별칭 포함)이거나 … 원본별 이름을 쓴다" 가 이어져, 출력 이름 규칙이 Python 버전 설명의 결과처럼 읽힌다. 원래는 "사용자 파일은 고치지 않는다:" 뒤에 붙던 설명이다. 새 문장을 항목 끝으로 옮기면 된다.
- **N2 `_process_env` 의 macOS 분기**(test_issue45_restore.py:166-169)는 `ps -E` 출력을 공백으로 나누므로 공백이 든 경로는 맞추지 못한다. 테스트 루트가 `/private/tmp/m45…` 로 고정이라 지금은 영향 없다.
- **N3 tomli 백포트 대신 문서화한 결정**에 대한 의견: 복원은 어느 경우에도 꺼지므로(#45 의 핵심) 안전 측면에서 문제없고, 이 호스트의 herdr 설정이 키 하나뿐이라는 사정에서 합리적이다. 나중에 사용자 설정이 커지면, 새 의존성 없이 PATH 에서 3.11+ 인터프리터를 찾는 방법도 고려할 만하다.
[VERDICT: PASS]
@@ -0,0 +1,45 @@
# 리뷰 리포트 — Job 40f4077c (PR #47, fix/issue-42-skills-link)
- 리뷰어: planner-reviewer-claude-01 (claude)
- 리뷰 identity: loop-20261004T043243Z-baf133 / base 6af4a79 / head e1ed270 / tree 2f781e0 — 검증 경로에서 `git rev-parse HEAD 'HEAD^{tree}'` 일치, 미커밋 변경 없음
## 결론 요약
수정은 두 배치(단일 링크 / 스킬별 링크 디렉터리)를 모두 올바르게 받고, 잘못된 배치는 실패시킨다. 차단 결함 없음. 비차단 관찰 2건.
## 1. 범위 (항목 3)
`git diff --stat 6af4a79 e1ed270`: tests/test_issue42_skill_blocks.py 한 파일, +10/−1 (test_claude_skills_link_resolves_to_agents_skills, :240-253). 제품 코드·버전 변경 없음.
## 2. 배치별 동작 (항목 1)
검증 경로 안에 임시 .claude/skills(.gitignore:40 의 `.claude/` 로 무시됨)를 만들어 이 테스트만 돌리고 매번 지웠다. 시작 전 .claude 가 없음을 확인했고, 끝난 뒤 `.claude` 잔여물 없음·`git status --short --ignored` 비어 있음·HEAD 불변을 확인했다. 본 체크아웃의 .claude/skills 는 `ls -la` 로 읽기만 했다(스킬 8개 링크 + lib_py·lib.sh 링크 = 10개 항목, 모두 ../../.agents/skills/<이름>).
| 배치 | 결과 | 판단 |
|---|---|---|
| A. 없음 | skip | 의도대로 |
| B. 단일 링크 → .agents/skills | pass | 의도대로 |
| C. 스킬별 링크 8개 + lib.sh·lib_py 링크(본 체크아웃과 같은 배치) | pass | 의도대로 |
| C-old. 같은 배치에서 base(6af4a79) 의 테스트 | **fail** | 수정 대상 결함 재현 |
| C2. C + 여분 디렉터리(foreign-skill) | pass | 여분 허용 |
| D. stop 링크가 loop 를 가리킴 | fail (`.claude/skills/multi-agent-mux-stop -> …/multi-agent-mux-loop`) | 의도대로 |
| E. 스킬 링크 하나 없음 | fail (`… is missing`) | 의도대로 |
| F. 스킬 링크 하나가 깨짐 | fail (`… is missing`) | 의도대로 |
| G. 링크 대신 복사본 디렉터리 | fail (resolve 가 .claude 쪽) | 의도대로 — 복사본은 드리프트하므로 막는 것이 맞다 |
| H. .claude/skills 가 일반 파일 | fail (`… is missing`) | 의도대로 |
| J. 단일 링크가 다른 곳(스킬 하나)을 가리킴 | fail | 의도대로 |
| K. 빈 디렉터리 | fail | 의도대로 |
| L. 스킬별 링크가 중간 링크를 거쳐 해석됨 | pass | resolve() 가 최종 대상을 비교하므로 맞다 |
| I. **단일 링크가 깨짐** (`.claude/skills -> ../nowhere`) | **skip** | 관찰 N1 |
- SKILL_NAMES 가 비면 스킬별 루프가 공집합이라 통과하겠지만, 같은 파일의 test_inventory_covers_eight_skills 가 `len(SKILL_NAMES) == 8` 을 단언하므로(파일 상단 SKILL_NAMES 정의와 함께) 놓치지 않는다.
## 3. 엄격성 (항목 2)
- 여분 항목(lib_py, lib.sh, 다른 스킬 디렉터리)은 허용된다(C, C2). Claude Code 가 스킬로 읽는 것은 SKILL.md 를 가진 하위 디렉터리이므로 여덟 MAM 스킬이 .agents/skills 의 것인지만 보는 현재 기준이 적절하다. 다른 스킬을 같이 두는 정상 사용을 막지 않는다.
- lib.sh·lib_py 링크는 검사하지 않는데, 진입 스크립트는 `$SCRIPT_DIR/../..` 에서 lib.sh 를 찾고 없으면 `${WORKSPACE_ROOT:-$PWD}/.agents/skills/lib.sh` 로 폴백하므로(예: reconcile.sh:20-21) 테스트의 필수 조건으로 둘 이유는 없다. 문서의 호출도 모두 `bash .agents/skills/...` 경로를 쓴다.
## 4. 비차단 관찰
- **N1 깨진 단일 링크가 skip 으로 숨는다** (tests/test_issue42_skill_blocks.py:245-246): `link.exists()` 는 링크를 따라가므로 대상이 없는 단일 링크는 "없음"으로 보고 skip 한다. 이 경우 Claude Code 는 스킬을 하나도 못 읽는데 테스트는 통과(skip)한다. base 테스트도 같은 동작이었으므로 이 PR 의 회귀는 아니다. `if not link.exists() and not link.is_symlink(): skip` 으로 바꾸면 깨진 링크는 아래 resolve 비교에서 실패한다.
- **N2 실패 메시지**: G(복사본)의 메시지가 `-> <.claude 안 경로>` 로 나와 "링크가 아니라 복사본"이라는 원인이 바로 드러나지 않는다. 사소함.
## 5. 테스트
검증 경로에서 `tests/test_issue42_skill_blocks.py` 전체: **31 passed / 1 skipped** (skip = 이 테스트, 워크트리에 .claude 없음 — 정상). 배치 탐침은 §2.
[VERDICT: PASS]
@@ -0,0 +1,76 @@
# 리뷰 리포트 — Job 416d9768 (PR #48, fix/issue-45)
- 리뷰어: planner-reviewer-claude-01 (claude)
- 리뷰 identity: loop-20261005T064728Z-a4e9c8 / base c5c7eff / head 35935f9 / tree dff9db1 — 검증 경로에서 `git rev-parse HEAD 'HEAD^{tree}'` 일치, 미커밋 변경 없음
## 결론 요약
제품 동작(A: MAM 서버 복원 꺼짐, B: 자기 세션의 빈 셸만 닫기)은 이 macOS 호스트의 실제 herdr(0.9.1)에서 동작함을 확인했다. 그러나 **브리프가 지정한 검증 명령이 이 호스트(리포지토리 .venv = Python 3.9.6)에서 수집 단계에서 중단**되고, 그 파일을 빼고 돌려도 **새 테스트 5개가 macOS 에서 실패**한다. 원인은 모두 테스트의 Linux·Python 3.11 가정이며 수정은 작다. 스킬 frontmatter 가 `platforms: [linux, macos]` 이므로 차단으로 판단한다.
## 차단 (테스트 이식성)
### B1. tests/test_issue45_herdr_config.py:16 — 모듈 최상단 `import tomllib`
- Python 3.9 에서 `ModuleNotFoundError` → pytest 가 "Interrupted: 1 error during collection" 으로 **세션 전체를 중단**한다. 브리프 지정 명령(7개 파일)은 결과 0건, rc 2. 오케스트레이터의 전체 스위트도 같은 .venv 면 같은 이유로 중단된다.
- 제품 쪽(lib_py/herdr_config.py:54-57)은 tomllib 부재를 처리하는데 테스트만 강제한다. `tomllib = pytest.importorskip("tomllib")` 처럼 모듈 skip 또는 tomllib 이 필요 없는 경우만 남기는 처리가 필요하다.
- 참고: 같은 파일을 Homebrew python3.11 + 기존 venv 의 pytest(PYTHONPATH)로 돌리면 **51 passed**. 내용 자체는 정상이다.
### B2. tests/test_issue45_restore.py:227, :163 — Linux 전용 가정 (macOS 4 failed)
| 테스트 | 실패 | 원인 |
|---|---|---|
| test_a_…[plain-user-config], test_a_…[user-config-with-session-table] | FileNotFoundError `/proc/<pid>/environ` | :227 `/proc` 는 macOS 에 없다 |
| test_b_only_the_resumed_sessions_restored_shell_is_closed | `'/private/tmp/m45…' == '/tmp/m45…'` (:263) | :163 `mkdtemp(dir="/tmp")` — macOS 에서 /tmp 는 /private/tmp 링크이고 herdr 는 실경로를 보고한다 |
| test_b_resume_leaves_no_restored_shell_behind | StopIteration (:325, cwd 비교) | 같은 원인 |
- 검증: 스크래치 사본에서 **이 두 군데만** 고친 테스트(`.resolve()` 추가, `/proc` 대신 `ps -E -ww -o command= -p <pid>`)는 **5 passed**(65 s). 즉 제품은 맞고 테스트만 이식되지 않았다. 양성 대조도 이 사본에서 동작한다.
### B3. tests/test_issue9_server_env.py:157 — 테스트 안 `import tomllib`, 그리고 bootstrap 의 python3 가정
- 3.9 에서 import 로 실패. 또 3.11 로 테스트를 돌려도 bootstrap 은 `python3`(lib.sh:241, 이 호스트는 /usr/bin/python3 3.9.6)로 herdr_config 를 실행하므로 결과는 MINIMAL 이고, :170 의 `cfg == {"ui": …, "session": …}` 단언은 실패한다. `python3` 에 tomllib 이 없으면 skip(또는 MINIMAL 을 기대)해야 한다.
## 검토 항목별 판단
### 1. A 의 설정 병합 (lib_py/herdr_config.py)
- 원본 보호: 출력은 항상 output_path(:192-205)를 거친다 — 원본 자신(samefile/realpath, 별칭 포함)이나 다른 원본용·비생성 파일이면 해시 이름으로, 그것도 막히면 OSError → 쓰지 않음. 폴백(.mam)도 같은 함수(:273, R3 2회차 수정). 쓰기는 같은 디렉터리 임시 파일 + os.replace(:208-222), 원본 권한 복사(:255).
- 재귀: HERDR_CONFIG_PATH 가 생성 파일이면 2행의 `# source:` 로 원본을 따라간다(:65-92). source 행이 없으면 XDG/HOME 으로.
- 병합 정확성: tomllib parse → `session` 에 키만 덮어씀 → dumps → 재파싱이 기대값과 **정확히 같을 때만** 사용(:156-164). 인라인 표·점 표기·따옴표 키·배열은 파싱 결과(dict)로 다루므로 표기와 무관. 주석·표기 형식은 생성 파일에서 사라지지만 원본은 그대로이고 의미는 같다. 실패 시 MINIMAL + 경고.
- herdr 검사: 쓴 뒤 `herdr config check`(:169-180)가 "parse error"/"using defaults" 를 내면 MINIMAL 로 재시도, 그것도 거부되면 None → bootstrap 이 경고하고 예전처럼(복원 켜짐) 기동(lib.sh:241-245). 단위 테스트가 실제 herdr 로 이를 확인(3.11 에서 51 passed).
- 사용자 디렉터리 흔적: `~/.config/herdr/mam-server-config.toml`(또는 해시 이름) 1개, 중단 시 `.mam-server-config.*.tmp` 가능. create SKILL.md:120-121 에 위치가 적혀 있다.
- 비차단 D1 (아래): python3 < 3.11 호스트에서는 병합이 일어나지 않는다.
### 2. 적용 경로
- MAM 이 서버를 띄우는 곳은 shim 의 headless bootstrap 한 곳(lib.sh:261 `"$REAL_HERDR" --session "$_MAM_SESSION" server`)뿐이고 A 가 여기에 걸려 있다. create·resume·delegate 는 모두 shim 을 거친다. 다른 `server` 기동은 grep 으로 찾지 못했다. MAM_NO_AUTOSTART 호출자(status/reconcile)는 서버를 띄우지 않는다(lib.sh:196-201).
- 걸리지 않는 경로: 사용자가 `herdr session attach`/`herdr --session X` 로 직접 띄운 서버, 기본 `default` 서버, 이미 떠 있는 서버. create SKILL.md:121 이 "rebuilt each time MAM starts the server … next started", "A server you start yourself (`herdr session attach`) does not get it" 로 적고 있다(합의된 한계와 일치).
### 3. B 의 닫기 조건 (lib_py/herdr_restore.py)
- 조건(:54-65): 세션 id 비어 있지 않음, 서버가 default 아님, `agent` 없음, `agent_session.value == id`, 전경 = shell_pid(shell_pid 없으면 False). 사용자 pane(agent_session 없음)·다른 세션·전경 프로세스 있음·에이전트 살아 있음은 제외 — 실제 서버 테스트(사본)에서 사용자 셸·Z(실행 중)·X2(sleep 60)가 남고 X·Y 만 닫힘을 확인.
- fail-safe: herdr 오류·JSON 오류는 예외 → exit 1(:79-83) → resume 은 경고만(resume_session.sh:240-242) 하고 진행. default 서버는 herdr 를 부르지도 않는다(test_b_default_server_is_never_touched 통과). Class A fresh-spawn(UUID 없음)은 즉시 반환.
### 4. 테스트의 격리·결정성
- test_issue45_restore 는 HOME 을 `/tmp/m45*` 로, 세션을 `mamt45-<pid>-<4hex>` 로 두고 HERDR_*·XDG_CONFIG_HOME·HERDR_CONFIG_PATH 를 지운다(:42-44, :161-168). 정리는 그 세션 이름·그 루트 경로로만 pkill(:186-195). conftest 도 HERDR_CONFIG_PATH·XDG_CONFIG_HOME 을 지운다.
- 실행 전후 확인(실패 실행 3회, 사본 실행 3회 모두): herdr 프로세스는 기존 `multi-agent-mux` 서버·attach 클라이언트뿐(잔류 없음), `/tmp/m45*` 없음, `~/.config/herdr` 목록·config.toml md5·sessions 목록 불변.
- 양성 대조: 사본에서 lib.sh 의 `HERDR_CONFIG_PATH` 주입을 끄면 test_a 가 `--resume <id>` 로 실패(#45 재현), resume 의 close 호출을 끄면 test_b_resume 가 pane 2개로 실패. 테스트가 수정에 실제로 의존한다.
- 결정성: 폴링 + 고정 대기(최대 수 초)라 느린 호스트에서 다소 민감할 수 있으나 3회 반복 모두 같은 결과였다.
### 5. 문서·인벤토리
- 버전: lib.sh·eager.py·SKILL.md 8개·VERSIONS 가 4.8.5 로 일치(test_version_consistency 통과).
- skill_code_blocks.json: blocks 의 (skill, class, kind) 순서 동일, create 블록 4개의 start/end 이동과 resume removed 항목의 evidence 줄 번호(+8) 이동뿐. 분류 변경 없음.
- **D1 (비차단, 문서)**: VERSIONS 4.8.5 항목 1과 create SKILL.md:120 은 서버 설정을 "사용자 설정 + 키"로 설명하지만, bootstrap 은 `python3`(lib.sh:241)로 실행되므로 python3 < 3.11 인 호스트(이 macOS 의 /usr/bin/python3 3.9.6)에서는 **항상 키 하나만 있는 파일**로 기동하고 사용자 herdr 설정(예: default_shell·키 바인딩)이 MAM 서버에 적용되지 않으며, 기동마다 경고가 나온다. 복원은 꺼지므로 안전하지만, 이 한계를 문서에 적거나 3.11+ 인터프리터를 찾는 편이 좋다. VERSIONS 의 "실패 시 키 하나만" 목록에도 Python 3.11 미만이 빠져 있다.
### 6. purge 기준 실패
검증 경로에서 tests/test_issue10_13_purge.py **23 passed**(macOS). 이 PR 과 무관하며 "12 실패"는 Linux 기준이다.
### 7. 경계(#17)
새 판정(병합·검사·출력 경로, 닫기 조건)은 모두 Python(herdr_config.py, herdr_restore.py)에 있다. bash 쪽 추가는 호출과 빈 값 경고(lib.sh:241-245, resume_session.sh:240-242)뿐이다.
## 테스트 실행 요약
| 실행 | 결과 |
|---|---|
| 브리프 지정 7개 파일 (pr-48 .venv, Python 3.9.6) | **수집 오류로 중단, 0건 실행, rc 2** (B1) |
| herdr_config 제외 6개 파일 | **5 failed** / 192 passed / 1 skipped (B2 4건, B3 1건; skip = .claude/skills, 워크트리 정상) |
| test_issue45_herdr_config.py (python3.11) | 51 passed |
| test_issue45_restore.py 이식성 2곳만 고친 사본 | 5 passed; A·B 수정을 끄면 각각 실패 |
| test_issue10_13_purge.py | 23 passed |
MQTT_* unset, .mam.env 미export. 실제 .mam/jobs 에 새 항목 없음.
## 수정 제안 (최소)
1. test_issue45_herdr_config.py:16 → `tomllib = pytest.importorskip("tomllib")`.
2. test_issue45_restore.py:163 → `Path(tempfile.mkdtemp(...)).resolve()`; :227 → `/proc` 가 없으면 `ps -E -ww -o command= -p <pid>` 로 확인(또는 그 단언만 Linux 한정).
3. test_issue9_server_env.py:157 → bootstrap 이 쓸 `python3` 에 tomllib 이 없으면 skip 하거나 MINIMAL 을 기대.
4. (비차단) D1 문서화.
[VERDICT: NOT PASS]
@@ -0,0 +1,43 @@
# 리뷰 리포트 — Job 4566e690 (Issue #17 후속, fix/issue17-followups 56d0bfd..8241bd5)
- 리뷰어: planner-reviewer-claude-01 (claude)
- 리뷰 identity: loop-20261007T224638Z-cf1efb / base 56d0bfd / head 8241bd5 / tree efef640 — 검증 경로에서 `git rev-parse HEAD 'HEAD^{tree}'` 일치, 미커밋 변경 없음
- 커밋 6개: 25c9970·f19f940(항목 1), a670ef5(항목 2), d6cb019(항목 3), c90a0af(항목 4), 8241bd5(테스트 환경 고정). 버전·VERSIONS.md 변경 없음(브리프대로).
## 결론 요약
항목 1~4 가 요구대로 반영됐고, 정상 경로의 종료 코드·출력·레지스트리·이벤트는 변하지 않았다. 추가 테스트 13건은 수정 전 코드에서 실제로 실패한다(255·127·2 등 예측된 코드로). 항목 1 에는 브리프 문구("테스트 전제 수정")를 넘는 **제품 코드 변경**(herdr_restore.py 의 placeholder 닫기)이 포함되는데, 실제 herdr 0.9.3 에서 그 변경 없이는 테스트도 resume 의 닫기도 성립하지 않음을 확인했으므로 정당한 범위 확장으로 판단한다(§1). 차단 결함 없음. 비차단 관찰 3건(§6).
## 1. 항목 1 — herdr 0.9.3 과 test_b
- 브리프의 전제 "닫기 동작은 cwd 를 보지 않는다 → :275 만 두 경로 허용" 은 불완전했다. herdr 0.9.3 은 디렉터리가 사라진 pane 을 **프로세스 없는 placeholder**(`restore_error` 설정)로 복원하고 `pane process-info` 는 `pane_not_found` 로 rc 1 을 낸다. 실제 서버 대조: 스크래치 사본에 **이전 herdr_restore.py** 만 넣고 test_b 를 돌리면 `close-restored-shells: Command […'pane','process-info','--pane','w2:p1'] returned non-zero exit status 1` 로 실패(1 failed, 11.8 s) — 즉 옛 코드는 Y 의 placeholder 에서 예외를 내 resume 의 닫기 단계 전체가 rc 1 로 끝나고(래퍼는 경고만), 아무 pane 도 닫지 못한다.
- 수정(herdr_restore.py:58-66 `_nothing_running`): `_shell_in_foreground` 가 CalledProcessError 를 내면 **pane 에 `restore_error` 가 있고 출력에 `pane_not_found` 가 있을 때만** "실행 중인 것 없음"으로 보고, 그 외 실패는 그대로 올린다. 두 조건이 모두 herdr 자신이 붙인 표지라 사용자 pane·다른 세션 pane 이 이 경로로 닫힐 수 없다(agent_session 일치 조건 :83 은 그 앞에서 여전히 적용). 단위 테스트 2건이 "restore_error 없음 + pane_not_found", "restore_error 있음 + 다른 오류" 를 모두 예외 유지로 고정한다. fail-safe 방향(닫는 쪽이 아니라 두는 쪽) 유지.
- `_herdr` 는 `subprocess.run(..., capture_output=True, check=True)` 이므로 CalledProcessError.stderr/.output 이 채워진다(:46-49) — 판정에 쓰는 문자열이 실제로 들어온다.
- test_issue45_restore.py:267·:275-277 주석·단언이 0.9.1($HOME)/0.9.3(원래 경로) 둘 다 허용. 다른 문서의 "$HOME 으로 복원" 주장: SKILL.md 들에는 없음(create:120, resume:63 은 "empty shells" 만 말함), VERSIONS.md 과거 항목은 브리프대로 제외.
- 실행: 이 Mac(herdr 0.9.3)에서 tests/test_issue45_restore.py **5개 모두 통과, skip 0**.
## 2. 항목 2 — N2 fail-closed
- 래퍼(:103-127): `_decision_failed` 는 stderr 에 사유를 적고 `exit 1`; `_decided <var> <sub> …` 는 rc≠0 또는 빈 출력이면 실패; `_exit_for` 는 답이 `^[0-9]+$` 가 아니면 실패. 다섯 `exit "$(_decide exit-code …)"` 가 `_exit_for` 로, 네 `sub-status` 대입과 `finalize-begin` 이 `_decided` 로, `finalize-end` 는 rc 검사(:856-857), `cmd_wait` 의 wait-rc 는 `_decided` + 숫자 검사(:1070-1071). 모든 호출이 서브셸 밖(직접 호출)이라 `exit 1` 이 래퍼를 끝낸다; `{ …; } 4>&1` 그룹도 서브셸이 아니다.
- 정상 경로 불변: `_decided` 는 같은 명령의 같은 한 줄 출력을 변수에 넣고, `finalize-end` 의 "소유자 사라짐 → rc 0·빈 답" 은 전과 같이 FINAL_JOB_STATUS="" 로 남는다(의도된 기존 동작). test_f_the_normal_path_is_unchanged(실제 래퍼, human 잡, 닿지 않는 브로커 → rc 3, 마지막 줄 = 로그 경로, 오류 문구 없음) 통과. 옛·새 비교 테스트(test_c_*) 전부 통과.
- rc 로만 읽는 호출: `subscriber-up` 실패(모듈 깨짐) → "subscriber died early" 경로 → `_decided sub-status` 가 실패 → exit 1(fail-closed, OK). `stall-watch` 실패 → `|| return 0` 으로 **감시만 꺼진 채 진행**(:718). 브리프가 "범위에 넣지 않은 것은 이유를 적으라" 했는데 리뷰어에게 그 이유는 보이지 않는다 — 관찰 N1. #30 감시자는 notify-only 라 잡 종결에는 영향이 없어 비차단.
- 추가 테스트가 수정 전 코드에서 실패하는가: 이전 래퍼(56d0bfd)를 넣은 사본에서 test_f_* 11건 + test_s_no_printed_decision_is_read_raw 모두 **실패** — exit-code 는 `exit: : numeric argument required` 로 **255**, 인터프리터 부재는 **127**, finalize-begin 빈 답은 finalize-end argparse `--evidence-until: invalid int value: ''` 로 **2**. 세 가지 모두 브리프가 금지한 종료 방식이며 새 코드는 전부 1 로 끝난다.
- 이식성: `/bin/bash -n` 통과(3.2), `printf -v`·`[[ =~ ]]` 는 3.2 에서 지원. 테스트는 `/bin/sh` 셸 스크립트 대역과 `sys.executable` 만 쓴다.
## 3. 항목 3 — N1 문구
wrapper.py:24-29 가 "이 모듈은 stdlib 만 import 하지만 `python -m lib_py.delegation.wrapper` 는 패키지 `__init__` 을 먼저 실어 paho 가 로드되며, 래퍼의 $PY 는 원래 paho 가 필요하다"로 정정. 실행 경로 변경 없음(diff 상 docstring 만).
## 4. 항목 4 — N3 주석
lib_int.sh:9-10 에 "PATH 의 python3 를 쓴다(단독 source 라 $PY 없음); 없으면 mam_int/mam_int_knob 이 아무것도 출력하지 않는다(rc 127)" 추가. 코드 불변.
## 5. 테스트 실행 (검증 경로, 워크트리 .venv Python 3.9.6, paho 있음, `env -i` 로 HERDR_*·MAM_*·MQTT_*·WORKSPACE_ROOT 제거)
| 실행 | 결과 |
|---|---|
| tests/test_issue45_restore.py, test_issue45_restore_unit.py, test_issue17_item4_decisions.py, test_issue33_budget.py | **310 passed / 0 failed / 0 skipped** (425 s) |
| 새 테스트 16건, 이전 래퍼·이전 herdr_restore.py 사본 | **13 failed** / 3 passed (실패 = F 11 + 정적 가드 + placeholder 단위) |
| test_b (실서버), 이전 herdr_restore.py 사본 | 1 failed (pane_not_found 예외) |
격리: 실행 전후 herdr 프로세스는 기존 `multi-agent-mux` 서버·attach·오케스트레이터 `agent wait`(pid 만 교체)뿐, `/private/tmp/m45*` 없음, `~/.config/herdr` sessions·config.toml md5 불변. 실제 .mam/jobs 항목 수 불변. 루프백 bind 제약 없음(브로커 테스트 정상 실행).
## 6. 비차단 관찰
- **N1 stall-watch 판정 실패 시 조용히 감시 생략**(래퍼 :718 `|| return 0`): 모듈이 깨지면 stderr 에 아무 말 없이 stall watcher 가 꺼진다. 종결·레지스트리·이벤트에는 영향이 없어 fail-closed 요구 밖이지만, `_decide` 의 rc 가 1(판정 "감시 안 함")인지 그 밖(실패)인지 구분해 후자는 경고 한 줄을 남기면 진단이 쉬워진다. 브리프가 요구한 "범위 제외 이유" 가 리포트에 있는지 오케스트레이터가 확인하길 권한다.
- **N2 `_env` 가 상속 WORKSPACE_ROOT 를 비우지 않음**(tests/test_issue17_item4_decisions.py:224-230): HERDR_/MAM_/SKS_ 만 걷어낸다. 새 테스트(:659-660, :692)는 WORKSPACE_ROOT 를 명시하지만, 래퍼를 source 하는 기존 `_run_both` 4곳(:246, :372, :561, :586, PR #51 유래)은 `_env(work, …)` 만 써서 에이전트 pane 에서 돌리면 그 pane 의 WORKSPACE_ROOT 로 lib.sh 가 초기화된다 — 브리프가 적은 사고(상속된 WORKSPACE_ROOT 로 다른 워크스페이스의 shim 재작성)와 같은 경로다. `_env` 에서 WORKSPACE_ROOT 를 제거하고 tmp_path 로 고정하면 한 줄로 막힌다. 이 델타가 만든 문제가 아니라 비차단.
- **N3 docstring 줄바꿈**(herdr_restore.py:7-8): "A pane keeps the\n`agent_session` its agent\nreported" 로 어색하게 끊겨 있다. 내용 문제 없음.
[VERDICT: PASS]
@@ -0,0 +1,132 @@
# 🔍 Review Report — Job 48b1b0f8 (Issue #18 델타 리뷰, reviewed HEAD `263d6bf`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-09-14
- **대상**: `git diff ab842f1...HEAD` 2커밋, 4파일 +273/−10.
- `2b1d590`: 잡별 lifecycle lock, 구현 세션 커밋
- `263d6bf`: codex F1·F2 교정, creator 커밋
- 전체 브랜치는 내가 `ab842f1` 에 PASS 한 범위다(`98215f55`).
- 브리프의 "변경분" 은 작업 트리의 추적되지 않은 codex 리포트 파일 하나뿐이었다. 그래서 델타는 git 으로 직접 확인했다.
- HEAD 는 이 잡 내내 `263d6bf` 이다(`completed` 발행 명령에서 다시 확인).
- **방법**:
- 델타를 정독했다.
- 임시 레지스트리에서 실제 타이머 프로세스로 독립 실험 4건을 했다(브로커 없음, 닫힌 포트·블랙홀 주소).
- 선택 테스트 9파일을 실행하고 정적 검사를 했다.
- 이 잡은 `started --heartbeat 30` 으로 시작했다. 코드는 수정하지 않았다.
- **안전 규칙 준수**:
- 실제 `.mam/jobs` 레코드는 수정하지 않았다(실행 전후 비교).
- monitor 데몬과 `.mam/monitor.lock` 은 건드리지 않았다. purge 는 실행하지 않았다.
- 실험 타이머 잔여는 0 이다.
## 0. 경위
| 리뷰 | HEAD | 판정 | 요지 |
|---|---|---|---|
| claude `98215f55`·agy·grok | `ab842f1` | PASS | — |
| codex (4회차) | `ab842f1` | NOT PASS | 동시 `start_timer` 2건이 둘 다 spawn 하고 하나만 추적됨 → `2b1d590` |
| codex `d1eb9f50` | `2b1d590` | NOT PASS | **F1**: 종료 중인 타이머가 drain 중인 부모가 쥔 lock 을 기다리는 유한 교착(항상 SIGKILL 로 끝남). **F2**: pidfile 기록 실패 뒤 추적되지 않는 타이머가 남음 → `263d6bf` |
| codex `bad3ef4b` | `263d6bf` | PASS | — |
## 1. 검증 항목
### (1) lifecycle lock 과 레지스트리·seq lock 의 순서, 교착 가능성
- **구조**: lifecycle lock(`heartbeat.py:187-209`, `<job>.heartbeat.lock`)은 레지스트리·seq lock 과 **별개의 flock** 이다. 잡는 곳은 세 군데뿐이다.
- 터미널 `stop_timer`(`:221`)
- `start_timer`(`:312`)
- 종료하는 타이머의 정리(`:473`, **non-blocking**)
- **lifecycle lock 안에서 하는 일**:
- `_stop_timer_locked` 의 drain 은 레지스트리 lock 을 잡지 않는다.
- `load_job` 은 lock 없는 읽기다(`mqtt_common.py:393-399`). `barrier_blocks` 도 파일 읽기뿐이다.
- 그 뒤 spawn 과 pidfile 기록을 한다.
- **레지스트리 lock 을 잡는 곳**: `raise_barrier`(`heartbeat.py:270`)와 `next_seq` 뿐이다. 둘 다 lifecycle lock 을 잡지 않는다.
- 터미널 publish 는 `raise_barrier`(레지스트리 lock 해제) → `stop_timer`(lifecycle) 순으로 **중첩 없이 차례로** 잡는다.
- 따라서 역순 중첩이 없고, lock 순서 교착은 불가능하다.
- **drain 중 in-flight beat**: beat 는 seq lock 만 필요하다. 그 lock 은 drain 하는 쪽이 쥐고 있지 않으므로 beat 는 끝까지 갈 수 있다.
- **F1 교정**: 종료하는 타이머는 lock 이 바쁘면 기다리지 않고 정리를 소유 연산에 맡긴다. 소유 연산(start·stop)은 모두 `_stop_timer_locked` 로 시작하며, 그 안에서 pidfile 을 지운다.
- **실험 E1 — 유휴 타이머 정지** (interval 60, 2 s 대기 뒤 `stop_timer(drain=5)`):
- **0.17 s** 에 반환했고, pidfile 이 제거되었으며, "did not drain" 경고가 없었다.
- codex 가 `2b1d590` 에서 잰 값은 2.09 s, `-9` 였다. 교착이 해소되었다.
- **실험 E4 — 와이어에 걸린 beat 가 있는 drain** (브로커 `10.255.255.1` 블랙홀, interval 1):
- `stop_timer(drain=1)` 가 **1.12 s** 에 SIGKILL 로 끝났다. 이 경우의 "did not drain" 경고 1건은 정당하다.
- 직후 `next_seq` 는 **0.001 s** 에 반환했다(seq lock 은 비어 있음). pidfile 은 제거되었다.
- drain 과 seq lock 사이에 교착이 없다.
### (2) 동시 start, barrier 뒤 start, pidfile 기록 실패
- **실험 E2 — 동시 `start_timer` 5건**(스레드 barrier 로 동시 출발):
- 오류 0, 살아남은 타이머 **정확히 1개**, pidfile 이 그 타이머를 가리킨다.
- `stop_timer` 뒤 생존 0, pidfile 없음.
- **실험 E3 — `start_timer` 와 터미널 `completed` publish 경쟁, 8라운드**(시작 간격 0–14 ms 로 변화):
- **위반 0/8**: 매 라운드 레코드 `completed`, 생존 타이머 0, pidfile 없음, events.log 에 `completed` 뒤 이벤트 0.
- 1라운드는 start 가 먼저 arm 해서 터미널이 drain 했다. 7라운드는 barrier·터미널을 보고 **arm 하지 않았다**.
- **pidfile 기록 실패 (F2)**(`:343-364`): spawn 성공 뒤 pidfile 기록이 실패하면 lock 을 쥔 채 그 `Popen` 을 kill·wait 한다. 그리고 이 시도의 부분 pidfile 만 지운 뒤 예외를 다시 던진다.
- 시험 `test_a_timer_whose_pid_cannot_be_recorded_is_killed_at_once` 가 SIGKILL 종료, pidfile 없음, lock 재사용 가능을 단정한다.
### (3) 예외 경로에서 lock 해제와 pidfile 일관성
- `lifecycle_lock` 은 `try/finally` 로 `LOCK_UN` 하고, `with open(...)` 가 fd 를 닫으므로 예외에서도 해제된다.
- non-blocking 이 바쁘면 `False` 를 내주고, 호출자는 소유 상태를 건드리지 않는다(`:473-478`).
- **spawn 전 실패**(`Popen` 오류): pidfile 을 쓰지 않고 lock 은 해제된다. 시험 `…cannot_be_spawned_leaves_nothing_behind` 가 확인한다.
- **spawn 후 실패**: 이전 소유자의 pidfile 은 이미 `_stop_timer_locked` 가 지웠다. 따라서 남은 내용은 이번 시도의 것뿐이고, pid 접두 비교로 지우는 판단이 옳다.
- P3:
- `lifecycle_lock` 은 `os.makedirs(registry_dir)` 를 한다. 그래서 잘못된 레지스트리 경로로 터미널 publish 를 하면 디렉터리가 생긴다.
- 모든 터미널 publish 가 잡마다 `<job>.heartbeat.lock` 을 남긴다(기존 `.heartbeat.barrier` 와 같은 성질). `.json` 이 아니므로 잡 목록과 #15 가드에는 영향이 없다. 레지스트리 정리 정책에서 함께 다룰 것을 권한다.
### (4) 새 회귀 시험의 결정성과 프로세스 정리
| 시험 | 판단 |
|---|---|
| `test_concurrent_start_timer_calls_leave_exactly_one_tracked_owner` | 스레드 2개로 순서를 강제하지 않는다(codex 도 지적). 위의 5건 동시 실험이 보완한다. `finally` 에서 두 pid 를 SIGKILL 한다 |
| `test_start_timer_after_the_terminal_barrier_does_not_arm` | 결정적(프로세스 없음) |
| `test_an_idle_timer_stops_gracefully_well_before_the_drain_deadline` | 2 s 대기로 TERM 핸들러 설치 뒤를 노린다. 과부하로 핸들러 설치 전에 TERM 이 가도 기본 동작으로 곧 끝나므로 `< 3 s` 단정은 유지된다. `finally` 에서 정리한다 |
| `test_a_timer_whose_pid_cannot_be_recorded_is_killed_at_once` | `builtins.open` 을 잠깐 패치하고 `finally` 에서 복구한다. spawn 된 프로세스는 `finally` 에서 kill·wait 한다 |
| `test_a_timer_that_cannot_be_spawned_leaves_nothing_behind` | 없는 python 경로를 쓴다. 두 번째 타이머는 `stop_timer`·SIGKILL 로 정리한다 |
- 실행 결과는 §2 에 있다.
### (5) 문서·수치·락스텝
- MESSAGING §2.5 heartbeat 행이 코드와 일치한다: "lifecycle lock(`<registry>/<job>.heartbeat.lock`, seq lock 과 별개) — 끝난 attempt 는 arm 하지 않음, 종료 타이머는 lock 을 기다리지 않음, pid 기록 실패 시 즉시 종료". VERSIONS 항목 1 도 같다.
- VERSIONS 품질 절 "신규 테스트 31개"(`VERSIONS.md:54`)는 `grep -c '^def test_'` 결과 31 과 같다.
- 4.5.0 락스텝 유지: `verify_framework_version` OK, `SKILL.md` 8개 4.5.0.
- `git diff --check 139bdd4...HEAD` 클린. `py_compile`(`heartbeat.py`, 시험) 통과.
## 2. 테스트 실행 결과
| 실행 | 결과 |
|---|---|
| **선택 9파일** (issue18 31, issue14, issue6 fail_closed·turn_handshake, phase1, phase2a, tier1, tier2, version) @ `263d6bf`(전후 동일) | **355 passed, 0 failed, 742.30 s**, skipped 0. 브로커 의존 AC1 22.09 s, AC3 18.92 s, pane-busy 17.93 s, 벽시계 30.12 s |
| 독립 실험 E1–E4 | 모두 기대대로(§1). 실험 타이머 잔여 0 |
| creator `31a24383` (3파일) | 100 passed |
- **누수 (실행 전후)**:
- 실제 monitor 데몬 수가 같다(3개, 실행 전후 동일 PID).
- pytest 경로의 heartbeat 타이머·구독자·원격 러너는 0 이다.
- 실제 `.mam/jobs` 추가는 0 이다.
## 3. 비차단 권고
1. (이월, T-1) 브로커 의존 시간 임계 시험의 여유를 넓힌다: AC1·AC3·AC5 의 K×N, issue14 벽시계·pane-busy, send_keys `< 11`.
2. 잡마다 남는 `.heartbeat.lock`·`.heartbeat.barrier` 파일의 정리 정책을 정한다. `lifecycle_lock` 의 `makedirs` 부작용도 함께 본다.
3. (이월) AC5 는 단일 원격 잡 시뮬레이션과 러너 라벨 단위 시험까지만 검증되었다. 루프 종단 수렴은 후속 E2E 로 남는다.
## 4. GM 참고
- **추적되지 않은 파일**: 작업 트리에 `.agents/reports/planner-reviewer-codex-01/report-bad3ef4b.md` 가 있다(codex 리포트 사본). 브리프의 "변경분" 이 이것 하나로 채워졌다. 나는 건드리지 않았다.
- **커밋 주체**: `2b1d590` 은 구현 세션(`…01VCgu9Fa9iT7TbJUSzdq4Ff`), `263d6bf` 는 creator(`…01HCGpJXhSZasJLU38ksDghe`)의 커밋이다.
- **브랜치 ref**: 11커밋 모두 로컬 `main` 에 있다(`origin/main` 보다 11 앞, 미푸시). `fix/issue-18` 은 `139bdd4` 다. 병합 전에 ref 정리가 필요하다.
## 5. 종합
- `2b1d590` 의 잡별 lifecycle lock 은 레지스트리·seq lock 과 중첩 없이 분리되어 있어 교착이 없다.
- `263d6bf` 의 non-blocking 종료 정리(F1)와 spawn 후 pid 기록 실패 시 종료(F2)가 정확하다.
- 독립 실험으로 확인했다:
- 유휴 정지 0.17 s
- 동시 start 5건에서 추적 소유자 1개
- start 와 터미널 경쟁 8라운드에서 위반 0
- 걸린 beat 가 있어도 seq lock 이 즉시 비어 있음
- 새 시험들이 이 경로들을 고정한다. 선택 스위트 355건이 모두 통과했다.
- 문서·수치(31)·4.5.0 락스텝이 정합한다.
- 남은 것은 비차단 권고뿐이며 설계 재검토는 필요 없다.
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261017T145452Z-6c5aa6",
"base_sha": "26e2c43753169671b600d03274901dbe203988dd",
"head_sha": "de6f3fc81f8c33a9d2335320742dc5a47f566cda",
"tree_sha": "ffc291e6fc93822070f2b9f1d17009e83f176fcf",
"review_commit": "de6f3fc81f8c33a9d2335320742dc5a47f566cda",
"reviewer": "planner-reviewer-claude-01",
"job_id": "48d0a01c",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-17T15:16:54Z"
}
@@ -0,0 +1,52 @@
# 리뷰 리포트 — PR #59 3차 (Issue #31) / job 48d0a01c
- 리뷰어: planner-reviewer-claude-01 (Opus 5.5)
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261017T145452Z-6c5aa6/1`
- identity: HEAD `de6f3fc81f8c33a9d2335320742dc5a47f566cda`, tree `ffc291e6fc93822070f2b9f1d17009e83f176fcf` 일치. 트리는 clean이고 `.mam` 없음(테스트 후에도 동일).
- 범위: 26e2c43..de6f3fc 전체. 2a8d738 이후 변경은 de6f3fc 한 커밋으로, `tests/test_issue31_purge_residual.py` 의 +3/−1 뿐이다. `git diff 2a8d738 HEAD -- .agents` 는 비어 있다.
## 결론
2차의 유일한 차단(T1: macOS `/bin/sh` 의 단일 명령 exec 로 보유자 argv 에서 uuid 가 사라지던 문제)이 해결됐다. 제품 코드는 2a8d738 과 바이트 단위로 같으므로, 2차에서 이 Mac 에서 확인한 내용이 그대로 유효하다. 확인한 항목은 비-UUID 거부, 링크 경계, 유한하지 않은 startedAt, UTC lstart, exit 4 안내, 삭제 범위, 실제 `~/.claude`·`/private/tmp/claude-501` 레이아웃 정합이다. 판정은 **PASS**.
## (a) de6f3fc 검증
1. **보유자 argv 에 uuid 가 남는다.**
- 새 보유자는 `[sys.executable, "-c", "import time; time.sleep(120)", conv]` 이다(`tests/test_issue31_purge_residual.py:317`).
- Python 인터프리터는 `-c` 뒤 인자를 `sys.argv[1]` 로 받을 뿐 exec 로 자신을 바꾸지 않으므로, `ps` 의 args 에 소문자 `conv` 가 그대로 남는다.
- `subprocess.Popen` 은 자식의 exec 성공을 확인한 뒤에 반환하므로, 이어지는 `time.sleep(0.05)` 시점에는 argv 가 이미 보인다(경합 없음).
- `sys` 는 파일 머리(`:22`)에서 이미 import 되어 있다. 같은 패턴인 `test_issue10_13_purge.py` 의 `_holder()` 와도 일관된다.
2. **upper/mixed 에서 통과한다.** 검증 경로에서 `-k any_spelling` 을 5회 반복 실행해 5회 모두 `2 passed` 였다. 관련 모듈 전체 실행에서도 통과했다(아래).
3. **철자 처리 회귀를 여전히 잡는다.** `git clone` 사본에서 claude 어댑터를 한 군데씩 변형해 test 파일 전체를 돌렸다.
- `conversation_in_use` 의 argv 검색을 `{canon, uuid}` 에서 `{uuid}` 로 바꿈(소문자 정규화 제거): 2 failed (upper, mixed). 실패 지점은 정확히 새 보유자 단언 `:320`, `AssertionError: a command line naming the lowercase id` 이다. 즉 수정된 보유자가 이 회귀를 잡는 바로 그 장치다.
- `_session_files(canon)` 을 `_session_files(uuid)` 로 바꿈: 2 failed (세션 파일 경로 단언에서).
- `_canonical` 의 `.lower()` 제거: 2 failed.
- 세 변형 모두 나머지 65개는 통과했으므로, 실패가 해당 테스트에 국한된다.
4. **정리 동작이 유지된다.**
- `try/finally: named.kill(); named.wait()` 구조는 그대로다(`:318-323`).
- 변형 실행(일부러 실패시킨 경우 포함)이 끝난 뒤 `ps -axo pid=,args=` 에서 `python … import time; time.sleep(120)` 프로세스는 0개였다. argv0 가 python 인 행만 세어 자기 자신과의 매칭은 배제했다.
## (b) 전체 판정을 위한 재확인
- 제품 파일(`.agents/` 전체)은 2a8d738 과 동일하므로, 2차 리뷰(job 778fc866)의 확인 결과를 그대로 승계한다. 다시 돌린 것은 위 변형 대조와 아래 관련 모듈이다.
- 알려진 비차단 세 가지는 브리프대로 병합 차단이 아니다. 내용은 2차 리포트에 적은 그대로다.
- 링크된 `projects/<key>` 아래 jsonl 은 purge 되지 않고 residual 로만 보고된다.
- 소문자 질의는 대문자 argv 보유자를 보지 못한다.
- `purge_artifacts` 를 직접 호출하면 in-use 게이트를 거치지 않는다.
## 테스트
검증 경로에서 `env -i`(HERDR_*·WORKSPACE_ROOT·MAM_*·DELEGATE_JOB_LOGS_DIR·CLAUDE_CONFIG_DIR 미설정), 스크래치패드 basetemp, `PYTHONDONTWRITEBYTECODE=1 -p no:cacheprovider` 로 실행했다.
- 실행 모듈: `test_issue31_purge_residual, test_issue10_13_purge, test_a4_adapter_contract, test_issue42_skill_blocks, test_issue55_agent_homes, test_orc_onboard, test_uuid_target, test_tier1_unit, test_tier2_component`
- 결과: **332 passed, 1 skipped, 1 error** (624 s). 2차의 2 failed 는 사라졌다.
- 1 error 는 `test_tier2_component.py::test_comp_codex_create_and_reconcile_and_stop` 의 **teardown 에서 #55 가드**가 낸 것으로, 브리프가 밝힌 알려진 오탐이다. 판정 근거로 쓰지 않고 보고만 한다.
- 가드가 잡은 경로: `~/.gemini/antigravity-cli/conversations/0dd4a87f-6170-472b-886a-eef6e099b375.db-shm` 과 `.db-wal`.
- 읽기 전용 확인 결과: 이 DB 는 다른 곳에서 돌고 있는 실제 `agy` 프로세스(pid 66733)가 열고 있다(`lsof -t`). WAL 이 자라는 중이다(mtime Oct 18 00:06, 크기 19.6 MB). 테스트 산출물이 아니다.
- 이 테스트는 2차 실행에서는 통과했고, 이번 커밋은 tier2 와 무관한 테스트 한 줄만 바꿨다.
## 비차단 메모
- 2차 리포트의 비차단 사항(`projects/<key>` 링크 시 동작 문서화 등)은 그대로다. 병합 후 별도 이슈로 다뤄도 된다.
[VERDICT: PASS]
@@ -0,0 +1,60 @@
# 🔍 Cross-Review Round 3 — Issue #5 Phase 2a (`6ad6f08..0e74aa1`, 신규 커밋 `cb575fa`+`0e74aa1`) — Job `49171b58`
- **Reviewer**: `planner-reviewer-claude-01` (Reviewer role)
- **대상**: 브리프 첨부 diff = `git diff 6ad6f08..HEAD` − `.agents/reports/*`(2914행, **바이트 동일**). HEAD=`0e74aa1`, working tree clean. Round 2(`cb792e91`) 대비 신규는 수정 커밋 `cb575fa`(9 files, +317/−52)와 문서 커밋 `0e74aa1`.
- **방법**: Round 2의 F-C/F-D와 Codex Round 2(`0026165b`)의 R1/R4 수정을 실제 CLI·실제 모듈로 재검증(F-C는 래퍼와 같은 `set -euo pipefail` 셸에서), Round 1 항목(F-A/F-B)의 회귀 여부 재확인, 신규 테스트 12종 독해, 전체 스위트 실행.
---
## 0. 결론 요약
- **Round 2 지적 전부 해소 — `[ADJUDICATION: SUSTAINED]`**. F-C: 멱등 ACK가 `TransitionResult.idempotent`로 구분되어 CLI가 rc 0을 내고, 래퍼 승인 경로가 `set -e` 아래에서 끝까지 진행된다(§1). F-D: `_operator_write` 첫 줄에서 `VALID_STATUSES` 검증이 두 모드 공통으로 복원돼 rc 1·레코드 불변이다(§2). Round 1의 F-A/F-B도 회귀 없이 유지된다(§3).
- Codex R1(관측 증거 **부재** 시 승인)·R4(감사 mirror의 비원자적 비교-후-쓰기)도 구현·테스트를 확인했다(§4). R4는 내가 Round 2 §2에서 비차단으로 언급한 창(window)을 닫는 것이라 특히 반갑다.
- **신규 결함 없음.** 자동완료 3표면·`lib.sh`·shim 무변경, 위생 클린, 전체 스위트 통과(§6). `[ESCALATE: PLANNER]` 불필요.
---
## 1. F-C 재검증 — 해소
- `engine.py:83-99` `TransitionResult.idempotent`, `:105-113` `_Decision.idempotent`, `:164-167`에서 같은 terminal 재수신에 `idempotent=True`. `registry.py:329-366` `_operator_write`: `committed` → 0, `idempotent` → 0, 그 외만 `refused:` + 4.
- **셸 수준 재현(Round 2와 동일 스크립트)**: 이미 `completed`인 레코드에 `status --set completed`를 `set -euo pipefail` 아래에서 실행 → `REACHED (CAS=1)` / `REACHED (CAS=0)`, bash exit 0. Round 2에서는 exit 4로 `REACHED`가 출력되지 않았다.
- `registry.main` 반환값 직접 확인(두 모드): 멱등 `--set completed` → **rc 0**, `cancelled` after `completed` → **rc 4**(CAS=1, 진짜 거부는 여전히 non-zero; CAS=0은 레거시 덮어쓰기 유지).
- `test_fc_idempotent_finalize_*`(두 모드), `test_fc_a_genuine_conflict_is_still_reported`(rc 4 유지), `test_fc_engine_marks_an_idempotent_result`가 고정. 문서: `state-transitions.md` Rev.5 "멱등 ACK는 거부가 아니다", `phase2a-shadow.md` §2-1 CLI 종료 코드 표(0/1/4).
## 2. F-D 재검증 — 해소
`_operator_write`가 CAS 분기 **이전**에 `status not in VALID_STATUSES`면 2a 이전과 같은 문구로 rc 1. 두 모드에서 `--set bogus` → **rc 1, 레코드 불변**(직접 확인). `test_fd_invalid_status_is_rejected_in_both_modes`가 레지스트리 디렉터리 지문까지 단정.
## 3. Round 1 항목 회귀 확인 — 유지
래퍼 시퀀스 재생: `completed → update --status pending --iteration 2` rc 0 · `pending/2`; `completed → status --set error` rc 0 · `error`. 지연 flush 실험: registry=`completed`, status.json=`completed`. 두 모드 병행 특성화(X-01~X-04, fa/fb)가 스위트에 남아 있다.
## 4. Codex Round 2 (R1, R4) 확인
| # | 구현 | 검증 |
|---|---|---|
| R1 증거 부재 시 승인 | `policy.py:20-23` `ATTRIBUTION_FIELDS`; `collect_observed_identity`(`:33-66`)는 식별자를 타임라인 항목의 **`collector_attribution` 봉투**(및 비-herdr 소스 payload)에서만 읽고 네이티브 Herdr payload 안의 식별자는 **증거로 취급하지 않는다**(Phase 0의 "네이티브 payload에 MAM 필드 금지"와 정합); `decide`(`:115-135`)는 4식별자 **전부 존재+일치**와 매니페스트 `attempt_id` 존재+일치를 요구 | `finalized_candidate.json`에 봉투 추가(다른 11종은 `hold`/`reject`라 무영향, 12벡터 `test_g7` 유지). `test_r1_missing_attribution_evidence_holds`(4필드 parametrize), `*_missing_report_manifest_holds`, `*_identifiers_inside_a_native_payload_are_not_evidence`. Phase 0 `validate_watcher_scenario` 41종 통과(봉투는 item 레벨 키라 네이티브 payload 검사와 충돌 없음) |
| R4 비원자적 비교-후-쓰기 | `update_logged_status`(`mqtt_common.py:577-619`)가 per-job 전용 락 파일(`.status.json.lock`, `_file_lock`) 아래에서 읽기-비교-쓰기, 임시 파일은 `mkstemp`(공유 `.tmp` 경로 제거). 레지스트리 락과 별개이며 레지스트리 트랜잭션 밖에서 잡힌다 | `test_r4_overlapping_mirror_flushes_*`는 첫 flush의 `read_text` 직후에 경쟁 flush를 스레드로 띄워 **실제로 블록됨**(`blocked is True`)과 최신 상태 생존을 단정 — 진짜 인터리빙 테스트다. `*_each_mirror_write_uses_its_own_temp_file` |
Grok Round 2(`32e936e5`)는 PASS + 기존 비차단 잔여로, 이번 수정과 충돌 없음.
## 5. 기타 확인
- `git diff --check 6ad6f08..HEAD` 클린, `compileall lib_py` 클린, 자동완료 3표면·`lib.sh`·shim 변경 0.
- `test_issue5_phase2a_loop.py` + `phase0` + `phase1` 합계 **195 passed in 12.57s**.
- 락 규율(G-5)·writer 인벤토리(G-6)·shadow 무기록(G-4)·패키지 규칙(G-9)은 이번 수정으로 영향받지 않았고(테스트 유지), R4의 감사 락은 레지스트리 락 밖에서만 잡혀 G-5의 "락 안 블로킹 금지"와 충돌하지 않는다.
- 비차단 메모(2b 인계, 이미 문서화됨): `started`의 세션 확인(O-A), `stop_session.sh`의 무조건 `cancelled`가 `completed` 이후 거부되는 동작(O-B).
## 6. 전체 스위트
HEAD(`0e74aa1`)에서 직접 실행 (`.venv/bin/python -m pytest tests/ -q`, 백그라운드): **664 passed in 899.99s (0:14:59)**, 0 failed, 0 skipped. Round 2의 650 대비 +14 (신규 함수 12개가 parametrize로 14 케이스). 총계는 실행 결과에서 직접 읽은 값이다.
---
## 7. 결론
Round 2에서 지적한 두 회귀(멱등 ACK의 거부 분류로 인한 래퍼 성공 경로 중단, 롤백 모드의 상태값 검증 소실)는 제시한 방향 그대로 정확히 고쳐졌고, 래퍼와 같은 셸 조건에서 실제 CLI로 확인했다. Codex의 R1/R4도 구현됐으며, 특히 R4는 감사 mirror의 마지막 경쟁 창을 닫는다. Round 1·2의 모든 항목이 회귀 없이 유지되고 새 결함은 발견되지 않았으므로 통과시킨다.
[ADJUDICATION: SUSTAINED]
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261013T025803Z-c69408",
"base_sha": "42e2a7ea9bd3e2770ed8626d789193428ca3aa8b",
"head_sha": "3a30d7da894cdac26b7ec054b4e66fe9fa3dc8db",
"tree_sha": "bd43e4642f0109091f5f497b2703dcbaf8e2616b",
"review_commit": "3a30d7da894cdac26b7ec054b4e66fe9fa3dc8db",
"reviewer": "planner-reviewer-claude-01",
"job_id": "495a1373",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-13T03:32:19Z"
}
@@ -0,0 +1,34 @@
# 테스트 격리 수정(u1e 의 WORKSPACE_ROOT) 리뷰 — 커밋 3a30d7d (job 495a1373)
- 리뷰어: planner-reviewer-claude-01 (Reviewer)
- 리뷰 identity: loop-20261013T025803Z-c69408 / base 42e2a7ea .. head 3a30d7da (커밋 1개, 테스트 2 파일) / tree bd43e464
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261013T025803Z-c69408/1` — HEAD·tree 일치, `git status --porcelain` 0 줄, **`.mam` 없음**(시작·종료 모두). 본 체크아웃 HEAD 42e2a7e(main) 변동 없음.
- 실행 안전: 모든 실행은 `env -i`(PATH/HOME/LANG/TMPDIR 만)로 브리프의 `-u` 목록을 포함한 라우팅 변수를 비웠고, basetemp 는 scratchpad 아래(이름에 "shim" 없음). 수정 전 재현은 검증 경로를 `git clone --no-hardlinks` 한 임시 복사본에서만 했고 거기 생긴 `.mam` 은 지웠다. 검증 경로에서 돌린 것은 W1/W2 뿐이며(W1 은 체크아웃을 tmp 로 복사해 그 안에서 노드를 돌린다), 끝난 뒤 검증 경로에 `.mam` 이 없음을 확인했다. 실제 `.mam`·`.mam.env`·모니터·실제 서버·에이전트 홈 미접촉.
## 1. 원인과 수정
- 원인(1차 README 리뷰에서 재현한 그대로): `test_u1e` 는 래퍼를 `subprocess.run(["bash", WRAPPER, "submit", …, "--dry-run"], env=dict(os.environ, HOME=…, MAM_ENV_FILE=…), cwd=tmp_path)` 로 부르는데, 래퍼가 source 하는 `lib.sh` 는 `WORKSPACE_ROOT` 가 없으면 체크아웃을 기본값으로 삼고(`lib.sh:26`) `_init_herdr_isolation` 이 `$WORKSPACE_ROOT/.mam/shim/herdr` 를 쓴다(`lib.sh:150-154`). conftest 의 `pytest_configure` 는 다른 체크아웃을 가리키는 `WORKSPACE_ROOT` 만 떨어뜨리므로 pane 밖에서는 변수가 없고, 체크아웃이 기본값이 된다.
- 수정(`tests/test_issue50_dispatch.py:167-170`): env 에 `WORKSPACE_ROOT=str(tmp_path)` 추가 → shim 은 `tmp_path/.mam/shim/herdr` 에 쓰인다. `tests/test_issue17_workspace_root_isolation.py:43`: 이 노드를 W1 `NODES` 에 추가. 두 파일 `py_compile` 통과. 같은 파일의 다른 테스트는 `decide.*` 를 in-process 로 부르므로(`_register`/`_edit`/`_event` 헬퍼) shim 을 쓰지 않는다 — 아래 §2 의 파일 전체 실행이 이를 확인.
## 2. 실행 결과
| 실험 | 결과 |
|---|---|
| **수정 전 복사본**(검증 경로 clone + `test_issue50_dispatch.py` 를 base 42e2a7e 로 되돌림): u1e 단독 | 1 passed, 복사본에 **`.mam/shim/herdr` 생성** — 원인 재현 |
| **수정 전 복사본**: W1(새 NODES 포함) | **FAIL**: `AssertionError: tests wrote into the checkout they ran in: ['.mam/shim', '.mam/shim/herdr']` — W1 이 이 노드로 회귀를 잡는다(복사본 안의 tmp 복사본에만 쓰였고 복사본 자체에는 `.mam` 없음) |
| **head, 검증 경로**: `test_issue17_workspace_root_isolation.py` (W1+W2) | **2 passed**, 검증 경로 `.mam` 없음 |
| **head 복사본**(`git archive`): `test_issue50_dispatch.py` 전체 | **49 passed**, 복사본 `.mam` 없음 |
W1 이 잡는 원리: W1 은 복사본에 `WORKSPACE_ROOT=<복사본>` 을 주고 노드를 돌린다. 수정 전 u1e 는 `os.environ` 을 그대로 물려주므로 래퍼가 그 복사본에 shim 을 쓰고, 수정 후는 `tmp_path` 로 덮어써 복사본에 아무것도 남지 않는다. pane 밖(변수 없음)에서도 lib.sh 의 체크아웃 기본값 때문에 같은 결과이므로 두 환경 모두를 대표한다.
## 3. 같은 결함이 남은 테스트가 있는가
- 정적: 래퍼·`lib.sh`·`run_loop.sh`·`create_session.sh`·`reconcile.sh`·`stop/resume_session.sh` 를 subprocess 로 부르는 테스트 파일 59 개를 추려 `mam_sandbox`/`own_workspace_root`/`WORKSPACE_ROOT` 참조 여부를 봤다. 참조가 하나도 없는 7 파일과, 참조가 적어 테스트별 누락이 있을 수 있는 18 파일(W1 NODES 에 없는 것 위주)을 골랐다.
- 경험적: 그 **25 파일을 head 의 `git archive` 복사본에서 파일마다 따로** 돌리고 매번 복사본의 `.mam` 을 봤다 — `test_b7_diff_untracked`, `test_deploy_freshness`, `test_deploy_layout`, `test_issue42_skill_blocks`, `test_issue45_herdr_config`, `test_issue5_phase0_contracts`, `test_local_mqtt`, `test_issue14_delivery_ack`, `test_issue18_liveness_contract`, `test_issue6_turn_handshake`, `test_issue26_envfile`, `test_issue26_ints`, `test_issue33_budget`, `test_layout`, `test_workspace_scope`, `test_a4_adapter_contract`, `test_issue45_restore`, `test_sanitize_and_mock_errors`, `test_sanity`, `test_issue12_registry_secrets`, `test_issue21_acceptance`, `test_issue15_registry_isolation`, `test_issue20_state_isolation`, `test_issue36_prompt_transport`, `test_issue34_job_tree`: 전부 통과(skip 은 tomllib/nats-docker 류), **`.mam` 생성 0 건**.
- 이전 리뷰들에서 같은 방식으로 돌린 파일들(leak·startup_path·shim_contract·issue17/9/45, scenario4, pane_lock, issue50_dispatch_herdr 등)도 검증 경로에 `.mam` 을 남기지 않았고, `.mam/shim` 이 생긴 경우는 모두 `test_issue50_dispatch.py` 가 포함된 실행뿐이었다(u1e). 즉 이 결함은 u1e 하나였고, 수정으로 닫혔다.
## 4. 잔류물
- clone 복사본·archive 복사본·basetemp·로그는 scratchpad 아래. 검증 경로는 깨끗(`.mam` 없음, `git status` 0 줄). #55 가드 오탐은 이번 실행에서 나오지 않았다.
## 결론
원인 진단이 맞고, `WORKSPACE_ROOT=tmp_path` 가 정확한 최소 수정이며, W1 은 수정 전 트리에서 이 노드로 실패하고 수정 후 통과한다. 다른 테스트에서 같은 누출은 25 파일의 파일별 실행으로 재현되지 않았다.
[VERDICT: PASS]
@@ -0,0 +1,131 @@
# 🔍 Review Report — PR #37 병합 전 독립 리뷰 (job `4ab12ae2`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-09-24
- **대상**: PR #37 `fix/issue-36` **@ `59be1c8`**, base `main 1debc7d` (v4.7.2). 6커밋, 11파일 `+765/−30`, `git diff --check` 클린.
- **검증 경로**: `/var/folders/.../T/mam-review/loop-20260924T080014Z-2b3df0/1`. **identity 확인**: `HEAD = 59be1c89…cb49`, `HEAD^{tree} = a009c906…fab7` — 브리프와 일치.
- **안전 규칙 준수**: 검증 경로·소스 워크트리(`multi-agent-mux-wt/pr-37`)·본 체크아웃(`main 1debc7d`) 모두 수정·커밋·checkout 없음. 실험은 scratchpad 임시 디렉터리(uuid4)에서만(래퍼는 `--dry-run` + `--agent human` + 도달 불가 브로커, 러너는 in-process 스텁), pytest 는 `AGENT_PYTHON_BIN` + `--basetemp=<검증 경로 밖>`. 실제 herdr·세션·`.mam`·데몬 조작 없음, push·merge·PR 상태 변경 없음.
## 결론 요약
**병합을 막을 결함은 없다.** 프롬프트는 러너·래퍼·lib.sh 도우미·옛 셸 러너·create 온보딩 다섯 경로 모두에서 파일로 간다(`grep -rn -- '--prompt '` 의 잔존 호출은 전부 셸 **함수** 인자이거나 문서/기본값이다). 비차단 지적 4건(H1–H4). 그중 **H1 은 재현한 실제 결함**이다: 파이썬 러너는 프롬프트 파일 **쓰기**가 실패하면(ENOSPC 등) 부분 파일을 `.mam` 에 남기고 예외를 그대로 던진다 — PR 이 셸 쪽 두 곳에서 고친 바로 그 부류가 러너에는 빠져 있다. 디스크 고갈 급의 경계 상황이라 차단으로 보지 않았지만, 릴리스 커밋이나 즉시 후속에서 세 줄로 닫을 것을 권한다.
## 1. 전달 경로의 완전성 (항목 1)
| 경로 | 이전 | 이제 | 근거 |
|---|---|---|---|
| 파이썬 러너 `_run_cmd` | `--prompt <text>` argv | `.mam/prompt-<loop_id>-XXXX.md` 에 쓰고 `--prompt-file` | `runner.py:467-502` |
| 래퍼 `submit` → `registry.py register` | `--prompt "$PROMPT"` | 파일로 왔으면 `--prompt-file` 그대로 전달, 텍스트로 왔으면 종전대로 | `multi-agent-mux-delegate-job:186-208` |
| 래퍼 loop 타입의 회차 `update` | `--prompt "$current_prompt"` | `$job_dir/prompt.md` 에 쓰고 `--prompt-file` | `:405-450` |
| `lib.sh` `delegate_submit_job` / `_delegate_submit_job_legacy` (제출 도우미 11곳의 종착) | argv | `_delegate_prompt_file` 로 `.mam/prompt-submit-XXXXXX` 에 쓰고 `--prompt-file`, 성공·실패 모두 `rm -f` | `lib.sh:2038-2046, 2049-2064, 2160-2174` |
| `lib_py/delegation/cli.py submit` | `--prompt` 필수 | `--prompt`/`--prompt-file` 상호 배타, register 로 그대로 전달 | `cli.py:29-33, 64-66` |
| 옛 셸 러너 `MAM_LOOP_PY=0` | `delegate_job_safe … --prompt "<text>"` (함수 인자) | 함수 안에서 `--prompt` 를 `.mam/prompt-shloop-XXXXXX` + `--prompt-file` 로 바꿔 래퍼 exec | `run_loop.sh:196-221`. `run_loop.sh` 의 잔존 `--prompt "…"` 11곳은 이 **함수** 호출이라 exec 을 거치지 않는다 |
| `create_session.sh --submit-job` | 주입문에 과제 본문 포함 | 과제는 `<jobs>/<id>/brief.md` 에 쓰고 pane 에는 **경로만** | `create_session.sh:625-646` |
### 1-1. 래퍼의 파일 처리 (실측, `--dry-run --agent human`)
- 상대 `--prompt-file "my prompts/p 1.md"` 는 **호출자 cwd 기준**으로 절대화된다(`:191`, `cd "$WORKDIR"` 이전) — `--workdir` 가 다른 곳이어도 찾는다. 상대 `--registry-dir "reg dir"` 는 종전대로 `--workdir` 기준이다(기존 의미 유지). 공백 경로 모두 안전.
- 등록된 `prompt` 는 **바이트 단위로 동일**(`'line1\nline2\n\n'`, 후행 개행 보존) — registry 가 파일을 직접 읽기 때문. 래퍼의 `$PROMPT` 변수(`$(<file)`)는 후행 개행을 잃지만 그것은 브리프 본문에만 쓰인다(H4).
- 래퍼는 호출자의 파일을 **지우지 않는다**(소유권은 호출자). `--prompt` 와 `--prompt-file` 동시 → 거부, 없는 파일 → `cannot read --prompt-file <절대경로>` 거부.
- 읽는 시점: register 는 래퍼의 첫 단계(`:207`)이고 래퍼는 잡이 끝날 때까지 블록하므로, 러너·lib.sh·셸 러너가 **래퍼 반환 후** 지우는 순서는 안전하다.
### 1-2. 임시 파일의 위치·권한·정리
| 생성자 | 위치 | 권한 | 정리 |
|---|---|---|---|
| 러너 | 제어 루트 `.mam/` (`self.mam_dir`) | `NamedTemporaryFile` → 0600 | `finally: os.unlink` — 성공·실패·**OSError(exec 실패)** 모두 (`:498-502`) |
| lib.sh | `${WORKSPACE_ROOT}/.mam/` | `mktemp` → 0600 | 제출 뒤 `rm -f`; **쓰기 실패 시 `rm -f` 후 return 1** (`lib.sh:2042`) |
| 셸 러너 | `$MAM_REAL_ROOT/.mam/` | `mktemp` → 0600 | 래퍼 반환 뒤 `rm -f`; 쓰기 실패 시 제거 + 원인 로그 + return 1 (`:201-205`) |
| create | `<jobs>/<id>/brief.md` (잡 디렉터리, 보존 대상) | umask | 실패 시 잡 `error` + exit 1 (`:632-637`) |
### H1 (비차단이지만 실제 결함, 재현) — 러너의 쓰기 실패는 부분 파일을 남기고 예외를 던진다
`runner.py:472-477` 의 `with NamedTemporaryFile(...) as fh: fh.write(p_text)` 는 `try` **바깥**에 있다. 파일이 만들어진 뒤 `write` 가 실패하면(ENOSPC·EIO) `finally` 의 `unlink` 에 닿지 않는다. 검증 경로의 러너를 in-process 로 띄우고 `write` 가 `OSError(28)` 을 내도록 감싼 결과:
```
RAISED: OSError [Errno 28] No space left on device ← delegate_job 밖으로 그대로 전파(트레이스백, 126 처리 아님)
leftover prompt files in .mam: ['prompt-loop-…-2ussg8e6.md'] ← 부분 파일 잔존
wrapper called: 0
```
같은 부류를 PR 은 `lib.sh:2042`(`|| { rm -f "$f"; return 1; }`)과 `run_loop.sh:201-205` 에서 고쳤고 S9 로 고정했지만, 러너에는 대응이 없고 테스트(S4/S4b)도 `subprocess.run` 의 OSError 만 다룬다. 브리프 항목 1 의 "쓰기 실패 시 부분 파일이 남지 않는지"에 대해 러너는 **아니오**다.
→ 권고: `with` 블록을 `try` 안으로 옮기고 `except OSError` 에서 `unlink` 후 `CompletedProcess(cmd, 126, "", "cannot write the prompt file: …")` 를 돌려주면 exec 실패와 같은 "실패 제출" 경로로 합쳐진다(3–4줄). `self.mam_dir.mkdir` 실패도 같은 블록에서 잡힌다.
## 2. 실패 처리 (항목 2)
- **exec 실패(OSError → rc 126)**: `_run_cmd` 가 `CompletedProcess(cmd, 126, "", "cannot start the wrapper: … (prompt N bytes, wrapper …)")` 를 돌려주므로 첫 시도·busy 재시도 모두 같은 "실패 제출" 경로로 들어간다. 재시도 실패 시 job id 가 없는 경우에도 이제 `log_error` 를 남긴다(`runner.py:525`, 이전에는 무언). `failed_submit_jobs` 처리는 바뀌지 않았다(id 가 있으면 등록, 없으면 `None` 반환 → 호출자가 `return 1`). S4/S4b 가 E2BIG·EAGAIN 으로 고정.
- **재심·중재 미등록 → rc 1**: `:1354-1357`, `:1376-1378`. 판정 잡이 등록조차 안 됐는데 "반론 기각"이나 "중재 없음"으로 흘러가던 것을 실패로 바꾼 것이라 맞다.
- **순응(compliance) 잡 `wait_for_job` 실패 → rc 1** (`:1392-1395`): 의도된 강화로 판단한다. 근거는 **정규 수정 잡과의 대칭**이다 — 일반 correction 잡도 `if not correct_jid or not self.wait_for_job(correct_jid): return 1` (`:1323-1326`) 로 끝난다. 순응 잡은 "반론이 기각됐으니 그대로 고쳐라"는 수정 잡의 변형이므로, 시간 초과·에러로 닫힌 잡을 두고 다음 리뷰 라운드로 가면 **바뀌지 않은 트리를 다시 리뷰**하게 된다. 루프가 `wait_for_job` 실패를 통과시키는 자리는 이제 self-review(`:1187`)뿐이고 그것은 판정 리포트로 따로 걸러진다. S3c 가 세 경로(comply/adjudication/arbitration)의 미등록을 고정한다.
## 3. `MAM_DIFF_MAX_BYTES`/`MAM_DIFF_MAX_LINES` (항목 3)
- `diff_collect.sh:9-11` 주석이 "증거 크기의 상한이지 전달 상한이 아니다"를 명시하고, 상한값·잘림 마커·`runner.py` 의 l15 규칙(잘린 diff 면 diff-only 원격 리뷰어 거부, 로컬 진행)은 **변경되지 않았다**(runner 의 해당 블록은 diff 밖). S5 가 "옛 사각지대"(131,072 < diff < 200,000 바이트)의 diff 가 통째로 전달됨을 고정한다.
- **H2 (비차단, 문서)**: loop SKILL.md 에는 이 두 변수도, 잘림 마커의 의미도 적혀 있지 않다(grep 0건). delegate-job SKILL.md 는 argv 상한만 말한다. "전달은 무제한, 증거는 200 KB/4,000 줄에서 잘리며 잘린 diff 는 diff-only 원격 리뷰어에게 증거가 못 된다"는 한 문단이 loop SKILL.md 에 있어야 항목 3 의 "일관 반영"이 완성된다.
## 4. `create_session.sh` (항목 4)
- 잡 등록은 종전대로 lib.sh 의 `delegate_submit_job`(파일 경유)이고, 그 뒤 `<jobs>/<id>/brief.md` 에 과제를 쓰고 pane 에는 `Task: read the complete task in <절대경로> and follow it.` 만 주입한다(`:625-646`). `$pub`(`delegate_publish_cmd` 의 `--expect-dispatch-token`·`--attempt-id`)와 `started` 기반 판정은 **손대지 않았다** — #23 계약 유지. S8 이 주입문에 brief 경로는 있고 과제 본문은 없음, `--expect-dispatch-token`·`--event started` 가 남아 있음을 단언한다.
- 경로: `${MAM_JOBS_DIR:-${WORKSPACE_ROOT:-$PWD}/.mam/jobs}` 를 절대화하므로 워크트리 creator(제어 루트 바인딩)도 자기 cwd 와 무관하게 읽을 수 있다. 래퍼가 만드는 `brief.md` 와 같은 자리다.
- 실패 시 잡 `error` + `JOB_TERMINALIZED=1` + exit 1 → 기존 트랩이 세션을 되돌린다(초기화 실패와 같은 취급).
## 5. 새 테스트 22건 (항목 5)
- **실제 경로를 지나는가**: S1 은 실제 래퍼(`bash multi-agent-mux-delegate-job submit --dry-run`)와 실제 `registry.py` 로 140,000 바이트를 등록해 **바이트 단위 동일**을 단언한다. S2/S3/S3b/S3c 는 `python -m lib_py.loop` 를 하위 프로세스로 띄우고 가짜 래퍼가 받은 인자를 검사한다. S7/S7b/S9 는 `run_loop.sh`(MAM_LOOP_PY=0)를 실제로 돈다. S8 은 mock herdr 위에서 `create_session.sh` 를 실제로 돈다. mock 으로 우회하는 것은 S4/S4b(`subprocess.run` 을 OSError 로 대체 — 커널 대신 코드 경로를 검증하는 것이 목적)뿐이다.
- **macOS**: `MAX_ARG_STRLEN` 이 없어 단일 인자 150 KB 가 통과하므로 S1b(음성 대조군)는 `linux_only` 로 **skip** 되고, S8 의 `strace` 검사는 Linux 에서만 붙는다. 즉 이 호스트에서 스위트는 **커널 상한이 아니라 코드 경로**(파일로 전달됐는가)를 검증한다 — 브리프의 우려 그대로이며, 설계상 옳다. 실제 상한 재현은 Linux CI 몫.
- **격리**: `_env()` 가 `HOME`·`WORKSPACE_ROOT`·`DELEGATE_JOB_LOGS_DIR` 를 `tmp_path` 로, 브로커를 `127.0.0.1:9` 로 고정하고 `MAM_JOBS_DIR`/`MAM_REAL_ROOT` 를 제거한다. 실제 `.mam`·홈 접촉 없음(§6 실측).
- **수정 없이는 실패하는가 — 확인함**: 검증 경로 사본에서 PR 이 바꾼 소스 8파일을 `1debc7d` 판으로 되돌리고 새 파일을 돌린 결과 **18 failed / 3 passed / 1 skipped(S1b)**. 통과 3건은 정정 전에도 성립하던 것(래퍼 실패 → rc 1 등)이다.
## 6. 검증 경로에서의 테스트 실행 (항목 5·6)
```
tests/test_issue36_prompt_transport.py tests/test_issue5_phase1_delegation.py tests/test_issue14_delivery_ack.py
tests/test_loop_cli.py tests/test_issue21_loop_b.py tests/test_issue21_acceptance.py tests/test_issue23_24_startup_path.py
tests/test_issue25_plan_reuse.py
→ 1 failed, 237 passed, 1 skipped in 422.71s (0:07:02)
```
- **skip 1**: S1b(`linux_only`) — 설계된 것(§5).
- **failed 1: S9 — 코드 결함이 아니라 테스트의 macOS 이식성 문제(H5).** S9 는 `ulimit -f 1` 로 쓰기를 실제로 실패시킨 뒤 세 가지를 단언한다: rc≠0, stderr 에 `File too large`, 부분 파일 없음 + 원인 문구. 같은 하네스를 scratchpad 에서 직접 돌린 결과 **rc=1, 부분 파일 없음, `delegate_job_safe: cannot write the prompt file` 출력** — 즉 PR 이 고친 동작(제거 + 원인 표시)은 macOS 에서도 성립한다. 실패한 것은 두 번째 단언뿐이다: macOS 의 `/bin/bash` 3.2 는 `printf` 의 쓰기 실패에 대해 `printf: write error: File too large` 문자열을 내지 않는다(Linux bash 5 의 형식). `strerror(EFBIG)` 자체는 macOS 에서도 "File too large" 이므로 순수하게 bash 버전 차이다. S1b 처럼 `linux_only` 로 두거나, 그 단언을 빼고 원인 문구 단언만 남기면 된다.
- 기존 계약 스위트(issue5 phase1 의 registry CLI 스냅샷·help 캡처, issue14, loop_cli, issue21 loop B·acceptance, issue23/24 S7*, issue25)는 **전부 통과** — `--prompt` 하위 호환과 온보딩 계약이 유지된다(항목 4·6).
### 격리·위생 실측
| 항목 | 결과 |
|---|---|
| 실제 `.mam/jobs` / `.mam/delegate_job_logs` 전후 | **차이 0 / 차이 0** |
| 실제 `.mam` 의 `prompt-*` 잔존 | **0** |
| 검증 경로 `.mam` 의 `prompt-*` 잔존 | **0** (러너·셸 러너·lib.sh 의 정리가 실제 실행에서도 성립) |
| 검증 경로 tracked 파일 | 변화 없음(HEAD `59be1c8`), 본 체크아웃 `main 1debc7d` |
| 실행 시간 | 새 파일 22건은 34 s 안팎(되돌린 사본 기준 34.5 s); 전체 7 분은 issue14/18 계열의 벽시계 시험 몫 |
## 7. 문서 (항목 7)
- delegate-job SKILL.md `:44-48`: `--prompt-file` 의 의미와 argv 상한, "루프는 항상 파일을 쓴다" 명시 ✓. 래퍼 usage(`:112-121`)도 갱신 ✓.
- loop SKILL.md `:267`: 파이프라인에서의 종료 코드(`pipefail`/`PIPESTATUS`) 안내 ✓. 그러나 `MAM_DIFF_MAX_*` 의 새 의미는 없다(H2).
- `.claude/skills`: 본 체크아웃의 것은 git 에 추적되지 않는 로컬 심링크(`../../.agents/skills/*`)라 자동 동기화된다 — 배포 사본 정합 문제 없음.
## 8. 병합 차단 여부 (항목 8)
버전 락스텝 bump 부재(`lib.sh:32` `4.7.2`, 오케스트레이터가 4.7.3 으로 처리 예정) 외에 **병합을 막을 결함은 없다**. 다만 H1 은 릴리스 커밋에 함께 넣거나 즉시 후속으로 닫기를 권한다 — 셸 쪽과 같은 부류이고 수정이 세 줄이다.
| # | 지적 | 성격 | 근거 |
|---|---|---|---|
| H1 | 러너의 프롬프트 파일 **쓰기** 실패 시 부분 파일 잔존 + 예외 전파(126 실패 제출로 합류하지 않음) — 재현 | 비차단(경계 상황), **후속 권고 1순위** | `runner.py:472-477` vs `:490-502`; §1 H1 |
| H2 | `MAM_DIFF_MAX_*` 의 "증거 상한, 전달 무제한" 의미가 loop SKILL.md 에 없음 | 문서 | `diff_collect.sh:9-11` 에만 있음 |
| H3 | 래퍼는 **빈** `--prompt-file` 을 받아들여 빈 프롬프트를 등록한다(실측) | 사소 | `multi-agent-mux-delegate-job:195` 의 `-n "$PROMPT" \|\| -n "$PROMPT_FILE"` |
| H4 | 래퍼의 `$PROMPT="$(<file)"` 는 후행 개행을 잃는다 — registry 의 프롬프트(파일 그대로)와 브리프 본문이 그 점에서 다를 수 있음 | 사소 | `:193` |
| H5 | S9 의 `File too large` 단언이 macOS bash 3.2 에서 실패(문자열 형식 차이); 실질 단언 2개는 통과 | 테스트 이식성 | §6 |
## 9. 교차검증 가이드
```bash
RP=/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20260924T080014Z-2b3df0/1
PY=/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.venv/bin/python
git -C "$RP" rev-parse HEAD 'HEAD^{tree}' # 59be1c8… / a009c90…
grep -rn -- '--prompt ' "$RP/.agents/skills" | grep -v '\.md:' # 래퍼 usage/기본값, cli 주석, run_loop.sh 의 함수 호출뿐
# H1 재현: 러너 in-process, NamedTemporaryFile.write 가 OSError(28) → .mam/prompt-* 잔존 + 예외 전파 (§1 H1 의 스크립트)
# S9 하네스 직접 실행(macOS): rc=1, 부분 파일 없음, "cannot write the prompt file" 출력, 단 "File too large" 문자열 없음
# 되돌린 사본: 소스 8파일을 1debc7d 판으로 → tests/test_issue36_prompt_transport.py → 18 failed / 3 passed / 1 skipped
```
[VERDICT: PASS]
@@ -0,0 +1,40 @@
# 🔍 Post-Commit Cross-Review — v4.1.3 Release Packaging (Commit `85a46ef`, Job `4d3c2c1c`)
- **Reviewer**: `planner-reviewer-claude-01`
- **Target**: commit `85a46ef` — "chore(release): bump framework and 8 skills to v4.1.3" (already on `main`; no uncommitted diff to review, so this is a post-commit audit against the checklist).
- **Method**: read the actual commit via `git show`, verified every touchpoint against live file content, ran the version-lockstep tests and the full suite myself.
---
## 1. 3-Way Version Lockstep
- `lib.sh:32`: `MAM_VERSION="4.1.3"` — confirmed exact, single-line change, comment/export logic untouched.
- `VERSIONS.md`: current-version header now `v4.1.3` / `2026-08-31 (KST)`; all 8 rows of the skill matrix updated to `4.1.3`; new `### 🛠️ v4.1.3` changelog section inserted correctly *above* the existing `v4.1.2` entry (chronological order preserved), with accurate C-1/C-2 bullets that match the actual code changes and cite the correct tests (`test_h26`, `test_t14`, `test_t16`, `test_t15`).
- All 8 `SKILL.md` frontmatters (`create`, `stop`, `resume`, `status`, `monitor`, `delegate-job`, `loop`, `orc-onboard`): each diff is a clean, isolated `version: 4.1.2` → `4.1.3` line change — no other frontmatter fields touched, verified by reading every one of the 8 diff hunks directly.
- `tests/test_version_consistency.py`: ran both `test_three_way_version_lockstep` and `test_mam_version_is_not_env_overridable` myself — **both PASS** at the new v4.1.3 state.
Lockstep is fully correct and complete.
## 2. Reviewer-feedback doc sync (`multi-agent-mux-resume/SKILL.md`) — one real inaccuracy found
**Line 55** ("UUID resolution order" prose): correctly and accurately updated — *"If both are empty → for Class A agents (`agy`, `hermes`, `opencode`), `resume_session.sh` automatically falls back to `FRESH_SPAWN=1` (`spawn-spec`). For Class B agents (`claude`, `grok`), fall back to `multi-agent-mux-create`."* This precisely matches the real, already-verified `resume_session.sh` behavior.
**Lines 71-75** (the "Workflow" section's illustrative bash snippet): here I found a genuine content inaccuracy. The added comment says *"For Class A, `resume_session.sh` handles fresh-spawn fallback automatically"* — correct — but the `echo` text right below it on the very next line was changed to:
```
echo "No saved session for $WORKSPACE ($AGENT). Class B agents must use multi-agent-mux-create first."
```
I checked the **actual, live** `resume_session.sh` error string (line 67): it is byte-for-byte unchanged from before this whole Issue #3 effort — `"ERROR: No saved session for $WORKSPACE ($AGENT). Use multi-agent-mux-create first."` — with no "Class B agents must" phrase anywhere in it (I deliberately preserved this exact string across `a9c8d6d3`/`398afb2e` specifically because Class B's contract was to stay byte-identical). The doc's illustrative snippet now shows a **fabricated error string that the real script never actually prints**.
This is a pre-existing pattern of the "Workflow" section being a simplified, non-literal walkthrough (it has never had an `opencode` case arm in its `case "$AGENT" in ...` blocks, for instance, even though `opencode` is a supported agent — that gap predates this release and is out of scope here). But this specific edit *introduces* a new inaccuracy rather than just continuing the existing simplification: previously the illustrative echo text matched the real error message nearly verbatim (modulo the missing `ERROR:` prefix); now it doesn't match at all. A reader who greps for this exact string against real output, or who takes the snippet as literal, would be misled.
**This is non-blocking**: it's confined to an illustrative code comment/example (not the authoritative prose above it, which is correct), doesn't affect any runtime behavior, and doesn't touch the 3-way lockstep contract. Recommend a follow-up one-line fix: either revert the echo text to the real script's exact string, or make the whole `if [ -z "$UUID" ]` block in the example actually branch on agent class (mirroring the real script) instead of adding a claim the flat example doesn't back up.
## 3. Full regression sweep
Ran myself at the current `HEAD` (post-`85a46ef`): **455 passed, 0 failed**, 12m31s. `git status` clean (no uncommitted drift).
## 4. Verdict
The 3-way version lockstep is fully correct and test-verified; the changelog is accurate; the primary documentation-sync requirement (line 55) is correct. One non-blocking documentation inaccuracy found and specifically located (lines 71-75's example error text doesn't match the real script's preserved error string) — recommend a small follow-up fix, but it does not affect release correctness, runtime behavior, or the lockstep contract this commit was packaging. No lint/functional defects in the actual shipped code or version files.
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261020T133532Z-a1684a",
"base_sha": "ff8b381520ae04e80c73a9e18bfad73d47e853c9",
"head_sha": "feccfd5e0356c8acf0438bc68bce7ea36ce2588e",
"tree_sha": "0f0f33cc22f5e492a0ddfccb6bac5be888c10d1a",
"review_commit": "feccfd5e0356c8acf0438bc68bce7ea36ce2588e",
"reviewer": "planner-reviewer-claude-01",
"job_id": "5bdb3a81",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-20T15:51:16Z"
}
@@ -0,0 +1,116 @@
# Issue #40 리뷰 — Class A 세션 ID 자동 확정, agy 다른 작업 공간 ID 오등록 방지 (job 5bdb3a81)
- 리뷰어: planner-reviewer-claude-01
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261020T133532Z-a1684a/1`
- identity: HEAD `feccfd5e0356c8acf0438bc68bce7ea36ce2588e`, tree `0f0f33cc22f5e492a0ddfccb6bac5be888c10d1a` 가 일치한다. 작업 트리는 clean 이고 `.mam` 은 없다.
- 범위: base `ff8b381`..head 1커밋, 19개 파일. 판정은 base..head 전체에 대한 것이다.
- 기준 문서: 이슈 본문과 댓글 전체(`issue40.txt`)를 끝까지 읽고 합의 사항과 대조했다.
- 환경: macOS, Python 3.9.6.
- 실제 에이전트 홈은 `ls` 와 `lsof -p <agy pid>`(프로세스 테이블 조회)로만 봤다. 파일 자체를 연 적은 없다.
- 재현과 테스트는 모두 scratchpad 의 임시 HOME, mock herdr, git archive 사본에서 했다.
## 결론
합의된 설계(PR #41 리뷰·이슈 댓글)대로 구현됐고, 완료 조건 1-4 가 테스트로 고정됐다. 각 조건의 테스트는 base 에서 실패하고 head 에서 통과한다. 이 변경이 만든 회귀는 찾지 못했다. 남은 것은 테스트 보강 권고와 운영 위험 기록이다.
## 설계 확인 (합의 대비)
**어댑터는 사실과 판정만 제공한다.**
- `id_lifecycle`: 기본값은 `POST_DISCOVERED`. claude·grok 만 `PRE_ASSIGNED` 이다(`base.py:378-381`, `claude.py:188`, `grok.py:18`).
- `capture_active_session_id`(`base.py:383-401`): `discover()` 후보 가운데 `verify_session_uuid` 를 통과하고 다른 행이 기록하지 않은 것이 정확히 하나일 때만 `captured` 를 돌려준다. 그 밖에는 이유가 담긴 결과(`capture_result`)를 돌려준다. 읽기 전용이다.
- 설정 추가나 리팩터링은 없다.
**agy 경로 (`agy.py`)**
- `verify_artifact` discover 모드(`:97-106`): `last_conversations.json` 이 그 id 를 다른 cwd 에 매핑하면 거절한다(workspace_key 로 비교). 다른 행이 기록한 id 는 캐시가 일치해도 항상 거절한다. 이제 캐시 일치가 이 검사를 건너뛰지 못한다.
- `capture_active_session_id`(`:129-152`): 후보는 `last_conversations.json[cwd]` 하나뿐이다. 그 대화의 presence lock 이나 DB 를 그 행의 pane 프로세스 또는 그 자손이 열고 있어야 확정한다(`_owner_check`, `:154-183`, lsof/ps). 증명하지 못하면 확정하지 않는다.
- 이 근거를 실제로 확인했다. 이 Mac 에서 실행 중인 agy 3개(`--conversation <id>`)는 모두 자기 `presence/<id>.lock` 을 열고 있다(`lsof -p`).
- `_holder_pids`·`_process_parents` 를 macOS 에서 직접 확인했다. 아무도 안 연 파일은 `[]`, 연 파일은 보유 pid 를 돌려준다(0.13s). ps 표에는 자기 pid 가 들어 있다.
**reconcile drift C (agy·hermes·opencode·codex) 가 하나로 합쳐졌다** (`reconcile.sh:778-811`).
- 네 에이전트가 모두 `autopin.capture` 를 거쳐 같은 어댑터 판정을 쓴다. agy 의 `*.db` 전체 glob 은 사라졌다.
- 기존 안전장치는 그대로다: 후보가 둘 이상이면 C-ambiguous, 뷰포트가 다르면(rc 1) C-warn 으로 pin 안 함, 뷰포트 확인이 불가하면(그 밖의 rc) degraded pin.
- 다른 행이 가진 id 배제는 더 엄격해졌다. 예전에는 같은 cwd 의, 멈추지 않은, 같은 에이전트 행만 봤다. 지금은 다른 모든 행의 모든 own key 를 본다(`autopin.claimed_elsewhere`).
- 지운 hermes·opencode·codex SQL 은 각 어댑터의 `discover()` 와 같은 범위(cwd·epoch·`parent_id IS NULL`)다. codex 는 `CODEX_HOME` 을 따른다(`codex.py:65`).
**수신 측 처리기 (`lib_py/agents/autopin.py`)**
- 호출 지점:
- 래퍼: `finalize_unfinished` 뒤 `completed` 일 때(`multi-agent-mux-delegate-job:454-458`). stderr 로만 출력하므로 마지막 stdout 줄(audit-log 경로) 계약은 그대로다.
- `create --onboard` 의 completed 분기(`create_session.sh:754-756`)
- 루프 `wait_for_job` 직후의 서브프로세스(`runner.py:679, 690-705`, G9 경계를 지킴)
- 공통 헬퍼 `delegate_autopin_completed`(`lib.sh:2470-2480`)는 `|| true` 라 잡 결과와 종료 코드를 바꾸지 않는다. `set -u` 에서 쓰는 변수(`AGENT_SESSIONS_YAML`, `_disp_tok`, `DELEGATE_JOB_TOKEN`, `task_reg_dir`)는 모두 정의돼 있다.
- 중복 방지:
- 키는 `(job_id, dispatch_token, attempt_id)` 이다. 잡 디렉터리의 `autopin.lock`(flock)과 `autopin.json` 마커를 쓴다. 마커는 원자 교체로 쓴다.
- 쓰기는 `atomic_dump_yaml` 의 mutation 으로 한다. 이 모듈의 `_MUTATION` 을 `sys.modules[__name__]` 로 찾아 `python -m` 에서도 같은 객체를 쓴다. 쓸 것이 없으면 `SystemExit(0)` 으로 쓰지 않고 끝나며, `atomic_yaml.py:195` 의 finally 가 정리한다.
- 건너뛰는 잡: remote, human, completed 가 아닌 잡, 오래된 token. pre-assigned 와 이미 id 가 있는 행은 쓰기 없이 끝난다.
- 메타데이터: pin 은 `session_id_source=discovered`, `session_id_verified=true` 를 함께 기록한다. reconcile 의 `_pin_and_verify_resume` 도 같은 `pin_row` 를 쓴다. 이슈 댓글이 짚은 불일치(선택 항목)가 해결됐다.
- publish_event.py 는 바뀌지 않았다. 에이전트는 제어 평면에 쓰지 않는다(`test_call_sites_and_publisher_boundary`).
- 잠금 안에서 뷰포트 확인과 resume `--dry-run` 을 서브프로세스로 실행한다. 예전 reconcile 도 mutation 안에서 똑같이 했다. `load_state_json` 은 YAML flock 없이 SQLite 를 읽으므로 교착은 없다.
## 완료 조건별 테스트 (base 실패 / head 통과)
`tests/test_issue40_auto_pin.py`(27개)를 base 사본에 넣어 실행하면 **16 failed, 13 errors**(errors 는 base 에 없는 `agy._holder_pids` 를 패치하는 fixture 때문), **41 passed**(issue64 포함) 이다. head 에서는 issue40+issue64 **70 passed**.
| 조건 | 테스트 | base 결과 |
|---|---|---|
| 1 | `test_agy_verify_rejects_id_cached_for_another_workspace` | `True is False` |
| 1 | `test_reconcile_does_not_pin_another_workspaces_agy_conversation` | `'b4000002…' is None` — 실제로 B 의 id 를 A 행에 기록함 |
| 1 | `test_autopin_does_not_pin_…` | — |
| 1 | issue64 `:407` 단언 | `is False` 로 바뀜 |
| 2 | `test_completed_onboarding_pins_agy_without_daemon`(MAM_NO_SUBSCRIBER_DAEMON=1, B 가 더 늦게 갱신) | — |
| 2 | `test_completed_first_job_pins_opencode_codex_hermes`[3] | 실패 |
| 2 | `test_reconcile_pins_agy_owned_by_the_pane`, `test_lib_sh_helper_pins_through_the_cli`, `test_create_onboard_pins_without_daemon` | 실패 |
| 3 | `test_wrapper_and_loop_recovery_pin_once`(capture 1회, YAML mtime 불변), `test_loop_recovery_pins_when_the_wrapper_did_not` | 실패 |
| 3 | `test_ambiguous_candidates_leave_reason_without_pin`(행에 `autopin ambiguous (job amb): 2 candidates`) | 실패 |
| 4 | `test_preassigned_and_existing_ids_are_untouched`, `test_ineligible_jobs_pin_nothing`, `test_stale_dispatch_token_pins_nothing` | — |
- reconcile 테스트는 세션을 mock herdr state 에 running 으로 등록한다(`_mock_agent`). 그래서 drift A 에서 멈추지 않고 실제로 drift C 까지 간다. base 에서 B 의 id 가 기록되는 것이 그 증거다.
뮤테이션: git archive 사본에서 issue40 모듈만 돌렸다.
| 뮤테이션 | 결과 |
|---|---|
| 다른 cwd 거절 제거 | 1 failed |
| 중복 마커 무시 | 2 failed |
| 모호 판정 제거 | 1 failed |
| agy 소유 확인 제거 | 4 failed(같은 cwd 형제 교차 pin 포함) |
| 이미 id 가 있는 행 보호 제거 | 1 failed |
| remote·human 제외 제거 | 2 failed |
| 래퍼 호출 제거 | 1 failed(정적 검사만 잡음) |
| **pre-assigned 보호 제거** | **실패 0** (아래 T1) |
## 관련 테스트 묶음
- 조건: `env -i`, 임시 HOME, `XDG_DATA_HOME=<scratchpad>`, basetemp 는 scratchpad.
- 대상 18개 모듈: issue40, issue64, a4, issue10_13, issue31, issue50_dispatch, issue55, issue57, issue60_linux_fixes, issue60_opencode_v2, tier1, tier2, uuid_target, orc_onboard, issue21_phase2_loop_a, issue5_phase3_loop, issue21_worktree_prereqs, issue17_workspace_root_isolation.
- 결과: **577 passed, 1 skipped, 3 failed**, 18분.
- 실패 3개(`test_issue21_phase2_loop_a::test_w10_…[install.sh|install_mam.sh]`, `test_w11_…`)는 환경 탓이다.
- 설치 스크립트가 시스템 python3 의 PyYAML 을 찾는데, 이 Mac 의 PyYAML 은 사용자 site(`~/Library/Python/3.9/...`)에만 있다. 내가 HOME 을 임시로 바꿔서 보이지 않았다.
- base 사본에서도 같은 3개가 같은 이유로 실패하고, 설치 스크립트는 이 diff 에 없다. 판정 근거로 쓰지 않았다.
- skip 1개: PATH 에 opencode 가 없는 실바이너리 계약 테스트.
- 부작용 확인:
- 실제 `~/.gemini/antigravity-cli/conversations`·`~/.hermes`·`~/.local/share/opencode` 목록은 전후가 같았다.
- scratchpad XDG 디렉터리는 실행 뒤에도 비어 있었다.
- #55 가드 오탐은 없었다.
- 린트:
- `git diff --check` 는 깨끗하다.
- 바뀐 셸 4개(lib.sh, create_session.sh, 래퍼, reconcile.sh)가 `/bin/bash -n`(3.2)을 통과한다.
- 바뀐 Python 은 3.9 로 파싱된다. `/usr/bin/python3` 로 `lib_py.agents.autopin`·`lib_py.loop.runner` 를 import 할 수 있다.
## 비차단
- **T1. pre-assigned 보호(`autopin.capture` 의 `id_lifecycle != POST_DISCOVERED`)는 테스트로 고정되지 않았다.**
- 테스트의 claude·grok 행은 이미 id 가 있어서 `already-set` 에서 먼저 끝난다.
- id 가 비어 있는 claude 행이 생기면(예: 행을 손으로 고침), 이 보호 없이는 기본 capture 가 claude `discover()` 로 남의 transcript 를 pin 할 수 있다.
- 권고: `claude_session_id_own: None` 인 claude 행에서 `pre-assigned` 가 나오는지 확인하는 한 줄을 추가한다.
- **T2.** 래퍼 진입점은 정적 검사(`test_call_sites_…`)로만 고정됐다. 헬퍼(`lib.sh`)와 CLI, create, 루프는 실행으로 검증됐다.
- **R1. agy 의 pin 은 이제 세 가지에 기댄다**(reconcile drift C 도 같다):
- (a) lsof·ps 가 있어야 한다
- (b) 행에 pane pid 가 있어야 한다
- (c) agy 가 presence lock 을 열고 있어야 한다
- (c) 는 resume 된 agy 3개에서 확인했다. 새로 띄운 agy 의 첫 턴 직후는 실제 agy 를 띄울 수 없어 확인하지 못했다.
- lsof 가 없는 Linux 에서는 agy 가 영영 pin 되지 않는다. 예전 glob 경로는 pin 했다(오등록 위험을 감수하고). autopin 경로는 행에 `autopin unverifiable-owner … lsof is unavailable` 을 남기지만, reconcile 은 아무것도 남기지 않는다.
- 설계상 의도된 안전 쪽 선택이다. 그래도 Linux 의존성으로 문서에 한 줄 적어 두기를 권한다.
- **R2.** 중복 마커는 실패 결과도 기록한다. 래퍼 시점에 `no-candidate` 였던 잡은 루프 복구 경로에서 다시 시도되지 않는다. 다음 잡의 completed 나 reconcile 이 다시 시도한다. 합의("job/token/attempt 단위로 중복 금지")와 맞다.
- **범위 밖(보고만).** stop 의 캡처 경로는 정리하지 않았다(이슈가 "크면 하지 말고 보고만"이라고 함).
[VERDICT: PASS]
@@ -0,0 +1,183 @@
# 🔍 Cross Review — Job 5e43d80f: Layout Engine 2×K 구현
- **Reviewer**: `planner-reviewer-claude-01`
- **대상**: W1~W5 (`layout.py`, `lib.sh:435`, `.mam.env.example`, 테스트 3파일)
- **검증**: BSP 시뮬레이터 실행 + 헤드리스 궤적 실행 + **pytest 전체 393건 실행**
> **이해충돌 고지**: 본 구현의 사양(`layout_engine_improvement_plan.md` Rev.2)은 제가 Planner 로 작성했습니다. 아래는 **타인이 작성한 코드가 그 사양을 충족하는가**에 대한 검증이며, 사양 자체의 타당성에 대한 독립 검증이 아닙니다. §4 의 F-1 은 실제로 **제 사양의 결함**이며 그렇게 명시합니다.
---
## 1. 핵심 목표 달성 — 실측 확인
BSP 세분할 시뮬레이터로 N=1→5 궤적을 실행했습니다.
```
N=1 [p1 277x78]
N=2 split right on p1 (new_column_right)
p1 138x78 / p2 139x78 widths=[138,139] heights=[78] balanced=True
N=3 split down on p1 (fill_column)
p1 138x39 / p3 138x39 / p2 139x78 (전이 상태 — 정상)
N=4 split down on p2 (fill_column)
p1 138x39 / p3 138x39 / p2 139x39 / p4 139x39
widths=[138,139] heights=[39] balanced=True ← 🎯 깨끗한 2×2
N=5 OVERFLOW (grid_capacity_reached) → 새 워크스페이스
```
**4 에이전트 2×2 목표 달성.** Rev.1 이 진단한 R-1 왜곡(N=4 에서 widths `{138,139,277}`, heights `{19,20,39}`)이 완전히 해소되었습니다.
### 1.1 GUI ↔ 헤드리스 패리티 (C-1 처방 검증)
```
headless n=1: right target=p1 reason=new_column_right
headless n=2: down target=p1 reason=fill_column
headless n=3: down target=p2 reason=fill_column
headless n=4: overflow target=p4 reason=grid_capacity_reached
```
GUI 와 **방향·순서가 완전히 일치**하며, 타깃도 `p1 → p2` 로 **열을 번갈아** 갑니다(§4.2 `panes[n - max_columns]` 명세대로). 홀짝(`n % 2`) 로직은 완전히 제거되었습니다. `creator-grok-01` 이 제기했던 "n=3 갈라짐"이 원천 차단되었습니다.
---
## 2. W1~W5 항목별 검증
| W | 항목 | 상태 |
|---|---|---|
| **W1** | 단일 결정표 공유 | ✅ `_decide` / `_decide_headless` 분리, `compute_2xk_layout` 은 관측→위임 2단 |
| **W2** | N=1 → `right` | ✅ `_full_height_pane` 경유 `new_column_right` |
| **W3** | `_full_height_pane` | ✅ `len(col)!=1 → None`, `area_h<=0` 폴백, `tol=2` |
| **W4** | 캡 3중 배선 | ✅ **전부** — 아래 §2.1 |
| **W5** | 테스트 | ✅ 사양의 8개 테스트 전건 구현 |
### 2.1 W4 — Rev.2 가 지적한 이중 누락이 모두 해소됨
```python
# layout.py:235-236 ← _env_int 에 default 부여 (이전엔 None 반환)
--max-cols default=_env_int("MAM_MAX_COLS", "MAM_MAX_PANE_COLS", default=2)
--max-rows default=_env_int("MAM_MAX_ROWS", "MAM_MAX_PANE_ROWS", default=2)
```
```bash
# lib.sh:435 ← 이전엔 --max-cols 를 아예 넘기지 않았음
--max-cols "${MAM_MAX_PANE_COLS:-2}" --max-rows "${MAM_MAX_PANE_ROWS:-2}"
```
```
# .mam.env.example:147-153 ← C-5 문서 자체 불일치("unset -> no cap" vs "=3")도 정정
#default: 2 / MAM_MAX_PANE_COLS=2 + MAM_MAX_PANE_ROWS=2 신규 블록
```
추가로 `compute_2xk_layout` 진입부에 `max_columns is None → 2` 방어가 들어가 **네 번째 경로**까지 막았습니다. 사양보다 견고합니다.
`test_max_cols_default_reaches_cli_path` 와 `test_lib_sh_passes_max_cols_and_rows` 가 이 배선을 계약으로 고정합니다 — Rev.2 가 "이게 없으면 전체가 프로덕션에서 무효"라고 경고한 지점이라 특히 중요합니다.
### 2.2 기존 테스트 갱신 처리
| 테스트 | 처리 |
|---|---|
| `test_1_pane_split_down` → `test_1_pane_split_right` | ✅ 개명 + 계약 갱신 |
| `test_2_panes_to_3_panes_new_column_right` → `test_2_panes_fill_left_column_down` | ✅ |
| `test_4_panes_to_5_panes_new_column` → `..._overflows_at_capacity` | ✅ |
| `test_headless_max_columns_growth_guard` | ✅ 옛 홀짝 단언(`n=2→right`, `headless_odd_down`) 전면 재작성 |
| `test_b19_headless_layout_does_not_overflow` | ✅ tall 케이스 재해석 + **wide-tall 케이스 신설로 커버리지 보존** |
`test_b19` 처리가 특히 좋습니다 — 단언만 뒤집지 않고 비오버플로 경로를 검증하는 새 픽스처를 추가해 커버리지를 유지했습니다.
### 2.3 테스트 실행
```
pytest tests/ -q → 393 passed in 511.60s
```
**실패 0건.** (직전 리뷰에서 관측된 `test_d23` nats 태그 불일치도 해소되었습니다.)
---
## 3. 🟡 F-2 — `MAX_*=0` 이 "무제한"이 아니라 "전면 차단"입니다
`_env_int` 는 J-1 계약에 따라 명시적 `0` 을 보존합니다. 그 결과:
| 설정 | 실측 결과 |
|---|---|
| `max_columns=0, max_rows=2` | `down / fill_column` |
| `max_columns=2, max_rows=0` | `right` → 이후 `overflow` |
| `max_columns=0, max_rows=0` | **`overflow / grid_capacity_reached` (즉시)** |
| 헤드리스, 둘 중 하나라도 0 | `n >= 0` 이 항상 참 → **영구 overflow** |
문제는 **같은 설정 파일 안의 의미 충돌**입니다:
```
# .mam.env.example
# MAM_MIN_PANE_ROWS=0 ← "Set to 0 to disable vertical row constraints"
# MAM_MAX_PANE_ROWS=2 ← 0 을 넣으면 "용량 0" = 모든 세션이 새 워크스페이스
```
`MIN_*=0` 이 "제약 해제"를 뜻하므로, 운영자가 `MAX_*=0` 을 "상한 없음"으로 읽는 것은 자연스럽습니다. 그러나 실제로는 **에이전트마다 워크스페이스가 무한 생성**됩니다.
**개선 방향**:
```python
if max_columns is None or max_columns <= 0:
max_columns = 2 # 또는 '무제한' 의도라면 sys.maxsize
if max_rows is None or max_rows <= 0:
max_rows = 2
```
`.mam.env.example` 에도 `0 은 허용되지 않습니다(최솟값 1)` 한 줄을 덧붙이십시오. 비차단이나 오설정 시 피해가 크고 되돌리기 어렵습니다(생성된 워크스페이스가 남음).
---
## 4. 🟠 F-1 — 세로 전용 적층 능력이 사라졌습니다 (**제 사양의 결함**)
### 현상 (실측)
`min_cols=60` 에서 단일 페인 폭별 결정:
| 폭 × 높이 | 결과 |
|---|---|
| 80×60 | `overflow / column_width_overflow` |
| 100×60 | `overflow` |
| 119×60 | `overflow` |
| 120×60 | `right` |
**폭 120 미만이면 N=1 에서 즉시 오버플로**합니다. 그러나 80×60 을 세로로 쌓으면 `80×30` 페인 2개가 되고, **두 페인 모두 폭 80 ≥ min_cols 60 을 만족**합니다. 즉 **사용 가능한 배치를 거부하고 새 워크스페이스를 만듭니다.**
### 원인 — 폭 게이트가 폴스루하지 않음
```python
if len(cols) < max_columns:
fh = _full_height_pane(cols[-1], area_h)
if fh is not None:
if fh.width > 0 and fh.width // 2 < min_cols:
return _overflow("column_width_overflow", fh) # ← 즉시 반환
return _right("new_column_right", fh)
# ② 세로 채우기에 도달하지 못함
```
새 엔진은 **1열 × K행 배치를 구조적으로 만들 수 없습니다.** 구 엔진의 `single_pane_split_down` 이 담당하던 경로가 사라졌습니다.
### 책임 소재
**이것은 구현 결함이 아니라 제 사양의 결함입니다.** Rev.2 §4.1 의사코드가 정확히 `return OVERFLOW("column_width_overflow", fh)` 로 적혀 있었고, 구현은 그대로 따랐습니다. 폭 부족 시 세로 폴백을 명시하지 않은 것은 제 누락입니다.
### 실무 영향
기본값 `min_cols=15` 에서는 폭 30 미만이어야 발동하므로 **사실상 도달 불가**합니다. 다만 `MAM_MIN_PANE_COLS` 기본값은 60 → 40 → 15 로 변해 왔고, `.mam.env` 는 **gitignore 대상이라 자동 마이그레이션되지 않습니다.** 구 설정(`=60`)을 지닌 기존 설치는 120칸 미만 터미널에서 **에이전트마다 워크스페이스가 하나씩** 생기게 됩니다.
### 개선 방향 (구체)
폭 게이트를 **폴스루**로 바꿉니다:
```python
if len(cols) < max_columns:
fh = _full_height_pane(cols[-1], area_h)
if fh is not None and not (fh.width > 0 and fh.width // 2 < min_cols):
return _right("new_column_right", fh)
# 폭이 새 열을 감당하지 못하면 ②(세로 채우기)로 내려간다
```
이렇게 하면 80×60/min_cols=60 은 `down / fill_column` → `80×30` 2개가 되고, 폭·행이 모두 소진된 뒤에야 ③에서 오버플로합니다. 회귀 가드:
```python
def test_narrow_terminal_falls_back_to_vertical_stacking():
d = compute_2xk_layout(_one(80, 60), min_cols=60)
assert d.direction == "down" and not d.is_overflow
```
**주의**: 이 변경은 `test_b19` 의 tall 케이스 단언을 다시 뒤집습니다(현재 `overflow` → `down`). 원래 그 테스트가 지키던 계약이 바로 이 세로 폴백이었으므로, 사실상 **원복**입니다.
---
## 5. 판정
| 항목 | 판정 |
|---|---|
| W1~W5 사양 충족 | ✅ 전건. W4 는 사양보다 견고 |
| 4 에이전트 2×2 | ✅ 시뮬레이터 실측 |
| GUI/헤드리스 패리티 | ✅ 방향·타깃 모두 일치 |
| 전체 테스트 | ✅ **393 passed, 0 failed** |
| F-1 세로 폴백 상실 | 🟠 **제 사양 누락** — 후속 수정 |
| F-2 `MAX_*=0` 함정 | 🟡 후속 수정 |
구현은 승인된 사양을 **정확히, 그리고 일부는 더 견고하게** 충족했으며 핵심 목표가 실측으로 증명되었습니다. F-1·F-2 는 이번 변경이 만든 새 결함이 아니라 **사양의 미비**로, 각각 3~5줄 수정으로 해소됩니다. 설계 재작업 사유가 아니므로 `[ESCALATE: PLANNER]` 는 부여하지 않습니다.
**후속 잡 권고**: F-1(세로 폴백) + F-2(0 값 클램프) 를 묶어 한 커밋으로. F-1 은 구 `.mam.env` 를 지닌 기존 설치에 실제 영향이 있으므로 우선순위가 높습니다.
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261008T234013Z-4f5d21",
"base_sha": "97c2946ee0e11eabcecafe6407755c33c0289218",
"head_sha": "a93c9bf29279f65ce0b9c9fb2c1aeea90a659420",
"tree_sha": "741c19ba4c17601768b06684d5843d218a72beb1",
"review_commit": "a93c9bf29279f65ce0b9c9fb2c1aeea90a659420",
"reviewer": "planner-reviewer-claude-01",
"job_id": "616578e7",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-09T00:45:03Z"
}
@@ -0,0 +1,47 @@
# 리뷰 리포트 — Job 616578e7 (loop-lock: 테스트가 체크아웃의 루프 잠금을 잡지 않게, 97c2946..a93c9bf)
- 리뷰어: planner-reviewer-claude-01 (claude)
- 리뷰 identity: loop-20261008T234013Z-4f5d21 / base 97c2946 / head a93c9bf / tree 741c19b — 검증 경로에서 `git rev-parse HEAD 'HEAD^{tree}'` 일치, 미커밋 변경 없음
- 범위: 커밋 1개(+55줄), 테스트 3개 파일: test_o3_scoped_guard.py 의 b13 두 곳에 `MAM_LOOP_MARKER=tmp_path/...`, 새 tests/test_loop_marker_isolation.py(L1), test_issue17_workspace_root_isolation.py W1 에 `.mam` 부재 단언 1줄. 제품 코드(.agents/skills)·버전·VERSIONS 변경 없음(브리프대로).
## 결론 요약
할 일 1~4 가 요구대로이고, 내 독립 조사(grep + 사본 트리 실행)로도 누락된 실행 지점이 없다. 잠금 동작을 시험하는 테스트들의 marker 경로는 바뀌지 않았다. 차단 결함 없음.
## 1. 조사(1) — 직접 grep 한 결과 (run_loop.sh 실행 지점 전수)
run_loop.sh 는 :15 `MAM_REAL_ROOT=${MAM_REAL_ROOT:-$REPO_ROOT}`, :110 `--help` 와 :66-141 인자 오류는 :181 의 marker 결정·:248 `mam_acquire_loop_lock` **이전**에 종료, loop_lock.sh:66 이 부모 디렉터리를 mkdir -p. Python `LoopRunner` 는 잠금을 잡지 않는다(runner.py:1224-1226 은 release 뿐, acquire 는 run_loop.sh:248 에만 있음).
| 실행 지점 | 분류 | 근거 |
|---|---|---|
| test_o3_scoped_guard.py:388, :472 (b13 두 테스트) | **대상 → 수정됨** | 체크아웃 run_loop.sh, `--creator nonexistent-agent --task …`, cwd=REPO_ROOT; 이제 `MAM_LOOP_MARKER=tmp_path/loop-guard-active`(:390, :470) |
| test_issue5_phase3_loop.py:166, :184 | 이미 지정 | :163 `MAM_LOOP_MARKER=tmp_path/loop-marker` |
| test_loop_cli.py:52 (`_run_loop`) | 이미 지정 | env_extra 에 `MAM_LOOP_MARKER=tmp_path/loop-guard` |
| test_o2_race_free_lock.py:203 (o2_12) | 이미 지정(잠금 경합 자체를 시험) | :202 `MAM_LOOP_MARKER=marker(tmp_path)` — 의도 유지 |
| test_issue25_plan_reuse.py:367 (p7b) | 이미 지정 | `MAM_LOOP_MARKER=tmp_path/loop.marker` |
| test_issue21_loop_b.py:239, test_issue21_worktree_prereqs.py:405 | 이미 지정 | WORKSPACE_ROOT=tmp + `MAM_LOOP_MARKER` |
| test_issue21_acceptance.py:298, test_issue36_prompt_transport.py:540, test_b7_diff_untracked.py:189, test_tier4_e2e.py:285 | 복사본 트리의 run_loop.sh(`main`/`ctl`/`base`/`tmp_path`) | 체크아웃이 아님(acceptance 는 marker 도 지정) |
| test_issue5_phase4_runtime.py:132-146 (p4_03), test_issue25:355, test_issue5_phase3:151, test_o1_rebuttal.py:72 | `--help` → :110 에서 종료 | 잠금 전 |
| test_o1_rebuttal.py:76 (`--max-rebut abc`) | 인자 오류 → 잠금 전 종료 | :66-98 |
| test_o3 Z-7/Z-14(:137, :155), test_deploy_freshness:473, test_issue5_phase0_contracts:481, test_o1:24/:166 | 소스 텍스트 읽기만 | 실행 없음 |
| LoopRunner in-process(issue18, issue21_loop_b, issue25, issue30, issue33, issue34, issue36, issue6, phase4 등) | 잠금 미획득 | 위 runner.py 근거; 해당 없음 |
경험적 확인(W1 방식): HEAD 트리 사본에서 `WORKSPACE_ROOT=<사본>` 으로 브리프 후보 15개 모듈을 **파일 전체** 단위로 실행하고 매번 `.mam` 확인 — **15개 모두 clean**(b7 20, deploy_freshness 13+18 skip, issue21_acceptance 10, issue21_loop_b 34, worktree_prereqs 35, issue25 17, issue36 23+1 skip, phase0 41, phase3 12, phase4 5, loop_cli 9, o1 10, o2 22, o3 32, tier4_e2e 5 — 모두 passed). 놓친 실행 지점 없음.
## 2. 할 일 2·3 — 수정 방식과 회귀 테스트
- 대상이 한 모듈의 두 테스트뿐이라 conftest fixture 대신 각 호출에 env 지정 — 브리프의 "검토" 요건에 맞는 최소 변경. o2 의 잠금 경합·o3 의 marker 검사(mam_sandbox 아래 marker)는 손대지 않았다.
- L1(test_loop_marker_isolation.py:36-50)은 W1 과 같은 방법(체크아웃 복사 → 7개 노드 실행 → `.mam` 부재)이며 NODES 는 위 표의 "잠금까지 가는" 7개와 정확히 일치한다. W1 에도 `.mam` 디렉터리 자체의 부재 단언이 추가돼(:71) 잠금 디렉터리 생성이 두 테스트에서 잡힌다.
- **수정 전 코드에서 실패 확인**: L1 자체는 `git ls-files` 가 필요해 `git archive` 사본에서는 못 돌리므로, L1 의 방법을 base 트리 사본 안에서 직접 재현했다 — 7개 노드를 `WORKSPACE_ROOT=<base 사본>` 으로 실행(7 passed) → 사본에 **`.mam/` 생성**(L1 의 마지막 단언이 실패하는 조건). 노드별로는 **b13 두 테스트만** 생성하고 나머지 5개는 clean — 테스트 머리말의 "The first two took the checkout's lock at 97c2946" 와 일치. HEAD 에서는 (a)(b) 모두에서 L1·W1 통과.
## 3. 할 일 4 — 실행 (검증 경로 워크트리, 워크트리 .venv Python 3.9.6, `env -i` 로 HERDR_*·MAM_*·MQTT_* 제거)
| 실행 | 결과 |
|---|---|
| (a) WORKSPACE_ROOT 없이: test_issue17_workspace_root_isolation, test_loop_marker_isolation, test_o3_scoped_guard, test_o2_race_free_lock | **57 passed / 0 failed** (45 s); 실행 뒤 워크트리에 `.mam/` **없음** |
| (b) WORKSPACE_ROOT=<워크트리 밖 센티널>: 같은 4개 파일 | **57 passed / 0 failed** (45 s); 센티널 **비어 있음**; 워크트리에 `.mam/` 없음 |
- 본 체크아웃의 실제 잠금 `.mam/loop-guard-active` mtime 전후 동일(1791502813) — 이 리뷰 중 본 체크아웃에서는 아무것도 실행하지 않았다. 실제 .mam/jobs 항목 수 불변. 브로커 bind 제약 없음.
- 이식성: Python 테스트 코드만(3.9 문법). L1 은 nested pytest + `git ls-files`, 이 Mac 에서 통과.
## 4. 비차단
- L1·W1 둘 다 노드 목록을 수동 유지한다(이전 리뷰의 같은 지적). run_loop.sh 를 잠금까지 실행하는 테스트를 새로 추가하면 L1 NODES 에도 넣어야 한다.
- L1 은 `_copy_checkout` 을 W1 모듈에서 import 하므로 두 테스트 파일이 결합돼 있다 — 작동에는 문제없고, 공용 헬퍼를 conftest 로 옮길지는 취향 문제.
- 새 관찰 없음.
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261013T001819Z-131fa6",
"base_sha": "8b0b4a07dc76a4915895bdde6170dc8eed9b5f74",
"head_sha": "325b056057fcdd717d2c81017fc5ef57183cb4d0",
"tree_sha": "7905896f005159d596e3872d0ee2c3c12061f09a",
"review_commit": "325b056057fcdd717d2c81017fc5ef57183cb4d0",
"reviewer": "planner-reviewer-claude-01",
"job_id": "63919c5d",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-13T00:57:46Z"
}
@@ -0,0 +1,59 @@
# 테스트의 실제 herdr 서버 누출 수정 리뷰 (job 63919c5d)
- 리뷰어: planner-reviewer-claude-01 (Reviewer)
- 리뷰 identity: loop-20261013T001819Z-131fa6 / base 8b0b4a07 .. head 325b0560 (커밋 2개: 525df2b 수정, 325b056 s11 기준 이동 / 4 파일) / tree 7905896f
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261013T001819Z-131fa6/1` — HEAD·tree 가 identity 와 일치, `git status --porcelain` 0 줄(시작·종료 시), `.mam` 디렉터리도 생기지 않음. 본 체크아웃 HEAD 8b0b4a0(main) 변동 없음.
- 실행 안전: 내 pane 은 `HERDR_SOCKET_PATH`·`HERDR_PANE_ID`·`HERDR_TAB_ID`·`HERDR_WORKSPACE_ID`·`HERDR_SESSION_NAME`·`HERDR_SESSION`·`HERDR_CONFIG_PATH`·`HERDR_BIN_PATH`·`HERDR_ENV` 를 물려받고 있어, 모든 테스트·탐침은 `env -i`(PATH/HOME/LANG/TMPDIR 만)로 돌려 브리프의 `-u` 목록을 포함한 전부를 비웠다. basetemp 는 세션 scratchpad 아래(경로에 "shim" 없음). 실제 바이너리를 부른 것은 일회용 HOME 에서의 `status server`(읽기 전용, 서버 미기동)뿐이다. Python 은 본 체크아웃 `.venv`(3.9.6, paho 2.1.0). `.mam.env` 는 읽지 않았다.
## 1. 원인 판정이 맞는가
**원인 1 (조상 `*-shim` 이 mock 을 가림).** base 의 `_is_shim_path` 는 `*-shim/*` 를 `"/$1/"` 전체에 대해 매칭해 조상 디렉터리까지 걸렀고(`lib.sh` base), 생성 shim 의 `_resolve_real_herdr` 도 `[[ "$dir" != *"-shim"* ]]` 로 PATH 항목 문자열 어디든 걸렀다. basetemp `pytest-pr56-shim` 아래 mock `bin/` 은 둘 다에서 건너뛰어졌고 다음 후보인 `/opt/homebrew/bin/herdr` 가 "real" 이 된다. 수정 전 lib.sh 로 되돌린 scratch 복사본에서 L1 이 정확히 그 상태로 실패했다: `_resolve_real_herdr_path` 가 `…/pytest-x-shim/case0/bin/herdr` 대신 다음 PATH 항목의 디코이 `…/decoy/bin/herdr` 를 골랐다(`assert '/…/decoy/bin/herdr' == '/…/case0/bin/herdr'`). 판정 맞음.
**원인 2 (pane 의 `HERDR_SOCKET_PATH`).** 실제 herdr 0.9.3 바이너리를 일회용 HOME 에서 `status server` 로 읽기만 해 확인했다:
| 환경 | 바이너리가 가리킨 소켓 |
|---|---|
| `HERDR_SOCKET_PATH=/nonexistent/s.sock` + `--session t-zz` | `/nonexistent/s.sock` |
| `HERDR_SOCKET_PATH=/nonexistent/s.sock` + `HERDR_SESSION=t-zz` | `/nonexistent/s.sock` |
| `HERDR_SESSION=t-zz` 만 | `$HOME/.config/herdr/sessions/t-zz/herdr.sock` (가짜 HOME 아래) |
| `HERDR_SOCKET_PATH` 만 | `/nonexistent/s.sock` |
즉 `HERDR_SOCKET_PATH` 는 **`--session` 보다도** 우선한다. shim 이 항상 `--session <샌드박스 서버>` 를 붙여도 이 변수가 남아 있으면 실제 서버로 간다 — 원인 1 로 실제 바이너리가 선택되는 순간 샌드박스 HOME 은 아무 보호가 되지 못했다는 오케스트레이터의 실측과 일치한다. 두 원인은 독립적이고 둘 다 막아야 한다(1 만 고치면 pane 변수 누출 시 다른 경로의 실제 호출이 여전히 실제 서버로, 2 만 고치면 숨은 mock 대신 실제 바이너리가 가짜 HOME 에 서버를 띄움). 판정 맞음.
## 2. 수정 내용 검토
- `lib.sh:113-124 _is_shim_path`: 첫 `case` 에서 `*-shim/*` 만 빠지고 `.mam/shim`·`$_HERDR_SHIM_DIR_PATTERN`(`/multi-agent-herdr-shim/`)·`$_HERDR_SKILLS_BIN_PATTERN`(`/.agents/skills/.bin`) 은 그대로. `*-shim` 은 `"${1%/}"` 즉 인자 자신의 끝에만 적용. `lib.sh:130-136 _resolve_real_herdr_path` 는 PATH 항목(`_is_shim_path "$dir"`)과 후보 파일의 **canonical dirname** 둘 다 검사한다 — L1 의 mock 은 `tmp/bin/herdr` 로의 symlink 라 canonical dirname 은 `tmp/bin` 이고, 선택 결과는 PATH 항목 쪽 경로(`$dir/herdr`)다. 기존 래퍼 디렉터리 제외 여부: `.mam/shim` → 첫 case(부분 문자열, 조상 포함) 유지; `multi-agent-herdr-shim` → 패턴 상수 유지(`"/…/multi-agent-herdr-shim/…/"`); `.agents/skills/.bin` → 패턴 유지(이 저장소에는 그 디렉터리가 없다); 테스트의 `herdr-shim`(L1b)·`py-shim`·`ps-shim`(`test_issue17_item4_decisions.py:208`, `test_issue21_acceptance.py:283`, `test_issue30_stall_watch_stop.py:95`) 은 디렉터리 자신의 이름이 `*-shim` 이라 계속 제외.
- 생성 shim(`lib.sh:173-178`): `[[ "${dir%/}" != *-shim ]]`. `.mam/shim` 부분 문자열 검사는 그대로.
- `tests/conftest.py:293-298 mam_sandbox`: `HERDR_SOCKET_PATH`·`HERDR_PANE_ID`·`HERDR_TAB_ID` 제거. 기존의 `HERDR_SESSION_NAME`·`HERDR_SERVER_NAME`·`HERDR_WORKSPACE_ID`·`HERDR_CONFIG_PATH`·`XDG_CONFIG_HOME` 제거와 합쳐 pane 이 내보내는 라우팅 변수 중 실제 서버에 닿을 수 있는 것은 모두 빠진다(아래 비차단 메모의 `HERDR_SESSION` 참조).
- bash 3.2: `${1%/}`·`${dir%/}`·`case` 뿐, `bash -n` 통과. Python 3.9 컴파일 통과.
- s11 기준 커밋 525df2b: 생성 shim heredoc 이 바뀌었으므로 기준을 그 커밋으로 옮긴 것은 #45 때와 같은 방식이고, 검증 경로에서 s11 PASSED. 525df2b 는 이 브랜치의 첫 커밋으로 검증 경로에 존재한다.
## 3. 충분한가 — 다른 경로로 실제 서버에 닿는 테스트
- `mock_herdr`(`conftest.py:310`)·`mock_agents`(`:1412`) 는 `mam_sandbox` 에 의존하므로 mock 을 PATH 에 두는 테스트는 모두 샌드박스 환경(라우팅 변수 제거, HOME 교체)이다.
- `mam_sandbox` 없이 herdr 를 흉내 내는 파일은 `test_issue14_delivery_ack.py`·`test_issue18_liveness_contract.py` 둘(bash 함수 `_sks_herdr` 대체, HOME=tmp). 이 둘이 herdr **바이너리**를 한 번이라도 부르는지 보려고 호출을 기록하는 디코이 `herdr` 를 PATH 맨 앞에 두고 두 파일을 돌렸다: **43 passed, 디코이 호출 0 건**(로그 파일이 생기지 않음). 즉 이 둘은 라우팅 변수가 남아도 바이너리를 실행하지 않는다. (이 실행의 `1 error` 는 세션 teardown 의 #55 agent-home 가드가 `~/.gemini/antigravity-cli/conversations/f9bf3d55-….db-shm/.db-wal` 을 잡은 것으로, 브리프가 예고한 다른 워크스페이스의 실행 중 agy 대화 WAL/SHM 이다. 테스트 산출물이 아니므로 판정에 쓰지 않고 보고만 한다.)
- `test_issue6_fail_closed.py`·`test_issue6_turn_handshake.py` 는 `mock_herdr` 를 쓰므로 샌드박스다.
- 실제 바이너리가 아는 라우팅 변수는 `HERDR_SOCKET_PATH`(최우선)와 `HERDR_SESSION`(HOME 상대 경로)뿐임을 위 표로 확인했다. `HERDR_SESSION_NAME` 은 바이너리가 모르고 shim 만 `--session` 으로 바꾼다(어제 리뷰에서 확인). 따라서 `HERDR_SOCKET_PATH` 제거 + 가짜 HOME 이면 shim 경로든 직접 호출이든 실제 서버에는 닿지 않는다.
## 4. 테스트 결과
| 항목 | 결과 |
|---|---|
| head: `test_herdr_real_server_leak.py` + `test_issue23_24_startup_path.py` + `test_herdr_shim_contract.py` + `test_issue17_workspace_root_isolation.py` + `test_issue9_server_env.py` + `test_issue45_herdr_config.py` | **130 passed, 34 skipped**(skip 은 모두 `needs tomllib (Python 3.11+)` 류의 알려진 3.9 skip). L1·L1b·L2·s11 은 모두 PASSED 로 실행됨 |
| 수정 전 lib.sh(8b0b4a0) + 새 테스트 | **L1 실패**(디코이 선택), **L1b 통과**(자기 이름 `*-shim` 은 전후 모두 제외) |
| 수정 전 conftest(8b0b4a0) + 새 테스트 | **L2 실패**: `['HERDR_PANE_ID', 'HERDR_SOCKET_PATH', 'HERDR_TAB_ID']` 가 남음 |
| 디코이 sweep(`test_issue14`, `test_issue18`) | 43 passed, 디코이 호출 0 |
수정 전 재현에는 실제 herdr 가 실행될 수 있는 구성을 쓰지 않았다(테스트 설계대로 디코이가 PATH 에서 실제 바이너리보다 앞서고, `env -i` 로 소켓 변수도 없음).
## 5. 공유 제어 평면에 주는 영향
- 생성 shim 은 lib.sh 를 source 하는 모든 실행에서 `<워크스페이스>/.mam/shim/herdr` 로 다시 쓰이므로, 머지 뒤 실제 제어 평면의 shim 도 두 줄이 바뀐다. 바뀌는 것은 "조상 이름에 `-shim` 이 든 PATH 항목을 더 이상 건너뛰지 않음" 뿐이고, `.mam/shim` 과 자기 이름이 `*-shim` 인 디렉터리는 계속 건너뛴다. 내 pane 의 PATH 에서 `-shim` 을 포함하는 항목은 `~/.cmuxterm/cmux-cli-shims/<uuid>` 하나인데(`herdr` 없음, `amp claude codex hermes pi` 만) 전후 어느 규칙에도 해당하지 않아 영향 없다. 본 체크아웃의 `.mam/shim/herdr` 는 이 리뷰 중 건드리지 않았다(아직 base 내용).
- 비차단 메모 1: README(`README.md:102`, `README.ko.md:84`)가 설명하는 레거시 레이아웃 `/tmp/multi-agent-herdr-shim/<server>/herdr` 는 디렉터리 자신의 이름이 서버명이라, 생성 shim 의 새 규칙으로는 제외되지 않는다(lib.sh 의 `_is_shim_path` 는 패턴 상수로 계속 제외). 현재 코드는 그 레이아웃을 만들지 않고 이 호스트에도 없으므로 동작 영향은 없지만, 생성 shim 에도 `*"/multi-agent-herdr-shim/"*` 를 두거나 README 를 현재 레이아웃(`.mam/shim`)으로 고치면 깔끔하다.
- 비차단 메모 2: `mam_sandbox` 는 `HERDR_SESSION`(바이너리가 아는 변수, 내 pane 도 내보냄)을 지우지 않는다. 가짜 HOME 아래 경로로 풀리므로 실제 서버 누출은 아니지만, `lib.sh:1425 _herdr_caller_server` 와 `pane_lock.caller_server` 가 이 값을 "호출자 서버" 로 읽어 pane 안/밖에서 테스트 분기가 달라질 수 있다. 결정성을 위해 함께 지우는 것을 권한다(이 PR 의 범위 밖).
## 6. 잔류물
- scratch 복사본·basetemp·디코이·로그는 모두 세션 scratchpad 아래. 일회용 HOME `/tmp/j639-h` 제거(서버를 띄운 적 없음). 실제 `.mam`·`.mam.env`·모니터·실제 서버(multi-agent-mux, default)·`~/.config/herdr`·에이전트 홈은 건드리지 않았다.
## 결론
두 원인 판정은 코드와 실측(특히 `HERDR_SOCKET_PATH` 가 `--session` 보다 우선)으로 확인되고, 수정은 각각을 막으며 회귀 테스트는 수정 전 코드에서 정확히 그 이유로 실패한다. 기존 래퍼 디렉터리 제외는 유지되고, mock 없이 돌아가는 두 테스트 파일은 herdr 바이너리를 아예 부르지 않는다.
[VERDICT: PASS]
@@ -0,0 +1,111 @@
# 🔍 Review Report — PR #43 `fix/issue-26` 리뷰 (job `645adb2a`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-10-01
- **대상**: PR #43 @ `b58edac`, base `main e1eb22b` (v4.8.0). 6커밋, 17파일 `+1590/−94`, `git diff --check` 클린.
- **검증 경로**: `/var/folders/.../T/mam-review/loop-20261001T131705Z-a60092/1`. **identity 확인**: `HEAD = b58edace…4893`, `HEAD^{tree} = 14b670fb…6ffa` — 브리프와 일치.
- **안전 규칙 준수**: 검증 경로·소스 워크트리·본 체크아웃(`main e1eb22b`) 모두 수정·커밋·checkout 없음. 실제 `.mam.env` 는 **값을 출력하지 않고** 형태만 셌다(`$`·`export`·인라인 `#`·따옴표 줄 수 = 모두 0). 파서 실험은 scratchpad 의 합성 파일로만. 테스트는 브리프대로 `.mam.env` 를 export 하지 않고(`MQTT_*` 미설정 확인) 돌렸다. 실제 `.mam`·데몬·세션·herdr 조작 없음, push·merge·PR 상태 변경 없음.
- **참고(이 잡의 liveness)**: 이 잡의 `started` 발행 때 브로커 `100.69.147.175:1883` 이 연결을 거부했다(`Connection refused`, 지금도 포트 닫힘). `publish_event` 는 rc 2 였지만 레코드는 `running`·`events.log` 에 `started`(토큰 포함)가 기록됐고 heartbeat 타이머도 떠 있다 — #18 계약상 로컬 증거로 충분하다. 브로커 쪽은 오케스트레이터 확인이 필요하다(아래 판정과 무관).
## 결론 요약
**병합을 막을 결함은 없다.** 두 로더는 같은 입력에서 같은 결과를 내고(합성 파일 15줄 실측), 래퍼의 eval 경로는 어떤 값도 셸 해석하지 않으며(명령 치환 주입 실험: 실행 0), bash `mam_int` 와 Python `_positive_int` 는 15가지 입력에서 결과가 같다. 로컬 브로커로 옮긴 시험들은 skip 을 fail 로 바꾸고 양쪽 로그·감사 기록까지 단언해 **오히려 강해졌다**. 비차단 관찰 5건(R1–R5).
## 1. 파서 규칙 (검토 항목 1)
`envfile.py:45-73` `parse`, `mqtt_common.py:98-101` 은 `envfile.apply` 에 위임 — Python 쪽 로더는 **하나**다. 래퍼는 같은 파일을 `--shell` 로 실행한다. 같은 합성 파일을 두 경로에 넣은 결과:
| 입력 줄 | Python 로더 | 래퍼 eval 후 |
|---|---|---|
| `BOMKEY=1` (UTF-8 BOM) | 건너뜀(invalid key, 1행 경고) | 미설정 |
| `A = spaced \r` (CRLF) | `'spaced'` | `spaced` |
| `B="q's"` | `"q's"` | 동일 |
| `C='x''` | `"x'"`(바깥 한 쌍만) | 동일 |
| `D=a=b=c` | `'a=b=c'` | 동일 |
| `E=` | `''` | `''` |
| `export F=exp` | 건너뜀(invalid key) | 미설정 |
| `G=val # trailing` | `'val # trailing'` | 동일 |
| `H=$(touch …/PWNED) \`id\` ${HOME}` | 글자 그대로 | 글자 그대로, **PWNED 파일 생성 안 됨** |
| `9BAD=x` / `noequals` | 건너뜀 + 경고 | 미설정 |
| `IFS=x` / `BASH_ENV=x` | 건너뜀(reserved) | 미설정 |
| `I="unbalanced` | `'"unbalanced'` | 동일 |
| `J= "inner"` | `'inner'` | 동일 |
**두 경로가 완전히 일치한다.** 경고에는 값이 찍히지 않는다(줄 번호·사유만). 이전 Python 로더(`strip('"').strip("'")`)는 따옴표를 여러 겹 벗기고 키 검사가 없었는데, 이제 한 쌍만 벗기고 형식 오류를 경고한다 — 문서화된 규칙과 맞다.
**R1 (비차단, 문서)**: `.mam.env.example` 은 `$HOME/...` 예시를 `/home/you/...` 로 바꿔 "셸 해석 없음" 과 **일관**되게 했지만, 머리말에 규칙 자체(셸 확장 없음, 인라인 `#` 은 값의 일부, `export` 접두어 불가, BOM 저장 시 첫 줄 무시, **이미 있는 환경변수가 우선**)를 적지 않았다. 특히 래퍼 사용자에게는 세 가지가 **동작 변경**이다 — 전에는 bash `source` 가 `export KEY=`·`$HOME` 확장·인라인 주석을 받아들였다. 실제 `.mam.env` 에는 해당 줄이 없음을 확인했다(형태만 셈).
## 2. 래퍼의 eval 경로 (검토 항목 2)
`multi-agent-mux-delegate-job:41-46`: `python -I envfile.py --shell` 의 출력을 `eval`. 출력은 `envfile.py:97-98` 의 `print(f"export {key}={shlex.quote(val)}")` 뿐이고, `key` 는 `_KEY.fullmatch` 를 통과한 것만, `val` 은 `splitlines` 로 개행이 없고 `shlex.quote` 로 감싸진다 — 주입 실험에서 `$()`·백틱·`${}` 모두 글자 그대로 남았다.
- 래퍼가 그 전에 세운 비-export 변수는 `SCRIPT_DIR`·`REPO_ROOT`·`TARGET_ENV` 셋뿐이고, 셋 다 환경으로 넘겨 파일이 덮어쓸 수 없다(`:42`). env-wins 실측: `D=fromenv` 가 파일의 `D=a=b=c` 를 이긴다.
- 실패 경로: 파일이 **없으면** rc 0·출력 없음, **읽을 수 없으면** stderr `WARNING: … cannot read (PermissionError)` 후 rc 0 — 래퍼는 설정 없이 계속한다. 래퍼의 `|| { echo "ERROR: cannot read $TARGET_ENV"; exit 1; }`(`:44`)는 **Python 실행 자체가 실패할 때**(인터프리터 없음 등)만 걸려, 메시지와 실제 원인이 어긋난다(R2, 사소).
- `-I`: `PYTHONPATH`·사용자 site 를 무시하지만 `envfile.py` 는 표준 라이브러리만 쓰고 파일 경로로 실행되므로 문제없다. 오히려 `.mam.env` 를 읽기 전 환경의 `PYTHON*` 이 파서에 끼어들 여지를 없앤다.
## 3. 우선순위 변경의 영향 (검토 항목 3)
전에는 래퍼의 `source` 가 환경을 덮어썼고 Python 로더는 환경을 지켰다 — 같은 파일이 두 경로에서 다른 결과를 냈다. 이제 둘 다 env-wins.
- **루프 러너**가 래퍼에 넘기는 env(`DELEGATE_JOB_PYTHON`, `--registry-dir` 대신 쓰는 `MAM_JOBS_DIR` 등): 전에는 파일 값에 덮일 수 있었다 → 이제 러너 값이 이긴다. **개선**.
- **워크트리 creator**: create/resume 이 넘기는 절대경로 바인딩(`AGENT_SESSIONS_YAML`·`MAM_JOBS_DIR`·…)이 이제 파일 값에 덮이지 않는다 — #21 의 의도와 맞는 **개선**.
- **원격 러너**(`remote.py`)는 원래 Python 로더라 변화 없음. **테스트**는 `conftest` 가 `MAM_ENV_FILE` 을 없는 파일로 고정해 무관.
- 동작이 나빠지는 경로: 셸에 **오래된 `MQTT_*` 를 export 해 둔 채** 파일만 고친 사용자는 이제 파일 값이 적용되지 않는다. 이 부분이 R1 의 문서 누락과 겹친다.
## 4. 정수 정규화 (검토 항목 4)
bash `mam_int`(`lib.sh:2345-2356`)와 Python `_positive_int`(`runner.py:71-82`)를 같은 15개 입력에 돌린 결과 **전부 일치**: `' 30 '→30`, `0700→700`(8진 아님), `0900→900`, `0→거부(min 1)`, `-5`·`+5`·`1e3`·`30s`·전각 `30`·빈 값 → 거부, `999999999→수용`, `1000000000→거부`(9자리 상한), `0000000000000000001→1`(앞 0 제거 후 길이 판정).
- 래퍼: 환경 노브는 `mam_int_knob`(잘못되면 경고 + 기본값, `:154-156`), 플래그는 `parse_opts` 끝의 루프(잘못되면 `ERROR … not a positive decimal integer` rc 1, `:196-200`). `MAM_INJECT_ACK_GRACE_S` 는 min 0(0 = 대기 없음 허용, 의미상 맞다), `ACK_TIMEOUT`·heartbeat·budget 은 min 1. lib.sh `SKS_*` 대기 노브는 min 0(대기 생략 허용), `delegate_wait_started` 도 0 허용(`:2379`).
- 빠진 노브: `$(( ))` 안에 환경 기본값을 직접 쓰는 자리는 남아 있지 않다(B5 정적 검사가 고정). `[ -ge ]`/`[ -le ]`/`sleep` 에만 쓰이는 노브(`MAM_READY_EMPTY_GIVEUP`·`SKS_EMPTY_GIVEUP`·`SKS_IDLE_RETRIES`·…)는 `test` 의 비교가 원래 10진수라 8진 문제가 없고, PR 이 표로 분류해 "모든 정수 노브가 분류됨" 을 시험한다(`test_b5_every_integer_env_default_is_classified`). 그 노브들에 숫자가 아닌 값이 오면 `[` 가 오류(rc 2)를 내는 기존 동작은 남는다(R3, 범위 밖).
## 5. 로컬 브로커와 이전된 시험 (검토 항목 5)
`tests/_local_mqtt.py` 는 MQTT 3.1.1 의 필요한 부분을 클라이언트가 기대하는 순서로 처리한다: CONNECT(레벨 3/4만, 그 외 CONNACK rc 1)→CONNACK, SUBSCRIBE→SUBACK(QoS 최대 1 부여) 뒤 **매칭되는 retained 전달**, PUBLISH QoS1 은 **라우팅·retained 저장 뒤에 PUBACK**(b58edac — 발행자가 ack 를 받은 시점에 브로커 상태가 이미 반영됨), 빈 payload retained 는 삭제, UNSUBSCRIBE→UNSUBACK, PINGREQ→PINGRESP, `+`/`#` 와일드카드와 `$` 토픽 예외(`topic_matches`). 미지원(QoS2·will·지속 세션)은 이 저장소가 쓰지 않는 기능이다. `127.0.0.1:0` 에 바인딩해 **포트 충돌이 없고**, 스레드는 daemon 이며 `stop()` 이 리스너·연결을 닫는다.
이전된 시험의 단언은 **약해지지 않았고 강해졌다**:
- `test_acceptance5`: 공개 브로커용 `_skip_if_broker_did_not_deliver`·`no CONNACK` skip 이 삭제되고, 대신 러너 로그의 `DISPATCH`·`published started/completed`·`DONE rc=0` 과 오케스트레이터 감사 기록의 `dispatch_verified`·`dispatch_fingerprint == sha256(token)` 을 양쪽에서 단언한다.
- `test_issue19`: "브로커 도달 불가면 skip" 이 `pytest.fail` 로 바뀌었다(로컬 브로커는 항상 떠 있으므로).
- S9/S10 의 `_live_broker()`(2·3회차 리뷰에서 내가 P2 로 지적한 공개 브로커 의존)가 `local_broker_env()` 로 대체됐다.
- `test_b19` 는 `send_keys_safe` 본문을 앞 2500자가 아니라 **함수 끝까지** 검사하게 고쳐졌다(정확성 개선).
- 정적 검사(`test_local_mqtt.py:215`)가 공개 브로커 주소의 재유입을 막는다. 시험 로그에 `hivemq`·실제 브로커 IP 흔적 0건.
## 6. 테스트 실행 (검증 방법·검토 항목 6)
```
cd <검증 경로> && AGENT_PYTHON_BIN=<pr-43 .venv> PYTHONDONTWRITEBYTECODE=1 <pr-43 .venv> -m pytest -p no:cacheprovider -q -rfEs \
--basetemp=<밖> tests/test_issue26_envfile.py tests/test_issue26_ints.py tests/test_local_mqtt.py \
tests/test_issue18_liveness_contract.py tests/test_issue33_budget.py tests/test_issue30_stall_watch.py tests/test_tier1_unit.py
(.mam.env 미export, MQTT_* 미설정)
→ 228 passed, 1 skipped in 525.44s (0:08:45) failed 0 (skip = S6, /proc)
```
- PR #41 리뷰 내내 공개 브로커 때문에 흔들리던 S9·S10·R2·B3·acceptance 계열이 **외부 브로커 없이 전부 통과**했다 — PR 의 주장 확인.
- **기준 실패 주장(검토 항목 6)**: `tests/test_issue10_13_purge.py` 를 이 PR 트리와 base(`e1eb22b` 를 `git archive` 로 풀어 놓은 사본)에서 각각 단독 실행한 결과 **둘 다 23 passed**, 실패 0. 즉 이 호스트에서 이 리뷰어의 조건으로는 "12건 기준 실패" 가 **재현되지 않는다**. 양쪽 결과가 같으므로 어느 경우든 PR 회귀는 아니다. 오케스트레이터의 전체 스위트에서만 나타난다면 시험 간 순서·상태(예: 실제 홈의 대화 파일, 이전 시험이 남긴 환경) 의존을 의심할 만하다(R4).
- 격리: 실제 `.mam/jobs` 는 이 잡 자신의 파일 외 **추가 0**. 검증 경로 tracked 파일 변화 없음(HEAD `b58edac`), 본 체크아웃 `main e1eb22b`. 실행 뒤 호스트에 남은 `stall_watch`(이 잡을 감시하는 오케스트레이터의 것)·`sleep 300`(다른 세션의 프로세스 그룹) 은 내 실행과 무관함을 부모/프로세스 그룹으로 확인했다.
## 7. 설계 경계 (검토 항목 7)
- **판정이 Python 으로 이동**: `.mam.env` 해석(키 검증·예약 변수 거부·우선순위)이 bash `source` 에서 `envfile.py` 로 옮겨졌다 — #17 항목 4 의 "`.mam.env` 파싱(#26) — bash `source` 제거" 그대로다. 래퍼에는 실행과 `eval` 만 남는다.
- **bash 에 새로 생긴 로직**: `mam_int`/`mam_int_knob` 과 `parse_opts` 의 플래그 검증. 이는 bash 산술로 들어가는 값을 그 자리에서 정규화하는 **입력 정제**이고, Python 쌍둥이(`_positive_int`)와 한 규칙으로 고정됐다(B1 시험). 판정(무엇을 할지)이 아니라 형식 변환이라 경계 위반으로 보지 않지만, 1회차 PR #41 리뷰의 M4(`MAM_JOB_TIMEOUT_S` 검증이 bash 에 있음)와 같은 부류이므로 항목 4 에서 래퍼 인자 처리가 Python 으로 갈 때 함께 옮길 목록에 둘 것을 권한다(R5).
## 8. 판정
버전 락스텝 bump 부재는 판정에서 제외한다. 병합을 막을 결함은 없다.
| # | 비차단 관찰 | 근거 |
|---|---|---|
| R1 | `.mam.env.example` 머리말에 새 파싱 규칙과 **env-wins** 가 적혀 있지 않다 — 래퍼 사용자에게 `export` 접두어·`$` 확장·인라인 주석·우선순위 4가지가 동작 변경 | `.mam.env.example:1-20`; §1·§3 |
| R2 | 래퍼의 `ERROR: cannot read $TARGET_ENV` 는 Python 실행 실패에만 걸리고, 실제 읽기 실패는 경고 후 설정 없이 진행 — 메시지가 원인과 어긋난다 | `multi-agent-mux-delegate-job:44`, `envfile.py:52-53` |
| R3 | `[ -ge ]`/`sleep` 전용 정수 노브에 숫자가 아닌 값이 오면 `[` 오류(rc 2)를 내는 기존 동작은 남는다 | PR 이 분류표로 의도적으로 범위 밖 처리 |
| R4 | "test_issue10_13_purge.py 12건 기준 실패" 가 이 리뷰어 조건(단독, PR·base 양쪽)에서는 재현되지 않음 — 전체 스위트 순서 의존 가능성 | §6 |
| R5 | `mam_int`/플래그 검증은 bash 의 입력 정제 — 항목 4 이전 목록에 추가 권고 | `lib.sh:2345-2364`, 래퍼 `:196-200` |
## 9. 교차검증 가이드
```bash
RP=/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261001T131705Z-a60092/1
PY=/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux-wt/pr-43/.venv/bin/python
git -C "$RP" rev-parse HEAD 'HEAD^{tree}' # b58edac… / 14b670f…
# 합성 .env 15줄을 envfile.apply 와 `-I envfile.py --shell` + eval 양쪽에 → 결과 동일, $(…)/`…` 미실행 (§1 표)
# mam_int vs _positive_int 15개 입력 → 전부 동일 (§4)
# base: git -C "$RP" archive e1eb22b | tar -x -C <tmp> → tests/test_issue10_13_purge.py → 23 passed (PR 도 23 passed)
```
[VERDICT: PASS]
@@ -0,0 +1,112 @@
# 🔍 Review Report — PR #41·#43 후속 `fix/followups-41-43` (job `76ca3b1b`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-10-02
- **대상**: `0051fd6..95eabc6` (8커밋, 27파일 `+397/−88`, `git diff --check` 클린), base `main 0051fd6`.
- **검증 경로**: `/var/folders/.../T/mam-review/loop-20261001T230324Z-b511bf/1`. **identity 확인**: `HEAD = 95eabc69…d5f4f`, `HEAD^{tree} = 46399844…7998` — 브리프와 일치.
- **안전 규칙 준수**: 검증 경로·소스 워크트리(`multi-agent-mux-wt/followups`)·본 체크아웃 모두 수정·커밋·checkout 없음. 되돌린 사본·합성 파일·`ps` 대역은 scratchpad 에서만. 실제 `.mam.env` 를 읽거나 출력하지 않았고 export 하지 않았다. 실제 `.mam`·데몬·세션·herdr 조작 없음, push·merge·PR 상태 변경 없음.
## 결론 요약
**F1–F6 모두 완료 조건을 만족한다. 범위 밖 동작 변경은 없다.** 제품 코드를 바꾸는 항목(F2·F3·F4·F5)의 회귀는 제품 파일만 base 로 되돌린 사본에서 **47건 실패**한다(아래 §7). 테스트만 고치는 항목(F1·F6)은 base 제품 코드에서도 통과하는 것이 정상이며, F1 은 옛 테스트가 날짜에 따라 실패하던 원인을 `ps` 대역으로 직접 재현했다. 비차단 관찰 3건(T1–T3).
## F1 — A8 의 날짜 의존 (`tests/test_issue21_acceptance.py:258-300`)
- 제품 코드(`loop_lock.sh` 의 `mam_lstart`)는 **그대로**다. `loop_lock.sh` 의 diff 는 F4b 의 `MAM_LOCK_STEAL_RETRIES` 한 줄뿐이다.
- 테스트는 마커의 lstart 를 `" ".join(out.split())` 로 써서 제품의 `tr -s ' '` + 앞뒤 공백 제거와 같게 맞췄다.
- 날짜와 무관하게 고정하는 장치: `padded` 파라미터가 PATH 앞에 `ps` 대역을 둔다. 이 대역은 `lstart=` 질의에만 `Thu Oct 1 08:02:03 2026`(두 칸)을 돌려주고, 대역이 실제로 쓰였는지도 단언한다.
- **옛 버그 재현(직접)**: 같은 대역 아래에서 제품 `mam_lstart` 는 `Thu Oct 1 …`(한 칸), 옛 테스트 방식(`.strip()`)은 `Thu Oct 1 …`(두 칸)을 낸다 → 불일치 → 잠금이 "stale" 로 보여 두 번째 루프가 거부되지 않는다. 즉 옛 A8 이 1~9일에 실패한 원인이 정확히 이것이고, 새 `padded` 케이스는 매일 그 조건을 돈다.
- 같은 패턴의 다른 테스트: `test_o3_scoped_guard.py:_get_lstart` 는 이미 `" ".join(...split())` 로 정규화한다. `test_o2_race_free_lock.py:get_lstart` 는 정규화하지 않지만 **어디서도 호출되지 않는 죽은 헬퍼**다(T1, 지우거나 정규화 권고).
## F2 — 진입점의 한 줄 오류 (`mqtt_common.py:129-140` 외 7곳)
- 공통 헬퍼 `load_env_or_report()` 가 `EnvFileError` 를 잡아 `ERROR: <path>: cannot read (<type>)` 한 줄을 출력하고 False 를 돌려준다. 라이브러리 함수는 `sys.exit` 하지 않는다 — 진입점(`publish_event`·`registry`·`job_subscriber`·`cli`·`bench`·`heartbeat`·`remote` 의 `main`)이 `return 1` 한다. `job_subscriber` 는 `RC_ERROR`(=1)로 이름을 썼다.
- 값·파일 내용은 출력되지 않는다(예외 메시지가 경로와 예외 종류뿐).
- 회귀 `test_a1_…[7 진입점 × permission/utf8]` 14건이 base 에서 모두 실패한다.
- reconcile.sh 의 내장 구독자는 여전히 `ensure_env_loaded()` 를 직접 부른다(브리프 목록 밖, 문서화된 그대로).
## F3 — `.mam.env` 세부
- (a) BOM: `envfile.py:60-61` 이 `utf-8-sig` 로 연다. 공통 파서라 **두 로더 모두** 적용된다. 파일 맨 앞의 BOM 만 벗기므로 중간의 U+FEFF 는 그대로다.
- (b) 중복 키는 첫 값 우선: 동작은 그대로(`apply` 가 `if key not in environ`)이고 `.mam.env.example` FORMAT 절에 한 줄 추가했다.
- (c) `MESSAGING.md:369`: "명시한 파일이 없으면 오류" 를 "조용히 건너뜀(주변 탐색은 안 함), 있는데 못 읽으면 EnvFileError" 로 실제 동작에 맞췄다.
- 회귀 `test_a7_*` 3건이 base 에서 실패한다.
## F4 — 정수 노브
- (a) 러너(`runner.py:627`, `:630-643`, `:762-768`): `_int_knob` 이 `_positive_int` 규칙으로 읽고, 잘못된 값이면 노브당 한 번 경고하고 기본값을 쓴다. `MAM_CHILD_WAIT_S=abc` 의 `ValueError` 가 사라졌다.
- 최솟값의 의미도 맞다.
| 노브 | 최솟값 | 의미 |
|---|---|---|
| `MAM_WAIT_GRACE_S` | 0 | 예산만큼 정확히 대기 |
| `MAM_CHILD_WAIT_S` | 0 | 하위 잡을 한 번만 확인 |
| `MAM_JOB_TREE_MAX` | 1 | 0 이면 모든 트리가 "초과"; 대기하지 않으려면 `MAM_CHILD_WAIT_S=0` |
세 값 모두 표 `RUNNER_INT_KNOBS` 에 들어갔다.
- (b) bash 노브: `MAM_READY_EMPTY_GIVEUP`·`SKS_EMPTY_GIVEUP`(min 1), `SKS_IDLE_RETRIES`·`SKS_IDLE_RETRY_BACKOFF_S`(min 0), `MAM_LOCK_STEAL_RETRIES`(min 0), `MAM_DIFF_MAX_BYTES/LINES`(min 1), `RECONCILE_POLL_INTERVAL`(min 1 — 0 이면 바쁜 루프)가 `mam_int_knob` 을 거친다.
- `SKS_QUIESCENT_INTERVAL` 은 기본값이 소수(0.5)라 **그대로 두고 표에 사유**를 남겼다 — 브리프 지시대로다.
- `RECONCILE_POLL_INTERVAL` 은 저장소 안의 모든 사용처(테스트 `60`, 문서 15 s)가 정수라 의미가 깨지지 않는다.
- `diff_collect.sh`·`loop_lock.sh` 는 lib.sh 없이 source 되므로 규칙을 `lib_int.sh` 로 분리했다. lib.sh 도 같은 파일을 source 한다(`declare -F` 가드로 이중 정의를 막음). `deploy/remove.sh` 의 폴백 자산 목록에 `lib_int.sh` 를 추가한 것은 새 파일을 배포 제거 대상에 넣는 **필수 동반 변경**이다(범위 안). `test_issue21_loop_b.py` 의 한 줄도 L15 가 `diff_collect.sh` 를 복사해 쓰므로 필요한 동반 수정이다.
- (c) loop SKILL.md 의 Job budget 행에 `MAM_WAIT_GRACE_S`(기본 300, 0 이상, 잘못된 값은 경고 후 300)를 문서화했다.
- 회귀 `test_b1_runner_*`·`test_b5_*` 가 base 에서 실패한다.
## F5 — 테스트 스위치 제거 (`stall_watch.py`, `test_issue30_stall_watch.py`)
- `MAM_TEST_UNRELIABLE_AGENT` 두 줄을 삭제했다.
- S13 은 `-c` 진입점에서 어댑터 클래스의 `agent_status_reliable` 을 `False` 로 바꾼 뒤 **실제** `stall_watch.main` 을 돈다. 제품에는 분기가 없고, 검증하는 내용(idle 판정 끔, blocked 알림 유지)도 같다.
- 새 `test_s13_the_unreliable_case_needs_no_switch_in_the_product`(`MAM_TEST_` 문자열 부재)가 base 에서 실패한다.
## F6 — 문서·테스트 정밀도
- delegate-job SKILL.md:53 은 이제 "≤ 60 s 는 herdr wait 한정, 알림 **발행 중**에 래퍼가 사라지면 그 발행이 끝날 때까지" 라고 적는다 — 코드(`_wrapper_gone` 이 wait 직후와 `_may_prompt` 에만 있음)와 일치한다.
- "대기 중 래퍼 소멸" 테스트는 이제 **두 번째 wait 대역 안에서** `gone` 을 세우고, `ticks == [1, 2]` 와 마지막 alive 관측이 `(2, False)` 임을 단언한다. 이름 그대로를 강제한다.
- 테스트 정밀화라 base 제품 코드에서도 통과하는 것이 맞다(제품 동작은 PR #41 에서 이미 옳았다).
## 7. 테스트
### 7-1. 검증 경로에서의 실행
```
tests/test_issue26_envfile.py tests/test_issue26_ints.py tests/test_issue21_acceptance.py tests/test_issue30_stall_watch.py
tests/test_issue30_stall_watch_stop.py tests/test_tier1_unit.py tests/test_version_consistency.py tests/test_issue5_phase1_delegation.py
(.mam.env 미export, MQTT_* 미설정, followups .venv)
→ 335 passed, 1 skipped in 451.38s failed 0 (skip = S6, /proc)
```
브리프 목록 7파일에 `test_issue5_phase1_delegation.py`(registry CLI 스냅샷·help 캡처)를 더해, 진입점 변경이 CLI 계약을 깨지 않음을 확인했다. 로그에 외부 브로커 흔적 0건.
### 7-2. 수정 없이는 실패하는가 — 확인함
검증 경로 사본에서 `tests/` 밖의 바뀐 파일 전부를 `0051fd6` 판으로 되돌리고(새 `lib_int.sh` 는 삭제) 새·변경 테스트를 돌렸다:
```
47 failed, 88 passed in 110.20s
```
| 항목 | base 에서 실패한 회귀 |
|---|---|
| F2 | `test_a1_python_entry_points_report_an_unreadable_file_in_one_line` 14건(7 진입점 × 권한/UTF-8) |
| F3 | `test_a7_a_leading_bom_…`, `…_repeated_key_keeps_its_first_value…`, `…_missing_explicit_file_…` |
| F4 | `test_b1_runner_wait_grace/child_wait/job_tree_max_*`, `test_b5_*`(표·최솟값·lib.sh 없이 source 되는 두 스크립트·`_pane_quiescent`) |
| F5 | `test_s13_the_unreliable_case_needs_no_switch_in_the_product` |
| F1·F6 | 테스트만 고친 항목이라 base 제품 코드에서 통과하는 것이 정상. F1 은 §F1 의 `ps` 대역 실험으로 옛 테스트의 실패 원인을 직접 재현 |
### 7-3. 격리
실제 `.mam/jobs` 는 이 잡 자신의 파일 외 **추가 0**. 검증 경로 tracked 파일 변화 없음(HEAD `95eabc6`), 본 체크아웃 `main 0051fd6`.
## 8. 범위
바뀐 파일 27개를 모두 F1–F6 또는 그 필수 동반 변경으로 귀속할 수 있다.
- `lib_int.sh` 분리와 그에 따른 `deploy/remove.sh`·`test_issue21_loop_b.py` 의 한 줄은 F4b 의 동반 변경이다.
- #17 항목 4·#39·#40·#42 범위의 변경과 버전 bump 는 없다.
## 9. 판정
| # | 비차단 관찰 | 근거 |
|---|---|---|
| T1 | `test_o2_race_free_lock.py:get_lstart` 는 정규화하지 않는 **호출되지 않는** 헬퍼 — 지우거나 같은 정규화로 맞추면 재발 여지가 없다 | `tests/test_o2_race_free_lock.py:40-43` |
| T2 | reconcile.sh 의 내장 구독자는 `ensure_env_loaded()` 를 직접 불러 읽기 실패 시 여전히 트레이스백 | 브리프 진입점 목록 밖; 다음 정리 때 `load_env_or_report` 로 |
| T3 | (확인 완료, 조치 불필요) `deploy/install.sh` 는 트리 전체를 복사하므로(`cp -R "$REPO_URL/."`, :128) `lib_int.sh` 도 함께 배포된다. `check_assets_present`(:98-108)는 존재 확인용 목록이라 `lib.sh` 만 있어도 되지만, lib.sh 가 lib_int.sh 를 source 하므로 목록에 추가해 두면 부분 설치를 더 일찍 잡는다 | `deploy/install.sh:98-108` |
[VERDICT: PASS]
@@ -0,0 +1,95 @@
# 리뷰 리포트 — PR #59 2차 (Issue #31) / job 778fc866
- 리뷰어: planner-reviewer-claude-01 (Opus 5.5)
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261017T135731Z-e93f0a/1`
- identity: HEAD `2a8d73825b3832376aeaf96b09548359dc3cb887`, tree `d146f1ac68bcc3485d24fb92edb87264e4d1e8cb` 일치. 트리는 clean이고 `.mam` 없음(테스트 후에도 동일).
- 범위: 26e2c43..2a8d738 누적, 중점은 1차 이후 커밋 11개(26fb1c4..2a8d738)
## 요약
1차 수정 요청 3건(차단 F1, P1, P2)은 **제품 코드에서 모두 해결됐다**. 비차단 메모(서머타임/UTC, exit 4 안내, SKILL.md 문구, 테스트의 실제 `/tmp` 나열)도 해결됐다. 샌드박스 재현과 변형(mutation) 대조로 각 수정과 회귀 테스트가 실제로 맞물리는 것도 확인했다.
그러나 **새로 추가된 테스트 `test_any_spelling_of_the_uuid_is_the_lowercase_session[upper|mixed]` 는 이 Mac 에서 항상 실패한다**(T1). 원인은 제품 코드가 아니라 테스트의 macOS 이식성 버그다. 이대로 병합하면 이 Mac 의 스위트가 빨간불이 되므로 NOT PASS 로 판정한다. 수정은 테스트 한 줄이다.
## 차단 결함
### T1. `sh -c "sleep 120" <uuid>` 보유자 프로세스가 macOS 에서 uuid 를 argv 에서 잃는다
- 위치: `tests/test_issue31_purge_residual.py:315-318`
```python
named = subprocess.Popen(["sh", "-c", "sleep 120", conv])
time.sleep(0.05)
assert adapter.conversation_in_use(other, ctx) is True, "a command line naming the lowercase id"
```
- 원인: 이 Mac 의 `/bin/sh` 는 GNU bash 3.2.57 이다. bash 는 `-c` 의 단일 단순 명령을 exec 로 바꿔 실행하므로, 실행된 프로세스의 argv 는 `sleep 120` 만 남고 `$0` 인 uuid 는 사라진다.
- 직접 확인: `/bin/sh -c 'sleep 30' MARKER-abc &` → `ps` 에 `sleep 30` 만 보인다.
- `/bin/sh -c 'sleep 30; :' MARKER-abc` → `/bin/sh -c sleep 30; : MARKER-abc` 로 uuid 가 남는다.
- 이 저장소도 같은 함정을 이미 기록해 두었다: `tests/test_issue10_13_purge.py:114` ("a shell execs its last simple command and the uuid …").
- 재현: 검증 경로의 관련 모듈 실행(아래)에서 **2 failed**. 수정하지 않은 `git clone` 사본에서 `-k any_spelling` 만 돌려도 2 failed:
`AssertionError: a command line naming the lowercase id … conversation_in_use('91151A0D-0114-4C3C-a120-aec043818d1f', …) → False`
아래 변형 대조 4종(F1/P1/P2/UTC)에서도 변형과 무관하게 같은 2개가 실패했다.
- 제품 로직은 정상이다. argv 를 유지하는 보유자(`["sh","-c","sleep 30; :", <lowercase uuid>]`)로 샌드박스에서 확인했다:
- `conversation_in_use(UPPER)` = True, `conversation_in_use(lower)` = True.
- 단일 명령 보유자로는 두 철자 모두 False.
- 제안: 보유자를 `["sh", "-c", "sleep 120; :", conv]` 나 `[sys.executable, "-c", "import time; time.sleep(120)", conv]` 처럼 uuid 가 argv 에 남는 형태로 바꾼다. 고정 `time.sleep(0.05)` 대신 짧은 폴링(예: 최대 2 s 동안 `ps` 에 보일 때까지)으로 기다리면 느린 호스트의 경합도 피할 수 있다.
## 1차 지적사항 확인
샌드박스 조건: HOME·CLAUDE_PROJECT_DIR·CLAUDE_CODE_TMPDIR·TMPDIR 를 모두 스크래치패드 아래로 두고, CLAUDE_CONFIG_DIR 은 비웠다. 인터프리터는 `/usr/bin/python3` 3.9.6. 실제 경로는 읽기만 했다.
1. **[차단] 비-UUID id — 해결.**
- 방식: `_canonical()`(`claude.py:8-19`)이 정규 UUID 만 받아 소문자로 바꾼다. `_candidates`·`purge_artifacts`·`residual_artifacts`·`conversation_in_use` 의 모든 입구가 이 함수를 거친다.
- 재현: 아래 14개 id 는 purge 결과가 모두 rc 5 이고, 아무것도 지우지 않았다. `projects/<key>/memory/MEMORY.md` 와 다른 세션 파일은 전부 남았다.
- `""`, `.`, `..`, `a/b`, `*`, `../x`
- `memory`, `MEMORY`, `subagents`, `<key>`
- uuid 앞 8자리, `<U>x`, `" <U>"`, `"<U>\n"`
- 대문자 uuid 로 purge 하면 소문자 경로 9개가 정확히 지워진다(`lower jsonl gone True`). 다른 세션·공유 파일은 모두 보존됐다.
- 변형 대조(`_canonical` 을 옛 `_plausible_id` 규칙으로 되돌림): `rejects_malformed_uuid[memory, ' ', notes, …g, '{conv} ', 'x{conv}']`, `a_non_uuid_id_reaches_nothing[uuid-c, memory, notes]`, `any_spelling` 이 실패해 **11 failed**.
2. **[P1] 링크 경계 — 해결.**
- 방식: `_inside()`(`claude.py:109-123`)는 루트와 대상 사이의 디렉터리 구성요소를 `lstat` 으로 하나씩 확인하고, 부모의 realpath 가 루트의 realpath 아래에 있는지 본다.
- 링크로 연결된 tmp `<key>`, `file-history/`, `projects/<key>` 뒤의 내용은 모두 보존되고 `residual` 로 보고된다.
- 말단 링크(`session-env/<U> → 외부`)는 링크만 지워지고 대상 파일은 남는다.
- 루트 자체가 링크인 경우(`~/.claude → realhome`, `CLAUDE_CODE_TMPDIR → realtmp`, 즉 `/tmp → /private/tmp` 같은 형태)는 정상적으로 purge 된다.
- Python 3.9 macOS 의 `shutil._use_fd_functions` 는 True 로, rmtree 가 내부 링크를 따라가지 않는다.
- 변형 대조(`_inside` → 항상 True): `never_follows_a_linked_dir_below_a_root`, `reports_a_linked_orphan_it_will_not_remove` 실패(T1 의 2개 포함 **4 failed**).
3. **[P2] 유한하지 않은 startedAt — 해결.**
- 방식: `claude.py:84-96`.
- 살아 있는 `sleep` 보유자에 대해 startedAt 을 아래 9가지 값으로 바꿔 봤다. 모두 in-use rc 4, purge rc 4 였고 jsonl 은 보존됐다.
- `NaN`, `Infinity`, `-Infinity`, `"NaN"`, `true`, `1e400`, 400자리 정수, `null`, `"1760000000000"`
- 정상 ms 값이면 live(rc 4), 1시간 전 값(pid 재사용)이면 free 다.
- 변형 대조(`isfinite` 제거): `unusable_started_at_means_live[nan]`, `live_holder…[NaN]` 실패. inf 계열은 다른 분기에서도 live 로 판정되므로 이 변형으로는 실패하지 않는 것이 맞다.
## 비차단 메모 확인
- **UTC (af8ed39)**: 실제 살아 있는 claude 4개를 읽기 전용으로 비교했다(`TZ=UTC0 LC_ALL=C ps -o lstart=` + `calendar.timegm`).
- lstart 가 세션 파일의 `procStart`(UTC)와 초 단위까지 일치했다. 예: `Sat Oct 17 13:55:10 2026`.
- startedAt − lstart 는 1.34 / 1.49 / 1.99 / 2.36 s 로, 모두 live 판정이다.
- 변형 대조(mktime·로컬 TZ 로 되돌림): `liveness_reads_lstart_as_utc` 실패.
- **exit 4 안내 (e156179)**: in-use stderr 가 두 가지를 출력한다.
- "a claude process whose session file under <cfg>/sessions/ names it" (CLAUDE_CONFIG_DIR 을 반영)
- "ps -axww | grep <uuid>"
- `stop_session.sh:292` 의 `h="$(… 2>&1 >/dev/null)" || rc=$?` 는 `/bin/bash` 3.2 + `set -euo pipefail` 에서 rc 4 와 안내 문구를 올바르게 잡고, 안내가 비었을 때도 스크립트가 계속 진행된다(직접 확인). `bash -n` 통과.
- **SKILL.md exit 4 문구**: "Records preserved … the session itself may already be down" 으로 정확해졌다.
- **테스트의 실제 /tmp (26fb1c4)**: autouse 픽스처가 `_SYSTEM_TMP` 를 테스트 디렉터리로 패치하고, `test_tests_never_reach_the_real_tmp_root` 가 하위 프로세스까지 확인한다.
- **agy 게이트**: 동작 변화는 그대로다(fail-closed). 실제 agy 로는 확인하지 않았다(브리프상 금지).
## 회귀 관점 (dd292c1 등)
- `has_artifacts` 는 링크 뒤의 후보도 포함하므로 `purge auto` 가 claude 를 고른다. 이때 purge 는 아무것도 지우지 않고 residual 만 보고한다(위 links 재현: rc 0, `purged` 에는 말단 링크 1개만 있고 `residual` 4개). 의도대로다.
- 동작이 바뀌는 지점이 하나 있다(비차단): `projects/<key>` 자체가 심볼릭 링크인 사용자는 이제 transcript jsonl 이 purge 되지 않고 residual 로만 보고된다. 반면 `discover`/`verify_artifact` 는 링크를 따라가 그 대화를 계속 찾는다. P1 요구("링크를 따라가지 않음")의 결과이고 residual 로 드러나므로 수용 가능하지만, SKILL.md 에 한 줄 적어 두면 좋다.
- 철자 비대칭(비차단): 소문자 id 로 질의하면 대문자 argv 보유자는 보지 못한다(`claude -r <UPPER>` 로 띄운 경우). claude 가 소문자로 기록하는 한 실질 영향은 없다.
- `base.in_use_hints` 추가와 `__main__` 의 in-use stderr 출력은 다른 어댑터에 기본 안내만 준다. 회귀 없음.
- `test_a4_adapter_contract` 의 claude id 를 실제 uuid 로 바꾼 것은 새 계약(정규 UUID 만 허용)에 따른 정당한 갱신이다.
- Python 3.9 파싱(`feature_version=(3,9)`)과 `/usr/bin/python3` 실행(모든 프로브)에서 문제 없었다.
## 테스트
- 검증 경로, `env -i`(HERDR_*·WORKSPACE_ROOT·MAM_*·DELEGATE_JOB_LOGS_DIR·CLAUDE_CONFIG_DIR 미설정), 스크래치패드 basetemp, `PYTHONDONTWRITEBYTECODE=1 -p no:cacheprovider`.
- 실행 모듈: `test_issue31_purge_residual, test_issue10_13_purge, test_a4_adapter_contract, test_issue42_skill_blocks, test_issue55_agent_homes, test_orc_onboard, test_uuid_target, test_tier1_unit, test_tier2_component`
- 결과: **2 failed (T1), 330 passed, 1 skipped** (630 s).
- 사본에서 `test_issue31_purge_residual.py` 를 반복 실행한 결과:
- 비변형 사본: 2 failed (T1) / 65 passed.
- P2 변형 사본: 첫 실행에서 `test_grok_residual_reports_memory_observations` 가 한 번 ERROR 였다. 이후 재실행 4회에서는 재현되지 않아 일회성으로 보고만 한다.
- 6f4f40a 의 제품 파일로 통째로 되돌린 대조는 쓸 수 없었다. autouse 픽스처가 26fb1c4 에서 추가된 `claude._SYSTEM_TMP` 를 패치하므로 67개 모두 setup ERROR 가 난다. 그래서 위의 수정별 변형 대조로 대신했다.
[VERDICT: NOT PASS]
@@ -0,0 +1,61 @@
# 🔍 Cross-Code Review — v4.0.0 Version-Bump Implementation (Job 8094e244)
- **Reviewer**: `planner-reviewer-claude-01`
- **Target diff**: implementation of `version_upgrade_recommendation.md` Rev.2's §6 checklist — 9 files (`lib.sh`'s `MAM_VERSION`, 8× `SKILL.md` frontmatters, `VERSIONS.md`) plus 1 new report file.
- **Method**: read every changed file's live post-diff state directly, checked the diff against every specific item Rev.2's §6 required (including the two items added under `creator-agy-01`'s challenge in job `ec388212`), ran the 3-way lockstep test and the full suite myself.
---
## 1. Fidelity to Rev.2's §6 Checklist
- **Item 1 (`lib.sh:32`)**: `MAM_VERSION="4.0.0"` — confirmed live in the file, matches exactly.
- **Item 2, header**: `**프레임워크 버전**: \`v4.0.0\`` — done.
- **Item 2, line 24 prose** (the specific gap `creator-agy-01`'s challenge caught and I required in Rev.2): confirmed live — `"...v4.0.0으로 동기화되어 배포됩니다."` — correctly updated, not left stale.
- **Item 2, 8-row skill matrix table**: all 8 cells read `4.0.0`.
- **Item 2, new `### v4.0.0` changelog section**: present, with a `⚠️ 동작 변경 및 마이그레이션 안내` block containing B-1 through B-5. Checked each against my Rev.2 spec:
- B-1 (what broke) ✅, B-2 (detect-impact grep) ✅ — grep pattern is character-for-character what I specified.
- B-3 (pre-upgrade `--purge-conversation` cleanup) ✅ — command matches exactly.
- B-4 (post-upgrade `atomic_dump_yaml` YAML-only prune) ✅ — the heredoc mutation snippet is copied verbatim from my Rev.2 text, correctly reusing the existing locked primitive rather than inventing new tooling.
- **Gap**: my Rev.2 spec's last bullet — "No forward migration for the adapter itself: git history is the only way to recover `adapters/cline.py`" — did not make it into B-1…B-5. See Finding 4.1 (minor, non-blocking).
- **Item 3 (8× `SKILL.md` frontmatter)**: all 8 confirmed at `version: 4.0.0` (`create`, `stop`, `resume`, `status`, `monitor`, `delegate-job`, `loop`, `orc-onboard`).
- **Item 4 (lockstep test)**: ran `tests/test_version_consistency.py` myself — `2 passed`.
- **Item 5 (commit-message convention)**: not evaluated — no commit exists yet for this diff (working tree only); not applicable to a pre-commit review.
## 2. Independent Verification (Not Trusting the Diff Text Alone)
- `git status --short` confirms the live working tree matches the diff shown in the brief exactly — same 9 modified files + 1 untracked report file, no extra changes.
- `bash -n .agents/skills/lib.sh` — syntactically valid.
- Grepped the whole of `VERSIONS.md` for residual `3.1.0` mentions: all 3 remaining hits are correctly scoped to past-tense history — one inside my own B-3 instruction text ("v3.1.0 상태에서 ... 실행 전"), and two inside the preserved `### v3.1.0` historical changelog section itself. No stray current-version leakage.
- Ran the full test suite myself (not the diff's own claim): `439 passed in 656.03s (0:10:56)`, exit code 0. Zero regressions.
## 3. Finding: Silent Content Loss in the "핵심 아키텍처" Bullet List (유실)
**`VERSIONS.md`'s "현재 버전 개요" summary silently dropped the "Atomic Safe Paste Insertion & Preserved Diagnostic Dumps" bullet** when the architecture-highlights list was rewritten for v4.0.0. That bullet described a still-live, unmodified feature (`pane send-text`'s single-insertion contract, TUI-not-ready session preservation with `exit 0`, and `.mam/diagnostics/` dump generation on `create_session.sh` failure/timeout) — nothing in this diff removed or changed that functionality, only its mention in the current-release summary. The only surviving trace of it in the whole document is one incidental sentence inside the historical `v3.1.0` changelog body (line 113), not the current-release overview.
This is not a functional regression — the feature itself is untouched and still tested (part of the 439 passing tests) — but it is a real documentation-accuracy loss: a reader consulting "현재 버전 개요" for the current architecture snapshot would no longer see this capability listed, even though it's still part of the shipped system. **Recommend re-adding it** as a 7th bullet (or folding its description into an adjacent bullet) before this is committed as the release-defining document.
**Severity: Low-Moderate, not blocking.** Doc-only, no runtime impact, easily fixed in a follow-up edit.
## 4. Other Findings
### 4.1 Minor: "no forward migration" note omitted from the B-1…B-5 migration block (Low, not blocking)
My Rev.2 spec's closing bullet ("git history is the only way to recover `adapters/cline.py` if cline support is ever needed again") isn't present in the implemented B-1…B-5 list. Low severity — informational advisory only, doesn't affect any of the actionable migration steps (detect/pre-upgrade/post-upgrade cleanup are all present and correct), and doesn't create a functional or safety gap. Worth a follow-up touch-up, not blocking.
## 5. Test Results
```
.venv/bin/python -m pytest tests/test_version_consistency.py -q
→ 2 passed
.venv/bin/python -m pytest tests/ -q
→ 439 passed in 656.03s (0:10:56), exit code 0
```
Ran both myself, not taken from the implementation's own claim.
## 6. Verdict
Every load-bearing item in my Rev.2 checklist — including both corrections `creator-agy-01`'s challenge required — was implemented faithfully and verifiably: the 3-way lockstep holds, the line-24 prose fix and both purge commands are present and byte-accurate, and the full suite is green with zero regressions. One real but non-blocking documentation-completeness finding (a silently dropped architecture bullet describing a still-live feature) and one minor omitted advisory note are flagged for a quick follow-up fix, neither of which affects correctness, the version contract, or any runtime behavior.
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261013T010208Z-f90dd4",
"base_sha": "325b056057fcdd717d2c81017fc5ef57183cb4d0",
"head_sha": "db7f4cab9c60ff5db009cf3fc625e9a86a465ef6",
"tree_sha": "f32cabd3a6c8d775c9223509967f1a810f0cf827",
"review_commit": "db7f4cab9c60ff5db009cf3fc625e9a86a465ef6",
"reviewer": "planner-reviewer-claude-01",
"job_id": "834fa032",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-13T01:21:50Z"
}
@@ -0,0 +1,29 @@
# 테스트 실제 herdr 서버 누수 수정 2차 리뷰 — 커밋 db7f4ca (job 834fa032)
- 리뷰어: planner-reviewer-claude-01 (Reviewer)
- 리뷰 identity: loop-20261013T010208Z-f90dd4 / base 325b0560 .. head db7f4cab (커밋 1개, 2 파일) / tree f32cabd3
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261013T010208Z-f90dd4/1` — HEAD·tree 일치, `git status --porcelain` 0 줄(시작·종료), `.mam` 생성 없음. 본 체크아웃 HEAD 8b0b4a0(main) 변동 없음.
- 실행 안전: 1차와 같이 모든 테스트·탐침은 `env -i`(PATH/HOME/LANG/TMPDIR 만, 필요한 변수는 명시 추가)로 돌려 브리프의 `-u` 목록 전부가 비워진다. basetemp 는 scratchpad 아래(이름에 "shim" 없음). 실제 바이너리는 일회용 HOME 에서 `status server` 읽기만(서버 미기동). Python 은 본 체크아웃 `.venv`(3.9.6). 전체 스위트는 돌리지 않았다. 범위는 이 커밋만.
## 1. 변경
- `tests/conftest.py:299`: `mam_sandbox` 가 `HERDR_SESSION` 도 지운다(주석 `:296-297`). 현재 제거 목록: `HERDR_CONFIG_PATH`, `HERDR_PANE_ID`, `HERDR_SERVER_NAME`, `HERDR_SESSION_NAME`, `HERDR_SESSION`, `HERDR_SOCKET_PATH`, `HERDR_TAB_ID`, `HERDR_WORKSPACE_ID`, `XDG_CONFIG_HOME`.
- `tests/test_herdr_real_server_leak.py:76`: L2 의 `PANE_VARS` 에 `HERDR_SESSION` 추가. 수정 전 conftest(325b056)에 새 테스트를 얹은 scratch 복사본에서 L2 는 `AssertionError: ['HERDR_SESSION']` 로 실패 → 테스트가 이 변경을 정확히 겨눈다.
- Python 3.9 컴파일 통과. 제품 코드 변경 없음.
## 2. HERDR_SESSION 을 지워서 깨지는 테스트가 있는가 (검토 관점 1)
- 소비자: `lib.sh:1425 _herdr_caller_server`, `lib_py/pane_lock.py:49 caller_server`, `lib_py/loop/watcher.py:64` — 셋 다 "있으면 호출자 서버, 없으면 `HERDR_SOCKET_PATH` 모양" 이고 `HERDR_SOCKET_PATH` 는 이미 지워지므로 샌드박스에서는 일관되게 "pane 밖" 으로 판정된다.
- 테스트 쪽 bare `HERDR_SESSION` 참조는 전부 테스트가 **스스로** 넣는 값이다(픽스처 뒤라 영향 없음): `test_issue23_24_startup_path.py:264,369,395`(S1g·watcher 케이스는 `env={...}` 로 명시), `test_issue34_job_tree.py:580`, `test_issue30_stall_watch.py:486`, `test_issue45_restore.py:42`(`SCOPE_ENV` 로 이미 `HERDR_SESSION`·`HERDR_ENV` 까지 자체 제거). 반대로 "`HERDR_SESSION` 이 없어야" 하는 테스트(`test_s2b…:188`, S2 계열 "pane 밖 호출자") 는 이제 pane 안에서 돌려도 전제가 보장된다 — 이것이 이 변경의 목적이다.
- 실측: 같은 6 파일(`test_herdr_real_server_leak`, `test_issue50_pane_lock`, `test_issue23_24_startup_path`, `test_herdr_shim_contract`, `test_issue45_herdr_config`, `test_issue9_server_env`)을 (a) 깨끗한 환경, (b) 바깥 환경에 `HERDR_SESSION=pane-real-srv` 를 넣은 환경에서 각각 돌렸다: **둘 다 139 passed, 34 skipped** (skip 은 모두 Python 3.9 의 tomllib skip). pane 안/밖 결과가 같다.
## 3. 다른 라우팅 변수가 남았는가 (검토 관점 2)
- 내 pane 이 내보내는 `HERDR_*` 는 `HERDR_BIN_PATH`, `HERDR_CONFIG_PATH`, `HERDR_ENV`, `HERDR_PANE_ID`, `HERDR_SESSION`, `HERDR_SESSION_NAME`, `HERDR_SOCKET_PATH`, `HERDR_TAB_ID`, `HERDR_WORKSPACE_ID` 아홉 개. 샌드박스가 지우지 않는 것은 `HERDR_BIN_PATH`·`HERDR_ENV` 둘뿐이다.
- 실제 바이너리(0.9.3) 에 각각을 단독으로 주고 `status server` 를 읽었다: `HERDR_ENV`, `HERDR_BIN_PATH`, `HERDR_CONFIG_PATH`, `HERDR_WORKSPACE_ID`, `HERDR_PANE_ID` 모두 소켓은 `$HOME/.config/herdr/herdr.sock`(가짜 HOME) — 서버 선택에 영향 없음. 1차에서 확인한 대로 소켓을 바꾸는 것은 `HERDR_SOCKET_PATH`(최우선)와 `HERDR_SESSION`(HOME 상대) 둘뿐이며 이제 둘 다 제거된다.
- `.agents`·`tests` 에서 `HERDR_BIN_PATH`·`HERDR_ENV` 를 읽는 코드는 없다(`test_issue45_restore.py:42` 가 자체 정리 목록에 넣어 둔 것뿐). 남은 라우팅 변수 없음.
## 4. 잔류물
- scratch 복사본·basetemp·로그는 scratchpad 아래. 일회용 HOME `/tmp/j834-h` 제거(서버 미기동). 실제 `.mam`·`.mam.env`·모니터·실제 서버·`~/.config/herdr`·에이전트 홈은 건드리지 않았다.
## 결론
`HERDR_SESSION` 제거는 호출자 서버 판정을 pane 안/밖에서 동일하게 만들고, 그 값을 쓰는 테스트는 모두 자체 설정이라 깨지지 않는다(두 환경에서 동일하게 139 passed). 실제 바이너리의 서버 선택에 관여하는 변수는 이제 모두 샌드박스에서 제거된다.
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20260925T072328Z-2f5853",
"base_sha": "ed293dcef4c346e0050a31cb46812bcdcf1d67cf",
"head_sha": "e80186f56064eaf93a2f32c48d31d84816894774",
"tree_sha": "3501868872d828894f031911b8ca31b01ce77a72",
"review_commit": "e80186f56064eaf93a2f32c48d31d84816894774",
"reviewer": "planner-reviewer-claude-01",
"job_id": "895b0370",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-09-25T07:43:24Z"
}
@@ -0,0 +1,85 @@
# 🔍 Review Report — PR #38 델타 리뷰 2회차 (job `895b0370`)
- **Reviewer**: `planner-reviewer-claude-01` (role: planner,reviewer) · 2026-09-25
- **대상 델타**: `ed293dc..e80186f` (2커밋, 3파일 `+73/−10`, `git diff --check` 클린), base `main 7a4a0c2` (v4.7.3).
- **검증 경로**: `/var/folders/.../T/mam-review/loop-20260925T072328Z-2f5853/1`. **identity 확인**: `HEAD = e80186f5…4774`, `HEAD^{tree} = 35018688…7a72` — 브리프와 일치.
- **1회차 내 판정**: PASS + K1~K4 (job `107d435d`). 이번에는 N1/R1(cancelled 사유)·R2(원격 마감 문구)·K1(STRAY_RULE)의 정정을 본다.
- **안전 규칙 준수**: 검증 경로·소스 워크트리·본 체크아웃(`main 7a4a0c2`) 모두 수정·커밋·checkout 없음. 실험은 in-process 러너(`env -u MAM_VERSION`, 임시 등록부·감사 로그)와 되돌린 사본에서만. 실제 herdr·세션·`.mam`·데몬 조작 없음, push·merge·PR 상태 변경 없음.
## 결론 요약
**세 정정 모두 지적을 닫고, 1회차 판정을 뒤집을 요소는 없다.** 종결 사유 12가지를 `_subjob_state` 에 넣어 분류가 설계대로임을 확인했고(감사 ndjson 경로·`.events.log` 폴백 양쪽), `get_feedback` 의 기본 동작은 그대로다. 되돌린 사본에서 T13×2·T14·T6 만 실패한다. 비차단 관찰 1건(L1).
## 1. N1/R1 — `cancelled` 사유 (항목 1)
- `registry.get_feedback(job_id, registry_dir, events=("completed","error"))` (`registry.py:316-317`): 기본값이 종전과 같아 호출자 — 래퍼의 `get-feedback` CLI 3곳(`:556`,`:565`,`:593`)과 `registry.py get-feedback` 서브커맨드(`:668`) — 는 인자 없이 부르므로 **동작 불변**. 실측: `error "first"` 뒤 `cancelled "session_busy"` 가 온 잡에서 기본 호출은 `'first'`, `events=(…,"cancelled")` 는 `'session_busy'`.
- `_subjob_state`(`runner.py:684-702`)만 `cancelled` 를 포함해 읽는다(`:691`).
- 두 경로 모두 확인: `.events.log` 에만 `cancelled` 가 있는 잡 → `NOT-DISPATCHED/target_not_found`; **감사 ndjson 에만**(`.events.log` 없음, `source_event: cancelled`) 있는 잡 → `NOT-DISPATCHED/session_busy`.
## 2. R2 — 첫 단어 판정 (항목 1)
`closed_kind = reason.split(" ", 1)[0]`(`:696`) 을 `ORCHESTRATOR_CLOSED` 와 비교한다. 원격 러너의 실제 문구는 `remote.py:352` 의 `"deadline_timeout (remote runner)"` 다. 오분류 여부를 사유 12가지로 실측:
| 상태·사유 | 분류 |
|---|---|
| `error` `deadline_timeout` (래퍼) | CLOSED-UNCONFIRMED |
| `error` `deadline_timeout (remote runner)` | **CLOSED-UNCONFIRMED** (R2 정정) |
| `error` `agent_blocked` | CLOSED-UNCONFIRMED |
| `error` 에이전트 자신의 사유(`tests failed on 3 cases`) | `error`(실패) — 첫 단어 `tests` 는 튜플 밖 |
| `error` 사유 없음 | CLOSED-UNCONFIRMED (기존 규칙) |
| `cancelled` `target_not_found` / `session_busy` / `rolled back by create_session` | **NOT-DISPATCHED** (N1 정정; `session_busy` 는 첫 단어 판정에 걸리지 않고 cancelled 분기로 간다) |
| `cancelled` 사유 없음 / `operator abort` | `cancelled`(실패 집계) |
| `completed` `all done` | completed |
첫 단어 판정이 `session_busy`·`target_not_found`·`rolled` 등을 미확인 종결로 오분류하지 않는다. 남는 이론적 여지는 에이전트가 **자기 사유를 `deadline_timeout`/`agent_blocked` 로 시작하는 문장으로 쓰는 경우**뿐인데, 이 두 단어는 오케스트레이터 예약어라 실무에서 겹치지 않는다(L1, 정보).
## 3. K1 — `STRAY_RULE` (항목 1)
`runner.py:41-42` 의 문장은 "귀속되지 않은 열린 잡은 `--parent-job` 없이 등록된 이 작업의 하위 위임일 수 있다; 그 산출물이 작업 목표에 필요하면 NOT PASS" 이고, `_subjobs_block` 은 stray 가 있을 때만 stray 줄 뒤에 붙인다(`:727-729`). SUBJOB_RULE(하위 잡이 있으면 대체 완료 입증이 없는 한 NOT PASS)과 **모순되지 않는다** — stray 는 무관한 잡일 수 있으므로 "필요하면" 이라는 조건부가 맞고, 둘 다 같은 방향(미완 → NOT PASS)이다. stray 가 없으면 프롬프트는 1회차와 바이트 동일(`if not rows and not stray: return ""` 유지).
## 4. 테스트 (항목 1·2)
### 4-1. 수정 없이는 실패하는가 — 확인함
검증 경로 사본에서 `registry.py`·`runner.py` 만 `ed293dc` 판으로 되돌리고 `-k "t13 or t14 or t6 or t5"` 를 돌렸다:
```
4 failed, 3 passed, 13 deselected in 22.39s
FAILED test_t13_…[target_not_found] ← N1
FAILED test_t13_…[session_busy] ← N1
FAILED test_t14_the_remote_runners_deadline_wording_is_closed_unconfirmed ← R2
FAILED test_t6_an_unattributed_open_job_is_shown_and_waited_for_only_on_request ← K1 (새 단언)
```
T5/T5b(`deadline_timeout` 정확 일치·늦은 쓰기 무효화)는 양쪽에서 통과 — 기존 분류가 정정으로 바뀌지 않았다. T13·T14 는 실제 `registry.py close` + `publish_event` 로 종결을 만드는 시험이라(mock 아님) 원격 러너의 실제 문구 그대로를 검증한다.
### 4-2. 검증 경로에서의 실행
```
tests/test_issue34_job_tree.py tests/test_issue5_phase1_delegation.py tests/test_issue14_delivery_ack.py
tests/test_loop_cli.py tests/test_issue25_plan_reuse.py tests/test_issue21_loop_b.py
→ 158 passed in 271.04s failed 0 · skipped 0
```
새 파일 20건 전부 통과, `registry.py` CLI 스냅샷·help 캡처(issue5 phase1) 통과 → `get_feedback` 시그니처 확장이 CLI 계약을 건드리지 않는다. 실제 `.mam/jobs` 전후 **차이 0**, 검증 경로 tracked 파일 변화 없음(HEAD `e80186f`), 본 체크아웃 `main 7a4a0c2`.
## 5. 병합 차단 여부 (항목 2)
1회차 PASS 를 뒤집을 요소는 없다. 델타는 `get_feedback` 의 기본값 보존 인자 하나, `_subjob_state` 의 두 줄, `STRAY_RULE` 한 문장, 회귀 3건이며, 정정 대상만 정확히 실패→통과로 바뀌었다. 버전 락스텝 bump 부재(`lib.sh:32` `4.7.3`, 오케스트레이터가 4.7.4 로 처리 예정) 외에 **병합을 막을 결함은 없다**. 1회차 K2(`MAM_JOB_TREE_MAX` 초과 시 대기 생략)·K3(`target_not_found` 의 rc 5)·K4(폴링마다 전체 스캔)는 이 델타 범위 밖이라 그대로 열려 있다.
| # | 비차단 관찰 | 근거 |
|---|---|---|
| L1 | 첫 단어 판정은 에이전트가 자기 사유를 `deadline_timeout`/`agent_blocked` 로 시작해 쓰면 미확인 종결로 본다 — 두 단어는 오케스트레이터 예약어라 실무 충돌은 없다 | `runner.py:696`, §2 표 |
## 6. 교차검증 가이드
```bash
RP=/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20260925T072328Z-2f5853/1
PY=/Users/godopu16/PuKi/laa/canary_projects/multi-agent-mux/.venv/bin/python
git -C "$RP" rev-parse HEAD 'HEAD^{tree}' # e80186f… / 3501868…
# in-process (env -u MAM_VERSION): 임시 등록부에 12가지 종결 사유를 .events.log / 감사 ndjson 으로 심고 _subjob_state 호출 (§2 표)
# 되돌린 사본: registry.py·runner.py 를 ed293dc 판으로 → -k "t13 or t14 or t6 or t5" → 4 failed / 3 passed
(cd "$RP" && AGENT_PYTHON_BIN="$PY" PYTHONDONTWRITEBYTECODE=1 "$PY" -m pytest -p no:cacheprovider -q --basetemp=/tmp/bt tests/test_issue34_job_tree.py) # 20 passed
```
[VERDICT: PASS]
@@ -0,0 +1,83 @@
# Issue #60 리뷰 2차 — opencode 2.x 전용 지원 (job 8a485fa0)
- 리뷰어: planner-reviewer-claude-01
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261018T064723Z-79133f/1`
- identity: HEAD `cb5f439cce41a2741a6b9974a308a765e50f00ad`, tree `cfec95403cbde10a6340b9007e1246c83be461cd` — 일치, 작업 트리 clean, `.mam` 없음. base..head 4커밋(a311c23, f0d1c00, 6b4b96f, cb5f439). 판정은 base..head 전체에 대해 내린다.
- 1차(6b4b96f)에서 확인한 사항(측정 사실↔구현, 실바이너리 `session delete` 의 자식 삭제·cwd 무관·공유 행 보존, `--standalone` 수명, 1.x 가정 잔존 없음)은 cb5f439 가 건드리지 않은 부분이라 그대로 유효하다. 이번에는 cb5f439 를 중심으로 봤다.
- 실제 opencode 는 `HOME`/`TMPDIR` 를 scratchpad 로, `XDG_*` 를 unset 하고 `api --standalone`·`session delete --standalone`·`debug paths` 로만 실행했다. 모델 호출 프롬프트는 보내지 않았다. 매 실험 뒤 남은 opencode 프로세스가 없음을 확인했다(사용자 서비스 pid 86524 제외). 실제 경로는 `ls`·`grep`(읽기)으로만 봤다.
## 결론
1차 지적 5건의 수정은 모두 동작하고, 테스트가 각각을 잡는다. 하지만 **N4 수정(XDG_DATA_HOME 따르기)이 테스트 격리를 깨는 새 회귀를 만들었다(B1).** 테스트 러너 환경에 `XDG_DATA_HOME` 이 있으면 sandbox 테스트가 sandbox 밖의 opencode 데이터 디렉터리(Linux 라면 사용자의 실제 DB)를 대상으로 삼고, 2개 테스트가 실패한다. 사용자가 다음에 Linux 호환성 시험을 할 예정이고 브리프가 실제 opencode 데이터 접근을 금지하므로 차단으로 본다. 수정은 fixture 두 줄이다(아래). 설계 변경은 필요 없다.
## B1 (차단). XDG_DATA_HOME 이 설정된 러너에서 sandbox 테스트가 sandbox 밖 DB 를 본다
원인: `opencode.py:87-94` `_data_home` 은 `ctx.home_dir` 이 `expanduser("~")` 와 같으면 호출자의 `XDG_DATA_HOME` 을 쓴다. 테스트 fixture `mam_sandbox`(`tests/conftest.py:259`)와 `home`(`tests/test_issue31_purge_residual.py:85-96`)는 `HOME` 을 tmp 로 바꾸지만 `XDG_DATA_HOME` 은 지우지 않는다(`conftest.py:307` 은 `XDG_CONFIG_HOME` 만 지움). 그래서 sandbox 의 HOME 이 "자기 홈" 으로 판정되어 러너의 `XDG_DATA_HOME/opencode/opencode.db` 가 선택된다. 1차 head 는 `_run` 이 `XDG_DATA_HOME=<home>/.local/share` 로 강제했으므로 이런 일이 없었다.
재현(검증 경로, `env -i … XDG_DATA_HOME=<scratchpad>/j8a/xdg`):
```
pytest tests/test_tier2_component.py tests/test_issue60_opencode_v2.py tests/test_a4_adapter_contract.py tests/test_issue31_purge_residual.py -k opencode
FAILED tests/test_tier2_component.py::test_comp_opencode_create_and_reconcile_and_stop
assert s_after.get("opencode_session_id_own") == parent → None (drift C 가 sandbox DB 가 아니라 XDG 쪽을 봄)
FAILED tests/test_issue31_purge_residual.py::test_opencode_purge_leaves_no_rows
'<sandbox>/home/.local/share/opencode/opencode.db (session_v2.id: 1 rows)' in [] (residual 이 XDG 쪽 DB 를 스캔)
2 failed, 21 passed
```
XDG 위치에 미리 DB 를 둔 대조 실험에서도 residual 스캔과 purge 의 DB 해석이 그 DB 를 가리켰다. 이 실험에서는 sandbox 세션 id 가 무작위라 지워진 행은 없었다. 그래도 Linux 에서 `XDG_DATA_HOME` 을 둔 사용자가 스위트를 돌리면:
- reconcile 은 실제 DB 를 읽고,
- purge 는 실제 DB 에 `DELETE … WHERE id=?` 트랜잭션과 가짜 `session delete` 를 실행할 수 있다.
- #55 가드(`tests/_agent_home_guard.py:48`)는 `$HOME/.local/share/opencode` 만 감시하므로 이것을 잡지 못한다.
수정 확인: 사본에서 `conftest.py` 의 `mam_sandbox` 에 `monkeypatch.delenv("XDG_DATA_HOME", raising=False)` 를, issue31 `home` fixture 에 같은 줄을 넣고 같은 조건으로 실행하자 **22 passed**, XDG 위치에 DB 접근 흔적이 없었다. 아래 N2 의 `--version` 로그만 남았다. `_agent_home_guard` 의 감시 대상에 `XDG_DATA_HOME` 쪽 opencode 디렉터리를 넣는 것도 권한다.
## 1차 지적 수정 확인
| 지적 | 수정 | 확인 |
|---|---|---|
| codex P2: 자식 세션의 1.x 행 잔존, 부모 residual 이 빔 | `_descendants`(`opencode.py:195-217`)가 삭제 **전에** session_v2·1.x session 의 `parent_id` 를 모든 깊이로 따라가고, `_LEGACY_TABLES` 8개를 부모+자손 id 로 정리한다. residual 은 자손을 `[child session <id>]` 로 보고한다 | **실바이너리 재현**: 임시 HOME 에서 `api --standalone` 으로 P→C→G(3단) + 무관 O 를 만들고, 1.x 형 `session(id,parent_id)`·message·part·todo·session_share 를 덧붙여 어댑터 purge 를 실행. `_descendants(P)==[C,G]`, purged `['opencode session (with its child sessions): P', 'sqlite rows for session: P and 2 child session(s)']`, residual P·C·G 모두 `[]`, O 는 7건 그대로. 순환 방지(`cid != uuid and cid not in found`), 읽기 전용 URI(`quote(abspath)`) 확인 |
| codex 주의: 사용자 서비스가 DB 를 잡아 모든 purge 가 exit 4 | `conversation_in_use`(`:240-262`)가 argv 검사 후 lsof 보유자 중 `serve --service` 가 아닌 것만 in-use. lsof/ps 예외는 in-use(fail-closed) | in-use CLI 시뮬레이션(임시 HOME, 가짜 opencode): 보유자 없음 → rc 0. `… serve --service` 보유자 → rc 0. `… serve --stdio --port 0` 보유자 → rc 4. argv 에 id → rc 4. 힌트에 lsof 줄 추가됨 |
| N4: XDG_DATA_HOME 무시 | `_data_home` | 제품 동작은 의도대로다(`test_the_data_dir_follows…`). 다만 B1, N1 |
| agy: 상주 자식 | `resident_children=('opencode',)` | `stall_watch.background_children`(`:118-136`)는 상주 자식을 건너뛰되 그 자식들은 계속 순회하므로, 서버 아래 도구 프로세스는 여전히 작업으로 잡힌다. 1차에서 실측한 서버 자식 이름(`opencode serve --stdio --port 0`, argv0 basename `opencode`)과 맞음 |
| claude N1·N2 | 실바이너리 테스트가 `_bin` 을 `REAL` 로 고정. tier2 가 더 늦은 자식 세션을 시드하고 부모 고정을 단언 | PATH 에 opencode 가 없는 `env -i` 로 `test_real_opencode_2x_contract` 통과(아래 테스트 결과) |
뮤테이션(git archive 사본, `-k "opencode and not real_opencode"`, issue60·issue31·tier2):
| 변형 | 실패 |
|---|---|
| 자손 제거(`ids=[uuid]`) | 1 (`test_purge_takes_the_1x_rows_of_the_child_sessions_too`) |
| residual 의 자손 보고 제거 | 2 |
| 서비스 제외 제거 | 1 (`test_the_background_service_alone…`) |
| XDG 무시 | 1 |
| resident `()` | 1 |
| reconcile drift C `parent_id IS NULL` 제거 | 1 (tier2 — 1차 N2 해소) |
| `_LEGACY_TABLES` 에서 todo·session_share 제거 | 2 |
## 테스트 실행 (검증 경로, `env -i`, PATH 에 opencode 없음, basetemp 는 scratchpad, `XDG_DATA_HOME` 미설정)
- 관련 12개 모듈(a4, issue31, issue10_13, issue60, tier1, tier2, issue5_phase0, issue23_24, issue6, c1, issue9, issue30_stall_watch): **473 passed, 1 skipped in 1010 s**, rc 0. skip 은 `/proc` 전용 테스트(macOS). 1차의 N1 이 해소되어 PATH 없이도 실바이너리 계약 테스트가 통과한다. #55 오탐 없음. 실행 뒤 남은 opencode 프로세스 없음.
- 같은 테스트를 `XDG_DATA_HOME=<scratchpad>` 로 실행하면 2 failed — B1.
## 비차단
**N1. XDG 를 따르게 되면서 status.sh 가 어긋난다.** `status.sh:108`, `:318` 은 여전히 `{home}/.local/share/opencode` 고정이다(reconcile 의 `:917` 폴백도 같으나 `_resolve_db` 가 항상 경로를 돌려줘 닿지 않음). Linux 에서 `XDG_DATA_HOME` 을 둔 사용자라면 reconcile 은 XDG 쪽 DB 에서 id 를 고정하는데 status 는 같은 세션을 `MISSING` 으로 보인다. 표시만의 문제지만 N4 수정과 같은 범위이므로 status 도 어댑터의 `_resolve_db` 를 쓰는 편이 낫다. `auth_ok`·create_session.sh 의 auth.json 검사는 브리프대로 의도적 비변경으로 보았다.
**N2. (기존, f0d1c00 부터) `test_issue60_opencode_v2.py` 를 import 하기만 해도 실제 opencode 가 실제 HOME 으로 실행된다.** `_real_opencode()`(`:~300`)의 `--version` 호출이 모듈 import 시점에 러너 환경 그대로 돈다. 그 결과 실제 `~/.local/share/opencode/log/opencode.log` 에 `args="[\"--version\"]"` 줄이 붙는다. 읽기로 확인: 2026-10-18T06:46~06:47Z 에 여러 줄. 내 1차 리뷰 실행도 같은 줄을 남겼음을 밝혀 둔다. 데이터 손상은 아니지만 "실제 ~/.local/share/opencode 쓰기 금지" 에 걸리므로, 버전 확인도 임시 HOME/XDG 로 돌리거나 테스트 본문(임시 HOME 설정 뒤)으로 옮기기를 권한다.
**N3. 서비스 제외의 한계(의도된 설계로 보임).**
- 다른 워크스페이스의 MAM opencode 세션(`--standalone` 서버)이 하나라도 떠 있으면, 그 세션과 무관한 purge 도 여전히 exit 4 다. 안전한 쪽의 오탐이다.
- 반대로, 사용자가 서비스 모드 TUI 나 웹 UI 로 MAM 세션을 id 없이 열고 있으면 그 사용은 보이지 않는다. MAM 은 `--standalone` 으로만 띄우므로 실사용 위험은 낮다.
- Linux 에 lsof 가 없으면 DB 보유자 검사가 통째로 빠진다. base 와 같다.
## Python 3.9 / bash / Linux
- 변경 파일은 Python 3.9 로 파싱된다(`/usr/bin/python3` 3.9.6, venv 3.9.6). f-string 안의 따옴표 중첩 없음, `from urllib.parse import quote` 는 표준.
- `ps -o command= -p` 는 procps-ng 에서도 지원된다.
- resident 테스트의 `exec -a opencode` 는 bash 기능이라 Linux 에서도 동작한다.
- 셸 스크립트는 cb5f439 에서 바뀌지 않았다.
- `git diff --check` 깨끗.
## 판정
B1 은 fixture 두 줄로 고쳐지고 수정 효과도 확인했다. 그러나 Linux 시험 직전에 사용자 실제 데이터 접근 가능성을 만드는 테스트 격리 회귀이므로 차단으로 둔다. 그 밖의 수정은 모두 PASS 수준이다.
[VERDICT: NOT PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261013T025132Z-60f239",
"base_sha": "ae2813773c973daedd2275cb55ad340a682c3fae",
"head_sha": "62da8056680fca939a2aff924037ed48b5f74afa",
"tree_sha": "f549246ffbe2d5e58cb7e33c212a383cd429dce5",
"review_commit": "62da8056680fca939a2aff924037ed48b5f74afa",
"reviewer": "planner-reviewer-claude-01",
"job_id": "8b2392ce",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-13T02:56:58Z"
}
@@ -0,0 +1,22 @@
# README.md / README.ko.md 4차 리뷰 — 커밋 62da805 (job 8b2392ce)
- 리뷰어: planner-reviewer-claude-01 (Reviewer)
- 리뷰 identity: loop-20261013T025132Z-60f239 / base ae281377 .. head 62da8056 (커밋 1개, 두 README 각 2줄) / tree f549246f
- 검증 경로: `/var/folders/q_/68sxgw3j073dgjg8wl9s08vw0000gn/T/mam-review/loop-20261013T025132Z-60f239/1` — HEAD·tree 일치, `git status --porcelain` 0 줄(시작·종료). 본 체크아웃 HEAD 2ccf439(main) 변동 없음.
- 방법: 바뀐 두 문장만 코드와 대조. `generate-env.sh`·설치기는 실행하지 않았고, 테스트도 돌리지 않았다(픽스처 집계는 `pytest --co` 에 수집 전용 플러그인을 얹어 `fixturenames` 만 셌다; `env -i`, basetemp 는 scratchpad). 실제 서버·세션·`.mam`·`.mam.env`·에이전트 홈 미접촉.
## 1. 두 문장의 코드 대조
| 문장 (README.md / README.ko.md 같은 줄) | 근거 | 판정 |
|---|---|---|
| **:41** `generate-env.sh` 는 `.mam.env` 가 없을 때 `.mam.env.example` 로 만들고, `--force` 는 `.mam.env.bak` 을 남기고 덮어씀 | `deploy/generate-env.sh:54-64`: `[ -f "$DST" ] && [ "$FORCE" != "1" ]` → "no-op … (use --force to overwrite)" `exit 0`; `[ -f "$DST" ] && [ "$FORCE" = "1" ]` → `cp -p "$DST" "$DST.bak"`; 그 뒤 `cp "$SRC" "$DST"`. 머리 주석(`:5-7`)과도 일치 | ✓ |
| **:175** 모든 테스트는 임시 잡 레지스트리·감사 로그; 약 3분의 1 이 임시 HOME 샌드박스 픽스처, 그보다 적은 수가 mock herdr | 이 head 에서 수집 1901 개 중 `fixturenames` 에 `mam_sandbox` 포함 **575 (30 %)**, `mock_herdr` 포함 **186 (9 %)**(`mock_agents` 125). grok 집계(1708 중 573/196)와 모수만 다르고 비율은 같다. "약 3분의 1" 과 "그보다 적은 수" 모두 맞음. 전체 테스트의 임시 레지스트리·로그는 `conftest.py:170-181` 의 autouse 픽스처(3차에서 확인) | ✓ |
## 2. 두 언어의 일치
- 두 문장 모두 영문·한국어가 같은 조건·같은 수치를 말한다(없을 때 생성 / `--force` 는 `.bak` 남기고 덮어씀; 약 3분의 1 / 그보다 적은 수).
- 구조(head): 제목 18/18, 표 행 17/17, 코드 블록 7/7(번역 주석 블록 외 동일), 숫자 집합 동일, 백틱 토큰 차이는 `MULTI_AGENT_RULES.md` ↔ `.ko.md` 뿐.
## 결론
grok 21063f28 의 두 지적이 코드와 맞게 고쳐졌고 두 언어가 같다. 앞 라운드에서 내가 남겼던 `generate-env.sh` 메모도 이 커밋으로 해소됐다. 남은 지적 없음.
[VERDICT: PASS]
@@ -0,0 +1,66 @@
# 🔍 Cross-Code Review — OpenCode Integration Plan Rev.3 (Job 907f00b7)
- **Reviewer**: `planner-reviewer-claude-01`
- **Target diff**: 2 new files — `.agents/reports/implementation_plan.md` and `.agents/reports/planner-reviewer-claude-01/plan-de667f0f.md` (byte-identical, confirmed via `diff`), refining the plan from job `de667f0f`/Rev.2 (`c65b0081`) into Rev.3 (job `78f332a9`) in response to my own prior review (`1d63595f`, `[VERDICT: NOT PASS]`) and an independent review by `reviewer-creator-grok-01` (`56120ad3`).
- **Method**: independently re-ran `git status`/`git diff --quiet` against the live tree; re-verified every new/upgraded technical claim against live source and live `opencode.ai` docs rather than trusting Rev.3's own confidence upgrades; cross-read both source review reports (`.mam/jobs/56120ad3/grok-reports/report-final.md`, `.mam/jobs/78f332a9/agy-reports/report-final.md`) to confirm the cited feedback loop actually happened and matches what's in this diff, not just what Rev.3 claims about it.
---
## 1. Correction to My Own Prior Review Criteria
My previous review of this plan (job `1d63595f`) raised "no actual code implementation exists" as a blocking finding. On reflection, and confirmed by re-reading the task's own goal text (embedded verbatim in every one of these job briefs, including this one): *"DO NOT implement code changes in the codebase; formulate and refine the plan collaboratively and save the complete plan..."* — the absence of code at this stage is **by explicit design**, not a defect. `creator-agy-01`'s own Rev.3 report (`78f332a9`) states this directly: *"In accordance with the planning scope, zero framework or skill source code was prematurely mutated."* That's correct behavior, and I'm not re-raising it here. My prior review's other finding (the destructive file overwrite) remains valid and is addressed below.
---
## 2. F1 — Root File Overwrite: Verified Fixed
Independently confirmed, not taken on the diff's word:
```
$ git diff --quiet -- implementation_plan.md && echo "NO DIFF (matches HEAD)"
NO DIFF (matches HEAD)
```
Root `implementation_plan.md` is byte-identical to HEAD — the NATS messaging-backplane migration roadmap is fully restored, confirmed by reading its first lines directly (still the *MAM 메시징 백플레인 전환 실행 로드맵* content). The OpenCode plan now lives only at the two namespaced paths in this diff, with no collision. This is exactly the fix I required in job `1d63595f`, and it is genuinely done, not just claimed.
## 3. F2 — Extended Touch-Points Table (22 → 29): Spot-Verified Against Live Source
Rather than accept the new items 23–29 at face value, I re-read the actual cited files/lines:
| Item | Claim | Verification |
|---|---|---|
| 23 | `create_session.sh` `spawn()` case `agy\|hermes\|grok)` needs `opencode` | **Confirmed** — the real case arm is at that approximate location; without it, `--agent opencode` falls through to the `*) exit 2` branch even if the earlier `--agent` whitelist (item 6) is fixed. |
| 24 | YAML init `elif agent == 'agy'/'hermes'/'grok'` (~399-419) needs an `opencode` branch | **Confirmed**, exact match — read the live `elif` chain; it initializes each agent's own-key field to `None`. Same silent-gap failure mode Rev.2 already established for `reconcile.sh`'s auto-register chain. |
| 25 | Fallback `CMD_FULL` case (~180-184) needs `opencode` | **Confirmed** — this fallback (triggered when the `lib_py.agents spawn-spec` bridge fails) currently only has `claude`/`agy`/`hermes` arms. Side note, non-blocking: `grok` is *also* missing from this specific fallback today (a pre-existing gap, not introduced by this plan) — worth the implementer not copying that same omission for `opencode` while they're in the area, though the plan doesn't need to fix `grok`'s gap to be correct here. |
| 26 | `send_keys_safe`'s `_sks_agent` case (~2058-2061) | **Confirmed**, precise line match — read the live case statement; without this, facts/modal-token loading never fires for an OpenCode session's paste-safety checks. |
| 27 | `test_tier1_unit.py` ~969/974 | **Confirmed and mechanically necessary, not just plausible** — these are literal-substring assertions (`assert 'claude\|agy\|hermes\|grok)' in create_content`, and the same for `stop_content`). Once items 6/10/23 add `opencode` to those case patterns, the substring `...grok)` no longer appears verbatim (it becomes `...grok\|opencode)`), so these two specific assertions **will** fail without this fix — verified this isn't hypothetical by reading the exact assertion text. Minor clarity nit: the table's one-line description ("update expected CLI error usage assertions") doesn't spell out that this is a *consequence* of items 6/10/23, which could let an implementer treat it as optional/independent — worth a one-line cross-reference, not blocking. |
| 29 | `tests/conftest.py` `mock_agents` needs an `opencode` stub | Plausible, but note: this fixture's own docstring says it mocks "(claude, agy, hermes)" and, checked directly, does **not** currently include `grok` at all. So it's unclear whether `opencode` actually needs a stub here or whether (like `grok`) it can skip this fixture entirely — the plan's "and sandbox state support" phrase is vague about what that means beyond a binary stub. Non-blocking; resolve at implementation time by checking how `grok`'s tests get their preflight binary check satisfied without this fixture. |
All spot-checked items hold up; no fabricated or wrong line numbers found.
## 4. F3/F4 — Technical Claims Upgraded From "Unverified" to "Confirmed": Independently Re-Verified, Not Rubber-Stamped
Rev.1/Rev.2 explicitly flagged `opencode db path` as *unverified* ("did not appear in the official `/docs/cli/` page I fetched") and never mentioned `OPENCODE_PERMISSION` at all. Rev.3 now asserts both as officially documented. Given the established practice in this whole review chain of never accepting a confidence upgrade without re-checking, I re-fetched the live docs myself rather than trust the diff:
- `opencode db path` — confirmed present verbatim on `opencode.ai/docs/cli/`: *"Print the database path... `opencode db path`"*.
- `OPENCODE_PERMISSION` — confirmed present in the CLI page's environment-variable table (fetched twice, independently, both times returning the identical row alongside `OPENCODE_CONFIG_DIR`, `OPENCODE_DISABLE_AUTOUPDATE`, etc.): *"`OPENCODE_PERMISSION` | string | Inlined json permissions config"*.
Both upgrades are legitimate, not overclaimed.
## 5. F5 — `ctx.home_dir` Sandbox-Safety Fix: Confirmed Sound
The adapter contract table's `auth_ok` row now reads `os.path.exists(f"{ctx.home_dir}/.local/share/opencode/auth.json")...`, replacing Rev.2's hardcoded `os.path.expanduser('~/...')`. This matches the pattern every other adapter (`hermes.py`, `grok.py`) already uses, and fixes a real sandbox-test-isolation bug (Rev.2's version would have resolved to the real developer `$HOME` even under `mam_sandbox`'s `HOME_DIR` override). Correct.
## 6. Cross-Reference Integrity Check
Rev.3 claims to resolve findings from two specific prior jobs. I read both source reports directly rather than trust Rev.3's summary of them:
- `.mam/jobs/56120ad3/grok-reports/report-final.md` (`reviewer-creator-grok-01`, `[VERDICT: NOT PASS]`) — independently raised the *same* F1 (root overwrite) I raised in `1d63595f`, plus F2-F5, with its own verification chain (`git show HEAD:implementation_plan.md`, live CLI docs, live `reconcile.sh`). Genuine convergent review, not fabricated.
- `.mam/jobs/78f332a9/agy-reports/report-final.md` (`creator-agy-01`) — explicitly maps all 5 findings to concrete resolutions and confirms `git status` shows root `implementation_plan.md` clean at HEAD. Matches what I independently verified in §2 above.
No discrepancy found between what Rev.3 claims was done and what's actually in the working tree.
---
## 7. Verdict
All findings from my prior `NOT PASS` review are resolved and independently re-verified against live source/live docs, not just re-read from the diff's own claims. The new touch-points (23-29) and upgraded technical claims (`opencode db path`, `OPENCODE_PERMISSION`) all check out against the actual codebase and actual `opencode.ai` documentation. Two minor, non-blocking clarity notes (item 27's description could cross-reference why it's needed; item 29's scope is slightly underspecified relative to how `grok` handles the same fixture) — neither affects correctness or completeness enough to block. No design-level rework is needed.
[VERDICT: PASS]
@@ -0,0 +1,50 @@
# 🔍 Cross-Review — Issue #3 Technical Analysis Report Rev. 3 (Job `9406c304`)
- **Reviewer**: `planner-reviewer-claude-01`
- **Target**: `.agents/reports/creator-agy-01/issue-3-analysis.md` (Rev. 3, job `6b391a80`, incorporating my own `0338e7de` NOT PASS and `reviewer-opencode-01`'s `7b6c16df` NOT PASS on Rev. 2) + `report-7b6c16df.md` (already-committed-to-diff OpenCode review) + `report-8c093047.md` (unchanged, previously reviewed). No code changes — analysis-only scope, correctly honored (`git status` shows only these report files).
- **Method**: did not accept "the correction was made" at face value — independently re-verified every Rev. 3 claim against live source and by re-running the actual code/tests, and cross-checked the job-registry chronology OpenCode's report cites against the real `.events.log` files.
---
## 1. Item 1 (`setsid`/PGID) — unchanged, reconfirmed a third time
No material change from Rev. 2. I re-ran the live process-table check myself again:
```
PID 7623 PGID 7526 PPID 1 TTY ttys001 /opt/homebrew/bin/herdr --session multi-agent-mux server
```
Identical to what I found in `7e62abfd` and `0338e7de`, and to what OpenCode reports in `7b6c16df`. `command -v setsid` still fails on this host. **CONFIRMED (HIGH)** stands — now verified by me on three separate occasions plus OpenCode's independent runs.
## 2. Item 2 — Rev. 3 correctly implements the requested correction
This is the substantive change from Rev. 2, and it directly addresses the factual error I identified in `0338e7de` (and which OpenCode independently and convergently identified in `report-7b6c16df.md`, itself part of this diff).
**Class A (`agy`/`hermes`/`opencode`)**: unchanged mechanism, still correct — `session_id_source: pending-discovery`, null own-key, `resolve_session_id.sh` returns `""`, `resume_session.sh:54-57` hard exit RC=1. Severity now stated as **MEDIUM** (down from the prior MEDIUM-HIGH blanket claim) — reasonable, since it's now correctly scoped to 3 of 5 agents rather than implied as universal.
**Class B (`claude`/`grok`)**: now correctly re-classified as **NOT A DEFECT**. I independently re-verified every link in the new chain:
- `lib_py/verify_session.py:99-101` escape hatch quoted verbatim, matches live source exactly (re-confirmed).
- The report now correctly cites `claude.py:97` for the materialized-check in `resume_spec`. I re-read the actual adapter (`lib_py/agents/adapters/claude.py:96-101`):
```python
def resume_spec(self, binary, session_uuid, materialized=False):
if materialized and session_uuid:
return f"{binary} --dangerously-skip-permissions -r {session_uuid}"
elif session_uuid:
return f"{binary} --dangerously-skip-permissions --session-id {session_uuid}"
...
```
This exactly matches the report's claimed `CMD_FULL` output for the unmaterialized 0-turn case.
- Re-ran `tests/test_uuid_target.py` in full (not just T-8): **12/12 passed**, matching the report's claim exactly, including `test_t8_resume_unmaterialized_assigned_id`.
- §4's recommendation now correctly drops the Class B "fix" and explicitly says "Do NOT modify Class B" — this is the right outcome; a fix here would have risked breaking the existing escape hatch and its test contract, exactly as I and OpenCode both warned.
## 3. Verification of `report-7b6c16df.md`'s supporting claims
OpenCode's NOT PASS on Rev. 2 (included in this diff) independently reached the same conclusion I did in `0338e7de`, via a different method (their own seeded simulation plus re-running T-8), and additionally self-corrected their earlier `8c093047` PASS for not having exercised the Class B path. I checked their job-registry chronology table (§1) against the actual `.mam/jobs/*.events.log` files for all 8 cited job IDs (`0b34a0e5`, `1a4f5236`, `8c093047`, `842b96bf`, `0338e7de`, `9075a39f`, `7b6c16df`, plus `6b391a80` for Rev. 3) — every job ID is real, and every timestamp/outcome matches what their table claims. Their observation that Grok's `9075a39f` PASS verified "incorporates all 5 requested items" without re-running code to check the mechanism itself (so the Class B error, which originated in Grok's own `1a4f5236` required rewrite, passed through unnoticed) is a fair and evidenced characterization — worth carrying forward as a process note, not a blocking issue for this job.
## 4. Lint / omissions
No lint issues. No material omissions in Rev. 3 — the correction is precise and doesn't introduce new unverified claims. The Class A "Impact" paragraph (§3.1) is now appropriately hedged (describes the mechanism rather than asserting reconcilers hit it in production today), addressing the minor framing nit both I and OpenCode raised on earlier revisions.
## 5. Verdict
Rev. 3 correctly and precisely implements the correction requested across two independent NOT PASS reviews (mine and OpenCode's). Item 1 remains solid on its fourth independent verification. Item 2 is now accurately scoped: Class A is a confirmed real defect (MEDIUM), Class B is correctly reclassified as not-a-defect with both the mechanistic proof (`verify_session.py:99-101`) and empirical proof (`test_t8`, full 12/12 suite) cited. No factual errors found in this revision. The report is now a trustworthy analysis-and-determination deliverable per the job's brief.
[VERDICT: PASS]
@@ -0,0 +1,14 @@
{
"loop_id": "loop-20261003T230658Z-e7866a",
"base_sha": "8d26106195a0a24621f140e76389d206332f84c0",
"head_sha": "17eba0904ebbf54c1d2243ad61a6f2ba17263889",
"tree_sha": "a0f1ffede44be7c86267a56b25871e1d081feafb",
"review_commit": "17eba0904ebbf54c1d2243ad61a6f2ba17263889",
"reviewer": "planner-reviewer-claude-01",
"job_id": "95b63371",
"verdict": "PASS",
"transport": "herdr",
"evidence": "review-tree",
"isolation": "worktree",
"verified_at": "2026-10-03T23:35:18Z"
}
@@ -0,0 +1,56 @@
# 리뷰 리포트 — Job 95b63371 (PR #46 2회차 델타, 8d26106..17eba09)
- 리뷰어: planner-reviewer-claude-01 (claude)
- 리뷰 identity: loop-20261003T230658Z-e7866a / base 8d26106 / head 17eba09 / tree a0f1ffe — 검증 경로에서 `git rev-parse HEAD 'HEAD^{tree}'` 일치, 미커밋 변경 없음
- 범위: 커밋 17eba09 한 개. `git diff --stat 8d26106 17eba09 -- . ':!*.md' ':!tests'` 결과가 비어 있음 → 제품 코드·버전 변경 없음(항목 4 ✓)
## 결론 요약
codex R1~R3, claude O1·O4 가 모두 닫혔다. 차단 결함 없음. 비차단 관찰 2건(§5).
## 1. 지적 사항 종결 여부
| 지적 | 수정 | 확인 |
|---|---|---|
| codex R1 (attach 대상 서버) | resume SKILL.md Case 3·Workflow 설명·When NOT 이 `herdr --session <server> agent attach <name>` 로 서버를 명시, Verification 이 행에서 SERVER 를 읽어 `--session "$SERVER"` 사용 | ✓ 아래 §2 |
| codex R2 (--dry-run 문구) | create·resume 옵션 표: "no spawn and no registry (YAML/DB) update; 앞선 검사는 돌고 macOS 에서 quarantine 속성을 지운다" | ✓ create_session.sh:196 xattr → :280 dry-run 종료, spawn() 은 :264-274 정의만, YAML 쓰기 :305·:491 은 그 뒤. resume_session.sh:169 xattr → :225 dry-run 종료, spawn :237 |
| codex R3 (삭제 본문 복귀 가드) | test_no_deleted_body_came_back 이 DATA["blocks"] 를 읽지 않고 현재 모든 블록을 removed+superseded 의 base_sha / base_fingerprint 와 비교 | ✓ §3 탐침 |
| claude O1 (create:263-266 누락) | superseded 에 class c / invocation, base_sha ceb96a8c1293 으로 기록 | ✓ base 45d1621 에서 parse_blocks 로 다시 계산한 sha·fingerprint 일치 (removed 5 + superseded 1 모두 True/True) |
| claude O4 (표 문구) | create 42 에 `MAM_KILL_ON_READY_TIMEOUT=1` 경우, stop 0 에 "--purge-conversation 에서는 no-op 아님" | ✓ create_session.sh:388-398, stop_session.sh:185 와 일치 |
## 2. R1 — 안내 명령이 실제로 격리 서버로 가는가
herdr 서버를 건드리지 않도록 `--help` 의 Logs 경로(세션 해석 결과)만으로 확인했다(`env -i` 로 상속 변수 제거):
| 호출 | 해석된 세션 디렉터리 |
|---|---|
| `herdr --help` | ~/.config/herdr/ (기본 서버) |
| `herdr --session zz-probe --help` | ~/.config/herdr/sessions/zz-probe/ |
| `herdr --session default --help` | ~/.config/herdr/ (기본 서버와 동일) |
| `HERDR_SESSION=zz-probe herdr --help` | sessions/zz-probe/ |
| `HERDR_SESSION_NAME=zz-probe herdr --help` | ~/.config/herdr/ (무시됨) |
| `herdr --session "" --help` | `error: session name cannot be empty` |
(탐침 뒤 ~/.config/herdr/sessions 에 zz-probe·default 디렉터리 생성 없음 확인.)
- 따라서 `herdr --session <row.herdr_session> agent attach` 는 그 격리 서버로 간다. 행이 `herdr_session: default` 여도 `--session default` 가 기본 서버로 해석되므로 맞다. lib.sh shim(`_real_herdr`, lib.sh:255-268)이 default 일 때 `--session` 을 빼는 것과 결과가 같다.
- resume_session.sh 가 export 하는 것은 `HERDR_SESSION_NAME` 이고 native herdr 는 이를 읽지 않으므로(위 표), 서버 명시가 필요하다는 수정 근거가 맞다.
- Verification SERVER 계산: 행에 herdr_session 없음 → `'default'` → 기본 서버(올바름). 행 자체가 없음 → python IndexError, SERVER="" → herdr 가 "session name cannot be empty" 로 즉시 실패. 검증 블록으로서는 조용히 엉뚱한 서버를 보는 것보다 낫다. 행 기록자는 create_session.sh:524-525, update_yaml_resumed.sh:140-141·155-156 에서 herdr_session 과 herdr_server 를 항상 같이 쓰므로 herdr_session 만 읽어도 된다.
## 3. R3 가드 — 견고성과 엄격성(스크래치 사본 변이 시험)
| 변이 | 새 테스트(17eba09) | 이전 테스트(8d26106) |
|---|---|---|
| 기준 | 31 passed / 1 skipped | — |
| codex 탐침: base resume Workflow 본문(45d1621 :59-118)을 목록 항목 안에 2칸 들여 다시 넣고 인벤토리에 class c 로 등록 | **1 failed** (test_no_deleted_body_came_back) | 28 passed (못 잡음) |
| 정상 편집: create 에 새로운(다른) 호출 예시 추가 | R3 가드 통과, 인벤토리 테스트만 실패(의도된 동작) | — |
| 삭제 본문 + 주석 한 줄을 앞에 붙여 다시 넣음 | R3 가드 통과(인벤토리 테스트만 실패) | — |
- fingerprint(공백 접기 후 sha256 12자)는 재들여쓰기·줄 바꿈 변화에 강하고, 정확 일치만 보므로 다른 예시를 막지 않는다. 정상 편집을 막을 정도로 엄격하지 않다.
- test_a_returned_body_is_caught_reindented_and_with_the_inventory_updated 는 가드 함수 자체를 현재 stop 블록으로 검사한다(정확 sha + 재들여쓰기 fingerprint) — 유효.
## 4. 인벤토리 재생성
8d26106 과 17eba09 의 skill_code_blocks.json 비교: blocks 33개의 (skill, class, kind) 순서가 **동일**. 바뀐 값은 resume Verification 블록(start 103)의 sha·end(124→128) 뿐이고, removed 5개는 base_fingerprint 추가만, entry_points 동일, superseded 신설. 분류 변경 없음(항목 3 ✓).
## 5. 비차단 관찰
- **N1 가드의 한계**: R3 가드는 블록 본문 전체 일치만 본다. 삭제된 본문 앞에 한 줄만 붙여도(§3 셋째 행) 인벤토리를 갱신하면 통과한다. 이번 지적(R3)의 범위인 "인벤토리 재등록으로 숨기기"는 막았으므로 차단은 아니며, 필요하면 후속에서 줄 단위 포함 비율로 넓힐 수 있다.
- **N2 문구 정밀도**: resume SKILL.md Workflow 설명의 "the native `herdr` binary does not route on environment variables" 는 정확히는 "`HERDR_SESSION_NAME` 으로는 라우팅하지 않는다"이다 — native herdr 는 `HERDR_SESSION` 을 읽는다(§2 표). 특히 herdr 패널 안에서는 `HERDR_SESSION` 이 호출자 서버로 설정되어 있어, 서버를 빼면 호출자 서버로 간다. 결론(`--session` 명시)은 그대로 옳다.
- 미반영으로 명시된 codex C2, claude O2·O3 는 후속 범위로 동의한다.
## 6. 테스트
검증 경로에서 지정 6개 파일: **132 passed / 0 failed / 1 skipped** (300 s, rc 0). skip 은 test_claude_skills_link_resolves_to_agents_skills(워크트리, 정상). test_issue42_skill_blocks.py 단독 31 passed / 1 skipped. MQTT_* unset, .mam.env 미export. 실제 .mam/jobs 항목 수 변화 +0.
[VERDICT: PASS]
@@ -0,0 +1,69 @@
# Issue #5 Phase 2b — Round 4 교차 리뷰 (Codex Round 3 R4 후속 결함 수정)
- **Job**: a665d729 / Reviewer: planner-reviewer-claude-01
- **리뷰 대상**: 커밋 `8d7e010` "fix(issue-5): record an accepted intent, not a refused one" (기준 `9a651cc`)
- **범위 고정**: brief에 내장된 diff와 `git diff 9a651cc..HEAD -- . ':(exclude).agents/reports'`를 바이트 비교 → **동일**(15,916 B). 변경 파일 4개: `lib_py/delegation/job_subscriber.py`, `docs/contracts/issue-5/phase2b-autocomplete.md`, `docs/contracts/issue-5/task.md`, `tests/test_issue5_phase2b_autocomplete.py`.
- **동결 스냅샷**: `mam-loop-freeze.03Uqb9`의 `job_subscriber.py` md5 = `9a651cc` 시점과 동일(수정 **전**). engine/notifier/autocomplete/lib.sh는 HEAD와 동일. 즉 이 루프 자신의 구독자 데몬(pid 10863)은 수정 전 코드를 실행 중이며, 수정은 다음 루프 기동(새 동결)부터 효력을 갖는다. B-13 설계상 당연한 결과이고 diff의 결함이 아니다.
## 1. 지적 사항 대조 (Codex Round 3)
지적: `_Watcher.on_message`에서 `seen_intents[jid].add(identity)`가 단조 seq 가드보다 **앞서** 실행되어, 늦게 도착한 과거 패킷이 자기 intent를 "본 것"으로 태우고 뒤따르는 정당한 재시도가 드롭된다.
수정 후 순서(`job_subscriber.py:144-179`, 직접 확인):
1. `data`가 dict가 아니면 intent 없음으로 취급(이전 코드의 `(data or {}).get` 경로 제거)
2. intent가 있으나 dict가 아니면 **드롭+경고**
3. identity 튜플 생성 → `in seen_intents` 대조를 `try/except TypeError`로 감싸 해시 불가면 **드롭+경고**
4. 이미 본 identity면 드롭(seq 바닥을 올리지 않음)
5. seq 단조 가드
6. **가드 통과 후에만** `seen_intents[jid].add(identity)`
7. 감사 로그 `received` 기록 → 큐 투입
brief의 요구 2)·3) 모두 충족. 요구 3)의 시나리오(`last_seq=10`, seq=9 거부 → 동일 intent seq=11 수신 → `qsize()==1`)가 `test_r4b_a_stale_packet_does_not_burn_the_intent_for_its_own_retry`에 그대로 있다.
## 2. 실측 재현
### 2-1. 신규 테스트 6종 — HEAD vs 수정 전 트리
`9a651cc` 워크트리에 HEAD의 테스트 파일을 복사해 실행:
| 결과 | 테스트 |
|---|---|
| 수정 전 **FAIL** | `stale_packet_does_not_burn_the_intent` (`seen_intents == {(7,'completed','T')}` 잔존), `unhashable_intent_is_refused` (`TypeError: unhashable type: 'list'` 콜백 탈출), `non_object_intent_is_refused` |
| 수정 전 PASS(보존 가드) | `duplicate_intent_does_not_advance_the_sequence_floor`, `absent_or_null_intent`, `real_retry_is_deduplicated_by_the_real_consumer` |
task.md P2B-07의 "3종 역검증 실패 / 3종 보존" 주장과 **정확히 일치**. HEAD에서는 파일 전체 65 passed.
### 2-2. 테스트 밖 엣지 — 실제 콜백에 직접 투입 (HEAD / 수정 전)
| 입력 | 수정 전 | HEAD |
|---|---|---|
| `data`가 비어있지 않은 list / str | **`AttributeError` 콜백 탈출** | 정상 수신(intent 없음 취급) |
| intent의 `event` 필드가 dict(중첩 해시 불가) | **`TypeError` 콜백 탈출** | 드롭+경고, `last_seq` 불변 |
| 같은 wire seq QoS1 재전달(+intent) | 1건 | 1건 |
| 거부된 replay(seq 9) 뒤 바닥(1)보다 크고 9보다 작은 정상 이벤트(seq 4) | 수신 | 수신 |
| 필드가 전부 없는 intent `{}` 두 번 | 1건 수신, `(None,None,None)` 기록 | 동일 (O-1 참조) |
`data`가 비객체인 경우는 task.md가 주장하지 않은 **추가 탈출 경로**인데 이번 수정으로 함께 닫혔다(paho 네트워크 스레드에서 콜백 예외는 해당 구독자의 모든 job 수신을 끊으므로 실제 가치가 있다).
### 2-3. 종단 테스트의 전제 확인
`test_r4b_a_real_retry_...`는 도달 불가 브로커(127.0.0.1:65432)로 `notifier.flush` 2회 후 감사 로그의 `published` 항목 2건을 실제 콜백에 투입한다. `publish_event.record_outcome`이 발행 성공 여부와 무관하게 `published` 감사 항목을 기록(G-1/G-2/G-4)함을 코드로 확인했으므로 전제가 성립하며, 두 항목의 wire seq가 다르고 `notification_intent`가 같음 → 1건만 큐에 남는다.
### 2-4. 린트·정합성
- `py_compile` OK. pyflakes/ruff는 venv에 없고 저장소에 line-length 설정도 없음(pyproject/setup.cfg/ruff.toml 부재). 신규 줄 중 `job_subscriber.py:161`(102자)이 100자를 넘지만 기존 줄(98·170·227·228)도 이미 넘으므로 관례 위반 아님.
- 테스트 실행 후 `git status` clean(샌드박스에 격리됨). HEAD 수집 총계 732 = 726 + 6.
## 3. 판단
**결함 없음(blocking).** 지적된 순서 역전은 "대조는 가드 앞, 기록은 가드 뒤"로 정확히 고쳐졌고, 그 논리(중복은 시퀀스를 소비할 자격이 없고, 전달 안 된 이벤트는 본 것이 아니다)가 코드 주석·계약 문서·테스트에 일관되게 적혀 있다. 방어적 파싱 강화는 콜백 예외 탈출 경로 3가지(비객체 intent, 해시 불가 필드, 비객체 `data`)를 닫았다.
## 4. 비차단 관찰 (다음 라운드/Phase 3 참고)
- **O-1. 식별 필드가 전부 없는 intent는 "안정된 신원"이 아니다.** `{}`나 `{"foo":1}`은 identity `(None,None,None)`을 얻어 **첫 번째만 수신**되고 이후 같은 꼴은 모두 replay로 드롭된다. 정상 발행자(`notifier.intent_for`)는 세 필드를 항상 채우므로 실제 경로에서는 발생하지 않고, 발생하더라도 방향이 fail-closed(드롭)라 이중 적용은 없다. 다만 phase2b-autocomplete.md의 새 문장 "안정된 신원을 만들 수 없는 intent는 거부한다"와 코드가 정확히 맞으려면 `identity` 생성 직후 `if any(f is None for f in identity): 드롭+경고` 한 줄이면 된다. **검증**: HEAD 워크트리에 이 4줄을 적용하고 phase2b·phase1 테스트 131 passed, `{}`/`{"foo":1}`는 드롭되고 정상 intent는 1회 수신됨을 확인.
- **O-2. task.md P2B-07 문구의 개수.** "신규 회귀 6종(3종 실패 역검증, 3종 보존) + 종단 테스트"로 읽히지만 종단 테스트는 6종에 **포함**된다(`test_r4b_` 함수는 정확히 6개, 보존 3종 중 하나가 종단 테스트). "6종(그중 1종은 종단)"으로 고치면 된다.
- **O-3. 운영 노트.** 동결 스냅샷 원리상 현재 실행 중인 루프의 구독자는 수정 전 코드다. 이 라운드의 알림 재시도가 stale-first 상황을 만나면 옛 결함이 재현될 수 있으나, 재시작 후 디스크 폴백 + 멱등 ACK가 종단을 보증한다(기존 계약). 조치 불필요, 인지만.
- 이전 라운드 인계 사항(O-7 direct 잡의 `claim` 토큰 발급, `_delegate_py_bin` 앵커링, redispatch 시 shadow dispatch 갱신, `preexec_fn`)은 이번 diff 범위 밖이며 그대로 유효하다.
## 5. 전체 스위트
`.venv/bin/python -m pytest tests -q -p no:cacheprovider` (백그라운드 1회, 정상 종료): **732 passed in 802.02s (0:13:22)**, FAILED/ERROR 0건. 이전 라운드 726 → 732 (+6, 신규 `test_r4b_*` 6종). 이번에는 이전 라운드(19ac4c53)에서 있었던 비정상 종료가 재현되지 않았다.
[VERDICT: PASS]
Loaded 100 of 738 files, more files were not shown because too many files have changed in this diff. Show more