@juicesharp/rpiv-workflow 1.18.1 → 1.19.0

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.
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Composition comparator and outcome deriver registries.
3
+ *
4
+ * Per-channel `CompositionComparator` and `OutcomeDeriverFn` registries,
5
+ * both anchored on `Symbol.for` global slots (same pattern as `registry.ts`).
6
+ */
7
+
8
+ import type { Workflow } from "../api.js";
9
+ import { globalSlot } from "../internal-utils.js";
10
+ import type { CompositionComparator, SkillContractMap } from "../skill-contract.js";
11
+
12
+ const COMPARATORS_KEY = Symbol.for("@juicesharp/rpiv-workflow:composition-comparators");
13
+ const DERIVERS_KEY = Symbol.for("@juicesharp/rpiv-workflow:outcome-derivers");
14
+
15
+ /**
16
+ * A callback that derives `OutputSpec` outcomes for `produces` stages from the
17
+ * skill contract registry. Registered by a consumer (e.g. rpiv-pi) that owns
18
+ * the ontology (the `artifactKind → bucket` normalization table). The loader
19
+ * invokes drained derivers after `buildEffectiveContracts` and before the
20
+ * validation loop, so derived outcomes satisfy the `produces`-without-`outcome`
21
+ * guard.
22
+ *
23
+ * Implementations mutate `stage.outcome` in place on stages that lack an
24
+ * explicit outcome. The framework stays ontology-blind — it never reads
25
+ * `meta.artifactKind` itself.
26
+ *
27
+ * `onIssue` lets the deriver report warnings (e.g. user-defined workflow with
28
+ * missing artifactKind). The callback maps directly to `acc.issues.push(...)`;
29
+ * the deriver only populates `message` and `severity` — the loader sets `kind`
30
+ * and `layer`.
31
+ */
32
+ export type OutcomeDeriverFn = (
33
+ workflows: Iterable<Workflow>,
34
+ skillContracts: SkillContractMap,
35
+ onIssue: (message: string, severity: "error" | "warning") => void,
36
+ ) => void;
37
+
38
+ /** channel name → consumer-supplied composition comparator. */
39
+ export const getCompositionComparators = globalSlot(COMPARATORS_KEY, () => new Map<string, CompositionComparator>());
40
+
41
+ /**
42
+ * Register a per-channel composition comparator. The framework invokes the
43
+ * comparator at all three adjudication points for any consumer that declares
44
+ * `consumes.reads[channelName]`, but never interprets the `meta` it compares —
45
+ * the channel's ontology is the consumer's. Per-channel
46
+ * (not a single global comparator) so different consumers own different channels
47
+ * without collision. Idempotent on channel name (re-register replaces). Anchored
48
+ * on a `Symbol.for` slot like the rest of the registry, so it survives Pi's
49
+ * double module-load.
50
+ */
51
+ export function registerCompositionComparator(channelName: string, comparator: CompositionComparator): void {
52
+ getCompositionComparators().set(channelName, comparator);
53
+ }
54
+
55
+ const getDerivers = globalSlot(DERIVERS_KEY, () => [] as OutcomeDeriverFn[]);
56
+
57
+ /**
58
+ * Register an outcome deriver — a callback that auto-wires `OutputSpec`
59
+ * outcomes onto `produces` stages from the skill contract registry. The
60
+ * loader drains and invokes all registered derivers after
61
+ * `buildEffectiveContracts` and before the validation loop. Register before
62
+ * the first `/wf load`.
63
+ *
64
+ * rpiv-pi uses this to derive `rpivBucketOutcome(bucket)` from
65
+ * `produces.meta.artifactKind` via its `BUCKET_BY_KIND` normalization table,
66
+ * keeping the framework ontology-blind.
67
+ */
68
+ export function registerOutcomeDeriver(deriver: OutcomeDeriverFn): void {
69
+ getDerivers().push(deriver);
70
+ }
71
+
72
+ /**
73
+ * Peek at registered outcome derivers (non-draining). `loadWorkflows` calls
74
+ * this on every load after `buildEffectiveContracts` and invokes each deriver
75
+ * with the merged workflow map and effective skill contracts. Derivers must
76
+ * re-run on every load because their effects (mutating `stage.outcome`) live
77
+ * on per-load workflow objects — fresh objects from cache re-imports carry no
78
+ * outcome. The deriver is idempotent (`if (stage.outcome) continue`), so
79
+ * re-running on already-derived stages is safe. Internal — not on the public
80
+ * barrel.
81
+ */
82
+ export function getOutcomeDerivers(): OutcomeDeriverFn[] {
83
+ return getDerivers();
84
+ }
85
+
86
+ /**
87
+ * Partial reset (comparator + deriver registries). The barrel's
88
+ * `__resetSkillContracts` calls `__resetRegistry` plus this.
89
+ */
90
+ export function __resetRegistries(): void {
91
+ getCompositionComparators().clear();
92
+ getDerivers().length = 0;
93
+ }
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Skill-contract registry — global state, providers, and collision tracking.
3
+ *
4
+ * Owns the `Symbol.for`-anchored global slots for the contract registry, lazy
5
+ * providers, failures, collisions, and ownership tracking. The registry is keyed
6
+ * by RESOLVED post-alias skill name (`stage.skill ?? recordKey`), identical to
7
+ * `ensureSkillRegistered` — so a stage's contract lookup follows aliasing for free.
8
+ *
9
+ * Companion modules:
10
+ * - harvest.ts — harvestStageContracts + buildEffectiveContracts.
11
+ * - composition.ts — canCompose + legalNextSkills.
12
+ * - registries.ts — CompositionComparator + OutcomeDeriver registries.
13
+ */
14
+
15
+ import { deepEqual, globalSlot } from "../internal-utils.js";
16
+ import type { SkillContract, SkillContractMap } from "../skill-contract.js";
17
+
18
+ const REGISTRY_KEY = Symbol.for("@juicesharp/rpiv-workflow:skill-contracts");
19
+ const PROVIDERS_KEY = Symbol.for("@juicesharp/rpiv-workflow:skill-contract-providers");
20
+ const FLUSH_KEY = Symbol.for("@juicesharp/rpiv-workflow:skill-contract-flush");
21
+ const FAILURES_KEY = Symbol.for("@juicesharp/rpiv-workflow:skill-contract-failures");
22
+ const COLLISIONS_KEY = Symbol.for("@juicesharp/rpiv-workflow:skill-contract-collisions");
23
+ const OWNERS_KEY = Symbol.for("@juicesharp/rpiv-workflow:skill-contract-owners");
24
+
25
+ /** A lazy contributor of skill contracts — run once by `flushSkillContractProviders`. */
26
+ type SkillContractsProvider = () => void | Promise<void>;
27
+
28
+ const getRegistry = globalSlot(REGISTRY_KEY, () => new Map<string, SkillContract>());
29
+ const getProviders = globalSlot(PROVIDERS_KEY, () => [] as SkillContractsProvider[]);
30
+ /** name → owner label of whoever last registered it (for prune-on-reload + collision detection). */
31
+ const getOwners = globalSlot(OWNERS_KEY, () => new Map<string, string>());
32
+ const getCollisions = globalSlot(COLLISIONS_KEY, () => [] as string[]);
33
+ const getFailures = globalSlot(FAILURES_KEY, () => [] as unknown[]);
34
+
35
+ /** The memoised flush latch — a Promise once flushed, `undefined` before first flush / after reset. */
36
+ function getFlushLatch(): Promise<void> | undefined {
37
+ return (globalThis as Record<symbol, unknown>)[FLUSH_KEY] as Promise<void> | undefined;
38
+ }
39
+
40
+ function setFlushLatch(latch: Promise<void> | undefined): void {
41
+ (globalThis as Record<symbol, unknown>)[FLUSH_KEY] = latch;
42
+ }
43
+
44
+ /**
45
+ * Register one or more skill contracts, keyed by RESOLVED skill name — a flat
46
+ * namespace SHARED by all consumers (the key must equal `stage.skill` for lookup,
47
+ * so it can't be per-consumer-prefixed). Idempotent on name (re-register replaces).
48
+ *
49
+ * `owner` (optional consumer label, e.g. `"rpiv-pi"`) makes two real-world cases
50
+ * safe:
51
+ * - prune-on-reload — an owner's call is treated as its FULL current
52
+ * snapshot: any name this owner previously registered but didn't include now
53
+ * (a skill deleted between `/reload`s) is dropped, so stale contracts don't
54
+ * linger. Other owners' entries are untouched.
55
+ * - collision surfacing — a DIFFERENT owner overwriting a name with a
56
+ * DIVERGENT contract is recorded (drained into a `LoadIssue` by
57
+ * `loadWorkflows`), turning a silent last-writer-wins into a visible warning.
58
+ * Omit `owner` for the simple additive behaviour (no prune, no ownership claim).
59
+ */
60
+ export function registerSkillContracts(contracts: Iterable<readonly [string, SkillContract]>, owner?: string): void {
61
+ const registry = getRegistry();
62
+ const owners = getOwners();
63
+ const incoming = [...contracts];
64
+ const incomingNames = new Set(incoming.map(([name]) => name));
65
+ if (owner !== undefined) {
66
+ for (const [name, prevOwner] of [...owners]) {
67
+ if (prevOwner === owner && !incomingNames.has(name)) {
68
+ registry.delete(name); // this owner dropped the skill — drop its contract
69
+ owners.delete(name);
70
+ }
71
+ }
72
+ }
73
+ for (const [name, contract] of incoming) {
74
+ const existing = registry.get(name);
75
+ const prevOwner = owners.get(name);
76
+ if (existing && prevOwner !== owner && !deepEqual(existing, contract)) {
77
+ getCollisions().push(
78
+ `skill "${name}": contract from ${owner ?? "an anonymous registrant"} overrides a divergent one from ${prevOwner ?? "an anonymous registrant"} (last writer wins)`,
79
+ );
80
+ }
81
+ registry.set(name, contract);
82
+ if (owner !== undefined) owners.set(name, owner);
83
+ else owners.delete(name); // anonymous registration relinquishes any prior ownership claim
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Register a LAZY contract provider. The thunk runs once on the first
89
+ * `flushSkillContractProviders()` (which `loadWorkflows` awaits), letting a
90
+ * sibling defer reading skill frontmatter off startup and onto first `/wf`.
91
+ * Register before the first read.
92
+ */
93
+ export function registerSkillContractsProvider(provider: SkillContractsProvider): void {
94
+ getProviders().push(provider);
95
+ }
96
+
97
+ /**
98
+ * Run all pending providers once, then memoize. Concurrency-safe (callers await
99
+ * the same promise). DELIBERATE divergence from `flushBuiltInProviders`: each
100
+ * provider is wrapped so a throw is RECORDED (into the failures slot, drained by
101
+ * `drainSkillContractProviderErrors`), not propagated. Contract providers read
102
+ * the filesystem / parse frontmatter (failure-prone), and `loadWorkflows` must
103
+ * honor its never-throws contract — a malformed source degrades to a
104
+ * partial/empty registry instead of crashing `/wf`, but the error is NOT
105
+ * swallowed silently: `loadWorkflows` surfaces it as a `LoadIssue` so a buggy
106
+ * provider is debuggable. Built-in providers are trusted in-process code and so
107
+ * don't need the guard.
108
+ */
109
+ export function flushSkillContractProviders(): Promise<void> {
110
+ const existing = getFlushLatch();
111
+ if (existing) return existing;
112
+ const pending = getProviders().splice(0);
113
+ const flush = Promise.all(
114
+ pending.map((p) =>
115
+ Promise.resolve()
116
+ .then(p)
117
+ .catch((err) => {
118
+ getFailures().push(err);
119
+ }),
120
+ ),
121
+ ).then(() => undefined);
122
+ setFlushLatch(flush);
123
+ return flush;
124
+ }
125
+
126
+ /**
127
+ * Drain (return + clear) the errors recorded by failed contract providers since
128
+ * the last drain. `loadWorkflows` calls this right after the flush and maps each
129
+ * into a `LoadIssue`, so a provider bug surfaces in `loaded.issues` instead of
130
+ * vanishing. Internal — not on the public barrel.
131
+ */
132
+ export function drainSkillContractProviderErrors(): unknown[] {
133
+ return getFailures().splice(0);
134
+ }
135
+
136
+ /**
137
+ * Drain (return + clear) the cross-owner collision messages recorded since the
138
+ * last drain. `loadWorkflows` maps each into a `warning` `LoadIssue`.
139
+ * Internal — not on the public barrel.
140
+ */
141
+ export function drainSkillContractCollisions(): string[] {
142
+ return getCollisions().splice(0);
143
+ }
144
+
145
+ /**
146
+ * Read-only snapshot of the registry — consumed by `load/index.ts` + `buildRunContext`.
147
+ * Returns a defensive copy so callers cannot mutate the shared global registry.
148
+ */
149
+ export function getSkillContracts(): SkillContractMap {
150
+ return new Map(getRegistry());
151
+ }
152
+
153
+ /**
154
+ * Partial reset (registry + providers + collision state). The barrel's
155
+ * `__resetSkillContracts` calls this plus `registries.__resetRegistries`.
156
+ */
157
+ export function __resetRegistry(): void {
158
+ getRegistry().clear();
159
+ getProviders().length = 0;
160
+ getFailures().length = 0;
161
+ getCollisions().length = 0;
162
+ getOwners().clear();
163
+ setFlushLatch(undefined);
164
+ }
package/startup.ts CHANGED
@@ -7,3 +7,9 @@
7
7
 
8
8
  export { registerBuiltIns, registerBuiltInsProvider } from "./built-ins.js";
9
9
  export { registerLifecycle } from "./lifecycle.js";
10
+ export {
11
+ registerCompositionComparator,
12
+ registerOutcomeDeriver,
13
+ registerSkillContracts,
14
+ registerSkillContractsProvider,
15
+ } from "./skill-contracts/index.js";
package/state/index.ts CHANGED
@@ -5,6 +5,8 @@
5
5
  */
6
6
 
7
7
  export type {
8
+ ClaimResult,
9
+ NamesIndex,
8
10
  RoutingDecision,
9
11
  RunSummary,
10
12
  StageStatus,
@@ -12,17 +14,24 @@ export type {
12
14
  WorkflowStage,
13
15
  } from "./state.js";
14
16
  export {
17
+ addNameToIndex,
15
18
  appendRoutingDecision,
16
19
  appendStage,
20
+ claimName,
17
21
  generateRunId,
22
+ isValidName,
18
23
  listArtifacts,
19
24
  listRuns,
25
+ namesFilePath,
20
26
  readAllStages,
21
27
  readHeader,
22
28
  readLastStage,
29
+ readNamesIndex,
23
30
  readRoutingDecisions,
31
+ rebuildIndex,
24
32
  resolveRun,
25
33
  runsDir,
26
34
  stateFilePath,
35
+ VALID_NAME,
27
36
  writeHeader,
28
37
  } from "./state.js";
package/state/names.ts ADDED
@@ -0,0 +1,174 @@
1
+ /**
2
+ * Sidecar `names.json` index — maps human-readable run names to runIds for
3
+ * O(1) resolution. Lives in `<cwd>/.rpiv/workflows/runs/names.json`, alongside
4
+ * the JSONL audit files.
5
+ *
6
+ * Internal module — not re-exported from registration.ts. The runner calls
7
+ * `readNamesIndex` for collision pre-flight and `addNameToIndex` after
8
+ * `writeHeader`. External consumers resolve names through `resolveRun`.
9
+ *
10
+ * Fail-soft like every state-layer module: readers return `undefined` or empty
11
+ * on failure; writers warn via `console.warn` with `[rpiv-workflow]` prefix.
12
+ */
13
+
14
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
15
+ import { namesFilePath, runsDir, stateFilePath } from "./paths.js";
16
+
17
+ // ---------------------------------------------------------------------------
18
+ // Types
19
+ // ---------------------------------------------------------------------------
20
+
21
+ /** name → runId mapping persisted in names.json. */
22
+ export type NamesIndex = Record<string, string>;
23
+
24
+ /** Outcome of `claimName` — a tagged result the caller maps to a UI string. */
25
+ export type ClaimResult =
26
+ | { ok: true }
27
+ | { ok: false; reason: "invalid" }
28
+ | { ok: false; reason: "collision"; runId: string }
29
+ | { ok: false; reason: "write-failed" };
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Validation
33
+ // ---------------------------------------------------------------------------
34
+
35
+ /** Well-formedness contract for a run name: 1-64 chars, leading letter/underscore. */
36
+ export const VALID_NAME = /^[a-zA-Z_][a-zA-Z0-9_-]{0,63}$/;
37
+
38
+ export function isValidName(name: string): boolean {
39
+ return VALID_NAME.test(name);
40
+ }
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Readers
44
+ // ---------------------------------------------------------------------------
45
+
46
+ /**
47
+ * Read the names index from disk. Returns `undefined` when the file is
48
+ * missing, empty, or contains invalid JSON. Never throws.
49
+ */
50
+ export function readNamesIndex(cwd: string): NamesIndex | undefined {
51
+ try {
52
+ const filePath = namesFilePath(cwd);
53
+ if (!existsSync(filePath)) return undefined;
54
+ const content = readFileSync(filePath, "utf-8").trim();
55
+ if (!content) return undefined;
56
+ const parsed: unknown = JSON.parse(content);
57
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
58
+ return parsed as NamesIndex;
59
+ } catch (e) {
60
+ console.warn(`[rpiv-workflow] names index: ${e instanceof Error ? e.message : String(e)}`);
61
+ return undefined;
62
+ }
63
+ }
64
+
65
+ // ---------------------------------------------------------------------------
66
+ // Writers
67
+ // ---------------------------------------------------------------------------
68
+
69
+ /**
70
+ * Add a name → runId mapping to the index. Reads the current index, adds the
71
+ * entry, and writes back. Creates the file if it doesn't exist. Returns `true`
72
+ * on success, `false` on failure (warns to stderr).
73
+ *
74
+ * Does NOT check for collisions — callers handle that before calling.
75
+ */
76
+ export function addNameToIndex(cwd: string, name: string, runId: string): boolean {
77
+ try {
78
+ const current = readNamesIndex(cwd) ?? {};
79
+ current[name] = runId;
80
+ const dir = runsDir(cwd);
81
+ mkdirSync(dir, { recursive: true });
82
+ writeFileSync(namesFilePath(cwd), `${JSON.stringify(current)}\n`, "utf-8");
83
+ return true;
84
+ } catch (e) {
85
+ console.warn(`[rpiv-workflow] names index: ${e instanceof Error ? e.message : String(e)}`);
86
+ return false;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Claim a name for a run: validate → collision-check → persist, in that order.
92
+ * The single transactional door for reserving a name; callers must claim
93
+ * BEFORE writing the JSONL header so the collision guard's truth-source (the
94
+ * index) can never lag the header. On any non-`ok` result nothing is written.
95
+ */
96
+ export function claimName(cwd: string, name: string, runId: string): ClaimResult {
97
+ if (!isValidName(name)) return { ok: false, reason: "invalid" };
98
+ const existing = readNamesIndex(cwd)?.[name];
99
+ if (existing) return { ok: false, reason: "collision", runId: existing };
100
+ if (!addNameToIndex(cwd, name, runId)) return { ok: false, reason: "write-failed" };
101
+ return { ok: true };
102
+ }
103
+
104
+ // ---------------------------------------------------------------------------
105
+ // Recovery
106
+ // ---------------------------------------------------------------------------
107
+
108
+ /**
109
+ * Rebuild the names index by scanning all JSONL headers. Overwrites the
110
+ * existing `names.json` unconditionally. Skips runs without a `name` field.
111
+ * Returns the rebuilt index, or `undefined` on failure.
112
+ */
113
+ export function rebuildIndex(cwd: string): NamesIndex | undefined {
114
+ try {
115
+ const dir = runsDir(cwd);
116
+ let entries: string[];
117
+ try {
118
+ entries = readdirSync(dir);
119
+ } catch {
120
+ return undefined;
121
+ }
122
+
123
+ const index: NamesIndex = {};
124
+ for (const fileName of entries) {
125
+ if (!fileName.endsWith(".jsonl")) continue;
126
+ const runId = fileName.slice(0, -".jsonl".length);
127
+ // Read only the name field from the JSONL header — avoids importing
128
+ // readHeader from reads.ts (which would create a circular dependency
129
+ // since reads.ts imports readNamesIndex from this module).
130
+ const name = readNameFromJsonlHeader(cwd, runId);
131
+ if (name) {
132
+ // readdirSync order is filesystem-dependent — surface duplicate
133
+ // claims instead of silently picking a winner.
134
+ if (index[name] && index[name] !== runId) {
135
+ console.warn(
136
+ `[rpiv-workflow] names index rebuild: duplicate name '${name}' claimed by runs ${index[name]} and ${runId} — keeping ${runId}`,
137
+ );
138
+ }
139
+ index[name] = runId;
140
+ }
141
+ }
142
+
143
+ mkdirSync(dir, { recursive: true });
144
+ writeFileSync(namesFilePath(cwd), `${JSON.stringify(index)}\n`, "utf-8");
145
+ return index;
146
+ } catch (e) {
147
+ console.warn(`[rpiv-workflow] names index rebuild: ${e instanceof Error ? e.message : String(e)}`);
148
+ return undefined;
149
+ }
150
+ }
151
+
152
+ /**
153
+ * Read only the `name` field from a JSONL run file's header line. Returns
154
+ * `undefined` when the file is missing, the first line isn't valid JSON, or
155
+ * the header has no `name` field. Intentionally does not validate the full
156
+ * header shape — rebuildIndex only needs the name, not the typed WorkflowHeader.
157
+ *
158
+ * Internal helper — not exported. Keeps names.ts acyclic with reads.ts.
159
+ */
160
+ function readNameFromJsonlHeader(cwd: string, runId: string): string | undefined {
161
+ try {
162
+ const filePath = stateFilePath(cwd, runId);
163
+ if (!existsSync(filePath)) return undefined;
164
+ const content = readFileSync(filePath, "utf-8");
165
+ const firstLine = content.split("\n", 1)[0] ?? "";
166
+ if (!firstLine) return undefined;
167
+ const parsed: unknown = JSON.parse(firstLine);
168
+ return typeof (parsed as Record<string, unknown>)?.name === "string"
169
+ ? ((parsed as Record<string, unknown>).name as string)
170
+ : undefined;
171
+ } catch {
172
+ return undefined;
173
+ }
174
+ }
package/state/paths.ts CHANGED
@@ -41,6 +41,10 @@ export function runsDir(cwd: string): string {
41
41
  return join(cwd, ".rpiv", "workflows", "runs");
42
42
  }
43
43
 
44
+ export function namesFilePath(cwd: string): string {
45
+ return join(runsDir(cwd), "names.json");
46
+ }
47
+
44
48
  export function stateFilePath(cwd: string, runId: string): string {
45
49
  return join(runsDir(cwd), `${runId}.jsonl`);
46
50
  }
package/state/reads.ts CHANGED
@@ -17,7 +17,9 @@
17
17
  */
18
18
 
19
19
  import { existsSync, readdirSync, readFileSync } from "node:fs";
20
+ import { basename } from "node:path";
20
21
  import type { Artifact } from "../handle.js";
22
+ import { readNamesIndex } from "./names.js";
21
23
  import { runsDir, stateFilePath } from "./paths.js";
22
24
  import type { RoutingDecision, RunSummary, WorkflowHeader, WorkflowStage } from "./state.js";
23
25
 
@@ -158,15 +160,36 @@ export function readHeader(cwd: string, runId: string): WorkflowHeader | undefin
158
160
  * Which to call: reach for `resolveRun` when the ref is **user-supplied** (the
159
161
  * `/wf @<ref>` token, a CLI arg); reach for `readHeader` when you already hold
160
162
  * a concrete `runId` (e.g. straight off `RunSummary.runId`). The split is
161
- * intent, not behaviour: **today `resolveRun` is an exact alias of
162
- * `readHeader`** (`ref === runId`). It exists as the single place a future
163
- * symbolic resolver — `@latest`, relative refs, a friendly-name index
164
- * (name → runId → readHeader) — slots in without touching any caller.
163
+ * intent, not behaviour.
164
+ *
165
+ * Resolution order:
166
+ * 1. Check the names index (`names.json`) for a name → runId mapping on the
167
+ * RAW ref. If found and the target JSONL exists, return its header.
168
+ * 2. Fall back to runId lookup via `readHeader`, on the ref normalized to a
169
+ * slug — a trailing `.jsonl` is stripped and any directory prefix is
170
+ * dropped (`basename`). This lets `/wf @<path>` accept an editor's
171
+ * file-autosuggested path to the run's JSONL (`.../runs/<id>.jsonl`),
172
+ * a bare `<id>.jsonl`, or the plain `<id>` slug interchangeably.
173
+ *
174
+ * Name lookup stays on the raw ref: a run name is never a path, so a name like
175
+ * `auth.jsonl` (were it ever claimed) must match verbatim, not as a slug.
165
176
  *
166
177
  * Fail-soft like every reader — returns undefined when the ref doesn't resolve.
178
+ * A missing or corrupt `names.json` degrades gracefully: the index lookup
179
+ * returns `undefined` and the literal fallback runs.
167
180
  */
168
181
  export function resolveRun(cwd: string, ref: string): WorkflowHeader | undefined {
169
- return readHeader(cwd, ref);
182
+ // Try the names index first — O(1) lookup for human-readable aliases.
183
+ // Matched on the raw ref: a name is never a path/`.jsonl` file.
184
+ const index = readNamesIndex(cwd);
185
+ if (index?.[ref]) {
186
+ const resolved = readHeader(cwd, index[ref]!);
187
+ if (resolved) return resolved;
188
+ }
189
+ // Fall back to runId lookup, tolerating a pasted/autosuggested path:
190
+ // reduce to the bare slug (drop dir prefix + trailing `.jsonl`).
191
+ const slug = basename(ref).replace(/\.jsonl$/, "");
192
+ return readHeader(cwd, slug);
170
193
  }
171
194
 
172
195
  /**
@@ -204,6 +227,7 @@ export function listRuns(cwd: string): RunSummary[] {
204
227
  input: header.input,
205
228
  ts: header.ts,
206
229
  trigger: header.trigger,
230
+ name: header.name,
207
231
  });
208
232
  }
209
233
  return summaries;
package/state/state.ts CHANGED
@@ -71,6 +71,9 @@ export interface WorkflowHeader {
71
71
  * `undefined` as "trigger unknown."
72
72
  */
73
73
  trigger?: RunTrigger;
74
+ /** Human-readable alias assigned at creation via `--name`. Optional so
75
+ * older JSONL files (written before the name field was added) still parse. */
76
+ name?: string;
74
77
  }
75
78
 
76
79
  /**
@@ -89,6 +92,8 @@ export interface RunSummary {
89
92
  ts: string;
90
93
  /** Mirrors `WorkflowHeader.trigger`; undefined for legacy rows. */
91
94
  trigger?: RunTrigger;
95
+ /** Mirrors `WorkflowHeader.name`; undefined for unnamed runs. */
96
+ name?: string;
92
97
  }
93
98
 
94
99
  export interface RoutingDecision {
@@ -103,7 +108,17 @@ export interface RoutingDecision {
103
108
  // Public barrel — paths + writes + reads
104
109
  // ---------------------------------------------------------------------------
105
110
 
106
- export { generateRunId, runsDir, stateFilePath } from "./paths.js";
111
+ export {
112
+ addNameToIndex,
113
+ type ClaimResult,
114
+ claimName,
115
+ isValidName,
116
+ type NamesIndex,
117
+ readNamesIndex,
118
+ rebuildIndex,
119
+ VALID_NAME,
120
+ } from "./names.js";
121
+ export { generateRunId, namesFilePath, runsDir, stateFilePath } from "./paths.js";
107
122
  export {
108
123
  listArtifacts,
109
124
  listRuns,
@@ -15,34 +15,35 @@
15
15
  * Standard Schema's `issues` only carries `message` + `path`.
16
16
  */
17
17
 
18
+ import type { StandardSchemaV1 } from "@standard-schema/spec";
18
19
  import type { Static, TSchema } from "typebox";
19
- import { Value } from "typebox/value";
20
- import type { StageSchema } from "./api.js";
20
+ import type { JsonSchemaCapable, JsonSchemaObject } from "./json-schema.js";
21
+ import { jsonSchemaConverter, validateToJsonSchemaIssues } from "./json-schema.js";
21
22
 
22
23
  /**
23
- * Wrap a TypeBox schema to satisfy `StageSchema` (Standard Schema v1). The
24
- * returned object is structurally a Standard Schema; downstream code
25
- * (`validateOutputData`) consults `~standard.validate` and never sees
26
- * the underlying TypeBox value.
24
+ * Wrap a TypeBox schema to return a `JsonSchemaCapable` — a Standard Schema v1
25
+ * that ALSO exposes its JSON Schema as data via the spec `jsonSchema` Converter.
26
+ * Downstream code (`validateOutputData`) still consults `~standard.validate`;
27
+ * the new Converter lets the edge-compat checker extract the schema as
28
+ * data without needing to know the schema library.
27
29
  *
28
30
  * Generic over the input schema `S` so the parsed type (`Static<S>`) flows
29
- * through `StageSchema<unknown, Static<S>>` and into the surrounding
31
+ * through `JsonSchemaCapable<unknown, Static<S>>` and into the surrounding
30
32
  * `StageDef<TIn, TOut>` — predicate bodies + downstream stage consumers can
31
33
  * read `output.data` with the parsed type instead of `unknown`.
32
34
  */
33
- export function typeboxSchema<S extends TSchema>(schema: S): StageSchema<unknown, Static<S>> {
35
+ export function typeboxSchema<S extends TSchema>(schema: S): JsonSchemaCapable<unknown, Static<S>> {
34
36
  return {
35
37
  "~standard": {
36
38
  version: 1,
37
39
  vendor: "typebox",
38
- validate: (value: unknown) => {
39
- if (Value.Check(schema, value)) return { value };
40
- const issues = [...Value.Errors(schema, value)].map((err) => ({
41
- message: err.message || `${err.keyword} validation failed at ${err.instancePath || "root"}`,
42
- path: err.instancePath ? err.instancePath.split("/").filter(Boolean) : undefined,
43
- }));
44
- return { issues };
45
- },
40
+ validate: ((value: unknown) => validateToJsonSchemaIssues(schema, value)) as StandardSchemaV1<
41
+ unknown,
42
+ Static<S>
43
+ >["~standard"]["validate"],
44
+ // A TypeBox v1 schema is structurally a clean JSON Schema (zero symbol
45
+ // keys, runtime-verified), so it doubles as the captured `jsonSchema` data.
46
+ jsonSchema: jsonSchemaConverter(schema as unknown as JsonSchemaObject),
46
47
  },
47
48
  };
48
49
  }