@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/dist/swarm.js CHANGED
@@ -18,7 +18,7 @@ import { HostError, object, message } from "./errors.js";
18
18
  import { accountIdentity, protectedPath, secureNew, } from "./identity.js";
19
19
  import { nodeError } from "./authoring.js";
20
20
  import { swarmUrl as canonicalSwarmUrl } from "./config.js";
21
- import { bundleJson, provideContent } from "./content-provider.js";
21
+ import { bundleJson, contentCar, provideContent } from "./content-provider.js";
22
22
  import { failedPin, pinCid, refreshPinClaim, reservePin, retainPin, } from "./pins.js";
23
23
  import { bytes, relativePath } from "./space.js";
24
24
  import { appSchemaCid } from "./app-definition.js";
@@ -27,6 +27,11 @@ import { privateDirectory, readPrivate, withPrivateLock, writePrivate, } from ".
27
27
  import { encryptionIdentity, openApproval, sealApproval, parseEnvelope, validateEncryptionIdentity, } from "./swarm-envelope.js";
28
28
  import { checkCachedNode, kuboSource, peerId, peerProof, prepareNode, startNode, validateAddress, } from "./kubo.js";
29
29
  import { memberPeers } from "./kubo-peering.js";
30
+ import { seedTemplateNames, seedTemplateSource } from "./template-source.js";
31
+ import { inspectTemplate, templatePublicationSource } from "./templates.js";
32
+ import { seedSkillSource } from "./skill-source.js";
33
+ import { skillIdentity, skillSchema } from "./skill-definition.js";
34
+ import { parseSwarmMeta, swarmMetaType, swarmMetaSchema, swarmStateType, legacySwarmStateType, legacySwarmStateSchema, isSwarmStateSchema, legacySwarmMetaType, legacySwarmMetaSchema, } from "./swarm-meta.js";
30
35
  async function contextIdentity(context, initialize = false) {
31
36
  context.identity ??= await accountIdentity(context.env, initialize);
32
37
  return context.identity;
@@ -757,7 +762,20 @@ export async function jsonBundle(store, type, value) {
757
762
  await encoded.close();
758
763
  }
759
764
  }
