@openwop/openwop-conformance 2.0.0-rc.6 → 2.0.0-rc.61

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/README.md +8 -3
  2. package/dist/cli.js +24 -34
  3. package/dist/lib/requirement-registry.js +69 -0
  4. package/dist/lib/scenario-disposition.js +84 -11
  5. package/dist/lib/seams.js +42 -0
  6. package/dist/lib/soft-skip.js +39 -8
  7. package/dist/spec-artifacts.lock.json +2 -2
  8. package/package.json +2 -2
  9. package/requirement-aliases.json +4 -1
  10. package/requirements.json +1129 -51
  11. package/scenario-majors.json +60 -3
  12. package/schemas/CORPUS-STAMP.json +40 -37
  13. package/src/cli.ts +23 -30
  14. package/src/global-setup.ts +11 -0
  15. package/src/lib/corpus-stamp.ts +24 -2
  16. package/src/lib/fixtures.ts +31 -0
  17. package/src/lib/requirement-registry.ts +68 -0
  18. package/src/lib/scenario-disposition.ts +88 -9
  19. package/src/lib/soft-skip.ts +42 -7
  20. package/src/lib/sse.ts +8 -0
  21. package/src/scenarios/era-key-stamped-v1.test.ts +156 -0
  22. package/src/scenarios/pause-resume.test.ts +159 -75
  23. package/src/scenarios/v2-advertised-fixtures-exist.test.ts +25 -43
  24. package/src/scenarios/v2-advertised-path-space-served.test.ts +165 -0
  25. package/src/scenarios/v2-coherence-not-in-bundle.test.ts +11 -2
  26. package/src/scenarios/v2-created-run-readable.test.ts +98 -0
  27. package/src/scenarios/v2-dual-stack-negotiation.test.ts +29 -1
  28. package/src/scenarios/v2-effect-seam-manifest.test.ts +21 -55
  29. package/src/scenarios/v2-effect-seam-no-refire.test.ts +88 -0
  30. package/src/scenarios/v2-era-2-append-vocabulary.test.ts +16 -2
  31. package/src/scenarios/v2-era-stamp-universal.test.ts +1 -1
  32. package/src/scenarios/v2-interrupt-token-scheme.test.ts +1 -1
  33. package/src/scenarios/v2-malformed-body-envelope.test.ts +79 -0
  34. package/src/scenarios/v2-run-annotation-not-event.test.ts +71 -0
  35. package/src/scenarios/v2-run-bulk-cancel.test.ts +91 -0
  36. package/src/scenarios/v2-run-cancel.test.ts +97 -0
  37. package/src/scenarios/v2-run-completed-outputs.test.ts +93 -0
  38. package/src/scenarios/v2-run-diff-identical.test.ts +75 -0
  39. package/src/scenarios/v2-run-fork-prefix.test.ts +140 -0
  40. package/src/scenarios/v2-run-fork-refusals.test.ts +70 -0
  41. package/src/scenarios/v2-run-options-limits.test.ts +69 -0
  42. package/src/scenarios/v2-run-pause-resume.test.ts +117 -0
  43. package/src/scenarios/v2-run-snapshot-etag.test.ts +57 -0
  44. package/src/scenarios/v2-sse-last-event-id.test.ts +93 -0
  45. package/src/scenarios/v2-stream-mode-refusal.test.ts +118 -0
  46. package/src/scenarios/v2-stream-sse-projection.test.ts +79 -0
  47. package/src/scenarios/v2-version-header-honored.test.ts +124 -0
  48. package/src/scenarios/version-negotiation.test.ts +25 -3
  49. package/src/setup.ts +104 -50
