@anhlp/alp-daemon 0.0.0-beta.2 → 0.0.1-beta.3

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/gitignore.ts CHANGED
@@ -140,8 +140,8 @@ function hasGitEntry(root: string): boolean {
140
140
  try {
141
141
  lstatSync(path.join(directory, '.git'));
142
142
  return true;
143
- } catch {
144
- // none here
143
+ } catch (error) {
144
+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw new IgnoreUnknown('cannot examine .git');
145
145
  }
146
146
  if (path.dirname(directory) === directory) return false;
147
147
  }
@@ -229,23 +229,30 @@ function check(git: string, root: string, paths: readonly string[], deadline: nu
229
229
  });
230
230
  child.stderr!.on('data', (chunk: Buffer) => { if (err.length < GIT_CHECK.maxErrorBytes) err += chunk.toString('utf8'); });
231
231
  child.on('error', error => finish(() => {
232
- // Removed since it was found: no rules to apply.
233
- if ((error as NodeJS.ErrnoException).code === 'ENOENT') resolve(null);
234
- else reject(new IgnoreUnknown(error.message));
232
+ // Git was resolved already. ENOENT can also mean a missing cwd or interpreter;
233
+ // it does not establish that no ignore rules apply.
234
+ reject(new IgnoreUnknown(error.message));
235
235
  }));
