@anhlp/alp-daemon 0.0.1-beta.5 → 0.0.1-beta.6

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/dist/alpd.js CHANGED
@@ -15264,10 +15264,15 @@ function addGate(projectRoot, id, { kind, note, until, ref, options: options2 }
15264
15264
  var GATE_OPTIONS = 10;
15265
15265
  var GATE_OPTION_CHARS = 200;
15266
15266
  var GATE_CHANNELS = ["paseo", "web", "cli"];
15267
+ var GATE_REJECT_LABELS = ["Reject", "T\u1EEB ch\u1ED1i"];
15268
+ var labelKey = (text3) => text3.normalize("NFC").trim().toLowerCase();
15269
+ var REJECT_KEYS = new Set(GATE_REJECT_LABELS.map(labelKey));
15267
15270
  function gateOptions(value) {
15268
15271
  if (!Array.isArray(value) || value.length > GATE_OPTIONS || !value.every((item) => typeof item === "string" && !!item.trim() && item.trim().length <= GATE_OPTION_CHARS)) {
15269
15272
  fail2("INVALID_TASK", `options must list at most ${GATE_OPTIONS} nonempty answers of at most ${GATE_OPTION_CHARS} characters`);
15270
15273
  }
15274
+ const reserved = value.find((item) => REJECT_KEYS.has(labelKey(item)));
15275
+ if (reserved !== void 0) fail2("INVALID_TASK", `"${reserved.trim()}" is the Reject answer every gate card already offers; name the options for approving only`);
15271
15276
  return [...new Set(value.map((item) => item.trim()))];
15272
15277
  }
15273
15278
  var checkChannel = (channel) => {
@@ -15327,13 +15332,13 @@ function gateDecisions(tasks) {
15327
15332
  }
15328
15333
  return found;
15329
15334
  }
15330
- function markGateNotified(projectRoot, id, gateId, decision) {
15335
+ function markGateNotified(projectRoot, id, gateId, decision, at2) {
15331
15336
  return locked(projectRoot, async () => {
15332
15337
  const { tasks } = await loadTasks(projectRoot);
15333
15338
  const task = tasks.find((entry) => entry.id === id);
15334
15339
  const gate = task?.gates?.find((entry) => entry.id === gateId);
15335
15340
  const record3 = decision === "approved" ? gate?.resolved : gate?.rejected;
15336
- if (!task || !record3?.channel || record3.notified) return false;
15341
+ if (!task || !record3?.channel || record3.notified || at2 !== void 0 && record3.at !== at2) return false;
15337
15342
  record3.notified = now();
15338
15343
  await save(projectRoot, task);
15339
15344
  return true;
@@ -15556,8 +15561,8 @@ async function validWorktree(directory) {
15556
15561
  async function reattachWorktree(worktree) {
15557
15562
  const exists5 = !!await stat3(worktree.path).catch(() => void 0);
15558
15563
  if (exists5 && await validWorktree(worktree.path)) {
15559
- const gitdir = await git(worktree.path, ["rev-parse", "--absolute-git-dir"]);
15560
- if (gitdir.code === 0) await rm3(path13.join(gitdir.stdout.trim(), "index.lock"), { force: true });
15564
+ const dirs = await gitDirs(worktree.path);
15565
+ if (dirs) await clearStaleLocks(dirs, worktree.branch);
15561
15566
  return worktree;
15562
15567
  }
15563
15568
  if (!await branchExists(worktree.checkout, worktree.branch)) throw new Error(`Branch ${worktree.branch} of the worktree no longer exists`);
@@ -15635,29 +15640,92 @@ async function removeWorktree(worktree, { deleteBranch = false } = {}) {
15635
15640
  await git(worktree.checkout, ["worktree", "prune"]);
15636
15641
  if (deleteBranch) await git(worktree.checkout, ["branch", "-D", worktree.branch]);
15637
15642
  }
15643
+ async function gitDirs(target) {
15644
+ const result = await git(target, ["rev-parse", "--path-format=absolute", "--absolute-git-dir", "--git-common-dir"]);
15645
+ if (result.code !== 0) return void 0;
15646
+ const [own2, common] = result.stdout.trim().split("\n").map((line) => path13.resolve(line.trim()));
15647
+ return own2 && common ? { own: own2, common } : void 0;
15648
+ }
15649
+ var SHARED_LOCK_STALE_MS = 1e4;
15650
+ async function clearStaleLocks(dirs, branch) {
15651
+ if (dirs.own === dirs.common) return;
15652
+ const own2 = (await readdir6(dirs.own).catch(() => [])).filter((name2) => name2.endsWith(".lock"));
15653
+ const refs = (await readdir6(path13.join(dirs.own, "refs"), { recursive: true }).catch(() => [])).filter((name2) => name2.endsWith(".lock")).map((name2) => path13.join("refs", name2));
15654
+ for (const name2 of [...own2, ...refs]) await unlink3(path13.join(dirs.own, name2)).catch(() => {
15655
+ });
15656
+ const shared = `${path13.join(dirs.common, "refs", "heads", ...branch.split("/"))}.lock`;
15657
+ const info = await lstat4(shared).catch(() => void 0);
15658
+ if (info?.isFile() && Date.now() - info.mtimeMs >= SHARED_LOCK_STALE_MS) await unlink3(shared).catch(() => {
15659
+ });
15660
+ }
15661
+ var KEEP_IGNORED = /^\.env/;
15662
+ async function ignoredToKeep(target) {
15663
+ const result = await git(target, ["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"]);
15664
+ if (result.code !== 0) return void 0;
15665
+ return result.stdout.split("\0").filter(Boolean).map((entry) => entry.replace(/\/$/, "")).filter((entry) => KEEP_IGNORED.test(path13.posix.basename(entry))).sort();
15666
+ }
15667
+ var firstLine = (result) => (result.stderr || result.stdout).trim().split("\n")[0] ?? "";
15638
15668
  async function reclaimWorktrees(root) {
15639
15669
  const kept = [];
15670
+ const left = [];
15640
15671
  const entries3 = await readdir6(root).catch(() => []);
15641
15672
  for (const name2 of entries3) {
15642
15673
  const target = path13.join(root, name2);
15674
+ const leave = (reason, extra = {}) => {
15675
+ left.push({ name: name2, path: target, reason, ...extra });
15676
+ };
15643
15677
  if (!(await stat3(target).catch(() => void 0))?.isDirectory()) continue;
15644
- if (!await validWorktree(target)) continue;
15645
- const common = await git(target, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
15646
- if (common.code !== 0) continue;
15647
- const checkout = path13.dirname(common.stdout.trim());
15678
+ if (!await validWorktree(target)) {
15679
+ leave("invalid");
15680
+ continue;
15681
+ }
15682
+ const dirs = await gitDirs(target);
15683
+ if (!dirs) {
15684
+ leave("invalid");
15685
+ continue;
15686
+ }
15687
+ if (dirs.own === dirs.common) {
15688
+ leave("not-linked");
15689
+ continue;
15690
+ }
15691
+ const checkout = path13.dirname(dirs.common);
15648
15692
  const ref = await git(target, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
15649
15693
  const branch = ref.stdout.trim();
15650
- if (ref.code !== 0 || branch !== `alp/${name2}`) continue;
15651
- if ((await git(target, ["add", "-A"])).code !== 0) continue;
15694
+ if (ref.code !== 0 || branch !== `alp/${name2}`) {
15695
+ leave("other-branch", ref.code === 0 && branch ? { branch } : {});
15696
+ continue;
15697
+ }
15698
+ await clearStaleLocks(dirs, branch);
15699
+ const added = await git(target, ["add", "-A"]);
15700
+ if (added.code !== 0) {
15701
+ leave("commit-failed", { branch, detail: firstLine(added) });
15702
+ continue;
15703
+ }
15652
15704
  if ((await git(target, ["diff", "--cached", "--quiet"])).code === 1) {
15653
- if ((await git(target, [...IDENTITY, "commit", "--quiet", "--no-verify", "-m", "alp: work left by an interrupted assignment"])).code !== 0) continue;
15705
+ const committed = await git(target, [...IDENTITY, "commit", "--quiet", "--no-verify", "-m", "alp: work left by an interrupted assignment"]);
15706
+ if (committed.code !== 0) {
15707
+ leave("commit-failed", { branch, detail: firstLine(committed) });
15708
+ continue;
15709
+ }
15654
15710
  }
15655
15711
  const status = await git(target, ["status", "--porcelain", "--ignored=no"]);
15656
- if (status.code !== 0 || status.stdout.trim()) continue;
15712
+ if (status.code !== 0 || status.stdout.trim()) {
15713
+ leave("uncommitted", { branch });
15714
+ continue;
15715
+ }
15716
+ const ignored = await ignoredToKeep(target);
15717
+ if (!ignored) {
15718
+ leave("ignored-files", { branch, detail: "git could not list its ignored files" });
15719
+ continue;
15720
+ }
15721
+ if (ignored.length) {
15722
+ leave("ignored-files", { branch, files: ignored });
15723
+ continue;
15724
+ }
15657
15725
  await removeWorktree({ checkout, path: target, workdir: target, branch, base: "" });
15658
15726
  kept.push(branch);
15659
15727
  }
15660
- return kept;
15728
+ return { kept, left };
15661
15729
  }
15662
15730
  async function createCopy(workdir, root, id) {
15663
15731
  const checkout = await checkoutOf(workdir);
@@ -31125,6 +31193,7 @@ function commandDecision(profile, command) {
31125
31193
 
31126
31194
  // packages/runtime/src/claude-transport.ts
31127
31195
  var CLAUDE_SDK = ["@anthropic-ai", "claude-agent-sdk"].join("/");
31196
+ var claudeSdk = () => packagedInfo()?.modules?.[CLAUDE_SDK]?.() ?? import(CLAUDE_SDK);
31128
31197
  var bounded = (schema, limits) => external_exports.preprocess((value, ctx) => {
31129
31198
  const error51 = inputLimitError(value, limits);
31130
31199
  if (error51) ctx.addIssue({ code: "custom", message: error51 });
@@ -31405,7 +31474,7 @@ function claudePermissions(sandbox, currentSandbox, rules, ask) {
31405
31474
  var claudeLimited = (info) => info?.status === "rejected" && info.overageStatus !== "allowed" && info.overageStatus !== "allowed_warning";
31406
31475
  var BOOT_MS = 15e3;
31407
31476
  async function claudeChain(sessionId, dir) {
31408
- const { getSessionMessages } = await import(CLAUDE_SDK);
31477
+ const { getSessionMessages } = await claudeSdk();
31409
31478
  let messages = dir ? await getSessionMessages(sessionId, { dir }) : [];
31410
31479
  if (!messages.length) messages = await getSessionMessages(sessionId);
31411
31480
  return messages.filter((message) => (message.type === "user" || message.type === "assistant") && typeof message.uuid === "string").map((message) => {
@@ -31491,7 +31560,7 @@ var ClaudeTransport = class {
31491
31560
  }
31492
31561
  /** The models Claude offers now, from a Claude process that sends no prompt and is closed after (t-e5ee). */
31493
31562
  async probeModels(signal) {
31494
- const { query } = await import(CLAUDE_SDK);
31563
+ const { query } = await claudeSdk();
31495
31564
  if (signal?.aborted) throw new Error("aborted");
31496
31565
  const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } });
31497
31566
  const stop = () => probe.close();
@@ -31507,7 +31576,7 @@ var ClaudeTransport = class {
31507
31576
  /** The plan's usage windows before a session starts, from a Claude process that sends no prompt and is closed after. */
31508
31577
  async probeUsage() {
31509
31578
  if (this.closed) return void 0;
31510
- const { query } = await import(CLAUDE_SDK);
31579
+ const { query } = await claudeSdk();
31511
31580
  const probe = query({ prompt: new InputQueue(), options: { cwd: this.cwd, env: this.env, settingSources: [], persistSession: false, strictMcpConfig: true, mcpServers: {}, pathToClaudeCodeExecutable: this.command } });
31512
31581
  try {
31513
31582
  return await probe.usage_EXPERIMENTAL_MAY_CHANGE_DO_NOT_RELY_ON_THIS_API_YET({ skipBehaviors: true });
@@ -31536,7 +31605,7 @@ var ClaudeTransport = class {
31536
31605
  }
31537
31606
  if (method === "thread/chain") return { entries: await claudeChain(params.threadId, params.cwd ?? this.cwd) };
31538
31607
  if (method === "thread/delete") {
31539
- const { deleteSession } = await import(CLAUDE_SDK);
31608
+ const { deleteSession } = await claudeSdk();
31540
31609
  await deleteSession(params.threadId, params.cwd ? { dir: params.cwd } : {});
31541
31610
  return {};
31542
31611
  }
@@ -31632,7 +31701,7 @@ var ClaudeTransport = class {
31632
31701
  if (this.bootError) throw this.bootError;
31633
31702
  }
31634
31703
  async start(from) {
31635
- const { createSdkMcpServer, query, tool } = await import(CLAUDE_SDK);
31704
+ const { createSdkMcpServer, query, tool } = await claudeSdk();
31636
31705
  const config2 = this.config;
31637
31706
  const mcpServers = this.convertMcp(config2.mcpServers);
31638
31707
  if (config2.dynamicTools.length) {
@@ -40882,7 +40951,7 @@ function nativeSessionConfig(runtimeKind, mapping, targets, parentAgent, role, s
40882
40951
 
40883
40952
  // packages/runtime/src/runtime.ts
40884
40953
  import { createHash as createHash12, randomUUID as randomUUID13 } from "node:crypto";
40885
- import { readFileSync as readFileSync5, realpathSync as realpathSync9 } from "node:fs";
40954
+ import { readFileSync as readFileSync5, realpathSync as realpathSync9, watch as watchFiles } from "node:fs";
40886
40955
  import { appendFile as appendFile2, mkdir as mkdir16, open as open5, readFile as readFile21, realpath as realpath5, rm as rm5, stat as stat6, writeFile as writeFile16 } from "node:fs/promises";
40887
40956
  import os11 from "node:os";
40888
40957
  import path37 from "node:path";
@@ -42548,7 +42617,9 @@ function createAlpRuntime(options2 = {}) {
42548
42617
  }
42549
42618
  cancelQuestions(sessionId, true);
42550
42619
  if (session.parent) sessions.get(session.parent)?.assignments.get(sessionId)?.ask?.resolve(toolResult(false, { error: "Turn ended" }));
42551
- session.mail = session.mail.filter((event) => !(event.deliveredTurn === turnId && state === "completed"));
42620
+ const taken = state === "completed" ? session.mail.filter((event) => event.deliveredTurn === turnId) : [];
42621
+ session.mail = session.mail.filter((event) => !taken.includes(event));
42622
+ for (const event of taken) gateMail.get(event)?.taken();
42552
42623
  for (const event of session.mail) {
42553
42624
  if (event.deliveredTurn === turnId) {
42554
42625
  event.deliveredTurn = void 0;
@@ -44825,6 +44896,9 @@ The user answered: "${answer}"`);
44825
44896
  }
44826
44897
  }
44827
44898
  const gateSyncs = /* @__PURE__ */ new Map();
44899
+ const gateMail = /* @__PURE__ */ new WeakMap();
44900
+ const gateTaken = /* @__PURE__ */ new Set();
44901
+ const gateMarks = /* @__PURE__ */ new Set();
44828
44902
  const gateCardId = (taskId, gateId) => `gate-${taskId}-${gateId}`;
44829
44903
  function mainSessionOf(projectRoot) {
44830
44904
  for (const [id, session] of sessions) {
@@ -44851,10 +44925,23 @@ The user answered: "${answer}"`);
44851
44925
  const { tasks } = await loadTasks(projectRoot);
44852
44926
  const main = mainSessionOf(projectRoot);
44853
44927
  if (main) for (const { task, gate, decision, record: record4 } of gateDecisions(tasks)) {
44854
- if (!await markGateNotified(projectRoot, task.id, gate.id, decision)) continue;
44928
+ const key3 = JSON.stringify([projectRoot, task.id, gate.id, decision, record4.at]);
44929
+ if (gateTaken.has(key3) || main.session.mail.some((event) => gateMail.get(event)?.key === key3)) continue;
44855
44930
  const choice = decision === "approved" ? record4.choice : void 0;
44856
44931
  const words2 = decision === "approved" ? `The user approved human gate ${gate.id} of ${task.id} in ${record4.channel}${choice ? `, choosing "${choice}"` : ""}${record4.note ? `: ${record4.note}` : ""}.` : `The user rejected human gate ${gate.id} of ${task.id} in ${record4.channel}${record4.reason ? `: ${record4.reason}` : ""}. The gate stays open.`;
44857
- post(main.id, { kind: "result", from: "ALP", assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words2} Task: ${task.title}` });
44932
+ const mail = post(main.id, { kind: "result", from: "ALP", assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words2} Task: ${task.title}. If this decision of ${gateCardId(task.id, gate.id)} was reported to you before, it is a repeat: act on it once.` });
44933
+ gateMail.set(mail, {
44934
+ key: key3,
44935
+ taken: () => {
44936
+ gateTaken.add(key3);
44937
+ const mark = markGateNotified(projectRoot, task.id, gate.id, decision, record4.at).catch((error51) => {
44938
+ gateTaken.delete(key3);
44939
+ runLog(main.id, { event: "gate.mark.failed", projectRoot, taskId: task.id, gateId: gate.id, error: errorData(error51).message });
44940
+ });
44941
+ gateMarks.add(mark);
44942
+ void mark.finally(() => gateMarks.delete(mark));
44943
+ }
44944
+ });
44858
44945
  runLog(main.id, { event: "gate.decision", projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record4.channel, ...choice ? { choice } : {} });
44859
44946
  }
44860
44947
  const wanted = /* @__PURE__ */ new Map();
@@ -44875,11 +44962,18 @@ The user answered: "${answer}"`);
44875
44962
  for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
44876
44963
  }
44877
44964
  let gateWatch;
44878
- function startGateWatch() {
44879
- if (gateWatch || options2.gateSyncMs === 0) return;
44965
+ const gateFiles = /* @__PURE__ */ new Map();
44966
+ function startGateWatch(projectRoot) {
44967
+ if (options2.gateSyncMs === 0) return;
44968
+ watchGateFiles(path37.resolve(projectRoot));
44969
+ if (gateWatch) return;
44880
44970
  gateWatch = setInterval(() => {
44881
44971
  const roots = new Set([...sessions.values()].filter((session) => !session.closed && !session.parent && session.role !== "supervisor" && session.mapping.agent.name === mainOf(session.mapping)).map((session) => path37.resolve(session.mapping.agent.projectRoot)));
44882
- for (const root of roots) void syncGates(root);
44972
+ for (const root of roots) {
44973
+ watchGateFiles(root);
44974
+ void syncGates(root);
44975
+ }
44976
+ for (const root of gateFiles.keys()) if (!roots.has(root)) unwatchGateFiles(root);
44883
44977
  if (!roots.size) {
44884
44978
  clearInterval(gateWatch);
44885
44979
  gateWatch = void 0;
@@ -44887,6 +44981,33 @@ The user answered: "${answer}"`);
44887
44981
  }, options2.gateSyncMs ?? 5e3);
44888
44982
  gateWatch.unref?.();
44889
44983
  }
44984
+ function watchGateFiles(root) {
44985
+ if (closed || gateFiles.has(root)) return;
44986
+ try {
44987
+ const entry = {
44988
+ // A burst of writes (a save, its ledger, a mark) syncs once.
44989
+ watcher: watchFiles(path37.join(root, TASKS_DIR), () => {
44990
+ if (entry.timer || closed) return;
44991
+ entry.timer = setTimeout(() => {
44992
+ entry.timer = void 0;
44993
+ void syncGates(root);
44994
+ }, 50);
44995
+ entry.timer.unref?.();
44996
+ })
44997
+ };
44998
+ entry.watcher.on("error", () => unwatchGateFiles(root));
44999
+ entry.watcher.unref?.();
45000
+ gateFiles.set(root, entry);
45001
+ } catch {
45002
+ }
45003
+ }
45004
+ function unwatchGateFiles(root) {
45005
+ const entry = gateFiles.get(root);
45006
+ if (!entry) return;
45007
+ gateFiles.delete(root);
45008
+ clearTimeout(entry.timer);
45009
+ entry.watcher.close();
45010
+ }
44890
45011
  function showGateCard(sessionId, session, projectRoot, task, gate) {
44891
45012
  const say = wordsFor(session);
44892
45013
  const vietnamese = say.approve === words("vi").approve;
@@ -44914,9 +45035,9 @@ ${gate.note ?? ""}`,
44914
45035
  }
44915
45036
  async function decideGate(projectRoot, question, card, reply, choices) {
44916
45037
  const defaults = !choices;
44917
- if (card.deciding) return;
44918
- card.deciding = true;
44919
45038
  const { taskId, gateId } = question.gate;
45039
+ if (card.deciding) throw gateRefusal("GATE_BUSY", `An answer to gate ${gateId} of ${taskId} is already being recorded`);
45040
+ card.deciding = true;
44920
45041
  const channel = reply.channel ?? "web";
44921
45042
  const text4 = reply.text?.trim();
44922
45043
  const approve2 = !reply.dismiss && !!text4 && (defaults ? APPROVALS.includes(text4.toLowerCase()) : choices.includes(text4));
@@ -44929,16 +45050,21 @@ ${gate.note ?? ""}`,
44929
45050
  if (error51?.code !== "TASK_CHANGED") throw error51;
44930
45051
  const current = (await loadTasks(projectRoot)).tasks.find((entry) => entry.id === taskId);
44931
45052
  const gate = current?.gates.find((entry) => entry.id === gateId);
44932
- if (!current || current.status === "closed" || !gate || gate.resolved || gate.rejected) return;
45053
+ if (!current || current.status === "closed" || !gate) throw gateRefusal("GATE_DECIDED", `Gate ${gateId} of ${taskId} is no longer open`);
45054
+ if (gate.resolved || gate.rejected) throw gateRefusal("GATE_DECIDED", `Gate ${gateId} of ${taskId} was already ${gate.resolved ? "approved" : "rejected"}${(gate.resolved ?? gate.rejected)?.channel ? ` in ${(gate.resolved ?? gate.rejected).channel}` : ""}`);
44933
45055
  await write(current.rev);
44934
45056
  }
44935
45057
  } catch (error51) {
44936
45058
  runLog(question.rootId, { event: "gate.answer.failed", questionId: question.id, error: errorData(error51).message });
45059
+ throw error51;
44937
45060
  } finally {
44938
45061
  card.deciding = false;
44939
45062
  await syncGates(projectRoot);
44940
45063
  }
44941
45064
  }
45065
+ function gateRefusal(code, message) {
45066
+ return Object.assign(new Error(message), { code });
45067
+ }
44942
45068
  function askTool(sessionId, session, args) {
44943
45069
  const parent = session.parent ? sessions.get(session.parent) : void 0;
44944
45070
  const assignment = parent?.assignments.get(sessionId);
@@ -45468,7 +45594,7 @@ ${digest3}` : "")
45468
45594
  });
45469
45595
  if (!session.parent && session.role !== "supervisor" && mapping.agent.name === mainOf(mapping)) {
45470
45596
  void syncGates(mapping.agent.projectRoot);
45471
- startGateWatch();
45597
+ startGateWatch(mapping.agent.projectRoot);
45472
45598
  }
45473
45599
  if (history === "replay") {
45474
45600
  for (const turn of result.thread.turns ?? []) {
@@ -46779,8 +46905,7 @@ ${interrupted}`), text_elements: [] }] : []
46779
46905
  if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
46780
46906
  if (pending.gate) {
46781
46907
  if (!reply.dismiss && (typeof reply.text !== "string" || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error("An answer needs text");
46782
- void pending.gate.decide(reply);
46783
- return;
46908
+ return pending.gate.decide(reply);
46784
46909
  }
46785
46910
  if (reply.dismiss) {
46786
46911
  pending.settle("dismissed", void 0, reply.reason);
@@ -46817,7 +46942,9 @@ ${interrupted}`), text_elements: [] }] : []
46817
46942
  );
46818
46943
  clearInterval(watchdog);
46819
46944
  if (gateWatch) clearInterval(gateWatch);
46945
+ for (const root of [...gateFiles.keys()]) unwatchGateFiles(root);
46820
46946
  await Promise.all(gateSyncs.values());
46947
+ await Promise.all(gateMarks);
46821
46948
  await Promise.all(boards.values());
46822
46949
  await boardDomain.flush();
46823
46950
  await runLogWrites;
@@ -49450,7 +49577,7 @@ function createOperations({ home: home2, templates, knownProjects = () => [], on
49450
49577
  return { id: task.id, status: task.status, rev: task.rev, ...landed ? { landed } : {} };
49451
49578
  }),
49452
49579
  // Approves a gate, or with reject records the user's rejection and leaves it open. Either way
49453
- // the runtime is told, so main gets the decision by mail once and the gate's card settles.
49580
+ // the runtime is told, so main gets the decision by mail (at least once) and the gate's card settles.
49454
49581
  "task.gate.resolve": guard(async ({ projectRoot, id, gate, note, ifRev, choice, reject, channel = "web" }, caller) => {
49455
49582
  const root = await project(projectRoot);
49456
49583
  if (caller?.agent) {
@@ -55858,14 +55985,18 @@ function createDaemonServer({ runtime, socketPath, version: version2, onShutdown
55858
55985
  throw new RpcError(ERROR.failed, error51?.message ?? String(error51));
55859
55986
  }
55860
55987
  },
55861
- "question.answer"(connection, { questionId, text: text3, dismiss = false, reason }) {
55988
+ async "question.answer"(connection, { questionId, text: text3, dismiss = false, reason }) {
55862
55989
  if (connection.agent) throw new RpcError(ERROR.forbidden, "Only the user answers a question; this connection was opened by an ALP agent", { reason: "user_only" });
55863
55990
  if (typeof questionId !== "string") throw new RpcError(-32602, "questionId is required");
55864
55991
  if (dismiss !== true && typeof text3 !== "string") throw new RpcError(-32602, "text or dismiss is required");
55865
55992
  const matches = runtime.questions().filter((question) => question.id === questionId || question.id.startsWith(questionId));
55866
55993
  if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
55867
55994
  const channel = connection.client?.startsWith("alp-paseo") ? "paseo" : "web";
55868
- runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text: text3, channel });
55995
+ const decided = runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text: text3, channel });
55996
+ if (decided) await decided.catch((error51) => {
55997
+ if (error51?.code === "GATE_BUSY" || error51?.code === "GATE_DECIDED") throw new RpcError(ERROR.conflict, error51.message, { reason: "task_state" });
55998
+ throw fromCore(error51);
55999
+ });
55869
56000
  return { questionId: matches[0].id };
55870
56001
  },
55871
56002
  "daemon.shutdown": () => {
@@ -57260,10 +57391,18 @@ function guardOutput(onError, fs) {
57260
57391
  }
57261
57392
 
57262
57393
  // packages/daemon/src/main.ts
57263
- var VERSION = true ? "0.0.1-beta.5" : "0.0.0-dev";
57394
+ var VERSION = true ? "0.0.1-beta.6" : "0.0.0-dev";
57264
57395
  var LOG_BYTES = 10 * 1024 * 1024;
57265
57396
  var LOG_FILES = 3;
57266
57397
  var log6 = createLogger({ component: "alpd" });
57398
+ var LEFT_REASONS = {
57399
+ invalid: () => "it is not a working git worktree (its git metadata is missing or broken)",
57400
+ "not-linked": () => "it is a git repository of its own, not a worktree of one",
57401
+ "other-branch": (entry) => entry.branch ? `it is on branch ${entry.branch}, not its alp branch` : "its HEAD is detached, so no branch holds its work",
57402
+ "commit-failed": (entry) => `its work could not be committed${entry.detail ? ` (${entry.detail})` : ""}`,
57403
+ uncommitted: () => "it still has changes that are not committed",
57404
+ "ignored-files": (entry) => entry.files?.length ? `its work is committed to ${entry.branch}, but it holds ignored files that exist nowhere else: ${entry.files.join(", ")}` : `its ignored files could not be checked${entry.detail ? ` (${entry.detail})` : ""}`
57405
+ };
57267
57406
  async function rotate(log7) {
57268
57407
  const size = await stat18(log7).then((info) => info.size, () => 0);
57269
57408
  if (size < LOG_BYTES) return;
@@ -57421,7 +57560,18 @@ async function run2(home2) {
57421
57560
  await writeFile24(marker, JSON.stringify({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString(), groupLeader: leadsGroup() }), { mode: 384 });
57422
57561
  const runLogDir = process.env.ALP_RUN_LOG_DIR || path59.join(home2, "runs");
57423
57562
  const worktreeDir = path59.join(home2, "worktrees");
57424
- for (const branch of await reclaimWorktrees(worktreeDir).catch(() => [])) log6.info(`kept interrupted work on branch ${branch}`, { event: "worktree.kept", branch });
57563
+ const reclaimed = await reclaimWorktrees(worktreeDir).catch(() => ({ kept: [], left: [] }));
57564
+ for (const branch of reclaimed.kept) log6.info(`kept interrupted work on branch ${branch}`, { event: "worktree.kept", branch });
57565
+ for (const entry of reclaimed.left) {
57566
+ log6.warn(`left worktree ${entry.path} in place: ${LEFT_REASONS[entry.reason](entry)}`, {
57567
+ event: "worktree.left",
57568
+ path: entry.path,
57569
+ reason: entry.reason,
57570
+ ...entry.branch ? { branch: entry.branch } : {},
57571
+ ...entry.detail ? { detail: entry.detail } : {},
57572
+ ...entry.files ? { files: entry.files } : {}
57573
+ });
57574
+ }
57425
57575
  const copyDir = path59.join(home2, "copies");
57426
57576
  await reclaimCopies(copyDir).catch(() => 0);
57427
57577
  const settings = await userSettings(home2);
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "0.0.1-beta.5",
2
+ "version": "0.0.1-beta.6",
3
3
  "entries": {
4
4
  "packages/daemon/dist/alpd.js": {
5
5
  "inputs": [
package/dist/main.js CHANGED
@@ -21,10 +21,18 @@ import { clearRestoredMarker, readRestoredMarker, recoverInterruptedRestore } fr
21
21
  import { migrateState } from "@anhlp/alp-core/migrations";
22
22
  import { createLogger } from "@anhlp/alp-core/log";
23
23
  import { selfCommand, selfEntry } from "@anhlp/alp-core/packaged";
24
- var VERSION = true ? "0.0.1-beta.5" : "0.0.0-dev";
24
+ var VERSION = true ? "0.0.1-beta.6" : "0.0.0-dev";
25
25
  var LOG_BYTES = 10 * 1024 * 1024;
26
26
  var LOG_FILES = 3;
27
27
  var log = createLogger({ component: "alpd" });
28
+ var LEFT_REASONS = {
29
+ invalid: () => "it is not a working git worktree (its git metadata is missing or broken)",
30
+ "not-linked": () => "it is a git repository of its own, not a worktree of one",
31
+ "other-branch": (entry) => entry.branch ? `it is on branch ${entry.branch}, not its alp branch` : "its HEAD is detached, so no branch holds its work",
32
+ "commit-failed": (entry) => `its work could not be committed${entry.detail ? ` (${entry.detail})` : ""}`,
33
+ uncommitted: () => "it still has changes that are not committed",
34
+ "ignored-files": (entry) => entry.files?.length ? `its work is committed to ${entry.branch}, but it holds ignored files that exist nowhere else: ${entry.files.join(", ")}` : `its ignored files could not be checked${entry.detail ? ` (${entry.detail})` : ""}`
35
+ };
28
36
  async function rotate(log2) {
29
37
  const size = await stat(log2).then((info) => info.size, () => 0);
30
38
  if (size < LOG_BYTES) return;
@@ -182,7 +190,18 @@ async function run(home2) {
182
190
  await writeFile(marker, JSON.stringify({ pid: process.pid, startedAt: (/* @__PURE__ */ new Date()).toISOString(), groupLeader: leadsGroup() }), { mode: 384 });
183
191
  const runLogDir = process.env.ALP_RUN_LOG_DIR || path.join(home2, "runs");
184
192
  const worktreeDir = path.join(home2, "worktrees");
185
- for (const branch of await reclaimWorktrees(worktreeDir).catch(() => [])) log.info(`kept interrupted work on branch ${branch}`, { event: "worktree.kept", branch });
193
+ const reclaimed = await reclaimWorktrees(worktreeDir).catch(() => ({ kept: [], left: [] }));
194
+ for (const branch of reclaimed.kept) log.info(`kept interrupted work on branch ${branch}`, { event: "worktree.kept", branch });
195
+ for (const entry of reclaimed.left) {
196
+ log.warn(`left worktree ${entry.path} in place: ${LEFT_REASONS[entry.reason](entry)}`, {
197
+ event: "worktree.left",
198
+ path: entry.path,
199
+ reason: entry.reason,
200
+ ...entry.branch ? { branch: entry.branch } : {},
201
+ ...entry.detail ? { detail: entry.detail } : {},
202
+ ...entry.files ? { files: entry.files } : {}
203
+ });
204
+ }
186
205
  const copyDir = path.join(home2, "copies");
187
206
  await reclaimCopies(copyDir).catch(() => 0);
188
207
  const settings = await userSettings(home2);
@@ -20,6 +20,10 @@ export type Caller = {
20
20
  agent?: boolean;
21
21
  };
22
22
  type Handler = (params: any, caller?: Caller) => Promise<unknown>;
23
+ /** Core refusals (AlpError codes) as protocol errors; `context` decides what an ambiguous one means. */
24
+ export declare function fromCore(error: any, context?: {
25
+ notFound?: 'not_found' | 'invalid_entry';
26
+ }): unknown;
23
27
  export declare function createOperations({ home, templates, knownProjects, onGateChange }?: OperationsOptions): {
24
28
  handlers: {
25
29
  [x: string]: Handler;
@@ -182,7 +182,7 @@ function createOperations({ home, templates, knownProjects = () => [], onGateCha
182
182
  return { id: task.id, status: task.status, rev: task.rev, ...landed ? { landed } : {} };
183
183
  }),
184
184
  // Approves a gate, or with reject records the user's rejection and leaves it open. Either way
185
- // the runtime is told, so main gets the decision by mail once and the gate's card settles.
185
+ // the runtime is told, so main gets the decision by mail (at least once) and the gate's card settles.
186
186
  "task.gate.resolve": guard(async ({ projectRoot, id, gate, note, ifRev, choice, reject, channel = "web" }, caller) => {
187
187
  const root = await project(projectRoot);
188
188
  if (caller?.agent) {
@@ -281,5 +281,6 @@ function createOperations({ home, templates, knownProjects = () => [], onGateCha
281
281
  };
282
282
  }
283
283
  export {
284
- createOperations
284
+ createOperations,
285
+ fromCore
285
286
  };
package/dist/server.js CHANGED
@@ -15,7 +15,7 @@ import { validateParams } from "@anhlp/alp-protocol/contract";
15
15
  import { ERROR as ERROR2 } from "@anhlp/alp-protocol";
16
16
  import { DEFAULT_MODEL, models, modes, thinkingOptions } from "@anhlp/alp-runtime/index";
17
17
  import { RpcError } from "./rpc-error.js";
18
- import { createOperations } from "./operations.js";
18
+ import { createOperations, fromCore } from "./operations.js";
19
19
  import { createFindPages, FileAccessError, FilesError, listWorkspaceDirectory, previewWorkspaceFile, readWorkspaceFile, searchHostDirectories, searchWorkspaceFiles } from "./files.js";
20
20
  import { createGitReader } from "./git.js";
21
21
  import { createScheduleStore, projectKey } from "./schedules.js";
@@ -1025,14 +1025,18 @@ function createDaemonServer({ runtime, socketPath, version, onShutdown, store, r
1025
1025
  throw new RpcError(ERROR.failed, error?.message ?? String(error));
1026
1026
  }
1027
1027
  },
1028
- "question.answer"(connection, { questionId, text, dismiss = false, reason }) {
1028
+ async "question.answer"(connection, { questionId, text, dismiss = false, reason }) {
1029
1029
  if (connection.agent) throw new RpcError(ERROR.forbidden, "Only the user answers a question; this connection was opened by an ALP agent", { reason: "user_only" });
1030
1030
  if (typeof questionId !== "string") throw new RpcError(-32602, "questionId is required");
1031
1031
  if (dismiss !== true && typeof text !== "string") throw new RpcError(-32602, "text or dismiss is required");
1032
1032
  const matches = runtime.questions().filter((question) => question.id === questionId || question.id.startsWith(questionId));
1033
1033
  if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
1034
1034
  const channel = connection.client?.startsWith("alp-paseo") ? "paseo" : "web";
1035
- runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
1035
+ const decided = runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
1036
+ if (decided) await decided.catch((error) => {
1037
+ if (error?.code === "GATE_BUSY" || error?.code === "GATE_DECIDED") throw new RpcError(ERROR.conflict, error.message, { reason: "task_state" });
1038
+ throw fromCore(error);
1039
+ });
1036
1040
  return { questionId: matches[0].id };
1037
1041
  },
1038
1042
  "daemon.shutdown": () => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-daemon",
3
- "version": "0.0.1-beta.5",
3
+ "version": "0.0.1-beta.6",
4
4
  "type": "module",
5
5
  "description": "ALP daemon module",
6
6
  "files": [
@@ -129,10 +129,10 @@
129
129
  "node": ">=22.12"
130
130
  },
131
131
  "dependencies": {
132
- "@anhlp/alp-core": "0.0.1-beta.5",
133
- "@anhlp/alp-runtime": "0.0.1-beta.5",
134
- "@anhlp/alp-client": "0.0.1-beta.5",
135
- "@anhlp/alp-protocol": "0.0.1-beta.5",
132
+ "@anhlp/alp-core": "0.0.1-beta.6",
133
+ "@anhlp/alp-runtime": "0.0.1-beta.6",
134
+ "@anhlp/alp-client": "0.0.1-beta.6",
135
+ "@anhlp/alp-protocol": "0.0.1-beta.6",
136
136
  "@anthropic-ai/sdk": "^0.131.0",
137
137
  "ws": "^8.22.0",
138
138
  "zod": "4.4.3",
package/src/main.ts CHANGED
@@ -6,6 +6,7 @@ import { fileURLToPath } from 'node:url';
6
6
  import templates from 'alp:templates';
7
7
  import { alpHome, daemonPaths, assertPrivateDirectory, PROTOCOL_VERSION, withDaemonLifecycle } from '@anhlp/alp-client/index';
8
8
  import { attachmentStageDir, createAlpRuntime, liveProbes, ModelCatalog, reclaimCopies, reclaimWorktrees, setActiveCatalog } from '@anhlp/alp-runtime/index';
9
+ import type { LeftWorktree } from '@anhlp/alp-runtime/index';
9
10
  import { createDaemonServer } from './server.js';
10
11
  import { acquireLock, heartbeat, releaseLock, updateLock } from './lock.js';
11
12
  import { createStore } from './store.js';
@@ -23,6 +24,18 @@ const LOG_BYTES = 10 * 1024 * 1024;
23
24
  const LOG_FILES = 3;
24
25
  const log = createLogger({ component: 'alpd' });
25
26
 
27
+ /** Why reclaimWorktrees left a directory in $ALP_HOME/worktrees, for the `worktree.left` line. */
28
+ const LEFT_REASONS: Record<LeftWorktree['reason'], (entry: LeftWorktree) => string> = {
29
+ invalid: () => 'it is not a working git worktree (its git metadata is missing or broken)',
30
+ 'not-linked': () => 'it is a git repository of its own, not a worktree of one',
31
+ 'other-branch': entry => entry.branch ? `it is on branch ${entry.branch}, not its alp branch` : 'its HEAD is detached, so no branch holds its work',
32
+ 'commit-failed': entry => `its work could not be committed${entry.detail ? ` (${entry.detail})` : ''}`,
33
+ uncommitted: () => 'it still has changes that are not committed',
34
+ 'ignored-files': entry => entry.files?.length
35
+ ? `its work is committed to ${entry.branch}, but it holds ignored files that exist nowhere else: ${entry.files.join(', ')}`
36
+ : `its ignored files could not be checked${entry.detail ? ` (${entry.detail})` : ''}`,
37
+ };
38
+
26
39
  async function rotate(log: string) {
27
40
  const size = await stat(log).then(info => info.size, () => 0);
28
41
  if (size < LOG_BYTES) return;
@@ -201,8 +214,16 @@ async function run(home: string) {
201
214
  await writeFile(marker, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString(), groupLeader: leadsGroup() }), { mode: 0o600 });
202
215
  const runLogDir = process.env.ALP_RUN_LOG_DIR || path.join(home, 'runs');
203
216
  const worktreeDir = path.join(home, 'worktrees');
204
- // Worktrees of assignments a crash interrupted: their work goes to their branches.
205
- for (const branch of await reclaimWorktrees(worktreeDir).catch(() => [] as string[])) log.info(`kept interrupted work on branch ${branch}`, { event: 'worktree.kept', branch });
217
+ // Worktrees of assignments a crash interrupted: their work goes to their branches. What
218
+ // reclaim leaves in place stays in $ALP_HOME/worktrees until the user looks: say where and why.
219
+ const reclaimed = await reclaimWorktrees(worktreeDir).catch(() => ({ kept: [] as string[], left: [] }));
220
+ for (const branch of reclaimed.kept) log.info(`kept interrupted work on branch ${branch}`, { event: 'worktree.kept', branch });
221
+ for (const entry of reclaimed.left) {
222
+ log.warn(`left worktree ${entry.path} in place: ${LEFT_REASONS[entry.reason](entry)}`, {
223
+ event: 'worktree.left', path: entry.path, reason: entry.reason,
224
+ ...(entry.branch ? { branch: entry.branch } : {}), ...(entry.detail ? { detail: entry.detail } : {}), ...(entry.files ? { files: entry.files } : {}),
225
+ });
226
+ }
206
227
  // Review copies of interrupted assignments hold nothing to keep.
207
228
  const copyDir = path.join(home, 'copies');
208
229
  await reclaimCopies(copyDir).catch(() => 0);
package/src/operations.ts CHANGED
@@ -51,7 +51,7 @@ const SECRET_MAPS: Record<string, string[][]> = {
51
51
  const failure = (code: number, reason: string, message: string, extra: object = {}) => new RpcError(code, message, { reason, ...extra });
52
52
 
53
53
  /** Core refusals (AlpError codes) as protocol errors; `context` decides what an ambiguous one means. */
54
- function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry' } = {}): unknown {
54
+ export function fromCore(error: any, context: { notFound?: 'not_found' | 'invalid_entry' } = {}): unknown {
55
55
  if (error instanceof RpcError || typeof error?.code !== 'string' || error?.name !== 'AlpError') return error;
56
56
  const message = error.message as string;
57
57
  switch (error.code) {
@@ -208,7 +208,7 @@ export function createOperations({ home, templates, knownProjects = () => [], on
208
208
  }),
209
209
 
210
210
  // Approves a gate, or with reject records the user's rejection and leaves it open. Either way
211
- // the runtime is told, so main gets the decision by mail once and the gate's card settles.
211
+ // the runtime is told, so main gets the decision by mail (at least once) and the gate's card settles.
212
212
  'task.gate.resolve': guard(async ({ projectRoot, id, gate, note, ifRev, choice, reject, channel = 'web' }, caller) => {
213
213
  const root = await project(projectRoot);
214
214
  // Only the user decides a human gate: never a connection an ALP agent opened (t-ca1f).
package/src/server.ts CHANGED
@@ -17,7 +17,7 @@ import type { Receipt, SessionRecord, SessionStatus, Store, UnreadableReceipt }
17
17
  import type { PromptContent, SessionSummary } from '@anhlp/alp-protocol/session';
18
18
  import type { ScheduleJob, TurnAttention } from '@anhlp/alp-protocol/index';
19
19
  import { RpcError } from './rpc-error.js';
20
- import { createOperations, type OperationsOptions } from './operations.js';
20
+ import { createOperations, fromCore, type OperationsOptions } from './operations.js';
21
21
  import { createFindPages, FileAccessError, FilesError, listWorkspaceDirectory, previewWorkspaceFile, readWorkspaceFile, searchHostDirectories, searchWorkspaceFiles } from './files.js';
22
22
  import { createGitReader } from './git.js';
23
23
  import { createScheduleStore, projectKey } from './schedules.js';
@@ -1298,7 +1298,7 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1298
1298
  }
1299
1299
  },
1300
1300
 
1301
- 'question.answer'(connection, { questionId, text, dismiss = false, reason }) {
1301
+ async 'question.answer'(connection, { questionId, text, dismiss = false, reason }) {
1302
1302
  // An answer speaks for the user (a gate card's answer decides the gate): never from a connection an ALP agent opened (t-ca1f).
1303
1303
  if (connection.agent) throw new RpcError(ERROR.forbidden, 'Only the user answers a question; this connection was opened by an ALP agent', { reason: 'user_only' });
1304
1304
  if (typeof questionId !== 'string') throw new RpcError(-32602, 'questionId is required');
@@ -1307,7 +1307,13 @@ export function createDaemonServer({ runtime, socketPath, version, onShutdown, s
1307
1307
  const matches = runtime.questions().filter(question => question.id === questionId || question.id.startsWith(questionId));
1308
1308
  if (matches.length !== 1) throw new RpcError(ERROR.notFound, matches.length ? `Question id ${questionId} is ambiguous` : `No question ${questionId} waits for an answer`);
1309
1309
  const channel = connection.client?.startsWith('alp-paseo') ? 'paseo' as const : 'web' as const;
1310
- runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
1310
+ // A gate card's answer settles once its decision is written; one that decides nothing is refused (t-595d).
1311
+ const decided = runtime.answer(matches[0].id, dismiss === true ? { dismiss: true, reason, channel } : { text, channel });
1312
+ if (decided) await decided.catch((error: any) => {
1313
+ // Another answer is being recorded, or another channel decided first: as task.gate.resolve says it.
1314
+ if (error?.code === 'GATE_BUSY' || error?.code === 'GATE_DECIDED') throw new RpcError(ERROR.conflict, error.message, { reason: 'task_state' });
1315
+ throw fromCore(error);
1316
+ });
1311
1317
  return { questionId: matches[0].id };
1312
1318
  },
1313
1319