owenloop 0.2.0 → 0.3.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.
package/dist/hub.js ADDED
@@ -0,0 +1,408 @@
1
+ /**
2
+ * Pure, unit-testable helpers for the hub-onboarding CLI verbs (`owenloop
3
+ * login` / `connect` / `push` / `logout`) — the client half of connecting the
4
+ * open-source engine to the hosted control plane.
5
+ *
6
+ * Same split as `src/add.ts`: the network-free, filesystem-adjacent pieces live
7
+ * here (origin normalization, PKCE, credential + project-binding (de)serialization
8
+ * with strict file-mode enforcement, server-diff computation, API-response shape
9
+ * guards); the async network + arg glue lives in `src/cli.ts` (`dispatchLogin`
10
+ * etc.) so this module stays trivially testable and `cli.ts` doesn't widen its
11
+ * export surface.
12
+ *
13
+ * `.owenloop/hub.json` is a pure binding (which hub this project publishes to)
14
+ * — there is no client-side push ledger. `push` diffs local defs against the
15
+ * server's own `hash` (`GET /api/workflows`, see `computeServerDiff`), and
16
+ * `POST /api/create_workflow` is idempotent, so the server is always the
17
+ * source of truth for "did this change" — a client-side cache would just be a
18
+ * second copy of that truth that can go stale.
19
+ *
20
+ * Secret hygiene is a hard rule here: credentials never land in the repo or a
21
+ * plaintext `.env`. The 0600 file backend below (dir 0700) lives under the
22
+ * user's config dir, never the project; all paths derive from the
23
+ * caller-supplied `env` (HOME / XDG_CONFIG_HOME), never `process.env` directly,
24
+ * so tests fixture `$HOME` and never touch ambient machine state. Both this
25
+ * file and `.owenloop/hub.json` are written via `writeFileAtomic` — temp file
26
+ * in the same dir + rename, refusing a symlinked destination (SEC-3). The
27
+ * parent-directory half of that guard is `mkdirRefusingSymlink` (in `util.ts`,
28
+ * so the core store factory can share it without core depending on this hub
29
+ * module): before creating the project `.owenloop` dir we refuse a symlinked
30
+ * `.owenloop` component, so a hostile checkout shipping `.owenloop -> /elsewhere`
31
+ * cannot redirect the write outside the project even though the final file
32
+ * itself is not (yet) a symlink.
33
+ *
34
+ * The server-parity def content hash (`hashDefForHub`) also lives here: it is a
35
+ * hub-facing concern (reproducing owenloop-service's canonicalization for the
36
+ * `push` diff), so keeping it in this module — not in engine core — is what
37
+ * lets `defs.ts` stay host/hub-agnostic.
38
+ */
39
+ import { createHash, randomBytes } from 'node:crypto';
40
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
41
+ import { basename, dirname, join } from 'node:path';
42
+ import { parse as parseYaml } from 'yaml';
43
+ import { hashDef, parseDef } from "./defs.js";
44
+ import { mkdirRefusingSymlink } from "./util.js";
45
+ // ---- server-parity def content hash ------------------------------------------
46
+ /**
47
+ * Reproduce the hub service's def content hash for the CLI `push` diff
48
+ * (`owenloop-service` `apps/hub-edge/README.md`, "Hub API parity for CLI"):
49
+ * `sha256(JSON.stringify(parseDef(YAML.parse(yaml))))` sliced to 16 hex
50
+ * chars, computed with **no `baseDir`** — the compiled def (defaults filled),
51
+ * exactly as the server computes it when it has no stored `defs` row. Taking
52
+ * no `baseDir` is deliberate, not an oversight: it means `parseDef` throws a
53
+ * `DefError` on any def using `bodyFile:` ("bodyFile requires a workflow
54
+ * loaded from disk"), which is exactly the server's own limitation — such a
55
+ * def can't be pushed as raw YAML anyway, so the caller should catch that and
56
+ * refuse the push with a clear reason, the same way it already refuses an
57
+ * `include:` def.
58
+ *
59
+ * Stable only per pinned engine version: the service pins its `parseDef`/
60
+ * `hashDef` lineage to a specific commit (`VENDORED_SHA`). As of writing that
61
+ * commit is an ancestor of this repo's `HEAD` with no changes to
62
+ * `parseDef`/`buildDef`/`hashDef` in between, so a locally computed hash
63
+ * currently matches the server's — but a future engine default change could
64
+ * make them drift. A drifted hash reads as `changed`, not an error: pushing
65
+ * converges state, because the server's own idempotent `create_workflow`
66
+ * still recognizes byte-identical content and replies `unchanged: true`.
67
+ */
68
+ export function hashDefForHub(yaml) {
69
+ return hashDef(parseDef(parseYaml(yaml)));
70
+ }
71
+ // ---- origin normalization ----------------------------------------------------
72
+ /**
73
+ * Loopback hosts allowed to use plaintext `http` for local development. Exact
74
+ * hostname match: WHATWG `URL` already lowercases hostnames (`HTTP://LOCALHOST`
75
+ * → `localhost`), canonicalizes IPv4 shorthand (`http://127.1` → `127.0.0.1`),
76
+ * and keeps the brackets on IPv6 (`http://[::1]` → `[::1]`), so a bare set
77
+ * membership on `url.hostname` is correct and needs no range parsing.
78
+ *
79
+ * Deliberately NOT the whole `127.0.0.0/8` range nor `*.localhost` subdomains —
80
+ * the exact enumeration the transport policy names (SEC-2). `http://127.0.0.2`
81
+ * and `http://192.168.x.x` are remote for this purpose and rejected. Conservative
82
+ * and cheap to widen later (a two-way door).
83
+ */
84
+ const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
85
+ /**
86
+ * Normalize a hub URL to a bare origin (`scheme://host[:port]`), stripping any
87
+ * path, query, trailing slash, and fragment. Requires an http(s) scheme. This
88
+ * is the credential-store key and the project binding value, so it must be
89
+ * canonical: `https://api.owenloop.com/` and `https://api.owenloop.com/foo`
90
+ * both key to `https://api.owenloop.com`.
91
+ *
92
+ * Transport policy (SEC-2): `https` is required for every hub origin EXCEPT the
93
+ * loopback hosts (`127.0.0.1`, `::1`, `localhost`), which may use `http` for
94
+ * local development. Remote `http` is rejected here, at normalization time, so a
95
+ * plaintext origin that would leak bearer/refresh tokens, auth codes, and
96
+ * workflow YAML to an on-path attacker can never be persisted into a credential
97
+ * key or a project binding.
98
+ */
99
+ export function normalizeOrigin(input) {
100
+ const trimmed = input.trim();
101
+ if (trimmed === '')
102
+ throw new Error('hub url is empty');
103
+ let url;
104
+ try {
105
+ url = new URL(trimmed);
106
+ }
107
+ catch {
108
+ throw new Error(`invalid hub url '${input}' — expected an http(s) URL`);
109
+ }
110
+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {
111
+ throw new Error(`invalid hub url '${input}' — must be http or https, got '${url.protocol}'`);
112
+ }
113
+ if (url.protocol === 'http:' && !LOOPBACK_HOSTS.has(url.hostname)) {
114
+ throw new Error(`invalid hub url '${input}' — http is only allowed for loopback hosts (127.0.0.1, ::1, localhost); use https`);
115
+ }
116
+ return url.origin;
117
+ }
118
+ /**
119
+ * Join an origin and an endpoint that may be absolute or a root-relative path,
120
+ * enforcing the same-origin policy for OAuth discovery metadata (SEC-4).
121
+ *
122
+ * This is the trust boundary for every endpoint consumed from OAuth metadata —
123
+ * authorization, token, and registration endpoints all flow through here, as do
124
+ * the CLI's own literal root-relative API paths. A metadata-derived absolute
125
+ * endpoint is allowed, but must resolve to the SAME origin as the hub; a
126
+ * cross-origin (or protocol-relative `//host`) endpoint is rejected so a
127
+ * discovered `token_endpoint` on a foreign origin can never receive a refresh
128
+ * token. Path and query are preserved — only `.origin` is compared. The
129
+ * https-except-loopback rule holds for free: `origin` here is already a
130
+ * `normalizeOrigin` output at every call site, so same-origin implies the
131
+ * transport policy.
132
+ */
133
+ export function resolveEndpoint(origin, endpoint) {
134
+ const resolved = new URL(endpoint, `${origin}/`);
135
+ if (resolved.origin !== origin) {
136
+ throw new Error(`refusing endpoint '${endpoint}' — it resolves to origin ${resolved.origin}, not the hub origin ${origin}`);
137
+ }
138
+ return resolved.toString();
139
+ }
140
+ // ---- PKCE (RFC 7636) + state -------------------------------------------------
141
+ /** URL-safe base64 with no padding (RFC 7636 §A). */
142
+ export function base64url(buf) {
143
+ return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
144
+ }
145
+ /**
146
+ * Generate a PKCE verifier/challenge pair for the S256 method. The verifier is
147
+ * 32 random bytes base64url-encoded (43 chars — within the RFC's 43..128 range
148
+ * and drawn from the unreserved charset); the challenge is
149
+ * base64url(sha256(verifier)).
150
+ */
151
+ export function pkcePair() {
152
+ const verifier = base64url(randomBytes(32));
153
+ const challenge = base64url(createHash('sha256').update(verifier).digest());
154
+ return { verifier, challenge };
155
+ }
156
+ /** A random anti-CSRF `state` token for the authorization request. */
157
+ export function randomState() {
158
+ return base64url(randomBytes(16));
159
+ }
160
+ /** The user-level config dir (never the project dir). Derives from the caller's env. */
161
+ export function configDir(env) {
162
+ const xdg = env.XDG_CONFIG_HOME;
163
+ if (xdg && xdg.trim() !== '')
164
+ return join(xdg, 'owenloop');
165
+ const home = env.HOME;
166
+ if (home && home.trim() !== '')
167
+ return join(home, '.config', 'owenloop');
168
+ throw new Error('cannot locate a config directory: set HOME or XDG_CONFIG_HOME');
169
+ }
170
+ export function credentialFilePath(env) {
171
+ return join(configDir(env), 'credentials.json');
172
+ }
173
+ /** Read the credential file; a missing file is an empty store, not an error. */
174
+ export function readCredentialFile(path) {
175
+ if (!existsSync(path))
176
+ return { version: 1, hubs: {} };
177
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
178
+ if (!parsed || typeof parsed !== 'object' || typeof parsed.hubs !== 'object') {
179
+ throw new Error(`malformed credential file at ${path}`);
180
+ }
181
+ return { version: 1, hubs: parsed.hubs };
182
+ }
183
+ /**
184
+ * Write `data` to `path` atomically, refusing a symlinked (or directory)
185
+ * destination (SEC-3).
186
+ *
187
+ * 1. `lstat` the destination: if it already exists AND is a symlink, throw a
188
+ * clear error naming the path rather than clobbering the arbitrary,
189
+ * possibly-privileged file the link points at. A pre-existing directory is
190
+ * likewise refused with a named error (instead of a raw ENOTDIR from
191
+ * rename).
192
+ * 2. Write to a temp file in the SAME directory (same-dir is required — a
193
+ * cross-filesystem rename is not atomic), then `chmod` the temp to `mode`
194
+ * BEFORE the rename so the final file never momentarily exists with a lax,
195
+ * umask-widened mode (preserving the old "re-chmod on every write"
196
+ * guarantee, now applied to the temp).
197
+ * 3. `rename(tmp, path)` — an atomic replace. On any failure after the temp
198
+ * exists, best-effort unlink the temp and rethrow.
199
+ *
200
+ * The `lstat` check is a courtesy clear-error, not the security boundary:
201
+ * `rename` replaces the destination inode rather than following it, so even a
202
+ * symlink raced into place between the `lstat` and the `rename` is replaced,
203
+ * never followed — the write can never escape to the link target.
204
+ */
205
+ export function writeFileAtomic(path, data, opts) {
206
+ const existing = lstatSync(path, { throwIfNoEntry: false });
207
+ if (existing?.isSymbolicLink()) {
208
+ throw new Error(`refusing to write ${path}: it is a symbolic link`);
209
+ }
210
+ if (existing?.isDirectory()) {
211
+ throw new Error(`refusing to write ${path}: it is a directory`);
212
+ }
213
+ const tmp = join(dirname(path), `.${basename(path)}.${randomBytes(6).toString('hex')}.tmp`);
214
+ try {
215
+ writeFileSync(tmp, data, opts?.mode !== undefined ? { mode: opts.mode } : undefined);
216
+ if (opts?.mode !== undefined)
217
+ chmodSync(tmp, opts.mode);
218
+ renameSync(tmp, path);
219
+ }
220
+ catch (e) {
221
+ rmSync(tmp, { force: true });
222
+ throw e;
223
+ }
224
+ }
225
+ /**
226
+ * Write the credential file with strict permissions: dir 0700, file 0600.
227
+ * The file itself is written atomically via `writeFileAtomic` (temp + rename),
228
+ * which also chmods the temp to 0600 before the rename — so the secret is
229
+ * never visible under a laxer mode, even briefly, and a symlinked destination
230
+ * is refused (SEC-3).
231
+ */
232
+ export function writeCredentialFile(path, file) {
233
+ const dir = dirname(path);
234
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
235
+ chmodSync(dir, 0o700);
236
+ writeFileAtomic(path, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o600 });
237
+ }
238
+ export function hubBindingPath(cwd) {
239
+ return join(cwd, '.owenloop', 'hub.json');
240
+ }
241
+ /**
242
+ * Read `.owenloop/hub.json`; a missing file is `null` (project not bound
243
+ * yet). A file written by a pre-server-diff CLI may still carry a `pushed`
244
+ * key (the old push ledger) — it parses fine and the key is silently
245
+ * ignored; the next `connect` rewrite drops it.
246
+ */
247
+ export function readHubBinding(path) {
248
+ if (!existsSync(path))
249
+ return null;
250
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
251
+ if (!parsed || typeof parsed.hub !== 'string') {
252
+ throw new Error(`malformed hub binding at ${path}`);
253
+ }
254
+ return { version: 1, hub: parsed.hub };
255
+ }
256
+ export function writeHubBinding(path, binding) {
257
+ // Refuse a symlinked `.owenloop` parent (SEC-3, parent-directory half): a
258
+ // hostile checkout can ship `.owenloop -> /elsewhere` to redirect this write
259
+ // outside the project. Unconditional — this function only ever writes the
260
+ // project binding, so there is no operator-supplied override to honor.
261
+ mkdirRefusingSymlink(dirname(path));
262
+ // Atomic + symlink-refusing on the FILE (SEC-3). Default mode — hub.json
263
+ // carries no secrets and is deliberately committable.
264
+ writeFileAtomic(path, `${JSON.stringify(binding, null, 2)}\n`);
265
+ }
266
+ /**
267
+ * Partition selected defs into those that need pushing vs. those already
268
+ * up-to-date, purely from the server's own `hash` for each name (from
269
+ * `GET /api/workflows`, via `parseWorkflowList`): a name absent from the
270
+ * server is `new`; present with a different (or missing) hash is `changed`;
271
+ * present with an equal hash is `unchanged` (skipped — no request sent).
272
+ *
273
+ * `force` pushes every candidate regardless of hash — labeled `new` when the
274
+ * server has no entry for it, `changed` otherwise (even when the hash is
275
+ * equal: force means "send it", and the label should still read true).
276
+ *
277
+ * Server names with no local counterpart are ignored (this is a push, not a
278
+ * sync — the CLI never deletes or reports on hub-only defs).
279
+ */
280
+ export function computeServerDiff(candidates, server, force) {
281
+ const toPush = [];
282
+ const unchanged = [];
283
+ for (const c of candidates) {
284
+ const remote = server.get(c.name);
285
+ const status = remote === undefined ? 'new' : 'changed';
286
+ if (force) {
287
+ toPush.push({ ...c, status });
288
+ }
289
+ else if (remote === undefined) {
290
+ toPush.push({ ...c, status: 'new' });
291
+ }
292
+ else if (remote.hash !== c.hash) {
293
+ toPush.push({ ...c, status: 'changed' });
294
+ }
295
+ else {
296
+ unchanged.push(c);
297
+ }
298
+ }
299
+ return { toPush, unchanged };
300
+ }
301
+ /**
302
+ * `POST /api/create_workflow` returns HTTP 200 with `{ok:false,error}` on a
303
+ * def-parse failure (engine-version skew is the realistic cause) — so a 200 is
304
+ * NOT sufficient; the body's `ok` must be inspected. Returns the parsed error
305
+ * text (verbatim) when the reply is a failure, or `null` when it is a success.
306
+ */
307
+ export function createWorkflowError(body) {
308
+ if (typeof body !== 'object' || body === null)
309
+ return 'unexpected response shape (not an object)';
310
+ const b = body;
311
+ if (b.ok === true)
312
+ return null;
313
+ const err = typeof b.error === 'string' ? b.error : 'unknown error';
314
+ return err;
315
+ }
316
+ /**
317
+ * Narrow a create_workflow success body to its typed shape (after
318
+ * `createWorkflowError` returns null), validating STRICTLY (REL-9): a 2xx with
319
+ * `ok:true` is not enough — the identity fields must be present, well-typed, and
320
+ * consistent with the def that was pushed, or the "success" is a malformed
321
+ * response and must be treated as a failure, not silently coerced to defaults.
322
+ *
323
+ * - `name` must be a string equal to `expectedName` (the pushed def's name) —
324
+ * a mismatch means the server acknowledged the wrong workflow.
325
+ * - `version` must be a positive integer (the server mints versions from 1).
326
+ * - `hash` must be a non-empty string. Presence and type only: it is NOT
327
+ * required to equal the locally computed `hashDefForHub`, because engine
328
+ * drift between CLI and hub legitimately produces differing hashes (see
329
+ * `hashDefForHub`'s doc comment).
330
+ * - `unchanged: true` passes through as an idempotent no-op, validated by the
331
+ * same field rules.
332
+ *
333
+ * Throws a descriptive `Error` (mirroring `asWhoami`'s throw-on-malformed style)
334
+ * on any violation; the caller records it as a per-def failure.
335
+ */
336
+ export function asCreateWorkflowOk(body, expectedName) {
337
+ if (typeof body !== 'object' || body === null) {
338
+ throw new Error('create_workflow: malformed success response — not an object');
339
+ }
340
+ const b = body;
341
+ if (typeof b.name !== 'string') {
342
+ throw new Error('create_workflow: malformed success response — missing string name');
343
+ }
344
+ if (b.name !== expectedName) {
345
+ throw new Error(`create_workflow: malformed success response — name '${b.name}' does not match pushed def '${expectedName}'`);
346
+ }
347
+ if (typeof b.version !== 'number' || !Number.isInteger(b.version) || b.version < 1) {
348
+ throw new Error('create_workflow: malformed success response — version must be a positive integer');
349
+ }
350
+ if (typeof b.hash !== 'string' || b.hash === '') {
351
+ throw new Error('create_workflow: malformed success response — missing non-empty hash');
352
+ }
353
+ const out = { ok: true, name: b.name, version: b.version, hash: b.hash };
354
+ if (b.unchanged === true)
355
+ out.unchanged = true;
356
+ return out;
357
+ }
358
+ /** Narrow a `GET /api/whoami` 200 body to its typed shape. Throws on a malformed body. */
359
+ export function asWhoami(body) {
360
+ if (typeof body !== 'object' || body === null)
361
+ throw new Error('whoami: unexpected response shape (not an object)');
362
+ const b = body;
363
+ if (typeof b.orgId !== 'string')
364
+ throw new Error('whoami: response missing string orgId');
365
+ const rawActor = (typeof b.actor === 'object' && b.actor !== null ? b.actor : {});
366
+ const identity = {
367
+ orgId: b.orgId,
368
+ orgName: typeof b.orgName === 'string' ? b.orgName : '',
369
+ actor: {
370
+ id: typeof rawActor.id === 'string' ? rawActor.id : '',
371
+ kind: typeof rawActor.kind === 'string' ? rawActor.kind : '',
372
+ role: typeof rawActor.role === 'string' ? rawActor.role : '',
373
+ },
374
+ authMethod: typeof b.authMethod === 'string' ? b.authMethod : '',
375
+ };
376
+ if (typeof b.email === 'string')
377
+ identity.email = b.email;
378
+ return identity;
379
+ }
380
+ /**
381
+ * Parse `GET /api/workflows`'s body into a `name -> WorkflowSummary` map for
382
+ * `computeServerDiff`. Throws a descriptive error (the caller wraps it in a
383
+ * `CliError`) on a missing/malformed `workflows` array.
384
+ */
385
+ export function parseWorkflowList(body) {
386
+ if (typeof body !== 'object' || body === null || !Array.isArray(body.workflows)) {
387
+ throw new Error('malformed response from the hub: expected a `workflows` array');
388
+ }
389
+ const list = body.workflows;
390
+ const out = new Map();
391
+ list.forEach((entry, i) => {
392
+ if (typeof entry !== 'object' || entry === null) {
393
+ throw new Error(`malformed response from the hub: workflows[${i}] is not an object`);
394
+ }
395
+ const e = entry;
396
+ if (typeof e.name !== 'string') {
397
+ throw new Error(`malformed response from the hub: workflows[${i}] missing string name`);
398
+ }
399
+ const summary = {
400
+ name: e.name,
401
+ hash: typeof e.hash === 'string' ? e.hash : '',
402
+ };
403
+ if (typeof e.version === 'number')
404
+ summary.version = e.version;
405
+ out.set(e.name, summary);
406
+ });
407
+ return out;
408
+ }
package/dist/index.d.ts CHANGED
@@ -12,12 +12,13 @@
12
12
  * process — software delivery, research, triage — on top of it.
