@anhlp/alp-runtime 0.0.0-beta.2 → 0.0.1-beta.10

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 (97) hide show
  1. package/dist/acp-transport.js +7 -36
  2. package/dist/antigravity-transport.d.ts +27 -2
  3. package/dist/antigravity-transport.js +104 -58
  4. package/dist/assignment-results.d.ts +55 -0
  5. package/dist/assignment-results.js +181 -0
  6. package/dist/attachments.d.ts +84 -0
  7. package/dist/attachments.js +213 -0
  8. package/dist/board-domain.js +2 -2
  9. package/dist/board.d.ts +6 -0
  10. package/dist/board.js +7 -0
  11. package/dist/catalog.d.ts +13 -0
  12. package/dist/catalog.js +11 -2
  13. package/dist/claude-transport.d.ts +80 -0
  14. package/dist/claude-transport.js +271 -23
  15. package/dist/compact.d.ts +29 -0
  16. package/dist/compact.js +49 -0
  17. package/dist/configure.d.ts +44 -0
  18. package/dist/configure.js +64 -0
  19. package/dist/contracts.d.ts +216 -7
  20. package/dist/contracts.js +11 -0
  21. package/dist/conversation.d.ts +45 -0
  22. package/dist/conversation.js +62 -0
  23. package/dist/index.d.ts +18 -5
  24. package/dist/index.js +48 -4
  25. package/dist/input-limits.d.ts +25 -0
  26. package/dist/input-limits.js +48 -0
  27. package/dist/language.d.ts +10 -0
  28. package/dist/language.js +26 -0
  29. package/dist/live.d.ts +2 -2
  30. package/dist/live.js +7 -2
  31. package/dist/mailbox.d.ts +2 -0
  32. package/dist/mailbox.js +3 -1
  33. package/dist/mcp-tools.d.ts +8 -0
  34. package/dist/mcp-tools.js +26 -0
  35. package/dist/model-catalog.d.ts +162 -0
  36. package/dist/model-catalog.js +338 -0
  37. package/dist/model-probes.d.ts +7 -0
  38. package/dist/model-probes.js +69 -0
  39. package/dist/providers.js +2 -0
  40. package/dist/recall.d.ts +2 -2
  41. package/dist/recall.js +4 -3
  42. package/dist/resolve.d.ts +2 -0
  43. package/dist/resolve.js +9 -5
  44. package/dist/runtime-context.d.ts +1 -1
  45. package/dist/runtime-context.js +1 -1
  46. package/dist/runtime.d.ts +9 -0
  47. package/dist/runtime.js +2078 -269
  48. package/dist/session-config.d.ts +378 -6
  49. package/dist/session-config.js +19 -15
  50. package/dist/session-state.d.ts +54 -7
  51. package/dist/skill-resources.d.ts +30 -0
  52. package/dist/skill-resources.js +55 -0
  53. package/dist/tool-detail.js +4 -1
  54. package/dist/tools.d.ts +154 -1
  55. package/dist/tools.js +99 -11
  56. package/dist/transport.js +3 -1
  57. package/dist/workspace.d.ts +31 -5
  58. package/dist/workspace.js +92 -11
  59. package/dist/worktree-domain.d.ts +2 -1
  60. package/dist/worktree-domain.js +4 -1
  61. package/dist/write-error.d.ts +2 -0
  62. package/dist/write-error.js +10 -0
  63. package/package.json +12 -4
  64. package/src/acp-transport.ts +10 -37
  65. package/src/antigravity-transport.ts +128 -55
  66. package/src/assignment-results.ts +154 -0
  67. package/src/attachments.ts +254 -0
  68. package/src/board-domain.ts +2 -2
  69. package/src/board.ts +7 -0
  70. package/src/catalog.ts +13 -2
  71. package/src/claude-transport.ts +333 -23
  72. package/src/compact.ts +62 -0
  73. package/src/configure.ts +93 -0
  74. package/src/contracts.ts +199 -8
  75. package/src/conversation.ts +81 -0
  76. package/src/index.ts +18 -5
  77. package/src/input-limits.ts +65 -0
  78. package/src/language.ts +28 -0
  79. package/src/live.ts +7 -3
  80. package/src/mailbox.ts +4 -1
  81. package/src/mcp-tools.ts +33 -0
  82. package/src/model-catalog.ts +316 -0
  83. package/src/model-probes.ts +58 -0
  84. package/src/providers.ts +3 -0
  85. package/src/recall.ts +4 -3
  86. package/src/resolve.ts +15 -7
  87. package/src/runtime-context.ts +2 -2
  88. package/src/runtime.ts +2253 -264
  89. package/src/session-config.ts +25 -14
  90. package/src/session-state.ts +39 -3
  91. package/src/skill-resources.ts +73 -0
  92. package/src/tool-detail.ts +4 -1
  93. package/src/tools.ts +97 -10
  94. package/src/transport.ts +3 -1
  95. package/src/workspace.ts +124 -18
  96. package/src/worktree-domain.ts +5 -1
  97. package/src/write-error.ts +4 -0
