@astrosheep/keiyaku 4.5.12 → 4.5.13

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 (42) hide show
  1. package/build/src/akuma/akuma-errors.d.ts +1 -0
  2. package/build/src/akuma/akuma-errors.js +1 -0
  3. package/build/src/akuma/body.js +65 -3
  4. package/build/src/akuma/heart/facts.d.ts +18 -0
  5. package/build/src/akuma/heart/facts.js +7 -0
  6. package/build/src/akuma/heart/index.d.ts +18 -3
  7. package/build/src/akuma/heart/index.js +48 -6
  8. package/build/src/akuma/heart/rows.d.ts +4 -1
  9. package/build/src/akuma/heart/rows.js +46 -19
  10. package/build/src/akuma/heart/schema.d.ts +1 -1
  11. package/build/src/akuma/heart/schema.js +18 -5
  12. package/build/src/akuma/heart/storage.d.ts +1 -1
  13. package/build/src/akuma/heart/tells.d.ts +7 -0
  14. package/build/src/akuma/heart/tells.js +48 -5
  15. package/build/src/akuma/heart/timeline.js +9 -3
  16. package/build/src/akuma/projection.js +3 -3
  17. package/build/src/akuma/provider.d.ts +1 -0
  18. package/build/src/akuma/providers/claude/index.js +3 -0
  19. package/build/src/akuma/providers/codex-app-server/index.js +1 -0
  20. package/build/src/akuma/providers/pi/index.js +7 -1
  21. package/build/src/akuma/turn-drive.d.ts +1 -0
  22. package/build/src/akuma/turn-drive.js +21 -7
  23. package/build/src/kanshi/read.js +17 -1
  24. package/build/src/kanshi/select.js +14 -1
  25. package/build/src/library/contract-forwarding.d.ts +2 -2
  26. package/build/src/library/contract-operations.d.ts +1 -1
  27. package/build/src/library/contract-operations.js +2 -2
  28. package/build/src/library/mutation.d.ts +360 -3
  29. package/build/src/library/mutation.js +22 -0
  30. package/build/src/library/refusal.d.ts +2 -0
  31. package/build/src/library/refusal.js +22 -0
  32. package/build/src/library/region.d.ts +0 -8
  33. package/build/src/library/region.js +1 -29
  34. package/build/src/protocol/audit.d.ts +1 -1
  35. package/build/src/protocol/audit.js +1 -0
  36. package/build/src/protocol/deliver.d.ts +1 -1
  37. package/build/src/protocol/deliver.js +1 -0
  38. package/build/src/protocol/review.d.ts +1 -1
  39. package/build/src/protocol/review.js +1 -0
  40. package/package.json +2 -2
  41. package/build/src/library/contract-forwarding-result.d.ts +0 -359
  42. package/build/src/library/contract-forwarding-result.js +0 -44
@@ -1,4 +1,5 @@
1
1
  import type { AkuId } from "./identity.js";
