owenloop 0.4.0 → 0.4.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,135 @@
1
+ /**
2
+ * A minimal, dependency-light MCP server core — newline-delimited JSON-RPC 2.0
3
+ * over stdio, hand-rolled (O2 plan Decision 1).
4
+ *
5
+ * PROVENANCE: this is a near-verbatim copy of owenwork's proven
6
+ * `src/mcp/server.ts` transport core (`createMcpServer` / `pumpStdin` /
7
+ * `textResult` / the error-code consts / `LineStream`). Only this header was
8
+ * changed. Consolidating the two copies into one shared package is DELIBERATELY
9
+ * DEFERRED (per the O2 brief): owenloop and owenwork are separate packages with
10
+ * no shared dependency today, and duplicating ~400 lines of a stable, test-pinned
11
+ * transport is cheaper than standing up a shared module for it now. owenloop's
12
+ * own `test/mcpcore.test.ts` re-proves the copied behavior against this file, so
13
+ * drift is caught here rather than assumed.
14
+ *
15
+ * WHY hand-rolled, not `@modelcontextprotocol/sdk`: this repo's posture is two
16
+ * runtime deps (`@cfworker/json-schema` + `yaml`). The SDK drags zod and a
17
+ * transport stack for a surface we need only a few hundred lines of. The hub
18
+ * side already proves interop against the official SDK client, so drift is
19
+ * tested rather than assumed.
20
+ *
21
+ * The core is transport-agnostic and side-effect-injected: it exposes
22
+ * `handleLine(line)` (feed it one framed JSON-RPC line) and `close(reason)`
23
+ * (transport EOF), and it emits every outbound frame through the injected
24
+ * `write(msg)`. Unit tests feed lines and inspect writes with no child process;
25
+ * `pumpStdin` wires the real `process.stdin`/`process.stdout` in the roles.
26
+ *
27
+ * Supported methods (the subset an MCP host needs):
28
+ * - `initialize` → capabilities `{tools:{}}`, serverInfo, and the
29
+ * agreed protocolVersion (echo the client's when
30
+ * recognized, else answer with ours).
31
+ * - `notifications/initialized` → no-op (no response; it is a notification).
32
+ * - `ping` → `{}`.
33
+ * - `tools/list` → the registered tool defs.
34
+ * - `tools/call` → dispatch to the tool handler; the result is
35
+ * `{content:[{type:'text',text:<JSON>}], isError?}`.
36
+ * - `notifications/cancelled` → abort a tracked in-flight `tools/call`; the
37
+ * aborted call sends NO response frame.
38
+ * - outbound `notifications/progress` when a call carried
39
+ * `params._meta.progressToken` (via `ctx.sendProgress`).
40
+ *
41
+ * Errors: unknown method → -32601; malformed JSON / bad envelope → -32700;
42
+ * invalid params → -32602. A notification (no `id`) never gets a response, even
43
+ * on error. The process must never crash on a bad line.
44
+ */
45
+ export declare const PARSE_ERROR = -32700;
46
+ export declare const INVALID_REQUEST = -32600;
47
+ export declare const METHOD_NOT_FOUND = -32601;
48
+ export declare const INVALID_PARAMS = -32602;
49
+ export declare const INTERNAL_ERROR = -32603;
50
+ /** A tool result as MCP serves it: text content blocks, optional error flag. */
51
+ export interface ToolResult {
52
+ content: Array<{
53
+ type: 'text';
54
+ text: string;
55
+ }>;
56
+ isError?: boolean;
57
+ }
58
+ /** Convenience: wrap a JSON-able value as a single text content block. */
59
+ export declare function textResult(value: unknown, isError?: boolean): ToolResult;
60
+ /** The per-call context handed to a tool handler. */
61
+ export interface ToolCallContext {
62
+ /** True once the caller cancelled this request (`notifications/cancelled`). */
63
+ readonly cancelled: boolean;
64
+ /** Register a callback fired when this request is cancelled. */
65
+ onCancel(cb: () => void): void;
66
+ /**
67
+ * Emit a `notifications/progress` frame for this call. A no-op when the caller
68
+ * supplied no `progressToken` (progress is meaningless without one).
69
+ */
70
+ sendProgress(payload: {
71
+ progress?: number;
72
+ total?: number;
73
+ message?: string;
74
+ }): void;
75
+ }
76
+ export type ToolHandler = (args: Record<string, unknown>, ctx: ToolCallContext) => Promise<ToolResult> | ToolResult;
77
+ /** A registered tool: its advertised shape plus the handler that runs it. */
78
+ export interface ToolRegistration {
79
+ name: string;
80
+ description: string;
81
+ /** JSON-Schema for the tool's arguments (advertised via `tools/list`). */
82
+ inputSchema: Record<string, unknown>;
83
+ handler: ToolHandler;
84
+ }
85
+ export interface McpServerOptions {
86
+ name: string;
87
+ version: string;
88
+ tools: ToolRegistration[];
89
+ /** Outbound frame sink — the caller JSON-serializes + newline-terminates. */
90
+ write: (msg: unknown) => void;
91
+ /** Diagnostic sink (stderr); protocol frames never go here. */
92
+ err?: (line: string) => void;
93
+ }
94
+ export interface McpServer {
95
+ /** Feed one framed JSON-RPC line (no trailing newline required). */
96
+ handleLine(line: string): Promise<void>;
97
+ /**
98
+ * Transport EOF — cancels in-flight calls so parked handlers unblock. Their
99
+ * replies are still flushed (close-cancel ≠ client-cancel; see `InFlight`).
100
+ */
101
+ close(reason?: string): void;
102
+ }
103
+ export declare function createMcpServer(opts: McpServerOptions): McpServer;
104
+ /** The slice of a readable stream `pumpStdin` needs — injectable for tests. */
105
+ export interface LineStream {
106
+ on(event: 'data', handler: (chunk: Buffer | string) => void): unknown;
107
+ on(event: 'end' | 'close', handler: () => void): unknown;
108
+ setEncoding?(enc: string): void;
109
+ resume?(): void;
110
+ }
111
+ /**
112
+ * Wire a real byte stream (`process.stdin`) into a server: buffer bytes, split
113
+ * on newlines, feed each complete line to `server.handleLine`, and call
114
+ * `server.close` + `onEof` once on EOF. A trailing partial line at EOF is
115
+ * flushed if non-empty.
116
+ *
117
+ * Every line is DISPATCHED THE MOMENT IT ARRIVES — never queued behind an
118
+ * in-flight `tools/call`. JSON-RPC over MCP is a concurrent protocol: while a
119
+ * long call is outstanding, `notifications/cancelled` must reach the server to
120
+ * abort it and `ping` must still answer. Serializing the pump behind the
121
+ * in-flight call chain would deadlock exactly those frames on the real
122
+ * transport. Per-frame ordering still holds for the non-parking methods because
123
+ * `handleLine` runs synchronously up to the first tool-handler await, and
124
+ * responses are matched by id, not by order.
125
+ *
126
+ * EOF flushes the tail line, then calls `server.close` RIGHT AWAY — `close()`
127
+ * cancels any parked in-flight call, which is what lets a process waiting on
128
+ * this pump actually exit (chaining the close behind a parked call would
129
+ * deadlock EOF against the very call only the close can unpark). A close-cancel
130
+ * does NOT suppress the call's reply the way a client cancel does — every call
131
+ * received before EOF still answers. `onEof` fires only after every dispatched
132
+ * line has settled, so those reply frames are on the pipe before the caller
133
+ * acts on EOF (e.g. exits the process).
134
+ */
135
+ export declare function pumpStdin(stream: LineStream, server: McpServer, onEof?: () => void): void;
@@ -0,0 +1,330 @@
1
+ /**
2
+ * A minimal, dependency-light MCP server core — newline-delimited JSON-RPC 2.0
3
+ * over stdio, hand-rolled (O2 plan Decision 1).
4
+ *
5
+ * PROVENANCE: this is a near-verbatim copy of owenwork's proven
6
+ * `src/mcp/server.ts` transport core (`createMcpServer` / `pumpStdin` /
7
+ * `textResult` / the error-code consts / `LineStream`). Only this header was
8
+ * changed. Consolidating the two copies into one shared package is DELIBERATELY
9
+ * DEFERRED (per the O2 brief): owenloop and owenwork are separate packages with
10
+ * no shared dependency today, and duplicating ~400 lines of a stable, test-pinned
11
+ * transport is cheaper than standing up a shared module for it now. owenloop's
12
+ * own `test/mcpcore.test.ts` re-proves the copied behavior against this file, so
13
+ * drift is caught here rather than assumed.
14
+ *
15
+ * WHY hand-rolled, not `@modelcontextprotocol/sdk`: this repo's posture is two
16
+ * runtime deps (`@cfworker/json-schema` + `yaml`). The SDK drags zod and a
17
+ * transport stack for a surface we need only a few hundred lines of. The hub
18
+ * side already proves interop against the official SDK client, so drift is
19
+ * tested rather than assumed.
20
+ *
21
+ * The core is transport-agnostic and side-effect-injected: it exposes
22
+ * `handleLine(line)` (feed it one framed JSON-RPC line) and `close(reason)`
23
+ * (transport EOF), and it emits every outbound frame through the injected
24
+ * `write(msg)`. Unit tests feed lines and inspect writes with no child process;
25
+ * `pumpStdin` wires the real `process.stdin`/`process.stdout` in the roles.
26
+ *
27
+ * Supported methods (the subset an MCP host needs):
28
+ * - `initialize` → capabilities `{tools:{}}`, serverInfo, and the
29
+ * agreed protocolVersion (echo the client's when
30
+ * recognized, else answer with ours).
31
+ * - `notifications/initialized` → no-op (no response; it is a notification).
32
+ * - `ping` → `{}`.
33
+ * - `tools/list` → the registered tool defs.
34
+ * - `tools/call` → dispatch to the tool handler; the result is
35
+ * `{content:[{type:'text',text:<JSON>}], isError?}`.
36
+ * - `notifications/cancelled` → abort a tracked in-flight `tools/call`; the
37
+ * aborted call sends NO response frame.
38
+ * - outbound `notifications/progress` when a call carried
39
+ * `params._meta.progressToken` (via `ctx.sendProgress`).
40
+ *
41
+ * Errors: unknown method → -32601; malformed JSON / bad envelope → -32700;
42
+ * invalid params → -32602. A notification (no `id`) never gets a response, even
43
+ * on error. The process must never crash on a bad line.
44
+ */
45
+ /** The MCP revisions this server will agree to echo back on `initialize`. */
46
+ const RECOGNIZED_PROTOCOL_VERSIONS = new Set([
47
+ '2024-11-05',
48
+ '2025-03-26',
49
+ '2025-06-18',
50
+ '2025-11-05',
51
+ ]);
52
+ /** The version we answer with when the client's is missing or unrecognized. */
53
+ const OUR_PROTOCOL_VERSION = '2025-06-18';
54
+ // ---- JSON-RPC error codes ---------------------------------------------------
55
+ export const PARSE_ERROR = -32700;
56
+ export const INVALID_REQUEST = -32600;
57
+ export const METHOD_NOT_FOUND = -32601;
58
+ export const INVALID_PARAMS = -32602;
59
+ export const INTERNAL_ERROR = -32603;
60
+ /** Convenience: wrap a JSON-able value as a single text content block. */
61
+ export function textResult(value, isError = false) {
62
+ return { content: [{ type: 'text', text: JSON.stringify(value) }], ...(isError ? { isError: true } : {}) };
63
+ }
64
+ export function createMcpServer(opts) {
65
+ const err = opts.err ?? (() => { });
66
+ const tools = new Map();
67
+ for (const t of opts.tools)
68
+ tools.set(t.name, t);
69
+ // Tracks in-flight tools/call requests by id so notifications/cancelled can
70
+ // abort them (and so we can suppress the response frame of a cancelled call).
71
+ const inFlight = new Map();
72
+ let closed = false;
73
+ // NOTE: deliberately NOT gated on `closed` — a reply whose handler settled a
74
+ // microtask after transport EOF must still reach the pipe (the cancel
75
+ // contract already suppresses replies of cancelled calls, and sendProgress
76
+ // gates on `closed` itself). A write to a gone pipe lands in the catch.
77
+ function send(msg) {
78
+ try {
79
+ opts.write(msg);
80
+ }
81
+ catch (e) {
82
+ err(`mcp: write failed: ${e instanceof Error ? e.message : String(e)}`);
83
+ }
84
+ }
85
+ function reply(id, result) {
86
+ send({ jsonrpc: '2.0', id, result });
87
+ }
88
+ function replyError(id, code, message) {
89
+ send({ jsonrpc: '2.0', id, error: { code, message } });
90
+ }
91
+ function keyOf(id) {
92
+ return typeof id === 'number' ? `n:${id}` : `s:${String(id)}`;
93
+ }
94
+ async function handleToolsCall(id, params) {
95
+ if (!isObject(params) || typeof params['name'] !== 'string') {
96
+ replyError(id, INVALID_PARAMS, 'tools/call requires a string "name"');
97
+ return;
98
+ }
99
+ const name = params['name'];
100
+ const reg = tools.get(name);
101
+ if (reg === undefined) {
102
+ replyError(id, METHOD_NOT_FOUND, `unknown tool '${name}'`);
103
+ return;
104
+ }
105
+ const rawArgs = params['arguments'];
106
+ const args = isObject(rawArgs) ? rawArgs : {};
107
+ const progressToken = readProgressToken(params);
108
+ const tracked = { cancelled: false, byClose: false, cancelCbs: [] };
109
+ // Only tracked when it has a concrete id (a notification cannot be cancelled).
110
+ if (id !== null && id !== undefined)
111
+ inFlight.set(keyOf(id), tracked);
112
+ const ctx = {
113
+ get cancelled() {
114
+ return tracked.cancelled;
115
+ },
116
+ onCancel(cb) {
117
+ if (tracked.cancelled)
118
+ cb();
119
+ else
120
+ tracked.cancelCbs.push(cb);
121
+ },
122
+ sendProgress(payload) {
123
+ if (progressToken === undefined || tracked.cancelled || closed)
124
+ return;
125
+ send({
126
+ jsonrpc: '2.0',
127
+ method: 'notifications/progress',
128
+ params: { progressToken, ...payload },
129
+ });
130
+ },
131
+ };
132
+ try {
133
+ const result = await reg.handler(args, ctx);
134
+ // A CLIENT-cancelled call sends NO response frame (the JSON-RPC/MCP
135
+ // cancel contract). A close-cancelled call still replies — see InFlight.
136
+ if (tracked.cancelled && !tracked.byClose)
137
+ return;
138
+ reply(id, result);
139
+ }
140
+ catch (e) {
141
+ if (tracked.cancelled && !tracked.byClose)
142
+ return;
143
+ err(`mcp: tool '${name}' threw: ${e instanceof Error ? e.message : String(e)}`);
144
+ reply(id, textResult({ error: e instanceof Error ? e.message : String(e) }, true));
145
+ }
146
+ finally {
147
+ if (id !== null && id !== undefined)
148
+ inFlight.delete(keyOf(id));
149
+ }
150
+ }
151
+ function handleCancelled(params) {
152
+ if (!isObject(params))
153
+ return;
154
+ const requestId = params['requestId'];
155
+ if (requestId === undefined || requestId === null)
156
+ return;
157
+ const tracked = inFlight.get(keyOf(requestId));
158
+ if (tracked === undefined)
159
+ return;
160
+ tracked.cancelled = true;
161
+ for (const cb of tracked.cancelCbs.splice(0)) {
162
+ try {
163
+ cb();
164
+ }
165
+ catch {
166
+ // a cancel callback must never take the server down
167
+ }
168
+ }
169
+ }
170
+ function handleInitialize(id, params) {
171
+ const requested = isObject(params) ? params['protocolVersion'] : undefined;
172
+ const agreed = typeof requested === 'string' && RECOGNIZED_PROTOCOL_VERSIONS.has(requested) ? requested : OUR_PROTOCOL_VERSION;
173
+ reply(id, {
174
+ protocolVersion: agreed,
175
+ capabilities: { tools: {} },
176
+ serverInfo: { name: opts.name, version: opts.version },
177
+ });
178
+ }
179
+ function handleToolsList(id) {
180
+ reply(id, {
181
+ tools: [...tools.values()].map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })),
182
+ });
183
+ }
184
+ async function handleLine(line) {
185
+ const trimmed = line.trim();
186
+ if (trimmed === '')
187
+ return;
188
+ let msg;
189
+ try {
190
+ msg = JSON.parse(trimmed);
191
+ }
192
+ catch {
193
+ // No id is recoverable from an unparseable line — reply with a null-id
194
+ // parse error per JSON-RPC and keep serving.
195
+ replyError(null, PARSE_ERROR, 'parse error: line was not valid JSON');
196
+ return;
197
+ }
198
+ if (!isObject(msg) || typeof msg.method !== 'string') {
199
+ const id = isObject(msg) && 'id' in msg ? msg.id : null;
200
+ replyError(id ?? null, INVALID_REQUEST, 'invalid request: missing "method"');
201
+ return;
202
+ }
203
+ const isNotification = !('id' in msg) || msg.id === undefined;
204
+ const id = (msg.id ?? null);
205
+ switch (msg.method) {
206
+ case 'initialize':
207
+ if (!isNotification)
208
+ handleInitialize(id, msg.params);
209
+ return;
210
+ case 'notifications/initialized':
211
+ case 'initialized':
212
+ return; // no-op notification
213
+ case 'ping':
214
+ if (!isNotification)
215
+ reply(id, {});
216
+ return;
217
+ case 'tools/list':
218
+ if (!isNotification)
219
+ handleToolsList(id);
220
+ return;
221
+ case 'tools/call':
222
+ if (isNotification)
223
+ return; // a call with no id has nowhere to answer
224
+ await handleToolsCall(id, msg.params);
225
+ return;
226
+ case 'notifications/cancelled':
227
+ case 'cancelled':
228
+ handleCancelled(msg.params);
229
+ return;
230
+ default:
231
+ if (!isNotification)
232
+ replyError(id, METHOD_NOT_FOUND, `unknown method '${msg.method}'`);
233
+ return;
234
+ }
235
+ }
236
+ function close() {
237
+ if (closed)
238
+ return;
239
+ closed = true;
240
+ for (const tracked of inFlight.values()) {
241
+ tracked.cancelled = true;
242
+ tracked.byClose = true;
243
+ for (const cb of tracked.cancelCbs.splice(0)) {
244
+ try {
245
+ cb();
246
+ }
247
+ catch {
248
+ // best-effort
249
+ }
250
+ }
251
+ }
252
+ inFlight.clear();
253
+ }
254
+ return { handleLine, close };
255
+ }
256
+ // ---- helpers ----------------------------------------------------------------
257
+ function isObject(v) {
258
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
259
+ }
260
+ /** Pull `params._meta.progressToken` (string|number) when present. */
261
+ function readProgressToken(params) {
262
+ const meta = params['_meta'];
263
+ if (!isObject(meta))
264
+ return undefined;
265
+ const tok = meta['progressToken'];
266
+ return typeof tok === 'string' || typeof tok === 'number' ? tok : undefined;
267
+ }
268
+ /**
269
+ * Wire a real byte stream (`process.stdin`) into a server: buffer bytes, split
270
+ * on newlines, feed each complete line to `server.handleLine`, and call
271
+ * `server.close` + `onEof` once on EOF. A trailing partial line at EOF is
272
+ * flushed if non-empty.
273
+ *
274
+ * Every line is DISPATCHED THE MOMENT IT ARRIVES — never queued behind an
275
+ * in-flight `tools/call`. JSON-RPC over MCP is a concurrent protocol: while a
276
+ * long call is outstanding, `notifications/cancelled` must reach the server to
277
+ * abort it and `ping` must still answer. Serializing the pump behind the
278
+ * in-flight call chain would deadlock exactly those frames on the real
279
+ * transport. Per-frame ordering still holds for the non-parking methods because
280
+ * `handleLine` runs synchronously up to the first tool-handler await, and
281
+ * responses are matched by id, not by order.
282
+ *
283
+ * EOF flushes the tail line, then calls `server.close` RIGHT AWAY — `close()`
284
+ * cancels any parked in-flight call, which is what lets a process waiting on
285
+ * this pump actually exit (chaining the close behind a parked call would
286
+ * deadlock EOF against the very call only the close can unpark). A close-cancel
287
+ * does NOT suppress the call's reply the way a client cancel does — every call
288
+ * received before EOF still answers. `onEof` fires only after every dispatched
289
+ * line has settled, so those reply frames are on the pipe before the caller
290
+ * acts on EOF (e.g. exits the process).
291
+ */
292
+ export function pumpStdin(stream, server, onEof) {
293
+ stream.setEncoding?.('utf8');
294
+ let buffer = '';
295
+ let ended = false;
296
+ const pending = new Set();
297
+ const dispatch = (line) => {
298
+ const p = Promise.resolve(server.handleLine(line)).catch(() => { });
299
+ pending.add(p);
300
+ void p.finally(() => pending.delete(p));
301
+ };
302
+ stream.on('data', (chunk) => {
303
+ buffer += typeof chunk === 'string' ? chunk : chunk.toString('utf8');
304
+ let nl = buffer.indexOf('\n');
305
+ while (nl !== -1) {
306
+ const line = buffer.slice(0, nl);
307
+ buffer = buffer.slice(nl + 1);
308
+ dispatch(line);
309
+ nl = buffer.indexOf('\n');
310
+ }
311
+ });
312
+ const finish = () => {
313
+ if (ended)
314
+ return;
315
+ ended = true;
316
+ const tail = buffer;
317
+ buffer = '';
318
+ if (tail.trim() !== '')
319
+ dispatch(tail);
320
+ // Snapshot BEFORE close: close() cancels parked calls, which is what makes
321
+ // these settle. A handler that ignores cancellation would stall EOF — ours
322
+ // all resolve on cancel or are bounded hub calls.
323
+ const flushed = Promise.allSettled([...pending]);
324
+ server.close('stdin-eof');
325
+ void flushed.then(() => onEof?.());
326
+ };
327
+ stream.on('end', finish);
328
+ stream.on('close', finish);
329
+ stream.resume?.();
330
+ }
package/dist/model.d.ts CHANGED
@@ -176,8 +176,44 @@ export declare function pendingOwed(def: WorkflowDef, arts: ArtifactMap): Artifa
176
176
  * output to discharge. This is the scheduling gate (§11.4): necessary, not
