harnessed 4.21.0 → 4.22.2

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 (52) hide show
  1. package/bin/harnessed-inject-state.mjs +68 -8
  2. package/dist/cli.mjs +922 -236
  3. package/dist/cli.mjs.map +1 -1
  4. package/dist/index.mjs +1 -1
  5. package/dist/index.mjs.map +1 -1
  6. package/package.json +1 -1
  7. package/workflows/auto/SKILL.md +5 -1
  8. package/workflows/auto/SKILL.zh-Hans.md +5 -1
  9. package/workflows/plan/architecture/SKILL.md +4 -0
  10. package/workflows/plan/architecture/SKILL.zh-Hans.md +4 -0
  11. package/workflows/plan/auto/SKILL.md +4 -0
  12. package/workflows/plan/auto/SKILL.zh-Hans.md +4 -0
  13. package/workflows/plan/phase/SKILL.md +4 -0
  14. package/workflows/plan/phase/SKILL.zh-Hans.md +4 -0
  15. package/workflows/research/SKILL.md +4 -0
  16. package/workflows/research/SKILL.zh-Hans.md +4 -0
  17. package/workflows/retro/SKILL.md +4 -0
  18. package/workflows/retro/SKILL.zh-Hans.md +4 -0
  19. package/workflows/ship/auto/SKILL.md +4 -0
  20. package/workflows/ship/auto/SKILL.zh-Hans.md +4 -0
  21. package/workflows/ship/preflight/SKILL.md +4 -0
  22. package/workflows/ship/preflight/SKILL.zh-Hans.md +4 -0
  23. package/workflows/task/auto/SKILL.md +4 -0
  24. package/workflows/task/auto/SKILL.zh-Hans.md +4 -0
  25. package/workflows/task/code/SKILL.md +4 -0
  26. package/workflows/task/code/SKILL.zh-Hans.md +4 -0
  27. package/workflows/task/deliver/SKILL.md +4 -0
  28. package/workflows/task/deliver/SKILL.zh-Hans.md +4 -0
  29. package/workflows/task/test/SKILL.md +4 -0
  30. package/workflows/task/test/SKILL.zh-Hans.md +4 -0
  31. package/workflows/verify/auto/SKILL.md +4 -0
  32. package/workflows/verify/auto/SKILL.zh-Hans.md +4 -0
  33. package/workflows/verify/code-review/SKILL.md +4 -0
  34. package/workflows/verify/code-review/SKILL.zh-Hans.md +4 -0
  35. package/workflows/verify/design/SKILL.md +4 -0
  36. package/workflows/verify/design/SKILL.zh-Hans.md +4 -0
  37. package/workflows/verify/eval-review/SKILL.md +4 -0
  38. package/workflows/verify/eval-review/SKILL.zh-Hans.md +4 -0
  39. package/workflows/verify/multispec/SKILL.md +4 -0
  40. package/workflows/verify/multispec/SKILL.zh-Hans.md +4 -0
  41. package/workflows/verify/paranoid/SKILL.md +4 -0
  42. package/workflows/verify/paranoid/SKILL.zh-Hans.md +4 -0
  43. package/workflows/verify/progress/SKILL.md +4 -0
  44. package/workflows/verify/progress/SKILL.zh-Hans.md +4 -0
  45. package/workflows/verify/qa/SKILL.md +4 -0
  46. package/workflows/verify/qa/SKILL.zh-Hans.md +4 -0
  47. package/workflows/verify/security/SKILL.md +4 -0
  48. package/workflows/verify/security/SKILL.zh-Hans.md +4 -0
  49. package/workflows/verify/simplify/SKILL.md +4 -0
  50. package/workflows/verify/simplify/SKILL.zh-Hans.md +4 -0
  51. package/workflows/verify/validate-phase/SKILL.md +4 -0
  52. package/workflows/verify/validate-phase/SKILL.zh-Hans.md +4 -0
