@astrosheep/keiyaku 4.6.33 → 4.6.34

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 (118) hide show
  1. package/README.md +10 -1
  2. package/build/plugins/claude/skills/keiyaku-akuma/SKILL.md +5 -2
  3. package/build/plugins/claude/skills/keiyaku-debt/SKILL.md +2 -1
  4. package/build/plugins/codex/skills/keiyaku-akuma/SKILL.md +5 -2
  5. package/build/plugins/codex/skills/keiyaku-debt/SKILL.md +2 -1
  6. package/build/plugins/opencode/skills/keiyaku-akuma/SKILL.md +5 -2
  7. package/build/plugins/opencode/skills/keiyaku-debt/SKILL.md +2 -1
  8. package/build/plugins/pi/keiyaku.ts +1 -135
  9. package/build/skills/keiyaku-akuma/SKILL.md +5 -2
  10. package/build/skills/keiyaku-debt/SKILL.md +2 -1
  11. package/build/src/akuma/akuma-observe.d.ts +8 -0
  12. package/build/src/akuma/akuma-observe.js +8 -0
  13. package/build/src/akuma/akuma-owner.d.ts +1 -0
  14. package/build/src/akuma/akuma-owner.js +3 -5
  15. package/build/src/akuma/akuma-wait.d.ts +117 -2
  16. package/build/src/akuma/akuma-wait.js +53 -22
  17. package/build/src/akuma/akuma.d.ts +6 -1
  18. package/build/src/akuma/akuma.js +37 -18
  19. package/build/src/akuma/heart/facts.d.ts +1 -0
  20. package/build/src/akuma/heart/facts.js +14 -0
  21. package/build/src/akuma/heart/index.d.ts +6 -0
  22. package/build/src/akuma/heart/index.js +27 -9
  23. package/build/src/akuma/heart/rows.d.ts +1 -0
  24. package/build/src/akuma/heart/rows.js +4 -0
  25. package/build/src/akuma/lineage-cache.d.ts +7 -2
  26. package/build/src/akuma/lineage-cache.js +48 -24
  27. package/build/src/akuma/projection-read.js +4 -9
  28. package/build/src/akuma/selection-observation.d.ts +622 -0
  29. package/build/src/akuma/selection-observation.js +7 -3
  30. package/build/src/bounded-list.d.ts +8 -0
  31. package/build/src/bounded-list.js +10 -0
  32. package/build/src/cli/commands/akuma-grammar.d.ts +2 -3
  33. package/build/src/cli/commands/akuma-grammar.js +32 -39
  34. package/build/src/cli/commands/akuma.js +6 -3
  35. package/build/src/cli/commands/contract-grammar.js +32 -31
  36. package/build/src/cli/commands/contract-help.d.ts +3 -3
  37. package/build/src/cli/commands/contract-help.js +10 -8
  38. package/build/src/cli/commands/contract.d.ts +3 -3
  39. package/build/src/cli/commands/contract.js +11 -10
  40. package/build/src/cli/parse.d.ts +4 -10
  41. package/build/src/cli/parse.js +1 -1
  42. package/build/src/cli/render/akuma-activity.d.ts +9 -19
  43. package/build/src/cli/render/akuma-activity.js +83 -110
  44. package/build/src/cli/render/catalog.js +3 -2
  45. package/build/src/cli/render/contract-history.d.ts +1 -3
  46. package/build/src/cli/render/contract-history.js +68 -49
  47. package/build/src/cli/render/contract-wait.js +9 -1
  48. package/build/src/cli/render/kanshi-akuma.d.ts +4 -3
  49. package/build/src/cli/render/kanshi-akuma.js +26 -21
  50. package/build/src/cli/render/kanshi.js +34 -43
  51. package/build/src/cli/render/verbs.js +20 -17
  52. package/build/src/cli/runtime.js +9 -23
  53. package/build/src/debt/board.d.ts +2 -1
  54. package/build/src/debt/board.js +3 -3
  55. package/build/src/debt/catalog.js +2 -1
  56. package/build/src/debt/document.d.ts +1 -0
  57. package/build/src/debt/document.js +3 -0
  58. package/build/src/debt/index.d.ts +2 -1
  59. package/build/src/debt/index.js +3 -3
  60. package/build/src/debt/operations.d.ts +2 -1
  61. package/build/src/git/observe.d.ts +4 -3
  62. package/build/src/git/observe.js +8 -7
  63. package/build/src/history.d.ts +26 -0
  64. package/build/src/history.js +43 -0
  65. package/build/src/index.d.ts +4 -3
  66. package/build/src/kanshi/counts.d.ts +15 -1
  67. package/build/src/kanshi/counts.js +14 -3
  68. package/build/src/kanshi/index.d.ts +3 -3
  69. package/build/src/kanshi/index.js +2 -2
  70. package/build/src/kanshi/read.js +5 -2
  71. package/build/src/library/akumas.d.ts +5 -1
  72. package/build/src/library/akumas.js +11 -5
  73. package/build/src/library/contract-composition.js +10 -10
  74. package/build/src/library/contract-creation.js +2 -2
  75. package/build/src/library/contract-types.d.ts +215 -25
  76. package/build/src/library/contract-types.js +31 -13
  77. package/build/src/library/contract-wait.d.ts +205 -0
  78. package/build/src/library/contract-wait.js +15 -3
  79. package/build/src/library/input.d.ts +3 -3
  80. package/build/src/library/input.js +5 -5
  81. package/build/src/library/kei.js +134 -76
  82. package/build/src/library/keiyaku-attribution.d.ts +1 -1
  83. package/build/src/library/keiyaku-attribution.js +3 -1
  84. package/build/src/library/keiyaku-classify.js +5 -1
  85. package/build/src/library/keiyaku-debt.d.ts +8 -7
  86. package/build/src/library/keiyaku-identity.d.ts +4 -3
  87. package/build/src/library/keiyaku-identity.js +30 -7
  88. package/build/src/library/keiyaku-verbs.d.ts +515 -44
  89. package/build/src/library/keiyaku-verbs.js +84 -79
  90. package/build/src/library/keiyaku-wait.d.ts +570 -0
  91. package/build/src/library/keiyaku-wait.js +25 -8
  92. package/build/src/library/keiyaku.d.ts +3110 -31
  93. package/build/src/library/keiyaku.js +335 -407
  94. package/build/src/library/model-tools.d.ts +268 -70
  95. package/build/src/library/model-tools.js +110 -95
  96. package/build/src/library/selection.d.ts +6 -5
  97. package/build/src/library/selection.js +10 -3
  98. package/build/src/mcp/adapter.js +1 -1
  99. package/build/src/mcp/help.d.ts +1 -1
  100. package/build/src/mcp/help.js +4 -3
  101. package/build/src/pi/index.d.ts +2 -0
  102. package/build/src/pi/index.js +23 -7
  103. package/build/src/pi/status.d.ts +12 -0
  104. package/build/src/pi/status.js +140 -0
  105. package/build/src/protocol/operations.d.ts +2 -0
  106. package/build/src/protocol/operations.js +1 -1
  107. package/build/src/protocol/read/status.d.ts +12 -4
  108. package/build/src/protocol/read/status.js +19 -12
  109. package/build/src/runtime/proc/windows-launch.exe +0 -0
  110. package/package.json +1 -1
  111. package/plugins/paseo/plugin/index.server.ts +6 -2
  112. package/plugins/paseo/plugin/server/attach.ts +68 -48
  113. package/plugins/paseo/plugin/server/directory.ts +259 -0
  114. package/plugins/paseo/plugin/server/mirror-identity.ts +3 -32
  115. package/plugins/paseo/plugin/server/reopen.ts +52 -38
  116. package/plugins/pi/keiyaku.ts +1 -135
  117. package/skills/keiyaku-akuma/SKILL.md +5 -2
  118. package/skills/keiyaku-debt/SKILL.md +2 -1
