harnessed 4.30.0 → 4.31.1

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.30.0",
41
+ version: "4.31.1",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -2149,107 +2149,51 @@ var init_path_guard = __esm({
2149
2149
  }
2150
2150
  });
2151
2151
 
2152
- // src/checkpoint/intentKind.ts
2153
- var intentKind_exports = {};
2154
- __export(intentKind_exports, {
2155
- classifyIntentKind: () => classifyIntentKind
2156
- });
2157
- function classifyIntentKind(sub, assetsRoot) {
2158
- try {
2159
- const raw = readFileSync(join(assetsRoot, "workflows", "role-prompts.yaml"), "utf8");
2160
- const doc = parse(raw);
2161
- return doc?.prompts?.[sub]?.is_master === true ? "master" : "leaf";
2162
- } catch {
2163
- return "leaf";
2164
- }
2165
- }
2166
- var init_intentKind = __esm({
2167
- "src/checkpoint/intentKind.ts"() {
2168
- }
2169
- });
2170
- function getPackageRoot() {
2171
- const thisFile = fileURLToPath(import.meta.url);
2172
- const thisDir = dirname(thisFile);
2173
- if (thisDir.endsWith("dist") || thisDir.replace(/\\/g, "/").endsWith("/dist")) {
2174
- return resolve(thisDir, "..");
2175
- }
2176
- return resolve(thisDir, "..", "..", "..");
2177
- }
2178
- var init_packagePath = __esm({
2179
- "src/cli/lib/packagePath.ts"() {
2180
- }
2181
- });
2182
-
2183
- // src/cli/lib/assetsRoot.ts
2184
- var assetsRoot_exports = {};
2185
- __export(assetsRoot_exports, {
2186
- compiledAssetsDir: () => compiledAssetsDir,
2187
- computeAssetsRoot: () => computeAssetsRoot,
2188
- getAssetsRoot: () => getAssetsRoot,
2189
- isCompiledModuleUrl: () => isCompiledModuleUrl,
2190
- isCompiledRuntime: () => isCompiledRuntime
2191
- });
2192
- function isCompiledRuntime(url = import.meta.url) {
2193
- return isCompiledModuleUrl(url);
2194
- }
2195
- function isCompiledModuleUrl(url) {
2196
- let s = url;
2197
- try {
2198
- s = decodeURIComponent(url);
2199
- } catch {
2200
- }
2201
- const normalized2 = s.replace(/\\/g, "/").toLowerCase();
2202
- return BUNFS_MARKERS.some((m) => normalized2.includes(m));
2203
- }
2204
- function computeAssetsRoot(d) {
2205
- const override = d.env.HARNESSED_ASSETS_OVERRIDE;
2206
- if (override && override.trim().length > 0) {
2207
- return { root: override.trim(), source: "override", compiledAssetsMissing: false };
2208
- }
2209
- if (isCompiledModuleUrl(d.moduleUrl)) {
2210
- const root = join(d.stateRoot(), "assets", d.version);
2211
- const present = d.exists(join(root, "workflows"));
2212
- return { root, source: "compiled", compiledAssetsMissing: !present };
2213
- }
2214
- return { root: d.packageRoot, source: "package", compiledAssetsMissing: false };
2215
- }
2216
- function compiledAssetsDir(version) {
2217
- return join(detectPlatform().stateRoot, "assets", version);
2218
- }
2219
- function realDeps() {
2220
- return {
2221
- env: process.env,
2222
- moduleUrl: import.meta.url,
2223
- exists: (p7) => {
2224
- try {
2225
- return existsSync(p7);
2226
- } catch {
2227
- return false;
2228
- }
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);
2229
2159
  },
2230
- stateRoot: () => detectPlatform().stateRoot,
2231
- packageRoot: getPackageRoot(),
2232
- 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
+ }
2233
2169
  };
2234
- }
2235
- function getAssetsRoot() {
2236
- const r = computeAssetsRoot(realDeps());
2237
- if (r.source === "compiled" && r.compiledAssetsMissing && !warnedMissing) {
2238
- warnedMissing = true;
2239
- console.error(
2240
- `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)`
2241
- );
2242
- }
2243
- return r.root;
2244
- }
2245
- var BUNFS_MARKERS, warnedMissing;
2246
- var init_assetsRoot = __esm({
2247
- "src/cli/lib/assetsRoot.ts"() {
2248
- init_package();
2249
- init_platform();
2250
- init_packagePath();
2251
- BUNFS_MARKERS = ["/$bunfs/", "/~bun/"];
2252
- 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
+ };
2253
2197
  }
2254
2198
  });
2255
2199
  function estimateTokens(s) {
@@ -3233,7 +3177,7 @@ function nameToYamlHintPath(name) {
3233
3177
  function shouldOverwriteFile(content) {
3234
3178
  return HARNESSED_MARKER_RX.test(content) || V3_4_3_SIGNATURE_SUB_RX.test(content) || V3_4_3_SIGNATURE_MASTER_RX.test(content);
3235
3179
  }
3236
- 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")) {
3237
3181
  const results = [];
3238
3182
  const aggregatedWarnings = /* @__PURE__ */ new Set();
3239
3183
  for (const name of slashNames) {
@@ -3252,7 +3196,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
3252
3196
  if (fileExists2(path)) {
3253
3197
  let existing = "";
3254
3198
  try {
3255
- existing = readFileSync16(path);
3199
+ existing = readFileSync18(path);
3256
3200
  } catch {
3257
3201
  existing = "";
3258
3202
  }
@@ -3685,6 +3629,14 @@ var init_judgment = __esm({
3685
3629
  );
3686
3630
  }
3687
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
+ });
3688
3640
  async function resolveJudgmentGate(gateRef, context, packageRoot) {
3689
3641
  const userOverrides = context.user_overrides;
3690
3642
  if (Array.isArray(userOverrides) && userOverrides.includes(gateRef)) {
@@ -3721,6 +3673,9 @@ async function resolveJudgmentGate(gateRef, context, packageRoot) {
3721
3673
  }
3722
3674
  return evalGate(expr, context);
3723
3675
  }
3676
+ function _clearJudgmentCache() {
3677
+ _fileCache.clear();
3678
+ }
3724
3679
  var TriggerNotFoundError, _fileCache;
3725
3680
  var init_judgmentResolver = __esm({
3726
3681
  "src/workflow/judgmentResolver.ts"() {
@@ -3937,6 +3892,9 @@ function matchSkipSub(requested, sub, master) {
3937
3892
  if (requested.has(sub)) return sub;
3938
3893
  const alias = `${master}-${sub}`;
3939
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
+ }
3940
3898
  return null;
3941
3899
  }
3942
3900
  function warnUnmatchedSkips(requested, matched, master, validSubs, warn) {
@@ -3947,8 +3905,10 @@ function warnUnmatchedSkips(requested, matched, master, validSubs, warn) {
3947
3905
  );
3948
3906
  }
3949
3907
  }
3908
+ var SKIP_SYNONYMS;
3950
3909
  var init_skipSubs = __esm({
3951
3910
  "src/workflow/skipSubs.ts"() {
3911
+ SKIP_SYNONYMS = { clarify: "discuss" };
3952
3912
  }
3953
3913
  });
3954
3914
  function resolveMasterYamlPath(masterName, packageRoot) {
@@ -4512,6 +4472,91 @@ This applies to: strategic-layer review skip / phase-layer clarification skip /
4512
4472
  };
4513
4473
  }
4514
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
+ });
4515
4560
  async function loadUserOverrides(packageRoot) {
4516
4561
  const yamlPath = resolve(packageRoot, "workflows", "judgments", "user-overrides.yaml");
4517
4562
  let raw;
@@ -5209,43 +5254,407 @@ var init_breakLoop = __esm({
5209
5254
  LOOP_THRESHOLD = 3;
5210
5255
  }
5211
5256
  });
5212
- 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) {
5213
5264
  try {
5214
- if (typeof spawnSync !== "function") return null;
5215
- const r = spawnSync(p7, ["-c", "echo harnessed-bash-ok"], { encoding: "utf8", timeout: 5e3 });
5216
- if (!r || r.error) return null;
5217
- 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";
5218
5268
  } catch {
5219
- return null;
5269
+ return "leaf";
5220
5270
  }
5221
5271
  }
