@holmes-lab/holmes-kit 0.31.2 → 0.33.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 (37) hide show
  1. package/CHANGELOG.md +104 -0
  2. package/README.md +3 -1
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/autonomy.js +15 -1
  5. package/dist/holmes/guardrail/impact-gate.js +50 -1
  6. package/dist/holmes/mcp/handlers/adoption.d.ts +17 -3
  7. package/dist/holmes/mcp/handlers/adoption.js +70 -2
  8. package/dist/holmes/mcp/handlers/graph-operations.js +6 -1
  9. package/dist/holmes/mcp/handlers/maintenance-analysis.js +17 -11
  10. package/dist/holmes/mcp/handlers/maintenance-evidence.d.ts +6 -0
  11. package/dist/holmes/mcp/handlers/phase-queries.d.ts +30 -2
  12. package/dist/holmes/mcp/handlers/phase-queries.js +5 -1
  13. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +163 -4
  14. package/dist/holmes/mcp/handlers/requirement-triage.js +26 -18
  15. package/dist/holmes/mcp/handlers/review-evidence.d.ts +44 -1
  16. package/dist/holmes/mcp/handlers/review-evidence.js +48 -2
  17. package/dist/holmes/mcp/handlers/spec-approval.d.ts +10 -0
  18. package/dist/holmes/mcp/handlers/spec-approval.js +16 -1
  19. package/dist/holmes/mcp/handlers/spec-queries.d.ts +1 -9
  20. package/dist/holmes/mcp/handlers/spec-queries.js +40 -15
  21. package/dist/holmes/mcp/handlers.d.ts +212 -18
  22. package/dist/holmes/mcp/maintenance-analyze.d.ts +19 -0
  23. package/dist/holmes/mcp/maintenance-analyze.js +171 -7
  24. package/dist/holmes/mcp/maintenance-evidence.d.ts +25 -0
  25. package/dist/holmes/mcp/maintenance-evidence.js +52 -1
  26. package/dist/holmes/mcp/tool-schemas.js +29 -6
  27. package/dist/holmes/reverse/scan.d.ts +6 -0
  28. package/dist/holmes/reverse/scan.js +4 -2
  29. package/dist/holmes/review/requirement-triage.d.ts +25 -1
  30. package/dist/holmes/review/requirement-triage.js +175 -12
  31. package/dist/holmes/rtm/localize.d.ts +7 -0
  32. package/dist/holmes/rtm/localize.js +10 -0
  33. package/dist/holmes/semantic/unreadable-paths.d.ts +30 -0
  34. package/dist/holmes/semantic/unreadable-paths.js +104 -0
  35. package/package.json +1 -1
  36. package/playbooks/author-slice/PLAYBOOK.md +1 -1
  37. package/playbooks/promote-slice/PLAYBOOK.md +1 -1
package/CHANGELOG.md CHANGED
@@ -5,6 +5,110 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
  <!-- @implements A-SPEC-209 -->
