@feng0531/dsh-vcs 0.7.3 → 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 +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 +2 -2
  12. package/dist/frontend.json +1 -1
  13. package/dist/interface.js +2 -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/README.md CHANGED
@@ -2,7 +2,9 @@
2
2
 
3
3
  在 DeepSeek Harness(DSH)Web 中查看 Git / SVN 文件变更和提交历史,**默认只读预览**。
4
4
 
5
- 你可以查看差异、浏览历史、追溯文件。0.6.0 起新增一个明确的写操作例外:预览并确认后切换已有本地 Git 分支,会改变 HEAD、暂存区和工作文件;不提供正文编辑、暂存、提交、拉取或推送。源码能力说明不代表目标版本已通过正式发布门禁,请核对对应发布渠道。
5
+ 你可以查看差异、浏览历史、追溯文件。已有确认式本地 Git 分支切换会改变 HEAD、暂存区和工作文件。当前冻结源码在 0.7.3 基础上累积了受限整文件/变更块/逐行暂存与取消暂存、commit/amend、从当前 HEAD 创建分支及两类标签、图片叠加/滑动比较和只读分支删除评估,计划以 **0.8.0** 收口,不再扩展功能。写操作必须先预览再明确确认,正文比较仍只读;不提供 fetch/pull/push、stash、merge 或冲突解决。
6
+
7
+ **0.8.0 发布验证:PENDING,尚未正式发布。** 最近一次记录的默认全量为 **3338/3348 通过、10 失败**,不能以专项测试代替默认全绿,也不表示日常 DSH GUI 已更新。见[本版说明](<https://github.com/f-e-n-g-0531/dsh-vcs/blob/main/docs/releases/0.8.0.md>)及[当前能力](<https://github.com/f-e-n-g-0531/dsh-vcs/blob/main/docs/CURRENT-CAPABILITIES.md>)。
6
8
 
7
9
  - npm 包:`@feng0531/dsh-vcs`
8
10
  - [下载正式版本](https://github.com/f-e-n-g-0531/dsh-vcs/releases/latest) · [查看更新](https://github.com/f-e-n-g-0531/dsh-vcs/blob/main/CHANGELOG.md)
@@ -18,7 +20,8 @@
18
20
  | 比较历史版本 | 比较提交与选定父提交,或选择两个本地提交进行 A/B 比较 |
19
21
  | 追溯代码来源 | 文件历史、唯一来源重命名追踪(含改名同时修改)、Blame(逐行查看最后修改者和提交) |
20
22
  | 搜索与定位 | 在固定提交中分页搜索内容,点击结果定位命中行;高级、基础与分段阅读支持目标行,返回保留结果与阅读设置 |
21
- | 查看其他内容 | 支持部分静态图片比较;较大历史 UTF-8 文件可分段阅读 |
23
+ | 查看其他内容 | 支持部分静态图片并排/叠加/滑动比较与双侧同步缩放;较大历史 UTF-8 文件可分段阅读 |
24
+ | 查看 HEAD 移动记录 | Reflog 只读查看最近200项,点击固定提交查看详情;不提供恢复、reset或checkout |
22
25
  | 浏览 SVN 历史 | 明确同意连接后,查看 HTTPS 仓库日志、修订差异和文件历史 |
23
26
  | 切换本地 Git 分支(0.6.0 起) | 独立入口预览当前/目标分支与提交,明确确认后执行;不是历史引用导航 |
24
27
 
@@ -75,7 +78,7 @@ VCS 顶部“更新插件”提供更新检查、宿主插件管理器与最新
75
78
 
76
79
  新增文件可能使用空白左侧。冲突文件只供查看,不提供三方合并或冲突解决。
77
80
 
78
- ### 确认式本地 Git 分支切换(0.6.0 候选)
81
+ ### 确认式本地 Git 分支切换
79
82
 
80
83
  历史页的分支下拉只改变阅读起点,**不会切换工作区**。实际切换使用独立的“切换本地分支”入口:先读取已有本地分支,选择目标并预览当前/目标完整引用及提交,再明确确认。预览约 60 秒失效,确认仅能使用一次;取消预览不执行切换,切换过程中不能重复提交。
81
84
 
@@ -89,9 +92,69 @@ VCS 顶部“更新插件”提供更新检查、宿主插件管理器与最新
89
92
 
90
93
  目前仅支持系统信任、**无需额外认证的 HTTPS SVN 服务**。不提供用户名/密码、自定义证书或其他协议。历史范围固定在本地工作副本的修订,不自动获取服务器最新版本。
91
94
 
95
+ ## 候选:确认式单文件取消暂存
96
+
97
+ 在Git“已暂存”模式选中普通修改文件后,使用“取消暂存”预览,核对路径、固定HEAD、原Index与目标OID/模式,再勾选确认。它只恢复该文件的Index条目,不改工作文件或其他暂存内容;不是逐行取消暂存,不执行reset。
98
+
99
+ 只支持工作字节仍等于Index的既有普通文件,拒绝选中MM、增删改名、冲突、unborn/detached、linked worktree、特殊Index、attributes/filters/hooks及扫描到的链接/硬链接。工作区含ignored/untracked也会扫描,每文件2MiB、总正文16MiB、最多2万节点,超限拒绝。过期或状态变化须重新预览;确认失败/取消可能结果未知,先点击恢复入口刷新核对,不自动重试或回滚。源码与隔离测试不等于正式发布或当前GUI已更新。
100
+
101
+ ## 候选:确认式单文件暂存
102
+
103
+ Git“未暂存”模式选择普通修改文件后,预览原Index与捕获字节对应的目标OID,勾选并确认。仅支持Index仍等于固定HEAD的既有文件,不支持所选MM/增删改名/冲突和内容转换;工作树扫描与取消暂存同样受限。浏览器不发送正文或路径,确认仅用一次性token。
104
+
105
+ Stage先追加已确认原始字节的blob,再CAS发布Index。取消/失败可能留下不可达blob,即使Index未改变也不能保证整个仓库毫无副作用;不会删除对象或GC回滚。结果未知时stage和unstage共用该仓库恢复门禁,显式刷新核对后再操作。
106
+
107
+ ## 候选:按完整变更块暂存
108
+
109
+ Git“未暂存”模式选中支持的普通文件后,读取精确块计划,勾选完整变更块,先生成候选预览,再核对并明确确认。计划和选择预览都只读;选择后重新修改勾选须重新获取计划。每侧最多256KiB、4000原始行及20万精确LCS格,显示真实换行标记,无近似写入。
110
+
111
+ 此入口按原子块选择,块内逐行使用下方独立入口;支持MM文件连续选择剩余块(按当前Index→Work,不重放HEAD差异);整文件stage/unstage仍拒绝MM。二进制/非UTF8、新增/删除/改名/冲突仍不支持;候选部分unstage见下文。工作文件保留所有修改,Index仅选中块;确认后取消的append-only副作用及恢复门禁与单文件stage一致。
112
+
113
+ ## 候选:按恢复块部分取消暂存
114
+
115
+ Git“已暂存”模式选中支持的M-space/MM文件后,读取Index→HEAD恢复计划。只撤回勾选的暂存块,其余暂存与全部工作修改保持。选择预览后核对候选OID,再独立确认;不是丢弃工作修改,不运行reset/checkout。
116
+
117
+ 每端256KiB/4000原始行/20万精确格,UTF8保留原始换行,原子块不可拆成任意逐行。计划/预览只读,确认可追加合成blob,取消后不保证对象不存在,不GC回滚。与其他Index操作共用pending/unknown门禁。
118
+
119
+ ## 候选:块内逐行选择
120
+
121
+ 精确逐行暂存(Index→Work)与逐行取消暂存(Index→HEAD)为每条删除/插入分别提供选择。未选旧行保留,选中目标行按目标序位于块内保留行之后;删除与插入不自动配对。先生成只读候选OID预览,再独立确认;工作文件不改。
122
+
123
+ 每输入及候选256KiB/4000行、精确LCS20万格、最多8000行操作。会合并原始行边界的EOF/CR-LF组合拒绝,不补换行。其余受限MM/仓库guard/append-only孤立对象及恢复门禁不变,不代表支持所有Git文件类型或配置。
124
+
125
+ ## 候选:显式提交预览与确认
126
+
127
+ Git已暂存模式可显式填写author/committer姓名邮箱、秒级时间/时区与消息,读取只读预览,核对父HEAD/分支、新tree/commit OID和原文,再独立确认一次token。内容仅来自完整Index,不自动暂存、不amend、不push,工作文件保留。
128
+
129
+ 初期仅支持已出生loose本地分支及既有reflog、普通stage0 Index、严格配置子集。initial/signed/hooks/packedrefs/shared-worktree/属性转换等拒绝,非一般Git提交兼容。提交作者与固定machine reflog审计身份不同;外部Git竞争不提供跨Index/ref全局原子性。确认中断需核对HEAD和Index,可能留下仅追加对象,不自动重试或回滚。
130
+
131
+ ## 候选:最近提交消息复用
132
+
133
+ 提交编辑器可显式读取最近HEAD的身份和原始消息。读取不会改草稿,点击复用才仅复制消息原文,不自动替换作者/提交者。复用立即作废旧预览,必须重新核对并确认;不是amend。CRLF/BOM/EOF状态保留,不支持的写入消息明确拒绝而不自动转换。
134
+
135
+ ## 候选:Amend历史替换
136
+
137
+ 独立amend编辑器显式填写提交者与消息,预览旧HEAD/旧tree、保留原作者和父列表,以及新tree/commitOID,再单独确认历史替换。支持受限same-tree消息修改,不自动stage、push或force。签名/hooks/packedrefs等当前严格拒绝,外部Git竞争不保证跨Index/ref全局原子。
138
+
139
+ ## 候选:从当前HEAD创建分支
140
+
141
+ 创建编辑器仅填写安全短名,预览服务器固定的HEAD起点/完整ref/当前分支后明确确认。创建不覆盖已有目标,不自动checkout、stage、commit或push;修改名称使旧预览失效,结果未知先核对refs和HEAD,不自动重试或删分支。当前严格Git子集和外部竞争限制保持。
142
+
143
+ ## 候选:删除分支只读评估
144
+
145
+ 输入短名可只读核对当前/目标tip和已合并祖先证明,明确不执行删除。无删除确认按钮、token或force入口;未合并/不完整历史/超限明确拒绝。评估不是未来删除授权,实际删除仍未开放。
146
+
147
+ ## 候选:当前HEAD的annotated tag
148
+
149
+ 显式填写短tag名、tagger和消息,先核对服务器固定HEAD、完整refs/tags和tag对象OID,再勾选单次确认。不覆盖已有标签,不签名、push或checkout;未知结果先核对引用和对象,不自动重试或删除。此入口仅支持严格 unsigned annotated 子集,不含任意起点;lightweight tag 使用下方独立入口。
150
+
151
+ ## 候选:当前HEAD的lightweight tag
152
+
153
+ 仅填写短tag名,核对固定HEAD和完整refs/tags后单次确认,引用直接指向commit,不生成annotated对象、不需要tagger或消息。与附注标签分开展示与授权;不覆盖、签名、push或checkout。未知结果先核对refs和HEAD,不自动重试或删除。
154
+
92
155
  ## 目前的限制
93
156
 
94
- - **不是完整的 Fork 客户端**:除上述确认式已有本地 Git 分支切换外,仓库浏览保持只读;不提供 stage、commit、stash、force、fetch 或 push。历史图和列表都有容量限制;历史分支导航可使用本地分支、标签及本地缓存的远程跟踪引用,不连接远端。
157
+ - **不是完整的 Fork 客户端**:上述写入口均限严格 Git 子集,逐行选择仅限精确模型与受支持文件;分支删除仅只读评估,不执行删除。仍缺少远端 fetch/pull/push、stash、merge/rebase 与冲突解决,不提供 force。历史图和列表都有容量限制;历史分支导航可使用本地分支、标签及本地缓存的远程跟踪引用,不连接远端。
95
158
  - 普通文本比较每侧最多 **2MiB**。Git提交/A-B/工作区三个模式比较超限时可手动加载完整文本(UTF-8/GBK/带BOM的UTF-16),每侧最多 **8MiB、10万行**,单行最多65536字符;计算超时会明确提示结果不完整。工作区读取期间发生变化会拒绝结果,但不是系统级原子快照;SVN大文件仍不支持。
96
159
  - 内容搜索每页最多100条匹配,扫描最多64个文件/16MiB正文,匹配列表最多1MiB;固定提交树上限10万项/16MiB。超过16MiB的文件跳过并提示结果不完整,二进制排除;无匹配的扫描页仍可能有下一页。长命中行仅显示开头片段,打开文件可继续阅读。
97
160
  - 历史 UTF-8 正文分段最多 **16MiB**,每片64KiB;按全局行号定位,行片段有明确提示;基础单版本阅读每窗口最多500行。分段阅读不是完整 Diff。正文按固定对象缓存,最多 32MiB/8 项/60 秒,缓存命中仍重新验证请求授权。历史目录按需分页,每页最多 100 项,单目录仍有 10 万项和 16MiB 命令输出上限。
@@ -110,7 +173,7 @@ VCS 顶部“更新插件”提供更新检查、宿主插件管理器与最新
110
173
  - **高级编辑器加载失败**:确认安装了完整正式包并重新加载宿主;失败时仍可使用基础比较。
111
174
  - **SVN 历史连接失败**:先确认是受信任 HTTPS 服务,且不要求本插件未支持的额外认证。
112
175
 
113
- 正式版本通过自动测试、Windows/Linux 检查和隔离浏览器回归。**这些不证明你的当前 DSH 页面已加载新版,也不代替你的实际环境验证。**
176
+ 正式发布要求通过同标签自动测试、Windows/Linux 检查、隔离浏览器和精确宿主合同等门禁。**0.8.0 当前为 PENDING,最近记录的默认全量仍有 10 项失败;历史或专项通过不代表本版发布通过,也不证明你的当前 DSH 页面已加载新版。** 本次收口不安装、升级或重启日常 GUI/profile。
114
177
 
115
178
  ## 开发与更多资料
116
179
 
package/amend-host.mjs ADDED
@@ -0,0 +1,48 @@
1
+ import {createConfirmedOperationCoordinator} from './confirmed-operation.mjs';
2
+ import {encodeGitCommit} from './src/git-commit-object.mjs';
3
+
4
+ const invalid=message=>Object.assign(new Error(message),{code:'vcs/amend-confirmation-invalid'});
5
+ function record(value,keys,label){
6
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw invalid('Invalid '+label+' record.');
7
+ const result={};
8
+ for(const key of Reflect.ownKeys(value)){
9
+ if(!keys.includes(key))throw invalid('Unsupported '+label+' field.');
10
+ const descriptor=Object.getOwnPropertyDescriptor(value,key);
11
+ if(!descriptor||!Object.hasOwn(descriptor,'value'))throw invalid(label+' requires own data properties.');
12
+ result[key]=descriptor.value;
13
+ }
14
+ return result;
15
+ }
16
+ const identityKeys=['name','email','timestamp','timezone'];
17
+ const projectIdentity=value=>Object.fromEntries(identityKeys.map(key=>[key,value[key]]));
18
+ function capture(address){
19
+ const saved=record(address,['sessionId','repositoryId','committer','message'],'amend address');
20
+ saved.committer=record(saved.committer,identityKeys,'committer');
21
+ if(typeof saved.sessionId!=='string'||!saved.sessionId||typeof saved.repositoryId!=='string'||!saved.repositoryId)throw invalid('Session and repository identifiers are required.');
22
+ if(typeof saved.message!=='string'||Buffer.byteLength(saved.message)>65536||!saved.message.trim()||/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/u.test(saved.message.replace(/[\n\t]/g,'')))throw invalid('Bounded plaintext commit message required.');
23
+ // Validate the owned scalar metadata with the same pure bounds as the adapter.
24
+ try{encodeGitCommit({tree:'1'.repeat(40),author:saved.committer,committer:saved.committer,message:saved.message});}
25
+ catch{throw invalid('Invalid commit identity or message.');}
26
+ Object.freeze(saved.committer);return Object.freeze(saved);
27
+ }
28
+
29
+ // Internal host adapter: authenticated grants and authorization callbacks remain
30
+ // the caller's responsibility. No raw browser repository paths or execution plans.
31
+ export function createAmendCoordinator({api,now=Date.now,ttlMs=60000,maxTokens=32}){
32
+ const coordinator=createConfirmedOperationCoordinator({
33
+ operationKind:'amend',now,ttlMs,maxTokens,
34
+ prepare:(repository,{address,signal})=>api.prepareAmendPreview({type:repository.type,root:repository.root},{committer:address.committer,message:address.message,signal}),
35
+ execute:(repository,request)=>api.applyAmendPreview({type:repository.type,root:repository.root},request),
36
+ project:snapshot=>({action:'amend',head:snapshot.head,ref:snapshot.ref,objectFormat:snapshot.objectFormat,indexDigest:snapshot.indexDigest,previousTree:snapshot.previousTree,parents:[...snapshot.parents],tree:snapshot.tree,commit:{oid:snapshot.commit.oid},author:projectIdentity(snapshot.author),committer:projectIdentity(snapshot.committer),message:snapshot.message}),
37
+ invalidCode:'vcs/amend-confirmation-invalid',
38
+ unknownCode:'vcs/amend-outcome-unknown',
39
+ unknownMessage:'Amend rewrites history. Amend started but its final result could not be confirmed. Append-only object writes may remain. Refresh the repository and inspect HEAD and the index before preparing another amend. Never retry automatically or roll back appended objects.',
40
+ });
41
+ return {
42
+ // Capture before invoking even an asynchronous adapter or authorization callback.
43
+ async prepare(address,binding){return coordinator.prepare(capture(address),binding);},
44
+ confirm:(address,binding)=>coordinator.confirm(address,binding),
45
+ invalidate:entry=>coordinator.invalidate(entry),
46
+ clear:()=>coordinator.clear(),
47
+ };
48
+ }
@@ -0,0 +1,42 @@
1
+ import {createConfirmedOperationCoordinator} from './confirmed-operation.mjs';
2
+
3
+ const invalid=message=>Object.assign(new Error(message),{code:'vcs/branch-create-confirmation-invalid'});
4
+ function capture(address){
5
+ if(!address||typeof address!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(address)))throw invalid('Invalid branch-create address record.');
6
+ const keys=['sessionId','repositoryId','name'],saved={};
7
+ for(const key of Reflect.ownKeys(address)){
8
+ if(!keys.includes(key))throw invalid('Unsupported branch-create address field.');
9
+ const descriptor=Object.getOwnPropertyDescriptor(address,key);
10
+ if(!descriptor||!Object.hasOwn(descriptor,'value'))throw invalid('Branch-create address requires own data properties.');
11
+ saved[key]=descriptor.value;
12
+ }
13
+ if(keys.some(key=>!Object.hasOwn(saved,key))||typeof saved.sessionId!=='string'||!saved.sessionId||typeof saved.repositoryId!=='string'||!saved.repositoryId)throw invalid('Session, repository and branch name are required.');
14
+ // Keep these portable short-name bounds aligned with branch-create-preview.
15
+ const name=saved.name;
16
+ if(typeof name!=='string'||!name||Buffer.from(name,'utf8').toString('utf8')!==name||Buffer.byteLength(name,'utf8')>1000||
17
+ name==='@'||name.toUpperCase()==='HEAD'||name.startsWith('-')||name.startsWith('refs/')||/[\x00-\x20\x7f~^:?*\[\\<>"|\p{Cc}\p{Cf}]/u.test(name)||name.includes('..')||name.includes('@{')||
18
+ name.split('/').some(p=>!p||Buffer.byteLength(p,'utf8')>255||p.startsWith('.')||/[. ]$/.test(p)||p.toLowerCase().endsWith('.lock')||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))
19
+ throw invalid('Safe portable short branch name required.');
20
+ return Object.freeze(saved);
21
+ }
22
+
23
+ // Internal adapter, not an authorization layer: bindings and authorization callbacks
24
+ // must come from the authenticated host. No browser OID, ref or execution plan.
25
+ export function createBranchCreateCoordinator({api,now=Date.now,ttlMs=60000,maxTokens=32}){
26
+ const coordinator=createConfirmedOperationCoordinator({
27
+ operationKind:'branch-create',now,ttlMs,maxTokens,
28
+ prepare:(repository,{address,signal})=>api.prepareBranchCreate({type:repository.type,root:repository.root},{name:address.name,signal}),
29
+ execute:(repository,request)=>api.applyBranchCreate({type:repository.type,root:repository.root},request),
30
+ project:snapshot=>({action:'branch-create',name:snapshot.name,ref:snapshot.ref,target:{oid:snapshot.target.oid},head:snapshot.head,currentRef:snapshot.currentRef,objectFormat:snapshot.objectFormat}),
31
+ invalidCode:'vcs/branch-create-confirmation-invalid',
32
+ unknownCode:'vcs/branch-create-outcome-unknown',
33
+ unknownMessage:'Branch creation started but its final result could not be confirmed. Refresh the repository and inspect refs and HEAD before preparing another branch creation. Never retry automatically or roll back.',
34
+ });
35
+ return {
36
+ // Capture own scalar data synchronously, before adapter or authorization awaits.
37
+ async prepare(address,binding){return coordinator.prepare(capture(address),binding);},
38
+ confirm:(address,binding)=>coordinator.confirm(address,binding),
39
+ invalidate:entry=>coordinator.invalidate(entry),
40
+ clear:()=>coordinator.clear(),
41
+ };
42
+ }
@@ -0,0 +1,196 @@
1
+ // Preview is read-only; its exact frozen summary is a private single-use capability.
2
+ // Supports canonical embedded, born symbolic-HEAD repositories only; packed refs
3
+ // (even unrelated) and reftable are conservatively refused. This is NOT all Git.
4
+ // Barriers detect observed changes, not global atomicity or hostile path swaps.
5
+ import * as fs from 'node:fs/promises';
6
+ import {constants} from 'node:fs';
7
+ import path from 'node:path';
8
+ import {readLatestCommit} from './latest-commit.mjs';
9
+ import {git as safeGit} from './local-command.mjs';
10
+ import {createLocalBranch} from './git-branch-create.mjs';
11
+ import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
12
+ const prepared=new WeakMap();
13
+
14
+ const fail=message=>Object.assign(new Error(message),{code:'vcs/branch-create-preview'});
15
+ const check=()=>currentOperationBudget().throwIfExpired();
16
+ const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
17
+ const identity=s=>[s.dev,s.ino,s.birthtimeNs].map(String);
18
+ const version=s=>[...identity(s),s.size,s.mtimeNs,s.ctimeNs,s.mode].map(String);
19
+ const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
20
+ function record(value,keys,label){
21
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw fail('Invalid '+label+' record');
22
+ const out={};for(const key of Reflect.ownKeys(value)){
23
+ if(!keys.includes(key))throw fail('Unsupported '+label+' field');
24
+ const d=Object.getOwnPropertyDescriptor(value,key);
25
+ if(!d||!Object.hasOwn(d,'value'))throw fail(label+' requires own data properties');
26
+ out[key]=d.value;
27
+ }return out;
28
+ }
29
+ function validateName(name){
30
+ if(typeof name!=='string'||!name||Buffer.from(name,'utf8').toString('utf8')!==name||Buffer.byteLength(name,'utf8')>1000||
31
+ name==='@'||name.toUpperCase()==='HEAD'||name.startsWith('-')||name.startsWith('refs/')||/[\x00-\x20\x7f~^:?*\[\\<>"|\p{Cc}\p{Cf}]/u.test(name)||name.includes('..')||name.includes('@{')||
32
+ name.split('/').some(p=>!p||Buffer.byteLength(p,'utf8')>255||p.startsWith('.')||/[. ]$/.test(p)||p.toLowerCase().endsWith('.lock')||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))
33
+ throw fail('Safe portable short branch name required');
34
+ }
35
+ async function stat(file){check();try{return await fs.lstat(file,{bigint:true});}catch(error){if(error.code==='ENOENT')return null;throw error;}}
36
+ async function directory(file){
37
+ const s=await stat(file);if(!s||!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(file)!==file)throw fail('Canonical metadata directory required');return s;
38
+ }
39
+ async function raw(file,max){
40
+ check();const before=await stat(file);
41
+ if(!before||!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});if(!plain(opened)||!equal(version(before),version(opened)))throw fail('Stale metadata opening');
45
+ const bytes=Buffer.alloc(max+1);let n=0;
46
+ while(n<bytes.length){check();const r=await handle.read(bytes,n,bytes.length-n,n);if(!r.bytesRead)break;n+=r.bytesRead;}
47
+ const after=await handle.stat({bigint:true}),now=await stat(file);
48
+ if(n>max||!now||!plain(now)||!equal(version(opened),version(after))||!equal(version(after),version(now))||BigInt(n)!==after.size)throw fail('Stale metadata reading');
49
+ return [version(after),bytes.subarray(0,n).toString('hex')];
50
+ }finally{await handle.close();}
51
+ }
52
+ // Match the full reader's metadata policy without reading object/index/hook bodies.
53
+ const forbidden=new Set(['commondir','gitdir','shallow','config.worktree','MERGE_HEAD','MERGE_MSG','CHERRY_PICK_HEAD','REVERT_HEAD','REBASE_HEAD','BISECT_LOG','BISECT_START','rebase-merge','rebase-apply','sequencer','worktrees','info/sparse-checkout','info/attributes','objects/info/alternates','objects/info/http-alternates'].map(s=>s.toLowerCase()));
54
+ const effectiveConfig=root=>safeGit(root,['--git-dir='+path.join(root,'.git'),'--work-tree='+root,'config','--no-includes','--null','--list'],256*1024);
55
+ async function capture(root,name,created=false){
56
+ check();const rootStat=await directory(root),git=path.join(root,'.git'),gitStat=await directory(git);
57
+ const entries=await fs.readdir(git);
58
+ if(entries.some(n=>['packed-refs','reftable'].includes(n.toLowerCase())))throw fail('Unsupported packed refs or reftable');
59
+ for(const expected of ['HEAD','config','refs','logs'])if(entries.some(n=>n.toLowerCase()===expected.toLowerCase()&&n!==expected))throw fail('Noncanonical metadata spelling');
60
+ const head=await raw(path.join(git,'HEAD'),4096),config=await raw(path.join(git,'config'),256*1024);
61
+ const rows=[];let nodes=0;
62
+ async function visit(file,rel){
63
+ check();if(++nodes>20000)throw fail('Namespace metadata limit exceeded');
64
+ const s=await stat(file);if(!s){rows.push([rel,null]);return;}
65
+ if(s.isSymbolicLink()||(!s.isDirectory()&&!plain(s))||await fs.realpath(file)!==file)throw fail('Linked or special namespace metadata');
66
+ const key=rel.toLowerCase();
67
+ 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);
68
+ rows.push([rel,version(s)]);
69
+ if(s.isDirectory()){
70
+ const names=await fs.readdir(file);if(names.length>20000-nodes)throw fail('Metadata inspection limit exceeded');
71
+ for(const entry of names.sort())await visit(path.join(file,entry),rel?rel+'/'+entry:entry);
72
+ }
73
+ }
74
+ await visit(git,'');
75
+ for(const base of ['refs','logs'])if(!entries.includes(base))rows.push([base,null]);
76
+ // Inspect every prefix, including the reflog namespace. An existing final
77
+ // directory is a collision too. Case-fold aliases fail closed on every OS.
78
+ for(const parts of created?[]:[['refs','heads',...name.split('/')],['logs','refs','heads',...name.split('/')]]){
79
+ let parent=git;
80
+ for(let i=0;i<parts.length;i++){
81
+ check();const names=await fs.readdir(parent),part=parts[i];
82
+ const matches=names.filter(n=>n.toLowerCase()===part.toLowerCase());
83
+ if(!matches.length)break;
84
+ if(matches.length!==1||matches[0]!==part)throw fail('Portable target namespace collision');
85
+ const file=path.join(parent,part),s=await stat(file);
86
+ if(i===parts.length-1||!s||!s.isDirectory()||s.isSymbolicLink())throw fail('Target branch or prefix/reflog collision');
87
+ if(await fs.realpath(file)!==file)throw fail('Noncanonical target prefix');parent=file;
88
+ }
89
+ }
90
+ check();return {root:identity(rootStat),git:identity(gitStat),head,config,rows};
91
+ }
92
+ /** Prepare only from authenticated CURRENT HEAD, never a caller-provided OID.
93
+ * No index/worktree contents are read. Preview makes no writes or temporary hooks.
94
+ * The exact returned object binds apply authority privately; copies carry none.
95
+ * Raw HEAD/config and namespace versions span BOTH readLatestCommit calls;
96
+ * effective configuration is pinned before full-reader policy validation.
97
+ * Concurrent mutation followed by restoration can escape observation barriers.
98
+ */
99
+ export async function prepareBranchCreate(repo,options={}){
100
+ const r=record(repo,['type','root'],'repository'),o=record(options,['name','signal'],'options');
101
+ if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root)throw fail('Canonical Git root required');
102
+ validateName(o.name);
103
+ if(o.signal!==undefined){try{Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get,o.signal,[]);}catch{throw fail('Native AbortSignal required');}}
104
+ const name=o.name,ref='refs/heads/'+name;
105
+ return withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
106
+ const before=await capture(r.root,name),configBaseline=await effectiveConfig(r.root);
107
+ // No caller callbacks between this baseline and strict full-reader validation.
108
+ const first=await readLatestCommit({type:r.type,root:r.root},{signal:o.signal});
109
+ const last=await readLatestCommit({type:r.type,root:r.root},{signal:o.signal});
110
+ const after=await capture(r.root,name); // Includes absence after the second read.
111
+ if(!(await effectiveConfig(r.root)).equals(configBaseline)||first.head!==last.head||first.ref!==last.ref||first.objectFormat!==last.objectFormat||!equal(before,after))throw fail('Stale repository changed during branch preview');
112
+ check();const summary=Object.freeze({action:'branch-create',name,ref,target:Object.freeze({oid:first.head}),head:first.head,currentRef:first.ref,objectFormat:first.objectFormat});
113
+ prepared.set(summary,{root:r.root,name,before,configBaseline,head:first.head,currentRef:first.ref,objectFormat:first.objectFormat,ref});return summary;
114
+ });
115
+ }
116
+
117
+ function createdCapture(before,after,ref){
118
+ for(const key of ['root','git','head','config'])if(!equal(before[key],after[key]))throw fail('Original repository metadata changed');
119
+ const targets=new Set([ref,'logs/'+ref]),ancestors=new Set(['']);
120
+ for(const target of targets){const parts=target.split('/');for(let i=1;i<parts.length;i++)ancestors.add(parts.slice(0,i).join('/'));}
121
+ const old=new Map(before.rows),now=new Map(after.rows);
122
+ const isDir=v=>v!=null&&(Number(v[6])&0o170000)===0o040000;
123
+ for(const [name,v] of old){
124
+ const n=now.get(name);
125
+ if(equal(v,n))continue;
126
+ // Only ancestor mkdir timestamps/size may change; preserve identity and mode.
127
+ // Never replace the original baseline with a fresh one.
128
+ if(ancestors.has(name)&&isDir(n)&&(v===null||isDir(v)&&equal(v.slice(0,3),n.slice(0,3))&&v[6]===n[6]))continue;
129
+ throw fail('Existing namespace row changed: '+name);
130
+ }
131
+ for(const [name,v] of now)if(!old.has(name)||old.get(name)===null){
132
+ if(targets.has(name)&&v!==null&&!isDir(v))continue;
133
+ if(ancestors.has(name)&&isDir(v))continue;
134
+ if(v===null&&old.get(name)===null)continue;
135
+ throw fail('Unexpected namespace addition: '+name);
136
+ }
137
+ if(!now.has(ref)||now.get(ref)===null)throw fail('Created target missing');
138
+ }
139
+
140
+ /** Apply an exact prepare result once. Caller MUST hold its repository writer
141
+ * mutex throughout. Reads, callbacks and primitive share one inherited <=15s
142
+ * budget, not a globally atomic filesystem snapshot. No name/OID overrides.
143
+ * Authorization may be async; trusted onStart MUST be synchronous.
144
+ * Returns {name,ref,commit,currentRef}, with commit fixed at preview HEAD.
145
+ * Every post-start failure is outcome-unknown: never retry or roll back a ref.
146
+ */
147
+ export async function applyBranchCreate(repo,options={}){
148
+ // Burn before any validation, callback or await. Never invoke token getters.
149
+ const descriptor=options&&typeof options==='object'?Object.getOwnPropertyDescriptor(options,'snapshot'):undefined;
150
+ const snapshot=descriptor&&Object.hasOwn(descriptor,'value')?descriptor.value:undefined;
151
+ const bound=prepared.get(snapshot);prepared.delete(snapshot);
152
+ const r=record(repo,['type','root'],'repository'),o=record(options,['snapshot','signal','assertAuthorized','onStart'],'options');
153
+ if(!bound||r.type!=='git'||r.root!==bound.root)throw fail('Missing, consumed or cross-repository branch snapshot');
154
+ if(typeof o.assertAuthorized!=='function'||typeof o.onStart!=='function')throw fail('Authorization and synchronous start callbacks required');
155
+ if(o.signal!==undefined){try{Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get,o.signal,[]);}catch{throw fail('Native AbortSignal required');}}
156
+ const fixedRepo={type:'git',root:bound.root};let started=false;
157
+ const facts=async()=>{
158
+ if(!(await effectiveConfig(bound.root)).equals(bound.configBaseline))throw fail('Effective Git configuration changed');
159
+ const direct=await raw(path.join(bound.root,'.git',...bound.currentRef.split('/')),4096);
160
+ // Full, direct OID bytes, never Git DWIM or a newly resolved symbolic ref.
161
+ if(![bound.head,bound.head+'\n'].some(text=>direct[1]===Buffer.from(text).toString('hex')))throw fail('Original HEAD facts changed');
162
+ };
163
+ const fresh=async()=>{
164
+ if(!equal(bound.before,await capture(bound.root,bound.name)))throw fail('Stale branch snapshot');
165
+ await facts();
166
+ if(!equal(bound.before,await capture(bound.root,bound.name)))throw fail('Stale branch snapshot');
167
+ check();
168
+ };
169
+ const post=async()=>{
170
+ createdCapture(bound.before,await capture(bound.root,bound.name,true),bound.ref);
171
+ await facts();
172
+ const target=path.join(bound.root,'.git',...bound.ref.split('/'));
173
+ const direct=await raw(target,4096);
174
+ if(direct[1]!==Buffer.from(bound.head+'\n').toString('hex'))throw fail('Created target is not the fixed direct commit');
175
+ const final=await capture(bound.root,bound.name,true);
176
+ createdCapture(bound.before,final,bound.ref);
177
+ if(!equal(new Map(final.rows).get(bound.ref),direct[0]))throw fail('Created target changed after raw verification');
178
+ check();
179
+ };
180
+ try{return await withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
181
+ // Authenticate policy and target bytes once, retaining PREPARE's metadata/config.
182
+ await fresh();
183
+ const latest=await readLatestCommit(fixedRepo,{signal:o.signal});
184
+ if(latest.head!==bound.head||latest.ref!==bound.currentRef||latest.objectFormat!==bound.objectFormat)throw fail('Original HEAD facts changed');
185
+ await fresh();
186
+ await createLocalBranch(fixedRepo,{ref:bound.ref,commit:bound.head,objectFormat:bound.objectFormat,signal:o.signal,
187
+ assertAuthorized:async()=>{check();await o.assertAuthorized();check();if(!started)await fresh();},
188
+ onStart:()=>{started=true;return o.onStart();}});
189
+ await post();
190
+ await o.assertAuthorized();check();await post();
191
+ return {name:bound.name,ref:bound.ref,commit:bound.head,currentRef:bound.currentRef};
192
+ });}catch(error){
193
+ if(started)throw Object.assign(new Error('Branch create outcome unknown; inspect before further action.',{cause:error}),{code:'vcs/branch-create-outcome-unknown',outcomeUnknown:true});
194
+ throw error;
195
+ }
196
+ }
@@ -0,0 +1,214 @@
1
+ // Internal confirmation capability. prepare remains read-only; apply requires a caller writer mutex.
2
+ // Trusted concurrency excludes raw-ref-type replacement after the last observation;
3
+ // Git old-OID CAS is NOT raw-type CAS (docs/BRANCH-DELETE-RAW-REF-RACE.md). No RPC/UI.
4
+ // Embedded born symbolic HEAD, direct loose target, no packed refs/shared metadata.
5
+ // Observation barriers detect changes, not hostile swaps or mutation-and-restoration.
6
+ import * as fs from 'node:fs/promises';
7
+ import {constants} from 'node:fs';
8
+ import path from 'node:path';
9
+ import {readLatestCommit} from './latest-commit.mjs';
10
+ import {deleteLocalBranch} from './git-branch-delete.mjs';
11
+ import {git} from './local-command.mjs';
12
+ import {parseVerifiedCommit} from './src/verified-commit.mjs';
13
+ import {createVerifiedBranchDeletePlan} from './src/verified-branch-delete-plan.mjs';
14
+ import {withOperationBudget,currentOperationBudget} from './src/operation-budget.mjs';
15
+ const capabilities=new WeakMap();
16
+ const BODY=2*1024*1024,TOTAL=16*1024*1024,NODES=10000;
17
+ const fail=message=>Object.assign(new Error(message),{code:'vcs/branch-delete-preview'});
18
+ const check=()=>currentOperationBudget().throwIfExpired();
19
+ const equal=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
20
+ const identity=s=>[s.dev,s.ino,s.birthtimeNs].map(String);
21
+ const version=s=>[...identity(s),s.size,s.mtimeNs,s.ctimeNs,s.mode].map(String);
22
+ const plain=s=>s.isFile()&&!s.isSymbolicLink()&&s.nlink===1n;
23
+ function record(value,keys,label){
24
+ if(!value||typeof value!=='object'||![Object.prototype,null].includes(Object.getPrototypeOf(value)))throw fail('Invalid '+label+' record');
25
+ const out=Object.create(null);for(const key of Reflect.ownKeys(value)){
26
+ if(!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
+ }return out;
31
+ }
32
+ function validateName(name){
33
+ if(typeof name!=='string'||!name||Buffer.from(name,'utf8').toString('utf8')!==name||Buffer.byteLength(name,'utf8')>1000||
34
+ name==='@'||name.toUpperCase()==='HEAD'||name.startsWith('-')||name.startsWith('refs/')||/[\x00-\x20\x7f~^:?*\[\\<>"|\p{Cc}\p{Cf}]/u.test(name)||name.includes('..')||name.includes('@{')||
35
+ name.split('/').some(p=>!p||Buffer.byteLength(p,'utf8')>255||p.startsWith('.')||/[. ]$/.test(p)||p.toLowerCase().endsWith('.lock')||/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(p)))
36
+ throw fail('Safe portable short branch name required');
37
+ }
38
+ async function stat(file){check();try{return await fs.lstat(file,{bigint:true});}catch(error){if(error.code==='ENOENT')return null;throw error;}}
39
+ async function directory(file){
40
+ const s=await stat(file);if(!s||!s.isDirectory()||s.isSymbolicLink()||await fs.realpath(file)!==file)throw fail('Canonical metadata directory required');return s;
41
+ }
42
+ async function raw(file,max){
43
+ check();const before=await stat(file);
44
+ if(!before||!plain(before)||before.size>BigInt(max))throw fail('Bounded single-link metadata file required');
45
+ const handle=await fs.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW||0));
46
+ try{
47
+ const opened=await handle.stat({bigint:true});if(!plain(opened)||!equal(version(before),version(opened)))throw fail('Stale metadata opening');
48
+ const bytes=Buffer.alloc(max+1);let n=0;
49
+ while(n<bytes.length){check();const r=await handle.read(bytes,n,bytes.length-n,n);if(!r.bytesRead)break;n+=r.bytesRead;}
50
+ const after=await handle.stat({bigint:true}),now=await stat(file);
51
+ if(n>max||!now||!plain(now)||!equal(version(opened),version(after))||!equal(version(after),version(now))||BigInt(n)!==after.size)throw fail('Stale metadata reading');
52
+ return [version(after),bytes.subarray(0,n).toString('hex')];
53
+ }finally{await handle.close();}
54
+ }
55
+
56
+ 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()));
57
+ async function metadata(directory){
58
+ const rows=[];let nodes=0;
59
+ async function visit(file,relative){
60
+ check();if(++nodes>20000)throw fail('Metadata inspection limit exceeded');
61
+ const key=relative.toLowerCase();
62
+ if(forbidden.has(key)||key.endsWith('.lock')||key.endsWith('.promisor')||key.startsWith('sharedindex.')||key.startsWith('hooks/')&&!key.endsWith('.sample'))throw fail('Unsupported repository metadata: '+relative);
63
+ const s=await fs.lstat(file,{bigint:true});
64
+ if(s.isSymbolicLink()||(!s.isDirectory()&&!plain(s))||await fs.realpath(file)!==file)throw fail('Linked or special repository metadata');
65
+ rows.push([relative,version(s)]);
66
+ if(s.isDirectory()){const names=await fs.readdir(file);check();if(names.length>20000-nodes)throw fail('Metadata inspection limit exceeded');for(const name of names.sort())await visit(path.join(file,name),relative?relative+'/'+name:name);}
67
+ }
68
+ await visit(directory,'');return rows;
69
+ }
70
+
71
+ // Pin effective system/global/local configuration without expanding includes.
72
+ const effectiveConfig=root=>git(root,['--git-dir='+path.join(root,'.git'),'--work-tree='+root,'config','--no-includes','--null','--list'],256*1024);
73
+ async function capture(root,name){
74
+ check();const rootStat=await directory(root),gitDir=path.join(root,'.git');await directory(gitDir);
75
+ const rows=await metadata(gitDir);
76
+ const entries=await fs.readdir(gitDir);
77
+ for(const expected of ['HEAD','config','refs','logs','objects','hooks'])if(entries.some(n=>n.toLowerCase()===expected.toLowerCase()&&n!==expected))throw fail('Noncanonical metadata spelling');
78
+ let parent=gitDir;const parts=['refs','heads',...name.split('/')];
79
+ for(let i=0;i<parts.length;i++){
80
+ check();const part=parts[i],matches=(await fs.readdir(parent)).filter(n=>n.toLowerCase()===part.toLowerCase());
81
+ if(matches.length!==1||matches[0]!==part)throw fail('Missing target or portable namespace collision');
82
+ const file=path.join(parent,part);
83
+ if(i<parts.length-1)await directory(file);
84
+ parent=file;
85
+ }
86
+ const head=await raw(path.join(gitDir,'HEAD'),4096),config=await raw(path.join(gitDir,'config'),256*1024),target=await raw(parent,65);
87
+ if(!equal(rows,await metadata(gitDir)))throw fail('Stale repository metadata during capture');
88
+ check();return {root:identity(rootStat),rows,head,config,target};
89
+ }
90
+ /** Strict own-data repo {type:'git',root} and options {name,signal?} only.
91
+ * 15s shared budget; <=20k metadata entries/scan, <=10k commits, <=2MiB/body,
92
+ * <=16MiB graph. All parents of BOTH tips must exist and pass strict verification.
93
+ * No worktree or index body opens. No network/lazy fetch. No force operation.
94
+ */
95
+ export async function prepareBranchDelete(repo,options={}){
96
+ const r=record(repo,['type','root'],'repository'),o=record(options,['name','signal'],'options');
97
+ if(r.type!=='git'||typeof r.root!=='string'||!path.isAbsolute(r.root)||path.resolve(r.root)!==r.root)throw fail('Canonical Git root required');
98
+ validateName(o.name);
99
+ if(o.signal!==undefined){try{Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get,o.signal,[]);}catch{throw fail('Native AbortSignal required');}}
100
+ const name=o.name,ref='refs/heads/'+name;
101
+ return withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
102
+ const before=await capture(r.root,name),configBaseline=await effectiveConfig(r.root);
103
+ const first=await readLatestCommit({type:r.type,root:r.root},{signal:o.signal});
104
+ validateName(first.ref.slice(11));
105
+ if(first.ref.toLowerCase()===ref.toLowerCase())throw fail('Cannot delete current branch or case-insensitive alias');
106
+ const text=Buffer.from(before.target[1],'hex').toString('latin1'),width=first.objectFormat==='sha1'?40:64;
107
+ if(!new RegExp('^[0-9a-f]{'+width+'}\\n?$').test(text)||/^0+\n?$/.test(text))throw fail('Target requires direct raw object id');
108
+ const oid=text.replace(/\n$/,''),current={ref:first.ref,oid:first.head},target={ref,oid};
109
+ const currentRaw=await raw(path.join(r.root,'.git',...current.ref.split('/')),65);
110
+ if(![current.oid,current.oid+'\n'].some(value=>Buffer.from(value).toString('hex')===currentRaw[1]))throw fail('Stale direct current ref');
111
+ if(!equal(before,await capture(r.root,name)))throw fail('Stale repository before traversal');
112
+ const queue=[...new Set([current.oid,target.oid])],seen=new Set(queue),objects=[];let total=0;
113
+ for(let i=0;i<queue.length;i++){
114
+ check();const oid=queue[i],body=await git(r.root,['cat-file','commit',oid],Math.min(BODY,TOTAL-total||1));
115
+ check();total+=body.length;if(total>TOTAL)throw fail('Aggregate object body byte limit exceeded');
116
+ const parsed=parseVerifiedCommit(body,{oid,objectFormat:first.objectFormat,signal:currentOperationBudget().signal});
117
+ objects.push({oid,body});
118
+ for(const parent of parsed.parents)if(!seen.has(parent)){
119
+ if(seen.size>=NODES)throw fail('Commit node limit exceeded');seen.add(parent);queue.push(parent);
120
+ }
121
+ }
122
+ if(!equal(before,await capture(r.root,name)))throw fail('Stale repository after traversal');
123
+ const last=await readLatestCommit({type:r.type,root:r.root},{signal:o.signal});
124
+ if(!equal(first,last)||!(await effectiveConfig(r.root)).equals(configBaseline)||!equal(currentRaw,await raw(path.join(r.root,'.git',...current.ref.split('/')),65))||!equal(before,await capture(r.root,name)))throw fail('Stale current facts or repository');
125
+ check();const plan=createVerifiedBranchDeletePlan({objectFormat:first.objectFormat,current,target,objects,signal:currentOperationBudget().signal});
126
+ check();const summary=Object.freeze({action:'branch-delete',name,ref,objectFormat:plan.objectFormat,current:plan.current,target:plan.target,merged:true,proof:plan.proof,planId:plan.id});
127
+ capabilities.set(summary,{root:r.root,name,ref,before,configBaseline,currentRaw,current,target,objectFormat:first.objectFormat,planId:plan.id});
128
+ return summary;
129
+ });
130
+ }
131
+
132
+ /** Internal only. Caller MUST hold the repository writer mutex and supply trusted
133
+ * callbacks. Exact summary identity is consumed synchronously, including invalid
134
+ * attempts. No clone, replay, overrides, rollback, checkout or graph recomputation.
135
+ * Full metadata versions pin the already hash-authenticated merged graph; this is
136
+ * observation safety, not hostile swaps/ABA isolation or atomic raw-ref-type CAS.
137
+ */
138
+ export async function applyBranchDelete(repo,options={}){
139
+ // Burn before record validation or any await; do not invoke a snapshot accessor.
140
+ const descriptor=options&&(typeof options==='object'||typeof options==='function')?Object.getOwnPropertyDescriptor(options,'snapshot'):undefined;
141
+ const snapshot=descriptor&&Object.hasOwn(descriptor,'value')?descriptor.value:undefined;
142
+ const authority=capabilities.get(snapshot);
143
+ if(authority)capabilities.delete(snapshot);
144
+ if(!authority)throw fail('Exact unused branch-delete snapshot required');
145
+ const r=record(repo,['type','root'],'repository');
146
+ const o=record(options,['snapshot','signal','assertAuthorized','onStart'],'options');
147
+ if(r.type!=='git'||r.root!==authority.root||typeof o.assertAuthorized!=='function'||typeof o.onStart!=='function')throw fail('Bound repository and authorization/start callbacks required');
148
+ if(o.signal!==undefined){try{Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,'aborted').get,o.signal,[]);}catch{throw fail('Native AbortSignal required');}}
149
+ const {root,name,ref,before,configBaseline,currentRaw,current,target,objectFormat}=authority;
150
+ const bound={type:'git',root};let started=false;
151
+ async function facts(){
152
+ if(!(await effectiveConfig(root)).equals(configBaseline))throw fail('Effective Git configuration changed');
153
+ // Format/policy were established by the full reader; retain EXACT prepare bytes.
154
+ if(!equal(currentRaw,await raw(path.join(root,'.git',...current.ref.split('/')),65)))throw fail('Original direct current ref changed');
155
+ }
156
+ async function fresh(){
157
+ check();if(!equal(before,await capture(root,name)))throw fail('Stale branch-delete snapshot');
158
+ await facts();
159
+ if(!equal(before,await capture(root,name)))throw fail('Stale authenticated current facts');
160
+ check();
161
+ }
162
+ const removed=new Set([ref,'logs/'+ref]),ancestors=new Set(['']);
163
+ for(const leaf of removed){let p=leaf;while(p.includes('/')){p=p.slice(0,p.lastIndexOf('/'));ancestors.add(p);}}
164
+ const original=new Map(before.rows);
165
+ async function deleted(){
166
+ check();const gitDir=path.join(root,'.git');
167
+ if(!equal(identity(await directory(root)),before.root))throw fail('Repository identity changed');
168
+ await directory(gitDir);const rows=await metadata(gitDir),now=new Map(rows);
169
+ for(const leaf of removed)if(now.has(leaf)||await stat(path.join(gitDir,...leaf.split('/'))))throw fail('Deleted target or reflog reappeared');
170
+ for(const [key,v] of rows){
171
+ const old=original.get(key);if(!old)throw fail('Unrelated metadata added');
172
+ if(ancestors.has(key)){
173
+ // Existing ancestor directories retain identity/type/mode, not size/times.
174
+ if(!equal(v.slice(0,3),old.slice(0,3))||v[6]!==old[6])throw fail('Ancestor directory replaced');
175
+ }else if(!equal(v,old))throw fail('Unrelated metadata changed');
176
+ }
177
+ for(const [key,v] of before.rows)if(!now.has(key)&&!removed.has(key)){
178
+ if(!key||!ancestors.has(key)||(BigInt(v[6])&0o170000n)!==0o040000n)throw fail('Unrelated metadata disappeared');
179
+ // Only ancestors made empty by the exact two removals may be pruned.
180
+ for(const [child] of before.rows)if(child.startsWith(key+'/')&&!removed.has(child)&&!ancestors.has(child))throw fail('Nonempty ancestor disappeared');
181
+ }
182
+ if(!equal(await raw(path.join(gitDir,'HEAD'),4096),before.head)||!equal(await raw(path.join(gitDir,'config'),256*1024),before.config))throw fail('Original HEAD/config changed');
183
+ await facts();
184
+ if(!equal(rows,await metadata(gitDir)))throw fail('Stale post-delete metadata');
185
+ check();
186
+ }
187
+ // Trusted authorization may remain pending. Race only its wait, never continue
188
+ // mutation after cancellation; Promise.race also observes a late rejection.
189
+ const authorization=async()=>{
190
+ check();const signal=currentOperationBudget().signal;let abort;
191
+ const cancelled=new Promise((_,reject)=>{abort=()=>reject(signal.reason);signal.addEventListener('abort',abort,{once:true});if(signal.aborted)abort();});
192
+ try{await Promise.race([Promise.resolve().then(()=>{check();return o.assertAuthorized();}),cancelled]);check();}
193
+ finally{signal.removeEventListener('abort',abort);}
194
+ };
195
+ const authorize=async()=>{
196
+ if(started){await deleted();await authorization();check();await deleted();}
197
+ else{await fresh();await authorization();check();await fresh();}
198
+ };
199
+ try{
200
+ return await withOperationBudget({signal:o.signal,timeoutMs:15000},async()=>{
201
+ // One full policy/hash authentication; every later barrier retains prepare baselines.
202
+ await fresh();
203
+ const latest=await readLatestCommit(bound,{signal:o.signal});
204
+ if(latest.ref!==current.ref||latest.head!==current.oid||latest.objectFormat!==objectFormat)throw fail('Stale authenticated current facts');
205
+ await fresh();
206
+ await deleteLocalBranch(bound,{ref,expectedOid:target.oid,objectFormat,signal:o.signal,assertAuthorized:authorize,onStart:()=>{started=true;return o.onStart();}});
207
+ await deleted();await authorize();await deleted();check();
208
+ return Object.freeze({name,ref,deletedOid:target.oid,currentRef:current.ref,currentOid:current.oid});
209
+ });
210
+ }catch(cause){
211
+ if(started)throw Object.assign(new Error('Branch deletion outcome is unknown; inspect before any further action.',{cause}),{code:'vcs/branch-delete-outcome-unknown',outcomeUnknown:true});
212
+ throw cause;
213
+ }
214
+ }