@awebai/oats 0.61.0 → 0.63.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 (90) hide show
  1. package/README.md +1 -1
  2. package/bin/oats.mjs +27 -12
  3. package/docs/capabilities.md +1 -1
  4. package/docs/desktop-cli-api.md +30 -2
  5. package/docs/execution-targets.md +89 -4
  6. package/docs/implementation.md +2 -1
  7. package/docs/named-test-runs.md +382 -0
  8. package/docs/official-catalog.md +1 -1
  9. package/docs/packages.md +5 -5
  10. package/docs/release-lane.md +13 -0
  11. package/docs/release-notes/v0.62.0.md +223 -0
  12. package/docs/release-notes/v0.63.0.md +135 -0
  13. package/docs/souls-and-instances.md +6 -1
  14. package/docs/upgrading.md +135 -11
  15. package/docs/workspaces.md +1 -1
  16. package/lib/core.mjs +73 -23
  17. package/lib/doctor-capture.mjs +35 -0
  18. package/lib/session-viewer.mjs +86 -7
  19. package/lib/tree-copy.mjs +188 -7
  20. package/package-catalog.json +1 -1
  21. package/package.json +1 -1
  22. package/packages/client/cli-locator.mjs +2 -2
  23. package/packages/record/README.md +87 -13
  24. package/packages/record/bin/capture-hook.mjs +8 -0
  25. package/packages/record/bin/capture.mjs +200 -139
  26. package/packages/record/bin/recall.mjs +8 -3
  27. package/packages/record/bin/setup.mjs +116 -225
  28. package/packages/record/bin/turn-record.mjs +2 -2
  29. package/packages/record/docs/capture-service.md +1527 -28
  30. package/packages/record/docs/capture-status.schema.json +429 -12
  31. package/packages/record/lib/capture-admission.mjs +82 -0
  32. package/packages/record/lib/capture-aw-unit.mjs +137 -0
  33. package/packages/record/lib/capture-aw.mjs +31 -12
  34. package/packages/record/lib/capture-budget.mjs +31 -0
  35. package/packages/record/lib/capture-cc.mjs +39 -6
  36. package/packages/record/lib/capture-cleanup-queue.mjs +135 -0
  37. package/packages/record/lib/capture-cleanup-work.mjs +77 -0
  38. package/packages/record/lib/capture-command-operation.mjs +37 -0
  39. package/packages/record/lib/capture-command-output.mjs +62 -0
  40. package/packages/record/lib/capture-command-worker.mjs +6 -0
  41. package/packages/record/lib/capture-command.mjs +65 -0
  42. package/packages/record/lib/capture-completion.mjs +152 -0
  43. package/packages/record/lib/capture-context.mjs +50 -0
  44. package/packages/record/lib/capture-default-roots.mjs +30 -0
  45. package/packages/record/lib/capture-discovery.mjs +114 -0
  46. package/packages/record/lib/capture-failures.mjs +45 -0
  47. package/packages/record/lib/capture-health-doctor.mjs +13 -0
  48. package/packages/record/lib/capture-health-installation.mjs +117 -0
  49. package/packages/record/lib/capture-health.mjs +116 -0
  50. package/packages/record/lib/capture-hook-ownership.mjs +58 -0
  51. package/packages/record/lib/capture-hook-runner.mjs +17 -0
  52. package/packages/record/lib/capture-hook.mjs +26 -0
  53. package/packages/record/lib/capture-index-inventory.mjs +205 -0
  54. package/packages/record/lib/capture-index-outcomes.mjs +113 -0
  55. package/packages/record/lib/capture-index-reset.mjs +110 -0
  56. package/packages/record/lib/capture-index-work.mjs +77 -0
  57. package/packages/record/lib/capture-issue-preparation.mjs +73 -0
  58. package/packages/record/lib/capture-issues.mjs +15 -2
  59. package/packages/record/lib/capture-lock.mjs +137 -17
  60. package/packages/record/lib/capture-native-unit.mjs +322 -0
  61. package/packages/record/lib/capture-pass.mjs +116 -0
  62. package/packages/record/lib/capture-recovery-snapshot.mjs +182 -0
  63. package/packages/record/lib/capture-retained-scratch.mjs +213 -0
  64. package/packages/record/lib/capture-retry.mjs +102 -0
  65. package/packages/record/lib/capture-run.mjs +125 -0
  66. package/packages/record/lib/capture-scratch.mjs +12 -3
  67. package/packages/record/lib/capture-service-definition.mjs +104 -0
  68. package/packages/record/lib/capture-service-install.mjs +362 -0
  69. package/packages/record/lib/capture-service-ownership.mjs +137 -0
  70. package/packages/record/lib/capture-service-runner.mjs +18 -0
  71. package/packages/record/lib/capture-small-snapshot.mjs +85 -0
  72. package/packages/record/lib/capture-source-discovery.mjs +319 -0
  73. package/packages/record/lib/capture-source-queue.mjs +199 -0
  74. package/packages/record/lib/capture-source-work.mjs +85 -0
  75. package/packages/record/lib/capture-state.mjs +16 -71
  76. package/packages/record/lib/capture-status.mjs +171 -0
  77. package/packages/record/lib/capture-supervisor.mjs +136 -0
  78. package/packages/record/lib/capture-watch.mjs +32 -0
  79. package/packages/record/lib/capture-work-session.mjs +241 -0
  80. package/packages/record/lib/capture-worker.mjs +74 -0
  81. package/packages/record/lib/derived-state.mjs +58 -17
  82. package/packages/record/lib/file-lines.mjs +22 -6
  83. package/packages/record/lib/formats.mjs +4 -3
  84. package/packages/record/lib/index-capture.mjs +97 -0
  85. package/packages/record/lib/index-db.mjs +121 -66
  86. package/packages/record/lib/index-reset.mjs +19 -0
  87. package/packages/record/lib/store.mjs +46 -14
  88. package/packages/record/lib/transcript-prefix.mjs +125 -0
  89. package/skills/oats-getting-started/SKILL.md +1 -1
  90. package/docs/macos-test-runs.md +0 -246
