@adhd/dispatch-core-optimizer 0.1.3 → 0.1.5

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 (4) hide show
  1. package/CHANGELOG.md +15 -0
  2. package/index.js +7 -10
  3. package/index.mjs +643 -908
  4. package/package.json +2 -2
package/index.mjs CHANGED
@@ -1,911 +1,646 @@
1
- const fe = /* @__PURE__ */ new Set([
2
- "create",
3
- "modify-signature",
4
- "modify-body",
5
- "add-export",
6
- "remove-export",
7
- "rename"
8
- ]), de = /* @__PURE__ */ new Set([
9
- "pending",
10
- "pending-surfaced",
11
- "in_progress",
12
- "complete",
13
- "failed",
14
- "skipped"
15
- ]), me = /* @__PURE__ */ new Set([
16
- "pending",
17
- "in_progress",
18
- "complete",
19
- "failed",
20
- "skipped"
1
+ //#region ../dispatch-base-spec/src/lib/types.ts
2
+ var e = /* @__PURE__ */ new Set([
3
+ "create",
4
+ "modify-signature",
5
+ "modify-body",
6
+ "add-export",
7
+ "remove-export",
8
+ "rename"
9
+ ]), t = /* @__PURE__ */ new Set([
10
+ "pending",
11
+ "pending-surfaced",
12
+ "in_progress",
13
+ "complete",
14
+ "failed",
15
+ "skipped"
16
+ ]), n = /* @__PURE__ */ new Set([
17
+ "pending",
18
+ "in_progress",
19
+ "complete",
20
+ "failed",
21
+ "skipped"
21
22
  ]);
22
- function T(e) {
23
- return typeof e == "object" && e !== null && !Array.isArray(e);
23
+ function r(e) {
24
+ return typeof e == "object" && !!e && !Array.isArray(e);
25
+ }
26
+ function i(e) {
27
+ return typeof e == "string";
28
+ }
29
+ function a(e, t, n) {
30
+ return {
31
+ path: e,
32
+ message: t,
33
+ value: n
34
+ };
35
+ }
36
+ function o(e) {
37
+ let o = [];
38
+ if (!r(e)) return {
39
+ valid: !1,
40
+ errors: [a("", "root must be an object")]
41
+ };
42
+ for (let t of ["snapshot_at", "description"]) i(e[t]) || o.push(a(t, "required string field missing", e[t]));
43
+ i(e.plan) || o.push(a("plan", "required string", e.plan));
44
+ let s = e.milestones;
45
+ if (!r(s)) o.push(a("milestones", "must be an object", s));
46
+ else {
47
+ let c = Object.keys(s), l = new Set(c);
48
+ for (let e of c) {
49
+ let n = s[e];
50
+ if (!r(n)) {
51
+ o.push(a(`milestones.${e}`, "must be an object", n));
52
+ continue;
53
+ }
54
+ let c = n.eligible, l = n.pending;
55
+ c === !0 && l != null && o.push(a(`milestones.${e}`, "D-07 violation: eligible=true but pending not null")), typeof c != "boolean" && o.push(a(`milestones.${e}.eligible`, "must be boolean", c));
56
+ let u = n.status;
57
+ (!i(u) || !t.has(u)) && o.push(a(`milestones.${e}.status`, "invalid status", u)), c === !0 && u === "complete" && o.push(a(`milestones.${e}`, "D-07 violation: eligible=true but status is complete"));
58
+ let d = n.wave;
59
+ (typeof d != "number" || !Number.isInteger(d) || d < 0) && o.push(a(`milestones.${e}.wave`, "must be non-negative integer", d));
60
+ let f = n.ki_estimate;
61
+ f != null && typeof f != "number" && o.push(a(`milestones.${e}.ki_estimate`, "must be number|null", f));
62
+ for (let t of ["tokens_estimated", "tokens_actual"]) {
63
+ let r = n[t];
64
+ r != null && typeof r != "number" && o.push(a(`milestones.${e}.${t}`, "must be number|null", r));
65
+ }
66
+ Array.isArray(n.artifacts) || o.push(a(`milestones.${e}.artifacts`, "must be an array", n.artifacts)), typeof n.si_bytes != "number" && o.push(a(`milestones.${e}.si_bytes`, "must be a number", n.si_bytes));
67
+ }
68
+ let u = e.operations;
69
+ if (!Array.isArray(u)) o.push(a("operations", "must be an array", u));
70
+ else for (let e of u) {
71
+ if (!r(e)) continue;
72
+ let t = i(e.id) ? e.id : "?", s = e.milestone;
73
+ i(s) && !l.has(s) && o.push(a(`operations[${t}].milestone`, `unknown milestone "${s}"`));
74
+ let c = e.status;
75
+ (!i(c) || !n.has(c)) && o.push(a(`operations[${t}].status`, "invalid operation status", c)), Array.isArray(e.dispatch_ids) || o.push(a(`operations[${t}].dispatch_ids`, "must be an array", e.dispatch_ids)), typeof e.attempt_count != "number" && o.push(a(`operations[${t}].attempt_count`, "must be a number", e.attempt_count)), Array.isArray(e.blast_radius) || o.push(a(`operations[${t}].blast_radius`, "must be an array", e.blast_radius));
76
+ }
77
+ let d = e.open_questions;
78
+ if (!Array.isArray(d)) o.push(a("open_questions", "must be an array", d));
79
+ else for (let e of d) {
80
+ if (!r(e)) continue;
81
+ let t = e.blocking;
82
+ (!i(t) || !l.has(t)) && o.push(a("open_questions", `unknown blocking milestone "${t}"`)), typeof e.surfaced != "boolean" && o.push(a(`open_questions[${e.id}]`, "surfaced must be boolean", e.surfaced)), typeof e.answered != "boolean" && o.push(a(`open_questions[${e.id}]`, "answered must be boolean", e.answered));
83
+ }
84
+ let f = e.dispatch_units;
85
+ if (f !== void 0) {
86
+ if (!Array.isArray(f)) o.push(a("dispatch_units", "must be an array if present", f));
87
+ else for (let e of f) {
88
+ if (!r(e)) continue;
89
+ let t = e.fits_context_window;
90
+ typeof t != "boolean" && o.push(a(`dispatch_units[${e.id}]`, "fits_context_window must be boolean", t));
91
+ let n = e.milestones;
92
+ if (Array.isArray(n)) for (let t of n) i(t) && !l.has(t) && o.push(a(`dispatch_units[${e.id}].milestones`, `unknown milestone "${t}"`));
93
+ }
94
+ }
95
+ r(e.pairwise_overlap) || o.push(a("pairwise_overlap", "must be an object", e.pairwise_overlap));
96
+ }
97
+ return {
98
+ valid: o.length === 0,
99
+ errors: o
100
+ };
101
+ }
102
+ function s(e) {
103
+ let t = o(e);
104
+ if (!t.valid) throw Error(`Snapshot validation failed:\n${t.errors.map((e) => ` ${e.path}: ${e.message}`).join("\n")}`);
105
+ }
106
+ //#endregion
107
+ //#region src/lib/size-tokens.ts
108
+ var c = {
109
+ prose: 5.5,
110
+ md: 5.5,
111
+ ts: 6.3,
112
+ tsx: 6.3,
113
+ py: 6.3,
114
+ default: 4
115
+ };
116
+ function l(e, t) {
117
+ if (e <= 0) return 0;
118
+ let n = c[t ? t.split(".").pop()?.toLowerCase() ?? "" : ""] ?? c.default ?? 4;
119
+ return Math.ceil(e / n);
120
+ }
121
+ function u(e, t) {
122
+ if (e.length === 0 || t.fileSizes === void 0) return /* @__PURE__ */ new Map();
123
+ try {
124
+ return t.fileSizes(e);
125
+ } catch {
126
+ return /* @__PURE__ */ new Map();
127
+ }
128
+ }
129
+ //#endregion
130
+ //#region src/lib/snapshot.ts
131
+ var d = {
132
+ low: 600,
133
+ medium: 1e3,
134
+ high: 2e3
135
+ }, f = e;
136
+ function p(e) {
137
+ let t = e.properties ?? {};
138
+ return Object.keys(t).length || Object.keys(e).length;
139
+ }
140
+ function m(e, t) {
141
+ if (e.type === "tool-call") return 0;
142
+ let n = e.shape;
143
+ if (n?.kind == null) return 0;
144
+ let r = n.kind;
145
+ return r === "function" || r === "interface" || r === "type" || r === "class" || r === "enum" || r === "const" || r === "script" ? ("ops" in n && Array.isArray(n.ops) ? n.ops : []).length * 200 : r === "config" || r === "env" || r === "schema" || r === "manifest" ? ("ops" in n && Array.isArray(n.ops) ? n.ops : []).length * 100 : r === "doc" ? d[t ?? "medium"] ?? 1e3 : r === "structured-output" ? p("schema" in n && n.schema ? n.schema : {}) * 50 : 0;
146
+ }
147
+ function h(e, t) {
148
+ let n = /* @__PURE__ */ new Set([...Object.keys(e), ...Object.keys(t)]), r = {};
149
+ for (let i of n) r[i] = e[i] ?? t[i] ?? null;
150
+ return r;
151
+ }
152
+ function g(e, t) {
153
+ let n = /* @__PURE__ */ new Set([...Object.keys(e), ...Object.keys(t)]), r = {};
154
+ for (let i of n) {
155
+ let n = e[i] ?? t[i];
156
+ if (n === void 0) throw TypeError(`Model tier "${i}" not found in dag or deps context_window_per_tier`);
157
+ r[i] = n;
158
+ }
159
+ return r;
160
+ }
161
+ function _(e) {
162
+ let t = Object.keys(e), n = /* @__PURE__ */ new Map(), r = /* @__PURE__ */ new Map();
163
+ for (let e of t) n.has(e) || n.set(e, 0), r.has(e) || r.set(e, []);
164
+ for (let i of t) {
165
+ let t = e[i]?.depends_on ?? [];
166
+ for (let e of t) {
167
+ let t = r.get(e);
168
+ t !== void 0 && t.push(i), n.set(i, (n.get(i) ?? 0) + 1);
169
+ }
170
+ }
171
+ let i = /* @__PURE__ */ new Map(), a = [], o = t.filter((e) => (n.get(e) ?? 0) === 0).sort();
172
+ for (let e of o) i.set(e, 0);
173
+ for (; o.length > 0;) {
174
+ let e = [];
175
+ for (let t of o) {
176
+ a.push(t);
177
+ let o = (r.get(t) ?? []).slice().sort();
178
+ for (let r of o) {
179
+ let a = (n.get(r) ?? 0) - 1;
180
+ n.set(r, a);
181
+ let o = i.get(t) ?? 0, s = i.get(r) ?? 0;
182
+ i.set(r, Math.max(s, o + 1)), a === 0 && e.push(r);
183
+ }
184
+ }
185
+ o = e.sort();
186
+ }
187
+ if (a.length !== t.length) {
188
+ let e = new Set(a), n = t.filter((t) => !e.has(t));
189
+ throw Error(`snapshot(): cycle detected in milestone depends_on graph. Nodes involved: [${n.join(", ")}]`);
190
+ }
191
+ return {
192
+ order: a,
193
+ waves: i
194
+ };
195
+ }
196
+ function v(e, t) {
197
+ if (t.length === 0) return [];
198
+ let n = new Set(t);
199
+ return e.filter((e) => e.operations.some((e) => n.has(e)));
200
+ }
201
+ function y(e, t) {
202
+ return e.filter((e) => e.operations.includes(t));
203
+ }
204
+ function b(e, t, n, r, i) {
205
+ let a = `${e}.guard`, o = [...n, a], s = v(r, o);
206
+ for (let e of s) for (let t of e.results) if (t.op_id === a && t.guard_result === "pass") return "complete";
207
+ for (let e of s) for (let t of e.results) if (o.includes(t.op_id) && t.status === "failed") return "failed";
208
+ for (let e of s) for (let t of e.results) if (o.includes(t.op_id) && t.status === "in_progress") return "in_progress";
209
+ let c = i.length === 0 || i.every((e) => e === "complete");
210
+ return t.pending !== null && c ? "pending-surfaced" : "pending";
211
+ }
212
+ function x(e, t) {
213
+ let n = `${e}.guard`, r = null, i = null, a = null;
214
+ for (let e of t) if (e.operations.includes(n)) for (let t of e.results) t.op_id === n && t.guard_result !== null && (r = t.guard_result, i = t.guard_output, t.guard_result === "pass" && (a = t.guard_ran_at));
215
+ return r === null ? {
216
+ guard_result: "pending",
217
+ guard_output: null,
218
+ completed_at: null
219
+ } : {
220
+ guard_result: r,
221
+ guard_output: i,
222
+ completed_at: a
223
+ };
24
224
  }
25
225
  function S(e) {
26
- return typeof e == "string";
27
- }
28
- function g(e, t, n) {
29
- return { path: e, message: t, value: n };
30
- }
31
- function _e(e) {
32
- const t = [];
33
- if (!T(e))
34
- return { valid: !1, errors: [g("", "root must be an object")] };
35
- for (const o of ["snapshot_at", "description"])
36
- S(e[o]) || t.push(g(o, "required string field missing", e[o]));
37
- S(e.plan) || t.push(g("plan", "required string", e.plan));
38
- const n = e.milestones;
39
- if (!T(n))
40
- t.push(g("milestones", "must be an object", n));
41
- else {
42
- const o = Object.keys(n), i = new Set(o);
43
- for (const s of o) {
44
- const r = n[s];
45
- if (!T(r)) {
46
- t.push(g(`milestones.${s}`, "must be an object", r));
47
- continue;
48
- }
49
- const a = r.eligible, u = r.pending;
50
- a === !0 && u !== null && u !== void 0 && t.push(
51
- g(
52
- `milestones.${s}`,
53
- "D-07 violation: eligible=true but pending not null"
54
- )
55
- ), typeof a != "boolean" && t.push(
56
- g(`milestones.${s}.eligible`, "must be boolean", a)
57
- );
58
- const f = r.status;
59
- (!S(f) || !de.has(f)) && t.push(g(`milestones.${s}.status`, "invalid status", f)), a === !0 && f === "complete" && t.push(
60
- g(
61
- `milestones.${s}`,
62
- "D-07 violation: eligible=true but status is complete"
63
- )
64
- );
65
- const _ = r.wave;
66
- (typeof _ != "number" || !Number.isInteger(_) || _ < 0) && t.push(
67
- g(`milestones.${s}.wave`, "must be non-negative integer", _)
68
- );
69
- const y = r.ki_estimate;
70
- y != null && typeof y != "number" && t.push(
71
- g(`milestones.${s}.ki_estimate`, "must be number|null", y)
72
- );
73
- for (const v of ["tokens_estimated", "tokens_actual"]) {
74
- const b = r[v];
75
- b != null && typeof b != "number" && t.push(g(`milestones.${s}.${v}`, "must be number|null", b));
76
- }
77
- Array.isArray(r.artifacts) || t.push(
78
- g(
79
- `milestones.${s}.artifacts`,
80
- "must be an array",
81
- r.artifacts
82
- )
83
- ), typeof r.si_bytes != "number" && t.push(
84
- g(`milestones.${s}.si_bytes`, "must be a number", r.si_bytes)
85
- );
86
- }
87
- const l = e.operations;
88
- if (!Array.isArray(l))
89
- t.push(g("operations", "must be an array", l));
90
- else
91
- for (const s of l) {
92
- if (!T(s))
93
- continue;
94
- const r = S(s.id) ? s.id : "?", a = s.milestone;
95
- S(a) && !i.has(a) && t.push(
96
- g(
97
- `operations[${r}].milestone`,
98
- `unknown milestone "${a}"`
99
- )
100
- );
101
- const u = s.status;
102
- (!S(u) || !me.has(u)) && t.push(
103
- g(
104
- `operations[${r}].status`,
105
- "invalid operation status",
106
- u
107
- )
108
- ), Array.isArray(s.dispatch_ids) || t.push(
109
- g(
110
- `operations[${r}].dispatch_ids`,
111
- "must be an array",
112
- s.dispatch_ids
113
- )
114
- ), typeof s.attempt_count != "number" && t.push(
115
- g(
116
- `operations[${r}].attempt_count`,
117
- "must be a number",
118
- s.attempt_count
119
- )
120
- ), Array.isArray(s.blast_radius) || t.push(
121
- g(
122
- `operations[${r}].blast_radius`,
123
- "must be an array",
124
- s.blast_radius
125
- )
126
- );
127
- }
128
- const p = e.open_questions;
129
- if (!Array.isArray(p))
130
- t.push(g("open_questions", "must be an array", p));
131
- else
132
- for (const s of p) {
133
- if (!T(s))
134
- continue;
135
- const r = s.blocking;
136
- (!S(r) || !i.has(r)) && t.push(
137
- g("open_questions", `unknown blocking milestone "${r}"`)
138
- ), typeof s.surfaced != "boolean" && t.push(
139
- g(
140
- `open_questions[${s.id}]`,
141
- "surfaced must be boolean",
142
- s.surfaced
143
- )
144
- ), typeof s.answered != "boolean" && t.push(
145
- g(
146
- `open_questions[${s.id}]`,
147
- "answered must be boolean",
148
- s.answered
149
- )
150
- );
151
- }
152
- const c = e.dispatch_units;
153
- if (c !== void 0)
154
- if (!Array.isArray(c))
155
- t.push(
156
- g("dispatch_units", "must be an array if present", c)
157
- );
158
- else
159
- for (const s of c) {
160
- if (!T(s))
161
- continue;
162
- const r = s.fits_context_window;
163
- typeof r != "boolean" && t.push(
164
- g(
165
- `dispatch_units[${s.id}]`,
166
- "fits_context_window must be boolean",
167
- r
168
- )
169
- );
170
- const a = s.milestones;
171
- if (Array.isArray(a))
172
- for (const u of a)
173
- S(u) && !i.has(u) && t.push(
174
- g(
175
- `dispatch_units[${s.id}].milestones`,
176
- `unknown milestone "${u}"`
177
- )
178
- );
179
- }
180
- T(e.pairwise_overlap) || t.push(
181
- g(
182
- "pairwise_overlap",
183
- "must be an object",
184
- e.pairwise_overlap
185
- )
186
- );
187
- }
188
- return { valid: t.length === 0, errors: t };
189
- }
190
- function he(e) {
191
- const t = _e(e);
192
- if (!t.valid)
193
- throw new Error(
194
- `Snapshot validation failed:
195
- ${t.errors.map((n) => ` ${n.path}: ${n.message}`).join(`
196
- `)}`
197
- );
198
- }
199
- const U = {
200
- prose: 5.5,
201
- md: 5.5,
202
- ts: 6.3,
203
- tsx: 6.3,
204
- py: 6.3,
205
- default: 4
206
- };
207
- function N(e, t) {
208
- if (e <= 0)
209
- return 0;
210
- const o = U[""] ?? U.default ?? 4;
211
- return Math.ceil(e / o);
212
- }
213
- function Z(e, t) {
214
- if (e.length === 0 || t.fileSizes === void 0)
215
- return /* @__PURE__ */ new Map();
216
- try {
217
- return t.fileSizes(e);
218
- } catch {
219
- return /* @__PURE__ */ new Map();
220
- }
221
- }
222
- const ge = {
223
- low: 600,
224
- medium: 1e3,
225
- high: 2e3
226
- }, ye = fe;
227
- function be(e) {
228
- const t = e.properties ?? {};
229
- return Object.keys(t).length || Object.keys(e).length;
230
- }
231
- function ve(e, t) {
232
- if (e.type === "tool-call")
233
- return 0;
234
- const n = e.shape;
235
- if (!n || n.kind === null)
236
- return 0;
237
- const o = n.kind;
238
- if (o === "function" || o === "interface" || o === "type" || o === "class" || o === "enum" || o === "const" || o === "script")
239
- return ("ops" in n && Array.isArray(n.ops) ? n.ops : []).length * 200;
240
- if (o === "config" || o === "env" || o === "schema" || o === "manifest")
241
- return ("ops" in n && Array.isArray(n.ops) ? n.ops : []).length * 100;
242
- if (o === "doc")
243
- return ge[t ?? "medium"] ?? 1e3;
244
- if (o === "structured-output") {
245
- const i = "schema" in n && n.schema ? n.schema : {};
246
- return be(i) * 50;
247
- }
248
- return 0;
249
- }
250
- function we(e, t) {
251
- const n = /* @__PURE__ */ new Set([...Object.keys(e), ...Object.keys(t)]), o = {};
252
- for (const i of n) {
253
- const l = e[i];
254
- o[i] = l ?? t[i] ?? null;
255
- }
256
- return o;
257
- }
258
- function ke(e, t) {
259
- const n = /* @__PURE__ */ new Set([...Object.keys(e), ...Object.keys(t)]), o = {};
260
- for (const i of n) {
261
- const l = e[i] ?? t[i];
262
- if (l === void 0)
263
- throw new TypeError(
264
- `Model tier "${i}" not found in dag or deps context_window_per_tier`
265
- );
266
- o[i] = l;
267
- }
268
- return o;
269
- }
270
- function $e(e) {
271
- var c;
272
- const t = Object.keys(e), n = /* @__PURE__ */ new Map(), o = /* @__PURE__ */ new Map();
273
- for (const s of t)
274
- n.has(s) || n.set(s, 0), o.has(s) || o.set(s, []);
275
- for (const s of t) {
276
- const r = ((c = e[s]) == null ? void 0 : c.depends_on) ?? [];
277
- for (const a of r) {
278
- const u = o.get(a);
279
- u !== void 0 && u.push(s), n.set(s, (n.get(s) ?? 0) + 1);
280
- }
281
- }
282
- const i = /* @__PURE__ */ new Map(), l = [];
283
- let p = t.filter((s) => (n.get(s) ?? 0) === 0).sort();
284
- for (const s of p)
285
- i.set(s, 0);
286
- for (; p.length > 0; ) {
287
- const s = [];
288
- for (const r of p) {
289
- l.push(r);
290
- const a = (o.get(r) ?? []).slice().sort();
291
- for (const u of a) {
292
- const f = (n.get(u) ?? 0) - 1;
293
- n.set(u, f);
294
- const _ = i.get(r) ?? 0, y = i.get(u) ?? 0;
295
- i.set(u, Math.max(y, _ + 1)), f === 0 && s.push(u);
296
- }
297
- }
298
- p = s.sort();
299
- }
300
- if (l.length !== t.length) {
301
- const s = new Set(l), r = t.filter((a) => !s.has(a));
302
- throw new Error(
303
- `snapshot(): cycle detected in milestone depends_on graph. Nodes involved: [${r.join(", ")}]`
304
- );
305
- }
306
- return { order: l, waves: i };
307
- }
308
- function ee(e, t) {
309
- if (t.length === 0)
310
- return [];
311
- const n = new Set(t);
312
- return e.filter(
313
- (o) => o.operations.some((i) => n.has(i))
314
- );
315
- }
316
- function te(e, t) {
317
- return e.filter((n) => n.operations.includes(t));
318
- }
319
- function Ae(e, t, n, o, i) {
320
- const l = `${e}.guard`, p = [...n, l], c = ee(o, p);
321
- for (const r of c)
322
- for (const a of r.results)
323
- if (a.op_id === l && a.guard_result === "pass")
324
- return "complete";
325
- for (const r of c)
326
- for (const a of r.results)
327
- if (p.includes(a.op_id) && a.status === "failed")
328
- return "failed";
329
- for (const r of c)
330
- for (const a of r.results)
331
- if (p.includes(a.op_id) && // "in_progress" is not a dispatch_log result status (only complete/failed/skipped)
332
- // but orchestrators may write it; guard defensively
333
- a.status === "in_progress")
334
- return "in_progress";
335
- const s = i.length === 0 || i.every((r) => r === "complete");
336
- return t.pending !== null && s ? "pending-surfaced" : "pending";
337
- }
338
- function Oe(e, t) {
339
- const n = `${e}.guard`;
340
- let o = null, i = null, l = null;
341
- for (const p of t)
342
- if (p.operations.includes(n))
343
- for (const c of p.results)
344
- c.op_id === n && c.guard_result !== null && (o = c.guard_result, i = c.guard_output, c.guard_result === "pass" && (l = c.guard_ran_at));
345
- return o !== null ? {
346
- guard_result: o,
347
- guard_output: i,
348
- completed_at: l
349
- } : { guard_result: "pending", guard_output: null, completed_at: null };
350
- }
351
- function Se(e) {
352
- const t = /* @__PURE__ */ new Set();
353
- for (const n of e)
354
- n.action === "move" && n.to_file ? t.add(n.to_file) : ye.has(n.action) && n.file && t.add(n.file);
355
- return Array.from(t);
356
- }
357
- function Te(e, t, n) {
358
- const o = te(n, e.id), i = o.map((a) => a.id);
359
- let l = null, p = null, c = null;
360
- for (const a of o)
361
- for (const u of a.results)
362
- u.op_id === e.id && u.guard_result !== null && (l = u.guard_result, p = u.guard_output, c = u.guard_ran_at);
363
- const s = e.ki_estimate !== null && e.ki_estimate !== void 0 ? e.ki_estimate : ve(e, t), r = Me(e.shape);
364
- return {
365
- ...e,
366
- ki_estimate: s,
367
- shape: r,
368
- dispatch_ids: i,
369
- // TODO: stubbed as 0 — op-level attempt_count requires per-op dispatch log scan
370
- attempt_count: 0,
371
- guard_result: l,
372
- guard_output: p,
373
- guard_ran_at: c,
374
- // TODO: stubbed — requires gitnexus_impact MCP call (future work)
375
- blast_radius: [],
376
- // TODO: stubbed — requires same-wave op-key collision scan (future work)
377
- conflict: {
378
- detected: !1,
379
- competing_op: null,
380
- op_key: null,
381
- resolution: null
382
- },
383
- // TODO: stubbed — requires ki_estimate share prorating across dispatch totals
384
- tokens_actual: null
385
- };
386
- }
387
- function Me(e) {
388
- if (!e)
389
- return null;
390
- if (e.kind === null)
391
- return e;
392
- const t = e.kind;
393
- if (t === "function" || t === "interface" || t === "type" || t === "class" || t === "enum" || t === "const" || t === "script" || t === "config" || t === "env" || t === "schema" || t === "manifest") {
394
- const n = ("ops" in e && Array.isArray(e.ops) ? e.ops : []).map((o) => ({
395
- ...o,
396
- // TODO: from/breaking/severity require AST read + gitnexus (future work)
397
- from: null,
398
- breaking: null,
399
- severity: null
400
- }));
401
- return { ...e, ops: n };
402
- }
403
- return e;
404
- }
405
- function je(e, t, n, o) {
406
- const i = `${e}.guard`, l = te(o, i), p = l.map((a) => a.id);
407
- let c = null, s = null, r = null;
408
- for (const a of l)
409
- for (const u of a.results)
410
- u.op_id === i && u.guard_result !== null && (c = u.guard_result, s = u.guard_output, r = u.guard_ran_at);
411
- return {
412
- id: i,
413
- milestone: e,
414
- depends_on: n,
415
- type: "tool-call",
416
- action: "guard",
417
- file: null,
418
- symbol: null,
419
- provenance: null,
420
- confidence: null,
421
- audit_check: null,
422
- criteria: [],
423
- tool: null,
424
- args: null,
425
- guard: t.guard ?? null,
426
- to_file: null,
427
- to_symbol: null,
428
- ki_estimate: 0,
429
- ki_source: null,
430
- authored_by: "synthesized",
431
- status: "pending",
432
- shape: null,
433
- dispatch_ids: p,
434
- attempt_count: 0,
435
- guard_result: c,
436
- guard_output: s,
437
- guard_ran_at: r,
438
- blast_radius: [],
439
- conflict: {
440
- detected: !1,
441
- competing_op: null,
442
- op_key: null,
443
- resolution: null
444
- },
445
- tokens_actual: null
446
- };
447
- }
448
- function xe(e, t) {
449
- const n = {}, {
450
- write_multiplier: o,
451
- read_multiplier: i,
452
- hit_probability: l
453
- } = t;
454
- for (const [p, c] of Object.entries(e))
455
- c === null ? n[p] = null : n[p] = Math.round(c * ((1 - l) * o + l * i));
456
- return n;
457
- }
458
- function Ie(e, t, n) {
459
- const o = Array.from(e.keys()), i = {};
460
- for (let l = 0; l < o.length; l++)
461
- for (let p = l + 1; p < o.length; p++) {
462
- const c = o[l], s = o[p];
463
- if (c === void 0 || s === void 0)
464
- continue;
465
- const [r, a] = c < s ? [c, s] : [s, c], u = `${r}:${a}`, f = e.get(c) ?? [], _ = e.get(s) ?? [], y = new Set(
466
- f.map((w) => w.file).filter((w) => w !== null)
467
- ), v = new Set(
468
- _.map((w) => w.file).filter((w) => w !== null)
469
- ), b = Array.from(y).filter((w) => v.has(w));
470
- if (b.length === 0)
471
- continue;
472
- const A = t.get(c) ?? "pending", j = t.get(s) ?? "pending", k = A === "complete" && j === "complete";
473
- let $ = 0;
474
- for (const w of b)
475
- $ += k ? n(w) : 0;
476
- i[u] = $;
477
- }
478
- return i;
479
- }
480
- function Pe(e) {
481
- return (Array.isArray(e) ? e : Object.values(e)).map(
482
- (n) => n.type === void 0 ? { ...n, type: "generative" } : n
483
- );
484
- }
485
- function Re(e, t) {
486
- const n = (/* @__PURE__ */ new Date()).toISOString(), o = t.dispatchLog ?? e.dispatch_log, i = e.optimization.sentinel_fanout, l = we(e.optimization.b_per_tier, t.bPerTier), p = ke(
487
- e.optimization.context_window_per_tier,
488
- t.contextWindowPerTier
489
- ), c = xe(l, i), { waves: s } = $e(e.milestones), r = Pe(e.operations), a = /* @__PURE__ */ new Map();
490
- for (const m of r) {
491
- const d = a.get(m.milestone) ?? [];
492
- d.push(m), a.set(m.milestone, d);
493
- }
494
- const u = /* @__PURE__ */ new Set();
495
- for (const m of r)
496
- m.file && u.add(m.file), m.action === "move" && m.to_file && u.add(m.to_file);
497
- const f = Z(Array.from(u), t), _ = (m) => f.get(m) ?? 0, y = /* @__PURE__ */ new Map(), v = Array.from(s.entries()).sort((m, d) => m[1] - d[1] || m[0].localeCompare(d[0])).map(([m]) => m);
498
- for (const m of v) {
499
- const d = e.milestones[m];
500
- if (d === void 0)
501
- continue;
502
- const x = (a.get(m) ?? []).map((M) => M.id), I = d.depends_on.map(
503
- (M) => y.get(M) ?? "pending"
504
- ), P = Ae(
505
- m,
506
- d,
507
- x,
508
- o,
509
- I
510
- );
511
- y.set(m, P);
512
- }
513
- const b = {}, A = [];
514
- for (const m of v) {
515
- const d = e.milestones[m];
516
- if (d === void 0)
517
- continue;
518
- const x = s.get(m) ?? 0, I = a.get(m) ?? [], P = I.map((h) => h.id), M = y.get(m) ?? "pending", C = d.depends_on.map(
519
- (h) => y.get(h) ?? "pending"
520
- ), re = d.depends_on.length === 0 || C.every((h) => h === "complete"), le = C.every((h) => h !== "failed"), ue = d.pending === null && re && le && M !== "complete", E = ee(o, [
521
- ...P,
522
- `${m}.guard`
523
- ]), ce = E.length > 0 ? E.map((h) => h.started_at).sort()[0] ?? null : null;
524
- let D, B, F;
525
- if (d.guard) {
526
- const h = Oe(m, o);
527
- D = h.guard_result, B = h.guard_output, F = h.completed_at;
528
- } else
529
- D = null, B = null, F = null;
530
- const R = Se(I), K = R.reduce((h, O) => h + _(O), 0), W = I.map(
531
- (h) => Te(h, d.effort, o)
532
- );
533
- let z = null, G = 0, Y = !1;
534
- for (const h of W) {
535
- if (h.ki_estimate === null) {
536
- Y = !0;
537
- break;
538
- }
539
- G += h.ki_estimate;
540
- }
541
- Y || (z = G);
542
- let H = null;
543
- const L = d.model;
544
- if (L !== null && z !== null) {
545
- const h = c[L] ?? null;
546
- if (h !== null) {
547
- const O = N(K);
548
- H = h + O + z;
549
- }
550
- }
551
- let V = null;
552
- const J = E.filter(
553
- (h) => h.completed_at !== null && h.results.length > 0 && h.results.every(
554
- (O) => O.status === "complete" || O.status === "skipped"
555
- )
556
- );
557
- J.length > 0 && (V = J.reduce((h, O) => h + O.turns.reduce((pe, Q) => pe + Q.input_tokens + Q.output_tokens, 0), 0));
558
- const ae = je(
559
- m,
560
- d,
561
- P,
562
- o
563
- );
564
- A.push(...W, ae), b[m] = {
565
- description: d.description,
566
- ...d.rationale !== void 0 ? { rationale: d.rationale } : {},
567
- authored_by: d.authored_by,
568
- pending: d.pending,
569
- triggered_by: d.triggered_by,
570
- phase: d.phase,
571
- depends_on: d.depends_on,
572
- agent: d.agent,
573
- model: d.model,
574
- effort: d.effort,
575
- two_stage: d.two_stage,
576
- read_only: d.read_only,
577
- guard: d.guard,
578
- context: `contexts/${m}.md`,
579
- wave: x,
580
- eligible: ue,
581
- status: M,
582
- started_at: ce,
583
- completed_at: F,
584
- guard_result: D,
585
- guard_output: B,
586
- artifacts: R,
587
- si_bytes: K,
588
- ki_estimate: z,
589
- tokens_estimated: H,
590
- tokens_actual: V
591
- };
592
- }
593
- const j = Ie(
594
- a,
595
- y,
596
- _
597
- ), k = ze(e, b), w = {
598
- tokens_naive: (() => {
599
- let m = 0;
600
- for (const d of Object.values(b))
601
- if (d.eligible && d.status === "pending" && d.model !== null) {
602
- const x = l[d.model] ?? t.bPerTier[d.model] ?? 0;
603
- m += x + (d.ki_estimate ?? 0);
604
- }
605
- return m;
606
- })(),
607
- sentinel_fanout: i,
608
- context_window_override: e.optimization.context_window_override,
609
- b_override: e.optimization.b_override,
610
- b_per_tier: l,
611
- b_eff_per_tier: c,
612
- context_window_per_tier: p
613
- }, q = {
614
- snapshot_at: n,
615
- snapshot_version: 1,
616
- // callers may increment if persisting
617
- plan: "",
618
- // caller sets this from directory name
619
- schema_version: e.schema_version,
620
- plan_kind: e.plan_kind,
621
- description: e.description,
622
- problem: e.problem,
623
- approach: e.approach,
624
- executor: e.executor,
625
- ...e.executor_model !== void 0 ? { executor_model: e.executor_model } : {},
626
- ...e.executor_effort !== void 0 ? { executor_effort: e.executor_effort } : {},
627
- phases: [...e.phases],
628
- terminal: e.terminal,
629
- ...e.assumed_baseline !== void 0 ? { assumed_baseline: e.assumed_baseline } : {},
630
- optimization: w,
631
- milestones: b,
632
- operations: A,
633
- pairwise_overlap: j,
634
- open_questions: k
635
- };
636
- return he(q), q;
637
- }
638
- function ze(e, t) {
639
- const n = [];
640
- for (const [o, i] of Object.entries(t)) {
641
- const l = e.milestones[o];
642
- if (l === void 0 || l.pending === null)
643
- continue;
644
- const p = i.status === "pending-surfaced";
645
- n.push({
646
- id: `q:${o}`,
647
- text: l.pending,
648
- blocking: o,
649
- surfaced: p,
650
- // TODO: scan dispatch_log notes for the turn/dispatch where question appeared
651
- raised_at_dispatch: null,
652
- raised_at_turn: null,
653
- answered: !1,
654
- answer: null
655
- });
656
- }
657
- return n;
658
- }
659
- const Ee = "You are a dispatch-orchestrator worker agent executing one or more milestones from a dependency-DAG build plan. Each task turn gives you the full compiled instructions for this dispatch: milestone description, the operations to perform, and the guard command that defines done. Execute the operations precisely and produce real output (code, docs, or config) — never a plan or a summary in place of the work.";
660
- function ne(e) {
661
- return Object.keys(e.milestones).filter((t) => {
662
- const n = e.milestones[t];
663
- return n !== void 0 && n.eligible === !0 && n.status === "pending";
664
- });
665
- }
666
- function De(e) {
667
- if (e.length === 0 || e.every((t) => t.type === "tool-call"))
668
- return "tool-call";
669
- for (const t of e) {
670
- if (t.type !== "generative" || !t.shape || t.shape.kind === null)
671
- continue;
672
- const n = t.shape.kind;
673
- if (n === "function" || n === "interface" || n === "type" || n === "class" || n === "enum" || n === "const" || n === "script" || n === "config" || n === "env" || n === "schema" || n === "manifest")
674
- return "code-config";
675
- if (n === "doc")
676
- return "doc";
677
- if (n === "structured-output")
678
- return "structured";
679
- }
680
- return "code-config";
681
- }
682
- function Be(e) {
683
- if (!e)
684
- return "";
685
- const t = e.indexOf(":");
686
- return t >= 0 ? e.slice(t + 1) : e;
687
- }
688
- function Fe(e, t, n) {
689
- let o = !0;
690
- const i = [];
691
- for (const l of e) {
692
- const p = t[l];
693
- if (p === void 0)
694
- continue;
695
- const c = n.filter(
696
- (r) => r.milestone === l && r.action !== "guard"
697
- );
698
- c.some((r) => r.type === "generative") && (o = !1), i.push(`## Milestone: ${l}`), i.push(p.description), p.rationale && i.push(`
699
- *Rationale:* ${p.rationale}`), i.push(`
700
- ### Operations:`);
701
- for (const r of c) {
702
- const a = r.file ? ` ${r.file}` : "", u = r.symbol ? ` (${r.symbol})` : "";
703
- if (i.push(`- [${r.id}] ${r.action}${a}${u}`), r.shape && r.shape.kind !== null) {
704
- const f = r.shape;
705
- if (f.kind === "doc")
706
- i.push(` Description: ${f.description}`), i.push(` Objective: ${f.objective}`), f.required_sections && f.required_sections.length > 0 && i.push(
707
- ` Required sections: ${f.required_sections.join(", ")}`
708
- );
709
- else if (f.kind === "structured-output")
710
- i.push(
711
- ` Schema:
712
- ` + JSON.stringify(f.schema, null, 2).split(`
713
- `).map((_) => ` ${_}`).join(`
714
- `)
715
- );
716
- else if ("ops" in f && Array.isArray(f.ops))
717
- for (const _ of f.ops) {
718
- const y = _.to !== null ? ` → ${_.to}` : "", v = _.target !== null ? ` "${_.target}"` : "";
719
- if (i.push(` - ${_.op}${v}${y}`), _.type_spec)
720
- for (const [b, A] of Object.entries(_.type_spec))
721
- i.push(` - ${b}: ${A}`);
722
- }
723
- }
724
- }
725
- const s = p.guard;
726
- i.push(`
727
- ### Guard: ${s ?? "none"}`), i.push("");
728
- }
729
- return o ? null : i.join(`
730
- `);
731
- }
732
- function oe(e, t, n) {
733
- if (e === null)
734
- return null;
735
- const o = t.optimization.b_eff_per_tier[e];
736
- if (o != null)
737
- return o;
738
- const i = t.optimization.b_per_tier[e];
739
- if (i != null)
740
- return i;
741
- const l = n.bPerTier[e];
742
- return l !== void 0 ? l : null;
743
- }
744
- function se(e, t, n) {
745
- if (e === null)
746
- return Number.POSITIVE_INFINITY;
747
- const o = t.optimization.context_window_per_tier[e];
748
- if (o !== void 0)
749
- return o;
750
- const i = n.contextWindowPerTier[e];
751
- return i !== void 0 ? i : Number.POSITIVE_INFINITY;
752
- }
753
- function ie(e, t) {
754
- const n = /* @__PURE__ */ new Set();
755
- for (const o of e) {
756
- const i = t.snapshot.milestones[o];
757
- if (i !== void 0) {
758
- n.add(i.context);
759
- for (const l of i.read_only)
760
- n.add(l);
761
- for (const l of t.opsByMilestone.get(o) ?? [])
762
- l.file && n.add(l.file);
763
- }
764
- }
765
- return Array.from(n);
766
- }
767
- function X(e, t, n) {
768
- const o = oe(t, n.snapshot, n.deps);
769
- if (o === null)
770
- return null;
771
- const l = ie(e, n).reduce(
772
- (s, r) => s + (n.sizeMap.get(r) ?? 0),
773
- 0
774
- ), p = N(l), c = e.reduce(
775
- (s, r) => {
776
- var a;
777
- return s + (((a = n.snapshot.milestones[r]) == null ? void 0 : a.ki_estimate) ?? 0);
778
- },
779
- 0
780
- );
781
- return o + p + c;
782
- }
783
- function Ne(e, t, n) {
784
- const o = se(t, n.snapshot, n.deps), i = [...e].sort((c, s) => {
785
- var u, f;
786
- const r = ((u = n.snapshot.milestones[c]) == null ? void 0 : u.ki_estimate) ?? 0, a = ((f = n.snapshot.milestones[s]) == null ? void 0 : f.ki_estimate) ?? 0;
787
- return r - a || c.localeCompare(s);
788
- }), l = [];
789
- let p = [];
790
- for (const c of i) {
791
- const s = [...p, c], r = X(s, t, n);
792
- r !== null && r > o && p.length > 0 ? (l.push(p), p = [c]) : p = s;
793
- }
794
- return p.length > 0 && l.push(p), l.filter((c) => {
795
- const s = X(c, t, n);
796
- return s === null || s <= o;
797
- });
798
- }
799
- function qe(e, t, n, o) {
800
- const i = e[0] ?? "", l = o.snapshot.milestones[i], p = (l == null ? void 0 : l.effort) ?? null, c = [];
801
- for (const k of e)
802
- for (const $ of o.opsByMilestone.get(k) ?? [])
803
- c.push($.id);
804
- const s = ie(e, o), r = s.reduce(
805
- (k, $) => k + (o.sizeMap.get($) ?? 0),
806
- 0
807
- ), a = oe(n, o.snapshot, o.deps), u = e.reduce(
808
- (k, $) => {
809
- var w;
810
- return k + (((w = o.snapshot.milestones[$]) == null ? void 0 : w.ki_estimate) ?? 0);
811
- },
812
- 0
813
- ), f = a !== null ? a + N(r) + u : null, _ = se(n, o.snapshot, o.deps), y = f !== null ? f <= _ : !0, v = Be((l == null ? void 0 : l.agent) ?? null), b = Fe(e, o.snapshot.milestones, o.snapshot.operations), A = b !== null ? "model-dispatch" : "guard-only", j = b !== null ? Ee : null;
814
- return {
815
- id: `${i}.dispatch.${t}`,
816
- milestones: e,
817
- operations: c,
818
- model: n,
819
- effort: p,
820
- two_stage: (l == null ? void 0 : l.two_stage) ?? !1,
821
- provider: null,
822
- agent_name: v,
823
- execution_mode: A,
824
- mcp_servers: null,
825
- resolved_max_tokens: null,
826
- background: !0,
827
- systemPrompt: j,
828
- prompt: b,
829
- context_files: s,
830
- si_bytes: r,
831
- tokens_estimated: f,
832
- fits_context_window: y,
833
- sentinel_role: null,
834
- dispatch_log_id: null,
835
- remote_task_id: null,
836
- result: null,
837
- status: "pending",
838
- started_at: null,
839
- completed_at: null,
840
- tokens_actual: null
841
- };
842
- }
843
- function Ke(e, t) {
844
- const n = ne(e);
845
- if (n.length === 0)
846
- return [];
847
- const o = /* @__PURE__ */ new Map();
848
- for (const u of e.operations) {
849
- if (u.action === "guard")
850
- continue;
851
- const f = o.get(u.milestone) ?? [];
852
- f.push(u), o.set(u.milestone, f);
853
- }
854
- const i = /* @__PURE__ */ new Map();
855
- for (const u of n) {
856
- const f = e.milestones[u];
857
- if (f === void 0)
858
- continue;
859
- const _ = De(o.get(u) ?? []), y = f.model ?? "_null", v = `${_}:${y}`, b = i.get(v) ?? [];
860
- b.push(u), i.set(v, b);
861
- }
862
- const l = /* @__PURE__ */ new Set();
863
- for (const u of n) {
864
- const f = e.milestones[u];
865
- if (f !== void 0) {
866
- l.add(f.context);
867
- for (const _ of f.read_only)
868
- l.add(_);
869
- for (const _ of o.get(u) ?? [])
870
- _.file && l.add(_.file);
871
- }
872
- }
873
- const p = Z(Array.from(l), t), c = { snapshot: e, deps: t, sizeMap: p, opsByMilestone: o }, s = [];
874
- let r = 0;
875
- const a = Array.from(i.keys()).sort();
876
- for (const u of a) {
877
- const f = i.get(u);
878
- if (f === void 0)
879
- continue;
880
- const _ = u.slice(u.indexOf(":") + 1), y = _ !== "_null" ? _ : null, v = Ne(f, y, c);
881
- for (const b of v)
882
- s.push(qe(b, r++, y, c));
883
- }
884
- return s;
885
- }
886
- function We(e, t) {
887
- let n = 0;
888
- for (const o of ne(e)) {
889
- const i = e.milestones[o];
890
- if (i === void 0)
891
- continue;
892
- const l = Ce(i.model, e, t) ?? 0;
893
- n += l + (i.ki_estimate ?? 0);
894
- }
895
- return n;
896
- }
897
- function Ce(e, t, n) {
898
- if (e === null)
899
- return null;
900
- const o = t.optimization.b_per_tier[e];
901
- if (o != null)
902
- return o;
903
- const i = n.bPerTier[e];
904
- return i !== void 0 ? i : null;
905
- }
906
- export {
907
- We as computeTokensNaive,
908
- Ke as optimize,
909
- Re as snapshot,
910
- $e as topoSortMilestones
911
- };
226
+ let t = /* @__PURE__ */ new Set();
227
+ for (let n of e) n.action === "move" && n.to_file ? t.add(n.to_file) : f.has(n.action) && n.file && t.add(n.file);
228
+ return Array.from(t);
229
+ }
230
+ function C(e, t, n) {
231
+ let r = y(n, e.id), i = r.map((e) => e.id), a = null, o = null, s = null;
232
+ for (let t of r) for (let n of t.results) n.op_id === e.id && n.guard_result !== null && (a = n.guard_result, o = n.guard_output, s = n.guard_ran_at);
233
+ let c = e.ki_estimate !== null && e.ki_estimate !== void 0 ? e.ki_estimate : m(e, t), l = w(e.shape);
234
+ return {
235
+ ...e,
236
+ ki_estimate: c,
237
+ shape: l,
238
+ dispatch_ids: i,
239
+ attempt_count: 0,
240
+ guard_result: a,
241
+ guard_output: o,
242
+ guard_ran_at: s,
243
+ blast_radius: [],
244
+ conflict: {
245
+ detected: !1,
246
+ competing_op: null,
247
+ op_key: null,
248
+ resolution: null
249
+ },
250
+ tokens_actual: null
251
+ };
252
+ }
253
+ function w(e) {
254
+ if (!e) return null;
255
+ if (e.kind === null) return e;
256
+ let t = e.kind;
257
+ if (t === "function" || t === "interface" || t === "type" || t === "class" || t === "enum" || t === "const" || t === "script" || t === "config" || t === "env" || t === "schema" || t === "manifest") {
258
+ let t = ("ops" in e && Array.isArray(e.ops) ? e.ops : []).map((e) => ({
259
+ ...e,
260
+ from: null,
261
+ breaking: null,
262
+ severity: null
263
+ }));
264
+ return {
265
+ ...e,
266
+ ops: t
267
+ };
268
+ }
269
+ return e;
270
+ }
271
+ function T(e, t, n, r) {
272
+ let i = `${e}.guard`, a = y(r, i), o = a.map((e) => e.id), s = null, c = null, l = null;
273
+ for (let e of a) for (let t of e.results) t.op_id === i && t.guard_result !== null && (s = t.guard_result, c = t.guard_output, l = t.guard_ran_at);
274
+ return {
275
+ id: i,
276
+ milestone: e,
277
+ depends_on: n,
278
+ type: "tool-call",
279
+ action: "guard",
280
+ file: null,
281
+ symbol: null,
282
+ provenance: null,
283
+ confidence: null,
284
+ audit_check: null,
285
+ criteria: [],
286
+ tool: null,
287
+ args: null,
288
+ guard: t.guard ?? null,
289
+ to_file: null,
290
+ to_symbol: null,
291
+ ki_estimate: 0,
292
+ ki_source: null,
293
+ authored_by: "synthesized",
294
+ status: "pending",
295
+ shape: null,
296
+ dispatch_ids: o,
297
+ attempt_count: 0,
298
+ guard_result: s,
299
+ guard_output: c,
300
+ guard_ran_at: l,
301
+ blast_radius: [],
302
+ conflict: {
303
+ detected: !1,
304
+ competing_op: null,
305
+ op_key: null,
306
+ resolution: null
307
+ },
308
+ tokens_actual: null
309
+ };
310
+ }
311
+ function E(e, t) {
312
+ let n = {}, { write_multiplier: r, read_multiplier: i, hit_probability: a } = t;
313
+ for (let [t, o] of Object.entries(e)) n[t] = o === null ? null : Math.round(o * ((1 - a) * r + a * i));
314
+ return n;
315
+ }
316
+ function D(e, t, n) {
317
+ let r = Array.from(e.keys()), i = {};
318
+ for (let a = 0; a < r.length; a++) for (let o = a + 1; o < r.length; o++) {
319
+ let s = r[a], c = r[o];
320
+ if (s === void 0 || c === void 0) continue;
321
+ let [l, u] = s < c ? [s, c] : [c, s], d = `${l}:${u}`, f = e.get(s) ?? [], p = e.get(c) ?? [], m = new Set(f.map((e) => e.file).filter((e) => e !== null)), h = new Set(p.map((e) => e.file).filter((e) => e !== null)), g = Array.from(m).filter((e) => h.has(e));
322
+ if (g.length === 0) continue;
323
+ let _ = t.get(s) ?? "pending", v = t.get(c) ?? "pending", y = _ === "complete" && v === "complete", b = 0;
324
+ for (let e of g) b += y ? n(e) : 0;
325
+ i[d] = b;
326
+ }
327
+ return i;
328
+ }
329
+ function O(e) {
330
+ return (Array.isArray(e) ? e : Object.values(e)).map((e) => e.type === void 0 ? {
331
+ ...e,
332
+ type: "generative"
333
+ } : e);
334
+ }
335
+ function k(e, t) {
336
+ let n = (/* @__PURE__ */ new Date()).toISOString(), r = t.dispatchLog ?? e.dispatch_log, i = e.optimization.sentinel_fanout, a = h(e.optimization.b_per_tier, t.bPerTier), o = g(e.optimization.context_window_per_tier, t.contextWindowPerTier), c = E(a, i), { waves: d } = _(e.milestones), f = O(e.operations), p = /* @__PURE__ */ new Map();
337
+ for (let e of f) {
338
+ let t = p.get(e.milestone) ?? [];
339
+ t.push(e), p.set(e.milestone, t);
340
+ }
341
+ let m = /* @__PURE__ */ new Set();
342
+ for (let e of f) e.file && m.add(e.file), e.action === "move" && e.to_file && m.add(e.to_file);
343
+ let y = u(Array.from(m), t), w = (e) => y.get(e) ?? 0, k = /* @__PURE__ */ new Map(), j = Array.from(d.entries()).sort((e, t) => e[1] - t[1] || e[0].localeCompare(t[0])).map(([e]) => e);
344
+ for (let t of j) {
345
+ let n = e.milestones[t];
346
+ if (n === void 0) continue;
347
+ let i = b(t, n, (p.get(t) ?? []).map((e) => e.id), r, n.depends_on.map((e) => k.get(e) ?? "pending"));
348
+ k.set(t, i);
349
+ }
350
+ let M = {}, N = [];
351
+ for (let t of j) {
352
+ let n = e.milestones[t];
353
+ if (n === void 0) continue;
354
+ let i = d.get(t) ?? 0, a = p.get(t) ?? [], o = a.map((e) => e.id), s = k.get(t) ?? "pending", u = n.depends_on.map((e) => k.get(e) ?? "pending"), f = n.depends_on.length === 0 || u.every((e) => e === "complete"), m = u.every((e) => e !== "failed"), h = n.pending === null && f && m && s !== "complete", g = v(r, [...o, `${t}.guard`]), _ = g.length > 0 ? g.map((e) => e.started_at).sort()[0] ?? null : null, y, b, E;
355
+ if (n.guard) {
356
+ let e = x(t, r);
357
+ y = e.guard_result, b = e.guard_output, E = e.completed_at;
358
+ } else y = null, b = null, E = null;
359
+ let D = S(a), O = D.reduce((e, t) => e + w(t), 0), A = a.map((e) => C(e, n.effort, r)), j = null, P = 0, F = !1;
360
+ for (let e of A) {
361
+ if (e.ki_estimate === null) {
362
+ F = !0;
363
+ break;
364
+ }
365
+ P += e.ki_estimate;
366
+ }
367
+ F || (j = P);
368
+ let I = null, L = n.model;
369
+ if (L !== null && j !== null) {
370
+ let e = c[L] ?? null;
371
+ e !== null && (I = e + l(O) + j);
372
+ }
373
+ let R = null, z = g.filter((e) => e.completed_at !== null && e.results.length > 0 && e.results.every((e) => e.status === "complete" || e.status === "skipped"));
374
+ z.length > 0 && (R = z.reduce((e, t) => e + t.turns.reduce((e, t) => e + t.input_tokens + t.output_tokens, 0), 0));
375
+ let B = T(t, n, o, r);
376
+ N.push(...A, B), M[t] = {
377
+ description: n.description,
378
+ ...n.rationale === void 0 ? {} : { rationale: n.rationale },
379
+ authored_by: n.authored_by,
380
+ pending: n.pending,
381
+ triggered_by: n.triggered_by,
382
+ phase: n.phase,
383
+ depends_on: n.depends_on,
384
+ agent: n.agent,
385
+ model: n.model,
386
+ effort: n.effort,
387
+ two_stage: n.two_stage,
388
+ read_only: n.read_only,
389
+ guard: n.guard,
390
+ context: `contexts/${t}.md`,
391
+ wave: i,
392
+ eligible: h,
393
+ status: s,
394
+ started_at: _,
395
+ completed_at: E,
396
+ guard_result: y,
397
+ guard_output: b,
398
+ artifacts: D,
399
+ si_bytes: O,
400
+ ki_estimate: j,
401
+ tokens_estimated: I,
402
+ tokens_actual: R
403
+ };
404
+ }
405
+ let P = D(p, k, w), F = A(e, M), I = {
406
+ tokens_naive: (() => {
407
+ let e = 0;
408
+ for (let n of Object.values(M)) if (n.eligible && n.status === "pending" && n.model !== null) {
409
+ let r = a[n.model] ?? t.bPerTier[n.model] ?? 0;
410
+ e += r + (n.ki_estimate ?? 0);
411
+ }
412
+ return e;
413
+ })(),
414
+ sentinel_fanout: i,
415
+ context_window_override: e.optimization.context_window_override,
416
+ b_override: e.optimization.b_override,
417
+ b_per_tier: a,
418
+ b_eff_per_tier: c,
419
+ context_window_per_tier: o
420
+ }, L = {
421
+ snapshot_at: n,
422
+ snapshot_version: 1,
423
+ plan: "",
424
+ schema_version: e.schema_version,
425
+ plan_kind: e.plan_kind,
426
+ description: e.description,
427
+ problem: e.problem,
428
+ approach: e.approach,
429
+ executor: e.executor,
430
+ ...e.executor_model === void 0 ? {} : { executor_model: e.executor_model },
431
+ ...e.executor_effort === void 0 ? {} : { executor_effort: e.executor_effort },
432
+ phases: [...e.phases],
433
+ terminal: e.terminal,
434
+ ...e.assumed_baseline === void 0 ? {} : { assumed_baseline: e.assumed_baseline },
435
+ optimization: I,
436
+ milestones: M,
437
+ operations: N,
438
+ pairwise_overlap: P,
439
+ open_questions: F
440
+ };
441
+ return s(L), L;
442
+ }
443
+ function A(e, t) {
444
+ let n = [];
445
+ for (let [r, i] of Object.entries(t)) {
446
+ let t = e.milestones[r];
447
+ if (t?.pending == null) continue;
448
+ let a = i.status === "pending-surfaced";
449
+ n.push({
450
+ id: `q:${r}`,
451
+ text: t.pending,
452
+ blocking: r,
453
+ surfaced: a,
454
+ raised_at_dispatch: null,
455
+ raised_at_turn: null,
456
+ answered: !1,
457
+ answer: null
458
+ });
459
+ }
460
+ return n;
461
+ }
462
+ //#endregion
463
+ //#region src/lib/optimize.ts
464
+ var j = "You are a dispatch-orchestrator worker agent executing one or more milestones from a dependency-DAG build plan. Each task turn gives you the full compiled instructions for this dispatch: milestone description, the operations to perform, and the guard command that defines done. Execute the operations precisely and produce real output (code, docs, or config) — never a plan or a summary in place of the work.";
465
+ function M(e) {
466
+ return Object.keys(e.milestones).filter((t) => {
467
+ let n = e.milestones[t];
468
+ return n?.eligible === !0 && n.status === "pending";
469
+ });
470
+ }
471
+ function N(e) {
472
+ if (e.length === 0 || e.every((e) => e.type === "tool-call")) return "tool-call";
473
+ for (let t of e) {
474
+ if (t.type !== "generative" || t.shape?.kind == null) continue;
475
+ let e = t.shape.kind;
476
+ if (e === "function" || e === "interface" || e === "type" || e === "class" || e === "enum" || e === "const" || e === "script" || e === "config" || e === "env" || e === "schema" || e === "manifest") return "code-config";
477
+ if (e === "doc") return "doc";
478
+ if (e === "structured-output") return "structured";
479
+ }
480
+ return "code-config";
481
+ }
482
+ function P(e) {
483
+ if (!e) return "";
484
+ let t = e.indexOf(":");
485
+ return t >= 0 ? e.slice(t + 1) : e;
486
+ }
487
+ function F(e, t, n) {
488
+ let r = !0, i = [];
489
+ for (let a of e) {
490
+ let e = t[a];
491
+ if (e === void 0) continue;
492
+ let o = n.filter((e) => e.milestone === a && e.action !== "guard");
493
+ o.some((e) => e.type === "generative") && (r = !1), i.push(`## Milestone: ${a}`), i.push(e.description), e.rationale && i.push(`\n*Rationale:* ${e.rationale}`), i.push("\n### Operations:");
494
+ for (let e of o) {
495
+ let t = e.file ? ` ${e.file}` : "", n = e.symbol ? ` (${e.symbol})` : "";
496
+ if (i.push(`- [${e.id}] ${e.action}${t}${n}`), e.shape && e.shape.kind !== null) {
497
+ let t = e.shape;
498
+ if (t.kind === "doc") i.push(` Description: ${t.description}`), i.push(` Objective: ${t.objective}`), t.required_sections && t.required_sections.length > 0 && i.push(` Required sections: ${t.required_sections.join(", ")}`);
499
+ else if (t.kind === "structured-output") i.push(" Schema:\n" + JSON.stringify(t.schema, null, 2).split("\n").map((e) => ` ${e}`).join("\n"));
500
+ else if ("ops" in t && Array.isArray(t.ops)) for (let e of t.ops) {
501
+ let t = e.to === null ? "" : ` → ${e.to}`, n = e.target === null ? "" : ` "${e.target}"`;
502
+ if (i.push(` - ${e.op}${n}${t}`), e.type_spec) for (let [t, n] of Object.entries(e.type_spec)) i.push(` - ${t}: ${n}`);
503
+ }
504
+ }
505
+ }
506
+ let s = e.guard;
507
+ i.push(`\n### Guard: ${s ?? "none"}`), i.push("");
508
+ }
509
+ return r ? null : i.join("\n");
510
+ }
511
+ function I(e, t, n) {
512
+ if (e === null) return null;
513
+ let r = t.optimization.b_eff_per_tier[e];
514
+ if (r != null) return r;
515
+ let i = t.optimization.b_per_tier[e];
516
+ if (i != null) return i;
517
+ let a = n.bPerTier[e];
518
+ return a === void 0 ? null : a;
519
+ }
520
+ function L(e, t, n) {
521
+ if (e === null) return Infinity;
522
+ let r = t.optimization.context_window_per_tier[e];
523
+ if (r !== void 0) return r;
524
+ let i = n.contextWindowPerTier[e];
525
+ return i === void 0 ? Infinity : i;
526
+ }
527
+ function R(e, t) {
528
+ let n = /* @__PURE__ */ new Set();
529
+ for (let r of e) {
530
+ let e = t.snapshot.milestones[r];
531
+ if (e !== void 0) {
532
+ n.add(e.context);
533
+ for (let t of e.read_only) n.add(t);
534
+ for (let e of t.opsByMilestone.get(r) ?? []) e.file && n.add(e.file);
535
+ }
536
+ }
537
+ return Array.from(n);
538
+ }
539
+ function z(e, t, n) {
540
+ let r = I(t, n.snapshot, n.deps);
541
+ if (r === null) return null;
542
+ let i = l(R(e, n).reduce((e, t) => e + (n.sizeMap.get(t) ?? 0), 0)), a = e.reduce((e, t) => e + (n.snapshot.milestones[t]?.ki_estimate ?? 0), 0);
543
+ return r + i + a;
544
+ }
545
+ function B(e, t, n) {
546
+ let r = L(t, n.snapshot, n.deps), i = [...e].sort((e, t) => (n.snapshot.milestones[e]?.ki_estimate ?? 0) - (n.snapshot.milestones[t]?.ki_estimate ?? 0) || e.localeCompare(t)), a = [], o = [];
547
+ for (let e of i) {
548
+ let i = [...o, e], s = z(i, t, n);
549
+ s !== null && s > r && o.length > 0 ? (a.push(o), o = [e]) : o = i;
550
+ }
551
+ return o.length > 0 && a.push(o), a.filter((e) => {
552
+ let i = z(e, t, n);
553
+ return i === null || i <= r;
554
+ });
555
+ }
556
+ function V(e, t, n, r) {
557
+ let i = e[0] ?? "", a = r.snapshot.milestones[i], o = a?.effort ?? null, s = [];
558
+ for (let t of e) for (let e of r.opsByMilestone.get(t) ?? []) s.push(e.id);
559
+ let c = R(e, r), u = c.reduce((e, t) => e + (r.sizeMap.get(t) ?? 0), 0), d = I(n, r.snapshot, r.deps), f = e.reduce((e, t) => e + (r.snapshot.milestones[t]?.ki_estimate ?? 0), 0), p = d === null ? null : d + l(u) + f, m = L(n, r.snapshot, r.deps), h = p === null || p <= m, g = P(a?.agent ?? null), _ = F(e, r.snapshot.milestones, r.snapshot.operations), v = _ === null ? "guard-only" : "model-dispatch", y = _ === null ? null : j;
560
+ return {
561
+ id: `${i}.dispatch.${t}`,
562
+ milestones: e,
563
+ operations: s,
564
+ model: n,
565
+ effort: o,
566
+ two_stage: a?.two_stage ?? !1,
567
+ provider: null,
568
+ agent_name: g,
569
+ execution_mode: v,
570
+ mcp_servers: null,
571
+ resolved_max_tokens: null,
572
+ background: !0,
573
+ systemPrompt: y,
574
+ prompt: _,
575
+ context_files: c,
576
+ si_bytes: u,
577
+ tokens_estimated: p,
578
+ fits_context_window: h,
579
+ sentinel_role: null,
580
+ dispatch_log_id: null,
581
+ remote_task_id: null,
582
+ result: null,
583
+ status: "pending",
584
+ started_at: null,
585
+ completed_at: null,
586
+ tokens_actual: null
587
+ };
588
+ }
589
+ function H(e, t) {
590
+ let n = M(e);
591
+ if (n.length === 0) return [];
592
+ let r = /* @__PURE__ */ new Map();
593
+ for (let t of e.operations) {
594
+ if (t.action === "guard") continue;
595
+ let e = r.get(t.milestone) ?? [];
596
+ e.push(t), r.set(t.milestone, e);
597
+ }
598
+ let i = /* @__PURE__ */ new Map();
599
+ for (let t of n) {
600
+ let n = e.milestones[t];
601
+ if (n === void 0) continue;
602
+ let a = `${N(r.get(t) ?? [])}:${n.model ?? "_null"}`, o = i.get(a) ?? [];
603
+ o.push(t), i.set(a, o);
604
+ }
605
+ let a = /* @__PURE__ */ new Set();
606
+ for (let t of n) {
607
+ let n = e.milestones[t];
608
+ if (n !== void 0) {
609
+ a.add(n.context);
610
+ for (let e of n.read_only) a.add(e);
611
+ for (let e of r.get(t) ?? []) e.file && a.add(e.file);
612
+ }
613
+ }
614
+ let o = {
615
+ snapshot: e,
616
+ deps: t,
617
+ sizeMap: u(Array.from(a), t),
618
+ opsByMilestone: r
619
+ }, s = [], c = 0, l = Array.from(i.keys()).sort();
620
+ for (let e of l) {
621
+ let t = i.get(e);
622
+ if (t === void 0) continue;
623
+ let n = e.slice(e.indexOf(":") + 1), r = n === "_null" ? null : n, a = B(t, r, o);
624
+ for (let e of a) s.push(V(e, c++, r, o));
625
+ }
626
+ return s;
627
+ }
628
+ function U(e, t) {
629
+ let n = 0;
630
+ for (let r of M(e)) {
631
+ let i = e.milestones[r];
632
+ if (i === void 0) continue;
633
+ let a = W(i.model, e, t) ?? 0;
634
+ n += a + (i.ki_estimate ?? 0);
635
+ }
636
+ return n;
637
+ }
638
+ function W(e, t, n) {
639
+ if (e === null) return null;
640
+ let r = t.optimization.b_per_tier[e];
641
+ if (r != null) return r;
642
+ let i = n.bPerTier[e];
643
+ return i === void 0 ? null : i;
644
+ }
645
+ //#endregion
646
+ export { U as computeTokensNaive, H as optimize, k as snapshot, _ as topoSortMilestones };