@dreamforgestudiollc/emet 0.3.6 → 0.3.7

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 (88) hide show
  1. package/.env.example +29 -0
  2. package/CHANGELOG.md +25 -1
  3. package/README.md +9 -3
  4. package/RELEASE_NOTES-0.2.6.md +1 -1
  5. package/RELEASE_NOTES-0.3.7.md +19 -0
  6. package/docs/BOTS.md +1 -1
  7. package/docs/DEPLOY.md +14 -1
  8. package/docs/ERROR-CODES-SPEC.md +4 -0
  9. package/docs/ERROR-CODES.md +7 -0
  10. package/docs/ROADMAP.md +3 -3
  11. package/docs/SETUP.md +4 -0
  12. package/docs/SUBKEYS.md +3 -1
  13. package/docs/continuity-currency-statechart.md +34 -0
  14. package/docs/features/README.md +21 -0
  15. package/docs/features/access.md +28 -0
  16. package/docs/features/documents.md +35 -0
  17. package/docs/features/errors.md +32 -0
  18. package/docs/features/gems.md +31 -0
  19. package/docs/features/memory.md +29 -0
  20. package/docs/features/pages.md +28 -0
  21. package/docs/features/record.md +27 -0
  22. package/docs/features/search.md +27 -0
  23. package/docs/features/startup.md +29 -0
  24. package/docs/features/subkeys.md +30 -0
  25. package/docs/features/transcripts.md +33 -0
  26. package/docs/per-tag-handoff-statechart.md +147 -0
  27. package/docs/subkey-session-statechart.md +57 -0
  28. package/package.json +3 -2
  29. package/server.json +27 -2
  30. package/src/annotations.js +4 -3
  31. package/src/attribution.js +1 -1
  32. package/src/chooser.js +74 -3
  33. package/src/conformance.js +2 -0
  34. package/src/continuity-currency-statechart.js +139 -0
  35. package/src/continuity-currency.js +869 -0
  36. package/src/dispatch.js +1 -1
  37. package/src/error-codes.js +7 -0
  38. package/src/http-remote.js +27 -4
  39. package/src/index.js +1 -0
  40. package/src/pages.js +15 -0
  41. package/src/per-tag-handoff-statechart.js +264 -0
  42. package/src/per-tag-handoff.js +988 -0
  43. package/src/persons.js +16 -0
  44. package/src/session-graph.js +118 -7
  45. package/src/session.js +54 -10
  46. package/src/setup.js +22 -1
  47. package/src/startup-pages.js +13 -2
  48. package/src/subkey-lifecycle.js +105 -0
  49. package/src/subkey-session-statechart.js +253 -0
  50. package/src/subkeys.js +648 -89
  51. package/src/tools.js +157 -32
  52. package/src/version.js +1 -1
  53. package/templates/INDEX.md +1 -0
  54. package/templates/TAGHANDOFF.md +45 -0
  55. package/verification/continuity-currency/ContinuityCurrency.cfg +12 -0
  56. package/verification/continuity-currency/ContinuityCurrency.tla +239 -0
  57. package/verification/continuity-currency/tlc-output.txt +32 -0
  58. package/verification/continuity-currency/view.mjs +54 -0
  59. package/verification/per-tag-handoff/PerTagHandoff.cfg +10 -0
  60. package/verification/per-tag-handoff/PerTagHandoff.tla +191 -0
  61. package/verification/per-tag-handoff/StampCounter.cfg +10 -0
  62. package/verification/per-tag-handoff/out/report.md +6 -0
  63. package/verification/per-tag-handoff/out-counter/chart.mmd +30 -0
  64. package/verification/per-tag-handoff/out-counter/report.md +15 -0
  65. package/verification/per-tag-handoff/out-counter/tlc.out +130 -0
  66. package/verification/per-tag-handoff/split/PerTagConflict.cfg +6 -0
  67. package/verification/per-tag-handoff/split/PerTagConflict.tla +104 -0
  68. package/verification/per-tag-handoff/split/PerTagTime.cfg +8 -0
  69. package/verification/per-tag-handoff/split/PerTagTime.tla +100 -0
  70. package/verification/per-tag-handoff/split/conflict-chart.mmd +47 -0
  71. package/verification/per-tag-handoff/split/conflict-report.md +8 -0
  72. package/verification/per-tag-handoff/split/conflict-tlc.txt +19 -0
  73. package/verification/per-tag-handoff/split/conflict-view.mjs +34 -0
  74. package/verification/per-tag-handoff/split/time-chart.mmd +44 -0
  75. package/verification/per-tag-handoff/split/time-report.md +8 -0
  76. package/verification/per-tag-handoff/split/time-tlc.txt +19 -0
  77. package/verification/per-tag-handoff/split/time-view.mjs +33 -0
  78. package/verification/per-tag-handoff/tlc-output.txt +19 -0
  79. package/verification/per-tag-handoff/v1-draft/PerTagHandoff.cfg +5 -0
  80. package/verification/per-tag-handoff/v1-draft/PerTagHandoff.tla +94 -0
  81. package/verification/per-tag-handoff/v1-draft/out/chart.mmd +37 -0
  82. package/verification/per-tag-handoff/v1-draft/out/report.md +7 -0
  83. package/verification/per-tag-handoff/v1-draft/out/tlc.out +19 -0
  84. package/verification/per-tag-handoff/v1-draft/view.mjs +20 -0
  85. package/verification/per-tag-handoff/view.mjs +31 -0
  86. package/verification/subkey-session/SubkeySession.cfg +11 -0
  87. package/verification/subkey-session/SubkeySession.tla +254 -0
  88. package/verification/subkey-session/tlc-output.txt +13 -0
