@anhlp/alp-runtime 0.0.1-beta.4 → 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.
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 +71 -10
  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 +32 -3
  18. package/dist/index.d.ts +10 -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 +665 -47
  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 +31 -5
  42. package/dist/workspace.js +92 -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 +79 -10
  51. package/src/compact.ts +62 -0
  52. package/src/configure.ts +3 -3
  53. package/src/contracts.ts +28 -2
  54. package/src/index.ts +10 -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 +718 -48
  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 +124 -18
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";
@@ -15,7 +16,7 @@ import { TASK_ACTIONS, TASK_PAST, TASK_FIELDS, mainOf, roleOf, taskActions, task
15
16
  import { nativeEnvironment, createTransport } from "./providers.js";
16
17
  import { nativeMode, codexApproval, profileEfforts, nativeSessionConfig } from "./session-config.js";
17
18
  import { createHash, randomUUID } from "node:crypto";
18
- import { readFileSync, realpathSync } from "node:fs";
19
+ import { readFileSync, realpathSync, watch as watchFiles } from "node:fs";
19
20
  import { appendFile, mkdir, open, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
20
21
  import { moveFile } from "@anhlp/alp-core/atomic";
21
22
  import os from "node:os";
@@ -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, TASKS_DIR, 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++;
@@ -231,7 +244,9 @@ function createAlpRuntime(options = {}) {
231
244
  }
232
245
  cancelQuestions(sessionId, true);
233
246
  if (session.parent) sessions.get(session.parent)?.assignments.get(sessionId)?.ask?.resolve(toolResult(false, { error: "Turn ended" }));
234
- session.mail = session.mail.filter((event) => !(event.deliveredTurn === turnId && state === "completed"));
247
+ const taken = state === "completed" ? session.mail.filter((event) => event.deliveredTurn === turnId) : [];
248
+ session.mail = session.mail.filter((event) => !taken.includes(event));
249
+ for (const event of taken) gateMail.get(event)?.taken();
235
250
  for (const event of session.mail) {
236
251
  if (event.deliveredTurn === turnId) {
237
252
  event.deliveredTurn = void 0;
@@ -248,7 +263,12 @@ function createAlpRuntime(options = {}) {
248
263
  }
249
264
  session.userStopped = false;
250
265
  if (session.role === "supervisor" && session.parent && sessions.get(session.parent)?.reviewPending) review(session.parent);
266
+ if (session.role === "supervisor" && session.parent) {
267
+ const root = sessions.get(session.parent);
268
+ if (root) queueMicrotask(() => compactAtBoundary(session.parent, root));
269
+ }
251
270
  if (!session.parent) void showTasks(sessionId, session);
271
+ if (!session.parent && session.role !== "supervisor") queueMicrotask(() => compactAtBoundary(sessionId, session, state));
252
272
  if (session.parkReason && state !== "completed") {
253
273
  park(sessionId, session);
254
274
  return;
@@ -407,7 +427,7 @@ function createAlpRuntime(options = {}) {
407
427
  if (state === "failed" && LIMIT_ERRORS.includes(params.turn.error?.codexErrorInfo)) {
408
428
  if (session.role !== "supervisor") {
409
429
  session.parkReason = `the ${label(session.runtimeKind)} usage limit was reached`;
410
- session.parkPause = { scope: paused.all ? "all" : session.runtimeKind };
430
+ session.parkPause = { scope: paused.all ? "all" : session.runtimeKind, ...paused.all?.cause === "disk" ? { disk: true } : {} };
411
431
  }
412
432
  void limitReached(session, params.turn.error);
413
433
  }
@@ -421,6 +441,7 @@ function createAlpRuntime(options = {}) {
421
441
  }
422
442
  const sessionClosures = /* @__PURE__ */ new WeakMap();
423
443
  const openedSessions = /* @__PURE__ */ new WeakSet();
444
+ const openings = /* @__PURE__ */ new WeakMap();
424
445
  const assignmentSessions = /* @__PURE__ */ new WeakMap();
425
446
  function closeSession(sessionId, session = sessions.get(sessionId), notify = true) {
426
447
  if (!session) return Promise.resolve();
@@ -834,22 +855,25 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
834
855
  return toolResult(true, { tasks: rows.slice(0, limit).map((task2) => summarize(task2, tasks2)), ...rows.length > limit ? { more: rows.length - limit } : {}, ...warnings });
835
856
  }
836
857
  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" });
858
+ 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")))) {
859
+ 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
860
  }
840
- const { kind, until, ref, gate, formula: _formula, vars: _vars, ...fields } = input;
861
+ const { kind, until, ref, gate, options: gateChoices, formula: _formula, vars: _vars, ...fields } = input;
841
862
  if (action === "clear") {
842
863
  const current = (await loadTasks(project)).tasks.find((candidate) => candidate.id === id);
843
864
  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
865
  }
845
866
  let poured;
846
867
  const hookedClose = async (id2) => {
868
+ const current = (await loadTasks(project)).tasks.find((candidate) => candidate.id === id2);
869
+ 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
870
  const refused = await runHooks(sessionId, session, "task.close", { reason, ...summary ? { summary } : {} }, id2);
848
871
  if (refused) throw new Error(`A task.close hook refused to close ${id2}: ${refused}`);
849
872
  return closeTask(project, id2, { reason, summary, unverified }, by);
850
873
  };
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);
874
+ 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
875
  touchTask(rootOf(sessionId), task.id);
876
+ if (action === "gate" && kind === "human") void syncGates(project);
853
877
  runLog(rootOf(sessionId), { event: "task", action, agent: by, id: task.id, title: task.title, status: task.status, ...summary ?? note ? { detail: summary ?? note } : {} });
854
878
  const { tasks } = await loadTasks(project);
855
879
  const landed = {};
@@ -956,6 +980,45 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
956
980
  return toolResult(false, { assignmentId: entry.assignmentId, error: errorData(error).message });
957
981
  }
958
982
  }
983
+ async function resolveTool(sessionId, session, args) {
984
+ 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)) {
985
+ return toolResult(false, { error: `Pass assignmentId, outcome (${RESULT_OUTCOMES.join(", ")}), and optionally a note of at most ${RESOLVE_NOTE_CHARS} characters` });
986
+ }
987
+ const id = args.assignmentId;
988
+ const outcome = args.outcome;
989
+ const note = args.note;
990
+ const live2 = [...sessions.values()];
991
+ if (sessions.has(id) || live2.some((other) => other.assignments.has(id)) || inFlight.all().some((entry2) => entry2.assignmentId === id) || inherited.some((entry2) => entry2.assignmentId === id)) {
992
+ return toolResult(false, { error: "That assignment is still running or can still be recovered; wait for its result" });
993
+ }
994
+ 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" });
995
+ let ledger;
996
+ try {
997
+ ledger = await assignmentResults.inspect();
998
+ } catch (error) {
999
+ return toolResult(false, { error: errorData(error).message });
1000
+ }
1001
+ const entry = ledger.results.find((owner) => owner.assignmentId === id && !owner.handled);
1002
+ const project = session.mapping.agent.projectRoot;
1003
+ const overlapping2 = async (a, b) => {
1004
+ const [x, y] = [await realpath(a).catch(() => a), await realpath(b).catch(() => b)];
1005
+ const within = (parent, child) => {
1006
+ const relative = path.relative(parent, child);
1007
+ return relative === "" || relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
1008
+ };
1009
+ return within(x, y) || within(y, x);
1010
+ };
1011
+ 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));
1012
+ if (!entry || !allowed) return toolResult(false, { error: `No unresolved assignment result ${id} of yours` });
1013
+ 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` });
1014
+ try {
1015
+ const archived = await assignmentResults.resolve(id, { outcome, by: `${session.mapping.agent.name} in ${sessionId}`, at: (/* @__PURE__ */ new Date()).toISOString(), ...note ? { note } : {} });
1016
+ runLog(rootOf(sessionId), { event: "result.resolved", assignmentId: id, agent: session.mapping.agent.name, outcome, ...note ? { note: clip(note, 500) } : {} });
1017
+ return toolResult(true, { resolved: id, outcome, archivedAt: archived.archivedAt });
1018
+ } catch (error) {
1019
+ return toolResult(false, { assignmentId: id, error: errorData(error).message });
1020
+ }
1021
+ }
959
1022
  let forgetting = Promise.resolve();
960
1023
  function forgetExpired() {
961
1024
  forgetting = forgetting.then(async () => {
@@ -983,7 +1046,7 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
983
1046
  const label = (kind) => kind === "claude" ? "Claude" : kind === "acp" ? "ACP agent" : kind === "antigravity" ? "Antigravity" : "Codex";
984
1047
  const pauseOf = (kind) => paused.all ?? paused.runtimes[kind];
985
1048
  const held = (session) => !!session.parked || !!pauseOf(session.runtimeKind) || (session.lifecycleHolds ?? 0) > 0;
986
- const holdsWake = (session) => held(session) || !!session.awaitingBrief;
1049
+ const holdsWake = (session) => held(session) || !!session.awaitingBrief || !!session.compacting;
987
1050
  function beginPending(session) {
988
1051
  let done;
989
1052
  session.pending = true;
@@ -1119,16 +1182,16 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1119
1182
  for (const [id, session] of sessions) {
1120
1183
  if (!session.parent || session.closed || !session.active || session.role === "supervisor" || scope !== "all" && session.runtimeKind !== scope) continue;
1121
1184
  if (session.parkReason && !session.parkPause) continue;
1122
- session.parkReason = `paused by ${pause.by}`;
1123
- session.parkPause = { scope };
1185
+ session.parkReason = pause.cause === "disk" ? pause.reason : `paused by ${pause.by}`;
1186
+ session.parkPause = { scope, ...pause.cause === "disk" ? { disk: true } : {} };
1124
1187
  void session.runtime.request("turn/interrupt", { threadId: session.threadId, turnId: session.active }).catch(() => {
1125
1188
  });
1126
1189
  runLog(rootOf(id), { event: "assignment.parking", assignmentId: id, agent: session.mapping.agent.name, reason: session.parkReason });
1127
1190
  }
1128
1191
  }
1129
1192
  }
1130
- function resumeRuntime(scope, by) {
1131
- if (scope === "all") paused = { runtimes: {} };
1193
+ function resumeRuntime(scope, by, keepRuntimes = false) {
1194
+ if (scope === "all") paused = keepRuntimes ? { runtimes: paused.runtimes } : { runtimes: {} };
1132
1195
  else delete paused.runtimes[scope];
1133
1196
  savePauses();
1134
1197
  watchLimits();
@@ -1163,6 +1226,7 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1163
1226
  if (!parent || !assignment) return;
1164
1227
  emit(session.parent, { type: "assignment", assignment: assignmentSnapshot(assignment, "parked") });
1165
1228
  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.` });