236
236
  child.on('close', code => finish(() => {
237
237
  // No repository: no rules. A `.git` that Git cannot use (a worktree whose repository moved)
238
238
  // is not "no repository": fail closed.
239
239
  if (code === 128 && /not a git repository/i.test(err)) {
240
- if (hasGitEntry(root)) reject(new IgnoreUnknown('a .git Git cannot use'));
241
- else resolve(null);
240
+ try {
241
+ if (hasGitEntry(root)) reject(new IgnoreUnknown('a .git Git cannot use'));
242
+ else resolve(null);
243
+ } catch (error) { reject(error); }
242
244
  return;
243
245
  }
244
246
  // 0: some paths are ignored; 1: none is.
245
247
  if (code !== 0 && code !== 1) { reject(new IgnoreUnknown(`exit ${code}`)); return; }
248
+ if (err.length || (code === 1 && outBytes) || (code === 0 && !outBytes)) {
249
+ reject(new IgnoreUnknown('inconsistent exit status or diagnostics')); return;
250
+ }
251
+ const output = Buffer.concat(out).toString('utf8');
252
+ if (outBytes && !output.endsWith('\0')) { reject(new IgnoreUnknown('unterminated answer')); return; }
246
253
  const asked = new Set(paths);
247
254
  const ignored = new Set<string>();
248
- for (const entry of Buffer.concat(out).toString('utf8').split('\0')) {
255
+ for (const entry of output.split('\0')) {
249
256
  if (!entry) continue;
250
257
  const relative = entry.startsWith('./') ? entry.slice(2) : undefined;
251
258
  if (relative === undefined || !asked.has(relative)) { reject(new IgnoreUnknown('an answer for a path not asked')); return; }
package/src/main.ts CHANGED
@@ -4,7 +4,7 @@ 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, assertPrivateDirectory, PROTOCOL_VERSION, withDaemonLifecycle } 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';
@@ -28,7 +28,9 @@ async function rotate(log: string) {
28
28
  }
29
29
  }
30
30
 
31
- /** Starts the daemon in a new session and returns at once, so it is not part of the caller's process tree. */
31
+ /** The launcher owns its detached child until that child acknowledges readiness or exits.
32
+ * A ready lock belonging to some other process cannot settle this launch.
33
+ */
32
34
  async function detach(home: string) {
33
35
  await assertPrivateDirectory(home, { create: true });
34
36
  const { log } = daemonPaths(home);
@@ -37,12 +39,35 @@ async function detach(home: string) {
37
39
  const output = await open(log, 'a', 0o600);
38
40
  const child = spawn(process.execPath, [fileURLToPath(import.meta.url)], {
39
41
  detached: true,
40
- stdio: ['ignore', output.fd, output.fd],
42
+ stdio: ['ignore', output.fd, output.fd, 'ipc'],
41
43
  env: process.env,
42
44
  windowsHide: true,
43
45
  });
44
- child.unref();
45
46
  await output.close();
47
+ await new Promise<void>((resolve, reject) => {
48
+ const requested = Number(process.argv.find(arg => arg.startsWith('--startup-timeout='))?.split('=')[1]);
49
+ const timeoutMs = Number.isFinite(requested) && requested > 0 ? requested : 15_000;
50
+ let timedOut = false;
51
+ let force: ReturnType<typeof setTimeout> | undefined;
52
+ const timer = setTimeout(() => {
53
+ timedOut = true;
54
+ child.kill();
55
+ force = setTimeout(() => child.kill('SIGKILL'), 1_000);
56
+ }, timeoutMs);
57
+ child.once('error', error => { clearTimeout(timer); clearTimeout(force); reject(error); });
58
+ child.once('exit', (code, signal) => {
59
+ clearTimeout(timer);
60
+ clearTimeout(force);
61
+ reject(new Error(timedOut ? `alpd startup timed out after ${timeoutMs} ms` : `alpd exited during startup (${code ?? signal})`));
62
+ });
63
+ child.once('message', message => {
64
+ if (message !== 'alpd.ready' || timedOut) return;
65
+ clearTimeout(timer);
66
+ child.disconnect();
67
+ child.unref();
68
+ resolve();
69
+ });
70
+ });
46
71
  }
47
72
 
48
73
  /**
@@ -177,8 +202,8 @@ async function run(home: string) {
177
202
  // Review copies of interrupted assignments hold nothing to keep.
178
203
  const copyDir = path.join(home, 'copies');
179
204
  await reclaimCopies(copyDir).catch(() => 0);
180
- // A hold (ALPD §40) only means something while alpd is stopped.
181
- await unlink(path.join(home, 'state', 'alpd.held')).catch(() => {});
205
+ // Requested starts lift the existing hold before launching. Never erase a stop
206
+ // published while this daemon was starting.
182
207
  const settings = await userSettings(home);
183
208
  const runtime = createAlpRuntime({
184
209
  templates, runLogDir, worktreeDir, copyDir, boardDir: path.join(home, 'boards'), libraryDir: home,
@@ -229,6 +254,7 @@ async function run(home: string) {
229
254
  .then(() => rename(`${install}.tmp`, install))
230
255
  .catch(error => log.warn('could not record alpd\'s location', { code: 'ALP_INSTALL_RECORD_FAILED', error }));
231
256
  if (opened.restored) await clearRestoredMarker(home).catch(error => log.warn('could not clear the restore marker', { code: 'ALP_STATE_RESTORED', error }));
257
+ if (process.connected) process.send?.('alpd.ready');
232
258
  log.info(`alpd ${VERSION} ready on ${socket} (pid ${process.pid})`, { event: 'ready', version: VERSION, pid: process.pid });
233
259
  }
234
260
 
@@ -236,8 +262,18 @@ const home = alpHome();
236
262
  try {
237
263
  if (process.argv.includes('--detach')) await detach(home);
238
264
  else {
265
+ // A direct foreground/login invocation is an explicit start. Do this before
266
+ // admission registration, so a stop published during startup is preserved.
267
+ if (!process.connected) await unlink(path.join(home, 'state', 'alpd.held')).catch(() => {});
239
268
  if (process.argv.includes('--service')) await serviceLog(home);
240
- await run(home);
269
+ if (process.connected) await run(home);
270
+ else {
271
+ // Retain admission through readiness even if the requesting service client
272
+ // times out. An invocation without a requester (including login) is explicit.
273
+ await withDaemonLifecycle(home, 'start', async () => {
274
+ await run(home);
275
+ }, { joinStart: true });
276
+ }
241
277
  }
242
278
  } catch (error: any) {
243
279
  // The log says where start-up stopped; alp doctor reads it from there.
package/src/operations.ts CHANGED
@@ -51,6 +51,7 @@ function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry
51
51
  if (error instanceof RpcError || typeof error?.code !== 'string' || error?.name !== 'AlpError') return error;
52
52
  const message = error.message as string;
53
53
  switch (error.code) {
54
+ case 'UNSAFE_LIBRARY_WRITE': return failure(ERROR.forbidden, 'library_policy', message);
54
55
  case 'UNSAFE_PATH': return failure(ERROR.forbidden, 'unsafe_path', message);
55
56
  case 'TASK_NOT_FOUND': return failure(ERROR.notFound, 'unknown_task', message);
56
57
  case 'TASK_CHANGED': case 'REVISION_CONFLICT': return failure(ERROR.conflict, 'revision_conflict', message);
@@ -228,7 +229,8 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
228
229
  return { ...entry, content, revision: toWire(entry.revision), ...(secrets.length ? { secrets } : {}) };
229
230
  }),
230
231
 
231
- 'library.save': guard(({ kind, name, scope, projectRoot, content, revision, sync = 'none' }) => serial(async () => {
232
+ 'library.save': guard(({ kind, name, scope, projectRoot, content, revision, policy, sync = 'none' }) => serial(async () => {
233
+ if (policy === 'project-data' && sync !== 'none') throw failure(ERROR.forbidden, 'library_policy', 'Project-data writes cannot synchronize projects');
232
234
  const options = await where(projectRoot, scope);
233
235
  const current = await layer(kind, name, options, scope);
234
236
  if (revision !== undefined && revision !== toWire(current?.revision ?? null)) {
@@ -237,7 +239,7 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
237
239
  const previous = current?.content ?? (await layer(kind, name, options))?.content;
238
240
  const next = unredact(kind, content, previous);
239
241
  // Core checks the revision again as it writes, against writers outside alpd.
240
- const saved = await saveEntry(kind, name, next, { ...options, scope, ...(revision !== undefined ? { revision: current?.revision ?? null } : {}) });
242
+ const saved = await saveEntry(kind, name, next, { ...options, scope, policy, ...(revision !== undefined ? { revision: current?.revision ?? null } : {}) });
241
243
  if (kind !== 'teams' || sync !== 'known-projects') return { revision: toWire(saved.revision) };
242
244
  const roots = new Set<string>(options.root ? [options.root] : []);
243
245
  if (scope === 'library') for (const root of knownProjects()) if (typeof root === 'string' && path.isAbsolute(root)) roots.add(path.resolve(root));
@@ -250,24 +252,24 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
250
252
  return { revision: toWire(saved.revision), syncedProjects, syncErrors };
251
253
  }), { notFound: 'invalid_entry' }),
252
254
 
253
- 'library.delete': guard(({ kind, name, scope, projectRoot, revision }) => serial(async () => {
255
+ 'library.delete': guard(({ kind, name, scope, projectRoot, revision, policy }) => serial(async () => {
254
256
  const options = await where(projectRoot, scope);
255
257
  const current = await layer(kind, name, options, scope);
256
258
  if (!current) throw failure(ERROR.notFound, 'not_found', `No ${kind} entry '${name}' in the ${scope}`);
257
259
  if (revision !== undefined && revision !== toWire(current.revision)) throw failure(ERROR.conflict, 'revision_conflict', `${kind} '${name}' changed in the ${scope} since you opened it`);
258
- return deleteEntry(kind, name, { ...options, scope, ...(revision !== undefined ? { revision: current.revision } : {}) });
260
+ return deleteEntry(kind, name, { ...options, scope, policy, ...(revision !== undefined ? { revision: current.revision } : {}) });
259
261
  })),
260
262
 
261
- 'library.duplicate': guard(({ kind, from, to, scope, projectRoot }) => serial(async () => {
263
+ 'library.duplicate': guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
262
264
  const options = await where(projectRoot, scope);
263
265
  try { await getEntry(kind, from, options); }
264
266
  catch (error) { throw fromCore(error, { notFound: 'not_found' }); }
265
- return { revision: toWire((await duplicateEntry(kind, from, to, { ...options, scope })).revision) };
267
+ return { revision: toWire((await duplicateEntry(kind, from, to, { ...options, scope, policy })).revision) };
266
268
  }), { notFound: 'invalid_entry' }),
267
269
 
268
- 'library.rename': guard(({ kind, from, to, scope, projectRoot }) => serial(async () => {
270
+ 'library.rename': guard(({ kind, from, to, scope, projectRoot, policy }) => serial(async () => {
269
271
  const options = await where(projectRoot, scope);
270
- return { revision: toWire((await renameEntry(kind, from, to, { ...options, scope })).revision) };
272
+ return { revision: toWire((await renameEntry(kind, from, to, { ...options, scope, policy })).revision) };
271
273
  })),
272
274
 
273
275
  'library.skills.set': guard(({ agent, skills }) => serial(() => setGivenSkills(agent, skills, { library: home })), { notFound: 'invalid_entry' }),
@@ -293,6 +295,6 @@ export function createOperations({ home, templates, knownProjects = () => [] }:
293
295
  const library = home !== undefined;
294
296
  return {
295
297
  handlers: { ...taskHandlers, ...(library ? libraryHandlers : {}) },
296
- capabilities: [CAPABILITY.task, ...(library ? [CAPABILITY.team, CAPABILITY.library, CAPABILITY.settingsLanguage] : [])],
298
+ capabilities: [CAPABILITY.task, ...(library ? [CAPABILITY.team, CAPABILITY.library, CAPABILITY.libraryProjectWrite, CAPABILITY.settingsLanguage] : [])],
297
299
  };
298
300
  }
package/src/server.ts CHANGED
@@ -230,14 +230,18 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
230
230
  record ??= { version: 1, id: sessionId, rootId: root, status: 'initializing', createdAt: now, updatedAt: now };
231
231
  // A reopened session keeps its last usage until its runtime reports again.
232
232
  const usage = event.session.usage ?? record.session?.usage;
233
- save(record, { rootId: root, session: { ...event.session, ...(usage ? { usage } : {}) }, status: 'idle', lastError: undefined, activeTurnId: undefined });
233
+ // Recovery has not yet restored runtime parking when session.opened arrives.
234
+ const parked = recovering.has(root) ? record.session?.parked : event.session.parked;
235
+ save(record, { rootId: root, session: { ...event.session, ...(usage ? { usage } : {}), ...(parked ? { parked } : {}) }, status: 'idle', lastError: undefined, activeTurnId: undefined });
234
236
  return false;
235
237
  }
236
238
  if (!record) return false;
237
239
  if (event.type === 'session.updated') save(record, { session: { ...record.session, ...event.session, ...(event.session.parked ? {} : { parked: undefined }) } });
238
240
  // Work on an archived session brings it back.
239
241
  else if (event.type === 'turn.started') save(record, { status: 'running', activeTurnId: event.turnId, archived: undefined });
240
- else if (event.type === 'turn.ended') save(record, { status: 'idle', activeTurnId: undefined, ...(event.state === 'failed' ? { lastError: { message: event.error?.message ?? 'Turn failed' } } : {}) });
242
+ else if (event.type === 'turn.ended') save(record, { status: 'idle', activeTurnId: undefined,
243
+ ...(record.session ? { session: { ...record.session, parked: event.state === 'failed' ? runtime.snapshot(sessionId)?.parked : undefined } } : {}),
244
+ ...(event.state === 'failed' ? { lastError: { message: event.error?.message ?? 'Turn failed' } } : {}) });
241
245
  // The latest usage, for a closed session's summary; written with the record's next change.
242
246
  else if (event.type === 'usage' && record.session) record.session = { ...record.session, usage: event.usage };
243
247
  else if (event.type === 'session.failed') save(record, { status: 'error', lastError: event.error });
@@ -315,7 +319,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
315
319
  for (const [root, tree] of byRoot) {
316
320
  const head = tree.find(record => record.id === root);
317
321
  if (removed.has(root)) continue;
318
- if (head && resumable(head) && (head.status === 'running' || tree.some(record => continuing.has(record.id)))) reopen.push({ record: head, working: head.status === 'running' });
322
+ if (head && resumable(head) && (head.status === 'running' || (head.status === 'idle' && head.session?.parked) || tree.some(record => continuing.has(record.id)))) reopen.push({ record: head, working: head.status === 'running' });
319
323
  if (tree.some(record => LIVE.includes(record.status))) seen(root, await store!.timeline(root));
320
324
  for (const record of tree as Array<SessionRecord & { activeTurnId?: string }>) {
321
325
  records.set(record.id, record);
@@ -324,7 +328,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
324
328
  // The turn a crash or a stop cut off is reported interrupted, never continued as if nothing happened.
325
329
  if (record.activeTurnId) keep(root, envelope({ type: 'turn.ended', turnId: record.activeTurnId, state: 'failed', error: { message: ended.message, code: ended.code } }));
326
330
  if (record.id === root) {
327
- save(record, record.status === 'idle' ? { status: 'closed', activeTurnId: undefined } : { status: 'error', lastError: ended, activeTurnId: undefined });
331
+ if (!(record.status === 'idle' && record.session?.parked)) save(record, record.status === 'idle' ? { status: 'closed', activeTurnId: undefined } : { status: 'error', lastError: ended, activeTurnId: undefined });
328
332
  } else if (continuing.has(record.id) && reopen.some(entry => entry.record.id === root)) {
329
333
  // The runtime reopens it under the same id; until then it is closed.
330
334
  save(record, { status: 'closed', activeTurnId: undefined });
@@ -444,7 +448,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
444
448
  persist: true,
445
449
  restore: { agent: session.agent, threadId: session.threadId, runtime: session.runtime, model: session.model, workflow: session.workflow },
446
450
  }, { history: 'skip', delegation: record.delegation ?? true });
447
- const outcomes = await runtime.recover(record.id, { continueRoot: working });
451
+ const outcomes = await runtime.recover(record.id, { continueRoot: working, parkedRoot: session.parked });
448
452
  recoveryLog.info(`recovered ${record.id}: ${outcomes.map(outcome => `${outcome.agent} ${outcome.outcome}`).join(', ') || 'root'}`, { event: 'recovered', sessionId: record.id, rootId: record.rootId });
449
453
  } catch (error: any) {
450
454
  recoveryLog.error(`could not recover ${record.id}`, { code: 'ALP_RECOVERY_FAILED', sessionId: record.id, rootId: record.rootId, error });