@feng0531/dsh-vcs 0.7.2 → 0.8.0

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 (56) hide show
  1. package/README.md +69 -6
  2. package/amend-host.mjs +48 -0
  3. package/branch-create-host.mjs +42 -0
  4. package/branch-create-preview.mjs +196 -0
  5. package/branch-delete-preview.mjs +214 -0
  6. package/branch-switch-host.mjs +13 -33
  7. package/commit-host.mjs +49 -0
  8. package/commit-object-publish.mjs +123 -0
  9. package/commit-preview.mjs +335 -0
  10. package/confirmed-operation.mjs +50 -0
  11. package/dist/client.js +2 -2
  12. package/dist/frontend.json +1 -1
  13. package/dist/interface.js +2 -2
  14. package/docs/RELEASING.md +7 -5
  15. package/git-blob-store.mjs +151 -0
  16. package/git-branch-create.mjs +156 -0
  17. package/git-branch-delete.mjs +175 -0
  18. package/git-lightweight-tag-create.mjs +181 -0
  19. package/git-object-store.mjs +162 -0
  20. package/git-ref-cas.mjs +119 -0
  21. package/git-tag-create.mjs +186 -0
  22. package/index-change-host.mjs +19 -0
  23. package/index-change.mjs +418 -0
  24. package/index-lock.mjs +231 -0
  25. package/index-stage-host.mjs +19 -0
  26. package/index.mjs +301 -4
  27. package/latest-commit.mjs +109 -0
  28. package/lightweight-tag-host.mjs +42 -0
  29. package/lightweight-tag-preview.mjs +183 -0
  30. package/line-index-host.mjs +58 -0
  31. package/locale/en.json +1 -1
  32. package/locale/zh.json +1 -1
  33. package/package.json +48 -3
  34. package/partial-stage-host.mjs +52 -0
  35. package/partial-unstage-host.mjs +52 -0
  36. package/src/amend-plan.mjs +74 -0
  37. package/src/branch-delete-plan.mjs +113 -0
  38. package/src/commit-plan.mjs +78 -0
  39. package/src/git-commit-object.mjs +99 -0
  40. package/src/git-index.mjs +113 -0
  41. package/src/git-tag-object.mjs +110 -0
  42. package/src/index-tree.mjs +77 -0
  43. package/src/lightweight-tag-plan.mjs +64 -0
  44. package/src/line-index.mjs +168 -0
  45. package/src/partial-index.mjs +199 -0
  46. package/src/reflog.mjs +33 -0
  47. package/src/settled-reads.mjs +5 -0
  48. package/src/verified-branch-delete-plan.mjs +95 -0
  49. package/src/verified-commit-metadata.mjs +57 -0
  50. package/src/verified-commit-plan.mjs +49 -0
  51. package/src/verified-commit.mjs +84 -0
  52. package/src/verified-tag-plan.mjs +72 -0
  53. package/tag-create-host.mjs +31 -0
  54. package/tag-create-preview.mjs +215 -0
  55. package/tag-object-publish.mjs +49 -0
  56. package/vcs.mjs +29 -0
