@spellkave/world-author 0.0.0-bootstrap

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 (57) hide show
  1. package/LICENSE +89 -0
  2. package/README.md +62 -0
  3. package/package.json +57 -0
  4. package/src/applyset-diff-types.ts +158 -0
  5. package/src/applyset.ts +82 -0
  6. package/src/authoring-harness.ts +487 -0
  7. package/src/browser.ts +114 -0
  8. package/src/compose.ts +699 -0
  9. package/src/corpus.generated.ts +279 -0
  10. package/src/corpus.ts +1180 -0
  11. package/src/damage.ts +75 -0
  12. package/src/diagnostics.ts +59 -0
  13. package/src/diff-manifest-core.ts +393 -0
  14. package/src/diff-manifest.ts +5 -0
  15. package/src/docs-index.ts +105 -0
  16. package/src/dsl.ts +10 -0
  17. package/src/evaluate.ts +100 -0
  18. package/src/explain-core.ts +219 -0
  19. package/src/explain.ts +43 -0
  20. package/src/filter-manifest-core.ts +122 -0
  21. package/src/filter-manifest.ts +41 -0
  22. package/src/grants-core.ts +38 -0
  23. package/src/grants.ts +10 -0
  24. package/src/included-manifest-metadata-core.ts +63 -0
  25. package/src/included-manifest-metadata.ts +21 -0
  26. package/src/index.ts +30 -0
  27. package/src/inspect.ts +35 -0
  28. package/src/inspection.ts +239 -0
  29. package/src/lint.ts +540 -0
  30. package/src/manifest-text.ts +21 -0
  31. package/src/manifest.ts +403 -0
  32. package/src/metadata.ts +137 -0
  33. package/src/npc-dm-authority-projection.ts +95 -0
  34. package/src/npc-dm-documents.ts +339 -0
  35. package/src/npc-dm-presentation.ts +17 -0
  36. package/src/npc-dm-srd.ts +51 -0
  37. package/src/npc-dm-types.ts +723 -0
  38. package/src/npc-kinds.ts +404 -0
  39. package/src/npc-quests.ts +319 -0
  40. package/src/observation-tokens.browser.ts +31 -0
  41. package/src/observation-tokens.ts +27 -0
  42. package/src/owner-instance-read.ts +765 -0
  43. package/src/patch.ts +47 -0
  44. package/src/ref-tags.ts +149 -0
  45. package/src/reference.ts +48 -0
  46. package/src/row-identity.ts +105 -0
  47. package/src/row-kinds-data.ts +35 -0
  48. package/src/row-kinds.ts +93 -0
  49. package/src/scenario-guidance.ts +180 -0
  50. package/src/scoped-instance-read.ts +187 -0
  51. package/src/service-only-audience.ts +14 -0
  52. package/src/session-predicates.ts +6 -0
  53. package/src/spell.ts +119 -0
  54. package/src/tag-prefix-families.ts +143 -0
  55. package/src/tooling.browser.ts +397 -0
  56. package/src/tooling.ts +38 -0
  57. package/src/validate.ts +255 -0
