pi-legion 0.16.0 → 2.0.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 (89) hide show
  1. package/CONTRIBUTING.md +58 -0
  2. package/README.md +313 -640
  3. package/agents/advisor.md +7 -5
  4. package/agents/centurion.md +53 -0
  5. package/agents/designer.md +33 -33
  6. package/agents/planner.md +1 -2
  7. package/agents/prototype.md +2 -2
  8. package/agents/reviewer.md +67 -31
  9. package/agents/scout.md +6 -2
  10. package/agents/worker.md +12 -3
  11. package/docs/contracts/esc-abort-v1.md +131 -0
  12. package/docs/contracts/esc-cascade-v2.md +100 -0
  13. package/docs/design.md +44 -25
  14. package/docs/legion-v2-contract.md +461 -0
  15. package/docs/legion-v2-delivery.md +62 -0
  16. package/docs/retire-hardening-contract.md +125 -0
  17. package/docs/subagents-teams.md +76 -0
  18. package/docs/tui-viewer-contract.md +276 -0
  19. package/docs/vexillatio-contract.md +162 -0
  20. package/index.ts +1462 -286
  21. package/package.json +12 -9
  22. package/skills/pi-legion/SKILL.md +74 -96
  23. package/src/agents/agents.ts +6 -11
  24. package/src/agents/overrides.ts +2 -1
  25. package/src/agents/paths.ts +1 -1
  26. package/src/agents/settings.ts +268 -20
  27. package/src/api.ts +47 -48
  28. package/src/{herdr → backends/legacy}/client.ts +14 -69
  29. package/src/{shared → backends/legacy}/cursor-chat.ts +2 -2
  30. package/src/{herdr → backends/legacy}/runner.ts +22 -9
  31. package/src/backends/legacy/types.ts +138 -0
  32. package/src/extension/auto-doctor.ts +144 -0
  33. package/src/extension/budget.ts +2 -2
  34. package/src/extension/child-guard.ts +214 -201
  35. package/src/extension/event-bus.ts +263 -0
  36. package/src/extension/legion-commands.ts +719 -0
  37. package/src/extension/legion-doctor.ts +888 -0
  38. package/src/extension/legion-stop.ts +150 -0
  39. package/src/extension/legion-tools.ts +816 -0
  40. package/src/extension/notify.ts +24 -19
  41. package/src/extension/playbook.ts +20 -89
  42. package/src/extension/recycle.ts +2 -7
  43. package/src/extension/runtime.ts +655 -105
  44. package/src/extension/scout-guard.ts +483 -0
  45. package/src/extension/slash.ts +89 -438
  46. package/src/extension/spawn-hints.ts +79 -0
  47. package/src/extension/summary.ts +17 -58
  48. package/src/legion/budget.ts +165 -0
  49. package/src/legion/db.ts +242 -0
  50. package/src/legion/events.ts +150 -0
  51. package/src/legion/mail.ts +412 -0
  52. package/src/legion/nodes.ts +461 -0
  53. package/src/legion/rebuild.ts +533 -0
  54. package/src/legion/state-machine.ts +313 -0
  55. package/src/legion/usage.ts +101 -0
  56. package/src/runs/acceptance.ts +82 -25
  57. package/src/runs/args.ts +51 -5
  58. package/src/runs/hygiene.ts +335 -0
  59. package/src/runs/orchestrator.ts +790 -1683
  60. package/src/runs/owner.ts +61 -0
  61. package/src/runs/provision.ts +135 -0
  62. package/src/runs/store.ts +44 -17
  63. package/src/runs/verify-queue.ts +195 -0
  64. package/src/shared/name.ts +29 -0
  65. package/src/shared/output-cap.ts +57 -0
  66. package/src/shared/progress.ts +57 -135
  67. package/src/shared/session.ts +243 -171
  68. package/src/shared/types.ts +107 -208
  69. package/src/supervisor/child-memory.ts +140 -0
  70. package/src/supervisor/proc-tree.ts +103 -0
  71. package/src/supervisor/rpc-supervisor.ts +1033 -0
  72. package/src/supervisor/types.ts +153 -0
  73. package/src/supervisor/ui-proxy.ts +226 -0
  74. package/src/tui/chat-items.ts +330 -0
  75. package/src/tui/live-overlay.ts +874 -0
  76. package/src/tui/status.ts +553 -27
  77. package/src/tui/tree-view.ts +808 -0
  78. package/src/tui/viz/canvas.ts +119 -0
  79. package/src/tui/viz/layout.ts +111 -0
  80. package/src/tui/viz/model.ts +123 -0
  81. package/src/tui/viz/palette.ts +188 -0
  82. package/src/tui/viz/panels.ts +530 -0
  83. package/src/tui/viz/railway.ts +313 -0
  84. package/src/tui/viz/rate.ts +211 -0
  85. package/src/tui/viz/view.ts +228 -0
  86. package/src/extension/parent-label.ts +0 -115
  87. package/src/profiles/classify.ts +0 -375
  88. package/src/profiles/profiles.ts +0 -730
  89. package/src/runs/layout.ts +0 -258
