@tangle-network/agent-runtime 1.0.0 → 2.0.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{activation-CFS31SWI.d.ts → activation-BuK2H7qx.d.ts} +2 -2
- package/dist/{activation-BwoSqHCc.js → activation-ZQWz04u8.js} +4 -4
- package/dist/{activation-BwoSqHCc.js.map → activation-ZQWz04u8.js.map} +1 -1
- package/dist/agent.d.ts +1 -1
- package/dist/agent.js +4 -3
- package/dist/agent.js.map +1 -1
- package/dist/{bundle-DeDkJbsr.js → bundle-PDYNXIEf.js} +2 -2
- package/dist/{bundle-DeDkJbsr.js.map → bundle-PDYNXIEf.js.map} +1 -1
- package/dist/candidate-execution/index.js +4 -4
- package/dist/{coordination-manager-ewBF777W.js → coordination-manager-BZLp9qpE.js} +8 -363
- package/dist/coordination-manager-BZLp9qpE.js.map +1 -0
- package/dist/coordination-map-routing-CUvwHAtv.js +362 -0
- package/dist/coordination-map-routing-CUvwHAtv.js.map +1 -0
- package/dist/{delegate-BiuSfwBa.js → delegate-C-MUU6ML.js} +2 -2
- package/dist/{delegate-BiuSfwBa.js.map → delegate-C-MUU6ML.js.map} +1 -1
- package/dist/durable-file-CksURHlH.js +1 -0
- package/dist/durable-file-DstVeHcj.js +228 -0
- package/dist/durable-file-DstVeHcj.js.map +1 -0
- package/dist/durable.d.ts +1 -1
- package/dist/durable.js +10 -8
- package/dist/durable.js.map +1 -1
- package/dist/{graph-D6FL1xze.js → graph-CM-6CV_K.js} +6 -5
- package/dist/{graph-D6FL1xze.js.map → graph-CM-6CV_K.js.map} +1 -1
- package/dist/graph-registry-72DlMnUl.js +585 -0
- package/dist/graph-registry-72DlMnUl.js.map +1 -0
- package/dist/graph-registry-CAX15LO6.js +1 -0
- package/dist/{improve-SiKDcz5_.js → improve-BuZ-I8DP.js} +9 -8
- package/dist/{improve-SiKDcz5_.js.map → improve-BuZ-I8DP.js.map} +1 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +12 -11
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +2 -2
- package/dist/intelligence.js +7 -7
- package/dist/{journal-store-BJPMUydp.js → journal-store-BpCOCDoO.js} +208 -635
- package/dist/journal-store-BpCOCDoO.js.map +1 -0
- package/dist/jsonl-file-BBP9Dz9w.js +429 -0
- package/dist/jsonl-file-BBP9Dz9w.js.map +1 -0
- package/dist/kernel.d.ts +1 -1
- package/dist/kernel.js +13 -12
- package/dist/{loop-runner-CqlcC0i4.js → loop-runner-BWD6v1rd.js} +2 -2
- package/dist/{loop-runner-CqlcC0i4.js.map → loop-runner-BWD6v1rd.js.map} +1 -1
- package/dist/{loop-runner-D9rcTNf2.d.ts → loop-runner-BpLTU_J4.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +1 -1
- package/dist/loop-runner-bin.js +1 -1
- package/dist/mcp/bin.js +3 -3
- package/dist/mcp/index.d.ts +1 -1
- package/dist/mcp/index.js +5 -5
- package/dist/{prepare-XWwsOh8O.js → prepare-Bv6X2Wnx.js} +4 -4
- package/dist/{prepare-XWwsOh8O.js.map → prepare-Bv6X2Wnx.js.map} +1 -1
- package/dist/{profile-C01SQZKa.js → profile-Dir2A1_2.js} +2 -2
- package/dist/{profile-C01SQZKa.js.map → profile-Dir2A1_2.js.map} +1 -1
- package/dist/profiles.d.ts +1 -1
- package/dist/{provision-supervisor-DnwR0AyW.js → provision-supervisor-BWEeWag1.js} +8 -6
- package/dist/{provision-supervisor-DnwR0AyW.js.map → provision-supervisor-BWEeWag1.js.map} +1 -1
- package/dist/{run-cancellation-CoJRKvih.js → run-cancellation-Cpm-BIUu.js} +3 -2
- package/dist/{run-cancellation-CoJRKvih.js.map → run-cancellation-Cpm-BIUu.js.map} +1 -1
- package/dist/{runtime-DSYZeav8.js → runtime-Cnr3213E.js} +18 -15
- package/dist/{runtime-DSYZeav8.js.map → runtime-Cnr3213E.js.map} +1 -1
- package/dist/{sandbox-profile-compat-CXjozdWL.js → sandbox-profile-compat-DRiz9kME.js} +2 -2
- package/dist/{sandbox-profile-compat-CXjozdWL.js.map → sandbox-profile-compat-DRiz9kME.js.map} +1 -1
- package/dist/{search-executor-DcGAOrAh.js → search-executor-__X1VKnU.js} +5 -5
- package/dist/{search-executor-DcGAOrAh.js.map → search-executor-__X1VKnU.js.map} +1 -1
- package/dist/{server-SrPLb8w0.js → server-CntFSTpW.js} +4 -4
- package/dist/{server-SrPLb8w0.js.map → server-CntFSTpW.js.map} +1 -1
- package/dist/{structural-rollout-C_lg83-u.js → structural-rollout-s8W19Mws.js} +5 -5
- package/dist/{structural-rollout-C_lg83-u.js.map → structural-rollout-s8W19Mws.js.map} +1 -1
- package/dist/{supervise-BXw89Ajc.js → supervise-Cl0F57m9.js} +32 -647
- package/dist/supervise-Cl0F57m9.js.map +1 -0
- package/dist/{supervision-discovery-CewADdEs.js → supervision-discovery-C3t0Xw-T.js} +5 -158
- package/dist/supervision-discovery-C3t0Xw-T.js.map +1 -0
- package/dist/{supervisor-hHU3ZJnR.js → supervisor-L7u3pQ1j.js} +99 -150
- package/dist/supervisor-L7u3pQ1j.js.map +1 -0
- package/dist/task-queue-DbpZAp6C.js +49 -0
- package/dist/task-queue-DbpZAp6C.js.map +1 -0
- package/dist/task-queue.js +1 -49
- package/dist/testing.d.ts +1 -1
- package/dist/testing.js +13 -13
- package/dist/top-web-BXICdHgc.js +1121 -0
- package/dist/top-web-BXICdHgc.js.map +1 -0
- package/dist/tui/bin.js +4 -3
- package/dist/tui/bin.js.map +1 -1
- package/dist/tui/index.d.ts +22 -2
- package/dist/tui/index.js +3 -3
- package/dist/{types-DTHxh4X9.d.ts → types-BfnQq-_k.d.ts} +17 -21
- package/dist/{util-ebWMWzY0.js → util-BX20UJ9X.js} +2 -2
- package/dist/{util-ebWMWzY0.js.map → util-BX20UJ9X.js.map} +1 -1
- package/package.json +10 -10
- package/skills/agent-graphs/references/authoring.md +1 -0
- package/dist/coordination-manager-ewBF777W.js.map +0 -1
- package/dist/journal-store-BJPMUydp.js.map +0 -1
- package/dist/supervise-BXw89Ajc.js.map +0 -1
- package/dist/supervision-discovery-CewADdEs.js.map +0 -1
- package/dist/supervisor-hHU3ZJnR.js.map +0 -1
- package/dist/task-queue.js.map +0 -1
- package/dist/top-snapshot-DcV7VG4m.js +0 -520
- package/dist/top-snapshot-DcV7VG4m.js.map +0 -1
|
@@ -0,0 +1,585 @@
|
|
|
1
|
+
import { m as ValidationError } from "./errors-AzSuGI23.js";
|
|
2
|
+
import { a as readCommittedJsonFile, c as withJsonlFileLock, l as sha256, n as isNoEntError, s as upsertCommittedJsonLine } from "./jsonl-file-BBP9Dz9w.js";
|
|
3
|
+
import { a as writeAtomicDurableFile } from "./durable-file-DstVeHcj.js";
|
|
4
|
+
import { n as resolveJsonPointer } from "./coordination-map-routing-CUvwHAtv.js";
|
|
5
|
+
import { z } from "zod";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
import { mkdir, readFile, readdir } from "node:fs/promises";
|
|
8
|
+
// src/runtime/supervise/graph-file-schema.ts
|
|
9
|
+
const scalar = z.union([
|
|
10
|
+
z.string(),
|
|
11
|
+
z.number().finite(),
|
|
12
|
+
z.boolean(),
|
|
13
|
+
z.null()
|
|
14
|
+
]);
|
|
15
|
+
const pointer = z.string().regex(/^(?:\/(?:[^~]|~[01])*)*$/);
|
|
16
|
+
const matchBase = {
|
|
17
|
+
node: z.string().min(1).optional(),
|
|
18
|
+
pointer
|
|
19
|
+
};
|
|
20
|
+
const equals = z.strictObject({
|
|
21
|
+
...matchBase,
|
|
22
|
+
equals: scalar
|
|
23
|
+
});
|
|
24
|
+
const oneOf = z.strictObject({
|
|
25
|
+
...matchBase,
|
|
26
|
+
in: z.array(scalar)
|
|
27
|
+
});
|
|
28
|
+
const exists = z.strictObject({
|
|
29
|
+
...matchBase,
|
|
30
|
+
exists: z.boolean()
|
|
31
|
+
});
|
|
32
|
+
const match = z.union([
|
|
33
|
+
equals,
|
|
34
|
+
oneOf,
|
|
35
|
+
exists
|
|
36
|
+
]);
|
|
37
|
+
/** The same data grammar as routes; no executable expressions or additional operators. */
|
|
38
|
+
const graphRouteWhenSchema = z.union([match, z.strictObject({ all: z.array(match).min(1) })]);
|
|
39
|
+
const parameter = z.strictObject({
|
|
40
|
+
default: z.unknown().optional(),
|
|
41
|
+
type: z.enum([
|
|
42
|
+
"string",
|
|
43
|
+
"number",
|
|
44
|
+
"integer",
|
|
45
|
+
"boolean",
|
|
46
|
+
"object",
|
|
47
|
+
"array",
|
|
48
|
+
"null"
|
|
49
|
+
]).optional()
|
|
50
|
+
});
|
|
51
|
+
const command = z.strictObject({
|
|
52
|
+
command: z.string().min(1),
|
|
53
|
+
timeoutMs: z.number().int().positive().optional()
|
|
54
|
+
});
|
|
55
|
+
const nonnegativeInteger = z.number().int().nonnegative();
|
|
56
|
+
/** Authoring envelope. Canonical profiles and topology are validated by their existing owners. */
|
|
57
|
+
const graphFileSchema = z.strictObject({
|
|
58
|
+
digest: z.string().min(1).optional(),
|
|
59
|
+
graph: z.string().min(1).optional(),
|
|
60
|
+
describe: z.string().optional(),
|
|
61
|
+
params: z.record(z.string().min(1), parameter).optional(),
|
|
62
|
+
nodes: z.array(z.strictObject({
|
|
63
|
+
id: z.string().min(1),
|
|
64
|
+
profile: z.record(z.string(), z.unknown()).optional(),
|
|
65
|
+
seat: z.union([z.string().min(1), z.array(z.string().min(1)).min(1)]).optional(),
|
|
66
|
+
needs: z.array(z.string().min(1)).optional()
|
|
67
|
+
})).min(1),
|
|
68
|
+
entry: z.array(z.union([z.string().min(1), z.strictObject({
|
|
69
|
+
node: z.string().min(1),
|
|
70
|
+
task: z.unknown()
|
|
71
|
+
})])).min(1).optional(),
|
|
72
|
+
edges: z.array(z.record(z.string(), z.unknown())),
|
|
73
|
+
gates: z.array(z.unknown()).optional(),
|
|
74
|
+
budget: z.strictObject({
|
|
75
|
+
maxIterations: nonnegativeInteger,
|
|
76
|
+
maxTokens: nonnegativeInteger,
|
|
77
|
+
maxUsd: z.number().finite().nonnegative().optional(),
|
|
78
|
+
deadlineMs: nonnegativeInteger.optional(),
|
|
79
|
+
resources: z.record(z.string(), z.strictObject({
|
|
80
|
+
unit: z.string().min(1),
|
|
81
|
+
limit: nonnegativeInteger
|
|
82
|
+
})).optional()
|
|
83
|
+
}),
|
|
84
|
+
check: z.union([
|
|
85
|
+
equals.extend({ describe: z.string().optional() }),
|
|
86
|
+
oneOf.extend({ describe: z.string().optional() }),
|
|
87
|
+
exists.extend({ describe: z.string().optional() }),
|
|
88
|
+
z.strictObject({
|
|
89
|
+
describe: z.string().optional(),
|
|
90
|
+
all: z.array(match).min(1)
|
|
91
|
+
}),
|
|
92
|
+
z.strictObject({
|
|
93
|
+
describe: z.string().optional(),
|
|
94
|
+
command
|
|
95
|
+
})
|
|
96
|
+
]).optional(),
|
|
97
|
+
deliverable: z.strictObject({
|
|
98
|
+
describe: z.string().optional(),
|
|
99
|
+
checkRef: z.string().min(1),
|
|
100
|
+
command: command.optional(),
|
|
101
|
+
when: graphRouteWhenSchema.optional()
|
|
102
|
+
}).optional(),
|
|
103
|
+
on: z.unknown().optional()
|
|
104
|
+
});
|
|
105
|
+
/** Judge the flow's terminal-output map with RouteWhen's own JSON-pointer semantics. */
|
|
106
|
+
function checkGraphRoute(when, output) {
|
|
107
|
+
return ("all" in when ? when.all : [when]).every((condition) => {
|
|
108
|
+
let document = output;
|
|
109
|
+
if (condition.node !== void 0) {
|
|
110
|
+
if (!output || typeof output !== "object" || !Object.hasOwn(output, condition.node)) return false;
|
|
111
|
+
document = output[condition.node];
|
|
112
|
+
}
|
|
113
|
+
const selected = resolveJsonPointer(document, condition.pointer);
|
|
114
|
+
if ("exists" in condition) return selected.found === condition.exists;
|
|
115
|
+
if (!selected.found) return false;
|
|
116
|
+
return "equals" in condition ? selected.value === condition.equals : condition.in.some((value) => value === selected.value);
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
// src/runtime/supervise/graph-parameters.ts
|
|
120
|
+
const triggerPart = z.strictObject({ trigger: z.array(z.string()).min(1) });
|
|
121
|
+
const literalPart = z.strictObject({ literal: z.string() });
|
|
122
|
+
/** Explicit authored trigger slots in compiled graph data. An empty list marks fully bound data. */
|
|
123
|
+
const graphTriggerBindingsSchema = z.array(z.strictObject({
|
|
124
|
+
path: z.array(z.union([z.string(), z.number().int().nonnegative()])).min(1),
|
|
125
|
+
mode: z.enum(["value", "text"]),
|
|
126
|
+
parts: z.array(z.union([literalPart, triggerPart])).min(1)
|
|
127
|
+
}).superRefine((slot, context) => {
|
|
128
|
+
if (!slot.parts.some((part) => "trigger" in part) || slot.mode === "value" && (slot.parts.length !== 1 || !("trigger" in slot.parts[0]))) context.addIssue({
|
|
129
|
+
code: "custom",
|
|
130
|
+
message: "binding requires authored trigger parts; value slots require one trigger"
|
|
131
|
+
});
|
|
132
|
+
}));
|
|
133
|
+
function readBinding(namespace, keys, bindings) {
|
|
134
|
+
let found = bindings[namespace];
|
|
135
|
+
for (const key of keys) {
|
|
136
|
+
if (!found || typeof found !== "object" || !Object.hasOwn(found, key)) throw new ValidationError(`graph parameters: missing ${[namespace, ...keys].join(".")}`);
|
|
137
|
+
found = found[key];
|
|
138
|
+
}
|
|
139
|
+
if (found === void 0) throw new ValidationError(`graph parameters: missing ${[namespace, ...keys].join(".")}`);
|
|
140
|
+
return structuredClone(found);
|
|
141
|
+
}
|
|
142
|
+
function textValue(value, expression) {
|
|
143
|
+
if (value !== null && typeof value === "object") throw new ValidationError(`graph parameters: ${expression} needs a whole JSON slot`);
|
|
144
|
+
return String(value);
|
|
145
|
+
}
|
|
146
|
+
function pendingText(parts) {
|
|
147
|
+
return parts.map((part) => "literal" in part ? part.literal : `\${trigger.${part.trigger.join(".")}}`).join("");
|
|
148
|
+
}
|
|
149
|
+
/** Compile authored slots once. Inserted values are data, never recursively parsed templates. */
|
|
150
|
+
function compileGraphParameters(value, bindings, options = {}) {
|
|
151
|
+
const visiting = /* @__PURE__ */ new Set();
|
|
152
|
+
const triggerBindings = [];
|
|
153
|
+
const bind = (item, path) => {
|
|
154
|
+
if (typeof item === "string") {
|
|
155
|
+
if (item.replace(/\$\{[^{}]+\}/g, "").includes("${")) throw new ValidationError("graph parameters: malformed reference");
|
|
156
|
+
const whole = /^\$\{([^{}]+)\}$/.exec(item);
|
|
157
|
+
const parts = [];
|
|
158
|
+
let cursor = 0;
|
|
159
|
+
let wholeValue;
|
|
160
|
+
let boundWhole = false;
|
|
161
|
+
for (const match of item.matchAll(/\$\{([^{}]+)\}/g)) {
|
|
162
|
+
if (match.index > cursor) parts.push({ literal: item.slice(cursor, match.index) });
|
|
163
|
+
const [namespace, ...keys] = match[1].split(".");
|
|
164
|
+
if (namespace !== "params" && namespace !== "trigger" || keys.length === 0) throw new ValidationError(`graph parameters: unsupported reference \${${match[1]}}`);
|
|
165
|
+
if (options.defer?.includes(namespace)) {
|
|
166
|
+
if (namespace === "trigger") parts.push({ trigger: keys });
|
|
167
|
+
else parts.push({ literal: match[0] });
|
|
168
|
+
} else {
|
|
169
|
+
const found = readBinding(namespace, keys, bindings);
|
|
170
|
+
if (whole) {
|
|
171
|
+
wholeValue = found;
|
|
172
|
+
boundWhole = true;
|
|
173
|
+
} else parts.push({ literal: textValue(found, match[1]) });
|
|
174
|
+
}
|
|
175
|
+
cursor = match.index + match[0].length;
|
|
176
|
+
}
|
|
177
|
+
if (boundWhole) return wholeValue;
|
|
178
|
+
if (cursor === 0) return item;
|
|
179
|
+
if (cursor < item.length) parts.push({ literal: item.slice(cursor) });
|
|
180
|
+
if (parts.some((part) => "trigger" in part)) triggerBindings.push({
|
|
181
|
+
path,
|
|
182
|
+
mode: whole ? "value" : "text",
|
|
183
|
+
parts
|
|
184
|
+
});
|
|
185
|
+
return pendingText(parts);
|
|
186
|
+
}
|
|
187
|
+
if (!item || typeof item !== "object") return item;
|
|
188
|
+
if (visiting.has(item)) throw new ValidationError("graph parameters: cyclic data is not JSON");
|
|
189
|
+
visiting.add(item);
|
|
190
|
+
const bound = Array.isArray(item) ? item.map((child, index) => bind(child, [...path, index])) : Object.fromEntries(Object.entries(item).map(([key, child]) => [key, bind(child, [...path, key])]));
|
|
191
|
+
visiting.delete(item);
|
|
192
|
+
return bound;
|
|
193
|
+
};
|
|
194
|
+
return {
|
|
195
|
+
value: bind(value, []),
|
|
196
|
+
triggerBindings
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
/** Legacy authored-data binding. Compiled graphs use bindCompiledGraphTriggers instead. */
|
|
200
|
+
function bindGraphParameters(value, bindings, options = {}) {
|
|
201
|
+
return compileGraphParameters(value, bindings, options).value;
|
|
202
|
+
}
|
|
203
|
+
/** Check provenance against the exact provisional values without reading trigger data. */
|
|
204
|
+
function assertGraphTriggerBindings(value, slots) {
|
|
205
|
+
const seen = /* @__PURE__ */ new Set();
|
|
206
|
+
for (const slot of graphTriggerBindingsSchema.parse(slots)) {
|
|
207
|
+
const key = JSON.stringify(slot.path.map(String));
|
|
208
|
+
if (seen.has(key)) throw new ValidationError("graph parameters: duplicate trigger binding path");
|
|
209
|
+
seen.add(key);
|
|
210
|
+
let found = value;
|
|
211
|
+
for (const key of slot.path) {
|
|
212
|
+
if (!found || typeof found !== "object" || !Object.hasOwn(found, key)) throw new ValidationError("graph parameters: trigger binding path does not exist");
|
|
213
|
+
found = found[key];
|
|
214
|
+
}
|
|
215
|
+
if (found !== pendingText(slot.parts)) throw new ValidationError("graph parameters: trigger binding does not match its provisional value");
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
/** Only explicitly recorded authored slots bind. Literal parameter/trigger values are untouched. */
|
|
219
|
+
function bindCompiledGraphTriggers(value, slots, trigger) {
|
|
220
|
+
assertGraphTriggerBindings(value, slots);
|
|
221
|
+
const bound = structuredClone(value);
|
|
222
|
+
for (const slot of slots) {
|
|
223
|
+
let parent = bound;
|
|
224
|
+
for (const key of slot.path.slice(0, -1)) parent = parent[key];
|
|
225
|
+
parent[slot.path.at(-1)] = slot.mode === "value" ? readBinding("trigger", slot.parts[0].trigger, { trigger }) : slot.parts.map((part) => "literal" in part ? part.literal : textValue(readBinding("trigger", part.trigger, { trigger }), `trigger.${part.trigger.join(".")}`)).join("");
|
|
226
|
+
}
|
|
227
|
+
return bound;
|
|
228
|
+
}
|
|
229
|
+
// src/runtime/supervise/graph-registry.ts
|
|
230
|
+
/**
|
|
231
|
+
* `graph-registry` — the designer's memory: graphs and their outcomes as files.
|
|
232
|
+
*
|
|
233
|
+
* The AgentGraph algebra makes a graph PLAIN DATA (nodes with pinned profiles,
|
|
234
|
+
* edges with registry-versioned directives, a budget, a deliverable
|
|
235
|
+
* description), which is the property that lets a graph be stored, replayed
|
|
236
|
+
* byte-identical, and mutated like code. This module is the thin durable layer
|
|
237
|
+
* on top: one JSONL record per run, the exact graph content-addressed beside
|
|
238
|
+
* it. The natural home is a SANDBOX WORKSPACE — the platform's snapshot story
|
|
239
|
+
* (Firecracker restore, warm leases, `continuity: 'resume'`) then makes the
|
|
240
|
+
* registry the agent's compounding execution memory across runs: a rerun over
|
|
241
|
+
* the same sandbox finds every graph the designer ever ran, what each cost,
|
|
242
|
+
* and whether it delivered.
|
|
243
|
+
*
|
|
244
|
+
* ORACLES STAY ENVIRONMENT-OWNED. `DeliverableSpec.check` is a function and is
|
|
245
|
+
* deliberately NOT stored: a stored graph keeps the deliverable's `describe`
|
|
246
|
+
* and an optional `checkRef`, and replay re-binds the check from the caller's
|
|
247
|
+
* environment. This is the graph contract's own doctrine — graders are
|
|
248
|
+
* environment, never workers — applied to persistence.
|
|
249
|
+
*
|
|
250
|
+
* Scoring is a documented heuristic, not a learned model: delivered beats
|
|
251
|
+
* failed, then cheaper (tokens, then iterations), then most recent. A designer
|
|
252
|
+
* that needs better selection replaces `pickBest`, not the records.
|
|
253
|
+
*/
|
|
254
|
+
const RECORDS_FILE = "records.jsonl";
|
|
255
|
+
const GRAPHS_DIR = "graphs";
|
|
256
|
+
/** Canonical serialization for content-addressing: stable key order, sorted. */
|
|
257
|
+
function canonicalJson(value) {
|
|
258
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
259
|
+
if (value && typeof value === "object") return `{${Object.entries(value).filter(([, v]) => v !== void 0).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
|
|
260
|
+
return JSON.stringify(value);
|
|
261
|
+
}
|
|
262
|
+
/** Digest of the exact graph (nodes + edges + budget + deliverable describe, and a flow graph's
|
|
263
|
+
* entry and gates). An absent key is not serialized, so a graph without `entry` keeps the digest
|
|
264
|
+
* it had before flow graphs were stored. */
|
|
265
|
+
function graphDigest(graph) {
|
|
266
|
+
return sha256(canonicalJson(graph));
|
|
267
|
+
}
|
|
268
|
+
/** Digest of the normalized task shape a designer looks records up by. */
|
|
269
|
+
function taskShapeDigest(taskShape) {
|
|
270
|
+
return sha256(canonicalJson(taskShape));
|
|
271
|
+
}
|
|
272
|
+
/** Digest of a runnable graph exactly as the registry stores it — the value
|
|
273
|
+
* `recordGraphRun` demands. Callers recording real runs hash through this,
|
|
274
|
+
* never hand-rolled, so a record always matches its graph. */
|
|
275
|
+
function digestOfGraph(graph) {
|
|
276
|
+
return storeGraph(graph).digest;
|
|
277
|
+
}
|
|
278
|
+
function storeGraph(graph) {
|
|
279
|
+
const { describe, checkRef, command, when } = graph.deliverable;
|
|
280
|
+
const content = {
|
|
281
|
+
nodes: graph.nodes,
|
|
282
|
+
edges: graph.edges,
|
|
283
|
+
budget: graph.budget,
|
|
284
|
+
...graph.triggerBindings === void 0 ? {} : { triggerBindings: graph.triggerBindings },
|
|
285
|
+
deliverable: {
|
|
286
|
+
...describe ? { describe } : {},
|
|
287
|
+
...checkRef ? { checkRef } : {},
|
|
288
|
+
...command ? { command } : {},
|
|
289
|
+
...when ? { when } : {}
|
|
290
|
+
},
|
|
291
|
+
...graph.entry === void 0 ? {} : { entry: graph.entry },
|
|
292
|
+
...graph.gates === void 0 ? {} : { gates: graph.gates }
|
|
293
|
+
};
|
|
294
|
+
return {
|
|
295
|
+
digest: graphDigest(content),
|
|
296
|
+
...content
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
function assertRecord(record) {
|
|
300
|
+
if (typeof record.graphDigest !== "string" || record.graphDigest.length === 0) throw new ValidationError("graph-registry: record.graphDigest is required");
|
|
301
|
+
if (typeof record.taskDigest !== "string" || record.taskDigest.length === 0) throw new ValidationError("graph-registry: record.taskDigest is required");
|
|
302
|
+
if (!Number.isFinite(Date.parse(record.startedAt))) throw new ValidationError("graph-registry: record.startedAt must be a timestamp");
|
|
303
|
+
if (![
|
|
304
|
+
"delivered",
|
|
305
|
+
"no-winner",
|
|
306
|
+
"unknown",
|
|
307
|
+
"running"
|
|
308
|
+
].includes(record.outcome.kind)) throw new ValidationError("graph-registry: invalid record.outcome.kind");
|
|
309
|
+
if ((record.outcome.kind === "delivered" || record.outcome.kind === "no-winner") && (!record.finishedAt || !Number.isFinite(Date.parse(record.finishedAt)))) throw new ValidationError("graph-registry: terminal outcomes require record.finishedAt");
|
|
310
|
+
if ((record.outcome.kind === "unknown" || record.outcome.kind === "running") && !record.outcome.reason) throw new ValidationError("graph-registry: incomplete outcomes require a reason");
|
|
311
|
+
if (record.source && (!record.source.kind || !record.source.id)) throw new ValidationError("graph-registry: source.kind and source.id are required");
|
|
312
|
+
if (record.finishedAt && (!Number.isFinite(Date.parse(record.finishedAt)) || Date.parse(record.finishedAt) < Date.parse(record.startedAt))) throw new ValidationError("graph-registry: finishedAt precedes startedAt or is invalid");
|
|
313
|
+
for (const [channel, value] of Object.entries(record.cost)) if (value !== void 0 && (typeof value !== "number" || !Number.isFinite(value) || value < 0)) throw new ValidationError(`graph-registry: invalid cost.${channel}`);
|
|
314
|
+
}
|
|
315
|
+
function recordKey(record) {
|
|
316
|
+
assertRecord(record);
|
|
317
|
+
if (record.source) return JSON.stringify([
|
|
318
|
+
"source",
|
|
319
|
+
record.source.kind,
|
|
320
|
+
record.source.id
|
|
321
|
+
]);
|
|
322
|
+
return JSON.stringify([
|
|
323
|
+
record.taskDigest,
|
|
324
|
+
record.graphDigest,
|
|
325
|
+
record.startedAt
|
|
326
|
+
]);
|
|
327
|
+
}
|
|
328
|
+
/** Open (or lazily create) a registry rooted at a workspace directory. The
|
|
329
|
+
* directory is the sandbox workspace; snapshots carry it across runs. */
|
|
330
|
+
function graphRegistry(root) {
|
|
331
|
+
if (!root || root.trim().length === 0) throw new ValidationError("graphRegistry: root directory is required");
|
|
332
|
+
return { root };
|
|
333
|
+
}
|
|
334
|
+
/** Append one run record; the exact graph is content-addressed beside it.
|
|
335
|
+
* Idempotent per (taskDigest, graphDigest, startedAt): a replayed append with
|
|
336
|
+
* the same key replaces the prior row rather than duplicating it. */
|
|
337
|
+
async function recordGraphRun(reg, graph, record) {
|
|
338
|
+
return recordStoredGraphRun(reg, storeGraph(graph), record);
|
|
339
|
+
}
|
|
340
|
+
/** Store an executable graph or an observed external topology in the same registry.
|
|
341
|
+
* Imported observations retain their source identity and never authorize replay.
|
|
342
|
+
* A reader refreshing facts can preserve independently joined labels; an explicit
|
|
343
|
+
* correction leaves preserveLabels unset and replaces the record. */
|
|
344
|
+
async function recordStoredGraphRun(reg, definition, record, options = {}) {
|
|
345
|
+
const { digest, ...content } = definition;
|
|
346
|
+
const stored = {
|
|
347
|
+
...content,
|
|
348
|
+
digest: digest ?? graphDigest(content)
|
|
349
|
+
};
|
|
350
|
+
if (stored.observed && !record) throw new ValidationError("graph-registry: observed graphs require a source run identity");
|
|
351
|
+
if (record) {
|
|
352
|
+
assertRecord(record);
|
|
353
|
+
if (stored.observed && !record.source) throw new ValidationError("graph-registry: observed graphs require a source run identity");
|
|
354
|
+
if (!stored.observed && !record.finishedAt) throw new ValidationError("graph-registry: native graph runs require a completion timestamp");
|
|
355
|
+
if ((!stored.observed || record.traversals !== void 0) && (!Number.isSafeInteger(record.traversals) || record.traversals < 0)) throw new ValidationError("graph-registry: native graphs require metered traversals; observed counts must be non-negative integers");
|
|
356
|
+
if (stored.digest !== record.graphDigest) throw new ValidationError(`graph-registry: record.graphDigest ${record.graphDigest} does not match the supplied graph (${stored.digest}) — record the graph that actually ran`);
|
|
357
|
+
}
|
|
358
|
+
if (graphDigest(content) !== stored.digest) throw new ValidationError("graph-registry: stored graph content does not match its digest");
|
|
359
|
+
await mkdir(join(reg.root, GRAPHS_DIR), { recursive: true });
|
|
360
|
+
const file = join(reg.root, RECORDS_FILE);
|
|
361
|
+
return withJsonlFileLock(file, async (canonicalPath) => {
|
|
362
|
+
if (!record) {
|
|
363
|
+
await persistGraph(reg, stored);
|
|
364
|
+
return stored;
|
|
365
|
+
}
|
|
366
|
+
let persisted = record;
|
|
367
|
+
if (options.preserveLabels && record.source) {
|
|
368
|
+
const prior = (await readCommittedJsonFile(canonicalPath)).find((row) => row.source?.kind === record.source.kind && row.source.id === record.source.id);
|
|
369
|
+
if (prior) {
|
|
370
|
+
const taskType = record.taskType ?? prior.taskType;
|
|
371
|
+
const priorTerminal = prior.outcome.kind === "delivered" || prior.outcome.kind === "no-winner";
|
|
372
|
+
const incomingUnassessed = record.outcome.kind === "unknown" || record.outcome.kind === "running";
|
|
373
|
+
if (priorTerminal && incomingUnassessed && prior.startedAt !== record.startedAt) throw new ValidationError("graph-registry: preserving labels requires the same task start and source identity");
|
|
374
|
+
const evidence = [...prior.evidence ?? [], ...record.evidence ?? []];
|
|
375
|
+
persisted = {
|
|
376
|
+
...record,
|
|
377
|
+
...taskType ? { taskType } : {},
|
|
378
|
+
...record.unknowns ? { unknowns: record.unknowns.filter((reason) => !(taskType && reason === "task type not explicitly labeled")) } : {},
|
|
379
|
+
...evidence.length ? { evidence: [...new Map(evidence.map((entry) => [canonicalJson(entry), entry])).values()] } : {},
|
|
380
|
+
...priorTerminal && incomingUnassessed ? {
|
|
381
|
+
outcome: prior.outcome,
|
|
382
|
+
finishedAt: prior.finishedAt,
|
|
383
|
+
cost: {
|
|
384
|
+
...record.cost,
|
|
385
|
+
...prior.cost.ms === void 0 ? {} : { ms: prior.cost.ms },
|
|
386
|
+
...prior.cost.mergeMs === void 0 ? {} : { mergeMs: prior.cost.mergeMs }
|
|
387
|
+
}
|
|
388
|
+
} : {}
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
assertRecord(persisted);
|
|
393
|
+
await persistGraph(reg, stored);
|
|
394
|
+
await upsertCommittedJsonLine(canonicalPath, persisted, recordKey);
|
|
395
|
+
return stored;
|
|
396
|
+
});
|
|
397
|
+
}
|
|
398
|
+
async function persistGraph(reg, stored) {
|
|
399
|
+
const revisionPath = join(reg.root, GRAPHS_DIR, `${stored.digest}.json`);
|
|
400
|
+
try {
|
|
401
|
+
const { digest: existingDigest, ...existing } = JSON.parse(await readFile(revisionPath, "utf8"));
|
|
402
|
+
if (existingDigest !== stored.digest || graphDigest(existing) !== stored.digest) throw new ValidationError("graph-registry: stored graph revision is immutable but its content differs");
|
|
403
|
+
} catch (error) {
|
|
404
|
+
if (!isNoEntError(error)) throw error;
|
|
405
|
+
writeAtomicDurableFile(revisionPath, JSON.stringify(stored), { preserveMode: true });
|
|
406
|
+
}
|
|
407
|
+
}
|
|
408
|
+
/** All records, newest last. */
|
|
409
|
+
async function listGraphRuns(reg) {
|
|
410
|
+
return readCommittedJsonFile(join(reg.root, RECORDS_FILE));
|
|
411
|
+
}
|
|
412
|
+
function observedTopology(record) {
|
|
413
|
+
return record.topologyDigest ?? (record.source ? "unknown" : record.graphDigest);
|
|
414
|
+
}
|
|
415
|
+
/** Records for one task shape or deterministic label query, newest last. */
|
|
416
|
+
async function graphRunsFor(reg, query = {}) {
|
|
417
|
+
const filters = typeof query === "string" ? { taskDigest: query } : query;
|
|
418
|
+
return (await listGraphRuns(reg)).filter((row) => (filters.taskDigest === void 0 || row.taskDigest === filters.taskDigest) && (filters.taskType === void 0 || (row.taskType ?? "unknown") === filters.taskType) && (filters.topologyDigest === void 0 || observedTopology(row) === filters.topologyDigest) && (filters.sourceKind === void 0 || (row.source?.kind ?? "native") === filters.sourceKind));
|
|
419
|
+
}
|
|
420
|
+
function medianKnown(values) {
|
|
421
|
+
const known = values.filter((value) => value !== void 0 && Number.isFinite(value) && value >= 0).sort((a, b) => a - b);
|
|
422
|
+
const middle = Math.floor(known.length / 2);
|
|
423
|
+
return {
|
|
424
|
+
count: known.length,
|
|
425
|
+
median: known.length === 0 ? null : known.length % 2 ? known[middle] : (known[middle - 1] + known[middle]) / 2
|
|
426
|
+
};
|
|
427
|
+
}
|
|
428
|
+
function observedGraphSummary(records) {
|
|
429
|
+
const groups = /* @__PURE__ */ new Map();
|
|
430
|
+
for (const record of records) {
|
|
431
|
+
const key = JSON.stringify([record.taskType ?? "unknown", observedTopology(record)]);
|
|
432
|
+
const rows = groups.get(key);
|
|
433
|
+
if (rows) rows.push(record);
|
|
434
|
+
else groups.set(key, [record]);
|
|
435
|
+
}
|
|
436
|
+
const summaries = [...groups.values()].map((runs) => {
|
|
437
|
+
const assessed = runs.filter((run) => run.outcome.kind === "delivered" || run.outcome.kind === "no-winner");
|
|
438
|
+
const delivered = assessed.filter((run) => run.outcome.kind === "delivered");
|
|
439
|
+
const wall = medianKnown(assessed.map((run) => run.cost.ms));
|
|
440
|
+
const merge = medianKnown(delivered.filter((run) => run.evidence?.some((entry) => entry.kind === "pr-merged")).map((run) => run.cost.mergeMs));
|
|
441
|
+
const tokens = medianKnown(assessed.map((run) => run.cost.tokens));
|
|
442
|
+
const human = medianKnown(assessed.map((run) => run.cost.humanMessages));
|
|
443
|
+
return {
|
|
444
|
+
taskType: runs[0].taskType ?? "unknown",
|
|
445
|
+
topologyDigest: observedTopology(runs[0]),
|
|
446
|
+
delivered: delivered.length,
|
|
447
|
+
assessed: assessed.length,
|
|
448
|
+
unknown: runs.length - assessed.length,
|
|
449
|
+
deliveredRate: assessed.length ? delivered.length / assessed.length : null,
|
|
450
|
+
medianWallMs: wall.median,
|
|
451
|
+
wallMsCount: wall.count,
|
|
452
|
+
medianMergeMs: merge.median,
|
|
453
|
+
mergeMsCount: merge.count,
|
|
454
|
+
medianTokens: tokens.median,
|
|
455
|
+
tokenCount: tokens.count,
|
|
456
|
+
medianHumanMessages: human.median,
|
|
457
|
+
humanMessageCount: human.count,
|
|
458
|
+
runs
|
|
459
|
+
};
|
|
460
|
+
});
|
|
461
|
+
summaries.sort((a, b) => {
|
|
462
|
+
const delivered = (b.deliveredRate ?? -1) - (a.deliveredRate ?? -1);
|
|
463
|
+
if (delivered) return delivered;
|
|
464
|
+
for (const key of [
|
|
465
|
+
"medianWallMs",
|
|
466
|
+
"medianTokens",
|
|
467
|
+
"medianHumanMessages"
|
|
468
|
+
]) {
|
|
469
|
+
if (a[key] === b[key]) continue;
|
|
470
|
+
if (a[key] === null) return 1;
|
|
471
|
+
if (b[key] === null) return -1;
|
|
472
|
+
return a[key] - b[key];
|
|
473
|
+
}
|
|
474
|
+
return a.taskType.localeCompare(b.taskType) || a.topologyDigest.localeCompare(b.topologyDigest);
|
|
475
|
+
});
|
|
476
|
+
return {
|
|
477
|
+
recordCount: records.length,
|
|
478
|
+
groups: summaries
|
|
479
|
+
};
|
|
480
|
+
}
|
|
481
|
+
/** Query and rank the same registry records using the opt-in observational
|
|
482
|
+
* policy: delivery rate, wall time, tokens, then human messages; unknowns last. */
|
|
483
|
+
async function graphCorpusSummary(reg, query = {}) {
|
|
484
|
+
return observedGraphSummary(await graphRunsFor(reg, query));
|
|
485
|
+
}
|
|
486
|
+
/** The documented heuristic: delivered beats failed; among delivered, cheaper
|
|
487
|
+
* (tokens, then iterations) wins; ties go to the most recent. */
|
|
488
|
+
function pickBestGraph(records, options = {}) {
|
|
489
|
+
if (options.policy === "observed") {
|
|
490
|
+
const group = observedGraphSummary(records).groups[0];
|
|
491
|
+
return group && pickBestGraph(group.runs);
|
|
492
|
+
}
|
|
493
|
+
const delivered = records.filter((row) => row.outcome.kind === "delivered");
|
|
494
|
+
if (delivered.length === 0) return void 0;
|
|
495
|
+
const better = (a, b) => {
|
|
496
|
+
const aTokens = a.cost.tokens ?? Number.POSITIVE_INFINITY;
|
|
497
|
+
const bTokens = b.cost.tokens ?? Number.POSITIVE_INFINITY;
|
|
498
|
+
if (aTokens !== bTokens) return aTokens < bTokens ? a : b;
|
|
499
|
+
const aIter = a.cost.iterations ?? Number.POSITIVE_INFINITY;
|
|
500
|
+
const bIter = b.cost.iterations ?? Number.POSITIVE_INFINITY;
|
|
501
|
+
if (aIter !== bIter) return aIter < bIter ? a : b;
|
|
502
|
+
return a.finishedAt >= b.finishedAt ? a : b;
|
|
503
|
+
};
|
|
504
|
+
return delivered.reduce((best, row) => better(best, row) === best ? best : row);
|
|
505
|
+
}
|
|
506
|
+
/** Load a stored graph by digest. */
|
|
507
|
+
async function loadGraph(reg, digest) {
|
|
508
|
+
try {
|
|
509
|
+
return JSON.parse(await readFile(join(reg.root, GRAPHS_DIR, `${digest}.json`), "utf8"));
|
|
510
|
+
} catch {
|
|
511
|
+
return;
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
/** The designer's lookup: replay the known-good graph for this task shape, or
|
|
515
|
+
* author a new one — with the reason stated either way (the decision is data). */
|
|
516
|
+
async function lookupGraph(reg, taskDigest) {
|
|
517
|
+
const records = await graphRunsFor(reg, taskDigest);
|
|
518
|
+
const candidates = [];
|
|
519
|
+
const loaded = /* @__PURE__ */ new Map();
|
|
520
|
+
for (const record of records) {
|
|
521
|
+
if (!loaded.has(record.graphDigest)) loaded.set(record.graphDigest, await loadGraph(reg, record.graphDigest));
|
|
522
|
+
if (!loaded.get(record.graphDigest)?.observed) candidates.push(record);
|
|
523
|
+
}
|
|
524
|
+
if (records.length && !candidates.length) return {
|
|
525
|
+
kind: "author",
|
|
526
|
+
reason: "only observed topologies are available; author an executable graph"
|
|
527
|
+
};
|
|
528
|
+
const best = pickBestGraph(candidates);
|
|
529
|
+
if (best) {
|
|
530
|
+
const graph = await loadGraph(reg, best.graphDigest);
|
|
531
|
+
if (graph) return {
|
|
532
|
+
kind: "replay",
|
|
533
|
+
graph,
|
|
534
|
+
record: best
|
|
535
|
+
};
|
|
536
|
+
return {
|
|
537
|
+
kind: "author",
|
|
538
|
+
reason: `best record's graph ${best.graphDigest.slice(0, 12)} is missing from the registry`
|
|
539
|
+
};
|
|
540
|
+
}
|
|
541
|
+
return {
|
|
542
|
+
kind: "author",
|
|
543
|
+
reason: records.length === 0 ? "first run for this task shape" : "no graph delivered for this task shape yet"
|
|
544
|
+
};
|
|
545
|
+
}
|
|
546
|
+
/** Rehydrate a stored graph, binding trigger data and an environment-owned named check. */
|
|
547
|
+
function graphFromStored(stored, environment = {}) {
|
|
548
|
+
if (stored.observed) throw new ValidationError("graphFromStored: observed topology cannot be replayed");
|
|
549
|
+
const { digest: _digest, observed: _observed, triggerBindings: _triggerBindings, deliverable, ...topology } = stored.triggerBindings !== void 0 ? bindCompiledGraphTriggers(stored, stored.triggerBindings, typeof environment === "function" ? void 0 : environment.trigger ?? {}) : typeof environment === "function" ? stored : bindGraphParameters(stored, { trigger: environment.trigger ?? {} });
|
|
550
|
+
const selected = typeof environment === "function" ? environment : environment.checks && Object.hasOwn(environment.checks, deliverable.checkRef ?? "") ? environment.checks[deliverable.checkRef] : deliverable.checkRef === "command" ? deliverable.command : deliverable.checkRef === "route" && deliverable.when ? ((out, context) => context ? context.originalVerdict?.valid !== false : checkGraphRoute(deliverable.when, out)) : void 0;
|
|
551
|
+
if (!selected) throw new ValidationError(`graphFromStored: unknown checkRef ${deliverable.checkRef ?? "(missing)"}`);
|
|
552
|
+
const materialized = stored.triggerBindings === void 0 ? {} : { triggerBindings: [] };
|
|
553
|
+
if (typeof selected === "function") {
|
|
554
|
+
const { command: _command, ...description } = deliverable;
|
|
555
|
+
return {
|
|
556
|
+
...topology,
|
|
557
|
+
...materialized,
|
|
558
|
+
deliverable: {
|
|
559
|
+
...description,
|
|
560
|
+
check: selected
|
|
561
|
+
}
|
|
562
|
+
};
|
|
563
|
+
}
|
|
564
|
+
const command = selected === deliverable.command ? selected : bindGraphParameters(selected, { trigger: environment.trigger ?? {} });
|
|
565
|
+
return {
|
|
566
|
+
...topology,
|
|
567
|
+
...materialized,
|
|
568
|
+
deliverable: {
|
|
569
|
+
...deliverable,
|
|
570
|
+
command,
|
|
571
|
+
check: () => false
|
|
572
|
+
}
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
/** Digests present on disk (integrity probe for tests and audits). */
|
|
576
|
+
async function storedGraphDigests(reg) {
|
|
577
|
+
try {
|
|
578
|
+
return (await readdir(join(reg.root, GRAPHS_DIR))).filter((name) => name.endsWith(".json")).map((name) => name.slice(0, -5)).sort();
|
|
579
|
+
} catch {
|
|
580
|
+
return [];
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
export { compileGraphParameters as _, graphRegistry as a, graphRouteWhenSchema as b, loadGraph as c, recordGraphRun as d, recordStoredGraphRun as f, bindGraphParameters as g, assertGraphTriggerBindings as h, graphFromStored as i, lookupGraph as l, taskShapeDigest as m, graphCorpusSummary as n, graphRunsFor as o, storedGraphDigests as p, graphDigest as r, listGraphRuns as s, digestOfGraph as t, pickBestGraph as u, graphTriggerBindingsSchema as v, graphFileSchema as y };
|
|
584
|
+
|
|
585
|
+
//# sourceMappingURL=graph-registry-72DlMnUl.js.map
|