@awebai/oats 0.61.0 → 0.62.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (85) hide show
  1. package/README.md +1 -1
  2. package/bin/oats.mjs +26 -11
  3. package/docs/capabilities.md +1 -1
  4. package/docs/execution-targets.md +49 -3
  5. package/docs/implementation.md +2 -1
  6. package/docs/named-test-runs.md +382 -0
  7. package/docs/official-catalog.md +1 -1
  8. package/docs/packages.md +5 -5
  9. package/docs/release-notes/v0.62.0.md +223 -0
  10. package/docs/upgrading.md +133 -11
  11. package/docs/workspaces.md +1 -1
  12. package/lib/core.mjs +2 -2
  13. package/lib/doctor-capture.mjs +35 -0
  14. package/lib/session-viewer.mjs +86 -7
  15. package/package-catalog.json +1 -1
  16. package/package.json +1 -1
  17. package/packages/client/cli-locator.mjs +2 -2
  18. package/packages/record/README.md +87 -13
  19. package/packages/record/bin/capture-hook.mjs +8 -0
  20. package/packages/record/bin/capture.mjs +143 -124
  21. package/packages/record/bin/recall.mjs +8 -3
  22. package/packages/record/bin/setup.mjs +115 -225
  23. package/packages/record/bin/turn-record.mjs +2 -2
  24. package/packages/record/docs/capture-service.md +1443 -28
  25. package/packages/record/docs/capture-status.schema.json +429 -12
  26. package/packages/record/lib/capture-admission.mjs +82 -0
  27. package/packages/record/lib/capture-aw-unit.mjs +137 -0
  28. package/packages/record/lib/capture-aw.mjs +31 -12
  29. package/packages/record/lib/capture-budget.mjs +31 -0
  30. package/packages/record/lib/capture-cc.mjs +39 -6
  31. package/packages/record/lib/capture-cleanup-queue.mjs +135 -0
  32. package/packages/record/lib/capture-cleanup-work.mjs +77 -0
  33. package/packages/record/lib/capture-command-operation.mjs +37 -0
  34. package/packages/record/lib/capture-command-output.mjs +61 -0
  35. package/packages/record/lib/capture-command-worker.mjs +6 -0
  36. package/packages/record/lib/capture-command.mjs +48 -0
  37. package/packages/record/lib/capture-completion.mjs +152 -0
  38. package/packages/record/lib/capture-context.mjs +50 -0
  39. package/packages/record/lib/capture-default-roots.mjs +30 -0
  40. package/packages/record/lib/capture-discovery.mjs +114 -0
  41. package/packages/record/lib/capture-failures.mjs +45 -0
  42. package/packages/record/lib/capture-health-doctor.mjs +13 -0
  43. package/packages/record/lib/capture-health-installation.mjs +117 -0
  44. package/packages/record/lib/capture-health.mjs +116 -0
  45. package/packages/record/lib/capture-hook-ownership.mjs +58 -0
  46. package/packages/record/lib/capture-hook-runner.mjs +17 -0
  47. package/packages/record/lib/capture-hook.mjs +26 -0
  48. package/packages/record/lib/capture-index-inventory.mjs +205 -0
  49. package/packages/record/lib/capture-index-outcomes.mjs +113 -0
  50. package/packages/record/lib/capture-index-reset.mjs +109 -0
  51. package/packages/record/lib/capture-index-work.mjs +77 -0
  52. package/packages/record/lib/capture-issue-preparation.mjs +73 -0
  53. package/packages/record/lib/capture-issues.mjs +15 -2
  54. package/packages/record/lib/capture-lock.mjs +102 -16
  55. package/packages/record/lib/capture-native-unit.mjs +322 -0
  56. package/packages/record/lib/capture-pass.mjs +102 -0
  57. package/packages/record/lib/capture-recovery-snapshot.mjs +182 -0
  58. package/packages/record/lib/capture-retained-scratch.mjs +213 -0
  59. package/packages/record/lib/capture-retry.mjs +102 -0
  60. package/packages/record/lib/capture-run.mjs +125 -0
  61. package/packages/record/lib/capture-scratch.mjs +12 -3
  62. package/packages/record/lib/capture-service-definition.mjs +104 -0
  63. package/packages/record/lib/capture-service-install.mjs +362 -0
  64. package/packages/record/lib/capture-service-ownership.mjs +137 -0
  65. package/packages/record/lib/capture-service-runner.mjs +18 -0
  66. package/packages/record/lib/capture-small-snapshot.mjs +85 -0
  67. package/packages/record/lib/capture-source-discovery.mjs +319 -0
  68. package/packages/record/lib/capture-source-queue.mjs +199 -0
  69. package/packages/record/lib/capture-source-work.mjs +85 -0
  70. package/packages/record/lib/capture-state.mjs +16 -71
  71. package/packages/record/lib/capture-status.mjs +171 -0
  72. package/packages/record/lib/capture-supervisor.mjs +117 -0
  73. package/packages/record/lib/capture-watch.mjs +32 -0
  74. package/packages/record/lib/capture-work-session.mjs +238 -0
  75. package/packages/record/lib/capture-worker.mjs +58 -0
  76. package/packages/record/lib/derived-state.mjs +28 -15
  77. package/packages/record/lib/file-lines.mjs +22 -6
  78. package/packages/record/lib/formats.mjs +4 -3
  79. package/packages/record/lib/index-capture.mjs +97 -0
  80. package/packages/record/lib/index-db.mjs +3 -17
  81. package/packages/record/lib/index-reset.mjs +19 -0
  82. package/packages/record/lib/store.mjs +36 -11
  83. package/packages/record/lib/transcript-prefix.mjs +125 -0
  84. package/skills/oats-getting-started/SKILL.md +1 -1
  85. package/docs/macos-test-runs.md +0 -246
