harnessed 4.22.0 → 4.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -3,7 +3,7 @@ import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync, readdir
3
3
  import { homedir } from 'os';
4
4
  import { join, resolve, dirname, sep, win32, relative } from 'path';
5
5
  import { Type } from '@sinclair/typebox';
6
- import { readFile, readdir, unlink, writeFile, stat, rm, cp, mkdir, rename, access, appendFile } from 'fs/promises';
6
+ import { readFile, readdir, unlink, writeFile, stat, rm, cp, mkdir, access, rename, appendFile } from 'fs/promises';
7
7
  import { Value } from '@sinclair/typebox/value';
8
8
  import lockfile from 'proper-lockfile';
9
9
  import { parse, LineCounter, parseDocument, isSeq, isScalar } from 'yaml';
@@ -38,7 +38,7 @@ var init_package = __esm({
38
38
  "package.json"() {
39
39
  package_default = {
40
40
  name: "harnessed",
41
- version: "4.22.0",
41
+ version: "4.23.0",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -1204,7 +1204,11 @@ var init_gitCloneWithSetup = __esm({
1204
1204
  env: Type.Optional(Type.Record(Type.String(), Type.String())),
1205
1205
  args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
1206
1206
  git_ref: Type.String({ minLength: 1, pattern: GIT_REF_PATTERN2 }),
1207
- idempotent_check: Type.String({ minLength: 1 })
1207
+ idempotent_check: Type.String({ minLength: 1 }),
1208
+ // 4.23.0 (issue #3 req 5) — skill names this pack copies into the flat
1209
+ // ~/.claude/skills namespace; enables pre-install collision warnings against
1210
+ // shipped workflow names + post-install undeclared-name drift detection.
1211
+ installs_skills: Type.Optional(Type.Array(Type.String({ minLength: 1 })))
1208
1212
  },
1209
1213
  { additionalProperties: false }
1210
1214
  );
@@ -1255,7 +1259,11 @@ var init_npmCli = __esm({
1255
1259
  env: Type.Optional(Type.Record(Type.String(), Type.String())),
1256
1260
  args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
1257
1261
  npm_version: Type.String({ minLength: 1 }),
1258
- idempotent_check: Type.String({ minLength: 1 })
1262
+ idempotent_check: Type.String({ minLength: 1 }),
1263
+ // 4.23.0 (issue #3 req 5) — skill names this pack copies into the flat
1264
+ // ~/.claude/skills namespace; enables pre-install collision warnings against
1265
+ // shipped workflow names + post-install undeclared-name drift detection.
1266
+ installs_skills: Type.Optional(Type.Array(Type.String({ minLength: 1 })))
1259
1267
  },
1260
1268
  { additionalProperties: false }
1261
1269
  );
@@ -1272,7 +1280,11 @@ var init_npxSkillInstaller = __esm({
1272
1280
  env: Type.Optional(Type.Record(Type.String(), Type.String())),
1273
1281
  args: Type.Optional(Type.Record(Type.String(), Type.Unknown())),
1274
1282
  npm_version: Type.String({ minLength: 1 }),
1275
- idempotent_check: Type.String({ minLength: 1 })
1283
+ idempotent_check: Type.String({ minLength: 1 }),
1284
+ // 4.23.0 (issue #3 req 5) — skill names this pack copies into the flat
1285
+ // ~/.claude/skills namespace; enables pre-install collision warnings against
1286
+ // shipped workflow names + post-install undeclared-name drift detection.
1287
+ installs_skills: Type.Optional(Type.Array(Type.String({ minLength: 1 })))
1276
1288
  },
1277
1289
  { additionalProperties: false }
1278
1290
  );
@@ -2290,6 +2302,421 @@ var init_engineHook = __esm({
2290
2302
  init_template();
2291
2303
  }
2292
2304
  });
2305
+ function getUserClaudeJsonPath() {
2306
+ return getMcpConfigPath();
2307
+ }
2308
+ async function readUserClaudeJson() {
2309
+ const path = getUserClaudeJsonPath();
2310
+ let raw;
2311
+ try {
2312
+ raw = await readFile(path, "utf8");
2313
+ } catch (err2) {
2314
+ if (err2.code === "ENOENT") return {};
2315
+ throw err2;
2316
+ }
2317
+ try {
2318
+ const parsed = JSON.parse(raw);
2319
+ if (parsed === null || typeof parsed !== "object") return {};
2320
+ return parsed;
2321
+ } catch {
2322
+ return {};
2323
+ }
2324
+ }
2325
+ function isMcpServerInToml(raw, name) {
2326
+ const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2327
+ const re = new RegExp(`^\\s*\\[mcp_servers\\.(?:${esc}|"${esc}"|'${esc}')(?:\\]|\\.)`, "m");
2328
+ return re.test(raw);
2329
+ }
2330
+ async function isMcpServerRegistered(name) {
2331
+ const platform = detectPlatform();
2332
+ if (platform.id === "codex") {
2333
+ let raw;
2334
+ try {
2335
+ raw = await readFile(platform.mcpConfigPath, "utf8");
2336
+ } catch (err2) {
2337
+ if (err2.code === "ENOENT") return false;
2338
+ throw err2;
2339
+ }
2340
+ return isMcpServerInToml(raw, name);
2341
+ }
2342
+ const config = await readUserClaudeJson();
2343
+ const servers = config.mcpServers;
2344
+ if (!servers || typeof servers !== "object") return false;
2345
+ return Object.hasOwn(servers, name);
2346
+ }
2347
+ async function isPluginRegistered(pluginName) {
2348
+ const registryPath = getPluginsRegistry();
2349
+ if (registryPath !== null) {
2350
+ try {
2351
+ const raw = await readFile(registryPath, "utf8");
2352
+ const parsed = JSON.parse(raw);
2353
+ const plugins = parsed.plugins;
2354
+ if (plugins && typeof plugins === "object") {
2355
+ if (Object.hasOwn(plugins, pluginName)) return true;
2356
+ if (Object.keys(plugins).some((k) => k.split("@")[0] === pluginName)) return true;
2357
+ }
2358
+ } catch {
2359
+ }
2360
+ }
2361
+ for (const path of [getSettingsPath(), getMcpConfigPath()]) {
2362
+ try {
2363
+ const raw = await readFile(path, "utf8");
2364
+ const parsed = JSON.parse(raw);
2365
+ const plugins = parsed.enabledPlugins;
2366
+ if (plugins && typeof plugins === "object") {
2367
+ if (Object.hasOwn(plugins, pluginName)) return true;
2368
+ if (Object.keys(plugins).some((k) => k.split("@")[0] === pluginName)) return true;
2369
+ }
2370
+ } catch {
2371
+ }
2372
+ }
2373
+ return false;
2374
+ }
2375
+ var init_readClaudeConfig = __esm({
2376
+ "src/installers/lib/readClaudeConfig.ts"() {
2377
+ init_platform();
2378
+ }
2379
+ });
2380
+ async function mergeSettingsEnvKey(key, value, opts = {}) {
2381
+ const path = getSettingsPath();
2382
+ let raw;
2383
+ try {
2384
+ raw = await readFile(path, "utf8");
2385
+ } catch (err2) {
2386
+ const code = err2.code;
2387
+ if (code !== "ENOENT") {
2388
+ return { outcome: "warn", message: `read ${path} failed: ${err2.message}` };
2389
+ }
2390
+ return createFresh(path, key, value);
2391
+ }
2392
+ let data;
2393
+ try {
2394
+ const parsed = JSON.parse(raw);
2395
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
2396
+ return { outcome: "warn", message: `${path} is not a JSON object` };
2397
+ }
2398
+ data = parsed;
2399
+ } catch (err2) {
2400
+ return { outcome: "warn", message: `${path} malformed JSON: ${err2.message}` };
2401
+ }
2402
+ const env = data.env ?? {};
2403
+ const existing = env[key];
2404
+ if (typeof existing === "string" && existing.length > 0 && opts.skipIfPresent?.(existing) === true) {
2405
+ return { outcome: "already", path, existing };
2406
+ }
2407
+ const backup2 = await backupOriginal(raw);
2408
+ if (backup2.status === "warn") return { outcome: "warn", message: backup2.message };
2409
+ data.env = { ...env, [key]: value };
2410
+ const writeErr = await atomicWrite(path, `${JSON.stringify(data, null, 2)}
2411
+ `);
2412
+ if (writeErr) return { outcome: "warn", message: writeErr };
2413
+ return { outcome: "merged", path, backupPath: backup2.path };
2414
+ }
2415
+ async function createFresh(path, key, value) {
2416
+ const data = { env: { [key]: value } };
2417
+ try {
2418
+ await mkdir(dirname(path), { recursive: true });
2419
+ } catch (err2) {
2420
+ return { outcome: "warn", message: `mkdir ~/.claude failed: ${err2.message}` };
2421
+ }
2422
+ const writeErr = await atomicWrite(path, `${JSON.stringify(data, null, 2)}
2423
+ `);
2424
+ if (writeErr) return { outcome: "warn", message: writeErr };
2425
+ return { outcome: "created", path };
2426
+ }
2427
+ async function backupOriginal(raw) {
2428
+ const backupRoot = harnessedSubdir("backups");
2429
+ const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-");
2430
+ const backupPath = join(backupRoot, `settings.json.${ts}.bak`);
2431
+ try {
2432
+ await mkdir(backupRoot, { recursive: true });
2433
+ await writeFile(backupPath, raw, "utf8");
2434
+ return { status: "ok", path: backupPath };
2435
+ } catch (err2) {
2436
+ return { status: "warn", message: `backup ${backupPath} failed: ${err2.message}` };
2437
+ }
2438
+ }
2439
+ async function atomicWrite(path, content) {
2440
+ const tmpPath = `${path}.tmp-${process.pid}-${Date.now()}`;
2441
+ try {
2442
+ await writeFile(tmpPath, content, "utf8");
2443
+ await rename(tmpPath, path);
2444
+ return void 0;
2445
+ } catch (err2) {
2446
+ return `write ${path} failed: ${err2.message}`;
2447
+ }
2448
+ }
2449
+ var init_settingsWriter = __esm({
2450
+ "src/cli/lib/settingsWriter.ts"() {
2451
+ init_harnessedRoot();
2452
+ init_platform();
2453
+ }
2454
+ });
2455
+
2456
+ // src/cli/lib/guard-exemption.ts
2457
+ var guard_exemption_exports = {};
2458
+ __export(guard_exemption_exports, {
2459
+ ECC_UPGRADE_CMD: () => ECC_UPGRADE_CMD,
2460
+ EXEMPT_ENV_KEY: () => EXEMPT_ENV_KEY,
2461
+ MANUAL_FIX_CMD: () => MANUAL_FIX_CMD,
2462
+ PLANNING_GLOB: () => PLANNING_GLOB,
2463
+ applyEnvExemption: () => applyEnvExemption,
2464
+ planEnvExemption: () => planEnvExemption,
2465
+ previewLines: () => previewLines,
2466
+ probeExemptCapability: () => probeExemptCapability,
2467
+ readCurrentEnvValue: () => readCurrentEnvValue,
2468
+ refusalLines: () => refusalLines,
2469
+ runExemptionFlow: () => runExemptionFlow,
2470
+ splitGlobs: () => splitGlobs,
2471
+ upgradeAdviceLines: () => upgradeAdviceLines
2472
+ });
2473
+ function defaultProbeDeps() {
2474
+ return {
2475
+ registryPath: () => getPluginsRegistry(),
2476
+ readFile: (p7) => readFile(p7, "utf8")
2477
+ };
2478
+ }
2479
+ async function probeExemptCapability(deps = {}) {
2480
+ const d = { ...defaultProbeDeps(), ...deps };
2481
+ try {
2482
+ const registry = d.registryPath();
2483
+ if (registry === null) return "legacy";
2484
+ const parsed = JSON.parse(await d.readFile(registry));
2485
+ const plugins = parsed.plugins ?? {};
2486
+ for (const key of Object.keys(plugins)) {
2487
+ if (key.split("@")[0] !== "ecc") continue;
2488
+ for (const entry of plugins[key] ?? []) {
2489
+ if (!entry.installPath) continue;
2490
+ const hook = join(entry.installPath, "scripts", "hooks", "gateguard-fact-force.js");
2491
+ try {
2492
+ if ((await d.readFile(hook)).includes(EXEMPT_ENV_KEY)) return "env-supported";
2493
+ } catch {
2494
+ }
2495
+ }
2496
+ }
2497
+ return "legacy";
2498
+ } catch {
2499
+ return "legacy";
2500
+ }
2501
+ }
2502
+ function splitGlobs(value) {
2503
+ return (value ?? "").split(",").map((t2) => t2.trim()).filter((t2) => t2.length > 0);
2504
+ }
2505
+ function planEnvExemption(existing) {
2506
+ const globs = splitGlobs(existing);
2507
+ if (globs.includes(PLANNING_GLOB)) return { action: "skip" };
2508
+ return { action: "set", value: [...globs, PLANNING_GLOB].join(",") };
2509
+ }
2510
+ async function readCurrentEnvValue(deps = {}) {
2511
+ const readSettings = deps.readSettings ?? (async () => {
2512
+ try {
2513
+ return await readFile(getSettingsPath(), "utf8");
2514
+ } catch {
2515
+ return null;
2516
+ }
2517
+ });
2518
+ try {
2519
+ const raw = await readSettings();
2520
+ if (raw === null) return void 0;
2521
+ const parsed = JSON.parse(raw);
2522
+ const v = parsed.env?.[EXEMPT_ENV_KEY];
2523
+ return typeof v === "string" && v.length > 0 ? v : void 0;
2524
+ } catch {
2525
+ return void 0;
2526
+ }
2527
+ }
2528
+ async function applyEnvExemption(value) {
2529
+ return mergeSettingsEnvKey(EXEMPT_ENV_KEY, value, {
2530
+ skipIfPresent: (existing) => splitGlobs(existing).includes(PLANNING_GLOB)
2531
+ });
2532
+ }
2533
+ function previewLines(existing, newValue) {
2534
+ const change = existing === void 0 ? ` + env.${EXEMPT_ENV_KEY} = "${newValue}"` : ` ~ env.${EXEMPT_ENV_KEY}: "${existing}" \u2192 "${newValue}"`;
2535
+ return [
2536
+ `[harnessed] GateGuard \u2194 evidence-guard conflict \u2014 sanctioned fix available:`,
2537
+ ` file: ${getSettingsPath()}`,
2538
+ change,
2539
+ ` backup: settings.json.<timestamp>.bak under the harnessed backups dir (written first)`
2540
+ ];
2541
+ }
2542
+ function refusalLines() {
2543
+ return [
2544
+ "",
2545
+ "\u26A0\uFE0F GateGuard exemption NOT applied \u2014 the dual-guard conflict remains:",
2546
+ " \u2022 verify-stage artifacts (code-review-report.md, qa-report.md, security-audit-report.md,",
2547
+ " paranoid-review-report.md, multispec-review-report.md) will be blocked at Write",
2548
+ " \u2022 subagents have no fact-retry channel \u2014 they will rename artifacts and every",
2549
+ " `checkpoint complete` will fail-closed block on the missing contract names",
2550
+ ` \u2022 fix anytime: \`${MANUAL_FIX_CMD}\` (or set ${EXEMPT_ENV_KEY}="${PLANNING_GLOB}" in your`,
2551
+ " harness settings env yourself)",
2552
+ " harnessed doctor will keep warning until this is resolved.",
2553
+ ""
2554
+ ];
2555
+ }
2556
+ function upgradeAdviceLines() {
2557
+ return [
2558
+ `[harnessed] your installed ecc GateGuard predates ${EXEMPT_ENV_KEY} exemption support.`,
2559
+ ` upgrade first: \`${ECC_UPGRADE_CMD}\` (restart required), then re-run \`${MANUAL_FIX_CMD}\`.`,
2560
+ " interim: set ECC_GATEGUARD=off for harnessed-orchestrated sessions."
2561
+ ];
2562
+ }
2563
+ async function runExemptionFlow(deps = {}) {
2564
+ const d = {
2565
+ probe: () => probeExemptCapability(),
2566
+ readEnvValue: () => readCurrentEnvValue(),
2567
+ merge: (value) => applyEnvExemption(value),
2568
+ supportsEnvWrite: () => detectPlatform().supportsEnvKeyWrite,
2569
+ print: (line) => console.error(line),
2570
+ ...deps
2571
+ };
2572
+ try {
2573
+ if (await d.probe() !== "env-supported") return "not-capable";
2574
+ if (!d.supportsEnvWrite()) {
2575
+ d.print(
2576
+ `[harnessed] this platform's config is not JSON-env writable \u2014 export ${EXEMPT_ENV_KEY}="${PLANNING_GLOB}" in your shell environment instead.`
2577
+ );
2578
+ return "unsupported-platform";
2579
+ }
2580
+ const existing = await d.readEnvValue();
2581
+ const plan = planEnvExemption(existing);
2582
+ if (plan.action === "skip") return "already";
2583
+ for (const line of previewLines(existing, plan.value ?? "")) d.print(line);
2584
+ if (!d.confirm) {
2585
+ d.print(` non-interactive session \u2014 run \`${MANUAL_FIX_CMD}\` to apply this fix.`);
2586
+ return "advised";
2587
+ }
2588
+ const yes = await d.confirm();
2589
+ if (!yes) {
2590
+ for (const line of refusalLines()) d.print(line);
2591
+ return "declined";
2592
+ }
2593
+ const r = await d.merge(plan.value ?? "");
2594
+ if (r.outcome === "created" || r.outcome === "merged") {
2595
+ const backup2 = r.outcome === "merged" ? ` (backup: ${r.backupPath})` : "";
2596
+ d.print(
2597
+ `\u2713 [harnessed] set ${EXEMPT_ENV_KEY}="${plan.value}" in ${r.path}${backup2} \u2014 restart the harness session to pick it up.`
2598
+ );
2599
+ return "applied";
2600
+ }
2601
+ if (r.outcome === "already") return "already";
2602
+ d.print(`\u26A0\uFE0F [harnessed] exemption failed: ${r.message} \u2014 apply manually: \`${MANUAL_FIX_CMD}\``);
2603
+ return "error";
2604
+ } catch (err2) {
2605
+ d.print(`\u26A0\uFE0F [harnessed] exemption flow error: ${err2.message}`);
2606
+ return "error";
2607
+ }
2608
+ }
2609
+ var PLANNING_GLOB, MANUAL_FIX_CMD, EXEMPT_ENV_KEY, ECC_UPGRADE_CMD;
2610
+ var init_guard_exemption = __esm({
2611
+ "src/cli/lib/guard-exemption.ts"() {
2612
+ init_platform();
2613
+ init_settingsWriter();
2614
+ PLANNING_GLOB = ".planning/**";
2615
+ MANUAL_FIX_CMD = "harnessed exempt-gateguard";
2616
+ EXEMPT_ENV_KEY = "GATEGUARD_EXEMPT_GLOBS";
2617
+ ECC_UPGRADE_CMD = "claude plugin update ecc";
2618
+ }
2619
+ });
2620
+
2621
+ // src/cli/lib/check-guard-conflict.ts
2622
+ var check_guard_conflict_exports = {};
2623
+ __export(check_guard_conflict_exports, {
2624
+ GUARD_CONFLICT_ADVICE: () => GUARD_CONFLICT_ADVICE,
2625
+ checkGuardConflict: () => checkGuardConflict,
2626
+ detectGateGuardActive: () => detectGateGuardActive
2627
+ });
2628
+ function defaultDeps() {
2629
+ return {
2630
+ env: process.env,
2631
+ readSettings: async () => {
2632
+ try {
2633
+ return await readFile(getSettingsPath(), "utf8");
2634
+ } catch {
2635
+ return null;
2636
+ }
2637
+ },
2638
+ eccPluginInstalled: async () => {
2639
+ try {
2640
+ return await isPluginRegistered("ecc");
2641
+ } catch {
2642
+ return false;
2643
+ }
2644
+ }
2645
+ };
2646
+ }
2647
+ async function detectGateGuardActive(deps = {}) {
2648
+ const d = { ...defaultDeps(), ...deps };
2649
+ try {
2650
+ const disabled = (d.env.GATEGUARD_DISABLED ?? "").trim() === "1";
2651
+ const eccEnv = (d.env.ECC_GATEGUARD ?? "").trim().toLowerCase();
2652
+ if (disabled || DISABLE_VALUES.has(eccEnv)) return { active: false, source: null };
2653
+ if (eccEnv.length > 0) return { active: true, source: "env" };
2654
+ const settings = await d.readSettings();
2655
+ if (settings !== null && /gateguard/i.test(settings)) {
2656
+ return { active: true, source: "settings-hooks" };
2657
+ }
2658
+ if (await d.eccPluginInstalled()) return { active: true, source: "ecc-plugin" };
2659
+ return { active: false, source: null };
2660
+ } catch {
2661
+ return { active: false, source: null };
2662
+ }
2663
+ }
2664
+ async function defaultExemptionProbe() {
2665
+ const { probeExemptCapability: probeExemptCapability2, readCurrentEnvValue: readCurrentEnvValue2 } = await Promise.resolve().then(() => (init_guard_exemption(), guard_exemption_exports));
2666
+ return {
2667
+ capability: () => probeExemptCapability2(),
2668
+ currentValue: () => readCurrentEnvValue2()
2669
+ };
2670
+ }
2671
+ async function checkGuardConflict(deps = {}, exemption) {
2672
+ const d = { ...defaultDeps(), ...deps };
2673
+ const det = await detectGateGuardActive(deps);
2674
+ if (!det.active) {
2675
+ return {
2676
+ name: "guard conflict (GateGuard)",
2677
+ status: "pass",
2678
+ message: "ECC GateGuard not detected \u2014 no dual-guard filename conflict"
2679
+ };
2680
+ }
2681
+ try {
2682
+ const probe = exemption ?? await defaultExemptionProbe();
2683
+ const { PLANNING_GLOB: PLANNING_GLOB2, splitGlobs: splitGlobs2 } = await Promise.resolve().then(() => (init_guard_exemption(), guard_exemption_exports));
2684
+ const persisted = await probe.currentValue();
2685
+ const live = d.env.GATEGUARD_EXEMPT_GLOBS;
2686
+ if (splitGlobs2(persisted).includes(PLANNING_GLOB2) || splitGlobs2(live).includes(PLANNING_GLOB2)) {
2687
+ return {
2688
+ name: "guard conflict (GateGuard)",
2689
+ status: "pass",
2690
+ message: "GateGuard active but .planning/** is exempted via GATEGUARD_EXEMPT_GLOBS \u2014 conflict resolved"
2691
+ };
2692
+ }
2693
+ if (await probe.capability() === "env-supported") {
2694
+ return {
2695
+ name: "guard conflict (GateGuard)",
2696
+ status: "warn",
2697
+ message: `ECC GateGuard appears active (via ${det.source}) \u2014 its fact-forcing policy collides with harnessed evidence-guard artifact names (findings.md, *-report.md); a sanctioned env exemption is available (GATEGUARD_EXEMPT_GLOBS)`,
2698
+ fix: GUARD_CONFLICT_ADVICE,
2699
+ install_commands: ["harnessed exempt-gateguard"]
2700
+ };
2701
+ }
2702
+ } catch {
2703
+ }
2704
+ return {
2705
+ name: "guard conflict (GateGuard)",
2706
+ status: "warn",
2707
+ message: `ECC GateGuard appears active (via ${det.source}) \u2014 its filename policy (blocks report/findings/summary/analysis Writes) collides with harnessed evidence-guard artifact names (findings.md, *-report.md); this ecc version predates the GATEGUARD_EXEMPT_GLOBS exemption surface`,
2708
+ fix: "upgrade ecc first: `claude plugin update ecc` (restart required), then run `harnessed exempt-gateguard` to persist the .planning/** exemption; interim: set ECC_GATEGUARD=off for harnessed-orchestrated sessions; do NOT blanket `checkpoint complete --force` \u2014 that silently voids the evidence guard."
2709
+ };
2710
+ }
2711
+ var DISABLE_VALUES, GUARD_CONFLICT_ADVICE;
2712
+ var init_check_guard_conflict = __esm({
2713
+ "src/cli/lib/check-guard-conflict.ts"() {
2714
+ init_platform();
2715
+ init_readClaudeConfig();
2716
+ DISABLE_VALUES = /* @__PURE__ */ new Set(["off", "0", "false", "disabled"]);
2717
+ GUARD_CONFLICT_ADVICE = 'options (best first): (1) run `harnessed exempt-gateguard` \u2014 persists GATEGUARD_EXEMPT_GLOBS=".planning/**" into the harness settings env (backed up first; planning dirs are the legitimate home of findings.md/*-report.md); (2) if your ecc predates GATEGUARD_EXEMPT_GLOBS support, upgrade first: `claude plugin update ecc`; (3) interim: set ECC_GATEGUARD=off for harnessed-orchestrated sessions; do NOT blanket `checkpoint complete --force` \u2014 that silently voids the evidence guard.';
2718
+ }
2719
+ });
2293
2720
 
2294
2721
  // src/workflow/interpolate.ts
2295
2722
  function interpolate(template, vars) {
@@ -4336,20 +4763,47 @@ async function checkArtifacts(sub, packageRoot) {
4336
4763
  const found = [];
4337
4764
  const missing = [];
4338
4765
  for (const rel of declared) {
4339
- const abs = resolve(cwd, rel);
4340
- const present = await stat(abs).then((s) => s.isFile()).catch(() => false);
4341
- if (present) found.push({ path: abs, sha256: await hashFile(abs) });
4766
+ const abs = await resolveDeclaredArtifact(cwd, rel);
4767
+ if (abs) found.push({ path: abs, sha256: await hashFile(abs) });
4342
4768
  else missing.push(rel);
4343
4769
  }
4344
4770
  return { status: missing.length === 0 ? "verified" : "missing", found, missing };
4345
4771
  }
4346
- async function checkPlanningSync(cwd, _workflowState) {
4347
- const planningDir = resolve(cwd, ".planning");
4348
- const hasPlanningDir = await stat(planningDir).then((s) => s.isDirectory()).catch(() => false);
4349
- if (!hasPlanningDir) return { status: "none_declared", missing: [] };
4350
- const stateFile = resolve(cwd, ".planning", "STATE.md");
4351
- const hasStateFile = await stat(stateFile).then((s) => s.isFile()).catch(() => false);
4352
- if (!hasStateFile) return { status: "missing", missing: [".planning/STATE.md"] };
4772
+ async function resolveDeclaredArtifact(cwd, rel) {
4773
+ const isFileAt = (p7) => stat(p7).then((s) => s.isFile()).catch(() => false);
4774
+ if (/[\\/]/.test(rel)) {
4775
+ const abs = resolve(cwd, rel);
4776
+ return await isFileAt(abs) ? abs : null;
4777
+ }
4778
+ const atRoot = resolve(cwd, rel);
4779
+ if (await isFileAt(atRoot)) return atRoot;
4780
+ for (const base of [resolve(cwd, ".planning", "phases"), resolve(cwd, ".planning")]) {
4781
+ let entries;
4782
+ try {
4783
+ entries = await readdir(base);
4784
+ } catch {
4785
+ continue;
4786
+ }
4787
+ let best = null;
4788
+ for (const entry of entries) {
4789
+ if (base.endsWith(".planning") && entry === "phases") continue;
4790
+ const cand = resolve(base, entry, rel);
4791
+ const st = await stat(cand).catch(() => null);
4792
+ if (st?.isFile() && (!best || st.mtimeMs > best.mtime)) {
4793
+ best = { abs: cand, mtime: st.mtimeMs };
4794
+ }
4795
+ }
4796
+ if (best) return best.abs;
4797
+ }
4798
+ return null;
4799
+ }
4800
+ async function checkPlanningSync(cwd, _workflowState) {
4801
+ const planningDir = resolve(cwd, ".planning");
4802
+ const hasPlanningDir = await stat(planningDir).then((s) => s.isDirectory()).catch(() => false);
4803
+ if (!hasPlanningDir) return { status: "none_declared", missing: [] };
4804
+ const stateFile = resolve(cwd, ".planning", "STATE.md");
4805
+ const hasStateFile = await stat(stateFile).then((s) => s.isFile()).catch(() => false);
4806
+ if (!hasStateFile) return { status: "missing", missing: [".planning/STATE.md"] };
4353
4807
  return { status: "verified", missing: [] };
4354
4808
  }
4355
4809
  async function detectDrift(evidence) {
@@ -4681,7 +5135,7 @@ function realExists(p7) {
4681
5135
  return false;
4682
5136
  }
4683
5137
  }
4684
- function defaultDeps() {
5138
+ function defaultDeps2() {
4685
5139
  return {
4686
5140
  platform: process.platform,
4687
5141
  env: process.env,
@@ -4692,7 +5146,7 @@ function defaultDeps() {
4692
5146
  }
4693
5147
  function resolveBash(deps) {
4694
5148
  if (cache2) return cache2;
4695
- cache2 = compute({ ...defaultDeps(), ...deps });
5149
+ cache2 = compute({ ...defaultDeps2(), ...deps });
4696
5150
  return cache2;
4697
5151
  }
4698
5152
  function compute(d) {
@@ -4712,8 +5166,8 @@ function compute(d) {
4712
5166
  }
4713
5167
  const gitFirst = d.where("git")[0];
4714
5168
  if (gitFirst && /git\.exe$/i.test(gitFirst)) {
4715
- const root = dirname8(dirname8(gitFirst));
4716
- for (const cand of [join19(root, "bin", "bash.exe"), join19(root, "usr", "bin", "bash.exe")]) {
5169
+ const root = dirname9(dirname9(gitFirst));
5170
+ for (const cand of [join21(root, "bin", "bash.exe"), join21(root, "usr", "bin", "bash.exe")]) {
4717
5171
  if (d.exists(cand) && usable(cand)) return { path: cand, source: "git-derived", wslOnPath };
4718
5172
  }
4719
5173
  }
@@ -4721,13 +5175,13 @@ function compute(d) {
4721
5175
  d.env.ProgramFiles,
4722
5176
  d.env.ProgramW6432,
4723
5177
  d.env["ProgramFiles(x86)"],
4724
- d.env.LOCALAPPDATA ? join19(d.env.LOCALAPPDATA, "Programs") : void 0
5178
+ d.env.LOCALAPPDATA ? join21(d.env.LOCALAPPDATA, "Programs") : void 0
4725
5179
  ];
4726
5180
  for (const base of bases) {
4727
5181
  if (!base) continue;
4728
5182
  for (const cand of [
4729
- join19(base, "Git", "bin", "bash.exe"),
4730
- join19(base, "Git", "usr", "bin", "bash.exe")
5183
+ join21(base, "Git", "bin", "bash.exe"),
5184
+ join21(base, "Git", "usr", "bin", "bash.exe")
4731
5185
  ]) {
4732
5186
  if (d.exists(cand) && usable(cand))
4733
5187
  return { path: cand, source: "standard-location", wslOnPath };
@@ -4740,10 +5194,10 @@ function compute(d) {
4740
5194
  }
4741
5195
  return { path: "bash", source: "path-fallback" };
4742
5196
  }
4743
- var dirname8, join19, WSL_STUB_RE, cache2;
5197
+ var dirname9, join21, WSL_STUB_RE, cache2;
4744
5198
  var init_resolveBash = __esm({
4745
5199
  "src/installers/lib/resolveBash.ts"() {
4746
- ({ dirname: dirname8, join: join19 } = win32);
5200
+ ({ dirname: dirname9, join: join21 } = win32);
4747
5201
  WSL_STUB_RE = /[\\/](windows[\\/](system32|sysnative|syswow64)|microsoft[\\/]windowsapps)[\\/]bash\.exe$/i;
4748
5202
  cache2 = null;
4749
5203
  }
@@ -5302,81 +5756,6 @@ var init_check_mattpocock_skills = __esm({
5302
5756
  REMEDIATION2 = "install via `npx skills@latest add mattpocock/skills` (or git clone https://github.com/mattpocock/skills ~/.claude/skills/mattpocock-skills); methodology fallback already inline in role-prompts.yaml per v3.6.0 Phase 1 \u2014 install is optional but enables /grill-with-docs /tdd /diagnosing-bugs etc. SlashCommand acceleration";
5303
5757
  }
5304
5758
  });
5305
- function getUserClaudeJsonPath() {
5306
- return getMcpConfigPath();
5307
- }
5308
- async function readUserClaudeJson() {
5309
- const path = getUserClaudeJsonPath();
5310
- let raw;
5311
- try {
5312
- raw = await readFile(path, "utf8");
5313
- } catch (err2) {
5314
- if (err2.code === "ENOENT") return {};
5315
- throw err2;
5316
- }
5317
- try {
5318
- const parsed = JSON.parse(raw);
5319
- if (parsed === null || typeof parsed !== "object") return {};
5320
- return parsed;
5321
- } catch {
5322
- return {};
5323
- }
5324
- }
5325
- function isMcpServerInToml(raw, name) {
5326
- const esc = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
5327
- const re = new RegExp(`^\\s*\\[mcp_servers\\.(?:${esc}|"${esc}"|'${esc}')(?:\\]|\\.)`, "m");
5328
- return re.test(raw);
5329
- }
5330
- async function isMcpServerRegistered(name) {
5331
- const platform = detectPlatform();
5332
- if (platform.id === "codex") {
5333
- let raw;
5334
- try {
5335
- raw = await readFile(platform.mcpConfigPath, "utf8");
5336
- } catch (err2) {
5337
- if (err2.code === "ENOENT") return false;
5338
- throw err2;
5339
- }
5340
- return isMcpServerInToml(raw, name);
5341
- }
5342
- const config = await readUserClaudeJson();
5343
- const servers = config.mcpServers;
5344
- if (!servers || typeof servers !== "object") return false;
5345
- return Object.hasOwn(servers, name);
5346
- }
5347
- async function isPluginRegistered(pluginName) {
5348
- const registryPath = getPluginsRegistry();
5349
- if (registryPath !== null) {
5350
- try {
5351
- const raw = await readFile(registryPath, "utf8");
5352
- const parsed = JSON.parse(raw);
5353
- const plugins = parsed.plugins;
5354
- if (plugins && typeof plugins === "object") {
5355
- if (Object.hasOwn(plugins, pluginName)) return true;
5356
- if (Object.keys(plugins).some((k) => k.split("@")[0] === pluginName)) return true;
5357
- }
5358
- } catch {
5359
- }
5360
- }
5361
- for (const path of [getSettingsPath(), getMcpConfigPath()]) {
5362
- try {
5363
- const raw = await readFile(path, "utf8");
5364
- const parsed = JSON.parse(raw);
5365
- const plugins = parsed.enabledPlugins;
5366
- if (plugins && typeof plugins === "object") {
5367
- if (Object.hasOwn(plugins, pluginName)) return true;
5368
- if (Object.keys(plugins).some((k) => k.split("@")[0] === pluginName)) return true;
5369
- }
5370
- } catch {
5371
- }
5372
- }
5373
- return false;
5374
- }
5375
- var init_readClaudeConfig = __esm({
5376
- "src/installers/lib/readClaudeConfig.ts"() {
5377
- init_platform();
5378
- }
5379
- });
5380
5759
 
5381
5760
  // src/cli/lib/check-mcp-availability.ts
5382
5761
  var check_mcp_availability_exports = {};
@@ -5509,6 +5888,264 @@ var init_check_bun = __esm({
5509
5888
  "src/cli/lib/check-bun.ts"() {
5510
5889
  }
5511
5890
  });
5891
+ async function scanWorkflowsNested(workflowsDir, entries) {
5892
+ const workflows = [];
5893
+ for (const entry of entries.sort()) {
5894
+ if (NON_WORKFLOW_DIRS.has(entry)) continue;
5895
+ const src = join(workflowsDir, entry);
5896
+ let s;
5897
+ try {
5898
+ s = await stat(src);
5899
+ } catch {
5900
+ continue;
5901
+ }
5902
+ if (!s.isDirectory()) continue;
5903
+ let hasFlatSkill = false;
5904
+ try {
5905
+ await stat(join(src, "SKILL.md"));
5906
+ hasFlatSkill = true;
5907
+ } catch {
5908
+ hasFlatSkill = false;
5909
+ }
5910
+ if (hasFlatSkill) {
5911
+ if (FLAT_LEGACY_KEEP.has(entry)) {
5912
+ workflows.push({ name: entry, relPath: entry, isMaster: FLAT_TOP_LEVEL_MASTERS.has(entry) });
5913
+ continue;
5914
+ }
5915
+ workflows.push({ name: entry, relPath: entry, isMaster: false });
5916
+ continue;
5917
+ }
5918
+ let subEntries;
5919
+ try {
5920
+ subEntries = await readdir(src);
5921
+ } catch {
5922
+ continue;
5923
+ }
5924
+ for (const sub of subEntries.sort()) {
5925
+ const subDir = join(src, sub);
5926
+ let ss;
5927
+ try {
5928
+ ss = await stat(subDir);
5929
+ } catch {
5930
+ continue;
5931
+ }
5932
+ if (!ss.isDirectory()) continue;
5933
+ try {
5934
+ await stat(join(subDir, "SKILL.md"));
5935
+ } catch {
5936
+ continue;
5937
+ }
5938
+ const name = sub === "auto" ? entry : `${entry}-${sub}`;
5939
+ workflows.push({ name, relPath: `${entry}/${sub}`, isMaster: sub === "auto" });
5940
+ }
5941
+ }
5942
+ return { workflows };
5943
+ }
5944
+ var FLAT_LEGACY_KEEP, FLAT_TOP_LEVEL_MASTERS, NON_WORKFLOW_DIRS;
5945
+ var init_scan_nested = __esm({
5946
+ "src/cli/lib/scan-nested.ts"() {
5947
+ FLAT_LEGACY_KEEP = /* @__PURE__ */ new Set(["research", "retro", "auto"]);
5948
+ FLAT_TOP_LEVEL_MASTERS = /* @__PURE__ */ new Set(["auto"]);
5949
+ NON_WORKFLOW_DIRS = /* @__PURE__ */ new Set(["disciplines", "judgments"]);
5950
+ }
5951
+ });
5952
+
5953
+ // src/cli/lib/skillIntegrity.ts
5954
+ var skillIntegrity_exports = {};
5955
+ __export(skillIntegrity_exports, {
5956
+ attachCulprits: () => attachCulprits,
5957
+ auditInstalledSkills: () => auditInstalledSkills,
5958
+ buildCulpritIndex: () => buildCulpritIndex,
5959
+ integrityReportLines: () => integrityReportLines,
5960
+ ledgerPath: () => ledgerPath,
5961
+ readHashLedger: () => readHashLedger,
5962
+ recordSkillHashes: () => recordSkillHashes,
5963
+ sha256Of: () => sha256Of
5964
+ });
5965
+ function ledgerPath() {
5966
+ return harnessedFile("skill-hashes.json");
5967
+ }
5968
+ function sha256Of(text) {
5969
+ return createHash("sha256").update(text, "utf8").digest("hex");
5970
+ }
5971
+ async function readHashLedger(path = ledgerPath()) {
5972
+ try {
5973
+ const parsed = JSON.parse(await readFile(path, "utf8"));
5974
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return null;
5975
+ return parsed;
5976
+ } catch {
5977
+ return null;
5978
+ }
5979
+ }
5980
+ async function recordSkillHashes(names, skillsBase, path = ledgerPath(), version = package_default.version) {
5981
+ try {
5982
+ const ledger = await readHashLedger(path) ?? {};
5983
+ const rendered_at = (/* @__PURE__ */ new Date()).toISOString();
5984
+ for (const name of names) {
5985
+ try {
5986
+ const text = await readFile(join(skillsBase, name, "SKILL.md"), "utf8");
5987
+ if (typeof text !== "string") continue;
5988
+ ledger[name] = { sha256: sha256Of(text), version, rendered_at };
5989
+ } catch {
5990
+ }
5991
+ }
5992
+ const tmp = `${path}.tmp-${process.pid}`;
5993
+ await writeFile(tmp, `${JSON.stringify(ledger, null, 2)}
5994
+ `, "utf8");
5995
+ await rename(tmp, path);
5996
+ } catch {
5997
+ }
5998
+ }
5999
+ function versionLt(a, b) {
6000
+ const pa = a.split(".").map(Number);
6001
+ const pb = b.split(".").map(Number);
6002
+ for (let i = 0; i < 3; i++) {
6003
+ const x = pa[i] ?? 0;
6004
+ const y = pb[i] ?? 0;
6005
+ if (x !== y) return x < y;
6006
+ }
6007
+ return false;
6008
+ }
6009
+ async function auditInstalledSkills(workflows, skillsBase, workflowsDir, opts = {}) {
6010
+ const ledger = opts.ledger !== void 0 ? opts.ledger : await readHashLedger();
6011
+ const out = [];
6012
+ for (const wf of workflows) {
6013
+ let src;
6014
+ try {
6015
+ src = await readFile(join(workflowsDir, wf.relPath, "SKILL.md"), "utf8");
6016
+ } catch {
6017
+ continue;
6018
+ }
6019
+ const srcMarker = typeof src === "string" ? HARNESSED_MARKER_RX2.exec(src) : null;
6020
+ if (!srcMarker) continue;
6021
+ const srcVersion = srcMarker[1] ?? "0.0.0";
6022
+ let installed;
6023
+ try {
6024
+ installed = await readFile(join(skillsBase, wf.name, "SKILL.md"), "utf8");
6025
+ } catch {
6026
+ installed = null;
6027
+ }
6028
+ if (installed === null || typeof installed !== "string") {
6029
+ out.push({ name: wf.name, status: "missing" });
6030
+ continue;
6031
+ }
6032
+ const marker = HARNESSED_MARKER_RX2.exec(installed);
6033
+ if (!marker) {
6034
+ out.push({ name: wf.name, status: "foreign" });
6035
+ continue;
6036
+ }
6037
+ const markerVersion = marker[1] ?? "0.0.0";
6038
+ if (versionLt(markerVersion, srcVersion)) {
6039
+ out.push({ name: wf.name, status: "stale" });
6040
+ continue;
6041
+ }
6042
+ const record = ledger?.[wf.name];
6043
+ if (!record) {
6044
+ out.push({ name: wf.name, status: "stale" });
6045
+ continue;
6046
+ }
6047
+ out.push({
6048
+ name: wf.name,
6049
+ status: sha256Of(installed) === record.sha256 ? "ok" : "tampered"
6050
+ });
6051
+ }
6052
+ return out;
6053
+ }
6054
+ async function buildCulpritIndex(manifestPaths) {
6055
+ const index = /* @__PURE__ */ new Map();
6056
+ for (const p7 of manifestPaths) {
6057
+ try {
6058
+ const parsed = parse(await readFile(p7, "utf8"));
6059
+ const pack = parsed?.metadata?.name;
6060
+ const skills = parsed?.spec?.install?.installs_skills;
6061
+ if (typeof pack !== "string" || !Array.isArray(skills)) continue;
6062
+ for (const s of skills) {
6063
+ if (typeof s === "string" && s.length > 0 && !index.has(s)) index.set(s, pack);
6064
+ }
6065
+ } catch {
6066
+ }
6067
+ }
6068
+ return index;
6069
+ }
6070
+ function attachCulprits(entries, culpritIndex) {
6071
+ return entries.map(
6072
+ (e) => e.status === "foreign" ? { ...e, culprit: culpritIndex.get(e.name) ?? e.culprit } : e
6073
+ );
6074
+ }
6075
+ function integrityReportLines(entries) {
6076
+ const bad = entries.filter((e) => e.status !== "ok");
6077
+ if (bad.length === 0) return [];
6078
+ const lines = [
6079
+ `\u26A0 ${bad.length} harnessed workflow skill(s) are not the shipped version \u2014 the slash command exists but may NOT enter the engine (no intent, no ledger, no evidence guard):`
6080
+ ];
6081
+ for (const e of bad) {
6082
+ const why = e.status === "foreign" ? "installed SKILL.md is not harnessed-generated" : e.status === "tampered" ? "modified since install (marker kept, content diverged from the install-time hash)" : e.status === "stale" ? "older install / no install-time hash recorded \u2014 re-run `harnessed setup` to refresh" : "missing";
6083
+ const culprit = e.culprit ? ` \u2014 likely overwritten by pack '${e.culprit}'` : "";
6084
+ lines.push(` ${e.name}: ${why}${culprit}`);
6085
+ }
6086
+ return lines;
6087
+ }
6088
+ var HARNESSED_MARKER_RX2;
6089
+ var init_skillIntegrity = __esm({
6090
+ "src/cli/lib/skillIntegrity.ts"() {
6091
+ init_package();
6092
+ init_harnessedRoot();
6093
+ HARNESSED_MARKER_RX2 = /<!--\s*harnessed-generated:v(\d+\.\d+\.\d+)\s*-->/;
6094
+ }
6095
+ });
6096
+
6097
+ // src/cli/lib/check-skill-integrity.ts
6098
+ var check_skill_integrity_exports = {};
6099
+ __export(check_skill_integrity_exports, {
6100
+ checkSkillIntegrity: () => checkSkillIntegrity
6101
+ });
6102
+ async function checkSkillIntegrity() {
6103
+ const name = "workflow skill integrity";
6104
+ try {
6105
+ const assetsRoot = getAssetsRoot();
6106
+ const workflowsDir = resolve(assetsRoot, "workflows");
6107
+ const entries = await readdir(workflowsDir);
6108
+ const { workflows } = await scanWorkflowsNested(workflowsDir, entries);
6109
+ if (workflows.length === 0) {
6110
+ return { name, status: "pass", message: "no shipped workflows to audit" };
6111
+ }
6112
+ const packsDir = resolve(assetsRoot, "manifests", "skill-packs");
6113
+ let manifestPaths = [];
6114
+ try {
6115
+ manifestPaths = (await readdir(packsDir)).filter((f) => f.endsWith(".yaml")).map((f) => resolve(packsDir, f));
6116
+ } catch {
6117
+ }
6118
+ const audit = attachCulprits(
6119
+ await auditInstalledSkills(workflows, getSkillsDir(), workflowsDir),
6120
+ await buildCulpritIndex(manifestPaths)
6121
+ );
6122
+ const bad = audit.filter((e) => e.status !== "ok");
6123
+ if (bad.length === 0) {
6124
+ return {
6125
+ name,
6126
+ status: "pass",
6127
+ message: `${audit.length} installed workflow skill(s) match their install-time hash ledger`
6128
+ };
6129
+ }
6130
+ const detail = bad.map((e) => `${e.name} (${e.status}${e.culprit ? `, likely pack '${e.culprit}'` : ""})`).join(", ");
6131
+ return {
6132
+ name,
6133
+ status: "warn",
6134
+ message: `${bad.length} workflow skill(s) diverged from the install-time state (foreign/tampered/stale/missing) \u2014 the slash command may NOT enter the engine: ${detail}`,
6135
+ fix: "re-run `harnessed setup` (its end-of-run integrity pass restores + re-pins the shipped versions)"
6136
+ };
6137
+ } catch {
6138
+ return { name, status: "pass", message: "skipped (environment not auditable)" };
6139
+ }
6140
+ }
6141
+ var init_check_skill_integrity = __esm({
6142
+ "src/cli/lib/check-skill-integrity.ts"() {
6143
+ init_platform();
6144
+ init_assetsRoot();
6145
+ init_scan_nested();
6146
+ init_skillIntegrity();
6147
+ }
6148
+ });
5512
6149
 
5513
6150
  // src/cli/lib/version-check.ts
5514
6151
  var version_check_exports = {};
@@ -5620,6 +6257,12 @@ var init_doctor_registry = __esm({
5620
6257
  // v4.16.1 T3 — bun presence (warn-only): gstack's upstream setup hard-requires
5621
6258
  // bun; missing bun is THE gstack refresh-failure cause on user dogfood machines.
5622
6259
  async () => (await Promise.resolve().then(() => (init_check_bun(), check_bun_exports))).checkBun(),
6260
+ // 4.22.1 T4 — dual-guard conflict (warn-only): ECC GateGuard's filename policy
6261
+ // vs evidence-guard artifact contract names (subagents cannot fact-retry).
6262
+ async () => (await Promise.resolve().then(() => (init_check_guard_conflict(), check_guard_conflict_exports))).checkGuardConflict(),
6263
+ // 4.23.0 (issue #3) — installed workflow-skill integrity (warn-only): flat
6264
+ // ~/.claude/skills packs can silently shadow shipped workflows; setup self-heals.
6265
+ async () => (await Promise.resolve().then(() => (init_check_skill_integrity(), check_skill_integrity_exports))).checkSkillIntegrity(),
5623
6266
  // Phase 20 — "update available" version check ('warn' only when behind; 'pass'
5624
6267
  // when current/ahead/npm-unreachable — fail-soft, never flips the summary).
5625
6268
  async () => (await Promise.resolve().then(() => (init_check_update(), check_update_exports))).checkUpdate()
@@ -6234,10 +6877,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
6234
6877
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
6235
6878
  stderr += chunk;
6236
6879
  });
6237
- return await new Promise((resolve17) => {
6880
+ return await new Promise((resolve19) => {
6238
6881
  const timer = setTimeout(() => {
6239
6882
  child.kill("SIGKILL");
6240
- resolve17({
6883
+ resolve19({
6241
6884
  ok: false,
6242
6885
  phase: "spawn",
6243
6886
  error: {
@@ -6258,7 +6901,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
6258
6901
  child.on("error", (err2) => {
6259
6902
  clearTimeout(timer);
6260
6903
  const bashMissing = triedBash && err2.code === "ENOENT";
6261
- resolve17({
6904
+ resolve19({
6262
6905
  ok: false,
6263
6906
  phase: "spawn",
6264
6907
  error: {
@@ -6273,7 +6916,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
6273
6916
  });
6274
6917
  child.on("close", (code) => {
6275
6918
  clearTimeout(timer);
6276
- resolve17({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
6919
+ resolve19({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
6277
6920
  });
6278
6921
  });
6279
6922
  }
@@ -6474,7 +7117,7 @@ var init_idempotent = __esm({
6474
7117
  }
6475
7118
  });
6476
7119
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
6477
- return new Promise((resolve17) => {
7120
+ return new Promise((resolve19) => {
6478
7121
  const isWin = process.platform === "win32";
6479
7122
  const stdio = ["ignore", "pipe", "pipe"];
6480
7123
  const child = isWin ? spawn("cmd.exe", ["/c", bin, ...args], { cwd, windowsHide: true, stdio }) : spawn(bin, args, { cwd, shell: false, stdio });
@@ -6488,17 +7131,17 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
6488
7131
  });
6489
7132
  const timer = setTimeout(() => {
6490
7133
  child.kill("SIGKILL");
6491
- resolve17({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
7134
+ resolve19({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
6492
7135
  }, timeoutMs);
6493
7136
  child.on("error", (e) => {
6494
7137
  clearTimeout(timer);
6495
7138
  const enoent = e.code === "ENOENT";
6496
7139
  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;
6497
- resolve17({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
7140
+ resolve19({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
6498
7141
  });
6499
7142
  child.on("close", (code) => {
6500
7143
  clearTimeout(timer);
6501
- resolve17({ exitCode: code ?? -1, stdout: stdout2, stderr });
7144
+ resolve19({ exitCode: code ?? -1, stdout: stdout2, stderr });
6502
7145
  });
6503
7146
  });
6504
7147
  }
@@ -6684,29 +7327,98 @@ ${newEntry}
6684
7327
  };
6685
7328
  }
6686
7329
  });
6687
- function gitRevParseHead(cwd, timeoutMs = 1e4) {
6688
- return new Promise((resolve17) => {
6689
- const isWin = process.platform === "win32";
6690
- const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
6691
- let stdout2 = "";
6692
- child.stdout?.setEncoding("utf8").on("data", (c) => {
6693
- stdout2 += c;
6694
- });
6695
- const timer = setTimeout(() => {
6696
- child.kill("SIGKILL");
6697
- resolve17({ sha: "", exit: -1 });
6698
- }, timeoutMs);
6699
- child.on("error", () => {
6700
- clearTimeout(timer);
6701
- resolve17({ sha: "", exit: -1 });
6702
- });
6703
- child.on("close", (code) => {
6704
- clearTimeout(timer);
6705
- resolve17({ sha: stdout2.trim(), exit: code ?? -1 });
6706
- });
6707
- });
7330
+ async function snapshotSkillNames(skillsDir = getSkillsDir()) {
7331
+ try {
7332
+ const entries = await readdir(skillsDir, { withFileTypes: true });
7333
+ return new Set(entries.filter((e) => e.isDirectory()).map((e) => e.name));
7334
+ } catch {
7335
+ return /* @__PURE__ */ new Set();
7336
+ }
6708
7337
  }
6709
- function extractRawCloneDest(cmd) {
7338
+ async function shippedWorkflowNames() {
7339
+ if (workflowNamesCache) return workflowNamesCache;
7340
+ try {
7341
+ const workflowsDir = resolve(getAssetsRoot(), "workflows");
7342
+ const entries = await readdir(workflowsDir);
7343
+ const { workflows } = await scanWorkflowsNested(workflowsDir, entries);
7344
+ workflowNamesCache = new Set(workflows.map((w) => w.name));
7345
+ } catch {
7346
+ workflowNamesCache = /* @__PURE__ */ new Set();
7347
+ }
7348
+ return workflowNamesCache;
7349
+ }
7350
+ function declaredSkills(ctx) {
7351
+ const declared = ctx.manifest.spec.install.installs_skills;
7352
+ return Array.isArray(declared) ? declared.filter((s) => typeof s === "string") : [];
7353
+ }
7354
+ async function warnDeclaredCollisions(ctx) {
7355
+ try {
7356
+ const declared = declaredSkills(ctx);
7357
+ if (declared.length === 0) return;
7358
+ const workflows = await shippedWorkflowNames();
7359
+ const collisions = declared.filter((s) => workflows.has(s));
7360
+ if (collisions.length === 0) return;
7361
+ console.warn(
7362
+ `\u26A0 [${ctx.manifest.metadata.name}] declares skill name(s) colliding with harnessed workflows: ${collisions.join(", ")} \u2014 the pack copy would shadow the engine workflow. Setup's integrity pass will restore the harnessed version; the pack's same-named skill will not be reachable.`
7363
+ );
7364
+ } catch {
7365
+ }
7366
+ }
7367
+ async function auditPostInstall(ctx, before, skillsDir = getSkillsDir()) {
7368
+ try {
7369
+ const after = await snapshotSkillNames(skillsDir);
7370
+ const added = [...after].filter((n) => !before.has(n));
7371
+ if (added.length === 0) return;
7372
+ const declared = new Set(declaredSkills(ctx));
7373
+ const pack = ctx.manifest.metadata.name;
7374
+ const undeclared = added.filter((n) => !declared.has(n));
7375
+ if (declared.size > 0 && undeclared.length > 0) {
7376
+ console.warn(
7377
+ `\u26A0 [${pack}] installed skill name(s) not declared in installs_skills: ${undeclared.join(", ")} \u2014 upstream added skills; update the manifest declaration so collisions stay detectable.`
7378
+ );
7379
+ }
7380
+ const workflows = await shippedWorkflowNames();
7381
+ const collisions = added.filter((n) => workflows.has(n));
7382
+ if (collisions.length > 0) {
7383
+ console.warn(
7384
+ `\u26A0 [${pack}] overwrote harnessed workflow skill(s): ${collisions.join(", ")} \u2014 the engine workflow at that name is now shadowed. Setup's end-of-run integrity pass restores it; re-run \`harnessed setup\` if you installed this pack standalone.`
7385
+ );
7386
+ }
7387
+ } catch {
7388
+ }
7389
+ }
7390
+ var workflowNamesCache;
7391
+ var init_packSkillAudit = __esm({
7392
+ "src/installers/lib/packSkillAudit.ts"() {
7393
+ init_assetsRoot();
7394
+ init_scan_nested();
7395
+ init_platform();
7396
+ workflowNamesCache = null;
7397
+ }
7398
+ });
7399
+ function gitRevParseHead(cwd, timeoutMs = 1e4) {
7400
+ return new Promise((resolve19) => {
7401
+ const isWin = process.platform === "win32";
7402
+ const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
7403
+ let stdout2 = "";
7404
+ child.stdout?.setEncoding("utf8").on("data", (c) => {
7405
+ stdout2 += c;
7406
+ });
7407
+ const timer = setTimeout(() => {
7408
+ child.kill("SIGKILL");
7409
+ resolve19({ sha: "", exit: -1 });
7410
+ }, timeoutMs);
7411
+ child.on("error", () => {
7412
+ clearTimeout(timer);
7413
+ resolve19({ sha: "", exit: -1 });
7414
+ });
7415
+ child.on("close", (code) => {
7416
+ clearTimeout(timer);
7417
+ resolve19({ sha: stdout2.trim(), exit: code ?? -1 });
7418
+ });
7419
+ });
7420
+ }
7421
+ function extractRawCloneDest(cmd) {
6710
7422
  const idx = cmd.indexOf("git clone");
6711
7423
  if (idx < 0) return null;
6712
7424
  const tail = cmd.slice(idx + "git clone".length).trim();
@@ -6758,6 +7470,7 @@ var init_gitCloneWithSetup2 = __esm({
6758
7470
  init_diff();
6759
7471
  init_err();
6760
7472
  init_idempotent();
7473
+ init_packSkillAudit();
6761
7474
  init_preflight();
6762
7475
  init_spawn();
6763
7476
  init_state2();
@@ -6839,6 +7552,8 @@ var init_gitCloneWithSetup2 = __esm({
6839
7552
  if (ctx.opts.dryRun) return { aborted: true, reason: "user-cancel" };
6840
7553
  const bk = await backup(plan, ctx);
6841
7554
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
7555
+ await warnDeclaredCollisions(ctx);
7556
+ const packSnapshot = await snapshotSkillNames();
6842
7557
  const sp = await spawnCmd(ctx, install.cmd, [], DEFAULT_INSTALL_TIMEOUT_MS, { posixShell: true });
6843
7558
  if (!("exitCode" in sp)) return { ...sp, backupId: bk.backupId };
6844
7559
  if (sp.exitCode !== 0) {
@@ -6855,6 +7570,7 @@ var init_gitCloneWithSetup2 = __esm({
6855
7570
  )
6856
7571
  };
6857
7572
  }
7573
+ await auditPostInstall(ctx, packSnapshot);
6858
7574
  const rp = isSelfCleaningCloneCmd(install.cmd) ? null : await gitRevParseHead(cloneTarget);
6859
7575
  if (rp === null) ; else if (rp.exit !== 0 || !rp.sha) {
6860
7576
  console.warn(
@@ -7276,6 +7992,7 @@ var init_npmCli2 = __esm({
7276
7992
  init_diff();
7277
7993
  init_err();
7278
7994
  init_idempotent();
7995
+ init_packSkillAudit();
7279
7996
  init_preflight();
7280
7997
  init_spawn();
7281
7998
  init_state2();
@@ -7338,6 +8055,8 @@ var init_npmCli2 = __esm({
7338
8055
  if (ctx.opts.dryRun) return { aborted: true, reason: "user-cancel" };
7339
8056
  const bk = await backup(plan, ctx);
7340
8057
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
8058
+ await warnDeclaredCollisions(ctx);
8059
+ const packSnapshot = await snapshotSkillNames();
7341
8060
  const sp = await spawnCmd(ctx, cmd, [], DEFAULT_INSTALL_TIMEOUT_MS, { neutralCwd: true });
7342
8061
  if (!("exitCode" in sp)) return { ...sp, backupId: bk.backupId };
7343
8062
  if (sp.exitCode !== 0) {
@@ -7354,6 +8073,7 @@ var init_npmCli2 = __esm({
7354
8073
  )
7355
8074
  };
7356
8075
  }
8076
+ await auditPostInstall(ctx, packSnapshot);
7357
8077
  const verifyTimeoutMs = ctx.manifest.spec.verify.timeout_ms ?? DEFAULT_VERIFY_TIMEOUT_MS;
7358
8078
  const vr = await spawnCmd(ctx, ctx.manifest.spec.verify.cmd, [], verifyTimeoutMs, {
7359
8079
  posixShell: true,
@@ -7388,6 +8108,7 @@ var init_npxSkillInstaller2 = __esm({
7388
8108
  init_diff();
7389
8109
  init_err();
7390
8110
  init_idempotent();
8111
+ init_packSkillAudit();
7391
8112
  init_platform();
7392
8113
  init_preflight();
7393
8114
  init_spawn();
@@ -7466,6 +8187,8 @@ var init_npxSkillInstaller2 = __esm({
7466
8187
  if (ctx.opts.dryRun) return { aborted: true, reason: "user-cancel" };
7467
8188
  const bk = await backup(plan, ctx);
7468
8189
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
8190
+ await warnDeclaredCollisions(ctx);
8191
+ const packSnapshot = await snapshotSkillNames();
7469
8192
  let sp = await spawnCmd(ctx, effectiveCmd, [], DEFAULT_INSTALL_TIMEOUT_MS, { neutralCwd: true });
7470
8193
  if (!("exitCode" in sp)) return { ...sp, backupId: bk.backupId };
7471
8194
  if (HARD_CRASH_EXITS.has(sp.exitCode)) {
@@ -7487,6 +8210,7 @@ var init_npxSkillInstaller2 = __esm({
7487
8210
  )
7488
8211
  };
7489
8212
  }
8213
+ await auditPostInstall(ctx, packSnapshot);
7490
8214
  const present = await detectSkillPresence(install.cmd, name);
7491
8215
  if (!present) {
7492
8216
  return {
@@ -7774,6 +8498,7 @@ var injectState_exports = {};
7774
8498
  __export(injectState_exports, {
7775
8499
  DEFAULT_INJECT_BUDGET: () => DEFAULT_INJECT_BUDGET,
7776
8500
  INTENT_TTL_MS: () => INTENT_TTL_MS,
8501
+ STALE_LEDGER_MS: () => STALE_LEDGER_MS,
7777
8502
  buildInjection: () => buildInjection,
7778
8503
  buildIntentBlock: () => buildIntentBlock,
7779
8504
  buildProjectContextBlock: () => buildProjectContextBlock,
@@ -7812,7 +8537,7 @@ function buildIntentBlock(intent, nowMs) {
7812
8537
  "</workflow-intent>"
7813
8538
  ].join("\n");
7814
8539
  }
7815
- function buildWorkflowStateBlock(wf, forward) {
8540
+ function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
7816
8541
  if (!wf) return "";
7817
8542
  const ledger = wf.sub_progress ?? [];
7818
8543
  const next = nextPending(ledger);
@@ -7823,7 +8548,12 @@ function buildWorkflowStateBlock(wf, forward) {
7823
8548
  `status: ${wf.status}`,
7824
8549
  next ? `next: ${next}` : "next: (none \u2014 all subs resolved)"
7825
8550
  ];
7826
- if (next) {
8551
+ if (next && typeof ledgerAgeMs === "number" && ledgerAgeMs > STALE_LEDGER_MS) {
8552
+ const days = Math.floor(ledgerAgeMs / (24 * 60 * 60 * 1e3));
8553
+ lines.push(
8554
+ `ENGINE: STALE state machine \u2014 sub '${next}' has been pending with NO checkpoint activity for >${days}d. This ledger may belong to an abandoned/bypassed run (issue #3 class). Run \`harnessed status --recover\` to re-orient, then either resume the sub or close it out with \`harnessed checkpoint fail ${next} --summary "<why>"\`.`
8555
+ );
8556
+ } else if (next) {
7827
8557
  lines.push(
7828
8558
  `ENGINE: mid state-machine \u2014 drive sub '${next}' via \`harnessed prompt ${next}\` \u2192 spawn \u2192 \`harnessed checkpoint complete/fail\`. Do NOT freestyle the orchestration or skip the ledger; run \`harnessed status --recover\` if unsure where you are.`
7829
8559
  );
@@ -7945,7 +8675,7 @@ function forwardPointer(repoRoot, wf) {
7945
8675
  if (unit.kind !== "phase" && unit.kind !== "task") return null;
7946
8676
  return { unit, remainingPhases: snapshot.phases.filter((p7) => !p7.complete).length };
7947
8677
  }
7948
- var INTENT_TTL_MS, DEFAULT_INJECT_BUDGET, tok;
8678
+ var INTENT_TTL_MS, STALE_LEDGER_MS, DEFAULT_INJECT_BUDGET, tok;
7949
8679
  var init_injectState = __esm({
7950
8680
  "src/checkpoint/injectState.ts"() {
7951
8681
  init_breakLoop();
@@ -7954,6 +8684,7 @@ var init_injectState = __esm({
7954
8684
  init_ledger();
7955
8685
  init_planningScan();
7956
8686
  INTENT_TTL_MS = 24 * 60 * 60 * 1e3;
8687
+ STALE_LEDGER_MS = 24 * 60 * 60 * 1e3;
7957
8688
  DEFAULT_INJECT_BUDGET = 1500;
7958
8689
  tok = (s) => Math.ceil(Buffer.byteLength(s, "utf8") / 4);
7959
8690
  }
@@ -7964,7 +8695,7 @@ var release_preflight_exports = {};
7964
8695
  __export(release_preflight_exports, {
7965
8696
  anyFailed: () => anyFailed,
7966
8697
  collectPreflight: () => collectPreflight,
7967
- defaultDeps: () => defaultDeps2
8698
+ defaultDeps: () => defaultDeps3
7968
8699
  });
7969
8700
  function unreleasedSection(changelog) {
7970
8701
  const start = changelog.indexOf("## [Unreleased]");
@@ -8019,7 +8750,7 @@ function collectPreflight(deps) {
8019
8750
  function anyFailed(checks) {
8020
8751
  return checks.some((c) => c.status === "fail");
8021
8752
  }
8022
- function defaultDeps2(cwd) {
8753
+ function defaultDeps3(cwd) {
8023
8754
  let changelog = "";
8024
8755
  let version = "";
8025
8756
  try {
@@ -8697,7 +9428,7 @@ function renderHumanTable(records) {
8697
9428
  }
8698
9429
  }
8699
9430
  function pipeToJq(filterExpr, lines) {
8700
- return new Promise((resolve17, reject) => {
9431
+ return new Promise((resolve19, reject) => {
8701
9432
  const child = spawn("jq", [filterExpr], {
8702
9433
  stdio: ["pipe", "inherit", "inherit"],
8703
9434
  windowsHide: true
@@ -8706,12 +9437,12 @@ function pipeToJq(filterExpr, lines) {
8706
9437
  const e = err2;
8707
9438
  if (e.code === "ENOENT") {
8708
9439
  console.error(t("audit_log.jq_missing"));
8709
- resolve17(1);
9440
+ resolve19(1);
8710
9441
  } else {
8711
9442
  reject(err2);
8712
9443
  }
8713
9444
  });
8714
- child.on("close", (code) => resolve17(code ?? 0));
9445
+ child.on("close", (code) => resolve19(code ?? 0));
8715
9446
  child.stdin.write(lines.join("\n"));
8716
9447
  child.stdin.end();
8717
9448
  });
@@ -8903,6 +9634,56 @@ function registerCheckpoint(program2) {
8903
9634
  }
8904
9635
  const { activatePhase: activatePhase2, completePhase: completePhase2 } = await Promise.resolve().then(() => (init_engineHook(), engineHook_exports));
8905
9636
  if (action === "start") {
9637
+ try {
9638
+ const { stat: statFs } = await import('fs/promises');
9639
+ const { resolve: resolvePath } = await import('path');
9640
+ const planningDir = resolvePath(process.cwd(), ".planning");
9641
+ const hasPlanning = await statFs(planningDir).then((s) => s.isDirectory()).catch(() => false);
9642
+ if (hasPlanning) {
9643
+ const missing = [];
9644
+ for (const f of ["STATE.md", "ROADMAP.md"]) {
9645
+ const ok = await statFs(resolvePath(planningDir, f)).then((s) => s.isFile()).catch(() => false);
9646
+ if (!ok) missing.push(`.planning/${f}`);
9647
+ }
9648
+ if (missing.length > 0) {
9649
+ console.error(
9650
+ `\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).`
9651
+ );
9652
+ }
9653
+ }
9654
+ } catch {
9655
+ }
9656
+ try {
9657
+ const { detectGateGuardActive: detectGateGuardActive2, GUARD_CONFLICT_ADVICE: GUARD_CONFLICT_ADVICE2 } = await Promise.resolve().then(() => (init_check_guard_conflict(), check_guard_conflict_exports));
9658
+ const det = await detectGateGuardActive2();
9659
+ if (det.active) {
9660
+ const ge = await Promise.resolve().then(() => (init_guard_exemption(), guard_exemption_exports));
9661
+ const isTty = process.stdin.isTTY === true && process.stdout.isTTY === true;
9662
+ const flowResult = await ge.runExemptionFlow({
9663
+ probe: () => ge.probeExemptCapability(),
9664
+ readEnvValue: () => ge.readCurrentEnvValue(),
9665
+ merge: (value) => ge.applyEnvExemption(value),
9666
+ print: (line) => console.error(line),
9667
+ ...isTty ? {
9668
+ confirm: async () => {
9669
+ const p7 = await import('@clack/prompts');
9670
+ const ans = await p7.confirm({
9671
+ message: 'Apply the GateGuard exemption now? (persists GATEGUARD_EXEMPT_GLOBS=".planning/**" into settings env \u2014 backed up first)',
9672
+ initialValue: true
9673
+ // D1 — default YES
9674
+ });
9675
+ return !p7.isCancel(ans) && ans === true;
9676
+ }
9677
+ } : {}
9678
+ });
9679
+ if (flowResult === "not-capable") {
9680
+ console.error(
9681
+ `\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
9682
+ );
9683
+ }
9684
+ }
9685
+ } catch {
9686
+ }
8906
9687
  const { checkpointPath } = await activatePhase2(sub);
8907
9688
  const plan = await parsePlan(opts.plan);
8908
9689
  if (plan) {
@@ -9094,12 +9875,38 @@ function registerDoctor(program2) {
9094
9875
  });
9095
9876
  }
9096
9877
 
9878
+ // src/cli/exempt-gateguard.ts
9879
+ init_guard_exemption();
9880
+ function registerExemptGateguard(program2) {
9881
+ program2.command("exempt-gateguard").description(
9882
+ 'Persist GATEGUARD_EXEMPT_GLOBS=".planning/**" into the harness settings env \u2014 resolves the dual-guard conflict with the harnessed evidence guard (backup-first, atomic write)'
9883
+ ).action(async () => {
9884
+ const result = await runExemptionFlow({
9885
+ probe: () => probeExemptCapability(),
9886
+ readEnvValue: () => readCurrentEnvValue(),
9887
+ merge: (value) => applyEnvExemption(value),
9888
+ print: (line) => console.log(line),
9889
+ confirm: async () => true
9890
+ // consent = invocation (see header)
9891
+ });
9892
+ if (result === "already") {
9893
+ console.log(
9894
+ "\u2713 [harnessed] .planning/** is already listed in GATEGUARD_EXEMPT_GLOBS \u2014 nothing to do."
9895
+ );
9896
+ }
9897
+ if (result === "not-capable") {
9898
+ for (const line of upgradeAdviceLines()) console.log(line);
9899
+ }
9900
+ process.exit(result === "error" ? 1 : 0);
9901
+ });
9902
+ }
9903
+
9097
9904
  // src/cli/gates.ts
9098
9905
  init_path_guard();
9099
9906
  init_judgmentResolver();
9100
9907
  init_assetsRoot();
9101
9908
  init_gateContext();
9102
- var VALID_MASTERS = /* @__PURE__ */ new Set(["auto", "discuss", "plan", "task", "verify"]);
9909
+ var VALID_MASTERS = /* @__PURE__ */ new Set(["auto", "discuss", "plan", "task", "verify", "ship"]);
9103
9910
  var STAGE_MASTERS = /* @__PURE__ */ new Set(["discuss", "plan", "task", "verify"]);
9104
9911
  var PARALLELISM_GATE = "judgments.parallelism-gate.agent-teams-upgrade.fires";
9105
9912
  function resolveMasterYamlPath2(master, packageRoot) {
@@ -9108,7 +9915,7 @@ function resolveMasterYamlPath2(master, packageRoot) {
9108
9915
  function registerGates(program2) {
9109
9916
  program2.command("gates").description(
9110
9917
  "Evaluate which sub-workflows fire for a master orchestrator (JSON plan, no spawn)."
9111
- ).argument("<master>", "master name: auto | discuss | plan | task | verify").option("--task <text>", "task description (injected as gateContext.task)").option(
9918
+ ).argument("<master>", "master name: auto | discuss | plan | task | verify | ship").option("--task <text>", "task description (injected as gateContext.task)").option(
9112
9919
  "--skip-sub <names>",
9113
9920
  "sub names to skip without gate eval (repeatable and/or comma-separated)",
9114
9921
  (v, prev) => [...prev, v],
@@ -9116,7 +9923,7 @@ function registerGates(program2) {
9116
9923
  ).option("--context <json>", "JSON object merged over the default gate context").action(async (master, raw) => {
9117
9924
  if (!VALID_MASTERS.has(master)) {
9118
9925
  console.error(
9119
- `error: unknown master '${master}'. Expected one of: auto, discuss, plan, task, verify.`
9926
+ `error: unknown master '${master}'. Expected one of: auto, discuss, plan, task, verify, ship.`
9120
9927
  );
9121
9928
  process.exit(1);
9122
9929
  return;
@@ -9520,6 +10327,15 @@ function registerStatus(program2) {
9520
10327
  } catch {
9521
10328
  }
9522
10329
  }
10330
+ try {
10331
+ const { checkSkillIntegrity: checkSkillIntegrity2 } = await Promise.resolve().then(() => (init_check_skill_integrity(), check_skill_integrity_exports));
10332
+ const integ = await checkSkillIntegrity2();
10333
+ if (integ.status === "warn") {
10334
+ console.warn(`\u26A0 ${integ.message}`);
10335
+ if (integ.fix) console.warn(` fix: ${integ.fix}`);
10336
+ }
10337
+ } catch {
10338
+ }
9523
10339
  const lines = await buildRecoverLines(wf, ledger, intent);
9524
10340
  for (const l of lines) console.log(l);
9525
10341
  return;
@@ -9896,8 +10712,8 @@ function registerReleasePreflight(program2) {
9896
10712
  program2.command("release-preflight").description(
9897
10713
  "Read-only release-readiness gate (CHANGELOG / version / git-clean / tag). Exits 1 if not ready."
9898
10714
  ).action(async () => {
9899
- const { collectPreflight: collectPreflight2, anyFailed: anyFailed2, defaultDeps: defaultDeps3 } = await Promise.resolve().then(() => (init_release_preflight(), release_preflight_exports));
9900
- const checks = collectPreflight2(defaultDeps3(process.cwd()));
10715
+ const { collectPreflight: collectPreflight2, anyFailed: anyFailed2, defaultDeps: defaultDeps4 } = await Promise.resolve().then(() => (init_release_preflight(), release_preflight_exports));
10716
+ const checks = collectPreflight2(defaultDeps4(process.cwd()));
9901
10717
  console.log("\n release preflight (read-only \u2014 nothing is pushed/published):\n");
9902
10718
  for (const c of checks) {
9903
10719
  const mark = c.status === "pass" ? "\u2713" : c.status === "warn" ? "\u26A0" : "\u2717";
@@ -10207,81 +11023,7 @@ function renderSkillBody(body, capabilities, installedPlugins, installedUserSkil
10207
11023
 
10208
11024
  // src/cli/lib/enableAgentTeamsInSettings.ts
10209
11025
  init_platform();
10210
-
10211
- // src/cli/lib/settingsWriter.ts
10212
- init_harnessedRoot();
10213
- init_platform();
10214
- async function mergeSettingsEnvKey(key, value, opts = {}) {
10215
- const path = getSettingsPath();
10216
- let raw;
10217
- try {
10218
- raw = await readFile(path, "utf8");
10219
- } catch (err2) {
10220
- const code = err2.code;
10221
- if (code !== "ENOENT") {
10222
- return { outcome: "warn", message: `read ${path} failed: ${err2.message}` };
10223
- }
10224
- return createFresh(path, key, value);
10225
- }
10226
- let data;
10227
- try {
10228
- const parsed = JSON.parse(raw);
10229
- if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
10230
- return { outcome: "warn", message: `${path} is not a JSON object` };
10231
- }
10232
- data = parsed;
10233
- } catch (err2) {
10234
- return { outcome: "warn", message: `${path} malformed JSON: ${err2.message}` };
10235
- }
10236
- const env = data.env ?? {};
10237
- const existing = env[key];
10238
- if (typeof existing === "string" && existing.length > 0 && opts.skipIfPresent?.(existing) === true) {
10239
- return { outcome: "already", path, existing };
10240
- }
10241
- const backup2 = await backupOriginal(raw);
10242
- if (backup2.status === "warn") return { outcome: "warn", message: backup2.message };
10243
- data.env = { ...env, [key]: value };
10244
- const writeErr = await atomicWrite(path, `${JSON.stringify(data, null, 2)}
10245
- `);
10246
- if (writeErr) return { outcome: "warn", message: writeErr };
10247
- return { outcome: "merged", path, backupPath: backup2.path };
10248
- }
10249
- async function createFresh(path, key, value) {
10250
- const data = { env: { [key]: value } };
10251
- try {
10252
- await mkdir(dirname(path), { recursive: true });
10253
- } catch (err2) {
10254
- return { outcome: "warn", message: `mkdir ~/.claude failed: ${err2.message}` };
10255
- }
10256
- const writeErr = await atomicWrite(path, `${JSON.stringify(data, null, 2)}
10257
- `);
10258
- if (writeErr) return { outcome: "warn", message: writeErr };
10259
- return { outcome: "created", path };
10260
- }
10261
- async function backupOriginal(raw) {
10262
- const backupRoot = harnessedSubdir("backups");
10263
- const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-");
10264
- const backupPath = join(backupRoot, `settings.json.${ts}.bak`);
10265
- try {
10266
- await mkdir(backupRoot, { recursive: true });
10267
- await writeFile(backupPath, raw, "utf8");
10268
- return { status: "ok", path: backupPath };
10269
- } catch (err2) {
10270
- return { status: "warn", message: `backup ${backupPath} failed: ${err2.message}` };
10271
- }
10272
- }
10273
- async function atomicWrite(path, content) {
10274
- const tmpPath = `${path}.tmp-${process.pid}-${Date.now()}`;
10275
- try {
10276
- await writeFile(tmpPath, content, "utf8");
10277
- await rename(tmpPath, path);
10278
- return void 0;
10279
- } catch (err2) {
10280
- return `write ${path} failed: ${err2.message}`;
10281
- }
10282
- }
10283
-
10284
- // src/cli/lib/enableAgentTeamsInSettings.ts
11026
+ init_settingsWriter();
10285
11027
  var ENV_KEY = "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS";
10286
11028
  async function enableAgentTeamsInSettings() {
10287
11029
  const platform = detectPlatform();
@@ -10308,6 +11050,7 @@ async function enableAgentTeamsInSettings() {
10308
11050
 
10309
11051
  // src/cli/lib/enableUserLangInSettings.ts
10310
11052
  init_platform();
11053
+ init_settingsWriter();
10311
11054
  var ENV_KEY2 = "HARNESSED_USER_LANG";
10312
11055
  function detectUserLang(override) {
10313
11056
  if (override) {
@@ -10466,64 +11209,7 @@ init_idempotent();
10466
11209
  init_platform();
10467
11210
  init_validate();
10468
11211
  init_checkAgentTeams();
10469
- var FLAT_LEGACY_KEEP = /* @__PURE__ */ new Set(["research", "retro", "auto"]);
10470
- var FLAT_TOP_LEVEL_MASTERS = /* @__PURE__ */ new Set(["auto"]);
10471
- var NON_WORKFLOW_DIRS = /* @__PURE__ */ new Set(["disciplines", "judgments"]);
10472
- async function scanWorkflowsNested(workflowsDir, entries) {
10473
- const workflows = [];
10474
- for (const entry of entries.sort()) {
10475
- if (NON_WORKFLOW_DIRS.has(entry)) continue;
10476
- const src = join(workflowsDir, entry);
10477
- let s;
10478
- try {
10479
- s = await stat(src);
10480
- } catch {
10481
- continue;
10482
- }
10483
- if (!s.isDirectory()) continue;
10484
- let hasFlatSkill = false;
10485
- try {
10486
- await stat(join(src, "SKILL.md"));
10487
- hasFlatSkill = true;
10488
- } catch {
10489
- hasFlatSkill = false;
10490
- }
10491
- if (hasFlatSkill) {
10492
- if (FLAT_LEGACY_KEEP.has(entry)) {
10493
- workflows.push({ name: entry, relPath: entry, isMaster: FLAT_TOP_LEVEL_MASTERS.has(entry) });
10494
- continue;
10495
- }
10496
- workflows.push({ name: entry, relPath: entry, isMaster: false });
10497
- continue;
10498
- }
10499
- let subEntries;
10500
- try {
10501
- subEntries = await readdir(src);
10502
- } catch {
10503
- continue;
10504
- }
10505
- for (const sub of subEntries.sort()) {
10506
- const subDir = join(src, sub);
10507
- let ss;
10508
- try {
10509
- ss = await stat(subDir);
10510
- } catch {
10511
- continue;
10512
- }
10513
- if (!ss.isDirectory()) continue;
10514
- try {
10515
- await stat(join(subDir, "SKILL.md"));
10516
- } catch {
10517
- continue;
10518
- }
10519
- const name = sub === "auto" ? entry : `${entry}-${sub}`;
10520
- workflows.push({ name, relPath: `${entry}/${sub}`, isMaster: sub === "auto" });
10521
- }
10522
- }
10523
- return { workflows };
10524
- }
10525
-
10526
- // src/cli/lib/setup-helpers.ts
11212
+ init_scan_nested();
10527
11213
  async function warnIfAgentTeamsMissing() {
10528
11214
  if (detectPlatform().id !== "claude") return;
10529
11215
  const r = await checkAgentTeams();
@@ -10858,6 +11544,66 @@ function registerSetup(program2) {
10858
11544
  console.log(t("setup.dry_run.run_hint"));
10859
11545
  process.exit(0);
10860
11546
  }
11547
+ const manifestPaths = await listBaseManifests2(pkgRoot);
11548
+ const forceFirstPass = raw.updateInstalled === true;
11549
+ const progressPrinter = (ev) => {
11550
+ console.log(` [${ev.done}/${ev.total}] ${ev.status} ${ev.name}`);
11551
+ };
11552
+ console.log(
11553
+ `
11554
+ installing ${manifestPaths.length} upstream components (MCP serialized, rest parallel)...`
11555
+ );
11556
+ const b = await runStepBInstall(manifestPaths, {
11557
+ updateInstalled: forceFirstPass,
11558
+ quiet: true,
11559
+ onProgress: progressPrinter
11560
+ });
11561
+ const stepBMs = (b.elapsedMs / 1e3).toFixed(1);
11562
+ console.log(
11563
+ t("setup.step_b_complete", {
11564
+ installed: b.installed.length,
11565
+ already: b.alreadyInstalled.length,
11566
+ skipped: b.skipped.length,
11567
+ failed: b.failed.length,
11568
+ seconds: stepBMs
11569
+ })
11570
+ );
11571
+ printGrouped(b);
11572
+ if (!forceFirstPass && !dryRun && raw.nonInteractive !== true && b.alreadyInstalled.length > 0) {
11573
+ const isTty = process.stdin.isTTY === true && process.stdout.isTTY === true;
11574
+ if (isTty) {
11575
+ const { confirm: confirm5, isCancel: isCancel7 } = await import('@clack/prompts');
11576
+ const ans = await confirm5({
11577
+ message: `Update ${b.alreadyInstalled.length} already-installed plugin(s) listed above? (MCP servers excluded \u2014 they ignore force-update)`,
11578
+ initialValue: false
11579
+ });
11580
+ if (!isCancel7(ans) && ans === true) {
11581
+ console.log(`
11582
+ force-updating ${b.alreadyInstalled.length} plugin(s)...`);
11583
+ const b2 = await runStepBInstall(manifestPaths, {
11584
+ updateInstalled: true,
11585
+ quiet: true,
11586
+ onProgress: progressPrinter
11587
+ });
11588
+ const probe = await makeIdempotentProbe(manifestPaths);
11589
+ const reclass = await reclassifyForceUpdateFailures(b, b2, probe);
11590
+ b2.failed = reclass.failed;
11591
+ b2.keptExisting = reclass.keptExisting;
11592
+ const stepB2Ms = (b2.elapsedMs / 1e3).toFixed(1);
11593
+ console.log(
11594
+ `
11595
+ Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting.length} kept-existing / ${b2.alreadyInstalled.length} still-already-installed (MCP) / ${b2.skipped.length} skipped / ${b2.failed.length} failed [parallel ${stepB2Ms}s]`
11596
+ );
11597
+ printGrouped(b2, "[force-update] ");
11598
+ if (b2.keptExisting.length > 0) {
11599
+ console.warn(
11600
+ `
11601
+ ${b2.keptExisting.length} plugin(s) kept their existing version \u2014 refresh failed but the prior install is still usable. Re-run \`harnessed setup\` later to retry the update.`
11602
+ );
11603
+ }
11604
+ }
11605
+ }
11606
+ }
10861
11607
  let skillsInstalled = 0;
10862
11608
  for (const wf of toInstall) {
10863
11609
  const src = join(workflowsDir, wf.relPath);
@@ -10885,6 +11631,11 @@ function registerSetup(program2) {
10885
11631
  console.warn(` - ${w}`);
10886
11632
  }
10887
11633
  }
11634
+ try {
11635
+ const { recordSkillHashes: recordSkillHashes2 } = await Promise.resolve().then(() => (init_skillIntegrity(), skillIntegrity_exports));
11636
+ await recordSkillHashes2(skillNames, skillsBase);
11637
+ } catch {
11638
+ }
10888
11639
  const commandsBase = getCommandsDir();
10889
11640
  try {
10890
11641
  await mkdir(commandsBase, { recursive: true });
@@ -10920,66 +11671,6 @@ function registerSetup(program2) {
10920
11671
  }
10921
11672
  await enableAgentTeamsInSettings();
10922
11673
  await enableUserLangInSettings(raw.userLang);
10923
- const manifestPaths = await listBaseManifests2(pkgRoot);
10924
- const forceFirstPass = raw.updateInstalled === true;
10925
- const progressPrinter = (ev) => {
10926
- console.log(` [${ev.done}/${ev.total}] ${ev.status} ${ev.name}`);
10927
- };
10928
- console.log(
10929
- `
10930
- installing ${manifestPaths.length} upstream components (MCP serialized, rest parallel)...`
10931
- );
10932
- const b = await runStepBInstall(manifestPaths, {
10933
- updateInstalled: forceFirstPass,
10934
- quiet: true,
10935
- onProgress: progressPrinter
10936
- });
10937
- const stepBMs = (b.elapsedMs / 1e3).toFixed(1);
10938
- console.log(
10939
- t("setup.step_b_complete", {
10940
- installed: b.installed.length,
10941
- already: b.alreadyInstalled.length,
10942
- skipped: b.skipped.length,
10943
- failed: b.failed.length,
10944
- seconds: stepBMs
10945
- })
10946
- );
10947
- printGrouped(b);
10948
- if (!forceFirstPass && !dryRun && raw.nonInteractive !== true && b.alreadyInstalled.length > 0) {
10949
- const isTty = process.stdin.isTTY === true && process.stdout.isTTY === true;
10950
- if (isTty) {
10951
- const { confirm: confirm5, isCancel: isCancel7 } = await import('@clack/prompts');
10952
- const ans = await confirm5({
10953
- message: `Update ${b.alreadyInstalled.length} already-installed plugin(s) listed above? (MCP servers excluded \u2014 they ignore force-update)`,
10954
- initialValue: false
10955
- });
10956
- if (!isCancel7(ans) && ans === true) {
10957
- console.log(`
10958
- force-updating ${b.alreadyInstalled.length} plugin(s)...`);
10959
- const b2 = await runStepBInstall(manifestPaths, {
10960
- updateInstalled: true,
10961
- quiet: true,
10962
- onProgress: progressPrinter
10963
- });
10964
- const probe = await makeIdempotentProbe(manifestPaths);
10965
- const reclass = await reclassifyForceUpdateFailures(b, b2, probe);
10966
- b2.failed = reclass.failed;
10967
- b2.keptExisting = reclass.keptExisting;
10968
- const stepB2Ms = (b2.elapsedMs / 1e3).toFixed(1);
10969
- console.log(
10970
- `
10971
- Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting.length} kept-existing / ${b2.alreadyInstalled.length} still-already-installed (MCP) / ${b2.skipped.length} skipped / ${b2.failed.length} failed [parallel ${stepB2Ms}s]`
10972
- );
10973
- printGrouped(b2, "[force-update] ");
10974
- if (b2.keptExisting.length > 0) {
10975
- console.warn(
10976
- `
10977
- ${b2.keptExisting.length} plugin(s) kept their existing version \u2014 refresh failed but the prior install is still usable. Re-run \`harnessed setup\` later to retry the update.`
10978
- );
10979
- }
10980
- }
10981
- }
10982
- }
10983
11674
  if (!dryRun && raw.nonInteractive !== true && b.skipped.some((s) => s.reason === "level-flag-missing")) {
10984
11675
  const isTty = process.stdin.isTTY === true && process.stdout.isTTY === true;
10985
11676
  if (isTty) {
@@ -11021,6 +11712,60 @@ ${b.failed.length} component(s) failed \u2014 see the notes in the tables above;
11021
11712
  // commander default = true; --no-auto-install flips
11022
11713
  });
11023
11714
  }
11715
+ try {
11716
+ const {
11717
+ attachCulprits: attachCulprits2,
11718
+ auditInstalledSkills: auditInstalledSkills2,
11719
+ buildCulpritIndex: buildCulpritIndex2,
11720
+ integrityReportLines: integrityReportLines2,
11721
+ recordSkillHashes: recordSkillHashes2
11722
+ } = await Promise.resolve().then(() => (init_skillIntegrity(), skillIntegrity_exports));
11723
+ const audit = attachCulprits2(
11724
+ await auditInstalledSkills2(toInstall, skillsBase, workflowsDir),
11725
+ await buildCulpritIndex2(manifestPaths)
11726
+ );
11727
+ const bad = audit.filter((e) => e.status !== "ok");
11728
+ if (bad.length > 0) {
11729
+ for (const line of integrityReportLines2(audit)) console.warn(line);
11730
+ let healed = 0;
11731
+ const healedNames = [];
11732
+ for (const e of bad) {
11733
+ const wf = toInstall.find((w) => w.name === e.name);
11734
+ if (!wf) continue;
11735
+ try {
11736
+ await cp(join(workflowsDir, wf.relPath), join(skillsBase, wf.name), {
11737
+ recursive: true,
11738
+ force: true
11739
+ });
11740
+ healed++;
11741
+ healedNames.push(e.name);
11742
+ } catch {
11743
+ console.warn(` \u2717 could not restore '${e.name}' \u2014 re-run \`harnessed setup\``);
11744
+ }
11745
+ }
11746
+ if (healed > 0) {
11747
+ try {
11748
+ await renderAllSkills(healedNames, skillsBase, workflowsDir, void 0, getLocale());
11749
+ } catch {
11750
+ }
11751
+ await recordSkillHashes2(healedNames, skillsBase);
11752
+ console.warn(
11753
+ ` \u2713 restored ${healed} harnessed workflow skill(s) from the bundle (packs keep their other skills; the colliding name belongs to the engine)`
11754
+ );
11755
+ }
11756
+ }
11757
+ } catch {
11758
+ }
11759
+ try {
11760
+ const { checkGuardConflict: checkGuardConflict2 } = await Promise.resolve().then(() => (init_check_guard_conflict(), check_guard_conflict_exports));
11761
+ const guard = await checkGuardConflict2();
11762
+ if (guard.status === "warn") {
11763
+ console.warn(`
11764
+ \u26A0 ${guard.name} \u2014 ${guard.message}`);
11765
+ if (guard.fix) console.warn(` fix: ${guard.fix}`);
11766
+ }
11767
+ } catch {
11768
+ }
11024
11769
  process.exit(0);
11025
11770
  });
11026
11771
  }
@@ -11236,7 +11981,7 @@ var uninstallNpmCli = async (ctx) => {
11236
11981
  const m = install.cmd.match(/npm\s+(?:install|i)\s+(?:-g\s+)?(\S+)/);
11237
11982
  const pkg = m?.[1] ?? ctx.manifest.metadata.upstream.source;
11238
11983
  const isWin = process.platform === "win32";
11239
- const result = await new Promise((resolve17) => {
11984
+ const result = await new Promise((resolve19) => {
11240
11985
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], { windowsHide: true }) : spawn("npm", ["uninstall", "-g", pkg], { shell: false });
11241
11986
  let stderr = "";
11242
11987
  child.stderr?.setEncoding("utf8").on("data", (c) => {
@@ -11244,15 +11989,15 @@ var uninstallNpmCli = async (ctx) => {
11244
11989
  });
11245
11990
  const timer = setTimeout(() => {
11246
11991
  child.kill("SIGKILL");
11247
- resolve17({ exitCode: -1, stderr: `${stderr}[timeout]` });
11992
+ resolve19({ exitCode: -1, stderr: `${stderr}[timeout]` });
11248
11993
  }, 3e4);
11249
11994
  child.on("error", (e) => {
11250
11995
  clearTimeout(timer);
11251
- resolve17({ exitCode: -1, stderr: e.message });
11996
+ resolve19({ exitCode: -1, stderr: e.message });
11252
11997
  });
11253
11998
  child.on("close", (code) => {
11254
11999
  clearTimeout(timer);
11255
- resolve17({ exitCode: code ?? -1, stderr });
12000
+ resolve19({ exitCode: code ?? -1, stderr });
11256
12001
  });
11257
12002
  });
11258
12003
  if (result.exitCode !== 0) {
@@ -11300,6 +12045,7 @@ async function runUninstall(manifest, opts) {
11300
12045
  // src/cli/uninstall.ts
11301
12046
  init_assetsRoot();
11302
12047
  init_generateCommands();
12048
+ init_scan_nested();
11303
12049
  async function discoverCommandFiles(commandsDir) {
11304
12050
  const owned = [];
11305
12051
  let entries;
@@ -11674,6 +12420,7 @@ registerAdvance(program);
11674
12420
  registerReject(program);
11675
12421
  registerCompact(program);
11676
12422
  registerWorkflows(program);
12423
+ registerExemptGateguard(program);
11677
12424
  registerLearn(program);
11678
12425
  registerUpdate(program);
11679
12426
  registerReleasePreflight(program);