package/src/dispatch.js CHANGED
@@ -38,7 +38,7 @@ import { beginStagedDoc, appendStagedChunk, commitStagedDoc, abortStagedDoc } fr
38
38
  import { reserveToolNames } from './rune-registry.js';
39
39
  import { applyCheckpoint, checkpointOnError, checkpointStatus } from './checkpoint.js';
40
40
 
41
- reserveToolNames([...TOOLS.map((tool) => tool.name), 'emet_subkey_request', 'emet_subkey_claim', 'emet_subkey_revoke', 'emet_subkey_end_session']);
41
+ reserveToolNames([...TOOLS.map((tool) => tool.name), 'emet_subkey_request', 'emet_subkey_claim', 'emet_subkey_revoke', 'emet_subkey_end_session', 'emet_subkey_set_kind']);
42
42
 
43
43
  /**
44
44
  * Route one tool call. `ctx` carries what the transport owns: dbManager, logger,
@@ -93,6 +93,7 @@ export const ERROR_CODES = Object.freeze({
93
93
  'EMET-CFG-012': Object.freeze({ area: 'CFG', summary: "Backup answer must be yes or no", status: 'active', internal: false }),
94
94
  'EMET-CFG-013': Object.freeze({ area: 'CFG', summary: "Setup requires the owner", status: 'active', internal: false }),
95
95
  'EMET-CFG-014': Object.freeze({ area: 'CFG', summary: "Store is already set up", status: 'active', internal: false }),
96
+ 'EMET-CFG-015': Object.freeze({ area: 'CFG', summary: "Per-tag handoffs are on and the hub tag is unset", status: 'active', internal: false }),
96
97
  'EMET-DB-001': Object.freeze({ area: 'DB', summary: "MONGODB_URI is not set", status: 'active', internal: false }),
97
98
  'EMET-DB-002': Object.freeze({ area: 'DB', summary: "Failed to connect to MongoDB", status: 'active', internal: false }),
98
99
  'EMET-DB-003': Object.freeze({ area: 'DB', summary: "Query failed on a memory layer", status: 'active', internal: false }),
@@ -207,6 +208,11 @@ export const ERROR_CODES = Object.freeze({
207
208
  'EMET-DOC-078': Object.freeze({ area: 'DOC', summary: "Commit reason does not match the stage", status: 'active', internal: false }),
208
209
  'EMET-DOC-079': Object.freeze({ area: 'DOC', summary: "This call's source does not match the stage", status: 'active', internal: false }),
209
210
  'EMET-DOC-080': Object.freeze({ area: 'DOC', summary: "This call's session does not match the stage", status: 'active', internal: false }),
211
+ 'EMET-DOC-084': Object.freeze({ area: 'DOC', summary: "Another tag's handoff, folder, or an unregistered credential", status: 'active', internal: false }),
212
+ 'EMET-DOC-085': Object.freeze({ area: 'DOC', summary: "A credential changed a board row it did not open", status: 'active', internal: false }),
213
+ 'EMET-DOC-086': Object.freeze({ area: 'DOC', summary: "A reserved, malformed, or person-equal handoff id", status: 'active', internal: false }),
214
+ 'EMET-DOC-087': Object.freeze({ area: 'DOC', summary: "A claimed tag cannot write a handoff", status: 'active', internal: false }),
215
+ 'EMET-DOC-088': Object.freeze({ area: 'DOC', summary: "A declared session tag is not the credential", status: 'active', internal: false }),
210
216
  'EMET-GEM-001': Object.freeze({ area: 'GEM', summary: "Read-back found no document", status: 'active', internal: false }),
211
217
  'EMET-GEM-002': Object.freeze({ area: 'GEM', summary: "Read-back content digest differs", status: 'active', internal: false }),
212
218
  'EMET-GEM-003': Object.freeze({ area: 'GEM', summary: "Read-back version differs", status: 'active', internal: false }),
@@ -307,6 +313,7 @@ export const ERROR_CODES = Object.freeze({
307
313
  'EMET-SESS-005': Object.freeze({ area: 'SESS', summary: "Session graph is unavailable", status: 'active', internal: false }),
308
314
  'EMET-SESS-006': Object.freeze({ area: 'SESS', summary: "Session close was blocked", status: 'active', internal: false }),
309
315
  'EMET-SESS-007': Object.freeze({ area: 'SESS', summary: "Session close escalated", status: 'active', internal: false }),
316
+ 'EMET-SESS-014': Object.freeze({ area: 'SESS', summary: "A stranded sub-key session needs a new open", status: 'active', internal: false }),
310
317
  'EMET-TOOL-001': Object.freeze({ area: 'TOOL', summary: "A tool has no annotation entry", status: 'active', internal: true }),
311
318
  'EMET-TOOL-002': Object.freeze({ area: 'TOOL', summary: "A source tag is required", status: 'active', internal: false }),
312
319
  'EMET-TOOL-003': Object.freeze({ area: 'TOOL', summary: "A source tag is required and none are registered", status: 'active', internal: false }),
@@ -110,23 +110,45 @@ function buildServer() {
110
110
  registry: t.sourceRegistry()
111
111
  }, actor, args, name));
112
112
  } catch (e) {
113
+ const { preflightHttpCode } = await import('./subkey-lifecycle.js');
114
+ const code = preflightHttpCode(e);
115
+ if (code === 'EMET-SESS-014') {
116
+ const { ValidationError } = await import('./validation.js');
117
+ const err = new ValidationError('session_handle', e.message, { code: 'EMET-SESS-014' });
118
+ const response = await actorStore.run(actor, () => t.handleError(err, name, logger));
119
+ return attachSubkeyNotice(response, e.subkeyHold);
120
+ }
113
121
  if (e && e.attributionRefusal) {
114
122
  const { ValidationError } = await import('./validation.js');
115
- const code = e.emetCode === 'EMET-AUTH-044' ? 'EMET-AUTH-044' : 'EMET-AUTH-039';
116
- const err = new ValidationError('source', e.message, { code });
123
+ const mapped = code === 'EMET-AUTH-044' ? 'EMET-AUTH-044' : 'EMET-AUTH-039';
124
+ const err = new ValidationError('source', e.message, { code: mapped });
117
125
  if (e.chooser) err.chooser = e.chooser;
118
126
  return actorStore.run(actor, () => t.handleError(err, name, logger));
119
127
  }
120
128
  throw e;
121
129
  }
122
130
  const result = await actorStore.run(actor, () => callTool(name, args));
131
+ const noted = actor && actor.subkeyRenewal ? attachSubkeyNotice(result, actor.subkeyRenewal) : result;
123
132
  const { toolCallAuditDetails } = await import('./grants.js');
124
- logger.audit(AuditOperation.TOOL_CALL, toolCallAuditDetails(actor, { tool: name, success: result.isError !== true, durationMs: Date.now() - t0, params: paramNames }));
125
- return result;
133
+ logger.audit(AuditOperation.TOOL_CALL, toolCallAuditDetails(actor, { tool: name, success: noted.isError !== true, durationMs: Date.now() - t0, params: paramNames }));
134
+ return noted;
126
135
  });
127
136
  return server;
128
137
  }
129
138
 
139
+ /** Put a renewal or wrap-up notice on a tool result. The tool body is unchanged when it is not JSON. */
140
+ function attachSubkeyNotice(result, notice) {
141
+ if (!notice || !result || !Array.isArray(result.content) || !result.content[0] || typeof result.content[0].text !== 'string') return result;
142
+ try {
143
+ const data = JSON.parse(result.content[0].text);
144
+ if (!data || typeof data !== 'object' || Array.isArray(data)) return result;
145
+ data.session_renewal = notice;
146
+ if (notice.wrap_up_notice && !data.wrap_up_notice) data.wrap_up_notice = notice.wrap_up_notice;
147
+ result.content[0].text = JSON.stringify(data);
148
+ } catch { /* a non-JSON tool body stays as the tool wrote it */ }
149
+ return result;
150
+ }
151
+
130
152
  async function callTool(name, args) {
131
153
  // One dispatch table for both transports - src/dispatch.js (audit 2026-09-27).
132
154
  return dispatchTool(name, args, { dbManager, logger, AuditOperation });
@@ -374,5 +396,6 @@ if (process.env.EMET_HTTP_LISTEN !== '0') (async () => {
374
396
  console.error(app.locals.rotateStartupLine());
375
397
  });
376
398
  import('./subkeys.js').then((m) => m.startFlagOffSweep((msg) => console.error(`[emet] ${msg}`))).catch(() => console.error('[emet] sub-key flag-off sweep failed'));
399
+ import('./subkeys.js').then((m) => m.startStrandedSweep((msg) => console.error(`[emet] ${msg}`), dbManager)).catch(() => console.error('[emet] sub-key sweep failed'));
377
400
  import('./error-log.js').then((m) => m.startErrorLogRotation()).catch(() => {});
378
401
  })();
