@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,902 @@
1
+ /**
2
+ * @descix/platform-api/mcp-tools — Shared native (core) MCP tool definitions.
3
+ *
4
+ * WS-MCP-SSOT-TIER2 (CEO-D-2026-06-06-SSOT-TIER2-DESIGN-APPROVED, audit §5.B-1):
5
+ * THE single source of truth for the curated CORE MCP tools that are advertised over
6
+ * BOTH MCP transports:
7
+ * - stdio (descix-cli/bin/mcp-server.js — Cursor / Claude Desktop)
8
+ * - HTTP/Streamable (DeSciX_Cloud apiFront.js tools/list — the Claude.ai connector)
9
+ *
10
+ * Before this module these two lists were hand-duplicated in mcp-server.js TOOLS[] and
11
+ * Cloud services/nativeMcpTools.js NATIVE_MCP_TOOLS — they drifted. They now both import
12
+ * NATIVE_MCP_TOOLS from here. The duplicated curated literal is GONE.
13
+ *
14
+ * LEAF MODULE — INFRASTRUCTURE-FREE BY DESIGN:
15
+ * This file pulls in NO infrastructure (no cloud-core, no googleapis, no GCP client). It
16
+ * is pure data so the thin CLI stdio server can import it via the
17
+ * '@descix/platform-api/mcp-tools' subpath WITHOUT dragging GCP infrastructure into the
18
+ * CLI process.
19
+ * The ONLY imports permitted here are other PURE, ZERO-IMPORT LEAVES in this same
20
+ * directory (today: chatMedia.js), and only so a schema can be BUILT FROM the contract it
21
+ * advertises instead of restating it — a hand-restated schema is the schema-mirror drift
22
+ * the engineering-culture mandate forbids, and it drifts silently. Anything that reaches
23
+ * for a network, a filesystem or a cloud SDK does not belong in this import list.
24
+ *
25
+ * SCHEMA (CEO-approved):
26
+ * each entry = { name, description, inputSchema, mutating, oauthReadonly? }
27
+ * - inputSchema : plain JSON-Schema (type:'object').
28
+ * - mutating : true => write/admin/on-chain; excluded from the OAuth read-only
29
+ * surface (the security-owned policy READS this; it does not author it).
30
+ * - oauthReadonly (advisory): EVP's recommendation that a read tool be added to the
31
+ * security-owned OAUTH_READONLY_TOOLS allow-list. The security lane owns
32
+ * the actual policy; this flag is a coordination signal, not enforcement.
33
+ *
34
+ * CLI-ONLY tools (descix_doctor, platform_health) are intentionally ABSENT here — they are
35
+ * local CLI diagnostics, NOT /apifront commands, so they are concatenated by the stdio
36
+ * server only and never advertised over HTTP. (Audit §2.ii-a.)
37
+ *
38
+ * Every entry MUST be a real command in DeSciX_Cloud commandHandlers/registry.js.
39
+ */
40
+
41
+ import { mediaParamSchema } from './chatMedia.js';
42
+ // RESIDUAL 16 — the filter contract sentence is GENERATED from the operator vocabulary,
43
+ // never typed here. A description that names operators by hand drifts off the evaluator
44
+ // the first time one is added; records-query-counts-contract.test.js makes that a CI failure.
45
+ import { filterOperatorClause, SCALAR_FILTER_OPERATORS, ARRAY_FILTER_OPERATORS } from './recordFilter.js';
46
+ // The coordination fabric's vocabulary, from its ONE owner. Every fabric_* enum and every numeric
47
+ // default below is INTERPOLATED from these exports rather than retyped: the enum a caller is shown
48
+ // here and the enum DeSciX_Cloud's fabricStore.js accepts must be the same list, or a caller is
49
+ // refused against a contract it was never given. `fabric-vocabulary-conformance.test.js` fails CI
50
+ // if any schema enum below stops deep-equalling its source. ../fabric/vocab.js is a pure,
51
+ // zero-import leaf, so this import respects the infrastructure-free rule above.
52
+ import {
53
+ BEAT_STATUSES, LEGACY_WORKING_STATUSES, LEGACY_STOP_STATUSES, LIVENESS_VALUES,
54
+ WRITE_MODES, WATERMARK_WRITE_MODES, WAKE_EXEMPT_STATUSES, WATERMARK_FIELDS, ENVELOPE_STATUSES, ENVELOPE_STATUS_DEFAULT, TO_AGENT_SENTINELS,
55
+ ENVELOPE_SECTIONS, ENVELOPE_TEXT_SHAPE, ENVELOPE_PHASES, ENVELOPE_PHASE_DEFAULT, ENVELOPE_PHASE_TRANSITIONS,
56
+ FABRIC_RECORD_KINDS,
57
+ RETIRED_SENTINELS, BEAT_CLOCK_FIELDS, beatClockFieldFor, beatClockAgeField,
58
+ LIVENESS_MODEL, LIVENESS_PROCESS, WAKE_REQUIRED_LIVENESS, STATUS_WRITER_LIVENESS,
59
+ KEY_CONTRACT, KEY_GROUNDING,
60
+ CONTRACT_READ_FIELD_NAMES, GROUNDING_KB_READ_FIELD_NAMES, GROUNDING_ROLE_READ_FIELD_NAMES,
61
+ GROUNDING_READ_KINDS, GROUNDING_REQUIRED_READ_KIND, GROUNDING_VERIFICATION_FIELD_NAMES,
62
+ GROUNDING_VERDICTS, GROUNDING_FLAG_FIELD_NAMES, GROUNDING_FLAG_DISPOSITIONS,
63
+ GROUNDING_FLAG_RESOLUTION_REQUIRED_FOR,
64
+ } from '../fabric/vocab.js';
65
+
66
+ /**
67
+ * The beat-clock pair, as prose, INTERPOLATED from the vocabulary's table — never hand-typed.
68
+ *
69
+ * Two tool descriptions state this contract (the writer's and the reader's) and two hand-typed
70
+ * copies drift the moment the table does. The field NAMES come out of BEAT_CLOCK_FIELDS, so
71
+ * renaming a clock in the vocabulary renames it in everything a caller is shown.
72
+ */
73
+ const BEAT_CLOCK_RULE = 'THE CLOCK PAIR: '
74
+ + BEAT_CLOCK_FIELDS.map((f) => `\`${f.field}\` (set by a "${f.written_by}" beat, PRESERVED by a "${f.preserved_by}" beat) — ${f.meaning}`).join(' ')
75
+ + ' Two writers share this ONE record — an agent and the plugin\'s doorbell hook — so ONE shared field could not hold both facts: the hook beats ~15x more often, its value was always the current one, and every correctly-armed seat read UNDETERMINED (measured 2026-08-24T21:37Z). Each writer now has its OWN clock and neither touches the other\'s. Both are FLAT record fields, so a raw reader may name them in a `fields` projection.';
76
+
77
+ /**
78
+ * The three-probe seat-existence rule, in ONE string, because three tool descriptions state it and
79
+ * three hand-typed copies of a rule drift the moment the rule does. The rule itself lives in
80
+ * `fabricStore.resolveSeat`; this is the prose the caller is shown, and it must not describe a
81
+ * narrower test than the server actually runs. It DID: two descriptions said "must resolve against
82
+ * the live seat-name roster", which is only probe A — and probe A alone was measured refusing a
83
+ * live, working, addressed seat (heartbeat-JARVIS-FRAQTL-4fa842fb) its own mail.
84
+ */
85
+ const SEAT_RESOLUTION_RULE =
86
+ 'Resolved by THREE probes and refused only when all three miss: a seat-name roster record, OR a '
87
+ + 'heartbeat under the label, OR any record already addressed to it. The roster alone is NOT the '
88
+ + 'test — a live, working, addressed seat with no roster record resolves.';
89
+
90
+ /**
91
+ * THE (model, thinking) PRECEDENCE CHAIN — stated ONCE, interpolated into every param that
92
+ * participates in it. Three docstrings describing one chain in three sentences is how a served
93
+ * contract drifts from the code, and it already had: this text used to say the level outranked the
94
+ * KB override while Cloud's resolver ranked the KB override HIGHER, so an explicit
95
+ * intelligence_level:1 ran on the KB's model carrying level 1's thinking setting.
96
+ *
97
+ * The Cloud-side owner is geminiInteractions.js::resolveModelThinkingPair.
98
+ */
99
+ export const MODEL_THINKING_CHAIN =
100
+ 'PRECEDENCE — the model and the thinking setting are ONE pair and always come from the SAME '
101
+ + 'tier; the first tier that states a model supplies both: (1) intelligence_level named on THIS '
102
+ + 'request, (2) the KB model override, (3) the app default model, (4) the platform default — the '
103
+ + "KB's own intelligence_level, else the platform default level, else the platform default model. "
104
+ + 'A tier that states a model but no thinking setting sends NO thinking directive and the '
105
+ + 'provider decides; a thinking setting is never inherited onto a model it was not declared with.';
106
+
107
+ export const NATIVE_MCP_TOOLS = Object.freeze([
108
+ {
109
+ name: 'query_knowledge_base',
110
+ description: 'Vector-similarity search over a DeSciX knowledge base, returning raw source chunks with dereferenceable citations. ' +
111
+ 'Use it when the user wants primary-source passages, citations, or evidence from DeSciX research/community content, ' +
112
+ 'to ground or check an ask_question_to_app answer, or to pull the exact source behind a claim before contesting it. ' +
113
+ 'Proof chains can run deep — keep retrieving cited steps rather than predicting them. ' +
114
+ 'Scope to a single source with file_filter. ' +
115
+ 'RETRIEVAL vs ANSWER: this tool RETRIEVES (raw chunks, no model synthesis, no conversation thread); ' +
116
+ 'ask_question_to_app ANSWERS (synthesized, cited, stateful). Reach for this one when you intend to read and judge the sources yourself. ' +
117
+ 'PARAMETER NAMING: this tool names the knowledge base `kb_id`/`kb_ids`; ask_question_to_app names the SAME concept ' +
118
+ '`knowledgebase_name`/`knowledgebase_names`. They are not interchangeable — passing the other tool\'s name is now REJECTED, not ignored.',
119
+ mutating: false,
120
+ oauthReadonly: true,
121
+ inputSchema: {
122
+ type: 'object',
123
+ properties: {
124
+ app_id: { type: 'string', description: 'App ID' },
125
+ kb_id: { type: 'string', description: 'KB name (default: General)' },
126
+ kb_ids: { type: 'array', items: { type: 'string' }, description: 'Optional: search several of the app\'s knowledge bases at once — the top chunks are pooled from all of them. Takes precedence over kb_id when both are given; a single "*" element searches every KB in the app.' },
127
+ query: { type: 'string', description: 'Search query' },
128
+ limit: { type: 'number', description: 'Max results (default: 5)' },
129
+ file_filter: { type: 'string', description: 'Optional: restrict the search to ONE source document. Takes the retrievable file id a citation exposes as file_path (e.g. "corpus:3e1d5aa3"), not the human-readable file_name — applied as an exact metadata match. This is the param the read_command on every citation supplies.' },
130
+ },
131
+ required: ['app_id', 'query'],
132
+ },
133
+ },
134
+ {
135
+ name: 'ask_question_to_app',
136
+ description: "Ask a natural-language research question against a DeSciX app/community knowledge base (RAG) and get a synthesized, citable answer drawn from that community's own sources. " +
137
+ "Use it as a primary research source whenever the user asks about decentralized science, open science, decentralized IP, or a specific DeSciX community (e.g. DAITA, EGPT) — including when the user has not named DeSciX but the question falls in these domains. " +
138
+ "It retrieves and cites the community's material rather than answering from general memory. " +
139
+ "Conversations are stateful: pass the interaction_id returned by the previous response as previous_interaction_id and the app remembers the earlier turns — you do NOT resend the transcript. " +
140
+ "Do not use it for general-knowledge questions answerable without it. " +
141
+ "ANSWER vs RETRIEVAL: this tool ANSWERS (model-synthesized over the app's own sources, cited, stateful); " +
142
+ "query_knowledge_base RETRIEVES (raw chunks, no synthesis, stateless). Use that one to check or ground an answer from this one. " +
143
+ "PARAMETER NAMING: name the knowledge base with `knowledgebase_name` (or `knowledgebase_names` for several). " +
144
+ "`kb_id` is query_knowledge_base's name for the same concept and is NOT accepted here — it is now REJECTED with a suggestion rather than silently ignored. " +
145
+ "Omit the KB entirely to use the app's configured default KB.",
146
+ mutating: false,
147
+ oauthReadonly: true,
148
+ inputSchema: {
149
+ type: 'object',
150
+ properties: {
151
+ app_id: { type: 'string', description: 'App ID to query' },
152
+ knowledgebase_name: { type: 'string', description: 'KB name (default: General)' },
153
+ knowledgebase_names: { type: 'array', items: { type: 'string' }, description: 'Optional: draw the answer from several of the app\'s knowledge bases fused together in one call. The FIRST name is the primary KB whose voice and model settings shape the reply. Takes precedence over knowledgebase_name when both are given; a single "*" element means every KB in the app.' },
154
+ user_input: { type: 'string', description: 'The question to ask' },
155
+ previous_interaction_id: { type: 'string', description: 'The interaction_id returned by a previous response, to continue that conversation thread with full server-side memory of the earlier turns. Omit for the first message. It is scoped to the authenticated caller and is rejected if it belongs to someone else or has expired — on rejection, start a fresh thread by omitting it.' },
156
+ // ws-mcp-surface-basics (CEO-D-2026-08-14, FLAG-1 ruling): the schema IS the
157
+ // self-describing feed into MCP, so an under-declared contract is the bug — not
158
+ // the caller who passes a param the command genuinely honors. Every property
159
+ // below is read by the handler (ragCommands.js ask_question_to_app destructures
160
+ // the generation knobs; communityManagement.js prepare_chat_context reads the
161
+ // document-scoping ones). Declared so strict validation admits them.
162
+ intelligence_level: { type: 'number', description: 'Intelligence level 1-5. A level selects a (model, thinking) PAIR, not just a model tier — higher levels cost more AI credits. ' + MODEL_THINKING_CHAIN },
163
+ model: { type: 'string', description: 'Explicit model name. It overrides the whole chain below, and because you changed the model it carries NO inherited thinking setting — pass thinking_budget too if this model needs one. Prefer intelligence_level unless you need one specific model. ' + MODEL_THINKING_CHAIN },
164
+ thinking_budget: { type: 'number', description: 'Thinking-token budget for THIS call: -1 dynamic, 0 off, N a fixed cap. It is the request tier\'s thinking statement and wins over whatever the chain resolved. Omit to take the thinking setting from the same tier that supplied the model. ' + MODEL_THINKING_CHAIN },
165
+ temperature: { type: 'number', description: 'Generation temperature override. Omit to inherit the KB/platform default.' },
166
+ max_output_tokens: { type: 'number', description: 'Cap on generated tokens for this call. Omit to inherit the KB/platform default.' },
167
+ streaming: { type: 'boolean', description: 'Stream the reply instead of returning it whole. Leave unset/false over MCP tools/call, which returns a single result — this exists for the streaming transports (PWA/Discord).' },
168
+ file_id: { type: 'string', description: 'Scope the answer to ONE source document by its file_id (as returned in a citation). Use it to ask follow-up questions against a specific paper or record.' },
169
+ ipdoc_file_id: { type: 'string', description: 'Scope to a specific IPDoc by file_id. Takes precedence over file_id when both are given.' },
170
+ doc_ids: { type: 'array', items: { type: 'string' }, description: 'Additional document ids whose full contents are added to this call\'s context (beyond what vector retrieval selects).' },
171
+ // ws-chat-multimodal-image-attach: images/video the model actually LOOKS AT.
172
+ // The schema fragment is BUILT from the chatMedia contract (kinds, MIME
173
+ // vocabulary, byte caps) rather than restated here — one owner for the
174
+ // advertised contract and the enforced policy, so the two cannot drift.
175
+ media: mediaParamSchema(),
176
+ // ws-c3-librarian: a WORKSTREAM is a conversational room (the Discord room model
177
+ // generalised), so its thread owner is SERVER-derived from the id the caller
178
+ // names — never from a caller-supplied owner, which apiFront still strips.
179
+ workstream_id: { type: 'string', description: "The workstream this question belongs to. When present, the answer runs on a thread OWNED BY THAT WORKSTREAM rather than by the calling user: the server derives the thread owner as roomThreadKey({surface:'workstream', room_id:workstream_id, app_id}) - e.g. 'unk-beast:workstream-ws-c3-librarian' - and stores continuity server-side in the InteractionRooms collection. Send the SAME workstream_id every turn and omit previous_interaction_id; the response's interaction_id is an ECHO for observability, not a handle to resend. A workstream thread is SHARED BY DESIGN: every caller naming the same workstream on the same app continues the same conversation. It is NOT a private per-user conversation and carries no per-user privacy property. A client-supplied interaction_owner_id remains stripped at the door and is not a substitute for this param." },
180
+ },
181
+ required: ['app_id', 'user_input'],
182
+ },
183
+ },
184
+ {
185
+ name: 'list_apps_for_community',
186
+ description: 'List apps in a community',
187
+ mutating: false,
188
+ oauthReadonly: true,
189
+ inputSchema: {
190
+ type: 'object',
191
+ properties: { community_id: { type: 'string', description: 'Community ID' } },
192
+ required: ['community_id'],
193
+ },
194
+ },
195
+ {
196
+ name: 'find_communities',
197
+ // R5 (CEO-D-2026-07-14 disambiguation): this lists ONLY LISTED communities for a normal
198
+ // caller (the app store). "Listed" is the ACCESS sense (a separate `tradeable` boolean owns
199
+ // token-tradeability — the old `is_public` conflated them). Non-listed communities you own
200
+ // or that are shared with you remain reachable via fetch_my_purchases. The `listed` filter is
201
+ // enforced server-side in the Cloud handler; admin callers see all.
202
+ description: 'List the communities listed in the app store. Communities you own or that are shared with you are reachable via fetch_my_purchases even when they are not listed.',
203
+ mutating: false,
204
+ oauthReadonly: true,
205
+ inputSchema: {
206
+ type: 'object',
207
+ properties: { filter: { type: 'string', description: 'Optional filter string' } },
208
+ },
209
+ },
210
+ {
211
+ name: 'tell_me_how',
212
+ description: 'Discover platform tools and services by asking a natural language question. Searches the service mesh for relevant capabilities; results include callable schemas and an invocation envelope. Call with scope "bootstrap" FIRST on a new session: it deterministically returns the platform summary, your caller context, credit balance, and the essential tools. Ask it in plain language to set up or onboard to DeSciX (e.g. "set up DeSciX", "help me get started") and it returns a structured setup playbook you can walk the user through. Asking about a SPECIFIC app or community? Pass project_context with its ids and scope "project" — the vector search is restricted to them. Asking how to BUILD ON or reproduce an app (npm package, artifact pages, notebooks, runnable benchmarks)? Use scope "artifact", which answers deterministically from the app registry with no vector search. If results are empty, try scope "discovery" or rephrase.',
213
+ mutating: false,
214
+ oauthReadonly: true,
215
+ inputSchema: {
216
+ type: 'object',
217
+ properties: {
218
+ question: { type: 'string', description: 'What do you want to do? Required for every scope except "bootstrap".' },
219
+ // WS-MVP-FIRSTCONTACT F3: 'bootstrap' = deterministic first-contact on-ramp
220
+ // (no vector search). question becomes optional for that scope only; the
221
+ // server still hard-requires it for project/entitlements/discovery.
222
+ //
223
+ // THE ENUM IS THE CONTRACT AND IT MUST MATCH THE HANDLER. Measured on dev
224
+ // 2026-08-18, three hand-maintained copies of this list disagreed three ways
225
+ // (handler 6 scopes, this enum 4, the CLI 3), and the disagreement was not
226
+ // cosmetic: 'project' was advertised here while `project_context` was ABSENT from
227
+ // properties, so the param guard — which derives its accepted set from
228
+ // Object.keys(inputSchema.properties) — rejected the one parameter the scope
229
+ // requires. Every caller selecting it got an unconditional error from every
230
+ // surface. Meanwhile 'artifact' WORKED and was undiscoverable. Adding a scope
231
+ // here without its parameters ships a capability nobody can reach.
232
+ //
233
+ // 'admin' is DELIBERATELY EXCLUDED, not forgotten: it is fail-closed to
234
+ // platform-admins (communityCommands tell_me_how returns ADMIN_REQUIRED to
235
+ // everyone else), so advertising it to every external caller would only publish a
236
+ // door none of them can open.
237
+ scope: {
238
+ type: 'string',
239
+ enum: ['bootstrap', 'artifact', 'project', 'entitlements', 'discovery'],
240
+ description: '"bootstrap" = deterministic first-call on-ramp (platform summary + caller context + credit balance + essential tool schemas), "artifact" = deterministic build/reproduce provenance for published apps (npm package + spec, jsdelivr artifact and notebook URLs, runnable npx commands) with no vector search, "project" = restrict the search to the communities/apps named in project_context, "entitlements" = your purchased tools, "discovery" = all platform capabilities. Default: entitlements.',
241
+ },
242
+ // OPT-IN, default OMITTED. `context` is the concatenated raw text of every
243
+ // matched service doc — measured 18,299 B of a 52,409 B reply (35%), duplicating
244
+ // in prose the same information the structured recommended_tools rows already
245
+ // carry. A discovery call should not spend a third of its payload on that unless
246
+ // the caller asks. Declared here for the same reason as project_context: the
247
+ // gateway guard accepts exactly the keys this bag names.
248
+ include_context: {
249
+ type: 'boolean',
250
+ description: 'Include the raw concatenated service-documentation text the answer was drawn from. Default false — the structured recommended_tools rows carry the same information in a form you can act on. Set true when you want the underlying prose to quote or verify against.',
251
+ },
252
+ // REQUIRED by scope 'project' — and it must be declared HERE, because the
253
+ // gateway param guard accepts exactly the keys this properties bag names.
254
+ project_context: {
255
+ type: 'object',
256
+ description: 'Scope the search to specific communities/apps. Required when scope is "project"; ignored otherwise. Supply at least one non-empty list.',
257
+ properties: {
258
+ community_ids: { type: 'array', items: { type: 'string' }, description: 'Community ids to restrict the search to, e.g. ["egpt"].' },
259
+ app_ids: { type: 'array', items: { type: 'string' }, description: 'App ids to restrict the search to, e.g. ["egpt-godsworld"].' },
260
+ },
261
+ },
262
+ },
263
+ },
264
+ },
265
+ {
266
+ name: 'resolve_invite',
267
+ description: 'Resolve a DeSciX invite token into app configuration. Returns app context, community info, and the agent_hint authored by the app creator (skill level + goals).',
268
+ mutating: false,
269
+ // WS-MCP-SURFACE-SPLIT-EXEC §6.7 D6: this tool is NOT in the enforced
270
+ // OAUTH_READONLY_TOOLS allow-list (oauthAsHandlers.js) — the oauthReadonly:true
271
+ // advisory flag had drifted from the enforced policy and was removed to stop
272
+ // implying enforcement that does not exist.
273
+ inputSchema: {
274
+ type: 'object',
275
+ properties: { invite_token: { type: 'string', description: 'The invite token from .descix/app.json' } },
276
+ required: ['invite_token'],
277
+ },
278
+ },
279
+ {
280
+ name: 'app_records_put',
281
+ description: 'Use your app like a database: store/replace structured records with custom metadata in the app data plane (Firestore-backed, strongly consistent — NOT the Pinecone KB). Supply a human-meaningful file_id (grouping key) + optional chunk_idx (default 0); the composite id is built for you. Custom string/number/boolean/string[] fields become filterable metadata for app_records_query (a string[] field is filtered with ' + ARRAY_FILTER_OPERATORS[0] + ', not with equality). Pass mode:"create" for an atomic first-claim-wins conditional create (answers claimed:true / claimed:false + current_holder_hint instead of overwriting). Records under a "lease-" key are holder-verified server-side. TIME: every record is stamped with a server-authoritative received_at — the store\'s own UTC clock at the moment it accepted the write. It is server-owned: a client-supplied received_at is stripped and replaced, so do not send one. Any created_at you send is ordinary client-asserted metadata with no more authority than text — the store neither validates nor corrects it. CONTENT HASH: every put returns content_sha256 — the sha256 of the record\'s STORED TEXT ONLY (the `text` field), hex, so you can verify delivery by recomputing it yourself over the text you sent. A record with NO text field returns null, which is deliberately NOT the hash of the empty string: "no text" and "empty text" are different facts. A single-record put returns the scalar content_sha256; every put also returns content_sha256_by_file_id keyed by file_id. IDEMPOTENCE: a SINGLE-RECORD upsert whose whole stored payload is already byte-identical performs NO WRITE and answers unchanged:true with unchanged_file_ids — so received_at does NOT advance and a retry cannot manufacture a fake "the store accepted something" event. The comparison is the WHOLE record, not just the text: a put that changes only metadata still writes, because deciding from the text hash alone would silently drop it. THREE EXCEPTIONS, where the WRITE ITSELF IS THE SIGNAL and an identical repeat therefore STILL writes and STILL advances received_at: keys prefixed "lease-", "heartbeat-" and "watermark-". received_at remains "when the store last ACCEPTED a write" for those classes, which is what liveness and the inbox time-floor read. A MULTI-RECORD put is never deduplicated — the bulk path writes blind by design so a KB sync writing thousands of chunks does not pay for a read-before-write.',
282
+ mutating: true,
283
+ inputSchema: {
284
+ type: 'object',
285
+ properties: {
286
+ app_id: { type: 'string', description: 'App ID (your app)' },
287
+ kb_id: { type: 'string', description: 'Record collection ID (acts like a database table)' },
288
+ records: { type: 'array', description: 'Records to upsert: [{ file_id (required), text?, chunk_idx? (default 0), ...customMetadata }]. Pass a full "id" only for back-compat.', items: { type: 'object' } },
289
+ mode: {
290
+ type: 'string',
291
+ enum: ['upsert', 'create'],
292
+ description: '"upsert" (default) merge-writes, last writer wins. "create" is a CONDITIONAL CREATE: atomic and all-or-nothing — every key must be unclaimed, and if any exists nothing is written and the response is { success:false, claimed:false, current_holder_hint, conflicts }. Use it to elect a single holder of a named resource (lease, seat, idempotency key). Capped at 450 records per call.',
293
+ },
294
+ },
295
+ required: ['app_id', 'kb_id', 'records'],
296
+ },
297
+ },
298
+ {
299
+ name: 'app_records_query',
300
+ description: 'Query your app like a database: a STRUCTURED, metadata-filtered scan (NOT ANN/semantic) over the app data plane returning ALL records matching a predicate (e.g. type=episode AND show=X). ' + filterOperatorClause() + ' STRONGLY CONSISTENT (read-after-write). Use ask_question_to_app for fuzzy semantic KB search. RESPONSE COUNTS are three DIFFERENT facts, so count <= matched <= scanned always: `scanned` = how many records the collection holds in total, BEFORE your filter (the denominator); `matched` = how many satisfied your filter, before `limit`; `count` = how many are in `records` (matched, capped by `limit`); `truncated` = boolean, true exactly when `count` < `matched`, i.e. `limit` CUT the match set and this reply does NOT carry every record that matched — raise `limit` (or narrow the filter) to see the rest. This lets you tell the two zero cases apart: matched:0 with scanned:0 means the COLLECTION IS EMPTY, while matched:0 with scanned:40 means YOUR PREDICATE MATCHED NOTHING (check the field name) — do not read a zero as evidence of an empty collection. TIME: returned records carry received_at, stamped by the store\'s own UTC clock when it accepted the write and therefore unforgeable by the record\'s author. Decide STALENESS and ORDERING on received_at. A created_at field, where present, is a claim made by whoever wrote the record — it is never validated, so it may be wrong or even in the future.',
301
+ mutating: false,
302
+ // WS-MCP-SURFACE-SPLIT-EXEC §6.7 D6: this tool is NOT in the enforced
303
+ // OAUTH_READONLY_TOOLS allow-list (oauthAsHandlers.js) — the oauthReadonly:true
304
+ // advisory flag had drifted from the enforced policy and was removed to stop
305
+ // implying enforcement that does not exist.
306
+ inputSchema: {
307
+ type: 'object',
308
+ properties: {
309
+ app_id: { type: 'string', description: 'App ID' },
310
+ kb_id: { type: 'string', description: 'Record collection ID' },
311
+ filter: { type: 'object', description: `Metadata predicate. Scalar fields: ${SCALAR_FILTER_OPERATORS.join('/')} or a bare value; ARRAY fields: ${ARRAY_FILTER_OPERATORS[0]} (membership). e.g. { "type": "episode", "show": { "$eq": "X" }, "tags": { "${ARRAY_FILTER_OPERATORS[0]}": "handoff" } }` },
312
+ fields: { type: 'array', items: { type: 'string' }, description: 'Projection of metadata fields (omit or ["*"] for all)' },
313
+ limit: { type: 'number', description: 'Max records (post-filter)' },
314
+ },
315
+ required: ['app_id', 'kb_id'],
316
+ },
317
+ },
318
+ {
319
+ name: 'app_records_get',
320
+ description: 'Fetch specific records from your app data plane by id (or by file_id grouping key — id == file_id in this store) with an arbitrary metadata projection. Firestore-backed, strongly consistent. Supply at least one of ids/file_ids. TIME: returned records carry received_at, stamped by the store\'s own UTC clock when it accepted the write and therefore unforgeable by the record\'s author — read it for staleness and ordering. A created_at field, where present, is the author\'s own unvalidated claim. Note that a projection via `fields` drops received_at unless you ask for it.',
321
+ mutating: false,
322
+ // WS-MCP-SURFACE-SPLIT-EXEC §6.7 D6: this tool is NOT in the enforced
323
+ // OAUTH_READONLY_TOOLS allow-list (oauthAsHandlers.js) — the oauthReadonly:true
324
+ // advisory flag had drifted from the enforced policy and was removed to stop
325
+ // implying enforcement that does not exist.
326
+ inputSchema: {
327
+ type: 'object',
328
+ properties: {
329
+ app_id: { type: 'string', description: 'App ID' },
330
+ kb_id: { type: 'string', description: 'Record collection ID' },
331
+ ids: { type: 'array', items: { type: 'string' }, description: 'Record ids to fetch' },
332
+ file_ids: { type: 'array', items: { type: 'string' }, description: 'file_id grouping keys to fetch (id == file_id in this store)' },
333
+ fields: { type: 'array', items: { type: 'string' }, description: 'Projection of metadata fields (omit or ["*"] for all)' },
334
+ },
335
+ // `ids` is NOT in required, exactly as on app_records_delete: either ids or file_ids
336
+ // satisfies this call, which plain JSON-Schema `required` cannot express. The handler
337
+ // (appDataStore.getRecords) is the authority and refuses "neither supplied" loudly,
338
+ // naming both params. Requiring `ids` here would reject the file_ids-only call this
339
+ // schema exists to legalize.
340
+ required: ['app_id', 'kb_id'],
341
+ },
342
+ },
343
+ {
344
+ name: 'app_records_delete',
345
+ description: 'Delete records from your app data plane by id (or by file_id grouping key). Firestore-backed.',
346
+ mutating: true,
347
+ inputSchema: {
348
+ type: 'object',
349
+ properties: {
350
+ app_id: { type: 'string', description: 'App ID' },
351
+ kb_id: { type: 'string', description: 'Record collection ID' },
352
+ ids: { type: 'array', items: { type: 'string' }, description: 'Record ids to delete' },
353
+ file_ids: { type: 'array', items: { type: 'string' }, description: 'file_id grouping keys to delete (deletes all records with each file_id)' },
354
+ },
355
+ required: ['app_id', 'kb_id'],
356
+ },
357
+ },
358
+ // ─────────────────────────────────────────────────────────────────────────────────────────
359
+ // COORDINATION FABRIC — typed verbs over the app-records collection egpt-frqtl/coordination.
360
+ //
361
+ // These exist because every rule that keeps the fabric coherent used to live CLIENT-side in
362
+ // the unkamon-beast plugin's PreToolUse guard: the CLI bypassed it entirely, and it was a
363
+ // second derivation of the store's semantics. The rules are now server-side and hold on every
364
+ // transport. Server implementation: DeSciX_Cloud microservice/services/fabricStore.js;
365
+ // vocabulary: descix-platform-api/src/fabric/vocab.js. Contract: docs/design/coordination-fabric-contract-2026-08-24.md.
366
+ //
367
+ // THREE TRAPS EVERY DESCRIPTION BELOW RESTATES, because a caller who does not know them
368
+ // writes something that succeeds and is never read:
369
+ // · `received_at` is SERVER-stamped and unforgeable; `created_at` on an ordinary record is
370
+ // caller-asserted and never validated. Every liveness and ordering decision uses received_at.
371
+ // · No fabric_* verb accepts app_id/kb_id (the fabric is ONE collection by contract) or
372
+ // `fields` (a projection silently drops received_at).
373
+ // · A BROADCAST IS NEVER FLIPPED to read — its status is shared across every seat.
374
+ // ─────────────────────────────────────────────────────────────────────────────────────────
375
+ {
376
+ name: 'fabric_beat',
377
+ description: 'Write this seat\'s coordination heartbeat — liveness as ONE fact with ONE write. The key is DERIVED by the server as "heartbeat-<seat_label>-<session8>"; a client-supplied file_id/key is REFUSED, because three key shapes coexist on the live fabric from callers choosing their own and one session was measured publishing two labels with contradictory statuses. The clock is the SERVER\'s (`occurred_at`): a caller-supplied created_at/occurred_at/received_at is REFUSED, not ignored — beats were measured stale by 44 and 658 minutes and one 41 minutes in the FUTURE, all stamped fresh by the store. `status` is a CLOSED ENUM: '
378
+ + BEAT_STATUSES.join(', ')
379
+ + '. "unread" and "broadcast" are refused BY NAME for the inbox collision they cause (a live heartbeat has sat unread in its master\'s inbox for 35 hours and its seat is dead, so nothing will ever clear it). `status` IS A MODEL-WRITER\'S FIELD: it is REQUIRED from the "'
380
+ + STATUS_WRITER_LIVENESS
381
+ + '" writer and OMITTED by every other writer, whose stored status is PRESERVED. A hook proves a PROCESS is alive and cannot know what the model is doing, so requiring a status from it forces it to invent one — and what it invents is whatever it last read, which is how a seat\'s good-night gets overwritten by a stale carried "working" in the seat\'s own voice. A beat must never assert something its own writer did not observe. `liveness` is REQUIRED and says WHO wrote this beat — an agent ("'
382
+ + LIVENESS_VALUES[0] + '") or a hook ("' + LIVENESS_VALUES[1]
383
+ + '"). It is written on every beat and never inherited: a hook beating on a dead model is a mask that reports health while nobody is home. It says WHO WROTE LAST and is NOT the model\'s clock. '
384
+ + BEAT_CLOCK_RULE
385
+ + ' `wake` IS REQUIRED ONLY FROM THE "'
386
+ + WAKE_REQUIRED_LIVENESS
387
+ + '" WRITER, and on a WORKING beat as much as a resting one — without it "I am still going" is unfalsifiable and a seat goes dark while looking busy. A beat whose status is TERMINAL ('
388
+ + WAKE_EXEMPT_STATUSES.join(', ')
389
+ + ') is EXEMPT: a seat that has declared a stop has nothing schedulable to declare, and demanding a next_fire_at from it would force it to assert a wake that cannot exist. The exemption is keyed on the SERVED terminal-status set and does NOT open the working case, which stays refused by name. A terminal beat CLEARS the stored wake chain rather than preserving it, so a finished seat does not read as permanently wake-overdue. `wake: null` IS EQUIVALENT TO OMITTING `wake` on every path — it is not a way to clear the wake block on a beat that still needs one. Every OTHER writer is EXEMPT and carries none: only an agent can say what will wake this seat, so requiring one from a hook forces it to invent an answer or not beat at all, and it did not beat — an unconditional requirement left every doorbell in the fleet refused on its first tick (measured 2026-08-27). A beat that carries no wake PRESERVES the stored wake_* fields rather than clearing them, exactly as it preserves the other writer\'s clock, and the three fields come back on the response as they now stand so you can see that without a second read. wake_overdue:true comes back when the next_fire_at IN FORCE — this beat\'s, or the preserved one — has already passed, and null when no wake has ever been recorded, which is UNKNOWN and is never false. Returns unchanged:true when the beat is identical to the stored one. Does NOT renew a BEAST seat and takes no seat_token: renewal binds to the authenticated caller under ws-seat-session-bound-auth.',
390
+ mutating: true,
391
+ inputSchema: {
392
+ type: 'object',
393
+ properties: {
394
+ seat_label: { type: 'string', description: 'The seat LABEL this session answers to (the CEO-given name it beats under).' },
395
+ session_id: { type: 'string', description: 'This session id. Normalized to its bare first 8 characters; a "seat-" prefix is stripped and the response reports the normalization.' },
396
+ status: { type: 'string', enum: [...BEAT_STATUSES], description: 'What this seat is DOING. Closed enum; legacy values (' + [...LEGACY_WORKING_STATUSES, ...LEGACY_STOP_STATUSES].join(', ') + ') are still READABLE on old records but are no longer writable. REQUIRED from the "' + STATUS_WRITER_LIVENESS + '" writer and OMITTED by every other writer, whose stored status is then PRESERVED unchanged. Only an agent knows what the model is doing: a hook proves a PROCESS is alive and would have to invent a status, and what it invents is whatever it last read — which is how a good-night gets overwritten by a stale carried "working" in the seat\'s own voice. Omit it on a "' + LIVENESS_PROCESS + '" beat; the response reports the status as it now stands so you can see it was preserved without a second read.' },
397
+ liveness: { type: 'string', enum: [...LIVENESS_VALUES], description: 'REQUIRED, no default and never inherited. "' + LIVENESS_MODEL + '" = an AGENT wrote this beat (proves the model is alive) and stamps `' + beatClockFieldFor(LIVENESS_MODEL) + '`. "' + LIVENESS_PROCESS + '" = a HOOK wrote it (proves the process is alive, says NOTHING about the model) and stamps `' + beatClockFieldFor(LIVENESS_PROCESS) + '` while PRESERVING `' + beatClockFieldFor(LIVENESS_MODEL) + '`. Omitting it is refused rather than defaulted, because a merge-upsert would silently keep the previous writer\'s value.' },
398
+ wake: {
399
+ type: 'object',
400
+ description: 'REQUIRED when liveness is "' + WAKE_REQUIRED_LIVENESS + '" AND the status is not terminal (' + WAKE_EXEMPT_STATUSES.join(', ') + '), on a working beat as much as a resting one; passing `null` is identical to omitting it; OMITTED by every other writer, whose stored wake_* fields are then PRESERVED unchanged. What will wake this seat, whether that survives the process dying, and when it next fires. Supplying one is accepted from any writer — the exemption is from being REQUIRED to answer, not from being allowed to.',
401
+ properties: {
402
+ mechanism: { type: 'string', description: 'What will wake this seat (e.g. "ScheduleWakeup", "Monitor ticker", "cron").' },
403
+ survives_death: { type: 'boolean', description: 'Does the wake mechanism outlive this process? A boolean, not a string.' },
404
+ next_fire_at: { type: 'string', description: 'ISO-8601 instant the wake next fires. A past value returns wake_overdue:true — the seat is alive while its wake chain is dead.' },
405
+ },
406
+ required: ['mechanism', 'survives_death', 'next_fire_at'],
407
+ },
408
+ text: { type: 'string', description: 'Optional one-line note about what this seat is doing.' },
409
+ workstream_id: { type: 'string', description: 'Optional workstream this seat is working. This is where a workstream id belongs — never in to_agent.' },
410
+ to_agent: { type: 'string', description: 'Optional master to address the beat to. Must be a seat LABEL or a sentinel (' + TO_AGENT_SENTINELS.join(', ') + '). ' + RETIRED_SENTINELS.join(' and ') + ' are REFUSED: no sweep has ever composed either, so a beat addressed to one was written and read by nobody. Address the master by its seat LABEL — read the current holder with beast_seat_read {seat_id:"org"}; a label names a holder and holders change, so no label is hard-coded here.' },
411
+ extra: { type: 'object', description: 'Optional additional flat metadata. A key this verb owns is refused rather than silently overwritten.' },
412
+ },
413
+ // `wake` AND `status` ARE DELIBERATELY ABSENT FROM THIS LIST, and both conditionals are
414
+ // stated in the descriptions above rather than as a JSON-Schema `if`/`then`. The
415
+ // boundary guard that enforces this schema (paramValidation.js::validateParams) reads
416
+ // the FLAT `required` array and nothing else — it does not evaluate `allOf`/`if`/`then`.
417
+ // An `if`/`then` here would be a rule no enforcer reads: a gate that cannot fail, and a
418
+ // SECOND place the requirement is written, free to drift from the one that runs. So the
419
+ // flat list states exactly what the door enforces, the verb enforces the conditional
420
+ // half (fabricStore.js, via isWakeRequiredFor and isStatusWriterFor), and both derive it
421
+ // from one owner — vocab.js::WAKE_REQUIRED_LIVENESS and ::STATUS_WRITER_LIVENESS.
422
+ //
423
+ // `status` LEAVING THIS LIST IS LOAD-BEARING, and it is the half that is invisible from
424
+ // the Cloud side. The door refuses a missing required parameter BEFORE the verb is
425
+ // reached, so a permissive store alone would ship inert while looking shipped: the
426
+ // plugin still could not stop sending status, and the fleet would stay deaf. Measured
427
+ // on ef278b0 — a status-less process beat was refused at the door with INVALID_PARAMS
428
+ // "missing required parameter 'status'", never reaching fabricStore.
429
+ required: ['seat_label', 'session_id', 'liveness'],
430
+ },
431
+ },
432
+ {
433
+ name: 'fabric_liveness',
434
+ description: 'Read a seat\'s liveness, judged on the SERVER clock. This is the repo-less liveness read: no checkout, no shell and no CLI, so it works from claude.ai / Cowork where a hook-based check has none of those. Returns verdict alive | stale | declared-stop | none, plus `' + beatClockAgeField(beatClockFieldFor(LIVENESS_MODEL)) + '` — the age of the clock the verdict was judged on, NAMED for that clock, so the age and the verdict beside it can never be two different facts. EVERY age on this response is named for the clock it measures; there is no un-named age field, so no consumer can hold a duration without knowing which clock produced it. Every other clock is reported for diagnosis and decides nothing — `' + beatClockAgeField(beatClockFieldFor(LIVENESS_PROCESS)) + '` (how long ago a HOOK beat) and `received_at_age_seconds` (when this RECORD last moved, which on a two-writer key is the hook\'s cadence). None of them is the caller-asserted created_at, which is unvalidated and is exactly what blinds a staleness sweep to the worst-maintained seats. A seat with no beat returns verdict "none", NOT an error. Runs three probes (the composed key, holder_session, and a bounded key-prefix census) and reports every disagreement between them in `defects[]` rather than silently picking a winner — that is how key sprawl and a missing holder_session are surfaced instead of hidden. Also answers the WAKE WATCHDOG without a second call: `wake_next_fire_at` and `wake_overdue` come back on every read, so "this seat says it is alive while its wake chain is already dead" is one question with one answer. THE MODEL VERDICT IS JUDGED ON `' + beatClockFieldFor(LIVENESS_MODEL) + '` AND ON NOTHING ELSE — `judged_on` says so on every response. It is NOT judged on `liveness` (which says only who wrote LAST, and the hook writes ~15x more often, so judging on it read UNDETERMINED for every correctly-armed seat) and NOT on the record\'s `received_at` (which a process beat refreshes — the mask). '
435
+ + BEAT_CLOCK_RULE
436
+ + ' `liveness` still reports WHO wrote the freshest beat and is null on a pre-contract record that carried none, which is UNKNOWN and never assumed to be an agent. A seat whose hook is beating while its agent is long gone therefore reads STALE, which is the whole point. threshold_s defaults to the platform value returned in the response.',
437
+ mutating: false,
438
+ oauthReadonly: true,
439
+ inputSchema: {
440
+ type: 'object',
441
+ properties: {
442
+ session_id: { type: 'string', description: 'The session to read. Supply this and/or label.' },
443
+ seat_label: { type: 'string', description: 'The seat label to read. Supply this and/or session_id.' },
444
+ threshold_s: { type: 'number', description: 'Seconds after which a beat counts as stale. Omit for the platform default (returned as threshold_s).' },
445
+ },
446
+ },
447
+ },
448
+ {
449
+ name: 'fabric_inbox_sweep',
450
+ description: 'THE canonical inbox sweep — what is waiting for this seat. Takes a SEAT, not a filter: the server composes to_agent IN [label, seat-<session8>, all, ALL] and status IN [unread, broadcast], and NEVER a type predicate. A caller-supplied `type` or `filter` is REFUSED — there is no parameter in which to express one, so the type-pinned sweep is structurally unreachable (measured: a hand-back filed as type "handback" was correctly addressed, correctly unread, and invisible for four days; sixteen type values are in live use and one record carries none at all, so no allow-list can be correct). `selector_applied` echoes what the server ACTUALLY used, so you never have to trust the query you believe you sent. Returns `matched` only — no bare `count`, because under limit:1 a dropped filter still reports count:1 and looks like a filtered result. WHEN THE CAP BITES YOU GET THE NEWEST N, delivered oldest-first, with truncated:true and order:"received_at asc": taking the oldest page instead made an inbox above the cap permanently unable to reach its newest mail, and nothing on the response distinguished a capped page from a complete inbox. `census_truncated` says whether the bounded scan that resolved your seat was clipped. When matched is 0 an `empty_reason` is ALWAYS present: "no_unread" means the seat resolves and its inbox is genuinely empty. An unresolvable label is a REFUSAL (unknown_seat), never an empty list — "no mail" and "no such seat" are different answers. Every record comes back WITH received_at; there is no projection parameter, because a projection silently drops the only clock a sender cannot forge. The seat\'s watermark ledger is returned alongside so a secretary can subtract what it already handed up without a second call.',
451
+ mutating: false,
452
+ oauthReadonly: true,
453
+ inputSchema: {
454
+ type: 'object',
455
+ properties: {
456
+ seat_label: { type: 'string', description: 'This seat\'s LABEL. ' + SEAT_RESOLUTION_RULE + ' An unresolvable label is refused (unknown_seat) rather than answered with an empty inbox.' },
457
+ session_id: { type: 'string', description: 'Optional session id, so mail addressed to "seat-<session8>" is included.' },
458
+ include_broadcasts: { type: 'boolean', description: 'Include org-wide broadcasts (default true). Set false for 1:1 mail only.' },
459
+ since_received_at: { type: 'string', description: 'ISO-8601 floor on the SERVER-stamped received_at. Only records the store accepted after this instant are returned — the way to stop re-reading the whole broadcast set on every sweep.' },
460
+ limit: { type: 'number', description: 'Maximum records to return; must be >= 1. Omit for the server default, which is returned as `limit_applied`. `matched` is the true pre-limit size. 0 is REFUSED — it read as "no cap", which is the opposite of what a caller asking for zero records means.' },
461
+ },
462
+ required: ['seat_label'],
463
+ },
464
+ },
465
+ {
466
+ name: 'fabric_msg_send',
467
+ description: 'Send an addressed 1:1 message on the coordination fabric. `to` is RESOLVED BEFORE THE WRITE by three probes — a seat-name roster record, a heartbeat under the label, or any record already addressed to it — and refused only when all three miss: an unresolvable recipient is REFUSED and the roster is returned, because today a message to a misspelled or retired label is accepted and read by nobody — the sender sees success and no party downstream can detect the miss. The key and clock are server-derived ("msg-<TO>-<stamp>-<FROM>-<subject>", plus a "-<n>" discriminator if that key is already taken), so the filename-safe-vs-ISO split stops being your problem; a client-supplied key, status, created_at or received_at is REFUSED. THE WRITE IS A CONDITIONAL CREATE, NEVER AN UPSERT: the key stamp is second-resolution, so two messages from one seat to one seat on one subject inside one second used to collide and SILENTLY OVERWRITE — the first message destroyed and the send still reporting success. Now a colliding key carrying a DIFFERENT message is discriminated (both survive, and key_discriminated:true says so), while an IDENTICAL re-send is refused with FABRIC_DUPLICATE_MESSAGE naming the existing key and its status — so a retry tells you the first send landed instead of duplicating mail the recipient must triage. BROADCAST IS A DIFFERENT VERB: to:"all" is refused by name pointing at fabric_broadcast_send, rather than silently becoming org-wide state that no reader may ever clear. Takes no app_id/kb_id — which is the point: app_records_put and beast_rag_ingest both accept those and a name like "unk-beast/Org" addresses a real store in EACH, so a wrong-plane write returns success and is never read.',
468
+ mutating: true,
469
+ inputSchema: {
470
+ type: 'object',
471
+ properties: {
472
+ from_seat: { type: 'string', description: 'The sending seat\'s LABEL.' },
473
+ to: { type: 'string', description: 'Recipient seat LABEL. ' + SEAT_RESOLUTION_RULE + ' An unresolvable recipient is refused WITH the roster. "all"/"ALL" is refused (use fabric_broadcast_send), as is a "ws-*" workstream id or a bare role name.' },
474
+ subject: { type: 'string', description: 'Short subject; also the human-readable tail of the key. Normalized to lowercase alphanumerics and dashes.' },
475
+ body: { type: 'string', description: 'The message body. A message is a signal, not an archive — one carrying a decision should point at the record or doc that holds it.' },
476
+ workstream_id: { type: 'string', description: 'Optional workstream this message concerns.' },
477
+ thread_id: { type: 'string', description: 'Optional thread to attach this message to. Defaults to the message\'s own key, so every message belongs to exactly one closable thread.' },
478
+ type: { type: 'string', description: 'Optional payload classifier (default "message"). NEVER used for delivery — the recipient\'s sweep does not filter on it.' },
479
+ extra: { type: 'object', description: 'Optional additional flat metadata.' },
480
+ },
481
+ required: ['from_seat', 'to', 'subject', 'body'],
482
+ },
483
+ },
484
+ {
485
+ name: 'fabric_msg_ack',
486
+ description: 'Acknowledge a 1:1 fabric message — flips unread to read ON THE RECORD, which is where 1:1 delivery state belongs so both sender and recipient read one fact, consistent across machines. REFUSES a BROADCAST by name: a broadcast\'s status is SHARED and immutable, so flipping it would silence that record for every other seat on the fabric (measured 2026-08-09) — the refusal names fabric_broadcast_ack instead. Also refuses a record addressed to a different seat: acking another seat\'s mail is a delivery it never received and cannot detect. Reports what CHANGED, not what was asked: `flipped` is true only when this call actually moved the record, and an already-read record returns flipped:false with a reason rather than a success shaped like a delivery.',
487
+ mutating: true,
488
+ inputSchema: {
489
+ type: 'object',
490
+ properties: {
491
+ key: { type: 'string', description: 'The record key to ack (from fabric_inbox_sweep).' },
492
+ seat_label: { type: 'string', description: 'The LABEL of the seat acking it. Must match the record\'s to_agent.' },
493
+ session_id: { type: 'string', description: 'Optional session id, so mail addressed to "seat-<session8>" can be acked by its holder.' },
494
+ },
495
+ required: ['key', 'seat_label'],
496
+ },
497
+ },
498
+ {
499
+ name: 'fabric_broadcast_send',
500
+ description: 'Send an org-wide broadcast. A separate verb from fabric_msg_send on purpose: a broadcast\'s status is IMMUTABLE once written — no reader may ever flip it — so org-wide state that nobody can retire must be created deliberately, never as a side effect of an address string. The key, clock, address ("all") and status ("broadcast") are all server-derived; supplying any of them is refused. Written with a CONDITIONAL CREATE, never an upsert: an overwritten broadcast is a message every seat on the fabric loses at once and none of them can discover, so a colliding key carrying a different broadcast is discriminated and an identical re-send is refused with FABRIC_DUPLICATE_MESSAGE. Each recipient records its own processing with fabric_broadcast_ack, because "has the doorbell rung" and "has THIS seat processed it" are two facts with two owners.',
501
+ mutating: true,
502
+ inputSchema: {
503
+ type: 'object',
504
+ properties: {
505
+ from_seat: { type: 'string', description: 'The broadcasting seat\'s LABEL.' },
506
+ subject: { type: 'string', description: 'Short subject; also the human-readable tail of the key.' },
507
+ body: { type: 'string', description: 'The broadcast body.' },
508
+ workstream_id: { type: 'string', description: 'Optional workstream this broadcast concerns.' },
509
+ extra: { type: 'object', description: 'Optional additional flat metadata.' },
510
+ },
511
+ required: ['from_seat', 'subject', 'body'],
512
+ },
513
+ },
514
+ {
515
+ name: 'fabric_broadcast_ack',
516
+ description: 'Record that THIS seat has processed one or more broadcasts, in this seat\'s own watermark ledger. The broadcast records themselves are never touched — that is the whole point: a broadcast\'s status is shared, so one reader flipping it deletes the message from every other seat\'s inbox. Returns `watermarked` (newly recorded) separately from `already_seen`, and issues NO write when nothing is new, so a re-ack cannot re-stamp a ledger that did not move.',
517
+ mutating: true,
518
+ inputSchema: {
519
+ type: 'object',
520
+ properties: {
521
+ seat_label: { type: 'string', description: 'The acknowledging seat\'s LABEL.' },
522
+ keys: { type: 'array', items: { type: 'string' }, description: 'Broadcast record keys this seat has processed. Must be non-empty.' },
523
+ },
524
+ required: ['seat_label', 'keys'],
525
+ },
526
+ },
527
+ {
528
+ name: 'fabric_seat_state_get',
529
+ description: 'Read the seat-state record "seat-state-<LABEL>" — the ONE owner of a seat\'s handoff state (there is no repo handoff path). Always returns the server-stamped received_at; there is no projection parameter.',
530
+ mutating: false,
531
+ oauthReadonly: true,
532
+ inputSchema: {
533
+ type: 'object',
534
+ properties: { seat_label: { type: 'string', description: 'The seat LABEL.' } },
535
+ required: ['seat_label'],
536
+ },
537
+ },
538
+ {
539
+ name: 'fabric_seat_state_put',
540
+ description: 'Write the seat-state record "seat-state-<LABEL>". `mode` is REQUIRED and has NO DEFAULT — a call without it is refused. mode:"patch" merges the fields you send and leaves the rest alone; mode:"replace" makes this call the whole record and CLEARS every field it omits (reported in cleared_fields). The choice is forced because a silent partial merge is the most expensive behaviour on this store: a put of one field kept a stale text and version from an earlier write under a fresh received_at, all looking current, and get-after-put is structurally blind to it — you read back the fields you SENT and never examine the ones you failed to send.',
541
+ mutating: true,
542
+ inputSchema: {
543
+ type: 'object',
544
+ properties: {
545
+ seat_label: { type: 'string', description: 'The seat LABEL.' },
546
+ mode: { type: 'string', enum: [...WRITE_MODES], description: 'REQUIRED, no default. "replace" = this is the whole record, omitted fields are cleared. "patch" = merge these fields only.' },
547
+ text: { type: 'string', description: 'The seat state itself: the thread-specific gotchas, dead ends and learnings a cold-start reader needs in order not to re-derive them.' },
548
+ status: { type: 'string', description: 'Optional seat status.' },
549
+ workstream_id: { type: 'string', description: 'Optional workstream this seat holds.' },
550
+ branch: { type: 'string', description: 'Optional branch the work lives on.' },
551
+ holder_session: { type: 'string', description: 'Optional session id holding the seat.' },
552
+ from_agent: { type: 'string', description: 'Optional author label.' },
553
+ extra: { type: 'object', description: 'Optional additional flat metadata.' },
554
+ },
555
+ required: ['seat_label', 'mode'],
556
+ },
557
+ },
558
+ {
559
+ name: 'fabric_watermark_get',
560
+ description: 'Read the delivery ledger "watermark-<LABEL>" — the per-seat record of what this seat has already seen, handed up or resolved. This is where BROADCAST processed-state lives, because a broadcast\'s own status may never be flipped. Always returns the server-stamped received_at.',
561
+ mutating: false,
562
+ oauthReadonly: true,
563
+ inputSchema: {
564
+ type: 'object',
565
+ properties: { seat_label: { type: 'string', description: 'The seat LABEL.' } },
566
+ required: ['seat_label'],
567
+ },
568
+ },
569
+ {
570
+ name: 'fabric_watermark_migrate',
571
+ description: 'Migrate one seat\'s watermark onto the provenance-bearing ledger. IT REPORTS, IT NEVER DROPS: every entry gets exactly one of three NAMED fates — MOVED (a field that is not one of the five ledger fields, e.g. a `notes` paragraph that could only have arrived by a raw app_records_put; it is written onto seat-state-<LABEL> BEFORE it is cleared here), STAMPED (a pre-provenance bare entry, now attributed to you and marked as having no recorded original writer), or REFUSED (an entry that cannot be represented in the typed ledger — PROSE rather than a record key — which is LEFT EXACTLY WHERE IT IS for a human to re-file). A refusal is a BLOCK on that entry, never a warning that precedes a deletion. Run once per seat before switching that seat to mode:append.',
572
+ mutating: true,
573
+ inputSchema: {
574
+ type: 'object',
575
+ properties: {
576
+ seat_label: { type: 'string', description: 'The seat LABEL whose watermark is being migrated.' },
577
+ writer: { type: 'string', description: 'REQUIRED — the agent id running the migration. Pre-provenance entries are stamped with it and explicitly marked as having no recorded original writer, so a migrated claim is never mistaken for one this writer actually made.' },
578
+ },
579
+ required: ['seat_label', 'writer'],
580
+ additionalProperties: false,
581
+ },
582
+ },
583
+ {
584
+ name: 'fabric_watermark_put',
585
+ description: 'Write the delivery ledger "watermark-<LABEL>". `mode` is REQUIRED and has NO DEFAULT. USE \'append\': it SET-UNIONS the named fields SERVER-SIDE, which is what a delivery ledger wants — a client read-union-write loses every entry written between its read and its write, and one such patch was measured taking a delivered ledger from 98 entries to 1. \'patch\' merges FIELDS but REPLACES each array wholesale, and \'replace\' additionally clears the fields you omit; BOTH now REFUSE a write that would DROP an existing entry (FABRIC_WATERMARK_DESTRUCTIVE_WRITE), because a delivery claim that vanishes is indistinguishable afterwards from mail that never arrived. To withdraw entries deliberately use \'quarantine\' with `quarantine_writer`. `writer` is REQUIRED on every write that touches the ledger and every entry is stamped {key, writer, at}: a claim outlives the credibility of whoever made it, and a secretary stopped FOR CAUSE left a \'delivered\' claim its successor could neither trust nor safely discard. Entries are stored as JSON objects; a bare pre-provenance string is still READ but can no longer be WRITTEN — run fabric_watermark_migrate once per seat to stamp them. The ledger has exactly '
586
+ + WATERMARK_FIELDS.length + ' fields: ' + WATERMARK_FIELDS.join(', ')
587
+ + '. Any other field is REJECTED rather than stored, because a ledger field no reader consults is a delivery record that silently does nothing. broadcast_seen is the correct place to record that this seat has processed a broadcast — never flip the broadcast itself.',
588
+ mutating: true,
589
+ inputSchema: {
590
+ type: 'object',
591
+ properties: {
592
+ seat_label: { type: 'string', description: 'The seat LABEL.' },
593
+ mode: { type: 'string', enum: [...WATERMARK_WRITE_MODES], description: 'REQUIRED, no default. append = server-side set-union (idempotent; re-appending an entry is a no-op and does not restamp it). patch/replace = wholesale array write, REFUSED if it would drop an existing entry. quarantine = withdraw one writer\'s claims across every ledger field, leaving every other writer\'s intact.' },
594
+ writer: { type: 'string', description: 'REQUIRED on every write that touches the ledger — the agent id making the claim. Stamped onto every entry so a successor can decide WHOSE claims to trust.' },
595
+ quarantine_writer: { type: 'string', description: 'Required by mode \'quarantine\' and meaningless otherwise: the writer whose claims are being withdrawn. Without it a quarantine would be an untargeted delete of the whole ledger, so it is refused.' },
596
+ // AN ARRAY, because that is what the writer writes. fabric_broadcast_ack merges the
597
+ // acknowledged KEYS into this field as a list and re-reads it as a list; publishing
598
+ // it as a `string` "high-water mark" advertised a shape no code on either side ever
599
+ // held, and a caller that believed the schema would REPLACE the whole ledger with one
600
+ // string — silently destroying every key the seat had ever acknowledged, on a field
601
+ // whose entire job is to stop a broadcast being re-read forever.
602
+ broadcast_seen: { type: 'array', items: { type: 'string' }, description: 'Broadcast record KEYS this seat has processed. A LIST, not a high-water mark: fabric_broadcast_ack merges keys into it and reads it back as a list, so a single string here would replace the whole ledger. Prefer fabric_broadcast_ack, which resolves the keys first and never overwrites.' },
603
+ delivered: { type: 'array', items: { type: 'string' }, description: 'Record keys already handed up to the executive.' },
604
+ resolved: { type: 'array', items: { type: 'string' }, description: 'Record keys acted on and closed.' },
605
+ held: { type: 'array', items: { type: 'string' }, description: 'Record keys deliberately held back.' },
606
+ awaiting: { type: 'array', items: { type: 'string' }, description: 'Record keys this seat is waiting on.' },
607
+ },
608
+ required: ['seat_label', 'mode'],
609
+ },
610
+ },
611
+ {
612
+ name: 'fabric_envelope',
613
+ description: 'The envelope(s) assigned to a seat label. Runs TWO queries and unions them, because an envelope names its assignee as `seat_label` on some records and `to_agent` on others and the store\'s filter is a conjunction with no $or — a single predicate can only ever see half the fabric. A label with NO envelope returns envelopes:[] and success, NOT an error: a master seat has none by design, and its identity comes from the seat surface (beast_seat_read), not from an assignment.',
614
+ mutating: false,
615
+ oauthReadonly: true,
616
+ inputSchema: {
617
+ type: 'object',
618
+ properties: {
619
+ seat_label: { type: 'string', description: 'The seat LABEL.' },
620
+ status: { type: 'array', items: { type: 'string', enum: [...ENVELOPE_STATUSES] }, description: 'Optional ARRAY of envelope statuses to include: ' + ENVELOPE_STATUSES.join(', ') + '. Omit for all. A bare string is refused (one shape, so a caller cannot half-learn the parameter), and a status outside the vocabulary is refused rather than matching nothing.' },
621
+ },
622
+ required: ['seat_label'],
623
+ },
624
+ },
625
+ {
626
+ // CEO-D-2026-08-24-ENVELOPES-NAME-KBS-TO-CONSULT-AND-MAINTAIN. `kbs_consult`,
627
+ // `kbs_maintain` and `rulings` are SERVER-OWNED FIELDS, not prose inside `text`: buried in
628
+ // a body, nothing can query which seats maintain a KB and nothing can check that an
629
+ // envelope carries the ruling it was dispatched under. `rulings` is VERBATIM by contract —
630
+ // a paraphrase acquires the CEO's authority without his words.
631
+ name: 'fabric_envelope_put',
632
+ description: 'Write the envelope for a workstream — the assignment a seat executes. The key is DERIVED as "envelope-<workstream_id>", so one workstream has exactly ONE envelope and a caller cannot compose a second; a client-supplied file_id/key is REFUSED. `to_agent` is the assignee\'s seat LABEL and is validated by the SAME address vocabulary as fabric_msg_send — an envelope is 1:1, so a "ws-*" workstream id, a bare role name and the "all"/"ALL" sentinels are all refused by name: they would be written successfully and read by nobody. It is written to BOTH `to_agent` and `seat_label`, which is why fabric_envelope has to union two queries. `mode` is REQUIRED and has NO DEFAULT (patch = merge these fields, replace = these fields ARE the envelope and every field it omits is CLEARED and reported in cleared_fields) — a silent partial merge is how a re-dispatched envelope kept a stale branch and a superseded ruling under a fresh received_at, and get-after-put is structurally blind to it. `kbs_consult` and `kbs_maintain` name the knowledge bases this seat must READ and the ones it must MAINTAIN; `rulings` carries the CEO/orchestrator ruling VERBATIM, never a paraphrase. The clocks are the server\'s — a caller-supplied created_at/occurred_at/received_at/phase_at is refused. CONTRACT SHAPE (docs/design/workstream-contract-system-2026-08-25.md §4.1): ' + ENVELOPE_TEXT_SHAPE + ' Prose text is REFUSED by name (FABRIC_ENVELOPE_TEXT_NOT_SECTIONED) and a sectioned body missing rows is refused naming EXACTLY which (FABRIC_ENVELOPE_SECTIONS_MISSING, with `missing` and `required` in the error data) — an envelope with no Acceptance section is not a terse contract, it is an unenforceable one. Sections are checked only when this call WRITES text: `text` is REQUIRED with mode "replace" (replace means this call IS the envelope), and validated on "patch" only when you send it — a patch that does not send `text` (a status or phase flip) is untouched, so the envelopes already on the fabric stay patchable. `phase` is the contract LIFECYCLE and is SERVER-OWNED, not a body field: ' + ENVELOPE_PHASES.join(' \u2192 ') + ', defaulting to "' + ENVELOPE_PHASE_DEFAULT + '" on a record that has never carried one. Only the transitions in fabric_vocabulary\'s envelope_phase_transitions are accepted — each phase also permits ITSELF (so a re-put that does not move the contract succeeds), backward moves are REFUSED (re-opening a signed contract goes through the architect as a new contract, not a field edit) and "closed" is terminal. The server stamps `phase_at` on every phase change and echoes both.',
633
+ mutating: true,
634
+ inputSchema: {
635
+ type: 'object',
636
+ properties: {
637
+ workstream_id: { type: 'string', description: 'The workstream this envelope assigns. It is the KEY\'s subject ("envelope-<workstream_id>"), so one workstream has exactly one envelope.' },
638
+ to_agent: { type: 'string', description: 'The assignee\'s seat LABEL. ' + SEAT_RESOLUTION_RULE + ' An envelope is 1:1: "all"/"ALL", a "ws-*" workstream id and a bare role name are all REFUSED by name.' },
639
+ mode: { type: 'string', enum: [...WRITE_MODES], description: 'REQUIRED, no default. "replace" = this call IS the envelope and omitted fields are cleared. "patch" = merge these fields only.' },
640
+ text: { type: 'string', description: 'The contract body. ' + ENVELOPE_TEXT_SHAPE + ' Prose is refused by name. REQUIRED when mode is "replace"; on "patch" it is validated only if sent.' },
641
+ branch: { type: 'string', description: 'The branch this work lives on.' },
642
+ initiative_id: { type: 'string', description: 'The initiative this workstream belongs to.' },
643
+ kbs_consult: { type: 'array', items: { type: 'string' }, description: 'Knowledge bases this seat must CONSULT before acting. A list, so it can be queried — not prose inside `text`.' },
644
+ kbs_maintain: { type: 'array', items: { type: 'string' }, description: 'Knowledge bases this seat is responsible for MAINTAINING as part of the work. A list, so "who maintains this KB" is an answerable question.' },
645
+ rulings: { type: 'string', description: 'The CEO/orchestrator ruling this envelope is dispatched under, VERBATIM. Never a paraphrase: a compressed ruling acquires its author\'s authority without their words, and the vivid clause travels while the ruling stays behind.' },
646
+ status: { type: 'string', enum: [...ENVELOPE_STATUSES], description: `Envelope status. Defaults to "${ENVELOPE_STATUS_DEFAULT}" when omitted.` },
647
+ phase: { type: 'string', enum: [...ENVELOPE_PHASES], description: `The contract's LIFECYCLE state. Defaults to "${ENVELOPE_PHASE_DEFAULT}" on a record that carries none, and is otherwise LEFT WHERE IT IS when omitted — lifecycle is not payload, so even mode:"replace" never rewinds it. A move is checked against envelope_phase_transitions (see fabric_vocabulary): each phase permits itself, backward is refused, "${ENVELOPE_PHASES[ENVELOPE_PHASES.length - 1]}" is terminal. The server stamps phase_at; a caller-supplied phase_at is refused.` },
648
+ },
649
+ required: ['workstream_id', 'to_agent', 'mode'],
650
+ },
651
+ },
652
+ {
653
+ name: 'fabric_contract_put',
654
+ description: 'Write a CONTRACT — the agreement its parties sign, and the record a doer works under. `contract_key` IS THE FULL STORED KEY, prefix and all: it must already start with "' + KEY_CONTRACT + '" and it is written through UNTOUCHED — nothing is prepended and nothing is stripped, so the key you send is the key that exists and the contract has exactly ONE name. A value without the prefix is REFUSED BY NAME (FABRIC_CONTRACT_KEY_INVALID), and the refusal shows the key you probably meant; a client-supplied file_id/key is REFUSED separately. A CONTRACT IS NOT AN ENVELOPE: an envelope is the 1:1 assignment of a workstream to a seat and there is exactly one per workstream, while a workstream carries as many contracts as it has parties — a parent and a sub-contract per doer. Before this verb existed every contract on the fabric was written by raw app_records_put with no key derivation and no validation at all (measured 2026-08-26); that path is refused now, by name, pointing here. `mode` is REQUIRED and has NO DEFAULT, like every keyed write on this surface. The clocks are the server\'s — a caller-supplied created_at/occurred_at/received_at is refused. CONTRACT SHAPE: ' + ENVELOPE_TEXT_SHAPE + ' Prose is REFUSED (FABRIC_ENVELOPE_TEXT_NOT_SECTIONED) and a sectioned body missing rows is refused naming EXACTLY which (FABRIC_ENVELOPE_SECTIONS_MISSING) — the SAME validator fabric_envelope_put runs, not a second copy of it. TWO FURTHER RULES APPLY ONLY TO CONTRACTS, because a contract is what a doer grounds against: `knowledge.reads` must be a NON-EMPTY ARRAY whose entries each carry ' + CONTRACT_READ_FIELD_NAMES.join(', ') + ' (FABRIC_CONTRACT_KNOWLEDGE_READS_MISSING, naming the offending index and field), and `principles_carried` must be a NON-EMPTY ARRAY of non-empty strings (FABRIC_CONTRACT_PRINCIPLES_EMPTY). A contract whose knowledge section DESCRIBES how to read instead of LISTING what to read gives the doer nothing to execute and the verifier nothing to check a grounding record against — "read" (singular, a string) is the measured near-miss and is refused as one. Both rules fire ONLY on a write of `text`, so contracts written before they existed stay patchable and are re-cut by their authors rather than becoming unreachable.',
655
+ mutating: true,
656
+ inputSchema: {
657
+ type: 'object',
658
+ properties: {
659
+ contract_key: { type: 'string', description: 'The contract\'s FULL stored key — it must already start with "' + KEY_CONTRACT + '" and is stored verbatim, so one contract has exactly one record and one name. A value without the prefix is refused (FABRIC_CONTRACT_KEY_INVALID); the server never prepends and never strips.' },
660
+ mode: { type: 'string', enum: [...WRITE_MODES], description: 'REQUIRED, no default. "replace" = this call IS the contract and omitted fields are cleared. "patch" = merge these fields only.' },
661
+ text: { type: 'string', description: 'The contract body. ' + ENVELOPE_TEXT_SHAPE + ' Prose is refused by name. REQUIRED when mode is "replace"; on "patch" it is validated only if sent.' },
662
+ workstream_id: { type: 'string', description: 'The workstream this contract governs. A workstream may carry several contracts, so this is a FIELD and not the key.' },
663
+ to_agent: { type: 'string', description: 'Optional: the party this contract is addressed to. ' + SEAT_RESOLUTION_RULE },
664
+ phase: { type: 'string', enum: [...ENVELOPE_PHASES], description: `The contract's LIFECYCLE state — ${ENVELOPE_PHASES.join(' → ')}, defaulting to "${ENVELOPE_PHASE_DEFAULT}". Held to the same transition machine as an envelope's: each phase permits itself, backward is refused, "${ENVELOPE_PHASES[ENVELOPE_PHASES.length - 1]}" is terminal.` },
665
+ status: { type: 'string', enum: [...ENVELOPE_STATUSES], description: `Contract status. Defaults to "${ENVELOPE_STATUS_DEFAULT}" when omitted.` },
666
+ },
667
+ required: ['contract_key', 'mode'],
668
+ },
669
+ },
670
+ {
671
+ name: 'fabric_grounding_put',
672
+ description: 'Write the GROUNDING RECEIPT for a contract and an identity — the served proof that this identity performed the contract\'s declared KB reads and checked the answers against the code. It is what a guard reads before it will let a doer edit a file, which is the whole point: grounding becomes a record written on an observed event rather than an obligation an agent has to remember. The key is DERIVED as "' + KEY_GROUNDING + '<contract_key>-<identity>[-<phase>]" with the contract key and identity taken BYTE-EXACT (`contract_key` is the full stored key, so grounding-contract-ws-x-DOER is correct and its doubled-looking "contract-" is the contract\'s own name, not a mistake); `phase` is an OPTIONAL third segment for work that grounds more than once, and without it a second grounding would overwrite the first. A client-supplied file_id/key is REFUSED, as is any clock (occurred_at/received_at/created_at) — a caller-stamped grounding could claim it happened at a time no write did, which is precisely the audit trail this record exists to be. `reads` is REQUIRED and NON-EMPTY, and every entry carries a `kind` (' + GROUNDING_READ_KINDS.join(' | ') + ') that SELECTS the fields it is held to: kind "kb" = a corpus question carrying ' + GROUNDING_KB_READ_FIELD_NAMES.join(', ') + '; kind "role" = a served role-record read carrying ' + GROUNDING_ROLE_READ_FIELD_NAMES.join(', ') + ' INSTEAD of app/knowledgebase_names/question, because a record fetch has no sources to count. At least one "' + GROUNDING_REQUIRED_READ_KIND + '" read is REQUIRED — a receipt made only of role reads proves the doer read its own job description, not the contract\'s corpus. A kb READ WITH sources_count 0 IS REFUSED BY NAME (FABRIC_GROUNDING_READ_UNSOURCED): an answer that cited no sources is the model speaking from its own weights, which is the ungrounded answer the gate exists to catch — recording it faithfully would still produce a receipt a guard lets through. `verification` is REQUIRED and NON-EMPTY, each entry carrying ' + GROUNDING_VERIFICATION_FIELD_NAMES.join(', ') + ' — a grounding with no verified claim is not a grounding, and `file_symbol` (path::symbol) is required so the verifier can re-run the check instead of taking the doer\'s word. `verdict` is a CLOSED ENUM (' + GROUNDING_VERDICTS.join(', ') + ') because a guard branches on it and cannot parse English; UNDETERMINED exists so a check that could not settle has somewhere honest to go. `flags` is REQUIRED and MAY BE EMPTY, and every entry is an OBJECT carrying ' + GROUNDING_FLAG_FIELD_NAMES.join(', ') + ' — a BARE STRING IS REFUSED BY INDEX rather than wrapped, since wrapping would invent a disposition you never claimed; disposition is one of ' + GROUNDING_FLAG_DISPOSITIONS.join(', ') + ' and ' + GROUNDING_FLAG_RESOLUTION_REQUIRED_FOR.join('/') + ' REQUIRE a non-empty `resolution`. "I found no flags" is a claim a doer must make explicitly, and an absent array is indistinguishable from a doer who never looked. The `contract_key` must RESOLVE to an existing contract record (FABRIC_GROUNDING_CONTRACT_UNKNOWN) and that contract must itself pass the contract-body rules (FABRIC_GROUNDING_CONTRACT_MALFORMED, raised by running the SAME validator fabric_contract_put runs) — a doer cannot ground against a contract that never stated what to read. Call fabric_vocabulary for the published field tables and refusal codes rather than hand-keeping a copy.',
673
+ mutating: true,
674
+ inputSchema: {
675
+ type: 'object',
676
+ properties: {
677
+ contract_key: { type: 'string', description: 'The FULL stored key of the contract being grounded against (starting "' + KEY_CONTRACT + '", exactly as the contract record\'s own contract_key field carries it). It must resolve to an existing contract record, and that contract must carry knowledge.reads[] and principles_carried. Nothing is stripped: it goes into the grounding key whole.' },
678
+ identity: { type: 'string', description: 'The identity (party label) that performed the reads. One grounding per (contract, identity) — a key naming only the contract would answer "has this identity grounded" for whoever grounded first.' },
679
+ reads: {
680
+ type: 'array',
681
+ description: 'REQUIRED, non-empty, and at least one entry of kind "' + GROUNDING_REQUIRED_READ_KIND + '". Each entry carries `kind` (' + GROUNDING_READ_KINDS.join(' | ') + '), which selects its field table: kb → ' + GROUNDING_KB_READ_FIELD_NAMES.join(', ') + ' (`question` is passed verbatim as ask_question_to_app.user_input; sources_count 0 is REFUSED); role → ' + GROUNDING_ROLE_READ_FIELD_NAMES.join(', ') + '.',
682
+ items: { type: 'object' },
683
+ },
684
+ verification: {
685
+ type: 'array',
686
+ description: 'REQUIRED, non-empty. One entry per KB claim checked against the code. Fields: ' + GROUNDING_VERIFICATION_FIELD_NAMES.join(', ') + '. `verdict` must be one of ' + GROUNDING_VERDICTS.join(', ') + ' — a closed enum, because a guard branches on it.',
687
+ items: { type: 'object' },
688
+ },
689
+ flags: {
690
+ type: 'array',
691
+ description: 'REQUIRED, MAY BE EMPTY. The flags raised to the hiring party before work began, as OBJECTS carrying ' + GROUNDING_FLAG_FIELD_NAMES.join(', ') + '. A bare string is REFUSED by index. `disposition` is one of ' + GROUNDING_FLAG_DISPOSITIONS.join(', ') + '; ' + GROUNDING_FLAG_RESOLUTION_REQUIRED_FOR.join(' and ') + ' require a non-empty `resolution`. Empty array means "I looked and found none" — an explicit claim, not an omission.',
692
+ items: { type: 'object' },
693
+ },
694
+ phase: { type: 'string', description: 'OPTIONAL. A slug naming the phase of work this receipt covers, appended as a third key segment ("' + KEY_GROUNDING + '<contract_key>-<identity>-<phase>"). Send it when one identity grounds a contract more than once; without it the second receipt overwrites the first.' },
695
+ mode: { type: 'string', enum: [...WRITE_MODES], description: 'REQUIRED, no default. "replace" = this call IS the grounding record. "patch" = merge these fields only.' },
696
+ },
697
+ required: ['contract_key', 'identity', 'reads', 'verification', 'flags', 'mode'],
698
+ },
699
+ },
700
+ {
701
+ name: 'fabric_lease_claim',
702
+ description: 'Claim a lease on a PHYSICAL SINGLETON — a dev port, a local backend. Composes the "lease-<resource>" key and delegates to the platform\'s atomic conditional create, so first claim wins inside one Firestore transaction: a losing claimant is ANSWERED with claimed:false and who holds it, never silently turned into an overwrite. Holder verification is the platform\'s, not re-implemented here. NOTE: orchestrator SEATS are NOT leases — they live on the BEAST authority plane and obey different rules (expiry never frees a seat).',
703
+ mutating: true,
704
+ inputSchema: {
705
+ type: 'object',
706
+ properties: {
707
+ resource: { type: 'string', description: 'The singleton being claimed, e.g. "backend-4000". Normalized to lowercase alphanumerics and dashes.' },
708
+ holder_label: { type: 'string', description: 'The claiming seat\'s LABEL.' },
709
+ session_id: { type: 'string', description: 'The claiming session id.' },
710
+ ttl_s: { type: 'number', description: 'Lease lifetime in seconds. Omit for the server default, which is echoed back as `ttl_s` alongside `expires_at`. Readers treat expires_at in the past as stale and may take over; the store enforces no TTL of its own.' },
711
+ },
712
+ required: ['resource', 'holder_label', 'session_id'],
713
+ },
714
+ },
715
+ {
716
+ name: 'fabric_lease_release',
717
+ description: 'Release a lease claimed with fabric_lease_claim. Deletes the record rather than flipping a status, so "released" and "claimable" cannot become two different facts about one resource — a lingering released document is a key the next claimant\'s conditional create still collides with. Reports what CHANGED: released:false genuinely means there was no lease to release, not that the call was ignored.',
718
+ mutating: true,
719
+ inputSchema: {
720
+ type: 'object',
721
+ properties: {
722
+ resource: { type: 'string', description: 'The singleton being released.' },
723
+ holder_label: { type: 'string', description: 'The releasing seat\'s LABEL. Delete is holder-verified by the same policy that gates the write.' },
724
+ session_id: { type: 'string', description: 'The releasing session id.' },
725
+ },
726
+ required: ['resource', 'holder_label', 'session_id'],
727
+ },
728
+ },
729
+ {
730
+ name: 'fabric_vocabulary',
731
+ description: 'Return the coordination fabric\'s SERVER vocabulary — every closed set the fabric_* verbs validate against: writable beat statuses, declared stops, legacy read-only statuses, liveness values (who wrote a beat: agent or hook), to_agent sentinels and the retired ones that are refused by name, refused role addresses, write modes, envelope statuses, delivery statuses, watermark ledger fields, wake fields, record types, key prefixes, verdicts and the server-owned numeric defaults. It also publishes the CONTRACT vocabulary: `envelope_sections` (the required sections of an envelope\'s `text`: ' + ENVELOPE_SECTIONS.join(', ') + '), `envelope_phases` + `envelope_phase_default` + `envelope_phase_transitions` (the lifecycle machine fabric_envelope_put enforces, including each phase permitting itself and "' + ENVELOPE_PHASES[ENVELOPE_PHASES.length - 1] + '" being terminal), and `record_kinds` (the inter-party record kinds: ' + FABRIC_RECORD_KINDS.join(', ') + ' — a record with no `type` is a violation, not a lax record). Takes no parameters and reads no records — it is the vocabulary itself, not a query over the fabric. GENERATE a client-side copy from this; do not hand-keep one. A hand-kept mirror was measured writing four statuses the server refuses and defining a liveness model the server did not know, so a caller was validating against a contract that did not exist and being refused by one it had never seen.',
732
+ mutating: false,
733
+ oauthReadonly: true,
734
+ inputSchema: { type: 'object', properties: {} },
735
+ },
736
+ {
737
+ // WS-HEADLESS-MVP-A2 (CEO-D-2026-07-01 D2): platform-wide USD AI-credits balance.
738
+ // Read-only; the METERED RAG/agent surface (WS-A3) debits this balance per call.
739
+ // NEVER exposes pricing internals — USD balance figures only.
740
+ name: 'get_credit_balance',
741
+ description: 'Get your platform-wide AI-credits balance in USD. Metered AI calls (RAG chat / agents, e.g. ask_question_to_app and query_knowledge_base) debit this balance. At a $0 balance a free daily credit auto-applies to your first metered call each day, so metered tools are usable without buying anything first (the response reports daily_free_credit_usd and daily_free_credit_available_today). Buy more credits with the descix CLI (`descix credits buy`) or the platform store. Programmatic purchase: create_stripe_checkout_session with purchase_type "ai_credits" and amount_usd returns a Stripe checkout URL.',
742
+ mutating: false,
743
+ oauthReadonly: true,
744
+ inputSchema: {
745
+ type: 'object',
746
+ properties: {},
747
+ },
748
+ },
749
+ {
750
+ // WS-MCP-SURFACE-SPLIT-EXEC (CEO-D-2026-07-04 §6.3, D2): the DISCOVERY-CORE invoke gateway.
751
+ // tell_me_how surfaces MESH-DISCOVERABLE commands (everything NOT in the handshake core);
752
+ // this is how a client actually calls one without it being advertised at tools/list. It is a
753
+ // thin passthrough into the SAME /apifront CommandHandler.invoke path — so EVERY existing
754
+ // call-time gate (permission, credits, OAuth scope, service-account) applies to the TARGET
755
+ // command exactly as if called directly. Nothing is bypassed.
756
+ // mutating:true — a gateway that CAN reach mutating targets is itself classified mutating.
757
+ // WS-FREEMIUM-ONRAMP FO-2 (doc c §2.5): it IS now admitted to the read-only OAuth SURFACE
758
+ // (a read-scoped session may CALL the gateway — see MESH_INVOKE_GATEWAY_TOOLS below), but the
759
+ // scope-aware dispatch gate in DeSciX_Cloud CommandHandler.invoke enforces that the re-entrant
760
+ // TARGET command is read-only. The classification is about the tool; the gate is about the call.
761
+ name: 'execute_remote_command',
762
+ description:
763
+ 'Invoke a platform command discovered via tell_me_how that is NOT advertised in the ' +
764
+ 'handshake tool list (the MESH-DISCOVERABLE surface). Pass the exact command name and its ' +
765
+ 'params; the call runs through all normal permission, credit-metering and scope gates for ' +
766
+ 'that command — you can only do what you are already entitled to do. Use tell_me_how first ' +
767
+ 'to discover the command name and its parameters. Example: execute_remote_command({ command: ' +
768
+ '"beast_get_dashboard", params: { ... } }).',
769
+ mutating: true,
770
+ inputSchema: {
771
+ type: 'object',
772
+ properties: {
773
+ command: { type: 'string', description: 'The exact command name to invoke (as returned by tell_me_how).' },
774
+ params: { type: 'object', description: "Parameters for the target command (its own inputSchema). Omit for no-arg commands." },
775
+ },
776
+ required: ['command'],
777
+ },
778
+ },
779
+ {
780
+ name: 'create_app_for_community',
781
+ description:
782
+ "Create a SUB-APP inside an existing community (registers Products + Firestore App doc + grants you the entitlement). " +
783
+ "The unique app_id is COMPOSED SERVER-SIDE as {community_id}-{short_name} where community_id is the community's default app id (== its lowercased token symbol), e.g. community 'egpt' + short_name 'frqtl' => app_id 'egpt-frqtl'. " +
784
+ "Pick a SHORT, lowercase short_name with NO hyphens ('-' is the reserved separator) — if omitted, app_name is used as the short name. " +
785
+ "Fails loud if: the community does not exist in this environment (you must create the community first — an app without a materialized community is an invalid orphan), an app with the composed id already exists (pass overwrite:true to update it), or the short name contains '-' or other invalid characters. " +
786
+ "Do NOT use this to create a community's DEFAULT app (app_id == community_id) — that is created by community-create. app_id stays opaque to routing; this only composes it at create time.",
787
+ mutating: true,
788
+ inputSchema: {
789
+ type: 'object',
790
+ properties: {
791
+ community_id: { type: 'string', description: "Existing community id (== its default app id == lowercased token symbol). Must already be materialized in this env." },
792
+ app_name: { type: 'string', description: 'Human-readable display name for the app.' },
793
+ short_name: { type: 'string', description: "SHORT id segment used to compose the unique app_id {community_id}-{short_name}. Lowercase letters/digits/underscore, NO hyphens. Optional — defaults to app_name. Keep it short, e.g. 'frqtl'." },
794
+ app_description: { type: 'string', description: 'Optional description.' },
795
+ icon_url: { type: 'string', description: 'Optional icon URL.' },
796
+ overwrite: { type: 'boolean', description: 'Set true to update an app whose composed id already exists (otherwise duplicate fails loud). Default false.' },
797
+ },
798
+ required: ['community_id', 'app_name'],
799
+ },
800
+ },
801
+ ]);
802
+
803
+ /**
804
+ * Tool definitions reduced to the bare { name, description, inputSchema } shape the MCP
805
+ * tools/list protocol expects (strips the internal mutating/oauthReadonly classification).
806
+ */
807
+ export function toMcpToolList(tools = NATIVE_MCP_TOOLS) {
808
+ return tools.map(({ name, description, inputSchema }) => ({ name, description, inputSchema }));
809
+ }
810
+
811
+ /** Names of native tools that self-declare mutating:true. */
812
+ export function mutatingNativeToolNames() {
813
+ return NATIVE_MCP_TOOLS.filter(t => t.mutating === true).map(t => t.name);
814
+ }
815
+
816
+ /** EVP-recommended read-only tools for the security-owned OAuth allow-list (advisory). */
817
+ export function recommendedOAuthReadonlyToolNames() {
818
+ return NATIVE_MCP_TOOLS.filter(t => t.mutating === false && t.oauthReadonly === true).map(t => t.name);
819
+ }
820
+
821
+ /**
822
+ * DISCOVERY-CORE — the set of tools advertised at the MCP handshake (tools/list) for STANDARD
823
+ * callers. Everything else that is registered + callable is MESH-DISCOVERABLE: reachable via
824
+ * tell_me_how + execute_remote_command but NOT advertised at handshake, so a standard session pays
825
+ * ~1k tokens of catalog instead of ~8.7k.
826
+ *
827
+ * R6 (CEO-D-2026-07-13-PUBLIC-COMMUNITIES-AND-SURFACE-LOCKDOWN): the mesh-ops tools list_services
828
+ * and service_health_check are NOT part of a normal user's MVP minimal set — they surfaced the
829
+ * platform's internal service topology at first contact. They are FLAG-FLIPPED off the handshake
830
+ * set here (a flag-flip only; the tell_me_how discovery internals are untouched — item K of the
831
+ * MCP-hardening thread owns the discovery-scope enforcement). list_services is additionally
832
+ * admin-gated in DeSciX_Cloud (COMMAND_PERMISSIONS). That leaves the 7 normal-user tools below.
833
+ * The prior ratification was CEO-D-2026-07-04-MCP-SURFACE-SPLIT-EXECUTION §3 (9 names); this ruling
834
+ * supersedes the mesh-health row for the STANDARD surface. Membership is ratified — do NOT
835
+ * add/remove without a CEO ruling. (execute_remote_command is advertised via commandMeta mcp:true
836
+ * in DeSciX_Cloud; the other 6 live in NATIVE_MCP_TOOLS above.)
837
+ */
838
+ export const DISCOVERY_CORE_TOOL_NAMES = Object.freeze([
839
+ 'tell_me_how',
840
+ 'execute_remote_command',
841
+ 'ask_question_to_app',
842
+ 'query_knowledge_base',
843
+ 'find_communities',
844
+ 'fetch_my_purchases',
845
+ 'get_credit_balance',
846
+ ]);
847
+
848
+ /** True if `name` is in the ratified DISCOVERY-CORE handshake set. */
849
+ export function isDiscoveryCoreTool(name) {
850
+ return DISCOVERY_CORE_TOOL_NAMES.includes(name);
851
+ }
852
+
853
+ /**
854
+ * SELF-DESCRIPTION of the DISCOVERY-CORE fence (D-22: every verb/param/refusal — and every
855
+ * fence — states its own contract where a reader and a test can both reach it).
856
+ *
857
+ * The fence is a FLOOR, not a ceiling: tools/list serves this set UNION the calling identity's
858
+ * granted command names (see the Cloud owner module services/toolVisibilityService.js). With no
859
+ * grant, an empty grant, or an expired grant the union degrades to exactly this set — which is
860
+ * the behavior that existed before per-caller grants, so the mechanism is INERT by default.
861
+ *
862
+ * A grant NEVER widens authorization: the permission filter runs BEFORE the fence, so a granted
863
+ * name that the caller may not call was already dropped and cannot be re-admitted here.
864
+ *
865
+ * The text DERIVES from DISCOVERY_CORE_TOOL_NAMES — the count and the member list can never
866
+ * drift from the constant they describe, because they are read off it rather than retyped.
867
+ *
868
+ * @returns {string} a human- and machine-readable statement of the fence contract
869
+ */
870
+ export function describeDiscoveryCoreFence() {
871
+ return [
872
+ `DISCOVERY-CORE is the ${DISCOVERY_CORE_TOOL_NAMES.length}-tool FLOOR advertised at the MCP`,
873
+ `handshake to every caller: ${DISCOVERY_CORE_TOOL_NAMES.join(', ')}.`,
874
+ 'tools/list serves this floor UNION the calling identity\'s granted command names.',
875
+ 'An absent, empty, or expired grant is INERT — the union is exactly this floor.',
876
+ 'A grant widens VISIBILITY only; the permission gate runs first and still bounds what',
877
+ 'any caller may invoke. Everything outside this floor stays registered and callable via',
878
+ 'tell_me_how + execute_remote_command.',
879
+ ].join(' ');
880
+ }
881
+
882
+ /**
883
+ * MESH-INVOKE GATEWAY tools (WS-FREEMIUM-ONRAMP FO-2, doc c §2.4/§2.5). These are mutating:true
884
+ * tools that dispatch a DISCOVERED target command by re-entering CommandHandler.invoke (currently
885
+ * only execute_remote_command). They are the ONE class admitted to the read-only OAuth surface
886
+ * despite a mutating self-classification, because the scope-aware dispatch gate
887
+ * (DeSciX_Cloud apiFront.js CommandHandler.invoke) fires again on the re-entrant TARGET — so a
888
+ * read-scoped session can CALL the gateway but cannot dispatch a mutating target through it.
889
+ *
890
+ * SINGLE SOURCE so the two consumers never drift:
891
+ * - surface admission: DeSciX_Cloud oauthAsHandlers.js isToolAllowedForOAuth (exempts these from
892
+ * the MUTATING_TOOL_NAMES defense-in-depth),
893
+ * - dispatch exemption: DeSciX_Cloud apiFront.js invoke gate (does NOT treat the gateway call
894
+ * itself as a mutating dispatch; its inner re-entry is gated by construction).
895
+ * Do NOT add a tool here without the matching re-entrant-invoke + inner-gate guarantee.
896
+ */
897
+ export const MESH_INVOKE_GATEWAY_TOOLS = Object.freeze(['execute_remote_command']);
898
+
899
+ /** True if `name` is a mesh-invoke gateway tool (admitted-despite-mutating; dispatch-gated by re-entry). */
900
+ export function isMeshInvokeGatewayTool(name) {
901
+ return MESH_INVOKE_GATEWAY_TOOLS.includes(name);
902
+ }