owenloop 0.4.1 → 0.5.1

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 (282) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +182 -53
  3. package/bin/owenloop.mjs +50 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +176 -0
  5. package/dist/packages/work/src/agent/brief.js +197 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +141 -0
  7. package/dist/packages/work/src/agent/loop.js +669 -0
  8. package/dist/packages/work/src/agent/model-policy.d.ts +49 -0
  9. package/dist/packages/work/src/agent/model-policy.js +138 -0
  10. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  11. package/dist/packages/work/src/agent/workdir.js +319 -0
  12. package/dist/packages/work/src/bundle/cache.d.ts +92 -0
  13. package/dist/packages/work/src/bundle/cache.js +338 -0
  14. package/dist/packages/work/src/bundle/fetch.d.ts +87 -0
  15. package/dist/packages/work/src/bundle/fetch.js +345 -0
  16. package/dist/packages/work/src/bundle/types.d.ts +164 -0
  17. package/dist/packages/work/src/bundle/types.js +1 -0
  18. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  19. package/dist/packages/work/src/consumed-verifier.js +205 -0
  20. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  21. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  22. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  23. package/dist/packages/work/src/credentials/reader.js +32 -0
  24. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  25. package/dist/packages/work/src/credentials/resolve.js +56 -0
  26. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  27. package/dist/packages/work/src/exec/instructions.js +323 -0
  28. package/dist/packages/work/src/exec/loop.d.ts +40 -0
  29. package/dist/packages/work/src/exec/loop.js +332 -0
  30. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  31. package/dist/packages/work/src/exec/payload.js +54 -0
  32. package/dist/packages/work/src/exec/receipt.d.ts +41 -0
  33. package/dist/packages/work/src/exec/receipt.js +32 -0
  34. package/dist/packages/work/src/exec/runner.d.ts +71 -0
  35. package/dist/packages/work/src/exec/runner.js +256 -0
  36. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  37. package/dist/packages/work/src/harness/child-env.js +134 -0
  38. package/dist/packages/work/src/harness/claude.d.ts +140 -0
  39. package/dist/packages/work/src/harness/claude.js +837 -0
  40. package/dist/packages/work/src/harness/codex.d.ts +111 -0
  41. package/dist/packages/work/src/harness/codex.js +1024 -0
  42. package/dist/packages/work/src/harness/contract.d.ts +308 -0
  43. package/dist/packages/work/src/harness/contract.js +32 -0
  44. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  45. package/dist/packages/work/src/harness/fake.js +91 -0
  46. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  47. package/dist/packages/work/src/harness/jsonrpc-stdio.js +351 -0
  48. package/dist/packages/work/src/harness/permissions.d.ts +75 -0
  49. package/dist/packages/work/src/harness/permissions.js +182 -0
  50. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  51. package/dist/packages/work/src/harness/registry.js +45 -0
  52. package/dist/packages/work/src/harness/session-store.d.ts +181 -0
  53. package/dist/packages/work/src/harness/session-store.js +523 -0
  54. package/dist/packages/work/src/harness/types.d.ts +29 -0
  55. package/dist/packages/work/src/harness/types.js +14 -0
  56. package/dist/packages/work/src/harnesses.d.ts +38 -0
  57. package/dist/packages/work/src/harnesses.js +38 -0
  58. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  59. package/dist/packages/work/src/hold/loop.js +23 -0
  60. package/dist/packages/work/src/hold/mcp.d.ts +75 -0
  61. package/dist/packages/work/src/hold/mcp.js +264 -0
  62. package/dist/packages/work/src/hub/client.d.ts +23 -0
  63. package/dist/packages/work/src/hub/client.js +91 -0
  64. package/dist/packages/work/src/hub/types.d.ts +326 -0
  65. package/dist/packages/work/src/hub/types.js +26 -0
  66. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  67. package/dist/packages/work/src/lease/loop.js +277 -0
  68. package/dist/packages/work/src/main.d.ts +1 -0
  69. package/dist/packages/work/src/main.js +48 -0
  70. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  71. package/dist/packages/work/src/mcp/server.js +320 -0
  72. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  73. package/dist/packages/work/src/owenloop-bin.js +18 -0
  74. package/dist/packages/work/src/roles/agent-run.d.ts +124 -0
  75. package/dist/packages/work/src/roles/agent-run.js +529 -0
  76. package/dist/packages/work/src/roles/exec.d.ts +48 -0
  77. package/dist/packages/work/src/roles/exec.js +228 -0
  78. package/dist/packages/work/src/roles/hold.d.ts +72 -0
  79. package/dist/packages/work/src/roles/hold.js +363 -0
  80. package/dist/packages/work/src/roles/join.d.ts +18 -0
  81. package/dist/packages/work/src/roles/join.js +204 -0
  82. package/dist/packages/work/src/roles/lint.d.ts +58 -0
  83. package/dist/packages/work/src/roles/lint.js +234 -0
  84. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  85. package/dist/packages/work/src/roles/prepare.js +249 -0
  86. package/dist/packages/work/src/roles/release.d.ts +48 -0
  87. package/dist/packages/work/src/roles/release.js +137 -0
  88. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  89. package/dist/packages/work/src/roles/sessions.js +180 -0
  90. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  91. package/dist/packages/work/src/roles/settings.js +71 -0
  92. package/dist/packages/work/src/roles/shift.d.ts +13 -0
  93. package/dist/packages/work/src/roles/shift.js +250 -0
  94. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  95. package/dist/packages/work/src/roles/signals.js +62 -0
  96. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  97. package/dist/packages/work/src/settings/provision.js +47 -0
  98. package/dist/packages/work/src/settings/settings.d.ts +136 -0
  99. package/dist/packages/work/src/settings/settings.js +155 -0
  100. package/dist/packages/work/src/shift/client.d.ts +24 -0
  101. package/dist/packages/work/src/shift/client.js +124 -0
  102. package/dist/packages/work/src/shift/loop.d.ts +131 -0
  103. package/dist/packages/work/src/shift/loop.js +751 -0
  104. package/dist/packages/work/src/shift/protocol.d.ts +95 -0
  105. package/dist/packages/work/src/shift/protocol.js +24 -0
  106. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  107. package/dist/packages/work/src/shift/routing.js +50 -0
  108. package/dist/packages/work/src/shift/runtime.d.ts +45 -0
  109. package/dist/packages/work/src/shift/runtime.js +337 -0
  110. package/dist/packages/work/src/shift/server.d.ts +23 -0
  111. package/dist/packages/work/src/shift/server.js +716 -0
  112. package/dist/packages/work/src/shift/spawn.d.ts +109 -0
  113. package/dist/packages/work/src/shift/spawn.js +158 -0
  114. package/dist/packages/work/src/shift/state.d.ts +79 -0
  115. package/dist/packages/work/src/shift/state.js +385 -0
  116. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  117. package/dist/packages/work/src/submit-proof.js +93 -0
  118. package/dist/packages/work/src/usage.d.ts +6 -0
  119. package/dist/packages/work/src/usage.js +175 -0
  120. package/dist/src/add.d.ts +189 -0
  121. package/dist/src/add.js +300 -0
  122. package/dist/src/archive.d.ts +97 -0
  123. package/dist/src/archive.js +591 -0
  124. package/dist/src/bundle/index.d.ts +64 -0
  125. package/dist/src/bundle/index.js +508 -0
  126. package/dist/src/bundle/manifest.d.ts +50 -0
  127. package/dist/src/bundle/manifest.js +435 -0
  128. package/dist/src/bundle/runtime.d.ts +26 -0
  129. package/dist/src/bundle/runtime.js +64 -0
  130. package/dist/src/bundle/tar.d.ts +62 -0
  131. package/dist/src/bundle/tar.js +238 -0
  132. package/dist/src/bundle/types.d.ts +105 -0
  133. package/dist/src/bundle/types.js +21 -0
  134. package/dist/{cli.d.ts → src/cli.d.ts} +92 -7
  135. package/dist/src/cli.js +5968 -0
  136. package/dist/{credentials.d.ts → src/credentials.d.ts} +22 -15
  137. package/dist/{credentials.js → src/credentials.js} +35 -31
  138. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  139. package/dist/src/crypto/allowed-signers.js +307 -0
  140. package/dist/src/crypto/canonical.d.ts +8 -0
  141. package/dist/src/crypto/canonical.js +92 -0
  142. package/dist/src/crypto/chain.d.ts +65 -0
  143. package/dist/src/crypto/chain.js +377 -0
  144. package/dist/src/crypto/dsse.d.ts +209 -0
  145. package/dist/src/crypto/dsse.js +282 -0
  146. package/dist/src/crypto/enrollment.d.ts +78 -0
  147. package/dist/src/crypto/enrollment.js +186 -0
  148. package/dist/src/crypto/index.d.ts +48 -0
  149. package/dist/src/crypto/index.js +44 -0
  150. package/dist/src/crypto/keys.d.ts +258 -0
  151. package/dist/src/crypto/keys.js +908 -0
  152. package/dist/src/crypto/org-root.d.ts +33 -0
  153. package/dist/src/crypto/org-root.js +78 -0
  154. package/dist/src/crypto/origin-rules.d.ts +56 -0
  155. package/dist/src/crypto/origin-rules.js +143 -0
  156. package/dist/src/crypto/policy-floor.d.ts +98 -0
  157. package/dist/src/crypto/policy-floor.js +353 -0
  158. package/dist/src/crypto/records.d.ts +316 -0
  159. package/dist/src/crypto/records.js +157 -0
  160. package/dist/src/crypto/scope.d.ts +49 -0
  161. package/dist/src/crypto/scope.js +83 -0
  162. package/dist/src/crypto/ssh.d.ts +171 -0
  163. package/dist/src/crypto/ssh.js +396 -0
  164. package/dist/src/crypto/submission.d.ts +33 -0
  165. package/dist/src/crypto/submission.js +47 -0
  166. package/dist/src/crypto/trust-roots.d.ts +29 -0
  167. package/dist/src/crypto/trust-roots.js +39 -0
  168. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  169. package/dist/src/crypto/verify-consumed.js +259 -0
  170. package/dist/src/crypto/verify-origin.d.ts +50 -0
  171. package/dist/src/crypto/verify-origin.js +151 -0
  172. package/dist/src/crypto/verify-publication.d.ts +60 -0
  173. package/dist/src/crypto/verify-publication.js +150 -0
  174. package/dist/{defs.d.ts → src/defs.d.ts} +24 -1
  175. package/dist/{defs.js → src/defs.js} +181 -61
  176. package/dist/{engine.d.ts → src/engine.d.ts} +105 -9
  177. package/dist/{engine.js → src/engine.js} +251 -47
  178. package/dist/{factory.d.ts → src/factory.d.ts} +16 -0
  179. package/dist/{factory.js → src/factory.js} +16 -4
  180. package/dist/src/global-config.d.ts +59 -0
  181. package/dist/src/global-config.js +84 -0
  182. package/dist/{hub.d.ts → src/hub.d.ts} +280 -31
  183. package/dist/{hub.js → src/hub.js} +493 -52
  184. package/dist/src/index.d.ts +47 -0
  185. package/dist/src/index.js +41 -0
  186. package/dist/src/install.d.ts +538 -0
  187. package/dist/src/install.js +1981 -0
  188. package/dist/src/lock.d.ts +38 -0
  189. package/dist/src/lock.js +325 -0
  190. package/dist/src/mcp/serve.d.ts +109 -0
  191. package/dist/{mcp → src/mcp}/serve.js +335 -75
  192. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  193. package/dist/{mcp → src/mcp}/server.js +18 -10
  194. package/dist/{model.d.ts → src/model.d.ts} +15 -0
  195. package/dist/{model.js → src/model.js} +112 -2
  196. package/dist/src/order-resolver.d.ts +184 -0
  197. package/dist/src/order-resolver.js +252 -0
  198. package/dist/src/package-version.d.ts +10 -0
  199. package/dist/src/package-version.js +42 -0
  200. package/dist/{paths.d.ts → src/paths.d.ts} +14 -1
  201. package/dist/{paths.js → src/paths.js} +18 -0
  202. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  203. package/dist/src/schemas/index.d.ts +1416 -0
  204. package/dist/src/schemas/index.js +31 -0
  205. package/dist/src/schemas/order.v1.schema.json +106 -0
  206. package/dist/src/schemas/origin.v1.schema.json +68 -0
  207. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  208. package/dist/src/schemas/publication.v1.schema.json +31 -0
  209. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  210. package/dist/src/schemas/submission.v1.schema.json +61 -0
  211. package/dist/src/store/def-source.d.ts +52 -0
  212. package/dist/src/store/def-source.js +335 -0
  213. package/dist/src/store/index-file.d.ts +69 -0
  214. package/dist/src/store/index-file.js +151 -0
  215. package/dist/src/store/index.d.ts +27 -0
  216. package/dist/src/store/index.js +22 -0
  217. package/dist/src/store/ingestor.d.ts +43 -0
  218. package/dist/src/store/ingestor.js +211 -0
  219. package/dist/src/store/install.d.ts +228 -0
  220. package/dist/src/store/install.js +555 -0
  221. package/dist/src/store/instruction-source.d.ts +49 -0
  222. package/dist/src/store/instruction-source.js +298 -0
  223. package/dist/src/store/origin-evidence.d.ts +21 -0
  224. package/dist/src/store/origin-evidence.js +66 -0
  225. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  226. package/dist/src/store/pre-commit-verifier.js +418 -0
  227. package/dist/src/store/resolve.d.ts +138 -0
  228. package/dist/src/store/resolve.js +363 -0
  229. package/dist/src/store/types.d.ts +288 -0
  230. package/dist/src/store/types.js +356 -0
  231. package/dist/{types.d.ts → src/types.d.ts} +58 -24
  232. package/dist/{untar.d.ts → src/untar.d.ts} +8 -23
  233. package/dist/src/untar.js +38 -0
  234. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  235. package/dist/{util.js → src/util.js} +3 -2
  236. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  237. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  238. package/docs/agent-runner.md +86 -0
  239. package/docs/authoring.md +150 -59
  240. package/docs/bundles.md +250 -0
  241. package/docs/cli.md +1758 -163
  242. package/docs/crypto.md +816 -0
  243. package/docs/design.md +374 -52
  244. package/docs/embedding.md +135 -27
  245. package/docs/wire-contracts.md +380 -0
  246. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  247. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  248. package/examples/workflows/judges/gate-sharpness.md +39 -0
  249. package/examples/workflows/judges/security.md +34 -0
  250. package/package.json +22 -8
  251. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  252. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  253. package/plugins/claude-code/plugin/.mcp.json +14 -0
  254. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  255. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  256. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  257. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  258. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  259. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  260. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  261. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  262. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  263. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  264. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  265. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  266. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  267. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  268. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
  269. package/dist/add.d.ts +0 -384
  270. package/dist/add.js +0 -834
  271. package/dist/cli.js +0 -3270
  272. package/dist/index.d.ts +0 -32
  273. package/dist/index.js +0 -23
  274. package/dist/lock.d.ts +0 -80
  275. package/dist/lock.js +0 -217
  276. package/dist/mcp/serve.d.ts +0 -84
  277. package/dist/untar.js +0 -164
  278. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  279. /package/dist/{schema.js → src/schema.js} +0 -0
  280. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  281. /package/dist/{store.js → src/store.js} +0 -0
  282. /package/dist/{types.js → src/types.js} +0 -0
