owenloop 0.5.0 → 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 (211) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +137 -35
  3. package/bin/owenloop.mjs +49 -1
  4. package/dist/packages/work/src/agent/brief.d.ts +8 -4
  5. package/dist/packages/work/src/agent/brief.js +7 -3
  6. package/dist/packages/work/src/agent/loop.d.ts +13 -7
  7. package/dist/packages/work/src/agent/loop.js +136 -9
  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/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 +12 -1
  20. package/dist/packages/work/src/exec/loop.js +137 -20
  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 +74 -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 +27 -9
  38. package/dist/packages/work/src/harness/session-store.js +271 -67
  39. package/dist/packages/work/src/hold/mcp.d.ts +25 -5
  40. package/dist/packages/work/src/hold/mcp.js +126 -11
  41. package/dist/packages/work/src/hub/client.d.ts +2 -1
  42. package/dist/packages/work/src/hub/client.js +14 -1
  43. package/dist/packages/work/src/hub/types.d.ts +69 -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 +116 -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 +4 -0
  53. package/dist/packages/work/src/roles/hold.js +44 -5
  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 +5 -0
  57. package/dist/packages/work/src/roles/shift.d.ts +1 -0
  58. package/dist/packages/work/src/roles/shift.js +23 -1
  59. package/dist/packages/work/src/settings/settings.d.ts +17 -1
  60. package/dist/packages/work/src/settings/settings.js +39 -0
  61. package/dist/packages/work/src/shift/loop.d.ts +14 -3
  62. package/dist/packages/work/src/shift/loop.js +447 -164
  63. package/dist/packages/work/src/shift/protocol.d.ts +4 -0
  64. package/dist/packages/work/src/shift/runtime.d.ts +2 -0
  65. package/dist/packages/work/src/shift/runtime.js +66 -3
  66. package/dist/packages/work/src/shift/spawn.d.ts +41 -18
  67. package/dist/packages/work/src/shift/spawn.js +89 -31
  68. package/dist/packages/work/src/shift/state.d.ts +53 -51
  69. package/dist/packages/work/src/shift/state.js +325 -102
  70. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  71. package/dist/packages/work/src/submit-proof.js +93 -0
  72. package/dist/src/add.d.ts +64 -259
  73. package/dist/src/add.js +81 -615
  74. package/dist/src/archive.d.ts +97 -0
  75. package/dist/src/archive.js +591 -0
  76. package/dist/src/bundle/index.d.ts +64 -0
  77. package/dist/src/bundle/index.js +508 -0
  78. package/dist/src/bundle/manifest.d.ts +50 -0
  79. package/dist/src/bundle/manifest.js +435 -0
  80. package/dist/src/bundle/runtime.d.ts +26 -0
  81. package/dist/src/bundle/runtime.js +64 -0
  82. package/dist/src/bundle/tar.d.ts +62 -0
  83. package/dist/src/bundle/tar.js +238 -0
  84. package/dist/src/bundle/types.d.ts +105 -0
  85. package/dist/src/bundle/types.js +21 -0
  86. package/dist/src/cli.d.ts +90 -20
  87. package/dist/src/cli.js +2407 -365
  88. package/dist/src/credentials.d.ts +4 -3
  89. package/dist/src/credentials.js +21 -19
  90. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  91. package/dist/src/crypto/allowed-signers.js +307 -0
  92. package/dist/src/crypto/canonical.d.ts +8 -0
  93. package/dist/src/crypto/canonical.js +92 -0
  94. package/dist/src/crypto/chain.d.ts +65 -0
  95. package/dist/src/crypto/chain.js +377 -0
  96. package/dist/src/crypto/dsse.d.ts +209 -0
  97. package/dist/src/crypto/dsse.js +282 -0
  98. package/dist/src/crypto/enrollment.d.ts +78 -0
  99. package/dist/src/crypto/enrollment.js +186 -0
  100. package/dist/src/crypto/index.d.ts +48 -0
  101. package/dist/src/crypto/index.js +44 -0
  102. package/dist/src/crypto/keys.d.ts +258 -0
  103. package/dist/src/crypto/keys.js +908 -0
  104. package/dist/src/crypto/org-root.d.ts +33 -0
  105. package/dist/src/crypto/org-root.js +78 -0
  106. package/dist/src/crypto/origin-rules.d.ts +56 -0
  107. package/dist/src/crypto/origin-rules.js +143 -0
  108. package/dist/src/crypto/policy-floor.d.ts +98 -0
  109. package/dist/src/crypto/policy-floor.js +353 -0
  110. package/dist/src/crypto/records.d.ts +316 -0
  111. package/dist/src/crypto/records.js +157 -0
  112. package/dist/src/crypto/scope.d.ts +49 -0
  113. package/dist/src/crypto/scope.js +83 -0
  114. package/dist/src/crypto/ssh.d.ts +171 -0
  115. package/dist/src/crypto/ssh.js +396 -0
  116. package/dist/src/crypto/submission.d.ts +33 -0
  117. package/dist/src/crypto/submission.js +47 -0
  118. package/dist/src/crypto/trust-roots.d.ts +29 -0
  119. package/dist/src/crypto/trust-roots.js +39 -0
  120. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  121. package/dist/src/crypto/verify-consumed.js +259 -0
  122. package/dist/src/crypto/verify-origin.d.ts +50 -0
  123. package/dist/src/crypto/verify-origin.js +151 -0
  124. package/dist/src/crypto/verify-publication.d.ts +60 -0
  125. package/dist/src/crypto/verify-publication.js +150 -0
  126. package/dist/src/defs.d.ts +24 -1
  127. package/dist/src/defs.js +145 -25
  128. package/dist/src/engine.d.ts +99 -3
  129. package/dist/src/engine.js +238 -34
  130. package/dist/src/factory.d.ts +16 -0
  131. package/dist/src/factory.js +16 -4
  132. package/dist/src/global-config.d.ts +59 -0
  133. package/dist/src/global-config.js +84 -0
  134. package/dist/src/hub.d.ts +75 -21
  135. package/dist/src/hub.js +123 -40
  136. package/dist/src/index.d.ts +17 -2
  137. package/dist/src/index.js +20 -2
  138. package/dist/src/install.d.ts +538 -0
  139. package/dist/src/install.js +1981 -0
  140. package/dist/src/lock.d.ts +15 -57
  141. package/dist/src/lock.js +251 -143
  142. package/dist/src/mcp/serve.d.ts +46 -22
  143. package/dist/src/mcp/serve.js +167 -44
  144. package/dist/src/mcp/server.js +12 -1
  145. package/dist/src/model.d.ts +15 -0
  146. package/dist/src/model.js +111 -1
  147. package/dist/src/order-resolver.d.ts +184 -0
  148. package/dist/src/order-resolver.js +252 -0
  149. package/dist/src/package-version.d.ts +10 -0
  150. package/dist/src/package-version.js +42 -0
  151. package/dist/src/paths.d.ts +14 -1
  152. package/dist/src/paths.js +18 -0
  153. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  154. package/dist/src/schemas/index.d.ts +1416 -0
  155. package/dist/src/schemas/index.js +31 -0
  156. package/dist/src/schemas/order.v1.schema.json +106 -0
  157. package/dist/src/schemas/origin.v1.schema.json +68 -0
  158. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  159. package/dist/src/schemas/publication.v1.schema.json +31 -0
  160. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  161. package/dist/src/schemas/submission.v1.schema.json +61 -0
  162. package/dist/src/store/def-source.d.ts +52 -0
  163. package/dist/src/store/def-source.js +335 -0
  164. package/dist/src/store/index-file.d.ts +69 -0
  165. package/dist/src/store/index-file.js +151 -0
  166. package/dist/src/store/index.d.ts +27 -0
  167. package/dist/src/store/index.js +22 -0
  168. package/dist/src/store/ingestor.d.ts +43 -0
  169. package/dist/src/store/ingestor.js +211 -0
  170. package/dist/src/store/install.d.ts +228 -0
  171. package/dist/src/store/install.js +555 -0
  172. package/dist/src/store/instruction-source.d.ts +49 -0
  173. package/dist/src/store/instruction-source.js +298 -0
  174. package/dist/src/store/origin-evidence.d.ts +21 -0
  175. package/dist/src/store/origin-evidence.js +66 -0
  176. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  177. package/dist/src/store/pre-commit-verifier.js +418 -0
  178. package/dist/src/store/resolve.d.ts +138 -0
  179. package/dist/src/store/resolve.js +363 -0
  180. package/dist/src/store/types.d.ts +288 -0
  181. package/dist/src/store/types.js +356 -0
  182. package/dist/src/types.d.ts +45 -11
  183. package/dist/src/untar.d.ts +8 -23
  184. package/dist/src/untar.js +10 -136
  185. package/docs/agent-runner.md +86 -0
  186. package/docs/authoring.md +57 -6
  187. package/docs/bundles.md +250 -0
  188. package/docs/cli.md +1171 -97
  189. package/docs/crypto.md +816 -0
  190. package/docs/design.md +342 -20
  191. package/docs/embedding.md +132 -25
  192. package/docs/wire-contracts.md +380 -0
  193. package/package.json +6 -1
  194. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  195. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  196. package/plugins/claude-code/plugin/.mcp.json +14 -0
  197. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  198. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  199. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  200. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  201. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  202. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  203. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  204. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  205. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  206. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  207. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  208. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  209. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  210. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  211. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
