@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mmerterden/multi-agent-pipeline",
3
- "version": "20.40.0",
3
+ "version": "20.42.0",
4
4
  "description": "6-phase AI development pipeline with full orchestration on Claude Code, Copilot CLI and Codex CLI. Analysis, planning, TDD, CLI-aware parallel review with consensus surfacing + Fable triage, default-FAIL evidence gates, secret + intent guards, per-phase cost ledger, persistent learnings memory, wiki generation, commit automation. Token-preserving uninstall.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -20,7 +20,7 @@
20
20
  },
21
21
  "scripts": {
22
22
  "start": "node index.js",
23
- "test": "npm run format:check && npm run lint && node --test test/*.test.mjs && node --test test/*.serial.mjs && node pipeline/scripts/run-smokes.mjs && node pipeline/scripts/lint-skills.mjs && node pipeline/scripts/gen-skills-index.mjs --check && node pipeline/scripts/build-skills-index.mjs --check && node pipeline/scripts/gen-free-llm-skill.mjs --check && node pipeline/scripts/gen-secret-patterns.mjs --check && node pipeline/scripts/gen-free-hosts.mjs --check && node pipeline/scripts/sync-skill-copies.mjs --check && node pipeline/scripts/gen-toolkit-path-params.mjs --check && node pipeline/scripts/gen-fact-marks.mjs --check && node pipeline/scripts/lint-personas.mjs && node pipeline/scripts/lint-mcp-refs.mjs && node pipeline/scripts/eval-triage.mjs && node pipeline/scripts/eval-golden-tasks.mjs && node pipeline/scripts/eval-intent.mjs && node pipeline/scripts/eval-recall.mjs && node pipeline/scripts/eval-guard-robustness.mjs && node pipeline/scripts/validate-schemas.mjs && node pipeline/scripts/validate-prefs.mjs && node pipeline/scripts/scorecard.mjs",
23
+ "test": "npm run format:check && npm run lint && node --test test/*.test.mjs && node --test test/*.serial.mjs && node pipeline/scripts/run-smokes.mjs && node pipeline/scripts/lint-skills.mjs && node pipeline/scripts/gen-skills-index.mjs --check && node pipeline/scripts/build-skills-index.mjs --check && node pipeline/scripts/gen-free-llm-skill.mjs --check && node pipeline/scripts/gen-secret-patterns.mjs --check && node pipeline/scripts/gen-free-hosts.mjs --check && node pipeline/scripts/sync-skill-copies.mjs --check && node pipeline/scripts/gen-toolkit-path-params.mjs --check && node pipeline/scripts/gen-fact-marks.mjs --check && node pipeline/scripts/lint-personas.mjs && node pipeline/scripts/lint-mcp-refs.mjs && node pipeline/scripts/eval-triage.mjs && node pipeline/scripts/eval-golden-tasks.mjs && node pipeline/scripts/eval-intent.mjs && node pipeline/scripts/eval-recall.mjs && node pipeline/scripts/eval-persona-walk.mjs && node pipeline/scripts/eval-guard-robustness.mjs --fast && node pipeline/scripts/validate-schemas.mjs && node pipeline/scripts/validate-prefs.mjs && node pipeline/scripts/scorecard.mjs",
24
24
  "test:unit": "node --test test/*.test.mjs && node --test test/*.serial.mjs",
25
25
  "test:smoke": "node pipeline/scripts/run-smokes.mjs",
26
26
  "lint:skills": "node pipeline/scripts/lint-skills.mjs",
@@ -31,6 +31,7 @@
31
31
  "format": "prettier --write \"**/*.{js,mjs,json,yml}\" --ignore-path .gitignore --ignore-path .prettierignore",
32
32
  "format:check": "prettier --check \"**/*.{js,mjs,json,yml}\" --ignore-path .gitignore --ignore-path .prettierignore",
33
33
  "audit:refs": "node pipeline/scripts/ref-filler-audit.mjs",
34
+ "eval:guards": "node pipeline/scripts/eval-guard-robustness.mjs",
34
35
  "scorecard": "node pipeline/scripts/scorecard.mjs",
35
36
  "prepack": "node pipeline/contract/build.mjs --write && node pipeline/scripts/make-manifest.mjs",
36
37
  "gate": "bash pipeline/scripts/pre-push-check.sh --run"
@@ -55,6 +55,17 @@ Run the task end-to-end with no confirmations.
55
55
  /multi-agent:autopilot resume #3
56
56
  ```
57
57
 
58
+ ## Loop mode (`--loop N`)
59
+
60
+ For mechanical batch work that takes several passes, `--loop N` does not run the task here. Start the bounded loop in the background and report its id:
61
+
62
+ ```bash
63
+ node "$HOME/.claude/scripts/autopilot-loop.mjs" start --task "<task>" --repo "$PWD" \
64
+ --max-iterations N [--max-minutes M] [--max-usd U] [--until "<command that exits 0 when done>"]
65
+ ```
66
+
67
+ Each iteration is one full autopilot run with every gate, launched unattended exactly as the queue runner launches an item (`install --unattended` must have run: without agent-guard registered and the sandbox profile in force the loop refuses to start, exit 4). The loop stops on a failed or missing gate, an incomplete run, two iterations that delivered nothing, a cap (iterations at most 25, minutes 120 by default, $20 by default) or `autopilot-loop.mjs stop <id>`. Only the loop declares it complete, after a gated iteration whose `--until` check exited 0; never write or claim completion yourself. Report `autopilot-loop.mjs status <id>` when asked.
68
+
58
69
  ## Steps
59
70
 
60
71
  1. **Parse input** - standard multi-agent input formats
@@ -25,7 +25,7 @@ Read `$HOME/.claude/multi-agent-refs/analysis/review.md` and execute it:
25
25
 
26
26
  1. **Resolve** the document from a local path, a Confluence URL or `pageId`, or a Jira key. With no argument, offer the recent analyses from `~/Desktop/multiAgentAnalysis/` and from each selected repo's `analysis/`, newest first.
27
27
  2. **Deterministic gates first**: `validate-analysis-doc.mjs` on the document, and `build-references.mjs --check` when the run's state JSON is available (`--state`, or a fresh analysis). Their output is reported verbatim, before any model reads the document. A finding a script already proves does not need an opinion.
28
- 3. **Parallel model review** against the rubric (buildability, evidence, spine, altitude, admitted gaps, contradiction), CLI-aware: 3 models on Claude Code, 3 on Copilot CLI.
28
+ 3. **Parallel model review** against the rubric (buildability, evidence, spine, altitude, admitted gaps, contradiction), CLI-aware: 3 models on Claude Code, 3 on Copilot CLI. With `review.personaWalk.enabled` (off by default), a persona walk runs beside them, and `persona-walk-anchors.mjs` drops every finding whose anchor is not in the document.
29
29
  4. **Triage** into Blocker / Important / Suggestion, dropping duplicates and anything the document answers elsewhere, on `$(bash "$HOME/.claude/lib/model-dispatch.sh" subagent --persona triage --default fable)`: Fable while the rung is on, Opus while it is off (this command has no Phase 0 to resolve it).
30
30
  5. **Report**, naming the profile it judged against and, explicitly, what was NOT checked.
31
31
  6. **Output** on request only: chat (default), Confluence comment, Jira comment, or a `-review.md` beside the document.
@@ -91,7 +91,7 @@ From scratch: `npx @{npm-scope}/multi-agent-pipeline install`, `/multi-agent set
91
91
 
92
92
  ### Step 8 - Enforcement hooks (optional)
93
93
 
94
- Claude Code: offer (picker, default Yes) to merge `$HOME/.claude/templates/claude-hooks.json` into `~/.claude/settings.json`; deep-merge EVERY event, never duplicate a matcher. Read `$HOME/.claude/multi-agent-refs/setup/hooks-and-plugins.md` before Step 8. Codex: only the syntax gate, via `node "$HOME/.codex/scripts/host-hooks.mjs" install --host codex`. Copilot CLI: no hook.
94
+ Claude Code: offer (picker, default Yes) to merge `$HOME/.claude/templates/claude-hooks.json` into `~/.claude/settings.json`; deep-merge EVERY event, never duplicate a matcher. First run `node "$HOME/.claude/lib/risky-settings.mjs" --json`; for each HIGH finding (bypass with a broad allow, a hook that runs fetched code, a literal secret) ask Keep / Fix it myself, naming the rule and place, never the value. Never edit the setting for the user; under autopilot only report. Read `$HOME/.claude/multi-agent-refs/setup/hooks-and-plugins.md` before Step 8. Codex: only the syntax gate, via `node "$HOME/.codex/scripts/host-hooks.mjs" install --host codex`. Copilot CLI: no hook.
95
95
 
96
96
  ### Step 9 - Default stack plugin enablement
97
97
 
@@ -1183,58 +1183,13 @@ export type OfficeServerRoomStatus = "green" | "yellow" | "red";
1183
1183
 
1184
1184
  export type OfficeServerRoomCount = number;
1185
1185
 
1186
- /** What GET /v1/archive returns and `office-archive.mjs --json` prints: per repository, the newest decisions with their rationale, security notes and learnings from the learnings ledger (entries their feedback retired, and entries a later entry superseded, are left out and counted apart), and the hubs, clusters, surprising connections and questions of the code graph report when one exists. Every text is redacted and cut short. Local only: never offered to a phone or a remote carrier. */
1186
+ /** What GET /v1/archive returns and `office-archive.mjs --json` prints: per repository, the newest decisions with their rationale, security notes and learnings from the learnings ledger (entries their feedback retired, and entries a later entry superseded, are left out and counted apart), and the hubs, clusters, surprising connections and questions of the code graph report when one exists. Learnings promoted across repositories sit apart under `global`. Every text is redacted and cut short. Local only: never offered to a phone or a remote carrier. */
1187
1187
  export interface OfficeArchive {
1188
1188
  contractVersion: string;
1189
1189
  generatedAt: string;
1190
- repos: Array<{
1191
- repo: string;
1192
- counts: {
1193
- decisions: OfficeArchiveCount;
1194
- securityNotes: OfficeArchiveCount;
1195
- learnings: OfficeArchiveCount;
1196
- /** Entries left out because their feedback retired them. */
1197
- retired: OfficeArchiveCount;
1198
- /** Entries left out because a later entry names them in its supersedes list. An entry both retired and superseded counts as retired. */
1199
- superseded: OfficeArchiveCount;
1200
- };
1201
- decisions: Array<{
1202
- statement: OfficeArchiveText;
1203
- scope: OfficeArchiveScope;
1204
- at: OfficeArchiveAt;
1205
- rationale: string | null;
1206
- confidence: "low" | "medium" | "high" | null;
1207
- }>;
1208
- securityNotes: Array<OfficeArchiveEntry>;
1209
- learnings: Array<{
1210
- kind: "fact" | "convention" | "rejected-preference";
1211
- statement: OfficeArchiveText;
1212
- scope: OfficeArchiveScope;
1213
- at: OfficeArchiveAt;
1214
- }>;
1215
- graph: null | {
1216
- builtAt: OfficeArchiveAt;
1217
- hubs: Array<{
1218
- name: OfficeArchiveCell;
1219
- kind: OfficeArchiveCell;
1220
- degree: number;
1221
- path: OfficeArchiveCell;
1222
- }>;
1223
- clusters: Array<{
1224
- files: number;
1225
- cohesion: number;
1226
- around: OfficeArchiveCell;
1227
- where: OfficeArchiveCell;
1228
- }>;
1229
- surprising: Array<{
1230
- from: OfficeArchiveCell;
1231
- to: OfficeArchiveCell;
1232
- kind: OfficeArchiveCell;
1233
- links: number;
1234
- }>;
1235
- questions: Array<OfficeArchiveCell>;
1236
- };
1237
- }>;
1190
+ repos: Array<OfficeArchiveShelf>;
1191
+ /** The global ledger (written only by learnings-ledger.mjs promote --accept) on a shelf of its own, in the same shape as a repository's with `repo` set to `_global` and `graph` null; null until a learning has been promoted. Never listed in `repos`. */
1192
+ global?: null | OfficeArchiveShelf;
1238
1193
  }
1239
1194
 
1240
1195
  export type OfficeArchiveCount = number;
@@ -1253,6 +1208,55 @@ export interface OfficeArchiveEntry {
1253
1208
  at: OfficeArchiveAt;
1254
1209
  }
1255
1210
 
1211
+ export interface OfficeArchiveShelf {
1212
+ repo: string;
1213
+ counts: {
1214
+ decisions: OfficeArchiveCount;
1215
+ securityNotes: OfficeArchiveCount;
1216
+ learnings: OfficeArchiveCount;
1217
+ /** Entries left out because their feedback retired them. */
1218
+ retired: OfficeArchiveCount;
1219
+ /** Entries left out because a later entry names them in its supersedes list. An entry both retired and superseded counts as retired. */
1220
+ superseded: OfficeArchiveCount;
1221
+ };
1222
+ decisions: Array<{
1223
+ statement: OfficeArchiveText;
1224
+ scope: OfficeArchiveScope;
1225
+ at: OfficeArchiveAt;
1226
+ rationale: string | null;
1227
+ confidence: "low" | "medium" | "high" | null;
1228
+ }>;
1229
+ securityNotes: Array<OfficeArchiveEntry>;
1230
+ learnings: Array<{
1231
+ kind: "fact" | "convention" | "rejected-preference";
1232
+ statement: OfficeArchiveText;
1233
+ scope: OfficeArchiveScope;
1234
+ at: OfficeArchiveAt;
1235
+ }>;
1236
+ graph: null | {
1237
+ builtAt: OfficeArchiveAt;
1238
+ hubs: Array<{
1239
+ name: OfficeArchiveCell;
1240
+ kind: OfficeArchiveCell;
1241
+ degree: number;
1242
+ path: OfficeArchiveCell;
1243
+ }>;
1244
+ clusters: Array<{
1245
+ files: number;
1246
+ cohesion: number;
1247
+ around: OfficeArchiveCell;
1248
+ where: OfficeArchiveCell;
1249
+ }>;
1250
+ surprising: Array<{
1251
+ from: OfficeArchiveCell;
1252
+ to: OfficeArchiveCell;
1253
+ kind: OfficeArchiveCell;
1254
+ links: number;
1255
+ }>;
1256
+ questions: Array<OfficeArchiveCell>;
1257
+ };
1258
+ }
1259
+
1256
1260
  /** What POST /v1/prune-logs returns. The preview (body {olderThanDays}) is prune-logs.sh's dry run for that age with a confirm token; the confirmation (body {confirmToken}) runs it again with the same age and --yes. The audit trail, the metrics corpus and task counters are never removed, and a folder written in the last minutes is spared. */
1257
1261
  export interface PruneLogs {
1258
1262
  contractVersion: string;
@@ -25,13 +25,19 @@
25
25
  * or a positional, at its place in argv: an error it throws for one argument
26
26
  * comes before any error a later argument would raise.
27
27
  *
28
+ * An "unknown" error names the nearest declared flag when one is close
29
+ * (`suggestions`, and a hint in the message in the output language), and
30
+ * `unknownSubcommand` builds the matching error for a script's subcommand.
31
+ *
28
32
  * @module pipeline/lib/args
29
33
  */
30
34
 
35
+ import { messages } from "./user-facing.mjs";
36
+
31
37
  export class ArgsError extends Error {
32
38
  /**
33
39
  * @param {string} message
34
- * @param {{kind: "missing-value"|"unknown"|"unexpected"|"duplicate"|"exclusive", token: string, flag?: string|null}} detail
40
+ * @param {{kind: "missing-value"|"unknown"|"unknown-subcommand"|"unexpected"|"duplicate"|"exclusive", token: string, flag?: string|null}} detail
35
41
  */
36
42
  constructor(message, { kind, token, flag = null }) {
37
43
  super(message);
@@ -39,6 +45,7 @@ export class ArgsError extends Error {
39
45
  this.kind = kind;
40
46
  this.token = token;
41
47
  this.flag = flag;
48
+ this.suggestions = [];
42
49
  }
43
50
  }
44
51
 
@@ -53,10 +60,129 @@ function put(flags, key, value, many) {
53
60
  });
54
61
  }
55
62
 
63
+ /**
64
+ * Optimal string alignment distance: insertions, deletions, substitutions and
65
+ * a swap of two adjacent characters each cost one, so the commonest typo
66
+ * (`--josn`) is one edit away rather than two.
67
+ *
68
+ * @param {string} a
69
+ * @param {string} b
70
+ * @returns {number}
71
+ */
72
+ export function editDistance(a, b) {
73
+ const s = String(a);
74
+ const t = String(b);
75
+ const d = Array.from({ length: s.length + 1 }, (_, i) => [i, ...new Array(t.length).fill(0)]);
76
+ for (let j = 1; j <= t.length; j++) d[0][j] = j;
77
+ for (let i = 1; i <= s.length; i++) {
78
+ for (let j = 1; j <= t.length; j++) {
79
+ const cost = s[i - 1] === t[j - 1] ? 0 : 1;
80
+ d[i][j] = Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1, d[i - 1][j - 1] + cost);
81
+ if (i > 1 && j > 1 && s[i - 1] === t[j - 2] && s[i - 2] === t[j - 1]) {
82
+ d[i][j] = Math.min(d[i][j], d[i - 2][j - 2] + 1);
83
+ }
84
+ }
85
+ }
86
+ return d[s.length][t.length];
87
+ }
88
+
89
+ /**
90
+ * The candidates a mistyped word most likely meant: those at the smallest
91
+ * edit distance, when that distance is within reach of the word's length
92
+ * (one edit up to three characters, two beyond), else the single candidate
93
+ * the word is a prefix of. Case is ignored and an exact match is no
94
+ * suggestion. A threshold that grew with length would start proposing
95
+ * unrelated words of similar size, which is worse than proposing nothing.
96
+ *
97
+ * @param {string} input
98
+ * @param {Iterable<string>} candidates
99
+ * @returns {string[]} sorted, possibly empty
100
+ */
101
+ export function suggest(input, candidates) {
102
+ const word = String(input ?? "").toLowerCase();
103
+ if (!word) return [];
104
+ const pool = [...new Set(Array.from(candidates ?? [], String))].filter(
105
+ (c) => c && c.toLowerCase() !== word,
106
+ );
107
+ const reach = word.length <= 3 ? 1 : 2;
108
+ let best = Infinity;
109
+ let near = [];
110
+ for (const c of pool) {
111
+ const dist = editDistance(word, c.toLowerCase());
112
+ if (dist > reach || dist > best) continue;
113
+ if (dist < best) {
114
+ best = dist;
115
+ near = [];
116
+ }
117
+ near.push(c);
118
+ }
119
+ if (near.length) return near.sort();
120
+ if (word.length < 3) return [];
121
+ const prefixed = pool.filter((c) => c.toLowerCase().startsWith(word));
122
+ return prefixed.length === 1 ? prefixed : [];
123
+ }
124
+
125
+ const HINT = {
126
+ en: {
127
+ meant: (names) => `did you mean ${names}?`,
128
+ known: (names) => `known: ${names}`,
129
+ or: " or ",
130
+ },
131
+ tr: {
132
+ meant: (names) => `${names} mi demek istediniz?`,
133
+ known: (names) => `bilinenler: ${names}`,
134
+ or: " ya da ",
135
+ },
136
+ };
137
+
138
+ /**
139
+ * " (did you mean --json?)" for a mistyped word, in the output language, or
140
+ * "" when no candidate is close. `prefix` is put in front of every name, so a
141
+ * flag reads as it is typed.
142
+ *
143
+ * @param {string} input
144
+ * @param {Iterable<string>} candidates
145
+ * @param {{prefix?: string}} [opts]
146
+ * @returns {string}
147
+ */
148
+ export function didYouMean(input, candidates, { prefix = "" } = {}) {
149
+ const names = suggest(input, candidates);
150
+ if (!names.length) return "";
151
+ const say = messages(HINT);
152
+ return ` (${say.meant(names.map((n) => `${prefix}${n}`).join(say.or))})`;
153
+ }
154
+
155
+ /**
156
+ * The error for a subcommand a script does not have: the nearest one when a
157
+ * name is close, else the whole list, since a subcommand set is short enough
158
+ * to read.
159
+ *
160
+ * @param {string} sub
161
+ * @param {Iterable<string>} known
162
+ * @returns {ArgsError}
163
+ */
164
+ export function unknownSubcommand(sub, known) {
165
+ const list = [...known];
166
+ const hint = didYouMean(sub, list) || ` (${messages(HINT).known(list.join(", "))})`;
167
+ const token = String(sub ?? "");
168
+ return new ArgsError(`unknown subcommand ${token}${hint}`, {
169
+ kind: "unknown-subcommand",
170
+ token,
171
+ });
172
+ }
173
+
56
174
  const missing = (token, flag) =>