@@ -0,0 +1,47 @@
1
+ /**
2
+ * owenloop — a generic dataflow workflow engine.
3
+ *
4
+ * Steps owe and consume artifacts; a step's eligibility to run is a pure
5
+ * function of artifact state (debts + dependency satisfaction), not a status
6
+ * enum. Rejection carries a reason thread; a forward cascade keeps the graph
7
+ * honest ("an artifact is green only while every artifact it consumed is
8
+ * green"); a commit-fingerprint CAS makes concurrent advancement safe.
9
+ *
10
+ * This is the public API. The engine is domain-neutral: a *wiring* (a set of
11
+ * workflow definitions + a Step Agent that executes orders) layers a concrete
12
+ * process — software delivery, research, triage — on top of it.
13
+ */
14
+ export { CallsPinError, Engine } from './engine.ts';
15
+ export type { CommitResult, CreateOpts, DefResolver, DeferredFiring, DeferredReason, EmitResult, EngineEvent, EngineListener, EngineWorkflowStatus, Order, ReapDetail, ReapReason, TickResult, } from './engine.ts';
16
+ export { createEngine } from './factory.ts';
17
+ export type { CreateEngineOpts, CreatedEngine } from './factory.ts';
18
+ export { createDefInstructionSource, defInstructionDigest, OrderResolver, substituteOrderVars, UnknownDefDigestError, UnknownInstructionError, } from './order-resolver.ts';
19
+ export type { OrderInstructionLookup, OrderInstructionRef, OrderInstructionSource, OrderRuntimeVars, ResolvedInstructionRecord, ResolvedInstructions, } from './order-resolver.ts';
20
+ export { Store, openStore, StoreVersionError } from './store.ts';
21
+ export type { ArtifactRow, RunRow, TaskRow, WorkflowRow } from './store.ts';
22
+ export { defDigest, emptyWorkflowStoreIndex, globalStoreRoot, hardenObjectModes, installWorkflowBundle, inspectCasDefs, isDefDigest, loadCasDefs, objectDestRelPath, objectDirForDigest, parseWorkflowCoordinate, parseWorkflowStoreIndex, projectStoreRoot, probeObjectDir, probeStoreRoot, readWorkflowStoreIndex, recoverWorkflowStore, resolveWorkflowCoordinate, resolveWorkflowDigest, serializeWorkflowStoreIndex, storeIndexPath, workflowCoordinate, workflowStoreStatePaths, WORKFLOW_STORE_INDEX_VERSION, WorkflowStoreError, StoreIndexError, StoreDigestError, StoreCoordinateError, StoreAmbiguityError, StoreNotFoundError, StoreIntegrityError, StoreConflictError, StoreDefinitionVerificationError, StoreOriginPolicyError, StorePathError, BundleIngestorUnavailableError, PreCommitVerifierUnavailableError, createExecutionOriginVerifier, originEvidencePath, persistOriginEvidence, readOriginEvidence, } from './store/index.ts';
23
+ export type { BundleInstallResult, BundleIngestor, BundleSource, CasDefInspectionResult, CasDefRegistration, DefDigest, LoadCasDefsArgs, InstallWorkflowBundleArgs, PreCommitVerifier, ExecutionOriginVerifierInput, RecoverWorkflowStoreArgs, ResolvedWorkflowObject, ResolveWorkflowCoordinateArgs, ResolveWorkflowDigestArgs, ResolutionLevel, StoreLevel, WorkflowCoordinate, WorkflowStoreIndex, WorkflowStoreIndexEntry, WorkflowStoreStatePaths, } from './store/index.ts';
24
+ export { buildDef, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, resolveCallsTarget, SUPPORTED_ENGINE_VERSION, validateDef } from './defs.ts';
25
+ export { credentialSlot, hashDefForHub, keychainServiceFor, normalizeOrigin, readStoredCredential } from './hub.ts';
26
+ export type { Credential, CredentialSlotSelector, Keychain, ReadStoredCredentialOpts } from './hub.ts';
27
+ export type { DefLoadFailure } from './defs.ts';
28
+ export { deleteCredential, ensureFreshOAuth, storeCredential } from './credentials.ts';
29
+ export type { CredentialIO } from './credentials.ts';
30
+ export { DSSE_SSH_NAMESPACE, DSSE_VERSION, DSSE_RECORD_PAYLOAD_TYPES, DsseEnvelopeError, isDsseRecordPayloadType, PAYLOAD_TYPE_ENROLLMENT_GRANT, PAYLOAD_TYPE_ORIGIN, PAYLOAD_TYPE_POLICY_FLOOR, PAYLOAD_TYPE_PUBLICATION, PAYLOAD_TYPE_REVOCATION, PAYLOAD_TYPE_SUBMISSION, PrincipalKeyManager, SshSigner, SshSignerError, assertEd25519PubText, assertKeyRef, canonicalKeyRef, createSshSigner, decodeBase64Strict, dsseSignEnrollmentGrant, dsseSignEnvelope, dsseSignOrigin, dsseSignPolicyFloor, dsseSignPublication, dsseSignRecord, dsseSignRevocation, dsseSignSubmission, dsseVerifyEnrollmentGrant, dsseVerifyEnvelope, dsseVerifyOrigin, dsseVerifyPolicyFloor, dsseVerifyPublication, dsseVerifyRecord, dsseVerifyRevocation, dsseVerifySubmission, encodeBase64, keyidFromBlob, keyRefHash, parseAllowedSigners, preAuthEncode, publicKeyDescriptor, allowedSignersPath, resolveAllowedSigners, resolveAllowedSignersFile, isDefPolicy, verifyOrigin, verifyOriginSidecar, verifyPublication, verifyPublicationSidecar, verifyConsumed, verifyConsumedArtifact, DEFAULT_MACHINE_SCOPE, buildEnrollmentGrant, verifyRosterEntry, validateEnrollmentChain, validateProducer, revocationTemporalConsistency, attenuate, axisPermits, delegationPermits, ORG_ROOT_SCOPE, scopePermits, loadRoster, loadRevocations, orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocationsDir, rosterDir, ENROLLMENT_GRANT_FIELDS, ENROLLMENT_KEY_FIELDS, GRANT_DELEGATION_ALLOWED_FIELDS, GRANT_DELEGATION_DENIED_FIELDS, GRANT_SCOPE_FIELDS, ORDER_FIELDS, ORDER_OWED_FIELDS, ORDER_REASON_FIELDS, ORIGIN_FIELDS, ORIGIN_SOURCE_AGENT_FIELDS, ORIGIN_SOURCE_CONSOLE_FIELDS, ORIGIN_SOURCE_GIT_FIELDS, POLICY_FLOOR_FIELDS, POLICY_FLOOR_RECORD_FIELDS, PRINCIPAL_REFERENCE_FIELDS, PUBLICATION_FIELDS, RECORD_PAYLOAD_TYPES, REVOCATION_FIELDS, SUBMISSION_FIELDS, SUBMISSION_PRODUCED_FIELDS, } from './crypto/index.ts';
31
+ export type { AllowedSignerEntry, AllowedSignerOptions, AllowedSignersFile, AllowedSignersParseError, AllowedSignersResolution, AllowedSignersPresent, AllowedSignersAbsent, DefPolicy, DefVerdict, OriginVerdict, VerifyOriginInput, VerifyOriginOptions, ConsumedVerdict, VerifyConsumedInput, VerifyConsumedOptions, VerifyPublicationInput, VerifyPublicationOptions, BuildEnrollmentGrantArgs, EnrollmentChainValidator, RosterVerdict, VerifyRosterEntryInput, VerifyRosterEntryOptions, ChainInput, ChainOptions, ChainVerdict, ScopeAxis, OrgRootAbsent, OrgRootPresent, OrgRootResolution, DetachedSignature, DsseEnvelope, DsseRecordPayloadType, DsseSignature, DsseVerifyResult, EnsureKeyResult, InspectKeyResult, KeyStorageBackendKind, PrincipalKeyRef, PrincipalKind, PublicKeyDescriptor, EnrollmentGrantRecord, EnrollmentKeyDescriptor, FieldManifest, GrantDelegation, GrantDelegationAllowed, GrantDelegationDenied, GrantScope, OptionalKeys, OriginRecord, OriginSource, OriginSourceAgent, OriginSourceConsole, OriginSourceGit, PolicyFloor, PolicyFloorRecord, PrincipalReference, PublicationRecord, RequiredKeys, RevocationRecord, SubmissionProducedArtifact, SubmissionRecord, Signer, SshProcessAdapter, SshSignerConfig, VerifiedSignature, } from './crypto/index.ts';
32
+ export { DEF_POLICY_RANK, POLICY_FLOOR_PRESETS, artifactPolicyMinimum, floorDefPolicyMinimum, mergePolicyFloorWithLocal, originRulesMinimum, policyFloorGaps, stricterDefPolicy, verifyPolicyFloorRecord, } from './crypto/index.ts';
33
+ export type { PolicyFloorGap, PolicyFloorMergeResult, PolicyFloorVerdict, VerifyPolicyFloorInput, VerifyPolicyFloorOptions, } from './crypto/index.ts';
34
+ export { ORIGIN_SOURCE_RANK, OriginRulesError, evaluateOriginRule, matchOriginRule, parseOriginRules, } from './crypto/index.ts';
35
+ export type { OriginPolicy, OriginRuleEvaluation, OriginRuleMatch, OriginRuleValue, OriginRules, } from './crypto/index.ts';
36
+ export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from './model.ts';
37
+ export type { ArtifactMap, Blocker, Firing, TimeFacts, WorkflowStatus } from './model.ts';
38
+ export { parseConsume, parseProduce, } from './paths.ts';
39
+ export { assertValidSchema, summarizeIssues, validateValue } from './schema.ts';
40
+ export type { SchemaCheck, SchemaIssue } from './schema.ts';
41
+ export { enrollmentGrantSchema, orderSchema, originSchema, policyFloorSchema, publicationSchema, RECORD_SCHEMAS, revocationSchema, SCHEMA_BY_PAYLOAD_TYPE, submissionSchema, WIRE_SCHEMAS, } from './schemas/index.ts';
42
+ export { BundleError, DEFAULT_BUNDLE_LIMITS, digestBundle, inspectBundle, packBundle, unpackBundle } from './bundle/index.ts';
43
+ export type { BundleEntryInfo, BundleErrorCode, BundleLimits, BundleManifest, BundleRuntimeRequirements, InspectOptions, InspectResult, PackOptions, PackResult, } from './bundle/index.ts';
44
+ export { DEBT_STATES, SETTLED_STATES } from './types.ts';
45
+ export type { Acceptance, ArtifactBiography, ArtifactData, Author, CheckFinding, CheckOptions, CheckReport, CheckStep, ConsumePattern, FiringTrigger, Fingerprint, GraphEdge, GraphNode, GraphNodeState, InputDef, InvariantDef, InvariantPredicate, InvariantViolation, JsonSchema, StepDef, ProducePattern, ReasonEntry, RejectKind, RunData, TaskData, TimelineEvent, WorkflowDef, WorkflowGraph, WorkflowTrace, } from './types.ts';
46
+ export { canonicalValueBytes, valueDigestHex, buildSubmissionRecord, signSubmission } from './crypto/index.ts';
47
+ export type { BuildSubmissionRecordInput, SubmissionProducedInput } from './crypto/index.ts';
@@ -0,0 +1,41 @@
1
+ /**
2
+ * owenloop — a generic dataflow workflow engine.
3
+ *
4
+ * Steps owe and consume artifacts; a step's eligibility to run is a pure
5
+ * function of artifact state (debts + dependency satisfaction), not a status
6
+ * enum. Rejection carries a reason thread; a forward cascade keeps the graph
7
+ * honest ("an artifact is green only while every artifact it consumed is
8
+ * green"); a commit-fingerprint CAS makes concurrent advancement safe.
9
+ *
10
+ * This is the public API. The engine is domain-neutral: a *wiring* (a set of
11
+ * workflow definitions + a Step Agent that executes orders) layers a concrete
12
+ * process — software delivery, research, triage — on top of it.
13
+ */
14
+ export { CallsPinError, Engine } from "./engine.js";
15
+ export { createEngine } from "./factory.js";
16
+ export { createDefInstructionSource, defInstructionDigest, OrderResolver, substituteOrderVars, UnknownDefDigestError, UnknownInstructionError, } from "./order-resolver.js";
17
+ export { Store, openStore, StoreVersionError } from "./store.js";
18
+ // The content-addressed WORKFLOW store (distinct from the SQLite runtime
19
+ // store above): two-level digest-addressed workflow objects + coordinate
20
+ // index, `.wnlp` bundle installation, and fail-closed resolution.
21
+ export { defDigest, emptyWorkflowStoreIndex, globalStoreRoot, hardenObjectModes, installWorkflowBundle, inspectCasDefs, isDefDigest, loadCasDefs, objectDestRelPath, objectDirForDigest, parseWorkflowCoordinate, parseWorkflowStoreIndex, projectStoreRoot, probeObjectDir, probeStoreRoot, readWorkflowStoreIndex, recoverWorkflowStore, resolveWorkflowCoordinate, resolveWorkflowDigest, serializeWorkflowStoreIndex, storeIndexPath, workflowCoordinate, workflowStoreStatePaths, WORKFLOW_STORE_INDEX_VERSION, WorkflowStoreError, StoreIndexError, StoreDigestError, StoreCoordinateError, StoreAmbiguityError, StoreNotFoundError, StoreIntegrityError, StoreConflictError, StoreDefinitionVerificationError, StoreOriginPolicyError, StorePathError, BundleIngestorUnavailableError, PreCommitVerifierUnavailableError, createExecutionOriginVerifier, originEvidencePath, persistOriginEvidence, readOriginEvidence, } from "./store/index.js";
22
+ export { buildDef, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, resolveCallsTarget, SUPPORTED_ENGINE_VERSION, validateDef } from "./defs.js";
23
+ export { credentialSlot, hashDefForHub, keychainServiceFor, normalizeOrigin, readStoredCredential } from "./hub.js";
24
+ export { deleteCredential, ensureFreshOAuth, storeCredential } from "./credentials.js";
25
+ export { DSSE_SSH_NAMESPACE, DSSE_VERSION, DSSE_RECORD_PAYLOAD_TYPES, DsseEnvelopeError, isDsseRecordPayloadType, PAYLOAD_TYPE_ENROLLMENT_GRANT, PAYLOAD_TYPE_ORIGIN, PAYLOAD_TYPE_POLICY_FLOOR, PAYLOAD_TYPE_PUBLICATION, PAYLOAD_TYPE_REVOCATION, PAYLOAD_TYPE_SUBMISSION, PrincipalKeyManager, SshSigner, SshSignerError, assertEd25519PubText, assertKeyRef, canonicalKeyRef, createSshSigner, decodeBase64Strict, dsseSignEnrollmentGrant, dsseSignEnvelope, dsseSignOrigin, dsseSignPolicyFloor, dsseSignPublication, dsseSignRecord, dsseSignRevocation, dsseSignSubmission, dsseVerifyEnrollmentGrant, dsseVerifyEnvelope, dsseVerifyOrigin, dsseVerifyPolicyFloor, dsseVerifyPublication, dsseVerifyRecord, dsseVerifyRevocation, dsseVerifySubmission, encodeBase64, keyidFromBlob, keyRefHash, parseAllowedSigners, preAuthEncode, publicKeyDescriptor, allowedSignersPath, resolveAllowedSigners, resolveAllowedSignersFile, isDefPolicy, verifyOrigin, verifyOriginSidecar, verifyPublication, verifyPublicationSidecar, verifyConsumed, verifyConsumedArtifact, DEFAULT_MACHINE_SCOPE, buildEnrollmentGrant, verifyRosterEntry, validateEnrollmentChain, validateProducer, revocationTemporalConsistency, attenuate, axisPermits, delegationPermits, ORG_ROOT_SCOPE, scopePermits, loadRoster, loadRevocations, orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocationsDir, rosterDir, ENROLLMENT_GRANT_FIELDS, ENROLLMENT_KEY_FIELDS, GRANT_DELEGATION_ALLOWED_FIELDS, GRANT_DELEGATION_DENIED_FIELDS, GRANT_SCOPE_FIELDS, ORDER_FIELDS, ORDER_OWED_FIELDS, ORDER_REASON_FIELDS, ORIGIN_FIELDS, ORIGIN_SOURCE_AGENT_FIELDS, ORIGIN_SOURCE_CONSOLE_FIELDS, ORIGIN_SOURCE_GIT_FIELDS, POLICY_FLOOR_FIELDS, POLICY_FLOOR_RECORD_FIELDS, PRINCIPAL_REFERENCE_FIELDS, PUBLICATION_FIELDS, RECORD_PAYLOAD_TYPES, REVOCATION_FIELDS, SUBMISSION_FIELDS, SUBMISSION_PRODUCED_FIELDS, } from "./crypto/index.js";
26
+ // ---- policy floors ----
27
+ export { DEF_POLICY_RANK, POLICY_FLOOR_PRESETS, artifactPolicyMinimum, floorDefPolicyMinimum, mergePolicyFloorWithLocal, originRulesMinimum, policyFloorGaps, stricterDefPolicy, verifyPolicyFloorRecord, } from "./crypto/index.js";
28
+ // ---- WP-E2a origin execution policy ----
29
+ export { ORIGIN_SOURCE_RANK, OriginRulesError, evaluateOriginRule, matchOriginRule, parseOriginRules, } from "./crypto/index.js";
30
+ export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from "./model.js";
31
+ export { parseConsume, parseProduce, } from "./paths.js";
32
+ export { assertValidSchema, summarizeIssues, validateValue } from "./schema.js";
33
+ export { enrollmentGrantSchema, orderSchema, originSchema, policyFloorSchema, publicationSchema, RECORD_SCHEMAS, revocationSchema, SCHEMA_BY_PAYLOAD_TYPE, submissionSchema, WIRE_SCHEMAS, } from "./schemas/index.js";
34
+ // Deterministic `.wnlp` bundle format (WP-A1) — the HIGH-LEVEL API only:
35
+ // pack/inspect/digest/unpack plus result/manifest types, limits/options, and
36
+ // typed errors. Low-level tar builders and add install primitives are
37
+ // deliberately NOT exported through this surface (see docs/bundles.md).
38
+ export { BundleError, DEFAULT_BUNDLE_LIMITS, digestBundle, inspectBundle, packBundle, unpackBundle } from "./bundle/index.js";
39
+ export { DEBT_STATES, SETTLED_STATES } from "./types.js";
40
+ // ---- WP-D2 signed submission records ----
41
+ export { canonicalValueBytes, valueDigestHex, buildSubmissionRecord, signSubmission } from "./crypto/index.js";
@@ -0,0 +1,538 @@
1
+ /**
2
+ * The host-neutral install transaction shared by every route that swaps a
3
+ * validated staging tree into place atomically: safe staging, the atomic
4
+ * destination→backup / staging→destination swap with a retained backup,
5
+ * finalize/rollback, the atomic metadata write, the per-root install lock, the
6
+ * base applying/finalizing crash-journal phases, the v2 repair substates, and
7
+ * recovery driven by durable phase, metadata, and actual filesystem state.
8
+ *
9
+ * Two consumers share it today:
10
+ * - `src/add.ts` (the GitHub `owenloop add` route): metadata = `installed.json`,
11
+ * destination segment = a single folder directly under the defs dir, v1
12
+ * journal schema (a 40-char GitHub sha + source/ref ledger corroboration).
13
+ * - `src/store/install.ts` (the content-addressed workflow store): metadata =
14
+ * `index.json`, destination segment = a three-segment object path
15
+ * (`objects/sha256/<digest>`), v2 journal schema (identity = a
16
+ * metadata-hash match, no route-specific fields).
17
+ *
18
+ * For v1, fresh v2 installs, and v2 dedupe, the durable COMMIT POINT is the
19
+ * atomic METADATA write. Same-digest v2 repair is different: the metadata may
20
+ * already contain the target digest before replacement starts, so a matching
21
+ * metadata hash is never enough to accept the replacement. Repair recovery
22
+ * restores the prior backup or resumes recursive hardening plus exact content
23
+ * and mode verification; only `finalizing` makes the prior backup disposable.
24
+ * The journal is removed LAST so recovery stays idempotent (running it again
25
+ * changes nothing).
26
+ *
27
+ * The journal is attacker-influenceable input (it may sit in a repo checkout):
28
+ * every path field is validated fail-closed as a safe single segment, and every
29
+ * mutation path is re-derived from the CURRENT run's resolved root plus those
30
+ * validated segments — never from a recorded absolute path. A bad shape,
31
+ * unknown phase, root mismatch, or contradictory disk state REFUSES with no
32
+ * filesystem mutation and leaves the journal in place as evidence.
33
+ *
34
+ * Engine core: this module imports Node builtins and core helpers only — it
35
+ * never imports `cli.ts`, `add.ts`, `untar.ts`, or a hub module.
36
+ */
37
+ import { releaseFileLock } from './lock.ts';
38
+ import type { AcquireFileLockOpts, FileLockHandle } from './lock.ts';
39
+ export { archivePathViolation } from './archive.ts';
40
+ /**
41
+ * Returns `undefined` if `relPath` is a safe SINGLE-SEGMENT path, else a
42
+ * human-readable reason it must be rejected. Stricter than
43
+ * {@link archivePathViolation}: ANY separator is refused outright. That one
44
+ * rule makes `..` traversal and nested escape shapes unrepresentable before
45
+ * any `join`/`rename` ever touches the path. Used for the GitHub route's
46
+ * top-level destination segment and every journal path segment field.
47
+ * Reject-don't-normalize, like {@link archivePathViolation}.
48
+ */
49
+ export declare function lockfilePathViolation(relPath: string): string | undefined;
50
+ /**
51
+ * Returns `undefined` if `relPath` is a safe MULTI-SEGMENT path under a store
52
+ * root (the CAS object path `objects/sha256/<digest>` is three segments), else
53
+ * a human-readable reason it must be rejected. Applies
54
+ * {@link archivePathViolation} to the whole path and to EVERY segment — the
55
+ * CAS destination segment set is never trusted from disk; it is validated
56
+ * fail-closed before any join or rename.
57
+ */
58
+ export declare function multiSegmentPathViolation(relPath: string): string | undefined;
59
+ /**
60
+ * Ensure a state directory is real before a caller creates or writes below it.
61
+ * The final directory and its immediate parent are checked with `lstat`; the
62
+ * caller's existing filesystem root may contain an operator/system symlink
63
+ * (for example macOS's `/var`), which is outside the state directory boundary.
64
+ * Missing directories are created recursively and the final leaf is checked
65
+ * again before the caller proceeds.
66
+ */
67
+ export declare function ensureDirectoryPathNoSymlink(dir: string, label?: string): void;
68
+ /** Refuse a symlink or non-regular-file state leaf; an absent leaf is allowed. */
69
+ export declare function guardStateFile(path: string, label?: string): void;
70
+ /**
71
+ * Read one regular file without following a symlink during the open. The
72
+ * initial `lstat` rejects a planted link or non-file, and `O_NOFOLLOW` closes
73
+ * the replace-between-check-and-open window. An absent file returns undefined
74
+ * so callers can distinguish an empty file (which still needs parsing) from a
75
+ * never-created metadata file.
76
+ */
77
+ export declare function readRegularFileNoFollow(path: string, label?: string): Uint8Array | undefined;
78
+ /**
79
+ * Probe a directory path without following symlinks through any component.
80
+ * Missing components mean the path is absent; an existing symlink or non-dir
81
+ * component is an integrity failure. This is used for CAS object ownership and
82
+ * recovery probes, where `existsSync` would incorrectly follow links.
83
+ */
84
+ export declare function probeDirectoryPath(path: string, label?: string, trustedBoundary?: string): 'dir' | 'absent';
85
+ export interface AtomicJsonWriteOpts {
86
+ /**
87
+ * Removal op used to clean up the temp sibling when the atomic rename fails.
88
+ * Defaults to `rmSync`; injectable so a test can force the cleanup itself to
89
+ * throw and prove the ORIGINAL rename error still surfaces.
90
+ */
91
+ rm?: (path: string, opts: {
92
+ force: true;
93
+ }) => void;
94
+ }
95
+ /**
96
+ * Serialize `value` as pretty JSON into a sibling temp file, then `renameSync`
97
+ * over `path` — one atomic tmp+rename discipline shared by the lockfile, the
98
+ * crash-recovery journal, and the workflow-store index. A crash or a
99
+ * concurrent reader never sees a half-written file (rename is atomic within a
100
+ * directory).
101
+ *
102
+ * If the final `renameSync` throws (EACCES, EISDIR on `path`, a full disk),
103
+ * the temp sibling is removed on a best-effort basis before the error
104
+ * propagates so a failed write cannot leak a `<path>.tmp.<pid>` file. The
105
+ * original rename error is surfaced unchanged — never swallowed, and never
106
+ * masked by a failure of that cleanup removal (if the removal itself throws,
107
+ * that error is swallowed and the tmp sibling may remain in that double fault).
108
+ */
109
+ export declare function writeJsonAtomic(path: string, value: unknown, opts?: AtomicJsonWriteOpts): void;
110
+ /** The staging root under a root dir where installs are assembled + validated. */
111
+ export declare const STAGING_DIRNAME = ".owenloop-staging";
112
+ /**
113
+ * Recursively remove `dir` WITHOUT requiring write permission inside it.
114
+ * Content-addressed objects are committed read-only + non-writable (files
115
+ * 0o444, dirs 0o555) — hardening is defense in depth, and it means a plain
116
+ * `rmSync` (which unlinks each entry through its PARENT dir's write mode)
117
+ * dies with EACCES as soon as a swapped-out backup or staging debris holds a
118
+ * hardened object. Each directory restores its own write+search modes BEFORE
119
+ * its entries are unlinked, so no level ever removes through a 0o555 dir —
120
+ * and a STORED object is never made transiently writable, only its doomed
121
+ * staging/undo/backup copy. Absent ⇒ no-op (idempotent). Every throw
122
+ * propagates: a half-removed staging root is the caller's error, never a
123
+ * silent leak.
124
+ */
125
+ export declare function rmRecursiveForce(dir: string): void;
126
+ /**
127
+ * Write `files` (relative path → bytes) into `targetDir` (a staging dir), NOT
128
+ * the final install destination. Unlike a direct install, this never clears a
129
+ * live folder: the caller stages here, validates, then `commitInstall`s with an
130
+ * atomic rename, so a failure mid-write can only ever corrupt throwaway staging
131
+ * content. Returns the sorted list of relative paths written.
132
+ */
133
+ export declare function stageFiles(targetDir: string, files: Map<string, Uint8Array>): string[];
134
+ /**
135
+ * Thrown by `commitInstall` when the atomic swap fails AND the rollback of it
136
+ * fails too — a near-impossible same-filesystem double-fault. Carries the path
137
+ * where the previous version was left so the caller can preserve it (its
138
+ * `preservedAt` sits under the staging root, which the caller would otherwise
139
+ * clean up as debris). A distinguishable type so the caller can tell this
140
+ * "must-preserve" double-fault apart from an ordinary swap failure.
141
+ */
142
+ export declare class RollbackFailedError extends Error {
143
+ readonly preservedAt: string;
144
+ constructor(message: string, preservedAt: string);
145
+ }
146
+ /**
147
+ * A handle to a committed-but-not-yet-finalized install, returned by
148
+ * `commitInstall`. The install directory already holds the NEW content, but the
149
+ * displaced previous install is RETAINED under the staging root — not yet
150
+ * discarded — so the caller can still roll the directory state back if a later
151
+ * step (the metadata write) fails. The caller MUST eventually either
152
+ * `finalizeInstallCommit` (discard the retained dirs) or `rollbackInstallCommit`
153
+ * (restore the previous state). All retained/undo paths derive from
154
+ * `stagingDir`, so they live under `<root>/.owenloop-staging/` — same
155
+ * filesystem (renames stay atomic), and the staging-root cleanup covers them.
156
+ */
157
+ export interface InstallCommitHandle {
158
+ /** `root/<destRelPath>` — now holding the NEW content. */
159
+ dest: string;
160
+ /** The destination's path relative to the root (for diagnostics/journals). */
161
+ destRelPath: string;
162
+ /** `${stagingDir}-old` — the displaced previous dest, if one existed. */
163
+ backupDir?: string;
164
+ /** `${stagingDir}-undo` — where a rollback parks the new content before restoring. */
165
+ undoDir: string;
166
+ }
167
+ /** Deterministic synchronization hook for transaction crash/concurrency tests. */
168
+ export interface CommitInstallOptions {
169
+ /** Runs after destination → backup and before staging → destination. */
170
+ afterBackupRename?: () => void;
171
+ }
172
+ /**
173
+ * Atomically swap a validated `stagingDir` into place at `root/<destRelPath>`.
174
+ * Both live on the same filesystem by construction (staging is under `root`),
175
+ * so the renames are atomic and `EXDEV` is impossible. `destRelPath` is a
176
+ * MULTI-SEGMENT path (a top-level folder for the GitHub route,
177
+ * `objects/sha256/<digest>` for the CAS route) and is re-validated HERE, at
178
+ * the mutation site — defense-in-depth alongside the callers' checks.
179
+ *
180
+ * Two-phase commit: unlike a one-shot swap, this does NOT delete the displaced
181
+ * previous install on success — it returns an {@link InstallCommitHandle} whose
182
+ * `backupDir` still holds it. The caller must then either
183
+ * {@link finalizeInstallCommit} (discard the backup, making the swap permanent)
184
+ * once its follow-on work — the metadata write — has durably succeeded, or
185
+ * {@link rollbackInstallCommit} to restore the previous directory state if that
186
+ * work fails. This is what lets "commit the directory + write the metadata" be
187
+ * one recoverable operation.
188
+ *
189
+ * Sequence: back up any existing install (rename dest → `<stagingDir>-old`) —
190
+ * if that fails nothing has changed; rename staging → dest; on failure rename
191
+ * the backup back (throwing {@link RollbackFailedError} if even that fails, so
192
+ * the caller can preserve the named copy).
193
+ */
194
+ export declare function commitInstall(root: string, destRelPath: string, stagingDir: string, options?: CommitInstallOptions): InstallCommitHandle;
195
+ /**
196
+ * Make the commit permanent: discard the retained previous install. Call ONLY
197
+ * after the follow-on metadata write has durably succeeded — this is the point
198
+ * of no return.
199
+ */
200
+ export declare function finalizeInstallCommit(handle: InstallCommitHandle): void;
201
+ /**
202
+ * Rename a real directory while preserving its exact 0o7777 root mode. macOS
203
+ * requires owner-write on a non-writable directory for rename even though the
204
+ * source and destination parents are writable. The optional `persistedMode`
205
+ * comes from durable transaction identity evidence written before the first
206
+ * chmod; recovery passes that value instead of inferring an original mode from
207
+ * a path that may still carry the temporary owner-write bit after a crash.
208
+ */
209
+ export declare function renameDirRestoringWrite(src: string, dst: string, persistedMode?: number): void;
210
+ /** Durable transition hooks for callers whose rollback needs a crash journal. */
211
+ export interface RollbackInstallCommitOptions {
212
+ /** Runs before the first rollback rename. A throw leaves the committed swap untouched. */
213
+ beforeRollback?: () => void;
214
+ /** Runs after destination → undo and before backup → destination. */
215
+ afterDestinationParked?: () => void;
216
+ /** Runs after backup → destination. Only called when a retained backup exists. */
217
+ afterPriorRestored?: () => void;
218
+ /** Remove the parked replacement after the prior destination is restored. Default: false. */
219
+ cleanupUndo?: boolean;
220
+ /** Runs after the parked replacement has been removed. */
221
+ afterUndoCleanup?: () => void;
222
+ }
223
+ /**
224
+ * Undo a `commitInstall`, restoring the pre-commit directory state. Order
225
+ * matters: (1) durably record rollback intent when the caller supplies a
226
+ * `beforeRollback` hook; (2) park the new content out of `dest` (rename dest →
227
+ * undoDir) — for a fresh install, this alone restores "nothing installed";
228
+ * (3) if a previous install was displaced, rename its backup back over `dest`;
229
+ * (4) optionally delete the parked replacement after the prior object is back.
230
+ *
231
+ * Every transition hook runs AFTER the transition named by the hook. A hook
232
+ * failure stops the state machine immediately and leaves the previous durable
233
+ * journal phase plus the newly observable filesystem state for recovery. The
234
+ * default options retain the historical generic behavior: no journal hooks and
235
+ * the undo directory left for the caller's staging-root cleanup.
236
+ *
237
+ * Renames go through {@link renameDirRestoringWrite}: the CAS route hardens
238
+ * objects at their committed location, so `dest` may already be non-writable
239
+ * when a late rollback (the index write failing) runs. Any throw propagates.
240
+ */
241
+ export declare function rollbackInstallCommit(handle: InstallCommitHandle, options?: RollbackInstallCommitOptions): void;
242
+ /** The install lock handle — the generic `FileLockHandle` from `lock.ts`. */
243
+ export type InstallLockHandle = FileLockHandle;
244
+ /** The install lock acquire options — the generic `AcquireFileLockOpts` from `lock.ts`. */
245
+ export type AcquireLockOpts = AcquireFileLockOpts;
246
+ /**
247
+ * Acquire the install lock at `lockPath`. A 1-line adapter over the generic
248
+ * `acquireFileLock`, pinning `label` so the timeout message reads "another
249
+ * owenloop add is in progress …" byte-for-byte as before. Always pair with
250
+ * `releaseInstallLock` in a `finally`.
251
+ */
252
+ export declare function acquireInstallLock(lockPath: string, opts?: AcquireLockOpts): Promise<InstallLockHandle>;
253
+ /** Release a lock acquired by `acquireInstallLock` — the generic `releaseFileLock`. */
254
+ export declare const releaseInstallLock: typeof releaseFileLock;
255
+ /** The crash-recovery journal filename (a sibling of the lock + metadata file). */
256
+ export declare const ADD_JOURNAL_FILENAME = "add.journal";
257
+ /**
258
+ * The two base durable phases shared by v1 and ordinary v2 transactions. Absent
259
+ * (no file) is the third, happy state. V2 same-digest repair extends these phases
260
+ * with the substates in {@link InstallJournalV2Phase}; ordinary transactions stay
261
+ * deliberately coarse because directory existence recovers their progress.
262
+ *
263
+ * - `applying`: written after staging+validation succeed, immediately before
264
+ * `commitInstall`. The metadata write (the durable commit point) has NOT yet
265
+ * happened, so recovery rolls BACK — unless the metadata turns out to already
266
+ * match (a crash in the tiny write→rewrite window), in which case it rolls
267
+ * forward.
268
+ * - `finalizing`: written immediately after the metadata write succeeds, before
269
+ * `finalizeInstallCommit`. The commit point has passed, so recovery rolls
270
+ * FORWARD (finishes discarding the retained backup).
271
+ */
272
+ export type AddJournalPhase = 'applying' | 'finalizing';
273
+ /**
274
+ * Durable v2 repair phases. Replacement phases roll a valid staged object
275
+ * forward. Rollback phases restore the retained prior directory through an
276
+ * explicit state machine: intent, replacement parked, prior restored, debris
277
+ * removed. Each phase is written only after the named transition has completed.
278
+ * Readers wait while the digest destination may still move; `finalizing`,
279
+ * `rollback-prior-restored`, and `rollback-complete` are stable because no later
280
+ * transition renames the digest destination.
281
+ */
282
+ export type InstallJournalV2Phase = AddJournalPhase | 'replacement-swapped' | 'replacement-hardened' | 'replacement-verified' | 'rollback-started' | 'rollback-replacement-parked' | 'rollback-prior-restored' | 'rollback-complete';
283
+ /** The v2 transaction kind; recorded so same-digest repair is never mistaken for dedupe. */
284
+ export type InstallJournalV2Operation = 'install' | 'dedupe' | 'repair';
285
+ /**
286
+ * One v1 (GitHub-route) crash-recovery journal record. `folder`, `stagingId`,
287
+ * and `oldNamePath` are single on-disk path segments (each
288
+ * {@link lockfilePathViolation}-checked on read); `defsDir` is compared for
289
+ * equality ONLY and is never joined into a mutation path; `ref`/`startedAt`
290
+ * are diagnostics. These invariants are NOT trusted from disk —
291
+ * {@link validateAddJournal} enforces every one, fail-closed.
292
+ */
293
+ export interface AddJournal {
294
+ version: 1;
295
+ phase: AddJournalPhase;
296
+ /** Ledger key of the source being installed — for the ledger-match check. */
297
+ source: string;
298
+ /** 40-char hex commit sha being installed — for the ledger-match check. */
299
+ sha: string;
300
+ /** Install folder segment (`dest = join(defsDir, folder)`). Single segment. */
301
+ folder: string;
302
+ /** Basename of this run's staging dir (`stg_<hex>`). Single segment. */
303
+ stagingId: string;
304
+ /** Did `dest` exist when the journal was written (⇒ a backup dir will exist)? */
305
+ hadDest: boolean;
306
+ /** Set only for an old-name (`<owner>-<repo>`) migration. Single segment. */
307
+ oldNamePath?: string;
308
+ /** Resolved defs dir at journal-write time — equality-checked, never joined. */
309
+ defsDir: string;
310
+ /** The `@ref` this install pinned — diagnostics only. */
311
+ ref: string;
312
+ /** Journal-write epoch ms — diagnostics only. */
313
+ startedAt: number;
314
+ }
315
+ /**
316
+ * One v2 (route-neutral) crash-recovery journal record. The destination is a
317
+ * validated segment list under the root (a single segment for a top-level
318
+ * folder, three for `objects/sha256/<digest>`); `metadataHash` is the SHA-256
319
+ * of the exact post-install metadata bytes, and the commit-point decision is
320
+ * `hash(current metadata bytes) === metadataHash` — recovery never assumes a
321
+ * route-specific metadata schema. `root` is equality-checked only, never
322
+ * joined. `label`/`startedAt` are diagnostics. Validated fail-closed by
323
+ * {@link validateInstallJournalV2}; never trusted from disk.
324
+ */
325
+ export interface InstallJournalV2 {
326
+ version: 2;
327
+ phase: InstallJournalV2Phase;
328
+ /** Explicitly separates a same-digest repair from a no-swap dedupe. */
329
+ operation?: InstallJournalV2Operation;
330
+ /** Destination path segments relative to the root (validated, never joined raw). */
331
+ destSegments: string[];
332
+ /** Basename of this run's staging dir (`stg_<hex>`). Single segment. */
333
+ stagingId: string;
334
+ /** Did `dest` exist when the journal was written (⇒ a backup dir will exist)? */
335
+ hadDest: boolean;
336
+ /** Resolved root at journal-write time — equality-checked, never joined. */
337
+ root: string;
338
+ /** SHA-256 hex of the exact post-install metadata bytes (the commit-point test). */
339
+ metadataHash: string;
340
+ /** Free-form route label (e.g. the CAS coordinate) — diagnostics only. */
341
+ label?: string;
342
+ /** Journal-write epoch ms — diagnostics only. */
343
+ startedAt?: number;
344
+ /** External transaction marker for a fresh install or identity-backed repair. */
345
+ recoveryMarkerId?: string;
346
+ /** Exact replacement-root mode captured durably before the first rollback rename. */
347
+ rollbackReplacementMode?: number;
348
+ }
349
+ /** A journal of either version, as read from disk. */
350
+ export type AnyInstallJournal = AddJournal | InstallJournalV2;
351
+ /**
352
+ * Structurally validate a parsed v1 `add.journal`, fail-closed — the trust
353
+ * boundary for v1 journals, mirroring the lockfile's validator. A
354
+ * parseable-but-invalid journal is a hard error naming the file and the manual
355
+ * remedy; recovery NEVER acts on a field that has not passed through here.
356
+ * Every path field must be a safe single segment so a crafted journal cannot
357
+ * represent traversal before any `join`/`rename`. Unknown extra keys are
358
+ * tolerated (forward compatibility, same as the lockfile). `ref`/`startedAt`
359
+ * are diagnostics: validated for type when present, but not required. `path`
360
+ * appears only in error messages.
361
+ */
362
+ export declare function validateAddJournal(parsed: unknown, path: string): AddJournal;
363
+ /**
364
+ * Structurally validate a parsed v2 journal, fail-closed — the trust boundary
365
+ * for route-neutral journals, same discipline as {@link validateAddJournal}:
366
+ * hard error naming the file on any bad shape, unknown extra keys tolerated,
367
+ * path fields validated as safe single segments, `root` equality-only,
368
+ * `metadataHash` a strict lowercase 64-hex value (never normalized).
369
+ */
370
+ export declare function validateInstallJournalV2(parsed: unknown, path: string): InstallJournalV2;
371
+ /**
372
+ * Validate a parsed journal of EITHER version (fail-closed, per-version).
373
+ * `readAddJournal` dispatches here on the raw `version` field, so a v2 journal
374
+ * is validated by the v2 rules and a v1 journal by the v1 rules — an older
375
+ * release's journal and a CAS route's journal both recover.
376
+ */
377
+ export declare function validateAnyInstallJournal(parsed: unknown, path: string): AnyInstallJournal;
378
+ export interface RecoveryDirectoryIdentity {
379
+ /** Decimal strings avoid platform-size loss when filesystem ids exceed 32 bits. */
380
+ dev: string;
381
+ ino: string;
382
+ /** Exact 0o7777 mode, persisted before any transaction rename chmod. */
383
+ mode?: number;
384
+ }
385
+ export interface RecoveryMarkerRecord {
386
+ version: 1;
387
+ root: string;
388
+ /** Exact store-root identity; absent only on markers written by older releases. */
389
+ rootIdentity?: RecoveryDirectoryIdentity;
390
+ destSegments: string[];
391
+ stagingId: string;
392
+ hadDest: boolean;
393
+ /** Absent only on legacy fresh-install markers. */
394
+ operation?: 'install' | 'repair';
395
+ /** Root directory identity of the staged replacement, captured before any rename. */
396
+ replacementIdentity?: RecoveryDirectoryIdentity;
397
+ /** Root directory identity of the retained prior object, captured after dest → backup. */
398
+ priorIdentity?: RecoveryDirectoryIdentity;
399
+ }
400
+ export interface RecoveryMarkerHandle {
401
+ id: string;
402
+ path: string;
403
+ markerDir: string;
404
+ record: RecoveryMarkerRecord;
405
+ }
406
+ /** Derive the external marker directory from the caller's injected home. */
407
+ export declare function defaultRecoveryMarkerDir(home: string): string;
408
+ export declare function createRecoveryMarker(input: {
409
+ root: string;
410
+ destSegments: string[];
411
+ stagingId: string;
412
+ markerDir: string;
413
+ /** Omit for the legacy fresh-install marker shape. */
414
+ operation?: 'install' | 'repair';
415
+ /** Required for repair; records the staged replacement before any rename. */
416
+ replacementDir?: string;
417
+ }): RecoveryMarkerHandle;
418
+ /**
419
+ * Add the retained prior-directory identity after destination → backup. The
420
+ * marker is outside the store root, so a repository-controlled journal cannot
421
+ * forge which inode is the prior object or which inode is the replacement.
422
+ */
423
+ export declare function recordRecoveryMarkerPriorIdentity(handle: RecoveryMarkerHandle, priorDir: string): RecoveryMarkerHandle;
424
+ export declare function readRecoveryMarker(id: string, markerDir: string): RecoveryMarkerRecord | null;
425
+ export declare function removeRecoveryMarker(handle: RecoveryMarkerHandle | {
426
+ id: string;
427
+ markerDir: string;
428
+ }): void;
429
+ /**
430
+ * Read the crash-recovery journal (either version). Absent ⇒ `null` (the happy
431
+ * path — no interrupted install to recover). Present-but-unparseable ⇒ a hard
432
+ * error; present-but-schema-invalid ⇒ a hard error via
433
+ * {@link validateAnyInstallJournal}. Never silently ignores a malformed journal
434
+ * (that would let a crafted file quietly disable recovery) and never trusts it
435
+ * for filesystem paths.
436
+ */
437
+ export declare function readAddJournal(path: string): AnyInstallJournal | null;
438
+ /** Write a journal record atomically (tmp+rename), same discipline as the metadata file. */
439
+ export declare function writeAddJournal(path: string, journal: AnyInstallJournal, opts?: AtomicJsonWriteOpts): void;
440
+ /** Remove the journal (force: absence is not an error — clean-completion / idempotent). */
441
+ export declare function removeAddJournal(path: string): void;
442
+ /** SHA-256 hex of raw bytes — the v2 journal's commit-point test primitive. */
443
+ export declare function sha256Hex(data: Uint8Array): string;
444
+ /** Serialize metadata canonically before hashing/writing (same bytes both times). */
445
+ export declare function canonicalJsonBytes(value: unknown): Uint8Array;
446
+ /**
447
+ * v1-only: read + validate the current ledger (fail-closed) and return a
448
+ * lookup over its entries. Required whenever a v1 journal may exist (the
449
+ * GitHub route always supplies it). A v2-only caller may omit it — recovery
450
+ * then refuses a v1 journal instead of guessing. The lookup feeds both the
451
+ * v1 commit-point test and the case-(c) old-name migration corroboration.
452
+ */
453
+ export type LedgerLookup = (source: string) => {
454
+ sha: string;
455
+ path: string;
456
+ } | undefined;
457
+ export interface V2ReplacementRecoveryActions {
458
+ /** Idempotently harden the replacement object recursively. */
459
+ harden(objectDir: string): void;
460
+ /** Verify canonical identity and exact hardened store modes. */
461
+ verify(objectDir: string, digest: string): void;
462
+ }
463
+ export interface RecoverInterruptedInstallArgs {
464
+ /** The CURRENT run's resolved root — every mutation path derives from it. */
465
+ defsDir: string;
466
+ /** Path to the crash-recovery journal. */
467
+ journalPath: string;
468
+ /** Metadata path (v1 `installed.json`, v2 `index.json`) used by ordinary commit-point checks. */
469
+ lockfilePath: string;
470
+ /** Directory holding external install/repair transaction markers. */
471
+ recoveryMarkerDir?: string;
472
+ /** CAS repair actions required to resume a swapped v2 replacement safely. */
473
+ v2Replacement?: V2ReplacementRecoveryActions;
474
+ /** See {@link LedgerLookup}. */
475
+ readLedger?: () => LedgerLookup;
476
+ }
477
+ /**
478
+ * What `recoverInterruptedInstall` DID, for callers (the offline `add --recover`
479
+ * entry point) that report the result to the user. A refusal is NOT an outcome —
480
+ * it throws. `'rolled-back'` collapses the roll-back table's terminal arms,
481
+ * including the touch-nothing / already-consistent ones (distinguishing
482
+ * "restored" from "was already consistent" per arm would thread state through
483
+ * the decision table for message cosmetics only).
484
+ */
485
+ export type RecoveryOutcome = 'no-journal' | 'rolled-forward' | 'rolled-back';
486
+ /**
487
+ * Bring an interrupted install back to a consistent (tree ⇔ metadata) state,
488
+ * then remove the journal. Called by install dispatchers under the root's
489
+ * install lock, BEFORE the stale-staging cleanup (the backups a rollback needs
490
+ * live under the staging root). With no journal, recovery first reconciles only
491
+ * same-root external markers whose inode evidence and untouched pre-journal
492
+ * topology prove a crash between marker creation and the journal write, then
493
+ * returns `no-journal`. Reads BOTH journal versions and dispatches on `version`.
494
+ *
495
+ * Ordinary v1/v2 transactions use the durable metadata write as the commit
496
+ * point. Same-digest v2 repair cannot: the index may already match before the
497
+ * replacement starts, so explicit replacement phases control recovery.
498
+ * Concretely:
499
+ *
500
+ * 1. `finalizing` ⇒ roll forward. V2 first re-verifies the exact destination's
501
+ * canonical bytes and hardened modes; only then may recovery discard the
502
+ * retained backup and staging root. V1 has no CAS verifier and performs the
503
+ * original cleanup behavior.
504
+ * 2. V2 repair in `applying`, `replacement-swapped`,
505
+ * `replacement-hardened`, or `replacement-verified` ⇒ use an exhaustive
506
+ * phase/topology table. Every accepted arm requires the matching external
507
+ * marker and exact directory identities before mutation. Proven pre-swap or
508
+ * interrupted legacy rollback states first enter `rollback-started`; the
509
+ * durable rollback phases perform every rename and cleanup. A replacement at
510
+ * destination with the retained prior backup resumes hardening/verification
511
+ * and advances to `finalizing`. Every other combination refuses unchanged.
512
+ * 3. Ordinary `applying` + the commit-point test passes (v1: ledger records
513
+ * this exact source@sha/path; v2: `hash(current metadata bytes) ===
514
+ * metadataHash`) ⇒ the commit MAY have landed, but the test alone does not
515
+ * prove it. Destination present means the swap completed and recovery rolls
516
+ * forward. Destination absent means recovery is inside the destination →
517
+ * backup / staging → destination window, so recovery restores the backup
518
+ * instead of deleting the only copy.
519
+ * 4. Ordinary `applying`, commit point not reached ⇒ roll back through the
520
+ * guarded, idempotent decision table below (mirroring
521
+ * `rollbackInstallCommit`'s order) — EXCEPT the v1 case-(c) fresh-install
522
+ * discard, which acts on the journal alone and therefore requires ledger
523
+ * corroboration of an interrupted old-name migration. V2 has no
524
+ * journal-alone destructive arm, so a forged v2 journal cannot delete an
525
+ * unrelated destination.
526
+ *
527
+ * Crash-safety of recovery itself: the journal is removed LAST, after all
528
+ * restore/discard renames, and every step is a single atomic rename guarded by
529
+ * existence probes — so a crash mid-recovery leaves the journal intact and a
530
+ * strict subset of the work done; the next attempt re-derives state from disk
531
+ * and continues. Running it twice is a no-op the second time.
532
+ *
533
+ * Any refusal (invalid journal, root mismatch, symlink where a directory is
534
+ * expected, contradictory disk state) throws WITHOUT mutating anything and
535
+ * leaves the journal in place; callers must preserve the staging root on
536
+ * refusal so the `finally` cannot destroy the backups a later attempt needs.
537
+ */
538
+ export declare function recoverInterruptedInstall(args: RecoverInterruptedInstallArgs): RecoveryOutcome;