@dtmd/temper 0.0.24 → 0.0.26

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 (70) hide show
  1. package/README.md +14 -12
  2. package/dist/src/assembly.d.ts +45 -11
  3. package/dist/src/assembly.js +116 -8
  4. package/dist/src/builtins.d.ts +436 -103
  5. package/dist/src/builtins.js +772 -167
  6. package/dist/src/claude-code.d.ts +6 -3
  7. package/dist/src/claude-code.js +2 -2
  8. package/dist/src/contract.d.ts +153 -44
  9. package/dist/src/contract.js +123 -34
  10. package/dist/src/counsel.d.ts +11 -0
  11. package/dist/src/counsel.js +68 -0
  12. package/dist/src/declarations.d.ts +108 -2
  13. package/dist/src/declarations.js +606 -100
  14. package/dist/src/dial.d.ts +3 -3
  15. package/dist/src/dial.js +21 -5
  16. package/dist/src/emit.d.ts +12 -14
  17. package/dist/src/emit.js +123 -47
  18. package/dist/src/generated/AbsenceGateRow.d.ts +16 -0
  19. package/dist/src/generated/AbsenceGateRow.js +2 -0
  20. package/dist/src/generated/AreaMode.d.ts +5 -0
  21. package/dist/src/generated/AreaMode.js +2 -0
  22. package/dist/src/generated/AreaRow.d.ts +20 -0
  23. package/dist/src/generated/AreaRow.js +1 -0
  24. package/dist/src/generated/AssemblyFactRow.d.ts +17 -4
  25. package/dist/src/generated/BoundRow.d.ts +9 -4
  26. package/dist/src/generated/CedeRow.d.ts +14 -0
  27. package/dist/src/generated/CedeRow.js +2 -0
  28. package/dist/src/generated/CharsetRow.d.ts +14 -3
  29. package/dist/src/generated/ClauseRow.d.ts +23 -21
  30. package/dist/src/generated/CollectionAddressRow.d.ts +1 -1
  31. package/dist/src/generated/Declarations.d.ts +24 -9
  32. package/dist/src/generated/FeatureValue.d.ts +3 -3
  33. package/dist/src/generated/Features.d.ts +3 -3
  34. package/dist/src/generated/KindFactRow.d.ts +41 -8
  35. package/dist/src/generated/Payload.d.ts +3 -5
  36. package/dist/src/generated/PayloadMember.d.ts +7 -0
  37. package/dist/src/generated/RunsRow.d.ts +17 -0
  38. package/dist/src/generated/RunsRow.js +2 -0
  39. package/dist/src/generated/Section.d.ts +2 -2
  40. package/dist/src/generated/SectionContainsRow.d.ts +1 -1
  41. package/dist/src/generated/TypecheckRow.d.ts +20 -0
  42. package/dist/src/generated/TypecheckRow.js +2 -0
  43. package/dist/src/generated/Verifier.d.ts +8 -2
  44. package/dist/src/generated/index.d.ts +6 -0
  45. package/dist/src/index.d.ts +20 -15
  46. package/dist/src/index.js +10 -9
  47. package/dist/src/kind.d.ts +382 -52
  48. package/dist/src/kind.js +461 -49
  49. package/dist/src/lockfile.d.ts +39 -0
  50. package/dist/src/lockfile.js +265 -0
  51. package/dist/src/member-address.d.ts +15 -3
  52. package/dist/src/member-address.js +23 -6
  53. package/dist/src/needs.d.ts +25 -15
  54. package/dist/src/needs.js +10 -11
  55. package/dist/src/patterns.d.ts +112 -0
  56. package/dist/src/patterns.js +90 -0
  57. package/dist/src/pipe.d.ts +16 -0
  58. package/dist/src/pipe.js +39 -0
  59. package/dist/src/playbook.d.ts +203 -0
  60. package/dist/src/playbook.js +239 -0
  61. package/dist/src/prose.d.ts +69 -12
  62. package/dist/src/prose.js +125 -13
  63. package/dist/src/reference.d.ts +70 -0
  64. package/dist/src/reference.js +368 -0
  65. package/package.json +13 -4
  66. package/schemas/agent.json +23 -0
  67. package/schemas/command.json +5 -0
  68. package/schemas/output-style.json +4 -0
  69. package/schemas/rule.json +33 -0
  70. package/schemas/skill.json +63 -0
package/dist/src/kind.js CHANGED
@@ -9,7 +9,27 @@
9
9
  * rows. Identity travels by import, never by string — a `kind` reference is the imported
10
10
  * value.
11
11
  */
12
+ import { memberProse } from "./prose.js";
12
13
  import { isOneSegment } from "./member-address.js";
