@cohortapp/agent-sdk 2.11.14 → 2.12.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 (172) hide show
  1. package/.env.example +37 -22
  2. package/README.md +2 -0
  3. package/bin/maestro.mjs +113 -39
  4. package/bin/maestro.test.mjs +175 -5
  5. package/docs/guides/front-door-session.md +264 -0
  6. package/docs/guides/mac-mini.md +100 -28
  7. package/docs/guides/org-onboarding.md +1 -1
  8. package/docs/guides/setup-wizard.md +9 -5
  9. package/docs/runbooks/cohort-cutover.md +11 -1
  10. package/docs/runbooks/mac-mini-bootstrap.md +38 -63
  11. package/lib/cadence-bus-requeue.test.mjs +83 -0
  12. package/lib/cadence-bus.mjs +43 -7
  13. package/lib/channels/inbox-item.mjs +59 -2
  14. package/lib/cli/board.mjs +285 -0
  15. package/lib/cli/board.test.mjs +227 -0
  16. package/lib/cli/doctor-checks.mjs +441 -0
  17. package/lib/cli/doctor-checks.test.mjs +336 -0
  18. package/lib/cli/global-setup-extras.mjs +410 -0
  19. package/lib/cli/global-setup-extras.test.mjs +367 -0
  20. package/lib/cli/inbox.mjs +304 -0
  21. package/lib/cli/inbox.test.mjs +230 -0
  22. package/lib/cli/session-ack.mjs +63 -0
  23. package/lib/cli/session-ack.test.mjs +63 -0
  24. package/lib/cli/session.mjs +750 -0
  25. package/lib/cli/session.test.mjs +602 -0
  26. package/lib/collective/global-config.mjs +204 -6
  27. package/lib/collective/global-config.test.mjs +140 -0
  28. package/lib/collective/global-skills.mjs +145 -0
  29. package/lib/collective/global-skills.test.mjs +126 -0
  30. package/lib/collective/presence.mjs +4 -3
  31. package/lib/comms/send-gate.mjs +115 -0
  32. package/lib/comms/send-gate.test.mjs +113 -0
  33. package/lib/feature-init.mjs +2 -2
  34. package/lib/identity/persona.mjs +29 -0
  35. package/lib/identity/persona.test.mjs +26 -1
  36. package/lib/mcp/server.test.mjs +9 -4
  37. package/lib/model-router/spawn.test.mjs +21 -0
  38. package/lib/org/board-mine-cache.mjs +99 -0
  39. package/lib/org/board-mine-cache.test.mjs +53 -0
  40. package/lib/org/board.mjs +11 -0
  41. package/lib/org/board.test.mjs +11 -1
  42. package/lib/org/client.mjs +36 -0
  43. package/lib/org/client.test.mjs +46 -0
  44. package/lib/org/inbound/directedness.mjs +18 -2
  45. package/lib/org/inbound/directedness.test.mjs +58 -0
  46. package/lib/org/inbound/index.mjs +8 -1
  47. package/lib/org/inbound/index.test.mjs +22 -0
  48. package/lib/org/mesh-directives.test.mjs +110 -0
  49. package/lib/org/mesh.mjs +61 -1
  50. package/lib/org/protocol.checksum +1 -1
  51. package/lib/org/protocol.mjs +52 -0
  52. package/lib/org/protocol.test.mjs +12 -1
  53. package/lib/org/registry.mjs +3 -2
  54. package/lib/org/tool-surface.mjs +120 -0
  55. package/lib/org/tool-surface.test.mjs +118 -5
  56. package/lib/security/external-content.mjs +1 -1
  57. package/lib/security/external-content.test.mjs +17 -0
  58. package/lib/session/config.mjs +137 -0
  59. package/lib/session/config.test.mjs +92 -0
  60. package/lib/session/feed-core.mjs +229 -0
  61. package/lib/session/feed-core.test.mjs +198 -0
  62. package/lib/session/first-run.mjs +126 -0
  63. package/lib/session/first-run.test.mjs +121 -0
  64. package/lib/session/frontdoor.mjs +266 -0
  65. package/lib/session/frontdoor.test.mjs +205 -0
  66. package/lib/session/handoffs.mjs +295 -0
  67. package/lib/session/handoffs.test.mjs +183 -0
  68. package/lib/session/identity.mjs +220 -0
  69. package/lib/session/identity.test.mjs +180 -0
  70. package/lib/session/inbox-claims.mjs +434 -0
  71. package/lib/session/inbox-claims.test.mjs +286 -0
  72. package/lib/session/launch-args.mjs +161 -0
  73. package/lib/session/launch-args.test.mjs +157 -0
  74. package/lib/session/liveness.mjs +174 -0
  75. package/lib/session/liveness.test.mjs +100 -0
  76. package/lib/session/status-summary.mjs +172 -0
  77. package/lib/session/status-summary.test.mjs +118 -0
  78. package/lib/session-permissions.mjs +39 -3
  79. package/lib/session-permissions.test.mjs +20 -0
  80. package/lib/setup/claude-probe.mjs +161 -24
  81. package/lib/setup/claude-probe.test.mjs +187 -0
  82. package/lib/setup/sections/learning.mjs +2 -1
  83. package/lib/setup/sections/model.mjs +104 -24
  84. package/lib/setup/sections/model.test.mjs +240 -0
  85. package/lib/setup/sections/org.mjs +27 -2
  86. package/lib/setup/sections/org.test.mjs +35 -2
  87. package/lib/setup/sections/verify.mjs +5 -0
  88. package/lib/setup/state.mjs +30 -10
  89. package/lib/setup/state.test.mjs +24 -1
  90. package/lib/singleton.js +11 -3
  91. package/lib/singleton.test.mjs +16 -0
  92. package/lib/subagents/lock.mjs +1 -1
  93. package/lib/telemetry/collect.mjs +270 -6
  94. package/lib/telemetry/collect.test.mjs +196 -1
  95. package/lib/upgrade/global-refresh.mjs +108 -0
  96. package/lib/upgrade/global-refresh.test.mjs +65 -0
  97. package/lib/upgrade/launchd-reconcile.mjs +327 -0
  98. package/lib/upgrade/launchd-reconcile.test.mjs +272 -0
  99. package/lib/upgrade/post-steps.mjs +151 -0
  100. package/lib/upgrade/post-steps.test.mjs +200 -0
  101. package/lib/upgrade/verify.mjs +215 -0
  102. package/lib/upgrade/verify.test.mjs +164 -0
  103. package/lib/voice/outbound.mjs +3 -2
  104. package/lib/voice/post-call-brief.mjs +2 -1
  105. package/lib/voice/session-rotation.mjs +6 -1
  106. package/lib/voice/session-rotation.test.mjs +114 -0
  107. package/package.json +3 -3
  108. package/plugins/maestro-skills/plugin.json +21 -1
  109. package/plugins/maestro-skills/skills/board-work.md +63 -0
  110. package/plugins/maestro-skills/skills/inbound-triage.md +80 -0
  111. package/plugins/maestro-skills/skills/main-session.md +102 -0
  112. package/plugins/maestro-skills/skills/peer-sessions.md +65 -0
  113. package/plugins/maestro-skills/skills/persona-discipline.md +75 -0
  114. package/scaffold/CLAUDE.md +34 -0
  115. package/scripts/ci/check-durable-write-seam.mjs +147 -0
  116. package/scripts/ci/check-durable-write-seam.test.mjs +90 -0
  117. package/scripts/ci/check.mjs +3 -0
  118. package/scripts/collective/hook-runner.mjs +39 -4
  119. package/scripts/collective/hook-runner.test.mjs +85 -2
  120. package/scripts/daemon/agent-daemon-board-mine.test.mjs +96 -0
  121. package/scripts/daemon/agent-daemon-frontdoor.test.mjs +60 -0
  122. package/scripts/daemon/agent-daemon.mjs +141 -10
  123. package/scripts/daemon/agent-daemon.test.mjs +73 -0
  124. package/scripts/daemon/assurance-e2e.test.mjs +141 -6
  125. package/scripts/daemon/assurance.mjs +461 -37
  126. package/scripts/daemon/assurance.test.mjs +408 -43
  127. package/scripts/daemon/cadence-consumer-frontdoor.test.mjs +334 -0
  128. package/scripts/daemon/cadence-consumer.mjs +254 -78
  129. package/scripts/daemon/cadence-handlers.mjs +53 -0
  130. package/scripts/daemon/classifier.mjs +1 -1
  131. package/scripts/daemon/dispatcher-resume.test.mjs +166 -0
  132. package/scripts/daemon/dispatcher.mjs +127 -19
  133. package/scripts/daemon/health.mjs +12 -1
  134. package/scripts/daemon/inbox-deferral-session.test.mjs +49 -0
  135. package/scripts/daemon/inbox-deferral.mjs +6 -0
  136. package/scripts/daemon/lib/self-echo.mjs +201 -0
  137. package/scripts/daemon/lib/self-echo.test.mjs +153 -0
  138. package/scripts/daemon/maestro-daemon.mjs +3 -0
  139. package/scripts/daemon/prompt-builder.mjs +9 -1
  140. package/scripts/daemon/prompt-builder.test.mjs +22 -0
  141. package/scripts/daemon/responder.mjs +61 -41
  142. package/scripts/daemon/sdk-version.mjs +51 -0
  143. package/scripts/daemon/sdk-version.test.mjs +31 -0
  144. package/scripts/hooks/pre-send-audit.sh +97 -4
  145. package/scripts/hooks/pre-send-audit.test.mjs +140 -1
  146. package/scripts/local-triggers/autoupdate.sh +243 -19
  147. package/scripts/local-triggers/autoupdate.test.mjs +488 -0
  148. package/scripts/local-triggers/generate-plists.sh +24 -1
  149. package/scripts/local-triggers/generate-plists.test.mjs +49 -11
  150. package/scripts/org/send-orgmail.first-contact.test.mjs +102 -0
  151. package/scripts/org/send-orgmail.mjs +27 -3
  152. package/scripts/poller/inbox-privilege-injection.test.mjs +167 -0
  153. package/scripts/poller/slack-poller.mjs +13 -1
  154. package/scripts/poller/utils.mjs +46 -1
  155. package/scripts/poller-launchd/install.sh +19 -11
  156. package/scripts/poller-launchd/install.test.mjs +243 -0
  157. package/scripts/poller-launchd/launchd-poller-wrapper.sh +92 -0
  158. package/scripts/poller-launchd/migrate.sh +66 -0
  159. package/scripts/poller-launchd/poller.plist.template +4 -2
  160. package/scripts/session/feed.mjs +237 -0
  161. package/scripts/session/feed.test.mjs +196 -0
  162. package/scripts/session/supervisor-sh.test.mjs +218 -0
  163. package/scripts/session/supervisor.mjs +328 -0
  164. package/scripts/session/supervisor.sh +141 -0
  165. package/scripts/session/supervisor.test.mjs +482 -0
  166. package/scripts/setup/configure-macos.sh +250 -55
  167. package/scripts/setup/configure-macos.test.mjs +306 -0
  168. package/scripts/setup/init-agent.sh +112 -7
  169. package/scripts/setup/init-agent.test.mjs +220 -1
  170. package/scripts/watchdog/memory-watchdog.sh +37 -1
  171. package/scripts/watchdog/memory-watchdog.test.mjs +64 -0
  172. package/scripts/setup/boot-claude-session.sh +0 -94