@@ -13,7 +13,7 @@
13
13
  // Every candidate is canonicalized to an absolute executable and accepted
14
14
  // ONLY if executable and `<bin> version --json` returns the v1 probe:
15
15
  // {"schemaVersion":1,"name":"@awebai/oats","version":"0.24.x","desktopApi":1}
16
- // Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.62.0 (the band is
16
+ // Desktop accepts desktopApi === 1 and semver >=0.26.0 <0.63.0 (the band is
17
17
  // spelled ONCE, in ACCEPT_RANGE below — this line only paraphrases it).
18
18
  // API version — not source adjacency — is authoritative.
19
19
  //
@@ -52,7 +52,7 @@ export const DESKTOP_API = 1;
52
52
  // carry a `description` for every kind and `<kind> update <id> --description`
53
53
  // sets one (feature `automation-descriptions`, which gates the Desktop's
54
54
  // summary writes). The Desktop v1 surface is otherwise unchanged.
55
- export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0, 62, 0] };
55
+ export const ACCEPT_RANGE = { min: [0, 26, 0], maxExclusive: [0, 63, 0] };
56
56
  /** The band as humans read it — derived, never hand-spelled, so the probe
57
57
  * rejection reason, the backend's /api status and the degradation card can
58
58
  * never disagree with the numbers actually enforced above. */
@@ -60,11 +60,11 @@ commands are `oats capture|recall|setup`.
60
60
 
61
61
  ```bash
62
62
  turn-record setup # install Stop/SessionEnd hooks into every
63
- # ~/.claude*/settings.json, install the background
64
- # watcher (launchd on macOS, systemd user unit on
63
+ # ~/.claude*/settings.json, install periodic capture
64
+ # (launchd on macOS, systemd user service + timer on
65
65
  # Linux), then run the first capture pass.
66
66
  # Idempotent; --dry-run previews; --owner overrides
67
- # the machine name.
67
+ # the machine name. --root selects the persisted store.
68
68
 
69
69
  turn-record capture # one reconciliation pass, then index update
70
70
  turn-record capture --watch # pass now, on filesystem change, every 15 min
@@ -77,13 +77,21 @@ turn-record recall --show t1:<hex> # print one turn
77
77
  turn-record recall --reindex # full rebuild of the derived index
78
78
  ```
79
79
 
80
+ `recall --thread <thread> --json` lists a thread in capture sequence.
81
+ For a thread spanning aweb accounts, cross-account sequence under the service
82
+ is unspecified, and an ID window may contain turns from more than one account.
83
+ `--after <id>` excludes its boundary; `--until <id>` includes its boundary.
84
+ `--ids-only` uses the same window and reports IDs and output byte sizes. Later
85
+ appends do not reorder an existing window; existing tombstone visibility rules
86
+ still apply. Text thread listings without a query remain timestamp-sorted.
87
+
80
88
  Store root: `--root`, else `$TURN_RECORD_ROOT`, else `~/.turn-record`.
81
89
 
82
90
  `recall --show` refuses a turn hidden by its author's tombstone, including a
83
91
  session event whose tombstone lives in another stream. It emits no turn payload
84
92
  and exits with status 1, as it does for a missing turn.
85
93
 
86
- **The `node` that `setup` writes down.** The hooks and the watcher's unit name
94
+ **The `node` that `setup` writes down.** The hooks and the service's unit name
87
95
  a `node` by its path, and only `setup` run again rewrites them. Which path
88
96
  depends on how it is run:
89
97
 
@@ -100,16 +108,66 @@ runs under the `node` that runs `setup`.
100
108
 
101
109
  Each path is written for what reads it: a shell word in the hook's command,
102
110
  systemd's quoting in `ExecStart`, XML text in the launchd plist. A path of
103
- plain characters is written bare. A run finds the hooks of an earlier run by
104
- their shape, quoted or not, and replaces their command; a command it cannot
111
+ plain characters stays bare in hook commands. A run finds the hooks of an earlier run by
112
+ their shape, quoted or not, and refreshes command, async and timeout fields; a command it cannot
105
113
  read as its own is left alone and a new hook is added beside it.
106
114
  Stream owner: `--owner`, else `$TURN_RECORD_OWNER`, else the short hostname.
107
115
 
