@feng0531/dsh-vcs 0.7.3 → 0.8.2

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 +68 -5
  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 +25 -2
  12. package/dist/frontend.json +1 -1
  13. package/dist/interface.js +25 -2
  14. package/docs/RELEASING.md +2 -0
  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 +47 -2
  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,84 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {TextDecoder} from 'node:util';
3
+
4
+ // Pure verification of raw commit BODY bytes, not a loose-object/zlib envelope.
5
+ // No I/O, refs, referenced-object existence/type checks, or returned body ownership.
6
+ // Snapshot Buffer synchronously (<=2 MiB); hash Git's commit + length + NUL framing.
7
+ // Header bytes including the blank separator are <=128 KiB, at most 256 lines.
8
+ // Initial scope: tree, 0..16 unique contiguous parents, author, committer, then
9
+ // optionally exact `encoding UTF-8`. All other headers and continuations (including
10
+ // gpgsig/mergetag) are rejected, not skipped. LF framing only; no header CR/NUL.
11
+ // Identities use strict UTF-8, nonblank NAME <EMAIL>, nonnegative safe integer
12
+ // timestamp, +/-HHMM offset <=1400 (minutes <60), and no controls/angle injection.
13
+ // Message bytes after the mandatory blank line are opaque: invalid UTF-8, CR,
14
+ // NUL, and header-like text are allowed, within the overall 2 MiB body limit.
15
+ const MAX_BODY_BYTES=2*1024*1024,MAX_HEADER_BYTES=128*1024,MAX_HEADERS=256;
16
+ const utf8=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true});
17
+ function checkAbort(signal){
18
+ if(signal?.aborted){
19
+ const error=new Error('Git commit verification aborted');error.name='AbortError';throw error;
20
+ }
21
+ }
22
+ function validOid(value,width){
23
+ if(typeof value!=='string'||value.length!==width||/[^0-9a-f]/.test(value)||/^0+$/.test(value))throw Error('Invalid Git object id');
24
+ return value;
25
+ }
26
+ function validateIdentity(value){
27
+ let text;
28
+ try{text=utf8.decode(value);}catch{throw Error('Git identity must be strict UTF-8');}
29
+ const match=/^([^<>]+) <([^<>]+)> (0|[1-9][0-9]*) ([-+][0-9]{4})$/.exec(text);
30
+ if(!match||!match[1].trim()||!match[2].trim()||/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(text))throw Error('Invalid Git identity');
31
+ if(!Number.isSafeInteger(Number(match[3])))throw Error('Invalid Git identity timestamp');
32
+ const hours=Number(match[4].slice(1,3)),minutes=Number(match[4].slice(3));
33
+ if(minutes>59||hours>14||(hours===14&&minutes!==0))throw Error('Invalid Git identity timezone');
34
+ }
35
+
36
+ export function parseVerifiedCommit(bytes,options={}){
37
+ if(!Buffer.isBuffer(bytes))throw Error('Git commit bytes must be a Buffer');
38
+ if(bytes.length>MAX_BODY_BYTES)throw Error('Git commit body byte limit exceeded');
39
+ const body=Buffer.from(bytes);
40
+ const {oid,objectFormat='sha1',signal}=options;
41
+ checkAbort(signal);
42
+ if(objectFormat!=='sha1'&&objectFormat!=='sha256')throw Error('Unsupported Git object format');
43
+ const width=objectFormat==='sha1'?40:64;
44
+ validOid(oid,width);
45
+ const actual=createHash(objectFormat).update(Buffer.from('commit '+body.length+'\0','ascii')).update(body).digest('hex');
46
+ if(actual!==oid)throw Error('Git commit object id mismatch');
47
+ checkAbort(signal);
48
+ const header=body.subarray(0,MAX_HEADER_BYTES);
49
+ let offset=0,count=0,tree,state='tree',encoding=false;
50
+ const parents=[],seen=new Set();
51
+ while(true){
52
+ checkAbort(signal);
53
+ const end=header.indexOf(10,offset);
54
+ if(end<0)throw Error('Git commit missing separator or header byte limit exceeded');
55
+ const line=header.subarray(offset,end);offset=end+1;
56
+ if(!line.length){
57
+ if(state!=='done')throw Error('Git commit missing required headers');
58
+ break;
59
+ }
60
+ if(++count>MAX_HEADERS)throw Error('Git commit header count limit exceeded');
61
+ if(line.includes(0)||line.includes(13))throw Error('Invalid Git commit header framing');
62
+ const space=line.indexOf(32);
63
+ if(space<=0)throw Error('Unsupported Git commit header or continuation');
64
+ const key=line.subarray(0,space).toString('latin1'),value=line.subarray(space+1);
65
+ if(key==='tree'&&state==='tree'){
66
+ tree=validOid(value.toString('latin1'),width);state='parents';
67
+ }else if(key==='parent'&&state==='parents'){
68
+ const parent=validOid(value.toString('latin1'),width);
69
+ if(parents.length===16)throw Error('Git commit parent limit exceeded');
70
+ if(seen.has(parent))throw Error('Duplicate Git commit parent');
71
+ seen.add(parent);parents.push(parent);
72
+ }else if(key==='author'&&state==='parents'){
73
+ validateIdentity(value);state='committer';
74
+ }else if(key==='committer'&&state==='committer'){
75
+ validateIdentity(value);state='done';
76
+ }else if(key==='encoding'&&state==='done'&&!encoding&&value.equals(Buffer.from('UTF-8'))){
77
+ encoding=true;
78
+ }else{
79
+ throw Error('Unsupported, duplicate or out-of-order Git commit header');
80
+ }
81
+ }
82
+ checkAbort(signal);
83
+ return Object.freeze({oid,tree,parents:Object.freeze(parents)});
84
+ }
@@ -0,0 +1,72 @@
1
+ import {createHash} from 'node:crypto';
2
+ import {parseVerifiedCommit} from './verified-commit.mjs';
3
+ import {encodeGitTag,parseVerifiedGitTag} from './git-tag-object.mjs';
4
+
5
+ const MAX_COMMIT_BYTES=2*1024*1024,MAX_MESSAGE_BYTES=64*1024;
6
+ const nativeAborted=Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get;
7
+ const nativeAbort=AbortSignal.prototype.throwIfAborted;
8
+ function owned(bytes){const copy=Buffer.alloc(bytes.length);Buffer.prototype.copy.call(bytes,copy);return copy;}
9
+ function record(value,keys,required,label){
10
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw Error('Invalid Git tag plan '+label+' record');
11
+ const out=Object.create(null);
12
+ for(const key of Reflect.ownKeys(value)){
13
+ if(typeof key!=='string'||!keys.includes(key))throw Error('Unsupported Git tag plan '+label+' field');
14
+ const d=Object.getOwnPropertyDescriptor(value,key);
15
+ if(!d||!Object.hasOwn(d,'value'))throw Error('Git tag plan '+label+' requires own data properties');
16
+ out[key]=d.value;
17
+ }
18
+ for(const key of required)if(!Object.hasOwn(out,key))throw Error('Missing Git tag plan '+label+' '+key);
19
+ return out;
20
+ }
21
+ function abortCheck(signal){
22
+ if(signal===undefined)return ()=>{};
23
+ let native=false;try{Reflect.apply(nativeAborted,signal,[]);native=true;}catch{}
24
+ if(native)return ()=>Reflect.apply(nativeAbort,signal,[]);
25
+ const s=record(signal,['aborted','throwIfAborted'],[],'signal');
26
+ if(s.aborted!==undefined&&typeof s.aborted!=='boolean'||s.throwIfAborted!==undefined&&typeof s.throwIfAborted!=='function')throw Error('Invalid Git tag plan signal');
27
+ return ()=>{if(s.aborted){const e=Error('Git tag verification aborted');e.name='AbortError';throw e;}if(s.throwIfAborted)Reflect.apply(s.throwIfAborted,signal,[]);};
28
+ }
29
+
30
+ // Pure synchronous plan over a raw commit BODY (<=2 MiB), copied before even
31
+ // inputs descriptor/prototype traps. Exact own-data plain/null-prototype inputs
32
+ // require target, tag, tagger and message; only objectFormat and signal are optional.
33
+ // The <=64 KiB strict UTF-8 message, scalar target/tag and full tagger identity are
34
+ // captured and validated before the first cancellation callback. Signal policy
35
+ // matches git-tag-object: intrinsic native checks or captured cooperative own-data
36
+ // aborted/throwIfAborted; caller getters are never invoked (no Proxy isolation).
37
+ // Commit syntax/hash is authenticated, not referenced-object existence, repository
38
+ // authorization/freshness or ref absence. No I/O, lookup, signing or publication.
39
+ // All result records are frozen EXCEPT the owned mutable object.body Buffer.
40
+ // A later publisher MUST recompute/verify that body's OID and revalidate ref state;
41
+ // freezing the wrapper does not authenticate subsequent Buffer mutations.
42
+ export function createVerifiedTagPlan(commitBody,inputs={}){
43
+ if(!Buffer.isBuffer(commitBody))throw Error('Git commit body must be a Buffer');
44
+ if(commitBody.length>MAX_COMMIT_BYTES)throw Error('Git commit body byte limit exceeded');
45
+ const body=owned(commitBody);
46
+ const r=record(inputs,['objectFormat','target','tag','tagger','message','signal'],['target','tag','tagger','message'],'input');
47
+ const objectFormat=r.objectFormat===undefined?'sha1':r.objectFormat,target=r.target,tag=r.tag;
48
+ const tagger=record(r.tagger,['name','email','timestamp','timezone'],['name','email','timestamp','timezone'],'tagger');
49
+ for(const key of ['name','email','timezone'])if(typeof tagger[key]!=='string')throw Error('Git identity '+key+' must be a string');
50
+ if(typeof tagger.timestamp!=='number')throw Error('Invalid Git identity timestamp');
51
+ let message=r.message;
52
+ if(Buffer.isBuffer(message)){
53
+ if(message.length>MAX_MESSAGE_BYTES)throw Error('Git tag message byte limit exceeded');
54
+ message=owned(message);
55
+ }
56
+ // Delegate every scalar/UTF-8/name/identity/byte-limit validation on owned data,
57
+ // with no caller signal involved. No invalid capture can invoke a callback.
58
+ encodeGitTag({object:target,tag,tagger,message},{objectFormat});
59
+ const check=abortCheck(r.signal);
60
+ // The commit parser's legacy aborted read is adapted to our captured policy;
61
+ // no read of a caller-controlled aborted getter can precede the body snapshot.
62
+ const commitSignal={get aborted(){check();return false;}};
63
+ const verified=parseVerifiedCommit(body,{oid:target,objectFormat,signal:commitSignal});
64
+ const encoded=encodeGitTag({object:verified.oid,tag,tagger,message},{objectFormat});
65
+ check();
66
+ const canonical=parseVerifiedGitTag(encoded.body,{oid:encoded.oid,objectFormat});
67
+ check();
68
+ const ref='refs/tags/'+canonical.tag;
69
+ // JSON tuple framing is unambiguous; Git target OID already binds targetTree.
70
+ const id=createHash('sha256').update(JSON.stringify(['dsh-vcs:verified-tag-plan:v1',objectFormat,verified.oid,canonical.oid,ref]),'utf8').digest('hex');
71
+ return Object.freeze({id,action:'tag-create',objectFormat,target:verified.oid,targetTree:verified.tree,tag:canonical.tag,ref,tagger:canonical.tagger,message:canonical.message,messageBytes:canonical.messageBytes,object:Object.freeze({oid:canonical.oid,body:encoded.body})});
72
+ }
@@ -0,0 +1,31 @@
1
+ import {createConfirmedOperationCoordinator} from './confirmed-operation.mjs';
2
+ import {encodeGitTag} from './src/git-tag-object.mjs';
3
+ const invalid=message=>Object.assign(new Error(message),{code:'vcs/tag-create-confirmation-invalid'});
4
+ function record(value,fields){
5
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw invalid('Expected own-data record.');
6
+ const out=Object.create(null);
7
+ for(const key of Reflect.ownKeys(value)){
8
+ if(!fields.includes(key))throw invalid('Unexpected field.');
9
+ const d=Object.getOwnPropertyDescriptor(value,key);if(!d||!Object.hasOwn(d,'value'))throw invalid('Accessors forbidden.');out[key]=d.value;
10
+ }
11
+ for(const key of fields)if(!Object.hasOwn(out,key))throw invalid('Missing '+key+'.');
12
+ return out;
13
+ }
14
+ function capture(address){
15
+ const saved=record(address,['sessionId','repositoryId','name','tagger','message']);
16
+ saved.tagger=record(saved.tagger,['name','email','timestamp','timezone']);
17
+ if(typeof saved.sessionId!=='string'||!saved.sessionId||typeof saved.repositoryId!=='string'||!saved.repositoryId||typeof saved.message!=='string')throw invalid('Session, repository and string message required.');
18
+ try{encodeGitTag({object:'1'.repeat(40),tag:saved.name,tagger:saved.tagger,message:saved.message});}catch{throw invalid('Invalid tag name, identity or message.');}
19
+ Object.freeze(saved.tagger);return Object.freeze(saved);
20
+ }
21
+ // Internal factory only: authenticated bindings come from caller. No RPC/UI,
22
+ // external-process atomicity, signing or automatic rollback is implied.
23
+ export function createTagCreateCoordinator({api,now=Date.now,ttlMs=60000,maxTokens=32}){
24
+ const coordinator=createConfirmedOperationCoordinator({operationKind:'tag-create',now,ttlMs,maxTokens,
25
+ prepare:(repository,{address,signal})=>api.prepareTagCreate({type:repository.type,root:repository.root},{name:address.name,tagger:address.tagger,message:address.message,signal}),
26
+ execute:(repository,request)=>api.applyTagCreate({type:repository.type,root:repository.root},request),
27
+ project:s=>({action:'tag-create',name:s.name,ref:s.ref,objectFormat:s.objectFormat,head:s.head,currentRef:s.currentRef,targetTree:s.targetTree,tagger:{name:s.tagger.name,email:s.tagger.email,timestamp:s.tagger.timestamp,timezone:s.tagger.timezone},message:s.message,messageBytes:s.messageBytes,object:{oid:s.object.oid},planId:s.planId}),
28
+ invalidCode:'vcs/tag-create-confirmation-invalid',unknownCode:'vcs/tag-create-outcome-unknown',
29
+ unknownMessage:'Tag creation started but its final result is unknown. Objects or refs may exist. Refresh and inspect refs and HEAD. Never retry automatically, delete objects or refs, or roll back.'});
30
+ return {async prepare(address,binding){return coordinator.prepare(capture(address),binding);},confirm:(address,binding)=>coordinator.confirm(address,binding),invalidate:entry=>coordinator.invalidate(entry),clear:()=>coordinator.clear()};
31
+ }
@@ -0,0 +1,215 @@
1
+ // CURRENT HEAD tag preview and single-use internal apply. Observation barriers
2
+ // detect observed changes, not mutation-and-restoration or hostile process atomicity.
3
+ import * as fs from 'node:fs/promises';
4
+ import {constants} from 'node:fs';
5
+ import path from 'node:path';
6
+ import {createHash} from 'node:crypto';
7
+ import {inflateSync} from 'node:zlib';
8
+ import {publishTagObject} from './tag-object-publish.mjs';
9
+ import {createLocalTag} from './git-tag-create.mjs';
10
+ const snapshots=new WeakMap();
11
+ import {git as safeGit} from './local-command.mjs';
12
+ import {readLatestCommit} from './latest-commit.mjs';
13
+ import {encodeGitTag} from './src/git-tag-object.mjs';
14
+ import {createVerifiedTagPlan} from './src/verified-tag-plan.mjs';
15
+ import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
16
+ const fail=message=>Object.assign(new Error(message),{code:'vcs/tag-create-preview'});
17
+ const check=()=>currentOperationBudget().throwIfExpired();
18
+ const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
19
+ const identity=s=>[s.dev,s.ino,s.birthtimeNs].map(String);
20
+ const version=s=>[...identity(s),s.size,s.mtimeNs,s.ctimeNs,s.mode].map(String);
21
+ const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
22
+ function record(value,keys,required,label){
23
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw fail('Invalid '+label+' record');
24
+ const out=Object.create(null);
25
+ for(const key of Reflect.ownKeys(value)){
26
+ if(typeof key!=='string'||!keys.includes(key))throw fail('Unsupported '+label+' field');
27
+ const d=Object.getOwnPropertyDescriptor(value,key);
28
+ if(!d||!Object.hasOwn(d,'value'))throw fail(label+' requires own data properties');
29
+ out[key]=d.value;
30
+ }
31
+ for(const key of required)if(!Object.hasOwn(out,key))throw fail('Missing '+label+' '+key);
32
+ return out;
33
+ }
34
+ async function directory(file){
35
+ check();const s=await fs.lstat(file,{bigint:true});
36
+ if(!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(file)!==file)throw fail('Canonical metadata directory required');
37
+ return s;
38
+ }
39
+ async function raw(file,max){
40
+ check();const before=await fs.lstat(file,{bigint:true});
41
+ if(!plain(before)||before.size>BigInt(max))throw fail('Bounded single-link metadata file required');
42
+ const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW||0));
43
+ try{
44
+ const opened=await handle.stat({bigint:true});
45
+ if(!plain(opened)||!equal(version(before),version(opened)))throw fail('Stale metadata opening');
46
+ const bytes=Buffer.alloc(max+1);let n=0;
47
+ while(n<bytes.length){check();const r=await handle.read(bytes,n,bytes.length-n,n);if(!r.bytesRead)break;n+=r.bytesRead;}
48
+ const after=await handle.stat({bigint:true}),now=await fs.lstat(file,{bigint:true});
49
+ if(n>max||!plain(now)||!equal(version(opened),version(after))||!equal(version(after),version(now))||BigInt(n)!==after.size)throw fail('Stale metadata reading');
50
+ return [version(after),bytes.subarray(0,n).toString('hex')];
51
+ }finally{await handle.close();}
52
+ }
53
+ const forbidden=new Set(['packed-refs','reftable','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()));
54
+ async function metadata(git){
55
+ const rows=[];let nodes=0;
56
+ async function visit(file,rel){
57
+ check();if(++nodes>20000)throw fail('Metadata inspection limit exceeded');
58
+ const key=rel.toLowerCase();
59
+ if(forbidden.has(key)||key.endsWith('.lock')||key.endsWith('.promisor')||key.startsWith('sharedindex.')||key.startsWith('hooks/')&&!key.endsWith('.sample'))throw fail('Unsupported repository metadata: '+rel);
60
+ const s=await fs.lstat(file,{bigint:true});
61
+ if(s.isSymbolicLink()||(!s.isDirectory()&&!plain(s))||await fs.realpath(file)!==file)throw fail('Linked or special repository metadata');
62
+ rows.push([rel,version(s)]);
63
+ if(s.isDirectory()){
64
+ const entries=await fs.readdir(file);
65
+ // Reject an excessive immediate fanout before sorting or visiting any child.
66
+ if(entries.length>20000-nodes)throw fail('Metadata inspection limit exceeded');
67
+ for(const name of entries.sort())await visit(path.join(file,name),rel?rel+'/'+name:name);
68
+ }
69
+ }
70
+ await visit(git,'');return rows;
71
+ }
72
+ function absence(rows,name){
73
+ const entries=new Map(rows);
74
+ for(const parts of [['refs','tags',...name.split('/')],['logs','refs','tags',...name.split('/')]]){
75
+ let parent='';
76
+ for(let i=0;i<parts.length;i++){
77
+ const target=parent?parent+'/'+parts[i]:parts[i];
78
+ const matches=rows.filter(([rel])=>rel.toLowerCase()===target.toLowerCase());
79
+ if(!matches.length)break;
80
+ if(matches.length!==1||matches[0][0]!==target||i===parts.length-1)throw fail('Portable target namespace collision');
81
+ const v=entries.get(target);
82
+ if((Number(v[6])&0o170000)!==0o040000)throw fail('Target prefix or reflog collision');
83
+ parent=target;
84
+ }
85
+ }
86
+ for(const expected of ['HEAD','config','refs','logs'])if(rows.some(([rel])=>rel.toLowerCase()===expected.toLowerCase()&&rel!==expected))throw fail('Noncanonical metadata spelling');
87
+ }
88
+ async function capture(root,name,created=false){
89
+ const rootStat=await directory(root),git=path.join(root,'.git'),gitStat=await directory(git);
90
+ const rows=await metadata(git);if(!created)absence(rows,name);
91
+ const head=await raw(path.join(git,'HEAD'),4096),config=await raw(path.join(git,'config'),256*1024);
92
+ const closing=await metadata(git);if(!created)absence(closing,name);
93
+ if(!equal(rows,closing)||!equal(identity(rootStat),identity(await directory(root)))||!equal(identity(gitStat),identity(await directory(git))))throw fail('Stale repository during capture');
94
+ check();return {root:identity(rootStat),git:identity(gitStat),head,config,rows};
95
+ }
96
+ /** Exact frozen safe summary only: no raw Buffer, private capability or mutation.
97
+ * Embedded born symbolic HEAD only; packed refs/shared repositories/active hooks
98
+ * and unsupported config are refused. No index or worktree body is opened.
99
+ * All reads share the inherited <=15 second deadline; no temp/object/ref writes.
100
+ */
101
+ export async function prepareTagCreate(repo,options={}){
102
+ const r=record(repo,['type','root'],['type','root'],'repository');
103
+ const o=record(options,['name','tagger','message','signal'],['name','tagger','message'],'options');
104
+ if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root)throw fail('Canonical Git root required');
105
+ const tagger=record(o.tagger,['name','email','timestamp','timezone'],['name','email','timestamp','timezone'],'tagger');
106
+ let message=o.message;
107
+ if(Buffer.isBuffer(message)){
108
+ if(message.length>64*1024)throw fail('Git tag message byte limit exceeded');
109
+ const copy=Buffer.alloc(message.length);Buffer.prototype.copy.call(message,copy);message=copy;
110
+ }
111
+ // Pure encoder validates every name/identity/message scalar before any I/O.
112
+ encodeGitTag({object:'1'.repeat(40),tag:o.name,tagger,message});
113
+ if(o.signal!==undefined){try{Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get,o.signal,[]);}catch{throw fail('Native AbortSignal required');}}
114
+ const name=o.name,ref='refs/tags/'+name;
115
+ return withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
116
+ const before=await capture(r.root,name);
117
+ const first=await readLatestCommit({type:r.type,root:r.root});
118
+ // Only the authenticated full fixed OID is ever passed as the raw target.
119
+ if(!(['sha1','sha256'].includes(first.objectFormat))||!(first.objectFormat==='sha1'?/^[a-f0-9]{40}$/:/^[a-f0-9]{64}$/).test(first.head))throw fail('Invalid fixed HEAD');
120
+ const body=await safeGit(r.root,['cat-file','commit',first.head],2*1024*1024);
121
+ const plan=createVerifiedTagPlan(body,{objectFormat:first.objectFormat,target:first.head,tag:name,tagger,message,signal:currentOperationBudget().signal});
122
+ const last=await readLatestCommit({type:r.type,root:r.root});
123
+ const after=await capture(r.root,name);
124
+ if(!equal(first,last)||plan.targetTree!==first.tree||!equal(before,after))throw fail('Stale repository changed during tag preview');
125
+ check();const summary=Object.freeze({action:'tag-create',name,ref,objectFormat:first.objectFormat,head:first.head,currentRef:first.ref,targetTree:plan.targetTree,tagger:plan.tagger,message:plan.message,messageBytes:plan.messageBytes,object:Object.freeze({oid:plan.object.oid}),planId:plan.id});
126
+ snapshots.set(summary,{root:r.root,name,ref,original:before,facts:first,targetBody:Buffer.from(body),tagBody:Buffer.from(plan.object.body),tagOid:plan.object.oid});
127
+ return summary;
128
+ });
129
+ }
130
+ // Internal writer: caller MUST hold the repository writer exclusion for this entire
131
+ // call. Exact-object identity is a one-use capability, not a serializable token.
132
+ // Checks observe filesystem versions; external ABA and hostile directory swaps are
133
+ // not isolated by portable Node path APIs. Never roll back or auto-retry after start.
134
+ export async function applyTagCreate(repo,options={}){
135
+ // Burn before validating ANY other input, callback, cancellation or first await.
136
+ const descriptor=options&&Object.getOwnPropertyDescriptor(options,'snapshot');
137
+ const snapshot=descriptor&&Object.hasOwn(descriptor,'value')?descriptor.value:undefined;
138
+ const saved=snapshots.get(snapshot);snapshots.delete(snapshot);
139
+ if(!saved)throw fail('Invalid or consumed tag snapshot');
140
+ const o=record(options,['snapshot','signal','assertAuthorized','onStart'],['snapshot','assertAuthorized','onStart'],'apply options');
141
+ const r=record(repo,['type','root'],['type','root'],'repository');
142
+ if(r.type!=='git'||r.root!==saved.root||typeof o.assertAuthorized!=='function'||typeof o.onStart!=='function')throw fail('Snapshot repository or callbacks mismatch');
143
+ if(o.signal!==undefined){try{Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get,o.signal,[]);}catch{throw fail('Native AbortSignal required');}}
144
+ let started=false;
145
+ try{return await withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
146
+ const {root,name,ref,original,facts,targetBody,tagBody,tagOid}=saved,git=path.join(root,'.git');
147
+ const objectPath='objects/'+tagOid.slice(0,2)+'/'+tagOid.slice(2),logPath='logs/'+ref;
148
+ const effectiveConfig=()=>safeGit(root,['--git-dir='+git,'--work-tree='+root,'config','--no-includes','--null','--list'],256*1024);
149
+ const configBaseline=await effectiveConfig();
150
+ const isDir=v=>(Number(v[6])&0o170000)===0o040000;
151
+ const ancestors=files=>new Set(files.flatMap(file=>{const parts=file.split('/'),out=[''];for(let i=1;i<parts.length;i++)out.push(parts.slice(0,i).join('/'));return out;}));
152
+ let appended,createdRows,cas=false;
153
+ function envelope(rows,base,files){
154
+ const before=new Map(base),now=new Map(rows),dirs=ancestors(files);
155
+ for(const [p,v] of before){const n=now.get(p);
156
+ if(!n||!(dirs.has(p)&&isDir(v)?equal([...v.slice(0,3),v[6]],[...n.slice(0,3),n[6]]):equal(v,n)))throw fail('Original metadata changed: '+p);
157
+ }
158
+ for(const [p,v] of rows)if(!before.has(p)&&!files.includes(p)&&!(dirs.has(p)&&isDir(v)))throw fail('Foreign metadata addition: '+p);
159
+ }
160
+ async function exactObject(){
161
+ const [,hex]=await raw(path.join(git,...objectPath.split('/')),128*1024+1024*1024),compressed=Buffer.from(hex,'hex');
162
+ const expected=Buffer.concat([Buffer.from('tag '+tagBody.length+'\0'),tagBody]);let inflated;
163
+ try{inflated=inflateSync(compressed,{maxOutputLength:expected.length,info:true});}catch{throw fail('Invalid appended tag compression');}
164
+ if(inflated.engine.bytesWritten!==compressed.length||!inflated.buffer.equals(expected)||createHash(facts.objectFormat).update(inflated.buffer).digest('hex')!==tagOid)throw fail('Appended tag raw hash/stream mismatch');
165
+ }
166
+ async function verify(phase){
167
+ check();if(!(await effectiveConfig()).equals(configBaseline))throw fail('Effective Git configuration changed');
168
+ const state=await capture(root,name,phase==='cas');
169
+ if(!equal(state.root,original.root)||!equal(state.git,original.git)||!equal(state.head,original.head)||!equal(state.config,original.config))throw fail('Original HEAD/config/identity changed');
170
+ if(phase==='original'){if(!equal(state,original))throw fail('Original metadata changed');}
171
+ else{
172
+ const allowed=phase==='cas'?[objectPath,ref,...(new Map(state.rows).has(logPath)?[logPath]:[])]:[objectPath];
173
+ envelope(state.rows,original.rows,allowed);
174
+ await exactObject();
175
+ if(appended)envelope(state.rows,appended,phase==='cas'?allowed.filter(p=>p!==objectPath):[]);
176
+ if(phase==='cas'&&new Map(state.rows).has(ref)){
177
+ const [,hex]=await raw(path.join(git,...ref.split('/')),4096);
178
+ if(Buffer.from(hex,'hex').toString()!==tagOid+'\n')throw fail('Created ref changed');
179
+ if(new Map(state.rows).has(logPath)){
180
+ const [,logHex]=await raw(path.join(git,...logPath.split('/')),4096);
181
+ if(!new RegExp('^'+'0'.repeat(tagOid.length)+' '+tagOid+' Dsh <dsh@localhost> [0-9]+ [+-][0-9]{4}\\tdsh: create local tag\\n$').test(Buffer.from(logHex,'hex').toString()))throw fail('Created reflog changed');
182
+ }
183
+ if(createdRows&&!equal(state.rows,createdRows))throw fail('Created metadata changed after verification');
184
+ createdRows=state.rows;
185
+ }else if(createdRows)throw fail('Created tag disappeared');
186
+ }
187
+ const [,branchHex]=await raw(path.join(git,...facts.ref.split('/')),4096);
188
+ if(Buffer.from(branchHex,'hex').toString()!==facts.head+'\n')throw fail('Current HEAD facts changed');
189
+ const after=await capture(root,name,phase==='cas');
190
+ if(!equal(after,state))throw fail('Metadata changed during validation');
191
+ check();return state.rows;
192
+ }
193
+ const authorize=async()=>{
194
+ check();const signal=currentOperationBudget().signal;let abort;
195
+ try{await Promise.race([Promise.resolve(o.assertAuthorized()),new Promise((_,reject)=>{abort=()=>reject(signal.reason);signal.addEventListener('abort',abort,{once:true});if(signal.aborted)abort();})]);check();}
196
+ finally{if(abort)signal.removeEventListener('abort',abort);}
197
+ };
198
+ const start=()=>{if(started)return;started=true;return o.onStart();};
199
+ const originalAuth=async()=>{await verify('original');await authorize();await verify('original');};
200
+ if(!equal(await readLatestCommit({type:'git',root}),facts))throw fail('Current repository facts changed');
201
+ await originalAuth();
202
+ await publishTagObject({gitDirectory:git,objectFormat:facts.objectFormat,target:{oid:facts.head,body:targetBody},tag:{oid:tagOid,body:tagBody},signal:currentOperationBudget().signal,
203
+ assertAuthorized:async()=>{if(!started)await originalAuth();else await authorize();},onStart:start});
204
+ appended=await verify('append');
205
+ await createLocalTag({type:'git',root},{ref,expectedTagOid:tagOid,objectFormat:facts.objectFormat,signal:currentOperationBudget().signal,
206
+ assertAuthorized:async()=>{const phase=cas?'cas':'append';await verify(phase);await authorize();await verify(phase);},
207
+ onStart:()=>{cas=true;return start();}});
208
+ await verify('cas');if(!createdRows)throw fail('Created tag missing');
209
+ await authorize();await verify('cas');check();
210
+ return {name,ref,tagOid,commit:facts.head,currentRef:facts.ref};
211
+ });}catch(cause){
212
+ if(!started)throw cause;
213
+ throw Object.assign(new Error('Append-only tag creation started; inspect repository before further action. Never roll back or retry automatically.',{cause}),{code:'vcs/tag-create-outcome-unknown',appendOnly:true,outcomeUnknown:true});
214
+ }
215
+ }
@@ -0,0 +1,49 @@
1
+ import {parseVerifiedCommit} from './src/verified-commit.mjs';
2
+ import {parseVerifiedGitTag} from './src/git-tag-object.mjs';
3
+ import {storeCapturedObject} from './git-object-store.mjs';
4
+ import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
5
+
6
+ const invalid=message=>Object.assign(new Error(message),{code:'vcs/tag-object-invalid'});
7
+ function record(value,required,optional=[]){
8
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw invalid('Expected own-data record.');
9
+ const out=Object.create(null);
10
+ for(const key of Reflect.ownKeys(value)){
11
+ if(!required.includes(key)&&!optional.includes(key))throw invalid('Unexpected field.');
12
+ const d=Object.getOwnPropertyDescriptor(value,key);if(!d||!Object.hasOwn(d,'value'))throw invalid('Accessors forbidden.');out[key]=d.value;
13
+ }
14
+ for(const key of required)if(!Object.hasOwn(out,key))throw invalid('Missing '+key+'.');
15
+ return out;
16
+ }
17
+ const length=Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),'byteLength').get;
18
+ function captureObject(value,max){
19
+ const row=record(value,['oid','body']);
20
+ if(!Buffer.isBuffer(row.body))throw invalid('Object body must be a Buffer.');
21
+ const size=Reflect.apply(length,row.body,[]);if(size>max)throw invalid('Object body bound exceeded.');
22
+ const body=Buffer.alloc(size);Reflect.apply(Uint8Array.prototype.set,body,[row.body]);return {oid:row.oid,body};
23
+ }
24
+ // Internal append-only adapter. Caller verifies repository safety, target existence,
25
+ // ref absence, writer exclusion and authorization independently. No refs or target writes.
26
+ // Both bounded bodies are owned before callbacks/awaits; no hostile Proxy/shared-memory isolation.
27
+ export async function publishTagObject(input){
28
+ const o=record(input,['gitDirectory','objectFormat','target','tag','assertAuthorized','onStart'],['signal']);
29
+ const target=captureObject(o.target,2*1024*1024),tag=captureObject(o.tag,128*1024);
30
+ if(typeof o.gitDirectory!=='string'||!['sha1','sha256'].includes(o.objectFormat)||typeof o.assertAuthorized!=='function'||typeof o.onStart!=='function')throw invalid('Invalid publication options.');
31
+ if(o.signal!==undefined){try{Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get,o.signal,[]);}catch{throw invalid('Native AbortSignal required.');}}
32
+ let started=false;
33
+ try{return await withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
34
+ const budget=currentOperationBudget(),check=()=>budget.throwIfExpired();check();
35
+ try{
36
+ const verified=parseVerifiedCommit(target.body,{oid:target.oid,objectFormat:o.objectFormat,signal:budget.signal});
37
+ const annotated=parseVerifiedGitTag(tag.body,{oid:tag.oid,objectFormat:o.objectFormat,signal:budget.signal});
38
+ if(annotated.object!==verified.oid)throw invalid('Tag target mismatch.');
39
+ }catch(cause){if(budget.signal.aborted)throw cause;throw invalid('Invalid authenticated target or tag: '+cause.message);}
40
+ const authorize=async()=>{check();await o.assertAuthorized();check();};
41
+ const start=()=>{if(started)return;started=true;const result=o.onStart();if(result&&typeof result.then==='function'){Promise.resolve(result).catch(()=>{});throw invalid('onStart must be synchronous.');}};
42
+ await authorize();
43
+ const result=await storeCapturedObject({gitDirectory:o.gitDirectory,objectFormat:o.objectFormat,type:'tag',bytes:tag.body,signal:budget.signal,assertAuthorized:authorize,onStart:start});
44
+ await authorize();if(result.oid!==tag.oid)throw invalid('Stored tag OID mismatch.');return {oid:result.oid,created:result.created};
45
+ });}catch(cause){
46
+ if(!started)throw cause;
47
+ throw Object.assign(new Error('Append-only tag publication started; inspect objects before further action. Never delete objects or retry automatically.',{cause}),{code:'vcs/tag-object-outcome-unknown',appendOnly:true,outcomeUnknown:true});
48
+ }
49
+ }
package/vcs.mjs CHANGED
@@ -1,4 +1,11 @@
1
1
  import {parseConflictStages} from './conflict-stages.mjs';
