@chroxy/server 0.11.10 → 0.11.11

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 (153) hide show
  1. package/CONFIG.md +4 -2
  2. package/package.json +3 -3
  3. package/src/acp-session.js +5 -1
  4. package/src/agent-connections.js +12 -1
  5. package/src/agent-control/client.js +29 -0
  6. package/src/agent-control/events.js +8 -4
  7. package/src/agent-control/local-connection.js +34 -16
  8. package/src/agent-control/mcp-server.js +2 -0
  9. package/src/anthropic-compatible-config.js +1 -0
  10. package/src/anthropic-gemini-shim.js +444 -0
  11. package/src/anthropic-gemini-translate.js +1030 -0
  12. package/src/base-session.js +319 -2
  13. package/src/bound-client-policy.js +12 -0
  14. package/src/byok-mcp-config.js +9 -5
  15. package/src/byok-mcp-trust.js +34 -20
  16. package/src/byok-session.js +62 -9
  17. package/src/byok-tool-executor.js +81 -1
  18. package/src/claude-setting-sources.js +74 -0
  19. package/src/claude-tui/pty-driver.js +5 -1
  20. package/src/claude-tui/usage-limit.js +2 -2
  21. package/src/claude-tui-session.js +57 -4
  22. package/src/cli/agent-cmd.js +236 -0
  23. package/src/cli/connection-state.js +54 -0
  24. package/src/cli/freshness-cmd.js +53 -0
  25. package/src/cli/pages-cmd.js +6 -4
  26. package/src/cli/pair-code-cmd.js +7 -6
  27. package/src/cli/pair-discord-cmd.js +7 -6
  28. package/src/cli/schedule-cmd.js +25 -3
  29. package/src/cli/server-cmd.js +6 -0
  30. package/src/cli/shell-cmd.js +7 -4
  31. package/src/cli/status-cmd.js +19 -5
  32. package/src/cli-session.js +190 -11
  33. package/src/cli.js +4 -0
  34. package/src/codex-app-server-session.js +78 -17
  35. package/src/codex-error-text.js +114 -0
  36. package/src/config-dir-migration.js +11 -6
  37. package/src/config.js +23 -3
  38. package/src/connection-info.js +73 -14
  39. package/src/continuations.js +153 -40
  40. package/src/conversation-scanner.js +2 -21
  41. package/src/conversation-search.js +4 -17
  42. package/src/dev-preview.js +2 -1
  43. package/src/docker-session.js +10 -1
  44. package/src/doctor.js +14 -3
  45. package/src/durable-write.js +35 -0
  46. package/src/environments/authority.js +7 -1
  47. package/src/event-normalizer.js +35 -2
  48. package/src/folder-trust-wire.js +137 -0
  49. package/src/folder-trust-worker.js +17 -0
  50. package/src/folder-trust.js +1572 -0
  51. package/src/freshness/activity-meter.js +101 -0
  52. package/src/freshness/adapter.js +199 -0
  53. package/src/freshness/checks.js +239 -0
  54. package/src/freshness/config.js +98 -0
  55. package/src/freshness/core.js +185 -0
  56. package/src/freshness/derive.js +680 -0
  57. package/src/freshness/exchange.js +305 -0
  58. package/src/freshness/file-ledger.js +400 -0
  59. package/src/freshness/grade.js +81 -0
  60. package/src/freshness/hash.js +45 -0
  61. package/src/freshness/inbox.js +163 -0
  62. package/src/freshness/index.js +20 -0
  63. package/src/freshness/investigation.js +474 -0
  64. package/src/freshness/keys.js +177 -0
  65. package/src/freshness/ledger.js +122 -0
  66. package/src/freshness/outbox.js +131 -0
  67. package/src/freshness/policy.js +599 -0
  68. package/src/freshness/queue.js +843 -0
  69. package/src/freshness/read-errors.js +23 -0
  70. package/src/freshness/render.js +153 -0
  71. package/src/freshness/runtime.js +113 -0
  72. package/src/freshness/session-registry-adapter.js +161 -0
  73. package/src/freshness/state-file-adapter.js +167 -0
  74. package/src/freshness-runner/build-info.js +139 -0
  75. package/src/freshness-runner/cli.js +105 -0
  76. package/src/freshness-runner/run-tick.js +109 -0
  77. package/src/freshness-runner/stamp.js +57 -0
  78. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  79. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  80. package/src/freshness-sources/index.js +8 -0
  81. package/src/gemini-byok-session.js +292 -0
  82. package/src/gemini-credentials.js +67 -0
  83. package/src/gemini-key-safety.js +246 -0
  84. package/src/gemini-models.js +386 -0
  85. package/src/handler-utils.js +6 -13
  86. package/src/handlers/checkpoint-handlers.js +8 -0
  87. package/src/handlers/folder-trust-handlers.js +90 -0
  88. package/src/handlers/input-handlers.js +40 -11
  89. package/src/handlers/principal-admin-handlers.js +229 -0
  90. package/src/handlers/principal-handlers.js +262 -0
  91. package/src/handlers/scheduler-handlers.js +4 -4
  92. package/src/handlers/session-handlers.js +10 -1
  93. package/src/handlers/settings-handlers.js +42 -8
  94. package/src/handlers/skills-handlers.js +7 -0
  95. package/src/history-page.js +8 -0
  96. package/src/jsonl-reader.js +90 -10
  97. package/src/jsonl-subprocess-session.js +4 -1
  98. package/src/logger.js +105 -15
  99. package/src/mailbox-route.js +102 -0
  100. package/src/notification-prefs.js +15 -0
  101. package/src/orchestration/orchestration-manager.js +38 -9
  102. package/src/orchestration/permission-gate.js +4 -1
  103. package/src/orchestration/run-record.js +11 -0
  104. package/src/orchestration/turn-driver.js +151 -33
  105. package/src/orphan-reaper.js +77 -20
  106. package/src/outgoing-policy.js +10 -4
  107. package/src/permission-floor.js +54 -2
  108. package/src/permission-manager.js +32 -13
  109. package/src/permission-resolved-by.js +89 -0
  110. package/src/permission-resolver.js +7 -3
  111. package/src/platform.js +156 -4
  112. package/src/principal-audit.js +189 -0
  113. package/src/principal-binding.js +25 -0
  114. package/src/principal-brakes.js +21 -0
  115. package/src/principal-effect.js +101 -0
  116. package/src/principal-journal.js +905 -0
  117. package/src/principal-kill-switch.js +183 -0
  118. package/src/principal-label.js +5 -0
  119. package/src/principal-pending-permissions.js +177 -0
  120. package/src/principal-policy.js +1094 -0
  121. package/src/principal-sessions-snapshot.js +208 -0
  122. package/src/principal-store.js +488 -0
  123. package/src/principal-subscriptions.js +283 -0
  124. package/src/providers.js +2 -0
  125. package/src/redaction.js +181 -22
  126. package/src/scheduled-task-store.js +12 -0
  127. package/src/scheduler.js +304 -17
  128. package/src/sdk-session.js +60 -7
  129. package/src/server-cli/push-notification-handler.js +6 -1
  130. package/src/server-cli.js +30 -1
  131. package/src/session-ci-watcher.js +210 -37
  132. package/src/session-manager.js +590 -19
  133. package/src/session-message-history.js +121 -2
  134. package/src/session-name-allocator.js +685 -0
  135. package/src/statusline.js +78 -19
  136. package/src/summarize-session.js +2 -0
  137. package/src/turn-outcome.js +5 -2
  138. package/src/utils/argv-safety.js +29 -0
  139. package/src/utils/binary-package-manifest.js +57 -15
  140. package/src/utils/bounded-regex-worker.js +4 -0
  141. package/src/utils/bounded-regex.js +16 -7
  142. package/src/utils/pid-liveness.js +47 -0
  143. package/src/web-task-manager.js +45 -4
  144. package/src/worktree-gc.js +195 -4
  145. package/src/ws-auth.js +103 -19
  146. package/src/ws-broadcaster.js +39 -7
  147. package/src/ws-client-manager.js +8 -0
  148. package/src/ws-file-ops/browser.js +35 -3
  149. package/src/ws-forwarding.js +23 -3
  150. package/src/ws-handler-context.js +18 -0
  151. package/src/ws-history.js +79 -12
  152. package/src/ws-message-handlers.js +10 -2
  153. package/src/ws-server.js +253 -13
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Public surface of the session freshness reconciler core. See README in
3
+ * tests/freshness for the model these modules implement, and
4
+ * docs/guides/freshness-reconciler.md for what this core does and does not do.
5
+ */
6
+
7
+ export * from './core.js'
8
+ export * from './adapter.js'
9
+ export * from './state-file-adapter.js'
10
+ export * from './session-registry-adapter.js'
11
+ export * from './activity-meter.js'
12
+ export * from './file-ledger.js'
13
+ export { EXCHANGE_FILES, createExchange, planExchange, writeToOutbox, currentMessage } from './exchange.js'
14
+ export { OUTBOX_VERSION, OUTBOX_FIELDS, OUTBOX_OPS, OUTBOX_CLASSES, outboxRecord, openOutbox } from './outbox.js'
15
+ export { RECEIPT_OUTCOMES, ACK_INTENTS, parseReceipt, parseAck, readInput } from './inbox.js'
16
+ export { exchangeLimits, deferLimits } from './config.js'
17
+ export { clean, headline, renderItem } from './render.js'
18
+ export { H, canonical, sha256 } from './hash.js'
19
+ export * as keys from './keys.js'
20
+ export * as ledger from './ledger.js'
@@ -0,0 +1,474 @@
1
+ /**
2
+ * The stale-investigation scheduler.
3
+ *
4
+ * Five level triggers, an onset per trigger, at most two cycles per onset, a
5
+ * recheck after a "working" or "waiting" verdict, two budgets, and a
6
+ * classification from evidence the caller's reads supplied. Read-only by
7
+ * construction: the only reads are the caller's functions, and the only
8
+ * outputs are ledger records and signals for the owner queue.
9
+ */
10
+
11
+ import { sourceCaps } from './config.js'
12
+ import { onsetOf, sessionsOf } from './derive.js'
13
+ import { put, planRead } from './checks.js'
14
+ import { H } from './hash.js'
15
+ import { isFileLevelReadError, isSourceLevelError } from './read-errors.js'
16
+ import {
17
+ READ_NO,
18
+ checkInvestigationKey,
19
+ investigationId,
20
+ investigationKey,
21
+ recheckInvestigationId,
22
+ sourceInvestigationId,
23
+ } from './keys.js'
24
+
25
+ function sessionEnvOf(s) {
26
+ return { source: s.session.source, native_id: s.session.native_id, incarnation: s.session.incarnation ?? null }
27
+ }
28
+
29
+ /**
30
+ * Whether every tracked session of the source failed its last two tick checks
31
+ * with an error that describes the source. An error that describes the one file
32
+ * read (see read-errors.js) is the session's own trouble and never counts.
33
+ */
34
+ export function sourceAllFailed(st, source, tickId) {
35
+ const ss = sessionsOf(st, source)
36
+ if (ss.length === 0) return false
37
+ return ss.every((s) => s.cur && s.cur.tickId === tickId && isSourceLevelError(s.cur) && isSourceLevelError(s.prev))
38
+ }
39
+
40
+ function firstCheckOfTick(st, source, tickId) {
41
+ let best = null
42
+ for (const s of sessionsOf(st, source)) {
43
+ if (s.cur && s.cur.tickId === tickId && (best == null || s.cur.seq < best.seq)) best = s.cur
44
+ }
45
+ return best ? best.checkId : null
46
+ }
47
+
48
+ /** The source-level onset at this tick, if the source-level trigger holds. */
49
+ export function sourceOnset(st, source, tickId) {
50
+ if (!sourceAllFailed(st, source, tickId)) return null
51
+ const prev = st.sourceTrigger.get(source)
52
+ if (prev && prev.held && prev.onset) return prev.onset
53
+ return firstCheckOfTick(st, source, tickId)
54
+ }
55
+
56
+ function nativeEvidence(s, read) {
57
+ if (read) {
58
+ return {
59
+ available: true,
60
+ answering_now: read.answering_now !== false,
61
+ turn_in_flight: Boolean(read.turn_in_flight),
62
+ busy_background: Boolean(read.busy_background),
63
+ pending: (read.pending ?? []).length > 0,
64
+ }
65
+ }
66
+ if (s.cur && s.cur.nativeAvailable) {
67
+ return {
68
+ available: true,
69
+ answering_now: s.cur.answeringNow,
70
+ turn_in_flight: s.cur.turnInFlight,
71
+ busy_background: s.cur.busyBackground,
72
+ pending: s.cur.pending.size > 0,
73
+ }
74
+ }
75
+ return null
76
+ }
77
+
78
+ /**
79
+ * DESIGN-GAP (added fields): the rules ask for each investigation's result to
80
+ * carry the evidence class of the reads it used, but a rung recorded only its
81
+ * outcome. Each rung of the close record also names the check it read
82
+ * (`read`, null when it read nothing) and the classes that read supplied
83
+ * (`evidence`); `classify` carries the union. The classes are the ledger's own
84
+ * (E2, E5 on a report, E1 on native state), never taken from the adapter.
85
+ *
86
+ * The evidence classes one read supplied, from the ledger's own records: a
87
+ * report it carried (E2 authored and host-timed, E5 relayed) and native state
88
+ * (E1). A read that carried neither supplied none. An activity read's report
89
+ * is never recorded, so it supplies E1 at most.
90
+ */
91
+ function evidenceOfCheck(st, body) {
92
+ const out = []
93
+ const rep = body.report_id ? st.reports.get(body.report_id)?.body : null
94
+ if (rep) out.push(rep.evidence_class)
95
+ if (body.native_available) out.push('E1')
96
+ return out.sort()
97
+ }
98
+
99
+ function* investigationRead(ctx, { invId, readNo, session, readFn, now, tickId, readKind }) {
100
+ const key = checkInvestigationKey(invId, readNo)
101
+ const recorded = ctx.policy.reuseRecorded(ctx.state.index, key, 'check')
102
+ if (recorded) {
103
+ const snap = ctx.state.checkNative.get(key)
104
+ const native = recorded.body.native_available
105
+ ? { turn_in_flight: Boolean(snap?.turn_in_flight), busy_background: Boolean(snap?.busy_background), pending: snap?.pending ?? [] }
106
+ : null
107
+ return { body: recorded.body, native, reused: true, checkId: key }
108
+ }
109
+ const read = readFn()
110
+ const r = yield* planRead(ctx, { key, trigger: 'investigation', session, read, now, tickId, investigationId: invId, readKind })
111
+ return { ...r, checkId: key }
112
+ }
113
+
114
+ /**
115
+ * Every candidate for one session, in trigger priority order: each trigger
116
+ * that holds and has a cycle (or a recheck) available. Choosing one per
117
+ * session is the policy's job (selectInvestigations).
118
+ */
119
+ function candidatesFor(ctx, s, { tickId, srcHeld }) {
120
+ const st = ctx.state
121
+ const P = ctx.policy
122
+ const caps = sourceCaps(st.config, s.session.source)
123
+ // A crashed run of this tick already investigated this session: resume an
124
+ // open investigation, or do nothing more for a closed one.
125
+ for (const inv of st.investigations.values()) {
126
+ if (inv.sk === s.sk && inv.tickId === tickId) {
127
+ if (inv.closed) return []
128
+ return [{ kind: inv.trigger === 'recheck' ? 'recheck' : 'cycle', resume: inv, s, key: s.sk, priority: -1, cycle: inv.cycle, trigger: inv.trigger, onset: inv.onset, onsetSeq: st.checks.get(inv.onset)?.seq ?? 0, needsRead: inv.trigger === 'recheck' && !caps.native_in_read, lastInvestigatedAt: s.lastClosedInv?.at ?? 0 }]
129
+ }
130
+ }
131
+ const out = []
132
+ P.triggerPriority.forEach((trigger, priority) => {
133
+ if (trigger === 'recheck') {
134
+ const last = s.lastClosedInv
135
+ // DESIGN-GAP: the recheck budget serves "least recently checked first",
136
+ // but every tracked session is read at every tick, so the time of a
137
+ // session's last read never tells two apart and the same sessions would
138
+ // win every tick. The model orders by the time of the session's last
139
+ // investigation instead, so each recheck sends a session to the back.
140
+ if (last && P.needsRecheck(last, P) && last.reportId === s.latestRead && last.tickId !== tickId) {
141
+ out.push({ kind: 'recheck', s, key: s.sk, priority, trigger, needsRead: !caps.native_in_read, lastInvestigatedAt: last.at ?? 0, cycle: null })
142
+ }
143
+ return
144
+ }
145
+ if (trigger === 'repeated_error' && srcHeld) return
146
+ if (!s.cur || s.cur.tickId !== tickId || !s.cur.flags[trigger]) return
147
+ if (trigger === 'native_disagreement' && !caps.native_in_read) return
148
+ const onset = onsetOf(s, trigger, P)
149
+ const o = st.onsets.get(`${s.sk}|${trigger}|${onset}`)
150
+ const closed = o?.closed ?? 0
151
+ let cycle = null
152
+ if (closed === 0) cycle = 1
153
+ else if (closed < P.maxCycles && P.secondCycleAfter.has(o.lastClass)) cycle = closed + 1
154
+ if (cycle == null) return
155
+ out.push({ kind: 'cycle', s, key: s.sk, priority, cycle, trigger, onset, onsetSeq: st.checks.get(onset)?.seq ?? 0 })
156
+ })
157
+ return out
158
+ }
159
+
160
+ function sourceCandidate(ctx, source, tickId) {
161
+ const st = ctx.state
162
+ const P = ctx.policy
163
+ const onset = sourceOnset(st, source, tickId)
164
+ if (!onset) return null
165
+ for (const inv of st.investigations.values()) {
166
+ if (inv.sourceLevel && inv.source === source && inv.tickId === tickId) {
167
+ if (inv.closed) return null
168
+ return { kind: 'cycle', sourceLevel: true, source, resume: inv, key: `src:${source}`, priority: -1, cycle: inv.cycle, trigger: 'repeated_error', onset, onsetSeq: st.checks.get(onset)?.seq ?? 0 }
169
+ }
170
+ }
171
+ const o = st.onsets.get(`src|${source}|${onset}`)
172
+ const closed = o?.closed ?? 0
173
+ let cycle = null
174
+ if (closed === 0) cycle = 1
175
+ else if (closed < P.maxCycles && P.secondCycleAfter.has(o.lastClass)) cycle = closed + 1
176
+ if (cycle == null) return null
177
+ // DESIGN-GAP: the rules do not say whether the one source-level
178
+ // investigation draws on the per-tick budget. The model counts it as a cycle.
179
+ return { kind: 'cycle', sourceLevel: true, source, key: `src:${source}`, priority: 0, cycle, trigger: 'repeated_error', onset, onsetSeq: st.checks.get(onset)?.seq ?? 0 }
180
+ }
181
+
182
+ function* runCandidate(ctx, cand, { tickId, now, world }) {
183
+ const st = ctx.state
184
+ const P = ctx.policy
185
+ const cfg = st.config
186
+ let s = cand.s
187
+ if (cand.sourceLevel) s = sessionsOf(st, cand.source)[0]
188
+ const session = s.session
189
+ const caps = sourceCaps(cfg, session.source)
190
+ const reportId = s.latestRead
191
+ const report = reportId ? st.reports.get(reportId)?.body : null
192
+ const invId = cand.resume
193
+ ? cand.resume.id
194
+ : afterAbandoned(
195
+ st,
196
+ cand.sourceLevel
197
+ ? sourceInvestigationId({ source: cand.source, onset: cand.onset, cycle: cand.cycle })
198
+ : cand.kind === 'recheck'
199
+ ? recheckInvestigationId({ session, reportId, tickId })
200
+ : investigationId({ session, reportId, trigger: cand.trigger, onset: cand.onset, cycle: cand.cycle }),
201
+ )
202
+
203
+ const closeKey = investigationKey(invId, 'close')
204
+ const recordedClose = P.reuseRecorded(st.index, closeKey, 'investigation')
205
+ if (recordedClose) return signalFrom(recordedClose.body, s, cand)
206
+
207
+ const env = cand.sourceLevel ? null : sessionEnvOf(s)
208
+ const openBody = {
209
+ investigation_id: invId,
210
+ trigger: cand.trigger,
211
+ onset: cand.kind === 'recheck' ? null : cand.onset,
212
+ report_id: cand.sourceLevel ? null : reportId,
213
+ cycle: cand.kind === 'recheck' ? null : cand.cycle,
214
+ phase: 'open',
215
+ source: session.source,
216
+ source_level: Boolean(cand.sourceLevel),
217
+ }
218
+ yield put({ kind: 'investigation', id: investigationKey(invId, 'open'), session: env, refs: { tick: tickId }, body: openBody }, now)
219
+
220
+ const rungs = []
221
+ let classification
222
+ let pendingSeen = false
223
+ let reportAgeMs = report ? now - report.last_report_at : null
224
+ if (cand.kind === 'recheck') {
225
+ let native = null
226
+ let readFailed = false
227
+ let rungBlocked = false
228
+ if (caps.native_in_read) {
229
+ native = nativeEvidence(s, null)
230
+ rungs.push({ rung: 'activity_read', outcome: native ? 'tick_read' : 'none', read: native ? (s.cur?.checkId ?? null) : null, evidence: native ? ['E1'] : [] })
231
+ } else if (caps.activity_read) {
232
+ const r = yield* investigationRead(ctx, { invId, readNo: READ_NO.ACTIVITY, session, readFn: () => world.activity(session, now), now, tickId, readKind: 'activity' })
233
+ readFailed = r.body.outcome === 'error'
234
+ rungBlocked = r.body.outcome === 'blocked'
235
+ native = r.native ? nativeEvidence(s, r.native) : null
236
+ rungs.push({ rung: 'activity_read', outcome: r.body.outcome, read: r.checkId, evidence: evidenceOfCheck(st, r.body) })
237
+ }
238
+ pendingSeen = Boolean(native?.pending)
239
+ classification = P.classifyRecheck({ native, readFailed, rungBlocked })
240
+ rungs.push({ rung: 'classify', outcome: classification, read: null, evidence: unionEvidence(rungs) })
241
+ } else {
242
+ // The re-read: the same adapter read, once more; then one retry of a failed read.
243
+ const reRead = yield* investigationRead(ctx, { invId, readNo: READ_NO.REREAD, session, readFn: () => world.reread(session, now), now, tickId })
244
+ rungs.push({ rung: 're_read', outcome: reRead.body.outcome, read: reRead.checkId, evidence: evidenceOfCheck(st, reRead.body) })
245
+ let failed = reRead.body.outcome === 'error'
246
+ let rungBlocked = reRead.body.outcome === 'blocked'
247
+ // The latest read of the cycle: the retry when the re-read failed.
248
+ let latest = reRead
249
+ if (failed) {
250
+ const retry = yield* investigationRead(ctx, { invId, readNo: READ_NO.RETRY, session, readFn: () => world.reread(session, now), now, tickId })
251
+ rungs.push({ rung: 're_read', outcome: retry.body.outcome, retry: true, read: retry.checkId, evidence: evidenceOfCheck(st, retry.body) })
252
+ failed = retry.body.outcome === 'error'
253
+ latest = retry
254
+ }
255
+ let confirmListed = null
256
+ if (cand.trigger === 'dropped_from_list' && !cand.sourceLevel) {
257
+ const c = yield* investigationRead(ctx, { invId, readNo: READ_NO.CONFIRM_GONE, session, readFn: () => world.reread(session, now), now, tickId })
258
+ confirmListed = c.body.listed !== false
259
+ rungs.push({ rung: 'confirm_gone', outcome: confirmListed ? 'listed' : 'not_listed', read: c.checkId, evidence: evidenceOfCheck(st, c.body) })
260
+ }
261
+ let native = null
262
+ if (!cand.sourceLevel && cand.trigger !== 'dropped_from_list') {
263
+ if (caps.native_in_read) {
264
+ // From the latest successful read of the cycle (the retry, if the
265
+ // re-read failed and it succeeded); from the tick's own read only
266
+ // when neither succeeded. A failed read carries no native state.
267
+ native = nativeEvidence(s, latest.native)
268
+ // The read named is the one the evidence came from: the cycle's latest
269
+ // read when it carried native state, else the tick's own check.
270
+ rungs.push({ rung: 'activity_read', outcome: native ? 'read' : 'none', read: native ? (latest.native ? latest.checkId : (s.cur?.checkId ?? null)) : null, evidence: native ? ['E1'] : [] })
271
+ } else if (caps.activity_read) {
272
+ const a = yield* investigationRead(ctx, { invId, readNo: READ_NO.ACTIVITY, session, readFn: () => world.activity(session, now), now, tickId, readKind: 'activity' })
273
+ if (a.body.outcome === 'blocked') rungBlocked = true
274
+ native = a.native ? nativeEvidence(s, a.native) : null
275
+ rungs.push({ rung: 'activity_read', outcome: a.body.outcome, read: a.checkId, evidence: evidenceOfCheck(st, a.body) })
276
+ } else {
277
+ rungs.push({ rung: 'activity_read', outcome: 'unavailable', read: null, evidence: [] })
278
+ }
279
+ }
280
+ // DESIGN-GAP: a stale owner block is explained by its owner item only
281
+ // while the item carries a live declared ask. A session rewound to an
282
+ // owner-block line whose ask already used it (and so never comes back)
283
+ // has no ask carrying it, and is classified, and rechecked, as any other
284
+ // stale line.
285
+ const declaredOpen = declaredAskLive(st, P, session)
286
+ const latestRead = st.sessions.get(s.sk)?.latestRead
287
+ const rep = latestRead ? st.reports.get(latestRead)?.body : report
288
+ reportAgeMs = rep ? now - rep.last_report_at : null
289
+ const ev = {
290
+ trigger: cand.trigger,
291
+ cycle: cand.cycle,
292
+ sourceLevel: Boolean(cand.sourceLevel),
293
+ // A source-level re-read that failed only on the one file it read says
294
+ // nothing about the source: not an outage.
295
+ rereadFailed: failed && !(cand.sourceLevel && isFileLevelReadError(latest.body.error_code)),
296
+ rungBlocked,
297
+ confirmListed,
298
+ canConfirmGone: caps.can_confirm_gone,
299
+ native,
300
+ events: st.sessions.get(s.sk)?.events ?? [],
301
+ reportAt: rep ? rep.last_report_at : -Infinity,
302
+ state: rep ? rep.state : 'none',
303
+ ownerBlock: rep ? P.isOwnerBlock(rep, cfg) && declaredOpen : false,
304
+ now,
305
+ reportAgeMs,
306
+ }
307
+ pendingSeen = Boolean(native?.available && native.pending)
308
+ classification = P.classify(ev, cfg)
309
+ rungs.push({ rung: 'classify', outcome: classification, read: null, evidence: unionEvidence(rungs) })
310
+ }
311
+ const surface = P.surfaceFor(classification, cand.kind === 'recheck' ? null : cand.cycle, { reportAgeMs }, cfg)
312
+ // DESIGN-GAP (added field): which owner the session waits on, so that a
313
+ // recheck can tell a pending prompt from an owner block.
314
+ const reportIsOwnerBlock = report ? P.isOwnerBlock(report, cfg) && declaredAskLive(st, P, session) : false
315
+ const ownerWaitBasis = classification === 'waiting_on_owner' ? (reportIsOwnerBlock || !pendingSeen ? 'owner_block' : 'prompt') : null
316
+ // DESIGN-GAP: an attention item's opening reference is "the trigger's
317
+ // onset", but a recheck (which can surface waiting_on_background) has no
318
+ // onset. Keyed by the recheck's own id, a dismissed item would reopen at
319
+ // the next recheck. The model uses the onset of the cycle that led to the
320
+ // recheck, so a dismissal holds until a new onset.
321
+ const basisOnset = cand.kind === 'recheck' ? cycleOnsetFor(st, s.sk, reportId) : null
322
+ const closeBody = { ...openBody, phase: 'close', rungs, classification, classified_at: now, report_age_ms: reportAgeMs, surface, owner_wait_basis: ownerWaitBasis, basis_onset: basisOnset }
323
+ // DESIGN-GAP: the investigation body names a `remainder` field that is never
324
+ // defined. The model stores what it decided for the queue (`surface`) and
325
+ // the age it decided on, so a replay re-derives the same signal.
326
+ yield put({ kind: 'investigation', id: closeKey, session: env, refs: { tick: tickId }, body: closeBody }, now)
327
+ return signalFrom(closeBody, s, cand)
328
+ }
329
+
330
+ /** The evidence classes of every read the rungs so far used, sorted and without repeats. */
331
+ function unionEvidence(rungs) {
332
+ return [...new Set(rungs.flatMap((r) => r.evidence ?? []))].sort()
333
+ }
334
+
335
+ /**
336
+ * DESIGN-GAP: a tick killed by a crash is replayed only within its own slot.
337
+ * When the process comes back after the slot has passed, the crashed tick is
338
+ * never replayed, and an investigation it opened would stay open for good;
339
+ * the next one for the same onset and cycle would have the same id, and its
340
+ * open record (naming another tick) would conflict with the first. The
341
+ * source's next tick closes such an investigation as `abandoned`: it decided
342
+ * nothing, surfaces nothing and counts as no cycle. Its reads are not
343
+ * reused. The investigation then run for that onset and cycle takes the id
344
+ * H(id, 'after_abandoned') instead, once for each abandoned one before it,
345
+ * so every id is still derived from the ledger alone. An investigation the
346
+ * crashed tick did close keeps its decision: its signal (attention, gone,
347
+ * outage) is applied by the source's next tick, as a replay in the same slot
348
+ * would have applied it, unless the item's closing evidence has arrived
349
+ * since; once a later tick of the source closes, the crashed tick is
350
+ * superseded and nothing more is taken from it. A crashed tick replayed
351
+ * after a later tick abandoned its investigation would count the abandoned
352
+ * one in its spent budget and its signal loop; the model cannot reach that,
353
+ * because a tick is replayed only within its own slot.
354
+ */
355
+ function afterAbandoned(st, id) {
356
+ let next = id
357
+ while (st.investigations.get(next)?.abandoned) next = H(next, 'after_abandoned')
358
+ return next
359
+ }
360
+
361
+ /** Close the investigations of this source left open by a tick that was never replayed. */
362
+ function* closeAbandoned(ctx, { source, tickId, now }) {
363
+ const st = ctx.state
364
+ if (!ctx.policy.closeAbandonedInvestigations) return
365
+ for (const inv of [...st.investigations.values()]) {
366
+ if (inv.closed || inv.source !== source || inv.tickId === tickId) continue
367
+ if (st.ticks.get(inv.tickId)?.closed) continue
368
+ const open = st.index.get(investigationKey(inv.id, 'open'))
369
+ if (!open) continue
370
+ const body = { ...open.body, phase: 'close', rungs: [], classification: 'abandoned', classified_at: null, report_age_ms: null, surface: null, owner_wait_basis: null, basis_onset: null, abandoned_by: tickId }
371
+ yield put({ kind: 'investigation', id: investigationKey(inv.id, 'close'), session: open.session, refs: { tick: tickId }, body }, now)
372
+ }
373
+ }
374
+
375
+ function declaredAskLive(st, P, session) {
376
+ const it = st.items.get(P.ownerItemOf(session, 'declared'))
377
+ return Boolean(it?.open && it.asks.has('declared'))
378
+ }
379
+
380
+ function cycleOnsetFor(st, sk, reportId) {
381
+ let best = null
382
+ for (const inv of st.investigations.values()) {
383
+ if (inv.sk === sk && inv.reportId === reportId && inv.trigger !== 'recheck' && inv.closed && (!best || inv.closeSeq > best.closeSeq)) best = inv
384
+ }
385
+ return best ? best.onset : null
386
+ }
387
+
388
+ function signalFrom(body, s, cand) {
389
+ if (!body.surface) return null
390
+ if (body.surface === 'outage') return { type: 'outage', source: body.source, onset: body.onset, investigationId: body.investigation_id }
391
+ return {
392
+ type: body.surface,
393
+ session: s.session,
394
+ sk: s.sk,
395
+ reportId: body.report_id,
396
+ onset: body.onset ?? body.basis_onset ?? body.investigation_id,
397
+ classification: body.classification,
398
+ investigationId: body.investigation_id,
399
+ trigger: cand.trigger,
400
+ }
401
+ }
402
+
403
+ /**
404
+ * Plan this tick's investigations for one source. Returns the queue signals
405
+ * (attention, gone, outage) the closed investigations produced.
406
+ */
407
+ export function* planInvestigations(ctx, { source, tickId, now, world }) {
408
+ const st = ctx.state
409
+ const P = ctx.policy
410
+ const cfg = st.config
411
+ yield* closeAbandoned(ctx, { source, tickId, now })
412
+ const srcHeld = sourceAllFailed(st, source, tickId)
413
+ const cands = []
414
+ const srcCand = srcHeld ? sourceCandidate(ctx, source, tickId) : null
415
+ if (srcCand) cands.push(srcCand)
416
+ for (const s of sessionsOf(st, source)) cands.push(...candidatesFor(ctx, s, { tickId, srcHeld }))
417
+ // Budgets already spent by a crashed run of this same tick.
418
+ let usedCycles = 0
419
+ let usedPaid = 0
420
+ for (const inv of st.investigations.values()) {
421
+ if (inv.tickId !== tickId || !inv.closed) continue
422
+ if (inv.trigger === 'recheck') {
423
+ if (!sourceCaps(cfg, inv.source).native_in_read) usedPaid += 1
424
+ } else usedCycles += 1
425
+ }
426
+ const selected = P.selectInvestigations(cands, {
427
+ cycleBudget: Math.max(0, cfg.investigation_budget_per_tick - usedCycles),
428
+ recheckBudget: Math.max(0, cfg.recheck_budget_per_tick - usedPaid),
429
+ })
430
+ const signals = []
431
+ for (const cand of selected) {
432
+ const sig = yield* runCandidate(ctx, cand, { tickId, now, world })
433
+ if (sig) signals.push(sig)
434
+ }
435
+ // Signals from investigations a crashed run of this tick already closed.
436
+ for (const inv of st.investigations.values()) {
437
+ if (inv.tickId !== tickId || !inv.closed) continue
438
+ if (selected.some((c) => c.resume?.id === inv.id)) continue
439
+ const rec = st.index.get(investigationKey(inv.id, 'close'))
440
+ const s = inv.sk ? st.sessions.get(inv.sk) : sessionsOf(st, inv.source)[0]
441
+ const sig = rec && s ? signalFrom(rec.body, s, { trigger: inv.trigger }) : null
442
+ if (sig && !signals.some((x) => x.investigationId === sig.investigationId)) signals.push(sig)
443
+ }
444
+ // Signals from investigations closed by an earlier tick of this source
445
+ // that was never replayed (see `closeAbandoned`), unless their closing
446
+ // evidence has arrived since. (The `abandoned` filter is belt and braces:
447
+ // an abandoned close surfaces nothing, so it yields no signal anyway.)
448
+ for (const inv of P.recoverAbandonedSignals ? st.investigations.values() : []) {
449
+ if (!inv.closed || inv.abandoned || inv.tickId === tickId || inv.source !== source) continue
450
+ const t = st.ticks.get(inv.tickId)
451
+ if (!t || t.closed || t.superseded) continue
452
+ const rec = st.index.get(investigationKey(inv.id, 'close'))
453
+ const s = inv.sk ? st.sessions.get(inv.sk) : sessionsOf(st, inv.source)[0]
454
+ const sig = rec && s ? signalFrom(rec.body, s, { trigger: inv.trigger }) : null
455
+ if (!sig || signals.some((x) => x.investigationId === sig.investigationId) || evidenceSince(st, sig, source, tickId)) continue
456
+ signals.push(sig)
457
+ }
458
+ return { signals, srcHeld, srcOnset: srcHeld ? sourceOnset(st, source, tickId) : null }
459
+ }
460
+
461
+ /**
462
+ * Whether the item a recovered signal would raise already has its closing
463
+ * evidence at this tick. (The `tickId` tests always hold here: every session
464
+ * of the source has its check of this tick before investigations run.)
465
+ */
466
+ function evidenceSince(st, sig, source, tickId) {
467
+ if (sig.type === 'outage') return sessionsOf(st, source).some((s) => s.cur && s.cur.tickId === tickId && (s.cur.outcome === 'ok' || s.cur.outcome === 'no_report'))
468
+ const s = st.sessions.get(sig.sk)
469
+ if (sig.type === 'gone') return Boolean(s?.cur && s.cur.tickId === tickId && s.cur.listed)
470
+ const latest = s?.latestAuthored ? st.reports.get(s.latestAuthored)?.body : null
471
+ const opening = sig.reportId ? st.reports.get(sig.reportId)?.body : null
472
+ return Boolean(latest && (!opening || latest.last_report_at > opening.last_report_at))
473
+ }
474
+
@@ -0,0 +1,177 @@
1
+ /**
2
+ * Idempotency keys for every record kind of the freshness ledger.
3
+ *
4
+ * Each function returns the record's `id`. The tuples follow the key table
5
+ * in README exactly, without extra kind tags, so that a collision the table
6
+ * allows is a collision the model reproduces. "Session" in a key is always the
7
+ * identity triple (source, native id, incarnation), never a label.
8
+ *
9
+ * Pure: no I/O, no clock, no randomness.
10
+ */
11
+
12
+ import { H } from './hash.js'
13
+
14
+ /** The session identity used in keys. A label is never part of it. */
15
+ export function sessionIdentity(session) {
16
+ return [session.source, session.native_id, session.incarnation ?? null]
17
+ }
18
+
19
+ /** A stable string form of the identity, used as a map key. */
20
+ export function sessionKey(session) {
21
+ return H('session', sessionIdentity(session))
22
+ }
23
+
24
+ /** `report`: H(session, report_time, fields_hash). */
25
+ export function reportKey(session, reportTime, fieldsHash) {
26
+ return H(sessionIdentity(session), reportTime, fieldsHash)
27
+ }
28
+
29
+ /** `tick_id`: H(ledger_id, source, slot_start). */
30
+ export function tickId(ledgerId, source, slotStart) {
31
+ return H(ledgerId, source, slotStart)
32
+ }
33
+
34
+ /** `tick` record: H(tick_id, phase). */
35
+ export function tickKey(id, phase) {
36
+ return H(id, phase)
37
+ }
38
+
39
+ /** `check` made by a tick: H(tick_id, session). */
40
+ export function checkTickKey(id, session) {
41
+ return H(id, sessionIdentity(session))
42
+ }
43
+
44
+ /** `check` made for an accepted emit: H(emit_id, session). */
45
+ export function checkEmitKey(emitId, session) {
46
+ return H(emitId, sessionIdentity(session))
47
+ }
48
+
49
+ /**
50
+ * The read numbers of the reads inside one investigation: 1 the re-read, 2 its
51
+ * one retry, 3 the read that confirms a session is gone; 4, the separate
52
+ * activity read, is the model's addition (README, key table).
53
+ */
54
+ export const READ_NO = Object.freeze({
55
+ REREAD: 1,
56
+ RETRY: 2,
57
+ CONFIRM_GONE: 3,
58
+ // DESIGN-GAP: the activity read on a source whose tick read carries no native state
59
+ // needs a separate activity read, and a recheck "that needs a read of its
60
+ // own" makes one too, but `read_no` defines only 1..3. The model gives the
61
+ // activity read number 4.
62
+ ACTIVITY: 4,
63
+ })
64
+
65
+ /** `check` made inside an investigation: H(investigation_id, read_no). */
66
+ export function checkInvestigationKey(investigationId, readNo) {
67
+ return H(investigationId, readNo)
68
+ }
69
+
70
+ /** `emit`: the source's event id, or H(session, type, host timestamp). */
71
+ export function emitKey({ sourceEventId, session, type, hostTs }) {
72
+ if (sourceEventId != null) return String(sourceEventId)
73
+ return H(sessionIdentity(session), type, hostTs)
74
+ }
75
+
76
+ /** `activity` for a state seen at a read: H(check_id, basis, ref). */
77
+ export function activityStateKey(checkId, basis, ref) {
78
+ return H(checkId, basis, ref ?? null)
79
+ }
80
+
81
+ /**
82
+ * `activity` for an event: the host's event id, or H(session, basis,
83
+ * activity_at) when the host gives none.
84
+ *
85
+ * DESIGN-GAP: the key table uses the host's event id alone. A host that
86
+ * numbers events per session gives two sessions the same id, and the second
87
+ * session's event would collide with the first's. The model puts the
88
+ * session identity in the key in both cases.
89
+ */
90
+ export function activityEventKey({ hostEventId, session, basis, activityAt }) {
91
+ if (hostEventId != null) return H(sessionIdentity(session), 'event', String(hostEventId))
92
+ return H(sessionIdentity(session), basis, activityAt ?? null)
93
+ }
94
+
95
+ /** `investigation_id` for a per-session cycle. */
96
+ export function investigationId({ session, reportId, trigger, onset, cycle }) {
97
+ return H(sessionIdentity(session), reportId ?? null, trigger, onset, cycle)
98
+ }
99
+
100
+ /** `investigation_id` for a source-level outage cycle. */
101
+ export function sourceInvestigationId({ source, onset, cycle }) {
102
+ return H(source, 'source_unreachable', onset, cycle)
103
+ }
104
+
105
+ /** `investigation_id` for a recheck: one per session, report and tick. */
106
+ export function recheckInvestigationId({ session, reportId, tickId: tid }) {
107
+ return H(sessionIdentity(session), reportId ?? null, 'recheck', tid)
108
+ }
109
+
110
+ /** `investigation` record: H(investigation_id, phase). */
111
+ export function investigationKey(id, phase) {
112
+ return H(id, phase)
113
+ }
114
+
115
+ /** Item identity by origin. */
116
+ export const itemIds = Object.freeze({
117
+ // One owner item per session, whatever its asks (a declared block, a
118
+ // pending prompt, or both).
119
+ owner: (session) => H(sessionIdentity(session), 'owner_block', 'owner'),
120
+ // An owner item per ask kind: the earlier identity, kept for the variant
121
+ // that restores two separate items.
122
+ ownerAsk: (session, kind) => H(sessionIdentity(session), 'owner_block', kind),
123
+ seed: (seedScope, seedSession) => H(seedScope, seedSession, 'session_request', 'seed'),
124
+ issue: (workKey) => H(workKey, 'session_request', 'issue'),
125
+ attention: (session, reportId) => H(sessionIdentity(session), 'session_attention', reportId ?? null),
126
+ gone: (session) => H(sessionIdentity(session), 'session_attention', 'gone'),
127
+ outage: (source) => H(source, 'source_unreachable'),
128
+ })
129
+
130
+ /** Steps that send, and so have an attempt and an outcome record. */
131
+ export const SENDING_STEPS = Object.freeze(new Set(['shown', 'reminded', 'returned']))
132
+
133
+ /**
134
+ * The per-step ordinal table (README, keys). `ctx` carries what the
135
+ * ordinal is drawn from: `presentation`, `k`, `ackRef`, `changeRef`.
136
+ */
137
+ export const SURFACE_ORDINAL = Object.freeze({
138
+ queued: () => 0,
139
+ resolved: () => 0,
140
+ withdrawn: () => 0,
141
+ shown: (ctx) => ctx.presentation,
142
+ expired: (ctx) => ctx.presentation,
143
+ preempted: (ctx) => ctx.presentation,
144
+ exhausted: (ctx) => ctx.presentation,
145
+ reminded: (ctx) => ctx.k,
146
+ returned: () => 1,
147
+ deferred: (ctx) => ctx.ackRef,
148
+ updated: (ctx) => ctx.changeRef,
149
+ })
150
+
151
+ export function surfaceOrdinal(step, ctx) {
152
+ const fn = SURFACE_ORDINAL[step]
153
+ if (!fn) throw new Error(`surfaceOrdinal: unknown step ${step}`)
154
+ const v = fn(ctx)
155
+ if (v === undefined) throw new Error(`surfaceOrdinal: ${step} needs an ordinal input`)
156
+ return v
157
+ }
158
+
159
+ /** `surface`: H(item_id, episode, step, ordinal, phase). */
160
+ export function surfaceKey(itemId, episode, step, ordinal, phase) {
161
+ return H(itemId, episode, step, ordinal, phase)
162
+ }
163
+
164
+ /** `owner_ack`: H(item_id, episode, ack_ref, phase). */
165
+ export function ownerAckKey(itemId, episode, ackRef, phase) {
166
+ return H(itemId, episode, ackRef, phase)
167
+ }
168
+
169
+ /** `config`: H(previous config record id, config_hash). */
170
+ export function configKey(previousConfigRecordId, configHash) {
171
+ return H(previousConfigRecordId ?? null, configHash)
172
+ }
173
+
174
+ /** `system`: H(event, the ids in detail). */
175
+ export function systemKey(event, ids) {
176
+ return H(event, ids)
177
+ }