shipmates 0.0.0-stage → 0.2.0

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 (68) hide show
  1. package/LICENSE +661 -0
  2. package/dist/cli-run.d.ts +9 -0
  3. package/dist/cli-run.d.ts.map +1 -0
  4. package/dist/cli-run.js +237 -0
  5. package/dist/cli-run.js.map +1 -0
  6. package/dist/cli.d.ts +3 -0
  7. package/dist/cli.d.ts.map +1 -0
  8. package/dist/cli.js +11 -0
  9. package/dist/cli.js.map +1 -0
  10. package/dist/delivery.d.ts +37 -0
  11. package/dist/delivery.d.ts.map +1 -0
  12. package/dist/delivery.js +13 -0
  13. package/dist/delivery.js.map +1 -0
  14. package/dist/host.d.ts +132 -0
  15. package/dist/host.d.ts.map +1 -0
  16. package/dist/host.js +66 -0
  17. package/dist/host.js.map +1 -0
  18. package/dist/ids.d.ts +3 -0
  19. package/dist/ids.d.ts.map +1 -0
  20. package/dist/ids.js +6 -0
  21. package/dist/ids.js.map +1 -0
  22. package/dist/index.d.ts +17 -0
  23. package/dist/index.d.ts.map +1 -0
  24. package/dist/index.js +11 -0
  25. package/dist/index.js.map +1 -0
  26. package/dist/liveness.d.ts +25 -0
  27. package/dist/liveness.d.ts.map +1 -0
  28. package/dist/liveness.js +75 -0
  29. package/dist/liveness.js.map +1 -0
  30. package/dist/quiet.d.ts +7 -0
  31. package/dist/quiet.d.ts.map +1 -0
  32. package/dist/quiet.js +19 -0
  33. package/dist/quiet.js.map +1 -0
  34. package/dist/shipmates.d.ts +401 -0
  35. package/dist/shipmates.d.ts.map +1 -0
  36. package/dist/shipmates.js +1112 -0
  37. package/dist/shipmates.js.map +1 -0
  38. package/dist/store.d.ts +19 -0
  39. package/dist/store.d.ts.map +1 -0
  40. package/dist/store.js +236 -0
  41. package/dist/store.js.map +1 -0
  42. package/dist/tail.d.ts +27 -0
  43. package/dist/tail.d.ts.map +1 -0
  44. package/dist/tail.js +127 -0
  45. package/dist/tail.js.map +1 -0
  46. package/dist/types.d.ts +129 -0
  47. package/dist/types.d.ts.map +1 -0
  48. package/dist/types.js +11 -0
  49. package/dist/types.js.map +1 -0
  50. package/dist/watch.d.ts +13 -0
  51. package/dist/watch.d.ts.map +1 -0
  52. package/dist/watch.js +30 -0
  53. package/dist/watch.js.map +1 -0
  54. package/package.json +48 -3
  55. package/src/cli-run.ts +263 -0
  56. package/src/cli.ts +11 -0
  57. package/src/delivery.ts +49 -0
  58. package/src/host.ts +161 -0
  59. package/src/ids.ts +6 -0
  60. package/src/index.ts +44 -0
  61. package/src/liveness.ts +86 -0
  62. package/src/quiet.ts +22 -0
  63. package/src/shipmates.ts +1634 -0
  64. package/src/store.ts +252 -0
  65. package/src/tail.ts +143 -0
  66. package/src/types.ts +138 -0
  67. package/src/watch.ts +32 -0
  68. package/README.md +0 -3
