@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
@@ -5,14 +5,14 @@ import type { ResolvedSession, RuntimeKind } from './resolve.js';
5
5
  import { models, thinkingOptionsFor } from './catalog.js';
6
6
  import { claudeSandboxAvailable, SKILL_PLUGIN } from './claude-transport.js';
7
7
  import { languageInstruction } from './language.js';
8
- import { HANDOFF_TOOL, WAIT_TOOL, SEND_TOOL, MERGE_TOOL, VERIFY_TOOL, DISCARD_TOOL, CANCEL_TOOL, RECALL_TOOL, PIN_TOOL, BOARD_TOOL, UNPIN_TOOL, ASK_TOOL, LESSON_TOOL, SKILL_TOOL, ISSUE_TOOL, SCHEDULE_TOOL, mainOf, taskActions, taskTool } from './tools.js';
8
+ import { antigravityModeText } from './antigravity-transport.js';
9
+ import { HANDOFF_TOOL, WAIT_TOOL, SEND_TOOL, MERGE_TOOL, VERIFY_TOOL, DISCARD_TOOL, RESOLVE_TOOL, CANCEL_TOOL, RECALL_TOOL, PIN_TOOL, BOARD_TOOL, UNPIN_TOOL, ASK_TOOL, LESSON_TOOL, LESSON_CURATE_TOOL, SKILL_TOOL, ISSUE_TOOL, SCHEDULE_TOOL, mainOf, taskActions, taskTool } from './tools.js';
9
10
 
10
11
  import { COMPACT_SHARE } from './runtime-context.js';
11
12
 
12
13
  /** The mode the native harness runs with: a session in a copy writes the copy, though ALP treats it as read-only. */
13
14
  export const nativeMode = (mapping: Pick<ResolvedSession, 'mode' | 'copy'> & Partial<Pick<ResolvedSession, 'runtimeKind' | 'antigravity'>>) =>
14
- mapping.runtimeKind === 'antigravity' && mapping.mode === 'read-only' && mapping.antigravity?.readOnlyMode === 'instructions'
15
- ? 'full-access' : mapping.copy ? 'workspace-write' : mapping.mode;
15
+ mapping.copy ? 'workspace-write' : mapping.mode;
16
16
 
17
17
  /** The OS sandbox ALP puts a Claude session's Bash in: its profile's base, or the copy it works in. */