2
+ export { AkumaBusyError } from "./heart/facts.js";
2
3
  export declare class AkumaNotBornError extends Error {
3
4
  readonly id: AkuId;
4
5
  readonly kind = "akuma-not-born";
@@ -1,3 +1,4 @@
1
+ export { AkumaBusyError } from "./heart/facts.js";
1
2
  export class AkumaNotBornError extends Error {
2
3
  id;
3
4
  kind = "akuma-not-born";
@@ -3,7 +3,7 @@ import { fileURLToPath } from "node:url";
3
3
  import { abortableDelay } from "./abort.js";
4
4
  import { BodySupervisor } from "./body-supervisor.js";
5
5
  import { driveTurn, turnRecipe } from "./turn-drive.js";
6
- import { HeldAkumaLeash, breakBody, decidePendingTellDisposition, endTurn, finishBodyIfIdle, heartExists, isHeartAbsent, probeLeash, projectTell, provePendingTellDispositionCustody, readHeart, readOpenPendingTellDisposition, readTell, readNonterminalRequests, recordUndeliveredPendingTells, resolvePendingTellDisposition, } from "./heart/index.js";
6
+ import { HeldAkumaLeash, breakBody, decidePendingTellDisposition, drainPendingTells, endTurn, failOpenBoundTurns, finishBodyIfIdle, heartExists, isHeartAbsent, probeLeash, projectTell, provePendingTellDispositionCustody, readHeart, readOpenPendingTellDisposition, readTell, readTurn, readNonterminalRequests, recordUndeliveredPendingTells, resolvePendingTellDisposition, } from "./heart/index.js";
7
7
  import { worldRootForAkumaPaths } from "./identity.js";
8
8
  import { pluginRuntime } from "../plugin/runtime.js";
9
9
  import { World } from "../world.js";
@@ -17,8 +17,14 @@ export { CONTROL_RESPONSE_MS } from "./body-supervisor.js";
17
17
  function missing(error) {
18
18
  return isHeartAbsent(error) || error.code === "ENOENT";
19
19
  }
20
+ async function failOpenBoundTurnsIfPresent(paths, bodySequence, diagnostic, at) {
21
+ if (!(await heartExists(paths)))
22
+ return;
23
+ await failOpenBoundTurns(paths, { bodySequence, diagnostic, completedAt: at });
24
+ }
20
25
  async function putDownIfControlled(paths, supervisor, bodySequence, now) {
21
26
  if (supervisor.reason === "control" && (await heartExists(paths))) {
27
+ await failOpenBoundTurnsIfPresent(paths, bodySequence, "Body put-down with open bound Turns", now());
22
28
  await breakBody(paths, { sequence: bodySequence, end: "put-down", at: now() });
23
29
  }
24
30
  }
@@ -62,8 +68,48 @@ async function launchCwd(launch) {
62
68
  throw new Error("Akuma wake has no born soul");
63
69
  return (await turnRecipe(launch.paths, soul)).cwd;
64
70
  }
71
+ function parseSchemaAnswerJson(raw) {
72
+ try {
73
+ JSON.parse(raw);
74
+ return { kind: "json", json: raw };
75
+ }
76
+ catch (error) {
77
+ return {
78
+ kind: "invalid",
79
+ diagnostic: error instanceof Error ? error.message : "Answer is not valid JSON",
80
+ };
81
+ }
82
+ }
65
83
  async function persistTurn(paths, turnSequence, result, completedAt) {
84
+ const turn = await readTurn(paths, turnSequence);
85
+ const schemaJson = turn?.schemaJson;
66
86
  if (result.kind === "answered" && result.session !== undefined) {
87
+ if (schemaJson !== undefined) {
88
+ const parsed = parseSchemaAnswerJson(result.answer);
89
+ if (parsed.kind === "invalid") {
90
+ const outcome = {
91
+ kind: "invalid-output",
92
+ diagnostic: parsed.diagnostic,
93
+ answer: result.answer,
94
+ session: result.session,
95
+ ...(result.historyId === undefined ? {} : { historyId: result.historyId }),
96
+ };
97
+ await endTurn(paths, { turnSequence, outcome, completedAt });
98
+ return { outcome: "failed", diagnostic: parsed.diagnostic };
99
+ }
100
+ await endTurn(paths, {
101
+ turnSequence,
102
+ outcome: {
103
+ kind: "answered",
104
+ session: result.session,
105
+ answer: result.answer,
106
+ answerJson: parsed.json,
107
+ ...(result.historyId === undefined ? {} : { historyId: result.historyId }),
108
+ },
109
+ completedAt,
110
+ });
111
+ return { outcome: "answered", answer: result.answer };
112
+ }
67
113
  await endTurn(paths, {
68
114
  turnSequence,
69
115
  outcome: {
@@ -178,7 +224,7 @@ async function runBodyTurns(input) {
178
224
  let initial = launch.initialBody;
179
225
  const emitTurnOutcome = turnOutcomeEmitter(launch, soul);
180
226
  for (;;) {
181
- const launchTells = supervisor.current().pending;
227
+ const launchTells = drainPendingTells(supervisor.current().pending);
182
228
  if (supervisor.signal.aborted) {
183
229
  await putDownIfControlled(launch.paths, supervisor, bodySequence, runtime.now);
184
230
  return;
@@ -203,12 +249,17 @@ async function runBodyTurns(input) {
203
249
  body: initial ?? "",
204
250
  ...(initial === undefined ? {} : { call: initial }),
205
251
  launchTells,
252
+ ...(launchTells.find((tell) => tell.schemaJson !== undefined)?.schemaJson === undefined
253
+ ? {}
254
+ : { schemaJson: launchTells.find((tell) => tell.schemaJson !== undefined).schemaJson }),
206
255
  world: runtime.world,
207
256
  externalCommands: runtime.externalCommands,
208
257
  now: runtime.now,
209
258
  });
210
- if (result.kind === "hung")
259
+ if (result.kind === "hung") {
260
+ await failOpenBoundTurnsIfPresent(launch.paths, bodySequence, "Body hung with open bound Turns", runtime.now());
211
261
  return;
262
+ }
212
263
  if (result.kind === "stopped") {
213
264
  await putDownIfControlled(launch.paths, supervisor, bodySequence, runtime.now);
214
265
  return;
@@ -216,12 +267,14 @@ async function runBodyTurns(input) {
216
267
  if (result.kind === "handoff")
217
268
  return "handoff";
218
269
  if (result.kind === "resume-unsupported") {
270
+ await failOpenBoundTurnsIfPresent(launch.paths, bodySequence, "resume-unsupported with open bound Turns", runtime.now());
219
271
  await breakBody(launch.paths, { sequence: bodySequence, end: "broke-off", at: runtime.now() });
220
272
  return;
221
273
  }
222
274
  const outcome = await persistTurn(launch.paths, result.turnSequence, result, runtime.now());
223
275
  emitTurnOutcome(result.turnSequence, outcome);
224
276
  if (outcome.outcome === "failed") {
277
+ await failOpenBoundTurnsIfPresent(launch.paths, bodySequence, outcome.diagnostic, runtime.now());
225
278
  await breakBody(launch.paths, { sequence: bodySequence, end: "broke-off", at: runtime.now() });
226
279
  return;
227
280
  }
@@ -378,6 +431,15 @@ export async function driveAkumaBody(launch, adapter, runtimeInput = {}) {
378
431
  }
379
432
  finally {
380
433
  if (bodySequence !== undefined && (await heartExists(launch.paths))) {
434
+ const body = (await readHeart(launch.paths)).latestBody;
435
+ const inert = body?.sequence === bodySequence && (body.end !== undefined || body.hung !== undefined);
436
+ if (inert) {
437
+ await failOpenBoundTurns(launch.paths, {
438
+ bodySequence,
439
+ diagnostic: body.hung?.diagnostic ?? `Body ${body.end ?? "ended"} with open bound Turns`,
440
+ completedAt: runtime.now(),
441
+ });
442
+ }
381
443
  decidedDisposition = await decidePendingTellDisposition(launch.paths, {
382
444
  bodySequence,
383
445
  at: runtime.now(),
@@ -58,15 +58,23 @@ export type TurnOutcome = Readonly<{
58
58
  historyId?: string;
59
59
  session: ResumeCoordinate;
60
60
  answer: string;
61
+ answerJson?: string;
61
62
  }> | Readonly<{
62
63
  kind: "failed";
63
64
  diagnostic: string;
65
+ }> | Readonly<{
66
+ kind: "invalid-output";
67
+ diagnostic: string;
68
+ answer: string;
69
+ historyId?: string;
70
+ session?: ResumeCoordinate;
64
71
  }>;
65
72
  export type TurnStartFact = Readonly<{
66
73
  kind: "turn-start";
67
74
  sequence: number;
68
75
  bodySequence: number;
69
76
  startedAt: string;
77
+ schemaJson?: string;
70
78
  }>;
71
79
  export type TurnEndFact = Readonly<{
72
80
  kind: "turn-end";
@@ -91,14 +99,20 @@ export type TellDelivery = Readonly<{
91
99
  receipt?: "unavailable" | "required";
92
100
  deliveredAt: string;
93
101
  }>;
102
+ export type TellBinding = Readonly<{
103
+ turnSequence: number;
104
+ boundAt: string;
105
+ }>;
94
106
  export type TellFact = Readonly<{
95
107
  kind: "tell";
96
108
  sequence: number;
97
109
  id: string;
98
110
  body: string;
111
+ schemaJson?: string;
99
112
  recordedAt: string;
100
113
  state: "pending" | "told";
101
114
  deliveries: readonly TellDelivery[];
115
+ binding?: TellBinding;
102
116
  }>;
103
117
  export type TellRow = Readonly<{
104
118
  kind: "tell";
@@ -110,6 +124,10 @@ export type TellRow = Readonly<{
110
124
  deliveries: readonly TellDelivery[];
111
125
  }>;
112
126
  export declare function projectTell(fact: TellFact): TellRow;
127
+ export declare class AkumaBusyError extends Error {
128
+ readonly kind = "akuma-busy";
129
+ constructor();
130
+ }
113
131
  export type TellDeliveryInput = Readonly<{
114
132
  tellId: string;
115
133
  turnSequence: number;
@@ -9,6 +9,13 @@ export function projectTell(fact) {
9
9
  deliveries: fact.deliveries,
10
10
  };
11
11
  }
12
+ export class AkumaBusyError extends Error {
13
+ kind = "akuma-busy";
14
+ constructor() {
15
+ super("Akuma is busy");
16
+ this.name = "AkumaBusyError";
17
+ }
18
+ }
12
19
  export function life(input) {
13
20
  if (input.body?.hung !== undefined)
14
21
  return "hung";
@@ -5,8 +5,9 @@ import type { ActivityFact } from "./rows.js";
5
5
  import { type ActivityFactSlice } from "./timeline.js";
6
6
  export { HeartAbsentError, HeldAkumaLeash, classifyHeartSchema, initializeHeart, isHeartAbsent, probeLeash, } from "./storage.js";
7
7
  export { admitRequest, beginRequest, isRequestInputConflict, readNonterminalRequests, readRequest, refuseRequest, reserveRequest, serveRequest, serveUpstreamRequest, unproveRequest, voidRequest, } from "./request-authority.js";
8
- export { life, lifeAt, projectTell } from "./facts.js";
9
- export type { AkumaLife, AkumaOrigin, BodyEnd, BodyFact, HeartSnapshot, ForkPoint, KillEvidence, KillFact, LeashProbe, PauseFact, RequestFact, RequestInput, RequestRecipe, SealFact, SessionFact, Soul, StopFact, TellFact, TellRow, TellDelivery, TellDeliveryInput, TellReceiptInput, TurnEndFact, TurnFact, TurnOutcome, TurnStartFact, } from "./facts.js";
8
+ export { AkumaBusyError, life, lifeAt, projectTell } from "./facts.js";
9
+ export { drainPendingTells } from "./tells.js";
10
+ export type { AkumaLife, AkumaOrigin, BodyEnd, BodyFact, HeartSnapshot, ForkPoint, KillEvidence, KillFact, LeashProbe, PauseFact, RequestFact, RequestInput, RequestRecipe, SealFact, SessionFact, Soul, StopFact, TellBinding, TellFact, TellRow, TellDelivery, TellDeliveryInput, TellReceiptInput, TurnEndFact, TurnFact, TurnOutcome, TurnStartFact, } from "./facts.js";
10
11
  export type { ResumeCoordinate } from "../coordinate.js";
11
12
  export declare function readSoul(paths: AkumaPaths): Promise<Soul | null>;
12
13
  export declare function heartExists(paths: AkumaPaths): Promise<boolean>;
@@ -21,7 +22,9 @@ export type ActivitySlice = ActivityFactSlice;
21
22
  export type { ActivityFact };
22
23
  export type { TimelineFact } from "./timeline.js";
23
24
  export declare function activitySlice(paths: AkumaPaths): Promise<ActivitySlice>;
24
- export declare function recordTell(paths: AkumaPaths, tell: Omit<TellFact, "sequence" | "state" | "deliveries">): Promise<Readonly<{
25
+ export declare function recordTell(paths: AkumaPaths, tell: Omit<TellFact, "sequence" | "state" | "deliveries" | "binding">, options?: Readonly<{
26
+ interrupt?: boolean;
27
+ }>): Promise<Readonly<{
25
28
  kind: "not-born";
26
29
  } | {
27
30
  kind: "recorded";
@@ -79,7 +82,19 @@ export declare function beginTurn(paths: AkumaPaths, input: Readonly<{
79
82
  bodySequence: number;
80
83
  startedAt: string;
81
84
  call?: string;
85
+ schemaJson?: string;
82
86
  }>): Promise<TurnStartFact>;
87
+ export declare function bindTellsToTurn(paths: AkumaPaths, input: Readonly<{
88
+ turnSequence: number;
89
+ tellIds: readonly string[];
90
+ boundAt: string;
91
+ }>): Promise<void>;
92
+ export declare function failOpenBoundTurns(paths: AkumaPaths, input: Readonly<{
93
+ bodySequence: number;
94
+ diagnostic: string;
95
+ completedAt: string;
96
+ }>): Promise<readonly number[]>;
97
+ export declare function readTurn(paths: AkumaPaths, sequence: number): Promise<TurnFact | null>;
83
98
  export declare function endTurn(paths: AkumaPaths, input: Readonly<{
84
99
  turnSequence: number;
85
100
  outcome: TurnOutcome;
@@ -1,12 +1,14 @@
1
1
  import { parsePublicHistoryId } from "../identity.js";
2
- import { answeredTurnFact, endBodyFact, finishBodyFact, insertActivityFact, insertTurnEndFact, insertTurnStartFact, insertPauseControl, insertSessionFact, insertStopControl, killFactForBody, latestBodyFact, latestKillFact, latestSessionFact, lastAnsweredTurnFact, pauseFact, sessionFactForCoordinate, stopFact, } from "./rows.js";
3
- import { insertTellDeliveryFact, dispositionSnapshotProven, insertTellDispositionSnapshot, insertTellFact, insertTellReceiptFact, insertUndeliveredTellReceipts, latestOpenTellDisposition, openTellDispositionIds, pendingTellFacts, resolveTellDispositionSnapshot, successorBodyHoldingDisposition, tellFact, tellIdsForFence, } from "./tells.js";
2
+ import { answeredTurnFact, decodeTurnRow, endBodyFact, finishBodyFact, insertActivityFact, insertTurnEndFact, insertTurnStartFact, insertPauseControl, insertSessionFact, insertStopControl, killFactForBody, latestBodyFact, latestKillFact, latestSessionFact, lastAnsweredTurnFact, pauseFact, sessionFactForCoordinate, stopFact, } from "./rows.js";
3
+ import { insertTellDeliveryFact, dispositionSnapshotProven, insertTellBindingFact, insertTellDispositionSnapshot, insertTellFact, insertTellReceiptFact, insertUndeliveredTellReceipts, latestOpenTellDisposition, openBoundTurns, openTellDispositionIds, pendingTellFacts, resolveTellDispositionSnapshot, successorBodyHoldingDisposition, tellFact, tellIdsForFence, } from "./tells.js";
4
4
  import { activityFactSlice, lastActivityAt as readLastActivityAt, pruneActivityFacts, } from "./timeline.js";
5
5
  import { isHeartAbsent, readSealFromLeash, readTransaction, transaction, withHeart, withReadOnlyHeart, } from "./storage.js";
6
6
  import { soulFact } from "./soul.js";
7
+ import { AkumaBusyError } from "./facts.js";
7
8
  export { HeartAbsentError, HeldAkumaLeash, classifyHeartSchema, initializeHeart, isHeartAbsent, probeLeash, } from "./storage.js";
8
9
  export { admitRequest, beginRequest, isRequestInputConflict, readNonterminalRequests, readRequest, refuseRequest, reserveRequest, serveRequest, serveUpstreamRequest, unproveRequest, voidRequest, } from "./request-authority.js";
9
- export { life, lifeAt, projectTell } from "./facts.js";
10
+ export { AkumaBusyError, life, lifeAt, projectTell } from "./facts.js";
11
+ export { drainPendingTells } from "./tells.js";
10
12
  const ACTIVITY_LIMIT = 5_000;
11
13
  export async function readSoul(paths) {
12
14
  try {
@@ -51,17 +53,23 @@ export async function appendActivity(paths, input) {
51
53
  export async function activitySlice(paths) {
52
54
  return await withHeart(paths, (heart) => readTransaction(heart, () => activityFactSlice(heart)));
53
55
  }
54
- export async function recordTell(paths, tell) {
56
+ function sameTellInput(existing, tell) {
57
+ return existing.body === tell.body && existing.recordedAt === tell.recordedAt && existing.schemaJson === tell.schemaJson;
58
+ }
59
+ export async function recordTell(paths, tell, options = {}) {
55
60
  return await withHeart(paths, (heart) => transaction(heart, () => {
56
61
  if (soulFact(heart) === null)
57
62
  return { kind: "not-born" };
58
63
  const existing = tellFact(heart, tell.id);
59
64
  if (existing !== null) {
60
- if (existing.body !== tell.body || existing.recordedAt !== tell.recordedAt) {
65
+ if (!sameTellInput(existing, tell))
61
66
  throw new Error(`tell ${tell.id} reused different input`);
62
- }
63
67
  return { kind: "recorded", tell: existing };
64
68
  }
69
+ const body = latestBodyFact(heart);
70
+ const running = body !== null && body.end === undefined && body.hung === undefined;
71
+ if (tell.schemaJson !== undefined && running && options.interrupt !== true)
72
+ throw new AkumaBusyError();
65
73
  const sequence = insertTellFact(heart, tell);
66
74
  pruneActivityFacts(heart, ACTIVITY_LIMIT);
67
75
  return { kind: "recorded", tell: { sequence, ...tell, state: "pending", deliveries: [] } };
@@ -202,6 +210,40 @@ export async function beginTurn(paths, input) {
202
210
  return fact;
203
211
  }));
204
212
  }
213
+ export async function bindTellsToTurn(paths, input) {
214
+ await withHeart(paths, (heart) => transaction(heart, () => {
215
+ for (const tellId of input.tellIds) {
216
+ if (tellFact(heart, tellId) === null)
217
+ throw new Error(`unknown tell ${tellId}`);
218
+ insertTellBindingFact(heart, { tellId, turnSequence: input.turnSequence, boundAt: input.boundAt });
219
+ }
220
+ pruneActivityFacts(heart, ACTIVITY_LIMIT);
221
+ }));
222
+ }
223
+ export async function failOpenBoundTurns(paths, input) {
224
+ return await withHeart(paths, (heart) => transaction(heart, () => {
225
+ const sequences = openBoundTurns(heart, input.bodySequence);
226
+ for (const turnSequence of sequences) {
227
+ insertTurnEndFact(heart, {
228
+ kind: "turn-end",
229
+ turnSequence,
230
+ outcome: { kind: "failed", diagnostic: input.diagnostic },
231
+ completedAt: input.completedAt,
232
+ });
233
+ }
234
+ pruneActivityFacts(heart, ACTIVITY_LIMIT);
235
+ return sequences;
236
+ }));
237
+ }
238
+ export async function readTurn(paths, sequence) {
239
+ return await withHeart(paths, (heart) => readTransaction(heart, () => {
240
+ const row = heart
241
+ .prepare(`SELECT sequence, body_sequence, started_at, end_sequence, outcome, history_id,
242
+ session_json, answer, answer_json, schema_json, diagnostic, completed_at FROM turns WHERE sequence = ?`)
243
+ .get(sequence);
244
+ return row === undefined ? null : decodeTurnRow(row);
245
+ }));
246
+ }
205
247
  export async function endTurn(paths, input) {
206
248
  return await withHeart(paths, (heart) => transaction(heart, () => {
207
249
  const fact = insertTurnEndFact(heart, { kind: "turn-end", ...input });
@@ -25,10 +25,12 @@ export type TurnRow = Readonly<{
25
25
  body_sequence: number;
26
26
  started_at: string;
27
27
  end_sequence: number | null;
28
- outcome: "answered" | "failed" | null;
28
+ outcome: "answered" | "failed" | "invalid-output" | null;
29
29
  history_id: string | null;
30
30
  session_json: string | null;
31
31
  answer: string | null;
32
+ answer_json: string | null;
33
+ schema_json: string | null;
32
34
  diagnostic: string | null;
33
35
  completed_at: string | null;
34
36
  }>;
@@ -104,6 +106,7 @@ export declare function insertTurnStartFact(database: DatabaseSync, input: Reado
104
106
  bodySequence: number;
105
107
  startedAt: string;
106
108
  call?: string;
109
+ schemaJson?: string;
107
110
  }>): TurnStartFact;
108
111
  export declare function insertTurnEndFact(database: DatabaseSync, input: Omit<TurnEndFact, "sequence">): TurnEndFact;
109
112
  export declare function finishBodyFact(database: DatabaseSync, input: Readonly<{
@@ -44,12 +44,34 @@ export function decodeBodyRow(row) {
44
44
  ...(row.ended_at === null ? {} : { endedAt: row.ended_at }),
45
45
  };
46
46
  }
47
+ function decodeTurnOutcome(row) {
48
+ if (row.outcome === "answered") {
49
+ return {
50
+ kind: "answered",
51
+ ...(row.history_id === null ? {} : { historyId: row.history_id }),
52
+ session: resumeCoordinate(parsed(row.session_json)),
53
+ answer: row.answer,
54
+ ...(row.answer_json === null ? {} : { answerJson: row.answer_json }),
55
+ };
56
+ }
57
+ if (row.outcome === "invalid-output") {
58
+ return {
59
+ kind: "invalid-output",
60
+ diagnostic: row.diagnostic,
61
+ answer: row.answer,
62
+ ...(row.history_id === null ? {} : { historyId: row.history_id }),
63
+ ...(row.session_json === null ? {} : { session: resumeCoordinate(parsed(row.session_json)) }),
64
+ };
65
+ }
66
+ return { kind: "failed", diagnostic: row.diagnostic };
67
+ }
47
68
  export function decodeTurnRow(row) {
48
69
  const start = {
49
70
  kind: "turn-start",
50
71
  sequence: row.sequence,
51
72
  bodySequence: row.body_sequence,
52
73
  startedAt: row.started_at,
74
+ ...(row.schema_json === null || row.schema_json === undefined ? {} : { schemaJson: row.schema_json }),
53
75
  };
54
76
  if (row.outcome === null)
55
77
  return start;
@@ -57,14 +79,7 @@ export function decodeTurnRow(row) {
57
79
  kind: "turn-end",
58
80
  sequence: row.end_sequence,
59
81
  turnSequence: row.sequence,
60
- outcome: row.outcome === "answered"
61
- ? {
62
- kind: "answered",
63
- ...(row.history_id === null ? {} : { historyId: row.history_id }),
64
- session: resumeCoordinate(parsed(row.session_json)),
65
- answer: row.answer,
66
- }
67
- : { kind: "failed", diagnostic: row.diagnostic },
82
+ outcome: decodeTurnOutcome(row),
68
83
  completedAt: row.completed_at,
69
84
  };
70
85
  return { ...start, end };
@@ -177,27 +192,39 @@ export function markBodyHung(database, input) {
177
192
  export function insertTurnStartFact(database, input) {
178
193
  const sequence = Number(database.prepare("INSERT INTO timeline(kind) VALUES ('turn-start')").run().lastInsertRowid);
179
194
  database
180
- .prepare("INSERT INTO turns(sequence, body_sequence, started_at) VALUES (?, ?, ?)")
181
- .run(sequence, input.bodySequence, input.startedAt);
195
+ .prepare("INSERT INTO turns(sequence, body_sequence, started_at, schema_json) VALUES (?, ?, ?, ?)")
196
+ .run(sequence, input.bodySequence, input.startedAt, input.schemaJson ?? null);
182
197
  if (input.call !== undefined) {
183
198
  const callSequence = Number(database.prepare("INSERT INTO timeline(kind) VALUES ('call')").run().lastInsertRowid);
184
199
  database
185
200
  .prepare("INSERT INTO calls(sequence, turn_sequence, body, at) VALUES (?, ?, ?, ?)")
186
201
  .run(callSequence, sequence, input.call, input.startedAt);
187
202
  }
188
- return { kind: "turn-start", sequence, bodySequence: input.bodySequence, startedAt: input.startedAt };
203
+ return {
204
+ kind: "turn-start",
205
+ sequence,
206
+ bodySequence: input.bodySequence,
207
+ startedAt: input.startedAt,
208
+ ...(input.schemaJson === undefined ? {} : { schemaJson: input.schemaJson }),
209
+ };
189
210
  }
190
211
  export function insertTurnEndFact(database, input) {
191
212
  const sequence = Number(database.prepare("INSERT INTO timeline(kind) VALUES ('turn-end')").run().lastInsertRowid);
192
213
  const result = input.outcome.kind === "answered"
193
214
  ? database
194
215
  .prepare(`UPDATE turns SET end_sequence = ?, outcome = 'answered', history_id = ?,
195
- session_json = ?, answer = ?, completed_at = ? WHERE sequence = ? AND end_sequence IS NULL`)
196
- .run(sequence, input.outcome.historyId ?? null, encodeResumeCoordinate(input.outcome.session), input.outcome.answer, input.completedAt, input.turnSequence)
197
- : database
198
- .prepare(`UPDATE turns SET end_sequence = ?, outcome = 'failed', diagnostic = ?, completed_at = ?
199
- WHERE sequence = ? AND end_sequence IS NULL`)
200
- .run(sequence, input.outcome.diagnostic, input.completedAt, input.turnSequence);
216
+ session_json = ?, answer = ?, answer_json = ?, completed_at = ? WHERE sequence = ? AND end_sequence IS NULL`)
217
+ .run(sequence, input.outcome.historyId ?? null, encodeResumeCoordinate(input.outcome.session), input.outcome.answer, input.outcome.answerJson ?? null, input.completedAt, input.turnSequence)
218
+ : input.outcome.kind === "invalid-output"
219
+ ? database
220
+ .prepare(`UPDATE turns SET end_sequence = ?, outcome = 'invalid-output', history_id = ?,
221
+ session_json = ?, answer = ?, diagnostic = ?, completed_at = ?
222
+ WHERE sequence = ? AND end_sequence IS NULL`)
223
+ .run(sequence, input.outcome.historyId ?? null, input.outcome.session === undefined ? null : encodeResumeCoordinate(input.outcome.session), input.outcome.answer, input.outcome.diagnostic, input.completedAt, input.turnSequence)
224
+ : database
225
+ .prepare(`UPDATE turns SET end_sequence = ?, outcome = 'failed', diagnostic = ?, completed_at = ?
226
+ WHERE sequence = ? AND end_sequence IS NULL`)
227
+ .run(sequence, input.outcome.diagnostic, input.completedAt, input.turnSequence);
201
228
  if (result.changes !== 1)
202
229
  throw new Error(`Akuma Turn ${input.turnSequence} is not open`);
203
230
  return { ...input, kind: "turn-end", sequence };
@@ -259,14 +286,14 @@ export function killFactForBody(database, bodySequence) {
259
286
  export function lastAnsweredTurnFact(database) {
260
287
  const row = database
261
288
  .prepare(`SELECT sequence, body_sequence, started_at, end_sequence, outcome, history_id,
262
- session_json, answer, diagnostic, completed_at FROM turns WHERE outcome = 'answered' ORDER BY end_sequence DESC LIMIT 1`)
289
+ session_json, answer, answer_json, schema_json, diagnostic, completed_at FROM turns WHERE outcome = 'answered' ORDER BY end_sequence DESC LIMIT 1`)
263
290
  .get();
264
291
  return row === undefined ? null : decodeTurnRow(row);
265
292
  }
266
293
  export function answeredTurnFact(database, turnSequence) {
267
294
  const row = database
268
295
  .prepare(`SELECT sequence, body_sequence, started_at, end_sequence, outcome, history_id,
269
- session_json, answer, diagnostic, completed_at FROM turns WHERE outcome = 'answered' AND sequence = ?`)
296
+ session_json, answer, answer_json, schema_json, diagnostic, completed_at FROM turns WHERE outcome = 'answered' AND sequence = ?`)
270
297
  .get(turnSequence);
271
298
  return row === undefined ? null : decodeTurnRow(row);
272
299
  }
@@ -2,5 +2,5 @@ import type { DatabaseSync } from "node:sqlite";
2
2
  export declare function assertHeartSchemaVersion(database: DatabaseSync): void;
3
3
  export declare function assertLeashSchemaVersion(database: DatabaseSync): void;
4
4
  export declare function heartSchemaIsCurrent(database: DatabaseSync): boolean;
5
- export declare const HEART_SCHEMA = "\n CREATE TABLE IF NOT EXISTS akuma_schema (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n version INTEGER NOT NULL CHECK (version = 23)\n ) STRICT;\n INSERT OR IGNORE INTO akuma_schema(singleton, version) VALUES (1, 23);\n CREATE TABLE IF NOT EXISTS soul (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n soul_json TEXT NOT NULL CHECK (json_valid(soul_json))\n ) STRICT;\n CREATE TABLE IF NOT EXISTS bodies (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n leash_taken_at TEXT NOT NULL,\n hung_diagnostic TEXT,\n hung_at TEXT,\n end TEXT CHECK (end IN ('exited', 'broke-off', 'put-down')),\n ended_at TEXT,\n CHECK ((hung_diagnostic IS NULL AND hung_at IS NULL)\n OR (hung_diagnostic IS NOT NULL AND hung_at IS NOT NULL))\n ) STRICT;\n CREATE TABLE IF NOT EXISTS sessions (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n provider TEXT NOT NULL,\n coordinate_json TEXT NOT NULL CHECK (json_valid(coordinate_json)),\n cwd TEXT NOT NULL,\n options_json TEXT NOT NULL CHECK (json_valid(options_json)),\n admitted_at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE IF NOT EXISTS turns (\n sequence INTEGER PRIMARY KEY REFERENCES timeline(sequence) ON DELETE CASCADE,\n body_sequence INTEGER NOT NULL REFERENCES bodies(sequence),\n started_at TEXT NOT NULL,\n end_sequence INTEGER UNIQUE REFERENCES timeline(sequence) ON DELETE SET NULL,\n outcome TEXT CHECK (outcome IN ('answered', 'failed')),\n history_id TEXT UNIQUE,\n session_json TEXT CHECK (session_json IS NULL OR json_valid(session_json)),\n answer TEXT,\n diagnostic TEXT,\n completed_at TEXT,\n CHECK (\n (outcome = 'answered' AND session_json IS NOT NULL AND answer IS NOT NULL AND diagnostic IS NULL)\n OR (outcome = 'failed' AND history_id IS NULL AND session_json IS NULL AND answer IS NULL AND diagnostic IS NOT NULL)\n OR (outcome IS NULL AND end_sequence IS NULL AND history_id IS NULL AND session_json IS NULL AND answer IS NULL AND diagnostic IS NULL AND completed_at IS NULL)\n )\n ) STRICT;\n CREATE TABLE IF NOT EXISTS timeline (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n kind TEXT NOT NULL CHECK (kind IN ('turn-start', 'call', 'activity', 'tell', 'turn-end'))\n ) STRICT;\n CREATE TABLE IF NOT EXISTS calls (\n sequence INTEGER PRIMARY KEY REFERENCES timeline(sequence) ON DELETE CASCADE,\n turn_sequence INTEGER NOT NULL REFERENCES turns(sequence) ON DELETE CASCADE,\n body TEXT NOT NULL,\n at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE IF NOT EXISTS activity (\n sequence INTEGER PRIMARY KEY REFERENCES timeline(sequence) ON DELETE CASCADE,\n turn_sequence INTEGER NOT NULL REFERENCES turns(sequence) ON DELETE CASCADE,\n event_json TEXT NOT NULL CHECK (json_valid(event_json)),\n at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE IF NOT EXISTS tells (\n id TEXT PRIMARY KEY,\n sequence INTEGER NOT NULL UNIQUE REFERENCES timeline(sequence) ON DELETE CASCADE,\n body TEXT NOT NULL,\n recorded_at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE IF NOT EXISTS tell_deliveries (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n tell_id TEXT NOT NULL REFERENCES tells(id) ON DELETE CASCADE,\n route TEXT NOT NULL CHECK (route IN ('launch', 'live')),\n turn_sequence INTEGER NOT NULL REFERENCES turns(sequence) ON DELETE CASCADE,\n fence TEXT NOT NULL,\n receipt TEXT CHECK (receipt IN ('unavailable', 'required')),\n delivered_at TEXT NOT NULL,\n CHECK ((route = 'launch' AND receipt IS NULL) OR (route = 'live' AND receipt IS NOT NULL)),\n UNIQUE (tell_id, turn_sequence, fence)\n ) STRICT;\n CREATE TABLE IF NOT EXISTS tell_receipts (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n evidence TEXT NOT NULL CHECK (evidence IN ('exact', 'fence')),\n tell_id TEXT REFERENCES tells(id) ON DELETE CASCADE,\n turn_sequence INTEGER REFERENCES turns(sequence) ON DELETE CASCADE,\n fence TEXT,\n kind TEXT NOT NULL,\n received_at TEXT NOT NULL,\n CHECK (\n (evidence = 'exact' AND tell_id IS NOT NULL AND turn_sequence IS NULL AND fence IS NULL)\n OR (evidence = 'fence' AND tell_id IS NULL AND turn_sequence IS NOT NULL AND fence IS NOT NULL)\n )\n ) STRICT;\n CREATE UNIQUE INDEX IF NOT EXISTS tell_receipts_exact\n ON tell_receipts(tell_id, kind) WHERE evidence = 'exact';\n CREATE UNIQUE INDEX IF NOT EXISTS tell_receipts_fence\n ON tell_receipts(turn_sequence, fence, kind) WHERE evidence = 'fence';\n CREATE TABLE IF NOT EXISTS tell_dispositions (\n body_sequence INTEGER NOT NULL REFERENCES bodies(sequence),\n tell_id TEXT NOT NULL REFERENCES tells(id),\n decided_at TEXT NOT NULL,\n resolved_at TEXT,\n PRIMARY KEY (body_sequence, tell_id)\n ) STRICT;\n CREATE TABLE IF NOT EXISTS requests (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n requester TEXT NOT NULL,\n action TEXT NOT NULL,\n payload_json TEXT NOT NULL CHECK (json_valid(payload_json)),\n admitted_at TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('admitted', 'reserved', 'begun', 'served', 'refused', 'voided', 'unproven')),\n child TEXT,\n service_json TEXT CHECK (service_json IS NULL OR json_valid(service_json)),\n diagnostic TEXT,\n evidence TEXT,\n CHECK (\n (state = 'admitted' AND child IS NULL AND service_json IS NULL AND diagnostic IS NULL AND evidence IS NULL)\n OR (state = 'reserved' AND child IS NOT NULL AND service_json IS NULL\n AND diagnostic IS NULL AND evidence IS NULL)\n OR (state = 'begun' AND child IS NULL AND service_json IS NULL AND diagnostic IS NULL AND evidence IS NULL)\n OR (state = 'served'\n AND ((child IS NOT NULL AND service_json IS NULL)\n OR (child IS NULL AND service_json IS NOT NULL))\n AND diagnostic IS NULL AND evidence IS NULL)\n OR (state = 'refused' AND child IS NULL AND service_json IS NULL AND diagnostic IS NOT NULL AND evidence IS NULL)\n OR (state = 'voided' AND child IS NULL AND service_json IS NULL AND diagnostic IS NULL AND evidence IS NOT NULL)\n OR (state = 'unproven' AND child IS NULL AND service_json IS NULL AND diagnostic IS NULL AND evidence IS NOT NULL)\n )\n ) STRICT;\n CREATE TABLE IF NOT EXISTS control (\n kind TEXT PRIMARY KEY CHECK (kind IN ('stop', 'pause')),\n value_json TEXT NOT NULL CHECK (json_valid(value_json)),\n at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE IF NOT EXISTS kills (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n body_sequence INTEGER NOT NULL UNIQUE REFERENCES bodies(sequence),\n evidence TEXT NOT NULL CHECK (evidence = 'killed'),\n at TEXT NOT NULL\n ) STRICT;\n";
5
+ export declare const HEART_SCHEMA = "\n CREATE TABLE IF NOT EXISTS akuma_schema (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n version INTEGER NOT NULL CHECK (version = 24)\n ) STRICT;\n INSERT OR IGNORE INTO akuma_schema(singleton, version) VALUES (1, 24);\n CREATE TABLE IF NOT EXISTS soul (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n soul_json TEXT NOT NULL CHECK (json_valid(soul_json))\n ) STRICT;\n CREATE TABLE IF NOT EXISTS bodies (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n leash_taken_at TEXT NOT NULL,\n hung_diagnostic TEXT,\n hung_at TEXT,\n end TEXT CHECK (end IN ('exited', 'broke-off', 'put-down')),\n ended_at TEXT,\n CHECK ((hung_diagnostic IS NULL AND hung_at IS NULL)\n OR (hung_diagnostic IS NOT NULL AND hung_at IS NOT NULL))\n ) STRICT;\n CREATE TABLE IF NOT EXISTS sessions (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n provider TEXT NOT NULL,\n coordinate_json TEXT NOT NULL CHECK (json_valid(coordinate_json)),\n cwd TEXT NOT NULL,\n options_json TEXT NOT NULL CHECK (json_valid(options_json)),\n admitted_at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE IF NOT EXISTS turns (\n sequence INTEGER PRIMARY KEY REFERENCES timeline(sequence) ON DELETE CASCADE,\n body_sequence INTEGER NOT NULL REFERENCES bodies(sequence),\n started_at TEXT NOT NULL,\n end_sequence INTEGER UNIQUE REFERENCES timeline(sequence) ON DELETE SET NULL,\n outcome TEXT CHECK (outcome IN ('answered', 'failed', 'invalid-output')),\n history_id TEXT UNIQUE,\n session_json TEXT CHECK (session_json IS NULL OR json_valid(session_json)),\n answer TEXT,\n answer_json TEXT CHECK (answer_json IS NULL OR json_valid(answer_json)),\n schema_json TEXT CHECK (schema_json IS NULL OR json_valid(schema_json)),\n diagnostic TEXT,\n completed_at TEXT,\n CHECK (\n (outcome = 'answered' AND session_json IS NOT NULL AND answer IS NOT NULL AND diagnostic IS NULL\n AND ((schema_json IS NULL AND answer_json IS NULL) OR (schema_json IS NOT NULL AND answer_json IS NOT NULL)))\n OR (outcome = 'failed' AND history_id IS NULL AND session_json IS NULL AND answer IS NULL\n AND answer_json IS NULL AND diagnostic IS NOT NULL)\n OR (outcome = 'invalid-output' AND answer IS NOT NULL AND answer_json IS NULL\n AND diagnostic IS NOT NULL AND schema_json IS NOT NULL)\n OR (outcome IS NULL AND end_sequence IS NULL AND history_id IS NULL AND session_json IS NULL\n AND answer IS NULL AND answer_json IS NULL AND diagnostic IS NULL AND completed_at IS NULL)\n )\n ) STRICT;\n CREATE TABLE IF NOT EXISTS timeline (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n kind TEXT NOT NULL CHECK (kind IN ('turn-start', 'call', 'activity', 'tell', 'turn-end'))\n ) STRICT;\n CREATE TABLE IF NOT EXISTS calls (\n sequence INTEGER PRIMARY KEY REFERENCES timeline(sequence) ON DELETE CASCADE,\n turn_sequence INTEGER NOT NULL REFERENCES turns(sequence) ON DELETE CASCADE,\n body TEXT NOT NULL,\n at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE IF NOT EXISTS activity (\n sequence INTEGER PRIMARY KEY REFERENCES timeline(sequence) ON DELETE CASCADE,\n turn_sequence INTEGER NOT NULL REFERENCES turns(sequence) ON DELETE CASCADE,\n event_json TEXT NOT NULL CHECK (json_valid(event_json)),\n at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE IF NOT EXISTS tells (\n id TEXT PRIMARY KEY,\n sequence INTEGER NOT NULL UNIQUE REFERENCES timeline(sequence) ON DELETE CASCADE,\n body TEXT NOT NULL,\n schema_json TEXT CHECK (schema_json IS NULL OR json_valid(schema_json)),\n recorded_at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE IF NOT EXISTS tell_bindings (\n tell_id TEXT PRIMARY KEY REFERENCES tells(id) ON DELETE CASCADE,\n turn_sequence INTEGER NOT NULL REFERENCES turns(sequence) ON DELETE CASCADE,\n bound_at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE IF NOT EXISTS tell_deliveries (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n tell_id TEXT NOT NULL REFERENCES tells(id) ON DELETE CASCADE,\n route TEXT NOT NULL CHECK (route IN ('launch', 'live')),\n turn_sequence INTEGER NOT NULL REFERENCES turns(sequence) ON DELETE CASCADE,\n fence TEXT NOT NULL,\n receipt TEXT CHECK (receipt IN ('unavailable', 'required')),\n delivered_at TEXT NOT NULL,\n CHECK ((route = 'launch' AND receipt IS NULL) OR (route = 'live' AND receipt IS NOT NULL)),\n UNIQUE (tell_id, turn_sequence, fence)\n ) STRICT;\n CREATE TABLE IF NOT EXISTS tell_receipts (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n evidence TEXT NOT NULL CHECK (evidence IN ('exact', 'fence')),\n tell_id TEXT REFERENCES tells(id) ON DELETE CASCADE,\n turn_sequence INTEGER REFERENCES turns(sequence) ON DELETE CASCADE,\n fence TEXT,\n kind TEXT NOT NULL,\n received_at TEXT NOT NULL,\n CHECK (\n (evidence = 'exact' AND tell_id IS NOT NULL AND turn_sequence IS NULL AND fence IS NULL)\n OR (evidence = 'fence' AND tell_id IS NULL AND turn_sequence IS NOT NULL AND fence IS NOT NULL)\n )\n ) STRICT;\n CREATE UNIQUE INDEX IF NOT EXISTS tell_receipts_exact\n ON tell_receipts(tell_id, kind) WHERE evidence = 'exact';\n CREATE UNIQUE INDEX IF NOT EXISTS tell_receipts_fence\n ON tell_receipts(turn_sequence, fence, kind) WHERE evidence = 'fence';\n CREATE TABLE IF NOT EXISTS tell_dispositions (\n body_sequence INTEGER NOT NULL REFERENCES bodies(sequence),\n tell_id TEXT NOT NULL REFERENCES tells(id),\n decided_at TEXT NOT NULL,\n resolved_at TEXT,\n PRIMARY KEY (body_sequence, tell_id)\n ) STRICT;\n CREATE TABLE IF NOT EXISTS requests (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n id TEXT NOT NULL UNIQUE,\n requester TEXT NOT NULL,\n action TEXT NOT NULL,\n payload_json TEXT NOT NULL CHECK (json_valid(payload_json)),\n admitted_at TEXT NOT NULL,\n state TEXT NOT NULL CHECK (state IN ('admitted', 'reserved', 'begun', 'served', 'refused', 'voided', 'unproven')),\n child TEXT,\n service_json TEXT CHECK (service_json IS NULL OR json_valid(service_json)),\n diagnostic TEXT,\n evidence TEXT,\n CHECK (\n (state = 'admitted' AND child IS NULL AND service_json IS NULL AND diagnostic IS NULL AND evidence IS NULL)\n OR (state = 'reserved' AND child IS NOT NULL AND service_json IS NULL\n AND diagnostic IS NULL AND evidence IS NULL)\n OR (state = 'begun' AND child IS NULL AND service_json IS NULL AND diagnostic IS NULL AND evidence IS NULL)\n OR (state = 'served'\n AND ((child IS NOT NULL AND service_json IS NULL)\n OR (child IS NULL AND service_json IS NOT NULL))\n AND diagnostic IS NULL AND evidence IS NULL)\n OR (state = 'refused' AND child IS NULL AND service_json IS NULL AND diagnostic IS NOT NULL AND evidence IS NULL)\n OR (state = 'voided' AND child IS NULL AND service_json IS NULL AND diagnostic IS NULL AND evidence IS NOT NULL)\n OR (state = 'unproven' AND child IS NULL AND service_json IS NULL AND diagnostic IS NULL AND evidence IS NOT NULL)\n )\n ) STRICT;\n CREATE TABLE IF NOT EXISTS control (\n kind TEXT PRIMARY KEY CHECK (kind IN ('stop', 'pause')),\n value_json TEXT NOT NULL CHECK (json_valid(value_json)),\n at TEXT NOT NULL\n ) STRICT;\n CREATE TABLE IF NOT EXISTS kills (\n sequence INTEGER PRIMARY KEY AUTOINCREMENT,\n body_sequence INTEGER NOT NULL UNIQUE REFERENCES bodies(sequence),\n evidence TEXT NOT NULL CHECK (evidence = 'killed'),\n at TEXT NOT NULL\n ) STRICT;\n";
6
6
  export declare const LEASH_SCHEMA = "\n PRAGMA journal_mode=DELETE;\n CREATE TABLE IF NOT EXISTS leash_schema (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n version INTEGER NOT NULL CHECK (version = 4)\n ) STRICT;\n INSERT OR IGNORE INTO leash_schema(singleton, version) VALUES (1, 4);\n CREATE TABLE IF NOT EXISTS seal (\n singleton INTEGER PRIMARY KEY CHECK (singleton = 1),\n evidence TEXT NOT NULL,\n at TEXT NOT NULL\n ) STRICT;\n";
@@ -1,4 +1,4 @@
1
- const HEART_SCHEMA_VERSION = 23;
1
+ const HEART_SCHEMA_VERSION = 24;
2
2
  const LEASH_SCHEMA_VERSION = 4;
3
3
  function assertSchemaVersion(database, table, expected) {
4
4
  const row = database.prepare(`SELECT version FROM ${table} WHERE singleton = 1`).get();
@@ -53,16 +53,23 @@ export const HEART_SCHEMA = `
53
53
  body_sequence INTEGER NOT NULL REFERENCES bodies(sequence),
54
54
  started_at TEXT NOT NULL,
55
55
  end_sequence INTEGER UNIQUE REFERENCES timeline(sequence) ON DELETE SET NULL,
56
- outcome TEXT CHECK (outcome IN ('answered', 'failed')),
56
+ outcome TEXT CHECK (outcome IN ('answered', 'failed', 'invalid-output')),
57
57
  history_id TEXT UNIQUE,
58
58
  session_json TEXT CHECK (session_json IS NULL OR json_valid(session_json)),
59
59
  answer TEXT,
60
+ answer_json TEXT CHECK (answer_json IS NULL OR json_valid(answer_json)),
61
+ schema_json TEXT CHECK (schema_json IS NULL OR json_valid(schema_json)),
60
62
  diagnostic TEXT,
61
63
  completed_at TEXT,
62
64
  CHECK (
63
- (outcome = 'answered' AND session_json IS NOT NULL AND answer IS NOT NULL AND diagnostic IS NULL)
64
- OR (outcome = 'failed' AND history_id IS NULL AND session_json IS NULL AND answer IS NULL AND diagnostic IS NOT NULL)
65
- OR (outcome IS NULL AND end_sequence IS NULL AND history_id IS NULL AND session_json IS NULL AND answer IS NULL AND diagnostic IS NULL AND completed_at IS NULL)
65
+ (outcome = 'answered' AND session_json IS NOT NULL AND answer IS NOT NULL AND diagnostic IS NULL
66
+ AND ((schema_json IS NULL AND answer_json IS NULL) OR (schema_json IS NOT NULL AND answer_json IS NOT NULL)))
67
+ OR (outcome = 'failed' AND history_id IS NULL AND session_json IS NULL AND answer IS NULL
68
+ AND answer_json IS NULL AND diagnostic IS NOT NULL)
69
+ OR (outcome = 'invalid-output' AND answer IS NOT NULL AND answer_json IS NULL
70
+ AND diagnostic IS NOT NULL AND schema_json IS NOT NULL)
71
+ OR (outcome IS NULL AND end_sequence IS NULL AND history_id IS NULL AND session_json IS NULL
72
+ AND answer IS NULL AND answer_json IS NULL AND diagnostic IS NULL AND completed_at IS NULL)
66
73
  )
67
74
  ) STRICT;
68
75
  CREATE TABLE IF NOT EXISTS timeline (
@@ -85,8 +92,14 @@ export const HEART_SCHEMA = `
85
92
  id TEXT PRIMARY KEY,
86
93
  sequence INTEGER NOT NULL UNIQUE REFERENCES timeline(sequence) ON DELETE CASCADE,
87
94
  body TEXT NOT NULL,
95
+ schema_json TEXT CHECK (schema_json IS NULL OR json_valid(schema_json)),
88
96
  recorded_at TEXT NOT NULL
89
97
  ) STRICT;
98
+ CREATE TABLE IF NOT EXISTS tell_bindings (
99
+ tell_id TEXT PRIMARY KEY REFERENCES tells(id) ON DELETE CASCADE,
100
+ turn_sequence INTEGER NOT NULL REFERENCES turns(sequence) ON DELETE CASCADE,
101
+ bound_at TEXT NOT NULL
102
+ ) STRICT;
90
103
  CREATE TABLE IF NOT EXISTS tell_deliveries (
91
104
  sequence INTEGER PRIMARY KEY AUTOINCREMENT,
92
105
  tell_id TEXT NOT NULL REFERENCES tells(id) ON DELETE CASCADE,
@@ -39,7 +39,7 @@ export declare class HeldAkumaLeash {
39
39
  target: StopFact;
40
40
  result: "recorded" | "already-killed";
41
41
  }> | null>;
42
- recordInterruptTell(paths: AkumaPaths, tell: Omit<TellFact, "sequence" | "state" | "deliveries">): Promise<Readonly<{
42
+ recordInterruptTell(paths: AkumaPaths, tell: Omit<TellFact, "sequence" | "state" | "deliveries" | "binding">): Promise<Readonly<{
43
43
  kind: "not-born";
44
44
  } | {
45
45
  kind: "recorded";
@@ -32,3 +32,10 @@ export declare function successorBodyHoldingDisposition(database: DatabaseSync,
32
32
  tellIds: readonly string[];
33
33
  }>): number | null;
34
34
  export declare function insertUndeliveredTellReceipts(database: DatabaseSync, tellIds: readonly string[], at: string): void;
35
+ export declare function insertTellBindingFact(database: DatabaseSync, input: Readonly<{
36
+ tellId: string;
37
+ turnSequence: number;
38
+ boundAt: string;
39
+ }>): void;
40
+ export declare function drainPendingTells(pending: readonly TellFact[]): readonly TellFact[];
41
+ export declare function openBoundTurns(database: DatabaseSync, bodySequence: number): readonly number[];