@ipab/cli 0.1.0-rc.6 → 0.1.0-rc.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.
Files changed (97) hide show
  1. package/README.md +72 -33
  2. package/dist/app-authoring.d.ts +5 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +4 -1
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/app-templates.d.ts +0 -1
  7. package/dist/app-templates.d.ts.map +1 -1
  8. package/dist/app-templates.js +6 -45
  9. package/dist/app-templates.js.map +1 -1
  10. package/dist/builtins/skill.ipab.car +0 -0
  11. package/dist/builtins/template.bundle-viewer.car +0 -0
  12. package/dist/builtins/template.check.car +0 -0
  13. package/dist/builtins/template.node.car +0 -0
  14. package/dist/builtins/template.web-app.car +0 -0
  15. package/dist/builtins.d.ts.map +1 -1
  16. package/dist/builtins.js +1 -39
  17. package/dist/builtins.js.map +1 -1
  18. package/dist/cli.d.ts +1 -0
  19. package/dist/cli.d.ts.map +1 -1
  20. package/dist/cli.js +395 -86
  21. package/dist/cli.js.map +1 -1
  22. package/dist/context.d.ts +16 -0
  23. package/dist/context.d.ts.map +1 -1
  24. package/dist/context.js +20 -0
  25. package/dist/context.js.map +1 -1
  26. package/dist/ipc.d.ts +2 -1
  27. package/dist/ipc.d.ts.map +1 -1
  28. package/dist/ipc.js +44 -3
  29. package/dist/ipc.js.map +1 -1
  30. package/dist/runtime.d.ts.map +1 -1
  31. package/dist/runtime.js +6 -3
  32. package/dist/runtime.js.map +1 -1
  33. package/dist/skill-definition.d.ts +6 -0
  34. package/dist/skill-definition.d.ts.map +1 -0
  35. package/dist/skill-definition.js +38 -0
  36. package/dist/skill-definition.js.map +1 -0
  37. package/dist/skill-source.d.ts +5 -0
  38. package/dist/skill-source.d.ts.map +1 -0
  39. package/dist/skill-source.js +12 -0
  40. package/dist/skill-source.js.map +1 -0
  41. package/dist/skills.d.ts +84 -0
  42. package/dist/skills.d.ts.map +1 -0
  43. package/dist/skills.js +736 -0
  44. package/dist/skills.js.map +1 -0
  45. package/dist/space.d.ts +15 -2
  46. package/dist/space.d.ts.map +1 -1
  47. package/dist/space.js +153 -3
  48. package/dist/space.js.map +1 -1
  49. package/dist/state.js +1 -1
  50. package/dist/swarm-files.d.ts +1 -1
  51. package/dist/swarm-files.d.ts.map +1 -1
  52. package/dist/swarm-files.js +2 -2
  53. package/dist/swarm-files.js.map +1 -1
  54. package/dist/swarm-meta.d.ts +17 -0
  55. package/dist/swarm-meta.d.ts.map +1 -0
  56. package/dist/swarm-meta.js +96 -0
  57. package/dist/swarm-meta.js.map +1 -0
  58. package/dist/swarm.d.ts +53 -0
  59. package/dist/swarm.d.ts.map +1 -1
  60. package/dist/swarm.js +465 -73
  61. package/dist/swarm.js.map +1 -1
  62. package/dist/template-paths.d.ts +7 -0
  63. package/dist/template-paths.d.ts.map +1 -0
  64. package/dist/template-paths.js +23 -0
  65. package/dist/template-paths.js.map +1 -0
  66. package/dist/template-presentation.d.ts +20 -0
  67. package/dist/template-presentation.d.ts.map +1 -0
  68. package/dist/template-presentation.js +133 -0
  69. package/dist/template-presentation.js.map +1 -0
  70. package/dist/template-source.d.ts +2 -1
  71. package/dist/template-source.d.ts.map +1 -1
  72. package/dist/template-source.js +7 -1
  73. package/dist/template-source.js.map +1 -1
  74. package/dist/templates.d.ts +11 -0
  75. package/dist/templates.d.ts.map +1 -0
  76. package/dist/templates.js +53 -0
  77. package/dist/templates.js.map +1 -0
  78. package/package.json +7 -6
  79. package/src/app-authoring.ts +18 -2
  80. package/src/app-templates.ts +8 -72
  81. package/src/builtins.ts +2 -48
  82. package/src/cli.ts +474 -71
  83. package/src/context.ts +45 -0
  84. package/src/ipc.ts +63 -2
  85. package/src/runtime.ts +6 -2
  86. package/src/skill-definition.ts +53 -0
  87. package/src/skill-source.ts +15 -0
  88. package/src/skills.ts +1005 -0
  89. package/src/space.ts +214 -5
  90. package/src/state.ts +1 -1
  91. package/src/swarm-files.ts +2 -1
  92. package/src/swarm-meta.ts +109 -0
  93. package/src/swarm.ts +721 -128
  94. package/src/template-paths.ts +43 -0
  95. package/src/template-presentation.ts +151 -0
  96. package/src/template-source.ts +9 -2
  97. package/src/templates.ts +77 -0
package/src/swarm.ts CHANGED
@@ -51,7 +51,7 @@ import {
51
51
  } from "./identity.js";
52
52
  import { nodeError } from "./authoring.js";
53
53
  import { swarmUrl as canonicalSwarmUrl } from "./config.js";