116
+ Ordinary/source-selected capture, explicit retry and foreground watch ticks use
117
+ the fixed supervised worker. Partial passes exit zero with pending work;
118
+ operational failures exit nonzero. `--no-index` never opens or mutates the
119
+ derived search index and supplies no fresh all-stage success. Quiet does not
120
+ imply a hook trigger. Explicit `--hook` launches a detached supervisor and reports
121
+ only “capture launched”, not initialization or completion. Owned Stop/SessionEnd
122
+ settings run the hook entry `bin/capture-hook.mjs` (the same launch as
123
+ `--quiet --hook`, under a file a rolled-back release cannot load, so it can
124
+ never return Claude's blocking exit two), `async:false` and `timeout:10`: the harness waits
125
+ for the launcher, while capture runs detached without its output pipes. Setup
126
+ refreshes these fields even when the owned command already matches, preserving
127
+ foreign hooks and unrelated fields. Hook errors, including usage, exit one,
128
+ never Claude's Stop-blocking exit two. Existing ordinary quiet argv remain
129
+ manual. Setup's first pass awaits the fixed supervisor with explicit `setup`
130
+ attribution and all sources/indexing enabled; `--no-service` still runs it,
131
+ while `--dry-run` starts no pass. Partial and overlap exit zero without claiming
132
+ completion; operational failures remain nonzero. Setup preflights named service
133
+ files, manager state and hook edits before mutation, then converts supported
134
+ legacy watchers to periodic capture, from the next release after 0.61.0;
135
+ 0.56.0–0.61.0 shipped without it.
136
+ See [command routing and receipts](docs/capture-service.md#ordinary-cli-and-foreground-watch).
137
+ See [detached hook launch limits](docs/capture-service.md#detached-hook-launcher).
138
+ The [service migration gate](docs/capture-service.md#setup-service-migration)
139
+ refuses foreign, disabled or masked definitions unless the operator explicitly
140
+ chooses `--replace-service`; `--no-service` bypasses service inspection and
141
+ actions while still installing requested hooks and running the first pass.
142
+ Refusals print that choice as the user-facing command with the selected
143
+ owner/root: `oats setup …` when the kernel environment handed in a node
144
+ (`OATS_NODE_BIN`, also set in instance shells), otherwise `turn-record setup …`.
145
+ Unknown/read errors always refuse, as does a macOS registration of the capture
146
+ label from another plist path, even with `--replace-service`. A refusal
147
+ changes nothing. A service failure after preflight still writes the hooks and
148
+ runs the first pass, then exits 1 with the
149
+ [setup summary](docs/capture-service.md#setup-service-migration) of what changed;
150
+ setup's private pending-activation marker (`<root>/capture-service-pending.json`)
151
+ lets a plain rerun finish its own activation, and `capture --health` reports it
152
+ as `capture-service-pending`.
153
+ Replacement saves nonoverwriting backups under the selected root and rechecks
154
+ file identity. `--dry-run` writes nothing and invokes no manager, so it reports
155
+ manager state as unexamined.
156
+ Healthy unchanged schedules preserve an active pass; successful setup reports
157
+ verified periodic scheduling, not a permanent PID. Real-manager lifecycle
158
+ and full service qualification remain separate gates.
159
+
108
160
  Transcript capture reads 64 KiB chunks and frames complete native records,
109
- including UTF-8 characters split across chunks. It appends batches of at most
110
- 8 MiB of source bytes plus the last record and checkpoints after each batch.
111
- One very large native record can still require memory proportional to that
112
- record; capture does not impose a new record-size policy.
161
+ including UTF-8 characters split across chunks. It flushes before adding a
162
+ record that would exceed an 8 MiB source batch and checkpoints after each batch.
163
+ Public synchronous capture can still process a larger individual record, with
164
+ memory proportional to that record; its resource contract is unchanged. The
165
+ supervised worker separately applies the fixed service policy beyond what is
166
+ already captured: it captures the complete records before a new record over
167
+ 8 MiB, then sets the input aside at that record's start. Records captured
168
+ earlier, of any size, are proved on recovery by streamed digests, not refused. Later records stay pending until the source is edited or the
169
+ whole input is ignored; `--retry-set-aside` cannot pass the oversized record
170
+ ([operator recovery](docs/capture-service.md#operator-recovery)).
113
171
  Final, attributed and protected Pi capture stage the descriptor's snapshot on
114
172
  private scratch under `<root>/.capture-tmp` before the first append, preserving
115
173
  attribution and custody checks without retaining the source in process memory.
@@ -163,8 +221,10 @@ Name-only patterns apply across every capture source: a short or generic
163
221
  pattern meant for one aw account can also catch a session file's basename
164
222
  or id in any format. Prefer path patterns for anything short or generic.
165
223
 
166
- Ignored files are counted in each pass (`N ignored` in capture output;
167
- `capture --status` shows the active pattern count), never skipped silently.
224
+ Ignored inputs are accounted for in worker run counts; exact synchronous
225
+ receipts retain their ignored counts. `capture --status` shows the active
226
+ pattern count. Ordinary text output summarizes confirmed appended turns and
227
+ outcome; `capture --health` exposes active refusals and remedies.
168
228
  The file is per record root and is local policy, not record truth — the
169
229
  sync guidance below replicates only `streams/` and `objects/`, so each
170
230
  machine decides what its own capture refuses to read; sync the `ignore`
@@ -173,6 +233,18 @@ ignore file that exists but cannot be read fails the pass loudly (a privacy
173
233
  control must not fail open), and ignoring is **forward-looking only** —
174
234
  turns already captured stay in the record; hide those with a tombstone.
175
235
 
236
+ `turn-record capture --health [--json]` reads offline installation,
237
+ receipt freshness/failure and current issue evidence without capture, repair,
238
+ root creation or manager calls. Warnings exit zero; unavailable readers fail.
239
+ A recent receipt or definition file does not certify enabled scheduling.
240
+ See [health diagnosis](docs/capture-service.md#offline-installation-and-run-diagnosis)
241
+ for exact installation candidates, nullable history, reader bounds and the
242
+ asleep/off-host caveat. Deployment `oats doctor` delegates once to package health
243
+ with a finite command timeout/output bound and maps its rows into warnings.
244
+ Command, reader or invalid-response failures yield `capture-health-unavailable`;
245
+ `--soul` remains composition-only. Kernel remedies say `oats`; standalone package
246
+ remedies say `turn-record`, without rewriting user paths or receipt data.
247
+
176
248
  ## Multi-machine
177
249
 
178
250
  Replicate `streams/` and `objects/` with any dumb file sync (syncthing,
@@ -301,7 +373,9 @@ output inventories without suppressing error counts.
301
373
 
302
374
  Verified snapshots and prefix comparisons use private record-root scratch, which
303
375
  can expand with source size; journal and derived-index disk space also grow with
304
- captured content. Staging is cleaned on success and failure. No new heap, record
376
+ captured content. Public per-call staging is cleaned on success and failure;
377
+ internal command recovery can retain explicitly owned jobs across workers, as
378
+ described in the [resource model](docs/capture-service.md#resource-model). No new heap, record
305
379
  size, elapsed-time or service policy limit is imposed by these algorithms.
306
380
 
307
381
  ## Known costs, accepted for v1
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env node
2
+ // The capture hook's entry: `capture --hook` under a file name of its own.
3
+ // Claude treats a hook's exit 2 as blocking. A release that predates this file
4
+ // cannot load it, so after a rollback the persisted hook line fails with exit 1
5
+ // ("Cannot find module"), which never blocks Stop or SessionEnd, instead of an
6
+ // older capture.mjs rejecting a flag it does not know with exit 2.
7
+ process.argv.splice(2, 0, "--hook");
8
+ await import("./capture.mjs");
@@ -12,34 +12,39 @@
12
12
  // accounts) whose sources are never captured — see lib/ignore.mjs.
13
13
  // Reconciliation is the capture; hooks and watch only decide when to run it.
14
14
 
15
- import { closeSync, constants, fstatSync, openSync, readFileSync, watch } from "node:fs";
15
+ import { closeSync, constants, fstatSync, openSync, readFileSync, realpathSync, watch } from "node:fs";
16
16
  import { homedir, hostname } from "node:os";
17
- import { basename, join, resolve } from "node:path";
17
+ import { basename, isAbsolute, join, resolve } from "node:path";
18
18
  import process from "node:process";
19
19
 
20
20
  import { RecordStore } from "../lib/store.mjs";
21
- import { captureAllSessions, captureSessions } from "../lib/capture-cc.mjs";
21
+ import { captureSessions } from "../lib/capture-cc.mjs";
22
22
  import { sessionsForHome } from "../lib/sessions-for-home.mjs";
23
23
  import { SESSION_FORMATS } from "../lib/formats.mjs";
24
24
  import { cwdOfLine } from "../lib/sessions-for-home.mjs";
25
25
  import { stageSnapshot } from "../lib/session-snapshot.mjs";
26
26
  import { cleanupCaptureScratch } from "../lib/capture-scratch.mjs";
27
27
  import { bufferLines } from "../lib/file-lines.mjs";
28
- import { captureAwLogs, defaultCommLogDir } from "../lib/capture-aw.mjs";
29
28
  import { withReceiptSummaries } from "../lib/receipt-summary.mjs";
30
29
  import { RecordIndex } from "../lib/index-db.mjs";
31
30
  import { IgnoreError, ignoreFilePath, loadIgnore } from "../lib/ignore.mjs";
32
- import { CAPTURE_SOURCES, captureHealth, resetSourceCursors, retrySetAside, writeCaptureStatus } from "../lib/capture-state.mjs";
31
+ import { CAPTURE_SOURCES, captureHealth, resetSourceCursors, writeCaptureStatus } from "../lib/capture-state.mjs";
33
32
  import { acquireCaptureLock } from "../lib/capture-lock.mjs";
33
+ import { captureHealthForDoctor } from "../lib/capture-health.mjs";
34
+ import { captureDefaultRootPlan, resolveCaptureDefaultRoots } from "../lib/capture-default-roots.mjs";
35
+ import { captureCommandPass, reportLockInitializationFailure, reportReclaimedLock, releaseDetail } from "../lib/capture-command-output.mjs";
36
+ import { captureWatchQueue } from "../lib/capture-watch.mjs";
37
+ import { launchCaptureHook } from "../lib/capture-hook.mjs";
34
38
 
35
39
  // Fail closed but actionably: an unreadable ignore file must stop capture,
36
40
  // as one clear line naming the file — never an uncaught stack trace.
37
- function loadIgnoreOrExit(recordRoot) {
41
+ class PrintedCaptureFailure extends Error {}
42
+ function loadIgnoreForCommand(recordRoot) {
38
43
  try {
39
44
  return loadIgnore(recordRoot);
40
45
  } catch (err) {
41
46
  console.error(err instanceof IgnoreError ? err.message : String(err));
42
- process.exit(1);
47
+ throw new PrintedCaptureFailure();
43
48
  }
44
49
  }
45
50
 
@@ -51,6 +56,7 @@ function loadIgnoreOrExit(recordRoot) {
51
56
  // it does not understand before anything can be written.
52
57
  const VALUE_FLAGS = new Set(["root", "owner", "home", "file", "format", "source"]);
53
58
  const BOOL_FLAGS = new Set([
59
+ "hook",
54
60
  "reset-cursors",
55
61
  "retry-set-aside",
56
62
  "health",
@@ -71,10 +77,12 @@ const USAGE = `capture — land sessions and aw client logs in the turn record.
71
77
  capture one reconciliation pass (sessions + aw logs)
72
78
  capture --sessions-only only session transcripts (Claude Code, pi, codex)
73
79
  capture --aw-only only aw client comm logs
80
+ capture --hook launch detached capture; exit 0 acknowledges
81
+ launch only, never capture completion
74
82
  capture --watch pass now, then re-pass on filesystem change
75
83
  (debounced) and every 15 minutes regardless
76
84
  capture --status show store/stream summary, capture nothing
77
- capture --health [--json] read capture set-aside diagnosis, capture nothing
85
+ capture --health [--json] read offline installation, run and issue diagnosis
78
86
  capture --reset-cursors [--source aw|cc|pi|codex]
79
87
  reset selected source cursors and exit; the next
80
88
  pass reprocesses them with journal deduplication
@@ -132,6 +140,10 @@ Every invocation with no explicit subcommand WRITES. Reconciliation is the
132
140
  capture; hooks and watch only decide when to run it.`;
133
141
 
134
142
  class UsageError extends Error {}
143
+ const hookRequested = process.argv.slice(2).some(arg => arg === "--hook" || arg.startsWith("--hook="));
144
+ function hookLaunchError(error) {
145
+ console.error(`capture hook launch failed: ${String(error.message).replace(/[\r\n]+/g, " ")}`);
146
+ }
135
147
 
136
148
  function parseArgs(argv) {
137
149
  const args = {};
@@ -144,7 +156,7 @@ function parseArgs(argv) {
144
156
  const name = a.slice(2);
145
157
  if (VALUE_FLAGS.has(name)) {
146
158
  const value = argv[++i];
147
- if (value === undefined) throw new UsageError(`${a} needs a value`);
159
+ if (value === undefined || hookRequested && value.startsWith("--")) throw new UsageError(`${a} needs a value`);
148
160
  if (name === "file" && args.file !== undefined) throw new UsageError("one --file per call");
149
161
  args[name] = value;
150
162
  } else if (BOOL_FLAGS.has(name)) {
@@ -156,6 +168,12 @@ function parseArgs(argv) {
156
168
  return args;
157
169
  }
158
170
 
171
+ // Terminal branches return instead of forcing termination while stdout/stderr
172
+ // may still contain queued pipe writes. Returning also prevents reporting from
173
+ // falling through to capture. Lock/child owners finish before returning; watch
174
+ // retains its signal lifecycle. No stream is closed or given an arbitrary delay.
175
+ const finish = code => { process.exitCode = code; };
176
+ async function main() {
159
177
  let args;
160
178
  try {
161
179
  args = parseArgs(process.argv.slice(2));
@@ -163,60 +181,93 @@ try {
163
181
  if (recovery.length > 1) throw new UsageError("choose one recovery or health operation");
164
182
  if (args.source !== undefined && (!args["reset-cursors"] || !CAPTURE_SOURCES.includes(args.source))) throw new UsageError("--source requires --reset-cursors and aw|cc|pi|codex");
165
183
  if (recovery.length && ["home", "file", "format", "watch", "status", "install-hint", "current-roots", "sessions-only", "aw-only"].some(key => args[key])) throw new UsageError("recovery/health cannot be combined with another capture mode");
184
+ if (args.hook && ["home", "file", "format", "watch", "status", "install-hint", "help", "current-roots", "json", ...recovery].some(key => args[key] !== undefined))
185
+ throw new UsageError("--hook cannot be combined with proof, recovery, JSON or another capture mode");
166
186
  } catch (err) {
167
187
  if (!(err instanceof UsageError)) throw err;
188
+ // Claude treats hook exit2 as blocking/model feedback. Explicit hook usage
189
+ // failures report launch failure on stderr/exit1, never that special status.
190
+ if (hookRequested) {
191
+ hookLaunchError(err);
192
+ return finish(1);
193
+ }
168
194
  // --file --json answers JSON even for a usage error: it is for programs.
169
195
  if (process.argv.includes("--json")) {
170
196
  console.log(JSON.stringify({ status: "failed", complete: false, code: "E_USAGE", error: err.message }, null, 2));
171
- process.exit(2);
197
+ return finish(2);
172
198
  }
173
199
  console.error(`capture: ${err.message}\n\n${USAGE}`);
174
- process.exit(2);
200
+ return finish(2);
175
201
  }
176
202
 
177
203
  if (args.help) {
178
204
  console.log(USAGE);
179
- process.exit(0);
205
+ return finish(0);
180
206
  }
181
207
 
182
208
  const root = args.root ?? process.env.TURN_RECORD_ROOT ?? join(homedir(), ".turn-record");
183
209
  const ownerExplicit = args.owner !== undefined || process.env.TURN_RECORD_OWNER !== undefined;
184
210
  const owner = args.owner ?? process.env.TURN_RECORD_OWNER ?? hostname().split(".")[0];
185
211
  const quiet = Boolean(args.quiet || args.json && (args["reset-cursors"] || args["retry-set-aside"]));
186
- const store = new RecordStore(root, { owner });
212
+ const store = args.hook || args.health ? null : new RecordStore(root, { owner });
187
213
 
188
214
  if (args.health) {
189
215
  try {
190
- const health = captureHealth(root);
216
+ // Remedies name the command the person has: `oats` when the kernel runs
217
+ // this script (it imports it, so argv[1] is the kernel's entry, an npm bin
218
+ // symlink named oats included) or handed a node, as setup's remedies do;
219
+ // `turn-record` when run alone.
220
+ const entry = (() => {
221
+ try { return realpathSync(process.argv[1] ?? ""); }
222
+ catch (error) { if (error.code === "ENOENT") return process.argv[1] ?? ""; throw error; }
223
+ })();
224
+ const viaKernel = basename(entry) === "oats.mjs" || isAbsolute(process.env.OATS_NODE_BIN ?? "");
225
+ const health = viaKernel ? captureHealthForDoctor(root) : captureHealth(root);
191
226
  if (args.json) console.log(JSON.stringify(health, null, 2));
192
227
  else {
193
228
  console.log(`capture: ${health.status}`);
194
229
  for (const row of health.rows) console.log(`${row.code}: ${row.message}`);
195
230
  for (const entry of health.backlog.setAside) console.log(`${entry.source}: ${entry.path}:${entry.line ?? "?"} offset ${entry.offset}: ${entry.reason}`);
196
231
  if (health.backlog.truncated) console.log("showing first 100 set-aside inputs");
232
+ for (const entry of health.backlog.failed) console.log(`${entry.stream}: unit starting at byte ${entry.offset} (failing frame unknown): ${entry.reason}; attempts ${entry.attempts}; next retry ${entry.nextRetryAt}`);
233
+ if (health.backlog.failedTruncated) console.log("showing first 100 failed stream units");
197
234
  }
198
235
  } catch (err) {
199
236
  if (args.json) console.log(JSON.stringify({ status: "failed", error: err.message }));
200
237
  else console.error(`capture: ${err.message}`);
201
238
  process.exitCode = 1;
202
239
  }
203
- process.exit(process.exitCode ?? 0);
240
+ return;
204
241
  }
205
242
  if (args["reset-cursors"] || args["retry-set-aside"]) {
206
243
  try {
207
244
  const result = args["reset-cursors"]
208
245
  ? withCaptureLock(() => { resetSourceCursors(root, owner, args.source); return { reset: true, sources: args.source ? [args.source] : CAPTURE_SOURCES }; })
209
- : pass({ retry: true });
246
+ : await pass({ retry: true });
210
247
  if (result.skipped) throw new Error("capture lock held; recovery was not performed");
211
248
  if (process.exitCode) throw new Error("recovery failed to release its capture lock");
212
249
  if (args.json) console.log(JSON.stringify(result));
213
250
  else if (args["reset-cursors"]) log(`capture: reset source cursors (${result.sources.join(", ")})`);
214
251
  } catch (err) {
252
+ if (err instanceof PrintedCaptureFailure) throw err;
215
253
  if (args.json) console.log(JSON.stringify({ status: "failed", complete: false, error: err.message }));
216
254
  else console.error(`capture: ${err.message}`);
217
255
  process.exitCode = 1;
218
256
  }
219
- process.exit(process.exitCode ?? 0);
257
+ return;
258
+ }
259
+
260
+ if (args.hook) {
261
+ try {
262
+ await launchCaptureHook(root, { owner, plan: commandPlan(), indexEnabled: !args["no-index"], trigger: "hook", retrySetAside: false });
263
+ log("capture launched; launch is not completion (see capture --health)");
264
+ } catch (error) {
265
+ hookLaunchError(error);
266
+ process.exitCode = 1;
267
+ }
268
+ // No capture work or discovery in the harness process. The detached owner
269
+ // takes the lock and retains the existing worker lifetime/reaping contract.
270
+ return;
220
271
  }
221
272
 
222
273
  // The owner decides the stream namespace, and turn ids hash it into the
@@ -265,18 +316,9 @@ function withCaptureLock(fn) {
265
316
  lock = acquireCaptureLock(root);
266
317
  // Said by the pass that removed it, never quiet, whether or not it then took the lock: a pass that
267
318
  // died holding the lock is worth knowing about.
268
- if (lock.reclaimed) console.error(`capture: reclaimed ${lock.path} from pid ${lock.reclaimed.pid}, which died (started ${lock.reclaimed.startedAt || "?"})`);
319
+ if (lock.reclaimed) reportReclaimedLock({ path: lock.path, ...lock.reclaimed });
269
320
  } catch (err) {
270
- if (err.lockCleanup) {
271
- const c = err.lockCleanup;
272
- const outcome = c.removed ? "the initializing lock was removed"
273
- : c.reason === "gone" ? "the initializing lock was already gone (removed by another party)"
274
- : c.reason === "replaced" ? (c.owner
275
- ? `the lock now belongs to pid ${c.owner.pid} (started ${c.owner.startedAt || "?"}) and was left alone`
276
- : "the lock directory changed or its identity could not be verified, no owner record was readable, and it was left alone")
277
- : `the initializing lock could NOT be removed${c.error ? ` (${c.error})` : ""}; ${c.recovery}`;
278
- console.error(`capture: could not write the owner record of ${c.path}: ${err.message}; ${outcome}`);
279
- }
321
+ reportLockInitializationFailure(err);
280
322
  throw err;
281
323
  }
282
324
  if (lock.held) {
@@ -303,72 +345,27 @@ function withCaptureLock(fn) {
303
345
  if (!r.released) {
304
346
  // Say what was observed: gone, unreadable (unknown), another owner, or
305
347
  // our own lock that would not go away; never a guess about liveness.
306
- const detail = r.reason === "gone" ? "it was already removed by another party (an operator recovery?); nothing to release"
307
- : r.reason === "not-owner" ? `it now belongs to pid ${r.owner.pid} (started ${r.owner.startedAt || "?"}); left alone`
308
- : r.reason === "unknown-owner" ? `its owner record is missing or unreadable, so it may be an operator removal in progress or a newer pass initializing; left alone; ${r.recovery}`
309
- : `${r.error ? `${r.error}; ` : ""}${r.recovery}`;
310
- console.error(`capture: did not release ${lock.path} (${r.reason}): ${detail}`);
348
+ console.error(`capture: did not release ${lock.path} (${r.reason}): ${releaseDetail(r)}`);
311
349
  process.exitCode = 1;
312
350
  }
313
351
  }
314
352
  }
315
353
 
316
- function pass({ retry = false } = {}) {
317
- // The privacy loader fails closed by exiting; it runs before the lock is
318
- // taken so that exit never leaves the lock behind.
319
- const ignore = loadIgnoreOrExit(root);
320
- return withCaptureLock(() => {
321
- if (retry) retrySetAside(root);
322
- const out = { appended: 0, pending: false };
323
- if (!args["aw-only"]) {
324
- for (const r of captureAllSessions(store, { owner, ignore, collectIssues: false })) {
325
- out.appended += r.appended;
326
- out.pending ||= !r.complete;
327
- const extras = [r.ignored ? `${r.ignored} ignored` : "", r.held ? `${r.held} held` : "", r.incomplete ? `${r.incomplete} incomplete` : ""]
328
- .filter(Boolean)
329
- .join(", ");
330
- log(
331
- `sessions: ${r.sessions} scanned, ${r.appended} new turns in ${r.streams} sessions${extras ? ` (${extras})` : ""} -> ${r.stream}`,
332
- );
333
- }
334
- }
335
- if (!args["sessions-only"]) {
336
- let awEntries = 0;
337
- let awAppended = 0;
338
- let awFailed = 0;
339
- let awFiles = 0;
340
- let awIgnored = 0;
341
- for (const r of captureAwLogs(store, { owner, ignore, collect: false })) {
342
- if (r.ignored) {
343
- awIgnored++;
344
- continue;
345
- }
346
- awFiles++;
347
- awEntries += r.entries;
348
- awAppended += r.appended;
349
- awFailed += r.failed;
350
- out.pending ||= r.failed > 0;
351
- out.appended += r.appended;
352
- if (r.failed) console.error(`aw-log ${r.account}: ${r.failed} entries failed to project`);
353
- }
354
- const ignored = awIgnored ? `, ${awIgnored} ignored` : "";
355
- log(`aw-logs: ${awFiles} files, ${awEntries} entries, ${awAppended} new, ${awFailed} failed${ignored}`);
356
- }
357
- // Index whenever this pass may index, not only when THIS pass appended:
358
- // an append-only pass (--no-index, the hook form) leaves turns behind
359
- // that the next indexing pass must pick up. index.update() walks
360
- // per-stream cursors, so a pass with nothing new is cheap.
361
- if (!args["no-index"]) {
362
- const index = new RecordIndex(store);
363
- try {
364
- index.update();
365
- log("index: updated");
366
- } finally {
367
- index.close();
368
- }
369
- }
370
- return out;
371
- });
354
+ function commandPlan() {
355
+ // Copy caller selection before spawning; only the admitted worker resolves
356
+ // the capture roots. Both selection flags retain their existing empty union.
357
+ const sources = CAPTURE_SOURCES.filter(source => source === "aw" ? !args["sessions-only"] : !args["aw-only"]);
358
+ return captureDefaultRootPlan({ home: homedir(), cwd: process.cwd(), env: process.env, sources });
359
+ }
360
+
361
+ async function pass({ retry = false, trigger = "manual" } = {}) {
362
+ // Privacy refusal unwinds to the command boundary before the lock is
363
+ // taken, leaving no admitted child or lock. The worker independently
364
+ // reloads privacy rules; this preflight supplies the existing actionable error.
365
+ loadIgnoreForCommand(root);
366
+ // Recovery JSON keeps its existing small shape. Never read a later status
367
+ // file after releasing the lock to reconstruct this pass's counters.
368
+ return captureCommandPass(root, { owner, plan: commandPlan(), indexEnabled: !args["no-index"], trigger, retrySetAside: retry }, { log });
372
369
  }
373
370
 
374
371
  /** A final capture of exact files, one batch per format, under the lock: counts into `outcome`, issues into
@@ -527,36 +524,40 @@ function fileCapture() {
527
524
  } finally { pinned.close(); }
528
525
  }
529
526
 
530
- if (args.file !== undefined || args.format !== undefined || args.json) process.exit(fileCapture());
527
+ if (args.file !== undefined || args.format !== undefined || args.json) return finish(fileCapture());
531
528
 
532
529
  if (args["install-hint"]) {
533
- const self = new URL(import.meta.url).pathname;
530
+ const self = new URL("./capture-hook.mjs", import.meta.url).pathname;
534
531
  console.log(`Add to Claude Code settings.json to capture on session stop/end:
535
532
 
536
533
  {
537
534
  "hooks": {
538
- "Stop": [{"hooks": [{"type": "command", "command": "node ${self} --sessions-only --no-index --quiet"}]}],
539
- "SessionEnd": [{"hooks": [{"type": "command", "command": "node ${self} --sessions-only --no-index --quiet"}]}]
535
+ "Stop": [{"hooks": [{"type": "command", "command": "node ${self} --sessions-only --no-index --quiet", "async": false, "timeout": 10}]}],
536
+ "SessionEnd": [{"hooks": [{"type": "command", "command": "node ${self} --sessions-only --no-index --quiet", "async": false, "timeout": 10}]}]
540
537
  }
541
538
  }
542
539
 
543
- Hook passes append turns only (--no-index); the search index is updated by
540
+ Hook acknowledgement means capture launched, not capture completed. The
541
+ harness waits only for the launcher (async:false, timeout:10); its detached
542
+ supervisor inherits no harness output pipes. Hook failures exit 1, never 2.
543
+ These hook passes append turns only (--no-index); the search index is updated by
544
544
  capture --watch (every 15 minutes and on change) or by a plain capture pass.
545
- One pass runs per record root at a time: a hook pass that finds another
546
- running exits at once, and a dropped hook is recovered by any later pass.`);
547
- process.exit(0);
545
+ One pass runs per record root at a time: the detached supervisor skips an
546
+ overlap; launch acknowledgement does not report that later decision. A dropped
547
+ hook is recovered by any later pass.`);
548
+ return finish(0);
548
549
  }
549
550
 
550
551
  if (args.status) {
551
552
  console.log(`root: ${root}\nowner: ${owner}`);
552
- const ignore = loadIgnoreOrExit(root);
553
+ const ignore = loadIgnoreForCommand(root);
553
554
  if (ignore.size > 0) {
554
555
  console.log(`ignore: ${ignore.size} pattern${ignore.size === 1 ? "" : "s"} (${ignoreFilePath(root)})`);
555
556
  }
556
557
  for (const streamId of store.listStreams()) {
557
558
  console.log(` ${streamId}: ${store.readStream(streamId).length} turns`);
558
559
  }
559
- process.exit(0);
560
+ return finish(0);
560
561
  }
561
562
 
562
563
  // One instance home: capture its own sessions and report them with exact
@@ -629,39 +630,57 @@ if (args.home) {
629
630
 
630
631
  warnOnStrangerOwner();
631
632
  try {
632
- pass();
633
+ await pass({ trigger: args.watch ? "watch" : "manual" });
633
634
  } catch (err) {
635
+ if (err instanceof PrintedCaptureFailure) throw err;
634
636
  // The lock's finally has run by now; one line, then the status.
635
637
  console.error(`capture pass failed: ${err.message}`);
636
- process.exit(1);
638
+ return finish(1);
637
639
  }
638
640
 
639
641
  if (args.watch) {
640
- const roots = [
641
- ...Object.values(SESSION_FORMATS).flatMap((f) => f.defaultRoots()),
642
- defaultCommLogDir(),
643
- ];
644
- let timer = null;
645
- const schedule = () => {
646
- if (timer) clearTimeout(timer);
647
- timer = setTimeout(() => {
648
- timer = null;
649
- try {
650
- pass();
651
- } catch (err) {
652
- console.error(`capture pass failed: ${err.message}`);
653
- }
654
- }, 2000);
655
- };
656
- for (const dir of roots) {
642
+ const queue = captureWatchQueue(() => pass({ trigger: "watch" }), {
643
+ onError: err => {
644
+ process.exitCode = 1;
645
+ // A privacy refusal used to terminate immediately. It still stops the
646
+ // watch, before child admission, but lets its already printed error drain.
647
+ if (err instanceof PrintedCaptureFailure) { stop(); return; }
648
+ console.error(`capture pass failed: ${err.message}`);
649
+ },
650
+ });
651
+ const watchers = [], plan = commandPlan();
652
+ // These are notification hints only. Their enumeration has parent metadata
653
+ // cost, supplies no capture authority, and may fail independently of a pass.
654
+ for (const source of plan.sources) {
657
655
  try {
658
- watch(dir, { recursive: true }, schedule);
659
- log(`watching ${dir}`);
660
- } catch (err) {
661
- console.error(`cannot watch ${dir}: ${err.message}`);
662
- }
656
+ for (const dir of resolveCaptureDefaultRoots(plan, source)) {
657
+ try {
658
+ const watcher = watch(dir, { recursive: true }, () => queue.schedule());
659
+ watcher.on("error", err => { console.error(`cannot watch ${dir}: ${err.message}`); watcher.close(); });
660
+ watchers.push(watcher);
661
+ log(`watching ${dir}`);
662
+ } catch (err) { console.error(`cannot watch ${dir}: ${err.message}`); }
663
+ }
664
+ } catch (err) { console.error(`cannot select ${source} watch hints: ${err.message}`); }
663
665
  }
664
- setInterval(schedule, 15 * 60 * 1000); // reconcile even if events were missed
666
+ const interval = setInterval(() => queue.schedule(), 15 * 60 * 1000);
667
+ const stop = () => {
668
+ queue.close(); clearInterval(interval);
669
+ for (const watcher of watchers) watcher.close();
670
+ process.off("SIGINT", stop); process.off("SIGTERM", stop);
671
+ // If a pass is active its supervisor also observes this signal and owns
672
+ // child termination/reaping and lock release. No new pass may start.
673
+ };
674
+ process.on("SIGINT", stop); process.on("SIGTERM", stop);
675
+ }
676
+
677
+ }
665
678
  }
666
679
 
680
+ try { await main(); }
681
+ catch (error) {
682
+ if (!(error instanceof PrintedCaptureFailure)) throw error;
683
+ // Privacy already printed its one actionable error. No duplicate diagnostic
684
+ // and no later mode may run, but both output pipes can finish normally.
685
+ process.exitCode = 1;
667
686
  }