@@ -0,0 +1,79 @@
1
+ /**
2
+ * Hints appended to child spawn failures, and a ring buffer of recent failures
3
+ * so `/legion doctor` / `subagent action=diagnose` can show what just broke.
4
+ */
5
+
6
+ export interface SpawnFailureRecord {
7
+ ts: number;
8
+ name: string;
9
+ message: string;
10
+ stderr?: string;
11
+ hadNoExtensions?: boolean;
12
+ }
13
+
14
+ const MAX_FAILURES = 8;
15
+ const recentFailures: SpawnFailureRecord[] = [];
16
+
17
+ export function recordSpawnFailure(entry: Omit<SpawnFailureRecord, "ts"> & { ts?: number }): void {
18
+ recentFailures.unshift({ ts: entry.ts ?? Date.now(), ...entry });
19
+ if (recentFailures.length > MAX_FAILURES) recentFailures.length = MAX_FAILURES;
20
+ }
21
+
22
+ export function recentSpawnFailures(): readonly SpawnFailureRecord[] {
23
+ return recentFailures;
24
+ }
25
+
26
+ /** Test helper. */
27
+ export function clearSpawnFailures(): void {
28
+ recentFailures.length = 0;
29
+ }
30
+
31
+ const MODEL_NOT_FOUND =
32
+ /Model\s+"[^"]+"\s+not found|No models available|Use --list-models/i;
33
+
34
+ export function looksLikeMissingModel(stderr: string | undefined): boolean {
35
+ return Boolean(stderr && MODEL_NOT_FOUND.test(stderr));
36
+ }
37
+
38
+ /**
39
+ * When a child dies because its model/provider is invisible under
40
+ * `--no-extensions`, point at the escape hatches and `/legion doctor`.
41
+ */
42
+ export function spawnFailureHint(input: {
43
+ stderr?: string;
44
+ args?: readonly string[];
45
+ }): string | undefined {
46
+ if (!looksLikeMissingModel(input.stderr)) return undefined;
47
+ const noExt = input.args?.includes("--no-extensions") ?? true;
48
+ if (!noExt) {
49
+ return (
50
+ "Hint: the child could not resolve that model. Run `/legion doctor` " +
51
+ "(or `subagent action=diagnose`) and compare host vs child model lists."
52
+ );
53
+ }
54
+ return (
55
+ "Hint: children start with `--no-extensions`, so host packages that register " +
56
+ "providers (e.g. `pi-any-endpoint`) are not loaded. The model works in the " +
57
+ "parent but is unknown to the child.\n" +
58
+ "Fix: set `PI_LEGION_CHILD_EXTENSIONS` to the provider extension path(s), " +
59
+ "add them under the role's `extensions:` frontmatter, or set " +
60
+ "`inheritExtensions: true` / `PI_LEGION_CHILD_INHERIT_EXTENSIONS=1` " +
61
+ "(costs more memory). Run `/legion doctor` or `subagent action=diagnose` for paths."
62
+ );
63
+ }
64
+
65
+ /** Short hint only. Spawn paths use `enrichFailureWithAutoDoctor` for auto snippets. */
66
+ export function withSpawnFailureHint(message: string, input: {
67
+ stderr?: string;
68
+ args?: readonly string[];
69
+ name?: string;
70
+ }): string {
71
+ const hint = spawnFailureHint(input);
72
+ recordSpawnFailure({
73
+ name: input.name ?? "?",
74
+ message,
75
+ stderr: input.stderr,
76
+ hadNoExtensions: input.args?.includes("--no-extensions"),
77
+ });
78
+ return hint ? `${message}\n\n${hint}` : message;
79
+ }
@@ -24,7 +24,7 @@ import type {
24
24
  TaskState,
25
25
  Usage,
26
26
  } from "../shared/types.ts";
