@mmerterden/multi-agent-pipeline 20.40.0 → 20.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +5 -2
  3. package/README.tr.md +5 -2
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +51 -14
  7. package/docs/facts.json +7 -7
  8. package/docs/features.md +15 -4
  9. package/install/claude.mjs +45 -3
  10. package/install/templates/claude-hooks.json +23 -1
  11. package/manifest.json +146 -107
  12. package/package.json +3 -2
  13. package/pipeline/commands/multi-agent/autopilot/SKILL.md +11 -0
  14. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  15. package/pipeline/commands/multi-agent/setup/SKILL.md +1 -1
  16. package/pipeline/contract/types/index.d.ts +53 -49
  17. package/pipeline/lib/args.mjs +131 -4
  18. package/pipeline/lib/bg-launch.mjs +5 -2
  19. package/pipeline/lib/context-budget.mjs +5 -42
  20. package/pipeline/lib/credential-store.sh +11 -1
  21. package/pipeline/lib/hook-once.mjs +134 -0
  22. package/pipeline/lib/hook-registration.mjs +5 -0
  23. package/pipeline/lib/isotonic.mjs +73 -0
  24. package/pipeline/lib/low-disk.mjs +153 -0
  25. package/pipeline/lib/mcp-schema-load.mjs +90 -0
  26. package/pipeline/lib/md2confluence-v3.py +19 -10
  27. package/pipeline/lib/model-dispatch.sh +26 -2
  28. package/pipeline/lib/normalize-text.mjs +135 -0
  29. package/pipeline/lib/outbound-gate.mjs +21 -3
  30. package/pipeline/lib/plan-todos.sh +17 -4
  31. package/pipeline/lib/redact.mjs +12 -3
  32. package/pipeline/lib/risky-settings.mjs +198 -0
  33. package/pipeline/lib/route-state.sh +1 -0
  34. package/pipeline/lib/secret-patterns.generated.mjs +6 -2
  35. package/pipeline/lib/session-usage.mjs +232 -0
  36. package/pipeline/lib/source-digest.mjs +211 -0
  37. package/pipeline/lib/tdd-evidence.mjs +250 -17
  38. package/pipeline/lib/tiered-budget.mjs +87 -0
  39. package/pipeline/lib/untrusted-fence.mjs +132 -1
  40. package/pipeline/multi-agent-refs/analysis/locked.md +1 -1
  41. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  42. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  43. package/pipeline/multi-agent-refs/features/cost-analysis.md +37 -2
  44. package/pipeline/multi-agent-refs/features/doctor.md +82 -4
  45. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -0
  46. package/pipeline/multi-agent-refs/features/plan-todos.md +4 -0
  47. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  48. package/pipeline/multi-agent-refs/features/unattended-gates.md +5 -3
  49. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  50. package/pipeline/multi-agent-refs/features/usage-reporting.md +33 -0
  51. package/pipeline/multi-agent-refs/help/en.md +2 -1
  52. package/pipeline/multi-agent-refs/help/tr.md +2 -1
  53. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  54. package/pipeline/multi-agent-refs/outside-the-pipeline.md +6 -0
  55. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  56. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +5 -1
  57. package/pipeline/multi-agent-refs/phases/phase-2-dev.md +4 -4
  58. package/pipeline/multi-agent-refs/phases/phase-3-review.md +2 -2
  59. package/pipeline/multi-agent-refs/phases/phase-5-report.md +4 -0
  60. package/pipeline/multi-agent-refs/progress-contract.md +3 -1
  61. package/pipeline/office/index.html +13 -7
  62. package/pipeline/office/toolkit.json +1 -1
  63. package/pipeline/preferences-template.json +1 -0
  64. package/pipeline/rules/outside-the-pipeline.md +1 -1
  65. package/pipeline/schemas/doctor-report.schema.json +47 -0
  66. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  67. package/pipeline/schemas/office-archive.schema.json +225 -128
  68. package/pipeline/schemas/plan-todos.schema.json +29 -1
  69. package/pipeline/schemas/prefs.schema.json +146 -0
  70. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  71. package/pipeline/schemas/product-tree.schema.json +136 -0
  72. package/pipeline/schemas/route-config.schema.json +51 -0
  73. package/pipeline/schemas/secret-patterns.json +17 -1
  74. package/pipeline/schemas/toolkit-path-params.json +15 -1
  75. package/pipeline/scripts/_cost-advise.mjs +357 -0
  76. package/pipeline/scripts/_cost-budget.mjs +78 -0
  77. package/pipeline/scripts/_cost.mjs +29 -0
  78. package/pipeline/scripts/_decode_text.py +107 -0
  79. package/pipeline/scripts/_eval-stats.mjs +182 -0
  80. package/pipeline/scripts/_guard-probe.mjs +406 -0
  81. package/pipeline/scripts/_guard_rules.py +336 -1
  82. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  83. package/pipeline/scripts/_locate.mjs +539 -0
  84. package/pipeline/scripts/_memory-policy.mjs +208 -33
  85. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  86. package/pipeline/scripts/_product-tree.mjs +923 -0
  87. package/pipeline/scripts/_retrieval.mjs +161 -4
  88. package/pipeline/scripts/_secret-scan.mjs +6 -1
  89. package/pipeline/scripts/_stack-routing.mjs +2 -0
  90. package/pipeline/scripts/_test-gaming.mjs +346 -0
  91. package/pipeline/scripts/_user_guard_rules.py +744 -0
  92. package/pipeline/scripts/agent-guard.py +69 -6
  93. package/pipeline/scripts/agent-guard.sh +8 -1
  94. package/pipeline/scripts/argv-secret-scan.mjs +2 -1
  95. package/pipeline/scripts/autopilot-loop.mjs +407 -0
  96. package/pipeline/scripts/autopilot-runner.mjs +38 -25
  97. package/pipeline/scripts/capture-resume.sh +9 -1
  98. package/pipeline/scripts/cost-analyze.mjs +66 -4
  99. package/pipeline/scripts/cost-budget-check.mjs +5 -13
  100. package/pipeline/scripts/disk-cleaner.mjs +1418 -0
  101. package/pipeline/scripts/doctor.mjs +324 -43
  102. package/pipeline/scripts/evidence-gate.mjs +90 -0
  103. package/pipeline/scripts/gate-ledger.mjs +76 -21
  104. package/pipeline/scripts/gc-tmp.sh +5 -0
  105. package/pipeline/scripts/graph-query.mjs +257 -17
  106. package/pipeline/scripts/guard-probe-known-holes.json +3 -0
  107. package/pipeline/scripts/learnings-ledger.mjs +680 -55
  108. package/pipeline/scripts/note-agent-event.mjs +2 -0
  109. package/pipeline/scripts/note-mcp-failure.mjs +363 -0
  110. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  111. package/pipeline/scripts/note-skill-use.mjs +96 -23
  112. package/pipeline/scripts/office-archive.mjs +23 -10
  113. package/pipeline/scripts/office-memory.mjs +4 -1
  114. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  115. package/pipeline/scripts/pre-commit-check.sh +2 -2
  116. package/pipeline/scripts/pre-push-check.sh +8 -1
  117. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  118. package/pipeline/scripts/product-tree.mjs +544 -0
  119. package/pipeline/scripts/publish-staged.mjs +324 -0
  120. package/pipeline/scripts/route-learn.mjs +628 -0
  121. package/pipeline/scripts/run-scope-guard.mjs +55 -1
  122. package/pipeline/scripts/scan-agent-config.sh +1 -1
  123. package/pipeline/scripts/statusline.mjs +309 -0
  124. package/pipeline/scripts/test-integrity-gate.mjs +97 -2
  125. package/pipeline/scripts/triage-memory.mjs +12 -4
  126. package/pipeline/scripts/uninstall.mjs +1 -0
  127. package/pipeline/skills/.skill-manifest.json +15 -7
  128. package/pipeline/skills/.skills-index.json +25 -3
  129. package/pipeline/skills/shared/README.md +6 -4
  130. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  131. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  132. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  133. package/pipeline/skills/shared/external/disk-cleaner/SKILL.md +105 -0
  134. package/pipeline/skills/shared/external/disk-cleaner/evals/evals.json +62 -0
  135. package/pipeline/skills/shared/external/disk-cleaner/scripts/disk-cleaner.mjs +1418 -0
  136. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  137. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  138. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  139. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  140. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  141. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  142. package/pipeline/skills/skill-copies.json +9 -1
  143. package/pipeline/skills/skills-index.md +4 -2