@@ -0,0 +1,1112 @@
1
+ import fs from 'node:fs';
2
+ import { defaultStateDir, openDb, write } from './store.js';
3
+ import { OsProbe } from './liveness.js';
4
+ import { ShipmatesError, } from './types.js';
5
+ import { newId } from './ids.js';
6
+ /** D14: message text is short; content stays in git and messages point at it. */
7
+ const DAY = 86_400_000;
8
+ export const MAX_TEXT_BYTES = 8 * 1024;
9
+ /**
10
+ * D24: an archive or delete cascade can be undone, as one batch, for 7 days. A
11
+ * cascade from an orchestrator takes every lane with it, and an accidental one
12
+ * is often noticed only after a weekend; until the window ends a host must not
13
+ * remove a deleted session's transcript. Rejected: a seconds-long "undo" toast
14
+ * (a cascade is noticed later than that) and 24 hours (shorter than a weekend).
15
+ */
16
+ export const ARCHIVE_UNDO_MS = 7 * DAY;
17
+ const toArchive = (r) => ({
18
+ session: r.session_file,
19
+ kind: r.kind,
20
+ batch: r.batch,
21
+ by: r.by_label,
22
+ at: r.at,
23
+ undoUntil: r.at + ARCHIVE_UNDO_MS,
24
+ });
25
+ const toStop = (r) => ({
26
+ id: r.id,
27
+ session: r.session_file,
28
+ by: r.by_session,
29
+ byLabel: r.by_label,
30
+ at: r.at,
31
+ handledAt: r.handled_at,
32
+ outcome: r.outcome,
33
+ });
34
+ function toQuestion(r) {
35
+ return {
36
+ id: r.id,
37
+ asker: r.asker_session,
38
+ askerLabel: r.asker_label,
39
+ messageId: r.message_id,
40
+ to: { kind: r.to_kind, target: r.to_target },
41
+ text: r.text,
42
+ state: r.state,
43
+ answer: r.answer,
44
+ answerOrigin: r.answer_origin,
45
+ answerRelay: r.answer_relay ? JSON.parse(r.answer_relay) : null,
46
+ answeredBy: r.answered_by,
47
+ createdAt: r.created_at,
48
+ };
49
+ }
50
+ function toItem(r) {
51
+ return {
52
+ id: r.id,
53
+ session: r.session_file,
54
+ question: r.question,
55
+ options: r.options ? JSON.parse(r.options) : null,
56
+ blocking: r.blocking === 1,
57
+ onBehalfOf: r.on_behalf_of ? JSON.parse(r.on_behalf_of) : [],
58
+ state: r.state,
59
+ answer: r.answer,
60
+ answerChannel: r.answer_channel,
61
+ createdAt: r.created_at,
62
+ };
63
+ }
64
+ /** D8: lower-case words joined by `._:/-`, e.g. `template-tree/push` or `orchestrator:template-tree`. */
65
+ const ROLE_RE = /^[a-z0-9][a-z0-9._:/-]{0,79}$/;
66
+ export class Shipmates {
67
+ db;
68
+ probe;
69
+ now;
70
+ localWrites = 0;
71
+ constructor(opts = {}) {
72
+ this.db = openDb(opts.stateDir ?? defaultStateDir());
73
+ this.probe = opts.probe ?? new OsProbe();
74
+ this.now = opts.now ?? Date.now;
75
+ }
76
+ close() {
77
+ this.db.close();
78
+ }
79
+ /** Changes whenever any connection (this one included) committed a write. */
80
+ changeToken() {
81
+ const row = this.db.prepare('PRAGMA data_version').get();
82
+ return `${row.data_version}:${this.localWrites}`;
83
+ }
84
+ tx(fn) {
85
+ const out = write(this.db, fn);
86
+ this.localWrites++;
87
+ return out;
88
+ }
89
+ // ---------------------------------------------------------------- presence
90
+ register(input) {
91
+ const me = this.probe.self();
92
+ const t = this.now();
93
+ this.tx(() => {
94
+ this.db
95
+ .prepare(`INSERT INTO presence(session_file, session_id, cwd, branch, state, pid, start_time, boot_id, host, registered_at, updated_at)
96
+ VALUES(?, ?, ?, ?, 'idle', ?, ?, ?, ?, ?, ?)
97
+ ON CONFLICT(session_file) DO UPDATE SET
98
+ session_id = excluded.session_id, cwd = excluded.cwd,
99
+ branch = COALESCE(excluded.branch, presence.branch),
100
+ pid = excluded.pid, start_time = excluded.start_time, boot_id = excluded.boot_id,
101
+ host = excluded.host, updated_at = excluded.updated_at,
102
+ state = CASE WHEN presence.pid = excluded.pid THEN presence.state ELSE 'idle' END`)
103
+ .run(input.sessionFile, input.sessionId ?? null, input.cwd ?? null, input.branch ?? null, me.pid, me.startTime, me.bootId, me.host, t, t);
104
+ });
105
+ return this.presence(input.sessionFile);
106
+ }
107
+ update(sessionFile, patch) {
108
+ const sets = [];
109
+ const vals = [];
110
+ const put = (col, v) => {
111
+ sets.push(`${col} = ?`);
112
+ vals.push(v);
113
+ };
114
+ if (patch.state !== undefined) {
115
+ put('state', patch.state);
116
+ if (patch.state === 'idle' || patch.state === 'waiting-for-human')
117
+ put('settled_at', this.now());
118
+ }
119
+ if (patch.status !== undefined)
120
+ put('status', patch.status);
121
+ if (patch.refs !== undefined)
122
+ put('refs', JSON.stringify(patch.refs));
123
+ if (patch.waitingOn !== undefined)
124
+ put('waiting_on', patch.waitingOn);
125
+ if (patch.branch !== undefined)
126
+ put('branch', patch.branch);
127
+ if (patch.cwd !== undefined)
128
+ put('cwd', patch.cwd);
129
+ if (patch.wake !== undefined)
130
+ put('wake', patch.wake ? 1 : 0);
131
+ put('updated_at', this.now());
132
+ this.tx(() => {
133
+ this.db
134
+ .prepare(`UPDATE presence SET ${sets.join(', ')} WHERE session_file = ?`)
135
+ .run(...vals, sessionFile);
136
+ });
137
+ }
138
+ unregister(sessionFile) {
139
+ const me = this.probe.self();
140
+ this.tx(() => {
141
+ // Only the process that registered it may remove it: the same file can be
142
+ // re-opened by another process (a resume elsewhere) before this one exits.
143
+ this.db
144
+ .prepare(`DELETE FROM presence WHERE session_file = ? AND pid = ?`)
145
+ .run(sessionFile, me.pid);
146
+ });
147
+ }
148
+ presence(sessionFile) {
149
+ const row = this.db
150
+ .prepare(`SELECT * FROM presence WHERE session_file = ?`)
151
+ .get(sessionFile);
152
+ return row ? this.toPresence(row) : null;
153
+ }
154
+ isLive(sessionFile) {
155
+ return this.presence(sessionFile)?.live ?? false;
156
+ }
157
+ list(filter = {}) {
158
+ const rows = this.db
159
+ .prepare(`SELECT * FROM presence ORDER BY updated_at DESC`)
160
+ .all();
161
+ return rows
162
+ .map((r) => this.toPresence(r))
163
+ .filter((p) => filter.includeGone || p.live)
164
+ .filter((p) => !filter.cwd || p.cwd === filter.cwd)
165
+ .filter((p) => !filter.state || p.state === filter.state)
166
+ .filter((p) => !filter.role || p.roles.includes(filter.role));
167
+ }
168
+ // ------------------------------------------------------------------- roles
169
+ claimRole(sessionFile, role, opts = {}) {
170
+ if (!ROLE_RE.test(role))
171
+ throw new ShipmatesError(`invalid role ${JSON.stringify(role)}: use lower-case words joined by . _ : / - (e.g. template-tree/push)`, 'bad-role');
172
+ return this.tx(() => {
173
+ const row = this.db
174
+ .prepare(`SELECT session_file FROM role WHERE role = ?`)
175
+ .get(role);
176
+ const holder = row?.session_file ?? null;
177
+ if (holder === sessionFile)
178
+ return { ok: true, previous: null };
179
+ if (holder && this.isLive(holder) && !opts.takeover)
180
+ return { ok: false, holder };
181
+ this.db
182
+ .prepare(`INSERT INTO role(role, session_file, claimed_at) VALUES(?, ?, ?)
183
+ ON CONFLICT(role) DO UPDATE SET session_file = excluded.session_file, claimed_at = excluded.claimed_at`)
184
+ .run(role, sessionFile, this.now());
185
+ if (holder && this.isLive(holder))
186
+ this.insertMessage({
187
+ from: sessionFile,
188
+ fromLabel: this.labelOf(sessionFile),
189
+ to: { kind: 'session', target: holder },
190
+ kind: 'notice',
191
+ text: `shipmates: the role ${role} was taken over by ${sessionFile}. You no longer hold it; messages to ${role} now go there.`,
192
+ origin: 'agent',
193
+ });
194
+ return { ok: true, previous: holder };
195
+ });
196
+ }
197
+ releaseRole(sessionFile, role) {
198
+ this.tx(() => {
199
+ this.db
200
+ .prepare(`DELETE FROM role WHERE role = ? AND session_file = ?`)
201
+ .run(role, sessionFile);
202
+ });
203
+ }
204
+ roleHolder(role) {
205
+ const row = this.db
206
+ .prepare(`SELECT session_file FROM role WHERE role = ?`)
207
+ .get(role);
208
+ return row?.session_file ?? null;
209
+ }
210
+ /** D15: a `.jsonl` string is a session; else an exact role; else a unique session-id prefix. */
211
+ resolve(target) {
212
+ const t = target.trim();
213
+ if (t.endsWith('.jsonl'))
214
+ return { kind: 'session', target: t, session: t };
215
+ const holder = this.roleHolder(t);
216
+ if (holder)
217
+ return { kind: 'role', target: t, session: holder };
218
+ const matches = this.db
219
+ .prepare(`SELECT session_file FROM presence WHERE session_id LIKE ? ESCAPE '\\'`)
220
+ .all(t.replace(/[\\%_]/g, (c) => '\\' + c) + '%');
221
+ if (matches.length === 1)
222
+ return {
223
+ kind: 'session',
224
+ target: matches[0].session_file,
225
+ session: matches[0].session_file,
226
+ };
227
+ if (matches.length > 1)
228
+ throw new ShipmatesError(`ambiguous target ${JSON.stringify(t)}: ${matches.map((m) => m.session_file).join(', ')}`, 'ambiguous', matches.map((m) => m.session_file));
229
+ // A role nobody holds yet still resolves (the message waits for its next
230
+ // holder), but only when it looks like one, so a typo is not silently queued.
231
+ if (ROLE_RE.test(t) && /[/:]/.test(t))
232
+ return { kind: 'role', target: t, session: null };
233
+ throw new ShipmatesError(`no session or role matches ${JSON.stringify(t)}`, 'not-found');
234
+ }
235
+ // ----------------------------------------------------------------- mailbox
236
+ /**
237
+ * Send a message. The result carries the target's presence and open
238
+ * questions, so the sender sees what it is talking to (read before send).
239
+ * `requestId` makes a retried send a no-op (exactly once per sender).
240
+ */
241
+ send(input) {
242
+ const text = input.text;
243
+ if (!text.trim())
244
+ throw new ShipmatesError('a message needs text', 'empty');
245
+ if (Buffer.byteLength(text) > MAX_TEXT_BYTES)
246
+ throw new ShipmatesError(`message is over 8 KB (${Buffer.byteLength(text)} bytes): put the content in git (a branch, a commit, a plan section) and send a pointer to it`, 'too-large');
247
+ const origin = input.origin ?? (input.from ? 'agent' : 'human');
248
+ if (origin === 'human-relayed' && !input.relay)
249
+ throw new ShipmatesError('a human-relayed message must carry the relay (the human words and where they were said)', 'no-relay');
250
+ const resolved = this.resolve(input.to);
251
+ const fromLabel = input.fromLabel ?? this.labelOf(input.from);
252
+ const kind = input.kind ?? 'tell';
253
+ const out = this.tx(() => {
254
+ if (input.requestId) {
255
+ const dup = this.db
256
+ .prepare(`SELECT * FROM message WHERE from_label = ? AND request_id = ?`)
257
+ .get(fromLabel, input.requestId);
258
+ if (dup)
259
+ return { id: dup.id, duplicate: true };
260
+ }
261
+ const questionId = kind === 'ask' ? newId('q') : null;
262
+ const id = this.insertMessage({
263
+ from: input.from,
264
+ fromLabel,
265
+ to: { kind: resolved.kind, target: resolved.target },
266
+ kind,
267
+ text,
268
+ origin,
269
+ relay: input.relay ?? null,
270
+ questionId,
271
+ requestId: input.requestId ?? null,
272
+ urgent: input.urgent,
273
+ });
274
+ if (questionId)
275
+ this.db
276
+ .prepare(`INSERT INTO question(id, asker_session, asker_label, message_id, to_kind, to_target, text, created_at)
277
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?)`)
278
+ .run(questionId, input.from, fromLabel, id, resolved.kind, resolved.target, text, this.now());
279
+ return { id, duplicate: false };
280
+ });
281
+ const message = this.message(out.id);
282
+ const session = resolved.kind === 'role'
283
+ ? this.roleHolder(resolved.target)
284
+ : resolved.session;
285
+ const target = session ? this.presence(session) : null;
286
+ return {
287
+ message,
288
+ question: message.questionId ? this.question(message.questionId) : null,
289
+ duplicate: out.duplicate,
290
+ target: target && target.live ? target : null,
291
+ openQuestions: session ? this.openQuestionsTo(session) : [],
292
+ };
293
+ }
294
+ /**
295
+ * Claim this session's deliverable messages for this process. A message is
296
+ * claimed by one process at a time (the same session file can be open in two),
297
+ * and a claim lapses when its process dies or its lease expires.
298
+ */
299
+ claim(sessionFile, opts = {}) {
300
+ const me = this.probe.self();
301
+ const until = this.now() + (opts.leaseMs ?? 60_000);
302
+ // The poller calls this every second in every process: take the write lock
303
+ // only when there is something to claim, or idle processes starve writers
304
+ // (measured: four processes claiming in a loop pushed a writer past
305
+ // busy_timeout).
306
+ const claimable = (m) => (!opts.ids || opts.ids.includes(m.id)) && !this.isClaimed(m);
307
+ if (!this.pendingRows(sessionFile).some(claimable))
308
+ return [];
309
+ return this.tx(() => {
310
+ const claimed = [];
311
+ for (const m of this.pendingRows(sessionFile)) {
312
+ if (!claimable(m))
313
+ continue;
314
+ this.db
315
+ .prepare(`UPDATE message SET claim_pid = ?, claim_start = ?, claim_until = ? WHERE id = ?`)
316
+ .run(me.pid, me.startTime, until, m.id);
317
+ claimed.push(this.toMessage(m));
318
+ }
319
+ return claimed;
320
+ });
321
+ }
322
+ /** Give claimed messages back (they were not injected after all). */
323
+ release(ids) {
324
+ const me = this.probe.self();
325
+ this.tx(() => {
326
+ for (const id of ids)
327
+ this.db
328
+ .prepare(`UPDATE message SET claim_pid = NULL, claim_start = NULL, claim_until = NULL WHERE id = ? AND claim_pid = ?`)
329
+ .run(id, me.pid);
330
+ });
331
+ }
332
+ /** The messages are in the receiver's transcript now. Idempotent. */
333
+ markDelivered(sessionFile, ids) {
334
+ const t = this.now();
335
+ this.tx(() => {
336
+ for (const id of ids)
337
+ this.db
338
+ .prepare(`UPDATE message SET state = 'delivered', delivered_to = ?, finished_at = ?, claim_pid = NULL, claim_until = NULL
339
+ WHERE id = ? AND state = 'pending'`)
340
+ .run(sessionFile, t, id);
341
+ });
342
+ }
343
+ supersede(from, id, text) {
344
+ const old = this.ownPending(from, id);
345
+ const sent = this.tx(() => {
346
+ const newIdValue = this.insertMessage({
347
+ from: old.from_session,
348
+ fromLabel: old.from_label,
349
+ to: { kind: old.to_kind, target: old.to_target },
350
+ kind: old.kind,
351
+ text,
352
+ origin: old.origin,
353
+ relay: old.relay ? JSON.parse(old.relay) : null,
354
+ questionId: old.question_id,
355
+ urgent: old.urgent === 1,
356
+ });
357
+ this.db
358
+ .prepare(`UPDATE message SET state = 'superseded', superseded_by = ?, finished_at = ? WHERE id = ?`)
359
+ .run(newIdValue, this.now(), id);
360
+ if (old.question_id)
361
+ this.db
362
+ .prepare(`UPDATE question SET message_id = ?, text = ? WHERE id = ?`)
363
+ .run(newIdValue, text, old.question_id);
364
+ return newIdValue;
365
+ });
366
+ return this.message(sent);
367
+ }
368
+ withdraw(from, id) {
369
+ const old = this.ownPending(from, id);
370
+ this.tx(() => {
371
+ this.db
372
+ .prepare(`UPDATE message SET state = 'withdrawn', finished_at = ? WHERE id = ?`)
373
+ .run(this.now(), id);
374
+ if (old.question_id)
375
+ this.db
376
+ .prepare(`UPDATE question SET state = 'withdrawn', finished_at = ? WHERE id = ? AND state = 'open'`)
377
+ .run(this.now(), old.question_id);
378
+ });
379
+ }
380
+ ownPending(from, id) {
381
+ const row = this.db
382
+ .prepare(`SELECT * FROM message WHERE id = ?`)
383
+ .get(id);
384
+ if (!row)
385
+ throw new ShipmatesError(`no message ${id}`, 'not-found');
386
+ if (row.from_session !== from)
387
+ throw new ShipmatesError(`message ${id} is not yours`, 'not-yours');
388
+ if (row.state !== 'pending')
389
+ throw new ShipmatesError(`message ${id} is already ${row.state}`, row.state);
390
+ if (this.isClaimed(row))
391
+ throw new ShipmatesError(`message ${id} is being delivered right now`, 'delivering');
392
+ return row;
393
+ }
394
+ /**
395
+ * Claimed by a live process whose lease has not expired, THIS process
396
+ * included: a message this process is already delivering must not be handed
397
+ * out again (measured: re-claiming returned in-flight messages twice).
398
+ */
399
+ isClaimed(m) {
400
+ if (m.claim_pid === null || m.claim_until === null)
401
+ return false;
402
+ if (m.claim_until < this.now())
403
+ return false;
404
+ const me = this.probe.self();
405
+ return this.probe.isAlive({
406
+ pid: m.claim_pid,
407
+ startTime: m.claim_start,
408
+ bootId: me.bootId,
409
+ host: me.host,
410
+ });
411
+ }
412
+ pendingRows(sessionFile) {
413
+ return this.db
414
+ .prepare(`SELECT * FROM message WHERE state = 'pending' AND (
415
+ (to_kind = 'session' AND to_target = ?) OR
416
+ (to_kind = 'role' AND to_target IN (SELECT role FROM role WHERE session_file = ?)))
417
+ ORDER BY created_at, rowid`)
418
+ .all(sessionFile, sessionFile);
419
+ }
420
+ // --------------------------------------------------------------- questions
421
+ question(id) {
422
+ const row = this.db
423
+ .prepare(`SELECT * FROM question WHERE id = ?`)
424
+ .get(id);
425
+ return row ? toQuestion(row) : null;
426
+ }
427
+ /** Open questions addressed to this session, directly or through a role it holds. */
428
+ openQuestionsTo(sessionFile) {
429
+ const rows = this.db
430
+ .prepare(`SELECT * FROM question WHERE state = 'open' AND (
431
+ (to_kind = 'session' AND to_target = ?) OR
432
+ (to_kind = 'role' AND to_target IN (SELECT role FROM role WHERE session_file = ?)))
433
+ ORDER BY created_at`)
434
+ .all(sessionFile, sessionFile);
435
+ return rows.map(toQuestion);
436
+ }
437
+ /**
438
+ * Answer a question: the only way to close one (D12). The answer is sent back
439
+ * to the asker as a message. Only the session it was asked of answers it
440
+ * (for a role, its current holder); `from: null` is a human at the CLI.
441
+ */
442
+ answer(input) {
443
+ const q = this.question(input.questionId);
444
+ if (!q)
445
+ throw new ShipmatesError(`no question ${input.questionId}`, 'not-found');
446
+ if (q.state !== 'open')
447
+ throw new ShipmatesError(`question ${q.id} is already ${q.state}`, q.state);
448
+ if (input.from !== null) {
449
+ const addressee = q.to.kind === 'session' ? q.to.target : this.roleHolder(q.to.target);
450
+ if (addressee !== input.from)
451
+ throw new ShipmatesError(`question ${q.id} was not asked of ${input.from}`, 'not-asked');
452
+ }
453
+ const origin = input.origin ?? (input.from ? 'agent' : 'human');
454
+ if (origin === 'human-relayed' && !input.relay)
455
+ throw new ShipmatesError('a human-relayed answer must carry the relay', 'no-relay');
456
+ const id = this.tx(() => {
457
+ const t = this.now();
458
+ this.db
459
+ .prepare(`UPDATE question SET state = 'answered', answer = ?, answer_origin = ?, answer_relay = ?, answered_by = ?, finished_at = ? WHERE id = ?`)
460
+ .run(input.text, origin, input.relay ? JSON.stringify(input.relay) : null, input.from ?? 'human', t, q.id);
461
+ return this.insertMessage({
462
+ from: input.from,
463
+ fromLabel: this.labelOf(input.from),
464
+ to: q.asker
465
+ ? { kind: 'session', target: q.asker }
466
+ : { kind: 'role', target: q.askerLabel },
467
+ kind: 'answer',
468
+ text: input.text,
469
+ origin,
470
+ relay: input.relay ?? null,
471
+ questionId: q.id,
472
+ });
473
+ });
474
+ return this.message(id);
475
+ }
476
+ /**
477
+ * What `session_wait` returns on (D12), or null to keep waiting: the answer;
478
+ * the target settling (idle or waiting for the human) after the wait began
479
+ * without answering; a new question addressed to the waiter (two sessions
480
+ * waiting on each other would otherwise deadlock until the timeout); or the
481
+ * question being withdrawn.
482
+ */
483
+ waitStatus(input) {
484
+ const q = this.question(input.questionId);
485
+ if (!q)
486
+ throw new ShipmatesError(`no question ${input.questionId}`, 'not-found');
487
+ if (q.state === 'answered')
488
+ return { status: 'answered', question: q };
489
+ if (q.state === 'withdrawn')
490
+ return { status: 'withdrawn', question: q };
491
+ const asked = this.openQuestionsTo(input.waiter).filter((x) => x.createdAt >= input.since);
492
+ if (asked.length)
493
+ return { status: 'asked', question: q, questions: asked };
494
+ const session = q.to.kind === 'session' ? q.to.target : this.roleHolder(q.to.target);
495
+ const target = session ? this.presence(session) : null;
496
+ if (target?.live &&
497
+ target.state !== 'running' &&
498
+ target.state !== 'waiting-for-session' &&
499
+ (target.settledAt ?? 0) > input.since)
500
+ return { status: 'settled', question: q, target };
501
+ return null;
502
+ }
503
+ // -------------------------------------------------------------- the human
504
+ /** Raise an attention item: a question for the human, in the one inbox (D13). */
505
+ humanAsk(input) {
506
+ const onBehalfOf = input.onBehalfOf ?? [];
507
+ for (const qid of onBehalfOf)
508
+ if (!this.question(qid))
509
+ throw new ShipmatesError(`onBehalfOf names no question: ${qid}`, 'not-found');
510
+ const id = newId('h');
511
+ this.tx(() => {
512
+ this.db
513
+ .prepare(`INSERT INTO item(id, session_file, question, options, blocking, on_behalf_of, created_at) VALUES(?, ?, ?, ?, ?, ?, ?)`)
514
+ .run(id, input.from, input.question, input.options?.length ? JSON.stringify(input.options) : null, input.blocking ? 1 : 0, onBehalfOf.length ? JSON.stringify(onBehalfOf) : null, this.now());
515
+ });
516
+ return this.item(id);
517
+ }
518
+ item(id) {
519
+ const row = this.db.prepare(`SELECT * FROM item WHERE id = ?`).get(id);
520
+ return row ? toItem(row) : null;
521
+ }
522
+ /** Open items, oldest first; blocking ones first of all. */
523
+ inbox() {
524
+ const rows = this.db
525
+ .prepare(`SELECT * FROM item WHERE state = 'open' ORDER BY blocking DESC, created_at`)
526
+ .all();
527
+ return rows.map(toItem);
528
+ }
529
+ /**
530
+ * The human answered an item. Callers must only call this for a real human act
531
+ * (a slash command, the CLI at a terminal, a host's authenticated UI): ADR 0003.
532
+ */
533
+ answerItem(itemId, text, opts) {
534
+ const item = this.item(itemId);
535
+ if (!item)
536
+ throw new ShipmatesError(`no item ${itemId}`, 'not-found');
537
+ if (item.state !== 'open')
538
+ throw new ShipmatesError(`item ${itemId} is already ${item.state}`, item.state);
539
+ const t = this.now();
540
+ const relay = {
541
+ text,
542
+ channel: opts.channel,
543
+ session: null,
544
+ itemId,
545
+ at: t,
546
+ };
547
+ const id = this.tx(() => {
548
+ this.db
549
+ .prepare(`UPDATE item SET state = 'answered', answer = ?, answer_channel = ?, finished_at = ? WHERE id = ?`)
550
+ .run(text, opts.channel, t, itemId);
551
+ return this.insertMessage({
552
+ from: null,
553
+ fromLabel: 'human',
554
+ to: { kind: 'session', target: item.session },
555
+ kind: 'answer',
556
+ text,
557
+ origin: 'human',
558
+ relay,
559
+ itemId,
560
+ });
561
+ });
562
+ return this.message(id);
563
+ }
564
+ withdrawItem(from, itemId) {
565
+ this.tx(() => {
566
+ this.db
567
+ .prepare(`UPDATE item SET state = 'withdrawn', finished_at = ? WHERE id = ? AND session_file = ? AND state = 'open'`)
568
+ .run(this.now(), itemId, from);
569
+ });
570
+ }
571
+ /** The human's answers to this session's items, newest first. */
572
+ humanAnswers(sessionFile) {
573
+ const rows = this.db
574
+ .prepare(`SELECT * FROM item WHERE session_file = ? AND state = 'answered' ORDER BY finished_at DESC`)
575
+ .all(sessionFile);
576
+ return rows.map(toItem);
577
+ }
578
+ /**
579
+ * Record a turn a human really typed into this session (ADR 0003): TUI input,
580
+ * or a host's `shipmates:human-input` mark. Never call this for agent text.
581
+ */
582
+ recordHumanTurn(sessionFile, input) {
583
+ const id = newId('t');
584
+ this.tx(() => {
585
+ this.db
586
+ .prepare(`INSERT INTO human_turn(id, session_file, text, channel, at) VALUES(?, ?, ?, ?, ?)`)
587
+ .run(id, sessionFile, input.text, input.channel, this.now());
588
+ });
589
+ return id;
590
+ }
591
+ /**
592
+ * Build the relay for a human-relayed message: the human's own words, found
593
+ * among this session's recent human turns (by a quote the agent gives, or the
594
+ * latest turn), or an answered inbox item of this session. An agent can carry
595
+ * a human's words; it cannot make them up.
596
+ */
597
+ relayFromHuman(sessionFile, ref) {
598
+ if (ref.itemId) {
599
+ const item = this.item(ref.itemId);
600
+ if (!item ||
601
+ item.session !== sessionFile ||
602
+ item.state !== 'answered' ||
603
+ item.answer === null)
604
+ throw new ShipmatesError(`no answered inbox item ${ref.itemId} for this session`, 'no-human-turn');
605
+ return {
606
+ text: item.answer,
607
+ channel: item.answerChannel ?? 'unknown',
608
+ session: null,
609
+ itemId: item.id,
610
+ at: this.now(),
611
+ };
612
+ }
613
+ const turns = this.db
614
+ .prepare(`SELECT * FROM human_turn WHERE session_file = ? ORDER BY at DESC, rowid DESC LIMIT 20`)
615
+ .all(sessionFile);
616
+ const norm = (x) => x.replace(/\s+/g, ' ').trim().toLowerCase();
617
+ const turn = ref.quote
618
+ ? turns.find((t) => norm(t.text).includes(norm(ref.quote)))
619
+ : turns[0];
620
+ if (!turn)
621
+ throw new ShipmatesError(ref.quote
622
+ ? `no human turn in this session contains ${JSON.stringify(ref.quote)}: only words the human typed can be relayed`
623
+ : 'no human turn in this session to relay', 'no-human-turn');
624
+ return {
625
+ text: turn.text,
626
+ channel: turn.channel,
627
+ session: sessionFile,
628
+ turnId: turn.id,
629
+ at: turn.at,
630
+ };
631
+ }
632
+ /** Open questions this session asked. */
633
+ openQuestionsFrom(sessionFile) {
634
+ const rows = this.db
635
+ .prepare(`SELECT * FROM question WHERE state = 'open' AND asker_session = ? ORDER BY created_at`)
636
+ .all(sessionFile);
637
+ return rows.map(toQuestion);
638
+ }
639
+ /** Messages this session may receive now: to it, or to a role it holds. */
640
+ pendingFor(sessionFile) {
641
+ return this.pendingRows(sessionFile).map((r) => this.toMessage(r));
642
+ }
643
+ message(id) {
644
+ const row = this.db
645
+ .prepare(`SELECT * FROM message WHERE id = ?`)
646
+ .get(id);
647
+ return row ? this.toMessage(row) : null;
648
+ }
649
+ insertMessage(m) {
650
+ const id = newId('m');
651
+ this.db
652
+ .prepare(`INSERT INTO message(id, from_session, from_label, to_kind, to_target, kind, question_id, item_id, text, origin, relay, request_id, urgent, created_at)
653
+ VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`)
654
+ .run(id, m.from, m.fromLabel, m.to.kind, m.to.target, m.kind, m.questionId ?? null, m.itemId ?? null, m.text, m.origin, m.relay ? JSON.stringify(m.relay) : null, m.requestId ?? null, m.urgent ? 1 : 0, this.now());
655
+ return id;
656
+ }
657
+ /** How a sender is named to receivers: its roles if it has any, else its file. */
658
+ labelOf(sessionFile) {
659
+ if (!sessionFile)
660
+ return 'human';
661
+ const roles = this.rolesOf(sessionFile);
662
+ return roles.length ? roles.join(',') : sessionFile;
663
+ }
664
+ toMessage(r) {
665
+ return {
666
+ id: r.id,
667
+ from: r.from_session,
668
+ fromLabel: r.from_label,
669
+ to: { kind: r.to_kind, target: r.to_target },
670
+ kind: r.kind,
671
+ questionId: r.question_id,
672
+ itemId: r.item_id,
673
+ text: r.text,
674
+ origin: r.origin,
675
+ relay: r.relay ? JSON.parse(r.relay) : null,
676
+ urgent: r.urgent === 1,
677
+ state: r.state,
678
+ supersededBy: r.superseded_by,
679
+ deliveredTo: r.delivered_to,
680
+ createdAt: r.created_at,
681
+ };
682
+ }
683
+ // --------------------------------------------------------------- ownership
684
+ /**
685
+ * Start a spawn: the ownership record exists before the new session does, so
686
+ * a terminal child can bind itself at its own `session_start` (D28). The owner
687
+ * is fixed here and never changes.
688
+ */
689
+ beginSpawn(input) {
690
+ if (input.prompt && Buffer.byteLength(input.prompt) > MAX_TEXT_BYTES)
691
+ throw new ShipmatesError(`the first prompt is over 8 KB (${Buffer.byteLength(input.prompt)} bytes): put the plan in git and point at it`, 'too-large');
692
+ if (input.role && !ROLE_RE.test(input.role))
693
+ throw new ShipmatesError(`invalid role ${JSON.stringify(input.role)}`, 'bad-role');
694
+ const id = newId('sp');
695
+ this.tx(() => {
696
+ this.db
697
+ .prepare(`INSERT INTO ownership(id, owner, folder, role, via, detail, prompt, created_at) VALUES(?, ?, ?, ?, ?, ?, ?, ?)`)
698
+ .run(id, input.owner, input.folder, input.role ?? null, input.via, input.detail ? JSON.stringify(input.detail) : null, input.prompt ?? null, this.now());
699
+ });
700
+ return this.spawnRecord(id);
701
+ }
702
+ /**
703
+ * The spawned session exists: bind it to its spawn, once, and queue its first
704
+ * prompt as a `spawn` message from the owner, origin agent (never a human
705
+ * turn, D28). Binding the same session again is a no-op; a session that is
706
+ * already owned, or a spawn bound to another session, is refused: ownership
707
+ * never changes.
708
+ */
709
+ bindSpawn(spawnId, sessionFile) {
710
+ this.tx(() => {
711
+ const row = this.db
712
+ .prepare(`SELECT * FROM ownership WHERE id = ?`)
713
+ .get(spawnId);
714
+ if (!row)
715
+ throw new ShipmatesError(`no spawn ${spawnId}`, 'not-found');
716
+ if (row.session_file === sessionFile)
717
+ return;
718
+ if (row.session_file)
719
+ throw new ShipmatesError(`spawn ${spawnId} is already ${row.session_file}`, 'owned');
720
+ const other = this.db
721
+ .prepare(`SELECT owner FROM ownership WHERE session_file = ?`)
722
+ .get(sessionFile);
723
+ if (other)
724
+ throw new ShipmatesError(`${sessionFile} is already owned by ${other.owner}; ownership never changes`, 'owned');
725
+ if (sessionFile === row.owner ||
726
+ this.ancestors(row.owner).includes(sessionFile))
727
+ throw new ShipmatesError(`${sessionFile} cannot be owned by ${row.owner}: that would be a cycle`, 'cycle');
728
+ this.db
729
+ .prepare(`UPDATE ownership SET session_file = ?, bound_at = ? WHERE id = ?`)
730
+ .run(sessionFile, this.now(), spawnId);
731
+ if (row.prompt)
732
+ this.insertMessage({
733
+ from: row.owner,
734
+ fromLabel: this.labelOf(row.owner),
735
+ to: { kind: 'session', target: sessionFile },
736
+ kind: 'spawn',
737
+ text: row.prompt,
738
+ origin: 'agent',
739
+ requestId: `spawn:${spawnId}`,
740
+ });
741
+ });
742
+ return this.spawnRecord(spawnId);
743
+ }
744
+ /** Record that `owner` owns an existing session (a host that spawned it by its own means). */
745
+ recordOwnership(input) {
746
+ const sp = this.beginSpawn(input);
747
+ try {
748
+ return this.bindSpawn(sp.id, input.session);
749
+ }
750
+ catch (e) {
751
+ this.tx(() => {
752
+ this.db.prepare(`DELETE FROM ownership WHERE id = ?`).run(sp.id);
753
+ });
754
+ throw e;
755
+ }
756
+ }
757
+ spawnRecord(spawnId) {
758
+ const row = this.db
759
+ .prepare(`SELECT * FROM ownership WHERE id = ?`)
760
+ .get(spawnId);
761
+ return row ? this.toOwnership(row) : null;
762
+ }
763
+ /** The ownership record of a session, or null when nobody spawned it. */
764
+ ownership(sessionFile) {
765
+ const row = this.db
766
+ .prepare(`SELECT * FROM ownership WHERE session_file = ?`)
767
+ .get(sessionFile);
768
+ return row ? this.toOwnership(row) : null;
769
+ }
770
+ ownerOf(sessionFile) {
771
+ return this.ownership(sessionFile)?.owner ?? null;
772
+ }
773
+ /**
774
+ * The sessions `owner` spawned, live or not, oldest first; with `transitive`,
775
+ * their own children too (depth first). Spawns that never came up are left out.
776
+ */
777
+ ownedBy(owner, opts = {}) {
778
+ const out = [];
779
+ const seen = new Set([owner]);
780
+ const walk = (o) => {
781
+ const rows = this.db
782
+ .prepare(`SELECT * FROM ownership WHERE owner = ? AND session_file IS NOT NULL ORDER BY created_at, rowid`)
783
+ .all(o);
784
+ for (const r of rows) {
785
+ if (seen.has(r.session_file))
786
+ continue;
787
+ seen.add(r.session_file);
788
+ out.push(this.toOwnership(r));
789
+ if (opts.transitive)
790
+ walk(r.session_file);
791
+ }
792
+ };
793
+ walk(owner);
794
+ return out;
795
+ }
796
+ /**
797
+ * Whether `caller` owns `target`, directly or through the sessions it owns
798
+ * (D23): an orchestrator answers for its children's children too.
799
+ */
800
+ owns(caller, target) {
801
+ return this.ancestors(target).includes(caller);
802
+ }
803
+ /** The owner, the owner's owner, and so on up. */
804
+ ancestors(sessionFile) {
805
+ const out = [];
806
+ for (let s = this.ownerOf(sessionFile); s && out.length < 64;) {
807
+ if (out.includes(s))
808
+ break;
809
+ out.push(s);
810
+ s = this.ownerOf(s);
811
+ }
812
+ return out;
813
+ }
814
+ /**
815
+ * A host archives or deletes a session: mark it and every session it owns,
816
+ * transitively, as one batch (D24). shipmates cannot touch transcripts; the host
817
+ * hides or deletes them, and must keep a deleted one until `undoUntil`.
818
+ * Sessions already archived keep their own batch.
819
+ */
820
+ archive(sessionFile, opts) {
821
+ const batch = newId('ar');
822
+ const at = this.now();
823
+ const sessions = this.tx(() => {
824
+ // Inside the transaction, so a child bound meanwhile is not missed.
825
+ const all = [
826
+ sessionFile,
827
+ ...this.ownedBy(sessionFile, { transitive: true }).map((o) => o.session),
828
+ ];
829
+ const marked = [];
830
+ for (const s of all) {
831
+ const r = this.db
832
+ .prepare(`INSERT INTO archive(session_file, kind, batch, by_label, at) VALUES(?, ?, ?, ?, ?) ON CONFLICT(session_file) DO NOTHING`)
833
+ .run(s, opts.kind, batch, opts.by, at);
834
+ if (r.changes)
835
+ marked.push(s);
836
+ }
837
+ return marked;
838
+ });
839
+ return { batch, at, undoUntil: at + ARCHIVE_UNDO_MS, sessions };
840
+ }
841
+ /** Undo a whole archive batch within its window; returns the sessions restored. */
842
+ undoArchive(batch) {
843
+ return this.tx(() => {
844
+ const rows = this.db
845
+ .prepare(`SELECT * FROM archive WHERE batch = ?`)
846
+ .all(batch);
847
+ if (!rows.length)
848
+ throw new ShipmatesError(`no archive batch ${batch}`, 'not-found');
849
+ if (rows[0].at + ARCHIVE_UNDO_MS < this.now())
850
+ throw new ShipmatesError(`archive ${batch} is past its undo window (7 days)`, 'expired');
851
+ this.db.prepare(`DELETE FROM archive WHERE batch = ?`).run(batch);
852
+ return rows.map((r) => r.session_file);
853
+ });
854
+ }
855
+ archiveMark(sessionFile) {
856
+ const row = this.db
857
+ .prepare(`SELECT * FROM archive WHERE session_file = ?`)
858
+ .get(sessionFile);
859
+ return row ? toArchive(row) : null;
860
+ }
861
+ /** Marks whose undo window has passed: a host may now make them permanent. */
862
+ expiredArchives() {
863
+ return this.db
864
+ .prepare(`SELECT * FROM archive WHERE at < ? ORDER BY at`)
865
+ .all(this.now() - ARCHIVE_UNDO_MS).map(toArchive);
866
+ }
867
+ /**
868
+ * D29: the headless children of `owner` that have messages to read which
869
+ * arrived after their last stop, and are not archived. One cached query,
870
+ * since every session's poller asks on every change. Measured: 3 µs for a
871
+ * session that owns nothing, 42 µs with 5 children and one to wake, against
872
+ * about 500 µs as separate reads per child. Liveness is left to the caller:
873
+ * it is a process probe, not SQL.
874
+ */
875
+ wakeCandidates(owner) {
876
+ const rows = this.cached(`SELECT o.* FROM ownership o
877
+ LEFT JOIN (SELECT session_file, max(at) AS at FROM stop_request GROUP BY session_file) s
878
+ ON s.session_file = o.session_file
879
+ WHERE o.owner = ? AND o.via = 'headless' AND o.session_file IS NOT NULL
880
+ AND NOT EXISTS (SELECT 1 FROM archive a WHERE a.session_file = o.session_file)
881
+ AND (EXISTS (SELECT 1 FROM message m WHERE m.state = 'pending' AND m.to_kind = 'session'
882
+ AND m.to_target = o.session_file AND m.created_at > COALESCE(s.at, -1))
883
+ OR EXISTS (SELECT 1 FROM role r JOIN message m ON m.state = 'pending' AND m.to_kind = 'role'
884
+ AND m.to_target = r.role
885
+ WHERE r.session_file = o.session_file AND m.created_at > COALESCE(s.at, -1)))
886
+ ORDER BY o.created_at`).all(owner);
887
+ return rows.map((r) => this.toOwnership(r));
888
+ }
889
+ /**
890
+ * Prepared once per connection, for the queries the poller runs on every
891
+ * change: compiling a statement is most of the cost of a small query.
892
+ */
893
+ statements = new Map();
894
+ cached(sql) {
895
+ let st = this.statements.get(sql);
896
+ if (!st)
897
+ this.statements.set(sql, (st = this.db.prepare(sql)));
898
+ return st;
899
+ }
900
+ /**
901
+ * A headless child is being woken (D29): granted to exactly one caller until
902
+ * the lease lapses, so two polls or two processes never start it twice. A
903
+ * refusal says when the current lease ends, so the caller can look again then.
904
+ */
905
+ leaseWake(sessionFile, ms) {
906
+ // Read first: a refused lease must not write. A write bumps changeToken(),
907
+ // which wakes every poller, which asks again: a write-lock loop every
908
+ // poll while the lease is held (invariant 4's reason; found in review).
909
+ const held = this.db
910
+ .prepare(`SELECT wake_until FROM ownership WHERE session_file = ?`)
911
+ .get(sessionFile);
912
+ if (!held)
913
+ return { ok: false, until: null };
914
+ if (held.wake_until != null && held.wake_until >= this.now())
915
+ return { ok: false, until: held.wake_until };
916
+ return this.tx(() => {
917
+ const t = this.now();
918
+ const r = this.db
919
+ .prepare(`UPDATE ownership SET wake_until = ? WHERE session_file = ? AND (wake_until IS NULL OR wake_until < ?)`)
920
+ .run(t + ms, sessionFile, t);
921
+ if (r.changes === 1)
922
+ return { ok: true };
923
+ const row = this.db
924
+ .prepare(`SELECT wake_until FROM ownership WHERE session_file = ?`)
925
+ .get(sessionFile);
926
+ return { ok: false, until: row?.wake_until ?? null };
927
+ });
928
+ }
929
+ /**
930
+ * The woken child is up: shorten its lease to `gapMs` from now. Once it has
931
+ * exited, the next wake may come after that gap, not before: a child that
932
+ * dies before reading its messages is retried at that pace, never in a loop.
933
+ */
934
+ wakeDone(sessionFile, gapMs) {
935
+ const until = this.now() + gapMs;
936
+ const row = this.db
937
+ .prepare(`SELECT wake_until FROM ownership WHERE session_file = ?`)
938
+ .get(sessionFile);
939
+ // No write lock for nothing (the reason behind invariant 4).
940
+ if (row?.wake_until == null || row.wake_until <= until)
941
+ return;
942
+ this.tx(() => {
943
+ this.db
944
+ .prepare(`UPDATE ownership SET wake_until = ? WHERE session_file = ? AND wake_until > ?`)
945
+ .run(until, sessionFile, until);
946
+ });
947
+ }
948
+ toOwnership(r) {
949
+ return {
950
+ id: r.id,
951
+ session: r.session_file,
952
+ owner: r.owner,
953
+ folder: r.folder,
954
+ role: r.role,
955
+ via: r.via,
956
+ detail: r.detail ? JSON.parse(r.detail) : {},
957
+ createdAt: r.created_at,
958
+ boundAt: r.bound_at,
959
+ archived: r.session_file ? this.archiveMark(r.session_file) : null,
960
+ };
961
+ }
962
+ // -------------------------------------------------------------------- stop
963
+ /**
964
+ * Ask a session to stop its current turn (D30). Its own extension acts on it
965
+ * at the next poll and records the outcome; it never cascades. Authorisation
966
+ * is the caller's job: the tool checks `owns`, the CLI that a human runs it.
967
+ */
968
+ requestStop(sessionFile, opts) {
969
+ const id = newId('s');
970
+ this.tx(() => {
971
+ this.db
972
+ .prepare(`INSERT INTO stop_request(id, session_file, by_session, by_label, at) VALUES(?, ?, ?, ?, ?)`)
973
+ .run(id, sessionFile, opts.by, this.labelOf(opts.by), this.now());
974
+ });
975
+ return this.stopRequest(id);
976
+ }
977
+ stopRequest(id) {
978
+ const row = this.db
979
+ .prepare(`SELECT * FROM stop_request WHERE id = ?`)
980
+ .get(id);
981
+ return row ? toStop(row) : null;
982
+ }
983
+ /** Stop requests this session has not acted on yet, oldest first. A read: no lock. */
984
+ openStops(sessionFile) {
985
+ return this.cached(`SELECT * FROM stop_request WHERE session_file = ? AND handled_at IS NULL ORDER BY at, rowid`).all(sessionFile).map(toStop);
986
+ }
987
+ settleStop(id, outcome) {
988
+ this.tx(() => {
989
+ this.db
990
+ .prepare(`UPDATE stop_request SET handled_at = ?, outcome = ? WHERE id = ? AND handled_at IS NULL`)
991
+ .run(this.now(), outcome, id);
992
+ });
993
+ }
994
+ /** When this session was last asked to stop, or null. */
995
+ lastStopAt(sessionFile) {
996
+ const row = this.db
997
+ .prepare(`SELECT max(at) AS at FROM stop_request WHERE session_file = ?`)
998
+ .get(sessionFile);
999
+ return row.at;
1000
+ }
1001
+ // --------------------------------------------------------------- retention
1002
+ /**
1003
+ * D11: finished messages, questions and items go after 30 days (the receiver's
1004
+ * transcript keeps every delivered message for good); presence of a dead process
1005
+ * after a day. Pending messages and open questions are never pruned by age.
1006
+ */
1007
+ prune() {
1008
+ const t = this.now();
1009
+ const finished = t - 30 * DAY;
1010
+ const dead = this.db
1011
+ .prepare(`SELECT * FROM presence WHERE updated_at < ?`)
1012
+ .all(t - DAY);
1013
+ this.tx(() => {
1014
+ this.db
1015
+ .prepare(`DELETE FROM message WHERE state != 'pending' AND finished_at < ?`)
1016
+ .run(finished);
1017
+ this.db
1018
+ .prepare(`DELETE FROM question WHERE state != 'open' AND finished_at < ?`)
1019
+ .run(finished);
1020
+ this.db
1021
+ .prepare(`DELETE FROM item WHERE state != 'open' AND finished_at < ?`)
1022
+ .run(finished);
1023
+ this.db.prepare(`DELETE FROM human_turn WHERE at < ?`).run(finished);
1024
+ this.db
1025
+ .prepare(`DELETE FROM stop_request WHERE handled_at IS NOT NULL AND handled_at < ?`)
1026
+ .run(finished);
1027
+ this.pruneOwnership(t);
1028
+ for (const row of dead)
1029
+ if (!this.probe.isAlive(this.identityOf(row)))
1030
+ this.db
1031
+ .prepare(`DELETE FROM presence WHERE session_file = ? AND pid = ?`)
1032
+ .run(row.session_file, row.pid);
1033
+ this.db
1034
+ .prepare(`INSERT OR REPLACE INTO meta(key, value) VALUES('last_prune', ?)`)
1035
+ .run(String(t));
1036
+ });
1037
+ }
1038
+ /**
1039
+ * D25: ownership is never pruned while its session exists. A spawn that never
1040
+ * came up goes after a day. A bound record goes only when its transcript file
1041
+ * is gone, nobody runs it, and it is over 30 days old (pi writes a transcript
1042
+ * only after the first assistant message, so a missing file alone proves
1043
+ * nothing about a fresh session). An archive mark goes with its transcript,
1044
+ * once the undo window has passed. Called inside prune's transaction.
1045
+ */
1046
+ pruneOwnership(t) {
1047
+ this.db
1048
+ .prepare(`DELETE FROM ownership WHERE session_file IS NULL AND created_at < ?`)
1049
+ .run(t - DAY);
1050
+ const old = this.db
1051
+ .prepare(`SELECT session_file FROM ownership WHERE session_file IS NOT NULL AND bound_at < ?`)
1052
+ .all(t - 30 * DAY);
1053
+ for (const { session_file } of old)
1054
+ if (!fs.existsSync(session_file) && !this.isLive(session_file))
1055
+ this.db
1056
+ .prepare(`DELETE FROM ownership WHERE session_file = ?`)
1057
+ .run(session_file);
1058
+ const marks = this.db
1059
+ .prepare(`SELECT session_file FROM archive WHERE at < ?`)
1060
+ .all(t - Math.max(ARCHIVE_UNDO_MS, 30 * DAY));
1061
+ for (const { session_file } of marks)
1062
+ if (!fs.existsSync(session_file))
1063
+ this.db
1064
+ .prepare(`DELETE FROM archive WHERE session_file = ?`)
1065
+ .run(session_file);
1066
+ }
1067
+ /** Prune when the last prune is a day old. Cheap enough to call on every open. */
1068
+ pruneIfDue() {
1069
+ const row = this.db
1070
+ .prepare(`SELECT value FROM meta WHERE key = 'last_prune'`)
1071
+ .get();
1072
+ if (row && Number(row.value) > this.now() - DAY)
1073
+ return false;
1074
+ this.prune();
1075
+ return true;
1076
+ }
1077
+ identityOf(row) {
1078
+ return {
1079
+ pid: row.pid,
1080
+ startTime: row.start_time,
1081
+ bootId: row.boot_id,
1082
+ host: row.host ?? '',
1083
+ };
1084
+ }
1085
+ rolesOf(sessionFile) {
1086
+ return this.db
1087
+ .prepare(`SELECT role FROM role WHERE session_file = ? ORDER BY role`)
1088
+ .all(sessionFile).map((r) => r.role);
1089
+ }
1090
+ toPresence(r) {
1091
+ return {
1092
+ sessionFile: r.session_file,
1093
+ sessionId: r.session_id,
1094
+ cwd: r.cwd,
1095
+ branch: r.branch,
1096
+ roles: this.rolesOf(r.session_file),
1097
+ state: r.state,
1098
+ status: r.status,
1099
+ refs: r.refs ? JSON.parse(r.refs) : [],
1100
+ waitingOn: r.waiting_on,
1101
+ wake: r.wake === 1,
1102
+ live: this.probe.isAlive(this.identityOf(r)),
1103
+ pid: r.pid,
1104
+ updatedAt: r.updated_at,
1105
+ settledAt: r.settled_at,
1106
+ };
1107
+ }
1108
+ }
1109
+ export function openShipmates(opts = {}) {
1110
+ return new Shipmates(opts);
1111
+ }
1112
+ //# sourceMappingURL=shipmates.js.map