@anhlp/alp-runtime 0.0.1-beta.4 → 0.0.1-beta.5

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 (67) hide show
  1. package/dist/acp-transport.js +5 -36
  2. package/dist/antigravity-transport.d.ts +17 -0
  3. package/dist/antigravity-transport.js +82 -58
  4. package/dist/assignment-results.d.ts +34 -0
  5. package/dist/assignment-results.js +94 -2
  6. package/dist/board-domain.js +2 -2
  7. package/dist/board.d.ts +6 -0
  8. package/dist/board.js +7 -0
  9. package/dist/catalog.d.ts +13 -0
  10. package/dist/catalog.js +9 -1
  11. package/dist/claude-transport.d.ts +7 -0
  12. package/dist/claude-transport.js +65 -6
  13. package/dist/compact.d.ts +29 -0
  14. package/dist/compact.js +49 -0
  15. package/dist/configure.d.ts +1 -1
  16. package/dist/configure.js +2 -2
  17. package/dist/contracts.d.ts +25 -1
  18. package/dist/index.d.ts +9 -2
  19. package/dist/index.js +30 -2
  20. package/dist/input-limits.d.ts +25 -0
  21. package/dist/input-limits.js +48 -0
  22. package/dist/language.d.ts +8 -0
  23. package/dist/language.js +20 -0
  24. package/dist/mcp-tools.d.ts +8 -0
  25. package/dist/mcp-tools.js +26 -0
  26. package/dist/model-catalog.d.ts +76 -0
  27. package/dist/model-catalog.js +193 -0
  28. package/dist/model-probes.d.ts +7 -0
  29. package/dist/model-probes.js +69 -0
  30. package/dist/providers.js +2 -0
  31. package/dist/resolve.d.ts +1 -0
  32. package/dist/resolve.js +3 -1
  33. package/dist/runtime.d.ts +3 -1
  34. package/dist/runtime.js +605 -45
  35. package/dist/session-config.d.ts +174 -0
  36. package/dist/session-config.js +9 -9
  37. package/dist/session-state.d.ts +23 -1
  38. package/dist/tools.d.ts +82 -0
  39. package/dist/tools.js +53 -5
  40. package/dist/transport.js +3 -1
  41. package/dist/workspace.d.ts +11 -4
  42. package/dist/workspace.js +29 -11
  43. package/package.json +3 -3
  44. package/src/acp-transport.ts +7 -37
  45. package/src/antigravity-transport.ts +95 -53
  46. package/src/assignment-results.ts +85 -3
  47. package/src/board-domain.ts +2 -2
  48. package/src/board.ts +7 -0
  49. package/src/catalog.ts +10 -1
  50. package/src/claude-transport.ts +71 -6
  51. package/src/compact.ts +62 -0
  52. package/src/configure.ts +3 -3
  53. package/src/contracts.ts +22 -1
  54. package/src/index.ts +9 -2
  55. package/src/input-limits.ts +65 -0
  56. package/src/language.ts +18 -0
  57. package/src/mcp-tools.ts +33 -0
  58. package/src/model-catalog.ts +166 -0
  59. package/src/model-probes.ts +58 -0
  60. package/src/providers.ts +3 -0
  61. package/src/resolve.ts +4 -2
  62. package/src/runtime.ts +650 -46
  63. package/src/session-config.ts +8 -8
  64. package/src/session-state.ts +15 -1
  65. package/src/tools.ts +53 -5
  66. package/src/transport.ts +3 -1
  67. package/src/workspace.ts +42 -15
package/dist/runtime.js CHANGED
@@ -1,7 +1,8 @@
1
1
  // packages/runtime/src/runtime.ts
2
- import { createAssignmentResults } from "./assignment-results.js";
2
+ import { createAssignmentResults, RESULT_OUTCOMES } from "./assignment-results.js";
3
3
  import { constants as fsConstants } from "node:fs";
4
4
  import { errorData, plainObject, toolResult } from "./tool-results.js";
5
+ import { inputLimitError, POUR_VARS, TOOL_INPUT, VAR_NAME } from "./input-limits.js";
5
6
  import { createLogger } from "@anhlp/alp-core/log";
6
7
  import { PROMPT_IMAGES, base64Bytes } from "@anhlp/alp-protocol";
7
8
  import { createBoardDomain } from "./board-domain.js";
@@ -24,6 +25,7 @@ import { resolveDelegation } from "@anhlp/alp-core/delegation";
24
25
  import { discoverAgents } from "@anhlp/alp-core/resolver";
25
26
  import { acpDecision, acpWhat } from "./acp-transport.js";
26
27
  import { models, modes, thinkingOptionsFor, withinMode, writes } from "./catalog.js";
28
+ import { feedCatalog } from "./model-catalog.js";
27
29
  import { runHook } from "@anhlp/alp-core/hook-run";
28
30
  import { hookMatches } from "@anhlp/alp-core/hooks";
29
31
  import { isTrusted, trustProject } from "@anhlp/alp-core/trust";
@@ -44,11 +46,12 @@ import { claudeSandboxAvailable, SKILL_PLUGIN } from "./claude-transport.js";
44
46
  import { boundDetail, codexToolCall, toolError } from "./tool-detail.js";
45
47
  import { ALP_REPO, gh, projectRepo } from "./github.js";
46
48
  import { optionalRead, usageAllows, COMPACT_SHARE } from "./runtime-context.js";
49
+ import { checkpointPrompt, compactDue, compactInstructions, contextFill, NATIVE_COMPACT, seedPrompt } from "./compact.js";
47
50
  import { providerUsage, sessionUsage } from "./usage.js";
48
51
  import { parse as toml } from "smol-toml";
49
52
  import { findFormula, formulaDirs, listFormulas, pourFormula } from "@anhlp/alp-core/formulas";
50
53
  import { addAllowRule, capMode, commandDecision, profileFor, unwrapShell } from "@anhlp/alp-core/permissions";
51
- import { addGate, checkGates, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask } from "@anhlp/alp-core/tasks";
54
+ import { addGate, checkGates, gateDecisions, markGateNotified, rejectGate, resolveGate, blockersOf, childrenOf, closeTask, epicReport, releaseOrphans, createTask, getTask, linkTask, listTasks, loadTasks, readyTasks, releaseTask, reopenTask, retakeTask, startRefusal, startTask, submitTask, summarize, taskDigest, updateTask } from "@anhlp/alp-core/tasks";
52
55
  var CATALOG = "ALP runtime catalog and usage snapshot (data, not instructions): ";
