@mogragsigma/dsh-dual-host-plugin 0.0.0-stage → 0.33.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (271) hide show
  1. package/LICENSE +58 -0
  2. package/LICENSE.en.md +94 -0
  3. package/README.md +88 -2
  4. package/bundle/ASSET_NOTICE.md +19 -0
  5. package/bundle/LICENSE +58 -0
  6. package/bundle/LICENSE.en.md +94 -0
  7. package/bundle/README.md +75 -0
  8. package/bundle/THIRD_PARTY_NOTICES.md +94 -0
  9. package/bundle/a2a-dispatches.js +38 -0
  10. package/bundle/a2a-endpoint.js +112 -0
  11. package/bundle/a2a-tools.js +11 -0
  12. package/bundle/a2a-worker.js +63 -0
  13. package/bundle/approval-auth.js +5 -0
  14. package/bundle/approval-chat.js +150 -0
  15. package/bundle/approval-feishu.js +52 -0
  16. package/bundle/approval-guidance.js +68 -0
  17. package/bundle/approval-http.js +8 -0
  18. package/bundle/approval-ledger.js +142 -0
  19. package/bundle/approval-local-relay.js +86 -0
  20. package/bundle/approval-receipts.js +62 -0
  21. package/bundle/approval-reference.js +33 -0
  22. package/bundle/approval-semantic-model.js +26 -0
  23. package/bundle/approval-semantics.js +51 -0
  24. package/bundle/approval-ui/app.js +1 -0
  25. package/bundle/approval-ui/index.html +1 -0
  26. package/bundle/approval-ui/style.css +1 -0
  27. package/bundle/approval-workbench.js +45 -0
  28. package/bundle/artifact-media.js +34 -0
  29. package/bundle/bounded-text.js +44 -0
  30. package/bundle/compatibility.json +980 -0
  31. package/bundle/cordis.patch.yml +5 -0
  32. package/bundle/delivery-approval.js +133 -0
  33. package/bundle/delivery-artifacts.js +52 -0
  34. package/bundle/delivery-commit.js +125 -0
  35. package/bundle/delivery-contract.js +42 -0
  36. package/bundle/delivery-git-read.js +217 -0
  37. package/bundle/delivery-index.js +23 -0
  38. package/bundle/delivery-journal.js +207 -0
  39. package/bundle/delivery-object-plan.js +138 -0
  40. package/bundle/delivery-preview.js +153 -0
  41. package/bundle/delivery-process-receipts.js +90 -0
  42. package/bundle/delivery-process.js +46 -0
  43. package/bundle/delivery-process.py +228 -0
  44. package/bundle/delivery-push-approval.js +89 -0
  45. package/bundle/delivery-push-plan.js +98 -0
  46. package/bundle/delivery-push-recovery.js +32 -0
  47. package/bundle/delivery-push.js +83 -0
  48. package/bundle/delivery-recovery.js +143 -0
  49. package/bundle/delivery-runtime.js +182 -0
  50. package/bundle/delivery-ssh.js +64 -0
  51. package/bundle/delivery-state.js +106 -0
  52. package/bundle/development-attention.js +35 -0
  53. package/bundle/development-bridge.js +136 -0
  54. package/bundle/development-command-review.js +110 -0
  55. package/bundle/development-container.js +110 -0
  56. package/bundle/development-contract.js +17 -0
  57. package/bundle/development-files.js +101 -0
  58. package/bundle/development-gate.js +236 -0
  59. package/bundle/development-model-budget.js +48 -0
  60. package/bundle/development-peer.js +155 -0
  61. package/bundle/development-plan.js +43 -0
  62. package/bundle/development-reconciliation.js +62 -0
  63. package/bundle/development-review.js +81 -0
  64. package/bundle/development-rules/AGENTS.md +51 -0
  65. package/bundle/development-runtime.js +68 -0
  66. package/bundle/development-source.js +48 -0
  67. package/bundle/development-test-runner.js +13 -0
  68. package/bundle/development-tools.js +45 -0
  69. package/bundle/development-worker-review.js +110 -0
  70. package/bundle/development-worker.js +68 -0
  71. package/bundle/development-workspace.js +54 -0
  72. package/bundle/diagnostics.js +78 -0
  73. package/bundle/distribution-lock.json +773 -0
  74. package/bundle/drained-process.js +26 -0
  75. package/bundle/durable-inbox.js +294 -0
  76. package/bundle/feishu-policy.js +24 -0
  77. package/bundle/gateway-maintenance.js +55 -0
  78. package/bundle/global-rules/AGENTS.md +83 -0
  79. package/bundle/im-delivery.js +60 -0
  80. package/bundle/index.js +445 -0
  81. package/bundle/intervention-actions.js +135 -0
  82. package/bundle/intervention-job-control.js +28 -0
  83. package/bundle/intervention-state.js +43 -0
  84. package/bundle/job-version.js +15 -0
  85. package/bundle/legacy-feishu-adapter.js +89 -0
  86. package/bundle/link-contract.js +80 -0
  87. package/bundle/maintenance-process-identity.js +93 -0
  88. package/bundle/model-selection.js +71 -0
  89. package/bundle/native-context.js +14 -0
  90. package/bundle/native-entry-admission.js +2 -0
  91. package/bundle/native-entry.js +58 -0
  92. package/bundle/native-file-reference.js +32 -0
  93. package/bundle/native-owner-origin.js +12 -0
  94. package/bundle/native-rules/AGENTS.md +199 -0
  95. package/bundle/native-tools.js +108 -0
  96. package/bundle/notification-artifacts.js +70 -0
  97. package/bundle/notification-contract.js +29 -0
  98. package/bundle/notification-defaults.js +81 -0
  99. package/bundle/notification-discovery.js +65 -0
  100. package/bundle/notification-endpoint.js +54 -0
  101. package/bundle/notification-feishu.js +51 -0
  102. package/bundle/notification-media-endpoint.js +94 -0
  103. package/bundle/notification-review.js +27 -0
  104. package/bundle/notification-targets.js +54 -0
  105. package/bundle/onboarding-activity.js +66 -0
  106. package/bundle/onboarding-agent-hold.js +94 -0
  107. package/bundle/onboarding-boundary.js +20 -0
  108. package/bundle/onboarding-cloud-contract.js +29 -0
  109. package/bundle/onboarding-cloud-file-review.js +58 -0
  110. package/bundle/onboarding-cloud-files.js +100 -0
  111. package/bundle/onboarding-cloud-im.js +34 -0
  112. package/bundle/onboarding-cloud-model-probe.js +53 -0
  113. package/bundle/onboarding-cloud-models.js +68 -0
  114. package/bundle/onboarding-cloud-operation.js +276 -0
  115. package/bundle/onboarding-cloud-package.js +38 -0
  116. package/bundle/onboarding-cloud-repositories.js +89 -0
  117. package/bundle/onboarding-cloud-retirement.js +59 -0
  118. package/bundle/onboarding-cloud-task-runtime.js +90 -0
  119. package/bundle/onboarding-cloud-web.js +85 -0
  120. package/bundle/onboarding-cloud.js +110 -0
  121. package/bundle/onboarding-coordinated-hold.js +94 -0
  122. package/bundle/onboarding-exclusive-rename.js +16 -0
  123. package/bundle/onboarding-existing-host.js +63 -0
  124. package/bundle/onboarding-existing-setup.js +123 -0
  125. package/bundle/onboarding-file-contract.js +31 -0
  126. package/bundle/onboarding-file-review-contract.js +38 -0
  127. package/bundle/onboarding-file-transfer.js +133 -0
  128. package/bundle/onboarding-handoff-remote.js +98 -0
  129. package/bundle/onboarding-handoff.js +112 -0
  130. package/bundle/onboarding-host-stop-observation.js +44 -0
  131. package/bundle/onboarding-host.js +254 -0
  132. package/bundle/onboarding-identity.js +9 -0
  133. package/bundle/onboarding-im-maintenance-native.js +30 -0
  134. package/bundle/onboarding-im-maintenance.js +70 -0
  135. package/bundle/onboarding-im.js +31 -0
  136. package/bundle/onboarding-inspection-guard.js +15 -0
  137. package/bundle/onboarding-install-fs.js +58 -0
  138. package/bundle/onboarding-installer.js +157 -0
  139. package/bundle/onboarding-local-pair-native.js +21 -0
  140. package/bundle/onboarding-local-pair.js +99 -0
  141. package/bundle/onboarding-maintenance-fs.js +69 -0
  142. package/bundle/onboarding-maintenance-plan.js +213 -0
  143. package/bundle/onboarding-maintenance-record.js +169 -0
  144. package/bundle/onboarding-maintenance.js +163 -0
  145. package/bundle/onboarding-model-probe.js +119 -0
  146. package/bundle/onboarding-models.js +107 -0
  147. package/bundle/onboarding-native-host.js +101 -0
  148. package/bundle/onboarding-native-probe.js +56 -0
  149. package/bundle/onboarding-native-runner.js +29 -0
  150. package/bundle/onboarding-node-bootstrap.py +678 -0
  151. package/bundle/onboarding-node.js +77 -0
  152. package/bundle/onboarding-notification-defaults.js +93 -0
  153. package/bundle/onboarding-package-source.js +33 -0
  154. package/bundle/onboarding-paths.js +58 -0
  155. package/bundle/onboarding-peer-binding.js +61 -0
  156. package/bundle/onboarding-peer-contract.js +12 -0
  157. package/bundle/onboarding-plugin-repair.js +116 -0
  158. package/bundle/onboarding-plugin-version.js +143 -0
  159. package/bundle/onboarding-remote-control.js +140 -0
  160. package/bundle/onboarding-remote-probe.js +40 -0
  161. package/bundle/onboarding-repositories.js +88 -0
  162. package/bundle/onboarding-repository.js +49 -0
  163. package/bundle/onboarding-runtime-activation.js +83 -0
  164. package/bundle/onboarding-runtime-artifacts-client.js +87 -0
  165. package/bundle/onboarding-runtime-artifacts.js +126 -0
  166. package/bundle/onboarding-runtime-extension.js +400 -0
  167. package/bundle/onboarding-runtime-inventory.js +88 -0
  168. package/bundle/onboarding-runtime-program.js +42 -0
  169. package/bundle/onboarding-runtime-reclaim-client.js +94 -0
  170. package/bundle/onboarding-runtime-reclaim-worker.js +63 -0
  171. package/bundle/onboarding-runtime-reclaim.js +132 -0
  172. package/bundle/onboarding-runtime-repair-client.js +50 -0
  173. package/bundle/onboarding-runtime-repair.js +88 -0
  174. package/bundle/onboarding-runtime-stop.js +90 -0
  175. package/bundle/onboarding-runtime-uninstall-client.js +88 -0
  176. package/bundle/onboarding-runtime-uninstall.js +167 -0
  177. package/bundle/onboarding-runtime-version-client.js +138 -0
  178. package/bundle/onboarding-runtime-version.js +145 -0
  179. package/bundle/onboarding-schema.js +42 -0
  180. package/bundle/onboarding-self-disable.js +3 -0
  181. package/bundle/onboarding-self-lifecycle.js +95 -0
  182. package/bundle/onboarding-self-maintenance.js +52 -0
  183. package/bundle/onboarding-self-remove.js +3 -0
  184. package/bundle/onboarding-self-stop.js +85 -0
  185. package/bundle/onboarding-ssh-forward.js +48 -0
  186. package/bundle/onboarding-ssh.js +105 -0
  187. package/bundle/onboarding-state.js +95 -0
  188. package/bundle/onboarding-task-runtime-contract.js +38 -0
  189. package/bundle/onboarding-task-runtime-native.js +80 -0
  190. package/bundle/onboarding-task-runtime.js +66 -0
  191. package/bundle/onboarding-token-plan.js +52 -0
  192. package/bundle/onboarding-version-activation-client.js +48 -0
  193. package/bundle/onboarding-version-candidate.js +96 -0
  194. package/bundle/onboarding-version-repair.js +128 -0
  195. package/bundle/package-lock.json +773 -0
  196. package/bundle/package.json +99 -0
  197. package/bundle/peer-file-fs.js +62 -0
  198. package/bundle/peer-file-migration.js +59 -0
  199. package/bundle/peer-file-review.js +107 -0
  200. package/bundle/peer-files.js +157 -0
  201. package/bundle/peer-mailbox.js +75 -0
  202. package/bundle/protocol.js +17 -0
  203. package/bundle/recovery.js +40 -0
  204. package/bundle/repository-catalog.js +85 -0
  205. package/bundle/repository-gitee.js +76 -0
  206. package/bundle/repository-managed.js +46 -0
  207. package/bundle/repository-writer.js +43 -0
  208. package/bundle/rules/AGENTS.md +22 -0
  209. package/bundle/runtime-im-lock.json +11577 -0
  210. package/bundle/runtime-im-package.json +18 -0
  211. package/bundle/runtime-lock.json +10152 -0
  212. package/bundle/runtime-package.json +17 -0
  213. package/bundle/scheduler-migration.js +45 -0
  214. package/bundle/search-contract.js +19 -0
  215. package/bundle/skills/dsh-dual-end/SKILL.md +12 -0
  216. package/bundle/skills/task-a2a/SKILL.md +55 -0
  217. package/bundle/skills/task-a2a-worker/SKILL.md +23 -0
  218. package/bundle/skills/task-approval/SKILL.md +128 -0
  219. package/bundle/skills/task-artifacts/SKILL.md +46 -0
  220. package/bundle/skills/task-development/SKILL.md +144 -0
  221. package/bundle/skills/task-diagnostics/SKILL.md +41 -0
  222. package/bundle/skills/task-direct-link/SKILL.md +143 -0
  223. package/bundle/skills/task-file-transfer/SKILL.md +107 -0
  224. package/bundle/skills/task-handoff/SKILL.md +23 -0
  225. package/bundle/skills/task-intake/SKILL.md +13 -0
  226. package/bundle/skills/task-notify/SKILL.md +102 -0
  227. package/bundle/skills/task-onboarding/SKILL.md +708 -0
  228. package/bundle/skills/task-recovery/SKILL.md +54 -0
  229. package/bundle/skills/task-repository/SKILL.md +145 -0
  230. package/bundle/skills/task-research/SKILL.md +43 -0
  231. package/bundle/skills/task-schedule/SKILL.md +79 -0
  232. package/bundle/skills/task-sidebar/SKILL.md +122 -0
  233. package/bundle/skills/task-workbench/SKILL.md +30 -0
  234. package/bundle/skills/task-worker/SKILL.md +88 -0
  235. package/bundle/source-search.js +89 -0
  236. package/bundle/source-web.js +17 -0
  237. package/bundle/ssh-connector.js +24 -0
  238. package/bundle/store.js +102 -0
  239. package/bundle/task-a2a.js +298 -0
  240. package/bundle/task-artifacts.js +179 -0
  241. package/bundle/task-board-a2a.js +55 -0
  242. package/bundle/task-board-development.js +83 -0
  243. package/bundle/task-board-planning.js +84 -0
  244. package/bundle/task-board.js +132 -0
  245. package/bundle/task-branch.js +2 -0
  246. package/bundle/task-catalog.js +77 -0
  247. package/bundle/task-context.js +40 -0
  248. package/bundle/task-envelope.js +96 -0
  249. package/bundle/task-interventions.js +54 -0
  250. package/bundle/task-jobs.js +156 -0
  251. package/bundle/task-notifications.js +132 -0
  252. package/bundle/task-results.js +16 -0
  253. package/bundle/task-scheduler.js +77 -0
  254. package/bundle/task-sources.js +101 -0
  255. package/bundle/task-trigger-time.js +46 -0
  256. package/bundle/task-triggers.js +157 -0
  257. package/bundle/task-worker.js +73 -0
  258. package/bundle/task-workflows.js +117 -0
  259. package/bundle/tools.js +13 -0
  260. package/bundle/workbench-assets/asset-provenance.json +26 -0
  261. package/bundle/workbench-assets/whale-ui-states.png +0 -0
  262. package/bundle/workbench-client.js +811 -0
  263. package/bundle/workbench-decisions.js +48 -0
  264. package/bundle/workbench-host.js +122 -0
  265. package/bundle/workbench-im-identity.js +51 -0
  266. package/bundle/workbench-proxy.js +127 -0
  267. package/bundle/worker-rules/AGENTS.md +84 -0
  268. package/bundle/worker-tools.js +13 -0
  269. package/compatibility.json +980 -0
  270. package/cordis.patch.yml +3 -0
  271. package/package.json +57 -4