@@ -1,5 +1,6 @@
1
1
  import { type AkumaCaller } from "./caller.js";
2
2
  import { z } from "zod";
3
+ import { type LifecycleSelection } from "../bounded-list.js";
3
4
  import type { WorldRoot } from "../world.js";
4
5
  import { type AkumaId, type AkumaPaths } from "./identity.js";
5
6
  import type { ActivitySnapshot } from "./projection.js";
@@ -33,6 +34,7 @@ export type AkumaCompleteList = Readonly<{
33
34
  export type AkumaRosterInput = Readonly<{
34
35
  akumaName?: string;
35
36
  caller?: AkumaCaller;
37
+ selection?: LifecycleSelection;
36
38
  limit?: number;
37
39
  }>;
38
40
  export declare const akumaStatusSchema: z.ZodReadonly<z.ZodObject<{
@@ -129,18 +131,21 @@ export declare function knownAkuma(path: WorldRoot, selected?: string): Promise<
129
131
  }>>;
130
132
  /** Exact running count requires every recognized coordinate to be readable. */
131
133
  export declare function countRunningAkuma(path: WorldRoot): Promise<number>;
134
+ /** Readable running subset of the same frozen caller tree used by listing. */
135
+ export declare function countCallerRunningAkuma(path: WorldRoot, caller: AkumaCaller): Promise<number>;
132
136
  export declare function rosterInput(input: AkumaRosterInput | Readonly<{
133
137
  akumaName?: string;
134
138
  }>, allowLimit: boolean): Readonly<{
135
139
  akumaName?: string;
136
140
  caller?: AkumaCaller;
141
+ selection?: LifecycleSelection;
137
142
  }>;
138
143
  /**
139
144
  * The bounded recent-activity roster: native membership, semantic order and
140
145
  * observed extent. A caller-scoped roster filters its World-local closure before
141
146
  * this same activity order and bound; World Alias context is attached above.
142
147
  */
143
- export declare function observeAkumaRoster(path: WorldRoot, limit: number, selected?: string, caller?: AkumaCaller): Promise<AkumaRosterPage>;
148
+ export declare function observeAkumaRoster(path: WorldRoot, limit: number, selected?: string, caller?: AkumaCaller, selection?: LifecycleSelection): Promise<AkumaRosterPage>;
144
149
  /** The complete native roster for callers whose semantics require a frozen set. */
145
150
  export declare function readAkumaCompleteRoster(path: WorldRoot, input?: Readonly<{
146
151
  akumaName?: string;
@@ -2,8 +2,9 @@ import { KeiyakuError } from "../errors.js";
2
2
  import { akumaBirthSchema, akumaCallerKey, decodeAkumaCaller } from "./caller.js";
3
3
  import { readdir, stat } from "node:fs/promises";
4
4
  import { z } from "zod";
5
- import { projectBoundedList } from "../bounded-list.js";
6
- import { rosterListRow } from "./akuma-observe.js";
5
+ import { projectBoundedList, lifecycleSelection } from "../bounded-list.js";
6
+ import { akumaLifecycle } from "./heart/facts.js";
7
+ import { readBornLife, rosterListRow } from "./akuma-observe.js";
7
8
  import { AkumaOwner } from "./akuma-owner.js";
8
9
  import { readSoul } from "./heart/index.js";
9
10
  import { akumaIdFromDirectoryName, akumaIdSchema, akumaPaths, akumaRunRoot, parseAkumaId, pathsForAkumaId, } from "./identity.js";
@@ -125,10 +126,26 @@ export async function countRunningAkuma(path) {
125
126
  throw new Error("Cannot classify every recognized Akuma", { cause: observed.failure });
126
127
  return observed.rows.filter((row) => row.life === "running").length;
127
128
  }
129
+ /** Readable running subset of the same frozen caller tree used by listing. */
130
+ export async function countCallerRunningAkuma(path, caller) {
131
+ const known = await knownAkuma(path);
132
+ const { edges } = await readDirectAkumaLineage(known.rows);
133
+ const members = callerClosure(edges, caller, path);
134
+ const running = await boundedMap(known.rows.filter(({ id }) => members.has(id)), async ({ id, paths }) => {
135
+ try {
136
+ return (await readBornLife(paths, id)) === "running" ? 1 : 0;
137
+ }
138
+ catch {
139
+ // Failed life does not erase the already proven Soul edge for descendants.
140
+ return 0;
141
+ }
142
+ });
143
+ return running.reduce((count, value) => count + value, 0);
144
+ }
128
145
  export function rosterInput(input, allowLimit) {
129
146
  if (typeof input !== "object" || input === null || Array.isArray(input))
130
147
  throw new KeiyakuError("invalid-input", "Akuma list input must be an object");
131
- const allowed = allowLimit ? ["akumaName", "caller", "limit"] : ["akumaName", "caller"];
148
+ const allowed = allowLimit ? ["akumaName", "caller", "selection", "limit"] : ["akumaName", "caller"];
132
149
  const unknown = Object.keys(input).find((key) => !allowed.includes(key));
133
150
  if (unknown !== undefined)
134
151
  throw new KeiyakuError("invalid-input", `Akuma list input has unknown field: ${unknown}`);
@@ -136,6 +153,7 @@ export function rosterInput(input, allowLimit) {
136
153
  return {
137
154
  ...(input.akumaName === undefined ? {} : { akumaName: validateAkumaName(input.akumaName) }),
138
155
  ...(caller === undefined ? {} : { caller }),
156
+ ...(allowLimit ? { selection: lifecycleSelection(input.selection) } : {}),
139
157
  };
140
158
  }
141
159
  /**
@@ -160,8 +178,8 @@ function callerClosure(lineage, root, world) {
160
178
  const included = new Set();
161
179
  const visited = new Set();
162
180
  const queue = [root];
163
- while (queue.length > 0) {
164
- const caller = queue.shift();
181
+ for (let cursor = 0; cursor < queue.length; cursor += 1) {
182
+ const caller = queue[cursor];
165
183
  const key = akumaCallerKey(caller);
166
184
  if (visited.has(key))
167
185
  continue;
@@ -248,7 +266,7 @@ async function verifyCallerMember(verification, id, observedCaller) {
248
266
  * closure's own born Soul edges are the proof. Unprovable members are skipped
249
267
  * honestly instead of reported as no more.
250
268
  */
251
- async function pageCallerRows(candidates, limit, admit) {
269
+ async function pageCallerRows(candidates, limit, admit, selection = "all") {
252
270
  const rows = [];
253
271
  let skipped = 0;
254
272
  let cursor = 0;
@@ -261,7 +279,7 @@ async function pageCallerRows(candidates, limit, admit) {
261
279
  const verdict = admit === undefined ? "included" : await admit(row);
262
280
  if (verdict === "invalid-cache")
263
281
  return { rows, skipped, invalid: true };
264
- if (verdict === "included")
282
+ if (verdict === "included" && (selection === "all" || akumaLifecycle(row.life) === selection))
265
283
  rows.push(row);
266
284
  else if (verdict === "unknown")
267
285
  skipped += 1;
@@ -294,21 +312,22 @@ async function callerCandidates(rows, lineage, root, world, selected) {
294
312
  * re-proven against its born Soul chain, and one disagreement discards the
295
313
  * record and answers from direct Soul evidence instead of an empty success.
296
314
  */
297
- async function readCallerPage(path, limit, selected, caller) {
315
+ async function readCallerPage(path, limit, selected, caller, selection = "all") {
298
316
  const known = await knownAkuma(path);
299
317
  const cached = await readAkumaLineage(path, known.rows);
300
- const verification = { world: path, root: caller, lineage: cached, souls: new Map() };
301
- const attempted = await pageCallerRows(await callerCandidates(known.rows, cached, caller, path, selected), limit,
318
+ const verification = { world: path, root: caller, lineage: cached.edges, souls: new Map() };
319
+ const attempted = await pageCallerRows(await callerCandidates(known.rows, cached.edges, caller, path, selected), limit,
302
320
  // A cache-proposed identity without a born Soul cannot justify inclusion.
303
- async (row) => (row.kind === "born" ? await verifyCallerMember(verification, row.id, row.caller) : "invalid-cache"));
321
+ async (row) => (row.kind === "born" ? await verifyCallerMember(verification, row.id, row.caller) : "invalid-cache"), selection);
304
322
  if (!attempted.invalid)
305
- return attempted;
323
+ return { ...attempted, skipped: attempted.skipped + cached.skipped };
306
324
  // One wrong edge makes the whole disposable record untrustworthy.
307
325
  await invalidateAkumaLineage(path);
308
326
  const direct = await readDirectAkumaLineage(known.rows);
309
- const repaired = await pageCallerRows(await callerCandidates(known.rows, direct, caller, path, selected), limit);
310
- await rebuildAkumaLineage(path, direct);
311
- return repaired;
327
+ const repaired = await pageCallerRows(await callerCandidates(known.rows, direct.edges, caller, path, selected), limit, undefined, selection);
328
+ if (direct.skipped === 0)
329
+ await rebuildAkumaLineage(path, direct.edges);
330
+ return { ...repaired, skipped: repaired.skipped + direct.skipped };
312
331
  }
313
332
  /** One roster answer: empty rows and known completeness are both omissions. */
314
333
  function rosterResult(observedAt, rows, more) {
@@ -323,15 +342,15 @@ function rosterResult(observedAt, rows, more) {
323
342
  * observed extent. A caller-scoped roster filters its World-local closure before
324
343
  * this same activity order and bound; World Alias context is attached above.
325
344
  */
326
- export async function observeAkumaRoster(path, limit, selected, caller) {
345
+ export async function observeAkumaRoster(path, limit, selected, caller, selection = "all") {
327
346
  const observedAt = new Date().toISOString();
328
347
  if (caller !== undefined) {
329
- const page = await readCallerPage(path, limit, selected, caller);
348
+ const page = await readCallerPage(path, limit, selected, caller, selection);
330
349
  const bounded = projectBoundedList(page.rows, limit);
331
350
  return rosterResult(observedAt, bounded.rows, bounded.hasMore || page.skipped > 0);
332
351
  }
333
352
  const known = await knownAkuma(path, selected);
334
- const ranked = await pageCallerRows(await freshnessOrdered(known.rows), limit);
353
+ const ranked = await pageCallerRows(await freshnessOrdered(known.rows), limit, undefined, selection);
335
354
  const bounded = projectBoundedList(ranked.rows, limit);
336
355
  return rosterResult(observedAt, bounded.rows, bounded.hasMore);
337
356
  }
@@ -223,6 +223,7 @@ export type SealFact = Readonly<{
223
223
  }>;
224
224
  export type LeashProbe = "held" | "free";
225
225
  export type AkumaLife = "running" | "asleep" | "stranded" | "hung" | "untidy" | "killed";
226
+ export declare function akumaLifecycle(life: AkumaLife | "unborn" | "stillborn"): "active" | "settled";
226
227
  export type HeartSnapshot = Readonly<{
227
228
  soul: Soul | null;
228
229
  latestBody: BodyFact | null;
@@ -58,6 +58,20 @@ export class BodyControlledError extends Error {
58
58
  this.name = "BodyControlledError";
59
59
  }
60
60
  }
61
+ export function akumaLifecycle(life) {
62
+ switch (life) {
63
+ case "running":
64
+ case "unborn":
65
+ case "stranded":
66
+ case "hung":
67
+ case "untidy":
68
+ return "active";
69
+ case "asleep":
70
+ case "killed":
71
+ case "stillborn":
72
+ return "settled";
73
+ }
74
+ }
61
75
  export function life(input) {
62
76
  if (input.body?.hung !== undefined)
63
77
  return "hung";
@@ -56,6 +56,7 @@ export declare function createTimelineReader(paths: AkumaPaths): Readonly<{
56
56
  /** One observer owns its connection and successful decoded frontier. */
57
57
  export declare function createStatusFactReader(paths: AkumaPaths): {
58
58
  life: (signal?: AbortSignal) => Promise<LifeSnapshot>;
59
+ wait: (recent: boolean, signal?: AbortSignal) => Promise<WaitFacts>;
59
60
  tellOutcome: (id: string, signal?: AbortSignal) => Promise<{
60
61
  tell: Readonly<{
61
62
  kind: "tell";
@@ -83,6 +84,11 @@ export declare function createStatusFactReader(paths: AkumaPaths): {
83
84
  type LifeSnapshot = Pick<HeartSnapshot, "soul" | "latestBody" | "latestSession" | "latestKill" | "lastActivityAt"> & Readonly<{
84
85
  hasPendingTell: boolean;
85
86
  }>;
87
+ export type WaitFacts = LifeSnapshot & Readonly<{
88
+ turn: TurnFact | null;
89
+ activity: ActivityFactSlice | undefined;
90
+ activityDiagnostic: string | undefined;
91
+ }>;
86
92
  /** Lifecycle probes do not load narration, Tell bodies, or delivery histories. */
87
93
  export declare function readLifeSnapshot(paths: AkumaPaths, signal?: AbortSignal, read?: HeartRead): Promise<LifeSnapshot>;
88
94
  export type InterruptTellAdmission = Readonly<{
@@ -1,7 +1,7 @@
1
1
  import { parsePublicHistoryId } from "../identity.js";
2
2
  import { decodeRuntimeModel, withoutModel } from "../provider-recipe.js";
3
3
  import { BodyControlledError } from "./facts.js";
4
- import { answeredTurnFact, completeInterruptBarrier as judgeInterruptBarrier, endBodyFact, finishBodyFact, deleteStopControl, insertReportFact, insertActivityFact, insertTurnEndFact, insertTurnStartFact, insertKillFact, insertSessionFact, insertStopControl, killFactForBody, hasBodyHandoffControl, latestBodyFact, insertInterruptBarrier, isTellProtectedByPause, latestKillFact, latestSessionFact, latestTurnFactForBody, lastAnsweredTurnFact, pauseFact, sessionFactForCoordinate, stopFact, turnFact, openTurnsForBody, terminalTurnForTell, } from "./rows.js";
4
+ import { answeredTurnFact, completeInterruptBarrier as judgeInterruptBarrier, endBodyFact, finishBodyFact, deleteStopControl, insertReportFact, insertActivityFact, insertTurnEndFact, insertTurnStartFact, insertKillFact, insertSessionFact, insertStopControl, killFactForBody, hasBodyHandoffControl, latestBodyFact, insertInterruptBarrier, isTellProtectedByPause, latestKillFact, latestSessionFact, latestTurnFactForBody, latestTurnFact, lastAnsweredTurnFact, pauseFact, sessionFactForCoordinate, stopFact, turnFact, openTurnsForBody, terminalTurnForTell, } from "./rows.js";
5
5
  import { insertTellDeliveryFact, dispositionSnapshotProven, insertTellBindingFact, insertTellDispositionSnapshot, insertTellReceiptFact, insertUndeliveredTellReceipts, latestOpenTellDisposition, openBoundTurns, openTellDispositionIds, pendingTellFacts, hasPendingTell, resolveTellDispositionSnapshot, sameTellInput, tellDispositionResolved, tellFact, tellIdsForFence, turnParticipants, } from "./tells.js";
6
6
  import { activityFactSlice, statusFacts, readStatusBatch, decodeTimelineBatch, timelineDataVersion, lastActivityAt as readLastActivityAt, pruneActivityFacts, } from "./timeline.js";
7
7
  import { createHeartReader, isHeartAbsent, readSealFromLeash, recordPendingTell, withHeartTransaction, withReadOnlyHeart, } from "./storage.js";
@@ -132,6 +132,21 @@ export function createStatusFactReader(paths) {
132
132
  let memo;
133
133
  return {
134
134
  life: (signal) => readLifeSnapshot(paths, signal, reader.read),
135
+ wait: (recent, signal) => reader.read((heart) => {
136
+ const snapshot = lifeSnapshot(heart);
137
+ const turn = latestTurnFact(heart);
138
+ let activity;
139
+ let activityDiagnostic;
140
+ if (recent) {
141
+ try {
142
+ activity = activityFactSlice(heart);
143
+ }
144
+ catch (error) {
145
+ activityDiagnostic = error instanceof Error ? error.message : String(error);
146
+ }
147
+ }
148
+ return { ...snapshot, turn, activity, activityDiagnostic };
149
+ }, signal),
135
150
  tellOutcome: (id, signal) => reader.read((heart) => {
136
151
  const tell = tellFact(heart, id);
137
152
  // A pending Tell may be retried by a successor after cancellation. Its
@@ -163,17 +178,20 @@ export function createStatusFactReader(paths) {
163
178
  },
164
179
  };
165
180
  }
181
+ function lifeSnapshot(heart) {
182
+ return {
183
+ soul: soulFact(heart),
184
+ latestBody: latestBodyFact(heart),
185
+ latestSession: latestSessionFact(heart),
186
+ latestKill: latestKillFact(heart),
187
+ hasPendingTell: hasPendingTell(heart),
188
+ lastActivityAt: readLastActivityAt(heart),
189
+ };
190
+ }
166
191
  /** Lifecycle probes do not load narration, Tell bodies, or delivery histories. */
167
192
  export async function readLifeSnapshot(paths, signal, read = (body, signal) => withReadOnlyHeart(paths, body, signal)) {
168
193
  try {
169
- return await read((heart) => ({
170
- soul: soulFact(heart),
171
- latestBody: latestBodyFact(heart),
172
- latestSession: latestSessionFact(heart),
173
- latestKill: latestKillFact(heart),
174
- hasPendingTell: hasPendingTell(heart),
175
- lastActivityAt: readLastActivityAt(heart),
176
- }), signal);
194
+ return await read(lifeSnapshot, signal);
177
195
  }
178
196
  catch (error) {
179
197
  if (isHeartAbsent(error))
@@ -189,4 +189,5 @@ export declare function killFactForBody(database: DatabaseSync, bodySequence: nu
189
189
  export declare function lastAnsweredTurnFact(database: DatabaseSync): TurnFact | null;
190
190
  export declare function answeredTurnFact(database: DatabaseSync, turnSequence: number): TurnFact | null;
191
191
  export declare function latestTurnFactForBody(database: DatabaseSync, bodySequence: number): TurnFact | null;
192
+ export declare function latestTurnFact(database: DatabaseSync): TurnFact | null;
192
193
  export declare function turnFact(database: DatabaseSync, turnSequence: number): TurnFact | null;
@@ -428,6 +428,10 @@ export function latestTurnFactForBody(database, bodySequence) {
428
428
  .get(bodySequence);
429
429
  return row === undefined ? null : decodeTurnRow(row);
430
430
  }
431
+ export function latestTurnFact(database) {
432
+ const latest = database.prepare("SELECT sequence FROM turns ORDER BY sequence DESC LIMIT 1").get();
433
+ return latest === undefined ? null : turnFact(database, latest.sequence);
434
+ }
431
435
  export function turnFact(database, turnSequence) {
432
436
  const row = database
433
437
  .prepare(`SELECT sequence, body_sequence, started_at, end_sequence, outcome, history_id,
@@ -7,13 +7,17 @@ import type { WorldRoot } from "../world.js";
7
7
  * rebuilt from Hearts, and an unavailable cache falls back to direct Soul reads.
8
8
  */
9
9
  export type AkumaLineage = ReadonlyMap<AkumaId, AkumaCaller | null>;
10
+ type LineageObservation = Readonly<{
11
+ edges: AkumaLineage;
12
+ skipped: number;
13
+ }>;
10
14
  export type LineageMember = Readonly<{
11
15
  id: AkumaId;
12
16
  paths: AkumaPaths;
13
17
  }>;
14
18
  export declare function akumaLineageCachePath(world: WorldRoot): string;
15
19
  /** Authoritative lineage read: every known born Soul, with no cache consultation. */
16
- export declare function readDirectAkumaLineage(members: readonly LineageMember[]): Promise<AkumaLineage>;
20
+ export declare function readDirectAkumaLineage(members: readonly LineageMember[]): Promise<LineageObservation>;
17
21
  /**
18
22
  * Discard the disposable record when an offered edge disagrees with a born
19
23
  * Soul. The next caller-scoped answer comes from direct Soul evidence and
@@ -36,4 +40,5 @@ export declare function recordAkumaLineage(world: WorldRoot, soul: Readonly<{
36
40
  * Rows whose Akuma directory no longer exists never join this view, and fresh
37
41
  * edges plus that pruning are written back best-effort.
38
42
  */
39
- export declare function readAkumaLineage(world: WorldRoot, members: readonly LineageMember[]): Promise<AkumaLineage>;
43
+ export declare function readAkumaLineage(world: WorldRoot, members: readonly LineageMember[]): Promise<LineageObservation>;
44
+ export {};
@@ -31,14 +31,14 @@ function readCachedEdge(row) {
31
31
  throw new Error("Akuma lineage cache row has an empty caller");
32
32
  return [akumaId, caller];
33
33
  }
34
- /** A readable cache, an empty map for a cache that was never written, or null when unusable. */
35
- async function readLineageCache(path) {
34
+ /** Decode only current members; obsolete and invalid rows are disposable misses. */
35
+ async function readLineageCache(path, known) {
36
36
  try {
37
37
  await lstat(path);
38
38
  }
39
39
  catch (error) {
40
40
  if (error.code === "ENOENT")
41
- return new Map();
41
+ return { edges: new Map(), stale: [] };
42
42
  return null;
43
43
  }
44
44
  let database;
@@ -53,7 +53,24 @@ async function readLineageCache(path) {
53
53
  try {
54
54
  database.exec("PRAGMA busy_timeout=0");
55
55
  const rows = database.prepare("SELECT aku_id, caller_json FROM lineage").all();
56
- return new Map(rows.map(readCachedEdge));
56
+ const edges = new Map();
57
+ const stale = [];
58
+ for (const row of rows) {
59
+ if (typeof row.aku_id !== "string")
60
+ continue;
61
+ if (known.has(row.aku_id)) {
62
+ try {
63
+ const [id, caller] = readCachedEdge(row);
64
+ edges.set(id, caller);
65
+ continue;
66
+ }
67
+ catch {
68
+ // A malformed current edge is a miss, not a reason to discard peers.
69
+ }
70
+ }
71
+ stale.push(row.aku_id);
72
+ }
73
+ return { edges, stale };
57
74
  }
58
75
  catch {
59
76
  return null;
@@ -76,10 +93,10 @@ async function writeLineageCache(path, fresh, stale, replace = false) {
76
93
  try {
77
94
  if (replace)
78
95
  database.exec("DELETE FROM lineage");
79
- for (const [akumaId, caller] of fresh)
80
- insert.run(akumaId, caller === null ? null : JSON.stringify(caller));
81
96
  for (const akumaId of stale)
82
97
  remove.run(akumaId);
98
+ for (const [akumaId, caller] of fresh)
99
+ insert.run(akumaId, caller === null ? null : JSON.stringify(caller));
83
100
  database.exec("COMMIT");
84
101
  }
85
102
  catch (error) {
@@ -98,16 +115,22 @@ async function writeLineageCache(path, fresh, stale, replace = false) {
98
115
  async function directEdge(member) {
99
116
  try {
100
117
  const soul = await readSoul(member.paths);
118
+ if (soul !== null && soul.id !== member.id)
119
+ throw new Error("Akuma soul does not match its coordinate");
101
120
  return soul === null ? null : [member.id, soul.caller ?? null];
102
121
  }
103
122
  catch {
104
- // A hard Heart read failure stays an omitted member, never an empty roster claim.
105
- return null;
123
+ // Unreadability is not authoritative absence and cannot justify a rebuild.
124
+ return undefined;
106
125
  }
107
126
  }
108
127
  /** Authoritative lineage read: every known born Soul, with no cache consultation. */
109
128
  export async function readDirectAkumaLineage(members) {
110
- return new Map((await boundedMap(members, directEdge)).filter((edge) => edge !== null));
129
+ const observed = await boundedMap(members, directEdge);
130
+ return {
131
+ edges: new Map(observed.filter((edge) => edge !== null && edge !== undefined)),
132
+ skipped: observed.filter((edge) => edge === undefined).length,
133
+ };
111
134
  }
112
135
  /**
113
136
  * Discard the disposable record when an offered edge disagrees with a born
@@ -144,19 +167,20 @@ export async function recordAkumaLineage(world, soul) {
144
167
  */
145
168
  export async function readAkumaLineage(world, members) {
146
169
  const path = akumaLineageCachePath(world);
147
- const cached = await readLineageCache(path);
148
- if (cached === null)
149
- return await readDirectAkumaLineage(members);
150
- const known = new Set(members.map((member) => member.id));
151
- const stale = [...cached.keys()].filter((id) => !known.has(id));
152
- const missing = members.filter((member) => !cached.has(member.id));
153
- const fresh = (await boundedMap(missing, directEdge)).filter((edge) => edge !== null);
154
- // A vanished directory never contributes an edge even if its prune write fails.
155
- for (const id of stale)
156
- cached.delete(id);
157
- for (const [akumaId, caller] of fresh)
158
- cached.set(akumaId, caller);
159
- if (fresh.length > 0 || stale.length > 0)
160
- await writeLineageCache(path, fresh, stale);
161
- return cached;
170
+ const cached = await readLineageCache(path, new Set(members.map((member) => member.id)));
171
+ if (cached === null) {
172
+ const direct = await readDirectAkumaLineage(members);
173
+ if (direct.skipped === 0) {
174
+ await invalidateAkumaLineage(world);
175
+ await rebuildAkumaLineage(world, direct.edges);
176
+ }
177
+ return direct;
178
+ }
179
+ const missing = members.filter((member) => !cached.edges.has(member.id));
180
+ const fresh = await readDirectAkumaLineage(missing);
181
+ for (const [akumaId, caller] of fresh.edges)
182
+ cached.edges.set(akumaId, caller);
183
+ if (fresh.edges.size > 0 || cached.stale.length > 0)
184
+ await writeLineageCache(path, [...fresh.edges], cached.stale);
185
+ return { edges: cached.edges, skipped: fresh.skipped };
162
186
  }
@@ -1,3 +1,4 @@
1
+ import { selectHistoryPage } from "../history.js";
1
2
  import { isAbsolute, relative, resolve, sep } from "node:path";
2
3
  export const DEFAULT_TAIL = 3;
3
4
  const REPORTED_CHANGE_LIMIT = 5;
@@ -180,21 +181,15 @@ export function selectSnapshot(ledger, input) {
180
181
  };
181
182
  }
182
183
  export function selectHistory(ledger, cursor) {
183
- const eligible = ledger.rows.filter((row) => cursor.before !== undefined
184
- ? row.sequence < cursor.before
185
- : cursor.since !== undefined
186
- ? row.sequence > cursor.since
187
- : true);
188
- const rows = cursor.since !== undefined ? eligible.slice(0, cursor.limit) : eligible.slice(-cursor.limit);
189
- const omitted = Math.max(0, eligible.length - rows.length);
184
+ const { rows, omitted } = selectHistoryPage(ledger.rows, (row) => row.sequence, cursor);
190
185
  const historyLost = cursor.since !== undefined
191
186
  ? ledger.rows[0] !== undefined && ledger.rows[0].sequence > cursor.since + 1
192
187
  : ledger.retained.lowestRetained !== null && ledger.retained.lowestRetained > 1 && omitted === 0;
193
188
  return {
194
189
  rows,
195
190
  omitted,
196
- hasEarlier: cursor.since === undefined && eligible.length > rows.length,
197
- hasLater: cursor.since !== undefined && eligible.length > rows.length,
191
+ hasEarlier: cursor.since === undefined && omitted > 0,
192
+ hasLater: cursor.since !== undefined && omitted > 0,
198
193
  historyLost,
199
194
  lowestRetained: ledger.retained.lowestRetained,
200
195
  highest: ledger.retained.highest,