@@ -13,7 +13,8 @@
13
13
 
14
14
  import { test } from "node:test";
15
15
  import assert from "node:assert/strict";
16
- import { readFileSync, writeFileSync, mkdtempSync, rmSync } from "node:fs";
16
+ import { readFileSync, writeFileSync, mkdtempSync, mkdirSync, chmodSync, existsSync, rmSync, readdirSync } from "node:fs";
17
+ import { spawnSync } from "node:child_process";
17
18
  import { execFileSync } from "node:child_process";
18
19
  import { join, dirname } from "node:path";
19
20
  import { tmpdir } from "node:os";
@@ -137,6 +138,14 @@ test("init-agent.sh additions contain no allow-all permissions or dangerous-skip
137
138
  assert.ok(!m[1].includes("Bash(*)"), "additions must not contain Bash(*) allow-all");
138
139
  });
139
140
 
141
+ test("init-agent.sh creates the front-door session state and log directories", () => {
142
+ // launchd creates StandardOutPath's FILE but not its directory; the session
143
+ // plist logs to logs/session/. The feed/supervisor write under state/session/.
144
+ for (const d of ["logs/session", "state/session", "state/session/handoffs/done"]) {
145
+ assert.ok(scriptSrc.includes(`"${d}"`), `DIRS must include ${d}`);
146
+ }
147
+ });
148
+
140
149
  test("init-agent.sh chmods the .env to 600", () => {
141
150
  assert.ok(/chmod 600 "\$ENV_FILE"/.test(scriptSrc),
142
151
  "the agent .env must be chmod 600 after writing (no world-readable credentials)");
@@ -149,3 +158,213 @@ test("init-agent.sh deep-merges rather than cat>-overwriting settings.json", ()
149
158
  assert.ok(scriptSrc.includes("node -e \"$MAESTRO_MERGE_NODE\""),
150
159
  "the merge must run via the embedded node program");
151
160
  });
161
+
162
+ // ---------------------------------------------------------------------------
163
+ // Front-door session prerequisites (design §3.7 / §6 WP-M3): the global SDK
164
+ // install and a terminal multiplexer. The block is embedded in init-agent.sh
165
+ // between BEGIN/END markers; we extract that exact block and run it under
166
+ // bash with stub binaries, so the test pins what the script actually ships.
167
+ // ---------------------------------------------------------------------------
168
+
169
+ function extractGlobalSdkBlock() {
170
+ const m = scriptSrc.match(/# --- BEGIN maestro global-sdk check[^\n]*\n([\s\S]*?)# --- END maestro global-sdk check ---/);
171
+ assert.ok(m, "global-sdk check block (BEGIN/END markers) not found in init-agent.sh");
172
+ return m[1];
173
+ }
174
+
175
+ /**
176
+ * Run the extracted block with a stub `npm` (and optional `tmux`) on PATH.
177
+ * `npm ls -g` exits per `installed`; `npm view` prints `latest`; every call is
178
+ * appended to calls.log. Returns {status, stdout, calls}.
179
+ */
180
+ function runGlobalSdkBlock({ installed, installedVersion = "1.0.0", latest = "1.0.0", tmux = false, screenBin, env = {} }) {
181
+ const dir = makeTmp();
182
+ try {
183
+ const bin = join(dir, "bin");
184
+ const log = join(dir, "calls.log");
185
+ mkdirSync(bin, { recursive: true });
186
+ writeFileSync(join(bin, "npm"), `#!/bin/bash
187
+ echo "npm $*" >> "${log}"
188
+ case "$1" in
189
+ ls) ${installed ? `echo "/usr/local/lib"; echo "└── @cohortapp/agent-sdk@${installedVersion}"; exit 0` : "exit 1"} ;;
190
+ view) echo "${latest}"; exit 0 ;;
191
+ install) exit 0 ;;
192
+ esac
193
+ exit 0
194
+ `);
195
+ chmodSync(join(bin, "npm"), 0o755);
196
+ if (tmux) { writeFileSync(join(bin, "tmux"), "#!/bin/bash\necho 'tmux 3.4'\n"); chmodSync(join(bin, "tmux"), 0o755); }
197
+ const prog = `log(){ echo "[init] $1"; }; ok(){ echo " ok $1"; }; warn(){ echo " warn $1"; }; fail(){ echo " FAIL $1"; exit 1; }\n${extractGlobalSdkBlock()}`;
198
+ writeFileSync(join(dir, "block.sh"), prog);
199
+ const r = spawnSync("/bin/bash", [join(dir, "block.sh")], {
200
+ encoding: "utf8",
201
+ env: { PATH: `${bin}:${env.MAESTRO_TEST_EXTRA_PATH ? `${env.MAESTRO_TEST_EXTRA_PATH}:` : ""}/usr/bin:/bin`, HOME: dir, MAESTRO_SCREEN_BIN: screenBin || join(dir, "no-such-screen"), ...env },
202
+ });
203
+ const calls = existsSync(log) ? readFileSync(log, "utf8") : "";
204
+ return { status: r.status, stdout: r.stdout + r.stderr, calls };
205
+ } finally {
206
+ rmSync(dir, { recursive: true, force: true });
207
+ }
208
+ }
209
+
210
+ test("global SDK present and current: verified, nothing installed", () => {
211
+ const r = runGlobalSdkBlock({ installed: true, installedVersion: "2.0.0", latest: "2.0.0", tmux: true });
212
+ assert.equal(r.status, 0, r.stdout);
213
+ assert.match(r.calls, /^npm ls -g @cohortapp\/agent-sdk/m, `must verify with npm ls -g; calls:\n${r.calls}`);
214
+ assert.ok(!/npm install -g/.test(r.calls), `must not install; calls:\n${r.calls}`);
215
+ assert.match(r.stdout, /Global SDK.*2\.0\.0/);
216
+ });
217
+
218
+ test("global SDK missing: installs @latest", () => {
219
+ const r = runGlobalSdkBlock({ installed: false, tmux: true });
220
+ assert.equal(r.status, 0, r.stdout);
221
+ assert.match(r.calls, /^npm install -g @cohortapp\/agent-sdk@latest/m, `expected a global install; calls:\n${r.calls}`);
222
+ });
223
+
224
+ test("global SDK outdated: upgrades to @latest", () => {
225
+ const r = runGlobalSdkBlock({ installed: true, installedVersion: "1.0.0", latest: "2.0.0", tmux: true });
226
+ assert.equal(r.status, 0, r.stdout);
227
+ assert.match(r.calls, /^npm install -g @cohortapp\/agent-sdk@latest/m, `expected an upgrade; calls:\n${r.calls}`);
228
+ });
229
+
230
+ test("MAESTRO_SKIP_GLOBAL_INSTALL=1 verifies but never installs or upgrades", () => {
231
+ for (const scenario of [{ installed: false }, { installed: true, installedVersion: "1.0.0", latest: "2.0.0" }]) {
232
+ const r = runGlobalSdkBlock({ ...scenario, tmux: true, env: { MAESTRO_SKIP_GLOBAL_INSTALL: "1" } });
233
+ assert.equal(r.status, 0, r.stdout);
234
+ assert.match(r.calls, /^npm ls -g @cohortapp\/agent-sdk/m, "still verifies");
235
+ assert.ok(!/npm install/.test(r.calls), `must not install under the skip flag; calls:\n${r.calls}`);
236
+ assert.match(r.stdout, /MAESTRO_SKIP_GLOBAL_INSTALL/, "must say why it skipped");
237
+ }
238
+ });
239
+
240
+ test("multiplexer: tmux preferred, /usr/bin/screen accepted, neither → warning naming brew install tmux", () => {
241
+ const withTmux = runGlobalSdkBlock({ installed: true, tmux: true });
242
+ assert.match(withTmux.stdout, /tmux/);
243
+ const dir = makeTmp();
244
+ try {
245
+ const screen = join(dir, "screen");
246
+ writeFileSync(screen, "#!/bin/bash\necho 'Screen version 4.00.03'\n"); chmodSync(screen, 0o755);
247
+ const withScreen = runGlobalSdkBlock({ installed: true, tmux: false, screenBin: screen });
248
+ assert.equal(withScreen.status, 0, withScreen.stdout);
249
+ assert.match(withScreen.stdout, /screen/i);
250
+ } finally { rmSync(dir, { recursive: true, force: true }); }
251
+ const neither = runGlobalSdkBlock({ installed: true, tmux: false });
252
+ assert.equal(neither.status, 0, "a missing multiplexer is a warning, not a fatal (screen ships with macOS)");
253
+ assert.match(neither.stdout, /brew install tmux/);
254
+ });
255
+
256
+ // ---------------------------------------------------------------------------
257
+ // Review fixes (2026-09-08): the global-sdk block also verifies PATH and never
258
+ // blocks on the registry; Step 5 never unload/loads a live session or daemon.
259
+ // ---------------------------------------------------------------------------
260
+
261
+ test("global SDK block: `npm view` carries a fetch timeout so an offline init-agent does not hang for minutes", () => {
262
+ const r = runGlobalSdkBlock({ installed: true, installedVersion: "2.0.0", latest: "2.0.0", tmux: true });
263
+ assert.match(r.calls, /^npm view @cohortapp\/agent-sdk version.*--fetch-timeout=\d+/m, `calls:\n${r.calls}`);
264
+ });
265
+
266
+ test("global SDK block: verifies that maestro and cohort-mcp resolve on PATH (spec §3.7(6))", () => {
267
+ const missing = runGlobalSdkBlock({ installed: true, installedVersion: "2.0.0", latest: "2.0.0", tmux: true });
268
+ assert.equal(missing.status, 0, missing.stdout);
269
+ assert.match(missing.stdout, /warn.*maestro.*not on PATH|warn.*not on PATH.*maestro/i, `must warn when maestro is missing from PATH:\n${missing.stdout}`);
270
+ assert.match(missing.stdout, /cohort-mcp/, "must name cohort-mcp too");
271
+ // Present on PATH → ok lines naming both.
272
+ const dir = makeTmp();
273
+ try {
274
+ const extra = join(dir, "gbin");
275
+ mkdirSync(extra, { recursive: true });
276
+ for (const b of ["maestro", "cohort-mcp"]) { writeFileSync(join(extra, b), "#!/bin/bash\nexit 0\n"); chmodSync(join(extra, b), 0o755); }
277
+ const present = runGlobalSdkBlock({ installed: true, installedVersion: "2.0.0", latest: "2.0.0", tmux: true, env: { MAESTRO_TEST_EXTRA_PATH: extra } });
278
+ assert.equal(present.status, 0, present.stdout);
279
+ assert.match(present.stdout, /ok.*maestro on PATH/i, present.stdout);
280
+ assert.match(present.stdout, /ok.*cohort-mcp on PATH/i, present.stdout);
281
+ assert.ok(!/not on PATH/.test(present.stdout));
282
+ } finally { rmSync(dir, { recursive: true, force: true }); }
283
+ });
284
+
285
+ function extractLaunchdBlock() {
286
+ const m = scriptSrc.match(/# --- BEGIN maestro launchd install[^\n]*\n([\s\S]*?)# --- END maestro launchd install ---/);
287
+ assert.ok(m, "launchd install block (BEGIN/END markers) not found in init-agent.sh");
288
+ return m[1];
289
+ }
290
+
291
+ /**
292
+ * Run Step 5 with a stub launchctl whose `list <label>` exits 0 for labels in
293
+ * `loaded`. Generated plists live in scripts/local-triggers/plists/ of a
294
+ * fixture agent dir. Returns {status, stdout, calls, home}.
295
+ */
296
+ function runLaunchdBlock({ plists, loaded = [], supervisor = true, migrate = false }) {
297
+ const dir = makeTmp();
298
+ const agent = join(dir, "agent");
299
+ const home = join(dir, "home");
300
+ const bin = join(dir, "bin");
301
+ const log = join(dir, "calls.log");
302
+ mkdirSync(join(agent, "scripts", "local-triggers", "plists"), { recursive: true });
303
+ mkdirSync(join(agent, "scripts", "session"), { recursive: true });
304
+ mkdirSync(join(agent, "scripts", "poller-launchd"), { recursive: true });
305
+ mkdirSync(join(home, "Library", "LaunchAgents"), { recursive: true });
306
+ mkdirSync(bin, { recursive: true });
307
+ for (const label of plists) writeFileSync(join(agent, "scripts", "local-triggers", "plists", `${label}.plist`), `<plist>${label}</plist>\n`);
308
+ if (supervisor) writeFileSync(join(agent, "scripts", "session", "supervisor.sh"), "#!/bin/bash\n");
309
+ if (migrate) { writeFileSync(join(agent, "scripts", "poller-launchd", "migrate.sh"), `#!/bin/bash\necho "migrate $*" >> "${log}"\n`); chmodSync(join(agent, "scripts", "poller-launchd", "migrate.sh"), 0o755); }
310
+ writeFileSync(join(bin, "launchctl"), `#!/bin/bash
311
+ echo "launchctl $*" >> "${log}"
312
+ if [ "$1" = "list" ] && [ -n "$2" ]; then case " ${loaded.join(" ")} " in *" $2 "*) exit 0 ;; *) exit 1 ;; esac; fi
313
+ exit 0
314
+ `);
315
+ chmodSync(join(bin, "launchctl"), 0o755);
316
+ const prog = `set -u
317
+ log(){ echo "[init] $1"; }; ok(){ echo " ok $1"; }; warn(){ echo " warn $1"; }
318
+ AGENT_DIR="${agent}"
319
+ LAUNCH_AGENTS_DIR="$HOME/Library/LaunchAgents"
320
+ PLIST_DIR="$AGENT_DIR/scripts/local-triggers/plists"
321
+ ${extractLaunchdBlock()}`;
322
+ writeFileSync(join(dir, "block.sh"), prog);
323
+ const r = spawnSync("/bin/bash", [join(dir, "block.sh")], { encoding: "utf8", env: { PATH: `${bin}:/usr/bin:/bin`, HOME: home } });
324
+ const calls = existsSync(log) ? readFileSync(log, "utf8") : "";
325
+ const installed = readdirSync(join(home, "Library", "LaunchAgents"));
326
+ rmSync(dir, { recursive: true, force: true });
327
+ return { status: r.status, stdout: r.stdout + r.stderr, calls, installed };
328
+ }
329
+
330
+ test("Step 5: a LOADED session or daemon job is rewritten but never unloaded/loaded on a re-run (WP-M6 'never bootout')", () => {
331
+ const r = runLaunchdBlock({
332
+ plists: ["ai.maestro.ivy-session", "ai.maestro.ivy-daemon", "ai.maestro.ivy-daily-brief"],
333
+ loaded: ["ai.maestro.ivy-session", "ai.maestro.ivy-daemon", "ai.maestro.ivy-daily-brief"],
334
+ });
335
+ assert.equal(r.status, 0, r.stdout);
336
+ assert.ok(!/launchctl (unload|bootout)[^\n]*-session/.test(r.calls), `must not unload the session job; calls:\n${r.calls}`);
337
+ assert.ok(!/launchctl load[^\n]*-session/.test(r.calls), `must not re-load a loaded session job; calls:\n${r.calls}`);
338
+ assert.ok(!/launchctl (unload|bootout|load)[^\n]*-daemon/.test(r.calls), `must not unload/load a loaded daemon; calls:\n${r.calls}`);
339
+ // The trigger job keeps today's unload + load (its script may have changed).
340
+ assert.match(r.calls, /launchctl unload[^\n]*daily-brief/);
341
+ assert.match(r.calls, /launchctl load[^\n]*daily-brief/);
342
+ // Files are still refreshed for all three.
343
+ assert.deepEqual(r.installed.sort(), ["ai.maestro.ivy-daemon.plist", "ai.maestro.ivy-daily-brief.plist", "ai.maestro.ivy-session.plist"]);
344
+ assert.match(r.stdout, /kept running/i);
345
+ });
346
+
347
+ test("Step 5: a NOT-loaded session/daemon job is installed and loaded (first run)", () => {
348
+ const r = runLaunchdBlock({ plists: ["ai.maestro.ivy-session", "ai.maestro.ivy-daemon"], loaded: [] });
349
+ assert.equal(r.status, 0, r.stdout);
350
+ assert.match(r.calls, /launchctl load[^\n]*ai\.maestro\.ivy-session\.plist/);
351
+ assert.match(r.calls, /launchctl load[^\n]*ai\.maestro\.ivy-daemon\.plist/);
352
+ assert.ok(!/launchctl unload/.test(r.calls), "nothing to unload on a first run");
353
+ });
354
+
355
+ test("Step 5: the session plist is skipped when scripts/session/supervisor.sh is absent (launchd would retry every 30 s forever)", () => {
356
+ const r = runLaunchdBlock({ plists: ["ai.maestro.ivy-session", "ai.maestro.ivy-daemon"], loaded: [], supervisor: false });
357
+ assert.equal(r.status, 0, r.stdout);
358
+ assert.ok(!/-session/.test(r.calls), `must not load a session plist with no supervisor; calls:\n${r.calls}`);
359
+ assert.ok(!r.installed.includes("ai.maestro.ivy-session.plist"));
360
+ assert.match(r.stdout, /supervisor\.sh/);
361
+ assert.match(r.calls, /launchctl load[^\n]*-daemon/);
362
+ });
363
+
364
+ test("Step 5: runs the poller-plist migration (audit F6 follow-through) when it ships", () => {
365
+ const r = runLaunchdBlock({ plists: ["ai.maestro.ivy-daemon"], migrate: true });
366
+ assert.equal(r.status, 0, r.stdout);
367
+ assert.match(r.calls, /^migrate/m, `calls:\n${r.calls}`);
368
+ const without = runLaunchdBlock({ plists: ["ai.maestro.ivy-daemon"], migrate: false });
369
+ assert.equal(without.status, 0, "an absent migrate.sh is not an error");
370
+ });
@@ -16,7 +16,10 @@
16
16
  # auto-expiring ceiling = liveCount-2 that the resource governor
17
17
  # reads to admit fewer sessions. NO kills.
18
18
  # HARD (sys 80–90% / claude ≥75%) → SIGTERM the youngest/biggest
19
- # subagents, sparing the oldest "main" session (MIN_AGE_SECONDS).
19
+ # subagents, sparing the oldest "main" session (MIN_AGE_SECONDS)
20
+ # and — audit F16 — NEVER the seat's interactive main session
21
+ # (`--name <first>-main`) or its feed (scripts/session/feed.mjs),
22
+ # whatever their age or size. See is_protected_cmdline.
20
23
  # CRITICAL (sys ≥90%, sustained 2 consecutive runs) → clean daemon RESTART
21
24
  # via `launchctl kickstart -k` (the daemon re-reads state/queues +
22
25
  # cooldowns + sweeps stale claims). NOT a halt. Only after 3 failed
@@ -156,6 +159,34 @@ count_claude_processes() {
156
159
 
157
160
  # --- Identification ----------------------------------------------------------
158
161
 
162
+ # Audit F16. The oldest-process heuristic below is not enough: after a relaunch
163
+ # the seat's interactive main session is the YOUNGEST claude process, and the
164
+ # HARD tier killed it. The main session is identified by its command line, not
165
+ # its age: `claude --name <first>-main …` (the supervisor launches it so) and
166
+ # the feed running inside it (`node scripts/session/feed.mjs`). Pure: takes the
167
+ # command line, exits 0 when the process must never be signalled.
168
+ is_protected_cmdline() {
169
+ local cmdline="${1:-}"
170
+ [ -z "$cmdline" ] && return 1
171
+ # `--name <token>-main` as a WHOLE token (not -mainline, not -main-2).
172
+ if printf '%s\n' "$cmdline" | grep -Eq -- '(^|[[:space:]])--name[[:space:]]+[A-Za-z0-9_.-]+-main([[:space:]]|$)'; then
173
+ return 0
174
+ fi
175
+ case "$cmdline" in
176
+ *scripts/session/feed.mjs*) return 0 ;;
177
+ esac
178
+ return 1
179
+ }
180
+
181
+ # Full command line of a pid ("" when the process is gone). `-ww` = unlimited
182
+ # width: without it macOS ps clips `command=` to the terminal width when
183
+ # stdout is a tty (an operator's --check / --dry-run), and a long claude argv
184
+ # can lose its `--name <first>-main` token — which would un-protect the main
185
+ # session exactly when a human is watching.
186
+ cmdline_of() {
187
+ /bin/ps -ww -o command= -p "$1" 2>/dev/null || true
188
+ }
189
+
159
190
  identify_main_session() {
160
191
  # The oldest claude process is treated as the "main" session and spared by
161
192
  # HARD-tier kills. (longest-running heuristic)
@@ -201,6 +232,11 @@ kill_youngest_biggest_subagents() {
201
232
  log_event "info" "skip_young" "PID $pid age ${age}s < ${MIN_AGE_SECONDS}s minimum"
202
233
  continue
203
234
  fi
235
+ # Audit F16: the interactive main session and its feed are never candidates.
236
+ if is_protected_cmdline "$(cmdline_of "$pid")"; then
237
+ log_event "info" "skip_protected" "PID $pid is the main session / feed — never signalled"
238
+ continue
239
+ fi
204
240
  if [ "$killed" -ge "$target_count" ]; then
205
241
  break
206
242
  fi
@@ -0,0 +1,64 @@
1
+ /**
2
+ * memory-watchdog.test.mjs — audit F16: the HARD tier could SIGTERM the
3
+ * seat's long-lived interactive main session (it only spared the OLDEST
4
+ * claude process, and a freshly relaunched main session is not the oldest).
5
+ *
6
+ * The rule under test is a pure shell function, `is_protected_cmdline`,
7
+ * extracted from the script and run under bash: a command line carrying
8
+ * `--name <anything>-main` or `scripts/session/feed.mjs` is never a kill
9
+ * candidate. The kill loop is also checked textually for the call site, so
10
+ * the function cannot be defined and then not used.
11
+ */
12
+
13
+ import { test } from "node:test";
14
+ import assert from "node:assert/strict";
15
+ import { readFileSync } from "node:fs";
16
+ import { spawnSync } from "node:child_process";
17
+ import { join, dirname } from "node:path";
18
+ import { fileURLToPath } from "node:url";
19
+
20
+ const SCRIPT = join(dirname(fileURLToPath(import.meta.url)), "memory-watchdog.sh");
21
+
22
+ /** Extract `is_protected_cmdline` from the script and evaluate it on one command line. Exit 0 = protected. */
23
+ function isProtected(cmdline) {
24
+ const src = readFileSync(SCRIPT, "utf8");
25
+ const m = src.match(/\nis_protected_cmdline\(\) \{[\s\S]*?\n\}\n/);
26
+ assert.ok(m, "memory-watchdog.sh defines is_protected_cmdline()");
27
+ const r = spawnSync("/bin/bash", ["-c", `${m[0]}\nis_protected_cmdline "$1"`, "_", cmdline], { encoding: "utf8" });
28
+ return r.status === 0;
29
+ }
30
+
31
+ test("the main session (`--name <first>-main`) is protected, whatever the first name", () => {
32
+ assert.equal(isProtected("claude --name alex-main --resume 1234 --dangerously-skip-permissions"), true);
33
+ assert.equal(isProtected("/opt/homebrew/bin/claude --dangerously-skip-permissions --name marc-main"), true);
34
+ assert.equal(isProtected("node /Users/x/.npm-global/lib/node_modules/@anthropic-ai/claude-code/cli.js --name olivia-main"), true);
35
+ });
36
+
37
+ test("the session feed (scripts/session/feed.mjs) is protected", () => {
38
+ assert.equal(isProtected("node /Users/alex/alex-ai/scripts/session/feed.mjs"), true);
39
+ assert.equal(isProtected("/usr/local/bin/node scripts/session/feed.mjs --agent-root /x"), true);
40
+ });
41
+
42
+ test("sub-sessions, peers and print spawns are NOT protected", () => {
43
+ assert.equal(isProtected("claude --print --output-format json --dangerously-skip-permissions prompt"), false);
44
+ assert.equal(isProtected("claude --name alex-research --dangerously-skip-permissions"), false);
45
+ assert.equal(isProtected("claude --name alex-mainline"), false, "-main must be a whole token");
46
+ assert.equal(isProtected("claude --name alex-main-2"), false);
47
+ assert.equal(isProtected("node scripts/daemon/maestro-daemon.mjs"), false);
48
+ assert.equal(isProtected(""), false);
49
+ });
50
+
51
+ test("the HARD-tier kill loop consults is_protected_cmdline before SIGTERM and logs the skip", () => {
52
+ const src = readFileSync(SCRIPT, "utf8");
53
+ const loop = src.slice(src.indexOf("kill_youngest_biggest_subagents() {"), src.indexOf('done <<< "$(get_claude_processes)"'));
54
+ assert.match(loop, /is_protected_cmdline/, "the kill loop calls the guard");
55
+ assert.match(loop, /skip_protected/, "a protected skip is logged");
56
+ assert.ok(loop.indexOf("is_protected_cmdline") < loop.indexOf('kill -TERM "$pid"'), "the guard runs before the signal");
57
+ });
58
+
59
+ test("cmdline_of reads the FULL command line (ps -ww) so a long argv is never cut before --name <first>-main on a narrow tty", () => {
60
+ const src = readFileSync(SCRIPT, "utf8");
61
+ const m = src.match(/\ncmdline_of\(\) \{[\s\S]*?\n\}\n/);
62
+ assert.ok(m, "memory-watchdog.sh defines cmdline_of()");
63
+ assert.match(m[0], /\/bin\/ps -ww /, "ps must be given -ww (unlimited width) — macOS truncates `-o command=` to the terminal width otherwise");
64
+ });
@@ -1,94 +0,0 @@
1
- #!/bin/bash
2
- # =============================================================================
3
- # boot-claude-session.sh — Launch interactive Claude Code session on boot
4
- # =============================================================================
5
- #
6
- # Opens Terminal.app with a Claude Code interactive session in the agent's
7
- # working directory. Called via launchd at login.
8
- #
9
- # This is separate from the maestro daemon (which runs headless as a Node.js
10
- # process for polling/dispatching). This script provides a visible, interactive
11
- # Claude Code session that the operator can observe and interact with.
12
- #
13
- # Usage:
14
- # ./scripts/setup/boot-claude-session.sh <agent-dir>
15
- #
16
- # =============================================================================
17
-
18
- set -euo pipefail
19
-
20
- SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
21
- MAESTRO_DIR="$(cd "$SCRIPT_DIR/../.." && pwd)"
22
-
23
- # Agent directory required as first argument (e.g. ~/<firstname>-ai).
24
- AGENT_DIR="${1:?Agent directory required as first argument (e.g. ~/<firstname>-ai)}"
25
- if [ ! -d "$AGENT_DIR" ]; then
26
- echo "ERROR: Agent directory does not exist: $AGENT_DIR" >&2
27
- exit 1
28
- fi
29
-
30
- AGENT_NAME=$(basename "$AGENT_DIR")
31
- # Resolve the agent's display name from config/agent.json (SOT), falling
32
- # back to the directory basename. Used for the Terminal window banner.
33
- AGENT_DISPLAY="$AGENT_NAME"
34
- if [ -f "$AGENT_DIR/config/agent.json" ]; then
35
- if command -v jq >/dev/null 2>&1; then
36
- fn=$(jq -r '.fullName // empty' "$AGENT_DIR/config/agent.json")
37
- [ -n "$fn" ] && AGENT_DISPLAY="$fn"
38
- fi
39
- fi
40
- LOG_FILE="$MAESTRO_DIR/logs/watchdog/$(date +%Y-%m-%d)-boot-session.log"
41
- mkdir -p "$(dirname "$LOG_FILE")"
42
-
43
- log() {
44
- echo "[$(date -u +"%Y-%m-%dT%H:%M:%SZ")] $1" | tee -a "$LOG_FILE"
45
- }
46
-
47
- # Wait for the system to settle after login (network, services, etc.)
48
- log "Waiting 15s for system to settle..."
49
- sleep 15
50
-
51
- # Check for emergency stop
52
- if [ -f "$AGENT_DIR/.emergency-stop" ]; then
53
- log "Emergency stop active — not starting Claude session"
54
- exit 0
55
- fi
56
-
57
- if [ -f "$MAESTRO_DIR/.emergency-stop" ]; then
58
- log "Emergency stop active in maestro — not starting Claude session"
59
- exit 0
60
- fi
61
-
62
- # Check if claude CLI is available
63
- if ! command -v claude &>/dev/null; then
64
- # Try common paths
65
- CLAUDE_PATH=""
66
- for p in "$HOME/.local/bin/claude" "/opt/homebrew/bin/claude" "/usr/local/bin/claude"; do
67
- if [ -x "$p" ]; then
68
- CLAUDE_PATH="$p"
69
- break
70
- fi
71
- done
72
-
73
- if [ -z "$CLAUDE_PATH" ]; then
74
- log "ERROR: claude CLI not found"
75
- exit 1
76
- fi
77
- else
78
- CLAUDE_PATH=$(which claude)
79
- fi
80
-
81
- log "Starting Claude Code session in $AGENT_DIR (claude: $CLAUDE_PATH)"
82
-
83
- # Open Terminal.app with Claude Code running in the agent directory
84
- osascript <<APPLESCRIPT
85
- tell application "Terminal"
86
- activate
87
- -- Open a new window with claude running in the agent directory
88
- do script "cd '$AGENT_DIR' && clear && echo '╔══════════════════════════════════════════════════════════╗' && echo '║ $AGENT_DISPLAY — Boot Session ($(date +%Y-%m-%d))' && echo '╠══════════════════════════════════════════════════════════╣' && echo '║ Agent dir: $AGENT_DIR' && echo '║ Claude: $CLAUDE_PATH' && echo '╚══════════════════════════════════════════════════════════╝' && echo '' && '$CLAUDE_PATH'"
89
- -- Set the window title
90
- set custom title of front window to "$AGENT_NAME — Claude Code"
91
- end tell
92
- APPLESCRIPT
93
-
94
- log "Terminal window opened with Claude Code session"