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,305 @@
1
+ // TaskGraph — a read-only derived view of exactly one TaskStore snapshot.
2
+ //
3
+ // NEW ARCHITECTURE. Implements the public API of design lock S19 and the
4
+ // snapshot/immutability contract of S14-S16 in
5
+ // `PHASE-5B-TASKGRAPH-NEW-ARCHITECTURE-DESIGN-LOCK.md`.
6
+ //
7
+ // The three invariants worth stating up front:
8
+ //
9
+ // TaskStore owns truth. TaskGraph interprets one coherent snapshot and
10
+ // never writes, never allocates identity and never executes work.
11
+ //
12
+ // PURE (design lock S22). This module performs no TaskStore access, no
13
+ // database access, no filesystem access, no process-global state, no
14
+ // randomness and no id formatting. Its only imports are types from the
15
+ // project plus this phase's own pure helpers.
16
+ //
17
+ // It has no `addNode`, `setParent`, `markReady`, `claim`, `execute`, `retry`,
18
+ // `cancel` or `complete`. Not by omission — adding any of them would make
19
+ // TaskGraph a second authority competing with TaskStore (design lock S14).
20
+
21
+ import {
22
+ analyseRelations,
23
+ type Diagnostic,
24
+ type GraphNode,
25
+ type RelationAnalysis,
26
+ } from "./graph-validate.ts"
27
+ import type { TaskSnapshot, TaskStatus } from "./model.ts"
28
+ import {
29
+ type Blocker,
30
+ computeBlockers,
31
+ isReady as computeIsReady,
32
+ eligibleForReadiness,
33
+ type NotReady,
34
+ } from "./readiness.ts"
35
+
36
+ export type { Diagnostic, GraphNode } from "./graph-validate.ts"
37
+ export type { Blocker, BlockerKind, NotReady } from "./readiness.ts"
38
+
39
+ const EMPTY_IDS: readonly string[] = Object.freeze([])
40
+
41
+ /**
42
+ * A genuinely `Blocker`-typed empty result.
43
+ *
44
+ * PHASE 5D.1 / defect D1. `blockers()` promises `readonly Blocker[]`, so its
45
+ * empty result must be typed as one. Returning `EMPTY_IDS` here handed callers a
46
+ * `readonly string[]` while claiming otherwise — a defect the runtime could not
47
+ * surface (the array is empty either way) and `tsc` did. Typed explicitly rather
48
+ * than cast: `Object.freeze([])` is `readonly never[]`, which is assignable to
49
+ * `readonly Blocker[]` with no assertion and no `as`.
50
+ */
51
+ const EMPTY_BLOCKERS: readonly Blocker[] = Object.freeze([])
52
+
53
+ /**
54
+ * Deterministic node order (design lock S12): `order` ascending, then `taskId`
55
+ * ascending.
56
+ *
57
+ * The id tiebreak is a plain lexicographic string compare, which is exactly
58
+ * what SQLite's `ORDER BY task_id` does for a TEXT column under BINARY
59
+ * collation. So graph iteration agrees with `listTasks` for free — including
60
+ * the `t10 < t2` consequence of comparing ids as text rather than as numbers.
61
+ * That is fidelity, not a bug: we mirror the store's own ordering exactly.
62
+ */
63
+ function compareNodes(a: GraphNode, b: GraphNode): number {
64
+ if (a.order !== b.order) return a.order < b.order ? -1 : 1
65
+ if (a.id === b.id) return 0
66
+ return a.id < b.id ? -1 : 1
67
+ }
68
+
69
+ /**
70
+ * A read-only projection of one coherent TaskStore snapshot.
71
+ *
72
+ * Immutable by construction: nodes and their `dependsOn` arrays are frozen
73
+ * copies taken at build time, so a later TaskStore mutation cannot retroactively
74
+ * change a graph that has already been built (design lock S16). There is no
75
+ * cache, no registry and no invalidation hook — a rebuild is cheap, so it is
76
+ * the cache.
77
+ */
78
+ export class TaskGraph {
79
+ /** The session this graph was derived from. */
80
+ readonly sessionId: string
81
+
82
+ /** Number of distinct tasks in the snapshot. */
83
+ readonly nodeCount: number
84
+
85
+ /**
86
+ * WEAK STALENESS HINT (design lock S15) — the maximum `revision` seen in the
87
+ * snapshot, or 0 for an empty snapshot.
88
+ *
89
+ * Deliberately NOT called `sourceRevision`, and deliberately NOT a
90
+ * compare-and-swap or version guarantee. It can go stale silently (removing
91
+ * the highest-revision task leaves it unchanged) and it means nothing across
92
+ * sessions. A consumer that needs certainty must re-read TaskStore; this
93
+ * exists only to let a consumer notice that it *may* be looking at an older
94
+ * view. Because the graph is read-only, a stale graph can never cause
95
+ * incorrect behaviour inside the graph.
96
+ */
97
+ readonly sourceMaxRevision: number
98
+
99
+ private readonly analysis: RelationAnalysis
100
+ private readonly ordered: readonly GraphNode[]
101
+ private readonly childrenIndex: ReadonlyMap<string, readonly string[]>
102
+ private readonly dependentsIndex: ReadonlyMap<string, readonly string[]>
103
+
104
+ constructor(snapshot: TaskSnapshot) {
105
+ this.sessionId = snapshot.sessionId
106
+
107
+ // --- project: defensive copy of the fields the graph reasons about -----
108
+ let maxRevision = 0
109
+ const projected: GraphNode[] = []
110
+ for (const task of snapshot.tasks) {
111
+ if (task.revision > maxRevision) maxRevision = task.revision
112
+ projected.push(
113
+ Object.freeze({
114
+ id: task.id,
115
+ title: task.title,
116
+ status: task.status,
117
+ order: task.order,
118
+ parentId: task.parentId,
119
+ // Copy the array: retaining the source array would let a caller
120
+ // mutate a live row through the graph.
121
+ dependsOn: Object.freeze([...task.dependsOn]),
122
+ blockedReason: task.blockedReason,
123
+ revision: task.revision,
124
+ }),
125
+ )
126
+ }
127
+ this.sourceMaxRevision = maxRevision
128
+
129
+ // Sort before validation so both the de-duplication choice (first wins) and
130
+ // diagnostic ordering are deterministic regardless of input array order
131
+ // (invariant G5). Array.prototype.sort is stable, so equal keys keep their
132
+ // relative order.
133
+ projected.sort(compareNodes)
134
+
135
+ this.analysis = analyseRelations(projected)
136
+ // byId preserves insertion order, which is the sorted order above.
137
+ this.ordered = Object.freeze([...this.analysis.byId.values()])
138
+ this.nodeCount = this.ordered.length
139
+
140
+ this.childrenIndex = buildAdjacency(this.ordered, "parent")
141
+ this.dependentsIndex = buildAdjacency(this.ordered, "dependency")
142
+ }
143
+
144
+ /** The node for `taskId`, or `undefined` if it is not in the snapshot. */
145
+ getNode(taskId: string): GraphNode | undefined {
146
+ return this.analysis.byId.get(taskId)
147
+ }
148
+
149
+ /** Every node, in deterministic order. */
150
+ nodes(): readonly GraphNode[] {
151
+ return this.ordered
152
+ }
153
+
154
+ /** Execution edges out: the ids this task depends on. */
155
+ dependencies(taskId: string): readonly string[] {
156
+ return this.getNode(taskId)?.dependsOn ?? EMPTY_IDS
157
+ }
158
+
159
+ /** Execution edges in: the ids that depend on this task. */
160
+ dependents(taskId: string): readonly string[] {
161
+ return this.dependentsIndex.get(taskId) ?? EMPTY_IDS
162
+ }
163
+
164
+ /** Containment edges: the ids nested directly under this task. */
165
+ children(taskId: string): readonly string[] {
166
+ return this.childrenIndex.get(taskId) ?? EMPTY_IDS
167
+ }
168
+
169
+ /** This task's parent id, or `null` when it is a root or absent. */
170
+ parent(taskId: string): string | null {
171
+ return this.getNode(taskId)?.parentId ?? null
172
+ }
173
+
174
+ /**
175
+ * Ids eligible for readiness, in deterministic order.
176
+ *
177
+ * `PENDING` and `BLOCKED` are eligible. Eligibility is not readiness: see
178
+ * `isReady`. Membership here is independent of graph validity, because a
179
+ * blocked-by-relation task is still an eligible candidate that happens not to
180
+ * be ready.
181
+ */
182
+ eligibleTasks(): readonly string[] {
183
+ const out: string[] = []
184
+ for (const node of this.ordered) {
185
+ if (eligibleForReadiness(node)) out.push(node.id)
186
+ }
187
+ return out
188
+ }
189
+
190
+ /**
191
+ * Ids that are ready, in deterministic order — or `[]` when the graph is
192
+ * invalid.
193
+ *
194
+ * An invalid graph must not publish a partial readiness answer: the
195
+ * structure is ill-defined, so any "ready" claim would be a lie (design lock
196
+ * S10). O(n + e) — one pass, per-node blocker derivation.
197
+ */
198
+ readyTasks(): readonly string[] {
199
+ if (!this.analysis.valid) return EMPTY_IDS
200
+ const out: string[] = []
201
+ for (const node of this.ordered) {
202
+ if (computeIsReady(node, this.analysis.byId, this.analysis)) out.push(node.id)
203
+ }
204
+ return out
205
+ }
206
+
207
+ /** True only for a `PENDING` task with no blockers in a valid graph. */
208
+ isReady(taskId: string): boolean {
209
+ const node = this.getNode(taskId)
210
+ if (node === undefined) return false
211
+ return computeIsReady(node, this.analysis.byId, this.analysis)
212
+ }
213
+
214
+ /**
215
+ * Why this task is or is not ready. `undefined` if the id is not in the snapshot.
216
+ *
217
+ * The order of these tests is the whole contract:
218
+ *
219
+ * 1. an invalid graph answers `graph-invalid` for EVERY id — the structure
220
+ * is ill-defined, so no partial readiness claim is permitted;
221
+ * 2. any blocker answers `blocked` — blockers outrank status, so a
222
+ * durably-`BLOCKED` task that also waits on a dependency reports the
223
+ * actionable reason;
224
+ * 3. `PENDING` with no blockers is the only `ready` case;
225
+ * 4. an ELIGIBLE task that survived the above is `eligible-not-ready` —
226
+ * this is the `BLOCKED`-with-no-blockers case, and it is exactly why
227
+ * Phase 5C.1 added the variant;
228
+ * 5. everything else is `not-eligible`.
229
+ *
230
+ * Step 4 tests `eligibleForReadiness` rather than hard-coding `"BLOCKED"`, so
231
+ * this classification can never drift away from `eligibleTasks()`, which uses
232
+ * the same predicate.
233
+ */
234
+ notReadyReason(taskId: string): NotReady | undefined {
235
+ const node = this.getNode(taskId)
236
+ if (node === undefined) return undefined
237
+
238
+ if (!this.analysis.valid) {
239
+ return { kind: "graph-invalid", diagnostics: this.analysis.diagnostics }
240
+ }
241
+
242
+ const blockers = computeBlockers(node, this.analysis.byId, this.analysis)
243
+ if (blockers.length > 0) return { kind: "blocked", blockers }
244
+
245
+ if (node.status === "PENDING") return { kind: "ready" }
246
+
247
+ if (eligibleForReadiness(node)) {
248
+ return { kind: "eligible-not-ready", status: node.status }
249
+ }
250
+
251
+ return { kind: "not-eligible", status: node.status }
252
+ }
253
+
254
+ /** Every relation-derived reason this task is not ready. */
255
+ blockers(taskId: string): readonly Blocker[] {
256
+ const node = this.getNode(taskId)
257
+ if (node === undefined) return EMPTY_BLOCKERS
258
+ return computeBlockers(node, this.analysis.byId, this.analysis)
259
+ }
260
+
261
+ /**
262
+ * Structural validity plus the diagnostics that explain an invalid graph.
263
+ *
264
+ * A dependency cycle keeps `valid === true`: it is a well-formed but
265
+ * unsatisfiable relation, and its members carry `DEPENDENCY_CYCLE` blockers
266
+ * instead.
267
+ */
268
+ validity(): { valid: boolean; diagnostics: readonly Diagnostic[] } {
269
+ return { valid: this.analysis.valid, diagnostics: this.analysis.diagnostics }
270
+ }
271
+ }
272
+
273
+ /**
274
+ * Build the reverse-relation index once, at construction.
275
+ *
276
+ * These are intrinsic indices over immutable data, not caches: there is
277
+ * nothing to invalidate because nothing can change. Edges to absent ids, and
278
+ * self edges, are excluded — both are already INVALID diagnostics, and a
279
+ * phantom index entry would misreport the graph's structure.
280
+ */
281
+ function buildAdjacency(
282
+ ordered: readonly GraphNode[],
283
+ relation: "parent" | "dependency",
284
+ ): ReadonlyMap<string, readonly string[]> {
285
+ const index = new Map<string, string[]>()
286
+ for (const node of ordered) index.set(node.id, [])
287
+
288
+ for (const node of ordered) {
289
+ const targets = relation === "parent" ? [node.parentId] : node.dependsOn
290
+ for (const target of targets) {
291
+ if (target === null || target === node.id) continue
292
+ const bucket = index.get(target)
293
+ if (bucket === undefined) continue
294
+ bucket.push(node.id)
295
+ }
296
+ }
297
+
298
+ // Iterate `ordered`, so every bucket is already in deterministic order.
299
+ const frozen = new Map<string, readonly string[]>()
300
+ for (const [id, bucket] of index) frozen.set(id, Object.freeze(bucket))
301
+ return frozen
302
+ }
303
+
304
+ /** Re-exported so a consumer can name the status type without a second import. */
305
+ export type { TaskStatus }
@@ -0,0 +1,230 @@
1
+ // Canonical task IDENTITY substrate — Phase 3A.
2
+ //
3
+ // THIS IS A RECONSTRUCTION, NOT A RECOVERY. There is no surviving source for
4
+ // `src/task/identity.ts` or `src/task/normalize.ts`, and the Phase 2 artifact
5
+ // (`todo.orig.ts`) contains ZERO occurrences of `taskId`, `ordinal`,
6
+ // `address`, `resolveTask`, `TaskStore` or `synchronizeTasks`. Nothing in this
7
+ // file may be described as "recovered".
8
+ //
9
+ // It is reconstructed from two real sources:
10
+ //
11
+ // 1. VERIFIED FROM CURRENT SOURCE — the Phase 1 TaskStore is the one and only
12
+ // allocator (`nextId` uses `max`, not `count`; `createTask` inserts
13
+ // `revision = 1`; the primary key is `(session_id, task_id)`). This file
14
+ // DELEGATES to it and never allocates an id of its own.
15
+ //
16
+ // 2. RECONSTRUCTED FROM HISTORY — the behaviour that was deferred in Phase 1
17
+ // lives in `store.orig.ts`'s `synchronizeTasks`, whose guard clauses are
18
+ // quoted at each rule below. That is genuine recovered evidence for the
19
+ // RULES, even though the Phase 3 wiring is gone.
20
+ //
21
+ // NOT IN SCOPE (Phase 3B): `TodoItem.taskId` propagation, `PlanStep.taskId`,
22
+ // `plan.updated` payloadVersion=2, the plan pipeline, TaskGraph, Scheduler.
23
+ // `DeclaredTask` below is this layer's own input contract precisely so that
24
+ // `TodoItem` is NOT modified here.
25
+
26
+ import type { TodoStatus } from "../tools/todo.ts"
27
+ import { isTaskId, type Task, TaskError, type TaskStatus } from "./model.ts"
28
+ import type { NewTaskInput, TaskStore } from "./store.ts"
29
+
30
+ // ── status mapping ───────────────────────────────────────────────────────────
31
+
32
+ /**
33
+ * Legacy todo status -> canonical Task status.
34
+ *
35
+ * RECONSTRUCTED FROM HISTORY: `store.orig.ts:501` calls exactly this -
36
+ * `todoStatusToTask(item.status as TodoStatus)`.
37
+ *
38
+ * [INFERRED] The 1:1 mapping. The CALL is recovered; the mapping body is not in
39
+ * any surviving source. It is the only mapping consistent with the surviving
40
+ * `TaskStatus` union in `model.ts`, which contains all five uppercase spellings
41
+ * of the five legacy statuses.
42
+ */
43
+ export function todoStatusToTask(status: TodoStatus): TaskStatus {
44
+ switch (status) {
45
+ case "pending":
46
+ return "PENDING"
47
+ case "in_progress":
48
+ return "IN_PROGRESS"
49
+ case "completed":
50
+ return "COMPLETED"
51
+ case "cancelled":
52
+ return "CANCELLED"
53
+ case "blocked":
54
+ return "BLOCKED"
55
+ }
56
+ }
57
+
58
+ // ── the declared shape ───────────────────────────────────────────────────────
59
+
60
+ /**
61
+ * One item as declared by a caller. Deliberately NOT `TodoItem`: attaching
62
+ * `taskId` to `TodoItem` is Phase 3B plan-pipeline work.
63
+ */
64
+ export interface DeclaredTask {
65
+ /** Canonical `t<n>` addressing an existing task, or absent for a new task. */
66
+ taskId?: string
67
+ title: string
68
+ status: TodoStatus
69
+ blockedReason?: string
70
+ }
71
+
72
+ export type IdentityKind = "existing" | "new"
73
+
74
+ export interface IdentityPlanEntry {
75
+ kind: IdentityKind
76
+ /** Present iff `kind === "existing"`. Already validated canonical. */
77
+ taskId?: string
78
+ /** Position in the declared list, which becomes display `order`. */
79
+ order: number
80
+ status: TaskStatus
81
+ title: string
82
+ blockedReason: string | null
83
+ /** NEW TASK INPUT, ready for `TaskStore.createTask`. Absent for existing. */
84
+ input?: NewTaskInput
85
+ }
86
+
87
+ export interface TaskIdentityPlan {
88
+ entries: IdentityPlanEntry[]
89
+ /** Ids that must already exist in the session before anything is written. */
90
+ requiredExisting: string[]
91
+ }
92
+
93
+ export interface ApplyOutcome {
94
+ existing: Task[]
95
+ created: Task[]
96
+ }
97
+
98
+ // ── planning: pure, no I/O, no allocation ────────────────────────────────────
99
+
100
+ /**
101
+ * Resolve declared items to identity, WITHOUT touching the store and WITHOUT
102
+ * allocating any id. Allocation belongs to `TaskStore` and nowhere else.
103
+ *
104
+ * Rules, each traced to evidence:
105
+ *
106
+ * - An explicit `taskId` must be canonical, else `TASK_INVALID_ID`.
107
+ * VERIFIED: `store.orig.ts:256,387,580` guard every id the same way.
108
+ * - A `taskId` may appear at most once per payload, else `TASK_DUPLICATE_ID`.
109
+ * VERIFIED: `store.orig.ts:479-488` - a `claimedInPayload` Set, throwing
110
+ * "`${item.taskId} appears twice in one payload`". The artifact's comment
111
+ * calls this a "pagar" (rail) whose absence would let two items silently
112
+ * last-write-win.
113
+ * - An item WITHOUT a `taskId` is a NEW task, never a silent re-addressing of
114
+ * an existing one.
115
+ * VERIFIED: `store.orig.ts:450` - "Item ber-id harus ada (ID tak
116
+ * diketahui = `TASK_NOT_FOUND`), item tanpa id = task baru."
117
+ * This is what makes the no-reallocation guarantee hold: an existing task is
118
+ * only ever reachable through its own id, so a payload that omits the id
119
+ * cannot overwrite or renumber it. Existing tasks it omits are simply left
120
+ * alone (the artifact's D7 retain rule).
121
+ * - `blockedReason` survives only for `BLOCKED`.
122
+ * VERIFIED: `store.orig.ts:502` - `status === "BLOCKED" ? item.blockedReason
123
+ * ?? null : null`.
124
+ * - `order` is the declared index, and is display position only - never
125
+ * identity. VERIFIED: `store.orig.ts:522,532` assign `order: index`.
126
+ */
127
+ export function planTaskIdentities(declared: readonly DeclaredTask[]): TaskIdentityPlan {
128
+ const entries: IdentityPlanEntry[] = []
129
+ const requiredExisting: string[] = []
130
+ const claimedInPayload = new Set<string>()
131
+
132
+ declared.forEach((item, index) => {
133
+ const status = todoStatusToTask(item.status)
134
+ const blockedReason = status === "BLOCKED" ? (item.blockedReason ?? null) : null
135
+
136
+ if (item.taskId === undefined || item.taskId === "") {
137
+ entries.push({
138
+ kind: "new",
139
+ order: index,
140
+ status,
141
+ title: item.title,
142
+ blockedReason,
143
+ input: {
144
+ title: item.title,
145
+ status,
146
+ order: index,
147
+ parentId: null,
148
+ dependsOn: [],
149
+ blockedReason,
150
+ provenance: { origin: "model", source: "todo_write" },
151
+ },
152
+ })
153
+ return
154
+ }
155
+
156
+ if (!isTaskId(item.taskId)) {
157
+ throw new TaskError("TASK_INVALID_ID", `not a canonical id: ${item.taskId}`)
158
+ }
159
+ if (claimedInPayload.has(item.taskId)) {
160
+ throw new TaskError("TASK_DUPLICATE_ID", `${item.taskId} appears twice in one payload`)
161
+ }
162
+ claimedInPayload.add(item.taskId)
163
+ requiredExisting.push(item.taskId)
164
+ entries.push({
165
+ kind: "existing",
166
+ taskId: item.taskId,
167
+ order: index,
168
+ status,
169
+ title: item.title,
170
+ blockedReason,
171
+ })
172
+ })
173
+
174
+ return { entries, requiredExisting }
175
+ }
176
+
177
+ // ── applying: delegates every write to TaskStore ─────────────────────────────
178
+
179
+ /**
180
+ * Apply a plan produced by `planTaskIdentities`.
181
+ *
182
+ * Every required id is checked for existence in a PRE-PASS, before the first
183
+ * write, so an unknown id cannot leave a half-applied payload. The artifact
184
+ * enforced the same thing at `store.orig.ts:494-496` (`TASK_NOT_FOUND` for an
185
+ * unknown explicit id); the pre-pass keeps that guarantee when the plan spans
186
+ * several writes instead of one.
187
+ *
188
+ * All writes go through `TaskStore.patchTask` / `createTask`, so `revision`,
189
+ * session ownership, the primary key and migration metadata stay owned by
190
+ * TaskStore. This layer holds no state of its own.
191
+ */
192
+ export function applyTaskIdentities(
193
+ store: TaskStore,
194
+ sessionId: string,
195
+ plan: TaskIdentityPlan,
196
+ ): ApplyOutcome {
197
+ for (const id of plan.requiredExisting) {
198
+ if (!store.getTask(sessionId, id)) {
199
+ throw new TaskError("TASK_NOT_FOUND", `declared unknown task ${id}`)
200
+ }
201
+ }
202
+
203
+ const existing: Task[] = []
204
+ const created: Task[] = []
205
+ for (const entry of plan.entries) {
206
+ if (entry.kind === "existing") {
207
+ existing.push(
208
+ store.patchTask(sessionId, entry.taskId!, {
209
+ title: entry.title,
210
+ status: entry.status,
211
+ order: entry.order,
212
+ blockedReason: entry.blockedReason,
213
+ }),
214
+ )
215
+ } else {
216
+ created.push(store.createTask(sessionId, entry.input!))
217
+ }
218
+ }
219
+ return { existing, created }
220
+ }
221
+
222
+ /** Convenience: plan then apply. Planning is pure, so this is still
223
+ * resolve-before-mutate: the plan throws before any write happens. */
224
+ export function synchronizeIdentities(
225
+ store: TaskStore,
226
+ sessionId: string,
227
+ declared: readonly DeclaredTask[],
228
+ ): ApplyOutcome {
229
+ return applyTaskIdentities(store, sessionId, planTaskIdentities(declared))
230
+ }