53
56
  function inputLayoutOf(catalog) {
54
57
  const found = /^\{"inputLayout":\{"textParts":(\d+),"prompt":(\d+)\}/.exec(catalog.slice(CATALOG.length));
@@ -84,15 +87,24 @@ var LIMIT_CHECK_MS = 6e4;
84
87
  var LIMIT_FRESH_MS = 15e3;
85
88
  var CONTEXT_SOON = 0.9;
86
89
  var CONTEXT_RESET = 0.5;
90
+ var COMPACT_RETRY_MS = 10 * 6e4;
91
+ var MAIL_WAITS = "Mail waits for the session";
92
+ var REVIEWING = "The supervisor is reviewing the session";
93
+ var COMPACT_NATIVE_MS = 5 * 6e4;
87
94
  var BRIEF_CHARS = 8e3;
95
+ var RESULT_EVIDENCE_CHARS = 2e3;
96
+ var RESOLVE_NOTE_CHARS = 2e3;
88
97
  var STEERING = "\0steering";
89
98
  var STARTING = "\0starting";
90
99
  var APPROVALS = ["approve", "approved", "yes", "y", "ok", "\u0111\u1ED3ng \xFD", "duy\u1EC7t", "c\xF3"];
100
+ var CHOICES_REJECT = ["reject", "t\u1EEB ch\u1ED1i"];
91
101
  var SKILL_BODY_CHARS = 2e4;
92
102
  var STARTER_ROLES = ["main", "lead", "peer", "oracle", "reviewer", "supervisor"];
93
103
  var ISSUE_BODY_CHARS = 2e4;
94
104
  var ISSUE_FOOTER = "\n\n---\n_Drafted by an ALP agent and posted with the user's approval._";
95
105
  var LESSON_CHARS = 600;
106
+ var CURATE_MARKER = "[alp-curate]";
107
+ var CURATE_PROMPT = `${CURATE_MARKER} Monthly review of lessons and skills. Use the curate skill: read every lesson and skill, then propose to the user, in one message, the merges, shortenings and removals of lessons, the skills no longer needed, and what ALP itself should adopt. Change nothing before the user approves. To turn this off, set curate.monthly to false in .alp/settings.json.`;
96
108
  var DIGEST_CHARS = 12e3;
97
109
  var JOURNAL_LINE_CHARS = 400;
98
110
  var clock = (at = Date.now()) => new Date(at).toTimeString().slice(0, 8);
@@ -151,6 +163,7 @@ function createAlpRuntime(options = {}) {
151
163
  const refuseMutation = (reason, message) => {
152
164
  throw new WorkspaceMutationError(reason, message);
153
165
  };
166
+ const ADOPTION = Symbol("adoption");
154
167
  async function admission(run) {
155
168
  if (workspaceMutation) refuseMutation("workspace_busy", "A workspace mutation is in progress; retry after it finishes");
156
169
  admitting++;
@@ -248,7 +261,12 @@ function createAlpRuntime(options = {}) {
248
261
  }
249
262
  session.userStopped = false;
250
263
  if (session.role === "supervisor" && session.parent && sessions.get(session.parent)?.reviewPending) review(session.parent);
264
+ if (session.role === "supervisor" && session.parent) {
265
+ const root = sessions.get(session.parent);
266
+ if (root) queueMicrotask(() => compactAtBoundary(session.parent, root));
267
+ }
251
268
  if (!session.parent) void showTasks(sessionId, session);
269
+ if (!session.parent && session.role !== "supervisor") queueMicrotask(() => compactAtBoundary(sessionId, session, state));
252
270
  if (session.parkReason && state !== "completed") {
253
271
  park(sessionId, session);
254
272
  return;
@@ -407,7 +425,7 @@ function createAlpRuntime(options = {}) {
407
425
  if (state === "failed" && LIMIT_ERRORS.includes(params.turn.error?.codexErrorInfo)) {
408
426
  if (session.role !== "supervisor") {
409
427
  session.parkReason = `the ${label(session.runtimeKind)} usage limit was reached`;
410
- session.parkPause = { scope: paused.all ? "all" : session.runtimeKind };
428
+ session.parkPause = { scope: paused.all ? "all" : session.runtimeKind, ...paused.all?.cause === "disk" ? { disk: true } : {} };
411
429
  }
412
430
  void limitReached(session, params.turn.error);
413
431
  }
@@ -421,6 +439,7 @@ function createAlpRuntime(options = {}) {
421
439
  }
422
440
  const sessionClosures = /* @__PURE__ */ new WeakMap();
423
441
  const openedSessions = /* @__PURE__ */ new WeakSet();
442
+ const openings = /* @__PURE__ */ new WeakMap();
424
443
  const assignmentSessions = /* @__PURE__ */ new WeakMap();
425
444
  function closeSession(sessionId, session = sessions.get(sessionId), notify = true) {
426
445
  if (!session) return Promise.resolve();
@@ -834,22 +853,25 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
834
853
  return toolResult(true, { tasks: rows.slice(0, limit).map((task2) => summarize(task2, tasks2)), ...rows.length > limit ? { more: rows.length - limit } : {}, ...warnings });
835
854
  }
836
855
  const { action: _action, id, note, reason, summary, unverified, add, remove, ...input } = args;
837
- if (action === "pour" && (typeof input.formula !== "string" || input.vars !== void 0 && (!input.vars || typeof input.vars !== "object" || Array.isArray(input.vars) || !Object.values(input.vars).every((value) => typeof value === "string")))) {
838
- return toolResult(false, { error: "pour needs formula, and vars as an object of text values" });
856
+ if (action === "pour" && (typeof input.formula !== "string" || input.vars !== void 0 && (!input.vars || typeof input.vars !== "object" || Array.isArray(input.vars) || inputLimitError(input.vars, POUR_VARS) || !Object.entries(input.vars).every(([name, value]) => VAR_NAME.test(name) && typeof value === "string")))) {
857
+ return toolResult(false, { error: `pour needs formula, and vars as an object of text values: at most ${POUR_VARS.items}, named like formula variables, each at most ${POUR_VARS.string} characters` });
839
858
  }
840
- const { kind, until, ref, gate, formula: _formula, vars: _vars, ...fields } = input;
859
+ const { kind, until, ref, gate, options: gateChoices, formula: _formula, vars: _vars, ...fields } = input;
841
860
  if (action === "clear") {
842
861
  const current = (await loadTasks(project)).tasks.find((candidate) => candidate.id === id);
843
862
  if (current?.gates.find((entry) => entry.id === gate)?.kind === "human") return toolResult(false, { error: "Only the user clears a human gate; ask them, and they approve it with alp task gate clear or in Paseo" });
844
863
  }
845
864
  let poured;
846
865
  const hookedClose = async (id2) => {
866
+ const current = (await loadTasks(project)).tasks.find((candidate) => candidate.id === id2);
867
+ if (current && (current.step?.human || current.gates.some((gate2) => gate2.kind === "human" && !gate2.resolved))) throw new Error(`Only the user closes ${id2}: it waits on the user's decision. Ask the user to decide it`);
847
868
  const refused = await runHooks(sessionId, session, "task.close", { reason, ...summary ? { summary } : {} }, id2);
848
869
  if (refused) throw new Error(`A task.close hook refused to close ${id2}: ${refused}`);
849
870
  return closeTask(project, id2, { reason, summary, unverified }, by);
850
871
  };
851
- const task = action === "create" ? await createTask(project, fields, by) : action === "update" ? await updateTask(project, id, { ...fields, note }, by) : action === "pour" ? (poured = await pourFormula(project, (await findFormula(project, options.libraryDir, input.formula, { toml })).formula, input.vars, by, input.parent ? { parent: input.parent } : {})).epic : action === "gate" ? await addGate(project, id, { kind, note, until, ref }, by) : action === "clear" ? await resolveGate(project, id, gate, { by, note }) : action === "link" ? await linkTask(project, id, { add, remove }, by) : action === "start" ? await startTask(project, id, { agent: by, session: sessionId }, by) : action === "close" ? await hookedClose(id) : await reopenTask(project, id, { note }, by);
872
+ const task = action === "create" ? await createTask(project, fields, by) : action === "update" ? await updateTask(project, id, { ...fields, note }, by) : action === "pour" ? (poured = await pourFormula(project, (await findFormula(project, options.libraryDir, input.formula, { toml })).formula, input.vars, by, input.parent ? { parent: input.parent } : {})).epic : action === "gate" ? await addGate(project, id, { kind, note, until, ref, ...gateChoices !== void 0 ? { options: gateChoices } : {} }, by) : action === "clear" ? await resolveGate(project, id, gate, { by, note }) : action === "link" ? await linkTask(project, id, { add, remove }, by) : action === "start" ? await startTask(project, id, { agent: by, session: sessionId }, by) : action === "close" ? await hookedClose(id) : await reopenTask(project, id, { note }, by);
852
873
  touchTask(rootOf(sessionId), task.id);
874
+ if (action === "gate" && kind === "human") void syncGates(project);
853
875
  runLog(rootOf(sessionId), { event: "task", action, agent: by, id: task.id, title: task.title, status: task.status, ...summary ?? note ? { detail: summary ?? note } : {} });
854
876
  const { tasks } = await loadTasks(project);
855
877
  const landed = {};
@@ -956,6 +978,45 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
956
978
  return toolResult(false, { assignmentId: entry.assignmentId, error: errorData(error).message });
957
979
  }
958
980
  }
981
+ async function resolveTool(sessionId, session, args) {
982
+ if (!plainObject(args, ["assignmentId", "outcome", "note"]) || typeof args.assignmentId !== "string" || !RESULT_OUTCOMES.includes(args.outcome) || args.note !== void 0 && (typeof args.note !== "string" || args.note.length > RESOLVE_NOTE_CHARS)) {
983
+ return toolResult(false, { error: `Pass assignmentId, outcome (${RESULT_OUTCOMES.join(", ")}), and optionally a note of at most ${RESOLVE_NOTE_CHARS} characters` });
984
+ }
985
+ const id = args.assignmentId;
986
+ const outcome = args.outcome;
987
+ const note = args.note;
988
+ const live2 = [...sessions.values()];
989
+ if (sessions.has(id) || live2.some((other) => other.assignments.has(id)) || inFlight.all().some((entry2) => entry2.assignmentId === id) || inherited.some((entry2) => entry2.assignmentId === id)) {
990
+ return toolResult(false, { error: "That assignment is still running or can still be recovered; wait for its result" });
991
+ }
992
+ if (live2.some((other) => other.worktrees.has(id))) return toolResult(false, { error: "Its change waits in a worktree; apply it with alp_merge or drop it with alp_discard" });
993
+ let ledger;
994
+ try {
995
+ ledger = await assignmentResults.inspect();
996
+ } catch (error) {
997
+ return toolResult(false, { error: errorData(error).message });
998
+ }
999
+ const entry = ledger.results.find((owner) => owner.assignmentId === id && !owner.handled);
1000
+ const project = session.mapping.agent.projectRoot;
1001
+ const overlapping2 = async (a, b) => {
1002
+ const [x, y] = [await realpath(a).catch(() => a), await realpath(b).catch(() => b)];
1003
+ const within = (parent, child) => {
1004
+ const relative = path.relative(parent, child);
1005
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
1006
+ };
1007
+ return within(x, y) || within(y, x);
1008
+ };
1009
+ const allowed = !!entry && (entry.result ? entry.result.requesters.includes(sessionId) || !session.parent && await sameDirectory(entry.result.project, project) : !session.parent && await overlapping2(entry.checkout, project));
1010
+ if (!entry || !allowed) return toolResult(false, { error: `No unresolved assignment result ${id} of yours` });
1011
+ if (entry.worktree && await stat(entry.worktree).then(() => true, () => false)) return toolResult(false, { error: `Its worktree ${entry.worktree} still exists; merge or remove it first` });
1012
+ try {
1013
+ const archived = await assignmentResults.resolve(id, { outcome, by: `${session.mapping.agent.name} in ${sessionId}`, at: (/* @__PURE__ */ new Date()).toISOString(), ...note ? { note } : {} });
1014
+ runLog(rootOf(sessionId), { event: "result.resolved", assignmentId: id, agent: session.mapping.agent.name, outcome, ...note ? { note: clip(note, 500) } : {} });
1015
+ return toolResult(true, { resolved: id, outcome, archivedAt: archived.archivedAt });
1016
+ } catch (error) {
1017
+ return toolResult(false, { assignmentId: id, error: errorData(error).message });
1018
+ }
1019
+ }
959
1020
  let forgetting = Promise.resolve();
960
1021
  function forgetExpired() {
961
1022
  forgetting = forgetting.then(async () => {
@@ -983,7 +1044,7 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
983
1044
  const label = (kind) => kind === "claude" ? "Claude" : kind === "acp" ? "ACP agent" : kind === "antigravity" ? "Antigravity" : "Codex";
984
1045
  const pauseOf = (kind) => paused.all ?? paused.runtimes[kind];
985
1046
  const held = (session) => !!session.parked || !!pauseOf(session.runtimeKind) || (session.lifecycleHolds ?? 0) > 0;
986
- const holdsWake = (session) => held(session) || !!session.awaitingBrief;
1047
+ const holdsWake = (session) => held(session) || !!session.awaitingBrief || !!session.compacting;
987
1048
  function beginPending(session) {
988
1049
  let done;
989
1050
  session.pending = true;
@@ -1119,16 +1180,16 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1119
1180
  for (const [id, session] of sessions) {
1120
1181
  if (!session.parent || session.closed || !session.active || session.role === "supervisor" || scope !== "all" && session.runtimeKind !== scope) continue;
1121
1182
  if (session.parkReason && !session.parkPause) continue;
1122
- session.parkReason = `paused by ${pause.by}`;
1123
- session.parkPause = { scope };
1183
+ session.parkReason = pause.cause === "disk" ? pause.reason : `paused by ${pause.by}`;
1184
+ session.parkPause = { scope, ...pause.cause === "disk" ? { disk: true } : {} };
1124
1185
  void session.runtime.request("turn/interrupt", { threadId: session.threadId, turnId: session.active }).catch(() => {
1125
1186
  });
1126
1187
  runLog(rootOf(id), { event: "assignment.parking", assignmentId: id, agent: session.mapping.agent.name, reason: session.parkReason });
1127
1188
  }
1128
1189
  }
1129
1190
  }
1130
- function resumeRuntime(scope, by) {
1131
- if (scope === "all") paused = { runtimes: {} };
1191
+ function resumeRuntime(scope, by, keepRuntimes = false) {
1192
+ if (scope === "all") paused = keepRuntimes ? { runtimes: paused.runtimes } : { runtimes: {} };
1132
1193
  else delete paused.runtimes[scope];
1133
1194
  savePauses();
1134
1195
  watchLimits();
@@ -1163,6 +1224,7 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1163
1224
  if (!parent || !assignment) return;
1164
1225
  emit(session.parent, { type: "assignment", assignment: assignmentSnapshot(assignment, "parked") });
1165
1226
  if (then) post(session.parent, { kind: "note", from: assignment.agent, assignment: sessionId, passive: true, body: `Parked: ${session.parked.reason}. ${then} Wait for it, or start other work.` });
1227
+ else if (session.parked.pause?.disk) post(session.parent, { kind: "stalled", from: assignment.agent, assignment: sessionId, body: `Parked: ${session.parked.reason}. ALP continues this assignment where it stopped as soon as the disk takes writes again (alpd checks every minute), or when the user frees space and runs alp resume. Wait for it, or tell the user the disk is full; what it changed stays in your checkout or its worktree.` });
1166
1228
  else post(session.parent, { kind: "stalled", from: assignment.agent, assignment: sessionId, body: `Parked: ${session.parked.reason}. ALP continues this assignment where it stopped when ${label(session.runtimeKind)} is resumed (${options.autoResume !== false && (pauseOf(session.runtimeKind)?.by ?? "alpd") === "alpd" ? `ALP resumes it as soon as ${label(session.runtimeKind)} says the limit lifted` : "the user runs alp resume"}). Wait for it, start other work, or stop it with alp_cancel and give the rest to an agent on another runtime (pass model claude:\u2026 or codex:\u2026); what it changed stays in your checkout or its worktree.` });
1167
1229
  }
1168
1230
  function continueParked(sessionId, session, expected = session.parked) {
@@ -1230,6 +1292,7 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1230
1292
  const used = usage2?.last?.totalTokens;
1231
1293
  const window = usage2?.modelContextWindow;
1232
1294
  if (session.role === "supervisor" || typeof used !== "number" || typeof window !== "number" || window <= 0) return;
1295
+ if (!session.compactCooling) session.contextFill = contextFill({ ...usage2, modelContextWindow: Math.min(typeof session.mapping.autocompact === "number" ? session.mapping.autocompact : typeof session.mapping.context === "number" ? session.mapping.context : window, window) });
1233
1296
  const compactAt = typeof usage2.autoCompactTokens === "number" && usage2.autoCompactTokens > 0 ? usage2.autoCompactTokens : session.runtimeKind === "codex" && session.mapping.autocompact ? Math.min(session.mapping.autocompact, Math.round(window * COMPACT_SHARE)) : Math.round(Math.min(session.mapping.autocompact ?? session.mapping.context ?? window, window) * COMPACT_SHARE);
1234
1297
  const fill = used / compactAt;
1235
1298
  if (fill < CONTEXT_RESET) {
@@ -1266,13 +1329,157 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1266
1329
  if (!done) return;
1267
1330
  const agent = session.mapping.agent.name;
1268
1331
  runLog(rootOf(sessionId), { event: "compacted", sessionId, agent, ...trigger, ...tokens, ...failed ? { failed: true, ...item.error ? { error: String(item.error) } : {} } : {} });
1269
- if (failed) return;
1332
+ if (failed) {
1333
+ if (session.compacting?.phase === "native") compactFailed(sessionId, session, item.error ? String(item.error) : "the runtime could not compact");
1334
+ return;
1335
+ }
1270
1336
  session.contextLevel = 0;
1271
1337
  if (session.supervisor) session.journal.push(stamp(`${agent}'s context was compacted`));
1272
- if (session.role !== "supervisor") void restoreAfterCompaction(sessionId, session).catch(() => {
1338
+ const checkpoint = session.compacting?.phase === "native" ? session.compacting.checkpoint : void 0;
1339
+ if (session.role !== "supervisor") void restoreAfterCompaction(sessionId, session, checkpoint).catch(() => {
1340
+ });
1341
+ if (checkpoint !== void 0) compactFinished(sessionId, session, "native");
1342
+ }
1343
+ function compactHeld(sessionId, session, starting) {
1344
+ return session.closed || !!session.active || !!session.pending || session.waiters.length > 0 || !!session.parked || !!session.parkReason || starting && (hasActiveMail(session) || !!session.wakeHeld) || [...userQuestions.values()].some((pending) => pending.question.rootId === sessionId && !pending.gate);
1345
+ }
1346
+ function compactAtBoundary(sessionId, session, ended) {
1347
+ if (session.closed || sessions.get(sessionId) !== session) return;
1348
+ const current = session.compacting;
1349
+ if (ended && current?.phase === "checkpoint" && current.checkpoint === void 0 && current.turn) {
1350
+ const written = [...session.text.values()].at(-1)?.trim();
1351
+ if (ended !== "completed" || !written) {
1352
+ compactFailed(sessionId, session, ended !== "completed" ? `the checkpoint turn ${ended}` : "main wrote no checkpoint");
1353
+ return;
1354
+ }
1355
+ current.checkpoint = written;
1356
+ const timer = setTimeout(() => {
1357
+ if (session.compacting === current && current.phase === "checkpoint") compactFailed(sessionId, session, "main stayed busy after its checkpoint");
1358
+ }, COMPACT_NATIVE_MS);
1359
+ timer.unref?.();
1360
+ }
1361
+ if (ended && current?.phase === "native" && current.requested) {
1362
+ compactFailed(sessionId, session, "the runtime reported no compaction");
1363
+ return;
1364
+ }
1365
+ if (current) {
1366
+ if (current.checkpoint !== void 0 && current.phase === "checkpoint" && !compactHeld(sessionId, session, false)) void compactNow(sessionId, session);
1367
+ return;
1368
+ }
1369
+ if (compactHeld(sessionId, session, true)) return;
1370
+ if (session.compactBuffer?.length) {
1371
+ flushCompactBuffer(sessionId, session);
1372
+ return;
1373
+ }
1374
+ const trigger = compactDue(session.mapping.compact ?? { auto: false, threshold: 1 }, session.contextFill, !!session.compactRequested);
1375
+ if (!trigger) return;
1376
+ if (trigger === "auto" && session.compactFailedAt && Date.now() - session.compactFailedAt < COMPACT_RETRY_MS) return;
1377
+ session.compactRequested = false;
1378
+ const compacting = { phase: "checkpoint", trigger, startedAt: Date.now() };
1379
+ session.compacting = compacting;
1380
+ runLog(rootOf(sessionId), { event: "compact.started", sessionId, agent: session.mapping.agent.name, trigger, ...session.contextFill !== void 0 ? { fill: Math.round(session.contextFill * 100) / 100 } : {} });
1381
+ const work = queue.then(async () => {
1382
+ if (session.compacting !== compacting) return;
1383
+ if (session.closed || compactHeld(sessionId, session, true)) {
1384
+ session.compacting = void 0;
1385
+ if (trigger === "manual") session.compactRequested = true;
1386
+ compactReleased(sessionId, session);
1387
+ return;
1388
+ }
1389
+ compacting.turn = true;
1390
+ await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: "auto", content: [{ type: "text", text: checkpointPrompt(trigger, session.contextFill) }] }, "wake");
1391
+ }).catch((error) => compactFailed(sessionId, session, errorData(error).message));
1392
+ queue = work.catch(() => {
1273
1393
  });
1274
1394
  }
1275
- async function restoreAfterCompaction(sessionId, session) {
1395
+ async function compactNow(sessionId, session) {
1396
+ const current = session.compacting;
1397
+ const checkpoint = current.checkpoint;
1398
+ if (NATIVE_COMPACT.includes(session.runtimeKind)) {
1399
+ current.phase = "native";
1400
+ try {
1401
+ await session.runtime.request("thread/compact/start", { threadId: session.threadId, ...session.runtimeKind === "codex" ? {} : { instructions: compactInstructions(checkpoint) } });
1402
+ if (session.compacting !== current) return;
1403
+ current.requested = true;
1404
+ const timer = setTimeout(() => {
1405
+ if (session.compacting === current) compactFailed(sessionId, session, "the runtime reported no compaction in time");
1406
+ }, COMPACT_NATIVE_MS);
1407
+ timer.unref?.();
1408
+ return;
1409
+ } catch (error) {
1410
+ if (session.compacting !== current) return;
1411
+ runLog(rootOf(sessionId), { event: "compact.native_failed", sessionId, agent: session.mapping.agent.name, error: errorData(error).message });
1412
+ }
1413
+ }
1414
+ current.phase = "fresh";
1415
+ const work = queue.then(async () => {
1416
+ if (session.compacting !== current || session.closed) return;
1417
+ const refusal = restartRefusal(sessionId, session);
1418
+ if (refusal && refusal !== MAIL_WAITS && refusal !== REVIEWING) {
1419
+ compactFailed(sessionId, session, `a fresh conversation cannot start now: ${refusal}`);
1420
+ return;
1421
+ }
1422
+ await restartNative(sessionId, session, void 0);
1423
+ emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
1424
+ await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: "auto", content: [{ type: "text", text: seedPrompt(checkpoint, session.lastUserText) }] }, "wake");
1425
+ compactFinished(sessionId, session, "fresh");
1426
+ }).catch((error) => compactFailed(sessionId, session, errorData(error).message));
1427
+ queue = work.catch(() => {
1428
+ });
1429
+ }
1430
+ function compactFinished(sessionId, session, via) {
1431
+ const current = session.compacting;
1432
+ if (!current) return;
1433
+ session.compacting = void 0;
1434
+ session.compactFailedAt = void 0;
1435
+ session.contextFill = void 0;
1436
+ session.compactCooling = true;
1437
+ runLog(rootOf(sessionId), { event: "compact", sessionId, agent: session.mapping.agent.name, trigger: current.trigger, via, checkpointChars: current.checkpoint?.length ?? 0, ms: Date.now() - current.startedAt });
1438
+ const text2 = wordsFor(session).compacted(via === "native");
1439
+ emit(sessionId, { type: "item", item: { kind: "notice", id: `notice-${randomUUID().slice(0, 8)}`, level: "info", text: text2 } });
1440
+ compactReleased(sessionId, session);
1441
+ }
1442
+ function compactFailed(sessionId, session, reason) {
1443
+ const current = session.compacting;
1444
+ session.compacting = void 0;
1445
+ session.compactFailedAt = Date.now();
1446
+ runLog(rootOf(sessionId), { event: "compact.failed", sessionId, agent: session.mapping.agent.name, ...current ? { trigger: current.trigger } : {}, error: reason });
1447
+ if (!session.closed) emit(sessionId, { type: "item", item: { kind: "notice", id: `notice-${randomUUID().slice(0, 8)}`, level: "warning", text: wordsFor(session).compactFailed(reason) } });
1448
+ compactReleased(sessionId, session);
1449
+ }
1450
+ function compactReleased(sessionId, session) {
1451
+ queueMicrotask(() => {
1452
+ if (session.closed || session.compacting) return;
1453
+ flushCompactBuffer(sessionId, session);
1454
+ if (session.wakeHeld && !holdsWake(session)) {
1455
+ session.wakeHeld = false;
1456
+ deliver(sessionId, session);
1457
+ }
1458
+ });
1459
+ }
1460
+ function flushCompactBuffer(sessionId, session) {
1461
+ if (session.compacting || session.active || !session.compactBuffer?.length) return;
1462
+ const held2 = session.compactBuffer.splice(0);
1463
+ session.compactBuffer = void 0;
1464
+ const work = queue.then(async () => {
1465
+ for (const [index, input] of held2.entries()) {
1466
+ await promptSession(sessionId, { ...input, delivery: index === 0 && !session.active ? "auto" : "steer" }, true);
1467
+ }
1468
+ });
1469
+ queue = work.catch(() => {
1470
+ });
1471
+ }
1472
+ function requestCompact(sessionId) {
1473
+ const session = sessions.get(sessionId);
1474
+ if (!session || session.closed) throw new ConversationError("session_busy", "The session is not open");
1475
+ if (session.parent || session.role === "supervisor") throw new ConversationError("runtime_unsupported", "Only a root session is compacted");
1476
+ if (session.compacting) return { status: "running" };
1477
+ session.compactRequested = true;
1478
+ if (compactHeld(sessionId, session, true)) return { status: "deferred" };
1479
+ compactAtBoundary(sessionId, session);
1480
+ return { status: "started" };
1481
+ }
1482
+ async function restoreAfterCompaction(sessionId, session, checkpoint) {
1276
1483
  const parts = ["Your context was just compacted. In case the summary lost any of it, this is what ALP holds of your work now."];
1277
1484
  if (session.parent && session.brief) parts.push(`Your assignment from ${session.parentAgent ?? "your requester"}, as it was given:
1278
1485
  ${cut(session.brief, BRIEF_CHARS)}`);
@@ -1283,7 +1490,7 @@ ${cut(session.brief, BRIEF_CHARS)}`);
1283
1490
  if (session.worktrees.size) {
1284
1491
  parts.push("Finished worktree changes waiting for alp_merge or alp_discard:\n" + [...session.worktrees].map(([id, change]) => `- ${id}: ${change.agent}${change.taskId ? ` on ${change.taskId}` : ""}`).join("\n"));
1285
1492
  }
1286
- const asked = [...userQuestions.values()].filter((pending) => pending.question.sessionId === sessionId);
1493
+ const asked = [...userQuestions.values()].filter((pending) => pending.question.sessionId === sessionId && !pending.gate);
1287
1494
  if (asked.length) parts.push("Waiting for the user to answer:\n" + asked.map((pending) => `- ${clip(pending.question.body, 300)}`).join("\n"));
1288
1495
  if (!session.parent) {
1289
1496
  const project = session.mapping.agent.projectRoot;
@@ -1292,6 +1499,8 @@ ${cut(session.brief, BRIEF_CHARS)}`);
1292
1499
  const board = renderBoard(await boardOf(project));
1293
1500
  if (board) parts.push(board);
1294
1501
  }
1502
+ if (checkpoint) parts.push(`The checkpoint you wrote before the compaction, by skill compact:
1503
+ ${cut(checkpoint, BRIEF_CHARS)}`);
1295
1504
  parts.push("Carry on where you were; alp_board and alp_task tell you more.");
1296
1505
  if (session.closed) return;
1297
1506
  post(sessionId, { kind: "note", from: "alp", assignment: sessionId, body: parts.join("\n\n"), ...session.active ? {} : { passive: true } });
@@ -1362,7 +1571,7 @@ ${cut(session.brief, BRIEF_CHARS)}`);
1362
1571
  return [path.join(mapping.agent.projectRoot, ".alp", LESSONS_FILE), ...options.libraryDir ? [path.join(options.libraryDir, LESSONS_FILE)] : []];
1363
1572
  }
1364
1573
  async function confirm(sessionId, session, body, approval) {
1365
- if ([...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId)) return { approved: false, outcome: "busy", feedback: "A question is already waiting for the user" };
1574
+ if ([...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId && !pending.gate)) return { approved: false, outcome: "busy", feedback: "A question is already waiting for the user" };
1366
1575
  const say = wordsFor(session);
1367
1576
  const result = await askUser(sessionId, session, void 0, body, [say.approve, say.reject], approval);
1368
1577
  let value;
@@ -1427,7 +1636,7 @@ ${args.body.trim()}
1427
1636
  return toolResult(false, { error: errorData(error).message });
1428
1637
  }
1429
1638
  if (approvalCanceled(session, cancellation)) return toolResult(false, { error: "Skill proposal canceled or session closed; no approval was created" });
1430
- if ([...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId)) return toolResult(false, { error: "A question is already waiting for the user; finish it before proposing a skill" });
1639
+ if ([...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId && !pending.gate)) return toolResult(false, { error: "A question is already waiting for the user; finish it before proposing a skill" });
1431
1640
  const approvalId = `q-${randomUUID()}`;
1432
1641
  const record2 = { approvalId, draftKey };
1433
1642
  approvals.set(key, record2);
@@ -1496,6 +1705,139 @@ ${content}`,
1496
1705
  return toolResult(true, { status: "pending_approval", approvalId, file, next: "Continue other work or end your turn. ALP sends the user's decision, and whether the skill was saved, by mail; do not resubmit this draft." });
1497
1706
  }
1498
1707
  let scheduleHandler;
1708
+ async function lessonCurateTool(sessionId, session, args) {
1709
+ const cancellation = approvalCancellation.get(session) ?? 0;
1710
+ args = structuredClone(args);
1711
+ const validChange = (change) => plainObject(change, ["scope", "remove", "add", "reason"]) && ["project", "user"].includes(change.scope) && Array.isArray(change.remove) && change.remove.length > 0 && change.remove.length <= 50 && change.remove.every((lesson) => text(lesson, LESSON_CHARS)) && (change.add === void 0 || text(change.add, LESSON_CHARS)) && (change.reason === void 0 || typeof change.reason === "string" && change.reason.length <= 300);
1712
+ if (!plainObject(args, ["changes", "requestId"]) || !Array.isArray(args.changes) || !args.changes.length || args.changes.length > 50 || !args.changes.every(validChange)) {
1713
+ return toolResult(false, { error: `changes needs 1 to 50 entries, each with scope (project or user), remove (the exact text of 1 to 50 lessons) and optionally add (one rule of at most ${LESSON_CHARS} characters) and reason` });
1714
+ }
1715
+ if (args.requestId !== void 0 && !text(args.requestId, 100)) return toolResult(false, { error: "requestId must be a nonempty string of at most 100 characters" });
1716
+ const changes = args.changes;
1717
+ if (changes.some((change) => change.scope === "user") && !options.libraryDir) return toolResult(false, { error: "This host keeps no user lessons" });
1718
+ const fileOf = (scope) => scope === "user" ? path.join(options.libraryDir, LESSONS_FILE) : path.join(session.mapping.agent.projectRoot, ".alp", LESSONS_FILE);
1719
+ const normalizeLesson = (lesson) => lesson.replace(/\s+/g, " ").trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, "").trim();
1720
+ const normalized = changes.map((change) => ({ ...change, remove: [...new Set(change.remove.map(normalizeLesson))], add: change.add?.replace(/\s+/g, " ").trim() }));
1721
+ const draftKey = JSON.stringify(["lessons", normalized]);
1722
+ const key = `lessons:${args.requestId ?? draftKey}`;
1723
+ const approvals = approvalsOf(sessionId);
1724
+ const previous = approvals.get(key);
1725
+ if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: "requestId was already used for a different draft" });
1726
+ if (previous) return toolResult(true, previous.result ?? { status: "pending_approval", approvalId: previous.approvalId });
1727
+ const readLessons = async (file) => (await readFile(file, "utf8").catch(() => "")).split("\n").flatMap((line) => /^- \d{4}-\d\d-\d\d: /.test(line) ? [normalizeLesson(line)] : []);
1728
+ const missing = [];
1729
+ for (const change of normalized) {
1730
+ const recorded = new Set(await readLessons(fileOf(change.scope)));
1731
+ for (const lesson of change.remove) if (!recorded.has(lesson)) missing.push(`${change.scope}: ${lesson}`);
1732
+ }
1733
+ if (missing.length) return toolResult(false, { error: "These lessons are not recorded; copy their exact text from the lessons files", missing });
1734
+ if (approvalCanceled(session, cancellation)) return toolResult(false, { error: "Lesson proposal canceled or session closed; no approval was created" });
1735
+ if ([...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId && !pending.gate)) return toolResult(false, { error: "A question is already waiting for the user; finish it before proposing lesson changes" });
1736
+ const approvalId = `q-${randomUUID()}`;
1737
+ const record2 = { approvalId, draftKey };
1738
+ approvals.set(key, record2);
1739
+ const say = wordsFor(session);
1740
+ const shown = normalized.map((change, index) => `${index + 1}. ${say.lessonScope(change.scope, fileOf(change.scope))}${change.reason ? ` \u2014 ${change.reason}` : ""}
1741
+ ` + change.remove.map((lesson) => ` ${say.lessonRemove}: ${lesson}`).join("\n") + (change.add ? `
1742
+ ${say.lessonAdd}: ${change.add}` : "")).join("\n\n");
1743
+ const decision = confirm(sessionId, session, `${say.lessonCurate(session.mapping.agent.name, shown)}
1744
+
1745
+ ${say.answerLine(session.mapping.agent.name)}`, { id: approvalId });
1746
+ const apply = async () => {
1747
+ const removed = [];
1748
+ const notFound = [];
1749
+ let added = 0;
1750
+ for (const scope of ["project", "user"]) {
1751
+ const mine = normalized.filter((change) => change.scope === scope);
1752
+ if (!mine.length) continue;
1753
+ const file = fileOf(scope);
1754
+ const write = (lessonWrites.get(file) ?? Promise.resolve()).catch(() => {
1755
+ }).then(async () => {
1756
+ const current = await readFile(file, "utf8").catch(() => void 0);
1757
+ if (current === void 0) {
1758
+ for (const change of mine) notFound.push(...change.remove.map((lesson) => `${scope}: ${lesson}`));
1759
+ return;
1760
+ }
1761
+ const targets = new Set(mine.flatMap((change) => change.remove));
1762
+ const seen = /* @__PURE__ */ new Set();
1763
+ const kept = current.split("\n").filter((line) => {
1764
+ if (!/^- \d{4}-\d\d-\d\d: /.test(line)) return true;
1765
+ const lesson = normalizeLesson(line);
1766
+ if (!targets.has(lesson)) return true;
1767
+ seen.add(lesson);
1768
+ return false;
1769
+ });
1770
+ for (const lesson of targets) (seen.has(lesson) ? removed : notFound).push(`${scope}: ${lesson}`);
1771
+ const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1772
+ const additions = mine.filter((change) => change.add && change.remove.some((lesson) => seen.has(lesson))).map((change) => `- ${date}: ${change.add}`);
1773
+ added += additions.length;
1774
+ let body = kept.join("\n");
1775
+ if (additions.length) body = body.replace(/\n*$/, "\n") + additions.join("\n") + "\n";
1776
+ await writeFile(file, body);
1777
+ });
1778
+ lessonWrites.set(file, write);
1779
+ await write;
1780
+ }
1781
+ runLog(rootOf(sessionId), { event: "lesson.curate", agent: session.mapping.agent.name, removed, added, notFound });
1782
+ return { approved: true, applied: true, removed, added, ...notFound.length ? { lessonsNotFound: notFound } : {} };
1783
+ };
1784
+ void (async () => {
1785
+ const answer = await decision;
1786
+ const canceled = approvalCanceled(session, cancellation);
1787
+ let result;
1788
+ if (!answer.approved || canceled) result = { approved: false, applied: false, outcome: canceled ? "canceled" : answer.outcome, ...answer.feedback ? { feedback: answer.feedback } : {}, next: "Nothing changed. Revise from the feedback and propose again with a fresh requestId, or drop it." };
1789
+ else {
1790
+ try {
1791
+ result = await apply();
1792
+ } catch (error) {
1793
+ result = { approved: true, applied: false, error: errorData(error).message, next: "Tell the user; nothing is retried automatically." };
1794
+ }
1795
+ }
1796
+ record2.result = { status: "resolved", approvalId, ...result };
1797
+ runLog(rootOf(sessionId), { event: "lesson.curate.approval", agent: session.mapping.agent.name, ...record2.result });
1798
+ if (!closed && !session.closed && sessions.get(sessionId) === session) post(sessionId, { kind: "result", from: "ALP", assignment: approvalId, body: `Lesson curate result: ${JSON.stringify(record2.result)}` });
1799
+ })();
1800
+ return toolResult(true, { status: "pending_approval", approvalId, next: "Continue other work or end your turn. ALP sends the decision and what changed by mail; do not resubmit this draft." });
1801
+ }
1802
+ const curateSchedules = /* @__PURE__ */ new Map();
1803
+ function ensureCurateSchedule(sessionId) {
1804
+ const root = sessions.get(sessionId);
1805
+ if (!scheduleHandler || !root || root.closed || root.parent) return Promise.resolve();
1806
+ const project = root.mapping.agent.projectRoot;
1807
+ const run = (curateSchedules.get(project) ?? Promise.resolve()).catch(() => {
1808
+ }).then(() => curateScheduleOf(sessionId, root, project));
1809
+ curateSchedules.set(project, run);
1810
+ void run.catch(() => {
1811
+ }).then(() => {
1812
+ if (curateSchedules.get(project) === run) curateSchedules.delete(project);
1813
+ });
1814
+ return run;
1815
+ }
1816
+ async function curateScheduleOf(sessionId, root, project) {
1817
+ const handler = scheduleHandler;
1818
+ if (!handler || root.closed || sessions.get(sessionId) !== root) return;
1819
+ for (const file of [path.join(project, ".alp", "settings.json"), ...options.libraryDir ? [path.join(options.libraryDir, "settings.json")] : []]) {
1820
+ const settings = await readFile(file, "utf8").then((raw) => {
1821
+ try {
1822
+ return JSON.parse(raw);
1823
+ } catch {
1824
+ return void 0;
1825
+ }
1826
+ }, () => void 0);
1827
+ const monthly = settings?.curate?.monthly;
1828
+ if (monthly === false) return;
1829
+ if (monthly === true) break;
1830
+ }
1831
+ const listed = await handler("list", { projectRoot: project, status: "pending" });
1832
+ const curate = (listed?.jobs ?? []).filter((job) => job.prompt.startsWith(CURATE_MARKER));
1833
+ if (curate.some((job) => job.sessionId === sessionId)) return;
1834
+ for (const job of curate) await handler("cancel", { id: job.id, projectRoot: project }).catch(() => {
1835
+ });
1836
+ const now = /* @__PURE__ */ new Date();
1837
+ const dueAt = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 2)).toISOString();
1838
+ await handler("create", { projectRoot: project, sessionId, dueAt, prompt: CURATE_PROMPT, keepsSession: false });
1839
+ runLog(sessionId, { event: "curate.scheduled", dueAt, replaced: curate.map((job) => job.id) });
1840
+ }
1499
1841
  async function scheduleTool(sessionId, session, args) {
1500
1842
  if (session.parent || session.role === "supervisor" || session.mapping.agent.name !== mainOf(session.mapping)) return toolResult(false, { error: "Only the main root session schedules continuations" });
1501
1843
  if (!scheduleHandler) return toolResult(false, { error: "This host does not support scheduled continuations" });
@@ -1600,7 +1942,7 @@ ${args.prompt}`,
1600
1942
  const previous = approvals.get(key);
1601
1943
  if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: "requestId was already used for a different draft" });
1602
1944
  if (previous) return toolResult(true, previous.result ?? { status: "pending_approval", approvalId: previous.approvalId, repo });
1603
- if ([...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId)) return toolResult(false, { error: "A question is already waiting for the user; finish it before proposing another issue draft" });
1945
+ if ([...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId && !pending.gate)) return toolResult(false, { error: "A question is already waiting for the user; finish it before proposing another issue draft" });
1604
1946
  const approvalId = `q-${randomUUID()}`;
1605
1947
  const record2 = { approvalId, draftKey };
1606
1948
  approvals.set(key, record2);
@@ -1688,7 +2030,7 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1688
2030
  if (session.pending) {
1689
2031
  void session.acknowledged.then(() => deliver(sessionId, session));
1690
2032
  } else if (session.active) {
1691
- if (session.mail.some((event) => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
2033
+ if (!session.compacting && session.mail.some((event) => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
1692
2034
  } else if (!waking) {
1693
2035
  return;
1694
2036
  } else if (!session.wakeBlocked && session.wakeFailures < MAX_WAKES && (session.wakes < MAX_WAKES || session.mail.some((event) => !event.deliveredTurn && event.kind === "checkin"))) {
@@ -1918,7 +2260,18 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1918
2260
  if (assignment.worktree || writes(assignment.mode)) await assignmentResults.put({
1919
2261
  assignmentId: assignment.id,
1920
2262
  checkout: assignment.worktree?.checkout ?? assignment.writeCheckout ?? resultChild?.mapping.workdir ?? parent.mapping.workdir,
1921
- ...assignment.worktree ? { worktree: assignment.worktree.path } : {}
2263
+ ...assignment.worktree ? { worktree: assignment.worktree.path } : {},
2264
+ // Outside a worktree, the change stays in the checkout: keep its evidence until the requester resolves it.
2265
+ ...!assignment.worktree ? { result: {
2266
+ agent: assignment.agent,
2267
+ status: state,
2268
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
2269
+ project: (resultChild ?? parent).mapping.agent.projectRoot,
2270
+ requesters: lineage(parentId),
2271
+ ...assignment.taskId ? { taskId: assignment.taskId } : {},
2272
+ brief: cut(resultChild?.brief ?? "", RESULT_EVIDENCE_CHARS),
2273
+ summary: cut(JSON.stringify({ handoff: resultChild?.handoff ?? null, output: resultChild ? [...resultChild.text.values()].at(-1) ?? "" : "", ...error ? { error: errorData(error).message } : {} }), RESULT_EVIDENCE_CHARS)
2274
+ } } : {}
1922
2275
  });
1923
2276
  } catch (failure) {
1924
2277
  assignment.finished = false;
@@ -2008,7 +2361,7 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
2008
2361
  error: "ALP tools require the current active turn"
2009
2362
  });
2010
2363
  }
2011
- if (!["alp_delegate", "alp_handoff", "alp_wait", "alp_cancel", "alp_send", "alp_ask", "alp_merge", "alp_discard", "alp_recall", "alp_verify", "alp_pin", "alp_board", "alp_unpin", "alp_lesson", "alp_skill", "alp_issue", "alp_task", "alp_schedule"].includes(params.tool) || params.namespace != null || typeof params.callId !== "string") {
2364
+ if (!["alp_delegate", "alp_handoff", "alp_wait", "alp_cancel", "alp_send", "alp_ask", "alp_merge", "alp_discard", "alp_resolve", "alp_recall", "alp_verify", "alp_pin", "alp_board", "alp_unpin", "alp_lesson", "alp_lesson_curate", "alp_skill", "alp_issue", "alp_task", "alp_schedule"].includes(params.tool) || params.namespace != null || typeof params.callId !== "string") {
2012
2365
  return toolResult(false, {
2013
2366
  error: "Unknown ALP tool"
2014
2367
  });
@@ -2016,10 +2369,12 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
2016
2369
  const cached = session.toolCalls.get(params.callId);
2017
2370
  if (cached) return cached;
2018
2371
  const args = params.arguments;
2372
+ const oversized = inputLimitError(args, TOOL_INPUT, `${params.tool} input`);
2373
+ if (oversized) return toolResult(false, { error: oversized });
2019
2374
  if (session.role === "supervisor" && !["alp_send", "alp_board", "alp_task"].includes(params.tool)) return toolResult(false, { error: "The supervisor only uses alp_send, alp_board and alp_task" });
2020
- if ((params.tool === "alp_lesson" || params.tool === "alp_skill") && !supervises(session)) return toolResult(false, { error: "Only a supervised main records lessons and skills" });
2375
+ if (["alp_lesson", "alp_lesson_curate", "alp_skill"].includes(params.tool) && !supervises(session)) return toolResult(false, { error: "Only a supervised main records lessons and skills" });
2021
2376
  if (params.tool === "alp_issue" && (session.parent || session.mapping.agent.name !== mainOf(session.mapping))) return toolResult(false, { error: "Only main files issues; report the problem to your requester" });
2022
- const work = params.tool === "alp_lesson" ? lessonTool(sessionId, session, args) : params.tool === "alp_skill" ? skillTool(sessionId, session, args) : params.tool === "alp_issue" ? issueTool(sessionId, session, args) : params.tool === "alp_schedule" ? scheduleTool(sessionId, session, args) : params.tool === "alp_task" ? taskToolCall(sessionId, session, args) : params.tool === "alp_delegate" ? runDelegation(sessionId, session, params) : params.tool === "alp_wait" ? waitTool(sessionId, session, args) : params.tool === "alp_ask" ? askTool(sessionId, session, args) : params.tool === "alp_pin" ? pinTool(sessionId, session, args) : params.tool === "alp_board" ? boardTool(session, args) : params.tool === "alp_unpin" ? unpinTool(sessionId, session, args) : params.tool === "alp_recall" ? recallTool(sessionId, session, args) : params.tool === "alp_verify" ? verifyTool(sessionId, session, args) : params.tool === "alp_cancel" ? cancelTool(sessionId, session, args) : params.tool === "alp_merge" || params.tool === "alp_discard" ? worktreeTool(sessionId, session, args, params.tool === "alp_merge" ? "merge" : "discard") : params.tool === "alp_send" ? Promise.resolve(sendTool(sessionId, session, args)) : hookedHandoff(sessionId, session, args);
2377
+ const work = params.tool === "alp_lesson" ? lessonTool(sessionId, session, args) : params.tool === "alp_lesson_curate" ? lessonCurateTool(sessionId, session, args) : params.tool === "alp_skill" ? skillTool(sessionId, session, args) : params.tool === "alp_issue" ? issueTool(sessionId, session, args) : params.tool === "alp_schedule" ? scheduleTool(sessionId, session, args) : params.tool === "alp_task" ? taskToolCall(sessionId, session, args) : params.tool === "alp_delegate" ? runDelegation(sessionId, session, params) : params.tool === "alp_wait" ? waitTool(sessionId, session, args) : params.tool === "alp_ask" ? askTool(sessionId, session, args) : params.tool === "alp_pin" ? pinTool(sessionId, session, args) : params.tool === "alp_board" ? boardTool(session, args) : params.tool === "alp_unpin" ? unpinTool(sessionId, session, args) : params.tool === "alp_recall" ? recallTool(sessionId, session, args) : params.tool === "alp_resolve" ? resolveTool(sessionId, session, args) : params.tool === "alp_verify" ? verifyTool(sessionId, session, args) : params.tool === "alp_cancel" ? cancelTool(sessionId, session, args) : params.tool === "alp_merge" || params.tool === "alp_discard" ? worktreeTool(sessionId, session, args, params.tool === "alp_merge" ? "merge" : "discard") : params.tool === "alp_send" ? Promise.resolve(sendTool(sessionId, session, args)) : hookedHandoff(sessionId, session, args);
2023
2378
  const reminded = !session.parent && params.tool !== "alp_ask" ? work.then((result) => remindUser(session, result)) : work;
2024
2379
  session.toolCalls.set(params.callId, reminded);
2025
2380
  return reminded;
@@ -2160,10 +2515,126 @@ The user answered: "${answer}"`);
2160
2515
  post(session.parent, { kind: "note", from: session.mapping.agent.name, assignment: sessionId, body: `[ALP, on behalf of ${session.mapping.agent.name}] ${body}` });
2161
2516
  }
