Personal Telegram developer console for GitHub

feat/studio-g0-foundation
audit/commit-drilldown audit/finalize-workspace-menu-security audit/ops-actionability audit/pr-menu-consolidation audit/status-menu-consolidation audit/telegram-menu-e2e audit/telegram-menu-e2e-wave2 chore/actions-node24-runtime cleanup/remove-diag design/cloudflare-ops-read docs/control-plane-2-7-design docs/guide-v2-1-sync docs/menu-audit-final-sync docs/phase2-acceptance-closeout docs/phase2-multifile-design feat/bootstrap-worker feat/cloudflare-ops-read feat/cp2-multifile-final feat/cp2-multifile-workspace feat/cp3-github-write-final feat/cp4-cloudflare-ops-final feat/cp5-cicd-control-plane feat/cp6-incident-manager feat/cp7-automation-engine feat/deep-file-browser feat/final-delivery-16-20 feat/github-advanced-read feat/in-app-guide-v2 feat/navigation-recovery-ux-v2 feat/ops-console-v2-1 feat/persistent-menu-code-input feat/phase2-multifile-workspace feat/phase2-multifile-workspace-v2 feat/plugin-foundation-v1 feat/safe-github-ops feat/self-register-webhook feat/studio-g0-foundation feat/telegram-main-inline-menu feat/telegram-pr-merge feat/ux-platform-8-12 feat/v3a-readonly-copilot feat/workspace-file-upload feature/mobile-repo-browser feature/multi-file-change-set fix/approval-expiry-feedback fix/callback-resilience-and-docs fix/ci-actions-pagination fix/cloudflare-fetch-binding fix/editor-request-body-cap fix/editor-safe-file-options fix/issues-permission-release-empty-ux fix/main-menu-callback-fallback fix/phase2-file-editor-selection fix/phase2-final-ux fix/phase2-workspace-ref-persistence fix/production-auto-deploy fix/provider-write-error-feedback fix/repository-id-navigation-fallback fix/repository-pr-navigation fix/telegram-callback-updates fix/telegram-runtime-diagnostics fix/workspace-editor-flow-v2 fix/workspace-recovery-validation hardening/ci-zero-test-telegram-token hardening/pr1-destructive-totp hardening/pr2-kill-switch main multifile-workspace nexa/edit-BwJEIIY3PW nexa/edit-IPHT8irO7b nexa/edit-b4Od3BIMYd p2-multifile phase2-20261005 phase2-20261005-a phase2-20261005-b phase2-20261005-c phase2-20261005-d phase2-20261005-e phase2-20261005-f phase2-20261005-g phase2-20261005-h phase2-20261005-i phase2-20261005-j phase2-20261005-k phase2-20261005-l phase2-20261005-m phase2-20261005-n phase2-20261005-o phase2-20261005-p phase2-20261005-q phase2-20261005-r phase2-20261005-s phase2-20261005-t phase2-20261005-u phase2-20261005-v phase2-20261005-w phase2-20261005-x phase2-20261005-y phase2-20261005-z phase2-acceptance-closeout phase2-add-file-hotfix phase2-change-set phase2-design-20261005 phase2-design-final phase2-implementation phase2-multifile-implementation phase2-multifile-spec phase2-spec-final phase2-workspace phase2/multifile-workspace plan/nexa-studio-v2-reviewed security/remove-telegram-setup spec/repository-workspace-editor v3a/multifile work/multifile
js 733 lines 24.4 KB
Raw
1 import { WORKSPACE_EDITOR_LIMITS } from '../core/workspace-policy.js';
2
3 const json = (payload, status = 200) => Response.json(payload, { status });
4 const HANDLE_ALPHABET =
5 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
6 const WORKSPACE_TTL_MS = 30 * 60_000,
7 REF_TTL_MS = 15 * 60_000,
8 COMMITTED_RETENTION_MS = 24 * 60 * 60_000;
9 const MAX_WORKSPACE_BYTES = 262144;
10 function randomHandle(length) {
11 const bytes = new Uint8Array(length);
12 crypto.getRandomValues(bytes);
13 let out = '';
14 for (const byte of bytes) out += HANDLE_ALPHABET[byte & 63];
15 return out;
16 }
17 function finiteNow(v) {
18 const n = Number(v);
19 return Number.isFinite(n) ? n : Date.now();
20 }
21 function positiveTtl(v, f) {
22 const n = Number(v);
23 return Number.isFinite(n) && n > 0 ? n : f;
24 }
25 function expired(r, now) {
26 return Boolean(
27 r && Number.isFinite(Number(r.expiresAt)) && Number(r.expiresAt) < now
28 );
29 }
30 function normalizePath(value) {
31 const path = String(value || '')
32 .replace(/\\/g, '/')
33 .replace(/^\.\//, '');
34 if (
35 !path ||
36 path.startsWith('/') ||
37 path.split('/').some((p) => !p || p === '.' || p === '..')
38 )
39 throw new Error('Workspace file path is invalid');
40 return path;
41 }
42 function fileRevision(file) {
43 return Number.isSafeInteger(file?.revision) && file.revision >= 0
44 ? file.revision
45 : 0;
46 }
47 function nextRevision(revision) {
48 if (!Number.isSafeInteger(revision) || revision >= Number.MAX_SAFE_INTEGER)
49 throw new Error('Workspace file revision limit reached');
50 return revision + 1;
51 }
52 function revisionConflict() {
53 const error = new Error('Workspace file revision conflict');
54 error.code = 'REVISION_CONFLICT';
55 return error;
56 }
57 function assertExpectedRevision(payload, revision) {
58 if (payload.expectedRevision === undefined) return;
59 if (
60 !Number.isSafeInteger(payload.expectedRevision) ||
61 payload.expectedRevision < 0
62 )
63 throw new Error('Workspace file revision is invalid');
64 if (payload.expectedRevision !== revision) throw revisionConflict();
65 }
66 function assertExpectedReview(expectedReview, workspace, proposed) {
67 if (expectedReview === undefined) return;
68 if (
69 !expectedReview ||
70 typeof expectedReview.baseHeadSha !== 'string' ||
71 !Array.isArray(expectedReview.files)
72 )
73 throw new Error('Workspace review is invalid');
74 const revisions = new Map();
75 for (const file of expectedReview.files) {
76 if (
77 typeof file?.path !== 'string' ||
78 !Number.isSafeInteger(file.revision) ||
79 file.revision < 0 ||
80 revisions.has(file.path)
81 )
82 throw new Error('Workspace review is invalid');
83 revisions.set(file.path, file.revision);
84 }
85 if (
86 expectedReview.baseHeadSha !== workspace.baseHeadSha ||
87 (expectedReview.commitMessageDigest !== undefined &&
88 expectedReview.commitMessageDigest !== workspace.commitMessageDigest) ||
89 revisions.size !== workspace.files.length ||
90 workspace.files.some(
91 (file) => revisions.get(file.path) !== fileRevision(file)
92 )
93 )
94 throw revisionConflict();
95 if (
96 expectedReview.commitMessageDigest !== undefined &&
97 (proposed.workspaceId !== workspace.id ||
98 Number(proposed.repoId) !== Number(workspace.repoId) ||
99 proposed.baseBranch !== workspace.baseBranch ||
100 proposed.baseHeadSha !== workspace.baseHeadSha ||
101 proposed.baseTreeSha !== workspace.baseTreeSha ||
102 proposed.commitMessageDigest !== workspace.commitMessageDigest ||
103 !Array.isArray(proposed.files) ||
104 proposed.files.length !== workspace.files.length ||
105 workspace.files.some(
106 (file, index) =>
107 proposed.files[index]?.path !== file.path ||
108 proposed.files[index]?.sourceBlobSha !== file.blobSha ||
109 proposed.files[index]?.contentDigest !== file.draftDigest
110 ))
111 )
112 throw revisionConflict();
113 }
114 function legacyFile(payload) {
115 return {
116 path: normalizePath(payload.path),
117 blobSha: String(payload.blobSha || ''),
118 originalText: String(payload.originalText ?? ''),
119 originalDigest: String(payload.originalDigest || ''),
120 draftText: String(payload.originalText ?? ''),
121 draftDigest: String(payload.originalDigest || ''),
122 revision: 0
123 };
124 }
125 function migrate(ws) {
126 if (!ws) return ws;
127 if (Array.isArray(ws.files))
128 return {
129 ...ws,
130 files: ws.files.map((file) => ({
131 ...file,
132 revision: fileRevision(file)
133 }))
134 };
135 return {
136 ...ws,
137 schemaVersion: 2,
138 files: [
139 {
140 path: String(ws.path || ''),
141 blobSha: String(ws.blobSha || ''),
142 originalText: String(ws.originalText ?? ''),
143 originalDigest: String(ws.originalDigest || ''),
144 draftText: String(ws.draftText ?? ws.originalText ?? ''),
145 draftDigest: String(ws.draftDigest || ws.originalDigest || ''),
146 revision: 0
147 }
148 ]
149 };
150 }
151 function bytes(files) {
152 return files.reduce(
153 (n, f) =>
154 n +
155 new TextEncoder().encode(String(f.originalText ?? '')).length +
156 new TextEncoder().encode(String(f.draftText ?? '')).length,
157 0
158 );
159 }
160 function validateFiles(files) {
161 if (!Array.isArray(files) || !files.length)
162 throw new Error('Workspace must contain at least one file');
163 const seen = new Set();
164 for (const f of files) {
165 const p = normalizePath(f.path);
166 if (seen.has(p)) throw new Error('Workspace file path already exists');
167 seen.add(p);
168 }
169 if (bytes(files) > MAX_WORKSPACE_BYTES)
170 throw new Error('Workspace aggregate size is too large');
171 const encoder = new TextEncoder(),
172 aggregateBytes = files.reduce(
173 (total, file) =>
174 total +
175 Math.max(
176 encoder.encode(String(file.originalText ?? '')).byteLength,
177 encoder.encode(String(file.draftText ?? '')).byteLength
178 ),
179 0
180 );
181 if (
182 files.length > WORKSPACE_EDITOR_LIMITS.maxFiles ||
183 aggregateBytes > WORKSPACE_EDITOR_LIMITS.maxAggregateBytes
184 ) {
185 const error = new Error('Workspace aggregate text or file limit exceeded');
186 error.code = 'WORKSPACE_LIMIT_EXCEEDED';
187 throw error;
188 }
189 }
190
191 export class WorkspaceStore {
192 constructor(state) {
193 this.state = state;
194 }
195 async fetch(request) {
196 const url = new URL(request.url);
197 if (request.method !== 'POST')
198 return new Response('Not Found', { status: 404 });
199 let payload;
200 try {
201 payload = await request.json();
202 } catch {
203 return json({ error: 'Invalid workspace payload' }, 400);
204 }
205 const now = finiteNow(payload?.now);
206 try {
207 switch (url.pathname) {
208 case '/refs/create':
209 return json({ result: await this.#createRefs(payload, now) });
210 case '/refs/get':
211 return json({
212 result: await this.#getExpiring(
213 `ref:${String(payload.refId || '')}`,
214 now
215 )
216 });
217 case '/workspace/create':
218 return json({ result: await this.#createWorkspace(payload, now) });
219 case '/workspace/get':
220 return json({
221 result: migrate(
222 await this.#getExpiring(
223 `ws:${String(payload.workspaceId || '')}`,
224 now
225 )
226 )
227 });
228 case '/workspace/draft':
229 return json({ result: await this.#updateDraft(payload, now) });
230 case '/workspace/file/upsert':
231 return json({ result: await this.#upsertFile(payload, now) });
232 case '/workspace/file/draft':
233 return json({ result: await this.#updateFileDraft(payload, now) });
234 case '/workspace/file/remove':
235 return json({ result: await this.#removeFile(payload, now) });
236 case '/workspace/message':
237 return json({ result: await this.#setCommitMessage(payload, now) });
238 case '/workspace/cancel':
239 return json({ result: await this.#cancelWorkspace(payload) });
240 case '/pending/set':
241 return json({ result: await this.#setPending(payload, now) });
242 case '/pending/get':
243 return json({ result: await this.#getPending(now) });
244 case '/pending/consume':
245 return json({ result: await this.#consumePending(payload, now) });
246 case '/intent/seal':
247 return json({ result: await this.#sealIntent(payload, now) });
248 case '/intent/get':
249 return json({
250 result: await this.#getExpiring(
251 `intent:${String(payload.intentId || '')}`,
252 now
253 )
254 });
255 case '/intent/begin':
256 return json({ result: await this.#beginCommit(payload, now) });
257 case '/intent/candidate':
258 return json({ result: await this.#setCandidate(payload, now) });
259 case '/intent/complete':
260 return json({ result: await this.#completeCommit(payload, now) });
261 case '/intent/stale':
262 return json({ result: await this.#markStale(payload, now) });
263 default:
264 return new Response('Not Found', { status: 404 });
265 }
266 } catch (error) {
267 const status = {
268 REVISION_CONFLICT: 409,
269 WORKSPACE_NOT_EDITABLE: 409,
270 WORKSPACE_LIMIT_EXCEEDED: 422
271 }[error?.code];
272 return json(
273 {
274 error: String(error?.message || 'Workspace store operation failed'),
275 ...(status ? { code: error.code } : {})
276 },
277 status || 400
278 );
279 }
280 }
281 async #schedule(expiresAt) {
282 const expiry = Number(expiresAt);
283 if (!Number.isFinite(expiry)) return;
284 const current = Number(await this.state.storage.get('__next_alarm'));
285 if (!Number.isFinite(current) || expiry < current) {
286 await this.state.storage.put('__next_alarm', expiry);
287 await this.state.storage.setAlarm(expiry);
288 }
289 }
290 async #getExpiring(key, now, storage = this.state.storage) {
291 if (!key || key.endsWith(':')) return null;
292 const record = await storage.get(key);
293 if (!record) return null;
294 if (expired(record, now)) {
295 await storage.delete(key);
296 return null;
297 }
298 return record;
299 }
300 async #createRefs(payload, now) {
301 if (!Array.isArray(payload.refs))
302 throw new Error('Navigation refs are required');
303 const expiresAt = now + positiveTtl(payload.ttlMs, REF_TTL_MS),
304 output = [];
305 for (const source of payload.refs) {
306 const refId = randomHandle(10),
307 type = ['dir', 'file', 'workspace-add', 'workspace-file'].includes(
308 source?.type
309 )
310 ? source.type
311 : 'file',
312 workspaceId = String(source?.workspaceId || '');
313 if (
314 type.startsWith('workspace-') &&
315 !/^[A-Za-z0-9_-]{10}$/.test(workspaceId)
316 )
317 throw new Error('Workspace navigation ref is invalid');
318 const record = {
319 repoId: source?.repoId,
320 path: String(source?.path || ''),
321 type,
322 sha: String(source?.sha || ''),
323 ...(type.startsWith('workspace-') ? { workspaceId } : {}),
324 expiresAt
325 };
326 await this.state.storage.put(`ref:${refId}`, record);
327 output.push({ refId });
328 }
329 await this.#schedule(expiresAt);
330 return output;
331 }
332 async #createWorkspace(payload, now) {
333 const id = randomHandle(10),
334 expiresAt = Number.isFinite(Number(payload.expiresAt))
335 ? Number(payload.expiresAt)
336 : now + WORKSPACE_TTL_MS;
337 if (expiresAt <= now)
338 throw new Error('Workspace expiry must be in the future');
339 const first = legacyFile(payload);
340 validateFiles([first]);
341 const workspace = {
342 id,
343 schemaVersion: 2,
344 repoId: payload.repoId,
345 repoFullName: String(payload.repoFullName || ''),
346 baseBranch: String(payload.baseBranch || ''),
347 baseHeadSha: String(payload.baseHeadSha || ''),
348 baseTreeSha: String(payload.baseTreeSha || ''),
349 path: first.path,
350 blobSha: first.blobSha,
351 originalText: first.originalText,
352 originalDigest: first.originalDigest,
353 draftText: first.draftText,
354 draftDigest: first.draftDigest,
355 files: [first],
356 commitMessage: '',
357 commitMessageDigest: '',
358 currentIntentId: null,
359 state: 'DRAFT',
360 createdAt: now,
361 updatedAt: now,
362 expiresAt
363 };
364 await this.state.storage.put(`ws:${id}`, workspace);
365 await this.#schedule(expiresAt);
366 return workspace;
367 }
368 async #requireWorkspace(id, now, storage = this.state.storage) {
369 const ws = migrate(
370 await this.#getExpiring(`ws:${String(id || '')}`, now, storage)
371 );
372 if (!ws) throw new Error('Workspace not found or expired');
373 return ws;
374 }
375 async #requireEditableWorkspace(id, now, storage) {
376 const workspace = await this.#requireWorkspace(id, now, storage);
377 const intent = workspace.currentIntentId
378 ? await storage.get(`intent:${workspace.currentIntentId}`)
379 : null;
380 if (
381 [workspace.state, intent?.state].some((state) =>
382 ['COMMITTING', 'COMMITTED'].includes(state)
383 )
384 ) {
385 const error = new Error('Workspace is not editable');
386 error.code = 'WORKSPACE_NOT_EDITABLE';
387 throw error;
388 }
389 return workspace;
390 }
391 async #saveMaterial(ws, files, now, storage, materialChanged = true) {
392 validateFiles(files);
393 const primary = files[0];
394 const updated = {
395 ...ws,
396 schemaVersion: 2,
397 files,
398 path: primary.path,
399 blobSha: primary.blobSha,
400 originalText: primary.originalText,
401 originalDigest: primary.originalDigest,
402 draftText: primary.draftText,
403 draftDigest: primary.draftDigest,
404 ...(materialChanged ? { currentIntentId: null, state: 'DRAFT' } : {}),
405 updatedAt: now
406 };
407 await storage.put(`ws:${ws.id}`, updated);
408 return updated;
409 }
410 async #upsertFile(payload, now) {
411 return this.state.storage.transaction(async (txn) => {
412 const ws = await this.#requireEditableWorkspace(
413 payload.workspaceId,
414 now,
415 txn
416 ),
417 source = payload.file || {},
418 path = normalizePath(source.path);
419 if (ws.files.some((f) => normalizePath(f.path) === path))
420 throw new Error('Workspace file path already exists');
421 const file = {
422 path,
423 blobSha: String(source.blobSha || ''),
424 originalText: String(source.originalText ?? ''),
425 originalDigest: String(source.originalDigest || ''),
426 draftText: String(source.draftText ?? source.originalText ?? ''),
427 draftDigest: String(source.draftDigest || source.originalDigest || ''),
428 revision: fileRevision({ revision: ws.fileRevisionFloor })
429 };
430 return this.#saveMaterial(ws, [...ws.files, file], now, txn);
431 });
432 }
433 async #updateFileDraft(payload, now) {
434 return this.state.storage.transaction(async (txn) => {
435 const ws = await this.#requireEditableWorkspace(
436 payload.workspaceId,
437 now,
438 txn
439 ),
440 path = normalizePath(payload.path),
441 digest = String(payload.digest || '');
442 if (!digest) throw new Error('Draft digest is required');
443 const file = ws.files.find((f) => normalizePath(f.path) === path);
444 if (!file) throw new Error('Workspace file not found');
445 assertExpectedRevision(payload, fileRevision(file));
446 const changed = file.draftDigest !== digest,
447 files = ws.files.map((f) =>
448 f === file
449 ? {
450 ...f,
451 ...(changed
452 ? {
453 draftText: String(payload.text ?? ''),
454 draftDigest: digest
455 }
456 : {}),
457 revision: nextRevision(fileRevision(f))
458 }
459 : f
460 );
461 return this.#saveMaterial(ws, files, now, txn, changed);
462 });
463 }
464 async #removeFile(payload, now) {
465 return this.state.storage.transaction(async (txn) => {
466 const ws = await this.#requireEditableWorkspace(
467 payload.workspaceId,
468 now,
469 txn
470 ),
471 path = normalizePath(payload.path),
472 files = ws.files.filter((f) => normalizePath(f.path) !== path);
473 if (files.length === ws.files.length)
474 throw new Error('Workspace file not found');
475 // A scalar floor prevents stale revisions matching a removed/readded path.
476 const fileRevisionFloor = nextRevision(
477 Math.max(
478 fileRevision({ revision: ws.fileRevisionFloor }),
479 ...ws.files.map(fileRevision)
480 )
481 );
482 return this.#saveMaterial({ ...ws, fileRevisionFloor }, files, now, txn);
483 });
484 }
485 async #updateDraft(payload, now) {
486 return this.state.storage.transaction(async (txn) => {
487 const ws = await this.#requireEditableWorkspace(
488 payload.workspaceId,
489 now,
490 txn
491 ),
492 digest = String(payload.digest || '');
493 if (!digest) throw new Error('Draft digest is required');
494 const changed = digest !== ws.draftDigest,
495 files = ws.files.map((f, i) =>
496 i
497 ? f
498 : {
499 ...f,
500 ...(changed
501 ? {
502 draftText: String(payload.text ?? ''),
503 draftDigest: digest
504 }
505 : {}),
506 revision: nextRevision(fileRevision(f))
507 }
508 );
509 return this.#saveMaterial(ws, files, now, txn, changed);
510 });
511 }
512 async #setCommitMessage(payload, now) {
513 return this.state.storage.transaction(async (txn) => {
514 const ws = await this.#requireEditableWorkspace(
515 payload.workspaceId,
516 now,
517 txn
518 ),
519 digest = String(payload.digest || '');
520 if (!digest) throw new Error('Commit message digest is required');
521 const changed = digest !== ws.commitMessageDigest,
522 updated = {
523 ...ws,
524 commitMessage: String(payload.message || ''),
525 commitMessageDigest: digest,
526 updatedAt: now,
527 ...(changed ? { currentIntentId: null, state: 'DRAFT' } : {})
528 };
529 await txn.put(`ws:${ws.id}`, updated);
530 return updated;
531 });
532 }
533 async #setPending(payload, now) {
534 const ws = await this.#requireWorkspace(payload.workspaceId, now),
535 mode = String(payload.mode || '');
536 if (!['draft', 'draft_file', 'commit_message'].includes(mode))
537 throw new Error('Pending input mode is invalid');
538 const pending = { workspaceId: ws.id, mode, expiresAt: ws.expiresAt };
539 await this.state.storage.put('pending', pending);
540 await this.#schedule(pending.expiresAt);
541 return pending;
542 }
543 async #getPending(now) {
544 const p = await this.state.storage.get('pending');
545 if (!p) return null;
546 if (expired(p, now)) {
547 await this.state.storage.delete('pending');
548 return null;
549 }
550 const ws = await this.#getExpiring(`ws:${p.workspaceId}`, now);
551 if (!ws) {
552 await this.state.storage.delete('pending');
553 return null;
554 }
555 return { workspaceId: p.workspaceId, mode: p.mode };
556 }
557 async #consumePending(payload, now) {
558 return this.state.storage.transaction(async (txn) => {
559 const p = await txn.get('pending');
560 if (!p || expired(p, now)) {
561 if (p) await txn.delete('pending');
562 return false;
563 }
564 if (
565 p.workspaceId !== String(payload.workspaceId || '') ||
566 p.mode !== String(payload.mode || '')
567 )
568 return false;
569 await txn.delete('pending');
570 return true;
571 });
572 }
573 async #sealIntent(payload, now) {
574 const intent = await this.state.storage.transaction(async (txn) => {
575 const ws = await this.#requireEditableWorkspace(
576 payload.workspaceId,
577 now,
578 txn
579 ),
580 proposed =
581 payload.intent && typeof payload.intent === 'object'
582 ? payload.intent
583 : null;
584 if (!proposed?.intentDigest)
585 throw new Error('Commit intent digest is required');
586 assertExpectedReview(payload.expectedReview, ws, proposed);
587 if (ws.currentIntentId) {
588 const existing = await this.#getExpiring(
589 `intent:${ws.currentIntentId}`,
590 now,
591 txn
592 );
593 if (existing?.intentDigest === proposed.intentDigest) return existing;
594 }
595 const id = randomHandle(8),
596 created = {
597 ...proposed,
598 id,
599 workspaceId: ws.id,
600 state: 'READY',
601 candidateCommitSha: null,
602 commitSha: null,
603 branch: null,
604 createdAt: now,
605 updatedAt: now,
606 expiresAt: ws.expiresAt
607 };
608 await txn.put(`intent:${id}`, created);
609 await txn.put(`ws:${ws.id}`, {
610 ...ws,
611 currentIntentId: id,
612 state: 'READY',
613 updatedAt: now
614 });
615 return created;
616 });
617 await this.#schedule(intent.expiresAt);
618 return intent;
619 }
620 async #beginCommit(payload, now) {
621 const key = `intent:${String(payload.intentId || '')}`;
622 return this.state.storage.transaction(async (txn) => {
623 const intent = await txn.get(key);
624 if (!intent || expired(intent, now))
625 throw new Error('Commit intent not found or expired');
626 if (intent.state === 'COMMITTED')
627 return { disposition: 'committed', intent };
628 if (intent.state === 'COMMITTING')
629 return { disposition: 'resume', intent };
630 if (intent.state !== 'READY')
631 throw new Error(`Commit intent is ${intent.state || 'invalid'}`);
632 const updated = { ...intent, state: 'COMMITTING', updatedAt: now };
633 await txn.put(key, updated);
634 return { disposition: 'start', intent: updated };
635 });
636 }
637 async #setCandidate(payload, now) {
638 const key = `intent:${String(payload.intentId || '')}`;
639 return this.state.storage.transaction(async (txn) => {
640 const intent = await txn.get(key);
641 if (!intent || expired(intent, now))
642 throw new Error('Commit intent not found or expired');
643 if (intent.state === 'COMMITTED') return intent;
644 if (intent.state !== 'COMMITTING')
645 throw new Error('Commit intent is not committing');
646 const updated = {
647 ...intent,
648 candidateCommitSha: String(payload.commitSha || ''),
649 updatedAt: now
650 };
651 await txn.put(key, updated);
652 return updated;
653 });
654 }
655 async #completeCommit(payload, now) {
656 const key = `intent:${String(payload.intentId || '')}`,
657 retainedUntil = now + COMMITTED_RETENTION_MS;
658 const completed = await this.state.storage.transaction(async (txn) => {
659 const intent = await txn.get(key);
660 if (!intent) throw new Error('Commit intent not found');
661 if (intent.state === 'COMMITTED') return intent;
662 if (intent.state !== 'COMMITTING')
663 throw new Error('Commit intent is not committing');
664 const updated = {
665 ...intent,
666 state: 'COMMITTED',
667 commitSha: String(payload.commitSha || ''),
668 branch: String(payload.branch || ''),
669 updatedAt: now,
670 expiresAt: retainedUntil
671 };
672 await txn.put(key, updated);
673 const wk = `ws:${intent.workspaceId}`,
674 ws = await txn.get(wk);
675 if (ws)
676 await txn.put(wk, {
677 ...ws,
678 state: 'COMMITTED',
679 currentIntentId: intent.id,
680 commitSha: updated.commitSha,
681 branch: updated.branch,
682 updatedAt: now,
683 expiresAt: retainedUntil
684 });
685 return updated;
686 });
687 await this.#schedule(retainedUntil);
688 return completed;
689 }
690 async #markStale(payload, now) {
691 const key = `intent:${String(payload.intentId || '')}`;
692 return this.state.storage.transaction(async (txn) => {
693 const intent = await txn.get(key);
694 if (!intent) throw new Error('Commit intent not found');
695 if (intent.state === 'COMMITTED') return intent;
696 const updated = {
697 ...intent,
698 state: 'STALE',
699 staleReason: String(payload.reason || 'stale'),
700 updatedAt: now
701 };
702 await txn.put(key, updated);
703 return updated;
704 });
705 }
706 async #cancelWorkspace(payload) {
707 const id = String(payload.workspaceId || '');
708 if (!id) throw new Error('Workspace ID is required');
709 await this.state.storage.transaction(async (txn) => {
710 await txn.delete(`ws:${id}`);
711 const p = await txn.get('pending');
712 if (p?.workspaceId === id) await txn.delete('pending');
713 });
714 return { cancelled: true };
715 }
716 async alarm() {
717 const now = Date.now(),
718 entries = await this.state.storage.list();
719 let next = Infinity;
720 for (const [key, value] of entries) {
721 if (key === '__next_alarm') continue;
722 const expiry = Number(value?.expiresAt);
723 if (!Number.isFinite(expiry)) continue;
724 if (expiry <= now) await this.state.storage.delete(key);
725 else next = Math.min(next, expiry);
726 }
727 await this.state.storage.delete('__next_alarm');
728 if (Number.isFinite(next)) {
729 await this.state.storage.put('__next_alarm', next);
730 await this.state.storage.setAlarm(next);
731 }
732 }
733 }