agentwrangler 0.1.1-next.bca85ea → 0.1.1-next.e259583

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 (83) hide show
  1. package/dist/daemon/http.js +8 -0
  2. package/dist/daemon/index.js +40 -81
  3. package/dist/daemon/lifecycle.js +122 -0
  4. package/dist/daemon/router.js +255 -8
  5. package/dist/db/migrations/019_work_records.sql +291 -0
  6. package/dist/detector/d7-loop-analysis.js +142 -0
  7. package/dist/detector/detectors/d7_loop_retry_waste.js +14 -127
  8. package/dist/effects/engine.js +27 -10
  9. package/dist/effects/index.js +1 -0
  10. package/dist/effects/registry.js +87 -6
  11. package/dist/effects/scope-identity.js +19 -0
  12. package/dist/effects/sql-observer.js +322 -8
  13. package/dist/ingest/ingestor.js +322 -73
  14. package/dist/ingest/tail.js +130 -20
  15. package/dist/query/api/effect-service.js +2 -0
  16. package/dist/query/api/esf-observations.js +117 -62
  17. package/dist/query/api/overview.js +28 -1
  18. package/dist/query/api/reported-work.js +46 -0
  19. package/dist/query/api/session-drivers.js +1 -1
  20. package/dist/query/api/spend-flavor.js +22 -15
  21. package/dist/query/api/trends.js +86 -6
  22. package/dist/query/api/work-records.js +85 -0
  23. package/dist/query/settings-store.js +9 -0
  24. package/dist/query/spend.js +27 -13
  25. package/dist/query/trends.js +27 -0
  26. package/dist/ui/assets/{BarChart-CIjCNfbI.js → BarChart-BfXUnteT.js} +1 -1
  27. package/dist/ui/assets/{BriefsPage-DIU8iFjV.js → BriefsPage-sn0-W0B4.js} +2 -2
  28. package/dist/ui/assets/{CacheWriteSpikesChart-1Nfnf7OX.js → CacheWriteSpikesChart-BlPZoXw7.js} +1 -1
  29. package/dist/ui/assets/{CartesianChart-DEnDOGKj.js → CartesianChart-D1C-ogvR.js} +19 -19
  30. package/dist/ui/assets/{Chip-s-32Dh3o.js → Chip-C8W1t74q.js} +1 -1
  31. package/dist/ui/assets/{ComposedChart-DUw8Y79v.js → ComposedChart-XQUPrkCS.js} +1 -1
  32. package/dist/ui/assets/{EmptyState-B8vpug3_.js → EmptyState-D6N4lUxb.js} +1 -1
  33. package/dist/ui/assets/FlavorDecomposition-BQV0Lk8v.js +1 -0
  34. package/dist/ui/assets/{FrictionCell-X75fKRBK.js → FrictionCell-Daijc0EC.js} +1 -1
  35. package/dist/ui/assets/{GlossaryPage-D1tYumqL.js → GlossaryPage-7_-coeLS.js} +1 -1
  36. package/dist/ui/assets/HotSessionsPage-DlDACLnm.js +1 -0
  37. package/dist/ui/assets/InfoTip-a2EJ0069.js +1 -0
  38. package/dist/ui/assets/{Legend-CB7sqqJH.js → Legend-cxA5nzh-.js} +1 -1
  39. package/dist/ui/assets/{Line-B9XY30uT.js → Line-kB1VJp4g.js} +1 -1
  40. package/dist/ui/assets/Modal-CFfklbqC.js +1 -0
  41. package/dist/ui/assets/ObservationEvidence--afwnISx.js +1 -0
  42. package/dist/ui/assets/ObservationEvidence-Bhnk-xkX.css +1 -0
  43. package/dist/ui/assets/OverviewPage-CBC7Qfkv.js +2 -0
  44. package/dist/ui/assets/RecommendationsPage-CjOd8haz.js +2 -0
  45. package/dist/ui/assets/{Scatter-BSWm_yIZ.js → Scatter-DZ5NglvP.js} +1 -1
  46. package/dist/ui/assets/SectionHeader-5oD6BJ5B.js +1 -0
  47. package/dist/ui/assets/SessionDetailPage-CVWjfdXl.js +1 -0
  48. package/dist/ui/assets/SettingsPage-NRR_6ITw.js +25 -0
  49. package/dist/ui/assets/Skeleton-CXrrpK3l.js +1 -0
  50. package/dist/ui/assets/SpendPercentileChip-DG-3Uxu2.js +1 -0
  51. package/dist/ui/assets/{TrendChart-BSLwlBiq.js → TrendChart-BzE5wAGh.js} +1 -1
  52. package/dist/ui/assets/WorkspaceDetailPage-DWudWMsb.js +1 -0
  53. package/dist/ui/assets/WorkspacesPage-1iY1rR05.js +1 -0
  54. package/dist/ui/assets/{chart-theme-DYgw_Tac.js → chart-theme-Bp6VGdf_.js} +1 -1
  55. package/dist/ui/assets/{graphicalItemSelectors-0-Ue_y1f.js → graphicalItemSelectors-DkZEtnAz.js} +1 -1
  56. package/dist/ui/assets/index-CkFwfN3_.css +1 -0
  57. package/dist/ui/assets/index-Dhqjt9Dc.js +41 -0
  58. package/dist/ui/assets/{prompt-templates-CVzMex9L.js → prompt-templates-m8ECNL1W.js} +1 -1
  59. package/dist/ui/assets/short-id-C12NbqLn.js +1 -0
  60. package/dist/ui/assets/{useExperimentalActions-aI00AFZv.js → useExperimentalActions-DTkahL7q.js} +1 -1
  61. package/dist/ui/assets/workspace-names-BFeVn_ot.js +1 -0
  62. package/dist/ui/index.html +2 -2
  63. package/dist/work-records/allocation.js +242 -0
  64. package/dist/work-records/ids.js +80 -0
  65. package/dist/work-records/index.js +4 -0
  66. package/dist/work-records/store.js +376 -0
  67. package/dist/work-records/types.js +29 -0
  68. package/dist/work-records/validation.js +71 -0
  69. package/package.json +2 -1
  70. package/dist/ui/assets/FlavorDecomposition-CkHX3M-U.js +0 -1
  71. package/dist/ui/assets/HotSessionsPage-8HlRe0VB.js +0 -1
  72. package/dist/ui/assets/InfoTip-CL8RC4vz.js +0 -1
  73. package/dist/ui/assets/OverviewPage-DL4joBBE.js +0 -2
  74. package/dist/ui/assets/RecommendationsPage-NkfH17eB.js +0 -2
  75. package/dist/ui/assets/SessionDetailPage-Ceqt7poO.js +0 -1
  76. package/dist/ui/assets/SettingsPage-ZK4ii5h_.js +0 -25
  77. package/dist/ui/assets/Skeleton-Dp_m79B8.js +0 -1
  78. package/dist/ui/assets/SpendPercentileChip-CzY6h1gP.js +0 -1
  79. package/dist/ui/assets/WorkspaceDetailPage-DFOdEB39.js +0 -1
  80. package/dist/ui/assets/WorkspacesPage-Doct6meK.js +0 -1
  81. package/dist/ui/assets/index-D_IJsvkJ.css +0 -1
  82. package/dist/ui/assets/index-DhFiA8Ch.js +0 -41
  83. package/dist/ui/assets/workspace-label-CysPJNc0.js +0 -1