@@ -5,8 +5,7 @@
5
5
  // 1. Stop + SessionEnd capture hooks into every ~/.claude*/settings.json
6
6
  // that exists (merged, never clobbered; unparseable files are skipped
7
7
  // loudly and left untouched);
8
- // 2. a background watcher service — launchd agent on macOS, systemd user
9
- // unit on Linux (printed instructions elsewhere);
8
+ // 2. a periodic bounded service — launchd on macOS, systemd user timer on Linux;
10
9
  // 3. then runs the first capture pass (the expensive one) unless --dry-run.
11
10
  //
12
11
  // Everything is derived from the running install: scripts resolved relative
@@ -16,113 +15,66 @@
16
15
  // an upgrade of Node), else process.execPath: see recordedNode().
17
16
  //
18
17
  // --owner <name> stream owner (default: LocalHostName on macOS, hostname)
18
+ // --root <dir> explicit record root, also persisted into hooks/services
19
+ // --replace-service explicitly replace foreign/disabled named capture service
19
20
  // --no-hooks skip step 1
20
21
  // --no-service skip step 2
21
22
  // --dry-run print what would change, change nothing
22
23
 
23
- import { execFileSync, spawnSync } from "node:child_process";
24
- import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
24
+ import { isCaptureHook } from "../lib/capture-hook-ownership.mjs";
25
+ import { execFileSync } from "node:child_process";
26
+ import { readdirSync } from "node:fs";
25
27
  import { homedir, hostname, platform } from "node:os";
26
- import { dirname, isAbsolute, join } from "node:path";
28
+ import { dirname, isAbsolute, join, resolve } from "node:path";
27
29
  import { fileURLToPath } from "node:url";