13
13
  */
14
14
  export { Engine } from './engine.ts';
15
- export type { CommitResult, CreateOpts, DefResolver, DeferredFiring, DeferredReason, EmitResult, EngineEvent, EngineListener, EngineWorkflowStatus, Order, TickResult, } from './engine.ts';
15
+ export type { CommitResult, CreateOpts, DefResolver, DeferredFiring, DeferredReason, EmitResult, EngineEvent, EngineListener, EngineWorkflowStatus, Order, ReapDetail, ReapReason, TickResult, } from './engine.ts';
16
16
  export { createEngine } from './factory.ts';
17
17
  export type { CreateEngineOpts, CreatedEngine } from './factory.ts';
18
18
  export { Store, openStore, StoreVersionError } from './store.ts';
19
19
  export type { ArtifactRow, RunRow, TaskRow, WorkflowRow } from './store.ts';
20
- export { buildDef, DefError, expandIncludes, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, SUPPORTED_ENGINE_VERSION, validateDef } from './defs.ts';
20
+ export { buildDef, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, SUPPORTED_ENGINE_VERSION, validateDef } from './defs.ts';
21
+ export { hashDefForHub } from './hub.ts';
21
22
  export type { DefLoadFailure } from './defs.ts';
22
23
  export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from './model.ts';
