@anhlp/alp-daemon 0.0.0-beta.1 → 0.10.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.
package/src/main.ts CHANGED
@@ -4,21 +4,17 @@ import { mkdir, open, readFile, rename, stat, unlink, utimes, writeFile } from '
4
4
  import path from 'node:path';
5
5
  import { fileURLToPath } from 'node:url';
6
6
  import templates from 'alp:templates';
7
- import { alpHome, daemonPaths, assertPrivateDirectory, PROTOCOL_VERSION } from '@anhlp/alp-client/index';
7
+ import { alpHome, daemonPaths, PROTOCOL_VERSION } from '@anhlp/alp-client/index';
8
8
  import { createAlpRuntime, reclaimCopies, reclaimWorktrees } from '@anhlp/alp-runtime/index';
9
9
  import { createDaemonServer } from './server.js';
10
10
  import { acquireLock, heartbeat, releaseLock, updateLock } from './lock.js';
11
11
  import { createStore } from './store.js';
12
12
  import { validateUserSettings } from '@anhlp/alp-core/validation';
13
- import { clearRestoredMarker, readRestoredMarker, recoverInterruptedRestore } from '@anhlp/alp-core/backup';
14
- import { migrateState } from '@anhlp/alp-core/migrations';
15
- import { createLogger } from '@anhlp/alp-core/log';
16
13
 
17
14
  declare const __ALP_VERSION__: string;
18
15
  const VERSION = typeof __ALP_VERSION__ === 'string' ? __ALP_VERSION__ : '0.0.0-dev';
19
16
  const LOG_BYTES = 10 * 1024 * 1024;
20
17
  const LOG_FILES = 3;
21
- const log = createLogger({ component: 'alpd' });
22
18
 