177
177
  * sufficient; the commit fingerprint (§12.2) is the correctness boundary.
178
178
  * Assumes `pendingOwed` has already been materialized into `arts`.
179
+ *
180
+ * `opts.ignoreFreeze` (used by `modelCheck`'s stall-vs-true-deadlock
181
+ * recompute): when true, treat every `frozen()` guard as false — i.e.
182
+ * "what would be eligible if every maxAttempts/maxSchemaFailures/held brake
183
+ * were lifted (a human `retry` = unlimited attempts)". It ONLY lifts the
184
+ * freeze; group-exclusivity, input-green gates, and `isDebt` are untouched.
185
+ */
186
+ export declare function eligibleFirings(def: WorkflowDef, arts: ArtifactMap, time?: TimeFacts, opts?: {
187
+ ignoreFreeze?: boolean;
188
+ }): Firing[];
189
+ /**
190
+ * Pure static predicate: can `step` EVER fire, under ANY search bounds?
191
+ *
192
+ * A SOUND detector of deadness: returns false ONLY when we are CERTAIN no
193
+ * firing can ever be pushed for this step, mirroring the discharge-set logic
194
+ * `eligibleFirings` (above) actually uses. When uncertain, returns true (the
195
+ * safe, non-failing default) — a false "structurally dead" would wrongly make
196
+ * `check` exit nonzero, so soundness is biased toward under-reporting.
197
+ *
198
+ * - Reachability: if any consumed stem is not reachable from the workflow
199
+ * inputs (see `reachableStems`), the step can never fire. Belt-and-suspenders
200
+ * — `validateDef`'s `reachabilityErrors` already turns this into a hard error
201
+ * before `modelCheck` ever runs, so this arm is defensive, not the live path.
202
+ * - Judge step (`step.judges`): fires against the judged stem, not a produces
203
+ * set; can-fire iff the judged stem is reachable (already implied by the
204
+ * reachability arm above, since a judge step consumes the judged stem — kept
205
+ * explicit for clarity and to stay correct if judge-step synthesis changes).
206
+ * - reduce: the discharge set is `singletonProduces(step)` only (see the
207
+ * reduce branch of `eligibleFirings`) — zero singleton produces means no
208
+ * firing is ever pushed, regardless of bounds.
209
+ * - map: needs both a map-consume and a map-produce to bind an element.
210
+ * - plain (inputsGreen / allGreen / idle): the discharge set is `plainOutputs`
211
+ * (singleton produces + collection seals) — empty means no firing ever.
212
+ *
213
+ * `reachable` may be precomputed once by the caller and passed in (modelCheck
214
+ * calls this per dead step and must not recompute the fixpoint each time).
179
215
  */
