harnessed 4.41.0 → 4.43.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.43.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
  });
@@ -1894,7 +1935,7 @@ var init_en = __esm({
1894
1935
  "setup.doctor_hint": "\nRun harnessed doctor to verify your environment.",
1895
1936
  "agent_teams.missing_header": "\n\u26A0\uFE0F Agent Teams not enabled \u2014 parallelism upgrade path unavailable",
1896
1937
  "agent_teams.missing_fix": " fix: claude config set env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS 1",
1897
- "agent_teams.missing_explanation": " harnessed task parallelism uses Subagent or Agent Teams (CC 2.1.133+)",
1938
+ "agent_teams.missing_explanation": " harnessed task parallelism uses Subagent or Agent Teams (CC 2.1.178+)",
1898
1939
  "agent_teams.missing_nonblocking": " non-blocking \u2014 auto-degrades to subagent fan-out\n",
1899
1940
  "install.manifest_not_found": "error: manifest '{{name}}' not found",
1900
1941
  "install.manifest_not_found.fix": " fix: ensure manifests/tools/{{name}}.yaml, manifests/skill-packs/{{name}}.yaml, or manifests/optional/{{name}}.yaml exists",
@@ -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
  });
@@ -4724,7 +4813,7 @@ async function checkAgentTeams() {
4724
4813
  detected,
4725
4814
  envValue,
4726
4815
  settingsValue,
4727
- remediation: 'Agent Teams not enabled. Add to ~/.claude/settings.json:\n "env": { "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1" }\nOR run: claude config set env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS 1\nOR export env var:\n export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1\nThen restart Claude Code (CC >= 2.1.133 required).'
4816
+ remediation: 'Agent Teams not enabled. Add to ~/.claude/settings.json:\n "env": { "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS": "1" }\nOR run: claude config set env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS 1\nOR export env var:\n export CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1\nThen restart Claude Code (CC >= 2.1.178 required).'
4728
4817
  };
4729
4818
  }