8
+ ## [0.33.0] - 2026-10-01
9
+
10
+ ### Changed
11
+
12
+ - **`spec_list`, `review_status` and `reverse_scan` answer with compressed defaults** (A-SPEC-746). On this
13
+ repository their default responses were 202,608, 96,407 and 123,552 characters — past the client's
14
+ tool-result limit. They now compress rather than cut: `review_status` merges review-needed signals per spec
15
+ and drops the from/to digests (every spec still listed, 11,043 characters); `reverse_scan` counts the test
16
+ matches the clusters already carry, writes paths relative to their cluster, groups unmatched tests by
17
+ directory and folds clusters that are already fully anchored (19,846); `spec_list` answers counts, the specs
18
+ that are not approved, and a cursor page (15,864), and `spec_list({ ids })` answers one row (224). Anything
19
+ still left out is counted with a note; `detail: "full"` (or paging) returns the previous answer. Playbooks
20
+ check a spec's existence with `spec_list({ ids })`.
21
+ - **`requirement_triage` confirms a lineage only when it mentions every code identifier the request names**
22
+ (A-SPEC-713.2). A request about `spec_list`/`review_status` was answered `fulfilled` by the `phase_status`
23
+ lineage, whose REQ puts other tools out of scope, and intake then refused the new requirement. Where the top
24
+ lineage never mentions (outside its Out of Scope text) a snake_case, camelCase, path or file name the request
25
+ names, the verdict is `ambiguous` with `identifiers-outside-lineage:<ids>`.
26
+ - **`requirement_triage` never confirms a lineage on a single channel** (A-SPEC-713.3). With no vector on any
27
+ candidate (no semantic layer, or a cold one), the lexical top alone answered `existing-change` for 47 of 60
28
+ requirements that were new at the time — and intake refuses a new REQ after `existing-change`. Such a run is
29
+ now `ambiguous` (`single-channel`); the lexical order stays visible. Two agreeing channels decide as before.
30
+ - **`spec_approve` answers a blocked spec with its blockers before choosing an approval channel**
31
+ (A-SPEC-551.2). An invalid `breaking_change` grade graded `hitl`, went to the owner's approval queue, and the
32
+ refusal named the approval channel instead of the blocker. When no channel already covers the act, the
33
+ `approval_status` blockers come back first and nothing is elicited or queued.
34
+
35
+ ### Fixed
36
+
37
+ - **`holmes-kit autonomy off` no longer says OFF while autonomous approval is still on** (A-SPEC-553.2). With
38
+ `HOLMES_AUTONOMOUS_APPROVAL` in `.mcp.json` (the project default), `autonomy status` answered OFF while the
39
+ server sealed specs autonomously, and `autonomy off` removed only the session marker yet answered "OFF — every
40
+ spec approval is human again". Both now read the same project default as the server and the session banner:
41
+ `status` reports it and how to turn it off, and `off` exits 1 and says the project default keeps autonomy on.
42
+ - **The pre-edit evidence gate finds the analysis the session persisted** (A-SPEC-278.1). `HOLMES_EVIDENCE` is
43
+ an environment variable a session cannot set, so every edit right after `maintenance_analyze({ persist: true })`
44
+ warned `no-analysis`. Without a declared digest the gate reads the newest of the 64 most recent persisted
45
+ analyses taken at the current HEAD whose prediction names the target (regular files only, 2 MiB bound).
46
+ - **`maintenance_analyze` no longer treats every Korean or Japanese request as about every unreadable file**
47
+ (A-SPEC-741.1). A request with a non-ASCII letter made each unreadable language (`.sh`, …) a classification
48
+ gap, so a Korean corpus was `ambiguous` 60/60. The request's ASCII words are now compared with the paths (a
49
+ leading commit type word such as `feat:` is not; its scope is), Korean/Japanese language names count, and on
50
+ the cloud tier the rest is compared by meaning with unreadable path vectors the reindex / Stop-hook warm
51
+ prepares (below `gemini-embedding-001`'s measured 0.65 → outside the change). No vector, no tier, a model
52
+ without a threshold (local bge-m3), or no ASCII word keeps the language relevant. Replay: 60/60 → 14/60 on
53
+ the Korean corpus with the top candidate unchanged; the test scope is unchanged.
54
+ - **The field report's deny-reason cardinality guard allows 96 keys** (A-SPEC-578.8). New gate wording took this
55
+ repository's ledger to 65 distinct keys against a cap of 64; every key was read and none carried a command,
56
+ path or value. A leak is still thousands of keys.
57
+
58
+ ## [0.32.0] - 2026-09-30
59
+
60
+ ### Changed
61
+
62
+ - **`maintenance_analyze` says its confidence is uncalibrated where the number is read** (A-SPEC-740). Every result
63
+ carries `confidenceCalibrated: false` and a `confidenceNote` (the value counts which kinds of evidence were present,
64
+ does not predict accuracy, and must not weight answers or narrow a test scope); every persisted evidence artifact
65
+ carries `confidenceCalibrated: false`. The value and formula are unchanged and the artifact schema stays
66
+ `maintenance-evidence/1.4`, so recorded artifacts still feed calibration. It ships before the classification gates
67
+ are relaxed: with them lifted, 120 of 120 replay cases would report 0.95 at 0.467/0.383 top-1 accuracy.
68
+ - **`requirement_triage` answers in summaries by default** (A-SPEC-743). Each candidate document is
69
+ `{ id, type, title, status, dependsOn }`; `detail: "full"` adds frontmatter and sections. The bodies were 72% of a
70
+ 201 KB median answer (holmes; 107 KB on a second corpus) — past the tool-result limit, so the mandated intake step
71
+ was read back from a file in slices. Verdict, reasons, candidate order and scores are identical either way.
72
+ - **`maintenance_analyze` lists candidate specs in relevance order** (A-SPEC-745): specs the request cites, then the
73
+ specs anchored by the top-ranked candidate files, then the rest. The response keeps ten, and id order made those
74
+ ten A-SPEC-100 and its neighbours for every request. The set and every computation over it are unchanged.
75
+ - **`requirement_triage` gives a confident verdict only when its channels agree** (A-SPEC-713.1). A lineage the
76
+ request cites ranks first; lineages with a requirement vector are ordered by semantic score before BM25 (the old
77
+ `max(BM25, cosine)` let cosine count only when BM25 was zero); `existing-change`/`fulfilled` need the lexical and
78
+ semantic top lineages to agree — each top unique, the lexical one above zero — and that lineage to be the first
79
+ ranked, otherwise `ambiguous` (`channels-disagree` / `citation-unbacked`). A citation only orders and never counts
80
+ toward agreement: "(unrelated to REQ-1)" or an id inside a URL is a mention, not evidence. BM25 now scores each
81
+ lineage's titles and sections only — id spellings are removed from the prompt, and the `id:`/`lineage:`/`status:`
82
+ header is not scored — so "REQ 742", "the 742 rows" or the word "spec" no longer pick a lineage. Ties are judged on
83
+ scores alone, and a lineage without a vector ties on the semantic side. On replay the
84
+ lexical top was the right lineage in 0.20–0.32 of cases and a second corpus already answered `existing-change`
85
+ wrongly four times in five; an `existing-change` answer also stops the intake from creating a new REQ.
86
+
87
+ ### Added
88
+
89
+ - **Persisted maintenance evidence says why its test scope was full** (A-SPEC-744): `uncertainty.testScopeReason` and
90
+ structured `testScopeCauses` (unsupported-language, impact-truncated, coverage-gap, no-anchored-tests, …), and `maintenance_calibration`
91
+ reports `scopeCauses` — how often each cause occurred, older artifacts counted as `unrecorded`. 455 persisted
92
+ analyses here were all `full` and none said why.
93
+
94
+ ### Fixed
95
+
96
+ - **`maintenance_analyze` is no longer `ambiguous` for every request** (A-SPEC-741). Since four CI `.sh` scripts
97
+ landed on 2026-09-03, every analysis in this repository (455 of 455) and every replay case on two corpora (120 of
98
+ 120) was `ambiguous`, because a language the scanner cannot read anywhere in the tree counted against every request,
99
+ and a truncated impact walk decided the classification too. The classification now counts an unsupported language
100
+ only when the change touches it — a changed file with that extension, a path in the request (`ci.sh.` included), or
101
+ an unreadable file whose path — folders included — shares a word or a five-letter stem with the request
102
+ (`app/session/store.rb` for "the sessions", `lib/isolate.rb` for "isolation"), or a request that names the language
103
+ ("the shell script", "Kotlin") — and leans to "about the change" wherever it cannot judge: a request in a non-Latin
104
+ script, or a list of unreadable files that hit its 5,000-path cap. Truncation no longer decides it. The **test scope is unchanged**: a first version also relaxed it, and on replay 10 of the 12
105
+ scopes that then narrowed missed a test the commit changed, so every language and every depth stop still widen it.
106
+ - **`requirement_triage` no longer discards its semantic layer in this repository** (A-SPEC-742). Coverage was compared
107
+ against every requirement document, including 24 legacy T-SPECs under C-SPECs that have no REQ lineage and can never
108
+ have a vector, so triage here was `ambiguous` on every call. Coverage now counts documents that can carry a vector
109
+ (`unlineaged` reported separately); a partially covered layer decides with `semantic-partial:<n>` and
110
+ `missingLineages` disclosed; a configured layer that covers nothing still forces `ambiguous`.
111
+
8
112
  ## [0.31.2] - 2026-09-30
9
113
 
10
114
  ### Fixed
package/README.md CHANGED
@@ -23,6 +23,8 @@ Measured at `173b99650442` (specs `sha256:215f84d4e9f4`) — reproduce with `hol
23
23
 
24
24
  ### 🛡️ Currently Supported Features (Production Features)
25
25
 
26
+ - 🗜️ **Large answers are compressed, not cut, and new requirements are not blocked by a guess** *(new in 0.33.0)*: `spec_list`, `review_status` and `reverse_scan` answer by default with a compressed view — duplicates removed, digests dropped, what needs action first, anything left out counted with a note — and `detail: "full"` (or paging, or `spec_list({ ids })` for one spec) gives the complete answer. `requirement_triage` confirms a lineage only when both of its channels agree and the lineage mentions every code identifier the request names, so a requirement next to a finished one, or on an install without a semantic layer, can still be admitted. `maintenance_analyze` judges a Korean or Japanese request against unreadable files by its words and, on the cloud tier, by meaning; the pre-edit gate finds the analysis the session persisted; `spec_approve` names a spec's blockers instead of queueing an approval nobody could use; and `holmes-kit autonomy status`/`off` read the project default in `.mcp.json`, so `off` never claims OFF while autonomous approval is still on.
27
+ - 🔎 **The analysis tools decide on evidence about the request, and say what they could not decide** *(new in 0.32.0)*: measured on two repositories by point-in-time replay, `maintenance_analyze` had answered `ambiguous` for every request because a shell script anywhere in the tree counted against it — the classification now counts an unreadable language only when the change touches it, while the test scope stays as conservative as before (relaxing it too let narrowed scopes miss the commit's own tests). `confidence` carries `confidenceCalibrated: false`; persisted evidence records why a scope was `full` and `maintenance_calibration` reports how often each cause occurred; candidate specs come in relevance order. `requirement_triage` answers in summaries by default (`detail: "full"` for document text), counts semantic coverage over documents that can have a vector, and gives `existing-change`/`fulfilled` only when its lexical and semantic channels agree on the first-ranked lineage — a lineage the request cites is listed first but a citation is not evidence — otherwise `ambiguous`, which leaves a new requirement possible.
26
28
  - 🚦 **The gate only ever denies** *(changed in 0.31.0)*: an action Holmes does not deny is left to your harness's own permission flow — Claude Code and Codex get no permission decision, Antigravity gets `ask` (or `allow` for a read inside the workspace that git does not ignore). Earlier versions answered `allow`, which Claude Code treats as "bypassing permission prompt", so anything the shell model missed ran unconfirmed. In Claude Code's default mode you now see its confirmations again, as without Holmes.
27
29
  - 🪝 **The Codex gate loads again on codex-cli 0.155** *(new in 0.31.0)*: plugin hooks were removed upstream, so `init --agent codex` wires the Holmes PreToolUse and Stop kernels into the user-level `$CODEX_HOME/hooks.json`, keeps every hook it does not own, and `--remove` takes away only its own groups. Codex runs a user hook only after you trust it once with `/hooks`; Holmes never forges that trust, and `doctor` says so instead of claiming enforcement.
28
30
  - 🧭 **The shell gate judges by identity, from where the command really runs** *(new in 0.31.0)*: wiring files, the whole `.ax` store and the files inside it are protected as shell WORDS resolved against each segment's real base — a `cd` moves the base only when it is certain to have run, an uncertain or expanded one (`cd .a?`, a link made in the same command, `cd "$X"`) leaves it unknown and the command is judged at every base it could have produced, and the base starts at the harness's own working directory (the payload `cwd`, a Codex `workdir`), not the project root. Every evaluation runs under a fail-closed deadline wall. The Codex oracle asks the installed Codex whether your config loads — locally, over copies, with plugins and every proxy closed, `sqlite_home`/`analytics`/`otel` isolated from the user copy alone, and a verdict it could not obtain labelled `approximate`. Source walkers skip nested git working trees only when git says the tree is not the project's, read regular files only, and ask git once per scan; every reader on a gate path is linear in its input.
@@ -286,7 +288,7 @@ flowchart LR
286
288
  | `holmes-kit init --dry-run` | Preview files and configuration changes without writing |
287
289
  | `holmes-kit autonomy status` | Show the current autonomous-approval posture (project default + session envelope) |
288
290
  | `holmes-kit autonomy on --for 2h` | Self-drive low-risk specs for this session only (expiring; needs a TTY or `HOLMES_APPROVAL`) |
289
- | `holmes-kit autonomy off` | End session autonomy immediately |
291
+ | `holmes-kit autonomy off` | End session autonomy immediately; if the project default in `.mcp.json` still keeps autonomy on, it says so and exits 1 instead of claiming OFF |
290
292
  | `holmes-kit semantic-setup` | Download and verify the local `bge-m3` model (retry/recovery; shared across projects) |
291
293
  | `holmes-kit semantic-check` | Verify local inference **offline**, without downloading anything |
292
294
  | `holmes-kit semantic-key set` | Store the cloud-tier key outside the tree (stdin only, never argv) |
package/dist/.build-id CHANGED
@@ -1 +1 @@
1
- 8bd6277b-mumvdzzj
1
+ cd3e509f-muobw3d9
@@ -35,11 +35,13 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.parseForMinutes = parseForMinutes;
37
37
  exports.runAutonomy = runAutonomy;
38
- // @implements A-SPEC-553.1
38
+ // @implements A-SPEC-553.1, A-SPEC-553.2
39
39
  const fs = __importStar(require("node:fs"));
40
40
  const path = __importStar(require("node:path"));
41
41
  const risk_gate_1 = require("../guardrail/risk-gate");
42
42
  const autonomy_1 = require("../governance/autonomy");
43
+ const PROJECT_DEFAULT_ON = 'autonomous spec approval: ON (project default, .mcp.json) — governance-critical still ask you. '
44
+ + 'Turn it off by removing HOLMES_AUTONOMOUS_APPROVAL from .mcp.json (or holmes-kit init --no-autonomy).';
43
45
  const ledger_store_1 = require("../governance/ledger-store");
44
46
  const provenance_chain_1 = require("../governance/provenance-chain");
45
47
  /** `--for` accepts `2h` / `90m` / a bare number of hours. Minutes, capped at 7 days (like grants);
@@ -69,6 +71,11 @@ function runAutonomy(root, sub, forStr, io) {
69
71
  const envOn = typeof env[autonomy_1.AUTONOMY_ENV] === 'string' && env[autonomy_1.AUTONOMY_ENV] !== '';
70
72
  if (envOn)
71
73
  return { ok: true, exitCode: 0, message: 'autonomous spec approval: ON (project default, .mcp.json) — governance-critical still ask you' };
74
+ // @implements A-SPEC-553.2 — the same project default the server and the session banner read
75
+ // (A-SPEC-560.2). The CLI read only the shell environment, which never carries .mcp.json's env, and
76
+ // answered OFF while the server sealed specs autonomously.
77
+ if ((0, autonomy_1.projectDefaultAutonomy)(root))
78
+ return { ok: true, exitCode: 0, message: PROJECT_DEFAULT_ON };
72
79
  if ((0, autonomy_1.sessionAutonomyActive)(root, io.now)) {
73
80
  let expires = '';
74
81
  try {
@@ -112,6 +119,13 @@ function runAutonomy(root, sub, forStr, io) {
112
119
  }
113
120
  catch { /* audit is best-effort; the marker is gone either way */ }
114
121
  }
122
+ // @implements A-SPEC-553.2 — the emergency control never reports a de-escalation that did not happen
123
+ // (A-SPEC-558.1): with the project default (or the environment switch) still on, autonomy is still ON.
124
+ const envStillOn = typeof env[autonomy_1.AUTONOMY_ENV] === 'string' && env[autonomy_1.AUTONOMY_ENV] !== '';
125
+ if (envStillOn || (0, autonomy_1.projectDefaultAutonomy)(root)) {
126
+ return { ok: false, exitCode: 1, message: 'session autonomy ended, but autonomous spec approval is still ON: the project default in .mcp.json '
127
+ + '(HOLMES_AUTONOMOUS_APPROVAL) keeps it on — remove it from .mcp.json (or holmes-kit init --no-autonomy) to turn it off.' };
128
+ }
115
129
  return { ok: true, exitCode: 0, message: 'autonomous spec approval: OFF — every spec approval is human again' };
116
130
  }
117
131
  if (sub === 'on') {
@@ -37,7 +37,7 @@ exports.isLowRiskTarget = isLowRiskTarget;
37
37
  exports.evaluateEditEvidence = evaluateEditEvidence;
38
38
  exports.preEditEvidenceDecision = preEditEvidenceDecision;
39
39
  exports.loadEditEvidence = loadEditEvidence;
40
- // @implements A-SPEC-279
40
+ // @implements A-SPEC-279, A-SPEC-278.1
41
41
  // @implements A-SPEC-278
42
42
  // @implements A-SPEC-277
43
43
  // @implements A-SPEC-276
@@ -244,6 +244,52 @@ function preEditEvidenceDecision(verdict, mode) {
244
244
  ? { permissionDecision: 'deny', permissionDecisionReason: reason }
245
245
  : { permissionDecision: 'allow', permissionDecisionReason: reason };
246
246
  }
247
+ const PERSISTED_SCAN_LIMIT = 64;
248
+ const PERSISTED_MAX_BYTES = 2 * 1024 * 1024;
249
+ /**
250
+ * @implements A-SPEC-278.1 — with no declared digest (HOLMES_EVIDENCE is an environment variable a session
251
+ * cannot set), the analysis `maintenance_analyze({ persist: true })` wrote is found here: the newest of the
252
+ * 64 most recently written artifacts that was taken at the current HEAD and names the target in its
253
+ * prediction. The directory is a protected governance path a session cannot write, so this admits only
254
+ * what the tool persisted. Links and non-regular files are skipped (`lstat`), and so is anything over
255
+ * 2 MiB — bounded reads, the same discipline as every other state file the gate reads.
256
+ */
257
+ function newestPersistedAnalysis(projectRoot, target, currentHead) {
258
+ const dir = path.join(projectRoot, '.ax', 'evidence', 'maintenance');
259
+ let entries = [];
260
+ try {
261
+ entries = fs.readdirSync(dir).filter((n) => n.endsWith('.json')).flatMap((n) => {
262
+ const file = path.join(dir, n);
263
+ try {
264
+ const st = fs.lstatSync(file);
265
+ return st.isFile() && st.size <= PERSISTED_MAX_BYTES ? [{ file, mtime: st.mtimeMs }] : [];
266
+ }
267
+ catch {
268
+ return [];
269
+ }
270
+ });
271
+ }
272
+ catch {
273
+ return null;
274
+ }
275
+ let best = null;
276
+ for (const { file } of entries.sort((a, b) => b.mtime - a.mtime).slice(0, PERSISTED_SCAN_LIMIT)) {
277
+ let candidate;
278
+ try {
279
+ candidate = JSON.parse(fs.readFileSync(file, 'utf8'));
280
+ }
281
+ catch {
282
+ continue;
283
+ }
284
+ if (candidate?.graphBasis?.head !== currentHead)
285
+ continue;
286
+ if (!Array.isArray(candidate?.predicted?.files) || !candidate.predicted.files.includes(target))
287
+ continue;
288
+ if (best === null || String(candidate.recordedAt ?? '') > String(best.recordedAt ?? ''))
289
+ best = candidate;
290
+ }
291
+ return best;
292
+ }
247
293
  /**
248
294
  * @implements A-SPEC-278
249
295
  * The I/O adapter, kept apart from the pure core on purpose: everything above this line is decided
@@ -268,6 +314,9 @@ function loadEditEvidence(projectRoot, target, digest, currentHead) {
268
314
  }
269
315
  }
270
316
  }
317
+ else {
318
+ artifact = newestPersistedAnalysis(projectRoot, rel, currentHead);
319
+ }
271
320
  let currentTargetDigest = null;
272
321
  try {
273
322
  const resolved = path.resolve(projectRoot, rel);
@@ -1,5 +1,7 @@
1
1
  import { Spec } from '../../spec/spec-parser';
2
2
  import { SpecStore } from '../../spec/spec-store';
3
+ import { type ReverseScanReport } from '../../reverse/scan';
4
+ import type { Cluster } from '../../reverse/cluster';
3
5
  import { DraftResult } from '../../reverse/draft';
4
6
  import { AnchorMapping } from '../../reverse/anchor';
5
7
  export interface AdoptionContext {
@@ -8,6 +10,16 @@ export interface AdoptionContext {
8
10
  assertReadableRoot(tool: string, root: string): void;
9
11
  occupiedTarget(specs: Spec[]): string | undefined;
10
12
  }
13
+ type ScanView = Omit<ReverseScanReport, 'surfaceByCluster' | 'anchoredFiles'>;
14
+ /**
15
+ * @implements A-SPEC-746 — the adoption inventory as an agent reads it. Compression, not a cut:
16
+ * test matches are counted (each cluster already lists its tests), paths are relative to their
17
+ * cluster, unmatched tests are grouped by directory with only the non-template reasons kept, and a
18
+ * cluster whose every file is already anchored — not an adoption candidate — folds to its size.
19
+ * Unanchored clusters come first. Only if the view is still over `budget` are the last clusters
20
+ * reduced to their size, counted, with a note naming `detail: "full"`.
21
+ */
22
+ export declare function conciseReverseScan(report: ScanView, anchored: ReadonlySet<string>, budget?: number): Record<string, unknown>;
11
23
  export declare function createAdoptionHandlers(context: AdoptionContext): {
12
24
  /**
13
25
  * Read-only inventory of a brownfield target: candidate clusters, coverage, and what the scan
@@ -17,7 +29,8 @@ export declare function createAdoptionHandlers(context: AdoptionContext): {
17
29
  reverse_scan(a: {
18
30
  root: string;
19
31
  maxFlagged?: number;
20
- }): Promise<{
32
+ detail?: unknown;
33
+ }): Promise<Record<string, unknown> | {
21
34
  root: string;
22
35
  isGit: boolean;
23
36
  scanned: number;
@@ -25,8 +38,8 @@ export declare function createAdoptionHandlers(context: AdoptionContext): {
25
38
  candidates: number;
26
39
  anchored: number;
27
40
  unanchored: number;
28
- clusters: import("../../reverse/cluster").Cluster[];
29
- testClusters: import("../../reverse/cluster").Cluster[];
41
+ clusters: Cluster[];
42
+ testClusters: Cluster[];
30
43
  coverage: {
31
44
  structurallyResolved: number;
32
45
  inTestClusters: number;
@@ -116,3 +129,4 @@ export declare function createAdoptionHandlers(context: AdoptionContext): {
116
129
  refused: import("../../reverse/anchor").RefusedAnchor[];
117
130
  }>;
118
131
  };
132
+ export {};
@@ -1,5 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.conciseReverseScan = conciseReverseScan;
3
4
  exports.createAdoptionHandlers = createAdoptionHandlers;
4
5
  const spec_store_1 = require("../../spec/spec-store");
5
6
  const validator_1 = require("../../spec/validator");
@@ -8,6 +9,66 @@ const approval_blockers_1 = require("../../spec/approval-blockers");
8
9
  const scan_1 = require("../../reverse/scan");
9
10
  const draft_1 = require("../../reverse/draft");
10
11
  const anchor_1 = require("../../reverse/anchor");
12
+ const cmpText = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
13
+ const relativeTo = (dir, file) => dir === '.' || dir === '' || !file.startsWith(`${dir}/`) ? file : file.slice(dir.length + 1);
14
+ const TEMPLATE_UNMATCHED = /^no candidate file named /;
15
+ /**
16
+ * @implements A-SPEC-746 — the adoption inventory as an agent reads it. Compression, not a cut:
17
+ * test matches are counted (each cluster already lists its tests), paths are relative to their
18
+ * cluster, unmatched tests are grouped by directory with only the non-template reasons kept, and a
19
+ * cluster whose every file is already anchored — not an adoption candidate — folds to its size.
20
+ * Unanchored clusters come first. Only if the view is still over `budget` are the last clusters
21
+ * reduced to their size, counted, with a note naming `detail: "full"`.
22
+ */
23
+ function conciseReverseScan(report, anchored, budget = 28000) {
24
+ const fold = (c) => {
25
+ const anchoredCount = c.files.filter((f) => anchored.has(f)).length;
26
+ if (c.files.length > 0 && anchoredCount === c.files.length)
27
+ return { dir: c.dir, fileCount: c.files.length, anchored: true };
28
+ return { ...c, files: c.files.map((f) => relativeTo(c.dir, f)), testFiles: (c.testFiles ?? []).map((f) => relativeTo(c.dir, f)), anchoredCount };
29
+ };
30
+ const order = (cs) => cs.map(fold)
31
+ .sort((a, b) => Number('anchored' in a) - Number('anchored' in b) || cmpText(a.dir, b.dir));
32
+ const matchedVia = {};
33
+ for (const m of report.tests.matched)
34
+ matchedVia[m.via] = (matchedVia[m.via] ?? 0) + 1;
35
+ const unmatchedByDir = {};
36
+ for (const u of report.tests.unmatched) {
37
+ const cut = u.file.lastIndexOf('/');
38
+ const dir = cut < 0 ? '.' : u.file.slice(0, cut);
39
+ (unmatchedByDir[dir] ??= []).push(cut < 0 ? u.file : u.file.slice(cut + 1));
40
+ }
41
+ const unmatchedReasons = report.tests.unmatched.filter((u) => !TEMPLATE_UNMATCHED.test(u.reason));
42
+ const view = {
43
+ ...report,
44
+ clusters: order(report.clusters),
45
+ testClusters: order(report.testClusters),
46
+ tests: {
47
+ matchedTotal: report.tests.matched.length, matchedVia,
48
+ unmatchedTotal: report.tests.unmatched.length, unmatchedByDir,
49
+ ...(unmatchedReasons.length > 0 ? { unmatchedReasons } : {}),
50
+ },
51
+ };
52
+ let size = JSON.stringify(view).length;
53
+ let reduced = 0;
54
+ for (const key of ['testClusters', 'clusters']) {
55
+ const list = view[key];
56
+ for (let i = list.length - 1; i >= 0 && size > budget; i--) {
57
+ const c = list[i];
58
+ if (!('files' in c))
59
+ continue;
60
+ const small = { dir: c.dir, fileCount: c.files.length, anchoredCount: c.anchoredCount };
61
+ size -= JSON.stringify(c).length - JSON.stringify(small).length;
62
+ list[i] = small;
63
+ reduced++;
64
+ }
65
+ }
66
+ if (reduced > 0) {
67
+ view.clustersReduced = reduced;
68
+ view.note = `${reduced} cluster(s) are listed by size only to keep this answer small — call reverse_scan with detail: "full" for every file, or reverse_draft with cluster for one.`;
69
+ }
70
+ return view;
71
+ }
11
72
  function createAdoptionHandlers(context) {
12
73
  return {
13
74
  // @implements A-SPEC-126
@@ -20,6 +81,10 @@ function createAdoptionHandlers(context) {
20
81
  * repository is a supported case here, reported as `isGit: false`.
21
82
  */
22
83
  async reverse_scan(a) {
84
+ // @implements A-SPEC-746 — an unknown view is refused before anything is read.
85
+ if (a.detail !== undefined && a.detail !== 'summary' && a.detail !== 'full') {
86
+ return { ok: false, reason: 'detail must be "summary" (the default, compressed view) or "full" (the complete answer).' };
87
+ }
23
88
  // @implements A-SPEC-189 §10 (round 11) — `reverse_scan`/`reverse_draft` never call
24
89
  // `projectRootOf`, so §7's refusal marker never reached them and their own POINTED sentence
25
90
  // ("<root> is not a directory") arrived at the wire as a raw -32603 fault. A refusal about the
@@ -28,8 +93,11 @@ function createAdoptionHandlers(context) {
28
93
  // `surfaceByCluster` is drafting evidence, not reading material. On the calibration target it
29
94
  // is 11,460 characters across 15 clusters, and this response enters context on every scan —
30
95
  // paying that to READ what only DRAFTING consumes. `reverse_draft` reads it in-process instead.
31
- const { surfaceByCluster: _drafting, ...response } = (0, scan_1.reverseScan)(a.root, { maxFlagged: a.maxFlagged });
32
- return response;
96
+ // @implements A-SPEC-746 — `anchoredFiles` is the handler's input for folding, never the reader's.
97
+ const { surfaceByCluster: _drafting, anchoredFiles, ...response } = (0, scan_1.reverseScan)(a.root, { maxFlagged: a.maxFlagged });
98
+ if (a.detail === 'full')
99
+ return response;
100
+ return conciseReverseScan(response, new Set(anchoredFiles));
33
101
  },
34
102
  /**
35
103
  * Draft H-SPEC/A-SPEC/T-SPEC documents for the recovered clusters under an EXISTING parent REQ.
@@ -39,7 +39,7 @@ exports.warmRequirementSemanticCache = warmRequirementSemanticCache;
39
39
  exports.headOf = headOf;
40
40
  exports.refreshSemanticVectors = refreshSemanticVectors;
41
41
  exports.createGraphOperationsHandlers = createGraphOperationsHandlers;
42
- // @implements A-SPEC-719, A-SPEC-734
42
+ // @implements A-SPEC-719, A-SPEC-734, A-SPEC-741.1
43
43
  // @implements A-SPEC-614, A-SPEC-613, A-SPEC-100.2, A-SPEC-121.2, A-SPEC-128, A-SPEC-139, A-SPEC-189, A-SPEC-280, A-SPEC-282, A-SPEC-283, A-SPEC-419, A-SPEC-433, A-SPEC-469, A-SPEC-478, A-SPEC-568.1, A-SPEC-568.2, A-SPEC-569.1, A-SPEC-569.2, A-SPEC-569.3, A-SPEC-589
44
44
  // @implements A-SPEC-632
45
45
  const fs = __importStar(require("node:fs"));
@@ -54,6 +54,7 @@ const trace_gaps_1 = require("../../rtm/trace-gaps");
54
54
  const tier_1 = require("../../semantic/tier");
55
55
  const vector_cache_1 = require("../../semantic/vector-cache");
56
56
  const embedder_1 = require("../../semantic/embedder");
57
+ const unreadable_paths_1 = require("../../semantic/unreadable-paths");
57
58
  const bounded_io_1 = require("../../project/bounded-io");
58
59
  const vector_coverage_1 = require("../../semantic/vector-coverage");
59
60
  // @implements A-SPEC-283 — bumped whenever the graph's node/edge shape changes, so a store written
@@ -104,6 +105,10 @@ async function warmSemanticCache(root, scanned) {
104
105
  const w = await rt.warm(docTexts);
105
106
  if (docTexts.length > 0 && w.computed + w.cached === 0)
106
107
  return { status: 'unavailable', tier: rt.label };
108
+ // @implements A-SPEC-741.1 — the unreadable files' path vectors a non-ASCII request is judged by.
109
+ // Best effort and NOT counted: the outcome is a persisted discharge shape (A-SPEC-632) that describes
110
+ // the source warm, and a missing path vector only keeps a language relevant.
111
+ await (0, unreadable_paths_1.warmUnreadablePaths)(rt, root);
107
112
  // @implements A-SPEC-683 — `stored` is measured by refreshSemanticVectors, NOT returned here.
108
113
  // This outcome flows into entity_integrate's discharge record, a PERSISTED artifact whose shape
109
114
  // A-SPEC-632 pins by toEqual and validates by RECORD_KEYS; widening it is a persisted-artifact
@@ -34,12 +34,13 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.createMaintenanceAnalysisHandlers = createMaintenanceAnalysisHandlers;
37
- // @implements A-SPEC-612, A-SPEC-100.2, A-SPEC-128, A-SPEC-189, A-SPEC-267, A-SPEC-268, A-SPEC-269, A-SPEC-277, A-SPEC-283, A-SPEC-290, A-SPEC-292, A-SPEC-293, A-SPEC-378, A-SPEC-388, A-SPEC-418, A-SPEC-478, A-SPEC-571.2, A-SPEC-573.4, A-SPEC-578.5, A-SPEC-734
37
+ // @implements A-SPEC-745, A-SPEC-741, A-SPEC-741.1, A-SPEC-612, A-SPEC-100.2, A-SPEC-128, A-SPEC-189, A-SPEC-267, A-SPEC-268, A-SPEC-269, A-SPEC-277, A-SPEC-283, A-SPEC-290, A-SPEC-292, A-SPEC-293, A-SPEC-378, A-SPEC-388, A-SPEC-418, A-SPEC-478, A-SPEC-571.2, A-SPEC-573.4, A-SPEC-578.5, A-SPEC-734
38
38
  const fs = __importStar(require("node:fs"));
39
39
  const path = __importStar(require("node:path"));
40
40
  const node_child_process_1 = require("node:child_process");
41
41
  const spec_types_1 = require("../../spec/spec-types");
42
42
  const cpg_scanner_1 = require("../../cpg/cpg-scanner");
43
+ const unreadable_paths_1 = require("../../semantic/unreadable-paths");
43
44
  const rtm_graph_1 = require("../../rtm/rtm-graph");
44
45
  const rtm_builder_1 = require("../../rtm/rtm-builder");
45
46
  const test_scope_1 = require("../../rtm/test-scope");
@@ -75,20 +76,21 @@ function createMaintenanceAnalysisHandlers(context) {
75
76
  head = (0, node_child_process_1.execFileSync)('git', ['-C', root, 'rev-parse', 'HEAD'], { maxBuffer: bounded_io_1.GIT_MAX_BUFFER, timeout: 5000, encoding: 'utf8', env: (0, root_1.cleanSubprocessEnv)(), stdio: ['ignore', 'pipe', 'pipe'] }).trim();
76
77
  }
77
78
  catch { /* non-git */ }
78
- const supportedExtensions = new Set(cpg_scanner_1.SCANNABLE_EXTENSIONS);
79
- const knownCodeExtensions = new Set(['.rb', '.php', '.kt', '.kts', '.swift', '.scala', '.sh', '.ex', '.exs', '.lua', '.r']);
80
79
  const unsupportedLanguages = new Set();
80
+ // @implements A-SPEC-741 — the paths too, so the analysis can tell an unreadable file that may
81
+ // be this request's target from one that is unrelated. Bounded: a vendored tree must not grow it.
82
+ // @implements A-SPEC-741.1 — enumerated by the same function the path-vector warm uses.
83
+ let unsupportedFiles = [];
84
+ let unsupportedFilesTruncated = false;
81
85
  try {
82
86
  // A-SPEC-734 (round 12): a root whose git timed out is not asked again (the shared memory).
83
87
  if ((0, bounded_io_1.gitRootBlocked)(root))
84
88
  throw new Error('git blocked on this root');
85
- // A-SPEC-734 (round 15): with the fsmonitor hook off.
86
- const files = (0, node_child_process_1.execFileSync)('git', ['-c', 'core.fsmonitor=false', '-C', root, 'ls-files', '-z', '--cached', '--others', '--exclude-standard'], { timeout: 5000, encoding: 'utf8', env: (0, root_1.cleanSubprocessEnv)(), maxBuffer: bounded_io_1.GIT_MAX_BUFFER }).split('\0'); // round 16: the shared bound
87
- for (const file of files) {
88
- const ext = path.extname(file).toLowerCase();
89
- if (knownCodeExtensions.has(ext) && !supportedExtensions.has(ext))
90
- unsupportedLanguages.add(ext);
91
- }
89
+ const listed = (0, unreadable_paths_1.listUnreadableFiles)(root);
90
+ for (const language of listed.languages)
91
+ unsupportedLanguages.add(language);
92
+ unsupportedFiles = listed.files;
93
+ unsupportedFilesTruncated = listed.truncated;
92
94
  }
93
95
  catch (e) {
94
96
  (0, bounded_io_1.noteGitFailure)(root, e);
@@ -125,6 +127,8 @@ function createMaintenanceAnalysisHandlers(context) {
125
127
  scannedFiles: scanned.length,
126
128
  skippedFiles: skipped.map((entry) => entry.file),
127
129
  unsupportedLanguages: [...unsupportedLanguages],
130
+ unsupportedFiles,
131
+ ...(unsupportedFilesTruncated ? { unsupportedFilesTruncated: true } : {}),
128
132
  historyStatus: 'not-requested',
129
133
  },
130
134
  };
@@ -172,7 +176,9 @@ function createMaintenanceAnalysisHandlers(context) {
172
176
  const directSeed = preliminary.candidates
173
177
  .flatMap((candidate) => candidate.symbols)
174
178
  .flatMap((qualifiedName) => graph.codeNodeIds(qualifiedName))[0];
175
- const specSeed = preliminary.candidateSpecs.find((id) => id.startsWith('A-SPEC-'));
179
+ // A-SPEC-745 keeps every computation over the candidate specs as it was: the emitted list is now
180
+ // in relevance order, so the seed is taken from the id-sorted set exactly as before.
181
+ const specSeed = [...preliminary.candidateSpecs].sort((a, b) => a.localeCompare(b)).find((id) => id.startsWith('A-SPEC-'));
176
182
  const seedId = directSeed ?? (specSeed ? `SPEC:${specSeed}` : undefined);
177
183
  const budget = Math.max(100, Math.min(10_000, Math.floor(a.contextBudget ?? 2_000)));
178
184
  const contextBundle = seedId
@@ -39,6 +39,12 @@ export declare function createMaintenanceEvidenceHandlers(context: MaintenanceEv
39
39
  falseNegatives: number;
40
40
  minSamples: number;
41
41
  status: "measured" | "insufficient-data";
42
+ scopeCauses: {
43
+ full: number;
44
+ narrow: number;
45
+ unrecorded: number;
46
+ causes: Record<string, number>;
47
+ };
42
48
  }>;
43
49
  };
44
50
  export {};
@@ -10,6 +10,26 @@ type PhaseRow = {
10
10
  type: string;
11
11
  status: string;
12
12
  };
13
+ export declare function limitProblem(limit: unknown): string | undefined;
14
+ export declare function phasePage<R extends PhaseRow>(all: R[], a: {
15
+ ids?: string[];
16
+ type?: string;
17
+ status?: string;
18
+ limit?: number;
19
+ cursor?: string;
20
+ }): {
21
+ unknownIds?: string[] | undefined;
22
+ unknownIdsTotal?: number | undefined;
23
+ nextCursor?: string | undefined;
24
+ summary: {
25
+ total: number;
26
+ counts: Record<string, Record<string, number>>;
27
+ notApproved: R[];
28
+ notApprovedTotal: number;
29
+ };
30
+ specs: R[];
31
+ matched: number;
32
+ };
13
33
  export declare function createPhaseQueryHandlers(context: PhaseQueryContext): {
14
34
  phase_status(a: {
15
35
  root?: string;
@@ -29,10 +49,18 @@ export declare function createPhaseQueryHandlers(context: PhaseQueryContext): {
29
49
  summary: {
30
50
  total: number;
31
51
  counts: Record<string, Record<string, number>>;
32
- notApproved: PhaseRow[];
52
+ notApproved: {
53
+ id: string;
54
+ type: import("../../spec/spec-types").SpecType;
55
+ status: "draft" | "review" | "approved" | "outdated";
56
+ }[];
33
57
  notApprovedTotal: number;
34
58
  };
35
- specs: PhaseRow[];
59
+ specs: {
60
+ id: string;
61
+ type: import("../../spec/spec-types").SpecType;
62
+ status: "draft" | "review" | "approved" | "outdated";
63
+ }[];
36
64
  matched: number;
37
65
  ok?: undefined;
38
66
  reason?: undefined;
@@ -33,8 +33,10 @@ var __importStar = (this && this.__importStar) || (function () {
33
33
  };
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.limitProblem = limitProblem;
37
+ exports.phasePage = phasePage;
36
38
  exports.createPhaseQueryHandlers = createPhaseQueryHandlers;
37
- // @implements A-SPEC-606, A-SPEC-100.2, A-SPEC-735
39
+ // @implements A-SPEC-606, A-SPEC-100.2, A-SPEC-735, A-SPEC-746
38
40
  const fs = __importStar(require("node:fs"));
39
41
  const path = __importStar(require("node:path"));
40
42
  const phase_1 = require("../../guardrail/phase");
@@ -51,6 +53,7 @@ const byId = (a, b) => a.id.localeCompare(b.id, 'en', { numeric: true })
51
53
  || codepoint(a.id, b.id) || codepoint(a.type, b.type) || codepoint(a.status, b.status);
52
54
  const CURSOR_SEP = '\u0001';
53
55
  const UNKNOWN_SHOWN = 50;
56
+ // @implements A-SPEC-746 — exported so spec_list pages by the same proved rules.
54
57
  function limitProblem(limit) {
55
58
  if (limit === undefined || limit === null)
56
59
  return undefined;
@@ -58,6 +61,7 @@ function limitProblem(limit) {
58
61
  return undefined;
59
62
  return `limit은 1..${PAGE_MAX} 범위의 정수여야 합니다 (받은 값: ${JSON.stringify(limit)}).`;
60
63
  }
64
+ // @implements A-SPEC-746 — generic over the row, so spec_list's extra fields (parent, legacy) travel.
61
65
  function phasePage(all, a) {
62
66
  const rows = [...all].sort(byId);
63
67
  // @implements A-SPEC-735 (round 2) — Maps, never assignment into a plain object: `type: __proto__`