@@ -4,7 +4,7 @@
4
4
  Reads the PreToolUse payload JSON on stdin and prints exactly one decision:
5
5
  BLOCK_ATTRIB | BLOCK_FORCE | BLOCK_NOVERIFY<TAB>reason | BLOCK_READONLY<TAB>reason |
6
6
  BLOCK_UNATTENDED<TAB>reason | BLOCK_PARSE | ASK<TAB>hook-json |
7
- DENY<TAB>reason | OK
7
+ DENY<TAB>reason | NOTE<TAB>hook-json | OK
8
8
 
9
9
  Never executes the command. shlex.split only tokenizes shell-like text; a
10
10
  `$(...)` in the command is a literal token, never a subshell. The processes it
@@ -15,8 +15,11 @@ Attended (MULTI_AGENT_UNATTENDED unset): the attribution (argv and -F
15
15
  message files), force-push and hook-skipping rules, plus the confirmations in
16
16
  _guard_rules.ask_reason, and any error prints OK (fail-open) so a guard bug cannot break a
17
17
  legitimate tool call. Unattended: unattended_policy.py is consulted as well,
18
- and an error prints BLOCK_PARSE (fail-closed).
18
+ and an error prints BLOCK_PARSE (fail-closed). The user's own rules
19
+ (prefs.global.guardRules, _user_guard_rules) are applied last and can only
20
+ make the verdict stricter; a warn rule's note is NOTE.
19
21
  """
22
+ import hashlib
20
23
  import json
21
24
  import os
22
25
  import re
@@ -27,6 +30,7 @@ import unicodedata
27
30
 
28
31
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
29
32
  import _guard_rules # noqa: E402
33
+ import _user_guard_rules # noqa: E402
30
34
 
31
35
  # An internal deadline well under the hook timeout: if the guard cannot decide
32
36
  # in this long, it prints the blocking verdict when unattended (fail-closed) and
@@ -362,7 +366,7 @@ def decide(cmd: str, depth: int = 0) -> str:
362
366
  if commits and _guard_rules.ai_generated(cmd, PAYLOAD_CWD["dir"]):
363
367
  return "BLOCK_ATTRIB"
364
368
  # Rule 7: a stored secret printed with nothing capturing it.
365
- reason = _guard_rules.secret_echo_reason(cmd)
369
+ reason = _guard_rules.secret_echo_reason(cmd) or _guard_rules.encoded_secret_read_reason(cmd)
366
370
  if reason:
367
371
  return "DENY\t" + reason
368
372
  pending_ask = None
@@ -411,6 +415,13 @@ def decide(cmd: str, depth: int = 0) -> str:
411
415
  if verdict != "OK":
412
416
  return verdict
413
417
 
418
+ if not pending_ask:
419
+ reason = _guard_rules.fork_bomb_reason(cmd) or _guard_rules.fork_bomb_reason(
420
+ normalize_for_match(cmd)
421
+ )
422
+ if reason:
423
+ pending_ask = "ASK\t" + reason
424
+
414
425
  verdict = _command_rules(cmd)
415
426
  if verdict.startswith("ASK"):
416
427
  return pending_ask or verdict
@@ -637,6 +648,27 @@ def fallback_verdict(text: str) -> str:
637
648
 
638
649
 
639
650
  FILE_TOOLS = {"Edit", "Write", "NotebookEdit", "MultiEdit"}
651
+ PRODUCT_TREE_OVERLAY = "product-tree-overlay.jsonl"
652
+
653
+
654
+ def product_tree_overlay_verdict(ti: dict, cwd: str = "") -> str:
655
+ """DENY for a file tool aimed at the product-tree overlay, attended and
656
+ unattended: its rows are the user's agree or reject decisions, written
657
+ only through product-tree.mjs. The name is compared casefolded, both as
658
+ given and after resolving symlinks against the payload's cwd, so a case
659
+ variant on a case-insensitive volume or a link to the overlay is refused
660
+ too."""
661
+ path = ti.get("file_path") or ti.get("notebook_path") if isinstance(ti, dict) else None
662
+ if not isinstance(path, str) or not path:
663
+ return "OK"
664
+ names = [os.path.basename(os.path.normpath(path))]
665
+ try:
666
+ names.append(os.path.basename(os.path.realpath(os.path.join(cwd or os.getcwd(), path))))
667
+ except (OSError, ValueError):
668
+ pass
669
+ if any(n.casefold() == PRODUCT_TREE_OVERLAY for n in names):
670
+ return "DENY\tonly product-tree.mjs propose writes the overlay; a decision is the user's"
671
+ return "OK"
640
672
 
641
673
 
642
674
  # Permission modes in which a hook's "ask" has no documented prompt to raise.
@@ -650,6 +682,28 @@ FILE_TOOLS = {"Edit", "Write", "NotebookEdit", "MultiEdit"}
650
682
  NO_PROMPT_MODES = {"bypassPermissions", "dontAsk"}
651
683
 
652
684
 
685
+ def confirmation_key(data: dict) -> str:
686
+ """What a recorded confirmation names: the exact command for Bash; for any
687
+ other tool its name, the target path when there is one, and the sha256 of
688
+ its input as sorted compact JSON, so a yes covers this exact call only."""
689
+ tool = data.get("tool_name")
690
+ ti = data.get("tool_input") or {}
691
+ if tool == "Bash" or not isinstance(tool, str) or not tool:
692
+ cmd = ti.get("command", "") if isinstance(ti, dict) else ""
693
+ return cmd if isinstance(cmd, str) else ""
694
+ try:
695
+ canonical = json.dumps(ti, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
696
+ except (TypeError, ValueError):
697
+ return ""
698
+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
699
+ path = (ti.get("file_path") or ti.get("notebook_path")) if isinstance(ti, dict) else None
700
+ parts = [tool]
701
+ if isinstance(path, str) and path and not any(c in path for c in "\r\n"):
702
+ parts.append(path)
703
+ parts.append("sha256:" + digest)
704
+ return " ".join(parts)
705
+
706
+
653
707
  def ask_verdict(reason: str, data: dict, strict: bool) -> str:
654
708
  """ASK<TAB>json for a prompt, DENY<TAB>reason where no prompt can be