18
18
  export function claudeFloor(mapping: Pick<ResolvedSession, 'mode' | 'copy' | 'permissions' | 'runtimeKind'>): 'read-only' | 'workspace-write' | undefined {
@@ -43,9 +43,8 @@ export function permissionNote(mapping: Pick<ResolvedSession, 'mode' | 'permissi
43
43
  const notes = [
44
44
  // ALPD §46: ALP has no sandbox around an ACP agent; it answers the agent's permission requests.
45
45
  ...(mapping.runtimeKind === 'acp' ? [`ALP's tools (alp_*) come from the MCP server named alp. ALP answers your permission requests by your ${mapping.mode} mode: ${mapping.mode === 'read-only' ? 'reading and searching only' : mapping.mode === 'workspace-write' ? `reading, running commands, and changing files inside ${mapping.workdir} only` : 'everything'}. Ask permission before every tool use that changes something, even where you would not need to.`] : []),
46
- ...(mapping.runtimeKind === 'antigravity' ? ["ALP's tools (alp_*) come from the MCP server named alp. Antigravity runs natively with full access.",
46
+ ...(mapping.runtimeKind === 'antigravity' ? [`ALP's tools (alp_*) come from the MCP server named alp. Your mode is ${mapping.mode}: ${antigravityModeText(mapping.mode)}`,
47
47
  'External MCP tools supplied by ALP also come from the MCP server named alp. Discover its tools: aliases beginning mcp__ and their descriptions identify the original server and tool. Use those aliases when calling the tools.',
48
- ...(mapping.mode === 'read-only' ? ['Read-only is emulated by instructions, not enforced by an OS sandbox. Your role is to read, analyze, advise and report only. Do not edit, create, delete or rename files. Do not run commands, builds, tests or native tools that mutate files, repositories, configuration or external state. Report any work that requires changes to your requester. ALP still restricts its own tools according to your read-only role.'] : []),
49
48
  ] : []),
50
49
  ...(mapping.copy ? [`You work in a disposable copy of your requester's tree at ${mapping.workdir}: the same files and git state, uncommitted changes included${mapping.copyOf ? `, mirroring ${mapping.copyOf}` : ''}. Write, build and test there; nothing you change reaches the requester, and the copy is removed when you finish. Where your brief names a path${mapping.copyOf ? ` under ${mapping.copyOf}` : ''}, use the same path in your copy. Never run a command in, or write to, the requester's tree.`] : []),
51
50
  ...(floor ? [`Bash runs in an OS sandbox: ${floor === 'read-only' ? 'it writes nothing but temporary files' : `it writes only ${mapping.workdir} and temporary files`}, and has no network. Run any command you need for your work in it.${profile?.allow.length || profile?.ask.length || profile?.beyondMode === 'ask' ? ' To run a command outside it (one your profile allows, or one for the user to approve), set dangerouslyDisableSandbox on that Bash call: ALP decides, and asks the user when your profile says so. A sandbox error (Operation not permitted, no network) is not a refusal by the user: run that same command again with dangerouslyDisableSandbox rather than report it refused.' : ''}`] : []),
@@ -163,6 +162,7 @@ export function nativeSessionConfig(
163
162
  `At most ${mapping.workflow.maxPeers} peers may run concurrently. Concurrent peers must be read-only or isolated: pass isolation "worktree" to give a writing peer its own git worktree. ` +
164
163
  'A worktree result lists its branch and changed files; apply it with alp_merge (uncommitted, conflicts left as markers) or drop it with alp_discard, then verify. ' +
165
164
  'Writers in this shared checkout run one at a time. ' +
165
+ "A writer's change outside a worktree stays a result ALP keeps, and its checkout cannot be removed, until you record with alp_resolve that you applied, discarded or acknowledged it. " +
166
166
  'To learn why a finished assignment did something, ask it with alp_recall rather than guessing from its handoff. ' +
167
167
  'When the project configures verify commands, ALP runs them before alp_merge applies a change, and after a writer in your checkout finishes; a failed check applies nothing. To fix a failed worktree change, delegate again with continueFrom set to its assignmentId. ' +
168
168
  'Do not run shell/file mutations in parallel with delegation. ' +
@@ -196,7 +196,7 @@ export function nativeSessionConfig(
196
196
  `Oracle runs on ${mapping.oracleModels.join(' or ')}; pass one as model (effort follows the team's oracle settings, otherwise high). For two independent opinions, start one oracle on each model with wait: false and compare their advice. If the model you need is unavailable, say so rather than choosing another. Usage context is advisory, may be unavailable or stale; never infer quota from token counts. Respect known exhausted limits and report them.`,
197
197
  ...(supervised
198
198
  ? ['A supervisor reviews your process after each turn. Its notes ask about process mistakes: answer them in your reply, then record each lesson with alp_lesson (scope project for this project, user for every project). Do not argue a note away; when it is wrong, say why in one line. ' +
199
- 'When three or more lessons cover one theme, or a lesson recurs, distill them into a skill with alp_skill: a method with steps and checks, listing the lessons it replaces. Scope it to the roles whose work it guides: yourself, lead, peer, oracle, reviewer, supervisor, or a custom agent; a lesson about briefing peers is yours, a lesson about verifying a change belongs to whoever makes it. The user approves it first.']
199
+ 'When three or more lessons cover one theme, or a lesson recurs, distill them into a skill with alp_skill: a method with steps and checks, listing the lessons it replaces. Scope it to the roles whose work it guides: yourself, lead, peer, oracle, reviewer, supervisor, or a custom agent; a lesson about briefing peers is yours, a lesson about verifying a change belongs to whoever makes it. The user approves it first. To merge, shorten or remove lessons use alp_lesson_curate (the curate skill), never a file edit.']
200
200
  : []),
201
201
  ...(!parentAgent && mapping.agent.name === mainOf(mapping)
202
202
  ? ['When you find a problem outside the task that is worth tracking (a bug or gap in this project, or in ALP itself: its process, tools, agent instructions or runtime), search with alp_issue action search, then propose a comment on a matching issue or a new issue. Include facts, reproduction and evidence, never secrets. The user approves every post; never post issues or comments any other way, such as with gh in a shell.']
@@ -289,10 +289,10 @@ export function nativeSessionConfig(
289
289
  },
290
290
  ]
291
291
  : []),
292
- ...(targets.length ? [WAIT_TOOL, CANCEL_TOOL, MERGE_TOOL, DISCARD_TOOL, VERIFY_TOOL, RECALL_TOOL] : []),
292
+ ...(targets.length ? [WAIT_TOOL, CANCEL_TOOL, MERGE_TOOL, DISCARD_TOOL, RESOLVE_TOOL, VERIFY_TOOL, RECALL_TOOL] : []),
293
293
  ...(targets.length || parentAgent ? [SEND_TOOL] : []),
294
294
  ...(parentAgent ? [HANDOFF_TOOL] : []),
295
- ...(supervised ? [LESSON_TOOL, SKILL_TOOL] : []),
295
+ ...(supervised ? [LESSON_TOOL, LESSON_CURATE_TOOL, SKILL_TOOL] : []),
296
296
  ...(!parentAgent && mapping.agent.name === mainOf(mapping) ? [ISSUE_TOOL, SCHEDULE_TOOL] : []),
297
297
  ASK_TOOL,
298
298
  PIN_TOOL,
@@ -7,7 +7,7 @@ import type { Handoff } from './handoff.js';
7
7
  import type { SessionUsage } from './events.js';
8
8
 
9
9
  /** The pause that stopped a turn; a matching resume may arrive before its interruption settles. */
10
- export type ParkPause = { scope: RuntimeKind | 'all'; resumed?: boolean };
10
+ export type ParkPause = { scope: RuntimeKind | 'all'; resumed?: boolean; /** The pause was alpd's, for a full disk (t-2831). */ disk?: boolean };
11
11
  export type Parked = { reason: string; since: number; prompt?: string; pause?: ParkPause };
12
12
 
13
13
  export type Session = {
@@ -70,6 +70,20 @@ export type Session = {
70
70
  usage?: SessionUsage;
71
71
  /** The context advisory was given since the context last emptied (ALPD §57). */
72
72
  contextLevel?: number;
73
+ /** How full its context last was, 0..1 (t-0e56). */
74
+ contextFill?: number;
75
+ /** The user asked to compact it; done at the next turn boundary (t-0e56). */
76
+ compactRequested?: boolean;
77
+ /** A compaction in progress (t-0e56): main writing its checkpoint, then the runtime compacting. */
78
+ compacting?: { phase: 'checkpoint' | 'native' | 'fresh'; trigger: 'auto' | 'manual'; checkpoint?: string; startedAt: number; /** Its checkpoint turn was started. */ turn?: boolean; /** The runtime took the native request. */ requested?: boolean };
79
+ /** Compacted since main's last turn began: usage reported meanwhile may still count the old context. */
80
+ compactCooling?: boolean;
81
+ /** When its last compaction failed: automatic ones wait COMPACT_RETRY_MS after it. */
82
+ compactFailedAt?: number;
83
+ /** The user's prompts held while it compacts, sent after (t-0e56). */
84
+ compactBuffer?: import('./contracts.js').PromptInput[];
85
+ /** The user's last message to it, seeded into a fresh conversation after a compaction (t-0e56). */
86
+ lastUserText?: string;
73
87
  /** An assignment's brief as its requester gave it, repeated after a compaction. */
74
88
  brief?: string;
75
89
  /** The skills it has used, each logged once (ALPD §59). */
package/src/tools.ts CHANGED
@@ -1,8 +1,10 @@
1
1
  import { CLOSE_REASONS, GATE_KINDS, TASK_STATUSES, TASK_TYPES, TASKS_DIR, type Task } from '@anhlp/alp-core/tasks';
2
2
  import { READ_ONLY_AGENTS, type ResolvedSession } from './resolve.js';
3
3
 
4
- import { PIN_KINDS } from './board.js';
4
+ import { PIN_KINDS, PIN_PATH_CHARS, PIN_PATHS } from './board.js';
5
+ import { POUR_VARS } from './input-limits.js';
5
6
  import { RECALL_KEEP_MS } from './recall.js';
7
+ import { RESULT_OUTCOMES } from './assignment-results.js';
6
8
  import { HANDOFF_OUTCOMES, VERDICT_RESULTS, CRITERION_RESULTS, SEVERITIES } from './handoff.js';
7
9
 
8
10
  export const handoffList = (description: string) => ({ type: 'array', items: { type: 'string' }, description });
@@ -133,6 +135,22 @@ export const DISCARD_TOOL = {
133
135
  },
134
136
  };
135
137
 
138
+ export const RESOLVE_TOOL = {
139
+ type: 'function',
140
+ name: 'alp_resolve',
141
+ 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.",
142
+ inputSchema: {
143
+ type: 'object',
144
+ properties: {
145
+ assignmentId: { type: 'string' },
146
+ outcome: { type: 'string', enum: RESULT_OUTCOMES },
147
+ note: { type: 'string', description: 'What you did with it, for the archive and the run log.' },
148
+ },
149
+ required: ['assignmentId', 'outcome'],
150
+ additionalProperties: false,
151
+ },
152
+ };
153
+
136
154
  export const CANCEL_TOOL = {
137
155
  type: 'function',
138
156
  name: 'alp_cancel',
@@ -173,7 +191,7 @@ export const PIN_TOOL = {
173
191
  properties: {
174
192
  kind: { type: 'string', enum: PIN_KINDS },
175
193
  body: { type: 'string', description: 'For a claim, what you are changing; otherwise the decision or finding itself.' },
176
- paths: { type: 'array', items: { type: 'string' }, description: 'Project-relative files or directories. Required for a claim.' },
194
+ 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.` },
177
195
  },
178
196
  required: ['kind', 'body'],
179
197
  additionalProperties: false,
@@ -187,7 +205,7 @@ export const BOARD_TOOL = {
187
205
  inputSchema: {
188
206
  type: 'object',
189
207
  properties: {
190
- kinds: { type: 'array', items: { type: 'string', enum: PIN_KINDS } },
208
+ kinds: { type: 'array', items: { type: 'string', enum: PIN_KINDS }, maxItems: PIN_KINDS.length },
191
209
  limit: { type: 'integer', description: 'Most recent decisions and findings to return. Default 30.' },
192
210
  },
193
211
  additionalProperties: false,
@@ -237,6 +255,35 @@ export const LESSON_TOOL = {
237
255
  },
238
256
  };
239
257
 
258
+ export const LESSON_CURATE_TOOL = {
259
+ type: 'function',
260
+ name: 'alp_lesson_curate',
261
+ 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.',
262
+ inputSchema: {
263
+ type: 'object',
264
+ properties: {
265
+ changes: {
266
+ type: 'array',
267
+ description: 'At most 50 changes.',
268
+ items: {
269
+ type: 'object',
270
+ properties: {
271
+ scope: { type: 'string', enum: ['project', 'user'] },
272
+ remove: { type: 'array', items: { type: 'string' }, description: 'The exact text of each lesson to remove, with or without its date.' },
273
+ add: { type: 'string', description: 'One rule, at most 600 characters, that replaces them.' },
274
+ reason: { type: 'string', description: 'Why, in one line.' },
275
+ },
276
+ required: ['scope', 'remove'],
277
+ additionalProperties: false,
278
+ },
279
+ },
280
+ requestId: { type: 'string', description: 'Optional session-scoped idempotency key (1-100 characters).' },
281
+ },
282
+ required: ['changes'],
283
+ additionalProperties: false,
284
+ },
285
+ };
286
+
240
287
  export const SKILL_TOOL = {
241
288
  type: 'function',
242
289
  name: 'alp_skill',
@@ -288,7 +335,7 @@ export const TASK_FIELDS: Record<TaskAction, string[]> = {
288
335
  start: ['id'],
289
336
  close: ['id', 'reason', 'summary', 'unverified'],
290
337
  reopen: ['id', 'note'],
291
- gate: ['id', 'kind', 'note', 'until', 'ref'],
338
+ gate: ['id', 'kind', 'note', 'until', 'ref', 'options'],
292
339
  clear: ['id', 'gate', 'note'],
293
340
  pour: ['formula', 'vars', 'parent'],
294
341
  formulas: [],
@@ -351,9 +398,10 @@ export function taskTool(actions: TaskAction[]) {
351
398
  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).' },
352
399
  until: { type: 'string', description: 'For a timer gate: an ISO time, or +30m, +2h, +3d.' },
353
400
  ref: { type: 'string', description: 'For a gh:pr or gh:run gate: 123, or owner/repo#123.' },
401
+ 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.' },
354
402
  gate: { type: 'string', description: 'For clear: the gate id, such as g1. You cannot clear a human gate; the user does.' },
355
403
  formula: { type: 'string', description: 'For pour: the formula name, from action formulas.' },
356
- vars: { type: 'object', additionalProperties: { type: 'string' }, description: 'For pour: values of the formula variables.' },
404
+ 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.` },
357
405
  summary: { type: 'string', description: 'For close: the outcome and its evidence.' },
358
406
  unverified: { type: 'string', description: "For close as done when the task's last verification failed: why it is done anyway. Recorded on the task." },
359
407
  note: { type: 'string', description: 'For update and reopen: why.' },
package/src/transport.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { optionalRead, codexUsage } from './runtime-context.js';
2
2
  import { spawn, execFile, type ChildProcessWithoutNullStreams } from 'node:child_process';
3
3
  import { createInterface } from 'node:readline';
4
+ import { scriptCommand } from '@anhlp/alp-core/packaged';
4
5
 
5
6
  /**
6
7
  * A request that was written but never answered: the process died, timed out or closed, so
@@ -25,7 +26,8 @@ export class CodexTransport {
25
26
  if (/\.(cmd|bat|ps1)$/i.test(command)) throw new Error('Codex executable must be a native binary, not a shell launcher');
26
27
  // Windows cannot exec a script by its shebang; a JavaScript command (the fake Codex of the tests) runs under this Node, still without a shell.
27
28
  const script = process.platform === 'win32' && /\.[cm]?js$/i.test(command);
28
- this.child = spawn(script ? process.execPath : command, script ? [command, ...args] : args, { cwd, env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
29
+ const run = script ? scriptCommand(command, args) : { command, args, env: undefined };
30
+ this.child = spawn(run.command, run.args, { cwd, env: run.env ? { ...env, ...run.env } : env, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
29
31
  this.exit = new Promise(resolve => { this.child.once('close', resolve); this.child.once('error', () => resolve()); });
30
32
  // Drain diagnostics without writing credentials or user configuration to the host log.
31
33
  this.child.stderr.on('data', () => {});
package/src/workspace.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { createHash } from 'node:crypto';
3
- import { copyFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rm, stat, symlink, unlink, writeFile } from 'node:fs/promises';
3
+ import { copyFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, stat, symlink, unlink, writeFile } from 'node:fs/promises';
4
4
  import os from 'node:os';
5
5
  import path from 'node:path';
6
6
 
@@ -140,17 +140,40 @@ export async function createWorktree(workdir: string, root: string, id: string,
140
140
  return { checkout, path: target, workdir: path.join(target, relative), branch, base, ...(fingerprint ? { fingerprint } : {}) };
141
141
  }
142
142
 
143
+ /** Whether `directory` is the top level of a working git worktree. */
144
+ async function validWorktree(directory: string) {
145
+ const top = await git(directory, ['rev-parse', '--show-toplevel']).catch(() => undefined);
146
+ if (top?.code !== 0) return false;
147
+ const [a, b] = await Promise.all([realpath(top.stdout.trim()).catch(() => ''), realpath(directory).catch(() => directory)]);
148
+ return a === b && (await git(directory, ['status', '--porcelain'])).code === 0;
149
+ }
150
+
143
151
  /**
144
- * Checks out an assignment's existing branch again at its worktree's place, after
145
- * reclaimWorktrees committed and removed it, so the assignment continues there.
152
+ * Continues an assignment in its worktree after a restart. A worktree that is still valid
153
+ * is reused as is, whatever it holds. A directory left without valid git metadata (a crash
154
+ * mid-write) is never deleted: it moves aside to `preserved` and the branch is checked out
155
+ * again at its place.
146
156
  */
147
- export async function reattachWorktree(worktree: Worktree): Promise<Worktree> {
157
+ export async function reattachWorktree(worktree: Worktree): Promise<Worktree & { preserved?: string }> {
158
+ const exists = !!await stat(worktree.path).catch(() => undefined);
159
+ if (exists && await validWorktree(worktree.path)) {
160
+ // A crash mid `git add`/`commit` leaves the index, HEAD or the branch locked; nothing else
161
+ // writes this worktree while its assignment reopens, so the locks are stale and would block
162
+ // every later commit.
163
+ const dirs = await gitDirs(worktree.path);
164
+ if (dirs) await clearStaleLocks(dirs, worktree.branch);
165
+ return worktree;
166
+ }
148
167
  if (!await branchExists(worktree.checkout, worktree.branch)) throw new Error(`Branch ${worktree.branch} of the worktree no longer exists`);
149
- if (await stat(worktree.path).catch(() => undefined)) return worktree;
168
+ let preserved: string | undefined;
169
+ if (exists) {
170
+ preserved = `${worktree.path}.preserved-${new Date().toISOString().replace(/[:.]/g, '-')}`;
171
+ await rename(worktree.path, preserved);
172
+ }
150
173
  await mkdir(path.dirname(worktree.path), { recursive: true, mode: 0o700 });
151
174
  await git(worktree.checkout, ['worktree', 'prune']);
152
175
  await checked(worktree.checkout, ['worktree', 'add', '--quiet', worktree.path, worktree.branch]);
153
- return worktree;
176
+ return preserved ? { ...worktree, preserved } : worktree;
154
177
  }
155
178
 
156
179
  /** A digest of a checkout's state: HEAD, its uncommitted changes, and the names of untracked files. */
@@ -232,31 +255,114 @@ export async function removeWorktree(worktree: Worktree, { deleteBranch = false
232
255
  if (deleteBranch) await git(worktree.checkout, ['branch', '-D', worktree.branch]);
233
256
  }
234
257
 
258
+ /** A linked worktree's own git directory and the repository's common one, both absolute. */
259
+ type GitDirs = { own: string; common: string };
260
+
261
+ async function gitDirs(target: string): Promise<GitDirs | undefined> {
262
+ const result = await git(target, ['rev-parse', '--path-format=absolute', '--absolute-git-dir', '--git-common-dir']);
263
+ if (result.code !== 0) return undefined;
264
+ const [own, common] = result.stdout.trim().split('\n').map(line => path.resolve(line.trim()));
265
+ return own && common ? { own, common } : undefined;
266
+ }
267
+
268
+ /**
269
+ * How old the branch's lock in the shared repository must be before ALP treats it as left by
270
+ * a crash. The user's own git commands in their checkout lock that ref too (`git gc`, `git branch
271
+ * -D`), but only for the moment a ref update takes.
272
+ */
273
+ const SHARED_LOCK_STALE_MS = 10_000;
274
+
275
+ /**
276
+ * Removes the locks a git command killed mid-write left in a worktree, which would fail every
277
+ * later `git add` or `git commit` there: `index.lock`, `HEAD.lock` and any other lock directly in
278
+ * the worktree's own git directory, and every `*.lock` under its `refs/`. Callers run this only
279
+ * where no ALP git command can be at work in that worktree (alpd's start, once it has stopped what
280
+ * a crashed alpd left running, and an assignment reopening): only ALP works in its worktrees, so
281
+ * those locks are stale, as `index.lock` always was. In the repository the worktree shares with
282
+ * the user's checkout, only the lock of the worktree's own branch is touched, and only once it is
283
+ * older than SHARED_LOCK_STALE_MS; every other lock there is the user's business.
284
+ */
285
+ async function clearStaleLocks(dirs: GitDirs, branch: string) {
286
+ if (dirs.own === dirs.common) return;
287
+ const own = (await readdir(dirs.own).catch(() => [] as string[])).filter(name => name.endsWith('.lock'));
288
+ const refs = (await readdir(path.join(dirs.own, 'refs'), { recursive: true }).catch(() => [] as string[])).filter(name => name.endsWith('.lock')).map(name => path.join('refs', name));
289
+ for (const name of [...own, ...refs]) await unlink(path.join(dirs.own, name)).catch(() => {});
290
+ const shared = `${path.join(dirs.common, 'refs', 'heads', ...branch.split('/'))}.lock`;
291
+ const info = await lstat(shared).catch(() => undefined);
292
+ if (info?.isFile() && Date.now() - info.mtimeMs >= SHARED_LOCK_STALE_MS) await unlink(shared).catch(() => {});
293
+ }
294
+
295
+ /** Ignored files that may hold what exists nowhere else, such as credentials: `.env`, `.env.local`. */
296
+ const KEEP_IGNORED = /^\.env/;
297
+
298
+ /**
299
+ * The ignored entries of a worktree that removing it would lose for good. git lists them, and an
300
+ * ignored directory (node_modules, build output) is one entry it does not look into.
301
+ */
302
+ async function ignoredToKeep(target: string) {
303
+ const result = await git(target, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--directory']);
304
+ if (result.code !== 0) return undefined;
305
+ return result.stdout.split('\0').filter(Boolean).map(entry => entry.replace(/\/$/, '')).filter(entry => KEEP_IGNORED.test(path.posix.basename(entry))).sort();
306
+ }
307
+
308
+ /**
309
+ * Why reclaimWorktrees left a directory in place: `invalid`, not the top level of a working git
310
+ * worktree; `not-linked`, a repository of its own rather than a worktree of one; `other-branch`,
311
+ * another branch or a detached HEAD, which does not hold this work; `commit-failed`, its work could
312
+ * not be committed (`detail` says why); `uncommitted`, something was still not committed after
313
+ * that; `ignored-files`, its work is committed but it holds ignored files that exist nowhere else.
314
+ */
315
+ export type LeftWorktree = {
316
+ name: string;
317
+ path: string;
318
+ reason: 'invalid' | 'not-linked' | 'other-branch' | 'commit-failed' | 'uncommitted' | 'ignored-files';
319
+ branch?: string;
320
+ detail?: string;
321
+ files?: string[];
322
+ };
323
+
324
+ const firstLine = (result: GitResult) => (result.stderr || result.stdout).trim().split('\n')[0] ?? '';
325
+
235
326
  /**
236
327
  * After a crash: commits work left in worktrees under `root` to their branches and
237
- * removes the directories. Returns the branches that were kept.
328
+ * removes the directories. Returns the branches that were kept, and the directories left in
329
+ * place with the reason. A directory is removed only once everything in it is committed to
330
+ * its own `alp/<name>` branch and it holds no ignored file to keep (`.env*`); any other one
331
+ * stays, so recovery reuses or preserves it and nothing uncommitted is lost. Stale locks a
332
+ * killed git command left in such a worktree are removed first (clearStaleLocks).
238
333
  */
239
- export async function reclaimWorktrees(root: string) {
334
+ export async function reclaimWorktrees(root: string): Promise<{ kept: string[]; left: LeftWorktree[] }> {
240
335
  const kept: string[] = [];
336
+ const left: LeftWorktree[] = [];
241
337
  const entries = await readdir(root).catch(() => [] as string[]);
242
338
  for (const name of entries) {
243
339
  const target = path.join(root, name);
340
+ const leave = (reason: LeftWorktree['reason'], extra: Omit<LeftWorktree, 'name' | 'path' | 'reason'> = {}) => { left.push({ name, path: target, reason, ...extra }); };
244
341
  if (!(await stat(target).catch(() => undefined))?.isDirectory()) continue;
245
- const common = await git(target, ['rev-parse', '--path-format=absolute', '--git-common-dir']).catch(() => undefined);
246
- if (common?.code !== 0) {
247
- await rm(target, { recursive: true, force: true });
248
- continue;
249
- }
250
- const checkout = path.dirname(common.stdout.trim());
251
- const branch = (await git(target, ['rev-parse', '--abbrev-ref', 'HEAD'])).stdout.trim();
252
- await git(target, ['add', '-A']);
342
+ if (!await validWorktree(target)) { leave('invalid'); continue; }
343
+ const dirs = await gitDirs(target);
344
+ if (!dirs) { leave('invalid'); continue; }
345
+ if (dirs.own === dirs.common) { leave('not-linked'); continue; }
346
+ const checkout = path.dirname(dirs.common);
347
+ const ref = await git(target, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
348
+ const branch = ref.stdout.trim();
349
+ if (ref.code !== 0 || branch !== `alp/${name}`) { leave('other-branch', ref.code === 0 && branch ? { branch } : {}); continue; }
350
+ await clearStaleLocks(dirs, branch);
351
+ const added = await git(target, ['add', '-A']);
352
+ if (added.code !== 0) { leave('commit-failed', { branch, detail: firstLine(added) }); continue; }
253
353
  if ((await git(target, ['diff', '--cached', '--quiet'])).code === 1) {
254
- await git(target, [...IDENTITY, 'commit', '--quiet', '--no-verify', '-m', 'alp: work left by an interrupted assignment']);
354
+ const committed = await git(target, [...IDENTITY, 'commit', '--quiet', '--no-verify', '-m', 'alp: work left by an interrupted assignment']);
355
+ if (committed.code !== 0) { leave('commit-failed', { branch, detail: firstLine(committed) }); continue; }
255
356
  }
357
+ const status = await git(target, ['status', '--porcelain', '--ignored=no']);
358
+ if (status.code !== 0 || status.stdout.trim()) { leave('uncommitted', { branch }); continue; }
359
+ const ignored = await ignoredToKeep(target);
360
+ if (!ignored) { leave('ignored-files', { branch, detail: 'git could not list its ignored files' }); continue; }
361
+ if (ignored.length) { leave('ignored-files', { branch, files: ignored }); continue; }
256
362
  await removeWorktree({ checkout, path: target, workdir: target, branch, base: '' });
257
363
  kept.push(branch);
258
364
  }
259
- return kept;
365
+ return { kept, left };
260
366
  }
261
367
 
262
368
  /**