package/dist/cli.mjs CHANGED
@@ -38,7 +38,7 @@ var init_package = __esm({
38
38
  "package.json"() {
39
39
  package_default = {
40
40
  name: "harnessed",
41
- version: "4.21.0",
41
+ version: "4.22.2",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -515,10 +515,12 @@ var init_schema = __esm({
515
515
  // src/checkpoint/workflowStore.ts
516
516
  var workflowStore_exports = {};
517
517
  __export(workflowStore_exports, {
518
+ IntentEntry: () => IntentEntry,
518
519
  RetroMetaEntry: () => RetroMetaEntry,
519
520
  WorkflowStoreV1: () => WorkflowStoreV1,
520
521
  activeKey: () => activeKey,
521
522
  listWorkflows: () => listWorkflows,
523
+ readIntent: () => readIntent,
522
524
  readStoreRaw: () => readStoreRaw,
523
525
  repoKey: () => repoKey,
524
526
  writeStoreRaw: () => writeStoreRaw
@@ -575,6 +577,10 @@ async function writeStoreRaw(store) {
575
577
  await mkdir(dirname(p7), { recursive: true });
576
578
  await writeFileAtomic(p7, JSON.stringify(store, null, 2));
577
579
  }
580
+ async function readIntent(cwd = process.cwd()) {
581
+ const store = await readStoreRaw();
582
+ return store.intents?.[activeKey(cwd)] ?? store.intents?.[repoKey(cwd)] ?? null;
583
+ }
578
584
  async function listWorkflows() {
579
585
  const store = await readStoreRaw();
580
586
  return Object.entries(store.workflows).map(([key, wf]) => ({
@@ -583,7 +589,7 @@ async function listWorkflows() {
583
589
  status: wf.status
584
590
  }));
585
591
  }
586
- var RetroMetaEntry, WorkflowStoreV1;
592
+ var RetroMetaEntry, IntentEntry, WorkflowStoreV1;
587
593
  var init_workflowStore = __esm({
588
594
  "src/checkpoint/workflowStore.ts"() {
589
595
  init_harnessedRoot();
@@ -598,12 +604,28 @@ var init_workflowStore = __esm({
598
604
  },
599
605
  { additionalProperties: false }
600
606
  );
607
+ IntentEntry = Type.Object(
608
+ {
609
+ // Invoked command name (master OR leaf sub — field name kept for 765cbc9
610
+ // store back-compat; kind carries the distinction).
611
+ master: Type.String({ minLength: 1 }),
612
+ ts: Type.String({ minLength: 1 }),
613
+ // 4.22.0 T6 — additive-optional: absent = 'master' (765cbc9 only ever wrote
614
+ // master intents). 'leaf' switches banner/nag to the leaf SOP wording
615
+ // (prompt → spawn → checkpoint complete) and the absorb trigger to that
616
+ // sub's complete/fail instead of `checkpoint start`.
617
+ kind: Type.Optional(Type.Union([Type.Literal("master"), Type.Literal("leaf")]))
618
+ },
619
+ { additionalProperties: false }
620
+ );
601
621
  WorkflowStoreV1 = Type.Object(
602
622
  {
603
623
  schemaVersion: Type.Literal(SCHEMA_VERSIONS.workflowStore),
604
624
  workflows: Type.Record(Type.String(), CurrentWorkflowV1),
605
625
  // Additive-optional (no schemaVersion bump — old stores Value.Check-pass).
606
- retro_meta: Type.Optional(Type.Record(Type.String(), RetroMetaEntry))
626
+ retro_meta: Type.Optional(Type.Record(Type.String(), RetroMetaEntry)),
627
+ // 4.22.0 — additive-optional, same rationale.
628
+ intents: Type.Optional(Type.Record(Type.String(), IntentEntry))
607
629
  },
608
630
  { additionalProperties: false }
609
631
  );
@@ -2077,6 +2099,106 @@ var init_path_guard = __esm({
2077
2099
  };
2078
2100
  }
2079
2101
  });
2102
+
2103
+ // src/checkpoint/intentKind.ts
2104
+ var intentKind_exports = {};
2105
+ __export(intentKind_exports, {
2106
+ classifyIntentKind: () => classifyIntentKind
2107
+ });
2108
+ function classifyIntentKind(sub, assetsRoot) {
2109
+ try {
2110
+ const raw = readFileSync(join(assetsRoot, "workflows", "role-prompts.yaml"), "utf8");
2111
+ const doc = parse(raw);
2112
+ return doc?.prompts?.[sub]?.is_master === true ? "master" : "leaf";
2113
+ } catch {
2114
+ return "leaf";
2115
+ }
2116
+ }
2117
+ var init_intentKind = __esm({
2118
+ "src/checkpoint/intentKind.ts"() {
2119
+ }
2120
+ });
2121
+ function getPackageRoot() {
2122
+ const thisFile = fileURLToPath(import.meta.url);
2123
+ const thisDir = dirname(thisFile);
2124
+ if (thisDir.endsWith("dist") || thisDir.replace(/\\/g, "/").endsWith("/dist")) {
2125
+ return resolve(thisDir, "..");
2126
+ }
2127
+ return resolve(thisDir, "..", "..", "..");
2128
+ }
2129
+ var init_packagePath = __esm({
2130
+ "src/cli/lib/packagePath.ts"() {
2131
+ }
2132
+ });
2133
+
2134
+ // src/cli/lib/assetsRoot.ts
2135
+ var assetsRoot_exports = {};
2136
+ __export(assetsRoot_exports, {
2137
+ compiledAssetsDir: () => compiledAssetsDir,
2138
+ computeAssetsRoot: () => computeAssetsRoot,
2139
+ getAssetsRoot: () => getAssetsRoot,
2140
+ isCompiledModuleUrl: () => isCompiledModuleUrl
2141
+ });
2142
+ function isCompiledModuleUrl(url) {
2143
+ let s = url;
2144
+ try {
2145
+ s = decodeURIComponent(url);
2146
+ } catch {
2147
+ }
2148
+ const normalized = s.replace(/\\/g, "/").toLowerCase();
2149
+ return BUNFS_MARKERS.some((m) => normalized.includes(m));
2150
+ }
2151
+ function computeAssetsRoot(d) {
2152
+ const override = d.env.HARNESSED_ASSETS_OVERRIDE;
2153
+ if (override && override.trim().length > 0) {
2154
+ return { root: override.trim(), source: "override", compiledAssetsMissing: false };
2155
+ }
2156
+ if (isCompiledModuleUrl(d.moduleUrl)) {
2157
+ const root = join(d.stateRoot(), "assets", d.version);
2158
+ const present = d.exists(join(root, "workflows"));
2159
+ return { root, source: "compiled", compiledAssetsMissing: !present };
2160
+ }
2161
+ return { root: d.packageRoot, source: "package", compiledAssetsMissing: false };
2162
+ }
2163
+ function compiledAssetsDir(version) {
2164
+ return join(detectPlatform().stateRoot, "assets", version);
2165
+ }
2166
+ function realDeps() {
2167
+ return {
2168
+ env: process.env,
2169
+ moduleUrl: import.meta.url,
2170
+ exists: (p7) => {
2171
+ try {
2172
+ return existsSync(p7);
2173
+ } catch {
2174
+ return false;
2175
+ }
2176
+ },
2177
+ stateRoot: () => detectPlatform().stateRoot,
2178
+ packageRoot: getPackageRoot(),
2179
+ version: package_default.version
2180
+ };
2181
+ }
2182
+ function getAssetsRoot() {
2183
+ const r = computeAssetsRoot(realDeps());
2184
+ if (r.source === "compiled" && r.compiledAssetsMissing && !warnedMissing) {
2185
+ warnedMissing = true;
2186
+ console.error(
2187
+ `warning: compiled harnessed binary but bundled assets are not unpacked at ${r.root} \u2014 asset-dependent commands (setup / run / prompt / install) will fail. Reinstall the binary, or use the npm distribution (npm i -g harnessed). (asset unpack pipeline lands in a later release \u2014 B1 seam)`
2188
+ );
2189
+ }
2190
+ return r.root;
2191
+ }
2192
+ var BUNFS_MARKERS, warnedMissing;
2193
+ var init_assetsRoot = __esm({
2194
+ "src/cli/lib/assetsRoot.ts"() {
2195
+ init_package();
2196
+ init_platform();
2197
+ init_packagePath();
2198
+ BUNFS_MARKERS = ["/$bunfs/", "/~bun/"];
2199
+ warnedMissing = false;
2200
+ }
2201
+ });
2080
2202
  function estimateTokens(s) {
2081
2203
  return Math.ceil(Buffer.byteLength(s, "utf8") / 4);
2082
2204
  }
@@ -2168,6 +2290,337 @@ var init_engineHook = __esm({
2168
2290
  init_template();
2169
2291
  }
2170
2292
  });
2293
+ function getUserClaudeJsonPath() {
2294
+ return getMcpConfigPath();
2295
+ }
2296
+ async function readUserClaudeJson() {
2297
+ const path = getUserClaudeJsonPath();
2298
+ let raw;
2299
+ try {
2300
+ raw = await readFile(path, "utf8");
2301
+ } catch (err2) {
2302
+ if (err2.code === "ENOENT") return {};
2303
+ throw err2;
2304
+ }
2305
+ try {
2306
+ const parsed = JSON.parse(raw);
2307
+ if (parsed === null || typeof parsed !== "object") return {};
2308
+ return parsed;
2309
+ } catch {
2310
+ return {};
2311
+ }
2312
+ }
2313
+ function isMcpServerInToml(raw, name) {
2314
+ const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2315
+ const re = new RegExp(`^\\s*\\[mcp_servers\\.(?:${esc}|"${esc}"|'${esc}')(?:\\]|\\.)`, "m");
2316
+ return re.test(raw);
2317
+ }
2318
+ async function isMcpServerRegistered(name) {
2319
+ const platform = detectPlatform();
2320
+ if (platform.id === "codex") {
2321
+ let raw;
2322
+ try {
2323
+ raw = await readFile(platform.mcpConfigPath, "utf8");
2324
+ } catch (err2) {
2325
+ if (err2.code === "ENOENT") return false;
2326
+ throw err2;
2327
+ }
2328
+ return isMcpServerInToml(raw, name);
2329
+ }
2330
+ const config = await readUserClaudeJson();
2331
+ const servers = config.mcpServers;
2332
+ if (!servers || typeof servers !== "object") return false;
2333
+ return Object.hasOwn(servers, name);
2334
+ }
2335
+ async function isPluginRegistered(pluginName) {
2336
+ const registryPath = getPluginsRegistry();
2337
+ if (registryPath !== null) {
2338
+ try {
2339
+ const raw = await readFile(registryPath, "utf8");
2340
+ const parsed = JSON.parse(raw);
2341
+ const plugins = parsed.plugins;
2342
+ if (plugins && typeof plugins === "object") {
2343
+ if (Object.hasOwn(plugins, pluginName)) return true;
2344
+ if (Object.keys(plugins).some((k) => k.split("@")[0] === pluginName)) return true;
2345
+ }
2346
+ } catch {
2347
+ }
2348
+ }
2349
+ for (const path of [getSettingsPath(), getMcpConfigPath()]) {
2350
+ try {
2351
+ const raw = await readFile(path, "utf8");
2352
+ const parsed = JSON.parse(raw);
2353
+ const plugins = parsed.enabledPlugins;
2354
+ if (plugins && typeof plugins === "object") {
2355
+ if (Object.hasOwn(plugins, pluginName)) return true;
2356
+ if (Object.keys(plugins).some((k) => k.split("@")[0] === pluginName)) return true;
2357
+ }
2358
+ } catch {
2359
+ }
2360
+ }
2361
+ return false;
2362
+ }
2363
+ var init_readClaudeConfig = __esm({
2364
+ "src/installers/lib/readClaudeConfig.ts"() {
2365
+ init_platform();
2366
+ }
2367
+ });
2368
+
2369
+ // src/cli/lib/guard-exemption.ts
2370
+ var guard_exemption_exports = {};
2371
+ __export(guard_exemption_exports, {
2372
+ MANUAL_FIX_CMD: () => MANUAL_FIX_CMD,
2373
+ PLANNING_GLOB: () => PLANNING_GLOB,
2374
+ applyExemption: () => applyExemption,
2375
+ findGateguardYml: () => findGateguardYml,
2376
+ planExemption: () => planExemption,
2377
+ previewLines: () => previewLines,
2378
+ refusalLines: () => refusalLines,
2379
+ runExemptionFlow: () => runExemptionFlow
2380
+ });
2381
+ function defaultFindDeps() {
2382
+ return {
2383
+ cwd: process.cwd(),
2384
+ home: homedir(),
2385
+ exists: async (p7) => readFile(p7, "utf8").then(
2386
+ () => true,
2387
+ () => false
2388
+ )
2389
+ };
2390
+ }
2391
+ async function findGateguardYml(deps = {}) {
2392
+ const d = { ...defaultFindDeps(), ...deps };
2393
+ for (const base of [d.cwd, d.home]) {
2394
+ const candidate = join(base, ".gateguard.yml");
2395
+ try {
2396
+ if (await d.exists(candidate)) return candidate;
2397
+ } catch {
2398
+ }
2399
+ }
2400
+ return null;
2401
+ }
2402
+ function planExemption(raw) {
2403
+ const entryBare = ` - "${PLANNING_GLOB}"`;
2404
+ if (raw.includes(PLANNING_GLOB)) return { action: "skip", insertedLines: [] };
2405
+ const eol = raw.includes("\r\n") ? "\r\n" : "\n";
2406
+ const headerRe = /^(ignore_paths[ \t]*:)[ \t]*$/m;
2407
+ const m = headerRe.exec(raw);
2408
+ if (m && m.index !== void 0) {
2409
+ const headerEnd = m.index + m[0].length;
2410
+ const afterHeader = raw.startsWith(eol, headerEnd) ? headerEnd + eol.length : headerEnd;
2411
+ const newText = raw.slice(0, afterHeader) + entryBare + eol + raw.slice(afterHeader);
2412
+ return { action: "append-entry", newText, insertedLines: [entryBare] };
2413
+ }
2414
+ const sep2 = raw.endsWith(eol) || raw.length === 0 ? "" : eol;
2415
+ const section = `${sep2}${eol}ignore_paths:${eol}${entryBare}${eol}`;
2416
+ return {
2417
+ action: "append-section",
2418
+ newText: raw + section,
2419
+ insertedLines: ["ignore_paths:", entryBare]
2420
+ };
2421
+ }
2422
+ async function defaultBackup(raw) {
2423
+ const backupRoot = harnessedSubdir("backups");
2424
+ const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-");
2425
+ const backupPath = join(backupRoot, `gateguard.yml.${ts}.bak`);
2426
+ try {
2427
+ await mkdir(backupRoot, { recursive: true });
2428
+ await writeFile(backupPath, raw, "utf8");
2429
+ return { status: "ok", path: backupPath };
2430
+ } catch (err2) {
2431
+ return { status: "warn", message: `backup ${backupPath} failed: ${err2.message}` };
2432
+ }
2433
+ }
2434
+ async function defaultWrite(p7, text) {
2435
+ const tmp = join(dirname(p7), `.gateguard.yml.${process.pid}.tmp`);
2436
+ await writeFile(tmp, text, "utf8");
2437
+ await rename(tmp, p7);
2438
+ }
2439
+ function defaultApplyDeps() {
2440
+ return {
2441
+ readFile: (p7) => readFile(p7, "utf8"),
2442
+ writeFile: defaultWrite,
2443
+ backup: defaultBackup
2444
+ };
2445
+ }
2446
+ async function applyExemption(ymlPath, deps = {}) {
2447
+ const d = { ...defaultApplyDeps(), ...deps };
2448
+ try {
2449
+ const raw = await d.readFile(ymlPath);
2450
+ const plan = planExemption(raw);
2451
+ if (plan.action === "skip") return { status: "already" };
2452
+ const bk = await d.backup(raw);
2453
+ if (bk.status === "warn") return { status: "error", message: bk.message };
2454
+ await d.writeFile(ymlPath, plan.newText ?? raw);
2455
+ return { status: "applied", backupPath: bk.path, insertedLines: plan.insertedLines };
2456
+ } catch (err2) {
2457
+ return { status: "error", message: err2.message };
2458
+ }
2459
+ }
2460
+ function previewLines(plan, ymlPath) {
2461
+ return [
2462
+ `[harnessed] GateGuard \u2194 evidence-guard conflict \u2014 sanctioned fix available:`,
2463
+ ` file: ${ymlPath}`,
2464
+ ...plan.insertedLines.map((l) => ` + ${l}`),
2465
+ ` backup: ${join(harnessedSubdir("backups"), "gateguard.yml.<timestamp>.bak")} (written first)`
2466
+ ];
2467
+ }
2468
+ function refusalLines() {
2469
+ return [
2470
+ "",
2471
+ "\u26A0\uFE0F GateGuard exemption NOT applied \u2014 the dual-guard conflict remains:",
2472
+ " \u2022 verify-stage artifacts (code-review-report.md, qa-report.md, security-audit-report.md,",
2473
+ " paranoid-review-report.md, multispec-review-report.md) will be blocked at Write",
2474
+ " \u2022 subagents have no fact-retry channel \u2014 they will rename artifacts and every",
2475
+ " `checkpoint complete` will fail-closed block on the missing contract names",
2476
+ ` \u2022 fix anytime: \`${MANUAL_FIX_CMD}\` (or add ".planning/**" to ignore_paths in your GateGuard config)`,
2477
+ " harnessed doctor will keep warning until this is resolved.",
2478
+ ""
2479
+ ];
2480
+ }
2481
+ async function runExemptionFlow(deps = {}) {
2482
+ const d = {
2483
+ ...defaultApplyDeps(),
2484
+ findYml: () => findGateguardYml(),
2485
+ print: (line) => console.error(line),
2486
+ ...deps
2487
+ };
2488
+ try {
2489
+ const ymlPath = await d.findYml();
2490
+ if (!ymlPath) return "no-yml";
2491
+ const raw = await d.readFile(ymlPath);
2492
+ const plan = planExemption(raw);
2493
+ if (plan.action === "skip") return "already";
2494
+ for (const line of previewLines(plan, ymlPath)) d.print(line);
2495
+ if (!d.confirm) {
2496
+ d.print(` non-interactive session \u2014 run \`${MANUAL_FIX_CMD}\` to apply this fix.`);
2497
+ return "advised";
2498
+ }
2499
+ const yes = await d.confirm();
2500
+ if (!yes) {
2501
+ for (const line of refusalLines()) d.print(line);
2502
+ return "declined";
2503
+ }
2504
+ const r = await applyExemption(ymlPath, d);
2505
+ if (r.status === "applied") {
2506
+ d.print(`\u2713 [harnessed] exempted "${PLANNING_GLOB}" in ${ymlPath} (backup: ${r.backupPath})`);
2507
+ return "applied";
2508
+ }
2509
+ if (r.status === "already") return "already";
2510
+ d.print(`\u26A0\uFE0F [harnessed] exemption failed: ${r.message} \u2014 apply manually: \`${MANUAL_FIX_CMD}\``);
2511
+ return "error";
2512
+ } catch (err2) {
2513
+ d.print(`\u26A0\uFE0F [harnessed] exemption flow error: ${err2.message}`);
2514
+ return "error";
2515
+ }
2516
+ }
2517
+ var PLANNING_GLOB, MANUAL_FIX_CMD;
2518
+ var init_guard_exemption = __esm({
2519
+ "src/cli/lib/guard-exemption.ts"() {
2520
+ init_harnessedRoot();
2521
+ PLANNING_GLOB = ".planning/**";
2522
+ MANUAL_FIX_CMD = "harnessed exempt-gateguard";
2523
+ }
2524
+ });
2525
+
2526
+ // src/cli/lib/check-guard-conflict.ts
2527
+ var check_guard_conflict_exports = {};
2528
+ __export(check_guard_conflict_exports, {
2529
+ GUARD_CONFLICT_ADVICE: () => GUARD_CONFLICT_ADVICE,
2530
+ checkGuardConflict: () => checkGuardConflict,
2531
+ detectGateGuardActive: () => detectGateGuardActive
2532
+ });
2533
+ function defaultDeps() {
2534
+ return {
2535
+ env: process.env,
2536
+ readSettings: async () => {
2537
+ try {
2538
+ return await readFile(getSettingsPath(), "utf8");
2539
+ } catch {
2540
+ return null;
2541
+ }
2542
+ },
2543
+ eccPluginInstalled: async () => {
2544
+ try {
2545
+ return await isPluginRegistered("ecc");
2546
+ } catch {
2547
+ return false;
2548
+ }
2549
+ }
2550
+ };
2551
+ }
2552
+ async function detectGateGuardActive(deps = {}) {
2553
+ const d = { ...defaultDeps(), ...deps };
2554
+ try {
2555
+ const disabled = (d.env.GATEGUARD_DISABLED ?? "").trim() === "1";
2556
+ const eccEnv = (d.env.ECC_GATEGUARD ?? "").trim().toLowerCase();
2557
+ if (disabled || DISABLE_VALUES.has(eccEnv)) return { active: false, source: null };
2558
+ if (eccEnv.length > 0) return { active: true, source: "env" };
2559
+ const settings = await d.readSettings();
2560
+ if (settings !== null && /gateguard/i.test(settings)) {
2561
+ return { active: true, source: "settings-hooks" };
2562
+ }
2563
+ if (await d.eccPluginInstalled()) return { active: true, source: "ecc-plugin" };
2564
+ return { active: false, source: null };
2565
+ } catch {
2566
+ return { active: false, source: null };
2567
+ }
2568
+ }
2569
+ async function defaultExemptionProbe() {
2570
+ const { findGateguardYml: findGateguardYml2 } = await Promise.resolve().then(() => (init_guard_exemption(), guard_exemption_exports));
2571
+ return {
2572
+ findYml: () => findGateguardYml2(),
2573
+ readFile: (p7) => readFile(p7, "utf8")
2574
+ };
2575
+ }
2576
+ async function checkGuardConflict(deps = {}, exemption) {
2577
+ const det = await detectGateGuardActive(deps);
2578
+ if (!det.active) {
2579
+ return {
2580
+ name: "guard conflict (GateGuard)",
2581
+ status: "pass",
2582
+ message: "ECC GateGuard not detected \u2014 no dual-guard filename conflict"
2583
+ };
2584
+ }
2585
+ try {
2586
+ const probe = exemption ?? await defaultExemptionProbe();
2587
+ const ymlPath = await probe.findYml();
2588
+ if (ymlPath) {
2589
+ const { planExemption: planExemption2 } = await Promise.resolve().then(() => (init_guard_exemption(), guard_exemption_exports));
2590
+ const plan = planExemption2(await probe.readFile(ymlPath));
2591
+ if (plan.action === "skip") {
2592
+ return {
2593
+ name: "guard conflict (GateGuard)",
2594
+ status: "pass",
2595
+ message: `GateGuard active but .planning/** is exempted in ${ymlPath} \u2014 conflict resolved`
2596
+ };
2597
+ }
2598
+ return {
2599
+ name: "guard conflict (GateGuard)",
2600
+ status: "warn",
2601
+ message: `ECC GateGuard appears active (via ${det.source}) with ${ymlPath} \u2014 its filename policy collides with harnessed evidence-guard artifact names (findings.md, *-report.md); a sanctioned auto-fix is available`,
2602
+ fix: GUARD_CONFLICT_ADVICE,
2603
+ install_commands: ["harnessed exempt-gateguard"]
2604
+ };
2605
+ }
2606
+ } catch {
2607
+ }
2608
+ return {
2609
+ name: "guard conflict (GateGuard)",
2610
+ status: "warn",
2611
+ message: `ECC GateGuard appears active (via ${det.source}) \u2014 its filename policy (blocks report/findings/summary/analysis Writes) collides with harnessed evidence-guard artifact names (findings.md, *-report.md); subagents have no fact-retry channel, so \`checkpoint complete\` will fail-closed block`,
2612
+ fix: GUARD_CONFLICT_ADVICE
2613
+ };
2614
+ }
2615
+ var DISABLE_VALUES, GUARD_CONFLICT_ADVICE;
2616
+ var init_check_guard_conflict = __esm({
2617
+ "src/cli/lib/check-guard-conflict.ts"() {
2618
+ init_platform();
2619
+ init_readClaudeConfig();
2620
+ DISABLE_VALUES = /* @__PURE__ */ new Set(["off", "0", "false", "disabled"]);
2621
+ GUARD_CONFLICT_ADVICE = "options (best first): (1) exempt .planning/ paths in the GateGuard config \u2014 planning docs are the legitimate home of findings.md/*-report.md; (2) set ECC_GATEGUARD=off for harnessed-orchestrated sessions; do NOT blanket `checkpoint complete --force` \u2014 that silently voids the evidence guard.";
2622
+ }
2623
+ });
2171
2624
 
2172
2625
  // src/workflow/interpolate.ts
2173
2626
  function interpolate(template, vars) {
@@ -2538,12 +2991,21 @@ function buildOrchestratorBody(name, prompt) {
2538
2991
  ``,
2539
2992
  `## How to run (orchestrator \u2014 clarify in THIS session, then drive native subagent spawns)`,
2540
2993
  ``,
2994
+ // 4.22.0 (L1 anti-freestyle) — CC pre-executes this at prompt-assembly time
2995
+ // (before the model sees anything): registers the invocation intent so the
2996
+ // per-turn inject nags until steps 2-3 seed the ledger. The CLI is fail-soft
2997
+ // (silent exit 0 on any error) because CC's failing-pre-exec behavior is
2998
+ // undocumented.
2999
+ `!\`harnessed checkpoint intent ${name}\``,
3000
+ ``,
3001
+ `> The banner above (when present) means this invocation is REGISTERED with the engine (an intent marker) \u2014 not yet compliant: steps 2-3 below seed the ledger, and a per-turn \`<workflow-intent>\` reminder persists until they run.`,
3002
+ ``,
2541
3003
  `harnessed is the orchestration brain: \`harnessed gates\` tells you which subs fire, \`harnessed prompt\` gives you each sub's spawn-ready prompt, and \`harnessed checkpoint\` records the per-sub state-machine ledger. YOU (the main session) do the spawning with CC-native Task / Agent tools \u2014 keeping the session responsive, enabling Agent Teams, and letting clarification round-trips reach the user.`,
2542
3004
  ``,
2543
3005
  `Drive this exact sequence (it is the state machine \u2014 follow the file, don't improvise from memory):`,
2544
3006
  ``,
2545
3007
  ...autoDiscussStep,
2546
- `2. Bash: \`harnessed gates ${name} --task "<locked spec>" --skip-sub clarify\` \u2192 parse the JSON \`{fire: [{sub, order, mode, is_master}], skip: [{sub, reason}], parallelism: {escalate_to_teams}}\`. This is the plan SoT (no spawn). Keep the verbatim JSON for the next step.`,
3008
+ `2. Bash: \`harnessed gates ${name} --task "<locked spec>" --skip-sub clarify\` \u2192 parse the JSON \`{fire: [{sub, order, mode, is_master}], skip: [{sub, reason}], parallelism: {escalate_to_teams}}\`. This is the plan SoT (no spawn). Keep the verbatim JSON for the next step.${name === "auto" ? " For a small self-contained task (single-file / single-page class), the sanctioned lite path is adding `--skip-sub verify --skip-sub retro` (repeatable / comma-separated) \u2014 skipped subs are still recorded in the ledger with reasons; lite \u2260 freestyle (the ledger/evidence IS the difference)." : ""}`,
2547
3009
  `3. Bash: \`harnessed checkpoint start ${name} --plan '<the verbatim gates JSON from step 2>'\` \u2192 seeds the sub-progress ledger in \`current-workflow.json\` (fired subs \u2192 \`pending\`, skipped subs \u2192 \`skipped\` + reason). This makes \`harnessed status --recover\` able to tell you where you are after compaction.`,
2548
3010
  `4. If \`parallelism.escalate_to_teams === true\`: this stage needs multiple subagents to coordinate (SendMessage / shared contract). Read \`~/.claude/rules/agent-teams.md\`, then \`TeamCreate\` \u2192 \`Agent(name, team_name, ...)\` per fired sub (prompt from \`harnessed prompt <sub>\`) \u2192 coordinate via SendMessage \u2192 \`SendMessage shutdown_request\` + \`TeamDelete\`. Still checkpoint each sub (\`complete\` / \`fail\`) as below.`,
2549
3011
  `5. Otherwise, for each fired sub in \`order\` (serial subs sequentially, parallel subs concurrently via parallel Task calls):`,
@@ -2576,6 +3038,13 @@ function buildExecutionBody(name, prompt) {
2576
3038
  ``,
2577
3039
  `## How to run (execution \u2014 native subagent spawn)`,
2578
3040
  ``,
3041
+ // 4.22.0 T6 — same L1 anti-freestyle pre-exec as the orchestrator body:
3042
+ // registers a LEAF intent (absorbed by this sub's checkpoint complete/fail);
3043
+ // the per-turn inject nags while it is fresh and unresolved. Fail-soft CLI.
3044
+ `!\`harnessed checkpoint intent ${name}\``,
3045
+ ``,
3046
+ `> The banner above (when present) means this invocation is REGISTERED with the engine (an intent marker) \u2014 not yet compliant: the steps below (prompt \u2192 spawn \u2192 checkpoint complete) resolve it, and a per-turn \`<workflow-intent>\` reminder persists until they run.`,
3047
+ ``,
2579
3048
  `harnessed gives you the spawn-ready prompt; YOU spawn the subagent with a CC-native Task / Agent tool (keeps the session responsive + lets clarification round-trips reach the user).`,
2580
3049
  ``,
2581
3050
  ...spawnLoopSteps("").map(
@@ -2627,7 +3096,7 @@ function nameToYamlHintPath(name) {
2627
3096
  function shouldOverwriteFile(content) {
2628
3097
  return HARNESSED_MARKER_RX.test(content) || V3_4_3_SIGNATURE_SUB_RX.test(content) || V3_4_3_SIGNATURE_MASTER_RX.test(content);
2629
3098
  }
2630
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync14 = (p7) => readFileSync(p7, "utf8")) {
3099
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync16 = (p7) => readFileSync(p7, "utf8")) {
2631
3100
  const results = [];
2632
3101
  const aggregatedWarnings = /* @__PURE__ */ new Set();
2633
3102
  for (const name of slashNames) {
@@ -2646,7 +3115,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
2646
3115
  if (fileExists2(path)) {
2647
3116
  let existing = "";
2648
3117
  try {
2649
- existing = readFileSync14(path);
3118
+ existing = readFileSync16(path);
2650
3119
  } catch {
2651
3120
  existing = "";
2652
3121
  }
@@ -3802,135 +4271,54 @@ This applies to: strategic-layer review skip / phase-layer clarification skip /
3802
4271
  opts?.rolePrompts,
3803
4272
  opts?.workflowName,
3804
4273
  opts?.modelTierOverride,
3805
- injectsRules
3806
- ),
3807
- {
3808
- expertName: skillName,
3809
- ...resumeSessionId ? { resumeSessionId } : {},
3810
- ...onSessionId ? { onSessionId } : {}
3811
- }
3812
- );
3813
- };
3814
- let envelopeJson;
3815
- try {
3816
- if (optIn) {
3817
- const maxIter = opts?.maxIter ?? RALPH_DEFAULT_MAX_ITER;
3818
- envelopeJson = await ralphLoopWrap(spawnOnce, maxIter);
3819
- } else {
3820
- envelopeJson = await spawnOnce();
3821
- }
3822
- } catch (err2) {
3823
- if (err2 instanceof MaxIterationsExceededError && opts?.fallback) {
3824
- handleMaxIterationsExceeded(err2, opts.fallback, {
3825
- subtaskSummary: `phase ${skillName}`,
3826
- // Phase 4 — plumbed actual workflow name (was hardcoded 'harnessed-run'
3827
- // pre-Phase 4); falls back to literal when opts.workflowName absent
3828
- // (preserves Phase 3 behavior for callers that don't pass workflowName).
3829
- workflowName: opts.workflowName ?? "harnessed-run",
3830
- phaseId: skillName,
3831
- maxIterations: opts?.maxIter ?? RALPH_DEFAULT_MAX_ITER
3832
- });
3833
- }
3834
- return {
3835
- status: "fail",
3836
- output: err2 instanceof MaxIterationsExceededError ? `ralph-loop max-iterations exceeded (${err2.iterations}) for ${skillName}` : `sdkSpawn failed for ${skillName}: ${err2.message}`
3837
- };
3838
- }
3839
- const env = JSON.parse(envelopeJson);
3840
- const status = env.structured_output?.status === "COMPLETE" || env.subtype === "success" ? "ok" : "fail";
3841
- const escalation = env.structured_output?.needs_teams_escalation === true;
3842
- return {
3843
- status,
3844
- output: env.text ?? env.result ?? "",
3845
- ...env.structured_output?.status ? { decision: env.structured_output.status } : {},
3846
- ...escalation ? {
3847
- needsTeamsEscalation: true,
3848
- ...env.structured_output?.escalation_reason ? { escalationReason: env.structured_output.escalation_reason } : {}
3849
- } : {}
3850
- };
3851
- }
3852
- };
3853
- }
3854
- });
3855
- function getPackageRoot() {
3856
- const thisFile = fileURLToPath(import.meta.url);
3857
- const thisDir = dirname(thisFile);
3858
- if (thisDir.endsWith("dist") || thisDir.replace(/\\/g, "/").endsWith("/dist")) {
3859
- return resolve(thisDir, "..");
3860
- }
3861
- return resolve(thisDir, "..", "..", "..");
3862
- }
3863
- var init_packagePath = __esm({
3864
- "src/cli/lib/packagePath.ts"() {
3865
- }
3866
- });
3867
-
3868
- // src/cli/lib/assetsRoot.ts
3869
- var assetsRoot_exports = {};
3870
- __export(assetsRoot_exports, {
3871
- compiledAssetsDir: () => compiledAssetsDir,
3872
- computeAssetsRoot: () => computeAssetsRoot,
3873
- getAssetsRoot: () => getAssetsRoot,
3874
- isCompiledModuleUrl: () => isCompiledModuleUrl
3875
- });
3876
- function isCompiledModuleUrl(url) {
3877
- let s = url;
3878
- try {
3879
- s = decodeURIComponent(url);
3880
- } catch {
3881
- }
3882
- const normalized = s.replace(/\\/g, "/").toLowerCase();
3883
- return BUNFS_MARKERS.some((m) => normalized.includes(m));
3884
- }
3885
- function computeAssetsRoot(d) {
3886
- const override = d.env.HARNESSED_ASSETS_OVERRIDE;
3887
- if (override && override.trim().length > 0) {
3888
- return { root: override.trim(), source: "override", compiledAssetsMissing: false };
3889
- }
3890
- if (isCompiledModuleUrl(d.moduleUrl)) {
3891
- const root = join(d.stateRoot(), "assets", d.version);
3892
- const present = d.exists(join(root, "workflows"));
3893
- return { root, source: "compiled", compiledAssetsMissing: !present };
3894
- }
3895
- return { root: d.packageRoot, source: "package", compiledAssetsMissing: false };
3896
- }
3897
- function compiledAssetsDir(version) {
3898
- return join(detectPlatform().stateRoot, "assets", version);
3899
- }
3900
- function realDeps() {
3901
- return {
3902
- env: process.env,
3903
- moduleUrl: import.meta.url,
3904
- exists: (p7) => {
3905
- try {
3906
- return existsSync(p7);
3907
- } catch {
3908
- return false;
4274
+ injectsRules
4275
+ ),
4276
+ {
4277
+ expertName: skillName,
4278
+ ...resumeSessionId ? { resumeSessionId } : {},
4279
+ ...onSessionId ? { onSessionId } : {}
4280
+ }
4281
+ );
4282
+ };
4283
+ let envelopeJson;
4284
+ try {
4285
+ if (optIn) {
4286
+ const maxIter = opts?.maxIter ?? RALPH_DEFAULT_MAX_ITER;
4287
+ envelopeJson = await ralphLoopWrap(spawnOnce, maxIter);
4288
+ } else {
4289
+ envelopeJson = await spawnOnce();
4290
+ }
4291
+ } catch (err2) {
4292
+ if (err2 instanceof MaxIterationsExceededError && opts?.fallback) {
4293
+ handleMaxIterationsExceeded(err2, opts.fallback, {
4294
+ subtaskSummary: `phase ${skillName}`,
4295
+ // Phase 4 — plumbed actual workflow name (was hardcoded 'harnessed-run'
4296
+ // pre-Phase 4); falls back to literal when opts.workflowName absent
4297
+ // (preserves Phase 3 behavior for callers that don't pass workflowName).
4298
+ workflowName: opts.workflowName ?? "harnessed-run",
4299
+ phaseId: skillName,
4300
+ maxIterations: opts?.maxIter ?? RALPH_DEFAULT_MAX_ITER
4301
+ });
4302
+ }
4303
+ return {
4304
+ status: "fail",
4305
+ output: err2 instanceof MaxIterationsExceededError ? `ralph-loop max-iterations exceeded (${err2.iterations}) for ${skillName}` : `sdkSpawn failed for ${skillName}: ${err2.message}`
4306
+ };
4307
+ }
4308
+ const env = JSON.parse(envelopeJson);
4309
+ const status = env.structured_output?.status === "COMPLETE" || env.subtype === "success" ? "ok" : "fail";
4310
+ const escalation = env.structured_output?.needs_teams_escalation === true;
4311
+ return {
4312
+ status,
4313
+ output: env.text ?? env.result ?? "",
4314
+ ...env.structured_output?.status ? { decision: env.structured_output.status } : {},
4315
+ ...escalation ? {
4316
+ needsTeamsEscalation: true,
4317
+ ...env.structured_output?.escalation_reason ? { escalationReason: env.structured_output.escalation_reason } : {}
4318
+ } : {}
4319
+ };
3909
4320
  }
3910
- },
3911
- stateRoot: () => detectPlatform().stateRoot,
3912
- packageRoot: getPackageRoot(),
3913
- version: package_default.version
3914
- };
3915
- }
3916
- function getAssetsRoot() {
3917
- const r = computeAssetsRoot(realDeps());
3918
- if (r.source === "compiled" && r.compiledAssetsMissing && !warnedMissing) {
3919
- warnedMissing = true;
3920
- console.error(
3921
- `warning: compiled harnessed binary but bundled assets are not unpacked at ${r.root} \u2014 asset-dependent commands (setup / run / prompt / install) will fail. Reinstall the binary, or use the npm distribution (npm i -g harnessed). (asset unpack pipeline lands in a later release \u2014 B1 seam)`
3922
- );
3923
- }
3924
- return r.root;
3925
- }
3926
- var BUNFS_MARKERS, warnedMissing;
3927
- var init_assetsRoot = __esm({
3928
- "src/cli/lib/assetsRoot.ts"() {
3929
- init_package();
3930
- init_platform();
3931
- init_packagePath();
3932
- BUNFS_MARKERS = ["/$bunfs/", "/~bun/"];
3933
- warnedMissing = false;
4321
+ };
3934
4322
  }
3935
4323
  });
3936
4324
  async function loadUserOverrides(packageRoot) {
@@ -4279,13 +4667,40 @@ async function checkArtifacts(sub, packageRoot) {
4279
4667
  const found = [];
4280
4668
  const missing = [];
4281
4669
  for (const rel of declared) {
4282
- const abs = resolve(cwd, rel);
4283
- const present = await stat(abs).then((s) => s.isFile()).catch(() => false);
4284
- if (present) found.push({ path: abs, sha256: await hashFile(abs) });
4670
+ const abs = await resolveDeclaredArtifact(cwd, rel);
4671
+ if (abs) found.push({ path: abs, sha256: await hashFile(abs) });
4285
4672
  else missing.push(rel);
4286
4673
  }
4287
4674
  return { status: missing.length === 0 ? "verified" : "missing", found, missing };
4288
4675
  }
4676
+ async function resolveDeclaredArtifact(cwd, rel) {
4677
+ const isFileAt = (p7) => stat(p7).then((s) => s.isFile()).catch(() => false);
4678
+ if (/[\\/]/.test(rel)) {
4679
+ const abs = resolve(cwd, rel);
4680
+ return await isFileAt(abs) ? abs : null;
4681
+ }
4682
+ const atRoot = resolve(cwd, rel);
4683
+ if (await isFileAt(atRoot)) return atRoot;
4684
+ for (const base of [resolve(cwd, ".planning", "phases"), resolve(cwd, ".planning")]) {
4685
+ let entries;
4686
+ try {
4687
+ entries = await readdir(base);
4688
+ } catch {
4689
+ continue;
4690
+ }
4691
+ let best = null;
4692
+ for (const entry of entries) {
4693
+ if (base.endsWith(".planning") && entry === "phases") continue;
4694
+ const cand = resolve(base, entry, rel);
4695
+ const st = await stat(cand).catch(() => null);
4696
+ if (st?.isFile() && (!best || st.mtimeMs > best.mtime)) {
4697
+ best = { abs: cand, mtime: st.mtimeMs };
4698
+ }
4699
+ }
4700
+ if (best) return best.abs;
4701
+ }
4702
+ return null;
4703
+ }
4289
4704
  async function checkPlanningSync(cwd, _workflowState) {
4290
4705
  const planningDir = resolve(cwd, ".planning");
4291
4706
  const hasPlanningDir = await stat(planningDir).then((s) => s.isDirectory()).catch(() => false);
@@ -4624,7 +5039,7 @@ function realExists(p7) {
4624
5039
  return false;
4625
5040
  }
4626
5041
  }
4627
- function defaultDeps() {
5042
+ function defaultDeps2() {
4628
5043
  return {
4629
5044
  platform: process.platform,
4630
5045
  env: process.env,
@@ -4635,7 +5050,7 @@ function defaultDeps() {
4635
5050
  }
4636
5051
  function resolveBash(deps) {
4637
5052
  if (cache2) return cache2;
4638
- cache2 = compute({ ...defaultDeps(), ...deps });
5053
+ cache2 = compute({ ...defaultDeps2(), ...deps });
4639
5054
  return cache2;
4640
5055
  }
4641
5056
  function compute(d) {
@@ -4655,8 +5070,8 @@ function compute(d) {
4655
5070
  }
4656
5071
  const gitFirst = d.where("git")[0];
4657
5072
  if (gitFirst && /git\.exe$/i.test(gitFirst)) {
4658
- const root = dirname8(dirname8(gitFirst));
4659
- for (const cand of [join18(root, "bin", "bash.exe"), join18(root, "usr", "bin", "bash.exe")]) {
5073
+ const root = dirname9(dirname9(gitFirst));
5074
+ for (const cand of [join20(root, "bin", "bash.exe"), join20(root, "usr", "bin", "bash.exe")]) {
4660
5075
  if (d.exists(cand) && usable(cand)) return { path: cand, source: "git-derived", wslOnPath };
4661
5076
  }
4662
5077
  }
@@ -4664,13 +5079,13 @@ function compute(d) {
4664
5079
  d.env.ProgramFiles,
4665
5080
  d.env.ProgramW6432,
4666
5081
  d.env["ProgramFiles(x86)"],
4667
- d.env.LOCALAPPDATA ? join18(d.env.LOCALAPPDATA, "Programs") : void 0
5082
+ d.env.LOCALAPPDATA ? join20(d.env.LOCALAPPDATA, "Programs") : void 0
4668
5083
  ];
4669
5084
  for (const base of bases) {
4670
5085
  if (!base) continue;
4671
5086
  for (const cand of [
4672
- join18(base, "Git", "bin", "bash.exe"),
4673
- join18(base, "Git", "usr", "bin", "bash.exe")
5087
+ join20(base, "Git", "bin", "bash.exe"),
5088
+ join20(base, "Git", "usr", "bin", "bash.exe")
4674
5089
  ]) {
4675
5090
  if (d.exists(cand) && usable(cand))
4676
5091
  return { path: cand, source: "standard-location", wslOnPath };
@@ -4683,10 +5098,10 @@ function compute(d) {
4683
5098
  }
4684
5099
  return { path: "bash", source: "path-fallback" };
4685
5100
  }
4686
- var dirname8, join18, WSL_STUB_RE, cache2;
5101
+ var dirname9, join20, WSL_STUB_RE, cache2;
4687
5102
  var init_resolveBash = __esm({
4688
5103
  "src/installers/lib/resolveBash.ts"() {
4689
- ({ dirname: dirname8, join: join18 } = win32);
5104
+ ({ dirname: dirname9, join: join20 } = win32);
4690
5105
  WSL_STUB_RE = /[\\/](windows[\\/](system32|sysnative|syswow64)|microsoft[\\/]windowsapps)[\\/]bash\.exe$/i;
4691
5106
  cache2 = null;
4692
5107
  }
@@ -5245,81 +5660,6 @@ var init_check_mattpocock_skills = __esm({
5245
5660
  REMEDIATION2 = "install via `npx skills@latest add mattpocock/skills` (or git clone https://github.com/mattpocock/skills ~/.claude/skills/mattpocock-skills); methodology fallback already inline in role-prompts.yaml per v3.6.0 Phase 1 \u2014 install is optional but enables /grill-with-docs /tdd /diagnosing-bugs etc. SlashCommand acceleration";
5246
5661
  }
5247
5662
  });
5248
- function getUserClaudeJsonPath() {
5249
- return getMcpConfigPath();
5250
- }
5251
- async function readUserClaudeJson() {
5252
- const path = getUserClaudeJsonPath();
5253
- let raw;
5254
- try {
5255
- raw = await readFile(path, "utf8");
5256
- } catch (err2) {
5257
- if (err2.code === "ENOENT") return {};
5258
- throw err2;
5259
- }
5260
- try {
5261
- const parsed = JSON.parse(raw);
5262
- if (parsed === null || typeof parsed !== "object") return {};
5263
- return parsed;
5264
- } catch {
5265
- return {};
5266
- }
5267
- }
5268
- function isMcpServerInToml(raw, name) {
5269
- const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5270
- const re = new RegExp(`^\\s*\\[mcp_servers\\.(?:${esc}|"${esc}"|'${esc}')(?:\\]|\\.)`, "m");
5271
- return re.test(raw);
5272
- }
5273
- async function isMcpServerRegistered(name) {
5274
- const platform = detectPlatform();
5275
- if (platform.id === "codex") {
5276
- let raw;
5277
- try {
5278
- raw = await readFile(platform.mcpConfigPath, "utf8");
5279
- } catch (err2) {
5280
- if (err2.code === "ENOENT") return false;
5281
- throw err2;
5282
- }
5283
- return isMcpServerInToml(raw, name);
5284
- }
5285
- const config = await readUserClaudeJson();
5286
- const servers = config.mcpServers;
5287
- if (!servers || typeof servers !== "object") return false;
5288
- return Object.hasOwn(servers, name);
5289
- }
5290
- async function isPluginRegistered(pluginName) {
5291
- const registryPath = getPluginsRegistry();
5292
- if (registryPath !== null) {
5293
- try {
5294
- const raw = await readFile(registryPath, "utf8");
5295
- const parsed = JSON.parse(raw);
5296
- const plugins = parsed.plugins;
5297
- if (plugins && typeof plugins === "object") {
5298
- if (Object.hasOwn(plugins, pluginName)) return true;
5299
- if (Object.keys(plugins).some((k) => k.split("@")[0] === pluginName)) return true;
5300
- }
5301
- } catch {
5302
- }
5303
- }
5304
- for (const path of [getSettingsPath(), getMcpConfigPath()]) {
5305
- try {
5306
- const raw = await readFile(path, "utf8");
5307
- const parsed = JSON.parse(raw);
5308
- const plugins = parsed.enabledPlugins;
5309
- if (plugins && typeof plugins === "object") {
5310
- if (Object.hasOwn(plugins, pluginName)) return true;
5311
- if (Object.keys(plugins).some((k) => k.split("@")[0] === pluginName)) return true;
5312
- }
5313
- } catch {
5314
- }
5315
- }
5316
- return false;
5317
- }
5318
- var init_readClaudeConfig = __esm({
5319
- "src/installers/lib/readClaudeConfig.ts"() {
5320
- init_platform();
5321
- }
5322
- });
5323
5663
 
5324
5664
  // src/cli/lib/check-mcp-availability.ts
5325
5665
  var check_mcp_availability_exports = {};
@@ -5459,14 +5799,14 @@ __export(version_check_exports, {
5459
5799
  compareVersions: () => compareVersions,
5460
5800
  fetchLatestVersion: () => fetchLatestVersion
5461
5801
  });
5462
- function parse2(v) {
5802
+ function parse3(v) {
5463
5803
  const m = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?$/.exec(v.trim());
5464
5804
  if (!m) return null;
5465
5805
  return { nums: [Number(m[1]), Number(m[2]), Number(m[3])], pre: m[4] ?? null };
5466
5806
  }
5467
5807
  function compareVersions(installed, latest) {
5468
- const a = parse2(installed);
5469
- const b = parse2(latest);
5808
+ const a = parse3(installed);
5809
+ const b = parse3(latest);
5470
5810
  if (!a || !b) return "unknown";
5471
5811
  for (let i = 0; i < 3; i++) {
5472
5812
  const ai = a.nums[i] ?? 0;
@@ -5563,6 +5903,9 @@ var init_doctor_registry = __esm({
5563
5903
  // v4.16.1 T3 — bun presence (warn-only): gstack's upstream setup hard-requires
5564
5904
  // bun; missing bun is THE gstack refresh-failure cause on user dogfood machines.
5565
5905
  async () => (await Promise.resolve().then(() => (init_check_bun(), check_bun_exports))).checkBun(),
5906
+ // 4.22.1 T4 — dual-guard conflict (warn-only): ECC GateGuard's filename policy
5907
+ // vs evidence-guard artifact contract names (subagents cannot fact-retry).
5908
+ async () => (await Promise.resolve().then(() => (init_check_guard_conflict(), check_guard_conflict_exports))).checkGuardConflict(),
5566
5909
  // Phase 20 — "update available" version check ('warn' only when behind; 'pass'
5567
5910
  // when current/ahead/npm-unreachable — fail-soft, never flips the summary).
5568
5911
  async () => (await Promise.resolve().then(() => (init_check_update(), check_update_exports))).checkUpdate()
@@ -7712,12 +8055,202 @@ var init_nextStep = __esm({
7712
8055
  }
7713
8056
  });
7714
8057
 
8058
+ // src/checkpoint/injectState.ts
8059
+ var injectState_exports = {};
8060
+ __export(injectState_exports, {
8061
+ DEFAULT_INJECT_BUDGET: () => DEFAULT_INJECT_BUDGET,
8062
+ INTENT_TTL_MS: () => INTENT_TTL_MS,
8063
+ buildInjection: () => buildInjection,
8064
+ buildIntentBlock: () => buildIntentBlock,
8065
+ buildProjectContextBlock: () => buildProjectContextBlock,
8066
+ buildWorkflowStateBlock: () => buildWorkflowStateBlock,
8067
+ filterRelevantLearnings: () => filterRelevantLearnings,
8068
+ findPhaseContextExcerpt: () => findPhaseContextExcerpt,
8069
+ formatIntentAge: () => formatIntentAge,
8070
+ parseLearnings: () => parseLearnings,
8071
+ selectWithinBudget: () => selectWithinBudget
8072
+ });
8073
+ function formatIntentAge(ms) {
8074
+ const m = Math.floor(ms / 6e4);
8075
+ if (m < 1) return "<1m";
8076
+ if (m < 60) return `${m}m`;
8077
+ return `${Math.floor(m / 60)}h`;
8078
+ }
8079
+ function buildIntentBlock(intent, nowMs) {
8080
+ if (!intent) return "";
8081
+ const born = Date.parse(intent.ts);
8082
+ if (Number.isNaN(born)) return "";
8083
+ const age = nowMs - born;
8084
+ if (age < 0 || age > INTENT_TTL_MS) return "";
8085
+ const m = intent.master;
8086
+ if (intent.kind === "leaf") {
8087
+ return [
8088
+ "<workflow-intent>",
8089
+ `intent: /${m} invoked ${formatIntentAge(age)} ago \u2014 sub NOT checkpointed`,
8090
+ `ENGINE: /${m} is registered but not engaged \u2014 freestyle risk. Run: \`harnessed prompt ${m} --task "<spec>" --json\` \u2192 spawn per SOP \u2192 \`harnessed checkpoint complete ${m}\` (or \`harnessed checkpoint fail ${m}\`).`,
8091
+ "</workflow-intent>"
8092
+ ].join("\n");
8093
+ }
8094
+ return [
8095
+ "<workflow-intent>",
8096
+ `intent: /${m} invoked ${formatIntentAge(age)} ago \u2014 ledger NOT seeded`,
8097
+ `ENGINE: /${m} is registered but not engaged \u2014 freestyle risk. Run: \`harnessed gates ${m} --task "<locked spec>"\` \u2192 \`harnessed checkpoint start ${m} --plan '<gates JSON>'\`; then drive each sub via \`harnessed prompt\` / \`harnessed checkpoint complete|fail\`.`,
8098
+ "</workflow-intent>"
8099
+ ].join("\n");
8100
+ }
8101
+ function buildWorkflowStateBlock(wf, forward) {
8102
+ if (!wf) return "";
8103
+ const ledger = wf.sub_progress ?? [];
8104
+ const next = nextPending(ledger);
8105
+ const loops = detectLoop(ledger);
8106
+ const lines = [
8107
+ "<workflow-state>",
8108
+ `phase: ${wf.phase}`,
8109
+ `status: ${wf.status}`,
8110
+ next ? `next: ${next}` : "next: (none \u2014 all subs resolved)"
8111
+ ];
8112
+ if (next) {
8113
+ lines.push(
8114
+ `ENGINE: mid state-machine \u2014 drive sub '${next}' via \`harnessed prompt ${next}\` \u2192 spawn \u2192 \`harnessed checkpoint complete/fail\`. Do NOT freestyle the orchestration or skip the ledger; run \`harnessed status --recover\` if unsure where you are.`
8115
+ );
8116
+ }
8117
+ if (!next && forward && (forward.unit.kind === "phase" || forward.unit.kind === "task")) {
8118
+ const n = forward.remainingPhases;
8119
+ lines.push(
8120
+ `NEXT-UNIT: current workflow complete \u2192 next is ${describeUnit(forward.unit)} (run /auto or \`harnessed advance\`); ${n} phase${n === 1 ? "" : "s"} remain`
8121
+ );
8122
+ }
8123
+ for (const l of loops) {
8124
+ lines.push(
8125
+ `BREAK-LOOP: sub '${l.sub}' failed ${l.count}x \u2014 stop retrying, run break-loop skill`
8126
+ );
8127
+ }
8128
+ if (wf.ship_ready) {
8129
+ lines.push(
8130
+ `SHIP-READY: ${wf.ship_commits ?? 0} commit(s) since the last release tag \u2014 consider shipping (harnessed release-preflight, then /ship)`
8131
+ );
8132
+ }
8133
+ if (wf.retro_due) {
8134
+ lines.push(
8135
+ "RETRO-DUE: enough phases completed since the last retro \u2014 run /retro, then `harnessed retro --done`"
8136
+ );
8137
+ }
8138
+ if (wf.verify_mode === "full") {
8139
+ lines.push(
8140
+ "VERIFY-MODE: full \u2014 run full verification (large/risky change: >5 files / >4 subs / >3 reqs)"
8141
+ );
8142
+ } else if (wf.verify_mode === "light") {
8143
+ lines.push("VERIFY-MODE: light \u2014 scope verification to the changed surface (small change)");
8144
+ }
8145
+ lines.push("</workflow-state>");
8146
+ return lines.join("\n");
8147
+ }
8148
+ function parseLearnings(md) {
8149
+ const blocks = md.split(/^### /m).slice(1);
8150
+ return blocks.map((b) => {
8151
+ const raw = `### ${b}`.trimEnd();
8152
+ const phase = /phase (\S+)/.exec(b)?.[1] ?? "";
8153
+ const subs = [];
8154
+ for (const m of b.matchAll(/^- (?:looped|rejected|failed): (\S+)/gm)) {
8155
+ if (m[1]) subs.push(m[1]);
8156
+ }
8157
+ return { raw, phase, subs };
8158
+ });
8159
+ }
8160
+ function filterRelevantLearnings(entries, ctx) {
8161
+ const rel = entries.filter(
8162
+ (e) => e.phase === ctx.phase || e.subs.some((s) => ctx.ledgerSubs.includes(s))
8163
+ );
8164
+ const ordered = [...rel].reverse();
8165
+ if (ordered.length === 0) {
8166
+ const last = entries[entries.length - 1];
8167
+ return last ? [last] : [];
8168
+ }
8169
+ return ordered;
8170
+ }
8171
+ function selectWithinBudget(entries, budget) {
8172
+ const out = [];
8173
+ let acc = 0;
8174
+ for (const e of entries) {
8175
+ const cost = tok(e.raw);
8176
+ if (acc + cost > budget) break;
8177
+ acc += cost;
8178
+ out.push(e);
8179
+ }
8180
+ return out;
8181
+ }
8182
+ function buildProjectContextBlock(input) {
8183
+ const parts = [];
8184
+ for (const l of input.learnings) parts.push(l.raw.trim());
8185
+ if (input.contextExcerpt) parts.push(input.contextExcerpt.trim());
8186
+ if (parts.length === 0) return "";
8187
+ return ["<project-context>", ...parts, "</project-context>"].join("\n");
8188
+ }
8189
+ function findPhaseContextExcerpt(repoRoot, phase, budget) {
8190
+ try {
8191
+ const phasesDir = join(repoRoot, ".planning", "phases");
8192
+ if (!existsSync(phasesDir)) return null;
8193
+ for (const dir of readdirSync(phasesDir)) {
8194
+ const num = /^(\d+)/.exec(dir)?.[1];
8195
+ if (!num || !phase.includes(num)) continue;
8196
+ const ctxFile = join(phasesDir, dir, `${num}-CONTEXT.md`);
8197
+ if (!existsSync(ctxFile)) continue;
8198
+ const body = readFileSync(ctxFile, "utf8");
8199
+ const goalIdx = body.indexOf("## Goal");
8200
+ const slice = goalIdx >= 0 ? body.slice(goalIdx) : body;
8201
+ const next = slice.indexOf("\n## ", 1);
8202
+ const excerpt = (next > 0 ? slice.slice(0, next) : slice).trim();
8203
+ return excerpt.length > budget * 4 ? excerpt.slice(0, budget * 4) : excerpt;
8204
+ }
8205
+ } catch {
8206
+ }
8207
+ return null;
8208
+ }
8209
+ function buildInjection(repoRoot, wf, learningsMd, budget = DEFAULT_INJECT_BUDGET, intent = null, nowMs = Date.now()) {
8210
+ const ledgerEmpty = (wf?.sub_progress ?? []).length === 0;
8211
+ const intentBlock = ledgerEmpty ? buildIntentBlock(intent, nowMs) : "";
8212
+ if (!wf) return intentBlock;
8213
+ const forward = nextPending(wf.sub_progress ?? []) === null ? forwardPointer(repoRoot, wf) : null;
8214
+ const ws = buildWorkflowStateBlock(wf, forward);
8215
+ const ledgerSubs = (wf.sub_progress ?? []).map((e) => e.sub);
8216
+ const rel = selectWithinBudget(
8217
+ filterRelevantLearnings(parseLearnings(learningsMd), { phase: wf.phase, ledgerSubs }),
8218
+ budget
8219
+ );
8220
+ const usedTokens = rel.reduce((a, e) => a + tok(e.raw), 0);
8221
+ const ctx = findPhaseContextExcerpt(repoRoot, wf.phase, Math.max(0, budget - usedTokens));
8222
+ const pc2 = buildProjectContextBlock({ learnings: rel, contextExcerpt: ctx ?? void 0 });
8223
+ const normal = pc2 ? `${ws}
8224
+ ${pc2}` : ws;
8225
+ return intentBlock ? `${intentBlock}
8226
+ ${normal}` : normal;
8227
+ }
8228
+ function forwardPointer(repoRoot, wf) {
8229
+ const snapshot = scanPlanning({ repoRoot, currentWorkflow: wf, includeTasks: false });
8230
+ const unit = deriveNext(snapshot);
8231
+ if (unit.kind !== "phase" && unit.kind !== "task") return null;
8232
+ return { unit, remainingPhases: snapshot.phases.filter((p7) => !p7.complete).length };
8233
+ }
8234
+ var INTENT_TTL_MS, DEFAULT_INJECT_BUDGET, tok;
8235
+ var init_injectState = __esm({
8236
+ "src/checkpoint/injectState.ts"() {
8237
+ init_breakLoop();
8238
+ init_deriveNext();
8239
+ init_forwardStep();
8240
+ init_ledger();
8241
+ init_planningScan();
8242
+ INTENT_TTL_MS = 24 * 60 * 60 * 1e3;
8243
+ DEFAULT_INJECT_BUDGET = 1500;
8244
+ tok = (s) => Math.ceil(Buffer.byteLength(s, "utf8") / 4);
8245
+ }
8246
+ });
8247
+
7715
8248
  // src/cli/lib/release-preflight.ts
7716
8249
  var release_preflight_exports = {};
7717
8250
  __export(release_preflight_exports, {
7718
8251
  anyFailed: () => anyFailed,
7719
8252
  collectPreflight: () => collectPreflight,
7720
- defaultDeps: () => defaultDeps2
8253
+ defaultDeps: () => defaultDeps3
7721
8254
  });
7722
8255
  function unreleasedSection(changelog) {
7723
8256
  const start = changelog.indexOf("## [Unreleased]");
@@ -7772,7 +8305,7 @@ function collectPreflight(deps) {
7772
8305
  function anyFailed(checks) {
7773
8306
  return checks.some((c) => c.status === "fail");
7774
8307
  }
7775
- function defaultDeps2(cwd) {
8308
+ function defaultDeps3(cwd) {
7776
8309
  let changelog = "";
7777
8310
  let version = "";
7778
8311
  try {
@@ -8563,7 +9096,7 @@ function registerBackupList(program2) {
8563
9096
  // src/cli/checkpoint.ts
8564
9097
  init_path_guard();
8565
9098
  init_ledger();
8566
- var ACTIONS = ["start", "complete", "fail"];
9099
+ var ACTIONS = ["start", "complete", "fail", "intent"];
8567
9100
  function isAction(a) {
8568
9101
  return ACTIONS.includes(a);
8569
9102
  }
@@ -8590,9 +9123,24 @@ async function parsePlan(raw) {
8590
9123
  }
8591
9124
  return plan;
8592
9125
  }
9126
+ async function absorbIntentFor(sub) {
9127
+ try {
9128
+ const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
9129
+ const { activeKey: activeKey2, repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
9130
+ await mutateStore2((store) => {
9131
+ if (!store.intents) return store;
9132
+ const intents = { ...store.intents };
9133
+ for (const k of [activeKey2(), repoKey2()]) {
9134
+ if (intents[k]?.master === sub) delete intents[k];
9135
+ }
9136
+ return { ...store, intents };
9137
+ });
9138
+ } catch {
9139
+ }
9140
+ }
8593
9141
  function registerCheckpoint(program2) {
8594
9142
  program2.command("checkpoint <action> <sub>").description(
8595
- "Record workflow progress: start | complete | fail <sub-workflow> (writes to ~/.claude/harnessed/checkpoints/)"
9143
+ "Record workflow progress: intent | start | complete | fail <sub-workflow> (writes to ~/.claude/harnessed/checkpoints/)"
8596
9144
  ).option("--summary <text>", "short summary stored as the checkpoint lastTask").option("--plan <json>", "gates plan JSON (start only) \u2014 seeds the sub-progress ledger").option(
8597
9145
  "--force",
8598
9146
  "complete only \u2014 override a missing-artifact evidence block (records overridden)"
@@ -8608,6 +9156,30 @@ function registerCheckpoint(program2) {
8608
9156
  process.exit(1);
8609
9157
  return;
8610
9158
  }
9159
+ if (action === "intent") {
9160
+ try {
9161
+ checkPathSafe(sub);
9162
+ const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
9163
+ const { activeKey: activeKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
9164
+ const { classifyIntentKind: classifyIntentKind2 } = await Promise.resolve().then(() => (init_intentKind(), intentKind_exports));
9165
+ const { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
9166
+ const kind = classifyIntentKind2(sub, getAssetsRoot2());
9167
+ const key = activeKey2();
9168
+ await mutateStore2((store) => ({
9169
+ ...store,
9170
+ intents: {
9171
+ ...store.intents ?? {},
9172
+ [key]: { master: sub, ts: (/* @__PURE__ */ new Date()).toISOString(), kind }
9173
+ }
9174
+ }));
9175
+ console.log(
9176
+ kind === "master" ? `[harnessed] engine engaged: /${sub} invoked \u2014 intent registered, ledger awaiting plan. Next: \`harnessed gates ${sub} --task "<locked spec>"\` \u2192 \`harnessed checkpoint start ${sub} --plan '<gates JSON>'\`. Freestyling past this point bypasses the ledger, evidence guard, and recovery.` : `[harnessed] engine engaged: /${sub} invoked \u2014 intent registered, sub not yet checkpointed. Next: \`harnessed prompt ${sub} --task "<spec>" --json\` \u2192 spawn per SOP \u2192 \`harnessed checkpoint complete ${sub}\` (or \`fail\`). Freestyling past this point bypasses the ledger, evidence guard, and recovery.`
9177
+ );
9178
+ } catch {
9179
+ }
9180
+ process.exit(0);
9181
+ return;
9182
+ }
8611
9183
  try {
8612
9184
  checkPathSafe(sub);
8613
9185
  } catch {
@@ -8617,6 +9189,54 @@ function registerCheckpoint(program2) {
8617
9189
  }
8618
9190
  const { activatePhase: activatePhase2, completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
8619
9191
  if (action === "start") {
9192
+ try {
9193
+ const { stat: statFs } = await import('fs/promises');
9194
+ const { resolve: resolvePath } = await import('path');
9195
+ const planningDir = resolvePath(process.cwd(), ".planning");
9196
+ const hasPlanning = await statFs(planningDir).then((s) => s.isDirectory()).catch(() => false);
9197
+ if (hasPlanning) {
9198
+ const missing = [];
9199
+ for (const f of ["STATE.md", "ROADMAP.md"]) {
9200
+ const ok = await statFs(resolvePath(planningDir, f)).then((s) => s.isFile()).catch(() => false);
9201
+ if (!ok) missing.push(`.planning/${f}`);
9202
+ }
9203
+ if (missing.length > 0) {
9204
+ console.error(
9205
+ `\u26A0\uFE0F [harnessed] step 0 skeleton missing (${missing.join(", ")}) \u2014 the evidence guard's planning-sync gate will block \`checkpoint complete\`. Create the skeleton first (see the /auto SKILL step 0).`
9206
+ );
9207
+ }
9208
+ }
9209
+ } catch {
9210
+ }
9211
+ try {
9212
+ const { detectGateGuardActive: detectGateGuardActive2, GUARD_CONFLICT_ADVICE: GUARD_CONFLICT_ADVICE2 } = await Promise.resolve().then(() => (init_check_guard_conflict(), check_guard_conflict_exports));
9213
+ const det = await detectGateGuardActive2();
9214
+ if (det.active) {
9215
+ const { findGateguardYml: findGateguardYml2, runExemptionFlow: runExemptionFlow2 } = await Promise.resolve().then(() => (init_guard_exemption(), guard_exemption_exports));
9216
+ const isTty = process.stdin.isTTY === true && process.stdout.isTTY === true;
9217
+ const flowResult = await runExemptionFlow2({
9218
+ findYml: () => findGateguardYml2(),
9219
+ print: (line) => console.error(line),
9220
+ ...isTty ? {
9221
+ confirm: async () => {
9222
+ const p7 = await import('@clack/prompts');
9223
+ const ans = await p7.confirm({
9224
+ message: 'Apply the GateGuard exemption now? (appends ".planning/**" to ignore_paths \u2014 backed up first)',
9225
+ initialValue: true
9226
+ // D1 — default YES
9227
+ });
9228
+ return !p7.isCancel(ans) && ans === true;
9229
+ }
9230
+ } : {}
9231
+ });
9232
+ if (flowResult === "no-yml") {
9233
+ console.error(
9234
+ `\u26A0\uFE0F [harnessed] ECC GateGuard appears active (via ${det.source}) \u2014 its filename policy (report/findings/summary/analysis) collides with the evidence-guard artifact names (findings.md, *-report.md); subagent Writes have no fact-retry channel and \`checkpoint complete\` will block. ` + GUARD_CONFLICT_ADVICE2
9235
+ );
9236
+ }
9237
+ }
9238
+ } catch {
9239
+ }
8620
9240
  const { checkpointPath } = await activatePhase2(sub);
8621
9241
  const plan = await parsePlan(opts.plan);
8622
9242
  if (plan) {
@@ -8624,6 +9244,18 @@ function registerCheckpoint(program2) {
8624
9244
  const { mutateSubProgress: mutateSubProgress3 } = await Promise.resolve().then(() => (init_state(), state_exports));
8625
9245
  await mutateSubProgress3(() => seedLedger2(plan));
8626
9246
  }
9247
+ try {
9248
+ const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
9249
+ const { activeKey: activeKey2, repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
9250
+ await mutateStore2((store) => {
9251
+ if (!store.intents) return store;
9252
+ const intents = { ...store.intents };
9253
+ delete intents[activeKey2()];
9254
+ delete intents[repoKey2()];
9255
+ return { ...store, intents };
9256
+ });
9257
+ } catch {
9258
+ }
8627
9259
  console.log(`[harnessed] checkpoint started: ${sub} \u2192 ${checkpointPath}`);
8628
9260
  process.exit(0);
8629
9261
  return;
@@ -8653,6 +9285,7 @@ function registerCheckpoint(program2) {
8653
9285
  else evidenceStatus = "none_declared";
8654
9286
  const markOpts = evidenceStatus === "none_declared" ? { evidence_status: evidenceStatus } : { evidence: result.found, evidence_status: evidenceStatus };
8655
9287
  await mutateSubProgress3((e) => markIfSeeded(e, sub, "done", markOpts));
9288
+ await absorbIntentFor(sub);
8656
9289
  const { collectScaleMetrics: collectScaleMetrics2, assessScale: assessScale2 } = await Promise.resolve().then(() => (init_scale(), scale_exports));
8657
9290
  const { readCurrentWorkflow: readCurrentWorkflow3, writeCurrentWorkflow: writeCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
8658
9291
  const afterMark = await readCurrentWorkflow3();
@@ -8719,6 +9352,7 @@ function registerCheckpoint(program2) {
8719
9352
  }
8720
9353
  const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
8721
9354
  await mutateSubProgress2((e) => markIfSeeded(e, sub, "failed"));
9355
+ await absorbIntentFor(sub);
8722
9356
  await completePhase2({
8723
9357
  phaseId: sub,
8724
9358
  status: "complete",
@@ -8794,12 +9428,37 @@ function registerDoctor(program2) {
8794
9428
  });
8795
9429
  }
8796
9430
 
9431
+ // src/cli/exempt-gateguard.ts
9432
+ init_guard_exemption();
9433
+ function registerExemptGateguard(program2) {
9434
+ program2.command("exempt-gateguard").description(
9435
+ `Add ".planning/**" to GateGuard's ignore_paths (.gateguard.yml) \u2014 resolves the dual-guard filename conflict with the harnessed evidence guard (backup-first, append-only)`
9436
+ ).action(async () => {
9437
+ const result = await runExemptionFlow({
9438
+ print: (line) => console.log(line),
9439
+ confirm: async () => true
9440
+ // consent = invocation (see header)
9441
+ });
9442
+ if (result === "already") {
9443
+ console.log(
9444
+ "\u2713 [harnessed] .planning/** is already exempted in .gateguard.yml \u2014 nothing to do."
9445
+ );
9446
+ }
9447
+ if (result === "no-yml") {
9448
+ console.log(
9449
+ "[harnessed] no .gateguard.yml found (project cwd or home). Your GateGuard variant is likely the bundled ecc fact-forcing hook (no filename policy / no config file) or a custom hookify rule. If subagent Writes are being blocked: have the MAIN session perform the artifact writes, or set ECC_GATEGUARD=off for harnessed-orchestrated sessions."
9450
+ );
9451
+ }
9452
+ process.exit(result === "error" ? 1 : 0);
9453
+ });
9454
+ }
9455
+
8797
9456
  // src/cli/gates.ts
8798
9457
  init_path_guard();
8799
9458
  init_judgmentResolver();
8800
9459
  init_assetsRoot();
8801
9460
  init_gateContext();
8802
- var VALID_MASTERS = /* @__PURE__ */ new Set(["auto", "discuss", "plan", "task", "verify"]);
9461
+ var VALID_MASTERS = /* @__PURE__ */ new Set(["auto", "discuss", "plan", "task", "verify", "ship"]);
8803
9462
  var STAGE_MASTERS = /* @__PURE__ */ new Set(["discuss", "plan", "task", "verify"]);
8804
9463
  var PARALLELISM_GATE = "judgments.parallelism-gate.agent-teams-upgrade.fires";
8805
9464
  function resolveMasterYamlPath2(master, packageRoot) {
@@ -8808,10 +9467,15 @@ function resolveMasterYamlPath2(master, packageRoot) {
8808
9467
  function registerGates(program2) {
8809
9468
  program2.command("gates").description(
8810
9469
  "Evaluate which sub-workflows fire for a master orchestrator (JSON plan, no spawn)."
8811
- ).argument("<master>", "master name: auto | discuss | plan | task | verify").option("--task <text>", "task description (injected as gateContext.task)").option("--skip-sub <names>", "comma-separated sub names to skip without gate eval").option("--context <json>", "JSON object merged over the default gate context").action(async (master, raw) => {
9470
+ ).argument("<master>", "master name: auto | discuss | plan | task | verify | ship").option("--task <text>", "task description (injected as gateContext.task)").option(
9471
+ "--skip-sub <names>",
9472
+ "sub names to skip without gate eval (repeatable and/or comma-separated)",
9473
+ (v, prev) => [...prev, v],
9474
+ []
9475
+ ).option("--context <json>", "JSON object merged over the default gate context").action(async (master, raw) => {
8812
9476
  if (!VALID_MASTERS.has(master)) {
8813
9477
  console.error(
8814
- `error: unknown master '${master}'. Expected one of: auto, discuss, plan, task, verify.`
9478
+ `error: unknown master '${master}'. Expected one of: auto, discuss, plan, task, verify, ship.`
8815
9479
  );
8816
9480
  process.exit(1);
8817
9481
  return;
@@ -8867,7 +9531,7 @@ function registerGates(program2) {
8867
9531
  }
8868
9532
  }
8869
9533
  const skipSubs = new Set(
8870
- typeof raw.skipSub === "string" && raw.skipSub.length > 0 ? raw.skipSub.split(",").map((s) => s.trim()).filter((s) => s.length > 0) : []
9534
+ (Array.isArray(raw.skipSub) ? raw.skipSub : []).flatMap((v) => v.split(",")).map((s) => s.trim()).filter((s) => s.length > 0)
8871
9535
  );
8872
9536
  ctx.skip_subs = [...skipSubs];
8873
9537
  const fire = [];
@@ -9155,8 +9819,14 @@ function evidenceLabel(entry) {
9155
9819
  return "evidence: none_declared";
9156
9820
  }
9157
9821
  }
9158
- async function buildRecoverLines(workflow, ledger) {
9822
+ async function buildRecoverLines(workflow, ledger, intent) {
9159
9823
  const lines = [];
9824
+ if (intent) {
9825
+ const { formatIntentAge: formatIntentAge2 } = await Promise.resolve().then(() => (init_injectState(), injectState_exports));
9826
+ lines.push(
9827
+ `\u26A0 intent pending: /${intent.master} invoked ${formatIntentAge2(intent.ageMs)} ago \u2014 ledger not seeded; run \`harnessed gates ${intent.master}\` \u2192 \`harnessed checkpoint start ${intent.master} --plan '<gates JSON>'\``
9828
+ );
9829
+ }
9160
9830
  if (!workflow || ledger.length === 0) {
9161
9831
  lines.push("no ledger \u2014 run gates + start");
9162
9832
  return lines;
@@ -9194,7 +9864,22 @@ function registerStatus(program2) {
9194
9864
  if (opts.recover) {
9195
9865
  const wf = await readCurrentWorkflow();
9196
9866
  const ledger = wf?.sub_progress ?? [];
9197
- const lines = await buildRecoverLines(wf, ledger);
9867
+ let intent = null;
9868
+ if (ledger.length === 0) {
9869
+ try {
9870
+ const { readIntent: readIntent2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
9871
+ const { INTENT_TTL_MS: INTENT_TTL_MS2 } = await Promise.resolve().then(() => (init_injectState(), injectState_exports));
9872
+ const raw = await readIntent2();
9873
+ if (raw) {
9874
+ const age = Date.now() - Date.parse(raw.ts);
9875
+ if (!Number.isNaN(age) && age >= 0 && age <= INTENT_TTL_MS2) {
9876
+ intent = { master: raw.master, ageMs: age };
9877
+ }
9878
+ }
9879
+ } catch {
9880
+ }
9881
+ }
9882
+ const lines = await buildRecoverLines(wf, ledger, intent);
9198
9883
  for (const l of lines) console.log(l);
9199
9884
  return;
9200
9885
  }
@@ -9570,8 +10255,8 @@ function registerReleasePreflight(program2) {
9570
10255
  program2.command("release-preflight").description(
9571
10256
  "Read-only release-readiness gate (CHANGELOG / version / git-clean / tag). Exits 1 if not ready."
9572
10257
  ).action(async () => {
9573
- const { collectPreflight: collectPreflight2, anyFailed: anyFailed2, defaultDeps: defaultDeps3 } = await Promise.resolve().then(() => (init_release_preflight(), release_preflight_exports));
9574
- const checks = collectPreflight2(defaultDeps3(process.cwd()));
10258
+ const { collectPreflight: collectPreflight2, anyFailed: anyFailed2, defaultDeps: defaultDeps4 } = await Promise.resolve().then(() => (init_release_preflight(), release_preflight_exports));
10259
+ const checks = collectPreflight2(defaultDeps4(process.cwd()));
9575
10260
  console.log("\n release preflight (read-only \u2014 nothing is pushed/published):\n");
9576
10261
  for (const c of checks) {
9577
10262
  const mark = c.status === "pass" ? "\u2713" : c.status === "warn" ? "\u26A0" : "\u2717";
@@ -11348,6 +12033,7 @@ registerAdvance(program);
11348
12033
  registerReject(program);
11349
12034
  registerCompact(program);
11350
12035
  registerWorkflows(program);
12036
+ registerExemptGateguard(program);
11351
12037
  registerLearn(program);
11352
12038
  registerUpdate(program);
11353
12039
  registerReleasePreflight(program);