655
709
  raised, BLOCK_UNATTENDED<TAB>reason when nobody is there to answer."""
@@ -659,12 +713,17 @@ def ask_verdict(reason: str, data: dict, strict: bool) -> str:
659
713
  # With prompts switched off the native ask cannot be raised, so the
660
714
  # recorded confirmation stands in for it. In every other mode the
661
715
  # prompt is the confirmation and a record must not skip it.
662
- if _guard_rules.confirmed((data.get("tool_input") or {}).get("command", "")):
716
+ key = confirmation_key(data)
717
+ if _guard_rules.confirmed(key):
663
718
  return "OK"
719
+ if data.get("tool_name") == "Bash" or not key:
720
+ what, again = "'<the exact command>'", "run the command again"
721
+ else:
722
+ what, again = shlex.quote(key), f"make the same {data.get('tool_name')} call again"
664
723
  return (
665
724
  "DENY\t" + reason + " (permission prompts are off in this mode: ask the user with AskUserQuestion; on yes, "
666
- "record it with node \"$HOME/.claude/scripts/confirm-command.mjs\" --command '<the exact command>' "
667
- "and run the command again, unchanged, within 10 minutes)"
725
+ f"record it with node \"$HOME/.claude/scripts/confirm-command.mjs\" --command {what} "
726
+ f"and {again}, unchanged, within 10 minutes)"
668
727
  )
669
728
  out = {
670
729
  "hookSpecificOutput": {
@@ -847,6 +906,8 @@ def main() -> None:
847
906
  )
848
907
  if reason:
849
908
  verdict = "BLOCK_READONLY\t" + reason
909
+ if verdict == "OK" and data.get("tool_name") in FILE_TOOLS:
910
+ verdict = product_tree_overlay_verdict(data.get("tool_input") or {}, PAYLOAD_CWD["dir"])
850
911
  if (
851
912
  verdict == "OK"
852
913
  and isinstance(cmd, str)
@@ -859,6 +920,7 @@ def main() -> None:
859
920
  "DENY\tthe " + str(data.get("agent_type")) + " subagent is read-only and " + effect
860
921
  + "; it returns findings, and the orchestrator acts on them"
861
922
  )
923
+ verdict, user_rule = _user_guard_rules.before_ask(verdict, data, strict, normalize_for_match)
862
924
  if verdict.startswith("ASK"):
863
925
  verdict = ask_verdict(verdict.split("\t", 1)[1], data, strict)
864
926
  if verdict == "OK" and strict:
@@ -868,6 +930,7 @@ def main() -> None:
868
930
  reason = unattended_policy.check(data)
869
931
  if reason:
870
932
  verdict = "BLOCK_UNATTENDED\t" + reason.replace("\n", " ")
933
+ verdict = _user_guard_rules.after_policy(verdict, user_rule, strict)
871
934
  print(verdict)
872
935
  except Exception:
873
936
  # Attended: a guard bug must not break a legitimate tool call.
@@ -16,6 +16,9 @@
16
16
  # PR body with Closes/Fixes/Resolves #N and a Jira transition POST. Where
17
17
  # the permission mode raises no prompt (bypassPermissions, dontAsk) the
18
18
  # call is denied with the reason instead; unattended it is blocked.
19
+ # 2f. The user's own rules in prefs.global.guardRules (warn, ask, block),
20
+ # applied after every built-in rule and only ever stricter
21
+ # (_user_guard_rules.py); unattended, ask is block.
19
22
  # 3. With MULTI_AGENT_UNATTENDED=1 in the hook's environment only: no outward
20
23
  # writes (push, PR, issue, tracker publishers, mutating API calls), no
21
24
  # Keychain reads, no fetch outside the network allowlist, no package
@@ -66,7 +69,7 @@ DECISION="$(printf '%s' "$PAYLOAD" | CUR_BRANCH="$CUR_BRANCH" python3 "$HELPER"
66
69
  # is said about the call (argv-secret-scan.mjs, the outbound gate's credential
67
70
  # shapes). Only rule names are printed, never the value.
68
71
  case "$DECISION" in
69
- OK|ASK*|DENY*)
72
+ OK|ASK*|DENY*|NOTE*)
70
73
  case "$PAYLOAD" in
71
74
  *'"tool_name":"Bash"'*|*'"tool_name": "Bash"'*)
72
75
  if command -v node >/dev/null 2>&1 && [ -f "$HERE/argv-secret-scan.mjs" ]; then
@@ -109,6 +112,10 @@ case "$DECISION" in
109
112
  DENY*)
110
113
  echo "BLOCKED by agent-guard: ${DECISION#DENY?}." >&2
111
114
  exit 2 ;;
115
+ NOTE*)
116
+ # A user guard rule with action warn: the call proceeds with a note.
117
+ printf '%s\n' "${DECISION#NOTE?}"
118
+ exit 0 ;;
112
119
  BLOCK_UNATTENDED*)
113
120
  echo "BLOCKED by agent-guard (unattended policy): ${DECISION#BLOCK_UNATTENDED?}." >&2
114
121
  echo "This run has nobody watching it. Outward writes go through pr-request.json and the runner;" >&2
@@ -51,7 +51,8 @@ export function withoutReferences(cmd) {
51
51
  return out;
52
52
  }
53
53
 
54
- const URL_CREDS = /\b([a-z][a-z0-9+.-]*:\/\/)([^\s/:@]+):([^\s/@]+)@(\[[^\]\s]+\]|[^\s/:?#'"]+)/gi;
54
+ const URL_CREDS =
55
+ /\b([a-z][a-z0-9+.-]{0,31}:\/\/)([^\s/:@]{1,255}):([^\s/@]+)@(\[[^\]\s]{1,255}\]|[^\s/:?#'"]{1,255})/gi;
55
56
  const LOCAL_HOST =
56
57
  /^(?:localhost|127(?:\.\d{1,3}){3}|0\.0\.0\.0|\[::1\]|::1|[\w.-]+\.(?:local|localhost|test|example|invalid))$/i;
57
58
  const PLACEHOLDERS = new Set([
@@ -0,0 +1,407 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * autopilot-loop.mjs - run one task as a bounded series of autopilot runs,
4
+ * for mechanical batch work that takes more than one pass.
5
+ *
6
+ * Each iteration is one whole `/multi-agent <task> autopilot` run, so every
7
+ * gate the pipeline has runs every time. What happens between iterations is
8
+ * decided here, from files, never from what a model wrote:
9
+ *
10
+ * judged the iteration's own agent-state.json must show a complete run
11
+ * (lib/run-completion.mjs completionGaps is empty) with at least
12
+ * one gate recorded and the latest verdict of every gate passing.
13
+ * Anything else stops the loop: gates-failed, gates-missing,
14
+ * incomplete, no-state.
15
+ * complete only after a judged iteration, and only when `--until "<cmd>"`
16
+ * exits 0, run here. The loop then writes complete.json itself,
17
+ * carrying a nonce kept in its own state, and `status` trusts a
18
+ * marker only with that nonce. There is no phrase a model can
19
+ * print to end it.
20
+ * no-progress two iterations in a row that delivered nothing (no commit
21
+ * and no pull request) end the loop.
22
+ *
23
+ * Hard caps, checked before every iteration: the iteration count (required,
24
+ * at most 25), wall time (default 120 minutes, at most 720; each launch is
25
+ * given only the time left) and cost (default $20, at most $200). The cost
26
+ * cap is checked against the spend so far plus the last iteration's cost, so
27
+ * an iteration that cannot be paid for is not started. An iteration whose
28
+ * cost cannot be measured stops the loop: a cap that cannot be checked is not
29
+ * a cap. A STOP file in the loop directory stops it before the next iteration.
30
+ *
31
+ * Every iteration is launched the way autopilot-runner launches an item, by
32
+ * the runner's own launch(), launchArgv() and launchEnv(): no permission
33
+ * prompts, the run's own launch settings file, MULTI_AGENT_UNATTENDED=1, the
34
+ * strict toolkit URL policy and index deny list, the unattended LOGS_ROOT,
35
+ * the checkout's HEAD as MA_RUN_BASE_SHA and the run's own Gradle home, with
36
+ * the sandbox precondition judging that exact argv and environment. Before
37
+ * the first iteration the runner's guard registration and sandbox checks run
38
+ * against the repository, and a failing one refuses the start. A launch the
39
+ * precondition refuses later stops the loop (launch-refused).
40
+ *
41
+ * The loop directory is ~/.claude/state/autopilot-loops/<id>/: state.json,
42
+ * written after every iteration, complete.json and STOP.
43
+ *
44
+ * Usage:
45
+ * autopilot-loop.mjs start --task <ref> --repo <dir> --max-iterations N
46
+ * [--max-minutes M] [--max-usd U] [--until "<cmd>"]
47
+ * [--dry-run] [--json]
48
+ * autopilot-loop.mjs status [<id>] [--json]
49
+ * autopilot-loop.mjs stop <id>
50
+ *
51
+ * Exit: 0 started and stopped normally (any stop reason) or a status / stop
52
+ * answered; 2 usage error; 3 no such loop; 4 the unattended preconditions
53
+ * refused the start.
54
+ */
55
+
56
+ import { spawnSync } from "node:child_process";
57
+ import { randomUUID } from "node:crypto";
58
+ import { existsSync, mkdirSync, readdirSync, statSync, writeFileSync } from "node:fs";
59
+ import { homedir } from "node:os";
60
+ import { join } from "node:path";
61
+
62
+ import { ArgsError, parseArgs, unknownSubcommand } from "../lib/args.mjs";
63
+ import { exitOnHelp } from "../lib/cli-help.mjs";
64
+ import { invokedDirectly } from "../lib/invoked-directly.mjs";
65
+ import { writeJsonAtomicSync } from "../lib/json-file-lock.mjs";
66
+ import { readRegularJson } from "../lib/regular-file.mjs";
67
+ import { completionGaps, phase4Evidence } from "../lib/run-completion.mjs";
68
+ import { unattendedLogsRoot } from "../lib/pr-request-location.mjs";
69
+ import { unattendedSettingsPath } from "../lib/unattended-settings-location.mjs";
70
+ import {
71
+ endRunHome,
72
+ findRunState,
73
+ guardRegistration,
74
+ headSha,
75
+ launch as unattendedLaunch,
76
+ launchArgv,
77
+ runUsd,
78
+ sandboxPrecondition,
79
+ } from "./autopilot-runner.mjs";
80
+
81
+ exitOnHelp(import.meta.url);
82
+
83
+ export const CEILINGS = { iterations: 25, minutes: 720, usd: 200 };
84
+ const DEFAULT_MINUTES = 120;
85
+ const DEFAULT_USD = 20;
86
+ const EMPTY_STREAK = 2;
87
+ const PASSING = new Set(["pass", "not-applicable"]);
88
+
89
+ const usage = (message) => new ArgsError(message, { kind: "unexpected", token: "start" });
90
+
91
+ /**
92
+ * The loop's caps from what was asked, each held under its ceiling.
93
+ *
94
+ * @param {{task?: string, maxIterations?: number, maxMinutes?: number, maxUsd?: number, until?: string|null}} ask
95
+ */
96
+ export function resolveCaps(ask) {
97
+ if (!ask.task) throw usage("start needs --task");
98
+ const n = Number(ask.maxIterations);
99
+ if (!Number.isInteger(n) || n < 1)
100
+ throw usage("start needs --max-iterations, a whole number of at least 1");
101
+ const minutes = ask.maxMinutes === undefined ? DEFAULT_MINUTES : Number(ask.maxMinutes);
102
+ const usd = ask.maxUsd === undefined ? DEFAULT_USD : Number(ask.maxUsd);
103
+ if (n > CEILINGS.iterations) throw usage(`--max-iterations is at most ${CEILINGS.iterations}`);
104
+ if (!(minutes > 0) || minutes > CEILINGS.minutes)
105
+ throw usage(`--max-minutes is above 0 and at most ${CEILINGS.minutes}`);
106
+ if (!(usd > 0) || usd > CEILINGS.usd)
107
+ throw usage(`--max-usd is above 0 and at most ${CEILINGS.usd}`);
108
+ if (ask.until !== undefined && ask.until !== null && !String(ask.until).trim())
109
+ throw usage("--until needs a command");
110
+ return {
111
+ task: ask.task,
112
+ maxIterations: n,
113
+ maxMinutes: minutes,
114
+ maxUsd: usd,
115
+ until: ask.until ?? null,
116
+ };
117
+ }
118
+
119
+ /**
120
+ * Whether one iteration's run may count: complete, gated, every gate passing.
121
+ *
122
+ * @param {object|null} state the run's agent-state.json
123
+ */
124
+ export function judgeIteration(state) {
125
+ if (!state || typeof state !== "object") return { ok: false, reason: "no-state" };
126
+ const latest = new Map();
127
+ for (const g of Array.isArray(state.gates) ? state.gates : []) {
128
+ if (!g || typeof g.gate !== "string") continue;
129
+ const prev = latest.get(g.gate);
130
+ if (!prev || (Date.parse(g.at) || 0) >= (Date.parse(prev.at) || 0)) latest.set(g.gate, g);
131
+ }
132
+ const total = latest.size;
133
+ const passed = [...latest.values()].filter((g) => PASSING.has(g.verdict)).length;
134
+ if (!total) return { ok: false, reason: "gates-missing", gates: { passed, total } };
135
+ if (passed < total) return { ok: false, reason: "gates-failed", gates: { passed, total } };
136
+ if (completionGaps(state).length)
137
+ return { ok: false, reason: "incomplete", gates: { passed, total } };
138
+ const p4 = state.phases?.["4"];
139
+ const decidedNothing = p4?.status === "skipped";
140
+ return {
141
+ ok: true,
142
+ delivered: phase4Evidence(state) && !decidedNothing,
143
+ gates: { passed, total },
144
+ };
145
+ }
146
+
147
+ /**
148
+ * The loop itself, with every effect injected.
149
+ *
150
+ * @param {ReturnType<typeof resolveCaps>} caps
151
+ * @param {{now: () => number, launch: Function, inspect: Function, measure: Function,
152
+ * check: Function, stopRequested: () => boolean, save: Function, writeMarker: Function,
153
+ * id?: string}} deps
154
+ */
155
+ export function runLoop(caps, deps) {
156
+ const startedAt = deps.now();
157
+ const s = {
158
+ id: deps.id ?? randomUUID(),
159
+ nonce: randomUUID(),
160
+ task: caps.task,
161
+ caps,
162
+ startedAt: new Date(startedAt).toISOString(),
163
+ status: "running",
164
+ iterations: [],
165
+ spentUsd: 0,
166
+ completed: false,
167
+ stopReason: null,
168
+ };
169
+ const stop = (reason) => {
170
+ s.status = reason === "complete" ? "complete" : "stopped";
171
+ s.stopReason = reason;
172
+ s.stoppedAt = new Date(deps.now()).toISOString();
173
+ deps.save(s);
174
+ return s;
175
+ };
176
+ const maxMs = caps.maxMinutes * 60_000;
177
+ let empty = 0;
178
+ for (let i = 1; ; i++) {
179
+ if (deps.stopRequested()) return stop("stop-requested");
180
+ if (i > caps.maxIterations) return stop("cap-iterations");
181
+ const remainingMs = maxMs - (deps.now() - startedAt);
182
+ if (remainingMs <= 0) return stop("cap-time");
183
+ const last = s.iterations.at(-1);
184
+ if (s.spentUsd >= caps.maxUsd || (last && s.spentUsd + last.usd > caps.maxUsd))
185
+ return stop("cap-cost");
186
+
187
+ const run = deps.launch({ iteration: i, remainingMs });
188
+ if (run.blocked) {
189
+ s.refusal = run.blocked;
190
+ return stop("launch-refused");
191
+ }
192
+ const found = deps.inspect(run);
193
+ const verdict = judgeIteration(found?.state ?? null);
194
+ const usd = found ? deps.measure(found) : null;
195
+ const row = {
196
+ iteration: i,
197
+ sessionId: run.sessionId,
198
+ taskId: found?.state?.taskId ?? null,
199
+ usd,
200
+ gates: verdict.gates ?? null,
201
+ delivered: verdict.delivered ?? false,
202
+ verdict: verdict.ok ? "pass" : verdict.reason,
203
+ at: new Date(deps.now()).toISOString(),
204
+ };
205
+ s.iterations.push(row);
206
+ if (Number.isFinite(usd)) s.spentUsd = Number((s.spentUsd + usd).toFixed(4));
207
+ deps.save(s);
208
+ if (run.timedOut) return stop("cap-time");
209
+ if (!verdict.ok) return stop(verdict.reason);
210
+ if (!Number.isFinite(usd)) return stop("cost-unmeasured");
211
+ if (caps.until) {
212
+ const r = deps.check(caps.until);
213
+ row.until = r.code;
214
+ if (r.ok) {
215
+ s.completed = true;
216
+ deps.writeMarker({
217
+ loopId: s.id,
218
+ nonce: s.nonce,
219
+ iteration: i,
220
+ until: caps.until,
221
+ completedAt: new Date(deps.now()).toISOString(),
222
+ });
223
+ return stop("complete");
224
+ }
225
+ }
226
+ empty = row.delivered ? 0 : empty + 1;
227
+ if (empty >= EMPTY_STREAK) return stop("no-progress");
228
+ }
229
+ }
230
+
231
+ /** One iteration: the runner's unattended launch of the task, in print mode, waited for. */
232
+ export function iterationArgv(task, sessionId, settingsFile = unattendedSettingsPath()) {
233
+ return launchArgv({ ref: task }, sessionId, settingsFile, { print: true });
234
+ }
235
+
236
+ /**
237
+ * The runner's tick-level checks, against the repository the loop works in:
238
+ * agent-guard registered with the unattended permission profile installed,
239
+ * and the profile's OS sandbox in force and not widened by the checkout.
240
+ *
241
+ * @returns {{ok: boolean, reason?: string}}
242
+ */
243
+ export function startPreconditions(repo, env = process.env) {
244
+ const guard = guardRegistration({ cwd: repo, env });
245
+ if (!guard.ok) return { ok: false, reason: guard.reason };
246
+ const sandbox = sandboxPrecondition({ cwd: repo });
247
+ if (!sandbox.ok) return { ok: false, reason: sandbox.reason };
248
+ return { ok: true };
249
+ }
250
+
251
+ // --- CLI ---------------------------------------------------------------------
252
+
253
+ const loopsDir = (env = process.env) =>
254
+ join(env.HOME || homedir(), ".claude", "state", "autopilot-loops");
255
+
256
+ function realDeps(caps, repo, dir, id) {
257
+ // Each run writes its state under the unattended LOGS_ROOT (launchEnv), so
258
+ // that is where findRunState has to look. An operator's own LOGS_ROOT is kept.
259
+ if (!process.env.LOGS_ROOT) process.env.LOGS_ROOT = unattendedLogsRoot();
260
+ return {
261
+ id,
262
+ now: Date.now,
263
+ launch: ({ remainingMs }) => {
264
+ const sessionId = randomUUID();
265
+ const r = unattendedLaunch(
266
+ (settingsFile) => iterationArgv(caps.task, sessionId, settingsFile),
267
+ repo,
268
+ sessionId,
269
+ headSha(repo),
270
+ { timeoutMs: remainingMs, stdio: "ignore" },
271
+ );
272
+ if (r.blocked) return { sessionId, blocked: r.blocked };
273
+ const timedOut = r.error?.code === "ETIMEDOUT" || r.signal === "SIGTERM";
274
+ if (r.status === 0 || timedOut) endRunHome(r.gradleHome, { reason: "finished" });
275
+ return { sessionId, timedOut };
276
+ },
277
+ inspect: ({ sessionId }) => {
278
+ const found = findRunState({ sessionId });
279
+ return found ? { ...found, state: readRegularJson(found.statePath, null) } : null;
280
+ },
281
+ measure: (found) => runUsd(found.runTaskId, found.statePath),
282
+ check: (cmd) => {
283
+ const r = spawnSync("/bin/sh", ["-c", cmd], {
284
+ cwd: repo,
285
+ stdio: "ignore",
286
+ timeout: 10 * 60_000,
287
+ });
288
+ return { ok: r.status === 0, code: r.status };
289
+ },
290
+ stopRequested: () => existsSync(join(dir, "STOP")),
291
+ save: (s) => writeJsonAtomicSync(join(dir, "state.json"), s),
292
+ writeMarker: (m) => writeJsonAtomicSync(join(dir, "complete.json"), m),
293
+ };
294
+ }
295
+
296
+ function statusOf(dir) {
297
+ const s = readRegularJson(join(dir, "state.json"), null);
298
+ if (!s) return null;
299
+ const marker = readRegularJson(join(dir, "complete.json"), null);
300
+ const markerOk = Boolean(marker && marker.nonce === s.nonce);
301
+ return {
302
+ id: s.id,
303
+ task: s.task,
304
+ status: s.status,
305
+ stopReason: s.stopReason,
306
+ iterations: s.iterations?.length ?? 0,
307
+ spentUsd: s.spentUsd ?? null,
308
+ caps: s.caps ?? null,
309
+ complete: Boolean(s.completed && markerOk),
310
+ note:
311
+ marker && !markerOk
312
+ ? "complete.json is present but not written by this loop; ignored"
313
+ : s.completed && !markerOk
314
+ ? "the loop recorded completion but its marker is missing"
315
+ : null,
316
+ };
317
+ }
318
+
319
+ function latestLoop(env) {
320
+ const root = loopsDir(env);
321
+ let best = null;
322
+ for (const e of existsSync(root) ? readdirSync(root, { withFileTypes: true }) : []) {
323
+ if (!e.isDirectory()) continue;
324
+ const m = statSync(join(root, e.name)).mtimeMs;
325
+ if (!best || m > best.m) best = { id: e.name, m };
326
+ }
327
+ return best?.id ?? null;
328
+ }
329
+
330
+ const SUBCOMMANDS = ["start", "status", "stop"];
331
+
332
+ async function main(argv, env) {
333
+ const [sub, ...rest] = argv;
334
+ if (!SUBCOMMANDS.includes(sub)) throw unknownSubcommand(sub ?? "", SUBCOMMANDS);
335
+ const { flags, positionals } = parseArgs(rest, {
336
+ unknown: "error",
337
+ booleans: ["json", "dry-run"],
338
+ strings: ["task", "repo", "max-iterations", "max-minutes", "max-usd", "until"],
339
+ });
340
+ const json = flags.json === true;
341
+ if (sub === "start") {
342
+ const caps = resolveCaps({
343
+ task: flags.task,
344
+ maxIterations: flags["max-iterations"],
345
+ maxMinutes: flags["max-minutes"],
346
+ maxUsd: flags["max-usd"],
347
+ until: flags.until,
348
+ });
349
+ const repo = flags.repo || process.cwd();
350
+ if (!existsSync(repo)) throw usage(`--repo ${repo} does not exist`);
351
+ if (flags["dry-run"]) {
352
+ const plan = { caps, repo, argv: iterationArgv(caps.task, "<session-id>"), launched: false };
353
+ return {
354
+ code: 0,
355
+ text: json ? `${JSON.stringify(plan, null, 2)}\n` : `${JSON.stringify(plan)}\n`,
356
+ };
357
+ }
358
+ const pre = startPreconditions(repo, env);
359
+ if (!pre.ok)
360
+ return {
361
+ code: 4,
362
+ text: "",
363
+ err: `autopilot-loop: not starting: ${pre.reason} (see features/unattended-security.md)\n`,
364
+ };
365
+ const id = randomUUID();
366
+ const dir = join(loopsDir(env), id);
367
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
368
+ process.stdout.write(`loop ${id}\n`);
369
+ const s = runLoop(caps, realDeps(caps, repo, dir, id));
370
+ const st = statusOf(dir);
371
+ return {
372
+ code: 0,
373
+ text: json
374
+ ? `${JSON.stringify(st, null, 2)}\n`
375
+ : `${s.status}: ${s.stopReason} after ${s.iterations.length} iteration(s), $${s.spentUsd}\n`,
376
+ };
377
+ }
378
+ const id = positionals[0] || (sub === "status" ? latestLoop(env) : null);
379
+ if (!id || !/^[A-Za-z0-9-]+$/.test(id)) throw usage(`${sub} needs a loop id`);
380
+ const dir = join(loopsDir(env), id);
381
+ if (!existsSync(join(dir, "state.json")))
382
+ return { code: 3, text: "", err: `autopilot-loop: no loop ${id}\n` };
383
+ if (sub === "stop") {
384
+ writeFileSync(join(dir, "STOP"), `${new Date().toISOString()}\n`);
385
+ return { code: 0, text: `loop ${id} stops before its next iteration\n` };
386
+ }
387
+ const st = statusOf(dir);
388
+ return {
389
+ code: 0,
390
+ text: json
391
+ ? `${JSON.stringify(st, null, 2)}\n`
392
+ : `${st.id} ${st.status}${st.stopReason ? ` (${st.stopReason})` : ""}: ${st.iterations} iteration(s), $${st.spentUsd}${st.complete ? ", complete" : ""}${st.note ? `\n ${st.note}` : ""}\n`,
393
+ };
394
+ }
395
+
396
+ if (invokedDirectly(import.meta.url)) {
397
+ try {
398
+ const { code, text, err } = await main(process.argv.slice(2), process.env);
399
+ process.stdout.write(text);
400
+ if (err) process.stderr.write(err);
401
+ process.exitCode = code;
402
+ } catch (e) {
403
+ if (!(e instanceof ArgsError)) throw e;
404
+ process.stderr.write(`autopilot-loop: ${e.message}\n`);
405
+ process.exitCode = 2;
406
+ }
407
+ }