harnessed 5.0.5 → 5.0.6

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.
Files changed (60) hide show
  1. package/CHANGELOG.md +3183 -0
  2. package/README-en.md +10 -1
  3. package/README-zh.md +10 -1
  4. package/README.md +10 -1
  5. package/bin/harnessed-check-docs.mjs +1 -0
  6. package/bin/harnessed-inject-state.mjs +57 -9
  7. package/bin/harnessed-stop-hook.mjs +51 -9
  8. package/bin/harnessed-update-reminder-worker.mjs +3 -1
  9. package/bin/harnessed-update-reminder.mjs +3 -1
  10. package/dist/cli.mjs +1952 -432
  11. package/dist/cli.mjs.map +1 -1
  12. package/dist/index.mjs +1 -1
  13. package/dist/index.mjs.map +1 -1
  14. package/manifests/optional/codegraph.yaml +2 -0
  15. package/manifests/skill-packs/gsd.yaml +5 -3
  16. package/manifests/skill-packs/mattpocock-skills.yaml +3 -3
  17. package/manifests/tools/playwright-cli.yaml +4 -0
  18. package/messages/en.json +1 -0
  19. package/messages/zh-Hans.json +3 -2
  20. package/package.json +3 -1
  21. package/workflows/auto/SKILL.md +1 -1
  22. package/workflows/auto/SKILL.zh-Hans.md +1 -1
  23. package/workflows/defaults.yaml +12 -0
  24. package/workflows/discuss/phase/SKILL.md +1 -1
  25. package/workflows/discuss/phase/SKILL.zh-Hans.md +1 -1
  26. package/workflows/discuss/subtask/SKILL.md +1 -1
  27. package/workflows/discuss/subtask/SKILL.zh-Hans.md +1 -1
  28. package/workflows/plan/ai-integration/SKILL.md +39 -0
  29. package/workflows/plan/ai-integration/SKILL.zh-Hans.md +38 -0
  30. package/workflows/plan/ai-integration/workflow.yaml +12 -0
  31. package/workflows/plan/auto/workflow.yaml +22 -2
  32. package/workflows/plan/phase/SKILL.md +2 -2
  33. package/workflows/plan/phase/SKILL.zh-Hans.md +2 -2
  34. package/workflows/plan/secure/SKILL.md +39 -0
  35. package/workflows/plan/secure/SKILL.zh-Hans.md +38 -0
  36. package/workflows/plan/secure/workflow.yaml +12 -0
  37. package/workflows/plan/spec/SKILL.md +39 -0
  38. package/workflows/plan/spec/SKILL.zh-Hans.md +38 -0
  39. package/workflows/plan/spec/workflow.yaml +12 -0
  40. package/workflows/plan/ui/SKILL.md +39 -0
  41. package/workflows/plan/ui/SKILL.zh-Hans.md +38 -0
  42. package/workflows/plan/ui/workflow.yaml +12 -0
  43. package/workflows/role-prompts.yaml +36 -6
  44. package/workflows/role-prompts.zh-Hans.yaml +36 -6
  45. package/workflows/ship/auto/SKILL.md +2 -1
  46. package/workflows/ship/auto/SKILL.zh-Hans.md +2 -1
  47. package/workflows/task/clarify/SKILL.md +2 -2
  48. package/workflows/task/clarify/SKILL.zh-Hans.md +2 -2
  49. package/workflows/task/code/SKILL.md +1 -1
  50. package/workflows/task/code/SKILL.zh-Hans.md +1 -1
  51. package/workflows/task/deliver/SKILL.md +1 -1
  52. package/workflows/task/deliver/SKILL.zh-Hans.md +1 -1
  53. package/workflows/task/test/SKILL.md +1 -1
  54. package/workflows/task/test/SKILL.zh-Hans.md +1 -1
  55. package/workflows/verify/auto/SKILL.md +1 -1
  56. package/workflows/verify/auto/SKILL.zh-Hans.md +1 -1
  57. package/workflows/verify/design/SKILL.md +1 -1
  58. package/workflows/verify/design/SKILL.zh-Hans.md +1 -1
  59. package/workflows/verify/progress/SKILL.md +1 -1
  60. package/workflows/verify/progress/SKILL.zh-Hans.md +1 -1
package/dist/cli.mjs CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
- import { readFileSync, existsSync, mkdirSync, renameSync, readdirSync, writeFileSync, appendFileSync, accessSync, constants, statSync, unlinkSync, realpathSync, openSync, closeSync, fsyncSync, rmSync, mkdtempSync, lstatSync, readSync, utimesSync } from 'fs';
2
+ import { readFileSync, existsSync, mkdirSync, readdirSync, writeFileSync, appendFileSync, accessSync, constants, statSync, unlinkSync, realpathSync, renameSync, openSync, closeSync, fsyncSync, rmSync, mkdtempSync, lstatSync, readSync, utimesSync, createReadStream } from 'fs';
3
3
  import { homedir, tmpdir } from 'os';
4
- import { join, resolve, dirname, basename, isAbsolute, relative, sep, win32, posix } from 'path';
4
+ import { join, dirname, resolve, basename, isAbsolute, relative, sep, win32, posix } from 'path';
5
5
  import { Type } from '@sinclair/typebox';
6
6
  import { readFile, mkdir, writeFile, readdir, stat, appendFile, rename, mkdtemp, rm, access, realpath, copyFile, unlink, chmod, cp, lstat, symlink } from 'fs/promises';
7
7
  import { Value } from '@sinclair/typebox/value';
