@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
@@ -13,6 +13,14 @@
13
13
  * required gate for that HEAD passed. A gate the run skipped leaves no entry,
14
14
  * and a missing entry blocks the commit the same way a failing one does.
15
15
  *
16
+ * The build and test gates (DIGEST_BOUND) also record `sourceDigest`, the
17
+ * digest of the working tree's content (lib/source-digest.mjs). An edit made
18
+ * after the build leaves HEAD where it was, so for those gates the digest
19
+ * decides: an entry whose digest is the tree's current one counts whatever
20
+ * HEAD it names, and one whose digest differs is stale, which blocks the
21
+ * commit like a missing entry and is reported as `stale`. An entry without a
22
+ * digest, or a tree git cannot digest, is judged by sha as before.
23
+ *
16
24
  * Entries are written while the quality gates are active (lib/unattended.mjs,
17
25
  * gatesActive): MULTI_AGENT_UNATTENDED=1, or a run in autopilot mode. A run
18
26
  * that is neither writes only the gates in ATTENDED_RECORDED, each entry marked
@@ -69,6 +77,7 @@ import { dirname, join } from "node:path";
69
77
  import { decisionEntry, withDecision } from "../lib/decisions.mjs";
70
78
  import { invokedDirectly } from "../lib/invoked-directly.mjs";
71
79
  import { readRegularFile, readRegularJson } from "../lib/regular-file.mjs";
80
+ import { sourceDigest } from "../lib/source-digest.mjs";
72
81
  import { writeFileSafe } from "../lib/safe-write.mjs";
73
82
  import { globalPref } from "../lib/prefs-value.mjs";
74
83
  import { modeEntry } from "../lib/run-completion.mjs";