@@ -0,0 +1,356 @@
1
+ /**
2
+ * The content-addressed workflow store's value types, constructors, and named
3
+ * error classes.
4
+ *
5
+ * TWO DISTINCT "STORES" live in this package — do not conflate them:
6
+ * - `src/store.ts` — the SQLite RUNTIME store (`Store`/`openStore`): engine
7
+ * execution state (workflows, runs, artifacts).
8
+ * - `src/store/` (this directory) — the content-addressed WORKFLOW store:
9
+ * immutable, digest-addressed workflow-definition objects plus a
10
+ * coordinate→digest index, installed from `.wnlp` bundles. This module is
11
+ * its type surface.
12
+ *
13
+ * On-disk layout, at EACH of two levels (project = the resolved defs dir;
14
+ * global = `~/.owenloop/workflows`):
15
+ *
16
+ * <root>/index.json coordinate → digest (+ pinned) index
17
+ * <root>/objects/sha256/<64-hex>/ one immutable object per digest
18
+ *
19
+ * Identity rules: a digest is a lowercase 64-char SHA-256 hex value owned by
20
+ * the bundle format module — this module only VALIDATES the
21
+ * shape (rejecting uppercase/noncanonical input rather than normalizing
22
+ * attacker-controlled data); it never recomputes bundle digests itself. A
23
+ * coordinate is `namespace/name@version` (the FULL coordinate — this module
24
+ * never derives one from a filename or URL). Object paths derive ONLY from
25
+ * validated digests; a coordinate or source URL is never joined into a
26
+ * filesystem path.
27
+ */
28
+ import { createRequire } from 'node:module';
29
+ import { join } from 'node:path';
30
+ import { isCanonicalSemver } from "../bundle/runtime.js";
31
+ const semver = createRequire(import.meta.url)('semver');
32
+ /** A lowercase 64-char SHA-256 hex digest — the store's only object identity. */
33
+ export const DIGEST_RE = /^[0-9a-f]{64}$/;
34
+ /**
35
+ * One coordinate component (`namespace`, `name`, or `version`). The grammar is
36
+ * deliberately broad: a component is a non-empty string free of control
37
+ * characters and path-significant characters. This module deliberately does
38
+ * NOT impose a semver grammar on `version` — the bundle format module owns
39
+ * version content; this module only keeps components filesystem-safe and
40
+ * unambiguous.
41
+ */
42
+ // eslint-disable-next-line no-control-regex -- the control-character exclusion IS the point: components must be filesystem-safe, so the range is deliberate.
43
+ export const COORDINATE_COMPONENT_RE = /^[^\x00-\x1f\x7f\\/:%#?]+$/;
44
+ /**
45
+ * A named store error: every fail-closed refusal the store produces carries a
46
+ * stable machine-readable `code` alongside the human message, so callers
47
+ * (CLI dispatch, resolution callers, tests) can branch on `instanceof` +
48
+ * `code` instead of matching message text. `path`/`entry`/`coordinate` are
49
+ * present only in messages, never trusted for control flow.
50
+ */
51
+ export class WorkflowStoreError extends Error {
52
+ code;
53
+ constructor(code, message) {
54
+ super(message);
55
+ this.name = 'WorkflowStoreError';
56
+ this.code = code;
57
+ }
58
+ }
59
+ /** The index file failed to parse or failed fail-closed validation. */
60
+ export class StoreIndexError extends WorkflowStoreError {
61
+ constructor(message) {
62
+ super('index-invalid', message);
63
+ this.name = 'StoreIndexError';
64
+ }
65
+ }
66
+ /** A digest string failed validation (wrong length/case/charset). */
67
+ export class StoreDigestError extends WorkflowStoreError {
68
+ constructor(message) {
69
+ super('digest-invalid', message);
70
+ this.name = 'StoreDigestError';
71
+ }
72
+ }
73
+ /** A coordinate string failed construction/parsing validation. */
74
+ export class StoreCoordinateError extends WorkflowStoreError {
75
+ constructor(message) {
76
+ super('coordinate-invalid', message);
77
+ this.name = 'StoreCoordinateError';
78
+ }
79
+ }
80
+ /**
81
+ * @deprecated Coordinate resolution is project-first and no longer throws this
82
+ * error when project and global indexes name different digests. The export and
83
+ * constructor remain for compatibility with older callers that import or
84
+ * instantiate the error class.
85
+ */
86
+ export class StoreAmbiguityError extends WorkflowStoreError {
87
+ coordinate;
88
+ projectDigest;
89
+ globalDigest;
90
+ constructor(coordinate, projectDigest, globalDigest) {
91
+ super('coordinate-ambiguous', `coordinate '${coordinate}' resolves to different digests in the project store ` +
92
+ `(${projectDigest}) and the global store (${globalDigest}) — ` +
93
+ `resolve the ambiguity explicitly instead of guessing`);
94
+ this.name = 'StoreAmbiguityError';
95
+ this.coordinate = coordinate;
96
+ this.projectDigest = projectDigest;
97
+ this.globalDigest = globalDigest;
98
+ }
99
+ }
100
+ /** The coordinate was not found in any consulted level's index. */
101
+ export class StoreNotFoundError extends WorkflowStoreError {
102
+ coordinate;
103
+ constructor(coordinate) {
104
+ super('coordinate-not-found', `coordinate '${coordinate}' is not in the workflow store index`);
105
+ this.name = 'StoreNotFoundError';
106
+ this.coordinate = coordinate;
107
+ }
108
+ }
109
+ /** An index entry names a digest whose object is missing or failed verification. */
110
+ export class StoreIntegrityError extends WorkflowStoreError {
111
+ digest;
112
+ constructor(code, digest, detail) {
113
+ super(code, `object ${digest}: ${detail}`);
114
+ this.name = 'StoreIntegrityError';
115
+ this.digest = digest;
116
+ }
117
+ }
118
+ /** Installing a coordinate the index already records at a DIFFERENT digest. */
119
+ export class StoreConflictError extends WorkflowStoreError {
120
+ coordinate;
121
+ existingDigest;
122
+ constructor(coordinate, existingDigest) {
123
+ super('coordinate-conflict', `coordinate '${coordinate}' is already recorded at digest ${existingDigest} — ` +
124
+ `an existing coordinate is never silently retargeted to a different digest ` +
125
+ `(use an explicit pin/update)`);
126
+ this.name = 'StoreConflictError';
127
+ this.coordinate = coordinate;
128
+ this.existingDigest = existingDigest;
129
+ }
130
+ }
131
+ /** The required bundle ingestion adapter was not supplied. Fail-closed. */
132
+ export class BundleIngestorUnavailableError extends WorkflowStoreError {
133
+ constructor() {
134
+ super('bundle-ingestor-unavailable', 'bundle ingestion is unavailable: no BundleIngestor adapter is bound — ' +
135
+ 'nothing was staged or committed');
136
+ this.name = 'BundleIngestorUnavailableError';
137
+ }
138
+ }
139
+ /** The required pre-commit signature/policy verifier was not supplied. Fail-closed. */
140
+ export class PreCommitVerifierUnavailableError extends WorkflowStoreError {
141
+ constructor() {
142
+ super('pre-commit-verifier-unavailable', 'pre-commit verification is unavailable: no PreCommitVerifier adapter is bound — ' +
143
+ 'nothing was staged or committed');
144
+ this.name = 'PreCommitVerifierUnavailableError';
145
+ }
146
+ }
147
+ /** A publication signature verdict was refused by the configured definition policy. */
148
+ export class StoreDefinitionVerificationError extends WorkflowStoreError {
149
+ verdict;
150
+ policy;
151
+ coordinate;
152
+ constructor(verdict, policy, coordinate, reason) {
153
+ super('definition-verification-refused', `definition '${coordinate}' was refused by defPolicy=${policy}: ${verdict} — ${reason}`);
154
+ this.name = 'StoreDefinitionVerificationError';
155
+ this.verdict = verdict;
156
+ this.policy = policy;
157
+ this.coordinate = coordinate;
158
+ }
159
+ }
160
+ /** A provenance rule refused a workflow definition before execution or install. */
161
+ export class StoreOriginPolicyError extends WorkflowStoreError {
162
+ coordinate;
163
+ namespace;
164
+ rule;
165
+ verdict;
166
+ constructor(coordinate, namespace, rule, verdict, detail) {
167
+ super('origin-policy-refused', `definition '${coordinate}' was refused by originRules=${rule} for namespace '${namespace}': ${verdict} — ${detail}`);
168
+ this.name = 'StoreOriginPolicyError';
169
+ this.coordinate = coordinate;
170
+ this.namespace = namespace;
171
+ this.rule = rule;
172
+ this.verdict = verdict;
173
+ }
174
+ }
175
+ /** A store root, objects dir, index file, or state path failed a type/symlink guard. */
176
+ export class StorePathError extends WorkflowStoreError {
177
+ constructor(message) {
178
+ super('path-refused', message);
179
+ this.name = 'StorePathError';
180
+ }
181
+ }
182
+ /** Validate a raw string as a {@link DefDigest}; throw {@link StoreDigestError} otherwise. */
183
+ export function defDigest(raw) {
184
+ if (!DIGEST_RE.test(raw)) {
185
+ throw new StoreDigestError(`invalid def digest ${JSON.stringify(raw)} — expected a lowercase 64-char sha256 hex value`);
186
+ }
187
+ return raw;
188
+ }
189
+ /** True when `raw` is a well-formed digest (lowercase 64-hex). */
190
+ export function isDefDigest(raw) {
191
+ return DIGEST_RE.test(raw);
192
+ }
193
+ function validateCoordinateComponent(kind, value) {
194
+ if (value === '') {
195
+ throw new StoreCoordinateError(`invalid coordinate: ${kind} is empty`);
196
+ }
197
+ if (!COORDINATE_COMPONENT_RE.test(value)) {
198
+ throw new StoreCoordinateError(`invalid coordinate: ${kind} ${JSON.stringify(value)} contains a control or path-significant character`);
199
+ }
200
+ }
201
+ /**
202
+ * Construct a validated {@link WorkflowCoordinate} from its three parts.
203
+ * Each part must be non-empty and free of control/path-significant characters;
204
+ * a violation throws {@link StoreCoordinateError}. The full text
205
+ * `namespace/name@version` is returned branded — the ONLY string shape the
206
+ * store accepts as a coordinate key.
207
+ */
208
+ export function workflowCoordinate(parts) {
209
+ validateCoordinateComponent('namespace', parts.namespace);
210
+ validateCoordinateComponent('name', parts.name);
211
+ validateCoordinateComponent('version', parts.version);
212
+ return `${parts.namespace}/${parts.name}@${parts.version}`;
213
+ }
214
+ /**
215
+ * Parse a full `namespace/name@version` coordinate text into its parts. The
216
+ * version is split at the FINAL `@` and the name at the FIRST `/` before it
217
+ * (a namespace/name itself never contains a slash); every component is
218
+ * validated exactly as {@link workflowCoordinate} validates it. A malformed
219
+ * shape throws {@link StoreCoordinateError}. Never used on untrusted input
220
+ * that then bypasses validation — the returned parts are only as safe as this
221
+ * function's checks.
222
+ */
223
+ export function parseWorkflowCoordinate(text) {
224
+ const at = text.lastIndexOf('@');
225
+ if (at <= 0 || at === text.length - 1) {
226
+ throw new StoreCoordinateError(`invalid coordinate ${JSON.stringify(text)} — expected 'namespace/name@version'`);
227
+ }
228
+ const namespaceAndName = text.slice(0, at);
229
+ const version = text.slice(at + 1);
230
+ const slash = namespaceAndName.indexOf('/');
231
+ if (slash <= 0 || slash === namespaceAndName.length - 1) {
232
+ throw new StoreCoordinateError(`invalid coordinate ${JSON.stringify(text)} — expected 'namespace/name@version'`);
233
+ }
234
+ const namespace = namespaceAndName.slice(0, slash);
235
+ const name = namespaceAndName.slice(slash + 1);
236
+ if (name.includes('/')) {
237
+ throw new StoreCoordinateError(`invalid coordinate ${JSON.stringify(text)} — expected exactly one '/' before the version`);
238
+ }
239
+ const coordinate = workflowCoordinate({ namespace, name, version });
240
+ // Defensive round-trip: the reconstructed full text must equal the input —
241
+ // a coordinate is only ever stored/compared in its exact input form.
242
+ if (coordinate !== text) {
243
+ throw new StoreCoordinateError(`invalid coordinate ${JSON.stringify(text)} — non-canonical form`);
244
+ }
245
+ return { namespace, name, version };
246
+ }
247
+ // ---- deterministic ordering and version selection -----------------------------
248
+ /**
249
+ * A total, LOCALE-INDEPENDENT order on store text (coordinates, digests,
250
+ * qualified names). `String.prototype.localeCompare` is deliberately avoided
251
+ * throughout the store: without an explicit locale its result depends on the
252
+ * host's ICU data, so two machines walking the same index could disagree on
253
+ * order.
254
+ *
255
+ * This is UTF-16 code-unit order (JS `<` on strings), which differs from true
256
+ * codepoint order for astral characters. That difference does not matter here:
257
+ * the requirement is a total order identical on every host, not one that
258
+ * matches any particular alphabet.
259
+ *
260
+ * This orders ENUMERATION only. It never decides which version of a package is
261
+ * the current one — {@link selectLatestVersion} owns that and is the store's
262
+ * only version-selection rule.
263
+ */
264
+ export function compareStoreText(a, b) {
265
+ if (a < b)
266
+ return -1;
267
+ if (a > b)
268
+ return 1;
269
+ return 0;
270
+ }
271
+ /**
272
+ * Rank two same-level candidates, BEST FIRST.
273
+ *
274
+ * 1. A canonical SemVer version outranks a non-SemVer one. A version the store
275
+ * cannot order never displaces one it can.
276
+ * 2. Between two canonical SemVer versions, higher SemVer precedence wins
277
+ * (SemVer §11 — so `0.1.10` beats `0.1.2`, and `1.0.0` beats `1.0.0-rc.1`).
278
+ * 3. Otherwise the two are indistinguishable by precedence: either they differ
279
+ * only in build metadata, or neither is SemVer at all. Fall through to raw
280
+ * text, then to the digest, purely so the answer is STABLE. Neither of those
281
+ * last two steps claims to say which version is newer; they exist so the
282
+ * result never depends on index insertion, filesystem, or install order.
283
+ */
284
+ function compareVersionCandidates(a, b) {
285
+ const aOrderable = isCanonicalSemver(a.version);
286
+ const bOrderable = isCanonicalSemver(b.version);
287
+ if (aOrderable !== bOrderable)
288
+ return aOrderable ? -1 : 1;
289
+ if (aOrderable && bOrderable) {
290
+ const byPrecedence = semver.compare(b.version, a.version);
291
+ if (byPrecedence !== 0)
292
+ return byPrecedence;
293
+ }
294
+ const byText = compareStoreText(b.version, a.version);
295
+ if (byText !== 0)
296
+ return byText;
297
+ return compareStoreText(a.digest, b.digest);
298
+ }
299
+ /**
300
+ * Choose the ONE candidate that holds an unqualified `package/workflow` name.
301
+ *
302
+ * Two rules apply in order, and neither consults arrival order:
303
+ *
304
+ * 1. LEVEL FIRST. If any candidate is named by the project index, only project
305
+ * candidates compete. This mirrors `resolveWorkflowCoordinate`, where the
306
+ * project index is the deterministic override: a project install of
307
+ * `pkg@0.1.0` beats a global install of `pkg@0.9.9`, because the project
308
+ * store is how an operator pins a workspace to a specific definition.
309
+ * 2. VERSION SECOND, by {@link compareVersionCandidates}, among the candidates
310
+ * at that one level.
311
+ *
312
+ * When the surviving group holds more than one candidate and none carries a
313
+ * canonical SemVer version, the result is `unorderable` and the unqualified name
314
+ * goes unregistered. A SINGLE non-SemVer candidate still wins its name — there
315
+ * is nothing to order, so refusing it would break `pkg@nightly` installs for no
316
+ * determinism gain.
317
+ */
318
+ export function selectLatestVersion(candidates) {
319
+ if (candidates.length === 0)
320
+ return { kind: 'unorderable', shadowed: [], competing: [] };
321
+ const hasProject = candidates.some((candidate) => candidate.level === 'project');
322
+ const competing = hasProject
323
+ ? candidates.filter((candidate) => candidate.level === 'project')
324
+ : [...candidates];
325
+ const outranked = hasProject
326
+ ? candidates.filter((candidate) => candidate.level !== 'project')
327
+ : [];
328
+ const ranked = [...competing].sort(compareVersionCandidates);
329
+ const best = ranked[0];
330
+ // Rule 1 sorts every orderable candidate ahead of every unorderable one, so a
331
+ // non-SemVer `best` proves the whole competing group is unorderable.
332
+ if (!isCanonicalSemver(best.version) && ranked.length > 1) {
333
+ return { kind: 'unorderable', shadowed: [...ranked, ...outranked], competing: ranked };
334
+ }
335
+ return { kind: 'selected', winner: best, shadowed: [...ranked.slice(1), ...outranked] };
336
+ }
337
+ /** The index filename at a store root. */
338
+ export const WORKFLOW_STORE_INDEX_FILENAME = 'index.json';
339
+ /** The objects subtree at a store root: `objects/sha256/<digest>/`. */
340
+ export const WORKFLOW_OBJECTS_DIRNAME = 'objects';
341
+ /** The digest algorithm directory under `objects/` (sha256 is the only one). */
342
+ export const WORKFLOW_OBJECTS_ALGO = 'sha256';
343
+ /**
344
+ * Derive the object directory for a validated digest under `root`. Digests are
345
+ * validated BEFORE this joins anything: a coordinate or URL must never reach a
346
+ * filesystem path. The digest is a single path segment by construction (64 hex
347
+ * chars), so the join cannot escape `root`.
348
+ */
349
+ export function objectDirForDigest(root, digest) {
350
+ // Re-assert the shape at the derivation site (belt-and-braces; the brand is
351
+ // compile-time only).
352
+ if (!DIGEST_RE.test(digest)) {
353
+ throw new StoreDigestError(`refusing to derive an object path from ${JSON.stringify(digest)}`);
354
+ }
355
+ return join(root, WORKFLOW_OBJECTS_DIRNAME, WORKFLOW_OBJECTS_ALGO, digest);
356
+ }
@@ -123,42 +123,70 @@ export interface TaskData {
123
123
  alarmAt?: number;
124
124
  }
125
125
  /** A run node — audit/budget trail, and the holder of a claim's fingerprint. */
126
- /** A self-contained unit of work emitted by a tick. */
126
+ /**
127
+ * A reference-mode unit of work emitted by a tick (WP-B1). The order is a
128
+ * REFERENCE packet: `defDigest` identifies the pinned definition snapshot
129
+ * that emitted it, and the authored static instruction bytes (prompt,
130
+ * command, acceptance) ride the resolver boundary instead — see
131
+ * `OrderResolver` in order-resolver.ts. An order NEVER carries authored
132
+ * prompt or command text, nor `owes[].acceptance` (the artifact lifecycle
133
+ * state is dynamic engine state, not channel-1 instructions). It does carry
134
+ * the routing/reference fields, the dynamic consumed input values, and the
135
+ * dynamic rejection feedback. One shape serves both local (`owenloop tick`)
136
+ * and embedded/library callers — there is no verify-mode or legacy branch.
137
+ */
127
138
  export interface Order {
128
139
  run: string;
129
140
  workflow: string;
130
141
  step: string;
131
142
  key: string;
132
143
  index?: number;
144
+ /** The digest of the definition snapshot this order was emitted against.
145
+ * Resolves static instructions through the `(defDigest, step, key)`
146
+ * boundary; an unknown digest is a named refusal (UnknownDefDigestError). */
147
+ defDigest: string;
133
148
  inputs: string[];
134
149
  outputs: string[];
135
150
  workdir?: string;
136
151
  model?: string;
137
- /** Declares which kind of executor this order is for. Absent = 'agent'
152
+ /** Declares which kind of worker this order is for. Absent = 'agent'
138
153
  * (today's behavior). Opaque to the engine; carried through verbatim from
139
- * the step definition, same pass-through contract as `model`/`x`. */
140
- executor?: string;
141
- /** The command string for a `executor: command` order. Opaque to the engine
142
- * — never parsed, never shelled out. */
143
- command?: string;
144
- /** Opaque config object for a non-agent/non-command executor type (or
145
- * alongside `command`). Carried through untouched, contents never read. */
154
+ * the authored step's `executor:` field (the YAML grammar is unchanged),
155
+ * same pass-through contract as `model`/`x`. */
156
+ worker?: string;
157
+ /** The artifact stem this order's judge step is verdicting, when present. */
158
+ judge?: string;
159
+ /** Opaque config object for a non-agent/non-command worker type (or
160
+ * alongside a command). Carried through untouched, contents never read. */
146
161
  spec?: Record<string, unknown>;
147
162
  /** §27.3: the step's opaque `x:` extension map, carried through untouched
148
163
  * (same pass-through contract as `model`). The engine never reads it —
149
164
  * it exists for the external runner/tooling consuming this order. */
150
165
  x?: Record<string, unknown>;
151
- prompt: string;
152
166
  /** captured handles of the green inputs this run builds on */
153
167
  consumes: Record<string, unknown>;
168
+ /**
169
+ * The versions of the consumed inputs captured at claim time. Drivers cover
170
+ * this map in a submission signature instead of recomputing it from values.
171
+ */
172
+ consumedFingerprint?: Fingerprint;
154
173
  /** the owed outputs and their accumulated reason threads (the feedback channel) */
155
174
  owes: Array<{
156
175
  path: string;
157
- acceptance: string;
176
+ /** Current committed artifact version captured by the engine at claim time. */
177
+ version?: number;
158
178
  judgmentRejects: number;
159
179
  schemaRejects: number;
160
180
  reasons: ReasonEntry[];
181
+ /** Opaque proof/signature placeholder for future WP-A4-signed reason
182
+ * threads. Data-only today: no cryptographic code attaches or verifies
183
+ * it — the slot exists so signed dynamic data can land without changing
184
+ * the reference-mode wire shape. */
185
+ proof?: string;
161
186
  }>;
187
+ /** Opaque proof/signature placeholder for future WP-A4-signed dynamic
188
+ * consume values. Data-only today — same contract as `owes[].proof`. */
189
+ consumesProof?: string;
162
190
  /** The trigger that woke this firing (§21). Absent = 'inputsGreen'. */
163
191
  cause?: FiringTrigger;
164
192
  }
@@ -335,6 +363,12 @@ export interface StepDef {
335
363
  spec?: Record<string, unknown>;
336
364
  /** opaque location hint passed through on the order; no default — absent unless the def sets it */
337
365
  workdir?: string;
366
+ /**
367
+ * Resolve the order's workdir from `<consumedStem>.<dotted.path>` in a consumed
368
+ * artifact value. Mutually exclusive with workdir; the stem must be a plain
369
+ * consume so the value passes the engine's consume-side verification gate.
370
+ */
371
+ workdirFrom?: string;
338
372
  /** the step's output is a destructive completion (e.g. a merge): green is terminal (§15.2) */
339
373
  terminal?: boolean;
340
374
  /** Step-level effect contract (§6.5). Only consulted for non-terminal greens whose inputs move. */
@@ -9,30 +9,15 @@
9
9
  * it would be silently skipped (unrepresentable, not corrupt).
10
10
  *
11
11
  * This is intentionally narrow: just enough tar to unpack a GitHub tarball,
12
- * not a general-purpose tar library.
12
+ * not a general-purpose tar library. The parsing, resource limits, and path
13
+ * policy live in `src/archive.ts` (the ONE shared archive boundary, also
14
+ * used by `src/bundle/` and `src/add.ts`); this module keeps the historical
15
+ * `extractTarGz` API and compatible reading behavior.
13
16
  */
14
- /**
15
- * Resource bounds enforced while unpacking a tarball. Defaults are sized for
16
- * GitHub codeload output and are deliberately generous; tests inject tiny
17
- * values to exercise the limits without building giant fixtures.
18
- *
19
- * - `maxCompressedBytes` (256 MiB): the buffered tarball download itself.
20
- * - `maxExpandedBytes` (1 GiB): total inflated size — kills gzip bombs at
21
- * inflate time. GitHub's own recommended repo size sits comfortably below.
22
- * - `maxFileCount` (50k): number of regular files kept.
23
- * - `maxFileBytes` (100 MiB): GitHub blocks pushing files larger than this,
24
- * and LFS content is never in the tarball, so no legit entry exceeds it.
25
- * - `maxPathLength` (1024): guards against absurdly long entry paths (pax or
26
- * USTAR prefix-composed) before they are ever used as a filesystem path.
27
- */
28
- export interface TarLimits {
29
- maxCompressedBytes: number;
30
- maxExpandedBytes: number;
31
- maxFileCount: number;
32
- maxFileBytes: number;
33
- maxPathLength: number;
34
- }
35
- export declare const DEFAULT_TAR_LIMITS: TarLimits;
17
+ import { DEFAULT_TAR_LIMITS } from './archive.ts';
18
+ import type { TarLimits } from './archive.ts';
19
+ export type { TarLimits };
20
+ export { DEFAULT_TAR_LIMITS };
36
21
  /**
37
22
  * Extract a gzipped tar archive into a flat map of in-archive path → file
38
23
  * bytes. Directory entries are dropped; only regular files are kept. Pax
package/dist/src/untar.js CHANGED
@@ -9,59 +9,13 @@
9
9
  * it would be silently skipped (unrepresentable, not corrupt).
10
10
  *
11
11
  * This is intentionally narrow: just enough tar to unpack a GitHub tarball,
12
- * not a general-purpose tar library.
12
+ * not a general-purpose tar library. The parsing, resource limits, and path
13
+ * policy live in `src/archive.ts` (the ONE shared archive boundary, also
14
+ * used by `src/bundle/` and `src/add.ts`); this module keeps the historical
15
+ * `extractTarGz` API and compatible reading behavior.
13
16
  */
14
- import { gunzipSync } from 'node:zlib';
15
- const BLOCK = 512;
16
- export const DEFAULT_TAR_LIMITS = {
17
- maxCompressedBytes: 256 * 1024 * 1024,
18
- maxExpandedBytes: 1024 * 1024 * 1024,
19
- maxFileCount: 50_000,
20
- maxFileBytes: 100 * 1024 * 1024,
21
- maxPathLength: 1024,
22
- };
23
- /** Parse a NUL/space-padded octal field (tar's numeric encoding) into a number. */
24
- function parseOctal(bytes) {
25
- let s = '';
26
- for (const b of bytes) {
27
- if (b === 0 || b === 32 /* space */)
28
- continue;
29
- s += String.fromCharCode(b);
30
- }
31
- return s.length ? parseInt(s, 8) : 0;
32
- }
33
- function readCString(bytes) {
34
- const nul = bytes.indexOf(0);
35
- const slice = nul >= 0 ? bytes.subarray(0, nul) : bytes;
36
- return Buffer.from(slice).toString('utf8');
37
- }
38
- /** Parse a pax extended-header data block's `key=value` records, e.g. `path=...`. */
39
- function parsePaxRecords(data) {
40
- const text = Buffer.from(data).toString('utf8');
41
- const out = new Map();
42
- let i = 0;
43
- while (i < text.length) {
44
- // Each record is "<len> <key>=<value>\n", <len> counts the whole record
45
- // (including the length prefix itself and the trailing newline).
46
- const spaceIdx = text.indexOf(' ', i);
47
- if (spaceIdx < 0)
48
- break;
49
- const len = parseInt(text.slice(i, spaceIdx), 10);
50
- if (!Number.isFinite(len) || len <= 0)
51
- break;
52
- const record = text.slice(i, i + len);
53
- const eq = record.indexOf('=', spaceIdx - i + 1);
54
- if (eq >= 0) {
55
- const key = record.slice(spaceIdx - i + 1, eq);
56
- // record.slice(eq + 1) still has the trailing '\n' the pax format
57
- // mandates — strip it to get the bare value.
58
- const value = record.slice(eq + 1).replace(/\n$/, '');
59
- out.set(key, value);
60
- }
61
- i += len;
62
- }
63
- return out;
64
- }
17
+ import { DEFAULT_TAR_LIMITS, inflateArchive, parseTar } from "./archive.js";
18
+ export { DEFAULT_TAR_LIMITS };
65
19
  /**
66
20
  * Extract a gzipped tar archive into a flat map of in-archive path → file
67
21
  * bytes. Directory entries are dropped; only regular files are kept. Pax
@@ -75,90 +29,10 @@ function parsePaxRecords(data) {
75
29
  */
76
30
  export function extractTarGz(bytes, limits = {}) {
77
31
  const lim = { ...DEFAULT_TAR_LIMITS, ...limits };
78
- if (bytes.length > lim.maxCompressedBytes) {
79
- throw new Error(`compressed archive size ${bytes.length} exceeds limit of ${lim.maxCompressedBytes} bytes`);
80
- }
81
- let tar;
82
- try {
83
- // maxOutputLength caps the inflated size — a gzip bomb aborts here with
84
- // ERR_BUFFER_TOO_LARGE rather than exhausting memory.
85
- tar = gunzipSync(bytes, { maxOutputLength: lim.maxExpandedBytes });
86
- }
87
- catch (e) {
88
- if (e.code === 'ERR_BUFFER_TOO_LARGE') {
89
- throw new Error(`expanded archive size exceeds limit of ${lim.maxExpandedBytes} bytes`);
90
- }
91
- throw e;
92
- }
32
+ const tar = inflateArchive(bytes, lim);
33
+ const entries = parseTar(tar, lim, { policy: 'compatible' });
93
34
  const out = new Map();
94
- let offset = 0;
95
- let fileCount = 0;
96
- let pendingLongPath;
97
- while (offset + BLOCK <= tar.length) {
98
- const header = tar.subarray(offset, offset + BLOCK);
99
- // Two consecutive all-zero blocks mark the end of the archive.
100
- if (header.every((b) => b === 0))
101
- break;
102
- const nameField = readCString(header.subarray(0, 100));
103
- const sizeField = parseOctal(header.subarray(124, 136));
104
- const typeflag = String.fromCharCode(header[156] ?? 0);
105
- const prefixField = readCString(header.subarray(345, 500));
106
- // parseOctal on a corrupt size field can yield NaN; a valid entry is a
107
- // non-negative integer.
108
- if (!Number.isInteger(sizeField) || sizeField < 0) {
109
- throw new Error(`corrupt tar header: invalid size field (got ${sizeField})`);
110
- }
111
- offset += BLOCK;
112
- const dataStart = offset;
113
- const dataEnd = dataStart + sizeField;
114
- // subarray silently clamps a past-the-end range, so a truncated archive
115
- // would otherwise yield a short read instead of an error — guard it.
116
- if (dataEnd > tar.length) {
117
- throw new Error(`corrupt tar archive: entry data (${sizeField} bytes) extends past end of archive`);
118
- }
119
- const data = tar.subarray(dataStart, dataEnd);
120
- // Data is padded up to the next 512-byte boundary.
121
- offset += Math.ceil(sizeField / BLOCK) * BLOCK;
122
- if (typeflag === '5') {
123
- // directory — nothing to keep
124
- continue;
125
- }
126
- if (typeflag === 'g') {
127
- // pax global extended header — applies to the whole archive; we don't
128
- // need any of its records (uid/gid/etc), just skip its data.
129
- continue;
130
- }
131
- if (typeflag === 'x') {
132
- // pax extended header for the NEXT entry — currently only 'path' matters.
133
- const records = parsePaxRecords(data);
134
- const p = records.get('path');
135
- if (p !== undefined)
136
- pendingLongPath = p;
137
- continue;
138
- }
139
- if (typeflag !== '0' && typeflag !== '\0') {
140
- // unsupported typeflag (symlink, hardlink, GNU longname, ...) — skip.
141
- pendingLongPath = undefined;
142
- continue;
143
- }
144
- // Regular file.
145
- if (sizeField > lim.maxFileBytes) {
146
- throw new Error(`archive entry exceeds per-file size limit of ${lim.maxFileBytes} bytes (${sizeField} bytes)`);
147
- }
148
- // Validate the FINAL, fully-resolved name (pax 'path' override or USTAR
149
- // prefix+name), not the raw 100-byte field — that is what a caller joins.
150
- const name = pendingLongPath ?? (prefixField ? `${prefixField}/${nameField}` : nameField);
151
- pendingLongPath = undefined;
152
- if (name) {
153
- if (name.length > lim.maxPathLength) {
154
- throw new Error(`archive entry path length ${name.length} exceeds limit of ${lim.maxPathLength} chars`);
155
- }
156
- fileCount += 1;
157
- if (fileCount > lim.maxFileCount) {
158
- throw new Error(`archive file count exceeds limit of ${lim.maxFileCount}`);
159
- }
160
- out.set(name, new Uint8Array(data));
161
- }
162
- }
35
+ for (const e of entries)
36
+ out.set(e.path, e.data);
163
37
  return out;
164
38
  }