23
24
  export type { ArtifactMap, Blocker, Firing, TimeFacts, WorkflowStatus } from './model.ts';
package/dist/index.js CHANGED
@@ -14,7 +14,8 @@
14
14
  export { Engine } from "./engine.js";
15
15
  export { createEngine } from "./factory.js";
16
16
  export { Store, openStore, StoreVersionError } from "./store.js";
17
- export { buildDef, DefError, expandIncludes, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, SUPPORTED_ENGINE_VERSION, validateDef } from "./defs.js";
17
+ export { buildDef, DefError, expandIncludes, finalizeDefs, hashDef, lintDef, loadDefFile, loadDefs, loadDefsRaw, parseDef, SUPPORTED_ENGINE_VERSION, validateDef } from "./defs.js";
18
+ export { hashDefForHub } from "./hub.js";
18
19
  export { buildGraph, buildTrace, eligibleFirings, graphToDot, graphToMermaid, isStalled, modelCheck, workflowStatus, } from "./model.js";
19
20
  export { parseConsume, parseProduce, } from "./paths.js";
20
21
  export { assertValidSchema, summarizeIssues, validateValue } from "./schema.js";
package/dist/model.d.ts CHANGED
@@ -191,6 +191,31 @@ export interface Blocker {
191
191
  step: string;
192
192
  blockedOn: string[];
193
193
  }