2
+ export {prepareCommitPreview,applyCommitPreview,prepareAmendPreview,applyAmendPreview} from './commit-preview.mjs';
3
+ export {readLatestCommit} from './latest-commit.mjs';
4
+ export {prepareBranchCreate,applyBranchCreate} from './branch-create-preview.mjs';
5
+ export {prepareTagCreate,applyTagCreate} from './tag-create-preview.mjs';
6
+ export {prepareLightweightTagCreate,applyLightweightTagCreate} from './lightweight-tag-preview.mjs';
7
+ export {prepareBranchDelete} from './branch-delete-preview.mjs';
8
+ export {prepareSelectedIndexUnstage,applyIndexUnstage,prepareSelectedIndexStage,applyIndexStage,preparePartialIndexStage,selectPartialIndexStage,preparePartialIndexUnstage,selectPartialIndexUnstage,applyPartialIndexUnstage,prepareLineIndexStage,selectLineIndexStage,applyLineIndexStage,prepareLineIndexUnstage,selectLineIndexUnstage,applyLineIndexUnstage} from './index-change.mjs';
2
9
  import {parseCommitSignature} from './src/commit-signature.mjs';
3
10
  import {parseSvnIdentity} from './src/svn-identity.mjs';
4
11
  import {prepareRaster} from './image-preview.mjs';