@@ -12,6 +12,7 @@ import { LineCounter, parseDocument, parse, isSeq, isAlias, isScalar, stringify,
12
12
  import { Ajv } from 'ajv';
13
13
  import * as ajvFormatsNs from 'ajv-formats';
14
14
  import { spawnSync, execFileSync, spawn, execFile, exec } from 'child_process';
15
+ import { AsyncLocalStorage } from 'async_hooks';
15
16
  import { promisify, isDeepStrictEqual } from 'util';
16
17
  import { Parser } from 'expr-eval';
17
18
  import * as p from '@clack/prompts';
@@ -39,7 +40,7 @@ var init_package = __esm({
39
40
  "package.json"() {
40
41
  package_default = {
41
42
  name: "harnessed",
42
- version: "5.0.5",
43
+ version: "5.0.6",
43
44
  description: "AI coding harness package manager + composition orchestrator",
44
45
  type: "module",
45
46
  license: "Apache-2.0",
@@ -90,6 +91,7 @@ var init_package = __esm({
90
91
  "routing",
91
92
  "config-templates",
92
93
  "schemas",
94
+ "CHANGELOG.md",
93
95
  "README.md",
94
96
  "README-en.md",
95
97
  "README-zh.md",
@@ -100,6 +102,7 @@ var init_package = __esm({
100
102
  scripts: {
101
103
  dev: "tsup --watch",
102
104
  build: "tsc --noEmit && tsup && node ./scripts/build-hooks.mjs",
105
+ prepack: "npm run build",
103
106
  "build:hooks": "node ./scripts/build-hooks.mjs",
104
107
  "build:schema": "node ./scripts/build-schema.mjs",
105
108
  "validate:schema": "node ./scripts/validate-schema.mjs",
@@ -159,6 +162,7 @@ __export(platform_exports, {
159
162
  claudeDescriptor: () => claudeDescriptor,
160
163
  codexDescriptor: () => codexDescriptor,
161
164
  descriptorFor: () => descriptorFor,
165
+ descriptorForConfiguredHome: () => descriptorForConfiguredHome,
162
166
  detectPlatform: () => detectPlatform,
163
167
  getCommandsDir: () => getCommandsDir,
164
168
  getMcpConfigPath: () => getMcpConfigPath,
@@ -212,8 +216,32 @@ function isHostId(id) {
212
216
  function descriptorFor(id, home = homedir()) {
213
217
  return id === "codex" ? codexDescriptor(home) : claudeDescriptor(home);
214
218
  }
215
- function descriptorById(id, home) {
216
- return isHostId(id) ? descriptorFor(id, home) : void 0;
219
+ function configuredHome(envVar) {
220
+ const value = process.env[envVar]?.trim();
221
+ return value || void 0;
222
+ }
223
+ function descriptorForConfiguredHome(id, home = homedir()) {
224
+ const descriptor = descriptorFor(id, home);
225
+ const nativeHome = configuredHome(id === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR");
226
+ if (nativeHome === void 0) return descriptor;
227
+ if (id === "codex") {
228
+ return {
229
+ ...descriptor,
230
+ homeDir: nativeHome,
231
+ stateRoot: join(nativeHome, "harnessed"),
232
+ commandsDir: join(nativeHome, "prompts"),
233
+ mcpConfigPath: join(nativeHome, "config.toml")
234
+ };
235
+ }
236
+ return {
237
+ ...descriptor,
238
+ homeDir: nativeHome,
239
+ stateRoot: join(nativeHome, "harnessed"),
240
+ settingsPath: join(nativeHome, "settings.json"),
241
+ skillsDir: join(nativeHome, "skills"),
242
+ commandsDir: join(nativeHome, "commands"),
243
+ pluginsRegistry: join(nativeHome, "plugins", "installed_plugins.json")
244
+ };
217
245
  }
218
246
  function detectPlatform(home = homedir()) {
219
247
  const resolved = resolveHost(home);
@@ -225,11 +253,18 @@ function resolveHost(home) {
225
253
  return resolveHostWithReason(home).descriptor;
226
254
  }
227
255
  function resolveHostWithReason(home = homedir()) {
228
- const base = claudeDescriptor(home);
256
+ const claudeHome = configuredHome("CLAUDE_CONFIG_DIR");
257
+ const codexHome = configuredHome("CODEX_HOME");
258
+ const envPlatform = process.env.HARNESSED_PLATFORM?.trim();
259
+ const explicitHost = envPlatform !== void 0 && isHostId(envPlatform) ? envPlatform : void 0;
260
+ if (explicitHost === void 0 && claudeHome !== void 0 && codexHome !== void 0) {
261
+ throw new Error("both CLAUDE_CONFIG_DIR and CODEX_HOME are set; pass --platform claude|codex");
262
+ }
263
+ const base = descriptorForConfiguredHome("claude", home);
264
+ const codex = descriptorForConfiguredHome("codex", home);
229
265
  const skipped = [];
230
- const envPlatform = process.env.HARNESSED_PLATFORM;
231
266
  if (envPlatform !== void 0 && envPlatform !== "") {
232
- const d = descriptorById(envPlatform, home);
267
+ const d = isHostId(envPlatform) ? descriptorForConfiguredHome(envPlatform, home) : void 0;
233
268
  if (d) {
234
269
  return {
235
270
  descriptor: d,
@@ -239,11 +274,23 @@ function resolveHostWithReason(home = homedir()) {
239
274
  }
240
275
  skipped.push({ kind: "env-platform-unknown", envVar: "HARNESSED_PLATFORM", value: envPlatform });
241
276
  }
277
+ if (claudeHome !== void 0 || codexHome !== void 0) {
278
+ const id = claudeHome !== void 0 ? "claude" : "codex";
279
+ return {
280
+ descriptor: id === "claude" ? base : codex,
281
+ reason: {
282
+ kind: "env-platform",
283
+ envVar: id === "claude" ? "CLAUDE_CONFIG_DIR" : "CODEX_HOME",
284
+ value: id === "claude" ? claudeHome : codexHome
285
+ },
286
+ skipped
287
+ };
288
+ }
242
289
  const inClaude = Boolean(process.env.CLAUDE_CODE_SESSION_ID?.trim());
243
290
  const inCodex = Boolean(process.env.CODEX_SESSION_ID?.trim());
244
291
  if (inClaude !== inCodex) {
245
292
  return {
246
- descriptor: inClaude ? base : codexDescriptor(home),
293
+ descriptor: inClaude ? base : codex,
247
294
  reason: {
248
295
  kind: "host-session-env",
249
296
  envVar: inClaude ? "CLAUDE_CODE_SESSION_ID" : "CODEX_SESSION_ID"
@@ -252,11 +299,11 @@ function resolveHostWithReason(home = homedir()) {
252
299
  };
253
300
  }
254
301
  if (inClaude && inCodex) skipped.push({ kind: "host-session-env-ambiguous" });
255
- for (const pinRoot of [codexDescriptor(home).stateRoot, base.stateRoot]) {
302
+ for (const pinRoot of [codex.stateRoot, base.stateRoot]) {
256
303
  const pinPath = join(pinRoot, ".platform");
257
304
  try {
258
305
  const value = readFileSync(pinPath, "utf8").trim();
259
- const d = descriptorById(value, home);
306
+ const d = isHostId(value) ? descriptorForConfiguredHome(value, home) : void 0;
260
307
  if (d) return { descriptor: d, reason: { kind: "platform-pin", pinPath, value }, skipped };
261
308
  skipped.push({ kind: "platform-pin-unknown", pinPath, value });
262
309
  } catch {
@@ -270,7 +317,6 @@ function resolveHostWithReason(home = homedir()) {
270
317
  skipped
271
318
  };
272
319
  }
273
- const codex = codexDescriptor(home);
274
320
  if (existsSync(codex.homeDir)) {
275
321
  return {
276
322
  descriptor: codex,
@@ -309,6 +355,52 @@ var init_platform = __esm({
309
355
  }
310
356
  });
311
357
 
358
+ // src/platform/hostInstallContext.ts
359
+ var hostInstallContext_exports = {};
360
+ __export(hostInstallContext_exports, {
361
+ captureHostInstallContext: () => captureHostInstallContext,
362
+ createHostInstallContext: () => createHostInstallContext
363
+ });
364
+ function createHostInstallContext(platform, selection) {
365
+ if (platform.id !== "claude" && platform.id !== "codex") {
366
+ throw new Error(`unsupported host: ${platform.id}`);
367
+ }
368
+ const nativeHome = platform.id === "codex" ? selection.nativeHome?.trim() : selection.nativeHome;
369
+ const neutralSpawnCwd = selection.neutralSpawnCwd?.trim();
370
+ return Object.freeze({
371
+ hostId: platform.id,
372
+ os: selection.os,
373
+ userHome: selection.userHome,
374
+ platform: Object.freeze({ ...platform }),
375
+ nativeHome: nativeHome || platform.homeDir,
376
+ ...neutralSpawnCwd ? { neutralSpawnCwd } : {}
377
+ });
378
+ }
379
+ function captureHostInstallContext(options = {}) {
380
+ if (options.hostId !== void 0 && !isHostId(options.hostId)) {
381
+ throw new Error(`unsupported host: ${options.hostId}`);
382
+ }
383
+ const userHome = options.userHome ?? homedir();
384
+ const platformEnv = process.env.HARNESSED_PLATFORM?.trim();
385
+ const explicitHost = options.hostId ?? (platformEnv !== void 0 && isHostId(platformEnv) ? platformEnv : void 0);
386
+ const hostId = explicitHost ?? detectPlatform(userHome).id;
387
+ if (!isHostId(hostId)) throw new Error(`unsupported host: ${hostId}`);
388
+ const platform = descriptorForConfiguredHome(hostId, userHome);
389
+ const rootKey = platform.id === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
390
+ const nativeHome = process.env[rootKey]?.trim() || platform.homeDir;
391
+ return createHostInstallContext(platform, {
392
+ os: options.os ?? process.platform,
393
+ userHome,
394
+ nativeHome,
395
+ neutralSpawnCwd: process.env.HARNESSED_SPAWN_CWD
396
+ });
397
+ }
398
+ var init_hostInstallContext = __esm({
399
+ "src/platform/hostInstallContext.ts"() {
400
+ init_platform();
401
+ }
402
+ });
403
+
312
404
  // src/platform/harnessedRoot.ts
313
405
  var harnessedRoot_exports = {};
314
406
  __export(harnessedRoot_exports, {
@@ -326,33 +418,46 @@ function harnessedSubdir(name) {
326
418
  function harnessedFile(name) {
327
419
  return join(getHarnessedRoot(), name);
328
420
  }
329
- function migrateLegacyHarnessedRoot() {
330
- const legacyRoot = join(homedir(), ".harnessed");
331
- const newRoot = join(homedir(), ".claude", "harnessed");
332
- const claudeParent = join(homedir(), ".claude");
421
+ function renameLegacyRoot(source, target) {
422
+ try {
423
+ renameSync(source, target);
424
+ return true;
425
+ } catch (error) {
426
+ if (error.code !== "EXDEV") throw error;
427
+ console.error(
428
+ `[harnessed] WARN: could not rename legacy state directory ${source} to ${target} (EXDEV); leaving legacy data in place`
429
+ );
430
+ return false;
431
+ }
432
+ }
433
+ function migrateLegacyHarnessedRoot(context = captureHostInstallContext()) {
434
+ const legacyRoot = join(context.userHome, ".harnessed");
435
+ const newRoot = context.platform.stateRoot;
436
+ const targetParent = dirname(newRoot);
333
437
  if (!existsSync(legacyRoot)) return;
334
438
  if (!existsSync(newRoot)) {
335
- mkdirSync(claudeParent, { recursive: true });
336
- renameSync(legacyRoot, newRoot);
439
+ mkdirSync(targetParent, { recursive: true });
440
+ if (!renameLegacyRoot(legacyRoot, newRoot)) return;
337
441
  console.error(
338
442
  `[harnessed] migrated legacy state directory ${legacyRoot} \u2192 ${newRoot} (v3.0.3 path change)`
339
443
  );
340
444
  return;
341
445
  }
342
- const safetyBak = join(homedir(), ".harnessed.legacy-bak");
446
+ const safetyBak = join(context.userHome, ".harnessed.legacy-bak");
343
447
  if (existsSync(safetyBak)) {
344
448
  console.error(
345
449
  `[harnessed] WARN: ${legacyRoot} reappeared after a prior migration (existing bak at ${safetyBak}); leaving in place \u2014 inspect manually if needed`
346
450
  );
347
451
  return;
348
452
  }
349
- renameSync(legacyRoot, safetyBak);
453
+ if (!renameLegacyRoot(legacyRoot, safetyBak)) return;
350
454
  console.error(
351
455
  `[harnessed] both ${legacyRoot} and ${newRoot} existed \u2014 legacy directory preserved at ${safetyBak} (review manually if you need data from it; v3.0.3 path change)`
352
456
  );
353
457
  }
354
458
  var init_harnessedRoot = __esm({
355
459
  "src/platform/harnessedRoot.ts"() {
460
+ init_hostInstallContext();
356
461
  init_platform();
357
462
  }
358
463
  });
@@ -568,6 +673,20 @@ var init_currentWorkflow_v1 = __esm({
568
673
  // (back-compat fail-soft; comet 0.3.9 phase-skip lesson).
569
674
  mode: Type.Optional(Type.Union([Type.Literal("serial"), Type.Literal("parallel")])),
570
675
  order: Type.Optional(Type.Integer()),
676
+ // Nested master replay identity. Additive-optional for old ledgers; new
677
+ // expansions stamp every child so replay can prove the exact parent,
678
+ // relative position, and child-plan length instead of matching a name prefix.
679
+ nested_expansion: Type.Optional(
680
+ Type.Object(
681
+ {
682
+ parent: Type.String({ minLength: 1 }),
683
+ index: Type.Integer({ minimum: 0 }),
684
+ length: Type.Integer({ minimum: 1 }),
685
+ start: Type.Integer({ minimum: 0 })
686
+ },
687
+ { additionalProperties: false }
688
+ )
689
+ ),
571
690
  // ── T2.7 (loop internalization) — three additive-optional fields that move the
572
691
  // completion GUARANTEE from the dead `harnessed run` path onto the ledger. Old
573
692
  // envelopes without them still Value.Check-pass → NO schemaVersion bump.
@@ -682,7 +801,8 @@ var init_checkpoint_v1 = __esm({
682
801
  CheckpointStatus = Type.Union([
683
802
  Type.Literal("active"),
684
803
  Type.Literal("paused"),
685
- Type.Literal("complete")
804
+ Type.Literal("complete"),
805
+ Type.Literal("failed")
686
806
  ]);
687
807
  CheckpointV1 = Type.Object(
688
808
  {
@@ -738,7 +858,7 @@ function lockTarget() {
738
858
  function lockOpts() {
739
859
  return {
740
860
  stale: 1e4,
741
- retries: { retries: 3, factor: 2, minTimeout: 100 },
861
+ retries: { retries: 20, factor: 1.3, minTimeout: 50, maxTimeout: 250, randomize: true },
742
862
  lockfilePath: harnessedFile(".lock")
743
863
  };
744
864
  }
@@ -1119,6 +1239,7 @@ var init_subAnchor = __esm({
1119
1239
  var ledger_exports = {};
1120
1240
  __export(ledger_exports, {
1121
1241
  annotateSpawnFailure: () => annotateSpawnFailure,
1242
+ expandNestedMaster: () => expandNestedMaster,
1122
1243
  findSerialBlockers: () => findSerialBlockers,
1123
1244
  markSub: () => markSub,
1124
1245
  nextPending: () => nextPending,
@@ -1151,6 +1272,96 @@ function seedLedger(plan) {
1151
1272
  );
1152
1273
  return [...fireEntries.map((e) => e.entry), ...skipEntries];
1153
1274
  }
1275
+ function orderBySequence(entries) {
1276
+ return entries.map((entry, index) => ({ entry, index })).sort((left, right) => {
1277
+ const orderDelta = (left.entry.order ?? PARALLEL_MID_ANCHOR) - (right.entry.order ?? PARALLEL_MID_ANCHOR);
1278
+ if (orderDelta !== 0) return orderDelta;
1279
+ if (left.entry.order === void 0 !== (right.entry.order === void 0)) {
1280
+ return left.entry.order === void 0 ? -1 : 1;
1281
+ }
1282
+ return left.index - right.index;
1283
+ }).map(({ entry }) => entry);
1284
+ }
1285
+ function renumberSequence(entries) {
1286
+ return entries.map((entry, index) => ({
1287
+ ...entry,
1288
+ order: index + 1,
1289
+ ...entry.nested_expansion ? {
1290
+ nested_expansion: {
1291
+ ...entry.nested_expansion,
1292
+ start: index - entry.nested_expansion.index
1293
+ }
1294
+ } : {}
1295
+ }));
1296
+ }
1297
+ function isEquivalentReplay(entries, children, parent) {
1298
+ if (children.length === 0) return false;
1299
+ if (entries.some((entry, index) => entry.order !== index + 1)) return false;
1300
+ const childSubs = new Set(children.map((entry) => entry.sub));
1301
+ if (entries.filter((entry) => childSubs.has(entry.sub)).length !== children.length) return false;
1302
+ return entries.some(
1303
+ (_, start) => children.every((expected, offset) => {
1304
+ const actual = entries[start + offset];
1305
+ if (!actual) return false;
1306
+ if (actual.sub !== expected.sub || actual.gate_fired !== expected.gate_fired || actual.mode !== expected.mode || actual.order !== start + offset + 1 || actual.nested_expansion?.parent !== parent || actual.nested_expansion.index !== offset || actual.nested_expansion.length !== children.length || actual.nested_expansion.start !== start) {
1307
+ return false;
1308
+ }
1309
+ return expected.status !== "skipped" || actual.status === "skipped" && actual.reason === expected.reason;
1310
+ })
1311
+ );
1312
+ }
1313
+ function expandNestedMaster(entries, parent, plan) {
1314
+ const seededChildren = orderBySequence(seedLedger(plan));
1315
+ const childSubs = seededChildren.map((entry) => entry.sub);
1316
+ if (childSubs.includes(parent)) {
1317
+ throw new Error(
1318
+ `expandNestedMaster: child sub '${parent}' conflicts with the parent ledger identity; nested expansion for '${parent}' was refused.`
1319
+ );
1320
+ }
1321
+ const duplicateChild = childSubs.find((sub, index) => childSubs.indexOf(sub) !== index);
1322
+ if (duplicateChild) {
1323
+ throw new Error(
1324
+ `expandNestedMaster: child sub '${duplicateChild}' conflicts with an existing ledger identity; nested expansion for '${parent}' was refused.`
1325
+ );
1326
+ }
1327
+ const parentIndex = entries.findIndex(
1328
+ (entry) => entry.sub === parent && entry.status === "pending"
1329
+ );
1330
+ if (parentIndex === -1) {
1331
+ if (entries.some((entry) => entry.sub === parent)) return { entries, matched: false };
1332
+ return { entries, matched: isEquivalentReplay(entries, seededChildren, parent) };
1333
+ }
1334
+ const conflictingSibling = entries.find(
1335
+ (entry, index) => index !== parentIndex && childSubs.includes(entry.sub)
1336
+ );
1337
+ if (conflictingSibling) {
1338
+ throw new Error(
1339
+ `expandNestedMaster: child sub '${conflictingSibling.sub}' conflicts with an existing ledger identity; nested expansion for '${parent}' was refused.`
1340
+ );
1341
+ }
1342
+ const orderedEntries = orderBySequence(entries);
1343
+ const orderedParentIndex = orderedEntries.findIndex(
1344
+ (entry) => entry.sub === parent && entry.status === "pending"
1345
+ );
1346
+ const children = seededChildren.map((entry, index) => ({
1347
+ ...entry,
1348
+ nested_expansion: {
1349
+ parent,
1350
+ index,
1351
+ length: seededChildren.length,
1352
+ start: orderedParentIndex
1353
+ }
1354
+ }));
1355
+ const expanded = [
1356
+ ...orderedEntries.slice(0, orderedParentIndex),
1357
+ ...children,
1358
+ ...orderedEntries.slice(orderedParentIndex + 1)
1359
+ ];
1360
+ return {
1361
+ entries: renumberSequence(expanded),
1362
+ matched: true
1363
+ };
1364
+ }
1154
1365
  function markSub(entries, sub, status, opts) {
1155
1366
  const idx = entries.findIndex((e) => e.sub === sub);
1156
1367
  if (idx === -1) {
@@ -1413,6 +1624,7 @@ var init_en = __esm({
1413
1624
  "setup.step_a_complete": "Step A: {{count}} workflows installed to {{path}}",
1414
1625
  "setup.step_a_render.complete": " generated {{count}}/{{total}} command files",
1415
1626
  "setup.step_a_render.warnings_header": " [A.5] warnings \u2014 some capability cmds could not be fully resolved:",
1627
+ "setup.command_warning": " [A.6] {{message}}",
1416
1628
  "setup.step_c.created": " [C] created {{path}} + enabled Agent Teams",
1417
1629
  "setup.step_c.already_enabled": " [C] Agent Teams already enabled ({{path}})",
1418
1630
  "setup.step_c.enabled_backup": " [C] enabled Agent Teams in {{path}} (backup saved \u2192 {{backupPath}})",
@@ -1982,8 +2194,8 @@ __export(agentsMd_exports, {
1982
2194
  runAgentsMd: () => runAgentsMd,
1983
2195
  stripAgentsMdSection: () => stripAgentsMdSection
1984
2196
  });
1985
- function agentsMdPath() {
1986
- return join(detectPlatform().homeDir, "AGENTS.md");
2197
+ function agentsMdPath(context) {
2198
+ return join(context?.nativeHome ?? detectPlatform().homeDir, "AGENTS.md");
1987
2199
  }
1988
2200
  function buildAgentsMdSection(opts) {
1989
2201
  const { commands, commandsDir, table: table2 } = opts;
@@ -2021,18 +2233,18 @@ function stripAgentsMdSection(body) {
2021
2233
  function insertAgentsMdSection(body, section) {
2022
2234
  const base = stripAgentsMdSection(body);
2023
2235
  if (section === "") return base;
2024
- const sep6 = base === "" || base.endsWith("\n\n") ? "" : base.endsWith("\n") ? "\n" : "\n\n";
2025
- return `${base}${sep6}${section}`;
2236
+ const sep5 = base === "" || base.endsWith("\n\n") ? "" : base.endsWith("\n") ? "\n" : "\n\n";
2237
+ return `${base}${sep5}${section}`;
2026
2238
  }
2027
2239
  async function resolveCommandNames(workflowsDir) {
2028
- const { readdir: readdir26 } = await import('fs/promises');
2029
- const entries = await readdir26(workflowsDir);
2240
+ const { readdir: readdir27 } = await import('fs/promises');
2241
+ const entries = await readdir27(workflowsDir);
2030
2242
  const { workflows } = await scanWorkflowsNested(workflowsDir, entries);
2031
2243
  const prompts = await loadRolePrompts(workflowsDir);
2032
2244
  return workflows.map((w) => w.name).filter((n) => prompts[n] !== void 0).sort();
2033
2245
  }
2034
2246
  async function runAgentsMd(opts) {
2035
- const path = agentsMdPath();
2247
+ const path = agentsMdPath(opts.hostContext);
2036
2248
  const read2 = opts.deps?.readFile ?? ((p8) => readFile(p8, "utf8"));
2037
2249
  const write = opts.deps?.writeFile ?? ((p8, c) => writeFile(p8, c, "utf8"));
2038
2250
  let current = "";
@@ -2052,7 +2264,7 @@ async function runAgentsMd(opts) {
2052
2264
  const locale = opts.locale ?? "en";
2053
2265
  const section = buildAgentsMdSection({
2054
2266
  commands: await resolveCommandNames(opts.workflowsDir),
2055
- commandsDir: detectPlatform().commandsDir,
2267
+ commandsDir: opts.hostContext?.platform.commandsDir ?? detectPlatform().commandsDir,
2056
2268
  table: await loadHostPrimitives({ workflowsDir: opts.workflowsDir, locale }),
2057
2269
  notes: await loadHostMapNotes({ workflowsDir: opts.workflowsDir, locale, host: "codex" })
2058
2270
  });
@@ -2094,8 +2306,10 @@ function registerAgentsMd(program2) {
2094
2306
  }
2095
2307
  const locale = getLocale();
2096
2308
  try {
2309
+ const hostContext = captureHostInstallContext({ hostId: "codex" });
2097
2310
  const r = await runAgentsMd({
2098
2311
  workflowsDir: join(getAssetsRoot(), "workflows"),
2312
+ hostContext,
2099
2313
  dryRun: raw.dryRun === true,
2100
2314
  remove: raw.remove === true,
2101
2315
  locale: locale === "zh-Hans" ? "zh-Hans" : "en"
@@ -2133,6 +2347,7 @@ var init_agents_md = __esm({
2133
2347
  "src/cli/agents-md.ts"() {
2134
2348
  init_i18n();
2135
2349
  init_assetsRoot();
2350
+ init_hostInstallContext();
2136
2351
  init_platform();
2137
2352
  init_agentsMd();
2138
2353
  }
@@ -3167,9 +3382,9 @@ function redactRecord(r) {
3167
3382
  }
3168
3383
  function renderHumanTable(records) {
3169
3384
  const header = `${"ts".padEnd(19)} | ${"phase".padEnd(6)} | ${"category".padEnd(11)} | ${"matched_rule_id".padEnd(20)} | outcome`;
3170
- const sep6 = `${"-".repeat(19)}-+-${"-".repeat(6)}-+-${"-".repeat(11)}-+-${"-".repeat(20)}-+--------`;
3385
+ const sep5 = `${"-".repeat(19)}-+-${"-".repeat(6)}-+-${"-".repeat(11)}-+-${"-".repeat(20)}-+--------`;
3171
3386
  console.log(header);
3172
- console.log(sep6);
3387
+ console.log(sep5);
3173
3388
  for (const r of records) {
3174
3389
  const ts = r.ts.slice(0, 19);
3175
3390
  const phase = r.phase.padEnd(6);
@@ -3179,7 +3394,7 @@ function renderHumanTable(records) {
3179
3394
  }
3180
3395
  }
3181
3396
  function pipeToJq(filterExpr, lines) {
3182
- return new Promise((resolve37, reject) => {
3397
+ return new Promise((resolve39, reject) => {
3183
3398
  const child = spawn("jq", [filterExpr], {
3184
3399
  stdio: ["pipe", "inherit", "inherit"],
3185
3400
  windowsHide: true
@@ -3188,12 +3403,12 @@ function pipeToJq(filterExpr, lines) {
3188
3403
  const e = err2;
3189
3404
  if (e.code === "ENOENT") {
3190
3405
  console.error(t("audit_log.jq_missing"));
3191
- resolve37(1);
3406
+ resolve39(1);
3192
3407
  } else {
3193
3408
  reject(err2);
3194
3409
  }
3195
3410
  });
3196
- child.on("close", (code2) => resolve37(code2 ?? 0));
3411
+ child.on("close", (code2) => resolve39(code2 ?? 0));
3197
3412
  child.stdin.on("error", (err2) => {
3198
3413
  if (err2.code !== "EPIPE") reject(err2);
3199
3414
  });
@@ -3693,6 +3908,32 @@ var init_runDeps = __esm({
3693
3908
  };
3694
3909
  }
3695
3910
  });
3911
+
3912
+ // src/checkpoint/failure.ts
3913
+ function hasLegacyFailedTask(lastTask) {
3914
+ return lastTask?.startsWith(LEGACY_FAILED_PREFIX) ?? false;
3915
+ }
3916
+ function isFailedCheckpoint(checkpoint) {
3917
+ return checkpoint.status === "failed" || hasLegacyFailedTask(checkpoint.last_task);
3918
+ }
3919
+ var LEGACY_FAILED_PREFIX;
3920
+ var init_failure = __esm({
3921
+ "src/checkpoint/failure.ts"() {
3922
+ LEGACY_FAILED_PREFIX = "FAILED:";
3923
+ }
3924
+ });
3925
+ function ownerHash(ownerKey = activeKey()) {
3926
+ return createHash("sha256").update(ownerKey).digest("hex").slice(0, 16);
3927
+ }
3928
+ function ownerPath(area, segments, ownerKey = activeKey()) {
3929
+ return join(harnessedSubdir(area), ownerHash(ownerKey), ...segments);
3930
+ }
3931
+ var init_ownerPath = __esm({
3932
+ "src/checkpoint/ownerPath.ts"() {
3933
+ init_harnessedRoot();
3934
+ init_workflowStore();
3935
+ }
3936
+ });
3696
3937
  function estimateTokens(s) {
3697
3938
  return Math.ceil(Buffer.byteLength(s, "utf8") / 4);
3698
3939
  }
@@ -3716,7 +3957,7 @@ function writeCheckpoint(c, customPath) {
3716
3957
  throw new CheckpointWriteError(`Schema validation failed: ${errs}`);
3717
3958
  }
3718
3959
  const enforced = enforceBudget(c);
3719
- const path = join(harnessedSubdir("checkpoints"), `${enforced.phase}.json`);
3960
+ const path = ownerPath("checkpoints", [`${enforced.phase}.json`]);
3720
3961
  mkdirSync(dirname(path), { recursive: true });
3721
3962
  writeFileSyncAtomic(path, JSON.stringify(enforced, null, 2));
3722
3963
  return path;
@@ -3724,8 +3965,8 @@ function writeCheckpoint(c, customPath) {
3724
3965
  var BUDGET_TOKEN, CheckpointTooLargeError, CheckpointWriteError;
3725
3966
  var init_template = __esm({
3726
3967
  "src/checkpoint/template.ts"() {
3727
- init_harnessedRoot();
3728
3968
  init_atomicWrite();
3969
+ init_ownerPath();
3729
3970
  init_schema();
3730
3971
  BUDGET_TOKEN = 1e3;
3731
3972
  CheckpointTooLargeError = class extends Error {
@@ -3750,27 +3991,27 @@ __export(engineHook_exports, {
3750
3991
  completePhase: () => completePhase
3751
3992
  });
3752
3993
  async function activatePhase(phaseId) {
3753
- const checkpointPath = join(harnessedSubdir("checkpoints"), `${phaseId}.json`);
3994
+ const checkpointPath = ownerPath("checkpoints", [`${phaseId}.json`]);
3754
3995
  await activate(phaseId, checkpointPath);
3755
3996
  return { checkpointPath };
3756
3997
  }
3757
3998
  async function completePhase(ctx) {
3758
3999
  if (ctx.phaseId === "unknown") {
3759
4000
  console.error(
3760
- `[harnessed] WARN engineHook: phaseId="unknown" \u2014 checkpoint paths fall back to ${join(harnessedSubdir("checkpoints"), "unknown.json")} (Karpathy fail-loud non-blocking; W-04 mitigation)`
4001
+ `[harnessed] WARN engineHook: phaseId="unknown" \u2014 checkpoint paths fall back to ${ownerPath("checkpoints", ["unknown.json"])} (Karpathy fail-loud non-blocking; W-04 mitigation)`
3761
4002
  );
3762
4003
  }
3763
4004
  writeCheckpoint({
3764
4005
  schemaVersion: SCHEMA_VERSIONS.checkpoint,
3765
4006
  phase: ctx.phaseId,
3766
- status: "complete",
4007
+ status: ctx.status === "failed" || hasLegacyFailedTask(ctx.lastTask) ? "failed" : ctx.status,
3767
4008
  last_task: ctx.lastTask ?? "engine.runRouting complete",
3768
4009
  key_decisions: ctx.keyDecisions ?? [],
3769
4010
  canonical_refs: ctx.canonicalRefs ?? [],
3770
4011
  ...ctx.sessionId ? { session_id: ctx.sessionId } : {},
3771
4012
  cwd: process.cwd(),
3772
4013
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
3773
- archive_path: `${join(harnessedSubdir("archive"), `phase-${ctx.phaseId}`)}/`
4014
+ archive_path: `${ownerPath("archive", [`phase-${ctx.phaseId}`])}/`
3774
4015
  });
3775
4016
  if (ctx.transitionWorkflowComplete !== false) {
3776
4017
  await complete();
@@ -3778,53 +4019,13 @@ async function completePhase(ctx) {
3778
4019
  }
3779
4020
  var init_engineHook = __esm({
3780
4021
  "src/checkpoint/engineHook.ts"() {
3781
- init_harnessedRoot();
3782
4022
  init_schemaVersion();
4023
+ init_failure();
4024
+ init_ownerPath();
3783
4025
  init_state();
3784
4026
  init_template();
3785
4027
  }
3786
4028
  });
3787
- function createHostInstallContext(platform, selection) {
3788
- if (platform.id !== "claude" && platform.id !== "codex") {
3789
- throw new Error(`unsupported host: ${platform.id}`);
3790
- }
3791
- const nativeHome = platform.id === "codex" ? selection.nativeHome?.trim() : selection.nativeHome;
3792
- const neutralSpawnCwd = selection.neutralSpawnCwd?.trim();
3793
- return Object.freeze({
3794
- hostId: platform.id,
3795
- os: selection.os,
3796
- userHome: selection.userHome,
3797
- platform: Object.freeze({ ...platform }),
3798
- nativeHome: nativeHome || platform.homeDir,
3799
- ...neutralSpawnCwd ? { neutralSpawnCwd } : {}
3800
- });
3801
- }
3802
- function captureHostInstallContext(options = {}) {
3803
- if (options.hostId !== void 0 && !isHostId(options.hostId)) {
3804
- throw new Error(`unsupported host: ${options.hostId}`);
3805
- }
3806
- const userHome = options.userHome ?? homedir();
3807
- let platform;
3808
- if (options.hostId === void 0) {
3809
- platform = detectPlatform(userHome);
3810
- } else {
3811
- platform = descriptorFor(options.hostId, userHome);
3812
- const stateRoot = process.env.HARNESSED_ROOT_OVERRIDE;
3813
- if (stateRoot !== void 0 && stateRoot !== "") platform = { ...platform, stateRoot };
3814
- }
3815
- const rootKey = platform.id === "codex" ? "CODEX_HOME" : "CLAUDE_CONFIG_DIR";
3816
- return createHostInstallContext(platform, {
3817
- os: options.os ?? process.platform,
3818
- userHome,
3819
- nativeHome: process.env[rootKey],
3820
- neutralSpawnCwd: process.env.HARNESSED_SPAWN_CWD
3821
- });
3822
- }
3823
- var init_hostInstallContext = __esm({
3824
- "src/platform/hostInstallContext.ts"() {
3825
- init_platform();
3826
- }
3827
- });
3828
4029
 
3829
4030
  // src/installers/lib/killTree.ts
3830
4031
  var killTree_exports = {};
@@ -3888,7 +4089,7 @@ function resolveWindowsBin(bin, env = process.env, isFile = (p8) => existsSync(p
3888
4089
  const candidates = extname(bin) ? [""] : exts;
3889
4090
  for (const dir of dirs) {
3890
4091
  for (const ext of candidates) {
3891
- const p8 = join18(dir, `${bin}${ext}`);
4092
+ const p8 = join17(dir, `${bin}${ext}`);
3892
4093
  if (isFile(p8)) return p8;
3893
4094
  }
3894
4095
  }
@@ -3903,10 +4104,10 @@ function planWindowsSpawn(bin, args, resolved) {
3903
4104
  const line = [escapeCommand(resolved), ...args.map((a) => escapeArgument(a))].join(" ");
3904
4105
  return { command: "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
3905
4106
  }
3906
- var extname, join18, META;
4107
+ var extname, join17, META;
3907
4108
  var init_winSpawn = __esm({
3908
4109
  "src/installers/lib/winSpawn.ts"() {
3909
- ({ extname, join: join18 } = win32);
4110
+ ({ extname, join: join17 } = win32);
3910
4111
  META = /([()\][%!^"`<>&|;, *?])/g;
3911
4112
  }
3912
4113
  });
@@ -3929,7 +4130,7 @@ function withHostInstallEnv(env, hostContext) {
3929
4130
  return { ...result, ...pins };
3930
4131
  }
3931
4132
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
3932
- return new Promise((resolve37) => {
4133
+ return new Promise((resolve39) => {
3933
4134
  const isWin = (hostContext?.os ?? process.platform) === "win32";
3934
4135
  const envOpts = hostContext ? { env: withHostInstallEnv(process.env, hostContext) } : {};
3935
4136
  const stdio = ["ignore", "pipe", "pipe"];
@@ -3957,17 +4158,17 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
3957
4158
  });
3958
4159
  const timer = setTimeout(() => {
3959
4160
  killProcessTree(child);
3960
- resolve37({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
4161
+ resolve39({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
3961
4162
  }, timeoutMs);
3962
4163
  child.on("error", (e) => {
3963
4164
  clearTimeout(timer);
3964
4165
  const enoent = e.code === "ENOENT";
3965
4166
  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;
3966
- resolve37({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
4167
+ resolve39({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
3967
4168
  });
3968
4169
  child.on("close", (code2) => {
3969
4170
  clearTimeout(timer);
3970
- resolve37({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
4171
+ resolve39({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
3971
4172
  });
3972
4173
  });
3973
4174
  }
@@ -4249,6 +4450,168 @@ var init_readClaudeConfig = __esm({
4249
4450
  init_codexPlugins();
4250
4451
  }
4251
4452
  });
4453
+ function lockRoots(hostContext) {
4454
+ return [join(hostContext?.nativeHome ?? detectPlatform().homeDir, "harnessed")];
4455
+ }
4456
+ async function withSettingsTransactionLock(hostContext, work) {
4457
+ const active = heldLocks.getStore();
4458
+ const roots = lockRoots(hostContext);
4459
+ if (roots.every((root) => active?.has(root))) return work();
4460
+ const releases = [];
4461
+ const next = new Set(active);
4462
+ try {
4463
+ for (const root of roots) {
4464
+ if (next.has(root)) continue;
4465
+ await mkdir(root, { recursive: true });
4466
+ releases.push(
4467
+ await lockfile.lock(root, {
4468
+ stale: 6e4,
4469
+ retries: {
4470
+ retries: 20,
4471
+ factor: 1.3,
4472
+ minTimeout: 50,
4473
+ maxTimeout: 250,
4474
+ randomize: true
4475
+ },
4476
+ lockfilePath: join(root, ".settings-transaction.lock")
4477
+ })
4478
+ );
4479
+ next.add(root);
4480
+ }
4481
+ return await heldLocks.run(next, work);
4482
+ } finally {
4483
+ for (const release of releases.reverse()) await release();
4484
+ }
4485
+ }
4486
+ var heldLocks;
4487
+ var init_settingsTransactionLock = __esm({
4488
+ "src/cli/lib/settingsTransactionLock.ts"() {
4489
+ init_platform();
4490
+ heldLocks = new AsyncLocalStorage();
4491
+ }
4492
+ });
4493
+ function settingsOwnershipReceiptPath(hostContext) {
4494
+ return hostContext ? join(hostContext.platform.stateRoot, SETTINGS_OWNERSHIP_RECEIPT_FILE) : harnessedFile(SETTINGS_OWNERSHIP_RECEIPT_FILE);
4495
+ }
4496
+ async function loadSettingsOwnershipReceipt(hostContext) {
4497
+ const path = settingsOwnershipReceiptPath(hostContext);
4498
+ let raw;
4499
+ try {
4500
+ raw = await readFile(path, "utf8");
4501
+ } catch (error) {
4502
+ if (error.code === "ENOENT") {
4503
+ try {
4504
+ const parent = await stat(dirname(path));
4505
+ if (!parent.isDirectory()) {
4506
+ return { status: "error", error: `receipt parent is not a directory: ${dirname(path)}` };
4507
+ }
4508
+ } catch (parentError) {
4509
+ if (parentError.code !== "ENOENT") {
4510
+ return {
4511
+ status: "error",
4512
+ error: `inspect ${dirname(path)} failed: ${parentError.message}`
4513
+ };
4514
+ }
4515
+ }
4516
+ return { status: "absent" };
4517
+ }
4518
+ return { status: "error", error: `read ${path} failed: ${error.message}` };
4519
+ }
4520
+ let parsed;
4521
+ try {
4522
+ parsed = JSON.parse(raw);
4523
+ } catch (error) {
4524
+ return { status: "corrupt", error: `parse ${path} failed: ${error.message}` };
4525
+ }
4526
+ if (!isReceipt(parsed)) return { status: "corrupt", error: `invalid receipt at ${path}` };
4527
+ return { status: "ok", receipt: parsed };
4528
+ }
4529
+ async function recordSettingsEnvOwnershipUnlocked(key, installedValue, previous, hostContext) {
4530
+ if (!MANAGED_ENV_KEYS.has(key)) throw new Error(`unsupported managed settings env key: ${key}`);
4531
+ if (previous.present && typeof previous.value !== "string") {
4532
+ throw new Error(`invalid previous value for managed settings env key: ${key}`);
4533
+ }
4534
+ const loaded = await loadSettingsOwnershipReceipt(hostContext);
4535
+ if (loaded.status === "corrupt" || loaded.status === "error") throw new Error(loaded.error);
4536
+ const existing = loaded.status === "ok" ? loaded.receipt : null;
4537
+ const priorEntry = existing?.entries[key];
4538
+ const retainedPrevious = priorEntry && previous.present && previous.value === priorEntry.installedValue ? priorEntry.previous : previous;
4539
+ const receipt = {
4540
+ version: 1,
4541
+ entries: {
4542
+ ...existing?.entries ?? {},
4543
+ [key]: { installedValue, previous: retainedPrevious }
4544
+ }
4545
+ };
4546
+ const path = settingsOwnershipReceiptPath(hostContext);
4547
+ const tmpPath = `${path}.tmp-${process.pid}-${Date.now()}`;
4548
+ await mkdir(dirname(path), { recursive: true });
4549
+ try {
4550
+ await writeFile(tmpPath, `${JSON.stringify(receipt, null, 2)}
4551
+ `, "utf8");
4552
+ await rename(tmpPath, path);
4553
+ } catch (error) {
4554
+ await rm(tmpPath, { force: true }).catch(() => void 0);
4555
+ throw error;
4556
+ }
4557
+ }
4558
+ function restoreOwnedSettingsEnv(data, receipt) {
4559
+ if (data.env !== void 0 && !isPlainRecord(data.env)) {
4560
+ throw new Error("settings env is not a JSON object");
4561
+ }
4562
+ const env = data.env ?? {};
4563
+ let restored = 0;
4564
+ let removed = 0;
4565
+ for (const [key, entry] of Object.entries(receipt.entries)) {
4566
+ if (!isManagedEntry(key, entry)) continue;
4567
+ if (env[key] !== entry.installedValue) continue;
4568
+ if (entry.previous.present) {
4569
+ env[key] = entry.previous.value;
4570
+ restored++;
4571
+ } else {
4572
+ delete env[key];
4573
+ removed++;
4574
+ }
4575
+ }
4576
+ const changed = restored + removed > 0;
4577
+ if (changed) {
4578
+ if (Object.keys(env).length === 0) delete data.env;
4579
+ else data.env = env;
4580
+ }
4581
+ return { changed, restored, removed };
4582
+ }
4583
+ function isPlainRecord(value) {
4584
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
4585
+ const prototype = Object.getPrototypeOf(value);
4586
+ return prototype === Object.prototype || prototype === null;
4587
+ }
4588
+ function isReceipt(value) {
4589
+ if (!value || typeof value !== "object" || Array.isArray(value)) return false;
4590
+ const receipt = value;
4591
+ if (receipt.version !== 1 || !receipt.entries || typeof receipt.entries !== "object") return false;
4592
+ return Object.entries(receipt.entries).every(([key, entry]) => isManagedEntry(key, entry));
4593
+ }
4594
+ function isManagedEntry(key, value) {
4595
+ if (!MANAGED_ENV_KEYS.has(key) || value === null || typeof value !== "object") return false;
4596
+ const entry = value;
4597
+ if (typeof entry.installedValue !== "string" || entry.previous === null || typeof entry.previous !== "object" || typeof entry.previous.present !== "boolean") {
4598
+ return false;
4599
+ }
4600
+ return !entry.previous.present || typeof entry.previous.value === "string";
4601
+ }
4602
+ var SETTINGS_OWNERSHIP_RECEIPT_FILE, MANAGED_ENV_KEYS;
4603
+ var init_settingsOwnershipReceipt = __esm({
4604
+ "src/cli/lib/settingsOwnershipReceipt.ts"() {
4605
+ init_harnessedRoot();
4606
+ init_settingsTransactionLock();
4607
+ SETTINGS_OWNERSHIP_RECEIPT_FILE = "settings-env-ownership.json";
4608
+ MANAGED_ENV_KEYS = /* @__PURE__ */ new Set([
4609
+ "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS",
4610
+ "GATEGUARD_EXEMPT_GLOBS",
4611
+ "HARNESSED_USER_LANG"
4612
+ ]);
4613
+ }
4614
+ });
4252
4615
  async function mergeSettingsEnvKey(key, value, opts = {}) {
4253
4616
  const hostContext = opts.hostContext;
4254
4617
  const path = hostContext ? hostContext.hostId === "claude" && hostContext.platform.supportsEnvKeyWrite ? join(hostContext.nativeHome, "settings.json") : null : getSettingsPath();
@@ -4257,6 +4620,19 @@ async function mergeSettingsEnvKey(key, value, opts = {}) {
4257
4620
  outcome: "warn",
4258
4621
  message: `no settings file on ${hostContext?.hostId ?? detectPlatform().id} \u2014 skipped`
4259
4622
  };
4623
+ try {
4624
+ return await withSettingsTransactionLock(
4625
+ hostContext,
4626
+ () => mergeSettingsEnvKeyUnlocked(path, key, value, opts, hostContext)
4627
+ );
4628
+ } catch (error) {
4629
+ return {
4630
+ outcome: "warn",
4631
+ message: `settings transaction lock failed: ${error.message}`
4632
+ };
4633
+ }
4634
+ }
4635
+ async function mergeSettingsEnvKeyUnlocked(path, key, value, opts, hostContext) {
4260
4636
  let raw;
4261
4637
  try {
4262
4638
  raw = await readFile(path, "utf8");
@@ -4265,7 +4641,7 @@ async function mergeSettingsEnvKey(key, value, opts = {}) {
4265
4641
  if (code2 !== "ENOENT") {
4266
4642
  return { outcome: "warn", message: `read ${path} failed: ${err2.message}` };
4267
4643
  }
4268
- return createFresh(path, key, value);
4644
+ return createFresh(path, key, value, hostContext);
4269
4645
  }
4270
4646
  let data;
4271
4647
  try {
@@ -4277,6 +4653,9 @@ async function mergeSettingsEnvKey(key, value, opts = {}) {
4277
4653
  } catch (err2) {
4278
4654
  return { outcome: "warn", message: `${path} malformed JSON: ${err2.message}` };
4279
4655
  }
4656
+ if (data.env !== void 0 && !isPlainRecord2(data.env)) {
4657
+ return { outcome: "warn", message: `${path} env is not a JSON object` };
4658
+ }
4280
4659
  const env = data.env ?? {};
4281
4660
  const existing = env[key];
4282
4661
  if (typeof existing === "string" && existing.length > 0 && opts.skipIfPresent?.(existing) === true) {
@@ -4288,9 +4667,24 @@ async function mergeSettingsEnvKey(key, value, opts = {}) {
4288
4667
  const writeErr = await atomicWrite(path, `${JSON.stringify(data, null, 2)}
4289
4668
  `);
4290
4669
  if (writeErr) return { outcome: "warn", message: writeErr };
4670
+ try {
4671
+ await recordSettingsEnvOwnershipUnlocked(
4672
+ key,
4673
+ value,
4674
+ { present: Object.hasOwn(env, key), value: existing },
4675
+ hostContext
4676
+ );
4677
+ } catch (err2) {
4678
+ const rollbackErr = await atomicWrite(path, raw);
4679
+ const suffix = rollbackErr ? `; rollback failed: ${rollbackErr}` : "; settings restored";
4680
+ return {
4681
+ outcome: "warn",
4682
+ message: `ownership receipt failed: ${err2.message}${suffix}`
4683
+ };
4684
+ }
4291
4685
  return { outcome: "merged", path, backupPath: backup2.path };
4292
4686
  }
4293
- async function createFresh(path, key, value) {
4687
+ async function createFresh(path, key, value, hostContext) {
4294
4688
  const data = { env: { [key]: value } };
4295
4689
  try {
4296
4690
  await mkdir(dirname(path), { recursive: true });
@@ -4300,8 +4694,27 @@ async function createFresh(path, key, value) {
4300
4694
  const writeErr = await atomicWrite(path, `${JSON.stringify(data, null, 2)}
4301
4695
  `);
4302
4696
  if (writeErr) return { outcome: "warn", message: writeErr };
4697
+ try {
4698
+ await recordSettingsEnvOwnershipUnlocked(key, value, { present: false }, hostContext);
4699
+ } catch (err2) {
4700
+ let rollbackMessage = "; created settings removed";
4701
+ try {
4702
+ await rm(path, { force: true });
4703
+ } catch (rollbackError) {
4704
+ rollbackMessage = `; rollback failed: ${rollbackError.message}`;
4705
+ }
4706
+ return {
4707
+ outcome: "warn",
4708
+ message: `ownership receipt failed: ${err2.message}${rollbackMessage}`
4709
+ };
4710
+ }
4303
4711
  return { outcome: "created", path };
4304
4712
  }
4713
+ function isPlainRecord2(value) {
4714
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
4715
+ const prototype = Object.getPrototypeOf(value);
4716
+ return prototype === Object.prototype || prototype === null;
4717
+ }
4305
4718
  async function backupOriginal(raw, hostContext) {
4306
4719
  const backupRoot = hostContext ? join(hostContext.platform.stateRoot, "backups") : harnessedSubdir("backups");
4307
4720
  const ts = (/* @__PURE__ */ new Date()).toISOString().replace(/:/g, "-");
@@ -4321,6 +4734,10 @@ async function atomicWrite(path, content) {
4321
4734
  await rename(tmpPath, path);
4322
4735
  return void 0;
4323
4736
  } catch (err2) {
4737
+ try {
4738
+ await rm(tmpPath, { force: true });
4739
+ } catch {
4740
+ }
4324
4741
  return `write ${path} failed: ${err2.message}`;
4325
4742
  }
4326
4743
  }
@@ -4328,6 +4745,8 @@ var init_settingsWriter = __esm({
4328
4745
  "src/cli/lib/settingsWriter.ts"() {
4329
4746
  init_harnessedRoot();
4330
4747
  init_platform();
4748
+ init_settingsOwnershipReceipt();
4749
+ init_settingsTransactionLock();
4331
4750
  }
4332
4751
  });
4333
4752
 
@@ -6165,12 +6584,29 @@ async function runCheckpointStart(sub, opts, deps = defaultRunDeps) {
6165
6584
  }
6166
6585
  } catch {
6167
6586
  }
6168
- const { checkpointPath } = await activatePhase2(sub);
6169
6587
  const plan = await parsePlan(opts.plan);
6588
+ let checkpointPath;
6589
+ let nestedMaster = false;
6170
6590
  if (plan) {
6171
- const { seedLedger: seedLedger2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
6172
- const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
6173
- await mutateSubProgress2(() => seedLedger2(plan));
6591
+ const { expandNestedMaster: expandNestedMaster2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
6592
+ const { mutateWorkflow: mutateWorkflow2 } = await Promise.resolve().then(() => (init_state(), state_exports));
6593
+ await mutateWorkflow2((workflow) => {
6594
+ if (workflow.phase === sub) return workflow;
6595
+ const expanded = expandNestedMaster2(workflow.sub_progress ?? [], sub, plan);
6596
+ if (!expanded.matched) return workflow;
6597
+ nestedMaster = true;
6598
+ checkpointPath = workflow.last_checkpoint_path ?? `[root workflow ${workflow.phase}]`;
6599
+ return expanded.entries === workflow.sub_progress ? workflow : { ...workflow, sub_progress: expanded.entries };
6600
+ });
6601
+ }
6602
+ if (!nestedMaster) {
6603
+ const activated = await activatePhase2(sub);
6604
+ checkpointPath = activated.checkpointPath;
6605
+ if (plan) {
6606
+ const { seedLedger: seedLedger2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
6607
+ const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
6608
+ await mutateSubProgress2(() => seedLedger2(plan));
6609
+ }
6174
6610
  }
6175
6611
  try {
6176
6612
  const { mutateStore: mutateStore2 } = await Promise.resolve().then(() => (init_state(), state_exports));
@@ -6362,7 +6798,7 @@ async function runCheckpointFail(sub, opts, deps = defaultRunDeps) {
6362
6798
  await absorbIntentFor(sub);
6363
6799
  await completePhase2({
6364
6800
  phaseId: sub,
6365
- status: "complete",
6801
+ status: "failed",
6366
6802
  lastTask: `FAILED: ${opts.summary ?? ""}`,
6367
6803
  transitionWorkflowComplete: false
6368
6804
  });
@@ -6821,8 +7257,8 @@ function compute(d) {
6821
7257
  }
6822
7258
  const gitFirst = d.where("git")[0];
6823
7259
  if (gitFirst && /git\.exe$/i.test(gitFirst)) {
6824
- const root = dirname10(dirname10(gitFirst));
6825
- for (const cand of [join29(root, "bin", "bash.exe"), join29(root, "usr", "bin", "bash.exe")]) {
7260
+ const root = dirname12(dirname12(gitFirst));
7261
+ for (const cand of [join30(root, "bin", "bash.exe"), join30(root, "usr", "bin", "bash.exe")]) {
6826
7262
  if (d.exists(cand) && usable(cand)) return { path: cand, source: "git-derived", wslOnPath };
6827
7263
  }
6828
7264
  }
@@ -6830,13 +7266,13 @@ function compute(d) {
6830
7266
  d.env.ProgramFiles,
6831
7267
  d.env.ProgramW6432,
6832
7268
  d.env["ProgramFiles(x86)"],
6833
- d.env.LOCALAPPDATA ? join29(d.env.LOCALAPPDATA, "Programs") : void 0
7269
+ d.env.LOCALAPPDATA ? join30(d.env.LOCALAPPDATA, "Programs") : void 0
6834
7270
  ];
6835
7271
  for (const base of bases) {
6836
7272
  if (!base) continue;
6837
7273
  for (const cand of [
6838
- join29(base, "Git", "bin", "bash.exe"),
6839
- join29(base, "Git", "usr", "bin", "bash.exe")
7274
+ join30(base, "Git", "bin", "bash.exe"),
7275
+ join30(base, "Git", "usr", "bin", "bash.exe")
6840
7276
  ]) {
6841
7277
  if (d.exists(cand) && usable(cand))
6842
7278
  return { path: cand, source: "standard-location", wslOnPath };
@@ -6849,10 +7285,10 @@ function compute(d) {
6849
7285
  }
6850
7286
  return { path: "bash", source: "path-fallback" };
6851
7287
  }
6852
- var dirname10, join29, WSL_STUB_RE, cache4;
7288
+ var dirname12, join30, WSL_STUB_RE, cache4;
6853
7289
  var init_resolveBash = __esm({
6854
7290
  "src/installers/lib/resolveBash.ts"() {
6855
- ({ dirname: dirname10, join: join29 } = win32);
7291
+ ({ dirname: dirname12, join: join30 } = win32);
6856
7292
  WSL_STUB_RE = /[\\/](windows[\\/](system32|sysnative|syswow64)|microsoft[\\/]windowsapps)[\\/]bash\.exe$/i;
6857
7293
  cache4 = null;
6858
7294
  }
@@ -8296,6 +8732,48 @@ function stripQuotes(token2) {
8296
8732
  function splitTokens(raw) {
8297
8733
  return raw.split(/\s+/).filter((t2) => t2.length > 0);
8298
8734
  }
8735
+ function commandScriptPath(command, marker) {
8736
+ const match = command.match(/^\s*(?:node|bun)\s+(?:"([^"]+)"|'([^']+)'|(\S+))(?:\s|$)/);
8737
+ const path = match?.[1] ?? match?.[2] ?? match?.[3];
8738
+ if (!path) return null;
8739
+ const normalized2 = path.replace(/\\/g, "/");
8740
+ return normalized2.split("/").at(-1) === `harnessed-${marker}.mjs` ? normalized2 : null;
8741
+ }
8742
+ function versionedAssetsIdentity(path, marker) {
8743
+ const match = path.match(new RegExp(`^(.*/assets/)[^/]+(/bin/harnessed-${marker}\\.mjs)$`, "i"));
8744
+ return match?.[1] && match[2] ? `${match[1].toLowerCase()}*${match[2].toLowerCase()}` : null;
8745
+ }
8746
+ function isTrustedAssetsScript(command, resolved, marker) {
8747
+ const commandPath = commandScriptPath(command, marker);
8748
+ const resolvedPath = commandScriptPath(resolved, marker);
8749
+ if (!commandPath || !resolvedPath) return false;
8750
+ if (commandPath.toLowerCase() === resolvedPath.toLowerCase()) return true;
8751
+ const commandIdentity = versionedAssetsIdentity(commandPath, marker);
8752
+ return commandIdentity !== null && commandIdentity === versionedAssetsIdentity(resolvedPath, marker);
8753
+ }
8754
+ function trustedCompiledPaths(resolved) {
8755
+ const paths = /* @__PURE__ */ new Set();
8756
+ const normalize2 = (path) => path.replace(/\\/g, "/").toLowerCase();
8757
+ const localAppData = process.env.LOCALAPPDATA;
8758
+ if (localAppData) paths.add(normalize2(join(localAppData, "harnessed", "bin", "harnessed.exe")));
8759
+ paths.add(normalize2(join(homedir(), "AppData", "Local", "harnessed", "bin", "harnessed.exe")));
8760
+ paths.add(normalize2(join(homedir(), ".local", "bin", "harnessed")));
8761
+ const resolvedPath = commandScriptPath(resolved, "inject-state") ?? commandScriptPath(resolved, "stop-hook") ?? commandScriptPath(resolved, "check-docs") ?? commandScriptPath(resolved, "update-reminder");
8762
+ const hostHome = resolvedPath?.match(/^(.*)\/(?:\.claude|\.codex)\/harnessed\/assets\//i)?.[1];
8763
+ if (hostHome) {
8764
+ paths.add(normalize2(`${hostHome}/.local/bin/harnessed`));
8765
+ paths.add(normalize2(`${hostHome}/AppData/Local/harnessed/bin/harnessed.exe`));
8766
+ }
8767
+ return paths;
8768
+ }
8769
+ function isTrustedCompiledTransport(command, resolved, marker) {
8770
+ const match = command.match(
8771
+ new RegExp(`^\\s*(?:"([^"]+)"|'([^']+)'|(\\S+))\\s+${marker}(?:\\s|$)`)
8772
+ );
8773
+ const path = match?.[1] ?? match?.[2] ?? match?.[3];
8774
+ if (!path) return false;
8775
+ return trustedCompiledPaths(resolved).has(path.replace(/\\/g, "/").toLowerCase());
8776
+ }
8299
8777
  function hookMarkerAt(raw) {
8300
8778
  const tokens = splitTokens(raw);
8301
8779
  for (const [i, token2] of tokens.entries()) {
@@ -8304,7 +8782,7 @@ function hookMarkerAt(raw) {
8304
8782
  const seg = bare2.split(/[\\/]/);
8305
8783
  const base = seg[seg.length - 1];
8306
8784
  if (base === void 0) return null;
8307
- const id = COMPILED_HOOK_IDENTITIES.find((k) => base.includes(k));
8785
+ const id = COMPILED_HOOK_IDENTITIES.find((k) => base === `harnessed-${k}.mjs`);
8308
8786
  return { marker: id ?? base, index: i };
8309
8787
  }
8310
8788
  for (const [i, token2] of tokens.entries()) {
@@ -8363,7 +8841,15 @@ function entryCommands(entry) {
8363
8841
  function entryMatchesRegistration(entry, raw, resolved, marker) {
8364
8842
  const cmds = entryCommands(entry);
8365
8843
  if (cmds.length === 0) return false;
8366
- if (marker) return cmds.some((c) => c.includes(marker));
8844
+ if (marker) {
8845
+ const known = COMPILED_HOOK_IDENTITIES.includes(marker);
8846
+ return cmds.some((command) => {
8847
+ if (command === raw || command === resolved) return true;
8848
+ if (!known) return false;
8849
+ const tokens = splitTokens(command).map((token2) => stripQuotes(token2).bare);
8850
+ return tokens[0] === "harnessed" && tokens[1] === marker || isTrustedCompiledTransport(command, resolved, marker) || isTrustedAssetsScript(command, resolved, marker);
8851
+ });
8852
+ }
8367
8853
  return cmds.some((c) => c === raw || c === resolved);
8368
8854
  }
8369
8855
  function desiredHookEntry(matcher, resolvedCmd) {
@@ -8407,12 +8893,49 @@ var init_hookEntry = __esm({
8407
8893
  ABSOLUTE_RE = /^([A-Za-z]:[\\/]|[\\/])/;
8408
8894
  }
8409
8895
  });
8410
-
8411
- // src/installers/lib/harnessedHookTeardown.ts
8896
+ function pathKey(path) {
8897
+ const normalized2 = path.replace(/\\/g, "/");
8898
+ return /^(?:[A-Za-z]:\/|\/\/)/.test(normalized2) ? normalized2.toLowerCase() : normalized2;
8899
+ }
8900
+ function commandScriptPath2(raw, id) {
8901
+ const match = raw.match(/^\s*(?:node|bun)\s+(?:"([^"]+)"|'([^']+)'|(\S+))(?:\s|$)/);
8902
+ const path = match?.[1] ?? match?.[2] ?? match?.[3];
8903
+ if (!path) return null;
8904
+ const normalized2 = path.replace(/\\/g, "/");
8905
+ return pathKey(normalized2).split("/").at(-1) === `harnessed-${id}.mjs` ? normalized2 : null;
8906
+ }
8907
+ function isTrustedScriptPath(path, id) {
8908
+ const file = `harnessed-${id}.mjs`;
8909
+ const relative10 = path.replace(/^\.\//, "");
8910
+ if (relative10 === `bin/${file}`) return true;
8911
+ if (!ABSOLUTE_RE2.test(path)) return false;
8912
+ const resolved = `${CAPTURED_ASSETS_ROOT}/bin/${file}`;
8913
+ if (pathKey(path) === pathKey(resolved)) return true;
8914
+ const versioned = new RegExp(`^(.+/assets/)[^/]+(/bin/${file})$`);
8915
+ const candidate = pathKey(path).match(versioned);
8916
+ const captured = pathKey(resolved).match(versioned);
8917
+ if (!candidate || !captured) return false;
8918
+ return candidate[1] === captured[1] && candidate[2] === captured[2];
8919
+ }
8920
+ function trustedCompiledPaths2() {
8921
+ const paths = /* @__PURE__ */ new Set();
8922
+ const localAppData = process.env.LOCALAPPDATA;
8923
+ if (localAppData) paths.add(pathKey(join(localAppData, "harnessed", "bin", "harnessed.exe")));
8924
+ paths.add(pathKey(join(homedir(), "AppData", "Local", "harnessed", "bin", "harnessed.exe")));
8925
+ paths.add(pathKey(join(homedir(), ".local", "bin", "harnessed")));
8926
+ return paths;
8927
+ }
8928
+ function commandBinaryPath(raw, id) {
8929
+ const match = raw.match(new RegExp(`^\\s*(?:"([^"]+)"|'([^']+)'|(\\S+))\\s+${id}(?:\\s|$)`));
8930
+ return match?.[1] ?? match?.[2] ?? match?.[3] ?? null;
8931
+ }
8412
8932
  function harnessedHookIdentity(raw) {
8413
8933
  for (const id of COMPILED_HOOK_IDENTITIES) {
8414
- if (new RegExp(`${LEFT}harnessed-${id}\\.mjs(?:["']|\\s|$)`).test(raw)) return id;
8415
- if (new RegExp(`${LEFT}harnessed(?:\\.exe)?["']?\\s+${id}(?:\\s|$)`).test(raw)) return id;
8934
+ const scriptPath = commandScriptPath2(raw, id);
8935
+ if (scriptPath && isTrustedScriptPath(scriptPath, id)) return id;
8936
+ const binaryPath = commandBinaryPath(raw, id);
8937
+ if (binaryPath === "harnessed") return id;
8938
+ if (binaryPath && trustedCompiledPaths2().has(pathKey(binaryPath))) return id;
8416
8939
  }
8417
8940
  return null;
8418
8941
  }
@@ -8487,13 +9010,14 @@ function harnessedStaleHookPaths(hooks, exists) {
8487
9010
  }
8488
9011
  return out;
8489
9012
  }
8490
- var ID_ALT, LEFT, ABSOLUTE_RE2;
9013
+ var ID_ALT, ABSOLUTE_RE2, CAPTURED_ASSETS_ROOT;
8491
9014
  var init_harnessedHookTeardown = __esm({
8492
9015
  "src/installers/lib/harnessedHookTeardown.ts"() {
9016
+ init_assetsRoot();
8493
9017
  init_hookEntry();
8494
9018
  ID_ALT = COMPILED_HOOK_IDENTITIES.join("|");
8495
- LEFT = `(?:^|[\\s"'=/\\\\])`;
8496
9019
  ABSOLUTE_RE2 = /^([A-Za-z]:[\\/]|[\\/])/;
9020
+ CAPTURED_ASSETS_ROOT = getAssetsRoot().replace(/\\/g, "/").replace(/\/$/, "");
8497
9021
  }
8498
9022
  });
8499
9023
 
@@ -9119,7 +9643,7 @@ async function withAppServer(deps, body) {
9119
9643
  const call = (method, params) => {
9120
9644
  if (closed) return Promise.reject(closed);
9121
9645
  const id = nextId++;
9122
- return new Promise((resolve37, reject) => {
9646
+ return new Promise((resolve39, reject) => {
9123
9647
  const timer = setTimeout(() => {
9124
9648
  pending.delete(id);
9125
9649
  reject(new RpcError("timeout", `${method} timed out after ${timeoutMs}ms`));
@@ -9127,7 +9651,7 @@ async function withAppServer(deps, body) {
9127
9651
  pending.set(id, {
9128
9652
  resolve: (v) => {
9129
9653
  clearTimeout(timer);
9130
- resolve37(v);
9654
+ resolve39(v);
9131
9655
  },
9132
9656
  reject: (e) => {
9133
9657
  clearTimeout(timer);
@@ -9797,7 +10321,7 @@ function normalizeString(s, roots) {
9797
10321
  out = out.split(root).join("<TMP>");
9798
10322
  out = out.split(fwd).join("<TMP>");
9799
10323
  }
9800
- return out.replace(/\\/g, "/");
10324
+ return out.replace(/\\/g, "/").replace(/\/(checkpoints|archive)\/[0-9a-f]{16}(?=\/)/g, "/$1/<OWNER>");
9801
10325
  }
9802
10326
  function normalizeGolden(value, tmpRoots) {
9803
10327
  if (typeof value === "string") return normalizeString(value, tmpRoots);
@@ -10593,7 +11117,7 @@ function realSpawn(req) {
10593
11117
  };
10594
11118
  }
10595
11119
  function runOnce(req, spawnFn, timeoutMs, onThreadId) {
10596
- return new Promise((resolve37, reject) => {
11120
+ return new Promise((resolve39, reject) => {
10597
11121
  const events = [];
10598
11122
  let garbageLines = 0;
10599
11123
  let stderr = "";
@@ -10614,9 +11138,9 @@ function runOnce(req, spawnFn, timeoutMs, onThreadId) {
10614
11138
  if (settled || !exited || openStreams > 0) return;
10615
11139
  settled = true;
10616
11140
  clearTimeout(timer);
10617
- resolve37({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
11141
+ resolve39({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
10618
11142
  };
10619
- const fail = (err2) => {
11143
+ const fail2 = (err2) => {
10620
11144
  if (settled) return;
10621
11145
  settled = true;
10622
11146
  clearTimeout(timer);
@@ -10661,7 +11185,7 @@ function runOnce(req, spawnFn, timeoutMs, onThreadId) {
10661
11185
  });
10662
11186
  proc.on(
10663
11187
  "error",
10664
- (e) => fail(new SpawnFailureError("SpawnExitNonZero", `spawn error: ${e.message}`))
11188
+ (e) => fail2(new SpawnFailureError("SpawnExitNonZero", `spawn error: ${e.message}`))
10665
11189
  );
10666
11190
  proc.on("exit", (code2, signal) => {
10667
11191
  exited = { code: code2, signal };
@@ -10669,7 +11193,7 @@ function runOnce(req, spawnFn, timeoutMs, onThreadId) {
10669
11193
  });
10670
11194
  if (timeoutMs > 0) {
10671
11195
  timer = setTimeout(
10672
- () => fail(
11196
+ () => fail2(
10673
11197
  new SpawnFailureError(
10674
11198
  "SpawnTimeout",
10675
11199
  `codex exec exceeded its ${timeoutMs}ms wall-clock timeout (HARNESSED_SPAWN_TIMEOUT_MS)`
@@ -11384,8 +11908,7 @@ async function runMasterOrchestrator(masterName, context, packageRoot, spawnDriv
11384
11908
  throw new Error(`Master workflow ${masterName} missing delegates_to`);
11385
11909
  }
11386
11910
  let effectiveOpts = opts;
11387
- const preflightActive = masterName === "auto" && (opts.assessComplexity !== void 0 || opts.prompter !== void 0 || opts.promptUserUnderstanding !== void 0);
11388
- if (preflightActive) {
11911
+ if (masterName === "auto") {
11389
11912
  const pre = await runAutoPreFlight(context, opts);
11390
11913
  if (!pre.proceed) {
11391
11914
  console.log(`[${masterName} master] Aborted by user (complexity gate decline).`);
@@ -11614,10 +12137,17 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
11614
12137
  const ownsRecord = opts.subOf === void 0;
11615
12138
  if (isMaster) {
11616
12139
  if (ownsRecord) await activatePhase(workflowName);
11617
- const r = await runMasterOrchestrator(workflowName, gateContext, packageRoot);
12140
+ const r = await runMasterOrchestrator(
12141
+ workflowName,
12142
+ gateContext,
12143
+ packageRoot,
12144
+ void 0,
12145
+ opts.masterOpts
12146
+ );
11618
12147
  if (ownsRecord) {
11619
12148
  await completePhase({
11620
12149
  phaseId: workflowName,
12150
+ status: "complete",
11621
12151
  lastTask: `master ${workflowName} complete: ${r.fired.length} sub(s) fired`
11622
12152
  });
11623
12153
  }
@@ -11687,6 +12217,7 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
11687
12217
  skippedPhases.push(ph.id);
11688
12218
  await completePhase({
11689
12219
  phaseId: ph.id,
12220
+ status: "complete",
11690
12221
  lastTask: `phase ${ph.id} skipped: gate ${ph.gate} evaluated false`,
11691
12222
  transitionWorkflowComplete
11692
12223
  });
@@ -11707,9 +12238,23 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
11707
12238
  if (r.failure) {
11708
12239
  try {
11709
12240
  const { mutateSubProgress: mutateSubProgress2 } = await Promise.resolve().then(() => (init_state(), state_exports));
11710
- const { annotateSpawnFailure: annotateSpawnFailure2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
12241
+ const { markSub: markSub2 } = await Promise.resolve().then(() => (init_ledger(), ledger_exports));
11711
12242
  const failure = r.failure;
11712
- await mutateSubProgress2((entries) => annotateSpawnFailure2(entries, workflowName, failure));
12243
+ await mutateSubProgress2((entries) => {
12244
+ if (!entries.some((e) => e.sub === workflowName)) {
12245
+ return [
12246
+ ...entries,
12247
+ {
12248
+ sub: workflowName,
12249
+ status: "failed",
12250
+ gate_fired: true,
12251
+ fail_count: 1,
12252
+ spawn_failure: failure
12253
+ }
12254
+ ];
12255
+ }
12256
+ return markSub2(entries, workflowName, "failed", { spawn_failure: failure });
12257
+ });
11713
12258
  } catch (err2) {
11714
12259
  console.warn(
11715
12260
  `\u26A0\uFE0F could not record spawn failure '${r.failure}' for ${workflowName} on the ledger (${err2.message}); the terminal checkpoint below is unaffected.`
@@ -11718,6 +12263,7 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
11718
12263
  }
11719
12264
  await completePhase({
11720
12265
  phaseId: ph.id,
12266
+ status: "complete",
11721
12267
  lastTask: `FAILED: phase ${ph.id}: ${r.output}`,
11722
12268
  transitionWorkflowComplete: false
11723
12269
  });
@@ -11731,6 +12277,7 @@ async function runWorkflow(yamlPath, vars, opts = {}) {
11731
12277
  }
11732
12278
  await completePhase({
11733
12279
  phaseId: ph.id,
12280
+ status: "complete",
11734
12281
  lastTask: `phase ${ph.id} complete: ${r.output}`,
11735
12282
  transitionWorkflowComplete
11736
12283
  });
@@ -12339,6 +12886,8 @@ function buildDefaultGateContext(task, stage) {
12339
12886
  // nulls with hints so the model supplies the real answer.
12340
12887
  has_ai_phase: false,
12341
12888
  requires_coverage_audit: false,
12889
+ requires_spec: false,
12890
+ builds_ai_system: false,
12342
12891
  requires_creative_polish: false,
12343
12892
  // T2.1 OQ2(c) — withdrawn: gated stage-routing.plan-architecture-delegate,
12344
12893
  // which meant /plan always spawned the eng-review architecture sub.
@@ -13363,6 +13912,8 @@ var init_facts = __esm({
13363
13912
  "phase.has_auth_or_secrets": "true if auth, credentials, tokens or secret handling changed (opens the security lane).",
13364
13913
  "phase.has_ai_phase": "true if this phase ships LLM/AI behaviour needing an eval-coverage audit.",
13365
13914
  "phase.requires_coverage_audit": "true if the phase needs a requirements-coverage audit rather than ordinary verification.",
13915
+ "phase.requires_spec": "true if execution needs a locked SDD specification before ordinary phase planning.",
13916
+ "phase.builds_ai_system": "true if the phase builds an AI system that needs an AI-SPEC.md design contract.",
13366
13917
  // subtask tier
13367
13918
  "subtask.type": "Subtask kind: 'crud' | 'core_logic' | 'algorithm' | 'ui_polish' | 'docs_only' | 'single_command_query' | 'standard_lib_call'. The first, last and 'ui_polish'/'docs_only' are what legitimately skip brainstorming / TDD.",
13368
13919
  "subtask.lines": "Rough size of the change in lines (derived from git when a diff exists; estimate it if nothing is written yet). <20 is the trivial-change skip.",
@@ -13761,15 +14312,6 @@ var init_state2 = __esm({
13761
14312
  DEFAULT_STATE = { version: "1", installed: {} };
13762
14313
  }
13763
14314
  });
13764
-
13765
- // src/installers/codexHookAdd.ts
13766
- var codexHookAdd_exports = {};
13767
- __export(codexHookAdd_exports, {
13768
- codexHookPaths: () => codexHookPaths,
13769
- installCodexHook: () => installCodexHook,
13770
- removeCodexHook: () => removeCodexHook,
13771
- resolveCodexHome: () => resolveCodexHome
13772
- });
13773
14315
  function resolveCodexHome(hostContext) {
13774
14316
  if (hostContext) return hostContext.nativeHome;
13775
14317
  const env = process.env.CODEX_HOME?.trim();
@@ -14382,13 +14924,146 @@ var init_preflight = __esm({
14382
14924
  GIT_REF_SHAPE = /^([a-f0-9]{7,40}|v?\d+\.\d+\.\d+([.-][\w.-]+)?)$/;
14383
14925
  }
14384
14926
  });
14385
- var installCcHookAdd;
14386
- var init_ccHookAdd2 = __esm({
14387
- "src/installers/ccHookAdd.ts"() {
14388
- init_security();
14389
- init_assetsRoot();
14390
- init_platform();
14391
- init_codexHookAdd();
14927
+ async function prepareHookSettings(ctx, settingsPath) {
14928
+ const install = ctx.manifest.spec.install;
14929
+ if (install.method !== "cc-hook-add") {
14930
+ return {
14931
+ ok: false,
14932
+ result: {
14933
+ ok: false,
14934
+ phase: "preflight",
14935
+ error: err(
14936
+ ctx,
14937
+ "/spec/install/method",
14938
+ `dispatch bug: ${install.method}`,
14939
+ "dispatch-mismatch"
14940
+ )
14941
+ }
14942
+ };
14943
+ }
14944
+ let existing;
14945
+ try {
14946
+ existing = await readFile(settingsPath, "utf8");
14947
+ } catch (error) {
14948
+ if (error.code !== "ENOENT") {
14949
+ return {
14950
+ ok: false,
14951
+ result: {
14952
+ ok: false,
14953
+ phase: "preflight",
14954
+ error: err(
14955
+ ctx,
14956
+ "/",
14957
+ `read settings.json failed: ${error.message}`,
14958
+ "settings-json-malformed"
14959
+ )
14960
+ }
14961
+ };
14962
+ }
14963
+ existing = null;
14964
+ }
14965
+ let settings;
14966
+ try {
14967
+ settings = JSON.parse(existing ?? "{}");
14968
+ } catch (error) {
14969
+ return {
14970
+ ok: false,
14971
+ result: {
14972
+ ok: false,
14973
+ phase: "preflight",
14974
+ error: err(
14975
+ ctx,
14976
+ "/",
14977
+ `malformed settings.json: ${error.message.slice(0, 200)}`,
14978
+ "settings-json-malformed"
14979
+ )
14980
+ }
14981
+ };
14982
+ }
14983
+ if (settings === null || typeof settings !== "object" || Array.isArray(settings)) {
14984
+ return {
14985
+ ok: false,
14986
+ result: {
14987
+ ok: false,
14988
+ phase: "preflight",
14989
+ error: err(
14990
+ ctx,
14991
+ "/",
14992
+ `malformed settings.json: top-level value must be a JSON object, got ${settings === null ? "null" : Array.isArray(settings) ? "array" : typeof settings}`,
14993
+ "settings-json-malformed"
14994
+ )
14995
+ }
14996
+ };
14997
+ }
14998
+ if (settings.hooks !== void 0 && (settings.hooks === null || typeof settings.hooks !== "object" || Array.isArray(settings.hooks))) {
14999
+ return {
15000
+ ok: false,
15001
+ result: {
15002
+ ok: false,
15003
+ phase: "preflight",
15004
+ error: err(
15005
+ ctx,
15006
+ "/",
15007
+ "malformed settings.json: hooks must be a JSON object",
15008
+ "settings-json-malformed"
15009
+ )
15010
+ }
15011
+ };
15012
+ }
15013
+ settings.hooks = settings.hooks ?? {};
15014
+ const cmdDeps = {
15015
+ assetsRoot: getAssetsRoot,
15016
+ exists: existsSync,
15017
+ compiledExecPath: () => isCompiledRuntime() ? process.execPath : null
15018
+ };
15019
+ const resolvedCmd = resolveHookCommand(install.hook_command, cmdDeps);
15020
+ const marker = hookScriptMarker(install.hook_command);
15021
+ const arr = settings.hooks[install.hook_event] ?? [];
15022
+ if (!Array.isArray(arr)) {
15023
+ return {
15024
+ ok: false,
15025
+ result: {
15026
+ ok: false,
15027
+ phase: "preflight",
15028
+ error: err(
15029
+ ctx,
15030
+ "/",
15031
+ `malformed settings.json: hooks.${install.hook_event} must be an array`,
15032
+ "settings-json-malformed"
15033
+ )
15034
+ }
15035
+ };
15036
+ }
15037
+ const ours = arr.filter(
15038
+ (entry) => entryMatchesRegistration(entry, install.hook_command, resolvedCmd, marker)
15039
+ );
15040
+ const desired = ours.length === 1 && isDesiredHookEntry(ours[0] ?? {}, install.hook_matcher, resolvedCmd);
15041
+ const others = arr.filter(
15042
+ (entry) => !entryMatchesRegistration(entry, install.hook_command, resolvedCmd, marker)
15043
+ );
15044
+ settings.hooks[install.hook_event] = [
15045
+ ...others,
15046
+ desiredHookEntry(install.hook_matcher, resolvedCmd)
15047
+ ];
15048
+ const newText = `${JSON.stringify(settings, null, 2)}
15049
+ `;
15050
+ return {
15051
+ ok: true,
15052
+ existing,
15053
+ resolvedCmd,
15054
+ desired,
15055
+ plan: { files: [{ target: settingsPath, scope: "HOME", oldText: existing ?? "", newText }] }
15056
+ };
15057
+ }
15058
+ var installCcHookAdd;
15059
+ var init_ccHookAdd2 = __esm({
15060
+ "src/installers/ccHookAdd.ts"() {
15061
+ init_settingsTransactionLock();
15062
+ init_settingsWriter();
15063
+ init_security();
15064
+ init_assetsRoot();
15065
+ init_platform();
15066
+ init_codexHookAdd();
14392
15067
  init_backup();
14393
15068
  init_confirm();
14394
15069
  init_diff();
@@ -14420,42 +15095,7 @@ var init_ccHookAdd2 = __esm({
14420
15095
  if ((ctx.hostContext?.hostId ?? detectPlatform().id) === "codex") return installCodexHook(ctx);
14421
15096
  const settingsPath = ctx.hostContext ? join(ctx.hostContext.nativeHome, "settings.json") : getSettingsPath();
14422
15097
  if (settingsPath === null) return { aborted: true, reason: "platform-mismatch" };
14423
- let existing;
14424
- try {
14425
- existing = await readFile(settingsPath, "utf8");
14426
- } catch {
14427
- existing = null;
14428
- }
14429
- let settings;
14430
- try {
14431
- settings = JSON.parse(existing ?? "{}");
14432
- } catch (e) {
14433
- return {
14434
- ok: false,
14435
- phase: "preflight",
14436
- error: err(
14437
- ctx,
14438
- "/",
14439
- `malformed settings.json: ${e.message.slice(0, 200)}`,
14440
- "settings-json-malformed"
14441
- )
14442
- };
14443
- }
14444
- if (settings === null || typeof settings !== "object" || Array.isArray(settings)) {
14445
- return {
14446
- ok: false,
14447
- phase: "preflight",
14448
- error: err(
14449
- ctx,
14450
- "/",
14451
- `malformed settings.json: top-level value must be a JSON object, got ${settings === null ? "null" : Array.isArray(settings) ? "array" : typeof settings}`,
14452
- "settings-json-malformed"
14453
- )
14454
- };
14455
- }
14456
- settings.hooks = settings.hooks ?? {};
14457
15098
  const ev = install.hook_event;
14458
- const matcher = install.hook_matcher;
14459
15099
  const cmd = install.hook_command;
14460
15100
  const cmdViolation = checkCmdString(cmd);
14461
15101
  if (cmdViolation) {
@@ -14470,73 +15110,111 @@ var init_ccHookAdd2 = __esm({
14470
15110
  )
14471
15111
  };
14472
15112
  }
14473
- const cmdDeps = {
14474
- assetsRoot: getAssetsRoot,
14475
- exists: existsSync,
14476
- compiledExecPath: () => isCompiledRuntime() ? process.execPath : null
14477
- };
14478
- const resolvedCmd = resolveHookCommand(cmd, cmdDeps);
14479
- const marker = hookScriptMarker(cmd);
14480
- const arr = settings.hooks[ev] ?? [];
14481
- const ours = arr.filter((e) => entryMatchesRegistration(e, cmd, resolvedCmd, marker));
14482
- if (ours.length === 1 && isDesiredHookEntry(ours[0] ?? {}, matcher, resolvedCmd)) {
14483
- if (ctx.opts.apply && !ctx.opts.dryRun) {
14484
- await recordObservedInstall(
14485
- ctx.cwd,
14486
- ctx.manifest.metadata.name,
14487
- "",
14488
- "",
14489
- ...ctx.hostContext ? [ctx.hostContext] : []
14490
- );
15113
+ const preview = await prepareHookSettings(ctx, settingsPath);
15114
+ if (!preview.ok) return preview.result;
15115
+ if (preview.desired) {
15116
+ let result;
15117
+ try {
15118
+ result = await withSettingsTransactionLock(ctx.hostContext, async () => {
15119
+ const current = await prepareHookSettings(ctx, settingsPath);
15120
+ if (!current.ok) return current.result;
15121
+ return current.desired ? { ok: true, alreadyInstalled: true, backupId: "idempotent-skip" } : null;
15122
+ });
15123
+ } catch (error) {
15124
+ return {
15125
+ ok: false,
15126
+ phase: "preflight",
15127
+ error: err(
15128
+ ctx,
15129
+ "/",
15130
+ `settings transaction lock failed: ${error.message}`,
15131
+ "settings-write-failed"
15132
+ )
15133
+ };
15134
+ }
15135
+ if (result !== null) {
15136
+ if ("ok" in result && result.ok && ctx.opts.apply && !ctx.opts.dryRun) {
15137
+ await recordObservedInstall(
15138
+ ctx.cwd,
15139
+ ctx.manifest.metadata.name,
15140
+ "",
15141
+ "",
15142
+ ...ctx.hostContext ? [ctx.hostContext] : []
15143
+ );
15144
+ }
15145
+ return result;
14491
15146
  }
14492
- return { ok: true, alreadyInstalled: true, backupId: "idempotent-skip" };
14493
15147
  }
14494
- const others = arr.filter((e) => !entryMatchesRegistration(e, cmd, resolvedCmd, marker));
14495
- settings.hooks[ev] = [...others, desiredHookEntry(matcher, resolvedCmd)];
14496
- const newText = `${JSON.stringify(settings, null, 2)}
14497
- `;
14498
- const plan = {
14499
- files: [{ target: settingsPath, scope: "HOME", oldText: existing ?? "", newText }]
14500
- };
14501
- if (!ctx.opts.quiet) process.stdout.write(renderDiff(plan, ctx));
15148
+ if (!ctx.opts.quiet) process.stdout.write(renderDiff(preview.plan, ctx));
14502
15149
  const conf = await confirmAt("L3", { ...ctx});
14503
15150
  if (!conf.proceed) {
14504
15151
  const reason = conf.reason === "flag-missing" ? "level-flag-missing" : "user-cancel";
14505
15152
  return { aborted: true, reason };
14506
15153
  }
14507
15154
  if (ctx.opts.dryRun) return { aborted: true, reason: "user-cancel" };
14508
- const bk = await backup(plan, ctx);
14509
- if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
14510
- await writeFile(settingsPath, newText);
14511
- let verify;
15155
+ let transaction;
14512
15156
  try {
14513
- verify = JSON.parse(await readFile(settingsPath, "utf8"));
14514
- } catch (e) {
14515
- return {
14516
- ok: false,
14517
- phase: "verify",
14518
- backupId: bk.backupId,
14519
- error: err(
14520
- ctx,
14521
- "/spec/install/hook_command",
14522
- `verify re-read fail: ${e.message.slice(0, 200)}`,
14523
- "verify-failed"
14524
- )
14525
- };
14526
- }
14527
- if (!verify.hooks?.[ev]?.some((e) => isDesiredHookEntry(e, matcher, resolvedCmd))) {
15157
+ transaction = await withSettingsTransactionLock(ctx.hostContext, async () => {
15158
+ const current = await prepareHookSettings(ctx, settingsPath);
15159
+ if (!current.ok) return current.result;
15160
+ if (current.desired) return { ok: true, alreadyInstalled: true, backupId: "idempotent-skip" };
15161
+ const bk = await backup(current.plan, ctx);
15162
+ if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
15163
+ const writeError = await atomicWrite(settingsPath, current.plan.files[0]?.newText ?? "");
15164
+ if (writeError) {
15165
+ return {
15166
+ ok: false,
15167
+ phase: "spawn",
15168
+ backupId: bk.backupId,
15169
+ error: err(ctx, "/", writeError, "settings-write-failed")
15170
+ };
15171
+ }
15172
+ let verify;
15173
+ try {
15174
+ verify = JSON.parse(await readFile(settingsPath, "utf8"));
15175
+ } catch (error) {
15176
+ return {
15177
+ ok: false,
15178
+ phase: "verify",
15179
+ backupId: bk.backupId,
15180
+ error: err(
15181
+ ctx,
15182
+ "/spec/install/hook_command",
15183
+ `verify re-read fail: ${error.message.slice(0, 200)}`,
15184
+ "verify-failed"
15185
+ )
15186
+ };
15187
+ }
15188
+ if (!verify.hooks?.[ev]?.some(
15189
+ (entry) => isDesiredHookEntry(entry, install.hook_matcher, current.resolvedCmd)
15190
+ )) {
15191
+ return {
15192
+ ok: false,
15193
+ phase: "verify",
15194
+ backupId: bk.backupId,
15195
+ error: err(
15196
+ ctx,
15197
+ "/spec/install/hook_command",
15198
+ `hook '${current.resolvedCmd.slice(0, 80)}' missing in hooks.${ev}[] after write`,
15199
+ "verify-failed"
15200
+ )
15201
+ };
15202
+ }
15203
+ return { ok: true, backupId: bk.backupId, appliedFiles: [settingsPath] };
15204
+ });
15205
+ } catch (error) {
14528
15206
  return {
14529
15207
  ok: false,
14530
- phase: "verify",
14531
- backupId: bk.backupId,
15208
+ phase: "preflight",
14532
15209
  error: err(
14533
15210
  ctx,
14534
- "/spec/install/hook_command",
14535
- `hook '${resolvedCmd.slice(0, 80)}' missing in hooks.${ev}[] after write`,
14536
- "verify-failed"
15211
+ "/",
15212
+ `settings transaction lock failed: ${error.message}`,
15213
+ "settings-write-failed"
14537
15214
  )
14538
15215
  };
14539
15216
  }
15217
+ if (!("ok" in transaction) || !transaction.ok) return transaction;
14540
15218
  await updateInstalled(
14541
15219
  ctx.cwd,
14542
15220
  ctx.manifest.metadata.name,
@@ -14544,7 +15222,7 @@ var init_ccHookAdd2 = __esm({
14544
15222
  "",
14545
15223
  ...ctx.hostContext ? [ctx.hostContext] : []
14546
15224
  );
14547
- return { ok: true, backupId: bk.backupId, appliedFiles: [settingsPath] };
15225
+ return transaction;
14548
15226
  };
14549
15227
  }
14550
15228
  });
@@ -14832,10 +15510,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
14832
15510
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
14833
15511
  stderr += chunk;
14834
15512
  });
14835
- return await new Promise((resolve37) => {
15513
+ return await new Promise((resolve39) => {
14836
15514
  const timer = setTimeout(() => {
14837
15515
  killProcessTree(child);
14838
- resolve37({
15516
+ resolve39({
14839
15517
  ok: false,
14840
15518
  phase: "spawn",
14841
15519
  error: {
@@ -14856,7 +15534,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
14856
15534
  child.on("error", (err2) => {
14857
15535
  clearTimeout(timer);
14858
15536
  const bashMissing = triedBash && err2.code === "ENOENT";
14859
- resolve37({
15537
+ resolve39({
14860
15538
  ok: false,
14861
15539
  phase: "spawn",
14862
15540
  error: {
@@ -14871,7 +15549,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
14871
15549
  });
14872
15550
  child.on("close", (code2) => {
14873
15551
  clearTimeout(timer);
14874
- resolve37({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
15552
+ resolve39({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
14875
15553
  });
14876
15554
  });
14877
15555
  }
@@ -15109,6 +15787,7 @@ async function isAlreadyInstalled(ctx, opts = {}) {
15109
15787
  installCfg.hook_matcher,
15110
15788
  {
15111
15789
  assetsRoot: getAssetsRoot,
15790
+ compiledExecPath: () => isCompiledRuntime() ? process.execPath : null,
15112
15791
  exists: existsSync
15113
15792
  }
15114
15793
  );
@@ -15454,6 +16133,15 @@ async function snapshotSkillNames(skillsDir = getSkillsDir()) {
15454
16133
  return /* @__PURE__ */ new Set();
15455
16134
  }
15456
16135
  }
16136
+ function skillRootsForContext(ctx) {
16137
+ if (!ctx.hostContext) return [resolve(getSkillsDir())];
16138
+ return [
16139
+ .../* @__PURE__ */ new Set([
16140
+ resolve(ctx.hostContext.platform.skillsDir),
16141
+ resolve(join(ctx.hostContext.nativeHome, "skills"))
16142
+ ])
16143
+ ];
16144
+ }
15457
16145
  async function shippedWorkflowNames() {
15458
16146
  if (workflowNamesCache) return workflowNamesCache;
15459
16147
  try {
@@ -15572,7 +16260,7 @@ function touch(binary, lease, source, scratch, context) {
15572
16260
  if (context) env = withHostInstallEnv(env, context);
15573
16261
  env.GSTACK_LEASE_DIR = shellPath(scratch, context);
15574
16262
  env.GSTACK_LEASE_LOCK_TRIES = "1";
15575
- return new Promise((resolve37, reject) => {
16263
+ return new Promise((resolve39, reject) => {
15576
16264
  const child = execFile(
15577
16265
  binary,
15578
16266
  [
@@ -15601,7 +16289,7 @@ function touch(binary, lease, source, scratch, context) {
15601
16289
  `official lease touch exit ${error.code ?? "unknown"}${error.killed ? " (timeout or termination)" : ""}: ${stderr.trim() || error.message}`
15602
16290
  )
15603
16291
  );
15604
- else resolve37();
16292
+ else resolve39();
15605
16293
  }
15606
16294
  );
15607
16295
  child.stdin?.end();
@@ -16141,7 +16829,7 @@ var init_verifyInstalled = __esm({
16141
16829
  }
16142
16830
  });
16143
16831
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
16144
- return new Promise((resolve37) => {
16832
+ return new Promise((resolve39) => {
16145
16833
  const isWin = process.platform === "win32";
16146
16834
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
16147
16835
  let stdout2 = "";
@@ -16150,15 +16838,15 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
16150
16838
  });
16151
16839
  const timer = setTimeout(() => {
16152
16840
  killProcessTree(child);
16153
- resolve37({ sha: "", exit: -1 });
16841
+ resolve39({ sha: "", exit: -1 });
16154
16842
  }, timeoutMs);
16155
16843
  child.on("error", () => {
16156
16844
  clearTimeout(timer);
16157
- resolve37({ sha: "", exit: -1 });
16845
+ resolve39({ sha: "", exit: -1 });
16158
16846
  });
16159
16847
  child.on("close", (code2) => {
16160
16848
  clearTimeout(timer);
16161
- resolve37({ sha: stdout2.trim(), exit: code2 ?? -1 });
16849
+ resolve39({ sha: stdout2.trim(), exit: code2 ?? -1 });
16162
16850
  });
16163
16851
  });
16164
16852
  }
@@ -16454,7 +17142,9 @@ function isReviewedNeutralTeardown(manifest) {
16454
17142
  "playwright-cli": "npm uninstall -g @playwright/cli"
16455
17143
  };
16456
17144
  const spec = manifest.spec;
16457
- return Object.hasOwn(commands, manifest.metadata.name) && spec.type === "cli-npm" && spec.component_type === "cli-binary" && spec.install_type === "npm" && Value.Check(NpmCli, spec.install) && spec.uninstall?.cmd === commands[manifest.metadata.name] && (spec.uninstall.cleanup_paths === void 0 || Array.isArray(spec.uninstall.cleanup_paths) && spec.uninstall.cleanup_paths.length === 0);
17145
+ const emptyCleanup = spec.uninstall?.cleanup_paths === void 0 || Array.isArray(spec.uninstall.cleanup_paths) && spec.uninstall.cleanup_paths.length === 0;
17146
+ const reviewedGsdCodex = manifest.metadata.name === "gsd" && manifest.metadata.upstream.source === "@opengsd/gsd-core" && spec.type === "cli-npm" && spec.component_type === "command" && spec.install_type === "npm" && Value.Check(NpmCli, spec.install) && spec.install.cmd === "npx --yes @opengsd/gsd-core@latest --codex --global" && spec.uninstall?.cmd === "npx --yes @opengsd/gsd-core@latest --codex --global --uninstall" && emptyCleanup;
17147
+ return reviewedGsdCodex || Object.hasOwn(commands, manifest.metadata.name) && spec.type === "cli-npm" && spec.component_type === "cli-binary" && spec.install_type === "npm" && Value.Check(NpmCli, spec.install) && spec.uninstall?.cmd === commands[manifest.metadata.name] && emptyCleanup;
16458
17148
  }
16459
17149
  function resolveComponentPlan(manifest, context, operation) {
16460
17150
  const override = context.hostId === "codex" ? manifest.spec.harness_overrides?.codex : void 0;
@@ -16994,6 +17684,402 @@ ${newEntry}
16994
17684
  };
16995
17685
  }
16996
17686
  });
17687
+ function isDirectChild(root, target) {
17688
+ const rel = relative(root, target);
17689
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) && dirname(target) === root;
17690
+ }
17691
+ async function digestFile(path) {
17692
+ const hash = createHash("sha256");
17693
+ for await (const chunk of createReadStream(path)) hash.update(chunk);
17694
+ return hash.digest("hex");
17695
+ }
17696
+ async function inspectRoot(root) {
17697
+ const info = await lstat(root);
17698
+ if (info.isSymbolicLink() || !info.isDirectory()) {
17699
+ throw new Error(`refusing symbolic link, junction, or non-directory root: ${root}`);
17700
+ }
17701
+ return { canonicalRoot: await realpath(root) };
17702
+ }
17703
+ async function prepareOwnedPathRemoval(root, target) {
17704
+ const resolvedRoot = resolve(root);
17705
+ const resolvedTarget = resolve(target);
17706
+ if (!isDirectChild(resolvedRoot, resolvedTarget)) {
17707
+ throw new Error(`refusing path outside authorized direct-child root: ${target}`);
17708
+ }
17709
+ const [{ canonicalRoot }, targetInfo] = await Promise.all([
17710
+ inspectRoot(resolvedRoot),
17711
+ lstat(resolvedTarget)
17712
+ ]);
17713
+ if (targetInfo.isSymbolicLink()) {
17714
+ throw new Error(`refusing symbolic link or junction path: ${target}`);
17715
+ }
17716
+ const canonicalTarget = await realpath(resolvedTarget);
17717
+ if (dirname(canonicalTarget) !== canonicalRoot) {
17718
+ throw new Error(`refusing canonical path outside authorized root: ${target}`);
17719
+ }
17720
+ const isDirectory = targetInfo.isDirectory();
17721
+ return {
17722
+ root: resolvedRoot,
17723
+ target: resolvedTarget,
17724
+ canonicalRoot,
17725
+ canonicalTarget,
17726
+ isDirectory,
17727
+ device: targetInfo.dev,
17728
+ inode: targetInfo.ino,
17729
+ contentDigest: isDirectory ? null : await digestFile(resolvedTarget)
17730
+ };
17731
+ }
17732
+ async function assertOwnedPathUnchanged(snapshot) {
17733
+ const current = await prepareOwnedPathRemoval(snapshot.root, snapshot.target);
17734
+ if (current.canonicalRoot !== snapshot.canonicalRoot || current.canonicalTarget !== snapshot.canonicalTarget || current.device !== snapshot.device || current.inode !== snapshot.inode || current.isDirectory !== snapshot.isDirectory || current.contentDigest !== snapshot.contentDigest) {
17735
+ throw new Error(`refusing path changed after preflight: ${snapshot.target}`);
17736
+ }
17737
+ }
17738
+ async function restoreQuarantine(quarantinePath, target) {
17739
+ try {
17740
+ await lstat(target);
17741
+ return `original path is occupied: ${target}`;
17742
+ } catch (error) {
17743
+ if (error.code !== "ENOENT") return error.message;
17744
+ }
17745
+ try {
17746
+ await rename(quarantinePath, target);
17747
+ return null;
17748
+ } catch (error) {
17749
+ return error.message;
17750
+ }
17751
+ }
17752
+ async function verifyQuarantine(snapshot, quarantinePath, verify) {
17753
+ const [{ canonicalRoot }, info] = await Promise.all([
17754
+ inspectRoot(snapshot.root),
17755
+ lstat(quarantinePath)
17756
+ ]);
17757
+ if (canonicalRoot !== snapshot.canonicalRoot) {
17758
+ throw new Error(`refusing root changed after preflight: ${snapshot.root}`);
17759
+ }
17760
+ if (info.isSymbolicLink() || !info.isDirectory()) {
17761
+ throw new Error(
17762
+ `refusing quarantined symbolic link, junction, or non-directory: ${snapshot.target}`
17763
+ );
17764
+ }
17765
+ if (info.dev !== snapshot.device || info.ino !== snapshot.inode) {
17766
+ throw new Error(
17767
+ `refusing quarantined path identity changed after preflight: ${snapshot.target}`
17768
+ );
17769
+ }
17770
+ const canonicalQuarantine = await realpath(quarantinePath);
17771
+ if (dirname(canonicalQuarantine) !== canonicalRoot) {
17772
+ throw new Error(`refusing quarantined path outside authorized root: ${snapshot.target}`);
17773
+ }
17774
+ await verify?.(quarantinePath);
17775
+ }
17776
+ async function verifyQuarantinedFile(snapshot, quarantinePath) {
17777
+ const [{ canonicalRoot }, info] = await Promise.all([
17778
+ inspectRoot(snapshot.root),
17779
+ lstat(quarantinePath)
17780
+ ]);
17781
+ if (canonicalRoot !== snapshot.canonicalRoot) {
17782
+ throw new Error(`refusing root changed after preflight: ${snapshot.root}`);
17783
+ }
17784
+ if (info.isSymbolicLink() || info.isDirectory()) {
17785
+ throw new Error(
17786
+ `refusing quarantined symbolic link, junction, or directory: ${snapshot.target}`
17787
+ );
17788
+ }
17789
+ if (info.dev !== snapshot.device || info.ino !== snapshot.inode) {
17790
+ throw new Error(
17791
+ `refusing quarantined path identity changed after preflight: ${snapshot.target}`
17792
+ );
17793
+ }
17794
+ if (await digestFile(quarantinePath) !== snapshot.contentDigest) {
17795
+ throw new Error(`refusing quarantined path content changed after preflight: ${snapshot.target}`);
17796
+ }
17797
+ const canonicalQuarantine = await realpath(quarantinePath);
17798
+ if (dirname(canonicalQuarantine) !== canonicalRoot) {
17799
+ throw new Error(`refusing quarantined path outside authorized root: ${snapshot.target}`);
17800
+ }
17801
+ }
17802
+ async function removeOwnedFileViaQuarantine(snapshot) {
17803
+ if (snapshot.isDirectory) {
17804
+ throw new Error(`refusing non-recursive removal of directory: ${snapshot.target}`);
17805
+ }
17806
+ const currentRoot = await inspectRoot(snapshot.root);
17807
+ if (currentRoot.canonicalRoot !== snapshot.canonicalRoot) {
17808
+ throw new Error(`refusing root changed after preflight: ${snapshot.root}`);
17809
+ }
17810
+ const quarantinePath = join(
17811
+ snapshot.root,
17812
+ `.harnessed-quarantine-${process.pid}-${randomBytes(16).toString("hex")}`
17813
+ );
17814
+ await rename(snapshot.target, quarantinePath);
17815
+ try {
17816
+ await verifyQuarantinedFile(snapshot, quarantinePath);
17817
+ } catch (error) {
17818
+ const restoreError = await restoreQuarantine(quarantinePath, snapshot.target);
17819
+ const detail = error instanceof Error ? error.message : String(error);
17820
+ throw new Error(
17821
+ restoreError === null ? detail : `${detail}; quarantine restore failed: ${restoreError}; retained at ${quarantinePath}`
17822
+ );
17823
+ }
17824
+ await rm(quarantinePath, { force: true });
17825
+ }
17826
+ async function removeOwnedDirectoryViaQuarantine(snapshot, options = {}) {
17827
+ if (!snapshot.isDirectory) {
17828
+ throw new Error(`refusing recursive removal of non-directory: ${snapshot.target}`);
17829
+ }
17830
+ const currentRoot = await inspectRoot(snapshot.root);
17831
+ if (currentRoot.canonicalRoot !== snapshot.canonicalRoot) {
17832
+ throw new Error(`refusing root changed after preflight: ${snapshot.root}`);
17833
+ }
17834
+ const quarantinePath = join(
17835
+ snapshot.root,
17836
+ `.harnessed-quarantine-${process.pid}-${randomBytes(16).toString("hex")}`
17837
+ );
17838
+ await rename(snapshot.target, quarantinePath);
17839
+ try {
17840
+ await verifyQuarantine(snapshot, quarantinePath, options.verify);
17841
+ } catch (error) {
17842
+ const restoreError = await restoreQuarantine(quarantinePath, snapshot.target);
17843
+ const detail = error instanceof Error ? error.message : String(error);
17844
+ throw new Error(
17845
+ restoreError === null ? detail : `${detail}; quarantine restore failed: ${restoreError}; retained at ${quarantinePath}`
17846
+ );
17847
+ }
17848
+ await rm(quarantinePath, { recursive: true, force: true, maxRetries: 3 });
17849
+ }
17850
+ var init_quarantineDelete = __esm({
17851
+ "src/lib/quarantineDelete.ts"() {
17852
+ }
17853
+ });
17854
+ function receiptContext(ctx) {
17855
+ const platform = ctx.hostContext?.platform ?? detectPlatform();
17856
+ return {
17857
+ component: ctx.manifest.metadata.name,
17858
+ hostId: ctx.hostContext?.hostId ?? platform.id,
17859
+ nativeRoot: resolve(ctx.hostContext?.nativeHome ?? platform.homeDir),
17860
+ stateRoot: resolve(platform.stateRoot)
17861
+ };
17862
+ }
17863
+ function fail(reason) {
17864
+ return new Error(`skill ownership receipt ${reason}; run repair or reinstall before uninstalling`);
17865
+ }
17866
+ function canonicalJson(value) {
17867
+ if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
17868
+ if (value && typeof value === "object") {
17869
+ return `{${Object.entries(value).sort(([left], [right]) => left.localeCompare(right)).map(([key, child]) => `${JSON.stringify(key)}:${canonicalJson(child)}`).join(",")}}`;
17870
+ }
17871
+ return JSON.stringify(value);
17872
+ }
17873
+ function ownershipFingerprint(ctx) {
17874
+ const value = {
17875
+ metadata: ctx.manifest.metadata,
17876
+ install: ctx.manifest.spec.install
17877
+ };
17878
+ return createHash("sha256").update(canonicalJson(value)).digest("hex");
17879
+ }
17880
+ function pathInsideRoot(root, path) {
17881
+ const rel = relative(root, path);
17882
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
17883
+ }
17884
+ function authorizedSkillNames(ctx) {
17885
+ const install = ctx.manifest.spec.install;
17886
+ const declared = install.installs_skills;
17887
+ const names = Array.isArray(declared) ? declared.filter((name) => typeof name === "string" && name.length > 0) : [];
17888
+ if (install.method === "npx-skill-installer") {
17889
+ const selected = install.cmd.match(/(?:^|\s)--skill(?:=|\s+)([a-zA-Z0-9][a-zA-Z0-9._-]*)/);
17890
+ if (selected?.[1]) names.push(selected[1]);
17891
+ }
17892
+ if (names.some((name) => !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name))) {
17893
+ throw fail("has an invalid declared skill name");
17894
+ }
17895
+ return [...new Set(names)].sort();
17896
+ }
17897
+ async function declaredSkillPaths(ctx, skillRoots) {
17898
+ const roots = normalizeRoots(skillRoots);
17899
+ const paths = [];
17900
+ for (const root of roots) {
17901
+ for (const name of authorizedSkillNames(ctx)) {
17902
+ const path = join(root, name);
17903
+ try {
17904
+ await lstat(path);
17905
+ paths.push(path);
17906
+ } catch (error) {
17907
+ if (error.code !== "ENOENT") throw error;
17908
+ }
17909
+ }
17910
+ }
17911
+ return paths.sort();
17912
+ }
17913
+ async function hashSkillTree(path) {
17914
+ const hash = createHash("sha256");
17915
+ const visit = async (dir, prefix) => {
17916
+ const entries = await readdir(dir, { withFileTypes: true });
17917
+ entries.sort((left, right) => left.name.localeCompare(right.name));
17918
+ for (const entry of entries) {
17919
+ const rel = prefix ? `${prefix}/${entry.name}` : entry.name;
17920
+ const target = join(dir, entry.name);
17921
+ if (entry.isSymbolicLink()) throw fail(`target contains a symbolic link: ${rel}`);
17922
+ if (entry.isDirectory()) {
17923
+ hash.update(`d\0${rel}\0`);
17924
+ await visit(target, rel);
17925
+ } else if (entry.isFile()) {
17926
+ hash.update(`f\0${rel}\0`);
17927
+ hash.update(await readFile(target));
17928
+ hash.update("\0");
17929
+ } else {
17930
+ throw fail(`target contains an unsupported filesystem entry: ${rel}`);
17931
+ }
17932
+ }
17933
+ };
17934
+ await visit(path, "");
17935
+ return hash.digest("hex");
17936
+ }
17937
+ function normalizeRoots(skillRoots) {
17938
+ if (skillRoots.length === 0 || skillRoots.some((root) => !isAbsolute(root))) {
17939
+ throw fail("is corrupt");
17940
+ }
17941
+ return [...new Set(skillRoots.map((root) => resolve(root)))];
17942
+ }
17943
+ function validateCreatedPaths(skillRoots, createdPaths) {
17944
+ const roots = normalizeRoots(skillRoots);
17945
+ if (createdPaths.some((path) => !isAbsolute(path))) {
17946
+ throw fail("contains a non-absolute path");
17947
+ }
17948
+ return [...new Set(createdPaths.map((path) => resolve(path)))].map((path) => {
17949
+ const root = roots.find((candidate) => {
17950
+ return pathInsideRoot(candidate, path);
17951
+ });
17952
+ if (!root) throw new Error(`skill ownership path is outside an allowed skill root: ${path}`);
17953
+ return path;
17954
+ });
17955
+ }
17956
+ function isSkillOwnershipManaged(ctx) {
17957
+ const install = ctx.spec.install;
17958
+ const installsSkills = install.installs_skills;
17959
+ return install.method === "npx-skill-installer" || Array.isArray(installsSkills) && installsSkills.length > 0;
17960
+ }
17961
+ function skillOwnershipReceiptPath(ctx) {
17962
+ const binding = receiptContext(ctx);
17963
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(binding.component)) {
17964
+ throw fail("has an invalid component binding");
17965
+ }
17966
+ return join(binding.stateRoot, "skill-ownership", `${binding.component}.json`);
17967
+ }
17968
+ async function writeSkillOwnershipReceipt(ctx, skillRoots, createdPaths) {
17969
+ const binding = receiptContext(ctx);
17970
+ const roots = normalizeRoots(skillRoots).sort();
17971
+ const paths = validateCreatedPaths(roots, createdPaths).sort();
17972
+ const contentSha256 = {};
17973
+ for (const path2 of paths) {
17974
+ const root = roots.find((candidate) => pathInsideRoot(candidate, path2));
17975
+ if (!root) throw fail(`contains a path outside an allowed skill root: ${path2}`);
17976
+ const info = await lstat(path2);
17977
+ if (info.isSymbolicLink()) throw fail(`target is a symbolic link: ${path2}`);
17978
+ if (!info.isDirectory()) throw fail(`target is not a real directory: ${path2}`);
17979
+ const [physicalRoot, physicalPath] = await Promise.all([realpath(root), realpath(path2)]);
17980
+ if (!pathInsideRoot(physicalRoot, physicalPath))
17981
+ throw fail(`target escapes its captured skill root: ${path2}`);
17982
+ contentSha256[path2] = await hashSkillTree(path2);
17983
+ }
17984
+ const receipt = {
17985
+ version: 2,
17986
+ component: binding.component,
17987
+ hostId: binding.hostId,
17988
+ nativeRoot: binding.nativeRoot,
17989
+ manifestSha256: ownershipFingerprint(ctx),
17990
+ skillRoots: roots,
17991
+ createdPaths: paths,
17992
+ contentSha256
17993
+ };
17994
+ const path = skillOwnershipReceiptPath(ctx);
17995
+ await mkdir(dirname(path), { recursive: true });
17996
+ const tmpPath = `${path}.${process.pid}.${Date.now()}.tmp`;
17997
+ await writeFile(tmpPath, `${JSON.stringify(receipt, null, 2)}
17998
+ `, "utf8");
17999
+ await rename(tmpPath, path);
18000
+ }
18001
+ async function readSkillOwnershipReceipt(ctx) {
18002
+ const path = skillOwnershipReceiptPath(ctx);
18003
+ let value;
18004
+ try {
18005
+ value = JSON.parse(await readFile(path, "utf8"));
18006
+ } catch (error) {
18007
+ if (error.code === "ENOENT") throw fail("is missing");
18008
+ throw fail("is corrupt");
18009
+ }
18010
+ if (!value || typeof value !== "object") throw fail("is corrupt");
18011
+ const receipt = value;
18012
+ if (receipt.version !== 2) throw fail("is legacy or unsupported");
18013
+ if (typeof receipt.component !== "string" || typeof receipt.hostId !== "string" || typeof receipt.nativeRoot !== "string" || typeof receipt.manifestSha256 !== "string" || !Array.isArray(receipt.skillRoots) || !receipt.skillRoots.every((root) => typeof root === "string") || !Array.isArray(receipt.createdPaths) || !receipt.createdPaths.every((path2) => typeof path2 === "string") || !receipt.contentSha256 || typeof receipt.contentSha256 !== "object") {
18014
+ throw fail("is corrupt");
18015
+ }
18016
+ const binding = receiptContext(ctx);
18017
+ if (receipt.component !== binding.component || receipt.hostId !== binding.hostId || resolve(receipt.nativeRoot) !== binding.nativeRoot) {
18018
+ throw fail("binding does not match the active component and host root");
18019
+ }
18020
+ if (receipt.manifestSha256 !== ownershipFingerprint(ctx)) throw fail("manifest identity changed");
18021
+ const currentRoots = new Set(
18022
+ skillRootsForContext(ctx).map((root) => resolve(root))
18023
+ );
18024
+ const normalizedReceiptRoots = normalizeRoots(receipt.skillRoots);
18025
+ if (normalizedReceiptRoots.some((root) => !currentRoots.has(root))) {
18026
+ throw fail("contains an unknown or inactive root");
18027
+ }
18028
+ const skillRoots = normalizedReceiptRoots;
18029
+ let createdPaths;
18030
+ try {
18031
+ createdPaths = validateCreatedPaths(skillRoots, receipt.createdPaths);
18032
+ } catch {
18033
+ throw fail("contains a path outside the active captured skill roots");
18034
+ }
18035
+ for (const path2 of createdPaths) {
18036
+ const digest = receipt.contentSha256[path2];
18037
+ if (typeof digest !== "string" || !/^[a-f0-9]{64}$/.test(digest)) {
18038
+ throw fail("contains an invalid or undeclared owned skill path");
18039
+ }
18040
+ }
18041
+ return {
18042
+ version: receipt.version,
18043
+ component: receipt.component,
18044
+ hostId: receipt.hostId,
18045
+ nativeRoot: binding.nativeRoot,
18046
+ manifestSha256: receipt.manifestSha256,
18047
+ skillRoots,
18048
+ createdPaths,
18049
+ contentSha256: receipt.contentSha256
18050
+ };
18051
+ }
18052
+ async function verifyOwnedSkillPath(receipt, path, actualPath = path) {
18053
+ const root = receipt.skillRoots.find((candidate) => dirname(path) === candidate);
18054
+ if (!root) throw fail("contains an owned path outside its captured roots");
18055
+ const [rootInfo, targetInfo] = await Promise.all([lstat(root), lstat(actualPath)]);
18056
+ if (rootInfo.isSymbolicLink() || targetInfo.isSymbolicLink() || !rootInfo.isDirectory() || !targetInfo.isDirectory()) {
18057
+ throw fail("target is a symbolic link, junction, or non-directory");
18058
+ }
18059
+ const [physicalRoot, physicalPath] = await Promise.all([realpath(root), realpath(actualPath)]);
18060
+ if (dirname(physicalPath) !== physicalRoot) throw fail("target escapes its captured skill root");
18061
+ if (await hashSkillTree(actualPath) !== receipt.contentSha256[path]) {
18062
+ throw fail("target content changed after installation");
18063
+ }
18064
+ }
18065
+ async function removeOwnedSkillPath(receipt, path) {
18066
+ const root = receipt.skillRoots.find((candidate) => dirname(path) === candidate);
18067
+ if (!root) throw fail("contains an owned path outside its captured roots");
18068
+ const snapshot = await prepareOwnedPathRemoval(root, path);
18069
+ await removeOwnedDirectoryViaQuarantine(snapshot, {
18070
+ verify: async (quarantinePath) => verifyOwnedSkillPath(receipt, path, quarantinePath)
18071
+ });
18072
+ }
18073
+ async function removeSkillOwnershipReceipt(ctx) {
18074
+ await rm(skillOwnershipReceiptPath(ctx), { force: true });
18075
+ }
18076
+ var init_skillOwnershipReceipt = __esm({
18077
+ "src/installers/lib/skillOwnershipReceipt.ts"() {
18078
+ init_quarantineDelete();
18079
+ init_platform();
18080
+ init_packSkillAudit();
18081
+ }
18082
+ });
16997
18083
  function detectLevel(cmd) {
16998
18084
  if (/\bnpm\s+install\s+-g\b/.test(cmd)) return "L4";
16999
18085
  if (/\bnpx\b/.test(cmd)) return "L1";
@@ -17024,6 +18110,7 @@ var init_npmCli2 = __esm({
17024
18110
  init_idempotent();
17025
18111
  init_packSkillAudit();
17026
18112
  init_preflight();
18113
+ init_skillOwnershipReceipt();
17027
18114
  init_spawn();
17028
18115
  init_state2();
17029
18116
  init_verifyInstalled();
@@ -17134,6 +18221,11 @@ var init_npmCli2 = __esm({
17134
18221
  const bk = await backup(plan, ctx);
17135
18222
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
17136
18223
  await warnDeclaredCollisions(ctx);
18224
+ const managesSkillOwnership = isSkillOwnershipManaged(ctx.manifest);
18225
+ const skillRoots = managesSkillOwnership ? skillRootsForContext(ctx) : [];
18226
+ const pathSnapshot = new Set(
18227
+ managesSkillOwnership ? await declaredSkillPaths(ctx, skillRoots) : []
18228
+ );
17137
18229
  const packSnapshot = await snapshotSkillNames(
17138
18230
  ...ctx.hostContext ? [ctx.hostContext.platform.skillsDir] : []
17139
18231
  );
@@ -17160,6 +18252,31 @@ var init_npmCli2 = __esm({
17160
18252
  );
17161
18253
  const verifyFailure = await verifyInstalled(ctx, { neutralCwd: true });
17162
18254
  if (verifyFailure) return { ...verifyFailure, backupId: bk.backupId };
18255
+ if (managesSkillOwnership) {
18256
+ try {
18257
+ const afterPaths = await declaredSkillPaths(ctx, skillRoots);
18258
+ await writeSkillOwnershipReceipt(
18259
+ ctx,
18260
+ skillRoots,
18261
+ afterPaths.filter((path) => !pathSnapshot.has(path))
18262
+ );
18263
+ } catch (error) {
18264
+ return {
18265
+ ok: false,
18266
+ phase: "verify",
18267
+ backupId: bk.backupId,
18268
+ error: {
18269
+ ...err(
18270
+ ctx,
18271
+ "/spec/install",
18272
+ `failed to persist skill ownership receipt: ${error.message}`,
18273
+ "verify-failed"
18274
+ ),
18275
+ suggest: "run repair or reinstall before uninstalling this skill pack"
18276
+ }
18277
+ };
18278
+ }
18279
+ }
17163
18280
  await updateInstalled(
17164
18281
  ctx.cwd,
17165
18282
  ctx.manifest.metadata.name,
@@ -17221,6 +18338,7 @@ var init_npxSkillInstaller2 = __esm({
17221
18338
  init_idempotent();
17222
18339
  init_packSkillAudit();
17223
18340
  init_preflight();
18341
+ init_skillOwnershipReceipt();
17224
18342
  init_spawn();
17225
18343
  init_state2();
17226
18344
  init_verifyInstalled();
@@ -17357,6 +18475,8 @@ var init_npxSkillInstaller2 = __esm({
17357
18475
  const bk = await backup(plan, ctx);
17358
18476
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
17359
18477
  await warnDeclaredCollisions(ctx);
18478
+ const skillRoots = skillRootsForContext(ctx);
18479
+ const pathSnapshot = new Set(await declaredSkillPaths(ctx, skillRoots));
17360
18480
  const packSnapshot = await snapshotSkillNames(
17361
18481
  ...ctx.hostContext ? [ctx.hostContext.platform.skillsDir] : []
17362
18482
  );
@@ -17405,6 +18525,29 @@ var init_npxSkillInstaller2 = __esm({
17405
18525
  }
17406
18526
  const verifyFailure = await verifyInstalled(ctx, { neutralCwd: true });
17407
18527
  if (verifyFailure) return { ...verifyFailure, backupId: bk.backupId };
18528
+ try {
18529
+ const afterPaths = await declaredSkillPaths(ctx, skillRoots);
18530
+ await writeSkillOwnershipReceipt(
18531
+ ctx,
18532
+ skillRoots,
18533
+ afterPaths.filter((path) => !pathSnapshot.has(path))
18534
+ );
18535
+ } catch (error) {
18536
+ return {
18537
+ ok: false,
18538
+ phase: "verify",
18539
+ backupId: bk.backupId,
18540
+ error: {
18541
+ ...err(
18542
+ ctx,
18543
+ "/spec/install",
18544
+ `failed to persist skill ownership receipt: ${error.message}`,
18545
+ "verify-failed"
18546
+ ),
18547
+ suggest: "run repair or reinstall before uninstalling this skill pack"
18548
+ }
18549
+ };
18550
+ }
17408
18551
  await updateInstalled(
17409
18552
  ctx.cwd,
17410
18553
  name,
@@ -17884,6 +19027,12 @@ function buildWorkflowStateBlock(wf, forward, ledgerAgeMs) {
17884
19027
  `REOPENED: sub '${next}' was sent back (attempt ${nextEntry.fail_count}${nextEntry.attempt_budget !== void 0 ? `/${nextEntry.attempt_budget}` : ""}) \u2014 ${nextEntry.reason}. Address THAT before re-running it; a repeat of the same attempt burns the budget.`
17885
19028
  );
17886
19029
  }
19030
+ for (const e of ledger) {
19031
+ if (!e.spawn_failure || isSettled(e)) continue;
19032
+ lines.push(
19033
+ `SPAWN-FAILED: sub '${e.sub}' failed to spawn (${e.spawn_failure}) \u2014 attempt ${e.fail_count ?? 0}; fix the cause before respawning it`
19034
+ );
19035
+ }
17887
19036
  if (!next && forward && (forward.unit.kind === "phase" || forward.unit.kind === "task")) {
17888
19037
  const n = forward.remainingPhases;
17889
19038
  lines.push(
@@ -18982,7 +20131,7 @@ function parseShaText(text) {
18982
20131
  return m?.[1]?.toLowerCase() ?? null;
18983
20132
  }
18984
20133
  async function runBinarySelfUpdate(deps, opts) {
18985
- const rename5 = deps.fsOps?.rename ?? rename;
20134
+ const rename8 = deps.fsOps?.rename ?? rename;
18986
20135
  const copyFile$1 = deps.fsOps?.copyFile ?? copyFile;
18987
20136
  const unlink2 = deps.fsOps?.unlink ?? unlink;
18988
20137
  if (normalized(deps.execPath).includes("/node_modules/")) {
@@ -19123,7 +20272,7 @@ async function runBinarySelfUpdate(deps, opts) {
19123
20272
  };
19124
20273
  }
19125
20274
  try {
19126
- await rename5(deps.execPath, bakPath);
20275
+ await rename8(deps.execPath, bakPath);
19127
20276
  } catch (e) {
19128
20277
  await unlink2(tempPath).catch(() => {
19129
20278
  });
@@ -19133,10 +20282,10 @@ async function runBinarySelfUpdate(deps, opts) {
19133
20282
  };
19134
20283
  }
19135
20284
  try {
19136
- await rename5(tempPath, deps.execPath);
20285
+ await rename8(tempPath, deps.execPath);
19137
20286
  } catch (e) {
19138
20287
  try {
19139
- await rename5(bakPath, deps.execPath);
20288
+ await rename8(bakPath, deps.execPath);
19140
20289
  return {
19141
20290
  status: "error",
19142
20291
  message: `swap failed (${e.message}) \u2014 rolled back to the previous binary`
@@ -19190,7 +20339,7 @@ async function finalizeBinarySelfUpdate(deps, outcome) {
19190
20339
  }
19191
20340
  }
19192
20341
  async function runBinaryRollback(deps, opts) {
19193
- const rename5 = deps.fsOps?.rename ?? rename;
20342
+ const rename8 = deps.fsOps?.rename ?? rename;
19194
20343
  const copyFile$1 = deps.fsOps?.copyFile ?? copyFile;
19195
20344
  const unlink2 = deps.fsOps?.unlink ?? unlink;
19196
20345
  if (normalized(deps.execPath).includes("/node_modules/")) {
@@ -19252,7 +20401,7 @@ async function runBinaryRollback(deps, opts) {
19252
20401
  };
19253
20402
  }
19254
20403
  try {
19255
- await rename5(deps.execPath, bakPath);
20404
+ await rename8(deps.execPath, bakPath);
19256
20405
  } catch (e) {
19257
20406
  await unlink2(tempPath).catch(() => {
19258
20407
  });
@@ -19262,10 +20411,10 @@ async function runBinaryRollback(deps, opts) {
19262
20411
  };
19263
20412
  }
19264
20413
  try {
19265
- await rename5(tempPath, deps.execPath);
20414
+ await rename8(tempPath, deps.execPath);
19266
20415
  } catch (e) {
19267
20416
  try {
19268
- await rename5(bakPath, deps.execPath);
20417
+ await rename8(bakPath, deps.execPath);
19269
20418
  return {
19270
20419
  status: "error",
19271
20420
  message: `swap failed (${e.message}) \u2014 restored the previous binary`
@@ -19696,7 +20845,7 @@ function decodeUpdateContinuation(encoded) {
19696
20845
  return value;
19697
20846
  }
19698
20847
  async function runContinuationProcess(executablePath, args, options) {
19699
- return new Promise((resolve37, reject) => {
20848
+ return new Promise((resolve39, reject) => {
19700
20849
  const child = spawn(executablePath, args, {
19701
20850
  cwd: options.cwd,
19702
20851
  env: options.env,
@@ -19710,7 +20859,7 @@ async function runContinuationProcess(executablePath, args, options) {
19710
20859
  child.once("error", reject);
19711
20860
  child.once("close", (exitCode, signal) => {
19712
20861
  clearTimeout(timer);
19713
- resolve37({ exitCode, signal });
20862
+ resolve39({ exitCode, signal });
19714
20863
  });
19715
20864
  });
19716
20865
  }
@@ -21751,13 +22900,13 @@ async function runResume() {
21751
22900
  error: "no current-workflow.json found under <harnessed-root>"
21752
22901
  };
21753
22902
  }
21754
- if (current.status !== "paused") {
21755
- return {
21756
- status: "no-paused-phase",
21757
- error: `workflow status is '${current.status}', not 'paused'`
21758
- };
21759
- }
21760
22903
  if (!current.last_checkpoint_path) {
22904
+ if (current.status !== "paused") {
22905
+ return {
22906
+ status: "no-paused-phase",
22907
+ error: `workflow status is '${current.status}', not 'paused'`
22908
+ };
22909
+ }
21761
22910
  return { status: "corrupt", error: "last_checkpoint_path missing", path: "" };
21762
22911
  }
21763
22912
  const path = current.last_checkpoint_path;
@@ -21765,12 +22914,24 @@ async function runResume() {
21765
22914
  try {
21766
22915
  raw = await readFile(path, "utf8");
21767
22916
  } catch (e) {
22917
+ if (current.status !== "paused") {
22918
+ return {
22919
+ status: "no-paused-phase",
22920
+ error: `workflow status is '${current.status}', not 'paused'`
22921
+ };
22922
+ }
21768
22923
  return { status: "corrupt", error: `checkpoint missing: ${e.message}`, path };
21769
22924
  }
21770
22925
  let parsed;
21771
22926
  try {
21772
22927
  parsed = JSON.parse(raw);
21773
22928
  } catch (e) {
22929
+ if (current.status !== "paused") {
22930
+ return {
22931
+ status: "no-paused-phase",
22932
+ error: `workflow status is '${current.status}', not 'paused'`
22933
+ };
22934
+ }
21774
22935
  return {
21775
22936
  status: "corrupt",
21776
22937
  error: `checkpoint JSON parse failed: ${e.message}`,
@@ -21783,9 +22944,28 @@ async function runResume() {
21783
22944
  unknown: () => null
21784
22945
  });
21785
22946
  if (!validated) {
22947
+ if (current.status !== "paused") {
22948
+ return {
22949
+ status: "no-paused-phase",
22950
+ error: `workflow status is '${current.status}', not 'paused'`
22951
+ };
22952
+ }
21786
22953
  const errs = [...Value.Errors(CheckpointV1, parsed)].map((e) => e.message).join("; ");
21787
22954
  return { status: "corrupt", error: `checkpoint schema validation failed: ${errs}`, path };
21788
22955
  }
22956
+ if (isFailedCheckpoint(validated)) {
22957
+ return {
22958
+ status: "failed",
22959
+ error: `checkpoint phase '${validated.phase}' failed: ${validated.last_task}`,
22960
+ checkpoint: validated
22961
+ };
22962
+ }
22963
+ if (current.status !== "paused") {
22964
+ return {
22965
+ status: "no-paused-phase",
22966
+ error: `workflow status is '${current.status}', not 'paused'`
22967
+ };
22968
+ }
21789
22969
  const cwd = process.cwd();
21790
22970
  const cwdWarn = validated.cwd !== cwd ? `\u26A0 checkpoint cwd '${validated.cwd}' \u2260 current cwd '${cwd}' \u2014 SDK session resume may fail (\xA7 1.3); fresh-session fallback` : void 0;
21791
22971
  const sidHint = validated.session_id ? ` (recorded session_id: ${validated.session_id}, resumable only on the host that created it; other hosts reload context from the checkpoint)` : " (fresh session \u2014 context reloaded from checkpoint)";
@@ -21812,6 +22992,7 @@ var init_resume = __esm({
21812
22992
  "src/checkpoint/resume.ts"() {
21813
22993
  init_schemaVersion();
21814
22994
  init_evidence();
22995
+ init_failure();
21815
22996
  init_recovery();
21816
22997
  init_schema();
21817
22998
  init_state();
@@ -21842,6 +23023,10 @@ function registerResume(program2) {
21842
23023
  console.error(t("resume.corrupt", { error: r.error, path: r.path }));
21843
23024
  process.exit(1);
21844
23025
  }
23026
+ if (r.status === "failed") {
23027
+ console.error(t("resume.fail", { error: r.error }));
23028
+ process.exit(1);
23029
+ }
21845
23030
  if (r.cwdWarn) console.error(r.cwdWarn);
21846
23031
  if (r.driftWarn) for (const w of r.driftWarn) console.error(w);
21847
23032
  console.log(`phase: ${r.checkpoint.phase}`);
@@ -22163,7 +23348,15 @@ function registerRun(program2) {
22163
23348
  }
22164
23349
  let result;
22165
23350
  try {
22166
- result = await runWorkflow(yamlPath, {}, { packageRoot: PACKAGE_ROOT2, gateContext });
23351
+ result = await runWorkflow(
23352
+ yamlPath,
23353
+ {},
23354
+ {
23355
+ packageRoot: PACKAGE_ROOT2,
23356
+ gateContext,
23357
+ ...name === "auto" && raw.staged ? { masterOpts: { pauseBetweenStages: true } } : {}
23358
+ }
23359
+ );
22167
23360
  } catch (err2) {
22168
23361
  if (err2 instanceof WorkflowHaltError) {
22169
23362
  process.exit(err2.exitCode);
@@ -23211,7 +24404,16 @@ __export(setup_exports, {
23211
24404
  printGrouped: () => printGrouped,
23212
24405
  registerSetup: () => registerSetup
23213
24406
  });
23214
- async function applyPlatformOption(platform, persist) {
24407
+ function isAdvisorySettingsWarning(message) {
24408
+ return message.includes("capability-absent");
24409
+ }
24410
+ function isCommandFailureWarning(warning) {
24411
+ return warning.startsWith("no role-prompts.yaml entry") || warning.startsWith("host-primitive render failed") || warning.startsWith("write failed");
24412
+ }
24413
+ function isDuplicateCommandFailureSummary(warning) {
24414
+ return warning.startsWith("role-prompts.yaml missing entry") || /^commands\/.+: host-primitive render failed$/.test(warning);
24415
+ }
24416
+ function applyPlatformOption(platform) {
23215
24417
  if (!KNOWN_PLATFORMS.includes(platform)) {
23216
24418
  console.error(
23217
24419
  `--platform: unknown id '${platform}' (expected one of: ${KNOWN_PLATFORMS.join(" | ")})`
@@ -23219,22 +24421,13 @@ async function applyPlatformOption(platform, persist) {
23219
24421
  process.exit(1);
23220
24422
  }
23221
24423
  process.env.HARNESSED_PLATFORM = platform;
23222
- if (!persist) return;
23223
- const [own, other] = platform === "codex" ? [codexDescriptor().stateRoot, claudeDescriptor().stateRoot] : [claudeDescriptor().stateRoot, codexDescriptor().stateRoot];
24424
+ }
24425
+ async function persistPlatformPin(context) {
24426
+ const platform = context.hostId;
24427
+ const own = join(context.nativeHome, "harnessed");
23224
24428
  try {
23225
24429
  await mkdir(own, { recursive: true });
23226
24430
  await writeFile(join(own, ".platform"), platform, "utf8");
23227
- const otherPin = join(other, ".platform");
23228
- let existing;
23229
- try {
23230
- const raw = await readFile(otherPin, "utf8");
23231
- existing = typeof raw === "string" ? raw.trim() : void 0;
23232
- } catch {
23233
- existing = void 0;
23234
- }
23235
- if (existing !== void 0 && existing !== platform) {
23236
- await writeFile(otherPin, platform, "utf8");
23237
- }
23238
24431
  } catch (e) {
23239
24432
  console.warn(` [--platform] could not persist .platform pin (${e.message})`);
23240
24433
  }
@@ -23387,8 +24580,12 @@ function registerSetup(program2) {
23387
24580
  ).action(async (raw) => {
23388
24581
  await printSetupVersionBanner();
23389
24582
  const dryRun = raw.dryRun === true;
23390
- if (raw.platform !== void 0) await applyPlatformOption(raw.platform, !dryRun);
23391
- const setupContext = captureHostInstallContext();
24583
+ const setupFailures = [];
24584
+ if (raw.platform !== void 0) applyPlatformOption(raw.platform);
24585
+ const setupContext = captureHostInstallContext(
24586
+ raw.platform === void 0 ? {} : { hostId: raw.platform }
24587
+ );
24588
+ if (raw.platform !== void 0 && !dryRun) await persistPlatformPin(setupContext);
23392
24589
  const skillLedgerPath = join(setupContext.platform.stateRoot, "skill-hashes.json");
23393
24590
  const pkgRoot = getAssetsRoot();
23394
24591
  const workflowsDir = resolve(pkgRoot, "workflows");
@@ -23574,15 +24771,26 @@ Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting
23574
24771
  }
23575
24772
  console.log(t("setup.step_a_complete", { count: skillsInstalled, path: skillsBase }));
23576
24773
  const skillNames = toInstall.map((wf) => wf.name);
23577
- const rendered = await renderAllSkills(
23578
- skillNames,
23579
- skillsBase,
23580
- workflowsDir,
23581
- void 0,
23582
- getLocale(),
23583
- setupContext.hostId,
23584
- setupContext
24774
+ let rendered;
24775
+ try {
24776
+ rendered = await renderAllSkills(
24777
+ skillNames,
24778
+ skillsBase,
24779
+ workflowsDir,
24780
+ void 0,
24781
+ getLocale(),
24782
+ setupContext.hostId,
24783
+ setupContext
24784
+ );
24785
+ } catch (err2) {
24786
+ const message = `skill render failed: ${err2.message}`;
24787
+ setupFailures.push(message);
24788
+ rendered = { results: [], aggregatedWarnings: [message] };
24789
+ }
24790
+ const renderErrors = new Set(
24791
+ rendered.results.filter((result) => result.error).map((result) => result.error)
23585
24792
  );
24793
+ setupFailures.push(...renderErrors);
23586
24794
  if (rendered.aggregatedWarnings.length > 0) {
23587
24795
  console.warn(t("setup.step_a_render.warnings_header"));
23588
24796
  for (const w of rendered.aggregatedWarnings) {
@@ -23645,6 +24853,18 @@ Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting
23645
24853
  );
23646
24854
  const writtenCount = cmdResult.results.filter((r) => r.written).length;
23647
24855
  const skippedCount = cmdResult.results.filter((r) => !r.written && r.warning).length;
24856
+ const commandWarnings = /* @__PURE__ */ new Set();
24857
+ for (const result of cmdResult.results) {
24858
+ if (!result.warning) continue;
24859
+ commandWarnings.add(result.warning);
24860
+ if (isCommandFailureWarning(result.warning)) setupFailures.push(result.warning);
24861
+ }
24862
+ for (const warning of cmdResult.warnings ?? []) {
24863
+ if (!isDuplicateCommandFailureSummary(warning)) commandWarnings.add(warning);
24864
+ }
24865
+ for (const warning of commandWarnings) {
24866
+ console.warn(t("setup.command_warning", { message: warning }));
24867
+ }
23648
24868
  if (writtenCount > 0 || skippedCount > 0) {
23649
24869
  console.log(
23650
24870
  ` generated ${writtenCount} commands/<x>.md file(s) (${skippedCount} skipped)`
@@ -23683,8 +24903,20 @@ Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting
23683
24903
  console.warn(` [A.7] codex agent roles skipped (${e.message})`);
23684
24904
  }
23685
24905
  }
23686
- await enableAgentTeamsInSettings(setupContext);
23687
- await enableUserLangInSettings(raw.userLang, setupContext);
24906
+ const agentTeamsResult = await enableAgentTeamsInSettings(setupContext);
24907
+ if (agentTeamsResult?.status === "warn") {
24908
+ console.warn(t("setup.step_c.skipped", { message: agentTeamsResult.message }));
24909
+ if (!isAdvisorySettingsWarning(agentTeamsResult.message)) {
24910
+ setupFailures.push(agentTeamsResult.message);
24911
+ }
24912
+ }
24913
+ const userLangResult = await enableUserLangInSettings(raw.userLang, setupContext);
24914
+ if (userLangResult?.status === "warn") {
24915
+ console.warn(t("setup.step_d.skipped", { message: userLangResult.message }));
24916
+ if (!isAdvisorySettingsWarning(userLangResult.message)) {
24917
+ setupFailures.push(userLangResult.message);
24918
+ }
24919
+ }
23688
24920
  let pendingNonInteractiveL4Repair = false;
23689
24921
  const hasL4RepairCandidate = b.skipped.some((s) => s.reason === "level-flag-missing") || b.failed.some((failure) => {
23690
24922
  const name = failure.split(": ", 1)[0] ?? failure;
@@ -23751,7 +24983,7 @@ Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting
23751
24983
  console.error(` [optional] ${failure.name}: ${failure.reason}`);
23752
24984
  }
23753
24985
  }
23754
- const failedCount = b.failed.length + optionalFailed;
24986
+ const failedCount = b.failed.length + optionalFailed + setupFailures.length;
23755
24987
  if (failedCount > 0) {
23756
24988
  console.error(
23757
24989
  `
@@ -23761,7 +24993,7 @@ ${failedCount} component(s) failed \u2014 see the notes above; re-run \`harnesse
23761
24993
  const configured = b.installed.length + b.alreadyInstalled.length + (b.keptExisting?.length ?? 0);
23762
24994
  if (failedCount > 0) {
23763
24995
  console.error(
23764
- `setup incomplete - ${skillsInstalled} workflow(s) installed; ${configured} base component(s) configured; ${failedCount} component(s) failed (${b.failed.length} base, ${optionalFailed} optional).`
24996
+ `setup incomplete - ${skillsInstalled} workflow(s) installed; ${configured} base component(s) configured; ${failedCount} component(s) failed (${b.failed.length} base, ${optionalFailed} optional, ${setupFailures.length} setup).`
23765
24997
  );
23766
24998
  } else {
23767
24999
  console.log(
@@ -23938,6 +25170,8 @@ var init_runOrPreview = __esm({
23938
25170
  var uninstallCcHookAdd;
23939
25171
  var init_ccHookAdd3 = __esm({
23940
25172
  "src/uninstallers/ccHookAdd.ts"() {
25173
+ init_settingsTransactionLock();
25174
+ init_settingsWriter();
23941
25175
  init_codexHookAdd();
23942
25176
  init_hookEntry();
23943
25177
  init_assetsRoot();
@@ -23961,40 +25195,61 @@ var init_ccHookAdd3 = __esm({
23961
25195
  }
23962
25196
  const settingsPath = context.platform.settingsPath === null ? null : join(context.nativeHome, "settings.json");
23963
25197
  if (settingsPath === null) return { ok: true, removedPaths: [] };
23964
- let existing;
23965
- try {
23966
- existing = await readFile(settingsPath, "utf8");
23967
- } catch {
23968
- return { ok: true, removedPaths: [] };
23969
- }
23970
- let settings;
23971
25198
  try {
23972
- settings = JSON.parse(existing);
23973
- } catch (e) {
25199
+ return await withSettingsTransactionLock(context, async () => {
25200
+ let existing;
25201
+ try {
25202
+ existing = await readFile(settingsPath, "utf8");
25203
+ } catch (error) {
25204
+ if (error.code === "ENOENT") {
25205
+ return { ok: true, removedPaths: [] };
25206
+ }
25207
+ return { ok: false, phase: "preflight", error: error.message };
25208
+ }
25209
+ let settings;
25210
+ try {
25211
+ settings = JSON.parse(existing);
25212
+ } catch (e) {
25213
+ return {
25214
+ ok: false,
25215
+ phase: "preflight",
25216
+ error: `malformed settings.json: ${e.message.slice(0, 200)}`
25217
+ };
25218
+ }
25219
+ if (settings === null || typeof settings !== "object" || Array.isArray(settings)) {
25220
+ return { ok: false, phase: "preflight", error: "malformed settings.json: expected object" };
25221
+ }
25222
+ const ev = install.hook_event;
25223
+ const cmd = install.hook_command;
25224
+ if (!settings.hooks?.[ev]) return { ok: true, removedPaths: [] };
25225
+ if (!Array.isArray(settings.hooks[ev])) {
25226
+ return {
25227
+ ok: false,
25228
+ phase: "preflight",
25229
+ error: `malformed settings.json: hooks.${ev} must be an array`
25230
+ };
25231
+ }
25232
+ const resolved = resolveHookCommand(cmd, { assetsRoot: getAssetsRoot, exists: existsSync });
25233
+ const marker = hookScriptMarker(cmd);
25234
+ const before = settings.hooks[ev].length;
25235
+ settings.hooks[ev] = settings.hooks[ev].filter(
25236
+ (hook) => !entryMatchesRegistration(hook, cmd, resolved, marker)
25237
+ );
25238
+ if (settings.hooks[ev].length === before) return { ok: true, removedPaths: [] };
25239
+ if (settings.hooks[ev].length === 0) delete settings.hooks[ev];
25240
+ if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
25241
+ const writeError = await atomicWrite(settingsPath, `${JSON.stringify(settings, null, 2)}
25242
+ `);
25243
+ if (writeError) return { ok: false, phase: "spawn", error: writeError };
25244
+ return { ok: true, removedPaths: [settingsPath] };
25245
+ });
25246
+ } catch (error) {
23974
25247
  return {
23975
25248
  ok: false,
23976
25249
  phase: "preflight",
23977
- error: `malformed settings.json: ${e.message.slice(0, 200)}`
25250
+ error: `settings transaction lock failed: ${error.message}`
23978
25251
  };
23979
25252
  }
23980
- const ev = install.hook_event;
23981
- const cmd = install.hook_command;
23982
- if (!settings.hooks?.[ev]) {
23983
- return { ok: true, removedPaths: [] };
23984
- }
23985
- const resolved = resolveHookCommand(cmd, { assetsRoot: getAssetsRoot, exists: existsSync });
23986
- const marker = hookScriptMarker(cmd);
23987
- const before = settings.hooks[ev].length;
23988
- settings.hooks[ev] = settings.hooks[ev].filter(
23989
- (h) => !entryMatchesRegistration(h, cmd, resolved, marker)
23990
- );
23991
- if (settings.hooks[ev].length === 0) delete settings.hooks[ev];
23992
- if (Object.keys(settings.hooks).length === 0) delete settings.hooks;
23993
- if (settings.hooks?.[ev]?.length === before || before === settings.hooks?.[ev]?.length) ;
23994
- const newText = `${JSON.stringify(settings, null, 2)}
23995
- `;
23996
- await writeFile(settingsPath, newText);
23997
- return { ok: true, removedPaths: [settingsPath] };
23998
25253
  };
23999
25254
  }
24000
25255
  });
@@ -24170,12 +25425,70 @@ async function runDeclaredTeardown(ctx) {
24170
25425
  }
24171
25426
  const abort = dryRunGate(ctx);
24172
25427
  if (abort) return abort;
24173
- const confined2 = [];
24174
- const canonicalTargets = /* @__PURE__ */ new Map();
25428
+ if (isSkillOwnershipManaged(ctx.manifest)) {
25429
+ let receipt;
25430
+ try {
25431
+ receipt = await readSkillOwnershipReceipt(ctx);
25432
+ } catch (error) {
25433
+ return {
25434
+ ok: false,
25435
+ phase: "preflight",
25436
+ error: error instanceof Error ? error.message : String(error)
25437
+ };
25438
+ }
25439
+ try {
25440
+ for (const path of receipt.createdPaths) await verifyOwnedSkillPath(receipt, path);
25441
+ } catch (error) {
25442
+ return {
25443
+ ok: false,
25444
+ phase: "preflight",
25445
+ error: error instanceof Error ? error.message : String(error)
25446
+ };
25447
+ }
25448
+ const removedPaths2 = [];
25449
+ const remainingPaths = [...receipt.createdPaths];
25450
+ for (const path of receipt.createdPaths) {
25451
+ try {
25452
+ await removeOwnedSkillPath(receipt, path);
25453
+ } catch (error) {
25454
+ return {
25455
+ ok: false,
25456
+ phase: "verify",
25457
+ error: error instanceof Error ? error.message : String(error)
25458
+ };
25459
+ }
25460
+ removedPaths2.push(path);
25461
+ remainingPaths.shift();
25462
+ try {
25463
+ if (remainingPaths.length > 0) {
25464
+ await writeSkillOwnershipReceipt(ctx, receipt.skillRoots, remainingPaths);
25465
+ } else {
25466
+ await removeSkillOwnershipReceipt(ctx);
25467
+ }
25468
+ } catch (error) {
25469
+ return {
25470
+ ok: false,
25471
+ phase: "verify",
25472
+ error: error instanceof Error ? error.message : String(error)
25473
+ };
25474
+ }
25475
+ }
25476
+ return { ok: true, removedPaths: removedPaths2 };
25477
+ }
25478
+ const cleanupTargets = [];
25479
+ const userHome = ctx.hostContext?.userHome ?? homedir();
25480
+ const canonicalHome = canonicalPath(resolve(userHome));
25481
+ if ((u.cleanup_paths?.length ?? 0) > 0 && !canonicalHome) {
25482
+ return {
25483
+ ok: false,
25484
+ phase: "preflight",
25485
+ error: "refusing cleanup_path: canonical home could not be verified"
25486
+ };
25487
+ }
24175
25488
  for (const raw of u.cleanup_paths ?? []) {
24176
25489
  let abs;
24177
25490
  try {
24178
- abs = confineCleanupPath(raw, ctx.hostContext?.userHome);
25491
+ abs = confineCleanupPath(raw, userHome);
24179
25492
  } catch {
24180
25493
  return {
24181
25494
  ok: false,
@@ -24190,19 +25503,35 @@ async function runDeclaredTeardown(ctx) {
24190
25503
  error: `refusing to remove cleanup_path outside $HOME: ${raw}`
24191
25504
  };
24192
25505
  }
24193
- if (ctx.hostContext) {
24194
- const canonicalHome = canonicalPath(resolve(ctx.hostContext.userHome));
24195
- const canonicalTarget = canonicalPath(abs);
24196
- if (!canonicalHome || !canonicalTarget?.startsWith(canonicalHome + sep)) {
25506
+ const canonicalTarget = canonicalPath(abs);
25507
+ if (!canonicalHome || !canonicalTarget?.startsWith(canonicalHome + sep)) {
25508
+ return {
25509
+ ok: false,
25510
+ phase: "preflight",
25511
+ error: "refusing cleanup_path: canonical target escapes captured home"
25512
+ };
25513
+ }
25514
+ let snapshot;
25515
+ try {
25516
+ snapshot = await prepareOwnedPathRemoval(dirname(abs), abs);
25517
+ } catch (error) {
25518
+ if (error.code === "ENOENT") snapshot = null;
25519
+ else {
24197
25520
  return {
24198
25521
  ok: false,
24199
25522
  phase: "preflight",
24200
- error: "refusing cleanup_path: canonical target escapes captured home"
25523
+ error: error instanceof Error ? error.message : String(error)
24201
25524
  };
24202
25525
  }
24203
- canonicalTargets.set(abs, canonicalTarget);
24204
25526
  }
24205
- confined2.push(abs);
25527
+ if (snapshot && (snapshot.canonicalTarget !== canonicalTarget || snapshot.canonicalRoot !== canonicalHome && !snapshot.canonicalRoot.startsWith(canonicalHome + sep))) {
25528
+ return {
25529
+ ok: false,
25530
+ phase: "preflight",
25531
+ error: "refusing cleanup_path: ownership snapshot escapes canonical home"
25532
+ };
25533
+ }
25534
+ cleanupTargets.push({ abs, snapshot });
24206
25535
  }
24207
25536
  const spawnCtx = {
24208
25537
  manifest: ctx.manifest,
@@ -24212,66 +25541,118 @@ async function runDeclaredTeardown(ctx) {
24212
25541
  opts: { apply: true, dryRun: false, yes: true }
24213
25542
  };
24214
25543
  let spawnRes;
25544
+ let spawnFailure = null;
24215
25545
  try {
24216
25546
  spawnRes = await spawnCmd(spawnCtx, u.cmd, [], DEFAULT_INSTALL_TIMEOUT_MS, {
24217
25547
  posixShell: true
24218
25548
  });
24219
25549
  } catch (error) {
24220
- if (ctx.hostContext?.hostId !== "codex") throw error;
24221
- return {
25550
+ spawnFailure = {
24222
25551
  ok: false,
24223
25552
  phase: "spawn",
24224
25553
  error: error instanceof Error ? error.message : String(error)
24225
25554
  };
25555
+ spawnRes = { ok: false, phase: "spawn", error: { message: spawnFailure.error } };
24226
25556
  }
24227
25557
  if (ctx.hostContext?.hostId === "codex") {
24228
25558
  if ("exitCode" in spawnRes) {
24229
25559
  if (spawnRes.exitCode !== 0) {
24230
- return {
25560
+ spawnFailure = {
24231
25561
  ok: false,
24232
25562
  phase: "spawn",
24233
25563
  error: spawnRes.stderr || spawnRes.stdout || `declared uninstall cmd exited ${spawnRes.exitCode}`
24234
25564
  };
24235
25565
  }
24236
25566
  } else if ("error" in spawnRes) {
24237
- return {
25567
+ spawnFailure = {
24238
25568
  ok: false,
24239
25569
  phase: spawnRes.phase === "preflight" || spawnRes.phase === "verify" ? spawnRes.phase : "spawn",
24240
25570
  error: spawnRes.error.message
24241
25571
  };
24242
25572
  } else {
24243
- return { ok: false, phase: "spawn", error: "declared uninstall cmd did not complete" };
25573
+ spawnFailure = {
25574
+ ok: false,
25575
+ phase: "spawn",
25576
+ error: "declared uninstall cmd did not complete"
25577
+ };
24244
25578
  }
24245
25579
  }
24246
25580
  const name = ctx.manifest.metadata.name;
24247
25581
  if (!("exitCode" in spawnRes)) {
24248
25582
  const msg = "error" in spawnRes ? spawnRes.error.message : "unknown spawn failure";
25583
+ spawnFailure ??= {
25584
+ ok: false,
25585
+ phase: "phase" in spawnRes && (spawnRes.phase === "preflight" || spawnRes.phase === "verify") ? spawnRes.phase : "spawn",
25586
+ error: msg
25587
+ };
24249
25588
  console.warn(
24250
25589
  `declared uninstall cmd for '${name}' could not run (${msg}); continuing to cleanup_paths (best-effort teardown).`
24251
25590
  );
24252
25591
  } else if (spawnRes.exitCode !== 0) {
25592
+ spawnFailure ??= {
25593
+ ok: false,
25594
+ phase: "spawn",
25595
+ error: spawnRes.stderr || spawnRes.stdout || `declared uninstall cmd exited ${spawnRes.exitCode}`
25596
+ };
24253
25597
  console.warn(
24254
25598
  `declared uninstall cmd for '${name}' exited ${spawnRes.exitCode} (best-effort teardown; continuing to cleanup_paths): ` + (spawnRes.stderr || spawnRes.stdout || "(no output)").slice(0, 200)
24255
25599
  );
24256
25600
  }
24257
25601
  const removedPaths = [];
24258
- for (const abs of confined2) {
24259
- if (ctx.hostContext && canonicalPath(abs) !== canonicalTargets.get(abs)) {
25602
+ for (const { abs, snapshot } of cleanupTargets) {
25603
+ if (snapshot === null) {
25604
+ try {
25605
+ await lstat(abs);
25606
+ } catch (error) {
25607
+ if (error.code === "ENOENT") {
25608
+ removedPaths.push(abs);
25609
+ continue;
25610
+ }
25611
+ return {
25612
+ ok: false,
25613
+ phase: "verify",
25614
+ error: error instanceof Error ? error.message : String(error)
25615
+ };
25616
+ }
24260
25617
  return {
24261
25618
  ok: false,
24262
- phase: "preflight",
24263
- error: "refusing cleanup_path: canonical target changed during teardown"
25619
+ phase: "verify",
25620
+ error: `refusing cleanup_path that appeared after preflight: ${abs}`
25621
+ };
25622
+ }
25623
+ try {
25624
+ await lstat(abs);
25625
+ } catch (error) {
25626
+ if (error.code === "ENOENT") {
25627
+ removedPaths.push(abs);
25628
+ continue;
25629
+ }
25630
+ return {
25631
+ ok: false,
25632
+ phase: "verify",
25633
+ error: error instanceof Error ? error.message : String(error)
25634
+ };
25635
+ }
25636
+ try {
25637
+ if (snapshot.isDirectory) await removeOwnedDirectoryViaQuarantine(snapshot);
25638
+ else await removeOwnedFileViaQuarantine(snapshot);
25639
+ } catch (error) {
25640
+ return {
25641
+ ok: false,
25642
+ phase: "verify",
25643
+ error: error instanceof Error ? error.message : String(error)
24264
25644
  };
24265
25645
  }
24266
- await rm(abs, { recursive: true, force: true, maxRetries: 3 });
24267
25646
  removedPaths.push(abs);
24268
25647
  }
24269
- return { ok: true, removedPaths };
25648
+ return spawnFailure ?? { ok: true, removedPaths };
24270
25649
  }
24271
25650
  var init_declaredTeardown = __esm({
24272
25651
  "src/uninstallers/lib/declaredTeardown.ts"() {
24273
25652
  init_componentPlan();
25653
+ init_skillOwnershipReceipt();
24274
25654
  init_spawn();
25655
+ init_quarantineDelete();
24275
25656
  init_path_guard();
24276
25657
  init_runOrPreview();
24277
25658
  }
@@ -24376,7 +25757,7 @@ var init_npmCli3 = __esm({
24376
25757
  cwd: ctx.hostContext.userHome,
24377
25758
  env: withHostInstallEnv(process.env, ctx.hostContext)
24378
25759
  } : {};
24379
- const result = await new Promise((resolve37) => {
25760
+ const result = await new Promise((resolve39) => {
24380
25761
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], {
24381
25762
  ...spawnOptions,
24382
25763
  windowsHide: true
@@ -24387,15 +25768,15 @@ var init_npmCli3 = __esm({
24387
25768
  });
24388
25769
  const timer = setTimeout(() => {
24389
25770
  child.kill("SIGKILL");
24390
- resolve37({ exitCode: -1, stderr: `${stderr}[timeout]` });
25771
+ resolve39({ exitCode: -1, stderr: `${stderr}[timeout]` });
24391
25772
  }, 3e4);
24392
25773
  child.on("error", (e) => {
24393
25774
  clearTimeout(timer);
24394
- resolve37({ exitCode: -1, stderr: e.message });
25775
+ resolve39({ exitCode: -1, stderr: e.message });
24395
25776
  });
24396
25777
  child.on("close", (code2) => {
24397
25778
  clearTimeout(timer);
24398
- resolve37({ exitCode: code2 ?? -1, stderr });
25779
+ resolve39({ exitCode: code2 ?? -1, stderr });
24399
25780
  });
24400
25781
  });
24401
25782
  if (result.exitCode !== 0) {
@@ -24545,59 +25926,93 @@ async function discoverCommandFiles(commandsDir) {
24545
25926
  }
24546
25927
  return owned;
24547
25928
  }
24548
- async function discoverCodexAgentRoles() {
25929
+ async function discoverCodexAgentRoles(context) {
24549
25930
  try {
24550
- const [{ resolveCodexHome: resolveCodexHome2 }, m] = await Promise.all([
24551
- Promise.resolve().then(() => (init_codexHookAdd(), codexHookAdd_exports)),
24552
- Promise.resolve().then(() => (init_codexAgentRoles(), codexAgentRoles_exports))
24553
- ]);
24554
- return await m.discoverCodexAgentRoleFiles(m.codexAgentsDir(resolveCodexHome2()));
25931
+ const m = await Promise.resolve().then(() => (init_codexAgentRoles(), codexAgentRoles_exports));
25932
+ return await m.discoverCodexAgentRoleFiles(m.codexAgentsDir(context.nativeHome));
24555
25933
  } catch {
24556
25934
  return [];
24557
25935
  }
24558
25936
  }
24559
- async function checkSettingsEnv(settingsPath) {
24560
- if (settingsPath === null) return { hasAgentTeams: false, hasUserLang: false, staleHooks: 0 };
25937
+ async function discoverOwnedSkillDirs(skillsDir, stateRoot) {
25938
+ const ledger = await readHashLedger(join(stateRoot, "skill-hashes.json"));
25939
+ if (ledger === null) return { dirs: [], failures: [], expectedHashes: /* @__PURE__ */ new Map() };
25940
+ const dirs = [];
25941
+ const failures = [];
25942
+ const expectedHashes = /* @__PURE__ */ new Map();
25943
+ for (const [name, record] of Object.entries(ledger)) {
25944
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name)) {
25945
+ failures.push(`invalid owned skill name in skill-hashes.json: ${name}`);
25946
+ continue;
25947
+ }
25948
+ const dir = join(skillsDir, name);
25949
+ try {
25950
+ const body = await readFile(join(dir, "SKILL.md"), "utf8");
25951
+ if (sha256Of(body) !== record.sha256) {
25952
+ failures.push(`${dir}: installed skill differs from the ownership ledger; repair first`);
25953
+ continue;
25954
+ }
25955
+ dirs.push(dir);
25956
+ expectedHashes.set(dir, record.sha256);
25957
+ } catch (error) {
25958
+ if (error.code !== "ENOENT") {
25959
+ failures.push(`${dir}: ${error.message}`);
25960
+ }
25961
+ }
25962
+ }
25963
+ return { dirs, failures, expectedHashes };
25964
+ }
25965
+ async function checkSettingsEnv(settingsPath, receipt) {
25966
+ if (settingsPath === null) return { status: "absent", hasOwnedEnv: false, staleHooks: 0 };
24561
25967
  try {
24562
25968
  const raw = await readFile(settingsPath, "utf8");
24563
25969
  const data = JSON.parse(raw);
24564
- const env = data.env ?? {};
24565
25970
  const hooks = data.hooks;
24566
25971
  return {
24567
- hasAgentTeams: "CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS" in env,
24568
- hasUserLang: "HARNESSED_USER_LANG" in env,
25972
+ status: "ok",
25973
+ hasOwnedEnv: receipt ? restoreOwnedSettingsEnv(data, receipt).changed : false,
24569
25974
  // issue #8 — count orphaned harnessed-owned Stop/UserPromptSubmit hooks.
24570
25975
  staleHooks: hooks && typeof hooks === "object" ? countHarnessedHooks(hooks) : 0
24571
25976
  };
24572
- } catch {
24573
- return { hasAgentTeams: false, hasUserLang: false, staleHooks: 0 };
25977
+ } catch (error) {
25978
+ if (error.code === "ENOENT") {
25979
+ return { status: "absent", hasOwnedEnv: false, staleHooks: 0 };
25980
+ }
25981
+ return {
25982
+ status: "error",
25983
+ error: error instanceof Error ? error.message : String(error),
25984
+ hasOwnedEnv: false,
25985
+ staleHooks: 0
25986
+ };
24574
25987
  }
24575
25988
  }
24576
- async function removeSettingsFootprint(settingsPath) {
24577
- const raw = await readFile(settingsPath, "utf8");
24578
- const data = JSON.parse(raw);
24579
- const env = data.env ?? {};
24580
- let envRemoved = false;
24581
- if ("CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS" in env) {
24582
- delete env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS;
24583
- envRemoved = true;
24584
- }
24585
- if ("HARNESSED_USER_LANG" in env) {
24586
- delete env.HARNESSED_USER_LANG;
24587
- envRemoved = true;
24588
- }
24589
- let hooksRemoved = 0;
24590
- const hooks = data.hooks;
24591
- if (hooks && typeof hooks === "object") {
24592
- hooksRemoved = stripHarnessedHooks(hooks).removed;
24593
- if (Object.keys(hooks).length === 0) delete data.hooks;
24594
- }
24595
- if (!envRemoved && hooksRemoved === 0) return { envRemoved: false, hooksRemoved: 0 };
24596
- if (Object.keys(env).length === 0) delete data.env;
24597
- else data.env = env;
24598
- await writeFile(settingsPath, `${JSON.stringify(data, null, 2)}
24599
- `, "utf8");
24600
- return { envRemoved, hooksRemoved };
25989
+ async function removeSettingsFootprint(settingsPath, context) {
25990
+ return withSettingsTransactionLock(context, async () => {
25991
+ const receiptResult = await loadSettingsOwnershipReceipt(context);
25992
+ if (receiptResult.status === "corrupt" || receiptResult.status === "error") {
25993
+ throw new Error(receiptResult.error);
25994
+ }
25995
+ const receipt = receiptResult.status === "ok" ? receiptResult.receipt : null;
25996
+ const raw = await readFile(settingsPath, "utf8");
25997
+ const data = JSON.parse(raw);
25998
+ if (data === null || typeof data !== "object" || Array.isArray(data)) {
25999
+ throw new Error("settings.json top-level value must be a JSON object");
26000
+ }
26001
+ const envRemoved = receipt ? restoreOwnedSettingsEnv(data, receipt).changed : false;
26002
+ let hooksRemoved = 0;
26003
+ const hooks = data.hooks;
26004
+ if (hooks && typeof hooks === "object" && !Array.isArray(hooks)) {
26005
+ hooksRemoved = stripHarnessedHooks(hooks).removed;
26006
+ if (Object.keys(hooks).length === 0) delete data.hooks;
26007
+ }
26008
+ if (envRemoved || hooksRemoved > 0) {
26009
+ const writeError = await atomicWrite(settingsPath, `${JSON.stringify(data, null, 2)}
26010
+ `);
26011
+ if (writeError) throw new Error(writeError);
26012
+ }
26013
+ if (receipt !== null) await rm(settingsOwnershipReceiptPath(context), { force: true });
26014
+ return { envRemoved, hooksRemoved };
26015
+ });
24601
26016
  }
24602
26017
  function printCliRemovalHint() {
24603
26018
  console.log(t("uninstall.unified.cli_hint_header"));
@@ -24621,35 +26036,75 @@ function printCliRemovalHint() {
24621
26036
  }
24622
26037
  console.log(t("uninstall.unified.cli_hint_other"));
24623
26038
  }
24624
- async function runUnifiedUninstall(home, dryRun) {
24625
- const platform = detectPlatform(home);
26039
+ async function runUnifiedUninstall(context, dryRun) {
26040
+ const platform = context.platform;
24626
26041
  const commandsDir = platform.commandsDir;
24627
26042
  const skillsDir = platform.skillsDir;
24628
26043
  const settingsPath = platform.settingsPath;
24629
- const harnessedRoot = getHarnessedRoot();
24630
- const pkgRoot = getAssetsRoot();
24631
- let workflowNames = [];
26044
+ const harnessedRoot = platform.stateRoot;
26045
+ const ownershipReceiptResult = await loadSettingsOwnershipReceipt(context);
26046
+ if (ownershipReceiptResult.status === "corrupt" || ownershipReceiptResult.status === "error") {
26047
+ console.error(`settings ownership receipt preflight failed: ${ownershipReceiptResult.error}`);
26048
+ process.exit(1);
26049
+ }
26050
+ const ownershipReceipt = ownershipReceiptResult.status === "ok" ? ownershipReceiptResult.receipt : null;
26051
+ const inventoryFailures = [];
26052
+ let stateEntries = [];
24632
26053
  try {
24633
- const wfEntries = await readdir(resolve(pkgRoot, "workflows"));
24634
- const scanResult = await scanWorkflowsNested(resolve(pkgRoot, "workflows"), wfEntries);
24635
- workflowNames = scanResult.workflows.map((w) => w.name);
24636
- } catch {
26054
+ stateEntries = (await readdir(harnessedRoot)).filter((entry) => entry !== "backups").map((entry) => join(harnessedRoot, entry));
26055
+ } catch (error) {
26056
+ if (error.code !== "ENOENT") {
26057
+ inventoryFailures.push(`${harnessedRoot}: ${error.message}`);
26058
+ }
24637
26059
  }
24638
26060
  const commandFiles = await discoverCommandFiles(commandsDir);
24639
- const agentRoleFiles = platform.id === "codex" ? await discoverCodexAgentRoles() : [];
24640
- const settingsEnv = await checkSettingsEnv(settingsPath);
24641
- const hasSettingsChanges = settingsEnv.hasAgentTeams || settingsEnv.hasUserLang;
26061
+ const agentRoleFiles = platform.id === "codex" ? await discoverCodexAgentRoles(context) : [];
26062
+ const settingsEnv = await checkSettingsEnv(settingsPath, ownershipReceipt);
26063
+ if (settingsEnv.status === "error" && settingsPath !== null) {
26064
+ inventoryFailures.push(`${settingsPath}: ${settingsEnv.error}`);
26065
+ }
26066
+ const hasSettingsChanges = settingsEnv.hasOwnedEnv;
24642
26067
  const staleHooks = settingsEnv.staleHooks;
24643
- const skillDirs = [];
24644
- for (const name of workflowNames) {
24645
- const dir = join(skillsDir, name);
26068
+ const settingsRemovalPath = settingsPath !== null && settingsEnv.status === "ok" && (ownershipReceipt !== null || hasSettingsChanges || staleHooks > 0) ? settingsPath : null;
26069
+ const ownedSkills = await discoverOwnedSkillDirs(skillsDir, harnessedRoot);
26070
+ const skillDirs = ownedSkills.dirs;
26071
+ inventoryFailures.push(...ownedSkills.failures);
26072
+ let agentsMdUpdate = null;
26073
+ if (platform.id === "codex") {
26074
+ const { agentsMdPath: agentsMdPath2, stripAgentsMdSection: stripAgentsMdSection2 } = await Promise.resolve().then(() => (init_agentsMd(), agentsMd_exports));
26075
+ const path = agentsMdPath2(context);
24646
26076
  try {
24647
- await stat(dir);
24648
- skillDirs.push(dir);
24649
- } catch {
26077
+ const before = await readFile(path, "utf8");
26078
+ const after = stripAgentsMdSection2(before);
26079
+ if (after !== before) agentsMdUpdate = { path, body: after };
26080
+ } catch (error) {
26081
+ if (error.code !== "ENOENT") {
26082
+ inventoryFailures.push(`${path}: ${error.message}`);
26083
+ }
26084
+ }
26085
+ }
26086
+ const destructivePaths = [
26087
+ ...commandFiles.map((target) => ({ root: commandsDir, target })),
26088
+ ...agentRoleFiles.map((target) => ({ root: join(context.nativeHome, "agents"), target })),
26089
+ ...skillDirs.map((target) => ({ root: skillsDir, target })),
26090
+ ...agentsMdUpdate ? [{ root: context.nativeHome, target: agentsMdUpdate.path }] : [],
26091
+ ...settingsRemovalPath !== null ? [{ root: context.nativeHome, target: settingsRemovalPath }] : [],
26092
+ ...stateEntries.map((target) => ({ root: harnessedRoot, target }))
26093
+ ];
26094
+ const canonicalPaths = /* @__PURE__ */ new Map();
26095
+ for (const item of destructivePaths) {
26096
+ try {
26097
+ canonicalPaths.set(item.target, await prepareOwnedPathRemoval(item.root, item.target));
26098
+ } catch (error) {
26099
+ inventoryFailures.push(`${item.target}: ${error.message}`);
24650
26100
  }
24651
26101
  }
24652
- const discoverable = commandFiles.length + agentRoleFiles.length + skillDirs.length + (hasSettingsChanges ? 1 : 0) + (staleHooks > 0 ? 1 : 0);
26102
+ if (inventoryFailures.length > 0) {
26103
+ console.error(t("uninstall.unified.partial_failure", { count: inventoryFailures.length }));
26104
+ for (const failure of inventoryFailures) console.error(` ${failure}`);
26105
+ process.exit(1);
26106
+ }
26107
+ const discoverable = commandFiles.length + agentRoleFiles.length + skillDirs.length + (hasSettingsChanges ? 1 : 0) + (staleHooks > 0 ? 1 : 0) + stateEntries.length;
24653
26108
  if (discoverable === 0) {
24654
26109
  console.log(t("uninstall.unified.nothing"));
24655
26110
  printCliRemovalHint();
@@ -24680,33 +26135,51 @@ async function runUnifiedUninstall(home, dryRun) {
24680
26135
  }
24681
26136
  console.log(t("uninstall.unified.removing"));
24682
26137
  const failures = [];
26138
+ const revalidate = async (path) => {
26139
+ const snapshot = canonicalPaths.get(path);
26140
+ if (!snapshot) {
26141
+ failures.push(`${path}: missing canonical preflight`);
26142
+ return false;
26143
+ }
26144
+ try {
26145
+ await assertOwnedPathUnchanged(snapshot);
26146
+ return true;
26147
+ } catch (error) {
26148
+ failures.push(`${path}: ${error.message}`);
26149
+ return false;
26150
+ }
26151
+ };
24683
26152
  let removedCommands = 0;
24684
26153
  for (const path of commandFiles) {
24685
26154
  try {
24686
- await rm(path, { force: true });
26155
+ if (!await revalidate(path)) continue;
26156
+ const snapshot = canonicalPaths.get(path);
26157
+ if (!snapshot) throw new Error("missing canonical preflight");
26158
+ await removeOwnedFileViaQuarantine(snapshot);
24687
26159
  removedCommands++;
24688
26160
  } catch (e) {
24689
26161
  failures.push(`${path}: ${e.message}`);
24690
26162
  }
24691
26163
  }
24692
26164
  let removedAgentsMdBlock = false;
24693
- if (platform.id === "codex") {
26165
+ if (agentsMdUpdate) {
24694
26166
  try {
24695
- const { agentsMdPath: agentsMdPath2, stripAgentsMdSection: stripAgentsMdSection2 } = await Promise.resolve().then(() => (init_agentsMd(), agentsMd_exports));
24696
- const p8 = agentsMdPath2();
24697
- const before = await readFile(p8, "utf8");
24698
- const after = stripAgentsMdSection2(before);
24699
- if (after !== before) {
24700
- await writeFile(p8, after, "utf8");
26167
+ if (await revalidate(agentsMdUpdate.path)) {
26168
+ const writeError = await atomicWrite(agentsMdUpdate.path, agentsMdUpdate.body);
26169
+ if (writeError) throw new Error(writeError);
24701
26170
  removedAgentsMdBlock = true;
24702
26171
  }
24703
- } catch {
26172
+ } catch (error) {
26173
+ failures.push(`${agentsMdUpdate.path}: ${error.message}`);
24704
26174
  }
24705
26175
  }
24706
26176
  let removedAgentRoles = 0;
24707
26177
  for (const path of agentRoleFiles) {
24708
26178
  try {
24709
- await rm(path, { force: true });
26179
+ if (!await revalidate(path)) continue;
26180
+ const snapshot = canonicalPaths.get(path);
26181
+ if (!snapshot) throw new Error("missing canonical preflight");
26182
+ await removeOwnedFileViaQuarantine(snapshot);
24710
26183
  removedAgentRoles++;
24711
26184
  } catch (e) {
24712
26185
  failures.push(`${path}: ${e.message}`);
@@ -24716,7 +26189,17 @@ async function runUnifiedUninstall(home, dryRun) {
24716
26189
  let removedSkills = 0;
24717
26190
  for (const dir of skillDirs) {
24718
26191
  try {
24719
- await rm(dir, { recursive: true, force: true });
26192
+ const snapshot = canonicalPaths.get(dir);
26193
+ const expectedHash = ownedSkills.expectedHashes.get(dir);
26194
+ if (!snapshot || !expectedHash) throw new Error("missing owned skill preflight");
26195
+ await removeOwnedDirectoryViaQuarantine(snapshot, {
26196
+ verify: async (quarantinePath) => {
26197
+ const body = await readFile(join(quarantinePath, "SKILL.md"), "utf8");
26198
+ if (sha256Of(body) !== expectedHash) {
26199
+ throw new Error("installed skill differs from the ownership ledger; repair first");
26200
+ }
26201
+ }
26202
+ });
24720
26203
  removedSkills++;
24721
26204
  } catch (e) {
24722
26205
  failures.push(`${dir}: ${e.message}`);
@@ -24724,27 +26207,40 @@ async function runUnifiedUninstall(home, dryRun) {
24724
26207
  }
24725
26208
  let removedSettings = false;
24726
26209
  let removedHooks = 0;
24727
- if (settingsPath !== null && (hasSettingsChanges || staleHooks > 0)) {
26210
+ let settingsRemovalSucceeded = false;
26211
+ let settingsWriteFailed = false;
26212
+ if (settingsRemovalPath !== null) {
24728
26213
  try {
24729
- const r = await removeSettingsFootprint(settingsPath);
24730
- removedSettings = r.envRemoved;
24731
- removedHooks = r.hooksRemoved;
26214
+ if (await revalidate(settingsRemovalPath)) {
26215
+ const r = await removeSettingsFootprint(settingsRemovalPath, context);
26216
+ removedSettings = r.envRemoved;
26217
+ removedHooks = r.hooksRemoved;
26218
+ settingsRemovalSucceeded = true;
26219
+ } else {
26220
+ settingsWriteFailed = true;
26221
+ }
24732
26222
  } catch (e) {
24733
- failures.push(`${settingsPath}: ${e.message}`);
26223
+ settingsWriteFailed = true;
26224
+ failures.push(`${settingsRemovalPath}: ${e.message}`);
24734
26225
  }
24735
26226
  }
24736
- const normalizedRoot = resolve(harnessedRoot);
24737
- const platformHome = platform.homeDir;
24738
- if (!normalizedRoot.startsWith(resolve(platformHome) + sep)) {
24739
- console.error(`error: state dir ${harnessedRoot} is not under ${platformHome} \u2014 refusing`);
24740
- process.exit(1);
24741
- }
24742
- let removedStateDir = false;
24743
- try {
24744
- await rm(harnessedRoot, { recursive: true, force: true });
24745
- removedStateDir = true;
24746
- } catch (e) {
24747
- failures.push(`${harnessedRoot}: ${e.message}`);
26227
+ const receiptPath = settingsOwnershipReceiptPath(context);
26228
+ let removedStateEntries = 0;
26229
+ for (const path of stateEntries) {
26230
+ if (settingsRemovalSucceeded && path === receiptPath) continue;
26231
+ if (failures.length > 0 || settingsWriteFailed && path === receiptPath) continue;
26232
+ try {
26233
+ const snapshot = canonicalPaths.get(path);
26234
+ if (!snapshot) throw new Error("missing canonical preflight");
26235
+ if (snapshot.isDirectory) await removeOwnedDirectoryViaQuarantine(snapshot);
26236
+ else {
26237
+ if (!await revalidate(path)) continue;
26238
+ await removeOwnedFileViaQuarantine(snapshot);
26239
+ }
26240
+ removedStateEntries++;
26241
+ } catch (e) {
26242
+ failures.push(`${path}: ${e.message}`);
26243
+ }
24748
26244
  }
24749
26245
  if (removedCommands > 0)
24750
26246
  console.log(t("uninstall.unified.removed_commands", { count: removedCommands }));
@@ -24754,10 +26250,12 @@ async function runUnifiedUninstall(home, dryRun) {
24754
26250
  console.log(t("uninstall.unified.removed_skills", { count: removedSkills }));
24755
26251
  if (removedSettings) console.log(t("uninstall.unified.removed_settings"));
24756
26252
  if (removedHooks > 0) console.log(t("uninstall.unified.removed_hooks", { count: removedHooks }));
24757
- if (removedStateDir) console.log(t("uninstall.unified.removed_state_dir"));
26253
+ if (removedStateEntries > 0) console.log(t("uninstall.unified.removed_state_dir"));
24758
26254
  if (failures.length > 0) {
24759
26255
  console.error(t("uninstall.unified.partial_failure", { count: failures.length }));
24760
26256
  for (const f of failures) console.error(` ${f}`);
26257
+ printCliRemovalHint();
26258
+ process.exit(1);
24761
26259
  }
24762
26260
  console.log(t("uninstall.unified.complete"));
24763
26261
  printCliRemovalHint();
@@ -24766,26 +26264,34 @@ async function runUnifiedUninstall(home, dryRun) {
24766
26264
  function registerUninstall(program2) {
24767
26265
  program2.command("uninstall [name]").description(
24768
26266
  "Uninstall an upstream by name, or remove all harnessed own files when no name given"
24769
- ).option("--dry-run", "preview only \u2014 do not delete files").action(async (name, raw) => {
26267
+ ).option("--dry-run", "preview only \u2014 do not delete files").option("--platform <id>", "target harness platform (claude | codex)").action(async (name, raw) => {
24770
26268
  const dryRun = raw.dryRun === true;
24771
- if (!name) {
24772
- await runUnifiedUninstall(homedir(), dryRun);
24773
- return;
26269
+ if (raw.platform !== void 0 && !HOST_IDS.includes(raw.platform)) {
26270
+ console.error(
26271
+ `--platform: unknown id '${raw.platform}' (expected one of: ${HOST_IDS.join(" | ")})`
26272
+ );
26273
+ process.exit(1);
24774
26274
  }
24775
26275
  let context;
24776
26276
  try {
24777
- context = captureHostInstallContext();
26277
+ context = captureHostInstallContext(
26278
+ raw.platform === void 0 ? {} : { hostId: raw.platform }
26279
+ );
24778
26280
  } catch (error) {
24779
26281
  console.error(`error: invalid uninstall context: ${error.message}`);
24780
26282
  process.exit(1);
24781
26283
  }
26284
+ if (!name) {
26285
+ await runUnifiedUninstall(context, dryRun);
26286
+ return;
26287
+ }
24782
26288
  const { resolveAlias: resolveAlias2 } = await Promise.resolve().then(() => (init_aliases(), aliases_exports));
24783
26289
  const resolvedName = resolveAlias2(name) ?? name;
24784
26290
  checkPathSafe(resolvedName);
24785
26291
  let yamlSrc;
24786
26292
  let chosenPath;
24787
26293
  for (const dir of ["tools", "skill-packs", "optional"]) {
24788
- const candidate = resolve(getAssetsRoot(), `manifests/${dir}/${resolvedName}.yaml`);
26294
+ const candidate = join(getAssetsRoot(), `manifests/${dir}/${resolvedName}.yaml`);
24789
26295
  try {
24790
26296
  yamlSrc = await readFile(candidate, "utf8");
24791
26297
  chosenPath = candidate;
@@ -24852,16 +26358,19 @@ var init_uninstall = __esm({
24852
26358
  init_i18n();
24853
26359
  init_componentPlan();
24854
26360
  init_harnessedHookTeardown();
26361
+ init_quarantineDelete();
24855
26362
  init_path_guard();
24856
26363
  init_validate();
24857
26364
  init_assetsRoot();
24858
- init_harnessedRoot();
24859
26365
  init_hostInstallContext();
24860
26366
  init_platform();
24861
26367
  init_runtime();
24862
26368
  init_uninstallers();
24863
- init_scan_nested();
24864
26369
  init_generateCommands();
26370
+ init_settingsOwnershipReceipt();
26371
+ init_settingsTransactionLock();
26372
+ init_settingsWriter();
26373
+ init_skillIntegrity();
24865
26374
  }
24866
26375
  });
24867
26376
 
@@ -25217,9 +26726,19 @@ var { registerUpdate: registerUpdate2 } = await Promise.resolve().then(() => (in
25217
26726
  var { registerWorkflows: registerWorkflows2 } = await Promise.resolve().then(() => (init_workflows(), workflows_exports));
25218
26727
  var { setLocale: setLocale2, wireMessagesDir: wireMessagesDir2 } = await Promise.resolve().then(() => (init_i18n(), i18n_exports));
25219
26728
  var { getAssetsRoot: getAssetsRoot2 } = await Promise.resolve().then(() => (init_assetsRoot(), assetsRoot_exports));
26729
+ var { captureHostInstallContext: captureHostInstallContext2 } = await Promise.resolve().then(() => (init_hostInstallContext(), hostInstallContext_exports));
25220
26730
  var { migrateLegacyHarnessedRoot: migrateLegacyHarnessedRoot2 } = await Promise.resolve().then(() => (init_harnessedRoot(), harnessedRoot_exports));
25221
26731
  wireMessagesDir2(() => join(getAssetsRoot2(), "messages"));
25222
26732
  var updateInvocation = entryArgs.includes("update");
26733
+ function explicitPlatform(args) {
26734
+ for (let index = 0; index < args.length; index++) {
26735
+ const arg = args[index];
26736
+ if (arg === "--") return void 0;
26737
+ if (arg === "--platform") return args[index + 1];
26738
+ if (arg?.startsWith("--platform=")) return arg.slice("--platform=".length);
26739
+ }
26740
+ return void 0;
26741
+ }
25223
26742
  var argv = process.argv;
25224
26743
  for (let i = 2; i < argv.length; i++) {
25225
26744
  const a = argv[i];
@@ -25246,7 +26765,8 @@ process.on("uncaughtException", (err2) => {
25246
26765
  fatal(err2 instanceof Error ? err2.message : String(err2));
25247
26766
  });
25248
26767
  if (!updateInvocation) {
25249
- migrateLegacyHarnessedRoot2();
26768
+ const hostId = explicitPlatform(entryArgs);
26769
+ migrateLegacyHarnessedRoot2(captureHostInstallContext2(hostId === void 0 ? {} : { hostId }));
25250
26770
  await migrateRepoKeyCase2().catch((e) => {
25251
26771
  console.error(
25252
26772
  `[harnessed] WARN: repo-key case migration deferred: ${e instanceof Error ? e.message : String(e)}`