765
+ async function writeStateBundle(store, configuration, targets) {
766
+ const meta = parseSwarmMeta(configuration);
767
+ const names = Object.fromEntries(Object.entries(targets).map(([name, cid]) => [
768
+ formalName(name),
769
+ cid.toString(),
770
+ ]));
771
+ return jsonBundle(store, meta.skillPath === undefined ? legacySwarmStateType : swarmStateType, { v: 5, ...meta, names });
772
+ }
760
773
  export async function writeSnapshot(store, snapshot) {
774
+ if (snapshot.stateBundle) {
775
+ if (Object.keys(snapshot.registrations ?? {}).length)
776
+ throw new HostError("State Bundles cannot contain legacy registrations.");
777
+ return writeStateBundle(store, snapshot.stateBundle.meta, snapshot.names);
778
+ }
761
779
  const put = async (value) => {
762
780
  const encoded = dagCbor.encode(value);
763
781
  const cid = CID.createV1(dagCbor.code, await sha256.digest(encoded));
@@ -765,12 +783,51 @@ export async function writeSnapshot(store, snapshot) {
765
783
  return cid;
766
784
  };
767
785
  const names = await put(snapshot.names);
768
- const registrations = await put(snapshot.registrations ?? {});
769
- return (await put({ v: 3, names, registrations })).toString();
786
+ if (Object.keys(snapshot.registrations ?? {}).length) {
787
+ const registrations = await put(snapshot.registrations);
788
+ return (await put({ v: 3, names, registrations })).toString();
789
+ }
790
+ return (await put({ v: 4, names })).toString();
770
791
  }
771
792
  async function readState(store, cid) {
793
+ if (cid.code !== dagCbor.code) {
794
+ const bundle = await openBundle(cid, {
795
+ resolveCid: (key) => store.block.get(key.toString()),
796
+ });
797
+ const type = bundle.schemaKey === legacySwarmStateSchema.cid.toString()
798
+ ? legacySwarmStateType
799
+ : swarmStateType;
800
+ const value = object(await typedJson(store, cid.toString(), type), "State Bundle");
801
+ if (value.v !== 5 ||
802
+ Object.keys(value).sort().join() !==
803
+ (type === legacySwarmStateType
804
+ ? "names,registryPath,templatePath,v"
805
+ : "names,registryPath,skillPath,templatePath,v"))
806
+ throw new HostError("Invalid State Bundle entry.");
807
+ const meta = parseSwarmMeta({
808
+ templatePath: value.templatePath,
809
+ registryPath: value.registryPath,
810
+ ...(type === legacySwarmStateType ? {} : { skillPath: value.skillPath }),
811
+ });
812
+ const names = Object.fromEntries(Object.entries(object(value.names, "Names")).map(([name, target]) => {
813
+ formalName(name);
814
+ if (typeof target !== "string" || exactCid(target) !== target)
815
+ throw new HostError("State Names require exact canonical CIDs.");
816
+ return [name, CID.parse(target)];
817
+ }));
818
+ return { v: 2, names, stateBundle: { meta, cid: cid.toString() } };
819
+ }
772
820
  const data = await store.block.get(cid.toString());
773
821
  const root = object(dagCbor.decode(data), "State");
822
+ if (root.v === 4) {
823
+ const names = CID.asCID(root.names);
824
+ if (!names || Object.keys(root).sort().join() !== "names,v")
825
+ throw new HostError("Invalid State Names root.");
826
+ return decodeSnapshot(dagCbor.encode({
827
+ v: 2,
828
+ names: dagCbor.decode(await store.block.get(names.toString())),
829
+ }));
830
+ }
774
831
  if (root.v !== 3)
775
832
  return decodeSnapshot(data);
776
833
  const names = CID.asCID(root.names), registrations = CID.asCID(root.registrations);
@@ -859,6 +916,12 @@ async function publication(store, state, previous) {
859
916
  await store.put(cid, data);
860
917
  return cid.toString();
861
918
  }
919
+ function missingContent(cause) {
920
+ let failure = cause;
921
+ for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
922
+ failure = failure.cause;
923
+ return failure instanceof ContentError && failure.code === "missing_block";
924
+ }
862
925
  export async function sharedSwarmStatus(context, configUrl) {
863
926
  const { config } = await fetchConfig(context, configUrl);
864
927
  const c = coordinates(configUrl);
@@ -868,7 +931,7 @@ export async function sharedSwarmStatus(context, configUrl) {
868
931
  content = await readHeaderSnapshot(context.store, head.root);
869
932
  }
870
933
  catch (cause) {
871
- if (!(cause instanceof ContentError) || cause.code !== "missing_block")
934
+ if (!missingContent(cause))
872
935
  throw cause;
873
936
  const registered = withState(context, (state) => state.swarms().some((entry) => entry.cid === configUrl));
874
937
  if (!registered)
@@ -974,7 +1037,18 @@ async function cachedHeader(context, record) {
974
1037
  (cached.epoch !== undefined && cached.epoch !== config.epoch) ||
975
1038
  !(age >= 0 && age < (context.cacheTtl ?? 300) * 1000))
976
1039
  return;
977
- const snapshot = decodeSnapshot(Buffer.from(cached.snapshot, "base64"));
1040
+ const cachedSnapshot = object(dagCbor.decode(Buffer.from(cached.snapshot, "base64")), "cached State");
1041
+ const { stateBundle, ...legacySnapshot } = cachedSnapshot;
1042
+ const snapshot = decodeSnapshot(dagCbor.encode(legacySnapshot));
1043
+ if (stateBundle !== undefined) {
1044
+ const data = object(stateBundle, "cached State Bundle");
1045
+ if (Object.keys(data).sort().join() !== "cid,meta" ||
1046
+ typeof data.cid !== "string" ||
1047
+ exactCid(data.cid) !== data.cid ||
1048
+ (cached.stateCid !== undefined && data.cid !== cached.stateCid))
1049
+ throw new HostError("Invalid cached State Bundle.");
1050
+ snapshot.stateBundle = { meta: parseSwarmMeta(data.meta), cid: data.cid };
1051
+ }
978
1052
  let stateCid = cached.stateCid;
979
1053
  if (!stateCid) {
980
1054
  try {
@@ -1011,7 +1085,7 @@ function projectHeader(context, record, header) {
1011
1085
  membership: JSON.stringify({ owner: record.owner, member }),
1012
1086
  };
1013
1087
  withState(context, (state) => {
1014
- state.projectSwarm(binding, header.snapshot.names, () => snapshotAssociations(header.snapshot));
1088
+ state.projectSwarm(binding, header.snapshot.names, () => []);
1015
1089
  });
1016
1090
  header.projection = binding;
1017
1091
  }
@@ -1147,14 +1221,44 @@ export async function createSwarm(context, options = {}) {
1147
1221
  const save = () => writePrivate(dir, `creation-${op}.json`, record);
1148
1222
  const api = client(context, service, identity);
1149
1223
  try {
1224
+ if (!record.seed) {
1225
+ if (record.headId)
1226
+ throw new HostError("Legacy creation has an unseeded HEAD. Preserve this recovery record and explicitly migrate the Swarm; it cannot complete as a newly seeded Swarm.");
1227
+ const names = {};
1228
+ for (const selector of seedTemplateNames) {
1229
+ const template = await seedTemplateSource(selector);
1230
+ for (const [cid, data] of template.blocks)
1231
+ await context.store.put(CID.parse(cid), data);
1232
+ names[`ipab/template/${selector}`] = CID.parse(template.cid);
1233
+ }
1234
+ const skill = await seedSkillSource();
1235
+ for (const [cid, data] of skill.blocks)
1236
+ await context.store.put(CID.parse(cid), data);
1237
+ names["ipab/skills/ipab"] = CID.parse(skill.cid);
1238
+ const root = await publication(context.store, await writeStateBundle(context.store, {
1239
+ templatePath: "ipab/template",
1240
+ registryPath: "ipab/registry",
1241
+ skillPath: "ipab/skills",
1242
+ }, names));
1243
+ const roots = await frozenPublicationClosure(context.store, root);
1244
+ record.seed = {
1245
+ root,
1246
+ roots,
1247
+ car: Buffer.from(await contentCar(context.store, roots)).toString("base64"),
1248
+ };
1249
+ await save();
1250
+ }
1251
+ const seedBytes = Buffer.from(record.seed.car, "base64");
1252
+ const seed = await CarBlockIterator.fromIterable(streamChunks(new Blob([seedBytes]).stream()));
1253
+ for await (const block of seed)
1254
+ await context.store.put(block.cid, block.bytes);
1150
1255
  if (!record.scopeId) {
1151
1256
  record.scopeId = (await api.createScope(`${op}.scope`)).id;
1152
1257
  await save();
1153
1258
  }
1154
1259
  const node = await prepareNode(context.stateDir, nodeScope(service, record.scopeId), context.listen);
1155
1260
  if (!record.headId) {
1156
- const root = await publication(context.store, await writeSnapshot(context.store, { v: 2, names: {} }));
1157
- record.headId = (await api.create(record.scopeId, { root }, `${op}.head`)).id;
1261
+ record.headId = (await api.create(record.scopeId, { root: record.seed.root }, `${op}.head`)).id;
1158
1262
  await save();
1159
1263
  }
1160
1264
  if (!record.profileId) {
@@ -1217,7 +1321,7 @@ export async function createSwarm(context, options = {}) {
1217
1321
  await saveLocal(context, membership);
1218
1322
  await activate(context, membership);
1219
1323
  const head = await api.read(record.scopeId, record.headId);
1220
- await provideContent(context.store, [headValue(head).root], context.node.api, context.fetch, context.node.auth);
1324
+ await provideContent(context.store, [...new Set([headValue(head).root, ...record.seed.roots])], context.node.api, context.fetch, context.node.auth);
1221
1325
  withState(context, (state) => state.registerSwarm(configUrl, options.alias));
1222
1326
  return configUrl;
1223
1327
  }
@@ -1787,13 +1891,14 @@ export async function resolveReference(context, reference, swarm, local, raw = f
1787
1891
  const cid = raw ? targetCid : await artifactValue(context.store, targetCid);
1788
1892
  return { targetCid, cid };
1789
1893
  }
1790
- async function artifactValue(store, targetCid) {
1894
+ async function artifactValue(store, targetCid, protect) {
1791
1895
  let cid = targetCid;
1792
1896
  const visited = new Set();
1793
1897
  for (let depth = 0;; depth++) {
1794
1898
  if (depth >= 64 || visited.has(cid))
1795
1899
  throw new HostError("Artifact resolution exceeds limits or contains a cycle.");
1796
1900
  visited.add(cid);
1901
+ await protect?.(cid);
1797
1902
  const bundle = await openBundle(CID.parse(cid), {
1798
1903
  resolveCid: (cid) => store.block.get(cid.toString()),
1799
1904
  });
@@ -1828,12 +1933,7 @@ export async function pinNameSubscription(context, reference, selected) {
1828
1933
  ];
1829
1934
  }
1830
1935
  catch (cause) {
1831
- let failure = cause;
1832
- for (let depth = 0; depth < 8 && failure instanceof ContentBundleError; depth++)
1833
- failure = failure.cause;
1834
- if (!selected ||
1835
- !(failure instanceof ContentError) ||
1836
- failure.code !== "missing_block")
1936
+ if (!selected || !missingContent(cause))
1837
1937
  throw cause;
1838
1938
  const swarm = withState(context, (state) => state.resolveSwarm(selected));
1839
1939
  await readyMembership(context, swarm);
@@ -1925,6 +2025,11 @@ async function currentDependencies(store, root, found = new Set()) {
1925
2025
  await currentDependencies(store, source.cid, found);
1926
2026
  }
1927
2027
  }
2028
+ else if (isSwarmStateSchema(bundle.schemaKey)) {
2029
+ const snapshot = await readState(store, CID.parse(root));
2030
+ for (const target of Object.values(snapshot.names))
2031
+ await currentDependencies(store, target.toString(), found);
2032
+ }
1928
2033
  return found;
1929
2034
  }
1930
2035
  export async function searchNames(context, query, swarms) {
@@ -1955,63 +2060,324 @@ export async function searchNames(context, query, swarms) {
1955
2060
  }
1956
2061
  return { matches, swarms: searched };
1957
2062
  }
1958
- function snapshotAssociations(snapshot) {
1959
- return Object.entries(snapshot.registrations ?? {})
1960
- .sort(([left], [right]) => left.localeCompare(right))
1961
- .map(([schemaCid, item]) => ({
1962
- schemaCid,
1963
- appCid: item.appCid.toString(),
1964
- argv: [...item.argv],
1965
- }));
2063
+ function assertNamesRegistry(snapshot) {
2064
+ if (Object.keys(snapshot.registrations ?? {}).length)
2065
+ throw new HostError("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.");
2066
+ }
2067
+ export async function swarmMeta(context, header) {
2068
+ if (header.snapshot.stateBundle)
2069
+ return header.snapshot.stateBundle.meta;
2070
+ const cid = header.snapshot.names.ipab;
2071
+ if (!cid)
2072
+ throw new HostError('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.');
2073
+ try {
2074
+ const bundle = await openBundle(cid, {
2075
+ resolveCid: (key) => context.store.block.get(key.toString()),
2076
+ });
2077
+ const type = bundle.schemaKey === legacySwarmMetaSchema.cid.toString()
2078
+ ? legacySwarmMetaType
2079
+ : swarmMetaType;
2080
+ return parseSwarmMeta(await typedJson(context.store, cid.toString(), type));
2081
+ }
2082
+ catch (cause) {
2083
+ throw new HostError(`Invalid Swarm Meta at Name "ipab": ${message(cause)}. Publish a valid typed Meta Bundle explicitly; no builtin or legacy fallback is used.`);
2084
+ }
2085
+ }
2086
+ function metaCid(snapshot) {
2087
+ return snapshot.stateBundle?.cid ?? snapshot.names.ipab.toString();
2088
+ }
2089
+ function hasMeta(snapshot) {
2090
+ return (snapshot.stateBundle !== undefined || Object.hasOwn(snapshot.names, "ipab"));
2091
+ }
2092
+ export async function swarmSkills(context, configUrl, requested, owner) {
2093
+ const warm = await localHeader(context, configUrl);
2094
+ if (warm && !warm.header.localSourceReady)
2095
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
2096
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
2097
+ const roots = new Set();
2098
+ const protect = async (cid) => {
2099
+ roots.add(cid);
2100
+ const values = [...roots];
2101
+ context.store.registerOwner(owner, values);
2102
+ await context.store.retain(owner, values);
2103
+ await context.store.confirmRetained(owner, values);
2104
+ };
2105
+ for (let attempt = 0;; attempt++) {
2106
+ if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
2107
+ header = await swarmHeader(context, configUrl, true);
2108
+ continue;
2109
+ }
2110
+ if (hasMeta(header.snapshot))
2111
+ await protect(metaCid(header.snapshot));
2112
+ const meta = await swarmMeta(context, header);
2113
+ if (!meta.skillPath)
2114
+ throw new HostError(header.snapshot.stateBundle
2115
+ ? "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."
2116
+ : `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.`);
2117
+ const prefix = `${meta.skillPath}/`;
2118
+ const entries = Object.entries(header.snapshot.names).filter(([name]) => name.startsWith(prefix));
2119
+ for (const [, target] of entries)
2120
+ roots.add(target.toString());
2121
+ context.store.registerOwner(owner, [...roots]);
2122
+ const result = [];
2123
+ const identities = new Set();
2124
+ for (const [name, target] of entries.sort(([a], [b]) => a.localeCompare(b))) {
2125
+ if (name.slice(prefix.length).includes("/"))
2126
+ throw new HostError(`Skill Name "${name}" must be flat under ${meta.skillPath}.`);
2127
+ const cid = await artifactValue(context.store, target.toString(), protect);
2128
+ const bundle = await openBundle(CID.parse(cid), {
2129
+ resolveCid: (key) => context.store.block.get(key.toString()),
2130
+ });
2131
+ if (bundle.schemaKey !== skillSchema.cid.toString())
2132
+ throw new HostError(`Name "${name}" is not an exact Skill type Bundle.`);
2133
+ const identity = await skillIdentity(bundle);
2134
+ if (identities.has(identity))
2135
+ throw new HostError(`Duplicate Skill installation name "${identity}" in this Swarm.`);
2136
+ identities.add(identity);
2137
+ result.push({ name, cid, identity });
2138
+ }
2139
+ const missing = requested.filter((reference) => !result.some((skill) => skill.name === reference || skill.identity === reference));
2140
+ if (missing.length && !attempt && header.source === "cache") {
2141
+ header = await swarmHeader(context, configUrl, true);
2142
+ continue;
2143
+ }
2144
+ if (missing.length)
2145
+ throw new HostError(`Skill identities or shared Names not found under ${meta.skillPath}: ${missing.join(", ")}.`);
2146
+ return result;
2147
+ }
2148
+ }
2149
+ export async function resolveTemplateSelector(context, selector, configUrl) {
2150
+ formalName(selector);
2151
+ const warm = await localHeader(context, configUrl);
2152
+ if (warm && !warm.header.localSourceReady)
2153
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
2154
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
2155
+ if (!hasMeta(header.snapshot) && header.source === "cache")
2156
+ header = await swarmHeader(context, configUrl, true);
2157
+ for (let attempt = 0;; attempt++) {
2158
+ const meta = await swarmMeta(context, header);
2159
+ const name = formalName(`${meta.templatePath}/${selector}`);
2160
+ const target = header.snapshot.names[name];
2161
+ if (target)
2162
+ return artifactValue(context.store, target.toString());
2163
+ if (attempt || header.source !== "cache")
2164
+ throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
2165
+ header = await swarmHeader(context, configUrl, true);
2166
+ }
2167
+ }
2168
+ export function templateName(name) {
2169
+ if (name.includes(":"))
2170
+ throw new HostError("Template NAME must be a safe relative Name, not a URI.");
2171
+ return formalName(name);
2172
+ }
2173
+ async function templateEntry(context, configUrl, header, selector) {
2174
+ const meta = await swarmMeta(context, header);
2175
+ const name = formalName(`${meta.templatePath}/${templateName(selector)}`);
2176
+ const target = header.snapshot.names[name];
2177
+ if (!target)
2178
+ throw new HostError(`Template Name "${name}" was not found after refreshing HEAD.`);
2179
+ const targetCid = target.toString();
2180
+ return {
2181
+ swarm: configUrl,
2182
+ templatePath: meta.templatePath,
2183
+ metaCid: metaCid(header.snapshot),
2184
+ name,
2185
+ selector,
2186
+ reference: formatNameReference(configUrl, name),
2187
+ targetCid,
2188
+ ...(await inspectTemplate(context.store, await artifactValue(context.store, targetCid))),
2189
+ };
2190
+ }
2191
+ export async function swarmTemplates(context, configUrl, selector) {
2192
+ if (selector !== undefined)
2193
+ templateName(selector);
2194
+ const warm = await localHeader(context, configUrl);
2195
+ if (warm && !warm.header.localSourceReady)
2196
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
2197
+ let header = warm?.header ??
2198
+ (await swarmHeader(context, configUrl, undefined, "local-first"));
2199
+ for (let attempt = 0;; attempt++) {
2200
+ if (!hasMeta(header.snapshot) && header.source === "cache" && !attempt) {
2201
+ header = await swarmHeader(context, configUrl, true, "local-first");
2202
+ continue;
2203
+ }
2204
+ const meta = await swarmMeta(context, header);
2205
+ const name = selector === undefined
2206
+ ? undefined
2207
+ : formalName(`${meta.templatePath}/${selector}`);
2208
+ if (name &&
2209
+ !header.snapshot.names[name] &&
2210
+ header.source === "cache" &&
2211
+ !attempt) {
2212
+ header = await swarmHeader(context, configUrl, true, "local-first");
2213
+ continue;
2214
+ }
2215
+ const selectors = selector === undefined
2216
+ ? Object.keys(header.snapshot.names)
2217
+ .filter((key) => key.startsWith(`${meta.templatePath}/`))
2218
+ .map((key) => key.slice(meta.templatePath.length + 1))
2219
+ .sort((a, b) => a.localeCompare(b))
2220
+ : [selector];
2221
+ const items = [];
2222
+ for (const item of selectors)
2223
+ items.push(await templateEntry(context, configUrl, header, item));
2224
+ return items;
2225
+ }
2226
+ }
2227
+ export async function setSwarmTemplate(context, configUrl, selector, source, expect) {
2228
+ templateName(selector);
2229
+ await pointer(context, configUrl);
2230
+ const content = await templatePublicationSource(source, context.store);
2231
+ const details = await inspectTemplate(context.store, content);
2232
+ let location;
2233
+ const targetCid = await publishContent(context, content, {
2234
+ swarm: configUrl,
2235
+ name: selector,
2236
+ ...(expect === undefined ? {} : { expect }),
2237
+ }, async (current) => {
2238
+ const meta = await swarmMeta(context, { snapshot: current });
2239
+ const name = formalName(`${meta.templatePath}/${selector}`);
2240
+ location = {
2241
+ name,
2242
+ templatePath: meta.templatePath,
2243
+ metaCid: metaCid(current),
2244
+ };
2245
+ return name;
2246
+ });
2247
+ return {
2248
+ swarm: configUrl,
2249
+ ...location,
2250
+ selector,
2251
+ reference: formatNameReference(configUrl, location.name),
2252
+ targetCid,
2253
+ ...details,
2254
+ };
2255
+ }
2256
+ export async function removeSwarmTemplate(context, configUrl, selector, expect) {
2257
+ templateName(selector);
2258
+ const expected = exactCid(expect);
2259
+ const head = await pointer(context, configUrl);
2260
+ let basis;
2261
+ for (let attempt = 0; attempt < 8; attempt++) {
2262
+ const currentHead = await head.read();
2263
+ const current = await readSnapshot(context.store, currentHead.root);
2264
+ const meta = await swarmMeta(context, { snapshot: current });
2265
+ const name = formalName(`${meta.templatePath}/${selector}`);
2266
+ if (basis !== undefined && basis !== name)
2267
+ throw new HostError("Template Meta path changed during removal; inspect and retry.", 3, "EDIT_CONFLICT", "publication");
2268
+ basis = name;
2269
+ const old = current.names[name]?.toString();
2270
+ if (!old)
2271
+ throw new HostError(`Template Name "${name}" is missing; nothing was removed.`);
2272
+ if (old !== expected)
2273
+ throw new HostError(`Edit conflict for ${name}; --expect must match the exact old Name target CID.`, 3, "EDIT_CONFLICT", "publication");
2274
+ const names = { ...current.names };
2275
+ delete names[name];
2276
+ const next = await prepareNamesPublication(context, configUrl, currentHead.root, current, names, []);
2277
+ try {
2278
+ await head.write(next, currentHead.cid, uniqueId());
2279
+ }
2280
+ catch (cause) {
2281
+ if (cause instanceof ScopeApiError && cause.status === 412)
2282
+ continue;
2283
+ throw new HostError(`Template removal unconfirmed: ${message(cause)}. Inspect HEAD before retry.`, 1, "HEAD_UNCONFIRMED", "publication");
2284
+ }
2285
+ try {
2286
+ await swarmHeader(context, configUrl, true);
2287
+ }
2288
+ catch (cause) {
2289
+ throw new HostError(`Template removal committed, but HEAD/subscription refresh failed: ${message(cause)}. No content was deleted.`, 1, "PIN_STALE", "publication");
2290
+ }
2291
+ return {
2292
+ swarm: configUrl,
2293
+ templatePath: meta.templatePath,
2294
+ metaCid: metaCid(current),
2295
+ selector,
2296
+ name,
2297
+ reference: formatNameReference(configUrl, name),
2298
+ targetCid: old,
2299
+ };
2300
+ }
2301
+ throw new HostError("HEAD is busy; retry the template removal.");
2302
+ }
2303
+ async function registryAssociations(context, header) {
2304
+ assertNamesRegistry(header.snapshot);
2305
+ const meta = await swarmMeta(context, header);
2306
+ const prefix = `${meta.registryPath}/`;
2307
+ const result = [];
2308
+ for (const [name, cid] of Object.entries(header.snapshot.names)) {
2309
+ if (!name.startsWith(prefix))
2310
+ continue;
2311
+ const schemaCid = name.slice(prefix.length);
2312
+ if (exactCid(schemaCid, true) !== schemaCid)
2313
+ throw new HostError(`Registry Name "${name}" must end in an exact canonical type CID.`);
2314
+ result.push(createAssociation(schemaCid, cid.toString(), ["%"]));
2315
+ }
2316
+ return result.sort((left, right) => left.schemaCid.localeCompare(right.schemaCid));
1966
2317
  }
1967
2318
  export async function swarmRegistrations(context, configUrl) {
1968
- const header = await swarmHeader(context, configUrl);
1969
- return withState(context, (state) => state.projectedSwarmRegistrations(headerProjection(header)));
2319
+ let header = await swarmHeader(context, configUrl);
2320
+ if (!hasMeta(header.snapshot) && header.source === "cache")
2321
+ header = await swarmHeader(context, configUrl, true);
2322
+ return registryAssociations(context, header);
1970
2323
  }
1971
2324
  export async function swarmAssociation(context, configUrl, schemaCid, mode = "active") {
1972
- let header = (mode === "local-first"
1973
- ? (await localHeader(context, configUrl))?.header
1974
- : undefined) ?? (await swarmHeader(context, configUrl));
1975
- let association = withState(context, (state) => state.projectedSwarmRegistrations(headerProjection(header), schemaCid)[0]);
2325
+ const warm = mode === "local-first" ? await localHeader(context, configUrl) : undefined;
2326
+ if (warm && !warm.header.localSourceReady)
2327
+ await lazyPrivateSource(context, configUrl, warm.account, warm.header.config);
2328
+ let header = warm?.header ?? (await swarmHeader(context, configUrl));
2329
+ if (!hasMeta(header.snapshot) && header.source === "cache")
2330
+ header = await swarmHeader(context, configUrl, true);
2331
+ let association = (await registryAssociations(context, header)).find((item) => item.schemaCid === schemaCid);
1976
2332
  if (!association && header.source === "cache") {
1977
2333
  header = await swarmHeader(context, configUrl, true);
1978
- association = withState(context, (state) => state.projectedSwarmRegistrations(headerProjection(header), schemaCid)[0]);
2334
+ association = (await registryAssociations(context, header)).find((item) => item.schemaCid === schemaCid);
1979
2335
  }
1980
2336
  return association;
1981
2337
  }
2338
+ async function prepareNamesPublication(context, configUrl, previousRoot, current, names, roots, retainedRoots) {
2339
+ const next = await publication(context.store, await writeSnapshot(context.store, { ...current, names }), previousRoot);
2340
+ const closure = await publicationClosure(context.store, next, false);
2341
+ await provideContent(context.store, [...new Set([...closure.provided, ...roots])], context.node.api, context.fetch, context.node.auth, [...new Set([next, ...closure.nameTargets, ...(retainedRoots ?? roots)])]);
2342
+ withState(context, (state) => {
2343
+ state.invalidateSwarmHeader(configUrl);
2344
+ });
2345
+ return next;
2346
+ }
1982
2347
  async function editSwarmAssociation(context, configUrl, schemaCid, association, replace) {
1983
2348
  const head = await pointer(context, configUrl);
2349
+ if (association) {
2350
+ const app = await openBundle(CID.parse(association.appCid), {
2351
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
2352
+ });
2353
+ if (app.schemaKey !== appSchemaCid.toString())
2354
+ throw new HostError("Registry Names must directly reference an App Bundle CID, not an Artifact or another content type.");
2355
+ }
1984
2356
  const roots = association
1985
2357
  ? await dependencies(context.store, association.appCid)
1986
2358
  : new Set();
1987
2359
  for (let attempt = 0; attempt < 8; attempt++) {
1988
2360
  const currentHead = await head.read();
1989
2361
  const current = await readSnapshot(context.store, currentHead.root);
1990
- const old = snapshotAssociations(current).find((item) => item.schemaCid === schemaCid);
2362
+ assertNamesRegistry(current);
2363
+ const meta = await swarmMeta(context, { snapshot: current });
2364
+ const name = formalName(`${meta.registryPath}/${schemaCid}`);
2365
+ const oldCid = current.names[name]?.toString();
1991
2366
  if (association) {
1992
- if (old &&
1993
- old.appCid === association.appCid &&
1994
- JSON.stringify(old.argv) === JSON.stringify(association.argv))
2367
+ if (oldCid === association.appCid)
1995
2368
  return;
1996
- if (old && !replace)
1997
- throw new HostError("Schema has another association; use --replace before --.");
2369
+ if (oldCid && !replace)
2370
+ throw new HostError("Schema has another association; use --replace.");
1998
2371
  }
1999
- else if (!old) {
2372
+ else if (!oldCid) {
2000
2373
  throw new HostError("No association exists for this Schema. Run ipab register list --swarm URL_OR_ALIAS.");
2001
2374
  }
2002
- const registrations = { ...current.registrations };
2375
+ const names = { ...current.names };
2003
2376
  if (association)
2004
- registrations[schemaCid] = {
2005
- appCid: CID.parse(association.appCid),
2006
- argv: association.argv,
2007
- };
2377
+ names[name] = CID.parse(association.appCid);
2008
2378
  else
2009
- delete registrations[schemaCid];
2010
- const next = await publication(context.store, await writeSnapshot(context.store, { ...current, registrations }), currentHead.root);
2011
- await provideContent(context.store, [next, ...roots], context.node.api, context.fetch, context.node.auth);
2012
- withState(context, (state) => {
2013
- state.invalidateSwarmHeader(configUrl);
2014
- });
2379
+ delete names[name];
2380
+ const next = await prepareNamesPublication(context, configUrl, currentHead.root, current, names, roots);
2015
2381
  try {
2016
2382
  await head.write(next, currentHead.cid, uniqueId());
2017
2383
  return;
@@ -2025,6 +2391,8 @@ async function editSwarmAssociation(context, configUrl, schemaCid, association,
2025
2391
  throw new HostError(`HEAD is busy for ${configUrl}; retry the registry edit.`);
2026
2392
  }
2027
2393
  export async function setSwarmAssociation(context, configUrl, value, replace = false) {
2394
+ if (value.argv.length !== 1 || value.argv[0] !== "%")
2395
+ throw new HostError('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.');
2028
2396
  const association = createAssociation(value.schemaCid, value.appCid, value.argv);
2029
2397
  await editSwarmAssociation(context, configUrl, association.schemaCid, association, replace);
2030
2398
  return association;
@@ -2058,10 +2426,18 @@ async function dependencies(store, root, found = new Set()) {
2058
2426
  await dependencies(store, source.cid, found);
2059
2427
  }
2060
2428
  }
2429
+ else if (isSwarmStateSchema(bundle.schemaKey)) {
2430
+ const snapshot = await readState(store, CID.parse(root));
2431
+ for (const target of Object.values(snapshot.names))
2432
+ await dependencies(store, target.toString(), found);
2433
+ }
2061
2434
  return found;
2062
2435
  }
2063
2436
  export async function frozenPublicationClosure(store, root) {
2064
- const publications = new Set(), content = new Set();
2437
+ return (await publicationClosure(store, root)).provided;
2438
+ }
2439
+ async function publicationClosure(store, root, includeDependencies = true) {
2440
+ const publications = new Set(), content = new Set(), nameTargets = new Set();
2065
2441
  let current = root;
2066
2442
  while (current !== undefined) {
2067
2443
  if (publications.has(current) || publications.size >= 256)
@@ -2069,35 +2445,52 @@ export async function frozenPublicationClosure(store, root) {
2069
2445
  publications.add(current);
2070
2446
  const publication = await readPublication(store, current);
2071
2447
  const snapshot = await readState(store, publication.state);
2072
- for (const target of Object.values(snapshot.names))
2073
- await dependencies(store, target.toString(), content);
2074
- for (const association of Object.values(snapshot.registrations ?? {}))
2075
- await dependencies(store, association.appCid.toString(), content);
2448
+ for (const target of Object.values(snapshot.names)) {
2449
+ nameTargets.add(target.toString());
2450
+ if (includeDependencies)
2451
+ await dependencies(store, target.toString(), content);
2452
+ else
2453
+ content.add(target.toString());
2454
+ }
2455
+ if (includeDependencies)
2456
+ for (const association of Object.values(snapshot.registrations ?? {}))
2457
+ await dependencies(store, association.appCid.toString(), content);
2076
2458
  current = publication.previous?.toString();
2077
2459
  }
2078
- return [
2079
- root,
2080
- ...[...new Set([...publications, ...content])]
2081
- .filter((cid) => cid !== root)
2082
- .sort(),
2083
- ];
2460
+ return {
2461
+ nameTargets,
2462
+ provided: [
2463
+ root,
2464
+ ...[...new Set([...publications, ...content])]
2465
+ .filter((cid) => cid !== root)
2466
+ .sort(),
2467
+ ],
2468
+ };
2084
2469
  }
2085
2470
  export async function publish(context, content, options) {
2471
+ return publishContent(context, content, options);
2472
+ }
2473
+ async function publishContent(context, content, options, nameForSnapshot) {
2086
2474
  if (!options.swarm)
2087
2475
  throw new HostError("Publication requires a selected Swarm configuration URL or alias.");
2088
2476
  const head = await pointer(context, options.swarm);
2089
2477
  const roots = await dependencies(context.store, content);
2090
2478
  const currentRoots = [...(await currentDependencies(context.store, content))];
2091
2479
  await withStateAsync(context, (state) => pinCid(state, content, context.store, currentRoots));
2092
- const name = formalName(options.name);
2480
+ let name = formalName(options.name);
2481
+ let resolvedName;
2093
2482
  if (options.snapshot && options.expect)
2094
2483
  throw new HostError("Snapshots cannot replace an occupied Name.");
2095
2484
  const expected = options.expect
2096
2485
  ? CID.parse(options.expect).toV1().toString()
2097
2486
  : undefined;
2098
- if (expected)
2099
- parseArtifact(await typedJson(context.store, expected, artifactType));
2100
- const candidate = options.snapshot
2487
+ const contentBundle = await openBundle(CID.parse(content), {
2488
+ resolveCid: (cid) => context.store.block.get(cid.toString()),
2489
+ });
2490
+ const direct = contentBundle.schemaKey === appSchemaCid.toString() ||
2491
+ contentBundle.schemaKey === swarmMetaSchema.cid.toString() ||
2492
+ contentBundle.schemaKey === legacySwarmMetaSchema.cid.toString();
2493
+ const candidate = options.snapshot || direct
2101
2494
  ? content
2102
2495
  : await jsonBundle(context.store, artifactType, {
2103
2496
  value: content,
@@ -2110,18 +2503,17 @@ export async function publish(context, content, options) {
2110
2503
  roots.add(root);
2111
2504
  for (let attempt = 0; attempt < 8; attempt++) {
2112
2505
  const currentHead = await head.read(), current = await readSnapshot(context.store, currentHead.root);
2506
+ if (nameForSnapshot) {
2507
+ name = await nameForSnapshot(current);
2508
+ if (resolvedName !== undefined && resolvedName !== name)
2509
+ throw new HostError("Template Meta path changed during publication; inspect and retry. Content remains pinned.", 3, "EDIT_CONFLICT", "publication");
2510
+ resolvedName = name;
2511
+ }
2113
2512
  if ((Object.hasOwn(current.names, name)
2114
2513
  ? current.names[name]?.toString()
2115
2514
  : undefined) !== expected)
2116
- throw new HostError(`Edit conflict for ${name}; content ${content} remains pinned. Occupied Names require --expect EXACT_OLD_ARTIFACT_CID; inspect the current Name before retrying.`, 3, "EDIT_CONFLICT", "publication");
2117
- const next = await publication(context.store, await writeSnapshot(context.store, {
2118
- ...current,
2119
- names: { ...current.names, [name]: CID.parse(candidate) },
2120
- }), currentHead.root);
2121
- await provideContent(context.store, [next, ...roots], context.node.api, context.fetch, context.node.auth, [next, ...(expected ? await dependencies(context.store, expected) : [])]);
2122
- withState(context, (state) => {
2123
- state.invalidateSwarmHeader(options.swarm);
2124
- });
2515
+ throw new HostError(`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.`, 3, "EDIT_CONFLICT", "publication");
2516
+ const next = await prepareNamesPublication(context, options.swarm, currentHead.root, current, { ...current.names, [name]: CID.parse(candidate) }, roots, expected ? await dependencies(context.store, expected) : []);
2125
2517
  try {
2126
2518
  await head.write(next, currentHead.cid, uniqueId());
2127
2519
  }