1229
+ 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
1230
  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
1231
  }
1168
1232
  function continueParked(sessionId, session, expected = session.parked) {
@@ -1230,6 +1294,7 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1230
1294
  const used = usage2?.last?.totalTokens;
1231
1295
  const window = usage2?.modelContextWindow;
1232
1296
  if (session.role === "supervisor" || typeof used !== "number" || typeof window !== "number" || window <= 0) return;
1297
+ 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
1298
  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
1299
  const fill = used / compactAt;
1235
1300
  if (fill < CONTEXT_RESET) {
@@ -1266,13 +1331,157 @@ Review the process against ALP.md, ${agent}'s AGENT.md and the recorded lessons.
1266
1331
  if (!done) return;
1267
1332
  const agent = session.mapping.agent.name;
1268
1333
  runLog(rootOf(sessionId), { event: "compacted", sessionId, agent, ...trigger, ...tokens, ...failed ? { failed: true, ...item.error ? { error: String(item.error) } : {} } : {} });
1269
- if (failed) return;
1334
+ if (failed) {
1335
+ if (session.compacting?.phase === "native") compactFailed(sessionId, session, item.error ? String(item.error) : "the runtime could not compact");
1336
+ return;
1337
+ }
1270
1338
  session.contextLevel = 0;
1271
1339
  if (session.supervisor) session.journal.push(stamp(`${agent}'s context was compacted`));
1272
- if (session.role !== "supervisor") void restoreAfterCompaction(sessionId, session).catch(() => {
1340
+ const checkpoint = session.compacting?.phase === "native" ? session.compacting.checkpoint : void 0;
1341
+ if (session.role !== "supervisor") void restoreAfterCompaction(sessionId, session, checkpoint).catch(() => {
1342
+ });
1343
+ if (checkpoint !== void 0) compactFinished(sessionId, session, "native");
1344
+ }
1345
+ function compactHeld(sessionId, session, starting) {
1346
+ 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);
1347
+ }
1348
+ function compactAtBoundary(sessionId, session, ended) {
1349
+ if (session.closed || sessions.get(sessionId) !== session) return;
1350
+ const current = session.compacting;
1351
+ if (ended && current?.phase === "checkpoint" && current.checkpoint === void 0 && current.turn) {
1352
+ const written = [...session.text.values()].at(-1)?.trim();
1353
+ if (ended !== "completed" || !written) {
1354
+ compactFailed(sessionId, session, ended !== "completed" ? `the checkpoint turn ${ended}` : "main wrote no checkpoint");
1355
+ return;
1356
+ }
1357
+ current.checkpoint = written;
1358
+ const timer = setTimeout(() => {
1359
+ if (session.compacting === current && current.phase === "checkpoint") compactFailed(sessionId, session, "main stayed busy after its checkpoint");
1360
+ }, COMPACT_NATIVE_MS);
1361
+ timer.unref?.();
1362
+ }
1363
+ if (ended && current?.phase === "native" && current.requested) {
1364
+ compactFailed(sessionId, session, "the runtime reported no compaction");
1365
+ return;
1366
+ }
1367
+ if (current) {
1368
+ if (current.checkpoint !== void 0 && current.phase === "checkpoint" && !compactHeld(sessionId, session, false)) void compactNow(sessionId, session);
1369
+ return;
1370
+ }
1371
+ if (compactHeld(sessionId, session, true)) return;
1372
+ if (session.compactBuffer?.length) {
1373
+ flushCompactBuffer(sessionId, session);
1374
+ return;
1375
+ }
1376
+ const trigger = compactDue(session.mapping.compact ?? { auto: false, threshold: 1 }, session.contextFill, !!session.compactRequested);
1377
+ if (!trigger) return;
1378
+ if (trigger === "auto" && session.compactFailedAt && Date.now() - session.compactFailedAt < COMPACT_RETRY_MS) return;
1379
+ session.compactRequested = false;
1380
+ const compacting = { phase: "checkpoint", trigger, startedAt: Date.now() };
1381
+ session.compacting = compacting;
1382
+ runLog(rootOf(sessionId), { event: "compact.started", sessionId, agent: session.mapping.agent.name, trigger, ...session.contextFill !== void 0 ? { fill: Math.round(session.contextFill * 100) / 100 } : {} });
1383
+ const work = queue.then(async () => {
1384
+ if (session.compacting !== compacting) return;
1385
+ if (session.closed || compactHeld(sessionId, session, true)) {
1386
+ session.compacting = void 0;
1387
+ if (trigger === "manual") session.compactRequested = true;
1388
+ compactReleased(sessionId, session);
1389
+ return;
1390
+ }
1391
+ compacting.turn = true;
1392
+ await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: "auto", content: [{ type: "text", text: checkpointPrompt(trigger, session.contextFill) }] }, "wake");
1393
+ }).catch((error) => compactFailed(sessionId, session, errorData(error).message));
1394
+ queue = work.catch(() => {
1395
+ });
1396
+ }
1397
+ async function compactNow(sessionId, session) {
1398
+ const current = session.compacting;
1399
+ const checkpoint = current.checkpoint;
1400
+ if (NATIVE_COMPACT.includes(session.runtimeKind)) {
1401
+ current.phase = "native";
1402
+ try {
1403
+ await session.runtime.request("thread/compact/start", { threadId: session.threadId, ...session.runtimeKind === "codex" ? {} : { instructions: compactInstructions(checkpoint) } });
1404
+ if (session.compacting !== current) return;
1405
+ current.requested = true;
1406
+ const timer = setTimeout(() => {
1407
+ if (session.compacting === current) compactFailed(sessionId, session, "the runtime reported no compaction in time");
1408
+ }, COMPACT_NATIVE_MS);
1409
+ timer.unref?.();
1410
+ return;
1411
+ } catch (error) {
1412
+ if (session.compacting !== current) return;
1413
+ runLog(rootOf(sessionId), { event: "compact.native_failed", sessionId, agent: session.mapping.agent.name, error: errorData(error).message });
1414
+ }
1415
+ }
1416
+ current.phase = "fresh";
1417
+ const work = queue.then(async () => {
1418
+ if (session.compacting !== current || session.closed) return;
1419
+ const refusal = restartRefusal(sessionId, session);
1420
+ if (refusal && refusal !== MAIL_WAITS && refusal !== REVIEWING) {
1421
+ compactFailed(sessionId, session, `a fresh conversation cannot start now: ${refusal}`);
1422
+ return;
1423
+ }
1424
+ await restartNative(sessionId, session, void 0);
1425
+ emit(sessionId, { type: "session.updated", session: snapshot(sessionId, session) });
1426
+ await startPrompt(sessionId, { clientMessageId: `alp-wake-compact-${randomUUID()}`, delivery: "auto", content: [{ type: "text", text: seedPrompt(checkpoint, session.lastUserText) }] }, "wake");
1427
+ compactFinished(sessionId, session, "fresh");
1428
+ }).catch((error) => compactFailed(sessionId, session, errorData(error).message));
1429
+ queue = work.catch(() => {
1430
+ });
1431
+ }
1432
+ function compactFinished(sessionId, session, via) {
1433
+ const current = session.compacting;
1434
+ if (!current) return;
1435
+ session.compacting = void 0;
1436
+ session.compactFailedAt = void 0;
1437
+ session.contextFill = void 0;
1438
+ session.compactCooling = true;
1439
+ 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 });
1440
+ const text2 = wordsFor(session).compacted(via === "native");
1441
+ emit(sessionId, { type: "item", item: { kind: "notice", id: `notice-${randomUUID().slice(0, 8)}`, level: "info", text: text2 } });
1442
+ compactReleased(sessionId, session);
1443
+ }
1444
+ function compactFailed(sessionId, session, reason) {
1445
+ const current = session.compacting;
1446
+ session.compacting = void 0;
1447
+ session.compactFailedAt = Date.now();
1448
+ runLog(rootOf(sessionId), { event: "compact.failed", sessionId, agent: session.mapping.agent.name, ...current ? { trigger: current.trigger } : {}, error: reason });
1449
+ if (!session.closed) emit(sessionId, { type: "item", item: { kind: "notice", id: `notice-${randomUUID().slice(0, 8)}`, level: "warning", text: wordsFor(session).compactFailed(reason) } });
1450
+ compactReleased(sessionId, session);
1451
+ }
1452
+ function compactReleased(sessionId, session) {
1453
+ queueMicrotask(() => {
1454
+ if (session.closed || session.compacting) return;
1455
+ flushCompactBuffer(sessionId, session);
1456
+ if (session.wakeHeld && !holdsWake(session)) {
1457
+ session.wakeHeld = false;
1458
+ deliver(sessionId, session);
1459
+ }
1460
+ });
1461
+ }
1462
+ function flushCompactBuffer(sessionId, session) {
1463
+ if (session.compacting || session.active || !session.compactBuffer?.length) return;
1464
+ const held2 = session.compactBuffer.splice(0);
1465
+ session.compactBuffer = void 0;
1466
+ const work = queue.then(async () => {
1467
+ for (const [index, input] of held2.entries()) {
1468
+ await promptSession(sessionId, { ...input, delivery: index === 0 && !session.active ? "auto" : "steer" }, true);
1469
+ }
1470
+ });
1471
+ queue = work.catch(() => {
1273
1472
  });
1274
1473
  }