@@ -140,6 +140,14 @@ function requiresSessionToken(pathname) {
140
140
  return true;
141
141
  if (/^\/api\/esf\/effects\/(track|stop|close|rollback|attest-rollback)$/.test(pathname))
142
142
  return true;
143
+ if (pathname === "/api/work-records" || pathname === "/api/work-records/ids")
144
+ return true;
145
+ if (/^\/api\/work-records\/[^/]+\/(edit|closeout|archive|reopen|sessions|contexts|delete)$/.test(pathname))
146
+ return true;
147
+ if (/^\/api\/work-records\/[^/]+\/(sessions|contexts)\/[^/]+\/detach$/.test(pathname))
148
+ return true;
149
+ if (pathname === "/api/work-records/allocations/recompute")
150
+ return true;
143
151
  return false;
144
152
  }
145
153
  /**
@@ -38,6 +38,7 @@ import { getSettingsData, setHealthInstance, setRuntimeResetHook, } from "../que
38
38
  import { loadConfig } from "./config.js";
39
39
  import { runEffectMeasurementPass } from "./effect-pass.js";
40
40
  import { createServer } from "./http.js";
41
+ import { createDaemonLifecycle } from "./lifecycle.js";
41
42
  import { createOutcomesPassRunner } from "./outcomes-pass.js";
42
43
  import { setReady, setScanRoots, setScanState } from "./readiness.js";
43
44
  const VERSION = "0.1.0";
@@ -171,10 +172,6 @@ runProbePass("boot");
171
172
  // The runner (src/daemon/outcomes-pass.ts) adds a hard 15-min per-pass deadline:
172
173
  // a hung pass can no longer wedge the poll cadence forever — the running flag
173
174
  // always clears and the next poll resumes.
174
- let outcomesTimer = null;
175
- let reportsTimer = null;
176
- let reportsRunning = false;
177
- let bptCalibrationTimer = null;
178
175
  const outcomesRunner = createOutcomesPassRunner({
179
176
  db,
180
177
  probe: () => runProbePass("poll"),
@@ -188,29 +185,31 @@ const outcomesRunner = createOutcomesPassRunner({
188
185
  function runOutcomesPass() {
189
186
  return outcomesRunner.run();
190
187
  }
188
+ // R12 bytes→token calibration — best-effort, never crash the daemon.
189
+ // Runs on boot (deferred) and weekly when: opt-in enabled AND ratio is absent
190
+ // or older than 30 days. Mirrors the outcomes bootstrap pattern.
191
+ const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
192
+ function runBptCalibrationIfStale() {
193
+ const enabled = bptConfigGet(db, "bytes_per_token_calibration_enabled");
194
+ if (enabled !== "true")
195
+ return;
196
+ const measuredAt = bptConfigGet(db, "bytes_per_token_measured_at");
197
+ if (measuredAt !== null && Date.now() - new Date(measuredAt).getTime() < THIRTY_DAYS_MS)
198
+ return;
199
+ calibrateBytesPerToken(db).catch((e) => {
200
+ console.error(`Bytes-per-token calibration failed (non-fatal): ${e instanceof Error ? e.message : String(e)}`);
201
+ });
202
+ }
191
203
  // ── Deferred boot scan (runs AFTER the HTTP port is bound) ───────────────────
192
204
  // startTailBatched() performs a yielding initial back-scan (ingestAllKnown +
193
205
  // reconcile), then arms the tail/discovery timers. We do NOT
194
206
  // also call runBackscan — that would spin up a second Ingestor whose separate
195
207
  // Health instance is the one surfaced in Settings. One Ingestor, one Health.
196
208
  // Bounded: if ingestion fails to start, still serve the dashboard (degraded).
197
- let handle = null;
198
- // One-shot guard: runBootScan executes exactly once regardless of how many
199
- // requests or timers fire kickBootScan concurrently.
200
- let scanKicked = false;
201
- function kickBootScan() {
202
- if (scanKicked)
203
- return;
204
- scanKicked = true;
205
- // Use setImmediate so the triggering HTTP response flushes before boot work
206
- // starts. The scan itself also yields between bounded batches.
207
- setImmediate(() => {
208
- runBootScan().catch((e) => {
209
- console.error(`Boot scan failed: ${e instanceof Error ? e.message : String(e)}`);
210
- });
211
- });
212
- }
209
+ // The one-shot kick guard, the daemon-owned intervals, and shutdown ordering
210
+ // live in the lifecycle harness (src/daemon/lifecycle.ts).
213
211
  async function runBootScan() {
212
+ let handle = null;
214
213
  try {
215
214
  const scanRoots = getSettingsData(db).scan_roots;
216
215
  setScanRoots(scanRoots);
@@ -263,21 +262,8 @@ async function runBootScan() {
263
262
  console.error(`Self-churn collection failed (non-fatal): ${e instanceof Error ? e.message : String(e)}`);
264
263
  }
265
264
  });
266
- // R12 bytes→token calibration — best-effort, never crash the daemon.
267
- // Runs on boot (deferred) and weekly when: opt-in enabled AND ratio is absent
268
- // or older than 30 days. Mirrors the outcomes bootstrap pattern.
269
- const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;
270
- function runBptCalibrationIfStale() {
271
- const enabled = bptConfigGet(db, "bytes_per_token_calibration_enabled");
272
- if (enabled !== "true")
273
- return;
274
- const measuredAt = bptConfigGet(db, "bytes_per_token_measured_at");
275
- if (measuredAt !== null && Date.now() - new Date(measuredAt).getTime() < THIRTY_DAYS_MS)
276
- return;
277
- calibrateBytesPerToken(db).catch((e) => {
278
- console.error(`Bytes-per-token calibration failed (non-fatal): ${e instanceof Error ? e.message : String(e)}`);
279
- });
280
- }
265
+ // Deferred boot calibration check (the weekly interval is armed by the
266
+ // lifecycle harness after this scan resolves).
281
267
  setImmediate(() => {
282
268
  try {
283
269
  runBptCalibrationIfStale();
@@ -286,42 +272,31 @@ async function runBootScan() {
286
272
  console.error(`Bytes-per-token calibration boot failed (non-fatal): ${e instanceof Error ? e.message : String(e)}`);
287
273
  }
288
274
  });
289
- bptCalibrationTimer = setInterval(() => {
290
- try {
291
- runBptCalibrationIfStale();
292
- }
293
- catch (e) {
294
- console.error(`Bytes-per-token calibration poll failed (non-fatal): ${e instanceof Error ? e.message : String(e)}`);
295
- }
296
- }, 7 * 24 * 60 * 60 * 1000);
297
- // 10-minute poll — guarded by outcomesRunning to prevent overlap
298
- outcomesTimer = setInterval(() => {
275
+ return handle;
276
+ }
277
+ // ── Lifecycle harness: boot-kick guard, daemon intervals, shutdown ordering ──
278
+ // closeServer closes over `server` (declared below); shutdown only ever runs
279
+ // after listen, so the reference is initialized by then.
280
+ const lifecycle = createDaemonLifecycle({
281
+ bootScan: runBootScan,
282
+ calibrationTick: runBptCalibrationIfStale,
283
+ outcomesTick: () => {
299
284
  runOutcomesPass().catch((e) => {
300
285
  console.error(`Outcomes poll failed: ${e instanceof Error ? e.message : String(e)}`);
301
286
  });
302
- }, 10 * 60 * 1000);
303
- reportsTimer = setInterval(async () => {
304
- if (reportsRunning)
305
- return;
306
- reportsRunning = true;
307
- try {
308
- await Promise.resolve(generateWeeklyReport(db, new Date()));
309
- }
310
- catch (e) {
311
- console.error(`Weekly report poll failed: ${e instanceof Error ? e.message : String(e)}`);
312
- }
313
- finally {
314
- reportsRunning = false;
315
- }
316
- }, 7 * 24 * 60 * 60 * 1000);
317
- }
287
+ },
288
+ reportsTick: () => generateWeeklyReport(db, new Date()),
289
+ closeServer: (onClosed) => server.close(onClosed),
290
+ closeDb: () => db.close(),
291
+ onClosed: () => process.exit(0),
292
+ });
318
293
  // ── 4. Start HTTP server ──────────────────────────────────────────────────────
319
294
  // Bind the port BEFORE the back-scan so the loading page is delivered
320
295
  // immediately while the initial scan yields between file batches.
321
296
  // Generate a random in-memory session token for the CSRF token gate.
322
297
  // NEVER log it, NEVER persist it — it lives only in process memory.
323
298
  const sessionToken = randomUUID();
324
- const server = createServer(db, config.port, config.uiRoot, sessionToken, kickBootScan);
299
+ const server = createServer(db, config.port, config.uiRoot, sessionToken, lifecycle.kickBootScan);
325
300
  server.listen(config.port, "127.0.0.1", () => {
326
301
  const url = `http://127.0.0.1:${config.port}`;
327
302
  console.log(`Listening on ${url}`);
@@ -334,7 +309,7 @@ server.listen(config.port, "127.0.0.1", () => {
334
309
  // Fallback: kick the back-scan after 3 s even if no browser request arrives
335
310
  // (headless mode, --no-open, CI). The one-shot guard in kickBootScan() makes
336
311
  // whichever trigger fires first the only one that runs the scan.
337
- setTimeout(kickBootScan, 3000);
312
+ lifecycle.armBootFallback();
338
313
  });
339
314
  /** Open `url` in the system default browser (best-effort; never crashes the daemon). */
