@holmes-lab/holmes-kit 0.27.0 → 0.29.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 (62) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +21 -17
  3. package/dist/.build-id +1 -1
  4. package/dist/holmes/cli/agents-guidance-command.d.ts +9 -0
  5. package/dist/holmes/cli/agents-guidance-command.js +61 -0
  6. package/dist/holmes/cli/agents-guidance-file.d.ts +7 -0
  7. package/dist/holmes/cli/agents-guidance-file.js +86 -0
  8. package/dist/holmes/cli/agents-guidance-history.d.ts +10 -0
  9. package/dist/holmes/cli/agents-guidance-history.js +35 -0
  10. package/dist/holmes/cli/agents-guidance-plan.d.ts +11 -0
  11. package/dist/holmes/cli/agents-guidance-plan.js +81 -0
  12. package/dist/holmes/cli/agents-guidance.d.ts +1 -0
  13. package/dist/holmes/cli/agents-guidance.js +40 -0
  14. package/dist/holmes/cli/agents.d.ts +3 -19
  15. package/dist/holmes/cli/agents.js +12 -108
  16. package/dist/holmes/cli/doctor-guidance.d.ts +2 -0
  17. package/dist/holmes/cli/doctor-guidance.js +61 -0
  18. package/dist/holmes/cli/doctor.d.ts +2 -0
  19. package/dist/holmes/cli/doctor.js +29 -1
  20. package/dist/holmes/cli/index.js +31 -3
  21. package/dist/holmes/cli/init.js +32 -5
  22. package/dist/holmes/cli/upgrade.js +23 -26
  23. package/dist/holmes/cli/worktree-readiness.d.ts +6 -0
  24. package/dist/holmes/cli/worktree-readiness.js +81 -0
  25. package/dist/holmes/cpg/ast-mutation.d.ts +2 -0
  26. package/dist/holmes/cpg/ast-mutation.js +4 -2
  27. package/dist/holmes/cpg/foundation/cfg.d.ts +10 -0
  28. package/dist/holmes/cpg/foundation/cfg.js +27 -1
  29. package/dist/holmes/mcp/handlers/graph-operations.d.ts +7 -0
  30. package/dist/holmes/mcp/handlers/graph-operations.js +25 -1
  31. package/dist/holmes/mcp/handlers/requirement-triage.d.ts +116 -0
  32. package/dist/holmes/mcp/handlers/requirement-triage.js +185 -0
  33. package/dist/holmes/mcp/handlers/workspace-preflight.d.ts +9 -0
  34. package/dist/holmes/mcp/handlers/workspace-preflight.js +13 -0
  35. package/dist/holmes/mcp/handlers.d.ts +157 -46
  36. package/dist/holmes/mcp/handlers.js +16 -3
  37. package/dist/holmes/mcp/requirement-triage-evidence.d.ts +11 -0
  38. package/dist/holmes/mcp/requirement-triage-evidence.js +79 -0
  39. package/dist/holmes/mcp/tool-schemas.js +19 -1
  40. package/dist/holmes/project/workspace-checkout.d.ts +8 -0
  41. package/dist/holmes/project/workspace-checkout.js +74 -0
  42. package/dist/holmes/project/workspace-preflight.d.ts +24 -0
  43. package/dist/holmes/project/workspace-preflight.js +99 -0
  44. package/dist/holmes/review/condition-hunk-replay.d.ts +33 -0
  45. package/dist/holmes/review/condition-hunk-replay.js +112 -0
  46. package/dist/holmes/review/condition-hunk-resolution.d.ts +65 -0
  47. package/dist/holmes/review/condition-hunk-resolution.js +207 -0
  48. package/dist/holmes/review/requirement-triage-benchmark.d.ts +45 -0
  49. package/dist/holmes/review/requirement-triage-benchmark.js +72 -0
  50. package/dist/holmes/review/requirement-triage.d.ts +61 -0
  51. package/dist/holmes/review/requirement-triage.js +143 -0
  52. package/dist/holmes/semantic/local-model.d.ts +3 -3
  53. package/dist/holmes/semantic/local-model.js +10 -12
  54. package/dist/holmes/semantic/model-cache.d.ts +15 -6
  55. package/dist/holmes/semantic/model-cache.js +77 -21
  56. package/dist/holmes/semantic/tier.d.ts +5 -1
  57. package/dist/holmes/semantic/tier.js +7 -6
  58. package/dist/holmes/semantic/vector-coverage.d.ts +17 -0
  59. package/dist/holmes/semantic/vector-coverage.js +37 -0
  60. package/docs/install-guide.md +73 -24
  61. package/package.json +1 -1
  62. package/playbooks/superpowers-compat/PLAYBOOK.md +46 -0
@@ -44,9 +44,11 @@ exports.mergeMarketplaceJson = mergeMarketplaceJson;
44
44
  exports.mergeWiringFile = mergeWiringFile;
45
45
  exports.agentFiles = agentFiles;
46
46
  exports.agentLinks = agentLinks;