1275
- async function restoreAfterCompaction(sessionId, session) {
1474
+ function requestCompact(sessionId) {
1475
+ const session = sessions.get(sessionId);
1476
+ if (!session || session.closed) throw new ConversationError("session_busy", "The session is not open");
1477
+ if (session.parent || session.role === "supervisor") throw new ConversationError("runtime_unsupported", "Only a root session is compacted");
1478
+ if (session.compacting) return { status: "running" };
1479
+ session.compactRequested = true;
1480
+ if (compactHeld(sessionId, session, true)) return { status: "deferred" };
1481
+ compactAtBoundary(sessionId, session);
1482
+ return { status: "started" };
1483
+ }
1484
+ async function restoreAfterCompaction(sessionId, session, checkpoint) {
1276
1485
  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
1486
  if (session.parent && session.brief) parts.push(`Your assignment from ${session.parentAgent ?? "your requester"}, as it was given:
1278
1487
  ${cut(session.brief, BRIEF_CHARS)}`);
@@ -1283,7 +1492,7 @@ ${cut(session.brief, BRIEF_CHARS)}`);
1283
1492
  if (session.worktrees.size) {
1284
1493
  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
1494
  }
1286
- const asked = [...userQuestions.values()].filter((pending) => pending.question.sessionId === sessionId);
1495
+ const asked = [...userQuestions.values()].filter((pending) => pending.question.sessionId === sessionId && !pending.gate);
1287
1496
  if (asked.length) parts.push("Waiting for the user to answer:\n" + asked.map((pending) => `- ${clip(pending.question.body, 300)}`).join("\n"));
1288
1497
  if (!session.parent) {
1289
1498
  const project = session.mapping.agent.projectRoot;
@@ -1292,6 +1501,8 @@ ${cut(session.brief, BRIEF_CHARS)}`);
1292
1501
  const board = renderBoard(await boardOf(project));
1293
1502
  if (board) parts.push(board);
1294
1503
  }
1504
+ if (checkpoint) parts.push(`The checkpoint you wrote before the compaction, by skill compact:
1505
+ ${cut(checkpoint, BRIEF_CHARS)}`);
1295
1506
  parts.push("Carry on where you were; alp_board and alp_task tell you more.");
1296
1507
  if (session.closed) return;
1297
1508
  post(sessionId, { kind: "note", from: "alp", assignment: sessionId, body: parts.join("\n\n"), ...session.active ? {} : { passive: true } });
@@ -1362,7 +1573,7 @@ ${cut(session.brief, BRIEF_CHARS)}`);
1362
1573
  return [path.join(mapping.agent.projectRoot, ".alp", LESSONS_FILE), ...options.libraryDir ? [path.join(options.libraryDir, LESSONS_FILE)] : []];
1363
1574
  }
1364
1575
  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" };
1576
+ 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
1577
  const say = wordsFor(session);
1367
1578
  const result = await askUser(sessionId, session, void 0, body, [say.approve, say.reject], approval);
1368
1579
  let value;
@@ -1427,7 +1638,7 @@ ${args.body.trim()}
1427
1638
  return toolResult(false, { error: errorData(error).message });
1428
1639
  }
1429
1640
  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" });
1641
+ 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
1642
  const approvalId = `q-${randomUUID()}`;
1432
1643
  const record2 = { approvalId, draftKey };
1433
1644
  approvals.set(key, record2);
@@ -1496,6 +1707,139 @@ ${content}`,
1496
1707
  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
1708
  }
1498
1709
  let scheduleHandler;
