owenloop 0.5.0 → 0.5.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 (229) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +144 -35
  3. package/bin/owenloop.mjs +49 -1
  4. package/dist/packages/work/src/agent/brief.d.ts +29 -4
  5. package/dist/packages/work/src/agent/brief.js +49 -4
  6. package/dist/packages/work/src/agent/capability-model.d.ts +123 -0
  7. package/dist/packages/work/src/agent/capability-model.js +148 -0
  8. package/dist/packages/work/src/agent/loop.d.ts +56 -7
  9. package/dist/packages/work/src/agent/loop.js +166 -9
  10. package/dist/packages/work/src/bundle/cache.d.ts +7 -5
  11. package/dist/packages/work/src/bundle/cache.js +20 -6
  12. package/dist/packages/work/src/bundle/fetch.d.ts +7 -5
  13. package/dist/packages/work/src/bundle/fetch.js +27 -7
  14. package/dist/packages/work/src/bundle/types.d.ts +8 -4
  15. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  16. package/dist/packages/work/src/consumed-verifier.js +205 -0
  17. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  18. package/dist/packages/work/src/exec/instructions.js +323 -0
  19. package/dist/packages/work/src/exec/loop.d.ts +29 -1
  20. package/dist/packages/work/src/exec/loop.js +313 -35
  21. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  22. package/dist/packages/work/src/exec/payload.js +54 -0
  23. package/dist/packages/work/src/exec/receipt.d.ts +9 -6
  24. package/dist/packages/work/src/exec/receipt.js +12 -1
  25. package/dist/packages/work/src/exec/runner.d.ts +7 -1
  26. package/dist/packages/work/src/exec/runner.js +84 -3
  27. package/dist/packages/work/src/harness/child-env.js +7 -0
  28. package/dist/packages/work/src/harness/claude.d.ts +20 -8
  29. package/dist/packages/work/src/harness/claude.js +260 -58
  30. package/dist/packages/work/src/harness/codex.d.ts +5 -4
  31. package/dist/packages/work/src/harness/codex.js +169 -41
  32. package/dist/packages/work/src/harness/contract.d.ts +36 -11
  33. package/dist/packages/work/src/harness/fake.js +1 -0
  34. package/dist/packages/work/src/harness/jsonrpc-stdio.js +7 -0
  35. package/dist/packages/work/src/harness/permissions.d.ts +16 -3
  36. package/dist/packages/work/src/harness/permissions.js +102 -13
  37. package/dist/packages/work/src/harness/session-store.d.ts +30 -10
  38. package/dist/packages/work/src/harness/session-store.js +317 -89
  39. package/dist/packages/work/src/hold/mcp.d.ts +25 -5
  40. package/dist/packages/work/src/hold/mcp.js +134 -12
  41. package/dist/packages/work/src/hub/client.d.ts +8 -1
  42. package/dist/packages/work/src/hub/client.js +15 -1
  43. package/dist/packages/work/src/hub/types.d.ts +137 -33
  44. package/dist/packages/work/src/hub/types.js +8 -10
  45. package/dist/packages/work/src/mcp/server.js +1 -1
  46. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  47. package/dist/packages/work/src/owenloop-bin.js +18 -0
  48. package/dist/packages/work/src/roles/agent-run.d.ts +12 -6
  49. package/dist/packages/work/src/roles/agent-run.js +115 -34
  50. package/dist/packages/work/src/roles/exec.d.ts +8 -0
  51. package/dist/packages/work/src/roles/exec.js +27 -2
  52. package/dist/packages/work/src/roles/hold.d.ts +6 -0
  53. package/dist/packages/work/src/roles/hold.js +83 -13
  54. package/dist/packages/work/src/roles/lint.d.ts +3 -4
  55. package/dist/packages/work/src/roles/lint.js +41 -7
  56. package/dist/packages/work/src/roles/settings.js +19 -2
  57. package/dist/packages/work/src/roles/shift.d.ts +1 -0
  58. package/dist/packages/work/src/roles/shift.js +36 -2
  59. package/dist/packages/work/src/settings/settings.d.ts +70 -1
  60. package/dist/packages/work/src/settings/settings.js +90 -4
  61. package/dist/packages/work/src/shift/logretention.d.ts +253 -0
  62. package/dist/packages/work/src/shift/logretention.js +407 -0
  63. package/dist/packages/work/src/shift/logsink.d.ts +14 -0
  64. package/dist/packages/work/src/shift/logsink.js +98 -0
  65. package/dist/packages/work/src/shift/loop.d.ts +32 -4
  66. package/dist/packages/work/src/shift/loop.js +687 -166
  67. package/dist/packages/work/src/shift/protocol.d.ts +128 -1
  68. package/dist/packages/work/src/shift/protocol.js +14 -0
  69. package/dist/packages/work/src/shift/runtime.d.ts +16 -0
  70. package/dist/packages/work/src/shift/runtime.js +291 -5
  71. package/dist/packages/work/src/shift/server.d.ts +13 -0
  72. package/dist/packages/work/src/shift/server.js +61 -36
  73. package/dist/packages/work/src/shift/spawn.d.ts +115 -19
  74. package/dist/packages/work/src/shift/spawn.js +234 -30
  75. package/dist/packages/work/src/shift/state.d.ts +76 -49
  76. package/dist/packages/work/src/shift/state.js +350 -103
  77. package/dist/packages/work/src/shift/truncate.d.ts +35 -0
  78. package/dist/packages/work/src/shift/truncate.js +73 -0
  79. package/dist/packages/work/src/submit-proof.d.ts +61 -0
  80. package/dist/packages/work/src/submit-proof.js +119 -0
  81. package/dist/packages/work/src/submit-value.d.ts +48 -0
  82. package/dist/packages/work/src/submit-value.js +118 -0
  83. package/dist/packages/work/src/usage.d.ts +1 -1
  84. package/dist/packages/work/src/usage.js +11 -0
  85. package/dist/src/add.d.ts +64 -259
  86. package/dist/src/add.js +81 -615
  87. package/dist/src/archive.d.ts +97 -0
  88. package/dist/src/archive.js +591 -0
  89. package/dist/src/bundle/index.d.ts +64 -0
  90. package/dist/src/bundle/index.js +508 -0
  91. package/dist/src/bundle/manifest.d.ts +50 -0
  92. package/dist/src/bundle/manifest.js +435 -0
  93. package/dist/src/bundle/runtime.d.ts +26 -0
  94. package/dist/src/bundle/runtime.js +64 -0
  95. package/dist/src/bundle/tar.d.ts +62 -0
  96. package/dist/src/bundle/tar.js +238 -0
  97. package/dist/src/bundle/types.d.ts +105 -0
  98. package/dist/src/bundle/types.js +21 -0
  99. package/dist/src/capabilities.d.ts +93 -0
  100. package/dist/src/capabilities.js +101 -0
  101. package/dist/src/cli.d.ts +90 -20
  102. package/dist/src/cli.js +2421 -374
  103. package/dist/src/credentials.d.ts +4 -3
  104. package/dist/src/credentials.js +21 -19
  105. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  106. package/dist/src/crypto/allowed-signers.js +307 -0
  107. package/dist/src/crypto/canonical.d.ts +8 -0
  108. package/dist/src/crypto/canonical.js +92 -0
  109. package/dist/src/crypto/chain.d.ts +65 -0
  110. package/dist/src/crypto/chain.js +377 -0
  111. package/dist/src/crypto/dsse.d.ts +209 -0
  112. package/dist/src/crypto/dsse.js +282 -0
  113. package/dist/src/crypto/enrollment.d.ts +78 -0
  114. package/dist/src/crypto/enrollment.js +186 -0
  115. package/dist/src/crypto/index.d.ts +48 -0
  116. package/dist/src/crypto/index.js +44 -0
  117. package/dist/src/crypto/keys.d.ts +258 -0
  118. package/dist/src/crypto/keys.js +908 -0
  119. package/dist/src/crypto/org-root.d.ts +33 -0
  120. package/dist/src/crypto/org-root.js +78 -0
  121. package/dist/src/crypto/origin-rules.d.ts +56 -0
  122. package/dist/src/crypto/origin-rules.js +143 -0
  123. package/dist/src/crypto/policy-floor.d.ts +98 -0
  124. package/dist/src/crypto/policy-floor.js +353 -0
  125. package/dist/src/crypto/records.d.ts +319 -0
  126. package/dist/src/crypto/records.js +168 -0
  127. package/dist/src/crypto/scope.d.ts +49 -0
  128. package/dist/src/crypto/scope.js +83 -0
  129. package/dist/src/crypto/ssh.d.ts +171 -0
  130. package/dist/src/crypto/ssh.js +396 -0
  131. package/dist/src/crypto/submission.d.ts +33 -0
  132. package/dist/src/crypto/submission.js +47 -0
  133. package/dist/src/crypto/trust-roots.d.ts +29 -0
  134. package/dist/src/crypto/trust-roots.js +39 -0
  135. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  136. package/dist/src/crypto/verify-consumed.js +259 -0
  137. package/dist/src/crypto/verify-origin.d.ts +50 -0
  138. package/dist/src/crypto/verify-origin.js +151 -0
  139. package/dist/src/crypto/verify-publication.d.ts +60 -0
  140. package/dist/src/crypto/verify-publication.js +150 -0
  141. package/dist/src/defs.d.ts +24 -1
  142. package/dist/src/defs.js +335 -27
  143. package/dist/src/engine.d.ts +211 -6
  144. package/dist/src/engine.js +459 -59
  145. package/dist/src/factory.d.ts +16 -0
  146. package/dist/src/factory.js +16 -4
  147. package/dist/src/global-config.d.ts +59 -0
  148. package/dist/src/global-config.js +84 -0
  149. package/dist/src/hub.d.ts +102 -32
  150. package/dist/src/hub.js +147 -58
  151. package/dist/src/index.d.ts +19 -2
  152. package/dist/src/index.js +23 -2
  153. package/dist/src/install.d.ts +538 -0
  154. package/dist/src/install.js +1981 -0
  155. package/dist/src/lock.d.ts +15 -57
  156. package/dist/src/lock.js +251 -143
  157. package/dist/src/mcp/serve.d.ts +46 -22
  158. package/dist/src/mcp/serve.js +174 -44
  159. package/dist/src/mcp/server.js +12 -1
  160. package/dist/src/model.d.ts +51 -0
  161. package/dist/src/model.js +157 -1
  162. package/dist/src/order-resolver.d.ts +184 -0
  163. package/dist/src/order-resolver.js +252 -0
  164. package/dist/src/package-version.d.ts +10 -0
  165. package/dist/src/package-version.js +42 -0
  166. package/dist/src/paths.d.ts +14 -1
  167. package/dist/src/paths.js +18 -0
  168. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  169. package/dist/src/schemas/index.d.ts +1433 -0
  170. package/dist/src/schemas/index.js +31 -0
  171. package/dist/src/schemas/order.v1.schema.json +120 -0
  172. package/dist/src/schemas/origin.v1.schema.json +68 -0
  173. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  174. package/dist/src/schemas/publication.v1.schema.json +31 -0
  175. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  176. package/dist/src/schemas/submission.v1.schema.json +61 -0
  177. package/dist/src/store/def-source.d.ts +52 -0
  178. package/dist/src/store/def-source.js +335 -0
  179. package/dist/src/store/index-file.d.ts +69 -0
  180. package/dist/src/store/index-file.js +151 -0
  181. package/dist/src/store/index.d.ts +27 -0
  182. package/dist/src/store/index.js +22 -0
  183. package/dist/src/store/ingestor.d.ts +43 -0
  184. package/dist/src/store/ingestor.js +211 -0
  185. package/dist/src/store/install.d.ts +228 -0
  186. package/dist/src/store/install.js +555 -0
  187. package/dist/src/store/instruction-source.d.ts +49 -0
  188. package/dist/src/store/instruction-source.js +298 -0
  189. package/dist/src/store/origin-evidence.d.ts +21 -0
  190. package/dist/src/store/origin-evidence.js +66 -0
  191. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  192. package/dist/src/store/pre-commit-verifier.js +418 -0
  193. package/dist/src/store/resolve.d.ts +138 -0
  194. package/dist/src/store/resolve.js +363 -0
  195. package/dist/src/store/types.d.ts +288 -0
  196. package/dist/src/store/types.js +356 -0
  197. package/dist/src/store.d.ts +33 -1
  198. package/dist/src/store.js +57 -4
  199. package/dist/src/types.d.ts +146 -12
  200. package/dist/src/untar.d.ts +8 -23
  201. package/dist/src/untar.js +10 -136
  202. package/docs/agent-runner.md +86 -0
  203. package/docs/authoring.md +64 -6
  204. package/docs/bundles.md +350 -0
  205. package/docs/cli.md +1298 -106
  206. package/docs/crypto.md +832 -0
  207. package/docs/design.md +342 -20
  208. package/docs/embedding.md +132 -25
  209. package/docs/shift-logs.md +642 -0
  210. package/docs/wire-contracts.md +395 -0
  211. package/package.json +6 -1
  212. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  213. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  214. package/plugins/claude-code/plugin/.mcp.json +14 -0
  215. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  216. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  217. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  218. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  219. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  220. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  221. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  222. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  223. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  224. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  225. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  226. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  227. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  228. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  229. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