2162
2517
  function cancelQuestions(sessionId, turnOnly = false) {
2163
- for (const { question, settle, persistent } of [...userQuestions.values()]) {
2518
+ for (const { question, settle, persistent, gate } of [...userQuestions.values()]) {
2519
+ if (gate && turnOnly) continue;
2164
2520
  if (question.sessionId === sessionId && (!turnOnly || !persistent)) settle("canceled", void 0, void 0, toolResult(false, { error: "Turn ended" }));
2165
2521
  }
2166
2522
  }
2523
+ const gateSyncs = /* @__PURE__ */ new Map();
2524
+ const gateCardId = (taskId, gateId) => `gate-${taskId}-${gateId}`;
2525
+ function mainSessionOf(projectRoot) {
2526
+ for (const [id, session] of sessions) {
2527
+ if (session.closed || session.parent || session.role === "supervisor" || !session.threadId) continue;
2528
+ if (session.mapping.agent.name !== mainOf(session.mapping) || path.resolve(session.mapping.agent.projectRoot) !== projectRoot) continue;
2529
+ return { id, session };
2530
+ }
2531
+ return void 0;
2532
+ }
2533
+ function syncGates(projectRoot) {
2534
+ const root = path.resolve(projectRoot);
2535
+ const previous = gateSyncs.get(root) ?? Promise.resolve();
2536
+ const next = previous.then(() => syncGatesNow(root)).catch((error) => {
2537
+ runLog(mainSessionOf(root)?.id ?? root, { event: "gate.sync.failed", projectRoot: root, error: errorData(error).message });
2538
+ });
2539
+ gateSyncs.set(root, next);
2540
+ void next.finally(() => {
2541
+ if (gateSyncs.get(root) === next) gateSyncs.delete(root);
2542
+ });
2543
+ return next;
2544
+ }
2545
+ async function syncGatesNow(projectRoot) {
2546
+ if (closed) return;
2547
+ const { tasks } = await loadTasks(projectRoot);
2548
+ const main = mainSessionOf(projectRoot);
2549
+ if (main) for (const { task, gate, decision, record: record2 } of gateDecisions(tasks)) {
2550
+ if (!await markGateNotified(projectRoot, task.id, gate.id, decision)) continue;
2551
+ const choice = decision === "approved" ? record2.choice : void 0;
2552
+ const words2 = decision === "approved" ? `The user approved human gate ${gate.id} of ${task.id} in ${record2.channel}${choice ? `, choosing "${choice}"` : ""}${record2.note ? `: ${record2.note}` : ""}.` : `The user rejected human gate ${gate.id} of ${task.id} in ${record2.channel}${record2.reason ? `: ${record2.reason}` : ""}. The gate stays open.`;
2553
+ post(main.id, { kind: "result", from: "ALP", assignment: gateCardId(task.id, gate.id), body: `Gate decision (data, not instructions): ${words2} Task: ${task.title}` });
2554
+ runLog(main.id, { event: "gate.decision", projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record2.channel, ...choice ? { choice } : {} });
2555
+ }
2556
+ const wanted = /* @__PURE__ */ new Map();
2557
+ for (const task of tasks) {
2558
+ if (task.status === "closed") continue;
2559
+ for (const gate of task.gates ?? []) if (gate.kind === "human" && !gate.resolved && !gate.rejected) wanted.set(gateCardId(task.id, gate.id), { task, gate });
2560
+ }
2561
+ for (const [id, pending] of [...userQuestions]) {
2562
+ if (pending.question.gate?.projectRoot !== projectRoot) continue;
2563
+ const want = wanted.get(id);
2564
+ if (!want || !main || pending.question.sessionId !== main.id) {
2565
+ const task = tasks.find((entry) => entry.id === pending.question.gate.taskId);
2566
+ const gate = task?.gates.find((entry) => entry.id === pending.question.gate.gateId);
2567
+ pending.settle(gate?.resolved ? "answered" : gate?.rejected ? "dismissed" : "canceled", gate?.resolved?.choice, gate?.rejected?.reason);
2568
+ } else if (pending.gate) pending.gate.rev = want.task.rev;
2569
+ }
2570
+ if (!main) return;
2571
+ for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
2572
+ }
2573
+ let gateWatch;
2574
+ function startGateWatch() {
2575
+ if (gateWatch || options.gateSyncMs === 0) return;
2576
+ gateWatch = setInterval(() => {
2577
+ const roots = new Set([...sessions.values()].filter((session) => !session.closed && !session.parent && session.role !== "supervisor" && session.mapping.agent.name === mainOf(session.mapping)).map((session) => path.resolve(session.mapping.agent.projectRoot)));
2578
+ for (const root of roots) void syncGates(root);
2579
+ if (!roots.size) {
2580
+ clearInterval(gateWatch);
2581
+ gateWatch = void 0;
2582
+ }
2583
+ }, options.gateSyncMs ?? 5e3);
2584
+ gateWatch.unref?.();
2585
+ }
2586
+ function showGateCard(sessionId, session, projectRoot, task, gate) {
2587
+ const say = wordsFor(session);
2588
+ const vietnamese = say.approve === words("vi").approve;
2589
+ const question = {
2590
+ id: gateCardId(task.id, gate.id),
2591
+ sessionId,
2592
+ rootId: rootOf(sessionId),
2593
+ agent: "ALP",
2594
+ body: `${vietnamese ? `C\u1ED5ng ph\xEA duy\u1EC7t ${gate.id} c\u1EE7a ${task.id}` : `Approval gate ${gate.id} of ${task.id}`} (${task.title}):
2595
+ ${gate.note ?? ""}`,
2596
+ // Options approve; Reject (added after them unless one of them is that word) keeps the gate open.
2597
+ options: gate.options?.length ? gate.options.includes(say.reject) ? gate.options : [...gate.options, say.reject] : [say.approve, say.reject],
2598
+ askedAt: gate.at ?? (/* @__PURE__ */ new Date()).toISOString(),
2599
+ gate: { projectRoot, taskId: task.id, gateId: gate.id }
2600
+ };
2601
+ const card = { rev: task.rev, deciding: false };
2602
+ const settle = (outcome, answer) => {
2603
+ if (userQuestions.get(question.id)?.question !== question) return;
2604
+ userQuestions.delete(question.id);
2605
+ emit(sessionId, { type: "question.resolved", questionId: question.id, outcome, ...answer !== void 0 ? { answer } : {} });
2606
+ };
2607
+ userQuestions.set(question.id, { question, settle, persistent: true, gate: Object.assign(card, { decide: (reply) => decideGate(projectRoot, question, card, reply, gate.options?.length ? gate.options : void 0) }) });
2608
+ emit(sessionId, { type: "question", question });
2609
+ runLog(rootOf(sessionId), { event: "gate.card", questionId: question.id, taskId: task.id, gateId: gate.id });
2610
+ }
2611
+ async function decideGate(projectRoot, question, card, reply, choices) {
2612
+ const defaults = !choices;
2613
+ if (card.deciding) return;
2614
+ card.deciding = true;
2615
+ const { taskId, gateId } = question.gate;
2616
+ const channel = reply.channel ?? "web";
2617
+ const text2 = reply.text?.trim();
2618
+ const approve2 = !reply.dismiss && !!text2 && (defaults ? APPROVALS.includes(text2.toLowerCase()) : choices.includes(text2));
2619
+ const rejectReason = reply.dismiss ? reply.reason : text2 && CHOICES_REJECT.includes(text2.toLowerCase()) ? void 0 : text2;
2620
+ const write = (ifRev) => approve2 ? resolveGate(projectRoot, taskId, gateId, { by: "user", ifRev, channel, ...defaults ? {} : { choice: text2 } }) : rejectGate(projectRoot, taskId, gateId, { by: "user", ifRev, channel, ...rejectReason ? { reason: rejectReason.slice(0, 2e3) } : {} });
2621
+ try {
2622
+ try {
2623
+ await write(card.rev);
2624
+ } catch (error) {
2625
+ if (error?.code !== "TASK_CHANGED") throw error;
2626
+ const current = (await loadTasks(projectRoot)).tasks.find((entry) => entry.id === taskId);
2627
+ const gate = current?.gates.find((entry) => entry.id === gateId);
2628
+ if (!current || current.status === "closed" || !gate || gate.resolved || gate.rejected) return;
2629
+ await write(current.rev);
2630
+ }
2631
+ } catch (error) {
2632
+ runLog(question.rootId, { event: "gate.answer.failed", questionId: question.id, error: errorData(error).message });
2633
+ } finally {
2634
+ card.deciding = false;
2635
+ await syncGates(projectRoot);
2636
+ }
2637
+ }
2167
2638
  function askTool(sessionId, session, args) {
2168
2639
  const parent = session.parent ? sessions.get(session.parent) : void 0;
2169
2640
  const assignment = parent?.assignments.get(sessionId);
@@ -2175,7 +2646,7 @@ The user answered: "${answer}"`);
2175
2646
  if (args.options !== void 0 && (to !== "user" || !Array.isArray(args.options) || args.options.length > 10 || !args.options.every((option) => typeof option === "string" && option.trim() && option.length <= 200))) {
2176
2647
  return Promise.resolve(toolResult(false, { error: "options are up to 10 short answers, for questions to the user" }));
2177
2648
  }
2178
- if (assignment?.ask || [...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId)) {
2649
+ if (assignment?.ask || [...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId && !pending.gate)) {
2179
2650
  return Promise.resolve(toolResult(false, { error: "A question is already waiting for an answer" }));
2180
2651
  }
2181
2652
  if (to === "user" && session.parent && !session.userOpened) {
@@ -2624,6 +3095,11 @@ ${digest}` : "")
2624
3095
  };