1710
+ async function lessonCurateTool(sessionId, session, args) {
1711
+ const cancellation = approvalCancellation.get(session) ?? 0;
1712
+ args = structuredClone(args);
1713
+ 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);
1714
+ if (!plainObject(args, ["changes", "requestId"]) || !Array.isArray(args.changes) || !args.changes.length || args.changes.length > 50 || !args.changes.every(validChange)) {
1715
+ 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` });
1716
+ }
1717
+ if (args.requestId !== void 0 && !text(args.requestId, 100)) return toolResult(false, { error: "requestId must be a nonempty string of at most 100 characters" });
1718
+ const changes = args.changes;
1719
+ if (changes.some((change) => change.scope === "user") && !options.libraryDir) return toolResult(false, { error: "This host keeps no user lessons" });
1720
+ const fileOf = (scope) => scope === "user" ? path.join(options.libraryDir, LESSONS_FILE) : path.join(session.mapping.agent.projectRoot, ".alp", LESSONS_FILE);
1721
+ const normalizeLesson = (lesson) => lesson.replace(/\s+/g, " ").trim().replace(/^(?:- )?\d{4}-\d\d-\d\d: /, "").trim();
1722
+ const normalized = changes.map((change) => ({ ...change, remove: [...new Set(change.remove.map(normalizeLesson))], add: change.add?.replace(/\s+/g, " ").trim() }));
1723
+ const draftKey = JSON.stringify(["lessons", normalized]);
1724
+ const key = `lessons:${args.requestId ?? draftKey}`;
1725
+ const approvals = approvalsOf(sessionId);
1726
+ const previous = approvals.get(key);
1727
+ if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: "requestId was already used for a different draft" });
1728
+ if (previous) return toolResult(true, previous.result ?? { status: "pending_approval", approvalId: previous.approvalId });
1729
+ const readLessons = async (file) => (await readFile(file, "utf8").catch(() => "")).split("\n").flatMap((line) => /^- \d{4}-\d\d-\d\d: /.test(line) ? [normalizeLesson(line)] : []);
1730
+ const missing = [];
1731
+ for (const change of normalized) {
1732
+ const recorded = new Set(await readLessons(fileOf(change.scope)));
1733
+ for (const lesson of change.remove) if (!recorded.has(lesson)) missing.push(`${change.scope}: ${lesson}`);
1734
+ }
1735
+ if (missing.length) return toolResult(false, { error: "These lessons are not recorded; copy their exact text from the lessons files", missing });
1736
+ if (approvalCanceled(session, cancellation)) return toolResult(false, { error: "Lesson proposal canceled or session closed; no approval was created" });
1737
+ 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" });
1738
+ const approvalId = `q-${randomUUID()}`;
1739
+ const record2 = { approvalId, draftKey };
1740
+ approvals.set(key, record2);
1741
+ const say = wordsFor(session);
1742
+ const shown = normalized.map((change, index) => `${index + 1}. ${say.lessonScope(change.scope, fileOf(change.scope))}${change.reason ? ` \u2014 ${change.reason}` : ""}
1743
+ ` + change.remove.map((lesson) => ` ${say.lessonRemove}: ${lesson}`).join("\n") + (change.add ? `
1744
+ ${say.lessonAdd}: ${change.add}` : "")).join("\n\n");
1745
+ const decision = confirm(sessionId, session, `${say.lessonCurate(session.mapping.agent.name, shown)}
1746
+
1747
+ ${say.answerLine(session.mapping.agent.name)}`, { id: approvalId });
1748
+ const apply = async () => {
1749
+ const removed = [];
1750
+ const notFound = [];
1751
+ let added = 0;
1752
+ for (const scope of ["project", "user"]) {
1753
+ const mine = normalized.filter((change) => change.scope === scope);
1754
+ if (!mine.length) continue;
1755
+ const file = fileOf(scope);
1756
+ const write = (lessonWrites.get(file) ?? Promise.resolve()).catch(() => {
1757
+ }).then(async () => {
1758
+ const current = await readFile(file, "utf8").catch(() => void 0);
1759
+ if (current === void 0) {
1760
+ for (const change of mine) notFound.push(...change.remove.map((lesson) => `${scope}: ${lesson}`));
1761
+ return;
1762
+ }
1763
+ const targets = new Set(mine.flatMap((change) => change.remove));
1764
+ const seen = /* @__PURE__ */ new Set();
1765
+ const kept = current.split("\n").filter((line) => {
1766
+ if (!/^- \d{4}-\d\d-\d\d: /.test(line)) return true;
1767
+ const lesson = normalizeLesson(line);
1768
+ if (!targets.has(lesson)) return true;
1769
+ seen.add(lesson);
1770
+ return false;
1771
+ });
1772
+ for (const lesson of targets) (seen.has(lesson) ? removed : notFound).push(`${scope}: ${lesson}`);
1773
+ const date = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
1774
+ const additions = mine.filter((change) => change.add && change.remove.some((lesson) => seen.has(lesson))).map((change) => `- ${date}: ${change.add}`);
1775
+ added += additions.length;
1776
+ let body = kept.join("\n");
1777
+ if (additions.length) body = body.replace(/\n*$/, "\n") + additions.join("\n") + "\n";
1778
+ await writeFile(file, body);
1779
+ });
1780
+ lessonWrites.set(file, write);
1781
+ await write;
1782
+ }
1783
+ runLog(rootOf(sessionId), { event: "lesson.curate", agent: session.mapping.agent.name, removed, added, notFound });
1784
+ return { approved: true, applied: true, removed, added, ...notFound.length ? { lessonsNotFound: notFound } : {} };
1785
+ };
1786
+ void (async () => {
1787
+ const answer = await decision;
1788
+ const canceled = approvalCanceled(session, cancellation);
1789
+ let result;
1790
+ 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." };
1791
+ else {
1792
+ try {
1793
+ result = await apply();
1794
+ } catch (error) {
1795
+ result = { approved: true, applied: false, error: errorData(error).message, next: "Tell the user; nothing is retried automatically." };
1796
+ }
1797
+ }
1798
+ record2.result = { status: "resolved", approvalId, ...result };
1799
+ runLog(rootOf(sessionId), { event: "lesson.curate.approval", agent: session.mapping.agent.name, ...record2.result });
1800
+ if (!closed && !session.closed && sessions.get(sessionId) === session) post(sessionId, { kind: "result", from: "ALP", assignment: approvalId, body: `Lesson curate result: ${JSON.stringify(record2.result)}` });
1801
+ })();
1802
+ 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." });
1803
+ }
1804
+ const curateSchedules = /* @__PURE__ */ new Map();
1805
+ function ensureCurateSchedule(sessionId) {
1806
+ const root = sessions.get(sessionId);
1807
+ if (!scheduleHandler || !root || root.closed || root.parent) return Promise.resolve();
1808
+ const project = root.mapping.agent.projectRoot;
1809
+ const run = (curateSchedules.get(project) ?? Promise.resolve()).catch(() => {
1810
+ }).then(() => curateScheduleOf(sessionId, root, project));
1811
+ curateSchedules.set(project, run);
1812
+ void run.catch(() => {
1813
+ }).then(() => {
1814
+ if (curateSchedules.get(project) === run) curateSchedules.delete(project);
1815
+ });
1816
+ return run;
1817
+ }
1818
+ async function curateScheduleOf(sessionId, root, project) {
1819
+ const handler = scheduleHandler;
1820
+ if (!handler || root.closed || sessions.get(sessionId) !== root) return;
1821
+ for (const file of [path.join(project, ".alp", "settings.json"), ...options.libraryDir ? [path.join(options.libraryDir, "settings.json")] : []]) {
1822
+ const settings = await readFile(file, "utf8").then((raw) => {
1823
+ try {
1824
+ return JSON.parse(raw);
1825
+ } catch {
1826
+ return void 0;
1827
+ }
1828
+ }, () => void 0);
1829
+ const monthly = settings?.curate?.monthly;
1830
+ if (monthly === false) return;
1831
+ if (monthly === true) break;
1832
+ }
1833
+ const listed = await handler("list", { projectRoot: project, status: "pending" });
1834
+ const curate = (listed?.jobs ?? []).filter((job) => job.prompt.startsWith(CURATE_MARKER));
1835
+ if (curate.some((job) => job.sessionId === sessionId)) return;
1836
+ for (const job of curate) await handler("cancel", { id: job.id, projectRoot: project }).catch(() => {
1837
+ });
1838
+ const now = /* @__PURE__ */ new Date();
1839
+ const dueAt = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1, 2)).toISOString();
1840
+ await handler("create", { projectRoot: project, sessionId, dueAt, prompt: CURATE_PROMPT, keepsSession: false });
1841
+ runLog(sessionId, { event: "curate.scheduled", dueAt, replaced: curate.map((job) => job.id) });
1842
+ }
1499
1843
  async function scheduleTool(sessionId, session, args) {
1500
1844
  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
1845
  if (!scheduleHandler) return toolResult(false, { error: "This host does not support scheduled continuations" });
@@ -1600,7 +1944,7 @@ ${args.prompt}`,
1600
1944
  const previous = approvals.get(key);
1601
1945
  if (previous && previous.draftKey !== draftKey) return toolResult(false, { error: "requestId was already used for a different draft" });
1602
1946
  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" });
1947
+ 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
1948
  const approvalId = `q-${randomUUID()}`;
1605
1949
  const record2 = { approvalId, draftKey };
1606
1950
  approvals.set(key, record2);
@@ -1688,7 +2032,7 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1688
2032
  if (session.pending) {
1689
2033
  void session.acknowledged.then(() => deliver(sessionId, session));
1690
2034
  } else if (session.active) {
1691
- if (session.mail.some((event) => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
2035
+ if (!session.compacting && session.mail.some((event) => !event.deliveredTurn && !event.passive && !event.defer)) void steerMail(sessionId, session);
1692
2036
  } else if (!waking) {
1693
2037
  return;
1694
2038
  } else if (!session.wakeBlocked && session.wakeFailures < MAX_WAKES && (session.wakes < MAX_WAKES || session.mail.some((event) => !event.deliveredTurn && event.kind === "checkin"))) {
@@ -1918,7 +2262,18 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
1918
2262
  if (assignment.worktree || writes(assignment.mode)) await assignmentResults.put({
1919
2263
  assignmentId: assignment.id,
1920
2264
  checkout: assignment.worktree?.checkout ?? assignment.writeCheckout ?? resultChild?.mapping.workdir ?? parent.mapping.workdir,
1921
- ...assignment.worktree ? { worktree: assignment.worktree.path } : {}
2265
+ ...assignment.worktree ? { worktree: assignment.worktree.path } : {},
2266
+ // Outside a worktree, the change stays in the checkout: keep its evidence until the requester resolves it.
2267
+ ...!assignment.worktree ? { result: {
2268
+ agent: assignment.agent,
2269
+ status: state,
2270
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
2271
+ project: (resultChild ?? parent).mapping.agent.projectRoot,
2272
+ requesters: lineage(parentId),
2273
+ ...assignment.taskId ? { taskId: assignment.taskId } : {},
2274
+ brief: cut(resultChild?.brief ?? "", RESULT_EVIDENCE_CHARS),
2275
+ summary: cut(JSON.stringify({ handoff: resultChild?.handoff ?? null, output: resultChild ? [...resultChild.text.values()].at(-1) ?? "" : "", ...error ? { error: errorData(error).message } : {} }), RESULT_EVIDENCE_CHARS)
2276
+ } } : {}
1922
2277
  });
1923
2278
  } catch (failure) {
1924
2279
  assignment.finished = false;
@@ -2008,7 +2363,7 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
2008
2363
  error: "ALP tools require the current active turn"
2009
2364
  });
2010
2365
  }
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") {
2366
+ 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
2367
  return toolResult(false, {
2013
2368
  error: "Unknown ALP tool"
2014
2369
  });
@@ -2016,10 +2371,12 @@ ${args.labels?.length ? `${say.issueLabels}: ${args.labels.join(", ")}
2016
2371
  const cached = session.toolCalls.get(params.callId);
2017
2372
  if (cached) return cached;
2018
2373
  const args = params.arguments;
2374
+ const oversized = inputLimitError(args, TOOL_INPUT, `${params.tool} input`);
2375
+ if (oversized) return toolResult(false, { error: oversized });
2019
2376
  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" });
2377
+ 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
2378
  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);
2379
+ 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
2380
  const reminded = !session.parent && params.tool !== "alp_ask" ? work.then((result) => remindUser(session, result)) : work;
2024
2381
  session.toolCalls.set(params.callId, reminded);
2025
2382
  return reminded;
@@ -2160,10 +2517,181 @@ The user answered: "${answer}"`);
2160
2517
  post(session.parent, { kind: "note", from: session.mapping.agent.name, assignment: sessionId, body: `[ALP, on behalf of ${session.mapping.agent.name}] ${body}` });
2161
2518
  }
