gsd-pi 2.57.0 → 2.58.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 (84) hide show
  1. package/dist/resources/extensions/gsd/auto/infra-errors.js +4 -0
  2. package/dist/resources/extensions/gsd/auto-dispatch.js +3 -3
  3. package/dist/resources/extensions/gsd/auto-worktree.js +7 -2
  4. package/dist/resources/extensions/gsd/auto.js +4 -0
  5. package/dist/resources/extensions/gsd/bootstrap/db-tools.js +2 -1
  6. package/dist/resources/extensions/gsd/dispatch-guard.js +11 -1
  7. package/dist/resources/extensions/gsd/gsd-db.js +8 -1
  8. package/dist/resources/extensions/gsd/parallel-orchestrator.js +23 -6
  9. package/dist/resources/extensions/gsd/preferences.js +29 -15
  10. package/dist/resources/extensions/gsd/prompts/validate-milestone.md +2 -2
  11. package/dist/resources/extensions/gsd/tools/validate-milestone.js +4 -0
  12. package/dist/web/standalone/.next/BUILD_ID +1 -1
  13. package/dist/web/standalone/.next/app-path-routes-manifest.json +9 -9
  14. package/dist/web/standalone/.next/build-manifest.json +3 -3
  15. package/dist/web/standalone/.next/prerender-manifest.json +3 -3
  16. package/dist/web/standalone/.next/react-loadable-manifest.json +1 -1
  17. package/dist/web/standalone/.next/required-server-files.json +1 -1
  18. package/dist/web/standalone/.next/server/app/_global-error.html +2 -2
  19. package/dist/web/standalone/.next/server/app/_global-error.rsc +1 -1
  20. package/dist/web/standalone/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
  21. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error/__PAGE__.segment.rsc +1 -1
  22. package/dist/web/standalone/.next/server/app/_global-error.segments/_global-error.segment.rsc +1 -1
  23. package/dist/web/standalone/.next/server/app/_global-error.segments/_head.segment.rsc +1 -1
  24. package/dist/web/standalone/.next/server/app/_global-error.segments/_index.segment.rsc +1 -1
  25. package/dist/web/standalone/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
  26. package/dist/web/standalone/.next/server/app/_not-found.html +1 -1
  27. package/dist/web/standalone/.next/server/app/_not-found.rsc +1 -1
  28. package/dist/web/standalone/.next/server/app/_not-found.segments/_full.segment.rsc +1 -1
  29. package/dist/web/standalone/.next/server/app/_not-found.segments/_head.segment.rsc +1 -1
  30. package/dist/web/standalone/.next/server/app/_not-found.segments/_index.segment.rsc +1 -1
  31. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found/__PAGE__.segment.rsc +1 -1
  32. package/dist/web/standalone/.next/server/app/_not-found.segments/_not-found.segment.rsc +1 -1
  33. package/dist/web/standalone/.next/server/app/_not-found.segments/_tree.segment.rsc +1 -1
  34. package/dist/web/standalone/.next/server/app/api/boot/route.js +1 -1
  35. package/dist/web/standalone/.next/server/app/api/session/events/route.js +1 -1
  36. package/dist/web/standalone/.next/server/app/api/shutdown/route.js +1 -1
  37. package/dist/web/standalone/.next/server/app/index.html +1 -1
  38. package/dist/web/standalone/.next/server/app/index.rsc +1 -1
  39. package/dist/web/standalone/.next/server/app/index.segments/__PAGE__.segment.rsc +1 -1
  40. package/dist/web/standalone/.next/server/app/index.segments/_full.segment.rsc +1 -1
  41. package/dist/web/standalone/.next/server/app/index.segments/_head.segment.rsc +1 -1
  42. package/dist/web/standalone/.next/server/app/index.segments/_index.segment.rsc +1 -1
  43. package/dist/web/standalone/.next/server/app/index.segments/_tree.segment.rsc +1 -1
  44. package/dist/web/standalone/.next/server/app-paths-manifest.json +9 -9
  45. package/dist/web/standalone/.next/server/middleware-build-manifest.js +1 -1
  46. package/dist/web/standalone/.next/server/middleware-react-loadable-manifest.js +1 -1
  47. package/dist/web/standalone/.next/server/pages/404.html +1 -1
  48. package/dist/web/standalone/.next/server/pages/500.html +2 -2
  49. package/dist/web/standalone/.next/server/server-reference-manifest.json +1 -1
  50. package/dist/web/standalone/.next/static/chunks/6502.8b732f67a11b11b4.js +9 -0
  51. package/dist/web/standalone/.next/static/chunks/{webpack-4332cbd5dd1be584.js → webpack-61d3afac6d0f0ce7.js} +1 -1
  52. package/dist/web/standalone/server.js +1 -1
  53. package/package.json +1 -1
  54. package/packages/daemon/src/cli.ts +49 -0
  55. package/packages/daemon/src/daemon.test.ts +104 -1
  56. package/packages/daemon/src/daemon.ts +23 -0
  57. package/packages/daemon/src/discord-bot.ts +62 -3
  58. package/packages/daemon/src/index.ts +9 -0
  59. package/packages/daemon/src/launchd.test.ts +356 -0
  60. package/packages/daemon/src/launchd.ts +242 -0
  61. package/packages/pi-coding-agent/package.json +1 -1
  62. package/pkg/package.json +1 -1
  63. package/src/resources/extensions/gsd/auto/infra-errors.ts +3 -0
  64. package/src/resources/extensions/gsd/auto-dispatch.ts +3 -3
  65. package/src/resources/extensions/gsd/auto-worktree.ts +7 -2
  66. package/src/resources/extensions/gsd/auto.ts +5 -0
  67. package/src/resources/extensions/gsd/bootstrap/db-tools.ts +2 -1
  68. package/src/resources/extensions/gsd/dispatch-guard.ts +12 -1
  69. package/src/resources/extensions/gsd/gsd-db.ts +6 -1
  70. package/src/resources/extensions/gsd/parallel-orchestrator.ts +23 -6
  71. package/src/resources/extensions/gsd/preferences.ts +32 -14
  72. package/src/resources/extensions/gsd/prompts/validate-milestone.md +2 -2
  73. package/src/resources/extensions/gsd/tests/auto-loop.test.ts +18 -0
  74. package/src/resources/extensions/gsd/tests/dispatch-guard.test.ts +47 -0
  75. package/src/resources/extensions/gsd/tests/parallel-worker-monitoring.test.ts +9 -8
  76. package/src/resources/extensions/gsd/tests/preferences.test.ts +34 -0
  77. package/src/resources/extensions/gsd/tests/prompt-contracts.test.ts +7 -0
  78. package/src/resources/extensions/gsd/tests/validate-milestone-write-order.test.ts +23 -1
  79. package/src/resources/extensions/gsd/tests/validation-gate-patterns.test.ts +44 -2
  80. package/src/resources/extensions/gsd/tests/worktree-db-same-file.test.ts +175 -0
  81. package/src/resources/extensions/gsd/tools/validate-milestone.ts +5 -0
  82. package/dist/web/standalone/.next/static/chunks/6502.2305d0afd2385711.js +0 -9
  83. /package/dist/web/standalone/.next/static/{yowc5qPtuKxjOr22KmOAy → IoheXIe-5DH7ieX8AUo8U}/_buildManifest.js +0 -0
  84. /package/dist/web/standalone/.next/static/{yowc5qPtuKxjOr22KmOAy → IoheXIe-5DH7ieX8AUo8U}/_ssgManifest.js +0 -0
