@andorra-labs/code 0.1.5 → 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 (224) hide show
  1. package/dist/src/account-presentation.js +3 -3
  2. package/dist/src/agent-execution.d.ts +2 -0
  3. package/dist/src/agent-execution.js +526 -41
  4. package/dist/src/agent-mcp-catalog.d.ts +21 -0
  5. package/dist/src/agent-mcp-catalog.js +40 -0
  6. package/dist/src/agent-mcp.d.ts +36 -3
  7. package/dist/src/agent-mcp.js +114 -45
  8. package/dist/src/app-server/protocol.d.ts +57 -5
  9. package/dist/src/app-server/protocol.js +18 -1
  10. package/dist/src/app-server/workspace.d.ts +9 -1
  11. package/dist/src/app-server/workspace.js +50 -3
  12. package/dist/src/app-server.d.ts +115 -41
  13. package/dist/src/app-server.js +1316 -221
  14. package/dist/src/auth/AuthManager.d.ts +33 -1
  15. package/dist/src/auth/AuthManager.js +138 -10
  16. package/dist/src/auth/callback-page.d.ts +4 -0
  17. package/dist/src/auth/callback-page.js +70 -0
  18. package/dist/src/auth/callback.d.ts +39 -0
  19. package/dist/src/auth/callback.js +146 -22
  20. package/dist/src/auth/index.d.ts +10 -6
  21. package/dist/src/auth/index.js +2 -2
  22. package/dist/src/auth/store.d.ts +142 -3
  23. package/dist/src/auth/store.js +334 -13
  24. package/dist/src/auth/types.d.ts +17 -1
  25. package/dist/src/auth-commands.d.ts +11 -2
  26. package/dist/src/auth-commands.js +14 -7
  27. package/dist/src/automation-runner.d.ts +9 -0
  28. package/dist/src/automation-runner.js +22 -1
  29. package/dist/src/automation-tool.js +18 -3
  30. package/dist/src/automations.d.ts +5 -0
  31. package/dist/src/automations.js +11 -1
  32. package/dist/src/browser-captcha-tool.d.ts +54 -0
  33. package/dist/src/browser-captcha-tool.js +374 -0
  34. package/dist/src/browser-panel-tool.d.ts +7 -0
  35. package/dist/src/browser-panel-tool.js +74 -3
  36. package/dist/src/browser-runner.js +19 -4
  37. package/dist/src/browser-server.js +21 -1
  38. package/dist/src/browser-session.d.ts +16 -0
  39. package/dist/src/browser-session.js +35 -0
  40. package/dist/src/browser-ui/app.js +193 -3
  41. package/dist/src/browser-ui/style.css +15 -1
  42. package/dist/src/browser-view.d.ts +72 -4
  43. package/dist/src/browser-view.js +229 -17
  44. package/dist/src/capabilities.d.ts +9 -3
  45. package/dist/src/capabilities.js +20 -5
  46. package/dist/src/capsolver.d.ts +60 -0
  47. package/dist/src/capsolver.js +101 -0
  48. package/dist/src/claude-provider.d.ts +6 -0
  49. package/dist/src/claude-provider.js +34 -3
  50. package/dist/src/cli-executable.d.ts +33 -0
  51. package/dist/src/cli-executable.js +64 -0
  52. package/dist/src/cli-process.d.ts +47 -0
  53. package/dist/src/cli-process.js +113 -0
  54. package/dist/src/cli-sign-in.d.ts +68 -0
  55. package/dist/src/cli-sign-in.js +224 -0
  56. package/dist/src/cli.js +84 -26
  57. package/dist/src/code-intelligence/CodeIntelligenceManager.d.ts +1 -1
  58. package/dist/src/code-intelligence/CodeIntelligenceManager.js +5 -5
  59. package/dist/src/codex-provider.js +12 -0
  60. package/dist/src/coding-tools.d.ts +5 -0
  61. package/dist/src/coding-tools.js +98 -53
  62. package/dist/src/command-output-tap.d.ts +16 -0
  63. package/dist/src/command-output-tap.js +45 -0
  64. package/dist/src/command-screens.js +3 -3
  65. package/dist/src/commands.d.ts +15 -2
  66. package/dist/src/commands.js +14 -13
  67. package/dist/src/completion.d.ts +23 -5
  68. package/dist/src/completion.js +380 -17
  69. package/dist/src/config.d.ts +61 -0
  70. package/dist/src/config.js +276 -12
  71. package/dist/src/context-budget.d.ts +7 -0
  72. package/dist/src/context-budget.js +18 -1
  73. package/dist/src/deadline.js +6 -0
  74. package/dist/src/decision/FactContinuations.d.ts +41 -6
  75. package/dist/src/decision/FactContinuations.js +211 -64
  76. package/dist/src/decision/PreparedSteps.js +3 -1
  77. package/dist/src/decision/checks.d.ts +25 -0
  78. package/dist/src/decision/checks.js +77 -6
  79. package/dist/src/delegation-changes.d.ts +109 -0
  80. package/dist/src/delegation-changes.js +431 -0
  81. package/dist/src/extensions.d.ts +1 -0
  82. package/dist/src/extensions.js +16 -3
  83. package/dist/src/graph-provider-portability.js +2 -2
  84. package/dist/src/graph-quota.d.ts +1 -1
  85. package/dist/src/graph-quota.js +1 -1
  86. package/dist/src/graph-runner.js +35 -21
  87. package/dist/src/graph-selection.d.ts +6 -0
  88. package/dist/src/graph-selection.js +10 -0
  89. package/dist/src/graph-server.d.ts +8 -0
  90. package/dist/src/graph-server.js +76 -6
  91. package/dist/src/graph-sync.d.ts +65 -0
  92. package/dist/src/graph-sync.js +433 -13
  93. package/dist/src/graph-tool.d.ts +52 -0
  94. package/dist/src/graph-tool.js +136 -0
  95. package/dist/src/graph-ui/app.js +272 -50
  96. package/dist/src/graph-ui/controls.js +6 -0
  97. package/dist/src/graph-ui/drafts.js +39 -0
  98. package/dist/src/graph-ui/embed.js +1 -1
  99. package/dist/src/graph-ui/icons.js +1 -0
  100. package/dist/src/graph-ui/index.html +2 -2
  101. package/dist/src/graph-ui/skill-picker.js +242 -0
  102. package/dist/src/graph-ui/studio.css +7 -5
  103. package/dist/src/graph-ui/style.css +65 -12
  104. package/dist/src/graphs.d.ts +60 -5
  105. package/dist/src/graphs.js +191 -37
  106. package/dist/src/grok-provider.d.ts +50 -0
  107. package/dist/src/grok-provider.js +186 -0
  108. package/dist/src/handoffs.d.ts +13 -0
  109. package/dist/src/handoffs.js +31 -1
  110. package/dist/src/hardened-runtime.d.ts +4 -4
  111. package/dist/src/hardened-runtime.js +109 -9
  112. package/dist/src/managed-sign-in.d.ts +38 -0
  113. package/dist/src/managed-sign-in.js +169 -0
  114. package/dist/src/markdown.d.ts +5 -0
  115. package/dist/src/markdown.js +5 -2
  116. package/dist/src/mcp.js +11 -0
  117. package/dist/src/membership.d.ts +8 -1
  118. package/dist/src/membership.js +15 -5
  119. package/dist/src/model-metadata.js +14 -2
  120. package/dist/src/model-override.d.ts +10 -0
  121. package/dist/src/model-override.js +20 -0
  122. package/dist/src/opencode-cli-provider.d.ts +122 -0
  123. package/dist/src/opencode-cli-provider.js +415 -0
  124. package/dist/src/opencode-provider.js +23 -8
  125. package/dist/src/palette.d.ts +2 -0
  126. package/dist/src/palette.js +2 -0
  127. package/dist/src/permissions.d.ts +19 -1
  128. package/dist/src/permissions.js +30 -1
  129. package/dist/src/powershell-pool.d.ts +11 -2
  130. package/dist/src/powershell-pool.js +34 -5
  131. package/dist/src/provider-connection.js +36 -0
  132. package/dist/src/provider-engine.d.ts +2 -1
  133. package/dist/src/provider-engine.js +64 -13
  134. package/dist/src/provider-import.js +6 -1
  135. package/dist/src/provider-keys.d.ts +48 -0
  136. package/dist/src/provider-keys.js +121 -0
  137. package/dist/src/provider-settings.js +22 -3
  138. package/dist/src/providers.d.ts +12 -1
  139. package/dist/src/providers.js +27 -8
  140. package/dist/src/pull-requests.d.ts +123 -20
  141. package/dist/src/pull-requests.js +334 -84
  142. package/dist/src/qa/qa-authorize.js +9 -1
  143. package/dist/src/qa/runtime/ProcessManager.d.ts +6 -0
  144. package/dist/src/qa/runtime/ProcessManager.js +16 -0
  145. package/dist/src/react-runtime.js +106 -7
  146. package/dist/src/read-image.d.ts +30 -0
  147. package/dist/src/read-image.js +97 -0
  148. package/dist/src/remote/engine-pool.js +1 -1
  149. package/dist/src/run-progress.js +6 -1
  150. package/dist/src/run-records.d.ts +133 -27
  151. package/dist/src/run-records.js +320 -40
  152. package/dist/src/runtime.d.ts +38 -1
  153. package/dist/src/runtime.js +27 -4
  154. package/dist/src/save-lock.d.ts +11 -0
  155. package/dist/src/save-lock.js +29 -2
  156. package/dist/src/secret-redaction.d.ts +13 -0
  157. package/dist/src/secret-redaction.js +71 -0
  158. package/dist/src/session-summary.d.ts +10 -4
  159. package/dist/src/session-summary.js +14 -7
  160. package/dist/src/sessions.js +8 -2
  161. package/dist/src/shell.js +4 -1
  162. package/dist/src/side-panel.d.ts +1 -1
  163. package/dist/src/side-panel.js +1 -1
  164. package/dist/src/skill-commands.d.ts +2 -0
  165. package/dist/src/skill-commands.js +2 -0
  166. package/dist/src/skills/bundled/create-agent/SKILL.md +81 -0
  167. package/dist/src/skills/bundled/create-skill/SKILL.md +81 -0
  168. package/dist/src/skills/bundled/doctor/SKILL.md +43 -0
  169. package/dist/src/skills/bundled/graph-manager/SKILL.md +100 -0
  170. package/dist/src/skills/bundled/graph-manager/errors.md +38 -0
  171. package/dist/src/skills/bundled/graph-manager/patterns.md +78 -0
  172. package/dist/src/skills/bundled/manage-mcp/SKILL.md +75 -0
  173. package/dist/src/skills/bundled/manage-mcp/probe.md +165 -0
  174. package/dist/src/skills/bundled/manage-skills/SKILL.md +67 -0
  175. package/dist/src/skills/bundled/provenance.json +50 -0
  176. package/dist/src/skills/bundled/write-instructions/SKILL.md +42 -0
  177. package/dist/src/skills/invocable-skills.d.ts +41 -0
  178. package/dist/src/skills/invocable-skills.js +49 -0
  179. package/dist/src/skills/prompt-skills.d.ts +1 -0
  180. package/dist/src/skills/prompt-skills.js +33 -0
  181. package/dist/src/skills/runtime-skills.d.ts +4 -0
  182. package/dist/src/skills/runtime-skills.js +21 -0
  183. package/dist/src/structured-step.d.ts +55 -0
  184. package/dist/src/structured-step.js +85 -0
  185. package/dist/src/subagent-run.d.ts +1 -1
  186. package/dist/src/subagent-run.js +29 -33
  187. package/dist/src/telemetry/schema.d.ts +2 -2
  188. package/dist/src/telemetry/schema.js +3 -2
  189. package/dist/src/terminal-ui.d.ts +38 -0
  190. package/dist/src/terminal-ui.js +126 -28
  191. package/dist/src/timers.d.ts +21 -2
  192. package/dist/src/timers.js +12 -4
  193. package/dist/src/tool-dependencies.js +4 -0
  194. package/dist/src/tool-names.d.ts +18 -0
  195. package/dist/src/tool-names.js +26 -0
  196. package/dist/src/tools.d.ts +9 -0
  197. package/dist/src/tools.js +159 -20
  198. package/dist/src/trajectory.js +32 -12
  199. package/dist/src/transcript.js +5 -0
  200. package/dist/src/types.d.ts +36 -0
  201. package/dist/src/web-search.d.ts +59 -0
  202. package/dist/src/web-search.js +216 -0
  203. package/docs/agents/README.md +2 -2
  204. package/docs/agents/mcp-server.md +28 -3
  205. package/docs/agents/subagent-mode.md +7 -4
  206. package/docs/concepts/README.md +1 -1
  207. package/docs/concepts/security.md +4 -2
  208. package/docs/getting-started/accounts.md +15 -4
  209. package/docs/getting-started/configure-providers.md +30 -3
  210. package/docs/guides/README.md +1 -0
  211. package/docs/guides/browser.md +12 -0
  212. package/docs/guides/desktop-app.md +11 -4
  213. package/docs/guides/graph-builder.md +9 -1
  214. package/docs/guides/web-search.md +47 -0
  215. package/docs/reference/cli.md +4 -3
  216. package/docs/reference/config.md +4 -4
  217. package/docs/reference/slash-commands.md +2 -1
  218. package/docs/superpowers/plans/2026-11-06-graph-soft-delete.md +125 -0
  219. package/docs/superpowers/plans/2026-11-09-orchestrator-delegation.md +295 -0
  220. package/docs/superpowers/specs/2026-11-01-pr-section-design.md +7 -0
  221. package/docs/superpowers/specs/2026-11-06-bundled-skills-design.md +206 -0
  222. package/docs/superpowers/specs/2026-11-09-orchestrator-delegation-design.md +291 -0
  223. package/package.json +1 -1
  224. package/tests/permissions-test-plan.md +2 -1