2162
2519
  function cancelQuestions(sessionId, turnOnly = false) {
2163
- for (const { question, settle, persistent } of [...userQuestions.values()]) {
2520
+ for (const { question, settle, persistent, gate } of [...userQuestions.values()]) {
2521
+ if (gate && turnOnly) continue;
2164
2522
  if (question.sessionId === sessionId && (!turnOnly || !persistent)) settle("canceled", void 0, void 0, toolResult(false, { error: "Turn ended" }));
2165
2523
  }
2166
2524
  }
2525
+ const gateSyncs = /* @__PURE__ */ new Map();
2526
+ const gateMail = /* @__PURE__ */ new WeakMap();
2527
+ const gateTaken = /* @__PURE__ */ new Set();
2528
+ const gateMarks = /* @__PURE__ */ new Set();
2529
+ const gateCardId = (taskId, gateId) => `gate-${taskId}-${gateId}`;
2530
+ function mainSessionOf(projectRoot) {
2531
+ for (const [id, session] of sessions) {
2532
+ if (session.closed || session.parent || session.role === "supervisor" || !session.threadId) continue;
2533
+ if (session.mapping.agent.name !== mainOf(session.mapping) || path.resolve(session.mapping.agent.projectRoot) !== projectRoot) continue;
2534
+ return { id, session };
2535
+ }
2536
+ return void 0;
2537
+ }
2538
+ function syncGates(projectRoot) {
2539
+ const root = path.resolve(projectRoot);
2540
+ const previous = gateSyncs.get(root) ?? Promise.resolve();
2541
+ const next = previous.then(() => syncGatesNow(root)).catch((error) => {
2542
+ runLog(mainSessionOf(root)?.id ?? root, { event: "gate.sync.failed", projectRoot: root, error: errorData(error).message });
2543
+ });
2544
+ gateSyncs.set(root, next);
2545
+ void next.finally(() => {
2546
+ if (gateSyncs.get(root) === next) gateSyncs.delete(root);
2547
+ });
2548
+ return next;
2549
+ }
2550
+ async function syncGatesNow(projectRoot) {
2551
+ if (closed) return;
2552
+ const { tasks } = await loadTasks(projectRoot);
2553
+ const main = mainSessionOf(projectRoot);
2554
+ if (main) for (const { task, gate, decision, record: record2 } of gateDecisions(tasks)) {
2555
+ const key = JSON.stringify([projectRoot, task.id, gate.id, decision, record2.at]);
2556
+ if (gateTaken.has(key) || main.session.mail.some((event) => gateMail.get(event)?.key === key)) continue;
2557
+ const choice = decision === "approved" ? record2.choice : void 0;
2558
+ 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.`;
2559
+ 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.` });
2560
+ gateMail.set(mail, {
2561
+ key,
2562
+ taken: () => {
2563
+ gateTaken.add(key);
2564
+ const mark = markGateNotified(projectRoot, task.id, gate.id, decision, record2.at).catch((error) => {
2565
+ gateTaken.delete(key);
2566
+ runLog(main.id, { event: "gate.mark.failed", projectRoot, taskId: task.id, gateId: gate.id, error: errorData(error).message });
2567
+ });
2568
+ gateMarks.add(mark);
2569
+ void mark.finally(() => gateMarks.delete(mark));
2570
+ }
2571
+ });
2572
+ runLog(main.id, { event: "gate.decision", projectRoot, taskId: task.id, gateId: gate.id, decision, channel: record2.channel, ...choice ? { choice } : {} });
2573
+ }
2574
+ const wanted = /* @__PURE__ */ new Map();
2575
+ for (const task of tasks) {
2576
+ if (task.status === "closed") continue;
2577
+ for (const gate of task.gates ?? []) if (gate.kind === "human" && !gate.resolved && !gate.rejected) wanted.set(gateCardId(task.id, gate.id), { task, gate });
2578
+ }
2579
+ for (const [id, pending] of [...userQuestions]) {
2580
+ if (pending.question.gate?.projectRoot !== projectRoot) continue;
2581
+ const want = wanted.get(id);
2582
+ if (!want || !main || pending.question.sessionId !== main.id) {
2583
+ const task = tasks.find((entry) => entry.id === pending.question.gate.taskId);
2584
+ const gate = task?.gates.find((entry) => entry.id === pending.question.gate.gateId);
2585
+ pending.settle(gate?.resolved ? "answered" : gate?.rejected ? "dismissed" : "canceled", gate?.resolved?.choice, gate?.rejected?.reason);
2586
+ } else if (pending.gate) pending.gate.rev = want.task.rev;
2587
+ }
2588
+ if (!main) return;
2589
+ for (const [id, { task, gate }] of wanted) if (!userQuestions.has(id)) showGateCard(main.id, main.session, projectRoot, task, gate);
2590
+ }
2591
+ let gateWatch;
2592
+ const gateFiles = /* @__PURE__ */ new Map();
2593
+ function startGateWatch(projectRoot) {
2594
+ if (options.gateSyncMs === 0) return;
2595
+ watchGateFiles(path.resolve(projectRoot));
2596
+ if (gateWatch) return;
2597
+ gateWatch = setInterval(() => {
2598
+ 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)));
2599
+ for (const root of roots) {
2600
+ watchGateFiles(root);
2601
+ void syncGates(root);
2602
+ }
2603
+ for (const root of gateFiles.keys()) if (!roots.has(root)) unwatchGateFiles(root);
2604
+ if (!roots.size) {
2605
+ clearInterval(gateWatch);
2606
+ gateWatch = void 0;
2607
+ }
2608
+ }, options.gateSyncMs ?? 5e3);
2609
+ gateWatch.unref?.();
2610
+ }
2611
+ function watchGateFiles(root) {
2612
+ if (closed || gateFiles.has(root)) return;
2613
+ try {
2614
+ const entry = {
2615
+ // A burst of writes (a save, its ledger, a mark) syncs once.
2616
+ watcher: watchFiles(path.join(root, TASKS_DIR), () => {
2617
+ if (entry.timer || closed) return;
2618
+ entry.timer = setTimeout(() => {
2619
+ entry.timer = void 0;
2620
+ void syncGates(root);
2621
+ }, 50);
2622
+ entry.timer.unref?.();
2623
+ })
2624
+ };
2625
+ entry.watcher.on("error", () => unwatchGateFiles(root));
2626
+ entry.watcher.unref?.();
2627
+ gateFiles.set(root, entry);
2628
+ } catch {
2629
+ }
2630
+ }
2631
+ function unwatchGateFiles(root) {
2632
+ const entry = gateFiles.get(root);
2633
+ if (!entry) return;
2634
+ gateFiles.delete(root);
2635
+ clearTimeout(entry.timer);
2636
+ entry.watcher.close();
2637
+ }
2638
+ function showGateCard(sessionId, session, projectRoot, task, gate) {
2639
+ const say = wordsFor(session);
2640
+ const vietnamese = say.approve === words("vi").approve;
2641
+ const question = {
2642
+ id: gateCardId(task.id, gate.id),
2643
+ sessionId,
2644
+ rootId: rootOf(sessionId),
2645
+ agent: "ALP",
2646
+ body: `${vietnamese ? `C\u1ED5ng ph\xEA duy\u1EC7t ${gate.id} c\u1EE7a ${task.id}` : `Approval gate ${gate.id} of ${task.id}`} (${task.title}):
2647
+ ${gate.note ?? ""}`,
2648
+ // Options approve; Reject (added after them unless one of them is that word) keeps the gate open.
2649
+ options: gate.options?.length ? gate.options.includes(say.reject) ? gate.options : [...gate.options, say.reject] : [say.approve, say.reject],
2650
+ askedAt: gate.at ?? (/* @__PURE__ */ new Date()).toISOString(),
2651
+ gate: { projectRoot, taskId: task.id, gateId: gate.id }
2652
+ };
2653
+ const card = { rev: task.rev, deciding: false };
2654
+ const settle = (outcome, answer) => {
2655
+ if (userQuestions.get(question.id)?.question !== question) return;
2656
+ userQuestions.delete(question.id);
2657
+ emit(sessionId, { type: "question.resolved", questionId: question.id, outcome, ...answer !== void 0 ? { answer } : {} });
2658
+ };
2659
+ 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) }) });
2660
+ emit(sessionId, { type: "question", question });
2661
+ runLog(rootOf(sessionId), { event: "gate.card", questionId: question.id, taskId: task.id, gateId: gate.id });
2662
+ }
2663
+ async function decideGate(projectRoot, question, card, reply, choices) {
2664
+ const defaults = !choices;
2665
+ const { taskId, gateId } = question.gate;
2666
+ if (card.deciding) throw gateRefusal("GATE_BUSY", `An answer to gate ${gateId} of ${taskId} is already being recorded`);
2667
+ card.deciding = true;
2668
+ const channel = reply.channel ?? "web";
2669
+ const text2 = reply.text?.trim();
2670
+ const approve2 = !reply.dismiss && !!text2 && (defaults ? APPROVALS.includes(text2.toLowerCase()) : choices.includes(text2));
2671
+ const rejectReason = reply.dismiss ? reply.reason : text2 && CHOICES_REJECT.includes(text2.toLowerCase()) ? void 0 : text2;
2672
+ 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) } : {} });
2673
+ try {
2674
+ try {
2675
+ await write(card.rev);
2676
+ } catch (error) {
2677
+ if (error?.code !== "TASK_CHANGED") throw error;
2678
+ const current = (await loadTasks(projectRoot)).tasks.find((entry) => entry.id === taskId);
2679
+ const gate = current?.gates.find((entry) => entry.id === gateId);
2680
+ if (!current || current.status === "closed" || !gate) throw gateRefusal("GATE_DECIDED", `Gate ${gateId} of ${taskId} is no longer open`);
2681
+ 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}` : ""}`);
2682
+ await write(current.rev);
2683
+ }
2684
+ } catch (error) {
2685
+ runLog(question.rootId, { event: "gate.answer.failed", questionId: question.id, error: errorData(error).message });
2686
+ throw error;
2687
+ } finally {
2688
+ card.deciding = false;
2689
+ await syncGates(projectRoot);
2690
+ }
2691
+ }
2692
+ function gateRefusal(code, message) {
2693
+ return Object.assign(new Error(message), { code });
2694
+ }
2167
2695
  function askTool(sessionId, session, args) {
2168
2696
  const parent = session.parent ? sessions.get(session.parent) : void 0;
2169
2697
  const assignment = parent?.assignments.get(sessionId);
@@ -2175,7 +2703,7 @@ The user answered: "${answer}"`);
2175
2703
  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
2704
  return Promise.resolve(toolResult(false, { error: "options are up to 10 short answers, for questions to the user" }));
2177
2705
  }
2178
- if (assignment?.ask || [...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId)) {
2706
+ if (assignment?.ask || [...userQuestions.values()].some((pending) => pending.question.sessionId === sessionId && !pending.gate)) {
2179
2707
  return Promise.resolve(toolResult(false, { error: "A question is already waiting for an answer" }));
2180
2708
  }
2181
2709
  if (to === "user" && session.parent && !session.userOpened) {
@@ -2624,6 +3152,11 @@ ${digest}` : "")
2624
3152
  };
