@dreamforgestudiollc/emet 0.3.5 → 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.
- package/.env.example +29 -0
- package/CHANGELOG.md +49 -11
- package/CHARTER.md +1 -1
- package/CONTRIBUTING.md +21 -0
- package/README.md +25 -10
- package/RELEASE_NOTES-0.2.6.md +43 -0
- package/RELEASE_NOTES-0.3.6.md +29 -0
- package/RELEASE_NOTES-0.3.7.md +19 -0
- package/SECURITY.md +13 -0
- package/docs/BOTS.md +4 -4
- package/docs/DEPLOY.md +23 -4
- package/docs/ERROR-CODES-SPEC.md +4 -0
- package/docs/ERROR-CODES.md +7 -0
- package/docs/GUIDED-SETUP.md +1 -1
- package/docs/ROADMAP.md +62 -49
- package/docs/SETUP.md +11 -1
- package/docs/SUBKEYS.md +3 -1
- package/docs/continuity-currency-statechart.md +34 -0
- package/docs/features/README.md +21 -0
- package/docs/features/access.md +28 -0
- package/docs/features/documents.md +35 -0
- package/docs/features/errors.md +32 -0
- package/docs/features/gems.md +31 -0
- package/docs/features/memory.md +29 -0
- package/docs/features/pages.md +28 -0
- package/docs/features/record.md +27 -0
- package/docs/features/search.md +27 -0
- package/docs/features/startup.md +29 -0
- package/docs/features/subkeys.md +30 -0
- package/docs/features/transcripts.md +33 -0
- package/docs/per-tag-handoff-statechart.md +147 -0
- package/docs/subkey-session-statechart.md +57 -0
- package/package.json +6 -2
- package/server.json +27 -2
- package/src/annotations.js +5 -3
- package/src/attribution.js +2 -2
- package/src/carry-forward-close.js +1 -1
- package/src/chooser.js +74 -3
- package/src/conformance.js +2 -0
- package/src/continuity-currency-statechart.js +139 -0
- package/src/continuity-currency.js +869 -0
- package/src/database.js +1 -1
- package/src/dispatch.js +1 -1
- package/src/error-codes.js +7 -0
- package/src/gem-check.js +4 -1
- package/src/grants.js +28 -5
- package/src/host-reach.js +1 -1
- package/src/http-remote.js +29 -5
- package/src/index.js +3 -2
- package/src/invites.js +2 -2
- package/src/owl.js +12 -11
- package/src/pages.js +15 -0
- package/src/per-tag-handoff-statechart.js +264 -0
- package/src/per-tag-handoff.js +988 -0
- package/src/persons.js +16 -0
- package/src/session-graph.js +123 -12
- package/src/session.js +56 -12
- package/src/setup.js +32 -11
- package/src/startup-pages.js +13 -2
- package/src/subkey-lifecycle.js +105 -0
- package/src/subkey-session-statechart.js +253 -0
- package/src/subkeys.js +648 -89
- package/src/tools.js +171 -51
- package/src/transcript-session.js +2 -2
- package/src/version.js +1 -1
- package/templates/INDEX.md +1 -0
- package/templates/SESSIONDISPOSITION.md +2 -2
- package/templates/TAGHANDOFF.md +45 -0
- package/verification/continuity-currency/ContinuityCurrency.cfg +12 -0
- package/verification/continuity-currency/ContinuityCurrency.tla +239 -0
- package/verification/continuity-currency/tlc-output.txt +32 -0
- package/verification/continuity-currency/view.mjs +54 -0
- package/verification/load-gate/load-gate.mjs +1 -1
- package/verification/per-tag-handoff/PerTagHandoff.cfg +10 -0
- package/verification/per-tag-handoff/PerTagHandoff.tla +191 -0
- package/verification/per-tag-handoff/StampCounter.cfg +10 -0
- package/verification/per-tag-handoff/out/report.md +6 -0
- package/verification/per-tag-handoff/out-counter/chart.mmd +30 -0
- package/verification/per-tag-handoff/out-counter/report.md +15 -0
- package/verification/per-tag-handoff/out-counter/tlc.out +130 -0
- package/verification/per-tag-handoff/split/PerTagConflict.cfg +6 -0
- package/verification/per-tag-handoff/split/PerTagConflict.tla +104 -0
- package/verification/per-tag-handoff/split/PerTagTime.cfg +8 -0
- package/verification/per-tag-handoff/split/PerTagTime.tla +100 -0
- package/verification/per-tag-handoff/split/conflict-chart.mmd +47 -0
- package/verification/per-tag-handoff/split/conflict-report.md +8 -0
- package/verification/per-tag-handoff/split/conflict-tlc.txt +19 -0
- package/verification/per-tag-handoff/split/conflict-view.mjs +34 -0
- package/verification/per-tag-handoff/split/time-chart.mmd +44 -0
- package/verification/per-tag-handoff/split/time-report.md +8 -0
- package/verification/per-tag-handoff/split/time-tlc.txt +19 -0
- package/verification/per-tag-handoff/split/time-view.mjs +33 -0
- package/verification/per-tag-handoff/tlc-output.txt +19 -0
- package/verification/per-tag-handoff/v1-draft/PerTagHandoff.cfg +5 -0
- package/verification/per-tag-handoff/v1-draft/PerTagHandoff.tla +94 -0
- package/verification/per-tag-handoff/v1-draft/out/chart.mmd +37 -0
- package/verification/per-tag-handoff/v1-draft/out/report.md +7 -0
- package/verification/per-tag-handoff/v1-draft/out/tlc.out +19 -0
- package/verification/per-tag-handoff/v1-draft/view.mjs +20 -0
- package/verification/per-tag-handoff/view.mjs +31 -0
- package/verification/subkey-session/SubkeySession.cfg +11 -0
- package/verification/subkey-session/SubkeySession.tla +254 -0
- package/verification/subkey-session/tlc-output.txt +13 -0
|
@@ -0,0 +1,988 @@
|
|
|
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 handoffs. One server, one store. The flag is off unless the
|
|
8
|
+
* value is warn or enforce. Off leaves every existing door as it is.
|
|
9
|
+
* Warn refuses the new HANDOFF/ prefix at once and logs the board-row
|
|
10
|
+
* rule and the gap on the existing records. Enforce refuses those too.
|
|
11
|
+
* The merged view is computed on read and is not a record.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import crypto from 'node:crypto';
|
|
15
|
+
import { setting } from './env.js';
|
|
16
|
+
import { ValidationError } from './validation.js';
|
|
17
|
+
import { currentActor, declaredAttribution } from './persons.js';
|
|
18
|
+
import { isBotTagLocal, approvedTags } from './attribution.js';
|
|
19
|
+
import { COLLECTION_PREFIX } from './database.js';
|
|
20
|
+
|
|
21
|
+
export const TAG_HANDOFF_FLAG = 'EMET_TAG_HANDOFFS';
|
|
22
|
+
export const HUB_TAG_FLAG = 'EMET_HUB_TAG';
|
|
23
|
+
export const AGING_DAYS_FLAG = 'EMET_HANDOFF_AGING_DAYS';
|
|
24
|
+
export const STALE_OPEN_HOURS_FLAG = 'EMET_STALE_OPEN_HOURS';
|
|
25
|
+
|
|
26
|
+
const TAG_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
27
|
+
const ROW_RE = /\bB-\d{3,}\b/;
|
|
28
|
+
const STAMP_SHA = /^[a-f0-9]{64}$/;
|
|
29
|
+
|
|
30
|
+
export function tagHandoffMode(raw = setting('TAG_HANDOFFS', 'off')) {
|
|
31
|
+
const value = String(raw ?? 'off').trim().toLowerCase();
|
|
32
|
+
if (value === 'warn' || value === 'enforce') return value;
|
|
33
|
+
return 'off';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function hubTag() {
|
|
37
|
+
const value = String(setting('HUB_TAG', '') ?? '').trim();
|
|
38
|
+
return value || null;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The flag on with no hub tag is a configuration refusal. Reads stay available. */
|
|
42
|
+
export function requireHubTag() {
|
|
43
|
+
const mode = tagHandoffMode();
|
|
44
|
+
if (mode === 'off') return hubTag();
|
|
45
|
+
const hub = hubTag();
|
|
46
|
+
if (!hub) {
|
|
47
|
+
throw new ValidationError(
|
|
48
|
+
'EMET_TAG_HANDOFFS is on and EMET_HUB_TAG is not set. Nothing was written.',
|
|
49
|
+
{ code: 'EMET-CFG-015' }
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
return hub;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Handoff ids a close may name for this tag. Null while the flag is off. The hub's only id is HANDOFF.md. */
|
|
56
|
+
export function handoffIdsFor(tag) {
|
|
57
|
+
if (!tag || tagHandoffMode() === 'off') return null;
|
|
58
|
+
if (hubTag() && tag === hubTag()) return [setting('HANDOFF_DOC', 'HANDOFF.md')];
|
|
59
|
+
const ids = [`HANDOFF/${tag}.md`];
|
|
60
|
+
if (isBotTagLocal(tag)) ids.push(`bots/${tag}/HANDOFF.md`);
|
|
61
|
+
return ids;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const OPEN_SESSION_LOOKBACK_MS = 30 * 86400000;
|
|
65
|
+
|
|
66
|
+
export function handoffAgingDays() {
|
|
67
|
+
const n = Number(setting('HANDOFF_AGING_DAYS', '7'));
|
|
68
|
+
return Number.isFinite(n) && n > 0 ? n : 7;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function staleOpenHours() {
|
|
72
|
+
const n = Number(setting('STALE_OPEN_HOURS', '24'));
|
|
73
|
+
return Number.isFinite(n) && n > 0 ? n : 24;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function writeTagRegistry() {
|
|
77
|
+
const env = String(setting('SOURCE_TAGS') ?? '').split(',').map((s) => s.trim()).filter(Boolean);
|
|
78
|
+
return [...new Set([...env, ...approvedTags()])];
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The credential is the sub-key stamp, the bound login, or the owner door
|
|
83
|
+
* writing its own tag. A declared tag is not the credential.
|
|
84
|
+
*/
|
|
85
|
+
export function credentialForWrite(updatedBy) {
|
|
86
|
+
const actor = currentActor();
|
|
87
|
+
const attr = declaredAttribution();
|
|
88
|
+
const http = actor && actor.transport === 'http';
|
|
89
|
+
const basis = attr && attr.basis;
|
|
90
|
+
if (http && basis === 'subkey' && attr.effective) {
|
|
91
|
+
return { tag: attr.effective, claimedOnly: false, kind: 'subkey' };
|
|
92
|
+
}
|
|
93
|
+
if (http && (basis === 'declared' || basis === 'auto' || basis === 'legacy')) {
|
|
94
|
+
return { tag: null, claimedOnly: true, kind: basis };
|
|
95
|
+
}
|
|
96
|
+
if (http && attr && attr.login) {
|
|
97
|
+
return { tag: attr.login, claimedOnly: false, kind: 'bound' };
|
|
98
|
+
}
|
|
99
|
+
if (http && actor.sourceTag) {
|
|
100
|
+
return { tag: actor.sourceTag, claimedOnly: false, kind: 'bound' };
|
|
101
|
+
}
|
|
102
|
+
const tag = (typeof updatedBy === 'string' && updatedBy.trim()) || setting('SOURCE_TAG') || null;
|
|
103
|
+
return { tag: tag || null, claimedOnly: false, kind: 'owner-door' };
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function parseHandoffId(docId, ownerPerson = 'owner') {
|
|
107
|
+
if (typeof docId !== 'string' || !docId) return { kind: 'other' };
|
|
108
|
+
if (docId === 'HANDOFF.md' || docId === setting('HANDOFF_DOC', 'HANDOFF.md')) return { kind: 'hub' };
|
|
109
|
+
if (docId.startsWith('handoffs/')) return { kind: 'draft-name' };
|
|
110
|
+
const short = /^HANDOFF\/([^/]+)\.md$/.exec(docId);
|
|
111
|
+
if (short) {
|
|
112
|
+
return { kind: 'short', tag: short[1], person: ownerPerson, storedId: docId };
|
|
113
|
+
}
|
|
114
|
+
const long = /^HANDOFF\/([^/]+)\/([^/]+)\.md$/.exec(docId);
|
|
115
|
+
if (long) return { kind: 'long', person: long[1], tag: long[2] };
|
|
116
|
+
if (docId.startsWith('HANDOFF/')) return { kind: 'malformed' };
|
|
117
|
+
const alias = /^bots\/([^/]+)\/HANDOFF\.md$/.exec(docId);
|
|
118
|
+
if (alias) return { kind: 'alias', tag: alias[1], person: ownerPerson, storedId: `HANDOFF/${alias[1]}.md` };
|
|
119
|
+
return { kind: 'other' };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function isTagHandoffDoc(docId) {
|
|
123
|
+
return parseHandoffId(docId).kind === 'short';
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function personSet(personIds, ownerPerson) {
|
|
127
|
+
const ids = new Set();
|
|
128
|
+
if (ownerPerson) ids.add(String(ownerPerson));
|
|
129
|
+
for (const id of personIds || []) if (id) ids.add(String(id));
|
|
130
|
+
return ids;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function refuse(message, code) {
|
|
134
|
+
const text = `${message} Nothing was written.`;
|
|
135
|
+
if (code === 'EMET-DOC-084') throw new ValidationError(text, { code: 'EMET-DOC-084' });
|
|
136
|
+
if (code === 'EMET-DOC-085') throw new ValidationError(text, { code: 'EMET-DOC-085' });
|
|
137
|
+
if (code === 'EMET-DOC-086') throw new ValidationError(text, { code: 'EMET-DOC-086' });
|
|
138
|
+
throw new ValidationError(text, { code: 'EMET-DOC-087' });
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Write check for a handoff id. `mode` off returns immediately.
|
|
143
|
+
* The new prefix is refused in warn and in enforce. The gap on HANDOFF.md
|
|
144
|
+
* and on another tag's bot folder warns in warn and refuses in enforce.
|
|
145
|
+
*/
|
|
146
|
+
export function authorizeHandoffWrite({
|
|
147
|
+
docId,
|
|
148
|
+
tool = 'write_doc',
|
|
149
|
+
mode = tagHandoffMode(),
|
|
150
|
+
credentialTag = null,
|
|
151
|
+
claimedOnly = false,
|
|
152
|
+
isBot = false,
|
|
153
|
+
isHub = false,
|
|
154
|
+
registered = true,
|
|
155
|
+
ownerPerson = 'owner',
|
|
156
|
+
personIds = []
|
|
157
|
+
} = {}) {
|
|
158
|
+
if (mode === 'off') return { ok: true };
|
|
159
|
+
const parsed = parseHandoffId(docId, ownerPerson);
|
|
160
|
+
const people = personSet(personIds, ownerPerson);
|
|
161
|
+
const where = `${tool}: ${docId}`;
|
|
162
|
+
|
|
163
|
+
if (parsed.kind === 'draft-name') {
|
|
164
|
+
refuse(`${where} is not a handoff id. A write tag's handoff is HANDOFF/<tag>.md.`, 'EMET-DOC-084');
|
|
165
|
+
}
|
|
166
|
+
if (parsed.kind === 'malformed') {
|
|
167
|
+
refuse(`${where} is not HANDOFF/<tag>.md.`, 'EMET-DOC-086');
|
|
168
|
+
}
|
|
169
|
+
if (parsed.kind === 'long') {
|
|
170
|
+
refuse(`${where} uses the reserved person segment. Phase 1 stores HANDOFF/<tag>.md, which resolves to the owner person. A two-segment id is refused.`, 'EMET-DOC-086');
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const onNewPrefix = parsed.kind === 'short';
|
|
174
|
+
if (onNewPrefix && claimedOnly) {
|
|
175
|
+
refuse(`${where} is a handoff and this write is a claimed tag, not a credential. A claimed tag cannot own a handoff.`, 'EMET-DOC-087');
|
|
176
|
+
}
|
|
177
|
+
if (onNewPrefix && people.has(parsed.tag)) {
|
|
178
|
+
refuse(`${where} uses a tag equal to a person id. A tag is not a person.`, 'EMET-DOC-086');
|
|
179
|
+
}
|
|
180
|
+
if (onNewPrefix && !TAG_RE.test(parsed.tag)) {
|
|
181
|
+
refuse(`${where} is not a tag handoff id.`, 'EMET-DOC-086');
|
|
182
|
+
}
|
|
183
|
+
if (onNewPrefix && isHub && parsed.tag === credentialTag) {
|
|
184
|
+
if (tool === 'retire_doc') return { ok: true, tag: parsed.tag, cleanup: true };
|
|
185
|
+
refuse(`${where} is the hub tag. The hub handoff is HANDOFF.md.`, 'EMET-DOC-084');
|
|
186
|
+
}
|
|
187
|
+
if (onNewPrefix) {
|
|
188
|
+
if (!credentialTag || parsed.tag !== credentialTag) {
|
|
189
|
+
refuse(`${where} belongs to ${parsed.tag}. This credential is ${credentialTag || 'missing'} and cannot write another tag's handoff.`, 'EMET-DOC-084');
|
|
190
|
+
}
|
|
191
|
+
if (!registered) {
|
|
192
|
+
refuse(`${where} needs a registered credential.`, 'EMET-DOC-084');
|
|
193
|
+
}
|
|
194
|
+
return { ok: true, tag: parsed.tag, person: ownerPerson, storedId: parsed.storedId };
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
if (parsed.kind === 'alias' && parsed.tag !== credentialTag) {
|
|
198
|
+
const message = `${where} is ${parsed.tag}'s handoff. This credential is ${credentialTag || 'missing'}.`;
|
|
199
|
+
if (mode === 'warn' && !isHub) return { ok: true, warning: `${message} Warn only: the write is kept. Enforce refuses it.` };
|
|
200
|
+
refuse(message, 'EMET-DOC-084');
|
|
201
|
+
}
|
|
202
|
+
if (parsed.kind === 'alias' && people.has(parsed.tag)) {
|
|
203
|
+
refuse(`${where} uses a tag equal to a person id. A tag is not a person.`, 'EMET-DOC-086');
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (parsed.kind === 'hub' && !isHub) {
|
|
207
|
+
const message = `${where} is the hub handoff. Only the hub tag writes it.`;
|
|
208
|
+
if (isBot) return { ok: true };
|
|
209
|
+
if (mode === 'warn') return { ok: true, warning: `${message} Warn only: the write is kept. Enforce refuses it.` };
|
|
210
|
+
refuse(message, 'EMET-DOC-084');
|
|
211
|
+
}
|
|
212
|
+
const nested = /^bots\/([^/]+)\/(.+)$/.exec(String(docId || ''));
|
|
213
|
+
if (nested && nested[1] !== credentialTag && nested[2] !== 'HANDOFF.md') {
|
|
214
|
+
const message = `${where} is in ${nested[1]}'s folder. This credential is ${credentialTag || 'missing'}.`;
|
|
215
|
+
if (mode === 'warn') return { ok: true, warning: `${message} Warn only: the write is kept. Enforce refuses it.` };
|
|
216
|
+
refuse(message, 'EMET-DOC-084');
|
|
217
|
+
}
|
|
218
|
+
return { ok: true };
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
export function guardTagHandoff(docId, updatedBy, tool) {
|
|
222
|
+
const mode = tagHandoffMode();
|
|
223
|
+
if (mode === 'off') return { ok: true };
|
|
224
|
+
requireHubTag();
|
|
225
|
+
const credential = credentialForWrite(updatedBy);
|
|
226
|
+
const tag = credential.tag;
|
|
227
|
+
const registry = writeTagRegistry();
|
|
228
|
+
const hub = hubTag();
|
|
229
|
+
const actor = currentActor();
|
|
230
|
+
return authorizeHandoffWrite({
|
|
231
|
+
docId,
|
|
232
|
+
tool,
|
|
233
|
+
mode,
|
|
234
|
+
credentialTag: tag,
|
|
235
|
+
claimedOnly: credential.claimedOnly,
|
|
236
|
+
isBot: !!(tag && isBotTagLocal(tag)),
|
|
237
|
+
isHub: !!(hub && tag === hub),
|
|
238
|
+
registered: registry.length === 0 || (!!tag && registry.includes(tag)),
|
|
239
|
+
ownerPerson: (actor && actor.personId) || 'owner',
|
|
240
|
+
personIds: []
|
|
241
|
+
});
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function sectionBodies(text) {
|
|
245
|
+
const sections = new Map();
|
|
246
|
+
let key = null;
|
|
247
|
+
const buf = [];
|
|
248
|
+
const flush = () => {
|
|
249
|
+
if (key) sections.set(key, buf.join('\n'));
|
|
250
|
+
buf.length = 0;
|
|
251
|
+
};
|
|
252
|
+
for (const line of String(text || '').split(/\r?\n/)) {
|
|
253
|
+
const match = line.match(/^##\s+§(\d+)\b/);
|
|
254
|
+
if (match) { flush(); key = match[1]; }
|
|
255
|
+
else if (key) buf.push(line);
|
|
256
|
+
}
|
|
257
|
+
flush();
|
|
258
|
+
return sections;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
function tableRows(body) {
|
|
262
|
+
const lines = String(body || '').split(/\r?\n/);
|
|
263
|
+
const start = lines.findIndex((line) => line.trim().startsWith('|'));
|
|
264
|
+
if (start < 0) return [];
|
|
265
|
+
const raw = [];
|
|
266
|
+
for (let i = start; i < lines.length; i++) {
|
|
267
|
+
if (!lines[i].trim().startsWith('|')) break;
|
|
268
|
+
raw.push(lines[i]);
|
|
269
|
+
}
|
|
270
|
+
if (raw.length < 2) return [];
|
|
271
|
+
const header = raw[0].trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell) => cell.trim().toLowerCase());
|
|
272
|
+
const idAt = header.findIndex((cell) => cell === 'id' || cell === 'row');
|
|
273
|
+
const rows = [];
|
|
274
|
+
for (const line of raw.slice(1)) {
|
|
275
|
+
const cells = line.trim().replace(/^\|/, '').replace(/\|$/, '').split('|').map((cell) => cell.trim());
|
|
276
|
+
if (cells.every((cell) => /^:?-{3,}:?$/.test(cell))) continue;
|
|
277
|
+
const idCell = (idAt >= 0 ? cells[idAt] : cells[0]) || '';
|
|
278
|
+
const id = (idCell.match(ROW_RE) || [])[0] || null;
|
|
279
|
+
if (!id) continue;
|
|
280
|
+
const stateAt = header.findIndex((cell) => cell === 'state' || cell.startsWith('state'));
|
|
281
|
+
const nextAt = header.findIndex((cell) => cell.startsWith('next'));
|
|
282
|
+
const statusAt = header.findIndex((cell) => cell === 'status' || cell.startsWith('status'));
|
|
283
|
+
rows.push({
|
|
284
|
+
id,
|
|
285
|
+
line: line.trim(),
|
|
286
|
+
state: stateAt >= 0 ? (cells[stateAt] || '') : (statusAt >= 0 ? (cells[statusAt] || '') : ''),
|
|
287
|
+
next: nextAt >= 0 ? (cells[nextAt] || '') : ''
|
|
288
|
+
});
|
|
289
|
+
}
|
|
290
|
+
return rows;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export function boardRows(content, sections = ['1', '2', '3', '4']) {
|
|
294
|
+
const bodies = sectionBodies(content);
|
|
295
|
+
const out = [];
|
|
296
|
+
const seen = new Set();
|
|
297
|
+
for (const num of sections) {
|
|
298
|
+
for (const row of tableRows(bodies.get(num))) {
|
|
299
|
+
if (seen.has(row.id)) continue;
|
|
300
|
+
seen.add(row.id);
|
|
301
|
+
out.push({ ...row, section: num });
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return out;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export function closedRowIds(content) {
|
|
308
|
+
const closed = new Set();
|
|
309
|
+
for (const row of boardRows(content, ['3'])) {
|
|
310
|
+
if (/^closed\b/i.test(row.state)) closed.add(row.id);
|
|
311
|
+
}
|
|
312
|
+
for (const row of boardRows(content, ['4'])) closed.add(row.id);
|
|
313
|
+
return closed;
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export function changedRowIds(previous, next) {
|
|
317
|
+
const before = new Map(boardRows(previous).map((row) => [row.id, row.line]));
|
|
318
|
+
const after = new Map(boardRows(next).map((row) => [row.id, row.line]));
|
|
319
|
+
const changed = [];
|
|
320
|
+
for (const [id, line] of before) {
|
|
321
|
+
if (!after.has(id) || after.get(id) !== line) changed.push(id);
|
|
322
|
+
}
|
|
323
|
+
for (const id of after.keys()) {
|
|
324
|
+
if (!before.has(id)) changed.push(id);
|
|
325
|
+
}
|
|
326
|
+
return changed;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/**
|
|
330
|
+
* Rows already on the board when the map is first stored belong to the hub.
|
|
331
|
+
* A row id that appears for the first time belongs to the credential that added it.
|
|
332
|
+
*/
|
|
333
|
+
export function seedOpeners(previousContent, stored, hub, at, version) {
|
|
334
|
+
const map = stored && typeof stored === 'object' ? { ...stored } : {};
|
|
335
|
+
const when = at || new Date(0).toISOString();
|
|
336
|
+
for (const row of boardRows(previousContent)) {
|
|
337
|
+
if (!map[row.id]) {
|
|
338
|
+
map[row.id] = { opener_tag: hub, opened_at: when, opened_in_version: version || 0, seeded: true };
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
return map;
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
export function applyOpeners(map, nextContent, writer, at, version) {
|
|
345
|
+
const out = { ...map };
|
|
346
|
+
const when = at || new Date(0).toISOString();
|
|
347
|
+
for (const row of boardRows(nextContent)) {
|
|
348
|
+
if (!out[row.id]) {
|
|
349
|
+
out[row.id] = { opener_tag: writer, opened_at: when, opened_in_version: version };
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
return out;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function stampHasAsOf(stamp) {
|
|
356
|
+
return !!(stamp && typeof stamp === 'object' && typeof stamp.as_of === 'string' && stamp.as_of.trim());
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* A tag patches a row it opened. The hub patches a foreign row only when
|
|
361
|
+
* that row is marked in conflict and the write names the stamp it resolved.
|
|
362
|
+
*/
|
|
363
|
+
export function decideRowWrite({
|
|
364
|
+
mode = tagHandoffMode(),
|
|
365
|
+
writer = null,
|
|
366
|
+
hub = null,
|
|
367
|
+
openers = {},
|
|
368
|
+
changed = [],
|
|
369
|
+
conflicts = [],
|
|
370
|
+
resolve = null,
|
|
371
|
+
currentStamp = null
|
|
372
|
+
} = {}) {
|
|
373
|
+
if (mode === 'off') return { ok: true, warnings: [], resolved: [] };
|
|
374
|
+
const conflictSet = new Set(conflicts || []);
|
|
375
|
+
const warnings = [];
|
|
376
|
+
const resolved = [];
|
|
377
|
+
const named = resolve && resolve.row_id;
|
|
378
|
+
for (const id of changed) {
|
|
379
|
+
const opener = openers && openers[id];
|
|
380
|
+
const openerTag = opener && opener.opener_tag;
|
|
381
|
+
if (!openerTag || openerTag === writer) continue;
|
|
382
|
+
const marked = conflictSet.has(id);
|
|
383
|
+
const hubResolving = writer && hub && writer === hub && marked && named === id;
|
|
384
|
+
if (hubResolving) {
|
|
385
|
+
if (!stampHasAsOf(resolve.handoff_view)) {
|
|
386
|
+
refuse(`The conflict on ${id} was named without as_of. Re-read the handoff view.`, 'EMET-DOC-085');
|
|
387
|
+
}
|
|
388
|
+
if (currentStamp && resolve.handoff_view.view_sha256 !== currentStamp.view_sha256) {
|
|
389
|
+
refuse(`The conflict on ${id} was named against a stamp that is not the view in force. Re-read the handoff view.`, 'EMET-DOC-085');
|
|
390
|
+
}
|
|
391
|
+
resolved.push(id);
|
|
392
|
+
continue;
|
|
393
|
+
}
|
|
394
|
+
const message = `${id} was opened by ${openerTag}. ${writer || 'This credential'} patches only a row it opened.`;
|
|
395
|
+
if (mode === 'warn') {
|
|
396
|
+
warnings.push(`${message} Warn only: the write is kept. Enforce refuses it.`);
|
|
397
|
+
continue;
|
|
398
|
+
}
|
|
399
|
+
refuse(message, 'EMET-DOC-085');
|
|
400
|
+
}
|
|
401
|
+
return { ok: true, warnings, resolved };
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
function dayOf(value) {
|
|
405
|
+
const ms = value instanceof Date ? value.getTime() : Date.parse(value);
|
|
406
|
+
if (!Number.isFinite(ms)) return null;
|
|
407
|
+
return new Date(ms).toISOString().slice(0, 10);
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function msOf(value) {
|
|
411
|
+
if (value instanceof Date) return value.getTime();
|
|
412
|
+
const ms = Date.parse(value);
|
|
413
|
+
return Number.isFinite(ms) ? ms : null;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function pictureLines(content) {
|
|
417
|
+
const body = sectionBodies(content).get('1') || '';
|
|
418
|
+
const table = tableRows(body);
|
|
419
|
+
if (table.length) {
|
|
420
|
+
return table.slice(0, 10).map((row) => ({
|
|
421
|
+
row_id: row.id,
|
|
422
|
+
state: row.state,
|
|
423
|
+
next: row.next,
|
|
424
|
+
text: row.line
|
|
425
|
+
}));
|
|
426
|
+
}
|
|
427
|
+
const lines = [];
|
|
428
|
+
for (const line of body.split(/\r?\n/)) {
|
|
429
|
+
const match = line.match(/^\s*[-*]\s+(B-\d{3,})\s*\|\s*([^|]+?)\s*\|\s*(.+?)\s*$/);
|
|
430
|
+
if (!match) continue;
|
|
431
|
+
lines.push({ row_id: match[1], state: match[2].trim(), next: match[3].trim(), text: line.trim() });
|
|
432
|
+
if (lines.length === 10) break;
|
|
433
|
+
}
|
|
434
|
+
return lines;
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
function closeLine(content) {
|
|
438
|
+
const lines = String(content || '').split(/\r?\n/);
|
|
439
|
+
for (const line of lines) {
|
|
440
|
+
const text = line.replace(/^\s+/, '').replace(/^(?:[-*+]|\d+[.)])\s+/, '').replace(/^(?:\*\*|__)/, '');
|
|
441
|
+
if (/^close verification\b/i.test(text)) return line.trim();
|
|
442
|
+
}
|
|
443
|
+
return null;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
function canonicalId(doc) {
|
|
447
|
+
if (doc && doc.canonical_id) return doc.canonical_id;
|
|
448
|
+
const parsed = parseHandoffId(doc && doc.doc_id);
|
|
449
|
+
if (parsed.kind === 'alias') return parsed.storedId;
|
|
450
|
+
return doc && doc.doc_id;
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
export function stampSessions(list) {
|
|
454
|
+
return (list || [])
|
|
455
|
+
.filter((row) => row && row.tag && row.material === true && row.closed !== true)
|
|
456
|
+
.map((row) => ({
|
|
457
|
+
session_id: row.session_id || null,
|
|
458
|
+
tag: row.tag,
|
|
459
|
+
since: row.since || null,
|
|
460
|
+
material: true
|
|
461
|
+
}))
|
|
462
|
+
.sort((a, b) => String(a.session_id).localeCompare(String(b.session_id)) || String(a.tag).localeCompare(String(b.tag)));
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
function sameStringList(a, b) {
|
|
466
|
+
return JSON.stringify([...(a || [])].sort()) === JSON.stringify([...(b || [])].sort());
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/**
|
|
470
|
+
* The stamp names every input the view used. A resolve is accepted only when
|
|
471
|
+
* those versions, settings, and sessions are still the ones in force, and the
|
|
472
|
+
* bytes rebuild at the stamp's own as_of.
|
|
473
|
+
*/
|
|
474
|
+
export function stampInForce(stamp, live) {
|
|
475
|
+
if (!stampHasAsOf(stamp)) return { ok: false, reason: 'stamp has no as_of' };
|
|
476
|
+
const problems = [];
|
|
477
|
+
const liveInputs = (live.inputs || [])
|
|
478
|
+
.filter((doc) => doc && doc.doc_id && doc.version != null)
|
|
479
|
+
.map((doc) => `${doc.doc_id}@v${doc.version}`);
|
|
480
|
+
if (!sameStringList(stamp.inputs, liveInputs)) problems.push('inputs');
|
|
481
|
+
const board = live.board || {};
|
|
482
|
+
const boardLabel = `${board.doc_id || 'STATE.md'}@v${board.version != null ? board.version : 0}`;
|
|
483
|
+
if (stamp.board !== boardLabel) problems.push('board');
|
|
484
|
+
if (stamp.person !== live.person) problems.push('person');
|
|
485
|
+
if (stamp.aging_days !== live.aging_days) problems.push('aging');
|
|
486
|
+
if (stamp.stale_open_hours !== live.stale_open_hours) problems.push('stale-open');
|
|
487
|
+
if (JSON.stringify(stamp.registry || []) !== JSON.stringify(live.registry || [])) problems.push('registry');
|
|
488
|
+
if (JSON.stringify(stamp.open_sessions || null) !== JSON.stringify(stampSessions(live.open_sessions))) problems.push('open sessions');
|
|
489
|
+
if (problems.length) return { ok: false, reason: problems.join(', ') };
|
|
490
|
+
const rebuilt = buildView({
|
|
491
|
+
inputs: live.inputs,
|
|
492
|
+
board: live.board,
|
|
493
|
+
as_of: stamp.as_of,
|
|
494
|
+
person: live.person,
|
|
495
|
+
open_sessions: live.open_sessions,
|
|
496
|
+
registry: live.registry,
|
|
497
|
+
aging_days: live.aging_days,
|
|
498
|
+
stale_open_hours: live.stale_open_hours,
|
|
499
|
+
settled: live.settled || null
|
|
500
|
+
});
|
|
501
|
+
if (!rebuilt.stamp || rebuilt.stamp.view_sha256 !== stamp.view_sha256) {
|
|
502
|
+
return { ok: false, reason: 'view_sha256' };
|
|
503
|
+
}
|
|
504
|
+
return { ok: true, view: rebuilt };
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* The merged view. Pure: the same inputs, board, and as_of return the same bytes.
|
|
509
|
+
* A stamp without as_of is flagged and is not reproducible.
|
|
510
|
+
*/
|
|
511
|
+
export function buildView({
|
|
512
|
+
inputs = [],
|
|
513
|
+
board = null,
|
|
514
|
+
as_of = null,
|
|
515
|
+
person = 'owner',
|
|
516
|
+
open_sessions = [],
|
|
517
|
+
retired_tags = [],
|
|
518
|
+
registry = [],
|
|
519
|
+
aging_days = 7,
|
|
520
|
+
stale_open_hours = 24,
|
|
521
|
+
now = null,
|
|
522
|
+
settled = null
|
|
523
|
+
} = {}) {
|
|
524
|
+
const asOf = typeof as_of === 'string' && as_of.trim() ? as_of.trim() : null;
|
|
525
|
+
const asOfMs = asOf ? msOf(asOf) : null;
|
|
526
|
+
const flagged = !asOf;
|
|
527
|
+
const boardRowsInOrder = boardRows(board && board.content, ['1', '3']);
|
|
528
|
+
const order = boardRowsInOrder.map((row) => row.id);
|
|
529
|
+
const closed = closedRowIds(board && board.content);
|
|
530
|
+
const retired = new Set(retired_tags || []);
|
|
531
|
+
const rank = new Map((registry || []).map((tag, index) => [tag, index]));
|
|
532
|
+
const lines = [];
|
|
533
|
+
for (const doc of inputs || []) {
|
|
534
|
+
if (!doc || typeof doc.content !== 'string' || !doc.doc_id || doc.version == null) continue;
|
|
535
|
+
const tag = doc.tag || parseHandoffId(doc.doc_id).tag;
|
|
536
|
+
if (!tag) continue;
|
|
537
|
+
const updated = msOf(doc.updated_at);
|
|
538
|
+
const date = dayOf(doc.updated_at) || 'unknown-date';
|
|
539
|
+
const cite = `[doc:${canonicalId(doc)}@v${doc.version} · ${tag} · ${date}]`;
|
|
540
|
+
const ageMs = aging_days * 86400000;
|
|
541
|
+
const aging = asOfMs != null && updated != null && asOfMs - updated > ageMs;
|
|
542
|
+
for (const picture of pictureLines(doc.content)) {
|
|
543
|
+
const rowClosed = closed.has(picture.row_id);
|
|
544
|
+
const tagRetired = retired.has(tag);
|
|
545
|
+
let currency = 'current';
|
|
546
|
+
if (tagRetired || rowClosed) currency = 'superseded-context';
|
|
547
|
+
else if (aging) currency = 'aging';
|
|
548
|
+
lines.push({
|
|
549
|
+
row_id: picture.row_id,
|
|
550
|
+
on_board: order.includes(picture.row_id),
|
|
551
|
+
tag,
|
|
552
|
+
state: picture.state,
|
|
553
|
+
next: picture.next,
|
|
554
|
+
currency,
|
|
555
|
+
updated_at: updated,
|
|
556
|
+
cite,
|
|
557
|
+
kind: 'picture'
|
|
558
|
+
});
|
|
559
|
+
}
|
|
560
|
+
const verify = closeLine(doc.content);
|
|
561
|
+
if (verify) {
|
|
562
|
+
lines.push({
|
|
563
|
+
row_id: null,
|
|
564
|
+
on_board: false,
|
|
565
|
+
tag,
|
|
566
|
+
state: '',
|
|
567
|
+
next: '',
|
|
568
|
+
currency: retired.has(tag) ? 'superseded-context' : 'current',
|
|
569
|
+
updated_at: updated,
|
|
570
|
+
cite,
|
|
571
|
+
kind: 'close',
|
|
572
|
+
text: verify
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
const byRow = new Map();
|
|
577
|
+
const loose = [];
|
|
578
|
+
const closes = [];
|
|
579
|
+
for (const line of lines) {
|
|
580
|
+
if (line.kind === 'close') { closes.push(line); continue; }
|
|
581
|
+
if (!line.on_board) { loose.push(line); continue; }
|
|
582
|
+
if (!byRow.has(line.row_id)) byRow.set(line.row_id, []);
|
|
583
|
+
byRow.get(line.row_id).push(line);
|
|
584
|
+
}
|
|
585
|
+
const sortLines = (list) => list.slice().sort((a, b) => {
|
|
586
|
+
const time = (b.updated_at || 0) - (a.updated_at || 0);
|
|
587
|
+
if (time !== 0) return time;
|
|
588
|
+
return (rank.get(a.tag) ?? 999) - (rank.get(b.tag) ?? 999);
|
|
589
|
+
});
|
|
590
|
+
const inputIds = (inputs || [])
|
|
591
|
+
.filter((doc) => doc && doc.doc_id && doc.version != null)
|
|
592
|
+
.map((doc) => `${doc.doc_id}@v${doc.version}`)
|
|
593
|
+
.sort();
|
|
594
|
+
const settlementCovers = (id) => {
|
|
595
|
+
const mark = settled && settled[id];
|
|
596
|
+
if (!mark || !Array.isArray(mark.inputs)) return false;
|
|
597
|
+
return mark.inputs.slice().sort().join('|') === inputIds.join('|');
|
|
598
|
+
};
|
|
599
|
+
const conflicts = [];
|
|
600
|
+
for (const id of order) {
|
|
601
|
+
const group = sortLines(byRow.get(id) || []);
|
|
602
|
+
const latest = new Map();
|
|
603
|
+
for (const line of group) if (!latest.has(line.tag)) latest.set(line.tag, line);
|
|
604
|
+
const views = [...latest.values()];
|
|
605
|
+
if (views.length >= 2) {
|
|
606
|
+
const first = views[0];
|
|
607
|
+
const disagree = views.some((line) => line.state !== first.state || line.next !== first.next);
|
|
608
|
+
if (disagree && !settlementCovers(id)) conflicts.push(id);
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
const conflictSet = new Set(conflicts);
|
|
612
|
+
const progress = [];
|
|
613
|
+
const stale = [];
|
|
614
|
+
const sessions = stampSessions(open_sessions);
|
|
615
|
+
const clock = asOfMs != null ? asOfMs : msOf(now);
|
|
616
|
+
for (const session of sessions) {
|
|
617
|
+
if (!session || session.closed === true || !session.tag || session.material !== true) continue;
|
|
618
|
+
const since = session.since || session.opened_at;
|
|
619
|
+
const sinceMs = msOf(since);
|
|
620
|
+
const hours = clock != null && sinceMs != null ? (clock - sinceMs) / 3600000 : 0;
|
|
621
|
+
const mark = hours > stale_open_hours;
|
|
622
|
+
progress.push({ tag: session.tag, since: since || null, session_id: session.session_id || null, stale: mark });
|
|
623
|
+
if (mark) stale.push({ tag: session.tag, since: since || null, session_id: session.session_id || null });
|
|
624
|
+
}
|
|
625
|
+
const blocks = [];
|
|
626
|
+
blocks.push(`person: ${person}`);
|
|
627
|
+
blocks.push(`as_of: ${asOf || ''}`);
|
|
628
|
+
blocks.push(`board: ${board && board.doc_id ? board.doc_id : 'STATE.md'}@v${board && board.version != null ? board.version : 0}`);
|
|
629
|
+
for (const id of order) {
|
|
630
|
+
const group = sortLines(byRow.get(id) || []);
|
|
631
|
+
if (!group.length) continue;
|
|
632
|
+
blocks.push('');
|
|
633
|
+
blocks.push(`## ${id}`);
|
|
634
|
+
if (conflictSet.has(id)) blocks.push('- conflict');
|
|
635
|
+
for (const line of group) {
|
|
636
|
+
blocks.push(`- ${line.cite} state: ${line.state}; next: ${line.next}`);
|
|
637
|
+
blocks.push(` class: ${line.currency}`);
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
const looseSorted = sortLines(loose);
|
|
641
|
+
if (looseSorted.length) {
|
|
642
|
+
blocks.push('');
|
|
643
|
+
blocks.push('## not on the board yet');
|
|
644
|
+
for (const line of looseSorted) {
|
|
645
|
+
blocks.push(`- ${line.cite} ${line.row_id} state: ${line.state}; next: ${line.next}`);
|
|
646
|
+
blocks.push(` class: ${line.currency}`);
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
if (closes.length) {
|
|
650
|
+
blocks.push('');
|
|
651
|
+
blocks.push('## close verification');
|
|
652
|
+
for (const line of sortLines(closes)) blocks.push(`- ${line.cite} ${line.text}`);
|
|
653
|
+
}
|
|
654
|
+
if (progress.length) {
|
|
655
|
+
blocks.push('');
|
|
656
|
+
blocks.push('## in progress');
|
|
657
|
+
for (const line of progress) {
|
|
658
|
+
blocks.push(`- in progress by ${line.tag} since ${line.since || 'unknown'}`);
|
|
659
|
+
if (line.stale) blocks.push(' stale-open');
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
const text = `${blocks.join('\n')}\n`;
|
|
663
|
+
const view_sha256 = crypto.createHash('sha256').update(text, 'utf8').digest('hex');
|
|
664
|
+
const stamp = flagged ? null : {
|
|
665
|
+
as_of: asOf,
|
|
666
|
+
person,
|
|
667
|
+
inputs: inputIds,
|
|
668
|
+
board: `${board && board.doc_id ? board.doc_id : 'STATE.md'}@v${board && board.version != null ? board.version : 0}`,
|
|
669
|
+
open_sessions: sessions,
|
|
670
|
+
aging_days,
|
|
671
|
+
stale_open_hours,
|
|
672
|
+
registry: [...(registry || [])],
|
|
673
|
+
view_sha256
|
|
674
|
+
};
|
|
675
|
+
return {
|
|
676
|
+
text,
|
|
677
|
+
stamp,
|
|
678
|
+
conflicts,
|
|
679
|
+
in_progress: progress,
|
|
680
|
+
stale_open: stale,
|
|
681
|
+
reproducible: !flagged,
|
|
682
|
+
stamp_flagged: flagged,
|
|
683
|
+
flag_reason: flagged ? 'stamp has no as_of' : null
|
|
684
|
+
};
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
export function initViewText(view, limit = 40) {
|
|
688
|
+
const lines = String(view && view.text || '').split('\n');
|
|
689
|
+
if (lines.length <= limit) return view.text;
|
|
690
|
+
const head = lines.slice(0, limit);
|
|
691
|
+
head.push('read_doc the handoff documents named in the stamp.');
|
|
692
|
+
return `${head.join('\n')}\n`;
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
export function stampWithoutAsOf(stamp) {
|
|
696
|
+
if (!stamp || typeof stamp !== 'object') return { ok: false, flagged: true, reason: 'stamp has no as_of' };
|
|
697
|
+
if (!stampHasAsOf(stamp)) return { ok: false, flagged: true, reason: 'stamp has no as_of' };
|
|
698
|
+
if (!STAMP_SHA.test(String(stamp.view_sha256 || ''))) return { ok: false, flagged: true, reason: 'stamp has no view_sha256' };
|
|
699
|
+
return { ok: true, flagged: false };
|
|
700
|
+
}
|
|
701
|
+
|
|
702
|
+
const STATUS_RANK = { unreadable: 0, warn: 1, no_handoff: 2, no_op: 3, current: 4 };
|
|
703
|
+
|
|
704
|
+
export function worstStatus(statuses) {
|
|
705
|
+
let worst = 'current';
|
|
706
|
+
for (const status of statuses || []) {
|
|
707
|
+
if (STATUS_RANK[status] == null) continue;
|
|
708
|
+
if (STATUS_RANK[status] < STATUS_RANK[worst]) worst = status;
|
|
709
|
+
}
|
|
710
|
+
return worst;
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
export function openSessionsFromRows(rows, nowMs = Date.now()) {
|
|
714
|
+
const out = [];
|
|
715
|
+
for (const row of rows || []) {
|
|
716
|
+
if (!row || row.closed === true) continue;
|
|
717
|
+
const tag = row.tag || row.source || row.channel || null;
|
|
718
|
+
if (!tag) continue;
|
|
719
|
+
const material = row.material === true || row.episodic === true || row.episodic_id != null;
|
|
720
|
+
if (!material) continue;
|
|
721
|
+
out.push({
|
|
722
|
+
tag,
|
|
723
|
+
since: row.opened_at || row.updated_at || null,
|
|
724
|
+
session_id: row.session_id || row._id || null,
|
|
725
|
+
material: true,
|
|
726
|
+
closed: false,
|
|
727
|
+
now: nowMs
|
|
728
|
+
});
|
|
729
|
+
}
|
|
730
|
+
return out;
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
function sourceOf(entry) {
|
|
734
|
+
const md = entry && entry.metadata;
|
|
735
|
+
if (md && typeof md === 'object' && typeof md.source === 'string') return md.source.trim();
|
|
736
|
+
if (typeof md === 'string') {
|
|
737
|
+
const match = md.match(/"source"\s*:\s*"([^"]+)"/);
|
|
738
|
+
if (match) return match[1].trim();
|
|
739
|
+
}
|
|
740
|
+
return null;
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
export function partitionEpisodic(entries, tags) {
|
|
744
|
+
const known = new Set(tags || []);
|
|
745
|
+
const byTag = new Map();
|
|
746
|
+
const unattributed = [];
|
|
747
|
+
for (const tag of known) byTag.set(tag, []);
|
|
748
|
+
for (const entry of entries || []) {
|
|
749
|
+
const source = sourceOf(entry);
|
|
750
|
+
if (source && known.has(source)) byTag.get(source).push(entry);
|
|
751
|
+
else unattributed.push(entry);
|
|
752
|
+
}
|
|
753
|
+
return { byTag, unattributed };
|
|
754
|
+
}
|
|
755
|
+
|
|
756
|
+
async function readDocs(db, query) {
|
|
757
|
+
const rows = await db.collection('documents').find(query).toArray();
|
|
758
|
+
return Array.isArray(rows) ? rows : [];
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
export async function boardWritePlan(col, {
|
|
762
|
+
previous = null,
|
|
763
|
+
next = '',
|
|
764
|
+
writer = null,
|
|
765
|
+
hub = null,
|
|
766
|
+
mode = tagHandoffMode(),
|
|
767
|
+
resolve = null,
|
|
768
|
+
at = new Date().toISOString(),
|
|
769
|
+
person = 'owner',
|
|
770
|
+
docId = 'STATE.md',
|
|
771
|
+
db = null
|
|
772
|
+
} = {}) {
|
|
773
|
+
if (mode === 'off') return { openers: null, warnings: [], conflict_settled: null };
|
|
774
|
+
requireHubTag();
|
|
775
|
+
const stored = previous && previous.row_openers && typeof previous.row_openers === 'object' ? previous.row_openers : null;
|
|
776
|
+
const openers = seedOpeners(previous && previous.content, stored, hub, at, previous && previous.version);
|
|
777
|
+
const changed = changedRowIds(previous && previous.content, next);
|
|
778
|
+
const loaded = db
|
|
779
|
+
? await loadHandoffInputs(db, { person, hub })
|
|
780
|
+
: await loadHandoffInputsFromCol(col, { person, hub });
|
|
781
|
+
const board = {
|
|
782
|
+
doc_id: docId,
|
|
783
|
+
version: previous && previous.version != null ? previous.version : 0,
|
|
784
|
+
content: previous && previous.content ? previous.content : ''
|
|
785
|
+
};
|
|
786
|
+
const named = resolve && resolve.handoff_view;
|
|
787
|
+
const asOf = stampHasAsOf(named) ? named.as_of.trim() : at;
|
|
788
|
+
const priorSettled = previous && previous.conflict_settled && typeof previous.conflict_settled === 'object'
|
|
789
|
+
? previous.conflict_settled
|
|
790
|
+
: null;
|
|
791
|
+
const live = {
|
|
792
|
+
inputs: loaded.inputs,
|
|
793
|
+
board,
|
|
794
|
+
person,
|
|
795
|
+
open_sessions: loaded.open_sessions || [],
|
|
796
|
+
registry: loaded.registry || [],
|
|
797
|
+
aging_days: handoffAgingDays(),
|
|
798
|
+
stale_open_hours: staleOpenHours(),
|
|
799
|
+
settled: priorSettled
|
|
800
|
+
};
|
|
801
|
+
if (stampHasAsOf(named)) {
|
|
802
|
+
const force = stampInForce(named, live);
|
|
803
|
+
if (!force.ok) {
|
|
804
|
+
refuse(`The conflict was named against a stamp that is not the view in force (${force.reason}). Re-read the handoff view.`, 'EMET-DOC-085');
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
const view = buildView({ ...live, as_of: asOf });
|
|
808
|
+
const decision = decideRowWrite({
|
|
809
|
+
mode,
|
|
810
|
+
writer,
|
|
811
|
+
hub,
|
|
812
|
+
openers,
|
|
813
|
+
changed,
|
|
814
|
+
conflicts: view.conflicts,
|
|
815
|
+
resolve,
|
|
816
|
+
currentStamp: view.stamp
|
|
817
|
+
});
|
|
818
|
+
const settled = { ...(priorSettled || {}) };
|
|
819
|
+
const inputIds = (view.stamp && view.stamp.inputs) || [];
|
|
820
|
+
for (const id of decision.resolved || []) settled[id] = { inputs: inputIds };
|
|
821
|
+
return {
|
|
822
|
+
openers: applyOpeners(openers, next, writer, at, (previous && previous.version ? previous.version : 0) + 1),
|
|
823
|
+
warnings: decision.warnings,
|
|
824
|
+
conflicts: view.conflicts,
|
|
825
|
+
conflict_settled: settled
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
async function loadHandoffInputsFromCol(col, { person, hub }) {
|
|
830
|
+
const tags = writeTagRegistry();
|
|
831
|
+
const hubName = hub === undefined ? hubTag() : hub;
|
|
832
|
+
const wanted = new Set(tags);
|
|
833
|
+
if (hubName) wanted.add(hubName);
|
|
834
|
+
let docs = [];
|
|
835
|
+
try {
|
|
836
|
+
docs = await col.find({
|
|
837
|
+
$or: [
|
|
838
|
+
{ doc_id: 'HANDOFF.md' },
|
|
839
|
+
{ doc_id: { $regex: '^HANDOFF/' } },
|
|
840
|
+
{ doc_id: { $regex: '^bots/[^/]+/HANDOFF\\.md$' } }
|
|
841
|
+
]
|
|
842
|
+
}).toArray();
|
|
843
|
+
} catch {
|
|
844
|
+
docs = [];
|
|
845
|
+
}
|
|
846
|
+
const byTag = new Map();
|
|
847
|
+
for (const doc of docs || []) {
|
|
848
|
+
if (!doc || doc.retired === true) continue;
|
|
849
|
+
const parsed = parseHandoffId(doc.doc_id, person);
|
|
850
|
+
if (parsed.kind === 'hub' && hubName) {
|
|
851
|
+
byTag.set(hubName, docInput(doc, hubName, 'HANDOFF.md'));
|
|
852
|
+
continue;
|
|
853
|
+
}
|
|
854
|
+
if (parsed.kind !== 'short' && parsed.kind !== 'alias') continue;
|
|
855
|
+
if (parsed.kind === 'short' && hubName && parsed.tag === hubName) continue;
|
|
856
|
+
if (!wanted.has(parsed.tag)) continue;
|
|
857
|
+
const current = byTag.get(parsed.tag);
|
|
858
|
+
if (parsed.kind === 'alias' && current && String(current.doc_id).startsWith('HANDOFF/')) continue;
|
|
859
|
+
byTag.set(parsed.tag, docInput(doc, parsed.tag, parsed.kind === 'alias' ? parsed.storedId : doc.doc_id));
|
|
860
|
+
}
|
|
861
|
+
return { inputs: [...byTag.values()], registry: [...wanted] };
|
|
862
|
+
}
|
|
863
|
+
|
|
864
|
+
function docInput(doc, tag, canonical) {
|
|
865
|
+
return {
|
|
866
|
+
doc_id: doc.doc_id,
|
|
867
|
+
tag,
|
|
868
|
+
version: doc.version,
|
|
869
|
+
updated_at: doc.updated_at,
|
|
870
|
+
content: typeof doc.content === 'string' ? doc.content : '',
|
|
871
|
+
canonical_id: canonical
|
|
872
|
+
};
|
|
873
|
+
}
|
|
874
|
+
|
|
875
|
+
export async function loadHandoffInputs(db, { person = 'owner', registry = null, hub } = {}) {
|
|
876
|
+
const tags = registry || writeTagRegistry();
|
|
877
|
+
const hubName = hub === undefined ? hubTag() : hub;
|
|
878
|
+
const wanted = new Set(tags);
|
|
879
|
+
if (hubName) wanted.add(hubName);
|
|
880
|
+
const docs = await readDocs(db, {
|
|
881
|
+
$or: [
|
|
882
|
+
{ doc_id: 'HANDOFF.md' },
|
|
883
|
+
{ doc_id: { $regex: '^HANDOFF/' } },
|
|
884
|
+
{ doc_id: { $regex: '^bots/[^/]+/HANDOFF\\.md$' } }
|
|
885
|
+
]
|
|
886
|
+
});
|
|
887
|
+
const byTag = new Map();
|
|
888
|
+
let board = null;
|
|
889
|
+
const stateId = setting('STATE_DOC', 'STATE.md');
|
|
890
|
+
const state = await db.collection('documents').findOne({ doc_id: stateId });
|
|
891
|
+
if (state) {
|
|
892
|
+
board = {
|
|
893
|
+
doc_id: state.doc_id,
|
|
894
|
+
version: state.version,
|
|
895
|
+
content: state.content || '',
|
|
896
|
+
updated_at: state.updated_at,
|
|
897
|
+
row_openers: state.row_openers || null,
|
|
898
|
+
conflict_settled: state.conflict_settled || null
|
|
899
|
+
};
|
|
900
|
+
}
|
|
901
|
+
for (const doc of docs) {
|
|
902
|
+
if (!doc || doc.retired === true) continue;
|
|
903
|
+
const parsed = parseHandoffId(doc.doc_id, person);
|
|
904
|
+
if (parsed.kind === 'hub') {
|
|
905
|
+
if (hubName) {
|
|
906
|
+
byTag.set(hubName, {
|
|
907
|
+
doc_id: doc.doc_id,
|
|
908
|
+
tag: hubName,
|
|
909
|
+
version: doc.version,
|
|
910
|
+
updated_at: doc.updated_at,
|
|
911
|
+
content: typeof doc.content === 'string' ? doc.content : '',
|
|
912
|
+
canonical_id: 'HANDOFF.md'
|
|
913
|
+
});
|
|
914
|
+
}
|
|
915
|
+
continue;
|
|
916
|
+
}
|
|
917
|
+
if (parsed.kind !== 'short' && parsed.kind !== 'alias') continue;
|
|
918
|
+
if (parsed.kind === 'short' && hubName && parsed.tag === hubName) continue;
|
|
919
|
+
if (!wanted.has(parsed.tag)) continue;
|
|
920
|
+
const current = byTag.get(parsed.tag);
|
|
921
|
+
if (parsed.kind === 'alias' && current && String(current.doc_id).startsWith('HANDOFF/')) continue;
|
|
922
|
+
byTag.set(parsed.tag, {
|
|
923
|
+
doc_id: doc.doc_id,
|
|
924
|
+
tag: parsed.tag,
|
|
925
|
+
version: doc.version,
|
|
926
|
+
updated_at: doc.updated_at,
|
|
927
|
+
content: typeof doc.content === 'string' ? doc.content : '',
|
|
928
|
+
canonical_id: parsed.kind === 'alias' ? parsed.storedId : doc.doc_id
|
|
929
|
+
});
|
|
930
|
+
}
|
|
931
|
+
let openRows = [];
|
|
932
|
+
try {
|
|
933
|
+
const cutoff = new Date(Date.now() - OPEN_SESSION_LOOKBACK_MS);
|
|
934
|
+
openRows = await db.collection(`${COLLECTION_PREFIX}sessions`).find(
|
|
935
|
+
{
|
|
936
|
+
closed: { $ne: true },
|
|
937
|
+
$or: [
|
|
938
|
+
{ updated_at: { $gte: cutoff } },
|
|
939
|
+
{ opened_at: { $gte: cutoff } }
|
|
940
|
+
]
|
|
941
|
+
},
|
|
942
|
+
{ projection: { tag: 1, source: 1, channel: 1, opened_at: 1, updated_at: 1, episodic: 1, episodic_id: 1, closed: 1 } }
|
|
943
|
+
).toArray();
|
|
944
|
+
} catch {
|
|
945
|
+
openRows = [];
|
|
946
|
+
}
|
|
947
|
+
return { inputs: [...byTag.values()], board, open_sessions: openSessionsFromRows(openRows), registry: [...wanted] };
|
|
948
|
+
}
|
|
949
|
+
|
|
950
|
+
export async function attachHandoffView(db, target, tag = null) {
|
|
951
|
+
if (!target || tagHandoffMode() === 'off') return target;
|
|
952
|
+
const actor = currentActor();
|
|
953
|
+
const readOnly = !!(actor && actor.door === 'guest');
|
|
954
|
+
const person = (actor && actor.personId) || 'owner';
|
|
955
|
+
const view = await loadHandoffView(db, {
|
|
956
|
+
person,
|
|
957
|
+
asOf: new Date().toISOString(),
|
|
958
|
+
readOnly,
|
|
959
|
+
tag: readOnly ? null : tag
|
|
960
|
+
});
|
|
961
|
+
Object.assign(target, view);
|
|
962
|
+
return target;
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
export async function loadHandoffView(db, { person = 'owner', asOf = new Date().toISOString(), readOnly = false, tag = null } = {}) {
|
|
966
|
+
const loaded = await loadHandoffInputs(db, { person });
|
|
967
|
+
const view = buildView({
|
|
968
|
+
inputs: loaded.inputs,
|
|
969
|
+
board: loaded.board,
|
|
970
|
+
as_of: asOf,
|
|
971
|
+
person,
|
|
972
|
+
open_sessions: loaded.open_sessions,
|
|
973
|
+
registry: loaded.registry,
|
|
974
|
+
aging_days: handoffAgingDays(),
|
|
975
|
+
stale_open_hours: staleOpenHours(),
|
|
976
|
+
settled: loaded.board && loaded.board.conflict_settled
|
|
977
|
+
});
|
|
978
|
+
const own = !readOnly && tag ? loaded.inputs.find((doc) => doc.tag === tag) : null;
|
|
979
|
+
const ownLines = own ? pictureLines(own.content) : [];
|
|
980
|
+
const stale = readOnly ? [] : (view.stale_open || []).filter((row) => !tag || row.tag === tag);
|
|
981
|
+
return {
|
|
982
|
+
handoff_view: view.stamp,
|
|
983
|
+
handoff_view_text: initViewText(view),
|
|
984
|
+
handoff_view_conflicts: view.conflicts,
|
|
985
|
+
...(readOnly ? {} : { own_handoff: own ? { doc_id: own.doc_id, version: own.version, section_1: ownLines } : { doc_id: tag ? `HANDOFF/${tag}.md` : null, version: null, section_1: [], note: 'no handoff yet' } }),
|
|
986
|
+
...(readOnly ? {} : { stale_open: stale })
|
|
987
|
+
};
|
|
988
|
+
}
|