@chroxy/server 0.11.0 → 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.
- package/CONFIG.md +206 -18
- package/README.md +2 -2
- package/hooks/claude-native-route-check.mjs +17 -0
- package/hooks/permission-hook.sh +166 -11
- package/package.json +16 -12
- package/sidecar/Dockerfile +1 -1
- package/sidecar/PROTOCOL.md +9 -1
- package/sidecar/agent.js +102 -10
- package/sidecar/package-lock.json +3 -3
- package/src/acp-config.js +206 -0
- package/src/acp-session.js +958 -0
- package/src/activity-registry.js +110 -5
- package/src/agent-connections.js +304 -0
- package/src/agent-control/client.js +1645 -0
- package/src/agent-control/events.js +551 -0
- package/src/agent-control/local-connection.js +293 -0
- package/src/agent-control/mcp-server.js +547 -0
- package/src/anthropic-compatible-config.js +30 -4
- package/src/anthropic-compatible-session.js +15 -6
- package/src/anthropic-gemini-shim.js +444 -0
- package/src/anthropic-gemini-translate.js +1030 -0
- package/src/anthropic-openai-shim.js +0 -1
- package/src/archive-continuation.js +164 -0
- package/src/assistant-response.js +24 -0
- package/src/auth-probes.js +120 -13
- package/src/background-shell-tracker.js +27 -0
- package/src/base-session.js +1520 -36
- package/src/bearer-recheck.js +49 -0
- package/src/billing-budget.js +19 -0
- package/src/billing-class.js +40 -7
- package/src/binary-provenance-trust.js +11 -5
- package/src/bound-client-policy.js +291 -0
- package/src/built-in-tools/bash-exec.js +46 -7
- package/src/built-in-tools/file-ops.js +69 -5
- package/src/built-in-tools/tool-transforms.js +1113 -13
- package/src/byok-compose-state.js +6 -9
- package/src/byok-credentials.js +2 -3
- package/src/byok-mcp-client.js +92 -7
- package/src/byok-mcp-config.js +633 -122
- package/src/byok-mcp-fleet.js +49 -7
- package/src/byok-mcp-oauth-store.js +18 -16
- package/src/byok-mcp-trust.js +37 -23
- package/src/byok-session.js +707 -179
- package/src/byok-tool-executor.js +2742 -26
- package/src/byok-tools.js +9 -2
- package/src/channels/chroxy-channel-server.js +2 -3
- package/src/checkpoint-manager.js +64 -46
- package/src/claude-channel-session.js +16 -10
- package/src/claude-model-catalog.js +131 -16
- package/src/claude-model-refresh.js +385 -0
- package/src/claude-model-request.js +103 -0
- package/src/claude-setting-sources.js +74 -0
- package/src/claude-stream-parser.js +53 -3
- package/src/claude-tui/diagnostic-tail.js +83 -0
- package/src/claude-tui/form-driver.js +44 -7
- package/src/claude-tui/model-error.js +41 -0
- package/src/claude-tui/pty-driver.js +215 -88
- package/src/claude-tui/sanitize-question-payload.js +109 -0
- package/src/claude-tui/usage-limit.js +239 -0
- package/src/claude-tui-session.js +3563 -284
- package/src/claude-tui-tool-response.js +300 -0
- package/src/cli/agent-cmd.js +236 -0
- package/src/cli/agent-control-cmd.js +65 -0
- package/src/cli/config-cmd.js +4 -4
- package/src/cli/config-dir-cmd.js +234 -0
- package/src/cli/connection-state.js +54 -0
- package/src/cli/deploy-cmd.js +45 -10
- package/src/cli/doctor-cmd.js +7 -3
- package/src/cli/freshness-cmd.js +53 -0
- package/src/cli/init-cmd.js +15 -16
- package/src/cli/pages-cmd.js +6 -4
- package/src/cli/pair-code-cmd.js +7 -6
- package/src/cli/pair-discord-cmd.js +7 -6
- package/src/cli/providers-cmd.js +3 -3
- package/src/cli/schedule-cmd.js +91 -40
- package/src/cli/server-cmd.js +54 -1
- package/src/cli/service-cmd.js +33 -10
- package/src/cli/session-cmd.js +227 -74
- package/src/cli/shared.js +162 -11
- package/src/cli/shell-cmd.js +7 -4
- package/src/cli/status-cmd.js +19 -5
- package/src/cli/tokens-cmd.js +4 -5
- package/src/cli/tunnel-cmd.js +255 -24
- package/src/cli/worktree-gc-cmd.js +2 -2
- package/src/cli-session.js +1250 -126
- package/src/cli.js +8 -0
- package/src/codex-app-server-client.js +36 -3
- package/src/codex-app-server-session.js +1517 -81
- package/src/codex-bundled-client.js +66 -0
- package/src/codex-error-text.js +114 -0
- package/src/codex-model-catalog.js +548 -0
- package/src/codex-model-rejections.js +87 -0
- package/src/codex-native-resume.js +104 -0
- package/src/codex-protocol-capabilities.js +188 -0
- package/src/codex-session.js +450 -27
- package/src/config-dir-migration.js +449 -0
- package/src/config-dir.js +108 -0
- package/src/config.js +306 -26
- package/src/connection-authority.js +48 -0
- package/src/connection-info.js +78 -23
- package/src/connection-locality.js +60 -0
- package/src/container-liveness-monitor.js +189 -0
- package/src/continuation-metadata-worker.js +17 -0
- package/src/continuations.js +227 -0
- package/src/control-room/host-prune.js +5 -0
- package/src/control-room/integrations.js +7 -20
- package/src/control-room/skills-inventory.js +2 -2
- package/src/conversation-scanner.js +42 -39
- package/src/conversation-scope.js +59 -39
- package/src/conversation-search.js +28 -39
- package/src/credential-store.js +23 -19
- package/src/daemon-commit.js +92 -0
- package/src/daemon-idle-state.js +171 -0
- package/src/daemon-update-status.js +314 -0
- package/src/dashboard-build.js +70 -0
- package/src/declared-status.js +90 -0
- package/src/deepseek-credentials.js +2 -3
- package/src/dev-preview.js +170 -182
- package/src/device-preferences.js +2 -2
- package/src/diff-parser.js +87 -0
- package/src/discord-credentials.js +2 -3
- package/src/docker-byok-pool.js +3 -1
- package/src/docker-byok-session.js +678 -78
- package/src/docker-image-allowlist.js +23 -1
- package/src/docker-sdk-session.js +172 -3
- package/src/docker-session.js +294 -11
- package/src/doctor.js +781 -64
- package/src/durable-write.js +35 -0
- package/src/edited-input.js +264 -0
- package/src/environment-manager.js +175 -36
- package/src/environments/authority.js +101 -0
- package/src/environments/backends/container-claude-spawn.js +94 -0
- package/src/environments/backends/docker.js +31 -10
- package/src/environments/backends/k8s.js +49 -24
- package/src/environments/destroy-with-sessions.js +142 -0
- package/src/event-ingest.js +118 -13
- package/src/event-normalizer.js +186 -235
- package/src/folder-trust-wire.js +137 -0
- package/src/folder-trust-worker.js +17 -0
- package/src/folder-trust.js +1572 -0
- package/src/freshness/activity-meter.js +101 -0
- package/src/freshness/adapter.js +199 -0
- package/src/freshness/checks.js +239 -0
- package/src/freshness/config.js +98 -0
- package/src/freshness/core.js +185 -0
- package/src/freshness/derive.js +680 -0
- package/src/freshness/exchange.js +305 -0
- package/src/freshness/file-ledger.js +400 -0
- package/src/freshness/grade.js +81 -0
- package/src/freshness/hash.js +45 -0
- package/src/freshness/inbox.js +163 -0
- package/src/freshness/index.js +20 -0
- package/src/freshness/investigation.js +474 -0
- package/src/freshness/keys.js +177 -0
- package/src/freshness/ledger.js +122 -0
- package/src/freshness/outbox.js +131 -0
- package/src/freshness/policy.js +599 -0
- package/src/freshness/queue.js +843 -0
- package/src/freshness/read-errors.js +23 -0
- package/src/freshness/render.js +153 -0
- package/src/freshness/runtime.js +113 -0
- package/src/freshness/session-registry-adapter.js +161 -0
- package/src/freshness/state-file-adapter.js +167 -0
- package/src/freshness-runner/build-info.js +139 -0
- package/src/freshness-runner/cli.js +105 -0
- package/src/freshness-runner/run-tick.js +109 -0
- package/src/freshness-runner/stamp.js +57 -0
- package/src/freshness-sources/claude-transcript-adapter.js +211 -0
- package/src/freshness-sources/codex-transcript-adapter.js +33 -0
- package/src/freshness-sources/index.js +8 -0
- package/src/gemini-byok-session.js +292 -0
- package/src/gemini-credentials.js +67 -0
- package/src/gemini-key-safety.js +246 -0
- package/src/gemini-models.js +386 -0
- package/src/gemini-session.js +81 -5
- package/src/handler-utils.js +540 -80
- package/src/handlers/checkpoint-handlers.js +47 -4
- package/src/handlers/control-room-handlers.js +51 -11
- package/src/handlers/conversation-handlers.js +469 -56
- package/src/handlers/daemon-update-handlers.js +81 -0
- package/src/handlers/evaluator-handlers.js +14 -1
- package/src/handlers/feature-handlers.js +186 -69
- package/src/handlers/file-handlers.js +57 -13
- package/src/handlers/folder-trust-handlers.js +90 -0
- package/src/handlers/input-handlers.js +714 -48
- package/src/handlers/orchestration-handlers.js +3 -3
- package/src/handlers/principal-admin-handlers.js +229 -0
- package/src/handlers/principal-handlers.js +262 -0
- package/src/handlers/scheduler-handlers.js +92 -18
- package/src/handlers/session-handlers.js +551 -20
- package/src/handlers/session-pr-status-handlers.js +283 -0
- package/src/handlers/session-pr-threads-handlers.js +247 -0
- package/src/handlers/settings-handlers.js +372 -50
- package/src/handlers/skills-handlers.js +20 -4
- package/src/handlers/summarize-handlers.js +32 -1
- package/src/handlers/survey-throttle.js +380 -0
- package/src/health-proof.js +40 -0
- package/src/history-page.js +112 -0
- package/src/http-routes.js +127 -8
- package/src/ide/search.js +24 -6
- package/src/ide/symbols.js +20 -6
- package/src/input-context.js +117 -0
- package/src/instruction-policy-compiler.js +229 -0
- package/src/instruction-policy.js +250 -0
- package/src/jsonl-reader.js +378 -91
- package/src/jsonl-subprocess-session.js +96 -9
- package/src/keychain.js +1 -1
- package/src/logger.js +166 -30
- package/src/mailbox-route.js +113 -22
- package/src/message-wire.js +386 -0
- package/src/model-discovery.js +43 -3
- package/src/models.js +1276 -174
- package/src/notification-prefs.js +27 -4
- package/src/notifications/discord-billing-sink.js +22 -5
- package/src/notifications/discord-ci-sink.js +243 -0
- package/src/notifications/discord-webhook-client.js +71 -0
- package/src/notifications/discord-webhook-sink.js +64 -23
- package/src/notifications/expo-push-sink.js +85 -6
- package/src/notifications/ready-body.js +16 -5
- package/src/ollama-session.js +34 -2
- package/src/orchestration/build-manager.js +9 -2
- package/src/orchestration/git-ops.js +41 -7
- package/src/orchestration/orchestration-manager.js +112 -36
- package/src/orchestration/permission-gate.js +17 -2
- package/src/orchestration/run-model.js +2 -1
- package/src/orchestration/run-record.js +11 -0
- package/src/orchestration/turn-driver.js +185 -43
- package/src/orphan-reaper.js +470 -0
- package/src/outgoing-policy.js +189 -0
- package/src/pairing.js +92 -13
- package/src/path-hash-trust-ledger.js +642 -25
- package/src/permission-deadlines.js +82 -0
- package/src/permission-floor.js +1410 -43
- package/src/permission-hook.js +180 -69
- package/src/permission-manager.js +737 -89
- package/src/permission-mode-support.js +35 -0
- package/src/permission-resolved-by.js +89 -0
- package/src/permission-resolver.js +126 -8
- package/src/permission-scope.js +43 -0
- package/src/platform.js +315 -47
- package/src/preview-ingress.js +54 -0
- package/src/preview-target.js +213 -0
- package/src/principal-audit.js +189 -0
- package/src/principal-binding.js +25 -0
- package/src/principal-brakes.js +21 -0
- package/src/principal-effect.js +101 -0
- package/src/principal-journal.js +905 -0
- package/src/principal-kill-switch.js +183 -0
- package/src/principal-label.js +5 -0
- package/src/principal-pending-permissions.js +177 -0
- package/src/principal-policy.js +1094 -0
- package/src/principal-sessions-snapshot.js +208 -0
- package/src/principal-store.js +488 -0
- package/src/principal-subscriptions.js +283 -0
- package/src/prompt-evaluator.js +34 -4
- package/src/provider-customization.js +180 -0
- package/src/providers.js +209 -4
- package/src/push.js +30 -4
- package/src/question-route-map.js +130 -0
- package/src/redaction.js +531 -20
- package/src/roster-broadcast.js +186 -0
- package/src/scheduled-task-store.js +330 -26
- package/src/scheduler.js +368 -11
- package/src/sdk-session.js +2114 -188
- package/src/server-cli/preview-shutdown.js +22 -0
- package/src/server-cli/push-notification-handler.js +17 -3
- package/src/server-cli/server-orchestrator.js +28 -5
- package/src/server-cli-child.js +33 -18
- package/src/server-cli.js +553 -38
- package/src/server-identity.js +15 -11
- package/src/service.js +396 -25
- package/src/session-archive-limits.js +15 -0
- package/src/session-archive.js +1029 -0
- package/src/session-busy-state.js +72 -0
- package/src/session-ci-watcher.js +1099 -0
- package/src/session-context.js +7 -2
- package/src/session-manager.js +4062 -312
- package/src/session-message-history.js +841 -16
- package/src/session-name-allocator.js +685 -0
- package/src/session-pr-status.js +654 -0
- package/src/session-pr-threads.js +271 -0
- package/src/session-preset-trust.js +3 -3
- package/src/session-preset.js +10 -5
- package/src/session-state-persistence.js +94 -17
- package/src/session-timeout-manager.js +20 -0
- package/src/session-token-store.js +17 -8
- package/src/session-wake.js +240 -0
- package/src/shell-approval-info.js +2 -2
- package/src/shell-approval-store.js +3 -1
- package/src/skills-loader.js +7 -4
- package/src/skills-manager.js +2 -2
- package/src/skills-trust.js +95 -13
- package/src/skills-usage.js +2 -3
- package/src/snapshots-store.js +2 -3
- package/src/statusline.js +100 -29
- package/src/summarize-session.js +53 -4
- package/src/supervisor.js +22 -11
- package/src/sweep-stale-provider-dirs.js +95 -0
- package/src/thinking-level-wire.js +39 -0
- package/src/thinking-stream.js +179 -0
- package/src/tool-result.js +61 -0
- package/src/transcript-sources.js +109 -0
- package/src/transcript-tasks.js +372 -25
- package/src/trusted-file-read.js +302 -0
- package/src/tunnel/base.js +0 -8
- package/src/tunnel/cloudflare.js +34 -31
- package/src/tunnel/index.js +9 -0
- package/src/tunnel/preview.js +64 -0
- package/src/turn-outcome.js +140 -0
- package/src/usage-normalize.js +9 -5
- package/src/user-shell-session.js +59 -5
- package/src/utils/agent-sdk-version.js +107 -0
- package/src/utils/argv-safety.js +770 -0
- package/src/utils/auth-cause.js +60 -0
- package/src/utils/binary-package-manifest.js +639 -0
- package/src/utils/binary-version.js +224 -0
- package/src/utils/bounded-regex-worker.js +29 -0
- package/src/utils/bounded-regex.js +162 -0
- package/src/utils/claude-binary.js +43 -0
- package/src/utils/claude-config-dir.js +245 -0
- package/src/utils/claude-login-command.js +16 -0
- package/src/utils/claude-native-route.js +81 -0
- package/src/utils/componentwise-resolver.js +133 -37
- package/src/utils/deploy-control-files.js +87 -0
- package/src/utils/exec-failure-reason.js +21 -0
- package/src/utils/git-repo.js +42 -0
- package/src/utils/is-entry-point.js +137 -0
- package/src/utils/node-pty-probe.js +95 -0
- package/src/utils/node-pty-support.js +118 -0
- package/src/utils/opened-file-path.js +167 -0
- package/src/utils/path-containment.js +165 -0
- package/src/utils/permission-mode-sidecar.js +51 -0
- package/src/utils/pid-liveness.js +47 -0
- package/src/utils/preflight.js +360 -16
- package/src/utils/read-limiter.js +217 -0
- package/src/utils/regular-file.js +375 -0
- package/src/utils/safe-regex.js +113 -0
- package/src/utils/small-file.js +129 -0
- package/src/utils/spawn-env.js +189 -4
- package/src/utils/stale-session-dirs.js +182 -0
- package/src/utils/stat-identity.js +43 -0
- package/src/utils/verify-provenance.js +406 -13
- package/src/web-task-manager.js +297 -16
- package/src/worktree-gc.js +202 -6
- package/src/ws-auth.js +163 -31
- package/src/ws-broadcaster.js +49 -5
- package/src/ws-client-manager.js +24 -1
- package/src/ws-client-sender.js +7 -0
- package/src/ws-file-ops/browser.js +363 -58
- package/src/ws-file-ops/common.js +320 -14
- package/src/ws-file-ops/git.js +395 -42
- package/src/ws-file-ops/index.js +2 -0
- package/src/ws-file-ops/memory.js +137 -35
- package/src/ws-file-ops/open-nofollow.js +354 -0
- package/src/ws-file-ops/reader.js +571 -113
- package/src/ws-forwarding.js +349 -39
- package/src/ws-handler-context.js +88 -2
- package/src/ws-history.js +1010 -175
- package/src/ws-message-handlers.js +25 -1
- package/src/ws-permissions.js +307 -37
- package/src/ws-schemas.js +5 -0
- package/src/ws-server.js +885 -98
- package/sidecar/node_modules/.package-lock.json +0 -29
- package/sidecar/node_modules/ws/LICENSE +0 -20
- package/sidecar/node_modules/ws/README.md +0 -548
- package/sidecar/node_modules/ws/browser.js +0 -8
- package/sidecar/node_modules/ws/index.js +0 -22
- package/sidecar/node_modules/ws/lib/buffer-util.js +0 -131
- package/sidecar/node_modules/ws/lib/constants.js +0 -19
- package/sidecar/node_modules/ws/lib/event-target.js +0 -292
- package/sidecar/node_modules/ws/lib/extension.js +0 -203
- package/sidecar/node_modules/ws/lib/limiter.js +0 -55
- package/sidecar/node_modules/ws/lib/permessage-deflate.js +0 -528
- package/sidecar/node_modules/ws/lib/receiver.js +0 -706
- package/sidecar/node_modules/ws/lib/sender.js +0 -602
- package/sidecar/node_modules/ws/lib/stream.js +0 -161
- package/sidecar/node_modules/ws/lib/subprotocol.js +0 -62
- package/sidecar/node_modules/ws/lib/validation.js +0 -152
- package/sidecar/node_modules/ws/lib/websocket-server.js +0 -554
- package/sidecar/node_modules/ws/lib/websocket.js +0 -1393
- package/sidecar/node_modules/ws/package.json +0 -70
- package/sidecar/node_modules/ws/wrapper.mjs +0 -21
- package/src/dashboard-next/dist/assets/index-C2ipeGlq.js +0 -111
- package/src/dashboard-next/dist/assets/index-DM-_dISG.css +0 -1
- package/src/dashboard-next/dist/index.html +0 -13
- package/src/dashboard-next/node_modules/.vite/vitest/da39a3ee5e6b4b0d3255bfef95601890afd80709/results.json +0 -1
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The per-application activity meter: for one day, how many sessions were live
|
|
3
|
+
* and for how many hours each host application was active.
|
|
4
|
+
*
|
|
5
|
+
* It is a pure function of samples. A sample is one snapshot of the live
|
|
6
|
+
* sessions at a time: `{ at, sessions: [{ id, app, busy }] }`, taken from the
|
|
7
|
+
* registry by `sampleRegistry`. Nothing here reads a clock or a file, and no
|
|
8
|
+
* title or path is in a sample, so none is in a record.
|
|
9
|
+
*
|
|
10
|
+
* Definitions (each is what a hand count would do):
|
|
11
|
+
* - live sessions: the distinct session ids seen in any sample dated inside
|
|
12
|
+
* the day, counted under the application of the first such sample;
|
|
13
|
+
* - active time: each sample holds until the next one. The span from a
|
|
14
|
+
* sample to the next counts, once, as active time for an application when
|
|
15
|
+
* any of its sessions was busy in the earlier sample. A span is credited
|
|
16
|
+
* at most `maxGapMs` (a gap between samples is not evidence of activity
|
|
17
|
+
* past it), is clipped to the day, and the last sample credits nothing
|
|
18
|
+
* because no later sample bounds it;
|
|
19
|
+
* - the day is the calendar day at `utcOffsetMinutes` from UTC (UTC by default).
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { loadRegistry } from './session-registry-adapter.js'
|
|
23
|
+
|
|
24
|
+
const HOUR_MS = 3_600_000
|
|
25
|
+
const DAY_MS = 24 * HOUR_MS
|
|
26
|
+
const DEFAULT_MAX_GAP_MS = 30 * 60 * 1000
|
|
27
|
+
const DAY_RE = /^(\d{4})-(\d{2})-(\d{2})$/
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* One sample of the registry at `at`, or null when it cannot be read this
|
|
31
|
+
* time (an unreadable registry is a missing sample, not an empty one).
|
|
32
|
+
*/
|
|
33
|
+
export function sampleRegistry({ dir, at, ...limits }) {
|
|
34
|
+
const snap = loadRegistry(dir, limits)
|
|
35
|
+
if (snap.error) return null
|
|
36
|
+
return { at, sessions: [...snap.rows.values()].map((r) => ({ id: r.id, app: r.app, busy: r.busy })) }
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function dayWindow(day, utcOffsetMinutes) {
|
|
40
|
+
const m = DAY_RE.exec(day)
|
|
41
|
+
if (!m) throw new TypeError('dailyActivity: day must be YYYY-MM-DD')
|
|
42
|
+
const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])]
|
|
43
|
+
const utc = new Date(Date.UTC(y, mo - 1, d))
|
|
44
|
+
// Round-trip: an impossible date would otherwise roll over into another day.
|
|
45
|
+
if (y < 1970 || utc.getUTCFullYear() !== y || utc.getUTCMonth() !== mo - 1 || utc.getUTCDate() !== d) throw new TypeError('dailyActivity: day is not a real date (YYYY-MM-DD, 1970 or later)')
|
|
46
|
+
const start = utc.getTime() - utcOffsetMinutes * 60_000
|
|
47
|
+
return { start, end: start + DAY_MS }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* The activity record for one day.
|
|
52
|
+
*
|
|
53
|
+
* @param {object} opts
|
|
54
|
+
* @param {object[]} opts.samples samples, in any order
|
|
55
|
+
* @param {string} opts.day `YYYY-MM-DD`
|
|
56
|
+
* @param {number} [opts.utcOffsetMinutes] the local time's offset from UTC in minutes, as for UTC-6 is -360 (default 0)
|
|
57
|
+
* @param {number} [opts.maxGapMs] longest span credited from one sample (default 30 minutes)
|
|
58
|
+
* @returns {{ day: string, utc_offset_minutes: number, samples: number, apps: { app: string, live_sessions: number, active_ms: number, active_hours: number }[] }}
|
|
59
|
+
*/
|
|
60
|
+
export function dailyActivity({ samples, day, utcOffsetMinutes = 0, maxGapMs = DEFAULT_MAX_GAP_MS }) {
|
|
61
|
+
if (!Array.isArray(samples)) throw new TypeError('dailyActivity: samples must be an array')
|
|
62
|
+
if (!Number.isFinite(utcOffsetMinutes) || Math.abs(utcOffsetMinutes) > 840 || !(maxGapMs > 0)) throw new TypeError('dailyActivity: bad offset or gap')
|
|
63
|
+
const { start, end } = dayWindow(day, utcOffsetMinutes)
|
|
64
|
+
// A malformed sample or session entry is dropped, never thrown on.
|
|
65
|
+
const okSession = (x) => x !== null && typeof x === 'object' && typeof x.id === 'string' && typeof x.app === 'string'
|
|
66
|
+
const ordered = samples
|
|
67
|
+
.filter((s) => s && Number.isFinite(s.at) && Array.isArray(s.sessions))
|
|
68
|
+
.map((s) => ({ at: s.at, sessions: s.sessions.filter(okSession) }))
|
|
69
|
+
.sort((a, b) => a.at - b.at)
|
|
70
|
+
const apps = new Map()
|
|
71
|
+
const slot = (app) => {
|
|
72
|
+
if (!apps.has(app)) apps.set(app, { app, ids: new Set(), active_ms: 0 })
|
|
73
|
+
return apps.get(app)
|
|
74
|
+
}
|
|
75
|
+
const seen = new Set()
|
|
76
|
+
let inDay = 0
|
|
77
|
+
for (const s of ordered) {
|
|
78
|
+
if (s.at < start || s.at >= end) continue
|
|
79
|
+
inDay++
|
|
80
|
+
for (const x of s.sessions) {
|
|
81
|
+
if (seen.has(x.id)) continue
|
|
82
|
+
seen.add(x.id)
|
|
83
|
+
slot(x.app).ids.add(x.id)
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
for (let i = 0; i + 1 < ordered.length; i++) {
|
|
87
|
+
const a = ordered[i]
|
|
88
|
+
const from = Math.max(a.at, start)
|
|
89
|
+
const to = Math.min(ordered[i + 1].at, a.at + maxGapMs, end)
|
|
90
|
+
if (!(to > from)) continue
|
|
91
|
+
for (const app of new Set(a.sessions.filter((x) => x.busy).map((x) => x.app))) slot(app).active_ms += to - from
|
|
92
|
+
}
|
|
93
|
+
return {
|
|
94
|
+
day,
|
|
95
|
+
utc_offset_minutes: utcOffsetMinutes,
|
|
96
|
+
samples: inDay,
|
|
97
|
+
apps: [...apps.values()]
|
|
98
|
+
.sort((a, b) => (a.app < b.app ? -1 : 1))
|
|
99
|
+
.map((a) => ({ app: a.app, live_sessions: a.ids.size, active_ms: a.active_ms, active_hours: Math.round((a.active_ms / HOUR_MS) * 100) / 100 })),
|
|
100
|
+
}
|
|
101
|
+
}
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The read-only adapter contract.
|
|
3
|
+
*
|
|
4
|
+
* An adapter is a reader for one source of session status. It has a `source`
|
|
5
|
+
* name and exactly two methods:
|
|
6
|
+
*
|
|
7
|
+
* list() -> [{ session: { source, native_id, incarnation? }, scope? }] | null
|
|
8
|
+
* (null: the source cannot be listed right now)
|
|
9
|
+
* read(session, now) -> a read, below
|
|
10
|
+
*
|
|
11
|
+
* There is no send method and no way to add one: `sealAdapter` accepts only a
|
|
12
|
+
* plain object whose own keys are `source`, `list` and `read`, and hands the
|
|
13
|
+
* reconciler a frozen view with nothing else on it. An adapter that carries a
|
|
14
|
+
* `send`, `post`, `notify` or any other member is refused, not trimmed, so the
|
|
15
|
+
* mistake is visible where it is made.
|
|
16
|
+
*
|
|
17
|
+
* A read is the data the model's `planRead` consumes:
|
|
18
|
+
*
|
|
19
|
+
* { listed?, outcome?: 'ok' | 'no_report' | 'error' | 'blocked',
|
|
20
|
+
* error_code?, not_read_reason?, source_now?, remote_without_clock?,
|
|
21
|
+
* report?: { state, last_report_at, declared_via, next?, declared_blocked_on?,
|
|
22
|
+
* decision?, decision_basis?, owner_named?, seed_ref?, time_trusted?,
|
|
23
|
+
* later_unfootered_messages? },
|
|
24
|
+
* native?: { turn_in_flight?, busy_background?, pending?, events? } }
|
|
25
|
+
*
|
|
26
|
+
* The adapter reports what it found: `source`, the time of the report
|
|
27
|
+
* (`last_report_at`) and its `state`. It never grades. The reconciler stamps
|
|
28
|
+
* `checked_at` and computes `freshness` (grade.js), so an adapter cannot
|
|
29
|
+
* vouch for its own report's age.
|
|
30
|
+
*
|
|
31
|
+
* `validateRead` shape-checks whatever an adapter returns. A read that does
|
|
32
|
+
* not have the shape, or an adapter that throws, becomes an `error` read with
|
|
33
|
+
* a fixed code. It is never turned into `no_report`, and never into a state.
|
|
34
|
+
*/
|
|
35
|
+
|
|
36
|
+
export class AdapterContractError extends Error {
|
|
37
|
+
constructor(message) {
|
|
38
|
+
super(message)
|
|
39
|
+
this.name = 'AdapterContractError'
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export const ADAPTER_MEMBERS = Object.freeze(['source', 'list', 'read'])
|
|
44
|
+
|
|
45
|
+
const MAX_STRING = 2000
|
|
46
|
+
const REPORT_STATES = new Set(['running', 'idle', 'blocked', 'stalled', 'done', 'unknown'])
|
|
47
|
+
const DECLARED_VIA = new Set(['marker', 'transcript', 'api', 'hook'])
|
|
48
|
+
const DECISION_BASIS = new Set(['none', 'stated', 'possibly_inherited'])
|
|
49
|
+
const OUTCOMES = new Set(['ok', 'no_report', 'error', 'blocked'])
|
|
50
|
+
const CODE_RE = /^[a-z][a-z0-9_]{0,39}$/
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* A source id: lowercase letters, digits, `_` and `-`, starting with a letter,
|
|
54
|
+
* at most 64 characters. It names an adapter in ledger records; it is not an
|
|
55
|
+
* MCP server name.
|
|
56
|
+
*/
|
|
57
|
+
export function validSourceName(name) {
|
|
58
|
+
return typeof name === 'string' && name.length >= 1 && name.length <= 64 && /^[a-z][a-z0-9_-]*$/.test(name)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function isPlain(v) {
|
|
62
|
+
if (v === null || typeof v !== 'object' || Array.isArray(v)) return false
|
|
63
|
+
const proto = Object.getPrototypeOf(v)
|
|
64
|
+
return proto === Object.prototype || proto === null
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Accept an adapter only if it is the read-only shape, and return a frozen
|
|
69
|
+
* view that carries `source`, `list` and `read` and nothing else.
|
|
70
|
+
*/
|
|
71
|
+
export function sealAdapter(adapter) {
|
|
72
|
+
if (!isPlain(adapter)) throw new AdapterContractError('adapter must be a plain object')
|
|
73
|
+
const extra = Reflect.ownKeys(adapter).filter((k) => !ADAPTER_MEMBERS.includes(k))
|
|
74
|
+
if (extra.length) {
|
|
75
|
+
throw new AdapterContractError(`adapter exposes ${extra.map(String).join(', ')}; the contract is read-only (${ADAPTER_MEMBERS.join(', ')})`)
|
|
76
|
+
}
|
|
77
|
+
for (const k of ADAPTER_MEMBERS) {
|
|
78
|
+
const d = Object.getOwnPropertyDescriptor(adapter, k)
|
|
79
|
+
if (!d || 'get' in d || 'set' in d) throw new AdapterContractError(`adapter.${k} must be a plain data member`)
|
|
80
|
+
}
|
|
81
|
+
if (!validSourceName(adapter.source)) {
|
|
82
|
+
throw new AdapterContractError('adapter.source must be a short lowercase name')
|
|
83
|
+
}
|
|
84
|
+
if (typeof adapter.list !== 'function' || typeof adapter.read !== 'function') {
|
|
85
|
+
throw new AdapterContractError('adapter.list and adapter.read must be functions')
|
|
86
|
+
}
|
|
87
|
+
const { source, list, read } = adapter
|
|
88
|
+
return Object.freeze({ source, list: () => list.call(adapter), read: (session, now) => read.call(adapter, session, now) })
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function str(v) {
|
|
92
|
+
return typeof v === 'string' && v.length <= MAX_STRING
|
|
93
|
+
}
|
|
94
|
+
function strOrNull(v) {
|
|
95
|
+
return v === undefined || v === null || str(v)
|
|
96
|
+
}
|
|
97
|
+
function onlyKeys(obj, allowed) {
|
|
98
|
+
return Object.keys(obj).every((k) => allowed.includes(k))
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const REPORT_FIELDS = ['state', 'last_report_at', 'declared_via', 'next', 'declared_blocked_on', 'decision', 'decision_basis', 'owner_named', 'seed_ref', 'time_trusted', 'later_unfootered_messages']
|
|
102
|
+
|
|
103
|
+
function validReport(r) {
|
|
104
|
+
if (!isPlain(r) || !onlyKeys(r, REPORT_FIELDS)) return false
|
|
105
|
+
if (!REPORT_STATES.has(r.state)) return false
|
|
106
|
+
if (!DECLARED_VIA.has(r.declared_via)) return false
|
|
107
|
+
if (!Number.isSafeInteger(r.last_report_at) || r.last_report_at < 0) return false
|
|
108
|
+
if (!strOrNull(r.next) || !strOrNull(r.declared_blocked_on) || !strOrNull(r.decision) || !strOrNull(r.owner_named)) return false
|
|
109
|
+
if (r.decision_basis !== undefined && !DECISION_BASIS.has(r.decision_basis)) return false
|
|
110
|
+
if (r.seed_ref !== undefined && r.seed_ref !== null && !str(r.seed_ref) && !isPlain(r.seed_ref)) return false
|
|
111
|
+
if (r.time_trusted !== undefined && typeof r.time_trusted !== 'boolean') return false
|
|
112
|
+
if (r.later_unfootered_messages !== undefined && typeof r.later_unfootered_messages !== 'boolean') return false
|
|
113
|
+
return true
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const NATIVE_FIELDS = ['turn_in_flight', 'busy_background', 'pending', 'events']
|
|
117
|
+
|
|
118
|
+
function validNative(n) {
|
|
119
|
+
if (!isPlain(n) || !onlyKeys(n, NATIVE_FIELDS)) return false
|
|
120
|
+
for (const k of ['turn_in_flight', 'busy_background']) if (n[k] !== undefined && typeof n[k] !== 'boolean') return false
|
|
121
|
+
if (n.pending !== undefined) {
|
|
122
|
+
if (!Array.isArray(n.pending)) return false
|
|
123
|
+
for (const p of n.pending) {
|
|
124
|
+
if (!isPlain(p) || !onlyKeys(p, ['ref', 'raised_at', 'deadline']) || !str(p.ref)) return false
|
|
125
|
+
for (const k of ['raised_at', 'deadline']) if (p[k] != null && !Number.isFinite(p[k])) return false
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (n.events !== undefined) {
|
|
129
|
+
if (!Array.isArray(n.events)) return false
|
|
130
|
+
for (const e of n.events) {
|
|
131
|
+
if (!isPlain(e) || !onlyKeys(e, ['id', 'basis', 'ref', 'activity_at']) || !str(e.basis)) return false
|
|
132
|
+
if (e.id != null && !(typeof e.id === 'string' || Number.isSafeInteger(e.id))) return false
|
|
133
|
+
if (e.ref != null && !str(e.ref)) return false
|
|
134
|
+
if (e.activity_at != null && !Number.isFinite(e.activity_at)) return false
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return true
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
const SHAPE_ERROR = Object.freeze({ outcome: 'error', error_code: 'adapter_shape' })
|
|
141
|
+
const FAULT_ERROR = Object.freeze({ outcome: 'error', error_code: 'adapter_fault' })
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* Shape-check one read. Returns a read the model can plan from: the read
|
|
145
|
+
* itself if it is well-formed, else an `error` read with a fixed code. The
|
|
146
|
+
* code is never taken from the offending read, so nothing it carried can
|
|
147
|
+
* reach the ledger through the error path.
|
|
148
|
+
*/
|
|
149
|
+
export function validateRead(read) {
|
|
150
|
+
if (!isPlain(read)) return SHAPE_ERROR
|
|
151
|
+
if (!onlyKeys(read, ['listed', 'outcome', 'error_code', 'not_read_reason', 'source_now', 'remote_without_clock', 'report', 'native'])) return SHAPE_ERROR
|
|
152
|
+
if (read.listed !== undefined && typeof read.listed !== 'boolean') return SHAPE_ERROR
|
|
153
|
+
if (read.outcome !== undefined && !OUTCOMES.has(read.outcome)) return SHAPE_ERROR
|
|
154
|
+
for (const k of ['error_code', 'not_read_reason']) {
|
|
155
|
+
if (read[k] !== undefined && read[k] !== null && !(typeof read[k] === 'string' && CODE_RE.test(read[k]))) return SHAPE_ERROR
|
|
156
|
+
}
|
|
157
|
+
if (read.source_now != null && !Number.isFinite(read.source_now)) return SHAPE_ERROR
|
|
158
|
+
if (read.remote_without_clock !== undefined && typeof read.remote_without_clock !== 'boolean') return SHAPE_ERROR
|
|
159
|
+
if (read.report !== undefined && read.report !== null && !validReport(read.report)) return SHAPE_ERROR
|
|
160
|
+
if (read.native !== undefined && read.native !== null && !validNative(read.native)) return SHAPE_ERROR
|
|
161
|
+
if (read.outcome === 'ok' && !read.report && read.listed !== false) return SHAPE_ERROR
|
|
162
|
+
if (read.report && read.outcome !== 'ok') return SHAPE_ERROR
|
|
163
|
+
return read
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** Shape-check a listing. Returns the list, or null when it is not a listing. */
|
|
167
|
+
export function validateList(list, source) {
|
|
168
|
+
if (list === null) return null
|
|
169
|
+
if (!Array.isArray(list)) return null
|
|
170
|
+
const out = []
|
|
171
|
+
for (const e of list) {
|
|
172
|
+
if (!isPlain(e) || !onlyKeys(e, ['session', 'scope']) || !isPlain(e.session)) return null
|
|
173
|
+
const s = e.session
|
|
174
|
+
if (!onlyKeys(s, ['source', 'native_id', 'incarnation'])) return null
|
|
175
|
+
if (s.source !== source || !str(s.native_id) || s.native_id === '') return null
|
|
176
|
+
if (s.incarnation != null && !str(s.incarnation) && !Number.isSafeInteger(s.incarnation)) return null
|
|
177
|
+
if (e.scope != null && !str(e.scope)) return null
|
|
178
|
+
out.push({ session: { source: s.source, native_id: s.native_id, incarnation: s.incarnation ?? null }, scope: e.scope ?? null })
|
|
179
|
+
}
|
|
180
|
+
return out
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Call an adapter's `read`, turning a throw or a malformed answer into an `error` read. */
|
|
184
|
+
export function safeRead(sealed, session, now) {
|
|
185
|
+
try {
|
|
186
|
+
return validateRead(sealed.read(session, now))
|
|
187
|
+
} catch {
|
|
188
|
+
return FAULT_ERROR
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Call an adapter's `list`; a throw or a malformed answer is `null`, a source that cannot be listed. */
|
|
193
|
+
export function safeList(sealed) {
|
|
194
|
+
try {
|
|
195
|
+
return validateList(sealed.list(), sealed.source)
|
|
196
|
+
} catch {
|
|
197
|
+
return null
|
|
198
|
+
}
|
|
199
|
+
}
|
|
@@ -0,0 +1,239 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Turning one adapter read into ledger records: an optional `report`, one
|
|
3
|
+
* `check`, and `activity` records for native evidence. The read itself is
|
|
4
|
+
* data the caller supplies; nothing here
|
|
5
|
+
* performs one.
|
|
6
|
+
*
|
|
7
|
+
* Planner functions in this directory are generators. They yield operations
|
|
8
|
+
* (`{ op: 'append', record, at }` or `{ op: 'send', effect }`) and receive the
|
|
9
|
+
* result of each; `run()` in reconciler.js is the driver. A crash is a driver
|
|
10
|
+
* that stops part-way.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { sourceCaps } from './config.js'
|
|
14
|
+
import { gradeRead } from './grade.js'
|
|
15
|
+
import { H } from './hash.js'
|
|
16
|
+
import { activityEventKey, activityStateKey, reportKey, sessionKey, systemKey } from './keys.js'
|
|
17
|
+
|
|
18
|
+
function sameEvent(prior, sessionEnv, e) {
|
|
19
|
+
if (!prior) return false
|
|
20
|
+
const b = prior.body
|
|
21
|
+
return (
|
|
22
|
+
prior.kind === 'activity' &&
|
|
23
|
+
prior.session?.source === sessionEnv.source &&
|
|
24
|
+
prior.session?.native_id === sessionEnv.native_id &&
|
|
25
|
+
(prior.session?.incarnation ?? null) === (sessionEnv.incarnation ?? null) &&
|
|
26
|
+
b.basis === e.basis &&
|
|
27
|
+
(b.ref ?? null) === (e.ref ?? null) &&
|
|
28
|
+
(b.activity_at ?? null) === (e.activity_at ?? null)
|
|
29
|
+
)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function put(record, at) {
|
|
33
|
+
return { op: 'append', record, at }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const RELAYED = new Set(['api', 'hook'])
|
|
37
|
+
|
|
38
|
+
function reportFields(rep) {
|
|
39
|
+
return {
|
|
40
|
+
state: rep.state,
|
|
41
|
+
next: rep.next ?? null,
|
|
42
|
+
declared_blocked_on: rep.declared_blocked_on ?? null,
|
|
43
|
+
decision: rep.decision ?? null,
|
|
44
|
+
decision_basis: rep.decision_basis ?? 'none',
|
|
45
|
+
declared_via: rep.declared_via,
|
|
46
|
+
owner_named: rep.owner_named ?? null,
|
|
47
|
+
seed_ref: rep.seed_ref ?? null,
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Plan the records for one read. Returns the check body, the report body (if
|
|
53
|
+
* any) and the native evidence the read carried, for the caller to classify.
|
|
54
|
+
*
|
|
55
|
+
* opts: { key, trigger, session, read, now, tickId, investigationId, scope, readKind }
|
|
56
|
+
*/
|
|
57
|
+
export function* planRead(ctx, opts) {
|
|
58
|
+
const { key, trigger, session, read, now } = opts
|
|
59
|
+
const st = ctx.state
|
|
60
|
+
const P = ctx.policy
|
|
61
|
+
const cfg = st.config
|
|
62
|
+
const caps = sourceCaps(cfg, session.source)
|
|
63
|
+
const sk = sessionKey(session)
|
|
64
|
+
const s = st.sessions.get(sk)
|
|
65
|
+
const listed = read.listed !== false
|
|
66
|
+
const sessionEnv = { source: session.source, native_id: session.native_id, incarnation: session.incarnation ?? null }
|
|
67
|
+
|
|
68
|
+
const body = {
|
|
69
|
+
check_id: key,
|
|
70
|
+
source: session.source,
|
|
71
|
+
checked_at: now,
|
|
72
|
+
trigger,
|
|
73
|
+
outcome: read.outcome ?? 'no_report',
|
|
74
|
+
report_id: null,
|
|
75
|
+
last_report_at: null,
|
|
76
|
+
state: 'none',
|
|
77
|
+
freshness: 'unknown',
|
|
78
|
+
report_age_s: null,
|
|
79
|
+
freshness_reason: null,
|
|
80
|
+
config_ref: st.configRef,
|
|
81
|
+
error_code: null,
|
|
82
|
+
not_read_reason: null,
|
|
83
|
+
// DESIGN-GAP: the check body has no way to say a session is unlisted,
|
|
84
|
+
// yet `dropped_from_list` must be derivable from the ledger. Added field.
|
|
85
|
+
listed,
|
|
86
|
+
scope: opts.scope ?? null,
|
|
87
|
+
// DESIGN-GAP: activity records are written only for states seen, so the
|
|
88
|
+
// ledger cannot tell "not busy" from "this read carried no native state".
|
|
89
|
+
// Added field.
|
|
90
|
+
native_available: false,
|
|
91
|
+
read_kind: opts.readKind ?? 'report',
|
|
92
|
+
// Added fields: what the grading depended on besides the report and the
|
|
93
|
+
// check time, so a reader can re-grade the check from the ledger alone.
|
|
94
|
+
source_now: read.source_now ?? null,
|
|
95
|
+
remote_without_clock: Boolean(read.remote_without_clock),
|
|
96
|
+
}
|
|
97
|
+
let reportDraft = null
|
|
98
|
+
let regressed = false
|
|
99
|
+
|
|
100
|
+
if (!listed) {
|
|
101
|
+
body.outcome = 'no_report'
|
|
102
|
+
// DESIGN-GAP: no `freshness_reason` value exists for a session that is no
|
|
103
|
+
// longer listed. Added value.
|
|
104
|
+
body.freshness_reason = 'not_listed'
|
|
105
|
+
} else if (body.outcome === 'ok' && read.report && opts.readKind !== 'activity') {
|
|
106
|
+
const rep = read.report
|
|
107
|
+
body.state = rep.state
|
|
108
|
+
if (rep.time_trusted === false) {
|
|
109
|
+
// The adapter rules: no report record; the check says why.
|
|
110
|
+
body.freshness_reason = 'time_untrusted'
|
|
111
|
+
} else {
|
|
112
|
+
const fields = reportFields(rep)
|
|
113
|
+
const fieldsHash = H(fields)
|
|
114
|
+
const rid = reportKey(session, rep.last_report_at, fieldsHash)
|
|
115
|
+
body.report_id = rid
|
|
116
|
+
body.last_report_at = rep.last_report_at
|
|
117
|
+
const relayed = RELAYED.has(rep.declared_via)
|
|
118
|
+
if (!st.index.has(rid)) {
|
|
119
|
+
const rbody = {
|
|
120
|
+
report_id: rid,
|
|
121
|
+
source: session.source,
|
|
122
|
+
last_report_at: rep.last_report_at,
|
|
123
|
+
report_time_basis: caps.report_time_basis,
|
|
124
|
+
declared_via: rep.declared_via,
|
|
125
|
+
key_basis: `${session.source}:${caps.report_time_basis}+fields`,
|
|
126
|
+
state: rep.state,
|
|
127
|
+
next: fields.next,
|
|
128
|
+
declared_blocked_on: fields.declared_blocked_on,
|
|
129
|
+
decision: fields.decision,
|
|
130
|
+
decision_basis: fields.decision_basis,
|
|
131
|
+
block_fingerprint: null,
|
|
132
|
+
later_unfootered_messages: Boolean(rep.later_unfootered_messages),
|
|
133
|
+
evidence_class: relayed ? 'E5' : 'E2',
|
|
134
|
+
locator: null,
|
|
135
|
+
fields_hash: fieldsHash,
|
|
136
|
+
// DESIGN-GAP: the owner-block rule needs the name in the OWNER slot
|
|
137
|
+
// and the seed origin needs the seed's scope, session and write
|
|
138
|
+
// time, but the report body stores neither, so neither origin could
|
|
139
|
+
// be derived from the ledger alone. Added fields.
|
|
140
|
+
owner_named: fields.owner_named,
|
|
141
|
+
seed_ref: fields.seed_ref,
|
|
142
|
+
}
|
|
143
|
+
rbody.block_fingerprint = P.blockFingerprint(rbody)
|
|
144
|
+
reportDraft = { kind: 'report', id: rid, session: sessionEnv, body: rbody }
|
|
145
|
+
}
|
|
146
|
+
if (!relayed && s?.latestAuthored && s.latestAuthored !== rid) {
|
|
147
|
+
const latest = st.reports.get(s.latestAuthored)
|
|
148
|
+
if (latest && latest.body.last_report_at > rep.last_report_at) regressed = true
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const previousCheckedAt = s?.cur && s.cur.reportId === body.report_id ? s.cur.checkedAt : null
|
|
154
|
+
if (opts.readKind !== 'activity' && listed) {
|
|
155
|
+
const g = gradeRead(
|
|
156
|
+
{
|
|
157
|
+
outcome: body.outcome,
|
|
158
|
+
state: body.state,
|
|
159
|
+
declaredVia: read.report?.declared_via,
|
|
160
|
+
timeTrusted: read.report?.time_trusted,
|
|
161
|
+
lastReportAt: body.last_report_at,
|
|
162
|
+
checkedAt: now,
|
|
163
|
+
previousCheckedAt,
|
|
164
|
+
sourceNow: read.source_now ?? null,
|
|
165
|
+
remoteWithoutClock: Boolean(read.remote_without_clock),
|
|
166
|
+
errorCode: read.error_code,
|
|
167
|
+
notReadReason: read.not_read_reason,
|
|
168
|
+
reason: body.freshness_reason ?? undefined,
|
|
169
|
+
},
|
|
170
|
+
cfg,
|
|
171
|
+
P.reportAge,
|
|
172
|
+
)
|
|
173
|
+
body.freshness = g.freshness
|
|
174
|
+
body.freshness_reason = g.reason ?? body.freshness_reason
|
|
175
|
+
body.report_age_s = g.ageS
|
|
176
|
+
body.error_code = g.errorCode
|
|
177
|
+
body.not_read_reason = g.notReadReason
|
|
178
|
+
if (g.errorCode === 'clock_skew') {
|
|
179
|
+
// A skewed clock makes the read's outcome `error: clock_skew`, whatever
|
|
180
|
+
// the read found (a status line or none), so it counts as an errored
|
|
181
|
+
// check; a line whose time cannot be trusted writes no report record,
|
|
182
|
+
// and no native state is taken from the read.
|
|
183
|
+
body.outcome = 'error'
|
|
184
|
+
body.report_id = null
|
|
185
|
+
reportDraft = null
|
|
186
|
+
regressed = false
|
|
187
|
+
}
|
|
188
|
+
} else if (body.outcome === 'error') {
|
|
189
|
+
body.freshness = 'error'
|
|
190
|
+
body.error_code = read.error_code ?? 'adapter_fault'
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const native = read.native && (body.outcome === 'ok' || body.outcome === 'no_report') ? read.native : null
|
|
194
|
+
body.native_available = native != null
|
|
195
|
+
|
|
196
|
+
if (reportDraft) yield put(reportDraft, now)
|
|
197
|
+
if (regressed) {
|
|
198
|
+
yield put({ kind: 'system', id: systemKey('report_regressed', [sk, body.report_id]), session: sessionEnv, body: { event: 'report_regressed', detail: { ids: [sk, body.report_id] } } }, now)
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// DESIGN-GAP: one read becomes several records (report, check, activity)
|
|
202
|
+
// and the rules give no atomicity rule (README, DESIGN-GAP choices). Written check-first, a crash
|
|
203
|
+
// between the check and its activity records leaves a partial observation
|
|
204
|
+
// that a resumed tick either keeps (if it reuses the check, the remaining
|
|
205
|
+
// observations are lost) or collides with (if it re-reads, the activity
|
|
206
|
+
// keys H(check_id, basis, ref) repeat with a different `observed_at`). The
|
|
207
|
+
// model writes the activity records first and the check LAST, as the
|
|
208
|
+
// commit point of the read; a re-read skips activity keys already written.
|
|
209
|
+
if (native) {
|
|
210
|
+
const state = (basis, ref, extra = {}) => {
|
|
211
|
+
const id = activityStateKey(key, basis, ref)
|
|
212
|
+
const prior = st.index.get(id)
|
|
213
|
+
// Written by a crashed run of this same read: same check, basis and ref.
|
|
214
|
+
if (prior && prior.body.check_id === key && prior.body.basis === basis && (prior.body.ref ?? null) === (ref ?? null)) return null
|
|
215
|
+
return put({ kind: 'activity', id, session: sessionEnv, body: { check_id: key, basis, ref: ref ?? null, activity_at: null, evidence_class: 'E1', observed_at: now, ...extra } }, now)
|
|
216
|
+
}
|
|
217
|
+
const ops = []
|
|
218
|
+
if (native.turn_in_flight) ops.push(state('busy_now_turn', null))
|
|
219
|
+
if (native.busy_background) ops.push(state('busy_now_background', null))
|
|
220
|
+
for (const p of native.pending ?? []) {
|
|
221
|
+
// DESIGN-GAP: the surfacing order sorts by deadline and the lapse rule
|
|
222
|
+
// needs the prompt's time, but the activity body carries neither.
|
|
223
|
+
// Added fields.
|
|
224
|
+
ops.push(state('pending_permission', p.ref, { raised_at: p.raised_at ?? null, deadline: p.deadline ?? null }))
|
|
225
|
+
}
|
|
226
|
+
for (const op of ops) if (op) yield op
|
|
227
|
+
for (const e of native.events ?? []) {
|
|
228
|
+
const id = activityEventKey({ hostEventId: e.id, session, basis: e.basis, activityAt: e.activity_at })
|
|
229
|
+
// The same event seen again at a later read is skipped, but only when
|
|
230
|
+
// it IS the same event: a different event under the same key goes on
|
|
231
|
+
// to append(), which records the collision as an idempotency_conflict
|
|
232
|
+
// instead of dropping it silently.
|
|
233
|
+
if (sameEvent(st.index.get(id), sessionEnv, e)) continue
|
|
234
|
+
yield put({ kind: 'activity', id, session: sessionEnv, body: { check_id: key, basis: e.basis, ref: e.ref ?? null, activity_at: e.activity_at ?? null, evidence_class: 'E1', observed_at: now } }, now)
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
yield put({ kind: 'check', id: key, session: sessionEnv, refs: { tick: opts.tickId ?? null, report: body.report_id, investigation: opts.investigationId ?? null }, body }, now)
|
|
238
|
+
return { body, native, report: read.report ?? null }
|
|
239
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Configuration for the session-freshness model: starting values
|
|
3
|
+
* expressed in seconds, plus the source capabilities the model needs to know.
|
|
4
|
+
*
|
|
5
|
+
* Every value here is a starting value, not a measurement. Pure data.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
const MIN = 60
|
|
9
|
+
const HOUR = 3600
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_CONFIG = Object.freeze({
|
|
12
|
+
// The name an `OWNER:` slot must carry for a blocked line to be an owner
|
|
13
|
+
// block. Deliberately unset: a deployment supplies it.
|
|
14
|
+
owner_name: null,
|
|
15
|
+
cadence_minutes: 30,
|
|
16
|
+
per_source: Object.freeze({}),
|
|
17
|
+
investigation_budget_per_tick: 3,
|
|
18
|
+
recheck_budget_per_tick: 3,
|
|
19
|
+
freshness: Object.freeze({
|
|
20
|
+
running: Object.freeze({ fresh_max_s: 20 * MIN, stale_after_s: 45 * MIN }),
|
|
21
|
+
unknown: Object.freeze({ fresh_max_s: 20 * MIN, stale_after_s: 45 * MIN }),
|
|
22
|
+
blocked: Object.freeze({ fresh_max_s: 60 * MIN, stale_after_s: 4 * HOUR }),
|
|
23
|
+
stalled: Object.freeze({ fresh_max_s: 60 * MIN, stale_after_s: 4 * HOUR }),
|
|
24
|
+
idle: Object.freeze({ fresh_max_s: 4 * HOUR, stale_after_s: 24 * HOUR }),
|
|
25
|
+
done: Object.freeze({ fresh_max_s: 4 * HOUR, stale_after_s: 24 * HOUR }),
|
|
26
|
+
}),
|
|
27
|
+
max_source_skew_seconds: 120,
|
|
28
|
+
investigation: Object.freeze({
|
|
29
|
+
activity_window_minutes: 20,
|
|
30
|
+
background_wait_max_minutes: 90,
|
|
31
|
+
}),
|
|
32
|
+
surface: Object.freeze({
|
|
33
|
+
reminder_after_minutes: Object.freeze([60, 180]),
|
|
34
|
+
item_time_limit_hours: 8,
|
|
35
|
+
max_presentations: 3,
|
|
36
|
+
// An owner's deferral: the longest one accepted, and how many an item
|
|
37
|
+
// may have in one episode. One past either is refused and recorded.
|
|
38
|
+
defer_max_minutes: 24 * 60,
|
|
39
|
+
defer_max_count: 3,
|
|
40
|
+
}),
|
|
41
|
+
// The files a consumer exchanges with the reconciler (exchange.js). Every
|
|
42
|
+
// input is untrusted: these bound what one tick will read from it.
|
|
43
|
+
exchange: Object.freeze({
|
|
44
|
+
max_file_bytes: 1024 * 1024,
|
|
45
|
+
max_line_bytes: 1024,
|
|
46
|
+
max_new_lines_per_tick: 200,
|
|
47
|
+
max_rejects_per_tick: 20,
|
|
48
|
+
text_field_max: 240,
|
|
49
|
+
digest_max_items: 12,
|
|
50
|
+
// Echo items one item may have per tick and per episode. Past the second,
|
|
51
|
+
// further lines are not judged: one counted record and one echo say so.
|
|
52
|
+
max_echoes_per_item_per_tick: 5,
|
|
53
|
+
max_echoes_per_episode: 50,
|
|
54
|
+
}),
|
|
55
|
+
// What each source's adapter can do. `native_in_read`: the report read also
|
|
56
|
+
// returns native state (busy, prompts, events). `activity_read`: a separate
|
|
57
|
+
// native-activity read exists. `scope`: the source gives a session's
|
|
58
|
+
// working scope. `can_confirm_gone`: a missing session may be called gone.
|
|
59
|
+
sources: Object.freeze({
|
|
60
|
+
chroxy: Object.freeze({ native_in_read: true, activity_read: false, scope: true, can_confirm_gone: true, report_time_basis: 'changed_at' }),
|
|
61
|
+
codex: Object.freeze({ native_in_read: false, activity_read: true, scope: true, can_confirm_gone: true, report_time_basis: 'authored_at' }),
|
|
62
|
+
'claude-desktop': Object.freeze({ native_in_read: false, activity_read: false, scope: false, can_confirm_gone: true, report_time_basis: 'authored_at' }),
|
|
63
|
+
}),
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
/** Cadence of one source in seconds. */
|
|
67
|
+
export function cadenceSeconds(config, source) {
|
|
68
|
+
const m = config.per_source?.[source] ?? config.cadence_minutes
|
|
69
|
+
return m * MIN
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Capabilities of one source; unknown sources have none. */
|
|
73
|
+
export function sourceCaps(config, source) {
|
|
74
|
+
return config.sources?.[source] ?? { native_in_read: false, activity_read: false, scope: false, can_confirm_gone: false, report_time_basis: 'none' }
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** A shallow-merged copy of the defaults with overrides, for tests and callers. */
|
|
78
|
+
export function makeConfig(overrides = {}) {
|
|
79
|
+
const base = structuredClone(DEFAULT_CONFIG)
|
|
80
|
+
for (const [k, v] of Object.entries(overrides)) {
|
|
81
|
+
if (v && typeof v === 'object' && !Array.isArray(v) && base[k] && typeof base[k] === 'object') {
|
|
82
|
+
base[k] = { ...base[k], ...structuredClone(v) }
|
|
83
|
+
} else {
|
|
84
|
+
base[k] = structuredClone(v)
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return base
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** The surface and exchange values of a configuration, with the defaults for a configuration stored before they existed. */
|
|
91
|
+
export function exchangeLimits(config) {
|
|
92
|
+
return { ...DEFAULT_CONFIG.exchange, ...(config?.exchange ?? {}) }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function deferLimits(config) {
|
|
96
|
+
const s = { ...DEFAULT_CONFIG.surface, ...(config?.surface ?? {}) }
|
|
97
|
+
return { maxMs: s.defer_max_minutes * MIN * 1000, maxCount: s.defer_max_count }
|
|
98
|
+
}
|