5222
- function realWhere(name) {
5223
- try {
5224
- if (typeof spawnSync !== "function") return [];
5225
- const r = spawnSync("where", [name], { encoding: "utf8" });
5226
- if (!r || r.status !== 0) return [];
5227
- return (r.stdout ?? "").split(/\r?\n/).map((s) => s.trim()).filter((s) => s.length > 0);
5228
- } catch {
5229
- return [];
5272
+ var init_intentKind = __esm({
5273
+ "src/checkpoint/intentKind.ts"() {
5230
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);
5231
5287
  }
5232
- 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;
5233
5294
  try {
5234
- return existsSync(p7);
5295
+ parsed = JSON.parse(raw);
5235
5296
  } catch {
5236
- return false;
5297
+ return null;
5237
5298
  }
5238
- }
5239
- function defaultDeps2() {
5240
- return {
5241
- platform: process.platform,
5242
- env: process.env,
5243
- where: realWhere,
5244
- exists: realExists,
5245
- 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 : []
5246
5304
  };
5247
- }
5248
- 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) {
5249
5658
  if (cache2) return cache2;
5250
5659
  cache2 = compute({ ...defaultDeps2(), ...deps });
5251
5660
  return cache2;
@@ -6475,53 +6884,222 @@ var init_doctor_registry = __esm({
6475
6884
  }
6476
6885
  });
6477
6886
 
6478
- // src/cli/gc.ts
6479
- var gc_exports = {};
6480
- __export(gc_exports, {
6481
- gcCompiledArtifacts: () => gcCompiledArtifacts,
6482
- registerGc: () => registerGc
6887
+ // src/cli/gates.ts
6888
+ var gates_exports = {};
6889
+ __export(gates_exports, {
6890
+ registerGates: () => registerGates,
6891
+ runGatesPlan: () => runGatesPlan
6483
6892
  });
6484
- async function gcCompiledArtifacts(opts) {
6485
- const removed = [];
6486
- const kept = [];
6487
- const keep = new Set(opts.keepVersions);
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
+ }
6488
6904
  try {
6489
- const assetsDir = join(opts.stateRoot, "assets");
6490
- for (const e of await readdir(assetsDir, { withFileTypes: true })) {
6491
- if (!e.isDirectory()) continue;
6492
- const p7 = join(assetsDir, e.name);
6493
- if (keep.has(e.name)) {
6494
- kept.push(p7);
6495
- continue;
6496
- }
6497
- removed.push(p7);
6498
- if (!opts.dryRun) await rm(p7, { recursive: true, force: true });
6499
- }
6905
+ checkPathSafe(master);
6500
6906
  } catch {
6907
+ deps.error("error: invalid master name (path traversal rejected)");
6908
+ deps.exit(1);
6909
+ return;
6501
6910
  }
6911
+ const packageRoot = getAssetsRoot();
6912
+ const yamlPath = resolveMasterYamlPath2(master, packageRoot);
6913
+ let raw_yaml;
6502
6914
  try {
6503
- const backupDir = join(opts.stateRoot, "bin-backup");
6504
- const vers = (await readdir(backupDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
6505
- for (const v of vers.slice(0, -1)) {
6506
- const p7 = join(backupDir, v);
6507
- removed.push(p7);
6508
- if (!opts.dryRun) await rm(p7, { recursive: true, force: true });
6509
- }
6510
- const newest = vers[vers.length - 1];
6511
- if (newest) kept.push(join(backupDir, newest));
6512
- } catch {
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;
6513
6922
  }
6514
- if (opts.execPath) {
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;
6515
6943
  try {
6516
- const dir = dirname(opts.execPath);
6517
- const base = basename(opts.execPath);
6518
- for (const e of await readdir(dir, { withFileTypes: true })) {
6519
- if (!e.isFile() || !e.name.startsWith(`${base}.bak-`)) continue;
6520
- const p7 = join(dir, e.name);
6521
- removed.push(p7);
6522
- if (!opts.dryRun) await rm(p7, { force: true });
6523
- }
6524
- } catch {
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
+
7056
+ // src/cli/gc.ts
7057
+ var gc_exports = {};
7058
+ __export(gc_exports, {
7059
+ gcCompiledArtifacts: () => gcCompiledArtifacts,
7060
+ registerGc: () => registerGc
7061
+ });
7062
+ async function gcCompiledArtifacts(opts) {
7063
+ const removed = [];
7064
+ const kept = [];
7065
+ const keep = new Set(opts.keepVersions);
7066
+ try {
7067
+ const assetsDir = join(opts.stateRoot, "assets");
7068
+ for (const e of await readdir(assetsDir, { withFileTypes: true })) {
7069
+ if (!e.isDirectory()) continue;
7070
+ const p7 = join(assetsDir, e.name);
7071
+ if (keep.has(e.name)) {
7072
+ kept.push(p7);
7073
+ continue;
7074
+ }
7075
+ removed.push(p7);
7076
+ if (!opts.dryRun) await rm(p7, { recursive: true, force: true });
7077
+ }
7078
+ } catch {
7079
+ }
7080
+ try {
7081
+ const backupDir = join(opts.stateRoot, "bin-backup");
7082
+ const vers = (await readdir(backupDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
7083
+ for (const v of vers.slice(0, -1)) {
7084
+ const p7 = join(backupDir, v);
7085
+ removed.push(p7);
7086
+ if (!opts.dryRun) await rm(p7, { recursive: true, force: true });
7087
+ }
7088
+ const newest = vers[vers.length - 1];
7089
+ if (newest) kept.push(join(backupDir, newest));
7090
+ } catch {
7091
+ }
7092
+ if (opts.execPath) {
7093
+ try {
7094
+ const dir = dirname(opts.execPath);
7095
+ const base = basename(opts.execPath);
7096
+ for (const e of await readdir(dir, { withFileTypes: true })) {
7097
+ if (!e.isFile() || !e.name.startsWith(`${base}.bak-`)) continue;
7098
+ const p7 = join(dir, e.name);
7099
+ removed.push(p7);
7100
+ if (!opts.dryRun) await rm(p7, { force: true });
7101
+ }
7102
+ } catch {
6525
7103
  }
6526
7104
  }
6527
7105
  return { removed, kept };
@@ -7264,10 +7842,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7264
7842
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
7265
7843
  stderr += chunk;
7266
7844
  });
7267
- return await new Promise((resolve19) => {
7845
+ return await new Promise((resolve21) => {
7268
7846
  const timer = setTimeout(() => {
7269
7847
  child.kill("SIGKILL");
7270
- resolve19({
7848
+ resolve21({
7271
7849
  ok: false,
7272
7850
  phase: "spawn",
7273
7851
  error: {
@@ -7288,7 +7866,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7288
7866
  child.on("error", (err2) => {
7289
7867
  clearTimeout(timer);
7290
7868
  const bashMissing = triedBash && err2.code === "ENOENT";
7291
- resolve19({
7869
+ resolve21({
7292
7870
  ok: false,
7293
7871
  phase: "spawn",
7294
7872
  error: {
@@ -7303,7 +7881,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7303
7881
  });
7304
7882
  child.on("close", (code) => {
7305
7883
  clearTimeout(timer);
7306
- resolve19({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
7884
+ resolve21({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
7307
7885
  });
7308
7886
  });
7309
7887
  }
@@ -7504,7 +8082,7 @@ var init_idempotent = __esm({
7504
8082
  }
7505
8083
  });
7506
8084
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
7507
- return new Promise((resolve19) => {
8085
+ return new Promise((resolve21) => {
7508
8086
  const isWin = process.platform === "win32";
7509
8087
  const stdio = ["ignore", "pipe", "pipe"];
7510
8088
  const child = isWin ? spawn("cmd.exe", ["/c", bin, ...args], { cwd, windowsHide: true, stdio }) : spawn(bin, args, { cwd, shell: false, stdio });
@@ -7518,17 +8096,17 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
7518
8096
  });
7519
8097
  const timer = setTimeout(() => {
7520
8098
  child.kill("SIGKILL");
7521
- resolve19({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
8099
+ resolve21({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
7522
8100
  }, timeoutMs);
7523
8101
  child.on("error", (e) => {
7524
8102
  clearTimeout(timer);
7525
8103
  const enoent = e.code === "ENOENT";
7526
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;
7527
- resolve19({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
8105
+ resolve21({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
7528
8106
  });
7529
8107
  child.on("close", (code) => {
7530
8108
  clearTimeout(timer);
7531
- resolve19({ exitCode: code ?? -1, stdout: stdout2, stderr });
8109
+ resolve21({ exitCode: code ?? -1, stdout: stdout2, stderr });
7532
8110
  });
7533
8111
  });
7534
8112
  }
@@ -7784,7 +8362,7 @@ var init_packSkillAudit = __esm({
7784
8362
  }
7785
8363
  });
7786
8364
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
7787
- return new Promise((resolve19) => {
8365
+ return new Promise((resolve21) => {
7788
8366
  const isWin = process.platform === "win32";
7789
8367
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
7790
8368
  let stdout2 = "";
@@ -7793,15 +8371,15 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
7793
8371
  });
7794
8372
  const timer = setTimeout(() => {
7795
8373
  child.kill("SIGKILL");
7796
- resolve19({ sha: "", exit: -1 });
8374
+ resolve21({ sha: "", exit: -1 });
7797
8375
  }, timeoutMs);
7798
8376
  child.on("error", () => {
7799
8377
  clearTimeout(timer);
7800
- resolve19({ sha: "", exit: -1 });
8378
+ resolve21({ sha: "", exit: -1 });
7801
8379
  });
7802
8380
  child.on("close", (code) => {
7803
8381
  clearTimeout(timer);
7804
- resolve19({ sha: stdout2.trim(), exit: code ?? -1 });
8382
+ resolve21({ sha: stdout2.trim(), exit: code ?? -1 });
7805
8383
  });
7806
8384
  });
7807
8385
  }
@@ -10156,7 +10734,7 @@ function renderHumanTable(records) {
10156
10734
  }
10157
10735
  }
10158
10736
  function pipeToJq(filterExpr, lines) {
10159
- return new Promise((resolve19, reject) => {
10737
+ return new Promise((resolve21, reject) => {
10160
10738
  const child = spawn("jq", [filterExpr], {
10161
10739
  stdio: ["pipe", "inherit", "inherit"],
10162
10740
  windowsHide: true
@@ -10165,12 +10743,12 @@ function pipeToJq(filterExpr, lines) {
10165
10743
  const e = err2;
10166
10744
  if (e.code === "ENOENT") {
10167
10745
  console.error(t("audit_log.jq_missing"));
10168
- resolve19(1);
10746
+ resolve21(1);
10169
10747
  } else {
10170
10748
  reject(err2);
10171
10749
  }
10172
10750
  });
10173
- child.on("close", (code) => resolve19(code ?? 0));
10751
+ child.on("close", (code) => resolve21(code ?? 0));
10174
10752
  child.stdin.write(lines.join("\n"));
10175
10753
  child.stdin.end();
10176
10754
  });
@@ -10266,374 +10844,523 @@ function registerBackupList(program2) {
10266
10844
  });
10267
10845
  }
10268
10846
 
10269
- // src/cli/checkpoint.ts
10270
- init_path_guard();
10271
- init_ledger();
10272
- var ACTIONS = ["start", "complete", "fail", "intent"];
10273
- function isAction(a) {
10274
- return ACTIONS.includes(a);
10847
+ // src/cli.ts
10848
+ init_checkpoint();
10849
+
10850
+ // src/cli/compact-cmd.ts
10851
+ function registerCompact(program2) {
10852
+ program2.command("compact").description(
10853
+ "Evict resolved (done/skipped/rejected, no fail_count) ledger entries; reports token reduction"
10854
+ ).action(async () => {
10855
+ const { compactWorkflow: compactWorkflow2 } = await Promise.resolve().then(() => (init_compact(), compact_exports));
10856
+ const r = await compactWorkflow2();
10857
+ if (r.evicted === 0) {
10858
+ console.log("[harnessed] compact: nothing to evict (all pending/failed or empty ledger)");
10859
+ process.exit(0);
10860
+ return;
10861
+ }
10862
+ console.log(
10863
+ `[harnessed] compact: phase=${r.phase} evicted=${r.evicted} tokens ${r.before_tokens}->${r.after_tokens} (-${r.pct_saved}%) \u2014 ${r.digest}`
10864
+ );
10865
+ process.exit(0);
10866
+ });
10275
10867
  }
10276
- function markIfSeeded(entries, sub, status, opts) {
10277
- return entries.some((e) => e.sub === sub) ? markSub(entries, sub, status, opts) : entries;
10868
+
10869
+ // src/cli/doctor.ts
10870
+ init_i18n();
10871
+ init_doctor_registry();
10872
+ function registerDoctor(program2) {
10873
+ program2.command("doctor").description(
10874
+ "Preflight checks (Node / MCP scope / jq / Win bash / origin URL / gstack prefix / deprecations / token budget / Agent Teams / planning-with-files / mattpocock-skills / MCP availability)"
10875
+ ).option("--json", "output JSON instead of human-readable").action(async (opts) => {
10876
+ const results = await Promise.all(CHECKS.map((c) => c()));
10877
+ const hasFail = results.some((r) => r.status === "fail");
10878
+ const hasWarn = results.some((r) => r.status === "warn");
10879
+ if (opts.json) {
10880
+ console.log(
10881
+ JSON.stringify(
10882
+ { checks: results, summary: hasFail ? "fail" : hasWarn ? "warn" : "pass" },
10883
+ null,
10884
+ 2
10885
+ )
10886
+ );
10887
+ } else {
10888
+ for (const r of results) {
10889
+ const mark = r.status === "pass" ? "\u2713" : r.status === "warn" ? "\u26A0" : "\u2717";
10890
+ console.log(`${mark} ${r.name} \u2014 ${r.message}`);
10891
+ if (r.status !== "pass" && r.fix) console.log(` fix: ${r.fix}`);
10892
+ }
10893
+ console.log(
10894
+ hasFail ? t("doctor.summary.fail") : hasWarn ? t("doctor.summary.warn") : t("doctor.summary.pass")
10895
+ );
10896
+ }
10897
+ process.exit(hasFail ? 1 : 0);
10898
+ });
10278
10899
  }
10279
- async function parsePlan(raw) {
10280
- if (!raw || raw.trim() === "") return null;
10281
- let parsed;
10282
- try {
10283
- parsed = JSON.parse(raw);
10284
- } catch {
10285
- return null;
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>");
10286
10910
  }
10287
- const p7 = parsed;
10288
- if (!Array.isArray(p7.fire) && !Array.isArray(p7.skip)) return null;
10289
- const plan = {
10290
- fire: Array.isArray(p7.fire) ? p7.fire : [],
10291
- skip: Array.isArray(p7.skip) ? p7.skip : []
10292
- };
10293
- if (typeof p7.master === "string") plan.master = p7.master;
10294
- if (p7.parallelism && typeof p7.parallelism === "object" && !Array.isArray(p7.parallelism)) {
10295
- plan.parallelism = p7.parallelism;
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;
10296
10923
  }
10297
- return plan;
10924
+ return value;
10298
10925
  }
10299
- async function absorbIntentFor(sub) {
10926
+ function loadGolden(path) {
10300
10927
  try {
10301
- const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10302
- const { activeKey: activeKey2, repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
10303
- await mutateStore2((store) => {
10304
- if (!store.intents) return store;
10305
- const intents = { ...store.intents };
10306
- for (const k of [activeKey2(), repoKey2()]) {
10307
- if (intents[k]?.master === sub) delete intents[k];
10308
- }
10309
- return { ...store, intents };
10310
- });
10928
+ return JSON.parse(readFileSync(path, "utf8"));
10311
10929
  } catch {
10930
+ return null;
10312
10931
  }
10313
10932
  }
10314
- async function serialOrderBlockers(sub) {
10315
- try {
10316
- const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10317
- const { findSerialBlockers: findSerialBlockers2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
10318
- const wf = await readCurrentWorkflow2();
10319
- return findSerialBlockers2(wf?.sub_progress ?? [], sub);
10320
- } catch (e) {
10321
- console.warn(`[harnessed] serial-order guard skipped (fail-soft): ${e.message}`);
10322
- return [];
10323
- }
10933
+ function writeGolden(path, value) {
10934
+ writeFileSync(path, `${JSON.stringify(value, null, 2)}
10935
+ `, "utf8");
10324
10936
  }
10325
- function enforceSerialOrder(action, sub, blockers, force) {
10326
- if (blockers.length === 0) return true;
10327
- if (!force) {
10328
- console.error(
10329
- `[harnessed] checkpoint ${action} BLOCKED: ${sub} \u2014 ${blockers.length} earlier serial-sequence sub(s) still pending (serial-order guard, fail-closed):`
10330
- );
10331
- for (const b of blockers) console.error(` - ${b} (complete or fail it first)`);
10332
- console.error(" (re-run with --force to jump the sequence deliberately)");
10333
- return false;
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;
10334
10951
  }
10335
- console.warn(
10336
- `[harnessed] serial-order guard overridden (--force): ${action} ${sub} ahead of pending sub(s) ${blockers.join(", ")}`
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}`
10337
11028
  );
10338
- return true;
11029
+ return { ok: false, errors: errors.length > 0 ? errors : ["invalid scenario"] };
10339
11030
  }
10340
- function registerCheckpoint(program2) {
10341
- program2.command("checkpoint <action> <sub>").description(
10342
- "Record workflow progress: intent | start | complete | fail <sub-workflow> (writes to ~/.claude/harnessed/checkpoints/)"
10343
- ).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(
10344
- "--force",
10345
- "complete/fail \u2014 override a fail-closed guard: the missing-artifact evidence block (complete; records overridden) or the serial-order guard"
10346
- ).option(
10347
- "--tokens <n>",
10348
- "complete only \u2014 conversation token count; auto-compacts the ledger when >= the shouldCompact threshold (Phase 14)"
10349
- ).action(
10350
- async (action, sub, opts) => {
10351
- if (!isAction(action)) {
10352
- console.error(
10353
- `[harnessed] checkpoint: unknown action "${action}" \u2014 expected one of ${ACTIONS.join(", ")}`
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
10354
11118
  );
10355
- process.exit(1);
10356
- return;
10357
- }
10358
- if (action === "intent") {
10359
- try {
10360
- checkPathSafe(sub);
10361
- const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10362
- const { activeKey: activeKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
10363
- const { classifyIntentKind: classifyIntentKind2 } = await Promise.resolve().then(() => (init_intentKind(), intentKind_exports));
10364
- const { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
10365
- const kind = classifyIntentKind2(sub, getAssetsRoot2());
10366
- const key = activeKey2();
10367
- await mutateStore2((store) => ({
10368
- ...store,
10369
- intents: {
10370
- ...store.intents ?? {},
10371
- [key]: { master: sub, ts: (/* @__PURE__ */ new Date()).toISOString(), kind }
10372
- }
10373
- }));
10374
- console.log(
10375
- 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.`
10376
- );
10377
- } catch {
10378
- }
10379
- process.exit(0);
10380
- return;
10381
- }
10382
- try {
10383
- checkPathSafe(sub);
10384
- } catch {
10385
- console.error("[harnessed] checkpoint: invalid sub name (path traversal rejected)");
10386
- process.exit(1);
10387
- return;
10388
- }
10389
- const { activatePhase: activatePhase2, completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
10390
- if (action === "start") {
10391
- try {
10392
- const { stat: statFs } = await import('fs/promises');
10393
- const { resolve: resolvePath } = await import('path');
10394
- const planningDir = resolvePath(process.cwd(), ".planning");
10395
- const hasPlanning = await statFs(planningDir).then((s) => s.isDirectory()).catch(() => false);
10396
- if (hasPlanning) {
10397
- const missing = [];
10398
- for (const f of ["STATE.md", "ROADMAP.md"]) {
10399
- const ok = await statFs(resolvePath(planningDir, f)).then((s) => s.isFile()).catch(() => false);
10400
- if (!ok) missing.push(`.planning/${f}`);
10401
- }
10402
- if (missing.length > 0) {
10403
- console.error(
10404
- `\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).`
10405
- );
10406
- }
10407
- }
10408
- } catch {
10409
- }
10410
- try {
10411
- const { detectGateGuardActive: detectGateGuardActive2, GUARD_CONFLICT_ADVICE: GUARD_CONFLICT_ADVICE2 } = await Promise.resolve().then(() => (init_check_guard_conflict(), check_guard_conflict_exports));
10412
- const det = await detectGateGuardActive2();
10413
- if (det.active) {
10414
- const ge = await Promise.resolve().then(() => (init_guard_exemption(), guard_exemption_exports));
10415
- const isTty = process.stdin.isTTY === true && process.stdout.isTTY === true;
10416
- const flowResult = await ge.runExemptionFlow({
10417
- probe: () => ge.probeExemptCapability(),
10418
- readEnvValue: () => ge.readCurrentEnvValue(),
10419
- merge: (value) => ge.applyEnvExemption(value),
10420
- print: (line) => console.error(line),
10421
- ...isTty ? {
10422
- confirm: async () => {
10423
- const p7 = await import('@clack/prompts');
10424
- const ans = await p7.confirm({
10425
- message: 'Apply the GateGuard exemption now? (persists GATEGUARD_EXEMPT_GLOBS=".planning/**" into settings env \u2014 backed up first)',
10426
- initialValue: true
10427
- // D1 — default YES
10428
- });
10429
- return !p7.isCancel(ans) && ans === true;
10430
- }
10431
- } : {}
10432
- });
10433
- if (flowResult === "not-capable") {
10434
- console.error(
10435
- `\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
10436
- );
10437
- }
10438
- }
10439
- } catch {
10440
- }
10441
- const { checkpointPath } = await activatePhase2(sub);
10442
- const plan = await parsePlan(opts.plan);
10443
- if (plan) {
10444
- const { seedLedger: seedLedger2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
10445
- const { mutateSubProgress: mutateSubProgress3 } = await Promise.resolve().then(() => (init_state(), state_exports));
10446
- await mutateSubProgress3(() => seedLedger2(plan));
10447
- }
10448
- try {
10449
- const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10450
- const { activeKey: activeKey2, repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
10451
- await mutateStore2((store) => {
10452
- if (!store.intents) return store;
10453
- const intents = { ...store.intents };
10454
- delete intents[activeKey2()];
10455
- delete intents[repoKey2()];
10456
- return { ...store, intents };
10457
- });
10458
- } catch {
10459
- }
10460
- console.log(`[harnessed] checkpoint started: ${sub} \u2192 ${checkpointPath}`);
10461
- process.exit(0);
10462
- return;
10463
11119
  }
10464
- if (action === "complete") {
10465
- if (!enforceSerialOrder("complete", sub, await serialOrderBlockers(sub), opts.force)) {
10466
- process.exit(1);
10467
- return;
10468
- }
10469
- const { checkArtifacts: checkArtifacts2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
10470
- const { mutateSubProgress: mutateSubProgress3 } = await Promise.resolve().then(() => (init_state(), state_exports));
10471
- const { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
10472
- const result = await checkArtifacts2(sub, getAssetsRoot2());
10473
- const { checkPlanningSync: checkPlanningSync2 } = await Promise.resolve().then(() => (init_evidence(), evidence_exports));
10474
- const syncResult = await checkPlanningSync2(process.cwd(), null);
10475
- const allMissing = [...result.missing, ...syncResult.missing];
10476
- if (allMissing.length > 0 && !opts.force) {
10477
- console.error(
10478
- `[harnessed] checkpoint complete BLOCKED: ${sub} \u2014 ${allMissing.length} item(s) missing (evidence guard + .planning/ sync, fail-closed):`
10479
- );
10480
- for (const m of allMissing) console.error(` - ${m}`);
10481
- console.error(
10482
- " (re-run with --force to override and record evidence_status=overridden)"
10483
- );
10484
- process.exit(1);
10485
- return;
10486
- }
10487
- let evidenceStatus;
10488
- if (allMissing.length > 0 && opts.force) evidenceStatus = "overridden";
10489
- else if (result.status === "verified") evidenceStatus = "verified";
10490
- else evidenceStatus = "none_declared";
10491
- const markOpts = evidenceStatus === "none_declared" ? { evidence_status: evidenceStatus } : { evidence: result.found, evidence_status: evidenceStatus };
10492
- await mutateSubProgress3((e) => markIfSeeded(e, sub, "done", markOpts));
10493
- await absorbIntentFor(sub);
10494
- const { collectScaleMetrics: collectScaleMetrics2, assessScale: assessScale2 } = await Promise.resolve().then(() => (init_scale(), scale_exports));
10495
- const { readCurrentWorkflow: readCurrentWorkflow3, writeCurrentWorkflow: writeCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10496
- const afterMark = await readCurrentWorkflow3();
10497
- if (afterMark) {
10498
- const metrics = await collectScaleMetrics2(process.cwd(), afterMark.sub_progress ?? []);
10499
- await writeCurrentWorkflow2({ ...afterMark, verify_mode: assessScale2(metrics) });
10500
- }
10501
- const { nextPending: nextPending2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
10502
- const allResolved = nextPending2(afterMark?.sub_progress ?? []) === null;
10503
- await completePhase2({
10504
- phaseId: sub,
10505
- status: "complete",
10506
- lastTask: opts.summary ?? `phase ${sub} complete`,
10507
- transitionWorkflowComplete: allResolved
10508
- });
10509
- if (allResolved && afterMark) {
10510
- const { captureWorkflowLearnings: captureWorkflowLearnings2 } = await Promise.resolve().then(() => (init_learnings(), learnings_exports));
10511
- const captured = await captureWorkflowLearnings2(afterMark.sub_progress ?? [], sub);
10512
- if (captured > 0) {
10513
- console.log(`[harnessed] captured ${captured} learning(s) \u2192 .planning/LEARNINGS.md`);
10514
- }
10515
- }
10516
- const { shouldAutoCompact: shouldAutoCompact2, compactWorkflow: compactWorkflow2 } = await Promise.resolve().then(() => (init_compact(), compact_exports));
10517
- if (shouldAutoCompact2(opts.tokens != null ? Number(opts.tokens) : void 0)) {
10518
- const c = await compactWorkflow2();
10519
- if (c.evicted > 0) {
10520
- console.log(
10521
- `[harnessed] auto-compact: evicted ${c.evicted} resolved entries (-${c.pct_saved}% tokens)`
10522
- );
10523
- }
10524
- }
10525
- if (allResolved) {
10526
- try {
10527
- const { defaultShipReady: defaultShipReady2 } = await Promise.resolve().then(() => (init_shipReady(), shipReady_exports));
10528
- const { incrementPhases: incrementPhases2, isRetroDue: isRetroDue2, retroThreshold: retroThreshold2 } = await Promise.resolve().then(() => (init_retroMeta(), retroMeta_exports));
10529
- const { mutateStore: mutateStore2, readCurrentWorkflow: readCurrentWorkflow4, writeCurrentWorkflow: writeCurrentWorkflow3 } = await Promise.resolve().then(() => (init_state(), state_exports));
10530
- const { repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
10531
- const ship = defaultShipReady2(process.cwd());
10532
- const key = repoKey2();
10533
- const threshold = retroThreshold2(process.env);
10534
- let retroDue = false;
10535
- await mutateStore2((store) => {
10536
- const meta = { ...store.retro_meta ?? {} };
10537
- const next = incrementPhases2(meta[key]);
10538
- meta[key] = next;
10539
- retroDue = isRetroDue2(next.phases_since_retro, threshold);
10540
- return { ...store, retro_meta: meta };
10541
- });
10542
- const latest2 = await readCurrentWorkflow4();
10543
- if (latest2) {
10544
- await writeCurrentWorkflow3({
10545
- ...latest2,
10546
- ship_ready: ship.ready,
10547
- ship_commits: ship.commits,
10548
- retro_due: retroDue
10549
- });
10550
- }
10551
- } catch {
10552
- }
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
+ const prevCeiling = process.env.GIT_CEILING_DIRECTORIES;
11161
+ process.env.GIT_CEILING_DIRECTORIES = tmpdir();
11162
+ process.env.HARNESSED_ROOT_OVERRIDE = stateRoot;
11163
+ if (scenario.assets_dir) {
11164
+ process.env.HARNESSED_ASSETS_OVERRIDE = isAbsolute(scenario.assets_dir) ? scenario.assets_dir : resolve(dir, scenario.assets_dir);
11165
+ }
11166
+ process.chdir(repoDir);
11167
+ const { _clearJudgmentCache: _clearJudgmentCache2 } = await Promise.resolve().then(() => (init_judgmentResolver(), judgmentResolver_exports));
11168
+ _clearJudgmentCache2();
11169
+ const steps = [];
11170
+ const evaluatedGateRefs = /* @__PURE__ */ new Set();
11171
+ let engineError = null;
11172
+ let workflow = null;
11173
+ try {
11174
+ for (const step of scenario.steps) {
11175
+ const rec = await execStep(scenario, step, repoDir);
11176
+ steps.push(rec);
11177
+ if (rec.kind === "gates") {
11178
+ for (const line of [...rec.stdout, ...rec.stderr]) {
11179
+ for (const m of line.matchAll(GATE_REF_RE)) evaluatedGateRefs.add(m[0]);
10553
11180
  }
10554
- console.log(`[harnessed] checkpoint complete: ${sub} (evidence: ${evidenceStatus})`);
10555
- process.exit(0);
10556
- return;
10557
- }
10558
- if (!enforceSerialOrder("fail", sub, await serialOrderBlockers(sub), opts.force)) {
10559
- process.exit(1);
10560
- return;
10561
11181
  }
10562
- const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10563
- await mutateSubProgress2((e) => markIfSeeded(e, sub, "failed"));
10564
- await absorbIntentFor(sub);
10565
- await completePhase2({
10566
- phaseId: sub,
10567
- status: "complete",
10568
- lastTask: `FAILED: ${opts.summary ?? ""}`,
10569
- transitionWorkflowComplete: false
10570
- });
11182
+ }
11183
+ try {
10571
11184
  const { readCurrentWorkflow: readCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
10572
- const { detectLoop: detectLoop2, LOOP_THRESHOLD: LOOP_THRESHOLD2 } = await Promise.resolve().then(() => (init_breakLoop(), breakLoop_exports));
10573
- const latest = await readCurrentWorkflow2();
10574
- const loops = detectLoop2(latest?.sub_progress ?? []);
10575
- const looped = loops.find((l) => l.sub === sub);
10576
- if (looped) {
10577
- console.error(
10578
- `[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/.`
10579
- );
10580
- }
10581
- console.error(
10582
- `[harnessed] checkpoint FAILED recorded: ${sub}${opts.summary ? ` \u2014 ${opts.summary}` : ""}`
10583
- );
10584
- process.exit(1);
11185
+ workflow = await readCurrentWorkflow2();
11186
+ } catch {
11187
+ workflow = null;
10585
11188
  }
10586
- );
11189
+ } catch (e) {
11190
+ engineError = e;
11191
+ } finally {
11192
+ process.chdir(prevCwd);
11193
+ if (prevRoot === void 0) delete process.env.HARNESSED_ROOT_OVERRIDE;
11194
+ else process.env.HARNESSED_ROOT_OVERRIDE = prevRoot;
11195
+ if (prevAssets === void 0) delete process.env.HARNESSED_ASSETS_OVERRIDE;
11196
+ else process.env.HARNESSED_ASSETS_OVERRIDE = prevAssets;
11197
+ if (prevCeiling === void 0) delete process.env.GIT_CEILING_DIRECTORIES;
11198
+ else process.env.GIT_CEILING_DIRECTORIES = prevCeiling;
11199
+ _clearJudgmentCache2();
11200
+ }
11201
+ const cleanup = () => {
11202
+ rmSync(stateRoot, { recursive: true, force: true });
11203
+ rmSync(repoDir, { recursive: true, force: true });
11204
+ };
11205
+ if (engineError) {
11206
+ cleanup();
11207
+ return {
11208
+ name: scenario.name,
11209
+ dir,
11210
+ status: "ERROR",
11211
+ detail: [engineError.message, ...(engineError.stack ?? "").split("\n").slice(1, 6)],
11212
+ evaluatedGateRefs: [...evaluatedGateRefs]
11213
+ };
11214
+ }
11215
+ cleanup();
11216
+ const actual = normalizeGolden({ steps, workflow }, [stateRoot, repoDir, tmpdir()]);
11217
+ const goldenPath = join(dir, scenario.expect?.golden ?? "golden.json");
11218
+ if (opts.updateGolden) {
11219
+ const before = loadGolden(goldenPath);
11220
+ writeGolden(goldenPath, actual);
11221
+ const detail = before ? diffGolden(before, actual) : ["(new golden recorded)"];
11222
+ return {
11223
+ name: scenario.name,
11224
+ dir,
11225
+ status: "UPDATED",
11226
+ detail,
11227
+ evaluatedGateRefs: [...evaluatedGateRefs]
11228
+ };
11229
+ }
11230
+ const golden = loadGolden(goldenPath);
11231
+ if (golden === null) {
11232
+ return {
11233
+ name: scenario.name,
11234
+ dir,
11235
+ status: "MISSING-GOLDEN",
11236
+ detail: [`no golden at ${goldenPath} \u2014 record it with \`harnessed eval --update-golden\``],
11237
+ evaluatedGateRefs: [...evaluatedGateRefs]
11238
+ };
11239
+ }
11240
+ const diff = diffGolden(golden, actual);
11241
+ if (diff.length > 0) {
11242
+ return {
11243
+ name: scenario.name,
11244
+ dir,
11245
+ status: "FAIL",
11246
+ detail: diff,
11247
+ evaluatedGateRefs: [...evaluatedGateRefs]
11248
+ };
11249
+ }
11250
+ return { name: scenario.name, dir, status: "PASS", evaluatedGateRefs: [...evaluatedGateRefs] };
10587
11251
  }
10588
-
10589
- // src/cli/compact-cmd.ts
10590
- function registerCompact(program2) {
10591
- program2.command("compact").description(
10592
- "Evict resolved (done/skipped/rejected, no fail_count) ledger entries; reports token reduction"
10593
- ).action(async () => {
10594
- const { compactWorkflow: compactWorkflow2 } = await Promise.resolve().then(() => (init_compact(), compact_exports));
10595
- const r = await compactWorkflow2();
10596
- if (r.evicted === 0) {
10597
- console.log("[harnessed] compact: nothing to evict (all pending/failed or empty ledger)");
10598
- process.exit(0);
10599
- return;
11252
+ async function runEvalSuite(suiteDir, opts) {
11253
+ const results = [];
11254
+ let entries = [];
11255
+ try {
11256
+ entries = readdirSync(suiteDir, { withFileTypes: true }).filter((d) => d.isDirectory()).map((d) => join(suiteDir, d.name)).sort();
11257
+ } catch {
11258
+ entries = [];
11259
+ }
11260
+ for (const dir of entries) {
11261
+ try {
11262
+ readFileSync(join(dir, "scenario.yaml"));
11263
+ } catch {
11264
+ continue;
10600
11265
  }
10601
- console.log(
10602
- `[harnessed] compact: phase=${r.phase} evicted=${r.evicted} tokens ${r.before_tokens}->${r.after_tokens} (-${r.pct_saved}%) \u2014 ${r.digest}`
10603
- );
10604
- process.exit(0);
10605
- });
11266
+ if (opts.filter && !dir.includes(opts.filter)) ;
11267
+ const r = await runScenarioDir(dir, opts);
11268
+ if (opts.filter && !r.name.includes(opts.filter) && !dir.includes(opts.filter)) continue;
11269
+ results.push(r);
11270
+ }
11271
+ const summary = {
11272
+ pass: results.filter((r) => r.status === "PASS").length,
11273
+ fail: results.filter((r) => r.status === "FAIL").length,
11274
+ error: results.filter((r) => r.status === "ERROR").length,
11275
+ configError: results.filter((r) => r.status === "CONFIG-ERROR").length,
11276
+ missingGolden: results.filter((r) => r.status === "MISSING-GOLDEN").length,
11277
+ updated: results.filter((r) => r.status === "UPDATED").length
11278
+ };
11279
+ return { results, summary };
11280
+ }
11281
+ function computeCoverage(evaluatedRefs, assetsRoot) {
11282
+ const evaluated = new Set(evaluatedRefs);
11283
+ const out = [];
11284
+ const dir = join(assetsRoot, "workflows", "judgments");
11285
+ let files = [];
11286
+ try {
11287
+ files = readdirSync(dir).filter((f) => f.endsWith(".yaml"));
11288
+ } catch {
11289
+ return out;
11290
+ }
11291
+ for (const f of files) {
11292
+ let parsed = null;
11293
+ try {
11294
+ parsed = parse(readFileSync(join(dir, f), "utf8"));
11295
+ } catch {
11296
+ continue;
11297
+ }
11298
+ const triggers = parsed?.triggers;
11299
+ if (!triggers) continue;
11300
+ const base = f.replace(/\.yaml$/, "");
11301
+ for (const key of Object.keys(triggers)) {
11302
+ const ref = `judgments.${base}.${key}.fires`;
11303
+ out.push({ ref, covered: evaluated.has(ref) });
11304
+ }
11305
+ }
11306
+ return out;
10606
11307
  }
10607
11308
 
10608
- // src/cli/doctor.ts
10609
- init_i18n();
10610
- init_doctor_registry();
10611
- function registerDoctor(program2) {
10612
- program2.command("doctor").description(
10613
- "Preflight checks (Node / MCP scope / jq / Win bash / origin URL / gstack prefix / deprecations / token budget / Agent Teams / planning-with-files / mattpocock-skills / MCP availability)"
10614
- ).option("--json", "output JSON instead of human-readable").action(async (opts) => {
10615
- const results = await Promise.all(CHECKS.map((c) => c()));
10616
- const hasFail = results.some((r) => r.status === "fail");
10617
- const hasWarn = results.some((r) => r.status === "warn");
10618
- if (opts.json) {
10619
- console.log(
10620
- JSON.stringify(
10621
- { checks: results, summary: hasFail ? "fail" : hasWarn ? "warn" : "pass" },
10622
- null,
10623
- 2
10624
- )
10625
- );
10626
- } else {
10627
- for (const r of results) {
10628
- const mark = r.status === "pass" ? "\u2713" : r.status === "warn" ? "\u26A0" : "\u2717";
10629
- console.log(`${mark} ${r.name} \u2014 ${r.message}`);
10630
- if (r.status !== "pass" && r.fix) console.log(` fix: ${r.fix}`);
11309
+ // src/cli/evalCmd.ts
11310
+ init_assetsRoot();
11311
+ init_runDeps();
11312
+ async function runEvalCommand(raw, deps = defaultRunDeps) {
11313
+ const suiteDir = resolve(raw.dir ?? resolve(process.cwd(), "fixtures", "eval"));
11314
+ const suite = await runEvalSuite(suiteDir, {
11315
+ ...raw.updateGolden !== void 0 ? { updateGolden: raw.updateGolden } : {},
11316
+ ...raw.filter !== void 0 ? { filter: raw.filter } : {}
11317
+ });
11318
+ const failures = suite.results.filter(
11319
+ (r) => r.status === "FAIL" || r.status === "ERROR" || r.status === "CONFIG-ERROR"
11320
+ );
11321
+ const missing = suite.results.filter((r) => r.status === "MISSING-GOLDEN");
11322
+ const failing = failures.length + missing.length;
11323
+ if (raw.json) {
11324
+ deps.log(JSON.stringify({ results: suite.results, summary: suite.summary }, null, 2));
11325
+ } else {
11326
+ if (suite.results.length === 0) {
11327
+ deps.log(`[harnessed eval] 0 scenarios under ${suiteDir}`);
11328
+ }
11329
+ for (const r of suite.results) {
11330
+ deps.log(`${r.status.padEnd(14)} ${r.name}`);
11331
+ if (r.status !== "PASS" && r.detail) {
11332
+ for (const line of r.detail.slice(0, 20)) deps.log(` ${line}`);
10631
11333
  }
10632
- console.log(
10633
- hasFail ? t("doctor.summary.fail") : hasWarn ? t("doctor.summary.warn") : t("doctor.summary.pass")
11334
+ }
11335
+ const s = suite.summary;
11336
+ deps.log(
11337
+ `[harnessed eval] pass ${s.pass} / fail ${s.fail} / error ${s.error} / config-error ${s.configError} / missing-golden ${s.missingGolden} / updated ${s.updated}`
11338
+ );
11339
+ }
11340
+ if (raw.coverage) {
11341
+ const refs = suite.results.flatMap((r) => r.evaluatedGateRefs);
11342
+ const cov = computeCoverage(refs, getAssetsRoot());
11343
+ const bare2 = cov.filter((c) => !c.covered);
11344
+ deps.log(`[harnessed eval] trigger coverage: ${cov.length - bare2.length}/${cov.length}`);
11345
+ for (const c of cov) {
11346
+ deps.log(` ${c.covered ? "covered " : "BARE "} ${c.ref}`);
11347
+ }
11348
+ }
11349
+ if (process.env.GITHUB_ACTIONS && failing > 0) {
11350
+ for (const r of [...failures, ...missing]) {
11351
+ deps.log(
11352
+ `::error title=harnessed eval ${r.status}::${r.name} \u2014 ${(r.detail ?? []).slice(0, 3).join(" | ")}`
10634
11353
  );
10635
11354
  }
10636
- process.exit(hasFail ? 1 : 0);
11355
+ }
11356
+ deps.exit(failing > 0 ? 1 : 0);
11357
+ return;
11358
+ }
11359
+ function registerEval(program2) {
11360
+ program2.command("eval").description(
11361
+ "run the orchestrator-behavior regression trap suite (deterministic replay; CI gate)"
11362
+ ).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) => {
11363
+ await runEvalCommand(raw);
10637
11364
  });
10638
11365
  }
10639
11366
 
@@ -10663,161 +11390,8 @@ function registerExemptGateguard(program2) {
10663
11390
  });
10664
11391
  }
10665
11392
 
10666
- // src/cli/gates.ts
10667
- init_path_guard();
10668
- init_exprBuilder();
10669
- init_judgmentResolver();
10670
- init_skipSubs();
10671
- init_assetsRoot();
10672
- init_gateContext();
10673
- var VALID_MASTERS = /* @__PURE__ */ new Set(["auto", "discuss", "plan", "task", "verify", "ship"]);
10674
- var STAGE_MASTERS = /* @__PURE__ */ new Set(["discuss", "plan", "task", "verify"]);
10675
- var PARALLELISM_GATE = "judgments.parallelism-gate.agent-teams-upgrade.fires";
10676
- function resolveMasterYamlPath2(master, packageRoot) {
10677
- return master === "auto" ? resolve(packageRoot, "workflows", "auto", "workflow.yaml") : resolve(packageRoot, "workflows", master, "auto", "workflow.yaml");
10678
- }
10679
- function registerGates(program2) {
10680
- program2.command("gates").description(
10681
- "Evaluate which sub-workflows fire for a master orchestrator (JSON plan, no spawn)."
10682
- ).argument("<master>", "master name: auto | discuss | plan | task | verify | ship").option("--task <text>", "task description (injected as gateContext.task)").option(
10683
- "--skip-sub <names>",
10684
- "sub names to skip without gate eval (repeatable and/or comma-separated)",
10685
- (v, prev) => [...prev, v],
10686
- []
10687
- ).option("--context <json>", "JSON object merged over the default gate context").action(async (master, raw) => {
10688
- if (!VALID_MASTERS.has(master)) {
10689
- console.error(
10690
- `error: unknown master '${master}'. Expected one of: auto, discuss, plan, task, verify, ship.`
10691
- );
10692
- process.exit(1);
10693
- return;
10694
- }
10695
- try {
10696
- checkPathSafe(master);
10697
- } catch {
10698
- console.error("error: invalid master name (path traversal rejected)");
10699
- process.exit(1);
10700
- return;
10701
- }
10702
- const packageRoot = getAssetsRoot();
10703
- const yamlPath = resolveMasterYamlPath2(master, packageRoot);
10704
- let raw_yaml;
10705
- try {
10706
- raw_yaml = await readFile(yamlPath, "utf8");
10707
- } catch (err2) {
10708
- console.error(
10709
- `error: failed to read master workflow.yaml at ${yamlPath} \u2014 ${err2.message}`
10710
- );
10711
- process.exit(1);
10712
- return;
10713
- }
10714
- let parsed;
10715
- try {
10716
- parsed = parse(raw_yaml);
10717
- } catch (err2) {
10718
- console.error(`error: failed to parse ${yamlPath} \u2014 ${err2.message}`);
10719
- process.exit(1);
10720
- return;
10721
- }
10722
- const delegates = parsed?.delegates_to;
10723
- if (!Array.isArray(delegates) || delegates.length === 0) {
10724
- console.error(`error: master '${master}' workflow.yaml missing delegates_to[]`);
10725
- process.exit(1);
10726
- return;
10727
- }
10728
- const clauses = delegates;
10729
- const task = typeof raw.task === "string" ? raw.task : "";
10730
- const stage = master;
10731
- let ctx = buildDefaultGateContext(task, stage);
10732
- if (typeof raw.context === "string" && raw.context.length > 0) {
10733
- let extra;
10734
- try {
10735
- extra = JSON.parse(raw.context);
10736
- } catch (err2) {
10737
- console.error(`error: --context is not valid JSON \u2014 ${err2.message}`);
10738
- process.exit(1);
10739
- return;
10740
- }
10741
- if (extra && typeof extra === "object" && !Array.isArray(extra)) {
10742
- ctx = mergeGateContext(ctx, extra);
10743
- }
10744
- }
10745
- const skipSubs = new Set(
10746
- (Array.isArray(raw.skipSub) ? raw.skipSub : []).flatMap((v) => v.split(",")).map((s) => s.trim()).filter((s) => s.length > 0)
10747
- );
10748
- ctx.skip_subs = [...skipSubs];
10749
- const fire = [];
10750
- const skip = [];
10751
- const matchedSkips = /* @__PURE__ */ new Set();
10752
- for (const clause of clauses) {
10753
- const skipHit = matchSkipSub(skipSubs, clause.sub, master);
10754
- if (skipHit !== null) {
10755
- matchedSkips.add(skipHit);
10756
- skip.push({
10757
- sub: clause.sub,
10758
- reason: "skipped via skip_subs (done interactively in main session)"
10759
- });
10760
- continue;
10761
- }
10762
- if (!clause.gate) {
10763
- fire.push(fireEntry(clause, master));
10764
- continue;
10765
- }
10766
- try {
10767
- const passes = await resolveJudgmentGate(clause.gate, ctx, packageRoot);
10768
- if (passes) {
10769
- fire.push(fireEntry(clause, master));
10770
- } else {
10771
- skip.push({ sub: clause.sub, reason: `gate ${clause.gate} = false` });
10772
- }
10773
- } catch (e) {
10774
- if (isUndefinedVariableError(e)) {
10775
- console.warn(
10776
- `\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.`
10777
- );
10778
- skip.push({
10779
- sub: clause.sub,
10780
- reason: `gate ${clause.gate} misconfigured (undefined variable) \u2014 fail-closed, not fired`
10781
- });
10782
- } else {
10783
- console.warn(
10784
- `\u26A0\uFE0F master ${master} sub ${clause.sub} gate ${clause.gate} eval failed (${e.message}); firing sub as if gate=true (ADR 0029 fail-soft).`
10785
- );
10786
- fire.push(fireEntry(clause, master));
10787
- }
10788
- }
10789
- }
10790
- warnUnmatchedSkips(
10791
- skipSubs,
10792
- matchedSkips,
10793
- master,
10794
- clauses.map((c) => c.sub),
10795
- (m) => console.warn(m)
10796
- );
10797
- let parallelism = { escalate_to_teams: false, reason: null };
10798
- try {
10799
- const escalate = await resolveJudgmentGate(PARALLELISM_GATE, ctx, packageRoot);
10800
- parallelism = escalate ? { escalate_to_teams: true, reason: "agent-teams-upgrade gate fired" } : { escalate_to_teams: false, reason: null };
10801
- } catch {
10802
- parallelism = { escalate_to_teams: false, reason: null };
10803
- }
10804
- const result = { master, fire, skip, parallelism };
10805
- console.log(JSON.stringify(result, null, 2));
10806
- process.exit(0);
10807
- });
10808
- }
10809
- function fireEntry(clause, master) {
10810
- const isMaster = STAGE_MASTERS.has(clause.sub);
10811
- const sub = master !== "auto" && !isMaster ? `${master}-${clause.sub}` : clause.sub;
10812
- const entry = { sub };
10813
- if (clause.order !== void 0) entry.order = clause.order;
10814
- if (clause.mode !== void 0) entry.mode = clause.mode;
10815
- if (clause.gate !== void 0) entry.gate = clause.gate;
10816
- if (isMaster) entry.is_master = true;
10817
- return entry;
10818
- }
10819
-
10820
11393
  // src/cli.ts
11394
+ init_gates();
10821
11395
  init_gc();
10822
11396
 
10823
11397
  // src/cli/injectStateCmd.ts
@@ -12765,7 +13339,7 @@ var uninstallNpmCli = async (ctx) => {
12765
13339
  const m = install.cmd.match(/npm\s+(?:install|i)\s+(?:-g\s+)?(\S+)/);
12766
13340
  const pkg = m?.[1] ?? ctx.manifest.metadata.upstream.source;
12767
13341
  const isWin = process.platform === "win32";
12768
- const result = await new Promise((resolve19) => {
13342
+ const result = await new Promise((resolve21) => {
12769
13343
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], { windowsHide: true }) : spawn("npm", ["uninstall", "-g", pkg], { shell: false });
12770
13344
  let stderr = "";
12771
13345
  child.stderr?.setEncoding("utf8").on("data", (c) => {
@@ -12773,15 +13347,15 @@ var uninstallNpmCli = async (ctx) => {
12773
13347
  });
12774
13348
  const timer = setTimeout(() => {
12775
13349
  child.kill("SIGKILL");
12776
- resolve19({ exitCode: -1, stderr: `${stderr}[timeout]` });
13350
+ resolve21({ exitCode: -1, stderr: `${stderr}[timeout]` });
12777
13351
  }, 3e4);
12778
13352
  child.on("error", (e) => {
12779
13353
  clearTimeout(timer);
12780
- resolve19({ exitCode: -1, stderr: e.message });
13354
+ resolve21({ exitCode: -1, stderr: e.message });
12781
13355
  });
12782
13356
  child.on("close", (code) => {
12783
13357
  clearTimeout(timer);
12784
- resolve19({ exitCode: code ?? -1, stderr });
13358
+ resolve21({ exitCode: code ?? -1, stderr });
12785
13359
  });
12786
13360
  });
12787
13361
  if (result.exitCode !== 0) {
@@ -13277,6 +13851,7 @@ registerReleasePreflight(program);
13277
13851
  registerRetro(program);
13278
13852
  registerInjectState(program);
13279
13853
  registerStopHook(program);
13854
+ registerEval(program);
13280
13855
  var bare = parseBareInvocation(process.argv.slice(2));
13281
13856
  if (bare.here) {
13282
13857
  void runHere({ json: bare.json });