47
- // @implements A-SPEC-202, A-SPEC-250, A-SPEC-341
47
+ // @implements A-SPEC-708, A-SPEC-707, A-SPEC-202, A-SPEC-250, A-SPEC-341
48
48
  // @implements A-SPEC-442
49
49
  // @implements A-SPEC-193
50
+ const agents_guidance_plan_1 = require("./agents-guidance-plan");
51
+ const agents_guidance_1 = require("./agents-guidance");
50
52
  const path = __importStar(require("node:path"));
51
53
  const node_child_process_1 = require("node:child_process");
52
54
  const mcp_launcher_1 = require("./mcp-launcher");
@@ -193,117 +195,19 @@ const hooksJson = (packageRoot) => `${JSON.stringify({
193
195
  Stop: [antigravityHookEntry(packageRoot, 'holmes-stop-antigravity.js')],
194
196
  },
195
197
  }, null, 2)}\n`;
196
- const AGENTS_MD = (enforced) => `# Holmes-Kit — Workspace Operational Discipline
197
-
198
- This repository operates under **No Spec, No Code** governance. An approved specification MUST exist before writing source or test code.
199
-
200
- ## 3 Core Operational Rules
201
-
202
- 1. **Tool-First Principle (NO Workaround Scripts)**:
203
- - Creating or mutating \`.ax/specs\` or governance ledgers via arbitrary temporary scripts (\`/tmp/*.js\`) is strictly forbidden.
204
- - \`spec_slice_init\` and \`spec_create\` SCAFFOLD spec documents; \`spec_slice_approve\` and \`spec_approve\` SEAL them. Use these tools for those two acts — never a script.
205
- - **Writing the body is editing the file.** After scaffolding, fill the \`TODO\` placeholders by editing the generated spec markdown in \`.ax/specs/\` with your normal editor. This is the expected authoring path, not a workaround — no MCP tool takes section text.
206
- - A REQ's \`## Success Criteria\` is scaffolded EMPTY on purpose, because a generator must not invent what "satisfied" means. Approval is refused until you write observable criteria there.
207
-
208
- 2. **Anchor-First Principle (Mandatory Code Anchors)**:
209
- - When creating or modifying source code and test files, line 1 MUST include an explicit anchor comment: \`// @\` + \`implements A-SPEC-XXX\`.
210
-
211
- 3. **Remediation Protocol (NO Guardrail Reverse Engineering)**:
212
- - When a tool call is denied by a hook gate, DO NOT inspect guardrail source code (\`pre-tool-use.ts\`, \`phase.ts\`) or attempt to write bypass code.
213
- - Immediately follow the 3-step remediation instructions provided in the refusal message or invoke the \`spec_remediate\` MCP tool / \`holmes-remediation\` playbook skill.
214
-
215
- ## Procedure
216
-
217
- 1. Run \`spec_slice_init\` or \`spec_create\` to scaffold REQ -> H-SPEC -> A-SPEC, then edit the generated markdown to replace every \`TODO\` and to write the REQ's Success Criteria.
218
- 2. Approve specs via \`spec_slice_approve\` or \`spec_approve\`.
219
- 3. **Before editing source**, run \`maintenance_analyze({ root, request, persist: true })\` and keep the digest it returns — that persisted analysis is what the pre-edit evidence gate checks.
220
- 4. **Write tests first** and verify failure (RED stage).
221
- 5. Approve the mirroring T-SPEC (\`A-SPEC-188\` -> \`T-SPEC-188\`).
222
- 6. Implement source code (GREEN stage).
223
-
224
- Use \`spec_next\` to check the next required governance step. Use \`phase_check\` to verify action permissions ahead of execution. Use \`impact_gate_check\` to ask what the pre-edit evidence gate would say about an edit — it is advisory and blocks nothing, so it answers the same way in every harness.
225
-
226
- ## Enforcement in this Harness
227
-
228
- ${enforced
229
- ? `Gates are **enforced**. Tool calls that write un-anchored code or target unapproved specifications will be denied. Unresolved critical findings block completion.`
230
- : `This harness does not have measured **hook enforcement points**. Holmes-Kit provides tools and guidance here without active gate blocking.`}
231
- `;
198
+ const AGENTS_MD = (_enforced) => (0, agents_guidance_1.renderCommonGuidance)();
232
199
  exports.AGENTS_MD = AGENTS_MD;