@@ -0,0 +1,77 @@
1
+ // Pre-Node bootstrap: fixed official release, explicit confirmation, durable local receipt.
2
+ // All remote execution is this archived controller over the existing pinned SSH binding.
3
+ import fs from 'node:fs/promises';
4
+ import path from 'node:path';
5
+ import {randomUUID,randomBytes} from 'node:crypto';
6
+ import {credentialKey} from '@deepseek-ai/dsh-credentials';
7
+ import {digest,fail,shellQuote} from './onboarding-ssh.js';
8
+ import {ancestors,snapshot,bytes} from './onboarding-install-fs.js';
9
+ export const NODE_RELEASE=Object.freeze({version:'22.23.4',hashes:Object.freeze({x64:'b8492284c76a54baf58d61668dd0e41ee0fc98adabf9503d30f05d08f55b4406',arm64:'f7a1e486dbc8b286847815b477d4fb5e9fb963ed4489c3e1588853d685f589f9'})});
10
+ const OWNER='dsh-dual-host-node-bootstrap',PLAN=credentialKey('dsh-task-gateway','onboarding-node-plan-v1'),OP=credentialKey('dsh-task-gateway','onboarding-node-operation-v1');
11
+ const uuid=x=>typeof x==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(x),hex=x=>typeof x==='string'&&/^[a-f0-9]{64}$/.test(x);
12
+ const exact=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join()===keys.sort().join();
13
+ const absolute=x=>typeof x==='string'&&x.length<1024&&path.posix.isAbsolute(x)&&path.posix.normalize(x)===x&&!/[\x00-\x1f\x7f]/.test(x);
14
+ const fields=['owner','schema','id','revision','binding','bindingFingerprint','plan','proof','sourceHash','phase','remote','error','createdAt','updatedAt'];
15
+ function record(r){if(!r)return null;const p=r.payload;if(r.kind!=='grant'||!exact(p,fields)||p.owner!==OWNER||p.schema!==1||!uuid(p.id)||!Number.isSafeInteger(p.revision)||p.revision<1||!hex(p.proof)||!hex(p.sourceHash)||!p.binding||digest(p.binding)!==p.bindingFingerprint||!p.plan||p.plan.bindingFingerprint!==p.bindingFingerprint||p.plan.sourceHash!==p.sourceHash||!['start_requested','observed','outcome_unknown','rollback_requested','rolled_back'].includes(p.phase))fail('NODE_RECORD_REVIEW');const {fingerprint,...body}=p.plan;if(digest(body)!==fingerprint)fail('NODE_RECORD_REVIEW');return p;}
16
+ const publicRecord=p=>p?{state:p.phase,operationId:p.id,revision:p.revision,receipt:p.remote,error:p.error,observedAt:p.updatedAt,cached:true,automaticRetry:false,systemNodeModified:false}:{state:'not_started',cached:true,automaticRetry:false,systemNodeModified:false};
17
+ export function nodeCommand(python,source){if(!absolute(python)||typeof source!=='string'||Buffer.byteLength(source)>65536)fail('NODE_PROGRAM_REVIEW');const code="import base64; SOURCE=base64.b64decode('"+Buffer.from(source).toString('base64')+"'); exec(compile(SOURCE, '<dsh-node-bootstrap>', 'exec'))";return shellQuote(python)+' -I -B -c '+shellQuote(code);}
18
+ function response(raw){let r;try{r=JSON.parse(raw);}catch{fail('NODE_RESPONSE_REVIEW');}if(!r?.ok){if(/^ONBOARDING_NODE_[A-Z_]+$/.test(r?.error))throw Error(r.error);fail('NODE_RESPONSE_REVIEW');}return r.value;}
19
+ export function validateNodePlan(v,b,parent){
20
+ const bad=()=>fail('NODE_RESPONSE_REVIEW'),r=v?.release;
21
+ if(!v||v.schema!==1||v.installationId!==b.installationId||v.platform!=='linux'||!['x64','arm64'].includes(v.arch)||!absolute(v.home)||v.home==='/'||!absolute(v.root)||v.parent!==(parent??path.posix.join(v.home,'.local/share/dsh-dual-host/instances'))||v.root!==path.posix.join(v.parent,'node-'+b.installationId)||v.sourceRoot!==path.posix.join(v.parent,'host-'+b.installationId)||!absolute(v.python?.path)||!/^3\.[0-9]+\.[0-9]+$/.test(v.python.version)||!hex(v.fingerprint)||typeof v.rootExists!=='boolean'||typeof v.writable!=='boolean'||!Number.isSafeInteger(v.freeBytes)||v.freeBytes<0||v.remoteWrites!==0||v.systemNodeModified!==false||v.npmGlobalModified!==false||v.serviceStarted!==false||v.modelEnabled!==false)bad();
22
+ if(r?.version!==NODE_RELEASE.version||r.arch!==v.arch||r.directory!==`node-v${NODE_RELEASE.version}-linux-${v.arch}`||r.sha256!==NODE_RELEASE.hashes[v.arch]||r.url!==`https://nodejs.org/dist/v${NODE_RELEASE.version}/${r.directory}.tar.gz`||r.maxArchiveBytes!==134217728||r.maxExpandedBytes!==536870912)bad();
23
+ return v;
24
+ }
25
+ export function createNodeBootstrap({credentials,readBinding,ssh,localState,enabled,canRemove,parent=null,now=Date.now,readSource=()=>fs.readFile(new URL('./onboarding-node-bootstrap.py',import.meta.url),'utf8')}){
26
+ let busy=false;
27
+ const read=async()=>record(await credentials().readRecord(OP));
28
+ const requireEnabled=()=>{if(!enabled())fail('NODE_DISABLED');};
29
+ async function exclusive(fn){requireEnabled();if(busy)fail('NODE_BUSY');busy=true;try{return await fn();}finally{busy=false;}}
30
+ async function binding(expectedRevision){const b=await readBinding();if(!b||b.revision!==expectedRevision)fail('SSH_BINDING_CONFLICT');return b;}
31
+ async function update(p,change){let next;await credentials().modifyRecord(OP,old=>{const current=record(old);if(!current||current.id!==p.id||current.revision!==p.revision)fail('NODE_OPERATION_CONFLICT');next={...current,...change,revision:current.revision+1,updatedAt:now()};return {kind:'grant',payload:next};});return next;}
32
+ async function readPlan(){const r=await credentials().readRecord(PLAN);if(!r)return null;const p=r.payload;if(r.kind!=='grant'||p?.owner!==OWNER||p.schema!==1||!uuid(p.id)||!hex(p.sourceHash)||!hex(p.fingerprint)||typeof p.canStart!=='boolean')fail('NODE_PLAN_REVIEW');const {fingerprint,...body}=p;if(digest(body)!==fingerprint)fail('NODE_PLAN_REVIEW');return p;}
33
+ async function preview(args){
34
+ if(!exact(args,['expectedRevision'])||!Number.isSafeInteger(args.expectedRevision))fail('NODE_ARGUMENTS');
35
+ return exclusive(async()=>{
36
+ const p=await read();if(p&&p.phase!=='rolled_back')fail('NODE_RECOVERY_REQUIRED');
37
+ const b=await binding(args.expectedRevision),source=await readSource();
38
+ const python=(await ssh.execute(b,"/bin/sh -c 'command -v python3 || true'")).trim();if(!absolute(python))fail('NODE_PYTHON_MISSING');
39
+ const remote=validateNodePlan(response(await ssh.execute(b,nodeCommand(python,source),JSON.stringify({action:'preview',installationId:b.installationId,parent}))),b,parent);
40
+ if(digest(await readBinding())!==digest(b))fail('SSH_BINDING_CONFLICT');
41
+ const plan={owner:OWNER,schema:1,id:randomUUID(),bindingFingerprint:digest(b),bindingRevision:b.revision,sourceHash:digest(source),remote,canStart:!remote.rootExists&&remote.writable&&remote.freeBytes>=2147483648,createdAt:now(),expiresAt:now()+300000};plan.fingerprint=digest(plan);
42
+ await readPlan();await credentials().modifyRecord(PLAN,()=>({kind:'grant',payload:plan}));return plan;
43
+ });
44
+ }
45
+ async function sourceFor(p){const file=path.join(localState,'node-bootstrap',p.id,'controller.py');await ancestors(path.dirname(file));const s=await snapshot(file,65536);if(s.missing||s.sha256!==p.sourceHash)fail('NODE_PROGRAM_REVIEW');return bytes(s).toString('utf8');}
46
+ async function invoke(p,action){
47
+ const b=await readBinding();if(digest(b)!==p.bindingFingerprint)fail('SSH_BINDING_CONFLICT');
48
+ const source=await sourceFor(p),q={action,installationId:b.installationId,parent,operationId:p.id,proof:p.proof};if(action==='start')q.fingerprint=p.plan.remote.fingerprint;
49
+ const v=response(await ssh.execute(b,nodeCommand(p.plan.remote.python.path,source),JSON.stringify(q),{timeoutMs:action==='rollback'?120000:30000}));
50
+ if(!v||v.operationId!==p.id||!['absent','launching','downloading','extracting','checking','ready','failed','stopped','needs_review','rolling_back','rolled_back'].includes(v.state)||v.systemNodeModified!==false||v.automaticRetry!==false||v.root&&v.root!==p.plan.remote.root)fail('NODE_RESPONSE_REVIEW');
51
+ if(v.state==='ready'&&(v.node!==`${p.plan.remote.root}/${p.plan.remote.release.directory}/bin/node`||v.npm!==`${p.plan.remote.root}/${p.plan.remote.release.directory}/bin/npm`||v.version!==p.plan.remote.release.version||v.arch!==p.plan.remote.arch))fail('NODE_RESPONSE_REVIEW');return v;
52
+ }
53
+ async function outcome(p,action){try{const remote=await invoke(p,action);const phase=remote.state==='rolled_back'?'rolled_back':remote.state==='absent'?'outcome_unknown':'observed';return update(p,{phase,remote,error:remote.state==='absent'?'NODE_ABSENCE_REQUIRES_REVIEW':null});}catch(e){return update(p,{phase:p.phase==='rollback_requested'?'rollback_requested':'outcome_unknown',error:/^ONBOARDING_[A-Z_]+$/.test(e.message)?e.message:'ONBOARDING_NODE_OUTCOME_UNKNOWN'});}}
54
+ async function start(args){
55
+ if(!exact(args,['id','fingerprint','confirm'])||!uuid(args.id)||!hex(args.fingerprint)||args.confirm!==true)fail('NODE_CONFIRMATION_REQUIRED');
56
+ return exclusive(async()=>{
57
+ const prior=await read();if(prior?.plan.id===args.id&&prior.plan.fingerprint===args.fingerprint)return publicRecord(prior);if(prior&&prior.phase!=='rolled_back')fail('NODE_RECOVERY_REQUIRED');
58
+ const plan=await readPlan();if(!plan||plan.id!==args.id||plan.fingerprint!==args.fingerprint||plan.expiresAt<now()||!plan.canStart)fail('NODE_PLAN_EXPIRED');
59
+ const b=await binding(plan.bindingRevision),source=await readSource();if(digest(b)!==plan.bindingFingerprint||digest(source)!==plan.sourceHash)fail('NODE_PLAN_DRIFT');
60
+ const id=randomUUID(),dir=path.join(localState,'node-bootstrap',id);await ancestors(dir);await fs.mkdir(dir,{recursive:true,mode:0o700});await ancestors(dir);const file=await fs.open(path.join(dir,'controller.py'),'wx',0o600);try{await file.writeFile(source);await file.sync();}finally{await file.close();}
61
+ const p={owner:OWNER,schema:1,id,revision:1,binding:b,bindingFingerprint:digest(b),plan,proof:randomBytes(32).toString('hex'),sourceHash:digest(source),phase:'start_requested',remote:null,error:null,createdAt:now(),updatedAt:now()};
62
+ if(prior)await credentials().modifyRecord(credentialKey('dsh-task-gateway','onboarding-node-history-v1-'+prior.id),old=>{if(old&&(old.kind!=='grant'||digest(old.payload)!==digest(prior)))fail('NODE_HISTORY_REVIEW');return old??{kind:'grant',payload:prior};});
63
+ await credentials().modifyRecord(OP,old=>{const r=record(old);if((r?.id??null)!==(prior?.id??null)||(r?.revision??null)!==(prior?.revision??null))fail('NODE_OPERATION_CONFLICT');return {kind:'grant',payload:p};});return publicRecord(await outcome(p,'start'));
64
+ });
65
+ }
66
+ async function status(args){
67
+ requireEnabled();if(!exact(args,['refresh'])||typeof args.refresh!=='boolean')fail('NODE_ARGUMENTS');
68
+ const p=await read();if(!p||!args.refresh||p.phase==='rolled_back')return publicRecord(p);
69
+ return exclusive(async()=>publicRecord(await outcome(await read(),'status')));
70
+ }
71
+ async function action(args){
72
+ if(!exact(args,['action','operationId','expectedRevision','confirm'])||!['stop','rollback'].includes(args.action)||!uuid(args.operationId)||!Number.isSafeInteger(args.expectedRevision)||args.confirm!==true)fail('NODE_CONFIRMATION_REQUIRED');
73
+ return exclusive(async()=>{let p=await read();if(!p||p.id!==args.operationId||p.revision!==args.expectedRevision)fail('NODE_OPERATION_CONFLICT');if(p.phase==='rolled_back')return publicRecord(p);if(args.action==='rollback'){if(!await canRemove())fail('NODE_HOST_REMOVAL_REQUIRED');p=await update(p,{phase:'rollback_requested',error:null});}return publicRecord(await outcome(p,args.action));});
74
+ }
75
+ async function selected(b){const p=await read();if(!p||p.phase==='rolled_back')return null;if(p.bindingFingerprint!==digest(b)||p.phase!=='observed'||p.remote?.state!=='ready')fail('NODE_RECOVERY_REQUIRED');const v=await invoke(p,'status');if(v.state!=='ready')fail('NODE_RECOVERY_REQUIRED');return {node:v.node,npm:v.npm};}
76
+ return {preview,start,status,action,selected,hasUnfinished:async()=>{const p=await read();return !!p&&p.phase!=='rolled_back';}};
77
+ }
@@ -0,0 +1,93 @@
1
+ // Page 3 owns one explicit default entry/return-channel selection. Native IM
2
+ // continues to own receiving messages. This module never starts an IM consumer.
3
+ import {handoffTarget} from './onboarding-handoff.js';
4
+ import {credentialKey} from '@deepseek-ai/dsh-credentials';
5
+ import {randomUUID} from 'node:crypto';
6
+ import {NotificationDiscovery} from './notification-discovery.js';
7
+ import {defaultPolicy} from './notification-defaults.js';
8
+ import {targets,digest} from './notification-contract.js';
9
+ const KEY=credentialKey('dsh-task-gateway','onboarding-notification-default-v1');
10
+ const exact=(x,keys)=>x&&typeof x==='object'&&!Array.isArray(x)&&Object.keys(x).sort().join()===keys.slice().sort().join();
11
+ const fail=c=>{throw Error('ONBOARDING_NOTIFICATION_'+c);};
12
+ const safe=e=>/^(NOTIFICATION|CAPABILITY|PROTOCOL|COORDINATOR|ONBOARDING)_[A-Z_]+$/.test(e?.message??'')?e.message:'ONBOARDING_NOTIFICATION_UNAVAILABLE';
13
+ function record(r){
14
+ if(!r)return null;if(r.kind!=='grant'||!exact(r.payload,['owner','policy'])||r.payload.owner!=='dsh-dual-host-onboarding')fail('RECORD_REVIEW');
15
+ try{return defaultPolicy(r.payload.policy);}catch{fail('RECORD_REVIEW');}
16
+ }
17
+ export function createOnboardingNotificationDefaults({state,credentials,im,gateway,role,remote,remoteEnabled,now=Date.now}){
18
+ let pending=null,busy=false,closed=false,lastSync=null,syncing=null,remoteTarget=null,peerTarget=null;
19
+ const discovery=new NotificationDiscovery({c:{role:role==='cloud'?'cloud':'local'},now,get closed(){return closed;}},im);
20
+ const available=()=>role!=='cloud'&&state.available()&&!!credentials();
21
+ const ready=()=>{if(!available()||closed)fail('UNAVAILABLE');return credentials();};
22
+ async function read(){return record(await ready().readRecord(KEY));}
23
+ async function run(fn){if(busy)fail('BUSY');busy=true;try{return await fn();}finally{busy=false;}}
24
+ function currentHost(host){return host===(role==='cloud'?'cloud':'local');}
25
+ async function scan(a){
26
+ if(!exact(a,['host'])||!['local','cloud'].includes(a.host))fail('ARGUMENTS');
27
+ if(currentHost(a.host))return discovery.inspect();
28
+ remoteTarget=null;peerTarget=null;
29
+ const g=gateway();
30
+ // Existing paired Hosts need no managed-install archive. Use their current
31
+ // authenticated protocol, never reinterpret them as a new cloud installation.
32
+ if(role!=='cloud'&&g&&!g.closed){
33
+ if(g.c.role!=='local')fail('CANDIDATE_REVIEW');
34
+ const r=await g.call('notification_default_peer_discover',a);
35
+ if(gateway()!==g||g.closed||closed||!exact(r,['instance_id','value'])||typeof r.instance_id!=='string'||!r.instance_id||r.value?.host!=='cloud'||!Array.isArray(r.value.items))fail('CANDIDATE_REVIEW');
36
+ peerTarget={gateway:g,instance:r.instance_id};return r.value;
37
+ }
38
+ if(role==='cloud'||!remoteEnabled())fail('PEER_UNAVAILABLE');
39
+ const r=await remote('notification_defaults_discover',a);handoffTarget(r.target);if(r.value?.host!=='cloud'||!Array.isArray(r.value.items))fail('CANDIDATE_REVIEW');remoteTarget=r.target;return r.value;
40
+ }
41
+ // Internal Host-to-Host read: revalidate the exact SDK candidate on its owning
42
+ // Host. No credentials are returned; the browser receives only the plan view.
43
+ async function candidate(a){
44
+ if(!exact(a,['host','candidate_id','label'])||!['local','cloud'].includes(a.host))fail('ARGUMENTS');
45
+ let d;
46
+ if(currentHost(a.host))d=await discovery.resolve(a.candidate_id,a.label);
47
+ else if(peerTarget){
48
+ const pin=peerTarget,g=gateway();if(g!==pin.gateway||g.closed)fail('CANDIDATE_CHANGED');
49
+ const r=await g.call('notification_default_peer_candidate',{...a,instance_id:pin.instance});
50
+ if(gateway()!==g||g.closed||peerTarget!==pin||!exact(r,['instance_id','value'])||r.instance_id!==pin.instance)fail('CANDIDATE_CHANGED');d=r.value;
51
+ }else {if(role==='cloud'||!remoteEnabled())fail('PEER_UNAVAILABLE');if(!remoteTarget)fail('CANDIDATE_REVIEW');const r=await remote('notification_defaults_candidate',a,remoteTarget);handoffTarget(r.target);if(digest(r.target)!==digest(remoteTarget))fail('CANDIDATE_CHANGED');d=r.value;}
52
+ try{const t=targets([d])[0];if(t.host!==a.host||t.label!==a.label||!t.alias.startsWith('discovered-'))fail('CANDIDATE_REVIEW');}catch{fail('CANDIDATE_REVIEW');}
53
+ return d;
54
+ }
55
+ function view(p){return {contract:1,enabled:p?.enabled??false,revision:p?.revision??0,operation:p?.operation??null,target:p?.definition?{host:p.definition.host,label:p.definition.label}:null,publication:p&&lastSync?.operation===p.operation?{state:lastSync.state,error:lastSync.error??null,observedAt:lastSync.at}:{state:p?'pending_pair_or_sync':'not_configured'},scope:'new_cloud_scheduled_tasks',events:['result','attention'],historicalBackfill:false,writeAuthorized:false};}
56
+ async function status(a){if(!exact(a,[]))fail('ARGUMENTS');return view(await read());}
57
+ async function preview(a){return run(async()=>{
58
+ pending=null;
59
+ if(!exact(a,a?.enabled?['enabled','host','candidate_id','label']:['enabled'])||typeof a.enabled!=='boolean')fail('ARGUMENTS');
60
+ const old=await read(),definition=a.enabled?await candidate({host:a.host,candidate_id:a.candidate_id,label:a.label}):null;
61
+ if(closed||(await read())?.revision!==old?.revision)fail('REVISION_CONFLICT');
62
+ const policy={contract:1,owner:old?.owner??randomUUID(),revision:(old?.revision??0)+1,operation:randomUUID(),enabled:a.enabled,definition,approvedAt:now()};
63
+ defaultPolicy(policy);pending={policy,input:a,expectedRevision:old?.revision??0,expiresAt:now()+300000,fingerprint:digest(policy)};
64
+ return {id:policy.operation,fingerprint:pending.fingerprint,expiresAt:pending.expiresAt,enabled:policy.enabled,revision:policy.revision,target:definition?{host:definition.host,label:definition.label}:null,events:['result','attention'],scope:'new_cloud_scheduled_tasks',endsPreviousInheritedConsent:true,inflightCannotBeRecalled:true,writeAuthorized:false};
65
+ });}
66
+ async function apply(a){return run(async()=>{
67
+ if(!exact(a,['id','fingerprint','confirm'])||a.confirm!==true)fail('CONFIRMATION_REQUIRED');
68
+ const p=pending;if(!p||p.policy.operation!==a.id||p.fingerprint!==a.fingerprint||p.expiresAt<=now())fail('PLAN_EXPIRED');
69
+ pending=null; // Unknown writes must be reconciled by status, never replayed.
70
+ if(p.policy.enabled){const d=await candidate({host:p.input.host,candidate_id:p.input.candidate_id,label:p.input.label});if(digest(d)!==digest(p.policy.definition))fail('CANDIDATE_CHANGED');}
71
+ if(closed||p.expiresAt<=now())fail('PLAN_EXPIRED');
72
+ await ready().modifyRecord(KEY,old=>{const r=record(old);if((r?.revision??0)!==p.expectedRevision)fail('REVISION_CONFLICT');return {kind:'grant',payload:{owner:'dsh-dual-host-onboarding',policy:p.policy}};});
73
+ lastSync=null; // Save first; absence/offline peer is not a failed local write.
74
+ try{await sync({});}catch{}
75
+ return status({});
76
+ });}
77
+ async function sync(a){
78
+ if(!exact(a,[]))fail('ARGUMENTS');if(syncing)return syncing;
79
+ syncing=(async()=>{
80
+ const p=await read();if(!p)return view(null);const g=gateway();
81
+ if(!g||g.closed){lastSync={operation:p.operation,state:'pending_pair_or_sync',at:now()};fail('PAIR_UNAVAILABLE');}
82
+ try{
83
+ if(lastSync?.operation!==p.operation||lastSync.state!=='active'||lastSync.gateway!==g||now()-lastSync.at>=10000||now()<lastSync.at){
84
+ await g.notifications.defaults.sync(p);
85
+ if(closed||gateway()!==g||(await read())?.operation!==p.operation)fail('REVISION_CONFLICT');
86
+ lastSync={operation:p.operation,state:'active',at:now(),gateway:g};
87
+ }
88
+ return view(p);
89
+ }catch(e){lastSync={operation:p.operation,state:'pending_or_review',error:safe(e),at:now()};throw e;}
90
+ })();try{return await syncing;}finally{syncing=null;}
91
+ }
92
+ return {available,scan,candidate,status,preview,apply,sync,dispose(){closed=true;pending=null;}};
93
+ }
@@ -0,0 +1,33 @@
1
+ // Installed package templates are read-only inputs, not writable owned targets.
2
+ // pnpm may hardlink them to its store. Never use this reader for user files,
3
+ // transaction journals or publication; their single-link checks remain mandatory.
4
+ import fs from 'node:fs/promises';
5
+ import {constants} from 'node:fs';
6
+ import path from 'node:path';
7
+ import {hash,identity,sameIdentity,fail} from './onboarding-install-fs.js';
8
+ export async function packageSourceParents(folder,io=fs){
9
+ if(!path.isAbsolute(folder))fail('INSTALL_SOURCE_INVALID');
10
+ let at=path.parse(folder).root;const rows=[];
11
+ for(const part of folder.split(path.sep).filter(Boolean)){
12
+ at=path.join(at,part);const s=await io.lstat(at);
13
+ if(s.isSymbolicLink()||!s.isDirectory())fail('UNSAFE_PATH');
14
+ rows.push({path:at,dev:s.dev,ino:s.ino,mode:s.mode&0o777});
15
+ }
16
+ return rows;
17
+ }
18
+ export async function packageSourceSnapshot(file,max=262144,io=fs){
19
+ if(!path.isAbsolute(file)||!Number.isSafeInteger(max)||max<1||max>2097152)fail('INSTALL_SOURCE_INVALID');
20
+ const parents=await packageSourceParents(path.dirname(file),io),before=await io.lstat(file);
21
+ if(before.isSymbolicLink()||!before.isFile()||before.nlink<1||before.size>max)fail('UNSAFE_FILE');
22
+ const h=await io.open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));
23
+ const same=(a,b)=>sameIdentity(a,b)&&a.isFile()&&b.isFile()&&a.size===b.size&&a.mtimeMs===b.mtimeMs&&a.ctimeMs===b.ctimeMs&&a.nlink===b.nlink&&(a.mode&0o777)===(b.mode&0o777);
24
+ try{
25
+ const a=await h.stat();if(!same(before,a))fail('FILE_DRIFT');
26
+ // Bound allocation and reads even if another store link grows concurrently.
27
+ const buffer=Buffer.alloc(a.size+1);let used=0;
28
+ while(used<buffer.length){const {bytesRead}=await h.read(buffer,used,buffer.length-used,used);if(!bytesRead)break;used+=bytesRead;}
29
+ const z=await h.stat(),current=await io.lstat(file);
30
+ if(!same(a,z)||current.isSymbolicLink()||!same(z,current)||used!==a.size||JSON.stringify(parents)!==JSON.stringify(await packageSourceParents(path.dirname(file),io)))fail('FILE_DRIFT');
31
+ const b=buffer.subarray(0,used);return {...identity(z),size:used,sha256:hash(b),data:b.toString('base64')};
32
+ }finally{await h.close();}
33
+ }
@@ -0,0 +1,58 @@
1
+ import path from 'node:path';
2
+ import {constants} from 'node:fs';
3
+ import {lstat,open} from 'node:fs/promises';
4
+ import {createHash} from 'node:crypto';
5
+ const ownedStart='<!-- dsh-dual-host:begin -->',ownedEnd='<!-- dsh-dual-host:end -->';
6
+ export function resolveOnboardingPaths({platform,home,env={},configured={}}){
7
+ if(!['darwin','linux','win32'].includes(platform))throw Error('ONBOARDING_PLATFORM_UNSUPPORTED');
8
+ const p=platform==='win32'?path.win32:path.posix;
9
+ const resolve=v=>{
10
+ if(typeof v!=='string'||!v||/[\u0000-\u001f]/u.test(v))throw Error('ONBOARDING_PATH_UNRESOLVED');
11
+ const x=v==='~'?home:/^~[\\/]/.test(v)?p.join(home,v.slice(2)):v;
12
+ if(!p.isAbsolute(x)||platform==='win32'&&/^[/\\](?![/\\])/.test(x))throw Error('ONBOARDING_PATH_UNRESOLVED');
13
+ return p.normalize(x);
14
+ };
15
+ if(!p.isAbsolute(home))throw Error('ONBOARDING_PATH_UNRESOLVED');
16
+ // Match official dsh-home-paths: blank environment overrides mean "unset".
17
+ // Explicit plugin paths remain strict, and still describe candidates, not activation.
18
+ const root=(key,variable,fallback)=>{
19
+ const fromEnv=typeof env[variable]==='string'&&env[variable].trim().length>0?env[variable]:undefined;
20
+ return {path:resolve(configured[key]??fromEnv??p.join(home,fallback)),source:configured[key]!==undefined?'plugin_configuration':fromEnv!==undefined?'process_environment':'platform_home_default'};
21
+ };
22
+ const dsh=root('dshHome','DSH_HOME','.dsh'),agents=root('agentsHome','DSH_AGENTS_HOME','.agents');
23
+ const custom=configured.customSkillDirs??[];
24
+ if(!Array.isArray(custom)||custom.length>32||configured.includeDefaultRoots!==undefined&&typeof configured.includeDefaultRoots!=='boolean')throw Error('ONBOARDING_PATH_UNRESOLVED');
25
+ const unique=xs=>[...new Set(xs)];
26
+ return {platform,dsh,agents,globalCandidates:unique([p.join(dsh.path,'AGENTS.md'),p.join(agents.path,'AGENTS.md')]),skillCandidates:unique([...(configured.includeDefaultRoots===false?[]:[p.join(dsh.path,'skills'),p.join(agents.path,'skills')]),...custom.map(resolve)]),includeDefaultRoots:configured.includeDefaultRoots!==false,activeRootsVerified:false,installationAllowed:false,warning:'候选路径来自本 Host 进程及显式配置;尚未证明指令/Skill 提供方正在加载它们。云端路径须在云端服务账号下独立核验。'};
27
+ }
28
+ // lstat each ancestor; never follow a user-controlled symlink into another rules file.
29
+ // This is a best-effort read-only observation, NOT an OS isolation or future write guarantee.
30
+ export async function inspectRuleFile(file){
31
+ try{
32
+ const parts=file.split(path.sep).filter(Boolean);let parent=path.parse(file).root;
33
+ for(let i=0;i<parts.length;i++){
34
+ parent=path.join(parent,parts[i]);let s;try{s=await lstat(parent);}catch(e){if(e.code==='ENOENT')return {path:file,state:'missing',action:'create_after_approval',contentRead:false};throw e;}
35
+ if(s.isSymbolicLink())return {path:file,state:'symlink_review',action:'blocked',contentRead:false};
36
+ if(i<parts.length-1&&!s.isDirectory())return {path:file,state:'not_directory',action:'blocked',contentRead:false};
37
+ if(i===parts.length-1&&(!s.isFile()||s.size>262144))return {path:file,state:'unsupported_file',action:'blocked',contentRead:false};
38
+ }
39
+ const f=await open(file,constants.O_RDONLY|(constants.O_NOFOLLOW??0)|(constants.O_NONBLOCK??0));
40
+ try{
41
+ const before=await f.stat();if(!before.isFile()||before.size>262144)return {path:file,state:'unsupported_file',action:'blocked',contentRead:false};
42
+ const bytes=Buffer.alloc(before.size);const {bytesRead}=await f.read(bytes,0,bytes.length,0),after=await f.stat();
43
+ if(bytesRead!==before.size||before.ino!==after.ino||before.size!==after.size||before.mtimeMs!==after.mtimeMs)return {path:file,state:'changed_during_read',action:'blocked',contentRead:false};
44
+ const content=bytes.toString('utf8'),starts=content.split(ownedStart).length-1,ends=content.split(ownedEnd).length-1;
45
+ const encodingOK=Buffer.from(content).equals(bytes),markerOK=starts===0&&ends===0||starts===1&&ends===1&&content.indexOf(ownedStart)<content.indexOf(ownedEnd);
46
+ const legacy=content.split(/\r?\n/).filter(line=>['## 双端协作(本地鱼 / 云端鱼)','## 双端协作(全局托管规则)'].includes(line)).length;
47
+ const blocked=!encodingOK||!markerOK||!(before.mode&0o222)||starts>0||legacy>0;
48
+ return {path:file,state:!encodingOK?'encoding_review':!markerOK||legacy>1?'marker_conflict':!(before.mode&0o222)?'read_only':starts?'owned_block_requires_manifest':legacy?'legacy_section_requires_manifest':'existing_user_rules',action:blocked?'blocked':'append_after_approval',sha256:createHash('sha256').update(bytes).digest('hex'),bytes:bytes.length,contentRead:true,contentReturned:false};
49
+ }finally{await f.close();}
50
+ }catch{return {path:file,state:'unreadable',action:'blocked',contentRead:false};}
51
+ }
52
+ export async function inspectSkillRoot(root,names){
53
+ const result={path:root,state:'candidate',conflicts:[],contentRead:false};
54
+ try{let cursor=path.parse(root).root;for(const part of root.split(path.sep).filter(Boolean)){cursor=path.join(cursor,part);const s=await lstat(cursor);if(s.isSymbolicLink()||!s.isDirectory())return {...result,state:'unsafe_path'};}
55
+ for(const name of names){try{await lstat(path.join(root,name));result.conflicts.push(name);}catch(e){if(e.code!=='ENOENT')return {...result,state:'unreadable'};}}
56
+ return {...result,state:result.conflicts.length?'ownership_review':'no_name_collision'};
57
+ }catch(e){return {...result,state:e.code==='ENOENT'?'missing':'unreadable'};}
58
+ }
@@ -0,0 +1,61 @@
1
+ // One explicitly bound controller, over the already verified owned SSH target.
2
+ // The peer token never leaves the cloud Host. Frames still use Gateway's native
3
+ // negotiation/authentication path; this is transport, not an execution grant.
4
+ import {credentialKey} from '@deepseek-ai/dsh-credentials';
5
+ import {randomUUID} from 'node:crypto';
6
+ import {digest} from './onboarding-ssh.js';
7
+ import {METHODS} from './link-contract.js';
8
+ const KEY=credentialKey('dsh-task-gateway','onboarding-peer-binding-v1');
9
+ const OWNER='dsh-dual-host-peer-binding';
10
+ const exact=(v,keys)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join()===keys.slice().sort().join();
11
+ const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(v);
12
+ const hex=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
13
+ const revision=v=>Number.isSafeInteger(v)&&v>=0&&v<Number.MAX_SAFE_INTEGER-1;
14
+ const fail=c=>{throw Error('ONBOARDING_TASK_RUNTIME_PAIR_'+c);};
15
+ function record(r){
16
+ if(!r)return null;const p=r.payload;
17
+ if(r.kind!=='grant'||!exact(p,['owner','schema','id','localId','runtimeId','enabled','revision','operation','planHash','updatedAt'])||p.owner!==OWNER||p.schema!==1||![p.id,p.localId,p.runtimeId,p.operation].every(uuid)||typeof p.enabled!=='boolean'||!revision(p.revision)||!p.revision||!hex(p.planHash)||!Number.isSafeInteger(p.updatedAt))fail('RECORD_REVIEW');return p;
18
+ }
19
+ export const peerBindingKey=p=>p?digest({id:p.id,localId:p.localId,runtimeId:p.runtimeId,enabled:p.enabled}):null;
20
+ export function createOnboardingPeerBinding({credentials,available,runtime,handle,run,refresh,now=Date.now}){
21
+ let plan=null,inflight=0;
22
+ const ready=()=>{if(!available())fail('UNAVAILABLE');return credentials();};
23
+ const read=async()=>record(await ready().readRecord(KEY));
24
+ async function binding(runtimeId){const p=await read();if(p&&p.runtimeId!==runtimeId)fail('RUNTIME_CHANGED');return p;}
25
+ async function status(a={}){
26
+ if(!exact(a,[]))fail('ARGUMENTS');const p=await read(),r=await runtime(),h=handle();if(p&&p.runtimeId!==r?.id)fail('RUNTIME_CHANGED');
27
+ return {contract:1,revision:p?.revision??0,id:p?.id??null,localId:p?.localId??null,runtimeId:p?.runtimeId??r?.id??null,enabled:p?.enabled??false,mounted:!!p?.enabled&&!!r?.enabled&&h?.active()===true&&h.pairingKey===peerBindingKey(p),namespace:r?'managed-'+r.id:null,appliedOperation:p?.operation??null,appliedPlanHash:p?.planHash??null,workerEnabled:false,writeAuthorized:false,publishEnabled:false};
28
+ }
29
+ async function quiescent(){if(inflight)fail('BUSY');await handle()?.quiescent();}
30
+ async function preview(a){return run(async()=>{
31
+ plan=null;if(!exact(a,['enabled','localId'])||typeof a.enabled!=='boolean'||!uuid(a.localId))fail('ARGUMENTS');
32
+ const r=await runtime(),p=await read();if(r?.workerEnabled)fail('WORKER_DISABLE_REQUIRED');if(!r?.enabled||a.enabled&&handle()?.active()!==true)fail('RUNTIME_NOT_READY');
33
+ if(p&&(p.localId!==a.localId||p.runtimeId!==r.id))fail('OWNER_MISMATCH');
34
+ await quiescent();const body={id:randomUUID(),pairId:p?.id??randomUUID(),localId:a.localId,runtimeId:r.id,runtimeRevision:r.revision,enabled:a.enabled,revision:p?.revision??0,expiresAt:now()+300000};plan={...body,fingerprint:digest(body)};
35
+ return {...plan,contract:1,namespace:'managed-'+r.id,scope:'single_verified_controller_transport',workerEnabled:false,writeAuthorized:false,publishEnabled:false};
36
+ });}
37
+ async function apply(a){return run(async()=>{
38
+ if(!exact(a,['id','fingerprint','confirm'])||!uuid(a.id)||!hex(a.fingerprint)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');
39
+ const old=await read();if(old?.operation===a.id&&old.planHash===a.fingerprint)return status({});
40
+ const p=plan;if(!p||p.id!==a.id||p.fingerprint!==a.fingerprint||p.expiresAt<=now())fail('PLAN_EXPIRED');plan=null;
41
+ const r=await runtime();if(r?.workerEnabled)fail('WORKER_DISABLE_REQUIRED');if(!r?.enabled||r.id!==p.runtimeId||r.revision!==p.runtimeRevision)fail('RUNTIME_CHANGED');await quiescent();
42
+ await ready().modifyRecord(KEY,prior=>{const v=record(prior);if((v?.revision??0)!==p.revision)fail('CONFLICT');if(v&&(v.localId!==p.localId||v.runtimeId!==p.runtimeId))fail('OWNER_MISMATCH');return {kind:'grant',payload:{owner:OWNER,schema:1,id:p.pairId,localId:p.localId,runtimeId:p.runtimeId,enabled:p.enabled,revision:p.revision+1,operation:p.id,planHash:p.fingerprint,updatedAt:now()}};});
43
+ await refresh();return status({});
44
+ });}
45
+ async function fence(a){return run(async()=>{
46
+ if(!exact(a,['operation','expectedRevision','id','localId','runtimeId','confirm'])||![a.operation,a.id,a.localId,a.runtimeId].every(uuid)||!revision(a.expectedRevision)||a.confirm!==true)fail('CONFIRMATION_REQUIRED');await quiescent();
47
+ const r=await runtime();if(r?.workerEnabled)fail('WORKER_DISABLE_REQUIRED');if(r?.id!==a.runtimeId)fail('RUNTIME_CHANGED');
48
+ await ready().modifyRecord(KEY,old=>{const p=record(old);if((p?.revision??0)!==a.expectedRevision)fail('CONFLICT');if(p&&(p.id!==a.id||p.localId!==a.localId||p.runtimeId!==a.runtimeId))fail('OWNER_MISMATCH');return {kind:'grant',payload:{...(p??{owner:OWNER,schema:1,id:a.id,localId:a.localId,runtimeId:a.runtimeId,enabled:false}),revision:a.expectedRevision+1,operation:a.operation,planHash:digest(a),updatedAt:now()}};});return status({});
49
+ });}
50
+ async function forward(a){
51
+ if(!exact(a,['id','localId','revision','frame'])||!uuid(a.id)||!uuid(a.localId)||!revision(a.revision)||!a.revision)fail('ARGUMENTS');
52
+ const f=a.frame;if(!exact(f,['method','args',...(f?.contract===undefined?[]:['contract'])])||!(f.method==='negotiate'||Object.hasOwn(METHODS,f.method))||!f.args||typeof f.args!=='object'||Array.isArray(f.args)||Buffer.byteLength(JSON.stringify(f))>131072)fail('FRAME_INVALID');
53
+ const admitted=await run(async()=>{const p=await read(),r=await runtime(),h=handle();
54
+ if(!p?.enabled||p.id!==a.id||p.localId!==a.localId||p.revision!==a.revision||!r?.enabled||r.id!==p.runtimeId)fail('AUTH_DENIED');
55
+ if(!h?.active()||h.pairingKey!==peerBindingKey(p)||typeof h.forward!=='function')fail('RUNTIME_NOT_READY');
56
+ // No approval or role rewriting: caller's exact frame reaches Gateway as local.
57
+ inflight++;return {p,h};});
58
+ try{const value=await admitted.h.forward(f);const after=await read();if(after?.revision!==admitted.p.revision||!after.enabled)fail('AUTH_CHANGED');return value;}finally{inflight--;}
59
+ }
60
+ return {binding,status,preview,apply,fence,forward,quiescent};
61
+ }
@@ -0,0 +1,12 @@
1
+ const exact=(v,k)=>v&&typeof v==='object'&&!Array.isArray(v)&&Object.keys(v).sort().join()===k.slice().sort().join();
2
+ const uuid=v=>typeof v==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(v);
3
+ const rev=v=>Number.isSafeInteger(v)&&v>=0&&v<Number.MAX_SAFE_INTEGER-1;
4
+ const hex=v=>typeof v==='string'&&/^[a-f0-9]{64}$/.test(v);
5
+ const fail=()=>{throw Error('ONBOARDING_LOCAL_PAIR_RESPONSE_REVIEW');};
6
+ export function peerBindingPlan(p){
7
+ if(!exact(p,['id','pairId','localId','runtimeId','runtimeRevision','enabled','revision','expiresAt','fingerprint','contract','namespace','scope','workerEnabled','writeAuthorized','publishEnabled'])||![p.id,p.pairId,p.localId,p.runtimeId].every(uuid)||!rev(p.runtimeRevision)||!p.runtimeRevision||!rev(p.revision)||typeof p.enabled!=='boolean'||!Number.isSafeInteger(p.expiresAt)||!hex(p.fingerprint)||p.contract!==1||p.namespace!=='managed-'+p.runtimeId||p.scope!=='single_verified_controller_transport'||p.workerEnabled!==false||p.writeAuthorized!==false||p.publishEnabled!==false)fail();return p;
8
+ }
9
+ export function peerBindingStatus(p){
10
+ if(!exact(p,['contract','revision','id','localId','runtimeId','enabled','mounted','namespace','appliedOperation','appliedPlanHash','workerEnabled','writeAuthorized','publishEnabled'])||p.contract!==1||!rev(p.revision)||p.runtimeId!==null&&!uuid(p.runtimeId)||p.namespace!==(p.runtimeId?'managed-'+p.runtimeId:null)||typeof p.enabled!=='boolean'||typeof p.mounted!=='boolean'||p.mounted&&!p.enabled||p.workerEnabled!==false||p.writeAuthorized!==false||p.publishEnabled!==false)fail();
11
+ if(p.revision===0){if(p.id!==null||p.localId!==null||p.appliedOperation!==null||p.appliedPlanHash!==null||p.enabled||p.mounted)fail();}else if(![p.id,p.localId,p.runtimeId,p.appliedOperation].every(uuid)||!hex(p.appliedPlanHash))fail();return p;
12
+ }
@@ -0,0 +1,116 @@
1
+ // Offline own-plugin repair transaction. Internal seam only: the verified runtime
2
+ // controller supplies exclusive ownership/stop proofs; no path is accepted over RPC.
3
+ import path from 'node:path';
4
+ import {randomUUID,createHmac,timingSafeEqual} from 'node:crypto';
5
+ import {fs,hash as bytesHash,bytes,snapshot,sameIdentity,identity,syncWrite,atomicState,ancestors} from './onboarding-install-fs.js';
6
+ import {publishMaintenanceItem,rollbackMaintenanceItem,statMaybe,syncDirectory} from './onboarding-maintenance-fs.js';
7
+ const hash=v=>bytesHash(typeof v==='string'||Buffer.isBuffer(v)?v:JSON.stringify(v));
8
+ const fail=c=>{throw Error('ONBOARDING_PLUGIN_REPAIR_'+c);};
9
+ const uuid=x=>typeof x==='string'&&/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/.test(x);
10
+ const digest=x=>typeof x==='string'&&/^[a-f0-9]{64}$/.test(x);
11
+ const exact=(x,k)=>x&&typeof x==='object'&&!Array.isArray(x)&&Object.keys(x).sort().join()===k.slice().sort().join();
12
+ const rel=x=>typeof x==='string'&&x.length<=240&&/^[A-Za-z0-9_.\/-]+$/.test(x)&&!x.startsWith('/')&&x.split('/').every(p=>p&&p!=='.'&&p!=='..')&&!x.split('/').includes('node_modules');
13
+ const view=j=>({contract:1,id:j.id,state:j.state,planHash:j.planHash,files:j.items.map(i=>({path:i.relative,action:i.action})),scope:'stopped_owned_plugin_files_only',versionUpgrade:false,hostStarted:false,activationVerified:false,ownershipRebased:false,review:j.review??[],recoveryRequired:!['committed','rolled_back'].includes(j.state)});
14
+ export function createPluginRepair({root,operationId,runtimeId,proof,manifest,inventory,exclusive,verifyOwnedStopped,now=Date.now,hook,versionContext}){
15
+ if(!path.isAbsolute(root)||path.resolve(root)!==root||!uuid(operationId)||!uuid(runtimeId)||!digest(proof)||typeof exclusive!=='function'||typeof verifyOwnedStopped!=='function'||!Array.isArray(manifest)||!manifest.length||manifest.length>512||!Array.isArray(inventory))fail('CONTRACT');
16
+ const source=versionContext?.source??path.join(root,'plugin'),target=path.join(root,'runtime/plugin'),control=versionContext?.control??path.join(root,'.control/runtime'),folder=path.join(control,'plugin-repairs');
17
+ if(versionContext){
18
+ const relativeControl=path.relative(path.join(root,'.control/runtime/plugin-versions'),control).split(path.sep),relativeSource=path.relative(path.join(root,'.control/runtime/plugin-candidates'),source).split(path.sep);
19
+ if(!exact(versionContext,['source','control','targetIdentity'])||relativeControl.length!==3||!uuid(relativeControl[0])||relativeControl[1]!=='repairs'||!uuid(relativeControl[2])||source!==path.join(root,'plugin')&&(relativeSource.length!==2||!uuid(relativeSource[0])||relativeSource[1]!=='plugin')||![versionContext.targetIdentity?.dev,versionContext.targetIdentity?.ino,versionContext.targetIdentity?.uid].every(Number.isSafeInteger)||versionContext.targetIdentity?.mode!==0o700)fail('CONTRACT');
20
+ }
21
+ const files=new Map(),owned=new Map();
22
+ for(const f of manifest){if(!exact(f,['path','sha256'])||!rel(f.path)||!digest(f.sha256)||files.has(f.path))fail('MANIFEST');files.set(f.path,{...f});}
23
+ for(const f of inventory){if(!exact(f,['path','identity','sha256','kind'])||!rel(f.path)||!['file','directory'].includes(f.kind)||owned.has(f.path)||!Number.isSafeInteger(f.identity?.dev)||!Number.isSafeInteger(f.identity?.ino)||f.kind==='file'&&!digest(f.sha256))fail('INVENTORY');owned.set(f.path,structuredClone(f));}
24
+ for(const name of files.keys())if(owned.get(name)?.kind!=='file')fail('INVENTORY');
25
+ for(const [name,row] of owned)if(row.kind==='file'&&!files.has(name))fail('INVENTORY');
26
+ const binding=hash({operationId,runtimeId,root,manifest:[...files],inventory:[...owned],...(versionContext?{versionContext}:{})});
27
+ const seal=body=>({...body,signature:createHmac('sha256',proof).update(JSON.stringify(body)).digest('hex')});
28
+ function unseal(value){if(!value||!digest(value.signature))fail('JOURNAL_REVIEW');const {signature,...body}=value,expected=seal(body).signature;if(!timingSafeEqual(Buffer.from(signature,'hex'),Buffer.from(expected,'hex')))fail('JOURNAL_REVIEW');return body;}
29
+ const planPath=path.join(control,'plugin-repair-plan.json');
30
+ async function guard(){const p=await verifyOwnedStopped();if(!exact(p,['operationId','runtimeId','stopped','ownershipVerified'])||p.operationId!==operationId||p.runtimeId!==runtimeId||p.stopped!==true||p.ownershipVerified!==true)fail('STOP_OR_OWNERSHIP_REQUIRED');}
31
+ async function inspect(){
32
+ await guard();await ancestors(source);await ancestors(target);await ancestors(control);
33
+ const targetStat=await fs.lstat(target),controlStat=await fs.lstat(control);if(targetStat.dev!==controlStat.dev)fail('CROSS_DEVICE');
34
+ if(versionContext&&(!sameIdentity(targetStat,versionContext.targetIdentity)||targetStat.uid!==versionContext.targetIdentity.uid||(targetStat.mode&0o777)!==0o700))fail('DIRECTORY_DRIFT');
35
+ const seen=new Set(),current=new Map();
36
+ async function walk(dir,prefix=''){
37
+ for(const name of (await fs.readdir(dir)).sort()){
38
+ const relative=prefix+name,p=path.join(dir,name),o=owned.get(relative);if(!o)fail('UNKNOWN_FILE');
39
+ const s=await fs.lstat(p);if(s.isSymbolicLink()||versionContext&&s.uid!==process.getuid())fail('UNSAFE_FILE');if(s.dev!==controlStat.dev)fail('CROSS_DEVICE');seen.add(relative);
40
+ if(versionContext&&o.kind==='directory'&&(s.mode&0o777)!==o.identity.mode)fail('DIRECTORY_DRIFT');
41
+ if(o.kind==='directory'){if(!s.isDirectory()||!sameIdentity(s,o.identity))fail('DIRECTORY_DRIFT');await walk(p,relative+'/');}
42
+ else {if(!s.isFile())fail('UNSAFE_FILE');current.set(relative,await snapshot(p,4194304));}
43
+ }
44
+ }
45
+ await walk(target);
46
+ for(const [name,o] of owned)if(o.kind==='directory'&&!seen.has(name))fail('DIRECTORY_MISSING');
47
+ const items=[];let total=0;
48
+ for(const [name,f] of files){
49
+ const s=await snapshot(path.join(source,name),4194304);if(s.missing||s.sha256!==f.sha256)fail('SOURCE_DRIFT');
50
+ const before=current.get(name)??{missing:true};
51
+ if(!before.missing&&before.mode!==0o600)fail('MODE_REVIEW');
52
+ if(!before.missing&&before.sha256===f.sha256){if(versionContext&&!sameIdentity(before,owned.get(name).identity))fail('OWNERSHIP_DRIFT');continue;}
53
+ total+=bytes(s).length+(before.missing?0:bytes(before).length);if(total>8388608)fail('SIZE_LIMIT');
54
+ items.push({relative:name,path:path.join(target,name),action:before.missing?'create':'replace',before,after:s.data,afterHash:s.sha256,phase:'pending'});
55
+ }
56
+ // Directory link counts change when the durable preview is created (APFS).
57
+ // Keep inode/device/mode/owner identity; file hard-link checks remain strict.
58
+ const directory=s=>({dev:s.dev,ino:s.ino,mode:s.mode&0o777,uid:s.uid});
59
+ return {items,targetIdentity:directory(targetStat),controlIdentity:directory(controlStat),observations:[...current].map(([name,s])=>({name,...s,data:undefined}))};
60
+ }
61
+ const journalPath=id=>path.join(folder,id,'journal.json');
62
+ async function save(j){await atomicState(journalPath(j.id),seal(j));}
63
+ async function read(id){
64
+ if(!uuid(id))fail('ARGUMENTS');const s=await snapshot(journalPath(id),16777216);if(s.missing)fail('NOT_FOUND');let j;try{j=unseal(JSON.parse(bytes(s)));}catch{fail('JOURNAL_REVIEW');}
65
+ if(j?.schema!==1||j.id!==id||j.binding!==binding||!digest(j.planHash)||!['applying','committed','rolling_back','rolled_back','needs_review'].includes(j.state)||!Array.isArray(j.items)||!j.items.length||j.items.length>512||new Set(j.items.map(x=>x.relative)).size!==j.items.length)fail('JOURNAL_REVIEW');
66
+ for(const i of j.items){
67
+ if(!files.has(i.relative)||i.path!==path.join(target,i.relative)||!['create','replace'].includes(i.action)||!['pending','intent','done','restored'].includes(i.phase)||!i.before||i.action==='create'&&!i.before.missing||i.action==='replace'&&i.before.missing||!i.before.missing&&(hash(bytes(i.before))!==i.before.sha256||bytes(i.before).length!==i.before.size)||typeof i.after!=='string'||hash(Buffer.from(i.after,'base64'))!==files.get(i.relative).sha256||i.afterHash!==files.get(i.relative).sha256||i.published&&(i.published.sha256!==i.afterHash||i.published.size!==Buffer.from(i.after,'base64').length))fail('JOURNAL_REVIEW');
68
+ }
69
+ if(!sameIdentity(await fs.lstat(path.dirname(journalPath(id))),j.directoryIdentity))fail('DIRECTORY_DRIFT');
70
+ const names=new Set(['journal.json',...j.items.flatMap((_,n)=>['stage-'+n,'backup-'+n])]);if((await fs.readdir(path.dirname(journalPath(id)))).some(n=>!names.has(n)))fail('JOURNAL_REVIEW');
71
+ if(!sameIdentity(await fs.lstat(target),j.targetIdentity)||!sameIdentity(await fs.lstat(control),j.controlIdentity))fail('DIRECTORY_DRIFT');return j;
72
+ }
73
+ async function pending(){
74
+ const stat=await statMaybe(folder);if(!stat)return null;await ancestors(folder);
75
+ for(const name of await fs.readdir(folder)){if(!uuid(name))fail('JOURNAL_REVIEW');const j=await read(name);if(!['committed','rolled_back'].includes(j.state))return j;}
76
+ return null;
77
+ }
78
+ async function rollback(j){
79
+ await guard();j.state='rolling_back';await save(j);const review=[];
80
+ for(let n=j.items.length-1;n>=0;n--){try{await guard();if(j.items[n].phase==='pending'&&(await statMaybe(path.join(path.dirname(journalPath(j.id)),'stage-'+n))||await statMaybe(path.join(path.dirname(journalPath(j.id)),'backup-'+n))))fail('UNRECORDED_STAGE');await rollbackMaintenanceItem(j.items[n],path.dirname(journalPath(j.id)),n,4194304);j.items[n].phase='restored';await save(j);}catch{review.push({path:j.items[n].relative,reason:'changed_or_unverified_preserved'});}}
81
+ j.review=review;j.state=review.length?'needs_review':'rolled_back';await save(j);return view(j);
82
+ }
83
+ async function preview(){return exclusive(async()=>{
84
+ if(await pending())fail('RECOVERY_REQUIRED');if(!(await snapshot(planPath,16777216)).missing)await loadPlan();const observation=await inspect(),id=randomUUID(),expiresAt=now()+300000;
85
+ const fingerprint=hash({binding,observation,id,expiresAt});await atomicState(planPath,seal({binding,id,expiresAt,fingerprint,observation}));
86
+ return {id,fingerprint,expiresAt,canApply:observation.items.length>0,changes:observation.items.map(i=>({path:i.relative,action:i.action,beforeHash:i.before.sha256??null,afterHash:i.afterHash})),scope:'stopped_owned_plugin_files_only',userDataChanged:false,credentialsChanged:false,versionUpgrade:false,hostStarted:false};
87
+ });}
88
+ async function loadPlan(){const s=await snapshot(planPath,16777216);if(s.missing)fail('PLAN_EXPIRED');let p;try{p=unseal(JSON.parse(bytes(s)));}catch{fail('JOURNAL_REVIEW');}if(p.binding!==binding||hash({binding,observation:p.observation,id:p.id,expiresAt:p.expiresAt})!==p.fingerprint)fail('PLAN_DRIFT');return p;}
89
+ async function validate(a){return exclusive(async()=>{if(!exact(a,['id','fingerprint','confirm'])||a.confirm!==true||!uuid(a.id)||!digest(a.fingerprint))fail('CONFIRMATION_REQUIRED');await guard();if(await pending())fail('RECOVERY_REQUIRED');const p=await loadPlan();if(p.id!==a.id||p.fingerprint!==a.fingerprint||p.expiresAt<=now())fail('PLAN_EXPIRED');if(!p.observation.items.length||hash(await inspect())!==hash(p.observation))fail('PLAN_DRIFT');return {id:p.id,fingerprint:p.fingerprint,ready:true};});}
90
+ async function apply(a){return exclusive(async()=>{
91
+ if(!exact(a,['id','fingerprint','confirm'])||a.confirm!==true||!uuid(a.id)||!digest(a.fingerprint))fail('CONFIRMATION_REQUIRED');await guard();
92
+ if(await statMaybe(journalPath(a.id))){const old=await read(a.id);if(old.planHash!==a.fingerprint)fail('PLAN_DRIFT');return {...view(old),notResent:true};}
93
+ if(await pending())fail('RECOVERY_REQUIRED');const p=await loadPlan();
94
+ if(p.id!==a.id||p.fingerprint!==a.fingerprint||p.expiresAt<=now())fail('PLAN_EXPIRED');
95
+ const fresh=await inspect();if(hash(fresh)!==hash(p.observation)||!fresh.items.length)fail('PLAN_DRIFT');
96
+ await fs.mkdir(folder,{recursive:true,mode:0o700});if((await fs.readdir(folder)).length>=128)fail('HISTORY_FULL');const dir=path.dirname(journalPath(p.id));await fs.mkdir(dir,{mode:0o700});await syncDirectory(folder);
97
+ const j={schema:1,id:p.id,binding,planHash:p.fingerprint,state:'applying',items:fresh.items,targetIdentity:fresh.targetIdentity,controlIdentity:fresh.controlIdentity,directoryIdentity:identity(await fs.lstat(dir)),review:[]};await save(j);
98
+ try{
99
+ for(let n=0;n<j.items.length;n++){await guard();await publishMaintenanceItem(j.items[n],dir,n,()=>save(j),hook,4194304);}
100
+ await guard();for(const i of j.items){const s=await snapshot(i.path,4194304);if(s.sha256!==i.afterHash||!sameIdentity(s,i.published))fail('PUBLISH_DRIFT');}
101
+ j.state='committed';await save(j);return view(j);
102
+ }catch(e){j.error=/^[A-Z_]+$/.test(e.message)?e.message:'REPAIR_INTERRUPTED';await save(j);return rollback(j);}
103
+ });}
104
+ async function recover(a){return exclusive(async()=>{if(!exact(a,['id','confirm'])||a.confirm!==true||!uuid(a.id))fail('CONFIRMATION_REQUIRED');await guard();
105
+ if(!await statMaybe(path.dirname(journalPath(a.id)))){const p=await loadPlan();if(p.id!==a.id||hash(await inspect())!==hash(p.observation))fail('JOURNAL_REVIEW');return {...view({id:p.id,planHash:p.fingerprint,state:'rolled_back',items:p.observation.items}),unchangedPreimageObserved:true};}
106
+ const j=await read(a.id);if(['committed','rolled_back'].includes(j.state))return {...view(j),notResent:true};return rollback(j);
107
+ });}
108
+ async function status(a){return exclusive(async()=>{if(!exact(a,['id']))fail('ARGUMENTS');return view(await read(a.id));});}
109
+ // Only a verified committed publication can supply replacement ownership.
110
+ // Do not rescan/adopt all current files or use a post-crash new inode as proof.
111
+ async function ownership(a){return exclusive(async()=>{if(!exact(a,['id']))fail('ARGUMENTS');await guard();const j=await read(a.id);if(j.state!=='committed')fail('NOT_COMMITTED');const rows=[];
112
+ for(const i of j.items){const s=await snapshot(i.path,4194304);if(!i.published||s.missing||s.sha256!==i.afterHash||s.mode!==0o600||!sameIdentity(s,i.published))fail('PUBLISH_DRIFT');rows.push({path:i.relative,sha256:s.sha256,bytes:s.size,identity:identity(s)});}
113
+ return rows;
114
+ });}
115
+ return {preview,validate,apply,recover,status,ownership};
116
+ }