harnessed 5.0.6 → 5.0.7

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.7",
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
  }
@@ -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;
@@ -9643,7 +9695,7 @@ async function withAppServer(deps, body) {
9643
9695
  const call = (method, params) => {
9644
9696
  if (closed) return Promise.reject(closed);
9645
9697
  const id = nextId++;
9646
- return new Promise((resolve39, reject) => {
9698
+ return new Promise((resolve40, reject) => {
9647
9699
  const timer = setTimeout(() => {
9648
9700
  pending.delete(id);
9649
9701
  reject(new RpcError("timeout", `${method} timed out after ${timeoutMs}ms`));
@@ -9651,7 +9703,7 @@ async function withAppServer(deps, body) {
9651
9703
  pending.set(id, {
9652
9704
  resolve: (v) => {
9653
9705
  clearTimeout(timer);
9654
- resolve39(v);
9706
+ resolve40(v);
9655
9707
  },
9656
9708
  reject: (e) => {
9657
9709
  clearTimeout(timer);
@@ -10577,25 +10629,25 @@ var init_discipline = __esm({
10577
10629
  );
10578
10630
  }
10579
10631
  });
10580
- async function loadDiscipline(basename9, packageRoot) {
10581
- const cached = _cache.get(basename9);
10632
+ async function loadDiscipline(basename10, packageRoot) {
10633
+ const cached = _cache.get(basename10);
10582
10634
  if (cached) return cached;
10583
- const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename9}.yaml`);
10635
+ const yamlPath = resolve(packageRoot, "workflows", "disciplines", `${basename10}.yaml`);
10584
10636
  const raw = await readFile(yamlPath, "utf8");
10585
10637
  const parsedRaw = parse(raw);
10586
10638
  if (!Value.Check(Discipline, parsedRaw)) {
10587
10639
  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}`);
10640
+ throw new Error(`Invalid discipline file ${basename10}.yaml: ${errors}`);
10589
10641
  }
10590
10642
  const parsed = parsedRaw;
10591
- _cache.set(basename9, parsed);
10643
+ _cache.set(basename10, parsed);
10592
10644
  return parsed;
10593
10645
  }
10594
10646
  async function loadAllApplied(disciplines_applied, packageRoot) {
10595
10647
  const applied = disciplines_applied && disciplines_applied.length > 0 ? disciplines_applied : DEFAULT_APPLIED;
10596
10648
  const out = /* @__PURE__ */ new Map();
10597
- for (const basename9 of applied) {
10598
- out.set(basename9, await loadDiscipline(basename9, packageRoot));
10649
+ for (const basename10 of applied) {
10650
+ out.set(basename10, await loadDiscipline(basename10, packageRoot));
10599
10651
  }
10600
10652
  return out;
10601
10653
  }
@@ -11117,7 +11169,7 @@ function realSpawn(req) {
11117
11169
  };
11118
11170
  }
11119
11171
  function runOnce(req, spawnFn, timeoutMs, onThreadId) {
11120
- return new Promise((resolve39, reject) => {
11172
+ return new Promise((resolve40, reject) => {
11121
11173
  const events = [];
11122
11174
  let garbageLines = 0;
11123
11175
  let stderr = "";
@@ -11138,7 +11190,7 @@ function runOnce(req, spawnFn, timeoutMs, onThreadId) {
11138
11190
  if (settled || !exited || openStreams > 0) return;
11139
11191
  settled = true;
11140
11192
  clearTimeout(timer);
11141
- resolve39({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
11193
+ resolve40({ exitCode: exited.code, signal: exited.signal, events, garbageLines, stderr });
11142
11194
  };
11143
11195
  const fail2 = (err2) => {
11144
11196
  if (settled) return;
@@ -15510,10 +15562,10 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15510
15562
  child.stderr?.setEncoding("utf8").on("data", (chunk) => {
15511
15563
  stderr += chunk;
15512
15564
  });
15513
- return await new Promise((resolve39) => {
15565
+ return await new Promise((resolve40) => {
15514
15566
  const timer = setTimeout(() => {
15515
15567
  killProcessTree(child);
15516
- resolve39({
15568
+ resolve40({
15517
15569
  ok: false,
15518
15570
  phase: "spawn",
15519
15571
  error: {
@@ -15534,7 +15586,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15534
15586
  child.on("error", (err2) => {
15535
15587
  clearTimeout(timer);
15536
15588
  const bashMissing = triedBash && err2.code === "ENOENT";
15537
- resolve39({
15589
+ resolve40({
15538
15590
  ok: false,
15539
15591
  phase: "spawn",
15540
15592
  error: {
@@ -15549,7 +15601,7 @@ async function spawnCmd(ctx, cmd, args, timeoutMs, opts) {
15549
15601
  });
15550
15602
  child.on("close", (code2) => {
15551
15603
  clearTimeout(timer);
15552
- resolve39({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
15604
+ resolve40({ ok: true, exitCode: code2 ?? -1, stdout: stdout2, stderr });
15553
15605
  });
15554
15606
  });
15555
15607
  }
@@ -16260,7 +16312,7 @@ function touch(binary, lease, source, scratch, context) {
16260
16312
  if (context) env = withHostInstallEnv(env, context);
16261
16313
  env.GSTACK_LEASE_DIR = shellPath(scratch, context);
16262
16314
  env.GSTACK_LEASE_LOCK_TRIES = "1";
16263
- return new Promise((resolve39, reject) => {
16315
+ return new Promise((resolve40, reject) => {
16264
16316
  const child = execFile(
16265
16317
  binary,
16266
16318
  [
@@ -16289,7 +16341,7 @@ function touch(binary, lease, source, scratch, context) {
16289
16341
  `official lease touch exit ${error.code ?? "unknown"}${error.killed ? " (timeout or termination)" : ""}: ${stderr.trim() || error.message}`
16290
16342
  )
16291
16343
  );
16292
- else resolve39();
16344
+ else resolve40();
16293
16345
  }
16294
16346
  );
16295
16347
  child.stdin?.end();
@@ -16829,7 +16881,7 @@ var init_verifyInstalled = __esm({
16829
16881
  }
16830
16882
  });
16831
16883
  function gitRevParseHead(cwd, timeoutMs = 1e4) {
16832
- return new Promise((resolve39) => {
16884
+ return new Promise((resolve40) => {
16833
16885
  const isWin = process.platform === "win32";
16834
16886
  const child = isWin ? spawn("cmd.exe", ["/c", "git", "rev-parse", "HEAD"], { cwd, windowsHide: true }) : spawn("git", ["rev-parse", "HEAD"], { cwd, shell: false });
16835
16887
  let stdout2 = "";
@@ -16838,15 +16890,15 @@ function gitRevParseHead(cwd, timeoutMs = 1e4) {
16838
16890
  });
16839
16891
  const timer = setTimeout(() => {
16840
16892
  killProcessTree(child);
16841
- resolve39({ sha: "", exit: -1 });
16893
+ resolve40({ sha: "", exit: -1 });
16842
16894
  }, timeoutMs);
16843
16895
  child.on("error", () => {
16844
16896
  clearTimeout(timer);
16845
- resolve39({ sha: "", exit: -1 });
16897
+ resolve40({ sha: "", exit: -1 });
16846
16898
  });
16847
16899
  child.on("close", (code2) => {
16848
16900
  clearTimeout(timer);
16849
- resolve39({ sha: stdout2.trim(), exit: code2 ?? -1 });
16901
+ resolve40({ sha: stdout2.trim(), exit: code2 ?? -1 });
16850
16902
  });
16851
16903
  });
16852
16904
  }
@@ -17144,7 +17196,12 @@ function isReviewedNeutralTeardown(manifest) {
17144
17196
  const spec = manifest.spec;
17145
17197
  const emptyCleanup = spec.uninstall?.cleanup_paths === void 0 || Array.isArray(spec.uninstall.cleanup_paths) && spec.uninstall.cleanup_paths.length === 0;
17146
17198
  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;
17199
+ 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;
17200
+ }
17201
+ function isDeclaredReceiptOnlyTeardown(manifest) {
17202
+ const uninstall = manifest.spec.uninstall;
17203
+ const resources = manifest.spec.ownership?.resources;
17204
+ return uninstall?.cmd.trim() === "true" && (uninstall.cleanup_paths === void 0 || uninstall.cleanup_paths.length === 0) && Array.isArray(resources) && resources.length > 0;
17148
17205
  }
17149
17206
  function resolveComponentPlan(manifest, context, operation) {
17150
17207
  const override = context.hostId === "codex" ? manifest.spec.harness_overrides?.codex : void 0;
@@ -17179,7 +17236,7 @@ function resolveComponentPlan(manifest, context, operation) {
17179
17236
  if (context.hostId === "codex" && operation === "uninstall") {
17180
17237
  const validName = /^[a-z0-9][a-z0-9-]*$/.test(effective.metadata.name);
17181
17238
  const portableHook = method === "cc-hook-add" && nativeTeardown && !override?.uninstall;
17182
- if (validName && (isReviewedNeutralTeardown(effective) || portableHook)) {
17239
+ if (validName && (isReviewedNeutralTeardown(effective) || isDeclaredReceiptOnlyTeardown(effective) || portableHook)) {
17183
17240
  return Object.freeze({ ...fields, status: "supported" });
17184
17241
  }
17185
17242
  let detail = `no safe codex uninstall contract for '${manifest.metadata.name}'`;
@@ -17684,6 +17741,25 @@ ${newEntry}
17684
17741
  };
17685
17742
  }
17686
17743
  });
17744
+ async function withInstallOwnershipLock(context, work) {
17745
+ const root = context.platform.stateRoot;
17746
+ await mkdir(root, { recursive: true });
17747
+ const release = await lockfile.lock(root, {
17748
+ lockfilePath: join(root, ".ownership.lock"),
17749
+ realpath: false,
17750
+ stale: 10 * 60 * 1e3,
17751
+ retries: { retries: 5, minTimeout: 25, maxTimeout: 250 }
17752
+ });
17753
+ try {
17754
+ return await work();
17755
+ } finally {
17756
+ await release();
17757
+ }
17758
+ }
17759
+ var init_installOwnershipLock = __esm({
17760
+ "src/installers/lib/installOwnershipLock.ts"() {
17761
+ }
17762
+ });
17687
17763
  function isDirectChild(root, target) {
17688
17764
  const rel = relative(root, target);
17689
17765
  return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) && dirname(target) === root;
@@ -17749,6 +17825,73 @@ async function restoreQuarantine(quarantinePath, target) {
17749
17825
  return error.message;
17750
17826
  }
17751
17827
  }
17828
+ async function rollbackQuarantines(transaction) {
17829
+ const failures = [];
17830
+ for (const quarantined of [...transaction.paths].reverse()) {
17831
+ const { snapshot, quarantinePath } = quarantined;
17832
+ try {
17833
+ await reverifyQuarantinedPath(quarantined);
17834
+ } catch (error) {
17835
+ const detail = error instanceof Error ? error.message : String(error);
17836
+ failures.push(
17837
+ `rollback reverify failed for ${snapshot.target}: ${detail}; retained at ${quarantinePath}`
17838
+ );
17839
+ continue;
17840
+ }
17841
+ const restoreError = await restoreQuarantine(quarantinePath, snapshot.target);
17842
+ if (restoreError !== null) {
17843
+ failures.push(
17844
+ `rollback failed for ${snapshot.target}: ${restoreError}; retained at ${quarantinePath}`
17845
+ );
17846
+ }
17847
+ }
17848
+ return failures;
17849
+ }
17850
+ async function finalizeQuarantines(transaction) {
17851
+ const failures = [];
17852
+ for (const quarantined of transaction.paths) {
17853
+ const { snapshot, quarantinePath } = quarantined;
17854
+ try {
17855
+ await reverifyQuarantinedPath(quarantined);
17856
+ } catch (error) {
17857
+ const detail = error instanceof Error ? error.message : String(error);
17858
+ failures.push(
17859
+ `cleanup reverify failed for ${snapshot.target}: ${detail}; retained at ${quarantinePath}`
17860
+ );
17861
+ continue;
17862
+ }
17863
+ try {
17864
+ await rm(
17865
+ quarantinePath,
17866
+ snapshot.isDirectory ? { recursive: true, force: true, maxRetries: 3 } : { force: true }
17867
+ );
17868
+ } catch (error) {
17869
+ const detail = error instanceof Error ? error.message : String(error);
17870
+ failures.push(
17871
+ `cleanup failed for ${snapshot.target}: ${detail}; retained at ${quarantinePath}`
17872
+ );
17873
+ }
17874
+ }
17875
+ return failures;
17876
+ }
17877
+ async function withQuarantineTransaction(operation, commit) {
17878
+ if (quarantineTransactions.getStore()) {
17879
+ throw new Error("nested quarantine transactions are not supported");
17880
+ }
17881
+ const transaction = { paths: [] };
17882
+ let value;
17883
+ try {
17884
+ value = await quarantineTransactions.run(transaction, operation);
17885
+ await commit();
17886
+ } catch (error) {
17887
+ const detail = error instanceof Error ? error.message : String(error);
17888
+ const rollbackFailures = await rollbackQuarantines(transaction);
17889
+ throw new Error(
17890
+ rollbackFailures.length === 0 ? detail : `${detail}; ${rollbackFailures.join("; ")}`
17891
+ );
17892
+ }
17893
+ return { value, cleanupFailures: await finalizeQuarantines(transaction) };
17894
+ }
17752
17895
  async function verifyQuarantine(snapshot, quarantinePath, verify) {
17753
17896
  const [{ canonicalRoot }, info] = await Promise.all([
17754
17897
  inspectRoot(snapshot.root),
@@ -17799,7 +17942,16 @@ async function verifyQuarantinedFile(snapshot, quarantinePath) {
17799
17942
  throw new Error(`refusing quarantined path outside authorized root: ${snapshot.target}`);
17800
17943
  }
17801
17944
  }
17802
- async function removeOwnedFileViaQuarantine(snapshot) {
17945
+ async function reverifyQuarantinedPath(quarantined) {
17946
+ const { snapshot, quarantinePath, verify } = quarantined;
17947
+ if (snapshot.isDirectory) {
17948
+ await verifyQuarantine(snapshot, quarantinePath, verify);
17949
+ return;
17950
+ }
17951
+ await verifyQuarantinedFile(snapshot, quarantinePath);
17952
+ await verify?.(quarantinePath);
17953
+ }
17954
+ async function removeOwnedFileViaQuarantine(snapshot, options = {}) {
17803
17955
  if (snapshot.isDirectory) {
17804
17956
  throw new Error(`refusing non-recursive removal of directory: ${snapshot.target}`);
17805
17957
  }
@@ -17814,6 +17966,7 @@ async function removeOwnedFileViaQuarantine(snapshot) {
17814
17966
  await rename(snapshot.target, quarantinePath);
17815
17967
  try {
17816
17968
  await verifyQuarantinedFile(snapshot, quarantinePath);
17969
+ await options.verify?.(quarantinePath);
17817
17970
  } catch (error) {
17818
17971
  const restoreError = await restoreQuarantine(quarantinePath, snapshot.target);
17819
17972
  const detail = error instanceof Error ? error.message : String(error);
@@ -17821,6 +17974,11 @@ async function removeOwnedFileViaQuarantine(snapshot) {
17821
17974
  restoreError === null ? detail : `${detail}; quarantine restore failed: ${restoreError}; retained at ${quarantinePath}`
17822
17975
  );
17823
17976
  }
17977
+ const transaction = quarantineTransactions.getStore();
17978
+ if (transaction) {
17979
+ transaction.paths.push({ snapshot, quarantinePath, verify: options.verify });
17980
+ return;
17981
+ }
17824
17982
  await rm(quarantinePath, { force: true });
17825
17983
  }
17826
17984
  async function removeOwnedDirectoryViaQuarantine(snapshot, options = {}) {
@@ -17845,12 +18003,64 @@ async function removeOwnedDirectoryViaQuarantine(snapshot, options = {}) {
17845
18003
  restoreError === null ? detail : `${detail}; quarantine restore failed: ${restoreError}; retained at ${quarantinePath}`
17846
18004
  );
17847
18005
  }
18006
+ const transaction = quarantineTransactions.getStore();
18007
+ if (transaction) {
18008
+ transaction.paths.push({ snapshot, quarantinePath, verify: options.verify });
18009
+ return;
18010
+ }
17848
18011
  await rm(quarantinePath, { recursive: true, force: true, maxRetries: 3 });
17849
18012
  }
18013
+ var quarantineTransactions;
17850
18014
  var init_quarantineDelete = __esm({
17851
18015
  "src/lib/quarantineDelete.ts"() {
18016
+ quarantineTransactions = new AsyncLocalStorage();
17852
18017
  }
17853
18018
  });
18019
+ function receiptParentFailure(reason) {
18020
+ return new Error(`skill ownership receipt parent ${reason}`);
18021
+ }
18022
+ async function captureSkillOwnershipReceiptParent(receiptPath, options = {}) {
18023
+ const parent = dirname(resolve(receiptPath));
18024
+ if (basename(parent) !== "skill-ownership") {
18025
+ throw receiptParentFailure("has an unexpected path");
18026
+ }
18027
+ let info;
18028
+ try {
18029
+ info = await lstat(parent, { bigint: true });
18030
+ } catch (error) {
18031
+ if (error.code !== "ENOENT") throw error;
18032
+ if (!options.create) return null;
18033
+ await mkdir(parent, { recursive: true });
18034
+ info = await lstat(parent, { bigint: true });
18035
+ }
18036
+ if (info.isSymbolicLink() || !info.isDirectory()) {
18037
+ throw receiptParentFailure("is a symlink, junction, reparse redirect, or non-directory");
18038
+ }
18039
+ const [canonicalPath2, canonicalStateRoot] = await Promise.all([
18040
+ realpath(parent),
18041
+ realpath(dirname(parent))
18042
+ ]);
18043
+ if (resolve(canonicalPath2) !== resolve(canonicalStateRoot, basename(parent))) {
18044
+ throw receiptParentFailure("canonical path is redirected");
18045
+ }
18046
+ const canonicalInfo = await lstat(canonicalPath2, { bigint: true });
18047
+ if (canonicalInfo.isSymbolicLink() || !canonicalInfo.isDirectory() || canonicalInfo.dev !== info.dev || canonicalInfo.ino !== info.ino) {
18048
+ throw receiptParentFailure("canonical identity is not a regular directory");
18049
+ }
18050
+ return {
18051
+ path: parent,
18052
+ canonicalPath: resolve(canonicalPath2),
18053
+ device: info.dev,
18054
+ inode: info.ino,
18055
+ type: "directory"
18056
+ };
18057
+ }
18058
+ async function assertSkillOwnershipReceiptParent(expected) {
18059
+ const current = await captureSkillOwnershipReceiptParent(join(expected.path, ".identity-check"));
18060
+ if (!current || current.canonicalPath !== expected.canonicalPath || current.device !== expected.device || current.inode !== expected.inode || current.type !== expected.type) {
18061
+ throw receiptParentFailure("identity changed");
18062
+ }
18063
+ }
17854
18064
  function receiptContext(ctx) {
17855
18065
  const platform = ctx.hostContext?.platform ?? detectPlatform();
17856
18066
  return {
@@ -17860,8 +18070,11 @@ function receiptContext(ctx) {
17860
18070
  stateRoot: resolve(platform.stateRoot)
17861
18071
  };
17862
18072
  }
17863
- function fail(reason) {
17864
- return new Error(`skill ownership receipt ${reason}; run repair or reinstall before uninstalling`);
18073
+ function isSkillOwnershipReceiptError(error) {
18074
+ return error instanceof SkillOwnershipReceiptError;
18075
+ }
18076
+ function fail(reason, kind = "corrupt") {
18077
+ return new SkillOwnershipReceiptError(kind, reason);
17865
18078
  }
17866
18079
  function canonicalJson(value) {
17867
18080
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
@@ -17873,7 +18086,10 @@ function canonicalJson(value) {
17873
18086
  function ownershipFingerprint(ctx) {
17874
18087
  const value = {
17875
18088
  metadata: ctx.manifest.metadata,
17876
- install: ctx.manifest.spec.install
18089
+ install: ctx.manifest.spec.install,
18090
+ ...ctx.manifest.spec.ownership !== void 0 && {
18091
+ ownership: ctx.manifest.spec.ownership
18092
+ } || {}
17877
18093
  };
17878
18094
  return createHash("sha256").update(canonicalJson(value)).digest("hex");
17879
18095
  }
@@ -17881,13 +18097,64 @@ function pathInsideRoot(root, path) {
17881
18097
  const rel = relative(root, path);
17882
18098
  return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
17883
18099
  }
18100
+ function rootForPath(roots, path) {
18101
+ return roots.find((root) => dirname(path) === root) ?? roots.find((root) => pathInsideRoot(root, path));
18102
+ }
18103
+ function declaredRootPath(ctx, root) {
18104
+ const host = ctx.hostContext;
18105
+ if (!host) return void 0;
18106
+ const roots = {
18107
+ "platform-skills": host.platform.skillsDir,
18108
+ "native-home": host.nativeHome,
18109
+ "host-agents": join(host.nativeHome, "agents"),
18110
+ "host-commands": host.platform.commandsDir
18111
+ };
18112
+ return roots[root] ? resolve(roots[root]) : void 0;
18113
+ }
18114
+ async function matchesDeclaredResource(ctx, path, kind, actualPath = path) {
18115
+ const ownership = ctx.manifest.spec.ownership;
18116
+ if (ownership === void 0) {
18117
+ if (kind !== "directory") return false;
18118
+ const roots = skillRootsForContext(ctx).map((root) => resolve(root));
18119
+ return roots.includes(resolve(dirname(path))) && authorizedSkillNames(ctx).includes(basename(path));
18120
+ }
18121
+ const resources = ownership.resources;
18122
+ if (!Array.isArray(resources)) return false;
18123
+ if (resources.length === 0) return false;
18124
+ for (const resource of resources) {
18125
+ const root = declaredRootPath(ctx, resource.root);
18126
+ if (!root || resource.kind !== kind || dirname(path) !== root) continue;
18127
+ const name = path.slice(root.length + 1);
18128
+ const names = resource.selector?.names;
18129
+ const prefix = resource.selector?.prefix;
18130
+ if (!names?.includes(name) && !(prefix && name.startsWith(prefix))) continue;
18131
+ const markerPath = resource.marker?.path ? join(actualPath, resource.marker.path) : actualPath;
18132
+ if (kind === "directory" && !pathInsideRoot(actualPath, markerPath)) continue;
18133
+ try {
18134
+ const targetInfo = await lstat(actualPath);
18135
+ const markerInfo = await lstat(markerPath);
18136
+ if (targetInfo.isSymbolicLink() || markerInfo.isSymbolicLink() || !markerInfo.isFile() || kind === "directory" && !targetInfo.isDirectory() || kind === "file" && !targetInfo.isFile())
18137
+ continue;
18138
+ if (kind === "directory") {
18139
+ const [physicalPath, physicalMarker] = await Promise.all([
18140
+ realpath(actualPath),
18141
+ realpath(markerPath)
18142
+ ]);
18143
+ if (!pathInsideRoot(physicalPath, physicalMarker)) continue;
18144
+ }
18145
+ if ((await readFile(markerPath, "utf8")).includes(resource.marker.contains)) return true;
18146
+ } catch {
18147
+ }
18148
+ }
18149
+ return false;
18150
+ }
17884
18151
  function authorizedSkillNames(ctx) {
17885
18152
  const install = ctx.manifest.spec.install;
17886
18153
  const declared = install.installs_skills;
17887
18154
  const names = Array.isArray(declared) ? declared.filter((name) => typeof name === "string" && name.length > 0) : [];
17888
18155
  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]);
18156
+ const selected2 = install.cmd.match(/(?:^|\s)--skill(?:=|\s+)([a-zA-Z0-9][a-zA-Z0-9._-]*)/);
18157
+ if (selected2?.[1]) names.push(selected2[1]);
17891
18158
  }
17892
18159
  if (names.some((name) => !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name))) {
17893
18160
  throw fail("has an invalid declared skill name");
@@ -17946,17 +18213,20 @@ function validateCreatedPaths(skillRoots, createdPaths) {
17946
18213
  throw fail("contains a non-absolute path");
17947
18214
  }
17948
18215
  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}`);
18216
+ const root = rootForPath(roots, path);
18217
+ if (!root || dirname(path) !== root)
18218
+ throw new Error(`skill ownership path is outside an allowed skill root: ${path}`);
17953
18219
  return path;
17954
18220
  });
17955
18221
  }
18222
+ function requireCreatedPaths(paths) {
18223
+ if (paths.length === 0) throw fail("is empty");
18224
+ }
17956
18225
  function isSkillOwnershipManaged(ctx) {
17957
18226
  const install = ctx.spec.install;
17958
18227
  const installsSkills = install.installs_skills;
17959
- return install.method === "npx-skill-installer" || Array.isArray(installsSkills) && installsSkills.length > 0;
18228
+ const resources = ctx.spec.ownership?.resources;
18229
+ return install.method === "npx-skill-installer" || Array.isArray(resources) && resources.length > 0 || Array.isArray(installsSkills) && installsSkills.length > 0;
17960
18230
  }
17961
18231
  function skillOwnershipReceiptPath(ctx) {
17962
18232
  const binding = receiptContext(ctx);
@@ -17969,57 +18239,82 @@ async function writeSkillOwnershipReceipt(ctx, skillRoots, createdPaths) {
17969
18239
  const binding = receiptContext(ctx);
17970
18240
  const roots = normalizeRoots(skillRoots).sort();
17971
18241
  const paths = validateCreatedPaths(roots, createdPaths).sort();
18242
+ requireCreatedPaths(paths);
17972
18243
  const contentSha256 = {};
18244
+ const pathKinds = {};
17973
18245
  for (const path2 of paths) {
17974
- const root = roots.find((candidate) => pathInsideRoot(candidate, path2));
18246
+ const root = rootForPath(roots, path2);
17975
18247
  if (!root) throw fail(`contains a path outside an allowed skill root: ${path2}`);
18248
+ if (dirname(path2) !== root)
18249
+ throw fail(`target is not a direct child of its captured root: ${path2}`);
17976
18250
  const info = await lstat(path2);
17977
18251
  if (info.isSymbolicLink()) throw fail(`target is a symbolic link: ${path2}`);
17978
- if (!info.isDirectory()) throw fail(`target is not a real directory: ${path2}`);
18252
+ if (!info.isDirectory() && !info.isFile()) throw fail(`target is not a regular path: ${path2}`);
17979
18253
  const [physicalRoot, physicalPath] = await Promise.all([realpath(root), realpath(path2)]);
17980
18254
  if (!pathInsideRoot(physicalRoot, physicalPath))
17981
18255
  throw fail(`target escapes its captured skill root: ${path2}`);
17982
- contentSha256[path2] = await hashSkillTree(path2);
18256
+ contentSha256[path2] = info.isDirectory() ? await hashSkillTree(path2) : createHash("sha256").update(await readFile(path2)).digest("hex");
18257
+ pathKinds[path2] = info.isDirectory() ? "directory" : "file";
18258
+ if (!await matchesDeclaredResource(ctx, path2, pathKinds[path2])) {
18259
+ throw fail("contains a path without a declared ownership marker");
18260
+ }
17983
18261
  }
17984
18262
  const receipt = {
17985
- version: 2,
18263
+ version: 3,
17986
18264
  component: binding.component,
17987
18265
  hostId: binding.hostId,
17988
18266
  nativeRoot: binding.nativeRoot,
17989
18267
  manifestSha256: ownershipFingerprint(ctx),
17990
18268
  skillRoots: roots,
17991
18269
  createdPaths: paths,
17992
- contentSha256
18270
+ contentSha256,
18271
+ pathKinds
17993
18272
  };
17994
18273
  const path = skillOwnershipReceiptPath(ctx);
17995
- await mkdir(dirname(path), { recursive: true });
18274
+ const parent = await captureSkillOwnershipReceiptParent(path, { create: true });
18275
+ if (!parent) throw receiptParentFailure("could not be created");
17996
18276
  const tmpPath = `${path}.${process.pid}.${Date.now()}.tmp`;
18277
+ await assertSkillOwnershipReceiptParent(parent);
17997
18278
  await writeFile(tmpPath, `${JSON.stringify(receipt, null, 2)}
17998
18279
  `, "utf8");
18280
+ await assertSkillOwnershipReceiptParent(parent);
17999
18281
  await rename(tmpPath, path);
18282
+ await assertSkillOwnershipReceiptParent(parent);
18000
18283
  }
18001
18284
  async function readSkillOwnershipReceipt(ctx) {
18002
18285
  const path = skillOwnershipReceiptPath(ctx);
18286
+ const parent = await captureSkillOwnershipReceiptParent(path);
18287
+ if (!parent) throw fail("is missing", "missing");
18003
18288
  let value;
18004
18289
  try {
18005
- value = JSON.parse(await readFile(path, "utf8"));
18290
+ const bytes = await readFile(path, "utf8");
18291
+ await assertSkillOwnershipReceiptParent(parent);
18292
+ value = JSON.parse(bytes);
18006
18293
  } catch (error) {
18007
- if (error.code === "ENOENT") throw fail("is missing");
18294
+ if (error.code === "ENOENT") throw fail("is missing", "missing");
18008
18295
  throw fail("is corrupt");
18009
18296
  }
18010
18297
  if (!value || typeof value !== "object") throw fail("is corrupt");
18011
18298
  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") {
18299
+ if (receipt.version !== 3) throw fail("is legacy or unsupported", "legacy");
18300
+ 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
18301
  throw fail("is corrupt");
18015
18302
  }
18303
+ requireCreatedPaths(receipt.createdPaths);
18016
18304
  const binding = receiptContext(ctx);
18017
18305
  if (receipt.component !== binding.component || receipt.hostId !== binding.hostId || resolve(receipt.nativeRoot) !== binding.nativeRoot) {
18018
18306
  throw fail("binding does not match the active component and host root");
18019
18307
  }
18020
18308
  if (receipt.manifestSha256 !== ownershipFingerprint(ctx)) throw fail("manifest identity changed");
18021
18309
  const currentRoots = new Set(
18022
- skillRootsForContext(ctx).map((root) => resolve(root))
18310
+ [
18311
+ ...skillRootsForContext(ctx),
18312
+ ...ctx.hostContext ? [
18313
+ ctx.hostContext.nativeHome,
18314
+ join(ctx.hostContext.nativeHome, "agents"),
18315
+ ctx.hostContext.platform.commandsDir
18316
+ ] : []
18317
+ ].map((root) => resolve(root))
18023
18318
  );
18024
18319
  const normalizedReceiptRoots = normalizeRoots(receipt.skillRoots);
18025
18320
  if (normalizedReceiptRoots.some((root) => !currentRoots.has(root))) {
@@ -18034,50 +18329,244 @@ async function readSkillOwnershipReceipt(ctx) {
18034
18329
  }
18035
18330
  for (const path2 of createdPaths) {
18036
18331
  const digest = receipt.contentSha256[path2];
18037
- if (typeof digest !== "string" || !/^[a-f0-9]{64}$/.test(digest)) {
18332
+ const kind = receipt.pathKinds[path2];
18333
+ const root = rootForPath(skillRoots, path2);
18334
+ if (!root || dirname(path2) !== root || kind !== "file" && kind !== "directory" || typeof digest !== "string" || !/^[a-f0-9]{64}$/.test(digest)) {
18038
18335
  throw fail("contains an invalid or undeclared owned skill path");
18039
18336
  }
18337
+ if (!await matchesDeclaredResource(ctx, path2, kind)) {
18338
+ throw fail("contains a path without a declared ownership marker");
18339
+ }
18340
+ }
18341
+ if (Object.keys(receipt.contentSha256).length !== createdPaths.length || Object.keys(receipt.contentSha256).some((path2) => !createdPaths.includes(path2))) {
18342
+ throw fail("contains undeclared content digests");
18040
18343
  }
18041
18344
  return {
18042
- version: receipt.version,
18345
+ version: 3,
18043
18346
  component: receipt.component,
18044
18347
  hostId: receipt.hostId,
18045
18348
  nativeRoot: binding.nativeRoot,
18046
18349
  manifestSha256: receipt.manifestSha256,
18047
18350
  skillRoots,
18048
18351
  createdPaths,
18049
- contentSha256: receipt.contentSha256
18352
+ contentSha256: receipt.contentSha256,
18353
+ pathKinds: receipt.pathKinds
18050
18354
  };
18051
18355
  }
18052
18356
  async function verifyOwnedSkillPath(receipt, path, actualPath = path) {
18053
18357
  const root = receipt.skillRoots.find((candidate) => dirname(path) === candidate);
18054
18358
  if (!root) throw fail("contains an owned path outside its captured roots");
18055
18359
  const [rootInfo, targetInfo] = await Promise.all([lstat(root), lstat(actualPath)]);
18056
- if (rootInfo.isSymbolicLink() || targetInfo.isSymbolicLink() || !rootInfo.isDirectory() || !targetInfo.isDirectory()) {
18360
+ if (rootInfo.isSymbolicLink() || targetInfo.isSymbolicLink() || !rootInfo.isDirectory()) {
18057
18361
  throw fail("target is a symbolic link, junction, or non-directory");
18058
18362
  }
18363
+ const expectedKind = receipt.pathKinds[path];
18364
+ if (expectedKind !== (targetInfo.isDirectory() ? "directory" : "file")) {
18365
+ throw fail("target type changed after installation");
18366
+ }
18059
18367
  const [physicalRoot, physicalPath] = await Promise.all([realpath(root), realpath(actualPath)]);
18060
18368
  if (dirname(physicalPath) !== physicalRoot) throw fail("target escapes its captured skill root");
18061
- if (await hashSkillTree(actualPath) !== receipt.contentSha256[path]) {
18369
+ const digest = targetInfo.isDirectory() ? await hashSkillTree(actualPath) : createHash("sha256").update(await readFile(actualPath)).digest("hex");
18370
+ if (digest !== receipt.contentSha256[path]) {
18062
18371
  throw fail("target content changed after installation");
18063
18372
  }
18064
18373
  }
18065
- async function removeOwnedSkillPath(receipt, path) {
18374
+ async function removeOwnedSkillPath(receipt, path, ctx) {
18066
18375
  const root = receipt.skillRoots.find((candidate) => dirname(path) === candidate);
18067
18376
  if (!root) throw fail("contains an owned path outside its captured roots");
18377
+ await verifyOwnedSkillPath(receipt, path);
18068
18378
  const snapshot = await prepareOwnedPathRemoval(root, path);
18069
- await removeOwnedDirectoryViaQuarantine(snapshot, {
18070
- verify: async (quarantinePath) => verifyOwnedSkillPath(receipt, path, quarantinePath)
18071
- });
18379
+ const verifyQuarantinedOwnership = async (quarantinePath) => {
18380
+ await verifyOwnedSkillPath(receipt, path, quarantinePath);
18381
+ if (ctx && !await matchesDeclaredResource(
18382
+ ctx,
18383
+ path,
18384
+ receipt.pathKinds[path],
18385
+ quarantinePath
18386
+ )) {
18387
+ throw fail("target no longer matches its declared ownership marker");
18388
+ }
18389
+ };
18390
+ if (snapshot.isDirectory) {
18391
+ await removeOwnedDirectoryViaQuarantine(snapshot, {
18392
+ verify: verifyQuarantinedOwnership
18393
+ });
18394
+ } else {
18395
+ await removeOwnedFileViaQuarantine(snapshot, {
18396
+ verify: verifyQuarantinedOwnership
18397
+ });
18398
+ }
18072
18399
  }
18073
18400
  async function removeSkillOwnershipReceipt(ctx) {
18074
- await rm(skillOwnershipReceiptPath(ctx), { force: true });
18401
+ const path = skillOwnershipReceiptPath(ctx);
18402
+ const parent = await captureSkillOwnershipReceiptParent(path);
18403
+ if (!parent) return;
18404
+ await assertSkillOwnershipReceiptParent(parent);
18405
+ await rm(path, { force: true });
18406
+ await assertSkillOwnershipReceiptParent(parent);
18075
18407
  }
18408
+ var SkillOwnershipReceiptError;
18076
18409
  var init_skillOwnershipReceipt = __esm({
18077
18410
  "src/installers/lib/skillOwnershipReceipt.ts"() {
18078
18411
  init_quarantineDelete();
18079
18412
  init_platform();
18080
18413
  init_packSkillAudit();
18414
+ SkillOwnershipReceiptError = class extends Error {
18415
+ constructor(kind, reason) {
18416
+ super(`skill ownership receipt ${reason}; run repair or reinstall before uninstalling`);
18417
+ this.kind = kind;
18418
+ this.name = "SkillOwnershipReceiptError";
18419
+ }
18420
+ kind;
18421
+ };
18422
+ }
18423
+ });
18424
+ function isResource(value) {
18425
+ if (!value || typeof value !== "object") return false;
18426
+ const resource = value;
18427
+ const selector = resource.selector;
18428
+ const marker = resource.marker;
18429
+ const roots = ["platform-skills", "native-home", "host-agents", "host-commands"];
18430
+ 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);
18431
+ const hasPrefix = typeof selector?.prefix === "string" && selector.prefix.length > 0;
18432
+ 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));
18433
+ }
18434
+ function isSafeMarkerPath(value) {
18435
+ 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 !== "..");
18436
+ }
18437
+ function resourcesFor(ctx) {
18438
+ const ownership = ctx.manifest.spec.ownership;
18439
+ if (!Array.isArray(ownership?.resources)) return [];
18440
+ if (!ownership.resources.every(isResource)) throw new Error("invalid ownership declaration");
18441
+ return ownership.resources;
18442
+ }
18443
+ function rootPath(ctx, root) {
18444
+ const host = ctx.hostContext;
18445
+ if (!host) return null;
18446
+ const roots = {
18447
+ "platform-skills": host.platform.skillsDir,
18448
+ "native-home": host.nativeHome,
18449
+ "host-agents": join(host.nativeHome, "agents"),
18450
+ "host-commands": host.platform.commandsDir
18451
+ };
18452
+ return resolve(roots[root]);
18453
+ }
18454
+ function isInside(root, path) {
18455
+ const rel = relative(root, path);
18456
+ return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel);
18457
+ }
18458
+ function selected(resource, name) {
18459
+ const { names, prefix } = resource.selector;
18460
+ return Boolean(names?.includes(name) || prefix?.length && name.startsWith(prefix));
18461
+ }
18462
+ async function regularMarker(candidate, canonicalCandidate, resource) {
18463
+ const markerRelativePath = resource.marker.path;
18464
+ if (resource.kind === "directory" && !markerRelativePath) return false;
18465
+ const markerPath = resource.kind === "file" ? candidate : resolve(candidate, markerRelativePath);
18466
+ if (resource.kind === "directory" && !isInside(candidate, markerPath)) return false;
18467
+ try {
18468
+ if (resource.kind === "directory") {
18469
+ const parts = relative(candidate, markerPath).split(sep);
18470
+ let current = candidate;
18471
+ for (const [index, part] of parts.entries()) {
18472
+ current = join(current, part);
18473
+ const info = await lstat(current);
18474
+ if (info.isSymbolicLink()) return false;
18475
+ if (index < parts.length - 1 && !info.isDirectory()) return false;
18476
+ if (index === parts.length - 1 && !info.isFile()) return false;
18477
+ }
18478
+ if (!isInside(canonicalCandidate, await realpath(markerPath))) return false;
18479
+ }
18480
+ return (await readFile(markerPath, "utf8")).includes(resource.marker.contains);
18481
+ } catch {
18482
+ return false;
18483
+ }
18484
+ }
18485
+ async function discoverResource(ctx, resource) {
18486
+ const root = rootPath(ctx, resource.root);
18487
+ if (!root) return [];
18488
+ let canonicalRoot;
18489
+ let entries;
18490
+ try {
18491
+ const rootInfo = await lstat(root);
18492
+ if (rootInfo.isSymbolicLink() || !rootInfo.isDirectory()) return [];
18493
+ [canonicalRoot, entries] = await Promise.all([
18494
+ realpath(root),
18495
+ readdir(root, { withFileTypes: true })
18496
+ ]);
18497
+ } catch {
18498
+ return [];
18499
+ }
18500
+ const resources = [];
18501
+ for (const entry of entries) {
18502
+ if (!selected(resource, entry.name)) continue;
18503
+ const path = resolve(root, entry.name);
18504
+ try {
18505
+ const info = await lstat(path);
18506
+ if (info.isSymbolicLink()) continue;
18507
+ if (resource.kind === "directory" ? !info.isDirectory() : !info.isFile()) continue;
18508
+ const canonicalPath2 = await realpath(path);
18509
+ if (dirname(canonicalPath2) !== canonicalRoot) continue;
18510
+ if (!await regularMarker(path, canonicalPath2, resource)) continue;
18511
+ resources.push({ path, root, kind: resource.kind });
18512
+ } catch {
18513
+ }
18514
+ }
18515
+ return resources;
18516
+ }
18517
+ async function snapshotResource(ctx, resource) {
18518
+ const root = rootPath(ctx, resource.root);
18519
+ if (!root) return [];
18520
+ let entries;
18521
+ try {
18522
+ const rootInfo = await lstat(root);
18523
+ if (rootInfo.isSymbolicLink() || !rootInfo.isDirectory()) return [];
18524
+ entries = await readdir(root, { withFileTypes: true });
18525
+ } catch {
18526
+ return [];
18527
+ }
18528
+ const resources = [];
18529
+ for (const entry of entries) {
18530
+ if (!selected(resource, entry.name)) continue;
18531
+ const path = resolve(root, entry.name);
18532
+ resources.push({ path, root, kind: resource.kind });
18533
+ }
18534
+ return resources;
18535
+ }
18536
+ async function discoverDeclaredOwnership(ctx) {
18537
+ const declarations = resourcesFor(ctx);
18538
+ const discovered = (await Promise.all(declarations.map((resource) => discoverResource(ctx, resource)))).flat().sort((left, right) => left.path.localeCompare(right.path));
18539
+ const resources = [...new Map(discovered.map((resource) => [resource.path, resource])).values()];
18540
+ return {
18541
+ resources,
18542
+ roots: [
18543
+ ...new Set(
18544
+ declarations.map((resource) => rootPath(ctx, resource.root)).filter((root) => root !== null)
18545
+ )
18546
+ ].sort(),
18547
+ paths: resources.map((resource) => resource.path).sort()
18548
+ };
18549
+ }
18550
+ async function snapshotDeclaredOwnership(ctx) {
18551
+ const declarations = resourcesFor(ctx);
18552
+ const discovered = (await Promise.all(declarations.map((resource) => snapshotResource(ctx, resource)))).flat().sort((left, right) => left.path.localeCompare(right.path));
18553
+ const resources = [...new Map(discovered.map((resource) => [resource.path, resource])).values()];
18554
+ return {
18555
+ resources,
18556
+ roots: [
18557
+ ...new Set(
18558
+ declarations.map((resource) => rootPath(ctx, resource.root)).filter((root) => root !== null)
18559
+ )
18560
+ ].sort(),
18561
+ paths: resources.map((resource) => resource.path).sort()
18562
+ };
18563
+ }
18564
+ async function writeDeclaredOwnershipReceipt(ctx, ownership) {
18565
+ await writeSkillOwnershipReceipt(ctx, ownership.roots, ownership.paths);
18566
+ }
18567
+ var init_ownershipContract = __esm({
18568
+ "src/installers/lib/ownershipContract.ts"() {
18569
+ init_skillOwnershipReceipt();
18081
18570
  }
18082
18571
  });
18083
18572
  function detectLevel(cmd) {
@@ -18100,7 +18589,7 @@ function unprovenPackTarget(ctx) {
18100
18589
  }
18101
18590
  };
18102
18591
  }
18103
- var installNpmCli;
18592
+ var installNpmCliUnlocked, installNpmCli;
18104
18593
  var init_npmCli2 = __esm({
18105
18594
  "src/installers/npmCli.ts"() {
18106
18595
  init_backup();
@@ -18108,6 +18597,8 @@ var init_npmCli2 = __esm({
18108
18597
  init_diff();
18109
18598
  init_err();
18110
18599
  init_idempotent();
18600
+ init_installOwnershipLock();
18601
+ init_ownershipContract();
18111
18602
  init_packSkillAudit();
18112
18603
  init_preflight();
18113
18604
  init_skillOwnershipReceipt();
@@ -18115,7 +18606,7 @@ var init_npmCli2 = __esm({
18115
18606
  init_state2();
18116
18607
  init_verifyInstalled();
18117
18608
  init_verifyMessage();
18118
- installNpmCli = async (ctx) => {
18609
+ installNpmCliUnlocked = async (ctx) => {
18119
18610
  const install = ctx.manifest.spec.install;
18120
18611
  if (install.method !== "npm-cli") {
18121
18612
  return {
@@ -18136,42 +18627,36 @@ var init_npmCli2 = __esm({
18136
18627
  const e = pre.errors[0] ?? err(ctx, "/", "preflight failed (no detail)", "preflight");
18137
18628
  return { ok: false, phase: "preflight", error: e };
18138
18629
  }
18630
+ const managesSkillOwnership = isSkillOwnershipManaged(ctx.manifest);
18631
+ const ownershipCandidateSnapshot = managesSkillOwnership ? await snapshotDeclaredOwnership(ctx) : void 0;
18632
+ const usesDeclaredOwnership = Array.isArray(
18633
+ ctx.manifest.spec.ownership?.resources
18634
+ );
18139
18635
  let existingPackTarget = false;
18140
18636
  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
- }
18637
+ if (usesDeclaredOwnership) {
18638
+ existingPackTarget = (ownershipCandidateSnapshot?.paths.length ?? 0) > 0;
18639
+ } else {
18640
+ const names = [ctx.manifest.metadata.name, ...install.installs_skills ?? []];
18641
+ if (names.some((name) => !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name)))
18642
+ return unprovenPackTarget(ctx);
18643
+ const roots = [
18644
+ .../* @__PURE__ */ new Set([
18645
+ ctx.hostContext.platform.skillsDir,
18646
+ join(ctx.hostContext.nativeHome, "skills"),
18647
+ join(ctx.hostContext.userHome, ".agents", "skills")
18648
+ ])
18649
+ ];
18650
+ const targets = roots.flatMap((root) => names.map((name) => join(root, name)));
18651
+ for (const target of targets) {
18652
+ if (await lstat(target).then(
18653
+ () => true,
18654
+ (error) => error.code !== "ENOENT"
18655
+ ))
18656
+ existingPackTarget = true;
18165
18657
  }
18166
18658
  }
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);
18659
+ if (ctx.opts.updateInstalled && !usesDeclaredOwnership) return unprovenPackTarget(ctx);
18175
18660
  }
18176
18661
  if (await isAlreadyInstalled(ctx)) {
18177
18662
  const verifyFailure2 = await verifyInstalled(ctx, { neutralCwd: true });
@@ -18221,10 +18706,9 @@ var init_npmCli2 = __esm({
18221
18706
  const bk = await backup(plan, ctx);
18222
18707
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
18223
18708
  await warnDeclaredCollisions(ctx);
18224
- const managesSkillOwnership = isSkillOwnershipManaged(ctx.manifest);
18225
18709
  const skillRoots = managesSkillOwnership ? skillRootsForContext(ctx) : [];
18226
18710
  const pathSnapshot = new Set(
18227
- managesSkillOwnership ? await declaredSkillPaths(ctx, skillRoots) : []
18711
+ usesDeclaredOwnership ? ownershipCandidateSnapshot?.paths ?? [] : managesSkillOwnership ? await declaredSkillPaths(ctx, skillRoots) : []
18228
18712
  );
18229
18713
  const packSnapshot = await snapshotSkillNames(
18230
18714
  ...ctx.hostContext ? [ctx.hostContext.platform.skillsDir] : []
@@ -18254,12 +18738,20 @@ var init_npmCli2 = __esm({
18254
18738
  if (verifyFailure) return { ...verifyFailure, backupId: bk.backupId };
18255
18739
  if (managesSkillOwnership) {
18256
18740
  try {
18257
- const afterPaths = await declaredSkillPaths(ctx, skillRoots);
18258
- await writeSkillOwnershipReceipt(
18259
- ctx,
18260
- skillRoots,
18261
- afterPaths.filter((path) => !pathSnapshot.has(path))
18262
- );
18741
+ if (usesDeclaredOwnership) {
18742
+ const discovered = await discoverDeclaredOwnership(ctx);
18743
+ await writeDeclaredOwnershipReceipt(ctx, {
18744
+ roots: discovered.roots,
18745
+ paths: discovered.paths.filter((path) => !pathSnapshot.has(path))
18746
+ });
18747
+ } else {
18748
+ const afterPaths = await declaredSkillPaths(ctx, skillRoots);
18749
+ await writeSkillOwnershipReceipt(
18750
+ ctx,
18751
+ skillRoots,
18752
+ afterPaths.filter((path) => !pathSnapshot.has(path))
18753
+ );
18754
+ }
18263
18755
  } catch (error) {
18264
18756
  return {
18265
18757
  ok: false,
@@ -18286,6 +18778,12 @@ var init_npmCli2 = __esm({
18286
18778
  );
18287
18779
  return { ok: true, backupId: bk.backupId, appliedFiles: [] };
18288
18780
  };
18781
+ installNpmCli = async (ctx) => {
18782
+ if (!ctx.hostContext || !isSkillOwnershipManaged(ctx.manifest)) {
18783
+ return installNpmCliUnlocked(ctx);
18784
+ }
18785
+ return withInstallOwnershipLock(ctx.hostContext, () => installNpmCliUnlocked(ctx));
18786
+ };
18289
18787
  }
18290
18788
  });
18291
18789
  function unprovenSkillTarget(ctx) {
@@ -18327,7 +18825,7 @@ async function activeTargetDirectoryExists(skillsDirs, names) {
18327
18825
  }
18328
18826
  return false;
18329
18827
  }
18330
- var HARD_CRASH_EXITS, HARD_CRASH_RETRY_DELAY_MS, installNpxSkillInstaller;
18828
+ var HARD_CRASH_EXITS, HARD_CRASH_RETRY_DELAY_MS, installNpxSkillInstallerUnlocked, installNpxSkillInstaller;
18331
18829
  var init_npxSkillInstaller2 = __esm({
18332
18830
  "src/installers/npxSkillInstaller.ts"() {
18333
18831
  init_platform();
@@ -18336,6 +18834,8 @@ var init_npxSkillInstaller2 = __esm({
18336
18834
  init_diff();
18337
18835
  init_err();
18338
18836
  init_idempotent();
18837
+ init_installOwnershipLock();
18838
+ init_ownershipContract();
18339
18839
  init_packSkillAudit();
18340
18840
  init_preflight();
18341
18841
  init_skillOwnershipReceipt();
@@ -18345,7 +18845,7 @@ var init_npxSkillInstaller2 = __esm({
18345
18845
  init_verifyMessage();
18346
18846
  HARD_CRASH_EXITS = /* @__PURE__ */ new Set([3221226505, 3221225477]);
18347
18847
  HARD_CRASH_RETRY_DELAY_MS = 500;
18348
- installNpxSkillInstaller = async (ctx) => {
18848
+ installNpxSkillInstallerUnlocked = async (ctx) => {
18349
18849
  const install = ctx.manifest.spec.install;
18350
18850
  if (install.method !== "npx-skill-installer") {
18351
18851
  return {
@@ -18389,6 +18889,12 @@ var init_npxSkillInstaller2 = __esm({
18389
18889
  ];
18390
18890
  const selectionFlags = [...install.cmd.matchAll(/(?:^|\s)(?:--skill|-s)(?:\s|=)/g)];
18391
18891
  const selectedSkill = selections.length === 1 && selectionFlags.length === 1 ? selections[0]?.[1] : void 0;
18892
+ const singleSkill = selectedSkill !== void 0 && !/[;&|<>`$\r\n]/.test(install.cmd);
18893
+ const hasDeclaredTargets = (install.installs_skills?.length ?? 0) > 0;
18894
+ const ownershipResources = ctx.manifest.spec.ownership?.resources;
18895
+ const usesDeclaredOwnership = Array.isArray(ownershipResources) && ownershipResources.length > 0;
18896
+ if (ctx.hostContext && !singleSkill && !hasDeclaredTargets && !usesDeclaredOwnership)
18897
+ return unprovenSkillTarget(ctx);
18392
18898
  const activeTargetNames = npxActiveTargetNames(
18393
18899
  install.cmd,
18394
18900
  ctx.manifest.metadata.name,
@@ -18400,30 +18906,34 @@ var init_npxSkillInstaller2 = __esm({
18400
18906
  )
18401
18907
  ] : [getSkillsDir()];
18402
18908
  const primaryActiveSkillsDir = activeSkillsDirs[0] ?? getSkillsDir();
18909
+ const ownershipCandidateSnapshot = await snapshotDeclaredOwnership(ctx);
18403
18910
  let anyExistingTarget = false;
18404
18911
  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;
18912
+ if (usesDeclaredOwnership) {
18913
+ anyExistingTarget = ownershipCandidateSnapshot.paths.length > 0;
18914
+ } else {
18915
+ const names = [.../* @__PURE__ */ new Set([skillSegment, ...install.installs_skills ?? []])];
18916
+ if (names.some((name2) => !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name2)))
18917
+ return unprovenSkillTarget(ctx);
18918
+ const roots = [
18919
+ .../* @__PURE__ */ new Set([
18920
+ ...activeSkillsDirs,
18921
+ ctx.hostContext.platform.skillsDir,
18922
+ join(ctx.hostContext.nativeHome, "skills"),
18923
+ join(ctx.hostContext.userHome, ".agents", "skills")
18924
+ ])
18925
+ ];
18926
+ for (const root of roots) {
18927
+ for (const name2 of names) {
18928
+ if (await lstat(join(root, name2)).then(
18929
+ () => true,
18930
+ (error) => error.code !== "ENOENT"
18931
+ )) {
18932
+ anyExistingTarget = true;
18933
+ }
18423
18934
  }
18424
18935
  }
18425
18936
  }
18426
- const singleSkill = selectedSkill !== void 0 && !/[;&|<>`$\r\n]/.test(install.cmd);
18427
18937
  if (ctx.opts.updateInstalled && (!singleSkill || anyExistingTarget || await isAlreadyInstalled(ctx, { honorUpdateFlag: false })))
18428
18938
  return unprovenSkillTarget(ctx);
18429
18939
  }
@@ -18476,7 +18986,9 @@ var init_npxSkillInstaller2 = __esm({
18476
18986
  if (!bk.ok) return { ok: false, phase: "preflight", error: bk.error };
18477
18987
  await warnDeclaredCollisions(ctx);
18478
18988
  const skillRoots = skillRootsForContext(ctx);
18479
- const pathSnapshot = new Set(await declaredSkillPaths(ctx, skillRoots));
18989
+ const pathSnapshot = new Set(
18990
+ usesDeclaredOwnership ? ownershipCandidateSnapshot.paths : await declaredSkillPaths(ctx, skillRoots)
18991
+ );
18480
18992
  const packSnapshot = await snapshotSkillNames(
18481
18993
  ...ctx.hostContext ? [ctx.hostContext.platform.skillsDir] : []
18482
18994
  );
@@ -18526,12 +19038,20 @@ var init_npxSkillInstaller2 = __esm({
18526
19038
  const verifyFailure = await verifyInstalled(ctx, { neutralCwd: true });
18527
19039
  if (verifyFailure) return { ...verifyFailure, backupId: bk.backupId };
18528
19040
  try {
18529
- const afterPaths = await declaredSkillPaths(ctx, skillRoots);
18530
- await writeSkillOwnershipReceipt(
18531
- ctx,
18532
- skillRoots,
18533
- afterPaths.filter((path) => !pathSnapshot.has(path))
18534
- );
19041
+ if (usesDeclaredOwnership) {
19042
+ const discovered = await discoverDeclaredOwnership(ctx);
19043
+ await writeDeclaredOwnershipReceipt(ctx, {
19044
+ roots: discovered.roots,
19045
+ paths: discovered.paths.filter((path) => !pathSnapshot.has(path))
19046
+ });
19047
+ } else {
19048
+ const afterPaths = await declaredSkillPaths(ctx, skillRoots);
19049
+ await writeSkillOwnershipReceipt(
19050
+ ctx,
19051
+ skillRoots,
19052
+ afterPaths.filter((path) => !pathSnapshot.has(path))
19053
+ );
19054
+ }
18535
19055
  } catch (error) {
18536
19056
  return {
18537
19057
  ok: false,
@@ -18557,6 +19077,10 @@ var init_npxSkillInstaller2 = __esm({
18557
19077
  );
18558
19078
  return { ok: true, backupId: bk.backupId, appliedFiles: [skillMdPath] };
18559
19079
  };
19080
+ installNpxSkillInstaller = async (ctx) => {
19081
+ if (!ctx.hostContext) return installNpxSkillInstallerUnlocked(ctx);
19082
+ return withInstallOwnershipLock(ctx.hostContext, () => installNpxSkillInstallerUnlocked(ctx));
19083
+ };
18560
19084
  }
18561
19085
  });
18562
19086
 
@@ -18828,18 +19352,18 @@ async function installBaseProfile(opts) {
18828
19352
  const installed2 = [];
18829
19353
  const alreadyInstalled = [];
18830
19354
  const skipped = [];
18831
- const failed = [];
19355
+ const failed2 = [];
18832
19356
  for (const path of await listBaseManifests(getAssetsRoot())) {
18833
19357
  let yamlSrc;
18834
19358
  try {
18835
19359
  yamlSrc = await readFile(path, "utf8");
18836
19360
  } catch (e) {
18837
- failed.push({ name: path, reason: `read: ${e.message}` });
19361
+ failed2.push({ name: path, reason: `read: ${e.message}` });
18838
19362
  continue;
18839
19363
  }
18840
19364
  const v = validateManifestFile(yamlSrc, path);
18841
19365
  if (!v.ok) {
18842
- failed.push({ name: path, reason: `validate: ${v.errors[0]?.message ?? "unknown"}` });
19366
+ failed2.push({ name: path, reason: `validate: ${v.errors[0]?.message ?? "unknown"}` });
18843
19367
  continue;
18844
19368
  }
18845
19369
  const name = v.manifest.metadata.name;
@@ -18847,9 +19371,9 @@ async function installBaseProfile(opts) {
18847
19371
  if ("aborted" in r) skipped.push({ name, reason: `aborted: ${r.reason}` });
18848
19372
  else if (r.ok && "alreadyInstalled" in r && r.alreadyInstalled) alreadyInstalled.push(name);
18849
19373
  else if (r.ok) installed2.push(name);
18850
- else failed.push({ name, reason: r.error.message });
19374
+ else failed2.push({ name, reason: r.error.message });
18851
19375
  }
18852
- return { installed: installed2, alreadyInstalled, skipped, failed };
19376
+ return { installed: installed2, alreadyInstalled, skipped, failed: failed2 };
18853
19377
  }
18854
19378
  function registerInstallBase(program2) {
18855
19379
  program2.command("install-base").description(
@@ -18864,17 +19388,17 @@ function registerInstallBase(program2) {
18864
19388
  fullDiff: false,
18865
19389
  color: "auto"
18866
19390
  };
18867
- const { installed: installed2, alreadyInstalled, skipped, failed } = await installBaseProfile(opts);
19391
+ const { installed: installed2, alreadyInstalled, skipped, failed: failed2 } = await installBaseProfile(opts);
18868
19392
  console.log(
18869
19393
  `
18870
- installed: ${installed2.length} / already-installed: ${alreadyInstalled.length} / skipped (user-aborted): ${skipped.length} / failed: ${failed.length}`
19394
+ installed: ${installed2.length} / already-installed: ${alreadyInstalled.length} / skipped (user-aborted): ${skipped.length} / failed: ${failed2.length}`
18871
19395
  );
18872
19396
  for (const i of installed2) console.log(` installed ${i}`);
18873
19397
  for (const a of alreadyInstalled)
18874
19398
  console.log(` already-installed ${a} \u2014 run \`/mcp\` in Claude Code to verify connection`);
18875
19399
  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);
19400
+ for (const f of failed2) console.error(` failed ${f.name} \u2014 ${f.reason}`);
19401
+ if (failed2.length > 0) process.exit(1);
18878
19402
  if (installed2.length === 0 && alreadyInstalled.length === 0) process.exit(2);
18879
19403
  process.exit(0);
18880
19404
  });
@@ -19464,8 +19988,7 @@ function createAgentRepairResult(input) {
19464
19988
  ...input.proposal ? { proposal: input.proposal } : {}
19465
19989
  };
19466
19990
  }
19467
- function createRepairRequest(result, context, authorization) {
19468
- const components = repairableComponents(result);
19991
+ function createRepairRequest(result, context, authorization, components = repairableComponents(result)) {
19469
19992
  return {
19470
19993
  host: context.hostId,
19471
19994
  runtime: result.runtime,
@@ -19647,6 +20170,311 @@ var init_agentRepairRunner = __esm({
19647
20170
  }
19648
20171
  });
19649
20172
 
20173
+ // src/cli/lib/ownershipAdoptionLock.ts
20174
+ async function withOwnershipAdoptionLock(context, work) {
20175
+ return withInstallOwnershipLock(context, work);
20176
+ }
20177
+ var init_ownershipAdoptionLock = __esm({
20178
+ "src/cli/lib/ownershipAdoptionLock.ts"() {
20179
+ init_installOwnershipLock();
20180
+ }
20181
+ });
20182
+ async function loadRequestedOwnershipManifests(componentIds) {
20183
+ const requested = new Set(componentIds);
20184
+ const found = [];
20185
+ for (const directory of ["tools", "skill-packs"]) {
20186
+ const root = join(getAssetsRoot(), "manifests", directory);
20187
+ for (const name of await readdir(root)) {
20188
+ if (!name.endsWith(".yaml")) continue;
20189
+ const path = join(root, name);
20190
+ const validated = validateManifestFile(await readFile(path, "utf8"), path);
20191
+ if (validated.ok && requested.has(validated.manifest.metadata.name)) {
20192
+ found.push(validated.manifest);
20193
+ } else if (!validated.ok && requested.has(name.slice(0, -5))) {
20194
+ throw new Error(`invalid ownership adoption manifest: ${name}`);
20195
+ }
20196
+ }
20197
+ }
20198
+ return found;
20199
+ }
20200
+ function declaresOwnership(manifest) {
20201
+ const resources = manifest.spec.ownership?.resources;
20202
+ return Array.isArray(resources) && resources.length > 0;
20203
+ }
20204
+ function buildOwnershipAdoptionPlans(request, context, manifests, resolvePlan) {
20205
+ return request.components.map(({ id }) => {
20206
+ const matches = manifests.filter((manifest2) => manifest2.metadata.name === id);
20207
+ if (matches.length !== 1) throw new Error(`ownership adoption manifest count mismatch: ${id}`);
20208
+ const manifest = matches[0];
20209
+ if (!manifest) throw new Error(`ownership adoption manifest missing: ${id}`);
20210
+ const plan = resolvePlan(manifest, context, "install");
20211
+ if (plan.status !== "supported" || plan.componentId !== id || plan.manifest.metadata.name !== id) {
20212
+ throw new Error(`ownership adoption plan mismatch: ${id}`);
20213
+ }
20214
+ return {
20215
+ ctx: {
20216
+ manifest: structuredClone(plan.manifest),
20217
+ hostContext: plan.context,
20218
+ level: "L4",
20219
+ cwd: plan.context.neutralSpawnCwd ?? plan.context.userHome,
20220
+ opts: {
20221
+ apply: false,
20222
+ dryRun: false,
20223
+ system: false,
20224
+ nonInteractive: true,
20225
+ fullDiff: false,
20226
+ color: false
20227
+ }
20228
+ }
20229
+ };
20230
+ }).filter(({ ctx }) => declaresOwnership(ctx.manifest));
20231
+ }
20232
+ var init_ownershipAdoptionPlan = __esm({
20233
+ "src/cli/lib/ownershipAdoptionPlan.ts"() {
20234
+ init_validate();
20235
+ init_assetsRoot();
20236
+ }
20237
+ });
20238
+ async function snapshotOwnershipReceipt(path) {
20239
+ const parentIdentity = await captureSkillOwnershipReceiptParent(path);
20240
+ if (!parentIdentity) return { path, bytes: null, mode: null, parentIdentity: null };
20241
+ try {
20242
+ const info = await lstat(path);
20243
+ if (info.isSymbolicLink() || !info.isFile()) throw new Error("receipt is not a regular file");
20244
+ const bytes = await readFile(path);
20245
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20246
+ return { path, bytes, mode: info.mode, parentIdentity };
20247
+ } catch (error) {
20248
+ if (error.code === "ENOENT") {
20249
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20250
+ return { path, bytes: null, mode: null, parentIdentity };
20251
+ }
20252
+ throw error;
20253
+ }
20254
+ }
20255
+ async function restoreOwnershipReceipt(snapshot) {
20256
+ const parentIdentity = snapshot.parentIdentity ? snapshot.parentIdentity : await captureSkillOwnershipReceiptParent(snapshot.path, { create: snapshot.bytes !== null });
20257
+ if (!parentIdentity) return;
20258
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20259
+ await rm(snapshot.path, { force: true });
20260
+ if (!snapshot.bytes) {
20261
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20262
+ return;
20263
+ }
20264
+ const temp = `${snapshot.path}.${process.pid}.${randomUUID()}.restore.tmp`;
20265
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20266
+ await writeFile(temp, snapshot.bytes, { mode: snapshot.mode ?? void 0 });
20267
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20268
+ await rename(temp, snapshot.path);
20269
+ await assertSkillOwnershipReceiptParent(parentIdentity);
20270
+ }
20271
+ async function restoreOwnershipReceipts(snapshots) {
20272
+ const restored = await Promise.allSettled(snapshots.map(restoreOwnershipReceipt));
20273
+ const failure = restored.find((result) => result.status === "rejected");
20274
+ if (failure?.status === "rejected") throw failure.reason;
20275
+ }
20276
+ function resourceKey(resource) {
20277
+ return JSON.stringify([resource.path, resource.root, resource.kind]);
20278
+ }
20279
+ function intersectDeclaredOwnership(before, after) {
20280
+ const beforeKeys = new Set(before.resources.map(resourceKey));
20281
+ const resources = after.resources.filter((resource) => beforeKeys.has(resourceKey(resource))).sort((left, right) => left.path.localeCompare(right.path));
20282
+ return {
20283
+ resources,
20284
+ roots: [...new Set(resources.map(({ root }) => root))].sort(),
20285
+ paths: resources.map(({ path }) => path)
20286
+ };
20287
+ }
20288
+ var init_ownershipAdoptionReceipt = __esm({
20289
+ "src/cli/lib/ownershipAdoptionReceipt.ts"() {
20290
+ init_skillOwnershipReceipt();
20291
+ }
20292
+ });
20293
+
20294
+ // src/cli/lib/ownershipAdoptionResult.ts
20295
+ function isVerifiedRepairCompletion(repair, request) {
20296
+ const expected = request.components.map(({ id }) => id).sort();
20297
+ const actual = [...new Set(repair.components)].sort();
20298
+ return repair.status === "completed" && repair.verified && repair.authorized && repair.execution === request.host && expected.length === actual.length && expected.every((id, index) => id === actual[index]);
20299
+ }
20300
+ var init_ownershipAdoptionResult = __esm({
20301
+ "src/cli/lib/ownershipAdoptionResult.ts"() {
20302
+ }
20303
+ });
20304
+
20305
+ // src/cli/lib/ownershipAdoption.ts
20306
+ function failed(request, reasonCode = "ownership-adoption-failed") {
20307
+ return createAgentRepairResult({
20308
+ requested: true,
20309
+ authorized: true,
20310
+ components: request.components.map(({ id }) => id),
20311
+ execution: request.host,
20312
+ status: "failed",
20313
+ verified: false,
20314
+ reasonCode
20315
+ });
20316
+ }
20317
+ async function invokeRepair(request, runRepair) {
20318
+ try {
20319
+ return await runRepair();
20320
+ } catch {
20321
+ return failed(request, "agent-repair-threw");
20322
+ }
20323
+ }
20324
+ async function runOwnershipAdoption(input, dependencies = {}) {
20325
+ const { context, request, runRepair } = input;
20326
+ const authorizationError = validateRepairAuthorization(request.authorization, request.components);
20327
+ if (authorizationError) {
20328
+ return createAgentRepairResult({
20329
+ requested: true,
20330
+ authorized: false,
20331
+ components: request.components.map(({ id }) => id),
20332
+ execution: request.host,
20333
+ status: "not-authorized",
20334
+ reasonCode: authorizationError
20335
+ });
20336
+ }
20337
+ let plans;
20338
+ try {
20339
+ const manifests = await (dependencies.loadManifests ?? loadRequestedOwnershipManifests)(
20340
+ request.components.map(({ id }) => id)
20341
+ );
20342
+ plans = buildOwnershipAdoptionPlans(
20343
+ request,
20344
+ context,
20345
+ manifests,
20346
+ dependencies.resolvePlan ?? resolveComponentPlan
20347
+ );
20348
+ } catch {
20349
+ return failed(request, "ownership-adoption-plan-failed");
20350
+ }
20351
+ if (plans.length === 0) {
20352
+ const repair = await invokeRepair(request, runRepair);
20353
+ if (repair.status === "completed" && repair.verified && !isVerifiedRepairCompletion(repair, request)) {
20354
+ return failed(request, "agent-repair-result-mismatch");
20355
+ }
20356
+ return repair;
20357
+ }
20358
+ const discover = dependencies.discover ?? discoverDeclaredOwnership;
20359
+ const writeReceipt = dependencies.writeReceipt ?? writeDeclaredOwnershipReceipt;
20360
+ const receiptPath = dependencies.receiptPath ?? skillOwnershipReceiptPath;
20361
+ const restoreReceipts = dependencies.restoreReceipts ?? restoreOwnershipReceipts;
20362
+ const withLock2 = dependencies.withLock ?? withOwnershipAdoptionLock;
20363
+ try {
20364
+ return await withLock2(context, async () => {
20365
+ const before = await Promise.all(plans.map(({ ctx }) => discover(ctx)));
20366
+ const receipts = await Promise.all(
20367
+ plans.map(({ ctx }) => snapshotOwnershipReceipt(receiptPath(ctx)))
20368
+ );
20369
+ const repair = await invokeRepair(request, runRepair);
20370
+ try {
20371
+ await restoreReceipts(receipts);
20372
+ } catch {
20373
+ return failed(request, "ownership-receipt-restore-failed");
20374
+ }
20375
+ if (repair.status !== "completed" || !repair.verified) return repair;
20376
+ if (!isVerifiedRepairCompletion(repair, request)) {
20377
+ return failed(request, "agent-repair-result-mismatch");
20378
+ }
20379
+ let adopted;
20380
+ try {
20381
+ const after = await Promise.all(plans.map(({ ctx }) => discover(ctx)));
20382
+ adopted = after.map(
20383
+ (value, index) => intersectDeclaredOwnership(before[index], value)
20384
+ );
20385
+ if (adopted.some(({ paths }) => paths.length === 0)) {
20386
+ return failed(request, "ownership-adoption-empty");
20387
+ }
20388
+ for (const [index, plan] of plans.entries()) {
20389
+ const ownership = adopted[index];
20390
+ await writeReceipt(plan.ctx, { roots: ownership.roots, paths: ownership.paths });
20391
+ }
20392
+ } catch {
20393
+ try {
20394
+ await restoreReceipts(receipts);
20395
+ } catch {
20396
+ return failed(request, "ownership-adoption-rollback-failed");
20397
+ }
20398
+ return failed(request, "ownership-adoption-writer-failed");
20399
+ }
20400
+ return repair;
20401
+ });
20402
+ } catch {
20403
+ return failed(request);
20404
+ }
20405
+ }
20406
+ var init_ownershipAdoption = __esm({
20407
+ "src/cli/lib/ownershipAdoption.ts"() {
20408
+ init_componentPlan();
20409
+ init_ownershipContract();
20410
+ init_skillOwnershipReceipt();
20411
+ init_agentRepair();
20412
+ init_ownershipAdoptionLock();
20413
+ init_ownershipAdoptionPlan();
20414
+ init_ownershipAdoptionReceipt();
20415
+ init_ownershipAdoptionResult();
20416
+ }
20417
+ });
20418
+
20419
+ // src/cli/lib/ownershipAdoptionCandidate.ts
20420
+ function declaresOwnership2(manifest) {
20421
+ const resources = manifest.spec.ownership?.resources;
20422
+ return Array.isArray(resources) && resources.length > 0;
20423
+ }
20424
+ function installContext(manifest, context) {
20425
+ return {
20426
+ manifest,
20427
+ hostContext: context,
20428
+ level: "L4",
20429
+ cwd: context.neutralSpawnCwd ?? context.userHome,
20430
+ opts: {
20431
+ apply: false,
20432
+ dryRun: false,
20433
+ system: false,
20434
+ nonInteractive: true,
20435
+ fullDiff: false,
20436
+ color: false
20437
+ }
20438
+ };
20439
+ }
20440
+ async function findOwnershipRepairCandidates(result, context, dependencies = {}) {
20441
+ const ids = result.components.filter(
20442
+ (component2) => component2.status === "current" && REVIEWED_REPAIR_COMPONENTS.has(component2.id)
20443
+ ).map(({ id }) => id);
20444
+ if (ids.length === 0) return [];
20445
+ const manifests = await (dependencies.loadManifests ?? loadRequestedOwnershipManifests)(ids);
20446
+ const resolvePlan = dependencies.resolvePlan ?? resolveComponentPlan;
20447
+ const readReceipt = dependencies.readReceipt ?? readSkillOwnershipReceipt;
20448
+ const candidates = [];
20449
+ for (const id of ids) {
20450
+ const matches = manifests.filter((manifest) => manifest.metadata.name === id);
20451
+ if (matches.length !== 1) throw new Error(`ownership repair manifest count mismatch: ${id}`);
20452
+ const source = matches[0];
20453
+ if (!source) throw new Error(`ownership repair manifest missing: ${id}`);
20454
+ const plan = resolvePlan(source, context, "install");
20455
+ if (plan.status !== "supported" || !declaresOwnership2(plan.manifest)) continue;
20456
+ try {
20457
+ await readReceipt(installContext(structuredClone(plan.manifest), plan.context));
20458
+ } catch (error) {
20459
+ if (!isSkillOwnershipReceiptError(error)) throw error;
20460
+ candidates.push({
20461
+ id,
20462
+ status: "current",
20463
+ reasonCode: "ownership-receipt-repair-required"
20464
+ });
20465
+ }
20466
+ }
20467
+ return candidates;
20468
+ }
20469
+ var init_ownershipAdoptionCandidate = __esm({
20470
+ "src/cli/lib/ownershipAdoptionCandidate.ts"() {
20471
+ init_componentPlan();
20472
+ init_skillOwnershipReceipt();
20473
+ init_agentRepair();
20474
+ init_ownershipAdoptionPlan();
20475
+ }
20476
+ });
20477
+
19650
20478
  // src/cli/lib/updateLock.ts
19651
20479
  var updateLock_exports = {};
19652
20480
  __export(updateLock_exports, {
@@ -20131,7 +20959,7 @@ function parseShaText(text) {
20131
20959
  return m?.[1]?.toLowerCase() ?? null;
20132
20960
  }
20133
20961
  async function runBinarySelfUpdate(deps, opts) {
20134
- const rename8 = deps.fsOps?.rename ?? rename;
20962
+ const rename9 = deps.fsOps?.rename ?? rename;
20135
20963
  const copyFile$1 = deps.fsOps?.copyFile ?? copyFile;
20136
20964
  const unlink2 = deps.fsOps?.unlink ?? unlink;
20137
20965
  if (normalized(deps.execPath).includes("/node_modules/")) {
@@ -20272,7 +21100,7 @@ async function runBinarySelfUpdate(deps, opts) {
20272
21100
  };
20273
21101
  }
20274
21102
  try {
20275
- await rename8(deps.execPath, bakPath);
21103
+ await rename9(deps.execPath, bakPath);
20276
21104
  } catch (e) {
20277
21105
  await unlink2(tempPath).catch(() => {
20278
21106
  });
@@ -20282,10 +21110,10 @@ async function runBinarySelfUpdate(deps, opts) {
20282
21110
  };
20283
21111
  }
20284
21112
  try {
20285
- await rename8(tempPath, deps.execPath);
21113
+ await rename9(tempPath, deps.execPath);
20286
21114
  } catch (e) {
20287
21115
  try {
20288
- await rename8(bakPath, deps.execPath);
21116
+ await rename9(bakPath, deps.execPath);
20289
21117
  return {
20290
21118
  status: "error",
20291
21119
  message: `swap failed (${e.message}) \u2014 rolled back to the previous binary`
@@ -20339,7 +21167,7 @@ async function finalizeBinarySelfUpdate(deps, outcome) {
20339
21167
  }
20340
21168
  }
20341
21169
  async function runBinaryRollback(deps, opts) {
20342
- const rename8 = deps.fsOps?.rename ?? rename;
21170
+ const rename9 = deps.fsOps?.rename ?? rename;
20343
21171
  const copyFile$1 = deps.fsOps?.copyFile ?? copyFile;
20344
21172
  const unlink2 = deps.fsOps?.unlink ?? unlink;
20345
21173
  if (normalized(deps.execPath).includes("/node_modules/")) {
@@ -20401,7 +21229,7 @@ async function runBinaryRollback(deps, opts) {
20401
21229
  };
20402
21230
  }
20403
21231
  try {
20404
- await rename8(deps.execPath, bakPath);
21232
+ await rename9(deps.execPath, bakPath);
20405
21233
  } catch (e) {
20406
21234
  await unlink2(tempPath).catch(() => {
20407
21235
  });
@@ -20411,10 +21239,10 @@ async function runBinaryRollback(deps, opts) {
20411
21239
  };
20412
21240
  }
20413
21241
  try {
20414
- await rename8(tempPath, deps.execPath);
21242
+ await rename9(tempPath, deps.execPath);
20415
21243
  } catch (e) {
20416
21244
  try {
20417
- await rename8(bakPath, deps.execPath);
21245
+ await rename9(bakPath, deps.execPath);
20418
21246
  return {
20419
21247
  status: "error",
20420
21248
  message: `swap failed (${e.message}) \u2014 restored the previous binary`
@@ -20845,7 +21673,7 @@ function decodeUpdateContinuation(encoded) {
20845
21673
  return value;
20846
21674
  }
20847
21675
  async function runContinuationProcess(executablePath, args, options) {
20848
- return new Promise((resolve39, reject) => {
21676
+ return new Promise((resolve40, reject) => {
20849
21677
  const child = spawn(executablePath, args, {
20850
21678
  cwd: options.cwd,
20851
21679
  env: options.env,
@@ -20859,7 +21687,7 @@ async function runContinuationProcess(executablePath, args, options) {
20859
21687
  child.once("error", reject);
20860
21688
  child.once("close", (exitCode, signal) => {
20861
21689
  clearTimeout(timer);
20862
- resolve39({ exitCode, signal });
21690
+ resolve40({ exitCode, signal });
20863
21691
  });
20864
21692
  });
20865
21693
  }
@@ -21664,8 +22492,8 @@ async function refreshWorkflows(context, assets) {
21664
22492
  context.hostId,
21665
22493
  context
21666
22494
  );
21667
- const failed = rendered.results.find((result) => result.error);
21668
- if (failed) throw new Error(failed.error);
22495
+ const failed2 = rendered.results.find((result) => result.error);
22496
+ if (failed2) throw new Error(failed2.error);
21669
22497
  await mkdir(context.platform.stateRoot, { recursive: true });
21670
22498
  await recordSkillHashes(names, skillsBase, ledgerPath2);
21671
22499
  if (context.hostId === "claude") {
@@ -21836,6 +22664,7 @@ __export(updateCoordinator_exports, {
21836
22664
  executeUpdate: () => executeUpdate,
21837
22665
  hasWrittenUpdateEnvelope: () => hasWrittenUpdateEnvelope,
21838
22666
  renderHumanUpdateResult: () => renderHumanUpdateResult,
22667
+ runAuthorizedAgentRepair: () => runAuthorizedAgentRepair,
21839
22668
  runUpdateCoordinator: () => runUpdateCoordinator,
21840
22669
  updateFailureResult: () => updateFailureResult,
21841
22670
  updateTarget: () => updateTarget,
@@ -22384,8 +23213,20 @@ async function executeUpdate(options) {
22384
23213
  );
22385
23214
  }
22386
23215
  }
22387
- async function runAuthorizedAgentRepair(deterministicResult, options, context) {
22388
- const components = repairableComponents(deterministicResult);
23216
+ async function runAuthorizedAgentRepair(deterministicResult, options, context, dependencies = {}) {
23217
+ const deterministicComponents = repairableComponents(deterministicResult);
23218
+ const ownershipCandidates = options.repair === true && options.yes === true && (options.all === true || options.upstreams === true) ? await (dependencies.findOwnershipRepairCandidates ?? findOwnershipRepairCandidates)(
23219
+ deterministicResult,
23220
+ context
23221
+ ) : [];
23222
+ const components = [
23223
+ ...new Map(
23224
+ [...deterministicComponents, ...ownershipCandidates].map((component2) => [
23225
+ component2.id,
23226
+ component2
23227
+ ])
23228
+ ).values()
23229
+ ];
22389
23230
  if (components.length === 0)
22390
23231
  return {
22391
23232
  ...deterministicResult,
@@ -22413,23 +23254,31 @@ async function runAuthorizedAgentRepair(deterministicResult, options, context) {
22413
23254
  components: [],
22414
23255
  grantedAt: null
22415
23256
  };
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
- }
23257
+ const request = createRepairRequest(deterministicResult, context, authorization, components);
23258
+ const repairRunner = dependencies.runAgentRepair ?? runAgentRepair;
23259
+ const adoptionRunner = dependencies.runOwnershipAdoption ?? runOwnershipAdoption;
23260
+ const repair = await adoptionRunner({
23261
+ context,
23262
+ request,
23263
+ runRepair: () => repairRunner(request, {
23264
+ verify: async (verificationRequest) => {
23265
+ const verification = await executeUpdate({
23266
+ all: true,
23267
+ check: true,
23268
+ json: true,
23269
+ nonInteractive: true,
23270
+ platform: verificationRequest.host,
23271
+ packageManager: options.packageManager
23272
+ });
23273
+ const checked = new Map(
23274
+ verification.components.map((component2) => [component2.id, component2])
23275
+ );
23276
+ return verificationRequest.components.every((component2) => {
23277
+ const current = checked.get(component2.id);
23278
+ return current?.verified === true && ["current", "updated"].includes(current.status);
23279
+ });
23280
+ }
23281
+ })
22433
23282
  });
22434
23283
  return {
22435
23284
  ...deterministicResult,
@@ -22447,6 +23296,8 @@ var init_updateCoordinator = __esm({
22447
23296
  init_runtime();
22448
23297
  init_agentRepair();
22449
23298
  init_agentRepairRunner();
23299
+ init_ownershipAdoption();
23300
+ init_ownershipAdoptionCandidate();
22450
23301
  init_packageUpdateTarget();
22451
23302
  init_updateResult();
22452
23303
  UpdateProtocolError = class extends Error {
@@ -22460,14 +23311,14 @@ var manifest_add_exports = {};
22460
23311
  __export(manifest_add_exports, {
22461
23312
  registerManifestAdd: () => registerManifestAdd
22462
23313
  });
22463
- function basename7(upstream) {
23314
+ function basename8(upstream) {
22464
23315
  return (upstream.split("/").pop() ?? upstream).replace(/\.git$/, "");
22465
23316
  }
22466
23317
  function registerManifestAdd(program2) {
22467
23318
  program2.command("manifest-add <upstream>").description(
22468
23319
  "Add a new upstream adapter (EE-5 5-question merge gate; immediate by default \u2014 use --dry-run for preview)"
22469
23320
  ).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);
23321
+ const name = raw.name ?? basename8(upstream);
22471
23322
  const category = raw.category ?? "skill-packs";
22472
23323
  try {
22473
23324
  checkSafeSegment(category);
@@ -22780,11 +23631,11 @@ function registerReleasePreflight(program2) {
22780
23631
  console.log(` ${mark} ${c.name} \u2014 ${c.message}`);
22781
23632
  if (c.status !== "pass" && c.fix) console.log(` fix: ${c.fix}`);
22782
23633
  }
22783
- const failed = anyFailed2(checks);
23634
+ const failed2 = anyFailed2(checks);
22784
23635
  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."
23636
+ failed2 ? "\n NOT release-ready \u2014 resolve the failures above before tagging." : "\n release-ready \u2014 tag the version to trigger publish.yml."
22786
23637
  );
22787
- process.exit(failed ? 1 : 0);
23638
+ process.exit(failed2 ? 1 : 0);
22788
23639
  });
22789
23640
  }
22790
23641
  var init_release_preflight2 = __esm({
@@ -23743,18 +24594,18 @@ async function runStepBInstall(manifestPaths, runOpts = {}) {
23743
24594
  const installed2 = [];
23744
24595
  const alreadyInstalled = [];
23745
24596
  const skipped = [];
23746
- const failed = [];
24597
+ const failed2 = [];
23747
24598
  for (const v of [...invalid, ...mcpEntries, ...restEntries]) {
23748
24599
  if (v.status === "installed") installed2.push(v.name);
23749
24600
  else if (v.status === "already-installed") alreadyInstalled.push(v.name);
23750
24601
  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}`);
24602
+ else if (v.status === "failed") failed2.push(`${v.name}: ${v.reason}`);
23752
24603
  }
23753
24604
  return {
23754
24605
  installed: installed2,
23755
24606
  alreadyInstalled,
23756
24607
  skipped,
23757
- failed,
24608
+ failed: failed2,
23758
24609
  failureKeywords,
23759
24610
  elapsedMs: Date.now() - start,
23760
24611
  componentTypes
@@ -23762,7 +24613,7 @@ async function runStepBInstall(manifestPaths, runOpts = {}) {
23762
24613
  }
23763
24614
  async function reclassifyForceUpdateFailures(firstPass, forcePass, probe) {
23764
24615
  const priorlyInstalled = new Set(firstPass.alreadyInstalled);
23765
- const failed = [];
24616
+ const failed2 = [];
23766
24617
  const keptExisting = [];
23767
24618
  for (const entry of forcePass.failed) {
23768
24619
  const m = entry.match(/^([^:]+):\s*(.*)$/s);
@@ -23783,9 +24634,9 @@ async function reclassifyForceUpdateFailures(firstPass, forcePass, probe) {
23783
24634
  continue;
23784
24635
  }
23785
24636
  }
23786
- failed.push(entry);
24637
+ failed2.push(entry);
23787
24638
  }
23788
- return { failed, keptExisting };
24639
+ return { failed: failed2, keptExisting };
23789
24640
  }
23790
24641
  async function makeIdempotentProbe(manifestPaths, context = captureHostInstallContext()) {
23791
24642
  const byName = /* @__PURE__ */ new Map();
@@ -23806,9 +24657,9 @@ async function makeIdempotentProbe(manifestPaths, context = captureHostInstallCo
23806
24657
  }
23807
24658
  }
23808
24659
  return async (name) => {
23809
- const selected = byName.get(name);
23810
- if (!selected) return false;
23811
- const { manifest, hostContext } = selected;
24660
+ const selected2 = byName.get(name);
24661
+ if (!selected2) return false;
24662
+ const { manifest, hostContext } = selected2;
23812
24663
  if (manifest.spec.install.method === "npx-skill-installer") {
23813
24664
  const install = manifest.spec.install;
23814
24665
  const targets = npxActiveTargetNames(
@@ -24646,7 +25497,7 @@ installing ${manifestPaths.length} upstream components (MCP serialized, rest par
24646
25497
  progress.done();
24647
25498
  if (forceFirstPass && b.failed.length > 0) {
24648
25499
  const probe = await makeIdempotentProbe(manifestPaths, setupContext);
24649
- const failed = [];
25500
+ const failed2 = [];
24650
25501
  for (const entry of b.failed) {
24651
25502
  const match = entry.match(/^([^:]+):\s*(.*)$/s);
24652
25503
  const name = (match?.[1] ?? entry).trim();
@@ -24660,9 +25511,9 @@ installing ${manifestPaths.length} upstream components (MCP serialized, rest par
24660
25511
  if (retained) {
24661
25512
  b.keptExisting ??= [];
24662
25513
  b.keptExisting.push({ name, reason: match?.[2]?.trim() ?? "" });
24663
- } else failed.push(entry);
25514
+ } else failed2.push(entry);
24664
25515
  }
24665
- b.failed = failed;
25516
+ b.failed = failed2;
24666
25517
  }
24667
25518
  const stepBMs = (b.elapsedMs / 1e3).toFixed(1);
24668
25519
  console.log(
@@ -25398,6 +26249,49 @@ function confineCleanupPath(raw, userHome = homedir()) {
25398
26249
  if (!abs.startsWith(home + sep)) return null;
25399
26250
  return abs;
25400
26251
  }
26252
+ async function runReceiptOwnedTeardownUnlocked(ctx) {
26253
+ let receipt;
26254
+ try {
26255
+ receipt = await readSkillOwnershipReceipt(ctx);
26256
+ } catch (error) {
26257
+ return {
26258
+ ok: false,
26259
+ phase: "preflight",
26260
+ error: error instanceof Error ? error.message : String(error)
26261
+ };
26262
+ }
26263
+ try {
26264
+ for (const path of receipt.createdPaths) await verifyOwnedSkillPath(receipt, path);
26265
+ } catch (error) {
26266
+ return {
26267
+ ok: false,
26268
+ phase: "preflight",
26269
+ error: error instanceof Error ? error.message : String(error)
26270
+ };
26271
+ }
26272
+ try {
26273
+ const transaction = await withQuarantineTransaction(
26274
+ async () => {
26275
+ for (const path of receipt.createdPaths) await removeOwnedSkillPath(receipt, path, ctx);
26276
+ },
26277
+ async () => removeSkillOwnershipReceipt(ctx)
26278
+ );
26279
+ if (transaction.cleanupFailures.length > 0) {
26280
+ return {
26281
+ ok: false,
26282
+ phase: "verify",
26283
+ error: transaction.cleanupFailures.join("; ")
26284
+ };
26285
+ }
26286
+ } catch (error) {
26287
+ return {
26288
+ ok: false,
26289
+ phase: "verify",
26290
+ error: error instanceof Error ? error.message : String(error)
26291
+ };
26292
+ }
26293
+ return { ok: true, removedPaths: [...receipt.createdPaths] };
26294
+ }
25401
26295
  function canonicalPath(path) {
25402
26296
  let candidate = path;
25403
26297
  const missing = [];
@@ -25426,54 +26320,14 @@ async function runDeclaredTeardown(ctx) {
25426
26320
  const abort = dryRunGate(ctx);
25427
26321
  if (abort) return abort;
25428
26322
  if (isSkillOwnershipManaged(ctx.manifest)) {
25429
- let receipt;
25430
- try {
25431
- receipt = await readSkillOwnershipReceipt(ctx);
25432
- } catch (error) {
25433
- return {
25434
- ok: false,
25435
- phase: "preflight",
25436
- error: error instanceof Error ? error.message : String(error)
25437
- };
25438
- }
25439
- try {
25440
- for (const path of receipt.createdPaths) await verifyOwnedSkillPath(receipt, path);
25441
- } catch (error) {
26323
+ if (!ctx.hostContext) {
25442
26324
  return {
25443
26325
  ok: false,
25444
26326
  phase: "preflight",
25445
- error: error instanceof Error ? error.message : String(error)
26327
+ error: "receipt-only uninstall requires a resolved host context"
25446
26328
  };
25447
26329
  }
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 };
26330
+ return withInstallOwnershipLock(ctx.hostContext, () => runReceiptOwnedTeardownUnlocked(ctx));
25477
26331
  }
25478
26332
  const cleanupTargets = [];
25479
26333
  const userHome = ctx.hostContext?.userHome ?? homedir();
@@ -25650,6 +26504,7 @@ async function runDeclaredTeardown(ctx) {
25650
26504
  var init_declaredTeardown = __esm({
25651
26505
  "src/uninstallers/lib/declaredTeardown.ts"() {
25652
26506
  init_componentPlan();
26507
+ init_installOwnershipLock();
25653
26508
  init_skillOwnershipReceipt();
25654
26509
  init_spawn();
25655
26510
  init_quarantineDelete();
@@ -25757,7 +26612,7 @@ var init_npmCli3 = __esm({
25757
26612
  cwd: ctx.hostContext.userHome,
25758
26613
  env: withHostInstallEnv(process.env, ctx.hostContext)
25759
26614
  } : {};
25760
- const result = await new Promise((resolve39) => {
26615
+ const result = await new Promise((resolve40) => {
25761
26616
  const child = isWin ? spawn("cmd.exe", ["/c", "npm", "uninstall", "-g", pkg], {
25762
26617
  ...spawnOptions,
25763
26618
  windowsHide: true
@@ -25768,15 +26623,15 @@ var init_npmCli3 = __esm({
25768
26623
  });
25769
26624
  const timer = setTimeout(() => {
25770
26625
  child.kill("SIGKILL");
25771
- resolve39({ exitCode: -1, stderr: `${stderr}[timeout]` });
26626
+ resolve40({ exitCode: -1, stderr: `${stderr}[timeout]` });
25772
26627
  }, 3e4);
25773
26628
  child.on("error", (e) => {
25774
26629
  clearTimeout(timer);
25775
- resolve39({ exitCode: -1, stderr: e.message });
26630
+ resolve40({ exitCode: -1, stderr: e.message });
25776
26631
  });
25777
26632
  child.on("close", (code2) => {
25778
26633
  clearTimeout(timer);
25779
- resolve39({ exitCode: code2 ?? -1, stderr });
26634
+ resolve40({ exitCode: code2 ?? -1, stderr });
25780
26635
  });
25781
26636
  });
25782
26637
  if (result.exitCode !== 0) {