package/src/index.js CHANGED
@@ -278,6 +278,7 @@ async function main() {
278
278
  }
279
279
 
280
280
  import('./subkeys.js').then((m) => m.startFlagOffSweep((msg) => logger.error(msg))).catch((e) => logger.error('sub-key flag-off sweep failed', { error: e && e.message }));
281
+ import('./subkeys.js').then((m) => m.startStrandedSweep((msg) => logger.error(msg), dbManager)).catch((e) => logger.error('sub-key sweep failed', { error: e && e.message }));
281
282
  import('./error-log.js').then((m) => m.startErrorLogRotation()).catch(() => {});
282
283
 
283
284
  const startupDurationMs = Date.now() - startTime;
package/src/pages.js CHANGED
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import { connectMongo } from './mongo-connect.js';
17
+ import { tagHandoffMode, loadHandoffView } from './per-tag-handoff.js';
17
18
  import { MONGODB_URI, MONGODB_DB, COLLECTION_PREFIX, DatabaseError } from './database.js';
18
19
  import { LAYERS } from './layers.js';
19
20
  import { classifyRow } from './gaps.js';
@@ -759,6 +760,20 @@ export async function lintPages({ area = null } = {}, now = new Date()) {
759
760
  }
760
761
  }
761
762
 
763
+ if (tagHandoffMode() !== 'off') {
764
+ try {
765
+ const view = await loadHandoffView(db, { asOf: now.toISOString(), readOnly: true });
766
+ if (view.handoff_view_conflicts && view.handoff_view_conflicts.length) {
767
+ pushFinding(findings, seen, {
768
+ class: 'handoff_conflict',
769
+ ids: view.handoff_view_conflicts.map((id) => `row:${id}`),
770
+ area: area || 'board',
771
+ detail: 'Two handoffs disagree on a board row. The view does not pick a winner.'
772
+ });
773
+ }
774
+ } catch { /* a view that cannot be read does not hide the other findings */ }
775
+ }
776
+
762
777
  return { findings, areas: slugs, read_only: true };