14
+ /** The kind names an edge's `to` set lists, in declared order — the names the lock records. */
15
+ export function edgeTargetNames(edge) {
16
+ return edge.to.map((target) => target.key);
17
+ }
18
+ /**
19
+ * An `at` locus's templates as a list of globs, in declared order — the one
20
+ * normalization of {@link Locus}'s `glob`, so no reader branches on its spellings.
21
+ */
22
+ export function templatesOf(locus) {
23
+ return typeof locus.glob === "string"
24
+ ? [locus.glob]
25
+ : locus.glob.map((template) => (typeof template === "string" ? template : template.glob));
26
+ }
27
+ /** The gated templates of an `at` locus, in declared order; empty for a locus gating none. */
28
+ export function absenceGatesOf(locus) {
29
+ return typeof locus.glob === "string"
30
+ ? []
31
+ : locus.glob.filter((template) => typeof template !== "string");
32
+ }
13
33
  /**
14
34
  * Declare a file a member's claims rest on — the lock fingerprints it and no byte
15
35
  * reaches the projection. The path resolves against the stating module, so the call is
@@ -19,7 +39,7 @@ export function input(moduleUrl, path) {
19
39
  return { kind: "input", path, moduleUrl };
20
40
  }
21
41
  /** The framework keys of a member init — everything else is a typed field (flat). */
22
- const FRAMEWORK_KEYS = new Set(["name", "host", "prose", "satisfies", "requires", "needs", "inputs", "residue"]);
42
+ const FRAMEWORK_KEYS = new Set(["name", "host", "location", "prose", "satisfies", "requires", "needs", "inputs", "mode", "residue"]);
23
43
  /**
24
44
  * The **reserved leaf key** a nested member's own span lands under (0051) —
25
45
  * `<host-address>/<kind>/<key>/prose`. On the read half a layout collection member's
@@ -56,20 +76,72 @@ const RESIDUE_KEY = "residue";
56
76
  * the fields are the whole member, folded into a manifest entry, never a header.
57
77
  *
58
78
  * A {@link RESIDUE_KEY} bag splices in last: what the program types, it orders; what it
59
- * merely carries, it sorts.
79
+ * merely carries, it sorts. A `plain` field — one an {@link extend} delta placed in the
80
+ * body ({@link BodyPlacement}) — is never projected: it lives where the base's format
81
+ * admits it, never as an undocumented key.
60
82
  */
