@andorra-labs/code 0.1.6 → 0.1.7

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 (108) hide show
  1. package/dist/src/agent-execution.js +404 -25
  2. package/dist/src/agent-mcp-catalog.d.ts +21 -0
  3. package/dist/src/agent-mcp-catalog.js +40 -0
  4. package/dist/src/agent-mcp.d.ts +19 -3
  5. package/dist/src/agent-mcp.js +18 -44
  6. package/dist/src/app-server/protocol.d.ts +25 -3
  7. package/dist/src/app-server/protocol.js +5 -1
  8. package/dist/src/app-server/workspace.d.ts +8 -1
  9. package/dist/src/app-server/workspace.js +43 -2
  10. package/dist/src/app-server.js +88 -3
  11. package/dist/src/auth/AuthManager.d.ts +33 -1
  12. package/dist/src/auth/AuthManager.js +138 -10
  13. package/dist/src/auth/callback-page.d.ts +4 -0
  14. package/dist/src/auth/callback-page.js +70 -0
  15. package/dist/src/auth/callback.d.ts +39 -0
  16. package/dist/src/auth/callback.js +146 -22
  17. package/dist/src/auth/index.d.ts +10 -6
  18. package/dist/src/auth/index.js +2 -2
  19. package/dist/src/auth/store.d.ts +142 -3
  20. package/dist/src/auth/store.js +334 -13
  21. package/dist/src/auth/types.d.ts +17 -1
  22. package/dist/src/auth-commands.d.ts +11 -2
  23. package/dist/src/auth-commands.js +14 -7
  24. package/dist/src/automation-tool.js +10 -2
  25. package/dist/src/automations.d.ts +5 -0
  26. package/dist/src/automations.js +10 -0
  27. package/dist/src/capabilities.d.ts +9 -3
  28. package/dist/src/capabilities.js +7 -3
  29. package/dist/src/cli.js +31 -4
  30. package/dist/src/codex-provider.js +12 -0
  31. package/dist/src/coding-tools.d.ts +5 -0
  32. package/dist/src/coding-tools.js +54 -48
  33. package/dist/src/commands.d.ts +5 -1
  34. package/dist/src/commands.js +7 -6
  35. package/dist/src/completion.js +46 -0
  36. package/dist/src/config.d.ts +48 -0
  37. package/dist/src/config.js +248 -10
  38. package/dist/src/context-budget.d.ts +7 -0
  39. package/dist/src/context-budget.js +18 -1
  40. package/dist/src/decision/FactContinuations.d.ts +41 -6
  41. package/dist/src/decision/FactContinuations.js +211 -64
  42. package/dist/src/decision/PreparedSteps.js +3 -1
  43. package/dist/src/decision/checks.d.ts +25 -0
  44. package/dist/src/decision/checks.js +77 -6
  45. package/dist/src/delegation-changes.d.ts +109 -0
  46. package/dist/src/delegation-changes.js +431 -0
  47. package/dist/src/graph-server.d.ts +1 -0
  48. package/dist/src/graph-server.js +15 -3
  49. package/dist/src/graph-sync.d.ts +15 -0
  50. package/dist/src/graph-sync.js +50 -1
  51. package/dist/src/graph-tool.d.ts +52 -0
  52. package/dist/src/graph-tool.js +136 -0
  53. package/dist/src/graph-ui/app.js +212 -43
  54. package/dist/src/graph-ui/controls.js +6 -0
  55. package/dist/src/graph-ui/drafts.js +39 -0
  56. package/dist/src/graph-ui/embed.js +1 -1
  57. package/dist/src/graph-ui/index.html +2 -2
  58. package/dist/src/graph-ui/studio.css +7 -5
  59. package/dist/src/graph-ui/style.css +46 -12
  60. package/dist/src/graphs.d.ts +15 -2
  61. package/dist/src/graphs.js +42 -13
  62. package/dist/src/hardened-runtime.d.ts +4 -4
  63. package/dist/src/hardened-runtime.js +109 -9
  64. package/dist/src/powershell-pool.d.ts +9 -0
  65. package/dist/src/powershell-pool.js +16 -0
  66. package/dist/src/provider-keys.d.ts +48 -0
  67. package/dist/src/provider-keys.js +121 -0
  68. package/dist/src/pull-requests.d.ts +14 -5
  69. package/dist/src/pull-requests.js +28 -10
  70. package/dist/src/qa/runtime/ProcessManager.d.ts +6 -0
  71. package/dist/src/qa/runtime/ProcessManager.js +16 -0
  72. package/dist/src/react-runtime.js +30 -2
  73. package/dist/src/read-image.d.ts +30 -0
  74. package/dist/src/read-image.js +97 -0
  75. package/dist/src/secret-redaction.d.ts +13 -0
  76. package/dist/src/secret-redaction.js +71 -0
  77. package/dist/src/session-summary.d.ts +10 -4
  78. package/dist/src/session-summary.js +14 -7
  79. package/dist/src/sessions.js +4 -1
  80. package/dist/src/skills/bundled/graph-manager/SKILL.md +14 -11
  81. package/dist/src/skills/bundled/provenance.json +1 -1
  82. package/dist/src/telemetry/schema.d.ts +1 -1
  83. package/dist/src/telemetry/schema.js +1 -1
  84. package/dist/src/terminal-ui.d.ts +9 -0
  85. package/dist/src/terminal-ui.js +14 -0
  86. package/dist/src/tool-dependencies.js +4 -0
  87. package/dist/src/tools.d.ts +9 -0
  88. package/dist/src/tools.js +116 -11
  89. package/dist/src/transcript.js +5 -0
  90. package/dist/src/types.d.ts +13 -0
  91. package/dist/src/web-search.d.ts +59 -0
  92. package/dist/src/web-search.js +216 -0
  93. package/docs/agents/README.md +2 -2
  94. package/docs/agents/mcp-server.md +15 -2
  95. package/docs/concepts/README.md +1 -1
  96. package/docs/concepts/security.md +2 -2
  97. package/docs/getting-started/accounts.md +15 -4
  98. package/docs/getting-started/configure-providers.md +1 -1
  99. package/docs/guides/README.md +1 -0
  100. package/docs/guides/desktop-app.md +1 -1
  101. package/docs/guides/graph-builder.md +1 -1
  102. package/docs/guides/web-search.md +47 -0
  103. package/docs/reference/cli.md +4 -3
  104. package/docs/reference/config.md +3 -3
  105. package/docs/reference/slash-commands.md +2 -1
  106. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +295 -0
  107. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +291 -0
  108. package/package.json +1 -1