@@ -0,0 +1,335 @@
1
+ // Internal preview capabilities and caller-serialized commit transaction.
2
+ import * as fs from 'node:fs/promises';
3
+ import {constants} from 'node:fs';
4
+ import path from 'node:path';
5
+ import os from 'node:os';
6
+ import {settledReads} from './src/settled-reads.mjs';
7
+ import {createHash} from 'node:crypto';
8
+ import {git} from './local-command.mjs';
9
+ import {inflateSync} from 'node:zlib';
10
+ import {publishCommitObjects} from './commit-object-publish.mjs';
11
+ import {compareAndSwapBranch} from './git-ref-cas.mjs';
12
+ import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
13
+ import {parseGitIndex} from './src/git-index.mjs';
14
+ import {encodeGitCommit} from './src/git-commit-object.mjs';
15
+ import {createVerifiedIndexCommitPlan} from './src/verified-commit-plan.mjs';
16
+ import {createAmendPlan} from './src/amend-plan.mjs';
17
+
18
+ const INDEX=8*1024*1024,PARENT=2*1024*1024,CONFIG=256*1024;
19
+ // Only the exact issued public summary is a key; private plans never leave this module.
20
+ const previews=new WeakMap();
21
+ // Amend capabilities are deliberately unusable by normal commit consumers.
22
+ const amendPreviews=new WeakMap();
23
+ const hash=b=>createHash('sha256').update(b).digest('hex');
24
+ const decode=b=>new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(b);
25
+ const check=()=>currentOperationBudget().throwIfExpired();
26
+ const fail=message=>Object.assign(new Error(message),{code:'vcs/commit-preview'});
27
+ const identity=s=>[s.dev,s.ino,s.birthtimeNs].map(String);
28
+ const version=s=>[...identity(s),s.size,s.mtimeNs,s.ctimeNs,s.mode].map(String);
29
+ const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
30
+ const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
31
+ function record(value,keys,label){
32
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw fail('Invalid '+label+' record');
33
+ const out={};for(const key of Reflect.ownKeys(value)){
34
+ if(!keys.includes(key))throw fail('Unsupported '+label+' field');
35
+ const d=Object.getOwnPropertyDescriptor(value,key);
36
+ if(!d||!Object.hasOwn(d,'value'))throw fail(label+' requires own data properties');
37
+ out[key]=d.value;
38
+ }return out;
39
+ }
40
+ async function readPlain(file,max){
41
+ check();const before=await fs.lstat(file,{bigint:true});
42
+ if(!plain(before)||before.size>BigInt(max))throw fail('Expected bounded single-link regular file: '+file);
43
+ const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW||0));
44
+ try{
45
+ const opened=await handle.stat({bigint:true});
46
+ if(!plain(opened)||!equal(version(before),version(opened)))throw fail('Stale file opening');
47
+ const bytes=Buffer.alloc(max+1);let length=0;
48
+ while(length<bytes.length){check();const r=await handle.read(bytes,length,bytes.length-length,length);if(!r.bytesRead)break;length+=r.bytesRead;}
49
+ const after=await handle.stat({bigint:true}),current=await fs.lstat(file,{bigint:true});
50
+ if(length>max||!plain(current)||!equal(version(opened),version(after))||!equal(version(after),version(current))||BigInt(length)!==after.size)throw fail('Stale or oversized file reading');
51
+ return {bytes:Buffer.from(bytes.subarray(0,length)),version:version(after)};
52
+ }finally{await handle.close();}
53
+ }
54
+ async function exists(file){try{await fs.lstat(file);return true;}catch(e){if(e.code==='ENOENT')return false;throw e;}}
55
+ const forbidden=new Set(['commondir','gitdir','shallow','config.worktree','MERGE_HEAD','MERGE_MSG','CHERRY_PICK_HEAD','REVERT_HEAD','REBASE_HEAD','BISECT_LOG','BISECT_START','rebase-merge','rebase-apply','sequencer','worktrees','info/sparse-checkout','info/attributes','objects/info/alternates','objects/info/http-alternates'].map(s=>s.toLowerCase()));
56
+ async function metadata(directory){
57
+ const rows=[];let nodes=0;
58
+ async function visit(file,relative){
59
+ check();if(++nodes>20000)throw fail('Metadata inspection limit exceeded');
60
+ const key=relative.toLowerCase();
61
+ if(forbidden.has(key)||key.endsWith('.lock')||key.endsWith('.promisor')||key.startsWith('sharedindex.')||key.startsWith('hooks/')&&!key.endsWith('.sample'))throw fail('Unsupported repository metadata: '+relative);
62
+ const s=await fs.lstat(file,{bigint:true});
63
+ if(s.isSymbolicLink()||(!s.isDirectory()&&!plain(s))||await fs.realpath(file)!==file)throw fail('Linked or special repository metadata');
64
+ rows.push([relative,s.isDirectory()?identity(s):version(s)]);
65
+ if(s.isDirectory()){
66
+ const names=await fs.readdir(file);check();
67
+ if(names.length>20000-nodes)throw fail('Metadata inspection limit exceeded');
68
+ for(const name of names.sort())await visit(path.join(file,name),relative?relative+'/'+name:name);
69
+ }
70
+ }
71
+ await visit(directory,'');return rows;
72
+ }
73
+ // Inspect names/types only, never read working file contents (including attributes).
74
+ async function workPolicy(root){
75
+ let nodes=0;const rows=[];
76
+ async function visit(dir,relative){
77
+ check();if(++nodes>20000)throw fail('Working directory inspection limit exceeded');
78
+ const s=await fs.lstat(dir,{bigint:true});
79
+ if(!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(dir)!==dir)throw fail('Linked working directory');
80
+ rows.push([relative,identity(s)]);
81
+ const names=(await fs.readdir(dir)).filter(name=>relative||name!=='.git');check();
82
+ if(names.length>20000-nodes)throw fail('Working directory inspection limit exceeded');
83
+ for(const name of names.sort()){
84
+ if(['.gitattributes','.gitmodules','.git'].includes(name.toLowerCase()))throw fail('Attributes, nested repositories or submodules unsupported');
85
+ const file=path.join(dir,name),stat=await fs.lstat(file,{bigint:true});
86
+ if(stat.isDirectory()&&!stat.isSymbolicLink())await visit(file,relative+'/'+name);
87
+ else if(++nodes>20000||!plain(stat))throw fail('Linked or special working file');
88
+ }
89
+ }await visit(root,'');return rows;
90
+ }
91
+ function validateConfig(bytes){
92
+ for(const row of decode(bytes).split('\0').filter(Boolean)){
93
+ const i=row.indexOf('\n'),key=(i<0?row:row.slice(0,i)).toLowerCase(),value=(i<0?'':row.slice(i+1)).toLowerCase();
94
+ if(/^(filter|hook|include|submodule|gpg)\./.test(key)||key.startsWith('includeif.')||key.startsWith('extensions.')&&key!=='extensions.objectformat'||['core.worktree','core.hookspath','core.attributesfile','core.sshcommand','core.gitproxy','core.sharedrepository','core.sparsecheckout','core.sparsecheckoutcone','core.splitindex','core.untrackedcache','index.sparse','commit.gpgsign','tag.gpgsign','user.signingkey','commit.template','i18n.commitencoding'].includes(key)||/^remote\..*\.(promisor|partialclonefilter)$/.test(key))throw fail('Unsupported repository configuration: '+key);
95
+ if(['core.autocrlf','core.safecrlf','core.fsmonitor'].includes(key)&&!['false','no','0'].includes(value))throw fail('Content conversions unsupported');
96
+ }
97
+ }
98
+ async function capture(root){
99
+ check();if(await fs.realpath(root)!==root)throw fail('Canonical root required');
100
+ const rootStat=await fs.lstat(root,{bigint:true});if(!rootStat.isDirectory()||rootStat.isSymbolicLink())throw fail('Directory root required');
101
+ const directory=path.join(root,'.git');
102
+ const [meta,work]=await settledReads([()=>metadata(directory),()=>workPolicy(root)]);
103
+ for(const file of [path.join(process.env.XDG_CONFIG_HOME||path.join(os.homedir(),'.config'),'git','attributes'),path.join(os.homedir(),'.gitattributes'),...(process.platform==='win32'?[]:['/etc/gitattributes','/usr/local/etc/gitattributes'])])if(await exists(file))throw fail('Global attributes unsupported');
104
+ const localConfig=await readPlain(path.join(directory,'config'),CONFIG);
105
+ const config=await git(root,['--git-dir='+directory,'--work-tree='+root,'config','--no-includes','--null','--list'],CONFIG);validateConfig(config);
106
+ const facts=decode(await git(root,['rev-parse','--absolute-git-dir','--git-common-dir','--show-toplevel','--is-bare-repository','--show-object-format','--verify','HEAD^{commit}'],16384)).split('\n');
107
+ if(facts.length!==7||facts[6]!==''||facts.slice(0,3).some(s=>!s||/[\r\0]/.test(s))||path.resolve(root,facts[0])!==directory||path.resolve(root,facts[1])!==directory||path.resolve(facts[2])!==root||facts[3]!=='false')throw fail('Born embedded non-bare Git repository required');
108
+ const objectFormat=facts[4],head=facts[5];
109
+ if(!['sha1','sha256'].includes(objectFormat)||!(objectFormat==='sha1'?/^[a-f0-9]{40}$/:/^[a-f0-9]{64}$/).test(head))throw fail('Invalid fixed HEAD');
110
+ const headFile=await readPlain(path.join(directory,'HEAD'),4096),text=decode(headFile.bytes);
111
+ if(!/^ref: refs\/heads\/[^\r\n]+\n?$/.test(text))throw fail('Born symbolic HEAD required');
112
+ const ref=text.replace(/\n$/,'').slice(5);await git(root,['check-ref-format',ref],4096);
113
+ const index=await readPlain(path.join(directory,'index'),INDEX),parsed=parseGitIndex(index.bytes,{objectFormat});
114
+ if(parsed.extensions.some(e=>!['TREE','EOIE','IEOT'].includes(e.signature)))throw fail('Unsupported Index extension');
115
+ const folded=new Set();for(const e of parsed.entries){
116
+ const key=e.path.toLowerCase();if(folded.has(key)||e.path.split('/').some(p=>['.gitattributes','.gitmodules'].includes(p.toLowerCase())))throw fail('Ambiguous Index paths or tracked attributes unsupported');folded.add(key);
117
+ }
118
+ // Close each capture with a metadata barrier as well: changes late in the
119
+ // second capture must not escape merely because HEAD was read earlier.
120
+ if(!equal(meta,await metadata(directory))||!equal(identity(rootStat),identity(await fs.lstat(root,{bigint:true})))||await fs.realpath(root)!==root)throw fail('Stale repository metadata during capture');
121
+ return {bytes:index.bytes,entries:parsed.entries,head,ref,objectFormat,fingerprint:{root:identity(rootStat),meta,work,config:hash(config),localConfig:[localConfig.version,hash(localConfig.bytes)],headFile:[headFile.version,hash(headFile.bytes)],index:[index.version,hash(index.bytes)],head,ref,objectFormat}};
122
+ }
123
+
124
+ async function readFixedHead(root,state){
125
+ // All capture policy guards precede fixed reads; never resolve moving HEAD.
126
+ // Cached attributes avoid opening working content.
127
+ for(let i=0;i<state.entries.length;i+=128){
128
+ if((await git(root,['check-attr','--cached','--all','-z','--',...state.entries.slice(i,i+128).map(e=>e.path)],CONFIG)).length)throw fail('Git attributes unsupported');
129
+ }
130
+ return git(root,['cat-file','commit',state.head],PARENT);
131
+ }
132
+ async function verifyFixedBlobs(root,state){
133
+ for(const oid of new Set(state.entries.map(e=>e.oid))){check();if(decode(await git(root,['cat-file','-t',oid],128))!=='blob\n')throw fail('Index entry is not an existing blob');}
134
+ }
135
+ async function rebuild(root,state,{author,committer,message}){
136
+ const body=await readFixedHead(root,state);
137
+ const plan=createVerifiedIndexCommitPlan(state.bytes,body,{objectFormat:state.objectFormat,parent:state.head,author,committer,message,signal:currentOperationBudget().signal});
138
+ await verifyFixedBlobs(root,state);
139
+ return plan;
140
+ }
141
+ function safeSummary(state,plan,{author,committer,message}){
142
+ return Object.freeze({head:state.head,ref:state.ref,objectFormat:state.objectFormat,indexDigest:plan.indexDigest,tree:plan.tree,commit:Object.freeze({oid:plan.commit.oid}),author,committer,message});
143
+ }
144
+ async function authorize(callback){
145
+ check();const {signal}=currentOperationBudget();
146
+ // A stalled external authorization callback cannot defeat the shared deadline.
147
+ let abort;const canceled=new Promise((_,reject)=>{abort=()=>reject(signal.reason);signal.addEventListener('abort',abort,{once:true});});
148
+ try{await Promise.race([Promise.resolve().then(callback),canceled]);check();}
149
+ finally{signal.removeEventListener('abort',abort);}
150
+ }
151
+ /** Single-use, read-only revalidation; not an execution/publication API.
152
+ * The retained plan is reserved for future internal composition and discarded here.
153
+ * Work content is neither read nor pinned: the existing fingerprint records directory
154
+ * identities only, while workPolicy still rejects special files/attributes/nested Git.
155
+ * No global filesystem atomicity is promised by these observation barriers.
156
+ */
157
+ export async function consumeCommitPreview(repo,options={}){
158
+ // Burn an own-data snapshot BEFORE validating any other metadata or callbacks,
159
+ // including malformed options and a wrong repository. Never invoke a getter.
160
+ const descriptor=options&&Object.getOwnPropertyDescriptor(options,'snapshot');
161
+ const snapshot=descriptor&&Object.hasOwn(descriptor,'value')?descriptor.value:undefined;
162
+ const saved=previews.get(snapshot);previews.delete(snapshot);
163
+ const r=record(repo,['type','root'],'repository'),o=record(options,['snapshot','signal','assertAuthorized'],'options');
164
+ if(!saved)throw fail('A single-use server-issued commit preview is required');
165
+ if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root||r.root!==saved.root)throw fail('Same canonical Git root required');
166
+ if(typeof o.assertAuthorized!=='function')throw fail('Authorization callback required');
167
+ return withOperationBudget({signal:o.signal},async()=>{
168
+ await authorize(o.assertAuthorized);
169
+ const first=await capture(r.root);
170
+ if(!equal(saved.fingerprint,first.fingerprint))throw fail('Stale repository changed since commit preview');
171
+ const plan=await rebuild(r.root,first,snapshot);
172
+ if(plan.id!==saved.plan.id)throw fail('Stale rebuilt commit plan');
173
+ await authorize(o.assertAuthorized);
174
+ // Must follow the LAST external callback, which may itself mutate the repository.
175
+ const final=await capture(r.root);
176
+ if(!equal(saved.fingerprint,final.fingerprint))throw fail('Stale repository changed during commit preview consumption');
177
+ check();return safeSummary(final,plan,snapshot);
178
+ });
179
+ }
180
+
181
+ /** Internal commit transaction. CALLER MUST hold the shared repository writer mutex
182
+ * across prepare/apply (at least the entire apply). No Host/UI integration.
183
+ * Observation barriers are not hostile-external-process isolation: no index lock is
184
+ * held, so index edits between the final check and ref CAS can only be diagnosed
185
+ * afterwards. No work content reads/writes, rollback, or crash-durability promise.
186
+ * Requires a loose born branch and existing HEAD/branch reflogs; no log creation.
187
+ * Publisher authorization is raw while its owned temporary file exists; full
188
+ * original+verified-created-object barriers follow publication and precede CAS.
189
+ */
190
+ export async function applyCommitPreview(repo,options={}){
191
+ const descriptor=options&&Object.getOwnPropertyDescriptor(options,'snapshot');
192
+ const snapshot=descriptor&&Object.hasOwn(descriptor,'value')?descriptor.value:undefined;
193
+ const saved=previews.get(snapshot);previews.delete(snapshot);
194
+ return executeSnapshot(repo,options,saved,'commit');
195
+ }
196
+
197
+ /** Internal amend transaction; the same caller-held writer mutex is required.
198
+ * Only this entrypoint can consume amend capabilities. No public mode flag. */
199
+ export async function applyAmendPreview(repo,options={}){
200
+ const descriptor=options&&Object.getOwnPropertyDescriptor(options,'snapshot');
201
+ const snapshot=descriptor&&Object.hasOwn(descriptor,'value')?descriptor.value:undefined;
202
+ const saved=amendPreviews.get(snapshot);amendPreviews.delete(snapshot);
203
+ return executeSnapshot(repo,options,saved,'amend');
204
+ }
205
+
206
+ async function executeSnapshot(repo,options,saved,kind){
207
+ const r=record(repo,['type','root'],'repository'),o=record(options,['snapshot','signal','assertAuthorized','onStart'],'options');
208
+ const snapshot=kind==='amend'?saved?.plan:o.snapshot;
209
+ if(!saved)throw fail('A single-use server-issued '+kind+' preview is required');
210
+ if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root||r.root!==saved.root)throw fail('Same canonical Git root required');
211
+ if(typeof o.assertAuthorized!=='function'||typeof o.onStart!=='function')throw fail('Authorization and synchronous start callbacks required');
212
+ let started=false;
213
+ try{return await withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
214
+ const original=saved.fingerprint,plan=saved.plan,directory=path.join(r.root,'.git');
215
+ const rawAuth=()=>authorize(o.assertAuthorized);
216
+ const start=()=>{
217
+ check();if(started)return;started=true;
218
+ const value=o.onStart();
219
+ if(value&&typeof value.then==='function'){Promise.resolve(value).catch(()=>{});throw fail('onStart must be synchronous');}
220
+ check();
221
+ };
222
+ const exact=state=>{if(!equal(original,state.fingerprint))throw fail('Stale repository changed since commit preview');};
223
+ await rawAuth();const first=await capture(r.root);exact(first);
224
+ const rebuilt=kind==='amend'
225
+ ?createAmendPlan(first.bytes,await readFixedHead(r.root,first),{head:first.head,objectFormat:first.objectFormat,committer:snapshot.committer,message:snapshot.message,signal:currentOperationBudget().signal})
226
+ :await rebuild(r.root,first,snapshot);
227
+ if(kind==='amend')await verifyFixedBlobs(r.root,first);
228
+ if(rebuilt.id!==plan.id)throw fail('Stale rebuilt '+kind+' plan');
229
+ const ref=original.ref,mutable=new Set([ref,'logs/HEAD','logs/'+ref]);
230
+ const baseline=new Map(original.meta),logs=new Map();
231
+ for(const name of mutable){
232
+ if(!baseline.has(name)||baseline.get(name).length!==7)throw fail('Existing loose branch and reflogs required');
233
+ const file=await readPlain(path.join(directory,...name.split('/')),1024*1024);
234
+ if(!equal(file.version,baseline.get(name)))throw fail('Stale branch or reflog');
235
+ if(name===ref){if(decode(file.bytes)!==original.head+'\n')throw fail('Exact loose branch required');}
236
+ else logs.set(name,file.bytes);
237
+ }
238
+ await rawAuth();exact(await capture(r.root));check();
239
+ const published=await publishCommitObjects({gitDirectory:directory,objectFormat:original.objectFormat,trees:plan.trees,commit:plan.commit,signal:currentOperationBudget().signal,assertAuthorized:rawAuth,onStart:start});
240
+ // Only the publisher's actual newly-created list grants additions. Existing
241
+ // object rows must remain byte-version-identical, even when candidates match.
242
+ const owned=new Map(),allowed=new Set();
243
+ for(const {type,oid} of published.created){
244
+ const object=type==='commit'?plan.commit:plan.trees.find(t=>t.oid===oid);
245
+ if(!object||object.oid!==oid)throw fail('Unexpected published object');
246
+ const name='objects/'+oid.slice(0,2)+'/'+oid.slice(2),fanout='objects/'+oid.slice(0,2);
247
+ if(baseline.has(name))throw fail('Publisher changed a preexisting object');
248
+ allowed.add(name);if(!baseline.has(fanout))allowed.add(fanout);
249
+ const stored=await readPlain(path.join(directory,...name.split('/')),object.body.length+1024*1024);
250
+ const inflated=inflateSync(stored.bytes,{maxOutputLength:object.body.length+128,info:true});check();
251
+ const raw=inflated.buffer,expected=Buffer.concat([Buffer.from(type+' '+object.body.length+'\0'),object.body]);
252
+ if(inflated.engine.bytesWritten!==stored.bytes.length||!raw.equals(expected)||createHash(original.objectFormat).update(raw).digest('hex')!==oid)throw fail('Stored object differs from saved plan');
253
+ owned.set(name,stored.version);
254
+ }
255
+ let ownedRows;
256
+ const barrier=async(post=false)=>{
257
+ const current=await capture(r.root),fp=current.fingerprint,rows=new Map(fp.meta);
258
+ for(const [name,row] of baseline){
259
+ if(!rows.has(name)||(!post||!mutable.has(name))&&!equal(row,rows.get(name)))throw fail('Stale original metadata: '+name);
260
+ }
261
+ for(const [name,row] of rows)if(!baseline.has(name)){
262
+ if(!allowed.has(name)||owned.has(name)&&!equal(owned.get(name),row))throw fail('Foreign or changed object metadata: '+name);
263
+ }
264
+ const additions=fp.meta.filter(([name])=>!baseline.has(name));
265
+ if(additions.length!==allowed.size||ownedRows&&!equal(ownedRows,additions))throw fail('Owned object metadata changed');
266
+ if(!ownedRows)ownedRows=additions;
267
+ const normalized={...fp,meta:original.meta,head:post?original.head:fp.head};
268
+ if(!equal(normalized,original)||post&&fp.head!==plan.commit.oid)throw fail('Stale repository fingerprint');
269
+ if(!current.bytes.equals(first.bytes))throw fail('Index bytes changed');
270
+ return current;
271
+ };
272
+ await barrier();
273
+ let refStarted=false;
274
+ await compareAndSwapBranch(r,{ref,expectedOid:original.head,newOid:plan.commit.oid,objectFormat:original.objectFormat,signal:currentOperationBudget().signal,
275
+ assertAuthorized:async()=>{await rawAuth();if(!refStarted)await barrier();},
276
+ onStart:()=>{check();refStarted=true;start();check();}});
277
+ await barrier(true);
278
+ for(const [name,before] of logs){
279
+ const after=(await readPlain(path.join(directory,...name.split('/')),1024*1024)).bytes;
280
+ const tail=after.subarray(before.length);
281
+ if(!after.subarray(0,before.length).equals(before)||!decode(tail).startsWith(original.head+' '+plan.commit.oid+' ')||decode(tail).split('\n').length!==2)throw fail('Unexpected reflog change');
282
+ }
283
+ if(decode((await readPlain(path.join(directory,...ref.split('/')),4096)).bytes)!==plan.commit.oid+'\n')throw fail('Unexpected branch tip');
284
+ check();return Object.freeze({head:plan.commit.oid,ref,tree:plan.tree,indexDigest:plan.indexDigest});
285
+ });}catch(cause){
286
+ if(!started)throw cause;
287
+ throw Object.assign(new Error((kind==='amend'?'Amend':'Commit')+' started; outcome unknown. Inspect repository; never roll back appended objects or retry automatically.',{cause}),{code:'vcs/'+kind+'-outcome-unknown',appendOnly:true,outcomeUnknown:true});
288
+ }
289
+ }
290
+
291
+ /** Read-only, conservative two-capture preview; private retained plan.
292
+ * Repeated observations are stale barriers, not global filesystem atomicity.
293
+ * Only regular stage-zero Index entries; no hooks/signing/attributes/conversions,
294
+ * linked/shared/alternate/shallow repositories, active operations or locks.
295
+ */
296
+ export async function prepareCommitPreview(repo,options={}){
297
+ // Strict metadata snapshots and validation happen synchronously before the first await.
298
+ const r=record(repo,['type','root'],'repository'),o=record(options,['author','committer','message','signal'],'options');
299
+ if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root)throw fail('Absolute canonical Git root required');
300
+ const author=record(o.author,['name','email','timestamp','timezone'],'author'),committer=record(o.committer,['name','email','timestamp','timezone'],'committer');
301
+ if(typeof o.message!=='string'||Buffer.byteLength(o.message)>65536||!o.message.trim()||/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(o.message.replace(/[\n\t]/g,'')))throw fail('Bounded plaintext commit message required');
302
+ const message=o.message;
303
+ // Reuse the pure encoder to reject all invalid identities before repository I/O.
304
+ encodeGitCommit({tree:'1'.repeat(40),parents:[],author,committer,message});
305
+ Object.freeze(author);Object.freeze(committer);
306
+ return withOperationBudget({signal:o.signal},async()=>{
307
+ const first=await capture(r.root);check();
308
+ const plan=await rebuild(r.root,first,{author,committer,message});
309
+ const second=await capture(r.root);
310
+ if(!equal(first.fingerprint,second.fingerprint))throw fail('Stale repository changed during commit preview');
311
+ check();const summary=safeSummary(first,plan,{author,committer,message});
312
+ previews.set(summary,{root:r.root,fingerprint:first.fingerprint,plan});return summary;
313
+ });
314
+ }
315
+ /** Read-only amend preview; its separate capability is consumed only by applyAmendPreview. */
316
+ export async function prepareAmendPreview(repo,options={}){
317
+ // Snapshot strict own-data metadata before the first await, just like commit preview.
318
+ const r=record(repo,['type','root'],'repository'),o=record(options,['committer','message','signal'],'options');
319
+ if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root)throw fail('Absolute canonical Git root required');
320
+ const committer=record(o.committer,['name','email','timestamp','timezone'],'committer');
321
+ if(typeof o.message!=='string'||Buffer.byteLength(o.message)>65536||!o.message.trim()||/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(o.message.replace(/[\n\t]/g,'')))throw fail('Bounded plaintext commit message required');
322
+ const message=o.message;
323
+ encodeGitCommit({tree:'1'.repeat(40),parents:[],author:committer,committer,message});
324
+ Object.freeze(committer);
325
+ return withOperationBudget({signal:o.signal},async()=>{
326
+ const first=await capture(r.root);check();
327
+ const body=await readFixedHead(r.root,first);
328
+ const plan=createAmendPlan(first.bytes,body,{head:first.head,objectFormat:first.objectFormat,committer,message,signal:currentOperationBudget().signal});
329
+ await verifyFixedBlobs(r.root,first);
330
+ const second=await capture(r.root);
331
+ if(!equal(first.fingerprint,second.fingerprint))throw fail('Stale repository changed during amend preview');
332
+ check();const summary=Object.freeze({action:'amend',head:first.head,ref:first.ref,objectFormat:first.objectFormat,indexDigest:plan.indexDigest,previousTree:plan.previousTree,parents:plan.parents,author:plan.author,committer:plan.committer,message:plan.message,tree:plan.tree,commit:Object.freeze({oid:plan.commit.oid})});
333
+ amendPreviews.set(summary,{root:r.root,fingerprint:first.fingerprint,plan});return summary;
334
+ });
335
+ }
@@ -0,0 +1,50 @@
1
+ // Server-owned, single-use confirmation and process-shared repository exclusion.
2
+ import {randomBytes} from 'node:crypto';
3
+ import path from 'node:path';
4
+ const access=new Map();
5
+ const error=(code,message)=>Object.assign(new Error(message),{code});
6
+ const keyOf=root=>{const key=path.resolve(root);return process.platform==='win32'?key.toLowerCase():key;};
7
+ export function acquireRepositoryAccess(root,write=false){
8
+ const key=keyOf(root),state=access.get(key)||{readers:0,writer:false};
9
+ if(state.writer||(write&&state.readers))throw error('vcs/busy','This repository has an active operation. Wait for it to finish and prepare again.');
10
+ if(write)state.writer=true;else state.readers++;access.set(key,state);let released=false;
11
+ return()=>{if(released)return;released=true;if(write)state.writer=false;else state.readers--;if(!state.writer&&!state.readers)access.delete(key);};
12
+ }
13
+
14
+ // operationKind and callbacks are selected by the host, never by a browser address.
15
+ // prepare(repository, {address, signal}) retains its entire result on the server.
16
+ // Only explicitly projected public fields cross the confirmation boundary.
17
+ export function createConfirmedOperationCoordinator({
18
+ operationKind,api,prepare=api?.prepare,execute=api?.execute,project=()=>({}),
19
+ now=Date.now,ttlMs=60000,maxTokens=32,
20
+ invalidCode='vcs/confirmation-invalid',
21
+ invalidMessage='Confirmation is expired, used, or belongs to a different Session/repository. Prepare again.',
22
+ unknownCode='vcs/outcome-unknown',
23
+ unknownMessage='The operation started but its final result could not be confirmed. Refresh the repository before preparing another operation.',
24
+ }){
25
+ if(typeof operationKind!=='string'||!operationKind.trim())throw new TypeError('A server-selected operationKind is required.');
26
+ if(typeof prepare!=='function'||typeof execute!=='function'||typeof project!=='function')throw new TypeError('Confirmation prepare, execute and project callbacks must be functions.');
27
+ if(!Number.isFinite(ttlMs)||ttlMs<=0||!Number.isSafeInteger(maxTokens)||maxTokens<=0)throw new TypeError('Confirmation ttlMs and maxTokens must be positive.');
28
+ const tokens=new Map();
29
+ const purge=()=>{for(const [token,row]of tokens)if(row.expiresAt<=now())tokens.delete(token);};
30
+ return {
31
+ invalidate(entry){for(const [token,row]of tokens)if(row.entry===entry)tokens.delete(token);},
32
+ clear(){tokens.clear();},
33
+ async prepare(address,{entry,repository,cwd,signal,assertAuthorized}){
34
+ const snapshot=await prepare.call(api,{...repository},{address,signal});await assertAuthorized();signal?.throwIfAborted();purge();
35
+ while(tokens.size>=maxTokens)tokens.delete(tokens.keys().next().value);
36
+ const token=randomBytes(32).toString('hex'),expiresAt=now()+ttlMs;
37
+ const publicFields=project(snapshot);
38
+ tokens.set(token,{snapshot,expiresAt,entry,repository,cwd,sessionId:address.sessionId,repositoryId:address.repositoryId,operationKind});
39
+ return {...publicFields,token,expiresAt};
40
+ },
41
+ async confirm(address,{entry,repository,cwd,signal,assertAuthorized}){
42
+ purge();const row=tokens.get(address.token);tokens.delete(address.token);
43
+ if(!row||row.operationKind!==operationKind||row.entry!==entry||row.repository!==repository||row.cwd!==cwd||row.sessionId!==address.sessionId||row.repositoryId!==address.repositoryId)throw error(invalidCode,invalidMessage);
44
+ const release=acquireRepositoryAccess(repository.root,true);let started=false;
45
+ try{await assertAuthorized();signal?.throwIfAborted();const result=await execute.call(api,{...repository},{snapshot:row.snapshot,signal,assertAuthorized,onStart(){started=true;}});await assertAuthorized();signal?.throwIfAborted();return result;}
46
+ catch(failure){if(started)throw error(unknownCode,unknownMessage);throw failure;}
47
+ finally{release();}
48
+ },
49
+ };
50
+ }