minicode-ai 0.11.1 → 0.13.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 (221) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -71
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +2 -2
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +52 -19
  184. package/src/ui/i18n/en.ts +58 -6
  185. package/src/ui/i18n/id.ts +58 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +507 -169
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -169
  221. package/docs/USAGE.md +0 -11
@@ -0,0 +1,165 @@
1
+ // PHASE 6T — SCHEDULING POLICY.
2
+ //
3
+ // TaskGraph answers: WHAT IS READY?
4
+ // This module answers: WHICH of those, NOW?
5
+ //
6
+ // [DESIGN DECISION] The boundary is drawn so that readiness is never recomputed
7
+ // here. `selectTask` receives an already-ordered list of ready ids and applies
8
+ // ORDERING ONLY. A second implementation of "ready" is the classic way a
9
+ // scheduler starts disagreeing with its own graph about what is runnable, and
10
+ // the disagreement is invisible until it strands work.
11
+
12
+ import type { TaskSnapshot } from "./model.ts"
13
+
14
+ /**
15
+ * [FACT] The order TaskGraph already publishes.
16
+ *
17
+ * `graph.ts:63-67` — `compareNodes` sorts by `order` ASC, then `id` ASC as a
18
+ * deterministic tiebreak, and `readyTasks()` walks that order. The Scheduler has
19
+ * always taken `ready[0]`, so this was never an accident of implementation: it
20
+ * has been this policy since 6C, just unnamed.
21
+ */
22
+ export type SelectionPolicy = "ORDER_ASC_THEN_ID_ASC"
23
+
24
+ /** The only selection policy. Present as a union so adding one is a type error. */
25
+ export const SELECTION_POLICY: SelectionPolicy = "ORDER_ASC_THEN_ID_ASC"
26
+
27
+ export interface SelectionResult {
28
+ readonly taskId: string | null
29
+ readonly policy: SelectionPolicy
30
+ /** Why nothing was selected. Distinguishes "no work" from "no eligible work". */
31
+ readonly reason: "selected" | "no-ready-tasks" | "unreadable"
32
+ }
33
+
34
+ /**
35
+ * [PHASE 6T] Choose the task to run.
36
+ *
37
+ * @param ready Already-ordered ready ids. NOT re-derived, NOT filtered, NOT
38
+ * reordered. Whatever TaskGraph said is what this sees.
39
+ * @param snapshot Used ONLY to prove a selected id is still claimable in the
40
+ * currency the graph was built from. It is deliberately not used to
41
+ * substitute a different task: that would be selection policy silently
42
+ * becoming readiness policy.
43
+ */
44
+ export function selectTask(ready: readonly string[], snapshot: TaskSnapshot): SelectionResult {
45
+ if (ready.length === 0) {
46
+ return { taskId: null, policy: SELECTION_POLICY, reason: "no-ready-tasks" }
47
+ }
48
+ // [FACT] The first candidate. `ready` arrives pre-sorted from the graph, so
49
+ // "first" IS the policy — ORDER ASC, then ID ASC.
50
+ const candidate = ready[0]!
51
+ if (snapshot.tasks.find((t) => t.id === candidate) === undefined) {
52
+ // The graph was built from this same snapshot, so this is unreachable in
53
+ // practice. Reported rather than guessed at: a policy that invents a
54
+ // replacement here would be deciding readiness, which is not its job.
55
+ return { taskId: null, policy: SELECTION_POLICY, reason: "unreadable" }
56
+ }
57
+ return { taskId: candidate, policy: SELECTION_POLICY, reason: "selected" }
58
+ }
59
+
60
+ // ── contention policy ─────────────────────────────────────────────────────────
61
+
62
+ /**
63
+ * [PHASE 6T] What to do when the runtime cannot take another execution.
64
+ *
65
+ * The mission's requirement is exact: *contention is not task execution*. A
66
+ * rejected capacity check must not increment a generation, alter ownership,
67
+ * create attempt lineage, mark a task failed, or mark it completed.
68
+ */
69
+ export type ContentionPolicy =
70
+ /** Do nothing this cycle. The task stays ready and untouched. [SELECTED] */
71
+ | "SKIP_CYCLE"
72
+ /** Block until capacity frees. Rejected: an unbounded wait with no owner. */
73
+ | "WAIT"
74
+ /** Re-evaluate after a delay. Rejected: a timer, and a lifecycle to own. */
75
+ | "RETRY_LATER"
76
+ /**
77
+ * Take the task and run it when capacity appears. Rejected: it consumes a
78
+ * generation for work that has not run — the exact defect 6T exists to fix.
79
+ */
80
+ | "CLAIM_AND_DEFER"
81
+
82
+ export const CONTENTION_POLICY: ContentionPolicy = "SKIP_CYCLE"
83
+
84
+ /** Why contention was detected. Both paths must leave the task untouched. */
85
+ export type ContentionSource = "pre-claim-probe" | "atomic-claim-predicate"
86
+
87
+ export interface ContentionDecision {
88
+ readonly policy: ContentionPolicy
89
+ readonly source: ContentionSource
90
+ /** Always false. A contention rejection never performs work. */
91
+ readonly mayClaim: false
92
+ /** Whether a later trigger should re-evaluate this task. */
93
+ readonly reEvaluateLater: true
94
+ }
95
+
96
+ /**
97
+ * [PHASE 6T] THE CONTENTION DECISION.
98
+ *
99
+ * [DESIGN DECISION] `SKIP_CYCLE`, and the rejection is total: no claim, no
100
+ * generation, no owner, no attempt, no status write, no retry loop. The task
101
+ * remains exactly as the graph found it.
102
+ *
103
+ * Rationale for rejecting the alternatives, in the order they were considered:
104
+ *
105
+ * - `WAIT` holds an in-memory wait across a user turn of unbounded length. It
106
+ * needs its own timeout, its own cancellation, and a decision about what to do
107
+ * when the wait outlasts the turn. All three are new lifecycle surface for a
108
+ * case that skipping already handles correctly.
109
+ * - `RETRY_LATER` is a timer plus the lifecycle to own it. 6T's own trigger
110
+ * survey found the runtime has NO periodic timer at all, so this would be
111
+ * inventing infrastructure. It also converts a policy decision into a
112
+ * background obligation that survives the thing that triggered it.
113
+ * - `CLAIM_AND_DEFER` is the one that looks attractive and is wrong: it spends
114
+ * a generation on work that will not run, which is the precise defect 6N
115
+ * reported and 6O designed against.
116
+ *
117
+ * `reEvaluateLater: true` is what keeps skipping from becoming starvation. The
118
+ * next trigger — whatever legitimately causes one — re-reads a fresh snapshot,
119
+ * so nothing is lost by declining to act now.
120
+ */
121
+ export function decideContention(source: ContentionSource): ContentionDecision {
122
+ return { policy: CONTENTION_POLICY, source, mayClaim: false, reEvaluateLater: true }
123
+ }
124
+
125
+ // ── starvation ────────────────────────────────────────────────────────────────
126
+
127
+ /**
128
+ * [PHASE 6T] Is the selected policy starvation-free? Stated as a claim so it can
129
+ * be tested rather than argued.
130
+ *
131
+ * [FACT] The mechanism is not fairness in the policy — it is that a task which
132
+ * has run leaves the ready set. `reconcileIfNoCompletedAttempt` (store) reverts
133
+ * `IN_PROGRESS` ONLY when the generation has no completion marker, so:
134
+ *
135
+ * attempt completed -> the marker exists -> NOT reverted -> stays IN_PROGRESS
136
+ * -> not PENDING -> not ready -> never re-selected
137
+ * attempt never ran -> no marker -> reverted -> PENDING -> ready again
138
+ *
139
+ * [INFERENCE] So a task that repeatedly fails by RETURNING does not starve its
140
+ * successors — it leaves the ready set on its first attempt. Strict `ORDER ASC`
141
+ * is therefore starvation-free here, without any fairness machinery.
142
+ *
143
+ * [INFERENCE] The same mechanism is the honest limit: there is no verifier, so a
144
+ * task that returned is also never moved on, and it stays IN_PROGRESS forever.
145
+ * That is not starvation of B; it is A being stuck. Both statements are true and
146
+ * the distinction matters, because the fix for "A is stuck" (a verifier that
147
+ * requeues it) is exactly what would REINTRODUCE starvation of B under a strict
148
+ * order — a lower-ordered task that always requeues would win every cycle.
149
+ *
150
+ * [DESIGN DECISION] Therefore: if a verifier is ever added, selection must gain
151
+ * an explicit anti-starvation rule at that moment. It is recorded here as a
152
+ * dependency rather than pre-solved, because no verifier exists and pre-building
153
+ * for it would be speculative.
154
+ */
155
+ export const SELECTION_IS_STARVATION_FREE = true
156
+
157
+ /**
158
+ * [PHASE 6T] The conditional fairness rule, stated now and NOT implemented.
159
+ *
160
+ * Exported so the dependency is machine-visible: when a requeueing authority
161
+ * appears, this is the property that must hold, and `policy6t.test.ts` asserts
162
+ * the current model satisfies the *unconditional* form.
163
+ */
164
+ export const ANTISTARVATION_REQUIREMENT =
165
+ "if a task can be requeued to PENDING after running, ORDER ASC alone is insufficient and selection must gain an age or attempt-count tiebreak"
@@ -0,0 +1,148 @@
1
+ // PHASE 6X — SESSION-LEVEL AUTONOMOUS EXECUTION AUTHORITY.
2
+ //
3
+ // Implements 6W ADR-20/ADR-21. This is a CLAIM ON THE RIGHT TO SCHEDULE, not a
4
+ // claim on a task and not a proof of liveness.
5
+ //
6
+ // ── WHAT IT IS ───────────────────────────────────────────────────────────────
7
+ //
8
+ // A durable record: (session, incarnation) -> (owner token, lease expiry).
9
+ // Exactly one Scheduler may hold it at a time. A second process that tries to
10
+ // acquire while the lease is valid FAILS CLOSED, which removes the precondition
11
+ // for FINDING-02: F02 required two reconcilers to coexist, and this prevents
12
+ // that outright.
13
+ //
14
+ // ── WHAT IT IS NOT ───────────────────────────────────────────────────────────
15
+ //
16
+ // It is NOT a liveness proof. An expired lease does not prove a process died; it
17
+ // proves only that nobody renewed in time. A process that is alive but stalled
18
+ // past the lease will lose authority — and 6W chose that direction deliberately,
19
+ // because at session granularity a wrong answer costs WASTED WORK, while at task
20
+ // granularity (the status quo) it costs DUPLICATE EXECUTION.
21
+ //
22
+ // It is NOT a replacement for lineage. `exec_generation` / `attempt_generation`
23
+ // still answer "what happened to this execution"; the lease answers "who may
24
+ // schedule for this session". The two layers never read each other.
25
+
26
+ /** How long an acquired lease remains valid. */
27
+ export const SESSION_LEASE_MS = 300_000
28
+
29
+ /** How often a live owner refreshes it. Five renewals per lease. */
30
+ export const SESSION_RENEW_INTERVAL_MS = 60_000
31
+
32
+ /**
33
+ * [PHASE 6X] Lease constants are DERIVED, not chosen.
34
+ *
35
+ * `FACT` The runtime's own limits, read from `src/constants.ts` and
36
+ * `autonomous-context.ts`:
37
+ *
38
+ * BASH_DEFAULT_TIMEOUT_MS 30_000 longest single tool call
39
+ * SUB_AGENT_TIMEOUT_MS 120_000 longest single sub-agent turn
40
+ * autonomous turn default 120_000 `timeoutMs ?? 120_000`
41
+ *
42
+ * `INFERENCE` The longest interval in which a legitimately running execution can
43
+ * go without making observable progress is bounded by the turn timeout, not by
44
+ * how fast the model happens to be today. A lease shorter than that would lapse
45
+ * during an ordinary slow call — which is precisely the false positive 6W chose
46
+ * to eliminate.
47
+ *
48
+ * `DESIGN DECISION` lease = 300_000 ms = 2.5x the 120_000 ms turn bound. A live
49
+ * process therefore retains authority across a stalled event loop of up to about
50
+ * four minutes. Renewal every 60_000 ms means five chances inside one lease, so
51
+ * a single missed tick is not fatal.
52
+ *
53
+ * `INFERENCE` These are the numbers to revisit if a sub-agent timeout is ever
54
+ * raised. They are named constants precisely so raising one without raising the
55
+ * other is a visible act, not a silent regression.
56
+ */
57
+
58
+ /**
59
+ * [PHASE 6X] Expiry boundary, stated once so no comparison is left to chance.
60
+ *
61
+ * A lease is ACTIVE while `lease_expires_at > now`, and EXPIRED when
62
+ * `lease_expires_at <= now`.
63
+ *
64
+ * `DESIGN DECISION` Expired-at-exactly-`now` counts as EXPIRED. Using `<=` on
65
+ * the acquirer's side means an expiring lease is immediately available, and the
66
+ * alternative (`<`) would let a lease whose deadline has passed keep blocking a
67
+ * takeover for one more clock tick — a needless availability loss with no safety
68
+ * gain, since the previous owner is by definition no longer renewing.
69
+ */
70
+ export function isLeaseActive(expiresAt: number, now: number): boolean {
71
+ return expiresAt > now
72
+ }
73
+
74
+ let counter = 0
75
+
76
+ /**
77
+ * [PHASE 6X] A fresh owner token.
78
+ *
79
+ * `DESIGN DECISION` NOT a PID and NOT an object identity. PIDs are reused and
80
+ * object identity is meaningless in another process; the token is the only value
81
+ * that distinguishes "me, still holding it" from "someone who took it after my
82
+ * lease expired". It is unpredictable, so it cannot be guessed by another local
83
+ * process, and it is regenerated on every acquisition — a restarted process can
84
+ * never present its predecessor's token.
85
+ */
86
+ export function newOwnerToken(): string {
87
+ counter += 1
88
+ const rand = Math.floor(Math.random() * 0xffffffff)
89
+ .toString(16)
90
+ .padStart(8, "0")
91
+ return `own-${Date.now().toString(36)}-${counter.toString(36)}-${rand}`
92
+ }
93
+
94
+ /** Test-only: make token generation reproducible. */
95
+ export function resetOwnerTokenCounterForTests(): void {
96
+ counter = 0
97
+ }
98
+
99
+ /** The durable row. One per (session, incarnation). */
100
+ export interface SessionAuthority {
101
+ readonly sessionId: string
102
+ /** 6Q incarnation. Keying on it stops a recreated session inheriting a lease. */
103
+ readonly incarnation: number
104
+ readonly ownerToken: string
105
+ readonly ownerPid: number
106
+ readonly acquiredAt: number
107
+ readonly leaseExpiresAt: number
108
+ }
109
+
110
+ export type AcquireOutcome =
111
+ /** The caller now holds the lease. */
112
+ | "ACQUIRED"
113
+ /** The caller already held it and refreshed it (idempotent re-acquire). */
114
+ | "RENEWED_BY_SELF"
115
+ /** Another owner's lease is still valid. The caller must not schedule. */
116
+ | "REFUSED_LEASE_HELD"
117
+
118
+ export type WithdrawOutcome =
119
+ /** The lease was refreshed and is still ours. */
120
+ | "RENEWED"
121
+ /** We no longer hold it — expired and taken, or deleted. */
122
+ | "AUTHORITY_LOST"
123
+
124
+ /** Parse a stored value defensively: a corrupt row must fail closed, not crash. */
125
+ export function parseAuthority(raw: string): SessionAuthority | null {
126
+ try {
127
+ const o = JSON.parse(raw) as Record<string, unknown>
128
+ const n = (k: string): number => Number(o[k])
129
+ if (typeof o.sessionId !== "string") return null
130
+ if (typeof o.ownerToken !== "string" || o.ownerToken.length === 0) return null
131
+ if (!Number.isFinite(n("incarnation"))) return null
132
+ if (!Number.isFinite(n("leaseExpiresAt"))) return null
133
+ return {
134
+ sessionId: o.sessionId,
135
+ incarnation: n("incarnation"),
136
+ ownerToken: o.ownerToken,
137
+ ownerPid: n("ownerPid"),
138
+ acquiredAt: n("acquiredAt"),
139
+ leaseExpiresAt: n("leaseExpiresAt"),
140
+ }
141
+ } catch {
142
+ return null
143
+ }
144
+ }
145
+
146
+ export function serializeAuthority(a: SessionAuthority): string {
147
+ return JSON.stringify(a)
148
+ }
@@ -0,0 +1,211 @@
1
+ // Phase 6B — session ownership, so reconciliation can fail closed.
2
+ //
3
+ // NEW ARCHITECTURE. This is the P3 prerequisite for the Phase 6A reconciliation
4
+ // contract. It is deliberately small, process-local, and honest about what it
5
+ // cannot guarantee.
6
+ //
7
+ // ── THE PROBLEM ──────────────────────────────────────────────────────────────
8
+ //
9
+ // 6A allows reconciliation to revert stranded `IN_PROGRESS` / `VERIFYING` work
10
+ // back to `PENDING`. That is only safe if the execution context that owns them
11
+ // is gone. Without any ownership signal, a reconciler cannot tell "stranded by a
12
+ // crash" from "actively running right now in another context", and reverting
13
+ // live work is worse than not reconciling at all.
14
+ //
15
+ // ── WHAT WAS EVALUATED (6B §8) ──────────────────────────────────────────────
16
+ //
17
+ // VERIFIED, all in the current source:
18
+ //
19
+ // A. deployment invariant — viable, and the only one expressible with no new
20
+ // durable state. Adopted, but as a *convention*
21
+ // plus a mechanical guard, never as a promise.
22
+ // B. process-local owner — ADOPTED here. Explicit, testable, Windows/Bun
23
+ // safe, no second task authority.
24
+ // C. durable owner row — REJECTED. `task_meta` could hold one, but that is
25
+ // a new durable authority, which 6B §19 lists as a
26
+ // stop condition.
27
+ // D. OS / process lock — REJECTED. `src/lib/safe-open.ts` uses `O_EXCL`
28
+ // for atomic writes, not session locking; there is
29
+ // no session lock to reuse.
30
+ // E. lease / heartbeat — REJECTED. Explicitly out of V1 scope. A lease also
31
+ // cannot survive a machine crash without expiry
32
+ // logic, i.e. it would be a second authority.
33
+ // F. existing mechanism — `src/session/journal.ts` "advisory" refers to
34
+ // DEGRADED JOURNAL HEALTH under append failure, not
35
+ // session ownership. Not a candidate.
36
+ //
37
+ // ── THE LIMITATION, LOCKED RATHER THAN PAPERED OVER ─────────────────────────
38
+ //
39
+ // This registry is PROCESS-LOCAL. It cannot see another OS process. Therefore:
40
+ //
41
+ // * If this process does not own the session, reconciliation REFUSES.
42
+ // * If another process DOES own the session, this process still sees
43
+ // "not owned" and refuses. The refusal is the safe direction: the cost of a
44
+ // false refusal is that stranded work waits, which is recoverable; the cost
45
+ // of a false reconciliation is reverting live work, which may not be.
46
+ //
47
+ // So the guarantee is asymmetric and deliberately so: **safe against false
48
+ // reconciliation, at the price of refusing cross-process reconciliation
49
+ // entirely.** Cross-process reconciliation is therefore NOT IMPLEMENTED and
50
+ // must not be enabled by removing this check.
51
+
52
+ /** Opaque identity of the in-process owner of a session. */
53
+ export type SessionOwner = { readonly token: symbol; readonly label: string }
54
+
55
+ export type ReleaseReason = "stopped" | "session-removed" | "replaced"
56
+
57
+ /**
58
+ * One owner per session, per process.
59
+ *
60
+ * Module-level because ownership is a property of the PROCESS, not of any
61
+ * TaskStore instance — two TaskStore instances over the same database in one
62
+ * process must agree about who owns a session.
63
+ *
64
+ * It is the ONLY process-global state introduced by Phase 6B, and it holds
65
+ * ownership only. It is not a task authority: it cannot read or write a task,
66
+ * and every durable mutation still goes through TaskStore.
67
+ */
68
+ const owners = new Map<string, SessionOwner>()
69
+
70
+ /**
71
+ * Take ownership of `sessionId` for this process.
72
+ *
73
+ * A second acquisition of the same session is refused rather than silently
74
+ * stealing, so a double-attach is visible instead of a silent last-writer-wins.
75
+ */
76
+ export function acquireSessionOwnership(sessionId: string, label: string): SessionOwner | null {
77
+ if (owners.has(sessionId)) return null
78
+ const owner: SessionOwner = { token: Symbol(label), label }
79
+ owners.set(sessionId, owner)
80
+ return owner
81
+ }
82
+
83
+ /** True only when `owner` is the owner this process recorded for `sessionId`. */
84
+ export function ownsSession(sessionId: string, owner: SessionOwner | null | undefined): boolean {
85
+ if (owner === null || owner === undefined) return false
86
+ const current = owners.get(sessionId)
87
+ return current !== undefined && current.token === owner.token
88
+ }
89
+
90
+ export function releaseSessionOwnership(
91
+ sessionId: string,
92
+ owner: SessionOwner,
93
+ _reason: ReleaseReason = "stopped",
94
+ ): boolean {
95
+ if (!ownsSession(sessionId, owner)) return false
96
+ owners.delete(sessionId)
97
+ return true
98
+ }
99
+
100
+ /** Sessions currently owned by this process. Diagnostics only. */
101
+ export function ownedSessions(): readonly string[] {
102
+ return [...owners.keys()]
103
+ }
104
+
105
+ /**
106
+ * [PHASE 6U] Per-session invalidation subscribers.
107
+ *
108
+ * A `SessionOwner` knows it OWNS a session; it has no way to learn that the
109
+ * session was deleted while it was not looking. 6Q closed that gap durably (the
110
+ * incarnation check at claim and lineage-write time), which makes a late write
111
+ * safe — but it cannot make a *live* autonomous turn stop, because nothing
112
+ * interrupts a turn that is already running.
113
+ *
114
+ * [DESIGN DECISION] This is the SAME process-local, per-session authority, not a
115
+ * second registry. Adding a map here is a smaller and more honest change than a
116
+ * new "scheduler registry": the Scheduler already consults this module, and one
117
+ * place should answer "who cares about this session in this process".
118
+ *
119
+ * [DESIGN DECISION] Process-local and therefore a best-effort OPTIMISATION, not a
120
+ * correctness boundary. A deletion in another process reaches nothing here — and
121
+ * must not need to: the incarnation check remains the authoritative barrier, and
122
+ * this only makes the stop happen sooner when someone is present to signal it.
123
+ * That asymmetry is the point; a subscriber that was mistaken for a guarantee
124
+ * would be worse than none.
125
+ */
126
+ const invalidated = new Map<string, Set<() => void>>()
127
+
128
+ /**
129
+ * Subscribe to "this session was deleted" for this process.
130
+ *
131
+ * Returns an unsubscribe function, and MUST be called on teardown: the set is
132
+ * process-global, so a leaked subscription would retain a whole Scheduler —
133
+ * including its provider and its child sessions — for the life of the process.
134
+ */
135
+ export function onSessionInvalidated(sessionId: string, cb: () => void): () => void {
136
+ let set = invalidated.get(sessionId)
137
+ if (set === undefined) {
138
+ set = new Set()
139
+ invalidated.set(sessionId, set)
140
+ }
141
+ set.add(cb)
142
+ let live = true
143
+ return () => {
144
+ if (!live) return
145
+ live = false
146
+ set.delete(cb)
147
+ if (set.size === 0) invalidated.delete(sessionId)
148
+ }
149
+ }
150
+
151
+ /**
152
+ * Tell subscribers that `sessionId` was deleted.
153
+ *
154
+ * Deliberately swallows subscriber failures: this is called from the deletion
155
+ * path, and a throwing observer must not be able to fail a deletion. Reporting
156
+ * the failure belongs to the subscriber's own logging, if it has any.
157
+ *
158
+ * @returns how many subscribers were notified. Diagnostics only.
159
+ */
160
+ export function notifySessionInvalidated(sessionId: string): number {
161
+ const set = invalidated.get(sessionId)
162
+ if (set === undefined) return 0
163
+ // Copied first: a subscriber that unsubscribes during notification must not
164
+ // mutate the set being iterated.
165
+ for (const cb of [...set]) {
166
+ try {
167
+ cb()
168
+ } catch {
169
+ /* an observer cannot fail a deletion */
170
+ }
171
+ }
172
+ return set.size
173
+ }
174
+
175
+ /** Sessions with at least one subscriber in this process. Diagnostics only. */
176
+ export function watchedSessions(): readonly string[] {
177
+ return [...invalidated.keys()]
178
+ }
179
+
180
+ /**
181
+ * Release the ownership token recorded under a known label, without holding the
182
+ * `SessionOwner`.
183
+ *
184
+ * [PHASE 6U] The composition root's shutdown path knows the session id and the
185
+ * label it composed with, but not the token `acquireSessionOwnership` minted.
186
+ * This releases by identity of intent (this process, this label) rather than
187
+ * requiring the caller to hold an opaque token it was never given.
188
+ *
189
+ * [DESIGN DECISION] Fail-closed on the token: only the CURRENT owner's token is
190
+ * removed, so a late shutdown from a superseded instance cannot evict its
191
+ * replacement. The extra token-identity check is what makes that safe.
192
+ */
193
+ export function releaseSessionOwnershipFor(sessionId: string, label: string): boolean {
194
+ const current = owners.get(sessionId)
195
+ if (current === undefined) return false
196
+ if (current.label !== label) return false
197
+ owners.delete(sessionId)
198
+ return true
199
+ }
200
+
201
+ /**
202
+ * Test-only. Clears all ownership.
203
+ *
204
+ * NOT a production affordance: nothing outside tests may call this, because it
205
+ * would let a caller manufacture the "not owned" state that reconciliation
206
+ * needs in order to refuse.
207
+ */
208
+ export function resetSessionOwnershipForTests(): void {
209
+ owners.clear()
210
+ invalidated.clear()
211
+ }