@mmerterden/multi-agent-pipeline 20.40.0 → 20.41.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 (76) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +4 -1
  3. package/README.tr.md +4 -1
  4. package/docs/adr/0019-product-tree.md +143 -0
  5. package/docs/adr/README.md +1 -0
  6. package/docs/ecosystem.md +9 -9
  7. package/docs/facts.json +4 -4
  8. package/docs/features.md +6 -0
  9. package/install/claude.mjs +12 -3
  10. package/install/templates/claude-hooks.json +12 -1
  11. package/manifest.json +79 -60
  12. package/package.json +2 -2
  13. package/pipeline/commands/multi-agent/review-analysis/SKILL.md +1 -1
  14. package/pipeline/contract/types/index.d.ts +53 -49
  15. package/pipeline/lib/context-budget.mjs +5 -42
  16. package/pipeline/lib/hook-registration.mjs +5 -0
  17. package/pipeline/lib/md2confluence-v3.py +12 -4
  18. package/pipeline/lib/tiered-budget.mjs +87 -0
  19. package/pipeline/multi-agent-refs/analysis/review.md +23 -1
  20. package/pipeline/multi-agent-refs/features/code-graph.md +11 -1
  21. package/pipeline/multi-agent-refs/features/doctor.md +32 -1
  22. package/pipeline/multi-agent-refs/features/product-tree.md +68 -0
  23. package/pipeline/multi-agent-refs/features/unattended-security.md +88 -1
  24. package/pipeline/multi-agent-refs/features/usage-reporting.md +31 -0
  25. package/pipeline/multi-agent-refs/help/en.md +1 -0
  26. package/pipeline/multi-agent-refs/help/tr.md +1 -0
  27. package/pipeline/multi-agent-refs/knowledge.md +58 -0
  28. package/pipeline/multi-agent-refs/phases/phase-0-init.md +4 -0
  29. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -0
  30. package/pipeline/multi-agent-refs/phases/phase-5-report.md +2 -0
  31. package/pipeline/office/index.html +13 -7
  32. package/pipeline/office/toolkit.json +1 -1
  33. package/pipeline/preferences-template.json +1 -0
  34. package/pipeline/schemas/learnings-ledger.schema.json +35 -2
  35. package/pipeline/schemas/office-archive.schema.json +225 -128
  36. package/pipeline/schemas/prefs.schema.json +83 -0
  37. package/pipeline/schemas/product-tree-overlay.schema.json +57 -0
  38. package/pipeline/schemas/product-tree.schema.json +136 -0
  39. package/pipeline/schemas/toolkit-path-params.json +1 -1
  40. package/pipeline/scripts/_eval-stats.mjs +182 -0
  41. package/pipeline/scripts/_guard_rules.py +130 -1
  42. package/pipeline/scripts/_learnings-promotion.mjs +229 -0
  43. package/pipeline/scripts/_locate.mjs +539 -0
  44. package/pipeline/scripts/_memory-policy.mjs +213 -14
  45. package/pipeline/scripts/_product-tree-extract.mjs +761 -0
  46. package/pipeline/scripts/_product-tree.mjs +923 -0
  47. package/pipeline/scripts/_retrieval.mjs +13 -2
  48. package/pipeline/scripts/_stack-routing.mjs +1 -0
  49. package/pipeline/scripts/_user_guard_rules.py +744 -0
  50. package/pipeline/scripts/agent-guard.py +61 -5
  51. package/pipeline/scripts/agent-guard.sh +8 -1
  52. package/pipeline/scripts/doctor.mjs +157 -1
  53. package/pipeline/scripts/graph-query.mjs +257 -17
  54. package/pipeline/scripts/learnings-ledger.mjs +664 -43
  55. package/pipeline/scripts/note-mcp-failure.mjs +356 -0
  56. package/pipeline/scripts/note-mcp-failure.sh +19 -0
  57. package/pipeline/scripts/note-skill-use.mjs +93 -23
  58. package/pipeline/scripts/office-archive.mjs +23 -10
  59. package/pipeline/scripts/office-memory.mjs +4 -1
  60. package/pipeline/scripts/persona-walk-anchors.mjs +443 -0
  61. package/pipeline/scripts/product-tree-eval.mjs +685 -0
  62. package/pipeline/scripts/product-tree.mjs +544 -0
  63. package/pipeline/skills/.skill-manifest.json +11 -7
  64. package/pipeline/skills/.skills-index.json +12 -1
  65. package/pipeline/skills/shared/README.md +4 -3
  66. package/pipeline/skills/shared/core/google-play-compliance/references/examples.md +1 -1
  67. package/pipeline/skills/shared/core/multi-agent-review-analysis/SKILL.md +1 -1
  68. package/pipeline/skills/shared/external/backlog/SKILL.md +1 -1
  69. package/pipeline/skills/shared/external/localization-reuse-map/SKILL.md +1 -1
  70. package/pipeline/skills/shared/external/spec-persona-walk/SKILL.md +118 -0
  71. package/pipeline/skills/shared/external/spec-persona-walk/evals/evals.json +50 -0
  72. package/pipeline/skills/shared/external/spec-persona-walk/scripts/persona-walk-anchors.mjs +443 -0
  73. package/pipeline/skills/shared/external/storekit/SKILL.md +1 -1
  74. package/pipeline/skills/shared/external/swiftdata/SKILL.md +1 -1
  75. package/pipeline/skills/skill-copies.json +5 -1
  76. package/pipeline/skills/skills-index.md +2 -1