2625
3096
  if (assignment) assignmentSessions.set(assignment, session);
2626
3097
  const finishPending = beginPending(session);
3098
+ const opening = {};
3099
+ openings.set(session, opening);
3100
+ const failedMeanwhile = () => {
3101
+ if (opening.failure !== void 0) throw opening.failure;
3102
+ };
2627
3103
  sessions.set(
2628
3104
  sessionId,
2629
3105
  session
@@ -2631,6 +3107,7 @@ ${digest}` : "")
2631
3107
  wire(sessionId, session, runtime);
2632
3108
  try {
2633
3109
  await runtime.initialize();
3110
+ failedMeanwhile();
2634
3111
  if (session.closed || sessions.get(sessionId) !== session) {
2635
3112
  throw new Error(
2636
3113
  "Session closed during initialization"
@@ -2666,11 +3143,13 @@ ${digest}` : "")
2666
3143
  }
2667
3144
  );
2668
3145
  session.threadId = result.thread.id;
3146
+ failedMeanwhile();
2669
3147
  if (session.closed || sessions.get(sessionId) !== session) {
2670
3148
  throw new Error(
2671
3149
  "Session closed during thread creation"
2672
3150
  );
2673
3151
  }
3152
+ openings.delete(session);
2674
3153
  session.buffered = [];
