@awebai/oats 0.60.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 (96) hide show
  1. package/README.md +15 -19
  2. package/bin/oats.mjs +68 -21
  3. package/docs/capabilities.md +1 -1
  4. package/docs/configuration.md +9 -0
  5. package/docs/desktop-cli-api.md +28 -5
  6. package/docs/desktop.md +7 -0
  7. package/docs/execution-targets.md +49 -3
  8. package/docs/first-team.md +8 -0
  9. package/docs/implementation.md +2 -1
  10. package/docs/named-test-runs.md +382 -0
  11. package/docs/official-catalog.md +1 -1
  12. package/docs/packages.md +5 -5
  13. package/docs/release-notes/v0.61.0.md +155 -0
  14. package/docs/release-notes/v0.62.0.md +223 -0
  15. package/docs/tui.md +10 -4
  16. package/docs/upgrading.md +133 -11
  17. package/docs/workspaces.md +1 -1
  18. package/lib/core.mjs +2 -2
  19. package/lib/doctor-capture.mjs +35 -0
  20. package/lib/session-viewer.mjs +86 -7
  21. package/package-catalog.json +1 -1
  22. package/package.json +1 -1
  23. package/packages/client/cli-locator.mjs +2 -2
  24. package/packages/client/instance-presentation.mjs +10 -0
  25. package/packages/client/instance-tree.mjs +48 -6
  26. package/packages/record/README.md +87 -13
  27. package/packages/record/bin/capture-hook.mjs +8 -0
  28. package/packages/record/bin/capture.mjs +143 -124
  29. package/packages/record/bin/recall.mjs +8 -3
  30. package/packages/record/bin/setup.mjs +115 -225
  31. package/packages/record/bin/turn-record.mjs +2 -2
  32. package/packages/record/docs/capture-service.md +1443 -28
  33. package/packages/record/docs/capture-status.schema.json +429 -12
  34. package/packages/record/lib/capture-admission.mjs +82 -0
  35. package/packages/record/lib/capture-aw-unit.mjs +137 -0
  36. package/packages/record/lib/capture-aw.mjs +31 -12
  37. package/packages/record/lib/capture-budget.mjs +31 -0
  38. package/packages/record/lib/capture-cc.mjs +39 -6
  39. package/packages/record/lib/capture-cleanup-queue.mjs +135 -0
  40. package/packages/record/lib/capture-cleanup-work.mjs +77 -0
  41. package/packages/record/lib/capture-command-operation.mjs +37 -0
  42. package/packages/record/lib/capture-command-output.mjs +61 -0
  43. package/packages/record/lib/capture-command-worker.mjs +6 -0
  44. package/packages/record/lib/capture-command.mjs +48 -0
  45. package/packages/record/lib/capture-completion.mjs +152 -0
  46. package/packages/record/lib/capture-context.mjs +50 -0
  47. package/packages/record/lib/capture-default-roots.mjs +30 -0
  48. package/packages/record/lib/capture-discovery.mjs +114 -0
  49. package/packages/record/lib/capture-failures.mjs +45 -0
  50. package/packages/record/lib/capture-health-doctor.mjs +13 -0
  51. package/packages/record/lib/capture-health-installation.mjs +117 -0
  52. package/packages/record/lib/capture-health.mjs +116 -0
  53. package/packages/record/lib/capture-hook-ownership.mjs +58 -0
  54. package/packages/record/lib/capture-hook-runner.mjs +17 -0
  55. package/packages/record/lib/capture-hook.mjs +26 -0
  56. package/packages/record/lib/capture-index-inventory.mjs +205 -0
  57. package/packages/record/lib/capture-index-outcomes.mjs +113 -0
  58. package/packages/record/lib/capture-index-reset.mjs +109 -0
  59. package/packages/record/lib/capture-index-work.mjs +77 -0
  60. package/packages/record/lib/capture-issue-preparation.mjs +73 -0
  61. package/packages/record/lib/capture-issues.mjs +15 -2
  62. package/packages/record/lib/capture-lock.mjs +102 -16
  63. package/packages/record/lib/capture-native-unit.mjs +322 -0
  64. package/packages/record/lib/capture-pass.mjs +102 -0
  65. package/packages/record/lib/capture-recovery-snapshot.mjs +182 -0
  66. package/packages/record/lib/capture-retained-scratch.mjs +213 -0
  67. package/packages/record/lib/capture-retry.mjs +102 -0
  68. package/packages/record/lib/capture-run.mjs +125 -0
  69. package/packages/record/lib/capture-scratch.mjs +12 -3
  70. package/packages/record/lib/capture-service-definition.mjs +104 -0
  71. package/packages/record/lib/capture-service-install.mjs +362 -0
  72. package/packages/record/lib/capture-service-ownership.mjs +137 -0
  73. package/packages/record/lib/capture-service-runner.mjs +18 -0
  74. package/packages/record/lib/capture-small-snapshot.mjs +85 -0
  75. package/packages/record/lib/capture-source-discovery.mjs +319 -0
  76. package/packages/record/lib/capture-source-queue.mjs +199 -0
  77. package/packages/record/lib/capture-source-work.mjs +85 -0
  78. package/packages/record/lib/capture-state.mjs +16 -71
  79. package/packages/record/lib/capture-status.mjs +171 -0
  80. package/packages/record/lib/capture-supervisor.mjs +117 -0
  81. package/packages/record/lib/capture-watch.mjs +32 -0
  82. package/packages/record/lib/capture-work-session.mjs +238 -0
  83. package/packages/record/lib/capture-worker.mjs +58 -0
  84. package/packages/record/lib/derived-state.mjs +28 -15
  85. package/packages/record/lib/file-lines.mjs +22 -6
  86. package/packages/record/lib/formats.mjs +4 -3
  87. package/packages/record/lib/index-capture.mjs +97 -0
  88. package/packages/record/lib/index-db.mjs +3 -17
  89. package/packages/record/lib/index-reset.mjs +19 -0
  90. package/packages/record/lib/store.mjs +36 -11
  91. package/packages/record/lib/transcript-prefix.mjs +125 -0
  92. package/packages/tui/lib/client.mjs +2 -2
  93. package/packages/tui/lib/model.mjs +15 -5
  94. package/packages/tui/lib/views/palette.mjs +7 -3
  95. package/skills/oats-getting-started/SKILL.md +1 -1
  96. 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,65 @@
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 { IgnoreError, loadIgnore } from "../lib/ignore.mjs";
33
+ import { preflightCaptureService, applyCaptureService, captureSetupSnapshot, recheckCaptureSetup, writeCaptureSetup } from "../lib/capture-service-install.mjs";
34
+ import { captureRemedyCommand } from "../lib/capture-health.mjs";
36
35
 