@@ -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
@@ -637,6 +641,27 @@ def fallback_verdict(text: str) -> str:
637
641
 
638
642
 
639
643
  FILE_TOOLS = {"Edit", "Write", "NotebookEdit", "MultiEdit"}
644
+ PRODUCT_TREE_OVERLAY = "product-tree-overlay.jsonl"
645
+
646
+
647
+ def product_tree_overlay_verdict(ti: dict, cwd: str = "") -> str:
648
+ """DENY for a file tool aimed at the product-tree overlay, attended and
649
+ unattended: its rows are the user's agree or reject decisions, written
650
+ only through product-tree.mjs. The name is compared casefolded, both as
651
+ given and after resolving symlinks against the payload's cwd, so a case
652
+ variant on a case-insensitive volume or a link to the overlay is refused
653
+ too."""
654
+ path = ti.get("file_path") or ti.get("notebook_path") if isinstance(ti, dict) else None
655
+ if not isinstance(path, str) or not path:
656
+ return "OK"
657
+ names = [os.path.basename(os.path.normpath(path))]
658
+ try:
659
+ names.append(os.path.basename(os.path.realpath(os.path.join(cwd or os.getcwd(), path))))
660
+ except (OSError, ValueError):
661
+ pass
662
+ if any(n.casefold() == PRODUCT_TREE_OVERLAY for n in names):
663
+ return "DENY\tonly product-tree.mjs propose writes the overlay; a decision is the user's"
664
+ return "OK"
640
665
 
641
666
 
642
667
  # Permission modes in which a hook's "ask" has no documented prompt to raise.
@@ -650,6 +675,28 @@ FILE_TOOLS = {"Edit", "Write", "NotebookEdit", "MultiEdit"}
650
675
  NO_PROMPT_MODES = {"bypassPermissions", "dontAsk"}
651
676
 
652
677
 
678
+ def confirmation_key(data: dict) -> str:
679
+ """What a recorded confirmation names: the exact command for Bash; for any
680
+ other tool its name, the target path when there is one, and the sha256 of
681
+ its input as sorted compact JSON, so a yes covers this exact call only."""
682
+ tool = data.get("tool_name")
683
+ ti = data.get("tool_input") or {}
684
+ if tool == "Bash" or not isinstance(tool, str) or not tool:
685
+ cmd = ti.get("command", "") if isinstance(ti, dict) else ""
686
+ return cmd if isinstance(cmd, str) else ""
687
+ try:
688
+ canonical = json.dumps(ti, sort_keys=True, ensure_ascii=False, separators=(",", ":"))
689
+ except (TypeError, ValueError):
690
+ return ""
691
+ digest = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
692
+ path = (ti.get("file_path") or ti.get("notebook_path")) if isinstance(ti, dict) else None
693
+ parts = [tool]
694
+ if isinstance(path, str) and path and not any(c in path for c in "\r\n"):
695
+ parts.append(path)
696
+ parts.append("sha256:" + digest)
697
+ return " ".join(parts)
698
+
699
+
653
700
  def ask_verdict(reason: str, data: dict, strict: bool) -> str:
654
701
  """ASK<TAB>json for a prompt, DENY<TAB>reason where no prompt can be
655
702
  raised, BLOCK_UNATTENDED<TAB>reason when nobody is there to answer."""
@@ -659,12 +706,17 @@ def ask_verdict(reason: str, data: dict, strict: bool) -> str:
659
706
  # With prompts switched off the native ask cannot be raised, so the
660
707
  # recorded confirmation stands in for it. In every other mode the
661
708
  # prompt is the confirmation and a record must not skip it.
662
- if _guard_rules.confirmed((data.get("tool_input") or {}).get("command", "")):
709
+ key = confirmation_key(data)
710
+ if _guard_rules.confirmed(key):
663
711
  return "OK"