2625
3153
  if (assignment) assignmentSessions.set(assignment, session);
2626
3154
  const finishPending = beginPending(session);
3155
+ const opening = {};
3156
+ openings.set(session, opening);
3157
+ const failedMeanwhile = () => {
3158
+ if (opening.failure !== void 0) throw opening.failure;
3159
+ };
2627
3160
  sessions.set(
2628
3161
  sessionId,
2629
3162
  session
@@ -2631,6 +3164,7 @@ ${digest}` : "")
2631
3164
  wire(sessionId, session, runtime);
2632
3165
  try {
2633
3166
  await runtime.initialize();
3167
+ failedMeanwhile();
2634
3168
  if (session.closed || sessions.get(sessionId) !== session) {
2635
3169
  throw new Error(
2636
3170
  "Session closed during initialization"
@@ -2666,11 +3200,13 @@ ${digest}` : "")
2666
3200
  }
2667
3201
  );
2668
3202
  session.threadId = result.thread.id;
3203
+ failedMeanwhile();
2669
3204
  if (session.closed || sessions.get(sessionId) !== session) {
2670
3205
  throw new Error(
2671
3206
  "Session closed during thread creation"
2672
3207
  );
2673
3208
  }
3209
+ openings.delete(session);
2674
3210
  session.buffered = [];
2675
3211
  finishPending();
2676
3212
  openedSessions.add(session);
@@ -2683,6 +3219,10 @@ ${digest}` : "")
2683
3219
  thinking: result.reasoningEffort ?? mapping.thinking
2684
3220
  }
2685
3221
  });
3222
+ if (!session.parent && session.role !== "supervisor" && mapping.agent.name === mainOf(mapping)) {
3223
+ void syncGates(mapping.agent.projectRoot);
3224
+ startGateWatch(mapping.agent.projectRoot);
3225
+ }
2686
3226
  if (history === "replay") {
2687
3227
  for (const turn of result.thread.turns ?? []) {
2688
3228
  for (const item of turn.items ?? []) {
@@ -2699,6 +3239,9 @@ ${digest}` : "")
2699
3239
  return snapshot(sessionId, session);
2700
3240
  } catch (error) {
2701
3241
  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 });
3242
+ const failed = openings.get(session);
3243
+ openings.delete(session);
3244
+ if (failed?.failure !== void 0) failSession(sessionId, session, failed.failure);
2702
3245
  const cleanup = closeSession(sessionId, session, false);
