harnessed 4.29.0 → 4.31.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.
package/dist/cli.mjs CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync, readdirSync, statSync } from 'fs';
3
- import { homedir } from 'os';
4
- import { join, resolve, dirname, basename, sep, win32, relative } from 'path';
2
+ import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync, readdirSync, realpathSync, mkdtempSync, utimesSync, rmSync, statSync } from 'fs';
3
+ import { homedir, tmpdir } from 'os';
4
+ import { join, resolve, dirname, basename, sep, isAbsolute, win32, relative } from 'path';
5
5
  import { Type } from '@sinclair/typebox';
6
6
  import { readFile, readdir, unlink, writeFile, stat, rm, cp, mkdir, access, rename, appendFile, copyFile, chmod } from 'fs/promises';
7
7
  import { Value } from '@sinclair/typebox/value';
8
8
  import lockfile from 'proper-lockfile';
9
- import { parse, LineCounter, parseDocument, isSeq, isScalar } from 'yaml';
9
+ import { LineCounter, parseDocument, parse, isSeq, isScalar } from 'yaml';
10
10
  import { Ajv } from 'ajv';
11
11
  import * as ajvFormatsNs from 'ajv-formats';
12
- import { execFileSync, spawnSync, spawn, exec, execSync, execFile } from 'child_process';
12
+ import { execFileSync, spawnSync, spawn, execSync, exec, execFile } from 'child_process';
13
13
  import { pathToFileURL, fileURLToPath } from 'url';
14
14
  import { createHash } from 'crypto';
15
15
  import { Parser } from 'expr-eval';