61
- function orderedFields(facts, init) {
83
+ function orderedFields(facts, init, plain) {
62
84
  if (facts.format === undefined && facts.shape !== "fields")
63
85
  return [];
64
86
  const typed = [];
65
87
  for (const [key, value] of Object.entries(init)) {
66
- if (!FRAMEWORK_KEYS.has(key))
88
+ if (!FRAMEWORK_KEYS.has(key) && !plain.has(key))
67
89
  typed.push([key, value]);
68
90
  }
69
- const head = facts.identityField !== undefined ? [[facts.identityField, init.name]] : [];
91
+ const head = facts.identityField !== undefined ? [[facts.identityField, identityFieldValue(facts, init.name, init.location)]] : [];
70
92
  const projected = [...head, ...typed];
71
93
  return [...projected, ...residueFields(facts, init, projected)];
72
94
  }
95
+ /**
96
+ * The value a member's name writes under its kind's identity field: the name less the
97
+ * prefix its declared location's `**`-spanned directories spell (`apps:web:deploy` at
98
+ * `apps/web/.claude/skills/deploy/SKILL.md` writes `deploy`), and the whole name where no
99
+ * location is declared. The prefix is read off the location, never cut from the name.
100
+ *
101
+ * # Throws
102
+ * If the name does not carry the prefix its location spells.
103
+ */
104
+ function identityFieldValue(facts, name, location) {
105
+ if (location === undefined || facts.locus.kind !== "at")
106
+ return name;
107
+ const prefix = locationPrefix(templatesOf(facts.locus), location);
108
+ if (prefix === "")
109
+ return name;
110
+ if (!name.startsWith(`${prefix}:`) || name.length === prefix.length + 1) {
111
+ throw new Error(`member \`${name}\` of kind \`${facts.name}\`: its location \`${location}\` spells the ` +
112
+ `identity prefix \`${prefix}\`, which the name does not carry — a name's path-derived ` +
113
+ `prefix and its location agree (specs/model/representation.md, "member").`);
114
+ }
115
+ return name.slice(prefix.length + 1);
116
+ }
117
+ /**
118
+ * The identity prefix a location spells: the directories the one `**` of the first
119
+ * template it fits spans, `:`-joined — the engine's read-side span over the same path.
120
+ * Empty where no template carries exactly one `**`, or the location fits none.
121
+ */
122
+ export function locationPrefix(templates, location) {
123
+ const components = location.split("/");
124
+ for (const template of templates) {
125
+ const segments = template.split("/");
126
+ let lead = 0;
127
+ while (lead < segments.length - 1 && !segments[lead].includes("*"))
128
+ lead += 1;
129
+ const tail = segments.slice(lead);
130
+ const globstars = tail.flatMap((segment, at) => (segment === "**" ? [at] : []));
131
+ if (globstars.length !== 1)
132
+ continue;
133
+ const at = globstars[0];
134
+ const after = tail.length - at - 1;
135
+ const placed = components.slice(lead);
136
+ if (placed.length < at + after || components.slice(0, lead).join("/") !== segments.slice(0, lead).join("/"))
137
+ continue;
138
+ const fixed = placed.slice(placed.length - after);
139
+ const fits = tail.slice(at + 1).every((segment, index) => segment.includes("*") || segment === fixed[index]);
140
+ if (fits)
141
+ return placed.slice(at, placed.length - after).join(":");
142
+ }
143
+ return "";
144
+ }
73
145
  /**
74
146
  * The init's residue bag as projected fields, key-sorted and disjoint from what the
75
147
  * member already projects. The bag is a record, so it carries no authored order to
@@ -124,39 +196,52 @@ function hostOf(facts, init) {
124
196
  }
125
197
  return init.host;
126
198
  }
127
- /**
128
- * Define a kind. Returns a constructor over the kind's typed
129
- * fields `T`; every type erases at the seam, so what the returned member carries
130
- * into emit is the seven facts plus flat field data. `options.render`, when given,
131
- * rides alongside `facts`/`key` on the returned constructor — never on the member
132
- * it builds, since it is erased before a member reaches emit.
133
- *
134
- * The facts are typed over the same `T` the constructor is, which is what binds a
135
- * declared {@link LeafSet} witness to `keyof T`: the leaf set is the kind's own surface,
136
- * checked here at the keystroke, and its lowering to the row is the one place it is
137
- * spelled again (`declarations.ts`).
138
- */
139
199
  export function kind(typed, options = {}) {
200
+ return defineKind(typed, options);
201
+ }
202
+ /** {@link kind} over the whole facts union — the body every overload shares, and the entry
203
+ * {@link relocate} takes, since a relocated facts value is any locus's. */
204
+ function defineKind(typed, options) {
140
205
  // The erasure, spelled: `T` binds the witness and the field slots at the keystroke and
141
206
  // then leaves. `keyof T` reads contravariantly, so the compiler will not widen a slot
142
207
  // set bound to `T` to the erased `string` on its own — every key of `T` is a string
143
208
  // the erased surface admits, which is all this assertion claims.
144
209
  const facts = typed;
145
- if (facts.collectionAddress !== undefined)
210
+ if (collectionAddressOf(facts) !== undefined)
146
211
  manifestOf(facts);
212
+ const body = options.body;
213
+ const plain = new Set(body?.plain ?? []);
147
214
  const construct = (init) => ({
148
215
  kind: facts.name,
149
216
  facts,
150
217
  name: init.name,
151
218
  host: hostOf(facts, init),
152
- prose: init.prose,
153
- fields: orderedFields(facts, init),
219
+ ...(init.location === undefined ? {} : { location: init.location }),
220
+ prose: memberProse(body?.render === undefined ? init.prose : body.render(init), init.name, facts.name),
221
+ fields: orderedFields(facts, init, plain),
154
222
  satisfies: init.satisfies ?? [],
155
223
  requires: init.requires ?? {},
156
224
  needs: init.needs ?? [],
157
225
  inputs: init.inputs ?? [],
226
+ ...(init.mode === undefined ? {} : { mode: init.mode }),
158
227
  });
159
- return Object.assign(construct, { facts, key: facts.name, render: options.render });
228
+ return Object.assign(construct, {
229
+ facts,
230
+ key: facts.name,
231
+ render: options.render,
232
+ ...(body === undefined ? {} : { body }),
233
+ });
234
+ }
235
+ function isAtLocus(facts) {
236
+ return facts.locus.kind === "at";
237
+ }
238
+ /** A kind's registration channel set — declared on an `at` locus, empty on every other. */
239
+ export function registrationOf(facts) {
240
+ return isAtLocus(facts) ? facts.registration : [];
241
+ }
242
+ /** A kind's collection address — only an `at` locus names a manifest to key inside. */
243
+ export function collectionAddressOf(facts) {
244
+ return isAtLocus(facts) ? facts.collectionAddress : undefined;
160
245
  }
161
246
  /**
162
247
  * The host manifest a registration kind surfaces in — its `at` locus glob, which must
@@ -167,49 +252,159 @@ export function kind(typed, options = {}) {
167
252
  * If the kind's locus is not `at`, or its glob carries a `*`.
168
253
  */
169
254
  export function manifestOf(facts) {
170
- if (facts.locus.kind !== "at" || facts.locus.glob.includes("*")) {
171
- const spelled = facts.locus.kind === "at" ? `\`${facts.locus.glob}\`` : `a \`${facts.locus.kind}\` locus`;
255
+ const templates = facts.locus.kind === "at" ? templatesOf(facts.locus) : [];
256
+ const [manifest] = templates;
257
+ if (facts.locus.kind !== "at" || templates.length !== 1 || manifest === undefined || manifest.includes("*")) {
258
+ const spelled = facts.locus.kind === "at" ? `\`${templates.join("`, `")}\`` : `a \`${facts.locus.kind}\` locus`;
172
259
  throw new Error(`kind \`${facts.name}\`: a collection address keys inside the one manifest the kind's ` +
173
260
  `locus names, and ${spelled} names no single file — declare an \`at\` locus whose ` +
174
261
  `glob carries no \`*\` (specs/model/representation.md, "Reach").`);
175
262
  }
176
- return facts.locus.glob;
263
+ return manifest;
177
264
  }
178
265
  /**
179
- * The locus a `governs` delta moves the base to: the base's `at` root and glob replaced,
180
- * every other locus fact (its commitment class among them) riding through.
266
+ * The locus a `locus` delta moves the base to: the base's `at` root and glob replaced,
267
+ * every other locus fact (its commitment class among them) riding through. Of the base's
268
+ * exclusions it keeps each the new template still matches or reaches beneath — moving one
269
+ * loader's reach moves no other's — and drops the rest, which the engine would refuse as
270
+ * subtracting nothing.
181
271
  *
182
272
  * # Throws
183
273
  * If the base's locus is not `at` — an embedded or nested-file kind governs no glob at
184
274
  * all (its members compose their paths from a host's unit, or own no file), so there is
185
- * no locus to move and its row carries no `governs` columns to move it to.
275
+ * no locus to move and its row carries no `locus_root`/`locus_glob` columns to move it to.
186
276
  */
187
- function relocatedLocus(base, governs) {
277
+ function relocatedLocus(base, target) {
188
278
  if (base.locus.kind !== "at") {
189
- throw new Error(`relocating kind \`${base.name}\`: a \`governs\` delta moves the ` +
279
+ throw new Error(`relocating kind \`${base.name}\`: a \`locus\` delta moves the ` +
190
280
  `path glob a kind's members are found at, and this kind's locus is \`${base.locus.kind}\` ` +
191
- `— it governs no glob of its own. Drop the \`governs\` face of the delta ` +
281
+ `— it governs no glob of its own. Drop the \`locus\` face of the delta ` +
192
282
  `(specs/model/representation.md, "locus").`);
193
283
  }
194
- return { ...base.locus, root: governs.root, glob: governs.glob };
284
+ const patterns = templatesOf(target).map((glob) => locusPattern(target.root, glob));
285
+ const kept = (base.locus.exclude ?? []).filter((path) => patterns.some((pattern) => templateMatches(pattern, path) || templateReachesBeneath(pattern, path)));
286
+ const { exclude: _replaced, ...rest } = base.locus;
287
+ return { ...rest, root: target.root, glob: target.glob, ...(kept.length > 0 ? { exclude: kept } : {}) };
288
+ }
289
+ /**
290
+ * The locus an `exclude` delta leaves: `moved` (or the base's own `at` locus, when the
291
+ * delta moves nothing) with the authored paths appended to the exclusions it already
292
+ * carries.
293
+ *
294
+ * # Throws
295
+ * If the base's locus is not `at` — there is no template to subtract from. If an
296
+ * authored path is not starless, is not one the template matches or reaches beneath
297
+ * (the engine refuses it as subtracting nothing when it loads the lock), or is already
298
+ * excluded — a second entry for one path subtracts nothing new.
299
+ */
300
+ function excludedLocus(base, moved, authored) {
301
+ if (base.locus.kind !== "at") {
302
+ throw new Error(`relocating kind \`${base.name}\`: an \`exclude\` delta subtracts paths from the ` +
303
+ `glob a kind's members are found at, and this kind's locus is \`${base.locus.kind}\` ` +
304
+ `— it governs no glob of its own. Drop the \`exclude\` face of the delta ` +
305
+ `(specs/model/representation.md, "locus").`);
306
+ }
307
+ const locus = moved ?? base.locus;
308
+ const patterns = templatesOf(locus).map((glob) => locusPattern(locus.root, glob));
309
+ const exclude = [...(locus.exclude ?? [])];
310
+ for (const path of authored) {
311
+ const starless = !/[*?[\]{}\\]/.test(path) && !path.split("/").some((part) => part === "");
312
+ const governed = patterns.some((pattern) => templateMatches(pattern, path) || templateReachesBeneath(pattern, path));
313
+ if (!starless || !governed) {
314
+ throw new Error(`relocating kind \`${base.name}\`: excluded path \`${path}\` must be a starless, ` +
315
+ `harness-relative path the locus template \`${patterns.join("`, `")}\` matches, or a bare ` +
316
+ `directory it reaches beneath — anything else subtracts nothing ` +
317
+ `(specs/model/representation.md, "locus").`);
318
+ }
319
+ if (exclude.includes(path)) {
320
+ throw new Error(`relocating kind \`${base.name}\`: path \`${path}\` is already excluded, and a ` +
321
+ `second exclusion of one path subtracts nothing new.`);
322
+ }
323
+ exclude.push(path);
324
+ }
325
+ return { ...locus, exclude };
326
+ }
327
+ /** A file locus as one harness-relative template, a root-locus kind's `.` dropped. */
328
+ export function locusPattern(root, glob) {
329
+ return root === "." ? glob : `${root}/${glob}`;
330
+ }
331
+ /**
332
+ * Whether every path the template `sub` matches, `base` matches too — the engine's
333
+ * `locus_within`, decided over the same witnesses: each `*` a fresh token no literal
334
+ * matches, a `**` zero, one and two fresh components.
335
+ */
336
+ function locusWithin(sub, base) {
337
+ const fresh = "\u0001";
338
+ const segments = sub.split("/").map((segment) => (segment === "**" ? segment : segment.split("*").join(fresh)));
339
+ const depths = segments.includes("**") ? [0, 1, 2] : [0];
340
+ return depths.every((depth) => templateMatches(base, segments.flatMap((segment) => (segment === "**" ? Array.from({ length: depth }, (_, n) => `${fresh}${n}`) : [segment])).join("/")));
341
+ }
342
+ /** Whether one path component matches one template segment: a literal, or one `*`. */
343
+ function segmentMatches(segment, component) {
344
+ const star = segment.indexOf("*");
345
+ if (star < 0) {
346
+ return segment === component;
347
+ }
348
+ const prefix = segment.slice(0, star);
349
+ const suffix = segment.slice(star + 1);
350
+ return component.length >= prefix.length + suffix.length && component.startsWith(prefix) && component.endsWith(suffix);
351
+ }
352
+ /**
353
+ * Whether the placement template `pattern` matches `path` whole — each `**` segment
354
+ * standing for any number of components, none included. Mirrors the engine's glob match
355
+ * over the placement-template subset, the only syntax a locus may carry.
356
+ */
357
+ function templateMatches(pattern, path) {
358
+ const matchFrom = (segments, components) => {
359
+ if (segments.length === 0)
360
+ return components.length === 0;
361
+ const [head, ...rest] = segments;
362
+ if (head === "**") {
363
+ return matchFrom(rest, components) || (components.length > 0 && matchFrom(segments, components.slice(1)));
364
+ }
365
+ return components.length > 0 && segmentMatches(head, components[0]) && matchFrom(rest, components.slice(1));
366
+ };
367
+ return matchFrom(pattern.split("/"), path.split("/"));
368
+ }
369
+ /**
370
+ * Whether the placement template `pattern` matches some path strictly beneath the
371
+ * directory `dir` — the engine's reach test for a directory exclusion (`src/kind.rs`,
372
+ * `template_reaches_beneath`), spelled over the same segments.
373
+ */
374
+ function templateReachesBeneath(pattern, dir) {
375
+ const reachFrom = (segments, components) => {
376
+ if (components.length === 0)
377
+ return segments.length > 0;
378
+ if (segments.length === 0)
379
+ return false;
380
+ const [head, ...rest] = segments;
381
+ if (head === "**") {
382
+ return reachFrom(rest, components) || reachFrom(segments, components.slice(1));
383
+ }
384
+ return segmentMatches(head, components[0]) && reachFrom(rest, components.slice(1));
385
+ };
386
+ return reachFrom(pattern.split("/"), dir.split("/"));
195
387
  }
196
388
  /**
197
389
  * **Relocate** a built-in kind: the sanctioned way an adopting corpus moves a kind it
198
- * does not own to its own root, adds an edge field to it, or both. Returns a fresh
199
- * constructor over the widened typed surface `T` (the base's fields plus the added edge
200
- * fields, spelled by the caller as one interface), carrying the base's facts with
201
- * `delta`'s edge fields appended, `delta`'s `governs` in place of the base's locus root
202
- * and glob, and the base's own {@link KindDefinition.render} hook preserved. Ownership,
390
+ * does not own to its own root, adds an edge field to it, excludes paths from it, or any
391
+ * combination. Returns a fresh constructor over the widened typed surface `T` (the
392
+ * base's fields plus the added edge fields, spelled by the caller as one interface),
393
+ * carrying the base's facts with `delta`'s edge fields appended, `delta`'s `locus` in
394
+ * place of the base's locus root and glob, `delta`'s `exclude` appended to the locus's
395
+ * exclusions, and the base's own {@link KindDefinition.render} hook preserved. Ownership,
203
396
  * not privilege — a relocated built-in is an ordinary kind value from here on, and its
204
397
  * added edge reaches the lock as an assembly `edge` row keyed by `from`, exactly as any
205
398
  * kind's does (`declarations.ts`), never as a column on a kind-fact row.
206
399
  *
207
400
  * A moved locus, by contrast, *is* a kind-fact row column pair: the emitted row carries
208
- * the delta's `governs_root`/`governs_glob` while `format`, `unit_shape` and
401
+ * the delta's `locus_root`/`locus_glob` while `format`, `unit_shape` and
209
402
  * `registration` stay the base's — which is precisely the three-fact test the lock
210
403
  * reader applies before overlaying the row onto its compiled-in built-in
211
404
  * (`src/compose.rs`'s `row_relocates_builtin`), so the engine reads members at the new
212
- * root rather than treating the row as a colliding kind.
405
+ * root rather than treating the row as a colliding kind. An `exclude` delta rides the
406
+ * same row's `exclude` column — the reached base exclusions, then the authored ones —
407
+ * which the overlay writes back whole.
213
408
  *
214
409
  * The produced facts carry `relocates`, naming the base — the marker that tells a
215
410
  * legitimate relocation from a genuine name collision when two same-named kinds are in
@@ -219,21 +414,87 @@ function relocatedLocus(base, governs) {
219
414
  * # Throws
220
415
  * If an added edge field re-declares one the base already carries, or one another
221
416
  * entry of the same delta already added — two `edge` rows over one `<from, field>`
222
- * cross-wire the graph instead of declaring one relationship. If a `governs` delta
223
- * names a base whose locus is not `at` ({@link relocatedLocus}). And if the delta
224
- * declares neither face, which would mint a marker-bearing clone of the base — a second
417
+ * cross-wire the graph instead of declaring one relationship. If a `locus` delta
418
+ * names a base whose locus is not `at` ({@link relocatedLocus}), or an `exclude` delta
419
+ * does, or names a path the locus cannot subtract ({@link excludedLocus}). And if the
420
+ * delta declares no face, which would mint a marker-bearing clone of the base — a second
225
421
  * same-named kind diverging on nothing, which is a name collision spelled as a
226
422
  * relocation.
227
423
  */
228
424
  export function relocate(base, delta) {
425
+ const { name: _name, ...relocation } = delta;
426
+ // A relocation keeps the base's surface by construction — it adds no plain field — so
427
+ // the surface witness `extend` demands holds; the generic `T` only defers its proof.
428
+ return extend(base, relocation);
429
+ }
430
+ /**
431
+ * **Extend** a kind. Under a new `name` the result is a **subkind**: it keeps the base's
432
+ * facts, adds `delta`'s edge fields, plain fields and counsel, governs a locus within the
433
+ * base's (the base's own unless `locus` moves it), and names the base in its `base`
434
+ * fact — the engine then reads a document in that locus as the subkind's one member.
435
+ * Under the base's name it is the relocation {@link relocate} documents, the same
436
+ * operation.
437
+ *
438
+ * A plain field lives where the base's format admits it ({@link KindExtension.fields}):
439
+ * a `field` region of the base's layout, or the body the delta's `render` builds. Either
440
+ * way a member never projects it as a frontmatter key, so the subkind's kind-fact row and
441
+ * its members' headers stay the base's documented format.
442
+ *
443
+ * The surface is typed: `T extends B` and {@link KeepsBaseSurface} make `tsc` refuse a
444
+ * delta whose surface retypes or drops a base field, optional ones included — every
445
+ * selection of the base binds the subkind's documents, so its members must read as the
446
+ * base's. Spell both: `extend<Rule, Standard>(rule, { … })`.
447
+ *
448
+ * # Throws
449
+ * As {@link relocate}; for a subkind, if a nested or embedded base's subkind declares a
450
+ * locus, or an `at` subkind's locus does not lie within its base's; if a `template` names
451
+ * no subkind of a layer or collection the host holds; and if a plain field has no place the base's format
452
+ * admits, or a `render` places none ({@link placedBody}).
453
+ */
454
+ export function extend(base, delta) {
455
+ const name = delta.name ?? base.facts.name;
456
+ const subkind = name !== base.facts.name;
457
+ if (subkind) {
458
+ if (base.facts.locus.kind !== "at" && (delta.locus !== undefined || (delta.exclude ?? []).length > 0)) {
459
+ throw new Error(`extending kind \`${base.facts.name}\` as \`${name}\`: a nested kind's members are placed by ` +
460
+ `its host's template, so its subkind declares no locus — name it from an extended host ` +
461
+ `instead: \`extend(host, { name, template: ${name} })\` (specs/model/representation.md, "kind").`);
462
+ }
463
+ if (delta.locus !== undefined && base.facts.locus.kind === "at") {
464
+ const target = delta.locus;
465
+ const baseLocus = base.facts.locus;
466
+ const held = templatesOf(baseLocus).map((glob) => locusPattern(baseLocus.root, glob));
467
+ const own = templatesOf(target)
468
+ .map((glob) => locusPattern(target.root, glob))
469
+ .find((pattern) => !held.some((heldPattern) => locusWithin(pattern, heldPattern)));
470
+ if (own !== undefined) {
471
+ throw new Error(`extending kind \`${base.facts.name}\` as \`${name}\`: the subkind's locus \`${own}\` ` +
472
+ `lies outside the base's \`${held.join("`, `")}\`, and a subkind governs a locus within its ` +
473
+ `base's (specs/model/representation.md, "kind").`);
474
+ }
475
+ }
476
+ }
229
477
  const declaredEdges = delta.edgeFields ?? [];
230
- if (declaredEdges.length === 0 && delta.governs === undefined) {
478
+ const counselled = delta.guidance !== undefined || delta.fieldGuidance !== undefined;
479
+ const body = placedBody(base, name, delta, declaredEdges);
480
+ const hosted = delta.template === undefined ? undefined : hostedLayers(base, name, delta.template);
481
+ const templates = hosted?.templates;
482
+ if (!subkind &&
483
+ body === base.body &&
484
+ templates === undefined &&
485
+ declaredEdges.length === 0 &&
486
+ delta.locus === undefined &&
487
+ (delta.exclude ?? []).length === 0 &&
488
+ !counselled &&
489
+ delta.mode === undefined) {
231
490
  throw new Error(`relocating kind \`${base.facts.name}\`: a relocation declares at least one diverging ` +
232
- `fact — \`edgeFields\`, \`governs\`, or both. A delta declaring neither mints a ` +
491
+ `fact — \`edgeFields\`, \`fields\`, \`locus\`, \`exclude\`, \`template\`, \`mode\`, or guidance. A delta declaring none mints a ` +
233
492
  `second kind of the base's own name that diverges on nothing, which reads as a name ` +
234
493
  `collision rather than a relocation (specs/model/representation.md, "kind").`);
235
494
  }
236
- const locus = delta.governs === undefined ? undefined : relocatedLocus(base.facts, delta.governs);
495
+ const authored = delta.exclude ?? [];
496
+ const moved = delta.locus === undefined ? undefined : relocatedLocus(base.facts, delta.locus);
497
+ const locus = authored.length === 0 ? moved : excludedLocus(base.facts, moved, authored);
237
498
  const inherited = base.facts.edgeFields ?? [];
238
499
  const claimed = new Set(inherited.map((edge) => edge.field));
239
500
  const added = [];
@@ -244,21 +505,172 @@ export function relocate(base, delta) {
244
505
  `adding a relationship (specs/model/representation.md, "kind").`);
245
506
  }
246
507
  claimed.add(edge.field);
247
- added.push({ field: edge.field, to: edge.to });
508
+ added.push(edge);
248
509
  }
249
510
  const edgeFields = [...inherited, ...added];
250
- const relocated = { ...base.facts, relocates: base.facts.name, edgeFields };
511
+ // The base's counsel is dropped, not inherited: the relocation's own, where declared,
512
+ // takes its place, so a guidance rule never projects a built-in's shipped counsel.
513
+ const { guidance: _guidance, fieldGuidance: _fieldGuidance, cite: _cite, ...uncounselled } = base.facts;
514
+ const { relocates: _relocates, base: _base, ...unmarked } = uncounselled;
515
+ const relocated = {
516
+ ...(subkind ? { ...unmarked, name, base: base.facts.name } : { ...uncounselled, relocates: base.facts.name }),
517
+ edgeFields,
518
+ ...(templates === undefined ? {} : { templates }),
519
+ ...(hosted?.content === undefined ? {} : { content: hosted.content }),
520
+ ...(delta.guidance === undefined ? {} : { guidance: delta.guidance }),
521
+ ...(delta.fieldGuidance === undefined ? {} : { fieldGuidance: delta.fieldGuidance }),
522
+ ...(delta.cite === undefined ? {} : { cite: delta.cite }),
523
+ ...(delta.mode === undefined ? {} : { mode: delta.mode }),
524
+ };
251
525
  // Two spellings, not one with an optional `locus`: `KindFacts` is a union discriminated
252
526
  // on the locus, so the moved case must carry the `at` locus as its own literal branch.
253
527
  // A moved locus is only ever an `at` base's (`relocatedLocus` refuses the rest), and an
254
- // `at` kind declares its registration set — so the base's set rides through as declared.
255
- const facts = locus === undefined ? relocated : { ...relocated, locus, registration: relocated.registration ?? [] };
528
+ // `at` kind declares its registration set — so the base's set and address ride through
529
+ // as declared, read off the `at` branch rather than the erased union's remedy slots.
530
+ const { registration: _registration, collectionAddress: _address, ...unregistered } = relocated;
531
+ const address = collectionAddressOf(base.facts);
532
+ const facts = locus === undefined
533
+ ? relocated
534
+ : {
535
+ ...unregistered,
536
+ locus,
537
+ registration: registrationOf(base.facts),
538
+ ...(address === undefined ? {} : { collectionAddress: address }),
539
+ };
256
540
  // The base's leaf-set witness rides through as data, and the assertion is that
257
541
  // pass-through spelled: a relocation appends *edge fields* over the kind's own surface,
258
542
  // never a leaf, so the set the base's own constructor already bound still names what a
259
543
  // member carries. `T` here is the widened surface (the base's fields plus the added
260
544
  // edges), so re-binding the witness to `keyof T` would demand the edge fields be leaves.
261
- return kind(facts, { render: base.render });
545
+ const extended = defineKind(facts, { render: base.render, ...(body === undefined ? {} : { body }) });
546
+ if (subkind)
547
+ BASES.set(extended.facts, base.facts);
548
+ return extended;
549
+ }
550
+ /**
551
+ * Each subkind's base facts, keyed by the subkind's own facts value. A kind's `base` fact
552
+ * carries its base's *name*, which is all the lock needs; the SDK reads a lineage by
553
+ * identity, so a subkind of a subkind still answers {@link extendsKind} for the root of
554
+ * its chain.
555
+ */
556
+ const BASES = new WeakMap();
557
+ /** The kind `facts` is a subkind of, by identity, or `undefined` for a kind {@link extend} minted no subkind from. */
558
+ export function baseOf(facts) {
559
+ return BASES.get(facts);
560
+ }
561
+ /**
562
+ * Whether `facts` is `ancestor`'s own facts or a subkind's anywhere down its
563
+ * {@link extend} chain. Identity travels by import: a same-named kind defined apart is
564
+ * no descendant.
565
+ */
566
+ export function extendsKind(facts, ancestor) {
567
+ for (let at = facts; at !== undefined; at = BASES.get(at)) {
568
+ if (at === ancestor)
569
+ return true;
570
+ }
571
+ return false;
572
+ }
573
+ /**
574
+ * The host's layers with `child` named in place of its base: each template layer whose
575
+ * child is `child`'s base takes `child`, path kept, and for an embedded child so does each
576
+ * layout collection of the base. A collection alone gains a path-less layer of `child`, so
577
+ * the host still names its child by value.
578
+ *
579
+ * # Throws
580
+ * If `child` is no subkind, or the host holds no layer of `child`'s base.
581
+ */
582
+ function hostedLayers(host, name, child) {
583
+ const at = `extending kind \`${host.facts.name}\`${name === host.facts.name ? "" : ` as \`${name}\``}`;
584
+ const childBase = child.facts.base;
585
+ if (childBase === undefined) {
586
+ throw new Error(`${at}: \`template\` names kind \`${child.facts.name}\` as the host's child, and it extends no ` +
587
+ `kind — a template names a subkind of a child the host already templates ` +
588
+ `(specs/model/representation.md, "kind").`);
589
+ }
590
+ const declared = host.facts.templates ?? [];
591
+ const templated = declared.some((layer) => layer.kind.key === childBase);
592
+ const regions = host.facts.content?.regions ?? [];
593
+ const collected = child.facts.locus.kind === "embedded" &&
594
+ regions.some((region) => region.region === "collection" && region.memberKind === childBase);
595
+ if (!templated && !collected) {
596
+ throw new Error(`${at}: \`template\` names \`${child.facts.name}\`, a subkind of \`${childBase}\`, and the ` +
597
+ `host templates no \`${childBase}\` layer for it to take the place of ` +
598
+ `(specs/model/representation.md, "kind").`);
599
+ }
600
+ const templates = templated
601
+ ? declared.map((layer) => (layer.kind.key === childBase ? { ...layer, kind: child } : layer))
602
+ : [...declared, { kind: child }];
603
+ if (!collected)
604
+ return { templates };
605
+ const content = {
606
+ regions: regions.map((region) => region.region === "collection" && region.memberKind === childBase
607
+ ? { ...region, memberKind: child.facts.name }
608
+ : region),
609
+ };
610
+ return { templates, content };
611
+ }
612
+ /**
613
+ * The {@link BodyPlacement} an extension of `base` carries: the base's own, with the
614
+ * delta's plain fields appended and its render composed over the base's. Returns
615
+ * `base.body` itself when the delta places nothing, which is how {@link extend} tells a
616
+ * delta adding no plain field.
617
+ *
618
+ * # Throws
619
+ * If a plain field is already one the base places, or one the delta declares an edge
620
+ * over; if a `"region"` field names no `field` region of the base's layout; if a
621
+ * `"render"` field sits over a base whose body is not one verbatim prose value (a layout,
622
+ * a fields-only kind, an embedded locus), or the delta declares no render to place it;
623
+ * and if a render is declared that places no field.
624
+ */
625
+ function placedBody(base, name, delta, edges) {
626
+ const declared = Object.entries(delta.fields ?? {}).filter((entry) => entry[1] !== undefined);
627
+ const at = `extending kind \`${base.facts.name}\`${name === base.facts.name ? "" : ` as \`${name}\``}`;
628
+ const inherited = base.body?.plain ?? [];
629
+ const edged = new Set([...(base.facts.edgeFields ?? []).map((edge) => edge.field), ...edges.map((edge) => edge.field)]);
630
+ const slots = new Set((base.facts.content?.regions ?? []).flatMap((region) => (region.region === "field" ? [region.slot] : [])));
631
+ const prose = base.facts.content === undefined && base.facts.shape !== "fields" && base.facts.locus.kind !== "embedded";
632
+ let rendered = false;
633
+ for (const [field, place] of declared) {
634
+ if (inherited.includes(field) || edged.has(field) || FRAMEWORK_KEYS.has(field) || field === base.facts.identityField) {
635
+ throw new Error(`${at}: plain field \`${field}\` is already a field the kind carries — a framework key, ` +
636
+ `its identity, an edge field, or a plain field its base placed — and one field takes ` +
637
+ `one place (specs/model/representation.md, "kind").`);
638
+ }
639
+ if (place === "region" && !slots.has(field)) {
640
+ throw new Error(`${at}: plain field \`${field}\` is placed in a body region, and the base's layout ` +
641
+ `declares no \`field\` region of slot \`${field}\` — a field lives where the base's ` +
642
+ `format admits it, never as an undocumented key. Place it with a \`render\` over a ` +
643
+ `\`file\`-content base, or extend a base whose layout holds the slot ` +
644
+ `(specs/model/representation.md, "kind").`);
645
+ }
646
+ if (place === "render" && !prose) {
647
+ throw new Error(`${at}: plain field \`${field}\` is placed by the kind's render, and the base's body is ` +
648
+ `not one verbatim prose value — a layout reads its body by region, a fields-only or ` +
649
+ `embedded kind writes no body of its own — so a render has nowhere to put it. A field ` +
650
+ `lives where the base's format admits it, never as an undocumented key ` +
651
+ `(specs/model/representation.md, "kind").`);
652
+ }
653
+ if (place === "render" && delta.render === undefined) {
654
+ throw new Error(`${at}: plain field \`${field}\` is placed by the kind's render, and the delta declares ` +
655
+ `no \`render\` — declare one that writes it into the body, or the field is an ` +
656
+ `undocumented key (specs/model/representation.md, "kind").`);
657
+ }
658
+ rendered ||= place === "render";
659
+ }
660
+ if (delta.render !== undefined && !rendered) {
661
+ throw new Error(`${at}: a \`render\` places the plain fields a delta adds, and this one places none — ` +
662
+ `name each it writes under \`fields\` as \`"render"\` (specs/model/representation.md, "kind").`);
663
+ }
664
+ if (declared.length === 0)
665
+ return base.body;
666
+ const outer = delta.render;
667
+ const inner = base.body?.render;
668
+ const render = outer === undefined
669
+ ? inner
670
+ : inner === undefined
671
+ ? outer
672
+ : (values) => outer({ ...values, prose: inner(values) });
673
+ return { plain: [...inherited, ...declared.map(([field]) => field)], ...(render === undefined ? {} : { render }) };
262
674
  }
263
675
  export function embeddedMemberValue(init) {
264
676
  const definition = typeof init.kind === "string" ? undefined : init.kind;