package/dist/tools.js CHANGED
@@ -1,8 +1,11 @@
1
1
  // packages/runtime/src/tools.ts
2
2
  import { CLOSE_REASONS, GATE_KINDS, TASK_STATUSES, TASK_TYPES, TASKS_DIR } from "@anhlp/alp-core/tasks";
3
3
  import { READ_ONLY_AGENTS } from "./resolve.js";
4
- import { PIN_KINDS } from "./board.js";
4
+ import { READ_ONLY_ROLES } from "@anhlp/alp-core/permissions";
5
+ import { PIN_KINDS, PIN_PATH_CHARS, PIN_PATHS } from "./board.js";
6
+ import { POUR_VARS } from "./input-limits.js";
5
7
  import { RECALL_KEEP_MS } from "./recall.js";
8
+ import { RESULT_OUTCOMES } from "./assignment-results.js";
6
9
  import { HANDOFF_OUTCOMES, VERDICT_RESULTS, CRITERION_RESULTS, SEVERITIES } from "./handoff.js";
7
10
  var handoffList = (description) => ({ type: "array", items: { type: "string" }, description });
8
11
  var HANDOFF_TOOL = {
@@ -64,7 +67,7 @@ var HANDOFF_TOOL = {
64
67
  var WAIT_TOOL = {
65
68
  type: "function",
66
69
  name: "alp_wait",
67
- description: "Wait for mail from your assignments: results, questions, notes, and stall reports. Returns as soon as any arrives, or with an empty list and a status snapshot on timeout.",
70
+ description: "Wait for mail from your assignments: results, questions, notes, and stall reports. Returns as soon as any arrives, a check-in comes or the user writes to you; otherwise with an empty list and a status snapshot after timeoutMs (default 5 minutes, at most 15). Ending your turn instead never cancels your assignments.",
68
71
  inputSchema: {
69
72
  type: "object",
70
73
  properties: {
@@ -125,6 +128,21 @@ var DISCARD_TOOL = {
125
128
  additionalProperties: false
126
129
  }
127
130
  };
131
+ var RESOLVE_TOOL = {
132
+ type: "function",
133
+ name: "alp_resolve",
134
+ description: "Record how you handled a finished writer's change in your checkout: applied (you kept or committed it), discarded (you reverted it) or acknowledged (you reviewed it; nothing to do). Until then ALP keeps its result and will not let that checkout be removed; then it archives the result.",
135
+ inputSchema: {
136
+ type: "object",
137
+ properties: {
138
+ assignmentId: { type: "string" },
139
+ outcome: { type: "string", enum: RESULT_OUTCOMES },
140
+ note: { type: "string", description: "What you did with it, for the archive and the run log." }
141
+ },
142
+ required: ["assignmentId", "outcome"],
143
+ additionalProperties: false
144
+ }
145
+ };
128
146
  var CANCEL_TOOL = {
129
147
  type: "function",
130
148
  name: "alp_cancel",
@@ -163,7 +181,7 @@ var PIN_TOOL = {
163
181
  properties: {
164
182
  kind: { type: "string", enum: PIN_KINDS },
165
183
  body: { type: "string", description: "For a claim, what you are changing; otherwise the decision or finding itself." },
166
- paths: { type: "array", items: { type: "string" }, description: "Project-relative files or directories. Required for a claim." }
184
+ paths: { type: "array", items: { type: "string", maxLength: PIN_PATH_CHARS }, maxItems: PIN_PATHS, description: `Project-relative files or directories, at most ${PIN_PATHS}. Required for a claim.` }
167
185
  },
168
186
  required: ["kind", "body"],
169
187
  additionalProperties: false
@@ -176,7 +194,7 @@ var BOARD_TOOL = {
176
194
  inputSchema: {
177
195
  type: "object",
178
196
  properties: {
179
- kinds: { type: "array", items: { type: "string", enum: PIN_KINDS } },
197
+ kinds: { type: "array", items: { type: "string", enum: PIN_KINDS }, maxItems: PIN_KINDS.length },
180
198
  limit: { type: "integer", description: "Most recent decisions and findings to return. Default 30." }
181
199
  },
182
200
  additionalProperties: false
@@ -196,7 +214,7 @@ var UNPIN_TOOL = {
196
214
  var ASK_TOOL = {
197
215
  type: "function",
198
216
  name: "alp_ask",
199
- description: "Ask a question and wait for the answer: your requester, or the user. Only main talks to the user, unless the user has written to you. Returns unanswered after the ask timeout.",
217
+ description: "Ask a question and wait for the answer: your requester, or the user. Only main talks to the user, unless the user has written to you. Holds your turn until answered; returns unanswered after the ask timeout (15 minutes for a requester, 30 for the user), and user_wrote when the user writes in the chat instead of answering.",
200
218
  inputSchema: {
201
219
  type: "object",
202
220
  properties: {
@@ -222,10 +240,38 @@ var LESSON_TOOL = {
222
240
  additionalProperties: false
223
241
  }
224
242
  };
243
+ var LESSON_CURATE_TOOL = {
244
+ type: "function",
245
+ name: "alp_lesson_curate",
246
+ description: "Merge, shorten or remove recorded lessons. Each change removes the exact text of lessons from one scope and may add one rule in their place (a merge or a shortening); a change without add removes them. ALP shows every change to the user at once and applies them only when the user approves. Returns pending_approval with approvalId immediately; the result (applied, lessons not found, or the user's feedback) arrives once by mail. Never edit lessons files any other way.",
247
+ inputSchema: {
248
+ type: "object",
249
+ properties: {
250
+ changes: {
251
+ type: "array",
252
+ description: "At most 50 changes.",
253
+ items: {
254
+ type: "object",
255
+ properties: {
256
+ scope: { type: "string", enum: ["project", "user"] },
257
+ remove: { type: "array", items: { type: "string" }, description: "The exact text of each lesson to remove, with or without its date." },
258
+ add: { type: "string", description: "One rule, at most 600 characters, that replaces them." },
259
+ reason: { type: "string", description: "Why, in one line." }
260
+ },
261
+ required: ["scope", "remove"],
262
+ additionalProperties: false
263
+ }
264
+ },
265
+ requestId: { type: "string", description: "Optional session-scoped idempotency key (1-100 characters)." }
266
+ },
267
+ required: ["changes"],
268
+ additionalProperties: false
269
+ }
270
+ };
225
271
  var SKILL_TOOL = {
226
272
  type: "function",
227
273
  name: "alp_skill",
228
- description: "Propose a skill distilled from your lessons. ALP shows the whole skill to the user, and saves it to the user's skill library and gives it to the roles only when the user approves; any other answer comes back as feedback.",
274
+ description: "Propose a skill distilled from your lessons. ALP shows the whole skill to the user, and saves it to the user's skill library and gives it to the roles only when the user approves. Returns pending_approval with approvalId immediately; the decision (saved, or not saved with the user's feedback) arrives once by mail, even after your turn ends. Continue other work. A retry of the same draft returns its existing pending/result in this session; use a fresh requestId only to propose an identical draft again.",
229
275
  inputSchema: {
230
276
  type: "object",
231
277
  properties: {
@@ -234,16 +280,32 @@ var SKILL_TOOL = {
234
280
  body: { type: "string", description: "The SKILL.md body in Markdown, without frontmatter: when to use it, the method as steps, and the checks." },
235
281
  roles: { type: "array", items: { type: "string" }, description: "The roles whose work the skill guides, and only those: any of main (yourself), lead, peer, oracle, reviewer, supervisor, or a custom agent of this project." },
236
282
  lessons: { type: "array", items: { type: "string" }, description: "The exact text of the lessons this skill replaces; they leave the lessons files once it is saved." },
237
- replace: { type: "boolean", description: "Propose a new version of an existing skill of this name." }
283
+ replace: { type: "boolean", description: "Propose a new version of an existing skill of this name." },
284
+ requestId: { type: "string", description: "Optional session-scoped idempotency key (1-100 characters). Reuse with the same draft on retries; a fresh key explicitly proposes a new operation." }
238
285
  },
239
286
  required: ["name", "description", "body", "roles"],
240
287
  additionalProperties: false
241
288
  }
242
289
  };
290
+ var SKILL_RETIRE_TOOL = {
291
+ type: "function",
292
+ name: "alp_skill_retire",
293
+ description: "Propose to retire a skill of the user's skill library that is no longer needed. ALP shows the skill and the roles that lose it to the user, and only when the user approves moves it out of the library into retired-skills (kept, so it can be restored) and removes it from role-skills.json. Nothing changes without that approval. Returns pending_approval with approvalId immediately; the result arrives once by mail. Never delete skill files any other way.",
294
+ inputSchema: {
295
+ type: "object",
296
+ properties: {
297
+ name: { type: "string", description: "The skill directory name in the library." },
298
+ reason: { type: "string", description: "Why it is no longer needed, in one line (at most 300 characters)." },
299
+ requestId: { type: "string", description: "Optional session-scoped idempotency key (1-100 characters)." }
300
+ },
301
+ required: ["name", "reason"],
302
+ additionalProperties: false
303
+ }
304
+ };
243
305
  var ISSUE_TOOL = {
244
306
  type: "function",
245
307
  name: "alp_issue",
246
- description: "GitHub issues of this project (target project, from its origin remote) or of ALP itself (target alp). search needs no approval. create and comment show the whole draft to the user and post it only when the user approves; any other answer comes back as feedback.",
308
+ description: "GitHub issues of this project (target project, from its origin remote) or of ALP itself (target alp). search needs no approval. create and comment show the whole draft to the user and post it only when the user approves; create/comment return pending_approval with approvalId immediately, then send one decision/posting result by mail, even after your turn ends. Continue other work. Draft retries return the existing pending/result in this session. Use a fresh requestId only to intentionally propose an identical draft again; reuse one requestId with the exact draft to replay safely.",
247
309
  inputSchema: {
248
310
  type: "object",
249
311
  properties: {
@@ -253,6 +315,7 @@ var ISSUE_TOOL = {
253
315
  title: { type: "string", description: "For create." },
254
316
  body: { type: "string", description: "For create and comment: Markdown. Facts, reproduction and evidence; no secrets." },
255
317
  issue: { type: "integer", description: "For comment: the issue number." },
318
+ requestId: { type: "string", description: "Optional session-scoped idempotency key (1-100 characters). Reuse with the same draft on retries; a fresh key explicitly proposes a new operation." },
256
319
  labels: { type: "array", items: { type: "string" }, description: "For create: existing labels of the repository." }
257
320
  },
258
321
  required: ["action", "target"],
@@ -268,7 +331,7 @@ var TASK_FIELDS = {
268
331
  start: ["id"],
269
332
  close: ["id", "reason", "summary", "unverified"],
270
333
  reopen: ["id", "note"],
271
- gate: ["id", "kind", "note", "until", "ref"],
334
+ gate: ["id", "kind", "note", "until", "ref", "options"],
272
335
  clear: ["id", "gate", "note"],
273
336
  pour: ["formula", "vars", "parent"],
274
337
  formulas: [],
@@ -278,10 +341,11 @@ var TASK_FIELDS = {
278
341
  };
279
342
  var mainOf = (mapping) => mapping.team?.main ?? "main";
280
343
  var roleOf = (mapping, agent) => mapping.team ? mapping.team.members[agent]?.role : { lead: "lead", peer: "peer", oracle: "advisor", reviewer: "reviewer" }[agent];
344
+ var readOnlyMember = (mapping, agent) => READ_ONLY_AGENTS.includes(agent) || READ_ONLY_ROLES.includes(roleOf(mapping, agent) ?? "");
281
345
  function taskActions(mapping, parentAgent, role) {
282
346
  if (role === "supervisor") return ["show", "list"];
283
347
  if (!parentAgent && mapping.agent.name === mainOf(mapping)) return [...TASK_ACTIONS];
284
- return READ_ONLY_AGENTS.includes(mapping.agent.name) ? ["show"] : ["show", "ready"];
348
+ return readOnlyMember(mapping, mapping.agent.name) ? ["show"] : ["show", "ready"];
285
349
  }
286
350
  var taskLinks = (description) => ({
287
351
  type: "object",
@@ -320,9 +384,10 @@ function taskTool(actions) {
320
384
  kind: { type: "string", enum: GATE_KINDS, description: "For gate: human (the user approves; give the question as note), timer (until), gh:pr (until a pull request merges; ref), gh:run (until a workflow run succeeds; ref)." },
321
385
  until: { type: "string", description: "For a timer gate: an ISO time, or +30m, +2h, +3d." },
322
386
  ref: { type: "string", description: "For a gh:pr or gh:run gate: 123, or owner/repo#123." },
387
+ options: { type: "array", items: { type: "string", maxLength: 200 }, maxItems: 10, description: "For a human gate: up to 10 answers the user picks from, each at most 200 characters; picking any approves it, and you get the choice by mail. Default approve or reject." },
323
388
  gate: { type: "string", description: "For clear: the gate id, such as g1. You cannot clear a human gate; the user does." },
324
389
  formula: { type: "string", description: "For pour: the formula name, from action formulas." },
325
- vars: { type: "object", additionalProperties: { type: "string" }, description: "For pour: values of the formula variables." },
390
+ vars: { type: "object", additionalProperties: { type: "string", maxLength: POUR_VARS.string }, description: `For pour: values of the formula variables (at most ${POUR_VARS.items}), each at most ${POUR_VARS.string} characters.` },
326
391
  summary: { type: "string", description: "For close: the outcome and its evidence." },
327
392
  unverified: { type: "string", description: "For close as done when the task's last verification failed: why it is done anyway. Recorded on the task." },
328
393
  note: { type: "string", description: "For update and reopen: why." }
@@ -346,6 +411,24 @@ function taskBrief(task, writing) {
346
411
  "Your handoff moves this task to review for your requester to accept. List work you found outside the task under discovered; only main and the user create tasks."
347
412
  ].join("\n");
348
413
  }
414
+ var SCHEDULE_TOOL = {
415
+ type: "function",
416
+ name: "alp_schedule",
417
+ description: "Create, list, inspect or cancel a one-shot continuation of this main/root session. create proposes the exact prompt and ISO time with UTC offset for user approval. Jobs wake an idle main without a user message; timer gates only unblock tasks, and assignment notes do not schedule a wake. Scheduling a quota-reset continuation never guarantees provider availability: recheck actual availability before delegating.",
418
+ inputSchema: {
419
+ type: "object",
420
+ properties: {
421
+ action: { type: "string", enum: ["create", "list", "get", "cancel"] },
422
+ dueAt: { type: "string", description: "For create: ISO timestamp with Z or an explicit UTC offset." },
423
+ prompt: { type: "string", description: "For create: the exact continuation, at most 8000 characters." },
424
+ requestId: { type: "string", description: "For create: stable id for this approval proposal; reuse only for an identical draft." },
425
+ id: { type: "string", description: "For get/cancel: the scheduled job id." },
426
+ status: { type: "string", enum: ["pending", "delivered", "failed", "cancelled"] }
427
+ },
428
+ required: ["action"],
429
+ additionalProperties: false
430
+ }
431
+ };
349
432
  export {
350
433
  ASK_TOOL,
351
434
  BOARD_TOOL,
@@ -353,11 +436,15 @@ export {
353
436
  DISCARD_TOOL,
354
437
  HANDOFF_TOOL,
355
438
  ISSUE_TOOL,
439
+ LESSON_CURATE_TOOL,
356
440
  LESSON_TOOL,
357
441
  MERGE_TOOL,
358
442
  PIN_TOOL,
359
443
  RECALL_TOOL,
444
+ RESOLVE_TOOL,
445
+ SCHEDULE_TOOL,
360
446
  SEND_TOOL,
447
+ SKILL_RETIRE_TOOL,
361
448
  SKILL_TOOL,
362
449
  TASK_ACTIONS,
363
450
  TASK_FIELDS,
@@ -367,6 +454,7 @@ export {
367
454
  WAIT_TOOL,
368
455
  handoffList,
369
456
  mainOf,
457
+ readOnlyMember,
370
458
  roleOf,
371
459
  taskActions,
372
460
  taskBrief,
package/dist/transport.js CHANGED
@@ -2,6 +2,7 @@
2
2
  import { optionalRead, codexUsage } from "./runtime-context.js";
3
3
  import { spawn, execFile } from "node:child_process";
4
4
  import { createInterface } from "node:readline";
5
+ import { scriptCommand } from "@anhlp/alp-core/packaged";
5
6
  function unanswered(error) {
6
7
  return Object.assign(new Error(error.message), { outcomeUnknown: true });
7
8
  }
@@ -17,7 +18,8 @@ var CodexTransport = class {
17
18
  constructor(command, cwd, env, args = ["app-server", "--listen", "stdio://"]) {
18
19
  if (/\.(cmd|bat|ps1)$/i.test(command)) throw new Error("Codex executable must be a native binary, not a shell launcher");
19
20
  const script = process.platform === "win32" && /\.[cm]?js$/i.test(command);
20
- this.child = spawn(script ? process.execPath : command, script ? [command, ...args] : args, { cwd, env, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
21
+ const run = script ? scriptCommand(command, args) : { command, args, env: void 0 };
22
+ this.child = spawn(run.command, run.args, { cwd, env: run.env ? { ...env, ...run.env } : env, windowsHide: true, stdio: ["pipe", "pipe", "pipe"] });
21
23
  this.exit = new Promise((resolve) => {
22
24
  this.child.once("close", resolve);
23
25
  this.child.once("error", () => resolve());
@@ -39,10 +39,14 @@ export declare function createWorktree(workdir: string, root: string, id: string
39
39
  commit: string;
40
40
  }): Promise<Worktree>;
41
41
  /**
42
- * Checks out an assignment's existing branch again at its worktree's place, after
43
- * reclaimWorktrees committed and removed it, so the assignment continues there.
42
+ * Continues an assignment in its worktree after a restart. A worktree that is still valid
43
+ * is reused as is, whatever it holds. A directory left without valid git metadata (a crash
44
+ * mid-write) is never deleted: it moves aside to `preserved` and the branch is checked out
45
+ * again at its place.
44
46
  */
45
- export declare function reattachWorktree(worktree: Worktree): Promise<Worktree>;
47
+ export declare function reattachWorktree(worktree: Worktree): Promise<Worktree & {
48
+ preserved?: string;
49
+ }>;
46
50
  /** A digest of a checkout's state: HEAD, its uncommitted changes, and the names of untracked files. */
47
51
  export declare function checkoutFingerprint(checkout: string): Promise<string | undefined>;
48
52
  /**
@@ -77,11 +81,33 @@ export declare function mergeWorktree(worktree: Worktree, change: WorktreeChange
77
81
  export declare function removeWorktree(worktree: Worktree, { deleteBranch }?: {
78
82
  deleteBranch?: boolean | undefined;
79
83
  }): Promise<void>;
84
+ /**
85
+ * Why reclaimWorktrees left a directory in place: `invalid`, not the top level of a working git
86
+ * worktree; `not-linked`, a repository of its own rather than a worktree of one; `other-branch`,
87
+ * another branch or a detached HEAD, which does not hold this work; `commit-failed`, its work could
88
+ * not be committed (`detail` says why); `uncommitted`, something was still not committed after
89
+ * that; `ignored-files`, its work is committed but it holds ignored files that exist nowhere else.
90
+ */
91
+ export type LeftWorktree = {
92
+ name: string;
93
+ path: string;
94
+ reason: 'invalid' | 'not-linked' | 'other-branch' | 'commit-failed' | 'uncommitted' | 'ignored-files';
95
+ branch?: string;
96
+ detail?: string;
97
+ files?: string[];
98
+ };
80
99
  /**
81
100
  * After a crash: commits work left in worktrees under `root` to their branches and
82
- * removes the directories. Returns the branches that were kept.
101
+ * removes the directories. Returns the branches that were kept, and the directories left in
102
+ * place with the reason. A directory is removed only once everything in it is committed to
103
+ * its own `alp/<name>` branch and it holds no ignored file to keep (`.env*`); any other one
104
+ * stays, so recovery reuses or preserves it and nothing uncommitted is lost. Stale locks a
105
+ * killed git command left in such a worktree are removed first (clearStaleLocks).
83
106
  */
84
- export declare function reclaimWorktrees(root: string): Promise<string[]>;
107
+ export declare function reclaimWorktrees(root: string): Promise<{
108
+ kept: string[];
109
+ left: LeftWorktree[];
110
+ }>;
85
111
  /**
86
112
  * A disposable copy of a checkout for an assignment that may build and test but
87
113
  * must not touch the requester's tree (ALPD §26): a detached worktree at the
package/dist/workspace.js CHANGED
@@ -1,7 +1,7 @@
1
1
  // packages/runtime/src/workspace.ts
2
2
  import { spawn } from "node:child_process";
3
3
  import { createHash } from "node:crypto";
4
- import { copyFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
4
+ import { copyFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, stat, symlink, unlink, writeFile } from "node:fs/promises";
5
5
  import os from "node:os";
6
6
  import path from "node:path";
7
7
  var IDENTITY = ["-c", "user.name=ALP", "-c", "user.email=alp@localhost", "-c", "commit.gpgsign=false"];
@@ -103,13 +103,29 @@ async function createWorktree(workdir, root, id, from) {
103
103
  const relative = path.relative(checkout, await realpath(workdir));
104
104
  return { checkout, path: target, workdir: path.join(target, relative), branch, base, ...fingerprint ? { fingerprint } : {} };
105
105
  }
106
+ async function validWorktree(directory) {
107
+ const top = await git(directory, ["rev-parse", "--show-toplevel"]).catch(() => void 0);
108
+ if (top?.code !== 0) return false;
109
+ const [a, b] = await Promise.all([realpath(top.stdout.trim()).catch(() => ""), realpath(directory).catch(() => directory)]);
110
+ return a === b && (await git(directory, ["status", "--porcelain"])).code === 0;
111
+ }
106
112
  async function reattachWorktree(worktree) {
113
+ const exists = !!await stat(worktree.path).catch(() => void 0);
114
+ if (exists && await validWorktree(worktree.path)) {
115
+ const dirs = await gitDirs(worktree.path);
116
+ if (dirs) await clearStaleLocks(dirs, worktree.branch);
117
+ return worktree;
118
+ }
107
119
  if (!await branchExists(worktree.checkout, worktree.branch)) throw new Error(`Branch ${worktree.branch} of the worktree no longer exists`);
108
- if (await stat(worktree.path).catch(() => void 0)) return worktree;
120
+ let preserved;
121
+ if (exists) {
122
+ preserved = `${worktree.path}.preserved-${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}`;
123
+ await rename(worktree.path, preserved);
124
+ }
109
125
  await mkdir(path.dirname(worktree.path), { recursive: true, mode: 448 });
110
126
  await git(worktree.checkout, ["worktree", "prune"]);
111
127
  await checked(worktree.checkout, ["worktree", "add", "--quiet", worktree.path, worktree.branch]);
112
- return worktree;
128
+ return preserved ? { ...worktree, preserved } : worktree;
113
129
  }
114
130
  async function checkoutFingerprint(checkout) {
115
131
  const head = await git(checkout, ["rev-parse", "--verify", "HEAD"]);
@@ -175,27 +191,92 @@ async function removeWorktree(worktree, { deleteBranch = false } = {}) {
175
191
  await git(worktree.checkout, ["worktree", "prune"]);
176
192
  if (deleteBranch) await git(worktree.checkout, ["branch", "-D", worktree.branch]);
177
193
  }
194
+ async function gitDirs(target) {
195
+ const result = await git(target, ["rev-parse", "--path-format=absolute", "--absolute-git-dir", "--git-common-dir"]);
196
+ if (result.code !== 0) return void 0;
197
+ const [own, common] = result.stdout.trim().split("\n").map((line) => path.resolve(line.trim()));
198
+ return own && common ? { own, common } : void 0;
199
+ }
200
+ var SHARED_LOCK_STALE_MS = 1e4;
201
+ async function clearStaleLocks(dirs, branch) {
202
+ if (dirs.own === dirs.common) return;
203
+ const own = (await readdir(dirs.own).catch(() => [])).filter((name) => name.endsWith(".lock"));
204
+ const refs = (await readdir(path.join(dirs.own, "refs"), { recursive: true }).catch(() => [])).filter((name) => name.endsWith(".lock")).map((name) => path.join("refs", name));
205
+ for (const name of [...own, ...refs]) await unlink(path.join(dirs.own, name)).catch(() => {
206
+ });
207
+ const shared = `${path.join(dirs.common, "refs", "heads", ...branch.split("/"))}.lock`;
208
+ const info = await lstat(shared).catch(() => void 0);
209
+ if (info?.isFile() && Date.now() - info.mtimeMs >= SHARED_LOCK_STALE_MS) await unlink(shared).catch(() => {
210
+ });
211
+ }
212
+ var KEEP_IGNORED = /^\.env/;
213
+ async function ignoredToKeep(target) {
214
+ const result = await git(target, ["ls-files", "-z", "--others", "--ignored", "--exclude-standard", "--directory"]);
215
+ if (result.code !== 0) return void 0;
216
+ return result.stdout.split("\0").filter(Boolean).map((entry) => entry.replace(/\/$/, "")).filter((entry) => KEEP_IGNORED.test(path.posix.basename(entry))).sort();
217
+ }
218
+ var firstLine = (result) => (result.stderr || result.stdout).trim().split("\n")[0] ?? "";
178
219
  async function reclaimWorktrees(root) {
179
220
  const kept = [];
221
+ const left = [];
180
222
  const entries = await readdir(root).catch(() => []);
181
223
  for (const name of entries) {
182
224
  const target = path.join(root, name);
225
+ const leave = (reason, extra = {}) => {
226
+ left.push({ name, path: target, reason, ...extra });
227
+ };
183
228
  if (!(await stat(target).catch(() => void 0))?.isDirectory()) continue;
184
- const common = await git(target, ["rev-parse", "--path-format=absolute", "--git-common-dir"]).catch(() => void 0);
185
- if (common?.code !== 0) {
186
- await rm(target, { recursive: true, force: true });
229
+ if (!await validWorktree(target)) {
230
+ leave("invalid");
231
+ continue;
232
+ }
233
+ const dirs = await gitDirs(target);
234
+ if (!dirs) {
235
+ leave("invalid");
236
+ continue;
237
+ }
238
+ if (dirs.own === dirs.common) {
239
+ leave("not-linked");
240
+ continue;
241
+ }
242
+ const checkout = path.dirname(dirs.common);
243
+ const ref = await git(target, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
244
+ const branch = ref.stdout.trim();
245
+ if (ref.code !== 0 || branch !== `alp/${name}`) {
246
+ leave("other-branch", ref.code === 0 && branch ? { branch } : {});
247
+ continue;
248
+ }
249
+ await clearStaleLocks(dirs, branch);
250
+ const added = await git(target, ["add", "-A"]);
251
+ if (added.code !== 0) {
252
+ leave("commit-failed", { branch, detail: firstLine(added) });
187
253
  continue;
188
254
  }
189
- const checkout = path.dirname(common.stdout.trim());
190
- const branch = (await git(target, ["rev-parse", "--abbrev-ref", "HEAD"])).stdout.trim();
191
- await git(target, ["add", "-A"]);
192
255
  if ((await git(target, ["diff", "--cached", "--quiet"])).code === 1) {
193
- await git(target, [...IDENTITY, "commit", "--quiet", "--no-verify", "-m", "alp: work left by an interrupted assignment"]);
256
+ const committed = await git(target, [...IDENTITY, "commit", "--quiet", "--no-verify", "-m", "alp: work left by an interrupted assignment"]);
257
+ if (committed.code !== 0) {
258
+ leave("commit-failed", { branch, detail: firstLine(committed) });
259
+ continue;
260
+ }
261
+ }
262
+ const status = await git(target, ["status", "--porcelain", "--ignored=no"]);
263
+ if (status.code !== 0 || status.stdout.trim()) {
264
+ leave("uncommitted", { branch });
265
+ continue;
266
+ }
267
+ const ignored = await ignoredToKeep(target);
268
+ if (!ignored) {
269
+ leave("ignored-files", { branch, detail: "git could not list its ignored files" });
270
+ continue;
271
+ }
272
+ if (ignored.length) {
273
+ leave("ignored-files", { branch, files: ignored });
274
+ continue;
194
275
  }
195
276
  await removeWorktree({ checkout, path: target, workdir: target, branch, base: "" });
196
277
  kept.push(branch);
197
278
  }
198
- return kept;
279
+ return { kept, left };
199
280
  }
200
281
  async function createCopy(workdir, root, id) {
201
282
  const checkout = await checkoutOf(workdir);
@@ -4,6 +4,7 @@ import type { RuntimeOptions } from './contracts.js';
4
4
  import type { Session, Assignment } from './session-state.js';
5
5
  type WorktreeContext = {
6
6
  options: RuntimeOptions;
7
+ releaseResult(assignmentId: string): Promise<void>;
7
8
  leases: Map<string, {
8
9
  assignment: string;
9
10
  agent: string;
@@ -15,7 +16,7 @@ type WorktreeContext = {
15
16
  touchTask(rootId: string, id: string): void;
16
17
  };
17
18
  /** Checkout mutation and verification retain one shared queue per checkout. */
18
- export declare function createWorktreeDomain({ options, leases, rootOf, lineage, runLog, runHooks, touchTask }: WorktreeContext): {
19
+ export declare function createWorktreeDomain({ options, leases, releaseResult, rootOf, lineage, runLog, runHooks, touchTask }: WorktreeContext): {
19
20
  settleWorktree: (parentId: string, parent: Session, assignment: Assignment) => Promise<{
20
21
  branch: string;
21
22
  files: never[];
@@ -8,7 +8,7 @@ import { writes } from "./catalog.js";
8
8
  import { nativeEnvironment } from "./providers.js";
9
9
  import { mainOf } from "./tools.js";
10
10
  import { errorData, plainObject, toolResult } from "./tool-results.js";
11
- function createWorktreeDomain({ options, leases, rootOf, lineage, runLog, runHooks, touchTask }) {
11
+ function createWorktreeDomain({ options, leases, releaseResult, rootOf, lineage, runLog, runHooks, touchTask }) {
12
12
  const merging = /* @__PURE__ */ new Map();
13
13
  async function settleWorktree(parentId, parent, assignment) {
14
14
  const worktree = assignment.worktree;
@@ -16,6 +16,7 @@ function createWorktreeDomain({ options, leases, rootOf, lineage, runLog, runHoo
16
16
  const change = await commitWorktree(worktree, `alp: ${assignment.agent} assignment ${assignment.id}`);
17
17
  if (!change.files.length) {
18
18
  await removeWorktree(worktree, { deleteBranch: true });
19
+ await releaseResult(assignment.id);
19
20
  return { branch: worktree.branch, files: [], note: "No changes; the worktree was removed" };
20
21
  }
21
22
  const described = { branch: worktree.branch, base: worktree.base, commit: change.commit, files: change.files, stat: change.stat };
@@ -44,6 +45,7 @@ function createWorktreeDomain({ options, leases, rootOf, lineage, runLog, runHoo
44
45
  if (action === "discard") {
45
46
  session.worktrees.delete(args.assignmentId);
46
47
  await removeWorktree(worktree, { deleteBranch: true });
48
+ await releaseResult(args.assignmentId);
47
49
  runLog(rootOf(sessionId), { event: "worktree.discarded", assignmentId: args.assignmentId, branch: worktree.branch });
48
50
  return toolResult(true, { discarded: args.assignmentId, branch: worktree.branch });
49
51
  }
@@ -104,6 +106,7 @@ ${refused}`, branch: worktree.branch, next: `Fix what it reports in a new assign
104
106
  return toolResult(false, { error: errorData(error).message, branch: worktree.branch, next: "Merge the branch yourself, or alp_discard it" });
105
107
  }
106
108
  await removeWorktree(worktree, { deleteBranch: merged.status !== "conflicts" });
109
+ if (merged.status !== "conflicts") await releaseResult(args.assignmentId);
107
110
  runLog(rootId, { event: "worktree.merged", assignmentId: args.assignmentId, branch: worktree.branch, ...merged });
108
111
  let checked;
109
112
  if (config && args.skipVerify === void 0 && merged.status === "applied" && moved) {
@@ -0,0 +1,2 @@
1
+ /** Tells `onError` of a failed write (t-e80a); what it throws must not change how the write failed. */
2
+ export declare function tell(onError: (error: unknown) => void, error: unknown): void;
@@ -0,0 +1,10 @@
1
+ // packages/runtime/src/write-error.ts
2
+ function tell(onError, error) {
3
+ try {
4
+ onError(error);
5
+ } catch {
6
+ }
7
+ }
8
+ export {
9
+ tell
10
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anhlp/alp-runtime",
3
- "version": "0.0.0-beta.2",
3
+ "version": "0.0.1-beta.10",
4
4
  "type": "module",
5
5
  "description": "ALP runtime module",
6
6
  "files": [
@@ -25,6 +25,14 @@
25
25
  "types": "./dist/antigravity-transport.d.ts",
26
26
  "default": "./dist/antigravity-transport.js"
27
27
  },
28
+ "./attachments": {
29
+ "alp-source": {
30
+ "types": "./src/attachments.ts",
31
+ "default": "./src/attachments.ts"
32
+ },
33
+ "types": "./dist/attachments.d.ts",
34
+ "default": "./dist/attachments.js"
35
+ },
28
36
  "./board": {
29
37
  "alp-source": {
30
38
  "types": "./src/board.ts",
@@ -222,13 +230,13 @@
222
230
  "node": ">=22.12"
223
231
  },
224
232
  "dependencies": {
225
- "@anhlp/alp-core": "0.0.0-beta.2",
226
- "@anhlp/alp-protocol": "0.0.0-beta.2",
233
+ "@anhlp/alp-core": "0.0.1-beta.10",
234
+ "@anhlp/alp-protocol": "0.0.1-beta.10",
227
235
  "@anthropic-ai/claude-agent-sdk": "^0.3.292",
228
236
  "@modelcontextprotocol/sdk": "^1.32.1",
229
237
  "@agentclientprotocol/sdk": "1.7.0",
230
238
  "smol-toml": "1.9.0",
231
- "zod": "4.4.3"
239
+ "zod": "4.6.7"
232
240
  },
233
241
  "scripts": {
234
242
  "build": "node ../../scripts/build-workspace.mjs runtime",