@lanefoundry/gatelane-sdk 0.0.0-canary-b3f6165

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 (47) hide show
  1. package/LICENSE +190 -0
  2. package/dist/candidate.d.ts +26 -0
  3. package/dist/candidate.d.ts.map +1 -0
  4. package/dist/candidate.js +41 -0
  5. package/dist/candidate.js.map +1 -0
  6. package/dist/capture.d.ts +105 -0
  7. package/dist/capture.d.ts.map +1 -0
  8. package/dist/capture.js +78 -0
  9. package/dist/capture.js.map +1 -0
  10. package/dist/dataset.d.ts +56 -0
  11. package/dist/dataset.d.ts.map +1 -0
  12. package/dist/dataset.js +35 -0
  13. package/dist/dataset.js.map +1 -0
  14. package/dist/gate.d.ts +81 -0
  15. package/dist/gate.d.ts.map +1 -0
  16. package/dist/gate.js +82 -0
  17. package/dist/gate.js.map +1 -0
  18. package/dist/index.d.ts +16 -0
  19. package/dist/index.d.ts.map +1 -0
  20. package/dist/index.js +16 -0
  21. package/dist/index.js.map +1 -0
  22. package/dist/promotion.d.ts +82 -0
  23. package/dist/promotion.d.ts.map +1 -0
  24. package/dist/promotion.js +14 -0
  25. package/dist/promotion.js.map +1 -0
  26. package/dist/storage-fs.d.ts +27 -0
  27. package/dist/storage-fs.d.ts.map +1 -0
  28. package/dist/storage-fs.js +68 -0
  29. package/dist/storage-fs.js.map +1 -0
  30. package/dist/storage-http.d.ts +43 -0
  31. package/dist/storage-http.d.ts.map +1 -0
  32. package/dist/storage-http.js +112 -0
  33. package/dist/storage-http.js.map +1 -0
  34. package/dist/storage.d.ts +76 -0
  35. package/dist/storage.d.ts.map +1 -0
  36. package/dist/storage.js +52 -0
  37. package/dist/storage.js.map +1 -0
  38. package/package.json +69 -0
  39. package/src/candidate.ts +76 -0
  40. package/src/capture.ts +153 -0
  41. package/src/dataset.ts +85 -0
  42. package/src/gate.ts +162 -0
  43. package/src/index.ts +16 -0
  44. package/src/promotion.ts +98 -0
  45. package/src/storage-fs.ts +76 -0
  46. package/src/storage-http.ts +143 -0
  47. package/src/storage.ts +97 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"storage.js","sourceRoot":"","sources":["../src/storage.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG;AAyCH,6EAA6E;AAC7E,MAAM,OAAO,eAAe;IACjB,IAAI,GAAG,QAAQ,CAAC;IACR,OAAO,GAAG,IAAI,GAAG,EAAyB,CAAC;IAE5D,KAAK,CAAC,KAAK,CAAC,MAAqB;QAC/B,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,EAAE,MAAM,CAAC,CAAC;QACpC,OAAO;YACL,EAAE,EAAE,MAAM,CAAC,EAAE;YACb,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACnC,OAAO,EAAE,IAAI,CAAC,IAAI;SACnB,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,EAAU;QACnB,OAAO,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,IAAI,IAAI,CAAC;IACtC,CAAC;IAED,KAAK,CAAC,IAAI,CAAC,MAAgE;QACzE,IAAI,GAAG,GAAG,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC;QAC5C,IAAI,MAAM,CAAC,WAAW,KAAK,SAAS,EAAE,CAAC;YACrC,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,QAAQ,EAAE,CAAC,aAAa,CAAC,KAAK,MAAM,CAAC,WAAW,CAAC,CAAC;QACpF,CAAC;QACD,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;YAC/B,MAAM,KAAK,GAAG,IAAI,CAAC,KAAK,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvC,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,UAAU,CAAC,IAAI,KAAK,CAAC,CAAC;QAC7D,CAAC;QACD,IAAI,MAAM,CAAC,KAAK,KAAK,SAAS,EAAE,CAAC;YAC/B,GAAG,GAAG,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,MAAM,CAAC,KAAK,CAAC,CAAC;QACnC,CAAC;QACD,OAAO,GAAG,CAAC;IACb,CAAC;CACF;AAED,yEAAyE;AACzE,IAAI,aAAa,GAAmB,IAAI,eAAe,EAAE,CAAC;AAE1D,iGAAiG;AACjG,MAAM,UAAU,UAAU,CAAC,OAAuB;IAChD,MAAM,QAAQ,GAAG,aAAa,CAAC;IAC/B,aAAa,GAAG,OAAO,CAAC;IACxB,OAAO,QAAQ,CAAC;AAClB,CAAC;AAED,sCAAsC;AACtC,MAAM,UAAU,UAAU;IACxB,OAAO,aAAa,CAAC;AACvB,CAAC"}
