UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 22.1 kB
import{a as e}from"./git-operation.worker-fs-safe-2XqdJR5K.mjs";import{D as t,w as n}from"./git-operation.worker-map-size-CypexNQj.mjs";import{a as r,c as i,i as a,o,r as s}from"./git-operation.worker-git-TpQcAIgG.mjs";import{Jt as c,Ut as l}from"./git-operation.worker.js";import{l as u,n as d,o as f,p,r as m,t as h,u as g}from"./git-operation.worker-schemas-6aIgnnYb.mjs";import{a as _,c as v,i as y,l as b,n as x,o as S,r as C,s as w,t as T}from"./git-operation.worker-git-path-inventory-BTOjkdj9.mjs";import{n as E,r as D,t as O}from"./git-operation.worker-git-worktree-operations.runtime-qkwXf5Xa.mjs";import{a as k,n as A}from"./git-operation.worker-staged-inputs-DZiTgX91.mjs";import j,{constants as M}from"node:fs";import N from"node:fs/promises";import P from"node:path";import{createHash as F}from"node:crypto";const resetChunks=()=>l({type:`worktree.snapshot-provisioned-reset`,input:{}});function sameFileState(e,t){return e.dev===t.dev&&e.ino===t.ino&&e.mode===t.mode&&e.size===t.size&&e.mtimeMs===t.mtimeMs&&e.ctimeMs===t.ctimeMs}async function readProvisionedMembership(e,t){let n=/* @__PURE__ */ new Set,r=/* @__PURE__ */ new Set,i=/* @__PURE__ */ new Set;for(let o of y(t))for(let[t,s]of[[n,[`ls-files`,`--others`,`--ignored`,`--exclude-standard`,`-z`]],[r,[`ls-files`,`--cached`,`-z`]],[i,[`ls-tree`,`-r`,`--name-only`,`-z`,`HEAD`]]]){let n=await a(e,[`--literal-pathspecs`,...s,`--`,...o],{killProcessTree:!0});for(let e of b(n))t.add(e.toString(`utf8`))}return{ignoredUntracked:n,currentTracked:r,trackedAtHead:i}}async function snapshotProvisionedFiles(e,t,n){let r=await E(e,t);if(r===void 0)throw Error(`provisioned path ledger is unavailable`);let i=n?new Map(n.files.map(e=>[e.path,e])):void 0;if(i&&(i.size!==r.length||r.some(e=>!i.has(e.path)||i.get(e.path)?.mode!==e.mode)))throw Error(`provisioned exact-state membership or modes changed after capture`);if(r.every(e=>e.mode===null))return await resetChunks(),r.map(e=>({path:e.path,mode:null,chunks:0}));let{ignoredUntracked:a,currentTracked:o,trackedAtHead:s}=await readProvisionedMembership(e,r.filter(e=>e.mode!==null).map(e=>e.path));await resetChunks();let c=[];try{for(let t of r){if(t.mode===null){c.push({path:t.path,mode:null,chunks:0});continue}if(o.has(t.path))throw Error(`provisioned path is now tracked: ${t.path}`);if(s.has(t.path))throw Error(`provisioned path is tracked at HEAD: ${t.path}`);if(!a.has(t.path))throw Error(`provisioned path is no longer ignored: ${t.path}`);let r=await O(e,t.path),u=await N.open(t.target,M.O_RDONLY|(M.O_NOFOLLOW??0));try{await D(r);let e=await u.stat(),a=i?.get(t.path);if(a&&(a.size!==e.size||a.mode!==(e.mode&4095)))throw Error(`provisioned exact-state size or mode changed after capture: ${t.path}`);let o=n?F(n.algorithm).update(`blob ${e.size}\0`):void 0,s=Buffer.allocUnsafe(1048576),d=0,f=0;for(;f<e.size;){let{bytesRead:n}=await u.read(s,0,Math.min(s.byteLength,e.size-f),f);if(n===0)throw Error(`provisioned file changed while snapshotting: ${t.path}`);o?.update(s.subarray(0,n)),await l({type:`worktree.snapshot-provisioned-chunk`,input:{path:t.path,chunkIndex:d,data:s.subarray(0,n)}}),f+=n,d+=1}let[p,m]=await Promise.all([u.stat(),N.lstat(t.target)]);if(await D(r),!sameFileState(e,p)||!sameFileState(e,m))throw Error(`provisioned file changed while snapshotting: ${t.path}`);if(o&&o.digest(`hex`)!==a?.blob)throw Error(`provisioned exact-state bytes changed after capture: ${t.path}`);c.push({path:t.path,mode:e.mode&4095,chunks:d})}finally{await u.close()}}return c}catch(e){throw await resetChunks(),e}}function exactIndexObjects(e,t){let n=e.length-t,invalid=()=>/* @__PURE__ */ Error(`Unsupported or invalid exact-state index; source preserved`);if(n<12||e.toString(`ascii`,0,4)!==`DIRC`||![2,3,4].includes(e.readUInt32BE(4))||!F(t===20?`sha1`:`sha256`).update(e.subarray(0,n)).digest().equals(e.subarray(n)))throw invalid();let r=/* @__PURE__ */ new Map,add=(n,i,a)=>{if(n+t>i)throw invalid();let o=e.subarray(n,n+t).toString(`hex`);/^0+$/u.test(o)||r.set(o,a)},nul=(t,n)=>{let r=e.indexOf(0,t);if(r<t||r>=n)throw invalid();return r},i=12;for(let r=0;r<e.readUInt32BE(8);r++){let r=i;if(i+=42+t,i>n)throw invalid();let a=e.readUInt32BE(r+24);if((a&61440)==57344)throw Error(`Nested Git index objects cannot be snapshotted losslessly`);if(add(r+40,n,(a&61440)==16384?`tree`:`blob`),e.readUInt16BE(i-2)&16384&&(i+=2),e.readUInt32BE(4)===4){let t=0;do if(i>=n||++t>10)throw invalid();while(e[i++]&128);i=nul(i,n)+1}else i=r+Math.ceil((nul(i,n)+1-r)/8)*8;if(i>n)throw invalid()}for(;i<n;){if(i+8>n)throw invalid();let r=e.toString(`ascii`,i,i+4),a=i+8+e.readUInt32BE(i+4);if(i+=8,a>n)throw invalid();if(r===`TREE`)for(;i<a;){i=nul(i,a)+1;let n=e.indexOf(10,i);if(n<i||n>=a)throw invalid();let r=/^(-?\d+) (\d+)$/u.exec(e.toString(`ascii`,i,n));if(!r)throw invalid();i=n+1,Number(r[1])>=0&&(add(i,a,`tree`),i+=t)}else if(r===`REUC`)for(;i<a;){i=nul(i,a)+1;let n=[];for(let t=0;t<3;t++){let t=nul(i,a),r=e.toString(`ascii`,i,t);if(!/^[0-7]+$/u.test(r))throw invalid();n.push(Number.parseInt(r,8)),i=t+1}for(let e of n)if(e!==0){if((e&61440)==57344)throw Error(`Nested Git resolve-undo objects cannot be snapshotted losslessly`);add(i,a,`blob`),i+=t}}else if(![`link`,`UNTR`,`FSMN`,`EOIE`,`IEOT`].includes(r))throw Error(`Unsupported exact-state index extension ${r}; source preserved`);i=a}return r}const I=p().regex(/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u),L=g({path:p().regex(/^(?:[a-f0-9]{2})+$/u),kind:h([`file`,`symlink`,`directory`,`missing`]),mode:u().int().nonnegative(),mtimeMs:u().finite(),blob:I.optional(),provisioned:m(),size:u().int().nonnegative()}).strict();g({version:f(1),sourceIdentity:g({device:p().regex(/^\d+$/u),inode:p().regex(/^\d+$/u)}).strict(),retirementName:p().regex(/^\.openclaw-retiring-[a-f0-9-]{36}$/u),head:I,branch:p(),branchHead:I,indexSha256:p().regex(/^[a-f0-9]{64}$/u),index:g({blob:I,mode:u().int(),mtimeMs:u().finite()}).strict(),sharedIndex:g({name:p().regex(/^sharedindex\.[a-f0-9]{40}(?:[a-f0-9]{24})?$/u),blob:I}).strict().optional(),files:d(L)}).strict();const sha256=e=>F(`sha256`).update(e).digest(`hex`),R={GIT_AUTHOR_NAME:`OpenClaw`,GIT_AUTHOR_EMAIL:`openclaw@localhost`,GIT_COMMITTER_NAME:`OpenClaw`,GIT_COMMITTER_EMAIL:`openclaw@localhost`},assertSnapshotCurrent=()=>l({type:`worktree.assert-current`,input:{}});function checkedPath(e){let t=Buffer.from(e,`hex`);if(t.includes(0)||t[0]===47||t.includes(92)&&process.platform===`win32`||t.toString(`latin1`).split(`/`).some(e=>!e||e===`.`||e===`..`||e.toLowerCase()===`.git`)||process.platform===`win32`&&t.includes(58))throw Error(`Invalid path in exact-state snapshot`);return t}async function checkParents(e,n,r=!1){let i=[e];for(let t=n.indexOf(47);t!==-1;t=n.indexOf(47,t+1))i.push(T(e,n.subarray(0,t)));let a=await Promise.all(i.map(async n=>{let i=await N.lstat(n,{bigint:!0}).catch(i=>{if(!(r&&n!==e&&t(i)))throw i});if(i&&!i.isDirectory())throw Error(`Exact-state path has a non-directory parent; checkout preserved`);return{parent:n,stat:i}}));return()=>{for(let{parent:e,stat:t}of a){let n=j.lstatSync(e,{bigint:!0,throwIfNoEntry:!r});if(t?!n?.isDirectory()||n.dev!==t.dev||n.ino!==t.ino:n!==void 0)throw Error(`Exact-state parent directory changed; source preserved`)}}}function blobOid(e,t){return F(t).update(`blob ${e.length}\0`).update(e).digest(`hex`)}function quotePath(e){return`"`+[...e].map(e=>`\\${e.toString(8).padStart(3,`0`)}`).join(``)+`"`}async function captureExactState(e){let n={...e,paths:[...e.paths]},a=n.checkoutPath,c=await N.lstat(a,{bigint:!0});if(!c.isDirectory())throw Error(`Exact-state source is no longer a directory; source preserved`);let u=await i(a,[`config`,`--bool`,`core.sparseCheckout`]);if(u.code!==1&&(u.code!==0||u.stdout.trim()!==`false`))throw Error(`Exact-state retirement requires a full, non-sparse checkout; source preserved`);let d=await s(a,[`rev-parse`,`HEAD^{commit}`]),f=await s(a,[`rev-parse`,`refs/heads/${n.branch}^{commit}`]),p=await o(a,`index`),m=await N.lstat(p);if(!m.isFile())throw Error(`Exact-state retirement requires a regular Git index`);let h=await N.readFile(p),g=sha256(h);if(d!==n.expected.head||f!==n.expected.branchHead||g!==n.expected.indexSha256)throw Error(`Worktree HEAD, branch or index changed; checkout preserved`);let _=d.length===64?`sha256`:`sha1`;if(n.write){let e=h.length;for(let t of n.paths){let n=await v(T(a,t));e+=(n?.size??0)+1024+t.length*4}let t=0;for(let e of n.provisionedPaths){let n=await v(P.join(a,e));t+=n?.size??0}let i=P.resolve(a,await r(a,[`rev-parse`,`--git-common-dir`]));await l({type:`worktree.snapshot-capacity`,input:{demands:[{path:i,bytes:2*e},...n.temporaryDirectory?[{path:n.temporaryDirectory,bytes:2*e}]:[]],stateBytes:2*t,purpose:`worktree safety snapshot`}})}let y=[],putBlob=async(e,t)=>{let r=blobOid(t,_);if(n.write&&await s(a,[`hash-object`,`--no-filters`,`-w`,`--stdin`],{input:t})!==r)throw Error(`Git exact-state object verification failed`);return y.push(`100644 blob ${r}\t${e}\0`),r},b={blob:await putBlob(`index`,h),mode:m.mode&4095,mtimeMs:m.mtimeMs},x=exactIndexObjects(h,d.length===64?32:20),S=await r(a,[`rev-parse`,`--shared-index-path`]),C;if(S){let e=P.resolve(a,S),t=P.basename(e);if(!/^sharedindex\.[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(t))throw Error(`Invalid split-index dependency`);let n=await N.readFile(e);C={name:t,blob:await putBlob(t,n)};for(let[e,t]of exactIndexObjects(n,d.length===64?32:20))x.set(e,t)}for(let[e,t]of x)y.push(`${t===`tree`?`040000`:`100644`} ${t} ${e}\tindex-object-${e}\0`);let w=new Set(n.provisionedPaths.map(e=>Buffer.from(e).toString(`hex`))),E=new Map([...n.paths,...n.provisionedPaths.map(e=>Buffer.from(e))].map(e=>[e.toString(`hex`),e])),D=Array.from(E.values());for(let e of D)for(let t=e.indexOf(47);t!==-1;t=e.indexOf(47,t+1)){let n=e.subarray(0,t);E.set(n.toString(`hex`),n)}let O=[],k=[],A=[];for(let[e,n]of[...E].toSorted(([e],[t])=>e.localeCompare(t))){checkedPath(e);let r;try{await checkParents(a,n),r=await N.lstat(T(a,n))}catch(n){if(!t(n))throw n;O.push({path:e,kind:`missing`,mode:0,size:0,mtimeMs:0,provisioned:w.has(e)});continue}let i=r.isFile()?`file`:r.isSymbolicLink()?`symlink`:r.isDirectory()?`directory`:void 0;if(!i)throw Error(`Exact-state snapshot contains an unsupported file type; checkout preserved`);let o={path:e,kind:i,mode:r.mode&4095,size:r.size,mtimeMs:r.mtimeMs,provisioned:w.has(e)};if(i!==`directory`){let e=T(a,n),t;if(i===`symlink`)t=await N.readlink(e,{encoding:`buffer`});else{let n=await N.open(e,M.O_RDONLY|(M.O_NOFOLLOW??0));try{t=await n.readFile()}finally{await n.close()}}if(o.blob=blobOid(t,_),!o.provisioned){i===`symlink`?await putBlob(`symlink-${O.length}`,t):A.push({path:n,blob:o.blob});let e=i===`symlink`?`120000`:o.mode&73?`100755`:`100644`;k.push(Buffer.concat([Buffer.from(`${e} ${o.blob}\t`),n,Buffer.from([0])]))}}O.push(o)}if(n.write)for(let e=0;e<A.length;e+=128){await assertSnapshotCurrent();let t=A.slice(e,e+128),n=(await s(a,[`hash-object`,`--no-filters`,`-w`,`--stdin-paths`],{input:Buffer.from(t.map(e=>quotePath(e.path)+` `).join(``))})).split(` `);if(n.some((e,n)=>e!==t[n]?.blob)||n.length!==t.length)throw Error(`Worktree files changed during exact-state capture; checkout preserved`)}let j={version:1,sourceIdentity:{device:c.dev.toString(),inode:c.ino.toString()},retirementName:n.retirementName,head:d,branch:n.branch,branchHead:f,indexSha256:g,index:b,...C?{sharedIndex:C}:{},files:O},F=Buffer.from(JSON.stringify(j));return await putBlob(`manifest.json`,F),{metadata:j,digest:sha256(F),treeEntries:k,metadataEntries:y}}async function writeExactStateCommit(e,t){let n=await s(e,[`mktree`,`-z`],{input:Buffer.from(t.metadataEntries.join(``))});return await s(e,[`commit-tree`,n,`-p`,t.metadata.branchHead,`-m`,`OpenClaw worktree exact state v1`],{env:R})}const assertCurrent=()=>l({type:`worktree.assert-current`,input:{}});async function listCollapsedOtherPaths(e,t){return b(await a(e,[`ls-files`,`-z`,`--others`,...t?[`--ignored`]:[],`--exclude-standard`,`--directory`]))}async function walkCollapsedPaths(e,r,i){let visitDirectory=async r=>{if(await w(T(e,Buffer.concat([r,Buffer.from(`/.git`)]))))return!0;let a=T(e,r),o=r.toString(`utf8`),s;if(!o.includes(`�`))try{s=await N.readdir(P.join(e,o),{withFileTypes:!0})}catch(e){if(!t(e)&&!n(e,`ENAMETOOLONG`))throw e}s?.some(e=>e.name.includes(`�`))&&(s=void 0);let c=s?.map(e=>Buffer.from(e.name))??await N.readdir(a,{encoding:`buffer`});for(let t=0;t<c.length;t+=64){let n=c.slice(t,t+64).map((e,n)=>{let i=s?.[t+n];return{path:Buffer.concat([r,Buffer.from(`/`),e]),directory:i?.isDirectory()?!0:i&&(i.isFile()||i.isSymbolicLink())?!1:void 0}}).filter(e=>!i.skip?.has(C(e.path))),a=n.some(e=>e.directory===void 0)?await Promise.allSettled(n.map(async t=>t.directory??(await v(T(e,t.path)))?.isDirectory()??!1)):void 0;for(let[e,t]of n.entries()){let n=a?.[e];if(n?.status===`rejected`)throw n.reason;if(n?n.value:t.directory){if(await visitDirectory(t.path))return!0}else await i.visitFile?.(t.path)}}return!1};for(let e of r)if(e.at(-1)===47){if(await visitDirectory(e.subarray(0,-1)))return!0}else await i.visitFile?.(e);return!1}function unstattedIndexPaths(e){return e.filter(e=>e.assumeUnchanged||e.skipWorktree).map(e=>e.path)}async function inspectOtherPaths(e,t){let n=await listCollapsedOtherPaths(e,!1),r=/* @__PURE__ */ new Map;for(let e of[...t.deletedOrUnmergedPaths,...t.unstattedIndexPaths??[]])r.set(C(e),e);let i=[...r.values()];for(let t=0;t<i.length;t+=64){let r=i.slice(t,t+64),a=await Promise.allSettled(r.map(t=>v(T(e,t))));for(let[e,t]of a.entries())if(t.status===`rejected`)throw t.reason;else t.value?.isDirectory()&&n.push(Buffer.concat([r[e],Buffer.from(`/`)]))}let a=await listCollapsedOtherPaths(e,!0);if(await x(e,[...n,...a]))return!0;let o=new Set(a.map(e=>C(e.at(-1)===47?e.subarray(0,-1):e)));return await walkCollapsedPaths(e,n,{visitFile:t.untracked,skip:o})||await walkCollapsedPaths(e,a,{visitFile:t.ignored})}async function collectSnapshotInventory(t){let n=await s(t.checkoutPath,[`rev-parse`,`--verify`,`HEAD^{commit}`]),r=_(await a(t.checkoutPath,[`ls-files`,`--stage`,`-v`,`-z`])),o=new Set(t.provisionedPaths.map(e=>C(Buffer.from(e)))),u=/* @__PURE__ */ new Map,add=e=>{let t=C(e);o.has(t)||u.set(t,e)},d=b(await a(t.checkoutPath,[`-c`,`core.ignoreStat=false`,`-c`,`core.trustctime=true`,`-c`,`core.checkStat=default`,...process.platform===`win32`?[]:[`-c`,`core.filemode=true`],`--no-optional-locks`,`status`,`--porcelain=v1`,`-z`,`--untracked-files=no`,`--no-renames`])),f=A(await e(t.checkoutPath)),p=0;if(await inspectOtherPaths(t.checkoutPath,{deletedOrUnmergedPaths:d.filter(e=>{let t=e.toString(`ascii`,0,2);return t[1]===`D`||t.includes(`U`)||t===`AA`}).map(e=>e.subarray(3)),unstattedIndexPaths:unstattedIndexPaths(r),untracked:async e=>{p++,add(e)},ignored:async e=>{let t=e.toString(`utf8`);k(t)&&await f(t)&&add(e)}})||await x(t.checkoutPath,r.map(e=>e.path)))throw Error(`nested git repositories cannot be snapshotted losslessly`);if(await l({type:`worktree.snapshot-inventory`,input:{tracked:r.length,untracked:p}}),!t.exactState&&d.length===0&&p===0&&u.size===0&&r.every(e=>!e.assumeUnchanged&&!e.skipWorktree&&e.mode!==`160000`))return t.provisionedPaths.length>0&&assertNoProvisionedTreePaths(r,t.provisionedPaths),{head:n,paths:u,changed:/* @__PURE__ */ new Set};let m=S(await a(t.checkoutPath,[`ls-tree`,`-r`,`-z`,n])),h=await i(t.checkoutPath,[`config`,`--bool`,`core.sparseCheckout`]);if(h.code!==0&&h.code!==1)throw c(`git config --bool core.sparseCheckout`,h);let g=h.code===0&&h.stdout.trim()===`true`,y=/* @__PURE__ */ new Set,E=[],D=new Set(m.map(e=>C(e.path)));for(let e of r)y.add(C(e.path)),(D.has(C(e.path))||!(await v(T(t.checkoutPath,e.path)))?.isDirectory())&&(!e.skipWorktree||await w(T(t.checkoutPath,e.path))||!g?add(e.path):E.push(e.path));if(E.length>0){let e=await a(t.checkoutPath,[`sparse-checkout`,`check-rules`,`-z`],{input:Buffer.concat(E.flatMap(e=>[e,Buffer.from([0])]))});for(let t of b(e))add(t)}for(let e of m)y.has(C(e.path))||add(e.path);let O=new Set(d.map(e=>C(e.subarray(3))));for(let e of unstattedIndexPaths(r))u.has(C(e))&&O.add(C(e));return{head:n,headPaths:m,paths:u,changed:O}}const z=[`-c`,`submodule.recurse=false`,`-c`,`core.splitIndex=false`,`-c`,`core.sparseCheckout=false`,`-c`,`index.sparse=false`,`-c`,`core.ignoreStat=false`,`-c`,`core.trustctime=true`,`-c`,`core.checkStat=default`,...process.platform===`win32`?[]:[`-c`,`core.filemode=true`]];async function prepareSnapshotIndex(e,t,n,i){let a=[...t.headPaths.map(e=>e.path),...t.paths.values()].reduce((e,t)=>e+512+2*t.length,0),o=new Set(t.headPaths.map(e=>C(e.path))),c=new Map([...t.paths].filter(([e])=>t.changed.has(e)||!o.has(e)));for(let t of e.provisionedPaths)c.set(C(Buffer.from(t)),Buffer.from(t));let u=new Set(e.provisionedPaths.map(e=>C(Buffer.from(e)))),d=0,f=0,p=[...c],m=/* @__PURE__ */ new Set;for(let t=0;t<p.length;t+=64){let n=p.slice(t,t+64),r=await Promise.allSettled(n.map(([,t])=>v(T(e.checkoutPath,t))));for(let[e,t]of r.entries()){let r=n[e][0];if(t.status===`rejected`)throw t.reason;t.value?u.has(r)?f+=t.value.size:d+=t.value.size:o.has(r)&&m.add(r)}}let h=await r(e.repoRoot,[`rev-parse`,`--git-common-dir`]);await l({type:`worktree.snapshot-capacity`,input:{demands:[{path:P.resolve(e.repoRoot,h),bytes:2*d+a},{path:i,bytes:2*a}],stateBytes:2*f,purpose:`worktree safety snapshot`}});let g=p.filter(([e])=>!u.has(e)).map(([,e])=>e),rank=e=>m.has(C(e))?0:o.has(C(e))?1:2;return g.sort((e,t)=>rank(e)-rank(t)||(rank(e)===0?Buffer.compare(t,e):0)),g.length>0&&await s(e.checkoutPath,[...z,`read-tree`,`--reset`,t.head],{env:n}),{paths:g,changed:g.length>0}}function assertNoProvisionedTreePaths(e,t){let n=new Set(t.map(e=>C(Buffer.from(e))));for(let t of e){if(t.mode===`160000`)throw Error(`nested git repositories cannot be snapshotted losslessly`);for(let e=t.path.length;e>=0;e=t.path.lastIndexOf(47,e-1)){let r=t.path.subarray(0,e);if(n.has(C(r)))throw Error(`provisioned path entered Git snapshot: ${r.toString(`utf8`)}`);if(e===0)break}}}async function snapshotWorktree(e){await assertCurrent();let t=await l({type:`git.temporary-directory`,input:{}}),n=process.platform===`win32`?[]:[`-c`,`core.filemode=true`],r={GIT_INDEX_FILE:P.join(t,`index`),GIT_AUTHOR_NAME:`OpenClaw`,GIT_AUTHOR_EMAIL:`openclaw@localhost`,GIT_COMMITTER_NAME:`OpenClaw`,GIT_COMMITTER_EMAIL:`openclaw@localhost`},i=await collectSnapshotInventory(e);await assertCurrent();let o=i.headPaths===void 0,c=e.exactState?`refs/openclaw/snapshots/exact-v1/${e.worktreeId}`:`refs/openclaw/snapshots/${o?`clean-v1/`:``}${e.worktreeId}`,u=e.exactState||o&&e.provisionedPaths.length===0?void 0:await prepareSnapshotIndex(e,{...i,headPaths:i.headPaths??[]},r,t),d=e.exactState?await captureExactState({checkoutPath:e.checkoutPath,...e.exactState,paths:i.paths.values(),provisionedPaths:e.provisionedPaths,write:!0,temporaryDirectory:t}):void 0,f=await snapshotProvisionedFiles(e.checkoutPath,e.provisionedPaths,d?{algorithm:d.metadata.head.length===64?`sha256`:`sha1`,files:d.metadata.files.filter(e=>e.provisioned).map(e=>({path:Buffer.from(e.path,`hex`).toString(`utf8`),mode:e.kind===`missing`?null:e.mode,size:e.size,blob:e.blob}))}:void 0);await assertCurrent(),u?.changed&&(await s(e.checkoutPath,[...z,`update-index`,`--add`,`--remove`,`-z`,`--stdin`],{env:r,input:Buffer.concat(u.paths.flatMap(e=>[e,Buffer.from([0])]))}),await assertCurrent()),d&&(await s(e.checkoutPath,[...z,`read-tree`,`--empty`],{env:r}),await s(e.checkoutPath,[...z,`update-index`,`-z`,`--index-info`],{env:r,input:Buffer.concat(d.treeEntries)}));let assertHeadCurrent=async()=>{if(await s(e.checkoutPath,[`rev-parse`,`--verify`,`HEAD^{commit}`])!==i.head)throw Error(`Worktree HEAD changed while preparing its snapshot; retry cleanup.`);await assertCurrent()},p=i.head;if(!o){let t=u?.changed===!1,o=t?await s(e.checkoutPath,[`rev-parse`,`${i.head}^{tree}`]):await s(e.checkoutPath,[...z,`write-tree`],{env:r}),c=t?i.headPaths??[]:S(await a(e.checkoutPath,[`ls-tree`,`-r`,`-z`,o]));assertNoProvisionedTreePaths(c,e.provisionedPaths);let l=await a(e.checkoutPath,[`cat-file`,`--buffer`,`--batch-check=%(objectname) %(objecttype)`],{input:Buffer.from([...new Set(c.filter(e=>e.mode!==`160000`).map(e=>e.oid))].map(e=>`${e}\n`).join(``))}),f=/^([a-f0-9]{40,64}) missing$/mu.exec(l.toString(`ascii`));if(f)throw Error(`Worktree snapshot has missing blob ${f[1]}; repair the repository before retrying cleanup. Checkout preserved.`);await assertHeadCurrent();let m=d?await writeExactStateCommit(e.checkoutPath,d):void 0;d&&await verifyExactStateSnapshot({...e,expectedDigest:d.digest}),p=await s(e.checkoutPath,[...n,`commit-tree`,o,`-p`,i.head,...m?[`-p`,m]:[],`-m`,`OpenClaw worktree snapshot: ${e.reason}`],{env:r})}return await assertHeadCurrent(),await s(e.checkoutPath,[`update-ref`,`--stdin`,`-z`],{input:Buffer.from(`start\0verify HEAD\0${i.head}\0${e.exactState?`verify refs/heads/${e.exactState.branch}\0${e.exactState.expected.branchHead}\0`:``}update ${c}\0${p}\0\0${e.exactState?``:`delete refs/openclaw/snapshots/${o?``:`clean-v1/`}${e.worktreeId}\0\0`}prepare\0commit\0`)}),{snapshotRef:c,provisionedState:f,...d?{exactStateDigest:d.digest}:{}}}async function verifyExactStateSnapshot(e){if(!e.exactState)throw Error(`Exact-state verification requires captured authority`);await assertCurrent();let t=await collectSnapshotInventory(e),n=await captureExactState({checkoutPath:e.checkoutPath,...e.exactState,paths:t.paths.values(),provisionedPaths:e.provisionedPaths,write:!1});if(await assertCurrent(),n.digest!==e.expectedDigest)throw Error(`Worktree contents or metadata changed after exact-state capture; checkout preserved`);return!0}async function inspectNestedRepository(e){let t=_(await a(e,[`ls-files`,`--stage`,`-v`,`-z`]));return t.some(e=>e.mode===`160000`)?!0:await x(e,t.map(e=>e.path))||await inspectOtherPaths(e,{deletedOrUnmergedPaths:b(await a(e,[`diff-files`,`-z`,`--name-only`,`--diff-filter=DU`])),unstattedIndexPaths:unstattedIndexPaths(t)})}export{inspectNestedRepository,snapshotWorktree,verifyExactStateSnapshot};