54
- import { bundleJson, provideContent } from "./content-provider.js";
54
+ import { bundleJson, contentCar, provideContent } from "./content-provider.js";
55
55
  import {
56
56
  failedPin,
57
57
  pinCid,
@@ -97,6 +97,22 @@ import {
97
97
  type ListenMode,
98
98
  } from "./kubo.js";
99
99
  import { memberPeers } from "./kubo-peering.js";
100
+ import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
101
+ import { inspectTemplate, templatePublicationSource } from "./templates.js";
102
+ import { seedSkillSource } from "./skill-source.js";
103
+ import { skillIdentity, skillSchema } from "./skill-definition.js";
104
+ import {
105
+ parseSwarmMeta,
106
+ swarmMetaType,
107
+ swarmMetaSchema,
108
+ swarmStateType,
109
+ legacySwarmStateType,
110
+ legacySwarmStateSchema,
111
+ isSwarmStateSchema,
112
+ type SwarmMeta,
113
+ legacySwarmMetaType,
114
+ legacySwarmMetaSchema,
115
+ } from "./swarm-meta.js";
100
116
 
101
117
  export interface Member {
102
118
  memberId?: string;
@@ -134,6 +150,7 @@ export interface Snapshot {
134
150
  v: 2;
135
151
  names: Record<string, CID>;
136
152
  registrations?: Record<string, { appCid: CID; argv: string[] }>;
153
+ stateBundle?: { meta: SwarmMeta; cid: string };
137
154
  }
138
155
  export interface MembershipRequest {
139
156
  v: 1;
@@ -1225,10 +1242,33 @@ export async function jsonBundle(
1225
1242
  await encoded.close();
1226
1243
  }
1227
1244
  }
1245
+ async function writeStateBundle(
1246
+ store: IpfsStore,
1247
+ configuration: SwarmMeta,
1248
+ targets: Record<string, CID>,
1249
+ ): Promise<string> {
1250
+ const meta = parseSwarmMeta(configuration);
1251
+ const names = Object.fromEntries(
1252
+ Object.entries(targets).map(([name, cid]) => [
1253
+ formalName(name),
1254
+ cid.toString(),
1255
+ ]),
1256
+ );
1257
+ return jsonBundle(
1258
+ store,
1259
+ meta.skillPath === undefined ? legacySwarmStateType : swarmStateType,
1260
+ { v: 5, ...meta, names },
1261
+ );
1262
+ }
1228
1263
  export async function writeSnapshot(
1229
1264
  store: IpfsStore,
1230
1265
  snapshot: Snapshot,
1231
1266
  ): Promise<string> {
1267
+ if (snapshot.stateBundle) {
1268
+ if (Object.keys(snapshot.registrations ?? {}).length)
1269
+ throw new HostError("State Bundles cannot contain legacy registrations.");
1270
+ return writeStateBundle(store, snapshot.stateBundle.meta, snapshot.names);
1271
+ }
1232
1272
  const put = async (value: unknown) => {
1233
1273
  const encoded = dagCbor.encode(value);
1234
1274
  const cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
@@ -1236,12 +1276,61 @@ export async function writeSnapshot(
1236
1276
  return cid;
1237
1277
  };
1238
1278
  const names = await put(snapshot.names);
1239
- const registrations = await put(snapshot.registrations ?? {});
1240
- return (await put({ v: 3, names, registrations })).toString();
1279
+ if (Object.keys(snapshot.registrations ?? {}).length) {
1280
+ const registrations = await put(snapshot.registrations);
1281
+ return (await put({ v: 3, names, registrations })).toString();
1282
+ }
1283
+ return (await put({ v: 4, names })).toString();
1241
1284
  }
1242
1285
  async function readState(store: IpfsStore, cid: CID): Promise<Snapshot> {
1286
+ if (cid.code !== dagCbor.code) {
1287
+ const bundle = await openBundle(cid, {
1288
+ resolveCid: (key) => store.block.get(key.toString()),
1289
+ });
1290
+ const type =
1291
+ bundle.schemaKey === legacySwarmStateSchema.cid.toString()
1292
+ ? legacySwarmStateType
1293
+ : swarmStateType;
1294
+ const value = object(
1295
+ await typedJson(store, cid.toString(), type),
1296
+ "State Bundle",
1297
+ );
1298
+ if (
1299
+ value.v !== 5 ||
1300
+ Object.keys(value).sort().join() !==
1301
+ (type === legacySwarmStateType
1302
+ ? "names,registryPath,templatePath,v"
1303
+ : "names,registryPath,skillPath,templatePath,v")
1304
+ )
1305
+ throw new HostError("Invalid State Bundle entry.");
1306
+ const meta = parseSwarmMeta({
1307
+ templatePath: value.templatePath,
1308
+ registryPath: value.registryPath,
1309
+ ...(type === legacySwarmStateType ? {} : { skillPath: value.skillPath }),
1310
+ });
1311
+ const names = Object.fromEntries(
1312
+ Object.entries(object(value.names, "Names")).map(([name, target]) => {
1313
+ formalName(name);
1314
+ if (typeof target !== "string" || exactCid(target) !== target)
1315
+ throw new HostError("State Names require exact canonical CIDs.");
1316
+ return [name, CID.parse(target)];
1317
+ }),
1318
+ );
1319
+ return { v: 2, names, stateBundle: { meta, cid: cid.toString() } };
1320
+ }
1243
1321
  const data = await store.block.get(cid.toString());
1244
1322
  const root = object(dagCbor.decode(data), "State");
1323
+ if (root.v === 4) {
1324
+ const names = CID.asCID(root.names);
1325
+ if (!names || Object.keys(root).sort().join() !== "names,v")
1326
+ throw new HostError("Invalid State Names root.");
1327
+ return decodeSnapshot(
1328
+ dagCbor.encode({
1329
+ v: 2,
1330
+ names: dagCbor.decode(await store.block.get(names.toString())),
1331
+ }),
1332
+ );
1333
+ }
1245
1334
  if (root.v !== 3) return decodeSnapshot(data);
1246
1335
  const names = CID.asCID(root.names),
1247
1336
  registrations = CID.asCID(root.registrations);
@@ -1378,6 +1467,16 @@ export interface SwarmHeader {
1378
1467
  projection?: SwarmProjection;
1379
1468
  localSourceReady?: boolean;
1380
1469
  }
1470
+ function missingContent(cause: unknown): boolean {
1471
+ let failure: unknown = cause;
1472
+ for (
1473
+ let depth = 0;
1474
+ depth < 8 && failure instanceof ContentBundleError;
1475
+ depth++
1476
+ )
1477
+ failure = failure.cause;
1478
+ return failure instanceof ContentError && failure.code === "missing_block";
1479
+ }
1381
1480
  export async function sharedSwarmStatus(
1382
1481
  context: SwarmContext,
1383
1482
  configUrl: string,
@@ -1391,8 +1490,7 @@ export async function sharedSwarmStatus(
1391
1490
  try {
1392
1491
  content = await readHeaderSnapshot(context.store, head.root);
1393
1492
  } catch (cause) {
1394
- if (!(cause instanceof ContentError) || cause.code !== "missing_block")
1395
- throw cause;
1493
+ if (!missingContent(cause)) throw cause;
1396
1494
  const registered = withState(context, (state) =>
1397
1495
  state.swarms().some((entry) => entry.cid === configUrl),
1398
1496
  );
@@ -1536,7 +1634,23 @@ async function cachedHeader(
1536
1634
  !(age >= 0 && age < (context.cacheTtl ?? 300) * 1000)
1537
1635
  )
1538
1636
  return;
1539
- const snapshot = decodeSnapshot(Buffer.from(cached.snapshot, "base64"));
1637
+ const cachedSnapshot = object(
1638
+ dagCbor.decode(Buffer.from(cached.snapshot, "base64")),
1639
+ "cached State",
1640
+ );
1641
+ const { stateBundle, ...legacySnapshot } = cachedSnapshot;
1642
+ const snapshot = decodeSnapshot(dagCbor.encode(legacySnapshot));
1643
+ if (stateBundle !== undefined) {
1644
+ const data = object(stateBundle, "cached State Bundle");
1645
+ if (
1646
+ Object.keys(data).sort().join() !== "cid,meta" ||
1647
+ typeof data.cid !== "string" ||
1648
+ exactCid(data.cid) !== data.cid ||
1649
+ (cached.stateCid !== undefined && data.cid !== cached.stateCid)
1650
+ )
1651
+ throw new HostError("Invalid cached State Bundle.");
1652
+ snapshot.stateBundle = { meta: parseSwarmMeta(data.meta), cid: data.cid };
1653
+ }
1540
1654
  let stateCid = cached.stateCid;
1541
1655
  if (!stateCid) {
1542
1656
  try {
@@ -1582,9 +1696,7 @@ function projectHeader(
1582
1696
  membership: JSON.stringify({ owner: record.owner, member }),
1583
1697
  };
1584
1698
  withState(context, (state) => {
1585
- state.projectSwarm(binding, header.snapshot.names, () =>
1586
- snapshotAssociations(header.snapshot),
1587
- );
1699
+ state.projectSwarm(binding, header.snapshot.names, () => []);
1588
1700
  });
1589
1701
  header.projection = binding;
1590
1702
  }
@@ -1719,6 +1831,7 @@ interface Creation {
1719
1831
  profileId?: string;
1720
1832
  configId?: string;
1721
1833
  config?: Organization;
1834
+ seed?: { root: string; car: string; roots: string[] };
1722
1835
  }
1723
1836
  export async function createSwarm(
1724
1837
  context: SwarmContext,
@@ -1782,6 +1895,50 @@ export async function createSwarm(
1782
1895
  const save = () => writePrivate(dir, `creation-${op}.json`, record);
1783
1896
  const api = client(context, service, identity);
1784
1897
  try {
1898
+ if (!record.seed) {
1899
+ if (record.headId)
1900
+ throw new HostError(
1901
+ "Legacy creation has an unseeded HEAD. Preserve this recovery record and explicitly migrate the Swarm; it cannot complete as a newly seeded Swarm.",
1902
+ );
1903
+ const names: Record<string, CID> = {};
1904
+ for (const selector of seedTemplateNames) {
1905
+ const template = await seedTemplateSource(selector);
1906
+ for (const [cid, data] of template.blocks)
1907
+ await context.store.put(CID.parse(cid), data);
1908
+ names[`ipab/template/${selector}`] = CID.parse(template.cid);
1909
+ }
1910
+ const skill = await seedSkillSource();
1911
+ for (const [cid, data] of skill.blocks)
1912
+ await context.store.put(CID.parse(cid), data);
1913
+ names["ipab/skills/ipab"] = CID.parse(skill.cid);
1914
+ const root = await publication(
1915
+ context.store,
1916
+ await writeStateBundle(
1917
+ context.store,
1918
+ {
1919
+ templatePath: "ipab/template",
1920
+ registryPath: "ipab/registry",
1921
+ skillPath: "ipab/skills",
1922
+ },
1923
+ names,
1924
+ ),
1925
+ );
1926
+ const roots = await frozenPublicationClosure(context.store, root);
1927
+ record.seed = {
1928
+ root,
1929
+ roots,
1930
+ car: Buffer.from(await contentCar(context.store, roots)).toString(
1931
+ "base64",
1932
+ ),
1933
+ };
1934
+ await save();
1935
+ }
1936
+ const seedBytes = Buffer.from(record.seed.car, "base64");
1937
+ const seed = await CarBlockIterator.fromIterable(
1938
+ streamChunks(new Blob([seedBytes]).stream()),
1939
+ );
1940
+ for await (const block of seed)
1941
+ await context.store.put(block.cid, block.bytes);
1785
1942
  if (!record.scopeId) {
1786
1943
  record.scopeId = (await api.createScope(`${op}.scope`)).id;
1787
1944
  await save();
@@ -1792,12 +1949,12 @@ export async function createSwarm(
1792
1949
  context.listen,
1793
1950
  );
1794
1951
  if (!record.headId) {
1795
- const root = await publication(
1796
- context.store,
1797
- await writeSnapshot(context.store, { v: 2, names: {} }),
1798
- );
1799
1952
  record.headId = (
1800
- await api.create(record.scopeId, { root }, `${op}.head`)
1953
+ await api.create(
1954
+ record.scopeId,
1955
+ { root: record.seed.root },
1956
+ `${op}.head`,
1957
+ )
1801
1958
  ).id;
1802
1959
  await save();
1803
1960
  }
@@ -1879,7 +2036,7 @@ export async function createSwarm(
1879
2036
  const head = await api.read(record.scopeId, record.headId);
1880
2037
  await provideContent(
1881
2038
  context.store,
1882
- [headValue(head).root],
2039
+ [...new Set([headValue(head).root, ...record.seed.roots])],
1883
2040
  context.node!.api,
1884
2041
  context.fetch,
1885
2042
  context.node!.auth,
@@ -2784,6 +2941,7 @@ export async function resolveReference(
2784
2941
  async function artifactValue(
2785
2942
  store: IpfsStore,
2786
2943
  targetCid: string,
2944
+ protect?: (cid: string) => Promise<void>,
2787
2945
  ): Promise<string> {
2788
2946
  let cid = targetCid;
2789
2947
  const visited = new Set<string>();
@@ -2793,6 +2951,7 @@ async function artifactValue(
2793
2951
  "Artifact resolution exceeds limits or contains a cycle.",
2794
2952
  );
2795
2953
  visited.add(cid);
2954
+ await protect?.(cid);
2796
2955
  const bundle = await openBundle(CID.parse(cid), {
2797
2956
  resolveCid: (cid) => store.block.get(cid.toString()),
2798
2957
  });
@@ -2839,19 +2998,7 @@ export async function pinNameSubscription(
2839
2998
  ...(await currentDependencies(context.store, canonical.reference)),
2840
2999
  ];
2841
3000
  } catch (cause) {
2842
- let failure: unknown = cause;
2843
- for (
2844
- let depth = 0;
2845
- depth < 8 && failure instanceof ContentBundleError;
2846
- depth++
2847
- )
2848
- failure = failure.cause;
2849
- if (
2850
- !selected ||
2851
- !(failure instanceof ContentError) ||
2852
- failure.code !== "missing_block"
2853
- )
2854
- throw cause;
3001
+ if (!selected || !missingContent(cause)) throw cause;
2855
3002
  const swarm = withState(context, (state) => state.resolveSwarm(selected));
2856
3003
  await readyMembership(context, swarm);
2857
3004
  roots = [
@@ -2982,6 +3129,10 @@ async function currentDependencies(
2982
3129
  throw new HostError("Invalid App source association.");
2983
3130
  await currentDependencies(store, source.cid, found);
2984
3131
  }
3132
+ } else if (isSwarmStateSchema(bundle.schemaKey)) {
3133
+ const snapshot = await readState(store, CID.parse(root));
3134
+ for (const target of Object.values(snapshot.names))
3135
+ await currentDependencies(store, target.toString(), found);
2985
3136
  }
2986
3137
  return found;
2987
3138
  }
@@ -3043,52 +3194,457 @@ export async function searchNames(
3043
3194
  }
3044
3195
  return { matches, swarms: searched };
3045
3196
  }
3046
- function snapshotAssociations(snapshot: Snapshot): Association[] {
3047
- return Object.entries(snapshot.registrations ?? {})
3048
- .sort(([left], [right]) => left.localeCompare(right))
3049
- .map(([schemaCid, item]) => ({
3050
- schemaCid,
3051
- appCid: item.appCid.toString(),
3052
- argv: [...item.argv],
3053
- }));
3197
+ function assertNamesRegistry(snapshot: Snapshot): void {
3198
+ if (Object.keys(snapshot.registrations ?? {}).length)
3199
+ throw new HostError(
3200
+ "Legacy shared registrations are inactive; per-association argv is unsupported and has not been dropped or migrated. Create a new seeded Swarm and explicitly register intended Apps there. Old Swarm content and history remain readable.",
3201
+ );
3054
3202
  }
3055
- export async function swarmRegistrations(
3203
+ export async function swarmMeta(
3204
+ context: SwarmContext,
3205
+ header: Pick<SwarmHeader, "snapshot">,
3206
+ ) {
3207
+ if (header.snapshot.stateBundle) return header.snapshot.stateBundle.meta;
3208
+ const cid = header.snapshot.names.ipab;
3209
+ if (!cid)
3210
+ throw new HostError(
3211
+ 'Swarm Meta Name "ipab" is missing. Create a new seeded Swarm or explicitly publish a typed Swarm Meta Bundle; existing Swarms are never automatically upgraded.',
3212
+ );
3213
+ try {
3214
+ const bundle = await openBundle(cid, {
3215
+ resolveCid: (key) => context.store.block.get(key.toString()),
3216
+ });
3217
+ const type =
3218
+ bundle.schemaKey === legacySwarmMetaSchema.cid.toString()
3219
+ ? legacySwarmMetaType
3220
+ : swarmMetaType;
3221
+ return parseSwarmMeta(await typedJson(context.store, cid.toString(), type));
3222
+ } catch (cause) {
3223
+ throw new HostError(
3224
+ `Invalid Swarm Meta at Name "ipab": ${message(cause)}. Publish a valid typed Meta Bundle explicitly; no builtin or legacy fallback is used.`,
3225
+ );
3226
+ }
3227
+ }
3228
+ function metaCid(snapshot: Snapshot): string {
3229
+ return snapshot.stateBundle?.cid ?? snapshot.names.ipab!.toString();
3230
+ }
3231
+ function hasMeta(snapshot: Snapshot): boolean {
3232
+ return (
3233
+ snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab")
3234
+ );
3235
+ }
3236
+ export interface SharedSkill {
3237
+ name: string;
3238
+ cid: string;
3239
+ identity: string;
3240
+ }
3241
+ export async function swarmSkills(
3242
+ context: SwarmContext,
3243
+ configUrl: string,
3244
+ requested: readonly string[],
3245
+ owner: string,
3246
+ ): Promise<SharedSkill[]> {
3247
+ const warm = await localHeader(context, configUrl);
3248
+ if (warm && !warm.header.localSourceReady)
3249
+ await lazyPrivateSource(
3250
+ context,
3251
+ configUrl,
3252
+ warm.account,
3253
+ warm.header.config,
3254
+ );
3255
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
3256
+ const roots = new Set<string>();
3257
+ const protect = async (cid: string) => {
3258
+ roots.add(cid);
3259
+ const values = [...roots];
3260
+ context.store.registerOwner(owner, values);
3261
+ await context.store.retain(owner, values);
3262
+ await context.store.confirmRetained(owner, values);
3263
+ };
3264
+ for (let attempt = 0; ; attempt++) {
3265
+ if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
3266
+ header = await swarmHeader(context, configUrl, true);
3267
+ continue;
3268
+ }
3269
+ if (hasMeta(header.snapshot)) await protect(metaCid(header.snapshot));
3270
+ const meta = await swarmMeta(context, header);
3271
+ if (!meta.skillPath)
3272
+ throw new HostError(
3273
+ header.snapshot.stateBundle
3274
+ ? "This Swarm uses the earlier exact State Bundle type without skillPath. There is no in-place root-configuration migration command. Create a new seeded Swarm and explicitly republish reviewed Names. Publishing a user Name ipab never overrides root configuration; upgrades never rewrite it."
3275
+ : `This Swarm uses the legacy exact Meta type without skillPath. Explicitly build and publish a new typed Meta Bundle with templatePath and registryPath preserved and skillPath chosen, then run ipab publish ipab META_SOURCE --expect ${metaCid(header.snapshot)}. Upgrades never overwrite Meta.`,
3276
+ );
3277
+ const prefix = `${meta.skillPath}/`;
3278
+ const entries = Object.entries(header.snapshot.names).filter(([name]) =>
3279
+ name.startsWith(prefix),
3280
+ );
3281
+ for (const [, target] of entries) roots.add(target.toString());
3282
+ context.store.registerOwner(owner, [...roots]);
3283
+ const result: SharedSkill[] = [];
3284
+ const identities = new Set<string>();
3285
+ for (const [name, target] of entries.sort(([a], [b]) =>
3286
+ a.localeCompare(b),
3287
+ )) {
3288
+ if (name.slice(prefix.length).includes("/"))
3289
+ throw new HostError(
3290
+ `Skill Name "${name}" must be flat under ${meta.skillPath}.`,
3291
+ );
3292
+ const cid = await artifactValue(
3293
+ context.store,
3294
+ target.toString(),
3295
+ protect,
3296
+ );
3297
+ const bundle = await openBundle(CID.parse(cid), {
3298
+ resolveCid: (key) => context.store.block.get(key.toString()),
3299
+ });
3300
+ if (bundle.schemaKey !== skillSchema.cid.toString())
3301
+ throw new HostError(
3302
+ `Name "${name}" is not an exact Skill type Bundle.`,
3303
+ );
3304
+ const identity = await skillIdentity(bundle);
3305
+ if (identities.has(identity))
3306
+ throw new HostError(
3307
+ `Duplicate Skill installation name "${identity}" in this Swarm.`,
3308
+ );
3309
+ identities.add(identity);
3310
+ result.push({ name, cid, identity });
3311
+ }
3312
+ const missing = requested.filter(
3313
+ (reference) =>
3314
+ !result.some(
3315
+ (skill) => skill.name === reference || skill.identity === reference,
3316
+ ),
3317
+ );
3318
+ if (missing.length && !attempt && header.source === "cache") {
3319
+ header = await swarmHeader(context, configUrl, true);
3320
+ continue;
3321
+ }
3322
+ if (missing.length)
3323
+ throw new HostError(
3324
+ `Skill identities or shared Names not found under ${meta.skillPath}: ${missing.join(", ")}.`,
3325
+ );
3326
+ return result;
3327
+ }
3328
+ }
3329
+ export async function resolveTemplateSelector(
3330
+ context: SwarmContext,
3331
+ selector: string,
3332
+ configUrl: string,
3333
+ ): Promise<string> {
3334
+ formalName(selector);
3335
+ const warm = await localHeader(context, configUrl);
3336
+ if (warm && !warm.header.localSourceReady)
3337
+ await lazyPrivateSource(
3338
+ context,
3339
+ configUrl,
3340
+ warm.account,
3341
+ warm.header.config,
3342
+ );
3343
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
3344
+ if (!hasMeta(header.snapshot) && header.source === "cache")
3345
+ header = await swarmHeader(context, configUrl, true);
3346
+ for (let attempt = 0; ; attempt++) {
3347
+ const meta = await swarmMeta(context, header);
3348
+ const name = formalName(`${meta.templatePath}/${selector}`);
3349
+ const target = header.snapshot.names[name];
3350
+ if (target) return artifactValue(context.store, target.toString());
3351
+ if (attempt || header.source !== "cache")
3352
+ throw new HostError(
3353
+ `Template Name "${name}" was not found after refreshing HEAD.`,
3354
+ );
3355
+ header = await swarmHeader(context, configUrl, true);
3356
+ }
3357
+ }
3358
+ export function templateName(name: string): string {
3359
+ if (name.includes(":"))
3360
+ throw new HostError(
3361
+ "Template NAME must be a safe relative Name, not a URI.",
3362
+ );
3363
+ return formalName(name);
3364
+ }
3365
+ async function templateEntry(
3366
+ context: SwarmContext,
3367
+ configUrl: string,
3368
+ header: Pick<SwarmHeader, "snapshot">,
3369
+ selector: string,
3370
+ ) {
3371
+ const meta = await swarmMeta(context, header);
3372
+ const name = formalName(`${meta.templatePath}/${templateName(selector)}`);
3373
+ const target = header.snapshot.names[name];
3374
+ if (!target)
3375
+ throw new HostError(
3376
+ `Template Name "${name}" was not found after refreshing HEAD.`,
3377
+ );
3378
+ const targetCid = target.toString();
3379
+ return {
3380
+ swarm: configUrl,
3381
+ templatePath: meta.templatePath,
3382
+ metaCid: metaCid(header.snapshot),
3383
+ name,
3384
+ selector,
3385
+ reference: formatNameReference(configUrl, name),
3386
+ targetCid,
3387
+ ...(await inspectTemplate(
3388
+ context.store,
3389
+ await artifactValue(context.store, targetCid),
3390
+ )),
3391
+ };
3392
+ }
3393
+ export async function swarmTemplates(
3056
3394
  context: SwarmContext,
3057
3395
  configUrl: string,
3396
+ selector?: string,
3397
+ ) {
3398
+ if (selector !== undefined) templateName(selector);
3399
+ const warm = await localHeader(context, configUrl);
3400
+ if (warm && !warm.header.localSourceReady)
3401
+ await lazyPrivateSource(
3402
+ context,
3403
+ configUrl,
3404
+ warm.account,
3405
+ warm.header.config,
3406
+ );
3407
+ let header =
3408
+ warm?.header ??
3409
+ (await swarmHeader(context, configUrl, undefined, "local-first"));
3410
+ for (let attempt = 0; ; attempt++) {
3411
+ if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
3412
+ header = await swarmHeader(context, configUrl, true, "local-first");
3413
+ continue;
3414
+ }
3415
+ const meta = await swarmMeta(context, header);
3416
+ const name =
3417
+ selector === undefined
3418
+ ? undefined
3419
+ : formalName(`${meta.templatePath}/${selector}`);
3420
+ if (
3421
+ name &&
3422
+ !header.snapshot.names[name] &&
3423
+ header.source === "cache" &&
3424
+ !attempt
3425
+ ) {
3426
+ header = await swarmHeader(context, configUrl, true, "local-first");
3427
+ continue;
3428
+ }
3429
+ const selectors =
3430
+ selector === undefined
3431
+ ? Object.keys(header.snapshot.names)
3432
+ .filter((key) => key.startsWith(`${meta.templatePath}/`))
3433
+ .map((key) => key.slice(meta.templatePath.length + 1))
3434
+ .sort((a, b) => a.localeCompare(b))
3435
+ : [selector];
3436
+ const items = [];
3437
+ for (const item of selectors)
3438
+ items.push(await templateEntry(context, configUrl, header, item));
3439
+ return items;
3440
+ }
3441
+ }
3442
+ export async function setSwarmTemplate(
3443
+ context: SwarmContext,
3444
+ configUrl: string,
3445
+ selector: string,
3446
+ source: string,
3447
+ expect?: string,
3448
+ ) {
3449
+ templateName(selector);
3450
+ await pointer(context, configUrl);
3451
+ const content = await templatePublicationSource(source, context.store);
3452
+ const details = await inspectTemplate(context.store, content);
3453
+ let location:
3454
+ { name: string; templatePath: string; metaCid: string } | undefined;
3455
+ const targetCid = await publishContent(
3456
+ context,
3457
+ content,
3458
+ {
3459
+ swarm: configUrl,
3460
+ name: selector,
3461
+ ...(expect === undefined ? {} : { expect }),
3462
+ },
3463
+ async (current) => {
3464
+ const meta = await swarmMeta(context, { snapshot: current });
3465
+ const name = formalName(`${meta.templatePath}/${selector}`);
3466
+ location = {
3467
+ name,
3468
+ templatePath: meta.templatePath,
3469
+ metaCid: metaCid(current),
3470
+ };
3471
+ return name;
3472
+ },
3473
+ );
3474
+ return {
3475
+ swarm: configUrl,
3476
+ ...location!,
3477
+ selector,
3478
+ reference: formatNameReference(configUrl, location!.name),
3479
+ targetCid,
3480
+ ...details,
3481
+ };
3482
+ }
3483
+ export async function removeSwarmTemplate(
3484
+ context: SwarmContext,
3485
+ configUrl: string,
3486
+ selector: string,
3487
+ expect: string,
3488
+ ) {
3489
+ templateName(selector);
3490
+ const expected = exactCid(expect);
3491
+ const head = await pointer(context, configUrl);
3492
+ let basis: string | undefined;
3493
+ for (let attempt = 0; attempt < 8; attempt++) {
3494
+ const currentHead = await head.read();
3495
+ const current = await readSnapshot(context.store, currentHead.root);
3496
+ const meta = await swarmMeta(context, { snapshot: current });
3497
+ const name = formalName(`${meta.templatePath}/${selector}`);
3498
+ if (basis !== undefined && basis !== name)
3499
+ throw new HostError(
3500
+ "Template Meta path changed during removal; inspect and retry.",
3501
+ 3,
3502
+ "EDIT_CONFLICT",
3503
+ "publication",
3504
+ );
3505
+ basis = name;
3506
+ const old = current.names[name]?.toString();
3507
+ if (!old)
3508
+ throw new HostError(
3509
+ `Template Name "${name}" is missing; nothing was removed.`,
3510
+ );
3511
+ if (old !== expected)
3512
+ throw new HostError(
3513
+ `Edit conflict for ${name}; --expect must match the exact old Name target CID.`,
3514
+ 3,
3515
+ "EDIT_CONFLICT",
3516
+ "publication",
3517
+ );
3518
+ const names = { ...current.names };
3519
+ delete names[name];
3520
+ const next = await prepareNamesPublication(
3521
+ context,
3522
+ configUrl,
3523
+ currentHead.root,
3524
+ current,
3525
+ names,
3526
+ [],
3527
+ );
3528
+ try {
3529
+ await head.write(next, currentHead.cid, uniqueId());
3530
+ } catch (cause) {
3531
+ if (cause instanceof ScopeApiError && cause.status === 412) continue;
3532
+ throw new HostError(
3533
+ `Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`,
3534
+ 1,
3535
+ "HEAD_UNCONFIRMED",
3536
+ "publication",
3537
+ );
3538
+ }
3539
+ try {
3540
+ await swarmHeader(context, configUrl, true);
3541
+ } catch (cause) {
3542
+ throw new HostError(
3543
+ `Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`,
3544
+ 1,
3545
+ "PIN_STALE",
3546
+ "publication",
3547
+ );
3548
+ }
3549
+ return {
3550
+ swarm: configUrl,
3551
+ templatePath: meta.templatePath,
3552
+ metaCid: metaCid(current),
3553
+ selector,
3554
+ name,
3555
+ reference: formatNameReference(configUrl, name),
3556
+ targetCid: old,
3557
+ };
3558
+ }
3559
+ throw new HostError("HEAD is busy; retry the template removal.");
3560
+ }
3561
+ async function registryAssociations(
3562
+ context: SwarmContext,
3563
+ header: SwarmHeader,
3058
3564
  ): Promise<Association[]> {
3059
- const header = await swarmHeader(context, configUrl);
3060
- return withState(context, (state) =>
3061
- state.projectedSwarmRegistrations(headerProjection(header)),
3565
+ assertNamesRegistry(header.snapshot);
3566
+ const meta = await swarmMeta(context, header);
3567
+ const prefix = `${meta.registryPath}/`;
3568
+ const result: Association[] = [];
3569
+ for (const [name, cid] of Object.entries(header.snapshot.names)) {
3570
+ if (!name.startsWith(prefix)) continue;
3571
+ const schemaCid = name.slice(prefix.length);
3572
+ if (exactCid(schemaCid, true) !== schemaCid)
3573
+ throw new HostError(
3574
+ `Registry Name "${name}" must end in an exact canonical type CID.`,
3575
+ );
3576
+ result.push(createAssociation(schemaCid, cid.toString(), ["%"]));
3577
+ }
3578
+ return result.sort((left, right) =>
3579
+ left.schemaCid.localeCompare(right.schemaCid),
3062
3580
  );
3063
3581
  }
3582
+ export async function swarmRegistrations(
3583
+ context: SwarmContext,
3584
+ configUrl: string,
3585
+ ): Promise<Association[]> {
3586
+ let header = await swarmHeader(context, configUrl);
3587
+ if (!hasMeta(header.snapshot) && header.source === "cache")
3588
+ header = await swarmHeader(context, configUrl, true);
3589
+ return registryAssociations(context, header);
3590
+ }
3064
3591
  export async function swarmAssociation(
3065
3592
  context: SwarmContext,
3066
3593
  configUrl: string,
3067
3594
  schemaCid: string,
3068
3595
  mode: "active" | "local-first" = "active",
3069
3596
  ): Promise<Association | undefined> {
3070
- let header =
3071
- (mode === "local-first"
3072
- ? (await localHeader(context, configUrl))?.header
3073
- : undefined) ?? (await swarmHeader(context, configUrl));
3074
- let association = withState(
3075
- context,
3076
- (state) =>
3077
- state.projectedSwarmRegistrations(headerProjection(header), schemaCid)[0],
3597
+ const warm =
3598
+ mode === "local-first" ? await localHeader(context, configUrl) : undefined;
3599
+ if (warm && !warm.header.localSourceReady)
3600
+ await lazyPrivateSource(
3601
+ context,
3602
+ configUrl,
3603
+ warm.account,
3604
+ warm.header.config,
3605
+ );
3606
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
3607
+ if (!hasMeta(header.snapshot) && header.source === "cache")
3608
+ header = await swarmHeader(context, configUrl, true);
3609
+ let association = (await registryAssociations(context, header)).find(
3610
+ (item) => item.schemaCid === schemaCid,
3078
3611
  );
3079
3612
  if (!association && header.source === "cache") {
3080
3613
  header = await swarmHeader(context, configUrl, true);
3081
- association = withState(
3082
- context,
3083
- (state) =>
3084
- state.projectedSwarmRegistrations(
3085
- headerProjection(header),
3086
- schemaCid,
3087
- )[0],
3614
+ association = (await registryAssociations(context, header)).find(
3615
+ (item) => item.schemaCid === schemaCid,
3088
3616
  );
3089
3617
  }
3090
3618
  return association;
3091
3619
  }
3620
+ async function prepareNamesPublication(
3621
+ context: SwarmContext,
3622
+ configUrl: string,
3623
+ previousRoot: string,
3624
+ current: Snapshot,
3625
+ names: Record<string, CID>,
3626
+ roots: Iterable<string>,
3627
+ retainedRoots?: Iterable<string>,
3628
+ ) {
3629
+ const next = await publication(
3630
+ context.store,
3631
+ await writeSnapshot(context.store, { ...current, names }),
3632
+ previousRoot,
3633
+ );
3634
+ const closure = await publicationClosure(context.store, next, false);
3635
+ await provideContent(
3636
+ context.store,
3637
+ [...new Set([...closure.provided, ...roots])],
3638
+ context.node!.api,
3639
+ context.fetch,
3640
+ context.node!.auth,
3641
+ [...new Set([next, ...closure.nameTargets, ...(retainedRoots ?? roots)])],
3642
+ );
3643
+ withState(context, (state) => {
3644
+ state.invalidateSwarmHeader(configUrl);
3645
+ });
3646
+ return next;
3647
+ }
3092
3648
  async function editSwarmAssociation(
3093
3649
  context: SwarmContext,
3094
3650
  configUrl: string,
@@ -3097,53 +3653,45 @@ async function editSwarmAssociation(
3097
3653
  replace: boolean,
3098
3654
  ): Promise<void> {
3099
3655
  const head = await pointer(context, configUrl);
3656
+ if (association) {
3657
+ const app = await openBundle(CID.parse(association.appCid), {
3658
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
3659
+ });
3660
+ if (app.schemaKey !== appSchemaCid.toString())
3661
+ throw new HostError(
3662
+ "Registry Names must directly reference an App Bundle CID, not an Artifact or another content type.",
3663
+ );
3664
+ }
3100
3665
  const roots = association
3101
3666
  ? await dependencies(context.store, association.appCid)
3102
3667
  : new Set<string>();
3103
3668
  for (let attempt = 0; attempt < 8; attempt++) {
3104
3669
  const currentHead = await head.read();
3105
3670
  const current = await readSnapshot(context.store, currentHead.root);
3106
- const old = snapshotAssociations(current).find(
3107
- (item) => item.schemaCid === schemaCid,
3108
- );
3671
+ assertNamesRegistry(current);
3672
+ const meta = await swarmMeta(context, { snapshot: current });
3673
+ const name = formalName(`${meta.registryPath}/${schemaCid}`);
3674
+ const oldCid = current.names[name]?.toString();
3109
3675
  if (association) {
3110
- if (
3111
- old &&
3112
- old.appCid === association.appCid &&
3113
- JSON.stringify(old.argv) === JSON.stringify(association.argv)
3114
- )
3115
- return;
3116
- if (old && !replace)
3117
- throw new HostError(
3118
- "Schema has another association; use --replace before --.",
3119
- );
3120
- } else if (!old) {
3676
+ if (oldCid === association.appCid) return;
3677
+ if (oldCid && !replace)
3678
+ throw new HostError("Schema has another association; use --replace.");
3679
+ } else if (!oldCid) {
3121
3680
  throw new HostError(
3122
3681
  "No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.",
3123
3682
  );
3124
3683
  }
3125
- const registrations = { ...current.registrations };
3126
- if (association)
3127
- registrations[schemaCid] = {
3128
- appCid: CID.parse(association.appCid),
3129
- argv: association.argv,
3130
- };
3131
- else delete registrations[schemaCid];
3132
- const next = await publication(
3133
- context.store,
3134
- await writeSnapshot(context.store, { ...current, registrations }),
3684
+ const names = { ...current.names };
3685
+ if (association) names[name] = CID.parse(association.appCid);
3686
+ else delete names[name];
3687
+ const next = await prepareNamesPublication(
3688
+ context,
3689
+ configUrl,
3135
3690
  currentHead.root,
3691
+ current,
3692
+ names,
3693
+ roots,
3136
3694
  );
3137
- await provideContent(
3138
- context.store,
3139
- [next, ...roots],
3140
- context.node!.api,
3141
- context.fetch,
3142
- context.node!.auth,
3143
- );
3144
- withState(context, (state) => {
3145
- state.invalidateSwarmHeader(configUrl);
3146
- });
3147
3695
  try {
3148
3696
  await head.write(next, currentHead.cid, uniqueId());
3149
3697
  return;
@@ -3168,6 +3716,10 @@ export async function setSwarmAssociation(
3168
3716
  value: Association,
3169
3717
  replace = false,
3170
3718
  ): Promise<Association> {
3719
+ if (value.argv.length !== 1 || value.argv[0] !== "%")
3720
+ throw new HostError(
3721
+ 'Custom per-association argv is unsupported. Apps opened through the registry receive only the content CID (whole "%" argument); adapt the App or use ipab exec APP_CID ARGS.',
3722
+ );
3171
3723
  const association = createAssociation(
3172
3724
  value.schemaCid,
3173
3725
  value.appCid,
@@ -3222,6 +3774,10 @@ async function dependencies(
3222
3774
  throw new HostError("Invalid App source association.");
3223
3775
  await dependencies(store, source.cid, found);
3224
3776
  }
3777
+ } else if (isSwarmStateSchema(bundle.schemaKey)) {
3778
+ const snapshot = await readState(store, CID.parse(root));
3779
+ for (const target of Object.values(snapshot.names))
3780
+ await dependencies(store, target.toString(), found);
3225
3781
  }
3226
3782
  return found;
3227
3783
  }
@@ -3229,8 +3785,16 @@ export async function frozenPublicationClosure(
3229
3785
  store: IpfsStore,
3230
3786
  root: string,
3231
3787
  ): Promise<string[]> {
3788
+ return (await publicationClosure(store, root)).provided;
3789
+ }
3790
+ async function publicationClosure(
3791
+ store: IpfsStore,
3792
+ root: string,
3793
+ includeDependencies = true,
3794
+ ) {
3232
3795
  const publications = new Set<string>(),
3233
- content = new Set<string>();
3796
+ content = new Set<string>(),
3797
+ nameTargets = new Set<string>();
3234
3798
  let current: string | undefined = root;
3235
3799
  while (current !== undefined) {
3236
3800
  if (publications.has(current) || publications.size >= 256)
@@ -3240,18 +3804,26 @@ export async function frozenPublicationClosure(
3240
3804
  publications.add(current);
3241
3805
  const publication = await readPublication(store, current);
3242
3806
  const snapshot = await readState(store, publication.state);
3243
- for (const target of Object.values(snapshot.names))
3244
- await dependencies(store, target.toString(), content);
3245
- for (const association of Object.values(snapshot.registrations ?? {}))
3246
- await dependencies(store, association.appCid.toString(), content);
3807
+ for (const target of Object.values(snapshot.names)) {
3808
+ nameTargets.add(target.toString());
3809
+ if (includeDependencies)
3810
+ await dependencies(store, target.toString(), content);
3811
+ else content.add(target.toString());
3812
+ }
3813
+ if (includeDependencies)
3814
+ for (const association of Object.values(snapshot.registrations ?? {}))
3815
+ await dependencies(store, association.appCid.toString(), content);
3247
3816
  current = publication.previous?.toString();
3248
3817
  }
3249
- return [
3250
- root,
3251
- ...[...new Set([...publications, ...content])]
3252
- .filter((cid) => cid !== root)
3253
- .sort(),
3254
- ];
3818
+ return {
3819
+ nameTargets,
3820
+ provided: [
3821
+ root,
3822
+ ...[...new Set([...publications, ...content])]
3823
+ .filter((cid) => cid !== root)
3824
+ .sort(),
3825
+ ],
3826
+ };
3255
3827
  }
3256
3828
  export async function publish(
3257
3829
  context: SwarmContext,
@@ -3262,6 +3834,19 @@ export async function publish(
3262
3834
  expect?: string;
3263
3835
  snapshot?: boolean;
3264
3836
  },
3837
+ ): Promise<string> {
3838
+ return publishContent(context, content, options);
3839
+ }
3840
+ async function publishContent(
3841
+ context: SwarmContext,
3842
+ content: string,
3843
+ options: {
3844
+ swarm?: string;
3845
+ name: string;
3846
+ expect?: string;
3847
+ snapshot?: boolean;
3848
+ },
3849
+ nameForSnapshot?: (current: Snapshot) => Promise<string>,
3265
3850
  ): Promise<string> {
3266
3851
  if (!options.swarm)
3267
3852
  throw new HostError(
@@ -3273,21 +3858,28 @@ export async function publish(
3273
3858
  await withStateAsync(context, (state) =>
3274
3859
  pinCid(state, content, context.store, currentRoots),
3275
3860
  );
3276
- const name = formalName(options.name);
3861
+ let name = formalName(options.name);
3862
+ let resolvedName: string | undefined;
3277
3863
  if (options.snapshot && options.expect)
3278
3864
  throw new HostError("Snapshots cannot replace an occupied Name.");
3279
3865
  const expected = options.expect
3280
3866
  ? CID.parse(options.expect).toV1().toString()
3281
3867
  : undefined;
3282
- if (expected)
3283
- parseArtifact(await typedJson(context.store, expected, artifactType));
3284
- const candidate = options.snapshot
3285
- ? content
3286
- : await jsonBundle(context.store, artifactType, {
3287
- value: content,
3288
- ...(expected ? { previous: expected } : {}),
3289
- timestamp: new Date().toISOString(),
3290
- });
3868
+ const contentBundle = await openBundle(CID.parse(content), {
3869
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
3870
+ });
3871
+ const direct =
3872
+ contentBundle.schemaKey === appSchemaCid.toString() ||
3873
+ contentBundle.schemaKey === swarmMetaSchema.cid.toString() ||
3874
+ contentBundle.schemaKey === legacySwarmMetaSchema.cid.toString();
3875
+ const candidate =
3876
+ options.snapshot || direct
3877
+ ? content
3878
+ : await jsonBundle(context.store, artifactType, {
3879
+ value: content,
3880
+ ...(expected ? { previous: expected } : {}),
3881
+ timestamp: new Date().toISOString(),
3882
+ });
3291
3883
  roots.add(candidate);
3292
3884
  if (expected)
3293
3885
  for (const root of await dependencies(context.store, expected))
@@ -3295,36 +3887,37 @@ export async function publish(
3295
3887
  for (let attempt = 0; attempt < 8; attempt++) {
3296
3888
  const currentHead = await head.read(),
3297
3889
  current = await readSnapshot(context.store, currentHead.root);
3890
+ if (nameForSnapshot) {
3891
+ name = await nameForSnapshot(current);
3892
+ if (resolvedName !== undefined && resolvedName !== name)
3893
+ throw new HostError(
3894
+ "Template Meta path changed during publication; inspect and retry. Content remains pinned.",
3895
+ 3,
3896
+ "EDIT_CONFLICT",
3897
+ "publication",
3898
+ );
3899
+ resolvedName = name;
3900
+ }
3298
3901
  if (
3299
3902
  (Object.hasOwn(current.names, name)
3300
3903
  ? current.names[name]?.toString()
3301
3904
  : undefined) !== expected
3302
3905
  )
3303
3906
  throw new HostError(
3304
- `Edit conflict for ${name}; content ${content} remains pinned. Occupied Names require --expect EXACT_OLD_ARTIFACT_CID; inspect the current Name before retrying.`,
3907
+ `Edit conflict for ${name}; content ${content} remains pinned. Occupied Names require --expect EXACT_OLD_CID (the old Artifact CID when applicable); inspect the current Name before retrying.`,
3305
3908
  3,
3306
3909
  "EDIT_CONFLICT",
3307
3910
  "publication",
3308
3911
  );
3309
- const next = await publication(
3310
- context.store,
3311
- await writeSnapshot(context.store, {
3312
- ...current,
3313
- names: { ...current.names, [name]: CID.parse(candidate) },
3314
- }),
3912
+ const next = await prepareNamesPublication(
3913
+ context,
3914
+ options.swarm,
3315
3915
  currentHead.root,
3916
+ current,
3917
+ { ...current.names, [name]: CID.parse(candidate) },
3918
+ roots,
3919
+ expected ? await dependencies(context.store, expected) : [],
3316
3920
  );
3317
- await provideContent(
3318
- context.store,
3319
- [next, ...roots],
3320
- context.node!.api,
3321
- context.fetch,
3322
- context.node!.auth,
3323
- [next, ...(expected ? await dependencies(context.store, expected) : [])],
3324
- );
3325
- withState(context, (state) => {
3326
- state.invalidateSwarmHeader(options.swarm!);
3327
- });
3328
3921
  try {
3329
3922
  await head.write(next, currentHead.cid, uniqueId());
3330
3923
  } catch (cause) {