57
175
  new ArgsError(`${token} needs a value`, { kind: "missing-value", token, flag });
58
- const unknownFlag = (token, flag) =>
59
- new ArgsError(`unknown option ${token}`, { kind: "unknown", token, flag });
176
+ const unknownFlag = (token, flag, known) => {
177
+ const suggestions = suggest(flag, known);
178
+ const e = new ArgsError(`unknown option ${token}${didYouMean(flag, known, { prefix: "--" })}`, {
179
+ kind: "unknown",
180
+ token,
181
+ flag,
182
+ });
183
+ e.suggestions = suggestions;
184
+ return e;
185
+ };
60
186
  const duplicate = (token, flag) =>
61
187
  new ArgsError(`${token} given more than once`, { kind: "duplicate", token, flag });
62
188
  const exclusive = (token, flag, group) =>
@@ -149,7 +275,8 @@ export function parseArgs(argv, opts = {}) {
149
275
  const body = a.slice(2);
150
276
  const eq = equals ? body.indexOf("=") : -1;
151
277
  const key = eq === -1 ? body : body.slice(0, eq);
152
- if (unknown === "error" && !known(key)) throw unknownFlag(a, key);
278
+ if (unknown === "error" && !known(key))
279
+ throw unknownFlag(a, key, [...booleans, ...strings, ...values, ...multiple]);
153
280
  if (unknown === "positional" && !known(key)) {
154
281
  if (!allowPositionals) throw unexpected(a);
155
282
  positionals.push(a);
@@ -20,7 +20,9 @@ export const LAUNCH_TIMEOUT_MS = 2 * 60 * 1000;
20
20
  /**
21
21
  * @param {{argv: string[], cwd: string, env: Record<string,string|undefined>,
22
22
  * precondition?: (o: {cwd: string, argv: string[], env: Record<string,string|undefined>}) => {ok: boolean, reason?: string},
23
- * bin?: string, timeoutMs?: number}} args
23
+ * bin?: string, timeoutMs?: number, stdio?: import("node:child_process").StdioOptions}} args
24
+ * stdio: a launch that runs to its end, rather than returning once the
25
+ * session exists, passes "ignore" so its output never fills a buffer.
24
26
  * @returns {{status: number|null, stdout?: string, stderr?: string, error?: Error, blocked?: string}}
25
27
  */
26
28
  export function startBackground({
@@ -30,6 +32,7 @@ export function startBackground({
30
32
  precondition,
31
33
  bin = resolveClaudeBin(env),
32
34
  timeoutMs = LAUNCH_TIMEOUT_MS,
35
+ stdio = ["ignore", "pipe", "pipe"],
33
36
  }) {
34
37
  if (!Array.isArray(argv) || !argv.every((a) => typeof a === "string")) {
35
38
  throw new TypeError("argv is a list of strings");
@@ -42,7 +45,7 @@ export function startBackground({
42
45
  cwd,
43
46
  env,
44
47
  encoding: "utf-8",
45
- stdio: ["ignore", "pipe", "pipe"],
48
+ stdio,
46
49
  timeout: timeoutMs,
47
50
  shell: false,
48
51
  });
@@ -17,6 +17,9 @@
17
17
  * measure (text) => number, default text.length
18
18
  * returns { text, dropped: [ids in the order they were dropped] }
19
19
  *
20
+ * The function itself lives in tiered-budget.mjs, which imports nothing so
21
+ * the toolkit can vendor it; it is re-exported here for the hook callers.
22
+ *
20
23
  * When anything is dropped, one line naming how many items were left out is
21
24
  * appended, and that line is counted against the budget too.
22
25
  *
@@ -31,49 +34,9 @@
31
34
 
32
35
  import { readFileSync } from "node:fs";
33
36
  import { invokedDirectly } from "./invoked-directly.mjs";
37
+ import { HOOK_OUTPUT_LIMIT, fitToBudget, omittedNote } from "./tiered-budget.mjs";
34
38
 
35
- export const HOOK_OUTPUT_LIMIT = 10000;
36
-
37
- /** The line appended when items were dropped. */
38
- export function omittedNote(n, maxChars) {
39
- return `(${n} ${n === 1 ? "item" : "items"} left out to stay under the ${maxChars}-character hook limit)`;
40
- }
41
-
42
- /**
43
- * @param {Array<{id?: string, priority?: number}>} items
44
- * @param {{maxChars?: number, render: (items: object[]) => string, measure?: (s: string) => number}} opts
45
- * @returns {{text: string, dropped: string[]}}
46
- */
47
- export function fitToBudget(items, { maxChars = HOOK_OUTPUT_LIMIT, render, measure } = {}) {
48
- const size = measure || ((s) => s.length);
49
- const list = Array.isArray(items) ? items : [];
50
- // An item that cannot fit even alone is never kept, so it goes first and
51
- // does not take the smaller items below it down with it.
52
- const dropOrder = list
53
- .map((it, index) => ({
54
- index,
55
- priority: Number(it?.priority) || 0,
56
- oversize: size(String(render([it]) ?? "")) > maxChars,
57
- }))
58
- .sort((a, b) => b.oversize - a.oversize || a.priority - b.priority || b.index - a.index)
59
- .map((x) => x.index);
60
- const gone = new Set();
61
- const dropped = [];
62
- for (let step = 0; step <= dropOrder.length; step++) {
63
- const kept = list.filter((_, i) => !gone.has(i));
64
- const body = kept.length ? String(render(kept) ?? "") : "";
65
- const text = dropped.length
66
- ? `${body}${body ? "\n" : ""}${omittedNote(dropped.length, maxChars)}`
67
- : body;
68
- if (size(text) <= maxChars) return { text, dropped };
69
- if (step === dropOrder.length) break;
70
- const i = dropOrder[step];
71
- gone.add(i);
72
- dropped.push(String(list[i]?.id ?? i));
73
- }
74
- const note = omittedNote(dropped.length, maxChars);
75
- return { text: size(note) <= maxChars ? note : "", dropped };
76
- }
39
+ export { HOOK_OUTPUT_LIMIT, fitToBudget, omittedNote };
77
40
 
78
41
  function main() {
79
42
  const args = process.argv.slice(2);
@@ -178,10 +178,20 @@ do_set() {
178
178
  [ -z "$key" ] && { echo "usage: $0 set <key> <value|->" >&2; exit 3; }
179
179
  # Resolve through the same mapping as do_get so set/get stay symmetric.
180
180
  key=$(resolve_key "$key")
181
- # "-" means: read the secret from stdin (keeps it off argv).
181
+ # "-" or no value: read the secret from stdin (keeps it off argv); on a
182
+ # terminal the prompt is hidden and the trailing newline is dropped.
182
183
  if [ "$val" = "-" ]; then
183
184
  val=$(cat)
185
+ elif [ $# -lt 2 ]; then
186
+ if [ -t 0 ]; then
187
+ printf 'Secret for %s (input hidden): ' "$key" >&2
188
+ IFS= read -rs val || true
189
+ printf '\n' >&2
190
+ else
191
+ val=$(cat)
192
+ fi
184
193
  fi
194
+ [ -z "$val" ] && { echo "usage: $0 set <key> [<value>|-] (empty secret refused; pipe it in or type it at the prompt)" >&2; exit 3; }
185
195
  # The delegate receives the secret on stdin and hands it to `security -i` on
186
196
  # stdin as well, so no argv ever carries it, and it writes both the -l and -s
187
197
  # attributes that lookups by either convention expect.
@@ -0,0 +1,134 @@
1
+ /**
2
+ * hook-once.mjs - run a hook's side effect once per event.
3
+ *
4
+ * The same event can reach a hook twice: a plugin and the user's settings
5
+ * register the same script on one matcher, or the host delivers again after
6
+ * a timeout. A hook that appends a row or mirrors a task would then write it
7
+ * twice. Before its side effect a hook claims the event; the claim is a file
8
+ * created with O_CREAT|O_EXCL|O_NOFOLLOW (safe-write.mjs createExclusive), so
9
+ * of any number of deliveries, concurrent ones included, exactly one wins.
10
+ *
11
+ * The event key is a sha256 of the hook name, the event name and the
12
+ * payload's tool_use_id, the one identity the host gives every tool event. A
13
+ * payload without one is not claimed and its side effect runs: two identical
14
+ * payloads without an id may be two real events, and a guess that folds them
15
+ * into one drops a row that should exist. The claim file is named by the
16
+ * digest and holds nothing from the payload.
17
+ *
18
+ * Claims live in MA_HOOK_ONCE_DIR, else /tmp/multi-agent-hook-once-<uid>
19
+ * (gc-tmp.sh sweeps the multi-agent-* prefix there), else the OS temp
20
+ * directory. The directory must be a real directory owned by this user with
21
+ * no access for others; anything else, a link included, is not used. Claims
22
+ * older than the TTL (ten minutes) are pruned at most once a TTL, by the hook
23
+ * that claims next.
24
+ *
25
+ * Failing open: when the claim cannot be made for any reason but "already
26
+ * claimed", the answer is true and the side effect runs. Writing a row twice
27
+ * is the smaller harm next to never writing it.
28
+ *
29
+ * @module pipeline/lib/hook-once
30
+ */
31
+
32
+ import { createHash } from "node:crypto";
33
+ import { existsSync, lstatSync, mkdirSync, readdirSync, statSync, unlinkSync } from "node:fs";
34
+ import { tmpdir } from "node:os";
35
+ import { join } from "node:path";
36
+
37
+ import { createExclusive, writeFileSafe } from "./safe-write.mjs";
38
+
39
+ export const HOOK_ONCE_TTL_MS = 10 * 60 * 1000;
40
+ const PRUNE_MARK = ".pruned";
41
+
42
+ const sha = (s) => createHash("sha256").update(s).digest("hex");
43
+
44
+ /** Where claims are kept. */
45
+ export function claimDir(env = process.env) {
46
+ if (env.MA_HOOK_ONCE_DIR) return env.MA_HOOK_ONCE_DIR;
47
+ const uid = typeof process.getuid === "function" ? process.getuid() : "user";
48
+ const base = existsSync("/tmp") ? "/tmp" : tmpdir();
49
+ return join(base, `multi-agent-hook-once-${uid}`);
50
+ }
51
+
52
+ /**
53
+ * The key one event has for one hook, or null when the payload carries no
54
+ * tool_use_id.
55
+ *
56
+ * @param {string} hook
57
+ * @param {object} payload
58
+ */
59
+ export function eventKey(hook, payload) {
60
+ if (!payload || typeof payload !== "object") return null;
61
+ const id = payload.tool_use_id;
62
+ if (typeof id !== "string" || !id) return null;
63
+ return sha(`${hook}\0${payload.hook_event_name ?? ""}\0${id}`);
64
+ }
65
+
66
+ /**
67
+ * dir, made 0700 if missing, or null when it is not safe to use: not a plain
68
+ * directory (a link included), not owned by this user, or open to others.
69
+ * The statusline cache keeps its file in such a directory too.
70
+ */
71
+ export function privateDir(dir) {
72
+ try {
73
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
74
+ const st = lstatSync(dir);
75
+ if (!st.isDirectory() || st.isSymbolicLink()) return null;
76
+ if (typeof process.getuid === "function" && st.uid !== process.getuid()) return null;
77
+ if ((st.mode & 0o077) !== 0) return null;
78
+ return dir;
79
+ } catch {
80
+ return null;
81
+ }
82
+ }
83
+
84
+ function prune(dir, ttlMs, now) {
85
+ const mark = join(dir, PRUNE_MARK);
86
+ try {
87
+ if (existsSync(mark) && now - statSync(mark).mtimeMs < ttlMs) return;
88
+ writeFileSafe(mark, "", { anchors: [dir] });
89
+ for (const name of readdirSync(dir)) {
90
+ if (name === PRUNE_MARK) continue;
91
+ const p = join(dir, name);
92
+ const st = lstatSync(p);
93
+ if (st.isFile() && now - st.mtimeMs > ttlMs) unlinkSync(p);
94
+ }
95
+ } catch {
96
+ return;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * Claim `key`. True when this call is the first claim (run the side effect),
102
+ * false when the key was already claimed.
103
+ *
104
+ * @param {string} key
105
+ * @param {{dir?: string, ttlMs?: number, now?: number}} [opts]
106
+ */
107
+ export function claimOnce(
108
+ key,
109
+ { dir = claimDir(), ttlMs = HOOK_ONCE_TTL_MS, now = Date.now() } = {},
110
+ ) {
111
+ if (typeof key !== "string" || !/^[0-9a-z]{1,128}$/i.test(key)) return true;
112
+ const at = privateDir(dir);
113
+ if (!at) return true;
114
+ prune(at, ttlMs, now);
115
+ try {
116
+ createExclusive(join(at, key), "", { anchors: [at] });
117
+ return true;
118
+ } catch (err) {
119
+ return err?.code !== "EEXIST";
120
+ }
121
+ }
122
+
123
+ /**
124
+ * claimOnce for a hook payload: true when this delivery should run the side
125
+ * effect.
126
+ *
127
+ * @param {string} hook
128
+ * @param {object} payload
129
+ * @param {{dir?: string, ttlMs?: number, now?: number}} [opts]
130
+ */
131
+ export function claimHookEvent(hook, payload, opts = {}) {
132
+ const key = eventKey(hook, payload);
133
+ return key === null ? true : claimOnce(key, opts);
134
+ }
@@ -65,6 +65,11 @@ export const INERT_PREFS = [
65
65
  active: (v) => Array.isArray(v) && v.length > 0,
66
66
  script: "agent-guard.sh",
67
67
  },
68
+ {
69
+ pref: "guardRules",
70
+ active: (v) => Array.isArray(v) && v.length > 0,
71
+ script: "agent-guard.sh",
72
+ },
68
73
  ];
69
74
 
70
75
  function readJson(p) {