Personal Telegram developer console for GitHub
feat(cp2): complete multi-file repository workspace
* feat(cp2): sync src/core/workspace-store.js * feat(cp2): sync src/durable/workspace-store.js * feat(cp2): sync src/plugins/github/workspace-commit.js * feat(cp2): sync test/workspace-multifile.test.js * test(cp2): add test/workspace-multifile-commit.test.js
davoodmehraban89 committed
Oct 5, 2026 at 05:54 UTC
e125190b9abd42abb0b72074188b929b53e8d07a
5 files changed
+134
-631
src/core/workspace-store.js
+22
-75
@@ -11,11 +11,7 @@ export class DurableWorkspaceStoreClient {
11
}
12
13
isConfigured() {
14
- return Boolean(
15
- this.namespace &&
16
- typeof this.namespace.idFromName === 'function' &&
17
- typeof this.namespace.get === 'function'
18
- );
14
+ return Boolean(this.namespace && typeof this.namespace.idFromName === 'function' && typeof this.namespace.get === 'function');
15
}
16
17
async #call(ownerId, operation, payload = {}) {
@@ -24,79 +20,30 @@ export class DurableWorkspaceStoreClient {
20
if (!owner) throw new Error('Workspace owner is required');
21
const id = this.namespace.idFromName(owner);
22
const stub = this.namespace.get(id);
27
- const response = await stub.fetch(jsonRequest(`https://workspace-store/${operation}`, {
28
- ...payload,
29
- now: Number(this.now())
30
- }));
23
+ const response = await stub.fetch(jsonRequest(`https://workspace-store/${operation}`, { ...payload, now: Number(this.now()) }));
24
let body = null;
25
try { body = await response.json(); } catch { body = null; }
33
- if (!response.ok) {
34
- throw new Error(body?.error || `Durable workspace store failed (${response.status})`);
35
- }
26
+ if (!response.ok) throw new Error(body?.error || `Durable workspace store failed (${response.status})`);
27
return body?.result ?? null;
28
}
29
39
- createNavigationRefs({ ownerId, refs, ttlMs = 900_000 } = {}) {
40
- return this.#call(ownerId, 'refs/create', { refs, ttlMs });
41
- }
42
-
43
- resolveNavigationRef({ ownerId, refId } = {}) {
44
- return this.#call(ownerId, 'refs/get', { refId });
45
- }
46
-
47
- createWorkspace({ ownerId, ...workspace } = {}) {
48
- return this.#call(ownerId, 'workspace/create', workspace);
49
- }
50
-
51
- getWorkspace({ ownerId, workspaceId } = {}) {
52
- return this.#call(ownerId, 'workspace/get', { workspaceId });
53
- }
54
-
55
- updateDraft({ ownerId, workspaceId, text, digest } = {}) {
56
- return this.#call(ownerId, 'workspace/draft', { workspaceId, text, digest });
57
- }
58
-
59
- setPendingInput({ ownerId, workspaceId, mode } = {}) {
60
- return this.#call(ownerId, 'pending/set', { workspaceId, mode });
61
- }
62
-
63
- getPendingInput({ ownerId } = {}) {
64
- return this.#call(ownerId, 'pending/get');
65
- }
66
-
67
- consumePendingInput({ ownerId, workspaceId, mode } = {}) {
68
- return this.#call(ownerId, 'pending/consume', { workspaceId, mode });
69
- }
70
-
71
- setCommitMessage({ ownerId, workspaceId, message, digest } = {}) {
72
- return this.#call(ownerId, 'workspace/message', { workspaceId, message, digest });
73
- }
74
-
75
- sealIntent({ ownerId, workspaceId, intent } = {}) {
76
- return this.#call(ownerId, 'intent/seal', { workspaceId, intent });
77
- }
78
-
79
- getIntent({ ownerId, intentId } = {}) {
80
- return this.#call(ownerId, 'intent/get', { intentId });
81
- }
82
-
83
- beginCommit({ ownerId, intentId } = {}) {
84
- return this.#call(ownerId, 'intent/begin', { intentId });
85
- }
86
-
87
- setCandidateCommit({ ownerId, intentId, commitSha } = {}) {
88
- return this.#call(ownerId, 'intent/candidate', { intentId, commitSha });
89
- }
90
-
91
- completeCommit({ ownerId, intentId, commitSha, branch } = {}) {
92
- return this.#call(ownerId, 'intent/complete', { intentId, commitSha, branch });
93
- }
94
-
95
- markStale({ ownerId, intentId, reason } = {}) {
96
- return this.#call(ownerId, 'intent/stale', { intentId, reason });
97
- }
98
-
99
- cancelWorkspace({ ownerId, workspaceId } = {}) {
100
- return this.#call(ownerId, 'workspace/cancel', { workspaceId });
101
- }
30
+ createNavigationRefs({ ownerId, refs, ttlMs = 900_000 } = {}) { return this.#call(ownerId, 'refs/create', { refs, ttlMs }); }
31
+ resolveNavigationRef({ ownerId, refId } = {}) { return this.#call(ownerId, 'refs/get', { refId }); }
32
+ createWorkspace({ ownerId, ...workspace } = {}) { return this.#call(ownerId, 'workspace/create', workspace); }
33
+ getWorkspace({ ownerId, workspaceId } = {}) { return this.#call(ownerId, 'workspace/get', { workspaceId }); }
34
+ updateDraft({ ownerId, workspaceId, text, digest } = {}) { return this.#call(ownerId, 'workspace/draft', { workspaceId, text, digest }); }
35
+ upsertWorkspaceFile({ ownerId, workspaceId, file } = {}) { return this.#call(ownerId, 'workspace/file/upsert', { workspaceId, file }); }
36
+ updateWorkspaceFileDraft({ ownerId, workspaceId, path, text, digest } = {}) { return this.#call(ownerId, 'workspace/file/draft', { workspaceId, path, text, digest }); }
37
+ removeWorkspaceFile({ ownerId, workspaceId, path } = {}) { return this.#call(ownerId, 'workspace/file/remove', { workspaceId, path }); }
38
+ setPendingInput({ ownerId, workspaceId, mode } = {}) { return this.#call(ownerId, 'pending/set', { workspaceId, mode }); }
39
+ getPendingInput({ ownerId } = {}) { return this.#call(ownerId, 'pending/get'); }
40
+ consumePendingInput({ ownerId, workspaceId, mode } = {}) { return this.#call(ownerId, 'pending/consume', { workspaceId, mode }); }
41
+ setCommitMessage({ ownerId, workspaceId, message, digest } = {}) { return this.#call(ownerId, 'workspace/message', { workspaceId, message, digest }); }
42
+ sealIntent({ ownerId, workspaceId, intent } = {}) { return this.#call(ownerId, 'intent/seal', { workspaceId, intent }); }
43
+ getIntent({ ownerId, intentId } = {}) { return this.#call(ownerId, 'intent/get', { intentId }); }
44
+ beginCommit({ ownerId, intentId } = {}) { return this.#call(ownerId, 'intent/begin', { intentId }); }
45
+ setCandidateCommit({ ownerId, intentId, commitSha } = {}) { return this.#call(ownerId, 'intent/candidate', { intentId, commitSha }); }
46
+ completeCommit({ ownerId, intentId, commitSha, branch } = {}) { return this.#call(ownerId, 'intent/complete', { intentId, commitSha, branch }); }
47
+ markStale({ ownerId, intentId, reason } = {}) { return this.#call(ownerId, 'intent/stale', { intentId, reason }); }
48
+ cancelWorkspace({ ownerId, workspaceId } = {}) { return this.#call(ownerId, 'workspace/cancel', { workspaceId }); }
49
}
src/durable/workspace-store.js
+42
-351
@@ -1,352 +1,43 @@
1
-const json = (payload, status = 200) => Response.json(payload, { status });
2
-const HANDLE_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
3
-const WORKSPACE_TTL_MS = 30 * 60_000;
4
-const REF_TTL_MS = 15 * 60_000;
5
-const COMMITTED_RETENTION_MS = 24 * 60 * 60_000;
6
-
7
-function randomHandle(length) {
8
- const bytes = new Uint8Array(length);
9
- crypto.getRandomValues(bytes);
10
- let out = '';
11
- for (const byte of bytes) out += HANDLE_ALPHABET[byte & 63];
12
- return out;
13
-}
14
-
15
-function finiteNow(value) {
16
- const parsed = Number(value);
17
- return Number.isFinite(parsed) ? parsed : Date.now();
18
-}
19
-
20
-function positiveTtl(value, fallback) {
21
- const parsed = Number(value);
22
- return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
23
-}
24
-
25
-function expired(record, now) {
26
- return Boolean(record && Number.isFinite(Number(record.expiresAt)) && Number(record.expiresAt) < now);
1
+const json=(payload,status=200)=>Response.json(payload,{status});
2
+const HANDLE_ALPHABET='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-';
3
+const WORKSPACE_TTL_MS=30*60_000, REF_TTL_MS=15*60_000, COMMITTED_RETENTION_MS=24*60*60_000;
4
+const MAX_WORKSPACE_BYTES=262144;
5
+function randomHandle(length){const bytes=new Uint8Array(length);crypto.getRandomValues(bytes);let out='';for(const byte of bytes)out+=HANDLE_ALPHABET[byte&63];return out}
6
+function finiteNow(v){const n=Number(v);return Number.isFinite(n)?n:Date.now()}
7
+function positiveTtl(v,f){const n=Number(v);return Number.isFinite(n)&&n>0?n:f}
8
+function expired(r,now){return Boolean(r&&Number.isFinite(Number(r.expiresAt))&&Number(r.expiresAt)<now)}
9
+function normalizePath(value){const path=String(value||'').replace(/\\/g,'/').replace(/^\.\//,'');if(!path||path.startsWith('/')||path.split('/').some(p=>!p||p==='.'||p==='..'))throw new Error('Workspace file path is invalid');return path}
10
+function legacyFile(payload){return {path:normalizePath(payload.path),blobSha:String(payload.blobSha||''),originalText:String(payload.originalText??''),originalDigest:String(payload.originalDigest||''),draftText:String(payload.originalText??''),draftDigest:String(payload.originalDigest||'')}}
11
+function migrate(ws){if(!ws)return ws;if(Array.isArray(ws.files))return ws;return {...ws,schemaVersion:2,files:[{path:String(ws.path||''),blobSha:String(ws.blobSha||''),originalText:String(ws.originalText??''),originalDigest:String(ws.originalDigest||''),draftText:String(ws.draftText??ws.originalText??''),draftDigest:String(ws.draftDigest||ws.originalDigest||'')}]} }
12
+function bytes(files){return files.reduce((n,f)=>n+new TextEncoder().encode(String(f.originalText??'')).length+new TextEncoder().encode(String(f.draftText??'')).length,0)}
13
+function validateFiles(files){if(!Array.isArray(files)||!files.length)throw new Error('Workspace must contain at least one file');const seen=new Set();for(const f of files){const p=normalizePath(f.path);if(seen.has(p))throw new Error('Workspace file path already exists');seen.add(p)}if(bytes(files)>MAX_WORKSPACE_BYTES)throw new Error('Workspace aggregate size is too large')}
14
+
15
+export class WorkspaceStore{
16
+ constructor(state){this.state=state}
17
+ async fetch(request){const url=new URL(request.url);if(request.method!=='POST')return new Response('Not Found',{status:404});let payload;try{payload=await request.json()}catch{return json({error:'Invalid workspace payload'},400)}const now=finiteNow(payload?.now);try{switch(url.pathname){
18
+ case'/refs/create':return json({result:await this.#createRefs(payload,now)});case'/refs/get':return json({result:await this.#getExpiring(`ref:${String(payload.refId||'')}`,now)});
19
+ case'/workspace/create':return json({result:await this.#createWorkspace(payload,now)});case'/workspace/get':return json({result:migrate(await this.#getExpiring(`ws:${String(payload.workspaceId||'')}`,now))});case'/workspace/draft':return json({result:await this.#updateDraft(payload,now)});
20
+ case'/workspace/file/upsert':return json({result:await this.#upsertFile(payload,now)});case'/workspace/file/draft':return json({result:await this.#updateFileDraft(payload,now)});case'/workspace/file/remove':return json({result:await this.#removeFile(payload,now)});
21
+ case'/workspace/message':return json({result:await this.#setCommitMessage(payload,now)});case'/workspace/cancel':return json({result:await this.#cancelWorkspace(payload)});case'/pending/set':return json({result:await this.#setPending(payload,now)});case'/pending/get':return json({result:await this.#getPending(now)});case'/pending/consume':return json({result:await this.#consumePending(payload,now)});case'/intent/seal':return json({result:await this.#sealIntent(payload,now)});case'/intent/get':return json({result:await this.#getExpiring(`intent:${String(payload.intentId||'')}`,now)});case'/intent/begin':return json({result:await this.#beginCommit(payload,now)});case'/intent/candidate':return json({result:await this.#setCandidate(payload,now)});case'/intent/complete':return json({result:await this.#completeCommit(payload,now)});case'/intent/stale':return json({result:await this.#markStale(payload,now)});default:return new Response('Not Found',{status:404})}}catch(error){return json({error:String(error?.message||'Workspace store operation failed')},400)}}
22
+ async #schedule(expiresAt){const expiry=Number(expiresAt);if(!Number.isFinite(expiry))return;const current=Number(await this.state.storage.get('__next_alarm'));if(!Number.isFinite(current)||expiry<current){await this.state.storage.put('__next_alarm',expiry);await this.state.storage.setAlarm(expiry)}}
23
+ async #getExpiring(key,now){if(!key||key.endsWith(':'))return null;const record=await this.state.storage.get(key);if(!record)return null;if(expired(record,now)){await this.state.storage.delete(key);return null}return record}
24
+ async #createRefs(payload,now){if(!Array.isArray(payload.refs))throw new Error('Navigation refs are required');const expiresAt=now+positiveTtl(payload.ttlMs,REF_TTL_MS),output=[];for(const source of payload.refs){const refId=randomHandle(10),record={repoId:source?.repoId,path:String(source?.path||''),type:source?.type==='dir'?'dir':'file',sha:String(source?.sha||''),expiresAt};await this.state.storage.put(`ref:${refId}`,record);output.push({refId})}await this.#schedule(expiresAt);return output}
25
+ async #createWorkspace(payload,now){const id=randomHandle(10),expiresAt=Number.isFinite(Number(payload.expiresAt))?Number(payload.expiresAt):now+WORKSPACE_TTL_MS;if(expiresAt<=now)throw new Error('Workspace expiry must be in the future');const first=legacyFile(payload);validateFiles([first]);const workspace={id,schemaVersion:2,repoId:payload.repoId,repoFullName:String(payload.repoFullName||''),baseBranch:String(payload.baseBranch||''),baseHeadSha:String(payload.baseHeadSha||''),baseTreeSha:String(payload.baseTreeSha||''),path:first.path,blobSha:first.blobSha,originalText:first.originalText,originalDigest:first.originalDigest,draftText:first.draftText,draftDigest:first.draftDigest,files:[first],commitMessage:'',commitMessageDigest:'',currentIntentId:null,state:'DRAFT',createdAt:now,updatedAt:now,expiresAt};await this.state.storage.put(`ws:${id}`,workspace);await this.#schedule(expiresAt);return workspace}
26
+ async #requireWorkspace(id,now){const ws=migrate(await this.#getExpiring(`ws:${String(id||'')}`,now));if(!ws)throw new Error('Workspace not found or expired');return ws}
27
+ async #saveMaterial(ws,files,now){validateFiles(files);const primary=files[0];const updated={...ws,schemaVersion:2,files,path:primary.path,blobSha:primary.blobSha,originalText:primary.originalText,originalDigest:primary.originalDigest,draftText:primary.draftText,draftDigest:primary.draftDigest,currentIntentId:null,state:'DRAFT',updatedAt:now};await this.state.storage.put(`ws:${ws.id}`,updated);return updated}
28
+ async #upsertFile(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),source=payload.file||{},path=normalizePath(source.path);if(ws.files.some(f=>normalizePath(f.path)===path))throw new Error('Workspace file path already exists');const file={path,blobSha:String(source.blobSha||''),originalText:String(source.originalText??''),originalDigest:String(source.originalDigest||''),draftText:String(source.draftText??source.originalText??''),draftDigest:String(source.draftDigest||source.originalDigest||'')};return this.#saveMaterial(ws,[...ws.files,file],now)}
29
+ async #updateFileDraft(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),path=normalizePath(payload.path),digest=String(payload.digest||'');if(!digest)throw new Error('Draft digest is required');let found=false;const files=ws.files.map(f=>normalizePath(f.path)===path?(found=true,{...f,draftText:String(payload.text??''),draftDigest:digest}):f);if(!found)throw new Error('Workspace file not found');if(ws.files.find(f=>normalizePath(f.path)===path)?.draftDigest===digest)return ws;return this.#saveMaterial(ws,files,now)}
30
+ async #removeFile(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),path=normalizePath(payload.path),files=ws.files.filter(f=>normalizePath(f.path)!==path);if(files.length===ws.files.length)throw new Error('Workspace file not found');return this.#saveMaterial(ws,files,now)}
31
+ async #updateDraft(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),digest=String(payload.digest||'');if(!digest)throw new Error('Draft digest is required');if(digest===ws.draftDigest)return ws;const files=ws.files.map((f,i)=>i?f:{...f,draftText:String(payload.text??''),draftDigest:digest});return this.#saveMaterial(ws,files,now)}
32
+ async #setCommitMessage(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),digest=String(payload.digest||'');if(!digest)throw new Error('Commit message digest is required');const changed=digest!==ws.commitMessageDigest,updated={...ws,commitMessage:String(payload.message||''),commitMessageDigest:digest,updatedAt:now,...(changed?{currentIntentId:null,state:'DRAFT'}:{})};await this.state.storage.put(`ws:${ws.id}`,updated);return updated}
33
+ async #setPending(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),mode=String(payload.mode||'');if(!['draft','draft_file','commit_message'].includes(mode))throw new Error('Pending input mode is invalid');const pending={workspaceId:ws.id,mode,expiresAt:ws.expiresAt};await this.state.storage.put('pending',pending);await this.#schedule(pending.expiresAt);return pending}
34
+ async #getPending(now){const p=await this.state.storage.get('pending');if(!p)return null;if(expired(p,now)){await this.state.storage.delete('pending');return null}const ws=await this.#getExpiring(`ws:${p.workspaceId}`,now);if(!ws){await this.state.storage.delete('pending');return null}return{workspaceId:p.workspaceId,mode:p.mode}}
35
+ async #consumePending(payload,now){return this.state.storage.transaction(async txn=>{const p=await txn.get('pending');if(!p||expired(p,now)){if(p)await txn.delete('pending');return false}if(p.workspaceId!==String(payload.workspaceId||'')||p.mode!==String(payload.mode||''))return false;await txn.delete('pending');return true})}
36
+ async #sealIntent(payload,now){const ws=await this.#requireWorkspace(payload.workspaceId,now),proposed=payload.intent&&typeof payload.intent==='object'?payload.intent:null;if(!proposed?.intentDigest)throw new Error('Commit intent digest is required');if(ws.currentIntentId){const existing=await this.#getExpiring(`intent:${ws.currentIntentId}`,now);if(existing?.intentDigest===proposed.intentDigest)return existing}const id=randomHandle(8),intent={...proposed,id,workspaceId:ws.id,state:'READY',candidateCommitSha:null,commitSha:null,branch:null,createdAt:now,updatedAt:now,expiresAt:ws.expiresAt};await this.state.storage.put(`intent:${id}`,intent);await this.state.storage.put(`ws:${ws.id}`,{...ws,currentIntentId:id,state:'READY',updatedAt:now});await this.#schedule(intent.expiresAt);return intent}
37
+ async #beginCommit(payload,now){const key=`intent:${String(payload.intentId||'')}`;return this.state.storage.transaction(async txn=>{const intent=await txn.get(key);if(!intent||expired(intent,now))throw new Error('Commit intent not found or expired');if(intent.state==='COMMITTED')return{disposition:'committed',intent};if(intent.state==='COMMITTING')return{disposition:'resume',intent};if(intent.state!=='READY')throw new Error(`Commit intent is ${intent.state||'invalid'}`);const updated={...intent,state:'COMMITTING',updatedAt:now};await txn.put(key,updated);return{disposition:'start',intent:updated}})}
38
+ async #setCandidate(payload,now){const key=`intent:${String(payload.intentId||'')}`;return this.state.storage.transaction(async txn=>{const intent=await txn.get(key);if(!intent||expired(intent,now))throw new Error('Commit intent not found or expired');if(intent.state==='COMMITTED')return intent;if(intent.state!=='COMMITTING')throw new Error('Commit intent is not committing');const updated={...intent,candidateCommitSha:String(payload.commitSha||''),updatedAt:now};await txn.put(key,updated);return updated})}
39
+ async #completeCommit(payload,now){const key=`intent:${String(payload.intentId||'')}`,retainedUntil=now+COMMITTED_RETENTION_MS;const completed=await this.state.storage.transaction(async txn=>{const intent=await txn.get(key);if(!intent)throw new Error('Commit intent not found');if(intent.state==='COMMITTED')return intent;if(intent.state!=='COMMITTING')throw new Error('Commit intent is not committing');const updated={...intent,state:'COMMITTED',commitSha:String(payload.commitSha||''),branch:String(payload.branch||''),updatedAt:now,expiresAt:retainedUntil};await txn.put(key,updated);const wk=`ws:${intent.workspaceId}`,ws=await txn.get(wk);if(ws)await txn.put(wk,{...ws,state:'COMMITTED',currentIntentId:intent.id,commitSha:updated.commitSha,branch:updated.branch,updatedAt:now,expiresAt:retainedUntil});return updated});await this.#schedule(retainedUntil);return completed}
40
+ async #markStale(payload,now){const key=`intent:${String(payload.intentId||'')}`;return this.state.storage.transaction(async txn=>{const intent=await txn.get(key);if(!intent)throw new Error('Commit intent not found');if(intent.state==='COMMITTED')return intent;const updated={...intent,state:'STALE',staleReason:String(payload.reason||'stale'),updatedAt:now};await txn.put(key,updated);return updated})}
41
+ async #cancelWorkspace(payload){const id=String(payload.workspaceId||'');if(!id)throw new Error('Workspace ID is required');await this.state.storage.transaction(async txn=>{await txn.delete(`ws:${id}`);const p=await txn.get('pending');if(p?.workspaceId===id)await txn.delete('pending')});return{cancelled:true}}
42
+ async alarm(){const now=Date.now(),entries=await this.state.storage.list();let next=Infinity;for(const[key,value]of entries){if(key==='__next_alarm')continue;const expiry=Number(value?.expiresAt);if(!Number.isFinite(expiry))continue;if(expiry<=now)await this.state.storage.delete(key);else next=Math.min(next,expiry)}await this.state.storage.delete('__next_alarm');if(Number.isFinite(next)){await this.state.storage.put('__next_alarm',next);await this.state.storage.setAlarm(next)}}
43
}
28
-
29
-export class WorkspaceStore {
30
- constructor(state) {
31
- this.state = state;
32
- }
33
-
34
- async fetch(request) {
35
- const url = new URL(request.url);
36
- if (request.method !== 'POST') return new Response('Not Found', { status: 404 });
37
-
38
- let payload;
39
- try { payload = await request.json(); } catch { return json({ error: 'Invalid workspace payload' }, 400); }
40
- const now = finiteNow(payload?.now);
41
-
42
- try {
43
- switch (url.pathname) {
44
- case '/refs/create': return json({ result: await this.#createRefs(payload, now) });
45
- case '/refs/get': return json({ result: await this.#getExpiring(`ref:${String(payload.refId || '')}`, now) });
46
- case '/workspace/create': return json({ result: await this.#createWorkspace(payload, now) });
47
- case '/workspace/get': return json({ result: await this.#getExpiring(`ws:${String(payload.workspaceId || '')}`, now) });
48
- case '/workspace/draft': return json({ result: await this.#updateDraft(payload, now) });
49
- case '/workspace/message': return json({ result: await this.#setCommitMessage(payload, now) });
50
- case '/workspace/cancel': return json({ result: await this.#cancelWorkspace(payload) });
51
- case '/pending/set': return json({ result: await this.#setPending(payload, now) });
52
- case '/pending/get': return json({ result: await this.#getPending(now) });
53
- case '/pending/consume': return json({ result: await this.#consumePending(payload, now) });
54
- case '/intent/seal': return json({ result: await this.#sealIntent(payload, now) });
55
- case '/intent/get': return json({ result: await this.#getExpiring(`intent:${String(payload.intentId || '')}`, now) });
56
- case '/intent/begin': return json({ result: await this.#beginCommit(payload, now) });
57
- case '/intent/candidate': return json({ result: await this.#setCandidate(payload, now) });
58
- case '/intent/complete': return json({ result: await this.#completeCommit(payload, now) });
59
- case '/intent/stale': return json({ result: await this.#markStale(payload, now) });
60
- default: return new Response('Not Found', { status: 404 });
61
- }
62
- } catch (error) {
63
- return json({ error: String(error?.message || 'Workspace store operation failed') }, 400);
64
- }
65
- }
66
-
67
- async #schedule(expiresAt) {
68
- const expiry = Number(expiresAt);
69
- if (!Number.isFinite(expiry)) return;
70
- const current = Number(await this.state.storage.get('__next_alarm'));
71
- if (!Number.isFinite(current) || expiry < current) {
72
- await this.state.storage.put('__next_alarm', expiry);
73
- await this.state.storage.setAlarm(expiry);
74
- }
75
- }
76
-
77
- async #getExpiring(key, now) {
78
- if (!key || key.endsWith(':')) return null;
79
- const record = await this.state.storage.get(key);
80
- if (!record) return null;
81
- if (expired(record, now)) {
82
- await this.state.storage.delete(key);
83
- return null;
84
- }
85
- return record;
86
- }
87
-
88
- async #createRefs(payload, now) {
89
- if (!Array.isArray(payload.refs)) throw new Error('Navigation refs are required');
90
- const ttlMs = positiveTtl(payload.ttlMs, REF_TTL_MS);
91
- const expiresAt = now + ttlMs;
92
- const output = [];
93
- for (const source of payload.refs) {
94
- const refId = randomHandle(10);
95
- const record = {
96
- repoId: source?.repoId,
97
- path: String(source?.path || ''),
98
- type: source?.type === 'dir' ? 'dir' : 'file',
99
- sha: String(source?.sha || ''),
100
- expiresAt
101
- };
102
- await this.state.storage.put(`ref:${refId}`, record);
103
- output.push({ refId });
104
- }
105
- await this.#schedule(expiresAt);
106
- return output;
107
- }
108
-
109
- async #createWorkspace(payload, now) {
110
- const id = randomHandle(10);
111
- const expiresAt = Number.isFinite(Number(payload.expiresAt)) ? Number(payload.expiresAt) : now + WORKSPACE_TTL_MS;
112
- if (expiresAt <= now) throw new Error('Workspace expiry must be in the future');
113
- const workspace = {
114
- id,
115
- repoId: payload.repoId,
116
- repoFullName: String(payload.repoFullName || ''),
117
- baseBranch: String(payload.baseBranch || ''),
118
- baseHeadSha: String(payload.baseHeadSha || ''),
119
- baseTreeSha: String(payload.baseTreeSha || ''),
120
- path: String(payload.path || ''),
121
- blobSha: String(payload.blobSha || ''),
122
- originalText: String(payload.originalText ?? ''),
123
- originalDigest: String(payload.originalDigest || ''),
124
- draftText: String(payload.originalText ?? ''),
125
- draftDigest: String(payload.originalDigest || ''),
126
- commitMessage: '',
127
- commitMessageDigest: '',
128
- currentIntentId: null,
129
- state: 'DRAFT',
130
- createdAt: now,
131
- updatedAt: now,
132
- expiresAt
133
- };
134
- await this.state.storage.put(`ws:${id}`, workspace);
135
- await this.#schedule(expiresAt);
136
- return workspace;
137
- }
138
-
139
- async #requireWorkspace(workspaceId, now) {
140
- const workspace = await this.#getExpiring(`ws:${String(workspaceId || '')}`, now);
141
- if (!workspace) throw new Error('Workspace not found or expired');
142
- return workspace;
143
- }
144
-
145
- async #updateDraft(payload, now) {
146
- const workspace = await this.#requireWorkspace(payload.workspaceId, now);
147
- const digest = String(payload.digest || '');
148
- if (!digest) throw new Error('Draft digest is required');
149
- const changed = digest !== workspace.draftDigest;
150
- const updated = {
151
- ...workspace,
152
- draftText: String(payload.text ?? ''),
153
- draftDigest: digest,
154
- updatedAt: now,
155
- ...(changed ? { currentIntentId: null, state: 'DRAFT' } : {})
156
- };
157
- await this.state.storage.put(`ws:${workspace.id}`, updated);
158
- return updated;
159
- }
160
-
161
- async #setCommitMessage(payload, now) {
162
- const workspace = await this.#requireWorkspace(payload.workspaceId, now);
163
- const digest = String(payload.digest || '');
164
- if (!digest) throw new Error('Commit message digest is required');
165
- const changed = digest !== workspace.commitMessageDigest;
166
- const updated = {
167
- ...workspace,
168
- commitMessage: String(payload.message || ''),
169
- commitMessageDigest: digest,
170
- updatedAt: now,
171
- ...(changed ? { currentIntentId: null, state: 'DRAFT' } : {})
172
- };
173
- await this.state.storage.put(`ws:${workspace.id}`, updated);
174
- return updated;
175
- }
176
-
177
- async #setPending(payload, now) {
178
- const workspace = await this.#requireWorkspace(payload.workspaceId, now);
179
- const mode = String(payload.mode || '');
180
- if (!['draft', 'draft_file', 'commit_message'].includes(mode)) throw new Error('Pending input mode is invalid');
181
- const pending = { workspaceId: workspace.id, mode, expiresAt: workspace.expiresAt };
182
- await this.state.storage.put('pending', pending);
183
- await this.#schedule(pending.expiresAt);
184
- return pending;
185
- }
186
-
187
- async #getPending(now) {
188
- const pending = await this.state.storage.get('pending');
189
- if (!pending) return null;
190
- if (expired(pending, now)) {
191
- await this.state.storage.delete('pending');
192
- return null;
193
- }
194
- const workspace = await this.#getExpiring(`ws:${pending.workspaceId}`, now);
195
- if (!workspace) {
196
- await this.state.storage.delete('pending');
197
- return null;
198
- }
199
- return { workspaceId: pending.workspaceId, mode: pending.mode };
200
- }
201
-
202
- async #consumePending(payload, now) {
203
- return this.state.storage.transaction(async txn => {
204
- const pending = await txn.get('pending');
205
- if (!pending || expired(pending, now)) {
206
- if (pending) await txn.delete('pending');
207
- return false;
208
- }
209
- if (pending.workspaceId !== String(payload.workspaceId || '') || pending.mode !== String(payload.mode || '')) return false;
210
- await txn.delete('pending');
211
- return true;
212
- });
213
- }
214
-
215
- async #sealIntent(payload, now) {
216
- const workspace = await this.#requireWorkspace(payload.workspaceId, now);
217
- const proposed = payload.intent && typeof payload.intent === 'object' ? payload.intent : null;
218
- if (!proposed?.intentDigest) throw new Error('Commit intent digest is required');
219
-
220
- if (workspace.currentIntentId) {
221
- const existing = await this.#getExpiring(`intent:${workspace.currentIntentId}`, now);
222
- if (existing?.intentDigest === proposed.intentDigest) return existing;
223
- }
224
-
225
- const id = randomHandle(8);
226
- const intent = {
227
- ...proposed,
228
- id,
229
- workspaceId: workspace.id,
230
- state: 'READY',
231
- candidateCommitSha: null,
232
- commitSha: null,
233
- branch: null,
234
- createdAt: now,
235
- updatedAt: now,
236
- expiresAt: workspace.expiresAt
237
- };
238
- await this.state.storage.put(`intent:${id}`, intent);
239
- await this.state.storage.put(`ws:${workspace.id}`, {
240
- ...workspace,
241
- currentIntentId: id,
242
- state: 'READY',
243
- updatedAt: now
244
- });
245
- await this.#schedule(intent.expiresAt);
246
- return intent;
247
- }
248
-
249
- async #beginCommit(payload, now) {
250
- const key = `intent:${String(payload.intentId || '')}`;
251
- return this.state.storage.transaction(async txn => {
252
- const intent = await txn.get(key);
253
- if (!intent || expired(intent, now)) throw new Error('Commit intent not found or expired');
254
- if (intent.state === 'COMMITTED') return { disposition: 'committed', intent };
255
- if (intent.state === 'COMMITTING') return { disposition: 'resume', intent };
256
- if (intent.state !== 'READY') throw new Error(`Commit intent is ${intent.state || 'invalid'}`);
257
- const updated = { ...intent, state: 'COMMITTING', updatedAt: now };
258
- await txn.put(key, updated);
259
- return { disposition: 'start', intent: updated };
260
- });
261
- }
262
-
263
- async #setCandidate(payload, now) {
264
- const key = `intent:${String(payload.intentId || '')}`;
265
- return this.state.storage.transaction(async txn => {
266
- const intent = await txn.get(key);
267
- if (!intent || expired(intent, now)) throw new Error('Commit intent not found or expired');
268
- if (intent.state === 'COMMITTED') return intent;
269
- if (intent.state !== 'COMMITTING') throw new Error('Commit intent is not committing');
270
- const updated = { ...intent, candidateCommitSha: String(payload.commitSha || ''), updatedAt: now };
271
- await txn.put(key, updated);
272
- return updated;
273
- });
274
- }
275
-
276
- async #completeCommit(payload, now) {
277
- const key = `intent:${String(payload.intentId || '')}`;
278
- const retainedUntil = now + COMMITTED_RETENTION_MS;
279
- const completed = await this.state.storage.transaction(async txn => {
280
- const intent = await txn.get(key);
281
- if (!intent) throw new Error('Commit intent not found');
282
- if (intent.state === 'COMMITTED') return intent;
283
- if (intent.state !== 'COMMITTING') throw new Error('Commit intent is not committing');
284
- const updated = {
285
- ...intent,
286
- state: 'COMMITTED',
287
- commitSha: String(payload.commitSha || ''),
288
- branch: String(payload.branch || ''),
289
- updatedAt: now,
290
- expiresAt: retainedUntil
291
- };
292
- await txn.put(key, updated);
293
- const workspaceKey = `ws:${intent.workspaceId}`;
294
- const workspace = await txn.get(workspaceKey);
295
- if (workspace) {
296
- await txn.put(workspaceKey, {
297
- ...workspace,
298
- state: 'COMMITTED',
299
- currentIntentId: intent.id,
300
- commitSha: updated.commitSha,
301
- branch: updated.branch,
302
- updatedAt: now,
303
- expiresAt: retainedUntil
304
- });
305
- }
306
- return updated;
307
- });
308
- await this.#schedule(retainedUntil);
309
- return completed;
310
- }
311
-
312
- async #markStale(payload, now) {
313
- const key = `intent:${String(payload.intentId || '')}`;
314
- return this.state.storage.transaction(async txn => {
315
- const intent = await txn.get(key);
316
- if (!intent) throw new Error('Commit intent not found');
317
- if (intent.state === 'COMMITTED') return intent;
318
- const updated = { ...intent, state: 'STALE', staleReason: String(payload.reason || 'stale'), updatedAt: now };
319
- await txn.put(key, updated);
320
- return updated;
321
- });
322
- }
323
-
324
- async #cancelWorkspace(payload) {
325
- const workspaceId = String(payload.workspaceId || '');
326
- if (!workspaceId) throw new Error('Workspace ID is required');
327
- await this.state.storage.transaction(async txn => {
328
- await txn.delete(`ws:${workspaceId}`);
329
- const pending = await txn.get('pending');
330
- if (pending?.workspaceId === workspaceId) await txn.delete('pending');
331
- });
332
- return { cancelled: true };
333
- }
334
-
335
- async alarm() {
336
- const now = Date.now();
337
- const entries = await this.state.storage.list();
338
- let next = Infinity;
339
- for (const [key, value] of entries) {
340
- if (key === '__next_alarm') continue;
341
- const expiry = Number(value?.expiresAt);
342
- if (!Number.isFinite(expiry)) continue;
343
- if (expiry <= now) await this.state.storage.delete(key);
344
- else next = Math.min(next, expiry);
345
- }
346
- await this.state.storage.delete('__next_alarm');
347
- if (Number.isFinite(next)) {
348
- await this.state.storage.put('__next_alarm', next);
349
- await this.state.storage.setAlarm(next);
350
- }
351
- }
352
-}
\ No newline at end of file
src/plugins/github/workspace-commit.js
+10
-156
@@ -1,156 +1,10 @@
1
-const INTENT_ID_PATTERN = /^[A-Za-z0-9_-]{8}$/;
2
-const FULL_SHA_PATTERN = /^[a-f0-9]{40}$/i;
3
-
4
-function assertOwner(ownerId) {
5
- const owner = String(ownerId ?? '');
6
- if (!owner) throw new Error('Workspace owner is required');
7
- return owner;
8
-}
9
-
10
-function assertRepoId(repoId) {
11
- const value = Number(repoId);
12
- if (!Number.isSafeInteger(value) || value < 1) throw new Error('Workspace repository ID is invalid');
13
- return value;
14
-}
15
-
16
-function assertIntentId(intentId) {
17
- const value = String(intentId || '');
18
- if (!INTENT_ID_PATTERN.test(value)) throw new Error('Workspace intent ID is invalid');
19
- return value;
20
-}
21
-
22
-function assertSha(value, label) {
23
- const sha = String(value || '');
24
- if (!FULL_SHA_PATTERN.test(sha)) throw new Error(`${label} SHA is invalid`);
25
- return sha;
26
-}
27
-
28
-function committedResult(intent, idempotent = true) {
29
- return {
30
- commitSha: assertSha(intent?.commitSha, 'Committed'),
31
- branch: String(intent?.branch || intent?.targetBranch || ''),
32
- idempotent
33
- };
34
-}
35
-
36
-function materialMismatch(intent, workspace, repoId, intentId) {
37
- return (
38
- Number(intent?.repoId) !== repoId ||
39
- Number(workspace?.repoId) !== repoId ||
40
- String(workspace?.id || '') !== String(intent?.workspaceId || '') ||
41
- String(workspace?.currentIntentId || '') !== intentId ||
42
- String(workspace?.baseBranch || '') !== String(intent?.baseBranch || '') ||
43
- String(workspace?.baseHeadSha || '') !== String(intent?.baseHeadSha || '') ||
44
- String(workspace?.baseTreeSha || '') !== String(intent?.baseTreeSha || '') ||
45
- String(workspace?.path || '') !== String(intent?.path || '') ||
46
- String(workspace?.blobSha || '') !== String(intent?.sourceBlobSha || '') ||
47
- String(workspace?.draftDigest || '') !== String(intent?.contentDigest || '') ||
48
- String(workspace?.commitMessageDigest || '') !== String(intent?.commitMessageDigest || '')
49
- );
50
-}
51
-
52
-async function markStaleThenThrow(workspaces, ownerId, intentId, reason) {
53
- try {
54
- await workspaces.markStale({ ownerId, intentId, reason });
55
- } catch {
56
- // The original safety failure remains authoritative.
57
- }
58
- throw new Error(reason);
59
-}
60
-
61
-async function reconcileCandidate({ github, workspaces, ownerId, repoId, intent, intentId }) {
62
- const candidate = assertSha(intent.candidateCommitSha, 'Candidate commit');
63
- const branch = String(intent.targetBranch || '');
64
- const existing = await github.getGitRef(repoId, branch, { allowMissing: true });
65
- if (existing?.sha === candidate) {
66
- await workspaces.completeCommit({ ownerId, intentId, commitSha: candidate, branch });
67
- return { commitSha: candidate, branch, idempotent: true };
68
- }
69
- if (existing) {
70
- throw new Error('Target branch exists at an unexpected commit');
71
- }
72
-
73
- const snapshot = await github.getBranchSnapshot(repoId, intent.baseBranch);
74
- if (snapshot.headSha !== intent.baseHeadSha) {
75
- return markStaleThenThrow(workspaces, ownerId, intentId, 'Base branch changed; commit intent is stale');
76
- }
77
-
78
- try {
79
- await github.createGitBranchRef(repoId, { branch, sha: candidate });
80
- } catch (error) {
81
- const observed = await github.getGitRef(repoId, branch, { allowMissing: true });
82
- if (observed?.sha !== candidate) {
83
- throw new Error(`Unable to reconcile candidate branch after provider error: ${error?.message || 'unknown error'}`);
84
- }
85
- }
86
- await workspaces.completeCommit({ ownerId, intentId, commitSha: candidate, branch });
87
- return { commitSha: candidate, branch, idempotent: true };
88
-}
89
-
90
-export async function commitWorkspaceIntent({ github, workspaces, ownerId, repoId, intentId } = {}) {
91
- if (!github) throw new Error('Workspace commit requires GitHub service');
92
- if (!workspaces) throw new Error('Workspace commit requires durable workspace store');
93
- const owner = assertOwner(ownerId);
94
- const repositoryId = assertRepoId(repoId);
95
- const id = assertIntentId(intentId);
96
-
97
- let intent = await workspaces.getIntent({ ownerId: owner, intentId: id });
98
- if (!intent) throw new Error('Commit intent not found or expired');
99
- if (Number(intent.repoId) !== repositoryId) throw new Error('Commit intent repository mismatch');
100
- if (intent.state === 'COMMITTED') return committedResult(intent, true);
101
-
102
- const workspace = await workspaces.getWorkspace({ ownerId: owner, workspaceId: intent.workspaceId });
103
- if (!workspace || materialMismatch(intent, workspace, repositoryId, id)) {
104
- return markStaleThenThrow(workspaces, owner, id, 'Workspace material changed; commit intent is stale');
105
- }
106
-
107
- const begun = await workspaces.beginCommit({ ownerId: owner, intentId: id });
108
- intent = begun?.intent;
109
- if (!intent) throw new Error('Commit intent could not begin');
110
- if (begun.disposition === 'committed' || intent.state === 'COMMITTED') return committedResult(intent, true);
111
-
112
- if (intent.candidateCommitSha) {
113
- return reconcileCandidate({ github, workspaces, ownerId: owner, repoId: repositoryId, intent, intentId: id });
114
- }
115
-
116
- const snapshot = await github.getBranchSnapshot(repositoryId, intent.baseBranch);
117
- if (snapshot.headSha !== intent.baseHeadSha) {
118
- return markStaleThenThrow(workspaces, owner, id, 'Base branch changed; commit intent is stale');
119
- }
120
-
121
- const existing = await github.getGitRef(repositoryId, intent.targetBranch, { allowMissing: true });
122
- if (existing) throw new Error('Target branch already exists unexpectedly');
123
-
124
- const blob = await github.createGitBlob(repositoryId, workspace.draftText);
125
- const tree = await github.createGitTree(repositoryId, {
126
- baseTreeSha: intent.baseTreeSha,
127
- entries: [{ path: intent.path, mode: '100644', type: 'blob', sha: blob.sha }]
128
- });
129
- const commit = await github.createGitCommit(repositoryId, {
130
- message: workspace.commitMessage,
131
- treeSha: tree.sha,
132
- parentSha: intent.baseHeadSha,
133
- timestamp: intent.commitTimestamp
134
- });
135
- const commitSha = assertSha(commit.sha, 'Candidate commit');
136
- await workspaces.setCandidateCommit({ ownerId: owner, intentId: id, commitSha });
137
-
138
- let idempotent = false;
139
- try {
140
- await github.createGitBranchRef(repositoryId, { branch: intent.targetBranch, sha: commitSha });
141
- } catch (error) {
142
- const observed = await github.getGitRef(repositoryId, intent.targetBranch, { allowMissing: true });
143
- if (observed?.sha !== commitSha) {
144
- throw new Error(`Unable to reconcile target branch after provider error: ${error?.message || 'unknown error'}`);
145
- }
146
- idempotent = true;
147
- }
148
-
149
- await workspaces.completeCommit({
150
- ownerId: owner,
151
- intentId: id,
152
- commitSha,
153
- branch: intent.targetBranch
154
- });
155
- return { commitSha, branch: intent.targetBranch, idempotent };
156
-}
1
+const INTENT_ID_PATTERN=/^[A-Za-z0-9_-]{8}$/;const FULL_SHA_PATTERN=/^[a-f0-9]{40}$/i;
2
+function assertOwner(v){const x=String(v??'');if(!x)throw new Error('Workspace owner is required');return x}function assertRepoId(v){const x=Number(v);if(!Number.isSafeInteger(x)||x<1)throw new Error('Workspace repository ID is invalid');return x}function assertIntentId(v){const x=String(v||'');if(!INTENT_ID_PATTERN.test(x))throw new Error('Workspace intent ID is invalid');return x}function assertSha(v,label){const x=String(v||'');if(!FULL_SHA_PATTERN.test(x))throw new Error(`${label} SHA is invalid`);return x}
3
+function committedResult(intent,idempotent=true){return{commitSha:assertSha(intent?.commitSha,'Committed'),branch:String(intent?.branch||intent?.targetBranch||''),idempotent}}
4
+function materialMismatch(intent,ws,repoId,intentId){if(Number(intent?.repoId)!==repoId||Number(ws?.repoId)!==repoId||String(ws?.id||'')!==String(intent?.workspaceId||'')||String(ws?.currentIntentId||'')!==intentId||String(ws?.baseBranch||'')!==String(intent?.baseBranch||'')||String(ws?.baseHeadSha||'')!==String(intent?.baseHeadSha||'')||String(ws?.baseTreeSha||'')!==String(intent?.baseTreeSha||'')||String(ws?.commitMessageDigest||'')!==String(intent?.commitMessageDigest||''))return true;
5
+ if(Array.isArray(intent?.files)){if(!Array.isArray(ws?.files)||intent.files.length!==ws.files.length)return true;return intent.files.some((f,i)=>String(f.path)!==String(ws.files[i]?.path)||String(f.sourceBlobSha)!==String(ws.files[i]?.blobSha)||String(f.contentDigest)!==String(ws.files[i]?.draftDigest))}
6
+ return String(ws?.path||'')!==String(intent?.path||'')||String(ws?.blobSha||'')!==String(intent?.sourceBlobSha||'')||String(ws?.draftDigest||'')!==String(intent?.contentDigest||'')}
7
+async function markStaleThenThrow(workspaces,ownerId,intentId,reason){try{await workspaces.markStale({ownerId,intentId,reason})}catch{}throw new Error(reason)}
8
+async function reconcileCandidate({github,workspaces,ownerId,repoId,intent,intentId}){const candidate=assertSha(intent.candidateCommitSha,'Candidate commit'),branch=String(intent.targetBranch||''),existing=await github.getGitRef(repoId,branch,{allowMissing:true});if(existing?.sha===candidate){await workspaces.completeCommit({ownerId,intentId,commitSha:candidate,branch});return{commitSha:candidate,branch,idempotent:true}}if(existing)throw new Error('Target branch exists at an unexpected commit');const snapshot=await github.getBranchSnapshot(repoId,intent.baseBranch);if(snapshot.headSha!==intent.baseHeadSha)return markStaleThenThrow(workspaces,ownerId,intentId,'Base branch changed; commit intent is stale');try{await github.createGitBranchRef(repoId,{branch,sha:candidate})}catch(error){const observed=await github.getGitRef(repoId,branch,{allowMissing:true});if(observed?.sha!==candidate)throw new Error(`Unable to reconcile candidate branch after provider error: ${error?.message||'unknown error'}`)}await workspaces.completeCommit({ownerId,intentId,commitSha:candidate,branch});return{commitSha:candidate,branch,idempotent:true}}
9
+export async function commitWorkspaceIntent({github,workspaces,ownerId,repoId,intentId}={}){if(!github)throw new Error('Workspace commit requires GitHub service');if(!workspaces)throw new Error('Workspace commit requires durable workspace store');const owner=assertOwner(ownerId),repositoryId=assertRepoId(repoId),id=assertIntentId(intentId);let intent=await workspaces.getIntent({ownerId:owner,intentId:id});if(!intent)throw new Error('Commit intent not found or expired');if(Number(intent.repoId)!==repositoryId)throw new Error('Commit intent repository mismatch');if(intent.state==='COMMITTED')return committedResult(intent,true);const workspace=await workspaces.getWorkspace({ownerId:owner,workspaceId:intent.workspaceId});if(!workspace||materialMismatch(intent,workspace,repositoryId,id))return markStaleThenThrow(workspaces,owner,id,'Workspace material changed; commit intent is stale');const begun=await workspaces.beginCommit({ownerId:owner,intentId:id});intent=begun?.intent;if(!intent)throw new Error('Commit intent could not begin');if(begun.disposition==='committed'||intent.state==='COMMITTED')return committedResult(intent,true);if(intent.candidateCommitSha)return reconcileCandidate({github,workspaces,ownerId:owner,repoId:repositoryId,intent,intentId:id});const snapshot=await github.getBranchSnapshot(repositoryId,intent.baseBranch);if(snapshot.headSha!==intent.baseHeadSha)return markStaleThenThrow(workspaces,owner,id,'Base branch changed; commit intent is stale');const existing=await github.getGitRef(repositoryId,intent.targetBranch,{allowMissing:true});if(existing)throw new Error('Target branch already exists unexpectedly');
10
+ const files=Array.isArray(intent.files)?intent.files.map((f,i)=>({intent:f,workspace:workspace.files[i]})):[{intent:{path:intent.path},workspace:{draftText:workspace.draftText}}];const entries=[];for(const item of files){const blob=await github.createGitBlob(repositoryId,item.workspace.draftText);entries.push({path:item.intent.path,mode:'100644',type:'blob',sha:blob.sha})}const tree=await github.createGitTree(repositoryId,{baseTreeSha:intent.baseTreeSha,entries});const commit=await github.createGitCommit(repositoryId,{message:workspace.commitMessage,treeSha:tree.sha,parentSha:intent.baseHeadSha,timestamp:intent.commitTimestamp});const commitSha=assertSha(commit.sha,'Candidate commit');await workspaces.setCandidateCommit({ownerId:owner,intentId:id,commitSha});let idempotent=false;try{await github.createGitBranchRef(repositoryId,{branch:intent.targetBranch,sha:commitSha})}catch(error){const observed=await github.getGitRef(repositoryId,intent.targetBranch,{allowMissing:true});if(observed?.sha!==commitSha)throw new Error(`Unable to reconcile target branch after provider error: ${error?.message||'unknown error'}`);idempotent=true}await workspaces.completeCommit({ownerId:owner,intentId:id,commitSha,branch:intent.targetBranch});return{commitSha,branch:intent.targetBranch,idempotent}}
test/workspace-multifile-commit.test.js
new
+26
@@ -0,0 +1,26 @@
1
+import test from 'node:test';
2
+import assert from 'node:assert/strict';
3
+import { commitWorkspaceIntent } from '../src/plugins/github/workspace-commit.js';
4
+
5
+const sha = c => c.repeat(40);
6
+
7
+test('approved multi-file intent creates one blob per file and one atomic tree/commit', async () => {
8
+ const calls=[];
9
+ const workspace={id:'AbCdEf1234',repoId:7,baseBranch:'main',baseHeadSha:sha('a'),baseTreeSha:sha('b'),commitMessage:'feat: multi',commitMessageDigest:'m',currentIntentId:'AbCd1234',files:[
10
+ {path:'a.txt',blobSha:sha('c'),draftText:'A2',draftDigest:'d1'},
11
+ {path:'b.txt',blobSha:sha('d'),draftText:'B2',draftDigest:'d2'}
12
+ ]};
13
+ const intent={id:'AbCd1234',workspaceId:workspace.id,repoId:7,state:'READY',baseBranch:'main',baseHeadSha:sha('a'),baseTreeSha:sha('b'),commitMessageDigest:'m',targetBranch:'nexa/edit-AbCdEf1234',commitTimestamp:'2026-10-05T00:00:00.000Z',files:[
14
+ {path:'a.txt',sourceBlobSha:sha('c'),contentDigest:'d1'},
15
+ {path:'b.txt',sourceBlobSha:sha('d'),contentDigest:'d2'}
16
+ ]};
17
+ const workspaces={async getIntent(){return intent},async getWorkspace(){return workspace},async beginCommit(){return{disposition:'start',intent}},async setCandidateCommit(){},async completeCommit(){},async markStale(){}};
18
+ const github={async getBranchSnapshot(){return{headSha:sha('a')}},async getGitRef(){return null},async createGitBlob(_r,text){calls.push(['blob',text]);return{sha:text==='A2'?sha('e'):sha('f')}},async createGitTree(_r,input){calls.push(['tree',input]);return{sha:sha('1')}},async createGitCommit(_r,input){calls.push(['commit',input]);return{sha:sha('2')}},async createGitBranchRef(_r,input){calls.push(['ref',input])}};
19
+ const result=await commitWorkspaceIntent({github,workspaces,ownerId:'42',repoId:7,intentId:'AbCd1234'});
20
+ assert.equal(result.commitSha,sha('2'));
21
+ assert.deepEqual(calls.filter(c=>c[0]==='blob').map(c=>c[1]),['A2','B2']);
22
+ const tree=calls.find(c=>c[0]==='tree')[1];
23
+ assert.deepEqual(tree.entries.map(e=>e.path),['a.txt','b.txt']);
24
+ assert.equal(calls.filter(c=>c[0]==='tree').length,1);
25
+ assert.equal(calls.filter(c=>c[0]==='commit').length,1);
26
+});
test/workspace-multifile.test.js
+34
-49
@@ -1,58 +1,43 @@
1
import test from 'node:test';
2
import assert from 'node:assert/strict';
3
-import { validateWorkspaceFiles, buildWorkspaceDiff, digestWorkspaceFiles } from '../src/core/workspace-policy.js';
3
+import { WorkspaceStore } from '../src/durable/workspace-store.js';
4
+import { DurableWorkspaceStoreClient } from '../src/core/workspace-store.js';
5
5
-const file = (path, originalText, draftText = originalText) => ({
6
- path,
7
- blobSha: 'a'.repeat(40),
8
- originalText,
9
- originalDigest: 'b'.repeat(64),
10
- draftText,
11
- draftDigest: 'c'.repeat(64)
12
-});
13
-
14
-test('multi-file workspace policy accepts a bounded unique file set', () => {
15
- const result = validateWorkspaceFiles([
16
- file('README.md', 'before\n', 'after\n'),
17
- file('src/app.js', 'export const a = 1;\n', 'export const a = 2;\n')
18
- ]);
19
- assert.equal(result.valid, true);
20
- assert.equal(result.files.length, 2);
21
- assert.ok(result.totalBytes > 0);
22
-});
6
+function makeState() {
7
+ const data = new Map();
8
+ const api = { async get(k){return data.get(k)}, async put(k,v){data.set(k, structuredClone(v))}, async delete(k){return data.delete(k)}, async list(){return new Map(data)} };
9
+ return { storage: { ...api, async transaction(fn){return fn(api)}, async setAlarm(){} } };
10
+}
11
+function makeNamespace() {
12
+ const states = new Map();
13
+ return { idFromName:n=>String(n), get(id){ if(!states.has(id)) states.set(id,makeState()); const store=new WorkspaceStore(states.get(id)); return {fetch:r=>store.fetch(r)}; } };
14
+}
15
+const base = { repoId:1, repoFullName:'davoodmehraban89/nexa-dev-bot', baseBranch:'main', baseHeadSha:'a'.repeat(40), baseTreeSha:'b'.repeat(40), path:'README.md', blobSha:'c'.repeat(40), originalText:'one\n', originalDigest:'d'.repeat(64), expiresAt:999999 };
16
24
-test('multi-file workspace rejects duplicate and sensitive paths and aggregate overflow', () => {
25
- assert.throws(() => validateWorkspaceFiles([file('a.txt', 'x'), file('a.txt', 'y')]), /duplicate/i);
26
- assert.throws(() => validateWorkspaceFiles([file('.env', 'x')]), /sensitive/i);
27
- assert.throws(() => validateWorkspaceFiles([
28
- file('a.txt', 'a'.repeat(65536)),
29
- file('b.txt', 'b'.repeat(65536)),
30
- file('c.txt', 'c')
31
- ]), /aggregate|131,072|131072/i);
17
+test('new workspace exposes versioned files while preserving legacy fields', async () => {
18
+ const client = new DurableWorkspaceStoreClient({ namespace:makeNamespace(), now:()=>1000 });
19
+ const ws = await client.createWorkspace({ownerId:'A', ...base});
20
+ assert.equal(ws.schemaVersion, 2);
21
+ assert.equal(ws.files.length, 1);
22
+ assert.equal(ws.files[0].path, 'README.md');
23
+ assert.equal(ws.path, 'README.md');
24
});
25
34
-test('aggregate diff preserves per-file identity and exact total counts', () => {
35
- const diff = buildWorkspaceDiff({
36
- files: [
37
- file('a.txt', 'one\ntwo\n', 'one\nTWO\n'),
38
- file('b.txt', 'x\n', 'x\ny\n')
39
- ],
40
- maxChars: 2600
41
- });
42
- assert.equal(diff.filesChanged, 2);
43
- assert.equal(diff.additions, 3);
44
- assert.equal(diff.deletions, 1);
45
- assert.match(diff.text, /a\/a\.txt/);
46
- assert.match(diff.text, /a\/b\.txt/);
26
+test('workspace can add update and remove files and material changes invalidate READY intent', async () => {
27
+ const client = new DurableWorkspaceStoreClient({ namespace:makeNamespace(), now:()=>1000 });
28
+ let ws = await client.createWorkspace({ownerId:'A', ...base});
29
+ ws = await client.upsertWorkspaceFile({ownerId:'A', workspaceId:ws.id, file:{path:'src/a.js', blobSha:'e'.repeat(40), originalText:'a\n', originalDigest:'1'.repeat(64), draftText:'b\n', draftDigest:'2'.repeat(64)}});
30
+ assert.deepEqual(ws.files.map(f=>f.path), ['README.md','src/a.js']);
31
+ assert.equal(ws.currentIntentId, null);
32
+ ws = await client.updateWorkspaceFileDraft({ownerId:'A', workspaceId:ws.id, path:'README.md', text:'changed\n', digest:'3'.repeat(64)});
33
+ assert.equal(ws.files.find(f=>f.path==='README.md').draftText, 'changed\n');
34
+ ws = await client.removeWorkspaceFile({ownerId:'A', workspaceId:ws.id, path:'src/a.js'});
35
+ assert.deepEqual(ws.files.map(f=>f.path), ['README.md']);
36
});
37
49
-test('workspace material digest is order-independent but changes with material', async () => {
50
- const a = file('a.txt', 'x', 'y');
51
- const b = file('b.txt', 'm', 'n');
52
- const first = await digestWorkspaceFiles([a, b]);
53
- const reordered = await digestWorkspaceFiles([b, a]);
54
- const changed = await digestWorkspaceFiles([a, { ...b, draftText: 'changed' }]);
55
- assert.match(first, /^[a-f0-9]{64}$/);
56
- assert.equal(first, reordered);
57
- assert.notEqual(first, changed);
38
+test('workspace rejects duplicate normalized paths and aggregate oversize payloads', async () => {
39
+ const client = new DurableWorkspaceStoreClient({ namespace:makeNamespace(), now:()=>1000 });
40
+ const ws = await client.createWorkspace({ownerId:'A', ...base});
41
+ await assert.rejects(() => client.upsertWorkspaceFile({ownerId:'A', workspaceId:ws.id, file:{path:'README.md', blobSha:'x', originalText:'x', originalDigest:'1', draftText:'x', draftDigest:'2'}}), /already exists|duplicate/i);
42
+ await assert.rejects(() => client.upsertWorkspaceFile({ownerId:'A', workspaceId:ws.id, file:{path:'huge.txt', blobSha:'x', originalText:'', originalDigest:'1', draftText:'x'.repeat(262145), draftDigest:'2'}}), /aggregate|large|size/i);
43
});