340
315
  function openBrowser(url) {
@@ -357,24 +332,8 @@ function openBrowser(url) {
357
332
  // ── Graceful shutdown ─────────────────────────────────────────────────────────
358
333
  process.on("SIGINT", () => {
359
334
  console.log("Shutting down…");
360
- handle?.stop();
361
- if (outcomesTimer !== null)
362
- clearInterval(outcomesTimer);
363
- if (reportsTimer !== null)
364
- clearInterval(reportsTimer);
365
- server.close(() => {
366
- db.close();
367
- process.exit(0);
368
- });
335
+ lifecycle.shutdown();
369
336
  });
370
337
  process.on("SIGTERM", () => {
371
- handle?.stop();
372
- if (outcomesTimer !== null)
373
- clearInterval(outcomesTimer);
374
- if (reportsTimer !== null)
375
- clearInterval(reportsTimer);
376
- server.close(() => {
377
- db.close();
378
- process.exit(0);
379
- });
338
+ lifecycle.shutdown();
380
339
  });
@@ -0,0 +1,122 @@
1
+ /**
2
+ * src/daemon/lifecycle.ts — daemon timer registration and graceful shutdown.
3
+ *
4
+ * Extracted from daemon/index.ts (PERF5) so the boot-kick guard, the three
5
+ * daemon-owned intervals (calibration / outcomes / weekly reports), and the
6
+ * shutdown ordering are deterministically unit-testable without booting the
7
+ * daemon. The signal handlers in index.ts stay thin: both call shutdown().
8
+ *
9
+ * Shutdown contract:
10
+ * - idempotent — a second signal is a no-op
11
+ * - clears the boot-fallback timeout so a shutdown during the 3 s window
12
+ * cannot start a scan afterwards
13
+ * - a pending boot-kick setImmediate checks the flag and never starts the
14
+ * scan after shutdown
15
+ * - when shutdown lands while the boot scan is still in flight, the timers
16
+ * are never armed and the tail handle is stopped as soon as the scan
17
+ * resolves (previously both leaked past db.close())
18
+ * - stopping the tail does NOT drain a suspended tail pass; the Ingestor's
19
+ * stopped flag makes it quit at the next file boundary (its contract)
20
+ */
21
+ const WEEK_MS = 7 * 24 * 60 * 60 * 1000;
22
+ export function createDaemonLifecycle(deps) {
23
+ const error = deps.error ?? ((msg) => console.error(msg));
24
+ const calibrationIntervalMs = deps.calibrationIntervalMs ?? WEEK_MS;
25
+ const outcomesIntervalMs = deps.outcomesIntervalMs ?? 10 * 60 * 1000;
26
+ const reportsIntervalMs = deps.reportsIntervalMs ?? WEEK_MS;
27
+ const bootFallbackMs = deps.bootFallbackMs ?? 3000;
28
+ let scanKicked = false;
29
+ let shutDown = false;
30
+ let handle = null;
31
+ let calibrationTimer = null;
32
+ let outcomesTimer = null;
33
+ let reportsTimer = null;
34
+ let fallbackTimer = null;
35
+ let reportsRunning = false;
36
+ function armTimers() {
37
+ calibrationTimer = setInterval(() => {
38
+ try {
39
+ deps.calibrationTick();
40
+ }
41
+ catch (e) {
42
+ error(`Bytes-per-token calibration poll failed (non-fatal): ${e instanceof Error ? e.message : String(e)}`);
43
+ }
44
+ }, calibrationIntervalMs);
45
+ outcomesTimer = setInterval(() => {
46
+ try {
47
+ deps.outcomesTick();
48
+ }
49
+ catch (e) {
50
+ error(`Outcomes poll failed: ${e instanceof Error ? e.message : String(e)}`);
51
+ }
52
+ }, outcomesIntervalMs);
53
+ reportsTimer = setInterval(() => {
54
+ if (reportsRunning)
55
+ return;
56
+ reportsRunning = true;
57
+ Promise.resolve()
58
+ .then(() => deps.reportsTick())
59
+ .catch((e) => {
60
+ error(`Weekly report poll failed: ${e instanceof Error ? e.message : String(e)}`);
61
+ })
62
+ .finally(() => {
63
+ reportsRunning = false;
64
+ });
65
+ }, reportsIntervalMs);
66
+ }
67
+ function kickBootScan() {
68
+ if (scanKicked || shutDown)
69
+ return;
70
+ scanKicked = true;
71
+ // setImmediate so the triggering HTTP response flushes before boot work
72
+ // starts. The scan itself also yields between bounded batches.
73
+ setImmediate(() => {
74
+ if (shutDown)
75
+ return;
76
+ deps
77
+ .bootScan()
78
+ .then((h) => {
79
+ handle = h;
80
+ if (shutDown) {
81
+ // Shutdown landed mid-scan: never arm timers; stop the tail now.
82
+ handle?.stop();
83
+ handle = null;
84
+ return;
85
+ }
86
+ armTimers();
87
+ })
88
+ .catch((e) => {
89
+ error(`Boot scan failed: ${e instanceof Error ? e.message : String(e)}`);
90
+ });
91
+ });
92
+ }
93
+ function shutdown() {
94
+ if (shutDown)
95
+ return;
96
+ shutDown = true;
97
+ if (fallbackTimer !== null)
98
+ clearTimeout(fallbackTimer);
99
+ handle?.stop();
100
+ handle = null;
101
+ if (calibrationTimer !== null)
102
+ clearInterval(calibrationTimer);
103
+ if (outcomesTimer !== null)
104
+ clearInterval(outcomesTimer);
105
+ if (reportsTimer !== null)
106
+ clearInterval(reportsTimer);
107
+ deps.closeServer(() => {
108
+ deps.closeDb();
109
+ deps.onClosed?.();
110
+ });
111
+ }
112
+ return {
113
+ kickBootScan,
114
+ armBootFallback() {
115
+ fallbackTimer = setTimeout(kickBootScan, bootFallbackMs);
116
+ },
117
+ shutdown,
118
+ get isShutDown() {
119
+ return shutDown;
120
+ },
121
+ };
122
+ }
@@ -1,11 +1,4 @@
1
- /**
2
- * src/daemon/router.ts — minimal API route dispatcher.
3
- *
4
- * Routes /api/* requests to the LocalQueryAPI stubs.
5
- * WP2 and WP4 replace the stub calls with real implementations.
6
- *
7
- * All responses are JSON with no permissive CORS headers.
8
- */
1
+ import { getReportedWork } from "../query/api/reported-work.js";
9
2
  import { getPractices } from "../detector/practice-registry.js";
10
3
  import { getOAuthStatus } from "../oauth/credentials.js";
11
4
  import { getGithubTokenStatus } from "../outcomes/github/credential.js";
@@ -17,6 +10,7 @@ import { getDeliveryMetrics } from "../query/api/delivery.js";
17
10
  import { EffectRequestError, listEffectEvidence, mutateEffectCycle, trackCompletedChange, } from "../query/api/effect-service.js";
18
11
  import { getClosureProxy } from "../query/api/effectiveness.js";
19
12
  import { getEfficiencyHeadroom } from "../query/api/efficiency-headroom.js";
13
+ import { getEsfObservations, getSessionEsfObservations } from "../query/api/esf-observations.js";
20
14
  import { getHeadroomTrend } from "../query/api/headroom-trend.js";
21
15
  import { getHotSessions } from "../query/api/hot-sessions.js";
22
16
  import { adoptRecommendation, calibrateBytesPerToken, calibrateLimit, confirmApplyJob, dismissRecommendation, getApplyJob, getContextBudget, getContextComposition, getGlobalOverview, getHookConfig, getIdleSessions, getLinkageRate, getLoopGuard, getSession, getSessionDrivers, getSettings, getSuccessRate, getTurnTimeline, getWorkspaceOutcomeDetail, installHookRoute, listLedger, listLiveSessions, listRecommendations, listSessions, listWorkspaceOutcomes, listWorkspaces, openTerminalForRec, resetDatabase, rollbackApplyJob, startApplyJob, uninstallHookRoute, updateHookConfig, updateSettings, } from "../query/api/index.js";
@@ -26,6 +20,7 @@ import { getSelfChurn } from "../query/api/self-churn.js";
26
20
  import { getSessionSpendPercentile, getWeeklySelfPercentile, } from "../query/api/self-percentiles.js";
27
21
  import { getFlavorDecomposition } from "../query/api/spend-flavor.js";
28
22
  import { getCacheWriteTrend, getTrends } from "../query/api/trends.js";
23
+ import { WorkRecordError, attachWorkRecordContextRoute, attachWorkRecordSessionRoute, closeoutWorkRecordRoute, createWorkRecordRoute, deleteWorkRecordRoute, detachWorkRecordContextRoute, detachWorkRecordSessionRoute, editWorkRecordRoute, getWorkAllocation, getWorkAllocationClaimKinds, getWorkRecord, issueWorkRecordId, listWorkRecords, recomputeWorkAllocationRoute, setWorkRecordArchivedRoute, workRecordResponse, } from "../query/api/work-records.js";
29
24
  import { getSettingsData } from "../query/settings-store.js";
30
25
  import { getScanStatus, isReady } from "./readiness.js";
31
26
  function sendJson(res, status, body) {
@@ -134,10 +129,96 @@ function jobRoute(pathname) {
134
129
  const action = m[2] === "confirm" || m[2] === "rollback" ? m[2] : "get";
135
130
  return { jobId: decodeURIComponent(m[1]), action };
136
131
  }
132
+ function workRecordId(pathname) {
133
+ const match = pathname.match(/^\/api\/work-records\/([^/]+)$/);
134
+ return match?.[1] === undefined ? null : decodeURIComponent(match[1]);
135
+ }
136
+ function listSavedCostReports(db, workspaceId) {
137
+ return db
138
+ .prepare(`SELECT r.allocation_revision_id, r.created_at, r.cohort_from, r.cohort_to,
139
+ SUM(CASE WHEN a.disposition = 'OWNED' THEN 1 ELSE 0 END) AS allocated_session_count,
140
+ COUNT(a.session_id) AS eligible_session_count
141
+ FROM work_allocation_revisions r
142
+ LEFT JOIN work_session_allocations a ON a.allocation_revision_id = r.allocation_revision_id
143
+ WHERE r.workspace_id = ?
144
+ GROUP BY r.allocation_revision_id
145
+ ORDER BY r.created_at DESC, r.allocation_revision_id DESC`)
146
+ .all(workspaceId);
147
+ }
148
+ function workRecordAction(pathname) {
149
+ const match = pathname.match(/^\/api\/work-records\/([^/]+)\/(edit|closeout|archive|reopen|sessions|contexts|delete)(?:\/([^/]+)\/detach)?$/);
150
+ if (match?.[1] === undefined || match[2] === undefined)
151
+ return null;
152
+ const result = { recordId: decodeURIComponent(match[1]), action: match[2] };
153
+ return match[3] === undefined ? result : { ...result, relatedId: decodeURIComponent(match[3]) };
154
+ }
155
+ function workRecordBody(raw, recordId, related) {
156
+ let body;
157
+ try {
158
+ body = JSON.parse(raw);
159
+ }
160
+ catch {
161
+ throw new WorkRecordError(400, "INVALID_REQUEST", "Invalid JSON body");
162
+ }
163
+ if (body === null || typeof body !== "object" || Array.isArray(body)) {
164
+ throw new WorkRecordError(400, "INVALID_REQUEST", "request body must be an object");
165
+ }
166
+ const result = { ...body };
167
+ if (recordId !== undefined) {
168
+ if (result.work_record_id !== undefined && result.work_record_id !== recordId) {
169
+ throw new WorkRecordError(400, "INVALID_REQUEST", "work_record_id must match the route");
170
+ }
171
+ result.work_record_id = recordId;
172
+ }
173
+ if (related !== undefined) {
174
+ if (result[related.key] !== undefined && result[related.key] !== related.value) {
175
+ throw new WorkRecordError(400, "INVALID_REQUEST", `${related.key} must match the route`);
176
+ }
177
+ result[related.key] = related.value;
178
+ }
179
+ return result;
180
+ }
181
+ function sendWorkRecordError(res, error) {
182
+ if (error instanceof EffectRequestError) {
183
+ sendJson(res, error.status, { error: error.message, code: "INVALID_REQUEST" });
184
+ return;
185
+ }
186
+ if (error instanceof WorkRecordError) {
187
+ sendJson(res, error.status, { error: error.message, code: error.code });
188
+ return;
189
+ }
190
+ sendJson(res, 500, { error: "Internal error" });
191
+ }
137
192
  export function handleApiRequest(_db, req, res, method, url) {
138
193
  // Strip query string for routing.
139
194
  const pathname = url.split("?")[0] ?? url;
140
195
  try {
196
+ if (method === "GET" && pathname === "/api/work-records/summary") {
197
+ const params = new URLSearchParams(url.split("?")[1] ?? "");
198
+ sendJson(res, 200, getReportedWork(_db, params.get("workspace_id") || null));
199
+ return;
200
+ }
201
+ // GET /api/esf/observations — complete selected-turn accounting cohort.
202
+ if (method === "GET" && pathname === "/api/esf/observations") {
203
+ const params = new URLSearchParams(url.split("?")[1] ?? "");
204
+ const window = resolveWindow(parseWindowFilter(url));
205
+ if (Date.parse(window.from) >= Date.parse(window.to)) {
206
+ sendJson(res, 400, { error: "from must precede to" });
207
+ return;
208
+ }
209
+ sendJson(res, 200, getEsfObservations(_db, {
210
+ workspaceId: params.get("workspace_id") || null,
211
+ ...window,
212
+ }));
213
+ return;
214
+ }
215
+ // Full-session aggregate: never derive this from a paginated timeline.
216
+ const sessionObservationId = pathname.match(/^\/api\/esf\/session-observations\/([^/]+)$/)?.[1];
217
+ if (method === "GET" && sessionObservationId !== undefined) {
218
+ const evidence = getSessionEsfObservations(_db, decodeURIComponent(sessionObservationId));
219
+ sendJson(res, evidence.data === null ? 404 : 200, evidence);
220
+ return;
221
+ }
141
222
  // GET /api/esf/effects — independently keyset-paged versioned and legacy evidence.
142
223
  if (method === "GET" && pathname === "/api/esf/effects") {
143
224
  const params = new URLSearchParams(url.split("?")[1] ?? "");
@@ -179,6 +260,172 @@ export function handleApiRequest(_db, req, res, method, url) {
179
260
  }));
180
261
  return;
181
262
  }
263
+ // ESF3 work records are local-only, structured records. The HTTP token gate
264
+ // in http.ts covers every mutation and ID issuance route below.
265
+ if (method === "GET" && pathname === "/api/work-records") {
266
+ const params = new URLSearchParams(url.split("?")[1] ?? "");
267
+ const workspaceId = params.get("workspace_id");
268
+ const includeArchived = params.get("include_archived");
269
+ if (workspaceId === null ||
270
+ workspaceId.length === 0 ||
271
+ (includeArchived !== null && includeArchived !== "true" && includeArchived !== "false")) {
272
+ sendJson(res, 400, { error: "workspace_id and include_archived are invalid" });
273
+ return;
274
+ }
275
+ const records = listWorkRecords(_db, workspaceId, includeArchived === "true");
276
+ sendJson(res, 200, workRecordResponse(records, { n: records.length, workspaceId }));
277
+ return;
278
+ }
279
+ if (method === "GET" && pathname === "/api/work-records/allocations") {
280
+ const workspaceId = new URLSearchParams(url.split("?")[1] ?? "").get("workspace_id");
281
+ if (workspaceId === null || workspaceId.length === 0) {
282
+ sendJson(res, 400, { error: "workspace_id is required" });
283
+ return;
284
+ }
285
+ const reports = listSavedCostReports(_db, workspaceId);
286
+ sendJson(res, 200, workRecordResponse(reports, { n: reports.length, workspaceId }));
287
+ return;
288
+ }
289
+ if (method === "GET" && pathname.startsWith("/api/work-records/allocations/")) {
290
+ const allocationId = pathname.slice("/api/work-records/allocations/".length);
291
+ if (allocationId.length === 0 || allocationId.includes("/")) {
292
+ sendJson(res, 404, { error: "Not found" });
293
+ return;
294
+ }
295
+ try {
296
+ const allocation = getWorkAllocation(_db, decodeURIComponent(allocationId));
297
+ sendJson(res, 200, workRecordResponse(allocation, {
298
+ n: allocation.eligible_session_count,
299
+ workspaceId: allocation.workspace_id,
300
+ claimKind: "EXPERIMENTAL",
301
+ meta: {
302
+ window: { from: allocation.cohort_from, to: allocation.cohort_to },
303
+ qualification: {
304
+ provisional_excluded: true,
305
+ unpriced_turns: allocation.unpriced_turn_count,
306
+ claim_kinds_count: getWorkAllocationClaimKinds(_db, allocation.allocation_revision_id),
307
+ note: "Frozen ESF3 allocation; unpriced turns are not zero cost.",
308
+ },
309
+ },
310
+ }));
311
+ }
312
+ catch (error) {
313
+ sendWorkRecordError(res, error);
314
+ }
315
+ return;
316
+ }
317
+ const recordId = workRecordId(pathname);
318
+ if (method === "GET" && recordId !== null) {
319
+ try {
320
+ const record = getWorkRecord(_db, recordId);
321
+ sendJson(res, 200, workRecordResponse(record, { workspaceId: record.workspace_id }));
322
+ }
323
+ catch (error) {
324
+ sendWorkRecordError(res, error);
325
+ }
326
+ return;
327
+ }
328
+ if (method === "POST" && pathname === "/api/work-records/ids") {
329
+ readBody(req, 1024)
330
+ .then((raw) => {
331
+ try {
332
+ sendJson(res, 200, workRecordResponse(issueWorkRecordId(_db, workRecordBody(raw))));
333
+ }
334
+ catch (error) {
335
+ sendWorkRecordError(res, error);
336
+ }
337
+ })
338
+ .catch((error) => sendWorkRecordError(res, error));
339
+ return;
340
+ }
341
+ if (method === "POST" && pathname === "/api/work-records") {
342
+ readBody(req, 4096)
343
+ .then((raw) => {
344
+ try {
345
+ const result = createWorkRecordRoute(_db, workRecordBody(raw));
346
+ sendJson(res, 200, workRecordResponse(result, { workspaceId: result.record.workspace_id }));
347
+ }
348
+ catch (error) {
349
+ sendWorkRecordError(res, error);
350
+ }
351
+ })
352
+ .catch((error) => sendWorkRecordError(res, error));
353
+ return;
354
+ }
355
+ if (method === "POST" && pathname === "/api/work-records/allocations/recompute") {
356
+ readBody(req, 4096)
357
+ .then((raw) => {
358
+ try {
359
+ const result = recomputeWorkAllocationRoute(_db, workRecordBody(raw));
360
+ sendJson(res, 200, workRecordResponse(result, {
361
+ n: result.allocation.eligible_session_count,
362
+ workspaceId: result.allocation.workspace_id,
363
+ claimKind: "EXPERIMENTAL",
364
+ meta: {
365
+ window: {
366
+ from: result.allocation.cohort_from,
367
+ to: result.allocation.cohort_to,
368
+ },
369
+ qualification: {
370
+ provisional_excluded: true,
371
+ unpriced_turns: result.allocation.unpriced_turn_count,
372
+ claim_kinds_count: getWorkAllocationClaimKinds(_db, result.allocation.allocation_revision_id),
373
+ note: "Frozen ESF3 allocation; unpriced turns are not zero cost.",
374
+ },
375
+ },
376
+ }));
377
+ }
378
+ catch (error) {
379
+ sendWorkRecordError(res, error);
380
+ }
381
+ })
382
+ .catch((error) => sendWorkRecordError(res, error));
383
+ return;
384
+ }
385
+ const recordAction = workRecordAction(pathname);
386
+ if (recordAction !== null &&
387
+ ((method === "POST" && recordAction.action !== "delete") ||
388
+ (method === "DELETE" && recordAction.action === "delete"))) {
389
+ readBody(req, 4096)
390
+ .then((raw) => {
391
+ try {
392
+ const related = recordAction.relatedId === undefined
393
+ ? undefined
394
+ : {
395
+ key: recordAction.action === "contexts" ? "context_ref_id" : "session_id",
396
+ value: recordAction.relatedId,
397
+ };
398
+ const body = workRecordBody(raw, recordAction.recordId, related);
399
+ const result = recordAction.action === "edit"
400
+ ? editWorkRecordRoute(_db, body)
401
+ : recordAction.action === "closeout"
402
+ ? closeoutWorkRecordRoute(_db, body)
403
+ : recordAction.action === "archive"
404
+ ? setWorkRecordArchivedRoute(_db, body, true)
405
+ : recordAction.action === "reopen"
406
+ ? setWorkRecordArchivedRoute(_db, body, false)
407
+ : recordAction.action === "sessions" && recordAction.relatedId === undefined
408
+ ? attachWorkRecordSessionRoute(_db, body)
409
+ : recordAction.action === "sessions"
410
+ ? detachWorkRecordSessionRoute(_db, body)
411
+ : recordAction.action === "contexts" &&
412
+ recordAction.relatedId === undefined
413
+ ? attachWorkRecordContextRoute(_db, body)
414
+ : recordAction.action === "contexts"
415
+ ? detachWorkRecordContextRoute(_db, body)
416
+ : deleteWorkRecordRoute(_db, body);
417
+ const workspaceId = "record" in result ? result.record.workspace_id : undefined;
418
+ sendJson(res, 200, workspaceId === undefined
419
+ ? workRecordResponse(result)
420
+ : workRecordResponse(result, { workspaceId }));
421
+ }
422
+ catch (error) {
423
+ sendWorkRecordError(res, error);
424
+ }
425
+ })
426
+ .catch((error) => sendWorkRecordError(res, error));
427
+ return;
428
+ }
182
429
  // GET /api/overview
183
430
  if (method === "GET" && pathname === "/api/overview") {
184
431
  sendJson(res, 200, getGlobalOverview(parseWindowFilter(url)));