4730
4819
  var init_checkAgentTeams = __esm({
@@ -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;
@@ -6378,11 +6480,7 @@ var init_judgment = __esm({
6378
6480
  );
6379
6481
  FallbackRule = Type.Object(
6380
6482
  {
6381
- description: Type.Optional(Type.String()),
6382
- fallback_action: Type.Optional(Type.String()),
6383
- message_template: Type.Optional(Type.String()),
6384
- override_signal: Type.Optional(Type.Array(Type.String())),
6385
- chain_isolation: Type.Optional(Type.Boolean())
6483
+ description: Type.Optional(Type.String())
6386
6484
  },
6387
6485
  { additionalProperties: false }
6388
6486
  );
@@ -6893,6 +6991,13 @@ __export(gc_exports, {
6893
6991
  gcCompiledArtifacts: () => gcCompiledArtifacts,
6894
6992
  registerGc: () => registerGc
6895
6993
  });
6994
+ function byVersion(a, b) {
6995
+ const c = compareVersions(a, b);
6996
+ if (c === "behind") return -1;
6997
+ if (c === "ahead") return 1;
6998
+ if (c === "current") return 0;
6999
+ return a.localeCompare(b);
7000
+ }
6896
7001
  async function gcCompiledArtifacts(opts) {
6897
7002
  const removed = [];
6898
7003
  const kept = [];
@@ -6913,7 +7018,7 @@ async function gcCompiledArtifacts(opts) {
6913
7018
  }
6914
7019
  try {
6915
7020
  const backupDir = join(opts.stateRoot, "bin-backup");
6916
- const vers = (await readdir(backupDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort();
7021
+ const vers = (await readdir(backupDir, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name).sort(byVersion);
6917
7022
  for (const v of vers.slice(0, -1)) {
6918
7023
  const p7 = join(backupDir, v);
6919
7024
  removed.push(p7);
@@ -7048,6 +7153,7 @@ var init_gc = __esm({
7048
7153
  init_package();
7049
7154
  init_i18n();
7050
7155
  init_backup();
7156
+ init_version_check();
7051
7157
  DURATION_RE = /^(\d+)([dhmw])$/;
7052
7158
  }
7053
7159
  });
@@ -7273,6 +7379,7 @@ var init_state2 = __esm({
7273
7379
  var installCcHookAdd;
7274
7380
  var init_ccHookAdd2 = __esm({
7275
7381
  "src/installers/ccHookAdd.ts"() {
7382
+ init_security();
7276
7383
  init_assetsRoot();
7277
7384
  init_platform();
7278
7385
  init_backup();
@@ -7325,10 +7432,35 @@ var init_ccHookAdd2 = __esm({
7325
7432
  )
7326
7433
  };
7327
7434
  }
7435
+ if (settings === null || typeof settings !== "object" || Array.isArray(settings)) {
7436
+ return {
7437
+ ok: false,
7438
+ phase: "preflight",
7439
+ error: err(
7440
+ ctx,
7441
+ "/",
7442
+ `malformed settings.json: top-level value must be a JSON object, got ${settings === null ? "null" : Array.isArray(settings) ? "array" : typeof settings}`,
7443
+ "settings-json-malformed"
7444
+ )
7445
+ };
7446
+ }
7328
7447
  settings.hooks = settings.hooks ?? {};
7329
7448
  const ev = install.hook_event;
7330
7449
  const matcher = install.hook_matcher;
7331
7450
  const cmd = install.hook_command;
7451
+ const cmdViolation = checkCmdString(cmd);
7452
+ if (cmdViolation) {
7453
+ return {
7454
+ ok: false,
7455
+ phase: "preflight",
7456
+ error: err(
7457
+ ctx,
7458
+ "/spec/install/hook_command",
7459
+ `shell escape detected in hook_command: ${cmdViolation.label} (${cmdViolation.hint})`,
7460
+ "security-gate-bypass"
7461
+ )
7462
+ };
7463
+ }
7332
7464
  const cmdDeps = {
7333
7465
  assetsRoot: getAssetsRoot,
7334
7466
  exists: existsSync,
@@ -7339,7 +7471,8 @@ var init_ccHookAdd2 = __esm({
7339
7471
  const arr = settings.hooks[ev] ?? [];
7340
7472
  const ours = arr.filter((e) => entryMatchesRegistration(e, cmd, resolvedCmd, marker));
7341
7473
  if (ours.length === 1 && isDesiredHookEntry(ours[0] ?? {}, matcher, resolvedCmd)) {
7342
- return { ok: true, backupId: "idempotent-skip", appliedFiles: [] };
7474
+ await recordObservedInstall(ctx.cwd, ctx.manifest.metadata.name, "", "");
7475
+ return { ok: true, alreadyInstalled: true, backupId: "idempotent-skip" };
7343
7476
  }
7344
7477
  const others = arr.filter((e) => !entryMatchesRegistration(e, cmd, resolvedCmd, marker));
7345
7478
  settings.hooks[ev] = [...others, desiredHookEntry(matcher, resolvedCmd)];
@@ -7392,6 +7525,130 @@ var init_ccHookAdd2 = __esm({
7392
7525
  };
7393
7526
  }
7394
7527
  });
7528
+
7529
+ // src/installers/lib/gitCloneArgs.ts
7530
+ function parseGitCloneDest(cmd) {
7531
+ const idx = cmd.indexOf("git clone");
7532
+ if (idx < 0) return null;
7533
+ const tokens = cmd.slice(idx + "git clone".length).trim().split(/\s+/);
7534
+ let i = 0;
7535
+ while (i < tokens.length) {
7536
+ const t2 = tokens[i];
7537
+ if (t2 === "--") {
7538
+ i += 1;
7539
+ break;
7540
+ }
7541
+ if (!t2.startsWith("-")) break;
7542
+ if (t2.startsWith("--") && t2.includes("=")) i += 1;
7543
+ else if (VALUE_FLAGS.has(t2)) i += 2;
7544
+ else if (BARE_FLAGS.has(t2)) i += 1;
7545
+ else return null;
7546
+ }
7547
+ const url = tokens[i];
7548
+ const dest = tokens[i + 1];
7549
+ if (!url || CLAUSE_END.has(url)) return null;
7550
+ if (!dest || CLAUSE_END.has(dest)) return null;
7551
+ return { raw: dest, cloneIdx: idx };
7552
+ }
7553
+ var VALUE_FLAGS, BARE_FLAGS, CLAUSE_END;
7554
+ var init_gitCloneArgs = __esm({
7555
+ "src/installers/lib/gitCloneArgs.ts"() {
7556
+ VALUE_FLAGS = /* @__PURE__ */ new Set([
7557
+ "-b",
7558
+ "--branch",
7559
+ "--depth",
7560
+ "-o",
7561
+ "--origin",
7562
+ "-u",
7563
+ "--upload-pack",
7564
+ "--reference",
7565
+ "--reference-if-able",
7566
+ "--separate-git-dir",
7567
+ "-c",
7568
+ "--config",
7569
+ "--shallow-since",
7570
+ "--shallow-exclude",
7571
+ "-j",
7572
+ "--jobs",
7573
+ "--filter",
7574
+ "--template",
7575
+ "--server-option",
7576
+ "--bundle-uri",
7577
+ "--ref-format"
7578
+ ]);
7579
+ BARE_FLAGS = /* @__PURE__ */ new Set([
7580
+ "-q",
7581
+ "--quiet",
7582
+ "-v",
7583
+ "--verbose",
7584
+ "--progress",
7585
+ "-n",
7586
+ "--no-checkout",
7587
+ "--bare",
7588
+ "--mirror",
7589
+ "-l",
7590
+ "--local",
7591
+ "--no-local",
7592
+ "--no-hardlinks",
7593
+ "-s",
7594
+ "--shared",
7595
+ "--single-branch",
7596
+ "--no-single-branch",
7597
+ "--tags",
7598
+ "--no-tags",
7599
+ "--recursive",
7600
+ "--recurse-submodules",
7601
+ "--shallow-submodules",
7602
+ "--no-shallow-submodules",
7603
+ "--remote-submodules",
7604
+ "--no-remote-submodules",
7605
+ "--sparse",
7606
+ "--reject-shallow",
7607
+ "--no-reject-shallow",
7608
+ "--also-filter-submodules"
7609
+ ]);
7610
+ CLAUSE_END = /* @__PURE__ */ new Set(["&&", ";", "|", "||"]);
7611
+ }
7612
+ });
7613
+ function descendantsOf(pid) {
7614
+ const r = spawnSync("pgrep", ["-P", String(pid)], { encoding: "utf8", timeout: 2e3 });
7615
+ if (r.status !== 0 || typeof r.stdout !== "string") return [];
7616
+ const out = [];
7617
+ for (const tok2 of r.stdout.split(/\s+/)) {
7618
+ const child = Number(tok2);
7619
+ if (Number.isInteger(child) && child > 0) out.push(child, ...descendantsOf(child));
7620
+ }
7621
+ return out;
7622
+ }
7623
+ function killProcessTree(child) {
7624
+ const pid = child.pid;
7625
+ if (pid === void 0) {
7626
+ child.kill("SIGKILL");
7627
+ return;
7628
+ }
7629
+ if (process.platform === "win32") {
7630
+ const r = spawnSync("taskkill", ["/PID", String(pid), "/T", "/F"], {
7631
+ windowsHide: true,
7632
+ stdio: "ignore",
7633
+ timeout: 5e3
7634
+ });
7635
+ if (r.status === 0) return;
7636
+ child.kill("SIGKILL");
7637
+ return;
7638
+ }
7639
+ const tree = descendantsOf(pid);
7640
+ child.kill("SIGKILL");
7641
+ for (const d of tree) {
7642
+ try {
7643
+ process.kill(d, "SIGKILL");
7644
+ } catch {
7645
+ }
7646
+ }
7647
+ }
7648
+ var init_killTree = __esm({
7649
+ "src/installers/lib/killTree.ts"() {
7650
+ }
7651
+ });
7395
7652
  function evalClause(clause, home) {
7396
7653
  const m = clause.match(CLAUSE_RE);
7397
7654
  if (!m?.[1] || !m[2]) return null;
@@ -7542,10 +7799,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7542
7799
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
7543
7800
  stderr += chunk;
7544
7801
  });
7545
- return await new Promise((resolve24) => {
7802
+ return await new Promise((resolve23) => {
7546
7803
  const timer = setTimeout(() => {
7547
- child.kill("SIGKILL");
7548
- resolve24({
7804
+ killProcessTree(child);
7805
+ resolve23({
7549
7806
  ok: false,
7550
7807
  phase: "spawn",
7551
7808
  error: {
@@ -7566,7 +7823,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7566
7823
  child.on("error", (err2) => {
7567
7824
  clearTimeout(timer);
7568
7825
  const bashMissing = triedBash && err2.code === "ENOENT";
7569
- resolve24({
7826
+ resolve23({
7570
7827
  ok: false,
7571
7828
  phase: "spawn",
7572
7829
  error: {
@@ -7581,7 +7838,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
7581
7838
  });
7582
7839
  child.on("close", (code) => {
7583
7840
  clearTimeout(timer);
7584
- resolve24({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
7841
+ resolve23({ ok: true, exitCode: code ?? -1, stdout: stdout2, stderr });
7585
7842
  });
7586
7843
  });
7587
7844
  }
@@ -7589,6 +7846,7 @@ var POSIX_SYNTAX_RE, POSIX_FIRST_TOKENS, DEFAULT_VERIFY_TIMEOUT_MS, DEFAULT_INST
7589
7846
  var init_spawn = __esm({
7590
7847
  "src/installers/lib/spawn.ts"() {
7591
7848
  init_security();
7849
+ init_killTree();
7592
7850
  init_nativeTest();
7593
7851
  init_resolveBash();
7594
7852
  init_safeCwd();
@@ -7631,16 +7889,8 @@ function extractSkillName(cmd, fallback) {
7631
7889
  return seg[seg.length - 1] ?? fallback;
7632
7890
  }
7633
7891
  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;
7892
+ const dest = parseGitCloneDest(cmd)?.raw;
7893
+ if (!dest) return null;
7644
7894
  if (dest.startsWith("~/")) return join(homedir(), dest.slice(2));
7645
7895
  if (dest.startsWith("/") || /^[A-Z]:[\\/]/i.test(dest)) return dest;
7646
7896
  return null;
@@ -7683,7 +7933,7 @@ async function detectNative(ctx) {
7683
7933
  }
7684
7934
  }
7685
7935
  if (method === "cc-plugin-marketplace") {
7686
- const m = cmd.match(/(?:claude\s+)?plugin\s+install\s+(\S+)/i);
7936
+ const m = cmd.match(/plugin\s+(?:install|add)\s+(?!marketplaceb)(\S+)/i);
7687
7937
  const pluginName = m?.[1]?.split("@")[0] ?? name;
7688
7938
  try {
7689
7939
  return await isPluginRegistered(pluginName);
@@ -7771,6 +8021,7 @@ var init_idempotent = __esm({
7771
8021
  init_assetsRoot();
7772
8022
  init_platform();
7773
8023
  init_binaryProbe();
8024
+ init_gitCloneArgs();
7774
8025
  init_hookEntry();
7775
8026
  init_readClaudeConfig();
7776
8027
  init_spawn();
@@ -7781,11 +8032,63 @@ var init_idempotent = __esm({
7781
8032
  };
7782
8033
  }
7783
8034
  });
8035
+ function escapeCommand(cmd) {
8036
+ return cmd.replace(META, "^$1");
8037
+ }
8038
+ function escapeArgument(arg, doubleEscape) {
8039
+ let a = `${arg}`;
8040
+ a = a.replace(/(\\*)"/g, '$1$1\\"');
8041
+ a = a.replace(/(\\*)$/, "$1$1");
8042
+ a = `"${a}"`;
8043
+ a = a.replace(META, "^$1");
8044
+ a = a.replace(META, "^$1");
8045
+ return a;
8046
+ }
8047
+ function resolveWindowsBin(bin, env = process.env, isFile = (p7) => existsSync(p7) && statSync(p7).isFile()) {
8048
+ const dirs = (env.PATH ?? env.Path ?? "").split(";").filter(Boolean);
8049
+ const exts = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
8050
+ const candidates = extname(bin) ? [""] : exts;
8051
+ for (const dir of dirs) {
8052
+ for (const ext of candidates) {
8053
+ const p7 = join40(dir, `${bin}${ext}`);
8054
+ if (isFile(p7)) return p7;
8055
+ }
8056
+ }
8057
+ return null;
8058
+ }
8059
+ function planWindowsSpawn(bin, args, resolved) {
8060
+ if (!resolved) return { command: bin, args, verbatim: false };
8061
+ const ext = extname(resolved).toLowerCase();
8062
+ if (ext !== ".cmd" && ext !== ".bat") {
8063
+ return { command: resolved, args, verbatim: false };
8064
+ }
8065
+ const line = [escapeCommand(resolved), ...args.map((a) => escapeArgument(a))].join(" ");
8066
+ return { command: "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
8067
+ }
8068
+ var extname, join40, META;
8069
+ var init_winSpawn = __esm({
8070
+ "src/installers/lib/winSpawn.ts"() {
8071
+ ({ extname, join: join40 } = win32);
8072
+ META = /([()\][%!^"`<>&|;, *?])/g;
8073
+ }
8074
+ });
7784
8075
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
7785
- return new Promise((resolve24) => {
8076
+ return new Promise((resolve23) => {
7786
8077
  const isWin = process.platform === "win32";
7787
8078
  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 });
8079
+ let child;
8080
+ if (isWin) {
8081
+ const plan = planWindowsSpawn(bin, args, resolveWindowsBin(bin));
8082
+ child = spawn(plan.command, plan.args, {
8083
+ cwd,
8084
+ windowsHide: true,
8085
+ stdio,
8086
+ shell: false,
8087
+ windowsVerbatimArguments: plan.verbatim
8088
+ });
8089
+ } else {
8090
+ child = spawn(bin, args, { cwd, shell: false, stdio });
8091
+ }
7789
8092
  let stdout2 = "";
7790
8093
  let stderr = "";
7791
8094
  child.stdout?.setEncoding("utf8").on("data", (c) => {
@@ -7795,18 +8098,18 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3) {
7795
8098
  stderr += c;
7796
8099
  });
7797
8100
  const timer = setTimeout(() => {
7798
- child.kill("SIGKILL");
7799
- resolve24({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
8101
+ killProcessTree(child);
8102
+ resolve23({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
7800
8103
  }, timeoutMs);
7801
8104
  child.on("error", (e) => {
7802
8105
  clearTimeout(timer);
7803
8106
  const enoent = e.code === "ENOENT";
7804
8107
  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}` });
8108
+ resolve23({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
7806
8109
  });
7807
8110
  child.on("close", (code) => {
7808
8111
  clearTimeout(timer);
7809
- resolve24({ exitCode: code ?? -1, stdout: stdout2, stderr });
8112
+ resolve23({ exitCode: code ?? -1, stdout: stdout2, stderr });
7810
8113
  });
7811
8114
  });
7812
8115
  }
@@ -7815,6 +8118,8 @@ function runArgs(claudeArgs, cwd, timeoutMs = 15e3) {
7815
8118
  }
7816
8119
  var init_runClaudeArgs = __esm({
7817
8120
  "src/installers/lib/runClaudeArgs.ts"() {
8121
+ init_killTree();
8122
+ init_winSpawn();
7818
8123
  }
7819
8124
  });
7820
8125
 
@@ -7895,10 +8200,12 @@ var init_ccPluginMarketplace2 = __esm({
7895
8200
  };
7896
8201
  }
7897
8202
  const pluginName = parsed.pluginAtMkt.split("@")[0] ?? parsed.pluginAtMkt;
8203
+ const declaredRef = install.marketplace_source?.source === "github" ? install.marketplace_source.repo : null;
8204
+ const marketplaceRef = declaredRef ?? parsed.marketplaceRef;
7898
8205
  const installArgs = bin === "codex" ? ["plugin", "add", parsed.pluginAtMkt] : ["plugin", "install", parsed.pluginAtMkt, "--scope", "user"];
7899
8206
  const allArgs = [];
7900
- if (parsed.marketplaceRef !== null) {
7901
- allArgs.push(["plugin", "marketplace", "add", parsed.marketplaceRef]);
8207
+ if (marketplaceRef !== null) {
8208
+ allArgs.push(["plugin", "marketplace", "add", marketplaceRef]);
7902
8209
  }
7903
8210
  allArgs.push(installArgs);
7904
8211
  for (const argSet of allArgs) {
@@ -7944,12 +8251,8 @@ ${newEntry}
7944
8251
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
7945
8252
  const spawnCwd = install.cwd ?? getMcpSpawnCwd();
7946
8253
  let stepOneStderr = "";
7947
- if (parsed.marketplaceRef !== null) {
7948
- const r1 = await runHarnessArgs(
7949
- bin,
7950
- ["plugin", "marketplace", "add", parsed.marketplaceRef],
7951
- spawnCwd
7952
- );
8254
+ if (marketplaceRef !== null) {
8255
+ const r1 = await runHarnessArgs(bin, ["plugin", "marketplace", "add", marketplaceRef], spawnCwd);
7953
8256
  stepOneStderr = r1.stderr;
7954
8257
  }
7955
8258
  const r2 = await runHarnessArgs(bin, installArgs, spawnCwd, 6e4);
@@ -7967,13 +8270,7 @@ ${newEntry}
7967
8270
  )
7968
8271
  };
7969
8272
  }
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
- }
8273
+ const registered = await isPluginRegistered(pluginName);
7977
8274
  if (!registered) {
7978
8275
  const cfgLabel = bin === "codex" ? "`codex plugin list` output" : "enabledPlugins map of ~/.claude.json";
7979
8276
  return {
@@ -8063,7 +8360,7 @@ var init_packSkillAudit = __esm({
8063
8360
  }
8064
8361
  });
8065
8362
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
8066
- return new Promise((resolve24) => {
8363
+ return new Promise((resolve23) => {
8067
8364
  const isWin = process.platform === "win32";
8068
8365
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
8069
8366
  let stdout2 = "";
@@ -8071,39 +8368,21 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
8071
8368
  stdout2 += c;
8072
8369
  });
8073
8370
  const timer = setTimeout(() => {
8074
- child.kill("SIGKILL");
8075
- resolve24({ sha: "", exit: -1 });
8371
+ killProcessTree(child);
8372
+ resolve23({ sha: "", exit: -1 });
8076
8373
  }, timeoutMs);
8077
8374
  child.on("error", () => {
8078
8375
  clearTimeout(timer);
8079
- resolve24({ sha: "", exit: -1 });
8376
+ resolve23({ sha: "", exit: -1 });
8080
8377
  });
8081
8378
  child.on("close", (code) => {
8082
8379
  clearTimeout(timer);
8083
- resolve24({ sha: stdout2.trim(), exit: code ?? -1 });
8380
+ resolve23({ sha: stdout2.trim(), exit: code ?? -1 });
8084
8381
  });
8085
8382
  });
8086
8383
  }
8087
8384
  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 };
8385
+ return parseGitCloneDest(cmd);
8107
8386
  }
8108
8387
  function extractCloneTarget(cmd) {
8109
8388
  const parsed = extractRawCloneDest(cmd);
@@ -8135,7 +8414,9 @@ var init_gitCloneWithSetup2 = __esm({
8135
8414
  init_confirm();
8136
8415
  init_diff();
8137
8416
  init_err();
8417
+ init_gitCloneArgs();
8138
8418
  init_idempotent();
8419
+ init_killTree();
8139
8420
  init_packSkillAudit();
8140
8421
  init_preflight();
8141
8422
  init_spawn();
@@ -8962,11 +9243,32 @@ function resolveForHarness(manifest) {
8962
9243
  return { manifest, gate: null };
8963
9244
  }
8964
9245
  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() });
9246
+ try {
9247
+ const resolved = resolveForHarness(manifest);
9248
+ if (resolved.gate) return resolved.gate;
9249
+ const effective = resolved.manifest;
9250
+ const installer = installers[effective.spec.install.method];
9251
+ return await installer({
9252
+ manifest: effective,
9253
+ opts,
9254
+ level: levelOf(effective),
9255
+ cwd: process.cwd()
9256
+ });
9257
+ } catch (e) {
9258
+ const code = e.code;
9259
+ return {
9260
+ ok: false,
9261
+ phase: "spawn",
9262
+ error: {
9263
+ file: manifest.metadata.name,
9264
+ path: "/spec/install",
9265
+ message: `installer threw unexpectedly${code ? ` (${code})` : ""}: ${e.message ?? String(e)}`,
9266
+ line: null,
9267
+ column: null,
9268
+ keyword: "installer-exception"
9269
+ }
9270
+ };
9271
+ }
8970
9272
  }
8971
9273
  var installers, CLAUDE_ONLY_METHODS;
8972
9274
  var init_installers = __esm({
@@ -9053,8 +9355,9 @@ function getPinnedVersion(upstreamName, harnessedVer) {
9053
9355
  var versionsDir, _cache;
9054
9356
  var init_knownGood = __esm({
9055
9357
  "src/manifest/knownGood.ts"() {
9358
+ init_assetsRoot();
9056
9359
  init_known_good_v1();
9057
- versionsDir = () => join(process.cwd(), "versions");
9360
+ versionsDir = () => join(getAssetsRoot(), "versions");
9058
9361
  _cache = /* @__PURE__ */ new Map();
9059
9362
  }
9060
9363
  });
@@ -9214,7 +9517,7 @@ function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
9214
9517
  if (!wf) return "";
9215
9518
  const ledger = wf.sub_progress ?? [];
9216
9519
  const next = nextPending(ledger);
9217
- const loops = detectLoop(ledger);
9520
+ const loops = detectLoop(ledger.filter((e) => !isSettled(e)));
9218
9521
  const lines = [
9219
9522
  "<workflow-state>",
9220
9523
  `phase: ${wf.phase}`,
@@ -9249,6 +9552,7 @@ function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
9249
9552
  );
9250
9553
  }
9251
9554
  for (const e of ledger) {
9555
+ if (isSettled(e)) continue;
9252
9556
  const attempts = e.fail_count ?? 0;
9253
9557
  if (e.attempt_budget !== void 0 && attempts >= e.attempt_budget) {
9254
9558
  lines.push(
@@ -9326,9 +9630,11 @@ function findPhaseContextExcerpt(repoRoot, phase, budget) {
9326
9630
  try {
9327
9631
  const phasesDir = join(repoRoot, ".planning", "phases");
9328
9632
  if (!existsSync(phasesDir)) return null;
9633
+ const phaseNum = /(\d+(?:\.\d+)?)/.exec(phase)?.[1];
9634
+ if (phaseNum === void 0) return null;
9329
9635
  for (const dir of readdirSync(phasesDir)) {
9330
- const num = /^(\d+)/.exec(dir)?.[1];
9331
- if (!num || !phase.includes(num)) continue;
9636
+ const num = /^(\d+(?:\.\d+)?)/.exec(dir)?.[1];
9637
+ if (num === void 0 || Number(num) !== Number(phaseNum)) continue;
9332
9638
  const ctxFile = join(phasesDir, dir, `${num}-CONTEXT.md`);
9333
9639
  if (!existsSync(ctxFile)) continue;
9334
9640
  const body = readFileSync(ctxFile, "utf8");
@@ -10601,7 +10907,7 @@ function renderHumanTable(records) {
10601
10907
  }
10602
10908
  }
10603
10909
  function pipeToJq(filterExpr, lines) {
10604
- return new Promise((resolve24, reject) => {
10910
+ return new Promise((resolve23, reject) => {
10605
10911
  const child = spawn("jq", [filterExpr], {
10606
10912
  stdio: ["pipe", "inherit", "inherit"],
10607
10913
  windowsHide: true
@@ -10610,12 +10916,15 @@ function pipeToJq(filterExpr, lines) {
10610
10916
  const e = err2;
10611
10917
  if (e.code === "ENOENT") {
10612
10918
  console.error(t("audit_log.jq_missing"));
10613
- resolve24(1);
10919
+ resolve23(1);
10614
10920
  } else {
10615
10921
  reject(err2);
10616
10922
  }
10617
10923
  });
10618
- child.on("close", (code) => resolve24(code ?? 0));
10924
+ child.on("close", (code) => resolve23(code ?? 0));
10925
+ child.stdin.on("error", (err2) => {
10926
+ if (err2.code !== "EPIPE") reject(err2);
10927
+ });
10619
10928
  child.stdin.write(lines.join("\n"));
10620
10929
  child.stdin.end();
10621
10930
  });
@@ -11035,7 +11344,13 @@ function recordScenario(from, opts = {}) {
11035
11344
 
11036
11345
  // src/eval/runner.ts
11037
11346
  init_runDeps();
11038
- var TIMESTAMP_KEYS = /* @__PURE__ */ new Set(["started_at", "completed_at", "paused_at", "timestamp"]);
11347
+ var TIMESTAMP_KEYS = /* @__PURE__ */ new Set([
11348
+ "started_at",
11349
+ "completed_at",
11350
+ "paused_at",
11351
+ "updated_at",
11352
+ "timestamp"
11353
+ ]);
11039
11354
  function normalizeString(s, roots) {
11040
11355
  let out = s;
11041
11356
  for (const root of roots) {
@@ -11197,6 +11512,10 @@ function composeContext(seed, step) {
11197
11512
  async function execStep(scenario, step, repoDir) {
11198
11513
  if ("file" in step) {
11199
11514
  const target = resolve(repoDir, step.file.path);
11515
+ const rel = relative(repoDir, target);
11516
+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) {
11517
+ throw new Error(`file step path escapes the scenario repo: ${step.file.path}`);
11518
+ }
11200
11519
  mkdirSync(dirname(target), { recursive: true });
11201
11520
  writeFileSync(target, step.file.content ?? "", "utf8");
11202
11521
  if (step.file.mtime) {
@@ -11293,19 +11612,18 @@ async function runScenarioDir(dir, opts) {
11293
11612
  const prevRoot = process.env.HARNESSED_ROOT_OVERRIDE;
11294
11613
  const prevAssets = process.env.HARNESSED_ASSETS_OVERRIDE;
11295
11614
  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
11615
  const steps = [];
11305
11616
  const evaluatedGateRefs = /* @__PURE__ */ new Set();
11306
11617
  let engineError = null;
11307
11618
  let workflow = null;
11308
11619
  try {
11620
+ process.env.GIT_CEILING_DIRECTORIES = tmpdir();
11621
+ process.env.HARNESSED_ROOT_OVERRIDE = stateRoot;
11622
+ if (scenario.assets_dir) {
11623
+ process.env.HARNESSED_ASSETS_OVERRIDE = isAbsolute(scenario.assets_dir) ? scenario.assets_dir : resolve(dir, scenario.assets_dir);
11624
+ }
11625
+ process.chdir(repoDir);
11626
+ (await Promise.resolve().then(() => (init_judgmentResolver(), judgmentResolver_exports)))._clearJudgmentCache();
11309
11627
  for (const step of scenario.steps) {
11310
11628
  const rec = await execStep(scenario, step, repoDir);
11311
11629
  steps.push(rec);
@@ -11331,7 +11649,11 @@ async function runScenarioDir(dir, opts) {
11331
11649
  else process.env.HARNESSED_ASSETS_OVERRIDE = prevAssets;
11332
11650
  if (prevCeiling === void 0) delete process.env.GIT_CEILING_DIRECTORIES;
11333
11651
  else process.env.GIT_CEILING_DIRECTORIES = prevCeiling;
11334
- _clearJudgmentCache2();
11652
+ try {
11653
+ ;
11654
+ (await Promise.resolve().then(() => (init_judgmentResolver(), judgmentResolver_exports)))._clearJudgmentCache();
11655
+ } catch {
11656
+ }
11335
11657
  }
11336
11658
  const cleanup = () => {
11337
11659
  rmSync(stateRoot, { recursive: true, force: true });
@@ -11393,15 +11715,22 @@ async function runEvalSuite(suiteDir, opts) {
11393
11715
  entries = [];
11394
11716
  }
11395
11717
  for (const dir of entries) {
11718
+ let raw;
11396
11719
  try {
11397
- readFileSync(join(dir, "scenario.yaml"));
11720
+ raw = readFileSync(join(dir, "scenario.yaml"), "utf8");
11398
11721
  } catch {
11399
11722
  continue;
11400
11723
  }
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);
11724
+ if (opts.filter && !dir.includes(opts.filter)) {
11725
+ let name = "";
11726
+ try {
11727
+ const doc = parse(raw);
11728
+ name = typeof doc?.name === "string" ? doc.name : "";
11729
+ } catch {
11730
+ }
11731
+ if (!name.includes(opts.filter)) continue;
11732
+ }
11733
+ results.push(await runScenarioDir(dir, opts));
11405
11734
  }
11406
11735
  const summary = {
11407
11736
  pass: results.filter((r) => r.status === "PASS").length,
@@ -12183,6 +12512,7 @@ async function runHere(opts) {
12183
12512
 
12184
12513
  // src/cli/manifest-add.ts
12185
12514
  init_i18n();
12515
+ init_path_guard();
12186
12516
  var QA = [
12187
12517
  { q: "\u2460 \u662F\u771F reusable surface \u8FD8\u662F\u4E34\u65F6 wrapper?", f: "q1_reusable_surface" },
12188
12518
  { 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 +12529,14 @@ function registerManifestAdd(program2) {
12199
12529
  ).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
12530
  const name = raw.name ?? basename2(upstream);
12201
12531
  const category = raw.category ?? "skill-packs";
12532
+ try {
12533
+ checkSafeSegment(category);
12534
+ checkSafeSegment(name);
12535
+ } catch {
12536
+ console.error("error: invalid --category / --name (path traversal rejected)");
12537
+ process.exit(2);
12538
+ return;
12539
+ }
12202
12540
  const outPath = `manifests/${category}/${name}.ee5-answers.json`;
12203
12541
  if (raw.nonInteractive) {
12204
12542
  console.warn(t("manifest_add.non_interactive_warn"));
@@ -12280,6 +12618,7 @@ function resolveLocaleYaml(dir, baseName, locale = getLocale()) {
12280
12618
  }
12281
12619
 
12282
12620
  // src/cli/prompt.ts
12621
+ init_path_guard();
12283
12622
  init_assetsRoot();
12284
12623
  init_resolveYaml();
12285
12624
 
@@ -12320,8 +12659,6 @@ var Enforcement = Type.Union([
12320
12659
  // process.exit non-zero, sister fallbackHandlers
12321
12660
  Type.Literal("warn"),
12322
12661
  // console.warn emit, continue
12323
- Type.Literal("auto-fix"),
12324
- // run auto_fix_cmd then continue (biome --write pattern)
12325
12662
  Type.Literal("info")
12326
12663
  // log only, no action
12327
12664
  ]);
@@ -12332,22 +12669,21 @@ var DisciplineRule = Type.Object(
12332
12669
  description: Type.String(),
12333
12670
  // human-readable
12334
12671
  enforcement: Enforcement,
12335
- trigger: Type.Union([Type.String(), Type.Array(Type.String())]),
12672
+ trigger: Type.Union([Type.String(), Type.Array(Type.String())])
12336
12673
  // expr OR always-on list
12337
- check_method: Type.String(),
12338
- // heuristic / regex / external-cmd / llm-judge / file-content-match
12339
- auto_fix_cmd: Type.Optional(Type.String())
12340
- // only enforcement=auto-fix
12674
+ // 4.43.0 — `check_method` / `auto_fix_cmd` and the `auto-fix` enforcement value
12675
+ // removed: nothing ever evaluated them (the only runner, the before-commit hook,
12676
+ // was unreachable and deleted in 4.42.0). A rule's description reaches the model
12677
+ // via `harnessed prompt`; mechanical checks live in `harnessed check-docs`.
12341
12678
  },
12342
12679
  { additionalProperties: false }
12343
12680
  );
12344
12681
  var PriorityHierarchy = Type.Array(Type.String(), { minItems: 1 });
12345
12682
  var ProtocolShape = Type.Object(
12346
12683
  {
12684
+ // required_fields / forbidden_phrases / file_ownership removed 4.43.0 (never
12685
+ // checked); their content now lives in the protocol's description text.
12347
12686
  description: Type.String(),
12348
- required_fields: Type.Optional(Type.Array(Type.String())),
12349
- forbidden_phrases: Type.Optional(Type.Array(Type.String())),
12350
- file_ownership: Type.Optional(Type.Record(Type.String(), Type.Array(Type.String()))),
12351
12687
  rules: Type.Optional(Type.Array(DisciplineRule))
12352
12688
  },
12353
12689
  { additionalProperties: false }
@@ -12358,7 +12694,6 @@ var Discipline = Type.Object(
12358
12694
  discipline: Type.String({ minLength: 1 }),
12359
12695
  // basename (karpathy / output-style / ...)
12360
12696
  enforcement_layer: EnforcementLayer,
12361
- auto_enforce: Type.Boolean(),
12362
12697
  rules: Type.Array(DisciplineRule),
12363
12698
  priority_hierarchy: Type.Optional(PriorityHierarchy),
12364
12699
  // priority.yaml only
@@ -12402,44 +12737,6 @@ async function loadAllApplied(disciplines_applied, packageRoot) {
12402
12737
  return out;
12403
12738
  }
12404
12739
 
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
12740
  // src/discipline/enforcement/before-phase-execute.ts
12444
12741
  async function loadDisciplinesForPhase(disciplines_applied, packageRoot) {
12445
12742
  return loadAllApplied(disciplines_applied, packageRoot);
@@ -12628,25 +12925,69 @@ var SpawnFailError = class extends Error {
12628
12925
  }
12629
12926
  lastMessage;
12630
12927
  };
12928
+ var DEFAULT_SPAWN_TIMEOUT_MS = 60 * 60 * 1e3;
12929
+ var SpawnTimeoutError = class extends Error {
12930
+ constructor(timeoutMs) {
12931
+ super(`sdkSpawn exceeded its ${timeoutMs}ms wall-clock timeout (HARNESSED_SPAWN_TIMEOUT_MS)`);
12932
+ this.timeoutMs = timeoutMs;
12933
+ this.name = "SpawnTimeoutError";
12934
+ }
12935
+ timeoutMs;
12936
+ };
12937
+ function envSpawnTimeoutMs() {
12938
+ const raw = Number.parseInt(process.env.HARNESSED_SPAWN_TIMEOUT_MS ?? "", 10);
12939
+ return Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_SPAWN_TIMEOUT_MS;
12940
+ }
12631
12941
  async function sdkSpawn(def, opts) {
12632
12942
  const sdkDef = toSdkAgentDefinition(def);
12633
- const injectedPrompt = injectFactoryInternalFields(def, def.initialPrompt ?? def.prompt);
12943
+ const injectedPrompt = injectFactoryInternalFields(def, def.prompt);
12634
12944
  const queryOptions = {
12635
- allowedTools: ["Read", "Edit", "Write", "Grep", "Glob", "Bash", "Task"],
12945
+ // The prompt runs as the MAIN thread of this query, so the def's declared
12946
+ // limits must land on the query options; registering them only on the
12947
+ // `agents` entry (or rendering them into prompt text) enforces nothing.
12948
+ allowedTools: def.tools ?? ["Read", "Edit", "Write", "Grep", "Glob", "Bash", "Task"],
12949
+ ...def.disallowedTools?.length ? { disallowedTools: def.disallowedTools } : {},
12950
+ ...def.maxTurns ? { maxTurns: def.maxTurns } : {},
12951
+ // bypassPermissions additionally needs allowDangerouslySkipPermissions; a
12952
+ // manifest field must not be able to switch that on, so it is not forwarded.
12953
+ ...def.permissionMode && def.permissionMode !== "bypassPermissions" ? { permissionMode: def.permissionMode } : {},
12636
12954
  agents: { [opts.expertName]: sdkDef },
12637
12955
  // PRIMARY signal (B-02 / B-07 SC3) — structured output via json_schema.
12638
12956
  outputFormat: { type: "json_schema", schema: COMPLETION_SCHEMA }
12639
12957
  };
12640
12958
  if (opts.resumeSessionId) queryOptions.resume = opts.resumeSessionId;
12959
+ const timeoutMs = opts.timeoutMs ?? envSpawnTimeoutMs();
12960
+ const abortController = new AbortController();
12961
+ queryOptions.abortController = abortController;
12641
12962
  const q = query({ prompt: injectedPrompt, options: queryOptions });
12642
12963
  let result;
12643
- for await (const msg of q) {
12644
- if (msg.type === "system" && msg.subtype === "init") {
12645
- opts.onSessionId?.(msg.session_id);
12964
+ const consume = (async () => {
12965
+ for await (const msg of q) {
12966
+ if (msg.type === "system" && msg.subtype === "init") {
12967
+ opts.onSessionId?.(msg.session_id);
12968
+ }
12969
+ if (msg.type === "result") {
12970
+ result = msg;
12971
+ }
12646
12972
  }
12647
- if (msg.type === "result") {
12648
- result = msg;
12973
+ })();
12974
+ let timer;
12975
+ try {
12976
+ if (timeoutMs > 0) {
12977
+ const timedOut = new Promise((_, reject) => {
12978
+ timer = setTimeout(() => {
12979
+ abortController.abort();
12980
+ reject(new SpawnTimeoutError(timeoutMs));
12981
+ }, timeoutMs);
12982
+ });
12983
+ consume.catch(() => {
12984
+ });
12985
+ await Promise.race([consume, timedOut]);
12986
+ } else {
12987
+ await consume;
12649
12988
  }
12989
+ } finally {
12990
+ clearTimeout(timer);
12650
12991
  }
12651
12992
  if (!result) throw new SpawnFailError();
12652
12993
  const structuredOutput = "structured_output" in result ? result.structured_output : void 0;
@@ -12927,6 +13268,7 @@ function loadPhases(yamlPath, vars) {
12927
13268
  init_subAnchor();
12928
13269
  init_exprBuilder();
12929
13270
  init_judgmentResolver();
13271
+ init_fallbackHandlers();
12930
13272
  init_skipGate();
12931
13273
  init_skipSubs();
12932
13274
  function resolveMasterYamlPath2(masterName, packageRoot) {
@@ -12943,7 +13285,15 @@ function resolveSubYamlPath(masterName, subName, packageRoot) {
12943
13285
  }
12944
13286
  var defaultSpawnDriver = async (masterName, subName, _context, packageRoot) => {
12945
13287
  const subYamlPath = resolveSubYamlPath(masterName, subName, packageRoot);
12946
- const result = await runWorkflow(subYamlPath, {}, { packageRoot, gateContext: _context });
13288
+ const result = await runWorkflow(
13289
+ subYamlPath,
13290
+ {},
13291
+ {
13292
+ packageRoot,
13293
+ gateContext: _context,
13294
+ subOf: masterName
13295
+ }
13296
+ );
12947
13297
  if (result.status === "failed") {
12948
13298
  throw new Error(
12949
13299
  `sub-workflow ${masterName}/${subName} failed` + (result.lastPhaseId ? ` at phase ${result.lastPhaseId}` : "")
@@ -13148,9 +13498,12 @@ async function runMasterOrchestrator(masterName, context, packageRoot, spawnDriv
13148
13498
  ).filter((x) => x !== null);
13149
13499
  if (parallelFailures.length > 0) {
13150
13500
  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
- );
13501
+ const message = `[${masterName} master] ${parallelFailures.length} parallel sub(s) failed \u2014 ${detail}`;
13502
+ const halts = parallelFailures.map((f) => f.reason).filter((r) => r instanceof WorkflowHaltError);
13503
+ if (halts.length > 0) {
13504
+ throw new WorkflowHaltError(message, Math.max(...halts.map((h) => h.exitCode)));
13505
+ }
13506
+ throw new Error(message);
13154
13507
  }
13155
13508
  for (const clause of serialTrailing) {
13156
13509
  console.log(` \u2192 ${clause.sub} (serial order=${clause.order ?? 0})`);
@@ -13358,8 +13711,16 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
13358
13711
  }
13359
13712
  const workflowName = parsed.workflow;
13360
13713
  const isMaster = "delegates_to" in parsed && Array.isArray(parsed.delegates_to) && parsed.delegates_to.length > 0 && MASTER_NAMES.includes(workflowName);
13714
+ const ownsRecord = opts.subOf === void 0;
13361
13715
  if (isMaster) {
13716
+ if (ownsRecord) await activatePhase(workflowName);
13362
13717
  const r = await runMasterOrchestrator(workflowName, gateContext, packageRoot);
13718
+ if (ownsRecord) {
13719
+ await completePhase({
13720
+ phaseId: workflowName,
13721
+ lastTask: `master ${workflowName} complete: ${r.fired.length} sub(s) fired`
13722
+ });
13723
+ }
13363
13724
  return {
13364
13725
  status: "complete",
13365
13726
  phasesRun: r.fired.length,
@@ -13376,11 +13737,18 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
13376
13737
  );
13377
13738
  }
13378
13739
  const skippedPhases = [];
13379
- const phases = parsed.phases ?? [];
13740
+ if (!Array.isArray(parsed.phases) || parsed.phases.length === 0) {
13741
+ const hasDelegates = "delegates_to" in parsed && Array.isArray(parsed.delegates_to) && parsed.delegates_to.length > 0;
13742
+ throw new Error(
13743
+ 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`
13744
+ );
13745
+ }
13746
+ const phases = parsed.phases;
13380
13747
  for (let i = 0; i < phases.length; i++) {
13381
13748
  const ph = phases[i];
13382
13749
  if (!ph) continue;
13383
- await activatePhase(ph.id);
13750
+ if (ownsRecord) await activatePhase(ph.id);
13751
+ const transitionWorkflowComplete = ownsRecord && i === phases.length - 1;
13384
13752
  const invokesTools = "invokes_tools" in ph && Array.isArray(ph.invokes_tools) ? ph.invokes_tools : void 0;
13385
13753
  if (invokesTools && invokesTools.length > 1) {
13386
13754
  try {
@@ -13419,7 +13787,8 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
13419
13787
  skippedPhases.push(ph.id);
13420
13788
  await completePhase({
13421
13789
  phaseId: ph.id,
13422
- lastTask: `phase ${ph.id} skipped: gate ${ph.gate} evaluated false`
13790
+ lastTask: `phase ${ph.id} skipped: gate ${ph.gate} evaluated false`,
13791
+ transitionWorkflowComplete
13423
13792
  });
13424
13793
  continue;
13425
13794
  }
@@ -13435,6 +13804,11 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
13435
13804
  ...typeof gateContext.modelTierOverride === "string" ? { modelTierOverride: gateContext.modelTierOverride } : {}
13436
13805
  });
13437
13806
  if (r.status !== "ok") {
13807
+ await completePhase({
13808
+ phaseId: ph.id,
13809
+ lastTask: `FAILED: phase ${ph.id}: ${r.output}`,
13810
+ transitionWorkflowComplete: false
13811
+ });
13438
13812
  return { status: "failed", phasesRun: i, lastPhaseId: ph.id };
13439
13813
  }
13440
13814
  if (r.needsTeamsEscalation === true) {
@@ -13443,24 +13817,10 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
13443
13817
  `\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
13818
  );
13445
13819
  }
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
13820
  await completePhase({
13462
13821
  phaseId: ph.id,
13463
- lastTask: `phase ${ph.id} complete: ${r.output}`
13822
+ lastTask: `phase ${ph.id} complete: ${r.output}`,
13823
+ transitionWorkflowComplete
13464
13824
  });
13465
13825
  }
13466
13826
  return {
@@ -13628,6 +13988,13 @@ function registerPrompt(program2) {
13628
13988
  program2.command("prompt").description(
13629
13989
  "Print a spawn-ready prompt for a sub-workflow (role + checklist + protocols, no spawn)."
13630
13990
  ).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) => {
13991
+ try {
13992
+ checkSafeSegment(sub);
13993
+ } catch {
13994
+ console.error("error: invalid workflow name (path traversal rejected)");
13995
+ process.exit(2);
13996
+ return;
13997
+ }
13631
13998
  const packageRoot = getAssetsRoot();
13632
13999
  const workflowsDir = resolve(packageRoot, "workflows");
13633
14000
  const rolePrompts = await loadRolePrompts(workflowsDir);
@@ -13715,7 +14082,21 @@ function registerReleasePreflight(program2) {
13715
14082
  // src/cli/research.ts
13716
14083
  init_i18n();
13717
14084
  init_assetsRoot();
14085
+ init_fallbackHandlers();
13718
14086
  init_resolveYaml();
14087
+
14088
+ // src/cli/lib/nestedHarness.ts
14089
+ init_platform();
14090
+ function isNestedHarnessContext() {
14091
+ if (process.env.HARNESSED_ALLOW_NESTED === "1") return false;
14092
+ const sessEnv = detectPlatform().sessionIdEnv;
14093
+ if (!sessEnv) return false;
14094
+ const sid = process.env[sessEnv]?.trim();
14095
+ if (!sid) return false;
14096
+ return !process.stdin.isTTY;
14097
+ }
14098
+
14099
+ // src/cli/research.ts
13719
14100
  var PACKAGE_ROOT = getAssetsRoot();
13720
14101
  var WORKFLOWS_DIR = join(PACKAGE_ROOT, "workflows");
13721
14102
  function registerResearch(program2) {
@@ -13741,10 +14122,21 @@ function registerResearch(program2) {
13741
14122
  process.exit(0);
13742
14123
  return;
13743
14124
  }
14125
+ if (isNestedHarnessContext()) {
14126
+ console.error(
14127
+ "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)."
14128
+ );
14129
+ process.exit(1);
14130
+ return;
14131
+ }
13744
14132
  let result;
13745
14133
  try {
13746
14134
  result = await runWorkflow(yamlPath, {}, { packageRoot: PACKAGE_ROOT, gateContext });
13747
14135
  } catch (err2) {
14136
+ if (err2 instanceof WorkflowHaltError) {
14137
+ process.exit(err2.exitCode);
14138
+ return;
14139
+ }
13748
14140
  console.error(`error: workflow runtime failed \u2014 ${err2.message}`);
13749
14141
  process.exit(1);
13750
14142
  return;
@@ -13823,12 +14215,20 @@ function registerRetro(program2) {
13823
14215
  // src/cli/rollback.ts
13824
14216
  init_i18n();
13825
14217
  init_backup();
14218
+ init_path_guard();
13826
14219
  function normalizeEol(buf, eol) {
13827
14220
  const lf = buf.toString("utf8").replace(/\r\n/g, "\n");
13828
14221
  return Buffer.from(eol === "crlf" ? lf.replace(/\n/g, "\r\n") : lf, "utf8");
13829
14222
  }
13830
14223
  function registerRollback(program2) {
13831
14224
  program2.command("rollback <timestamp>").description("Restore files from a backup snapshot (preserves original LF/CRLF)").action(async (timestamp) => {
14225
+ try {
14226
+ checkSafeSegment(timestamp);
14227
+ } catch {
14228
+ console.error("error: invalid backup timestamp (path traversal rejected)");
14229
+ process.exit(2);
14230
+ return;
14231
+ }
13832
14232
  const dir = join(getBackupRoot(), timestamp);
13833
14233
  const metaPath = join(dir, "metadata.json");
13834
14234
  let meta;
@@ -13846,7 +14246,28 @@ ${t("rollback.metadata_unreadable.fix")}`
13846
14246
  const planned = [];
13847
14247
  for (const entry of ordered) {
13848
14248
  if (entry.backup === "") {
13849
- planned.push({ target: entry.target, action: "unlink" });
14249
+ if (entry.sentinel === "created") {
14250
+ planned.push({ target: entry.target, action: "remove-created" });
14251
+ } else if (entry.sentinel === "preexisting-dir") {
14252
+ planned.push({
14253
+ target: entry.target,
14254
+ action: "keep",
14255
+ why: "existed before install and could not be byte-backed-up; left untouched"
14256
+ });
14257
+ } else {
14258
+ let isDir = false;
14259
+ try {
14260
+ isDir = (await stat(entry.target)).isDirectory();
14261
+ } catch {
14262
+ }
14263
+ planned.push(
14264
+ isDir ? {
14265
+ target: entry.target,
14266
+ action: "keep",
14267
+ why: "directory from pre-sentinel backup metadata; origin unknown, not deleting"
14268
+ } : { target: entry.target, action: "unlink" }
14269
+ );
14270
+ }
13850
14271
  continue;
13851
14272
  }
13852
14273
  let buf;
@@ -13872,6 +14293,14 @@ ${t("rollback.metadata_unreadable.fix")}`
13872
14293
  planned.push({ target: entry.target, action: "write", data: normalizeEol(buf, entry.eol) });
13873
14294
  }
13874
14295
  for (const op of planned) {
14296
+ if (op.action === "keep") {
14297
+ console.warn(`[harnessed] rollback: ${op.target} \u2014 ${op.why}`);
14298
+ continue;
14299
+ }
14300
+ if (op.action === "remove-created") {
14301
+ await rm(op.target, { recursive: true, force: true });
14302
+ continue;
14303
+ }
13875
14304
  if (op.action === "unlink") {
13876
14305
  try {
13877
14306
  await unlink(op.target);
@@ -13894,7 +14323,7 @@ ${t("rollback.metadata_unreadable.fix")}`
13894
14323
  // src/cli/run.ts
13895
14324
  init_path_guard();
13896
14325
  init_assetsRoot();
13897
- init_platform();
14326
+ init_fallbackHandlers();
13898
14327
  init_resolveYaml();
13899
14328
 
13900
14329
  // src/cli/lib/extract-user-overrides.ts
@@ -13945,13 +14374,20 @@ var PACKAGE_ROOT2 = getAssetsRoot();
13945
14374
  var WORKFLOWS_DIR2 = join(PACKAGE_ROOT2, "workflows");
13946
14375
  var _autoChainCache = null;
13947
14376
  var _autoChainLoadFailed = false;
14377
+ function parseMaxIterations(v) {
14378
+ const n = Number(v);
14379
+ if (!/^\s*\d+\s*$/.test(v) || !Number.isInteger(n) || n < 1 || n > 100) {
14380
+ throw new InvalidArgumentError(`expected an integer between 1 and 100, got '${v}'`);
14381
+ }
14382
+ return n;
14383
+ }
13948
14384
  function registerRun(program2) {
13949
14385
  program2.command("run").description(
13950
14386
  "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
14387
  ).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
14388
  "--max-iterations <n>",
13953
- "SDK-path retry-loop max iter (default 20; honored Phase 3 onward)",
13954
- (v) => parseInt(v, 10)
14389
+ "SDK-path retry-loop max iter (default 20; integer 1-100)",
14390
+ parseMaxIterations
13955
14391
  ).option("--model <model>", "subagent model: 'haiku' | 'sonnet' | 'opus'").option(
13956
14392
  "--dry-run",
13957
14393
  "validate yaml load + walk runtime without spawning (Phase 1 default for verification)"
@@ -14033,6 +14469,10 @@ function registerRun(program2) {
14033
14469
  try {
14034
14470
  result = await runWorkflow(yamlPath, {}, { packageRoot: PACKAGE_ROOT2, gateContext });
14035
14471
  } catch (err2) {
14472
+ if (err2 instanceof WorkflowHaltError) {
14473
+ process.exit(err2.exitCode);
14474
+ return;
14475
+ }
14036
14476
  console.error(`error: workflow runtime failed \u2014 ${err2.message}`);
14037
14477
  process.exit(1);
14038
14478
  return;
@@ -14048,14 +14488,6 @@ function registerRun(program2) {
14048
14488
  process.exit(result.status === "failed" ? 1 : 0);
14049
14489
  });
14050
14490
  }
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
14491
  async function listWorkflowNames(workflowsDir) {
14060
14492
  const names = [];
14061
14493
  const entries = await readdir(workflowsDir);
@@ -14510,7 +14942,7 @@ var V3_4_3_SIGNATURE_MASTER_RX = /\*\*Preferred path\*\*[\s\S]*dispatch to the p
14510
14942
  function shouldOverwriteFile(content) {
14511
14943
  return HARNESSED_MARKER_RX2.test(content) || V3_4_3_SIGNATURE_SUB_RX.test(content) || V3_4_3_SIGNATURE_MASTER_RX.test(content);
14512
14944
  }
14513
- async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync25 = (p7) => readFileSync(p7, "utf8")) {
14945
+ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabilities, installedPlugins, installedUserSkills, writer, fileExists2 = existsSync, readFileSync24 = (p7) => readFileSync(p7, "utf8")) {
14514
14946
  const results = [];
14515
14947
  const aggregatedWarnings = /* @__PURE__ */ new Set();
14516
14948
  for (const name of slashNames) {
@@ -14529,7 +14961,7 @@ async function writeAllCommands(slashNames, commandsDir, rolePrompts, capabiliti
14529
14961
  if (fileExists2(path)) {
14530
14962
  let existing = "";
14531
14963
  try {
14532
- existing = readFileSync25(path);
14964
+ existing = readFileSync24(path);
14533
14965
  } catch {
14534
14966
  existing = "";
14535
14967
  }
@@ -14684,7 +15116,7 @@ async function warnIfAgentTeamsMissing() {
14684
15116
  console.warn("\n\u26A0\uFE0F Agent Teams \u672A\u542F\u7528 \u2014 parallelism-gate \u5347\u7EA7\u8DEF\u5F84\u4E0D\u53EF\u7528");
14685
15117
  console.warn(" \u4FEE\u590D: claude config set env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS 1");
14686
15118
  console.warn(
14687
- " \u8BF4\u660E: harnessed v3.0 \u4E09\u5C42\u6808\u65B9\u6CD5\u8BBA parallelism-gate \u5347\u7EA7\u8DEF\u5F84\u9700 CC 2.1.133+ Agent Teams enable"
15119
+ " \u8BF4\u660E: harnessed v3.0 \u4E09\u5C42\u6808\u65B9\u6CD5\u8BBA parallelism-gate \u5347\u7EA7\u8DEF\u5F84\u9700 CC 2.1.178+ Agent Teams enable"
14688
15120
  );
14689
15121
  console.warn(
14690
15122
  " \u4E0D\u963B\u585E setup,\u540E\u7EED parallelism-gate workflow phase \u89E6\u53D1\u65F6\u81EA\u52A8\u964D\u7EA7 subagent fan-out\n"
@@ -14903,7 +15335,7 @@ async function printSetupVersionBanner() {
14903
15335
 
14904
15336
  // src/cli/setup.ts
14905
15337
  var KNOWN_PLATFORMS = ["claude", "codex"];
14906
- async function applyPlatformOption(platform) {
15338
+ async function applyPlatformOption(platform, persist) {
14907
15339
  if (!KNOWN_PLATFORMS.includes(platform)) {
14908
15340
  console.error(
14909
15341
  `--platform: unknown id '${platform}' (expected one of: ${KNOWN_PLATFORMS.join(" | ")})`
@@ -14911,10 +15343,11 @@ async function applyPlatformOption(platform) {
14911
15343
  process.exit(1);
14912
15344
  }
14913
15345
  process.env.HARNESSED_PLATFORM = platform;
14914
- const stateRoot = detectPlatform().stateRoot;
15346
+ if (!persist) return;
15347
+ const pinRoot = claudeDescriptor().stateRoot;
14915
15348
  try {
14916
- await mkdir(stateRoot, { recursive: true });
14917
- await writeFile(join(stateRoot, ".platform"), platform, "utf8");
15349
+ await mkdir(pinRoot, { recursive: true });
15350
+ await writeFile(join(pinRoot, ".platform"), platform, "utf8");
14918
15351
  } catch (e) {
14919
15352
  console.warn(` [--platform] could not persist .platform pin (${e.message})`);
14920
15353
  }
@@ -15028,7 +15461,7 @@ function registerSetup(program2) {
15028
15461
  ).action(async (raw) => {
15029
15462
  await printSetupVersionBanner();
15030
15463
  const dryRun = raw.dryRun === true;
15031
- if (raw.platform !== void 0) await applyPlatformOption(raw.platform);
15464
+ if (raw.platform !== void 0) await applyPlatformOption(raw.platform, !dryRun);
15032
15465
  const pkgRoot = getAssetsRoot();
15033
15466
  const workflowsDir = resolve(pkgRoot, "workflows");
15034
15467
  const skillsBase = getSkillsDir();
@@ -15662,7 +16095,7 @@ var uninstallNpmCli = async (ctx) => {
15662
16095
  const m = install.cmd.match(/npm\s+(?:install|i)\s+(?:-g\s+)?(\S+)/);
15663
16096
  const pkg = m?.[1] ?? ctx.manifest.metadata.upstream.source;
15664
16097
  const isWin = process.platform === "win32";
15665
- const result = await new Promise((resolve24) => {
16098
+ const result = await new Promise((resolve23) => {
15666
16099
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], { windowsHide: true }) : spawn("npm", ["uninstall", "-g", pkg], { shell: false });
15667
16100
  let stderr = "";
15668
16101
  child.stderr?.setEncoding("utf8").on("data", (c) => {
@@ -15670,15 +16103,15 @@ var uninstallNpmCli = async (ctx) => {
15670
16103
  });
15671
16104
  const timer = setTimeout(() => {
15672
16105
  child.kill("SIGKILL");
15673
- resolve24({ exitCode: -1, stderr: `${stderr}[timeout]` });
16106
+ resolve23({ exitCode: -1, stderr: `${stderr}[timeout]` });
15674
16107
  }, 3e4);
15675
16108
  child.on("error", (e) => {
15676
16109
  clearTimeout(timer);
15677
- resolve24({ exitCode: -1, stderr: e.message });
16110
+ resolve23({ exitCode: -1, stderr: e.message });
15678
16111
  });
15679
16112
  child.on("close", (code) => {
15680
16113
  clearTimeout(timer);
15681
- resolve24({ exitCode: code ?? -1, stderr });
16114
+ resolve23({ exitCode: code ?? -1, stderr });
15682
16115
  });
15683
16116
  });
15684
16117
  if (result.exitCode !== 0) {