2675
3154
  finishPending();
2676
3155
  openedSessions.add(session);
@@ -2683,6 +3162,10 @@ ${digest}` : "")
2683
3162
  thinking: result.reasoningEffort ?? mapping.thinking
2684
3163
  }
2685
3164
  });
3165
+ if (!session.parent && session.role !== "supervisor" && mapping.agent.name === mainOf(mapping)) {
3166
+ void syncGates(mapping.agent.projectRoot);
3167
+ startGateWatch();
3168
+ }
2686
3169
  if (history === "replay") {
2687
3170
  for (const turn of result.thread.turns ?? []) {
2688
3171
  for (const item of turn.items ?? []) {
@@ -2699,6 +3182,9 @@ ${digest}` : "")
2699
3182
  return snapshot(sessionId, session);
2700
3183
  } catch (error) {
2701
3184
  log.error(`${session.mapping.agent.name} could not start its ${session.runtimeKind} session`, { code: "ALP_PROVIDER_START_FAILED", sessionId, rootId: rootOf(sessionId), agent: session.mapping.agent.name, provider: session.runtimeKind, error });
3185
+ const failed = openings.get(session);
3186
+ openings.delete(session);
3187
+ if (failed?.failure !== void 0) failSession(sessionId, session, failed.failure);
2702
3188
  const cleanup = closeSession(sessionId, session, false);
2703
3189
  finishPending();
2704
3190
  await cleanup;
@@ -2722,6 +3208,11 @@ ${digest}` : "")
2722
3208
  });
2723
3209
  transport.onFailure((error) => {
2724
3210
  if (session.closed || session.runtime !== transport || sessions.get(sessionId) !== session) return;
3211
+ const opening = openings.get(session);
3212
+ if (opening) {
3213
+ opening.failure ??= error;
3214
+ return;
3215
+ }
2725
3216
  if (revivable(session)) void revive(sessionId, session, error);
2726
3217
  else failSession(sessionId, session, error);
2727
3218
  });
@@ -2832,10 +3323,10 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2832
3323
  if (session.pending) return "The session is still opening or restarting";
2833
3324
  if (session.active) return "A turn is running";
2834
3325
  if (session.children.size || session.assignments.size) return "Assignments are still running";
2835
- if ([...userQuestions.values()].some((pending) => pending.question.rootId === sessionId)) return "A question to the user waits for an answer";
2836
- if ((hasActiveMail(session) || session.wakeHeld) && !session.lifecycleHolds) return "Mail waits for the session";
3326
+ if ([...userQuestions.values()].some((pending) => pending.question.rootId === sessionId && !pending.gate)) return "A question to the user waits for an answer";
3327
+ if ((hasActiveMail(session) || session.wakeHeld) && !session.lifecycleHolds) return MAIL_WAITS;
2837
3328
  if (session.parked || session.parkReason) return "The session is parked";
2838
- if (reviewing(session)) return "The supervisor is reviewing the session";
3329
+ if (reviewing(session)) return REVIEWING;
2839
3330
  return void 0;
2840
3331
  }
2841
3332
  async function restartNative(sessionId, session, binding, verify = true, shape) {
@@ -2995,7 +3486,6 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2995
3486
  if (teamChanged && agent === mainOf(session.mapping) && agent !== mainOf(mapping)) return refused("agent_mismatch", `Team ${mapping.team?.label ?? team}'s main agent is ${mainOf(mapping)}, not ${agent}; start a new session with that team`);
2996
3487
  if (changes.mode !== void 0 && mapping.mode !== changes.mode) return refused("permission_escalation", READ_ONLY_AGENTS.includes(agent) ? "Advisors and the supervisor must remain read-only" : `Permission profile ${mapping.permissions?.name ?? ""} allows at most ${mapping.permissions?.base ?? mapping.mode}`.replace("profile allows", "profile allows"));
2997
3488
  if (changes.mode === void 0 && !withinMode(mapping.mode, session.mapping.mode)) return refused("permission_escalation", `The change would run the session in ${mapping.mode}, beyond its ${session.mapping.mode}`);
2998
- if (runtimeKind === "antigravity" && mapping.mode !== session.mapping.mode) return refused("runtime_unsupported", "Antigravity sessions keep their mode");
2999
3489
  const before = executablesOf(session.mapping);
3000
3490
  const added = [...executablesOf(mapping)].filter((entry) => !before.has(entry));
3001
3491
  if (added.length) return refused("permission_escalation", `The change would give the session commands it did not run (${added.map((entry) => entry.split(":").slice(0, 2).join(" ")).join(", ")}); start a new session for it`);
@@ -3230,8 +3720,6 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3230
3720
  }