@@ -0,0 +1,356 @@
1
+ import { describe, it, beforeEach, afterEach } from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import { mkdtempSync, existsSync, readFileSync, writeFileSync, rmSync, mkdirSync, statSync } from 'node:fs';
4
+ import { join, dirname } from 'node:path';
5
+ import { tmpdir, homedir } from 'node:os';
6
+ import { randomUUID } from 'node:crypto';
7
+ import {
8
+ escapeXml,
9
+ generatePlist,
10
+ getPlistPath,
11
+ install,
12
+ uninstall,
13
+ status,
14
+ } from './launchd.js';
15
+ import type { PlistOptions, RunCommandFn, LaunchdStatus } from './launchd.js';
16
+
17
+ // ---------- helpers ----------
18
+
19
+ function tmpDir(): string {
20
+ return mkdtempSync(join(tmpdir(), `launchd-test-${randomUUID().slice(0, 8)}-`));
21
+ }
22
+
23
+ const cleanupDirs: string[] = [];
24
+ afterEach(() => {
25
+ while (cleanupDirs.length) {
26
+ const d = cleanupDirs.pop()!;
27
+ if (existsSync(d)) rmSync(d, { recursive: true, force: true });
28
+ }
29
+ });
30
+
31
+ function basePlistOpts(overrides?: Partial<PlistOptions>): PlistOptions {
32
+ return {
33
+ nodePath: '/usr/local/bin/node',
34
+ scriptPath: '/usr/local/lib/gsd-daemon/dist/cli.js',
35
+ configPath: join(homedir(), '.gsd', 'daemon.yaml'),
36
+ ...overrides,
37
+ };
38
+ }
39
+
40
+ // ---------- escapeXml ----------
41
+
42
+ describe('escapeXml', () => {
43
+ it('escapes & < > " \'', () => {
44
+ assert.equal(escapeXml('a&b<c>d"e\'f'), 'a&amp;b&lt;c&gt;d&quot;e&apos;f');
45
+ });
46
+
47
+ it('leaves plain strings untouched', () => {
48
+ assert.equal(escapeXml('/usr/local/bin/node'), '/usr/local/bin/node');
49
+ });
50
+
51
+ it('escapes paths with spaces and special chars', () => {
52
+ const input = '/Users/John & Jane/my "project"/file.js';
53
+ const output = escapeXml(input);
54
+ assert.ok(output.includes('&amp;'));
55
+ assert.ok(output.includes('&quot;'));
56
+ // Verify no raw unescaped & remain (all & are part of &amp; &lt; etc.)
57
+ assert.equal(output, '/Users/John &amp; Jane/my &quot;project&quot;/file.js');
58
+ });
59
+ });
60
+
61
+ // ---------- generatePlist ----------
62
+
63
+ describe('generatePlist', () => {
64
+ it('produces valid XML with plist header', () => {
65
+ const xml = generatePlist(basePlistOpts());
66
+ assert.ok(xml.startsWith('<?xml version="1.0"'));
67
+ assert.ok(xml.includes('<!DOCTYPE plist'));
68
+ assert.ok(xml.includes('<plist version="1.0">'));
69
+ assert.ok(xml.includes('</plist>'));
70
+ });
71
+
72
+ it('includes label com.gsd.daemon', () => {
73
+ const xml = generatePlist(basePlistOpts());
74
+ assert.ok(xml.includes('<string>com.gsd.daemon</string>'));
75
+ });
76
+
77
+ it('uses the absolute node path from opts', () => {
78
+ const opts = basePlistOpts({ nodePath: '/home/user/.nvm/versions/node/v22.0.0/bin/node' });
79
+ const xml = generatePlist(opts);
80
+ assert.ok(xml.includes('<string>/home/user/.nvm/versions/node/v22.0.0/bin/node</string>'));
81
+ });
82
+
83
+ it('includes NVM bin directory in PATH', () => {
84
+ const opts = basePlistOpts({ nodePath: '/home/user/.nvm/versions/node/v22.0.0/bin/node' });
85
+ const xml = generatePlist(opts);
86
+ assert.ok(xml.includes('/home/user/.nvm/versions/node/v22.0.0/bin'));
87
+ });
88
+
89
+ it('sets KeepAlive with SuccessfulExit false', () => {
90
+ const xml = generatePlist(basePlistOpts());
91
+ assert.ok(xml.includes('<key>KeepAlive</key>'));
92
+ assert.ok(xml.includes('<key>SuccessfulExit</key>'));
93
+ assert.ok(xml.includes('<false/>'));
94
+ });
95
+
96
+ it('sets RunAtLoad true', () => {
97
+ const xml = generatePlist(basePlistOpts());
98
+ assert.ok(xml.includes('<key>RunAtLoad</key>'));
99
+ assert.ok(xml.includes('<true/>'));
100
+ });
101
+
102
+ it('includes --config with the config path', () => {
103
+ const configPath = '/custom/path/daemon.yaml';
104
+ const xml = generatePlist(basePlistOpts({ configPath }));
105
+ assert.ok(xml.includes('<string>--config</string>'));
106
+ assert.ok(xml.includes(`<string>${configPath}</string>`));
107
+ });
108
+
109
+ it('includes HOME environment variable', () => {
110
+ const xml = generatePlist(basePlistOpts());
111
+ assert.ok(xml.includes('<key>HOME</key>'));
112
+ assert.ok(xml.includes(`<string>${homedir()}</string>`));
113
+ });
114
+
115
+ it('includes StandardOutPath and StandardErrorPath', () => {
116
+ const xml = generatePlist(basePlistOpts());
117
+ assert.ok(xml.includes('<key>StandardOutPath</key>'));
118
+ assert.ok(xml.includes('<key>StandardErrorPath</key>'));
119
+ });
120
+
121
+ it('escapes special characters in paths', () => {
122
+ const opts = basePlistOpts({
123
+ configPath: '/Users/John & Jane/config.yaml',
124
+ });
125
+ const xml = generatePlist(opts);
126
+ assert.ok(xml.includes('John &amp; Jane'));
127
+ assert.ok(!xml.includes('John & Jane'));
128
+ });
129
+
130
+ it('uses custom stdout/stderr paths when provided', () => {
131
+ const opts = basePlistOpts({
132
+ stdoutPath: '/tmp/my-stdout.log',
133
+ stderrPath: '/tmp/my-stderr.log',
134
+ });
135
+ const xml = generatePlist(opts);
136
+ assert.ok(xml.includes('<string>/tmp/my-stdout.log</string>'));
137
+ assert.ok(xml.includes('<string>/tmp/my-stderr.log</string>'));
138
+ });
139
+
140
+ it('uses custom working directory when provided', () => {
141
+ const opts = basePlistOpts({
142
+ workingDirectory: '/custom/work/dir',
143
+ });
144
+ const xml = generatePlist(opts);
145
+ assert.ok(xml.includes('<string>/custom/work/dir</string>'));
146
+ });
147
+ });
148
+
149
+ // ---------- getPlistPath ----------
150
+
151
+ describe('getPlistPath', () => {
152
+ it('returns ~/Library/LaunchAgents/com.gsd.daemon.plist', () => {
153
+ const expected = join(homedir(), 'Library', 'LaunchAgents', 'com.gsd.daemon.plist');
154
+ assert.equal(getPlistPath(), expected);
155
+ });
156
+ });
157
+
158
+ // ---------- install ----------
159
+
160
+ describe('install', () => {
161
+ let tmp: string;
162
+ let fakePlistPath: string;
163
+
164
+ // We can't mock getPlistPath directly, but we can verify the commands
165
+ // issued and the plist content by intercepting runCommand and filesystem ops.
166
+ // For filesystem testing, we test the functions that call writeFileSync indirectly
167
+ // by verifying the runCommand calls and returned values.
168
+
169
+ it('calls launchctl load with the plist path', () => {
170
+ const calls: string[] = [];
171
+ const mockRun: RunCommandFn = (cmd: string) => {
172
+ calls.push(cmd);
173
+ return '';
174
+ };
175
+
176
+ // install will try to write to the real plist path, so we need to be careful.
177
+ // We test the command flow by catching the writeFileSync error (dir may not exist in CI)
178
+ // or by letting it proceed in local dev.
179
+ try {
180
+ install(basePlistOpts(), mockRun);
181
+ } catch {
182
+ // writeFileSync may fail if ~/Library/LaunchAgents doesn't exist in test env
183
+ }
184
+
185
+ const loadCalls = calls.filter(c => c.startsWith('launchctl load'));
186
+ const listCalls = calls.filter(c => c.startsWith('launchctl list'));
187
+ // Should have at least attempted launchctl load
188
+ assert.ok(loadCalls.length > 0 || calls.length > 0, 'Expected launchctl commands to be called');
189
+ });
190
+
191
+ it('generates valid plist content when called', () => {
192
+ // Test that the plist content would be correct by testing generatePlist
193
+ // (install is a thin wrapper around generatePlist + writeFile + launchctl)
194
+ const xml = generatePlist(basePlistOpts());
195
+ assert.ok(xml.includes('<key>Label</key>'));
196
+ assert.ok(xml.includes('<string>com.gsd.daemon</string>'));
197
+ });
198
+
199
+ it('handles idempotent install (unloads first if plist exists)', () => {
200
+ const calls: string[] = [];
201
+ const mockRun: RunCommandFn = (cmd: string) => {
202
+ calls.push(cmd);
203
+ return '';
204
+ };
205
+
206
+ // To simulate idempotent install, we need an existing plist file.
207
+ // Since install writes to getPlistPath(), we test the command sequence.
208
+ try {
209
+ install(basePlistOpts(), mockRun);
210
+ // Second install
211
+ install(basePlistOpts(), mockRun);
212
+ } catch {
213
+ // filesystem may not be writable
214
+ }
215
+
216
+ // The second install should have tried to unload first
217
+ const unloadCalls = calls.filter(c => c.startsWith('launchctl unload'));
218
+ // If the plist path exists, we expect at least one unload attempt on second call
219
+ // This is a command-level check; filesystem existence depends on environment
220
+ });
221
+ });
222
+
223
+ // ---------- uninstall ----------
224
+
225
+ describe('uninstall', () => {
226
+ it('calls launchctl unload when plist would exist', () => {
227
+ const calls: string[] = [];
228
+ const mockRun: RunCommandFn = (cmd: string) => {
229
+ calls.push(cmd);
230
+ return '';
231
+ };
232
+
233
+ // uninstall checks existsSync(plistPath) — if plist doesn't exist, it's a no-op
234
+ uninstall(mockRun);
235
+
236
+ // If plist doesn't exist in test environment, calls should be empty (graceful)
237
+ // That's the "handles missing plist gracefully" case
238
+ });
239
+
240
+ it('handles missing plist gracefully (no-op)', () => {
241
+ const calls: string[] = [];
242
+ const mockRun: RunCommandFn = (cmd: string) => {
243
+ calls.push(cmd);
244
+ return '';
245
+ };
246
+
247
+ // Shouldn't throw even if plist doesn't exist
248
+ assert.doesNotThrow(() => uninstall(mockRun));
249
+ });
250
+
251
+ it('handles already-unloaded agent gracefully', () => {
252
+ const mockRun: RunCommandFn = (cmd: string) => {
253
+ if (cmd.includes('launchctl unload')) {
254
+ throw new Error('Could not find specified service');
255
+ }
256
+ return '';
257
+ };
258
+
259
+ // Should not throw even if launchctl unload fails
260
+ assert.doesNotThrow(() => uninstall(mockRun));
261
+ });
262
+ });
263
+
264
+ // ---------- status ----------
265
+
266
+ describe('status', () => {
267
+ it('parses running daemon output (PID present)', () => {
268
+ const mockRun: RunCommandFn = (_cmd: string) => {
269
+ return '{\n\t"PID" = 1234;\n\t"Label" = "com.gsd.daemon";\n}\nPID\tStatus\tLabel\n1234\t0\tcom.gsd.daemon\n';
270
+ };
271
+
272
+ const result = status(mockRun);
273
+ assert.equal(result.registered, true);
274
+ assert.equal(result.pid, 1234);
275
+ assert.equal(result.lastExitStatus, 0);
276
+ });
277
+
278
+ it('parses stopped daemon output (no PID)', () => {
279
+ const mockRun: RunCommandFn = (_cmd: string) => {
280
+ return 'PID\tStatus\tLabel\n-\t78\tcom.gsd.daemon\n';
281
+ };
282
+
283
+ const result = status(mockRun);
284
+ assert.equal(result.registered, true);
285
+ assert.equal(result.pid, null);
286
+ assert.equal(result.lastExitStatus, 78);
287
+ });
288
+
289
+ it('returns not-registered when launchctl list fails', () => {
290
+ const mockRun: RunCommandFn = (_cmd: string) => {
291
+ throw new Error('Could not find service "com.gsd.daemon" in domain for port');
292
+ };
293
+
294
+ const result = status(mockRun);
295
+ assert.equal(result.registered, false);
296
+ assert.equal(result.pid, null);
297
+ assert.equal(result.lastExitStatus, null);
298
+ });
299
+
300
+ it('returns structured result with all fields', () => {
301
+ const mockRun: RunCommandFn = (_cmd: string) => {
302
+ return 'PID\tStatus\tLabel\n5678\t0\tcom.gsd.daemon\n';
303
+ };
304
+
305
+ const result = status(mockRun);
306
+ assert.ok('registered' in result);
307
+ assert.ok('pid' in result);
308
+ assert.ok('lastExitStatus' in result);
309
+ });
310
+
311
+ it('parses JSON-style dict output (newer macOS)', () => {
312
+ const mockRun: RunCommandFn = (_cmd: string) => {
313
+ return `{
314
+ \t"StandardOutPath" = "/Users/me/.gsd/daemon-stdout.log";
315
+ \t"LimitLoadToSessionType" = "Aqua";
316
+ \t"StandardErrorPath" = "/Users/me/.gsd/daemon-stderr.log";
317
+ \t"Label" = "com.gsd.daemon";
318
+ \t"OnDemand" = true;
319
+ \t"LastExitStatus" = 0;
320
+ \t"PID" = 23802;
321
+ \t"Program" = "/usr/local/bin/node";
322
+ };`;
323
+ };
324
+
325
+ const result = status(mockRun);
326
+ assert.equal(result.registered, true);
327
+ assert.equal(result.pid, 23802);
328
+ assert.equal(result.lastExitStatus, 0);
329
+ });
330
+
331
+ it('parses JSON-style dict output when daemon stopped (no PID key)', () => {
332
+ const mockRun: RunCommandFn = (_cmd: string) => {
333
+ return `{
334
+ \t"Label" = "com.gsd.daemon";
335
+ \t"LastExitStatus" = 1;
336
+ \t"OnDemand" = true;
337
+ };`;
338
+ };
339
+
340
+ const result = status(mockRun);
341
+ assert.equal(result.registered, true);
342
+ assert.equal(result.pid, null);
343
+ assert.equal(result.lastExitStatus, 1);
344
+ });
345
+
346
+ it('handles unexpected output format gracefully', () => {
347
+ const mockRun: RunCommandFn = (_cmd: string) => {
348
+ return 'some unexpected output without the label';
349
+ };
350
+
351
+ // Should not throw — should return registered:true but with null fields
352
+ // since the command succeeded (label was found) but output didn't match
353
+ const result = status(mockRun);
354
+ assert.equal(result.registered, true);
355
+ });
356
+ });
@@ -0,0 +1,242 @@
1
+ import { writeFileSync, unlinkSync, existsSync, chmodSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import { homedir } from 'node:os';
4
+ import { execSync } from 'node:child_process';
5
+ import { dirname } from 'node:path';
6
+
7
+ // --------------- types ---------------
8
+
9
+ export interface PlistOptions {
10
+ /** Absolute path to the Node.js binary */
11
+ nodePath: string;
12
+ /** Absolute path to the daemon script (cli.js) */
13
+ scriptPath: string;
14
+ /** Absolute path to the config file */
15
+ configPath: string;
16
+ /** Directory to use as WorkingDirectory in the plist (defaults to homedir) */
17
+ workingDirectory?: string;
18
+ /** Override stdout log path */
19
+ stdoutPath?: string;
20
+ /** Override stderr log path */
21
+ stderrPath?: string;
22
+ }
23
+
24
+ export interface LaunchdStatus {
25
+ /** Whether the daemon is registered with launchd */
26
+ registered: boolean;
27
+ /** PID if currently running, null otherwise */
28
+ pid: number | null;
29
+ /** Last exit status code, null if never exited or not available */
30
+ lastExitStatus: number | null;
31
+ }
32
+
33
+ export type RunCommandFn = (cmd: string) => string;
34
+
35
+ // --------------- constants ---------------
36
+
37
+ const LABEL = 'com.gsd.daemon';
38
+ const PLIST_FILENAME = `${LABEL}.plist`;
39
+
40
+ // --------------- helpers ---------------
41
+
42
+ /** Escape special XML characters in a string. */
43
+ export function escapeXml(str: string): string {
44
+ return str
45
+ .replace(/&/g, '&amp;')
46
+ .replace(/</g, '&lt;')
47
+ .replace(/>/g, '&gt;')
48
+ .replace(/"/g, '&quot;')
49
+ .replace(/'/g, '&apos;');
50
+ }
51
+
52
+ /** Return the canonical plist path under ~/Library/LaunchAgents/. */
53
+ export function getPlistPath(): string {
54
+ return resolve(homedir(), 'Library', 'LaunchAgents', PLIST_FILENAME);
55
+ }
56
+
57
+ /**
58
+ * Build the NVM-aware PATH string.
59
+ * Includes the directory containing the Node binary so that launchd can find node
60
+ * even when launched outside a shell session (where NVM isn't sourced).
61
+ */
62
+ function buildEnvPath(nodePath: string): string {
63
+ const nodeBinDir = dirname(nodePath);
64
+ // Keep system essentials and prepend the node binary's directory
65
+ return `${nodeBinDir}:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin`;
66
+ }
67
+
68
+ // --------------- plist generation ---------------
69
+
70
+ /** Generate valid launchd plist XML for the GSD daemon. */
71
+ export function generatePlist(opts: PlistOptions): string {
72
+ const home = homedir();
73
+ const workDir = opts.workingDirectory ?? home;
74
+ const stdoutPath = opts.stdoutPath ?? resolve(home, '.gsd', 'daemon-stdout.log');
75
+ const stderrPath = opts.stderrPath ?? resolve(home, '.gsd', 'daemon-stderr.log');
76
+ const envPath = buildEnvPath(opts.nodePath);
77
+
78
+ // Forward ANTHROPIC_API_KEY so the orchestrator LLM can authenticate.
79
+ // Captured at install time from the current process environment.
80
+ const anthropicKey = process.env.ANTHROPIC_API_KEY;
81
+ const anthropicKeyXml = anthropicKey
82
+ ? `\n\t\t<key>ANTHROPIC_API_KEY</key>\n\t\t<string>${escapeXml(anthropicKey)}</string>`
83
+ : '';
84
+
85
+ return `<?xml version="1.0" encoding="UTF-8"?>
86
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
87
+ <plist version="1.0">
88
+ <dict>
89
+ \t<key>Label</key>
90
+ \t<string>${escapeXml(LABEL)}</string>
91
+
92
+ \t<key>ProgramArguments</key>
93
+ \t<array>
94
+ \t\t<string>${escapeXml(opts.nodePath)}</string>
95
+ \t\t<string>${escapeXml(opts.scriptPath)}</string>
96
+ \t\t<string>--config</string>
97
+ \t\t<string>${escapeXml(opts.configPath)}</string>
98
+ \t</array>
99
+
100
+ \t<key>KeepAlive</key>
101
+ \t<dict>
102
+ \t\t<key>SuccessfulExit</key>
103
+ \t\t<false/>
104
+ \t</dict>
105
+
106
+ \t<key>RunAtLoad</key>
107
+ \t<true/>
108
+
109
+ \t<key>EnvironmentVariables</key>
110
+ \t<dict>
111
+ \t\t<key>PATH</key>
112
+ \t\t<string>${escapeXml(envPath)}</string>
113
+ \t\t<key>HOME</key>
114
+ \t\t<string>${escapeXml(home)}</string>${anthropicKeyXml}
115
+ \t</dict>
116
+
117
+ \t<key>WorkingDirectory</key>
118
+ \t<string>${escapeXml(workDir)}</string>
119
+
120
+ \t<key>StandardOutPath</key>
121
+ \t<string>${escapeXml(stdoutPath)}</string>
122
+
123
+ \t<key>StandardErrorPath</key>
124
+ \t<string>${escapeXml(stderrPath)}</string>
125
+ </dict>
126
+ </plist>
127
+ `;
128
+ }
129
+
130
+ // --------------- install / uninstall / status ---------------
131
+
132
+ /** Default runCommand using execSync. */
133
+ function defaultRunCommand(cmd: string): string {
134
+ return execSync(cmd, { encoding: 'utf-8', stdio: ['pipe', 'pipe', 'pipe'] });
135
+ }
136
+
137
+ /**
138
+ * Install the launchd agent: write plist and load it.
139
+ * Idempotent — unloads first if already loaded.
140
+ */
141
+ export function install(
142
+ opts: PlistOptions,
143
+ runCommand: RunCommandFn = defaultRunCommand,
144
+ ): void {
145
+ const plistPath = getPlistPath();
146
+ const xml = generatePlist(opts);
147
+
148
+ // Unload first if already present (ignore errors)
149
+ if (existsSync(plistPath)) {
150
+ try {
151
+ runCommand(`launchctl unload ${plistPath}`);
152
+ } catch {
153
+ // already unloaded — fine
154
+ }
155
+ }
156
+
157
+ writeFileSync(plistPath, xml, 'utf-8');
158
+ chmodSync(plistPath, 0o644);
159
+
160
+ runCommand(`launchctl load ${plistPath}`);
161
+
162
+ // Verify it loaded
163
+ try {
164
+ runCommand(`launchctl list ${LABEL}`);
165
+ } catch {
166
+ throw new Error(
167
+ `Plist was written to ${plistPath} and launchctl load succeeded, but launchctl list ${LABEL} failed. The agent may not have started.`,
168
+ );
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Uninstall the launchd agent: unload and remove plist.
174
+ * Graceful — does not throw if already uninstalled.
175
+ */
176
+ export function uninstall(runCommand: RunCommandFn = defaultRunCommand): void {
177
+ const plistPath = getPlistPath();
178
+
179
+ if (existsSync(plistPath)) {
180
+ try {
181
+ runCommand(`launchctl unload ${plistPath}`);
182
+ } catch {
183
+ // already unloaded — that's fine
184
+ }
185
+ unlinkSync(plistPath);
186
+ }
187
+ // If plist doesn't exist, nothing to do — already uninstalled
188
+ }
189
+
190
+ /**
191
+ * Query launchd for the daemon's status.
192
+ * Returns structured information about registration, PID, and last exit code.
193
+ *
194
+ * Handles two launchctl output formats:
195
+ * 1. Tabular: "PID\tStatus\tLabel" (older macOS)
196
+ * 2. JSON-style dict: `"PID" = 1234;` / `"LastExitStatus" = 0;` (newer macOS)
197
+ */
198
+ export function status(runCommand: RunCommandFn = defaultRunCommand): LaunchdStatus {
199
+ try {
200
+ const output = runCommand(`launchctl list ${LABEL}`);
201
+
202
+ // --- Try tabular format first ---
203
+ const lines = output.trim().split('\n');
204
+ for (const line of lines) {
205
+ const parts = line.trim().split(/\t+/);
206
+ if (parts.length >= 3 && parts[2] === LABEL) {
207
+ const pidStr = parts[0];
208
+ const statusStr = parts[1];
209
+
210
+ const pid = pidStr === '-' ? null : parseInt(pidStr, 10);
211
+ const lastExitStatus = statusStr != null ? parseInt(statusStr, 10) : null;
212
+
213
+ return {
214
+ registered: true,
215
+ pid: Number.isNaN(pid!) ? null : pid,
216
+ lastExitStatus: Number.isNaN(lastExitStatus!) ? null : lastExitStatus,
217
+ };
218
+ }
219
+ }
220
+
221
+ // --- Try JSON-style dict format ---
222
+ // Matches: "PID" = 1234; or "LastExitStatus" = 0;
223
+ const pidMatch = output.match(/"PID"\s*=\s*(\d+)\s*;/);
224
+ const exitMatch = output.match(/"LastExitStatus"\s*=\s*(\d+)\s*;/);
225
+
226
+ if (pidMatch || exitMatch) {
227
+ const pid = pidMatch ? parseInt(pidMatch[1], 10) : null;
228
+ const lastExitStatus = exitMatch ? parseInt(exitMatch[1], 10) : null;
229
+ return {
230
+ registered: true,
231
+ pid: Number.isNaN(pid!) ? null : pid,
232
+ lastExitStatus: Number.isNaN(lastExitStatus!) ? null : lastExitStatus,
233
+ };
234
+ }
235
+
236
+ // Label resolved (no error) but no parseable output — still registered
237
+ return { registered: true, pid: null, lastExitStatus: null };
238
+ } catch {
239
+ // launchctl list exits non-zero when the label isn't found
240
+ return { registered: false, pid: null, lastExitStatus: null };
241
+ }
242
+ }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@gsd/pi-coding-agent",
3
- "version": "2.57.0",
3
+ "version": "2.58.0",
4
4
  "description": "Coding agent CLI (vendored from pi-mono)",
5
5
  "type": "module",
6
6
  "piConfig": {
package/pkg/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@glittercowboy/gsd",
3
- "version": "2.57.0",
3
+ "version": "2.58.0",
4
4
  "piConfig": {
5
5
  "name": "gsd",
6
6
  "configDir": ".gsd"
@@ -41,5 +41,8 @@ export function isInfrastructureError(err: unknown): string | null {
41
41
  for (const code of INFRA_ERROR_CODES) {
42
42
  if (msg.includes(code)) return code;
43
43
  }
44
+ // SQLite WAL corruption is not transient — retrying burns LLM budget
45
+ // for guaranteed failures (#2823).
46
+ if (msg.includes("database disk image is malformed")) return "SQLITE_CORRUPT";
44
47
  return null;
45
48
  }
@@ -677,13 +677,13 @@ export const DISPATCH_RULES: DispatchRule[] = [
677
677
  if (validationPath) {
678
678
  const validationContent = await loadFile(validationPath);
679
679
  if (validationContent) {
680
- // Accept either the structured template format (table with MET/N/A)
680
+ // Accept either the structured template format (table with MET/N/A/SATISFIED)
681
681
  // or prose evidence patterns the validation agent may emit.
682
682
  const structuredMatch =
683
683
  validationContent.includes("Operational") &&
684
- (validationContent.includes("MET") || validationContent.includes("N/A"));
684
+ (validationContent.includes("MET") || validationContent.includes("N/A") || validationContent.includes("SATISFIED"));
685
685
  const proseMatch =
686
- /[Oo]perational[\s:][^\n]*(?:pass|verified|confirmed|met|complete|true|yes|addressed|covered|n\/a|not\s+applicable)/i.test(validationContent);
686
+ /[Oo]perational[\s\S]{0,500}?(?:✅|pass|verified|confirmed|met|complete|true|yes|addressed|covered|satisfied|partially|n\/a|not[\s-]+applicable)/i.test(validationContent);
687
687
  const hasOperationalCheck = structuredMatch || proseMatch;
688
688
  if (!hasOperationalCheck) {
689
689
  return {
@@ -1264,12 +1264,17 @@ export function mergeMilestoneToMain(
1264
1264
  // 1. Auto-commit dirty state in worktree before leaving
1265
1265
  autoCommitDirtyState(worktreeCwd);
1266
1266
 
1267
- // Reconcile worktree DB into main DB before leaving worktree context
1267
+ // Reconcile worktree DB into main DB before leaving worktree context.
1268
+ // Skip when both paths resolve to the same physical file (shared WAL /
1269
+ // symlink layout) — ATTACHing a WAL-mode file to itself corrupts the
1270
+ // database (#2823).
1268
1271
  if (isDbAvailable()) {
1269
1272
  try {
1270
1273
  const worktreeDbPath = join(worktreeCwd, ".gsd", "gsd.db");
1271
1274
  const mainDbPath = join(originalBasePath_, ".gsd", "gsd.db");
1272
- reconcileWorktreeDb(mainDbPath, worktreeDbPath);
1275
+ if (!isSamePath(worktreeDbPath, mainDbPath)) {
1276
+ reconcileWorktreeDb(mainDbPath, worktreeDbPath);
1277
+ }
1273
1278
  } catch {
1274
1279
  /* non-fatal */
1275
1280
  }
@@ -1061,6 +1061,11 @@ export async function startAuto(
1061
1061
  verboseMode: boolean,
1062
1062
  options?: { step?: boolean },
1063
1063
  ): Promise<void> {
1064
+ if (s.active) {
1065
+ debugLog("startAuto", { phase: "already-active", skipping: true });
1066
+ return;
1067
+ }
1068
+
1064
1069
  const requestedStepMode = options?.step ?? false;
1065
1070
 
1066
1071
  // Escape stale worktree cwd from a previous milestone (#608).