@@ -137,6 +146,35 @@ export function trailingFailures(gates, gate) {
137
146
 
138
147
  export const ATTENDED_COMMIT_EVIDENCE = ["evidence-gate/build", "evidence-gate/test"];
139
148
 
149
+ /** Gates whose entries carry the working tree's source digest. */
150
+ export const DIGEST_BOUND = new Set(["evidence-gate/build", "evidence-gate/test"]);
151
+
152
+ /** The digest of the tree at `dir`, or null when it cannot be read. */
153
+ export function currentDigestOf(dir) {
154
+ return sourceDigest(dir)?.digest ?? null;
155
+ }
156
+
157
+ /**
158
+ * Latest entry per gate among those that speak for the current content: a
159
+ * digest-bound entry with a digest is matched on the digest when the current
160
+ * one is known, every other entry on its sha. Also names the digest-bound
161
+ * gates whose only candidates were recorded on other content.
162
+ */
163
+ function evidenceFor(gates, { sha, currentDigest = null, sameTree = null }) {
164
+ const onSha = (s) => s === sha || (sameTree ? sameTree(s) : false);
165
+ const byDigest = (e) =>
166
+ DIGEST_BOUND.has(e.gate) && Boolean(currentDigest) && typeof e.sourceDigest === "string";
167
+ const latest = latestWhere(gates, (e) =>
168
+ byDigest(e) ? e.sourceDigest === currentDigest : onSha(e.sha),
169
+ );
170
+ const stale = new Set();
171
+ for (const e of Array.isArray(gates) ? gates : []) {
172
+ if (e && byDigest(e) && e.sourceDigest !== currentDigest && !latest.has(e.gate))
173
+ stale.add(e.gate);
174
+ }
175
+ return { latest, stale };
176
+ }
177
+
140
178
  /** Asked for too once the run is in its commit phase: the review verdict. */
141
179
  export const ATTENDED_REVIEW_EVIDENCE = "review-decision";
142
180
  export const ATTENDED_REVIEW_FROM_PHASE = 4;
@@ -159,16 +197,14 @@ export const ATTENDED_COMMIT_MODES = ["off", "warn", "block", "auto"];
159
197
  * @param {string} sha
160
198
  * @returns {string[]}
161
199
  */
162
- export function attendedEvidenceGaps(state, sha, { sameTree } = {}) {
200
+ export function attendedEvidenceGaps(state, sha, { sameTree, currentDigest = null } = {}) {
163
201
  const wanted = [...ATTENDED_COMMIT_EVIDENCE];
164
202
  if (Number(state?.currentPhase) >= ATTENDED_REVIEW_FROM_PHASE)
165
203
  wanted.push(ATTENDED_REVIEW_EVIDENCE);
166
204
  const asked = (Array.isArray(state?.gates) ? state.gates : []).filter((e) =>
167
205
  wanted.includes(e?.gate),
168
206
  );
169
- const latest = sameTree
170
- ? latestByGateWhere(asked, (s) => s === sha || sameTree(s))
171
- : latestByGate(asked, sha);
207
+ const { latest } = evidenceFor(asked, { sha, currentDigest, sameTree });
172
208
  return wanted.filter((g) => {
173
209
  const e = latest.get(g);
174
210
  return !e || !PASSING.has(e.verdict);
@@ -494,11 +530,13 @@ export async function record(
494
530
  const wt = ctx.state?.worktreePath;
495
531
  shaRepo = typeof wt === "string" && existsSync(wt) ? wt : process.cwd();
496
532
  }
533
+ const digest = DIGEST_BOUND.has(gate) ? currentDigestOf(shaRepo) : null;
497
534
  const entry = {
498
535
  gate,
499
536
  verdict,
500
537
  at: new Date().toISOString(),
501
538
  sha: headSha(shaRepo),
539
+ ...(digest ? { sourceDigest: digest } : {}),
502
540
  detail: detail && typeof detail === "object" ? detail : { value: detail },
503
541
  ...(attended ? { attended: true } : {}),
504
542
  };
@@ -613,9 +651,14 @@ export function latestByGate(gates, sha) {
613
651
 
614
652
  /** latestByGate over the entries whose sha `accept` takes. */
615
653
  export function latestByGateWhere(gates, accept) {
654
+ return latestWhere(gates, (e) => accept(e.sha));
655
+ }
656
+
657
+ /** Latest entry per gate over the entries `accept` takes. */
658
+ function latestWhere(gates, accept) {
616
659
  const out = new Map();
617
660
  (Array.isArray(gates) ? gates : []).forEach((e, i) => {
618
- if (!e || typeof e !== "object" || typeof e.gate !== "string" || !accept(e.sha)) return;
661
+ if (!e || typeof e !== "object" || typeof e.gate !== "string" || !accept(e)) return;
619
662
  const prev = out.get(e.gate);
620
663
  const t = Date.parse(e.at) || 0;
621
664
  if (!prev || t > prev.t || (t === prev.t && i > prev.i)) out.set(e.gate, { e, t, i });
@@ -628,24 +671,31 @@ export function latestByGateWhere(gates, accept) {
628
671
  *
629
672
  * @param {object} state
630
673
  * @param {string} sha
631
- * @param {{mandatory?: string[]}} [opts]
632
- * @returns {{ok: boolean, missing: string[], failing: object[], sha: string}}
674
+ * @param {{mandatory?: string[], currentDigest?: string|null}} [opts]
675
+ * @returns {{ok: boolean, missing: string[], failing: object[], stale: string[], sha: string}}
633
676
  */
634
- export function checkCommit(state, sha, { mandatory = MANDATORY_AT_COMMIT } = {}) {
677
+ export function checkCommit(
678
+ state,
679
+ sha,
680
+ { mandatory = MANDATORY_AT_COMMIT, currentDigest = null } = {},
681
+ ) {
635
682
  // An entry written while the gates were off says what an attended run
636
683
  // observed; it never stands in for a verdict the unattended contract requires.
637
684
  const gated = (Array.isArray(state?.gates) ? state.gates : []).filter(
638
685
  (e) => !(e && e.attended === true),
639
686
  );
640
- const latest = latestByGate(gated, sha);
687
+ const { latest, stale: staleSet } = evidenceFor(gated, { sha, currentDigest });
641
688
  const missing = [];
642
689
  const failing = [];
690
+ const stale = [];
643
691
  for (const g of mandatory) {
644
692
  const e = latest.get(g);
645
- if (!e) missing.push(g);
693
+ if (!e && staleSet.has(g)) stale.push(g);
694
+ else if (!e) missing.push(g);
646
695
  else if (!PASSING.has(e.verdict)) failing.push(e);
647
696
  }
648
- return { ok: missing.length === 0 && failing.length === 0, missing, failing, sha };
697
+ const ok = missing.length === 0 && failing.length === 0 && stale.length === 0;
698
+ return { ok, missing, failing, stale, sha };
649
699
  }
650
700
 
651
701
  // ---------------------------------------------------------------------------
@@ -705,23 +755,25 @@ async function main(argv) {
705
755
  return 3;
706
756
  }
707
757
  const state = readJson(path);
708
- const sha =
709
- opts.sha ||
710
- headSha(
711
- opts.repo || !(state?.worktreePath && existsSync(state.worktreePath))
712
- ? repo
713
- : state.worktreePath,
714
- );
758
+ const tree =
759
+ opts.repo || !(state?.worktreePath && existsSync(state.worktreePath))
760
+ ? repo
761
+ : state.worktreePath;
762
+ const sha = opts.sha || headSha(tree);
715
763
  if (!state || !sha) {
716
764
  process.stderr.write(`gate-ledger: cannot read ${path} or resolve HEAD\n`);
717
765
  return 3;
718
766
  }
719
- const r = checkCommit(state, sha);
767
+ const r = checkCommit(state, sha, { currentDigest: currentDigestOf(tree) });
720
768
  if (opts.json) writeFileSync(1, `${JSON.stringify({ statePath: path, ...r }, null, 2)}\n`);
721
769
  if (!r.ok) {
722
770
  const lines = [
723
771
  `gate-ledger: the unattended commit on ${sha.slice(0, 12)} is not backed by the gate ledger (${path})`,
724
772
  ...r.missing.map((g) => ` missing: ${g} has no entry for this HEAD`),
773
+ ...r.stale.map(
774
+ (g) =>
775
+ ` stale: ${g} was recorded on other source; a file changed after it ran, so run it again`,
776
+ ),
725
777
  ...r.failing.map(
726
778
  (e) =>
727
779
  ` failing: ${e.gate} -> ${e.verdict}${e.detail?.reason ? ` (${e.detail.reason})` : ""}`,
@@ -765,7 +817,10 @@ async function main(argv) {
765
817
  const bound =
766
818
  (session && state.hostSessionId === session) || (launched && state.sessionId === launched);
767
819
  const gateMode = effectiveCommitMode(pref, Boolean(bound));
768
- const missing = attendedEvidenceGaps(state, sha, { sameTree: sameTreeAs(repo) });
820
+ const missing = attendedEvidenceGaps(state, sha, {
821
+ sameTree: sameTreeAs(repo),
822
+ currentDigest: currentDigestOf(repo),
823
+ });
769
824
  if (opts.json)
770
825
  writeFileSync(1, `${JSON.stringify({ statePath: path, sha, gateMode, missing })}\n`);
771
826
  if (!missing.length) return 0;
@@ -773,7 +828,7 @@ async function main(argv) {
773
828
  writeFileSync(
774
829
  2,
775
830
  `${[
776
- `pre-commit-check: ${verb}: the run's gate ledger (${path}) has no passing ${missing.join(" / ")} for HEAD ${sha.slice(0, 12)}.`,
831
+ `pre-commit-check: ${verb}: the run's gate ledger (${path}) has no passing ${missing.join(" / ")} for HEAD ${sha.slice(0, 12)} and the source as it is now; an edit after the build or the tests makes their verdict stale.`,
777
832
  " Run the build and the tests through evidence-gate.mjs (Phase 2 Gate 1), and in the commit phase the review verdict (review-decision-gate.mjs), so the commit rests on recorded evidence.",
778
833
  gateMode === "block"
779
834
  ? " This session drives the run, so the commit waits for the evidence; prefs.global.attendedCommitGate.mode warn lets it through."
@@ -123,6 +123,11 @@ NAME_ARGS=(
123
123
  -o \( -name '*-wiki' -type d \)
124
124
  )
125
125
 
126
+ # `multi-agent-*` also covers lib/hook-once.mjs's claim directory
127
+ # (multi-agent-hook-once-<uid>). Its claims prune themselves after ten
128
+ # minutes; a sweep here removes the directory once no hook has claimed in it
129
+ # for the grace window.
130
+ #
126
131
  # `complaint-analysis-*` needs its own entry: find matches the basename against
127
132
  # the whole glob, so `analysis-*` never matched it. Same for the other three,
128
133
  # which were writing into $ROOT with nothing sweeping them (phase-0-init.md,
@@ -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");
@@ -0,0 +1,3 @@
1
+ {
2
+ "holes": []
3
+ }