harnessed 5.0.6 → 5.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.mjs CHANGED
@@ -6,7 +6,7 @@ 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';
8
8
  import lockfile from 'proper-lockfile';
9
- import { createHash, randomBytes, timingSafeEqual, verify, createPublicKey } from 'crypto';
9
+ import { createHash, randomBytes, timingSafeEqual, verify, createPublicKey, randomUUID } from 'crypto';
10
10
  import { pathToFileURL, fileURLToPath } from 'url';
11
11
  import { LineCounter, parseDocument, parse, isSeq, isAlias, isScalar, stringify, isMap } from 'yaml';
12
12
  import { Ajv } from 'ajv';
@@ -40,7 +40,7 @@ var init_package = __esm({
40
40
  "package.json"() {
41
41
  package_default = {
42
42
  name: "harnessed",
43
- version: "5.0.6",
43
+ version: "5.0.8",
44
44
  description: "AI coding harness package manager + composition orchestrator",
45
45
  type: "module",
46
46
  license: "Apache-2.0",
@@ -1430,12 +1430,12 @@ var init_ledger = __esm({
1430
1430
  function deriveNext(snapshot) {
1431
1431
  const pendingSub = nextPending(snapshot.subProgress);
1432
1432
  if (pendingSub !== null) return { kind: "sub", sub: pendingSub };
1433
- const failed = snapshot.subProgress.find((e) => e.status === "failed" && (e.fail_count ?? 0) > 0);
1434
- if (failed) {
1433
+ const failed2 = snapshot.subProgress.find((e) => e.status === "failed" && (e.fail_count ?? 0) > 0);
1434
+ if (failed2) {
1435
1435
  return {
1436
1436
  kind: "blocked",
1437
- unit: failed.sub,
1438
- reason: `sub '${failed.sub}' failed ${failed.fail_count}x \u2014 resolve before advancing`
1437
+ unit: failed2.sub,
1438
+ reason: `sub '${failed2.sub}' failed ${failed2.fail_count}x \u2014 resolve before advancing`
1439
1439
  };
1440
1440
  }
1441
1441
  const firstIncomplete = snapshot.phases.find((p8) => !p8.complete);
@@ -2233,12 +2233,12 @@ function stripAgentsMdSection(body) {
2233
2233
  function insertAgentsMdSection(body, section) {
2234
2234
  const base = stripAgentsMdSection(body);
2235
2235
  if (section === "") return base;
2236
- const sep5 = base === "" || base.endsWith("\n\n") ? "" : base.endsWith("\n") ? "\n" : "\n\n";
2237
- return `${base}${sep5}${section}`;
2236
+ const sep6 = base === "" || base.endsWith("\n\n") ? "" : base.endsWith("\n") ? "\n" : "\n\n";
2237
+ return `${base}${sep6}${section}`;
2238
2238
  }
2239
2239
  async function resolveCommandNames(workflowsDir) {
2240
- const { readdir: readdir27 } = await import('fs/promises');
2241
- const entries = await readdir27(workflowsDir);
2240
+ const { readdir: readdir28 } = await import('fs/promises');
2241
+ const entries = await readdir28(workflowsDir);
2242
2242
  const { workflows } = await scanWorkflowsNested(workflowsDir, entries);
2243
2243
  const prompts = await loadRolePrompts(workflowsDir);
2244
2244
  return workflows.map((w) => w.name).filter((n) => prompts[n] !== void 0).sort();
@@ -2645,7 +2645,7 @@ var init_installMethods = __esm({
2645
2645
  Type.Union([...branches]);
2646
2646
  }
2647
2647
  });
2648
- var TypeEnum, ComponentType, Verify, Uninstall, Stability, FallbackAction, UpstreamHealth, Platform, Signature, Category, InstallType, DecisionRules, Phase, Triggers, ProvidedUnit, HarnessOverride, HarnessOverrides, SpecSchema;
2648
+ var TypeEnum, ComponentType, Verify, Uninstall, Stability, FallbackAction, UpstreamHealth, Platform, Signature, Category, InstallType, DecisionRules, Phase, Triggers, ProvidedUnit, HarnessOverride, HarnessOverrides, OwnershipRoot, OwnershipSelector, DirectoryOwnershipResource, FileOwnershipResource, Ownership, SpecSchema;
2649
2649
  var init_spec = __esm({
2650
2650
  "src/manifest/schema/spec.ts"() {
2651
2651
  init_installMethods();
@@ -2783,6 +2783,57 @@ var init_spec = __esm({
2783
2783
  },
2784
2784
  { additionalProperties: false }
2785
2785
  );
2786
+ OwnershipRoot = Type.Union([
2787
+ Type.Literal("platform-skills"),
2788
+ Type.Literal("native-home"),
2789
+ Type.Literal("host-agents"),
2790
+ Type.Literal("host-commands")
2791
+ ]);
2792
+ OwnershipSelector = Type.Union([
2793
+ Type.Object(
2794
+ { names: Type.Array(Type.String({ minLength: 1 }), { minItems: 1, uniqueItems: true }) },
2795
+ { additionalProperties: false }
2796
+ ),
2797
+ Type.Object({ prefix: Type.String({ minLength: 1 }) }, { additionalProperties: false })
2798
+ ]);
2799
+ DirectoryOwnershipResource = Type.Object(
2800
+ {
2801
+ root: OwnershipRoot,
2802
+ kind: Type.Literal("directory"),
2803
+ selector: OwnershipSelector,
2804
+ marker: Type.Object(
2805
+ {
2806
+ path: Type.String({
2807
+ minLength: 1,
2808
+ pattern: "^(?!/)(?![A-Za-z]:/)(?!.*//)(?!.*(?:^|/)(?:\\.|\\.\\.)(?:/|$))[^\\\\]+$"
2809
+ }),
2810
+ contains: Type.String({ minLength: 1 })
2811
+ },
2812
+ { additionalProperties: false }
2813
+ )
2814
+ },
2815
+ { additionalProperties: false }
2816
+ );
2817
+ FileOwnershipResource = Type.Object(
2818
+ {
2819
+ root: OwnershipRoot,
2820
+ kind: Type.Literal("file"),
2821
+ selector: OwnershipSelector,
2822
+ marker: Type.Object(
2823
+ { contains: Type.String({ minLength: 1 }) },
2824
+ { additionalProperties: false }
2825
+ )
2826
+ },
2827
+ { additionalProperties: false }
2828
+ );
2829
+ Ownership = Type.Object(
2830
+ {
2831
+ resources: Type.Array(Type.Union([DirectoryOwnershipResource, FileOwnershipResource]), {
2832
+ minItems: 1
2833
+ })
2834
+ },
2835
+ { additionalProperties: false }
2836
+ );
2786
2837
  SpecSchema = Type.Object(
2787
2838
  {
2788
2839
  type: TypeEnum,
@@ -2812,7 +2863,8 @@ var init_spec = __esm({
2812
2863
  // ADR 0010 errata (phase 2.1 T1.3) — bundle-install `provides` field.
2813
2864
  provides: Type.Optional(Type.Array(ProvidedUnit, { minItems: 2, uniqueItems: true })),
2814
2865
  // Per-harness install/verify/uninstall interfaces (codex only for now).
2815
- harness_overrides: Type.Optional(HarnessOverrides)
2866
+ harness_overrides: Type.Optional(HarnessOverrides),
2867
+ ownership: Type.Optional(Ownership)
2816
2868
  },
2817
2869
  { additionalProperties: false }
2818
2870
  );
@@ -3382,9 +3434,9 @@ function redactRecord(r) {
3382
3434
  }
3383
3435
  function renderHumanTable(records) {
3384
3436
  const header = `${"ts".padEnd(19)} | ${"phase".padEnd(6)} | ${"category".padEnd(11)} | ${"matched_rule_id".padEnd(20)} | outcome`;
3385
- const sep5 = `${"-".repeat(19)}-+-${"-".repeat(6)}-+-${"-".repeat(11)}-+-${"-".repeat(20)}-+--------`;
3437
+ const sep6 = `${"-".repeat(19)}-+-${"-".repeat(6)}-+-${"-".repeat(11)}-+-${"-".repeat(20)}-+--------`;
3386
3438
  console.log(header);
3387
- console.log(sep5);
3439
+ console.log(sep6);
3388
3440
  for (const r of records) {
3389
3441
  const ts = r.ts.slice(0, 19);
3390
3442
  const phase = r.phase.padEnd(6);
@@ -3394,7 +3446,7 @@ function renderHumanTable(records) {
3394
3446
  }
3395
3447
  }
3396
3448
  function pipeToJq(filterExpr, lines) {
3397
- return new Promise((resolve39, reject) => {
3449
+ return new Promise((resolve40, reject) => {
3398
3450
  const child = spawn("jq", [filterExpr], {
3399
3451
  stdio: ["pipe", "inherit", "inherit"],
3400
3452
  windowsHide: true
@@ -3403,12 +3455,12 @@ function pipeToJq(filterExpr, lines) {
3403
3455
  const e = err2;
3404
3456
  if (e.code === "ENOENT") {
3405
3457
  console.error(t("audit_log.jq_missing"));
3406
- resolve39(1);
3458
+ resolve40(1);
3407
3459
  } else {
3408
3460
  reject(err2);
3409
3461
  }
3410
3462
  });
3411
- child.on("close", (code2) => resolve39(code2 ?? 0));
3463
+ child.on("close", (code2) => resolve40(code2 ?? 0));
3412
3464
  child.stdin.on("error", (err2) => {
3413
3465
  if (err2.code !== "EPIPE") reject(err2);
3414
3466
  });
@@ -4130,7 +4182,7 @@ function withHostInstallEnv(env, hostContext) {
4130
4182
  return { ...result, ...pins };
4131
4183
  }
4132
4184
  function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
4133
- return new Promise((resolve39) => {
4185
+ return new Promise((resolve40) => {
4134
4186
  const isWin = (hostContext?.os ?? process.platform) === "win32";
4135
4187
  const envOpts = hostContext ? { env: withHostInstallEnv(process.env, hostContext) } : {};
4136
4188
  const stdio = ["ignore", "pipe", "pipe"];
@@ -4158,17 +4210,17 @@ function runHarnessArgs(bin, args, cwd, timeoutMs = 15e3, hostContext) {
4158
4210
  });
4159
4211
  const timer = setTimeout(() => {
4160
4212
  killProcessTree(child);
4161
- resolve39({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
4213
+ resolve40({ exitCode: -1, stdout: stdout2, stderr: `${stderr}[timeout after ${timeoutMs}ms]` });
4162
4214
  }, timeoutMs);
4163
4215
  child.on("error", (e) => {
4164
4216
  clearTimeout(timer);
4165
4217
  const enoent = e.code === "ENOENT";
4166
4218
  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;
4167
- resolve39({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
4219
+ resolve40({ exitCode: -1, stdout: stdout2, stderr: `${stderr}${msg}` });
4168
4220
  });
4169
4221
  child.on("close", (code2) => {
4170
4222
  clearTimeout(timer);
4171
- resolve39({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
4223
+ resolve40({ exitCode: code2 ?? -1, stdout: stdout2, stderr });
4172
4224
  });
4173
4225
  });
4174
4226
  }
@@ -5318,11 +5370,11 @@ function isComplete(output) {
5318
5370
  if (succeeded) return true;
5319
5371
  return extractPromise(env.text ?? env.result ?? "") === "COMPLETE";
5320
5372
  }
5321
- async function ralphLoopWrap(spawn9, maxIter) {
5373
+ async function ralphLoopWrap(spawn10, maxIter) {
5322
5374
  let last = "";
5323
5375
  let sessionId;
5324
5376
  for (let i = 0; i < maxIter; i++) {
5325
- last = await spawn9(sessionId, (id) => {
5377
+ last = await spawn10(sessionId, (id) => {
5326
5378
  sessionId = id;
5327
5379
  });
5328
5380
  if (isComplete(last)) return last;
@@ -8906,8 +8958,8 @@ function commandScriptPath2(raw, id) {
8906
8958
  }
8907
8959
  function isTrustedScriptPath(path, id) {
8908
8960
  const file = `harnessed-${id}.mjs`;
8909
- const relative10 = path.replace(/^\.\//, "");
8910
- if (relative10 === `bin/${file}`) return true;
8961
+ const relative11 = path.replace(/^\.\//, "");
8962
+ if (relative11 === `bin/${file}`) return true;
8911
8963
  if (!ABSOLUTE_RE2.test(path)) return false;
8912
8964
  const resolved = `${CAPTURED_ASSETS_ROOT}/bin/${file}`;
8913
8965
  if (pathKey(path) === pathKey(resolved)) return true;
@@ -8939,6 +8991,62 @@ function harnessedHookIdentity(raw) {
8939
8991
  }
8940
8992
  return null;
8941
8993
  }
8994
+ function commandScriptToken(raw) {
8995
+ const match = raw.match(/^\s*(?:node|bun)\s+(?:"([^"]+)"|'([^']+)'|(\S+))(?:\s|$)/);
8996
+ return match?.[1] ?? match?.[2] ?? match?.[3] ?? null;
8997
+ }
8998
+ function commandTransportSubcommand(raw) {
8999
+ const match = raw.match(/^\s*(?:"([^"]+)"|'([^']+)'|(\S+))\s+(\S+)/);
9000
+ const sub = match?.[4];
9001
+ return sub && COMPILED_HOOK_IDENTITIES.includes(sub) ? sub : null;
9002
+ }
9003
+ function escapeRegExp(value) {
9004
+ return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
9005
+ }
9006
+ function isTrustedScriptFile(path, rel, assetsRoot) {
9007
+ const normalized2 = path.replace(/\\/g, "/");
9008
+ const relNormalized = rel.replace(/\\/g, "/");
9009
+ if (normalized2 === relNormalized) return true;
9010
+ const root = assetsRoot.replace(/\\/g, "/").replace(/\/+$/, "");
9011
+ const resolved = `${root}/${relNormalized}`;
9012
+ if (pathKey(normalized2) === pathKey(resolved)) return true;
9013
+ const versioned = new RegExp(`^(.+/assets/)[^/]+(/${escapeRegExp(relNormalized)})$`);
9014
+ const candidate = pathKey(normalized2).match(versioned);
9015
+ const captured = pathKey(resolved).match(versioned);
9016
+ return candidate !== null && captured !== null && candidate[1] === captured[1] && candidate[2] === captured[2];
9017
+ }
9018
+ function referenceScriptToken(hookCommand) {
9019
+ const script = commandScriptToken(hookCommand);
9020
+ if (script) {
9021
+ const normalized2 = script.replace(/\\/g, "/");
9022
+ return ABSOLUTE_RE2.test(normalized2) ? null : normalized2;
9023
+ }
9024
+ const sub = commandTransportSubcommand(hookCommand);
9025
+ return sub ? `bin/harnessed-${sub}.mjs` : null;
9026
+ }
9027
+ function isRegistrationOf(recorded, reference, assetsRoot) {
9028
+ const script = commandScriptToken(recorded);
9029
+ if (script) return isTrustedScriptFile(script, reference, assetsRoot);
9030
+ const sub = commandTransportSubcommand(recorded);
9031
+ if (!sub) return false;
9032
+ if (`bin/harnessed-${sub}.mjs` !== reference) return false;
9033
+ return harnessedHookIdentity(recorded) === sub;
9034
+ }
9035
+ function harnessedHookRegistrations(hooks, hookCommand, deps) {
9036
+ const reference = referenceScriptToken(hookCommand);
9037
+ if (!reference) return [];
9038
+ const assetsRoot = (deps?.assetsRoot ?? getAssetsRoot)();
9039
+ const out = [];
9040
+ for (const [event, arr] of Object.entries(hooks)) {
9041
+ if (!Array.isArray(arr)) continue;
9042
+ for (const entry of arr) {
9043
+ for (const command of entryCommands(entry)) {
9044
+ if (isRegistrationOf(command, reference, assetsRoot)) out.push({ event, command });
9045
+ }
9046
+ }
9047
+ }
9048
+ return out;
9049
+ }
8942
9050
  function harnessedHookScriptPath(raw) {
8943
9051
  const qMjs = raw.match(new RegExp(`"([^"]*harnessed-(?:${ID_ALT})\\.mjs)"`)) ?? raw.match(new RegExp(`'([^']*harnessed-(?:${ID_ALT})\\.mjs)'`));
8944
9052
  if (qMjs?.[1]) return qMjs[1];
@@ -9064,19 +9172,23 @@ function checkStaleHooks(deps) {
9064
9172
  return { name: NAME, status: "pass", message: "no orphaned harnessed hooks" };
9065
9173
  }
9066
9174
  const list = stale.map((s) => `${s.event} \u2192 ${s.path}`).join("; ");
9175
+ const versioned = stale.filter((s) => VERSIONED_ASSETS_RE.test(s.path.replace(/\\/g, "/")));
9176
+ const orphaned = stale.filter((s) => !VERSIONED_ASSETS_RE.test(s.path.replace(/\\/g, "/")));
9177
+ const fix = versioned.length > 0 ? `run 'harnessed setup' (or 'harnessed update') to re-register the stale harnessed hook(s) to the current version, or delete the matching Stop/UserPromptSubmit entries from ${settingsPath}${orphaned.length > 0 ? " \u2014 entries whose package is gone can also be removed with 'harnessed uninstall'" : ""}` : `run 'harnessed uninstall' to strip them, or delete the matching Stop/UserPromptSubmit entries from ${settingsPath}`;
9067
9178
  return {
9068
9179
  name: NAME,
9069
9180
  status: "warn",
9070
9181
  message: `${stale.length} harnessed hook(s) point at a missing/unresolvable script \u2014 Claude Code errors MODULE_NOT_FOUND every prompt (${list})`,
9071
- fix: `run 'harnessed uninstall' to strip them, or delete the matching Stop/UserPromptSubmit entries from ${settingsPath}`
9182
+ fix
9072
9183
  };
9073
9184
  }
9074
- var NAME;
9185
+ var NAME, VERSIONED_ASSETS_RE;
9075
9186
  var init_check_stale_hooks = __esm({
9076
9187
  "src/cli/lib/check-stale-hooks.ts"() {
9077
9188
  init_harnessedHookTeardown();
9078
9189
  init_platform();
9079
9190
  NAME = "stale hooks";
9191
+ VERSIONED_ASSETS_RE = /\/assets\/[^/]+\//;
9080
9192
  }
9081
9193
  });
9082
9194
 
@@ -9643,7 +9755,7 @@ async function withAppServer(deps, body) {
9643
9755
  const call = (method, params) => {
9644
9756
  if (closed) return Promise.reject(closed);
9645
9757
  const id = nextId++;
9646
- return new Promise((resolve39, reject) => {
9758
+ return new Promise((resolve40, reject) => {
9647
9759
  const timer = setTimeout(() => {
9648
9760
  pending.delete(id);
9649
9761
  reject(new RpcError("timeout", `${method} timed out after ${timeoutMs}ms`));
@@ -9651,7 +9763,7 @@ async function withAppServer(deps, body) {
9651
9763
  pending.set(id, {
9652
9764
  resolve: (v) => {
9653
9765
  clearTimeout(timer);
9654
- resolve39(v);
9766
+ resolve40(v);
9655
9767
  },
9656
9768
  reject: (e) => {
9657
9769
  clearTimeout(timer);
@@ -10577,25 +10689,25 @@ var init_discipline = __esm({
10577
10689
  );
10578
10690
  }
10579
10691
  });
10580
- async function loadDiscipline(basename9, packageRoot) {
10581
- const cached = _cache.get(basename9);
10692
+ async function loadDiscipline(basename10, packageRoot) {
10693
+ const cached = _cache.get(basename10);
10582
10694
  if (cached) return cached;
10583
- const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename9}.yaml`);
10695
+ const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename10}.yaml`);
10584
10696
  const raw = await readFile(yamlPath, "utf8");
10585
10697
  const parsedRaw = parse(raw);
10586
10698
  if (!Value.Check(Discipline, parsedRaw)) {
10587
10699
  const errors = [...Value.Errors(Discipline, parsedRaw)].slice(0, 3).map((e) => `${e.path} ${e.message}`).join("; ");
10588
- throw new Error(`Invalid discipline file ${basename9}.yaml: ${errors}`);
10700
+ throw new Error(`Invalid discipline file ${basename10}.yaml: ${errors}`);
10589
10701
  }
10590
10702
  const parsed = parsedRaw;
10591
- _cache.set(basename9, parsed);
10703
+ _cache.set(basename10, parsed);
10592
10704
  return parsed;
10593
10705
  }
10594
10706
  async function loadAllApplied(disciplines_applied, packageRoot) {
10595
10707
  const applied = disciplines_applied && disciplines_applied.length > 0 ? disciplines_applied : DEFAULT_APPLIED;
10596
10708
  const out = /* @__PURE__ */ new Map();
10597
- for (const basename9 of applied) {
10598
- out.set(basename9, await loadDiscipline(basename9, packageRoot));
10709
+ for (const basename10 of applied) {
10710
+ out.set(basename10, await loadDiscipline(basename10, packageRoot));
10599
10711
  }
10600
10712
  return out;
10601
10713
  }
@@ -11117,7 +11229,7 @@ function realSpawn(req) {
11117
11229
  };
11118
11230
  }
11119
11231
  function runOnce(req, spawnFn, timeoutMs, onThreadId) {
11120
- return new Promise((resolve39, reject) => {
11232
+ return new Promise((resolve40, reject) => {
11121
11233
  const events = [];
11122
11234
  let garbageLines = 0;
11123
11235
  let stderr = "";
@@ -11138,7 +11250,7 @@ function runOnce(req, spawnFn, timeoutMs, onThreadId) {
11138
11250
  if (settled || !exited || openStreams > 0) return;
11139
11251
  settled = true;
11140
11252
  clearTimeout(timer);
11141
- resolve39({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
11253
+ resolve40({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
11142
11254
  };
11143
11255
  const fail2 = (err2) => {
11144
11256
  if (settled) return;
@@ -11433,11 +11545,11 @@ function resolveSpawnHost() {
11433
11545
  async function dispatchSpawn(def, opts, deps = {}) {
11434
11546
  const host = (deps.hostId ?? resolveSpawnHost)();
11435
11547
  if (host === "codex") {
11436
- const spawn10 = deps.codexExecSpawn ?? (await Promise.resolve().then(() => (init_codexExecSpawn(), codexExecSpawn_exports))).codexExecSpawn;
11437
- return spawn10(def, { expertName: opts.expertName });
11548
+ const spawn11 = deps.codexExecSpawn ?? (await Promise.resolve().then(() => (init_codexExecSpawn(), codexExecSpawn_exports))).codexExecSpawn;
11549
+ return spawn11(def, { expertName: opts.expertName });
11438
11550
  }
11439
- const spawn9 = deps.sdkSpawn ?? (await Promise.resolve().then(() => (init_sdkSpawn(), sdkSpawn_exports))).sdkSpawn;
11440
- return spawn9(def, opts);
11551
+ const spawn10 = deps.sdkSpawn ?? (await Promise.resolve().then(() => (init_sdkSpawn(), sdkSpawn_exports))).sdkSpawn;
11552
+ return spawn10(def, opts);
11441
11553
  }
11442
11554
  var init_spawnDispatch = __esm({
11443
11555
  "src/workflow/lib/spawnDispatch.ts"() {
@@ -13938,6 +14050,7 @@ var gc_exports = {};
13938
14050
  __export(gc_exports, {
13939
14051
  gcCompiledArtifacts: () => gcCompiledArtifacts,
13940
14052
  gcLedger: () => gcLedger,
14053
+ referencedAssetVersions: () => referencedAssetVersions,
13941
14054
  registerGc: () => registerGc
13942
14055
  });
13943
14056
  function byVersion(a, b) {
@@ -13947,16 +14060,54 @@ function byVersion(a, b) {
13947
14060
  if (c === "current") return 0;
13948
14061
  return a.localeCompare(b);
13949
14062
  }
14063
+ async function referencedAssetVersions(settingsPath) {
14064
+ const versions = /* @__PURE__ */ new Set();
14065
+ if (!settingsPath) return versions;
14066
+ let raw;
14067
+ try {
14068
+ raw = await readFile(settingsPath, "utf8");
14069
+ } catch {
14070
+ return versions;
14071
+ }
14072
+ let parsed;
14073
+ try {
14074
+ parsed = JSON.parse(raw);
14075
+ } catch {
14076
+ return versions;
14077
+ }
14078
+ const hooks = parsed.hooks;
14079
+ if (!hooks || typeof hooks !== "object") return versions;
14080
+ for (const arr of Object.values(hooks)) {
14081
+ if (!Array.isArray(arr)) continue;
14082
+ for (const entry of arr) {
14083
+ for (const command of entryCommands(entry)) {
14084
+ const match = command.replace(/\\/g, "/").match(REFERENCED_ASSETS_RE);
14085
+ if (match?.[1]) versions.add(match[1]);
14086
+ }
14087
+ }
14088
+ }
14089
+ return versions;
14090
+ }
14091
+ function hostSettingsPath() {
14092
+ try {
14093
+ return getSettingsPath();
14094
+ } catch {
14095
+ return null;
14096
+ }
14097
+ }
13950
14098
  async function gcCompiledArtifacts(opts) {
13951
14099
  const removed = [];
13952
14100
  const kept = [];
13953
14101
  const keep = new Set(opts.keepVersions);
14102
+ const referenced = await referencedAssetVersions(
14103
+ opts.settingsPath === void 0 ? hostSettingsPath() : opts.settingsPath
14104
+ );
13954
14105
  try {
13955
14106
  const assetsDir = join(opts.stateRoot, "assets");
13956
14107
  for (const e of await readdir(assetsDir, { withFileTypes: true })) {
13957
14108
  if (!e.isDirectory()) continue;
13958
14109
  const p8 = join(assetsDir, e.name);
13959
- if (keep.has(e.name)) {
14110
+ if (keep.has(e.name) || referenced.has(e.name)) {
13960
14111
  kept.push(p8);
13961
14112
  continue;
13962
14113
  }
@@ -14112,14 +14263,17 @@ ${t("gc.invalid_duration.fix")}`
14112
14263
  }
14113
14264
  });
14114
14265
  }
14115
- var DURATION_RE;
14266
+ var REFERENCED_ASSETS_RE, DURATION_RE;
14116
14267
  var init_gc = __esm({
14117
14268
  "src/cli/gc.ts"() {
14118
14269
  init_package();
14119
14270
  init_pruneSlots();
14120
14271
  init_i18n();
14121
14272
  init_backup();
14273
+ init_hookEntry();
14274
+ init_platform();
14122
14275
  init_version_check();
14276
+ REFERENCED_ASSETS_RE = /\/assets\/([^/]+)\/(?:bin|scripts)\/[^\s"']*\.mjs/;
14123
14277
  DURATION_RE = /^(\d+)([dhmw])$/;
14124
14278
  }
14125
14279
  });
@@ -15034,13 +15188,15 @@ async function prepareHookSettings(ctx, settingsPath) {
15034
15188
  }
15035
15189
  };
15036
15190
  }
15037
- const ours = arr.filter(
15038
- (entry) => entryMatchesRegistration(entry, install.hook_command, resolvedCmd, marker)
15191
+ const firstParty = new Set(
15192
+ harnessedHookRegistrations({ [install.hook_event]: arr }, install.hook_command, {
15193
+ assetsRoot: cmdDeps.assetsRoot
15194
+ }).map((registration) => registration.command)
15039
15195
  );
15196
+ const isOurs = (entry) => entryMatchesRegistration(entry, install.hook_command, resolvedCmd, marker) || entryCommands(entry).some((command) => firstParty.has(command));
15197
+ const ours = arr.filter(isOurs);
15040
15198
  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
- );
15199
+ const others = arr.filter((entry) => !isOurs(entry));
15044
15200
  settings.hooks[install.hook_event] = [
15045
15201
  ...others,
15046
15202
  desiredHookEntry(install.hook_matcher, resolvedCmd)
@@ -15068,6 +15224,7 @@ var init_ccHookAdd2 = __esm({
15068
15224
  init_confirm();
15069
15225
  init_diff();
15070
15226
  init_err();
15227
+ init_harnessedHookTeardown();
15071
15228
  init_hookEntry();
15072
15229
  init_preflight();
15073
15230
  init_state2();
@@ -15510,10 +15667,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15510
15667
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
15511
15668
  stderr += chunk;
15512
15669
  });
15513
- return await new Promise((resolve39) => {
15670
+ return await new Promise((resolve40) => {
15514
15671
  const timer = setTimeout(() => {
15515
15672
  killProcessTree(child);
15516
- resolve39({
15673
+ resolve40({
15517
15674
  ok: false,
15518
15675
  phase: "spawn",
15519
15676
  error: {
@@ -15534,7 +15691,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15534
15691
  child.on("error", (err2) => {
15535
15692
  clearTimeout(timer);
15536
15693
  const bashMissing = triedBash && err2.code === "ENOENT";
15537
- resolve39({
15694
+ resolve40({
15538
15695
  ok: false,
15539
15696
  phase: "spawn",
15540
15697
  error: {
@@ -15549,7 +15706,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15549
15706
  });
15550
15707
  child.on("close", (code2) => {
15551
15708
  clearTimeout(timer);
15552
- resolve39({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
15709
+ resolve40({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
15553
15710
  });
15554
15711
  });
15555
15712
  }
@@ -16260,7 +16417,7 @@ function touch(binary, lease, source, scratch, context) {
16260
16417
  if (context) env = withHostInstallEnv(env, context);
16261
16418
  env.GSTACK_LEASE_DIR = shellPath(scratch, context);
16262
16419
  env.GSTACK_LEASE_LOCK_TRIES = "1";
16263
- return new Promise((resolve39, reject) => {
16420
+ return new Promise((resolve40, reject) => {
16264
16421
  const child = execFile(
16265
16422
  binary,
16266
16423
  [
@@ -16289,7 +16446,7 @@ function touch(binary, lease, source, scratch, context) {
16289
16446
  `official lease touch exit ${error.code ?? "unknown"}${error.killed ? " (timeout or termination)" : ""}: ${stderr.trim() || error.message}`
16290
16447
  )
16291
16448
  );
16292
- else resolve39();
16449
+ else resolve40();
16293
16450
  }
16294
16451
  );
16295
16452
  child.stdin?.end();
@@ -16829,7 +16986,7 @@ var init_verifyInstalled = __esm({
16829
16986
  }
16830
16987
  });
16831
16988
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
16832
- return new Promise((resolve39) => {
16989
+ return new Promise((resolve40) => {
16833
16990
  const isWin = process.platform === "win32";
16834
16991
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
16835
16992
  let stdout2 = "";
@@ -16838,15 +16995,15 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
16838
16995
  });
16839
16996
  const timer = setTimeout(() => {
16840
16997
  killProcessTree(child);
16841
- resolve39({ sha: "", exit: -1 });
16998
+ resolve40({ sha: "", exit: -1 });
16842
16999
  }, timeoutMs);
16843
17000
  child.on("error", () => {
16844
17001
  clearTimeout(timer);
16845
- resolve39({ sha: "", exit: -1 });
17002
+ resolve40({ sha: "", exit: -1 });
16846
17003
  });
16847
17004
  child.on("close", (code2) => {
16848
17005
  clearTimeout(timer);
16849
- resolve39({ sha: stdout2.trim(), exit: code2 ?? -1 });
17006
+ resolve40({ sha: stdout2.trim(), exit: code2 ?? -1 });
16850
17007
  });
16851
17008
  });
16852
17009
  }
@@ -17144,7 +17301,12 @@ function isReviewedNeutralTeardown(manifest) {
17144
17301
  const spec = manifest.spec;
17145
17302
  const emptyCleanup = spec.uninstall?.cleanup_paths === void 0 || Array.isArray(spec.uninstall.cleanup_paths) && spec.uninstall.cleanup_paths.length === 0;
17146
17303
  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;
17304
+ return isDeclaredReceiptOnlyTeardown(manifest) || 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;
17305
+ }
17306
+ function isDeclaredReceiptOnlyTeardown(manifest) {
17307
+ const uninstall = manifest.spec.uninstall;
17308
+ const resources = manifest.spec.ownership?.resources;
17309
+ return uninstall?.cmd.trim() === "true" && (uninstall.cleanup_paths === void 0 || uninstall.cleanup_paths.length === 0) && Array.isArray(resources) && resources.length > 0;
17148
17310
  }
17149
17311
  function resolveComponentPlan(manifest, context, operation) {
17150
17312
  const override = context.hostId === "codex" ? manifest.spec.harness_overrides?.codex : void 0;
@@ -17179,7 +17341,7 @@ function resolveComponentPlan(manifest, context, operation) {
17179
17341
  if (context.hostId === "codex" && operation === "uninstall") {
17180
17342
  const validName = /^[a-z0-9][a-z0-9-]*$/.test(effective.metadata.name);
17181
17343
  const portableHook = method === "cc-hook-add" && nativeTeardown && !override?.uninstall;
17182
- if (validName && (isReviewedNeutralTeardown(effective) || portableHook)) {
17344
+ if (validName && (isReviewedNeutralTeardown(effective) || isDeclaredReceiptOnlyTeardown(effective) || portableHook)) {
17183
17345
  return Object.freeze({ ...fields, status: "supported" });
17184
17346
  }
17185
17347
  let detail = `no safe codex uninstall contract for '${manifest.metadata.name}'`;
@@ -17229,6 +17391,56 @@ var init_componentPlan = __esm({
17229
17391
  init_verificationEnv();
17230
17392
  }
17231
17393
  });
17394
+ function isLockContention(error) {
17395
+ return error?.code === "ELOCKED";
17396
+ }
17397
+ function backoffDelay(attempt) {
17398
+ return Math.min(
17399
+ INSTALL_OWNERSHIP_LOCK_RETRIES.minTimeout * 2 ** attempt,
17400
+ INSTALL_OWNERSHIP_LOCK_RETRIES.maxTimeout
17401
+ );
17402
+ }
17403
+ async function acquireOwnershipLock(root) {
17404
+ for (let attempt = 0; ; attempt += 1) {
17405
+ try {
17406
+ return await lockfile.lock(root, {
17407
+ lockfilePath: join(root, ".ownership.lock"),
17408
+ realpath: false,
17409
+ stale: 10 * 60 * 1e3,
17410
+ // One attempt only — the loop below owns the backoff.
17411
+ retries: 0
17412
+ });
17413
+ } catch (error) {
17414
+ if (!isLockContention(error) || attempt >= INSTALL_OWNERSHIP_LOCK_RETRIES.retries) {
17415
+ throw error;
17416
+ }
17417
+ await sleep(backoffDelay(attempt));
17418
+ }
17419
+ }
17420
+ }
17421
+ async function withInstallOwnershipLock(context, work) {
17422
+ const root = context.platform.stateRoot;
17423
+ await mkdir(root, { recursive: true });
17424
+ const release = await acquireOwnershipLock(root);
17425
+ try {
17426
+ return await work();
17427
+ } finally {
17428
+ await release();
17429
+ }
17430
+ }
17431
+ var INSTALL_OWNERSHIP_LOCK_RETRIES, sleep;
17432
+ var init_installOwnershipLock = __esm({
17433
+ "src/installers/lib/installOwnershipLock.ts"() {
17434
+ INSTALL_OWNERSHIP_LOCK_RETRIES = {
17435
+ retries: 30,
17436
+ minTimeout: 250,
17437
+ maxTimeout: 4e3
17438
+ };
17439
+ sleep = (ms) => new Promise((resolve40) => {
17440
+ setTimeout(resolve40, ms);
17441
+ });
17442
+ }
17443
+ });
17232
17444
  async function mcpReadinessFailure(ctx, allowAbsent = false) {
17233
17445
  if (ctx.hostContext?.hostId !== "codex") return null;
17234
17446
  const servers = await listCodexMcpServerMetadata(ctx.hostContext);
@@ -17749,6 +17961,73 @@ async function restoreQuarantine(quarantinePath, target) {
17749
17961
  return error.message;
17750
17962
  }
17751
17963
  }
17964
+ async function rollbackQuarantines(transaction) {
17965
+ const failures = [];
17966
+ for (const quarantined of [...transaction.paths].reverse()) {
17967
+ const { snapshot, quarantinePath } = quarantined;
17968
+ try {
17969
+ await reverifyQuarantinedPath(quarantined);
17970
+ } catch (error) {
17971
+ const detail = error instanceof Error ? error.message : String(error);
17972
+ failures.push(
17973
+ `rollback reverify failed for ${snapshot.target}: ${detail}; retained at ${quarantinePath}`
17974
+ );
17975
+ continue;
17976
+ }
17977
+ const restoreError = await restoreQuarantine(quarantinePath, snapshot.target);
17978
+ if (restoreError !== null) {
17979
+ failures.push(
17980
+ `rollback failed for ${snapshot.target}: ${restoreError}; retained at ${quarantinePath}`
17981
+ );
17982
+ }
17983
+ }
17984
+ return failures;
17985
+ }
17986
+ async function finalizeQuarantines(transaction) {
17987
+ const failures = [];
17988
+ for (const quarantined of transaction.paths) {
17989
+ const { snapshot, quarantinePath } = quarantined;
17990
+ try {
17991
+ await reverifyQuarantinedPath(quarantined);
17992
+ } catch (error) {
17993
+ const detail = error instanceof Error ? error.message : String(error);
17994
+ failures.push(
17995
+ `cleanup reverify failed for ${snapshot.target}: ${detail}; retained at ${quarantinePath}`
17996
+ );
17997
+ continue;
17998
+ }
17999
+ try {
18000
+ await rm(
18001
+ quarantinePath,
18002
+ snapshot.isDirectory ? { recursive: true, force: true, maxRetries: 3 } : { force: true }
18003
+ );
18004
+ } catch (error) {
18005
+ const detail = error instanceof Error ? error.message : String(error);
18006
+ failures.push(
18007
+ `cleanup failed for ${snapshot.target}: ${detail}; retained at ${quarantinePath}`
18008
+ );
18009
+ }
18010
+ }
18011
+ return failures;
18012
+ }
18013
+ async function withQuarantineTransaction(operation, commit) {
18014
+ if (quarantineTransactions.getStore()) {
18015
+ throw new Error("nested quarantine transactions are not supported");
18016
+ }
18017
+ const transaction = { paths: [] };
18018
+ let value;
18019
+ try {
18020
+ value = await quarantineTransactions.run(transaction, operation);
18021
+ await commit();
18022
+ } catch (error) {
18023
+ const detail = error instanceof Error ? error.message : String(error);
18024
+ const rollbackFailures = await rollbackQuarantines(transaction);
18025
+ throw new Error(
18026
+ rollbackFailures.length === 0 ? detail : `${detail}; ${rollbackFailures.join("; ")}`
18027
+ );
18028
+ }
18029
+ return { value, cleanupFailures: await finalizeQuarantines(transaction) };
18030
+ }
17752
18031
  async function verifyQuarantine(snapshot, quarantinePath, verify) {
17753
18032
  const [{ canonicalRoot }, info] = await Promise.all([
17754
18033
  inspectRoot(snapshot.root),
@@ -17799,7 +18078,16 @@ async function verifyQuarantinedFile(snapshot, quarantinePath) {
17799
18078
  throw new Error(`refusing quarantined path outside authorized root: ${snapshot.target}`);
17800
18079
  }
17801
18080
  }
17802
- async function removeOwnedFileViaQuarantine(snapshot) {
18081
+ async function reverifyQuarantinedPath(quarantined) {
18082
+ const { snapshot, quarantinePath, verify } = quarantined;
18083
+ if (snapshot.isDirectory) {
18084
+ await verifyQuarantine(snapshot, quarantinePath, verify);
18085
+ return;
18086
+ }
18087
+ await verifyQuarantinedFile(snapshot, quarantinePath);
18088
+ await verify?.(quarantinePath);
18089
+ }
18090
+ async function removeOwnedFileViaQuarantine(snapshot, options = {}) {
17803
18091
  if (snapshot.isDirectory) {
17804
18092
  throw new Error(`refusing non-recursive removal of directory: ${snapshot.target}`);
17805
18093
  }
@@ -17814,6 +18102,7 @@ async function removeOwnedFileViaQuarantine(snapshot) {
17814
18102
  await rename(snapshot.target, quarantinePath);
17815
18103
  try {
17816
18104
  await verifyQuarantinedFile(snapshot, quarantinePath);
18105
+ await options.verify?.(quarantinePath);
17817
18106
  } catch (error) {
17818
18107
  const restoreError = await restoreQuarantine(quarantinePath, snapshot.target);
17819
18108
  const detail = error instanceof Error ? error.message : String(error);
@@ -17821,6 +18110,11 @@ async function removeOwnedFileViaQuarantine(snapshot) {
17821
18110
  restoreError === null ? detail : `${detail}; quarantine restore failed: ${restoreError}; retained at ${quarantinePath}`
17822
18111
  );
17823
18112
  }
18113
+ const transaction = quarantineTransactions.getStore();
18114
+ if (transaction) {
18115
+ transaction.paths.push({ snapshot, quarantinePath, verify: options.verify });
18116
+ return;
18117
+ }
17824
18118
  await rm(quarantinePath, { force: true });
17825
18119
  }
17826
18120
  async function removeOwnedDirectoryViaQuarantine(snapshot, options = {}) {
@@ -17845,12 +18139,64 @@ async function removeOwnedDirectoryViaQuarantine(snapshot, options = {}) {
17845
18139
  restoreError === null ? detail : `${detail}; quarantine restore failed: ${restoreError}; retained at ${quarantinePath}`
17846
18140
  );
17847
18141
  }
18142
+ const transaction = quarantineTransactions.getStore();
18143
+ if (transaction) {
18144
+ transaction.paths.push({ snapshot, quarantinePath, verify: options.verify });
18145
+ return;
18146
+ }
17848
18147
  await rm(quarantinePath, { recursive: true, force: true, maxRetries: 3 });
17849
18148
  }
18149
+ var quarantineTransactions;
17850
18150
  var init_quarantineDelete = __esm({
17851
18151
  "src/lib/quarantineDelete.ts"() {
18152
+ quarantineTransactions = new AsyncLocalStorage();
17852
18153
  }
17853
18154
  });
18155
+ function receiptParentFailure(reason) {
18156
+ return new Error(`skill ownership receipt parent ${reason}`);
18157
+ }
18158
+ async function captureSkillOwnershipReceiptParent(receiptPath, options = {}) {
18159
+ const parent = dirname(resolve(receiptPath));
18160
+ if (basename(parent) !== "skill-ownership") {
18161
+ throw receiptParentFailure("has an unexpected path");
18162
+ }
18163
+ let info;
18164
+ try {
18165
+ info = await lstat(parent, { bigint: true });
18166
+ } catch (error) {
18167
+ if (error.code !== "ENOENT") throw error;
18168
+ if (!options.create) return null;
18169
+ await mkdir(parent, { recursive: true });
18170
+ info = await lstat(parent, { bigint: true });
18171
+ }
18172
+ if (info.isSymbolicLink() || !info.isDirectory()) {
18173
+ throw receiptParentFailure("is a symlink, junction, reparse redirect, or non-directory");
18174
+ }
18175
+ const [canonicalPath2, canonicalStateRoot] = await Promise.all([
18176
+ realpath(parent),
18177
+ realpath(dirname(parent))
18178
+ ]);
18179
+ if (resolve(canonicalPath2) !== resolve(canonicalStateRoot, basename(parent))) {
18180
+ throw receiptParentFailure("canonical path is redirected");
18181
+ }
18182
+ const canonicalInfo = await lstat(canonicalPath2, { bigint: true });
18183
+ if (canonicalInfo.isSymbolicLink() || !canonicalInfo.isDirectory() || canonicalInfo.dev !== info.dev || canonicalInfo.ino !== info.ino) {
18184
+ throw receiptParentFailure("canonical identity is not a regular directory");
18185
+ }
18186
+ return {
18187
+ path: parent,
18188
+ canonicalPath: resolve(canonicalPath2),
18189
+ device: info.dev,
18190
+ inode: info.ino,
18191
+ type: "directory"
18192
+ };
18193
+ }
18194
+ async function assertSkillOwnershipReceiptParent(expected) {
18195
+ const current = await captureSkillOwnershipReceiptParent(join(expected.path, ".identity-check"));
18196
+ if (!current || current.canonicalPath !== expected.canonicalPath || current.device !== expected.device || current.inode !== expected.inode || current.type !== expected.type) {
18197
+ throw receiptParentFailure("identity changed");
18198
+ }
18199
+ }
17854
18200
  function receiptContext(ctx) {
17855
18201
  const platform = ctx.hostContext?.platform ?? detectPlatform();
17856
18202
  return {
@@ -17860,8 +18206,11 @@ function receiptContext(ctx) {
17860
18206
  stateRoot: resolve(platform.stateRoot)
17861
18207
  };
17862
18208
  }
17863
- function fail(reason) {
17864
- return new Error(`skill ownership receipt ${reason}; run repair or reinstall before uninstalling`);
18209
+ function isSkillOwnershipReceiptError(error) {
18210
+ return error instanceof SkillOwnershipReceiptError;
18211
+ }
18212
+ function fail(reason, kind = "corrupt") {
18213
+ return new SkillOwnershipReceiptError(kind, reason);
17865
18214
  }
17866
18215
  function canonicalJson(value) {
17867
18216
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
@@ -17873,7 +18222,10 @@ function canonicalJson(value) {
17873
18222
  function ownershipFingerprint(ctx) {
17874
18223
  const value = {
17875
18224
  metadata: ctx.manifest.metadata,
17876
- install: ctx.manifest.spec.install
18225
+ install: ctx.manifest.spec.install,
18226
+ ...ctx.manifest.spec.ownership !== void 0 && {
18227
+ ownership: ctx.manifest.spec.ownership
18228
+ } || {}
17877
18229
  };
17878
18230
  return createHash("sha256").update(canonicalJson(value)).digest("hex");
17879
18231
  }
@@ -17881,13 +18233,64 @@ function pathInsideRoot(root, path) {
17881
18233
  const rel = relative(root, path);
17882
18234
  return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
17883
18235
  }
18236
+ function rootForPath(roots, path) {
18237
+ return roots.find((root) => dirname(path) === root) ?? roots.find((root) => pathInsideRoot(root, path));
18238
+ }
18239
+ function declaredRootPath(ctx, root) {
18240
+ const host = ctx.hostContext;
18241
+ if (!host) return void 0;
18242
+ const roots = {
18243
+ "platform-skills": host.platform.skillsDir,
18244
+ "native-home": host.nativeHome,
18245
+ "host-agents": join(host.nativeHome, "agents"),
18246
+ "host-commands": host.platform.commandsDir
18247
+ };
18248
+ return roots[root] ? resolve(roots[root]) : void 0;
18249
+ }
18250
+ async function matchesDeclaredResource(ctx, path, kind, actualPath = path) {
18251
+ const ownership = ctx.manifest.spec.ownership;
18252
+ if (ownership === void 0) {
18253
+ if (kind !== "directory") return false;
18254
+ const roots = skillRootsForContext(ctx).map((root) => resolve(root));
18255
+ return roots.includes(resolve(dirname(path))) && authorizedSkillNames(ctx).includes(basename(path));
18256
+ }
18257
+ const resources = ownership.resources;
18258
+ if (!Array.isArray(resources)) return false;
18259
+ if (resources.length === 0) return false;
18260
+ for (const resource of resources) {
18261
+ const root = declaredRootPath(ctx, resource.root);
18262
+ if (!root || resource.kind !== kind || dirname(path) !== root) continue;
18263
+ const name = path.slice(root.length + 1);
18264
+ const names = resource.selector?.names;
18265
+ const prefix = resource.selector?.prefix;
18266
+ if (!names?.includes(name) && !(prefix && name.startsWith(prefix))) continue;
18267
+ const markerPath = resource.marker?.path ? join(actualPath, resource.marker.path) : actualPath;
18268
+ if (kind === "directory" && !pathInsideRoot(actualPath, markerPath)) continue;
18269
+ try {
18270
+ const targetInfo = await lstat(actualPath);
18271
+ const markerInfo = await lstat(markerPath);
18272
+ if (targetInfo.isSymbolicLink() || markerInfo.isSymbolicLink() || !markerInfo.isFile() || kind === "directory" && !targetInfo.isDirectory() || kind === "file" && !targetInfo.isFile())
18273
+ continue;
18274
+ if (kind === "directory") {
18275
+ const [physicalPath, physicalMarker] = await Promise.all([
18276
+ realpath(actualPath),
18277
+ realpath(markerPath)
18278
+ ]);
18279
+ if (!pathInsideRoot(physicalPath, physicalMarker)) continue;
18280
+ }
18281
+ if ((await readFile(markerPath, "utf8")).includes(resource.marker.contains)) return true;
18282
+ } catch {
18283
+ }
18284
+ }
18285
+ return false;
18286
+ }
17884
18287
  function authorizedSkillNames(ctx) {
17885
18288
  const install = ctx.manifest.spec.install;
17886
18289
  const declared = install.installs_skills;
17887
18290
  const names = Array.isArray(declared) ? declared.filter((name) => typeof name === "string" && name.length > 0) : [];
17888
18291
  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]);
18292
+ const selected2 = install.cmd.match(/(?:^|\s)--skill(?:=|\s+)([a-zA-Z0-9][a-zA-Z0-9._-]*)/);
18293
+ if (selected2?.[1]) names.push(selected2[1]);
17891
18294
  }
17892
18295
  if (names.some((name) => !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name))) {
17893
18296
  throw fail("has an invalid declared skill name");
@@ -17946,17 +18349,20 @@ function validateCreatedPaths(skillRoots, createdPaths) {
17946
18349
  throw fail("contains a non-absolute path");
17947
18350
  }
17948
18351
  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}`);
18352
+ const root = rootForPath(roots, path);
18353
+ if (!root || dirname(path) !== root)
18354
+ throw new Error(`skill ownership path is outside an allowed skill root: ${path}`);
17953
18355
  return path;
17954
18356
  });
17955
18357
  }
18358
+ function requireCreatedPaths(paths) {
18359
+ if (paths.length === 0) throw fail("is empty");
18360
+ }
17956
18361
  function isSkillOwnershipManaged(ctx) {
17957
18362
  const install = ctx.spec.install;
17958
18363
  const installsSkills = install.installs_skills;
17959
- return install.method === "npx-skill-installer" || Array.isArray(installsSkills) && installsSkills.length > 0;
18364
+ const resources = ctx.spec.ownership?.resources;
18365
+ return install.method === "npx-skill-installer" || Array.isArray(resources) && resources.length > 0 || Array.isArray(installsSkills) && installsSkills.length > 0;
17960
18366
  }
17961
18367
  function skillOwnershipReceiptPath(ctx) {
17962
18368
  const binding = receiptContext(ctx);
@@ -17969,57 +18375,82 @@ async function writeSkillOwnershipReceipt(ctx, skillRoots, createdPaths) {
17969
18375
  const binding = receiptContext(ctx);
17970
18376
  const roots = normalizeRoots(skillRoots).sort();
17971
18377
  const paths = validateCreatedPaths(roots, createdPaths).sort();
18378
+ requireCreatedPaths(paths);
17972
18379
  const contentSha256 = {};
18380
+ const pathKinds = {};
17973
18381
  for (const path2 of paths) {
17974
- const root = roots.find((candidate) => pathInsideRoot(candidate, path2));
18382
+ const root = rootForPath(roots, path2);
17975
18383
  if (!root) throw fail(`contains a path outside an allowed skill root: ${path2}`);
18384
+ if (dirname(path2) !== root)
18385
+ throw fail(`target is not a direct child of its captured root: ${path2}`);
17976
18386
  const info = await lstat(path2);
17977
18387
  if (info.isSymbolicLink()) throw fail(`target is a symbolic link: ${path2}`);
17978
- if (!info.isDirectory()) throw fail(`target is not a real directory: ${path2}`);
18388
+ if (!info.isDirectory() && !info.isFile()) throw fail(`target is not a regular path: ${path2}`);
17979
18389
  const [physicalRoot, physicalPath] = await Promise.all([realpath(root), realpath(path2)]);
17980
18390
  if (!pathInsideRoot(physicalRoot, physicalPath))
17981
18391
  throw fail(`target escapes its captured skill root: ${path2}`);
17982
- contentSha256[path2] = await hashSkillTree(path2);
18392
+ contentSha256[path2] = info.isDirectory() ? await hashSkillTree(path2) : createHash("sha256").update(await readFile(path2)).digest("hex");
18393
+ pathKinds[path2] = info.isDirectory() ? "directory" : "file";
18394
+ if (!await matchesDeclaredResource(ctx, path2, pathKinds[path2])) {
18395
+ throw fail("contains a path without a declared ownership marker");
18396
+ }
17983
18397
  }
17984
18398
  const receipt = {
17985
- version: 2,
18399
+ version: 3,
17986
18400
  component: binding.component,
17987
18401
  hostId: binding.hostId,
17988
18402
  nativeRoot: binding.nativeRoot,
17989
18403
  manifestSha256: ownershipFingerprint(ctx),
17990
18404
  skillRoots: roots,
17991
18405
  createdPaths: paths,
17992
- contentSha256
18406
+ contentSha256,
18407
+ pathKinds
17993
18408
  };
17994
18409
  const path = skillOwnershipReceiptPath(ctx);
17995
- await mkdir(dirname(path), { recursive: true });
18410
+ const parent = await captureSkillOwnershipReceiptParent(path, { create: true });
18411
+ if (!parent) throw receiptParentFailure("could not be created");
17996
18412
  const tmpPath = `${path}.${process.pid}.${Date.now()}.tmp`;
18413
+ await assertSkillOwnershipReceiptParent(parent);
17997
18414
  await writeFile(tmpPath, `${JSON.stringify(receipt, null, 2)}
17998
18415
  `, "utf8");
18416
+ await assertSkillOwnershipReceiptParent(parent);
17999
18417
  await rename(tmpPath, path);
18418
+ await assertSkillOwnershipReceiptParent(parent);
18000
18419
  }
18001
18420
  async function readSkillOwnershipReceipt(ctx) {
18002
18421
  const path = skillOwnershipReceiptPath(ctx);
18422
+ const parent = await captureSkillOwnershipReceiptParent(path);
18423
+ if (!parent) throw fail("is missing", "missing");
18003
18424
  let value;
18004
18425
  try {
18005
- value = JSON.parse(await readFile(path, "utf8"));
18426
+ const bytes = await readFile(path, "utf8");
18427
+ await assertSkillOwnershipReceiptParent(parent);
18428
+ value = JSON.parse(bytes);
18006
18429
  } catch (error) {
18007
- if (error.code === "ENOENT") throw fail("is missing");
18430
+ if (error.code === "ENOENT") throw fail("is missing", "missing");
18008
18431
  throw fail("is corrupt");
18009
18432
  }
18010
18433
  if (!value || typeof value !== "object") throw fail("is corrupt");
18011
18434
  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") {
18435
+ if (receipt.version !== 3) throw fail("is legacy or unsupported", "legacy");
18436
+ 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" || Array.isArray(receipt.contentSha256) || !receipt.pathKinds || typeof receipt.pathKinds !== "object" || Array.isArray(receipt.pathKinds)) {
18014
18437
  throw fail("is corrupt");
18015
18438
  }
18439
+ requireCreatedPaths(receipt.createdPaths);
18016
18440
  const binding = receiptContext(ctx);
18017
18441
  if (receipt.component !== binding.component || receipt.hostId !== binding.hostId || resolve(receipt.nativeRoot) !== binding.nativeRoot) {
18018
18442
  throw fail("binding does not match the active component and host root");
18019
18443
  }
18020
18444
  if (receipt.manifestSha256 !== ownershipFingerprint(ctx)) throw fail("manifest identity changed");
18021
18445
  const currentRoots = new Set(
18022
- skillRootsForContext(ctx).map((root) => resolve(root))
18446
+ [
18447
+ ...skillRootsForContext(ctx),
18448
+ ...ctx.hostContext ? [
18449
+ ctx.hostContext.nativeHome,
18450
+ join(ctx.hostContext.nativeHome, "agents"),
18451
+ ctx.hostContext.platform.commandsDir
18452
+ ] : []
18453
+ ].map((root) => resolve(root))
18023
18454
  );
18024
18455
  const normalizedReceiptRoots = normalizeRoots(receipt.skillRoots);
18025
18456
  if (normalizedReceiptRoots.some((root) => !currentRoots.has(root))) {
@@ -18034,50 +18465,244 @@ async function readSkillOwnershipReceipt(ctx) {
18034
18465
  }
18035
18466
  for (const path2 of createdPaths) {
18036
18467
  const digest = receipt.contentSha256[path2];
18037
- if (typeof digest !== "string" || !/^[a-f0-9]{64}$/.test(digest)) {
18468
+ const kind = receipt.pathKinds[path2];
18469
+ const root = rootForPath(skillRoots, path2);
18470
+ if (!root || dirname(path2) !== root || kind !== "file" && kind !== "directory" || typeof digest !== "string" || !/^[a-f0-9]{64}$/.test(digest)) {
18038
18471
  throw fail("contains an invalid or undeclared owned skill path");
18039
18472
  }
18473
+ if (!await matchesDeclaredResource(ctx, path2, kind)) {
18474
+ throw fail("contains a path without a declared ownership marker");
18475
+ }
18476
+ }
18477
+ if (Object.keys(receipt.contentSha256).length !== createdPaths.length || Object.keys(receipt.contentSha256).some((path2) => !createdPaths.includes(path2))) {
18478
+ throw fail("contains undeclared content digests");
18040
18479
  }
18041
18480
  return {
18042
- version: receipt.version,
18481
+ version: 3,
18043
18482
  component: receipt.component,
18044
18483
  hostId: receipt.hostId,
18045
18484
  nativeRoot: binding.nativeRoot,
18046
18485
  manifestSha256: receipt.manifestSha256,
18047
18486
  skillRoots,
18048
18487
  createdPaths,
18049
- contentSha256: receipt.contentSha256
18488
+ contentSha256: receipt.contentSha256,
18489
+ pathKinds: receipt.pathKinds
18050
18490
  };
18051
18491
  }
18052
18492
  async function verifyOwnedSkillPath(receipt, path, actualPath = path) {
18053
18493
  const root = receipt.skillRoots.find((candidate) => dirname(path) === candidate);
18054
18494
  if (!root) throw fail("contains an owned path outside its captured roots");
18055
18495
  const [rootInfo, targetInfo] = await Promise.all([lstat(root), lstat(actualPath)]);
18056
- if (rootInfo.isSymbolicLink() || targetInfo.isSymbolicLink() || !rootInfo.isDirectory() || !targetInfo.isDirectory()) {
18496
+ if (rootInfo.isSymbolicLink() || targetInfo.isSymbolicLink() || !rootInfo.isDirectory()) {
18057
18497
  throw fail("target is a symbolic link, junction, or non-directory");
18058
18498
  }
18499
+ const expectedKind = receipt.pathKinds[path];
18500
+ if (expectedKind !== (targetInfo.isDirectory() ? "directory" : "file")) {
18501
+ throw fail("target type changed after installation");
18502
+ }
18059
18503
  const [physicalRoot, physicalPath] = await Promise.all([realpath(root), realpath(actualPath)]);
18060
18504
  if (dirname(physicalPath) !== physicalRoot) throw fail("target escapes its captured skill root");
18061
- if (await hashSkillTree(actualPath) !== receipt.contentSha256[path]) {
18505
+ const digest = targetInfo.isDirectory() ? await hashSkillTree(actualPath) : createHash("sha256").update(await readFile(actualPath)).digest("hex");
18506
+ if (digest !== receipt.contentSha256[path]) {
18062
18507
  throw fail("target content changed after installation");
18063
18508
  }
18064
18509
  }
18065
- async function removeOwnedSkillPath(receipt, path) {
18510
+ async function removeOwnedSkillPath(receipt, path, ctx) {
18066
18511
  const root = receipt.skillRoots.find((candidate) => dirname(path) === candidate);
18067
18512
  if (!root) throw fail("contains an owned path outside its captured roots");
18513
+ await verifyOwnedSkillPath(receipt, path);
18068
18514
  const snapshot = await prepareOwnedPathRemoval(root, path);
18069
- await removeOwnedDirectoryViaQuarantine(snapshot, {
18070
- verify: async (quarantinePath) => verifyOwnedSkillPath(receipt, path, quarantinePath)
18071
- });
18515
+ const verifyQuarantinedOwnership = async (quarantinePath) => {
18516
+ await verifyOwnedSkillPath(receipt, path, quarantinePath);
18517
+ if (ctx && !await matchesDeclaredResource(
18518
+ ctx,
18519
+ path,
18520
+ receipt.pathKinds[path],
18521
+ quarantinePath
18522
+ )) {
18523
+ throw fail("target no longer matches its declared ownership marker");
18524
+ }
18525
+ };
18526
+ if (snapshot.isDirectory) {
18527
+ await removeOwnedDirectoryViaQuarantine(snapshot, {
18528
+ verify: verifyQuarantinedOwnership
18529
+ });
18530
+ } else {
18531
+ await removeOwnedFileViaQuarantine(snapshot, {
18532
+ verify: verifyQuarantinedOwnership
18533
+ });
18534
+ }
18072
18535
  }
18073
18536
  async function removeSkillOwnershipReceipt(ctx) {
18074
- await rm(skillOwnershipReceiptPath(ctx), { force: true });
18537
+ const path = skillOwnershipReceiptPath(ctx);
18538
+ const parent = await captureSkillOwnershipReceiptParent(path);
18539
+ if (!parent) return;
18540
+ await assertSkillOwnershipReceiptParent(parent);
18541
+ await rm(path, { force: true });
18542
+ await assertSkillOwnershipReceiptParent(parent);
18075
18543
  }
18544
+ var SkillOwnershipReceiptError;
18076
18545
  var init_skillOwnershipReceipt = __esm({
18077
18546
  "src/installers/lib/skillOwnershipReceipt.ts"() {
18078
18547
  init_quarantineDelete();
18079
18548
  init_platform();
18080
18549
  init_packSkillAudit();
18550
+ SkillOwnershipReceiptError = class extends Error {
18551
+ constructor(kind, reason) {
18552
+ super(`skill ownership receipt ${reason}; run repair or reinstall before uninstalling`);
18553
+ this.kind = kind;
18554
+ this.name = "SkillOwnershipReceiptError";
18555
+ }
18556
+ kind;
18557
+ };
18558
+ }
18559
+ });
18560
+ function isResource(value) {
18561
+ if (!value || typeof value !== "object") return false;
18562
+ const resource = value;
18563
+ const selector = resource.selector;
18564
+ const marker = resource.marker;
18565
+ const roots = ["platform-skills", "native-home", "host-agents", "host-commands"];
18566
+ const hasNames = Array.isArray(selector?.names) && selector.names.length > 0 && new Set(selector.names).size === selector.names.length && selector.names.every((name) => typeof name === "string" && name.length > 0);
18567
+ const hasPrefix = typeof selector?.prefix === "string" && selector.prefix.length > 0;
18568
+ return roots.includes(resource.root) && (resource.kind === "file" || resource.kind === "directory") && Boolean(hasNames) !== Boolean(hasPrefix) && typeof marker?.contains === "string" && marker.contains.length > 0 && (resource.kind === "file" ? marker.path === void 0 || isSafeMarkerPath(marker.path) : typeof marker.path === "string" && isSafeMarkerPath(marker.path));
18569
+ }
18570
+ function isSafeMarkerPath(value) {
18571
+ return typeof value === "string" && value.length > 0 && !value.startsWith("/") && !/^[A-Za-z]:\//.test(value) && !value.includes("\\") && value.split("/").every((part) => part.length > 0 && part !== "." && part !== "..");
18572
+ }
18573
+ function resourcesFor(ctx) {
18574
+ const ownership = ctx.manifest.spec.ownership;
18575
+ if (!Array.isArray(ownership?.resources)) return [];
18576
+ if (!ownership.resources.every(isResource)) throw new Error("invalid ownership declaration");
18577
+ return ownership.resources;
18578
+ }
18579
+ function rootPath(ctx, root) {
18580
+ const host = ctx.hostContext;
18581
+ if (!host) return null;
18582
+ const roots = {
18583
+ "platform-skills": host.platform.skillsDir,
18584
+ "native-home": host.nativeHome,
18585
+ "host-agents": join(host.nativeHome, "agents"),
18586
+ "host-commands": host.platform.commandsDir
18587
+ };
18588
+ return resolve(roots[root]);
18589
+ }
18590
+ function isInside(root, path) {
18591
+ const rel = relative(root, path);
18592
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
18593
+ }
18594
+ function selected(resource, name) {
18595
+ const { names, prefix } = resource.selector;
18596
+ return Boolean(names?.includes(name) || prefix?.length && name.startsWith(prefix));
18597
+ }
18598
+ async function regularMarker(candidate, canonicalCandidate, resource) {
18599
+ const markerRelativePath = resource.marker.path;
18600
+ if (resource.kind === "directory" && !markerRelativePath) return false;
18601
+ const markerPath = resource.kind === "file" ? candidate : resolve(candidate, markerRelativePath);
18602
+ if (resource.kind === "directory" && !isInside(candidate, markerPath)) return false;
18603
+ try {
18604
+ if (resource.kind === "directory") {
18605
+ const parts = relative(candidate, markerPath).split(sep);
18606
+ let current = candidate;
18607
+ for (const [index, part] of parts.entries()) {
18608
+ current = join(current, part);
18609
+ const info = await lstat(current);
18610
+ if (info.isSymbolicLink()) return false;
18611
+ if (index < parts.length - 1 && !info.isDirectory()) return false;
18612
+ if (index === parts.length - 1 && !info.isFile()) return false;
18613
+ }
18614
+ if (!isInside(canonicalCandidate, await realpath(markerPath))) return false;
18615
+ }
18616
+ return (await readFile(markerPath, "utf8")).includes(resource.marker.contains);
18617
+ } catch {
18618
+ return false;
18619
+ }
18620
+ }
18621
+ async function discoverResource(ctx, resource) {
18622
+ const root = rootPath(ctx, resource.root);
18623
+ if (!root) return [];
18624
+ let canonicalRoot;
18625
+ let entries;
18626
+ try {
18627
+ const rootInfo = await lstat(root);
18628
+ if (rootInfo.isSymbolicLink() || !rootInfo.isDirectory()) return [];
18629
+ [canonicalRoot, entries] = await Promise.all([
18630
+ realpath(root),
18631
+ readdir(root, { withFileTypes: true })
18632
+ ]);
18633
+ } catch {
18634
+ return [];
18635
+ }
18636
+ const resources = [];
18637
+ for (const entry of entries) {
18638
+ if (!selected(resource, entry.name)) continue;
18639
+ const path = resolve(root, entry.name);
18640
+ try {
18641
+ const info = await lstat(path);
18642
+ if (info.isSymbolicLink()) continue;
18643
+ if (resource.kind === "directory" ? !info.isDirectory() : !info.isFile()) continue;
18644
+ const canonicalPath2 = await realpath(path);
18645
+ if (dirname(canonicalPath2) !== canonicalRoot) continue;
18646
+ if (!await regularMarker(path, canonicalPath2, resource)) continue;
18647
+ resources.push({ path, root, kind: resource.kind });
18648
+ } catch {
18649
+ }
18650
+ }
18651
+ return resources;
18652
+ }
18653
+ async function snapshotResource(ctx, resource) {
18654
+ const root = rootPath(ctx, resource.root);
18655
+ if (!root) return [];
18656
+ let entries;
18657
+ try {
18658
+ const rootInfo = await lstat(root);
18659
+ if (rootInfo.isSymbolicLink() || !rootInfo.isDirectory()) return [];
18660
+ entries = await readdir(root, { withFileTypes: true });
18661
+ } catch {
18662
+ return [];
18663
+ }
18664
+ const resources = [];
18665
+ for (const entry of entries) {
18666
+ if (!selected(resource, entry.name)) continue;
18667
+ const path = resolve(root, entry.name);
18668
+ resources.push({ path, root, kind: resource.kind });
18669
+ }
18670
+ return resources;
18671
+ }
18672
+ async function discoverDeclaredOwnership(ctx) {
18673
+ const declarations = resourcesFor(ctx);
18674
+ const discovered = (await Promise.all(declarations.map((resource) => discoverResource(ctx, resource)))).flat().sort((left, right) => left.path.localeCompare(right.path));
18675
+ const resources = [...new Map(discovered.map((resource) => [resource.path, resource])).values()];
18676
+ return {
18677
+ resources,
18678
+ roots: [
18679
+ ...new Set(
18680
+ declarations.map((resource) => rootPath(ctx, resource.root)).filter((root) => root !== null)
18681
+ )
18682
+ ].sort(),
18683
+ paths: resources.map((resource) => resource.path).sort()
18684
+ };
18685
+ }
18686
+ async function snapshotDeclaredOwnership(ctx) {
18687
+ const declarations = resourcesFor(ctx);
18688
+ const discovered = (await Promise.all(declarations.map((resource) => snapshotResource(ctx, resource)))).flat().sort((left, right) => left.path.localeCompare(right.path));
18689
+ const resources = [...new Map(discovered.map((resource) => [resource.path, resource])).values()];
18690
+ return {
18691
+ resources,
18692
+ roots: [
18693
+ ...new Set(
18694
+ declarations.map((resource) => rootPath(ctx, resource.root)).filter((root) => root !== null)
18695
+ )
18696
+ ].sort(),
18697
+ paths: resources.map((resource) => resource.path).sort()
18698
+ };
18699
+ }
18700
+ async function writeDeclaredOwnershipReceipt(ctx, ownership) {
18701
+ await writeSkillOwnershipReceipt(ctx, ownership.roots, ownership.paths);
18702
+ }
18703
+ var init_ownershipContract = __esm({
18704
+ "src/installers/lib/ownershipContract.ts"() {
18705
+ init_skillOwnershipReceipt();
18081
18706
  }
18082
18707
  });
18083
18708
  function detectLevel(cmd) {
@@ -18100,7 +18725,7 @@ function unprovenPackTarget(ctx) {
18100
18725
  }
18101
18726
  };
18102
18727
  }
18103
- var installNpmCli;
18728
+ var installNpmCliUnlocked, installNpmCli;
18104
18729
  var init_npmCli2 = __esm({
18105
18730
  "src/installers/npmCli.ts"() {
18106
18731
  init_backup();
@@ -18108,6 +18733,8 @@ var init_npmCli2 = __esm({
18108
18733
  init_diff();
18109
18734
  init_err();
18110
18735
  init_idempotent();
18736
+ init_installOwnershipLock();
18737
+ init_ownershipContract();
18111
18738
  init_packSkillAudit();
18112
18739
  init_preflight();
18113
18740
  init_skillOwnershipReceipt();
@@ -18115,7 +18742,7 @@ var init_npmCli2 = __esm({
18115
18742
  init_state2();
18116
18743
  init_verifyInstalled();
18117
18744
  init_verifyMessage();
18118
- installNpmCli = async (ctx) => {
18745
+ installNpmCliUnlocked = async (ctx) => {
18119
18746
  const install = ctx.manifest.spec.install;
18120
18747
  if (install.method !== "npm-cli") {
18121
18748
  return {
@@ -18136,42 +18763,36 @@ var init_npmCli2 = __esm({
18136
18763
  const e = pre.errors[0] ?? err(ctx, "/", "preflight failed (no detail)", "preflight");
18137
18764
  return { ok: false, phase: "preflight", error: e };
18138
18765
  }
18766
+ const managesSkillOwnership = isSkillOwnershipManaged(ctx.manifest);
18767
+ const ownershipCandidateSnapshot = managesSkillOwnership ? await snapshotDeclaredOwnership(ctx) : void 0;
18768
+ const usesDeclaredOwnership = Array.isArray(
18769
+ ctx.manifest.spec.ownership?.resources
18770
+ );
18139
18771
  let existingPackTarget = false;
18140
18772
  if (ctx.hostContext && (ctx.manifest.spec.component_type !== "cli-binary" || install.installs_skills !== void 0)) {
18141
- const names = [ctx.manifest.metadata.name, ...install.installs_skills ?? []];
18142
- if (names.some((name) => !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name)))
18143
- return unprovenPackTarget(ctx);
18144
- const roots = [
18145
- .../* @__PURE__ */ new Set([
18146
- ctx.hostContext.platform.skillsDir,
18147
- join(ctx.hostContext.nativeHome, "skills"),
18148
- join(ctx.hostContext.userHome, ".agents", "skills")
18149
- ])
18150
- ];
18151
- const targets = roots.flatMap((root) => names.map((name) => join(root, name)));
18152
- if (ctx.manifest.metadata.name === "gsd") {
18153
- targets.push(join(ctx.hostContext.nativeHome, "gsd-core"));
18154
- for (const root of [
18155
- ...roots,
18156
- join(ctx.hostContext.nativeHome, "agents"),
18157
- ctx.hostContext.platform.commandsDir
18158
- ]) {
18159
- try {
18160
- if ((await readdir(root)).some((entry) => entry === "gsd" || entry.startsWith("gsd-")))
18161
- existingPackTarget = true;
18162
- } catch (error) {
18163
- if (error.code !== "ENOENT") existingPackTarget = true;
18164
- }
18773
+ if (usesDeclaredOwnership) {
18774
+ existingPackTarget = (ownershipCandidateSnapshot?.paths.length ?? 0) > 0;
18775
+ } else {
18776
+ const names = [ctx.manifest.metadata.name, ...install.installs_skills ?? []];
18777
+ if (names.some((name) => !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name)))
18778
+ return unprovenPackTarget(ctx);
18779
+ const roots = [
18780
+ .../* @__PURE__ */ new Set([
18781
+ ctx.hostContext.platform.skillsDir,
18782
+ join(ctx.hostContext.nativeHome, "skills"),
18783
+ join(ctx.hostContext.userHome, ".agents", "skills")
18784
+ ])
18785
+ ];
18786
+ const targets = roots.flatMap((root) => names.map((name) => join(root, name)));
18787
+ for (const target of targets) {
18788
+ if (await lstat(target).then(
18789
+ () => true,
18790
+ (error) => error.code !== "ENOENT"
18791
+ ))
18792
+ existingPackTarget = true;
18165
18793
  }
18166
18794
  }
18167
- for (const target of targets) {
18168
- if (await lstat(target).then(
18169
- () => true,
18170
- (error) => error.code !== "ENOENT"
18171
- ))
18172
- existingPackTarget = true;
18173
- }
18174
- if (ctx.opts.updateInstalled) return unprovenPackTarget(ctx);
18795
+ if (ctx.opts.updateInstalled && !usesDeclaredOwnership) return unprovenPackTarget(ctx);
18175
18796
  }
18176
18797
  if (await isAlreadyInstalled(ctx)) {
18177
18798
  const verifyFailure2 = await verifyInstalled(ctx, { neutralCwd: true });
@@ -18221,10 +18842,9 @@ var init_npmCli2 = __esm({
18221
18842
  const bk = await backup(plan, ctx);
18222
18843
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
18223
18844
  await warnDeclaredCollisions(ctx);
18224
- const managesSkillOwnership = isSkillOwnershipManaged(ctx.manifest);
18225
18845
  const skillRoots = managesSkillOwnership ? skillRootsForContext(ctx) : [];
18226
18846
  const pathSnapshot = new Set(
18227
- managesSkillOwnership ? await declaredSkillPaths(ctx, skillRoots) : []
18847
+ usesDeclaredOwnership ? ownershipCandidateSnapshot?.paths ?? [] : managesSkillOwnership ? await declaredSkillPaths(ctx, skillRoots) : []
18228
18848
  );
18229
18849
  const packSnapshot = await snapshotSkillNames(
18230
18850
  ...ctx.hostContext ? [ctx.hostContext.platform.skillsDir] : []
@@ -18254,12 +18874,20 @@ var init_npmCli2 = __esm({
18254
18874
  if (verifyFailure) return { ...verifyFailure, backupId: bk.backupId };
18255
18875
  if (managesSkillOwnership) {
18256
18876
  try {
18257
- const afterPaths = await declaredSkillPaths(ctx, skillRoots);
18258
- await writeSkillOwnershipReceipt(
18259
- ctx,
18260
- skillRoots,
18261
- afterPaths.filter((path) => !pathSnapshot.has(path))
18262
- );
18877
+ if (usesDeclaredOwnership) {
18878
+ const discovered = await discoverDeclaredOwnership(ctx);
18879
+ await writeDeclaredOwnershipReceipt(ctx, {
18880
+ roots: discovered.roots,
18881
+ paths: discovered.paths.filter((path) => !pathSnapshot.has(path))
18882
+ });
18883
+ } else {
18884
+ const afterPaths = await declaredSkillPaths(ctx, skillRoots);
18885
+ await writeSkillOwnershipReceipt(
18886
+ ctx,
18887
+ skillRoots,
18888
+ afterPaths.filter((path) => !pathSnapshot.has(path))
18889
+ );
18890
+ }
18263
18891
  } catch (error) {
18264
18892
  return {
18265
18893
  ok: false,
@@ -18286,6 +18914,12 @@ var init_npmCli2 = __esm({
18286
18914
  );
18287
18915
  return { ok: true, backupId: bk.backupId, appliedFiles: [] };
18288
18916
  };
18917
+ installNpmCli = async (ctx) => {
18918
+ if (!ctx.hostContext || !isSkillOwnershipManaged(ctx.manifest)) {
18919
+ return installNpmCliUnlocked(ctx);
18920
+ }
18921
+ return withInstallOwnershipLock(ctx.hostContext, () => installNpmCliUnlocked(ctx));
18922
+ };
18289
18923
  }
18290
18924
  });
18291
18925
  function unprovenSkillTarget(ctx) {
@@ -18327,7 +18961,7 @@ async function activeTargetDirectoryExists(skillsDirs, names) {
18327
18961
  }
18328
18962
  return false;
18329
18963
  }
18330
- var HARD_CRASH_EXITS, HARD_CRASH_RETRY_DELAY_MS, installNpxSkillInstaller;
18964
+ var HARD_CRASH_EXITS, HARD_CRASH_RETRY_DELAY_MS, installNpxSkillInstallerUnlocked, installNpxSkillInstaller;
18331
18965
  var init_npxSkillInstaller2 = __esm({
18332
18966
  "src/installers/npxSkillInstaller.ts"() {
18333
18967
  init_platform();
@@ -18336,6 +18970,8 @@ var init_npxSkillInstaller2 = __esm({
18336
18970
  init_diff();
18337
18971
  init_err();
18338
18972
  init_idempotent();
18973
+ init_installOwnershipLock();
18974
+ init_ownershipContract();
18339
18975
  init_packSkillAudit();
18340
18976
  init_preflight();
18341
18977
  init_skillOwnershipReceipt();
@@ -18345,7 +18981,7 @@ var init_npxSkillInstaller2 = __esm({
18345
18981
  init_verifyMessage();
18346
18982
  HARD_CRASH_EXITS = /* @__PURE__ */ new Set([3221226505, 3221225477]);
18347
18983
  HARD_CRASH_RETRY_DELAY_MS = 500;
18348
- installNpxSkillInstaller = async (ctx) => {
18984
+ installNpxSkillInstallerUnlocked = async (ctx) => {
18349
18985
  const install = ctx.manifest.spec.install;
18350
18986
  if (install.method !== "npx-skill-installer") {
18351
18987
  return {
@@ -18389,6 +19025,12 @@ var init_npxSkillInstaller2 = __esm({
18389
19025
  ];
18390
19026
  const selectionFlags = [...install.cmd.matchAll(/(?:^|\s)(?:--skill|-s)(?:\s|=)/g)];
18391
19027
  const selectedSkill = selections.length === 1 && selectionFlags.length === 1 ? selections[0]?.[1] : void 0;
19028
+ const singleSkill = selectedSkill !== void 0 && !/[;&|<>`$\r\n]/.test(install.cmd);
19029
+ const hasDeclaredTargets = (install.installs_skills?.length ?? 0) > 0;
19030
+ const ownershipResources = ctx.manifest.spec.ownership?.resources;
19031
+ const usesDeclaredOwnership = Array.isArray(ownershipResources) && ownershipResources.length > 0;
19032
+ if (ctx.hostContext && !singleSkill && !hasDeclaredTargets && !usesDeclaredOwnership)
19033
+ return unprovenSkillTarget(ctx);
18392
19034
  const activeTargetNames = npxActiveTargetNames(
18393
19035
  install.cmd,
18394
19036
  ctx.manifest.metadata.name,
@@ -18400,30 +19042,34 @@ var init_npxSkillInstaller2 = __esm({
18400
19042
  )
18401
19043
  ] : [getSkillsDir()];
18402
19044
  const primaryActiveSkillsDir = activeSkillsDirs[0] ?? getSkillsDir();
19045
+ const ownershipCandidateSnapshot = await snapshotDeclaredOwnership(ctx);
18403
19046
  let anyExistingTarget = false;
18404
19047
  if (ctx.hostContext) {
18405
- const names = [.../* @__PURE__ */ new Set([skillSegment, ...install.installs_skills ?? []])];
18406
- if (names.some((name2) => !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name2)))
18407
- return unprovenSkillTarget(ctx);
18408
- const roots = [
18409
- .../* @__PURE__ */ new Set([
18410
- ...activeSkillsDirs,
18411
- ctx.hostContext.platform.skillsDir,
18412
- join(ctx.hostContext.nativeHome, "skills"),
18413
- join(ctx.hostContext.userHome, ".agents", "skills")
18414
- ])
18415
- ];
18416
- for (const root of roots) {
18417
- for (const name2 of names) {
18418
- if (await lstat(join(root, name2)).then(
18419
- () => true,
18420
- (error) => error.code !== "ENOENT"
18421
- )) {
18422
- anyExistingTarget = true;
19048
+ if (usesDeclaredOwnership) {
19049
+ anyExistingTarget = ownershipCandidateSnapshot.paths.length > 0;
19050
+ } else {
19051
+ const names = [.../* @__PURE__ */ new Set([skillSegment, ...install.installs_skills ?? []])];
19052
+ if (names.some((name2) => !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name2)))
19053
+ return unprovenSkillTarget(ctx);
19054
+ const roots = [
19055
+ .../* @__PURE__ */ new Set([
19056
+ ...activeSkillsDirs,
19057
+ ctx.hostContext.platform.skillsDir,
19058
+ join(ctx.hostContext.nativeHome, "skills"),
19059
+ join(ctx.hostContext.userHome, ".agents", "skills")
19060
+ ])
19061
+ ];
19062
+ for (const root of roots) {
19063
+ for (const name2 of names) {
19064
+ if (await lstat(join(root, name2)).then(
19065
+ () => true,
19066
+ (error) => error.code !== "ENOENT"
19067
+ )) {
19068
+ anyExistingTarget = true;
19069
+ }
18423
19070
  }
18424
19071
  }
18425
19072
  }
18426
- const singleSkill = selectedSkill !== void 0 && !/[;&|<>`$\r\n]/.test(install.cmd);
18427
19073
  if (ctx.opts.updateInstalled && (!singleSkill || anyExistingTarget || await isAlreadyInstalled(ctx, { honorUpdateFlag: false })))
18428
19074
  return unprovenSkillTarget(ctx);
18429
19075
  }
@@ -18476,7 +19122,9 @@ var init_npxSkillInstaller2 = __esm({
18476
19122
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
18477
19123
  await warnDeclaredCollisions(ctx);
18478
19124
  const skillRoots = skillRootsForContext(ctx);
18479
- const pathSnapshot = new Set(await declaredSkillPaths(ctx, skillRoots));
19125
+ const pathSnapshot = new Set(
19126
+ usesDeclaredOwnership ? ownershipCandidateSnapshot.paths : await declaredSkillPaths(ctx, skillRoots)
19127
+ );
18480
19128
  const packSnapshot = await snapshotSkillNames(
18481
19129
  ...ctx.hostContext ? [ctx.hostContext.platform.skillsDir] : []
18482
19130
  );
@@ -18526,12 +19174,20 @@ var init_npxSkillInstaller2 = __esm({
18526
19174
  const verifyFailure = await verifyInstalled(ctx, { neutralCwd: true });
18527
19175
  if (verifyFailure) return { ...verifyFailure, backupId: bk.backupId };
18528
19176
  try {
18529
- const afterPaths = await declaredSkillPaths(ctx, skillRoots);
18530
- await writeSkillOwnershipReceipt(
18531
- ctx,
18532
- skillRoots,
18533
- afterPaths.filter((path) => !pathSnapshot.has(path))
18534
- );
19177
+ if (usesDeclaredOwnership) {
19178
+ const discovered = await discoverDeclaredOwnership(ctx);
19179
+ await writeDeclaredOwnershipReceipt(ctx, {
19180
+ roots: discovered.roots,
19181
+ paths: discovered.paths.filter((path) => !pathSnapshot.has(path))
19182
+ });
19183
+ } else {
19184
+ const afterPaths = await declaredSkillPaths(ctx, skillRoots);
19185
+ await writeSkillOwnershipReceipt(
19186
+ ctx,
19187
+ skillRoots,
19188
+ afterPaths.filter((path) => !pathSnapshot.has(path))
19189
+ );
19190
+ }
18535
19191
  } catch (error) {
18536
19192
  return {
18537
19193
  ok: false,
@@ -18557,6 +19213,10 @@ var init_npxSkillInstaller2 = __esm({
18557
19213
  );
18558
19214
  return { ok: true, backupId: bk.backupId, appliedFiles: [skillMdPath] };
18559
19215
  };
19216
+ installNpxSkillInstaller = async (ctx) => {
19217
+ if (!ctx.hostContext) return installNpxSkillInstallerUnlocked(ctx);
19218
+ return withInstallOwnershipLock(ctx.hostContext, () => installNpxSkillInstallerUnlocked(ctx));
19219
+ };
18560
19220
  }
18561
19221
  });
18562
19222
 
@@ -18595,16 +19255,17 @@ async function runInstall(manifest, opts, hostContext) {
18595
19255
  });
18596
19256
  } catch (e) {
18597
19257
  const code2 = e.code;
19258
+ const contention = isLockContention(e);
18598
19259
  return {
18599
19260
  ok: false,
18600
19261
  phase: "spawn",
18601
19262
  error: {
18602
19263
  file: manifest.metadata.name,
18603
19264
  path: "/spec/install",
18604
- message: `installer threw unexpectedly${code2 ? ` (${code2})` : ""}: ${e.message ?? String(e)}`,
19265
+ message: contention ? `install lock contention${code2 ? ` (${code2})` : ""}: ${e.message ?? String(e)} \u2014 retryable, re-run to install this component` : `installer threw unexpectedly${code2 ? ` (${code2})` : ""}: ${e.message ?? String(e)}`,
18605
19266
  line: null,
18606
19267
  column: null,
18607
- keyword: "installer-exception"
19268
+ keyword: contention ? "lock-contention" : "installer-exception"
18608
19269
  }
18609
19270
  };
18610
19271
  }
@@ -18617,6 +19278,7 @@ var init_installers = __esm({
18617
19278
  init_ccPluginMarketplace2();
18618
19279
  init_gitCloneWithSetup2();
18619
19280
  init_componentPlan();
19281
+ init_installOwnershipLock();
18620
19282
  init_mcpHttpAdd2();
18621
19283
  init_mcpStdioAdd2();
18622
19284
  init_npmCli2();
@@ -18828,18 +19490,18 @@ async function installBaseProfile(opts) {
18828
19490
  const installed2 = [];
18829
19491
  const alreadyInstalled = [];
18830
19492
  const skipped = [];
18831
- const failed = [];
19493
+ const failed2 = [];
18832
19494
  for (const path of await listBaseManifests(getAssetsRoot())) {
18833
19495
  let yamlSrc;
18834
19496
  try {
18835
19497
  yamlSrc = await readFile(path, "utf8");
18836
19498
  } catch (e) {
18837
- failed.push({ name: path, reason: `read: ${e.message}` });
19499
+ failed2.push({ name: path, reason: `read: ${e.message}` });
18838
19500
  continue;
18839
19501
  }
18840
19502
  const v = validateManifestFile(yamlSrc, path);
18841
19503
  if (!v.ok) {
18842
- failed.push({ name: path, reason: `validate: ${v.errors[0]?.message ?? "unknown"}` });
19504
+ failed2.push({ name: path, reason: `validate: ${v.errors[0]?.message ?? "unknown"}` });
18843
19505
  continue;
18844
19506
  }
18845
19507
  const name = v.manifest.metadata.name;
@@ -18847,9 +19509,9 @@ async function installBaseProfile(opts) {
18847
19509
  if ("aborted" in r) skipped.push({ name, reason: `aborted: ${r.reason}` });
18848
19510
  else if (r.ok && "alreadyInstalled" in r && r.alreadyInstalled) alreadyInstalled.push(name);
18849
19511
  else if (r.ok) installed2.push(name);
18850
- else failed.push({ name, reason: r.error.message });
19512
+ else failed2.push({ name, reason: r.error.message });
18851
19513
  }
18852
- return { installed: installed2, alreadyInstalled, skipped, failed };
19514
+ return { installed: installed2, alreadyInstalled, skipped, failed: failed2 };
18853
19515
  }
18854
19516
  function registerInstallBase(program2) {
18855
19517
  program2.command("install-base").description(
@@ -18864,17 +19526,17 @@ function registerInstallBase(program2) {
18864
19526
  fullDiff: false,
18865
19527
  color: "auto"
18866
19528
  };
18867
- const { installed: installed2, alreadyInstalled, skipped, failed } = await installBaseProfile(opts);
19529
+ const { installed: installed2, alreadyInstalled, skipped, failed: failed2 } = await installBaseProfile(opts);
18868
19530
  console.log(
18869
19531
  `
18870
- installed: ${installed2.length} / already-installed: ${alreadyInstalled.length} / skipped (user-aborted): ${skipped.length} / failed: ${failed.length}`
19532
+ installed: ${installed2.length} / already-installed: ${alreadyInstalled.length} / skipped (user-aborted): ${skipped.length} / failed: ${failed2.length}`
18871
19533
  );
18872
19534
  for (const i of installed2) console.log(` installed ${i}`);
18873
19535
  for (const a of alreadyInstalled)
18874
19536
  console.log(` already-installed ${a} \u2014 run \`/mcp\` in Claude Code to verify connection`);
18875
19537
  for (const s of skipped) console.log(` skipped ${s.name} \u2014 ${s.reason}`);
18876
- for (const f of failed) console.error(` failed ${f.name} \u2014 ${f.reason}`);
18877
- if (failed.length > 0) process.exit(1);
19538
+ for (const f of failed2) console.error(` failed ${f.name} \u2014 ${f.reason}`);
19539
+ if (failed2.length > 0) process.exit(1);
18878
19540
  if (installed2.length === 0 && alreadyInstalled.length === 0) process.exit(2);
18879
19541
  process.exit(0);
18880
19542
  });
@@ -19464,8 +20126,7 @@ function createAgentRepairResult(input) {
19464
20126
  ...input.proposal ? { proposal: input.proposal } : {}
19465
20127
  };
19466
20128
  }
19467
- function createRepairRequest(result, context, authorization) {
19468
- const components = repairableComponents(result);
20129
+ function createRepairRequest(result, context, authorization, components = repairableComponents(result)) {
19469
20130
  return {
19470
20131
  host: context.hostId,
19471
20132
  runtime: result.runtime,
@@ -19647,6 +20308,311 @@ var init_agentRepairRunner = __esm({
19647
20308
  }
19648
20309
  });
19649
20310
 
20311
+ // src/cli/lib/ownershipAdoptionLock.ts
20312
+ async function withOwnershipAdoptionLock(context, work) {
20313
+ return withInstallOwnershipLock(context, work);
20314
+ }
20315
+ var init_ownershipAdoptionLock = __esm({
20316
+ "src/cli/lib/ownershipAdoptionLock.ts"() {
20317
+ init_installOwnershipLock();
20318
+ }
20319
+ });
20320
+ async function loadRequestedOwnershipManifests(componentIds) {
20321
+ const requested = new Set(componentIds);
20322
+ const found = [];
20323
+ for (const directory of ["tools", "skill-packs"]) {
20324
+ const root = join(getAssetsRoot(), "manifests", directory);
20325
+ for (const name of await readdir(root)) {
20326
+ if (!name.endsWith(".yaml")) continue;
20327
+ const path = join(root, name);
20328
+ const validated = validateManifestFile(await readFile(path, "utf8"), path);
20329
+ if (validated.ok && requested.has(validated.manifest.metadata.name)) {
20330
+ found.push(validated.manifest);
20331
+ } else if (!validated.ok && requested.has(name.slice(0, -5))) {
20332
+ throw new Error(`invalid ownership adoption manifest: ${name}`);
20333
+ }
20334
+ }
20335
+ }
20336
+ return found;
20337
+ }
20338
+ function declaresOwnership(manifest) {
20339
+ const resources = manifest.spec.ownership?.resources;
20340
+ return Array.isArray(resources) && resources.length > 0;
20341
+ }
20342
+ function buildOwnershipAdoptionPlans(request, context, manifests, resolvePlan) {
20343
+ return request.components.map(({ id }) => {
20344
+ const matches = manifests.filter((manifest2) => manifest2.metadata.name === id);
20345
+ if (matches.length !== 1) throw new Error(`ownership adoption manifest count mismatch: ${id}`);
20346
+ const manifest = matches[0];
20347
+ if (!manifest) throw new Error(`ownership adoption manifest missing: ${id}`);
20348
+ const plan = resolvePlan(manifest, context, "install");
20349
+ if (plan.status !== "supported" || plan.componentId !== id || plan.manifest.metadata.name !== id) {
20350
+ throw new Error(`ownership adoption plan mismatch: ${id}`);
20351
+ }
20352
+ return {
20353
+ ctx: {
20354
+ manifest: structuredClone(plan.manifest),
20355
+ hostContext: plan.context,
20356
+ level: "L4",
20357
+ cwd: plan.context.neutralSpawnCwd ?? plan.context.userHome,
20358
+ opts: {
20359
+ apply: false,
20360
+ dryRun: false,
20361
+ system: false,
20362
+ nonInteractive: true,
20363
+ fullDiff: false,
20364
+ color: false
20365
+ }
20366
+ }
20367
+ };
20368
+ }).filter(({ ctx }) => declaresOwnership(ctx.manifest));
20369
+ }
20370
+ var init_ownershipAdoptionPlan = __esm({
20371
+ "src/cli/lib/ownershipAdoptionPlan.ts"() {
20372
+ init_validate();
20373
+ init_assetsRoot();
20374
+ }
20375
+ });
20376
+ async function snapshotOwnershipReceipt(path) {
20377
+ const parentIdentity = await captureSkillOwnershipReceiptParent(path);
20378
+ if (!parentIdentity) return { path, bytes: null, mode: null, parentIdentity: null };
20379
+ try {
20380
+ const info = await lstat(path);
20381
+ if (info.isSymbolicLink() || !info.isFile()) throw new Error("receipt is not a regular file");
20382
+ const bytes = await readFile(path);
20383
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20384
+ return { path, bytes, mode: info.mode, parentIdentity };
20385
+ } catch (error) {
20386
+ if (error.code === "ENOENT") {
20387
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20388
+ return { path, bytes: null, mode: null, parentIdentity };
20389
+ }
20390
+ throw error;
20391
+ }
20392
+ }
20393
+ async function restoreOwnershipReceipt(snapshot) {
20394
+ const parentIdentity = snapshot.parentIdentity ? snapshot.parentIdentity : await captureSkillOwnershipReceiptParent(snapshot.path, { create: snapshot.bytes !== null });
20395
+ if (!parentIdentity) return;
20396
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20397
+ await rm(snapshot.path, { force: true });
20398
+ if (!snapshot.bytes) {
20399
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20400
+ return;
20401
+ }
20402
+ const temp = `${snapshot.path}.${process.pid}.${randomUUID()}.restore.tmp`;
20403
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20404
+ await writeFile(temp, snapshot.bytes, { mode: snapshot.mode ?? void 0 });
20405
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20406
+ await rename(temp, snapshot.path);
20407
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20408
+ }
20409
+ async function restoreOwnershipReceipts(snapshots) {
20410
+ const restored = await Promise.allSettled(snapshots.map(restoreOwnershipReceipt));
20411
+ const failure = restored.find((result) => result.status === "rejected");
20412
+ if (failure?.status === "rejected") throw failure.reason;
20413
+ }
20414
+ function resourceKey(resource) {
20415
+ return JSON.stringify([resource.path, resource.root, resource.kind]);
20416
+ }
20417
+ function intersectDeclaredOwnership(before, after) {
20418
+ const beforeKeys = new Set(before.resources.map(resourceKey));
20419
+ const resources = after.resources.filter((resource) => beforeKeys.has(resourceKey(resource))).sort((left, right) => left.path.localeCompare(right.path));
20420
+ return {
20421
+ resources,
20422
+ roots: [...new Set(resources.map(({ root }) => root))].sort(),
20423
+ paths: resources.map(({ path }) => path)
20424
+ };
20425
+ }
20426
+ var init_ownershipAdoptionReceipt = __esm({
20427
+ "src/cli/lib/ownershipAdoptionReceipt.ts"() {
20428
+ init_skillOwnershipReceipt();
20429
+ }
20430
+ });
20431
+
20432
+ // src/cli/lib/ownershipAdoptionResult.ts
20433
+ function isVerifiedRepairCompletion(repair, request) {
20434
+ const expected = request.components.map(({ id }) => id).sort();
20435
+ const actual = [...new Set(repair.components)].sort();
20436
+ return repair.status === "completed" && repair.verified && repair.authorized && repair.execution === request.host && expected.length === actual.length && expected.every((id, index) => id === actual[index]);
20437
+ }
20438
+ var init_ownershipAdoptionResult = __esm({
20439
+ "src/cli/lib/ownershipAdoptionResult.ts"() {
20440
+ }
20441
+ });
20442
+
20443
+ // src/cli/lib/ownershipAdoption.ts
20444
+ function failed(request, reasonCode = "ownership-adoption-failed") {
20445
+ return createAgentRepairResult({
20446
+ requested: true,
20447
+ authorized: true,
20448
+ components: request.components.map(({ id }) => id),
20449
+ execution: request.host,
20450
+ status: "failed",
20451
+ verified: false,
20452
+ reasonCode
20453
+ });
20454
+ }
20455
+ async function invokeRepair(request, runRepair) {
20456
+ try {
20457
+ return await runRepair();
20458
+ } catch {
20459
+ return failed(request, "agent-repair-threw");
20460
+ }
20461
+ }
20462
+ async function runOwnershipAdoption(input, dependencies = {}) {
20463
+ const { context, request, runRepair } = input;
20464
+ const authorizationError = validateRepairAuthorization(request.authorization, request.components);
20465
+ if (authorizationError) {
20466
+ return createAgentRepairResult({
20467
+ requested: true,
20468
+ authorized: false,
20469
+ components: request.components.map(({ id }) => id),
20470
+ execution: request.host,
20471
+ status: "not-authorized",
20472
+ reasonCode: authorizationError
20473
+ });
20474
+ }
20475
+ let plans;
20476
+ try {
20477
+ const manifests = await (dependencies.loadManifests ?? loadRequestedOwnershipManifests)(
20478
+ request.components.map(({ id }) => id)
20479
+ );
20480
+ plans = buildOwnershipAdoptionPlans(
20481
+ request,
20482
+ context,
20483
+ manifests,
20484
+ dependencies.resolvePlan ?? resolveComponentPlan
20485
+ );
20486
+ } catch {
20487
+ return failed(request, "ownership-adoption-plan-failed");
20488
+ }
20489
+ if (plans.length === 0) {
20490
+ const repair = await invokeRepair(request, runRepair);
20491
+ if (repair.status === "completed" && repair.verified && !isVerifiedRepairCompletion(repair, request)) {
20492
+ return failed(request, "agent-repair-result-mismatch");
20493
+ }
20494
+ return repair;
20495
+ }
20496
+ const discover = dependencies.discover ?? discoverDeclaredOwnership;
20497
+ const writeReceipt = dependencies.writeReceipt ?? writeDeclaredOwnershipReceipt;
20498
+ const receiptPath = dependencies.receiptPath ?? skillOwnershipReceiptPath;
20499
+ const restoreReceipts = dependencies.restoreReceipts ?? restoreOwnershipReceipts;
20500
+ const withLock2 = dependencies.withLock ?? withOwnershipAdoptionLock;
20501
+ try {
20502
+ return await withLock2(context, async () => {
20503
+ const before = await Promise.all(plans.map(({ ctx }) => discover(ctx)));
20504
+ const receipts = await Promise.all(
20505
+ plans.map(({ ctx }) => snapshotOwnershipReceipt(receiptPath(ctx)))
20506
+ );
20507
+ const repair = await invokeRepair(request, runRepair);
20508
+ try {
20509
+ await restoreReceipts(receipts);
20510
+ } catch {
20511
+ return failed(request, "ownership-receipt-restore-failed");
20512
+ }
20513
+ if (repair.status !== "completed" || !repair.verified) return repair;
20514
+ if (!isVerifiedRepairCompletion(repair, request)) {
20515
+ return failed(request, "agent-repair-result-mismatch");
20516
+ }
20517
+ let adopted;
20518
+ try {
20519
+ const after = await Promise.all(plans.map(({ ctx }) => discover(ctx)));
20520
+ adopted = after.map(
20521
+ (value, index) => intersectDeclaredOwnership(before[index], value)
20522
+ );
20523
+ if (adopted.some(({ paths }) => paths.length === 0)) {
20524
+ return failed(request, "ownership-adoption-empty");
20525
+ }
20526
+ for (const [index, plan] of plans.entries()) {
20527
+ const ownership = adopted[index];
20528
+ await writeReceipt(plan.ctx, { roots: ownership.roots, paths: ownership.paths });
20529
+ }
20530
+ } catch {
20531
+ try {
20532
+ await restoreReceipts(receipts);
20533
+ } catch {
20534
+ return failed(request, "ownership-adoption-rollback-failed");
20535
+ }
20536
+ return failed(request, "ownership-adoption-writer-failed");
20537
+ }
20538
+ return repair;
20539
+ });
20540
+ } catch {
20541
+ return failed(request);
20542
+ }
20543
+ }
20544
+ var init_ownershipAdoption = __esm({
20545
+ "src/cli/lib/ownershipAdoption.ts"() {
20546
+ init_componentPlan();
20547
+ init_ownershipContract();
20548
+ init_skillOwnershipReceipt();
20549
+ init_agentRepair();
20550
+ init_ownershipAdoptionLock();
20551
+ init_ownershipAdoptionPlan();
20552
+ init_ownershipAdoptionReceipt();
20553
+ init_ownershipAdoptionResult();
20554
+ }
20555
+ });
20556
+
20557
+ // src/cli/lib/ownershipAdoptionCandidate.ts
20558
+ function declaresOwnership2(manifest) {
20559
+ const resources = manifest.spec.ownership?.resources;
20560
+ return Array.isArray(resources) && resources.length > 0;
20561
+ }
20562
+ function installContext(manifest, context) {
20563
+ return {
20564
+ manifest,
20565
+ hostContext: context,
20566
+ level: "L4",
20567
+ cwd: context.neutralSpawnCwd ?? context.userHome,
20568
+ opts: {
20569
+ apply: false,
20570
+ dryRun: false,
20571
+ system: false,
20572
+ nonInteractive: true,
20573
+ fullDiff: false,
20574
+ color: false
20575
+ }
20576
+ };
20577
+ }
20578
+ async function findOwnershipRepairCandidates(result, context, dependencies = {}) {
20579
+ const ids = result.components.filter(
20580
+ (component2) => component2.status === "current" && REVIEWED_REPAIR_COMPONENTS.has(component2.id)
20581
+ ).map(({ id }) => id);
20582
+ if (ids.length === 0) return [];
20583
+ const manifests = await (dependencies.loadManifests ?? loadRequestedOwnershipManifests)(ids);
20584
+ const resolvePlan = dependencies.resolvePlan ?? resolveComponentPlan;
20585
+ const readReceipt = dependencies.readReceipt ?? readSkillOwnershipReceipt;
20586
+ const candidates = [];
20587
+ for (const id of ids) {
20588
+ const matches = manifests.filter((manifest) => manifest.metadata.name === id);
20589
+ if (matches.length !== 1) throw new Error(`ownership repair manifest count mismatch: ${id}`);
20590
+ const source = matches[0];
20591
+ if (!source) throw new Error(`ownership repair manifest missing: ${id}`);
20592
+ const plan = resolvePlan(source, context, "install");
20593
+ if (plan.status !== "supported" || !declaresOwnership2(plan.manifest)) continue;
20594
+ try {
20595
+ await readReceipt(installContext(structuredClone(plan.manifest), plan.context));
20596
+ } catch (error) {
20597
+ if (!isSkillOwnershipReceiptError(error)) throw error;
20598
+ candidates.push({
20599
+ id,
20600
+ status: "current",
20601
+ reasonCode: "ownership-receipt-repair-required"
20602
+ });
20603
+ }
20604
+ }
20605
+ return candidates;
20606
+ }
20607
+ var init_ownershipAdoptionCandidate = __esm({
20608
+ "src/cli/lib/ownershipAdoptionCandidate.ts"() {
20609
+ init_componentPlan();
20610
+ init_skillOwnershipReceipt();
20611
+ init_agentRepair();
20612
+ init_ownershipAdoptionPlan();
20613
+ }
20614
+ });
20615
+
19650
20616
  // src/cli/lib/updateLock.ts
19651
20617
  var updateLock_exports = {};
19652
20618
  __export(updateLock_exports, {
@@ -19965,18 +20931,18 @@ function preparePackageUpdate(manager, target, context = {}) {
19965
20931
  const cwd = context.cwd ?? process.cwd();
19966
20932
  const executable = npmPath(env, cwd);
19967
20933
  const plan = (args) => {
19968
- const spawn9 = process.platform === "win32" ? planWindowsSpawn("npm", args, executable) : { command: executable, args, verbatim: false };
19969
- const command = spawn9.verbatim ? resolveWindowsBin("cmd.exe", env) : spawn9.command;
20934
+ const spawn10 = process.platform === "win32" ? planWindowsSpawn("npm", args, executable) : { command: executable, args, verbatim: false };
20935
+ const command = spawn10.verbatim ? resolveWindowsBin("cmd.exe", env) : spawn10.command;
19970
20936
  if (!command || !isAbsolute(command)) throw new Error("Selected npm launcher is unresolved");
19971
20937
  return {
19972
20938
  command,
19973
- args: spawn9.args,
20939
+ args: spawn10.args,
19974
20940
  options: {
19975
20941
  cwd,
19976
20942
  env,
19977
20943
  shell: false,
19978
20944
  windowsHide: true,
19979
- windowsVerbatimArguments: spawn9.verbatim
20945
+ windowsVerbatimArguments: spawn10.verbatim
19980
20946
  }
19981
20947
  };
19982
20948
  };
@@ -20122,6 +21088,11 @@ function assetNameFor(platform, arch) {
20122
21088
  function normalized(p8) {
20123
21089
  return p8.replace(/\\/g, "/");
20124
21090
  }
21091
+ function downloadFailureMessage(error, version, url) {
21092
+ const detail = error instanceof Error ? error.message : String(error);
21093
+ const target = version ? ` for release v${version}` : "";
21094
+ return `download failed${target}${url ? ` (tried ${url})` : ""}: ${detail} \u2014 if the network blocks GitHub, use the npm channel (\`npm i -g harnessed@latest\`) or a local build via \`HARNESSED_UPDATE_SOURCE_DIR=<dir> harnessed update\``;
21095
+ }
20125
21096
  async function sha256File(p8) {
20126
21097
  const buf = await readFile(p8);
20127
21098
  return createHash("sha256").update(buf).digest("hex");
@@ -20131,7 +21102,7 @@ function parseShaText(text) {
20131
21102
  return m?.[1]?.toLowerCase() ?? null;
20132
21103
  }
20133
21104
  async function runBinarySelfUpdate(deps, opts) {
20134
- const rename8 = deps.fsOps?.rename ?? rename;
21105
+ const rename9 = deps.fsOps?.rename ?? rename;
20135
21106
  const copyFile$1 = deps.fsOps?.copyFile ?? copyFile;
20136
21107
  const unlink2 = deps.fsOps?.unlink ?? unlink;
20137
21108
  if (normalized(deps.execPath).includes("/node_modules/")) {
@@ -20146,6 +21117,10 @@ async function runBinarySelfUpdate(deps, opts) {
20146
21117
  let targetVersion = null;
20147
21118
  let assetUrl = null;
20148
21119
  let shaUrl = null;
21120
+ let sigUrl = null;
21121
+ let assetFallbackUrl;
21122
+ let shaFallbackUrl;
21123
+ let sigFallbackUrl;
20149
21124
  let sourceAsset = null;
20150
21125
  let sourceSha = null;
20151
21126
  if (deps.sourceDir) {
@@ -20175,7 +21150,7 @@ async function runBinarySelfUpdate(deps, opts) {
20175
21150
  if (rel === null) {
20176
21151
  return {
20177
21152
  status: "error",
20178
- message: "could not reach GitHub releases to resolve the latest binary \u2014 check the network or use the npm channel (`npm i -g harnessed@latest`)"
21153
+ message: "could not reach GitHub releases to resolve the latest binary \u2014 check the network or use the npm channel (`npm i -g harnessed@latest`), or point `HARNESSED_UPDATE_SOURCE_DIR=<dir>` at a local build and re-run `harnessed update`"
20179
21154
  };
20180
21155
  }
20181
21156
  if ("error" in rel) {
@@ -20187,6 +21162,10 @@ async function runBinarySelfUpdate(deps, opts) {
20187
21162
  targetVersion = rel.version;
20188
21163
  assetUrl = rel.assetUrl;
20189
21164
  shaUrl = rel.shaUrl;
21165
+ sigUrl = rel.sigUrl ?? null;
21166
+ assetFallbackUrl = rel.assetFallbackUrl;
21167
+ shaFallbackUrl = rel.shaFallbackUrl;
21168
+ sigFallbackUrl = rel.sigFallbackUrl;
20190
21169
  if (opts.check) {
20191
21170
  return {
20192
21171
  status: "checked",
@@ -20219,15 +21198,15 @@ async function runBinarySelfUpdate(deps, opts) {
20219
21198
  if (deps.sourceDir && sourceAsset) {
20220
21199
  await copyFile(sourceAsset, tempPath);
20221
21200
  } else if (assetUrl) {
20222
- await deps.downloadTo(assetUrl, tempPath);
21201
+ await deps.downloadTo(assetUrl, tempPath, assetFallbackUrl);
20223
21202
  }
20224
21203
  } catch (e) {
20225
21204
  await unlink2(tempPath).catch(() => {
20226
21205
  });
20227
- return { status: "error", message: `download failed: ${e.message}` };
21206
+ return { status: "error", message: downloadFailureMessage(e, targetVersion, assetUrl) };
20228
21207
  }
20229
21208
  try {
20230
- const shaText = deps.sourceDir ? await readFile(sourceSha ?? "", "utf8") : await deps.fetchShaText(shaUrl ?? "");
21209
+ const shaText = deps.sourceDir ? await readFile(sourceSha ?? "", "utf8") : await deps.fetchShaText(shaUrl ?? "", shaFallbackUrl);
20231
21210
  const expected = parseShaText(shaText);
20232
21211
  if (!expected) throw new Error(`malformed .sha256 content`);
20233
21212
  const actual = await sha256File(tempPath);
@@ -20237,7 +21216,7 @@ async function runBinarySelfUpdate(deps, opts) {
20237
21216
  );
20238
21217
  }
20239
21218
  if (!deps.sourceDir) {
20240
- const sigText = await deps.fetchShaText(`${shaUrl ?? ""}.sig`).catch(() => {
21219
+ const sigText = await deps.fetchShaText(sigUrl ?? `${shaUrl ?? ""}.sig`, sigFallbackUrl).catch(() => {
20241
21220
  throw new Error(`missing .sha256.sig (signature is contractual since 4.32.19)`);
20242
21221
  });
20243
21222
  if (!verifyShaSignature(shaText, sigText, deps.publicKeyPem)) {
@@ -20272,7 +21251,7 @@ async function runBinarySelfUpdate(deps, opts) {
20272
21251
  };
20273
21252
  }
20274
21253
  try {
20275
- await rename8(deps.execPath, bakPath);
21254
+ await rename9(deps.execPath, bakPath);
20276
21255
  } catch (e) {
20277
21256
  await unlink2(tempPath).catch(() => {
20278
21257
  });
@@ -20282,10 +21261,10 @@ async function runBinarySelfUpdate(deps, opts) {
20282
21261
  };
20283
21262
  }
20284
21263
  try {
20285
- await rename8(tempPath, deps.execPath);
21264
+ await rename9(tempPath, deps.execPath);
20286
21265
  } catch (e) {
20287
21266
  try {
20288
- await rename8(bakPath, deps.execPath);
21267
+ await rename9(bakPath, deps.execPath);
20289
21268
  return {
20290
21269
  status: "error",
20291
21270
  message: `swap failed (${e.message}) \u2014 rolled back to the previous binary`
@@ -20339,7 +21318,7 @@ async function finalizeBinarySelfUpdate(deps, outcome) {
20339
21318
  }
20340
21319
  }
20341
21320
  async function runBinaryRollback(deps, opts) {
20342
- const rename8 = deps.fsOps?.rename ?? rename;
21321
+ const rename9 = deps.fsOps?.rename ?? rename;
20343
21322
  const copyFile$1 = deps.fsOps?.copyFile ?? copyFile;
20344
21323
  const unlink2 = deps.fsOps?.unlink ?? unlink;
20345
21324
  if (normalized(deps.execPath).includes("/node_modules/")) {
@@ -20401,7 +21380,7 @@ async function runBinaryRollback(deps, opts) {
20401
21380
  };
20402
21381
  }
20403
21382
  try {
20404
- await rename8(deps.execPath, bakPath);
21383
+ await rename9(deps.execPath, bakPath);
20405
21384
  } catch (e) {
20406
21385
  await unlink2(tempPath).catch(() => {
20407
21386
  });
@@ -20411,10 +21390,10 @@ async function runBinaryRollback(deps, opts) {
20411
21390
  };
20412
21391
  }
20413
21392
  try {
20414
- await rename8(tempPath, deps.execPath);
21393
+ await rename9(tempPath, deps.execPath);
20415
21394
  } catch (e) {
20416
21395
  try {
20417
- await rename8(bakPath, deps.execPath);
21396
+ await rename9(bakPath, deps.execPath);
20418
21397
  return {
20419
21398
  status: "error",
20420
21399
  message: `swap failed (${e.message}) \u2014 restored the previous binary`
@@ -20441,57 +21420,113 @@ async function runBinaryRollback(deps, opts) {
20441
21420
  });
20442
21421
  return { status: "rolled-back", from: deps.currentVersion, to: target, backupUsed: backupBin };
20443
21422
  }
20444
- async function fetchWithTimeout(url, timeoutMs) {
21423
+ async function fetchWithTimeout(url, timeoutMs, net = {}, headers = {}) {
20445
21424
  await ensureProxyDispatcher();
21425
+ const doFetch = net.fetchImpl ?? fetch;
20446
21426
  const ac = new AbortController();
20447
21427
  const timer = setTimeout(() => ac.abort(), timeoutMs);
20448
21428
  try {
20449
- return await fetch(url, {
21429
+ return await doFetch(url, {
20450
21430
  signal: ac.signal,
20451
- headers: { "user-agent": `harnessed/${package_default.version}` }
21431
+ headers: { "user-agent": `harnessed/${package_default.version}`, ...headers },
21432
+ // GitHub's asset endpoint answers 302 → release-assets.githubusercontent.com
21433
+ // only when the Accept header asks for the raw bytes; without it the API
21434
+ // returns asset METADATA JSON instead of the file.
21435
+ redirect: "follow"
20452
21436
  });
20453
21437
  } finally {
20454
21438
  clearTimeout(timer);
20455
21439
  }
20456
21440
  }
20457
- async function resolveLatestRelease(platform = process.platform, arch = process.arch) {
21441
+ function isTransientNetworkError(error) {
21442
+ const code2 = error?.code;
21443
+ if (code2 && ["ECONNRESET", "ECONNREFUSED", "ETIMEDOUT", "EPIPE", "EAI_AGAIN"].includes(code2)) {
21444
+ return true;
21445
+ }
21446
+ const message = error instanceof Error ? error.message : String(error);
21447
+ return /socket connection was closed|ECONNRESET|ETIMEDOUT|network|terminated|fetch failed/i.test(
21448
+ message
21449
+ );
21450
+ }
21451
+ async function fetchAsset(url, fallbackUrl, timeoutMs, net, label) {
21452
+ const sleep2 = net.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
21453
+ const attempts = [];
21454
+ let lastError;
21455
+ for (const candidate of [url, fallbackUrl].filter((u) => !!u)) {
21456
+ for (let attempt = 1; attempt <= DOWNLOAD_ATTEMPTS; attempt++) {
21457
+ try {
21458
+ const res = await fetchWithTimeout(candidate, timeoutMs, net, {
21459
+ accept: "application/octet-stream"
21460
+ });
21461
+ if (res.ok) return res;
21462
+ lastError = new Error(`HTTP ${res.status} downloading ${candidate}`);
21463
+ if (res.status < 500) break;
21464
+ } catch (error) {
21465
+ lastError = error;
21466
+ if (!isTransientNetworkError(error)) break;
21467
+ }
21468
+ attempts.push(candidate);
21469
+ if (attempt < DOWNLOAD_ATTEMPTS) await sleep2(250 * attempt);
21470
+ }
21471
+ }
21472
+ throw new Error(
21473
+ `${label} download failed (${attempts.length} attempt(s) over ${[url, fallbackUrl].filter(Boolean).join(", ")}): ${lastError instanceof Error ? lastError.message : String(lastError)}`
21474
+ );
21475
+ }
21476
+ async function resolveLatestRelease(platform = process.platform, arch = process.arch, net = {}) {
20458
21477
  try {
20459
- const res = await fetchWithTimeout(RELEASES_LATEST_URL, 1e4);
21478
+ const res = await fetchWithTimeout(RELEASES_LATEST_URL, 1e4, net);
20460
21479
  if (!res.ok) return null;
20461
21480
  const body = await res.json();
20462
21481
  const version = (body.tag_name ?? "").replace(/^v/, "");
20463
21482
  if (!/^\d+\.\d+\.\d+/.test(version)) return null;
20464
21483
  const asset = assetNameFor(platform, arch);
20465
- const found = body.assets?.find((a) => a.name === asset);
20466
- const sha = body.assets?.find((a) => a.name === `${asset}.sha256`);
20467
- if (!found?.browser_download_url) {
21484
+ const pick = (name) => body.assets?.find((a) => a.name === name);
21485
+ const found = pick(asset);
21486
+ const sha = pick(`${asset}.sha256`);
21487
+ const sig = pick(`${asset}.sha256.sig`);
21488
+ if (!found?.browser_download_url && !found?.url) {
20468
21489
  return { error: `asset ${asset} not found on release v${version}` };
20469
21490
  }
20470
- if (!sha?.browser_download_url) {
21491
+ if (!sha?.browser_download_url && !sha?.url) {
20471
21492
  return { error: `asset ${asset}.sha256 not found on release v${version}` };
20472
21493
  }
20473
- return { version, assetUrl: found.browser_download_url, shaUrl: sha.browser_download_url };
21494
+ const pair = (a) => {
21495
+ const api = a?.url;
21496
+ const browser = a?.browser_download_url;
21497
+ return api && browser ? { primary: api, fallback: browser } : { primary: api ?? browser ?? "", fallback: void 0 };
21498
+ };
21499
+ const assetPair = pair(found);
21500
+ const shaPair = pair(sha);
21501
+ const sigPair = pair(sig);
21502
+ return {
21503
+ version,
21504
+ assetUrl: assetPair.primary,
21505
+ shaUrl: shaPair.primary,
21506
+ sigUrl: sigPair.primary || void 0,
21507
+ assetFallbackUrl: assetPair.fallback,
21508
+ shaFallbackUrl: shaPair.fallback,
21509
+ sigFallbackUrl: sigPair.fallback
21510
+ };
20474
21511
  } catch {
20475
21512
  return null;
20476
21513
  }
20477
21514
  }
20478
- function realSelfUpdateDeps(context) {
21515
+ function realSelfUpdateDeps(context, net = {}) {
20479
21516
  return {
20480
21517
  execPath: process.execPath,
20481
21518
  platform: process.platform,
20482
21519
  arch: process.arch,
20483
21520
  currentVersion: package_default.version,
20484
21521
  sourceDir: process.env.HARNESSED_UPDATE_SOURCE_DIR?.trim() || null,
20485
- resolveRelease: () => resolveLatestRelease(),
20486
- downloadTo: async (url, dest) => {
20487
- const res = await fetchWithTimeout(url, 12e4);
20488
- if (!res.ok) throw new Error(`HTTP ${res.status} downloading ${url}`);
21522
+ resolveRelease: () => resolveLatestRelease(process.platform, process.arch, net),
21523
+ downloadTo: async (url, dest, fallbackUrl) => {
21524
+ const res = await fetchAsset(url, fallbackUrl, 12e4, net, "binary");
20489
21525
  const buf = Buffer.from(await res.arrayBuffer());
20490
21526
  await writeFile(dest, buf);
20491
21527
  },
20492
- fetchShaText: async (url) => {
20493
- const res = await fetchWithTimeout(url, 3e4);
20494
- if (!res.ok) throw new Error(`HTTP ${res.status} fetching ${url}`);
21528
+ fetchShaText: async (url, fallbackUrl) => {
21529
+ const res = await fetchAsset(url, fallbackUrl, 3e4, net, "checksum");
20495
21530
  return res.text();
20496
21531
  },
20497
21532
  smoke: async (bin) => {
@@ -20522,7 +21557,7 @@ async function execDirWritable(execPath) {
20522
21557
  return false;
20523
21558
  }
20524
21559
  }
20525
- var OWNER_REPO, RELEASES_LATEST_URL;
21560
+ var OWNER_REPO, RELEASES_LATEST_URL, DOWNLOAD_ATTEMPTS;
20526
21561
  var init_selfUpdateBinary = __esm({
20527
21562
  "src/cli/lib/selfUpdateBinary.ts"() {
20528
21563
  init_package();
@@ -20532,6 +21567,7 @@ var init_selfUpdateBinary = __esm({
20532
21567
  init_version_check();
20533
21568
  OWNER_REPO = "easyinplay/harnessed";
20534
21569
  RELEASES_LATEST_URL = `https://api.github.com/repos/${OWNER_REPO}/releases/latest`;
21570
+ DOWNLOAD_ATTEMPTS = 3;
20535
21571
  }
20536
21572
  });
20537
21573
 
@@ -20845,7 +21881,7 @@ function decodeUpdateContinuation(encoded) {
20845
21881
  return value;
20846
21882
  }
20847
21883
  async function runContinuationProcess(executablePath, args, options) {
20848
- return new Promise((resolve39, reject) => {
21884
+ return new Promise((resolve40, reject) => {
20849
21885
  const child = spawn(executablePath, args, {
20850
21886
  cwd: options.cwd,
20851
21887
  env: options.env,
@@ -20859,7 +21895,7 @@ async function runContinuationProcess(executablePath, args, options) {
20859
21895
  child.once("error", reject);
20860
21896
  child.once("close", (exitCode, signal) => {
20861
21897
  clearTimeout(timer);
20862
- resolve39({ exitCode, signal });
21898
+ resolve40({ exitCode, signal });
20863
21899
  });
20864
21900
  });
20865
21901
  }
@@ -21664,8 +22700,8 @@ async function refreshWorkflows(context, assets) {
21664
22700
  context.hostId,
21665
22701
  context
21666
22702
  );
21667
- const failed = rendered.results.find((result) => result.error);
21668
- if (failed) throw new Error(failed.error);
22703
+ const failed2 = rendered.results.find((result) => result.error);
22704
+ if (failed2) throw new Error(failed2.error);
21669
22705
  await mkdir(context.platform.stateRoot, { recursive: true });
21670
22706
  await recordSkillHashes(names, skillsBase, ledgerPath2);
21671
22707
  if (context.hostId === "claude") {
@@ -21712,6 +22748,29 @@ async function reminderEnabled(context) {
21712
22748
  return error.code === "ENOENT";
21713
22749
  }
21714
22750
  }
22751
+ async function hasFirstPartyRegistration(context, hookEvent, hookCommand) {
22752
+ let raw;
22753
+ try {
22754
+ raw = await readFile(join(context.nativeHome, "settings.json"), "utf8");
22755
+ } catch {
22756
+ return false;
22757
+ }
22758
+ let parsed;
22759
+ try {
22760
+ parsed = JSON.parse(raw);
22761
+ } catch {
22762
+ return false;
22763
+ }
22764
+ const hooks = parsed.hooks;
22765
+ if (!hooks || typeof hooks !== "object") return false;
22766
+ try {
22767
+ return harnessedHookRegistrations(hooks, hookCommand).some(
22768
+ (registration) => registration.event === hookEvent
22769
+ );
22770
+ } catch {
22771
+ return false;
22772
+ }
22773
+ }
21715
22774
  async function refreshOwnedUpdate(context) {
21716
22775
  const assets = getAssetsRoot();
21717
22776
  const results = [];
@@ -21763,17 +22822,26 @@ async function refreshOwnedUpdate(context) {
21763
22822
  if (!validated.ok || validated.manifest.metadata.name !== name || validated.manifest.metadata.upstream?.repository !== "https://github.com/easyinplay/harnessed.git" || validated.manifest.spec.install.method !== "cc-hook-add")
21764
22823
  throw new Error(`Invalid first-party hook: ${name}`);
21765
22824
  const plan = resolveComponentPlan(validated.manifest, context, "install");
21766
- if (name !== "update-reminder" && !await isAlreadyInstalled(
21767
- {
21768
- manifest: structuredClone(plan.manifest),
21769
- opts,
21770
- level: "L3",
21771
- cwd: context.neutralSpawnCwd ?? context.userHome,
21772
- hostContext: context
21773
- },
21774
- { honorUpdateFlag: false }
21775
- ))
21776
- continue;
22825
+ if (name !== "update-reminder") {
22826
+ const installed2 = await isAlreadyInstalled(
22827
+ {
22828
+ manifest: structuredClone(plan.manifest),
22829
+ opts,
22830
+ level: "L3",
22831
+ cwd: context.neutralSpawnCwd ?? context.userHome,
22832
+ hostContext: context
22833
+ },
22834
+ { honorUpdateFlag: false }
22835
+ );
22836
+ if (!installed2) {
22837
+ const registered = await hasFirstPartyRegistration(
22838
+ context,
22839
+ validated.manifest.spec.install.hook_event,
22840
+ validated.manifest.spec.install.hook_command
22841
+ );
22842
+ if (!registered) continue;
22843
+ }
22844
+ }
21777
22845
  const result = await runInstall(validated.manifest, opts, context);
21778
22846
  results.push(
21779
22847
  createUpdateComponent({
@@ -21805,6 +22873,7 @@ var init_refreshOwnedUpdate = __esm({
21805
22873
  init_i18n();
21806
22874
  init_installers();
21807
22875
  init_componentPlan();
22876
+ init_harnessedHookTeardown();
21808
22877
  init_idempotent();
21809
22878
  init_validate();
21810
22879
  init_assetsRoot();
@@ -21836,6 +22905,7 @@ __export(updateCoordinator_exports, {
21836
22905
  executeUpdate: () => executeUpdate,
21837
22906
  hasWrittenUpdateEnvelope: () => hasWrittenUpdateEnvelope,
21838
22907
  renderHumanUpdateResult: () => renderHumanUpdateResult,
22908
+ runAuthorizedAgentRepair: () => runAuthorizedAgentRepair,
21839
22909
  runUpdateCoordinator: () => runUpdateCoordinator,
21840
22910
  updateFailureResult: () => updateFailureResult,
21841
22911
  updateTarget: () => updateTarget,
@@ -22384,8 +23454,20 @@ async function executeUpdate(options) {
22384
23454
  );
22385
23455
  }
22386
23456
  }
22387
- async function runAuthorizedAgentRepair(deterministicResult, options, context) {
22388
- const components = repairableComponents(deterministicResult);
23457
+ async function runAuthorizedAgentRepair(deterministicResult, options, context, dependencies = {}) {
23458
+ const deterministicComponents = repairableComponents(deterministicResult);
23459
+ const ownershipCandidates = options.repair === true && options.yes === true && (options.all === true || options.upstreams === true) ? await (dependencies.findOwnershipRepairCandidates ?? findOwnershipRepairCandidates)(
23460
+ deterministicResult,
23461
+ context
23462
+ ) : [];
23463
+ const components = [
23464
+ ...new Map(
23465
+ [...deterministicComponents, ...ownershipCandidates].map((component2) => [
23466
+ component2.id,
23467
+ component2
23468
+ ])
23469
+ ).values()
23470
+ ];
22389
23471
  if (components.length === 0)
22390
23472
  return {
22391
23473
  ...deterministicResult,
@@ -22413,23 +23495,31 @@ async function runAuthorizedAgentRepair(deterministicResult, options, context) {
22413
23495
  components: [],
22414
23496
  grantedAt: null
22415
23497
  };
22416
- const request = createRepairRequest(deterministicResult, context, authorization);
22417
- const repair = await runAgentRepair(request, {
22418
- verify: async (verificationRequest) => {
22419
- const verification = await executeUpdate({
22420
- all: true,
22421
- check: true,
22422
- json: true,
22423
- nonInteractive: true,
22424
- platform: verificationRequest.host,
22425
- packageManager: options.packageManager
22426
- });
22427
- const checked = new Map(verification.components.map((component2) => [component2.id, component2]));
22428
- return verificationRequest.components.every((component2) => {
22429
- const current = checked.get(component2.id);
22430
- return current?.verified === true && ["current", "updated"].includes(current.status);
22431
- });
22432
- }
23498
+ const request = createRepairRequest(deterministicResult, context, authorization, components);
23499
+ const repairRunner = dependencies.runAgentRepair ?? runAgentRepair;
23500
+ const adoptionRunner = dependencies.runOwnershipAdoption ?? runOwnershipAdoption;
23501
+ const repair = await adoptionRunner({
23502
+ context,
23503
+ request,
23504
+ runRepair: () => repairRunner(request, {
23505
+ verify: async (verificationRequest) => {
23506
+ const verification = await executeUpdate({
23507
+ all: true,
23508
+ check: true,
23509
+ json: true,
23510
+ nonInteractive: true,
23511
+ platform: verificationRequest.host,
23512
+ packageManager: options.packageManager
23513
+ });
23514
+ const checked = new Map(
23515
+ verification.components.map((component2) => [component2.id, component2])
23516
+ );
23517
+ return verificationRequest.components.every((component2) => {
23518
+ const current = checked.get(component2.id);
23519
+ return current?.verified === true && ["current", "updated"].includes(current.status);
23520
+ });
23521
+ }
23522
+ })
22433
23523
  });
22434
23524
  return {
22435
23525
  ...deterministicResult,
@@ -22447,6 +23537,8 @@ var init_updateCoordinator = __esm({
22447
23537
  init_runtime();
22448
23538
  init_agentRepair();
22449
23539
  init_agentRepairRunner();
23540
+ init_ownershipAdoption();
23541
+ init_ownershipAdoptionCandidate();
22450
23542
  init_packageUpdateTarget();
22451
23543
  init_updateResult();
22452
23544
  UpdateProtocolError = class extends Error {
@@ -22460,14 +23552,14 @@ var manifest_add_exports = {};
22460
23552
  __export(manifest_add_exports, {
22461
23553
  registerManifestAdd: () => registerManifestAdd
22462
23554
  });
22463
- function basename7(upstream) {
23555
+ function basename8(upstream) {
22464
23556
  return (upstream.split("/").pop() ?? upstream).replace(/\.git$/, "");
22465
23557
  }
22466
23558
  function registerManifestAdd(program2) {
22467
23559
  program2.command("manifest-add <upstream>").description(
22468
23560
  "Add a new upstream adapter (EE-5 5-question merge gate; immediate by default \u2014 use --dry-run for preview)"
22469
23561
  ).option("--category <cat>", "manifest category (skill-packs | tools)", "skill-packs").option("--name <name>", "short adapter name (defaults to <upstream> basename)").option("--dry-run", "preview only \u2014 do not write JSON (opt-in for advanced users)").option("--non-interactive", "CI/scripts \u2014 WARN-only dry-run").action(async (upstream, raw) => {
22470
- const name = raw.name ?? basename7(upstream);
23562
+ const name = raw.name ?? basename8(upstream);
22471
23563
  const category = raw.category ?? "skill-packs";
22472
23564
  try {
22473
23565
  checkSafeSegment(category);
@@ -22780,11 +23872,11 @@ function registerReleasePreflight(program2) {
22780
23872
  console.log(` ${mark} ${c.name} \u2014 ${c.message}`);
22781
23873
  if (c.status !== "pass" && c.fix) console.log(` fix: ${c.fix}`);
22782
23874
  }
22783
- const failed = anyFailed2(checks);
23875
+ const failed2 = anyFailed2(checks);
22784
23876
  console.log(
22785
- failed ? "\n NOT release-ready \u2014 resolve the failures above before tagging." : "\n release-ready \u2014 tag the version to trigger publish.yml."
23877
+ failed2 ? "\n NOT release-ready \u2014 resolve the failures above before tagging." : "\n release-ready \u2014 tag the version to trigger publish.yml."
22786
23878
  );
22787
- process.exit(failed ? 1 : 0);
23879
+ process.exit(failed2 ? 1 : 0);
22788
23880
  });
22789
23881
  }
22790
23882
  var init_release_preflight2 = __esm({
@@ -23743,18 +24835,18 @@ async function runStepBInstall(manifestPaths, runOpts = {}) {
23743
24835
  const installed2 = [];
23744
24836
  const alreadyInstalled = [];
23745
24837
  const skipped = [];
23746
- const failed = [];
24838
+ const failed2 = [];
23747
24839
  for (const v of [...invalid, ...mcpEntries, ...restEntries]) {
23748
24840
  if (v.status === "installed") installed2.push(v.name);
23749
24841
  else if (v.status === "already-installed") alreadyInstalled.push(v.name);
23750
24842
  else if (v.status === "skipped") skipped.push({ name: v.name, reason: v.reason });
23751
- else if (v.status === "failed") failed.push(`${v.name}: ${v.reason}`);
24843
+ else if (v.status === "failed") failed2.push(`${v.name}: ${v.reason}`);
23752
24844
  }
23753
24845
  return {
23754
24846
  installed: installed2,
23755
24847
  alreadyInstalled,
23756
24848
  skipped,
23757
- failed,
24849
+ failed: failed2,
23758
24850
  failureKeywords,
23759
24851
  elapsedMs: Date.now() - start,
23760
24852
  componentTypes
@@ -23762,7 +24854,7 @@ async function runStepBInstall(manifestPaths, runOpts = {}) {
23762
24854
  }
23763
24855
  async function reclassifyForceUpdateFailures(firstPass, forcePass, probe) {
23764
24856
  const priorlyInstalled = new Set(firstPass.alreadyInstalled);
23765
- const failed = [];
24857
+ const failed2 = [];
23766
24858
  const keptExisting = [];
23767
24859
  for (const entry of forcePass.failed) {
23768
24860
  const m = entry.match(/^([^:]+):\s*(.*)$/s);
@@ -23783,9 +24875,9 @@ async function reclassifyForceUpdateFailures(firstPass, forcePass, probe) {
23783
24875
  continue;
23784
24876
  }
23785
24877
  }
23786
- failed.push(entry);
24878
+ failed2.push(entry);
23787
24879
  }
23788
- return { failed, keptExisting };
24880
+ return { failed: failed2, keptExisting };
23789
24881
  }
23790
24882
  async function makeIdempotentProbe(manifestPaths, context = captureHostInstallContext()) {
23791
24883
  const byName = /* @__PURE__ */ new Map();
@@ -23806,9 +24898,9 @@ async function makeIdempotentProbe(manifestPaths, context = captureHostInstallCo
23806
24898
  }
23807
24899
  }
23808
24900
  return async (name) => {
23809
- const selected = byName.get(name);
23810
- if (!selected) return false;
23811
- const { manifest, hostContext } = selected;
24901
+ const selected2 = byName.get(name);
24902
+ if (!selected2) return false;
24903
+ const { manifest, hostContext } = selected2;
23812
24904
  if (manifest.spec.install.method === "npx-skill-installer") {
23813
24905
  const install = manifest.spec.install;
23814
24906
  const targets = npxActiveTargetNames(
@@ -24473,6 +25565,7 @@ function mergeStepBResults(first, next) {
24473
25565
  first.failed = first.failed.filter((entry) => !replaced.has(failureName(entry))).concat(next.failed);
24474
25566
  first.skipped = first.skipped.filter((entry) => !replaced.has(entry.name)).concat(skipped);
24475
25567
  first.keptExisting = (first.keptExisting ?? []).filter((entry) => !replaced.has(entry.name)).concat(next.keptExisting ?? []);
25568
+ first.failureKeywords = { ...first.failureKeywords, ...next.failureKeywords };
24476
25569
  first.componentTypes = { ...first.componentTypes, ...next.componentTypes };
24477
25570
  first.elapsedMs += next.elapsedMs;
24478
25571
  }
@@ -24646,7 +25739,7 @@ installing ${manifestPaths.length} upstream components (MCP serialized, rest par
24646
25739
  progress.done();
24647
25740
  if (forceFirstPass && b.failed.length > 0) {
24648
25741
  const probe = await makeIdempotentProbe(manifestPaths, setupContext);
24649
- const failed = [];
25742
+ const failed2 = [];
24650
25743
  for (const entry of b.failed) {
24651
25744
  const match = entry.match(/^([^:]+):\s*(.*)$/s);
24652
25745
  const name = (match?.[1] ?? entry).trim();
@@ -24660,9 +25753,9 @@ installing ${manifestPaths.length} upstream components (MCP serialized, rest par
24660
25753
  if (retained) {
24661
25754
  b.keptExisting ??= [];
24662
25755
  b.keptExisting.push({ name, reason: match?.[2]?.trim() ?? "" });
24663
- } else failed.push(entry);
25756
+ } else failed2.push(entry);
24664
25757
  }
24665
- b.failed = failed;
25758
+ b.failed = failed2;
24666
25759
  }
24667
25760
  const stepBMs = (b.elapsedMs / 1e3).toFixed(1);
24668
25761
  console.log(
@@ -24983,17 +26076,31 @@ Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting
24983
26076
  console.error(` [optional] ${failure.name}: ${failure.reason}`);
24984
26077
  }
24985
26078
  }
24986
- const failedCount = b.failed.length + optionalFailed + setupFailures.length;
26079
+ const lockContentionFailures = b.failed.filter(
26080
+ (failure) => b.failureKeywords?.[failure.split(": ", 1)[0] ?? failure] === "lock-contention"
26081
+ );
26082
+ const fatalBaseFailures = b.failed.length - lockContentionFailures.length;
26083
+ const failedCount = fatalBaseFailures + optionalFailed + setupFailures.length;
24987
26084
  if (failedCount > 0) {
24988
26085
  console.error(
24989
26086
  `
24990
26087
  ${failedCount} component(s) failed \u2014 see the notes above; re-run \`harnessed setup\` to retry, or run \`harnessed doctor\` for environment diagnostics.`
24991
26088
  );
24992
26089
  }
26090
+ if (lockContentionFailures.length > 0) {
26091
+ console.warn(
26092
+ `
26093
+ ${lockContentionFailures.length} component(s) hit install lock contention \u2014 re-run \`harnessed setup\` to finish them.`
26094
+ );
26095
+ }
24993
26096
  const configured = b.installed.length + b.alreadyInstalled.length + (b.keptExisting?.length ?? 0);
24994
26097
  if (failedCount > 0) {
24995
26098
  console.error(
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).`
26099
+ `setup incomplete - ${skillsInstalled} workflow(s) installed; ${configured} base component(s) configured; ${failedCount} component(s) failed (${fatalBaseFailures} base, ${optionalFailed} optional, ${setupFailures.length} setup).`
26100
+ );
26101
+ } else if (lockContentionFailures.length > 0) {
26102
+ console.warn(
26103
+ `setup finished with ${lockContentionFailures.length} component(s) awaiting a re-run \u2014 ${configured} base component(s) configured.`
24997
26104
  );
24998
26105
  } else {
24999
26106
  console.log(
@@ -25398,6 +26505,49 @@ function confineCleanupPath(raw, userHome = homedir()) {
25398
26505
  if (!abs.startsWith(home + sep)) return null;
25399
26506
  return abs;
25400
26507
  }
26508
+ async function runReceiptOwnedTeardownUnlocked(ctx) {
26509
+ let receipt;
26510
+ try {
26511
+ receipt = await readSkillOwnershipReceipt(ctx);
26512
+ } catch (error) {
26513
+ return {
26514
+ ok: false,
26515
+ phase: "preflight",
26516
+ error: error instanceof Error ? error.message : String(error)
26517
+ };
26518
+ }
26519
+ try {
26520
+ for (const path of receipt.createdPaths) await verifyOwnedSkillPath(receipt, path);
26521
+ } catch (error) {
26522
+ return {
26523
+ ok: false,
26524
+ phase: "preflight",
26525
+ error: error instanceof Error ? error.message : String(error)
26526
+ };
26527
+ }
26528
+ try {
26529
+ const transaction = await withQuarantineTransaction(
26530
+ async () => {
26531
+ for (const path of receipt.createdPaths) await removeOwnedSkillPath(receipt, path, ctx);
26532
+ },
26533
+ async () => removeSkillOwnershipReceipt(ctx)
26534
+ );
26535
+ if (transaction.cleanupFailures.length > 0) {
26536
+ return {
26537
+ ok: false,
26538
+ phase: "verify",
26539
+ error: transaction.cleanupFailures.join("; ")
26540
+ };
26541
+ }
26542
+ } catch (error) {
26543
+ return {
26544
+ ok: false,
26545
+ phase: "verify",
26546
+ error: error instanceof Error ? error.message : String(error)
26547
+ };
26548
+ }
26549
+ return { ok: true, removedPaths: [...receipt.createdPaths] };
26550
+ }
25401
26551
  function canonicalPath(path) {
25402
26552
  let candidate = path;
25403
26553
  const missing = [];
@@ -25426,54 +26576,14 @@ async function runDeclaredTeardown(ctx) {
25426
26576
  const abort = dryRunGate(ctx);
25427
26577
  if (abort) return abort;
25428
26578
  if (isSkillOwnershipManaged(ctx.manifest)) {
25429
- let receipt;
25430
- try {
25431
- receipt = await readSkillOwnershipReceipt(ctx);
25432
- } catch (error) {
26579
+ if (!ctx.hostContext) {
25433
26580
  return {
25434
26581
  ok: false,
25435
26582
  phase: "preflight",
25436
- error: error instanceof Error ? error.message : String(error)
26583
+ error: "receipt-only uninstall requires a resolved host context"
25437
26584
  };
25438
26585
  }
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 };
26586
+ return withInstallOwnershipLock(ctx.hostContext, () => runReceiptOwnedTeardownUnlocked(ctx));
25477
26587
  }
25478
26588
  const cleanupTargets = [];
25479
26589
  const userHome = ctx.hostContext?.userHome ?? homedir();
@@ -25650,6 +26760,7 @@ async function runDeclaredTeardown(ctx) {
25650
26760
  var init_declaredTeardown = __esm({
25651
26761
  "src/uninstallers/lib/declaredTeardown.ts"() {
25652
26762
  init_componentPlan();
26763
+ init_installOwnershipLock();
25653
26764
  init_skillOwnershipReceipt();
25654
26765
  init_spawn();
25655
26766
  init_quarantineDelete();
@@ -25757,7 +26868,7 @@ var init_npmCli3 = __esm({
25757
26868
  cwd: ctx.hostContext.userHome,
25758
26869
  env: withHostInstallEnv(process.env, ctx.hostContext)
25759
26870
  } : {};
25760
- const result = await new Promise((resolve39) => {
26871
+ const result = await new Promise((resolve40) => {
25761
26872
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], {
25762
26873
  ...spawnOptions,
25763
26874
  windowsHide: true
@@ -25768,15 +26879,15 @@ var init_npmCli3 = __esm({
25768
26879
  });
25769
26880
  const timer = setTimeout(() => {
25770
26881
  child.kill("SIGKILL");
25771
- resolve39({ exitCode: -1, stderr: `${stderr}[timeout]` });
26882
+ resolve40({ exitCode: -1, stderr: `${stderr}[timeout]` });
25772
26883
  }, 3e4);
25773
26884
  child.on("error", (e) => {
25774
26885
  clearTimeout(timer);
25775
- resolve39({ exitCode: -1, stderr: e.message });
26886
+ resolve40({ exitCode: -1, stderr: e.message });
25776
26887
  });
25777
26888
  child.on("close", (code2) => {
25778
26889
  clearTimeout(timer);
25779
- resolve39({ exitCode: code2 ?? -1, stderr });
26890
+ resolve40({ exitCode: code2 ?? -1, stderr });
25780
26891
  });
25781
26892
  });
25782
26893
  if (result.exitCode !== 0) {
@@ -26374,6 +27485,99 @@ var init_uninstall = __esm({
26374
27485
  }
26375
27486
  });
26376
27487
 
27488
+ // src/cli/lib/ownedRefreshFlag.ts
27489
+ var ownedRefreshFlag_exports = {};
27490
+ __export(ownedRefreshFlag_exports, {
27491
+ OWNED_REFRESH_FLAG: () => OWNED_REFRESH_FLAG
27492
+ });
27493
+ var OWNED_REFRESH_FLAG;
27494
+ var init_ownedRefreshFlag = __esm({
27495
+ "src/cli/lib/ownedRefreshFlag.ts"() {
27496
+ OWNED_REFRESH_FLAG = "--internal-owned-refresh";
27497
+ }
27498
+ });
27499
+
27500
+ // src/cli/lib/ownedRefresh.ts
27501
+ var ownedRefresh_exports = {};
27502
+ __export(ownedRefresh_exports, {
27503
+ refreshOwnedState: () => refreshOwnedState,
27504
+ runOwnedRefreshEntry: () => runOwnedRefreshEntry,
27505
+ spawnOwnedRefresh: () => spawnOwnedRefresh
27506
+ });
27507
+ async function refreshOwnedState(context) {
27508
+ const { refreshOwnedUpdate: refreshOwnedUpdate2 } = await Promise.resolve().then(() => (init_refreshOwnedUpdate(), refreshOwnedUpdate_exports));
27509
+ const components = await refreshOwnedUpdate2(context);
27510
+ return {
27511
+ ok: !components.some((component2) => component2.status === "failed"),
27512
+ updated: components.filter((component2) => component2.status === "updated").map((c) => c.id),
27513
+ failed: components.filter((component2) => component2.status === "failed").map((c) => c.id)
27514
+ };
27515
+ }
27516
+ async function runOwnedRefreshEntry() {
27517
+ const { captureHostInstallContext: captureHostInstallContext3 } = await Promise.resolve().then(() => (init_hostInstallContext(), hostInstallContext_exports));
27518
+ const context = captureHostInstallContext3();
27519
+ const outcome = await refreshOwnedState(context);
27520
+ if (outcome.ok) {
27521
+ console.log(
27522
+ `[harnessed] owned state refreshed (${outcome.updated.length} component(s): ${outcome.updated.join(", ")})`
27523
+ );
27524
+ return 0;
27525
+ }
27526
+ console.warn(
27527
+ `[harnessed] owned state refresh incomplete (${outcome.failed.join(", ")}) \u2014 run 'harnessed setup' to finish`
27528
+ );
27529
+ return 1;
27530
+ }
27531
+ async function spawnOwnedRefresh(execPath, context, deps = {}, timeoutMs = OWNED_REFRESH_TIMEOUT_MS) {
27532
+ const spawnImpl = deps.spawn ?? spawn;
27533
+ return new Promise((resolve40) => {
27534
+ let child;
27535
+ try {
27536
+ child = spawnImpl(execPath, [OWNED_REFRESH_FLAG], {
27537
+ env: withHostInstallEnv(process.env, context),
27538
+ // stdout is dropped on purpose: the handover's result is the exit code,
27539
+ // and the parent owns the user-facing line. Keeping the child's stdout
27540
+ // empty also means an abrupt child exit cannot truncate a half-written
27541
+ // summary. stderr stays inherited so a failed refresh explains itself.
27542
+ stdio: ["ignore", "ignore", "inherit"],
27543
+ windowsHide: true,
27544
+ shell: false
27545
+ });
27546
+ } catch (error) {
27547
+ resolve40({
27548
+ ok: false,
27549
+ exitCode: null,
27550
+ error: error instanceof Error ? error.message : String(error)
27551
+ });
27552
+ return;
27553
+ }
27554
+ const timer = setTimeout(() => {
27555
+ try {
27556
+ killProcessTree(child);
27557
+ } catch {
27558
+ }
27559
+ resolve40({ ok: false, exitCode: null, error: `timed out after ${timeoutMs}ms` });
27560
+ }, timeoutMs);
27561
+ child.on("error", (error) => {
27562
+ clearTimeout(timer);
27563
+ resolve40({ ok: false, exitCode: null, error: error.message });
27564
+ });
27565
+ child.on("close", (code2) => {
27566
+ clearTimeout(timer);
27567
+ resolve40({ ok: code2 === 0, exitCode: code2 });
27568
+ });
27569
+ });
27570
+ }
27571
+ var OWNED_REFRESH_TIMEOUT_MS;
27572
+ var init_ownedRefresh = __esm({
27573
+ "src/cli/lib/ownedRefresh.ts"() {
27574
+ init_killTree();
27575
+ init_runClaudeArgs();
27576
+ init_ownedRefreshFlag();
27577
+ OWNED_REFRESH_TIMEOUT_MS = 18e4;
27578
+ }
27579
+ });
27580
+
26377
27581
  // src/cli/lib/migration-report.ts
26378
27582
  var migration_report_exports = {};
26379
27583
  __export(migration_report_exports, {
@@ -26489,6 +27693,17 @@ async function runCompiledFlow(opts, context) {
26489
27693
  console.log(
26490
27694
  ` note: ${r.bakPath} left in place (running image / rollback net) \u2014 gc sweeps it later`
26491
27695
  );
27696
+ const { spawnOwnedRefresh: spawnOwnedRefresh2 } = await Promise.resolve().then(() => (init_ownedRefresh(), ownedRefresh_exports));
27697
+ const refresh = await spawnOwnedRefresh2(process.execPath, context);
27698
+ if (refresh.ok) {
27699
+ console.log(
27700
+ `[harnessed] refreshed workflow skills + hooks for ${r.to} (owned state re-synced).`
27701
+ );
27702
+ } else {
27703
+ console.warn(
27704
+ `[harnessed] could not refresh skills/hooks after the update (${refresh.error ?? `exit ${refresh.exitCode}`}) \u2014 run 'harnessed setup' to finish.`
27705
+ );
27706
+ }
26492
27707
  try {
26493
27708
  const { gcCompiledArtifacts: gcCompiledArtifacts2 } = await Promise.resolve().then(() => (init_gc(), gc_exports));
26494
27709
  await gcCompiledArtifacts2({
@@ -26773,6 +27988,11 @@ if (!updateInvocation) {
26773
27988
  );
26774
27989
  });
26775
27990
  }
27991
+ var { OWNED_REFRESH_FLAG: OWNED_REFRESH_FLAG2 } = await Promise.resolve().then(() => (init_ownedRefreshFlag(), ownedRefreshFlag_exports));
27992
+ if (entryArgs.length === 1 && entryArgs[0] === OWNED_REFRESH_FLAG2) {
27993
+ const { runOwnedRefreshEntry: runOwnedRefreshEntry2 } = await Promise.resolve().then(() => (init_ownedRefresh(), ownedRefresh_exports));
27994
+ process.exit(await runOwnedRefreshEntry2());
27995
+ }
26776
27996
  var program = new Command();
26777
27997
  if (wantsUpdateEnvelope2(process.argv)) program.exitOverride();
26778
27998
  program.name("harnessed").description("AI coding harness package manager + composition orchestrator").version(package_default.version).option("--lang <code>", "output language: en | zh (auto-detect from $LANG / Intl if absent)");