2703
3246
  finishPending();
2704
3247
  await cleanup;
@@ -2722,6 +3265,11 @@ ${digest}` : "")
2722
3265
  });
2723
3266
  transport.onFailure((error) => {
2724
3267
  if (session.closed || session.runtime !== transport || sessions.get(sessionId) !== session) return;
3268
+ const opening = openings.get(session);
3269
+ if (opening) {
3270
+ opening.failure ??= error;
3271
+ return;
3272
+ }
2725
3273
  if (revivable(session)) void revive(sessionId, session, error);
2726
3274
  else failSession(sessionId, session, error);
2727
3275
  });
@@ -2832,10 +3380,10 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2832
3380
  if (session.pending) return "The session is still opening or restarting";
2833
3381
  if (session.active) return "A turn is running";
2834
3382
  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";
3383
+ if ([...userQuestions.values()].some((pending) => pending.question.rootId === sessionId && !pending.gate)) return "A question to the user waits for an answer";
3384
+ if ((hasActiveMail(session) || session.wakeHeld) && !session.lifecycleHolds) return MAIL_WAITS;
2837
3385
  if (session.parked || session.parkReason) return "The session is parked";
2838
- if (reviewing(session)) return "The supervisor is reviewing the session";
3386
+ if (reviewing(session)) return REVIEWING;
2839
3387
  return void 0;
2840
3388
  }
2841
3389
  async function restartNative(sessionId, session, binding, verify = true, shape) {
@@ -2995,7 +3543,6 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
2995
3543
  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
3544
  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
3545
  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
3546
  const before = executablesOf(session.mapping);
3000
3547
  const added = [...executablesOf(mapping)].filter((entry) => !before.has(entry));
3001
3548
  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 +3777,6 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3230
3777
  }
3231
3778
  if (assignment.copy) await removeCopy(assignment.copy).catch(() => {
3232
3779
  });
3233
- if (assignment.worktree) await removeWorktree(assignment.worktree).catch(() => {
3234
- });
3235
3780
  };
3236
3781
  try {
3237
3782
  if (entry.lease) {
@@ -3242,7 +3787,14 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3242
3787
  leases.set(entry.lease, { assignment: id, agent: entry.agent });
3243
3788
  }
3244
3789
  }
3245
- if (entry.worktree) assignment.worktree = await reattachWorktree(entry.worktree);
3790
+ if (entry.worktree) {
3791
+ const { preserved, ...worktree } = await reattachWorktree(entry.worktree);
3792
+ assignment.worktree = worktree;
3793
+ if (preserved) {
3794
+ runLog(entry.rootId, { event: "worktree.preserved", assignmentId: id, branch: worktree.branch, preserved });
3795
+ 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}.` });
3796
+ }
3797
+ }
3246
3798
  if (entry.copyOf) {
3247
3799
  assignment.copy = await createCopy(entry.copyOf, copyRoot, id);
3248
3800
  spec = { ...spec, workdir: assignment.copy.workdir };
@@ -3283,7 +3835,17 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3283
3835
  if (entry.worktree || writes(entry.mode)) await assignmentResults.put({
3284
3836
  assignmentId: entry.assignmentId,
3285
3837
  checkout: entry.worktree?.checkout ?? entry.lease ?? entry.spec.writeRoot ?? entry.spec.workdir ?? entry.project,
3286
- ...entry.worktree ? { worktree: entry.worktree.path } : {}
3838
+ ...entry.worktree ? { worktree: entry.worktree.path } : {},
3839
+ ...!entry.worktree ? { result: {
3840
+ agent: entry.agent,
3841
+ status: "abandoned",
3842
+ finishedAt: (/* @__PURE__ */ new Date()).toISOString(),
3843
+ project: entry.project,
3844
+ requesters: sessions.has(entry.parentId) ? lineage(entry.parentId) : [entry.parentId],
3845
+ ...entry.taskId ? { taskId: entry.taskId } : {},
3846
+ brief: cut(entry.brief ?? "", RESULT_EVIDENCE_CHARS),
3847
+ summary: cut(JSON.stringify({ reason }), RESULT_EVIDENCE_CHARS)
3848
+ } } : {}
3287
3849
  });
3288
3850
  await inFlight.remove(entry.assignmentId);
3289
3851
  const parent = sessions.get(entry.parentId);
@@ -3387,8 +3949,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3387
3949
  }
3388
3950
  const parent = session.parent ? sessions.get(session.parent) : void 0;
3389
3951
  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 }) });
3952
+ if (session.runtimeKind === "claude" || session.runtimeKind === "antigravity") await session.runtime.request("session/configure", { sandbox: nativeMode({ mode, copy: session.mapping.copy }) });
3392
3953
  session.mapping.mode = mode;
3393
3954
  session.spec = { ...session.spec, mode };
3394
3955
  const updated = snapshot(sessionId, session);
@@ -3434,8 +3995,12 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3434
3995
  );
3435
3996
  }
3436
3997
  }
3437
- async function promptSession(sessionId, input) {
3998
+ async function promptSession(sessionId, input, flushing = false) {
3438
3999
  const session = sessions.get(sessionId);
4000
+ if (!flushing && session && !session.parent && (session.compacting || session.compactBuffer?.length)) {
4001
+ if (!session.seen.has(input.clientMessageId) && !session.compactBuffer?.some((held2) => held2.clientMessageId === input.clientMessageId)) (session.compactBuffer ??= []).push(input);
4002
+ return;
4003
+ }
3439
4004
  const parked = session?.parked;
3440
4005
  try {
3441
4006
  const prompt = session?.active && session.resumedTurn === session.active && input.delivery === "auto" ? { ...input, delivery: "steer" } : input;
@@ -3511,6 +4076,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3511
4076
  if (prompt.delivery !== "steer") {
3512
4077
  session.text.clear();
3513
4078
  session.toolCalls.clear();
4079
+ if (!/^alp-wake-compact-/.test(prompt.clientMessageId)) session.compactCooling = false;
3514
4080
  session.supervisorWake = !!wake?.length && wake.every((event) => event.defer);
3515
4081
  if (!wake) {
3516
4082
  session.handoff = void 0;
@@ -3522,6 +4088,7 @@ Write scope: change files only under ${session.spec.writeRoot}. Your working dir
3522
4088
  }
3523
4089
  try {
3524
4090
  const orchestration = session.runtime.orchestrationContext ? await session.runtime.orchestrationContext().catch(() => ({ available: false })) : { available: false };
4091
+ feedCatalog(orchestration);
3525
4092
  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
4093
  const interrupted = prompt.delivery !== "steer" && !wake && session.threadId ? interruptedThreads.get(session.threadId) : void 0;
3527
4094
  if (interrupted) interruptedThreads.delete(session.threadId);
@@ -3588,6 +4155,7 @@ ${interrupted}`), text_elements: [] }] : []
3588
4155
  }
3589
4156
  });
3590
4157
  if (origin === "user" && !session.parent) session.userWaiting ??= Date.now();
4158
+ if (origin === "user" && !session.parent && text2) session.lastUserText = clip(text2, 16e3);
3591
4159
  if (session.supervisor && origin === "user") session.journal.push(stamp(`user ${prompt.delivery === "steer" ? "steered" : "asked"} ${session.mapping.agent.name}: ${clip(text2, 1500)}`));
3592
4160
  if (prompt.delivery === "steer" && origin === "user" && !session.parent) {
3593
4161
  releaseWaiters(session);
@@ -3619,7 +4187,7 @@ ${interrupted}`), text_elements: [] }] : []
3619
4187
  }
3620
4188
  }
3621
4189
  if (options.recallFile) void forgetExpired();
