@anhlp/alp-runtime 0.0.0-stage → 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 (127) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +7 -0
  3. package/README.md +6 -2
  4. package/dist/acp-transport.d.ts +130 -0
  5. package/dist/acp-transport.js +482 -0
  6. package/dist/antigravity-transport.d.ts +107 -0
  7. package/dist/antigravity-transport.js +665 -0
  8. package/dist/assignment-results.d.ts +55 -0
  9. package/dist/assignment-results.js +181 -0
  10. package/dist/attachments.d.ts +84 -0
  11. package/dist/attachments.js +213 -0
  12. package/dist/board-domain.d.ts +56 -0
  13. package/dist/board-domain.js +157 -0
  14. package/dist/board.d.ts +27 -0
  15. package/dist/board.js +76 -0
  16. package/dist/catalog.d.ts +44 -0
  17. package/dist/catalog.js +47 -0
  18. package/dist/claude-transport.d.ts +251 -0
  19. package/dist/claude-transport.js +931 -0
  20. package/dist/compact.d.ts +29 -0
  21. package/dist/compact.js +49 -0
  22. package/dist/configure.d.ts +44 -0
  23. package/dist/configure.js +64 -0
  24. package/dist/contracts.d.ts +378 -0
  25. package/dist/contracts.js +16 -0
  26. package/dist/conversation.d.ts +45 -0
  27. package/dist/conversation.js +62 -0
  28. package/dist/events.d.ts +1 -0
  29. package/dist/events.js +0 -0
  30. package/dist/github.d.ts +10 -0
  31. package/dist/github.js +39 -0
  32. package/dist/handoff.d.ts +36 -0
  33. package/dist/handoff.js +73 -0
  34. package/dist/index.d.ts +39 -0
  35. package/dist/index.js +122 -0
  36. package/dist/input-limits.d.ts +25 -0
  37. package/dist/input-limits.js +48 -0
  38. package/dist/language.d.ts +51 -0
  39. package/dist/language.js +94 -0
  40. package/dist/live.d.ts +48 -0
  41. package/dist/live.js +50 -0
  42. package/dist/mailbox.d.ts +26 -0
  43. package/dist/mailbox.js +38 -0
  44. package/dist/mcp-tools.d.ts +123 -0
  45. package/dist/mcp-tools.js +97 -0
  46. package/dist/model-catalog.d.ts +162 -0
  47. package/dist/model-catalog.js +338 -0
  48. package/dist/model-probes.d.ts +7 -0
  49. package/dist/model-probes.js +69 -0
  50. package/dist/permission-path.d.ts +2 -0
  51. package/dist/permission-path.js +44 -0
  52. package/dist/process-info.d.ts +14 -0
  53. package/dist/process-info.js +32 -0
  54. package/dist/providers.d.ts +28 -0
  55. package/dist/providers.js +73 -0
  56. package/dist/recall.d.ts +42 -0
  57. package/dist/recall.js +61 -0
  58. package/dist/resolve.d.ts +123 -0
  59. package/dist/resolve.js +242 -0
  60. package/dist/runtime-context.d.ts +43 -0
  61. package/dist/runtime-context.js +61 -0
  62. package/dist/runtime.d.ts +13 -0
  63. package/dist/runtime.js +4818 -0
  64. package/dist/session-config.d.ts +2345 -0
  65. package/dist/session-config.js +209 -0
  66. package/dist/session-state.d.ts +190 -0
  67. package/dist/session-state.js +0 -0
  68. package/dist/skill-resources.d.ts +30 -0
  69. package/dist/skill-resources.js +55 -0
  70. package/dist/tool-detail.d.ts +81 -0
  71. package/dist/tool-detail.js +332 -0
  72. package/dist/tool-results.d.ts +12 -0
  73. package/dist/tool-results.js +25 -0
  74. package/dist/tools.d.ts +827 -0
  75. package/dist/tools.js +463 -0
  76. package/dist/transport.d.ts +47 -0
  77. package/dist/transport.js +171 -0
  78. package/dist/usage.d.ts +25 -0
  79. package/dist/usage.js +60 -0
  80. package/dist/workspace.d.ts +127 -0
  81. package/dist/workspace.js +340 -0
  82. package/dist/worktree-domain.d.ts +89 -0
  83. package/dist/worktree-domain.js +199 -0
  84. package/dist/write-error.d.ts +2 -0
  85. package/dist/write-error.js +10 -0
  86. package/package.json +262 -4
  87. package/src/acp-transport.ts +481 -0
  88. package/src/antigravity-transport.ts +740 -0
  89. package/src/assignment-results.ts +154 -0
  90. package/src/attachments.ts +254 -0
  91. package/src/board-domain.ts +185 -0
  92. package/src/board.ts +87 -0
  93. package/src/catalog.ts +43 -0
  94. package/src/claude-transport.ts +1097 -0
  95. package/src/compact.ts +62 -0
  96. package/src/configure.ts +93 -0
  97. package/src/contracts.ts +363 -0
  98. package/src/conversation.ts +81 -0
  99. package/src/events.ts +1 -0
  100. package/src/github.ts +37 -0
  101. package/src/handoff.ts +86 -0
  102. package/src/index.ts +41 -0
  103. package/src/input-limits.ts +65 -0
  104. package/src/language.ts +130 -0
  105. package/src/live.ts +90 -0
  106. package/src/mailbox.ts +49 -0
  107. package/src/mcp-tools.ts +106 -0
  108. package/src/model-catalog.ts +316 -0
  109. package/src/model-probes.ts +58 -0
  110. package/src/permission-path.ts +37 -0
  111. package/src/process-info.ts +40 -0
  112. package/src/providers.ts +87 -0
  113. package/src/recall.ts +86 -0
  114. package/src/resolve.ts +238 -0
  115. package/src/runtime-context.ts +49 -0
  116. package/src/runtime.ts +5608 -0
  117. package/src/session-config.ts +312 -0
  118. package/src/session-state.ts +180 -0
  119. package/src/skill-resources.ts +73 -0
  120. package/src/tool-detail.ts +397 -0
  121. package/src/tool-results.ts +26 -0
  122. package/src/tools.ts +466 -0
  123. package/src/transport.ts +118 -0
  124. package/src/usage.ts +79 -0
  125. package/src/workspace.ts +424 -0
  126. package/src/worktree-domain.ts +220 -0
  127. package/src/write-error.ts +4 -0
