minicode-ai 0.11.0 → 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 +98 -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 -66
  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 +17 -7
  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 +54 -18
  184. package/src/ui/i18n/en.ts +62 -6
  185. package/src/ui/i18n/id.ts +62 -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 +598 -133
  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 -165
  221. package/docs/USAGE.md +0 -11
@@ -0,0 +1,767 @@
1
+ // P14.2/P14.4/P14.6 — PROYEKSI open-work lintas sesi. READ-ONLY, MURNI di
2
+ // atas sumber kanonik yang sudah ada:
3
+ //
4
+ // tasks.db (TaskStore) → status task = SATU-SATUNYA otoritas
5
+ // sessions.db (persistence)→ meta sesi = bukti asal/provenance
6
+ // presentation_events → histori intent terstruktur (P14.2 penuh)
7
+ // runs → eksekusi yang terputus (P14.1 RUN)
8
+ // checkpoint manifest → inventaris artefak progress (P14.0)
9
+ //
10
+ // Modul ini TIDAK PERNAH menulis: tidak ada INSERT/UPDATE/DELETE, tidak ada
11
+ // lease yang diakuisisi, tidak ada scheduler yang dipicu. Ia adalah indeks
12
+ // lintas sesi — persis batas yang ditetapkan roadmap P14: "Hasil agregasi
13
+ // adalah indeks/proyeksi lintas sesi. TaskStore tetap menjadi authority
14
+ // status tugas."
15
+ //
16
+ // Tiga aturan kejujuran yang dijaga di sini:
17
+ //
18
+ // 1. UNKNOWN dilabel, bukan disembunyikan. Task tanpa baris sesi di
19
+ // sessions.db = `SESSION_MISSING` — provenance tidak bisa ditelusuri,
20
+ // dan itu dinyatakan apa adanya.
21
+ // 2. Kemiripan judul BUKAN bukti identitas. Penanda duplikat lintas sesi
22
+ // hanya UNPROVEN; penggabungan tetap hanya lewat
23
+ // `TaskStore.declareTaskDuplicate` yang eksplisit + ber-evidence.
24
+ // 3. Closure feedback tidak menyimpulkan. Entri "closed" adalah baris yang
25
+ // SUDAH terminal di TaskStore (atau barisnya sudah tidak ada) DAN punya
26
+ // provenance P14, atau artefak intent yang eksplisit terminal dengan
27
+ // klaimnya dilabel verified/unverified. Status task selalu dibaca ulang
28
+ // dari tabel tasks saat proyeksi berjalan — duplikat yang dibuka kembali
29
+ // oleh operator otomatis muncul kembali sebagai open, tanpa tulisan apa
30
+ // pun dari lapisan ini.
31
+ //
32
+ // Intent dari histori HANYA berasal dari artefak terstruktur (plan/approval/
33
+ // delegation/run) — lihat `open-work-intent.ts`. Pesan bebas pengguna tidak
34
+ // pernah dipindai untuk "komitmen": roadmap P14 melarang menganggap
35
+ // brainstorming sebagai tugas.
36
+
37
+ import { resolve as resolvePath } from "node:path"
38
+ import type { TaskStatus, TaskVerification } from "../task/model.ts"
39
+ import type { ExecutionOwner, TaskMerge, TaskTransfer, UnfinishedWorkItem } from "../task/store.ts"
40
+ import { TaskStore } from "../task/store.ts"
41
+ import { readCheckpointInventorySync } from "./checkpoint.ts"
42
+ import {
43
+ buildWorkInventory,
44
+ classifySessionScopes,
45
+ extractIntentCandidates,
46
+ type IntentCandidate,
47
+ nextActionFor,
48
+ type OpenWorkState,
49
+ taskWorkState,
50
+ type WorkInventory,
51
+ type WorkPriorityLevel,
52
+ type WorkRunRow,
53
+ workPriority,
54
+ } from "./open-work-intent.ts"
55
+ import {
56
+ type RunInventoryRow,
57
+ readAllPresentationEventsReadOnly,
58
+ readRunRowsReadOnly,
59
+ readSessionInventoryRows,
60
+ readSessionMetaRows,
61
+ type SessionInventoryRow,
62
+ } from "./persistence.ts"
63
+
64
+ /**
65
+ * Batas usia default sebelum item disebut STALE (7 hari).
66
+ *
67
+ * Angka ini hanya soal PENANDA prioritas, bukan keputusan otoritas: item
68
+ * stale tetap valid dan tetap boleh diadopsi/dilanjutkan. Konstanta bernama
69
+ * supaya mengubahnya adalah tindakan yang terlihat.
70
+ */
71
+ export const DEFAULT_OPEN_WORK_STALE_MS = 7 * 24 * 60 * 60 * 1000
72
+
73
+ /**
74
+ * Kategori open-work — pemetaan MEKANIS dari `TaskStatus`, bukan inferensi.
75
+ * Setiap kategori berpasangan eksak dengan satu status; tidak ada tebakan
76
+ * "mungkin menunggu user" dari teks judul.
77
+ */
78
+ export type OpenWorkCategory =
79
+ | "OPEN"
80
+ | "IN_PROGRESS"
81
+ | "VERIFYING"
82
+ | "BLOCKED"
83
+ | "FAILED_NEEDS_FOLLOWUP"
84
+ | "RETRYING"
85
+
86
+ export function openWorkCategory(status: TaskStatus): OpenWorkCategory {
87
+ switch (status) {
88
+ case "PENDING":
89
+ return "OPEN"
90
+ case "IN_PROGRESS":
91
+ return "IN_PROGRESS"
92
+ case "VERIFYING":
93
+ return "VERIFYING"
94
+ case "BLOCKED":
95
+ return "BLOCKED"
96
+ case "FAILED":
97
+ return "FAILED_NEEDS_FOLLOWUP"
98
+ case "RETRYING":
99
+ return "RETRYING"
100
+ default:
101
+ // Fail-closed: status terminal tidak pernah menjadi item open-work.
102
+ // `listUnfinishedWork` memang hanya mengembalikan status non-terminal,
103
+ // jadi mencapai cabang ini berarti ada bug di discovery — jangan
104
+ // ditebak kategorinya.
105
+ throw new Error(`open-work: terminal status is never an open item: ${status}`)
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Kunci kemiripan judul — HANYA untuk penanda presentasi.
111
+ *
112
+ * Normalisasi: huruf kecil, buang semua karakter non-alnum, rangkum jadi satu
113
+ * spasi. Deterministik dan murni. Kunci yang sama TIDAK berarti dua task
114
+ * adalah pekerjaan yang sama (tugas berulang yang sengaja independen akan
115
+ * berbagi kunci); penggabungan tetap harus lewat `declareTaskDuplicate`.
116
+ */
117
+ export function normalizeTitleKey(title: string): string {
118
+ return title
119
+ .toLowerCase()
120
+ .replace(/[^a-z0-9]+/g, " ")
121
+ .trim()
122
+ }
123
+
124
+ /** Umur manusiawi yang deterministik dari `ageMs` (tidak pernah negatif). */
125
+ export function formatAge(ageMs: number): string {
126
+ const ms = Math.max(0, Math.floor(ageMs))
127
+ if (ms < 60_000) return "now"
128
+ const minutes = Math.floor(ms / 60_000)
129
+ if (minutes < 60) return `${minutes}m`
130
+ const hours = Math.floor(minutes / 60)
131
+ if (hours < 48) return `${hours}h`
132
+ const days = Math.floor(hours / 24)
133
+ return `${days}d`
134
+ }
135
+
136
+ // ── P14.1/P14.4 — bidang portofolio. SEMUANYA proyeksi, bukan otoritas ──────
137
+
138
+ /** Satu blocker eksplisit; detail wajib, tidak pernah "unknown" kosong. */
139
+ export interface WorkBlocker {
140
+ readonly kind: "TASK_BLOCKED" | "DEPENDENCY" | "VERIFICATION" | "PROVENANCE"
141
+ readonly detail: string
142
+ }
143
+
144
+ /** Dependensi kanonik task, direkonsiliasi ke status TaskStore saat baca. */
145
+ export interface WorkDependency {
146
+ readonly taskId: string
147
+ readonly title: string | null
148
+ readonly status: TaskStatus | "MISSING"
149
+ /** Hanya COMPLETED yang memuaskan; selain itu blocker eksplisit. */
150
+ readonly satisfied: boolean
151
+ }
152
+
153
+ /** Bukti plan terstruktur yang menunjuk task ini (provenance P14.2 penuh). */
154
+ export interface PlanStepEvidence {
155
+ readonly planId: string
156
+ readonly stepId: string
157
+ readonly claimedStatus: string
158
+ readonly eventSeq: number
159
+ readonly turnId: number
160
+ readonly observedAtIso: string
161
+ }
162
+
163
+ /**
164
+ * Grup duplikat lintas sesi — SELALU `UNPROVEN`.
165
+ *
166
+ * Kontrak P14.3: kemiripan lintas sesi diungkapkan sebagai konflik/kandidat,
167
+ * tidak pernah digabung otomatis. Perpindahan otoritas tetap wajib lewat
168
+ * adopsi eksplisit; merge tetap satu-sesi. `divergentStates` = item dalam
169
+ * grup mengklaim state berbeda — konflik yang harus dilihat operator.
170
+ */
171
+ export interface DuplicateGroupRef {
172
+ readonly key: string
173
+ readonly count: number
174
+ readonly sessions: readonly string[]
175
+ readonly divergentStates: boolean
176
+ readonly proven: false
177
+ }
178
+
179
+ /** Entri open-work: task non-terminal + provenance + penanda. */
180
+ export interface OpenWorkEntry {
181
+ readonly sessionId: string
182
+ readonly taskId: string
183
+ readonly title: string
184
+ readonly status: TaskStatus
185
+ readonly category: OpenWorkCategory
186
+ readonly revision: number
187
+ readonly createdAt: string
188
+ readonly updatedAt: string
189
+ readonly ageMs: number
190
+ readonly sessionIncarnation: number
191
+ /** `SESSION_MISSING` = tidak ada baris sessions.db → provenance UNKNOWN. */
192
+ readonly provenance: "SESSION_PRESENT" | "SESSION_MISSING"
193
+ readonly sessionUpdatedAtMs: number | null
194
+ readonly stale: boolean
195
+ readonly executionOwner: ExecutionOwner | null
196
+ readonly execGeneration: number
197
+ readonly attemptGeneration: number | null
198
+ readonly transferredFromSessionId: string | null
199
+ readonly transferredAt: string | null
200
+ /** Kunci kemiripan (presentasi saja; bukan bukti identitas). */
201
+ readonly titleKey: string
202
+ /** Berapa item open berbagi kunci judul. >1 = kandidat serupa UNPROVEN. */
203
+ readonly similarCount: number
204
+ /** State P14.1 berbasis bukti; beda dari `category` yang mekanis per status. */
205
+ readonly state: OpenWorkState
206
+ readonly stateReason: string
207
+ readonly priority: { level: WorkPriorityLevel; reason: string }
208
+ readonly blockers: readonly WorkBlocker[]
209
+ readonly dependencies: readonly WorkDependency[]
210
+ readonly nextAction: string
211
+ readonly verification: TaskVerification | null
212
+ /** Langkah plan terstruktur yang menunjuk task ini (provenance P14.2). */
213
+ readonly planSteps: readonly PlanStepEvidence[]
214
+ /** Grup duplikat lintas sesi (task + intent); SELALU UNPROVEN. */
215
+ readonly duplicate: DuplicateGroupRef | null
216
+ }
217
+
218
+ /**
219
+ * Entri closure feedback: pekerjaan dengan provenance P14 yang SUDAH tertutup
220
+ * di TaskStore, atau barisnya sudah tidak ada.
221
+ *
222
+ * `kind` menjawab "provenance penutupan apa yang dimiliki item ini":
223
+ * transfer lintas sesi, atau deklarasi duplikat. Status SELALU dibaca ulang
224
+ * dari tabel tasks — proyeksi tidak pernah menyimpan salinan status.
225
+ */
226
+ export interface ClosedWorkEntry {
227
+ readonly kind: "TRANSFERRED" | "MERGED_DUPLICATE" | "INTENT"
228
+ readonly sessionId: string
229
+ /** Null untuk closure intent tanpa task kanonik (mis. approval DECLINED). */
230
+ readonly taskId: string | null
231
+ readonly title: string | null
232
+ /** Status KANONIK saat ini, atau "MISSING" bila barisnya sudah tidak ada. */
233
+ readonly status: TaskStatus | "MISSING" | null
234
+ readonly closedAt: string | null
235
+ readonly revision: number | null
236
+ readonly transferredFromSessionId: string | null
237
+ readonly transferredAt: string | null
238
+ readonly mergeSurvivorId: string | null
239
+ readonly mergeEvidence: string | null
240
+ // ── P14.1/P14.6 — state intent + label klaim untuk closure artefak ──
241
+ /** State P14.1 dari closure ini (untuk kind INTENT; null bila task-based). */
242
+ readonly intentState: OpenWorkState | null
243
+ /**
244
+ * Label kejujuran klaim penyelesaian: `verified` = task kanonik dengan
245
+ * verification passed; `unverified` = klaim artefak tanpa verifikasi
246
+ * (ditampilkan apa adanya, BUKAN disembunyikan); `not-applicable` =
247
+ * DECLINED/CANCELLED (tidak ada klaim penyelesaian untuk diverifikasi).
248
+ */
249
+ readonly claim: "verified" | "unverified" | "not-applicable"
250
+ /** Alasan closure eksplisit — wajib untuk kind INTENT. */
251
+ readonly reason: string
252
+ }
253
+
254
+ export interface OpenWorkReport {
255
+ readonly generatedAtIso: string
256
+ readonly staleMs: number
257
+ readonly open: readonly OpenWorkEntry[]
258
+ /**
259
+ * Kandidat intent open dari histori terstruktur (P14.2 penuh): approval
260
+ * yang menunggu, delegasi sub-agent tanpa hasil terminal, run terputus,
261
+ * langkah plan tanpa task kanonik. SEMUANYA proyeksi berprovenance; tidak
262
+ * ada satu pun yang otomatis dieksekusi.
263
+ */
264
+ readonly intent: readonly IntentCandidate[]
265
+ /** Grup duplikat lintas sesi (task + intent) — SELALU UNPROVEN. */
266
+ readonly duplicateGroups: readonly DuplicateGroupRef[]
267
+ readonly closed: readonly ClosedWorkEntry[]
268
+ /** Inventaris P14.0; null kecuali diminta eksplisit. */
269
+ readonly inventory: WorkInventory | null
270
+ /** Event presentasi yang gagal didekode — bukti tak terbaca, tidak disembunyikan. */
271
+ readonly rejectedEvents: number
272
+ readonly counts: {
273
+ readonly open: number
274
+ readonly stale: number
275
+ readonly unknownProvenance: number
276
+ /** Jumlah kunci judul yang dibagi >1 item open (kandidat UNPROVEN). */
277
+ readonly similarGroups: number
278
+ readonly closed: number
279
+ /** Kandidat intent open (non-terminal, tanpa task kanonik). */
280
+ readonly intent: number
281
+ /** Grup duplikat lintas sesi (count > 1, lintas task+intent). */
282
+ readonly duplicateGroups: number
283
+ /** Grup duplikat yang state-nya saling bertentangan (wajib dilihat). */
284
+ readonly conflicts: number
285
+ }
286
+ }
287
+
288
+ export interface ProjectOpenWorkOptions {
289
+ readonly cwd?: string
290
+ /** Waktu evaluasi; default `Date.now()`. Tes menyuntikkan nilai tetap. */
291
+ readonly now?: number
292
+ /** Ambang STALE; default `DEFAULT_OPEN_WORK_STALE_MS`. */
293
+ readonly staleMs?: number
294
+ /** Batasi ke satu sesi (namespace TaskStore). */
295
+ readonly sessionId?: string
296
+ /** Sertakan seksi closure feedback (default false: hanya open). */
297
+ readonly includeClosed?: boolean
298
+ /** Sertakan ekstraksi intent dari histori (default true). */
299
+ readonly includeIntent?: boolean
300
+ /** Sertakan inventaris P14.0 (default false; membaca lebih banyak sumber). */
301
+ readonly includeInventory?: boolean
302
+ /** Batas kandidat intent (default di modul kontrak). */
303
+ readonly maxIntentCandidates?: number
304
+ }
305
+
306
+ const TERMINAL_STATUSES: ReadonlySet<TaskStatus> = new Set(["COMPLETED", "CANCELLED"])
307
+
308
+ function toMs(iso: string): number {
309
+ const t = Date.parse(iso)
310
+ return Number.isFinite(t) ? t : 0
311
+ }
312
+
313
+ /**
314
+ * Proyeksikan open-work lintas sesi untuk SATU workspace.
315
+ *
316
+ * Cakupan mengikuti `tasks.db` (per-workspace): sesi proyek lain memang tak
317
+ * terlihat, dan itu batas yang benar — tanpa aturan merge lintas-proyek,
318
+ * menggabungkan keduanya akan menyatukan pekerjaan yang berbeda. Sesi dari
319
+ * histori dibatasi lebih jauh oleh binding `cwd` baris sesi (P14.0): sesi
320
+ * milik workspace lain dilabel FOREIGN_WORKSPACE dan dikeluarkan; sesi tanpa
321
+ * binding dilabel UNBOUND_WORKSPACE — tidak ada yang ditebak milik sini.
322
+ */
323
+ export function projectOpenWork(opts: ProjectOpenWorkOptions = {}): OpenWorkReport {
324
+ const now = opts.now ?? Date.now()
325
+ const staleMs = opts.staleMs ?? DEFAULT_OPEN_WORK_STALE_MS
326
+ const store = new TaskStore(opts.cwd)
327
+ const workspace = resolvePath(opts.cwd ?? process.cwd())
328
+
329
+ const items: readonly UnfinishedWorkItem[] = store.listUnfinishedWork(opts.sessionId)
330
+ const sessionMeta = new Map(readSessionMetaRows(opts.cwd).map((r) => [r.id, r]))
331
+
332
+ // ── sumber histori + runtime (P14.0/P14.2) — semua jalur baca read-only ──
333
+ const wantHistory = opts.includeIntent !== false || opts.includeInventory === true
334
+ const inventoryRows: readonly SessionInventoryRow[] = wantHistory
335
+ ? readSessionInventoryRows(opts.cwd)
336
+ : []
337
+ const eventLoad = wantHistory
338
+ ? readAllPresentationEventsReadOnly(opts.cwd)
339
+ : { events: [], rejected: 0 }
340
+ /** Event presentasi yang gagal didekode — dilaporkan, tidak disembunyikan. */
341
+ const rejectedEvents: number = eventLoad.rejected
342
+ const runRows: readonly RunInventoryRow[] = wantHistory ? readRunRowsReadOnly(opts.cwd) : []
343
+ const workSessions = inventoryRows.map((r) => ({
344
+ id: r.id,
345
+ createdAtMs: r.created_at,
346
+ updatedAtMs: r.updated_at,
347
+ cwd: r.cwd,
348
+ parentSessionId: r.parent_session_id,
349
+ }))
350
+ const workRuns: readonly WorkRunRow[] = runRows
351
+ .filter(
352
+ (
353
+ r,
354
+ ): r is RunInventoryRow & {
355
+ status: "CREATED" | "RUNNING" | "COMPLETED" | "INTERRUPTED" | "FAILED"
356
+ } =>
357
+ r.status === "CREATED" ||
358
+ r.status === "RUNNING" ||
359
+ r.status === "COMPLETED" ||
360
+ r.status === "INTERRUPTED" ||
361
+ r.status === "FAILED",
362
+ )
363
+ .map((r) => ({
364
+ runId: r.run_id,
365
+ sessionId: r.session_id,
366
+ status: r.status,
367
+ startedAtMs: r.started_at,
368
+ endedAtMs: r.ended_at,
369
+ recoveryStatus: r.recovery_status,
370
+ }))
371
+ const rawCandidates = extractIntentCandidates({
372
+ workspace,
373
+ sessions: workSessions,
374
+ events: eventLoad.events,
375
+ runs: workRuns,
376
+ ...(opts.maxIntentCandidates !== undefined ? { maxCandidates: opts.maxIntentCandidates } : {}),
377
+ })
378
+ // Filter `--session` berlaku konsisten untuk task DAN intent: bila operator
379
+ // membatasi laporan ke satu sesi, kandidat sesi lain bukan bagian laporan
380
+ // yang diminta.
381
+ const candidates: readonly IntentCandidate[] =
382
+ opts.includeIntent === false
383
+ ? []
384
+ : opts.sessionId !== undefined
385
+ ? rawCandidates.filter((c) => c.sessionId === opts.sessionId)
386
+ : rawCandidates
387
+
388
+ // Kunci kemiripan dihitung dulu agar `similarCount` akurat untuk semua item.
389
+ const titleKeys = items.map((i) => normalizeTitleKey(i.task.title))
390
+ const keyCounts = new Map<string, number>()
391
+ for (const key of titleKeys) {
392
+ if (key.length === 0) continue
393
+ keyCounts.set(key, (keyCounts.get(key) ?? 0) + 1)
394
+ }
395
+
396
+ const open: OpenWorkEntry[] = items.map((item, idx) => {
397
+ const meta = sessionMeta.get(item.sessionId)
398
+ const ageMs = Math.max(0, now - toMs(item.task.updatedAt))
399
+ const titleKey = titleKeys[idx] ?? ""
400
+
401
+ // ── P14.4: dependensi direkonsiliasi ke status kanonik saat baca ──
402
+ const dependencies: WorkDependency[] = item.task.dependsOn.map((depId) => {
403
+ const dep = store.getTask(item.sessionId, depId)
404
+ const status: TaskStatus | "MISSING" = dep?.status ?? "MISSING"
405
+ return {
406
+ taskId: depId,
407
+ title: dep?.title ?? null,
408
+ status,
409
+ satisfied: status === "COMPLETED",
410
+ }
411
+ })
412
+
413
+ // ── P14.1: state berbasis bukti, bukan tebakan ──
414
+ const unresolvedDep = dependencies.find((d) => !d.satisfied)
415
+ const { state, reason: stateReason } = taskWorkState(item.task.status, {
416
+ verification: item.task.verification,
417
+ unresolvedDependency: unresolvedDep !== undefined,
418
+ })
419
+
420
+ // ── P14.4: blocker eksplisit (blocker kosong = tidak ada yang diklaim) ──
421
+ const blockers: WorkBlocker[] = []
422
+ if (item.task.blockedReason !== null && item.task.blockedReason.trim() !== "") {
423
+ blockers.push({ kind: "TASK_BLOCKED", detail: item.task.blockedReason })
424
+ }
425
+ for (const d of dependencies) {
426
+ if (!d.satisfied) {
427
+ blockers.push({ kind: "DEPENDENCY", detail: `${d.taskId} (${d.status})` })
428
+ }
429
+ }
430
+ if (item.task.verification?.verdict === "failed") {
431
+ blockers.push({
432
+ kind: "VERIFICATION",
433
+ detail: item.task.verification.detail ?? "verification failed",
434
+ })
435
+ }
436
+
437
+ const priority = workPriority(state, ageMs >= staleMs)
438
+ const topBlocker = blockers[0]?.detail ?? ""
439
+ const planSteps: PlanStepEvidence[] = candidates
440
+ .filter(
441
+ (c): boolean =>
442
+ c.source === "PLAN_STEP" &&
443
+ c.sessionId === item.sessionId &&
444
+ c.provenance.taskId === item.task.id,
445
+ )
446
+ .map((c) => ({
447
+ planId: c.provenance.planId ?? "",
448
+ stepId: c.provenance.stepId ?? "",
449
+ claimedStatus: c.artifactStatus ?? "?",
450
+ eventSeq: c.provenance.eventSeq ?? -1,
451
+ turnId: c.provenance.turnId ?? -1,
452
+ observedAtIso: c.observedAtIso,
453
+ }))
454
+
455
+ return {
456
+ sessionId: item.sessionId,
457
+ taskId: item.task.id,
458
+ title: item.task.title,
459
+ status: item.task.status,
460
+ category: openWorkCategory(item.task.status),
461
+ revision: item.task.revision,
462
+ createdAt: item.task.createdAt,
463
+ updatedAt: item.task.updatedAt,
464
+ ageMs,
465
+ sessionIncarnation: item.sessionIncarnation,
466
+ provenance: meta === undefined ? "SESSION_MISSING" : "SESSION_PRESENT",
467
+ sessionUpdatedAtMs: meta === undefined ? null : meta.updated_at,
468
+ stale: ageMs >= staleMs,
469
+ executionOwner: item.executionOwner,
470
+ execGeneration: item.execGeneration,
471
+ attemptGeneration: item.attemptGeneration,
472
+ transferredFromSessionId: item.transferredFromSessionId,
473
+ transferredAt: item.transferredAt,
474
+ titleKey,
475
+ similarCount: titleKey.length === 0 ? 1 : (keyCounts.get(titleKey) ?? 1),
476
+ state,
477
+ stateReason,
478
+ priority,
479
+ blockers,
480
+ dependencies,
481
+ nextAction: nextActionFor(state, topBlocker),
482
+ verification: item.task.verification ?? null,
483
+ planSteps,
484
+ // Diisi setelah grup duplikat lintas sesi dihitung di bawah.
485
+ duplicate: null,
486
+ }
487
+ })
488
+ // Tertua dulu (portofolio = prioritas lanjutan), tie-breaker deterministik.
489
+ open.sort((a, b) => {
490
+ if (a.ageMs !== b.ageMs) return b.ageMs - a.ageMs
491
+ if (a.sessionId !== b.sessionId) return a.sessionId < b.sessionId ? -1 : 1
492
+ return a.taskId < b.taskId ? -1 : a.taskId > b.taskId ? 1 : 0
493
+ })
494
+
495
+ const similarGroups = [...keyCounts.values()].filter((n) => n > 1).length
496
+
497
+ // ── P14.3 penuh: grup duplikat LINTAS SESI (task + intent), SELALU UNPROVEN ──
498
+ // Kemiripan tidak pernah jadi merge otomatis; perpindahan otoritas tetap
499
+ // lewat adopsi eksplisit, merge tetap satu-sesi. Grup hanya MENGUNGKAP:
500
+ // count, sesi mana saja, dan apakah state-nya saling bertentangan.
501
+ const groupAgg = new Map<
502
+ string,
503
+ { count: number; sessions: Set<string>; states: Set<OpenWorkState> }
504
+ >()
505
+ const addToGroups = (key: string, sessionId: string, state: OpenWorkState): void => {
506
+ if (key.length === 0) return
507
+ let g = groupAgg.get(key)
508
+ if (g === undefined) {
509
+ g = { count: 0, sessions: new Set(), states: new Set() }
510
+ groupAgg.set(key, g)
511
+ }
512
+ g.count++
513
+ g.sessions.add(sessionId)
514
+ g.states.add(state)
515
+ }
516
+ for (const e of open) addToGroups(e.titleKey, e.sessionId, e.state)
517
+
518
+ // ── P14.2: pisahkan kandidat intent ─────────────────────────────────────
519
+ // (1) plan step dengan taskId yang task-nya OPEN → diwakili task kanonik,
520
+ // bukan item duplikat (bukti menempel di entry.planSteps);
521
+ // (2) plan step dengan taskId yang task-nya TERMINAL → TIDAK dihidupkan
522
+ // kembali (larangan P14); masuk closure INTENT dengan konflik klaim
523
+ // plan vs status kanonik yang diungkapkan eksplisit;
524
+ // (3) sisanya (approval menunggu/ditolak, delegasi, run terputus, langkah
525
+ // plan tanpa task / baris task hilang) → open bila non-terminal,
526
+ // closure bila terminal.
527
+ const openIntent: IntentCandidate[] = []
528
+ const closedIntentCandidates: IntentCandidate[] = []
529
+ const supersededPlanClaims: {
530
+ candidate: IntentCandidate
531
+ taskStatus: TaskStatus
532
+ taskUpdatedAt: string
533
+ verified: boolean
534
+ }[] = []
535
+ for (const c of candidates) {
536
+ if (c.source === "PLAN_STEP" && c.provenance.taskId !== null) {
537
+ const task = store.getTask(c.sessionId, c.provenance.taskId)
538
+ if (task !== null) {
539
+ // Klaim plan menunjuk task kanonik yang ADA → task adalah otoritas.
540
+ if (!TERMINAL_STATUSES.has(task.status)) {
541
+ continue // (1) task masih open: entry task mewakili, bukti di planSteps
542
+ }
543
+ // (2) task terminal: jangan hidupkan kembali; ungkap konflik klaim.
544
+ supersededPlanClaims.push({
545
+ candidate: c,
546
+ taskStatus: task.status,
547
+ taskUpdatedAt: task.updatedAt,
548
+ verified: task.verification?.verdict === "passed",
549
+ })
550
+ continue
551
+ }
552
+ // Baris task hilang: klaim plan tetap bukti terstruktur, dilanjutkan
553
+ // dengan state dari plan step itu sendiri (jujur, tanpa menebak).
554
+ }
555
+ if (c.terminal) closedIntentCandidates.push(c)
556
+ else openIntent.push(c) // (3)
557
+ }
558
+ // Kandidat intent open juga masuk peta grup duplikat.
559
+ for (const c of openIntent) addToGroups(normalizeTitleKey(c.summary), c.sessionId, c.state)
560
+
561
+ const duplicateGroups: DuplicateGroupRef[] = [...groupAgg.entries()]
562
+ .filter(([, v]) => v.count > 1)
563
+ .map(([key, v]) => ({
564
+ key,
565
+ count: v.count,
566
+ sessions: [...v.sessions].sort(),
567
+ divergentStates: v.states.size > 1,
568
+ proven: false as const,
569
+ }))
570
+ .sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0))
571
+ const duplicateByKey = new Map(duplicateGroups.map((g) => [g.key, g]))
572
+ // Entri bersifat readonly: hubungkan grup duplikat lewat pemetaan baru,
573
+ // bukan mutasi properti (proyeksi tidak pernah mengubah apa pun setelah
574
+ // konstruksi — konsisten dengan kontrak kemurniannya).
575
+ const openWithDuplicates: readonly OpenWorkEntry[] = open.map((e) =>
576
+ e.titleKey.length > 0 && duplicateByKey.has(e.titleKey)
577
+ ? { ...e, duplicate: duplicateByKey.get(e.titleKey) ?? null }
578
+ : e,
579
+ )
580
+ const conflicts = duplicateGroups.filter((g) => g.divergentStates).length
581
+
582
+ // ── closure feedback (P14.6) ─────────────────────────────────────────────
583
+ // Task-based: hanya item dengan provenance P14 (ledger transfer/merge);
584
+ // closure feedback adalah jawaban atas "pekerjaan yang diadopsi/didedup —
585
+ // sudah tertutupkah?", bukan daftar seluruh task terminal yang pernah ada.
586
+ // Intent-based: artefak terstruktur yang eksplisit terminal, DENGAN label
587
+ // klaim (verified/unverified/not-applicable) supaya klaim penyelesaian
588
+ // tanpa verifikasi tidak pernah tampil seolah-olah terbukti.
589
+ const closed: ClosedWorkEntry[] = []
590
+ if (opts.includeClosed === true) {
591
+ const inScope = (sessionId: string): boolean =>
592
+ opts.sessionId === undefined || sessionId === opts.sessionId
593
+
594
+ const transfers: readonly TaskTransfer[] = store
595
+ .listTaskTransfers()
596
+ .filter((t) => inScope(t.toSessionId))
597
+ for (const t of transfers) {
598
+ const task = store.getTask(t.toSessionId, t.taskId)
599
+ if (task !== null && !TERMINAL_STATUSES.has(task.status)) continue
600
+ closed.push({
601
+ kind: "TRANSFERRED",
602
+ sessionId: t.toSessionId,
603
+ taskId: t.taskId,
604
+ title: task?.title ?? null,
605
+ status: task?.status ?? "MISSING",
606
+ closedAt: task?.updatedAt ?? null,
607
+ revision: task?.revision ?? null,
608
+ transferredFromSessionId: t.fromSessionId,
609
+ transferredAt: t.transferredAt,
610
+ mergeSurvivorId: null,
611
+ mergeEvidence: null,
612
+ intentState: null,
613
+ claim:
614
+ task === null
615
+ ? "not-applicable"
616
+ : task.status === "CANCELLED"
617
+ ? "not-applicable"
618
+ : task.verification?.verdict === "passed"
619
+ ? "verified"
620
+ : "unverified",
621
+ reason:
622
+ task === null
623
+ ? "task row removed after transfer (ledger is the evidence)"
624
+ : `canonical status ${task.status}`,
625
+ })
626
+ }
627
+
628
+ const merges: readonly TaskMerge[] = store.listTaskMerges().filter((m) => inScope(m.sessionId))
629
+ for (const m of merges) {
630
+ const dup = store.getTask(m.sessionId, m.duplicateId)
631
+ // Duplikat yang dibuka kembali operator TIDAK masuk daftar closed —
632
+ // ia jujur muncul kembali di seksi open. Ledger tetap memuat
633
+ // deklarasi lama sebagai sejarah audit.
634
+ if (dup !== null && !TERMINAL_STATUSES.has(dup.status)) continue
635
+ closed.push({
636
+ kind: "MERGED_DUPLICATE",
637
+ sessionId: m.sessionId,
638
+ taskId: m.duplicateId,
639
+ title: dup?.title ?? null,
640
+ status: dup?.status ?? "MISSING",
641
+ closedAt: dup?.updatedAt ?? m.mergedAt,
642
+ revision: dup?.revision ?? m.duplicateRevision,
643
+ transferredFromSessionId: null,
644
+ transferredAt: null,
645
+ mergeSurvivorId: m.survivorId,
646
+ mergeEvidence: m.evidence,
647
+ intentState: null,
648
+ claim: "not-applicable",
649
+ reason: `duplicate of ${m.survivorId}: ${m.evidence}`,
650
+ })
651
+ }
652
+
653
+ // Klaim plan yang tersapu status kanonik terminal — konflik diungkap, tidak
654
+ // disembunyikan, dan TIDAK menghidupkan kembali apa pun (larangan P14).
655
+ for (const s of supersededPlanClaims) {
656
+ closed.push({
657
+ kind: "INTENT",
658
+ sessionId: s.candidate.sessionId,
659
+ taskId: s.candidate.provenance.taskId,
660
+ title: s.candidate.summary,
661
+ status: s.taskStatus,
662
+ closedAt: s.taskUpdatedAt,
663
+ revision: null,
664
+ transferredFromSessionId: null,
665
+ transferredAt: null,
666
+ mergeSurvivorId: null,
667
+ mergeEvidence: null,
668
+ intentState: s.taskStatus === "COMPLETED" ? "COMPLETED" : "CANCELLED",
669
+ claim:
670
+ s.taskStatus === "CANCELLED" ? "not-applicable" : s.verified ? "verified" : "unverified",
671
+ reason: `canonical task ${s.taskStatus} supersedes plan claim (${s.candidate.reason})`,
672
+ })
673
+ }
674
+
675
+ // Artefak intent yang eksplisit terminal (approval DECLINED, plan step
676
+ // completed/cancelled tanpa task, delegasi dengan hasil terminal).
677
+ for (const c of closedIntentCandidates) {
678
+ if (!inScope(c.sessionId)) continue
679
+ closed.push({
680
+ kind: "INTENT",
681
+ sessionId: c.sessionId,
682
+ taskId: c.provenance.taskId,
683
+ title: c.summary,
684
+ status: null,
685
+ closedAt: c.observedAtIso,
686
+ revision: null,
687
+ transferredFromSessionId: null,
688
+ transferredAt: null,
689
+ mergeSurvivorId: null,
690
+ mergeEvidence: null,
691
+ intentState: c.state,
692
+ claim: c.state === "COMPLETED" ? "unverified" : "not-applicable",
693
+ reason: c.reason,
694
+ })
695
+ }
696
+
697
+ closed.sort((a, b) => {
698
+ const at = toMs(a.closedAt ?? "")
699
+ const bt = toMs(b.closedAt ?? "")
700
+ if (at !== bt) return bt - at
701
+ if (a.sessionId !== b.sessionId) return a.sessionId < b.sessionId ? -1 : 1
702
+ const atid = a.taskId ?? ""
703
+ const btid = b.taskId ?? ""
704
+ return atid < btid ? -1 : atid > btid ? 1 : 0
705
+ })
706
+ }
707
+
708
+ // ── inventaris P14.0 (hanya bila diminta — membaca lebih banyak sumber) ──
709
+ let inventory: WorkInventory | null = null
710
+ if (opts.includeInventory === true) {
711
+ const allTasks = store.listAllTasks()
712
+ const openCount = store.listUnfinishedWork().length
713
+ const sessionScopes = classifySessionScopes(workspace, workSessions)
714
+ let sessionsWithManifest = 0
715
+ let checkpointEntries = 0
716
+ let corruptManifests = 0
717
+ for (const s of workSessions) {
718
+ if (sessionScopes.get(s.id) !== "IN_SCOPE") continue
719
+ const cp = readCheckpointInventorySync(s.id, opts.cwd)
720
+ if (!cp.exists) continue
721
+ sessionsWithManifest++
722
+ if (cp.corrupt) {
723
+ corruptManifests++
724
+ continue
725
+ }
726
+ checkpointEntries += cp.checkpointCount
727
+ }
728
+ inventory = buildWorkInventory({
729
+ workspace,
730
+ sessions: workSessions,
731
+ events: eventLoad.events,
732
+ runs: workRuns,
733
+ candidates,
734
+ taskCounts: {
735
+ total: allTasks.length,
736
+ open: openCount,
737
+ terminal: allTasks.length - openCount,
738
+ },
739
+ checkpoints: {
740
+ sessionsWithManifest,
741
+ entries: checkpointEntries,
742
+ corrupt: corruptManifests,
743
+ },
744
+ })
745
+ }
746
+
747
+ return {
748
+ generatedAtIso: new Date(now).toISOString(),
749
+ staleMs,
750
+ open: openWithDuplicates,
751
+ intent: openIntent,
752
+ duplicateGroups,
753
+ closed,
754
+ inventory,
755
+ rejectedEvents,
756
+ counts: {
757
+ open: open.length,
758
+ stale: open.filter((e) => e.stale).length,
759
+ unknownProvenance: open.filter((e) => e.provenance === "SESSION_MISSING").length,
760
+ similarGroups,
761
+ closed: closed.length,
762
+ intent: openIntent.length,
763
+ duplicateGroups: duplicateGroups.length,
764
+ conflicts,
765
+ },
766
+ }
767
+ }