@@ -0,0 +1,64 @@
1
+ /**
2
+ * High-level `.wnlp` bundle API (WP-A1): pack, inspect, digest, unpack.
3
+ *
4
+ * The API is byte-oriented and store-independent on purpose: WP-A2 (signing)
5
+ * signs the digest returned here, WP-A3 (trust/installation) inspects and
6
+ * unpacks bytes BEFORE installation, WP-B1 (transport) carries the digest —
7
+ * none of them need the CLI, a local store, or each other.
8
+ *
9
+ * Reading is strict and fail-closed (see `src/archive.ts` strict policy):
10
+ * every failure is a {@link BundleError} with a stable `code`.
11
+ */
12
+ import type { BundleLimits, InspectOptions, InspectResult, PackOptions, PackResult } from './types.ts';
13
+ export type { BundleEntryInfo, BundleErrorCode, BundleLimits, BundleManifest, BundleRuntimeRequirements, InspectOptions, InspectResult, PackOptions, PackResult, } from './types.ts';
14
+ export { BundleError } from './types.ts';
15
+ /** Default resource bounds for bundle reading/writing (the shared archive limits). */
16
+ export declare const DEFAULT_BUNDLE_LIMITS: BundleLimits;
17
+ /**
18
+ * Bounded inflation + SHA-256 over the EXACT uncompressed canonical tar
19
+ * bytes. No files are written. This digest — not the gzip bytes — is the
20
+ * bundle's identity.
21
+ */
22
+ export declare function digestBundle(bytes: Uint8Array, opts?: InspectOptions): {
23
+ digest: string;
24
+ };
25
+ /**
26
+ * Strictly validate a `.wnlp` bundle from its bytes, WITHOUT filesystem
27
+ * extraction: bounded inflate, strict tar parse, one canonical root
28
+ * `bundle.yaml`, every declared workflow validation, exact integrity coverage,
29
+ * and per-file hash verification. Returns the digest, the manifest, and
30
+ * sorted entry metadata.
31
+ */
32
+ export declare function inspectBundle(bytes: Uint8Array, opts?: InspectOptions): InspectResult;
33
+ /**
34
+ * Materialize a `.wnlp` bundle onto disk — archive materialization only (NOT
35
+ * a local-store installation: no install lockfile, engine validation
36
+ * pipeline, or crash journal).
37
+ *
38
+ * Runs the same strict inspection first; then requires the destination to be
39
+ * ABSENT, stages under a fresh sibling directory using only validated paths,
40
+ * and atomically renames staging to destination. Cleans the staging
41
+ * directory on every failure. Refuses a symlinked destination parent before
42
+ * staging.
43
+ */
44
+ export declare function unpackBundle(bytes: Uint8Array, destination: string, opts?: InspectOptions): InspectResult & {
45
+ path: string;
46
+ };
47
+ /**
48
+ * Pack a bundle source directory into deterministic `.wnlp` bytes.
49
+ *
50
+ * - Walks the source without following symlinks; refuses symlinked roots or
51
+ * members and unsafe paths (shared archive policy).
52
+ * - Requires exactly one root `bundle.yaml` and every workflow path listed by
53
+ * that manifest.
54
+ * - Validates the source manifest, loads every listed workflow with the engine's
55
+ * definition loader (retaining contained-`bodyFile` checks), requires
56
+ * each def name to equal its workflow map key, and requires a lock entry for
57
+ * each explicit `namespace/name@version` `calls:` target.
58
+ * - Regenerates `integrity.files` from the actual file bytes (author-supplied
59
+ * hashes are replaceable generated data) and serializes a canonical
60
+ * manifest IN MEMORY — the source directory is never modified.
61
+ * - Builds the canonical tar, computes the digest over those exact bytes,
62
+ * and gzips deterministically.
63
+ */
64
+ export declare function packBundle(sourceDir: string, opts?: PackOptions): PackResult;
@@ -0,0 +1,508 @@
1
+ /**
2
+ * High-level `.wnlp` bundle API (WP-A1): pack, inspect, digest, unpack.
3
+ *
4
+ * The API is byte-oriented and store-independent on purpose: WP-A2 (signing)
5
+ * signs the digest returned here, WP-A3 (trust/installation) inspects and
6
+ * unpacks bytes BEFORE installation, WP-B1 (transport) carries the digest —
7
+ * none of them need the CLI, a local store, or each other.
8
+ *
9
+ * Reading is strict and fail-closed (see `src/archive.ts` strict policy):
10
+ * every failure is a {@link BundleError} with a stable `code`.
11
+ */
12
+ import { closeSync, lstatSync, mkdirSync, mkdtempSync, openSync, readFileSync, realpathSync, renameSync, rmSync, writeSync } from 'node:fs';
13
+ import { basename, dirname, join, resolve } from 'node:path';
14
+ import { DEFAULT_TAR_LIMITS, canonicalBundlePathViolation, inflateArchive, parseTar } from "../archive.js";
15
+ import { parseDef } from "../defs.js";
16
+ import { loadDefFile } from "../defs.js";
17
+ import { parse as parseYaml } from 'yaml';
18
+ import { assertLockCoverage, manifestIsCanonical, manifestToBytes, parseManifestBytes, sha256Hex, } from "./manifest.js";
19
+ import { buildCanonicalTar, collectSourceFiles, gzipDeterministic } from "./tar.js";
20
+ import { BundleError } from "./types.js";
21
+ export { BundleError } from "./types.js";
22
+ /** Default resource bounds for bundle reading/writing (the shared archive limits). */
23
+ export const DEFAULT_BUNDLE_LIMITS = { ...DEFAULT_TAR_LIMITS };
24
+ function mergeLimits(partial) {
25
+ const limits = { ...DEFAULT_BUNDLE_LIMITS, ...partial };
26
+ for (const [name, value] of Object.entries(limits)) {
27
+ if (!Number.isSafeInteger(value) || value <= 0) {
28
+ throw new BundleError('BUNDLE_LIMIT', `${name} must be a positive safe integer`);
29
+ }
30
+ }
31
+ return limits;
32
+ }
33
+ /** Wrap a DefError/parse failure into a stable-code BundleError. */
34
+ function workflowError(message, entryPath) {
35
+ return new BundleError('WORKFLOW_ERROR', `${entryPath}: ${message}`, entryPath);
36
+ }
37
+ /**
38
+ * Bounded inflation + SHA-256 over the EXACT uncompressed canonical tar
39
+ * bytes. No files are written. This digest — not the gzip bytes — is the
40
+ * bundle's identity.
41
+ */
42
+ export function digestBundle(bytes, opts = {}) {
43
+ const lim = mergeLimits(opts.limits);
44
+ let tar;
45
+ try {
46
+ tar = inflateArchive(bytes, lim);
47
+ }
48
+ catch (e) {
49
+ throw limitOrArchiveError(e);
50
+ }
51
+ return { digest: sha256Hex(tar) };
52
+ }
53
+ /** Convert archive/limit failures into stable-code BundleErrors. */
54
+ function limitOrArchiveError(e) {
55
+ if (e instanceof BundleError)
56
+ return e;
57
+ const err = e;
58
+ const msg = err?.message ?? String(e);
59
+ // archive.ts strict violations carry a stable code; surface it as-is.
60
+ const code = err?.code;
61
+ const known = [
62
+ 'ARCHIVE_TOO_MANY_ENTRIES',
63
+ 'ARCHIVE_ENTRY_TOO_LARGE',
64
+ 'ARCHIVE_PATH_TOO_LONG',
65
+ 'ARCHIVE_PATH_VIOLATION',
66
+ 'ARCHIVE_DUPLICATE_PATH',
67
+ 'ARCHIVE_PATH_PREFIX_COLLISION',
68
+ 'ARCHIVE_TRUNCATED',
69
+ 'ARCHIVE_BAD_CHECKSUM',
70
+ 'ARCHIVE_BAD_OCTAL',
71
+ 'ARCHIVE_BAD_PAX',
72
+ 'ARCHIVE_DANGLING_PAX',
73
+ 'ARCHIVE_TRAILING_BYTES',
74
+ 'UNSUPPORTED_ENTRY_TYPE',
75
+ 'NON_CANONICAL_HEADER',
76
+ ];
77
+ if (code && known.includes(code)) {
78
+ return new BundleError(code, msg, err.entryPath);
79
+ }
80
+ // gzip failures (corrupt/non-gzip input) and inflate limit refusals.
81
+ if (msg.includes('expanded archive size exceeds limit') || msg.includes('compressed archive size')) {
82
+ return new BundleError('BUNDLE_LIMIT', msg);
83
+ }
84
+ return new BundleError('BUNDLE_NOT_GZIP', `cannot read archive: ${msg}`);
85
+ }
86
+ function readBundleStrict(bytes, lim) {
87
+ let tar;
88
+ let entries;
89
+ try {
90
+ tar = inflateArchive(bytes, lim);
91
+ entries = parseTar(tar, lim, { policy: 'strict' });
92
+ }
93
+ catch (e) {
94
+ throw limitOrArchiveError(e);
95
+ }
96
+ const manifests = entries.filter((e) => e.path === 'bundle.yaml');
97
+ if (manifests.length === 0) {
98
+ throw new BundleError('MANIFEST_MISSING', "bundle has no root 'bundle.yaml' manifest");
99
+ }
100
+ const manifestEntry = manifests[0];
101
+ const manifest = parseManifestBytes(manifestEntry.data);
102
+ if (!manifestIsCanonical(manifestEntry.data)) {
103
+ throw new BundleError('MANIFEST_ERROR', 'bundle.yaml: not in canonical form (pack it with owenloop bundle pack)');
104
+ }
105
+ return { digest: sha256Hex(tar), entries, manifest };
106
+ }
107
+ /**
108
+ * Replace archive-contained `bodyFile` references with their file text before
109
+ * calling the normal definition parser. The disk loader resolves these paths
110
+ * against the workflow directory; an archive reader has no directory, so the
111
+ * equivalent in-memory operation must enforce the same relative-path policy,
112
+ * require a regular archive entry, and then provide the resolved body string.
113
+ */
114
+ function inlineArchiveBodyFiles(value, files, workflowPath, context) {
115
+ if (Array.isArray(value)) {
116
+ return value.map((item, i) => inlineArchiveBodyFiles(item, files, workflowPath, `${context}[${i}]`));
117
+ }
118
+ if (typeof value !== 'object' || value === null)
119
+ return value;
120
+ const source = value;
121
+ const out = {};
122
+ const hasBody = Object.prototype.hasOwnProperty.call(source, 'body');
123
+ const escapedWorkflowPath = workflowPath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
124
+ const canResolveBodyFile = new RegExp(`^${escapedWorkflowPath}\\.steps\\[\\d+\\](?:\\.produces\\[\\d+\\]\\.judges\\[\\d+\\])?$`).test(context);
125
+ const slash = workflowPath.lastIndexOf('/');
126
+ const workflowDirectory = slash === -1 ? '' : workflowPath.slice(0, slash);
127
+ for (const [key, item] of Object.entries(source)) {
128
+ if (canResolveBodyFile && key === 'bodyFile' && typeof item === 'string' && !hasBody) {
129
+ const violation = canonicalBundlePathViolation(item);
130
+ if (violation) {
131
+ throw new Error(`${context}.bodyFile '${item}' is unsafe: ${violation}`);
132
+ }
133
+ const targetPath = workflowDirectory === '' ? item : `${workflowDirectory}/${item}`;
134
+ const targetViolation = canonicalBundlePathViolation(targetPath);
135
+ if (targetViolation) {
136
+ throw new Error(`${context}.bodyFile '${item}' is unsafe after resolving against '${workflowDirectory}': ${targetViolation}`);
137
+ }
138
+ const target = files.get(targetPath);
139
+ if (!target) {
140
+ throw new Error(`${context}.bodyFile '${item}' is missing from the archive`);
141
+ }
142
+ let body;
143
+ try {
144
+ body = new TextDecoder('utf-8', { fatal: true }).decode(target.data);
145
+ }
146
+ catch {
147
+ throw new Error(`${context}.bodyFile '${item}' is not valid UTF-8`);
148
+ }
149
+ out.body = body;
150
+ continue;
151
+ }
152
+ out[key] = inlineArchiveBodyFiles(item, files, workflowPath, `${context}.${key}`);
153
+ }
154
+ return out;
155
+ }
156
+ /** Workflow validation shared by inspect and unpack (in-memory; no disk). */
157
+ function validateWorkflowsBytes(entries, manifest) {
158
+ const files = new Map(entries.map((entry) => [entry.path, entry]));
159
+ const callsTargets = [];
160
+ for (const [workflowName, workflowPath] of Object.entries(manifest.workflows)) {
161
+ const workflowEntry = files.get(workflowPath);
162
+ if (!workflowEntry) {
163
+ throw new BundleError('WORKFLOW_MISSING', `bundle is missing workflow '${workflowName}' at '${workflowPath}'`, workflowPath);
164
+ }
165
+ let text;
166
+ try {
167
+ text = new TextDecoder('utf-8', { fatal: true }).decode(workflowEntry.data);
168
+ }
169
+ catch {
170
+ throw workflowError('not valid UTF-8', workflowPath);
171
+ }
172
+ let raw;
173
+ try {
174
+ raw = parseYaml(text);
175
+ }
176
+ catch (e) {
177
+ throw workflowError(`YAML parse error: ${e.message.split('\n')[0]}`, workflowPath);
178
+ }
179
+ let def;
180
+ try {
181
+ const inlined = inlineArchiveBodyFiles(raw, files, workflowPath, workflowPath);
182
+ def = parseDef(inlined, workflowPath, undefined);
183
+ }
184
+ catch (e) {
185
+ throw workflowError(e.message, workflowPath);
186
+ }
187
+ if (def.name !== workflowName) {
188
+ throw new BundleError('WORKFLOW_ERROR', `${workflowPath}: definition name '${def.name}' must equal workflow map key '${workflowName}'`, workflowPath);
189
+ }
190
+ callsTargets.push(...def.steps.map((step) => step.calls).filter((target) => typeof target === 'string'));
191
+ }
192
+ assertLockCoverage(manifest, callsTargets);
193
+ }
194
+ /** Exact-set integrity coverage + per-file hash verification. */
195
+ function verifyIntegrity(entries, manifest) {
196
+ const archivePaths = new Set(entries.map((e) => e.path));
197
+ const integrityKeys = Object.keys(manifest.integrity.files);
198
+ for (const key of integrityKeys) {
199
+ if (!archivePaths.has(key)) {
200
+ throw new BundleError('INTEGRITY_MISMATCH', `integrity lists '${key}' which is not in the archive`, key);
201
+ }
202
+ }
203
+ for (const e of entries) {
204
+ if (e.path === 'bundle.yaml')
205
+ continue; // excluded: recursive self-hash
206
+ if (!Object.prototype.hasOwnProperty.call(manifest.integrity.files, e.path)) {
207
+ throw new BundleError('INTEGRITY_MISMATCH', `archive file '${e.path}' has no integrity entry`, e.path);
208
+ }
209
+ const expected = manifest.integrity.files[e.path];
210
+ const actual = sha256Hex(e.data);
211
+ if (actual !== expected) {
212
+ throw new BundleError('INTEGRITY_MISMATCH', `integrity mismatch for '${e.path}' (expected ${expected}, got ${actual})`, e.path);
213
+ }
214
+ }
215
+ }
216
+ function entryInfos(entries) {
217
+ return entries.map((e) => ({
218
+ path: e.path,
219
+ size: e.size,
220
+ executable: e.mode === 0o755,
221
+ sha256: sha256Hex(e.data),
222
+ }));
223
+ }
224
+ const ROOT_PATH_ALIASES = ['/var', '/tmp'];
225
+ /**
226
+ * Normalize the two conventional root aliases before checking ancestors. On
227
+ * systems where an alias is a real directory this is a no-op. On systems where
228
+ * an alias resolves elsewhere, the resolved path is checked instead, so the
229
+ * ancestor validation has one rule on every platform. User-created symlinks
230
+ * below the normalized root remain visible to the lexical lstat walk and are
231
+ * refused.
232
+ */
233
+ function normalizeRootAliases(absolute) {
234
+ let normalized = absolute;
235
+ for (const alias of ROOT_PATH_ALIASES) {
236
+ let target;
237
+ try {
238
+ target = realpathSync(alias);
239
+ }
240
+ catch {
241
+ continue;
242
+ }
243
+ if (target === alias)
244
+ continue;
245
+ if (dirname(target) !== '/private' || basename(target) !== basename(alias))
246
+ continue;
247
+ if (normalized === alias || normalized.startsWith(`${alias}/`)) {
248
+ normalized = `${target}${normalized.slice(alias.length)}`;
249
+ }
250
+ }
251
+ return normalized;
252
+ }
253
+ function assertDestinationParent(parent) {
254
+ const absolute = normalizeRootAliases(resolve(parent));
255
+ let resolved;
256
+ try {
257
+ // Resolve before validating the canonical path. A dangling ancestor is an
258
+ // invalid destination, not a request to create a new parent tree.
259
+ resolved = realpathSync(absolute);
260
+ }
261
+ catch {
262
+ throw new BundleError('DESTINATION_PARENT_INVALID', `unpack destination parent '${parent}' does not exist`);
263
+ }
264
+ const components = [];
265
+ let current = absolute;
266
+ while (true) {
267
+ components.push(current);
268
+ const next = dirname(current);
269
+ if (next === current)
270
+ break;
271
+ current = next;
272
+ }
273
+ for (const component of components.reverse()) {
274
+ let st;
275
+ try {
276
+ st = lstatSync(component, { throwIfNoEntry: false });
277
+ }
278
+ catch (error) {
279
+ const message = error instanceof Error ? error.message : String(error);
280
+ throw new BundleError('DESTINATION_PARENT_INVALID', `cannot inspect unpack destination parent '${parent}': ${message}`);
281
+ }
282
+ if (!st) {
283
+ throw new BundleError('DESTINATION_PARENT_INVALID', `unpack destination parent '${parent}' does not exist`);
284
+ }
285
+ if (st.isSymbolicLink()) {
286
+ throw new BundleError('DESTINATION_PARENT_INVALID', `unpack destination ancestor '${component}' is a symbolic link`);
287
+ }
288
+ if (!st.isDirectory()) {
289
+ throw new BundleError('DESTINATION_PARENT_INVALID', `unpack destination ancestor '${component}' is not a directory`);
290
+ }
291
+ }
292
+ return resolved;
293
+ }
294
+ function lstatDestination(path) {
295
+ try {
296
+ return lstatSync(path, { throwIfNoEntry: false });
297
+ }
298
+ catch (error) {
299
+ const message = error instanceof Error ? error.message : String(error);
300
+ throw new BundleError('DESTINATION_PARENT_INVALID', `cannot inspect unpack destination '${path}': ${message}`);
301
+ }
302
+ }
303
+ /**
304
+ * Strictly validate a `.wnlp` bundle from its bytes, WITHOUT filesystem
305
+ * extraction: bounded inflate, strict tar parse, one canonical root
306
+ * `bundle.yaml`, every declared workflow validation, exact integrity coverage,
307
+ * and per-file hash verification. Returns the digest, the manifest, and
308
+ * sorted entry metadata.
309
+ */
310
+ export function inspectBundle(bytes, opts = {}) {
311
+ const lim = mergeLimits(opts.limits);
312
+ const { digest, entries, manifest } = readBundleStrict(bytes, lim);
313
+ validateWorkflowsBytes(entries, manifest);
314
+ verifyIntegrity(entries, manifest);
315
+ return { digest, manifest, entries: entryInfos(entries) };
316
+ }
317
+ /**
318
+ * Materialize a `.wnlp` bundle onto disk — archive materialization only (NOT
319
+ * a local-store installation: no install lockfile, engine validation
320
+ * pipeline, or crash journal).
321
+ *
322
+ * Runs the same strict inspection first; then requires the destination to be
323
+ * ABSENT, stages under a fresh sibling directory using only validated paths,
324
+ * and atomically renames staging to destination. Cleans the staging
325
+ * directory on every failure. Refuses a symlinked destination parent before
326
+ * staging.
327
+ */
328
+ export function unpackBundle(bytes, destination, opts = {}) {
329
+ const lim = mergeLimits(opts.limits);
330
+ const { digest, entries, manifest } = readBundleStrict(bytes, lim);
331
+ validateWorkflowsBytes(entries, manifest);
332
+ verifyIntegrity(entries, manifest);
333
+ const destAbs = resolve(destination);
334
+ const parent = dirname(destAbs);
335
+ // Destination must not exist (any kind).
336
+ const existing = lstatDestination(destAbs);
337
+ if (existing) {
338
+ throw new BundleError('DESTINATION_EXISTS', `unpack destination '${destination}' already exists`);
339
+ }
340
+ // Resolve the existing parent before checking its components. Staging uses
341
+ // the resolved sibling path, while the public result retains the caller's
342
+ // absolute spelling of the destination.
343
+ const resolvedParent = assertDestinationParent(parent);
344
+ // mkdtempSync creates a fresh sibling even when another process is unpacking
345
+ // the same destination concurrently; the predictable pid/timestamp name
346
+ // used by older partial code could collide.
347
+ const staging = mkdtempSync(join(resolvedParent, `.${basename(destAbs)}.owenloop-unpack-`));
348
+ let staged = true;
349
+ try {
350
+ for (const e of entries) {
351
+ // Paths are already strict-validated (no traversal/absolute/NUL);
352
+ // re-check against the shared policy as defense-in-depth.
353
+ const violation = canonicalBundlePathViolation(e.path);
354
+ if (violation) {
355
+ throw new BundleError('ARCHIVE_PATH_VIOLATION', `unsafe archive path '${e.path}': ${violation}`, e.path);
356
+ }
357
+ const target = join(staging, e.path);
358
+ const targetDir = dirname(target);
359
+ mkdirSync(targetDir, { recursive: true, mode: 0o755 });
360
+ const fd = openSync(target, 'wx', e.mode === 0o755 ? 0o755 : 0o644);
361
+ try {
362
+ // fs.writeSync from a Uint8Array view.
363
+ const buf = Buffer.from(e.data.buffer, e.data.byteOffset, e.data.byteLength);
364
+ let written = 0;
365
+ while (written < buf.length) {
366
+ written += writeSync(fd, buf.subarray(written));
367
+ }
368
+ }
369
+ finally {
370
+ closeSync(fd);
371
+ }
372
+ }
373
+ if (lstatDestination(destAbs)) {
374
+ throw new BundleError('DESTINATION_EXISTS', `unpack destination '${destination}' already exists`);
375
+ }
376
+ renameSync(staging, destAbs);
377
+ staged = false;
378
+ }
379
+ finally {
380
+ if (staged) {
381
+ rmSync(staging, { recursive: true, force: true });
382
+ }
383
+ }
384
+ return { digest, manifest, entries: entryInfos(entries), path: destAbs };
385
+ }
386
+ /**
387
+ * Pack a bundle source directory into deterministic `.wnlp` bytes.
388
+ *
389
+ * - Walks the source without following symlinks; refuses symlinked roots or
390
+ * members and unsafe paths (shared archive policy).
391
+ * - Requires exactly one root `bundle.yaml` and every workflow path listed by
392
+ * that manifest.
393
+ * - Validates the source manifest, loads every listed workflow with the engine's
394
+ * definition loader (retaining contained-`bodyFile` checks), requires
395
+ * each def name to equal its workflow map key, and requires a lock entry for
396
+ * each explicit `namespace/name@version` `calls:` target.
397
+ * - Regenerates `integrity.files` from the actual file bytes (author-supplied
398
+ * hashes are replaceable generated data) and serializes a canonical
399
+ * manifest IN MEMORY — the source directory is never modified.
400
+ * - Builds the canonical tar, computes the digest over those exact bytes,
401
+ * and gzips deterministically.
402
+ */
403
+ export function packBundle(sourceDir, opts = {}) {
404
+ const lim = mergeLimits(opts.limits);
405
+ const files = collectSourceFiles(sourceDir, lim);
406
+ const sourcePaths = new Set(files.map((f) => f.rel));
407
+ if (!sourcePaths.has('bundle.yaml')) {
408
+ throw new BundleError('MANIFEST_MISSING', `source '${sourceDir}' has no root 'bundle.yaml'`);
409
+ }
410
+ // Read file bytes, re-checking each node is still the same regular file it
411
+ // was during the walk (reduces TOCTOU ambiguity).
412
+ const contents = new Map();
413
+ for (const f of files) {
414
+ let st;
415
+ try {
416
+ st = lstatSync(f.abs);
417
+ }
418
+ catch {
419
+ throw new BundleError('SOURCE_FILE_CHANGED', `'${f.rel}' disappeared during packing`, f.rel);
420
+ }
421
+ if (st.isSymbolicLink() || !st.isFile()) {
422
+ throw new BundleError('SOURCE_FILE_CHANGED', `'${f.rel}' changed type during packing`, f.rel);
423
+ }
424
+ if (st.size > lim.maxFileBytes) {
425
+ throw new BundleError('ARCHIVE_ENTRY_TOO_LARGE', `archive entry '${f.rel}' is ${st.size} bytes; limit is ${lim.maxFileBytes}`, f.rel);
426
+ }
427
+ try {
428
+ contents.set(f.rel, new Uint8Array(readFileSync(f.abs)));
429
+ }
430
+ catch {
431
+ throw new BundleError('SOURCE_FILE_CHANGED', `'${f.rel}' could not be read during packing`, f.rel);
432
+ }
433
+ }
434
+ const sourceManifest = parseManifestBytes(contents.get('bundle.yaml'));
435
+ // Load every declared workflow with the disk loader so bodyFile paths use
436
+ // the workflow file's own directory, then check the union of all calls.
437
+ const callsTargets = [];
438
+ for (const [workflowName, workflowPath] of Object.entries(sourceManifest.workflows)) {
439
+ if (!sourcePaths.has(workflowPath)) {
440
+ throw new BundleError('WORKFLOW_MISSING', `source '${sourceDir}' is missing workflow '${workflowName}' at '${workflowPath}'`, workflowPath);
441
+ }
442
+ let def;
443
+ try {
444
+ def = loadDefFile(join(resolve(sourceDir), workflowPath));
445
+ }
446
+ catch (e) {
447
+ throw workflowError(e.message, workflowPath);
448
+ }
449
+ if (def.name !== workflowName) {
450
+ throw new BundleError('WORKFLOW_ERROR', `${workflowPath}: definition name '${def.name}' must equal workflow map key '${workflowName}'`, workflowPath);
451
+ }
452
+ callsTargets.push(...def.steps.map((step) => step.calls).filter((target) => typeof target === 'string'));
453
+ }
454
+ assertLockCoverage(sourceManifest, callsTargets);
455
+ // Regenerate the integrity map from the actual bytes (bundle.yaml excluded:
456
+ // recursive self-hash; the digest covers it through the canonical tar).
457
+ const integrityFiles = {};
458
+ for (const f of files) {
459
+ if (f.rel === 'bundle.yaml')
460
+ continue;
461
+ integrityFiles[f.rel] = sha256Hex(contents.get(f.rel));
462
+ }
463
+ const canonicalManifest = {
464
+ ...sourceManifest,
465
+ ...(sourceManifest.runtime === undefined
466
+ ? {}
467
+ : {
468
+ runtime: {
469
+ ...(sourceManifest.runtime.minVersion === undefined
470
+ ? {}
471
+ : { minVersion: sourceManifest.runtime.minVersion }),
472
+ ...(sourceManifest.runtime.features === undefined
473
+ ? {}
474
+ : {
475
+ features: [...sourceManifest.runtime.features].sort((a, b) => Buffer.compare(Buffer.from(a, 'utf8'), Buffer.from(b, 'utf8'))),
476
+ }),
477
+ },
478
+ }),
479
+ integrity: { algorithm: 'sha256', files: integrityFiles },
480
+ };
481
+ const canonicalBytes = manifestToBytes(canonicalManifest);
482
+ // Replace the manifest entry ONLY in the in-memory file set.
483
+ const executableByPath = new Map(files.map((f) => [f.rel, f.executable]));
484
+ const tarFiles = files.map((f) => ({
485
+ path: f.rel,
486
+ bytes: f.rel === 'bundle.yaml' ? canonicalBytes : contents.get(f.rel),
487
+ mode: (executableByPath.get(f.rel) ?? false) ? 0o755 : 0o644,
488
+ }));
489
+ // files is already sorted by ascending UTF-8 path order; bundle.yaml
490
+ // participates in that sort as one entry among the rest.
491
+ const tar = buildCanonicalTar(tarFiles, lim);
492
+ const digest = sha256Hex(tar);
493
+ const bytes = gzipDeterministic(tar);
494
+ if (bytes.length > lim.maxCompressedBytes) {
495
+ throw new BundleError('BUNDLE_LIMIT', `compressed archive size ${bytes.length} exceeds limit of ${lim.maxCompressedBytes} bytes`);
496
+ }
497
+ return {
498
+ bytes,
499
+ digest,
500
+ manifest: canonicalManifest,
501
+ entries: tarFiles.map((f) => ({
502
+ path: f.path,
503
+ size: f.bytes.length,
504
+ executable: f.mode === 0o755,
505
+ sha256: sha256Hex(f.bytes),
506
+ })),
507
+ };
508
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * `.wnlp` manifest (`bundle.yaml`) — strict fail-closed parsing, schema
3
+ * validation, cross-reference lock checks, integrity construction, and
4
+ * canonical YAML serialization (WP-A1, see `docs/bundles.md`).
5
+ *
6
+ * The manifest is package-only: it carries identity, platform selectors, a
7
+ * named workflow-to-path map, a per-file integrity map, REQUESTED capabilities
8
+ * (never granted here), and a digest-pinned `lock` map for explicit
9
+ * `namespace/name@version` call references. Execution fields (`worker`,
10
+ * `command`, interpreter, script…) are unknown keys and refused — workflow
11
+ * files remain the only execution surface.
12
+ *
13
+ * Parsing is fail-closed on the YAML AST: parse errors AND warnings refuse
14
+ * the document; aliases, merge keys, tags (custom or built-in), non-string
15
+ * map keys, and duplicate keys are all named refusals. Canonical
16
+ * serialization is deterministic: fixed key order, sorted map keys and list
17
+ * values (ascending UTF-8 bytes), every string double-quoted, two-space
18
+ * indent, one final newline.
19
+ */
20
+ import type { BundleManifest } from './types.ts';
21
+ /** Lowercase 64-hex SHA-256 of `bytes`. */
22
+ export declare function sha256Hex(bytes: Uint8Array): string;
23
+ /** Workflow map keys: lowercase-start, lowercase alphanumeric and hyphen. */
24
+ export declare const WORKFLOW_NAME_RE: RegExp;
25
+ /** True when `text` is the explicit `namespace/name@version` reference form. */
26
+ export declare function isVersionedReference(text: string): boolean;
27
+ /**
28
+ * Parse and validate `.wnlp` manifest bytes, fail-closed. Refuses non-UTF-8
29
+ * input, a missing (or double) final newline, any YAML parse error or
30
+ * warning, and every shape violation. Returns the validated manifest; the
31
+ * source byte order of collections is NOT enforced here — canonicality is a
32
+ * separate concern ({@link manifestIsCanonical}).
33
+ */
34
+ export declare function parseManifestBytes(bytes: Uint8Array): BundleManifest;
35
+ /**
36
+ * Serialize a manifest to its canonical bytes: fixed top-level key order,
37
+ * map keys and list values sorted by ascending UTF-8 bytes, every string
38
+ * double-quoted, two-space indent, one final newline. Deterministic across
39
+ * platforms — the checked-in golden vector freezes the result.
40
+ */
41
+ export declare function manifestToBytes(manifest: BundleManifest): Uint8Array;
42
+ /** True when `bytes` is exactly the canonical serialization of the manifest it parses to. */
43
+ export declare function manifestIsCanonical(bytes: Uint8Array): boolean;
44
+ /**
45
+ * Cross-reference check: every `calls:` target in `callsTargets` that uses
46
+ * the explicit `namespace/name@version` form must carry a `lock` entry. Bare
47
+ * (same-package) calls stay governed by the existing def grammar and need no
48
+ * lock. A1 does not resolve or fetch locks — it only validates coverage.
49
+ */
50
+ export declare function assertLockCoverage(manifest: BundleManifest, callsTargets: string[]): void;