28
-
29
- // Config files deserve the same crash safety as the store's objects:
30
- // write-then-rename, never a partial write in place.
31
- function writeFileAtomic(path, content) {
32
- const tmp = path + ".tmp-" + process.pid;
33
- writeFileSync(tmp, content);
34
- renameSync(tmp, path);
35
- }
30
+ import { captureDefaultRootPlan } from "../lib/capture-default-roots.mjs";
31
+ import { captureCommandPass } from "../lib/capture-command-output.mjs";
32
+ import { captureCommandEntry } from "../lib/capture-command.mjs";
33
+ import { IgnoreError, loadIgnore } from "../lib/ignore.mjs";
34
+ import { preflightCaptureService, applyCaptureService, captureSetupSnapshot, recheckCaptureSetup, writeCaptureSetup } from "../lib/capture-service-install.mjs";
35
+ import { captureRemedyCommand } from "../lib/capture-health.mjs";
36
36
 
37
37
  // The node written into what outlives this process: the hooks and the
38
38
  // service. `oats setup` hands in the kernel's answer for a node that survives
39
39
  // an upgrade of Node, as OATS_NODE_BIN; this package has no such rule of its
40
40
  // own, so run alone it records the node it runs under. What runs at once (the
41
41
  // first capture pass) runs under process.execPath whatever is recorded.