@@ -38,7 +38,7 @@ var init_package = __esm({
38
38
  "package.json"() {
39
39
  package_default = {
40
40
  name: "harnessed",
41
- version: "4.29.0",
41
+ version: "4.31.0",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -1177,7 +1177,9 @@ var init_ccHookAdd = __esm({
1177
1177
  Type.Literal("SessionStart"),
1178
1178
  Type.Literal("UserPromptSubmit"),
1179
1179
  Type.Literal("PreToolUse"),
1180
- Type.Literal("PostToolUse")
1180
+ Type.Literal("PostToolUse"),
1181
+ // 4.30.0 (issue #6) — Stop hook for mode-B tool-call corruption auto-recovery.
1182
+ Type.Literal("Stop")
1181
1183
  ]);
1182
1184
  CcHookAdd = Type.Object(
1183
1185
  {
@@ -2147,107 +2149,51 @@ var init_path_guard = __esm({
2147
2149
  }
2148
2150
  });
2149
2151
 
2150
- // src/checkpoint/intentKind.ts
2151
- var intentKind_exports = {};
2152
- __export(intentKind_exports, {
2153
- classifyIntentKind: () => classifyIntentKind
2154
- });
2155
- function classifyIntentKind(sub, assetsRoot) {
2156
- try {
2157
- const raw = readFileSync(join(assetsRoot, "workflows", "role-prompts.yaml"), "utf8");
2158
- const doc = parse(raw);
2159
- return doc?.prompts?.[sub]?.is_master === true ? "master" : "leaf";
2160
- } catch {
2161
- return "leaf";
2162
- }
2163
- }
2164
- var init_intentKind = __esm({
2165
- "src/checkpoint/intentKind.ts"() {
2166
- }
2167
- });
2168
- function getPackageRoot() {
2169
- const thisFile = fileURLToPath(import.meta.url);
2170
- const thisDir = dirname(thisFile);
2171
- if (thisDir.endsWith("dist") || thisDir.replace(/\\/g, "/").endsWith("/dist")) {
2172
- return resolve(thisDir, "..");
2173
- }
2174
- return resolve(thisDir, "..", "..", "..");
2175
- }
2176
- var init_packagePath = __esm({
2177
- "src/cli/lib/packagePath.ts"() {
2178
- }
2179
- });
2180
-
2181
- // src/cli/lib/assetsRoot.ts
2182
- var assetsRoot_exports = {};
2183
- __export(assetsRoot_exports, {
2184
- compiledAssetsDir: () => compiledAssetsDir,
2185
- computeAssetsRoot: () => computeAssetsRoot,
2186
- getAssetsRoot: () => getAssetsRoot,
2187
- isCompiledModuleUrl: () => isCompiledModuleUrl,
2188
- isCompiledRuntime: () => isCompiledRuntime
2189
- });
2190
- function isCompiledRuntime(url = import.meta.url) {
2191
- return isCompiledModuleUrl(url);
2192
- }
2193
- function isCompiledModuleUrl(url) {
2194
- let s = url;
2195
- try {
2196
- s = decodeURIComponent(url);
2197
- } catch {
2198
- }
2199
- const normalized2 = s.replace(/\\/g, "/").toLowerCase();
2200
- return BUNFS_MARKERS.some((m) => normalized2.includes(m));
2201
- }
2202
- function computeAssetsRoot(d) {
2203
- const override = d.env.HARNESSED_ASSETS_OVERRIDE;
2204
- if (override && override.trim().length > 0) {
2205
- return { root: override.trim(), source: "override", compiledAssetsMissing: false };
2206
- }
2207
- if (isCompiledModuleUrl(d.moduleUrl)) {
2208
- const root = join(d.stateRoot(), "assets", d.version);
2209
- const present = d.exists(join(root, "workflows"));
2210
- return { root, source: "compiled", compiledAssetsMissing: !present };
2211
- }
2212
- return { root: d.packageRoot, source: "package", compiledAssetsMissing: false };
2213
- }
2214
- function compiledAssetsDir(version) {
2215
- return join(detectPlatform().stateRoot, "assets", version);
2216
- }
2217
- function realDeps() {
2218
- return {
2219
- env: process.env,
2220
- moduleUrl: import.meta.url,
2221
- exists: (p7) => {
2222
- try {
2223
- return existsSync(p7);
2224
- } catch {
2225
- return false;
2226
- }
2152
+ // src/cli/lib/runDeps.ts
2153
+ function captureRunDeps() {
2154
+ const stdout2 = [];
2155
+ const stderr = [];
2156
+ const deps = {
2157
+ exit(code) {
2158
+ throw new ExitError(code);
2227
2159
  },
2228
- stateRoot: () => detectPlatform().stateRoot,
2229
- packageRoot: getPackageRoot(),
2230
- version: package_default.version
2160
+ log: (...args) => {
2161
+ stdout2.push(args.map(String).join(" "));
2162
+ },
2163
+ error: (...args) => {
2164
+ stderr.push(args.map(String).join(" "));
2165
+ },
2166
+ warn: (...args) => {
2167
+ stderr.push(args.map(String).join(" "));
2168
+ }
2231
2169
  };
2232
- }
2233
- function getAssetsRoot() {
2234
- const r = computeAssetsRoot(realDeps());
2235
- if (r.source === "compiled" && r.compiledAssetsMissing && !warnedMissing) {
2236
- warnedMissing = true;
2237
- console.error(
2238
- `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)`
2239
- );
2240
- }
2241
- return r.root;
2242
- }
2243
- var BUNFS_MARKERS, warnedMissing;
2244
- var init_assetsRoot = __esm({
2245
- "src/cli/lib/assetsRoot.ts"() {
2246
- init_package();
2247
- init_platform();
2248
- init_packagePath();
2249
- BUNFS_MARKERS = ["/$bunfs/", "/~bun/"];
2250
- warnedMissing = false;
2170
+ return { deps, stdout: stdout2, stderr };
2171
+ }
2172
+ var ExitError, defaultRunDeps;
2173
+ var init_runDeps = __esm({
2174
+ "src/cli/lib/runDeps.ts"() {
2175
+ ExitError = class extends Error {
2176
+ constructor(code) {
2177
+ super(`process.exit(${code})`);
2178
+ this.code = code;
2179
+ this.name = "ExitError";
2180
+ }
2181
+ code;
2182
+ };
2183
+ defaultRunDeps = {
2184
+ exit(code) {
2185
+ return process.exit(code);
2186
+ },
2187
+ log: (...args) => {
2188
+ console.log(...args);
2189
+ },
2190
+ error: (...args) => {
2191
+ console.error(...args);
2192
+ },
2193
+ warn: (...args) => {
2194
+ console.warn(...args);
2195
+ }
2196
+ };
2251
2197
  }
2252
2198
  });
2253
2199
  function estimateTokens(s) {
@@ -3231,7 +3177,7 @@ function nameToYamlHintPath(name) {
3231
3177
  function shouldOverwriteFile(content) {
3232
3178
  return HARNESSED_MARKER_RX.test(content) || V3_4_3_SIGNATURE_SUB_RX.test(content) || V3_4_3_SIGNATURE_MASTER_RX.test(content);
3233
3179
  }
3234
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync16 = (p7) => readFileSync(p7, "utf8")) {
3180
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync18 = (p7) => readFileSync(p7, "utf8")) {
3235
3181
  const results = [];
3236
3182
  const aggregatedWarnings = /* @__PURE__ */ new Set();
3237
3183
  for (const name of slashNames) {
@@ -3250,7 +3196,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
3250
3196
  if (fileExists2(path)) {
3251
3197
  let existing = "";
3252
3198
  try {
3253
- existing = readFileSync16(path);
3199
+ existing = readFileSync18(path);
3254
3200
  } catch {
3255
3201
  existing = "";
3256
3202
  }
@@ -3683,6 +3629,14 @@ var init_judgment = __esm({
3683
3629
  );
3684
3630
  }
3685
3631
  });
3632
+
3633
+ // src/workflow/judgmentResolver.ts
3634
+ var judgmentResolver_exports = {};
3635
+ __export(judgmentResolver_exports, {
3636
+ TriggerNotFoundError: () => TriggerNotFoundError,
3637
+ _clearJudgmentCache: () => _clearJudgmentCache,
3638
+ resolveJudgmentGate: () => resolveJudgmentGate
3639
+ });
3686
3640
  async function resolveJudgmentGate(gateRef, context, packageRoot) {
3687
3641
  const userOverrides = context.user_overrides;
3688
3642
  if (Array.isArray(userOverrides) && userOverrides.includes(gateRef)) {
@@ -3719,6 +3673,9 @@ async function resolveJudgmentGate(gateRef, context, packageRoot) {
3719
3673
  }
3720
3674
  return evalGate(expr, context);
3721
3675
  }
3676
+ function _clearJudgmentCache() {
3677
+ _fileCache.clear();
3678
+ }
3722
3679
  var TriggerNotFoundError, _fileCache;
3723
3680
  var init_judgmentResolver = __esm({
3724
3681
  "src/workflow/judgmentResolver.ts"() {
@@ -3935,6 +3892,9 @@ function matchSkipSub(requested, sub, master) {
3935
3892
  if (requested.has(sub)) return sub;
3936
3893
  const alias = `${master}-${sub}`;
3937
3894
  if (requested.has(alias)) return alias;
3895
+ for (const [syn, canonical] of Object.entries(SKIP_SYNONYMS)) {
3896
+ if (canonical === sub && requested.has(syn)) return syn;
3897
+ }
3938
3898
  return null;
3939
3899
  }
3940
3900
  function warnUnmatchedSkips(requested, matched, master, validSubs, warn) {
@@ -3945,8 +3905,10 @@ function warnUnmatchedSkips(requested, matched, master, validSubs, warn) {
3945
3905
  );
3946
3906
  }
3947
3907
  }
3908
+ var SKIP_SYNONYMS;
3948
3909
  var init_skipSubs = __esm({
3949
3910
  "src/workflow/skipSubs.ts"() {
3911
+ SKIP_SYNONYMS = { clarify: "discuss" };
3950
3912
  }
3951
3913
  });
3952
3914
  function resolveMasterYamlPath(masterName, packageRoot) {
@@ -4510,6 +4472,91 @@ This applies to: strategic-layer review skip / phase-layer clarification skip /
4510
4472
  };
4511
4473
  }
4512
4474
  });
4475
+ function getPackageRoot() {
4476
+ const thisFile = fileURLToPath(import.meta.url);
4477
+ const thisDir = dirname(thisFile);
4478
+ if (thisDir.endsWith("dist") || thisDir.replace(/\\/g, "/").endsWith("/dist")) {
4479
+ return resolve(thisDir, "..");
4480
+ }
4481
+ return resolve(thisDir, "..", "..", "..");
4482
+ }
4483
+ var init_packagePath = __esm({
4484
+ "src/cli/lib/packagePath.ts"() {
4485
+ }
4486
+ });
4487
+
4488
+ // src/cli/lib/assetsRoot.ts
4489
+ var assetsRoot_exports = {};
4490
+ __export(assetsRoot_exports, {
4491
+ compiledAssetsDir: () => compiledAssetsDir,
4492
+ computeAssetsRoot: () => computeAssetsRoot,
4493
+ getAssetsRoot: () => getAssetsRoot,
4494
+ isCompiledModuleUrl: () => isCompiledModuleUrl,
4495
+ isCompiledRuntime: () => isCompiledRuntime
4496
+ });
4497
+ function isCompiledRuntime(url = import.meta.url) {
4498
+ return isCompiledModuleUrl(url);
4499
+ }
4500
+ function isCompiledModuleUrl(url) {
4501
+ let s = url;
4502
+ try {
4503
+ s = decodeURIComponent(url);
4504
+ } catch {
4505
+ }
4506
+ const normalized2 = s.replace(/\\/g, "/").toLowerCase();
4507
+ return BUNFS_MARKERS.some((m) => normalized2.includes(m));
4508
+ }
4509
+ function computeAssetsRoot(d) {
4510
+ const override = d.env.HARNESSED_ASSETS_OVERRIDE;
4511
+ if (override && override.trim().length > 0) {
4512
+ return { root: override.trim(), source: "override", compiledAssetsMissing: false };
4513
+ }
4514
+ if (isCompiledModuleUrl(d.moduleUrl)) {
4515
+ const root = join(d.stateRoot(), "assets", d.version);
4516
+ const present = d.exists(join(root, "workflows"));
4517
+ return { root, source: "compiled", compiledAssetsMissing: !present };
4518
+ }
4519
+ return { root: d.packageRoot, source: "package", compiledAssetsMissing: false };
4520
+ }
4521
+ function compiledAssetsDir(version) {
4522
+ return join(detectPlatform().stateRoot, "assets", version);
4523
+ }
4524
+ function realDeps() {
4525
+ return {
4526
+ env: process.env,
4527
+ moduleUrl: import.meta.url,
4528
+ exists: (p7) => {
4529
+ try {
4530
+ return existsSync(p7);
4531
+ } catch {
4532
+ return false;
4533
+ }
4534
+ },
4535
+ stateRoot: () => detectPlatform().stateRoot,
4536
+ packageRoot: getPackageRoot(),
4537
+ version: package_default.version
4538
+ };
4539
+ }
4540
+ function getAssetsRoot() {
4541
+ const r = computeAssetsRoot(realDeps());
4542
+ if (r.source === "compiled" && r.compiledAssetsMissing && !warnedMissing) {
4543
+ warnedMissing = true;
4544
+ console.error(
4545
+ `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)`
4546
+ );
4547
+ }
4548
+ return r.root;
4549
+ }
4550
+ var BUNFS_MARKERS, warnedMissing;
4551
+ var init_assetsRoot = __esm({
4552
+ "src/cli/lib/assetsRoot.ts"() {
4553
+ init_package();
4554
+ init_platform();
4555
+ init_packagePath();
4556
+ BUNFS_MARKERS = ["/$bunfs/", "/~bun/"];
4557
+ warnedMissing = false;
4558
+ }
4559
+ });
4513
4560
  async function loadUserOverrides(packageRoot) {
4514
4561
  const yamlPath = resolve(packageRoot, "workflows", "judgments", "user-overrides.yaml");
4515
4562
  let raw;
@@ -5207,43 +5254,407 @@ var init_breakLoop = __esm({
5207
5254
  LOOP_THRESHOLD = 3;
5208
5255
  }
5209
5256
  });
5210
- function realProbe(p7) {
5257
+
5258
+ // src/checkpoint/intentKind.ts
5259
+ var intentKind_exports = {};
5260
+ __export(intentKind_exports, {
5261
+ classifyIntentKind: () => classifyIntentKind
5262
+ });
5263
+ function classifyIntentKind(sub, assetsRoot) {
5211
5264
  try {
5212
- if (typeof spawnSync !== "function") return null;
5213
- const r = spawnSync(p7, ["-c", "echo harnessed-bash-ok"], { encoding: "utf8", timeout: 5e3 });
5214
- if (!r || r.error) return null;
5215
- return r.status === 0;
5265
+ const raw = readFileSync(join(assetsRoot, "workflows", "role-prompts.yaml"), "utf8");
5266
+ const doc = parse(raw);
5267
+ return doc?.prompts?.[sub]?.is_master === true ? "master" : "leaf";
5216
5268
  } catch {
5217
- return null;
5269
+ return "leaf";
5218
5270
  }
5219
5271
  }
5220
- function realWhere(name) {
5221
- try {
5222
- if (typeof spawnSync !== "function") return [];
5223
- const r = spawnSync("where", [name], { encoding: "utf8" });
5224
- if (!r || r.status !== 0) return [];
5225
- return (r.stdout ?? "").split(/\r?\n/).map((s) => s.trim()).filter((s) => s.length > 0);
5226
- } catch {
5227
- return [];
5272
+ var init_intentKind = __esm({
5273
+ "src/checkpoint/intentKind.ts"() {
5228
5274
  }
5275
+ });
5276
+
5277
+ // src/cli/checkpoint.ts
5278
+ var checkpoint_exports = {};
5279
+ __export(checkpoint_exports, {
5280
+ registerCheckpoint: () => registerCheckpoint,
5281
+ runCheckpointComplete: () => runCheckpointComplete,
5282
+ runCheckpointFail: () => runCheckpointFail,
5283
+ runCheckpointStart: () => runCheckpointStart
5284
+ });
5285
+ function isAction(a) {
5286
+ return ACTIONS.includes(a);
5229
5287
  }
5230
- function realExists(p7) {
5288
+ function markIfSeeded(entries, sub, status, opts) {
5289
+ return entries.some((e) => e.sub === sub) ? markSub(entries, sub, status, opts) : entries;
5290
+ }
5291
+ async function parsePlan(raw) {
5292
+ if (!raw || raw.trim() === "") return null;
5293
+ let parsed;
5231
5294
  try {
5232
- return existsSync(p7);
5295
+ parsed = JSON.parse(raw);
5233
5296
  } catch {
5234
- return false;
5297
+ return null;
5235
5298
  }
5236
- }
5237
- function defaultDeps2() {
5238
- return {
5239
- platform: process.platform,
5240
- env: process.env,
5241
- where: realWhere,
5242
- exists: realExists,
5243
- probe: realProbe
5299
+ const p7 = parsed;
5300
+ if (!Array.isArray(p7.fire) && !Array.isArray(p7.skip)) return null;
5301
+ const plan = {
5302
+ fire: Array.isArray(p7.fire) ? p7.fire : [],
5303
+ skip: Array.isArray(p7.skip) ? p7.skip : []
5244
5304
  };
5245
- }
5246
- function resolveBash(deps) {
5305
+ if (typeof p7.master === "string") plan.master = p7.master;
5306
+ if (p7.parallelism && typeof p7.parallelism === "object" && !Array.isArray(p7.parallelism)) {
5307
+ plan.parallelism = p7.parallelism;
5308
+ }
5309
+ return plan;
5310
+ }
5311
+ async function absorbIntentFor(sub) {
5312
+ try {
5313
+ const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
5314
+ const { activeKey: activeKey2, repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
5315
+ await mutateStore2((store) => {
5316
+ if (!store.intents) return store;
5317
+ const intents = { ...store.intents };
5318
+ for (const k of [activeKey2(), repoKey2()]) {
5319
+ if (intents[k]?.master === sub) delete intents[k];
5320
+ }
5321
+ return { ...store, intents };
5322
+ });
5323
+ } catch {
5324
+ }
5325
+ }
5326
+ async function serialOrderBlockers(sub, deps = defaultRunDeps) {
5327
+ try {
5328
+ const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
5329
+ const { findSerialBlockers: findSerialBlockers2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
5330
+ const wf = await readCurrentWorkflow2();
5331
+ return findSerialBlockers2(wf?.sub_progress ?? [], sub);
5332
+ } catch (e) {
5333
+ deps.warn(`[harnessed] serial-order guard skipped (fail-soft): ${e.message}`);
5334
+ return [];
5335
+ }
5336
+ }
5337
+ function enforceSerialOrder(action, sub, blockers, force, deps = defaultRunDeps) {
5338
+ if (blockers.length === 0) return true;
5339
+ if (!force) {
5340
+ deps.error(
5341
+ `[harnessed] checkpoint ${action} BLOCKED: ${sub} \u2014 ${blockers.length} earlier serial-sequence sub(s) still pending (serial-order guard, fail-closed):`
5342
+ );
5343
+ for (const b of blockers) deps.error(` - ${b} (complete or fail it first)`);
5344
+ deps.error(" (re-run with --force to jump the sequence deliberately)");
5345
+ return false;
5346
+ }
5347
+ deps.warn(
5348
+ `[harnessed] serial-order guard overridden (--force): ${action} ${sub} ahead of pending sub(s) ${blockers.join(", ")}`
5349
+ );
5350
+ return true;
5351
+ }
5352
+ async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
5353
+ const { activatePhase: activatePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
5354
+ try {
5355
+ const { stat: statFs } = await import('fs/promises');
5356
+ const { resolve: resolvePath } = await import('path');
5357
+ const planningDir = resolvePath(process.cwd(), ".planning");
5358
+ const hasPlanning = await statFs(planningDir).then((s) => s.isDirectory()).catch(() => false);
5359
+ if (hasPlanning) {
5360
+ const missing = [];
5361
+ for (const f of ["STATE.md", "ROADMAP.md"]) {
5362
+ const ok = await statFs(resolvePath(planningDir, f)).then((s) => s.isFile()).catch(() => false);
5363
+ if (!ok) missing.push(`.planning/${f}`);
5364
+ }
5365
+ if (missing.length > 0) {
5366
+ deps.error(
5367
+ `\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).`
5368
+ );
5369
+ }
5370
+ }
5371
+ } catch {
5372
+ }
5373
+ try {
5374
+ const { detectGateGuardActive: detectGateGuardActive2, GUARD_CONFLICT_ADVICE: GUARD_CONFLICT_ADVICE2 } = await Promise.resolve().then(() => (init_check_guard_conflict(), check_guard_conflict_exports));
5375
+ const det = await detectGateGuardActive2();
5376
+ if (det.active) {
5377
+ const ge = await Promise.resolve().then(() => (init_guard_exemption(), guard_exemption_exports));
5378
+ const isTty = process.stdin.isTTY === true && process.stdout.isTTY === true;
5379
+ const flowResult = await ge.runExemptionFlow({
5380
+ probe: () => ge.probeExemptCapability(),
5381
+ readEnvValue: () => ge.readCurrentEnvValue(),
5382
+ merge: (value) => ge.applyEnvExemption(value),
5383
+ print: (line) => deps.error(line),
5384
+ ...isTty ? {
5385
+ confirm: async () => {
5386
+ const p7 = await import('@clack/prompts');
5387
+ const ans = await p7.confirm({
5388
+ message: 'Apply the GateGuard exemption now? (persists GATEGUARD_EXEMPT_GLOBS=".planning/**" into settings env \u2014 backed up first)',
5389
+ initialValue: true
5390
+ // D1 — default YES
5391
+ });
5392
+ return !p7.isCancel(ans) && ans === true;
5393
+ }
5394
+ } : {}
5395
+ });
5396
+ if (flowResult === "not-capable") {
5397
+ deps.error(
5398
+ `\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
5399
+ );
5400
+ }
5401
+ }
5402
+ } catch {
5403
+ }
5404
+ const { checkpointPath } = await activatePhase2(sub);
5405
+ const plan = await parsePlan(opts.plan);
5406
+ if (plan) {
5407
+ const { seedLedger: seedLedger2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
5408
+ const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
5409
+ await mutateSubProgress2(() => seedLedger2(plan));
5410
+ }
5411
+ try {
5412
+ const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
5413
+ const { activeKey: activeKey2, repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
5414
+ await mutateStore2((store) => {
5415
+ if (!store.intents) return store;
5416
+ const intents = { ...store.intents };
5417
+ delete intents[activeKey2()];
5418
+ delete intents[repoKey2()];
5419
+ return { ...store, intents };
5420
+ });
5421
+ } catch {
5422
+ }
5423
+ deps.log(`[harnessed] checkpoint started: ${sub} \u2192 ${checkpointPath}`);
5424
+ deps.exit(0);
5425
+ return;
5426
+ }
5427
+ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
5428
+ const { completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
5429
+ if (!enforceSerialOrder("complete", sub, await serialOrderBlockers(sub, deps), opts.force, deps)) {
5430
+ deps.exit(1);
5431
+ return;
5432
+ }
5433
+ const { checkArtifacts: checkArtifacts2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
5434
+ const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
5435
+ const { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
5436
+ const result = await checkArtifacts2(sub, getAssetsRoot2());
5437
+ const { checkPlanningSync: checkPlanningSync2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
5438
+ const syncResult = await checkPlanningSync2(process.cwd(), null);
5439
+ const allMissing = [...result.missing, ...syncResult.missing];
5440
+ if (allMissing.length > 0 && !opts.force) {
5441
+ deps.error(
5442
+ `[harnessed] checkpoint complete BLOCKED: ${sub} \u2014 ${allMissing.length} item(s) missing (evidence guard + .planning/ sync, fail-closed):`
5443
+ );
5444
+ for (const m of allMissing) deps.error(` - ${m}`);
5445
+ deps.error(" (re-run with --force to override and record evidence_status=overridden)");
5446
+ deps.exit(1);
5447
+ return;
5448
+ }
5449
+ let evidenceStatus;
5450
+ if (allMissing.length > 0 && opts.force) evidenceStatus = "overridden";
5451
+ else if (result.status === "verified") evidenceStatus = "verified";
5452
+ else evidenceStatus = "none_declared";
5453
+ const markOpts = evidenceStatus === "none_declared" ? { evidence_status: evidenceStatus } : { evidence: result.found, evidence_status: evidenceStatus };
5454
+ await mutateSubProgress2((e) => markIfSeeded(e, sub, "done", markOpts));
5455
+ await absorbIntentFor(sub);
5456
+ const { collectScaleMetrics: collectScaleMetrics2, assessScale: assessScale2 } = await Promise.resolve().then(() => (init_scale(), scale_exports));
5457
+ const { readCurrentWorkflow: readCurrentWorkflow2, writeCurrentWorkflow: writeCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
5458
+ const afterMark = await readCurrentWorkflow2();
5459
+ if (afterMark) {
5460
+ const metrics = await collectScaleMetrics2(process.cwd(), afterMark.sub_progress ?? []);
5461
+ await writeCurrentWorkflow2({ ...afterMark, verify_mode: assessScale2(metrics) });
5462
+ }
5463
+ const { nextPending: nextPending2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
5464
+ const allResolved = nextPending2(afterMark?.sub_progress ?? []) === null;
5465
+ await completePhase2({
5466
+ phaseId: sub,
5467
+ status: "complete",
5468
+ lastTask: opts.summary ?? `phase ${sub} complete`,
5469
+ transitionWorkflowComplete: allResolved
5470
+ });
5471
+ if (allResolved && afterMark) {
5472
+ const { captureWorkflowLearnings: captureWorkflowLearnings2 } = await Promise.resolve().then(() => (init_learnings(), learnings_exports));
5473
+ const captured = await captureWorkflowLearnings2(afterMark.sub_progress ?? [], sub);
5474
+ if (captured > 0) {
5475
+ deps.log(`[harnessed] captured ${captured} learning(s) \u2192 .planning/LEARNINGS.md`);
5476
+ }
5477
+ }
5478
+ const { shouldAutoCompact: shouldAutoCompact2, compactWorkflow: compactWorkflow2 } = await Promise.resolve().then(() => (init_compact(), compact_exports));
5479
+ if (shouldAutoCompact2(opts.tokens != null ? Number(opts.tokens) : void 0)) {
5480
+ const c = await compactWorkflow2();
5481
+ if (c.evicted > 0) {
5482
+ deps.log(
5483
+ `[harnessed] auto-compact: evicted ${c.evicted} resolved entries (-${c.pct_saved}% tokens)`
5484
+ );
5485
+ }
5486
+ }
5487
+ if (allResolved) {
5488
+ try {
5489
+ const { defaultShipReady: defaultShipReady2 } = await Promise.resolve().then(() => (init_shipReady(), shipReady_exports));
5490
+ const { incrementPhases: incrementPhases2, isRetroDue: isRetroDue2, retroThreshold: retroThreshold2 } = await Promise.resolve().then(() => (init_retroMeta(), retroMeta_exports));
5491
+ const { mutateStore: mutateStore2, readCurrentWorkflow: readCurrentWorkflow3, writeCurrentWorkflow: writeCurrentWorkflow3 } = await Promise.resolve().then(() => (init_state(), state_exports));
5492
+ const { repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
5493
+ const ship = defaultShipReady2(process.cwd());
5494
+ const key = repoKey2();
5495
+ const threshold = retroThreshold2(process.env);
5496
+ let retroDue = false;
5497
+ await mutateStore2((store) => {
5498
+ const meta = { ...store.retro_meta ?? {} };
5499
+ const next = incrementPhases2(meta[key]);
5500
+ meta[key] = next;
5501
+ retroDue = isRetroDue2(next.phases_since_retro, threshold);
5502
+ return { ...store, retro_meta: meta };
5503
+ });
5504
+ const latest = await readCurrentWorkflow3();
5505
+ if (latest) {
5506
+ await writeCurrentWorkflow3({
5507
+ ...latest,
5508
+ ship_ready: ship.ready,
5509
+ ship_commits: ship.commits,
5510
+ retro_due: retroDue
5511
+ });
5512
+ }
5513
+ } catch {
5514
+ }
5515
+ }
5516
+ deps.log(`[harnessed] checkpoint complete: ${sub} (evidence: ${evidenceStatus})`);
5517
+ deps.exit(0);
5518
+ return;
5519
+ }
5520
+ async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
5521
+ const { completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
5522
+ if (!enforceSerialOrder("fail", sub, await serialOrderBlockers(sub, deps), opts.force, deps)) {
5523
+ deps.exit(1);
5524
+ return;
5525
+ }
5526
+ const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
5527
+ await mutateSubProgress2((e) => markIfSeeded(e, sub, "failed"));
5528
+ await absorbIntentFor(sub);
5529
+ await completePhase2({
5530
+ phaseId: sub,
5531
+ status: "complete",
5532
+ lastTask: `FAILED: ${opts.summary ?? ""}`,
5533
+ transitionWorkflowComplete: false
5534
+ });
5535
+ const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
5536
+ const { detectLoop: detectLoop2, LOOP_THRESHOLD: LOOP_THRESHOLD2 } = await Promise.resolve().then(() => (init_breakLoop(), breakLoop_exports));
5537
+ const latest = await readCurrentWorkflow2();
5538
+ const loops = detectLoop2(latest?.sub_progress ?? []);
5539
+ const looped = loops.find((l) => l.sub === sub);
5540
+ if (looped) {
5541
+ deps.error(
5542
+ `[harnessed] BREAK-LOOP: sub '${sub}' failed ${looped.count}x (>= ${LOOP_THRESHOLD2}). Stop retrying \u2014 run the break-loop skill for root-cause analysis and capture the lesson to .planning/.`
5543
+ );
5544
+ }
5545
+ deps.error(
5546
+ `[harnessed] checkpoint FAILED recorded: ${sub}${opts.summary ? ` \u2014 ${opts.summary}` : ""}`
5547
+ );
5548
+ deps.exit(1);
5549
+ return;
5550
+ }
5551
+ function registerCheckpoint(program2) {
5552
+ program2.command("checkpoint <action> <sub>").description(
5553
+ "Record workflow progress: intent | start | complete | fail <sub-workflow> (writes to ~/.claude/harnessed/checkpoints/)"
5554
+ ).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(
5555
+ "--force",
5556
+ "complete/fail \u2014 override a fail-closed guard: the missing-artifact evidence block (complete; records overridden) or the serial-order guard"
5557
+ ).option(
5558
+ "--tokens <n>",
5559
+ "complete only \u2014 conversation token count; auto-compacts the ledger when >= the shouldCompact threshold (Phase 14)"
5560
+ ).action(
5561
+ async (action, sub, opts) => {
5562
+ if (!isAction(action)) {
5563
+ console.error(
5564
+ `[harnessed] checkpoint: unknown action "${action}" \u2014 expected one of ${ACTIONS.join(", ")}`
5565
+ );
5566
+ process.exit(1);
5567
+ return;
5568
+ }
5569
+ if (action === "intent") {
5570
+ try {
5571
+ checkPathSafe(sub);
5572
+ const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
5573
+ const { activeKey: activeKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
5574
+ const { classifyIntentKind: classifyIntentKind2 } = await Promise.resolve().then(() => (init_intentKind(), intentKind_exports));
5575
+ const { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
5576
+ const kind = classifyIntentKind2(sub, getAssetsRoot2());
5577
+ const key = activeKey2();
5578
+ await mutateStore2((store) => ({
5579
+ ...store,
5580
+ intents: {
5581
+ ...store.intents ?? {},
5582
+ [key]: { master: sub, ts: (/* @__PURE__ */ new Date()).toISOString(), kind }
5583
+ }
5584
+ }));
5585
+ console.log(
5586
+ 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.`
5587
+ );
5588
+ } catch {
5589
+ }
5590
+ process.exit(0);
5591
+ return;
5592
+ }
5593
+ try {
5594
+ checkPathSafe(sub);
5595
+ } catch {
5596
+ console.error("[harnessed] checkpoint: invalid sub name (path traversal rejected)");
5597
+ process.exit(1);
5598
+ return;
5599
+ }
5600
+ if (action === "start") {
5601
+ await runCheckpointStart(sub, opts);
5602
+ return;
5603
+ }
5604
+ if (action === "complete") {
5605
+ await runCheckpointComplete(sub, opts);
5606
+ return;
5607
+ }
5608
+ await runCheckpointFail(sub, opts);
5609
+ }
5610
+ );
5611
+ }
5612
+ var ACTIONS;
5613
+ var init_checkpoint = __esm({
5614
+ "src/cli/checkpoint.ts"() {
5615
+ init_path_guard();
5616
+ init_runDeps();
5617
+ init_ledger();
5618
+ ACTIONS = ["start", "complete", "fail", "intent"];
5619
+ }
5620
+ });
5621
+ function realProbe(p7) {
5622
+ try {
5623
+ if (typeof spawnSync !== "function") return null;
5624
+ const r = spawnSync(p7, ["-c", "echo harnessed-bash-ok"], { encoding: "utf8", timeout: 5e3 });
5625
+ if (!r || r.error) return null;
5626
+ return r.status === 0;
5627
+ } catch {
5628
+ return null;
5629
+ }
5630
+ }
5631
+ function realWhere(name) {
5632
+ try {
5633
+ if (typeof spawnSync !== "function") return [];
5634
+ const r = spawnSync("where", [name], { encoding: "utf8" });
5635
+ if (!r || r.status !== 0) return [];
5636
+ return (r.stdout ?? "").split(/\r?\n/).map((s) => s.trim()).filter((s) => s.length > 0);
5637
+ } catch {
5638
+ return [];
5639
+ }
5640
+ }
5641
+ function realExists(p7) {
5642
+ try {
5643
+ return existsSync(p7);
5644
+ } catch {
5645
+ return false;
5646
+ }
5647
+ }
5648
+ function defaultDeps2() {
5649
+ return {
5650
+ platform: process.platform,
5651
+ env: process.env,
5652
+ where: realWhere,
5653
+ exists: realExists,
5654
+ probe: realProbe
5655
+ };
5656
+ }
5657
+ function resolveBash(deps) {
5247
5658
  if (cache2) return cache2;
5248
5659
  cache2 = compute({ ...defaultDeps2(), ...deps });
5249
5660
  return cache2;
@@ -6473,6 +6884,175 @@ var init_doctor_registry = __esm({
6473
6884
  }
6474
6885
  });
6475
6886
 
6887
+ // src/cli/gates.ts
6888
+ var gates_exports = {};
6889
+ __export(gates_exports, {
6890
+ registerGates: () => registerGates,
6891
+ runGatesPlan: () => runGatesPlan
6892
+ });
6893
+ function resolveMasterYamlPath2(master, packageRoot) {
6894
+ return master === "auto" ? resolve(packageRoot, "workflows", "auto", "workflow.yaml") : resolve(packageRoot, "workflows", master, "auto", "workflow.yaml");
6895
+ }
6896
+ async function runGatesPlan(master, raw, deps = defaultRunDeps) {
6897
+ if (!VALID_MASTERS.has(master)) {
6898
+ deps.error(
6899
+ `error: unknown master '${master}'. Expected one of: auto, discuss, plan, task, verify, ship.`
6900
+ );
6901
+ deps.exit(1);
6902
+ return;
6903
+ }
6904
+ try {
6905
+ checkPathSafe(master);
6906
+ } catch {
6907
+ deps.error("error: invalid master name (path traversal rejected)");
6908
+ deps.exit(1);
6909
+ return;
6910
+ }
6911
+ const packageRoot = getAssetsRoot();
6912
+ const yamlPath = resolveMasterYamlPath2(master, packageRoot);
6913
+ let raw_yaml;
6914
+ try {
6915
+ raw_yaml = await readFile(yamlPath, "utf8");
6916
+ } catch (err2) {
6917
+ deps.error(
6918
+ `error: failed to read master workflow.yaml at ${yamlPath} \u2014 ${err2.message}`
6919
+ );
6920
+ deps.exit(1);
6921
+ return;
6922
+ }
6923
+ let parsed;
6924
+ try {
6925
+ parsed = parse(raw_yaml);
6926
+ } catch (err2) {
6927
+ deps.error(`error: failed to parse ${yamlPath} \u2014 ${err2.message}`);
6928
+ deps.exit(1);
6929
+ return;
6930
+ }
6931
+ const delegates = parsed?.delegates_to;
6932
+ if (!Array.isArray(delegates) || delegates.length === 0) {
6933
+ deps.error(`error: master '${master}' workflow.yaml missing delegates_to[]`);
6934
+ deps.exit(1);
6935
+ return;
6936
+ }
6937
+ const clauses = delegates;
6938
+ const task = typeof raw.task === "string" ? raw.task : "";
6939
+ const stage = master;
6940
+ let ctx = buildDefaultGateContext(task, stage);
6941
+ if (typeof raw.context === "string" && raw.context.length > 0) {
6942
+ let extra;
6943
+ try {
6944
+ extra = JSON.parse(raw.context);
6945
+ } catch (err2) {
6946
+ deps.error(`error: --context is not valid JSON \u2014 ${err2.message}`);
6947
+ deps.exit(1);
6948
+ return;
6949
+ }
6950
+ if (extra && typeof extra === "object" && !Array.isArray(extra)) {
6951
+ ctx = mergeGateContext(ctx, extra);
6952
+ }
6953
+ }
6954
+ const skipSubs = new Set(
6955
+ (Array.isArray(raw.skipSub) ? raw.skipSub : []).flatMap((v) => v.split(",")).map((s) => s.trim()).filter((s) => s.length > 0)
6956
+ );
6957
+ ctx.skip_subs = [...skipSubs];
6958
+ const fire = [];
6959
+ const skip = [];
6960
+ const matchedSkips = /* @__PURE__ */ new Set();
6961
+ for (const clause of clauses) {
6962
+ const skipHit = matchSkipSub(skipSubs, clause.sub, master);
6963
+ if (skipHit !== null) {
6964
+ matchedSkips.add(skipHit);
6965
+ skip.push({
6966
+ sub: clause.sub,
6967
+ reason: "skipped via skip_subs (done interactively in main session)"
6968
+ });
6969
+ continue;
6970
+ }
6971
+ if (!clause.gate) {
6972
+ fire.push(fireEntry(clause, master));
6973
+ continue;
6974
+ }
6975
+ try {
6976
+ const passes = await resolveJudgmentGate(clause.gate, ctx, packageRoot);
6977
+ if (passes) {
6978
+ fire.push(fireEntry(clause, master));
6979
+ } else {
6980
+ skip.push({ sub: clause.sub, reason: `gate ${clause.gate} = false` });
6981
+ }
6982
+ } catch (e) {
6983
+ if (isUndefinedVariableError(e)) {
6984
+ deps.warn(
6985
+ `\u26A0\uFE0F master ${master} sub ${clause.sub} gate ${clause.gate} references a variable missing from the gate context (${e.message}). Treating as NOT fired (fail-closed for config errors) \u2014 fix the judgments yaml expression or supply the variable via --context / gateContext defaults.`
6986
+ );
6987
+ skip.push({
6988
+ sub: clause.sub,
6989
+ reason: `gate ${clause.gate} misconfigured (undefined variable) \u2014 fail-closed, not fired`
6990
+ });
6991
+ } else {
6992
+ deps.warn(
6993
+ `\u26A0\uFE0F master ${master} sub ${clause.sub} gate ${clause.gate} eval failed (${e.message}); firing sub as if gate=true (ADR 0029 fail-soft).`
6994
+ );
6995
+ fire.push(fireEntry(clause, master));
6996
+ }
6997
+ }
6998
+ }
6999
+ warnUnmatchedSkips(
7000
+ skipSubs,
7001
+ matchedSkips,
7002
+ master,
7003
+ clauses.map((c) => c.sub),
7004
+ (m) => deps.warn(m)
7005
+ );
7006
+ let parallelism = { escalate_to_teams: false, reason: null };
7007
+ try {
7008
+ const escalate = await resolveJudgmentGate(PARALLELISM_GATE, ctx, packageRoot);
7009
+ parallelism = escalate ? { escalate_to_teams: true, reason: "agent-teams-upgrade gate fired" } : { escalate_to_teams: false, reason: null };
7010
+ } catch {
7011
+ parallelism = { escalate_to_teams: false, reason: null };
7012
+ }
7013
+ const result = { master, fire, skip, parallelism };
7014
+ deps.log(JSON.stringify(result, null, 2));
7015
+ deps.exit(0);
7016
+ return;
7017
+ }
7018
+ function registerGates(program2) {
7019
+ program2.command("gates").description(
7020
+ "Evaluate which sub-workflows fire for a master orchestrator (JSON plan, no spawn)."
7021
+ ).argument("<master>", "master name: auto | discuss | plan | task | verify | ship").option("--task <text>", "task description (injected as gateContext.task)").option(
7022
+ "--skip-sub <names>",
7023
+ "sub names to skip without gate eval (repeatable and/or comma-separated)",
7024
+ (v, prev) => [...prev, v],
7025
+ []
7026
+ ).option("--context <json>", "JSON object merged over the default gate context").action(async (master, raw) => {
7027
+ await runGatesPlan(master, raw);
7028
+ });
7029
+ }
7030
+ function fireEntry(clause, master) {
7031
+ const isMaster = STAGE_MASTERS.has(clause.sub);
7032
+ const sub = master !== "auto" && !isMaster ? `${master}-${clause.sub}` : clause.sub;
7033
+ const entry = { sub };
7034
+ if (clause.order !== void 0) entry.order = clause.order;
7035
+ if (clause.mode !== void 0) entry.mode = clause.mode;
7036
+ if (clause.gate !== void 0) entry.gate = clause.gate;
7037
+ if (isMaster) entry.is_master = true;
7038
+ return entry;
7039
+ }
7040
+ var VALID_MASTERS, STAGE_MASTERS, PARALLELISM_GATE;
7041
+ var init_gates = __esm({
7042
+ "src/cli/gates.ts"() {
7043
+ init_path_guard();
7044
+ init_exprBuilder();
7045
+ init_judgmentResolver();
7046
+ init_skipSubs();
7047
+ init_assetsRoot();
7048
+ init_gateContext();
7049
+ init_runDeps();
7050
+ VALID_MASTERS = /* @__PURE__ */ new Set(["auto", "discuss", "plan", "task", "verify", "ship"]);
7051
+ STAGE_MASTERS = /* @__PURE__ */ new Set(["discuss", "plan", "task", "verify"]);
7052
+ PARALLELISM_GATE = "judgments.parallelism-gate.agent-teams-upgrade.fires";
7053
+ }
7054
+ });
7055
+
6476
7056
  // src/cli/gc.ts
6477
7057
  var gc_exports = {};
6478
7058
  __export(gc_exports, {
@@ -6754,9 +7334,10 @@ function stripQuotes(token) {
6754
7334
  return { bare: token, quoted: false };
6755
7335
  }
6756
7336
  function resolveHookCommand(raw, deps) {
6757
- if (deps.compiledExecPath && hookScriptMarker(raw) === INJECT_IDENTITY) {
7337
+ const marker = deps.compiledExecPath ? hookScriptMarker(raw) : null;
7338
+ if (deps.compiledExecPath && marker && COMPILED_HOOK_IDENTITIES.includes(marker)) {
6758
7339
  const exe = deps.compiledExecPath();
6759
- if (exe) return `"${exe.replace(/\\/g, "/")}" ${INJECT_IDENTITY}`;
7340
+ if (exe) return `"${exe.replace(/\\/g, "/")}" ${marker}`;
6760
7341
  }
6761
7342
  let root = null;
6762
7343
  const tokens = raw.split(/\s+/).filter((t2) => t2.length > 0);
@@ -6776,12 +7357,14 @@ function hookScriptMarker(raw) {
6776
7357
  if (isRelativeFileToken(bare2)) {
6777
7358
  const seg = bare2.split(/[\\/]/);
6778
7359
  const base = seg[seg.length - 1] ?? null;
6779
- if (base?.includes(INJECT_IDENTITY)) return INJECT_IDENTITY;
7360
+ const id = COMPILED_HOOK_IDENTITIES.find((k) => base?.includes(k));
7361
+ if (id) return id;
6780
7362
  return base;
6781
7363
  }
6782
7364
  }
6783
7365
  for (const token of raw.split(/\s+/)) {
6784
- if (stripQuotes(token).bare === INJECT_IDENTITY) return INJECT_IDENTITY;
7366
+ const { bare: bare2 } = stripQuotes(token);
7367
+ if (COMPILED_HOOK_IDENTITIES.includes(bare2)) return bare2;
6785
7368
  }
6786
7369
  return null;
6787
7370
  }
@@ -6829,10 +7412,10 @@ function detectCcHookInstalled(settingsRaw, ev, raw, matcher, deps) {
6829
7412
  const matching = arr.filter((e) => entryMatchesRegistration(e, raw, resolved, marker));
6830
7413
  return matching.length === 1 && isDesiredHookEntry(matching[0] ?? {}, matcher, resolved);
6831
7414
  }
6832
- var INJECT_IDENTITY, ABSOLUTE_RE;
7415
+ var COMPILED_HOOK_IDENTITIES, ABSOLUTE_RE;
6833
7416
  var init_hookEntry = __esm({
6834
7417
  "src/installers/lib/hookEntry.ts"() {
6835
- INJECT_IDENTITY = "inject-state";
7418
+ COMPILED_HOOK_IDENTITIES = ["inject-state", "stop-hook"];
6836
7419
  ABSOLUTE_RE = /^([A-Za-z]:[\\/]|[\\/])/;
6837
7420
  }
6838
7421
  });
@@ -7259,10 +7842,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7259
7842
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
7260
7843
  stderr += chunk;
7261
7844
  });
7262
- return await new Promise((resolve19) => {
7845
+ return await new Promise((resolve21) => {
7263
7846
  const timer = setTimeout(() => {
7264
7847
  child.kill("SIGKILL");
7265
- resolve19({
7848
+ resolve21({
7266
7849
  ok: false,
7267
7850
  phase: "spawn",
7268
7851
  error: {
@@ -7283,7 +7866,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7283
7866
  child.on("error", (err2) => {
7284
7867
  clearTimeout(timer);
7285
7868
  const bashMissing = triedBash && err2.code === "ENOENT";
7286
- resolve19({
7869
+ resolve21({
7287
7870
  ok: false,
7288
7871
  phase: "spawn",
7289
7872
  error: {
@@ -7298,7 +7881,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7298
7881
  });
7299
7882
  child.on("close", (code) => {
7300
7883
  clearTimeout(timer);
7301
- resolve19({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
7884
+ resolve21({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
7302
7885
  });
7303
7886
  });
7304
7887
  }
@@ -7499,7 +8082,7 @@ var init_idempotent = __esm({
7499
8082
  }
7500
8083
  });
7501
8084
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
7502
- return new Promise((resolve19) => {
8085
+ return new Promise((resolve21) => {
7503
8086
  const isWin = process.platform === "win32";
7504
8087
  const stdio = ["ignore", "pipe", "pipe"];
7505
8088
  const child = isWin ? spawn("cmd.exe", ["/c", bin, ...args], { cwd, windowsHide: true, stdio }) : spawn(bin, args, { cwd, shell: false, stdio });
@@ -7513,17 +8096,17 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
7513
8096
  });
7514
8097
  const timer = setTimeout(() => {
7515
8098
  child.kill("SIGKILL");
7516
- resolve19({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
8099
+ resolve21({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
7517
8100
  }, timeoutMs);
7518
8101
  child.on("error", (e) => {
7519
8102
  clearTimeout(timer);
7520
8103
  const enoent = e.code === "ENOENT";
7521
8104
  const msg = enoent && bin === "codex" ? "codex CLI not found on PATH \u2014 install Codex CLI or re-run setup on the claude platform" : e.message;
7522
- resolve19({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
8105
+ resolve21({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
7523
8106
  });
7524
8107
  child.on("close", (code) => {
7525
8108
  clearTimeout(timer);
7526
- resolve19({ exitCode: code ?? -1, stdout: stdout2, stderr });
8109
+ resolve21({ exitCode: code ?? -1, stdout: stdout2, stderr });
7527
8110
  });
7528
8111
  });
7529
8112
  }
@@ -7779,7 +8362,7 @@ var init_packSkillAudit = __esm({
7779
8362
  }
7780
8363
  });
7781
8364
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
7782
- return new Promise((resolve19) => {
8365
+ return new Promise((resolve21) => {
7783
8366
  const isWin = process.platform === "win32";
7784
8367
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
7785
8368
  let stdout2 = "";
@@ -7788,15 +8371,15 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
7788
8371
  });
7789
8372
  const timer = setTimeout(() => {
7790
8373
  child.kill("SIGKILL");
7791
- resolve19({ sha: "", exit: -1 });
8374
+ resolve21({ sha: "", exit: -1 });
7792
8375
  }, timeoutMs);
7793
8376
  child.on("error", () => {
7794
8377
  clearTimeout(timer);
7795
- resolve19({ sha: "", exit: -1 });
8378
+ resolve21({ sha: "", exit: -1 });
7796
8379
  });
7797
8380
  child.on("close", (code) => {
7798
8381
  clearTimeout(timer);
7799
- resolve19({ sha: stdout2.trim(), exit: code ?? -1 });
8382
+ resolve21({ sha: stdout2.trim(), exit: code ?? -1 });
7800
8383
  });
7801
8384
  });
7802
8385
  }
@@ -10151,7 +10734,7 @@ function renderHumanTable(records) {
10151
10734
  }
10152
10735
  }
10153
10736
  function pipeToJq(filterExpr, lines) {
10154
- return new Promise((resolve19, reject) => {
10737
+ return new Promise((resolve21, reject) => {
10155
10738
  const child = spawn("jq", [filterExpr], {
10156
10739
  stdio: ["pipe", "inherit", "inherit"],
10157
10740
  windowsHide: true
@@ -10160,12 +10743,12 @@ function pipeToJq(filterExpr, lines) {
10160
10743
  const e = err2;
10161
10744
  if (e.code === "ENOENT") {
10162
10745
  console.error(t("audit_log.jq_missing"));
10163
- resolve19(1);
10746
+ resolve21(1);
10164
10747
  } else {
10165
10748
  reject(err2);
10166
10749
  }
10167
10750
  });
10168
- child.on("close", (code) => resolve19(code ?? 0));
10751
+ child.on("close", (code) => resolve21(code ?? 0));
10169
10752
  child.stdin.write(lines.join("\n"));
10170
10753
  child.stdin.end();
10171
10754
  });
@@ -10248,339 +10831,22 @@ function registerBackupList(program2) {
10248
10831
  for (const ts of dirs) {
10249
10832
  try {
10250
10833
  const meta = JSON.parse(
10251
- await readFile(join(root, ts, "metadata.json"), "utf8")
10252
- );
10253
- console.log(
10254
- `${ts} ${meta.manifest} (${meta.files.length} file${meta.files.length === 1 ? "" : "s"})`
10255
- );
10256
- } catch {
10257
- console.log(`${ts} (metadata.json missing or unreadable)`);
10258
- }
10259
- }
10260
- console.log(t("backup.total_snapshots", { count: dirs.length }));
10261
- });
10262
- }
10263
-
10264
- // src/cli/checkpoint.ts
10265
- init_path_guard();
10266
- init_ledger();
10267
- var ACTIONS = ["start", "complete", "fail", "intent"];
10268
- function isAction(a) {
10269
- return ACTIONS.includes(a);
10270
- }
10271
- function markIfSeeded(entries, sub, status, opts) {
10272
- return entries.some((e) => e.sub === sub) ? markSub(entries, sub, status, opts) : entries;
10273
- }
10274
- async function parsePlan(raw) {
10275
- if (!raw || raw.trim() === "") return null;
10276
- let parsed;
10277
- try {
10278
- parsed = JSON.parse(raw);
10279
- } catch {
10280
- return null;
10281
- }
10282
- const p7 = parsed;
10283
- if (!Array.isArray(p7.fire) && !Array.isArray(p7.skip)) return null;
10284
- const plan = {
10285
- fire: Array.isArray(p7.fire) ? p7.fire : [],
10286
- skip: Array.isArray(p7.skip) ? p7.skip : []
10287
- };
10288
- if (typeof p7.master === "string") plan.master = p7.master;
10289
- if (p7.parallelism && typeof p7.parallelism === "object" && !Array.isArray(p7.parallelism)) {
10290
- plan.parallelism = p7.parallelism;
10291
- }
10292
- return plan;
10293
- }
10294
- async function absorbIntentFor(sub) {
10295
- try {
10296
- const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10297
- const { activeKey: activeKey2, repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
10298
- await mutateStore2((store) => {
10299
- if (!store.intents) return store;
10300
- const intents = { ...store.intents };
10301
- for (const k of [activeKey2(), repoKey2()]) {
10302
- if (intents[k]?.master === sub) delete intents[k];
10303
- }
10304
- return { ...store, intents };
10305
- });
10306
- } catch {
10307
- }
10308
- }
10309
- async function serialOrderBlockers(sub) {
10310
- try {
10311
- const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10312
- const { findSerialBlockers: findSerialBlockers2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
10313
- const wf = await readCurrentWorkflow2();
10314
- return findSerialBlockers2(wf?.sub_progress ?? [], sub);
10315
- } catch (e) {
10316
- console.warn(`[harnessed] serial-order guard skipped (fail-soft): ${e.message}`);
10317
- return [];
10318
- }
10319
- }
10320
- function enforceSerialOrder(action, sub, blockers, force) {
10321
- if (blockers.length === 0) return true;
10322
- if (!force) {
10323
- console.error(
10324
- `[harnessed] checkpoint ${action} BLOCKED: ${sub} \u2014 ${blockers.length} earlier serial-sequence sub(s) still pending (serial-order guard, fail-closed):`
10325
- );
10326
- for (const b of blockers) console.error(` - ${b} (complete or fail it first)`);
10327
- console.error(" (re-run with --force to jump the sequence deliberately)");
10328
- return false;
10329
- }
10330
- console.warn(
10331
- `[harnessed] serial-order guard overridden (--force): ${action} ${sub} ahead of pending sub(s) ${blockers.join(", ")}`
10332
- );
10333
- return true;
10334
- }
10335
- function registerCheckpoint(program2) {
10336
- program2.command("checkpoint <action> <sub>").description(
10337
- "Record workflow progress: intent | start | complete | fail <sub-workflow> (writes to ~/.claude/harnessed/checkpoints/)"
10338
- ).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(
10339
- "--force",
10340
- "complete/fail \u2014 override a fail-closed guard: the missing-artifact evidence block (complete; records overridden) or the serial-order guard"
10341
- ).option(
10342
- "--tokens <n>",
10343
- "complete only \u2014 conversation token count; auto-compacts the ledger when >= the shouldCompact threshold (Phase 14)"
10344
- ).action(
10345
- async (action, sub, opts) => {
10346
- if (!isAction(action)) {
10347
- console.error(
10348
- `[harnessed] checkpoint: unknown action "${action}" \u2014 expected one of ${ACTIONS.join(", ")}`
10349
- );
10350
- process.exit(1);
10351
- return;
10352
- }
10353
- if (action === "intent") {
10354
- try {
10355
- checkPathSafe(sub);
10356
- const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10357
- const { activeKey: activeKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
10358
- const { classifyIntentKind: classifyIntentKind2 } = await Promise.resolve().then(() => (init_intentKind(), intentKind_exports));
10359
- const { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
10360
- const kind = classifyIntentKind2(sub, getAssetsRoot2());
10361
- const key = activeKey2();
10362
- await mutateStore2((store) => ({
10363
- ...store,
10364
- intents: {
10365
- ...store.intents ?? {},
10366
- [key]: { master: sub, ts: (/* @__PURE__ */ new Date()).toISOString(), kind }
10367
- }
10368
- }));
10369
- console.log(
10370
- 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.`
10371
- );
10372
- } catch {
10373
- }
10374
- process.exit(0);
10375
- return;
10376
- }
10377
- try {
10378
- checkPathSafe(sub);
10379
- } catch {
10380
- console.error("[harnessed] checkpoint: invalid sub name (path traversal rejected)");
10381
- process.exit(1);
10382
- return;
10383
- }
10384
- const { activatePhase: activatePhase2, completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
10385
- if (action === "start") {
10386
- try {
10387
- const { stat: statFs } = await import('fs/promises');
10388
- const { resolve: resolvePath } = await import('path');
10389
- const planningDir = resolvePath(process.cwd(), ".planning");
10390
- const hasPlanning = await statFs(planningDir).then((s) => s.isDirectory()).catch(() => false);
10391
- if (hasPlanning) {
10392
- const missing = [];
10393
- for (const f of ["STATE.md", "ROADMAP.md"]) {
10394
- const ok = await statFs(resolvePath(planningDir, f)).then((s) => s.isFile()).catch(() => false);
10395
- if (!ok) missing.push(`.planning/${f}`);
10396
- }
10397
- if (missing.length > 0) {
10398
- console.error(
10399
- `\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).`
10400
- );
10401
- }
10402
- }
10403
- } catch {
10404
- }
10405
- try {
10406
- const { detectGateGuardActive: detectGateGuardActive2, GUARD_CONFLICT_ADVICE: GUARD_CONFLICT_ADVICE2 } = await Promise.resolve().then(() => (init_check_guard_conflict(), check_guard_conflict_exports));
10407
- const det = await detectGateGuardActive2();
10408
- if (det.active) {
10409
- const ge = await Promise.resolve().then(() => (init_guard_exemption(), guard_exemption_exports));
10410
- const isTty = process.stdin.isTTY === true && process.stdout.isTTY === true;
10411
- const flowResult = await ge.runExemptionFlow({
10412
- probe: () => ge.probeExemptCapability(),
10413
- readEnvValue: () => ge.readCurrentEnvValue(),
10414
- merge: (value) => ge.applyEnvExemption(value),
10415
- print: (line) => console.error(line),
10416
- ...isTty ? {
10417
- confirm: async () => {
10418
- const p7 = await import('@clack/prompts');
10419
- const ans = await p7.confirm({
10420
- message: 'Apply the GateGuard exemption now? (persists GATEGUARD_EXEMPT_GLOBS=".planning/**" into settings env \u2014 backed up first)',
10421
- initialValue: true
10422
- // D1 — default YES
10423
- });
10424
- return !p7.isCancel(ans) && ans === true;
10425
- }
10426
- } : {}
10427
- });
10428
- if (flowResult === "not-capable") {
10429
- console.error(
10430
- `\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
10431
- );
10432
- }
10433
- }
10434
- } catch {
10435
- }
10436
- const { checkpointPath } = await activatePhase2(sub);
10437
- const plan = await parsePlan(opts.plan);
10438
- if (plan) {
10439
- const { seedLedger: seedLedger2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
10440
- const { mutateSubProgress: mutateSubProgress3 } = await Promise.resolve().then(() => (init_state(), state_exports));
10441
- await mutateSubProgress3(() => seedLedger2(plan));
10442
- }
10443
- try {
10444
- const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10445
- const { activeKey: activeKey2, repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
10446
- await mutateStore2((store) => {
10447
- if (!store.intents) return store;
10448
- const intents = { ...store.intents };
10449
- delete intents[activeKey2()];
10450
- delete intents[repoKey2()];
10451
- return { ...store, intents };
10452
- });
10453
- } catch {
10454
- }
10455
- console.log(`[harnessed] checkpoint started: ${sub} \u2192 ${checkpointPath}`);
10456
- process.exit(0);
10457
- return;
10458
- }
10459
- if (action === "complete") {
10460
- if (!enforceSerialOrder("complete", sub, await serialOrderBlockers(sub), opts.force)) {
10461
- process.exit(1);
10462
- return;
10463
- }
10464
- const { checkArtifacts: checkArtifacts2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
10465
- const { mutateSubProgress: mutateSubProgress3 } = await Promise.resolve().then(() => (init_state(), state_exports));
10466
- const { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
10467
- const result = await checkArtifacts2(sub, getAssetsRoot2());
10468
- const { checkPlanningSync: checkPlanningSync2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
10469
- const syncResult = await checkPlanningSync2(process.cwd(), null);
10470
- const allMissing = [...result.missing, ...syncResult.missing];
10471
- if (allMissing.length > 0 && !opts.force) {
10472
- console.error(
10473
- `[harnessed] checkpoint complete BLOCKED: ${sub} \u2014 ${allMissing.length} item(s) missing (evidence guard + .planning/ sync, fail-closed):`
10474
- );
10475
- for (const m of allMissing) console.error(` - ${m}`);
10476
- console.error(
10477
- " (re-run with --force to override and record evidence_status=overridden)"
10478
- );
10479
- process.exit(1);
10480
- return;
10481
- }
10482
- let evidenceStatus;
10483
- if (allMissing.length > 0 && opts.force) evidenceStatus = "overridden";
10484
- else if (result.status === "verified") evidenceStatus = "verified";
10485
- else evidenceStatus = "none_declared";
10486
- const markOpts = evidenceStatus === "none_declared" ? { evidence_status: evidenceStatus } : { evidence: result.found, evidence_status: evidenceStatus };
10487
- await mutateSubProgress3((e) => markIfSeeded(e, sub, "done", markOpts));
10488
- await absorbIntentFor(sub);
10489
- const { collectScaleMetrics: collectScaleMetrics2, assessScale: assessScale2 } = await Promise.resolve().then(() => (init_scale(), scale_exports));
10490
- const { readCurrentWorkflow: readCurrentWorkflow3, writeCurrentWorkflow: writeCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10491
- const afterMark = await readCurrentWorkflow3();
10492
- if (afterMark) {
10493
- const metrics = await collectScaleMetrics2(process.cwd(), afterMark.sub_progress ?? []);
10494
- await writeCurrentWorkflow2({ ...afterMark, verify_mode: assessScale2(metrics) });
10495
- }
10496
- const { nextPending: nextPending2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
10497
- const allResolved = nextPending2(afterMark?.sub_progress ?? []) === null;
10498
- await completePhase2({
10499
- phaseId: sub,
10500
- status: "complete",
10501
- lastTask: opts.summary ?? `phase ${sub} complete`,
10502
- transitionWorkflowComplete: allResolved
10503
- });
10504
- if (allResolved && afterMark) {
10505
- const { captureWorkflowLearnings: captureWorkflowLearnings2 } = await Promise.resolve().then(() => (init_learnings(), learnings_exports));
10506
- const captured = await captureWorkflowLearnings2(afterMark.sub_progress ?? [], sub);
10507
- if (captured > 0) {
10508
- console.log(`[harnessed] captured ${captured} learning(s) \u2192 .planning/LEARNINGS.md`);
10509
- }
10510
- }
10511
- const { shouldAutoCompact: shouldAutoCompact2, compactWorkflow: compactWorkflow2 } = await Promise.resolve().then(() => (init_compact(), compact_exports));
10512
- if (shouldAutoCompact2(opts.tokens != null ? Number(opts.tokens) : void 0)) {
10513
- const c = await compactWorkflow2();
10514
- if (c.evicted > 0) {
10515
- console.log(
10516
- `[harnessed] auto-compact: evicted ${c.evicted} resolved entries (-${c.pct_saved}% tokens)`
10517
- );
10518
- }
10519
- }
10520
- if (allResolved) {
10521
- try {
10522
- const { defaultShipReady: defaultShipReady2 } = await Promise.resolve().then(() => (init_shipReady(), shipReady_exports));
10523
- const { incrementPhases: incrementPhases2, isRetroDue: isRetroDue2, retroThreshold: retroThreshold2 } = await Promise.resolve().then(() => (init_retroMeta(), retroMeta_exports));
10524
- const { mutateStore: mutateStore2, readCurrentWorkflow: readCurrentWorkflow4, writeCurrentWorkflow: writeCurrentWorkflow3 } = await Promise.resolve().then(() => (init_state(), state_exports));
10525
- const { repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
10526
- const ship = defaultShipReady2(process.cwd());
10527
- const key = repoKey2();
10528
- const threshold = retroThreshold2(process.env);
10529
- let retroDue = false;
10530
- await mutateStore2((store) => {
10531
- const meta = { ...store.retro_meta ?? {} };
10532
- const next = incrementPhases2(meta[key]);
10533
- meta[key] = next;
10534
- retroDue = isRetroDue2(next.phases_since_retro, threshold);
10535
- return { ...store, retro_meta: meta };
10536
- });
10537
- const latest2 = await readCurrentWorkflow4();
10538
- if (latest2) {
10539
- await writeCurrentWorkflow3({
10540
- ...latest2,
10541
- ship_ready: ship.ready,
10542
- ship_commits: ship.commits,
10543
- retro_due: retroDue
10544
- });
10545
- }
10546
- } catch {
10547
- }
10548
- }
10549
- console.log(`[harnessed] checkpoint complete: ${sub} (evidence: ${evidenceStatus})`);
10550
- process.exit(0);
10551
- return;
10552
- }
10553
- if (!enforceSerialOrder("fail", sub, await serialOrderBlockers(sub), opts.force)) {
10554
- process.exit(1);
10555
- return;
10556
- }
10557
- const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10558
- await mutateSubProgress2((e) => markIfSeeded(e, sub, "failed"));
10559
- await absorbIntentFor(sub);
10560
- await completePhase2({
10561
- phaseId: sub,
10562
- status: "complete",
10563
- lastTask: `FAILED: ${opts.summary ?? ""}`,
10564
- transitionWorkflowComplete: false
10565
- });
10566
- const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10567
- const { detectLoop: detectLoop2, LOOP_THRESHOLD: LOOP_THRESHOLD2 } = await Promise.resolve().then(() => (init_breakLoop(), breakLoop_exports));
10568
- const latest = await readCurrentWorkflow2();
10569
- const loops = detectLoop2(latest?.sub_progress ?? []);
10570
- const looped = loops.find((l) => l.sub === sub);
10571
- if (looped) {
10572
- console.error(
10573
- `[harnessed] BREAK-LOOP: sub '${sub}' failed ${looped.count}x (>= ${LOOP_THRESHOLD2}). Stop retrying \u2014 run the break-loop skill for root-cause analysis and capture the lesson to .planning/.`
10834
+ await readFile(join(root, ts, "metadata.json"), "utf8")
10835
+ );
10836
+ console.log(
10837
+ `${ts} ${meta.manifest} (${meta.files.length} file${meta.files.length === 1 ? "" : "s"})`
10574
10838
  );
10839
+ } catch {
10840
+ console.log(`${ts} (metadata.json missing or unreadable)`);
10575
10841
  }
10576
- console.error(
10577
- `[harnessed] checkpoint FAILED recorded: ${sub}${opts.summary ? ` \u2014 ${opts.summary}` : ""}`
10578
- );
10579
- process.exit(1);
10580
10842
  }
10581
- );
10843
+ console.log(t("backup.total_snapshots", { count: dirs.length }));
10844
+ });
10582
10845
  }
10583
10846
 
10847
+ // src/cli.ts
10848
+ init_checkpoint();
10849
+
10584
10850
  // src/cli/compact-cmd.ts
10585
10851
  function registerCompact(program2) {
10586
10852
  program2.command("compact").description(
@@ -10632,6 +10898,468 @@ function registerDoctor(program2) {
10632
10898
  });
10633
10899
  }
10634
10900
 
10901
+ // src/eval/runner.ts
10902
+ init_runDeps();
10903
+ var TIMESTAMP_KEYS = /* @__PURE__ */ new Set(["started_at", "completed_at", "paused_at", "timestamp"]);
10904
+ function normalizeString(s, roots) {
10905
+ let out = s;
10906
+ for (const root of roots) {
10907
+ const fwd = root.replace(/\\/g, "/");
10908
+ out = out.split(root).join("<TMP>");
10909
+ out = out.split(fwd).join("<TMP>");
10910
+ }
10911
+ return out.replace(/\\/g, "/");
10912
+ }
10913
+ function normalizeGolden(value, tmpRoots) {
10914
+ if (typeof value === "string") return normalizeString(value, tmpRoots);
10915
+ if (Array.isArray(value)) return value.map((v) => normalizeGolden(v, tmpRoots));
10916
+ if (value && typeof value === "object") {
10917
+ const out = {};
10918
+ for (const [k, v] of Object.entries(value)) {
10919
+ if (TIMESTAMP_KEYS.has(k)) continue;
10920
+ out[k] = normalizeGolden(v, tmpRoots);
10921
+ }
10922
+ return out;
10923
+ }
10924
+ return value;
10925
+ }
10926
+ function loadGolden(path) {
10927
+ try {
10928
+ return JSON.parse(readFileSync(path, "utf8"));
10929
+ } catch {
10930
+ return null;
10931
+ }
10932
+ }
10933
+ function writeGolden(path, value) {
10934
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
10935
+ `, "utf8");
10936
+ }
10937
+ function diffGolden(expected, actual, path = "") {
10938
+ if (JSON.stringify(expected) === JSON.stringify(actual)) return [];
10939
+ const label = path || "(root)";
10940
+ const isObj = (v) => !!v && typeof v === "object" && !Array.isArray(v);
10941
+ if (Array.isArray(expected) && Array.isArray(actual)) {
10942
+ const out = [];
10943
+ const len = Math.max(expected.length, actual.length);
10944
+ if (expected.length !== actual.length) {
10945
+ out.push(`${label}: expected length ${expected.length}, actual ${actual.length}`);
10946
+ }
10947
+ for (let i = 0; i < len; i++) {
10948
+ out.push(...diffGolden(expected[i], actual[i], `${path}[${i}]`));
10949
+ }
10950
+ return out;
10951
+ }
10952
+ if (isObj(expected) && isObj(actual)) {
10953
+ const out = [];
10954
+ for (const k of /* @__PURE__ */ new Set([...Object.keys(expected), ...Object.keys(actual)])) {
10955
+ out.push(...diffGolden(expected[k], actual[k], path ? `${path}.${k}` : k));
10956
+ }
10957
+ return out;
10958
+ }
10959
+ return [`${label}: expected ${JSON.stringify(expected)}, actual ${JSON.stringify(actual)}`];
10960
+ }
10961
+ var GatesStep = Type.Object(
10962
+ {
10963
+ gates: Type.Object(
10964
+ {
10965
+ master: Type.String({ minLength: 1 }),
10966
+ task: Type.Optional(Type.String()),
10967
+ skip_sub: Type.Optional(Type.Array(Type.String())),
10968
+ context: Type.Optional(Type.Record(Type.String(), Type.Unknown()))
10969
+ },
10970
+ { additionalProperties: false }
10971
+ )
10972
+ },
10973
+ { additionalProperties: false }
10974
+ );
10975
+ var CheckpointStep = Type.Object(
10976
+ {
10977
+ checkpoint: Type.Object(
10978
+ {
10979
+ action: Type.Union([Type.Literal("start"), Type.Literal("complete"), Type.Literal("fail")]),
10980
+ sub: Type.String({ minLength: 1 }),
10981
+ // start-only: gates plan (object form; runner serializes to --plan JSON).
10982
+ plan: Type.Optional(Type.Unknown()),
10983
+ summary: Type.Optional(Type.String()),
10984
+ force: Type.Optional(Type.Boolean()),
10985
+ tokens: Type.Optional(Type.String())
10986
+ },
10987
+ { additionalProperties: false }
10988
+ )
10989
+ },
10990
+ { additionalProperties: false }
10991
+ );
10992
+ var FileStep = Type.Object(
10993
+ {
10994
+ file: Type.Object(
10995
+ {
10996
+ // Relative to the scenario's temp repo dir (the runner chdir target).
10997
+ path: Type.String({ minLength: 1 }),
10998
+ content: Type.Optional(Type.String()),
10999
+ // ISO-8601; applied via utimes — evidence multi-base resolution picks
11000
+ // the newest mtime, scenarios must control it explicitly.
11001
+ mtime: Type.Optional(Type.String())
11002
+ },
11003
+ { additionalProperties: false }
11004
+ )
11005
+ },
11006
+ { additionalProperties: false }
11007
+ );
11008
+ var EvalStep = Type.Union([GatesStep, CheckpointStep, FileStep]);
11009
+ var EvalScenario = Type.Object(
11010
+ {
11011
+ name: Type.String({ minLength: 1 }),
11012
+ description: Type.Optional(Type.String()),
11013
+ assets_dir: Type.Optional(Type.String({ minLength: 1 })),
11014
+ seed_context: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
11015
+ steps: Type.Array(EvalStep, { minItems: 1 }),
11016
+ expect: Type.Optional(
11017
+ Type.Object({ golden: Type.Optional(Type.String()) }, { additionalProperties: false })
11018
+ )
11019
+ },
11020
+ { additionalProperties: false }
11021
+ );
11022
+ function validateScenario(parsed) {
11023
+ if (Value.Check(EvalScenario, parsed)) {
11024
+ return { ok: true, scenario: parsed };
11025
+ }
11026
+ const errors = [...Value.Errors(EvalScenario, parsed)].map(
11027
+ (e) => `${e.path || "/"}: ${e.message}`
11028
+ );
11029
+ return { ok: false, errors: errors.length > 0 ? errors : ["invalid scenario"] };
11030
+ }
11031
+
11032
+ // src/eval/runner.ts
11033
+ var GATE_REF_RE = /judgments\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.(?:fires|skips)/g;
11034
+ function deepMerge(a, b) {
11035
+ const out = { ...a };
11036
+ for (const [k, v] of Object.entries(b)) {
11037
+ const prev = out[k];
11038
+ if (prev && typeof prev === "object" && !Array.isArray(prev) && v && typeof v === "object" && !Array.isArray(v)) {
11039
+ out[k] = deepMerge(prev, v);
11040
+ } else {
11041
+ out[k] = v;
11042
+ }
11043
+ }
11044
+ return out;
11045
+ }
11046
+ function composeContext(seed, step) {
11047
+ const { $unset, ...seedRest } = seed ?? {};
11048
+ const merged = deepMerge(seedRest, step ?? {});
11049
+ const unsetList = Array.isArray($unset) ? $unset : [];
11050
+ for (const keyPath of unsetList) {
11051
+ const parts = keyPath.split(".");
11052
+ let cursor = merged;
11053
+ for (let i = 0; i < parts.length - 1 && cursor; i++) {
11054
+ const next = cursor[parts[i]];
11055
+ cursor = next && typeof next === "object" && !Array.isArray(next) ? next : void 0;
11056
+ }
11057
+ if (cursor) delete cursor[parts[parts.length - 1]];
11058
+ }
11059
+ if (Object.keys(merged).length === 0) return void 0;
11060
+ return merged;
11061
+ }
11062
+ async function execStep(scenario, step, repoDir) {
11063
+ if ("file" in step) {
11064
+ const target = resolve(repoDir, step.file.path);
11065
+ mkdirSync(dirname(target), { recursive: true });
11066
+ writeFileSync(target, step.file.content ?? "", "utf8");
11067
+ if (step.file.mtime) {
11068
+ const t2 = new Date(step.file.mtime);
11069
+ utimesSync(target, t2, t2);
11070
+ }
11071
+ return { kind: "file", exitCode: null, stdout: [], stderr: [] };
11072
+ }
11073
+ const { deps, stdout: stdout2, stderr } = captureRunDeps();
11074
+ let exitCode = null;
11075
+ try {
11076
+ if ("gates" in step) {
11077
+ const { runGatesPlan: runGatesPlan2 } = await Promise.resolve().then(() => (init_gates(), gates_exports));
11078
+ const ctx = composeContext(scenario.seed_context, step.gates.context);
11079
+ await runGatesPlan2(
11080
+ step.gates.master,
11081
+ {
11082
+ ...step.gates.task !== void 0 ? { task: step.gates.task } : {},
11083
+ ...step.gates.skip_sub !== void 0 ? { skipSub: step.gates.skip_sub } : {},
11084
+ ...ctx !== void 0 ? { context: JSON.stringify(ctx) } : {}
11085
+ },
11086
+ deps
11087
+ );
11088
+ } else {
11089
+ const { runCheckpointStart: runCheckpointStart2, runCheckpointComplete: runCheckpointComplete2, runCheckpointFail: runCheckpointFail2 } = await Promise.resolve().then(() => (init_checkpoint(), checkpoint_exports));
11090
+ const c = step.checkpoint;
11091
+ if (c.action === "start") {
11092
+ await runCheckpointStart2(
11093
+ c.sub,
11094
+ {
11095
+ ...c.summary !== void 0 ? { summary: c.summary } : {},
11096
+ ...c.plan !== void 0 ? { plan: JSON.stringify(c.plan) } : {}
11097
+ },
11098
+ deps
11099
+ );
11100
+ } else if (c.action === "complete") {
11101
+ await runCheckpointComplete2(
11102
+ c.sub,
11103
+ {
11104
+ ...c.summary !== void 0 ? { summary: c.summary } : {},
11105
+ ...c.force !== void 0 ? { force: c.force } : {},
11106
+ ...c.tokens !== void 0 ? { tokens: c.tokens } : {}
11107
+ },
11108
+ deps
11109
+ );
11110
+ } else {
11111
+ await runCheckpointFail2(
11112
+ c.sub,
11113
+ {
11114
+ ...c.summary !== void 0 ? { summary: c.summary } : {},
11115
+ ...c.force !== void 0 ? { force: c.force } : {}
11116
+ },
11117
+ deps
11118
+ );
11119
+ }
11120
+ }
11121
+ } catch (e) {
11122
+ if (e instanceof ExitError) {
11123
+ exitCode = e.code;
11124
+ } else {
11125
+ throw e;
11126
+ }
11127
+ }
11128
+ return { kind: "gates" in step ? "gates" : "checkpoint", exitCode, stdout: stdout2, stderr };
11129
+ }
11130
+ async function runScenarioDir(dir, opts) {
11131
+ const scenarioPath = join(dir, "scenario.yaml");
11132
+ let parsed;
11133
+ try {
11134
+ parsed = parse(readFileSync(scenarioPath, "utf8"));
11135
+ } catch (e) {
11136
+ return {
11137
+ name: dir,
11138
+ dir,
11139
+ status: "CONFIG-ERROR",
11140
+ detail: [`failed to read/parse ${scenarioPath}: ${e.message}`],
11141
+ evaluatedGateRefs: []
11142
+ };
11143
+ }
11144
+ const v = validateScenario(parsed);
11145
+ if (!v.ok) {
11146
+ return {
11147
+ name: typeof parsed?.name === "string" ? String(parsed.name) : dir,
11148
+ dir,
11149
+ status: "CONFIG-ERROR",
11150
+ detail: [`invalid scenario.yaml (${scenarioPath}):`, ...v.errors],
11151
+ evaluatedGateRefs: []
11152
+ };
11153
+ }
11154
+ const scenario = v.scenario;
11155
+ const stateRoot = realpathSync(mkdtempSync(join(tmpdir(), "eval-run-root-")));
11156
+ const repoDir = realpathSync(mkdtempSync(join(tmpdir(), "eval-run-repo-")));
11157
+ const prevCwd = process.cwd();
11158
+ const prevRoot = process.env.HARNESSED_ROOT_OVERRIDE;
11159
+ const prevAssets = process.env.HARNESSED_ASSETS_OVERRIDE;
11160
+ process.env.HARNESSED_ROOT_OVERRIDE = stateRoot;
11161
+ if (scenario.assets_dir) {
11162
+ process.env.HARNESSED_ASSETS_OVERRIDE = isAbsolute(scenario.assets_dir) ? scenario.assets_dir : resolve(dir, scenario.assets_dir);
11163
+ }
11164
+ process.chdir(repoDir);
11165
+ const { _clearJudgmentCache: _clearJudgmentCache2 } = await Promise.resolve().then(() => (init_judgmentResolver(), judgmentResolver_exports));
11166
+ _clearJudgmentCache2();
11167
+ const steps = [];
11168
+ const evaluatedGateRefs = /* @__PURE__ */ new Set();
11169
+ let engineError = null;
11170
+ let workflow = null;
11171
+ try {
11172
+ for (const step of scenario.steps) {
11173
+ const rec = await execStep(scenario, step, repoDir);
11174
+ steps.push(rec);
11175
+ if (rec.kind === "gates") {
11176
+ for (const line of [...rec.stdout, ...rec.stderr]) {
11177
+ for (const m of line.matchAll(GATE_REF_RE)) evaluatedGateRefs.add(m[0]);
11178
+ }
11179
+ }
11180
+ }
11181
+ try {
11182
+ const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
11183
+ workflow = await readCurrentWorkflow2();
11184
+ } catch {
11185
+ workflow = null;
11186
+ }
11187
+ } catch (e) {
11188
+ engineError = e;
11189
+ } finally {
11190
+ process.chdir(prevCwd);
11191
+ if (prevRoot === void 0) delete process.env.HARNESSED_ROOT_OVERRIDE;
11192
+ else process.env.HARNESSED_ROOT_OVERRIDE = prevRoot;
11193
+ if (prevAssets === void 0) delete process.env.HARNESSED_ASSETS_OVERRIDE;
11194
+ else process.env.HARNESSED_ASSETS_OVERRIDE = prevAssets;
11195
+ _clearJudgmentCache2();
11196
+ }
11197
+ const cleanup = () => {
11198
+ rmSync(stateRoot, { recursive: true, force: true });
11199
+ rmSync(repoDir, { recursive: true, force: true });
11200
+ };
11201
+ if (engineError) {
11202
+ cleanup();
11203
+ return {
11204
+ name: scenario.name,
11205
+ dir,
11206
+ status: "ERROR",
11207
+ detail: [engineError.message, ...(engineError.stack ?? "").split("\n").slice(1, 6)],
11208
+ evaluatedGateRefs: [...evaluatedGateRefs]
11209
+ };
11210
+ }
11211
+ cleanup();
11212
+ const actual = normalizeGolden({ steps, workflow }, [stateRoot, repoDir, tmpdir()]);
11213
+ const goldenPath = join(dir, scenario.expect?.golden ?? "golden.json");
11214
+ if (opts.updateGolden) {
11215
+ const before = loadGolden(goldenPath);
11216
+ writeGolden(goldenPath, actual);
11217
+ const detail = before ? diffGolden(before, actual) : ["(new golden recorded)"];
11218
+ return {
11219
+ name: scenario.name,
11220
+ dir,
11221
+ status: "UPDATED",
11222
+ detail,
11223
+ evaluatedGateRefs: [...evaluatedGateRefs]
11224
+ };
11225
+ }
11226
+ const golden = loadGolden(goldenPath);
11227
+ if (golden === null) {
11228
+ return {
11229
+ name: scenario.name,
11230
+ dir,
11231
+ status: "MISSING-GOLDEN",
11232
+ detail: [`no golden at ${goldenPath} \u2014 record it with \`harnessed eval --update-golden\``],
11233
+ evaluatedGateRefs: [...evaluatedGateRefs]
11234
+ };
11235
+ }
11236
+ const diff = diffGolden(golden, actual);
11237
+ if (diff.length > 0) {
11238
+ return {
11239
+ name: scenario.name,
11240
+ dir,
11241
+ status: "FAIL",
11242
+ detail: diff,
11243
+ evaluatedGateRefs: [...evaluatedGateRefs]
11244
+ };
11245
+ }
11246
+ return { name: scenario.name, dir, status: "PASS", evaluatedGateRefs: [...evaluatedGateRefs] };
11247
+ }
11248
+ async function runEvalSuite(suiteDir, opts) {
11249
+ const results = [];
11250
+ let entries = [];
11251
+ try {
11252
+ entries = readdirSync(suiteDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => join(suiteDir, d.name)).sort();
11253
+ } catch {
11254
+ entries = [];
11255
+ }
11256
+ for (const dir of entries) {
11257
+ try {
11258
+ readFileSync(join(dir, "scenario.yaml"));
11259
+ } catch {
11260
+ continue;
11261
+ }
11262
+ if (opts.filter && !dir.includes(opts.filter)) ;
11263
+ const r = await runScenarioDir(dir, opts);
11264
+ if (opts.filter && !r.name.includes(opts.filter) && !dir.includes(opts.filter)) continue;
11265
+ results.push(r);
11266
+ }
11267
+ const summary = {
11268
+ pass: results.filter((r) => r.status === "PASS").length,
11269
+ fail: results.filter((r) => r.status === "FAIL").length,
11270
+ error: results.filter((r) => r.status === "ERROR").length,
11271
+ configError: results.filter((r) => r.status === "CONFIG-ERROR").length,
11272
+ missingGolden: results.filter((r) => r.status === "MISSING-GOLDEN").length,
11273
+ updated: results.filter((r) => r.status === "UPDATED").length
11274
+ };
11275
+ return { results, summary };
11276
+ }
11277
+ function computeCoverage(evaluatedRefs, assetsRoot) {
11278
+ const evaluated = new Set(evaluatedRefs);
11279
+ const out = [];
11280
+ const dir = join(assetsRoot, "workflows", "judgments");
11281
+ let files = [];
11282
+ try {
11283
+ files = readdirSync(dir).filter((f) => f.endsWith(".yaml"));
11284
+ } catch {
11285
+ return out;
11286
+ }
11287
+ for (const f of files) {
11288
+ let parsed = null;
11289
+ try {
11290
+ parsed = parse(readFileSync(join(dir, f), "utf8"));
11291
+ } catch {
11292
+ continue;
11293
+ }
11294
+ const triggers = parsed?.triggers;
11295
+ if (!triggers) continue;
11296
+ const base = f.replace(/\.yaml$/, "");
11297
+ for (const key of Object.keys(triggers)) {
11298
+ const ref = `judgments.${base}.${key}.fires`;
11299
+ out.push({ ref, covered: evaluated.has(ref) });
11300
+ }
11301
+ }
11302
+ return out;
11303
+ }
11304
+
11305
+ // src/cli/evalCmd.ts
11306
+ init_assetsRoot();
11307
+ init_runDeps();
11308
+ async function runEvalCommand(raw, deps = defaultRunDeps) {
11309
+ const suiteDir = resolve(raw.dir ?? resolve(process.cwd(), "fixtures", "eval"));
11310
+ const suite = await runEvalSuite(suiteDir, {
11311
+ ...raw.updateGolden !== void 0 ? { updateGolden: raw.updateGolden } : {},
11312
+ ...raw.filter !== void 0 ? { filter: raw.filter } : {}
11313
+ });
11314
+ const failures = suite.results.filter(
11315
+ (r) => r.status === "FAIL" || r.status === "ERROR" || r.status === "CONFIG-ERROR"
11316
+ );
11317
+ const missing = suite.results.filter((r) => r.status === "MISSING-GOLDEN");
11318
+ const failing = failures.length + missing.length;
11319
+ if (raw.json) {
11320
+ deps.log(JSON.stringify({ results: suite.results, summary: suite.summary }, null, 2));
11321
+ } else {
11322
+ if (suite.results.length === 0) {
11323
+ deps.log(`[harnessed eval] 0 scenarios under ${suiteDir}`);
11324
+ }
11325
+ for (const r of suite.results) {
11326
+ deps.log(`${r.status.padEnd(14)} ${r.name}`);
11327
+ if (r.status !== "PASS" && r.detail) {
11328
+ for (const line of r.detail.slice(0, 20)) deps.log(` ${line}`);
11329
+ }
11330
+ }
11331
+ const s = suite.summary;
11332
+ deps.log(
11333
+ `[harnessed eval] pass ${s.pass} / fail ${s.fail} / error ${s.error} / config-error ${s.configError} / missing-golden ${s.missingGolden} / updated ${s.updated}`
11334
+ );
11335
+ }
11336
+ if (raw.coverage) {
11337
+ const refs = suite.results.flatMap((r) => r.evaluatedGateRefs);
11338
+ const cov = computeCoverage(refs, getAssetsRoot());
11339
+ const bare2 = cov.filter((c) => !c.covered);
11340
+ deps.log(`[harnessed eval] trigger coverage: ${cov.length - bare2.length}/${cov.length}`);
11341
+ for (const c of cov) {
11342
+ deps.log(` ${c.covered ? "covered " : "BARE "} ${c.ref}`);
11343
+ }
11344
+ }
11345
+ if (process.env.GITHUB_ACTIONS && failing > 0) {
11346
+ for (const r of [...failures, ...missing]) {
11347
+ deps.log(
11348
+ `::error title=harnessed eval ${r.status}::${r.name} \u2014 ${(r.detail ?? []).slice(0, 3).join(" | ")}`
11349
+ );
11350
+ }
11351
+ }
11352
+ deps.exit(failing > 0 ? 1 : 0);
11353
+ return;
11354
+ }
11355
+ function registerEval(program2) {
11356
+ program2.command("eval").description(
11357
+ "run the orchestrator-behavior regression trap suite (deterministic replay; CI gate)"
11358
+ ).option("--dir <path>", "scenario suite directory (default: ./fixtures/eval)").option("--json", "machine-readable results").option("--coverage", "print judgments-trigger coverage matrix (bare triggers highlighted)").option("--update-golden", "re-record goldens (prints the diff \u2014 review it, never blind-bless)").option("--filter <substr>", "run only scenarios whose name/dir matches").action(async (raw) => {
11359
+ await runEvalCommand(raw);
11360
+ });
11361
+ }
11362
+
10635
11363
  // src/cli/exempt-gateguard.ts
10636
11364
  init_guard_exemption();
10637
11365
  function registerExemptGateguard(program2) {
@@ -10658,161 +11386,8 @@ function registerExemptGateguard(program2) {
10658
11386
  });
10659
11387
  }
10660
11388
 
10661
- // src/cli/gates.ts
10662
- init_path_guard();
10663
- init_exprBuilder();
10664
- init_judgmentResolver();
10665
- init_skipSubs();
10666
- init_assetsRoot();
10667
- init_gateContext();
10668
- var VALID_MASTERS = /* @__PURE__ */ new Set(["auto", "discuss", "plan", "task", "verify", "ship"]);
10669
- var STAGE_MASTERS = /* @__PURE__ */ new Set(["discuss", "plan", "task", "verify"]);
10670
- var PARALLELISM_GATE = "judgments.parallelism-gate.agent-teams-upgrade.fires";
10671
- function resolveMasterYamlPath2(master, packageRoot) {
10672
- return master === "auto" ? resolve(packageRoot, "workflows", "auto", "workflow.yaml") : resolve(packageRoot, "workflows", master, "auto", "workflow.yaml");
10673
- }
10674
- function registerGates(program2) {
10675
- program2.command("gates").description(
10676
- "Evaluate which sub-workflows fire for a master orchestrator (JSON plan, no spawn)."
10677
- ).argument("<master>", "master name: auto | discuss | plan | task | verify | ship").option("--task <text>", "task description (injected as gateContext.task)").option(
10678
- "--skip-sub <names>",
10679
- "sub names to skip without gate eval (repeatable and/or comma-separated)",
10680
- (v, prev) => [...prev, v],
10681
- []
10682
- ).option("--context <json>", "JSON object merged over the default gate context").action(async (master, raw) => {
10683
- if (!VALID_MASTERS.has(master)) {
10684
- console.error(
10685
- `error: unknown master '${master}'. Expected one of: auto, discuss, plan, task, verify, ship.`
10686
- );
10687
- process.exit(1);
10688
- return;
10689
- }
10690
- try {
10691
- checkPathSafe(master);
10692
- } catch {
10693
- console.error("error: invalid master name (path traversal rejected)");
10694
- process.exit(1);
10695
- return;
10696
- }
10697
- const packageRoot = getAssetsRoot();
10698
- const yamlPath = resolveMasterYamlPath2(master, packageRoot);
10699
- let raw_yaml;
10700
- try {
10701
- raw_yaml = await readFile(yamlPath, "utf8");
10702
- } catch (err2) {
10703
- console.error(
10704
- `error: failed to read master workflow.yaml at ${yamlPath} \u2014 ${err2.message}`
10705
- );
10706
- process.exit(1);
10707
- return;
10708
- }
10709
- let parsed;
10710
- try {
10711
- parsed = parse(raw_yaml);
10712
- } catch (err2) {
10713
- console.error(`error: failed to parse ${yamlPath} \u2014 ${err2.message}`);
10714
- process.exit(1);
10715
- return;
10716
- }
10717
- const delegates = parsed?.delegates_to;
10718
- if (!Array.isArray(delegates) || delegates.length === 0) {
10719
- console.error(`error: master '${master}' workflow.yaml missing delegates_to[]`);
10720
- process.exit(1);
10721
- return;
10722
- }
10723
- const clauses = delegates;
10724
- const task = typeof raw.task === "string" ? raw.task : "";
10725
- const stage = master;
10726
- let ctx = buildDefaultGateContext(task, stage);
10727
- if (typeof raw.context === "string" && raw.context.length > 0) {
10728
- let extra;
10729
- try {
10730
- extra = JSON.parse(raw.context);
10731
- } catch (err2) {
10732
- console.error(`error: --context is not valid JSON \u2014 ${err2.message}`);
10733
- process.exit(1);
10734
- return;
10735
- }
10736
- if (extra && typeof extra === "object" && !Array.isArray(extra)) {
10737
- ctx = mergeGateContext(ctx, extra);
10738
- }
10739
- }
10740
- const skipSubs = new Set(
10741
- (Array.isArray(raw.skipSub) ? raw.skipSub : []).flatMap((v) => v.split(",")).map((s) => s.trim()).filter((s) => s.length > 0)
10742
- );
10743
- ctx.skip_subs = [...skipSubs];
10744
- const fire = [];
10745
- const skip = [];
10746
- const matchedSkips = /* @__PURE__ */ new Set();
10747
- for (const clause of clauses) {
10748
- const skipHit = matchSkipSub(skipSubs, clause.sub, master);
10749
- if (skipHit !== null) {
10750
- matchedSkips.add(skipHit);
10751
- skip.push({
10752
- sub: clause.sub,
10753
- reason: "skipped via skip_subs (done interactively in main session)"
10754
- });
10755
- continue;
10756
- }
10757
- if (!clause.gate) {
10758
- fire.push(fireEntry(clause, master));
10759
- continue;
10760
- }
10761
- try {
10762
- const passes = await resolveJudgmentGate(clause.gate, ctx, packageRoot);
10763
- if (passes) {
10764
- fire.push(fireEntry(clause, master));
10765
- } else {
10766
- skip.push({ sub: clause.sub, reason: `gate ${clause.gate} = false` });
10767
- }
10768
- } catch (e) {
10769
- if (isUndefinedVariableError(e)) {
10770
- console.warn(
10771
- `\u26A0\uFE0F master ${master} sub ${clause.sub} gate ${clause.gate} references a variable missing from the gate context (${e.message}). Treating as NOT fired (fail-closed for config errors) \u2014 fix the judgments yaml expression or supply the variable via --context / gateContext defaults.`
10772
- );
10773
- skip.push({
10774
- sub: clause.sub,
10775
- reason: `gate ${clause.gate} misconfigured (undefined variable) \u2014 fail-closed, not fired`
10776
- });
10777
- } else {
10778
- console.warn(
10779
- `\u26A0\uFE0F master ${master} sub ${clause.sub} gate ${clause.gate} eval failed (${e.message}); firing sub as if gate=true (ADR 0029 fail-soft).`
10780
- );
10781
- fire.push(fireEntry(clause, master));
10782
- }
10783
- }
10784
- }
10785
- warnUnmatchedSkips(
10786
- skipSubs,
10787
- matchedSkips,
10788
- master,
10789
- clauses.map((c) => c.sub),
10790
- (m) => console.warn(m)
10791
- );
10792
- let parallelism = { escalate_to_teams: false, reason: null };
10793
- try {
10794
- const escalate = await resolveJudgmentGate(PARALLELISM_GATE, ctx, packageRoot);
10795
- parallelism = escalate ? { escalate_to_teams: true, reason: "agent-teams-upgrade gate fired" } : { escalate_to_teams: false, reason: null };
10796
- } catch {
10797
- parallelism = { escalate_to_teams: false, reason: null };
10798
- }
10799
- const result = { master, fire, skip, parallelism };
10800
- console.log(JSON.stringify(result, null, 2));
10801
- process.exit(0);
10802
- });
10803
- }
10804
- function fireEntry(clause, master) {
10805
- const isMaster = STAGE_MASTERS.has(clause.sub);
10806
- const sub = master !== "auto" && !isMaster ? `${master}-${clause.sub}` : clause.sub;
10807
- const entry = { sub };
10808
- if (clause.order !== void 0) entry.order = clause.order;
10809
- if (clause.mode !== void 0) entry.mode = clause.mode;
10810
- if (clause.gate !== void 0) entry.gate = clause.gate;
10811
- if (isMaster) entry.is_master = true;
10812
- return entry;
10813
- }
10814
-
10815
11389
  // src/cli.ts
11390
+ init_gates();
10816
11391
  init_gc();
10817
11392
 
10818
11393
  // src/cli/injectStateCmd.ts
@@ -12536,6 +13111,19 @@ ${b.failed.length} component(s) failed \u2014 see the notes in the tables above;
12536
13111
  });
12537
13112
  }
12538
13113
 
13114
+ // src/cli/stopHookCmd.ts
13115
+ init_assetsRoot();
13116
+ function registerStopHook(program2) {
13117
+ program2.command("stop-hook").description("(internal) Stop hook \u2014 auto-recovers mode-B tool-call corruption (issue #6)").action(async () => {
13118
+ try {
13119
+ const mjs = join(getAssetsRoot(), "bin", "harnessed-stop-hook.mjs");
13120
+ if (!existsSync(mjs)) return;
13121
+ await import(pathToFileURL(mjs).href);
13122
+ } catch {
13123
+ }
13124
+ });
13125
+ }
13126
+
12539
13127
  // src/cli/uninstall.ts
12540
13128
  init_i18n();
12541
13129
  init_harnessedRoot();
@@ -12747,7 +13335,7 @@ var uninstallNpmCli = async (ctx) => {
12747
13335
  const m = install.cmd.match(/npm\s+(?:install|i)\s+(?:-g\s+)?(\S+)/);
12748
13336
  const pkg = m?.[1] ?? ctx.manifest.metadata.upstream.source;
12749
13337
  const isWin = process.platform === "win32";
12750
- const result = await new Promise((resolve19) => {
13338
+ const result = await new Promise((resolve21) => {
12751
13339
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], { windowsHide: true }) : spawn("npm", ["uninstall", "-g", pkg], { shell: false });
12752
13340
  let stderr = "";
12753
13341
  child.stderr?.setEncoding("utf8").on("data", (c) => {
@@ -12755,15 +13343,15 @@ var uninstallNpmCli = async (ctx) => {
12755
13343
  });
12756
13344
  const timer = setTimeout(() => {
12757
13345
  child.kill("SIGKILL");
12758
- resolve19({ exitCode: -1, stderr: `${stderr}[timeout]` });
13346
+ resolve21({ exitCode: -1, stderr: `${stderr}[timeout]` });
12759
13347
  }, 3e4);
12760
13348
  child.on("error", (e) => {
12761
13349
  clearTimeout(timer);
12762
- resolve19({ exitCode: -1, stderr: e.message });
13350
+ resolve21({ exitCode: -1, stderr: e.message });
12763
13351
  });
12764
13352
  child.on("close", (code) => {
12765
13353
  clearTimeout(timer);
12766
- resolve19({ exitCode: code ?? -1, stderr });
13354
+ resolve21({ exitCode: code ?? -1, stderr });
12767
13355
  });
12768
13356
  });
12769
13357
  if (result.exitCode !== 0) {
@@ -13258,6 +13846,8 @@ registerUpdate(program);
13258
13846
  registerReleasePreflight(program);
13259
13847
  registerRetro(program);
13260
13848
  registerInjectState(program);
13849
+ registerStopHook(program);
13850
+ registerEval(program);
13261
13851
  var bare = parseBareInvocation(process.argv.slice(2));
13262
13852
  if (bare.here) {
13263
13853
  void runHere({ json: bare.json });