23
19
  async function rotate(log: string) {
24
20
  const size = await stat(log).then(info => info.size, () => 0);
@@ -30,9 +26,8 @@ async function rotate(log: string) {
30
26
 
31
27
  /** Starts the daemon in a new session and returns at once, so it is not part of the caller's process tree. */
32
28
  async function detach(home: string) {
33
- await assertPrivateDirectory(home, { create: true });
34
29
  const { log } = daemonPaths(home);
35
- await assertPrivateDirectory(path.dirname(log), { create: true });
30
+ await mkdir(path.dirname(log), { recursive: true, mode: 0o700 });
36
31
  await rotate(log);
37
32
  const output = await open(log, 'a', 0o600);
38
33
  const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], {
@@ -51,9 +46,8 @@ async function detach(home: string) {
51
46
  * manager's own file keeps only what Node prints when it dies.
52
47
  */
53
48
  async function serviceLog(home: string) {
54
- await assertPrivateDirectory(home, { create: true });
55
49
  const { log } = daemonPaths(home);
56
- await assertPrivateDirectory(path.dirname(log), { create: true });
50
+ await mkdir(path.dirname(log), { recursive: true, mode: 0o700 });
57
51
  await rotate(log);
58
52
  const fd = openSync(log, 'a', 0o600);
59
53
  for (const stream of [process.stdout, process.stderr]) {
@@ -77,7 +71,7 @@ async function userSettings(home: string): Promise<any> {
77
71
  try { text = await readFile(file, 'utf8'); } catch { return {}; }
78
72
  try { return validateUserSettings(JSON.parse(text), file); }
79
73
  catch (error: any) {
80
- log.warn(`ignoring ${file}: ${error?.message ?? error}`, { code: 'ALP_SETTINGS_INVALID' });
74
+ console.error(`${new Date().toISOString()} ignoring ${file}: ${error?.message ?? error}`);
81
75
  return {};
82
76
  }
83
77
  }
@@ -92,98 +86,39 @@ async function previousExit(marker: string): Promise<{ kind: 'clean' | 'crash';
92
86
  return info ? { kind: 'crash', at: info.mtime.toISOString() } : { kind: 'clean' };
93
87
  }
94
88
 
95
- /** Whether a process group `id` exists; on POSIX a pid is never reused while its group lives. */
96
- function groupAlive(id: number) {
97
- try { process.kill(-id, 0); return true; } catch (error: any) { return error?.code === 'EPERM'; }
98
- }
99
-
100
- /** alpd leads its own process group when started detached or by a service manager. */
101
- const leadsGroup = () => process.platform !== 'win32' && groupAlive(process.pid);
102
-
103
- /**
104
- * Stops what a crashed alpd left running (ALPD §66): its provider processes normally exit
105
- * when their stdin closes, but a stuck one, or a command an agent started, can outlive it.
106
- * They stay in the crashed alpd's process group, so alpd ends that group when the crashed
107
- * one led its group and this one leads its own (so it is not a member). Not on Windows.
108
- */
109
- async function stopLeftovers(previous: { pid?: number; groupLeader?: boolean } | undefined) {
110
- const pid = previous?.pid;
111
- if (!previous?.groupLeader || !Number.isSafeInteger(pid) || pid === process.pid || !leadsGroup() || !groupAlive(pid!)) return;
112
- log.warn(`stopping processes the previous alpd (pid ${pid}) left running`, { code: 'ALP_LEFTOVER_PROCESSES', previousPid: pid });
113
- const signal = (name: NodeJS.Signals) => { try { process.kill(-pid!, name); } catch {} };
114
- signal('SIGTERM');
115
- for (let waited = 0; waited < 3000 && groupAlive(pid!); waited += 50) await new Promise(resolve => setTimeout(resolve, 50));
116
- if (groupAlive(pid!)) signal('SIGKILL');
117
- }
118
-
119
- /** Where start-up stands, so a failure says which step it stopped at. */
120
- type Phase = 'home' | 'lock' | 'state' | 'recovery' | 'listen' | 'ready';
121
- let phase: Phase = 'home';
122
- const STARTUP_CODES = { home: 'ALP_HOME_UNUSABLE', lock: 'ALP_LOCK_FAILED', state: 'ALP_STATE_UNUSABLE', recovery: 'ALP_STARTUP_FAILED', listen: 'ALP_IPC_LISTEN_FAILED', ready: 'ALP_STARTUP_FAILED' } as const;
123
-
124
- /**
125
- * Before anything reads or writes the state (ALPD §68): a restore cut short is settled, a
126
- * state of a newer schema is refused untouched, an older one is migrated forward, and a
127
- * restore's marker says to continue no work by itself this time; it is cleared once alpd is
128
- * ready, so a start that fails keeps it for the next.
129
- */
130
- async function openState(home: string) {
131
- const settled = await recoverInterruptedRestore(home);
132
- if (settled) log.warn(`a restore from ${settled.file} was cut short and has been ${settled.outcome}`, { code: 'ALP_RESTORE_SETTLED', outcome: settled.outcome });
133
- const migrated = await migrateState(home, { by: `alpd ${VERSION}`, log });
134
- for (const step of migrated.steps) log.info(`state migrated from schema ${step.from} to ${step.to} (${step.name}); the state before it is in ${step.backup}`, { code: 'ALP_STATE_MIGRATED', from: step.from, to: step.to, migration: step.name });
135
- const restored = await readRestoredMarker(home);
136
- if (restored) log.info(`state restored${restored.from ? ` from ${restored.from}` : ''}; sessions that were working wait for the user`, { code: 'ALP_STATE_RESTORED' });
137
- return { restored: !!restored };
138
- }
139
-
140
89
  async function run(home: string) {
141
- await assertPrivateDirectory(home, { create: true });
142
- phase = 'lock';
90
+ await mkdir(home, { recursive: true, mode: 0o700 });
143
91
  const { socket } = daemonPaths(home);
144
92
  let lock;
145
93
  try {
146
94
  lock = await acquireLock(home, { version: VERSION, protocolVersion: PROTOCOL_VERSION, socket });
147
95
  } catch (error: any) {
148
96
  // Under a service manager, another alpd serving this home is no failure to retry.
149
- if (process.argv.includes('--service') && /already running|ALP is busy/.test(error?.message ?? '')) {
150
- log.info(`${error.message}; this one exits`, { code: 'ALP_LOCK_HELD' });
97
+ if (process.argv.includes('--service') && /already running/.test(error?.message ?? '')) {
98
+ console.log(`${new Date().toISOString()} ${error.message}; this one exits`);
151
99
  process.exit(0);
152
100
  }
153
101
  throw error;
154
102
  }
155
- phase = 'state';
156
- let opened;
157
- try {
158
- opened = await openState(home);
159
- } catch (error) {
160
- await releaseLock(home);
161
- throw error;
162
- }
163
- phase = 'recovery';
164
- // First: nothing a crashed alpd left running may still write while this one recovers.
165
- const marker = path.join(home, 'state', 'alpd.running');
166
- const exit = await previousExit(marker);
167
- if (exit.kind === 'crash') {
168
- log.warn(`the previous alpd stopped unexpectedly around ${exit.at}`, { code: 'ALP_PREVIOUS_CRASH', at: exit.at });
169
- await stopLeftovers(await readFile(marker, 'utf8').then(JSON.parse).catch(() => undefined));
170
- }
171
- await mkdir(path.dirname(marker), { recursive: true, mode: 0o700 });
172
- await writeFile(marker, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), groupLeader: leadsGroup() }), { mode: 0o600 });
173
103
  const runLogDir = process.env.ALP_RUN_LOG_DIR || path.join(home, 'runs');
174
104
  const worktreeDir = path.join(home, 'worktrees');
175
105
  // Worktrees of assignments a crash interrupted: their work goes to their branches.
176
- for (const branch of await reclaimWorktrees(worktreeDir).catch(() => [] as string[])) log.info(`kept interrupted work on branch ${branch}`, { event: 'worktree.kept', branch });
106
+ for (const branch of await reclaimWorktrees(worktreeDir).catch(() => [] as string[])) console.log(`${new Date().toISOString()} kept interrupted work on branch ${branch}`);
177
107
  // Review copies of interrupted assignments hold nothing to keep.
178
108
  const copyDir = path.join(home, 'copies');
179
109
  await reclaimCopies(copyDir).catch(() => 0);
180
110
  // A hold (ALPD §40) only means something while alpd is stopped.
181
111
  await unlink(path.join(home, 'state', 'alpd.held')).catch(() => {});
112
+ const marker = path.join(home, 'state', 'alpd.running');
113
+ const exit = await previousExit(marker);
114
+ if (exit.kind === 'crash') console.log(`${new Date().toISOString()} the previous alpd stopped unexpectedly around ${exit.at}`);
115
+ await mkdir(path.dirname(marker), { recursive: true, mode: 0o700 });
116
+ await writeFile(marker, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }), { mode: 0o600 });
182
117
  const settings = await userSettings(home);
183
118
  const runtime = createAlpRuntime({
184
119
  templates, runLogDir, worktreeDir, copyDir, boardDir: path.join(home, 'boards'), libraryDir: home,
185
120
  recallFile: path.join(home, 'state', 'recall.json'), pauseFile: path.join(home, 'state', 'pause.json'), liveFile: path.join(home, 'state', 'live.json'),
186
- autoResume: settings?.limits?.autoResume !== false, recoveryResume: settings?.recovery?.autoResume !== false && !opened.restored, previousExit: exit,
121
+ autoResume: settings?.limits?.autoResume !== false, recoveryResume: settings?.recovery?.autoResume !== false, previousExit: exit,
187
122
  });
188
123
  const store = createStore(path.join(home, 'state'));
189
124
  let stopping: Promise<void> | undefined;
@@ -198,12 +133,12 @@ async function run(home: string) {
198
133
  // Last: what remains is a clean stop.
199
134
  await unlink(marker).catch(() => {});
200
135
  await releaseLock(home);
201
- log.info('alpd stopped', { event: 'stopped', exitCode: code });
136
+ console.log(`${new Date().toISOString()} alpd stopped`);
202
137
  process.exit(code);
203
138
  })();
204
139
  return stopping;
205
140
  };
206
- const server = createDaemonServer({ runtime, socketPath: socket, version: VERSION, store, runLogDir, previousExit: exit, home, templates, onShutdown: () => void shutdown() });
141
+ const server = createDaemonServer({ runtime, socketPath: socket, version: VERSION, store, runLogDir, previousExit: exit, onShutdown: () => void shutdown() });
207
142
  const beat = setInterval(() => {
208
143
  void heartbeat(home).then(owned => { if (!owned) void shutdown(1); });
209
144
  const now = new Date();
@@ -211,40 +146,27 @@ async function run(home: string) {
211
146
  }, 30_000);
212
147
  beat.unref();
213
148
  for (const signal of ['SIGINT', 'SIGTERM'] as const) process.on(signal, () => void shutdown());
214
- process.on('uncaughtException', error => { log.error('uncaught exception; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
215
- process.on('unhandledRejection', error => { log.error('unhandled rejection; alpd stops', { code: 'ALP_FATAL', error }); void shutdown(1); });
216
- phase = 'listen';
149
+ process.on('uncaughtException', error => { console.error(`${new Date().toISOString()} fatal`, error); void shutdown(1); });
150
+ process.on('unhandledRejection', error => { console.error(`${new Date().toISOString()} fatal`, error); void shutdown(1); });
217
151
  try {
218
152
  await server.listen();
219
153
  } catch (error) {
220
154
  await releaseLock(home);
221
155
  throw error;
222
156
  }
223
- phase = 'ready';
224
157
  // Web app and relay are owned by the optional Paseo integration process.
225
158
  await updateLock(home, { ...lock, ready: true });
226
159
  // Clients that cannot locate alpd themselves (the Paseo plugin) start it from here next time.
227
160
  const { install } = daemonPaths(home);
228
161
  await writeFile(`${install}.tmp`, JSON.stringify({ entry: fileURLToPath(import.meta.url), version: VERSION }), { mode: 0o600 })
229
162
  .then(() => rename(`${install}.tmp`, install))
230
- .catch(error => log.warn('could not record alpd\'s location', { code: 'ALP_INSTALL_RECORD_FAILED', error }));
231
- if (opened.restored) await clearRestoredMarker(home).catch(error => log.warn('could not clear the restore marker', { code: 'ALP_STATE_RESTORED', error }));
232
- log.info(`alpd ${VERSION} ready on ${socket} (pid ${process.pid})`, { event: 'ready', version: VERSION, pid: process.pid });
163
+ .catch(error => console.error(`${new Date().toISOString()} could not record alpd's location`, error));
164
+ console.log(`${new Date().toISOString()} alpd ${VERSION} ready on ${socket} (pid ${process.pid})`);
233
165
  }
234
166
 
235
167
  const home = alpHome();
236
- try {
237
- if (process.argv.includes('--detach')) await detach(home);
238
- else {
239
- if (process.argv.includes('--service')) await serviceLog(home);
240
- await run(home);
241
- }
242
- } catch (error: any) {
243
- // The log says where start-up stopped; alp doctor reads it from there.
244
- const stoppedIn = phase as Phase;
245
- // Opening the state fails with the state's own code (a newer schema, a failed migration).
246
- const code = /already running|ALP is busy/.test(error?.message ?? '') ? 'ALP_LOCK_HELD'
247
- : stoppedIn === 'state' && typeof error?.code === 'string' && /^[A-Z_]+$/.test(error.code) ? `ALP_${error.code}` : STARTUP_CODES[stoppedIn];
248
- log.error(`alpd failed to start while ${{ home: 'preparing its home', lock: 'taking its lock', state: 'opening its state', recovery: 'recovering earlier work', listen: 'opening its IPC endpoint', ready: 'finishing start-up' }[stoppedIn]}${stoppedIn === 'state' ? `: ${error?.message ?? error}` : ''}`, { code, phase: stoppedIn, error });
249
- process.exit(1);
168
+ if (process.argv.includes('--detach')) await detach(home);
169
+ else {
170
+ if (process.argv.includes('--service')) await serviceLog(home);
171
+ await run(home);
250
172
  }