harnessed 5.0.14 → 5.0.16

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
@@ -42,7 +42,7 @@ var init_package = __esm({
42
42
  "package.json"() {
43
43
  package_default = {
44
44
  name: "harnessed",
45
- version: "5.0.14",
45
+ version: "5.0.16",
46
46
  description: "AI coding harness package manager + composition orchestrator",
47
47
  type: "module",
48
48
  license: "Apache-2.0",
@@ -432,6 +432,8 @@ function renameLegacyRoot(source, target) {
432
432
  }
433
433
  }
434
434
  function migrateLegacyHarnessedRoot(context = captureHostInstallContext()) {
435
+ const override = process.env.HARNESSED_ROOT_OVERRIDE;
436
+ if (override !== void 0 && override !== "") return;
435
437
  const legacyRoot = join(context.userHome, ".harnessed");
436
438
  const newRoot = context.platform.stateRoot;
437
439
  const targetParent = dirname(newRoot);
@@ -2799,6 +2801,9 @@ var init_spec = __esm({
2799
2801
  );
2800
2802
  OwnershipRoot = Type.Union([
2801
2803
  Type.Literal("platform-skills"),
2804
+ // Phase 85 — the `skills` CLI installs into ~/.agents/skills by default and
2805
+ // links it into the host skills dir; the real files live here.
2806
+ Type.Literal("agents-skills"),
2802
2807
  Type.Literal("native-home"),
2803
2808
  Type.Literal("host-agents"),
2804
2809
  Type.Literal("host-commands")
@@ -4096,6 +4101,149 @@ var init_autoUpdateCmd = __esm({
4096
4101
  init_updateReminderPreferences();
4097
4102
  }
4098
4103
  });
4104
+
4105
+ // src/installers/lib/jsonSubtree.ts
4106
+ function isJsonObject(v) {
4107
+ return typeof v === "object" && v !== null && !Array.isArray(v);
4108
+ }
4109
+ function tryParseJsonObject(text) {
4110
+ try {
4111
+ const v = JSON.parse(text);
4112
+ return isJsonObject(v) ? v : null;
4113
+ } catch {
4114
+ return null;
4115
+ }
4116
+ }
4117
+ function hasOwn(obj, key) {
4118
+ return Object.hasOwn(obj, key);
4119
+ }
4120
+ function setOwn(obj, key, value) {
4121
+ Object.defineProperty(obj, key, {
4122
+ value,
4123
+ writable: true,
4124
+ enumerable: true,
4125
+ configurable: true
4126
+ });
4127
+ }
4128
+ function deepEqualJson(a, b) {
4129
+ if (a === b) return true;
4130
+ if (Array.isArray(a) && Array.isArray(b)) {
4131
+ return a.length === b.length && a.every((v, i) => deepEqualJson(v, b[i]));
4132
+ }
4133
+ if (isJsonObject(a) && isJsonObject(b)) {
4134
+ const aKeys = Object.keys(a);
4135
+ const bKeys = Object.keys(b);
4136
+ return aKeys.length === bKeys.length && aKeys.every((k) => hasOwn(b, k) && deepEqualJson(a[k], b[k]));
4137
+ }
4138
+ return false;
4139
+ }
4140
+ function diffJsonObjects(oldObj, newObj) {
4141
+ const changes = [];
4142
+ const walk = (o, n, base) => {
4143
+ for (const key of Object.keys(o)) {
4144
+ const path = [...base, key];
4145
+ if (!hasOwn(n, key)) {
4146
+ changes.push({ path, existed: true, value: o[key] });
4147
+ } else {
4148
+ compare(o[key], n[key], path);
4149
+ }
4150
+ }
4151
+ for (const key of Object.keys(n)) {
4152
+ if (!hasOwn(o, key)) changes.push({ path: [...base, key], existed: false });
4153
+ }
4154
+ };
4155
+ const compare = (a, b, path) => {
4156
+ if (isJsonObject(a) && isJsonObject(b)) {
4157
+ walk(a, b, path);
4158
+ } else if (!deepEqualJson(a, b)) {
4159
+ changes.push({ path, existed: true, value: a });
4160
+ }
4161
+ };
4162
+ walk(oldObj, newObj, []);
4163
+ return changes;
4164
+ }
4165
+ function containsUnsafeJsonNumber(value) {
4166
+ if (typeof value === "number") {
4167
+ return !Number.isFinite(value) || Number.isInteger(value) && !Number.isSafeInteger(value);
4168
+ }
4169
+ if (Array.isArray(value)) return value.some(containsUnsafeJsonNumber);
4170
+ if (isJsonObject(value)) {
4171
+ return Object.keys(value).some((k) => containsUnsafeJsonNumber(value[k]));
4172
+ }
4173
+ return false;
4174
+ }
4175
+ function pathsOverlap(a, b) {
4176
+ const n = Math.min(a.length, b.length);
4177
+ return a.slice(0, n).every((seg, i) => seg === b[i]);
4178
+ }
4179
+ function validateSubtreePayload(parsed) {
4180
+ if (!isJsonObject(parsed)) return { ok: false, reason: "payload is not a JSON object" };
4181
+ if (parsed.version !== SUBTREE_PAYLOAD_VERSION) {
4182
+ return { ok: false, reason: `unsupported payload version ${String(parsed.version)}` };
4183
+ }
4184
+ const raw = parsed.changes;
4185
+ if (!Array.isArray(raw)) return { ok: false, reason: "changes is not an array" };
4186
+ const changes = [];
4187
+ for (const item of raw) {
4188
+ if (!isJsonObject(item)) return { ok: false, reason: "change entry is not an object" };
4189
+ const { path, existed } = item;
4190
+ if (!Array.isArray(path) || path.length === 0 || !path.every((seg) => typeof seg === "string")) {
4191
+ return { ok: false, reason: "change path must be a non-empty string array" };
4192
+ }
4193
+ if (typeof existed !== "boolean") {
4194
+ return { ok: false, reason: "change existed must be boolean" };
4195
+ }
4196
+ const hasValue = hasOwn(item, "value");
4197
+ if (existed && !hasValue) {
4198
+ return { ok: false, reason: "existed change missing old value" };
4199
+ }
4200
+ if (!existed && hasValue) {
4201
+ return { ok: false, reason: "added-path change must not carry a value" };
4202
+ }
4203
+ const p8 = path;
4204
+ for (const prev of changes) {
4205
+ if (pathsOverlap(prev.path, p8)) {
4206
+ return {
4207
+ ok: false,
4208
+ reason: `duplicate or overlapping change path ${JSON.stringify(p8)}`
4209
+ };
4210
+ }
4211
+ }
4212
+ const change = { path: p8, existed };
4213
+ if (hasValue) change.value = item.value;
4214
+ changes.push(change);
4215
+ }
4216
+ return { ok: true, changes };
4217
+ }
4218
+ function applySubtreeChanges(current, changes) {
4219
+ for (const change of changes) {
4220
+ let node = current;
4221
+ for (const seg of change.path.slice(0, -1)) {
4222
+ const next = hasOwn(node, seg) ? node[seg] : void 0;
4223
+ if (!isJsonObject(next)) {
4224
+ return {
4225
+ ok: false,
4226
+ reason: `conflict at ${JSON.stringify(change.path)}: parent ${JSON.stringify(seg)} is missing or not an object`
4227
+ };
4228
+ }
4229
+ node = next;
4230
+ }
4231
+ const leaf = change.path[change.path.length - 1];
4232
+ if (change.existed) {
4233
+ setOwn(node, leaf, change.value);
4234
+ } else if (hasOwn(node, leaf)) {
4235
+ delete node[leaf];
4236
+ }
4237
+ }
4238
+ return { ok: true };
4239
+ }
4240
+ var SUBTREE_PAYLOAD_VERSION, SUBTREE_ENTRY_SHA1;
4241
+ var init_jsonSubtree = __esm({
4242
+ "src/installers/lib/jsonSubtree.ts"() {
4243
+ SUBTREE_PAYLOAD_VERSION = 1;
4244
+ SUBTREE_ENTRY_SHA1 = "json-subtree-v1";
4245
+ }
4246
+ });
4099
4247
  function getBackupRoot(hostContext) {
4100
4248
  return hostContext ? join(hostContext.platform.stateRoot, "backups") : harnessedSubdir("backups");
4101
4249
  }
@@ -4171,12 +4319,56 @@ async function backup(plan, ctx) {
4171
4319
  }
4172
4320
  };
4173
4321
  }
4174
- const sha1 = createHash("sha1").update(buf).digest("hex");
4175
4322
  const eol = detectEol(buf);
4176
4323
  const dest = mirrorPath(file.target, file.scope, backupDir, ctx.hostContext);
4324
+ const entry = {
4325
+ target: file.target,
4326
+ backup: dest,
4327
+ sha1: createHash("sha1").update(buf).digest("hex"),
4328
+ eol
4329
+ };
4330
+ let stored = buf;
4331
+ const oldJson = tryParseJsonObject(file.oldText);
4332
+ const newJson = tryParseJsonObject(file.newText);
4333
+ if (oldJson !== null && newJson !== null) {
4334
+ if (buf.toString("utf8") !== file.oldText) {
4335
+ return {
4336
+ ok: false,
4337
+ error: {
4338
+ file: filename,
4339
+ path: file.target,
4340
+ message: "on-disk content differs from plan oldText (stale plan); re-run the install to regenerate the plan",
4341
+ line: null,
4342
+ column: null,
4343
+ keyword: "backup-stale-plan"
4344
+ }
4345
+ };
4346
+ }
4347
+ if (containsUnsafeJsonNumber(oldJson) || containsUnsafeJsonNumber(newJson)) {
4348
+ return {
4349
+ ok: false,
4350
+ error: {
4351
+ file: filename,
4352
+ path: file.target,
4353
+ message: "JSON contains a number that cannot round-trip through JSON.stringify (non-finite or unsafe integer); scoped backup refused \u2014 edit the file manually",
4354
+ line: null,
4355
+ column: null,
4356
+ keyword: "backup-json-unsafe-number"
4357
+ }
4358
+ };
4359
+ }
4360
+ stored = Buffer.from(
4361
+ `${JSON.stringify({ version: 1, changes: diffJsonObjects(oldJson, newJson) }, null, 2)}
4362
+ `,
4363
+ "utf8"
4364
+ );
4365
+ entry.kind = "json-subtree";
4366
+ entry.sha1 = SUBTREE_ENTRY_SHA1;
4367
+ entry.payloadSha1 = createHash("sha1").update(stored).digest("hex");
4368
+ }
4177
4369
  try {
4178
4370
  await mkdir(dirname(dest), { recursive: true });
4179
- await writeFile(dest, buf);
4371
+ await writeFile(dest, stored);
4180
4372
  } catch (err2) {
4181
4373
  return {
4182
4374
  ok: false,
@@ -4190,7 +4382,7 @@ async function backup(plan, ctx) {
4190
4382
  }
4191
4383
  };
4192
4384
  }
4193
- entries.push({ target: file.target, backup: dest, sha1, eol });
4385
+ entries.push(entry);
4194
4386
  }
4195
4387
  const metadata = {
4196
4388
  installer: filename,
@@ -4221,6 +4413,7 @@ var HOME_DIR;
4221
4413
  var init_backup = __esm({
4222
4414
  "src/installers/lib/backup.ts"() {
4223
4415
  init_harnessedRoot();
4416
+ init_jsonSubtree();
4224
4417
  HOME_DIR = process.env.HOME ?? process.env.USERPROFILE ?? "";
4225
4418
  }
4226
4419
  });
@@ -16914,7 +17107,10 @@ var init_ccPluginMarketplace2 = __esm({
16914
17107
  const selectedPlugin = ctx.hostContext ? parseCmd(install.cmd)?.pluginAtMkt : void 0;
16915
17108
  const existingPlugin = ctx.hostContext && selectedPlugin ? await isPluginRegistered(selectedPlugin.split("@")[0] ?? selectedPlugin, ctx.hostContext) : false;
16916
17109
  const conflictingPlugin = ctx.hostContext && selectedPlugin && existingPlugin ? !await isPluginRegistered(selectedPlugin, ctx.hostContext) : false;
16917
- if (conflictingPlugin || ctx.hostContext && ctx.opts.updateInstalled && (existingPlugin || await isAlreadyInstalled(ctx, { honorUpdateFlag: false }))) {
17110
+ const qualifiedProven = Boolean(
17111
+ ctx.hostContext && existingPlugin && selectedPlugin && await isPluginRegistered(selectedPlugin, ctx.hostContext)
17112
+ );
17113
+ if (conflictingPlugin || ctx.hostContext && ctx.opts.updateInstalled && !qualifiedProven && (existingPlugin || await isAlreadyInstalled(ctx, { honorUpdateFlag: false }))) {
16918
17114
  return {
16919
17115
  ok: false,
16920
17116
  phase: "preflight",
@@ -16929,7 +17125,7 @@ var init_ccPluginMarketplace2 = __esm({
16929
17125
  }
16930
17126
  };
16931
17127
  }
16932
- if (existingPlugin || await isAlreadyInstalled(ctx)) {
17128
+ if (existingPlugin && !(ctx.opts.updateInstalled && qualifiedProven) || await isAlreadyInstalled(ctx)) {
16933
17129
  if (ctx.hostContext) {
16934
17130
  const parsed2 = parseCmd(install.cmd);
16935
17131
  if (!parsed2)
@@ -17891,6 +18087,52 @@ function unprovenCloneTarget(ctx) {
17891
18087
  }
17892
18088
  };
17893
18089
  }
18090
+ function normalizeGitUrl(url) {
18091
+ return url.replace(/\/+$/, "").replace(/\.git$/, "");
18092
+ }
18093
+ function extractCloneUrl(cmd) {
18094
+ const m = cmd.match(/\bgit\s+clone\s+((?:-{1,2}[\w-]+(?:\s+\S+)?\s+)*)(\S+)/);
18095
+ return m?.[2] ?? null;
18096
+ }
18097
+ function externalWriteTargets(cmd, destRaw) {
18098
+ const dest = destRaw.replace(/\/+$/, "");
18099
+ const inside = (target) => {
18100
+ const normalized2 = target.replace(/\/+$/, "");
18101
+ return normalized2 === dest || normalized2.startsWith(`${dest}/`);
18102
+ };
18103
+ const out = [];
18104
+ for (const segment of cmd.split(/\s*(?:&&|\|\||;|\|)\s*/)) {
18105
+ const tokens = segment.split(/\s+/).filter(Boolean);
18106
+ for (let index = 0; index < tokens.length; index++) {
18107
+ const token2 = tokens[index];
18108
+ if (token2 === "rm") {
18109
+ let next = index + 1;
18110
+ while (next < tokens.length && tokens[next].startsWith("-")) next++;
18111
+ const target = tokens[next];
18112
+ if (target && !inside(target)) out.push(target);
18113
+ index = next;
18114
+ continue;
18115
+ }
18116
+ if (token2 === "cp" || token2 === "mv" || token2 === "rsync") {
18117
+ const target = tokens[tokens.length - 1];
18118
+ if (target && target !== token2 && !inside(target)) out.push(target);
18119
+ index = tokens.length;
18120
+ }
18121
+ }
18122
+ }
18123
+ return out;
18124
+ }
18125
+ async function cloneOriginProven(checkoutDir, cmdUrl) {
18126
+ if (!cmdUrl) return false;
18127
+ try {
18128
+ const config = await readFile(join(checkoutDir, ".git", "config"), "utf8");
18129
+ const section = config.match(/\[remote "origin"\]([^[]*)/);
18130
+ const url = section?.[1]?.match(/url\s*=\s*(\S+)/)?.[1];
18131
+ return url !== void 0 && normalizeGitUrl(url) === normalizeGitUrl(cmdUrl);
18132
+ } catch {
18133
+ return false;
18134
+ }
18135
+ }
17894
18136
  function isSelfCleaningCloneCmd(cmd) {
17895
18137
  const parsed = extractRawCloneDest(cmd);
17896
18138
  if (!parsed) return false;
@@ -17958,7 +18200,8 @@ var init_gitCloneWithSetup2 = __esm({
17958
18200
  };
17959
18201
  }
17960
18202
  const cloneTarget = extractCloneTarget(install.cmd, ctx.hostContext?.userHome);
17961
- if (!cloneTarget) {
18203
+ const parsedDest = extractRawCloneDest(install.cmd);
18204
+ if (!cloneTarget || !parsedDest) {
17962
18205
  return {
17963
18206
  ok: false,
17964
18207
  phase: "preflight",
@@ -18004,9 +18247,15 @@ var init_gitCloneWithSetup2 = __esm({
18004
18247
  }
18005
18248
  }
18006
18249
  const plainClone = /^\s*git\s+clone\s+[^;&|<>`$\r\n]+$/.test(install.cmd);
18007
- if (ctx.hostContext && ctx.opts.updateInstalled) {
18008
- if (!plainClone || existingTarget || await isAlreadyInstalled(ctx, { honorUpdateFlag: false }))
18009
- return unprovenCloneTarget(ctx);
18250
+ const originProven = await cloneOriginProven(
18251
+ resolve(install.cwd ?? ctx.cwd, cloneTarget),
18252
+ extractCloneUrl(install.cmd)
18253
+ );
18254
+ const footprintBounded = externalWriteTargets(install.cmd, parsedDest.raw).length === 0;
18255
+ const installedSignal = existingTarget || (ctx.hostContext && ctx.opts.updateInstalled ? await isAlreadyInstalled(ctx, { honorUpdateFlag: false }) : false);
18256
+ const refreshAuthorized = ctx.opts.updateInstalled && installedSignal && originProven && footprintBounded;
18257
+ if (ctx.hostContext && ctx.opts.updateInstalled && !refreshAuthorized) {
18258
+ if (!plainClone || installedSignal) return unprovenCloneTarget(ctx);
18010
18259
  }
18011
18260
  if (await isAlreadyInstalled(ctx)) {
18012
18261
  const verifyFailure2 = await verifyInstalled(ctx);
@@ -18020,7 +18269,7 @@ var init_gitCloneWithSetup2 = __esm({
18020
18269
  );
18021
18270
  return { ok: true, alreadyInstalled: true, backupId: "noop-idempotent" };
18022
18271
  }
18023
- if (existingTarget) return unprovenCloneTarget(ctx);
18272
+ if (existingTarget && !refreshAuthorized) return unprovenCloneTarget(ctx);
18024
18273
  const name = ctx.manifest.metadata.name;
18025
18274
  const plan = {
18026
18275
  files: [
@@ -19083,6 +19332,8 @@ function declaredRootPath(ctx, root) {
19083
19332
  if (!host) return void 0;
19084
19333
  const roots = {
19085
19334
  "platform-skills": host.platform.skillsDir,
19335
+ // Phase 85 — the `skills` CLI's default install root.
19336
+ "agents-skills": join(host.userHome, ".agents", "skills"),
19086
19337
  "native-home": host.nativeHome,
19087
19338
  "host-agents": join(host.nativeHome, "agents"),
19088
19339
  "host-commands": host.platform.commandsDir
@@ -19404,7 +19655,13 @@ function isResource(value) {
19404
19655
  const resource = value;
19405
19656
  const selector = resource.selector;
19406
19657
  const marker = resource.marker;
19407
- const roots = ["platform-skills", "native-home", "host-agents", "host-commands"];
19658
+ const roots = [
19659
+ "platform-skills",
19660
+ "agents-skills",
19661
+ "native-home",
19662
+ "host-agents",
19663
+ "host-commands"
19664
+ ];
19408
19665
  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);
19409
19666
  const hasPrefix = typeof selector?.prefix === "string" && selector.prefix.length > 0;
19410
19667
  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));
@@ -19423,6 +19680,9 @@ function rootPath(ctx, root) {
19423
19680
  if (!host) return null;
19424
19681
  const roots = {
19425
19682
  "platform-skills": host.platform.skillsDir,
19683
+ // Phase 85 — the `skills` CLI's default install root (the real files of a
19684
+ // host-skills-dir symlink live here).
19685
+ "agents-skills": join(host.userHome, ".agents", "skills"),
19426
19686
  "native-home": host.nativeHome,
19427
19687
  "host-agents": join(host.nativeHome, "agents"),
19428
19688
  "host-commands": host.platform.commandsDir
@@ -19437,6 +19697,13 @@ function selected(resource, name) {
19437
19697
  const { names, prefix } = resource.selector;
19438
19698
  return Boolean(names?.includes(name) || prefix?.length && name.startsWith(prefix));
19439
19699
  }
19700
+ function declaredCoversSkillNames(ctx, names) {
19701
+ const claimed = (names ?? []).filter((name) => name.length > 0);
19702
+ if (claimed.length === 0) return true;
19703
+ const resources = resourcesFor(ctx);
19704
+ if (resources.length === 0) return false;
19705
+ return claimed.every((name) => resources.some((resource) => selected(resource, name)));
19706
+ }
19440
19707
  async function regularMarker(candidate, canonicalCandidate, resource) {
19441
19708
  const markerRelativePath = resource.marker.path;
19442
19709
  if (resource.kind === "directory" && !markerRelativePath) return false;
@@ -19607,13 +19874,19 @@ var init_npmCli2 = __esm({
19607
19874
  }
19608
19875
  const managesSkillOwnership = isSkillOwnershipManaged(ctx.manifest);
19609
19876
  const ownershipCandidateSnapshot = managesSkillOwnership ? await snapshotDeclaredOwnership(ctx) : void 0;
19610
- const usesDeclaredOwnership = Array.isArray(
19611
- ctx.manifest.spec.ownership?.resources
19612
- );
19877
+ const ownershipResources = ctx.manifest.spec.ownership?.resources;
19878
+ const usesDeclaredOwnership = Array.isArray(ownershipResources) && ownershipResources.length > 0;
19879
+ const declaredSnapshot = ownershipCandidateSnapshot ?? (usesDeclaredOwnership ? await snapshotDeclaredOwnership(ctx) : void 0);
19880
+ const declaredProven = usesDeclaredOwnership && // Phase 85 — every skill the manifest claims to install must be declared,
19881
+ // or the declaration does not bound what a refresh may overwrite.
19882
+ declaredCoversSkillNames(ctx, install.installs_skills) && declaredSnapshot !== void 0 && await (async () => {
19883
+ const discovered = await discoverDeclaredOwnership(ctx);
19884
+ return declaredSnapshot.paths.every((path) => discovered.paths.includes(path));
19885
+ })();
19613
19886
  let existingPackTarget = false;
19614
19887
  if (ctx.hostContext && (ctx.manifest.spec.component_type !== "cli-binary" || install.installs_skills !== void 0)) {
19615
19888
  if (usesDeclaredOwnership) {
19616
- existingPackTarget = (ownershipCandidateSnapshot?.paths.length ?? 0) > 0;
19889
+ existingPackTarget = (declaredSnapshot?.paths.length ?? 0) > 0;
19617
19890
  } else {
19618
19891
  const names = [ctx.manifest.metadata.name, ...install.installs_skills ?? []];
19619
19892
  if (names.some((name) => !/^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(name)))
@@ -19634,7 +19907,7 @@ var init_npmCli2 = __esm({
19634
19907
  existingPackTarget = true;
19635
19908
  }
19636
19909
  }
19637
- if (ctx.opts.updateInstalled && !usesDeclaredOwnership) return unprovenPackTarget(ctx);
19910
+ if (ctx.opts.updateInstalled && !declaredProven) return unprovenPackTarget(ctx);
19638
19911
  }
19639
19912
  if (await isAlreadyInstalled(ctx)) {
19640
19913
  const verifyFailure2 = await verifyInstalled(ctx, { neutralCwd: true });
@@ -19648,7 +19921,8 @@ var init_npmCli2 = __esm({
19648
19921
  );
19649
19922
  return { ok: true, alreadyInstalled: true, backupId: "noop-idempotent" };
19650
19923
  }
19651
- if (existingPackTarget) return unprovenPackTarget(ctx);
19924
+ if (existingPackTarget && !(ctx.opts.updateInstalled && declaredProven))
19925
+ return unprovenPackTarget(ctx);
19652
19926
  let level = detectLevel(install.cmd);
19653
19927
  let cmd = install.cmd;
19654
19928
  const plan = { files: [] };
@@ -19718,9 +19992,10 @@ var init_npmCli2 = __esm({
19718
19992
  try {
19719
19993
  if (usesDeclaredOwnership) {
19720
19994
  const discovered = await discoverDeclaredOwnership(ctx);
19995
+ const refreshAuthorized = ctx.opts.updateInstalled && declaredProven;
19721
19996
  await writeDeclaredOwnershipReceipt(ctx, {
19722
19997
  roots: discovered.roots,
19723
- paths: discovered.paths.filter((path) => !pathSnapshot.has(path))
19998
+ paths: refreshAuthorized ? discovered.paths : discovered.paths.filter((path) => !pathSnapshot.has(path))
19724
19999
  });
19725
20000
  } else {
19726
20001
  const afterPaths = await declaredSkillPaths(ctx, skillRoots);
@@ -19885,6 +20160,12 @@ var init_npxSkillInstaller2 = __esm({
19885
20160
  ] : [getSkillsDir()];
19886
20161
  const primaryActiveSkillsDir = activeSkillsDirs[0] ?? getSkillsDir();
19887
20162
  const ownershipCandidateSnapshot = await snapshotDeclaredOwnership(ctx);
20163
+ const declaredProven = usesDeclaredOwnership && // Phase 85 — every skill the manifest claims to install must be declared,
20164
+ // or the declaration does not bound what a refresh may overwrite.
20165
+ declaredCoversSkillNames(ctx, install.installs_skills) && await (async () => {
20166
+ const discovered = await discoverDeclaredOwnership(ctx);
20167
+ return ownershipCandidateSnapshot.paths.every((path) => discovered.paths.includes(path));
20168
+ })();
19888
20169
  let anyExistingTarget = false;
19889
20170
  if (ctx.hostContext) {
19890
20171
  if (usesDeclaredOwnership) {
@@ -19912,12 +20193,12 @@ var init_npxSkillInstaller2 = __esm({
19912
20193
  }
19913
20194
  }
19914
20195
  }
19915
- if (ctx.opts.updateInstalled && (!singleSkill || anyExistingTarget || await isAlreadyInstalled(ctx, { honorUpdateFlag: false })))
20196
+ if (ctx.opts.updateInstalled && !declaredProven && (!singleSkill || anyExistingTarget || await isAlreadyInstalled(ctx, { honorUpdateFlag: false })))
19916
20197
  return unprovenSkillTarget(ctx);
19917
20198
  }
19918
20199
  const activeTargetExists = await activeSkillPresent(activeSkillsDirs, activeTargetNames);
19919
20200
  const alreadyInstalled = ctx.hostContext ? !ctx.opts.dryRun && activeTargetExists : await isAlreadyInstalled(ctx);
19920
- if (alreadyInstalled) {
20201
+ if (alreadyInstalled && !(ctx.opts.updateInstalled && declaredProven)) {
19921
20202
  const verifyFailure2 = await verifyInstalled(ctx, { neutralCwd: true });
19922
20203
  if (verifyFailure2) return verifyFailure2;
19923
20204
  await recordObservedInstall(
@@ -20018,9 +20299,10 @@ var init_npxSkillInstaller2 = __esm({
20018
20299
  try {
20019
20300
  if (usesDeclaredOwnership) {
20020
20301
  const discovered = await discoverDeclaredOwnership(ctx);
20302
+ const refreshAuthorized = ctx.opts.updateInstalled && declaredProven;
20021
20303
  await writeDeclaredOwnershipReceipt(ctx, {
20022
20304
  roots: discovered.roots,
20023
- paths: discovered.paths.filter((path) => !pathSnapshot.has(path))
20305
+ paths: refreshAuthorized ? discovered.paths : discovered.paths.filter((path) => !pathSnapshot.has(path))
20024
20306
  });
20025
20307
  } else {
20026
20308
  const afterPaths = await declaredSkillPaths(ctx, skillRoots);
@@ -22153,7 +22435,7 @@ async function runBinarySelfUpdate(deps, opts) {
22153
22435
  try {
22154
22436
  const dir = join(deps.stateRoot(), "bin-backup", deps.currentVersion);
22155
22437
  await mkdir(dir, { recursive: true });
22156
- await copyFile$1(bakPath, join(dir, execBase));
22438
+ await copyFile$1(bakPath, join(dir, asset));
22157
22439
  backupDir = dir;
22158
22440
  copied = true;
22159
22441
  } catch (e) {
@@ -22198,20 +22480,26 @@ async function runBinaryRollback(deps, opts) {
22198
22480
  }
22199
22481
  const asset = assetNameFor(deps.platform, deps.arch);
22200
22482
  const backupsRoot = join(deps.stateRoot(), "bin-backup");
22201
- let versions = [];
22483
+ const execBase = basename(deps.execPath);
22484
+ const banked = /* @__PURE__ */ new Map();
22202
22485
  try {
22203
22486
  const entries = await readdir(backupsRoot, { withFileTypes: true });
22204
22487
  for (const e of entries) {
22205
22488
  if (!e.isDirectory()) continue;
22206
- const has = await access(join(backupsRoot, e.name, asset)).then(
22207
- () => true,
22208
- () => false
22209
- );
22210
- if (has) versions.push(e.name);
22489
+ for (const name of asset === execBase ? [asset] : [asset, execBase]) {
22490
+ const has = await access(join(backupsRoot, e.name, name)).then(
22491
+ () => true,
22492
+ () => false
22493
+ );
22494
+ if (has) {
22495
+ banked.set(e.name, name);
22496
+ break;
22497
+ }
22498
+ }
22211
22499
  }
22212
22500
  } catch {
22213
- versions = [];
22214
22501
  }
22502
+ const versions = [...banked.keys()];
22215
22503
  if (versions.length === 0) {
22216
22504
  return {
22217
22505
  status: "error",
@@ -22230,9 +22518,8 @@ async function runBinaryRollback(deps, opts) {
22230
22518
  } else {
22231
22519
  target = versions.reduce((a, b) => compareVersions(a, b) === "behind" ? b : a);
22232
22520
  }
22233
- const backupBin = join(backupsRoot, target, asset);
22521
+ const backupBin = join(backupsRoot, target, banked.get(target) ?? asset);
22234
22522
  const execDir = dirname(deps.execPath);
22235
- const execBase = basename(deps.execPath);
22236
22523
  const ext = deps.platform === "win32" ? ".exe" : "";
22237
22524
  const tempPath = join(execDir, `.harnessed-rollback-${deps.pid}${ext}`);
22238
22525
  const bakPath = join(execDir, `${execBase}.bak-${deps.currentVersion}`);
@@ -22281,7 +22568,7 @@ async function runBinaryRollback(deps, opts) {
22281
22568
  try {
22282
22569
  const dir = join(backupsRoot, deps.currentVersion);
22283
22570
  await mkdir(dir, { recursive: true });
22284
- await copyFile$1(bakPath, join(dir, execBase));
22571
+ await copyFile$1(bakPath, join(dir, asset));
22285
22572
  copied = true;
22286
22573
  } catch (e) {
22287
22574
  deps.log(
@@ -25291,9 +25578,49 @@ ${t("rollback.metadata_unreadable.fix")}`
25291
25578
  process.exit(1);
25292
25579
  return;
25293
25580
  }
25581
+ {
25582
+ const counts = /* @__PURE__ */ new Map();
25583
+ for (const entry of meta.files) {
25584
+ counts.set(entry.target, (counts.get(entry.target) ?? 0) + 1);
25585
+ }
25586
+ const dupInvolvingSubtree = meta.files.some(
25587
+ (entry) => entry.kind === "json-subtree" && (counts.get(entry.target) ?? 0) > 1
25588
+ );
25589
+ if (dupInvolvingSubtree) {
25590
+ console.error(
25591
+ "error: backup metadata has duplicate entries for a json-subtree target; refusing to guess composition order"
25592
+ );
25593
+ process.exit(1);
25594
+ return;
25595
+ }
25596
+ }
25294
25597
  const ordered = [...meta.files].reverse();
25295
25598
  const planned = [];
25296
25599
  for (const entry of ordered) {
25600
+ if (entry.kind === "json-subtree") {
25601
+ if (entry.sha1 !== SUBTREE_ENTRY_SHA1 || typeof entry.payloadSha1 !== "string" || !/^[a-f0-9]{40}$/.test(entry.payloadSha1) || entry.backup === "" || entry.sentinel !== void 0) {
25602
+ console.error(
25603
+ `error: malformed json-subtree backup entry for ${entry.target}; scoped snapshots require a compatible harnessed reader \u2014 restore manually`
25604
+ );
25605
+ process.exit(1);
25606
+ return;
25607
+ }
25608
+ } else {
25609
+ if (entry.kind !== void 0 && entry.kind !== "bytes") {
25610
+ console.error(
25611
+ `error: backup entry for ${entry.target} has unknown kind ${String(entry.kind)}; upgrade harnessed or restore manually`
25612
+ );
25613
+ process.exit(1);
25614
+ return;
25615
+ }
25616
+ if (entry.payloadSha1 !== void 0) {
25617
+ console.error(
25618
+ `error: backup entry for ${entry.target} carries payloadSha1 without json-subtree kind; refusing to guess its format`
25619
+ );
25620
+ process.exit(1);
25621
+ return;
25622
+ }
25623
+ }
25297
25624
  if (entry.backup === "") {
25298
25625
  if (entry.sentinel === "created") {
25299
25626
  planned.push({ target: entry.target, action: "remove-created" });
@@ -25327,13 +25654,81 @@ ${t("rollback.metadata_unreadable.fix")}`
25327
25654
  process.exit(1);
25328
25655
  return;
25329
25656
  }
25330
- const sha1 = createHash("sha1").update(buf).digest("hex");
25331
- if (sha1 !== entry.sha1) {
25657
+ const digest = createHash("sha1").update(buf).digest("hex");
25658
+ if (entry.kind === "json-subtree") {
25659
+ if (digest !== entry.payloadSha1) {
25660
+ console.error(
25661
+ t("rollback.checksum_mismatch", {
25662
+ target: entry.target,
25663
+ expected: (entry.payloadSha1 ?? "").slice(0, 12),
25664
+ actual: digest.slice(0, 12)
25665
+ })
25666
+ );
25667
+ process.exit(1);
25668
+ return;
25669
+ }
25670
+ let parsedPayload;
25671
+ try {
25672
+ parsedPayload = JSON.parse(buf.toString("utf8"));
25673
+ } catch {
25674
+ console.error(`error: backup payload for ${entry.target} is not valid JSON`);
25675
+ process.exit(1);
25676
+ return;
25677
+ }
25678
+ const payload = validateSubtreePayload(parsedPayload);
25679
+ if (!payload.ok) {
25680
+ console.error(
25681
+ `error: invalid json-subtree payload for ${entry.target}: ${payload.reason}`
25682
+ );
25683
+ process.exit(1);
25684
+ return;
25685
+ }
25686
+ const currentText = await (async () => {
25687
+ try {
25688
+ return await readFile(entry.target, "utf8");
25689
+ } catch {
25690
+ return null;
25691
+ }
25692
+ })();
25693
+ const current = currentText === null ? null : tryParseJsonObject(currentText);
25694
+ if (current === null) {
25695
+ console.error(
25696
+ `error: cannot restore ${entry.target}: current content is not a readable JSON object (refusing to overwrite user edits)`
25697
+ );
25698
+ process.exit(1);
25699
+ return;
25700
+ }
25701
+ const unsafe = containsUnsafeJsonNumber(current) || payload.changes.some((c) => c.existed && containsUnsafeJsonNumber(c.value));
25702
+ if (unsafe) {
25703
+ console.error(
25704
+ `error: cannot restore ${entry.target}: JSON contains a number that cannot round-trip through JSON.stringify (non-finite or unsafe integer) \u2014 restore manually`
25705
+ );
25706
+ process.exit(1);
25707
+ return;
25708
+ }
25709
+ const applied = applySubtreeChanges(current, payload.changes);
25710
+ if (!applied.ok) {
25711
+ console.error(`error: cannot restore ${entry.target}: ${applied.reason}`);
25712
+ process.exit(1);
25713
+ return;
25714
+ }
25715
+ planned.push({
25716
+ target: entry.target,
25717
+ action: "write",
25718
+ data: normalizeEol(
25719
+ Buffer.from(`${JSON.stringify(current, null, 2)}
25720
+ `, "utf8"),
25721
+ entry.eol
25722
+ )
25723
+ });
25724
+ continue;
25725
+ }
25726
+ if (digest !== entry.sha1) {
25332
25727
  console.error(
25333
25728
  t("rollback.checksum_mismatch", {
25334
25729
  target: entry.target,
25335
25730
  expected: entry.sha1.slice(0, 12),
25336
- actual: sha1.slice(0, 12)
25731
+ actual: digest.slice(0, 12)
25337
25732
  })
25338
25733
  );
25339
25734
  process.exit(1);
@@ -25372,6 +25767,7 @@ var init_rollback = __esm({
25372
25767
  "src/cli/rollback.ts"() {
25373
25768
  init_i18n();
25374
25769
  init_backup();
25770
+ init_jsonSubtree();
25375
25771
  init_path_guard();
25376
25772
  }
25377
25773
  });
@@ -25751,6 +26147,10 @@ async function warnIfAgentTeamsMissing() {
25751
26147
  async function scanWorkflowsWithSkill(workflowsDir, entries) {
25752
26148
  return scanWorkflowsNested(workflowsDir, entries);
25753
26149
  }
26150
+ function isGlobalNpmInstall(plan) {
26151
+ if (effectiveInstallMethod(plan) !== "npm-cli") return false;
26152
+ return /\bnpm\s+install\s+-g\b/.test(plan.manifest.spec.install.cmd);
26153
+ }
25754
26154
  async function runStepBInstall(manifestPaths, runOpts = {}) {
25755
26155
  const hostContext = runOpts.hostContext ?? captureHostInstallContext();
25756
26156
  const opts = {
@@ -25765,6 +26165,7 @@ async function runStepBInstall(manifestPaths, runOpts = {}) {
25765
26165
  };
25766
26166
  const start = Date.now();
25767
26167
  const componentTypes = {};
26168
+ const globalNpmComponents = [];
25768
26169
  const failureKeywords = {};
25769
26170
  const total = manifestPaths.length;
25770
26171
  let done = 0;
@@ -25799,12 +26200,18 @@ async function runStepBInstall(manifestPaths, runOpts = {}) {
25799
26200
  }
25800
26201
  const plan = resolveComponentPlan(v.manifest, hostContext, "install");
25801
26202
  componentTypes[v.manifest.metadata.name] = installGroupForPlan(plan);
26203
+ if (isGlobalNpmInstall(plan)) globalNpmComponents.push(v.manifest.metadata.name);
25802
26204
  valid.push({ manifest: v.manifest, plan });
25803
26205
  }
25804
- const runOne = async (manifest) => {
26206
+ const runOne = async (manifest, plan) => {
25805
26207
  const name = manifest.metadata.name;
25806
26208
  try {
25807
- const r = await runInstall(manifest, opts, hostContext);
26209
+ const forceSystem = runOpts.forceSystemScope === true && plan !== void 0 && isGlobalNpmInstall(plan);
26210
+ const r = await runInstall(
26211
+ manifest,
26212
+ forceSystem ? { ...opts, system: true } : opts,
26213
+ hostContext
26214
+ );
25808
26215
  if ("aborted" in r) {
25809
26216
  const reason = r.reason === "harness-mismatch" ? `harness-mismatch \u2014 claude-only install method (no ${hostContext.hostId} equivalent)` : r.reason === "level-flag-missing" && runOpts.updateInstalled === true ? `L4 system-scope \u2014 excluded from force-update; update manually: \`${manifest.spec.install.cmd}\`` : r.reason;
25810
26217
  return emit({ status: "skipped", name, reason });
@@ -25822,12 +26229,12 @@ async function runStepBInstall(manifestPaths, runOpts = {}) {
25822
26229
  const rest = valid.filter((v) => !MCP_METHODS.has(effectiveInstallMethod(v.plan)));
25823
26230
  const runMcpSerial = async () => {
25824
26231
  const out = [];
25825
- for (const { manifest } of mcp) out.push(await runOne(manifest));
26232
+ for (const { manifest, plan } of mcp) out.push(await runOne(manifest, plan));
25826
26233
  return out;
25827
26234
  };
25828
26235
  const [mcpEntries, restSettled] = await Promise.all([
25829
26236
  runMcpSerial(),
25830
- Promise.allSettled(rest.map(({ manifest }) => runOne(manifest)))
26237
+ Promise.allSettled(rest.map(({ manifest, plan }) => runOne(manifest, plan)))
25831
26238
  ]);
25832
26239
  const restEntries = restSettled.map(
25833
26240
  (s) => s.status === "fulfilled" ? s.value : { status: "failed", name: "?", reason: String(s.reason) }
@@ -25849,7 +26256,8 @@ async function runStepBInstall(manifestPaths, runOpts = {}) {
25849
26256
  failed: failed2,
25850
26257
  failureKeywords,
25851
26258
  elapsedMs: Date.now() - start,
25852
- componentTypes
26259
+ componentTypes,
26260
+ globalNpmComponents
25853
26261
  };
25854
26262
  }
25855
26263
  async function reclassifyForceUpdateFailures(firstPass, forcePass, probe) {
@@ -25861,7 +26269,7 @@ async function reclassifyForceUpdateFailures(firstPass, forcePass, probe) {
25861
26269
  const name = (m?.[1] ?? entry).trim();
25862
26270
  if (priorlyInstalled.has(name)) {
25863
26271
  if (forcePass.failureKeywords?.[name] === "update-unsupported") {
25864
- keptExisting.push({ name, reason: m?.[2]?.trim() ?? "" });
26272
+ keptExisting.push({ name, reason: m?.[2]?.trim() ?? "", retryable: false });
25865
26273
  continue;
25866
26274
  }
25867
26275
  let present = false;
@@ -25871,7 +26279,7 @@ async function reclassifyForceUpdateFailures(firstPass, forcePass, probe) {
25871
26279
  present = false;
25872
26280
  }
25873
26281
  if (present) {
25874
- keptExisting.push({ name, reason: m?.[2]?.trim() ?? "" });
26282
+ keptExisting.push({ name, reason: m?.[2]?.trim() ?? "", retryable: true });
25875
26283
  continue;
25876
26284
  }
25877
26285
  }
@@ -26761,7 +27169,11 @@ installing ${manifestPaths.length} upstream components (MCP serialized, rest par
26761
27169
  }
26762
27170
  if (retained) {
26763
27171
  b.keptExisting ??= [];
26764
- b.keptExisting.push({ name, reason: match?.[2]?.trim() ?? "" });
27172
+ b.keptExisting.push({
27173
+ name,
27174
+ reason: match?.[2]?.trim() ?? "",
27175
+ retryable: b.failureKeywords?.[name] !== "update-unsupported"
27176
+ });
26765
27177
  } else failed2.push(entry);
26766
27178
  }
26767
27179
  b.failed = failed2;
@@ -26777,14 +27189,17 @@ installing ${manifestPaths.length} upstream components (MCP serialized, rest par
26777
27189
  })
26778
27190
  );
26779
27191
  printGrouped(b);
27192
+ let forceInstalledNames = [];
26780
27193
  if (!forceFirstPass && !dryRun && raw.nonInteractive !== true && b.alreadyInstalled.length > 0) {
26781
27194
  const isTty = process.stdin.isTTY === true && process.stdout.isTTY === true;
26782
27195
  if (isTty) {
26783
27196
  const { confirm: confirm6, isCancel: isCancel8 } = await import('@clack/prompts');
26784
27197
  const mcpExcluded = b.alreadyInstalled.filter((n) => b.componentTypes[n] === "mcp-tool");
26785
27198
  const exclusionNote = mcpExcluded.length > 0 ? ` (${mcpExcluded.length} MCP server(s) excluded \u2014 they ignore force-update: ${mcpExcluded.join(", ")})` : "";
27199
+ const globalNpm = b.globalNpmComponents ?? [];
27200
+ const systemNote = globalNpm.length > 0 ? ` (${globalNpm.join(", ")} will be installed/upgraded in system scope via the official \`npm install -g\` command)` : "";
26786
27201
  const ans = await confirm6({
26787
- message: `Update ${b.alreadyInstalled.length} already-installed plugin(s) listed above?${exclusionNote}`,
27202
+ message: `Update ${b.alreadyInstalled.length} already-installed plugin(s) listed above?${exclusionNote}${systemNote}`,
26788
27203
  initialValue: false
26789
27204
  });
26790
27205
  if (!isCancel8(ans) && ans === true) {
@@ -26794,6 +27209,11 @@ force-updating ${b.alreadyInstalled.length} plugin(s)...`);
26794
27209
  hostContext: setupContext,
26795
27210
  updateInstalled: true,
26796
27211
  system: raw.system === true,
27212
+ // Phase 85 — the force pass upgrades global npm tools with the
27213
+ // official command (`npm install -g <pkg>`). The user already
27214
+ // confirmed this pass; the L4 gate does not apply to the official
27215
+ // npm upgrade path.
27216
+ forceSystemScope: true,
26797
27217
  quiet: true,
26798
27218
  onProgress: progress.onProgress
26799
27219
  });
@@ -26807,12 +27227,23 @@ force-updating ${b.alreadyInstalled.length} plugin(s)...`);
26807
27227
  `
26808
27228
  Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting.length} kept-existing / ${b2.alreadyInstalled.length} still-already-installed (MCP) / ${b2.skipped.length} skipped / ${b2.failed.length} failed [parallel ${stepB2Ms}s]`
26809
27229
  );
27230
+ forceInstalledNames = b2.installed;
26810
27231
  printGrouped(b2, "[force-update] ");
26811
27232
  if (b2.keptExisting.length > 0) {
26812
- console.warn(
26813
- `
26814
- ${b2.keptExisting.length} plugin(s) kept their existing version \u2014 refresh failed but the prior install is still usable. Re-run \`harnessed setup\` later to retry the update.`
26815
- );
27233
+ const blocked = b2.keptExisting.filter((entry) => entry.retryable === false);
27234
+ const retryable = b2.keptExisting.filter((entry) => entry.retryable !== false);
27235
+ if (retryable.length > 0) {
27236
+ console.warn(
27237
+ `
27238
+ ${retryable.length} plugin(s) kept their existing version \u2014 refresh failed but the prior install is still usable. Re-run \`harnessed setup\` later to retry the update.`
27239
+ );
27240
+ }
27241
+ if (blocked.length > 0) {
27242
+ console.warn(
27243
+ `
27244
+ ${blocked.length} component(s) kept their existing version \u2014 harnessed refuses to replace them (existing source or write footprint not provably ours). Update them with their upstream tool: ${blocked.map((entry) => entry.name).join(", ")}`
27245
+ );
27246
+ }
26816
27247
  }
26817
27248
  mergeStepBResults(b, b2);
26818
27249
  }
@@ -27019,6 +27450,14 @@ Force-update pass complete: ${b2.installed.length} installed / ${b2.keptExisting
27019
27450
  setupFailures.push(userLangResult.message);
27020
27451
  }
27021
27452
  }
27453
+ if (forceInstalledNames.length > 0) {
27454
+ const upgraded = new Set(forceInstalledNames);
27455
+ b.skipped = b.skipped.filter((entry) => !upgraded.has(entry.name));
27456
+ b.failed = b.failed.filter((failure) => {
27457
+ const name = failure.split(": ", 1)[0] ?? failure;
27458
+ return !upgraded.has(name);
27459
+ });
27460
+ }
27022
27461
  let pendingNonInteractiveL4Repair = false;
27023
27462
  const hasL4RepairCandidate = b.skipped.some((s) => s.reason === "level-flag-missing") || b.failed.some((failure) => {
27024
27463
  const name = failure.split(": ", 1)[0] ?? failure;
@@ -28539,7 +28978,7 @@ async function runOwnedRefreshEntry() {
28539
28978
  const { captureHostInstallContext: captureHostInstallContext3 } = await Promise.resolve().then(() => (init_hostInstallContext(), hostInstallContext_exports));
28540
28979
  const context = captureHostInstallContext3();
28541
28980
  const outcome = await refreshOwnedState(context);
28542
- writeAutoUpdateNoticeForNewBinary(context);
28981
+ await writeAutoUpdateNoticeForNewBinary(context);
28543
28982
  if (outcome.ok) {
28544
28983
  console.log(
28545
28984
  `[harnessed] owned state refreshed (${outcome.updated.length} component(s): ${outcome.updated.join(", ")})`