@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
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
  新增宿主兼容声明时,还需对精确宿主执行隔离检查:
@@ -35,7 +37,7 @@ npm run test:host-compat -- "<installed @deepseek-ai/dsh/package.json>"
35
37
  1. 提交并推送版本修改,创建新标签 `vX.Y.Z`;不移动已有标签。
36
38
  2. 等待标签 CI 的 Windows/Ubuntu × Node 22/24 全部成功。
37
39
  3. 手动在同一标签运行 **Browser layout checks**,等待成功。
38
- 4. 在同一标签运行 **Controlled host compatibility**,提供受控离线宿主工件 run ID 和四个精确版本的 SHA-256。每个版本必须有自己的真实合同结果。
40
+ 4. 在同一标签运行 **Controlled host compatibility**,提供受控离线宿主工件 run ID 和五个精确版本的 SHA-256。每个版本必须有自己的真实合同结果。
39
41
  5. 发布预检自动下载四份候选包与浏览器/宿主证据,绑定完整 tag ref、提交 SHA、run ID 和 attempt;核对内嵌版本、零跳过测试摘要及四包字节一致。缺失或失败均阻断。
40
42
 
41
43
  分支检查不能代替同标签检查。失败后先定位;需要修改源码或测试时使用新的版本和标签。
@@ -44,15 +46,15 @@ npm run test:host-compat -- "<installed @deepseek-ai/dsh/package.json>"
44
46
 