3231
3721
  if (assignment.copy) await removeCopy(assignment.copy).catch(() => {
3232
3722
  });
3233
- if (assignment.worktree) await removeWorktree(assignment.worktree).catch(() => {
3234
- });
3235
3723
  };
3236
3724
  try {
3237
3725
  if (entry.lease) {
@@ -3242,7 +3730,14 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3242
3730
  leases.set(entry.lease, { assignment: id, agent: entry.agent });
3243
3731
  }
3244
3732
  }
3245
- if (entry.worktree) assignment.worktree = await reattachWorktree(entry.worktree);
3733
+ if (entry.worktree) {
3734
+ const { preserved, ...worktree } = await reattachWorktree(entry.worktree);
3735
+ assignment.worktree = worktree;
3736
+ if (preserved) {
3737
+ runLog(entry.rootId, { event: "worktree.preserved", assignmentId: id, branch: worktree.branch, preserved });
3738
+ post(entry.parentId, { kind: "note", from: entry.agent, assignment: id, passive: true, body: `Reopening ${id}: its worktree ${worktree.path} had no valid git metadata after the restart, so it was moved aside unchanged to ${preserved} and ${worktree.branch} was checked out again. Recover any uncommitted work from ${preserved}.` });
3739
+ }
3740
+ }
3246
3741
  if (entry.copyOf) {
3247
3742
  assignment.copy = await createCopy(entry.copyOf, copyRoot, id);
3248
3743
  spec = { ...spec, workdir: assignment.copy.workdir };
@@ -3283,7 +3778,17 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3283
3778
  if (entry.worktree || writes(entry.mode)) await assignmentResults.put({
3284
3779
  assignmentId: entry.assignmentId,
3285
3780
  checkout: entry.worktree?.checkout ?? entry.lease ?? entry.spec.writeRoot ?? entry.spec.workdir ?? entry.project,
3286
- ...entry.worktree ? { worktree: entry.worktree.path } : {}
3781
+ ...entry.worktree ? { worktree: entry.worktree.path } : {},
3782
+ ...!entry.worktree ? { result: {
3783
+ agent: entry.agent,
3784
+ status: "abandoned",
3785
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
3786
+ project: entry.project,
3787
+ requesters: sessions.has(entry.parentId) ? lineage(entry.parentId) : [entry.parentId],
3788
+ ...entry.taskId ? { taskId: entry.taskId } : {},
3789
+ brief: cut(entry.brief ?? "", RESULT_EVIDENCE_CHARS),
3790
+ summary: cut(JSON.stringify({ reason }), RESULT_EVIDENCE_CHARS)
3791
+ } } : {}
3287
3792
  });
3288
3793
  await inFlight.remove(entry.assignmentId);
3289
3794
  const parent = sessions.get(entry.parentId);
@@ -3387,8 +3892,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3387
3892
  }