package/src/usage.ts ADDED
@@ -0,0 +1,79 @@
1
+ import type { SessionUsage } from './events.js';
2
+
3
+ /** Account-free usage data shown in ALP's viewers. */
4
+ export type UsageWindow = { name: string; usedPercent: number | null; resetsAt: string | null };
5
+ export type ProviderUsage = {
6
+ runtime: 'codex' | 'claude';
7
+ available: boolean;
8
+ checkedAt: string;
9
+ plan: string | null;
10
+ limited: boolean;
11
+ windows: UsageWindow[];
12
+ };
13
+
14
+ const text = (value: unknown): string | null => typeof value === 'string' && value.trim() ? value : null;
15
+ function resetTime(value: unknown): string | null {
16
+ const ms = typeof value === 'number' ? value * 1000 : typeof value === 'string' ? Date.parse(value) : NaN;
17
+ return Number.isFinite(ms) && Math.abs(ms) <= 8.64e15 ? new Date(ms).toISOString() : null;
18
+ }
19
+ function windowName(window: any, index: number) {
20
+ if (text(window.name)) return window.name.replaceAll('_', ' ');
21
+ const minutes = window.windowMinutes;
22
+ if (typeof minutes === 'number' && minutes > 0) {
23
+ if (minutes % 1440 === 0) return `${minutes / 1440} day window`;
24
+ if (minutes % 60 === 0) return `${minutes / 60} hour window`;
25
+ return `${minutes} minute window`;
26
+ }
27
+ return `Window ${index + 1}`;
28
+ }
29
+ export function providerUsage(runtime: ProviderUsage['runtime'], usage: any, checkedAt = new Date().toISOString()): ProviderUsage {
30
+ const limits: any[] = Array.isArray(usage?.limits) ? usage.limits : [];
31
+ const windows = (limits.length ? limits.flatMap(limit => (Array.isArray(limit?.windows) ? limit.windows : []).map((window: any) => ({ ...window, group: text(limit.name) ?? text(limit.model) }))) : Array.isArray(usage?.windows) ? usage.windows : [])
32
+ .filter((window: any) => window && typeof window === 'object')
33
+ .map((window: any, index: number) => ({
34
+ name: `${window.group ? `${window.group} · ` : ''}${windowName(window, index)}`,
35
+ usedPercent: typeof window.usedPercent === 'number' && Number.isFinite(window.usedPercent) ? Math.min(100, Math.max(0, window.usedPercent)) : null,
36
+ resetsAt: resetTime(window.resetsAt),
37
+ }));
38
+ return {
39
+ runtime, available: usage?.available === true, checkedAt,
40
+ plan: text(usage?.plan) ?? limits.map(limit => text(limit?.plan)).find(Boolean) ?? null,
41
+ limited: usage?.ordinaryUsageAllowed === false || limits.some(limit => limit?.spendControlReached === true) || windows.some((window: UsageWindow) => window.usedPercent === 100),
42
+ windows,
43
+ };
44
+ }
45
+
46
+ const tokens = (value: unknown, least = 0): number | undefined =>
47
+ typeof value === 'number' && Number.isInteger(value) && value >= least ? value : undefined;
48
+
49
+ /**
50
+ * A session's usage after one token report (ALPD §57), as Paseo's AgentUsage. Every transport
51
+ * reports as Codex's thread/tokenUsage/updated does: `last` the latest model call, of which
52
+ * `totalTokens` is what the context holds now; `modelContextWindow` the window once known;
53
+ * `totalCostUsd` the session's cost where the runtime counts it. The fields a report carries
54
+ * replace the session's; the others are kept, except that the latest response's input, cached and
55
+ * output counts are replaced together. Undefined when the report changes nothing.
56
+ */
57
+ export function sessionUsage(previous: SessionUsage | undefined, report: any): SessionUsage | undefined {
58
+ if (!report || typeof report !== 'object') return undefined;
59
+ const last = report.last && typeof report.last === 'object' ? report.last : {};
60
+ const cost = report.totalCostUsd;
61
+ const fields: SessionUsage = {
62
+ contextWindowUsedTokens: tokens(last.totalTokens),
63
+ contextWindowMaxTokens: tokens(report.modelContextWindow, 1),
64
+ inputTokens: tokens(last.inputTokens),
65
+ cachedInputTokens: tokens(last.cachedInputTokens ?? report.cachedInputTokens),
66
+ outputTokens: tokens(last.outputTokens),
67
+ totalCostUsd: typeof cost === 'number' && Number.isFinite(cost) && cost >= 0 ? cost : undefined,
68
+ };
69
+ const next: SessionUsage = { ...previous };
70
+ // The latest response's counts go together: a report with any of them replaces all three, so a
71
+ // count an earlier response had never sits beside a newer one's.
72
+ if (fields.inputTokens !== undefined || fields.cachedInputTokens !== undefined || fields.outputTokens !== undefined) {
73
+ delete next.inputTokens; delete next.cachedInputTokens; delete next.outputTokens;
74
+ }
75
+ for (const [key, value] of Object.entries(fields) as Array<[keyof SessionUsage, number | undefined]>) if (value !== undefined) next[key] = value;
76
+ const keys = Object.keys(next) as Array<keyof SessionUsage>;
77
+ if (keys.length === Object.keys(previous ?? {}).length && keys.every(key => previous?.[key] === next[key])) return undefined;
78
+ return next;
79
+ }
@@ -0,0 +1,424 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { createHash } from 'node:crypto';
3
+ import { copyFile, lstat, mkdir, mkdtemp, readdir, readFile, realpath, rename, rm, stat, symlink, unlink, writeFile } from 'node:fs/promises';
4
+ import os from 'node:os';
5
+ import path from 'node:path';
6
+
7
+ /**
8
+ * Phase C isolation (plans/reference/ALPD.md §16): a writing assignment may run in its
9
+ * own git worktree, so writers do not share a checkout. Its work is committed to a
10
+ * branch when it ends, and the requester merges the change into its checkout or
11
+ * discards it. Branches outlive their worktrees, so work is never deleted silently.
12
+ */
13
+
14
+ export type Worktree = {
15
+ /** The requester's checkout, which receives the change on merge. */
16
+ checkout: string;
17
+ /** The worktree's top level, and the assignment's working directory inside it. */
18
+ path: string;
19
+ workdir: string;
20
+ branch: string;
21
+ /** The requester's state when the assignment started: HEAD plus uncommitted tracked changes. */
22
+ base: string;
23
+ /** checkoutFingerprint of the requester's checkout then, to tell whether it changed since. */
24
+ fingerprint?: string;
25
+ };
26
+
27
+ export type WorktreeChange = { commit: string; files: string[]; stat: string };
28
+
29
+ type GitResult = { code: number; stdout: string; stderr: string };
30
+
31
+ /** Commits made for ALP never run the project's hooks and need no user identity. */
32
+ const IDENTITY = ['-c', 'user.name=ALP', '-c', 'user.email=alp@localhost', '-c', 'commit.gpgsign=false'];
33
+
34
+ /**
35
+ * Variables git sets for its hooks and aliases, which would point ALP's git
36
+ * commands at another repository, index or configuration (ALPD §32).
37
+ */
38
+ const GIT_CONTEXT = [
39
+ 'GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_OBJECT_DIRECTORY', 'GIT_ALTERNATE_OBJECT_DIRECTORIES',
40
+ 'GIT_PREFIX', 'GIT_NAMESPACE', 'GIT_IMPLICIT_WORK_TREE', 'GIT_GRAFT_FILE', 'GIT_REPLACE_REF_BASE', 'GIT_NO_REPLACE_OBJECTS',
41
+ 'GIT_SHALLOW_FILE', 'GIT_CONFIG', 'GIT_CONFIG_PARAMETERS', 'GIT_CONFIG_COUNT',
42
+ ];
43
+
44
+ /** The environment ALP runs git in: the caller's, without git's own context, and never prompting. */
45
+ export function gitEnvironment(env: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
46
+ const clean: NodeJS.ProcessEnv = { ...env, GIT_TERMINAL_PROMPT: '0' };
47
+ for (const key of Object.keys(clean)) {
48
+ if (GIT_CONTEXT.includes(key) || /^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(key)) delete clean[key];
49
+ }
50
+ return clean;
51
+ }
52
+
53
+ function git(cwd: string, args: string[], input?: string): Promise<GitResult> {
54
+ return new Promise((resolve, reject) => {
55
+ const child = spawn('git', args, { cwd, stdio: [input === undefined ? 'ignore' : 'pipe', 'pipe', 'pipe'], windowsHide: true, env: gitEnvironment() });
56
+ let stdout = '';
57
+ let stderr = '';
58
+ child.stdout!.on('data', chunk => { stdout += chunk; });
59
+ child.stderr!.on('data', chunk => { stderr += chunk; });
60
+ child.once('error', reject);
61
+ child.once('close', code => resolve({ code: code ?? 1, stdout, stderr }));
62
+ if (child.stdin) {
63
+ // git may exit before reading its input (EPIPE); its exit code reports the failure.
64
+ child.stdin.on('error', () => {});
65
+ child.stdin.end(input);
66
+ }
67
+ });
68
+ }
69
+
70
+ async function checked(cwd: string, args: string[], input?: string) {
71
+ const result = await git(cwd, args, input);
72
+ if (result.code !== 0) throw new Error(`git ${args[0]} failed: ${(result.stderr || result.stdout).trim()}`);
73
+ return result.stdout.trim();
74
+ }
75
+
76
+ /** A file's content at a revision, or undefined where it does not exist. */
77
+ function blob(cwd: string, revision: string, file: string): Promise<Buffer | undefined> {
78
+ return new Promise((resolve, reject) => {
79
+ const child = spawn('git', ['cat-file', 'blob', `${revision}:${file}`], { cwd, stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true, env: gitEnvironment() });
80
+ const chunks: Buffer[] = [];
81
+ child.stdout.on('data', chunk => chunks.push(chunk));
82
+ child.once('error', reject);
83
+ child.once('close', code => resolve(code === 0 ? Buffer.concat(chunks) : undefined));
84
+ });
85
+ }
86
+
87
+ const binary = (content: Buffer) => content.subarray(0, 8000).includes(0);
88
+ const same = (a?: Buffer, b?: Buffer) => a === b || (!!a && !!b && a.equals(b));
89
+
90
+ /** Three-way merges one text file; returns the result and whether it has conflict markers. */
91
+ async function mergeText(ours: Buffer, base: Buffer, theirs: Buffer) {
92
+ const directory = await mkdtemp(path.join(os.tmpdir(), 'alp-merge-'));
93
+ try {
94
+ const [o, b, t] = ['ours', 'base', 'theirs'].map(name => path.join(directory, name));
95
+ await Promise.all([writeFile(o, ours), writeFile(b, base), writeFile(t, theirs)]);
96
+ const result = await git(directory, ['merge-file', '-p', '-L', 'yours', '-L', 'base', '-L', 'assignment', o, b, t]);
97
+ if (result.code < 0 || result.code > 127) throw new Error(`git merge-file failed: ${result.stderr.trim()}`);
98
+ return { content: result.stdout, conflict: result.code > 0 };
99
+ } finally {
100
+ await rm(directory, { recursive: true, force: true });
101
+ }
102
+ }
103
+
104
+ /** The top level of the git checkout containing `directory`, or undefined outside git. */
105
+ export async function checkoutOf(directory: string) {
106
+ const result = await git(directory, ['rev-parse', '--show-toplevel']).catch(() => undefined);
107
+ return result?.code === 0 ? realpath(result.stdout.trim()) : undefined;
108
+ }
109
+
110
+ /** The key that writers of one checkout share: its top level, or the directory itself outside git. */
111
+ export async function checkoutKey(directory: string) {
112
+ return (await checkoutOf(directory)) ?? realpath(directory).catch(() => path.resolve(directory));
113
+ }
114
+
115
+ /** Whether the checkout containing `directory` has a local branch of that name. */
116
+ export async function branchExists(directory: string, branch: string) {
117
+ const result = await git(directory, ['rev-parse', '--verify', '--quiet', `refs/heads/${branch}`]).catch(() => undefined);
118
+ return result?.code === 0;
119
+ }
120
+
121
+ /** Creates a worktree for `id` from the current state of the checkout containing `workdir`. */
122
+ /**
123
+ * Creates a worktree for `id` from the current state of the checkout containing `workdir`,
124
+ * or, with `from`, from an earlier assignment's committed change, keeping that assignment's
125
+ * base so a merge applies both changes together.
126
+ */
127
+ export async function createWorktree(workdir: string, root: string, id: string, from?: Pick<Worktree, 'base' | 'fingerprint'> & { commit: string }): Promise<Worktree> {
128
+ const checkout = await checkoutOf(workdir);
129
+ if (!checkout) throw new Error('Worktree isolation needs a git repository');
130
+ const head = await git(checkout, ['rev-parse', '--verify', 'HEAD']);
131
+ if (head.code !== 0) throw new Error('Worktree isolation needs at least one commit');
132
+ const fingerprint = from ? from.fingerprint : await checkoutFingerprint(checkout);
133
+ // `stash create` snapshots uncommitted tracked changes without touching the checkout.
134
+ const base = from ? from.base : (await checked(checkout, ['stash', 'create'])) || head.stdout.trim();
135
+ const target = path.join(root, id);
136
+ const branch = `alp/${id}`;
137
+ await mkdir(root, { recursive: true, mode: 0o700 });
138
+ await checked(checkout, ['worktree', 'add', '--quiet', '-b', branch, target, from ? from.commit : base]);
139
+ const relative = path.relative(checkout, await realpath(workdir));
140
+ return { checkout, path: target, workdir: path.join(target, relative), branch, base, ...(fingerprint ? { fingerprint } : {}) };
141
+ }
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
+
151
+ /**
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.
156
+ */
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
+ }
167
+ if (!await branchExists(worktree.checkout, worktree.branch)) throw new Error(`Branch ${worktree.branch} of the worktree no longer exists`);
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
+ }
173
+ await mkdir(path.dirname(worktree.path), { recursive: true, mode: 0o700 });
174
+ await git(worktree.checkout, ['worktree', 'prune']);
175
+ await checked(worktree.checkout, ['worktree', 'add', '--quiet', worktree.path, worktree.branch]);
176
+ return preserved ? { ...worktree, preserved } : worktree;
177
+ }
178
+
179
+ /** A digest of a checkout's state: HEAD, its uncommitted changes, and the names of untracked files. */
180
+ export async function checkoutFingerprint(checkout: string) {
181
+ const head = await git(checkout, ['rev-parse', '--verify', 'HEAD']);
182
+ if (head.code !== 0) return undefined;
183
+ const diff = await git(checkout, ['diff', '--binary', 'HEAD']);
184
+ const untracked = await git(checkout, ['ls-files', '--others', '--exclude-standard', '-z']);
185
+ return createHash('sha256').update(head.stdout).update('\0').update(diff.stdout).update('\0').update(untracked.stdout).digest('hex');
186
+ }
187
+
188
+ /**
189
+ * Links the project's node_modules into the same place in a worktree that has none,
190
+ * so its build and tests run; returns what undoes it. Commits never see the link,
191
+ * because ALP removes it before the worktree is committed again.
192
+ */
193
+ export async function linkModules(projectDir: string, worktreeDir: string) {
194
+ const source = path.join(projectDir, 'node_modules');
195
+ const target = path.join(worktreeDir, 'node_modules');
196
+ if (!(await stat(source).catch(() => undefined))?.isDirectory() || await lstat(target).catch(() => undefined)) return async () => {};
197
+ await symlink(source, target, 'dir');
198
+ return async () => { await unlink(target).catch(() => {}); };
199
+ }
200
+
201
+ /** Commits whatever the assignment left in its worktree and describes the change from its base. */
202
+ export async function commitWorktree(worktree: Worktree, message: string): Promise<WorktreeChange> {
203
+ await checked(worktree.path, ['add', '-A']);
204
+ const staged = await git(worktree.path, ['diff', '--cached', '--quiet']);
205
+ if (staged.code === 1) await checked(worktree.path, [...IDENTITY, 'commit', '--quiet', '--no-verify', '-m', message]);
206
+ const commit = await checked(worktree.path, ['rev-parse', 'HEAD']);
207
+ const names = await checked(worktree.path, ['diff', '--name-only', worktree.base, commit]);
208
+ const stat = await checked(worktree.path, ['diff', '--shortstat', worktree.base, commit]);
209
+ return { commit, files: names ? names.split('\n') : [], stat };
210
+ }
211
+
212
+ /**
213
+ * Applies the change to the requester's working tree without committing or touching
214
+ * its index. A patch that applies cleanly is applied as is; otherwise each file is
215
+ * merged three ways against the requester's current file, leaving conflict markers.
216
+ * Where a file was deleted on one side or is binary, the requester's version is kept
217
+ * and reported as a conflict.
218
+ */
219
+ export async function mergeWorktree(worktree: Worktree, change: WorktreeChange) {
220
+ if (!change.files.length) return { status: 'empty' as const, files: [] };
221
+ const patch = await checked(worktree.checkout, ['diff', '--binary', worktree.base, change.commit]);
222
+ if ((await git(worktree.checkout, ['apply', '--whitespace=nowarn'], `${patch}\n`)).code === 0) return { status: 'applied' as const, files: change.files };
223
+ const conflicts: string[] = [];
224
+ for (const file of change.files) {
225
+ const target = path.join(worktree.checkout, file);
226
+ const ours = await readFile(target).catch(() => undefined);
227
+ const base = await blob(worktree.checkout, worktree.base, file);
228
+ const theirs = await blob(worktree.checkout, change.commit, file);
229
+ if (same(ours, theirs)) continue;
230
+ if (same(ours, base)) {
231
+ if (theirs) {
232
+ await mkdir(path.dirname(target), { recursive: true });
233
+ await writeFile(target, theirs);
234
+ } else {
235
+ await rm(target, { force: true });
236
+ }
237
+ continue;
238
+ }
239
+ if (!ours || !theirs || binary(ours) || binary(theirs) || (base && binary(base))) {
240
+ conflicts.push(file);
241
+ continue;
242
+ }
243
+ const merged = await mergeText(ours, base ?? Buffer.alloc(0), theirs);
244
+ await writeFile(target, merged.content);
245
+ if (merged.conflict) conflicts.push(file);
246
+ }
247
+ return conflicts.length ? { status: 'conflicts' as const, files: change.files, conflicts } : { status: 'applied' as const, files: change.files };
248
+ }
249
+
250
+ /** Removes the worktree directory; the branch stays unless `deleteBranch`. */
251
+ export async function removeWorktree(worktree: Worktree, { deleteBranch = false } = {}) {
252
+ await git(worktree.checkout, ['worktree', 'remove', '--force', worktree.path]);
253
+ await rm(worktree.path, { recursive: true, force: true });
254
+ await git(worktree.checkout, ['worktree', 'prune']);
255
+ if (deleteBranch) await git(worktree.checkout, ['branch', '-D', worktree.branch]);
256
+ }
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
+
326
+ /**
327
+ * After a crash: commits work left in worktrees under `root` to their branches and
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).
333
+ */
334
+ export async function reclaimWorktrees(root: string): Promise<{ kept: string[]; left: LeftWorktree[] }> {
335
+ const kept: string[] = [];
336
+ const left: LeftWorktree[] = [];
337
+ const entries = await readdir(root).catch(() => [] as string[]);
338
+ for (const name of entries) {
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 }); };
341
+ if (!(await stat(target).catch(() => undefined))?.isDirectory()) continue;
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; }
353
+ if ((await git(target, ['diff', '--cached', '--quiet'])).code === 1) {
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; }
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; }
362
+ await removeWorktree({ checkout, path: target, workdir: target, branch, base: '' });
363
+ kept.push(branch);
364
+ }
365
+ return { kept, left };
366
+ }
367
+
368
+ /**
369
+ * A disposable copy of a checkout for an assignment that may build and test but
370
+ * must not touch the requester's tree (ALPD §26): a detached worktree at the
371
+ * requester's HEAD with its uncommitted changes applied as uncommitted changes, so
372
+ * `git diff` and `git status` there show what they show the requester, plus its
373
+ * untracked files.
374
+ * A top-level node_modules is linked, not copied. Nothing in it is ever merged.
375
+ */
376
+ export type Copy = { checkout: string; path: string; workdir: string };
377
+
378
+ export async function createCopy(workdir: string, root: string, id: string): Promise<Copy> {
379
+ const checkout = await checkoutOf(workdir);
380
+ if (!checkout) throw new Error('A review copy needs a git repository');
381
+ const head = await git(checkout, ['rev-parse', '--verify', 'HEAD']);
382
+ if (head.code !== 0) throw new Error('A review copy needs at least one commit');
383
+ const target = path.join(root, id);
384
+ await mkdir(root, { recursive: true, mode: 0o700 });
385
+ await checked(checkout, ['worktree', 'add', '--quiet', '--detach', target, head.stdout.trim()]);
386
+ try {
387
+ const patch = (await git(checkout, ['diff', '--binary', 'HEAD'])).stdout;
388
+ if (patch.trim()) await checked(target, ['apply', '--whitespace=nowarn', '--binary'], patch);
389
+ const untracked = (await checked(checkout, ['ls-files', '--others', '--exclude-standard', '-z'])).split('\0').filter(Boolean);
390
+ for (const file of untracked) {
391
+ const from = path.join(checkout, file);
392
+ if (!(await lstat(from).catch(() => undefined))?.isFile()) continue;
393
+ await mkdir(path.dirname(path.join(target, file)), { recursive: true });
394
+ await copyFile(from, path.join(target, file));
395
+ }
396
+ const modules = path.join(checkout, 'node_modules');
397
+ if ((await stat(modules).catch(() => undefined))?.isDirectory()) await symlink(modules, path.join(target, 'node_modules'), 'dir');
398
+ } catch (error) {
399
+ await removeCopy({ checkout, path: target, workdir: target });
400
+ throw error;
401
+ }
402
+ const relative = path.relative(checkout, await realpath(workdir));
403
+ return { checkout, path: target, workdir: path.join(target, relative) };
404
+ }
405
+
406
+ export async function removeCopy(copy: Copy) {
407
+ await git(copy.checkout, ['worktree', 'remove', '--force', copy.path]).catch(() => undefined);
408
+ await rm(copy.path, { recursive: true, force: true });
409
+ await git(copy.checkout, ['worktree', 'prune']).catch(() => undefined);
410
+ }
411
+
412
+ /** After a crash: removes copies left under `root`; they hold nothing to keep. */
413
+ export async function reclaimCopies(root: string) {
414
+ let removed = 0;
415
+ for (const name of await readdir(root).catch(() => [] as string[])) {
416
+ const target = path.join(root, name);
417
+ const common = await git(target, ['rev-parse', '--path-format=absolute', '--git-common-dir']).catch(() => undefined);
418
+ if (common?.code === 0) await removeCopy({ checkout: path.dirname(common.stdout.trim()), path: target, workdir: target });
419
+ else await rm(target, { recursive: true, force: true });
420
+ removed++;
421
+ }
422
+ return removed;
423
+ }
424
+