3622
- return {
4190
+ const api = {
3623
4191
  registerWorkspace: (directory) => enqueue(async () => {
3624
4192
  try {
3625
4193
  await assignmentResults.register(await realpath(directory));
@@ -3627,7 +4195,7 @@ ${interrupted}`), text_elements: [] }] : []
3627
4195
  refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot register workspace result ownership");
3628
4196
  }
3629
4197
  }),
3630
- withWorkspaceMutation: (directory, run) => {
4198
+ withWorkspaceMutation: (directory, run, adoption) => {
3631
4199
  if (workspaceMutation || admitting) return Promise.reject(new WorkspaceMutationError("workspace_busy", "A session or assignment is opening; retry after it finishes"));
3632
4200
  workspaceMutation = true;
3633
4201
  return enqueue(async () => {
@@ -3638,7 +4206,7 @@ ${interrupted}`), text_elements: [] }] : []
3638
4206
  } catch (error) {
3639
4207
  refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot inspect permanent assignment results");
3640
4208
  }
3641
- if (!resultLedger.workspaces.includes(target)) refuseMutation("workspace_assignment_result", "Workspace predates authoritative assignment tracking; an audited migration is required before removal");
4209
+ if (!resultLedger.workspaces.includes(target) && adoption !== ADOPTION) refuseMutation("workspace_assignment_result", "Workspace predates authoritative assignment tracking; an audited migration is required before removal");
3642
4210
  const canonical = (value) => {
3643
4211
  try {
3644
4212
  return realpathSync(value);
@@ -3660,7 +4228,15 @@ ${interrupted}`), text_elements: [] }] : []
3660
4228
  };
3661
4229
  return contains(target, owner) || contains(owner, target);
3662
4230
  };
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}`);
4231
+ 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}`);
4232
+ const resolved = async (assignmentId) => {
4233
+ if (resultLedger.results.some((owner) => owner.assignmentId === assignmentId && owner.handled)) return true;
4234
+ try {
4235
+ return !!await assignmentResults.archived(assignmentId);
4236
+ } catch {
4237
+ return refuseMutation("workspace_assignment_result", "Cannot inspect the assignment result archive; repair it before removing the workspace");
4238
+ }
4239
+ };
3664
4240
  for (const [project, pins] of loadedBoards) for (const pin of pins) {
3665
4241
  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
4242
  }
@@ -3692,15 +4268,24 @@ ${interrupted}`), text_elements: [] }] : []
3692
4268
  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
4269
  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
4270
  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}`);
4271
+ 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
4272
  }
3697
4273
  }
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}`);
4274
+ 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
4275
  return await run();
3700
4276
  }).finally(() => {
3701
4277
  workspaceMutation = false;
3702
4278
  });
3703
4279
  },
4280
+ adoptWorkspace: (directory, verify) => api.withWorkspaceMutation(directory, async () => {
4281
+ if (await realpath(directory) !== directory) refuseMutation("workspace_identity", `Adopt ${directory} by its canonical path`);
4282
+ await verify(directory);
4283
+ try {
4284
+ await assignmentResults.register(directory);
4285
+ } catch (error) {
4286
+ refuseMutation("workspace_assignment_result", error instanceof Error ? error.message : "Cannot register workspace result ownership");
4287
+ }
4288
+ }, ADOPTION),
3704
4289
  bindSchedules(handler) {
3705
4290
  scheduleHandler = handler;
3706
4291
  },
@@ -3723,7 +4308,10 @@ ${interrupted}`), text_elements: [] }] : []
3723
4308
  open: (sessionId, spec, { history = "skip", delegation = true } = {}) => enqueue(async () => {
3724
4309
  const opened = await openSession(sessionId, spec, history, delegation);
3725
4310
  const root = sessions.get(sessionId);
3726
- if (supervises(root)) void enqueue(() => openSupervisor(sessionId));
4311
+ if (supervises(root)) {
4312
+ void enqueue(() => openSupervisor(sessionId));
4313
+ void ensureCurateSchedule(sessionId).catch((error) => runLog(sessionId, { event: "curate.schedule.failed", error: errorData(error).message }));
4314
+ }
3727
4315
  return opened;
3728
4316
  }),
3729
4317
  prompt: (sessionId, input) => enqueue(() => promptSession(sessionId, input)),
@@ -3774,6 +4362,7 @@ ${interrupted}`), text_elements: [] }] : []
3774
4362
  branch: (request) => branchConversation(request),
3775
4363
  rebind: (sessionId, binding) => enqueue(() => rebindSession(sessionId, binding)),
3776
4364
  reload: (sessionId) => enqueue(() => reloadSession(sessionId)),
4365
+ compact: (sessionId) => requestCompact(sessionId),
3777
4366
  previewConfigure: (sessionId, changes) => previewConfigureSession(sessionId, changes),
3778
4367
  reconfigure: (sessionId, changes, options2) => enqueue(() => reconfigureSession(sessionId, changes, options2)),
3779
4368
  starting: (sessionId) => {
@@ -3823,7 +4412,7 @@ ${interrupted}`), text_elements: [] }] : []
3823
4412
  };
3824
4413
  visit(rootId);
3825
4414
  const questions = [...userQuestions.values()].map((pending) => pending.question).filter((question) => question.rootId === rootId);
3826
- const asking = new Set(questions.map((question) => question.sessionId));
4415
+ const asking = new Set(questions.filter((question) => !question.gate).map((question) => question.sessionId));
3827
4416
  const ids = new Set(tree.map(([id]) => id));
3828
4417
  return {
3829
4418
  rootId,
@@ -3875,6 +4464,21 @@ ${interrupted}`), text_elements: [] }] : []
3875
4464
  return pauseState();
3876
4465
  },
3877
4466
  pauses: () => pauseState(),
4467
+ holdForDisk(reason) {
4468
+ if (paused.all) return pauseState();
4469
+ pauseRuntime("all", { since: (/* @__PURE__ */ new Date()).toISOString(), by: "alpd", reason, cause: "disk" }, true);
4470
+ notice("error", (say) => say.diskFull(reason));
4471
+ return pauseState();
4472
+ },
4473
+ releaseDisk(by) {
4474
+ if (paused.all?.cause !== "disk") return pauseState();
4475
+ resumeRuntime("all", by, true);
4476
+ return pauseState();
4477
+ },
4478
+ diskHeld: () => paused.all?.cause === "disk",
4479
+ diskLow(free) {
4480
+ notice("warning", (say) => say.diskLow(free));
4481
+ },
3878
4482
  async usage(refresh = false) {
3879
4483
  const providers = await Promise.all(["codex", "claude"].map((kind) => cachedUsage(kind, refresh)));
3880
4484
  const state = pauseState();
@@ -3905,6 +4509,10 @@ ${interrupted}`), text_elements: [] }] : []
3905
4509
  thinking: mapping.thinking
3906
4510
  };
3907
4511
  },
4512
+ syncGates(projectRoot) {
4513
+ if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) return Promise.reject(new Error("syncGates needs an absolute projectRoot"));
4514
+ return syncGates(projectRoot);
4515
+ },
3908
4516
  async board(projectRoot) {
3909
4517
  if (typeof projectRoot !== "string" || !path.isAbsolute(projectRoot)) throw new Error("board needs an absolute projectRoot");
3910
4518
  return (await boardOf(path.resolve(projectRoot))).filter(live);
@@ -3922,6 +4530,10 @@ ${interrupted}`), text_elements: [] }] : []
3922
4530
  answer(questionId, reply) {
3923
4531
  const pending = userQuestions.get(questionId);
3924
4532
  if (!pending) throw new Error(`No question ${questionId} waits for an answer`);
4533
+ if (pending.gate) {
4534
+ if (!reply.dismiss && (typeof reply.text !== "string" || !reply.text.trim() || reply.text.length > MAIL_BODY_CHARS)) throw new Error("An answer needs text");
4535
+ return pending.gate.decide(reply);
4536
+ }
3925
4537
  if (reply.dismiss) {
3926
4538
  pending.settle("dismissed", void 0, reply.reason);
3927
4539
  return;
@@ -3956,6 +4568,10 @@ ${interrupted}`), text_elements: [] }] : []
3956
4568
  )
3957
4569
  );
3958
4570
  clearInterval(watchdog);
4571
+ if (gateWatch) clearInterval(gateWatch);
4572
+ for (const root of [...gateFiles.keys()]) unwatchGateFiles(root);
4573
+ await Promise.all(gateSyncs.values());
4574
+ await Promise.all(gateMarks);
3959
4575
  await Promise.all(boards.values());
3960
4576
  await boardDomain.flush();
3961
4577
  await runLogWrites;
@@ -3968,8 +4584,10 @@ ${interrupted}`), text_elements: [] }] : []
3968
4584
  listeners.clear();
3969
4585
  }
3970
4586
  };
4587
+ return api;
3971
4588
  }
3972
4589
  export {
4590
+ CURATE_MARKER,
3973
4591
  DEFAULT_TEAM,
3974
4592
  WorkspaceMutationError,
3975
4593
  createAlpRuntime