@descix/platform-api 1.0.1

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.
@@ -0,0 +1,1402 @@
1
+ /**
2
+ * Coordination-fabric vocabulary — THE single owner, in the shared package.
3
+ *
4
+ * The BEAST coordination fabric is the app-records collection `egpt-frqtl/coordination`. Every rule
5
+ * that keeps it coherent is server-side, on the `fabric_*` verbs. This module is the vocabulary
6
+ * those rules are written against.
7
+ *
8
+ * WHY IT LIVES IN @descix/platform-api AND NOT IN THE CLOUD MICROSERVICE. There are two consumers
9
+ * in two repositories: DeSciX_Cloud's `fabricStore.js` (which enforces the vocabulary) and
10
+ * DeSciX_Core's `mcp-tools/nativeTools.js` (which PUBLISHES it as tool-schema enums and prose). A
11
+ * copy in each is the mirror-drift bug class — the enum a caller is SHOWN and the enum the server
12
+ * ACCEPTS would disagree silently, and the caller would be refused against a contract it was never
13
+ * given. One export, two importers, and `fabric-vocabulary-conformance.test.js` fails CI if a tool
14
+ * schema's enum stops deep-equalling its source here.
15
+ *
16
+ * PURE DATA + PURE PREDICATES. No I/O, no imports, no dependencies. A vocabulary that needed
17
+ * infrastructure to answer "is this a legal status" could not be asserted in CI, and this module is
18
+ * imported by a package whose other entry points pull in Firestore.
19
+ *
20
+ * The `fabric_vocabulary` verb returns this module's contents over the wire, so a CLIENT (the
21
+ * unkamon-beast plugin's `hooks/lib/vocab.py`) can GENERATE its copy instead of hand-keeping one.
22
+ * A hand-kept client mirror was measured writing four statuses the server refuses and defining a
23
+ * `liveness` model the server did not know (2026-08-24).
24
+ */
25
+
26
+ // ── The fabric's address ─────────────────────────────────────────────────────────────────────
27
+ //
28
+ // A record addressed to a seat (`to_agent`) on any OTHER app/kb reaches no sweeper: every sweep
29
+ // reads THIS collection and the store answers success:true either way (measured twice on
30
+ // 2026-08-23 — a CEO ruling addressed to VISION sat unread in unk-beast/Org for three hours). The
31
+ // fabric verbs do not take app_id/kb_id from the caller for exactly that reason.
32
+ export const FABRIC_APP = 'egpt-frqtl';
33
+ export const FABRIC_KB = 'coordination';
34
+
35
+ // THERE IS NO ORG-MASTER LABEL CONSTANT HERE, AND THAT IS THE POINT. A seat label names a HOLDER,
36
+ // and a holder changes; a literal in a shipped package is a snapshot of who held the org seat on the
37
+ // day the package was cut, and it does not update when the holder does. The identical class as
38
+ // `CEO`/`master` below: a value that reads authoritative, is wrong, and cannot detect that it is
39
+ // wrong. The seat's CURRENT holder has one owner — the BEAST seat surface — so every refusal that
40
+ // needs to say "address the org master" says how to LOOK IT UP (`beast_seat_read {seat_id:'org'}`)
41
+ // and names no label.
42
+
43
+ // ── Heartbeat statuses ───────────────────────────────────────────────────────────────────────
44
+ //
45
+ // WRITE-STRICT, READ-TOLERANT. These are two different questions and they get two different sets.
46
+ //
47
+ // The WRITE set is a CLOSED ENUM. It is deliberately NARROWER than what is live on the fabric: a
48
+ // census of 33 heartbeats found ELEVEN distinct values, and an unbounded vocabulary is why "is this
49
+ // seat alive" has no computable answer. `active`, `alive`, `idle` and `in-progress` all mean
50
+ // `working`; `complete` and `superseded` mean `done`. Collapsing them is the point.
51
+ //
52
+ // A heartbeat must never carry a DELIVERY status. `unread` collides with the inbox sweep (which
53
+ // carries no type filter, by design) — `heartbeat-RELAY-aeea43e3` sat in VISION's inbox as unread
54
+ // mail for 35 hours and RELAY is dead, so nothing will ever clear it. `broadcast` is worse:
55
+ // doctrine forbids flipping a broadcast and a heartbeat re-puts itself every beat, so it is
56
+ // permanent self-refreshing pollution in every inbox on the fabric (measured 2026-08-22T14:16Z).
57
+ // Both are refused BY NAME, citing the collision.
58
+ export const WORKING_STATUSES = Object.freeze(['working', 'blocked', 'handing-back']);
59
+
60
+ // DECLARED stops. A declaration is not a death (CEO-D-2026-08-18-SEATS-STAY-REACHABLE): a liveness
61
+ // check must report `declared-stop`, not `stale`, when it sees one of these.
62
+ export const DECLARED_STOPS = Object.freeze(['quiesced', 'good-night', 'done']);
63
+
64
+ /** The closed enum `fabric_beat` accepts. Nothing else may be WRITTEN. */
65
+ export const BEAT_STATUSES = Object.freeze([...WORKING_STATUSES, ...DECLARED_STOPS]);
66
+
67
+ /**
68
+ * The READ set. `fabric_liveness` must interpret records written before this contract existed — 33
69
+ * of them are live right now, none of them ours to rewrite. A reader that treated a legacy `active`
70
+ * beat as uninterpretable would report a healthy seat as defective, which is the cry-wolf failure
71
+ * that trains a master to ignore the instrument. So legacy values are MAPPED on read and never
72
+ * accepted on write.
73
+ */
74
+ export const LEGACY_WORKING_STATUSES = Object.freeze(['active', 'alive', 'idle', 'in-progress']);
75
+ export const LEGACY_STOP_STATUSES = Object.freeze(['complete', 'superseded']);
76
+
77
+ /** Every status a READER may encounter and classify. Never use this to validate a write. */
78
+ export const READABLE_STATUSES = Object.freeze([
79
+ ...BEAT_STATUSES, ...LEGACY_WORKING_STATUSES, ...LEGACY_STOP_STATUSES,
80
+ ]);
81
+
82
+ // The literals the platform's own writers use, named so no consumer retypes one.
83
+ export const BEAT_WORKING = 'working';
84
+ export const BEAT_SESSION_END = 'good-night';
85
+
86
+ /** The wake block. A working seat's continuity is exactly as checkable a fact as a resting seat's,
87
+ * and exempting it is how a seat goes dark while looking busy. WHICH WRITER must carry one is
88
+ * WAKE_REQUIRED_LIVENESS, declared below the liveness values it is expressed in. */
89
+ export const WAKE_FIELDS = Object.freeze(['mechanism', 'survives_death', 'next_fire_at']);
90
+
91
+ /** The wake block FLATTENED onto the record, as `fabric_beat` writes it: the store's metadata is
92
+ * flat string/number/boolean/string[], so a nested object is neither filterable nor projectable
93
+ * and a master could not sweep for overdue wakes.
94
+ *
95
+ * DERIVED from WAKE_FIELDS rather than listed beside it. This mapping was being re-derived BY HAND
96
+ * in three places in the executing store (the beat's write, the liveness empty-record shape, the
97
+ * liveness diagnostic block), and making `wake` conditional needs a FOURTH copy for its preserve
98
+ * set — four hand copies of one mapping is how a field gets renamed in three of them. */
99
+ export const WAKE_PARAM_NAME = 'wake';
100
+ export const WAKE_RECORD_FIELD_PREFIX = `${WAKE_PARAM_NAME}_`;
101
+ export const WAKE_RECORD_FIELD_NAMES = Object.freeze(
102
+ WAKE_FIELDS.map((f) => `${WAKE_RECORD_FIELD_PREFIX}${f}`));
103
+
104
+ /**
105
+ * THE WAKE FACT OWNS A NAMESPACE, not a list of field names — `wake` itself and every `wake_*` key,
106
+ * whether or not any beat writes one.
107
+ *
108
+ * WHY A NAMESPACE AND NOT A LIST. The hole this closes is a caller planting a SHADOW copy of the
109
+ * wake fact through the `extra` bag under a name the record does not own. `extra.wake_mechanism` is
110
+ * already refused, but `extra.wake` and `extra.wake_block` are accepted with no guard, and that
111
+ * asymmetry is how three live heartbeats acquired null `wake` / `wake_block` fossils.
112
+ *
113
+ * `wake_block` is not a field this vocabulary has ever declared, so NO derivation from WAKE_FIELDS
114
+ * reaches it. A list would have to HAND-TYPE it — and a hand-typed list is a second derivation of
115
+ * "what belongs to the wake fact", free to drift from WAKE_FIELDS, which is the mirror-drift bug
116
+ * class this module exists to close. The namespace rule reaches every such name at once, including
117
+ * names nobody has invented yet, and a fourth entry added to WAKE_FIELDS extends the refusal with
118
+ * NO edit to any guard, because its record name is `wake_<field>` and the prefix already owns it.
119
+ *
120
+ * It is expressed as a PREDICATE rather than an array because the set is infinite. `describe` is
121
+ * carried beside it so a refusal can tell the caller what it collided with, in the owner's words
122
+ * rather than the guard's.
123
+ */
124
+ export const WAKE_NAMESPACE = Object.freeze({
125
+ owns: (key) => typeof key === 'string'
126
+ && (key === WAKE_PARAM_NAME || key.startsWith(WAKE_RECORD_FIELD_PREFIX)),
127
+ describe: `the wake fact's namespace — '${WAKE_PARAM_NAME}' itself and every `
128
+ + `'${WAKE_RECORD_FIELD_PREFIX}*' key, whether or not this beat writes one`,
129
+ });
130
+
131
+ /** Which flat record field holds this wake field. Derived, so a fourth wake field added to
132
+ * WAKE_FIELDS gets its record field for free, and a name that is not a wake field reads null
133
+ * rather than composing a plausible-looking field that no record carries. */
134
+ export function wakeRecordFieldFor(wakeField) {
135
+ return WAKE_FIELDS.includes(wakeField) ? `${WAKE_RECORD_FIELD_PREFIX}${wakeField}` : null;
136
+ }
137
+
138
+ /** The flat bag a beat writes for a wake block, or NULL when there is no wake to write.
139
+ *
140
+ * Null is not an empty bag, and the difference is the whole point: a beat is a WHOLE-STATE write,
141
+ * so a field absent from the outgoing record is CLEARED rather than inherited. A writer exempt
142
+ * from carrying wake must therefore PRESERVE the stored fields explicitly — writing an empty bag
143
+ * would erase the seat's wake chain while returning success, which is the same silent failure in
144
+ * the opposite direction. */
145
+ export function flattenWake(wake) {
146
+ if (!wake || typeof wake !== 'object' || Array.isArray(wake)) return null;
147
+ const out = {};
148
+ for (const f of WAKE_FIELDS) out[wakeRecordFieldFor(f)] = wake[f];
149
+ return out;
150
+ }
151
+
152
+ // ── liveness: WHO wrote this beat ────────────────────────────────────────────────────────────
153
+ //
154
+ // A beat proves something is alive. WHICH thing depends entirely on who wrote it, and the two
155
+ // answers are not interchangeable:
156
+ //
157
+ // model — an AGENT wrote it (a seat or its secretary). Proves the MODEL is alive.
158
+ // process — a HOOK wrote it. Proves the PROCESS is alive and says NOTHING about the model.
159
+ //
160
+ // A hook beating on a dead model is a mask: the process reports health while nobody is home. So
161
+ // this is a REQUIRED, closed-enum parameter of `fabric_beat`, not an optional hint. It cannot be
162
+ // defaulted and it cannot be inherited: a merge-upsert that omitted it would silently keep the
163
+ // PREVIOUS writer's value, so a hook's beat on a seat that last beat as `model` would keep
164
+ // claiming a live model. That inheritance was measured in the client mirror.
165
+ //
166
+ // `liveness` SAYS WHO WROTE LAST, AND THAT IS ALL IT SAYS. It is NOT the model's clock: the two
167
+ // writers share this one key and the hook writes ~15x more often, so a reader that judged the model
168
+ // on it read UNDETERMINED for every correctly-armed seat (measured 2026-08-24T21:37Z). The clocks
169
+ // are BEAT_CLOCK_FIELDS below, and the judgement is judgeModelLiveness().
170
+ export const LIVENESS_MODEL = 'model';
171
+ export const LIVENESS_PROCESS = 'process';
172
+ export const LIVENESS_VALUES = Object.freeze([LIVENESS_MODEL, LIVENESS_PROCESS]);
173
+
174
+ // ── WHICH WRITER MUST CARRY `wake` ───────────────────────────────────────────────────────────
175
+ //
176
+ // ONE OWNER OF THE RULE, consumed by the descriptor that PUBLISHES it (nativeTools.js
177
+ // `fabric_beat`) and by the verb that ENFORCES it (DeSciX_Cloud fabricStore.js). Under
178
+ // CEO-D-2026-08-22-PROTOCOL-TRUTH-IS-THE-MCP-DESCRIPTOR the served descriptor IS the protocol, so
179
+ // a server enforcing one rule while its descriptor states another has two truths and callers build
180
+ // against the wrong one. Both read this constant; neither restates it.
181
+ //
182
+ // A `wake` block answers "what will wake THIS SEAT'S AGENT, does that survive this process dying,
183
+ // and when does it next fire". ONLY THE AGENT CAN ANSWER IT. A hook's beat proves a process is
184
+ // alive and knows nothing about the agent's continuity, so requiring a wake from a hook forces it
185
+ // to invent an answer or not beat at all — and it did not beat: an unconditional requirement left
186
+ // EVERY doorbell in the fleet exiting on its first tick, because the plugin's pulse sends
187
+ // seat_label, session_id, status, liveness and text and no wake (measured 2026-08-27T12:31Z, and
188
+ // re-measured at the served verb before this change). A beat must never fail because something
189
+ // ancillary TO THAT WRITER failed.
190
+ //
191
+ // This is the same law as the beat clocks below: a beat may only assert what its own writer
192
+ // observed. The clocks make it a rule about what a writer may WRITE; this makes it a rule about
193
+ // what a writer may be REQUIRED to write. A process beat carries no wake and the stored wake_*
194
+ // fields are PRESERVED, exactly as its model clock is.
195
+ export const WAKE_REQUIRED_LIVENESS = LIVENESS_MODEL;
196
+
197
+ /** Must a beat of this `liveness` carry a `wake` block? Derived from WAKE_REQUIRED_LIVENESS so no
198
+ * consumer restates the rule. Callers validate `liveness` against its closed enum FIRST, so an
199
+ * unrecognised value never reaches here and is never silently exempted. */
200
+ export function isWakeRequiredFor(liveness) {
201
+ const v = typeof liveness === 'string' ? liveness.trim().toLowerCase() : null;
202
+ return v === WAKE_REQUIRED_LIVENESS;
203
+ }
204
+
205
+ // ── WHICH WRITER OWNS `status` ───────────────────────────────────────────────────────────────
206
+ //
207
+ // ONE OWNER OF THE RULE, consumed by the descriptor that PUBLISHES it (nativeTools.js
208
+ // `fabric_beat`) and by the verb that ENFORCES it (DeSciX_Cloud fabricStore.js), exactly as
209
+ // WAKE_REQUIRED_LIVENESS is. Under CEO-D-2026-08-22-PROTOCOL-TRUTH-IS-THE-MCP-DESCRIPTOR the
210
+ // served descriptor IS the protocol, so a server enforcing one rule while its descriptor states
211
+ // another has two truths and callers build against the wrong one.
212
+ //
213
+ // `status` IS A MODEL-WRITER'S FIELD. It says WHAT THE SEAT IS DOING — working, done, good-night.
214
+ // Only the agent knows that. A hook's beat proves a PROCESS is alive and knows nothing about what
215
+ // the model is doing, so a hook that must supply a status has to invent one, and what it invents
216
+ // is whatever it last read. That is not hypothetical: the doorbell reads the served status at
217
+ // preflight and re-seeds it every tick, so a good-night declared between the read and the next
218
+ // tick is overwritten by a stale carried "working" — the seat says goodnight and the hook says it
219
+ // is still working, in the seat's own voice, on the seat's own record.
220
+ //
221
+ // This is the same law as the beat clocks and the wake block: A BEAT MAY ONLY ASSERT WHAT ITS OWN
222
+ // WRITER OBSERVED. The clocks made it a rule about what a writer may WRITE; the wake block made it
223
+ // a rule about what a writer may be REQUIRED to write; this makes it a rule about what a writer may
224
+ // be PERMITTED to write. A process beat carries no status and the stored status is PRESERVED,
225
+ // exactly as its model clock and its wake chain are.
226
+ export const STATUS_WRITER_LIVENESS = LIVENESS_MODEL;
227
+
228
+ /** Does a beat of this `liveness` OWN the `status` field — i.e. may it write one, and must it?
229
+ * Derived from STATUS_WRITER_LIVENESS so no consumer restates the rule. Callers validate
230
+ * `liveness` against its closed enum FIRST, so an unrecognised value never reaches here and is
231
+ * never silently exempted. */
232
+ export function isStatusWriterFor(liveness) {
233
+ const v = typeof liveness === 'string' ? liveness.trim().toLowerCase() : null;
234
+ return v === STATUS_WRITER_LIVENESS;
235
+ }
236
+
237
+ /**
238
+ * The statuses that EXEMPT a beat from carrying a wake — the TERMINAL set, and it is DECLARED_STOPS
239
+ * itself rather than a list beside it. One owner, consumed by the verb (fabricStore.js::validateWake)
240
+ * AND by the served descriptor, so the rule the server enforces and the rule callers are shown
241
+ * cannot become two truths.
242
+ *
243
+ * WHY A TERMINAL BEAT IS EXEMPT. `wake` answers "what will wake this seat, does it survive this
244
+ * process dying, when does it next fire". A seat that has declared `done`, `good-night` or
245
+ * `quiesced` has by definition nothing schedulable that wakes it, so the rule was demanding a claim
246
+ * that CANNOT be true — and a field a writer cannot honestly supply gets invented or gets the beat
247
+ * skipped. That is the same law the liveness axis already fixed for hooks: a beat may only assert
248
+ * what its own writer observed, so a writer must not be REFUSED for lacking a field it cannot
249
+ * honestly supply.
250
+ *
251
+ * WHAT THIS DELIBERATELY DOES NOT OPEN. A WORKING beat is not terminal and stays REQUIRED to carry
252
+ * a wake — that is the whole point of keying on status rather than relaxing the rule. An exemption
253
+ * that also opened the working case would be a hole wearing an exemption's clothes, and it would
254
+ * undo the fix that stopped seats going dark while looking busy.
255
+ */
256
+ export const WAKE_EXEMPT_STATUSES = DECLARED_STOPS;
257
+
258
+ /**
259
+ * Must a beat with this (liveness, status) pair carry a `wake` block?
260
+ *
261
+ * TWO AXES, ONE ANSWER. Axis 1 is the WRITER (`isWakeRequiredFor`): only an agent can say what will
262
+ * wake a seat, so a hook is exempt. Axis 2 is the STATUS: a seat that has declared a stop has no
263
+ * wake to describe. Both consumers — the store and the published descriptor — call THIS, so neither
264
+ * re-derives either axis.
265
+ *
266
+ * Callers validate `status` against BEAT_STATUSES first, so a legacy or unknown value never reaches
267
+ * here and is never silently exempted.
268
+ */
269
+ export function isWakeRequiredForBeat(liveness, status) {
270
+ if (!isWakeRequiredFor(liveness)) return false;
271
+ const s = typeof status === 'string' ? status.trim().toLowerCase() : null;
272
+ return !WAKE_EXEMPT_STATUSES.some((x) => x.toLowerCase() === s);
273
+ }
274
+
275
+ // ── Delivery statuses: what is WAITING for a seat ────────────────────────────────────────────
276
+ export const STATUS_UNREAD = 'unread';
277
+ export const STATUS_BROADCAST = 'broadcast';
278
+ export const STATUS_READ = 'read';
279
+ export const DELIVERY_STATUSES = Object.freeze([STATUS_UNREAD, STATUS_BROADCAST]);
280
+
281
+ export const ENVELOPE_STATUSES = Object.freeze([
282
+ 'assigned', 'dispatched', 'preallocated', 'unassigned',
283
+ 'recalled-unassigned', 'accepted', 'rejected',
284
+ ]);
285
+
286
+ /** The status `fabric_envelope_put` writes when the caller names none. Named rather than indexed,
287
+ * because `ENVELOPE_STATUSES[0]` is a position and a position is not a meaning. */
288
+ export const ENVELOPE_STATUS_DEFAULT = 'assigned';
289
+
290
+ /**
291
+ * LIFECYCLE STATE THAT SURVIVES A WRITE THAT DOES NOT MENTION IT — the ONE owner of that rule,
292
+ * consumed by `fabric_envelope_put` AND `fabric_contract_put`.
293
+ *
294
+ * WHY THIS EXISTS AS AN OWNER RATHER THAN AS A CORRECT COPY IN EACH VERB. It was derived twice
295
+ * inside a single file and the copies disagreed: `envelopePut` wrote `phase` unconditionally (with
296
+ * a comment explaining that a `replace` clears every field the new record omits), while
297
+ * `contractPut` wrote it only when the caller supplied one — so a `mode:"replace"` on a SIGNED
298
+ * contract that said nothing about phase NULLED the org's own signature, and the receipt then
299
+ * reported the phase it had just deleted. Measured on Cloud@b57bd01:
300
+ * contractPut {phase:null} vs envelopePut {phase:"signed"} on the identical scenario.
301
+ * Correcting the divergent copy would leave two copies to drift again, so both verbs now call
302
+ * `resolvePreservedLifecycle` and neither decides anything itself.
303
+ *
304
+ * `status` is here for the same reason and it is the half nobody had noticed: BOTH verbs
305
+ * initialised `status` to the default and wrote it unconditionally, so a `mode:"patch"` that
306
+ * carried a branch name and said nothing about status silently reset an ACCEPTED assignment to
307
+ * `assigned`. That is the same law — lifecycle state must survive a write that does not mention it
308
+ * — and it was wrong in both copies rather than one, which is precisely what a single owner
309
+ * prevents from recurring.
310
+ */
311
+ export const LIFECYCLE_PRESERVED_FIELDS = Object.freeze(['phase', 'status']);
312
+
313
+ /**
314
+ * Resolve the lifecycle fields for a write, given what is STORED and what the caller REQUESTED.
315
+ *
316
+ * The rule, in one place: a field the caller named takes the caller's value; a field the caller did
317
+ * NOT name keeps the stored value; and only when there is no stored value at all does the default
318
+ * apply. The returned bag is written UNCONDITIONALLY onto the record by both verbs — never
319
+ * conditionally — because a `replace` clears every field the new record omits, so a value carried
320
+ * forward must still be PRESENT on the write that carries it.
321
+ *
322
+ * @param {object|null} prior the stored record, or null when the key is new
323
+ * @param {object} requested { phase, status } as the caller supplied them; undefined/null = not named
324
+ * @param {object} defaults { phase, status } to fall back to when neither stored nor requested
325
+ * @returns {{phase: string, status: string, changed: string[]}}
326
+ */
327
+ export function resolvePreservedLifecycle(prior, requested = {}, defaults = {}) {
328
+ const out = { changed: [] };
329
+ for (const f of LIFECYCLE_PRESERVED_FIELDS) {
330
+ const asked = requested[f] === undefined || requested[f] === null ? null : requested[f];
331
+ const stored = prior && prior[f] !== undefined && prior[f] !== null ? prior[f] : null;
332
+ const value = asked ?? stored ?? defaults[f] ?? null;
333
+ out[f] = value;
334
+ // "changed" is judged against what was STORED, so a re-put of the same value is not a move
335
+ // — a phase_at refreshed by a write that changed nothing reads as a signature event that
336
+ // never happened.
337
+ if (stored !== value) out.changed.push(f);
338
+ }
339
+ return out;
340
+ }
341
+
342
+ /**
343
+ * The envelope's caller-writable payload fields — ONE owner, consumed by the schema and the writer.
344
+ *
345
+ * WHY THE LAST THREE ARE HERE AND NOT IN A PROSE BODY (CEO-D-2026-08-24-ENVELOPES-NAME-KBS-TO-
346
+ * CONSULT-AND-MAINTAIN). An envelope that names the KBs a seat must consult and the KBs it must
347
+ * maintain, and that carries the ruling it was dispatched under VERBATIM, only works if those are
348
+ * FIELDS the server owns. Buried in `text` they are prose: nothing can query "which seats maintain
349
+ * this KB", nothing can check an envelope carries its ruling, and a paraphrase of a ruling acquires
350
+ * the CEO's authority without his words. As fields they are addressable, and `rulings` holds the
351
+ * verbatim text so the vivid clause cannot travel without the ruling behind it.
352
+ *
353
+ * `workstream_id`, `to_agent` and `mode` are NOT here: the first is the KEY's subject, the second
354
+ * is the address (written to both `to_agent` and `seat_label`), and the third is the write mode.
355
+ * All three are owned by the verb itself, the same way `seat_label`/`mode`/`extra` are owned by
356
+ * `fabric_seat_state_put`.
357
+ */
358
+ export const ENVELOPE_FIELDS = Object.freeze([
359
+ 'text', 'branch', 'initiative_id', 'kbs_consult', 'kbs_maintain', 'rulings', 'status',
360
+ ]);
361
+
362
+ /**
363
+ * The REQUIRED sections of a contract envelope's `text` — the closed set every envelope body is
364
+ * checked against, from docs/design/workstream-contract-system-2026-08-25.md §4.1.
365
+ *
366
+ * WHY IT IS A CLOSED SET AND NOT A SUGGESTION. A workstream is a CONTRACT between parties, and a
367
+ * contract missing its Acceptance section is not a terse contract, it is an unenforceable one: the
368
+ * builder has nothing to hand back against and the verifier has nothing to verify. Prose envelopes
369
+ * omitted sections silently and nobody could tell which — "does this envelope state its budget"
370
+ * had no computable answer. As a closed set the question is decidable, and the refusal names
371
+ * EXACTLY which sections are absent instead of asking the caller to re-read a design doc.
372
+ *
373
+ * THE NINTH ROW OF §4.1 — "Phase · Signature" — IS DELIBERATELY NOT HERE. It is lifecycle STATE,
374
+ * not prose the parties author: the server owns it, writes it as the `phase` field and stamps
375
+ * `phase_at` itself. A lifecycle state carried inside the body would be a second derivation of
376
+ * "what phase is this contract in", and the copy that is wrong is always the one in the prose.
377
+ */
378
+ export const ENVELOPE_SECTIONS = Object.freeze([
379
+ 'objective', 'parties', 'interfaces', 'constraints',
380
+ 'knowledge', 'principles_carried', 'acceptance', 'budget',
381
+ ]);
382
+
383
+ /**
384
+ * WHAT `text` IS — stated ONCE, quoted by every surface that describes or enforces it.
385
+ *
386
+ * THE DEFECT THIS REPLACES (ws-c3-live-leg / D-22, measured on the served DEV surface 2026-08-25):
387
+ * `fabric_envelope_put` stated this fact in THREE places — its tool `description`, its
388
+ * `properties.text.description`, and the server's refusal in fabricStore's assertSectionedText —
389
+ * and they had drifted. The tool description said "`text` is a JSON OBJECT whose keys are the
390
+ * contract's SECTIONS"; the property description said "a JSON OBJECT serialized to a string"; the
391
+ * schema declares `type: 'string'`. A caller who followed the TOOL description exactly and sent an
392
+ * actual object was refused with FABRIC_ENVELOPE_TEXT_NOT_SECTIONED and the words "it did not
393
+ * parse as a JSON object" — told the opposite of what was wrong, because `String(anObject)` is
394
+ * "[object Object]" and the JSON never survived the wire at all.
395
+ *
396
+ * Two derivations of one fact is the general form of mirror drift, and a docstring is not exempt:
397
+ * the copy that is wrong is the one the caller reads. One owner, three consumers.
398
+ *
399
+ * QUOTED KEY FORM ON PURPOSE. The sections are rendered as `"objective": ...` rather than a bare
400
+ * comma list so this one sentence is directly usable as the refusal's "here is the shape you
401
+ * wanted" — a refusal that names the required set without showing it makes the caller go and
402
+ * find a design doc.
403
+ */
404
+ export const ENVELOPE_TEXT_SHAPE = '`text` is a STRING carrying the JSON of an object keyed by SECTION — '
405
+ + 'send JSON.stringify(body), never the object itself (an object arrives as "[object Object]" and its '
406
+ + 'JSON never reaches the server). Every section is REQUIRED and must be non-empty: { '
407
+ + ENVELOPE_SECTIONS.map((k) => `"${k}": ...`).join(', ') + ' }.';
408
+
409
+ /**
410
+ * The contract lifecycle, as a closed enum. Design → signed → build → accept → closed.
411
+ *
412
+ * A CLOSED SET BECAUSE A PHASE IS READ AS PROGRESS. An unbounded phase vocabulary is the heartbeat
413
+ * failure on the record that says whether a contract may be built against: eleven spellings of
414
+ * "in progress" mean "has this been signed" cannot be answered by a query.
415
+ */
416
+ export const ENVELOPE_PHASES = Object.freeze(['design', 'signed', 'build', 'accept', 'closed']);
417
+
418
+ /** The phase an envelope carries when nobody has named one. NAMED, never `ENVELOPE_PHASES[0]` —
419
+ * a position is not a meaning, and a reordering of the list would silently change the default.
420
+ * A contract that has not been signed is in `design`, which is the honest reading of a record
421
+ * that has never been through the architect. */
422
+ export const ENVELOPE_PHASE_DEFAULT = 'design';
423
+
424
+ /**
425
+ * The LEGAL next-phases per phase — the whole transition rule, in one owner, so no verb hand-lists
426
+ * it. `ENVELOPE_PHASE_TRANSITIONS[prior].includes(next)` is the complete answer to "may this write
427
+ * move the contract from prior to next"; there is no additional same-phase or terminal special
428
+ * case anywhere else, because a rule split between a table and an `if` is two derivations of one
429
+ * fact and the `if` is the copy that drifts.
430
+ *
431
+ * A PHASE IS IN ITS OWN LEGAL SET, AND THAT IS THE LOAD-BEARING ENTRY. Re-writing an envelope that
432
+ * is already in `build` without moving it must SUCCEED — otherwise a contract becomes unpatchable
433
+ * the moment work starts on it, and the parties go back to editing prose out of band. Every phase
434
+ * therefore permits itself.
435
+ *
436
+ * BACKWARD IS REFUSED. A contract that silently regressed from `build` to `design` would make the
437
+ * phase unreadable as progress, and re-opening a signed contract is not a field edit — design §4.3
438
+ * routes it: "Anything else is a contract change and goes through the architect", who authors a
439
+ * NEW contract rather than rewinding the record its parties already signed.
440
+ *
441
+ * `closed` IS TERMINAL — it permits only itself, so a closed contract can still be patched but can
442
+ * never be re-opened by a write.
443
+ */
444
+ export const ENVELOPE_PHASE_TRANSITIONS = Object.freeze({
445
+ design: Object.freeze(['design', 'signed']),
446
+ signed: Object.freeze(['signed', 'build']),
447
+ build: Object.freeze(['build', 'accept']),
448
+ accept: Object.freeze(['accept', 'closed']),
449
+ closed: Object.freeze(['closed']),
450
+ });
451
+
452
+ /**
453
+ * The inter-party record kinds the contract system permits on the fabric.
454
+ *
455
+ * The first three are design §4.3's three messages after signature: a HAND-BACK carries evidence
456
+ * against a named acceptance row, a BLOCKER names the clause it cannot satisfy, a CONTRACT-DEFECT
457
+ * reports an ambiguity or a served surface that does not match its description and goes to the
458
+ * architect. `identity` and `roster` are the contract's own record types — an identity hired from
459
+ * a role (§5) and the roster of identities a contract's Parties section points at.
460
+ *
461
+ * A RECORD WITHOUT A `type` IS A VIOLATION, not a lax record. "Seats do not chat": anything that is
462
+ * none of these kinds is a contract change and belongs to the architect, and a type-less record is
463
+ * precisely the chat that routes to nobody — it matches no kind-filtered sweep, so it is written
464
+ * successfully and read by whoever happens to be looking.
465
+ */
466
+ export const FABRIC_RECORD_KINDS = Object.freeze([
467
+ 'handback', 'blocker', 'contract-defect', 'identity', 'roster', 'grounding',
468
+ ]);
469
+
470
+ // ── to_agent: the ONLY delivery selector ─────────────────────────────────────────────────────
471
+ //
472
+ // ONE LIST. A record is delivered by `to_agent` + `status`, and the addresses a seat actually
473
+ // sweeps are composed by `inboxAddresses()` below: its own label, `seat-<session8>`, and these
474
+ // sentinels. A sentinel that is NOT in the composed set is written successfully and read by
475
+ // nobody, so the two lists must be the same list — they were not, and `CEO`/`master` were the
476
+ // difference. See RETIRED_SENTINELS.
477
+ export const TO_AGENT_SENTINELS = Object.freeze(['all', 'ALL']);
478
+
479
+ /**
480
+ * Sentinels that were accepted and delivered to NOBODY. `CEO` and `master` are ROLES, and
481
+ * `inboxAddresses()` has never composed either: a beat or message addressed to one was written,
482
+ * returned success, and no sweep on the fabric could ever select it. They are refused BY NAME, and
483
+ * the refusal says how to FIND the org master's current seat label (`beast_seat_read
484
+ * {seat_id:'org'}`) rather than naming one — a label names a holder, and a literal here would be a
485
+ * snapshot that goes wrong silently the first time the seat changes hands. A refusal that does not
486
+ * say what to say instead is an invitation to work around it.
487
+ */
488
+ export const RETIRED_SENTINELS = Object.freeze(['CEO', 'master']);
489
+
490
+ // Role names that cannot be a seat address. DELIBERATELY NARROW: roles are not swept, seats are.
491
+ // "JARVIS" and "VISION" are NOT here — they are real seat names the master's alias set polls, and
492
+ // refusing them would block real mail. Refuse only on certainty.
493
+ export const FORBIDDEN_ROLE_ADDRESSES = Object.freeze([
494
+ 'cos', 'coo', 'evp', 'evp-descix', 'evp-egpt', 'evp-fraqtl', 'evp-ssg',
495
+ 'chief-of-staff', 'orchestrator',
496
+ ]);
497
+
498
+ // ── Record types the verbs own ───────────────────────────────────────────────────────────────
499
+ // `type` is a PAYLOAD CLASSIFIER and NEVER a delivery selector. These constants exist so the verbs
500
+ // stamp a consistent classifier; no read path may filter an inbox on them.
501
+ export const TYPE_HEARTBEAT = 'heartbeat';
502
+ export const TYPE_MESSAGE = 'message';
503
+ export const TYPE_ENVELOPE = 'envelope';
504
+ export const TYPE_SEAT_STATE = 'seat-state';
505
+ export const TYPE_WATERMARK = 'watermark';
506
+ export const TYPE_SEAT_NAME = 'seat-name';
507
+ export const TYPE_LEASE = 'lease';
508
+ export const TYPE_CONTRACT = 'contract';
509
+ export const TYPE_GROUNDING = 'grounding';
510
+
511
+ // ── Key prefixes ─────────────────────────────────────────────────────────────────────────────
512
+ export const KEY_HEARTBEAT = 'heartbeat-';
513
+ export const KEY_MESSAGE = 'msg-';
514
+ export const KEY_SEAT_STATE = 'seat-state-';
515
+ export const KEY_WATERMARK = 'watermark-';
516
+ export const KEY_LEASE = 'lease-';
517
+ /** `envelope-<workstream_id>` — composed by `fabric_envelope_put`, never by a caller. */
518
+ export const KEY_ENVELOPE = 'envelope-';
519
+ /** `seat-name-<LABEL>` — the roster record. No fabric verb WRITES one yet; the prefix is here
520
+ * because the raw-surface guard must recognise a roster read, and a prefix known in one place and
521
+ * hand-typed in the other is the mirror this module exists to close. */
522
+ export const KEY_SEAT_NAME = 'seat-name-';
523
+ /**
524
+ * `contract-<contract_key>` — the CONTRACT record, written by `fabric_contract_put`.
525
+ *
526
+ * A CONTRACT IS NOT AN ENVELOPE, and the two prefixes are the difference. An envelope is the 1:1
527
+ * ASSIGNMENT of a workstream to a seat (`envelope-<workstream_id>`, one per workstream); a contract
528
+ * is the agreement its parties sign, and one workstream can carry several — a parent and a
529
+ * sub-contract per doer. Collapsing them onto one key would make "which contract am I working
530
+ * under" unanswerable the moment a workstream had more than one party.
531
+ *
532
+ * MEASURED 2026-08-26 (CLOUD-G): before this prefix existed, every contract on the fabric was
533
+ * written by raw `app_records_put` — no key derivation, no section gate, no sub-structure check.
534
+ * The contracts that commissioned this very rule were written that way.
535
+ */
536
+ export const KEY_CONTRACT = 'contract-';
537
+ /**
538
+ * `grounding-<contract_key>-<identity>` — the GROUNDING RECEIPT, written by `fabric_grounding_put`.
539
+ *
540
+ * One per (contract, identity): the receipt that THIS identity performed THIS contract's declared
541
+ * reads and verified them against the code. The key carries both segments because the question a
542
+ * guard asks is "has this identity grounded on this contract", and a key that named only the
543
+ * contract would answer it for whoever grounded first.
544
+ */
545
+ export const KEY_GROUNDING = 'grounding-';
546
+
547
+ // ── Grounding: the contract's KB reads, and the receipt that they happened ────────────────────
548
+ //
549
+ // TWO TABLES, ONE SUBJECT. `CONTRACT_READ_FIELDS` is what a CONTRACT declares ("go and ask this");
550
+ // `GROUNDING_READ_FIELDS` is what a RECEIPT reports ("I asked it, and this came back"). The receipt
551
+ // is a superset: it repeats the declaration verbatim so the two can be compared without a join, and
552
+ // adds what only the execution knows. They are separate tables because a contract author cannot
553
+ // know `sources_count` and a grounding writer must not be free to re-word the question.
554
+
555
+ /**
556
+ * The fields every entry of a contract's `knowledge.reads` must carry.
557
+ *
558
+ * A TABLE, NOT A CHAIN OF `if`s, because the refusal has to name the offending field AND the
559
+ * offending INDEX. "knowledge.reads is malformed" sends an author to re-read a design doc;
560
+ * "reads[2] is missing `question`" is repaired in one edit. The predicate and the human-readable
561
+ * expectation sit in the same row, so a refusal can never describe a rule the check does not apply.
562
+ */
563
+ export const CONTRACT_READ_FIELDS = Object.freeze([
564
+ Object.freeze({
565
+ field: 'app', type: 'string',
566
+ expected: 'a non-empty string naming the app to ask',
567
+ description: 'The app_id the read is issued against — passed verbatim as ask_question_to_app.app_id.',
568
+ ok: (v) => typeof v === 'string' && v.trim() !== '',
569
+ }),
570
+ Object.freeze({
571
+ field: 'knowledgebase_names', type: 'string[]',
572
+ expected: 'a non-empty ARRAY of non-empty knowledge-base names',
573
+ description: 'The KBs to fuse for this read — passed verbatim as ask_question_to_app.knowledgebase_names.',
574
+ // A BARE STRING IS REFUSED RATHER THAN WRAPPED, the same rule the envelope's array fields
575
+ // hold: a scalar in a field every reader scans as a list names one KB while looking like it
576
+ // named none, and a shape silently coerced here is a shape the caller never learns.
577
+ ok: (v) => Array.isArray(v) && v.length > 0
578
+ && v.every((n) => typeof n === 'string' && n.trim() !== ''),
579
+ }),
580
+ Object.freeze({
581
+ field: 'question', type: 'string',
582
+ expected: 'a non-empty string — the question actually asked',
583
+ // THE NAME DIFFERS FROM THE SERVED PARAMETER ON PURPOSE, and the mapping is stated ONCE,
584
+ // here (VISION ruling 2026-08-26 on DEVPLANE's FLAG3). The record field is `question`
585
+ // because a contract is read by people; the served tool's parameter is `user_input`. One
586
+ // consumer (/ground) maps it in one place; nothing else renames anything.
587
+ description: 'The question to ask — passed verbatim as ask_question_to_app.user_input.',
588
+ ok: (v) => typeof v === 'string' && v.trim() !== '',
589
+ }),
590
+ ]);
591
+
592
+ /** Read once, so a refusal's text and the check it describes iterate the SAME list. */
593
+ export const CONTRACT_READ_FIELD_NAMES = Object.freeze(CONTRACT_READ_FIELDS.map((f) => f.field));
594
+
595
+ /**
596
+ * The KINDS of read a grounding receipt can report.
597
+ *
598
+ * A DOER GROUNDS ON TWO DIFFERENT THINGS and they are not the same act. A `kb` read asks a question
599
+ * of a corpus and is answerable only if sources came back. A `role` read fetches the doer's SERVED
600
+ * ROLE RECORD — a keyed document, not a retrieval — and has no sources to count: demanding one
601
+ * would force a doer to report a number that does not exist, and the honest report (zero) would be
602
+ * refused as ungrounded. So the kinds carry DIFFERENT FIELD TABLES and the unsourced rule is scoped
603
+ * to `kb`.
604
+ */
605
+ export const GROUNDING_READ_KINDS = Object.freeze(['kb', 'role']);
606
+
607
+ /** The discriminator itself — one row, shared by both tables, so the two can never disagree. */
608
+ const READ_KIND_FIELD = Object.freeze({
609
+ field: 'kind', type: 'string',
610
+ expected: `one of ${GROUNDING_READ_KINDS.join(', ')}`,
611
+ description: 'Which kind of read this entry reports. `kb` = a corpus question (sources required); '
612
+ + '`role` = the served role record (role_id + updated_at instead).',
613
+ ok: (v) => typeof v === 'string' && GROUNDING_READ_KINDS.includes(v),
614
+ });
615
+
616
+ /**
617
+ * The fields every `kind: "kb"` entry of a grounding record's `reads` must carry — the declaration,
618
+ * repeated, plus what only the execution knows.
619
+ *
620
+ * `sources_count` IS THE LOAD-BEARING ONE. A read that returned no sources is not a read: the model
621
+ * answered from its own weights, which is precisely the ungrounded answer the whole gate exists to
622
+ * refuse. It is reported rather than inferred because the server cannot see the caller's tool
623
+ * result, and it is REFUSED at zero rather than merely recorded, because a receipt that faithfully
624
+ * records a failure is still a receipt a guard would let through.
625
+ */
626
+ export const GROUNDING_KB_READ_FIELDS = Object.freeze([
627
+ READ_KIND_FIELD,
628
+ ...CONTRACT_READ_FIELDS,
629
+ Object.freeze({
630
+ field: 'sources_count', type: 'integer',
631
+ expected: 'a non-negative integer — how many sources the answer cited',
632
+ description: 'Length of the `sources` array the read returned. ZERO IS REFUSED: an answer with no sources is ungrounded.',
633
+ ok: (v) => Number.isInteger(v) && v >= 0,
634
+ }),
635
+ Object.freeze({
636
+ field: 'input_tokens', type: 'integer',
637
+ expected: 'a non-negative integer',
638
+ description: 'message.usage.input_tokens for this read.',
639
+ ok: (v) => Number.isInteger(v) && v >= 0,
640
+ }),
641
+ Object.freeze({
642
+ field: 'output_tokens', type: 'integer',
643
+ expected: 'a non-negative integer',
644
+ description: 'message.usage.output_tokens for this read.',
645
+ ok: (v) => Number.isInteger(v) && v >= 0,
646
+ }),
647
+ ]);
648
+
649
+ export const GROUNDING_KB_READ_FIELD_NAMES = Object.freeze(GROUNDING_KB_READ_FIELDS.map((f) => f.field));
650
+
651
+ /**
652
+ * The fields every `kind: "role"` entry must carry.
653
+ *
654
+ * `updated_at` IS THE POINT OF THE ROW. A role record read six weeks ago is not grounding — it is a
655
+ * memory of grounding — and the only way a verifier can tell the difference is the version the doer
656
+ * actually held. A role read is otherwise unlike a KB read in every respect, which is why it gets
657
+ * its own table rather than optional columns on the other one: optional columns make "which fields
658
+ * apply here" a thing the reader has to infer.
659
+ */
660
+ export const GROUNDING_ROLE_READ_FIELDS = Object.freeze([
661
+ READ_KIND_FIELD,
662
+ Object.freeze({
663
+ field: 'role_id', type: 'string',
664
+ expected: 'a non-empty string — the role whose served record was read',
665
+ description: 'The role_id passed to the served role read, e.g. `orchestrate-platform`.',
666
+ ok: (v) => typeof v === 'string' && v.trim() !== '',
667
+ }),
668
+ Object.freeze({
669
+ field: 'updated_at', type: 'string',
670
+ expected: 'a non-empty string — the role record\'s own updated_at, as served',
671
+ description: 'The `updated_at` the role record carried when it was read. Reported verbatim: a stale '
672
+ + 'role read is a real defect and it is invisible without the version.',
673
+ ok: (v) => typeof v === 'string' && v.trim() !== '',
674
+ }),
675
+ ]);
676
+
677
+ export const GROUNDING_ROLE_READ_FIELD_NAMES = Object.freeze(GROUNDING_ROLE_READ_FIELDS.map((f) => f.field));
678
+
679
+ /**
680
+ * The tables, keyed by their discriminator, so a validator DISPATCHES on the kind instead of
681
+ * branching on it. A third kind is added here and nowhere else.
682
+ */
683
+ export const GROUNDING_READ_FIELDS_BY_KIND = Object.freeze({
684
+ kb: GROUNDING_KB_READ_FIELDS,
685
+ role: GROUNDING_ROLE_READ_FIELDS,
686
+ });
687
+
688
+ /**
689
+ * The kind that must appear AT LEAST ONCE in every grounding record.
690
+ *
691
+ * A receipt made entirely of role reads proves the doer looked up its own job description. It does
692
+ * not prove it read the contract's corpus, which is the claim the gate exists to make.
693
+ */
694
+ export const GROUNDING_REQUIRED_READ_KIND = 'kb';
695
+
696
+ /**
697
+ * The verdicts a verification row may carry — CLOSED, because a guard branches on this value.
698
+ *
699
+ * Declared before the table that reads it, the same way `GROUNDING_FIELDS` is declared after
700
+ * `WRITE_MODES`: a set named in a row's `expected` string is interpolated from the one owner, never
701
+ * hand-typed beside it.
702
+ */
703
+ export const GROUNDING_VERDICTS = Object.freeze(['CONFIRMED', 'FALSIFIED', 'UNDETERMINED']);
704
+
705
+ /**
706
+ * The fields every entry of a grounding record's `verification` must carry.
707
+ *
708
+ * A KB answer is a CLAIM until it is checked against the code that executes. `file_symbol` is the
709
+ * citation — `path/to/file.js::symbol` — and it is required because a verification that names no
710
+ * artifact cannot be re-run by the verifier, which makes it indistinguishable from an assertion.
711
+ */
712
+ export const GROUNDING_VERIFICATION_FIELDS = Object.freeze([
713
+ Object.freeze({
714
+ field: 'claim', type: 'string',
715
+ expected: 'a non-empty string — what the KB said',
716
+ description: 'The claim taken from the KB answer, in the doer\'s words.',
717
+ ok: (v) => typeof v === 'string' && v.trim() !== '',
718
+ }),
719
+ Object.freeze({
720
+ field: 'file_symbol', type: 'string',
721
+ expected: 'a non-empty string — the artifact checked, as path::symbol',
722
+ description: 'The code the claim was checked against, e.g. services/fabricStore.js::envelopePut.',
723
+ ok: (v) => typeof v === 'string' && v.trim() !== '',
724
+ }),
725
+ Object.freeze({
726
+ field: 'verdict', type: 'string',
727
+ expected: `one of ${GROUNDING_VERDICTS.join(', ')}`,
728
+ // A CLOSED ENUM, because the reader of this field is a MACHINE. A verifier and a guard have
729
+ // to answer "did the code agree with the KB" without parsing English, and free text made
730
+ // that a string-match against wording no two doers chose the same way. UNDETERMINED is in
731
+ // the set precisely so nuance has somewhere to go that is not prose: a claim the doer could
732
+ // not settle is a real, reportable outcome, and forcing it into CONFIRMED is the failure.
733
+ description: 'The outcome of checking the claim against the artifact: CONFIRMED (the code agrees), '
734
+ + 'FALSIFIED (the code contradicts it), UNDETERMINED (the check could not settle it). '
735
+ + 'The detail belongs in `claim`; this field is read by machines.',
736
+ ok: (v) => typeof v === 'string' && GROUNDING_VERDICTS.includes(v),
737
+ }),
738
+ ]);
739
+
740
+ export const GROUNDING_VERIFICATION_FIELD_NAMES = Object.freeze(
741
+ GROUNDING_VERIFICATION_FIELDS.map((f) => f.field));
742
+
743
+ /**
744
+ * The refusal codes this vocabulary's rules produce, PUBLISHED BY NAME.
745
+ *
746
+ * A client that branches on a refusal needs the code, and a code discovered by triggering the
747
+ * failure in production is a contract learned the expensive way. Grouped by the verb that raises
748
+ * them so a consumer can tell which surface it is programming against.
749
+ */
750
+ export const FABRIC_CONTRACT_REFUSAL_CODES = Object.freeze([
751
+ 'FABRIC_ENVELOPE_TEXT_NOT_SECTIONED',
752
+ 'FABRIC_ENVELOPE_SECTIONS_MISSING',
753
+ 'FABRIC_CONTRACT_KNOWLEDGE_READS_MISSING',
754
+ 'FABRIC_CONTRACT_PRINCIPLES_EMPTY',
755
+ 'FABRIC_CONTRACT_KEY_INVALID',
756
+ 'FABRIC_SERVER_OWNED_FIELD',
757
+ ]);
758
+
759
+ export const FABRIC_GROUNDING_REFUSAL_CODES = Object.freeze([
760
+ 'FABRIC_GROUNDING_READ_UNSOURCED',
761
+ 'FABRIC_GROUNDING_CONTRACT_UNKNOWN',
762
+ 'FABRIC_GROUNDING_CONTRACT_MALFORMED',
763
+ 'FABRIC_GROUNDING_SHAPE_INVALID',
764
+ 'FABRIC_SERVER_OWNED_FIELD',
765
+ ]);
766
+
767
+ // ── Write modes ──────────────────────────────────────────────────────────────────────────────
768
+ //
769
+ // A partial `app_records_put` MERGES: send `status` alone and the store keeps every other field
770
+ // from the prior write under a fresh `received_at`. Measured three times in one night; the worst
771
+ // carried a stale `plugin_version` and an hours-old `text` describing a superseded release, all
772
+ // looking current. Get-after-put is STRUCTURALLY BLIND to it — you read back the fields you sent,
773
+ // and the fields you failed to send are never examined. So the keyed-record verbs REQUIRE an
774
+ // explicit mode and have no default.
775
+ //
776
+ // patch — merge these fields into the record, leave the rest alone.
777
+ // replace — this record IS the record. Every field the prior version carried and this one does
778
+ // not is explicitly CLEARED, in one atomic put.
779
+ export const WRITE_MODES = Object.freeze(['replace', 'patch']);
780
+
781
+ /**
782
+ * What a flag's DISPOSITION may be — CLOSED, and read by the same machines that read a verdict.
783
+ *
784
+ * open — raised to the hiring party; no answer yet. The doer is working around it or waiting.
785
+ * ruled — the hiring party ANSWERED it, and `resolution` carries the ruling.
786
+ * resolved — it turned out not to be a defect, or the doer settled it itself; `resolution` says how.
787
+ */
788
+ export const GROUNDING_FLAG_DISPOSITIONS = Object.freeze(['open', 'ruled', 'resolved']);
789
+
790
+ /**
791
+ * The dispositions that REQUIRE a non-empty `resolution`.
792
+ *
793
+ * "Ruled" and "resolved" are both claims that something was SETTLED, and a settlement nobody wrote
794
+ * down is indistinguishable from one that never happened — the same rule as `flags` being required
795
+ * but permitted empty. `open` is exempt because there is genuinely nothing to record yet.
796
+ */
797
+ export const GROUNDING_FLAG_RESOLUTION_REQUIRED_FOR = Object.freeze(['ruled', 'resolved']);
798
+
799
+ /**
800
+ * The fields every entry of a grounding record's `flags` must carry.
801
+ *
802
+ * A FLAG IS A RECORD, NOT A SENTENCE. A flags array of bare strings could be counted and nothing
803
+ * else: a verifier could not tell an answered flag from an abandoned one, and a guard could not
804
+ * refuse a doer that raised a blocker and worked through it anyway. `disposition` is the field that
805
+ * makes that answerable, and it is why a string entry is REFUSED BY INDEX rather than wrapped —
806
+ * wrapping would silently invent a disposition the doer never claimed.
807
+ */
808
+ export const GROUNDING_FLAG_FIELDS = Object.freeze([
809
+ Object.freeze({
810
+ field: 'id', type: 'string',
811
+ expected: 'a non-empty string — a stable handle for this flag',
812
+ description: 'A short id the parties can quote back, e.g. FLAG-4. It is how a ruling names its subject.',
813
+ ok: (v) => typeof v === 'string' && v.trim() !== '',
814
+ }),
815
+ Object.freeze({
816
+ field: 'kind', type: 'string',
817
+ expected: 'a non-empty string — what class of problem this is',
818
+ description: 'The doer\'s own classification, e.g. contract-defect, platform-defect, ambiguity.',
819
+ ok: (v) => typeof v === 'string' && v.trim() !== '',
820
+ }),
821
+ Object.freeze({
822
+ field: 'detail', type: 'string',
823
+ expected: 'a non-empty string — what was actually observed',
824
+ description: 'What the doer found, in enough detail that the hiring party can rule on it without asking.',
825
+ ok: (v) => typeof v === 'string' && v.trim() !== '',
826
+ }),
827
+ Object.freeze({
828
+ field: 'disposition', type: 'string',
829
+ expected: `one of ${GROUNDING_FLAG_DISPOSITIONS.join(', ')}`,
830
+ description: `Where the flag stands. ${GROUNDING_FLAG_RESOLUTION_REQUIRED_FOR.join(' and ')} REQUIRE a `
831
+ + 'non-empty `resolution`; `open` does not.',
832
+ ok: (v) => typeof v === 'string' && GROUNDING_FLAG_DISPOSITIONS.includes(v),
833
+ }),
834
+ Object.freeze({
835
+ field: 'resolution', type: 'string',
836
+ expected: 'a string — the ruling or the reason it was settled (may be empty ONLY while `open`)',
837
+ description: 'How it was settled, quoted from the ruling where there is one. Required non-empty when '
838
+ + `disposition is ${GROUNDING_FLAG_RESOLUTION_REQUIRED_FOR.join(' or ')}.`,
839
+ ok: (v) => typeof v === 'string',
840
+ }),
841
+ ]);
842
+
843
+ export const GROUNDING_FLAG_FIELD_NAMES = Object.freeze(GROUNDING_FLAG_FIELDS.map((f) => f.field));
844
+
845
+ /**
846
+ * The top-level shape of `fabric_grounding_put`, PUBLISHED so the plugin's `/ground` skill and its
847
+ * guards GENERATE their copy instead of hand-keeping one.
848
+ *
849
+ * DECLARED AFTER `WRITE_MODES` BECAUSE IT READS IT. The `mode` row names the legal modes from the
850
+ * one owner rather than restating them — a second list of "replace, patch" published beside the
851
+ * first is the mirror this module exists to close, and it would be the copy consumers read.
852
+ *
853
+ * `flags` IS REQUIRED AND MAY BE EMPTY, and that pair is deliberate. "I found no flags" is a claim a
854
+ * doer must make explicitly; an ABSENT flags array is indistinguishable from a doer who never
855
+ * looked, and the two must not read the same to a verifier.
856
+ */
857
+ export const GROUNDING_FIELDS = Object.freeze([
858
+ Object.freeze({ name: 'contract_key', type: 'string', required: true,
859
+ description: 'The FULL stored key of the contract this grounding is for — exactly as the contract '
860
+ + `record's own contract_key field carries it, prefix included ("${KEY_CONTRACT}..."). Nothing is `
861
+ + 'stripped and nothing is prepended.' }),
862
+ Object.freeze({ name: 'identity', type: 'string', required: true,
863
+ description: 'The identity (party label) that performed the reads.' }),
864
+ Object.freeze({ name: 'reads', type: 'object[]', required: true,
865
+ description: `Non-empty, and at least one entry of kind '${GROUNDING_REQUIRED_READ_KIND}'. Each entry `
866
+ + `carries \`kind\` (${GROUNDING_READ_KINDS.join(' | ')}) and the fields of that kind's table: `
867
+ + `kb → ${GROUNDING_KB_READ_FIELD_NAMES.join(', ')}; role → ${GROUNDING_ROLE_READ_FIELD_NAMES.join(', ')}.` }),
868
+ Object.freeze({ name: 'verification', type: 'object[]', required: true,
869
+ description: `Non-empty. Each entry carries ${GROUNDING_VERIFICATION_FIELD_NAMES.join(', ')}; `
870
+ + `verdict is one of ${GROUNDING_VERDICTS.join(', ')}.` }),
871
+ Object.freeze({ name: 'flags', type: 'object[]', required: true,
872
+ description: `Flags raised before work, as OBJECTS carrying ${GROUNDING_FLAG_FIELD_NAMES.join(', ')} — a `
873
+ + 'bare string is refused by index. REQUIRED but may be empty: "no flags" is an explicit claim, '
874
+ + 'not an omission.' }),
875
+ Object.freeze({ name: 'phase', type: 'string', required: false,
876
+ description: 'OPTIONAL. A slug for the phase of work this receipt covers, appended as a THIRD key '
877
+ + 'segment. One contract can be grounded more than once by one identity when the work has '
878
+ + 'phases; without it, the second grounding would overwrite the first.' }),
879
+ Object.freeze({ name: 'mode', type: 'string', required: true,
880
+ description: `One of ${WRITE_MODES.join(', ')}. No default, like every keyed write on this surface.` }),
881
+ ]);
882
+
883
+ // ── Numeric defaults — the SERVER owns every one ─────────────────────────────────────────────
884
+ //
885
+ // Each of these is returned on the response that used it, so no client needs its own copy and no
886
+ // tool description hand-types the number. The plugin's BEAT_TTL is retired against
887
+ // DEFAULT_LIVENESS_THRESHOLD_S, not mirrored from it.
888
+
889
+ /** The beat cadence a working seat is held to is ~15 minutes; this allows one miss. */
890
+ export const DEFAULT_LIVENESS_THRESHOLD_S = 1200;
891
+
892
+ /** Records `fabric_inbox_sweep` returns when the caller names no limit. */
893
+ export const DEFAULT_INBOX_LIMIT = 200;
894
+
895
+ /** Lifetime of a lease claimed without an explicit ttl_s. */
896
+ export const DEFAULT_LEASE_TTL_S = 3600;
897
+
898
+ /**
899
+ * The cap on any heartbeat CENSUS (a `{type:"heartbeat"}` scan with no key predicate).
900
+ *
901
+ * A census is the only probe that can see a beat whose key converged on nothing, so it cannot be
902
+ * removed — but unbounded it grows with every seat that has ever beaten, on a query the store
903
+ * answers by scanning. Bounded, the diagnostic keeps working and the cost stops being a function
904
+ * of the fabric's whole history. See the contract's Open calls for the pushdown that removes the
905
+ * scan entirely.
906
+ */
907
+ export const HEARTBEAT_CENSUS_LIMIT = 500;
908
+
909
+ export const VERDICT = Object.freeze({
910
+ ALIVE: 'alive',
911
+ STALE: 'stale',
912
+ DECLARED_STOP: 'declared-stop',
913
+ NONE: 'none',
914
+ });
915
+
916
+ // ── THE BEAT CLOCK PAIR: two writers, two clocks, ONE owner ──────────────────────────────────
917
+ //
918
+ // MEASURED DEFECT (BEAST, 2026-08-24T21:37Z). The record `heartbeat-<LABEL>-<session8>` has TWO
919
+ // writers on ONE key — the seat's AGENT (liveness `model`) and the plugin's doorbell hook every
920
+ // 60 seconds (liveness `process`). Both wrote the same field, `liveness`, and the reader judged
921
+ // the MODEL on whichever value was current. The hook writes 15x more often than the agent, so the
922
+ // current value is almost always `process`, and EVERY correctly-armed seat read UNDETERMINED. The
923
+ // process beat did not merely fail to prove the model alive: it ERASED the proof.
924
+ //
925
+ // A second measurement (18:25Z, 20:42Z) found the mirror failure on the write side: `fabric_beat`
926
+ // with liveness=model CLEARED `model_beat_at`, because the whole-state rule ("a beat is not a
927
+ // diff") swept it up as "a field the previous beat left behind".
928
+ //
929
+ // THE FIX IS NOT A THIRD FIELD, IT IS TWO CLOCKS. "When did an agent last prove itself alive" and
930
+ // "when did a process last prove itself alive" are TWO FACTS. One field cannot hold two facts, and
931
+ // two writers sharing one field is the general form of mirror drift — the copies WILL disagree
932
+ // silently, and here the disagreement is invisible because the loser is overwritten rather than
933
+ // contradicted. So each writer gets its OWN clock, and neither may touch the other's.
934
+ //
935
+ // `liveness` REMAINS, and it still means what it meant: WHO wrote the most recent beat. It is no
936
+ // longer the model's clock and no reader may use it as one.
937
+ //
938
+ // THIS TABLE IS THE CONTRACT. It is exported so the plugin reader (unkamon-beast
939
+ // `hooks/lib/fabric_read.py`), the secretary definition and DeSciX_Cloud's `fabricStore.js` consume
940
+ // ONE description instead of three hand-listed field sets — the schema-mirror-drift rule in
941
+ // Unkamon/CLAUDE.md §Engineering Culture. `projectable: true` is load-bearing: both fields are
942
+ // FLAT top-level record fields, so a raw reader may name them in a `fields` projection. A nested
943
+ // clock block would be unprojectable AND unfilterable, and the raw reader would have to fetch the
944
+ // whole record to answer one question.
945
+ export const BEAT_CLOCK_FIELDS = Object.freeze([
946
+ Object.freeze({
947
+ field: 'model_beat_at',
948
+ meaning: 'The server clock at the last beat an AGENT wrote. THE ONLY evidence a model is alive.',
949
+ written_by: LIVENESS_MODEL,
950
+ preserved_by: LIVENESS_PROCESS,
951
+ projectable: true,
952
+ }),
953
+ Object.freeze({
954
+ field: 'process_beat_at',
955
+ meaning: 'The server clock at the last beat a HOOK wrote. Proves a process is alive and says '
956
+ + 'NOTHING about the model.',
957
+ written_by: LIVENESS_PROCESS,
958
+ preserved_by: LIVENESS_MODEL,
959
+ projectable: true,
960
+ }),
961
+ ]);
962
+
963
+ /** The two clock field NAMES, DERIVED from the table above — never a second hand-typed list. Every
964
+ * consumer that needs "which fields are the beat clocks" (the store's never-cleared set, a
965
+ * projection, a conformance test) reads this rather than retyping two strings. */
966
+ export const BEAT_CLOCK_FIELD_NAMES = Object.freeze(BEAT_CLOCK_FIELDS.map((f) => f.field));
967
+
968
+ /** Which clock a beat of this `liveness` WRITES. Derived from the table, so a third liveness value
969
+ * added to the table gets its clock for free and one added without a clock is visibly absent. */
970
+ export function beatClockFieldFor(liveness) {
971
+ const v = typeof liveness === 'string' ? liveness.trim().toLowerCase() : null;
972
+ return BEAT_CLOCK_FIELDS.find((f) => f.written_by === v)?.field ?? null;
973
+ }
974
+
975
+ /**
976
+ * normalize(partial) -> FULL BAG. The canonical reader of a heartbeat's clock pair.
977
+ *
978
+ * Every key of the contract is present on the result, `null` where the record carries nothing
979
+ * readable. A consumer that destructures this can never be surprised by an absent key, and — the
980
+ * point of the exercise — it never re-enumerates the field list to find them.
981
+ *
982
+ * `null` IS NOT `0` AND IS NOT `now`. An absent model clock means UNKNOWN (a pre-contract record,
983
+ * or a seat only its hook has ever beaten for). Substituting any instant here would manufacture the
984
+ * exact claim — "an agent is alive" — that this pair exists to make falsifiable.
985
+ *
986
+ * `liveness` is carried through the same normalization because it is read from the same record by
987
+ * the same consumers, and because a reader that took it raw would re-open the case-and-vocabulary
988
+ * question this module answers once.
989
+ */
990
+ export function normalizeBeatClocks(record) {
991
+ const r = (record && typeof record === 'object') ? record : {};
992
+ const str = (v) => (typeof v === 'string' && v.trim() !== '' ? v.trim() : null);
993
+ const out = {};
994
+ for (const { field } of BEAT_CLOCK_FIELDS) out[field] = str(r[field]);
995
+ const lv = str(r.liveness);
996
+ out.liveness = (lv && isLivenessValue(lv)) ? lv.toLowerCase() : null;
997
+ return out;
998
+ }
999
+
1000
+ /**
1001
+ * THE liveness judgement, as ONE exported rule.
1002
+ *
1003
+ * The plugin reader and `fabricStore.liveness()` are two consumers in two repositories asking one
1004
+ * question. Two derivations of one fact is the bug class this whole module exists to close, and
1005
+ * the two-writers defect above is what it costs when the copies disagree.
1006
+ *
1007
+ * JUDGED ON `model_beat_at` AND NOTHING ELSE. Not on `liveness` (that says who wrote LAST, and a
1008
+ * hook writes 15x more often), not on `received_at` (that is the record's clock, which a process
1009
+ * beat refreshes — the mask), not on `occurred_at`.
1010
+ *
1011
+ * none — no readable model clock. The record has never carried proof an agent was alive. This
1012
+ * is UNKNOWN, and it is deliberately NOT `stale`: "nobody has ever beaten as a model"
1013
+ * and "an agent beat and then went quiet" are different facts for a master.
1014
+ * stale — a model clock exists and is older than the threshold, OR is present but unreadable.
1015
+ * An unreadable instant must never read alive; it is the friendliest possible lie.
1016
+ * alive — a model clock exists, is readable, and is within the threshold.
1017
+ *
1018
+ * A FUTURE model clock is `alive`, not an error: this rule reads only the server's own stamps
1019
+ * (`fabric_beat` refuses a caller-asserted clock), so a future value cannot be a forgery — it can
1020
+ * only be clock skew, and refusing on it would take a live seat dark. Detecting skew is the
1021
+ * caller's job and it has the two instants to do it with.
1022
+ *
1023
+ * DECLARED STOPS ARE NOT JUDGED HERE. A declaration is not a death
1024
+ * (CEO-D-2026-08-18-SEATS-STAY-REACHABLE) and it is judged on `status`, not on a clock. The caller
1025
+ * applies that precedence over this verdict; folding it in would make this rule need a status it
1026
+ * has no business reading.
1027
+ *
1028
+ * `threshold_s` HAS NO DEFAULT HERE. The platform default is `DEFAULT_LIVENESS_THRESHOLD_S` and it
1029
+ * is the CALLER's to pass, so a caller that forgot one fails loudly instead of silently being
1030
+ * judged against a number it never chose.
1031
+ *
1032
+ * THE ARGUMENT IS THE NORMALIZED BAG PLUS THE TWO SCALARS, and callers are meant to SPREAD
1033
+ * `normalizeBeatClocks(record)` into it (`{...clocks, now, threshold_s}`) rather than pick
1034
+ * `model_beat_at` out and re-label it. Extra keys from the bag are ignored. That is not cosmetic:
1035
+ * a call site that names the field is a second place the string lives, which is the drift this
1036
+ * whole contract exists to close — DeSciX_Cloud's conformance gate refuses a hand-typed clock name
1037
+ * in `fabricStore.js` on exactly that ground.
1038
+ *
1039
+ * @param {{model_beat_at: ?string, now: string, threshold_s: number}} args
1040
+ * @returns {'alive'|'stale'|'none'}
1041
+ */
1042
+ export function judgeModelLiveness({ model_beat_at, now, threshold_s } = {}) {
1043
+ if (typeof threshold_s !== 'number' || !Number.isFinite(threshold_s) || threshold_s <= 0) {
1044
+ throw new TypeError('judgeModelLiveness: threshold_s must be a positive finite number of seconds '
1045
+ + `(got ${JSON.stringify(threshold_s)}). There is no default here — pass `
1046
+ + 'DEFAULT_LIVENESS_THRESHOLD_S, so a caller judged against a number it never chose is impossible.');
1047
+ }
1048
+ const nowMs = Date.parse(now);
1049
+ if (!Number.isFinite(nowMs)) {
1050
+ throw new TypeError(`judgeModelLiveness: 'now' must be a readable ISO-8601 instant (got ${JSON.stringify(now)}). `
1051
+ + 'An unreadable now would silently make every seat look fresh or every seat look dead.');
1052
+ }
1053
+ if (model_beat_at === null || model_beat_at === undefined || model_beat_at === '') return VERDICT.NONE;
1054
+ const beatMs = Date.parse(model_beat_at);
1055
+ // Present but unreadable: STALE, never ALIVE and never NONE. It is not "no beat" — a value IS
1056
+ // there — and it must not be credited as fresh.
1057
+ if (!Number.isFinite(beatMs)) return VERDICT.STALE;
1058
+ return ((nowMs - beatMs) / 1000) > threshold_s ? VERDICT.STALE : VERDICT.ALIVE;
1059
+ }
1060
+
1061
+ /**
1062
+ * The RESPONSE FIELD NAME that carries a beat clock's age — derived FROM the clock it ages.
1063
+ *
1064
+ * `fabric_liveness` reports one age per clock, and a hand-typed age field is the same mirror as a
1065
+ * hand-typed clock: rename `model_beat_at` in the table above and a literal `model_beat_age_seconds`
1066
+ * elsewhere goes quietly wrong, still passing every test that also hand-typed it. So the name has
1067
+ * ONE derivation, here, and the server, the published tool description and the MCP class guard all
1068
+ * read it from this function.
1069
+ *
1070
+ * The trailing `_at` is dropped because it is the CLOCK's tense, not the AGE's — `model_beat_at` is
1071
+ * an instant, `model_beat_age_seconds` is a duration, and `model_beat_at_age_seconds` reads as the
1072
+ * age of an instant-named-thing rather than the age of the beat.
1073
+ */
1074
+ export function beatClockAgeField(clockField) {
1075
+ const f = typeof clockField === 'string' ? clockField.trim() : '';
1076
+ if (!f) return null;
1077
+ return `${f.replace(/_at$/, '')}_age_seconds`;
1078
+ }
1079
+
1080
+ /** Every beat-clock age field, DERIVED — what a consumer (the MCP class guard) registers instead of
1081
+ * listing two more literals beside the two it already had to stop listing. */
1082
+ export const BEAT_CLOCK_AGE_FIELDS = Object.freeze(BEAT_CLOCK_FIELD_NAMES.map(beatClockAgeField));
1083
+
1084
+ /** Age in seconds of a beat clock against `now`, or null when either instant is unreadable —
1085
+ * NEVER 0, which reads as "brand new" and is the friendliest possible lie for a liveness check.
1086
+ * Exported beside the rule that consumes the same two instants, so a caller reporting the age it
1087
+ * was judged on cannot compute it a second way. */
1088
+ export function beatClockAgeSeconds(beatIso, nowIso) {
1089
+ const a = Date.parse(beatIso);
1090
+ const b = Date.parse(nowIso);
1091
+ if (!Number.isFinite(a) || !Number.isFinite(b)) return null;
1092
+ return (b - a) / 1000;
1093
+ }
1094
+
1095
+ /** The watermark's per-seat delivery ledger. Named so a writer cannot invent a sixth field that no
1096
+ * reader consults, and so fabric_watermark_put can refuse an unknown one instead of storing it
1097
+ * where it will never be read. */
1098
+ export const WATERMARK_FIELDS = Object.freeze([
1099
+ 'broadcast_seen', 'delivered', 'resolved', 'held', 'awaiting',
1100
+ ]);
1101
+
1102
+ /**
1103
+ * THE LEDGER ENTRY — a delivery claim, and WHO made it.
1104
+ *
1105
+ * WHY PROVENANCE. A claim outlives the credibility of whoever made it. A secretary that was stopped
1106
+ * FOR CAUSE left a `delivered` claim on its seat's watermark that its successor could neither trust
1107
+ * nor safely discard, because nothing on the entry said who wrote it: dropping it risked re-handing
1108
+ * mail already delivered, keeping it risked never handing up mail that never was. Stamping the
1109
+ * writer makes that a decidable question, which is the whole point of R2 and the reason
1110
+ * `quarantine` can exist at all.
1111
+ *
1112
+ * ENCODING. An entry is JSON `{"key":…,"writer":…,"at":…}` in the flat string[] the store allows —
1113
+ * a nested object is neither filterable nor projectable here, exactly as the wake block is flat for
1114
+ * the same reason. A BARE STRING is a PRE-PROVENANCE entry: it is READ (so the live ledgers stay
1115
+ * legible) and it is MIGRATED, but it can no longer be WRITTEN.
1116
+ */
1117
+ export const LEDGER_ENTRY_FIELDS = Object.freeze(['key', 'writer', 'at']);
1118
+
1119
+ /** The record key a ledger entry refers to, whichever encoding it is in. ONE owner of "what does
1120
+ * this entry point at", so dedupe, union and quarantine cannot disagree about identity. */
1121
+ export function ledgerEntryKey(entry) {
1122
+ if (typeof entry !== 'string') return null;
1123
+ if (!entry.startsWith('{')) return entry;
1124
+ try {
1125
+ const p = JSON.parse(entry);
1126
+ return typeof p?.key === 'string' ? p.key : entry;
1127
+ } catch { return entry; }
1128
+ }
1129
+
1130
+ /** The writer that made this claim, or null for a pre-provenance bare entry. */
1131
+ export function ledgerEntryWriter(entry) {
1132
+ if (typeof entry !== 'string' || !entry.startsWith('{')) return null;
1133
+ try {
1134
+ const p = JSON.parse(entry);
1135
+ return typeof p?.writer === 'string' ? p.writer : null;
1136
+ } catch { return null; }
1137
+ }
1138
+
1139
+ /** Stamp a key into a provenance-bearing entry. The clock is the SERVER's, passed in — never read
1140
+ * here — so a ledger entry cannot claim it was written at a time no write happened. */
1141
+ export function stampLedgerEntry(key, writer, at) {
1142
+ return JSON.stringify({ key: String(key), writer: String(writer), at: String(at) });
1143
+ }
1144
+
1145
+ /**
1146
+ * SERVER-SIDE SET-UNION of a ledger field, deduplicated BY KEY, first claim winning.
1147
+ *
1148
+ * This GENERALISES the union `fabric_broadcast_ack` already owned for `broadcast_seen` — it is not
1149
+ * a second owner. That verb computed a merge for exactly one of the five ledger fields and the
1150
+ * semantics were never lifted, which is why every other field was left to a client read-union-write
1151
+ * that a single racing patch could wipe (measured: one patch took a `delivered` ledger from 98
1152
+ * entries to 1).
1153
+ *
1154
+ * FIRST CLAIM WINS on a duplicate key, so the union is IDEMPOTENT and re-appending an entry does
1155
+ * not restamp it with a later writer's name — a delivery is a fact about when it FIRST happened.
1156
+ */
1157
+ export function unionLedger(existing = [], incoming = []) {
1158
+ const out = [];
1159
+ const seen = new Set();
1160
+ for (const e of [...(existing || []), ...(incoming || [])]) {
1161
+ const k = ledgerEntryKey(e);
1162
+ if (k === null || seen.has(k)) continue;
1163
+ seen.add(k);
1164
+ out.push(e);
1165
+ }
1166
+ return out;
1167
+ }
1168
+
1169
+ /**
1170
+ * The write modes `fabric_watermark_put` accepts — the two generic ones PLUS the two the ledger
1171
+ * needs. It is its OWN set rather than an extension of WRITE_MODES because `append` and
1172
+ * `quarantine` are meaningless on every other record on this surface, and widening the shared enum
1173
+ * would advertise them on verbs that would then have to refuse them one by one.
1174
+ */
1175
+ export const WATERMARK_WRITE_MODES = Object.freeze([...WRITE_MODES, 'append', 'quarantine']);
1176
+
1177
+ // ── Predicates ───────────────────────────────────────────────────────────────────────────────
1178
+
1179
+ /** Case-folded membership. The fabric is written by shells, Python hooks and models alike; a
1180
+ * vocabulary check that is case-sensitive refuses `Working` while meaning to accept it. */
1181
+ function has(list, value) {
1182
+ if (typeof value !== 'string') return false;
1183
+ const v = value.trim().toLowerCase();
1184
+ return list.some((x) => x.toLowerCase() === v);
1185
+ }
1186
+
1187
+ /** WRITE validation: is this a value fabric_beat may accept? Closed enum, nothing else. */
1188
+ export const isBeatStatus = (v) => has(BEAT_STATUSES, v);
1189
+
1190
+ /** WRITE validation: is this a legal `liveness` value? Closed enum; absence is not a value. */
1191
+ export const isLivenessValue = (v) => has(LIVENESS_VALUES, v);
1192
+
1193
+ /** READ classification: does this status — canonical OR legacy — mean the seat declared a stop? */
1194
+ export const isDeclaredStop = (v) => has(DECLARED_STOPS, v) || has(LEGACY_STOP_STATUSES, v);
1195
+
1196
+ /** READ classification: is this a status a reader can interpret at all? */
1197
+ export const isReadableStatus = (v) => has(READABLE_STATUSES, v);
1198
+
1199
+ /** READ classification: a legacy value is interpretable but was written before the closed enum. */
1200
+ export const isLegacyStatus = (v) => has(LEGACY_WORKING_STATUSES, v) || has(LEGACY_STOP_STATUSES, v);
1201
+ export const isDeliveryStatus = (v) => has(DELIVERY_STATUSES, v);
1202
+ export const isEnvelopeStatus = (v) => has(ENVELOPE_STATUSES, v);
1203
+ export const isEnvelopePhase = (v) => has(ENVELOPE_PHASES, v);
1204
+ export const isFabricRecordKind = (v) => has(FABRIC_RECORD_KINDS, v);
1205
+ /**
1206
+ * How a STORED phase is READ — WRITE-STRICT, READ-TOLERANT, the same split the beat statuses hold.
1207
+ *
1208
+ * A record whose `phase` is absent (every envelope written before this contract existed) or outside
1209
+ * the enum (nothing this verb can produce — a raw `app_records_put` can) is READ as the default. A
1210
+ * reader that treated it as uninterpretable would answer "no transition is legal from here" and
1211
+ * leave that contract permanently unmovable with a refusal naming an empty set, which is a dead end
1212
+ * a caller cannot act on. Tolerated on READ, never accepted on WRITE, and the verb REPORTS the
1213
+ * substitution instead of performing it silently.
1214
+ */
1215
+ export const readEnvelopePhase = (v) => (isEnvelopePhase(v) ? v : ENVELOPE_PHASE_DEFAULT);
1216
+
1217
+ /** The transition rule itself, read from its ONE owner, through the one reader above. */
1218
+ export const isLegalPhaseTransition = (from, to) =>
1219
+ (ENVELOPE_PHASE_TRANSITIONS[readEnvelopePhase(from)] || []).includes(to);
1220
+ export const isForbiddenRoleAddress = (v) => has(FORBIDDEN_ROLE_ADDRESSES, v);
1221
+ export const isWriteMode = (v) => WRITE_MODES.includes(v);
1222
+
1223
+ /** A sentinel is matched EXACTLY (`all` / `ALL`), not case-folded, because these strings appear
1224
+ * verbatim in the `$in` list of every live sweep. */
1225
+ export const isSentinelAddress = (v) => TO_AGENT_SENTINELS.includes(v);
1226
+
1227
+ /** A retired sentinel is matched exactly for the same reason: it is the literal a caller typed. */
1228
+ export const isRetiredSentinel = (v) => RETIRED_SENTINELS.includes(v);
1229
+
1230
+ /** A workstream id is not an address. No seat sweeps on it. */
1231
+ export const isWorkstreamId = (v) => typeof v === 'string' && v.trim().toLowerCase().startsWith('ws-');
1232
+
1233
+ /**
1234
+ * The session discriminator used in `heartbeat-<LABEL>-<session8>`.
1235
+ *
1236
+ * TWO spellings of a session id are live on the fabric simultaneously — bare `de6593f4` and
1237
+ * prefixed `seat-a0893295`, on the same seat's records (census 2026-08-22: 14 seat-name records, 3
1238
+ * prefixed). A resolver that knows only one returns ZERO for the other half and reports it as
1239
+ * "this session is UNNAMED". So the prefix is stripped, then the first 8 characters are taken —
1240
+ * which is what every live heartbeat key already carries.
1241
+ */
1242
+ export function session8(session_id) {
1243
+ const raw = String(session_id ?? '').trim();
1244
+ const bare = raw.startsWith('seat-') ? raw.slice(5) : raw;
1245
+ return bare.slice(0, 8);
1246
+ }
1247
+
1248
+ /** Both live spellings of a session id, for a `$in` that covers the whole fabric. */
1249
+ export function sessionSpellings(session_id) {
1250
+ const s = session8(session_id);
1251
+ const raw = String(session_id ?? '').trim();
1252
+ const bare = raw.startsWith('seat-') ? raw.slice(5) : raw;
1253
+ return [...new Set([bare, s, `seat-${bare}`, `seat-${s}`])].filter(Boolean);
1254
+ }
1255
+
1256
+ /** The addresses a seat answers to. This is the inbox's `to_agent` set and it has ONE definition —
1257
+ * which is the same definition TO_AGENT_SENTINELS is validated against, so nothing addressable is
1258
+ * unsweepable and nothing sweepable is unaddressable. */
1259
+ export function inboxAddresses(label, session_id) {
1260
+ const out = [];
1261
+ if (label) out.push(String(label));
1262
+ if (session_id) out.push(`seat-${session8(session_id)}`);
1263
+ out.push(...TO_AGENT_SENTINELS);
1264
+ return [...new Set(out)];
1265
+ }
1266
+
1267
+ /**
1268
+ * The whole vocabulary as one plain object — what `fabric_vocabulary` returns over the wire.
1269
+ *
1270
+ * This exists so a client GENERATES its copy rather than keeping one. Every set a client needs in
1271
+ * order to validate a call before making it is here; anything absent from this bag is a set the
1272
+ * client would have to hand-type, which is the drift this module was moved to close.
1273
+ *
1274
+ * THREE THINGS ARE DELIBERATELY NOT IN THIS PAYLOAD, and each absence is load-bearing:
1275
+ *
1276
+ * · `fabric_app_id` / `fabric_kb_id` — the raw-path COORDINATES. No `fabric_*` verb accepts
1277
+ * either (both are refused with FABRIC_PLANE_NOT_CALLER_CHOSEN), so a client has nothing to do
1278
+ * with them except hand-compose the `app_records_*` call this surface exists to replace and
1279
+ * stage 3 refuses. Publishing them here would be the vocabulary handing out the address of the
1280
+ * door it just locked.
1281
+ *
1282
+ * AND NO `fabric_*` RESPONSE ECHOES THEM EITHER — the withholding is ONE story across the whole
1283
+ * surface, not a rule this payload keeps while every success response breaks it. There is a
1284
+ * single named exception and it is the refusal ABOUT the address: a caller told
1285
+ * FABRIC_PLANE_NOT_CALLER_CHOSEN is being told to STOP aiming at a plane, and the refusal names
1286
+ * the collection so the caller can see it did not need to choose one. A refusal that cannot be
1287
+ * acted on is a refusal that gets worked around.
1288
+ * · `org_master_seat_label` — a seat label names a HOLDER and holders change. A literal returned
1289
+ * by a compile-time payload is a snapshot that goes wrong silently the first time the org seat
1290
+ * changes hands, and a client that cached it would address mail to a label nobody sweeps —
1291
+ * which is exactly the RETIRED_SENTINELS failure in newer clothes. The seat's current holder has
1292
+ * one owner: `beast_seat_read {seat_id:'org'}`.
1293
+ */
1294
+ export function fabricVocabulary() {
1295
+ return {
1296
+ beat_statuses: [...BEAT_STATUSES],
1297
+ working_statuses: [...WORKING_STATUSES],
1298
+ declared_stops: [...DECLARED_STOPS],
1299
+ legacy_working_statuses: [...LEGACY_WORKING_STATUSES],
1300
+ legacy_stop_statuses: [...LEGACY_STOP_STATUSES],
1301
+ readable_statuses: [...READABLE_STATUSES],
1302
+ liveness_values: [...LIVENESS_VALUES],
1303
+ delivery_statuses: [...DELIVERY_STATUSES],
1304
+ status_read: STATUS_READ,
1305
+ envelope_statuses: [...ENVELOPE_STATUSES],
1306
+ envelope_status_default: ENVELOPE_STATUS_DEFAULT,
1307
+ envelope_fields: [...ENVELOPE_FIELDS],
1308
+ envelope_sections: [...ENVELOPE_SECTIONS],
1309
+ envelope_phases: [...ENVELOPE_PHASES],
1310
+ envelope_phase_default: ENVELOPE_PHASE_DEFAULT,
1311
+ // Deep-copied, not handed out by reference: the payload is a plain object a client
1312
+ // serialises, and a frozen nested list published by reference invites a consumer to
1313
+ // read it as mutable state.
1314
+ envelope_phase_transitions: Object.fromEntries(
1315
+ Object.entries(ENVELOPE_PHASE_TRANSITIONS).map(([k, v]) => [k, [...v]])),
1316
+ record_kinds: [...FABRIC_RECORD_KINDS],
1317
+ to_agent_sentinels: [...TO_AGENT_SENTINELS],
1318
+ retired_sentinels: [...RETIRED_SENTINELS],
1319
+ forbidden_role_addresses: [...FORBIDDEN_ROLE_ADDRESSES],
1320
+ write_modes: [...WRITE_MODES],
1321
+ watermark_fields: [...WATERMARK_FIELDS],
1322
+ wake_fields: [...WAKE_FIELDS],
1323
+ // WHICH WRITER must carry a wake block, and the flat fields it lands in. Served so a client
1324
+ // GENERATES its copy of the conditional instead of hand-keeping one: a hand-kept mirror of
1325
+ // "wake is required" is exactly what left every doorbell in the fleet refused.
1326
+ wake_required_for_liveness: WAKE_REQUIRED_LIVENESS,
1327
+ // The SECOND wake axis, served beside the first so a client reads both from one
1328
+ // place. A terminal beat has nothing schedulable to declare; a WORKING beat still
1329
+ // must carry a wake, and that is not relaxed here.
1330
+ wake_exempt_statuses: [...WAKE_EXEMPT_STATUSES],
1331
+ // The lifecycle fields that SURVIVE a write that does not mention them, on both
1332
+ // fabric_envelope_put and fabric_contract_put.
1333
+ lifecycle_preserved_fields: [...LIFECYCLE_PRESERVED_FIELDS],
1334
+ // The ledger's provenance contract: the modes fabric_watermark_put accepts and the
1335
+ // fields every stamped entry carries.
1336
+ watermark_write_modes: [...WATERMARK_WRITE_MODES],
1337
+ ledger_entry_fields: [...LEDGER_ENTRY_FIELDS],
1338
+ wake_record_field_names: [...WAKE_RECORD_FIELD_NAMES],
1339
+ // The beat-clock contract, so the plugin reader GENERATES its copy of "which field is the
1340
+ // model's clock" instead of hand-typing it — the exact mirror that made the two-writers
1341
+ // defect invisible for a day. The names are derived from the table, not listed beside it.
1342
+ beat_clock_fields: BEAT_CLOCK_FIELDS.map((f) => ({ ...f })),
1343
+ beat_clock_field_names: [...BEAT_CLOCK_FIELD_NAMES],
1344
+ beat_clock_age_fields: [...BEAT_CLOCK_AGE_FIELDS],
1345
+ record_types: {
1346
+ heartbeat: TYPE_HEARTBEAT, message: TYPE_MESSAGE, envelope: TYPE_ENVELOPE,
1347
+ seat_state: TYPE_SEAT_STATE, watermark: TYPE_WATERMARK, seat_name: TYPE_SEAT_NAME,
1348
+ lease: TYPE_LEASE, contract: TYPE_CONTRACT, grounding: TYPE_GROUNDING,
1349
+ },
1350
+ key_prefixes: {
1351
+ heartbeat: KEY_HEARTBEAT, message: KEY_MESSAGE, seat_state: KEY_SEAT_STATE,
1352
+ watermark: KEY_WATERMARK, lease: KEY_LEASE, envelope: KEY_ENVELOPE,
1353
+ seat_name: KEY_SEAT_NAME, contract: KEY_CONTRACT, grounding: KEY_GROUNDING,
1354
+ },
1355
+ // The key TEMPLATES, so a client composes nothing from a prefix plus a guess. Both are
1356
+ // server-derived — a caller supplying `file_id` or `key` is refused — and they are published
1357
+ // so a READER can find a record it did not write.
1358
+ key_templates: {
1359
+ // THE CONTRACT KEY IS THE KEY. `contract_key` is passed as the full stored key, prefix
1360
+ // and all, and the server never prepends — see `fabric_contract_put`'s refusal
1361
+ // FABRIC_CONTRACT_KEY_INVALID. Published as a literal because a shape written
1362
+ // `${KEY_CONTRACT}<contract_key>` is exactly the derive-by-prepend reading this rule
1363
+ // exists to close.
1364
+ contract: '<contract_key>, which already starts with ' + KEY_CONTRACT,
1365
+ grounding: `${KEY_GROUNDING}<contract_key>-<identity>[-<phase>]`,
1366
+ },
1367
+ // THE GROUNDING CONTRACT, PUBLISHED. Spread row-by-row exactly like `beat_clock_fields`:
1368
+ // the `ok` predicates are functions and JSON drops them on the way out, so what crosses the
1369
+ // wire is the NAME, TYPE, EXPECTATION and MEANING — everything a consumer needs to build a
1370
+ // conforming call, and nothing it could not execute anyway. Spreading rather than picking
1371
+ // named keys also keeps these rows deep-equal to their exports, which is what makes the
1372
+ // conformance test able to notice a list that stopped being published.
1373
+ contract_read_fields: CONTRACT_READ_FIELDS.map((f) => ({ ...f })),
1374
+ contract_read_field_names: [...CONTRACT_READ_FIELD_NAMES],
1375
+ grounding_fields: GROUNDING_FIELDS.map((f) => ({ ...f })),
1376
+ grounding_read_kinds: [...GROUNDING_READ_KINDS],
1377
+ grounding_required_read_kind: GROUNDING_REQUIRED_READ_KIND,
1378
+ grounding_kb_read_fields: GROUNDING_KB_READ_FIELDS.map((f) => ({ ...f })),
1379
+ grounding_kb_read_field_names: [...GROUNDING_KB_READ_FIELD_NAMES],
1380
+ grounding_role_read_fields: GROUNDING_ROLE_READ_FIELDS.map((f) => ({ ...f })),
1381
+ grounding_role_read_field_names: [...GROUNDING_ROLE_READ_FIELD_NAMES],
1382
+ grounding_verification_fields: GROUNDING_VERIFICATION_FIELDS.map((f) => ({ ...f })),
1383
+ grounding_verification_field_names: [...GROUNDING_VERIFICATION_FIELD_NAMES],
1384
+ grounding_verdicts: [...GROUNDING_VERDICTS],
1385
+ grounding_flag_fields: GROUNDING_FLAG_FIELDS.map((f) => ({ ...f })),
1386
+ grounding_flag_field_names: [...GROUNDING_FLAG_FIELD_NAMES],
1387
+ grounding_flag_dispositions: [...GROUNDING_FLAG_DISPOSITIONS],
1388
+ grounding_flag_resolution_required_for: [...GROUNDING_FLAG_RESOLUTION_REQUIRED_FOR],
1389
+ // TOP-LEVEL, not nested under a `refusal_codes` object: a client generating its mirror
1390
+ // walks the payload's arrays, and a list hidden inside an object is a list it would
1391
+ // hand-type — the exact drift this verb exists to close.
1392
+ contract_refusal_codes: [...FABRIC_CONTRACT_REFUSAL_CODES],
1393
+ grounding_refusal_codes: [...FABRIC_GROUNDING_REFUSAL_CODES],
1394
+ verdicts: { ...VERDICT },
1395
+ defaults: {
1396
+ liveness_threshold_s: DEFAULT_LIVENESS_THRESHOLD_S,
1397
+ inbox_limit: DEFAULT_INBOX_LIMIT,
1398
+ lease_ttl_s: DEFAULT_LEASE_TTL_S,
1399
+ heartbeat_census_limit: HEARTBEAT_CENSUS_LIMIT,
1400
+ },
1401
+ };
1402
+ }