@@ -1,11 +1,14 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, readdir, readFile, rename, writeFile, link, unlink } from 'node:fs/promises';
3
+ import { setTimeout as delay } from 'node:timers/promises';
3
4
  import { join, relative } from 'node:path';
4
5
  import { AUTH_REFRESH_BUDGET_MS, getAccessToken, getAuthConfiguration, getAuthStatus } from './auth/index.js';
5
6
  import { decodeJwt } from 'jose';
6
7
  import { GraphConflictError, restoreGraphRevision, validateGraph } from './graphs.js';
8
+ import { acquireSaveLock, removeLockedFolder, SaveLockBusyError } from './save-lock.js';
7
9
  import { readGraphQuota } from './graph-quota.js';
8
10
  const MAX_BYTES = 600 * 1024;
11
+ const DELETION_MARKER = '.graph-deletion-pending.json';
9
12
  const digest = (raw) => createHash('sha256').update(raw).digest('hex');
10
13
  const safeId = (id) => typeof id === 'string' && /^[\w-]{1,128}$/.test(id);
11
14
  const safeHash = (hash) => typeof hash === 'string' && /^[a-f0-9]{64}$/.test(hash);
@@ -148,9 +151,22 @@ export class GraphSync {
148
151
  const original = envelope('draft', content);
149
152
  if (this.lastDraft.get(content.id) === digest(original))
150
153
  return;
154
+ // A deleted graph's drafts die with it: a write that races the deletion's cleanup must not
155
+ // recreate one, or the tombstone's promise that no trace of the graph survives is broken
156
+ // while the machine is offline and no pruning pass removes it.
157
+ if ((await this.readDeletedGraphs()).has(content.id))
158
+ return;
151
159
  const raw = envelope('draft', { ...content, metadata: { ...content.metadata, updatedAt: new Date().toISOString() } });
160
+ const path = join(this.directory, 'graph-drafts', `${digest(raw)}.json`);
152
161
  await mkdir(join(this.directory, 'graph-drafts'), { recursive: true });
153
- await atomic(join(this.directory, 'graph-drafts', `${digest(raw)}.json`), raw);
162
+ await atomic(path, raw);
163
+ // The tombstone can land while this write is in flight: forgetGraph prunes drafts only
164
+ // after its own cleanup, so a write that read the tombstone before the deletion must not
165
+ // outlive it either. The file is dropped when the graph is tombstoned by the time it landed.
166
+ if ((await this.readDeletedGraphs()).has(content.id)) {
167
+ await unlink(path).catch(() => { });
168
+ return;
169
+ }
154
170
  this.lastDraft.set(content.id, digest(original));
155
171
  this.generation++;
156
172
  this.status = { state: 'pending', detail: 'Draft saved locally; cloud sync pending' };
@@ -158,6 +174,7 @@ export class GraphSync {
158
174
  }
159
175
  async drafts() {
160
176
  const result = [];
177
+ const cleared = await this.readClearedDrafts();
161
178
  for (const entry of await entries(join(this.directory, 'graph-drafts'))) {
162
179
  if (!entry.isFile() || !/^[a-f0-9]{64}\.json$/.test(entry.name))
163
180
  continue;
@@ -165,7 +182,11 @@ export class GraphSync {
165
182
  const hash = entry.name.slice(0, -5);
166
183
  const value = parseSnapshot(await readFile(join(this.directory, 'graph-drafts', entry.name), 'utf8'), hash);
167
184
  const timestamp = value.content.metadata?.updatedAt;
168
- result.push({ snapshot: hash, name: typeof value.content.name === 'string' ? value.content.name : value.graphId, graphId: value.graphId, revision: value.revision, updatedAt: typeof timestamp === 'string' ? Date.parse(timestamp) || 0 : 0 });
185
+ const updatedAt = typeof timestamp === 'string' ? Date.parse(timestamp) || 0 : 0;
186
+ const mark = cleared.get(value.graphId);
187
+ if (mark && (updatedAt <= mark.at || mark.snapshots.has(hash)))
188
+ continue;
189
+ result.push({ snapshot: hash, name: typeof value.content.name === 'string' ? value.content.name : value.graphId, graphId: value.graphId, revision: value.revision, updatedAt });
169
190
  }
170
191
  catch {
171
192
  this.status = { state: 'offline', detail: 'A local draft cannot be read. Other drafts remain available; the damaged file is preserved.' };
@@ -173,11 +194,281 @@ export class GraphSync {
173
194
  }
174
195
  return result.sort((a, b) => b.updatedAt - a.updatedAt);
175
196
  }
197
+ /**
198
+ * Draft snapshots are immutable, and every sweep restores the ones the account holds, so a draft
199
+ * the user cleared cannot be unlinked: it would come back. Each cleared graph instead has its own
200
+ * marker file under `graph-drafts-cleared/`, naming the instant up to which its drafts are
201
+ * cleared and any snapshot dated after that instant (saved under a clock that ran ahead) that
202
+ * was cleared with them. The listing leaves those out; a later autosave is a new snapshot, newer
203
+ * than the mark, and is listed again. A cleared snapshot stays on disk and still opens by hash.
204
+ *
205
+ * One file per graph, replaced whole, so two editors sharing this folder cannot drop each
206
+ * other's clears: clears of different graphs touch different files, and two clears of the same
207
+ * graph each record every draft that graph had.
208
+ */
209
+ async readClearedDrafts() {
210
+ const cleared = new Map();
211
+ for (const entry of await entries(join(this.directory, 'graph-drafts-cleared'))) {
212
+ if (!entry.isFile() || !/^[a-f0-9]{64}\.json$/.test(entry.name))
213
+ continue;
214
+ try {
215
+ const saved = JSON.parse(await readFile(join(this.directory, 'graph-drafts-cleared', entry.name), 'utf8'));
216
+ if (!object(saved) || !safeId(saved.graphId) || typeof saved.at !== 'number' || !Number.isFinite(saved.at))
217
+ continue;
218
+ const snapshots = Array.isArray(saved.snapshots) ? saved.snapshots.filter((hash) => typeof hash === 'string' && /^[a-f0-9]{64}$/.test(hash)) : [];
219
+ cleared.set(saved.graphId, { at: saved.at, snapshots: new Set(snapshots) });
220
+ }
221
+ catch { /* A damaged marker clears nothing, so no draft is hidden by mistake. */ }
222
+ }
223
+ return cleared;
224
+ }
225
+ /** Clear every draft the named graphs have right now, whatever clock dated them. */
226
+ async clearDrafts(graphIds) {
227
+ if (!Array.isArray(graphIds) || !graphIds.length || graphIds.length > 500 || graphIds.some(id => !safeId(id)))
228
+ throw new Error('Invalid draft');
229
+ const wanted = new Set(graphIds), now = Date.now();
230
+ const [listed, cleared] = [await this.drafts(), await this.readClearedDrafts()];
231
+ await mkdir(join(this.directory, 'graph-drafts-cleared'), { recursive: true });
232
+ for (const id of wanted) {
233
+ // A snapshot dated at or before now is covered by the instant; only one dated later needs
234
+ // naming. Earlier names are kept while they stay ahead of the instant, newest 500 at most.
235
+ const ahead = listed.filter(item => item.graphId === id && item.updatedAt > now).map(item => item.snapshot);
236
+ const snapshots = [...new Set([...ahead, ...(cleared.get(id)?.snapshots ?? [])])].slice(0, 500);
237
+ await atomic(join(this.directory, 'graph-drafts-cleared', `${digest(id)}.json`), JSON.stringify({ graphId: id, at: now, snapshots }));
238
+ this.lastDraft.delete(id);
239
+ }
240
+ }
176
241
  async draft(hash) {
177
242
  if (!/^[a-f0-9]{64}$/.test(hash))
178
243
  throw new Error('Invalid draft');
179
244
  return parseSnapshot(await readFile(join(this.directory, 'graph-drafts', `${hash}.json`), 'utf8'), hash).content;
180
245
  }
246
+ /**
247
+ * The tombstones and their lineage floors are one durable record. Keeping them in one atomic
248
+ * replacement means a crash cannot publish a deletion without its floor (or vice versa).
249
+ * The legacy split files are read only for migration; the next mutation writes the combined file.
250
+ */
251
+ async readDeletionState() {
252
+ const parse = (value) => {
253
+ const deleted = new Set();
254
+ const floors = Object.create(null);
255
+ // "pending" holds the head at deletion, not the historic cloud floor. It is paired
256
+ // with a marker in the old folder to distinguish interrupted removal from a new save.
257
+ const pending = Object.create(null);
258
+ if (Array.isArray(value)) {
259
+ for (const id of value)
260
+ if (safeId(id))
261
+ deleted.add(id);
262
+ }
263
+ else if (object(value) && Array.isArray(value.deleted) && object(value.floors)) {
264
+ for (const id of value.deleted)
265
+ if (safeId(id))
266
+ deleted.add(id);
267
+ for (const [id, floor] of Object.entries(value.floors))
268
+ if (safeId(id) && Number.isSafeInteger(floor) && floor >= 1)
269
+ floors[id] = floor;
270
+ if (value.pending !== undefined) {
271
+ if (!object(value.pending))
272
+ throw new Error('Invalid graph deletion pending state');
273
+ for (const [id, head] of Object.entries(value.pending))
274
+ if (safeId(id) && Number.isSafeInteger(head) && head >= 0)
275
+ pending[id] = head;
276
+ }
277
+ }
278
+ else
279
+ throw new Error('Invalid graph deletion state');
280
+ return { deleted, floors, pending };
281
+ };
282
+ try {
283
+ return parse(JSON.parse(await readFile(join(this.folder, 'deletion-state.json'), 'utf8')));
284
+ }
285
+ catch (error) {
286
+ if (error.code !== 'ENOENT')
287
+ throw error;
288
+ }
289
+ // Upgrade older installations that persisted the two parts separately.
290
+ let deleted;
291
+ let floors;
292
+ try {
293
+ const saved = JSON.parse(await readFile(join(this.folder, 'deleted-graphs.json'), 'utf8'));
294
+ deleted = new Set(Array.isArray(saved) ? saved.filter(safeId) : []);
295
+ }
296
+ catch (error) {
297
+ if (error.code === 'ENOENT')
298
+ deleted = new Set();
299
+ else
300
+ throw error;
301
+ }
302
+ try {
303
+ const saved = JSON.parse(await readFile(join(this.folder, 'deleted-revisions.json'), 'utf8'));
304
+ floors = Object.create(null);
305
+ if (object(saved))
306
+ for (const [id, floor] of Object.entries(saved))
307
+ if (safeId(id) && Number.isSafeInteger(floor) && floor >= 1)
308
+ floors[id] = floor;
309
+ }
310
+ catch (error) {
311
+ if (error.code === 'ENOENT')
312
+ floors = Object.create(null);
313
+ else
314
+ throw error;
315
+ }
316
+ return { deleted, floors, pending: Object.create(null) };
317
+ }
318
+ async readDeletedGraphs() { return (await this.readDeletionState()).deleted; }
319
+ async readDeletedRevisions() { return (await this.readDeletionState()).floors; }
320
+ /**
321
+ * Read-modify-write the deletion state under one account-wide lock. Two editors deleting
322
+ * different graphs hold different graphs' save locks, so only a lock across the account stops
323
+ * one replacement from dropping the other's deletion; reviveGraph is serialized by it too.
324
+ * A deletion records its floor in the same lock hold, so a revival can never inherit a floor
325
+ * without the tombstone that justifies it.
326
+ */
327
+ async updateDeletionState(mutate, maxAttempts = 80) {
328
+ const release = await this.acquireAccountLock(maxAttempts);
329
+ try {
330
+ const { deleted, floors, pending } = await this.readDeletionState();
331
+ if (!mutate(deleted, floors, pending))
332
+ return;
333
+ await atomic(join(this.folder, 'deletion-state.json'), JSON.stringify({ deleted: [...deleted], floors, pending }));
334
+ }
335
+ finally {
336
+ await release();
337
+ }
338
+ }
339
+ /**
340
+ * The account-wide lock every tombstone change and deletion tail runs under: two editors
341
+ * deleting different graphs hold different graphs' save locks, so only a lock across the
342
+ * account stops one replacement from dropping the other's deletion, and reviveGraph is
343
+ * serialized by it too.
344
+ */
345
+ async acquireAccountLock(maxAttempts = 80) {
346
+ for (let attempt = 0;; attempt++) {
347
+ try {
348
+ return await acquireSaveLock(this.folder);
349
+ }
350
+ catch (error) {
351
+ if (!(error instanceof SaveLockBusyError))
352
+ throw error;
353
+ if (attempt >= maxAttempts)
354
+ throw new GraphConflictError('Another editor is updating this account. Try again.');
355
+ await delay(25);
356
+ }
357
+ }
358
+ }
359
+ /**
360
+ * The user deleted a graph. Record that before removing anything: the tombstone is written under
361
+ * the graph's save lock, and every later cloud restore re-reads it under the same lock, so a pass
362
+ * running while the delete lands cannot write the graph back. The graph's drafts die with it —
363
+ * each draft snapshot names a graph, and none is left to open. The newest revision the folder had
364
+ * reached is recorded with the tombstone: it is the floor a later revival needs to keep the old
365
+ * lineage's cloud revisions from advancing a replacement.
366
+ */
367
+ async forgetGraph(id) {
368
+ if (!safeId(id) || id === 'default')
369
+ throw new Error('Invalid graph id');
370
+ await mkdir(this.folder, { recursive: true });
371
+ const folder = join(this.directory, 'graphs', id);
372
+ let release;
373
+ for (let attempt = 0; !release; attempt++) {
374
+ try {
375
+ release = await acquireSaveLock(folder);
376
+ }
377
+ catch (error) {
378
+ if (!(error instanceof SaveLockBusyError))
379
+ throw error;
380
+ if (attempt >= 80)
381
+ throw new GraphConflictError('Wait for the current save before deleting this graph.');
382
+ await delay(25);
383
+ }
384
+ }
385
+ // Acquire the account lock once and keep it continuously from the tombstone/floor commit
386
+ // through folder removal and draft pruning. This blocks a concurrent revival from clearing
387
+ // the tombstone between those steps, and every failure path releases both locks.
388
+ let accountRelease;
389
+ try {
390
+ accountRelease = await this.acquireAccountLock();
391
+ // Read while the storage is still there: after the removal the folder no longer says how
392
+ // far the deleted graph had come.
393
+ let newest = 0;
394
+ try {
395
+ const value = JSON.parse(await readFile(join(folder, 'latest.json'), 'utf8'));
396
+ if (Number.isSafeInteger(value) && value >= 1)
397
+ newest = value;
398
+ }
399
+ catch (error) {
400
+ if (error.code !== 'ENOENT')
401
+ throw error;
402
+ }
403
+ // Publish the old folder's identity before the tombstone: a crash after the tombstone
404
+ // but before detach leaves proof that even an uncached graph is deletion residue.
405
+ // A newly-created folder lacks this marker; a save to this same folder advances its head.
406
+ await writeFile(join(folder, DELETION_MARKER), JSON.stringify({ head: newest }), { mode: 0o600 });
407
+ const { deleted, floors, pending } = await this.readDeletionState();
408
+ let changed = false;
409
+ if (!deleted.has(id)) {
410
+ deleted.add(id);
411
+ changed = true;
412
+ }
413
+ // A re-created id can be deleted again: never lower a previous lineage's floor.
414
+ if (newest >= 1 && newest > (floors[id] ?? 0)) {
415
+ floors[id] = newest;
416
+ changed = true;
417
+ }
418
+ if (pending[id] !== newest) {
419
+ pending[id] = newest;
420
+ changed = true;
421
+ }
422
+ if (changed)
423
+ await atomic(join(this.folder, 'deletion-state.json'), JSON.stringify({ deleted: [...deleted], floors, pending }));
424
+ // The graph lock prevents restores/saves to this id; the account lock prevents revival and
425
+ // concurrent tombstone mutations until both the folder and drafts are gone.
426
+ await removeLockedFolder(folder);
427
+ await release();
428
+ await this.pruneDrafts(id);
429
+ this.generation++;
430
+ }
431
+ finally {
432
+ await accountRelease?.();
433
+ await release();
434
+ }
435
+ this.status = { state: 'pending', detail: 'Graph deleted; cloud sync pending' };
436
+ void this.sync();
437
+ }
438
+ /** Remove every draft that names the graph: its drafts die with it. The caller holds the account lock. */
439
+ async pruneDrafts(id) {
440
+ for (const entry of await entries(join(this.directory, 'graph-drafts'))) {
441
+ if (!entry.isFile() || !/^[a-f0-9]{64}\.json$/.test(entry.name))
442
+ continue;
443
+ try {
444
+ const raw = await readFile(join(this.directory, 'graph-drafts', entry.name), 'utf8');
445
+ if (parseSnapshot(raw, entry.name.slice(0, -5)).graphId !== id)
446
+ continue;
447
+ }
448
+ catch {
449
+ continue;
450
+ }
451
+ await unlink(join(this.directory, 'graph-drafts', entry.name)).catch(() => { });
452
+ }
453
+ this.lastDraft.delete(id);
454
+ }
455
+ /**
456
+ * A graph with this id was saved again: its cloud snapshots may restore once more. The floor
457
+ * recorded at the deletion stays — it is what keeps the old lineage's revisions from advancing
458
+ * the replacement's latest pointer.
459
+ */
460
+ async reviveGraph(id) {
461
+ if (!safeId(id) || id === 'default')
462
+ return;
463
+ // A slow draft prune can hold the account lock past the normal two-second budget.
464
+ // A successful save must not return while its tombstone remains: keep retrying the
465
+ // durable revival, and propagate a real failure instead of silently swallowing it.
466
+ await this.updateDeletionState((deleted, _floors, pending) => {
467
+ const changed = deleted.delete(id) || Object.hasOwn(pending, id);
468
+ delete pending[id];
469
+ return changed;
470
+ }, 600);
471
+ }
181
472
  sync() {
182
473
  if (this.stopped)
183
474
  return Promise.resolve();
@@ -211,6 +502,98 @@ export class GraphSync {
211
502
  throw error;
212
503
  }
213
504
  }
505
+ /**
506
+ * A committed tombstone has two possible local folders: the old folder an interrupted
507
+ * delete did not detach, or a replacement published while revival waited for the account
508
+ * lock. The deletion marker and head at deletion identify only the former. Legacy
509
+ * tombstones have no marker, so retain the existing conservative cached-head check.
510
+ *
511
+ * Lock order matches forgetGraph (graph, then account); inspect fresh state only while
512
+ * holding both locks, so a concurrent save/revival cannot be removed by a stale pass.
513
+ */
514
+ async reconcileDeletedFolders(deleted) {
515
+ for (const id of deleted) {
516
+ const folder = join(this.directory, 'graphs', id);
517
+ try {
518
+ await readdir(folder);
519
+ }
520
+ catch (error) {
521
+ if (error.code === 'ENOENT')
522
+ continue;
523
+ throw error;
524
+ }
525
+ let release;
526
+ try {
527
+ for (let attempt = 0; !release; attempt++) {
528
+ try {
529
+ release = await acquireSaveLock(folder);
530
+ }
531
+ catch (error) {
532
+ if (!(error instanceof SaveLockBusyError))
533
+ throw error;
534
+ if (attempt >= 80)
535
+ throw new GraphConflictError('Wait for the current save before deleting this graph.');
536
+ await delay(25);
537
+ }
538
+ }
539
+ const accountRelease = await this.acquireAccountLock();
540
+ try {
541
+ const state = await this.readDeletionState();
542
+ if (!state.deleted.has(id))
543
+ continue;
544
+ let head = 0;
545
+ try {
546
+ const saved = JSON.parse(await readFile(join(folder, 'latest.json'), 'utf8'));
547
+ if (!Number.isSafeInteger(saved) || saved < 1)
548
+ continue;
549
+ head = saved;
550
+ }
551
+ catch (error) {
552
+ if (error.code !== 'ENOENT')
553
+ throw error;
554
+ }
555
+ const pending = Object.hasOwn(state.pending, id) ? state.pending[id] : undefined;
556
+ if (pending !== undefined) {
557
+ let marker;
558
+ try {
559
+ const value = JSON.parse(await readFile(join(folder, DELETION_MARKER), 'utf8'));
560
+ if (object(value) && Number.isSafeInteger(value.head) && value.head >= 0)
561
+ marker = value.head;
562
+ }
563
+ catch { /* A missing or damaged marker is not proof of residue: preserve data. */ }
564
+ if (marker === pending && head === pending) {
565
+ await removeLockedFolder(folder);
566
+ await this.pruneDrafts(id);
567
+ }
568
+ else if (head >= 1) {
569
+ // A new folder (no marker) or an advanced head is a save performed after the
570
+ // tombstone. Complete its interrupted revival while preserving the old floor.
571
+ state.deleted.delete(id);
572
+ delete state.pending[id];
573
+ await atomic(join(this.folder, 'deletion-state.json'), JSON.stringify({ deleted: [...state.deleted], floors: state.floors, pending: state.pending }));
574
+ this.generation++;
575
+ }
576
+ }
577
+ else if (head >= 1) {
578
+ // Legacy interrupted deletes have no marker. Only an uploaded, cached head
579
+ // demonstrates the old lineage, so never destroy an uncached legacy folder.
580
+ const hash = digest(envelope('revision', JSON.parse(await readFile(join(folder, `${head}.json`), 'utf8'))));
581
+ if (await this.cached(hash)) {
582
+ await removeLockedFolder(folder);
583
+ await this.pruneDrafts(id);
584
+ }
585
+ }
586
+ }
587
+ finally {
588
+ await accountRelease();
589
+ }
590
+ }
591
+ catch { /* Retry a locked or damaged folder on the next pass; never guess and remove it. */ }
592
+ finally {
593
+ await release?.();
594
+ }
595
+ }
596
+ }
214
597
  async request(path, token, body) {
215
598
  this.checkBudget();
216
599
  if (await this.deps.subject() !== this.subject)
@@ -257,19 +640,20 @@ export class GraphSync {
257
640
  async perform() {
258
641
  this.deadline = this.now() + 20_000;
259
642
  this.status = { state: 'syncing', detail: 'Saving graphs to your account…' };
260
- // The token first: it may have to wait for another process's rotation, and the subject check
261
- // reads the same stored session under the same auth lock, so checking the subject first would
262
- // time out ahead of that wait and turn the pass offline before it ever reaches the rotation.
643
+ // Repair interrupted local deletions before network authorization: even an offline machine
644
+ // must not show a graph whose tombstone was committed before a crash. A save that landed
645
+ // after that tombstone is revived rather than removed.
646
+ await mkdir(join(this.folder, 'snapshots'), { recursive: true });
647
+ await this.reconcileDeletedFolders(await this.readDeletedGraphs());
648
+ const deleted = await this.readDeletedGraphs();
649
+ // Token acquisition may wait for a refresh rotation; check the account afterwards.
263
650
  const token = await this.deps.token(this.closer.signal);
264
651
  if (!token)
265
652
  throw new Error('Sign in required');
266
653
  if (await this.deps.subject() !== this.subject)
267
654
  throw new Error('Account changed');
268
- // The server verifies the signature; this comparison binds the captured token to
269
- // the local queue even if another process changes accounts during token refresh.
270
655
  if (decodeJwt(token).sub !== this.subject)
271
656
  throw new Error('Account changed');
272
- await mkdir(join(this.folder, 'snapshots'), { recursive: true });
273
657
  let receipts = {};
274
658
  try {
275
659
  const saved = JSON.parse(await readFile(join(this.folder, 'receipts.json'), 'utf8'));
@@ -350,7 +734,11 @@ export class GraphSync {
350
734
  };
351
735
  const exhausted = () => processed >= 32 || this.now() >= localDeadline || this.stopped;
352
736
  if (!local.drafts) {
353
- const dirs = (await entries(join(this.directory, 'graphs'))).filter(dir => dir.isDirectory() && safeId(dir.name)).sort((a, b) => a.name < b.name ? -1 : 1);
737
+ // A folder a tombstone still names is either deletion residue (reconciled above) or a
738
+ // replacement whose revival has not landed yet: uploading either would put a deleted
739
+ // graph's revisions back into the cloud. The revival clears the tombstone, and the next
740
+ // sweep then uploads the replacement.
741
+ const dirs = (await entries(join(this.directory, 'graphs'))).filter(dir => dir.isDirectory() && safeId(dir.name) && !deleted.has(dir.name)).sort((a, b) => a.name < b.name ? -1 : 1);
354
742
  // A free account's cloud allowance is pinned to the first graph whose revision arrives, and the
355
743
  // graph it keeps here is its oldest. One revision of the kept graph therefore goes first in every
356
744
  // sweep, so the two agree whatever the ids' order; one is enough to set the pin. The checkpoint
@@ -409,6 +797,21 @@ export class GraphSync {
409
797
  localComplete = false;
410
798
  break;
411
799
  }
800
+ // A draft of a deleted graph is residue from a restore that raced the delete; prune it so
801
+ // the graph's tombstone keeps every trace of the graph off this machine.
802
+ if (deleted.size) {
803
+ try {
804
+ const raw = await readFile(join(this.directory, 'graph-drafts', file.name), 'utf8');
805
+ if (deleted.has(parseSnapshot(raw, file.name.slice(0, -5)).graphId)) {
806
+ await unlink(join(this.directory, 'graph-drafts', file.name)).catch(() => { });
807
+ local.file = file.name;
808
+ processed++;
809
+ await atomic(localPath, JSON.stringify(local));
810
+ continue;
811
+ }
812
+ }
813
+ catch { /* A damaged draft is left for the drafts() reader to report. */ }
814
+ }
412
815
  await upload(join(this.directory, 'graph-drafts', file.name), 'draft', file.name);
413
816
  local.file = file.name;
414
817
  processed++;
@@ -459,7 +862,7 @@ export class GraphSync {
459
862
  ? await readFile(join(this.folder, 'snapshots', `${hash}.json`), 'utf8')
460
863
  : await this.request(`/${hash}`, token);
461
864
  // A cloud receipt proves upload, not that its user-visible copy still exists.
462
- await this.restoreSnapshot(raw, hash, receipts);
865
+ await this.restoreSnapshot(raw, hash, receipts, deleted);
463
866
  progress.page.remaining.shift();
464
867
  await atomic(progressPath, JSON.stringify(progress));
465
868
  }
@@ -492,8 +895,15 @@ export class GraphSync {
492
895
  }
493
896
  await immutable(path, raw);
494
897
  }
495
- async restoreSnapshot(raw, hash, receipts) {
898
+ async restoreSnapshot(raw, hash, receipts, deleted) {
496
899
  const value = parseSnapshot(raw, hash);
900
+ // A graph deleted on this machine stays deleted: its snapshots stay cached but restore no
901
+ // more. A draft restored in the window between a delete and this verdict is pruned by the
902
+ // next pass over the local drafts; the revision path below closes its own race under the lock.
903
+ if (deleted.has(value.graphId)) {
904
+ await immutable(join(this.folder, 'snapshots', `${hash}.json`), raw);
905
+ return;
906
+ }
497
907
  // Never overwrite a local graph. Stable recovery IDs retain conflicting versions.
498
908
  if (value.kind === 'revision') {
499
909
  let graph;
@@ -505,14 +915,24 @@ export class GraphSync {
505
915
  await immutable(join(this.folder, 'snapshots', `${hash}.json`), raw);
506
916
  return;
507
917
  }
918
+ // The guard re-reads the tombstone file under the graph's save lock, so a delete that landed
919
+ // while this pass was running is honored even though this pass read an older verdict.
920
+ let restored = true;
508
921
  try {
509
- await restoreGraphRevision(graph, this.directory);
922
+ ({ restored } = await restoreGraphRevision(graph, this.directory, async (candidate) => (await this.readDeletedGraphs()).has(candidate.id), async (candidate) => (await this.readDeletedRevisions())[candidate.id]));
510
923
  }
511
924
  catch (error) {
925
+ // Never overwrite a local graph: a conflicting revision is kept beside the original under
926
+ // a stable recovery id. The recovery copy is a graph like any other, so the same deletion
927
+ // guard applies to it: a recovery id the user deleted is not written back either.
512
928
  if (!(error instanceof GraphConflictError))
513
929
  throw error;
514
930
  graph = { ...graph, id: `cloud-${hash.slice(0, 40)}`, name: `${graph.name} (conflict r${graph.revision})`.slice(0, 120) };
515
- await restoreGraphRevision(graph, this.directory);
931
+ ({ restored } = await restoreGraphRevision(graph, this.directory, async (candidate) => (await this.readDeletedGraphs()).has(candidate.id), async (candidate) => (await this.readDeletedRevisions())[candidate.id]));
932
+ }
933
+ if (!restored) {
934
+ await immutable(join(this.folder, 'snapshots', `${hash}.json`), raw);
935
+ return;
516
936
  }
517
937
  const path = join(this.directory, 'graphs', graph.id, `${graph.revision}.json`);
518
938
  const fingerprint = digest(await readFile(path, 'utf8'));
@@ -0,0 +1,52 @@
1
+ import type { Tool } from './types.js';
2
+ /** What the tool needs from the graph backend; `AgentMcpBackend` in production. */
3
+ export interface GraphBackend {
4
+ call(name: string, args: unknown, options?: {
5
+ beforeSave?: () => void;
6
+ }): Promise<{
7
+ ok: true;
8
+ data: unknown;
9
+ } | {
10
+ ok: false;
11
+ error: unknown;
12
+ }>;
13
+ close(): Promise<void>;
14
+ }
15
+ /**
16
+ * One graph backend per installation directory, created on the first graph action and closed after
17
+ * an idle hour.
18
+ *
19
+ * Shared across the tasks of one process so a draft begun in one task survives into the next, and so
20
+ * at most one cloud-sync loop runs per home however many tasks touch graphs. Nothing is loaded until
21
+ * a graph action runs: the backend module pulls in graph sync, membership and the subagent runner.
22
+ */
23
+ export declare class GraphBackendPool {
24
+ private readonly options;
25
+ private readonly entries;
26
+ constructor(options?: {
27
+ create?: (directory: string) => Promise<GraphBackend>;
28
+ idleCloseMs?: number;
29
+ });
30
+ call(directory: string, action: string, args: unknown, options?: {
31
+ beforeSave?: () => void;
32
+ }): Promise<{
33
+ ok: true;
34
+ data: unknown;
35
+ } | {
36
+ ok: false;
37
+ error: unknown;
38
+ }>;
39
+ /** Close every backend (tests, shutdown). A later action opens a fresh one. */
40
+ close(): Promise<void>;
41
+ /** Open backends, by directory; for tests that prove laziness and idle closing. */
42
+ get size(): number;
43
+ private closeEntry;
44
+ }
45
+ /**
46
+ * The engine's built-in graph authoring tool: the graph MCP server's graph actions, in process.
47
+ *
48
+ * Agents inside Andorra get graph authoring without a configured MCP server, a child process or an
49
+ * `andorra` command on PATH. One tool with an `action` keeps every request's schema small; the action
50
+ * names are the MCP tool names, so the guide, the graph-manager skill and the error codes apply as-is.
51
+ */
52
+ export declare function createGraphTool(pool?: GraphBackendPool): Tool;