763
778
  });
764
779
  }
@@ -0,0 +1,264 @@
1
+ /**
2
+ * EMET - Enduring Memory & Epistemic Tiers
3
+ * Copyright (c) 2026 Dreamforge Studio LLC
4
+ *
5
+ * Licensed under the MIT License - see LICENSE
6
+ *
7
+ * Per-tag handoff statechart. Served on /statechart.
8
+ * The picture is docs/per-tag-handoff-statechart.md.
9
+ * The reference model is verification/per-tag-handoff/PerTagHandoff.tla
10
+ * (958,557 states). The pictures are the split models under
11
+ * verification/per-tag-handoff/split/.
12
+ */
13
+
14
+ export const PER_TAG_HANDOFF_MERMAID = `stateDiagram-v2
15
+ state "Legend" as legend {
16
+ lg0: refused
17
+ lg1: session
18
+ lg2: rest
19
+ }
20
+ class lg0 pink
21
+ class lg1 blue
22
+ class lg2 teal
23
+ s0: No handoffs yet
24
+ s1: In session, merged view read
25
+ s2: Write refused, nothing written
26
+ s3: Handoffs at rest
27
+ s4: In session, board moved since read
28
+ s5: In session, row conflict waiting for the hub
29
+ s6: At rest, row conflict waiting for the hub
30
+ [*] --> s0
31
+ s0 --> s1: an AI starts and reads the view
32
+ s1 --> s2: an AI tries to write another AI's handoff or an AI tries to patch a row it did not open
33
+ s1 --> s3: a write AI writes its own handoff last
34
+ s1 --> s4: a write AI opens a board row
35
+ s2 --> s1: an AI starts and reads the view or a write AI opens a board row or a write AI writes its own handoff last
36
+ s2 --> s3: a write AI writes its own handoff last
37
+ s3 --> s1: an AI starts and reads the view
38
+ s2 --> s4: a write AI opens a board row or a write AI writes its own handoff last or an AI starts and reads the view
39
+ s4 --> s2: an AI tries to patch a row it did not open or an AI tries to write another AI's handoff or a write on a moved board is refused
40
+ s4 --> s1: a write AI writes its own handoff last
41
+ s4 --> s5: a write AI writes its own handoff last
42
+ s1 --> s5: a write AI writes its own handoff last
43
+ s2 --> s5: a write AI writes its own handoff last or an AI starts and reads the view
44
+ s4 --> s3: a write AI writes its own handoff last
45
+ s4 --> s6: a write AI writes its own handoff last
46
+ s1 --> s6: a write AI writes its own handoff last
47
+ s5 --> s2: an AI tries to write another AI's handoff or an AI tries to patch a row it did not open
48
+ s5 --> s6: a write AI writes its own handoff last
49
+ s2 --> s6: a write AI writes its own handoff last
50
+ s6 --> s5: an AI starts and reads the view
51
+ class s0 teal
52
+ class s1 blue
53
+ class s2 pink
54
+ class s3 teal
55
+ class s4 blue
56
+ class s5 blue
57
+ class s6 teal
58
+ `;
59
+
60
+ export const PER_TAG_TIME_MERMAID = `stateDiagram-v2
61
+ state "Legend" as legend {
62
+ lg0: session
63
+ lg1: rest
64
+ }
65
+ class lg0 blue
66
+ class lg1 teal
67
+ s0: No handoff yet
68
+ s1: In session, merged view read
69
+ s2: In session, work shown in progress
70
+ s3: Handoff at rest
71
+ s4: In session, open work marked stale
72
+ s5: Handoff at rest, line aging
73
+ s6: In session, reading an aging line
74
+ [*] --> s0
75
+ s0 --> s1: an AI starts, reads the view, and stamps it
76
+ s1 --> s2: a write AI saves work in an open session
77
+ s1 --> s3: a write AI writes its own handoff last or a read-only AI leaves, writing nothing
78
+ s1 --> s0: a read-only AI leaves, writing nothing
79
+ s1 --> s4: a write AI saves work in an open session
80
+ s2 --> s4: time passes (24 hours open, 7 days aging)
81
+ s2 --> s3: a write AI writes its own handoff last
82
+ s3 --> s1: an AI starts, reads the view, and stamps it
83
+ s3 --> s5: time passes (24 hours open, 7 days aging)
84
+ s2 --> s1: a write AI writes its own handoff last
85
+ s4 --> s3: a write AI writes its own handoff last
86
+ s5 --> s6: an AI starts, reads the view, and stamps it
87
+ s4 --> s1: a write AI writes its own handoff last
88
+ s6 --> s2: a write AI saves work in an open session
89
+ s1 --> s6: an AI starts, reads the view, and stamps it
90
+ s6 --> s5: a read-only AI leaves, writing nothing
91
+ s1 --> s5: a read-only AI leaves, writing nothing
92
+ s6 --> s4: a write AI saves work in an open session
93
+ s6 --> s1: a read-only AI leaves, writing nothing
94
+ class s0 teal
95
+ class s1 blue
96
+ class s2 blue
97
+ class s3 teal
98
+ class s4 blue
99
+ class s5 teal
100
+ class s6 blue
101
+ `;
102
+
103
+ export const PER_TAG_HANDOFF_STEPS = Object.freeze([
104
+ 'A session reads the shared handoff view. The stamp includes the time it was read, the person, each handoff version, and the board version.',
105
+ 'Rows already on the board belong to the hub tag. Another tag patching one of those rows is refused.',
106
+ 'A new row belongs to the credential that adds it. That tag can patch it. A bot tag can patch its own rows and still cannot write the hub handoff.',
107
+ 'The hub changes another tag\'s row only when the view has marked that row in conflict, and the write names the stamp, including the time it was read. With no mark the hub is refused.',
108
+ 'Each write tag writes its own handoff last. A write of another tag\'s handoff, or of the hub handoff by anyone else, is refused.',
109
+ 'A read-only tag receives the view and writes nothing.',
110
+ 'An open session with material work is an in-progress line. It is not a pointer and it is not a lag. After 24 hours the line is marked stale-open. The gate stays warn-only.',
111
+ 'A handoff line older than 7 days, by the revision\'s updated_at, is aging. The same stamp rebuilds that class because it carries the time it was read. A stamp of versions alone does not.'
112
+ ]);
113
+
114
+ const PLACES = new Set([
115
+ 'reading', 'opened', 'ownRow', 'foreignRefused', 'conflict', 'resolved',
116
+ 'hubRefused', 'ownHandoff', 'foreignHandoff', 'readOnly',
117
+ 'inProgress', 'staleOpen', 'agingLine', 'done'
118
+ ]);
119
+
120
+ export function perTagInitial() {
121
+ return {
122
+ place: 'reading',
123
+ conflict: false,
124
+ stale: false,
125
+ aging: false,
126
+ stampAsOf: true,
127
+ handoffBy: 'none',
128
+ rowOwner: 'hub',
129
+ refused: false,
130
+ blocked: false,
131
+ person: 'owner'
132
+ };
133
+ }
134
+
135
+ function same(state, extra) {
136
+ return { ...state, ...extra, person: 'owner', blocked: false };
137
+ }
138
+
139
+ /**
140
+ * One step of the chart. An event that cannot happen returns null.
141
+ * blocked stays false. The person stays the owner.
142
+ */
143
+ export function perTagHandoffStep(state, event) {
144
+ if (!state || !PLACES.has(state.place)) return null;
145
+ if (!event || typeof event.type !== 'string') return null;
146
+ const type = event.type;
147
+ if (type === 'start') {
148
+ if (state.place !== 'reading') return null;
149
+ return same(state, { stampAsOf: true });
150
+ }
151
+ if (type === 'open_row') {
152
+ if (state.place !== 'reading' || state.rowOwner !== 'hub') return null;
153
+ return same(state, { place: 'opened', rowOwner: 'writer', refused: false });
154
+ }
155
+ if (type === 'patch_own') {
156
+ if (state.place !== 'opened' || state.rowOwner !== 'writer') return null;
157
+ return same(state, { place: 'ownRow', refused: false });
158
+ }
159
+ if (type === 'foreign_row') {
160
+ if (state.place !== 'reading' || state.rowOwner !== 'hub') return null;
161
+ return same(state, { place: 'foreignRefused', refused: true });
162
+ }
163
+ if (type === 'mark_conflict') {
164
+ if (state.place !== 'opened') return null;
165
+ return same(state, { place: 'conflict', conflict: true });
166
+ }
167
+ if (type === 'resolve') {
168
+ if (state.place !== 'conflict' || state.conflict !== true || state.stampAsOf !== true) return null;
169
+ return same(state, { place: 'resolved', refused: false });
170
+ }
171
+ if (type === 'resolve_unmarked') {
172
+ if (state.place !== 'opened' || state.conflict !== false || state.rowOwner !== 'writer') return null;
173
+ return same(state, { place: 'hubRefused', refused: true });
174
+ }
175
+ if (type === 'wrap_own') {
176
+ if (!['reading', 'ownRow', 'resolved', 'inProgress'].includes(state.place)) return null;
177
+ return same(state, { place: 'ownHandoff', handoffBy: 'writer', refused: false });
178
+ }
179
+ if (type === 'foreign_handoff') {
180
+ if (state.place !== 'reading') return null;
181
+ return same(state, { place: 'foreignHandoff', refused: true, handoffBy: 'none' });
182
+ }
183
+ if (type === 'leave_readonly') {
184
+ if (state.place !== 'reading') return null;
185
+ return same(state, { place: 'readOnly', refused: false });
186
+ }
187
+ if (type === 'show_progress') {
188
+ if (state.place !== 'reading') return null;
189
+ return same(state, { place: 'inProgress', stale: false });
190
+ }
191
+ if (type === 'tick_open') {
192
+ if (state.place !== 'inProgress') return null;
193
+ return same(state, { place: 'staleOpen', stale: true });
194
+ }
195
+ if (type === 'tick_age') {
196
+ if (!['reading', 'ownHandoff'].includes(state.place) || state.stampAsOf !== true) return null;
197
+ return same(state, { place: 'agingLine', aging: true });
198
+ }
199
+ if (type === 'done') {
200
+ if (!['ownRow', 'foreignRefused', 'resolved', 'hubRefused', 'ownHandoff', 'foreignHandoff', 'readOnly', 'staleOpen', 'agingLine', 'done'].includes(state.place)) return null;
201
+ return same(state, { place: 'done' });
202
+ }
203
+ return null;
204
+ }
205
+
206
+ /** The chart rules. A block, a lost opener, or a stamp with no as_of breaks one. */
207
+ export function perTagInvariant(state) {
208
+ if (!state) return false;
209
+ if (state.blocked !== false) return false;
210
+ if (state.person !== 'owner') return false;
211
+ if (state.handoffBy !== 'none' && state.handoffBy !== 'writer') return false;
212
+ if (state.place === 'resolved' && state.conflict !== true) return false;
213
+ if (state.place === 'hubRefused' && (state.conflict !== false || state.rowOwner !== 'writer')) return false;
214
+ if (state.place === 'foreignRefused' && state.rowOwner !== 'hub') return false;
215
+ if (state.place === 'readOnly' && (state.handoffBy !== 'none' || state.rowOwner !== 'hub')) return false;
216
+ if ((state.place === 'inProgress' || state.place === 'staleOpen') && state.handoffBy !== 'none') return false;
217
+ if (state.stale === true && state.place !== 'staleOpen' && state.place !== 'done') return false;
218
+ if (state.stampAsOf !== true) return false;
219
+ return true;
220
+ }
221
+
222
+ /**
223
+ * The four-step counter-check. Versions without as_of do not rebuild the view
224
+ * once the line has aged. The real stamp carries as_of, so the same inputs rebuild.
225
+ */
226
+ export function stampCounterSteps(build) {
227
+ const asOf = '2026-11-03T00:00:00.000Z';
228
+ const later = '2026-11-11T00:00:00.000Z';
229
+ const board = { doc_id: 'STATE.md', version: 1, content: boardText() };
230
+ const input = {
231
+ doc_id: 'HANDOFF/writer.md',
232
+ tag: 'writer',
233
+ version: 1,
234
+ updated_at: '2026-11-03T00:00:00.000Z',
235
+ content: handoffText('B-001', 'open', 'wait')
236
+ };
237
+ const first = build({ inputs: [input], board, as_of: asOf, person: 'owner' });
238
+ const again = build({ inputs: [input], board, as_of: asOf, person: 'owner' });
239
+ const aged = build({ inputs: [input], board, as_of: later, person: 'owner' });
240
+ const versionsOnly = { inputs: ['HANDOFF/writer.md@v1'], board: 'STATE.md@v1' };
241
+ return { first, again, aged, versionsOnly };
242
+ }
243
+
244
+ export function boardText() {
245
+ return [
246
+ '## §1 HALF-STATE',
247
+ '| Id | State | Next action |',
248
+ '| --- | --- | --- |',
249
+ '| B-001 | open | wait |',
250
+ '## §3 OPEN BOARD',
251
+ '| Id | Status | Next action |',
252
+ '| --- | --- | --- |'
253
+ ].join('\n');
254
+ }
255
+
256
+ export function handoffText(row, state, next) {
257
+ return [
258
+ '## §1 OVERALL PICTURE',
259
+ '| Row | State | Next step |',
260
+ '| --- | --- | --- |',
261
+ `| ${row} | ${state} | ${next} |`,
262
+ 'Close verification: episodic 1'
263
+ ].join('\n');
264
+ }