@@ -0,0 +1,69 @@
1
+ /**
2
+ * `spec/v2/core/runs.md` §Run options — `tags`, `metadata`, and the closed
3
+ * create body (suite 2.0.0, target major 2; unaided; one run created).
4
+ *
5
+ * `tags` is opaque: a host MUST NOT reject a tag on format and MUST answer
6
+ * `400 validation_error` over the limits (100 entries, 256 characters).
7
+ * `metadata` MUST be persisted and surface unchanged on the snapshot, as MUST
8
+ * `tags`. The create body is closed at the composition, so an unknown ROOT key
9
+ * MUST be refused `400 validation_error` (`v2-configurable-closed` covers keys
10
+ * inside `configurable` only).
11
+ *
12
+ * The refusals are the control for the acceptance and vice versa: a host that
13
+ * accepts everything fails the 400 legs; a host that refuses odd tags fails the
14
+ * 201 leg. `""` is deliberately not among the odd tags — the schema's
15
+ * `minLength: 1` is a length rule, not a format rule (finding 4).
16
+ *
17
+ * @see spec/v2/core/runs.md §Run options
18
+ * @see schemas/v2/run-options.schema.json
19
+ */
20
+
21
+ import { describe, it, expect } from 'vitest';
22
+ import { driver, type OpenWOPResponse } from '../lib/driver.js';
23
+ import { v2Discovery } from '../lib/v2.js';
24
+ import { readErrorCode } from '../lib/error-envelope.js';
25
+ import { softSkip } from '../lib/soft-skip.js';
26
+ import { req } from '../lib/requirement-ids.js';
27
+
28
+ const ID = 'openwop.requirement.0171.run-options-limits';
29
+ const DOC = 'spec/v2/core/runs.md §Run options';
30
+ const NOOP = 'conformance-noop';
31
+ const ODD_TAGS = ['has space', 'emoji 🚀', 'slash/colon:pipe|', 'UPPER-and_under', 'x'.repeat(256)];
32
+ const METADATA = { nested: { a: 1, b: [1, '2', null, true] }, s: 'unicode ∞ ok', n: 0 };
33
+
34
+ async function discovery(): Promise<Record<string, unknown> | null> { try { return await v2Discovery(); } catch { return null; } }
35
+ async function http(fn: () => Promise<OpenWOPResponse>): Promise<OpenWOPResponse | null> { try { return await fn(); } catch { return null; } }
36
+
37
+ async function refused(body: Record<string, unknown>, what: string): Promise<string | null> {
38
+ const res = await http(() => driver.post('/runs', body));
39
+ if (res === null) return `POST /runs unreachable (fetch failed) for ${what}`;
40
+ expect(res.status, req(ID, DOC, `${what} MUST be refused 400 — got ${res.status} ${readErrorCode(res.json) ?? ''}`.trim())).toBe(400);
41
+ expect(readErrorCode(res.json), req(ID, DOC, `the refusal for ${what} MUST be validation_error`)).toBe('validation_error');
42
+ return null;
43
+ }
44
+
45
+ describe('v2 run-options-limits (runs.md §Run options)', () => {
46
+ it('more than 100 tags, a tag over 256 characters, and an unknown root key are each refused 400 validation_error', async () => {
47
+ if (!(await discovery())) return softSkip('blocked', 'v2 discovery unreachable');
48
+ const probes: Array<[Record<string, unknown>, string]> = [
49
+ [{ workflowId: NOOP, tags: Array.from({ length: 101 }, (_, i) => `t${i}`) }, '101 tags'],
50
+ [{ workflowId: NOOP, tags: ['y'.repeat(257)] }, 'a 257-character tag'],
51
+ [{ workflowId: NOOP, conformanceUnknownRootKey: 1 }, 'an unknown root key on the create body (closed at the composition)'],
52
+ ];
53
+ for (const [body, what] of probes) { const r = await refused(body, what); if (r) return softSkip('blocked', r); }
54
+ });
55
+
56
+ it('odd-format tags and free-form metadata are accepted and surface unchanged on the snapshot', async () => {
57
+ if (!(await discovery())) return softSkip('blocked', 'v2 discovery unreachable');
58
+ const res = await http(() => driver.post('/runs', { workflowId: NOOP, tags: ODD_TAGS, metadata: METADATA }));
59
+ if (res === null) return softSkip('blocked', 'POST /runs unreachable (fetch failed)');
60
+ expect(res.status, req(ID, DOC, `a host MUST NOT reject a tag on format and MUST accept free-form metadata — got ${res.status} ${readErrorCode(res.json) ?? ''}`.trim())).toBe(201);
61
+ const runId = (res.json as { runId?: unknown } | null)?.runId;
62
+ if (typeof runId !== 'string') return softSkip('blocked', 'the 201 carried no runId');
63
+ const snap = await http(() => driver.get(`/runs/${encodeURIComponent(runId)}`));
64
+ if (snap === null || snap.status !== 200) return softSkip('blocked', `GET /runs/{runId} answered ${snap?.status ?? 'no response'} for the run just created`);
65
+ const body = snap.json as { tags?: unknown; metadata?: unknown } | null;
66
+ expect(body?.tags, req(ID, DOC, 'tags MUST surface unchanged on RunSnapshot')).toEqual(ODD_TAGS);
67
+ expect(body?.metadata, req(ID, DOC, 'metadata MUST be persisted and surface unchanged on RunSnapshot')).toEqual(METADATA);
68
+ });
69
+ });
@@ -0,0 +1,117 @@
1
+ /**
2
+ * `spec/v2/core/runs.md` §Pause and resume (suite 2.0.0, target major 2).
3
+ *
4
+ * Legs:
5
+ * 1. unaided: `:pause` and `:resume` on a terminal run MUST answer 409 with an
6
+ * error envelope. The prose names no code; only `run_terminal` is
7
+ * registered (finding 2). The leg asserts 409 + a code and names none. On
8
+ * its own this leg is one-sided — a host that answers 409 to everything
9
+ * passes it — so its recorded reason says so when leg 2 cannot run.
10
+ * 2. on `conformance-delay`: pause → `202 { runId, status: paused }`; pause
11
+ * again → 409; resume → `202 { runId, status: running }`; the log carries
12
+ * `run.paused` then `run.resumed`. The run is cancelled at the end so
13
+ * nothing is left running.
14
+ *
15
+ * @see spec/v2/core/runs.md §Pause and resume
16
+ * @see conformance/fixtures.md §conformance-delay
17
+ */
18
+
19
+ import { describe, it, expect } from 'vitest';
20
+ import { driver, type OpenWOPResponse } from '../lib/driver.js';
21
+ import { v2Discovery } from '../lib/v2.js';
22
+ import { isFixtureAdvertised } from '../lib/fixtures.js';
23
+ import { readErrorCode } from '../lib/error-envelope.js';
24
+ import { softSkip } from '../lib/soft-skip.js';
25
+ import { req } from '../lib/requirement-ids.js';
26
+
27
+ const ID = 'openwop.requirement.0170.run-pause-resume';
28
+ const DOC = 'spec/v2/core/runs.md §Pause and resume';
29
+ const NOOP = 'conformance-noop';
30
+ const DELAY = 'conformance-delay';
31
+ const TERMINAL = new Set(['completed', 'failed', 'cancelled']);
32
+
33
+ async function discovery(): Promise<Record<string, unknown> | null> { try { return await v2Discovery(); } catch { return null; } }
34
+ async function http(fn: () => Promise<OpenWOPResponse>): Promise<OpenWOPResponse | null> { try { return await fn(); } catch { return null; } }
35
+ const enc = (id: string): string => encodeURIComponent(id);
36
+ async function create(body: Record<string, unknown>): Promise<{ runId: string } | { reason: string }> {
37
+ const res = await http(() => driver.post('/runs', body));
38
+ if (res === null) return { reason: 'POST /runs unreachable (fetch failed)' };
39
+ const runId = (res.json as { runId?: unknown } | null)?.runId;
40
+ if (res.status !== 201 || typeof runId !== 'string') return { reason: `POST /runs answered ${res.status} ${readErrorCode(res.json) ?? ''} — create refused`.trim() };
41
+ return { runId };
42
+ }
43
+ async function statusOf(runId: string): Promise<string | null> {
44
+ const res = await http(() => driver.get(`/runs/${enc(runId)}`));
45
+ return res?.status === 200 ? String((res.json as { status?: unknown } | null)?.status ?? '') : null;
46
+ }
47
+ async function waitFor(runId: string, pred: (s: string) => boolean, ms: number): Promise<string | null> {
48
+ const t0 = Date.now(); let last: string | null = null;
49
+ while (Date.now() - t0 < ms) { last = await statusOf(runId); if (last !== null && pred(last)) return last; await new Promise((r) => setTimeout(r, 250)); }
50
+ return last;
51
+ }
52
+ async function eventTypes(runId: string): Promise<string[] | null> {
53
+ const res = await http(() => driver.get(`/runs/${enc(runId)}/events/poll?timeout=1`));
54
+ const events = (res?.json as { events?: unknown } | null)?.events;
55
+ return res?.status === 200 && Array.isArray(events) ? events.map((e) => String((e as { type?: unknown }).type)) : null;
56
+ }
57
+
58
+ describe('v2 run-pause-resume (runs.md §Pause and resume)', () => {
59
+ it('pause and resume on a terminal run answer 409 with an error envelope', async () => {
60
+ if (!(await discovery())) return softSkip('blocked', 'v2 discovery unreachable');
61
+ const c = await create({ workflowId: NOOP });
62
+ if ('reason' in c) return softSkip('blocked', c.reason);
63
+ const s = await waitFor(c.runId, (x) => TERMINAL.has(x), 10_000);
64
+ if (s === null || !TERMINAL.has(s)) return softSkip('blocked', `the noop run did not reach a terminal status within 10 s (last: ${s ?? 'unreadable'})`);
65
+ const pause = await http(() => driver.post(`/runs/${enc(c.runId)}:pause`, {}));
66
+ if (pause === null) return softSkip('blocked', 'POST /runs/{runId}:pause unreachable (fetch failed)');
67
+ if (pause.status === 404) return softSkip('blocked', 'POST /runs/{runId}:pause answered 404 — pauseRun is a core operation (runs.md §Surface) and is not mounted');
68
+ expect(pause.status, req(ID, DOC, `pause on a terminal (${s}) run MUST answer 409 — got ${pause.status} ${readErrorCode(pause.json) ?? ''}`.trim())).toBe(409);
69
+ expect(readErrorCode(pause.json), req(ID, DOC, `a pause refused because the run is terminal MUST carry run_terminal (got ${String(readErrorCode(pause.json))})`)).toBe('run_terminal');
70
+ const resume = await http(() => driver.post(`/runs/${enc(c.runId)}:resume`, {}));
71
+ if (resume === null) return softSkip('blocked', 'POST /runs/{runId}:resume unreachable (fetch failed)');
72
+ expect(resume.status, req(ID, DOC, `resume on a run that is not paused MUST answer 409 — got ${resume.status} ${readErrorCode(resume.json) ?? ''}`.trim())).toBe(409);
73
+ expect(readErrorCode(resume.json), req(ID, DOC, `a resume refused because the run is terminal MUST carry run_terminal (got ${String(readErrorCode(resume.json))})`)).toBe('run_terminal');
74
+ if (!isFixtureAdvertised(DELAY)) return softSkip('inapplicable', `${DELAY} fixture not advertised — the positive pause/resume leg cannot run, so the two 409s above are witnessed without their control (a host answering 409 to everything would pass them)`);
75
+ });
76
+
77
+ it('a running run pauses (202 paused), refuses a second pause (409), resumes (202 running), and the log carries run.paused then run.resumed', async () => {
78
+ if (!(await discovery())) return softSkip('blocked', 'v2 discovery unreachable');
79
+ if (!isFixtureAdvertised(DELAY)) return softSkip('inapplicable', `${DELAY} fixture not advertised — no run stays running long enough to pause`);
80
+ const c = await create({ workflowId: DELAY, inputs: { delayMs: 15_000 } });
81
+ if ('reason' in c) return softSkip('blocked', c.reason);
82
+ const running = await waitFor(c.runId, (x) => x === 'running' || TERMINAL.has(x), 5_000);
83
+ if (running !== 'running') return softSkip('blocked', `${DELAY} did not reach running within 5 s (last: ${running ?? 'unreadable'})`);
84
+ try {
85
+ const pause = await http(() => driver.post(`/runs/${enc(c.runId)}:pause`, { reason: 'conformance', drainPolicy: 'immediate' }));
86
+ if (pause === null) return softSkip('blocked', 'POST /runs/{runId}:pause unreachable (fetch failed)');
87
+ if (pause.status === 404) return softSkip('blocked', 'POST /runs/{runId}:pause answered 404 — not mounted');
88
+ expect(pause.status, req(ID, DOC, `pauseRun on a running run MUST answer 202 — got ${pause.status} ${readErrorCode(pause.json) ?? ''}`.trim())).toBe(202);
89
+ const pb = pause.json as { runId?: unknown; status?: unknown } | null;
90
+ expect(pb?.runId, req(ID, DOC, 'the 202 MUST carry the runId')).toBe(c.runId);
91
+ expect(pb?.status, req(ID, DOC, `the 202 MUST carry status paused (got ${String(pb?.status)})`)).toBe('paused');
92
+ const again = await http(() => driver.post(`/runs/${enc(c.runId)}:pause`, {}));
93
+ expect(again?.status ?? null, req(ID, DOC, `a second pause on a paused run MUST answer 409 — got ${again?.status ?? 'no response'}`)).toBe(409);
94
+ expect(readErrorCode(again?.json), req(ID, DOC, `a pause refused on a non-terminal run MUST carry run_state_conflict (got ${String(readErrorCode(again?.json))})`)).toBe('run_state_conflict');
95
+ // `details` sits at the envelope ROOT (schemas/v2/error-envelope.schema.json), not under `error`.
96
+ const runStatus = (again?.json as { details?: { runStatus?: unknown } } | null)?.details?.runStatus;
97
+ expect(runStatus, req(ID, DOC, `run_state_conflict MUST carry details.runStatus naming the status that refused it (got ${String(runStatus)})`)).toBe('paused');
98
+ const resume = await http(() => driver.post(`/runs/${enc(c.runId)}:resume`, { reason: 'conformance' }));
99
+ expect(resume?.status ?? null, req(ID, DOC, `resumeRun on a paused run MUST answer 202 — got ${resume?.status ?? 'no response'} ${readErrorCode(resume?.json) ?? ''}`.trim())).toBe(202);
100
+ const rb = resume?.json as { runId?: unknown; status?: unknown } | null;
101
+ expect(rb?.status, req(ID, DOC, `the 202 MUST carry status running (got ${String(rb?.status)})`)).toBe('running');
102
+ const types = await eventTypes(c.runId);
103
+ const p = types?.indexOf('run.paused') ?? -1; const r = types?.indexOf('run.resumed') ?? -1;
104
+ expect(p >= 0 && r > p, req(ID, 'spec/v2/core/events.md §run.paused', `the log MUST carry run.paused then run.resumed (types: ${(types ?? []).join(', ')})`)).toBe(true);
105
+ // An immediate pause cuts the executing attempt BETWEEN events: no terminal
106
+ // node event for it, ever — a node.failed here makes a replay fold a
107
+ // failure the source never had (runs.md §Pause and resume; replay.md).
108
+ const between = (types ?? []).slice(p + 1, r);
109
+ expect(between.some((t) => t === 'node.failed' || t === 'node.completed' || t === 'node.cancelled'), req(ID, DOC, `with drainPolicy immediate the interrupted attempt MUST NOT record a terminal node event (between run.paused and run.resumed: ${between.join(', ') || 'nothing'})`)).toBe(false);
110
+ const poll = await http(() => driver.get(`/runs/${enc(c.runId)}/events/poll?timeout=1`));
111
+ const paused = ((poll?.json as { events?: Array<{ type?: unknown; payload?: { drainPolicy?: unknown } }> } | null)?.events ?? []).find((e) => e.type === 'run.paused');
112
+ expect(paused?.payload?.drainPolicy, req(ID, DOC, `run.paused's payload MUST echo the request's drainPolicy word (got ${String(paused?.payload?.drainPolicy)})`)).toBe('immediate');
113
+ } finally {
114
+ await http(() => driver.post(`/runs/${enc(c.runId)}/cancel`, { reason: 'conformance cleanup' }));
115
+ }
116
+ }, 30_000);
117
+ });
@@ -0,0 +1,57 @@
1
+ /**
2
+ * `spec/v2/core/runs.md` §Snapshot — the conditional GET (suite 2.0.0, target
3
+ * major 2; unaided; one run created).
4
+ *
5
+ * The 200 SHOULD carry a strong `ETag`; WHEN PRESENT, a matching
6
+ * `If-None-Match` MUST receive `304` with no body. The SHOULD gates the MUST:
7
+ * a host that sends no ETag records `inapplicable`. Every response carries
8
+ * `OpenWOP-Version` (versioning.md §1.4), the 304 included.
9
+ *
10
+ * Control: a non-matching `If-None-Match` MUST receive 200 with the body — a
11
+ * host that answers 304 to any conditional request fails here. `headers.md`
12
+ * scopes `If-None-Match` to the discovery document; runs.md applies it to the
13
+ * snapshot with a MUST (finding 5, filed).
14
+ *
15
+ * @see spec/v2/core/runs.md §Snapshot
16
+ * @see spec/v2/core/versioning.md §1.4
17
+ */
18
+
19
+ import { describe, it, expect } from 'vitest';
20
+ import { driver, type OpenWOPResponse } from '../lib/driver.js';
21
+ import { v2Discovery } from '../lib/v2.js';
22
+ import { readErrorCode } from '../lib/error-envelope.js';
23
+ import { softSkip } from '../lib/soft-skip.js';
24
+ import { req } from '../lib/requirement-ids.js';
25
+
26
+ const ID = 'openwop.requirement.0170.run-snapshot-etag';
27
+ const DOC = 'spec/v2/core/runs.md §Snapshot';
28
+ const NOOP = 'conformance-noop';
29
+
30
+ async function discovery(): Promise<Record<string, unknown> | null> { try { return await v2Discovery(); } catch { return null; } }
31
+ async function http(fn: () => Promise<OpenWOPResponse>): Promise<OpenWOPResponse | null> { try { return await fn(); } catch { return null; } }
32
+
33
+ describe('v2 run-snapshot-etag (runs.md §Snapshot)', () => {
34
+ it('a matching If-None-Match receives 304 with no body and the version header; a non-matching one receives 200', async () => {
35
+ if (!(await discovery())) return softSkip('blocked', 'v2 discovery unreachable');
36
+ const created = await http(() => driver.post('/runs', { workflowId: NOOP }));
37
+ if (created === null) return softSkip('blocked', 'POST /runs unreachable (fetch failed)');
38
+ const runId = (created.json as { runId?: unknown } | null)?.runId;
39
+ if (created.status !== 201 || typeof runId !== 'string') return softSkip('blocked', `POST /runs answered ${created.status} ${readErrorCode(created.json) ?? ''} — create refused`.trim());
40
+ const path = `/runs/${encodeURIComponent(runId)}`;
41
+ // Let the noop settle so the tag is stable across the two conditional reads.
42
+ await new Promise((r) => setTimeout(r, 1_000));
43
+ const first = await http(() => driver.get(path));
44
+ if (first === null || first.status !== 200) return softSkip('blocked', `GET /runs/{runId} answered ${first?.status ?? 'no response'}`);
45
+ const etag = first.headers.get('etag');
46
+ if (!etag) return softSkip('inapplicable', 'the snapshot carries no ETag — runs.md §Snapshot makes the ETag a SHOULD; the 304 rule applies only when it is present');
47
+ const hit = await http(() => driver.get(path, { headers: { 'If-None-Match': etag } }));
48
+ if (hit === null) return softSkip('blocked', 'conditional GET unreachable (fetch failed)');
49
+ expect(hit.status, req(ID, DOC, `a request whose If-None-Match matches the ETag MUST receive 304 — got ${hit.status}`)).toBe(304);
50
+ expect(hit.text.length, req(ID, DOC, `the 304 MUST carry no body (got ${hit.text.length} byte(s))`)).toBe(0);
51
+ expect(hit.headers.get('openwop-version'), req(ID, 'spec/v2/core/versioning.md §1.4', 'every response carries OpenWOP-Version, the 304 included')).not.toBeNull();
52
+ const miss = await http(() => driver.get(path, { headers: { 'If-None-Match': '"openwop-conformance-no-such-tag"' } }));
53
+ if (miss === null) return softSkip('blocked', 'conditional GET unreachable (fetch failed)');
54
+ expect(miss.status, req(ID, DOC, `a non-matching If-None-Match MUST receive 200 with the body — got ${miss.status} (a host answering 304 to any conditional request is not honouring the tag)`)).toBe(200);
55
+ expect((miss.json as { runId?: unknown } | null)?.runId, req(ID, DOC, 'the 200 body is the snapshot')).toBe(runId);
56
+ });
57
+ });
@@ -0,0 +1,93 @@
1
+ /**
2
+ * `spec/v2/core/events.md` §SSE frames — `Last-Event-ID` resumes every mode
3
+ * (suite 2.0.0, target major 2; unaided; one run created).
4
+ *
5
+ * The host MUST look up the event with that sequence, MUST begin at the next
6
+ * sequence, and MUST NOT re-emit the resumption point; in `values` mode the
7
+ * resumption MUST emit a `state.snapshot` first. Frames carry `id:` = the
8
+ * sequence (0-based: the first frame's id is `0`, so ids are tested for
9
+ * presence and parsed, never for truthiness).
10
+ *
11
+ * Legs and controls, all on one completed noop run:
12
+ * 1. the full stream: ≥1 frame, numeric ids, closed by the server;
13
+ * 2. resume at the first id: the first resumed id is greater, the resumption
14
+ * id is absent, and the resumed set equals the full set minus every id at
15
+ * or below it — one assertion catches loss and duplication;
16
+ * 3. resume at the last id: zero frames, closed by server (a host that ignores
17
+ * the header re-sends all N against an expected 0; a host that closes
18
+ * every stream empty fails leg 1);
19
+ * 4. if `values` is served: a `values` resume's first frame is
20
+ * `event: state.snapshot` (a frame name, not a type — §SSE frames).
21
+ *
22
+ * @see spec/v2/core/events.md §SSE frames
23
+ */
24
+
25
+ import { describe, it, expect } from 'vitest';
26
+ import { driver, type OpenWOPResponse } from '../lib/driver.js';
27
+ import { subscribe, type SseEvent } from '../lib/sse.js';
28
+ import { v2Discovery } from '../lib/v2.js';
29
+ import { readErrorCode } from '../lib/error-envelope.js';
30
+ import { softSkip } from '../lib/soft-skip.js';
31
+ import { req } from '../lib/requirement-ids.js';
32
+
33
+ const ID = 'openwop.requirement.0171.sse-last-event-id';
34
+ const DOC = 'spec/v2/core/events.md §SSE frames';
35
+ const NOOP = 'conformance-noop';
36
+ const V2 = { 'OpenWOP-Version': '2.0' };
37
+
38
+ async function discovery(): Promise<Record<string, unknown> | null> { try { return await v2Discovery(); } catch { return null; } }
39
+ async function http(fn: () => Promise<OpenWOPResponse>): Promise<OpenWOPResponse | null> { try { return await fn(); } catch { return null; } }
40
+ const enc = (id: string): string => encodeURIComponent(id);
41
+ /** The frame's sequence, or null when the frame carries no id — `0` is a valid id. */
42
+ function seqOf(f: SseEvent): number | null { if (f.id === null || f.id === '') return null; const n = Number.parseInt(f.id, 10); return Number.isFinite(n) ? n : null; }
43
+
44
+ async function createSettled(): Promise<{ runId: string } | { reason: string }> {
45
+ const res = await http(() => driver.post('/runs', { workflowId: NOOP }));
46
+ if (res === null) return { reason: 'POST /runs unreachable (fetch failed)' };
47
+ const runId = (res.json as { runId?: unknown } | null)?.runId;
48
+ if (res.status !== 201 || typeof runId !== 'string') return { reason: `POST /runs answered ${res.status} ${readErrorCode(res.json) ?? ''}`.trim() };
49
+ const t0 = Date.now();
50
+ while (Date.now() - t0 < 10_000) {
51
+ const s = await http(() => driver.get(`/runs/${enc(runId)}`));
52
+ if (s?.status === 200 && ['completed', 'failed', 'cancelled'].includes(String((s.json as { status?: unknown }).status))) return { runId };
53
+ await new Promise((r) => setTimeout(r, 250));
54
+ }
55
+ return { reason: 'the noop run did not settle within 10 s' };
56
+ }
57
+
58
+ describe('v2 sse-last-event-id (events.md §SSE frames)', () => {
59
+ it('Last-Event-ID resumes at the next sequence, never re-emits the resumption point, loses nothing, and at the last id yields nothing', async () => {
60
+ if (!(await discovery())) return softSkip('blocked', 'v2 discovery unreachable');
61
+ const c = await createSettled(); if ('reason' in c) return softSkip('blocked', c.reason);
62
+ const path = `/runs/${enc(c.runId)}/events?streamMode=debug`;
63
+ const full = await subscribe(path, { timeoutMs: 8_000, extraHeaders: V2 });
64
+ if (full.status === 404) return softSkip('blocked', 'GET /runs/{runId}/events answered 404 — streamRunEvents is a core operation and is not mounted');
65
+ expect(full.status, req(ID, DOC, `the stream MUST answer 200 — got ${full.status}`)).toBe(200);
66
+ expect(full.events.length, req(ID, DOC, 'the completed log MUST stream as at least one frame')).toBeGreaterThan(0);
67
+ expect(full.closedBy, req(ID, DOC, `the host MUST close after the terminal event (closed by ${full.closedBy})`)).toBe('server');
68
+ const ids = full.events.map(seqOf);
69
+ expect(ids.every((n) => n !== null), req(ID, DOC, `every frame MUST carry id: = its sequence (frames without a parseable id: ${ids.filter((n) => n === null).length} of ${ids.length})`)).toBe(true);
70
+ const seqs = ids as number[];
71
+ expect([...seqs].sort((a, b) => a - b), req(ID, DOC, 'frames MUST arrive in log order')).toEqual(seqs);
72
+ const first = seqs[0]!; const last = seqs[seqs.length - 1]!;
73
+
74
+ const resumed = await subscribe(path, { timeoutMs: 8_000, extraHeaders: V2, lastEventId: String(first) });
75
+ expect(resumed.status, req(ID, DOC, `a resume with Last-Event-ID MUST answer 200 — got ${resumed.status}`)).toBe(200);
76
+ const rseqs = resumed.events.map(seqOf).filter((n): n is number => n !== null);
77
+ expect(rseqs.includes(first), req(ID, DOC, `the host MUST NOT re-emit the resumption point (Last-Event-ID ${first} re-emitted)`)).toBe(false);
78
+ expect(rseqs, req(ID, DOC, `the host MUST begin at the next sequence and lose nothing: resumed ids (${rseqs.join(',')}) MUST equal the full set minus every id ≤ ${first} (${seqs.filter((n) => n > first).join(',')})`)).toEqual(seqs.filter((n) => n > first));
79
+
80
+ const atEnd = await subscribe(path, { timeoutMs: 8_000, extraHeaders: V2, lastEventId: String(last) });
81
+ expect(atEnd.status, req(ID, DOC, `a resume at the terminal sequence MUST answer 200 — got ${atEnd.status}`)).toBe(200);
82
+ expect(atEnd.events.length, req(ID, DOC, `a resume at the last sequence (${last}) MUST emit nothing and close — a host ignoring the header re-sends all ${seqs.length} (got ${atEnd.events.length})`)).toBe(0);
83
+ expect(atEnd.closedBy, req(ID, DOC, 'the host MUST close the empty resume itself')).toBe('server');
84
+
85
+ // values: resumption MUST emit a state.snapshot first — only where the host serves values.
86
+ const probe = await http(() => driver.get(`/runs/${enc(c.runId)}/events?streamMode=bogus`, { headers: { Accept: 'text/event-stream' } }));
87
+ const supported = (probe?.json as { details?: { supported?: unknown } } | null)?.details?.supported;
88
+ if (!Array.isArray(supported) || !supported.includes('values')) return softSkip('inapplicable', `values mode not served (details.supported: ${JSON.stringify(supported)}) — the state.snapshot-first resumption leg does not apply`);
89
+ const values = await subscribe(`/runs/${enc(c.runId)}/events?streamMode=values`, { timeoutMs: 8_000, extraHeaders: V2, lastEventId: String(first) });
90
+ expect(values.status, req(ID, DOC, `a values resume MUST answer 200 — got ${values.status}`)).toBe(200);
91
+ expect(values.events[0]?.event ?? null, req(ID, DOC, `in values mode a resumption MUST emit a state.snapshot first (first frame: ${values.events[0]?.event ?? 'none'})`)).toBe('state.snapshot');
92
+ }, 45_000);
93
+ });
@@ -0,0 +1,118 @@
1
+ /**
2
+ * `spec/v2/core/events.md` §The events channel — `streamMode` is one pattern,
3
+ * refused with `400 unsupported_stream_mode`, validated before content
4
+ * negotiation; `bufferMs` batches (suite 2.0.0, target major 2; unaided; one
5
+ * run created).
6
+ *
7
+ * Legs:
8
+ * 1. `?streamMode=bogus` → 400 `unsupported_stream_mode`, `details.supported`
9
+ * a non-empty array of individual modes; the same request with
10
+ * `Accept: application/json` → still 400, never 406 (validation runs
11
+ * before content negotiation; the only v2 406 is a version mismatch and
12
+ * this request names a listed major); `?streamMode=updates,values` → 400
13
+ * (`values` never combines); a mode absent from `supported`, if any → 400.
14
+ * 2. control: `?streamMode=updates` → 200 `text/event-stream` with ≥1 frame
15
+ * (a host that answers 400 to every mode fails here; `updates` is a MUST).
16
+ * 3. `?bufferMs=200` → at least one `event: batch` frame whose `data:` is an
17
+ * array of RunEventDoc, and the flattened frames equal the log in order;
18
+ * without `bufferMs` no frame is `batch` (the control). "Every frame is
19
+ * batch" is deliberately NOT asserted: a consumer MUST tolerate an
20
+ * unbatched frame beside a one-element batch (§SSE frames).
21
+ *
22
+ * @see spec/v2/core/events.md §The events channel, §SSE frames
23
+ * @see spec/v2/errors.json unsupported_stream_mode
24
+ */
25
+
26
+ import { describe, it, expect } from 'vitest';
27
+ import { driver, type OpenWOPResponse } from '../lib/driver.js';
28
+ import { subscribe, type SseEvent } from '../lib/sse.js';
29
+ import { v2Discovery } from '../lib/v2.js';
30
+ import { readErrorCode } from '../lib/error-envelope.js';
31
+ import { softSkip } from '../lib/soft-skip.js';
32
+ import { req } from '../lib/requirement-ids.js';
33
+
34
+ const ID = 'openwop.requirement.0171.stream-mode-refusal';
35
+ const DOC = 'spec/v2/core/events.md §The events channel';
36
+ const NOOP = 'conformance-noop';
37
+ const MODES = ['values', 'updates', 'messages', 'debug'];
38
+ const V2 = { 'OpenWOP-Version': '2.0' };
39
+
40
+ async function discovery(): Promise<Record<string, unknown> | null> { try { return await v2Discovery(); } catch { return null; } }
41
+ async function http(fn: () => Promise<OpenWOPResponse>): Promise<OpenWOPResponse | null> { try { return await fn(); } catch { return null; } }
42
+ const enc = (id: string): string => encodeURIComponent(id);
43
+
44
+ async function createSettled(): Promise<{ runId: string } | { reason: string }> {
45
+ const res = await http(() => driver.post('/runs', { workflowId: NOOP }));
46
+ if (res === null) return { reason: 'POST /runs unreachable (fetch failed)' };
47
+ const runId = (res.json as { runId?: unknown } | null)?.runId;
48
+ if (res.status !== 201 || typeof runId !== 'string') return { reason: `POST /runs answered ${res.status} ${readErrorCode(res.json) ?? ''}`.trim() };
49
+ const t0 = Date.now();
50
+ while (Date.now() - t0 < 10_000) {
51
+ const s = await http(() => driver.get(`/runs/${enc(runId)}`));
52
+ if (s?.status === 200 && ['completed', 'failed', 'cancelled'].includes(String((s.json as { status?: unknown }).status))) return { runId };
53
+ await new Promise((r) => setTimeout(r, 250));
54
+ }
55
+ return { reason: 'the noop run did not settle within 10 s' };
56
+ }
57
+
58
+ /** The events a frame carries: a batch frame's array flattened, a plain frame's one document. */
59
+ function docsOf(frame: SseEvent): Array<Record<string, unknown>> {
60
+ try { const p = JSON.parse(frame.data) as unknown; return (Array.isArray(p) ? p : [p]).filter((x): x is Record<string, unknown> => !!x && typeof x === 'object'); } catch { return []; }
61
+ }
62
+
63
+ describe('v2 stream-mode-refusal (events.md §The events channel)', () => {
64
+ it('a value outside the pattern, a forbidden combination, and an unimplemented mode are refused 400 unsupported_stream_mode with details.supported — before content negotiation', async () => {
65
+ if (!(await discovery())) return softSkip('blocked', 'v2 discovery unreachable');
66
+ const c = await createSettled(); if ('reason' in c) return softSkip('blocked', c.reason);
67
+ const path = `/runs/${enc(c.runId)}/events`;
68
+ const bogus = await http(() => driver.get(`${path}?streamMode=bogus`, { headers: { Accept: 'text/event-stream' } }));
69
+ if (bogus === null) return softSkip('blocked', 'GET /runs/{runId}/events unreachable (fetch failed)');
70
+ if (bogus.status === 404) return softSkip('blocked', 'GET /runs/{runId}/events answered 404 — streamRunEvents is a core operation (runs.md §Surface) and is not mounted');
71
+ expect(bogus.status, req(ID, DOC, `a streamMode outside the pattern MUST be refused 400 — got ${bogus.status}`)).toBe(400);
72
+ expect(readErrorCode(bogus.json), req(ID, DOC, 'the refusal MUST be unsupported_stream_mode')).toBe('unsupported_stream_mode');
73
+ const supported = (bogus.json as { details?: { supported?: unknown } } | null)?.details?.supported;
74
+ expect(Array.isArray(supported) && supported.length > 0 && supported.every((m) => MODES.includes(String(m))), req(ID, DOC, `details.supported MUST list each individual mode the host serves (got ${JSON.stringify(supported)})`)).toBe(true);
75
+ expect((supported as string[]).includes('updates'), req(ID, DOC, 'a host MUST implement updates, so supported MUST list it')).toBe(true);
76
+
77
+ const negotiated = await http(() => driver.get(`${path}?streamMode=bogus`, { headers: { Accept: 'application/json' } }));
78
+ expect(negotiated?.status ?? null, req(ID, DOC, `validation MUST run before any content negotiation: a bogus streamMode with Accept: application/json is still 400 unsupported_stream_mode, never 406 (the only v2 406 is a version mismatch and this request names a listed major) — got ${negotiated?.status ?? 'no response'}`)).toBe(400);
79
+
80
+ const combo = await http(() => driver.get(`${path}?streamMode=updates,values`, { headers: { Accept: 'text/event-stream' } }));
81
+ expect(combo?.status ?? null, req(ID, DOC, `values never combines: streamMode=updates,values is outside the pattern and MUST be refused 400 — got ${combo?.status ?? 'no response'}`)).toBe(400);
82
+ expect(readErrorCode(combo?.json), req(ID, DOC, 'the refusal MUST be unsupported_stream_mode')).toBe('unsupported_stream_mode');
83
+
84
+ // The unimplemented-mode leg has something to request only when a mode is
85
+ // absent from details.supported; a host serving all four has no such mode,
86
+ // and the three refusals above are its witness.
87
+ const missing = MODES.find((m) => !(supported as string[]).includes(m));
88
+ if (missing !== undefined) {
89
+ const unimpl = await http(() => driver.get(`${path}?streamMode=${missing}`, { headers: { Accept: 'text/event-stream' } }));
90
+ expect(unimpl?.status ?? null, req(ID, DOC, `a mode the host does not implement (${missing}, absent from details.supported) MUST be refused 400 — got ${unimpl?.status ?? 'no response'}`)).toBe(400);
91
+ expect(readErrorCode(unimpl?.json), req(ID, DOC, 'the refusal MUST be unsupported_stream_mode')).toBe('unsupported_stream_mode');
92
+ }
93
+ }, 30_000);
94
+
95
+ it('updates streams 200 text/event-stream with frames; bufferMs yields at least one batch frame whose data is an array and loses nothing; without bufferMs no frame is batch', async () => {
96
+ if (!(await discovery())) return softSkip('blocked', 'v2 discovery unreachable');
97
+ const c = await createSettled(); if ('reason' in c) return softSkip('blocked', c.reason);
98
+ const path = `/runs/${enc(c.runId)}/events`;
99
+ const plain = await subscribe(`${path}?streamMode=updates`, { timeoutMs: 8_000, extraHeaders: V2 });
100
+ if (plain.status === 404) return softSkip('blocked', 'GET /runs/{runId}/events answered 404 — not mounted');
101
+ expect(plain.status, req(ID, DOC, `updates is a MUST: streamMode=updates MUST answer 200 — got ${plain.status} (the control for the refusals: a host answering 400 to every mode fails here)`)).toBe(200);
102
+ expect(plain.events.length, req(ID, 'spec/v2/core/events.md §SSE frames', 'the completed run\'s log MUST stream as at least one frame before the server closes')).toBeGreaterThan(0);
103
+ expect(plain.closedBy, req(ID, 'spec/v2/core/events.md §SSE frames', `the host MUST close after the terminal event (closed by ${plain.closedBy})`)).toBe('server');
104
+ expect(plain.events.some((f) => f.event === 'batch'), req(ID, 'spec/v2/core/events.md §SSE frames', 'without bufferMs no frame is a batch (the control for the batch leg)')).toBe(false);
105
+ const plainDocs = plain.events.flatMap(docsOf).map((d) => d['sequence']);
106
+
107
+ const buffered = await subscribe(`${path}?streamMode=updates&bufferMs=200`, { timeoutMs: 8_000, extraHeaders: V2 });
108
+ expect(buffered.status, req(ID, 'spec/v2/core/events.md §SSE frames', `streamMode=updates&bufferMs=200 MUST answer 200 — got ${buffered.status}`)).toBe(200);
109
+ const batches = buffered.events.filter((f) => f.event === 'batch');
110
+ expect(batches.length, req(ID, 'spec/v2/core/events.md §SSE frames', `with bufferMs the host accumulates events into event: batch frames — none seen among ${buffered.events.length} frame(s) (${[...new Set(buffered.events.map((f) => f.event))].join(', ')})`)).toBeGreaterThan(0);
111
+ for (const b of batches) {
112
+ let parsed: unknown; try { parsed = JSON.parse(b.data); } catch { parsed = undefined; }
113
+ expect(Array.isArray(parsed), req(ID, 'spec/v2/core/events.md §SSE frames', 'a batch frame\'s data MUST be an array of RunEventDoc')).toBe(true);
114
+ }
115
+ const bufferedDocs = buffered.events.flatMap(docsOf).map((d) => d['sequence']);
116
+ expect(bufferedDocs, req(ID, 'spec/v2/core/events.md §SSE frames', 'batching MUST NOT lose or reorder events: the flattened buffered stream equals the unbuffered log (a one-element batch and an unbatched frame are both tolerated)')).toEqual(plainDocs);
117
+ }, 30_000);
118
+ });
@@ -0,0 +1,79 @@
1
+ /**
2
+ * `spec/v2/core/events.md` §SSE frames + `identity.md` §5 — every `data:` frame
3
+ * on the major-2 run stream names the run by its tenant-bound id (suite 2.0.0,
4
+ * target major 2; unaided).
5
+ *
6
+ * This scenario exists because both production hosts shipped the same defect
7
+ * and the suite could not see it. Each built one projection seam for the
8
+ * tenant-bound `runId` and each found an emitter outside it on the stream
9
+ * path: one host's SSE route had three `res.write` sites and no per-frame
10
+ * projector at all; the other's per-frame path projected while its `batch`
11
+ * flush wrote the raw array. Sixteen green mount tests on one host all used
12
+ * `res.json` handlers. Of the 56 `v2-*` files, none read a stream frame —
13
+ * `grep -E '^v2-.*(sse|stream)'` was empty — so both defects were invisible to
14
+ * the suite by construction and were found by a live witness and by a peer's
15
+ * report. A tier-1 host asked for this file by name.
16
+ *
17
+ * The assertion is one line: every frame's `runId` is the bound id the create
18
+ * returned. It is asserted per frame rather than on the first, because the
19
+ * batch-flush variant projects the first frame and not the rest.
20
+ *
21
+ * @see spec/v2/core/events.md §SSE frames
22
+ * @see spec/v2/core/identity.md §5
23
+ */
24
+
25
+ import { describe, it, expect } from 'vitest';
26
+ import { driver, type OpenWOPResponse } from '../lib/driver.js';
27
+ import { v2Discovery, v2Validator } from '../lib/v2.js';
28
+ import { streamEvents } from '../lib/era2-seed.js';
29
+ import { readErrorCode } from '../lib/error-envelope.js';
30
+ import { softSkip } from '../lib/soft-skip.js';
31
+ import { req } from '../lib/requirement-ids.js';
32
+
33
+ const ID = 'openwop.requirement.0171.stream-sse-projection';
34
+ const DOC = 'spec/v2/core/events.md §SSE frames';
35
+ const NOOP_WORKFLOW_ID = 'conformance-noop';
36
+ const RUN_ID = /^[A-Za-z0-9._~-]{1,128}\/[A-Za-z0-9._~-]{16,128}$/;
37
+
38
+ async function http(fn: () => Promise<OpenWOPResponse>): Promise<OpenWOPResponse | null> {
39
+ try { return await fn(); } catch { return null; }
40
+ }
41
+
42
+ async function createRun(): Promise<{ runId: string } | { reason: string }> {
43
+ try { if (!(await v2Discovery())) return { reason: 'v2 discovery unreachable' }; } catch { return { reason: 'v2 discovery unreachable' }; }
44
+ const res = await http(() => driver.post('/runs', { workflowId: NOOP_WORKFLOW_ID }));
45
+ if (res === null) return { reason: 'POST /runs unreachable (fetch failed)' };
46
+ const runId = (res.json as { runId?: unknown } | undefined)?.runId;
47
+ if (res.status !== 201 || typeof runId !== 'string') return { reason: `POST /runs {workflowId: ${NOOP_WORKFLOW_ID}} answered ${res.status} ${readErrorCode(res.json) ?? ''} — the smallest valid create was refused (fixture not seeded?)`.trim() };
48
+ return { runId };
49
+ }
50
+
51
+ describe('v2 stream-sse-projection (events.md §SSE frames)', () => {
52
+ it('every data: frame on the major-2 stream carries the tenant-bound runId of the run it belongs to', async () => {
53
+ const c = await createRun();
54
+ if ('reason' in c) return softSkip('blocked', c.reason);
55
+ expect(RUN_ID.test(c.runId), req(ID, 'spec/v2/core/identity.md §5', `the created runId MUST be tenant-bound before the stream can be held to it (got ${c.runId})`)).toBe(true);
56
+
57
+ const s = await streamEvents(c.runId);
58
+ if (s === null) return softSkip('blocked', 'GET /runs/{runId}/events (SSE, OpenWOP-Version: 2.0) unreachable (fetch failed)');
59
+ if (s.status !== 200) return softSkip('blocked', `GET /runs/{runId}/events (SSE) answered ${s.status} for the run just created`);
60
+ if (s.events.length === 0) return softSkip('blocked', 'the stream delivered no data: frames within the window — nothing to hold to the grammar');
61
+
62
+ const validate = v2Validator('run-event');
63
+ let i = 0;
64
+ for (const ev of s.events) {
65
+ i += 1;
66
+ const rid = (ev as { runId?: unknown }).runId;
67
+ expect(
68
+ typeof rid === 'string' && RUN_ID.test(rid),
69
+ req(ID, DOC, `frame ${i} (${String((ev as { type?: unknown }).type)}): data.runId MUST be tenant-bound <tenantId>/<opaque> (identity.md §5) — a stream frame is a rendering of the run event and every rendering of a v2 runId uses the same grammar; a bare storage id here is the projection seam missing the stream path (got ${JSON.stringify(rid)})`),
70
+ ).toBe(true);
71
+ expect(
72
+ rid,
73
+ req(ID, DOC, `frame ${i}: data.runId MUST be the run's own bound id — asserted on EVERY frame, not the first, because a batch flush that skips the per-frame projector projects frame 1 and not the rest`),
74
+ ).toBe(c.runId);
75
+ const r = validate(ev);
76
+ expect(r.ok, req(ID, DOC, `frame ${i}: data MUST be a valid RunEventDoc (run-event.schema.json) — ${r.errors}`)).toBe(true);
77
+ }
78
+ });
79
+ });