package/package.json ADDED
@@ -0,0 +1,69 @@
1
+ {
2
+ "name": "@lanefoundry/gatelane-sdk",
3
+ "version": "0.0.0-canary-b3f6165",
4
+ "description": "Capture SDK + type-only shapes for the gatelane promotion gate.",
5
+ "license": "Apache-2.0",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/lanefoundry/gatelane.git",
9
+ "directory": "packages/gatelane-sdk"
10
+ },
11
+ "homepage": "https://github.com/lanefoundry/gatelane/tree/main/packages/gatelane-sdk",
12
+ "type": "module",
13
+ "main": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
15
+ "exports": {
16
+ ".": {
17
+ "types": "./dist/index.d.ts",
18
+ "import": "./dist/index.js"
19
+ },
20
+ "./gate": {
21
+ "types": "./dist/gate.d.ts",
22
+ "import": "./dist/gate.js"
23
+ },
24
+ "./dataset": {
25
+ "types": "./dist/dataset.d.ts",
26
+ "import": "./dist/dataset.js"
27
+ },
28
+ "./candidate": {
29
+ "types": "./dist/candidate.d.ts",
30
+ "import": "./dist/candidate.js"
31
+ },
32
+ "./promotion": {
33
+ "types": "./dist/promotion.d.ts",
34
+ "import": "./dist/promotion.js"
35
+ },
36
+ "./capture": {
37
+ "types": "./dist/capture.d.ts",
38
+ "import": "./dist/capture.js"
39
+ },
40
+ "./storage": {
41
+ "types": "./dist/storage.d.ts",
42
+ "import": "./dist/storage.js"
43
+ },
44
+ "./storage-fs": {
45
+ "types": "./dist/storage-fs.d.ts",
46
+ "import": "./dist/storage-fs.js"
47
+ },
48
+ "./storage-http": {
49
+ "types": "./dist/storage-http.d.ts",
50
+ "import": "./dist/storage-http.js"
51
+ }
52
+ },
53
+ "publishConfig": {
54
+ "access": "public"
55
+ },
56
+ "files": [
57
+ "dist",
58
+ "src"
59
+ ],
60
+ "devDependencies": {
61
+ "@types/node": "^22.0.0",
62
+ "typescript": "^5.5.4",
63
+ "vitest": "^2.0.5"
64
+ },
65
+ "scripts": {
66
+ "build": "tsc -p tsconfig.json",
67
+ "test": "vitest run"
68
+ }
69
+ }
@@ -0,0 +1,76 @@
1
+ /**
2
+ * Candidate types — any component swap in the agent's context that can be attacked.
3
+ *
4
+ * gatelane's gate treats all 10 as first-class. The GateReport
5
+ * carries the SHA of every candidate.
6
+ *
7
+ * @see docs/prd.md §5.3 — Candidate types table
8
+ */
9
+ export type CandidateRef = {
10
+ /** Discriminator + identifier. Format: `<type>:<id>[@<version>]`. */
11
+ readonly ref: string;
12
+ /** SHA captured in the GateReport. */
13
+ readonly sha: string;
14
+ /** Optional human-readable label for reports. */
15
+ readonly label?: string;
16
+ };
17
+
18
+ export type CandidateType =
19
+ | 'model'
20
+ | 'prompt'
21
+ | 'skill'
22
+ | 'config'
23
+ | 'tool'
24
+ | 'eval'
25
+ | 'kb'
26
+ | 'memory'
27
+ | 'dispatcher'
28
+ | 'guardrail';
29
+
30
+ /** Parse a candidate ref string like `tool:mcp-server-foo@1.2.0` into type + id + version. */
31
+ export function parseCandidateRef(ref: string): {
32
+ type: CandidateType;
33
+ id: string;
34
+ version?: string;
35
+ } {
36
+ const colonIdx = ref.indexOf(':');
37
+ if (colonIdx < 0) {
38
+ throw new Error(`invalid candidate ref: ${ref} (expected <type>:<id>[@<version>])`);
39
+ }
40
+ const type = ref.slice(0, colonIdx) as CandidateType;
41
+ const rest = ref.slice(colonIdx + 1);
42
+ const valid: CandidateType[] = [
43
+ 'model',
44
+ 'prompt',
45
+ 'skill',
46
+ 'config',
47
+ 'tool',
48
+ 'eval',
49
+ 'kb',
50
+ 'memory',
51
+ 'dispatcher',
52
+ 'guardrail',
53
+ ];
54
+ if (!valid.includes(type)) {
55
+ throw new Error(
56
+ `invalid candidate type: ${type} (expected one of ${valid.join(', ')})`,
57
+ );
58
+ }
59
+ const atIdx = rest.lastIndexOf('@');
60
+ if (atIdx < 0) {
61
+ return { type, id: rest };
62
+ }
63
+ return { type, id: rest.slice(0, atIdx), version: rest.slice(atIdx + 1) };
64
+ }
65
+
66
+ /** Compute a placeholder SHA for a candidate ref. Stub: SHA-256 of the ref string. */
67
+ export async function shaOfCandidateRef(ref: string): Promise<string> {
68
+ // v0.0.0-dev stub: deterministic placeholder so reports are reproducible.
69
+ // Real implementation in W2 will hash the actual artifact content.
70
+ const data = new TextEncoder().encode(ref);
71
+ const digest = await crypto.subtle.digest('SHA-256', data);
72
+ const hex = Array.from(new Uint8Array(digest))
73
+ .map((b) => b.toString(16).padStart(2, '0'))
74
+ .join('');
75
+ return `sha256:${hex}`;
76
+ }
package/src/capture.ts ADDED
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Capture SDK — one-line instrumentation for agent calls.
3
+ *
4
+ * Wraps an LLM/tool/judge call so gatelane can observe (and later replay) it.
5
+ * Records go through the active StorageAdapter (in-memory by default; HTTP via
6
+ * HttpStorage for production; filesystem via FilesystemStorage for local dev).
7
+ *
8
+ * @example
9
+ * ```ts
10
+ * import { capture, setStorage, HttpStorage } from "@lanefoundry/gatelane-sdk";
11
+ *
12
+ * // One-time setup: point capture at the production Worker.
13
+ * setStorage(new HttpStorage({
14
+ * endpoint: process.env.GATELANE_ENDPOINT!,
15
+ * token: process.env.GATELANE_CAPTURE_TOKEN!,
16
+ * }));
17
+ *
18
+ * // Now every call site uses the same wrapper.
19
+ * const response = await capture({
20
+ * prompt: [{ role: "user", content: userInput }],
21
+ * model: "gpt-4o",
22
+ * metadata: { traceId: "...", agentVersion: "..." },
23
+ * }, async () => openai.chat.completions.create({ ... }));
24
+ * ```
25
+ *
26
+ * @see docs/prd.md §5.6 — SDK & API surface
27
+ */
28
+
29
+ import { getStorage } from './storage.js';
30
+
31
+ import type { DatasetSourceKind } from './dataset.js';
32
+
33
+ export type CaptureMetadata = {
34
+ readonly traceId?: string;
35
+ readonly agentVersion?: string;
36
+ readonly dataset?: string;
37
+ readonly source_kind?: DatasetSourceKind;
38
+ /** Free-form metadata. */
39
+ readonly [key: string]: unknown;
40
+ };
41
+
42
+ export type CaptureInput = {
43
+ readonly prompt: ReadonlyArray<{ role: string; content: string }>;
44
+ readonly model?: string;
45
+ readonly metadata?: CaptureMetadata;
46
+ };
47
+
48
+ /** What the capture SDK stores per call. */
49
+ export type CapturedCall = {
50
+ readonly id: string;
51
+ readonly input: CaptureInput;
52
+ readonly output: unknown;
53
+ readonly started_at: string;
54
+ readonly completed_at: string;
55
+ readonly cost_usd: number;
56
+ readonly latency_ms: number;
57
+ /** Span kind: gate.replay, gate.compare, gate.promote, scan.attack, scan.judge. */
58
+ readonly span_kind?: string;
59
+ };
60
+
61
+ /** A single step in a multi-turn agent trace (user/assistant/tool). */
62
+ export type Turn = {
63
+ readonly role: 'system' | 'user' | 'assistant' | 'tool';
64
+ readonly content: string | null;
65
+ readonly tool_call_id?: string;
66
+ readonly name?: string;
67
+ readonly tool_calls?: ReadonlyArray<{ id: string; name: string; arguments: string }>;
68
+ readonly status?: 'ok' | 'error' | 'timeout';
69
+ readonly error?: { type: string; message: string; stack?: string };
70
+ readonly span_kind?: string;
71
+ readonly span_id?: string;
72
+ readonly parent_span_id?: string;
73
+ readonly model?: string;
74
+ readonly started_at?: string;
75
+ readonly completed_at?: string;
76
+ readonly cost_usd?: number;
77
+ readonly latency_ms?: number;
78
+ readonly tokens_in?: number;
79
+ readonly tokens_out?: number;
80
+ };
81
+
82
+ export type CaptureOptions = {
83
+ readonly span_kind?: string;
84
+ /** If true, observe without writing. Used for SDK validation in prod. */
85
+ readonly dry_run?: boolean;
86
+ };
87
+
88
+ /**
89
+ * Wrap an LLM/tool/judge call so gatelane captures it.
90
+ *
91
+ * Production behavior: writes the record to the active StorageAdapter (HTTP → Worker → R2/D1).
92
+ * Tests: in-memory adapter keeps everything in process.
93
+ * Local dev without Worker: filesystem adapter.
94
+ */
95
+ export async function capture<T>(
96
+ input: CaptureInput,
97
+ call: () => Promise<T>,
98
+ options: CaptureOptions = {},
99
+ ): Promise<T> {
100
+ const started_at = new Date().toISOString();
101
+ const start = performance.now();
102
+ const output = await call();
103
+ const latency_ms = performance.now() - start;
104
+ const completed_at = new Date().toISOString();
105
+
106
+ if (options.dry_run) {
107
+ return output;
108
+ }
109
+
110
+ const record: CapturedCall = {
111
+ id: crypto.randomUUID(),
112
+ input,
113
+ output,
114
+ started_at,
115
+ completed_at,
116
+ cost_usd: 0, // placeholder; real impl reads from model registry
117
+ latency_ms,
118
+ ...(options.span_kind !== undefined ? { span_kind: options.span_kind } : {}),
119
+ };
120
+
121
+ // Fire-and-await: a capture write failure must not break the user's call.
122
+ // The Worker is the source of truth; SDK surfaces the error to stderr but
123
+ // does NOT throw, so a flaky network does not turn into a broken agent.
124
+ try {
125
+ await getStorage().write(record);
126
+ } catch (err) {
127
+ process.stderr.write(
128
+ `[gatelane] capture write failed (record id=${record.id}): ${err instanceof Error ? err.message : String(err)}\n`,
129
+ );
130
+ }
131
+
132
+ return output;
133
+ }
134
+
135
+ /**
136
+ * Wrap an existing agent function so every call is captured.
137
+ * Sugar over {@link capture} for the common case.
138
+ */
139
+ export function withCapture<TArgs extends unknown[], TReturn>(
140
+ fn: (...args: TArgs) => Promise<TReturn>,
141
+ options: { span_kind?: string } = {},
142
+ ): (...args: TArgs) => Promise<TReturn> {
143
+ return async (...args: TArgs): Promise<TReturn> => {
144
+ return capture(
145
+ {
146
+ prompt: [],
147
+ metadata: { args: args.length },
148
+ },
149
+ () => fn(...args),
150
+ options,
151
+ );
152
+ };
153
+ }
package/src/dataset.ts ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Frozen dataset — content-addressed, immutable, versioned.
3
+ *
4
+ * A dataset is the input to a gate run. Three sources:
5
+ * - `scan` — curated attacks from garak / PyRIT / Promptfoo / DeepTeam
6
+ * - `prod` — frozen production slice from capture SDK
7
+ * - `compliance` — curated cases mapped to NIST / AI Basic Act / EU AI Act
8
+ *
9
+ * @see docs/prd.md §5.2 — Three dataset sources
10
+ */
11
+
12
+ export type DatasetSourceKind = 'scan' | 'prod' | 'compliance';
13
+
14
+ export type FrozenDataset = {
15
+ /** Content hash of the dataset. */
16
+ readonly content_hash: string;
17
+ /** Schema version. */
18
+ readonly version: string;
19
+ /** Where this dataset came from. */
20
+ readonly source_kind: DatasetSourceKind;
21
+ /** Free-form reference to the upstream source (e.g. "garak@0.14.0+owasp-agentic-v1"). */
22
+ readonly source_ref: string;
23
+ /** Optional slice filter (time range, user cohort, etc.). */
24
+ readonly slice_filter?: Record<string, unknown>;
25
+ /** When the dataset was frozen. ISO 8601 timestamp. */
26
+ readonly frozen_at: string;
27
+ /** Number of items in the dataset. */
28
+ readonly item_count: number;
29
+ /** Items themselves (lazy-loaded). */
30
+ readonly items?: ReadonlyArray<DatasetItem>;
31
+ };
32
+
33
+ import type { Turn } from './capture.js';
34
+
35
+ export type DatasetItem = {
36
+ readonly id: string;
37
+ /** For red-team: the attack payload. For prod: the captured user input. For compliance: the test case. */
38
+ readonly input: unknown;
39
+ /** Optional expected outcome (for compliance / eval datasets). */
40
+ readonly expected?: unknown;
41
+ /** Full multi-turn agent trace from the original capture, when available.
42
+ * Includes tool calls, tool results, and intermediate assistant turns. */
43
+ readonly turns?: ReadonlyArray<Turn>;
44
+ /** Metadata from the original capture (model, cost, latency, etc.). */
45
+ readonly metadata?: Record<string, unknown>;
46
+ /** OWASP Agentic Top 10 mapping, if known. */
47
+ readonly mapped_asi?: 'ASI01' | 'ASI02' | 'ASI03' | 'ASI04' | 'ASI05' | 'ASI06' | 'ASI07' | 'ASI08' | 'ASI09' | 'ASI10';
48
+ /** MITRE ATLAS technique ID, if known. */
49
+ readonly mapped_atlas?: string;
50
+ };
51
+
52
+ /** Compute a placeholder content hash from item count + source ref. Stub. */
53
+ export async function hashDataset(
54
+ source_kind: DatasetSourceKind,
55
+ source_ref: string,
56
+ item_count: number,
57
+ ): Promise<string> {
58
+ const data = new TextEncoder().encode(`${source_kind}|${source_ref}|${item_count}`);
59
+ const digest = await crypto.subtle.digest('SHA-256', data);
60
+ const hex = Array.from(new Uint8Array(digest))
61
+ .map((b) => b.toString(16).padStart(2, '0'))
62
+ .join('');
63
+ return `sha256:${hex}`;
64
+ }
65
+
66
+ /** Build a stub FrozenDataset. Items optional. */
67
+ export async function freezeDataset(args: {
68
+ source_kind: DatasetSourceKind;
69
+ source_ref: string;
70
+ slice_filter?: Record<string, unknown>;
71
+ items?: ReadonlyArray<DatasetItem>;
72
+ }): Promise<FrozenDataset> {
73
+ const item_count = args.items?.length ?? 0;
74
+ const content_hash = await hashDataset(args.source_kind, args.source_ref, item_count);
75
+ return {
76
+ content_hash,
77
+ version: '0.0.0-dev',
78
+ source_kind: args.source_kind,
79
+ source_ref: args.source_ref,
80
+ ...(args.slice_filter !== undefined ? { slice_filter: args.slice_filter } : {}),
81
+ frozen_at: new Date().toISOString(),
82
+ item_count,
83
+ ...(args.items !== undefined ? { items: args.items } : {}),
84
+ };
85
+ }
package/src/gate.ts ADDED
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Gate runner registry — the SDK defines the shape, the engine plugs in the impl.
3
+ *
4
+ * The default export is a stub that produces a deterministic mock. Production
5
+ * installs the engine package and calls {@link setGateRunner} once at process
6
+ * startup; subsequent {@link runGate} calls delegate to the engine.
7
+ *
8
+ * Decoupling: SDK doesn't depend on engine (engine depends on SDK). Test code
9
+ * can install a fake runner for deterministic gate outputs.
10
+ *
11
+ * @see docs/prd.md §5.1 — The gate
12
+ */
13
+
14
+ import { shaOfCandidateRef } from './candidate.js';
15
+ import type { FrozenDataset } from './dataset.js';
16
+ import {
17
+ DEFAULT_POLICY,
18
+ type GateDecision,
19
+ type GatePolicy,
20
+ type GateReport,
21
+ } from './promotion.js';
22
+
23
+ export type GateRunArgs = {
24
+ readonly candidates: ReadonlyArray<string>;
25
+ readonly dataset: FrozenDataset;
26
+ readonly judges: ReadonlyArray<string>;
27
+ readonly baseline?: string;
28
+ readonly policy?: GatePolicy;
29
+ readonly approver?: string;
30
+ };
31
+
32
+ /** Lightweight replay row shape (mirrors engine's ReplayRow without importing it). */
33
+ export type GateReplayRow = {
34
+ readonly item_id: string;
35
+ readonly candidate_ref: string;
36
+ readonly response: {
37
+ readonly content: string;
38
+ readonly cost_usd: number;
39
+ readonly latency_ms: number;
40
+ readonly tokens_in?: number;
41
+ readonly tokens_out?: number;
42
+ readonly finish_reason?: string;
43
+ };
44
+ };
45
+
46
+ /** Lightweight judge verdict shape (mirrors engine's JudgeVerdict). */
47
+ export type GateJudgeVerdict = {
48
+ readonly candidate_ref: string;
49
+ readonly judge_ref: string;
50
+ readonly item_id: string;
51
+ readonly outcome: 'pass' | 'fail';
52
+ readonly score: number;
53
+ readonly reasoning?: string;
54
+ readonly cost_usd: number;
55
+ readonly latency_ms: number;
56
+ };
57
+
58
+ /** Lightweight per-candidate metric shape (mirrors engine's CandidateMetric). */
59
+ export type GateCandidateMetric = {
60
+ readonly mean_score: number;
61
+ readonly pass_rate: number;
62
+ readonly n_items: number;
63
+ readonly total_cost_usd: number;
64
+ readonly mean_latency_ms: number;
65
+ readonly aggregate_delta: number;
66
+ readonly cost_delta: number;
67
+ readonly latency_delta: number;
68
+ };
69
+
70
+ export type GateRunResult = {
71
+ readonly report: GateReport;
72
+ readonly decision: GateDecision;
73
+ /** Per-item replay outputs for every (candidate, item) pair. */
74
+ readonly replay_rows?: ReadonlyArray<GateReplayRow>;
75
+ /** Per-item judge verdicts with scores and reasoning. */
76
+ readonly verdicts?: ReadonlyArray<GateJudgeVerdict>;
77
+ /** Per-candidate aggregate metrics (mean_score, pass_rate, cost, latency, deltas). */
78
+ readonly candidate_metrics?: Readonly<Record<string, GateCandidateMetric>>;
79
+ };
80
+
81
+ /** Runner interface. The engine implements this and registers it. */
82
+ export type GateRunner = (args: GateRunArgs) => Promise<GateRunResult>;
83
+
84
+ let registeredRunner: GateRunner | null = null;
85
+
86
+ /** Install the real engine runner. Idempotent; subsequent calls overwrite. */
87
+ export function setGateRunner(runner: GateRunner): void {
88
+ registeredRunner = runner;
89
+ }
90
+
91
+ /** Reset to the stub runner. Tests use this. */
92
+ export function resetGateRunner(): void {
93
+ registeredRunner = null;
94
+ }
95
+
96
+ /**
97
+ * Run the gate. If an engine runner is installed, delegates to it.
98
+ * Otherwise produces a deterministic mock report (W1 behavior).
99
+ */
100
+ export async function runGate(args: GateRunArgs): Promise<GateRunResult> {
101
+ if (registeredRunner !== null) {
102
+ return registeredRunner(args);
103
+ }
104
+ return stubRunGate(args);
105
+ }
106
+
107
+ /** v0.0.0-dev stub — kept for SDK consumers that don't load the engine yet. */
108
+ export async function stubRunGate(args: GateRunArgs): Promise<GateRunResult> {
109
+ const policy = args.policy ?? DEFAULT_POLICY;
110
+ const baseline = args.baseline ?? 'model:baseline';
111
+ const runId = crypto.randomUUID();
112
+ const reportId = crypto.randomUUID();
113
+
114
+ const candidate_shas: Record<string, string> = {};
115
+ for (const ref of args.candidates) {
116
+ candidate_shas[ref] = await shaOfCandidateRef(ref);
117
+ }
118
+ const judge_shas: Record<string, string> = {};
119
+ for (const judge of args.judges) {
120
+ judge_shas[judge] = await shaOfCandidateRef(judge);
121
+ }
122
+
123
+ const report: GateReport = {
124
+ id: reportId,
125
+ gate_run_id: runId,
126
+ dataset_content_hash: args.dataset.content_hash,
127
+ dataset_version: args.dataset.version,
128
+ candidate_shas,
129
+ judge_shas,
130
+ scorer_code_sha: await shaOfCandidateRef('gatelane-sdk:scorer:v0.0.0-dev'),
131
+ baseline_metrics: { primary_score: 0.7 },
132
+ candidate_metrics: Object.fromEntries(
133
+ args.candidates.map((ref) => [
134
+ ref,
135
+ { aggregate_delta: 0.05, cost_delta: 0.02, latency_delta: 0.03 },
136
+ ]),
137
+ ),
138
+ judge_matrix: {
139
+ candidates: args.candidates,
140
+ judges: args.judges,
141
+ winners_by_judge: Object.fromEntries(
142
+ args.candidates.map((ref) => [ref, args.judges.length]),
143
+ ),
144
+ consensus_winners: args.candidates,
145
+ },
146
+ policy,
147
+ ...(args.approver !== undefined ? { approver: args.approver } : {}),
148
+ timestamp: new Date().toISOString(),
149
+ signature: 'stub:unsigned',
150
+ };
151
+
152
+ const winner = args.candidates[0] ?? baseline;
153
+ const decision: GateDecision = policy.approval_required
154
+ ? { action: 'hold_for_review', reason: 'approval_required' }
155
+ : {
156
+ action: 'pass',
157
+ winner,
158
+ reason: `stub: all candidates passed policy (min_delta=${policy.min_delta})`,
159
+ };
160
+
161
+ return { report, decision, replay_rows: [], verdicts: [], candidate_metrics: {} };
162
+ }
package/src/index.ts ADDED
@@ -0,0 +1,16 @@
1
+ /**
2
+ * @lanefoundry/gatelane-sdk — promotion gate SDK.
3
+ *
4
+ * Public API for v0.0.1-dev. Engine wires up across W1–W6 per docs/roadmap.md.
5
+ *
6
+ * @see docs/prd.md §5.6 — SDK & API surface
7
+ */
8
+
9
+ export * from './capture.js';
10
+ export * from './candidate.js';
11
+ export * from './dataset.js';
12
+ export * from './gate.js';
13
+ export * from './promotion.js';
14
+ export * from './storage.js';
15
+ export * from './storage-fs.js';
16
+ export * from './storage-http.js';
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Gate policy, report, and decision — the signed artifacts produced by a gate run.
3
+ *
4
+ * @see docs/prd.md §5.1 — The gate
5
+ */
6
+
7
+ export type GatePolicy = {
8
+ /** Minimum aggregate delta over baseline required to pass. */
9
+ readonly min_delta: number;
10
+ /** Minimum fraction of judges that must agree on the winning candidate (e.g., 0.67 = 2 of 3). */
11
+ readonly judge_stability_threshold: number;
12
+ /** Maximum cost increase over baseline permitted for a pass decision. */
13
+ readonly cost_ceiling: number;
14
+ /** Maximum latency increase over baseline permitted for a pass decision. */
15
+ readonly latency_ceiling: number;
16
+ /** Whether human approval is required before the gate decision is executed. */
17
+ readonly approval_required: boolean;
18
+ /** Trigger condition under which a deployed canary is automatically blocked. */
19
+ readonly auto_block_rule?: {
20
+ /** Metric drop threshold (e.g., 0.05 = 5% drop). */
21
+ readonly metric_drop: number;
22
+ /** Window to observe canary before passing to 100% (e.g., "24h"). */
23
+ readonly window: string;
24
+ };
25
+ };
26
+
27
+ /** @deprecated Use GatePolicy instead. */
28
+ export type PromotionPolicy = GatePolicy;
29
+
30
+ export type JudgeStabilityMatrix = {
31
+ readonly candidates: ReadonlyArray<string>;
32
+ readonly judges: ReadonlyArray<string>;
33
+ /** winners_by_judge[candidate] = count of judges that picked this candidate as winner. */
34
+ readonly winners_by_judge: Record<string, number>;
35
+ /** Candidates that won under at least judge_stability_threshold × judges.length judges. */
36
+ readonly consensus_winners: ReadonlyArray<string>;
37
+ };
38
+
39
+ export type GateReport = {
40
+ readonly id: string;
41
+ readonly gate_run_id: string;
42
+ readonly dataset_content_hash: string;
43
+ readonly dataset_version: string;
44
+ /** SHA per candidate, keyed by candidate ref. */
45
+ readonly candidate_shas: Record<string, string>;
46
+ /** SHA per judge, keyed by judge ref. */
47
+ readonly judge_shas: Record<string, string>;
48
+ /** SHA of the scorer / evaluator code. */
49
+ readonly scorer_code_sha: string;
50
+ /** Baseline metrics: per-metric. */
51
+ readonly baseline_metrics: Record<string, number>;
52
+ /** Per-candidate metrics: aggregate delta + cost + latency. */
53
+ readonly candidate_metrics: Record<string, {
54
+ aggregate_delta: number;
55
+ cost_delta: number;
56
+ latency_delta: number;
57
+ }>;
58
+ /** Which judge picked which candidate as winner. */
59
+ readonly judge_matrix: JudgeStabilityMatrix;
60
+ /** Policy that was applied to this gate run. */
61
+ readonly policy: GatePolicy;
62
+ /** Who approved the decision (when approval_required = true). */
63
+ readonly approver?: string;
64
+ /** ISO 8601 timestamp of report signing. */
65
+ readonly timestamp: string;
66
+ /** Signature. Stub in v0.0.0-dev. */
67
+ readonly signature: string;
68
+ };
69
+
70
+ /** @deprecated Use GateReport instead. */
71
+ export type PromotionReport = GateReport;
72
+
73
+ export type GateDecision =
74
+ | {
75
+ readonly action: 'pass';
76
+ readonly winner: string;
77
+ readonly reason: string;
78
+ }
79
+ | {
80
+ readonly action: 'block';
81
+ readonly reason: string;
82
+ }
83
+ | {
84
+ readonly action: 'hold_for_review';
85
+ readonly reason: string;
86
+ };
87
+
88
+ /** @deprecated Use GateDecision instead. */
89
+ export type PromotionDecision = GateDecision;
90
+
91
+ /** Default gate policy. */
92
+ export const DEFAULT_POLICY: GatePolicy = {
93
+ min_delta: 0.02,
94
+ judge_stability_threshold: 0.67,
95
+ cost_ceiling: 0.1,
96
+ latency_ceiling: 0.2,
97
+ approval_required: false,
98
+ };