@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,139 @@
1
+ /**
2
+ * What build is running, for the freshness runner's tick records.
3
+ *
4
+ * Three facts go into every tick record, all read from disk at run time:
5
+ * - the commit of the build, from `build-info.json` stamped into the
6
+ * installed package by `stamp.js` at install time (nothing here asks git);
7
+ * - the installed daemon package's version, from the package's own
8
+ * `package.json` (never from a module imported at startup);
9
+ * - the state file's schema version (`version`), read from the file the
10
+ * runner is pointed at; null when it cannot be read.
11
+ *
12
+ * A pinned install is a copy of the package under a `node_modules`
13
+ * directory. A development checkout is any other location, and switching
14
+ * branches there changes what runs, so the runner refuses it unless asked.
15
+ */
16
+
17
+ import fs from 'node:fs'
18
+ import path from 'node:path'
19
+
20
+ export const BUILD_INFO_FILE = 'build-info.json'
21
+ // Built from parts: the image smoke script reads any quoted scope-slash string as an import specifier.
22
+ export const DAEMON_PACKAGE_NAME = ['@chroxy', 'server'].join('/')
23
+ const COMMIT_RE = /^[0-9a-f]{40}$/
24
+ const VERSION_RE = /^[0-9]{1,6}\.[0-9]{1,6}\.[0-9]{1,6}(-[0-9A-Za-z.-]{1,40})?$/
25
+ const MAX_INFO_BYTES = 4096
26
+ const MAX_STATE_BYTES = 64 * 1024 * 1024
27
+
28
+ export class BuildError extends Error {
29
+ constructor(code, message) {
30
+ super(message)
31
+ this.name = 'BuildError'
32
+ this.code = code
33
+ }
34
+ }
35
+
36
+ /** Is `s` a full 40-character lowercase commit id? */
37
+ export function isCommit(s) {
38
+ return typeof s === 'string' && COMMIT_RE.test(s)
39
+ }
40
+
41
+ function readSmallJson(file, what) {
42
+ let text
43
+ try {
44
+ const st = fs.statSync(file)
45
+ if (!st.isFile() || st.size > MAX_INFO_BYTES) throw new BuildError('build_unreadable', `${what} is not a small regular file`)
46
+ text = fs.readFileSync(file, 'utf8')
47
+ } catch (err) {
48
+ if (err instanceof BuildError) throw err
49
+ if (err?.code === 'ENOENT') return null
50
+ throw new BuildError('build_unreadable', `${what} cannot be read`)
51
+ }
52
+ try {
53
+ const v = JSON.parse(text)
54
+ if (v === null || typeof v !== 'object' || Array.isArray(v)) throw new Error('shape')
55
+ return v
56
+ } catch {
57
+ throw new BuildError('build_unreadable', `${what} is not a JSON object`)
58
+ }
59
+ }
60
+
61
+ /** The nearest `.git` entry at or above `dir`, or null when there is none. */
62
+ function findGitAtOrAbove(dir) {
63
+ for (let cur = dir; ; cur = path.dirname(cur)) {
64
+ const git = path.join(cur, '.git')
65
+ if (fs.existsSync(git)) return git
66
+ if (path.dirname(cur) === cur) return null
67
+ }
68
+ }
69
+
70
+ /** The `development_checkout` refusal; names the `.git` when a pinned install was refused because of one. */
71
+ export function checkoutRefusal(git, lead) {
72
+ return new BuildError('development_checkout', git === null ? lead : `${lead}: the pinned install sits inside a git checkout (${git}); install it outside any git tree`)
73
+ }
74
+
75
+ /**
76
+ * Classify the package at `packageRoot` once: `{ kind, git }`, where `git` is the
77
+ * `.git` that made a node_modules/@chroxy/server install a checkout, else null.
78
+ */
79
+ export function classifyInstall(packageRoot) {
80
+ const real = fs.realpathSync(packageRoot)
81
+ const tail = real.split(path.sep).slice(-3)
82
+ if (tail.join('/') !== `node_modules/${DAEMON_PACKAGE_NAME}`) return { kind: 'checkout', git: null }
83
+ const git = findGitAtOrAbove(real)
84
+ return git !== null ? { kind: 'checkout', git } : { kind: 'pinned', git: null }
85
+ }
86
+
87
+ /**
88
+ * `pinned` when the real path of the package ends in `node_modules/@chroxy/server`
89
+ * and no `.git` entry exists at or above it; otherwise `checkout`. A workspace
90
+ * link into a checkout resolves out of `node_modules` and so reads `checkout`.
91
+ */
92
+ export function installKind(packageRoot) {
93
+ return classifyInstall(packageRoot).kind
94
+ }
95
+
96
+ /**
97
+ * Read the build facts of the package at `packageRoot`. Throws `BuildError`
98
+ * unless the build is a stamped pinned install; `allowCheckout` lets an
99
+ * unstamped development checkout through, recorded with `commit: null`.
100
+ *
101
+ * @param {string} packageRoot the directory holding the daemon package's package.json
102
+ * @param {{ allowCheckout?: boolean }} [opts]
103
+ * @returns {{ install: 'pinned'|'checkout', commit: string|null, daemon_version: string }}
104
+ */
105
+ export function readBuild(packageRoot, { allowCheckout = false } = {}) {
106
+ const pkg = readSmallJson(path.join(packageRoot, 'package.json'), 'package.json')
107
+ if (!pkg || pkg.name !== DAEMON_PACKAGE_NAME) throw new BuildError('not_daemon_package', `${packageRoot} is not the ${DAEMON_PACKAGE_NAME} package`)
108
+ if (typeof pkg.version !== 'string' || !VERSION_RE.test(pkg.version)) throw new BuildError('bad_version', 'the installed package has no readable version')
109
+ const { kind: install, git } = classifyInstall(packageRoot)
110
+ if (install === 'checkout' && !allowCheckout) {
111
+ throw checkoutRefusal(git, 'this is a development checkout, whose files change with the branch; run a pinned install (see docs/guides/freshness-runner.md) or pass --allow-dev-checkout')
112
+ }
113
+ const info = readSmallJson(path.join(packageRoot, BUILD_INFO_FILE), BUILD_INFO_FILE)
114
+ let commit = null
115
+ if (info !== null) {
116
+ if (!isCommit(info.commit)) throw new BuildError('bad_stamp', `${BUILD_INFO_FILE} does not carry a full commit id`)
117
+ commit = info.commit
118
+ } else if (install === 'pinned') {
119
+ throw new BuildError('unstamped', `the install carries no ${BUILD_INFO_FILE}; stamp it with "freshness stamp" after installing`)
120
+ }
121
+ return { install, commit, daemon_version: pkg.version }
122
+ }
123
+
124
+ /** The state file's schema version (its `version` integer), or null when it cannot be read. */
125
+ export function readStateSchemaVersion(stateFile) {
126
+ try {
127
+ const st = fs.statSync(stateFile)
128
+ if (!st.isFile() || st.size > MAX_STATE_BYTES) return null
129
+ const doc = JSON.parse(fs.readFileSync(stateFile, 'utf8'))
130
+ return doc !== null && typeof doc === 'object' && Number.isSafeInteger(doc.version) ? doc.version : null
131
+ } catch {
132
+ return null
133
+ }
134
+ }
135
+
136
+ /** The `build` object a tick record carries. */
137
+ export function tickBuild(build, stateSchemaVersion) {
138
+ return { commit: build.commit, state_schema_version: stateSchemaVersion, daemon_version: build.daemon_version, install: build.install }
139
+ }
@@ -0,0 +1,105 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Entry point of the freshness runner: `tick` runs one read-only tick and
4
+ * exits, `stamp` records the commit of a pinned install.
5
+ *
6
+ * node <install>/node_modules/@chroxy/server/src/freshness-runner/cli.js tick --ledger-dir <dir> [options]
7
+ * node <install>/node_modules/@chroxy/server/src/freshness-runner/cli.js stamp --commit <sha>
8
+ *
9
+ * It starts no daemon and loads no daemon command. Exit codes: 0 ticked,
10
+ * 1 a source's tick failed (the others ran), 2 refused (usage, build not
11
+ * pinned or not stamped, ledger inside the daemon's state directory or a
12
+ * source, ledger corrupt or fenced), 3 the ledger is held by another reconciler.
13
+ */
14
+
15
+ import { parseArgs } from 'node:util'
16
+ import path from 'node:path'
17
+ import { fileURLToPath } from 'node:url'
18
+ import { BuildError, readBuild } from './build-info.js'
19
+ import { runTick } from './run-tick.js'
20
+ import { stampBuild } from './stamp.js'
21
+ import { LedgerHeldError } from '../freshness/index.js'
22
+ import { isEntryPoint } from '../utils/is-entry-point.js'
23
+
24
+ export const USAGE = [
25
+ 'usage: freshness tick --ledger-dir <dir> [--state-file <file>] [--registry-dir <dir>] [--projects-dir <dir>]',
26
+ ' [--cadence-minutes <n>] [--lease-minutes <n>] [--ledger-id <id>] [--mode read-only] [--allow-dev-checkout]',
27
+ ' freshness stamp --commit <40-hex sha> [--package-dir <dir>] [--force]',
28
+ ].join('\n')
29
+
30
+ /** The daemon package directory this file belongs to. */
31
+ export const PACKAGE_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..')
32
+
33
+ const OPTIONS = {
34
+ 'ledger-dir': { type: 'string' },
35
+ 'state-file': { type: 'string' },
36
+ 'registry-dir': { type: 'string' },
37
+ 'projects-dir': { type: 'string' },
38
+ 'cadence-minutes': { type: 'string' },
39
+ 'lease-minutes': { type: 'string' },
40
+ 'ledger-id': { type: 'string' },
41
+ mode: { type: 'string' },
42
+ 'allow-dev-checkout': { type: 'boolean' },
43
+ commit: { type: 'string' },
44
+ 'package-dir': { type: 'string' },
45
+ force: { type: 'boolean' },
46
+ }
47
+
48
+ function num(name, v) {
49
+ if (v === undefined) return undefined
50
+ if (!/^[0-9]+(\.[0-9]+)?$/.test(v)) throw new TypeError(`${name} must be a number`)
51
+ return Number(v)
52
+ }
53
+
54
+ /**
55
+ * Run the command in `argv` (the arguments after the script). Returns the
56
+ * exit code; writes one JSON line to `out` on success and a message to `err`.
57
+ */
58
+ export function main(argv, { out = (s) => process.stdout.write(s + '\n'), err = (s) => process.stderr.write(s + '\n'), packageRoot = PACKAGE_ROOT, now = Date.now() } = {}) {
59
+ let cmd
60
+ let values
61
+ try {
62
+ const parsed = parseArgs({ args: argv, options: OPTIONS, allowPositionals: true, strict: true })
63
+ ;[cmd] = parsed.positionals
64
+ values = parsed.values
65
+ if (parsed.positionals.length !== 1 || (cmd !== 'tick' && cmd !== 'stamp')) throw new TypeError('expected one command: tick or stamp')
66
+ } catch (e) {
67
+ err(`${e.message}\n${USAGE}`)
68
+ return 2
69
+ }
70
+ try {
71
+ if (cmd === 'stamp') {
72
+ if (values.commit === undefined) throw new TypeError('--commit is required')
73
+ const file = stampBuild(values['package-dir'] ? path.resolve(values['package-dir']) : packageRoot, values.commit, { force: values.force === true })
74
+ out(JSON.stringify({ stamped: file }))
75
+ return 0
76
+ }
77
+ if (values['ledger-dir'] === undefined) throw new TypeError('--ledger-dir is required: the ledger must sit outside the daemon state directory, so it has no default')
78
+ const build = readBuild(packageRoot, { allowCheckout: values['allow-dev-checkout'] === true })
79
+ const summary = runTick({
80
+ ledgerDir: path.resolve(values['ledger-dir']),
81
+ build,
82
+ stateFile: values['state-file'] && path.resolve(values['state-file']),
83
+ registryDir: values['registry-dir'] && path.resolve(values['registry-dir']),
84
+ projectsDir: values['projects-dir'] && path.resolve(values['projects-dir']),
85
+ ledgerId: values['ledger-id'],
86
+ cadenceMinutes: num('--cadence-minutes', values['cadence-minutes']),
87
+ leaseMinutes: num('--lease-minutes', values['lease-minutes']),
88
+ mode: values.mode,
89
+ now,
90
+ })
91
+ out(JSON.stringify(summary))
92
+ return summary.failed.length === 0 ? 0 : 1
93
+ } catch (e) {
94
+ if (e instanceof LedgerHeldError) {
95
+ err('the ledger is held by another reconciler; no source was ticked')
96
+ return 3
97
+ }
98
+ err(e instanceof BuildError || e instanceof TypeError ? `refused: ${e.message}` : `refused: ${e?.name ?? 'Error'}: ${e?.message}`)
99
+ return 2
100
+ }
101
+ }
102
+
103
+ if (isEntryPoint(import.meta.url)) {
104
+ process.exitCode = main(process.argv.slice(2))
105
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * One tick of the freshness reconciler over the three live sources, in
3
+ * read-only mode: the ledger is written, nothing is delivered.
4
+ *
5
+ * Sources (each a read-only adapter, see docs/guides/freshness-reconciler.md):
6
+ * - the daemon's persisted session-state file,
7
+ * - the Claude Code session registry (activity evidence),
8
+ * - the Claude transcript tail reader.
9
+ *
10
+ * Defaults resolve the way the daemon resolves them: the state file under the
11
+ * daemon's config dir (`CHROXY_CONFIG_DIR`), the registry and the transcript
12
+ * projects under Claude's config dir (`CLAUDE_CONFIG_DIR`). Every path can be
13
+ * overridden; tests always do.
14
+ *
15
+ * Read-only is structural, not a flag the code checks: this module imports no
16
+ * network, child-process or credential module, the reconciler has no send
17
+ * method, and the only directory written is the ledger's.
18
+ */
19
+
20
+ import path from 'node:path'
21
+ import { coreConfig, createSessionRegistryAdapter, createStateFileAdapter, openReconciler, REGISTRY_SOURCE, STATE_FILE_SOURCE } from '../freshness/index.js'
22
+ import { CLAUDE_TRANSCRIPT_CAPS, CLAUDE_TRANSCRIPT_SOURCE, createClaudeTranscriptAdapter } from '../freshness-sources/index.js'
23
+ import { configDir, configPath } from '../config-dir.js'
24
+ import { claudeConfigDir, claudeProjectsDir } from '../utils/claude-config-dir.js'
25
+ import { readStateSchemaVersion, tickBuild } from './build-info.js'
26
+
27
+ export const DEFAULT_LEDGER_ID = 'chroxy-freshness'
28
+ export const DEFAULT_CADENCE_MINUTES = 30
29
+ export const SOURCES = Object.freeze([STATE_FILE_SOURCE, REGISTRY_SOURCE, CLAUDE_TRANSCRIPT_SOURCE])
30
+ export const MODES = Object.freeze(['read-only'])
31
+
32
+ /** The default location of each source, resolved as the daemon resolves it. */
33
+ export function defaultSourcePaths(env = process.env) {
34
+ return {
35
+ stateFile: configPath('session-state.json'),
36
+ registryDir: path.join(claudeConfigDir(env), 'sessions'),
37
+ projectsDir: claudeProjectsDir(env),
38
+ }
39
+ }
40
+
41
+ function requireAbsolute(name, value) {
42
+ if (typeof value !== 'string' || !path.isAbsolute(value)) throw new TypeError(`${name} must be an absolute path`)
43
+ return path.resolve(value)
44
+ }
45
+
46
+ /**
47
+ * Run one tick of every source and return a summary. Throws before reading a
48
+ * source when the ledger is held, corrupt or inside the daemon's state
49
+ * directory; a source whose tick throws is reported in `failed` and the other
50
+ * sources still run.
51
+ *
52
+ * @param {object} opts
53
+ * @param {string} opts.ledgerDir absolute; outside the daemon's state directory
54
+ * @param {{commit:string|null,daemon_version:string,install:string}} opts.build from `readBuild`
55
+ * @param {string} [opts.stateFile] @param {string} [opts.registryDir] @param {string} [opts.projectsDir]
56
+ * @param {string} [opts.ledgerId]
57
+ * @param {number} [opts.cadenceMinutes]
58
+ * @param {number} [opts.leaseMinutes] must exceed the cadence (the core enforces it)
59
+ * @param {string} [opts.mode] only `read-only`
60
+ * @param {number} [opts.now] ms
61
+ * @param {string[]} [opts.keepOutOf] added to the daemon's config dir, the state file's directory, both source directories and Claude's config dir
62
+ * @param {object[]} [opts.adapters] replaces the three live adapters; a test seam
63
+ */
64
+ export function runTick({ ledgerDir, build, stateFile, registryDir, projectsDir, ledgerId = DEFAULT_LEDGER_ID, cadenceMinutes = DEFAULT_CADENCE_MINUTES, leaseMinutes, mode = 'read-only', now = Date.now(), keepOutOf = [], adapters: adaptersOverride }) {
65
+ if (!MODES.includes(mode)) throw new TypeError(`mode must be one of ${MODES.join(', ')}; delivery is not part of this runner`)
66
+ if (!Number.isFinite(cadenceMinutes) || cadenceMinutes <= 0) throw new TypeError('cadenceMinutes must be a positive number')
67
+ if (leaseMinutes !== undefined && !(Number.isFinite(leaseMinutes) && leaseMinutes > 0)) throw new TypeError('leaseMinutes must be a positive number')
68
+ const defaults = defaultSourcePaths()
69
+ const paths = {
70
+ stateFile: requireAbsolute('stateFile', stateFile ?? defaults.stateFile),
71
+ registryDir: requireAbsolute('registryDir', registryDir ?? defaults.registryDir),
72
+ projectsDir: requireAbsolute('projectsDir', projectsDir ?? defaults.projectsDir),
73
+ }
74
+ const ledger = requireAbsolute('ledgerDir', ledgerDir)
75
+ const cadenceMs = cadenceMinutes * 60_000
76
+ const config = coreConfig({ cadence_minutes: cadenceMinutes, sources: { [CLAUDE_TRANSCRIPT_SOURCE]: CLAUDE_TRANSCRIPT_CAPS } })
77
+ const adapters = adaptersOverride ?? [
78
+ createStateFileAdapter({ path: paths.stateFile }),
79
+ createSessionRegistryAdapter({ dir: paths.registryDir }),
80
+ createClaudeTranscriptAdapter({ projectsDir: paths.projectsDir }),
81
+ ]
82
+ const recorded = tickBuild(build, readStateSchemaVersion(paths.stateFile))
83
+ const slotStart = Math.floor(now / cadenceMs) * cadenceMs
84
+ const rec = openReconciler({
85
+ dir: ledger,
86
+ ledgerId,
87
+ config,
88
+ adapters,
89
+ now,
90
+ leaseMs: leaseMinutes === undefined ? undefined : leaseMinutes * 60_000,
91
+ keepOutOf: [configDir(), path.dirname(paths.stateFile), paths.registryDir, paths.projectsDir, claudeConfigDir(), ...keepOutOf],
92
+ })
93
+ const sources = []
94
+ try {
95
+ for (const source of SOURCES) {
96
+ try {
97
+ const res = rec.tick({ source, slotStart, now, build: recorded })
98
+ const byFreshness = {}
99
+ for (const r of res.reads) byFreshness[r.freshness] = (byFreshness[r.freshness] ?? 0) + 1
100
+ sources.push({ source, ok: true, tick_id: res.tickId, skipped: res.skipped ?? null, sessions: res.reads.length, by_freshness: byFreshness })
101
+ } catch (err) {
102
+ sources.push({ source, ok: false, error: err?.name ?? 'Error', code: typeof err?.code === 'string' ? err.code : null })
103
+ }
104
+ }
105
+ } finally {
106
+ rec.close()
107
+ }
108
+ return { mode, slot_start: slotStart, build: recorded, ledger: ledger, sources, failed: sources.filter((s) => !s.ok).map((s) => s.source) }
109
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Stamp an installed daemon package with the commit it was built from.
3
+ *
4
+ * This is the only writer in the runner and it is not part of a tick: an
5
+ * operator runs it once after installing a pinned build. It writes one small
6
+ * file, `build-info.json`, into the package directory it is given, and
7
+ * refuses a directory that is not the installed daemon package or that is a
8
+ * development checkout.
9
+ */
10
+
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import { randomBytes } from 'node:crypto'
14
+ import { BUILD_INFO_FILE, BuildError, DAEMON_PACKAGE_NAME, checkoutRefusal, classifyInstall, isCommit } from './build-info.js'
15
+
16
+ /**
17
+ * @param {string} packageRoot
18
+ * @param {string} commit
19
+ * @param {{ force?: boolean }} [opts] replace a different existing stamp
20
+ * @returns {string} the path written
21
+ */
22
+ export function stampBuild(packageRoot, commit, { force = false } = {}) {
23
+ if (!isCommit(commit)) throw new BuildError('bad_commit', 'the commit must be a full 40-character lowercase id')
24
+ let pkg
25
+ try {
26
+ pkg = JSON.parse(fs.readFileSync(path.join(packageRoot, 'package.json'), 'utf8'))
27
+ } catch {
28
+ throw new BuildError('not_daemon_package', `${packageRoot} has no readable package.json`)
29
+ }
30
+ if (pkg?.name !== DAEMON_PACKAGE_NAME) throw new BuildError('not_daemon_package', `${packageRoot} is not the ${DAEMON_PACKAGE_NAME} package`)
31
+ const { kind, git } = classifyInstall(packageRoot)
32
+ if (kind !== 'pinned') throw checkoutRefusal(git, 'refusing to stamp a development checkout; stamp the installed copy under node_modules')
33
+ const file = path.join(packageRoot, BUILD_INFO_FILE)
34
+ if (fs.existsSync(file)) {
35
+ let existing = null
36
+ try {
37
+ existing = JSON.parse(fs.readFileSync(file, 'utf8'))?.commit ?? null
38
+ } catch {
39
+ existing = null
40
+ }
41
+ if (existing === commit) return file
42
+ if (!force) throw new BuildError('already_stamped', `${BUILD_INFO_FILE} already holds ${existing === null ? 'an unreadable stamp' : 'a different commit'}; pass --force to replace it`)
43
+ }
44
+ const tmp = `${file}.tmp-${process.pid}-${randomBytes(6).toString('hex')}`
45
+ fs.writeFileSync(tmp, JSON.stringify({ commit }) + '\n', { mode: 0o644, flag: 'wx' })
46
+ try {
47
+ fs.renameSync(tmp, file)
48
+ } catch (err) {
49
+ try {
50
+ fs.unlinkSync(tmp)
51
+ } catch {
52
+ // best effort: the rename's error is the one to report
53
+ }
54
+ throw err
55
+ }
56
+ return file
57
+ }
@@ -0,0 +1,211 @@
1
+ /**
2
+ * Tail-only status reader for local Claude Code transcripts (JSONL).
3
+ *
4
+ * It answers one question per session: what is the last status block the
5
+ * assistant authored, and when. It reads the END of the transcript file, keeps
6
+ * that block and its time, and discards every other line as soon as it has
7
+ * been looked at. Nothing else a transcript holds (prompts, tool input and
8
+ * output, earlier blocks, prose, titles, working directories) is carried into
9
+ * a value this module returns, so it cannot reach the ledger.
10
+ *
11
+ * - Location: the same locator the closed-conversation endpoint uses
12
+ * (`resolveTranscriptSource`). It refuses a locator that does not name the
13
+ * session, a path that resolves outside the provider's projects root, and
14
+ * returns the file's identity; this reader opens the file read-only and
15
+ * refuses a file that is not that same object or not a regular file.
16
+ * - Bounded: at most `maxTailBytes` are read, from the end. A line cut by
17
+ * the start of the window is dropped; an unterminated final line (a write
18
+ * still in flight) is ignored. A line in between that does not parse is a
19
+ * damaged transcript, which is an `error`, not a shorter one.
20
+ * - A window that starts mid-file and holds no status block is an `error`
21
+ * (`window_exhausted`), not `no_report`: a large tool result can push a
22
+ * recent block out of the window. `no_report` means the whole file was read.
23
+ * - Authored: only top-level assistant entries count. A user entry, a tool
24
+ * result or a subagent (sidechain) entry that quotes a status block is not
25
+ * one the session authored.
26
+ * - Parsed by the daemon's own parser (`reportFromText` over
27
+ * `extractDeclaredStatus`); nothing here parses a status block.
28
+ * - Changed format is `error`, never `no_report`, never idle: an assistant
29
+ * entry whose `message.content` is not a list of typed blocks, an entry with
30
+ * no `type`, a status block with no readable time.
31
+ *
32
+ * It never writes, never creates a file and has no way to send input to a
33
+ * session: `list` and `read` are the whole adapter (`sealAdapter` refuses
34
+ * anything else).
35
+ *
36
+ * Time: the report is timed with the `timestamp` of the entry that carries the
37
+ * block (`report_time_basis: authored_at`).
38
+ *
39
+ * One recorded sample read of a real transcript confirms the format before the
40
+ * first run against real data; that read is an operator step, not part of this
41
+ * module, and it uses only the checks above.
42
+ */
43
+
44
+ import { isAbsolute, join } from 'node:path'
45
+ import { closeSync, constants as fsConstants, fstatSync, openSync, readSync, readdirSync } from 'node:fs'
46
+ import { AdapterContractError, validSourceName } from '../freshness/adapter.js'
47
+ import { reportFromText } from '../freshness/state-file-adapter.js'
48
+ import { resolveTranscriptSource } from '../transcript-sources.js'
49
+
50
+ export const CLAUDE_TRANSCRIPT_SOURCE = 'claude-transcript'
51
+
52
+ /** The capabilities to register for this source in the reconciler's configuration. */
53
+ export const CLAUDE_TRANSCRIPT_CAPS = Object.freeze({ native_in_read: false, activity_read: false, scope: false, can_confirm_gone: true, report_time_basis: 'authored_at' })
54
+
55
+ /** Default window read from the end of a transcript. */
56
+ export const DEFAULT_MAX_TAIL_BYTES = 4 * 1024 * 1024
57
+ const DEFAULT_MAX_SESSIONS = 5000
58
+ const NEWLINE = 0x0a
59
+
60
+ const AMBIGUOUS = Symbol('ambiguous')
61
+
62
+ /** A conversation id as a file name: no separators, no dots at the start. */
63
+ function safeId(id) {
64
+ return typeof id === 'string' && id.length >= 1 && id.length <= 128 && /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(id)
65
+ }
66
+
67
+ function isPlain(v) {
68
+ return v !== null && typeof v === 'object' && !Array.isArray(v)
69
+ }
70
+
71
+ /** One snapshot of which sessions exist: names only, no file is opened. */
72
+ function scanProjects(projectsDir, maxSessions) {
73
+ let dirs
74
+ try {
75
+ dirs = readdirSync(projectsDir, { withFileTypes: true })
76
+ } catch {
77
+ return null
78
+ }
79
+ const byId = new Map()
80
+ for (const d of dirs) {
81
+ if (!d.isDirectory()) continue
82
+ let files
83
+ try {
84
+ files = readdirSync(join(projectsDir, d.name), { withFileTypes: true })
85
+ } catch {
86
+ // A directory that cannot be listed is not an empty one: a partial listing would read as sessions gone.
87
+ return null
88
+ }
89
+ for (const f of files) {
90
+ if (!f.isFile() || !f.name.endsWith('.jsonl')) continue
91
+ const id = f.name.slice(0, -'.jsonl'.length)
92
+ // A name the reader would not accept is an unexpected store, not an absent session.
93
+ if (!safeId(id)) return null
94
+ byId.set(id, byId.has(id) ? AMBIGUOUS : `${d.name}/${f.name}`)
95
+ if (byId.size > maxSessions) return null
96
+ }
97
+ }
98
+ return byId
99
+ }
100
+
101
+ const fail = (error_code) => ({ outcome: 'error', error_code })
102
+
103
+ /**
104
+ * Read the window and find the last authored status block in it.
105
+ * Returns a read.
106
+ */
107
+ function readTail(fd, expectedIdentity, maxTailBytes) {
108
+ const st = fstatSync(fd, { bigint: true })
109
+ if (!st.isFile()) return fail('not_regular')
110
+ if (expectedIdentity && (st.dev !== expectedIdentity.dev || st.ino !== expectedIdentity.ino)) return fail('file_changed')
111
+ const size = Number(st.size)
112
+ // One byte before the window says whether the window starts on a line boundary.
113
+ const start = size > maxTailBytes ? size - maxTailBytes - 1 : 0
114
+ const length = size - start
115
+ const buf = Buffer.alloc(length)
116
+ let off = 0
117
+ while (off < length) {
118
+ const n = readSync(fd, buf, off, length - off, start + off)
119
+ if (n === 0) break
120
+ off += n
121
+ }
122
+ let from = 0
123
+ if (start > 0) {
124
+ // A line the window starts inside of is dropped whole.
125
+ from = buf[0] === NEWLINE ? 1 : buf.indexOf(NEWLINE) + 1
126
+ if (from === 0 || from >= off) return fail('tail_too_small')
127
+ }
128
+ const lines = buf.toString('utf8', from, off).split('\n')
129
+
130
+ let last = null // the last status block: { report } or { badTime }
131
+ let later = false // an assistant message with text and no status block after it
132
+ for (let i = 0; i < lines.length; i++) {
133
+ const line = lines[i].trim()
134
+ if (!line) continue
135
+ let entry
136
+ try {
137
+ entry = JSON.parse(line)
138
+ } catch {
139
+ // An unterminated final line is a write still in flight; any other bad line is damage.
140
+ if (i === lines.length - 1) continue
141
+ return fail('corrupt')
142
+ }
143
+ if (!isPlain(entry) || typeof entry.type !== 'string') return fail('shape_changed')
144
+ if (entry.type !== 'assistant' || entry.isSidechain === true) continue
145
+ const content = entry.message?.content
146
+ if (!isPlain(entry.message) || !Array.isArray(content)) return fail('shape_changed')
147
+ const texts = []
148
+ for (const block of content) {
149
+ if (!isPlain(block) || typeof block.type !== 'string') return fail('shape_changed')
150
+ if (block.type !== 'text') continue
151
+ if (typeof block.text !== 'string') return fail('shape_changed')
152
+ texts.push(block.text)
153
+ }
154
+ const text = texts.join('\n')
155
+ if (text.trim() === '') continue
156
+ const at = typeof entry.timestamp === 'string' ? Date.parse(entry.timestamp) : NaN
157
+ const report = reportFromText(text, { updatedAt: Number.isSafeInteger(at) && at >= 0 ? at : -1 })
158
+ if (report) {
159
+ last = report.last_report_at < 0 ? { badTime: true } : { report }
160
+ later = false
161
+ } else {
162
+ later = true
163
+ }
164
+ }
165
+ // A window that began mid-file and found nothing has not shown the session never reported: an earlier block may lie before it.
166
+ if (!last) return start > 0 ? fail('window_exhausted') : { outcome: 'no_report' }
167
+ if (last.badTime) return fail('bad_timestamp')
168
+ return { outcome: 'ok', report: { ...last.report, later_unfootered_messages: later } }
169
+ }
170
+
171
+ /**
172
+ * @param {object} opts
173
+ * @param {string} opts.projectsDir the Claude projects directory (absolute), the provider's store
174
+ * @param {string} [opts.source] source name (default `claude-transcript`)
175
+ * @param {number} [opts.maxTailBytes] bytes read from the end of a transcript
176
+ * @param {number} [opts.maxSessions] a store listing more sessions than this cannot be listed
177
+ * @param {Function} [opts.resolve] locator (default `resolveTranscriptSource`); for tests
178
+ */
179
+ export function createClaudeTranscriptAdapter({ projectsDir, source = CLAUDE_TRANSCRIPT_SOURCE, maxTailBytes = DEFAULT_MAX_TAIL_BYTES, maxSessions = DEFAULT_MAX_SESSIONS, resolve = resolveTranscriptSource }) {
180
+ if (typeof projectsDir !== 'string' || !isAbsolute(projectsDir)) throw new TypeError('createClaudeTranscriptAdapter: projectsDir must be an absolute path')
181
+ if (!validSourceName(source)) throw new AdapterContractError('adapter.source must be a short lowercase name')
182
+ if (!Number.isSafeInteger(maxTailBytes) || maxTailBytes < 1024) throw new TypeError('createClaudeTranscriptAdapter: maxTailBytes must be an integer of at least 1024')
183
+ let snapshot = null
184
+ const sources = [{ provider: 'claude', projectsDir }]
185
+ return {
186
+ source,
187
+ list() {
188
+ snapshot = scanProjects(projectsDir, maxSessions)
189
+ if (!snapshot) return null
190
+ return [...snapshot.keys()].map((id) => ({ session: { source, native_id: id, incarnation: null }, scope: null }))
191
+ },
192
+ read(session) {
193
+ if (!snapshot) snapshot = scanProjects(projectsDir, maxSessions)
194
+ if (!snapshot) return fail('source_missing')
195
+ const locator = snapshot.get(session.native_id)
196
+ if (locator === undefined) return { listed: false }
197
+ if (locator === AMBIGUOUS) return fail('ambiguous_id')
198
+ const found = resolve({ provider: 'claude', conversationId: session.native_id, sourceLocator: locator, sources })
199
+ if (!found.ok) return fail(found.code === 'source_unavailable' ? 'source_missing' : 'invalid_source')
200
+ let fd
201
+ try {
202
+ fd = openSync(found.path, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW || 0) | (fsConstants.O_NONBLOCK || 0))
203
+ return readTail(fd, found.identity, maxTailBytes)
204
+ } catch (err) {
205
+ return fail(err?.code === 'ENOENT' || err?.code === 'ENOTDIR' ? 'source_missing' : 'unreadable')
206
+ } finally {
207
+ if (fd !== undefined) closeSync(fd)
208
+ }
209
+ },
210
+ }
211
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Codex transcripts: not supported, and said so.
3
+ *
4
+ * The transcript locator marks the Codex format unsupported
5
+ * (`resolveTranscriptSource`), and no recorded Codex transcript sample backs a
6
+ * reader yet. A reader written from a guess at the format could read a
7
+ * different record as the status block, or read nothing and report a quiet
8
+ * session. This adapter therefore reads nothing: it cannot list, and every read
9
+ * is `error: unsupported`. It opens no file. The reconciler records an
10
+ * unlistable source as `source_unreadable` and an unsupported read as an
11
+ * `error` check, so a Codex session is never graded `idle` and never reads as
12
+ * having no status.
13
+ *
14
+ * Replace this with a tail reader like `claude-transcript-adapter.js` once a
15
+ * sample of the format is recorded and the locator supports it.
16
+ */
17
+
18
+ import { AdapterContractError, validSourceName } from '../freshness/adapter.js'
19
+
20
+ export const CODEX_TRANSCRIPT_SOURCE = 'codex-transcript'
21
+
22
+ /** The capabilities to register for this source in the reconciler's configuration. */
23
+ export const CODEX_TRANSCRIPT_CAPS = Object.freeze({ native_in_read: false, activity_read: false, scope: false, can_confirm_gone: false, report_time_basis: 'authored_at' })
24
+
25
+ /** @param {{ source?: string }} [opts] */
26
+ export function createCodexTranscriptAdapter({ source = CODEX_TRANSCRIPT_SOURCE } = {}) {
27
+ if (!validSourceName(source)) throw new AdapterContractError('adapter.source must be a short lowercase name')
28
+ return {
29
+ source,
30
+ list: () => null,
31
+ read: () => ({ outcome: 'error', error_code: 'unsupported' }),
32
+ }
33
+ }
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Live sources for the freshness reconciler: tail-only status readers over
3
+ * local provider transcripts. They are kept out of `src/freshness/`, whose
4
+ * isolation test allows no import of the daemon's transcript locator.
5
+ */
6
+
7
+ export * from './claude-transcript-adapter.js'
8
+ export * from './codex-transcript-adapter.js'