@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
package/docs/RELEASING.md CHANGED
@@ -20,6 +20,8 @@
20
20
  npm run verify:package
21
21
  npm run test:install
22
22
 
23
+ `npm test` 与 TAP 发布运行器均明确以最多 2 个测试文件进程执行:遍历全部 `test/*.test.mjs`,每个文件一次,保留文件内的并发/竞争测试,不过滤、不重试、不跳过。该调度避免机器核心数放大真实 Git/磁盘竞争,生产请求仍使用原 15 秒共同预算。运行器每次开始先移除旧成功摘要,只有本轮全量零失败/取消/跳过/todo 才生成新摘要。历史无界并行压力运行的失败保留,不用低并发通过倒写为历史全绿。
24
+
23
25
  测试失败或跳过须调查;隔离安装只检查包和宿主注册,不是用户实际 DSH 验收。
24
26
 
25
27
  新增宿主兼容声明时,还需对精确宿主执行隔离检查:
@@ -0,0 +1,151 @@
1
+ // Internal append-only primitive. No RPC, subprocess, Index, refs or worktree writes.
2
+ import {constants} from 'node:fs';
3
+ import {lstat, realpath, open, mkdir, link, unlink} from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import {createHash, randomUUID} from 'node:crypto';
6
+ import {deflateSync, inflateSync} from 'node:zlib';
7
+ import {currentOperationBudget} from './src/operation-budget.mjs';
8
+
9
+ export const MAX_BLOB_BYTES = 2 * 1024 * 1024;
10
+ const MAX_LOOSE_BYTES = MAX_BLOB_BYTES + 65536;
11
+ const fail = (kind, message, cause) => Object.assign(new Error(message, {cause}), {code:'vcs/blob-' + kind});
12
+ const same = (a,b) => a.dev === b.dev && a.ino === b.ino;
13
+ const plain = s => s.isFile() && !s.isSymbolicLink() && s.nlink === 1n;
14
+ const normalized = p => process.platform === 'win32' ? p.toLowerCase() : p;
15
+ const hash = (format, bytes) => createHash(format).update(bytes).digest('hex');
16
+
17
+ /**
18
+ * Capture a Buffer synchronously before the first await, then store its exact Git
19
+ * blob representation. Returns {oid,created}; sha1 and sha256 are the only formats.
20
+ * The caller supplies an already validated embedded canonical .git directory and
21
+ * mandatory authorization and synchronous onStart callbacks. onStart precedes even
22
+ * fanout mkdir. All errors after that notification are append-only outcome-unknown;
23
+ * a published object is NEVER removed, including after cancellation/revocation.
24
+ * Existing loose objects must be plain single-link files with bounded compressed
25
+ * and inflated size and exact raw content/hash. Packed-only objects are not read:
26
+ * creating a correct loose duplicate is safe. Alternates are not supported.
27
+ *
28
+ * Requires local filesystem exclusive-create and atomic hardlink NOREPLACE
29
+ * semantics. Unsupported hardlinks fail closed (no rename/copy fallback). Identity
30
+ * checks are conservative, not isolation against malicious concurrent directory
31
+ * replacement; Node has no portable dirfd-relative filesystem transaction. Caller
32
+ * must exclude hostile filesystem mutation. File sync is attempted, but directory
33
+ * fsync/crash durability and network filesystem semantics are NOT guaranteed.
34
+ */
35
+ export async function storeCapturedBlob({gitDirectory, objectFormat, bytes, signal, assertAuthorized, onStart} = {}) {
36
+ if (!Buffer.isBuffer(bytes)) throw fail('invalid','bytes must be a Buffer.');
37
+ if (bytes.length > MAX_BLOB_BYTES) throw fail('too-large','Blob exceeds 2MiB.');
38
+ const captured = Buffer.from(bytes); // Do not move below any await/callback.
39
+ if (!['sha1','sha256'].includes(objectFormat) || typeof gitDirectory !== 'string' ||
40
+ !path.isAbsolute(gitDirectory) || path.basename(gitDirectory) !== '.git' ||
41
+ typeof assertAuthorized !== 'function' || typeof onStart !== 'function') {
42
+ throw fail('invalid','Canonical embedded .git, exact objectFormat and authorization/start callbacks are required.');
43
+ }
44
+ const budget = currentOperationBudget();
45
+ const check = () => { signal?.throwIfAborted(); budget?.throwIfExpired(); };
46
+ const authorize = async () => { check(); await assertAuthorized(); check(); };
47
+ const directory = path.resolve(gitDirectory), objects = path.join(directory,'objects');
48
+ if(normalized(directory) !== normalized(gitDirectory))throw fail('unsafe','gitDirectory must be canonical, not a path alias.');
49
+ const raw = Buffer.concat([Buffer.from('blob ' + captured.length + '\0'),captured]);
50
+ const oid = hash(objectFormat,raw), fanout = path.join(objects,oid.slice(0,2)), target = path.join(fanout,oid.slice(2));
51
+ let started = false, handle, owned, temporary;
52
+ const directories = new Map();
53
+ const verifyDirectory = async p => {
54
+ check();
55
+ const s = await lstat(p,{bigint:true});
56
+ if (!s.isDirectory() || s.isSymbolicLink() || normalized(await realpath(p)) !== normalized(p) ||
57
+ (directories.has(p) && !same(directories.get(p),s))) throw fail('unsafe','Noncanonical or changed object directory.');
58
+ directories.set(p,s);
59
+ };
60
+ const absent = async p => {
61
+ try { await lstat(p); } catch(e) { if(e.code === 'ENOENT')return; throw e; }
62
+ throw fail('unsafe','Alternate or shared object storage is unsupported.');
63
+ };
64
+ const verifyStorage = async () => {
65
+ await verifyDirectory(directory); await verifyDirectory(objects);
66
+ await absent(path.join(directory,'commondir'));
67
+ const info = path.join(objects,'info');
68
+ try { await verifyDirectory(info); } catch(e) { if(e.code !== 'ENOENT')throw e; }
69
+ await absent(path.join(info,'alternates')); await absent(path.join(info,'http-alternates'));
70
+ check();
71
+ };
72
+ const validateExisting = async () => {
73
+ await verifyStorage(); await verifyDirectory(fanout);
74
+ let entry;
75
+ try { entry = await lstat(target,{bigint:true}); } catch(e) { if(e.code === 'ENOENT')return false; throw e; }
76
+ if(!plain(entry))throw fail('unsafe','Object must be a plain single-link file.');
77
+ if(entry.size > BigInt(MAX_LOOSE_BYTES))throw fail('corrupt','Compressed object exceeds bound.');
78
+ const file = await open(target,constants.O_RDONLY | (constants.O_NOFOLLOW || 0));
79
+ try {
80
+ const before = await file.stat({bigint:true});
81
+ if(!plain(before) || !same(entry,before))throw fail('unsafe','Object identity changed while opening.');
82
+ if(before.size > BigInt(MAX_LOOSE_BYTES))throw fail('corrupt','Compressed object exceeds bound.');
83
+ const buffer = Buffer.alloc(Number(before.size) + 1); let length = 0;
84
+ while(length < buffer.length) {
85
+ check(); const {bytesRead} = await file.read(buffer,length,buffer.length-length,length);
86
+ if(!bytesRead)break; length += bytesRead;
87
+ }
88
+ const after = await file.stat({bigint:true}), current = await lstat(target,{bigint:true});
89
+ if(!plain(after) || !plain(current) || !same(before,current) || length !== Number(before.size) ||
90
+ before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs)throw fail('unsafe','Object changed while reading.');
91
+ let inflated;
92
+ try { inflated = inflateSync(buffer.subarray(0,length),{maxOutputLength:raw.length,info:true}); }
93
+ catch(e) { throw fail('corrupt','Invalid or oversized loose object.',e); }
94
+ if(inflated.engine.bytesWritten !== length || !inflated.buffer.equals(raw) || hash(objectFormat,inflated.buffer) !== oid)throw fail('corrupt','Loose object content/hash mismatch.');
95
+ await verifyStorage(); await verifyDirectory(fanout); check(); return true;
96
+ } finally { await file.close(); }
97
+ };
98
+ // Cleanup deliberately ignores cancellation but never removes a foreign path or
99
+ // final object. Retain uncertain temp files rather than guessing ownership.
100
+ const cleanup = async () => {
101
+ if(!temporary || !owned)return;
102
+ for(const p of [directory,objects,fanout]) {
103
+ const s = await lstat(p,{bigint:true});
104
+ if(!s.isDirectory() || s.isSymbolicLink() || !same(s,directories.get(p)) || normalized(await realpath(p)) !== normalized(p))throw fail('unsafe','Cannot safely clean changed directory.');
105
+ }
106
+ let current;
107
+ try { current = await lstat(temporary,{bigint:true}); } catch(e) { if(e.code === 'ENOENT'){temporary=undefined;return;} throw e; }
108
+ if(!current.isFile() || current.isSymbolicLink() || !same(current,owned))throw fail('unsafe','Temporary path ownership changed; retained.');
109
+ await unlink(temporary); temporary=undefined;
110
+ };
111
+ try {
112
+ await authorize(); await verifyStorage();
113
+ let hasFanout = true;
114
+ try { await verifyDirectory(fanout); } catch(e) { if(e.code !== 'ENOENT')throw e; hasFanout=false; }
115
+ if(hasFanout && await validateExisting()) { await authorize(); return {oid,created:false}; }
116
+ const compressed = deflateSync(raw); check();
117
+ await authorize(); await verifyStorage();
118
+ if(hasFanout)await verifyDirectory(fanout);
119
+ started=true;
120
+ const notification=onStart();
121
+ if(notification && typeof notification.then === 'function') {
122
+ Promise.resolve(notification).catch(()=>{});
123
+ throw fail('invalid','onStart must be synchronous.');
124
+ }
125
+ check();
126
+ if(!hasFanout) {
127
+ try { await mkdir(fanout); } catch(e) { if(e.code !== 'EEXIST')throw e; }
128
+ }
129
+ await verifyStorage(); await verifyDirectory(fanout); check();
130
+ temporary=path.join(fanout,'.dsh-blob-' + randomUUID());
131
+ handle=await open(temporary,constants.O_CREAT|constants.O_EXCL|constants.O_WRONLY|(constants.O_NOFOLLOW||0),0o600);
132
+ owned=await handle.stat({bigint:true});
133
+ if(!plain(owned))throw fail('unsafe','Temporary object is not single-link.');
134
+ await handle.writeFile(compressed); check(); await handle.sync();
135
+ await handle.close(); handle=undefined;
136
+ await authorize(); await verifyStorage(); await verifyDirectory(fanout);
137
+ const temp=await lstat(temporary,{bigint:true});
138
+ if(!plain(temp) || !same(temp,owned) || temp.size !== BigInt(compressed.length))throw fail('unsafe','Temporary object changed.');
139
+ check(); let created=true;
140
+ try { await link(temporary,target); }
141
+ catch(e) { if(e.code !== 'EEXIST')throw e; created=false; }
142
+ await cleanup(); // Drop our second link before validating the final nlink=1.
143
+ if(!await validateExisting())throw fail('corrupt','Published object is missing.');
144
+ await authorize(); return {oid,created};
145
+ } catch(error) {
146
+ try { if(handle){await handle.close();handle=undefined;} await cleanup(); }
147
+ catch(cleanupError) { error = new AggregateError([error,cleanupError],'Blob operation and owned-temp cleanup failed.'); }
148
+ if(!started)throw error;
149
+ throw Object.assign(fail('outcome-unknown','Append-only blob storage started; object may exist. Never roll back with deletion or GC.',error),{outcomeUnknown:true,appendOnly:true});
150
+ }
151
+ }
@@ -0,0 +1,156 @@
1
+ // Internal only: caller owns the repository mutation mutex and trusted callbacks.
2
+ // No RPC/UI/commit adapter. Hostile concurrent directory replacement is excluded:
3
+ // portable Node path/identity checks cannot provide dirfd-relative isolation.
4
+ // Packed refs, linked/shared metadata, reftable and alternates fail closed.
5
+ import * as fs from 'node:fs/promises';
6
+ import {constants} from 'node:fs';
7
+ import path from 'node:path';
8
+ import os from 'node:os';
9
+ import {git} from './local-command.mjs';
10
+ import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
11
+
12
+ const fail=(kind,message,cause)=>Object.assign(new Error(message,{cause}),{code:'vcs/branch-create-'+kind});
13
+ const same=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.birthtimeNs===b.birthtimeNs;
14
+ const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
15
+ const decode=b=>new TextDecoder('utf-8',{fatal:true}).decode(b);
16
+ function validRef(ref){
17
+ if(typeof ref!=='string'||Buffer.from(ref,'utf8').toString('utf8')!==ref||!ref.startsWith('refs/heads/')||Buffer.byteLength(ref)>1024||
18
+ /[\x00- \x7f~^:?*[\\]/.test(ref)||ref.includes('..')||ref.includes('@{')||ref.endsWith('.')||
19
+ ref.split('/').some(p=>!p||p.startsWith('.')||p.toLowerCase().endsWith('.lock')||/[. ]$/.test(p)||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))
20
+ throw fail('invalid','An exact safe refs/heads branch is required.');
21
+ }
22
+
23
+ /** Create one absent local branch via Git update-ref --no-deref full-width zero-old CAS.
24
+ * Internal only: the caller MUST hold the repository writer mutex throughout.
25
+ * Existing born symbolic HEAD is pinned as a current fact, never a caller token.
26
+ * Returns {ref,commit}; fixed Dsh audit attribution, not user authorship.
27
+ * Packed refs (even unrelated), linked/shared metadata and locks fail closed.
28
+ * Index bodies are not read: optional index metadata versions are pinned only.
29
+ * No checkout, HEAD/index/worktree/object mutation, signing, network or retry.
30
+ * All failures after synchronous onStart are outcome-unknown. Never roll back,
31
+ * remove a competing ref or Git lock, or retry on the caller's behalf.
32
+ * Trusted callbacks must not mutate filesystem state; onStart must be synchronous.
33
+ * Portable path checks do not isolate hostile concurrent directory replacement.
34
+ */
35
+ export async function createLocalBranch(repo,{ref,commit,objectFormat,signal,assertAuthorized,onStart}={}){
36
+ const root=repo?.root;
37
+ validRef(ref);
38
+ const oidPattern=objectFormat==='sha1'?/^[0-9a-f]{40}$/:objectFormat==='sha256'?/^[0-9a-f]{64}$/:null;
39
+ if(repo?.type!=='git'||typeof root!=='string'||!path.isAbsolute(root)||path.resolve(root)!==root||
40
+ !oidPattern||typeof commit!=='string'||!oidPattern.test(commit)||/^0+$/.test(commit)||
41
+ typeof assertAuthorized!=='function'||typeof onStart!=='function')throw fail('invalid','Canonical embedded Git root, a full commit OID and callbacks required.');
42
+ let started=false,hooks,owned,headText,headRef,headOid,indexVersion;
43
+ const directory=path.join(root,'.git'),identities=new Map();
44
+ const check=()=>{signal?.throwIfAborted();currentOperationBudget()?.throwIfExpired();};
45
+ const authorize=async()=>{check();await assertAuthorized();check();};
46
+ async function dir(p){
47
+ check();const s=await fs.lstat(p,{bigint:true});
48
+ if(!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(p)!==p||(identities.has(p)&&!same(identities.get(p),s)))throw fail('unsafe','Noncanonical or replaced directory.');
49
+ identities.set(p,s);return s;
50
+ }
51
+ async function read(p,max=4096){
52
+ check();const before=await fs.lstat(p,{bigint:true});
53
+ if(!plain(before)||before.size>BigInt(max))throw fail('unsafe','Expected bounded single-link metadata.');
54
+ const h=await fs.open(p,constants.O_RDONLY|(constants.O_NOFOLLOW||0));
55
+ try{
56
+ const opened=await h.stat({bigint:true});
57
+ if(!plain(opened)||!same(before,opened))throw fail('unsafe','Metadata replaced.');
58
+ const b=Buffer.alloc(max+1);let n=0;
59
+ while(n<b.length){check();const r=await h.read(b,n,b.length-n,n);if(!r.bytesRead)break;n+=r.bytesRead;}
60
+ const after=await h.stat({bigint:true}),now=await fs.lstat(p,{bigint:true});
61
+ if(n>max||!plain(now)||!same(opened,now)||opened.size!==after.size||opened.mtimeNs!==after.mtimeNs||opened.ctimeNs!==after.ctimeNs||after.size!==now.size||after.mtimeNs!==now.mtimeNs||after.ctimeNs!==now.ctimeNs||BigInt(n)!==after.size)throw fail('unsafe','Metadata changed.');
62
+ return decode(b.subarray(0,n));
63
+ }finally{await h.close();}
64
+ }
65
+ async function metadata(){
66
+ await dir(root);let count=0;
67
+ const forbidden=new Set(['commondir','gitdir','worktrees','reftable','packed-refs','shallow','config.worktree','objects/info/alternates','objects/info/http-alternates','MERGE_HEAD','CHERRY_PICK_HEAD','REVERT_HEAD','rebase-merge','rebase-apply','sequencer'].map(s=>s.toLowerCase()));
68
+ async function visit(p,rel){
69
+ check();if(++count>20000)throw fail('unsupported','Metadata node bound exceeded.');
70
+ const lower=rel.toLowerCase();
71
+ if(forbidden.has(lower)||lower.endsWith('.lock')||lower.endsWith('.promisor')||lower.startsWith('sharedindex.'))throw fail('unsupported','Unsupported metadata or lock: '+rel);
72
+ const s=await fs.lstat(p,{bigint:true});
73
+ if(s.isSymbolicLink()||await fs.realpath(p)!==p)throw fail('unsafe','Linked metadata.');
74
+ if(s.isDirectory()){await dir(p);for(const name of await fs.readdir(p))await visit(path.join(p,name),rel?rel+'/'+name:name);}
75
+ else if(!plain(s))throw fail('unsafe','Shared or special metadata.');
76
+ }
77
+ await visit(directory,'');
78
+ }
79
+ const run=(args,max=16384)=>{check();return git(root,['-c','core.hooksPath='+hooks,'-c','user.name=Dsh','-c','user.email=dsh@localhost','-c','committer.name=Dsh','-c','committer.email=dsh@localhost','--git-dir='+directory,'--work-tree='+root,...args],max,{signal});};
80
+ async function config(){
81
+ // FIRST Git call: never expand include/includeIf (including global/system).
82
+ const rows=decode(await run(['config','--no-includes','--null','--list'],128*1024)).split('\0').filter(Boolean);
83
+ for(const row of rows){const i=row.indexOf('\n'),key=(i<0?row:row.slice(0,i)).toLowerCase(),value=i<0?'':row.slice(i+1).toLowerCase();
84
+ if(key.startsWith('include')||key.startsWith('extensions.')&&key!=='extensions.objectformat'||key==='core.worktree'||key==='core.repositoryformatversion'&&!['0','1'].includes(value)||key==='core.bare'&&value!=='false'||key==='core.sharedrepository'&&!['false','0'].includes(value)||/^remote\..*\.(promisor|partialclonefilter)$/.test(key))throw fail('unsupported','Unsupported configuration: '+key);
85
+ }
86
+ }
87
+ async function indexStat(){
88
+ check();try{
89
+ const s=await fs.lstat(path.join(directory,'index'),{bigint:true});
90
+ if(!plain(s))throw fail('unsafe','Index must be single-link regular metadata.');
91
+ return s;
92
+ }catch(error){if(error.code==='ENOENT')return null;throw error;}
93
+ }
94
+ function sameVersion(a,b){return a===null?b===null:b!==null&&same(a,b)&&a.size===b.size&&a.mtimeNs===b.mtimeNs&&a.ctimeNs===b.ctimeNs;}
95
+ async function absentTarget(){
96
+ // Metadata walk rejects packed-refs wholesale, including unrelated entries.
97
+ // Git's full-width zero-old CAS is the actual exclusive-create boundary.
98
+ const parts=ref.split('/');
99
+ for(let i=1;i<=parts.length;i++){
100
+ const p=path.join(directory,...parts.slice(0,i));
101
+ try{const s=await fs.lstat(p,{bigint:true});
102
+ if(i===parts.length||!s.isDirectory())throw fail('exists','Target branch or namespace already exists.');
103
+ await dir(p);
104
+ }catch(error){if(error.code==='ENOENT')break;throw error;}
105
+ }
106
+ try{await fs.lstat(path.join(directory,'logs',...parts));throw fail('exists','Target reflog already exists.');}
107
+ catch(error){if(error.code!=='ENOENT')throw error;}
108
+ }
109
+ async function state(created=false){
110
+ await metadata();await config();
111
+ const current=await read(path.join(directory,'HEAD'));
112
+ if(headText===undefined){
113
+ if(!current.startsWith('ref: ')||!current.endsWith('\n'))throw fail('stale','Existing born symbolic HEAD required.');
114
+ headRef=current.slice(5,-1);validRef(headRef);headText=current;
115
+ headOid=(await read(path.join(directory,...headRef.split('/')))).replace(/\n$/,'');
116
+ if(!oidPattern.test(headOid)||/^0+$/.test(headOid))throw fail('stale','HEAD must name a born direct commit.');
117
+ }
118
+ if(current!==headText||await read(path.join(directory,...headRef.split('/')))!==headOid+'\n')throw fail('stale','Original HEAD changed.');
119
+ if(created){
120
+ if(await read(path.join(directory,...ref.split('/')))!==commit+'\n')throw fail('stale','Created branch is no longer the exact direct commit.');
121
+ }else await absentTarget();
122
+ const facts=decode(await run(['rev-parse','--absolute-git-dir','--git-common-dir','--show-toplevel','--is-bare-repository','--show-object-format','--verify','HEAD'])).trimEnd().split('\n');
123
+ if(facts.length!==6||path.resolve(root,facts[0])!==directory||path.resolve(root,facts[1])!==directory||path.resolve(facts[2])!==root||facts[3]!=='false'||facts[4]!==objectFormat||facts[5]!==headOid)throw fail('stale','Git repository facts changed.');
124
+ const now=await indexStat();
125
+ if(indexVersion===undefined)indexVersion=now;
126
+ else if(!sameVersion(indexVersion,now))throw fail('stale','Index metadata version changed.');
127
+ }
128
+ async function verifyHooks(){
129
+ const s=await fs.lstat(hooks,{bigint:true});
130
+ if(!s.isDirectory()||s.isSymbolicLink()||!same(owned,s)||await fs.realpath(hooks)!==hooks||(await fs.readdir(hooks)).length)throw fail('unsafe','Owned hooks directory changed or is not empty.');
131
+ }
132
+ try{
133
+ return await withOperationBudget({signal},async()=>{
134
+ await authorize();await metadata();
135
+ const temp=await fs.realpath(os.tmpdir());
136
+ if(temp===root||temp.startsWith(root+path.sep))throw fail('unsafe','Hooks directory must be outside repository.');
137
+ hooks=await fs.mkdtemp(path.join(temp,'dsh-branch-create-hooks-'+process.pid+'-'));owned=await fs.lstat(hooks,{bigint:true});await verifyHooks();
138
+ await state();
139
+ if(decode(await run(['cat-file','-t',commit],1024))!=='commit\n')throw fail('invalid','commit must name a real existing commit object.');
140
+ if(decode(await run(['cat-file','-t',headOid],1024))!=='commit\n')throw fail('invalid','Expected born branch must name a commit.');
141
+ await authorize();await state();await verifyHooks();check();
142
+ started=true;const result=onStart();
143
+ if(result&&typeof result.then==='function'){Promise.resolve(result).catch(()=>{});throw fail('invalid','onStart must be synchronous.');}
144
+ // No asynchronous work between the notification and mutation subprocess.
145
+ await run(['update-ref','--no-deref','-m','dsh: create local branch',ref,commit,'0'.repeat(commit.length)],4096);
146
+ await authorize();await state(true);await authorize();check();
147
+ return {ref,commit};
148
+ });
149
+ }catch(error){
150
+ if(started)throw Object.assign(fail('outcome-unknown','Branch update outcome is unknown; inspect before any further action.',error),{outcomeUnknown:true});
151
+ throw error;
152
+ }finally{
153
+ // Never recursively remove, unlink foreign entries, or delete a replaced path.
154
+ if(hooks&&owned)try{const s=await fs.lstat(hooks,{bigint:true});if(s.isDirectory()&&!s.isSymbolicLink()&&same(owned,s)&&await fs.realpath(hooks)===hooks&&(await fs.readdir(hooks)).length===0)await fs.rmdir(hooks);}catch{}
155
+ }
156
+ }
@@ -0,0 +1,175 @@
1
+ // Internal only: caller owns the repository mutation mutex and trusted callbacks.
2
+ // No RPC/UI/commit adapter. Hostile concurrent directory replacement is excluded:
3
+ // portable Node path/identity checks cannot provide dirfd-relative isolation.
4
+ // Packed refs, linked/shared metadata, reftable and alternates fail closed.
5
+ import * as fs from 'node:fs/promises';
6
+ import {constants} from 'node:fs';
7
+ import path from 'node:path';
8
+ import os from 'node:os';
9
+ import {git} from './local-command.mjs';
10
+ import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
11
+
12
+ const fail=(kind,message,cause)=>Object.assign(new Error(message,{cause}),{code:'vcs/branch-delete-'+kind});
13
+ const same=(a,b)=>a.dev===b.dev&&a.ino===b.ino&&a.birthtimeNs===b.birthtimeNs;
14
+ const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
15
+ const decode=b=>new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(b);
16
+ function validRef(ref){
17
+ const name=typeof ref==='string'&&ref.startsWith('refs/heads/')?ref.slice(11):'';
18
+ if(!name||Buffer.from(name,'utf8').toString('utf8')!==name||Buffer.byteLength(name)>1000||
19
+ name==='@'||name.toUpperCase()==='HEAD'||name.startsWith('-')||name.startsWith('refs/')||/[\x00-\x20\x7f~^:?*\[\\<>"|\p{Cc}\p{Cf}]/u.test(name)||name.includes('..')||name.includes('@{')||
20
+ name.split('/').some(p=>!p||Buffer.byteLength(p)>255||p.startsWith('.')||/[. ]$/.test(p)||p.toLowerCase().endsWith('.lock')||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))
21
+ throw fail('invalid','An exact safe portable refs/heads branch is required.');
22
+ }
23
+
24
+ /** Internal low-level OID CAS only: NO merged/ancestry or user-delete authorization.
25
+ * Caller MUST hold the repository writer mutex and supply trusted callbacks.
26
+ * Deletes exactly one direct loose branch; returns {ref,expectedOid}.
27
+ * No checkout, HEAD/index/worktree/object mutation, force, retry or rollback.
28
+ * Original HEAD raw bytes, direct tip, HEAD/current-branch logs and optional index
29
+ * metadata are pinned. This is NOT full namespace/adapter verification.
30
+ * Packed refs wholesale, shared/linked metadata, unsafe config and locks refused.
31
+ * Own empty external hooks directory and fixed Dsh audit attribution only.
32
+ * All failures after entering synchronous onStart are outcome-unknown, even when
33
+ * the mutation command was not run. Never recreate a target or remove a competitor.
34
+ * After onStart we re-read the raw target to reject an OBSERVED symbolic/OID
35
+ * replacement before Git. This is not atomic raw-type CAS: Git --no-deref with
36
+ * old OID can delete a symbolic ref resolving to that OID (destination untouched).
37
+ * A replacement after that read can therefore evade type observation. The actual
38
+ * atomic boundary is Git's old-OID comparison, not proof of a direct raw ref.
39
+ * Trust synchronous onStart; no hostile directory-swap isolation or ABA guarantee.
40
+ */
41
+ export async function deleteLocalBranch(repo,{ref,expectedOid,objectFormat,signal,assertAuthorized,onStart}={}){
42
+ const root=repo?.root;
43
+ validRef(ref);
44
+ const oidPattern=objectFormat==='sha1'?/^[0-9a-f]{40}$/:objectFormat==='sha256'?/^[0-9a-f]{64}$/:null;
45
+ if(repo?.type!=='git'||typeof root!=='string'||!path.isAbsolute(root)||path.resolve(root)!==root||
46
+ !oidPattern||typeof expectedOid!=='string'||!oidPattern.test(expectedOid)||/^0+$/.test(expectedOid)||
47
+ typeof assertAuthorized!=='function'||typeof onStart!=='function')throw fail('invalid','Canonical embedded Git root, a full commit OID and callbacks required.');
48
+ let started=false,hooks,owned,headText,headRef,headOid,indexVersion,headLog,branchLog;
49
+ const directory=path.join(root,'.git'),identities=new Map();
50
+ const check=()=>{signal?.throwIfAborted();currentOperationBudget()?.throwIfExpired();};
51
+ const authorize=async()=>{check();await assertAuthorized();check();};
52
+ async function dir(p){
53
+ check();const s=await fs.lstat(p,{bigint:true});
54
+ if(!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(p)!==p||(identities.has(p)&&!same(identities.get(p),s)))throw fail('unsafe','Noncanonical or replaced directory.');
55
+ identities.set(p,s);return s;
56
+ }
57
+ async function read(p,max=4096){
58
+ check();const before=await fs.lstat(p,{bigint:true});
59
+ if(!plain(before)||before.size>BigInt(max))throw fail('unsafe','Expected bounded single-link metadata.');
60
+ const h=await fs.open(p,constants.O_RDONLY|(constants.O_NOFOLLOW||0));
61
+ try{
62
+ const opened=await h.stat({bigint:true});
63
+ if(!plain(opened)||!same(before,opened))throw fail('unsafe','Metadata replaced.');
64
+ const b=Buffer.alloc(max+1);let n=0;
65
+ while(n<b.length){check();const r=await h.read(b,n,b.length-n,n);if(!r.bytesRead)break;n+=r.bytesRead;}
66
+ const after=await h.stat({bigint:true}),now=await fs.lstat(p,{bigint:true});
67
+ if(n>max||!plain(now)||!same(opened,now)||opened.size!==after.size||opened.mtimeNs!==after.mtimeNs||opened.ctimeNs!==after.ctimeNs||after.size!==now.size||after.mtimeNs!==now.mtimeNs||after.ctimeNs!==now.ctimeNs||BigInt(n)!==after.size)throw fail('unsafe','Metadata changed.');
68
+ return decode(b.subarray(0,n));
69
+ }finally{await h.close();}
70
+ }
71
+ async function metadata(){
72
+ await dir(root);let count=0;
73
+ const forbidden=new Set(['commondir','gitdir','worktrees','reftable','packed-refs','shallow','config.worktree','objects/info/alternates','objects/info/http-alternates','MERGE_HEAD','CHERRY_PICK_HEAD','REVERT_HEAD','rebase-merge','rebase-apply','sequencer'].map(s=>s.toLowerCase()));
74
+ async function visit(p,rel){
75
+ check();if(++count>20000)throw fail('unsupported','Metadata node bound exceeded.');
76
+ const lower=rel.toLowerCase();
77
+ if(forbidden.has(lower)||lower.endsWith('.lock')||lower.endsWith('.promisor')||lower.startsWith('sharedindex.'))throw fail('unsupported','Unsupported metadata or lock: '+rel);
78
+ const s=await fs.lstat(p,{bigint:true});
79
+ if(s.isSymbolicLink()||await fs.realpath(p)!==p)throw fail('unsafe','Linked metadata.');
80
+ if(s.isDirectory()){await dir(p);for(const name of await fs.readdir(p))await visit(path.join(p,name),rel?rel+'/'+name:name);}
81
+ else if(!plain(s))throw fail('unsafe','Shared or special metadata.');
82
+ }
83
+ await visit(directory,'');
84
+ }
85
+ const run=(args,max=16384)=>{check();return git(root,['-c','core.hooksPath='+hooks,'-c','user.name=Dsh','-c','user.email=dsh@localhost','-c','committer.name=Dsh','-c','committer.email=dsh@localhost','--git-dir='+directory,'--work-tree='+root,...args],max,{signal});};
86
+ async function config(){
87
+ // FIRST Git call: never expand include/includeIf (including global/system).
88
+ const rows=decode(await run(['config','--no-includes','--null','--list'],128*1024)).split('\0').filter(Boolean);
89
+ for(const row of rows){const i=row.indexOf('\n'),key=(i<0?row:row.slice(0,i)).toLowerCase(),value=i<0?'':row.slice(i+1).toLowerCase();
90
+ if(key.startsWith('include')||key.startsWith('extensions.')&&key!=='extensions.objectformat'||key==='core.worktree'||key==='core.repositoryformatversion'&&!['0','1'].includes(value)||key==='core.bare'&&value!=='false'||key==='core.sharedrepository'&&!['false','0'].includes(value)||/^remote\..*\.(promisor|partialclonefilter)$/.test(key))throw fail('unsupported','Unsupported configuration: '+key);
91
+ }
92
+ }
93
+ async function indexStat(){
94
+ check();try{
95
+ const s=await fs.lstat(path.join(directory,'index'),{bigint:true});
96
+ if(!plain(s))throw fail('unsafe','Index must be single-link regular metadata.');
97
+ return s;
98
+ }catch(error){if(error.code==='ENOENT')return null;throw error;}
99
+ }
100
+ function sameVersion(a,b){return a===null?b===null:b!==null&&same(a,b)&&a.size===b.size&&a.mtimeNs===b.mtimeNs&&a.ctimeNs===b.ctimeNs;}
101
+ async function exactPath(parts){
102
+ let parent=directory;
103
+ for(let i=0;i<parts.length;i++){
104
+ const matches=(await fs.readdir(parent)).filter(n=>n.toLowerCase()===parts[i].toLowerCase());
105
+ if(matches.length!==1||matches[0]!==parts[i])throw fail('stale','Missing target or portable namespace alias.');
106
+ parent=path.join(parent,parts[i]);if(i<parts.length-1)await dir(parent);
107
+ }
108
+ return parent;
109
+ }
110
+ async function directTarget(){
111
+ const file=await exactPath(ref.split('/'));
112
+ if(await read(file,65)!==expectedOid+'\n')throw fail('stale','Target must remain the exact expected direct OID.');
113
+ }
114
+ async function optionalLog(parts){
115
+ try{return await read(path.join(directory,'logs',...parts),2*1024*1024);}
116
+ catch(error){if(error.code==='ENOENT')return null;throw error;}
117
+ }
118
+ async function absentTarget(){
119
+ for(const file of [path.join(directory,...ref.split('/')),path.join(directory,'logs',...ref.split('/'))]){
120
+ try{await fs.lstat(file);throw fail('stale','Deleted target or target reflog still exists.');}
121
+ catch(error){if(error.code!=='ENOENT')throw error;}
122
+ }
123
+ }
124
+ async function state(deleted=false){
125
+ await metadata();await config();
126
+ const current=await read(path.join(directory,'HEAD'));
127
+ if(headText===undefined){
128
+ if(!current.startsWith('ref: ')||!current.endsWith('\n'))throw fail('stale','Existing born symbolic HEAD required.');
129
+ headRef=current.slice(5,-1);validRef(headRef);headText=current;
130
+ if(headRef.toLowerCase()===ref.toLowerCase())throw fail('invalid','Cannot delete current branch or case-insensitive alias.');
131
+ await exactPath(headRef.split('/'));
132
+ headLog=await optionalLog(['HEAD']);branchLog=await optionalLog(headRef.split('/'));
133
+ headOid=(await read(path.join(directory,...headRef.split('/')))).replace(/\n$/,'');
134
+ if(!oidPattern.test(headOid)||/^0+$/.test(headOid))throw fail('stale','HEAD must name a born direct commit.');
135
+ }
136
+ if(current!==headText||await read(path.join(directory,...headRef.split('/')))!==headOid+'\n')throw fail('stale','Original HEAD changed.');
137
+ await exactPath(headRef.split('/'));
138
+ if(await optionalLog(['HEAD'])!==headLog||await optionalLog(headRef.split('/'))!==branchLog)throw fail('stale','Original HEAD or current branch reflog changed.');
139
+ if(deleted)await absentTarget();else await directTarget();
140
+ const facts=decode(await run(['rev-parse','--absolute-git-dir','--git-common-dir','--show-toplevel','--is-bare-repository','--show-object-format','--verify','HEAD'])).trimEnd().split('\n');
141
+ if(facts.length!==6||path.resolve(root,facts[0])!==directory||path.resolve(root,facts[1])!==directory||path.resolve(facts[2])!==root||facts[3]!=='false'||facts[4]!==objectFormat||facts[5]!==headOid)throw fail('stale','Git repository facts changed.');
142
+ const now=await indexStat();
143
+ if(indexVersion===undefined)indexVersion=now;
144
+ else if(!sameVersion(indexVersion,now))throw fail('stale','Index metadata version changed.');
145
+ }
146
+ async function verifyHooks(){
147
+ const s=await fs.lstat(hooks,{bigint:true});
148
+ if(!s.isDirectory()||s.isSymbolicLink()||!same(owned,s)||await fs.realpath(hooks)!==hooks||(await fs.readdir(hooks)).length)throw fail('unsafe','Owned hooks directory changed or is not empty.');
149
+ }
150
+ try{
151
+ return await withOperationBudget({signal},async()=>{
152
+ await authorize();await metadata();
153
+ const temp=await fs.realpath(os.tmpdir());
154
+ if(temp===root||temp.startsWith(root+path.sep))throw fail('unsafe','Hooks directory must be outside repository.');
155
+ hooks=await fs.mkdtemp(path.join(temp,'dsh-branch-delete-hooks-'+process.pid+'-'));owned=await fs.lstat(hooks,{bigint:true});await verifyHooks();
156
+ await state();
157
+ if(decode(await run(['cat-file','-t',expectedOid],1024))!=='commit\n')throw fail('invalid','expectedOid must name a real existing commit object.');
158
+ if(decode(await run(['cat-file','-t',headOid],1024))!=='commit\n')throw fail('invalid','Expected born branch must name a commit.');
159
+ await authorize();await state();await verifyHooks();check();
160
+ started=true;const result=onStart();
161
+ if(result&&typeof result.then==='function'){Promise.resolve(result).catch(()=>{});throw fail('invalid','onStart must be synchronous.');}
162
+ // Observation only: a later symbolic replacement is not atomically excluded.
163
+ await directTarget();check();
164
+ await run(['update-ref','--no-deref','-d',ref,expectedOid],4096);
165
+ await authorize();await state(true);await authorize();check();
166
+ return {ref,expectedOid};
167
+ });
168
+ }catch(error){
169
+ if(started)throw Object.assign(fail('outcome-unknown','Branch update outcome is unknown; inspect before any further action.',error),{outcomeUnknown:true});
170
+ throw error;
171
+ }finally{
172
+ // Never recursively remove, unlink foreign entries, or delete a replaced path.
173
+ if(hooks&&owned)try{const s=await fs.lstat(hooks,{bigint:true});if(s.isDirectory()&&!s.isSymbolicLink()&&same(owned,s)&&await fs.realpath(hooks)===hooks&&(await fs.readdir(hooks)).length===0)await fs.rmdir(hooks);}catch{}
174
+ }
175
+ }