712
+ if data.get("tool_name") == "Bash" or not key:
713
+ what, again = "'<the exact command>'", "run the command again"
714
+ else:
715
+ what, again = shlex.quote(key), f"make the same {data.get('tool_name')} call again"
664
716
  return (
665
717
  "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)"
718
+ f"record it with node \"$HOME/.claude/scripts/confirm-command.mjs\" --command {what} "
719
+ f"and {again}, unchanged, within 10 minutes)"
668
720
  )
669
721
  out = {
670
722
  "hookSpecificOutput": {
@@ -847,6 +899,8 @@ def main() -> None:
847
899
  )
848
900
  if reason:
849
901
  verdict = "BLOCK_READONLY\t" + reason
902
+ if verdict == "OK" and data.get("tool_name") in FILE_TOOLS:
903
+ verdict = product_tree_overlay_verdict(data.get("tool_input") or {}, PAYLOAD_CWD["dir"])
850
904
  if (
851
905
  verdict == "OK"
852
906
  and isinstance(cmd, str)
@@ -859,6 +913,7 @@ def main() -> None:
859
913
  "DENY\tthe " + str(data.get("agent_type")) + " subagent is read-only and " + effect
860
914
  + "; it returns findings, and the orchestrator acts on them"
861
915
  )
916
+ verdict, user_rule = _user_guard_rules.before_ask(verdict, data, strict, normalize_for_match)
862
917
  if verdict.startswith("ASK"):
863
918
  verdict = ask_verdict(verdict.split("\t", 1)[1], data, strict)
864
919
  if verdict == "OK" and strict:
@@ -868,6 +923,7 @@ def main() -> None:
868
923
  reason = unattended_policy.check(data)
869
924
  if reason:
870
925
  verdict = "BLOCK_UNATTENDED\t" + reason.replace("\n", " ")
926
+ verdict = _user_guard_rules.after_policy(verdict, user_rule, strict)
871
927
  print(verdict)
872
928
  except Exception:
873
929
  # 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
@@ -61,7 +61,7 @@ import {
61
61
  } from "../lib/unattended-settings-location.mjs";
62
62
  import { prefsHosts, profileGaps } from "../lib/unattended-profile-check.mjs";
63
63
  import { xcodeSkillsStatus } from "../lib/xcode-plugin.mjs";
64
- import { hookReport } from "../lib/hook-registration.mjs";
64
+ import { hookReport, registrationGaps } from "../lib/hook-registration.mjs";
65
65
  import { PREFS_ENV, prefsFileIn } from "../lib/prefs-value.mjs";
66
66
  import { exitOnHelp } from "../lib/cli-help.mjs";
67
67
 
@@ -101,6 +101,7 @@ const CHECK_IDS = [
101
101
  "identity",
102
102
  "hook-coverage",
103
103
  "hook-reachability",
104
+ "guard-rules",
104
105
  "credential-mapping",
105
106
  "credential-liveness",
106
107
  "store-reference",
@@ -108,6 +109,7 @@ const CHECK_IDS = [
108
109
  "task-tools",
109
110
  "mcp-registration",
110
111
  "mcp-surface",
112
+ "mcp-failures",
111
113
  "disk-space",
112
114
  "worktree-residue",
113
115
  "usage-report",
@@ -573,6 +575,112 @@ function checkHookReachability() {
573
575
  );
574
576
  }
575
577
 
578
+ // prefs.global.guardRules as the guard reads them (_user_guard_rules.py
579
+ // --report, same file lookup), so doctor and the guard cannot disagree on
580
+ // which rule is valid. Reports rule labels and problems, never a pattern.
581
+ // A rule whose tool agent-guard.sh is not registered on does nothing; Read is
582
+ // the usual case, since the default hooks do not register the guard there.
583
+ const GUARD_COMMAND = 'bash "$HOME/.claude/scripts/agent-guard.sh"';
584
+ // The host tools a rule's tool name governs. MultiEdit is left out: the
585
+ // current host has no such tool, so requiring a registration for it would
586
+ // warn on every default install.
587
+ const GUARD_RULE_TOOLS = { Edit: ["Edit", "NotebookEdit"] };
588
+
589
+ function guardRulesReport() {
590
+ const script = join(HERE, "_user_guard_rules.py");
591
+ if (!existsSync(script)) return { skip: "_user_guard_rules.py is not installed" };
592
+ try {
593
+ const out = execFileSync("python3", [script, "--report"], {
594
+ encoding: "utf8",
595
+ timeout: 10000,
596
+ stdio: ["ignore", "pipe", "ignore"],
597
+ });
598
+ return JSON.parse(out);
599
+ } catch {
600
+ return { skip: "python3 could not read the guard rules" };
601
+ }
602
+ }
603
+
604
+ function checkGuardRules() {
605
+ const r = guardRulesReport();
606
+ if (r.skip) {
607
+ skip("guard-rules", r.skip);
608
+ return;
609
+ }
610
+ if (r.error) {
611
+ report(
612
+ "guard-rules",
613
+ "WARN",
614
+ `${r.error}: no guard rule applies; attended each call a rule could govern carries a note, and ` +
615
+ (r.holdsRules === false
616
+ ? "unattended nothing is refused, since the file does not name guardRules"
617
+ : "every such call is refused unattended"),
618
+ `set ${r.source} to valid JSON with prefs.global.guardRules as a list`,
619
+ null,
620
+ );
621
+ return;
622
+ }
623
+ if (!r.rules) {
624
+ ok("guard-rules");
625
+ return;
626
+ }
627
+ const parts = [];
628
+ const detail = [];
629
+ const step = [];
630
+ if (r.invalid.length) {
631
+ const blocks = r.invalid.filter((i) => i.action === "block" && i.tool).length;
632
+ parts.push(
633
+ `${r.invalid.length} of ${r.rules} guard rule(s) are invalid and ignored` +
634
+ (blocks ? `, and ${blocks} invalid block rule(s) refuse their tool unattended` : ""),
635
+ );
636
+ for (const i of r.invalid) detail.push(`${i.label}: ${i.problem}`);
637
+ step.push("set prefs.global.guardRules so every rule validates (--explain names each)");
638
+ }
639
+ const uncovered = r.tools.flatMap((tool) => {
640
+ const names = GUARD_RULE_TOOLS[tool] || [tool.replace(/[*?]/g, "x")];
641
+ const missing = names.filter((name) => {
642
+ const template = {
643
+ hooks: {
644
+ PreToolUse: [{ matcher: name, hooks: [{ type: "command", command: GUARD_COMMAND }] }],
645
+ },
646
+ };
647
+ return registrationGaps({ template, home: HOME }).missing.length > 0;
648
+ });
649
+ if (!missing.length) return [];
650
+ return [missing.length === names.length ? tool : `${tool} (${missing.join(", ")})`];
651
+ });
652
+ if (uncovered.length) {
653
+ parts.push(
654
+ `guard rules for ${uncovered.join(", ")} do nothing: agent-guard.sh is not registered there`,
655
+ );
656
+ for (const t of uncovered) detail.push(`PreToolUse ${t}: agent-guard.sh not registered`);
657
+ step.push(
658
+ `merge a PreToolUse entry running agent-guard.sh for ${uncovered.join(", ")} into ${join(CLAUDE, "settings.json")}`,
659
+ );
660
+ }
661
+ const slow = Array.isArray(r.slow) ? r.slow : [];
662
+ const slowNote =
663
+ `${slow.length} guard rule(s) have a slow shape and run under the 1-second matching budget, ` +
664
+ "where a block or ask rule that runs out of time refuses unattended and asks attended";
665
+ for (const i of slow) detail.push(`${i.label}: ${i.shape}`);
666
+ if (!parts.length && slow.length) {
667
+ report(
668
+ "guard-rules",
669
+ "INFO",
670
+ slowNote,
671
+ "set each named rule's match to a tighter pattern: bound the inner quantifier or make its neighbours disjoint",
672
+ detail,
673
+ );
674
+ return;
675
+ }
676
+ if (slow.length) parts.push(slowNote);
677
+ if (!parts.length) {
678
+ ok("guard-rules");
679
+ return;
680
+ }
681
+ report("guard-rules", "WARN", parts.join("; "), step.join("; then "), detail);
682
+ }
683
+
576
684
  function credentialInventory() {
577
685
  const inv = join(CLAUDE, "lib", "credential-inventory.sh");
578
686
  if (!existsSync(inv)) return null;
@@ -977,6 +1085,52 @@ function checkMcpSurface() {
977
1085
  );
978
1086
  }
979
1087
 
1088
+ // The local MCP failure log note-mcp-failure.sh writes. A missing sibling
1089
+ // leaves the check to SKIP rather than taking doctor down with it: doctor is
1090
+ // what a half-installed machine runs.
1091
+ let mcpFailureLog = null;
1092
+ try {
1093
+ mcpFailureLog = await import("./note-mcp-failure.mjs");
1094
+ } catch {
1095
+ mcpFailureLog = null;
1096
+ }
1097
+
1098
+ // A server whose calls keep failing, read from the failures this machine
1099
+ // already recorded. Nothing is probed. INFO, never WARN: a flaky third-party
1100
+ // server degrades a session but is not this install's health, and the step
1101
+ // names the server so the user can decide.
1102
+ function checkMcpFailures() {
1103
+ if (!mcpFailureLog) {
1104
+ skip("mcp-failures", "note-mcp-failure.mjs is not installed");
1105
+ return;
1106
+ }
1107
+ if (!mcpFailureLog.captureEnabled()) {
1108
+ skip("mcp-failures", "MCP failure counting is off (mcpFailures.enabled or usageLog.optOut)");
1109
+ return;
1110
+ }
1111
+ const summary = mcpFailureLog.failureSummary(mcpFailureLog.readFailures());
1112
+ const repeated = summary.servers.filter((s) => summary.repeated.includes(s.server));
1113
+ if (!repeated.length) {
1114
+ ok("mcp-failures");
1115
+ return;
1116
+ }
1117
+ const worst = repeated[0];
1118
+ const others = repeated.length > 1 ? ` (and ${repeated.length - 1} more server(s))` : "";
1119
+ report(
1120
+ "mcp-failures",
1121
+ "INFO",
1122
+ `${worst.server} failed ${worst.failures} times in the last ${summary.hours} hours${others}`,
1123
+ `run claude mcp list to see whether ${worst.server} is connected, then node ${join(HERE, "note-mcp-failure.mjs")} summary for the failing tools`,
1124
+ repeated.map((r) => ({
1125
+ server: r.server,
1126
+ failures: r.failures,
1127
+ tools: r.tools,
1128
+ classes: r.classes,
1129
+ last: r.last,
1130
+ })),
1131
+ );
1132
+ }
1133
+
980
1134
  // usage-report.mjs runs detached with its output discarded, so the record it
981
1135
  // writes after every send attempt is the one place a broken reporting path
982
1136
  // becomes visible.
@@ -1493,12 +1647,14 @@ function main() {
1493
1647
  checkIdentity();
1494
1648
  checkHookCoverage();
1495
1649
  checkHookReachability();
1650
+ checkGuardRules();
1496
1651
  checkCredentials(credentialInventory());
1497
1652
  checkStoreReference();
1498
1653
  checkEmbeddedCredentials();
1499
1654
  checkTaskTools();
1500
1655
  checkMcpRegistration();
1501
1656
  checkMcpSurface();
1657
+ checkMcpFailures();
1502
1658
  checkDiskSpace();
1503
1659
  checkWorktreeResidue();
1504
1660
  checkUsageReport();
@@ -21,6 +21,23 @@
21
21
  * reported, so an expansion can only point at names that
22
22
  * exist; vocabulary words past the twelfth are reported as
23
23
  * over the limit. `vocab --like` lists candidates.
24
+ * --tier <t> quick | panorama | deep: answer in a fixed character
25
+ * budget instead of the token-budgeted walk (--budget,
26
+ * --depth and --seeds are then ignored).
27
+ * quick the top matches only, about 1.5k characters
28
+ * panorama matches, the hubs and clusters around them
29
+ * and their direct neighbours, about 6k
30
+ * deep matches in full detail, the shortest paths
31
+ * between them and neighbours two hops out,
32
+ * about 12k
33
+ * Each tier is fitted with fitToBudget
34
+ * (lib/tiered-budget.mjs): whole lines are dropped, lowest
35
+ * rank first and interleaved across sections, and one
36
+ * closing line says how many. The header echoes at most
37
+ * 120 characters of the question, so a long one leaves
38
+ * room for matches. --tier=<t> is the same flag; a name
39
+ * outside the three exits 64. Without --tier the output is
40
+ * the walk below, unchanged.
24
41
  * --no-log Do not append this query to the query log
25
42
  * --json Emit JSON instead of text
26
43
  *
@@ -68,12 +85,31 @@ import { join, resolve, basename, dirname } from "node:path";
68
85
  import { homedir } from "node:os";
69
86
  import { bm25, shortId } from "./_retrieval.mjs";
70
87
  import { standing } from "./_memory-policy.mjs";
71
- import { parseFlags } from "./graph-build.mjs";
88
+ import { parseArgs } from "../lib/args.mjs";
72
89
  import { exitOnHelp } from "../lib/cli-help.mjs";
90
+ import { TIER_NAMES, fitToBudget, tierChars, tierNote } from "../lib/tiered-budget.mjs";
91
+ import { clusters } from "./_graph-analysis.mjs";
73
92
 
74
93
  exitOnHelp(import.meta.url);
75
94
 
76
95
  const CHARS_PER_TOKEN = 4;
96
+ const HEADER_QUESTION_MAX = 120;
97
+
98
+ /**
99
+ * Flags and positionals. `--name=value` is a value, as lib/args reads it by
100
+ * default; a bare `--` stays a positional, as it always was here.
101
+ */
102
+ function parseFlags(argv) {
103
+ const { flags, positionals } = parseArgs(argv, { terminator: false });
104
+ return { flags, positional: positionals };
105
+ }
106
+
107
+ /** The question as the tier header shows it: at most HEADER_QUESTION_MAX characters. */
108
+ function headerQuestion(question) {
109
+ if (question.length <= HEADER_QUESTION_MAX) return question;
110
+ const cut = question.slice(0, HEADER_QUESTION_MAX).trimEnd();
111
+ return `${cut} [+${question.length - cut.length} chars]`;
112
+ }
77
113
  const MAX_EXPAND = 12;
78
114
  const MAX_LIKE = 50;
79
115
  const LIKE_DISTANCE = 2;
@@ -438,6 +474,168 @@ export function traverse({
438
474
  return { seeds, hits, truncated, tokens };
439
475
  }
440
476
 
477
+ const TIER_SEEDS = { quick: 20, panorama: 8, deep: 8 };
478
+ const PANORAMA_HUBS = 10;
479
+ const PANORAMA_CLUSTERS = 6;
480
+ const PANORAMA_NEIGHBOURS = 60;
481
+ const DEEP_PATH_PAIRS = 6;
482
+ const DEEP_PATH_DEPTH = 6;
483
+ const DEEP_NEIGHBOURS = 120;
484
+ const CLUSTER_SEEDS_SHOWN = 4;
485
+ const SECTION_ORDER = ["Matches", "Paths", "Clusters", "Hubs", "Neighbours"];
486
+
487
+ /** A node with everything the graph records about it, for the deep tier. */
488
+ export function detailLine(node) {
489
+ const kind = node.symbolKind ? `${node.kind}/${node.symbolKind}` : node.kind;
490
+ const span =
491
+ Number.isInteger(node.startLine) && Number.isInteger(node.endLine)
492
+ ? `, lines ${node.startLine}-${node.endLine}`
493
+ : Number.isInteger(node.line)
494
+ ? `, line ${node.line}`
495
+ : "";
496
+ return `${node.name} (${kind}) ${node.path || "-"}${span}, degree ${node.degree ?? 0}, id ${node.id}`;
497
+ }
498
+
499
+ /** The file a node lives in: itself for a file, its defining file for a symbol. */
500
+ function fileOfNode(graph, node) {
501
+ if (node.kind === "file") return node.id;
502
+ const def = graph.edges.find((e) => e.kind === "defines" && e.to === node.id);
503
+ return def ? def.from : null;
504
+ }
505
+
506
+ function neighbourRows(graph, seeds, maxDepth, cap) {
507
+ const byId = new Map(graph.nodes.map((n) => [n.id, n]));
508
+ const adj = adjacency(graph);
509
+ const seen = new Set(seeds.map((n) => n.id));
510
+ const rows = [];
511
+ let frontier = seeds.map((n) => ({ node: n, from: n }));
512
+ for (let d = 1; d <= maxDepth && frontier.length && rows.length < cap; d++) {
513
+ const next = [];
514
+ for (const { node, from } of frontier) {
515
+ const out = (adj.get(node.id) || [])
516
+ .slice()
517
+ .sort((a, b) => (byId.get(b.id)?.degree || 0) - (byId.get(a.id)?.degree || 0));
518
+ for (const n of out) {
519
+ if (seen.has(n.id) || rows.length >= cap) continue;
520
+ const target = byId.get(n.id);
521
+ if (!target) continue;
522
+ seen.add(n.id);
523
+ rows.push({ node: target, dist: d, via: `${n.kind}/${n.dir}`, from });
524
+ next.push({ node: target, from });
525
+ }
526
+ }
527
+ frontier = next;
528
+ }
529
+ return rows;
530
+ }
531
+
532
+ function panoramaSections(graph, seeds) {
533
+ const neighbours = neighbourRows(graph, seeds, 1, PANORAMA_NEIGHBOURS);
534
+ const region = new Map([...seeds, ...neighbours.map((r) => r.node)].map((n) => [n.id, n]));
535
+ const hubs = [...region.values()]
536
+ .filter((n) => n.kind !== "module")
537
+ .sort((a, b) => (b.degree || 0) - (a.degree || 0) || (a.id < b.id ? -1 : 1))
538
+ .slice(0, PANORAMA_HUBS)
539
+ .map((n) => `${renderNode(n)}, degree ${n.degree ?? 0}`);
540
+ const seedFiles = new Map();
541
+ for (const s of seeds) {
542
+ const f = fileOfNode(graph, s);
543
+ if (f && !seedFiles.has(f)) seedFiles.set(f, s.name);
544
+ }
545
+ const groups = clusters(graph)
546
+ .filter((c) => c.files.some((f) => seedFiles.has(f)))
547
+ .slice(0, PANORAMA_CLUSTERS)
548
+ .map((c) => {
549
+ const here = c.files.filter((f) => seedFiles.has(f)).map((f) => seedFiles.get(f));
550
+ const shown = here.slice(0, CLUSTER_SEEDS_SHOWN).join(", ");
551
+ const more =
552
+ here.length > CLUSTER_SEEDS_SHOWN ? ` +${here.length - CLUSTER_SEEDS_SHOWN}` : "";
553
+ return `${c.dirs}: ${c.files.length} files, cohesion ${c.cohesion}, hub ${c.id}; matches here: ${shown}${more}`;
554
+ });
555
+ return {
556
+ Clusters: groups,
557
+ Hubs: hubs,
558
+ Neighbours: neighbours.map(
559
+ (r) => `${printedLine(1, renderNode(r.node), r.via)} from ${r.from.name}`,
560
+ ),
561
+ };
562
+ }
563
+
564
+ function deepSections(graph, seeds) {
565
+ const pairs = [];
566
+ for (let i = 0; i < seeds.length && pairs.length < DEEP_PATH_PAIRS; i++) {
567
+ for (let j = i + 1; j < seeds.length && pairs.length < DEEP_PATH_PAIRS; j++) {
568
+ pairs.push([seeds[i], seeds[j]]);
569
+ }
570
+ }
571
+ const paths = [];
572
+ for (const [a, b] of pairs) {
573
+ const { path } = shortestPath(graph, a.id, b.id, { maxDepth: DEEP_PATH_DEPTH });
574
+ if (!path || path.length < 2) continue;
575
+ const chain = path
576
+ .map((h, i) => (i === 0 ? h.node.name : `-[${h.via}]-> ${h.node.name}`))
577
+ .join(" ");
578
+ const hops = path.length - 1;
579
+ paths.push(`${a.name} to ${b.name}, ${hops} ${hops === 1 ? "hop" : "hops"}: ${chain}`);
580
+ }
581
+ return {
582
+ Paths: paths,
583
+ Neighbours: neighbourRows(graph, seeds, 2, DEEP_NEIGHBOURS).map(
584
+ (r) => `${printedLine(r.dist, detailLine(r.node), r.via)} from ${r.from.name}`,
585
+ ),
586
+ };
587
+ }
588
+
589
+ /**
590
+ * The answer to a question at one tier, fitted to the tier's characters.
591
+ *
592
+ * Lines are interleaved across sections when they are dropped: the n-th line
593
+ * of every section outranks the (n+1)-th line of any, so a tight budget keeps
594
+ * a little of each section rather than all of one.
595
+ *
596
+ * @returns {{tier: string, maxChars: number, text: string, dropped: string[], kept: number, seeds: object[]}}
597
+ */
598
+ export function tieredGraphQuery({ graph, question, tier, expand = [], standing: byNode = null }) {
599
+ const maxChars = tierChars(tier);
600
+ if (maxChars === null) throw new Error(`unknown tier: ${tier}`);
601
+ const seeds = rankNodes(graph, question, { expand, standing: byNode })
602
+ .slice(0, TIER_SEEDS[tier])
603
+ .map((r) => r.node);
604
+ const sections = {
605
+ Matches: seeds.map((n) =>
606
+ tier === "deep" ? `* ${detailLine(n)}` : printedLine(0, renderNode(n), null),
607
+ ),
608
+ ...(tier === "panorama" ? panoramaSections(graph, seeds) : {}),
609
+ ...(tier === "deep" ? deepSections(graph, seeds) : {}),
610
+ };
611
+ const items = [];
612
+ for (const [section, lines] of Object.entries(sections)) {
613
+ const order = SECTION_ORDER.indexOf(section);
614
+ lines.forEach((line, rank) =>
615
+ items.push({
616
+ id: `${section}:${rank}`,
617
+ section,
618
+ line,
619
+ priority: -(rank * SECTION_ORDER.length + order),
620
+ }),
621
+ );
622
+ }
623
+ const header = `# ${headerQuestion(question)} (${tier})`;
624
+ const render = (kept) => {
625
+ const out = [header];
626
+ for (const section of SECTION_ORDER) {
627
+ const lines = kept.filter((k) => k.section === section).map((k) => k.line);
628
+ if (lines.length) out.push("", `## ${section}`, ...lines);
629
+ }
630
+ if (out.length === 1) out.push("", "no matching nodes");
631
+ return out.join("\n");
632
+ };
633
+ const { text, dropped } = items.length
634
+ ? fitToBudget(items, { maxChars, render, note: tierNote(tier, maxChars) })
635
+ : { text: render([]), dropped: [] };
636
+ return { tier, maxChars, text, dropped, kept: items.length - dropped.length, seeds };
637
+ }
638
+
441
639
  function pathMain(flags, positional, graph) {
442
640
  if (positional.length !== 2) {
443
641
  process.stderr.write(
@@ -519,6 +717,8 @@ function main() {
519
717
  process.exit(vocabMain(flags, graph));
520
718
  }
521
719
 
720
+ if (flags.tier !== undefined) process.exit(tierMain(flags, graph, path, question));
721
+
522
722
  const budget = Number(flags.budget) > 0 ? Number(flags.budget) : 2000;
523
723
  const depth = Number(flags.depth) > 0 ? Number(flags.depth) : 2;
524
724
  const seedCount = Number(flags.seeds) > 0 ? Number(flags.seeds) : 8;
@@ -535,22 +735,7 @@ function main() {
535
735
  standing: standingByNode(path),
536
736
  });
537
737
 
538
- let logId = null;
539
- if (flags["no-log"] !== true && process.env.MULTI_AGENT_GRAPH_LOG !== "0") {
540
- const ts = new Date().toISOString();
541
- logId = shortId("Q", ts, question, expansion?.used.join(" ") ?? "");
542
- try {
543
- appendBounded(queryLogPath(path), {
544
- id: logId,
545
- ts,
546
- query: question,
547
- expand: expansion?.used ?? [],
548
- top: result.seeds.slice(0, LOG_TOP).map((n) => n.id),
549
- });
550
- } catch {
551
- logId = null;
552
- }
553
- }
738
+ const logId = logQuery(flags, path, question, expansion, result.seeds);
554
739
 
555
740
  if (flags.json === true) {
556
741
  const doc = { question, budget, ...result };
@@ -590,6 +775,61 @@ function main() {
590
775
  );
591
776
  }
592
777
 
778
+ /** Append a free-text query to the log beside the graph; its id, or null when not logged. */
779
+ function logQuery(flags, path, question, expansion, seeds) {
780
+ if (flags["no-log"] === true || process.env.MULTI_AGENT_GRAPH_LOG === "0") return null;
781
+ const ts = new Date().toISOString();
782
+ const id = shortId("Q", ts, question, expansion?.used.join(" ") ?? "");
783
+ try {
784
+ appendBounded(queryLogPath(path), {
785
+ id,
786
+ ts,
787
+ query: question,
788
+ expand: expansion?.used ?? [],
789
+ top: seeds.slice(0, LOG_TOP).map((n) => n.id),
790
+ });
791
+ return id;
792
+ } catch {
793
+ return null;
794
+ }
795
+ }
796
+
797
+ function tierMain(flags, graph, path, question) {
798
+ if (typeof flags.tier !== "string" || tierChars(flags.tier) === null) {
799
+ process.stderr.write(
800
+ `graph-query: --tier takes ${TIER_NAMES.slice(0, -1).join(", ")} or deep\n`,
801
+ );
802
+ return 64;
803
+ }
804
+ const expansion =
805
+ typeof flags.expand === "string" ? expandTerms(vocabulary(graph), flags.expand) : null;
806
+ const r = tieredGraphQuery({
807
+ graph,
808
+ question,
809
+ tier: flags.tier,
810
+ expand: expansion?.used ?? [],
811
+ standing: standingByNode(path),
812
+ });
813
+ const logId = logQuery(flags, path, question, expansion, r.seeds);
814
+ if (flags.json === true) {
815
+ const doc = {
816
+ question,
817
+ tier: r.tier,
818
+ maxChars: r.maxChars,
819
+ chars: r.text.length,
820
+ kept: r.kept,
821
+ dropped: r.dropped.length,
822
+ text: r.text,
823
+ };
824
+ if (expansion) doc.expansion = expansion;
825
+ if (logId) doc.logId = logId;
826
+ process.stdout.write(JSON.stringify(doc, null, 2) + "\n");
827
+ } else {
828
+ process.stdout.write(`${r.text}\n`);
829
+ }
830
+ return 0;
831
+ }
832
+
593
833
  function vocabMain(flags, graph) {
594
834
  if (typeof flags.like !== "string" || !flags.like.trim()) {
595
835
  process.stderr.write("graph-query: vocab needs --like <word>\n");