@@ -0,0 +1,109 @@
1
+ /** Characters of a change's diff that are inlined into the spawn observation. */
2
+ export declare const DELEGATION_DIFF_LIMIT = 20000;
3
+ /** The repository toplevel for a workspace, which may be a subfolder of the repository. */
4
+ export declare function repositoryRoot(workspace: string, signal: AbortSignal): Promise<string>;
5
+ /** Checks the Git the delegation path depends on before any worktree is created. */
6
+ export declare function assertDelegationGit(workspace: string, signal: AbortSignal): Promise<void>;
7
+ /**
8
+ * A commit whose tree is the working folder as it stands (tracked plus untracked non-ignored files)
9
+ * and whose parent is HEAD. It is the base a writing subagent starts from and is diffed against.
10
+ */
11
+ export declare function snapshotWorkspace(workspace: string, signal: AbortSignal): Promise<string>;
12
+ /** A detached worktree at `commit` under a fresh temporary directory. */
13
+ export declare function addChangeWorktree(workspace: string, commit: string, signal: AbortSignal): Promise<string>;
14
+ export interface CollectedChange {
15
+ tree: string;
16
+ files: {
17
+ path: string;
18
+ status: 'A' | 'M' | 'D' | 'R';
19
+ }[];
20
+ diff: string;
21
+ /** Every path the change writes or removes, relative to the repository root: `files`, plus the path a rename moved away from. */
22
+ paths: string[];
23
+ }
24
+ /**
25
+ * The worktree's final files against the snapshot it started from. Commits the subagent made inside
26
+ * the worktree do not matter: the tree is taken from disk, the way the snapshot was.
27
+ */
28
+ export declare function collectChange(worktree: string, base: string, signal: AbortSignal): Promise<CollectedChange>;
29
+ /** `stale`: the landing was refused because the working folder changed after it was prepared. */
30
+ export type LandResult = {
31
+ landed: true;
32
+ files: string[];
33
+ } | {
34
+ landed: false;
35
+ conflicts: string[];
36
+ detail: string;
37
+ stale?: true;
38
+ };
39
+ /**
40
+ * Landing wrote part of a change and could not put the working folder back. The message names the
41
+ * snapshot commit that holds the folder as it was and the paths that were not restored.
42
+ */
43
+ export declare class LandingRestoreError extends Error {
44
+ readonly snapshot: string;
45
+ readonly paths: string[];
46
+ constructor(message: string, snapshot: string, paths: string[]);
47
+ }
48
+ /**
49
+ * A landing that merged cleanly and has not been written yet: the patch that turns the working
50
+ * folder as it stood (`ours`) into the merged result, and every path that patch writes or removes.
51
+ */
52
+ export interface PreparedLanding {
53
+ root: string;
54
+ /** The snapshot commit of the working folder the patch was made against. */
55
+ ours: string;
56
+ /**
57
+ * Every path the patch writes or removes, relative to the repository root. These are where the
58
+ * change ends up after the merge, which is not always where the subagent made it: a file the
59
+ * user renamed meanwhile takes the subagent's edit at its new path.
60
+ */
61
+ files: string[];
62
+ patch: Buffer;
63
+ }
64
+ export type PrepareResult = {
65
+ ready: true;
66
+ landing: PreparedLanding;
67
+ } | {
68
+ ready: false;
69
+ conflicts: string[];
70
+ detail: string;
71
+ };
72
+ /**
73
+ * Merges `tree` (a change collected against `base`) with the working folder as it stands, which is
74
+ * "ours", so edits the user made since the snapshot are merged with the change rather than
75
+ * overwritten. Nothing in the working folder is written: the result is the patch `applyLanding`
76
+ * would apply and the paths it touches, so a caller can decide whether those paths may be written
77
+ * before any of them is.
78
+ */
79
+ export declare function prepareLanding(workspace: string, base: string, tree: string, signal: AbortSignal): Promise<PrepareResult>;
80
+ /**
81
+ * Writes a prepared landing to the working folder as uncommitted edits. Only the paths in
82
+ * `landing.files` are written or removed: the patch is fixed, and `git apply` refuses it as a whole
83
+ * when the folder no longer matches what it was made against.
84
+ *
85
+ * Landing is all or nothing. `git apply` checks a patch before it writes, but the writing itself is
86
+ * not atomic: a file another program holds open, a full disk or a cancelled run stops it with some
87
+ * files rewritten and others already removed. So the files the patch touches are copied aside
88
+ * first, and any failure of the apply puts them back, removes what the patch added, and reports the
89
+ * landing as not done, with `stale` set when the folder changed after the landing was prepared (a
90
+ * new preparation may then work). If the folder cannot be put back, a `LandingRestoreError` names
91
+ * the snapshot commit holding the folder as it was. The hooks exist for tests: `applied` runs after
92
+ * an apply that worked, and a throw from it is handled as the apply failing once its writes were
93
+ * made; `applyFailed` runs between a failed apply and the restore.
94
+ */
95
+ export declare function applyLanding(landing: PreparedLanding, signal: AbortSignal, hooks?: {
96
+ applied?: () => Promise<void>;
97
+ applyFailed?: () => Promise<void>;
98
+ }): Promise<LandResult>;
99
+ /**
100
+ * Lands `tree` (a change collected against `base`) on the working folder as uncommitted edits:
101
+ * `prepareLanding`, then `applyLanding`. On a conflict nothing is written. A caller that must
102
+ * authorize the paths a landing writes uses the two steps itself.
103
+ */
104
+ export declare function landChange(workspace: string, base: string, tree: string, signal: AbortSignal, hooks?: {
105
+ applied?: () => Promise<void>;
106
+ applyFailed?: () => Promise<void>;
107
+ }): Promise<LandResult>;
108
+ /** Removes a worktree made by `addChangeWorktree` and its temporary directory. Best effort; never throws. */
109
+ export declare function removeChangeWorktree(workspace: string, worktree: string): Promise<void>;
@@ -0,0 +1,431 @@
1
+ // Git operations behind Orchestrator delegation: snapshot the working folder, give a writing
2
+ // subagent a worktree that starts from that snapshot, collect what it changed, and land the
3
+ // change back as uncommitted edits with a three-way merge.
4
+ //
5
+ // Every operation here works on private objects. The user's index, refs, stash and branches are
6
+ // never read for state or written: snapshots use a temporary index file and dangling commits, and
7
+ // landing writes nothing but working-tree files, and puts every one of them back if it fails partway.
8
+ import { execFile } from 'node:child_process';
9
+ import { promisify } from 'node:util';
10
+ import { chmod, copyFile, lstat, mkdir, mkdtemp, readFile, readdir, readlink, realpath, rm, rmdir, symlink, writeFile } from 'node:fs/promises';
11
+ import { tmpdir } from 'node:os';
12
+ import { basename, dirname, join } from 'node:path';
13
+ const exec = promisify(execFile);
14
+ /** Characters of a change's diff that are inlined into the spawn observation. */
15
+ export const DELEGATION_DIFF_LIMIT = 20_000;
16
+ const WORKTREE_PREFIX = 'andorra-subagent-';
17
+ const GIT_TIMEOUT_MS = 15_000;
18
+ // Snapshotting and diffing a whole working folder is bounded by its size, not by a single status.
19
+ const BULK_TIMEOUT_MS = 120_000;
20
+ const DIFF_MAX_BUFFER = 256 * 1024 * 1024;
21
+ // `git add -A` over a whole folder can print a warning per file (line-ending conversion notices).
22
+ const ADD_MAX_BUFFER = 64 * 1024 * 1024;
23
+ // A process a subagent started may still be letting go of a file when its worktree is removed.
24
+ const REMOVE_RETRIES = { maxRetries: 5, retryDelay: 100 };
25
+ // The hooks and fsmonitor settings are the same hardening the existing worktree path applies: a
26
+ // repository must not get to run its own programs because a subagent was spawned. safecrlf is off
27
+ // because a snapshot takes the files as they are: with `core.safecrlf=true` Git refuses to add a
28
+ // file whose line endings its own conversion would change, and the snapshot would fail.
29
+ const HARDENED = ['-c', 'core.hooksPath=', '-c', 'core.fsmonitor=false', '-c', 'core.safecrlf=false'];
30
+ // Patches are made with the diff-tree plumbing, not porcelain `git diff`: porcelain honours the
31
+ // user's diff.noprefix, diff.external, colour and textconv settings, any of which turns a clean
32
+ // merge into a patch `git apply` rejects or rewrites. Plumbing ignores them by default; the
33
+ // switches make that explicit.
34
+ const PATCH = ['diff-tree', '-r', '--no-color', '--no-ext-diff', '--no-textconv'];
35
+ // Snapshot commits are private, so they carry a fixed identity rather than requiring the user to
36
+ // have configured one.
37
+ const SNAPSHOT_IDENTITY = {
38
+ GIT_AUTHOR_NAME: 'Andorra', GIT_AUTHOR_EMAIL: 'andorra@localhost',
39
+ GIT_COMMITTER_NAME: 'Andorra', GIT_COMMITTER_EMAIL: 'andorra@localhost',
40
+ };
41
+ async function git(cwd, args, options = {}) {
42
+ const { stdout } = await exec('git', [...HARDENED, ...args], {
43
+ cwd, signal: options.signal, windowsHide: true, timeout: options.timeout ?? GIT_TIMEOUT_MS,
44
+ maxBuffer: options.maxBuffer ?? 1 << 20, env: options.env ? { ...process.env, ...options.env } : undefined,
45
+ });
46
+ return stdout;
47
+ }
48
+ /** Removes a temporary directory this module made. A failure here never replaces the error that led to it. */
49
+ async function removeQuietly(directory) {
50
+ try {
51
+ await rm(directory, { recursive: true, force: true, ...REMOVE_RETRIES });
52
+ }
53
+ catch { /* best effort */ }
54
+ }
55
+ /** Runs the callback with a temporary index file that is removed afterwards. */
56
+ async function withTemporaryIndex(callback) {
57
+ const directory = await mkdtemp(join(tmpdir(), 'andorra-index-'));
58
+ try {
59
+ return await callback({ GIT_INDEX_FILE: join(directory, 'index') });
60
+ }
61
+ finally {
62
+ await removeQuietly(directory);
63
+ }
64
+ }
65
+ // Andorra's own runtime files (job logs of AsyncProcess, QA run output) are written under
66
+ // `.andorra/runtime` of whichever folder a tool ran in, which for a writing subagent is inside its
67
+ // worktree. They are by-products of running, not work: left in, a job that printed one line would
68
+ // add its log to the change and land it in the user's folder. The same exclusion applies to every
69
+ // tree made here (the snapshot, the change, the folder at landing), so the path never differs
70
+ // between them. The glob form matches the folder at any depth, for a subfolder workspace.
71
+ const RUNTIME_FILES = ':(exclude,glob)**/.andorra/runtime/**';
72
+ /**
73
+ * Writes a tree of the folder's files as they stand: the tracked files of `start` updated from disk,
74
+ * plus untracked files that are not ignored, without Andorra's runtime files. The real index is not involved.
75
+ */
76
+ async function writeWorkingTree(root, start, signal) {
77
+ return withTemporaryIndex(async (env) => {
78
+ await git(root, ['read-tree', start], { signal, env });
79
+ await git(root, ['add', '-A', '--', '.', RUNTIME_FILES], { signal, env, timeout: BULK_TIMEOUT_MS, maxBuffer: ADD_MAX_BUFFER });
80
+ return (await git(root, ['write-tree'], { signal, env })).trim();
81
+ });
82
+ }
83
+ /** A dangling commit holding `tree`; it is never referenced by a ref. */
84
+ async function commitTree(root, tree, parent, message, signal) {
85
+ return (await git(root, ['commit-tree', tree, '-p', parent, '-m', message], { signal, env: SNAPSHOT_IDENTITY })).trim();
86
+ }
87
+ function isGitFailure(error, code) {
88
+ return error instanceof Error && error.code === code && typeof error.stdout === 'string';
89
+ }
90
+ /** The repository toplevel for a workspace, which may be a subfolder of the repository. */
91
+ export async function repositoryRoot(workspace, signal) {
92
+ let toplevel;
93
+ try {
94
+ toplevel = (await git(workspace, ['rev-parse', '--show-toplevel'], { signal })).trim();
95
+ }
96
+ catch (error) {
97
+ if (isGitFailure(error, 128))
98
+ throw new Error('Delegated writing needs the workspace to be a Git repository.');
99
+ throw error;
100
+ }
101
+ if (!toplevel)
102
+ throw new Error('Delegated writing needs the workspace to be a Git repository.');
103
+ return realpath(toplevel);
104
+ }
105
+ /** Checks the Git the delegation path depends on before any worktree is created. */
106
+ export async function assertDelegationGit(workspace, signal) {
107
+ const version = /git version (\d+)\.(\d+)/.exec(await git(workspace, ['--version'], { signal }));
108
+ const [major, minor] = version ? [Number(version[1]), Number(version[2])] : [0, 0];
109
+ // `merge-tree --write-tree --merge-base` is what lands a change; it arrived in 2.40.
110
+ if (major < 2 || (major === 2 && minor < 40))
111
+ throw new Error('Delegated writing needs Git 2.40 or newer.');
112
+ const root = await repositoryRoot(workspace, signal);
113
+ try {
114
+ await git(root, ['rev-parse', '--verify', '-q', 'HEAD^{commit}'], { signal });
115
+ }
116
+ catch (error) {
117
+ if (isGitFailure(error, 1))
118
+ throw new Error('Delegated writing needs a Git repository with at least one commit.');
119
+ throw error;
120
+ }
121
+ }
122
+ /**
123
+ * A commit whose tree is the working folder as it stands (tracked plus untracked non-ignored files)
124
+ * and whose parent is HEAD. It is the base a writing subagent starts from and is diffed against.
125
+ */
126
+ export async function snapshotWorkspace(workspace, signal) {
127
+ const root = await repositoryRoot(workspace, signal);
128
+ const tree = await writeWorkingTree(root, 'HEAD', signal);
129
+ return commitTree(root, tree, 'HEAD', 'Andorra delegation snapshot', signal);
130
+ }
131
+ /** A detached worktree at `commit` under a fresh temporary directory. */
132
+ export async function addChangeWorktree(workspace, commit, signal) {
133
+ const directory = await mkdtemp(join(tmpdir(), WORKTREE_PREFIX));
134
+ const worktree = join(directory, 'worktree');
135
+ try {
136
+ await git(workspace, ['worktree', 'add', '--detach', worktree, commit], { signal, timeout: BULK_TIMEOUT_MS });
137
+ }
138
+ catch (error) {
139
+ await removeQuietly(directory);
140
+ throw error;
141
+ }
142
+ return worktree;
143
+ }
144
+ /**
145
+ * The worktree's final files against the snapshot it started from. Commits the subagent made inside
146
+ * the worktree do not matter: the tree is taken from disk, the way the snapshot was.
147
+ */
148
+ export async function collectChange(worktree, base, signal) {
149
+ const tree = await writeWorkingTree(worktree, base, signal);
150
+ const range = [`${base}^{tree}`, tree];
151
+ const diff = await git(worktree, [...PATCH, '-p', '--binary', '-M', ...range], { signal, timeout: BULK_TIMEOUT_MS, maxBuffer: DIFF_MAX_BUFFER });
152
+ const status = await git(worktree, [...PATCH, '--name-status', '-M', '-z', ...range], { signal, timeout: BULK_TIMEOUT_MS, maxBuffer: DIFF_MAX_BUFFER });
153
+ const files = [];
154
+ const paths = [];
155
+ const fields = status.split('\0');
156
+ for (let index = 0; index + 1 < fields.length; index += 2) {
157
+ const kind = fields[index][0];
158
+ // A rename record carries the old path before the new one; the change is reported at its new path.
159
+ if (kind === 'R') {
160
+ files.push({ path: fields[index + 2], status: 'R' });
161
+ paths.push(fields[index + 1], fields[index + 2]);
162
+ index += 1;
163
+ continue;
164
+ }
165
+ files.push({ path: fields[index + 1], status: kind === 'A' || kind === 'D' ? kind : 'M' });
166
+ paths.push(fields[index + 1]);
167
+ }
168
+ return { tree, files, diff, paths };
169
+ }
170
+ /**
171
+ * Landing wrote part of a change and could not put the working folder back. The message names the
172
+ * snapshot commit that holds the folder as it was and the paths that were not restored.
173
+ */
174
+ export class LandingRestoreError extends Error {
175
+ snapshot;
176
+ paths;
177
+ constructor(message, snapshot, paths) {
178
+ super(message);
179
+ this.snapshot = snapshot;
180
+ this.paths = paths;
181
+ this.name = 'LandingRestoreError';
182
+ }
183
+ }
184
+ const missing = (error) => ['ENOENT', 'ENOTDIR'].includes(error.code ?? '');
185
+ const present = (target) => lstat(target).catch((error) => { if (missing(error))
186
+ return undefined; throw error; });
187
+ /** How many folders deep a repository path is; Git prints paths with forward slashes. */
188
+ const depth = (path) => path.split('/').length;
189
+ /**
190
+ * Copies the files a patch is about to touch into `directory`, byte for byte. The copies, not the
191
+ * snapshot's blobs, are what a failed landing restores: a blob went through Git's line-ending and
192
+ * filter conversion on the way in, so checking it out again is not guaranteed to give the same bytes.
193
+ * Also records the directories the patch would have to create, so a restore can remove them again.
194
+ */
195
+ async function saveTouched(root, paths, directory) {
196
+ const saved = [];
197
+ const created = new Set();
198
+ for (const [index, path] of paths.entries()) {
199
+ const target = join(root, path);
200
+ const info = await present(target);
201
+ if (!info) {
202
+ saved.push({ path, kind: 'absent' });
203
+ for (let parent = dirname(target); parent.length > root.length && !(await present(parent)); parent = dirname(parent))
204
+ created.add(parent);
205
+ }
206
+ else if (info.isSymbolicLink())
207
+ saved.push({ path, kind: 'link', target: await readlink(target) });
208
+ else if (info.isFile()) {
209
+ const copy = join(directory, String(index));
210
+ await copyFile(target, copy);
211
+ saved.push({ path, kind: 'file', copy, mode: info.mode & 0o777 });
212
+ // A directory where the patch puts a file: the files under it are saved under their own paths.
213
+ }
214
+ else
215
+ saved.push({ path, kind: info.isDirectory() ? 'directory' : 'other' });
216
+ }
217
+ // Deepest first, which is the order a restore removes them in.
218
+ return { saved, created: [...created].sort((left, right) => right.length - left.length) };
219
+ }
220
+ /**
221
+ * Removes a directory that holds nothing but empty directories. A file in it was not put there by
222
+ * the landing (what the landing added is removed before this runs), so it stops the removal.
223
+ */
224
+ async function removeEmptyTree(directory) {
225
+ for (const entry of await readdir(directory, { withFileTypes: true })) {
226
+ if (!entry.isDirectory())
227
+ throw new Error(`${join(directory, entry.name)} was not added by the landing, so the directory holding it is kept`);
228
+ await removeEmptyTree(join(directory, entry.name));
229
+ }
230
+ await rmdir(directory);
231
+ }
232
+ /** Takes away what stands at a path so that what was saved can go back there. */
233
+ const clear = (target, info) => info.isDirectory() ? removeEmptyTree(target) : rm(target, { force: true });
234
+ /**
235
+ * Puts every saved path back as it was. Returns the paths that could not be restored, with the reason.
236
+ *
237
+ * A patch can change what kind of thing a path is: a file becomes a directory with files under it,
238
+ * or a directory becomes a file. So the order matters. What the patch added goes first, deepest
239
+ * first, together with the directories it made; only then are saved files put back, shallowest
240
+ * first, each one replacing a directory that the patch left in its place.
241
+ */
242
+ async function restoreTouched(root, state) {
243
+ const failed = new Map();
244
+ const attempt = async (entry, action) => {
245
+ try {
246
+ await action(join(root, entry.path));
247
+ }
248
+ catch (error) {
249
+ if (!failed.has(entry.path))
250
+ failed.set(entry.path, error instanceof Error ? error.message : String(error));
251
+ }
252
+ };
253
+ const deepestFirst = [...state.saved].sort((left, right) => depth(right.path) - depth(left.path));
254
+ for (const entry of deepestFirst) {
255
+ // Nothing stood here: whatever is here now is the patch's.
256
+ if (entry.kind === 'absent')
257
+ await attempt(entry, async (target) => { const info = await present(target); if (info)
258
+ await clear(target, info); });
259
+ // A directory stood here: a file here now is the patch's, and the directory comes back below.
260
+ if (entry.kind === 'directory')
261
+ await attempt(entry, async (target) => { const info = await present(target); if (info && !info.isDirectory())
262
+ await rm(target, { force: true }); });
263
+ }
264
+ // Only a directory the patch made, and only once it is empty again.
265
+ for (const directory of state.created)
266
+ await rmdir(directory).catch(() => { });
267
+ for (const entry of deepestFirst.reverse()) {
268
+ if (entry.kind === 'directory')
269
+ await attempt(entry, async (target) => { await mkdir(target, { recursive: true }); });
270
+ if (entry.kind === 'link')
271
+ await attempt(entry, async (target) => {
272
+ const info = await present(target);
273
+ if (info?.isSymbolicLink() && await readlink(target) === entry.target)
274
+ return;
275
+ if (info)
276
+ await clear(target, info);
277
+ await mkdir(dirname(target), { recursive: true });
278
+ await symlink(entry.target, target);
279
+ });
280
+ if (entry.kind === 'file')
281
+ await attempt(entry, async (target) => {
282
+ const info = await present(target);
283
+ // A file the patch never reached is left alone: rewriting it could only fail for no gain.
284
+ if (info?.isFile() && (await readFile(target)).equals(await readFile(entry.copy))) {
285
+ if ((info.mode & 0o777) !== entry.mode)
286
+ await chmod(target, entry.mode);
287
+ return;
288
+ }
289
+ if (info)
290
+ await clear(target, info);
291
+ await mkdir(dirname(target), { recursive: true });
292
+ await copyFile(entry.copy, target);
293
+ await chmod(target, entry.mode);
294
+ });
295
+ }
296
+ return [...failed].map(([path, reason]) => ({ path, reason }));
297
+ }
298
+ /**
299
+ * Merges `tree` (a change collected against `base`) with the working folder as it stands, which is
300
+ * "ours", so edits the user made since the snapshot are merged with the change rather than
301
+ * overwritten. Nothing in the working folder is written: the result is the patch `applyLanding`
302
+ * would apply and the paths it touches, so a caller can decide whether those paths may be written
303
+ * before any of them is.
304
+ */
305
+ export async function prepareLanding(workspace, base, tree, signal) {
306
+ const root = await repositoryRoot(workspace, signal);
307
+ const ours = await snapshotWorkspace(root, signal);
308
+ // Git 2.40's merge-tree takes commits for the sides it merges (later versions accept trees), so
309
+ // the change is wrapped in a throwaway commit on its base.
310
+ const theirs = await commitTree(root, tree, base, 'Andorra delegated change', signal);
311
+ let merged;
312
+ try {
313
+ merged = (await git(root, ['merge-tree', '--write-tree', `--merge-base=${base}`, '--name-only', ours, theirs], { signal, timeout: BULK_TIMEOUT_MS, maxBuffer: DIFF_MAX_BUFFER })).trim();
314
+ }
315
+ catch (error) {
316
+ // Exit 1 is a conflict, with the merged tree, the conflicted paths and a blank line before the messages.
317
+ if (!isGitFailure(error, 1))
318
+ throw error;
319
+ const [, ...rest] = error.stdout.split('\n');
320
+ const conflicts = [];
321
+ for (const line of rest) {
322
+ if (line === '')
323
+ break;
324
+ conflicts.push(line);
325
+ }
326
+ return { ready: false, conflicts, detail: error.stdout.trim() };
327
+ }
328
+ const patch = await exec('git', [...HARDENED, ...PATCH, '-p', '--binary', ours, merged], { cwd: root, signal, windowsHide: true, timeout: BULK_TIMEOUT_MS, maxBuffer: DIFF_MAX_BUFFER, encoding: 'buffer' });
329
+ // Without rename detection a moved file is listed at both of its paths: one is removed, one written.
330
+ const files = (await git(root, [...PATCH, '--name-only', '-z', '--no-renames', ours, merged], { signal, timeout: BULK_TIMEOUT_MS, maxBuffer: DIFF_MAX_BUFFER })).split('\0').filter(Boolean);
331
+ return { ready: true, landing: { root, ours, files, patch: patch.stdout } };
332
+ }
333
+ /** Whether the working folder no longer holds the files the snapshot commit `ours` recorded. */
334
+ async function folderMoved(root, ours, signal) {
335
+ try {
336
+ return await writeWorkingTree(root, 'HEAD', signal) !== (await git(root, ['rev-parse', `${ours}^{tree}`], { signal })).trim();
337
+ }
338
+ catch {
339
+ return false;
340
+ }
341
+ }
342
+ /**
343
+ * Writes a prepared landing to the working folder as uncommitted edits. Only the paths in
344
+ * `landing.files` are written or removed: the patch is fixed, and `git apply` refuses it as a whole
345
+ * when the folder no longer matches what it was made against.
346
+ *
347
+ * Landing is all or nothing. `git apply` checks a patch before it writes, but the writing itself is
348
+ * not atomic: a file another program holds open, a full disk or a cancelled run stops it with some
349
+ * files rewritten and others already removed. So the files the patch touches are copied aside
350
+ * first, and any failure of the apply puts them back, removes what the patch added, and reports the
351
+ * landing as not done, with `stale` set when the folder changed after the landing was prepared (a
352
+ * new preparation may then work). If the folder cannot be put back, a `LandingRestoreError` names
353
+ * the snapshot commit holding the folder as it was. The hooks exist for tests: `applied` runs after
354
+ * an apply that worked, and a throw from it is handled as the apply failing once its writes were
355
+ * made; `applyFailed` runs between a failed apply and the restore.
356
+ */
357
+ export async function applyLanding(landing, signal, hooks = {}) {
358
+ const { root, ours, files, patch } = landing;
359
+ if (patch.length === 0)
360
+ return { landed: true, files };
361
+ // The patch goes through a file rather than stdin so Git sees the exact bytes; `git apply` without
362
+ // `--index` touches only the working tree, which is the snapshot's "ours" and so passes the check
363
+ // `git apply` makes before it writes. `--whitespace=nowarn` overrides an apply.whitespace setting
364
+ // that would strip or reject what the merge produced.
365
+ const directory = await mkdtemp(join(tmpdir(), 'andorra-land-'));
366
+ try {
367
+ const file = join(directory, 'change.patch');
368
+ await writeFile(file, patch);
369
+ // Nothing is written to the folder yet, so failing to copy the files aside just fails the landing.
370
+ const state = await saveTouched(root, files, directory);
371
+ signal.throwIfAborted();
372
+ try {
373
+ await git(root, ['apply', '--whitespace=nowarn', file], { signal, timeout: BULK_TIMEOUT_MS });
374
+ await hooks.applied?.();
375
+ }
376
+ catch (error) {
377
+ const stderr = error.stderr;
378
+ const detail = (typeof stderr === 'string' && stderr.trim()) || (error instanceof Error ? error.message : String(error));
379
+ try {
380
+ await hooks.applyFailed?.();
381
+ }
382
+ catch { /* a test hook must not hide the failure */ }
383
+ const failed = await restoreTouched(root, state);
384
+ if (failed.length) {
385
+ throw new LandingRestoreError(`Landing failed partway and the working folder could not be put back. The folder as it was before the landing is in Git commit ${ours}; recover a file with: git show ${ours}:<path>. Not restored: ${failed.map(entry => `${entry.path} (${entry.reason})`).join('; ')}. The landing failed with: ${detail}`, ours, failed.map(entry => entry.path));
386
+ }
387
+ // The folder is as it was. A cancelled run still ends as a cancellation, not as a conflict.
388
+ if (signal.aborted)
389
+ throw error;
390
+ return { landed: false, conflicts: [], detail, ...(await folderMoved(root, ours, signal) ? { stale: true } : {}) };
391
+ }
392
+ }
393
+ finally {
394
+ await removeQuietly(directory);
395
+ }
396
+ return { landed: true, files };
397
+ }
398
+ /**
399
+ * Lands `tree` (a change collected against `base`) on the working folder as uncommitted edits:
400
+ * `prepareLanding`, then `applyLanding`. On a conflict nothing is written. A caller that must
401
+ * authorize the paths a landing writes uses the two steps itself.
402
+ */
403
+ export async function landChange(workspace, base, tree, signal, hooks = {}) {
404
+ const prepared = await prepareLanding(workspace, base, tree, signal);
405
+ if (!prepared.ready)
406
+ return { landed: false, conflicts: prepared.conflicts, detail: prepared.detail };
407
+ return applyLanding(prepared.landing, signal, hooks);
408
+ }
409
+ /** Removes a worktree made by `addChangeWorktree` and its temporary directory. Best effort; never throws. */
410
+ export async function removeChangeWorktree(workspace, worktree) {
411
+ let removed = true;
412
+ try {
413
+ await git(workspace, ['worktree', 'remove', '--force', worktree], { timeout: BULK_TIMEOUT_MS });
414
+ }
415
+ catch {
416
+ removed = false;
417
+ }
418
+ // Only a directory this module created is deleted wholesale; anything else loses just the worktree.
419
+ const parent = dirname(worktree);
420
+ try {
421
+ await rm(basename(parent).startsWith(WORKTREE_PREFIX) ? parent : worktree, { recursive: true, force: true, ...REMOVE_RETRIES });
422
+ }
423
+ catch { /* best effort */ }
424
+ // Git forgets the worktree itself when the removal works; only a failed one leaves a record to prune.
425
+ if (!removed) {
426
+ try {
427
+ await git(workspace, ['worktree', 'prune']);
428
+ }
429
+ catch { /* best effort */ }
430
+ }
431
+ }
@@ -5,6 +5,7 @@ export declare function createGraphSessionCheck(subject: string | undefined, sta
5
5
  export declare function requireGraphProviders(directory?: string): Promise<Config>;
6
6
  export declare function startGraphServer(directory?: string, checkMembership?: () => Promise<unknown>, options?: {
7
7
  membership?: () => Promise<Membership>;
8
+ sync?: GraphSync;
8
9
  }): Promise<{
9
10
  url: string;
10
11
  origin: string;
@@ -55,11 +55,14 @@ export async function requireGraphProviders(directory = configDirectory()) {
55
55
  if (!value || typeof value !== 'object' || !Array.isArray(value.providers) || !value.providers.length)
56
56
  throw new Error(setupMessage);
57
57
  try {
58
- return validateConfig(value);
58
+ validateConfig({ ...value, providerKeys: undefined, providerKeysPendingDeletion: undefined });
59
59
  }
60
60
  catch {
61
61
  throw new Error('Invalid provider configuration. Run `andorra` and open `/providers` to repair it.');
62
62
  }
63
+ // Loaded through the configuration reader so saved API keys come back from the OS credential store;
64
+ // a store that cannot be read says so rather than passing for an invalid file.
65
+ return await loadConfig(directory);
63
66
  }
64
67
  /** Graph editing may be provider-free, but invalid config keeps actionable repair guidance. */
65
68
  async function editorConfig(directory) {
@@ -76,7 +79,8 @@ export async function startGraphServer(directory = configDirectory(), checkMembe
76
79
  // A caller supplying its own authorization check has no production account binding.
77
80
  const account = checkMembership === readGraphMembership ? await getAuthStatus() : { signedIn: false, subject: undefined };
78
81
  const graphDirectory = account.subject ? await graphStorageDirectory(directory, account.subject, true) : directory;
79
- const sync = account.subject ? new GraphSync(graphDirectory, account.subject) : undefined;
82
+ // A caller may bring its own store of drafts: a test has no signed-in account to bind one to.
83
+ const sync = options.sync ?? (account.subject ? new GraphSync(graphDirectory, account.subject) : undefined);
80
84
  await sync?.start();
81
85
  const checkSession = checkMembership === readGraphMembership ? createGraphSessionCheck(account.subject) : checkMembership;
82
86
  // Whether this account is held to the free allowance. A membership answer that could not be read
@@ -106,6 +110,7 @@ export async function startGraphServer(directory = configDirectory(), checkMembe
106
110
  '/studio.css': ['studio.css', 'text/css; charset=utf-8'],
107
111
  '/embed.js': ['embed.js', 'text/javascript; charset=utf-8'],
108
112
  '/sidebar.js': ['sidebar.js', 'text/javascript; charset=utf-8'],
113
+ '/drafts.js': ['drafts.js', 'text/javascript; charset=utf-8'],
109
114
  '/edge-router.js': ['edge-router.js', 'text/javascript; charset=utf-8'],
110
115
  '/icons.js': ['icons.js', 'text/javascript; charset=utf-8'],
111
116
  '/controls.js': ['controls.js', 'text/javascript; charset=utf-8'],
@@ -397,7 +402,7 @@ export async function startGraphServer(directory = configDirectory(), checkMembe
397
402
  reply(res, 200, { deleted: id });
398
403
  return;
399
404
  }
400
- if (req.method === 'POST' && ['/api/graphs', '/api/drafts', '/api/validate', '/api/definitions', '/api/definitions/import', '/api/preview'].includes(path)) {
405
+ if (req.method === 'POST' && ['/api/graphs', '/api/drafts', '/api/drafts/clear', '/api/validate', '/api/definitions', '/api/definitions/import', '/api/preview'].includes(path)) {
401
406
  if (!req.headers['content-type']?.startsWith('application/json')) {
402
407
  reply(res, 415, { error: 'Expected application/json' });
403
408
  return;
@@ -419,6 +424,13 @@ export async function startGraphServer(directory = configDirectory(), checkMembe
419
424
  reply(res, 400, { error: 'metadata.deletedAt is reserved for deleting a graph through the graph MCP server.' });
420
425
  return;
421
426
  }
427
+ if (path === '/api/drafts/clear') {
428
+ if (!sync)
429
+ throw new Error('Sign in to persist drafts');
430
+ await sync.clearDrafts(value?.graphIds);
431
+ reply(res, 200, await sync.drafts());
432
+ return;
433
+ }
422
434
  if (path === '/api/drafts') {
423
435
  if (!sync)
424
436
  throw new Error('Sign in to persist drafts');
@@ -38,6 +38,21 @@ export declare class GraphSync {
38
38
  revision: number;
39
39
  updatedAt: number;
40
40
  }[]>;
41
+ /**
42
+ * Draft snapshots are immutable, and every sweep restores the ones the account holds, so a draft
43
+ * the user cleared cannot be unlinked: it would come back. Each cleared graph instead has its own
44
+ * marker file under `graph-drafts-cleared/`, naming the instant up to which its drafts are
45
+ * cleared and any snapshot dated after that instant (saved under a clock that ran ahead) that
46
+ * was cleared with them. The listing leaves those out; a later autosave is a new snapshot, newer
47
+ * than the mark, and is listed again. A cleared snapshot stays on disk and still opens by hash.
48
+ *
49
+ * One file per graph, replaced whole, so two editors sharing this folder cannot drop each
50
+ * other's clears: clears of different graphs touch different files, and two clears of the same
51
+ * graph each record every draft that graph had.
52
+ */
53
+ private readClearedDrafts;
54
+ /** Clear every draft the named graphs have right now, whatever clock dated them. */
55
+ clearDrafts(graphIds: string[]): Promise<void>;
41
56
  draft(hash: string): Promise<Graph>;
42
57
  /**
43
58
  * The tombstones and their lineage floors are one durable record. Keeping them in one atomic