harnessed 4.41.0 → 4.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -1,15 +1,15 @@
1
1
  #!/usr/bin/env node
2
- import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync, readdirSync, realpathSync, mkdtempSync, utimesSync, rmSync, statSync, appendFileSync } from 'fs';
2
+ import { existsSync, mkdirSync, renameSync, writeFileSync, readFileSync, readdirSync, realpathSync, mkdtempSync, rmSync, utimesSync, statSync, appendFileSync } from 'fs';
3
3
  import { homedir, tmpdir } from 'os';
4
- import { join, resolve, dirname, basename, sep, isAbsolute, win32, posix, relative } from 'path';
4
+ import { join, resolve, dirname, basename, sep, isAbsolute, relative, win32, posix } from 'path';
5
5
  import { Type } from '@sinclair/typebox';
6
- import { readFile, readdir, unlink, writeFile, stat, rm, cp, mkdir, access, rename, appendFile, copyFile, chmod } from 'fs/promises';
6
+ import { readFile, readdir, stat, rm, unlink, writeFile, 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
9
  import { LineCounter, parseDocument, parse, isSeq, isScalar, stringify } from 'yaml';
10
10
  import { Ajv } from 'ajv';
11
11
  import * as ajvFormatsNs from 'ajv-formats';
12
- import { execFileSync, spawnSync, spawn, execSync, execFile, exec } from 'child_process';
12
+ import { execFileSync, spawnSync, spawn, execFile, exec } from 'child_process';
13
13
  import { pathToFileURL, fileURLToPath } from 'url';
14
14
  import { createHash, verify, createPublicKey } from 'crypto';
15
15
  import { promisify } from 'util';
@@ -17,7 +17,7 @@ import { Parser } from 'expr-eval';
17
17
  import * as p from '@clack/prompts';
18
18
  import { createPatch } from 'diff';
19
19
  import pc from 'picocolors';
20
- import { Command } from 'commander';
20
+ import { Command, InvalidArgumentError } from 'commander';
21
21
  import { stdout, stdin } from 'process';
22
22
  import * as readline from 'readline/promises';
23
23
  import { query } from '@anthropic-ai/claude-agent-sdk';
@@ -38,7 +38,7 @@ var init_package = __esm({
38
38
  "package.json"() {
39
39
  package_default = {
40
40
  name: "harnessed",
41
- version: "4.41.0",
41
+ version: "4.42.0",
42
42
  description: "AI coding harness package manager + composition orchestrator",
43
43
  type: "module",
44
44
  license: "Apache-2.0",
@@ -366,11 +366,18 @@ async function writeFileAtomic(path, data) {
366
366
  await rename(tmp, path);
367
367
  return;
368
368
  } catch (e) {
369
- if (i >= RENAME_RETRIES || !isTransient(e)) throw e;
369
+ if (i >= RENAME_RETRIES || !isTransient(e)) {
370
+ await rm(tmp, { force: true }).catch(() => {
371
+ });
372
+ throw e;
373
+ }
370
374
  await new Promise((r) => setTimeout(r, 10 * (i + 1)));
371
375
  }
372
376
  }
373
377
  }
378
+ function sleepSync(ms) {
379
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
380
+ }
374
381
  function writeFileSyncAtomic(path, data) {
375
382
  const tmp = tmpName(path);
376
383
  writeFileSync(tmp, data, "utf8");
@@ -379,7 +386,14 @@ function writeFileSyncAtomic(path, data) {
379
386
  renameSync(tmp, path);
380
387
  return;
381
388
  } catch (e) {
382
- if (i >= RENAME_RETRIES || !isTransient(e)) throw e;
389
+ if (i >= RENAME_RETRIES || !isTransient(e)) {
390
+ try {
391
+ rmSync(tmp, { force: true });
392
+ } catch {
393
+ }
394
+ throw e;
395
+ }
396
+ sleepSync(10 * (i + 1));
383
397
  }
384
398
  }
385
399
  }
@@ -525,6 +539,12 @@ var init_currentWorkflow_v1 = __esm({
525
539
  // G2 — when true the next-step contract reports NEXT:auto (skill auto-advances);
526
540
  // when false NEXT:manual (pause for the operator). Precedence env > this > default.
527
541
  auto_transition: Type.Optional(Type.Boolean()),
542
+ // Last write to THIS slot (stamped by writeCurrentWorkflowUnlocked). The STALE
543
+ // ledger breadcrumb used the mtime of the whole multi-repo workflows.json, which
544
+ // any repo's write refreshes, so an abandoned ledger in one repo never aged
545
+ // while another repo was active (external review L8). Additive-optional: old
546
+ // records without it fall back to the file mtime.
547
+ updated_at: Type.Optional(Type.String({ minLength: 1 })),
528
548
  // Phase 14 — compaction digest: cumulative summary of resolved sub-progress
529
549
  // entries evicted by `compact`. Additive-optional (NO schemaVersion bump; old
530
550
  // files without it still Value.Check-pass). Keeps a readable trace after
@@ -682,6 +702,7 @@ __export(state_exports, {
682
702
  complete: () => complete,
683
703
  mutateStore: () => mutateStore,
684
704
  mutateSubProgress: () => mutateSubProgress,
705
+ mutateWorkflow: () => mutateWorkflow,
685
706
  pause: () => pause,
686
707
  readCurrentWorkflow: () => readCurrentWorkflow,
687
708
  writeCurrentWorkflow: () => writeCurrentWorkflow
@@ -719,7 +740,8 @@ async function readCurrentWorkflow() {
719
740
  const store = await readStoreRaw();
720
741
  return store.workflows[activeKey()] ?? store.workflows[repoKey()] ?? null;
721
742
  }
722
- async function writeCurrentWorkflowUnlocked(s) {
743
+ async function writeCurrentWorkflowUnlocked(input) {
744
+ const s = { ...input, updated_at: (/* @__PURE__ */ new Date()).toISOString() };
723
745
  if (!Value.Check(CurrentWorkflowV1, s)) {
724
746
  const errs = [...Value.Errors(CurrentWorkflowV1, s)].map((e) => e.message).join("; ");
725
747
  throw new WorkflowStateError(`current-workflow schema validation failed: ${errs}`);
@@ -740,6 +762,13 @@ async function mutateSubProgress(fn) {
740
762
  await writeCurrentWorkflowUnlocked({ ...s, sub_progress: next });
741
763
  });
742
764
  }
765
+ async function mutateWorkflow(fn) {
766
+ await withLock(async () => {
767
+ const s = await readCurrentWorkflow();
768
+ if (!s) return;
769
+ await writeCurrentWorkflowUnlocked(fn(s));
770
+ });
771
+ }
743
772
  async function mutateStore(fn) {
744
773
  await withLock(async () => {
745
774
  const store = await readStoreRaw();
@@ -756,14 +785,14 @@ async function activate(phase, checkpointPath = null) {
756
785
  });
757
786
  }
758
787
  async function pause() {
759
- const s = await readCurrentWorkflow();
760
- if (!s) return;
761
- await writeCurrentWorkflow({ ...s, status: "paused", paused_at: (/* @__PURE__ */ new Date()).toISOString() });
788
+ await mutateWorkflow((s) => ({ ...s, status: "paused", paused_at: (/* @__PURE__ */ new Date()).toISOString() }));
762
789
  }
763
790
  async function complete() {
764
- const s = await readCurrentWorkflow();
765
- if (!s) return;
766
- await writeCurrentWorkflow({ ...s, status: "complete", completed_at: (/* @__PURE__ */ new Date()).toISOString() });
791
+ await mutateWorkflow((s) => ({
792
+ ...s,
793
+ status: "complete",
794
+ completed_at: (/* @__PURE__ */ new Date()).toISOString()
795
+ }));
767
796
  }
768
797
  var WorkflowStateError, LockHeldError;
769
798
  var init_state = __esm({
@@ -1411,7 +1440,7 @@ var init_installMethods = __esm({
1411
1440
  Type.Union([...branches]);
1412
1441
  }
1413
1442
  });
1414
- var TypeEnum, ComponentType, Verify, Uninstall, Stability, FallbackAction, UpstreamHealth, Platform, Signature, TestedWithVersions, Category, InstallType, DecisionRules, Phase, Triggers, ProvidedUnit, HarnessOverride, HarnessOverrides, SpecSchema;
1443
+ var TypeEnum, ComponentType, Verify, Uninstall, Stability, FallbackAction, UpstreamHealth, Platform, Signature, Category, InstallType, DecisionRules, Phase, Triggers, ProvidedUnit, HarnessOverride, HarnessOverrides, SpecSchema;
1415
1444
  var init_spec = __esm({
1416
1445
  "src/manifest/schema/spec.ts"() {
1417
1446
  init_installMethods();
@@ -1472,13 +1501,6 @@ var init_spec = __esm({
1472
1501
  { sigstore_bundle: Type.String({ format: "uri" }) },
1473
1502
  { additionalProperties: false }
1474
1503
  );
1475
- TestedWithVersions = Type.Object(
1476
- {
1477
- cc_versions: Type.Optional(Type.Array(Type.String())),
1478
- node_versions: Type.Optional(Type.Array(Type.String()))
1479
- },
1480
- { additionalProperties: false }
1481
- );
1482
1504
  Category = Type.Union([
1483
1505
  Type.Literal("meta"),
1484
1506
  Type.Literal("engineering"),
@@ -1566,8 +1588,15 @@ var init_spec = __esm({
1566
1588
  signed_by: Type.String({ pattern: "^[a-zA-Z0-9-]+$", minLength: 1 }),
1567
1589
  signature: Type.Optional(Signature),
1568
1590
  platforms: Type.Array(Platform, { minItems: 1, uniqueItems: true }),
1569
- tested_with_versions: Type.Optional(TestedWithVersions),
1570
- mutually_exclusive_with: Type.Optional(Type.Array(Type.String())),
1591
+ // Phase 61 — `tested_with_versions` and `mutually_exclusive_with` removed;
1592
+ // both were evaluated by nothing. `mutually_exclusive_with` is the sharper
1593
+ // lesson: schema'd and documented as "v0.2+ 启用", never wired, ZERO manifests
1594
+ // ever declared it — and when a real mutual exclusion appeared (ECC's bundled
1595
+ // chrome-devtools connector vs the standalone chrome-devtools-mcp manifest) it
1596
+ // was solved imperatively by hand in src/cli/lib/check-ecc.ts, with nothing
1597
+ // noticing the declarative mechanism for that exact job was sitting dead.
1598
+ // Re-introduce it only when a second real case exists AND the same commit
1599
+ // wires it; scripts/check-schema-consumers.mjs now fails CI otherwise.
1571
1600
  category: Category,
1572
1601
  install_type: InstallType,
1573
1602
  decision_rules: Type.Optional(DecisionRules),
@@ -1678,7 +1707,16 @@ function checkSecurityViolations(doc, filename, lineCounter) {
1678
1707
  const cmdPaths = [
1679
1708
  ["spec", "install", "cmd"],
1680
1709
  ["spec", "verify", "cmd"],
1681
- ["spec", "uninstall", "cmd"]
1710
+ ["spec", "uninstall", "cmd"],
1711
+ // `hook_command` is written verbatim into ~/.claude/settings.json and then
1712
+ // executed by Claude Code on EVERY matching lifecycle event — the most-run
1713
+ // command string a manifest can carry, and it was the one never screened:
1714
+ // `bash -c "$(curl …)"` validated clean.
1715
+ ["spec", "install", "hook_command"],
1716
+ // harness_overrides replaces the install/verify block wholesale on codex, so
1717
+ // its commands run exactly like the base ones and need the same screen.
1718
+ ["spec", "harness_overrides", "codex", "install", "cmd"],
1719
+ ["spec", "harness_overrides", "codex", "verify", "cmd"]
1682
1720
  ];
1683
1721
  for (const p7 of cmdPaths) {
1684
1722
  const err2 = checkScalarCmd(doc, lineCounter, p7, filename);
@@ -1807,7 +1845,10 @@ var init_validate = __esm({
1807
1845
  npm: ["npm-cli"],
1808
1846
  mcp: ["mcp-stdio-add", "mcp-http-add"],
1809
1847
  git: ["git-clone-with-setup"],
1810
- skill: ["cc-plugin-marketplace", "npx-skill-installer"]
1848
+ skill: ["cc-plugin-marketplace", "npx-skill-installer"],
1849
+ // 5th install_type (Phase 2.4). Missing here meant `install_type: hook` accepted
1850
+ // ANY method: an unconstrained bucket, not a closed one (external review L10).
1851
+ hook: ["cc-hook-add"]
1811
1852
  };
1812
1853
  }
1813
1854
  });
@@ -2109,15 +2150,22 @@ async function backup(plan, ctx) {
2109
2150
  entries.push({
2110
2151
  target: file.target,
2111
2152
  backup: "",
2112
- // sentinel: no backup written; rollback should unlink target
2153
+ // sentinel: no backup written; rollback removes the target
2113
2154
  sha1: "",
2114
- eol: "lf"
2155
+ eol: "lf",
2115
2156
  // moot for non-existent file; default to lf
2157
+ sentinel: "created"
2116
2158
  });
2117
2159
  continue;
2118
2160
  }
2119
2161
  if (code === "EISDIR") {
2120
- entries.push({ target: file.target, backup: "", sha1: "", eol: "lf" });
2162
+ entries.push({
2163
+ target: file.target,
2164
+ backup: "",
2165
+ sha1: "",
2166
+ eol: "lf",
2167
+ sentinel: "preexisting-dir"
2168
+ });
2121
2169
  continue;
2122
2170
  }
2123
2171
  return {
@@ -2198,6 +2246,12 @@ var init_ablation = __esm({
2198
2246
  });
2199
2247
 
2200
2248
  // src/manifest/lib/path-guard.ts
2249
+ function checkSafeSegment(input) {
2250
+ checkPathSafe(input);
2251
+ if (input === "" || input === "." || input === ".." || /[\\/]/.test(input)) {
2252
+ throw new PathTraversalError();
2253
+ }
2254
+ }
2201
2255
  function checkPathSafe(input) {
2202
2256
  for (const re of PATH_TRAVERSAL_PATTERNS) {
2203
2257
  if (re.test(input)) throw new PathTraversalError();
@@ -2409,7 +2463,22 @@ async function isMcpServerRegistered(name) {
2409
2463
  if (!servers || typeof servers !== "object") return false;
2410
2464
  return Object.hasOwn(servers, name);
2411
2465
  }
2466
+ function isPluginInToml(raw, pluginName) {
2467
+ const esc = (v) => v.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2468
+ const [plugin = "", market] = pluginName.split("@");
2469
+ const key = market ? `${esc(plugin)}@${esc(market)}` : `${esc(plugin)}(?:@[^"'\\]]+)?`;
2470
+ const re = new RegExp(`^\\s*\\[plugins\\.(?:"${key}"|'${key}')\\]`, "m");
2471
+ return re.test(raw);
2472
+ }
2412
2473
  async function isPluginRegistered(pluginName) {
2474
+ const platform = detectPlatform();
2475
+ if (platform.id === "codex") {
2476
+ try {
2477
+ return isPluginInToml(await readFile(platform.mcpConfigPath, "utf8"), pluginName);
2478
+ } catch {
2479
+ return false;
2480
+ }
2481
+ }
2413
2482
  const registryPath = getPluginsRegistry();
2414
2483
  if (registryPath !== null) {
2415
2484
  try {
@@ -3135,11 +3204,22 @@ Manual options:
3135
3204
  Exit code: ${fallback.exit_code}
3136
3205
  ${yamlShort}`;
3137
3206
  console.error(uxText);
3138
- process.exit(fallback.exit_code);
3139
- throw new Error("unreachable");
3207
+ throw new WorkflowHaltError(
3208
+ `ralph-loop max-iterations exceeded (${err2.iterations}/${ctx.maxIterations}) for ${ctx.workflowName} / phase ${ctx.phaseId}`,
3209
+ fallback.exit_code
3210
+ );
3140
3211
  }
3212
+ var WorkflowHaltError;
3141
3213
  var init_fallbackHandlers = __esm({
3142
3214
  "src/workflow/lib/fallbackHandlers.ts"() {
3215
+ WorkflowHaltError = class extends Error {
3216
+ constructor(message, exitCode) {
3217
+ super(message);
3218
+ this.exitCode = exitCode;
3219
+ this.name = "WorkflowHaltError";
3220
+ }
3221
+ exitCode;
3222
+ };
3143
3223
  }
3144
3224
  });
3145
3225
 
@@ -3533,20 +3613,25 @@ async function compactWorkflow() {
3533
3613
  phase: "(none)"
3534
3614
  };
3535
3615
  }
3536
- const r = compactLedger(wf.sub_progress ?? []);
3537
- if (r.evicted > 0) {
3538
- const prev = wf.compacted_summary;
3539
- await writeCurrentWorkflow({
3540
- ...wf,
3616
+ const probe = compactLedger(wf.sub_progress ?? []);
3617
+ if (probe.evicted === 0) return { ...probe, phase: wf.phase };
3618
+ let result = { ...probe, phase: wf.phase };
3619
+ await mutateWorkflow((cur) => {
3620
+ const r = compactLedger(cur.sub_progress ?? []);
3621
+ result = { ...r, phase: cur.phase };
3622
+ if (r.evicted === 0) return cur;
3623
+ const prev = cur.compacted_summary;
3624
+ return {
3625
+ ...cur,
3541
3626
  sub_progress: r.kept,
3542
3627
  compacted_summary: {
3543
3628
  evicted: (prev?.evicted ?? 0) + r.evicted,
3544
3629
  by_status: mergeCounts(prev?.by_status, r.by_status),
3545
3630
  last_at: (/* @__PURE__ */ new Date()).toISOString()
3546
3631
  }
3547
- });
3548
- }
3549
- return { ...r, phase: wf.phase };
3632
+ };
3633
+ });
3634
+ return result;
3550
3635
  }
3551
3636
  var DEFAULT_THRESHOLD_PCT, DEFAULT_CONTEXT_WINDOW;
3552
3637
  var init_compact = __esm({
@@ -3739,11 +3824,15 @@ var init_budget = __esm({
3739
3824
  var breakLoop_exports = {};
3740
3825
  __export(breakLoop_exports, {
3741
3826
  LOOP_THRESHOLD: () => LOOP_THRESHOLD,
3742
- detectLoop: () => detectLoop
3827
+ detectLoop: () => detectLoop,
3828
+ isSettled: () => isSettled
3743
3829
  });
3744
3830
  function detectLoop(ledger) {
3745
3831
  return ledger.filter((e) => (e.fail_count ?? 0) >= LOOP_THRESHOLD).map((e) => ({ sub: e.sub, count: e.fail_count }));
3746
3832
  }
3833
+ function isSettled(e) {
3834
+ return e.status === "done" || e.status === "skipped" || e.status === "rejected";
3835
+ }
3747
3836
  var LOOP_THRESHOLD;
3748
3837
  var init_breakLoop = __esm({
3749
3838
  "src/checkpoint/breakLoop.ts"() {
@@ -3980,11 +4069,12 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
3980
4069
  await mutateSubProgress2((e) => markIfSeeded(e, sub, "done", markOpts));
3981
4070
  await absorbIntentFor(sub);
3982
4071
  const { collectScaleMetrics: collectScaleMetrics2, assessScale: assessScale2 } = await Promise.resolve().then(() => (init_scale(), scale_exports));
3983
- const { readCurrentWorkflow: readCurrentWorkflow2, writeCurrentWorkflow: writeCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
4072
+ const { readCurrentWorkflow: readCurrentWorkflow2, mutateWorkflow: mutateWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
3984
4073
  const afterMark = await readCurrentWorkflow2();
3985
4074
  if (afterMark) {
3986
4075
  const metrics = await collectScaleMetrics2(process.cwd(), afterMark.sub_progress ?? []);
3987
- await writeCurrentWorkflow2({ ...afterMark, verify_mode: assessScale2(metrics) });
4076
+ const verifyMode = assessScale2(metrics);
4077
+ await mutateWorkflow2((s) => ({ ...s, verify_mode: verifyMode }));
3988
4078
  }
3989
4079
  const { nextPending: nextPending2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
3990
4080
  const allResolved = nextPending2(afterMark?.sub_progress ?? []) === null;
@@ -4021,7 +4111,7 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
4021
4111
  try {
4022
4112
  const { defaultShipReady: defaultShipReady2 } = await Promise.resolve().then(() => (init_shipReady(), shipReady_exports));
4023
4113
  const { incrementPhases: incrementPhases2, isRetroDue: isRetroDue2, retroThreshold: retroThreshold2 } = await Promise.resolve().then(() => (init_retroMeta(), retroMeta_exports));
4024
- const { mutateStore: mutateStore2, readCurrentWorkflow: readCurrentWorkflow3, writeCurrentWorkflow: writeCurrentWorkflow3 } = await Promise.resolve().then(() => (init_state(), state_exports));
4114
+ const { mutateStore: mutateStore2, mutateWorkflow: mutateWorkflow3 } = await Promise.resolve().then(() => (init_state(), state_exports));
4025
4115
  const { repoKey: repoKey2 } = await Promise.resolve().then(() => (init_workflowStore(), workflowStore_exports));
4026
4116
  const ship = defaultShipReady2(process.cwd());
4027
4117
  const key = repoKey2();
@@ -4034,15 +4124,12 @@ async function runCheckpointComplete(sub, opts, deps = defaultRunDeps) {
4034
4124
  retroDue = isRetroDue2(next.phases_since_retro, threshold);
4035
4125
  return { ...store, retro_meta: meta };
4036
4126
  });
4037
- const latest = await readCurrentWorkflow3();
4038
- if (latest) {
4039
- await writeCurrentWorkflow3({
4040
- ...latest,
4041
- ship_ready: ship.ready,
4042
- ship_commits: ship.commits,
4043
- retro_due: retroDue
4044
- });
4045
- }
4127
+ await mutateWorkflow3((s) => ({
4128
+ ...s,
4129
+ ship_ready: ship.ready,
4130
+ ship_commits: ship.commits,
4131
+ retro_due: retroDue
4132
+ }));
4046
4133
  } catch {
4047
4134
  }
4048
4135
  }
@@ -4124,7 +4211,7 @@ async function runCheckpointReopen(sub, opts, deps = defaultRunDeps) {
4124
4211
  deps.exit(1);
4125
4212
  return;
4126
4213
  }
4127
- const { readCurrentWorkflow: readCurrentWorkflow2, mutateSubProgress: mutateSubProgress2, writeCurrentWorkflow: writeCurrentWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
4214
+ const { readCurrentWorkflow: readCurrentWorkflow2, mutateWorkflow: mutateWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
4128
4215
  const wf = await readCurrentWorkflow2();
4129
4216
  if (!wf) {
4130
4217
  deps.error("[harnessed] checkpoint reopen: no active workflow \u2014 nothing to send back.");
@@ -4140,10 +4227,11 @@ async function runCheckpointReopen(sub, opts, deps = defaultRunDeps) {
4140
4227
  deps.exit(1);
4141
4228
  return;
4142
4229
  }
4143
- await mutateSubProgress2((e) => reopenSub2(e, sub, reason));
4144
- if (wf.status === "complete") {
4145
- await writeCurrentWorkflow2({ ...wf, status: "active" });
4146
- }
4230
+ await mutateWorkflow2((s) => ({
4231
+ ...s,
4232
+ sub_progress: reopenSub2(s.sub_progress ?? [], sub, reason),
4233
+ status: s.status === "complete" ? "active" : s.status
4234
+ }));
4147
4235
  const latest = await readCurrentWorkflow2();
4148
4236
  const entry = latest?.sub_progress?.find((e) => e.sub === sub);
4149
4237
  const attempts = entry?.fail_count ?? 0;
@@ -4591,8 +4679,8 @@ __export(aliases_exports, {
4591
4679
  });
4592
4680
  function loadAliases() {
4593
4681
  if (_cached) return _cached;
4594
- if (!existsSync(ALIASES_PATH)) return null;
4595
- const raw = readFileSync(ALIASES_PATH, "utf8");
4682
+ if (!existsSync(aliasesPath())) return null;
4683
+ const raw = readFileSync(aliasesPath(), "utf8");
4596
4684
  const parsed = parse(raw);
4597
4685
  if (!Value.Check(AliasesV1, parsed)) {
4598
4686
  const errs = [...Value.Errors(AliasesV1, parsed)].slice(0, 3);
@@ -4611,12 +4699,13 @@ function listDeprecations() {
4611
4699
  const a = loadAliases();
4612
4700
  return a ? Object.entries(a.aliases).map(([old, entry]) => ({ old, entry })) : [];
4613
4701
  }
4614
- var ALIASES_PATH, _cached;
4702
+ var aliasesPath, _cached;
4615
4703
  var init_aliases = __esm({
4616
4704
  "src/manifest/aliases.ts"() {
4705
+ init_assetsRoot();
4617
4706
  init_path_guard();
4618
4707
  init_aliases_v1();
4619
- ALIASES_PATH = join(process.cwd(), "manifests", "aliases.yaml");
4708
+ aliasesPath = () => join(getAssetsRoot(), "manifests", "aliases.yaml");
4620
4709
  _cached = null;
4621
4710
  }
4622
4711
  });
@@ -5407,6 +5496,13 @@ function npmExecutable() {
5407
5496
  return process.platform === "win32" ? "npm.cmd" : "npm";
5408
5497
  }
5409
5498
  async function defaultRunner() {
5499
+ if (process.platform === "win32") {
5500
+ const { stdout: stdout3 } = await execAsync("npm view harnessed version", {
5501
+ timeout: 8e3,
5502
+ windowsHide: true
5503
+ });
5504
+ return stdout3;
5505
+ }
5410
5506
  const { stdout: stdout2 } = await execFileAsync(npmExecutable(), ["view", "harnessed", "version"], {
5411
5507
  timeout: 8e3,
5412
5508
  windowsHide: true
@@ -5421,10 +5517,11 @@ async function fetchLatestVersion(runner = defaultRunner) {
5421
5517
  return null;
5422
5518
  }
5423
5519
  }
5424
- var execFileAsync;
5520
+ var execFileAsync, execAsync;
5425
5521
  var init_version_check = __esm({
5426
5522
  "src/cli/lib/version-check.ts"() {
5427
5523
  execFileAsync = promisify(execFile);
5524
+ execAsync = promisify(exec);
5428
5525
  }
5429
5526
  });
5430
5527
 
@@ -5565,7 +5662,12 @@ function joinFor(platform) {
5565
5662
  function realNpmPrefix() {
5566
5663
  try {
5567
5664
  if (typeof spawnSync !== "function") return null;
5568
- const r = spawnSync("npm", ["prefix", "-g"], { encoding: "utf8", timeout: 5e3 });
5665
+ const r = process.platform === "win32" ? spawnSync("npm prefix -g", {
5666
+ encoding: "utf8",
5667
+ timeout: 5e3,
5668
+ shell: true,
5669
+ windowsHide: true
5670
+ }) : spawnSync("npm", ["prefix", "-g"], { encoding: "utf8", timeout: 5e3 });
5569
5671
  if (!r || r.error || r.status !== 0) return null;
5570
5672
  const out = (r.stdout ?? "").trim();
5571
5673
  return out.length > 0 ? out : null;
@@ -6893,6 +6995,13 @@ __export(gc_exports, {
6893
6995
  gcCompiledArtifacts: () => gcCompiledArtifacts,
6894
6996
  registerGc: () => registerGc
6895
6997
  });
6998
+ function byVersion(a, b) {
6999
+ const c = compareVersions(a, b);
7000
+ if (c === "behind") return -1;
7001
+ if (c === "ahead") return 1;
7002
+ if (c === "current") return 0;
7003
+ return a.localeCompare(b);
7004
+ }
6896
7005
  async function gcCompiledArtifacts(opts) {
6897
7006
  const removed = [];
6898
7007
  const kept = [];
@@ -6913,7 +7022,7 @@ async function gcCompiledArtifacts(opts) {
6913
7022
  }
6914
7023
  try {
6915
7024
  const backupDir = join(opts.stateRoot, "bin-backup");
6916
- const vers = (await readdir(backupDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
7025
+ const vers = (await readdir(backupDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort(byVersion);
6917
7026
  for (const v of vers.slice(0, -1)) {
6918
7027
  const p7 = join(backupDir, v);
6919
7028
  removed.push(p7);
@@ -7048,6 +7157,7 @@ var init_gc = __esm({
7048
7157
  init_package();
7049
7158
  init_i18n();
7050
7159
  init_backup();
7160
+ init_version_check();
7051
7161
  DURATION_RE = /^(\d+)([dhmw])$/;
7052
7162
  }
7053
7163
  });
@@ -7273,6 +7383,7 @@ var init_state2 = __esm({
7273
7383
  var installCcHookAdd;
7274
7384
  var init_ccHookAdd2 = __esm({
7275
7385
  "src/installers/ccHookAdd.ts"() {
7386
+ init_security();
7276
7387
  init_assetsRoot();
7277
7388
  init_platform();
7278
7389
  init_backup();
@@ -7325,10 +7436,35 @@ var init_ccHookAdd2 = __esm({
7325
7436
  )
7326
7437
  };
7327
7438
  }
7439
+ if (settings === null || typeof settings !== "object" || Array.isArray(settings)) {
7440
+ return {
7441
+ ok: false,
7442
+ phase: "preflight",
7443
+ error: err(
7444
+ ctx,
7445
+ "/",
7446
+ `malformed settings.json: top-level value must be a JSON object, got ${settings === null ? "null" : Array.isArray(settings) ? "array" : typeof settings}`,
7447
+ "settings-json-malformed"
7448
+ )
7449
+ };
7450
+ }
7328
7451
  settings.hooks = settings.hooks ?? {};
7329
7452
  const ev = install.hook_event;
7330
7453
  const matcher = install.hook_matcher;
7331
7454
  const cmd = install.hook_command;
7455
+ const cmdViolation = checkCmdString(cmd);
7456
+ if (cmdViolation) {
7457
+ return {
7458
+ ok: false,
7459
+ phase: "preflight",
7460
+ error: err(
7461
+ ctx,
7462
+ "/spec/install/hook_command",
7463
+ `shell escape detected in hook_command: ${cmdViolation.label} (${cmdViolation.hint})`,
7464
+ "security-gate-bypass"
7465
+ )
7466
+ };
7467
+ }
7332
7468
  const cmdDeps = {
7333
7469
  assetsRoot: getAssetsRoot,
7334
7470
  exists: existsSync,
@@ -7339,7 +7475,8 @@ var init_ccHookAdd2 = __esm({
7339
7475
  const arr = settings.hooks[ev] ?? [];
7340
7476
  const ours = arr.filter((e) => entryMatchesRegistration(e, cmd, resolvedCmd, marker));
7341
7477
  if (ours.length === 1 && isDesiredHookEntry(ours[0] ?? {}, matcher, resolvedCmd)) {
7342
- return { ok: true, backupId: "idempotent-skip", appliedFiles: [] };
7478
+ await recordObservedInstall(ctx.cwd, ctx.manifest.metadata.name, "", "");
7479
+ return { ok: true, alreadyInstalled: true, backupId: "idempotent-skip" };
7343
7480
  }
7344
7481
  const others = arr.filter((e) => !entryMatchesRegistration(e, cmd, resolvedCmd, marker));
7345
7482
  settings.hooks[ev] = [...others, desiredHookEntry(matcher, resolvedCmd)];
@@ -7392,6 +7529,130 @@ var init_ccHookAdd2 = __esm({
7392
7529
  };
7393
7530
  }
7394
7531
  });
7532
+
7533
+ // src/installers/lib/gitCloneArgs.ts
7534
+ function parseGitCloneDest(cmd) {
7535
+ const idx = cmd.indexOf("git clone");
7536
+ if (idx < 0) return null;
7537
+ const tokens = cmd.slice(idx + "git clone".length).trim().split(/\s+/);
7538
+ let i = 0;
7539
+ while (i < tokens.length) {
7540
+ const t2 = tokens[i];
7541
+ if (t2 === "--") {
7542
+ i += 1;
7543
+ break;
7544
+ }
7545
+ if (!t2.startsWith("-")) break;
7546
+ if (t2.startsWith("--") && t2.includes("=")) i += 1;
7547
+ else if (VALUE_FLAGS.has(t2)) i += 2;
7548
+ else if (BARE_FLAGS.has(t2)) i += 1;
7549
+ else return null;
7550
+ }
7551
+ const url = tokens[i];
7552
+ const dest = tokens[i + 1];
7553
+ if (!url || CLAUSE_END.has(url)) return null;
7554
+ if (!dest || CLAUSE_END.has(dest)) return null;
7555
+ return { raw: dest, cloneIdx: idx };
7556
+ }
7557
+ var VALUE_FLAGS, BARE_FLAGS, CLAUSE_END;
7558
+ var init_gitCloneArgs = __esm({
7559
+ "src/installers/lib/gitCloneArgs.ts"() {
7560
+ VALUE_FLAGS = /* @__PURE__ */ new Set([
7561
+ "-b",
7562
+ "--branch",
7563
+ "--depth",
7564
+ "-o",
7565
+ "--origin",
7566
+ "-u",
7567
+ "--upload-pack",
7568
+ "--reference",
7569
+ "--reference-if-able",
7570
+ "--separate-git-dir",
7571
+ "-c",
7572
+ "--config",
7573
+ "--shallow-since",
7574
+ "--shallow-exclude",
7575
+ "-j",
7576
+ "--jobs",
7577
+ "--filter",
7578
+ "--template",
7579
+ "--server-option",
7580
+ "--bundle-uri",
7581
+ "--ref-format"
7582
+ ]);
7583
+ BARE_FLAGS = /* @__PURE__ */ new Set([
7584
+ "-q",
7585
+ "--quiet",
7586
+ "-v",
7587
+ "--verbose",
7588
+ "--progress",
7589
+ "-n",
7590
+ "--no-checkout",
7591
+ "--bare",
7592
+ "--mirror",
7593
+ "-l",
7594
+ "--local",
7595
+ "--no-local",
7596
+ "--no-hardlinks",
7597
+ "-s",
7598
+ "--shared",
7599
+ "--single-branch",
7600
+ "--no-single-branch",
7601
+ "--tags",
7602
+ "--no-tags",
7603
+ "--recursive",
7604
+ "--recurse-submodules",
7605
+ "--shallow-submodules",
7606
+ "--no-shallow-submodules",
7607
+ "--remote-submodules",
7608
+ "--no-remote-submodules",
7609
+ "--sparse",
7610
+ "--reject-shallow",
7611
+ "--no-reject-shallow",
7612
+ "--also-filter-submodules"
7613
+ ]);
7614
+ CLAUSE_END = /* @__PURE__ */ new Set(["&&", ";", "|", "||"]);
7615
+ }
7616
+ });
7617
+ function descendantsOf(pid) {
7618
+ const r = spawnSync("pgrep", ["-P", String(pid)], { encoding: "utf8", timeout: 2e3 });
7619
+ if (r.status !== 0 || typeof r.stdout !== "string") return [];
7620
+ const out = [];
7621
+ for (const tok2 of r.stdout.split(/\s+/)) {
7622
+ const child = Number(tok2);
7623
+ if (Number.isInteger(child) && child > 0) out.push(child, ...descendantsOf(child));
7624
+ }
7625
+ return out;
7626
+ }
7627
+ function killProcessTree(child) {
7628
+ const pid = child.pid;
7629
+ if (pid === void 0) {
7630
+ child.kill("SIGKILL");
7631
+ return;
7632
+ }
7633
+ if (process.platform === "win32") {
7634
+ const r = spawnSync("taskkill", ["/PID", String(pid), "/T", "/F"], {
7635
+ windowsHide: true,
7636
+ stdio: "ignore",
7637
+ timeout: 5e3
7638
+ });
7639
+ if (r.status === 0) return;
7640
+ child.kill("SIGKILL");
7641
+ return;
7642
+ }
7643
+ const tree = descendantsOf(pid);
7644
+ child.kill("SIGKILL");
7645
+ for (const d of tree) {
7646
+ try {
7647
+ process.kill(d, "SIGKILL");
7648
+ } catch {
7649
+ }
7650
+ }
7651
+ }
7652
+ var init_killTree = __esm({
7653
+ "src/installers/lib/killTree.ts"() {
7654
+ }
7655
+ });
7395
7656
  function evalClause(clause, home) {
7396
7657
  const m = clause.match(CLAUSE_RE);
7397
7658
  if (!m?.[1] || !m[2]) return null;
@@ -7542,10 +7803,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7542
7803
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
7543
7804
  stderr += chunk;
7544
7805
  });
7545
- return await new Promise((resolve24) => {
7806
+ return await new Promise((resolve23) => {
7546
7807
  const timer = setTimeout(() => {
7547
- child.kill("SIGKILL");
7548
- resolve24({
7808
+ killProcessTree(child);
7809
+ resolve23({
7549
7810
  ok: false,
7550
7811
  phase: "spawn",
7551
7812
  error: {
@@ -7566,7 +7827,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7566
7827
  child.on("error", (err2) => {
7567
7828
  clearTimeout(timer);
7568
7829
  const bashMissing = triedBash && err2.code === "ENOENT";
7569
- resolve24({
7830
+ resolve23({
7570
7831
  ok: false,
7571
7832
  phase: "spawn",
7572
7833
  error: {
@@ -7581,7 +7842,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7581
7842
  });
7582
7843
  child.on("close", (code) => {
7583
7844
  clearTimeout(timer);
7584
- resolve24({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
7845
+ resolve23({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
7585
7846
  });
7586
7847
  });
7587
7848
  }
@@ -7589,6 +7850,7 @@ var POSIX_SYNTAX_RE, POSIX_FIRST_TOKENS, DEFAULT_VERIFY_TIMEOUT_MS, DEFAULT_INST
7589
7850
  var init_spawn = __esm({
7590
7851
  "src/installers/lib/spawn.ts"() {
7591
7852
  init_security();
7853
+ init_killTree();
7592
7854
  init_nativeTest();
7593
7855
  init_resolveBash();
7594
7856
  init_safeCwd();
@@ -7631,16 +7893,8 @@ function extractSkillName(cmd, fallback) {
7631
7893
  return seg[seg.length - 1] ?? fallback;
7632
7894
  }
7633
7895
  function extractGitCloneTarget(cmd) {
7634
- const idx = cmd.indexOf("git clone");
7635
- if (idx < 0) return null;
7636
- const tail = cmd.slice(idx + "git clone".length).trim();
7637
- const tokens = tail.split(/\s+/);
7638
- let i = 0;
7639
- while (i < tokens.length && tokens[i]?.startsWith("-")) {
7640
- i += tokens[i]?.includes("=") ? 1 : 2;
7641
- }
7642
- const dest = tokens[i + 1];
7643
- if (!dest || dest === "&&" || dest === ";" || dest === "|") return null;
7896
+ const dest = parseGitCloneDest(cmd)?.raw;
7897
+ if (!dest) return null;
7644
7898
  if (dest.startsWith("~/")) return join(homedir(), dest.slice(2));
7645
7899
  if (dest.startsWith("/") || /^[A-Z]:[\\/]/i.test(dest)) return dest;
7646
7900
  return null;
@@ -7683,7 +7937,7 @@ async function detectNative(ctx) {
7683
7937
  }
7684
7938
  }
7685
7939
  if (method === "cc-plugin-marketplace") {
7686
- const m = cmd.match(/(?:claude\s+)?plugin\s+install\s+(\S+)/i);
7940
+ const m = cmd.match(/plugin\s+(?:install|add)\s+(?!marketplaceb)(\S+)/i);
7687
7941
  const pluginName = m?.[1]?.split("@")[0] ?? name;
7688
7942
  try {
7689
7943
  return await isPluginRegistered(pluginName);
@@ -7771,6 +8025,7 @@ var init_idempotent = __esm({
7771
8025
  init_assetsRoot();
7772
8026
  init_platform();
7773
8027
  init_binaryProbe();
8028
+ init_gitCloneArgs();
7774
8029
  init_hookEntry();
7775
8030
  init_readClaudeConfig();
7776
8031
  init_spawn();
@@ -7781,11 +8036,63 @@ var init_idempotent = __esm({
7781
8036
  };
7782
8037
  }
7783
8038
  });
8039
+ function escapeCommand(cmd) {
8040
+ return cmd.replace(META, "^$1");
8041
+ }
8042
+ function escapeArgument(arg, doubleEscape) {
8043
+ let a = `${arg}`;
8044
+ a = a.replace(/(\\*)"/g, '$1$1\\"');
8045
+ a = a.replace(/(\\*)$/, "$1$1");
8046
+ a = `"${a}"`;
8047
+ a = a.replace(META, "^$1");
8048
+ a = a.replace(META, "^$1");
8049
+ return a;
8050
+ }
8051
+ function resolveWindowsBin(bin, env = process.env, isFile = (p7) => existsSync(p7) && statSync(p7).isFile()) {
8052
+ const dirs = (env.PATH ?? env.Path ?? "").split(";").filter(Boolean);
8053
+ const exts = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
8054
+ const candidates = extname(bin) ? [""] : exts;
8055
+ for (const dir of dirs) {
8056
+ for (const ext of candidates) {
8057
+ const p7 = join40(dir, `${bin}${ext}`);
8058
+ if (isFile(p7)) return p7;
8059
+ }
8060
+ }
8061
+ return null;
8062
+ }
8063
+ function planWindowsSpawn(bin, args, resolved) {
8064
+ if (!resolved) return { command: bin, args, verbatim: false };
8065
+ const ext = extname(resolved).toLowerCase();
8066
+ if (ext !== ".cmd" && ext !== ".bat") {
8067
+ return { command: resolved, args, verbatim: false };
8068
+ }
8069
+ const line = [escapeCommand(resolved), ...args.map((a) => escapeArgument(a))].join(" ");
8070
+ return { command: "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
8071
+ }
8072
+ var extname, join40, META;
8073
+ var init_winSpawn = __esm({
8074
+ "src/installers/lib/winSpawn.ts"() {
8075
+ ({ extname, join: join40 } = win32);
8076
+ META = /([()\][%!^"`<>&|;, *?])/g;
8077
+ }
8078
+ });
7784
8079
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
7785
- return new Promise((resolve24) => {
8080
+ return new Promise((resolve23) => {
7786
8081
  const isWin = process.platform === "win32";
7787
8082
  const stdio = ["ignore", "pipe", "pipe"];
7788
- const child = isWin ? spawn("cmd.exe", ["/c", bin, ...args], { cwd, windowsHide: true, stdio }) : spawn(bin, args, { cwd, shell: false, stdio });
8083
+ let child;
8084
+ if (isWin) {
8085
+ const plan = planWindowsSpawn(bin, args, resolveWindowsBin(bin));
8086
+ child = spawn(plan.command, plan.args, {
8087
+ cwd,
8088
+ windowsHide: true,
8089
+ stdio,
8090
+ shell: false,
8091
+ windowsVerbatimArguments: plan.verbatim
8092
+ });
8093
+ } else {
8094
+ child = spawn(bin, args, { cwd, shell: false, stdio });
8095
+ }
7789
8096
  let stdout2 = "";
7790
8097
  let stderr = "";
7791
8098
  child.stdout?.setEncoding("utf8").on("data", (c) => {
@@ -7795,18 +8102,18 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
7795
8102
  stderr += c;
7796
8103
  });
7797
8104
  const timer = setTimeout(() => {
7798
- child.kill("SIGKILL");
7799
- resolve24({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
8105
+ killProcessTree(child);
8106
+ resolve23({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
7800
8107
  }, timeoutMs);
7801
8108
  child.on("error", (e) => {
7802
8109
  clearTimeout(timer);
7803
8110
  const enoent = e.code === "ENOENT";
7804
8111
  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;
7805
- resolve24({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
8112
+ resolve23({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
7806
8113
  });
7807
8114
  child.on("close", (code) => {
7808
8115
  clearTimeout(timer);
7809
- resolve24({ exitCode: code ?? -1, stdout: stdout2, stderr });
8116
+ resolve23({ exitCode: code ?? -1, stdout: stdout2, stderr });
7810
8117
  });
7811
8118
  });
7812
8119
  }
@@ -7815,6 +8122,8 @@ function runArgs(claudeArgs, cwd, timeoutMs = 15e3) {
7815
8122
  }
7816
8123
  var init_runClaudeArgs = __esm({
7817
8124
  "src/installers/lib/runClaudeArgs.ts"() {
8125
+ init_killTree();
8126
+ init_winSpawn();
7818
8127
  }
7819
8128
  });
7820
8129
 
@@ -7895,10 +8204,12 @@ var init_ccPluginMarketplace2 = __esm({
7895
8204
  };
7896
8205
  }
7897
8206
  const pluginName = parsed.pluginAtMkt.split("@")[0] ?? parsed.pluginAtMkt;
8207
+ const declaredRef = install.marketplace_source?.source === "github" ? install.marketplace_source.repo : null;
8208
+ const marketplaceRef = declaredRef ?? parsed.marketplaceRef;
7898
8209
  const installArgs = bin === "codex" ? ["plugin", "add", parsed.pluginAtMkt] : ["plugin", "install", parsed.pluginAtMkt, "--scope", "user"];
7899
8210
  const allArgs = [];
7900
- if (parsed.marketplaceRef !== null) {
7901
- allArgs.push(["plugin", "marketplace", "add", parsed.marketplaceRef]);
8211
+ if (marketplaceRef !== null) {
8212
+ allArgs.push(["plugin", "marketplace", "add", marketplaceRef]);
7902
8213
  }
7903
8214
  allArgs.push(installArgs);
7904
8215
  for (const argSet of allArgs) {
@@ -7944,12 +8255,8 @@ ${newEntry}
7944
8255
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
7945
8256
  const spawnCwd = install.cwd ?? getMcpSpawnCwd();
7946
8257
  let stepOneStderr = "";
7947
- if (parsed.marketplaceRef !== null) {
7948
- const r1 = await runHarnessArgs(
7949
- bin,
7950
- ["plugin", "marketplace", "add", parsed.marketplaceRef],
7951
- spawnCwd
7952
- );
8258
+ if (marketplaceRef !== null) {
8259
+ const r1 = await runHarnessArgs(bin, ["plugin", "marketplace", "add", marketplaceRef], spawnCwd);
7953
8260
  stepOneStderr = r1.stderr;
7954
8261
  }
7955
8262
  const r2 = await runHarnessArgs(bin, installArgs, spawnCwd, 6e4);
@@ -7967,13 +8274,7 @@ ${newEntry}
7967
8274
  )
7968
8275
  };
7969
8276
  }
7970
- let registered;
7971
- if (bin === "codex") {
7972
- const vr = await runHarnessArgs("codex", ["plugin", "list"], spawnCwd, 15e3);
7973
- registered = vr.exitCode === 0 && vr.stdout.includes(pluginName);
7974
- } else {
7975
- registered = await isPluginRegistered(pluginName);
7976
- }
8277
+ const registered = await isPluginRegistered(pluginName);
7977
8278
  if (!registered) {
7978
8279
  const cfgLabel = bin === "codex" ? "`codex plugin list` output" : "enabledPlugins map of ~/.claude.json";
7979
8280
  return {
@@ -8063,7 +8364,7 @@ var init_packSkillAudit = __esm({
8063
8364
  }
8064
8365
  });
8065
8366
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
8066
- return new Promise((resolve24) => {
8367
+ return new Promise((resolve23) => {
8067
8368
  const isWin = process.platform === "win32";
8068
8369
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
8069
8370
  let stdout2 = "";
@@ -8071,39 +8372,21 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
8071
8372
  stdout2 += c;
8072
8373
  });
8073
8374
  const timer = setTimeout(() => {
8074
- child.kill("SIGKILL");
8075
- resolve24({ sha: "", exit: -1 });
8375
+ killProcessTree(child);
8376
+ resolve23({ sha: "", exit: -1 });
8076
8377
  }, timeoutMs);
8077
8378
  child.on("error", () => {
8078
8379
  clearTimeout(timer);
8079
- resolve24({ sha: "", exit: -1 });
8380
+ resolve23({ sha: "", exit: -1 });
8080
8381
  });
8081
8382
  child.on("close", (code) => {
8082
8383
  clearTimeout(timer);
8083
- resolve24({ sha: stdout2.trim(), exit: code ?? -1 });
8384
+ resolve23({ sha: stdout2.trim(), exit: code ?? -1 });
8084
8385
  });
8085
8386
  });
8086
8387
  }
8087
8388
  function extractRawCloneDest(cmd) {
8088
- const idx = cmd.indexOf("git clone");
8089
- if (idx < 0) return null;
8090
- const tail = cmd.slice(idx + "git clone".length).trim();
8091
- const tokens = tail.split(/\s+/);
8092
- let i = 0;
8093
- while (i < tokens.length) {
8094
- const t2 = tokens[i];
8095
- if (t2 === void 0 || !t2.startsWith("-")) break;
8096
- if (t2 === "--depth" || t2 === "--branch" || t2 === "-b") {
8097
- i += 2;
8098
- } else if (t2.includes("=")) {
8099
- i += 1;
8100
- } else {
8101
- i += 2;
8102
- }
8103
- }
8104
- const dest = tokens[i + 1];
8105
- if (!dest || dest === "&&" || dest === ";" || dest === "|") return null;
8106
- return { raw: dest, cloneIdx: idx };
8389
+ return parseGitCloneDest(cmd);
8107
8390
  }
8108
8391
  function extractCloneTarget(cmd) {
8109
8392
  const parsed = extractRawCloneDest(cmd);
@@ -8135,7 +8418,9 @@ var init_gitCloneWithSetup2 = __esm({
8135
8418
  init_confirm();
8136
8419
  init_diff();
8137
8420
  init_err();
8421
+ init_gitCloneArgs();
8138
8422
  init_idempotent();
8423
+ init_killTree();
8139
8424
  init_packSkillAudit();
8140
8425
  init_preflight();
8141
8426
  init_spawn();
@@ -8962,11 +9247,32 @@ function resolveForHarness(manifest) {
8962
9247
  return { manifest, gate: null };
8963
9248
  }
8964
9249
  async function runInstall(manifest, opts) {
8965
- const resolved = resolveForHarness(manifest);
8966
- if (resolved.gate) return resolved.gate;
8967
- const effective = resolved.manifest;
8968
- const installer = installers[effective.spec.install.method];
8969
- return installer({ manifest: effective, opts, level: levelOf(effective), cwd: process.cwd() });
9250
+ try {
9251
+ const resolved = resolveForHarness(manifest);
9252
+ if (resolved.gate) return resolved.gate;
9253
+ const effective = resolved.manifest;
9254
+ const installer = installers[effective.spec.install.method];
9255
+ return await installer({
9256
+ manifest: effective,
9257
+ opts,
9258
+ level: levelOf(effective),
9259
+ cwd: process.cwd()
9260
+ });
9261
+ } catch (e) {
9262
+ const code = e.code;
9263
+ return {
9264
+ ok: false,
9265
+ phase: "spawn",
9266
+ error: {
9267
+ file: manifest.metadata.name,
9268
+ path: "/spec/install",
9269
+ message: `installer threw unexpectedly${code ? ` (${code})` : ""}: ${e.message ?? String(e)}`,
9270
+ line: null,
9271
+ column: null,
9272
+ keyword: "installer-exception"
9273
+ }
9274
+ };
9275
+ }
8970
9276
  }
8971
9277
  var installers, CLAUDE_ONLY_METHODS;
8972
9278
  var init_installers = __esm({
@@ -9053,8 +9359,9 @@ function getPinnedVersion(upstreamName, harnessedVer) {
9053
9359
  var versionsDir, _cache;
9054
9360
  var init_knownGood = __esm({
9055
9361
  "src/manifest/knownGood.ts"() {
9362
+ init_assetsRoot();
9056
9363
  init_known_good_v1();
9057
- versionsDir = () => join(process.cwd(), "versions");
9364
+ versionsDir = () => join(getAssetsRoot(), "versions");
9058
9365
  _cache = /* @__PURE__ */ new Map();
9059
9366
  }
9060
9367
  });
@@ -9214,7 +9521,7 @@ function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
9214
9521
  if (!wf) return "";
9215
9522
  const ledger = wf.sub_progress ?? [];
9216
9523
  const next = nextPending(ledger);
9217
- const loops = detectLoop(ledger);
9524
+ const loops = detectLoop(ledger.filter((e) => !isSettled(e)));
9218
9525
  const lines = [
9219
9526
  "<workflow-state>",
9220
9527
  `phase: ${wf.phase}`,
@@ -9249,6 +9556,7 @@ function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
9249
9556
  );
9250
9557
  }
9251
9558
  for (const e of ledger) {
9559
+ if (isSettled(e)) continue;
9252
9560
  const attempts = e.fail_count ?? 0;
9253
9561
  if (e.attempt_budget !== void 0 && attempts >= e.attempt_budget) {
9254
9562
  lines.push(
@@ -9326,9 +9634,11 @@ function findPhaseContextExcerpt(repoRoot, phase, budget) {
9326
9634
  try {
9327
9635
  const phasesDir = join(repoRoot, ".planning", "phases");
9328
9636
  if (!existsSync(phasesDir)) return null;
9637
+ const phaseNum = /(\d+(?:\.\d+)?)/.exec(phase)?.[1];
9638
+ if (phaseNum === void 0) return null;
9329
9639
  for (const dir of readdirSync(phasesDir)) {
9330
- const num = /^(\d+)/.exec(dir)?.[1];
9331
- if (!num || !phase.includes(num)) continue;
9640
+ const num = /^(\d+(?:\.\d+)?)/.exec(dir)?.[1];
9641
+ if (num === void 0 || Number(num) !== Number(phaseNum)) continue;
9332
9642
  const ctxFile = join(phasesDir, dir, `${num}-CONTEXT.md`);
9333
9643
  if (!existsSync(ctxFile)) continue;
9334
9644
  const body = readFileSync(ctxFile, "utf8");
@@ -10601,7 +10911,7 @@ function renderHumanTable(records) {
10601
10911
  }
10602
10912
  }
10603
10913
  function pipeToJq(filterExpr, lines) {
10604
- return new Promise((resolve24, reject) => {
10914
+ return new Promise((resolve23, reject) => {
10605
10915
  const child = spawn("jq", [filterExpr], {
10606
10916
  stdio: ["pipe", "inherit", "inherit"],
10607
10917
  windowsHide: true
@@ -10610,12 +10920,15 @@ function pipeToJq(filterExpr, lines) {
10610
10920
  const e = err2;
10611
10921
  if (e.code === "ENOENT") {
10612
10922
  console.error(t("audit_log.jq_missing"));
10613
- resolve24(1);
10923
+ resolve23(1);
10614
10924
  } else {
10615
10925
  reject(err2);
10616
10926
  }
10617
10927
  });
10618
- child.on("close", (code) => resolve24(code ?? 0));
10928
+ child.on("close", (code) => resolve23(code ?? 0));
10929
+ child.stdin.on("error", (err2) => {
10930
+ if (err2.code !== "EPIPE") reject(err2);
10931
+ });
10619
10932
  child.stdin.write(lines.join("\n"));
10620
10933
  child.stdin.end();
10621
10934
  });
@@ -11035,7 +11348,13 @@ function recordScenario(from, opts = {}) {
11035
11348
 
11036
11349
  // src/eval/runner.ts
11037
11350
  init_runDeps();
11038
- var TIMESTAMP_KEYS = /* @__PURE__ */ new Set(["started_at", "completed_at", "paused_at", "timestamp"]);
11351
+ var TIMESTAMP_KEYS = /* @__PURE__ */ new Set([
11352
+ "started_at",
11353
+ "completed_at",
11354
+ "paused_at",
11355
+ "updated_at",
11356
+ "timestamp"
11357
+ ]);
11039
11358
  function normalizeString(s, roots) {
11040
11359
  let out = s;
11041
11360
  for (const root of roots) {
@@ -11197,6 +11516,10 @@ function composeContext(seed, step) {
11197
11516
  async function execStep(scenario, step, repoDir) {
11198
11517
  if ("file" in step) {
11199
11518
  const target = resolve(repoDir, step.file.path);
11519
+ const rel = relative(repoDir, target);
11520
+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) {
11521
+ throw new Error(`file step path escapes the scenario repo: ${step.file.path}`);
11522
+ }
11200
11523
  mkdirSync(dirname(target), { recursive: true });
11201
11524
  writeFileSync(target, step.file.content ?? "", "utf8");
11202
11525
  if (step.file.mtime) {
@@ -11293,19 +11616,18 @@ async function runScenarioDir(dir, opts) {
11293
11616
  const prevRoot = process.env.HARNESSED_ROOT_OVERRIDE;
11294
11617
  const prevAssets = process.env.HARNESSED_ASSETS_OVERRIDE;
11295
11618
  const prevCeiling = process.env.GIT_CEILING_DIRECTORIES;
11296
- process.env.GIT_CEILING_DIRECTORIES = tmpdir();
11297
- process.env.HARNESSED_ROOT_OVERRIDE = stateRoot;
11298
- if (scenario.assets_dir) {
11299
- process.env.HARNESSED_ASSETS_OVERRIDE = isAbsolute(scenario.assets_dir) ? scenario.assets_dir : resolve(dir, scenario.assets_dir);
11300
- }
11301
- process.chdir(repoDir);
11302
- const { _clearJudgmentCache: _clearJudgmentCache2 } = await Promise.resolve().then(() => (init_judgmentResolver(), judgmentResolver_exports));
11303
- _clearJudgmentCache2();
11304
11619
  const steps = [];
11305
11620
  const evaluatedGateRefs = /* @__PURE__ */ new Set();
11306
11621
  let engineError = null;
11307
11622
  let workflow = null;
11308
11623
  try {
11624
+ process.env.GIT_CEILING_DIRECTORIES = tmpdir();
11625
+ process.env.HARNESSED_ROOT_OVERRIDE = stateRoot;
11626
+ if (scenario.assets_dir) {
11627
+ process.env.HARNESSED_ASSETS_OVERRIDE = isAbsolute(scenario.assets_dir) ? scenario.assets_dir : resolve(dir, scenario.assets_dir);
11628
+ }
11629
+ process.chdir(repoDir);
11630
+ (await Promise.resolve().then(() => (init_judgmentResolver(), judgmentResolver_exports)))._clearJudgmentCache();
11309
11631
  for (const step of scenario.steps) {
11310
11632
  const rec = await execStep(scenario, step, repoDir);
11311
11633
  steps.push(rec);
@@ -11331,7 +11653,11 @@ async function runScenarioDir(dir, opts) {
11331
11653
  else process.env.HARNESSED_ASSETS_OVERRIDE = prevAssets;
11332
11654
  if (prevCeiling === void 0) delete process.env.GIT_CEILING_DIRECTORIES;
11333
11655
  else process.env.GIT_CEILING_DIRECTORIES = prevCeiling;
11334
- _clearJudgmentCache2();
11656
+ try {
11657
+ ;
11658
+ (await Promise.resolve().then(() => (init_judgmentResolver(), judgmentResolver_exports)))._clearJudgmentCache();
11659
+ } catch {
11660
+ }
11335
11661
  }
11336
11662
  const cleanup = () => {
11337
11663
  rmSync(stateRoot, { recursive: true, force: true });
@@ -11393,15 +11719,22 @@ async function runEvalSuite(suiteDir, opts) {
11393
11719
  entries = [];
11394
11720
  }
11395
11721
  for (const dir of entries) {
11722
+ let raw;
11396
11723
  try {
11397
- readFileSync(join(dir, "scenario.yaml"));
11724
+ raw = readFileSync(join(dir, "scenario.yaml"), "utf8");
11398
11725
  } catch {
11399
11726
  continue;
11400
11727
  }
11401
- if (opts.filter && !dir.includes(opts.filter)) ;
11402
- const r = await runScenarioDir(dir, opts);
11403
- if (opts.filter && !r.name.includes(opts.filter) && !dir.includes(opts.filter)) continue;
11404
- results.push(r);
11728
+ if (opts.filter && !dir.includes(opts.filter)) {
11729
+ let name = "";
11730
+ try {
11731
+ const doc = parse(raw);
11732
+ name = typeof doc?.name === "string" ? doc.name : "";
11733
+ } catch {
11734
+ }
11735
+ if (!name.includes(opts.filter)) continue;
11736
+ }
11737
+ results.push(await runScenarioDir(dir, opts));
11405
11738
  }
11406
11739
  const summary = {
11407
11740
  pass: results.filter((r) => r.status === "PASS").length,
@@ -12183,6 +12516,7 @@ async function runHere(opts) {
12183
12516
 
12184
12517
  // src/cli/manifest-add.ts
12185
12518
  init_i18n();
12519
+ init_path_guard();
12186
12520
  var QA = [
12187
12521
  { q: "\u2460 \u662F\u771F reusable surface \u8FD8\u662F\u4E34\u65F6 wrapper?", f: "q1_reusable_surface" },
12188
12522
  { q: "\u2461 \u4E0A\u6E38\u540D\u5B57 fit \u9879\u76EE shape \u5417? \u6709\u73B0\u6709\u547D\u540D\u51B2\u7A81\u5417?", f: "q2_name_fit" },
@@ -12199,6 +12533,14 @@ function registerManifestAdd(program2) {
12199
12533
  ).option("--category <cat>", "manifest category (skill-packs | tools)", "skill-packs").option("--name <name>", "short adapter name (defaults to <upstream> basename)").option("--dry-run", "preview only \u2014 do not write JSON (opt-in for advanced users)").option("--non-interactive", "CI/scripts \u2014 WARN-only dry-run").action(async (upstream, raw) => {
12200
12534
  const name = raw.name ?? basename2(upstream);
12201
12535
  const category = raw.category ?? "skill-packs";
12536
+ try {
12537
+ checkSafeSegment(category);
12538
+ checkSafeSegment(name);
12539
+ } catch {
12540
+ console.error("error: invalid --category / --name (path traversal rejected)");
12541
+ process.exit(2);
12542
+ return;
12543
+ }
12202
12544
  const outPath = `manifests/${category}/${name}.ee5-answers.json`;
12203
12545
  if (raw.nonInteractive) {
12204
12546
  console.warn(t("manifest_add.non_interactive_warn"));
@@ -12280,6 +12622,7 @@ function resolveLocaleYaml(dir, baseName, locale = getLocale()) {
12280
12622
  }
12281
12623
 
12282
12624
  // src/cli/prompt.ts
12625
+ init_path_guard();
12283
12626
  init_assetsRoot();
12284
12627
  init_resolveYaml();
12285
12628
 
@@ -12402,44 +12745,6 @@ async function loadAllApplied(disciplines_applied, packageRoot) {
12402
12745
  return out;
12403
12746
  }
12404
12747
 
12405
- // src/discipline/enforcement/before-commit.ts
12406
- var TS_JS_RE = /\.(ts|tsx|js|mjs)$/;
12407
- async function runBeforeCommitHook(ctx) {
12408
- const d = await loadDiscipline("operational", ctx.packageRoot);
12409
- if (ctx.changedFiles.some((f) => TS_JS_RE.test(f))) {
12410
- const rule = d.rules.find((r) => r.id === "biome-preempt");
12411
- if (rule?.auto_fix_cmd) {
12412
- console.warn("\u26A0\uFE0F biome preempt \u2014 running auto-fix before commit");
12413
- execSync(rule.auto_fix_cmd, { cwd: ctx.packageRoot, stdio: "inherit" });
12414
- }
12415
- }
12416
- if (ctx.cmdArgs.includes("--no-verify")) {
12417
- console.error("\u274C no-skip-hooks violated: --no-verify forbidden");
12418
- process.exit(2);
12419
- }
12420
- if (ctx.changedFiles.some((f) => f.includes(".planning/STATE.md"))) {
12421
- const docD = await loadDiscipline("doc-discipline", ctx.packageRoot);
12422
- const rule = docD.rules.find((r) => r.id === "state-digest-line-limit");
12423
- if (rule?.enforcement === "halt") {
12424
- if (process.env.HARNESSED_ALLOW_LONG_STATE) {
12425
- console.warn(
12426
- "\u26A0\uFE0F doc-discipline: state-digest-line-limit override active (HARNESSED_ALLOW_LONG_STATE)"
12427
- );
12428
- } else {
12429
- const content = readFileSync(resolve(ctx.packageRoot, ".planning/STATE.md"), "utf8");
12430
- const lines = content.split(/\r?\n/);
12431
- const lineCount = lines[lines.length - 1] === "" ? lines.length - 1 : lines.length;
12432
- if (lineCount > 100) {
12433
- console.error(
12434
- `\u274C doc-discipline: STATE.md exceeds 100-line digest limit (current: ${lineCount} lines). Set HARNESSED_ALLOW_LONG_STATE=1 to override.`
12435
- );
12436
- process.exit(2);
12437
- }
12438
- }
12439
- }
12440
- }
12441
- }
12442
-
12443
12748
  // src/discipline/enforcement/before-phase-execute.ts
12444
12749
  async function loadDisciplinesForPhase(disciplines_applied, packageRoot) {
12445
12750
  return loadAllApplied(disciplines_applied, packageRoot);
@@ -12628,25 +12933,69 @@ var SpawnFailError = class extends Error {
12628
12933
  }
12629
12934
  lastMessage;
12630
12935
  };
12936
+ var DEFAULT_SPAWN_TIMEOUT_MS = 60 * 60 * 1e3;
12937
+ var SpawnTimeoutError = class extends Error {
12938
+ constructor(timeoutMs) {
12939
+ super(`sdkSpawn exceeded its ${timeoutMs}ms wall-clock timeout (HARNESSED_SPAWN_TIMEOUT_MS)`);
12940
+ this.timeoutMs = timeoutMs;
12941
+ this.name = "SpawnTimeoutError";
12942
+ }
12943
+ timeoutMs;
12944
+ };
12945
+ function envSpawnTimeoutMs() {
12946
+ const raw = Number.parseInt(process.env.HARNESSED_SPAWN_TIMEOUT_MS ?? "", 10);
12947
+ return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_SPAWN_TIMEOUT_MS;
12948
+ }
12631
12949
  async function sdkSpawn(def, opts) {
12632
12950
  const sdkDef = toSdkAgentDefinition(def);
12633
- const injectedPrompt = injectFactoryInternalFields(def, def.initialPrompt ?? def.prompt);
12951
+ const injectedPrompt = injectFactoryInternalFields(def, def.prompt);
12634
12952
  const queryOptions = {
12635
- allowedTools: ["Read", "Edit", "Write", "Grep", "Glob", "Bash", "Task"],
12953
+ // The prompt runs as the MAIN thread of this query, so the def's declared
12954
+ // limits must land on the query options; registering them only on the
12955
+ // `agents` entry (or rendering them into prompt text) enforces nothing.
12956
+ allowedTools: def.tools ?? ["Read", "Edit", "Write", "Grep", "Glob", "Bash", "Task"],
12957
+ ...def.disallowedTools?.length ? { disallowedTools: def.disallowedTools } : {},
12958
+ ...def.maxTurns ? { maxTurns: def.maxTurns } : {},
12959
+ // bypassPermissions additionally needs allowDangerouslySkipPermissions; a
12960
+ // manifest field must not be able to switch that on, so it is not forwarded.
12961
+ ...def.permissionMode && def.permissionMode !== "bypassPermissions" ? { permissionMode: def.permissionMode } : {},
12636
12962
  agents: { [opts.expertName]: sdkDef },
12637
12963
  // PRIMARY signal (B-02 / B-07 SC3) — structured output via json_schema.
12638
12964
  outputFormat: { type: "json_schema", schema: COMPLETION_SCHEMA }
12639
12965
  };
12640
12966
  if (opts.resumeSessionId) queryOptions.resume = opts.resumeSessionId;
12967
+ const timeoutMs = opts.timeoutMs ?? envSpawnTimeoutMs();
12968
+ const abortController = new AbortController();
12969
+ queryOptions.abortController = abortController;
12641
12970
  const q = query({ prompt: injectedPrompt, options: queryOptions });
12642
12971
  let result;
12643
- for await (const msg of q) {
12644
- if (msg.type === "system" && msg.subtype === "init") {
12645
- opts.onSessionId?.(msg.session_id);
12972
+ const consume = (async () => {
12973
+ for await (const msg of q) {
12974
+ if (msg.type === "system" && msg.subtype === "init") {
12975
+ opts.onSessionId?.(msg.session_id);
12976
+ }
12977
+ if (msg.type === "result") {
12978
+ result = msg;
12979
+ }
12646
12980
  }
12647
- if (msg.type === "result") {
12648
- result = msg;
12981
+ })();
12982
+ let timer;
12983
+ try {
12984
+ if (timeoutMs > 0) {
12985
+ const timedOut = new Promise((_, reject) => {
12986
+ timer = setTimeout(() => {
12987
+ abortController.abort();
12988
+ reject(new SpawnTimeoutError(timeoutMs));
12989
+ }, timeoutMs);
12990
+ });
12991
+ consume.catch(() => {
12992
+ });
12993
+ await Promise.race([consume, timedOut]);
12994
+ } else {
12995
+ await consume;
12649
12996
  }
12997
+ } finally {
12998
+ clearTimeout(timer);
12650
12999
  }
12651
13000
  if (!result) throw new SpawnFailError();
12652
13001
  const structuredOutput = "structured_output" in result ? result.structured_output : void 0;
@@ -12927,6 +13276,7 @@ function loadPhases(yamlPath, vars) {
12927
13276
  init_subAnchor();
12928
13277
  init_exprBuilder();
12929
13278
  init_judgmentResolver();
13279
+ init_fallbackHandlers();
12930
13280
  init_skipGate();
12931
13281
  init_skipSubs();
12932
13282
  function resolveMasterYamlPath2(masterName, packageRoot) {
@@ -12943,7 +13293,15 @@ function resolveSubYamlPath(masterName, subName, packageRoot) {
12943
13293
  }
12944
13294
  var defaultSpawnDriver = async (masterName, subName, _context, packageRoot) => {
12945
13295
  const subYamlPath = resolveSubYamlPath(masterName, subName, packageRoot);
12946
- const result = await runWorkflow(subYamlPath, {}, { packageRoot, gateContext: _context });
13296
+ const result = await runWorkflow(
13297
+ subYamlPath,
13298
+ {},
13299
+ {
13300
+ packageRoot,
13301
+ gateContext: _context,
13302
+ subOf: masterName
13303
+ }
13304
+ );
12947
13305
  if (result.status === "failed") {
12948
13306
  throw new Error(
12949
13307
  `sub-workflow ${masterName}/${subName} failed` + (result.lastPhaseId ? ` at phase ${result.lastPhaseId}` : "")
@@ -13148,9 +13506,12 @@ async function runMasterOrchestrator(masterName, context, packageRoot, spawnDriv
13148
13506
  ).filter((x) => x !== null);
13149
13507
  if (parallelFailures.length > 0) {
13150
13508
  const detail = parallelFailures.map((f) => `${f.sub}: ${f.reason instanceof Error ? f.reason.message : String(f.reason)}`).join("; ");
13151
- throw new Error(
13152
- `[${masterName} master] ${parallelFailures.length} parallel sub(s) failed \u2014 ${detail}`
13153
- );
13509
+ const message = `[${masterName} master] ${parallelFailures.length} parallel sub(s) failed \u2014 ${detail}`;
13510
+ const halts = parallelFailures.map((f) => f.reason).filter((r) => r instanceof WorkflowHaltError);
13511
+ if (halts.length > 0) {
13512
+ throw new WorkflowHaltError(message, Math.max(...halts.map((h) => h.exitCode)));
13513
+ }
13514
+ throw new Error(message);
13154
13515
  }
13155
13516
  for (const clause of serialTrailing) {
13156
13517
  console.log(` \u2192 ${clause.sub} (serial order=${clause.order ?? 0})`);
@@ -13358,8 +13719,16 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
13358
13719
  }
13359
13720
  const workflowName = parsed.workflow;
13360
13721
  const isMaster = "delegates_to" in parsed && Array.isArray(parsed.delegates_to) && parsed.delegates_to.length > 0 && MASTER_NAMES.includes(workflowName);
13722
+ const ownsRecord = opts.subOf === void 0;
13361
13723
  if (isMaster) {
13724
+ if (ownsRecord) await activatePhase(workflowName);
13362
13725
  const r = await runMasterOrchestrator(workflowName, gateContext, packageRoot);
13726
+ if (ownsRecord) {
13727
+ await completePhase({
13728
+ phaseId: workflowName,
13729
+ lastTask: `master ${workflowName} complete: ${r.fired.length} sub(s) fired`
13730
+ });
13731
+ }
13363
13732
  return {
13364
13733
  status: "complete",
13365
13734
  phasesRun: r.fired.length,
@@ -13376,11 +13745,18 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
13376
13745
  );
13377
13746
  }
13378
13747
  const skippedPhases = [];
13379
- const phases = parsed.phases ?? [];
13748
+ if (!Array.isArray(parsed.phases) || parsed.phases.length === 0) {
13749
+ const hasDelegates = "delegates_to" in parsed && Array.isArray(parsed.delegates_to) && parsed.delegates_to.length > 0;
13750
+ throw new Error(
13751
+ hasDelegates ? `workflow '${workflowName}' declares delegates_to but is not a master workflow (${MASTER_NAMES.join(", ")}), and has no phases \u2014 its delegates would be ignored` : `workflow '${workflowName}' has neither phases nor delegates_to \u2014 nothing would run`
13752
+ );
13753
+ }
13754
+ const phases = parsed.phases;
13380
13755
  for (let i = 0; i < phases.length; i++) {
13381
13756
  const ph = phases[i];
13382
13757
  if (!ph) continue;
13383
- await activatePhase(ph.id);
13758
+ if (ownsRecord) await activatePhase(ph.id);
13759
+ const transitionWorkflowComplete = ownsRecord && i === phases.length - 1;
13384
13760
  const invokesTools = "invokes_tools" in ph && Array.isArray(ph.invokes_tools) ? ph.invokes_tools : void 0;
13385
13761
  if (invokesTools && invokesTools.length > 1) {
13386
13762
  try {
@@ -13419,7 +13795,8 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
13419
13795
  skippedPhases.push(ph.id);
13420
13796
  await completePhase({
13421
13797
  phaseId: ph.id,
13422
- lastTask: `phase ${ph.id} skipped: gate ${ph.gate} evaluated false`
13798
+ lastTask: `phase ${ph.id} skipped: gate ${ph.gate} evaluated false`,
13799
+ transitionWorkflowComplete
13423
13800
  });
13424
13801
  continue;
13425
13802
  }
@@ -13435,6 +13812,11 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
13435
13812
  ...typeof gateContext.modelTierOverride === "string" ? { modelTierOverride: gateContext.modelTierOverride } : {}
13436
13813
  });
13437
13814
  if (r.status !== "ok") {
13815
+ await completePhase({
13816
+ phaseId: ph.id,
13817
+ lastTask: `FAILED: phase ${ph.id}: ${r.output}`,
13818
+ transitionWorkflowComplete: false
13819
+ });
13438
13820
  return { status: "failed", phasesRun: i, lastPhaseId: ph.id };
13439
13821
  }
13440
13822
  if (r.needsTeamsEscalation === true) {
@@ -13443,24 +13825,10 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
13443
13825
  `\u26A0\uFE0F phase ${ph.id} suggests Agent Teams escalation \u2014 ${reason}. Consider forming a team in your main Claude Code session (spawn background teammates with the Agent tool) if continuing this work benefits from teammate coordination. See workflows/judgments/parallelism-gate.yaml for the 5 upgrade triggers.`
13444
13826
  );
13445
13827
  }
13446
- if (r.triggers_commit === true) {
13447
- try {
13448
- await runBeforeCommitHook({
13449
- changedFiles: [],
13450
- cmdArgs: [],
13451
- packageRoot,
13452
- cmdType: "git-commit",
13453
- hasUserApproval: false
13454
- });
13455
- } catch (err2) {
13456
- console.warn(
13457
- `\u26A0\uFE0F phase ${ph.id} before-commit hook failed (${err2.message}); proceeding (ADR 0029 fail-soft).`
13458
- );
13459
- }
13460
- }
13461
13828
  await completePhase({
13462
13829
  phaseId: ph.id,
13463
- lastTask: `phase ${ph.id} complete: ${r.output}`
13830
+ lastTask: `phase ${ph.id} complete: ${r.output}`,
13831
+ transitionWorkflowComplete
13464
13832
  });
13465
13833
  }
13466
13834
  return {
@@ -13628,6 +13996,13 @@ function registerPrompt(program2) {
13628
13996
  program2.command("prompt").description(
13629
13997
  "Print a spawn-ready prompt for a sub-workflow (role + checklist + protocols, no spawn)."
13630
13998
  ).argument("<sub>", "sub-workflow name (e.g. task-code, verify-paranoid)").option("--task <text>", "task description prepended as a ## Task section").option("--json", "emit JSON {prompt, max_iterations, model, specialist} instead of text").action(async (sub, raw) => {
13999
+ try {
14000
+ checkSafeSegment(sub);
14001
+ } catch {
14002
+ console.error("error: invalid workflow name (path traversal rejected)");
14003
+ process.exit(2);
14004
+ return;
14005
+ }
13631
14006
  const packageRoot = getAssetsRoot();
13632
14007
  const workflowsDir = resolve(packageRoot, "workflows");
13633
14008
  const rolePrompts = await loadRolePrompts(workflowsDir);
@@ -13715,7 +14090,21 @@ function registerReleasePreflight(program2) {
13715
14090
  // src/cli/research.ts
13716
14091
  init_i18n();
13717
14092
  init_assetsRoot();
14093
+ init_fallbackHandlers();
13718
14094
  init_resolveYaml();
14095
+
14096
+ // src/cli/lib/nestedHarness.ts
14097
+ init_platform();
14098
+ function isNestedHarnessContext() {
14099
+ if (process.env.HARNESSED_ALLOW_NESTED === "1") return false;
14100
+ const sessEnv = detectPlatform().sessionIdEnv;
14101
+ if (!sessEnv) return false;
14102
+ const sid = process.env[sessEnv]?.trim();
14103
+ if (!sid) return false;
14104
+ return !process.stdin.isTTY;
14105
+ }
14106
+
14107
+ // src/cli/research.ts
13719
14108
  var PACKAGE_ROOT = getAssetsRoot();
13720
14109
  var WORKFLOWS_DIR = join(PACKAGE_ROOT, "workflows");
13721
14110
  function registerResearch(program2) {
@@ -13741,10 +14130,21 @@ function registerResearch(program2) {
13741
14130
  process.exit(0);
13742
14131
  return;
13743
14132
  }
14133
+ if (isNestedHarnessContext()) {
14134
+ console.error(
14135
+ "error: `harnessed research` is the CI/headless path (in-process SDK spawn) and hangs when invoked from inside a Claude Code session. Use the CC-native `/research` slash command instead. Set HARNESSED_ALLOW_NESTED=1 to override (CI / testing only)."
14136
+ );
14137
+ process.exit(1);
14138
+ return;
14139
+ }
13744
14140
  let result;
13745
14141
  try {
13746
14142
  result = await runWorkflow(yamlPath, {}, { packageRoot: PACKAGE_ROOT, gateContext });
13747
14143
  } catch (err2) {
14144
+ if (err2 instanceof WorkflowHaltError) {
14145
+ process.exit(err2.exitCode);
14146
+ return;
14147
+ }
13748
14148
  console.error(`error: workflow runtime failed \u2014 ${err2.message}`);
13749
14149
  process.exit(1);
13750
14150
  return;
@@ -13823,12 +14223,20 @@ function registerRetro(program2) {
13823
14223
  // src/cli/rollback.ts
13824
14224
  init_i18n();
13825
14225
  init_backup();
14226
+ init_path_guard();
13826
14227
  function normalizeEol(buf, eol) {
13827
14228
  const lf = buf.toString("utf8").replace(/\r\n/g, "\n");
13828
14229
  return Buffer.from(eol === "crlf" ? lf.replace(/\n/g, "\r\n") : lf, "utf8");
13829
14230
  }
13830
14231
  function registerRollback(program2) {
13831
14232
  program2.command("rollback <timestamp>").description("Restore files from a backup snapshot (preserves original LF/CRLF)").action(async (timestamp) => {
14233
+ try {
14234
+ checkSafeSegment(timestamp);
14235
+ } catch {
14236
+ console.error("error: invalid backup timestamp (path traversal rejected)");
14237
+ process.exit(2);
14238
+ return;
14239
+ }
13832
14240
  const dir = join(getBackupRoot(), timestamp);
13833
14241
  const metaPath = join(dir, "metadata.json");
13834
14242
  let meta;
@@ -13846,7 +14254,28 @@ ${t("rollback.metadata_unreadable.fix")}`
13846
14254
  const planned = [];
13847
14255
  for (const entry of ordered) {
13848
14256
  if (entry.backup === "") {
13849
- planned.push({ target: entry.target, action: "unlink" });
14257
+ if (entry.sentinel === "created") {
14258
+ planned.push({ target: entry.target, action: "remove-created" });
14259
+ } else if (entry.sentinel === "preexisting-dir") {
14260
+ planned.push({
14261
+ target: entry.target,
14262
+ action: "keep",
14263
+ why: "existed before install and could not be byte-backed-up; left untouched"
14264
+ });
14265
+ } else {
14266
+ let isDir = false;
14267
+ try {
14268
+ isDir = (await stat(entry.target)).isDirectory();
14269
+ } catch {
14270
+ }
14271
+ planned.push(
14272
+ isDir ? {
14273
+ target: entry.target,
14274
+ action: "keep",
14275
+ why: "directory from pre-sentinel backup metadata; origin unknown, not deleting"
14276
+ } : { target: entry.target, action: "unlink" }
14277
+ );
14278
+ }
13850
14279
  continue;
13851
14280
  }
13852
14281
  let buf;
@@ -13872,6 +14301,14 @@ ${t("rollback.metadata_unreadable.fix")}`
13872
14301
  planned.push({ target: entry.target, action: "write", data: normalizeEol(buf, entry.eol) });
13873
14302
  }
13874
14303
  for (const op of planned) {
14304
+ if (op.action === "keep") {
14305
+ console.warn(`[harnessed] rollback: ${op.target} \u2014 ${op.why}`);
14306
+ continue;
14307
+ }
14308
+ if (op.action === "remove-created") {
14309
+ await rm(op.target, { recursive: true, force: true });
14310
+ continue;
14311
+ }
13875
14312
  if (op.action === "unlink") {
13876
14313
  try {
13877
14314
  await unlink(op.target);
@@ -13894,7 +14331,7 @@ ${t("rollback.metadata_unreadable.fix")}`
13894
14331
  // src/cli/run.ts
13895
14332
  init_path_guard();
13896
14333
  init_assetsRoot();
13897
- init_platform();
14334
+ init_fallbackHandlers();
13898
14335
  init_resolveYaml();
13899
14336
 
13900
14337
  // src/cli/lib/extract-user-overrides.ts
@@ -13945,13 +14382,20 @@ var PACKAGE_ROOT2 = getAssetsRoot();
13945
14382
  var WORKFLOWS_DIR2 = join(PACKAGE_ROOT2, "workflows");
13946
14383
  var _autoChainCache = null;
13947
14384
  var _autoChainLoadFailed = false;
14385
+ function parseMaxIterations(v) {
14386
+ const n = Number(v);
14387
+ if (!/^\s*\d+\s*$/.test(v) || !Number.isInteger(n) || n < 1 || n > 100) {
14388
+ throw new InvalidArgumentError(`expected an integer between 1 and 100, got '${v}'`);
14389
+ }
14390
+ return n;
14391
+ }
13948
14392
  function registerRun(program2) {
13949
14393
  program2.command("run").description(
13950
14394
  "Run a harnessed workflow via in-process SDK spawn (CI/headless mode \u2014 blocks, no Agent Teams, no clarification round-trip). Slash commands use CC-native spawn via gates/prompt/checkpoint instead."
13951
14395
  ).argument("[name]", "workflow name (e.g. discuss, verify-paranoid, research, auto)").option("--task <text>", "task description (passed as workflow gateContext.task)").option("--task-stdin", "read task description from stdin until EOF (avoids shell-escape)").option(
13952
14396
  "--max-iterations <n>",
13953
- "SDK-path retry-loop max iter (default 20; honored Phase 3 onward)",
13954
- (v) => parseInt(v, 10)
14397
+ "SDK-path retry-loop max iter (default 20; integer 1-100)",
14398
+ parseMaxIterations
13955
14399
  ).option("--model <model>", "subagent model: 'haiku' | 'sonnet' | 'opus'").option(
13956
14400
  "--dry-run",
13957
14401
  "validate yaml load + walk runtime without spawning (Phase 1 default for verification)"
@@ -14033,6 +14477,10 @@ function registerRun(program2) {
14033
14477
  try {
14034
14478
  result = await runWorkflow(yamlPath, {}, { packageRoot: PACKAGE_ROOT2, gateContext });
14035
14479
  } catch (err2) {
14480
+ if (err2 instanceof WorkflowHaltError) {
14481
+ process.exit(err2.exitCode);
14482
+ return;
14483
+ }
14036
14484
  console.error(`error: workflow runtime failed \u2014 ${err2.message}`);
14037
14485
  process.exit(1);
14038
14486
  return;
@@ -14048,14 +14496,6 @@ function registerRun(program2) {
14048
14496
  process.exit(result.status === "failed" ? 1 : 0);
14049
14497
  });
14050
14498
  }
14051
- function isNestedHarnessContext() {
14052
- if (process.env.HARNESSED_ALLOW_NESTED === "1") return false;
14053
- const sessEnv = detectPlatform().sessionIdEnv;
14054
- if (!sessEnv) return false;
14055
- const sid = process.env[sessEnv]?.trim();
14056
- if (!sid) return false;
14057
- return !process.stdin.isTTY;
14058
- }
14059
14499
  async function listWorkflowNames(workflowsDir) {
14060
14500
  const names = [];
14061
14501
  const entries = await readdir(workflowsDir);
@@ -14510,7 +14950,7 @@ var V3_4_3_SIGNATURE_MASTER_RX = /\*\*Preferred path\*\*[\s\S]*dispatch to the p
14510
14950
  function shouldOverwriteFile(content) {
14511
14951
  return HARNESSED_MARKER_RX2.test(content) || V3_4_3_SIGNATURE_SUB_RX.test(content) || V3_4_3_SIGNATURE_MASTER_RX.test(content);
14512
14952
  }
14513
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync25 = (p7) => readFileSync(p7, "utf8")) {
14953
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync24 = (p7) => readFileSync(p7, "utf8")) {
14514
14954
  const results = [];
14515
14955
  const aggregatedWarnings = /* @__PURE__ */ new Set();
14516
14956
  for (const name of slashNames) {
@@ -14529,7 +14969,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
14529
14969
  if (fileExists2(path)) {
14530
14970
  let existing = "";
14531
14971
  try {
14532
- existing = readFileSync25(path);
14972
+ existing = readFileSync24(path);
14533
14973
  } catch {
14534
14974
  existing = "";
14535
14975
  }
@@ -14903,7 +15343,7 @@ async function printSetupVersionBanner() {
14903
15343
 
14904
15344
  // src/cli/setup.ts
14905
15345
  var KNOWN_PLATFORMS = ["claude", "codex"];
14906
- async function applyPlatformOption(platform) {
15346
+ async function applyPlatformOption(platform, persist) {
14907
15347
  if (!KNOWN_PLATFORMS.includes(platform)) {
14908
15348
  console.error(
14909
15349
  `--platform: unknown id '${platform}' (expected one of: ${KNOWN_PLATFORMS.join(" | ")})`
@@ -14911,10 +15351,11 @@ async function applyPlatformOption(platform) {
14911
15351
  process.exit(1);
14912
15352
  }
14913
15353
  process.env.HARNESSED_PLATFORM = platform;
14914
- const stateRoot = detectPlatform().stateRoot;
15354
+ if (!persist) return;
15355
+ const pinRoot = claudeDescriptor().stateRoot;
14915
15356
  try {
14916
- await mkdir(stateRoot, { recursive: true });
14917
- await writeFile(join(stateRoot, ".platform"), platform, "utf8");
15357
+ await mkdir(pinRoot, { recursive: true });
15358
+ await writeFile(join(pinRoot, ".platform"), platform, "utf8");
14918
15359
  } catch (e) {
14919
15360
  console.warn(` [--platform] could not persist .platform pin (${e.message})`);
14920
15361
  }
@@ -15028,7 +15469,7 @@ function registerSetup(program2) {
15028
15469
  ).action(async (raw) => {
15029
15470
  await printSetupVersionBanner();
15030
15471
  const dryRun = raw.dryRun === true;
15031
- if (raw.platform !== void 0) await applyPlatformOption(raw.platform);
15472
+ if (raw.platform !== void 0) await applyPlatformOption(raw.platform, !dryRun);
15032
15473
  const pkgRoot = getAssetsRoot();
15033
15474
  const workflowsDir = resolve(pkgRoot, "workflows");
15034
15475
  const skillsBase = getSkillsDir();
@@ -15662,7 +16103,7 @@ var uninstallNpmCli = async (ctx) => {
15662
16103
  const m = install.cmd.match(/npm\s+(?:install|i)\s+(?:-g\s+)?(\S+)/);
15663
16104
  const pkg = m?.[1] ?? ctx.manifest.metadata.upstream.source;
15664
16105
  const isWin = process.platform === "win32";
15665
- const result = await new Promise((resolve24) => {
16106
+ const result = await new Promise((resolve23) => {
15666
16107
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], { windowsHide: true }) : spawn("npm", ["uninstall", "-g", pkg], { shell: false });
15667
16108
  let stderr = "";
15668
16109
  child.stderr?.setEncoding("utf8").on("data", (c) => {
@@ -15670,15 +16111,15 @@ var uninstallNpmCli = async (ctx) => {
15670
16111
  });
15671
16112
  const timer = setTimeout(() => {
15672
16113
  child.kill("SIGKILL");
15673
- resolve24({ exitCode: -1, stderr: `${stderr}[timeout]` });
16114
+ resolve23({ exitCode: -1, stderr: `${stderr}[timeout]` });
15674
16115
  }, 3e4);
15675
16116
  child.on("error", (e) => {
15676
16117
  clearTimeout(timer);
15677
- resolve24({ exitCode: -1, stderr: e.message });
16118
+ resolve23({ exitCode: -1, stderr: e.message });
15678
16119
  });
15679
16120
  child.on("close", (code) => {
15680
16121
  clearTimeout(timer);
15681
- resolve24({ exitCode: code ?? -1, stderr });
16122
+ resolve23({ exitCode: code ?? -1, stderr });
15682
16123
  });
15683
16124
  });
15684
16125
  if (result.exitCode !== 0) {