42
- function recordedNode(env = process.env) {
42
+ function handedNode(env = process.env) {
43
43
  const handed = env.OATS_NODE_BIN;
44
- return typeof handed === "string" && isAbsolute(handed) ? handed : process.execPath;
44
+ return typeof handed === "string" && isAbsolute(handed) ? handed : null;
45
45
  }
46
+ function recordedNode(env = process.env) { return handedNode(env) ?? process.execPath; }
46
47
 
47
48
  const HERE = dirname(fileURLToPath(import.meta.url));
48
49
  const NODE = recordedNode();
50
+ // Recoveries name the command a person runs, never this file: only a rerun
51
+ // through `oats setup` selects its stable node again. Health's wording function
52
+ // decides the words; setup's input to it is whether a node was handed in
53
+ // (OATS_NODE_BIN), which `oats setup` always does and instance shells also
54
+ // carry, so either printed command records that same node.
55
+ const SETUP_COMMAND = `${captureRemedyCommand(Boolean(handedNode()))} setup`;
49
56
  const CAPTURE = join(HERE, "capture.mjs");
57
+ // The hooks run their own entry, which a rolled-back install lacks: see it.
58
+ const CAPTURE_HOOK = join(HERE, "capture-hook.mjs");
50
59
 
51
- // Each path is written for the reader it has: a shell (the hook's command),
52
- // systemd (ExecStart) or an XML parser (the plist). A path of plain
53
- // characters is written bare by all three, so the files of an install that
54
- // needs no quoting do not change.
60
+ // Hooks use POSIX shell words. The separate definition builder owns the
61
+ // manager-specific XML/systemd representations.
55
62
  const SHELL_PLAIN = /^[A-Za-z0-9_./:@%+,-]+$/;
56
- const SYSTEMD_PLAIN = /^[A-Za-z0-9_./:@+,-]+$/;
57
63
 
58
64
  // A shell word: POSIX single quotes, a quote itself as '\''.
59
65
  function shellWord(value) {
60
66
  return SHELL_PLAIN.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
61
67
  }
62
68
 
63
- // The words of a command as /bin/sh reads them, for what setup writes: plain
64
- // characters, single-quoted runs and \' for a quote, adjacent pieces joined
65
- // into one word, words apart by spaces or tabs. null when the command holds
66
- // anything else outside quotes (an expansion, an operator, a redirection, a
67
- // double quote, a newline, which ends a command) or a quote left open: the
68
- // shell would do more with it than run those words, so it is not read.
69
- //
70
- // Any character above U+007F is part of a word too, as an earlier setup
71
- // wrote it bare in a path (shellWord now quotes it). bash, dash and zsh end
72
- // a word only at a space, a tab, a newline or an operator, all ASCII, so a
73
- // command of such words carries nothing a rewrite would lose. POSIX lets a
74
- // shell end a word at any blank of its locale (U+3000, say): such a shell
75
- // would see one more argument of the same command, which a rewrite does not
76
- // lose either, so no character above U+007F is refused.
77
- function shellWords(command) {
78
- const words = [];
79
- let word = null;
80
- for (let i = 0; i < command.length; ) {
81
- const c = command[i];
82
- if (c === " " || c === "\t") {
83
- if (word !== null) words.push(word);
84
- word = null;
85
- i++;
86
- } else if (c === "'") {
87
- const end = command.indexOf("'", i + 1);
88
- if (end < 0) return null;
89
- word = (word ?? "") + command.slice(i + 1, end);
90
- i = end + 1;
91
- } else if (c === "\\" && command[i + 1] === "'") {
92
- word = (word ?? "") + "'";
93
- i += 2;
94
- } else if (SHELL_PLAIN.test(c) || c > "\x7F") {
95
- word = (word ?? "") + c;
96
- i++;
97
- } else return null;
98
- }
99
- if (word !== null) words.push(word);
100
- return words;
101
- }
102
-
103
- // A word of a systemd command line: `%` is a specifier (`%%`), a
104
- // double-quoted string protects spaces, backslash and double quote are
105
- // escaped. In an argument `${VAR}` is substituted and a literal dollar is
106
- // `$$`; the executable is not substituted, and `$$` there names another file.
107
- // (systemd itself starts no executable whose path holds a quote or a
108
- // backslash, however it is written: its refusal is what setup reports.)
109
- function systemdWord(value, { argument = false } = {}) {
110
- if (SYSTEMD_PLAIN.test(value)) return value;
111
- let v = value.replace(/%/g, "%%").replace(/\\/g, "\\\\").replace(/"/g, '\\"');
112
- if (argument) v = v.replace(/\$/g, "$$$$");
113
- return `"${v}"`;
114
- }
115
-
116
- // Text of an XML element.
117
- function xmlText(value) {
118
- return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
119
- }
120
-
121
69
  function parseArgs(argv) {
122
70
  const args = {};
123
71
  for (let i = 0; i < argv.length; i++) {
124
72
  const a = argv[i];
125
- if (a === "--owner") args.owner = argv[++i];
73
+ if (a === "--owner" || a === "--root") {
74
+ const value = argv[++i];
75
+ if (!value || value.startsWith("--") || value.includes("\0")) { console.error(`${a} requires a value`); process.exit(2); }
76
+ args[a.slice(2)] = value;
77
+ }
126
78
  else if (a.startsWith("--")) args[a.slice(2)] = true;
127
79
  else {
128
80
  console.error(`unknown argument ${a}`);
@@ -147,6 +99,7 @@ function defaultOwner() {
147
99
  const args = parseArgs(process.argv.slice(2));
148
100
  const owner = args.owner ?? defaultOwner();
149
101
  const dry = Boolean(args["dry-run"]);
102
+ const root = resolve(args.root ?? process.env.TURN_RECORD_ROOT ?? join(homedir(), ".turn-record"));
150
103
 
151
104
  // The owner is interpolated into a persisted shell command, a launchd
152
105
  // plist, and a systemd unit. Restricting it to the stream-id character
@@ -159,8 +112,10 @@ if (!/^[A-Za-z0-9._-]+$/.test(owner)) {
159
112
  process.exit(2);
160
113
  }
161
114
 
162
- const hookCommand = `${shellWord(NODE)} ${shellWord(CAPTURE)} --owner ${owner} --quiet`;
163
- const HOOK = { type: "command", command: hookCommand, async: true, timeout: 120 };
115
+ const hookCommand = `${shellWord(NODE)} ${shellWord(CAPTURE_HOOK)} --owner ${owner} --quiet --root ${shellWord(root)}`;
116
+ // The harness waits only for OS launch acknowledgement. Capture itself is
117
+ // detached and owns no harness pipes; these are launcher, not worker limits.
118
+ const HOOK = { type: "command", command: hookCommand, async: false, timeout: 10 };
164
119
 
165
120
  console.log(`owner: ${owner}`);
166
121
  console.log(`node: ${NODE}`);
@@ -170,19 +125,22 @@ console.log(`node: ${NODE}`);
170
125
  function settingsFiles() {
171
126
  const home = homedir();
172
127
  const files = [];
173
- for (const name of readdirSync(home).sort()) {
174
- if (!name.startsWith(".claude")) continue;
175
- const path = join(home, name, "settings.json");
176
- if (existsSync(path)) files.push(path);
128
+ for (const entry of readdirSync(home, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
129
+ if (!entry.name.startsWith(".claude") || (!entry.isDirectory() && !entry.isSymbolicLink())) continue;
130
+ const path = join(home, entry.name, "settings.json");
131
+ if (captureSetupSnapshot(path).kind !== "absent") files.push(path);
177
132
  }
178
133
  return files;
179
134
  }
180
135
 
181
- function installHooks() {
136
+ function prepareHooks() {
137
+ const edits = [];
182
138
  for (const path of settingsFiles()) {
139
+ const snapshot = captureSetupSnapshot(path);
140
+ if (snapshot.kind !== "file") throw new Error(`cannot safely read hook settings ${path}; preserve it and use --no-hooks`);
183
141
  let settings;
184
142
  try {
185
- settings = JSON.parse(readFileSync(path, "utf8"));
143
+ settings = JSON.parse(snapshot.bytes.toString("utf8"));
186
144
  } catch (err) {
187
145
  console.error(`SKIP ${path}: not valid JSON (${err.message}) — fix it and re-run setup`);
188
146
  continue;
@@ -194,11 +152,12 @@ function installHooks() {
194
152
  let changed = false;
195
153
  settings.hooks = settings.hooks ?? {};
196
154
  // Ours = a command whose STRUCTURE matches what setup generates:
197
- // "<node> <...>/capture.mjs ... --owner ... --quiet ...". Matching by
155
+ // "<node> <...>/capture.mjs ... --owner ... --quiet ...", or the hook
156
+ // entry capture-hook.mjs in place of capture.mjs. Matching by
198
157
  // shape rather than this install's absolute path means a moved install
199
158
  // (npm upgrade, checkout -> global) updates the old hook in place
200
159
  // instead of stacking a second one. The structural requirements (script
201
- // is the second token and ends in /capture.mjs; both flags present as
160
+ // is the second token and ends in /capture.mjs or /capture-hook.mjs; both flags present as
202
161
  // whole tokens) keep it from firing on unrelated hooks that merely
203
162
  // mention similar words; when in doubt it errs toward appending a new
204
163
  // group, never toward overwriting someone else's command.
@@ -210,28 +169,19 @@ function installHooks() {
210
169
  // every command written before paths were quoted, except one with `=`,
211
170
  // `~` or another ASCII character outside the plain set left bare in a
212
171
  // path, or with a space in one, which was split.
213
- const ours = (h) => {
214
- if (h?.type !== "command") return false;
215
- const tokens = shellWords(String(h.command));
216
- return (
217
- tokens !== null &&
218
- tokens.length >= 2 &&
219
- tokens[1].endsWith("/capture.mjs") &&
220
- tokens.includes("--owner") &&
221
- tokens.includes("--quiet")
222
- );
223
- };
224
172
  for (const event of ["Stop", "SessionEnd"]) {
225
173
  const groups = (settings.hooks[event] = settings.hooks[event] ?? []);
226
174
  let found = false;
227
- // Every hook that is ours gets the current command and none is removed,
175
+ // Every hook that is ours gets the current command/scheduling fields; none is removed,
228
176
  // two in one event included: the shape is not proof of ownership.
229
177
  for (const group of groups) {
230
178
  for (const hook of group.hooks ?? []) {
231
- if (!ours(hook)) continue;
179
+ if (!isCaptureHook(hook)) continue;
232
180
  found = true;
233
- if (hook.command !== hookCommand) {
181
+ if (hook.command !== hookCommand || hook.async !== HOOK.async || hook.timeout !== HOOK.timeout) {
234
182
  hook.command = hookCommand;
183
+ hook.async = HOOK.async;
184
+ hook.timeout = HOOK.timeout;
235
185
  changed = true;
236
186
  }
237
187
  }
@@ -241,134 +191,75 @@ function installHooks() {
241
191
  changed = true;
242
192
  }
243
193
  }
244
- if (!changed) {
245
- console.log(`hooks: ${path} already installed`);
246
- } else if (dry) {
247
- console.log(`hooks: would install Stop+SessionEnd capture in ${path}`);
248
- } else {
249
- writeFileAtomic(path, JSON.stringify(settings, null, 2) + "\n");
250
- console.log(`hooks: installed Stop+SessionEnd capture in ${path}`);
251
- }
194
+ edits.push({ snapshot, contents: changed ? JSON.stringify(settings, null, 2) + "\n" : null });
252
195
  }
196
+ return edits;
253
197
  }
254
198
 
255
- // ----------------------------------------------------------------- service
256
-
257
- function installServiceDarwin() {
258
- const label = "ai.aweb.turn-record-capture";
259
- const path = join(homedir(), "Library", "LaunchAgents", `${label}.plist`);
260
- const logPath = join(homedir(), "Library", "Logs", "turn-record-capture.log");
261
- const plist = `<?xml version="1.0" encoding="UTF-8"?>
262
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
263
- <plist version="1.0">
264
- <dict>
265
- <key>Label</key>
266
- <string>${label}</string>
267
- <key>ProgramArguments</key>
268
- <array>
269
- <string>${xmlText(NODE)}</string>
270
- <string>${xmlText(CAPTURE)}</string>
271
- <string>--watch</string>
272
- <string>--owner</string>
273
- <string>${owner}</string>
274
- </array>
275
- <key>RunAtLoad</key>
276
- <true/>
277
- <key>KeepAlive</key>
278
- <true/>
279
- <key>ThrottleInterval</key>
280
- <integer>60</integer>
281
- <key>StandardOutPath</key>
282
- <string>${xmlText(logPath)}</string>
283
- <key>StandardErrorPath</key>
284
- <string>${xmlText(logPath)}</string>
285
- </dict>
286
- </plist>
287
- `;
288
- const current = existsSync(path) ? readFileSync(path, "utf8") : null;
289
- if (current === plist) {
290
- console.log(`service: ${path} already installed`);
291
- return;
292
- }
293
- if (dry) {
294
- console.log(`service: would ${current ? "update" : "install"} launchd agent at ${path}`);
295
- return;
296
- }
297
- mkdirSync(dirname(path), { recursive: true });
298
- writeFileAtomic(path, plist);
299
- const uid = process.getuid();
300
- spawnSync("launchctl", ["bootout", `gui/${uid}/${label}`], { stdio: "ignore" });
301
- const boot = spawnSync("launchctl", ["bootstrap", `gui/${uid}`, path], { encoding: "utf8" });
302
- if (boot.status === 0) {
303
- console.log(`service: launchd agent ${label} running (log: ${logPath})`);
304
- } else {
305
- console.error(
306
- `service: wrote ${path} but launchctl bootstrap failed (${(boot.stderr || "").trim()}); ` +
307
- `load it manually: launchctl bootstrap gui/${uid} ${shellWord(path)}`,
308
- );
309
- }
199
+ // --------------------------------------------------------------------- run
200
+ // Once setup starts changing things it ends with one setup summary: fixed
201
+ // labels, one item per line, the same order on every run, so a nonzero exit
202
+ // never reads as "nothing happened". It is held as one value.
203
+ const oneLine = text => String(text).replace(/\s*[\r\n]+\s*/g, " ");
204
+ const rerun = `${SETUP_COMMAND} --owner ${shellWord(owner)} --root ${shellWord(root)}${args["no-hooks"] ? " --no-hooks" : ""}${args["replace-service"] ? " --replace-service" : ""}`;
205
+ const summary = { hooks: [], firstPass: "not run", service: "not changed", serviceChanges: [], remedy: "none" };
206
+ function printSummary(failed) {
207
+ console.log(["setup summary:", ` status: ${failed ? "incomplete (exit 1)" : "complete"}`,
208
+ ...(summary.hooks.length ? summary.hooks : ["none"]).map(path => ` hooks written: ${path}`),
209
+ ` first capture pass: ${summary.firstPass}`, ` service: ${summary.service}`,
210
+ // What a failed service apply had already changed, in order.
211
+ ...summary.serviceChanges.map(change => ` service changed: ${oneLine(change)}`), ` remedy: ${summary.remedy}`].join("\n"));
310
212
  }
311
-
312
- function installServiceLinux() {
313
- const path = join(homedir(), ".config", "systemd", "user", "turn-record-capture.service");
314
- const unit = `[Unit]
315
- Description=turn-record capture watcher
316
-
317
- [Service]
318
- ExecStart=${systemdWord(NODE)} ${systemdWord(CAPTURE, { argument: true })} --watch --owner ${owner}
319
- Restart=always
320
- RestartSec=60
321
-
322
- [Install]
323
- WantedBy=default.target
324
- `;
325
- const current = existsSync(path) ? readFileSync(path, "utf8") : null;
326
- if (current === unit) {
327
- console.log(`service: ${path} already installed`);
328
- return;
329
- }
330
- if (dry) {
331
- console.log(`service: would ${current ? "update" : "install"} systemd user unit at ${path}`);
332
- return;
213
+ let captureStarted = false, changing = false, serviceFailure = null;
214
+ try {
215
+ const hooks = args["no-hooks"] ? [] : prepareHooks();
216
+ const plan = captureDefaultRootPlan({ home: homedir(), cwd: process.cwd(), env: process.env });
217
+ // Every target and applicable manager is inspected before hook/service or
218
+ // capture mutations. --no-service never even reads named service files.
219
+ let service = null;
220
+ if (!args["no-service"]) {
221
+ if (["darwin", "linux"].includes(platform())) service = preflightCaptureService({ platform: platform(), node: NODE,
222
+ request: { root, owner, plan }, setupCommand: SETUP_COMMAND, dry, replace: Boolean(args["replace-service"]), noHooks: Boolean(args["no-hooks"]) });
223
+ else {
224
+ console.log(`service: no service template for ${platform()}; run this in the background yourself:\n` +
225
+ ` ${shellWord(NODE)} ${shellWord(CAPTURE)} --watch --owner ${owner} --root ${shellWord(root)}`);
226
+ summary.service = `no service template for ${platform()}`;
227
+ }
228
+ } else summary.service = "skipped (--no-service)";
229
+ if (!dry) loadIgnore(root);
230
+ const createdParents = new Map();
231
+ for (const hook of hooks) recheckCaptureSetup(hook.snapshot, createdParents);
232
+ changing = !dry;
233
+ // A service failure after preflight leaves hooks and the bounded first pass
234
+ // to run: capture is never skipped for it, and the exit still reports it.
235
+ if (service) {
236
+ try { applyCaptureService(service, createdParents); summary.service = "scheduled"; }
237
+ catch (error) {
238
+ if (dry) throw error;
239
+ serviceFailure = error; summary.service = `failed: ${oneLine(error.message)}`; summary.serviceChanges = error.applied ?? [];
240
+ console.error(`setup: service failed: ${error.message}`);
241
+ }
333
242
  }
334
- mkdirSync(dirname(path), { recursive: true });
335
- writeFileAtomic(path, unit);
336
- const enable = spawnSync(
337
- "systemctl",
338
- ["--user", "enable", "--now", "turn-record-capture.service"],
339
- { encoding: "utf8" },
340
- );
341
- if (enable.status === 0) {
342
- console.log("service: systemd user unit turn-record-capture running");
343
- } else {
344
- console.error(
345
- `service: wrote ${path} but systemctl enable failed (${(enable.stderr || "").trim()}); ` +
346
- "enable it manually: systemctl --user enable --now turn-record-capture.service",
347
- );
243
+ for (const { snapshot, contents } of hooks) {
244
+ if (!contents) console.log(`hooks: ${snapshot.path} already installed`);
245
+ else if (dry) console.log(`hooks: would install Stop+SessionEnd capture in ${snapshot.path}`);
246
+ else { writeCaptureSetup(snapshot, contents, createdParents); summary.hooks.push(snapshot.path); console.log(`hooks: installed Stop+SessionEnd capture in ${snapshot.path}`); }
348
247
  }
349
- }
350
-
351
- function installService() {
352
- const os = platform();
353
- if (os === "darwin") installServiceDarwin();
354
- else if (os === "linux") installServiceLinux();
248
+ if (dry) console.log("dry run: no first capture pass");
355
249
  else {
356
- console.log(
357
- `service: no service template for ${os}; run this in the background yourself:\n` +
358
- ` ${shellWord(NODE)} ${shellWord(CAPTURE)} --watch --owner ${owner}`,
359
- );
250
+ console.log("running first capture pass (the initial one can take minutes)...");
251
+ captureStarted = true;
252
+ try {
253
+ const pass = await captureCommandPass(root, { owner, plan, indexEnabled: true, trigger: "setup", retrySetAside: false }, { entry: captureCommandEntry() });
254
+ summary.firstPass = pass.skipped ? "skipped: another pass holds the record root" : `appended ${pass.appended}, pending ${pass.pending ? "yes" : "no"}`;
255
+ } catch (error) { summary.firstPass = `failed: ${oneLine(error.message)}`; throw error; }
360
256
  }
257
+ if (serviceFailure) { summary.remedy = `rerun ${rerun}`; process.exitCode = 1; }
258
+ } catch (error) {
259
+ console.error(error instanceof IgnoreError ? error.message : `${captureStarted ? "capture pass" : "setup"} failed: ${error.message}`);
260
+ if (changing) summary.remedy = captureStarted && !serviceFailure ? `inspect ${captureRemedyCommand(Boolean(handedNode()))} capture --health --json, then rerun ${rerun}` : `rerun ${rerun}`;
261
+ else if (!captureStarted && !(error instanceof IgnoreError) && !error.code?.startsWith("E_CAPTURE_SERVICE_"))
262
+ console.error(`setup recovery: inspect the reported files/manager state, then retry ${rerun}; use --no-service to preserve the existing manager service`);
263
+ process.exitCode = 1;
361
264
  }
362
-
363
- // --------------------------------------------------------------------- run
364
-
365
- if (!args["no-hooks"]) installHooks();
366
- if (!args["no-service"]) installService();
367
-
368
- if (dry) {
369
- console.log("dry run: no first capture pass");
370
- } else {
371
- console.log("running first capture pass (the initial one can take minutes)...");
372
- const pass = spawnSync(process.execPath, [CAPTURE, "--owner", owner], { stdio: "inherit" });
373
- process.exit(pass.status ?? 1);
374
- }
265
+ if (changing) printSummary(Boolean(process.exitCode));
@@ -3,7 +3,7 @@
3
3
  //
4
4
  // turn-record capture [...] land sessions and aw logs in the record
5
5
  // turn-record recall [...] search the record
6
- // turn-record setup [...] install hooks + background watcher, run first pass
6
+ // turn-record setup [...] install hooks + periodic capture, run first pass
7
7
  //
8
8
  // The experimental tools over the record (dress, spawn, segments, mind)
9
9
  // live in packages/experimental of the oats repo and run as
@@ -41,7 +41,7 @@ switch (sub) {
41
41
  "usage: turn-record <capture|recall|setup> [options]\n" +
42
42
  " capture [--watch|--status|--owner <name>|--root <dir>]\n" +
43
43
  " recall [--kind k] [--thread t] [--from f] [--show id] <query>\n" +
44
- " setup [--owner <name>] [--no-service] [--no-hooks] [--dry-run]",
44
+ " setup [--owner <name>] [--root <dir>] [--replace-service] [--no-service] [--no-hooks] [--dry-run]",
45
45
  );
46
46
  process.exit(sub === undefined || sub === "--help" || sub === "-h" ? 0 : 2);
47
47
  }