trantor 0.18.157 → 0.18.159

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.
@@ -6,14 +6,14 @@
6
6
  },
7
7
  "metadata": {
8
8
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + context-handoff for independent AI coding agents (Claude, Codex, Gemini, …)",
9
- "version": "0.18.157"
9
+ "version": "0.18.159"
10
10
  },
11
11
  "plugins": [
12
12
  {
13
13
  "name": "trantor",
14
14
  "source": "./",
15
15
  "description": "The hub-world for AI agent crews. Say \"fire up the crew\" and Claude becomes the architect: a plan-aware Advisor routes the work (solo / cheap inline calls / live crew of Codex, GLM, Kimi & DeepSeek in their own terminal windows), a Kanban/flow command center with a testing gate tracks it, and an economics brain (Scrooge) keeps the receipts. Includes the relay MCP, a SessionStart auto-discovery hook, and a PreCompact context-handoff so a fresh session can take over a full window instead of compacting.",
16
- "version": "0.18.157",
16
+ "version": "0.18.159",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.157",
3
+ "version": "0.18.159",
4
4
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek)",
5
5
  "mcpServers": {
6
6
  "relay": {
package/bin/crew/open.mjs CHANGED
@@ -122,12 +122,16 @@ function orchestratorCommand(ctx, id) {
122
122
  return `${env} claude${harnessFlag(ctx)} ${action}`;
123
123
  }
124
124
 
125
- function reportOrchestrator(ctx, pane, id) {
125
+ export function orchestratorResumeArgv(ctx, id) {
126
126
  const resumeArgv = ["env", ...STRIP.flatMap(name => ["-u", name]), `TRANTOR_ORCH=${ctx.project}`, "claude"];
127
127
  // #14563: the reported resume argv must be the SAME command the pane runs, dial included.
128
128
  resumeArgv.push(...harnessFlag(ctx).trim().split(" "));
129
129
  resumeArgv.push("--resume", id);
130
- reportAgent(ctx, pane, "claude", { sessionId: id, resumeArgv });
130
+ return resumeArgv;
131
+ }
132
+
133
+ function reportOrchestrator(ctx, pane, id) {
134
+ reportAgent(ctx, pane, "claude", { sessionId: id, resumeArgv: orchestratorResumeArgv(ctx, id) });
131
135
  }
132
136
 
133
137
  export function paneHasAgent(ctx, pane) {
package/bin/dispatch.mjs CHANGED
@@ -11,6 +11,10 @@ import {
11
11
  } from "../lib/dispatcher/preflight.mjs";
12
12
 
13
13
  const args = process.argv.slice(2);
14
+ if (args[0] === 'policy' && args[1] === 'draft') {
15
+ const { runPolicyDraft } = await import('./policy-draft.mjs');
16
+ process.exit(await runPolicyDraft(args.slice(2)));
17
+ }
14
18
  const asJson = args.includes("--json");
15
19
  const flag = (name) => { const i = args.indexOf(name); return i > -1 ? args[i + 1] : null; };
16
20
  const flags = (name) => args.flatMap((a, i) => (a === name ? [args[i + 1]] : []));
package/bin/duty.mjs CHANGED
@@ -15,7 +15,7 @@
15
15
  // same crew-runner as crew seats, with a triage doctrine instead of "work your card".
16
16
  import { spawn, execSync, execFileSync } from "node:child_process";
17
17
  import { readFileSync, writeFileSync, existsSync, mkdirSync, openSync, rmSync, unlinkSync } from "node:fs";
18
- import { join, dirname } from "node:path";
18
+ import { join, dirname, resolve } from "node:path";
19
19
  import { homedir } from "node:os";
20
20
  import { fileURLToPath } from "node:url";
21
21
  import { loadOrCreate } from "../lib/identity.mjs";
@@ -32,6 +32,7 @@ const DUTY_LABEL = "com.trantor.duty";
32
32
  const DUTY_PLIST = join(homedir(), "Library", "LaunchAgents", `${DUTY_LABEL}.plist`);
33
33
 
34
34
  const argv = process.argv.slice(2);
35
+ const IS_MAIN = process.argv[1] && fileURLToPath(import.meta.url) === resolve(process.argv[1]);
35
36
  const cmd = argv[0] || "status";
36
37
  const val = (k, d) => { const i = argv.indexOf(`--${k}`); return i >= 0 ? (argv[i + 1] || d) : d; };
37
38
 
@@ -170,10 +171,15 @@ function keepalivePlistBody() {
170
171
  // a command line. Single-quote every value so bash 3.2 treats them literally. #14646: the node is
171
172
  // resolved at EXEC time (command -v node against the PATH exported above) — a pinned execPath is
172
173
  // a versioned Homebrew Cellar path that `brew upgrade node` deletes out from under launchd.
173
- function writeLauncher(env) {
174
+ export function launcherBody(env) {
174
175
  const shquote = (v) => `'${String(v).replace(/'/g, `'\\''`)}'`;
175
176
  const exports = Object.entries(env).map(([k, v]) => `export ${k}=${shquote(v)}`).join("\n");
176
- writeFileSync(LAUNCHER, `#!/bin/bash\n# written by \`trantor duty up\` — safe to delete when the seat is down\n${exports}\n${nodeResolverSnippet()}\nexec "$NODE_BIN" ${shquote(join(ROOT, "bin", "crew-runner.mjs"))} ${shquote(AGENT)} ${shquote(DIR)}\n`, { mode: 0o700 });
177
+ // #14774: launchd reruns this script; $$ remains the runner's pid across exec.
178
+ return `#!/bin/bash\n# written by \`trantor duty up\` — safe to delete when the seat is down\n${exports}\n${nodeResolverSnippet()}\nprintf '%s\\n' "$$" > ${shquote(PIDF)}\nexec "$NODE_BIN" ${shquote(join(ROOT, "bin", "crew-runner.mjs"))} ${shquote(AGENT)} ${shquote(DIR)}\n`;
179
+ }
180
+
181
+ function writeLauncher(env) {
182
+ writeFileSync(LAUNCHER, launcherBody(env), { mode: 0o700 });
177
183
  }
178
184
 
179
185
  // The old headless start: a detached child of whoever ran `up`. No keepalive — it dies with a
@@ -218,7 +224,7 @@ function closeDutyWorkspace() {
218
224
  return closed;
219
225
  }
220
226
 
221
- if (cmd === "up") {
227
+ if (IS_MAIN && cmd === "up") {
222
228
  const hub = fleetHub();
223
229
  mkdirSync(DIR, { recursive: true });
224
230
  const prior = alivePid();
@@ -309,7 +315,7 @@ if (cmd === "up") {
309
315
  process.exit(0); // the seat IS up; a hub that won't feed it is a warning, not a failed start
310
316
  }
311
317
 
312
- if (cmd === "down") {
318
+ if (IS_MAIN && cmd === "down") {
313
319
  const hadKeepalive = existsSync(DUTY_PLIST);
314
320
  // Unload the keepalive FIRST (bootout kills the job's process), then remove the plist so a
315
321
  // reboot cannot resurrect the seat behind a `down`. `up` rewrites both.
@@ -361,7 +367,7 @@ function dutyHealth() {
361
367
  }
362
368
 
363
369
  // status
364
- {
370
+ if (IS_MAIN) {
365
371
  const pid = alivePid();
366
372
  // Lead with what it IS. Someone running this because an unexplained window appeared should not
367
373
  // have to read source to find out what started on their machine.
@@ -14,12 +14,14 @@ const PLIST = join(homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
14
14
  const LOG = "/tmp/trantor-herdr-server.log";
15
15
  const RESTORE_LOG = "/tmp/trantor-herdr-restore.log";
16
16
  const RESTORE_SCRIPT = join(homedir(), "Library", "LaunchAgents", "trantor-herdr-restore.sh");
17
+ const LAUNCHCTL = process.env.TRANTOR_LAUNCHCTL_BIN || "/bin/launchctl";
17
18
  const D = "\x1b[2m", R = "\x1b[0m";
18
19
 
19
20
  const shellQuote = value => `'${String(value).replaceAll("'", `'\\''`)}'`;
20
21
  const xmlEscape = value => String(value).replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;");
21
22
 
22
23
  export function herdrBin() {
24
+ if (process.env.TRANTOR_HERDR_BIN) return process.env.TRANTOR_HERDR_BIN;
23
25
  // launchd runs with a minimal PATH, so the absolute path has to be baked in at install time.
24
26
  for (const p of [join(homedir(), ".local/bin/herdr"), "/opt/homebrew/bin/herdr", "/usr/local/bin/herdr"]) {
25
27
  if (existsSync(p)) return p;
@@ -131,25 +133,32 @@ if (cmd === "install") {
131
133
  writeFileSync(RESTORE_SCRIPT, restoreScriptBody({ herdr: bin }));
132
134
  chmodSync(RESTORE_SCRIPT, 0o755);
133
135
  writeFileSync(PLIST, plistBody(bin));
134
- // bootout first so a re-install replaces rather than stacks
135
- try { execFileSync("/bin/launchctl", ["bootout", `gui/${uid}/${LABEL}`], { stdio: "ignore" }); } catch { /* not loaded */ }
136
- try {
137
- execFileSync("/bin/launchctl", ["bootstrap", `gui/${uid}`, PLIST], { stdio: "ignore" });
138
- } catch (e) {
139
- console.error(`wrote ${PLIST} but launchctl bootstrap failed: ${e?.message || e}`);
140
- process.exit(1);
136
+ let running = false;
137
+ try { running = /status:\s*running/.test(execFileSync(bin, ["status"], { encoding: "utf8" })); } catch { /* server down */ }
138
+ if (running) {
139
+ // #14774: this launchd job IS the running server; booting it out kills every restored pane.
140
+ console.log("herdr is already running; left the server and every pane alive — the updated plist takes effect at next login");
141
+ } else {
142
+ // bootout first so a re-install replaces rather than stacks
143
+ try { execFileSync(LAUNCHCTL, ["bootout", `gui/${uid}/${LABEL}`], { stdio: "ignore" }); } catch { /* not loaded */ }
144
+ try {
145
+ execFileSync(LAUNCHCTL, ["bootstrap", `gui/${uid}`, PLIST], { stdio: "ignore" });
146
+ } catch (e) {
147
+ console.error(`wrote ${PLIST} but launchctl bootstrap failed: ${e?.message || e}`);
148
+ process.exit(1);
149
+ }
141
150
  }
142
151
  console.log(`herdr's server now starts at login (${bin} server)`);
143
152
  console.log(`${D}plist: ${PLIST} log: ${LOG} restore log: ${RESTORE_LOG}${R}`);
144
153
  } else if (cmd === "remove") {
145
- try { execFileSync("/bin/launchctl", ["bootout", `gui/${uid}/${LABEL}`], { stdio: "ignore" }); } catch { /* not loaded */ }
154
+ try { execFileSync(LAUNCHCTL, ["bootout", `gui/${uid}/${LABEL}`], { stdio: "ignore" }); } catch { /* not loaded */ }
146
155
  if (existsSync(PLIST)) { unlinkSync(PLIST); console.log("removed the herdr login agent"); }
147
156
  else console.log("no herdr login agent installed");
148
157
  } else if (cmd === "status") {
149
158
  const installed = existsSync(PLIST);
150
159
  let loaded = false;
151
160
  try {
152
- loaded = execFileSync("/bin/launchctl", ["list"], { encoding: "utf8" }).split("\n").some(l => l.includes(LABEL));
161
+ loaded = execFileSync(LAUNCHCTL, ["list"], { encoding: "utf8" }).split("\n").some(l => l.includes(LABEL));
153
162
  } catch { /* launchctl unavailable */ }
154
163
  let running = false;
155
164
  try { running = /status:\s*running/.test(execFileSync(herdrBin() || "herdr", ["status"], { encoding: "utf8" })); } catch { /* server down */ }
package/bin/patrol.mjs CHANGED
@@ -88,7 +88,7 @@ export function buildPatrolReport(rawInventory = {}, reaped = [], { bus = busDir
88
88
  orphans.push({ type: "live-runner-without-row", project: p, agent: runner.agent, pid: runner.pid, dir: runner.dir });
89
89
  }
90
90
  // #13474: the same rule the runner refuses a turn on.
91
- const mm = providerMismatch(String(runner?.agent || ""), runner?.model);
91
+ const mm = providerMismatch(String(runner?.agent || ""), runner?.model, runner?.modelSource);
92
92
  if (mm) {
93
93
  warnings.push({
94
94
  type: "seat-model-provider-mismatch",
@@ -0,0 +1,40 @@
1
+ #!/usr/bin/env node
2
+ import { pathToFileURL } from 'node:url';
3
+ import { signedPost, sessionContext } from '../hooks/lib/api.mjs';
4
+
5
+ export async function runPolicyDraft(args, { post = signedPost, context = sessionContext,
6
+ print = console.log, report = console.error } = {}) {
7
+ if (args.includes('--help')) {
8
+ print('trantor dispatch policy draft [--project <project>] [--version <new-version>] [--json]\nPrints the full policy JSON; summary goes to stderr. --json prints {policy,summary}. Does not activate.');
9
+ return 0;
10
+ }
11
+ const values = {};
12
+ for (let index = 0; index < args.length; index++) {
13
+ const arg = args[index];
14
+ if (arg === '--json') continue;
15
+ if (!['--project', '--version'].includes(arg) || !args[index + 1] || args[index + 1].startsWith('--')) {
16
+ report(`Invalid policy draft option: ${arg}`);
17
+ return 2;
18
+ }
19
+ values[arg.slice(2)] = args[++index];
20
+ }
21
+ const project = values.project || context().project;
22
+ if (!project) { report('Policy draft requires --project.'); return 2; }
23
+ const request = { project };
24
+ if (values.version) request.version = values.version;
25
+ const response = await post('/dispatcher/policy/draft', request,
26
+ { project, timeoutMs: 30_000 });
27
+ if (!response.ok) {
28
+ report(`Policy draft failed: ${response.json?.code || response.reason || `HTTP ${response.status}`}`);
29
+ return 1;
30
+ }
31
+ const { policy, summary } = response.json;
32
+ print(JSON.stringify(args.includes('--json') ? response.json : policy, null, 2));
33
+ report(`Draft ${policy.version} (parent ${summary.parentVersion}): ${summary.rosterEntries} bound seats, ${summary.priorsDerived} priors from ${summary.rowsRead} history rows.`);
34
+ report(JSON.stringify(summary, null, 2));
35
+ return 0;
36
+ }
37
+
38
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
39
+ process.exitCode = await runPolicyDraft(process.argv.slice(2));
40
+ }
@@ -13,6 +13,7 @@ const HERE = dirname(fileURLToPath(import.meta.url)); // <pkg>/hooks/
13
13
  const PKGROOT = join(HERE, "..", "..");
14
14
  const CMUX_APP_BIN = "/Applications/cmux.app/Contents/Resources/bin/cmux";
15
15
  const TIMEOUT = 2000; // contract: every subprocess ≤2s
16
+ const OPENCODE_BACKED = new Set(["glm", "deepseek", "qwen", "openrouter", "dsh", "opencode"]);
16
17
 
17
18
  const busDir = () => process.env.RELAY_DATA_DIR || join(homedir(), ".agent-bus");
18
19
 
@@ -97,8 +98,10 @@ export function liveRunners(project = null) {
97
98
  // never return the rest of `ps eww`, which can contain provider credentials.
98
99
  const envLine = run("ps", ["eww", "-p", String(pid), "-o", "command="]);
99
100
  const pinnedModel = (envLine.match(/(?:^|\s)CREW_MODEL=([^\s]*)/) || [])[1] || "";
100
- const model = pinnedModel || globalModel;
101
- const modelSource = pinnedModel ? "crew" : (globalModel ? "opencode-global" : "");
101
+ const base = agent.split(":").pop().replace(/-\d+$/, "");
102
+ const defaultModel = OPENCODE_BACKED.has(base) ? globalModel : "";
103
+ const model = pinnedModel || defaultModel;
104
+ const modelSource = pinnedModel ? "crew" : (defaultModel ? "opencode-global" : "cli-default");
102
105
  out.push({ pid, agent, dir, model, modelSource });
103
106
  }
104
107
  return out;
@@ -5,7 +5,7 @@
5
5
  import { readFileSync, existsSync, appendFileSync } from "node:fs";
6
6
  import { join, basename, dirname } from "node:path";
7
7
  import { homedir, hostname } from "node:os";
8
- import { execSync, spawn } from "node:child_process";
8
+ import { execSync, spawn, spawnSync } from "node:child_process";
9
9
  import { fileURLToPath } from "node:url";
10
10
  import { resolveProject, hostId, resolveHubInfo, knownProjects, nonSeatReason, nestedProjects, readConfig as readBusConfig, handoffDir, readOrchSession, writeOrchSession, busDirFor } from "../lib/project.mjs";
11
11
  import { formatSubagentManifest } from "../lib/subagent-manifest.mjs";
@@ -21,6 +21,8 @@ import { HUB_DOWN_LINE, loopbackUrl, shouldWarnUnpinned, wantsBuildDoctrine } fr
21
21
  import { memoryStartLine } from "./lib/memory-start.mjs";
22
22
  import { staleResumeLine } from "./lib/cc-signals.mjs";
23
23
  import { machineLabel } from "../lib/machine-label.mjs";
24
+ import { reportHerdrSessionResume } from "../lib/herdr-integration.mjs";
25
+ import { orchestratorResumeArgv } from "../bin/crew/open.mjs";
24
26
 
25
27
  // The build doctrine (docs/BUILD-DOCTRINE.md) in short form, one line per rule, injected for every
26
28
  // project's ORCHESTRATOR at boot (#6452): orchestrators that never opened the doc missed the ruling.
@@ -48,6 +50,22 @@ function buildDoctrineShortForm() {
48
50
 
49
51
  function nowSec() { try { return Number(execSync("date +%s", { encoding: "utf8" }).trim()) || 0; } catch { return 0; } }
50
52
 
53
+ async function reportRestoredHerdrSession({ source, project, sessionId, transcriptPath, isOrchPane, isPrintRun }) {
54
+ const pane = process.env.HERDR_PANE_ID || "";
55
+ if (source !== "startup" || !isOrchPane || isPrintRun || !sessionId || !process.env.HERDR_ENV || !pane) return;
56
+ try {
57
+ const listed = spawnSync("herdr", ["agent", "list"], { encoding: "utf8", timeout: 1500 });
58
+ if (listed.status !== 0) return;
59
+ const agents = JSON.parse(listed.stdout || "{}")?.result?.agents;
60
+ const restored = Array.isArray(agents) && agents.find(a => a?.pane_id === pane)?.agent_session?.value;
61
+ if (!restored || restored === sessionId) return;
62
+ const root = dirname(dirname(fileURLToPath(import.meta.url)));
63
+ const resumeArgv = orchestratorResumeArgv({ root, project, env: process.env }, sessionId);
64
+ const reported = await reportHerdrSessionResume({ pane, sessionId, transcriptPath, resumeArgv });
65
+ if (reported) process.stderr.write(`[trantor] restored herdr pane ${pane} now follows session ${sessionId}\n`);
66
+ } catch {}
67
+ }
68
+
51
69
  function readStdin() {
52
70
  return new Promise(res => { let d = ""; process.stdin.setEncoding("utf8");
53
71
  process.stdin.on("data", c => (d += c)); process.stdin.on("end", () => res(d));
@@ -448,6 +466,8 @@ try {
448
466
  const isPrintRun = String(process.env.CLAUDE_CODE_ENTRYPOINT || "cli").startsWith("sdk-");
449
467
  const orchEnv = process.env.TRANTOR_ORCH || "";
450
468
  const isOrchPane = !!orchEnv && (orchEnv === "1" || orchEnv === project); // project-matched: a child claude in another dir must not inherit the badge
469
+ await reportRestoredHerdrSession({ source, project, sessionId: String(stdinObj.session_id || ""),
470
+ transcriptPath: String(stdinObj.transcript_path || ""), isOrchPane, isPrintRun });
451
471
  const orchSid = readOrchSession(project);
452
472
  const holdMs = Number(process.env.TRANTOR_ORCH_HOLD_MS || 30 * 60 * 1000);
453
473
  const peek = loadPendingHandoff(basename(projectDir), { claim: false });
@@ -1,6 +1,7 @@
1
1
  import { z } from 'zod';
2
2
  import { reject } from '../../lib/dispatcher/admission.mjs';
3
3
  import { requireRole } from '../../lib/dispatcher/operations.mjs';
4
+ import { draftPolicyFromStore } from '../../lib/dispatcher/policy-draft.mjs';
4
5
 
5
6
  export function dispatcherEndpoint(method, path, query) {
6
7
  return path === '/dispatch' || path.startsWith('/dispatch/') || path.startsWith('/dispatcher/')
@@ -71,9 +72,15 @@ export async function routeDispatcherOperations({ req, res, P, q, auth, ctx }) {
71
72
  if (req.method === 'POST' && P === '/dispatcher/bridge-grants') {
72
73
  return ctx.json(res, 200, await service.registerBridgeGrant(orgId, await ctx.body(req), actor));
73
74
  }
75
+ if (req.method === 'POST' && P === '/dispatcher/shadow-grants') {
76
+ return ctx.json(res, 200, await service.registerShadowGrant(orgId, await ctx.body(req), actor));
77
+ }
74
78
  if (req.method === 'POST' && P === '/dispatcher/policy/activate') {
75
79
  return ctx.json(res, 200, await service.activatePolicy(orgId, await ctx.body(req), actor));
76
80
  }
81
+ if (req.method === 'POST' && P === '/dispatcher/policy/draft') {
82
+ return ctx.json(res, 200, await draftPolicyFromStore({ service, orgId, input: await ctx.body(req), actor, requireRole }));
83
+ }
77
84
  if (req.method === 'POST' && P === '/dispatcher/control') {
78
85
  return ctx.json(res, 200, await service.executor.kill(orgId, await ctx.body(req), actor));
79
86
  }
package/hub.mjs CHANGED
@@ -143,6 +143,7 @@ const context = {
143
143
  };
144
144
  if (store.dispatcher && AUTH_MODE !== 'off') {
145
145
  setInterval(createDispatcherTick({ dispatcher: store.dispatcher }), 1000).unref();
146
+ setInterval(() => store.dispatcher.tickShadow(), 1000).unref();
146
147
  }
147
148
  const sessionChat = createSessionRuntime({
148
149
  state: store.state, markDirty: store.markDirty,
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.157",
3
+ "version": "0.18.159",
4
4
  "description": "Trantor — the hub-world for AI agent crews: live message bus, presence, project Kanban/flow board + crew orchestration for independent AI coding agents (Claude, Codex, Gemini, Kimi, DeepSeek). This manifest makes Kimi Code CLI a first-class ORCHESTRATOR, mirroring .claude-plugin/plugin.json. Hooks are the CANONICAL hooks/** executed through the kimi dialect bridge (kimi/bridge.mjs) — docs/KIMI-BRIDGE-CONTRACT.md.",
5
5
  "interface": {
6
6
  "displayName": "Trantor",
@@ -189,13 +189,13 @@ function seatEvidence({ rows, balances, orgId, nowMs, policy }) {
189
189
  if (row?.kind !== 'agent') continue;
190
190
  const id = text(row?.session, 200);
191
191
  const machine = text(row?.machine, 60);
192
- const harness = text(row?.llm, 200);
192
+ const agent = text(row?.llm, 200);
193
193
  const observedAtMs = timestamp(row?.lastSeen);
194
- if (!id || !machine || !harness || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
194
+ if (!id || !machine || !agent || !fresh(observedAtMs, nowMs, policy.machineTtlMs)) continue;
195
195
  const lastTurnMs = timestamp(row?.lastTurn?.ts);
196
196
  const binding = resolveSeatAccount({ identity: row.accountIdentity, accounts });
197
197
  const record = { id, machine, accountId: binding.accountId, accountBindingReason: binding.reason,
198
- harness, model: text(row.model, 512) || null,
198
+ harness: 'crew', agent, model: text(row.model, 512) || null,
199
199
  busy: row.online === true && /^(working|busy)$/i.test(text(row.status, 100)),
200
200
  lastBeatMs: observedAtMs, lastTurnMs };
201
201
  if (row.project) record.project = text(row.project, 200);
@@ -242,16 +242,17 @@ function modelEvidence({ rows, seats, nowMs, policy, catalog }) {
242
242
  }
243
243
  }
244
244
  for (const seat of Array.isArray(seats) ? seats : []) {
245
+ if (seat?.kind !== 'agent') continue;
245
246
  const model = text(seat?.lastTurn?.model, 512);
246
247
  const seatId = text(seat?.session, 200);
247
- const harness = text(seat?.llm, 200);
248
+ const agent = text(seat?.llm, 200);
248
249
  const observedAtMs = timestamp(seat?.lastTurn?.ts);
249
- if (!model || !seatId || !harness || !fresh(observedAtMs, nowMs, policy.invocationTtlMs)) continue;
250
- const provider = model.includes('/') ? text(model.split('/')[0], 200) : harness;
250
+ if (!model || !seatId || !agent || !fresh(observedAtMs, nowMs, policy.invocationTtlMs)) continue;
251
+ const provider = model.includes('/') ? text(model.split('/')[0], 200) : agent;
251
252
  const key = `${provider}\0${model}`;
252
253
  const envelope = models.get(key) || modelEnvelope({ provider, model, observedAtMs,
253
254
  expiresAtMs: observedAtMs + policy.invocationTtlMs, nowMs, catalog });
254
- envelope.record.invocation = observation({ value: { model, seatId, harness }, observedAtMs,
255
+ envelope.record.invocation = observation({ value: { model, seatId, harness: 'crew' }, observedAtMs,
255
256
  receivedAtMs: nowMs, source: 'presence:last-turn', status: 'ok', sourceRevision: observedAtMs });
256
257
  envelope.observedAtMs = Math.max(envelope.observedAtMs, observedAtMs);
257
258
  envelope.expiresAtMs = Math.max(envelope.expiresAtMs, observedAtMs + policy.invocationTtlMs);
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { projectBoardCards } from './board-bridge.mjs';
3
- import { createRolloutOperations, RolloutApprovalSchema, validateRolloutApproval, rolloutPolicyHash } from './rollout.mjs';
3
+ import { createRolloutOperations, createShadowScheduler, RolloutApprovalSchema, validateRolloutApproval, rolloutPolicyHash } from './rollout.mjs';
4
4
  import { AccountSchema, MachineSchema, SeatSchema, ModelEvidenceSchema, FitnessCellSchema,
5
5
  ProjectScheduleSchema, WorkCardSchema, PolicySchema } from './schemas.mjs';
6
6
  import { createAdmission, createFinancialOperations, AdmissionAuthoritySchema, WindowLedgerSchema,
@@ -489,6 +489,7 @@ export function createDispatcherOperations({ durableStore, orgId: configuredOrg,
489
489
  },
490
490
  };
491
491
  Object.assign(service, createRolloutOperations({ service, requireRole, clock, advisorWorld }));
492
+ service.tickShadow = createShadowScheduler({ service, orgId: configuredOrg, clock });
492
493
  service.executor = { ...executor, kill(orgId, input, actor) {
493
494
  const control = KillSchema.parse(input);
494
495
  return control.enabled ? executor.kill(orgId, control, actor) : service.clearControl(orgId, control, actor);
@@ -84,11 +84,15 @@ export function deriveCandidates(snapshot, policy) {
84
84
  return [...candidates.values()].sort((a, b) => compare(a.id, b.id));
85
85
  }
86
86
 
87
- function priorFor(candidate, card, policy) {
87
+ function priorFor(candidate, card, policy, snapshot) {
88
+ if (candidate.model === null && !snapshot.seats.some(seat => seat.id === candidate.seatId
89
+ && seat.harness === candidate.harness && seat.model === null)) return null;
88
90
  const matching = policy.qualityPriors.filter(prior => prior.provider === candidate.provider
89
91
  && prior.model === candidate.model && prior.effort === candidate.effort
92
+ && (prior.harness === undefined || prior.harness === candidate.harness)
90
93
  && prior.difficulty === card.difficulty && ((kinds.has(card.kind) && prior.kind === card.kind) || prior.kind === '*'));
91
- return matching.sort((a, b) => Number(b.kind === card.kind) - Number(a.kind === card.kind)
94
+ return matching.sort((a, b) => Number(b.harness === candidate.harness) - Number(a.harness === candidate.harness)
95
+ || Number(b.kind === card.kind) - Number(a.kind === card.kind)
92
96
  || b.sourceDateMs - a.sourceDateMs || compare(canonicalJson(a), canonicalJson(b)))[0] ?? null;
93
97
  }
94
98
 
@@ -120,11 +124,13 @@ export function fitnessEstimate(candidate, card, snapshot, policy) {
120
124
  expectedMs: ceilRatio(BigInt(cell.medianDurationMs) * denominator, numerator) };
121
125
  }
122
126
  }
123
- const prior = priorFor(candidate, card, policy);
124
- if (!prior || prior.successPseudoCount === 0) return null;
125
- const numerator = BigInt(prior.successPseudoCount);
126
- const denominator = numerator + BigInt(prior.failurePseudoCount);
127
- return { poolLevel: 'prior', sampleCount: 0, exactSamples: exact?.judged ?? 0,
127
+ const prior = priorFor(candidate, card, policy, snapshot);
128
+ if (!prior) return null;
129
+ const measured = prior.judged !== undefined && prior.passes !== undefined;
130
+ if (!measured && prior.successPseudoCount === 0) return null;
131
+ const numerator = measured ? BigInt(prior.passes) + 1n : BigInt(prior.successPseudoCount);
132
+ const denominator = measured ? BigInt(prior.judged) + 2n : numerator + BigInt(prior.failurePseudoCount);
133
+ return { poolLevel: 'prior', sampleCount: measured ? prior.judged : 0, exactSamples: exact?.judged ?? 0,
128
134
  qualityProbabilityPpm: safeNumber(numerator * PPM / denominator),
129
135
  time: { numerator: BigInt(prior.durationMs) * denominator, denominator: numerator },
130
136
  expectedMs: ceilRatio(BigInt(prior.durationMs) * denominator, numerator) };
@@ -222,7 +228,7 @@ function rankCandidates(entries, policy) {
222
228
  }
223
229
 
224
230
  export function estimateCharges(candidate, card, snapshot, policy) {
225
- const prior = priorFor(candidate, card, policy);
231
+ const prior = priorFor(candidate, card, policy, snapshot);
226
232
  const account = snapshot.accounts.find(entry => entry.id === candidate.accountId);
227
233
  if (!prior || prior.rateAsOfMs > snapshot.asOfMs || !account?.windows.length) return null;
228
234
  const charges = [];
@@ -296,7 +302,7 @@ function assess(card, candidates, snapshot, policy, state) {
296
302
  excluded.push({ candidateId: candidate.id, reasons: [...new Set(reasons)].sort(compare) });
297
303
  continue;
298
304
  }
299
- const prior = priorFor(candidate, card, policy);
305
+ const prior = priorFor(candidate, card, policy, snapshot);
300
306
  const floor = policy.capabilityFloors.filter(entry => entry.difficulty === card.difficulty
301
307
  && [card.kind, 'code', '*'].includes(entry.kind));
302
308
  if (!floor.length || !prior || floor.some(entry => prior.capabilityScorePpm < entry.minimumScorePpm)) reasons.push('capability_floor');
@@ -0,0 +1,158 @@
1
+ import { z } from 'zod';
2
+ import { createPolicy, verifyPolicy, LEGACY_RATE_INPUTS } from './policy.mjs';
3
+ import { verifySnapshot, canonicalHash, canonicalJson } from './snapshot.mjs';
4
+ import { classifyAttemptVerification } from './acceptance.mjs';
5
+
6
+ const text = z.string().min(1).max(8192);
7
+ const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
8
+ const SampleSchema = z.object({ id: text, project: text, ts: integer,
9
+ duration_ms: integer, tokens: integer.nullable(),
10
+ attempt: z.object({ id: text, provider: text, harness: text, model: text.nullable(),
11
+ difficulty: z.enum(['easy', 'medium', 'hard']), infraFailure: z.boolean() }).passthrough(),
12
+ usage: z.object({ priceVersion: text.nullable().optional() }).passthrough().optional(),
13
+ executionAttemptId: text.nullable().optional(),
14
+ }).passthrough();
15
+ export const PolicyDraftRequestSchema = z.strictObject({ project: text, version: text.optional() });
16
+ const key = row => JSON.stringify([row.provider, row.harness, row.model, row.difficulty]);
17
+ const median = values => {
18
+ const sorted = [...values].sort((a, b) => a - b);
19
+ const middle = Math.floor(sorted.length / 2);
20
+ return sorted.length % 2 ? sorted[middle] : Math.ceil(sorted[middle - 1] / 2 + sorted[middle] / 2);
21
+ };
22
+
23
+ function supportsModel(seat, model, snapshot, policy) {
24
+ if (seat.model === model) return true;
25
+ return model !== null && snapshot.models.some(entry => entry.invocation.status === 'ok'
26
+ && entry.invocation.value?.seatId === seat.id && entry.invocation.value?.model === model
27
+ && entry.invocation.observedAtMs !== null
28
+ && entry.invocation.observedAtMs <= snapshot.asOfMs
29
+ && snapshot.asOfMs - entry.invocation.observedAtMs <= policy.invocationTtlMs);
30
+ }
31
+
32
+ function collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptances) {
33
+ const groups = new Map();
34
+ const seen = new Set();
35
+ const excluded = { invalid: 0, duplicate: 0, future: 0, unknownModel: 0, infrastructure: 0 };
36
+ for (const input of turns) {
37
+ const parsed = SampleSchema.safeParse(input);
38
+ if (!parsed.success) { excluded.invalid++; continue; }
39
+ const row = parsed.data;
40
+ if (row.project !== project) continue;
41
+ if (seen.has(row.id)) { excluded.duplicate++; continue; }
42
+ seen.add(row.id);
43
+ if (row.ts > nowMs) { excluded.future++; continue; }
44
+ if (row.attempt.model === 'unknown') { excluded.unknownModel++; continue; }
45
+ if (row.attempt.infraFailure) { excluded.infrastructure++; continue; }
46
+ const seat = bound.find(entry => entry.id === row.attempt.seat
47
+ && (entry.harness === row.attempt.harness || entry.harness === 'crew' && entry.agent === row.attempt.harness)
48
+ && supportsModel(entry, row.attempt.model, snapshot, policy));
49
+ const account = seat && snapshot.accounts.find(entry => entry.id === seat.accountId);
50
+ const identity = { provider: account?.provider ?? row.attempt.provider, harness: seat?.harness ?? row.attempt.harness,
51
+ model: row.attempt.model, difficulty: row.attempt.difficulty };
52
+ const groupKey = key(identity);
53
+ if (!groups.has(groupKey)) groups.set(groupKey, { ...identity, rows: [], tokens: [], durations: [], judged: 0, passes: 0, acceptances: new Set() });
54
+ const group = groups.get(groupKey);
55
+ group.rows.push(row);
56
+ if (row.tokens !== null) group.tokens.push(row.tokens);
57
+ if (row.duration_ms > 0) group.durations.push(row.duration_ms);
58
+ const acceptance = acceptances.find(record => record.attemptId === (row.executionAttemptId ?? row.attempt.id)
59
+ && record.atMs <= nowMs);
60
+ const verification = classifyAttemptVerification({ ...row.attempt, acceptance, executionAttemptId: row.executionAttemptId });
61
+ if (['accepted', 'failed'].includes(verification.status) && !group.acceptances.has(verification.acceptance.id)) {
62
+ group.acceptances.add(verification.acceptance.id);
63
+ group.judged++;
64
+ if (verification.status === 'accepted') group.passes++;
65
+ }
66
+ }
67
+ return { groups, excluded };
68
+ }
69
+
70
+ function ratesFor(group, policy) {
71
+ const prior = policy.qualityPriors.filter(row => row.provider === group.provider && row.model === group.model
72
+ && (row.harness === undefined || row.harness === group.harness) && row.difficulty === group.difficulty)
73
+ .sort((a, b) => b.rateAsOfMs - a.rateAsOfMs || canonicalJson(a).localeCompare(canonicalJson(b)))[0];
74
+ if (prior) return { rates: prior.rates, priceVersion: prior.priceVersion,
75
+ rateSource: `policy:${policy.version}:${prior.rateSource}`, rateAsOfMs: prior.rateAsOfMs };
76
+ const seed = LEGACY_RATE_INPUTS.find(row => row.model === group.model);
77
+ return seed ? { rates: seed.rates, priceVersion: null, rateSource: seed.rateSource, rateAsOfMs: seed.rateAsOfMs }
78
+ : { rates: { usdMicrosPerMTok: null, quotaMillionthsPerMTok: null }, priceVersion: null,
79
+ rateSource: 'unobserved: no active policy rate or legacy model rate', rateAsOfMs: 0 };
80
+ }
81
+
82
+ export function draftPolicy({ policy: inputPolicy, snapshot: inputSnapshot, turns, acceptances = [], project, version, createdBy, nowMs }) {
83
+ const policy = verifyPolicy(inputPolicy);
84
+ const snapshot = verifySnapshot(inputSnapshot);
85
+ if (snapshot.policyVersion !== policy.version) throw new Error('policy_stale');
86
+ const bound = snapshot.seats.filter(seat => (seat.project === project || seat.project === undefined)
87
+ && snapshot.accounts.some(account => account.id === seat.accountId && account.status === 'verified')
88
+ && snapshot.machines.some(machine => machine.id === seat.machine));
89
+ const roster = bound.map(seat => {
90
+ const entry = { seatId: seat.id, harness: seat.harness, enabled: true, host: seat.machine, model: seat.model,
91
+ adapterVersions: snapshot.machines.find(machine => machine.id === seat.machine).adapterVersions };
92
+ if (seat.agent !== undefined) entry.agent = seat.agent;
93
+ return entry;
94
+ });
95
+ const { groups, excluded } = collectSamples(turns, project, nowMs, bound, snapshot, policy, acceptances);
96
+ const qualityPriors = [];
97
+ const samples = [];
98
+ for (const group of [...groups.values()].sort((a, b) => key(a).localeCompare(key(b)))) {
99
+ const sampleCount = group.rows.length;
100
+ const priceVersions = [...new Set(group.rows.map(row => row.usage?.priceVersion ?? null))]
101
+ .sort((a, b) => String(a).localeCompare(String(b)));
102
+ const sample = { provider: group.provider, harness: group.harness, model: group.model, difficulty: group.difficulty,
103
+ sampleCount, tokenSampleCount: group.tokens.length, durationSampleCount: group.durations.length,
104
+ judged: group.judged, passes: group.passes, priceVersions,
105
+ recordedProviders: [...new Set(group.rows.map(row => row.attempt.provider))].sort(),
106
+ recordedHarnesses: [...new Set(group.rows.map(row => row.attempt.harness))].sort(),
107
+ medianTokens: group.tokens.length ? median(group.tokens) : null,
108
+ medianDurationMs: group.durations.length ? median(group.durations) : null };
109
+ const matchingSeats = bound.filter(seat => seat.harness === group.harness && supportsModel(seat, group.model, snapshot, policy)
110
+ && snapshot.accounts.find(account => account.id === seat.accountId)?.provider === group.provider);
111
+ const efforts = [...new Set(snapshot.models.filter(model => model.provider === group.provider && model.model === group.model
112
+ && matchingSeats.some(seat => model.accountId === null || model.accountId === seat.accountId))
113
+ .flatMap(model => model.efforts))].sort();
114
+ const reason = !group.tokens.length || !group.durations.length ? 'no_measurements'
115
+ : !matchingSeats.length ? 'no_bound_seat' : !efforts.length ? 'no_effort_evidence' : null;
116
+ samples.push({ ...sample, reason });
117
+ if (reason) continue;
118
+ const qualityPpm = Number((BigInt(group.passes) + 1n) * 1_000_000n / (BigInt(group.judged) + 2n));
119
+ const rates = ratesFor(group, policy);
120
+ for (const effort of efforts) qualityPriors.push({ provider: group.provider, harness: group.harness,
121
+ model: group.model, effort, kind: '*', difficulty: group.difficulty,
122
+ durationMs: sample.medianDurationMs, tokenEstimate: sample.medianTokens,
123
+ capabilityScorePpm: qualityPpm, successPseudoCount: group.passes, failurePseudoCount: group.judged - group.passes,
124
+ sampleCount, tokenSampleCount: group.tokens.length, durationSampleCount: group.durations.length,
125
+ judged: group.judged, passes: group.passes, priceVersions,
126
+ source: `turn-history:${project}:${canonicalHash(group.rows.map(row => row.id).sort())}; pooled across effort and kind`,
127
+ sourceDateMs: group.rows.reduce((latest, row) => Math.max(latest, row.ts), 0), ...rates });
128
+ }
129
+ const { hash: _hash, ...previous } = policy;
130
+ const draft = createPolicy({ ...previous, parentVersion: policy.version,
131
+ version: version || `${policy.version}-draft-${nowMs}`, createdAtMs: nowMs, createdBy,
132
+ roster: [...policy.roster.filter(row => !snapshot.seats.some(seat => seat.id === row.seatId
133
+ && (seat.project === project || seat.project === undefined))), ...roster],
134
+ qualityPriors: [...policy.qualityPriors.filter(prior => !bound.some(seat => (prior.harness === undefined || prior.harness === seat.harness)
135
+ && snapshot.accounts.find(account => account.id === seat.accountId)?.provider === prior.provider)), ...qualityPriors] });
136
+ if (draft.version === policy.version) throw new Error('draft_version_must_change');
137
+ return { policy: draft, summary: { project, snapshotId: snapshot.id, parentVersion: policy.version,
138
+ rosterEntries: roster.length, priorsDerived: qualityPriors.length, rowsRead: turns.length,
139
+ verifiedAcceptancesRead: acceptances.length, excluded, samples,
140
+ seatsWithoutSamples: roster.filter(seat => !qualityPriors.some(prior => prior.harness === seat.harness && prior.model === seat.model))
141
+ .map(seat => seat.seatId),
142
+ priorsWithUnknownRates: qualityPriors.filter(prior => Object.values(prior.rates).some(rate => rate === null)).length } };
143
+ }
144
+
145
+ export async function draftPolicyFromStore({ service, orgId, input, actor, requireRole, clock = Date.now }) {
146
+ const request = PolicyDraftRequestSchema.parse(input);
147
+ return service.store.locked(orgId, async client => {
148
+ await requireRole(client, orgId, actor, '*', ['owner'], true);
149
+ const authority = await service.readAdvice(client, { orgId, request: { project: request.project } });
150
+ const turns = (await client.query("SELECT row FROM turns WHERE org_id=$1 AND row->>'project'=$2 ORDER BY ts,id",
151
+ [orgId, request.project])).rows.map(row => row.row);
152
+ const acceptances = (await client.query(`SELECT a.row FROM dispatcher_acceptances a
153
+ JOIN dispatcher_verification_jobs j ON j.org_id=a.org_id AND j.id=a.job_id AND j.acceptance_id=a.id
154
+ WHERE a.org_id=$1 AND j.project=$2 AND j.state IN ('passed','failed') ORDER BY (a.row->>'atMs')::bigint DESC,a.id`,
155
+ [orgId, request.project])).rows.map(row => row.row);
156
+ return draftPolicy({ ...authority, ...request, turns, acceptances, createdBy: actor.pubkey, nowMs: clock() });
157
+ });
158
+ }
@@ -11,6 +11,9 @@ import { executionRows, fenceExecution, KillSchema } from './executor.mjs';
11
11
  const text = z.string().min(1).max(8192);
12
12
  const integer = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
13
13
  const DAY = 86400_000;
14
+ export const SHADOW_INTERVAL_MS = 30 * 60_000;
15
+ export const ShadowGrantSchema = z.strictObject({ grantId: text, projects: z.array(text).min(1).max(1000),
16
+ expiresAtMs: integer.nullable().optional(), revoked: z.boolean() });
14
17
  export const FIRST_WAVE_DRILLS = Array.from({ length: 25 }, (_, i) => `D${i + 1}`).filter(id => id !== 'D12');
15
18
  export const RolloutApprovalSchema = z.strictObject({ cohortId: text, testedSha: z.string().regex(/^[a-f0-9]{40}$/),
16
19
  baselineId: text, checks: z.strictObject({ crewMatrix: text, healthyCanaries: text, accountMappings: text, spendReconciliation: text }) });
@@ -22,16 +25,26 @@ const key = card => `${card.project}:${card.card}`;
22
25
  const sanitize = value => JSON.parse(redactKeys(JSON.stringify(value, (name, item) =>
23
26
  /secret|password|api.?key|(?:access|refresh).?token|authorization|^token$/i.test(name) ? '<redacted>' : item)));
24
27
 
25
- export function captureShadow({ snapshot, policy, cards, packages, world }) {
28
+ export function captureShadow({ snapshot, policy, cards, packages, world, project = cards[0]?.project }) {
26
29
  if (cards.some(card => policy.modeByProject[card.project] !== 'shadow')) reject('shadow_required');
27
30
  if (packages.length !== cards.length) reject('card_stale');
28
31
  const decision = plan({ snapshot, policy, cards });
29
32
  const legacy = advise({ packages }, world);
30
33
  const bindings = Object.fromEntries(Object.entries(world.roster).map(([executor, entry]) => {
31
- const seats = snapshot.seats.filter(seat => seat.harness === 'crew' && seat.id === entry.session);
32
- return [executor, seats.length === 1 ? { seatId: seats[0].id, harness: seats[0].harness, machine: seats[0].machine } : null];
34
+ const scoped = snapshot.seats.filter(seat => seat.harness === 'crew'
35
+ && (seat.project === undefined || seat.project === project));
36
+ const exact = scoped.filter(seat => seat.id === entry.session || seat.id === `${entry.session}:${project}`);
37
+ const matching = scoped.filter(seat => policy.roster.some(row => row.enabled
38
+ && row.seatId === seat.id && row.host === seat.machine && row.harness === seat.harness)
39
+ && [entry.cli, executor].includes(seat.agent)
40
+ && snapshot.accounts.some(account => account.id === seat.accountId && account.status === 'verified'
41
+ && account.provider === entry.provider));
42
+ const seats = matching.length ? matching : exact;
43
+ const identities = seats.map(seat => ({ seatId: seat.id, harness: seat.harness, machine: seat.machine }));
44
+ return [executor, identities.length === 1 ? { ...identities[0], matchBy: 'seat' }
45
+ : identities.length > 1 ? { matchBy: 'cli', agent: executor, seats: identities } : null];
33
46
  }));
34
- const mapping = { version: 1, bindings };
47
+ const mapping = { version: 2, bindings };
35
48
  const policyFingerprint = rolloutPolicyHash(policy);
36
49
  const companion = sanitize({ snapshotId: snapshot.id, policyVersion: policy.version,
37
50
  input: { packages }, world, output: legacy, mapping: { ...mapping, hash: canonicalHash(mapping) } });
@@ -40,7 +53,7 @@ export function captureShadow({ snapshot, policy, cards, packages, world }) {
40
53
  const old = legacy.routing[index];
41
54
  const assignment = decision.assignments.find(a => key(a) === key(card));
42
55
  const candidate = assignment?.candidate || null;
43
- const binding = ['orchestrator', 'scrooge'].includes(old.executor) ? null : bindings[old.executor];
56
+ const binding = ['orchestrator', 'scrooge', 'sub-agent'].includes(old.executor) ? null : bindings[old.executor];
44
57
  const comparable = Boolean(binding);
45
58
  const costByAccount = new Map();
46
59
  for (const charge of assignment?.estimates || []) if (charge.unit === 'usdMicros') {
@@ -49,7 +62,11 @@ export function captureShadow({ snapshot, policy, cards, packages, world }) {
49
62
  const plannerUsd = costByAccount.size ? [...costByAccount.values()].reduce((a, b) => a + b, 0) / 1_000_000 : null;
50
63
  const differences = [];
51
64
  if (comparable) {
52
- for (const field of ['seatId', 'harness', 'machine']) if (binding[field] !== candidate?.[field]) differences.push(field);
65
+ if (binding.matchBy === 'cli') {
66
+ if (!binding.seats.some(seat => ['seatId', 'harness', 'machine'].every(field => seat[field] === candidate?.[field]))) differences.push('cli');
67
+ } else {
68
+ for (const field of ['seatId', 'harness', 'machine']) if (binding[field] !== candidate?.[field]) differences.push(field);
69
+ }
53
70
  if (old.model != null && old.model !== candidate?.model) differences.push('model');
54
71
  const effort = z.string().safeParse(old.effort?.params?.reasoning_effort ?? old.effort);
55
72
  if (effort.success && effort.data !== candidate?.effort) differences.push('effort');
@@ -148,21 +165,73 @@ export function createRolloutOperations({ service, requireRole, clock, advisorWo
148
165
  for (const { id } of live) await fenceExecution(client, orgId, await executionRows(client, orgId, id), reason, clock());
149
166
  return live.length;
150
167
  };
168
+ const capture = async (client, orgId, request, actor, provenance = {}) => {
169
+ const authority = await service.readAdvice(client, { orgId, request });
170
+ if (authority.policy.modeByProject[request.project] !== 'shadow') reject('shadow_required');
171
+ const cards = authority.snapshot.readyQueue.filter(c => c.project === request.project);
172
+ const tasks = (await client.query('SELECT id,title FROM tasks WHERE org_id=$1 AND project=$2', [orgId, request.project])).rows;
173
+ const packages = cards.map(card => {
174
+ const task = tasks.find(t => Number(t.id) === card.card);
175
+ if (!task) reject('card_stale');
176
+ return { title: task.title, difficulty: card.difficulty, kind: card.kind };
177
+ });
178
+ const captured = captureShadow({ ...authority, cards, packages, world: await advisorWorld(request.project), project: request.project });
179
+ return audit(client, orgId, 'rollout-shadow', { project: request.project, ...captured, ...provenance }, actor);
180
+ };
151
181
  return {
182
+ async registerShadowGrant(orgId, input, actor) {
183
+ const grant = ShadowGrantSchema.parse(input);
184
+ return store.locked(orgId, async client => {
185
+ await owner(client, orgId, actor);
186
+ await client.query(`INSERT INTO dispatcher_shadow_grants VALUES($1,$2,$3,$4)
187
+ ON CONFLICT(org_id,grant_id) DO UPDATE SET approved_by=EXCLUDED.approved_by,row=EXCLUDED.row`,
188
+ [orgId, grant.grantId, actor.pubkey, grant]);
189
+ await audit(client, orgId, 'shadow-grant-registered', { ...grant, approvedBy: actor.pubkey }, actor);
190
+ return grant;
191
+ });
192
+ },
193
+ async shadowProjects(orgId) {
194
+ const policy = (await store.pool.query(`SELECT p.row FROM dispatcher_authority_state a
195
+ JOIN dispatcher_policies p ON p.org_id=a.org_id AND p.version=a.policy_version WHERE a.org_id=$1`, [orgId])).rows[0]?.row;
196
+ return Object.entries(policy?.modeByProject || {}).filter(([, mode]) => mode === 'shadow')
197
+ .map(([project]) => ({ project, policyVersion: policy.version }));
198
+ },
199
+ async scheduledShadowTick(orgId, project) {
200
+ return store.locked(orgId, async client => {
201
+ const policy = (await client.query(`SELECT p.row FROM dispatcher_authority_state a
202
+ JOIN dispatcher_policies p ON p.org_id=a.org_id AND p.version=a.policy_version WHERE a.org_id=$1`, [orgId])).rows[0]?.row;
203
+ if (policy?.modeByProject[project] !== 'shadow') return { skipped: 'shadow_required' };
204
+ const grants = (await client.query('SELECT * FROM dispatcher_shadow_grants WHERE org_id=$1 ORDER BY grant_id', [orgId])).rows;
205
+ let reason = grants.length ? 'shadow_grant_wrong_project' : 'shadow_grant_missing';
206
+ let selected;
207
+ for (const grant of grants.filter(g => g.row.projects.includes(project))) {
208
+ if (grant.row.revoked) { reason = 'shadow_grant_revoked'; continue; }
209
+ if (grant.row.expiresAtMs != null && grant.row.expiresAtMs <= clock()) { reason = 'shadow_grant_expired'; continue; }
210
+ try { await owner(client, orgId, { pubkey: grant.approved_by }); }
211
+ catch (error) {
212
+ if (error.code !== 'permission_denied') throw error;
213
+ reason = 'shadow_grant_owner_revoked';
214
+ continue;
215
+ }
216
+ selected = grant;
217
+ break;
218
+ }
219
+ if (!selected) return { skipped: reason };
220
+ const last = (await client.query(`SELECT at_ms FROM dispatcher_audit WHERE org_id=$1
221
+ AND row->>'action'='rollout-shadow' AND row->>'project'=$2 ORDER BY at_ms DESC LIMIT 1`, [orgId, project])).rows[0];
222
+ const intervalMs = policy.shadowIntervalMs ?? SHADOW_INTERVAL_MS;
223
+ const nextAtMs = last ? Number(last.at_ms) + intervalMs : clock();
224
+ if (nextAtMs > clock()) return { nextAtMs };
225
+ const tick = await capture(client, orgId, { project }, { pubkey: selected.approved_by },
226
+ { approvedBy: selected.approved_by, grantId: selected.grant_id });
227
+ return { tickId: tick.id, nextAtMs: tick.atMs + intervalMs };
228
+ });
229
+ },
152
230
  async shadowTick(orgId, input, actor) {
153
231
  const request = z.strictObject({ project: text, snapshotId: text.optional() }).parse(input);
154
232
  return store.locked(orgId, async client => {
155
233
  await owner(client, orgId, actor);
156
- const authority = await service.readAdvice(client, { orgId, request });
157
- const cards = authority.snapshot.readyQueue.filter(c => c.project === request.project);
158
- const tasks = (await client.query('SELECT id,title FROM tasks WHERE org_id=$1 AND project=$2', [orgId, request.project])).rows;
159
- const packages = cards.map(card => {
160
- const task = tasks.find(t => Number(t.id) === card.card);
161
- if (!task) reject('card_stale');
162
- return { title: task.title, difficulty: card.difficulty, kind: card.kind };
163
- });
164
- const captured = captureShadow({ ...authority, cards, packages, world: await advisorWorld(request.project) });
165
- return audit(client, orgId, 'rollout-shadow', { project: request.project, ...captured }, actor);
234
+ return capture(client, orgId, request, actor);
166
235
  });
167
236
  },
168
237
  async rolloutReport(orgId, input, actor) {
@@ -355,3 +424,48 @@ async function storedCohort(client, orgId, project, period) {
355
424
  return acceptedCohort(rows.map(row => ({ attempt: row.attempt, policy: row.policy,
356
425
  card: row.snapshot.readyQueue.find(c => key(c) === key(row.attempt)) })), period);
357
426
  }
427
+
428
+ export function createShadowScheduler({ service, orgId, clock = Date.now, log = console.error }) {
429
+ const states = new Map();
430
+ let running = false;
431
+ let discoveryRetryAtMs = 0;
432
+ let discoveryFailures = 0;
433
+ let discoveryReason = null;
434
+ const backoff = failures => Math.min(30_000, 1000 * 2 ** Math.min(failures - 1, 5));
435
+ return async () => {
436
+ if (running || clock() < discoveryRetryAtMs) return;
437
+ running = true;
438
+ try {
439
+ const projects = await service.shadowProjects(orgId);
440
+ discoveryFailures = 0;
441
+ discoveryReason = null;
442
+ const active = new Set(projects.map(entry => entry.project));
443
+ for (const project of states.keys()) if (!active.has(project)) states.delete(project);
444
+ for (const { project, policyVersion } of projects) {
445
+ let state = states.get(project);
446
+ if (!state || state.policyVersion !== policyVersion) {
447
+ state = { policyVersion, nextAtMs: 0, failures: 0, reason: null };
448
+ states.set(project, state);
449
+ }
450
+ if (clock() < state.nextAtMs) continue;
451
+ try {
452
+ const result = await service.scheduledShadowTick(orgId, project);
453
+ if (result.skipped && state.reason !== result.skipped) log(`[trantor] shadow ${project}: ${result.skipped}`);
454
+ state.reason = result.skipped || null;
455
+ state.failures = 0;
456
+ state.nextAtMs = result.nextAtMs ?? clock() + 30_000;
457
+ } catch (error) {
458
+ const reason = error.code || 'shadow_tick_failed';
459
+ if (state.reason !== reason) log(`[trantor] shadow ${project}: ${reason}`);
460
+ state.reason = reason;
461
+ state.nextAtMs = clock() + backoff(++state.failures);
462
+ }
463
+ }
464
+ } catch (error) {
465
+ const reason = error.code || 'shadow_schedule_failed';
466
+ if (discoveryReason !== reason) log(`[trantor] shadow schedule: ${reason}`);
467
+ discoveryReason = reason;
468
+ discoveryRetryAtMs = clock() + backoff(++discoveryFailures);
469
+ } finally { running = false; }
470
+ };
471
+ }
@@ -104,6 +104,7 @@ export const MachineSchema = object({
104
104
  });
105
105
  export const SeatSchema = object({
106
106
  project: text.optional(), accountBindingReason: nullable(text).optional(),
107
+ agent: text.optional(),
107
108
  id: text, machine: text, accountId: nullable(text), harness: text, model: nullable(text),
108
109
  busy: z.boolean(), lastBeatMs: nullable(integer), lastTurnMs: nullable(integer),
109
110
  });
@@ -124,18 +125,24 @@ export const AccountOverrideSchema = object({
124
125
  expiresAtMs: integer, approvalId: text, reason: text,
125
126
  });
126
127
  export const QualityPriorSchema = object({
127
- provider: text, model: text, effort: text, kind: text, difficulty: text,
128
+ provider: text, model: nullable(text), effort: text, kind: text, difficulty: text,
129
+ harness: text.optional(), sampleCount: integer.optional(), tokenSampleCount: integer.optional(),
130
+ durationSampleCount: integer.optional(), judged: integer.optional(), passes: integer.optional(),
131
+ priceVersions: list(nullable(text)).optional(),
128
132
  durationMs: positive, tokenEstimate: integer, capabilityScorePpm: ppm,
129
133
  successPseudoCount: integer, failurePseudoCount: integer,
130
134
  priceVersion: nullable(text), source: text, sourceDateMs: integer,
131
135
  rates: object({ usdMicrosPerMTok: nullable(integer), quotaMillionthsPerMTok: nullable(integer) }),
132
136
  rateSource: text, rateAsOfMs: integer,
133
- });
137
+ }).refine(prior => (prior.judged === undefined) === (prior.passes === undefined)
138
+ && (prior.judged === undefined || prior.passes <= prior.judged), { message: 'Measured quality requires passes <= judged' });
134
139
  export const PolicySchema = object({
135
140
  schemaVersion: version, version: text, parentVersion: nullable(text), hash: text,
136
141
  createdAtMs: integer, createdBy: text, plannerVersion: text,
137
142
  modeByProject: record(z.enum(['off', 'shadow', 'admit'])),
138
- roster: list(object({ seatId: text, harness: text, enabled: z.boolean(), host: text })),
143
+ shadowIntervalMs: positive.optional(),
144
+ roster: list(object({ seatId: text, harness: text, enabled: z.boolean(), host: text,
145
+ model: nullable(text).optional(), adapterVersions: strings.optional(), agent: text.optional() })),
139
146
  placementByKind: record(text), discoveryTtlMs: positive, invocationTtlMs: positive,
140
147
  balanceTtlMs: positive, machineTtlMs: positive, heartbeatMs: positive, leaseSilenceMs: positive,
141
148
  reserveFractionPpm: ppm, prepaidReserveFloorMicros: integer,
@@ -191,6 +191,11 @@ CREATE TABLE IF NOT EXISTS dispatcher_bridge_grants (
191
191
  PRIMARY KEY(org_id, grant_id),
192
192
  FOREIGN KEY(org_id, approved_by) REFERENCES identities(org_id, pubkey)
193
193
  );
194
+ CREATE TABLE IF NOT EXISTS dispatcher_shadow_grants (
195
+ org_id TEXT NOT NULL, grant_id TEXT NOT NULL, approved_by TEXT NOT NULL,
196
+ row JSONB NOT NULL, PRIMARY KEY(org_id, grant_id),
197
+ FOREIGN KEY(org_id, approved_by) REFERENCES identities(org_id, pubkey)
198
+ );
194
199
  CREATE TABLE IF NOT EXISTS dispatcher_evidence (
195
200
  org_id TEXT NOT NULL, kind TEXT NOT NULL, id TEXT NOT NULL, revision BIGINT NOT NULL CHECK(revision>0),
196
201
  source TEXT NOT NULL, source_ref TEXT NOT NULL, observed_at_ms BIGINT NOT NULL,
@@ -4,6 +4,7 @@ import { spawnSync } from "node:child_process";
4
4
  import { readFileSync, readdirSync, realpathSync, statSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { createHash } from "node:crypto";
7
+ import { createConnection } from "node:net";
7
8
  import { codexRolloutCwd } from "./turn-usage.mjs";
8
9
 
9
10
  export const HERDR_CLAUDE_INSTALL = "herdr integration install claude";
@@ -37,6 +38,67 @@ const validArgv = (args) => args.length > 0 && args.length <= 64
37
38
  && args.every(validArg)
38
39
  && Buffer.byteLength(args.join("\0")) <= 8192;
39
40
 
41
+ function herdrSocketAttempt(wire, socketPath, timeoutMs) {
42
+ return new Promise(resolve => {
43
+ let done = false, timeout;
44
+ const socket = createConnection(socketPath);
45
+ const finish = delivered => {
46
+ if (done) return;
47
+ done = true;
48
+ clearTimeout(timeout);
49
+ socket.destroy();
50
+ resolve(delivered);
51
+ };
52
+ socket.on("error", () => finish(false));
53
+ socket.on("connect", () => socket.write(wire));
54
+ socket.on("data", () => finish(true));
55
+ socket.on("end", () => finish(false));
56
+ timeout = setTimeout(() => finish(false), timeoutMs);
57
+ });
58
+ }
59
+
60
+ function herdrRequestWire(request) {
61
+ const seq = request.params.seq;
62
+ const json = JSON.stringify({ ...request, params: { ...request.params, seq: seq.toString() } });
63
+ return `${json.replace(`"seq":"${seq}"`, `"seq":${seq}`)}\n`;
64
+ }
65
+
66
+ async function herdrSocketRequest(request, wire = herdrRequestWire(request)) {
67
+ const socketPath = process.env.HERDR_SOCKET_PATH || "";
68
+ if (!socketPath) return false;
69
+ if (await herdrSocketAttempt(wire, socketPath, 500)) return true;
70
+ return herdrSocketAttempt(wire, socketPath, 1500);
71
+ }
72
+
73
+ function reportedHerdrSession(pane) {
74
+ try {
75
+ const result = spawnSync("herdr", ["agent", "get", pane], { encoding: "utf8", timeout: 1500 });
76
+ if (result.status !== 0) return "";
77
+ return JSON.parse(result.stdout || "{}")?.result?.agent?.agent_session?.value || "";
78
+ } catch { return ""; }
79
+ }
80
+
81
+ const herdrClockWall = BigInt(Date.now()) * 1_000_000n;
82
+ const herdrClockMono = process.hrtime.bigint();
83
+ let herdrReportSeq = 0n;
84
+ function nextHerdrReportSeq() {
85
+ const wall = herdrClockWall + process.hrtime.bigint() - herdrClockMono;
86
+ herdrReportSeq = wall > herdrReportSeq ? wall : herdrReportSeq + 1n;
87
+ return herdrReportSeq;
88
+ }
89
+
90
+ export async function reportHerdrSessionResume({ pane, sessionId, transcriptPath = "", resumeArgv = [] }, transport = herdrSocketRequest, readSession = reportedHerdrSession) {
91
+ if (!pane || !sessionId || !validArgv(resumeArgv)) return false;
92
+ // #14774: herdr orders reports by time_ns; BigInt keeps the ns integer exact.
93
+ const params = { pane_id: pane, source: "herdr:claude", agent: "claude", seq: nextHerdrReportSeq(),
94
+ agent_session_id: sessionId, session_start_source: "resume", resume_argv: resumeArgv };
95
+ if (transcriptPath) params.agent_session_path = transcriptPath;
96
+ const request = { id: `herdr:claude:${Date.now()}:${Math.random().toString(36).slice(2)}`,
97
+ method: "pane.report_agent_session", params };
98
+ if (!await transport(request, herdrRequestWire(request))) return false;
99
+ return await readSession(pane) === sessionId;
100
+ }
101
+
40
102
  export function runnerResumeArgv({ agent, driver = agent, persona = agent, dir, runnerPath, model = "", effort = null, project, hub, sessionId }) {
41
103
  if (!sessionId || !RESUMABLE.has(driver)) return [];
42
104
  const args = ["node", runnerPath, persona, dir, "--agent", agent, "--persona", persona,
@@ -19,7 +19,8 @@ export function seatProvider(agent) {
19
19
  }
20
20
 
21
21
  /** null when label and live model agree; else { label, model, expected, actual } for the refusal. */
22
- export function providerMismatch(label, model) {
22
+ export function providerMismatch(label, model, modelSource = "") {
23
+ if (modelSource === "cli-default") return null;
23
24
  const m = String(model || "");
24
25
  const actual = m.split("/")[0];
25
26
  if (!actual) return null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.157",
3
+ "version": "0.18.159",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"