27
- import { sendSlashText } from "./slash.ts";
27
+ import { sendSlashText, type LegionSubcommand } from "./slash.ts";
28
28
 
29
29
  const RUNNING_STATES: ReadonlySet<TaskState> = new Set([
30
30
  "working",
@@ -41,7 +41,7 @@ const OUTCOME_ORDER: readonly ExecutionStatus[] = [
41
41
  "unknown",
42
42
  ];
43
43
 
44
- const SUMMARY_USAGE = "Usage: /subagents-summary [--all] [<name>]";
44
+ const SUMMARY_USAGE = "Usage: /legion summary [--all] [<name>]";
45
45
 
46
46
  /** Session data supplied by the command layer to the pure aggregator. */
47
47
  export type SummarySession = ParsedSession;
@@ -105,7 +105,6 @@ export interface SubagentSummary {
105
105
  export interface SummaryFormatOptions {
106
106
  /** Used only by the empty-state message and relative session paths. */
107
107
  cwd?: string;
108
- parentPaneId?: string;
109
108
  }
110
109
 
111
110
  export interface SummaryDetailInput {
@@ -117,8 +116,8 @@ export interface SummaryDetailInput {
117
116
  }
118
117
 
119
118
  /**
120
- * Return the role used for grouping. Herdr's `kind` is intentionally not used:
121
- * several CLI kinds can be launched for the same logical role.
119
+ * Return the role used for grouping. Child execution kind is intentionally not
120
+ * used: one logical role may be relaunched under the same run record.
122
121
  */
123
122
  export function summaryRole(child: Pick<ChildRecord, "agent" | "name">): string {
124
123
  const role = child.agent ?? child.name.replace(/-\d+$/, "");
@@ -328,7 +327,7 @@ function incrementOutcome(
328
327
 
329
328
  function outcomeForChild(child: SummaryChild): ExecutionStatus | null {
330
329
  if (child.running) {
331
- // An awaiting pane may retain a terminal execution snapshot while its
330
+ // An awaiting child may retain a terminal execution snapshot while its
332
331
  // process is still open. Count that status as well as running. Working
333
332
  // and blocked snapshots are stale lifecycle data, so do not present them
334
333
  // as terminal outcomes.
@@ -571,10 +570,7 @@ export function formatSubagentSummary(
571
570
  ): string {
572
571
  if (summary.childCount === 0) {
573
572
  const cwd = options.cwd ?? summary.cwd ?? process.cwd();
574
- const parent = options.parentPaneId?.trim();
575
- return parent
576
- ? `No subagent runs under this session (parent pane ${parent}).\nLaunch children with the subagent tool to see them here.`
577
- : `No subagent runs under ${cwd}.\nLaunch children with the subagent tool to see them here.`;
573
+ return `No subagent runs under ${cwd}.\nLaunch children with the subagent tool to see them here.`;
578
574
  }
579
575
 
580
576
  const start = formatLocalTime(summary.earliestSpawnedAtMs);
@@ -621,12 +617,7 @@ export function formatSubagentDetail(input: SummaryDetailInput): string {
621
617
  if (child.thinking !== undefined) stateBits.push(`thinking: ${child.thinking}`);
622
618
  const lines = [title, ` ${stateBits.join(" · ")}`];
623
619
 
624
- const runBits = [`run: ${run.runId}`];
625
- if (child.paneId !== undefined) {
626
- runBits.push(`pane: ${child.paneId ?? "(recycled)"}`);
627
- }
628
- const tabId = child.tabId ?? run.herdr.tabId;
629
- if (tabId) runBits.push(`tab: ${tabId}`);
620
+ const runBits = [`run: ${run.runId}`, `supervisor: ${run.herdr.supervisor ?? "legacy"}`];
630
621
  lines.push(` ${runBits.join(" · ")}`);
631
622
 
632
623
  const startedAtMs = parseTimestamp(child.spawnedAt);
@@ -680,13 +671,8 @@ function parseSummaryArgs(
680
671
  return { ok: true, all, ...(name ? { name } : {}) };
681
672
  }
682
673
 
683
- function filteredRuns(
684
- runs: readonly RunRecord[],
685
- parentPaneId: string | undefined,
686
- all: boolean,
687
- ): RunRecord[] {
688
- if (all || !parentPaneId) return [...runs];
689
- return runs.filter((run) => run.herdr.parentPaneId === parentPaneId);
674
+ function filteredRuns(runs: readonly RunRecord[], _all: boolean): RunRecord[] {
675
+ return [...runs];
690
676
  }
691
677
 
692
678
  function sessionMapFor(runs: readonly RunRecord[]): Map<string, SummarySession> {
@@ -703,7 +689,7 @@ function sessionMapFor(runs: readonly RunRecord[]): Map<string, SummarySession>
703
689
 
704
690
  function completionRuns(cwd: string, all: boolean): RunRecord[] {
705
691
  const store = new RunStore({ rootDir: path.join(cwd, ".pi-subagents") });
706
- return filteredRuns(store.listRuns(), process.env.HERDR_PANE_ID?.trim(), all);
692
+ return filteredRuns(store.listRuns(), all);
707
693
  }
708
694
 
709
695
  function summaryCompletions(
@@ -739,10 +725,10 @@ function notifyUnknownChild(
739
725
  );
740
726
  }
741
727
 
742
- /** Register /subagents-summary on the host Pi extension. */
743
- export function registerSummaryCommand(pi: ExtensionAPI): void {
728
+ /** Build the `/legion summary [--all] [<name>]` handler. */
729
+ export function createSummaryCommand(pi: ExtensionAPI): LegionSubcommand {
744
730
  let completionCwd = process.cwd();
745
- pi.registerCommand("subagents-summary", {
731
+ return {
746
732
  description: "Summarize subagent runs under the current session",
747
733
  getArgumentCompletions: (prefix) => summaryCompletions(prefix, completionCwd),
748
734
  handler: async (args, ctx) => {
@@ -752,38 +738,14 @@ export function registerSummaryCommand(pi: ExtensionAPI): void {
752
738
  ctx.ui.notify(parsed.message, "error");
753
739
  return;
754
740
  }
755
- const parentPaneId = process.env.HERDR_PANE_ID?.trim() || undefined;
756
741
  const store = new RunStore({
757
742
  rootDir: path.join(ctx.cwd, ".pi-subagents"),
758
743
  });
759
- const runs = filteredRuns(store.listRuns(), parentPaneId, parsed.all);
744
+ const runs = filteredRuns(store.listRuns(), parsed.all);
760
745
  const sessions = sessionMapFor(runs);
761
746
  const now = Date.now();
762
747
  if (parsed.name) {
763
- // Without a pane id the lookup cannot be scoped to this session, and
764
- // pickChildByName prefers a LIVE child over the newest run — a name
765
- // shared with another parent would silently show that parent's child.
766
- // Flag the ambiguity instead of guessing.
767
- const scope = parentPaneId && !parsed.all ? { parentPaneId } : undefined;
768
- const picked = pickChildByName(runs, parsed.name, scope);
769
- if (!picked) {
770
- notifyUnknownChild(ctx, parsed.name);
771
- return;
772
- }
773
- if (
774
- !scope &&
775
- new Set(
776
- runs
777
- .filter((r) => r.children.some((c) => c.name === parsed.name))
778
- .map((r) => r.herdr.parentPaneId),
779
- ).size > 1
780
- ) {
781
- ctx.ui.notify(
782
- `"${parsed.name}" exists under multiple parent panes and this session has no HERDR_PANE_ID; showing the live/newest match. Run with --all to see every run.`,
783
- "error",
784
- );
785
- return;
786
- }
748
+ const picked = pickChildByName(runs, parsed.name);
787
749
  if (!picked) {
788
750
  notifyUnknownChild(ctx, parsed.name);
789
751
  return;
@@ -803,11 +765,8 @@ export function registerSummaryCommand(pi: ExtensionAPI): void {
803
765
  const summary = aggregateSubagentRuns(runs, { now, sessions });
804
766
  sendSlashText(
805
767
  pi,
806
- formatSubagentSummary(summary, {
807
- cwd: ctx.cwd,
808
- ...(!parsed.all && parentPaneId ? { parentPaneId } : {}),
809
- }),
768
+ formatSubagentSummary(summary, { cwd: ctx.cwd }),
810
769
  );
811
770
  },
812
- });
771
+ };
813
772
  }
@@ -0,0 +1,165 @@
1
+ import type { DatabaseSync } from "./db.ts";
2
+ import { withTransaction } from "./db.ts";
3
+ import { appendEvent } from "./events.ts";
4
+
5
+ export const DEFAULT_LEGION_BUDGETS = {
6
+ maxDepth: 4,
7
+ maxChildrenPerNode: 8,
8
+ maxActiveNodes: 30,
9
+ } as const;
10
+
11
+ export type LegionBudgetLimits = {
12
+ maxDepth?: number;
13
+ maxChildrenPerNode?: number;
14
+ maxActiveNodes?: number;
15
+ };
16
+
17
+ export interface NormalizedBudgetLimits {
18
+ maxDepth: number;
19
+ maxChildrenPerNode: number;
20
+ maxActiveNodes: number;
21
+ }
22
+
23
+ export type BudgetRefusalReason =
24
+ | "max_depth"
25
+ | "max_children_per_node"
26
+ | "max_active_nodes"
27
+ | "parent_not_found";
28
+
29
+ export interface LaunchBudgetRequest {
30
+ parentId: string | null;
31
+ depth: number;
32
+ nodeId?: string;
33
+ }
34
+
35
+ export type BudgetDecision =
36
+ | { allowed: true; depth: number; activeNodes: number; children: number; limits: NormalizedBudgetLimits }
37
+ | {
38
+ allowed: false;
39
+ reason: BudgetRefusalReason;
40
+ message: string;
41
+ depth: number;
42
+ activeNodes: number;
43
+ children: number;
44
+ limits: NormalizedBudgetLimits;
45
+ };
46
+
47
+ export interface BudgetCheckOptions {
48
+ limits?: LegionBudgetLimits;
49
+ }
50
+
51
+ export interface BudgetGateOptions extends BudgetCheckOptions {
52
+ now?: () => number;
53
+ }
54
+
55
+ export type BudgetGateResult<T> =
56
+ | { allowed: true; decision: Extract<BudgetDecision, { allowed: true }>; value: T }
57
+ | { allowed: false; decision: Extract<BudgetDecision, { allowed: false }> };
58
+
59
+ /** Read-only check of all three governance gates with one SELECT. */
60
+ export function checkLaunchBudget(
61
+ db: DatabaseSync,
62
+ request: LaunchBudgetRequest,
63
+ options: BudgetCheckOptions = {},
64
+ ): BudgetDecision {
65
+ validateRequest(request);
66
+ const limits = normalizeLimits(options.limits);
67
+ const row = db
68
+ .prepare(
69
+ `SELECT
70
+ (SELECT COUNT(*) FROM nodes WHERE parent_id IS ?) AS child_count,
71
+ (SELECT COUNT(*) FROM nodes WHERE status IN ('running', 'starting')) AS active_count,
72
+ CASE WHEN ? IS NULL THEN 1 ELSE EXISTS(SELECT 1 FROM nodes WHERE id = ?) END AS parent_exists`,
73
+ )
74
+ .get(request.parentId, request.parentId, request.parentId);
75
+ const counts = {
76
+ children: Number(row?.child_count ?? 0),
77
+ activeNodes: Number(row?.active_count ?? 0),
78
+ };
79
+ const base = { depth: request.depth, ...counts, limits };
80
+ if (Number(row?.parent_exists ?? 0) !== 1) {
81
+ return denied("parent_not_found", `parent node does not exist: ${request.parentId}`, base);
82
+ }
83
+ if (request.depth > limits.maxDepth) {
84
+ return denied("max_depth", `node depth ${request.depth} exceeds maxDepth ${limits.maxDepth}`, base);
85
+ }
86
+ if (counts.children >= limits.maxChildrenPerNode) {
87
+ return denied(
88
+ "max_children_per_node",
89
+ `parent already has ${counts.children} children; maxChildrenPerNode is ${limits.maxChildrenPerNode}`,
90
+ base,
91
+ );
92
+ }
93
+ if (counts.activeNodes >= limits.maxActiveNodes) {
94
+ return denied(
95
+ "max_active_nodes",
96
+ `tree already has ${counts.activeNodes} active nodes; maxActiveNodes is ${limits.maxActiveNodes}`,
97
+ base,
98
+ );
99
+ }
100
+ return { allowed: true, ...base };
101
+ }
102
+
103
+ /** Hold a write reservation over check+insert to prevent concurrent over-allocation. */
104
+ export function withLaunchBudget<T>(
105
+ db: DatabaseSync,
106
+ request: LaunchBudgetRequest,
107
+ createNode: (decision: Extract<BudgetDecision, { allowed: true }>) => T,
108
+ options: BudgetGateOptions = {},
109
+ ): BudgetGateResult<T> {
110
+ const clock = options.now ?? (() => Date.now());
111
+ const timestamp = clock();
112
+ if (!Number.isFinite(timestamp)) throw new TypeError("budget clock must return a finite timestamp");
113
+ return withTransaction(db, () => {
114
+ const decision = checkLaunchBudget(db, request, options);
115
+ if (!decision.allowed) {
116
+ appendEvent(
117
+ db,
118
+ request.nodeId ?? request.parentId ?? "root",
119
+ "budget_refused",
120
+ {
121
+ reason: decision.reason,
122
+ message: decision.message,
123
+ depth: decision.depth,
124
+ activeNodes: decision.activeNodes,
125
+ children: decision.children,
126
+ limits: decision.limits,
127
+ },
128
+ { now: () => timestamp },
129
+ );
130
+ return { allowed: false, decision };
131
+ }
132
+ return { allowed: true, decision, value: createNode(decision) };
133
+ });
134
+ }
135
+
136
+ function denied(
137
+ reason: BudgetRefusalReason,
138
+ message: string,
139
+ base: Omit<Extract<BudgetDecision, { allowed: true }>, "allowed">,
140
+ ): Extract<BudgetDecision, { allowed: false }> {
141
+ return { allowed: false, reason, message, ...base };
142
+ }
143
+
144
+ function normalizeLimits(limits: LegionBudgetLimits | undefined): NormalizedBudgetLimits {
145
+ const normalized = {
146
+ maxDepth: limits?.maxDepth ?? DEFAULT_LEGION_BUDGETS.maxDepth,
147
+ maxChildrenPerNode: limits?.maxChildrenPerNode ?? DEFAULT_LEGION_BUDGETS.maxChildrenPerNode,
148
+ maxActiveNodes: limits?.maxActiveNodes ?? DEFAULT_LEGION_BUDGETS.maxActiveNodes,
149
+ };
150
+ for (const [name, value] of Object.entries(normalized)) {
151
+ if (!Number.isSafeInteger(value) || value < 0) {
152
+ throw new TypeError(`${name} must be a non-negative safe integer`);
153
+ }
154
+ }
155
+ return normalized;
156
+ }
157
+
158
+ function validateRequest(request: LaunchBudgetRequest): void {
159
+ if (request.parentId !== null && (typeof request.parentId !== "string" || !request.parentId)) {
160
+ throw new TypeError("parentId must be null or a non-empty string");
161
+ }
162
+ if (!Number.isSafeInteger(request.depth) || request.depth < 0) {
163
+ throw new TypeError("depth must be a non-negative safe integer");
164
+ }
165
+ }
@@ -0,0 +1,242 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import { createRequire } from "node:module";
4
+
5
+ export const LEGION_DB_USER_VERSION = 1;
6
+ export const LEGION_DB_BUSY_TIMEOUT_MS = 5_000;
7
+
8
+ export type SqliteBindValue = string | number | bigint | null | Uint8Array;
9
+ export type SqliteRow = Record<string, string | number | bigint | null | Uint8Array>;
10
+
11
+ export interface LegionStatementSync {
12
+ /**
13
+ * Fetch one row. Node's `node:sqlite` returns `undefined` on a miss;
14
+ * Bun's `bun:sqlite` returns `null`. Callers must treat both as absent
15
+ * (see {@link sqliteHasRow}).
16
+ */
17
+ get(...parameters: SqliteBindValue[]): SqliteRow | null | undefined;
18
+ all(...parameters: SqliteBindValue[]): SqliteRow[];
19
+ run(...parameters: SqliteBindValue[]): {
20
+ changes: number | bigint;
21
+ lastInsertRowid: number | bigint;
22
+ };
23
+ }
24
+
25
+ /** Minimal synchronous SQL interface shared by Bun and Node SQLite drivers. */
26
+ export interface DatabaseSync {
27
+ exec(sql: string): void;
28
+ prepare(sql: string): LegionStatementSync;
29
+ close(): void;
30
+ }
31
+
32
+ type SqliteDatabaseConstructor = new (dbPath: string) => DatabaseSync;
33
+ type SqliteModule = Record<string, unknown>;
34
+ type SqliteDriver = {
35
+ id: "bun:sqlite" | "node:sqlite";
36
+ constructorName: "Database" | "DatabaseSync";
37
+ };
38
+ const SQLITE_DRIVERS: readonly SqliteDriver[] = [
39
+ { id: "bun:sqlite", constructorName: "Database" },
40
+ { id: "node:sqlite", constructorName: "DatabaseSync" },
41
+ ];
42
+ let cachedSqliteConstructor: SqliteDatabaseConstructor | null | undefined;
43
+ const transactionDepth = new WeakMap<DatabaseSync, number>();
44
+ let savepointSequence = 0;
45
+
46
+ const SCHEMA_V1 = `
47
+ CREATE TABLE nodes (
48
+ id TEXT PRIMARY KEY,
49
+ parent_id TEXT REFERENCES nodes(id),
50
+ name TEXT NOT NULL,
51
+ role TEXT NOT NULL,
52
+ kind TEXT NOT NULL DEFAULT 'pi',
53
+ depth INTEGER NOT NULL,
54
+ run_id TEXT,
55
+ session_file TEXT,
56
+ worktree_path TEXT,
57
+ model TEXT,
58
+ team TEXT,
59
+ status TEXT NOT NULL,
60
+ phase TEXT,
61
+ phase_since INTEGER,
62
+ rework_count INTEGER NOT NULL DEFAULT 0,
63
+ contract_path TEXT,
64
+ task_summary TEXT,
65
+ created_at INTEGER NOT NULL,
66
+ updated_at INTEGER NOT NULL
67
+ );
68
+ CREATE INDEX idx_nodes_parent ON nodes(parent_id);
69
+ CREATE INDEX idx_nodes_status ON nodes(status, updated_at);
70
+
71
+ CREATE TABLE events (
72
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
73
+ node_id TEXT NOT NULL,
74
+ type TEXT NOT NULL,
75
+ data TEXT,
76
+ ts INTEGER NOT NULL
77
+ );
78
+ CREATE INDEX idx_events_node ON events(node_id, id);
79
+ CREATE INDEX idx_events_type_ts ON events(type, ts);
80
+
81
+ CREATE TABLE usage (
82
+ node_id TEXT PRIMARY KEY REFERENCES nodes(id),
83
+ tokens_in INTEGER NOT NULL DEFAULT 0,
84
+ tokens_out INTEGER NOT NULL DEFAULT 0,
85
+ cost_usd REAL NOT NULL DEFAULT 0,
86
+ updated_at INTEGER
87
+ );
88
+
89
+ CREATE TABLE messages (
90
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
91
+ from_node TEXT NOT NULL,
92
+ to_node TEXT NOT NULL,
93
+ subject TEXT NOT NULL,
94
+ body TEXT NOT NULL,
95
+ kind TEXT,
96
+ urgency TEXT NOT NULL DEFAULT 'info',
97
+ delivered INTEGER NOT NULL DEFAULT 0,
98
+ delivered_at INTEGER,
99
+ created_at INTEGER NOT NULL
100
+ );
101
+ CREATE INDEX idx_messages_inbox ON messages(to_node, delivered, id);
102
+ `;
103
+
104
+ /**
105
+ * True when a prepared-statement `.get()` returned a real row.
106
+ * Bun returns `null` for no match; Node returns `undefined` — both are misses.
107
+ */
108
+ export function sqliteHasRow(row: SqliteRow | null | undefined): boolean {
109
+ return row != null;
110
+ }
111
+
112
+ /** Resolve the tree ledger location specified by contract §4.1. */
113
+ export function legionDbPath(rootRunDir: string): string {
114
+ if (typeof rootRunDir !== "string" || rootRunDir.trim().length === 0) {
115
+ throw new TypeError("rootRunDir must be a non-empty path");
116
+ }
117
+ return path.join(rootRunDir, "legion.db");
118
+ }
119
+
120
+ /**
121
+ * Open one supervisor's connection to the shared tree ledger. SQLite is loaded
122
+ * lazily so importing the extension does not require a driver until v2 is used.
123
+ */
124
+ export function openLegionDb(dbPath: string): DatabaseSync {
125
+ if (typeof dbPath !== "string" || dbPath.trim().length === 0) {
126
+ throw new TypeError("dbPath must be a non-empty path");
127
+ }
128
+ if (dbPath !== ":memory:") {
129
+ fs.mkdirSync(path.dirname(path.resolve(dbPath)), { recursive: true });
130
+ }
131
+ const Database = sqliteDatabaseConstructor();
132
+ const db = new Database(dbPath);
133
+ try {
134
+ db.exec(`PRAGMA busy_timeout = ${LEGION_DB_BUSY_TIMEOUT_MS};`);
135
+ db.exec("PRAGMA foreign_keys = ON;");
136
+ db.exec("PRAGMA journal_mode = WAL;");
137
+ migrate(db);
138
+ return db;
139
+ } catch (error) {
140
+ db.close();
141
+ throw error;
142
+ }
143
+ }
144
+
145
+ /** Run a short synchronous write transaction. Nested ledger helpers use savepoints. */
146
+ export function withTransaction<T>(db: DatabaseSync, run: () => T): T {
147
+ const depth = transactionDepth.get(db) ?? 0;
148
+ const savepoint = depth > 0 ? `legion_nested_${++savepointSequence}` : null;
149
+ db.exec(savepoint ? `SAVEPOINT ${savepoint};` : "BEGIN IMMEDIATE;");
150
+ transactionDepth.set(db, depth + 1);
151
+ try {
152
+ const result = run();
153
+ db.exec(savepoint ? `RELEASE SAVEPOINT ${savepoint};` : "COMMIT;");
154
+ return result;
155
+ } catch (error) {
156
+ try {
157
+ if (savepoint) {
158
+ db.exec(`ROLLBACK TO SAVEPOINT ${savepoint};`);
159
+ db.exec(`RELEASE SAVEPOINT ${savepoint};`);
160
+ } else {
161
+ db.exec("ROLLBACK;");
162
+ }
163
+ } catch {
164
+ // Preserve the original error if SQLite has already ended the transaction.
165
+ }
166
+ throw error;
167
+ } finally {
168
+ if (depth === 0) transactionDepth.delete(db);
169
+ else transactionDepth.set(db, depth);
170
+ }
171
+ }
172
+
173
+ function migrate(db: DatabaseSync): void {
174
+ let version = readUserVersion(db);
175
+ if (version > LEGION_DB_USER_VERSION) {
176
+ throw new Error(
177
+ `legion.db schema version ${version} is newer than supported version ${LEGION_DB_USER_VERSION}`,
178
+ );
179
+ }
180
+ if (version === LEGION_DB_USER_VERSION) return;
181
+
182
+ db.exec("BEGIN IMMEDIATE;");
183
+ try {
184
+ // A supervisor can wait here while another connection creates schema v1.
185
+ version = readUserVersion(db);
186
+ if (version > LEGION_DB_USER_VERSION) {
187
+ throw new Error(
188
+ `legion.db schema version ${version} is newer than supported version ${LEGION_DB_USER_VERSION}`,
189
+ );
190
+ }
191
+ if (version === 0) {
192
+ db.exec(SCHEMA_V1);
193
+ db.exec(`PRAGMA user_version = ${LEGION_DB_USER_VERSION};`);
194
+ }
195
+ db.exec("COMMIT;");
196
+ } catch (error) {
197
+ try {
198
+ db.exec("ROLLBACK;");
199
+ } catch {
200
+ // Preserve the original migration error.
201
+ }
202
+ throw error;
203
+ }
204
+ }
205
+
206
+ function sqliteDatabaseConstructor(): SqliteDatabaseConstructor {
207
+ if (cachedSqliteConstructor) return cachedSqliteConstructor;
208
+ let required: (id: string) => SqliteModule;
209
+ try {
210
+ required = createRequire(import.meta.url) as (id: string) => SqliteModule;
211
+ } catch (error) {
212
+ throw new Error("cannot create a lazy require for the SQLite driver", { cause: error });
213
+ }
214
+ const bunRuntime = (globalThis as typeof globalThis & { Bun?: unknown }).Bun;
215
+ const orderedDrivers = bunRuntime ? SQLITE_DRIVERS : [...SQLITE_DRIVERS].reverse();
216
+ const failures: Error[] = [];
217
+ for (const driver of orderedDrivers) {
218
+ let moduleValue: SqliteModule;
219
+ try {
220
+ moduleValue = required(driver.id);
221
+ } catch (error) {
222
+ failures.push(new Error(`SQLite driver ${driver.id} is unavailable`, { cause: error }));
223
+ continue;
224
+ }
225
+ const constructor = moduleValue[driver.constructorName];
226
+ if (typeof constructor !== "function") {
227
+ failures.push(
228
+ new TypeError(`SQLite driver ${driver.id} does not export ${driver.constructorName}`),
229
+ );
230
+ continue;
231
+ }
232
+ cachedSqliteConstructor = constructor as SqliteDatabaseConstructor;
233
+ return cachedSqliteConstructor;
234
+ }
235
+ cachedSqliteConstructor = null;
236
+ throw new AggregateError(failures, "no supported synchronous SQLite driver is available");
237
+ }
238
+
239
+ function readUserVersion(db: DatabaseSync): number {
240
+ const row = db.prepare("PRAGMA user_version;").get();
241
+ return Number(row?.user_version ?? 0);
242
+ }