@@ -17,6 +24,7 @@ import {createHistoricalAccess,validateHistoricalPath} from './src/historical-ac
17
24
  import {withComparisonPreview} from './src/preview-capabilities.mjs';
18
25
  import {searchContentPage} from './src/content-search.mjs';
19
26
  import {withOperationBudget} from './src/operation-budget.mjs';
27
+ import {parseReflog, REFLOG_FORMAT, REFLOG_MAX_OUTPUT} from './src/reflog.mjs';
20
28
 
21
29
  const historicalAccess = createHistoricalAccess({run:git});
22
30
  /** Host invalidates object bytes on grant replacement, expiry and plugin disposal. */
@@ -257,6 +265,27 @@ export async function listReferences(repo,{signal}={}){
257
265
  return {references:parseReferences(raw.toString('utf8'))};
258
266
  }
259
267
 
268
+ /** One read-only HEAD reflog snapshot; selectors are display metadata, never inputs. */
269
+ export async function listReflog(repo,{signal}={}) {
270
+ return withOperationBudget({signal},async()=>{
271
+ signal?.throwIfAborted();
272
+ repo=await checkedGitRepo(repo,signal,'Reflog supports Git only',undefined,false);
273
+ const run=args=>git(repo.root,args,REFLOG_MAX_OUTPUT,{signal});
274
+ // Prove an unborn HEAD before reading: never reinterpret a show failure as empty.
275
+ // Existing HEAD without a log produces successful empty output below.
276
+ if(await resolveHeadCommit(run)===null) {
277
+ try { await run(['reflog','exists','HEAD']); }
278
+ catch(missing) {
279
+ if(missing.code==='VCS_COMMAND'&&missing.exitCode===1)return {entries:[],truncated:false};
280
+ throw missing;
281
+ }
282
+ }
283
+ const raw=await run(['reflog','show','-z','--no-show-signature','--encoding=UTF-8','--date=iso-strict','--max-count=201','--format='+REFLOG_FORMAT,'HEAD','--']);
284
+ signal?.throwIfAborted();
285
+ return parseReflog(raw);
286
+ });
287
+ }
288
+
260
289
  const STASH_FORMAT='%H%x00%gs%x00%gd';
261
290
  export async function listStashes(repo,{signal}={}){
262
291
  signal?.throwIfAborted();repo=await checkedGitRepo(repo,signal,'Stash supports Git only');