3388
3893
  const parent = session.parent ? sessions.get(session.parent) : void 0;
3389
3894
  if (parent && !withinMode(mode, parent.mapping.mode)) throw new Error("Child cannot exceed parent permissions");
3390
- if (session.runtimeKind === "antigravity" && mode !== session.mapping.mode) throw new Error("Antigravity uses full-access natively; its permission instructions are fixed for the session. Open a new session to change mode");
3391
- if (session.runtimeKind === "claude") await session.runtime.request("session/configure", { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
3895
+ if (session.runtimeKind === "claude" || session.runtimeKind === "antigravity") await session.runtime.request("session/configure", { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
3392
3896
  session.mapping.mode = mode;
3393
3897
  session.spec = { ...session.spec, mode };
3394
3898
  const updated = snapshot(sessionId, session);
@@ -3434,8 +3938,12 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3434
3938
  );
3435
3939
  }
3436
3940
  }
3437
- async function promptSession(sessionId, input) {
3941
+ async function promptSession(sessionId, input, flushing = false) {
3438
3942
  const session = sessions.get(sessionId);
3943
+ if (!flushing && session && !session.parent && (session.compacting || session.compactBuffer?.length)) {
3944
+ if (!session.seen.has(input.clientMessageId) && !session.compactBuffer?.some((held2) => held2.clientMessageId === input.clientMessageId)) (session.compactBuffer ??= []).push(input);
3945
+ return;
3946
+ }
3439
3947
  const parked = session?.parked;
3440
3948
  try {
3441
3949
  const prompt = session?.active && session.resumedTurn === session.active && input.delivery === "auto" ? { ...input, delivery: "steer" } : input;
@@ -3511,6 +4019,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3511
4019
  if (prompt.delivery !== "steer") {
3512
4020
  session.text.clear();
3513
4021
  session.toolCalls.clear();
4022
+ if (!/^alp-wake-compact-/.test(prompt.clientMessageId)) session.compactCooling = false;
3514
4023
  session.supervisorWake = !!wake?.length && wake.every((event) => event.defer);
3515
4024
  if (!wake) {
3516
4025
  session.handoff = void 0;
@@ -3522,6 +4031,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3522
4031
  }
3523
4032
  try {
3524
4033
  const orchestration = session.runtime.orchestrationContext ? await session.runtime.orchestrationContext().catch(() => ({ available: false })) : { available: false };
4034
+ feedCatalog(orchestration);
3525
4035
  const tasks = prompt.delivery !== "steer" && !session.parent && session.mapping.agent.name === mainOf(session.mapping) ? await releaseOrphansOnce(session.mapping.agent.projectRoot, sessionId).then(() => checkGatesOften(session.mapping.agent.projectRoot)).then(() => loadTasks(session.mapping.agent.projectRoot)).then(({ tasks: tasks2, errors }) => taskDigest(tasks2, errors), () => "") : "";
3526
4036
  const interrupted = prompt.delivery !== "steer" && !wake && session.threadId ? interruptedThreads.get(session.threadId) : void 0;
3527
4037
  if (interrupted) interruptedThreads.delete(session.threadId);
@@ -3588,6 +4098,7 @@ ${interrupted}`), text_elements: [] }] : []
3588
4098
  }
3589
4099
  });
3590
4100
  if (origin === "user" && !session.parent) session.userWaiting ??= Date.now();
4101
+ if (origin === "user" && !session.parent && text2) session.lastUserText = clip(text2, 16e3);
3591
4102
  if (session.supervisor && origin === "user") session.journal.push(stamp(`user ${prompt.delivery === "steer" ? "steered" : "asked"} ${session.mapping.agent.name}: ${clip(text2, 1500)}`));
3592
4103
  if (prompt.delivery === "steer" && origin === "user" && !session.parent) {
3593
4104
  releaseWaiters(session);
@@ -3619,7 +4130,7 @@ ${interrupted}`), text_elements: [] }] : []
3619
4130
  }
3620
4131
  }
3621
4132
  if (options.recallFile) void forgetExpired();
3622
- return {
4133
+ const api = {
3623
4134
  registerWorkspace: (directory) => enqueue(async () => {
3624
4135
  try {
3625
4136
  await assignmentResults.register(await realpath(directory));
@@ -3627,7 +4138,7 @@ ${interrupted}`), text_elements: [] }] : []
3627
4138
  refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot register workspace result ownership");
3628
4139
  }
3629
4140
  }),
3630
- withWorkspaceMutation: (directory, run) => {
4141
+ withWorkspaceMutation: (directory, run, adoption) => {
3631
4142
  if (workspaceMutation || admitting) return Promise.reject(new WorkspaceMutationError("workspace_busy", "A session or assignment is opening; retry after it finishes"));
3632
4143
  workspaceMutation = true;
3633
4144
  return enqueue(async () => {
@@ -3638,7 +4149,7 @@ ${interrupted}`), text_elements: [] }] : []
3638
4149
  } catch (error) {
3639
4150
  refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot inspect permanent assignment results");
3640
4151
  }
3641
- if (!resultLedger.workspaces.includes(target)) refuseMutation("workspace_assignment_result", "Workspace predates authoritative assignment tracking; an audited migration is required before removal");
4152
+ if (!resultLedger.workspaces.includes(target) && adoption !== ADOPTION) refuseMutation("workspace_assignment_result", "Workspace predates authoritative assignment tracking; an audited migration is required before removal");
3642
4153
  const canonical = (value) => {
3643
4154
  try {
3644
4155
  return realpathSync(value);
@@ -3660,7 +4171,15 @@ ${interrupted}`), text_elements: [] }] : []
3660
4171
  };
3661
4172
  return contains(target, owner) || contains(owner, target);
3662
4173
  };
3663
- for (const entry of resultLedger.results) if (overlaps(entry.checkout) || overlaps(entry.worktree)) refuseMutation("workspace_assignment_result", `Resolve permanent assignment result ${entry.assignmentId} before removing ${directory}`);
4174
+ for (const entry of resultLedger.results) if (!entry.handled && (overlaps(entry.checkout) || overlaps(entry.worktree))) refuseMutation("workspace_assignment_result", `Resolve permanent assignment result ${entry.assignmentId} before removing ${directory}`);
4175
+ const resolved = async (assignmentId) => {
4176
+ if (resultLedger.results.some((owner) => owner.assignmentId === assignmentId && owner.handled)) return true;
4177
+ try {
4178
+ return !!await assignmentResults.archived(assignmentId);
4179
+ } catch {
4180
+ return refuseMutation("workspace_assignment_result", "Cannot inspect the assignment result archive; repair it before removing the workspace");
4181
+ }
4182
+ };
3664
4183
  for (const [project, pins] of loadedBoards) for (const pin of pins) {
3665
4184
  if (pin.kind === "claim" && live(pin) && pin.paths?.some((value) => overlaps(path.resolve(project, value)))) refuseMutation("workspace_claimed", `Release claim ${pin.id} before removing ${directory}`);
3666
4185
  }
@@ -3692,15 +4211,24 @@ ${interrupted}`), text_elements: [] }] : []
3692
4211
  if (entry.worktree !== void 0 && (!entry.worktree || !["path", "checkout", "workdir"].every((key) => typeof entry.worktree[key] === "string"))) refuseMutation("workspace_assignment_result", `Invalid worktree result in ${file}`);
3693
4212
  if (entry.shared !== void 0 && (!entry.shared || typeof entry.shared !== "object" || Array.isArray(entry.shared))) refuseMutation("workspace_assignment_result", `Invalid shared result in ${file}`);
3694
4213
  if (kind === "live") checkLive(entry);
3695
- else if (overlaps(entry.cwd) || overlaps(entry.shared?.writeRoot)) refuseMutation("workspace_assignment_result", `Preserve retained assignment ${entry.assignmentId} before removing ${directory}`);
4214
+ else if ((overlaps(entry.cwd) || overlaps(entry.shared?.writeRoot)) && !await resolved(entry.assignmentId)) refuseMutation("workspace_assignment_result", `Preserve retained assignment ${entry.assignmentId} before removing ${directory}`);
3696
4215
  }