194
+ /**
195
+ * A compact summary of a `calls:` child instance, attached to the parent's
196
+ * `calls:` debt by `Engine.status()`. A pure data shape (no logic) so it can
197
+ * live here next to `WorkflowStatus` — the `debts[]` entry type references it,
198
+ * and `model.ts` imports nothing from `engine.ts`, which avoids a source cycle.
199
+ * All the instance-crossing work that populates it (resolving the child def,
200
+ * reading the child's artifacts, recursing along the unpaid `calls:` path)
201
+ * stays in `engine.ts`; `workflowStatus` never sets it.
202
+ * - `workflow` — the child instance id (the handle a human uses to inspect /
203
+ * `retry` the child).
204
+ * - `def` — the child def name.
205
+ * - `done` — the child's own done-ness.
206
+ * - `stalled` — true when the child (or, recursively, any descendant on ITS
207
+ * unpaid `calls:` path) has a stalled debt; lets a grandchild stall surface
208
+ * as `child.stalled: true` on the root debt.
209
+ * - `debts` — a COUNT of the child's own debts (the `workflow` id is the
210
+ * inspection handle for the detail).
211
+ */
212
+ export interface ChildStatusSummary {
213
+ workflow: string;
214
+ def: string;
215
+ done: boolean;
216
+ stalled: boolean;
217
+ debts: number;
218
+ }
194
219
  export interface WorkflowStatus {
195
220
  done: boolean;
196
221
  debts: Array<{
@@ -212,6 +237,17 @@ export interface WorkflowStatus {
212
237
  * Absent when zero or unknown.
213
238
  */
214
239
  attempts?: number;
240
+ /**
241
+ * §23.6.8: when this debt is a `calls:` step's produced artifact and a
242
+ * child instance has been spawned, a summary of that child (id, def,
243
+ * done-ness, recursive stall flag, own-debt count). Engine-enriched from
244
+ * the cross-instance store like `failedRuns`/`attempts` — populated only
245
+ * by `Engine.status()`, never by the pure `workflowStatus`. Absent when
246
+ * the debt is not a `calls:` artifact, no child exists yet, or the child's
247
+ * def is unresolvable (unpinned row whose def was removed — the summary is
248
+ * enrichment and must not make `status` throw).
249
+ */
250
+ child?: ChildStatusSummary;
215
251
  }>;
216
252
  eligible: Firing[];
217
253
  blocked: Blocker[];
package/dist/model.js CHANGED
@@ -657,13 +657,17 @@ export function maintainDecisions(def, arts, time) {
657
657
  }
658
658
  // §26: declarative exclusive produce-groups — auto-skip losing siblings.
659
659
  // Once a group (exactlyOne/atMostOne) has a green winner, every other member
660
- // still resting in a debt state (owed/rejected) can never legally commit —
661
- // the group's exclusivity is enforced at commit time by the engine's
662
- // groupCasCheck, so those siblings would just stall forever without this.
663
- // Auto-skip settles them; the ordinary skipped-artifact rearm loop above
664
- // (which runs on the artifact's own next maintenance pass) revives them if
665
- // the winner is later un-greened (rejected/retracted) and the group's
666
- // fingerprint-gated inputs move again — no separate rearm code is needed.
660
+ // still resting in a debt state (owed/rejected) or awaiting judgment
661
+ // (submitted) can never legally commit — the group's exclusivity is
662
+ // enforced at commit time by the engine's groupCasCheck, so those siblings
663
+ // would just stall forever without this. A submitted sibling in particular
664
+ // is an OUTSTANDING state; left alone the instance can never reach
665
+ // done: true. Auto-skip settles them (clearing any partial approvals so a
666
+ // later resubmission never inherits a stale sign-off); the ordinary
667
+ // skipped-artifact rearm loop above (which runs on the artifact's own next
668
+ // maintenance pass) revives them if the winner is later un-greened
669
+ // (rejected/retracted) and the group's fingerprint-gated inputs move again
670
+ // — no separate rearm code is needed.
667
671
  for (const step of def.steps) {
668
672
  if (!step.groups || step.groups.length === 0)
669
673
  continue;
@@ -679,7 +683,9 @@ export function maintainDecisions(def, arts, time) {
679
683
  const sib = arts.get(stem);
680
684
  if (!sib)
681
685
  continue;
682
- if (sib.acceptance !== 'owed' && sib.acceptance !== 'rejected')
686
+ if (sib.acceptance !== 'owed' &&
687
+ sib.acceptance !== 'rejected' &&
688
+ sib.acceptance !== 'submitted')
683
689
  continue; // already skipped/retracted/green
684
690
  ops.push({
685
691
  kind: 'skip',
@@ -1426,10 +1432,15 @@ function applyOpInMemory(arts, def, op) {
1426
1432
  return;
1427
1433
  }
1428
1434
  if (op.kind === 'skip') {
1429
- // mirrors Engine.applyOp skip branch: acceptance → 'skipped' + fingerprint
1435
+ // mirrors Engine.applyOp skip branch: acceptance → 'skipped' + fingerprint.
1436
+ // §26.2: also mirrors the approvals-clear now applied on the engine side —
1437
+ // a submitted sibling auto-skipped out of a losing group must not carry a
1438
+ // stale partial sign-off into a later re-arm.
1439
+ const clearApprovals = art.acceptance === 'submitted' && art.approvals !== undefined;
1430
1440
  arts.set(op.path, {
1431
1441
  ...art,
1432
1442
  acceptance: 'skipped',
1443
+ ...(clearApprovals ? { approvals: undefined } : {}),
1433
1444
  fingerprint: computeFingerprint(arts, requiredInputs(def, arts, art)),
1434
1445
  });
1435
1446
  return;
package/dist/store.d.ts CHANGED
@@ -13,7 +13,7 @@
13
13
  * and (de)serialized at the boundary so callers always see real objects.
14
14
  */
15
15
  import { DatabaseSync } from 'node:sqlite';
16
- import type { ArtifactData, RunData, TaskData, WorkflowData, WorkflowDef } from './types.ts';
16
+ import type { ArtifactData, ArtifactHistory, RunData, TaskData, WorkflowData, WorkflowDef } from './types.ts';
17
17
  export interface ArtifactRow extends ArtifactData {
18
18
  id: string;
19
19
  updatedAt: number;
@@ -46,6 +46,8 @@ export declare class StoreVersionError extends Error {
46
46
  export declare class Store {
47
47
  readonly db: DatabaseSync;
48
48
  constructor(path: string);
49
+ /** Read the stored schema version without writing, refusing newer databases. */
50
+ private refuseIfNewer;
49
51
  close(): void;
50
52
  /**
51
53
  * Pre-schema migration: rename the legacy `loop` column to `step` on an
@@ -109,7 +111,17 @@ export declare class Store {
109
111
  getArtifactById(id: string): ArtifactRow | undefined;
110
112
  listArtifacts(workflow: string): ArtifactRow[];
111
113
  /** Insert or fully replace the artifact at (workflow, path). */
112
- putArtifact(data: ArtifactData): ArtifactRow;
114
+ putArtifact(data: ArtifactData, provenance?: {
115
+ action?: string;
116
+ actor?: string;
117
+ reason?: string;
118
+ kind?: string;
119
+ timestamp?: number;
120
+ key?: string;
121
+ }): ArtifactRow;
122
+ private insertArtifactEvent;
123
+ /** Returns history for exactly one artifact; list/status reads stay projection-only. */
124
+ getArtifactHistory(workflow: string, path: string): ArtifactHistory | undefined;
113
125
  deleteArtifact(workflow: string, path: string): void;
114
126
  getTask(workflow: string, step: string, key: string): TaskRow | undefined;
115
127
  listTasks(workflow: string): TaskRow[];