180
- export declare function eligibleFirings(def: WorkflowDef, arts: ArtifactMap, time?: TimeFacts): Firing[];
216
+ export declare function canEverFire(step: StepDef, def: WorkflowDef, reachable?: Set<string>): boolean;
181
217
  /**
182
218
  * The standing guard: re-derive the invariant "an artifact is green only while
183
219
  * every artifact it directly consumed is green and unmoved" and report the
@@ -368,10 +404,29 @@ export declare function applyOutcome(def: WorkflowDef, arts: Map<string, Artifac
368
404
  * Bounded reachability / liveness checker over a workflow definition.
369
405
  *
370
406
  * Explores the full (or depth/state-bounded) state space via BFS to find:
371
- * - deadlocks: reachable states that are not done and have no eligible firings
372
- * - stuck states: reachable states with a stalled debt
407
+ * - a non-done, zero-eligible-firings state is split into exactly ONE of two
408
+ * mutually exclusive buckets by recomputing eligibility with every freeze
409
+ * lifted (unlimited attempts — see `eligibleFirings`'s `ignoreFreeze`):
410
+ * - stall states: the recompute yields >= 1 firing — the state's only
411
+ * blocker is a frozen/stalled debt (maxAttempts / maxSchemaFailures /
412
+ * held). A by-design human-escalation brake. EXPECTED, never a defect.
413
+ * - true deadlocks: the recompute STILL yields zero firings — a genuine
414
+ * structural dead-end with no path to completion even at unlimited
415
+ * attempts. A real defect.
416
+ * - stuck states: reachable states that have a stalled debt but STILL have
417
+ * >= 1 eligible firing elsewhere (a brake tripped on one branch while the
418
+ * line moves on another). Informational only; a no-moves state is never
419
+ * listed here — it lands in `stallStates` or `deadlocks` instead, so no
420
+ * state is ever double-listed.
373
421
  * - completability: whether any reachable state is done (with an example path)
374
- * - dead steps: steps whose name never appears as a firing in any explored transition
422
+ * - dead steps: steps whose name never appears as a firing in any explored
423
+ * transition. Split into two categories by the static `canEverFire` check
424
+ * (independent of search bounds):
425
+ * - structurally-dead: `canEverFire` is false — the step can NEVER fire
426
+ * regardless of `--max-depth`/`--max-states`. A genuine wiring defect.
427
+ * - unreached-within-bounds: `canEverFire` is true — the step CAN fire in
428
+ * principle but the bounded search didn't reach it. A bounds artifact,
429
+ * not a defect; raising `--max-states`/`--max-depth` may surface it.
375
430
  *
376
431
  * Pure — no store, no engine, no IO.
377
432
  */