@anhlp/alp-runtime 0.0.1-beta.4 → 0.0.1-beta.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/acp-transport.js +5 -36
- package/dist/antigravity-transport.d.ts +17 -0
- package/dist/antigravity-transport.js +82 -58
- package/dist/assignment-results.d.ts +34 -0
- package/dist/assignment-results.js +94 -2
- package/dist/board-domain.js +2 -2
- package/dist/board.d.ts +6 -0
- package/dist/board.js +7 -0
- package/dist/catalog.d.ts +13 -0
- package/dist/catalog.js +9 -1
- package/dist/claude-transport.d.ts +7 -0
- package/dist/claude-transport.js +65 -6
- package/dist/compact.d.ts +29 -0
- package/dist/compact.js +49 -0
- package/dist/configure.d.ts +1 -1
- package/dist/configure.js +2 -2
- package/dist/contracts.d.ts +25 -1
- package/dist/index.d.ts +9 -2
- package/dist/index.js +30 -2
- package/dist/input-limits.d.ts +25 -0
- package/dist/input-limits.js +48 -0
- package/dist/language.d.ts +8 -0
- package/dist/language.js +20 -0
- package/dist/mcp-tools.d.ts +8 -0
- package/dist/mcp-tools.js +26 -0
- package/dist/model-catalog.d.ts +76 -0
- package/dist/model-catalog.js +193 -0
- package/dist/model-probes.d.ts +7 -0
- package/dist/model-probes.js +69 -0
- package/dist/providers.js +2 -0
- package/dist/resolve.d.ts +1 -0
- package/dist/resolve.js +3 -1
- package/dist/runtime.d.ts +3 -1
- package/dist/runtime.js +605 -45
- package/dist/session-config.d.ts +174 -0
- package/dist/session-config.js +9 -9
- package/dist/session-state.d.ts +23 -1
- package/dist/tools.d.ts +82 -0
- package/dist/tools.js +53 -5
- package/dist/transport.js +3 -1
- package/dist/workspace.d.ts +11 -4
- package/dist/workspace.js +29 -11
- package/package.json +3 -3
- package/src/acp-transport.ts +7 -37
- package/src/antigravity-transport.ts +95 -53
- package/src/assignment-results.ts +85 -3
- package/src/board-domain.ts +2 -2
- package/src/board.ts +7 -0
- package/src/catalog.ts +10 -1
- package/src/claude-transport.ts +71 -6
- package/src/compact.ts +62 -0
- package/src/configure.ts +3 -3
- package/src/contracts.ts +22 -1
- package/src/index.ts +9 -2
- package/src/input-limits.ts +65 -0
- package/src/language.ts +18 -0
- package/src/mcp-tools.ts +33 -0
- package/src/model-catalog.ts +166 -0
- package/src/model-probes.ts +58 -0
- package/src/providers.ts +3 -0
- package/src/resolve.ts +4 -2
- package/src/runtime.ts +650 -46
- package/src/session-config.ts +8 -8
- package/src/session-state.ts +15 -1
- package/src/tools.ts +53 -5
- package/src/transport.ts +3 -1
- package/src/workspace.ts +42 -15
package/src/session-config.ts
CHANGED
|
@@ -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 {
|
|
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.
|
|
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' ? [
|
|
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,
|
package/src/session-state.ts
CHANGED
|
@@ -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:
|
|
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:
|
|
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
|
-
|
|
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,39 @@ 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
|
-
*
|
|
145
|
-
*
|
|
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 locked; nothing else writes this worktree
|
|
161
|
+
// while its assignment reopens, so the lock is stale and would block every later commit.
|
|
162
|
+
const gitdir = await git(worktree.path, ['rev-parse', '--absolute-git-dir']);
|
|
163
|
+
if (gitdir.code === 0) await rm(path.join(gitdir.stdout.trim(), 'index.lock'), { force: true });
|
|
164
|
+
return worktree;
|
|
165
|
+
}
|
|
148
166
|
if (!await branchExists(worktree.checkout, worktree.branch)) throw new Error(`Branch ${worktree.branch} of the worktree no longer exists`);
|
|
149
|
-
|
|
167
|
+
let preserved: string | undefined;
|
|
168
|
+
if (exists) {
|
|
169
|
+
preserved = `${worktree.path}.preserved-${new Date().toISOString().replace(/[:.]/g, '-')}`;
|
|
170
|
+
await rename(worktree.path, preserved);
|
|
171
|
+
}
|
|
150
172
|
await mkdir(path.dirname(worktree.path), { recursive: true, mode: 0o700 });
|
|
151
173
|
await git(worktree.checkout, ['worktree', 'prune']);
|
|
152
174
|
await checked(worktree.checkout, ['worktree', 'add', '--quiet', worktree.path, worktree.branch]);
|
|
153
|
-
return worktree;
|
|
175
|
+
return preserved ? { ...worktree, preserved } : worktree;
|
|
154
176
|
}
|
|
155
177
|
|
|
156
178
|
/** A digest of a checkout's state: HEAD, its uncommitted changes, and the names of untracked files. */
|
|
@@ -234,7 +256,10 @@ export async function removeWorktree(worktree: Worktree, { deleteBranch = false
|
|
|
234
256
|
|
|
235
257
|
/**
|
|
236
258
|
* After a crash: commits work left in worktrees under `root` to their branches and
|
|
237
|
-
* removes the directories. Returns the branches that were kept.
|
|
259
|
+
* removes the directories. Returns the branches that were kept. A directory is removed
|
|
260
|
+
* only once everything in it is committed to its own `alp/<name>` branch; any other one
|
|
261
|
+
* (invalid git metadata, a failed commit, another branch checked out, a detached HEAD)
|
|
262
|
+
* stays untouched, so recovery reuses or preserves it and nothing uncommitted is lost.
|
|
238
263
|
*/
|
|
239
264
|
export async function reclaimWorktrees(root: string) {
|
|
240
265
|
const kept: string[] = [];
|
|
@@ -242,17 +267,19 @@ export async function reclaimWorktrees(root: string) {
|
|
|
242
267
|
for (const name of entries) {
|
|
243
268
|
const target = path.join(root, name);
|
|
244
269
|
if (!(await stat(target).catch(() => undefined))?.isDirectory()) continue;
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
continue;
|
|
249
|
-
}
|
|
270
|
+
if (!await validWorktree(target)) continue;
|
|
271
|
+
const common = await git(target, ['rev-parse', '--path-format=absolute', '--git-common-dir']);
|
|
272
|
+
if (common.code !== 0) continue;
|
|
250
273
|
const checkout = path.dirname(common.stdout.trim());
|
|
251
|
-
const
|
|
252
|
-
|
|
274
|
+
const ref = await git(target, ['symbolic-ref', '--quiet', '--short', 'HEAD']);
|
|
275
|
+
const branch = ref.stdout.trim();
|
|
276
|
+
if (ref.code !== 0 || branch !== `alp/${name}`) continue;
|
|
277
|
+
if ((await git(target, ['add', '-A'])).code !== 0) continue;
|
|
253
278
|
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']);
|
|
279
|
+
if ((await git(target, [...IDENTITY, 'commit', '--quiet', '--no-verify', '-m', 'alp: work left by an interrupted assignment'])).code !== 0) continue;
|
|
255
280
|
}
|
|
281
|
+
const status = await git(target, ['status', '--porcelain', '--ignored=no']);
|
|
282
|
+
if (status.code !== 0 || status.stdout.trim()) continue;
|
|
256
283
|
await removeWorktree({ checkout, path: target, workdir: target, branch, base: '' });
|
|
257
284
|
kept.push(branch);
|
|
258
285
|
}
|