@andorra-labs/code 0.1.16 → 0.1.18
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/src/acp-agent.d.ts +6 -0
- package/dist/src/acp-agent.js +15 -4
- package/dist/src/agent-execution.js +108 -19
- package/dist/src/agent-mcp-catalog.js +1 -0
- package/dist/src/agent-mcp.d.ts +3 -0
- package/dist/src/agent-mcp.js +33 -1
- package/dist/src/andorra/entry.d.ts +10 -0
- package/dist/src/andorra/entry.js +18 -4
- package/dist/src/andorra/errors.js +3 -0
- package/dist/src/andorra/hosted.d.ts +2 -1
- package/dist/src/andorra/hosted.js +2 -1
- package/dist/src/andorra/notices.d.ts +5 -0
- package/dist/src/andorra/notices.js +7 -0
- package/dist/src/andorra/state.d.ts +3 -2
- package/dist/src/andorra/state.js +4 -4
- package/dist/src/andorra/terminal.js +7 -2
- package/dist/src/anthropic-credentials.js +2 -0
- package/dist/src/app-server/error.d.ts +5 -0
- package/dist/src/app-server/error.js +7 -0
- package/dist/src/app-server/protocol.d.ts +30 -44
- package/dist/src/app-server/protocol.js +5 -1
- package/dist/src/app-server/workspace.d.ts +108 -0
- package/dist/src/app-server/workspace.js +608 -11
- package/dist/src/app-server.d.ts +390 -33
- package/dist/src/app-server.js +3033 -565
- package/dist/src/attachments.d.ts +10 -0
- package/dist/src/attachments.js +102 -7
- package/dist/src/automation-tool.js +2 -1
- package/dist/src/bridge/cloud.d.ts +27 -0
- package/dist/src/bridge/cloud.js +187 -0
- package/dist/src/bridge/command.d.ts +30 -0
- package/dist/src/bridge/command.js +359 -0
- package/dist/src/bridge/control.d.ts +70 -0
- package/dist/src/bridge/control.js +238 -0
- package/dist/src/bridge/engines.d.ts +90 -0
- package/dist/src/bridge/engines.js +601 -0
- package/dist/src/bridge/github.d.ts +108 -0
- package/dist/src/bridge/github.js +378 -0
- package/dist/src/bridge/host-ops.d.ts +9 -0
- package/dist/src/bridge/host-ops.js +139 -0
- package/dist/src/bridge/host.d.ts +47 -0
- package/dist/src/bridge/host.js +543 -0
- package/dist/src/bridge/link.d.ts +38 -0
- package/dist/src/bridge/link.js +508 -0
- package/dist/src/bridge/login-link.d.ts +29 -0
- package/dist/src/bridge/login-link.js +54 -0
- package/dist/src/bridge/protocol.d.ts +136 -0
- package/dist/src/bridge/protocol.js +11 -0
- package/dist/src/bridge/store.d.ts +12 -0
- package/dist/src/bridge/store.js +61 -0
- package/dist/src/bridge/wording.d.ts +6 -0
- package/dist/src/bridge/wording.js +10 -0
- package/dist/src/browser-server.js +7 -1
- package/dist/src/browser-ui/tokens.css +1 -1
- package/dist/src/bug-report-attachments.d.ts +48 -0
- package/dist/src/bug-report-attachments.js +327 -0
- package/dist/src/bug-report.d.ts +23 -3
- package/dist/src/bug-report.js +72 -9
- package/dist/src/change-authors.d.ts +41 -0
- package/dist/src/change-authors.js +146 -0
- package/dist/src/cli.d.ts +1 -3
- package/dist/src/cli.js +191 -35
- package/dist/src/codex-provider.js +1 -1
- package/dist/src/coding-tools.js +24 -17
- package/dist/src/command-screens.d.ts +6 -0
- package/dist/src/command-screens.js +14 -11
- package/dist/src/commands.d.ts +15 -3
- package/dist/src/commands.js +2 -1
- package/dist/src/compaction-phrases.js +1 -1
- package/dist/src/completion.js +89 -8
- package/dist/src/config.d.ts +71 -3
- package/dist/src/config.js +205 -78
- package/dist/src/context-budget.js +15 -2
- package/dist/src/deadline.js +13 -1
- package/dist/src/decision/DecisionEngine.d.ts +2 -0
- package/dist/src/decision/DecisionManager.d.ts +11 -0
- package/dist/src/decision/DecisionManager.js +36 -0
- package/dist/src/decision/applyTaskKind.d.ts +8 -0
- package/dist/src/decision/applyTaskKind.js +53 -0
- package/dist/src/decision/checks.js +1 -1
- package/dist/src/decision/hostedPolicy.js +2 -1
- package/dist/src/decision/providers/AndorraDecisionProvider.d.ts +2 -0
- package/dist/src/decision/providers/AndorraDecisionProvider.js +12 -0
- package/dist/src/decision/requestPhrases.js +0 -1
- package/dist/src/decision/taskKind.d.ts +52 -0
- package/dist/src/decision/taskKind.js +76 -0
- package/dist/src/decision/types.d.ts +1 -1
- package/dist/src/default-graph.js +1 -1
- package/dist/src/efficiency.d.ts +5 -0
- package/dist/src/efficiency.js +5 -1
- package/dist/src/effort-routing.d.ts +27 -0
- package/dist/src/effort-routing.js +34 -0
- package/dist/src/evidence.d.ts +110 -0
- package/dist/src/evidence.js +195 -0
- package/dist/src/file-diff.d.ts +4 -0
- package/dist/src/file-diff.js +2 -1
- package/dist/src/github-app/agent-writes.d.ts +102 -0
- package/dist/src/github-app/agent-writes.js +320 -0
- package/dist/src/github-app/client.d.ts +368 -0
- package/dist/src/github-app/client.js +830 -0
- package/dist/src/github-app/event-source.d.ts +208 -0
- package/dist/src/github-app/event-source.js +684 -0
- package/dist/src/github-app/metrics.d.ts +32 -0
- package/dist/src/github-app/metrics.js +49 -0
- package/dist/src/github-app/review-loop.d.ts +274 -0
- package/dist/src/github-app/review-loop.js +1177 -0
- package/dist/src/github-app/review-node.d.ts +81 -0
- package/dist/src/github-app/review-node.js +205 -0
- package/dist/src/github-app/review-post.d.ts +73 -0
- package/dist/src/github-app/review-post.js +139 -0
- package/dist/src/github-app/review-text.d.ts +107 -0
- package/dist/src/github-app/review-text.js +1133 -0
- package/dist/src/github-app/review-threads.d.ts +47 -0
- package/dist/src/github-app/review-threads.js +107 -0
- package/dist/src/github-app/reviewer.d.ts +121 -0
- package/dist/src/github-app/reviewer.js +598 -0
- package/dist/src/github-app/store.d.ts +59 -0
- package/dist/src/github-app/store.js +148 -0
- package/dist/src/github-app/triggers.d.ts +141 -0
- package/dist/src/github-app/triggers.js +441 -0
- package/dist/src/github-names.d.ts +15 -0
- package/dist/src/github-names.js +15 -0
- package/dist/src/glob-search.d.ts +61 -0
- package/dist/src/glob-search.js +180 -0
- package/dist/src/graph-health.js +6 -1
- package/dist/src/graph-manager-chat.js +1 -1
- package/dist/src/graph-preview.d.ts +48 -0
- package/dist/src/graph-preview.js +56 -0
- package/dist/src/graph-provider-portability.js +2 -1
- package/dist/src/graph-runner.js +65 -4
- package/dist/src/graph-server.js +7 -5
- package/dist/src/graph-sync.js +3 -3
- package/dist/src/graph-ui/app.js +121 -7
- package/dist/src/graph-ui/icons.js +2 -1
- package/dist/src/graph-ui/studio.js +15 -1
- package/dist/src/graph-ui/tokens.css +1 -1
- package/dist/src/graphs.d.ts +40 -1
- package/dist/src/graphs.js +164 -15
- package/dist/src/hardened-runtime.js +32 -21
- package/dist/src/image-input.d.ts +16 -0
- package/dist/src/image-input.js +41 -0
- package/dist/src/membership.d.ts +10 -0
- package/dist/src/membership.js +19 -4
- package/dist/src/model-health-cache.js +1 -1
- package/dist/src/model-metadata.d.ts +6 -0
- package/dist/src/model-metadata.js +35 -15
- package/dist/src/model-override.d.ts +2 -1
- package/dist/src/model-override.js +9 -0
- package/dist/src/model-relay/local.d.ts +116 -0
- package/dist/src/model-relay/local.js +468 -0
- package/dist/src/model-relay/remote.d.ts +129 -0
- package/dist/src/model-relay/remote.js +252 -0
- package/dist/src/model-relay/runs.d.ts +34 -0
- package/dist/src/model-relay/runs.js +146 -0
- package/dist/src/model-relay/wire.d.ts +5 -0
- package/dist/src/model-relay/wire.js +5 -0
- package/dist/src/model-tiers.d.ts +3 -0
- package/dist/src/model-tiers.js +3 -3
- package/dist/src/project-registry.d.ts +21 -0
- package/dist/src/project-registry.js +74 -0
- package/dist/src/provider-engine.d.ts +13 -1
- package/dist/src/provider-engine.js +74 -0
- package/dist/src/provider-import.d.ts +0 -12
- package/dist/src/provider-import.js +7 -195
- package/dist/src/providers.d.ts +28 -2
- package/dist/src/providers.js +59 -12
- package/dist/src/pull-request-logs.d.ts +12 -1
- package/dist/src/pull-request-logs.js +14 -3
- package/dist/src/pull-requests.d.ts +338 -8
- package/dist/src/pull-requests.js +482 -53
- package/dist/src/react-runtime.js +99 -16
- package/dist/src/remote/engine-pool.d.ts +88 -4
- package/dist/src/remote/engine-pool.js +367 -90
- package/dist/src/remote/roots.d.ts +19 -0
- package/dist/src/remote/roots.js +45 -7
- package/dist/src/remote/types.d.ts +0 -44
- package/dist/src/run-control.d.ts +7 -0
- package/dist/src/run-control.js +23 -0
- package/dist/src/run-records.d.ts +7 -2
- package/dist/src/run-records.js +71 -6
- package/dist/src/runtime.d.ts +34 -2
- package/dist/src/runtime.js +18 -2
- package/dist/src/session-changes.d.ts +35 -0
- package/dist/src/session-changes.js +194 -6
- package/dist/src/session-monitor.js +2 -1
- package/dist/src/session-reaper.d.ts +1 -1
- package/dist/src/session-reaper.js +6 -1
- package/dist/src/session-summary.d.ts +2 -1
- package/dist/src/session-summary.js +2 -1
- package/dist/src/sessions.d.ts +35 -1
- package/dist/src/sessions.js +70 -4
- package/dist/src/skills/bundled/bug-report/SKILL.md +51 -7
- package/dist/src/skills/bundled/diagram/SKILL.md +5 -3
- package/dist/src/skills/bundled/graph-manager/SKILL.md +7 -4
- package/dist/src/skills/bundled/provenance.json +3 -3
- package/dist/src/skills/runtime-skills.js +1 -1
- package/dist/src/task-checkout.d.ts +141 -0
- package/dist/src/task-checkout.js +558 -0
- package/dist/src/telemetry/emitter.d.ts +15 -0
- package/dist/src/telemetry/emitter.js +35 -1
- package/dist/src/telemetry/schema.d.ts +25 -2
- package/dist/src/telemetry/schema.js +52 -4
- package/dist/src/telemetry/surface.d.ts +2 -1
- package/dist/src/telemetry/surface.js +4 -1
- package/dist/src/terminal-ui.d.ts +1 -0
- package/dist/src/terminal-ui.js +10 -3
- package/dist/src/test-edit-guard.d.ts +37 -0
- package/dist/src/test-edit-guard.js +216 -3
- package/dist/src/thinking-level-detect.d.ts +11 -0
- package/dist/src/thinking-level-detect.js +47 -0
- package/dist/src/thinking-levels.d.ts +30 -0
- package/dist/src/thinking-levels.js +124 -0
- package/dist/src/timers.d.ts +3 -0
- package/dist/src/tool-catalog.js +1 -1
- package/dist/src/tools.js +59 -9
- package/dist/src/transcript.js +1 -1
- package/dist/src/types.d.ts +34 -0
- package/package.json +6 -1
- package/dist/src/remote/cert.d.ts +0 -11
- package/dist/src/remote/cert.js +0 -87
- package/dist/src/remote/client.d.ts +0 -119
- package/dist/src/remote/client.js +0 -544
- package/dist/src/remote/command.d.ts +0 -4
- package/dist/src/remote/command.js +0 -194
- package/dist/src/remote/errors.d.ts +0 -11
- package/dist/src/remote/errors.js +0 -14
- package/dist/src/remote/network.d.ts +0 -22
- package/dist/src/remote/network.js +0 -102
- package/dist/src/remote/pairing.d.ts +0 -63
- package/dist/src/remote/pairing.js +0 -299
- package/dist/src/remote/pem.d.ts +0 -2
- package/dist/src/remote/pem.js +0 -7
- package/dist/src/remote/serve.d.ts +0 -68
- package/dist/src/remote/serve.js +0 -244
- package/dist/src/remote/server.d.ts +0 -21
- package/dist/src/remote/server.js +0 -406
|
@@ -0,0 +1,558 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process';
|
|
2
|
+
import { mkdir, readFile, readdir, readlink, realpath, rename, rm, rmdir, stat, writeFile } from 'node:fs/promises';
|
|
3
|
+
import { homedir, hostname } from 'node:os';
|
|
4
|
+
import { basename, dirname, isAbsolute, join, relative, resolve } from 'node:path';
|
|
5
|
+
const GIT_TIMEOUT_MS = 15_000;
|
|
6
|
+
const FETCH_TIMEOUT_MS = 15_000;
|
|
7
|
+
const MAX_BRANCHES = 1_000;
|
|
8
|
+
const MAX_SLUG = 40;
|
|
9
|
+
const MAX_SUFFIX = 99;
|
|
10
|
+
const KEY = /^[A-Za-z0-9_-]{8,64}$/;
|
|
11
|
+
/** Git asks no one for credentials or host keys: a start never waits on a prompt nobody can see. */
|
|
12
|
+
const QUIET_GIT = { GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', GCM_INTERACTIVE: 'never', GIT_OPTIONAL_LOCKS: '0' };
|
|
13
|
+
export class TaskCheckoutError extends Error {
|
|
14
|
+
}
|
|
15
|
+
function git(cwd, args, options = {}) {
|
|
16
|
+
return new Promise(resolvePromise => {
|
|
17
|
+
execFile('git', args, {
|
|
18
|
+
cwd, windowsHide: true, timeout: options.timeout ?? GIT_TIMEOUT_MS, maxBuffer: 4 << 20,
|
|
19
|
+
// GIT_OPTIONAL_LOCKS=0: reading the person's checkout never takes its index lock out from under their own Git.
|
|
20
|
+
env: { ...process.env, ...QUIET_GIT, ...(options.env ?? {}) },
|
|
21
|
+
}, (error, stdout, stderr) => {
|
|
22
|
+
const code = error === null ? 0 : typeof error.code === 'number' ? error.code : 1;
|
|
23
|
+
// Killed at the time limit: say so, rather than repeat the command line.
|
|
24
|
+
const timedOut = error !== null && error.killed === true;
|
|
25
|
+
const said = timedOut ? `no answer within ${Math.round((options.timeout ?? GIT_TIMEOUT_MS) / 1000)} seconds` : error !== null && !String(stderr).trim() ? error.message : String(stderr);
|
|
26
|
+
resolvePromise({ code, stdout: String(stdout), stderr: said });
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
async function gitOk(cwd, args, options) {
|
|
31
|
+
const result = await git(cwd, args, options);
|
|
32
|
+
if (result.code !== 0)
|
|
33
|
+
throw new TaskCheckoutError(firstLine(result.stderr) || `git ${args[0]} failed`);
|
|
34
|
+
return result.stdout;
|
|
35
|
+
}
|
|
36
|
+
function firstLine(text) {
|
|
37
|
+
return text.trim().split('\n').map(line => line.replace(/^(fatal|error):\s*/, '').trim()).find(Boolean)?.slice(0, 300) ?? '';
|
|
38
|
+
}
|
|
39
|
+
async function exists(path) {
|
|
40
|
+
return stat(path).then(() => true, () => false);
|
|
41
|
+
}
|
|
42
|
+
async function realOrSelf(path) {
|
|
43
|
+
return realpath(path).catch(() => resolve(path));
|
|
44
|
+
}
|
|
45
|
+
/** The repository's top and where the project folder sits in it; undefined outside a repository. */
|
|
46
|
+
export async function repositoryOf(root) {
|
|
47
|
+
const shown = await git(root, ['rev-parse', '--show-toplevel', '--git-common-dir']);
|
|
48
|
+
if (shown.code !== 0)
|
|
49
|
+
return undefined;
|
|
50
|
+
const [topLine, commonLine] = shown.stdout.split('\n').map(line => line.trim());
|
|
51
|
+
if (!topLine || !commonLine)
|
|
52
|
+
return undefined;
|
|
53
|
+
const top = await realOrSelf(topLine);
|
|
54
|
+
const prefix = relative(top, await realOrSelf(root));
|
|
55
|
+
if (prefix.startsWith('..') || isAbsolute(prefix))
|
|
56
|
+
return undefined;
|
|
57
|
+
const commonDir = await realOrSelf(isAbsolute(commonLine) ? commonLine : join(root, commonLine));
|
|
58
|
+
return { top, prefix, commonDir };
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* The repository a project folder starts tasks from: one whose top is the folder or its parent, as the rest of the app
|
|
62
|
+
* reads a project's Git state (gitTop in app-server/workspace.ts). A folder deep inside an unrelated repository, such as
|
|
63
|
+
* a home directory kept in Git, is treated as a plain folder.
|
|
64
|
+
*/
|
|
65
|
+
async function projectRepository(root) {
|
|
66
|
+
const repository = await repositoryOf(root);
|
|
67
|
+
if (repository === undefined)
|
|
68
|
+
return undefined;
|
|
69
|
+
return repository.prefix.split(/[\\/]/).filter(Boolean).length > 1 ? undefined : repository;
|
|
70
|
+
}
|
|
71
|
+
async function refExists(cwd, ref) {
|
|
72
|
+
return (await git(cwd, ['show-ref', '--verify', '--quiet', ref])).code === 0;
|
|
73
|
+
}
|
|
74
|
+
async function currentBranch(cwd) {
|
|
75
|
+
const head = await git(cwd, ['symbolic-ref', '-q', '--short', 'HEAD']);
|
|
76
|
+
return head.code === 0 ? head.stdout.trim() || undefined : undefined;
|
|
77
|
+
}
|
|
78
|
+
async function dirtyCount(cwd) {
|
|
79
|
+
const status = await git(cwd, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);
|
|
80
|
+
if (status.code !== 0)
|
|
81
|
+
return 0;
|
|
82
|
+
let count = 0;
|
|
83
|
+
const records = status.stdout.split('\0');
|
|
84
|
+
for (let index = 0; index < records.length; index++) {
|
|
85
|
+
const record = records[index];
|
|
86
|
+
if (record.length < 4)
|
|
87
|
+
continue;
|
|
88
|
+
count++;
|
|
89
|
+
if (record[0] === 'R' || record[0] === 'C')
|
|
90
|
+
index++;
|
|
91
|
+
}
|
|
92
|
+
return count;
|
|
93
|
+
}
|
|
94
|
+
/** The default branch: origin's HEAD, else `main` or `master` on origin, else locally. */
|
|
95
|
+
async function defaultBranchOf(cwd) {
|
|
96
|
+
const head = await git(cwd, ['symbolic-ref', '-q', '--short', 'refs/remotes/origin/HEAD']);
|
|
97
|
+
const named = head.code === 0 ? head.stdout.trim().replace(/^origin\//, '') : '';
|
|
98
|
+
if (named && await refExists(cwd, `refs/remotes/origin/${named}`))
|
|
99
|
+
return { branch: named, ref: `origin/${named}`, remote: true };
|
|
100
|
+
for (const name of ['main', 'master']) {
|
|
101
|
+
if (await refExists(cwd, `refs/remotes/origin/${name}`))
|
|
102
|
+
return { branch: name, ref: `origin/${name}`, remote: true };
|
|
103
|
+
}
|
|
104
|
+
for (const name of [named, 'main', 'master'].filter(Boolean)) {
|
|
105
|
+
if (await refExists(cwd, `refs/heads/${name}`))
|
|
106
|
+
return { branch: name, ref: name, remote: false };
|
|
107
|
+
}
|
|
108
|
+
return undefined;
|
|
109
|
+
}
|
|
110
|
+
async function fetchedAt(commonDir) {
|
|
111
|
+
const info = await stat(join(commonDir, 'FETCH_HEAD')).catch(() => undefined);
|
|
112
|
+
return info ? info.mtime.toISOString() : undefined;
|
|
113
|
+
}
|
|
114
|
+
/** What New Task offers to start from in `root`'s repository. */
|
|
115
|
+
export async function taskStartPoints(root) {
|
|
116
|
+
const repository = await projectRepository(root);
|
|
117
|
+
if (repository === undefined)
|
|
118
|
+
return { repository: false, dirty: 0, branches: [] };
|
|
119
|
+
const [current, dirty, fallback, fetched, listed] = await Promise.all([
|
|
120
|
+
currentBranch(root), dirtyCount(root), defaultBranchOf(root), fetchedAt(repository.commonDir),
|
|
121
|
+
git(root, ['for-each-ref', '--format=%(refname:lstrip=2)', '--sort=-committerdate', 'refs/heads']),
|
|
122
|
+
]);
|
|
123
|
+
const all = listed.code === 0 ? listed.stdout.split('\n').map(line => line.trim()).filter(Boolean) : [];
|
|
124
|
+
const others = all.filter(name => name !== current && name !== fallback?.branch);
|
|
125
|
+
return {
|
|
126
|
+
repository: true,
|
|
127
|
+
...(current === undefined ? {} : { current }),
|
|
128
|
+
dirty,
|
|
129
|
+
...(fallback === undefined ? {} : { defaultBranch: fallback.branch, defaultRef: fallback.ref }),
|
|
130
|
+
...(fallback?.remote && fetched !== undefined ? { fetchedAt: fetched } : {}),
|
|
131
|
+
branches: others.slice(0, MAX_BRANCHES),
|
|
132
|
+
...(others.length > MAX_BRANCHES ? { truncated: true } : {}),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
/** A task branch's name from the prompt: lower case, hyphens, at most 40 characters. */
|
|
136
|
+
export function taskSlug(text) {
|
|
137
|
+
const slug = text.toLowerCase().normalize('NFKD').replace(/[̀-ͯ]/g, '')
|
|
138
|
+
.replace(/[^a-z0-9]+/g, '-').replace(/^-+/, '').slice(0, MAX_SLUG).replace(/-+$/, '');
|
|
139
|
+
// A Windows device name cannot be a folder there.
|
|
140
|
+
return !slug ? 'task' : /^(con|prn|aux|nul|com\d|lpt\d)$/.test(slug) ? `${slug}-task` : slug;
|
|
141
|
+
}
|
|
142
|
+
function folderName(root) {
|
|
143
|
+
return basename(root).replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[.-]+/, '').slice(0, 64) || 'project';
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Where task worktrees go: `~/worktrees/<project>/<slug>`, outside Andorra's home, whose files the permission rules
|
|
147
|
+
* protect from the agent.
|
|
148
|
+
*/
|
|
149
|
+
export function worktreesRoot() {
|
|
150
|
+
return join(homedir(), 'worktrees');
|
|
151
|
+
}
|
|
152
|
+
/** The folder a project's task worktrees go in. */
|
|
153
|
+
export function worktreesFolder(root, under = worktreesRoot()) {
|
|
154
|
+
return join(under, folderName(root));
|
|
155
|
+
}
|
|
156
|
+
/** Andorra's record of a start's preparation, so a retried start reuses its worktree. */
|
|
157
|
+
function preparedFile(home, key) {
|
|
158
|
+
return join(home, 'task-starts', `${key}.json`);
|
|
159
|
+
}
|
|
160
|
+
async function readPrepared(home, key) {
|
|
161
|
+
try {
|
|
162
|
+
const value = JSON.parse(await readFile(preparedFile(home, key), 'utf8'));
|
|
163
|
+
return value && value.key === key && validCheckout(value.prepared?.checkout) ? value : undefined;
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
async function writePrepared(home, record) {
|
|
170
|
+
const file = preparedFile(home, record.key);
|
|
171
|
+
await mkdir(dirname(file), { recursive: true });
|
|
172
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
173
|
+
await writeFile(temporary, JSON.stringify(record));
|
|
174
|
+
await rename(temporary, file);
|
|
175
|
+
}
|
|
176
|
+
const START_RECORD_DAYS = 7;
|
|
177
|
+
/** Drops start records a week old: their starts began, were given up, or the app was closed on them. */
|
|
178
|
+
async function pruneStartRecords(home) {
|
|
179
|
+
const folder = join(home, 'task-starts');
|
|
180
|
+
const names = await readdir(folder).catch(() => []);
|
|
181
|
+
const before = Date.now() - START_RECORD_DAYS * 86_400_000;
|
|
182
|
+
for (const name of names) {
|
|
183
|
+
const file = join(folder, name);
|
|
184
|
+
const info = await stat(file).catch(() => undefined);
|
|
185
|
+
if (info !== undefined && info.mtimeMs < before)
|
|
186
|
+
await rm(file, { force: true }).catch(() => { });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
/** Forgets a start's preparation, once its task has begun or it was given up. */
|
|
190
|
+
export async function forgetPrepared(home, key) {
|
|
191
|
+
if (!KEY.test(key))
|
|
192
|
+
return;
|
|
193
|
+
await rm(preparedFile(home, key), { force: true }).catch(() => { });
|
|
194
|
+
}
|
|
195
|
+
/** The prepared checkout a run.start names, checked to belong to `root`'s repository. */
|
|
196
|
+
export async function takePrepared(home, root, key) {
|
|
197
|
+
if (!KEY.test(key))
|
|
198
|
+
throw new TaskCheckoutError('That start has no prepared worktree.');
|
|
199
|
+
const record = await readPrepared(home, key);
|
|
200
|
+
if (record === undefined || resolve(record.root) !== resolve(root))
|
|
201
|
+
throw new TaskCheckoutError('That start has no prepared worktree. Start the task again.');
|
|
202
|
+
const state = await checkoutState(record.prepared.checkout, root);
|
|
203
|
+
if (state.state !== 'ok')
|
|
204
|
+
throw new TaskCheckoutError(state.reason);
|
|
205
|
+
return record.prepared.checkout;
|
|
206
|
+
}
|
|
207
|
+
/**
|
|
208
|
+
* Makes a writing task's worktree: resolves `base` to a commit (refreshing the default branch from its remote first),
|
|
209
|
+
* then adds a worktree on a new `task/<slug>` branch in `~/worktrees/<project>`. Names stay distinct across simultaneous
|
|
210
|
+
* starts. The same `key` returns the same worktree while it still stands, so a retried start reuses its preparation.
|
|
211
|
+
*/
|
|
212
|
+
export async function prepareTaskWorktree(options) {
|
|
213
|
+
const { home, root, key } = options;
|
|
214
|
+
if (!KEY.test(key))
|
|
215
|
+
throw new TaskCheckoutError('A start key is required.');
|
|
216
|
+
const previous = await readPrepared(home, key);
|
|
217
|
+
if (previous !== undefined && resolve(previous.root) === resolve(root)) {
|
|
218
|
+
if ((await checkoutState(previous.prepared.checkout, root)).state === 'ok')
|
|
219
|
+
return { ...previous.prepared, reused: true };
|
|
220
|
+
await forgetPrepared(home, key);
|
|
221
|
+
}
|
|
222
|
+
const repository = await projectRepository(root);
|
|
223
|
+
if (repository === undefined)
|
|
224
|
+
throw new TaskCheckoutError('The project folder is not in a Git repository, so the task cannot have its own worktree.');
|
|
225
|
+
await pruneStartRecords(home);
|
|
226
|
+
const base = options.base.trim();
|
|
227
|
+
if (!base || base.startsWith('-') || (await git(root, ['check-ref-format', '--branch', base])).code !== 0) {
|
|
228
|
+
throw new TaskCheckoutError(`Not a branch to start from: ${base || '(none)'}`);
|
|
229
|
+
}
|
|
230
|
+
const fallback = await defaultBranchOf(root);
|
|
231
|
+
let ref;
|
|
232
|
+
// Resolved by its full name, so a tag that shares the branch's name is never taken instead.
|
|
233
|
+
let fullRef;
|
|
234
|
+
let refreshed;
|
|
235
|
+
let refreshError;
|
|
236
|
+
if (fallback !== undefined && fallback.branch === base && fallback.remote) {
|
|
237
|
+
const fetched = await git(root, ['fetch', '--no-tags', '--quiet', 'origin', `+refs/heads/${base}:refs/remotes/origin/${base}`], { timeout: FETCH_TIMEOUT_MS });
|
|
238
|
+
refreshed = fetched.code === 0;
|
|
239
|
+
if (!refreshed)
|
|
240
|
+
refreshError = firstLine(fetched.stderr) || 'the fetch did not finish';
|
|
241
|
+
ref = `origin/${base}`;
|
|
242
|
+
fullRef = `refs/remotes/origin/${base}`;
|
|
243
|
+
}
|
|
244
|
+
else if (await refExists(root, `refs/heads/${base}`)) {
|
|
245
|
+
ref = base;
|
|
246
|
+
fullRef = `refs/heads/${base}`;
|
|
247
|
+
}
|
|
248
|
+
else if (await refExists(root, `refs/remotes/origin/${base}`)) {
|
|
249
|
+
ref = `origin/${base}`;
|
|
250
|
+
fullRef = `refs/remotes/origin/${base}`;
|
|
251
|
+
}
|
|
252
|
+
else {
|
|
253
|
+
throw new TaskCheckoutError(`There is no branch named ${base} to start from.`);
|
|
254
|
+
}
|
|
255
|
+
const commit = (await gitOk(root, ['rev-parse', '--verify', '--quiet', `${fullRef}^{commit}`])).trim();
|
|
256
|
+
if (!/^[0-9a-f]{40,64}$/.test(commit))
|
|
257
|
+
throw new TaskCheckoutError(`${ref} does not name a commit.`);
|
|
258
|
+
// A project below the repository's top must be in the commit, or the worktree would not hold it.
|
|
259
|
+
if (repository.prefix && (await git(root, ['cat-file', '-e', `${commit}:${repository.prefix.split(/[\\]/).join('/')}`])).code !== 0) {
|
|
260
|
+
throw new TaskCheckoutError(`${repository.prefix} is not in ${ref}, so a worktree from it would not hold this project. Commit the folder first, or use the current checkout.`);
|
|
261
|
+
}
|
|
262
|
+
// A branch named `task` leaves no room for task/<slug> branches.
|
|
263
|
+
if (await refExists(root, 'refs/heads/task'))
|
|
264
|
+
throw new TaskCheckoutError('A branch named “task” exists, so task/<name> branches cannot be made. Rename that branch, or use the current checkout.');
|
|
265
|
+
const folder = worktreesFolder(root, options.worktrees);
|
|
266
|
+
try {
|
|
267
|
+
await mkdir(folder, { recursive: true });
|
|
268
|
+
}
|
|
269
|
+
catch (error) {
|
|
270
|
+
const code = error.code;
|
|
271
|
+
throw new TaskCheckoutError(`The worktree could not be created: ${folder} ${code === 'EEXIST' || code === 'ENOTDIR' ? 'is a file, not a folder' : code === 'EACCES' || code === 'EPERM' ? 'cannot be written' : `could not be made (${code ?? 'unknown error'})`}.`);
|
|
272
|
+
}
|
|
273
|
+
const slug = taskSlug(options.slug);
|
|
274
|
+
for (let suffix = 1; suffix <= MAX_SUFFIX; suffix++) {
|
|
275
|
+
const name = suffix === 1 ? slug : `${slug}-${suffix}`;
|
|
276
|
+
const branch = `task/${name}`;
|
|
277
|
+
const worktree = join(folder, name);
|
|
278
|
+
if (await refExists(root, `refs/heads/${branch}`))
|
|
279
|
+
continue;
|
|
280
|
+
// Taking the folder first claims the name: a second start that picked it moves on.
|
|
281
|
+
try {
|
|
282
|
+
await mkdir(worktree);
|
|
283
|
+
}
|
|
284
|
+
catch (error) {
|
|
285
|
+
if (error.code === 'EEXIST')
|
|
286
|
+
continue;
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
const added = await git(repository.top, ['worktree', 'add', '--quiet', '-b', branch, worktree, commit], { timeout: 120_000 });
|
|
290
|
+
if (added.code !== 0) {
|
|
291
|
+
await rm(worktree, { recursive: true, force: true }).catch(() => { });
|
|
292
|
+
if (/already exists|cannot lock ref|is already checked out|already used by worktree/i.test(added.stderr))
|
|
293
|
+
continue;
|
|
294
|
+
throw new TaskCheckoutError(`The worktree could not be created: ${firstLine(added.stderr) || 'git worktree add failed'}`);
|
|
295
|
+
}
|
|
296
|
+
const top = await realOrSelf(worktree);
|
|
297
|
+
const checkout = {
|
|
298
|
+
kind: 'worktree', path: repository.prefix ? join(top, repository.prefix) : top, host: hostname(), branch,
|
|
299
|
+
baseBranch: base, baseRef: ref, baseCommit: commit, ...(repository.prefix ? { worktree: top } : {}),
|
|
300
|
+
createdAt: new Date().toISOString(),
|
|
301
|
+
};
|
|
302
|
+
const prepared = { checkout, ...(refreshed === undefined ? {} : { refreshed }), ...(refreshError === undefined ? {} : { refreshError }) };
|
|
303
|
+
await writePrepared(home, { key, root: resolve(root), prepared });
|
|
304
|
+
return prepared;
|
|
305
|
+
}
|
|
306
|
+
throw new TaskCheckoutError(`Every task branch name for ${slug} is taken. Rename the task and start again.`);
|
|
307
|
+
}
|
|
308
|
+
/** What an in-place task records: the project folder, and the branch and commit it began on. */
|
|
309
|
+
export async function inPlaceCheckout(root) {
|
|
310
|
+
const repository = await projectRepository(root);
|
|
311
|
+
const createdAt = new Date().toISOString();
|
|
312
|
+
if (repository === undefined)
|
|
313
|
+
return { kind: 'folder', path: root, host: hostname(), createdAt };
|
|
314
|
+
const branch = await currentBranch(root);
|
|
315
|
+
const head = await git(root, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']);
|
|
316
|
+
const commit = head.code === 0 ? head.stdout.trim() : undefined;
|
|
317
|
+
return { kind: 'checkout', path: root, host: hostname(), ...(branch ? { branch, baseBranch: branch, baseRef: branch } : {}), ...(commit ? { baseCommit: commit } : {}), createdAt };
|
|
318
|
+
}
|
|
319
|
+
export function checkoutTop(checkout) {
|
|
320
|
+
return checkout.worktree ?? checkout.path;
|
|
321
|
+
}
|
|
322
|
+
/** Whether a task's recorded worktree is still where it was, a worktree of `root`'s repository. */
|
|
323
|
+
export async function checkoutState(checkout, root) {
|
|
324
|
+
// An in-place task works in its project's folder, wherever the project now is.
|
|
325
|
+
if (checkout.kind !== 'worktree')
|
|
326
|
+
return { state: 'ok' };
|
|
327
|
+
if (checkout.removedAt !== undefined)
|
|
328
|
+
return { state: 'removed', reason: `This task's worktree was removed.${checkout.branch ? ` Its branch ${checkout.branch} keeps its commits.` : ''}` };
|
|
329
|
+
const top = checkoutTop(checkout);
|
|
330
|
+
// A machine's name can change under it, so only a folder that is not here is put down to another machine.
|
|
331
|
+
if (!await exists(top)) {
|
|
332
|
+
return checkout.host !== hostname()
|
|
333
|
+
? { state: 'other-host', reason: `This task's worktree ${top} is on ${checkout.host}, not on this computer.` }
|
|
334
|
+
: { state: 'missing', reason: `This task's worktree ${top} is missing.` };
|
|
335
|
+
}
|
|
336
|
+
const shown = await repositoryOf(checkout.path);
|
|
337
|
+
const project = await repositoryOf(root);
|
|
338
|
+
if (shown === undefined || project === undefined || shown.commonDir !== project.commonDir || shown.top !== await realOrSelf(top)) {
|
|
339
|
+
return { state: 'moved', reason: `${top} is no longer this task's worktree.` };
|
|
340
|
+
}
|
|
341
|
+
// The agent may switch branches, rebase or bisect in its worktree: that is its work, not a moved folder.
|
|
342
|
+
return { state: 'ok' };
|
|
343
|
+
}
|
|
344
|
+
/** Adds the worktree back at its recorded place from the task branch, which keeps every commit the task made. */
|
|
345
|
+
export async function recreateTaskWorktree(checkout, root) {
|
|
346
|
+
if (checkout.kind !== 'worktree' || checkout.branch === undefined)
|
|
347
|
+
throw new TaskCheckoutError('Only a task worktree can be recreated.');
|
|
348
|
+
const repository = await repositoryOf(root);
|
|
349
|
+
if (repository === undefined)
|
|
350
|
+
throw new TaskCheckoutError('The project folder is no longer in a Git repository.');
|
|
351
|
+
const top = checkoutTop(checkout);
|
|
352
|
+
if (await exists(top) && (await readdir(top)).length > 0)
|
|
353
|
+
throw new TaskCheckoutError(`${top} already exists and is not empty. Move it aside, or locate it instead.`);
|
|
354
|
+
// A branch removed with an empty worktree is made again at the commit the task started from.
|
|
355
|
+
const branchKept = await refExists(root, `refs/heads/${checkout.branch}`);
|
|
356
|
+
if (!branchKept && checkout.baseCommit === undefined)
|
|
357
|
+
throw new TaskCheckoutError(`The task branch ${checkout.branch} no longer exists, so its worktree cannot be recreated.`);
|
|
358
|
+
await mkdir(dirname(top), { recursive: true });
|
|
359
|
+
// --force takes over this worktree's stale registration without pruning anyone else's.
|
|
360
|
+
const added = await git(repository.top, ['worktree', 'add', '--quiet', '--force', ...(branchKept ? [top, checkout.branch] : ['-b', checkout.branch, top, checkout.baseCommit])], { timeout: 120_000 });
|
|
361
|
+
if (added.code !== 0)
|
|
362
|
+
throw new TaskCheckoutError(`The worktree could not be recreated: ${firstLine(added.stderr) || 'git worktree add failed'}`);
|
|
363
|
+
const { removedAt: _removed, ...kept } = checkout;
|
|
364
|
+
return kept;
|
|
365
|
+
}
|
|
366
|
+
/** Takes a folder the lead picked as the task's moved worktree, once it is on the task branch in the same repository. */
|
|
367
|
+
export async function locateTaskWorktree(checkout, root, picked) {
|
|
368
|
+
if (checkout.kind !== 'worktree')
|
|
369
|
+
throw new TaskCheckoutError('Only a task worktree can be located.');
|
|
370
|
+
const folder = await realpath(picked).catch(() => { throw new TaskCheckoutError(`${picked} does not exist.`); });
|
|
371
|
+
const project = await repositoryOf(root);
|
|
372
|
+
if (project === undefined)
|
|
373
|
+
throw new TaskCheckoutError('The project folder is no longer in a Git repository.');
|
|
374
|
+
// Before repair, a moved worktree's registration still names where it was: that proves it is this task's.
|
|
375
|
+
const registered = await registeredPath(folder);
|
|
376
|
+
const same = registered !== undefined && resolve(registered) === resolve(join(checkoutTop(checkout), '.git'));
|
|
377
|
+
// The folder may be one whose links went stale when it moved: repairing them first lets Git read it.
|
|
378
|
+
await git(project.top, ['worktree', 'repair', folder]);
|
|
379
|
+
const found = await repositoryOf(folder);
|
|
380
|
+
if (found === undefined)
|
|
381
|
+
throw new TaskCheckoutError(`${folder} is not a Git worktree.`);
|
|
382
|
+
if (found.commonDir !== project.commonDir)
|
|
383
|
+
throw new TaskCheckoutError(`${folder} belongs to another repository.`);
|
|
384
|
+
if (found.top === project.top)
|
|
385
|
+
throw new TaskCheckoutError(`${folder} is the project's own checkout, not the task's worktree.`);
|
|
386
|
+
// The task's own worktree holds its branch: on it, or moved on from it to a branch or commit of the agent's.
|
|
387
|
+
const branch = await currentBranch(found.top);
|
|
388
|
+
if (!same && checkout.branch !== undefined && branch !== checkout.branch) {
|
|
389
|
+
// Containment proves it only once the task branch has commits of its own, and never for another task's branch.
|
|
390
|
+
const head = await git(root, ['rev-parse', '--verify', '--quiet', `refs/heads/${checkout.branch}^{commit}`]);
|
|
391
|
+
const advanced = head.code === 0 && head.stdout.trim() !== checkout.baseCommit;
|
|
392
|
+
const onward = advanced && !branch?.startsWith('task/')
|
|
393
|
+
&& (await git(found.top, ['merge-base', '--is-ancestor', `refs/heads/${checkout.branch}`, 'HEAD'])).code === 0;
|
|
394
|
+
if (!onward)
|
|
395
|
+
throw new TaskCheckoutError(`${folder} is on ${branch ?? 'a detached commit'}, which does not hold ${checkout.branch}.`);
|
|
396
|
+
}
|
|
397
|
+
const prefix = checkout.worktree === undefined ? '' : relative(checkout.worktree, checkout.path);
|
|
398
|
+
const { removedAt: _removed, worktree: _top, ...kept } = checkout;
|
|
399
|
+
return { ...kept, path: prefix ? join(found.top, prefix) : found.top, ...(prefix ? { worktree: found.top } : {}) };
|
|
400
|
+
}
|
|
401
|
+
/** The path a worktree's registration in its repository records for it (`<common>/worktrees/<name>/gitdir`). */
|
|
402
|
+
async function registeredPath(folder) {
|
|
403
|
+
const link = await readFile(join(folder, '.git'), 'utf8').catch(() => undefined);
|
|
404
|
+
const admin = link?.match(/^gitdir:\s*(.+)\s*$/m)?.[1]?.trim();
|
|
405
|
+
if (admin === undefined)
|
|
406
|
+
return undefined;
|
|
407
|
+
const recorded = await readFile(join(isAbsolute(admin) ? admin : join(folder, admin), 'gitdir'), 'utf8').catch(() => undefined);
|
|
408
|
+
return recorded?.trim() || undefined;
|
|
409
|
+
}
|
|
410
|
+
const LISTED = 20;
|
|
411
|
+
/** What removing a task's worktree would lose, and what holds it. */
|
|
412
|
+
export async function inspectWorktreeRemoval(checkout, root) {
|
|
413
|
+
if (checkout.kind !== 'worktree')
|
|
414
|
+
throw new TaskCheckoutError('This task works in the project folder, not in a worktree of its own.');
|
|
415
|
+
const top = checkoutTop(checkout);
|
|
416
|
+
const status = await git(top, ['status', '--porcelain=v1', '-z', '--untracked-files=all']);
|
|
417
|
+
const files = [];
|
|
418
|
+
if (status.code === 0) {
|
|
419
|
+
const records = status.stdout.split('\0');
|
|
420
|
+
for (let index = 0; index < records.length; index++) {
|
|
421
|
+
const record = records[index];
|
|
422
|
+
if (record.length < 4)
|
|
423
|
+
continue;
|
|
424
|
+
files.push(record.slice(3));
|
|
425
|
+
if (record[0] === 'R' || record[0] === 'C')
|
|
426
|
+
index++;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
const ignoredStatus = await git(top, ['status', '--porcelain=v1', '-z', '--ignored=matching', '--untracked-files=normal']);
|
|
430
|
+
const ignored = ignoredStatus.code === 0 ? ignoredStatus.stdout.split('\0').filter(record => record.startsWith('!! ')).map(record => record.slice(3)) : [];
|
|
431
|
+
const unmerged = await unmergedCommits(checkout, root);
|
|
432
|
+
const processes = await processesInside(top);
|
|
433
|
+
return {
|
|
434
|
+
dirty: { count: files.length, files: files.slice(0, LISTED) },
|
|
435
|
+
ignored: { count: ignored.length, files: ignored.slice(0, LISTED) },
|
|
436
|
+
unmerged,
|
|
437
|
+
...(processes === undefined ? {} : { processes }),
|
|
438
|
+
};
|
|
439
|
+
}
|
|
440
|
+
async function unmergedCommits(checkout, root) {
|
|
441
|
+
if (checkout.branch === undefined || !await refExists(root, `refs/heads/${checkout.branch}`))
|
|
442
|
+
return { count: 0, commits: [] };
|
|
443
|
+
const fallback = await defaultBranchOf(root);
|
|
444
|
+
const exclude = ['--not', '--remotes', ...(fallback ? [`refs/heads/${fallback.branch}`] : [])];
|
|
445
|
+
const counted = await git(root, ['rev-list', '--count', `refs/heads/${checkout.branch}`, ...exclude]);
|
|
446
|
+
const count = counted.code === 0 ? Number.parseInt(counted.stdout.trim(), 10) || 0 : 0;
|
|
447
|
+
if (count === 0)
|
|
448
|
+
return { count: 0, commits: [] };
|
|
449
|
+
const listed = await git(root, ['log', `--max-count=${LISTED}`, '--format=%h %s', `refs/heads/${checkout.branch}`, ...exclude]);
|
|
450
|
+
return { count, commits: listed.code === 0 ? listed.stdout.split('\n').map(line => line.trim()).filter(Boolean) : [] };
|
|
451
|
+
}
|
|
452
|
+
function insideFolder(folder, path) {
|
|
453
|
+
const below = relative(folder, path);
|
|
454
|
+
return below === '' || (!below.startsWith('..') && !isAbsolute(below));
|
|
455
|
+
}
|
|
456
|
+
/** Processes working inside `folder`, from /proc on Linux; undefined elsewhere. */
|
|
457
|
+
async function processesInside(folder) {
|
|
458
|
+
if (process.platform !== 'linux')
|
|
459
|
+
return undefined;
|
|
460
|
+
const target = await realOrSelf(folder);
|
|
461
|
+
let entries;
|
|
462
|
+
try {
|
|
463
|
+
entries = await readdir('/proc');
|
|
464
|
+
}
|
|
465
|
+
catch {
|
|
466
|
+
return undefined;
|
|
467
|
+
}
|
|
468
|
+
const names = [];
|
|
469
|
+
let count = 0;
|
|
470
|
+
for (const entry of entries) {
|
|
471
|
+
if (!/^\d+$/.test(entry) || Number(entry) === process.pid)
|
|
472
|
+
continue;
|
|
473
|
+
const cwd = await readlink(`/proc/${entry}/cwd`).catch(() => undefined);
|
|
474
|
+
if (cwd === undefined || !insideFolder(target, cwd))
|
|
475
|
+
continue;
|
|
476
|
+
count++;
|
|
477
|
+
const name = (await readFile(`/proc/${entry}/comm`, 'utf8').catch(() => '')).trim();
|
|
478
|
+
if (name && names.length < LISTED && !names.includes(name))
|
|
479
|
+
names.push(name);
|
|
480
|
+
}
|
|
481
|
+
return { count, names };
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
484
|
+
* Removes a task's worktree. Refused while a process works in it, or when it holds uncommitted files the lead was not
|
|
485
|
+
* shown (`expectDirty` is the count they saw). The branch is deleted only when no commit would be lost; otherwise it
|
|
486
|
+
* stays, holding the task's commits.
|
|
487
|
+
*/
|
|
488
|
+
export async function removeTaskWorktree(checkout, root, options) {
|
|
489
|
+
const check = await inspectWorktreeRemoval(checkout, root);
|
|
490
|
+
if (check.processes !== undefined && check.processes.count > 0) {
|
|
491
|
+
throw new TaskCheckoutError(`Close the task’s terminals and stop what is running in the worktree first (${check.processes.names.join(', ') || `${check.processes.count} processes`}).`);
|
|
492
|
+
}
|
|
493
|
+
if (check.dirty.count !== options.expectDirty)
|
|
494
|
+
throw new TaskCheckoutError('The worktree changed since it was checked. Check it again before removing it.');
|
|
495
|
+
const repository = await repositoryOf(root);
|
|
496
|
+
if (repository === undefined)
|
|
497
|
+
throw new TaskCheckoutError('The project folder is no longer in a Git repository.');
|
|
498
|
+
const top = checkoutTop(checkout);
|
|
499
|
+
const removed = await git(repository.top, ['worktree', 'remove', ...(check.dirty.count > 0 ? ['--force'] : []), top], { timeout: 120_000 });
|
|
500
|
+
if (removed.code !== 0 && await exists(top))
|
|
501
|
+
throw new TaskCheckoutError(`The worktree could not be removed: ${firstLine(removed.stderr) || 'git worktree remove failed'}`);
|
|
502
|
+
await rmdir(dirname(top)).catch(() => { });
|
|
503
|
+
let branchDeleted = false;
|
|
504
|
+
if (checkout.branch !== undefined && check.unmerged.count === 0 && await refExists(root, `refs/heads/${checkout.branch}`)) {
|
|
505
|
+
branchDeleted = (await git(repository.top, ['branch', '-D', checkout.branch])).code === 0;
|
|
506
|
+
}
|
|
507
|
+
return { checkout: { ...checkout, removedAt: new Date().toISOString() }, branchDeleted };
|
|
508
|
+
}
|
|
509
|
+
/** Removes a worktree a start made and never used: only while it is clean and its branch has no commit of its own. */
|
|
510
|
+
export async function discardPreparedWorktree(home, root, key) {
|
|
511
|
+
if (!KEY.test(key))
|
|
512
|
+
return false;
|
|
513
|
+
const record = await readPrepared(home, key);
|
|
514
|
+
if (record === undefined || resolve(record.root) !== resolve(root))
|
|
515
|
+
return false;
|
|
516
|
+
const checkout = record.prepared.checkout;
|
|
517
|
+
try {
|
|
518
|
+
if ((await checkoutState(checkout, root)).state !== 'ok') {
|
|
519
|
+
await forgetPrepared(home, key);
|
|
520
|
+
return false;
|
|
521
|
+
}
|
|
522
|
+
const top = checkoutTop(checkout);
|
|
523
|
+
const head = (await gitOk(top, ['rev-parse', 'HEAD'])).trim();
|
|
524
|
+
if (head !== checkout.baseCommit || await dirtyCount(top) > 0)
|
|
525
|
+
return false;
|
|
526
|
+
const repository = await repositoryOf(root);
|
|
527
|
+
if (repository === undefined)
|
|
528
|
+
return false;
|
|
529
|
+
if ((await git(repository.top, ['worktree', 'remove', top])).code !== 0)
|
|
530
|
+
return false;
|
|
531
|
+
if (checkout.branch !== undefined)
|
|
532
|
+
await git(repository.top, ['branch', '-D', checkout.branch]);
|
|
533
|
+
await forgetPrepared(home, key);
|
|
534
|
+
return true;
|
|
535
|
+
}
|
|
536
|
+
catch {
|
|
537
|
+
return false;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
export function validCheckout(value) {
|
|
541
|
+
if (value === null || typeof value !== 'object')
|
|
542
|
+
return false;
|
|
543
|
+
const entry = value;
|
|
544
|
+
const optionalText = (field) => entry[field] === undefined || (typeof entry[field] === 'string' && entry[field].length <= 4096);
|
|
545
|
+
return (entry.kind === 'worktree' || entry.kind === 'checkout' || entry.kind === 'folder')
|
|
546
|
+
&& typeof entry.path === 'string' && entry.path.length > 0 && entry.path.length <= 4096 && isAbsolute(entry.path)
|
|
547
|
+
&& typeof entry.host === 'string' && entry.host.length <= 256
|
|
548
|
+
&& typeof entry.createdAt === 'string' && Number.isFinite(Date.parse(entry.createdAt))
|
|
549
|
+
&& ['branch', 'baseBranch', 'baseRef', 'baseCommit', 'worktree', 'removedAt'].every(optionalText)
|
|
550
|
+
&& (entry.worktree === undefined || isAbsolute(entry.worktree));
|
|
551
|
+
}
|
|
552
|
+
/** What the agent is told about a task worktree. */
|
|
553
|
+
export function worktreeInstructions(checkout) {
|
|
554
|
+
if (checkout?.kind !== 'worktree')
|
|
555
|
+
return '';
|
|
556
|
+
const from = checkout.baseRef ? ` from ${checkout.baseRef}${checkout.baseCommit ? ` at ${checkout.baseCommit.slice(0, 7)}` : ''}` : '';
|
|
557
|
+
return `\n\nThis task works in its own Git worktree, ${checkout.path}, on the branch ${checkout.branch ?? '(detached)'}${from}. The person's own checkout of the project is elsewhere and is not touched. Files Git ignores, such as node_modules, build output and .env files, are not in this worktree: install or create what a build or test needs inside it.`;
|
|
558
|
+
}
|
|
@@ -45,5 +45,20 @@ export declare function emitRunStarted(context: TelemetryContext, input: RunDime
|
|
|
45
45
|
}): Promise<number | undefined>;
|
|
46
46
|
export declare function emitRunFinished(context: TelemetryContext, input: RunFinishInput): Promise<boolean>;
|
|
47
47
|
export declare function emitInterruptedRun(context: TelemetryContext, record: Record<string, unknown>): Promise<boolean>;
|
|
48
|
+
export interface GitHubWatchInput {
|
|
49
|
+
minutes: number;
|
|
50
|
+
coverage: {
|
|
51
|
+
state: string;
|
|
52
|
+
prs: number;
|
|
53
|
+
calls: number;
|
|
54
|
+
}[];
|
|
55
|
+
wakeLatencies: number[];
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* One window of the GitHub App watcher's counts (ADR 0021, `github.watch`): per coverage state, how many PRs
|
|
59
|
+
* were watched and how many gh calls the watcher made for them, and the Auto-fix wake latencies in whole
|
|
60
|
+
* seconds. Built field by field: no PR, repository, account or session reaches the record.
|
|
61
|
+
*/
|
|
62
|
+
export declare function emitGitHubWatch(context: TelemetryContext, input: GitHubWatchInput): Promise<boolean>;
|
|
48
63
|
export declare function engineSpoolId(prefix: string): string;
|
|
49
64
|
export declare function telemetryHome(home?: string): string;
|
|
@@ -5,7 +5,7 @@ import { classifyOutcome, classifyTaskCounts, stopReasonFor } from './classify.j
|
|
|
5
5
|
import { createRunTelemetry, hasRunTelemetry, recordRunError, savingsFrom } from './capture.js';
|
|
6
6
|
import { aggregateModelTuples } from './aggregate.js';
|
|
7
7
|
import { ensureInstallId, telemetryDirectory } from './identity.js';
|
|
8
|
-
import { TELEMETRY_PERMISSION_MODES, TELEMETRY_ROUTING, TELEMETRY_BOUNDS, bucketAppVersion, bucketArchitecture, bucketErrorCode, bucketGraph, bucketOperatingSystem, isMetadataTool, telemetryEventId, telemetryTimestamp, validateTelemetryEvent, } from './schema.js';
|
|
8
|
+
import { TELEMETRY_PERMISSION_MODES, TELEMETRY_ROUTING, TELEMETRY_BOUNDS, bucketAppVersion, bucketArchitecture, bucketErrorCode, bucketGraph, bucketOperatingSystem, isMetadataTool, TELEMETRY_GITHUB_COVERAGE, telemetryEventId, telemetrySchemaFor, telemetryTimestamp, validateTelemetryEvent, } from './schema.js';
|
|
9
9
|
import { telemetryGate } from './gate.js';
|
|
10
10
|
import { queueEvent } from './uploader.js';
|
|
11
11
|
import { appVersion } from './version.js';
|
|
@@ -247,6 +247,40 @@ export async function emitInterruptedRun(context, record) {
|
|
|
247
247
|
decisionRouting: typeof telemetry.decisionRouting === 'string' ? telemetry.decisionRouting : undefined,
|
|
248
248
|
});
|
|
249
249
|
}
|
|
250
|
+
/**
|
|
251
|
+
* One window of the GitHub App watcher's counts (ADR 0021, `github.watch`): per coverage state, how many PRs
|
|
252
|
+
* were watched and how many gh calls the watcher made for them, and the Auto-fix wake latencies in whole
|
|
253
|
+
* seconds. Built field by field: no PR, repository, account or session reaches the record.
|
|
254
|
+
*/
|
|
255
|
+
export async function emitGitHubWatch(context, input) {
|
|
256
|
+
let queued = false;
|
|
257
|
+
await safely(async () => {
|
|
258
|
+
const watched = TELEMETRY_GITHUB_COVERAGE.flatMap(coverage => {
|
|
259
|
+
const record = input.coverage.find(entry => entry.state === coverage);
|
|
260
|
+
if (!record || record.prs < 1)
|
|
261
|
+
return [];
|
|
262
|
+
return [{ coverage: coverage, prs: Math.min(record.prs, TELEMETRY_BOUNDS.watchedPrs), ghCalls: Math.max(0, Math.min(record.calls, TELEMETRY_BOUNDS.counter)) }];
|
|
263
|
+
});
|
|
264
|
+
if (!watched.length)
|
|
265
|
+
return;
|
|
266
|
+
const resolved = await identityFor(context);
|
|
267
|
+
if (!resolved)
|
|
268
|
+
return;
|
|
269
|
+
const latencies = input.wakeLatencies.slice(0, TELEMETRY_BOUNDS.wakeLatencies)
|
|
270
|
+
.map(seconds => Math.max(0, Math.min(TELEMETRY_BOUNDS.wakeLatencySeconds, Math.round(seconds))));
|
|
271
|
+
const event = {
|
|
272
|
+
...resolved.identity,
|
|
273
|
+
schema: telemetrySchemaFor('github.watch'),
|
|
274
|
+
event: 'github.watch',
|
|
275
|
+
minutes: Math.max(1, Math.min(TELEMETRY_BOUNDS.watchMinutes, Math.round(input.minutes))),
|
|
276
|
+
watched,
|
|
277
|
+
...(latencies.length ? { wakeLatencies: latencies } : {}),
|
|
278
|
+
};
|
|
279
|
+
await queue(context, resolved.generation, event);
|
|
280
|
+
queued = true;
|
|
281
|
+
});
|
|
282
|
+
return queued;
|
|
283
|
+
}
|
|
250
284
|
export function engineSpoolId(prefix) {
|
|
251
285
|
return `${prefix}-${process.pid}-${Math.random().toString(36).slice(2, 10)}`;
|
|
252
286
|
}
|