233
- exports.MANAGED_BEGIN = '<!-- holmes-kit:managed:begin -->';
234
- exports.MANAGED_END = '<!-- holmes-kit:managed:end -->';
235
- const PRESERVED_NOTE = '<!-- kept from this file by holmes-kit init — holmes-kit does not write below this line -->';
236
- /**
237
- * @implements A-SPEC-576.2
238
- * The regeneration that keeps what it did not write.
239
- *
240
- * Measured cause: `init` rewrote AGENTS.md from the template, deleting the ADR-018 parity rule a
241
- * commit had added the day before — and said nothing, so the loss was found weeks later by grep.
242
- * Generated text now lives inside a MANAGED BLOCK; everything outside it belongs to the person
243
- * whose repository this is.
244
- *
245
- * PURE, and it takes the whole file rather than a path: the caller reads `before` during init's
246
- * COMPUTE phase, so a dry-run predicts the same bytes the real run writes (A-SPEC-190 §9).
247
- *
248
- * `preserved` is the report, not a courtesy. A run that moved something and returned an empty list
249
- * would be the same silent loss in a new costume.
250
- */
251
- function mergeAgentsMd(existing, generated) {
252
- const block = exports.MANAGED_BEGIN + '\n' + (generated.endsWith('\n') ? generated : generated + '\n') + exports.MANAGED_END + '\n';
253
- if (existing === null || existing === '')
254
- return { content: block, preserved: [], note: null };
255
- const b = existing.indexOf(exports.MANAGED_BEGIN);
256
- const e = existing.indexOf(exports.MANAGED_END);
257
- if (b !== -1 && e > b) {
258
- // The ordinary case once a file has been through here: swap the block, and do not touch a
259
- // single byte on either side of it.
260
- const body = generated.endsWith('\n') ? generated : generated + '\n';
261
- return {
262
- content: existing.slice(0, b) + exports.MANAGED_BEGIN + '\n' + body + exports.MANAGED_END + existing.slice(e + exports.MANAGED_END.length),
263
- preserved: [],
264
- note: null,
265
- };
266
- }
267
- // LEGACY: a file written before the markers existed — every AGENTS.md in the field today. Its
268
- // lines are compared to the generated ones, and whatever the generator never wrote is carried
269
- // below the block. Line terminators are kept as read, so a CRLF checkout stays CRLF.
270
- const known = new Set(generated.split(/\r?\n/).map((l) => l.trim()).filter((l) => l !== ''));
271
- const lines = existing.split(/(?<=\n)/);
272
- const runs = [];
273
- let run = [];
274
- let pendingBlanks = [];
275
- for (const line of lines) {
276
- const t = line.trim();
277
- if (t === '') {
278
- if (run.length > 0)
279
- pendingBlanks.push(line);
280
- continue;
281
- }
282
- if (known.has(t)) {
283
- run = closeRun(runs, run);
284
- pendingBlanks = [];
285
- continue;
286
- }
287
- // A blank line INSIDE a run is part of it; blanks trailing a run are not.
288
- run.push(...pendingBlanks, line);
289
- pendingBlanks = [];
290
- }
291
- closeRun(runs, run);
292
- if (runs.length === 0)
293
- return { content: block, preserved: [], note: null };
294
- const preserved = runs.map((r) => (r.find((l) => l.trim() !== '') ?? '').trim());
200
+ var agents_guidance_plan_2 = require("./agents-guidance-plan");
201
+ Object.defineProperty(exports, "MANAGED_BEGIN", { enumerable: true, get: function () { return agents_guidance_plan_2.MANAGED_BEGIN; } });
202
+ Object.defineProperty(exports, "MANAGED_END", { enumerable: true, get: function () { return agents_guidance_plan_2.MANAGED_END; } });
203
+ function mergeAgentsMd(existing, _generated) {
204
+ const plan = (0, agents_guidance_plan_1.planGuidance)(existing);
295
205
  return {
296
- content: block + '\n' + PRESERVED_NOTE + '\n\n' + runs.map((r) => r.join('')).join('\n'),
297
- preserved,
298
- note: `kept ${runs.length} section(s) this generator did not write`,
206
+ content: plan.after ?? existing ?? '', preserved: plan.preserved,
207
+ note: plan.after === null ? `guidance conflict: ${plan.reasons.join(' ')}`
208
+ : plan.reasons.length ? plan.reasons.join(' ') : null,
299
209
  };
300
210
  }
301
- /** Close the current run into `runs` (dropping an empty one) and hand back a fresh one. */
302
- function closeRun(runs, run) {
303
- if (run.length > 0)
304
- runs.push(run);
305
- return [];
306
- }
307
211
  const HOLMES = 'holmes-kit';
308
212
  /** Parse, or explain why not. An unreadable file is never replaced: silently deleting it is the defect. */
309
213
  function parseOr(before, ours, what) {
@@ -0,0 +1,2 @@
1
+ import type { Check } from './doctor-check';
2
+ export declare function guidanceChecks(packageRoot: string, target: string): Check[];
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.guidanceChecks = guidanceChecks;
37
+ // @implements A-SPEC-710
38
+ const fs = __importStar(require("node:fs"));
39
+ const path = __importStar(require("node:path"));
40
+ const agents_guidance_plan_1 = require("./agents-guidance-plan");
41
+ const agents_guidance_file_1 = require("./agents-guidance-file");
42
+ function guidanceChecks(packageRoot, target) {
43
+ const file = path.join(target, 'AGENTS.md');
44
+ let version = 'unknown';
45
+ try {
46
+ version = String(JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8')).version ?? 'unknown');
47
+ }
48
+ catch { /* report unknown version explicitly */ }
49
+ try {
50
+ const plan = (0, agents_guidance_plan_1.planGuidance)((0, agents_guidance_file_1.readGuidanceFile)(file));
51
+ const level = plan.after === null ? 'FAIL' : plan.state === 'current' ? 'PASS' : 'WARN';
52
+ return [{ name: 'managed AGENTS guidance', level,
53
+ detail: `${file}: ${plan.state}; installed package ${version}. ${plan.reasons.join(' ')} File currency does not prove active-session loading or hook enforcement.`,
54
+ ...(level === 'PASS' ? {} : { fix: plan.after === null
55
+ ? `Review the named conflict in ${file}; preserve project rules, then run guidance check --target "${target}".`
56
+ : `holmes-kit guidance refresh --target "${target}" --dry-run; review, then run without --dry-run.` }) }];
57
+ }
58
+ catch (e) {
59
+ return [{ name: 'managed AGENTS guidance', level: 'FAIL', detail: `${file}: ${String(e)}; installed package ${version}.` }];
60
+ }
61
+ }
@@ -13,9 +13,11 @@ export declare function resolvesToPackage(filePath: string, packageRoot: string)
13
13
  */
14
14
  import type { Check, Level } from './doctor-check';
15
15
  export type { Check, Level } from './doctor-check';
16
+ import type { Agent } from './agents';
16
17
  export interface DoctorOptions {
17
18
  run?: ProbeRunner;
18
19
  autoFix?: boolean;
20
+ agent?: Agent;
19
21
  }
20
22
  /**
21
23
  * Environment variables removed before spawning a probe.
@@ -53,6 +53,8 @@ exports.wiringHandshakeChecks = wiringHandshakeChecks;
53
53
  exports.semanticCoverageCheck = semanticCoverageCheck;
54
54
  exports.semanticTierVerdict = semanticTierVerdict;
55
55
  exports.detectTreeKeyTemporary = detectTreeKeyTemporary;
56
+ // @implements A-SPEC-704, A-SPEC-710, A-SPEC-712
57
+ const doctor_guidance_1 = require("./doctor-guidance");
56
58
  // @implements A-SPEC-264, A-SPEC-423, A-SPEC-549.1, A-SPEC-590
57
59
  // @implements A-SPEC-594
58
60
  // @implements A-SPEC-592
@@ -114,6 +116,7 @@ function resolvesToPackage(filePath, packageRoot) {
114
116
  return false;
115
117
  }
116
118
  }
119
+ const worktree_readiness_1 = require("./worktree-readiness");
117
120
  const GRAMMARS = [
118
121
  'tree-sitter-typescript', 'tree-sitter-python', 'tree-sitter-c-sharp', 'tree-sitter-java',
119
122
  'tree-sitter-go', 'tree-sitter-rust', 'tree-sitter-cpp',
@@ -421,7 +424,7 @@ function resolveWiringPath(target, arg) {
421
424
  return path.isAbsolute(arg) ? arg : path.resolve(target, arg);
422
425
  }
423
426
  async function runDoctor(packageRoot, target, opts, extraChecks) {
424
- const checks = [];
427
+ const checks = (0, doctor_guidance_1.guidanceChecks)(packageRoot, target ?? process.cwd());
425
428
  const add = (name, level, detail, fix) => checks.push({ name, level, detail, fix });
426
429
  // 1. Build output — also the "prepare didn't run" detector.
427
430
  const serverJs = path.join(packageRoot, 'dist', 'holmes', 'mcp', 'server.js');
@@ -1323,6 +1326,7 @@ async function runDoctor(packageRoot, target, opts, extraChecks) {
1323
1326
  if (ci)
1324
1327
  checks.push(ci);
1325
1328
  }
1329
+ checks.push(...(0, worktree_readiness_1.worktreeReadinessChecks)(packageRoot, target ?? process.cwd(), { agent: opts?.agent }));
1326
1330
  if (extraChecks) {
1327
1331
  checks.push(...extraChecks);
1328
1332
  }
@@ -1808,6 +1812,30 @@ function semanticTierVerdict(t) {
1808
1812
  fix: 'Run holmes-kit semantic-check for actual offline inference; if unavailable, run holmes-kit semantic-setup.',
1809
1813
  };
1810
1814
  }
1815
+ // @implements A-SPEC-712 — a cache directory is only a candidate. The receipt is written after
1816
+ // successful offline inference, so its absence or a fingerprint mismatch is degraded rather than
1817
+ // a normal first-install state. Tell the user whether setup will verify existing assets or must
1818
+ // fetch them, without pretending the local tier can answer meanwhile.
1819
+ if (t.localRuntimePresent && t.localState) {
1820
+ const changed = t.localState === 'stale-receipt';
1821
+ const invalid = t.localState === 'invalid-receipt';
1822
+ const missing = t.localState === 'missing-cache';
1823
+ const detail = missing
1824
+ ? 'Semantic search tier: unavailable — the local runtime is installed but the BGE-M3 cache is absent.'
1825
+ : changed
1826
+ ? 'Semantic search tier: degraded — the changed BGE-M3 cache no longer matches its verified-inference receipt.'
1827
+ : invalid
1828
+ ? 'Semantic search tier: degraded — the BGE-M3 readiness receipt is invalid, so cached assets are not trusted.'
1829
+ : 'Semantic search tier: degraded — an existing BGE-M3 cache has not completed verified offline inference.';
1830
+ const fix = missing
1831
+ ? 'Run `holmes-kit semantic-setup` to download and verify BGE-M3 offline.'
1832
+ : changed
1833
+ ? 'Run `holmes-kit semantic-setup` to re-verify the changed BGE-M3 cache offline.'
1834
+ : invalid
1835
+ ? 'Run `holmes-kit semantic-setup` to replace the invalid BGE-M3 readiness receipt.'
1836
+ : 'Run `holmes-kit semantic-setup` to verify the existing BGE-M3 cache offline.';
1837
+ return { level: 'WARN', detail, fix };
1838
+ }
1811
1839
  // @implements A-SPEC-594 — two different 'none' states need two different sentences. When the
1812
1840
  // runtime is already installed, telling the user to install it is noise; the missing piece is
1813
1841
  // the model, and the command that fetches it is the whole fix. Both stay PASS: a user who never
@@ -37,6 +37,7 @@ exports.isBrokenPipe = void 0;
37
37
  exports.packageRoot = packageRoot;
38
38
  exports.main = main;
39
39
  exports.installPipeGuard = installPipeGuard;
40
+ // @implements A-SPEC-704, A-SPEC-709
40
41
  // @implements A-SPEC-549.2
41
42
  // @implements A-SPEC-591, A-SPEC-626
42
43
  const cli_execution_1 = require("./cli-execution");
@@ -76,9 +77,10 @@ function packageRoot() {
76
77
  * REQ-144's "cannot decide is not permission", applied to CLI arguments.
77
78
  */
78
79
  const KNOWN_FLAGS = {
80
+ guidance: ['help', 'target', 'dry-run'],
79
81
  init: ['help', 'target', 'mode', 'specs-dir', 'settings', 'matcher', 'dry-run', 'no-mcp', 'remove', 'force', 'agent', 'mcp-launcher', 'autonomy', 'no-autonomy'],
80
82
  autonomy: ['help', 'target', 'for'],
81
- doctor: ['help', 'target', 'json'],
83
+ doctor: ['help', 'target', 'json', 'agent'],
82
84
  // @implements A-SPEC-702 — a statement, not a gate: how many source files trace to an approved spec.
83
85
  attest: ['help', 'target', 'exclude', 'json', 'badge', 'readme'],
84
86
  skills: ['help', 'target'],
@@ -250,6 +252,8 @@ const USAGE = `holmes-kit — deterministic ASE governance for a project
250
252
  --readme update ONLY the region between the holmes-kit:attest markers in README.md;
251
253
  a README without the markers is never written
252
254
 
255
+ holmes-kit guidance check|refresh --target <dir> [--dry-run] inspect or update AGENTS.md only
256
+
253
257
  holmes-kit upgrade [flags] install the latest and re-pin every recorded workspace (one command)
254
258
  --dry-run show the plan (current→latest, workspaces to re-pin), change nothing
255
259
  --yes skip the confirmation prompt (required in a non-interactive shell)
@@ -296,7 +300,7 @@ async function main(argv) {
296
300
  }
297
301
  // Positionals these commands do not take are refused, not dropped: `skills refresh <dir>`
298
302
  // silently wrote into CWD while the named target stayed stale (round-3 HIGH).
299
- const expected = cmd === 'skills' ? ['refresh'] : cmd === 'ledger' ? ['rechain']
303
+ const expected = cmd === 'guidance' ? ['check', 'refresh'] : cmd === 'skills' ? ['refresh'] : cmd === 'ledger' ? ['rechain']
300
304
  : cmd === 'semantic-key' ? ['set', 'unset', 'status']
301
305
  : cmd === 'autonomy' ? ['status', 'on', 'off'] : [];
302
306
  const unexpected = positionals.filter((p) => !expected.includes(p));
@@ -334,6 +338,25 @@ async function main(argv) {
334
338
  process.stdout.write((0, colophon_1.colophon)());
335
339
  return 0;
336
340
  }
341
+ if (cmd === 'guidance') {
342
+ if (positionals.length !== 1 || !['check', 'refresh'].includes(positionals[0])) {
343
+ process.stderr.write('Use guidance check|refresh --target <dir> [--dry-run]\n');
344
+ return 2;
345
+ }
346
+ const { runGuidanceCommand } = await Promise.resolve().then(() => __importStar(require('./agents-guidance-command')));
347
+ const r = runGuidanceCommand({ target: path.resolve(typeof flags.target === 'string' ? flags.target : process.cwd()), operation: positionals[0], dryRun: flags['dry-run'] === true });
348
+ process.stdout.write(`AGENTS.md: ${r.plan.state}\n${r.plan.reasons.join('\n')}\n`);
349
+ if (flags['dry-run'] && r.plan.after !== null && r.plan.after !== r.plan.before) {
350
+ process.stdout.write(`--- AGENTS.md (before)\n${r.plan.before ?? ''}\n+++ AGENTS.md (proposed)\n${r.plan.after}`);
351
+ }
352
+ if (flags['dry-run'] && r.plan.after === null && r.plan.before !== null) {
353
+ const { planGuidance } = await Promise.resolve().then(() => __importStar(require('./agents-guidance-plan')));
354
+ process.stdout.write(`--- AGENTS.md (preserved; manual review required)\n${r.plan.before}\n+++ Expected managed block (reference only; preserve project rules)\n${planGuidance(null).after ?? ''}`);
355
+ }
356
+ if (positionals[0] === 'refresh' && !flags['dry-run'] && r.exitCode === 0 && r.plan.before !== r.plan.after)
357
+ process.stdout.write('New reads use this guidance; reload instructions or restart existing agent sessions.\n');
358
+ return r.exitCode;
359
+ }
337
360
  if (cmd === 'semantic-setup' || cmd === 'semantic-check') {
338
361
  const { runModelSetup } = await Promise.resolve().then(() => __importStar(require('../semantic/local-model')));
339
362
  return runModelSetup({ offline: cmd === 'semantic-check' });
@@ -405,7 +428,12 @@ async function main(argv) {
405
428
  return 2;
406
429
  }
407
430
  }
408
- const checks = await (0, doctor_1.runDoctor)(packageRoot(), typeof flags.target === 'string' ? path.resolve(flags.target) : undefined);
431
+ const { AGENTS } = require('./agents');
432
+ if (flags.agent !== undefined && (typeof flags.agent !== 'string' || !AGENTS.includes(flags.agent))) {
433
+ process.stderr.write(`unknown --agent ${String(flags.agent)} (${AGENTS.join('|')})\n\n${USAGE}`);
434
+ return 2;
435
+ }
436
+ const checks = await (0, doctor_1.runDoctor)(packageRoot(), typeof flags.target === 'string' ? path.resolve(flags.target) : undefined, { agent: flags.agent });
409
437
  process.stdout.write(flags.json ? JSON.stringify(checks, null, 2) + '\n' : (0, doctor_1.formatChecks)(checks) + '\n');
410
438
  return checks.some((c) => c.level === 'FAIL') ? 1 : 0;
411
439
  }
@@ -36,6 +36,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.settingsPathOf = exports.MATCHERS = exports.SERVER_NAME = void 0;
37
37
  exports.buildHookPlan = buildHookPlan;
38
38
  exports.runInit = runInit;
39
+ // @implements A-SPEC-709
39
40
  // @implements A-SPEC-340
40
41
  // @implements A-SPEC-100.2
41
42
  const fs = __importStar(require("node:fs"));
@@ -44,6 +45,8 @@ const settings_merge_1 = require("./settings-merge");
44
45
  const gitignore_merge_1 = require("./gitignore-merge");
45
46
  const settings_merge_2 = require("./settings-merge");
46
47
  const playbook_skills_1 = require("./playbook-skills");
48
+ const agents_guidance_plan_1 = require("./agents-guidance-plan");
49
+ const agents_guidance_file_1 = require("./agents-guidance-file");
47
50
  const agents_1 = require("./agents");
48
51
  const roles_readme_1 = require("./roles-readme");
49
52
  const mcp_launcher_1 = require("./mcp-launcher");
@@ -212,6 +215,18 @@ function runInit(opts) {
212
215
  const messages = [];
213
216
  const changes = [];
214
217
  const removals = [];
218
+ const guidanceFile = path.join(opts.target, 'AGENTS.md');
219
+ let guidance;
220
+ if (!opts.remove) {
221
+ try {
222
+ guidance = (0, agents_guidance_plan_1.planGuidance)((0, agents_guidance_file_1.readGuidanceFile)(guidanceFile));
223
+ }
224
+ catch (e) {
225
+ return { ok: false, exitCode: 2, changes, messages: [String(e)] };
226
+ }
227
+ if (guidance.after === null)
228
+ return { ok: false, exitCode: 2, changes, messages: guidance.reasons };
229
+ }
215
230
  const settingsPath = (0, exports.settingsPathOf)(opts.target, opts.settingsFile);
216
231
  const mcpPath = path.join(opts.target, '.mcp.json');
217
232
  const gitignorePath = path.join(opts.target, '.gitignore');
@@ -464,10 +479,13 @@ function runInit(opts) {
464
479
  // and said nothing. The merge runs in the COMPUTE phase so `--dry-run` predicts the same
465
480
  // bytes the write produces (A-SPEC-190 §9), and whatever it moves, it names.
466
481
  if (path.basename(f.path) === 'AGENTS.md') {
467
- const merged = (0, agents_1.mergeAgentsMd)(before, f.content);
468
- changes.push({ path: f.path, before, after: merged.content });
469
- if (merged.preserved.length > 0) {
470
- messages.push(`${f.path}: ${merged.note} — ${merged.preserved.join(' | ')}`);
482
+ if (!changes.some(c => c.path === f.path)) {
483
+ const planned = guidance ?? (0, agents_guidance_plan_1.planGuidance)(before);
484
+ if (planned.after === null)
485
+ return { ok: false, exitCode: 2, changes, messages: planned.reasons };
486
+ guidance = planned;
487
+ changes.push({ path: f.path, before, after: planned.after });
488
+ messages.push(...planned.reasons);
471
489
  }
472
490
  continue;
473
491
  }
@@ -522,6 +540,9 @@ function runInit(opts) {
522
540
  }
523
541
  }
524
542
  }
543
+ if (guidance && !changes.some(c => c.path === guidanceFile)) {
544
+ changes.push({ path: guidanceFile, before: guidance.before, after: guidance.after });
545
+ }
525
546
  if (!opts.dryRun) {
526
547
  // @implements A-SPEC-190 §17/§18 (round 13) — a write we refuse to make (unreadable original)
527
548
  // or cannot finish (rename failure) is a REFUSAL with a next action, not a raw Node stack. The
@@ -530,7 +551,13 @@ function runInit(opts) {
530
551
  if (c.after === null)
531
552
  continue;
532
553
  try {
533
- writeFileSafe(c.path, c.after);
554
+ if (c.path === guidanceFile && guidance) {
555
+ const applied = (0, agents_guidance_file_1.applyGuidancePlan)(c.path, guidance);
556
+ if (!applied.ok)
557
+ throw new Error(applied.reason);
558
+ }
559
+ else
560
+ writeFileSafe(c.path, c.after);
534
561
  }
535
562
  catch (e) {
536
563
  return { ok: false, exitCode: 2, changes, messages: [
@@ -34,6 +34,7 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.runUpgrade = runUpgrade;
37
+ // @implements A-SPEC-709
37
38
  // @implements A-SPEC-543.2
38
39
  const fs = __importStar(require("node:fs"));
39
40
  const os = __importStar(require("node:os"));
@@ -133,8 +134,18 @@ async function runUpgrade(io) {
133
134
  }
134
135
  catch { /* cache clear is best-effort */ }
135
136
  // (3) re-pin every registered workspace that still exists.
136
- const { runInit } = require('./init');
137
- const newRoot = packageRoot(); // may differ after a global install; re-resolve
137
+ // Load the newly installed package in a fresh process: the caller already cached old init.
138
+ let newCli;
139
+ try {
140
+ const modulesRoot = (0, node_child_process_1.execFileSync)(npmBin(), ['root', ...(plan.installMode === 'global-npx' ? ['-g'] : [])], { cwd: process.cwd(), encoding: 'utf8' }).trim();
141
+ newCli = path.join(modulesRoot, PKG, 'bin', 'holmes-kit.js');
142
+ if (!fs.statSync(newCli).isFile())
143
+ throw new Error('new CLI is not a file');
144
+ }
145
+ catch (e) {
146
+ io.stderr(`Installed package CLI could not be resolved; no workspace re-pinned: ${String(e)}\n`);
147
+ return 1;
148
+ }
138
149
  let repinned = 0, skipped = 0, failed = 0;
139
150
  io.stdout('\nRe-pinning workspaces:\n');
140
151
  for (const w of registry.workspaces) {
@@ -144,34 +155,20 @@ async function runUpgrade(io) {
144
155
  continue;
145
156
  }
146
157
  try {
147
- const res = runInit({
148
- target: w.target,
149
- packageRoot: newRoot,
150
- mode: 'guardrail',
151
- specsDir: '.ax/specs',
152
- settingsFile: 'local',
153
- mcp: true,
154
- dryRun: false,
155
- force: true,
156
- remove: false,
157
- agents: w.agents,
158
- allowAdditive: true,
159
- });
160
- if (res.ok) {
161
- io.stdout(` re-pinned: ${w.target}\n`);
162
- repinned++;
163
- }
164
- else {
165
- io.stdout(` failed: ${w.target}\n`);
166
- failed++;
167
- }
158
+ const agents = w.agents.length ? w.agents.join(',') : 'claude';
159
+ const output = (0, node_child_process_1.execFileSync)(process.execPath, [newCli, 'init', '--target', w.target,
160
+ '--agent', agents, '--mode', 'guardrail', '--mcp-launcher', 'npx'], { cwd: process.cwd(), encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
161
+ io.stdout(output);
162
+ io.stdout(` re-pinned: ${w.target}\n`);
163
+ repinned++;
168
164
  }
169
- catch {
170
- io.stdout(` failed: ${w.target}\n`);
165
+ catch (e) {
166
+ const failure = e;
167
+ io.stdout(` failed: ${w.target}: ${String(failure.stderr ?? failure.message ?? e)}\n`);
171
168
  failed++;
172
169
  }
173
170
  }
174
171
  io.stdout(`\nUpgraded to ${plan.latest}. re-pinned ${repinned} · skipped ${skipped} · failed ${failed}. A new session's hooks/MCP will read the new wiring.\n`);
175
172
  io.stdout(`(You can re-wire any individual workspace at any time with ${(0, npx_bin_1.npxBin)()} holmes-kit init --agent <…> --force.)\n`);
176
- return 0;
173
+ return failed > 0 ? 1 : 0;
177
174
  }
@@ -0,0 +1,6 @@
1
+ import type { Agent } from './agents';
2
+ import type { Check } from './doctor-check';
3
+ /** Disk preparation evidence for one selected harness. It never observes a client's loaded config. */
4
+ export declare function worktreeReadinessChecks(packageRoot: string, target: string, opts?: {
5
+ agent?: Agent;
6
+ }): Check[];
@@ -0,0 +1,81 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.worktreeReadinessChecks = worktreeReadinessChecks;
37
+ // @implements A-SPEC-704
38
+ const fs = __importStar(require("node:fs"));
39
+ const path = __importStar(require("node:path"));
40
+ const workspace_checkout_1 = require("../project/workspace-checkout");
41
+ const workspace_identity_1 = require("../project/workspace-identity");
42
+ const WIRING = {
43
+ claude: ['.mcp.json'],
44
+ codex: ['.codex/config.toml', '.claude-plugin/marketplace.json'],
45
+ antigravity: ['.agents/mcp_config.json', '.agents/hooks.json'],
46
+ };
47
+ /** Disk preparation evidence for one selected harness. It never observes a client's loaded config. */
48
+ function worktreeReadinessChecks(packageRoot, target, opts = {}) {
49
+ const agent = opts.agent;
50
+ if (!agent)
51
+ return [];
52
+ const checkout = (0, workspace_checkout_1.inspectWorkspaceCheckout)(target);
53
+ let identity = 'unavailable';
54
+ let identityWarning = false;
55
+ try {
56
+ const status = (0, workspace_identity_1.workspaceIdentity)(target, 'status');
57
+ identity = status.state;
58
+ identityWarning = status.state === 'initialized';
59
+ }
60
+ catch (e) {
61
+ identityWarning = true;
62
+ identity = `unavailable (${e instanceof Error ? e.message : String(e)})`;
63
+ }
64
+ const files = WIRING[agent];
65
+ const missing = files.filter((file) => !fs.existsSync(path.join(target, file)));
66
+ const build = fs.existsSync(path.join(packageRoot, 'dist', 'holmes', 'mcp', 'server.js'));
67
+ const level = missing.length || identityWarning || checkout.kind === 'unknown' || !build ? 'WARN' : 'PASS';
68
+ const repair = `Run holmes-kit init --target ${target} --agent ${agent}, then restart that harness session.`;
69
+ const detail = [
70
+ `disk preparation only: ${agent}; checkout=${checkout.kind}${checkout.detached ? ' (detached)' : ''}; identity=${identity}.`,
71
+ missing.length ? `missing local wiring: ${missing.join(', ')}.` : `local wiring present: ${files.join(', ')}.`,
72
+ build ? 'package build is present.' : 'package build is absent.',
73
+ 'This does not prove whether a current client loaded hooks or MCP configuration.',
74
+ ].join(' ');
75
+ return [
76
+ { name: `${agent} worktree readiness`, level, detail, fix: level === 'PASS' ? undefined : repair },
77
+ { name: `${agent} live session enforcement`, level: 'WARN',
78
+ detail: 'unknown: disk preparation and a doctor-spawned MCP probe are separate-process evidence, not proof of this client session.',
79
+ fix: 'Restart the selected harness in this workspace and run workspace_preflight from that live session.' },
80
+ ];
81
+ }
@@ -17,6 +17,8 @@ export interface MutationResult {
17
17
  mutationScorePct: number;
18
18
  mutants: AstMutant[];
19
19
  }
20
+ /** Shared mutation vocabulary used by mutation scoring and condition-direction advisories. */
21
+ export declare const MUTATION_MAP: Readonly<Record<MutationOperator, Readonly<Record<string, readonly string[]>>>>;
20
22
  /**
21
23
  * Generate AST mutants for static CPG scanned files.
22
24
  *
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MUTATION_MAP = void 0;
3
4
  exports.generateAstMutants = generateAstMutants;
4
5
  exports.evaluateMutationScore = evaluateMutationScore;
5
- const MUTATION_MAP = {
6
+ /** Shared mutation vocabulary used by mutation scoring and condition-direction advisories. */
7
+ exports.MUTATION_MAP = {
6
8
  relational: {
7
9
  '>': ['<', '>='],
8
10
  '<': ['>', '<='],
@@ -47,7 +49,7 @@ function generateAstMutants(scannedFiles, operators) {
47
49
  for (const sym of symbols) {
48
50
  let mutIndex = 0;
49
51
  for (const opType of targetOps) {
50
- const opRules = MUTATION_MAP[opType];
52
+ const opRules = exports.MUTATION_MAP[opType];
51
53
  if (!opRules)
52
54
  continue;
53
55
  for (const [origToken, replacements] of Object.entries(opRules)) {