37
36
  // The node written into what outlives this process: the hooks and the
38
37
  // service. `oats setup` hands in the kernel's answer for a node that survives
39
38
  // an upgrade of Node, as OATS_NODE_BIN; this package has no such rule of its
40
39
  // own, so run alone it records the node it runs under. What runs at once (the
41
40
  // first capture pass) runs under process.execPath whatever is recorded.
42
- function recordedNode(env = process.env) {
41
+ function handedNode(env = process.env) {
43
42
  const handed = env.OATS_NODE_BIN;
44
- return typeof handed === "string" && isAbsolute(handed) ? handed : process.execPath;
43
+ return typeof handed === "string" && isAbsolute(handed) ? handed : null;
45
44
  }
45
+ function recordedNode(env = process.env) { return handedNode(env) ?? process.execPath; }
46
46
 
47
47
  const HERE = dirname(fileURLToPath(import.meta.url));
48
48
  const NODE = recordedNode();
49
+ // Recoveries name the command a person runs, never this file: only a rerun
50
+ // through `oats setup` selects its stable node again. Health's wording function
51
+ // decides the words; setup's input to it is whether a node was handed in
52
+ // (OATS_NODE_BIN), which `oats setup` always does and instance shells also
53
+ // carry, so either printed command records that same node.
54
+ const SETUP_COMMAND = `${captureRemedyCommand(Boolean(handedNode()))} setup`;
49
55
  const CAPTURE = join(HERE, "capture.mjs");
56
+ // The hooks run their own entry, which a rolled-back install lacks: see it.
57
+ const CAPTURE_HOOK = join(HERE, "capture-hook.mjs");
50
58
 
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.
59
+ // Hooks use POSIX shell words. The separate definition builder owns the
60
+ // manager-specific XML/systemd representations.
55
61
  const SHELL_PLAIN = /^[A-Za-z0-9_./:@%+,-]+$/;
56
- const SYSTEMD_PLAIN = /^[A-Za-z0-9_./:@+,-]+$/;
57
62
 
58
63
  // A shell word: POSIX single quotes, a quote itself as '\''.
59
64
  function shellWord(value) {
60
65
  return SHELL_PLAIN.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
61
66
  }
62
67
 
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
68
  function parseArgs(argv) {
122
69
  const args = {};
123
70
  for (let i = 0; i < argv.length; i++) {
124
71
  const a = argv[i];
125
- if (a === "--owner") args.owner = argv[++i];
72
+ if (a === "--owner" || a === "--root") {
73
+ const value = argv[++i];
74
+ if (!value || value.startsWith("--") || value.includes("\0")) { console.error(`${a} requires a value`); process.exit(2); }
75
+ args[a.slice(2)] = value;
76
+ }
126
77
  else if (a.startsWith("--")) args[a.slice(2)] = true;
127
78
  else {
128
79
  console.error(`unknown argument ${a}`);
@@ -147,6 +98,7 @@ function defaultOwner() {
147
98
  const args = parseArgs(process.argv.slice(2));
148
99
  const owner = args.owner ?? defaultOwner();
149
100
  const dry = Boolean(args["dry-run"]);
101
+ const root = resolve(args.root ?? process.env.TURN_RECORD_ROOT ?? join(homedir(), ".turn-record"));
150
102
 
151
103
  // The owner is interpolated into a persisted shell command, a launchd
152
104
  // plist, and a systemd unit. Restricting it to the stream-id character
@@ -159,8 +111,10 @@ if (!/^[A-Za-z0-9._-]+$/.test(owner)) {
159
111
  process.exit(2);
160
112
  }
161
113
 
162
- const hookCommand = `${shellWord(NODE)} ${shellWord(CAPTURE)} --owner ${owner} --quiet`;
163
- const HOOK = { type: "command", command: hookCommand, async: true, timeout: 120 };
114
+ const hookCommand = `${shellWord(NODE)} ${shellWord(CAPTURE_HOOK)} --owner ${owner} --quiet --root ${shellWord(root)}`;
115
+ // The harness waits only for OS launch acknowledgement. Capture itself is
116
+ // detached and owns no harness pipes; these are launcher, not worker limits.
117
+ const HOOK = { type: "command", command: hookCommand, async: false, timeout: 10 };
164
118
 
165
119
  console.log(`owner: ${owner}`);
166
120
  console.log(`node: ${NODE}`);
@@ -170,19 +124,22 @@ console.log(`node: ${NODE}`);
170
124
  function settingsFiles() {
171
125
  const home = homedir();
172
126
  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);
127
+ for (const entry of readdirSync(home, { withFileTypes: true }).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)) {
128
+ if (!entry.name.startsWith(".claude") || (!entry.isDirectory() && !entry.isSymbolicLink())) continue;
129
+ const path = join(home, entry.name, "settings.json");
130
+ if (captureSetupSnapshot(path).kind !== "absent") files.push(path);
177
131
  }
178
132
  return files;
179
133
  }
180
134
 
181
- function installHooks() {
135
+ function prepareHooks() {
136
+ const edits = [];
182
137
  for (const path of settingsFiles()) {
138
+ const snapshot = captureSetupSnapshot(path);
139
+ if (snapshot.kind !== "file") throw new Error(`cannot safely read hook settings ${path}; preserve it and use --no-hooks`);
183
140
  let settings;
184
141
  try {
185
- settings = JSON.parse(readFileSync(path, "utf8"));
142
+ settings = JSON.parse(snapshot.bytes.toString("utf8"));
186
143
  } catch (err) {
187
144
  console.error(`SKIP ${path}: not valid JSON (${err.message}) — fix it and re-run setup`);
188
145
  continue;
@@ -194,11 +151,12 @@ function installHooks() {
194
151
  let changed = false;
195
152
  settings.hooks = settings.hooks ?? {};
196
153
  // Ours = a command whose STRUCTURE matches what setup generates:
197
- // "<node> <...>/capture.mjs ... --owner ... --quiet ...". Matching by
154
+ // "<node> <...>/capture.mjs ... --owner ... --quiet ...", or the hook
155
+ // entry capture-hook.mjs in place of capture.mjs. Matching by
198
156
  // shape rather than this install's absolute path means a moved install
199
157
  // (npm upgrade, checkout -> global) updates the old hook in place
200
158
  // instead of stacking a second one. The structural requirements (script
201
- // is the second token and ends in /capture.mjs; both flags present as
159
+ // is the second token and ends in /capture.mjs or /capture-hook.mjs; both flags present as
202
160
  // whole tokens) keep it from firing on unrelated hooks that merely
203
161
  // mention similar words; when in doubt it errs toward appending a new
204
162
  // group, never toward overwriting someone else's command.
@@ -210,28 +168,19 @@ function installHooks() {
210
168
  // every command written before paths were quoted, except one with `=`,
211
169
  // `~` or another ASCII character outside the plain set left bare in a
212
170
  // 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
171
  for (const event of ["Stop", "SessionEnd"]) {
225
172
  const groups = (settings.hooks[event] = settings.hooks[event] ?? []);
226
173
  let found = false;
227
- // Every hook that is ours gets the current command and none is removed,
174
+ // Every hook that is ours gets the current command/scheduling fields; none is removed,
228
175
  // two in one event included: the shape is not proof of ownership.
229
176
  for (const group of groups) {
230
177
  for (const hook of group.hooks ?? []) {
231
- if (!ours(hook)) continue;
178
+ if (!isCaptureHook(hook)) continue;
232
179
  found = true;
233
- if (hook.command !== hookCommand) {
180
+ if (hook.command !== hookCommand || hook.async !== HOOK.async || hook.timeout !== HOOK.timeout) {
234
181
  hook.command = hookCommand;
182
+ hook.async = HOOK.async;
183
+ hook.timeout = HOOK.timeout;
235
184
  changed = true;
236
185
  }
237
186
  }
@@ -241,134 +190,75 @@ function installHooks() {
241
190
  changed = true;
242
191
  }
243
192
  }
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
- }
193
+ edits.push({ snapshot, contents: changed ? JSON.stringify(settings, null, 2) + "\n" : null });
252
194
  }
195
+ return edits;
253
196
  }
254
197
 
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
- }
198
+ // --------------------------------------------------------------------- run
199
+ // Once setup starts changing things it ends with one setup summary: fixed
200
+ // labels, one item per line, the same order on every run, so a nonzero exit
201
+ // never reads as "nothing happened". It is held as one value.
202
+ const oneLine = text => String(text).replace(/\s*[\r\n]+\s*/g, " ");
203
+ const rerun = `${SETUP_COMMAND} --owner ${shellWord(owner)} --root ${shellWord(root)}${args["no-hooks"] ? " --no-hooks" : ""}${args["replace-service"] ? " --replace-service" : ""}`;
204
+ const summary = { hooks: [], firstPass: "not run", service: "not changed", serviceChanges: [], remedy: "none" };
205
+ function printSummary(failed) {
206
+ console.log(["setup summary:", ` status: ${failed ? "incomplete (exit 1)" : "complete"}`,
207
+ ...(summary.hooks.length ? summary.hooks : ["none"]).map(path => ` hooks written: ${path}`),
208
+ ` first capture pass: ${summary.firstPass}`, ` service: ${summary.service}`,
209
+ // What a failed service apply had already changed, in order.
210
+ ...summary.serviceChanges.map(change => ` service changed: ${oneLine(change)}`), ` remedy: ${summary.remedy}`].join("\n"));
310
211
  }
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;
212
+ let captureStarted = false, changing = false, serviceFailure = null;
213
+ try {
214
+ const hooks = args["no-hooks"] ? [] : prepareHooks();
215
+ const plan = captureDefaultRootPlan({ home: homedir(), cwd: process.cwd(), env: process.env });
216
+ // Every target and applicable manager is inspected before hook/service or
217
+ // capture mutations. --no-service never even reads named service files.
218
+ let service = null;
219
+ if (!args["no-service"]) {
220
+ if (["darwin", "linux"].includes(platform())) service = preflightCaptureService({ platform: platform(), node: NODE,
221
+ request: { root, owner, plan }, setupCommand: SETUP_COMMAND, dry, replace: Boolean(args["replace-service"]), noHooks: Boolean(args["no-hooks"]) });
222
+ else {
223
+ console.log(`service: no service template for ${platform()}; run this in the background yourself:\n` +
224
+ ` ${shellWord(NODE)} ${shellWord(CAPTURE)} --watch --owner ${owner} --root ${shellWord(root)}`);
225
+ summary.service = `no service template for ${platform()}`;
226
+ }
227
+ } else summary.service = "skipped (--no-service)";
228
+ if (!dry) loadIgnore(root);
229
+ const createdParents = new Map();
230
+ for (const hook of hooks) recheckCaptureSetup(hook.snapshot, createdParents);
231
+ changing = !dry;
232
+ // A service failure after preflight leaves hooks and the bounded first pass
233
+ // to run: capture is never skipped for it, and the exit still reports it.
234
+ if (service) {
235
+ try { applyCaptureService(service, createdParents); summary.service = "scheduled"; }
236
+ catch (error) {
237
+ if (dry) throw error;
238
+ serviceFailure = error; summary.service = `failed: ${oneLine(error.message)}`; summary.serviceChanges = error.applied ?? [];
239
+ console.error(`setup: service failed: ${error.message}`);
240
+ }
333
241
  }
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
- );
242
+ for (const { snapshot, contents } of hooks) {
243
+ if (!contents) console.log(`hooks: ${snapshot.path} already installed`);
244
+ else if (dry) console.log(`hooks: would install Stop+SessionEnd capture in ${snapshot.path}`);
245
+ else { writeCaptureSetup(snapshot, contents, createdParents); summary.hooks.push(snapshot.path); console.log(`hooks: installed Stop+SessionEnd capture in ${snapshot.path}`); }
348
246
  }
349
- }
350
-
351
- function installService() {
352
- const os = platform();
353
- if (os === "darwin") installServiceDarwin();
354
- else if (os === "linux") installServiceLinux();
247
+ if (dry) console.log("dry run: no first capture pass");
355
248
  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
- );
249
+ console.log("running first capture pass (the initial one can take minutes)...");
250
+ captureStarted = true;
251
+ try {
252
+ const pass = await captureCommandPass(root, { owner, plan, indexEnabled: true, trigger: "setup", retrySetAside: false });
253
+ summary.firstPass = pass.skipped ? "skipped: another pass holds the record root" : `appended ${pass.appended}, pending ${pass.pending ? "yes" : "no"}`;
254
+ } catch (error) { summary.firstPass = `failed: ${oneLine(error.message)}`; throw error; }
360
255
  }
256
+ if (serviceFailure) { summary.remedy = `rerun ${rerun}`; process.exitCode = 1; }
257
+ } catch (error) {
258
+ console.error(error instanceof IgnoreError ? error.message : `${captureStarted ? "capture pass" : "setup"} failed: ${error.message}`);
259
+ if (changing) summary.remedy = captureStarted && !serviceFailure ? `inspect ${captureRemedyCommand(Boolean(handedNode()))} capture --health --json, then rerun ${rerun}` : `rerun ${rerun}`;
260
+ else if (!captureStarted && !(error instanceof IgnoreError) && !error.code?.startsWith("E_CAPTURE_SERVICE_"))
261
+ console.error(`setup recovery: inspect the reported files/manager state, then retry ${rerun}; use --no-service to preserve the existing manager service`);
262
+ process.exitCode = 1;
361
263
  }
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
- }
264
+ 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
  }