package/src/patch.ts ADDED
@@ -0,0 +1,47 @@
1
+ // Authoring operations over a parsed, schema-shaped manifest object.
2
+ //
3
+ // These mutate the raw `Record<string, unknown>` shape that
4
+ // `inspectManifest(...).manifest` yields and `renderSchemaManifest(...)`
5
+ // serializes — the same object the validator consumes. They live in the SDK (not
6
+ // the CLI shell) so any author — the `manifest patch` command, a bulk importer,
7
+ // a future GUI — drives one authoring surface. Adding a row kind here makes it
8
+ // available everywhere at once.
9
+ //
10
+ // #1968 R7 (ADR-0087, tasks.md section 3): all 13 manifest-mutation ops this
11
+ // module used to hand-implement (row shape, upsert-by-natural-key semantics,
12
+ // field coercion) are now Rust-owned in `spellkave-authoring::patch`, exposed
13
+ // through the `patch_manifest_json` wasm export — see that crate's
14
+ // `src/patch/mod.rs` for the op dispatcher and `src/patch/support.rs` for the
15
+ // shared read/write contract (whole-manifest JSON in, only-the-changed-
16
+ // table(s) JSON out) every op follows. This file is now a thin forwarder;
17
+ // the per-op provenance comments this file used to carry (schema line
18
+ // numbers, canon-warden conditions, deny_unknown_fields traps, upsert-key
19
+ // rationale) now live on each Rust function's own doc comment instead.
20
+
21
+ import { patch_manifest_json } from "@spellkave/authoring-wasm";
22
+
23
+ /**
24
+ * Apply one authoring operation to a parsed schema-shaped manifest object, in
25
+ * place. Exported so every author — the `manifest patch` CLI command and bulk
26
+ * importers (e.g. the SRD Foundry importer) alike — drives the same authoring
27
+ * surface, in-process, without one subprocess per row.
28
+ *
29
+ * Forwards to the Rust-owned `patch_manifest_json` wasm export, which reads
30
+ * the WHOLE manifest for context (bundle_id fallback, existing rows to
31
+ * upsert against) but returns ONLY the table(s) the op actually mutated —
32
+ * every other table on `manifest` stays the exact same JS array it already
33
+ * was, never round-tripped through this call. An unrecognized `op` throws
34
+ * the same `unknown patch op: <op>` error the wasm dispatcher's own fallback
35
+ * arm produces.
36
+ */
37
+ export function patchManifest(
38
+ manifest: Record<string, unknown>,
39
+ op: string,
40
+ payload: Record<string, unknown>,
41
+ ): void {
42
+ const patchedJson = patch_manifest_json(JSON.stringify(manifest), op, JSON.stringify(payload));
43
+ const patched = JSON.parse(patchedJson) as Record<string, unknown[]>;
44
+ for (const [table, rows] of Object.entries(patched)) {
45
+ manifest[table] = rows;
46
+ }
47
+ }
@@ -0,0 +1,149 @@
1
+ // Ref-typed tag values (srd-cc finding ledger finding #2,
2
+ // `packages/spellkave-srd-cc/ledger/findings.md`; design draft:
3
+ // `packages/spellkave-srd-cc/ledger/designs/finding-02-typed-tag-refs.md`).
4
+ //
5
+ // `*_tag` rows (`capability_definition_tag`, `resource_definition_tag`, and
6
+ // nine siblings) carry a single free-string `tag` field. Some content
7
+ // bundles use a dotted `<prefix>.<value>` convention inside that string for
8
+ // identity-only groupings that have no first-class column — e.g.
9
+ // `srd.ability.wis` on a skill capability (`@spellkave/srd-cc`'s own bundle-
10
+ // private prefix; see that package's `src/ref-tag-families.ts`). Nothing
11
+ // resolves the value after the prefix against a real row today: no validator
12
+ // parses a tag's VALUE, and `./inspection.ts`'s `isRefField` heuristic only
13
+ // recognizes `*_id`/`*_key`/`*_ref`/bare `id` FIELD NAMES, never a field's
14
+ // string CONTENT — the field is literally named `tag`, so it never qualifies
15
+ // regardless of what its value encodes.
16
+ //
17
+ // This file declares the MECHANISM for a caller-supplied, explicit,
18
+ // hand-maintained vocabulary of which tag-key prefixes are ref-typed and
19
+ // what they resolve against — consumed by `./lint.ts`'s `dangling-ref-tag`
20
+ // rule (typo protection at author time) and `./inspection.ts`'s
21
+ // `refTagOutboundRefs` (ref-graph traversal, wired into `spellkave_query`'s
22
+ // composite-key detail path). Neither function seeds any family itself —
23
+ // see the interface's own doc comment below for why. Advisory tooling
24
+ // metadata about a content CONVENTION, not a structural
25
+ // manifest fact — deliberately NOT colocated in `./row-kinds.ts`, which is
26
+ // Rust-owned/wasm-mirrored (see that file's own header) for a DIFFERENT
27
+ // reason: `./row-kinds.ts` is loaded via a synchronous nodejs-only
28
+ // `spellkave-authoring-wasm` import, eagerly evaluated at module-import time
29
+ // (its `ROW_KIND_NATURAL_KEY`/`ROW_KIND_COMPOSITE_KEY` consts are computed as
30
+ // soon as the module loads, not lazily). `./lint.ts` and `./inspection.ts`
31
+ // are BOTH statically imported by `./browser.ts` (the wasm-web/browser
32
+ // entry point) — importing `./row-kinds.ts` from either would drag that
33
+ // nodejs wasm binding into the browser bundle, which `./row-kinds.ts`'s own
34
+ // header flags as a real gap ("no browser-bundle consumer today"). This
35
+ // module therefore hand-carries each family's natural-key field directly
36
+ // (`naturalKeyField`) instead of deriving it from `ROW_KIND_NATURAL_KEY` at
37
+ // call time — a small, deliberate duplication in exchange for keeping the
38
+ // browser entry point wasm-web-only.
39
+ //
40
+ // NO SEEDED VOCABULARY HERE (2026-07-27 correction — see `packages/spellkave-
41
+ // srd-cc/ledger/findings.md` finding #2's rename addendum). This module
42
+ // used to export a shared `REF_TAG_FAMILIES` const seeding 5e-shaped keys
43
+ // (`ability=`, `spellcasting=`) directly into this game-agnostic engine —
44
+ // wrong on two counts: (1) it baked content vocabulary into
45
+ // `@spellkave/world-author`, which every OTHER content bundle also depends
46
+ // on, even though only `@spellkave/srd-cc` ever populated a resolvable
47
+ // family; (2) the `key=value` string-tag grammar it validated is itself a
48
+ // documented anti-pattern (`docs/data-model-concepts/tagging.md`'s "A tag is
49
+ // membership, not a behaviour parameter" section: "a `key=value` 'tag'
50
+ // smuggles a typed parameter into the membership table"). The MECHANISM
51
+ // (this interface + `resolveRefTagValue`, plus `./lint.ts`'s
52
+ // `dangling-ref-tag` rule and `./inspection.ts`'s `refTagOutboundRefs`) stays
53
+ // here and stays generic; the FAMILY LIST is now caller-supplied at every
54
+ // call site (`lintManifest`'s `options.refTagFamilies`, `refTagOutboundRefs`'s
55
+ // own parameter) — this package declares zero families of its own. A content
56
+ // bundle wanting typo protection / ref-graph traversal for its own
57
+ // `key=value` tag convention declares its own `RefTagFamily[]` and passes it
58
+ // in (see `@spellkave/srd-cc`'s `src/ref-tag-families.ts` for the first such
59
+ // declaration, using the canonical dotted grammar — `srd.ability.<code>`,
60
+ // not `ability=<code>` — per the tagging.md convention above).
61
+ //
62
+ // A manifest-level declaration surface (a bundle stating its own tag
63
+ // prefixes IN the manifest — the `tag_prefixes`/`allow_flat_tags` concept
64
+ // `docs/data-model-concepts/tagging.md` already documents but that remains
65
+ // unimplemented) is a SEPARATE, larger change proposed via OpenSpec — this
66
+ // module is deliberately NOT that: it is the smallest mechanism a caller can
67
+ // drive today with a hand-written family list.
68
+ export interface RefTagFamily {
69
+ /** e.g. "srd.ability." or "ability=" — the tag value's leading key, INCLUDING the trailing delimiter. */
70
+ readonly prefix: string;
71
+ /** The row kind the value after the prefix should resolve against. */
72
+ readonly targetKind: string;
73
+ /** `targetKind`'s natural-key field (mirrors `ROW_KIND_NATURAL_KEY[targetKind]` — see header for why it's hand-carried here rather than looked up). */
74
+ readonly naturalKeyField: string;
75
+ /** Bundle that declared this manifest-sourced family; absent for legacy callers. */
76
+ readonly declaringBundleId?: string;
77
+ }
78
+
79
+ function isRecord(value: unknown): value is Record<string, unknown> {
80
+ return typeof value === "object" && value !== null && !Array.isArray(value);
81
+ }
82
+
83
+ /**
84
+ * Does `targetKind`'s natural-key id space contain a row matching `value`,
85
+ * either exactly or as its final `/`-segment (e.g. "wis" matches "srd/wis")?
86
+ * Suffix match, not prefix/substring — deliberately loose about the
87
+ * bundle-namespace prefix so this works across any content bundle's own id
88
+ * scheme, not just "srd/*". Returns the resolved row's FULL id, or
89
+ * `undefined` if nothing matches.
90
+ */
91
+ export type RefTagResolution =
92
+ | { readonly kind: "resolved"; readonly value: string }
93
+ | { readonly kind: "unresolved" }
94
+ | { readonly kind: "ambiguous"; readonly candidates: readonly string[] };
95
+
96
+ export function resolveRefTagValueOutcome(
97
+ manifest: Record<string, unknown>,
98
+ targetKind: string,
99
+ naturalKeyField: string,
100
+ value: string,
101
+ fullTag = value,
102
+ visibleBundleIds?: ReadonlySet<string>,
103
+ ): RefTagResolution {
104
+ const table = manifest[targetKind];
105
+ if (!Array.isArray(table)) return { kind: "unresolved" };
106
+ const ids = table
107
+ .filter(isRecord)
108
+ .filter(
109
+ (row) =>
110
+ visibleBundleIds === undefined ||
111
+ (typeof row.bundle_id === "string" && visibleBundleIds.has(row.bundle_id)),
112
+ )
113
+ .map((row) => row[naturalKeyField])
114
+ .filter((id): id is string => typeof id === "string");
115
+ for (const candidates of [
116
+ new Set(ids.filter((id) => id === fullTag)),
117
+ new Set(ids.filter((id) => id === value)),
118
+ new Set(ids.filter((id) => id.slice(id.lastIndexOf("/") + 1) === value)),
119
+ ]) {
120
+ if (candidates.size === 0) continue;
121
+ const sorted = [...candidates].sort();
122
+ if (sorted.length === 1) {
123
+ const [resolved] = sorted;
124
+ if (resolved !== undefined) return { kind: "resolved", value: resolved };
125
+ }
126
+ return { kind: "ambiguous", candidates: sorted };
127
+ }
128
+ return { kind: "unresolved" };
129
+ }
130
+
131
+ /** Compatibility helper for callers that only need a safe outbound target. */
132
+ export function resolveRefTagValue(
133
+ manifest: Record<string, unknown>,
134
+ targetKind: string,
135
+ naturalKeyField: string,
136
+ value: string,
137
+ fullTag = value,
138
+ visibleBundleIds?: ReadonlySet<string>,
139
+ ): string | undefined {
140
+ const outcome = resolveRefTagValueOutcome(
141
+ manifest,
142
+ targetKind,
143
+ naturalKeyField,
144
+ value,
145
+ fullTag,
146
+ visibleBundleIds,
147
+ );
148
+ return outcome.kind === "resolved" ? outcome.value : undefined;
149
+ }
@@ -0,0 +1,48 @@
1
+ import {
2
+ dsl_reference_json,
3
+ manifest_schema_json,
4
+ observation_placeholder_tokens_json,
5
+ } from "@spellkave/validate-wasm";
6
+
7
+ export interface DslArgReference {
8
+ name: string;
9
+ shape: string;
10
+ }
11
+
12
+ export interface DslOperatorReference {
13
+ operator: string;
14
+ expression_kind: string;
15
+ returns: string;
16
+ args: DslArgReference[];
17
+ notes: string[];
18
+ examples: string[];
19
+ /** `"expression"` = parseable DSL text; `"frame_write"` = structured consequence row (example is conceptual, not DSL). */
20
+ authoring: "expression" | "frame_write";
21
+ }
22
+
23
+ export interface DslReference {
24
+ operators: DslOperatorReference[];
25
+ }
26
+
27
+ export type ManifestSchema = Record<string, unknown>;
28
+
29
+ export function describeManifestSchema(): ManifestSchema {
30
+ return JSON.parse(manifest_schema_json()) as ManifestSchema;
31
+ }
32
+
33
+ export function describeDsl(): DslReference {
34
+ return JSON.parse(dsl_reference_json()) as DslReference;
35
+ }
36
+
37
+ /**
38
+ * #1968 B-9 (canon-warden Phase-2 condition 3): the FROZEN closed set of
39
+ * presentation-layer placeholder tokens an authored `outcome_template.description`
40
+ * may reference, single-sourced from `spellkave_validate::OBSERVATION_PLACEHOLDER_TOKENS`
41
+ * (Rust). Callers that resolve/interpolate observation prose (the companion
42
+ * agent's `observation.ts`) import THIS function rather than hand-mirroring
43
+ * the list — see the wasm export's own doc comment for why the set does not
44
+ * grow by convention.
45
+ */
46
+ export function observationPlaceholderTokens(): string[] {
47
+ return JSON.parse(observation_placeholder_tokens_json()) as string[];
48
+ }
@@ -0,0 +1,105 @@
1
+
2
+ import { ROW_KIND_NATURAL_KEY } from "./row-kinds";
3
+
4
+ export const SURROGATE_ID_FIELDS: Readonly<Record<string, { camel: string; snake: string }>> = {
5
+ entities: { camel: "entityId", snake: "entity_id" },
6
+ actors: { camel: "actorId", snake: "actor_id" },
7
+ };
8
+
9
+ /** A row's identity descriptor — see this module's header for which kinds get which form. */
10
+ export type RowIdentity =
11
+ | { form: "surrogate"; kind: string; id: number }
12
+ | { form: "natural-key"; kind: string; key: string };
13
+
14
+ function knownKinds(): string[] {
15
+ return [
16
+ ...new Set([...Object.keys(SURROGATE_ID_FIELDS), ...Object.keys(ROW_KIND_NATURAL_KEY)]),
17
+ ].sort();
18
+ }
19
+
20
+ /**
21
+ * Derive `row`'s identity descriptor for row kind `kind`.
22
+ *
23
+ * `entities`/`actors`: `row` MUST be a LIVE row (a query result carrying the
24
+ * numeric surrogate id — camelCase `entityId`/`actorId`, matching the
25
+ * SpacetimeDB SDK binding convention, or snake_case `entity_id`/`actor_id`
26
+ * for a raw/manifest-shaped stand-in) — a bare authoring-time manifest row
27
+ * (only `entity_key`, no numeric id yet) throws, naming the missing field.
28
+ *
29
+ * Every other kind: `row` is keyed by its `ROW_KIND_NATURAL_KEY` column.
30
+ *
31
+ * An unrecognized `kind` throws, naming every known kind (surrogate + natural-
32
+ * key) — the wrong-usage guard this helper exists to provide.
33
+ */
34
+ export function identityOf(kind: string, row: Record<string, unknown>): RowIdentity {
35
+ const surrogate = SURROGATE_ID_FIELDS[kind];
36
+ if (surrogate !== undefined) {
37
+ const raw = row[surrogate.camel] ?? row[surrogate.snake];
38
+ if (typeof raw !== "number" && typeof raw !== "bigint") {
39
+ throw new Error(
40
+ `identityOf: surrogate kind '${kind}' row has no numeric '${surrogate.camel}'/'${surrogate.snake}' ` +
41
+ "field — pass a LIVE row (a query result), not a bare manifest row (which carries only the " +
42
+ `authoring-time '${ROW_KIND_NATURAL_KEY[kind]}' natural key, not yet a live surrogate id).`,
43
+ );
44
+ }
45
+ return { form: "surrogate", kind, id: Number(raw) };
46
+ }
47
+ const naturalKeyField = ROW_KIND_NATURAL_KEY[kind];
48
+ if (naturalKeyField === undefined) {
49
+ throw new Error(
50
+ `identityOf: unknown row kind '${kind}' — not a surrogate kind (${Object.keys(
51
+ SURROGATE_ID_FIELDS,
52
+ ).join(
53
+ ", ",
54
+ )}) and not registered in ROW_KIND_NATURAL_KEY. Known kinds: ${knownKinds().join(", ")}.`,
55
+ );
56
+ }
57
+ const rawKey = row[naturalKeyField];
58
+ if (typeof rawKey !== "string" || rawKey.length === 0) {
59
+ throw new Error(
60
+ `identityOf: row of kind '${kind}' has no non-empty '${naturalKeyField}' natural-key field — the ` +
61
+ `offending row: ${JSON.stringify(row)}.`,
62
+ );
63
+ }
64
+ return { form: "natural-key", kind, key: rawKey };
65
+ }
66
+
67
+ /**
68
+ * Assert `kind`'s identity held across `before` -> `after` (e.g. a re-author,
69
+ * re-apply, or apply-then-act cycle). Throws with a descriptive message on
70
+ * mismatch; returns nothing on success ("no news is good news", matching this
71
+ * package's other assert* helpers, e.g. `spell.ts`'s
72
+ * `assertSpellCatalogBinding`).
73
+ *
74
+ * Surrogate kinds (`entities`/`actors`): the numeric id must be IDENTICAL —
75
+ * this is the "never deleted and recreated" proof.
76
+ * Natural-key kinds (everything else): the SAME key must be present in both —
77
+ * every OTHER field is free to differ (that is what an upsert-by-key IS).
78
+ */
79
+ export function assertIdentityStable(
80
+ before: Record<string, unknown>,
81
+ after: Record<string, unknown>,
82
+ kind: string,
83
+ ): void {
84
+ const beforeId = identityOf(kind, before);
85
+ const afterId = identityOf(kind, after);
86
+ if (beforeId.form === "surrogate") {
87
+ const afterDescribed = afterId.form === "surrogate" ? String(afterId.id) : "(natural-key form)";
88
+ if (afterId.form !== "surrogate" || afterId.id !== beforeId.id) {
89
+ throw new Error(
90
+ `assertIdentityStable: surrogate kind '${kind}' identity changed — before id ${beforeId.id}, after ` +
91
+ `${afterDescribed}. A re-authored/re-applied row of a surrogate kind must keep the SAME live id, ` +
92
+ "never delete+recreate under the same authored key.",
93
+ );
94
+ }
95
+ return;
96
+ }
97
+ const afterDescribed = afterId.form === "natural-key" ? `'${afterId.key}'` : "(surrogate form)";
98
+ if (afterId.form !== "natural-key" || afterId.key !== beforeId.key) {
99
+ throw new Error(
100
+ `assertIdentityStable: natural-key kind '${kind}' identity changed — before key '${beforeId.key}', ` +
101
+ `after ${afterDescribed}. Field changes are fine (that is what upsert-by-key IS) — the KEY itself ` +
102
+ "must stay the same row identity.",
103
+ );
104
+ }
105
+ }
@@ -0,0 +1,35 @@
1
+ // Mutable only while a runtime-specific wasm binding initializes. Consumers
2
+ // receive the Rust-owned, frozen Node records or the browser's initialized
3
+ // web-wasm records through these accessors.
4
+ let natural: Readonly<Record<string, string>> = {};
5
+ let composite: Readonly<Record<string, readonly string[]>> = {};
6
+
7
+ export function setRowKindMaps(
8
+ nextNatural: Readonly<Record<string, string>>,
9
+ nextComposite: Readonly<Record<string, readonly string[]>>,
10
+ ): void {
11
+ natural = nextNatural;
12
+ composite = nextComposite;
13
+ }
14
+
15
+ export function rowKindNaturalKey(): Readonly<Record<string, string>> {
16
+ return natural;
17
+ }
18
+
19
+ export function rowKindCompositeKey(): Readonly<Record<string, readonly string[]>> {
20
+ return composite;
21
+ }
22
+
23
+ // sk-jay0.7.174.15: row kind (or "*") -> fields `r_export_manifest` does not
24
+ // round-trip. Rust-owned (`spellkave_schema::export_round_trip`), set by the
25
+ // same wasm initializers as the row-kind maps above.
26
+ let notRoundTripped: Readonly<Record<string, readonly string[]>> = {};
27
+
28
+ export function setExportNotRoundTripped(next: Readonly<Record<string, readonly string[]>>): void {
29
+ notRoundTripped = next;
30
+ }
31
+
32
+ /** Fields a live export may differ in from the authored `kind` row without drift. */
33
+ export function exportNotRoundTrippedFields(kind: string): readonly string[] {
34
+ return [...(notRoundTripped["*"] ?? []), ...(notRoundTripped[kind] ?? [])];
35
+ }
@@ -0,0 +1,93 @@
1
+ // Manifest row-kind -> single-column natural-key field.
2
+ //
3
+ // #1968 R7 (ADR-0087) slice 2: this table is now Rust-owned
4
+ // (`crates/spellkave-authoring/src/row_kinds.rs`'s `ROW_KIND_NATURAL_KEY`,
5
+ // the single source of truth) — this file is a thin wrapper that reads it
6
+ // through the vendored `spellkave-authoring-wasm` nodejs-target package
7
+ // (mirrors `manifest.ts`'s direct, synchronous import of
8
+ // `spellkave-validate-wasm`; the nodejs wasm-pack target loads its wasm
9
+ // module synchronously at `require` time, so a top-level `const` here is
10
+ // safe exactly the same way `render_manifest_json_to_toml` already is).
11
+ // Browser callers receive the same Rust-owned maps through the conditional
12
+ // `@spellkave/world-author/tooling` export. `tooling.browser.ts` initializes
13
+ // the web WASM and these maps in `loadBrowserAuthorTooling`; scoped instance
14
+ // projection imports that port so browser builds never load this Node shim.
15
+ //
16
+ // Two independent consumers share this SINGLE source of truth rather than
17
+ // each carrying its own copy:
18
+ // 1. shared tool runtime's workspace idempotency merge (upsert-by-authored-key
19
+ // re-run proofs, `authoring-verbs.ts`'s `commitOrReport`/`clearRowsByKey`
20
+ // callers).
21
+ // 2. this package's `AuthorTarget`-facing local-folder driver (`author-
22
+ // target.ts` in shared tool runtime) — resolving/listing rows against a TOML
23
+ // folder needs the SAME natural-key knowledge the workspace merge already
24
+ // has, generically, for ANY row kind present in that folder.
25
+ //
26
+ // world-author has no dependency on shared tool runtime (see that package's own
27
+ // authoring-harness.ts header) — shared tool runtime depends on world-author, so
28
+ // this is the correct direction: the generic manifest-shape fact lives here,
29
+ // shared tool runtime imports it.
30
+ //
31
+ // The full provenance/verification history (`commit.rs`'s authored-key
32
+ // branches, `spatial_state_definitions`, `actor_identities`, …) now lives on
33
+ // the Rust `ROW_KIND_NATURAL_KEY` const's own doc comment — see
34
+ // `crates/spellkave-authoring/src/row_kinds.rs`, not duplicated here.
35
+ import {
36
+ export_not_round_tripped_json,
37
+ row_kind_composite_key_json,
38
+ row_kind_natural_key_json,
39
+ row_kind_storage_key_json,
40
+ } from "@spellkave/authoring-wasm";
41
+ import { setExportNotRoundTripped, setRowKindMaps } from "./row-kinds-data";
42
+
43
+ export const ROW_KIND_NATURAL_KEY: Readonly<Record<string, string>> = Object.freeze(
44
+ JSON.parse(row_kind_natural_key_json()) as Record<string, string>,
45
+ );
46
+
47
+ /**
48
+ * Manifest row-kind -> ordered composite-key fields (srd-cc battle-test
49
+ * ledger finding #9, 2026-07-26): the `*_tag` satellite kinds, each
50
+ * `{<parent_field>, "tag"}` — absent from `ROW_KIND_NATURAL_KEY` above
51
+ * because a bare tag value is not a row's identity (many tag rows share the
52
+ * same parent). Same Rust-owned single-source-of-truth discipline as
53
+ * `ROW_KIND_NATURAL_KEY` — see `crates/spellkave-authoring/src/row_kinds.rs`'s
54
+ * `ROW_KIND_COMPOSITE_KEY` doc comment for the full provenance note and why
55
+ * only the uniform `*_tag` kinds are covered here (other satellite/junction
56
+ * kinds are non-uniform and deliberately left out).
57
+ */
58
+ export const ROW_KIND_COMPOSITE_KEY: Readonly<Record<string, readonly string[]>> = Object.freeze(
59
+ Object.fromEntries(
60
+ Object.entries(JSON.parse(row_kind_composite_key_json()) as Record<string, string[]>).map(
61
+ ([kind, fields]) => [kind, Object.freeze(fields)],
62
+ ),
63
+ ),
64
+ );
65
+
66
+ /**
67
+ * Manifest row-kind -> ordered storage-key fields (ADR-0146,
68
+ * sk-jay0.7.174.30): the wider set of kinds whose server-side identity/
69
+ * upsert key is more than the `*_tag` uniform pair — junction/satellite rows
70
+ * (`entity_definition_initial_*`, `actor_capabilities`, `object_state`, the
71
+ * twelve `*_tag` kinds plus `entity_tag`, …) each verified field-by-field
72
+ * against their own manifest row struct and server upsert. Same Rust-owned
73
+ * single-source-of-truth discipline as `ROW_KIND_NATURAL_KEY`/
74
+ * `ROW_KIND_COMPOSITE_KEY` above — see
75
+ * `crates/spellkave-schema/src/row_identity.rs`'s `ROW_KIND_STORAGE_KEY` doc
76
+ * comment for the full per-kind provenance. A kind present here and in
77
+ * `ROW_KIND_COMPOSITE_KEY` (the `*_tag` kinds) carries the WIDER key here —
78
+ * `ROW_KIND_COMPOSITE_KEY` stays the narrower `(parent, "tag")` shape only
79
+ * `diff-manifest-core.ts` still reads (see `row_identity.rs`'s own doc
80
+ * comment for why that consumer keeps the narrower shape).
81
+ */
82
+ export const ROW_KIND_STORAGE_KEY: Readonly<Record<string, readonly string[]>> = Object.freeze(
83
+ Object.fromEntries(
84
+ Object.entries(JSON.parse(row_kind_storage_key_json()) as Record<string, string[]>).map(
85
+ ([kind, fields]) => [kind, Object.freeze(fields)],
86
+ ),
87
+ ),
88
+ );
89
+
90
+ setRowKindMaps(ROW_KIND_NATURAL_KEY, ROW_KIND_COMPOSITE_KEY);
91
+ setExportNotRoundTripped(
92
+ Object.freeze(JSON.parse(export_not_round_tripped_json()) as Record<string, string[]>),
93
+ );
@@ -0,0 +1,180 @@
1
+ import type { DocEvidenceState } from "./test/doc-evidence/protocol";
2
+
3
+ /** Captured artifacts supplied by feature owners, using existing evidence states. */
4
+ export interface ScenarioCapture {
5
+ scenario: string;
6
+ test: string;
7
+ state: DocEvidenceState;
8
+ implementing_revision: string;
9
+ fixture_revision: string;
10
+ source_revision: string;
11
+ surface: string;
12
+ surface_revision: string;
13
+ tested_at: string;
14
+ assertions: readonly string[];
15
+ interactions: readonly {
16
+ argv?: readonly string[];
17
+ /** Exact captured MCP frame; data only, never dispatched by projection. */
18
+ mcp_request?: { method: string; params?: unknown };
19
+ stdout: string;
20
+ stderr: string;
21
+ exit_code: number;
22
+ }[];
23
+ evidence_doc: string;
24
+ }
25
+
26
+ /** Redaction happens before projection; aliases retain the synthetic proof's meaning. */
27
+ export function sanitizeScenarioText(
28
+ text: string,
29
+ aliases: Readonly<Record<string, string>>,
30
+ ): string {
31
+ let sanitized = text;
32
+ for (const [privateValue, alias] of Object.entries(aliases).sort(
33
+ (a, b) => b[0].length - a[0].length,
34
+ )) {
35
+ if (privateValue.length === 0 || !/^<[a-z0-9-]+>$/i.test(alias))
36
+ throw new Error("Invalid fixture alias");
37
+ sanitized = sanitized.replaceAll(privateValue, alias);
38
+ }
39
+ // Parse serialized captures before matching strings: escaped quotes/newlines
40
+ // must not turn a complete JSON header value into a partial redaction.
41
+ if (/^\s*[[{]/.test(sanitized)) {
42
+ try {
43
+ const parsed: unknown = JSON.parse(sanitized);
44
+ const redact = (value: unknown, key = ""): unknown => {
45
+ if (
46
+ /^(?:authorization|proxy-authorization|password|access_token|api_key|token|secret)$/i.test(
47
+ key,
48
+ )
49
+ )
50
+ return "<redacted>";
51
+ if (Array.isArray(value)) {
52
+ if (key === "argv") return sanitizeScenarioArgv(value.map(String), aliases);
53
+ return value.map((entry) => redact(entry));
54
+ }
55
+ if (value && typeof value === "object")
56
+ return Object.fromEntries(
57
+ Object.entries(value).map(([name, entry]) => [name, redact(entry, name)]),
58
+ );
59
+ return typeof value === "string" ? sanitizeScenarioText(value, aliases) : value;
60
+ };
61
+ const cleaned = redact(parsed);
62
+ if (JSON.stringify(cleaned) !== JSON.stringify(parsed)) return JSON.stringify(cleaned);
63
+ return sanitized;
64
+ } catch {
65
+ /* Ordinary prose/code is not necessarily JSON. */
66
+ }
67
+ }
68
+ return sanitized
69
+ .replace(/(\b(?:proxy-)?authorization\s*[:=]\s*)[^\r\n]+/gi, "$1<redacted>")
70
+ .replace(/((?:password|access_token|api_key)["']?\s*[:=]\s*["']?)[^\s"',}]+/gi, "$1<redacted>")
71
+ .replace(/\/(?:Users|home|private|tmp|var)\/[^\s"']+/g, "<private-path>");
72
+ }
73
+
74
+ export function sanitizeScenarioArgv(
75
+ argv: readonly string[],
76
+ aliases: Readonly<Record<string, string>>,
77
+ ): string[] {
78
+ let credentialValue = false;
79
+ return argv.map((arg) => {
80
+ if (credentialValue) {
81
+ credentialValue = false;
82
+ return "<redacted>";
83
+ }
84
+ if (
85
+ /^--(?:authorization|proxy-authorization|password|access-token|access_token|api-key|api_key|token|secret)$/i.test(
86
+ arg,
87
+ )
88
+ ) {
89
+ credentialValue = true;
90
+ return arg;
91
+ }
92
+ if (
93
+ /^--(?:authorization|proxy-authorization|password|access-token|access_token|api-key|api_key|token|secret)=/i.test(
94
+ arg,
95
+ )
96
+ )
97
+ return `${arg.split("=", 1)[0]}=<redacted>`;
98
+ return sanitizeScenarioText(arg, aliases);
99
+ });
100
+ }
101
+
102
+ /** Fail closed: stale/failed/unexecuted captures cannot produce verified commands. */
103
+ export function projectScenarioGuide(
104
+ capture: ScenarioCapture,
105
+ current: { source_revision: string; surface: string; surface_revision: string },
106
+ ): { status: "verified" | "unverified"; reasons: string[]; body: string } {
107
+ const reasons: string[] = [];
108
+ const scenario =
109
+ typeof capture.scenario === "string" &&
110
+ /^[A-Za-z][A-Za-z0-9]*(?:[-_.][A-Za-z0-9]+)*$/.test(capture.scenario) &&
111
+ capture.scenario.length <= 80
112
+ ? capture.scenario
113
+ : "Unverified scenario";
114
+ if (scenario === "Unverified scenario") reasons.push("invalid public scenario ID");
115
+ if (capture.state !== "proven") reasons.push("capture was not proven");
116
+ if (
117
+ !capture.test ||
118
+ !capture.implementing_revision ||
119
+ !capture.fixture_revision ||
120
+ !Number.isFinite(Date.parse(capture.tested_at))
121
+ )
122
+ reasons.push("incomplete provenance");
123
+ if (!capture.source_revision || capture.source_revision !== current.source_revision)
124
+ reasons.push("source changed");
125
+ if (
126
+ capture.surface !== current.surface ||
127
+ !capture.surface_revision ||
128
+ capture.surface_revision === "unknown" ||
129
+ current.surface_revision === "unknown" ||
130
+ capture.surface_revision !== current.surface_revision
131
+ )
132
+ reasons.push("surface revision unavailable or stale");
133
+ if (capture.assertions.length === 0 || capture.interactions.length === 0)
134
+ reasons.push("missing captured interaction or independent assertions");
135
+ if (!/^evidence\/[a-z0-9-]+$/.test(capture.evidence_doc))
136
+ reasons.push("missing packaged evidence ID");
137
+ if (
138
+ capture.interactions.some(
139
+ (step) =>
140
+ (!Array.isArray(step.argv) || step.argv.length === 0) &&
141
+ (!step.mcp_request ||
142
+ typeof step.mcp_request.method !== "string" ||
143
+ !step.mcp_request.method.trim()),
144
+ )
145
+ )
146
+ reasons.push("missing captured operation");
147
+ if (
148
+ capture.interactions.some((step) => {
149
+ const transcript = JSON.stringify(step);
150
+ return sanitizeScenarioText(transcript, {}) !== transcript;
151
+ })
152
+ )
153
+ reasons.push("transcript requires redaction");
154
+ const { interactions: _interactions, ...provenance } = capture;
155
+ const serializedProvenance = JSON.stringify(provenance);
156
+ if (sanitizeScenarioText(serializedProvenance, {}) !== serializedProvenance)
157
+ reasons.push("provenance or assertions require redaction");
158
+ if (reasons.length)
159
+ return {
160
+ status: "unverified",
161
+ reasons,
162
+ body: `${scenario}: unverified (${reasons.join("; ")}).`,
163
+ };
164
+ // Never hand-copy argv into a second source. JSON preserves argument boundaries.
165
+ const commands = capture.interactions
166
+ .slice(0, 3)
167
+ .map(
168
+ (step) =>
169
+ `\`\`\`json\n${JSON.stringify({ ...(step.mcp_request ? { mcp_request: step.mcp_request } : { argv: step.argv }), exit_code: step.exit_code })}\n\`\`\``,
170
+ )
171
+ .join("\n\n");
172
+ const evidenceRoute = capture.interactions.some((step) => step.mcp_request)
173
+ ? `spellkave_docs with ${JSON.stringify({ doc: capture.evidence_doc, full: true })}`
174
+ : `sk docs ${capture.evidence_doc} --full`;
175
+ return {
176
+ status: "verified",
177
+ reasons,
178
+ body: `${capture.scenario} — verified on ${capture.surface} ${capture.surface_revision}.\n\nTest: ${capture.test}; implementation: ${capture.implementing_revision}; fixture: ${capture.fixture_revision}; source: ${capture.source_revision}; captured: ${capture.tested_at}.\n\n${commands}\n\nFull sanitized interactions and assertions: \`${evidenceRoute}\`.`,
179
+ };
180
+ }