45
47
  浏览器与宿主合同任务不重新构建插件:先以 `npm ci --include=dev --ignore-scripts` 安装测试依赖,再由[发布预检脚本](<https://github.com/f-e-n-g-0531/dsh-vcs/blob/main/scripts/release-preflight.mjs>)的 `select-ci` 选定同标签、同提交的成功 CI run/attempt,下载全部四矩阵候选;`consume` 校验版本、测试零失败/取消/跳过/待办及四包字节一致后,将候选包里的发行文件作为本次测试输入。
46
48
 
47
- 消费过程生成 `consumed-candidate.json` 收据,记录候选归档 SHA-256、CI run/attempt 和归档位置。生成 Chrome 或宿主成功报告前,再核对原归档及每个已消费发行文件的实际字节;变化即失败,不能用重新构建的文件替代。报告中的 `candidateSha256`、`ciRun`、`ciAttempt` 必须与最终发布预检选中的四份 CI 候选一致,同时仍核对各自的完整 tag ref、提交 SHA 和证据任务 run/attempt。仅“同一提交测试通过”而没有这条字节关联,不足以放行;CI 重跑后也必须重新取得对应候选的浏览器与四版本宿主证据。
49
+ 消费过程生成 `consumed-candidate.json` 收据,记录候选归档 SHA-256、CI run/attempt 和归档位置。生成 Chrome 或宿主成功报告前,再核对原归档及每个已消费发行文件的实际字节;变化即失败,不能用重新构建的文件替代。报告中的 `candidateSha256`、`ciRun`、`ciAttempt` 必须与最终发布预检选中的四份 CI 候选一致,同时仍核对各自的完整 tag ref、提交 SHA 和证据任务 run/attempt。仅“同一提交测试通过”而没有这条字节关联,不足以放行;CI 重跑后也必须重新取得对应候选的浏览器与五版本宿主证据。
48
50
 
49
51
  ## 受控宿主准备与离线合同
50
52
 
51
- [宿主工件工作流](<https://github.com/f-e-n-g-0531/dsh-vcs/blob/main/.github/workflows/host-fixtures.yml>)仅允许默认分支手动执行,在 GitHub 托管的 Ubuntu runner 上为四个精确版本分别准备真实宿主:`0.1.7-rc.2`、`0.2.0-rc.2`、`0.2.1-rc.2`、`0.2.1-rc.5`。这是明确授权的**在线准备阶段**,不是离线安装,也不使用日常 DSH 的配置或依赖目录。
53
+ [宿主工件工作流](<https://github.com/f-e-n-g-0531/dsh-vcs/blob/main/.github/workflows/host-fixtures.yml>)仅允许默认分支手动执行,在 GitHub 托管的 Ubuntu runner 上为五个精确版本分别准备真实宿主:`0.1.7-rc.2`、`0.2.0-rc.2`、`0.2.1-rc.2`、`0.2.1-rc.5`、`0.2.2-rc.1`。这是明确授权的**在线准备阶段**,不是离线安装,也不使用日常 DSH 的配置或依赖目录。
52
54
 
53
55
  工作流通过[准备脚本](<https://github.com/f-e-n-g-0531/dsh-vcs/blob/main/scripts/prepare-host-fixture.mjs>)固定同版本的官方 DSH 与 ui-slots 包,仅从 `https://registry.npmjs.org` 解析依赖。先生成锁文件并校验精确版本、下载地址及 SHA-512 integrity,再按锁文件安装;两次 npm 操作均禁用安装脚本。工件同时保存锁文件及准备记录,包括锁文件 SHA-256、准备源码 SHA、run ID 和 attempt。不启动宿主,不安装插件,不接触运行中的 profile。
54
56
 
55
- 准备完成后,在待发布标签运行[宿主兼容工作流](<https://github.com/f-e-n-g-0531/dsh-vcs/blob/main/.github/workflows/host-compat.yml>),提供成功准备任务的 `fixture_run` 和四个版本各自 `host.tar.gz` 的 SHA-256 映射 `fixture_hashes`。工作流只接受本仓库默认分支的受控准备工作流结果,拒绝其他工作流、fork/PR 以及不匹配的摘要;验证归档路径后提取真实依赖树。**宿主合同使用已准备的离线依赖树**,不再在线安装宿主、不启动 profile,也不能用 mock 或一个版本的结果冒充四版本通过。工作流下载证据及安装插件项目的测试依赖仍需要网络,不表示整项 CI 在断网环境运行。
57
+ 准备完成后,在待发布标签运行[宿主兼容工作流](<https://github.com/f-e-n-g-0531/dsh-vcs/blob/main/.github/workflows/host-compat.yml>),提供成功准备任务的 `fixture_run` 和五个版本各自 `host.tar.gz` 的 SHA-256 映射 `fixture_hashes`。工作流只接受本仓库默认分支的受控准备工作流结果,拒绝其他工作流、fork/PR 以及不匹配的摘要;验证归档路径后提取真实依赖树。**宿主合同使用已准备的离线依赖树**,不再在线安装宿主、不启动 profile,也不能用 mock 或一个版本的结果冒充五版本通过。工作流下载证据及安装插件项目的测试依赖仍需要网络,不表示整项 CI 在断网环境运行。
56
58
 
57
59
  若维护者已有完整可信依赖树,也可本地生成相同宿主归档:
58
60
 
@@ -60,7 +62,7 @@ npm run test:host-compat -- "<installed @deepseek-ai/dsh/package.json>"
60
62
  node scripts/release-host-fixture.mjs pack <含node_modules和package-lock.json的根目录> <精确版本> <新的输出目录>
61
63
  ```
62
64
 
63
- 归档来源必须包含完整依赖与锁文件;根目录内合法依赖链接可物化为普通文件,指向根目录外的链接或外部依赖 store 会被拒绝,须先将依赖完整准备在根目录内。归档本身不得保留链接或越界项。本地生成归档不绕过发布工作流的受控来源检查;四版本工件或真实合同不完整时发布仍会阻断。
65
+ 归档来源必须包含完整依赖与锁文件;根目录内合法依赖链接可物化为普通文件,指向根目录外的链接或外部依赖 store 会被拒绝,须先将依赖完整准备在根目录内。归档本身不得保留链接或越界项。本地生成归档不绕过发布工作流的受控来源检查;五版本工件或真实合同不完整时发布仍会阻断。
64
66
 
65
67
  ## 3. 按渠道发布
66
68
 
@@ -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
+ }