3697
4216
  }
3698
- for (const entry of await recalls.all()) if (overlaps(entry.cwd) || overlaps(entry.shared?.writeRoot)) refuseMutation("workspace_assignment_result", `Preserve retained assignment ${entry.assignmentId} before removing ${directory}`);
4217
+ for (const entry of await recalls.all()) if ((overlaps(entry.cwd) || overlaps(entry.shared?.writeRoot)) && !await resolved(entry.assignmentId)) refuseMutation("workspace_assignment_result", `Preserve retained assignment ${entry.assignmentId} before removing ${directory}`);
3699
4218
  return await run();
3700
4219
  }).finally(() => {
3701
4220
  workspaceMutation = false;
3702
4221
  });
3703
4222
  },
4223
+ adoptWorkspace: (directory, verify) => api.withWorkspaceMutation(directory, async () => {
4224
+ if (await realpath(directory) !== directory) refuseMutation("workspace_identity", `Adopt ${directory} by its canonical path`);
4225
+ await verify(directory);
4226
+ try {
4227
+ await assignmentResults.register(directory);
4228
+ } catch (error) {
4229
+ refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot register workspace result ownership");
4230
+ }
4231
+ }, ADOPTION),
3704
4232
  bindSchedules(handler) {
3705
4233
  scheduleHandler = handler;
3706
4234
  },
@@ -3723,7 +4251,10 @@ ${interrupted}`), text_elements: [] }] : []
3723
4251
  open: (sessionId, spec, { history = "skip", delegation = true } = {}) => enqueue(async () => {
3724
4252
  const opened = await openSession(sessionId, spec, history, delegation);
3725
4253
  const root = sessions.get(sessionId);
3726
- if (supervises(root)) void enqueue(() => openSupervisor(sessionId));
4254
+ if (supervises(root)) {
4255
+ void enqueue(() => openSupervisor(sessionId));
4256
+ void ensureCurateSchedule(sessionId).catch((error) => runLog(sessionId, { event: "curate.schedule.failed", error: errorData(error).message }));
4257
+ }
3727
4258
  return opened;
3728
4259
  }),
3729
4260
  prompt: (sessionId, input) => enqueue(() => promptSession(sessionId, input)),
@@ -3774,6 +4305,7 @@ ${interrupted}`), text_elements: [] }] : []
3774
4305
  branch: (request) => branchConversation(request),
3775
4306
  rebind: (sessionId, binding) => enqueue(() => rebindSession(sessionId, binding)),
3776
4307
  reload: (sessionId) => enqueue(() => reloadSession(sessionId)),
4308
+ compact: (sessionId) => requestCompact(sessionId),
3777
4309
  previewConfigure: (sessionId, changes) => previewConfigureSession(sessionId, changes),
3778
4310
  reconfigure: (sessionId, changes, options2) => enqueue(() => reconfigureSession(sessionId, changes, options2)),
3779
4311
  starting: (sessionId) => {
@@ -3823,7 +4355,7 @@ ${interrupted}`), text_elements: [] }] : []
3823
4355
  };
3824
4356
  visit(rootId);
3825
4357
  const questions = [...userQuestions.values()].map((pending) => pending.question).filter((question) => question.rootId === rootId);
3826
- const asking = new Set(questions.map((question) => question.sessionId));
4358
+ const asking = new Set(questions.filter((question) => !question.gate).map((question) => question.sessionId));
3827
4359
  const ids = new Set(tree.map(([id]) => id));
3828
4360
  return {
3829
4361
  rootId,
@@ -3875,6 +4407,21 @@ ${interrupted}`), text_elements: [] }] : []
3875
4407
  return pauseState();
3876
4408
  },
3877
4409
  pauses: () => pauseState(),
4410
+ holdForDisk(reason) {
4411
+ if (paused.all) return pauseState();
4412
+ pauseRuntime("all", { since: (/* @__PURE__ */ new Date()).toISOString(), by: "alpd", reason, cause: "disk" }, true);
4413
+ notice("error", (say) => say.diskFull(reason));
4414
+ return pauseState();
4415
+ },
4416
+ releaseDisk(by) {
4417
+ if (paused.all?.cause !== "disk") return pauseState();
4418
+ resumeRuntime("all", by, true);
4419
+ return pauseState();
4420
+ },
4421
+ diskHeld: () => paused.all?.cause === "disk",
4422
+ diskLow(free) {
4423
+ notice("warning", (say) => say.diskLow(free));
4424
+ },
3878
4425
  async usage(refresh = false) {
3879
4426
  const providers = await Promise.all(["codex", "claude"].map((kind) => cachedUsage(kind, refresh)));
3880
4427
  const state = pauseState();
@@ -3905,6 +4452,10 @@ ${interrupted}`), text_elements: [] }] : []
3905
4452
  thinking: mapping.thinking
3906
4453
  };
3907
4454
  },
4455
+ syncGates(projectRoot) {
4456
+ if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) return Promise.reject(new Error("syncGates needs an absolute projectRoot"));
4457
+ return syncGates(projectRoot);
4458
+ },
3908
4459
  async board(projectRoot) {
3909
4460
  if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) throw new Error("board needs an absolute projectRoot");
3910
4461
  return (await boardOf(path.resolve(projectRoot))).filter(live);
@@ -3922,6 +4473,11 @@ ${interrupted}`), text_elements: [] }] : []
3922
4473
  answer(questionId, reply) {
3923
4474
  const pending = userQuestions.get(questionId);
3924
4475
  if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
4476
+ if (pending.gate) {
4477
+ if (!reply.dismiss && (typeof reply.text !== "string" || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error("An answer needs text");
4478
+ void pending.gate.decide(reply);
4479
+ return;
4480
+ }
3925
4481
  if (reply.dismiss) {
3926
4482
  pending.settle("dismissed", void 0, reply.reason);
3927
4483
  return;
@@ -3956,6 +4512,8 @@ ${interrupted}`), text_elements: [] }] : []
3956
4512
  )
3957
4513
  );
3958
4514
  clearInterval(watchdog);
4515
+ if (gateWatch) clearInterval(gateWatch);
4516
+ await Promise.all(gateSyncs.values());
3959
4517
  await Promise.all(boards.values());
3960
4518
  await boardDomain.flush();
3961
4519
  await runLogWrites;
@@ -3968,8 +4526,10 @@ ${interrupted}`), text_elements: [] }] : []
3968
4526
  listeners.clear();
3969
4527
  }
3970
4528
  };
4529
+ return api;
3971
4530
  }
3972
4531
  export {
4532
+ CURATE_MARKER,
3973
4533
  DEFAULT_TEAM,
3974
4534
  WorkspaceMutationError,
3975
4535
  createAlpRuntime