trantor 0.18.139 → 0.18.141

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.139"
9
+ "version": "0.18.141"
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.139",
16
+ "version": "0.18.141",
17
17
  "author": {
18
18
  "name": "Sasha Bogojevic"
19
19
  },
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.139",
3
+ "version": "0.18.141",
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/README.md CHANGED
@@ -445,7 +445,7 @@ trantor setup | doctor | connect | profile | provider | models
445
445
  (`TRANTOR_DEV_ROOT`, else the Projects folder chosen in the app's Settings, stored as
446
446
  `projectsRoot` in `~/.agent-bus/config.json`, else `~/development`), git on main (or `--from <git-url>`, or `--adopt` an
447
447
  existing folder), installs the auto-card hook, posts the brief to the hub, and opens the first
448
- card "genesis: <name>". `--json` for machines. It never spawns a session — firing the crew
448
+ card "genesis: <name>". It asks once whether the project's agents ask before acting (the default) or act without asking (bypass); without a terminal it refuses unless `--permissions ask|bypass` is given. Change it later with `trantor project permissions <name> ask|bypass`. `--json` for machines. It never spawns a session — firing the crew
449
449
  stays your call. Two paths in: **blank** (no brief) wakes the orchestrator plainly and you work
450
450
  with it iteratively; **from a brief** (`--brief <file>`, or a PRD dropped on the app's Genesis
451
451
  sheet) stores it in `docs/PRD.md` with a small CLAUDE.md pointer, and the wake runs
package/bin/cli.mjs CHANGED
@@ -83,6 +83,24 @@ switch (cmd) {
83
83
  run("hub.mjs"); break;
84
84
  }
85
85
  case "project": {
86
+ // #14563: the per-project permission mode — the same harness dial `trantor new` asks about
87
+ // and `trantor open` launches with. Words are the user's (ask|bypass), storage is the
88
+ // autonomy dial (prompt|bypass).
89
+ if (args[0] === "permissions") {
90
+ const { resolveAutonomy, setAutonomy } = await import(join(ROOT, "lib/autonomy.mjs"));
91
+ const project = args[1];
92
+ const value = args[2];
93
+ const describe = (harness) => (harness === "bypass" ? "act without asking" : "ask before acting");
94
+ if (!project) { console.error("usage: trantor project permissions <name> [ask|bypass]"); process.exit(1); }
95
+ if (value === undefined) {
96
+ console.log(`${project}: agents ${describe(resolveAutonomy(project).harness)}`);
97
+ break;
98
+ }
99
+ if (value !== "ask" && value !== "bypass") { console.error(`value must be ask or bypass (got "${value}")`); process.exit(1); }
100
+ setAutonomy(project, { harness: value === "bypass" ? "bypass" : "prompt" });
101
+ console.log(`${project}: agents ${describe(value)}`);
102
+ break;
103
+ }
86
104
  // The checkout's identity (#6724): show where this project's name comes from, or record an id
87
105
  // in .trantor/project.json so a directory rename cannot orphan the pin, board and sessions.
88
106
  const { resolveProjectInfo, resolveHubInfo, gitRoot, readProjectId, writeProjectId, isProjectId, PROJECT_MARKER } = await import(join(ROOT, "lib/project.mjs"));
@@ -297,6 +315,7 @@ switch (cmd) {
297
315
  trantor handoff finish this session NOW: write a handoff, open a fresh session that takes over, and close this one (manual baton)
298
316
  trantor advise ask the Advisor directly (JSON on stdin; --demo to see it)
299
317
  trantor project this checkout's identity: project [<id>] — records .trantor/project.json so a directory rename cannot orphan the board, pin and sessions
318
+ project permissions <name> [ask|bypass] — whether <name>'s agents ask before acting or act without asking; no value prints it
300
319
  trantor hub run the hub in the foreground (setup installs it as a service instead)
301
320
  …or manage per-project hub pins: hub list · hub set <project> <url> · hub unset <project>
302
321
  seats: which project lives in which directory — seats · seats add · seats up · seats login install
package/bin/crew/open.mjs CHANGED
@@ -102,9 +102,11 @@ export function takeoverSessionId(ctx, id) {
102
102
  return hasPendingHandoff(ctx, id) ? randomUUID() : id;
103
103
  }
104
104
 
105
+ // #14563: bare `claude` inherits permissions.defaultMode from ~/.claude/settings.json, so a
106
+ // prompt project still ran bypass there — the dial must say its side out loud, both sides.
105
107
  function harnessFlag(ctx) {
106
108
  const result = call(process.execPath, [join(ctx.root, "bin/autonomy.mjs"), "get", "harness", "--project", ctx.project], { env: ctx.env });
107
- return result.stdout === "bypass" ? " --dangerously-skip-permissions" : "";
109
+ return result.stdout === "bypass" ? " --dangerously-skip-permissions" : " --permission-mode default";
108
110
  }
109
111
 
110
112
  function transcript(ctx, id) {
@@ -120,7 +122,8 @@ function orchestratorCommand(ctx, id) {
120
122
 
121
123
  function reportOrchestrator(ctx, pane, id) {
122
124
  const resumeArgv = ["env", ...STRIP.flatMap(name => ["-u", name]), `TRANTOR_ORCH=${ctx.project}`, "claude"];
123
- if (harnessFlag(ctx).trim()) resumeArgv.push("--dangerously-skip-permissions");
125
+ // #14563: the reported resume argv must be the SAME command the pane runs, dial included.
126
+ resumeArgv.push(...harnessFlag(ctx).trim().split(" "));
124
127
  resumeArgv.push("--resume", id);
125
128
  reportAgent(ctx, pane, "claude", { sessionId: id, resumeArgv });
126
129
  }
@@ -214,10 +217,9 @@ function hostPane(ctx, chosen, id) {
214
217
  return pane;
215
218
  }
216
219
 
217
- // #6888: index the project once so its seats' Graft tools (graft_find_code, _trace_calls, …) have a
218
- // graph to serve. Non-blocking — the pane opens now, the ~7s build lands in the background; a no-op
219
- // if graft isn't installed or the index already exists (the graph self-refreshes per query after the
220
- // first build). Keeps the 20MB index out of the project's git.
220
+ // #6888: index the project once for the desktop's direct graft CLI reads. Non-blocking — the pane
221
+ // opens now, the ~7s build lands in the background; a no-op if graft isn't installed or the index
222
+ // already exists. Keeps the 20MB index out of the project's git.
221
223
  // Hide graft/ through .git/info/exclude, never the user's tracked .gitignore (#14322). Returns the file written, "" when not a git checkout.
222
224
  export function excludeGraftLocally(dir) {
223
225
  try {
@@ -251,7 +253,7 @@ export function maybeBuildGraft(dir) {
251
253
  const child = spawn("graft", ["build", dir], { cwd: dir, stdio: ["ignore", fd, fd], detached: true });
252
254
  child.on("error", () => {}); // ENOENT/EACCES: the log and the absent index are the evidence
253
255
  child.unref();
254
- console.error(`— indexing this project for the seats' Graft tools in the background (failures land in ${log}) —`);
256
+ console.error(`— indexing this project for the desktop's graft CLI in the background (failures land in ${log}) —`);
255
257
  } catch {}
256
258
  }
257
259
 
@@ -19,16 +19,16 @@ import { shellQuote } from "./crew/core.mjs";
19
19
  // One ownership map. Shared steps must finish before ANY card they cover can close.
20
20
  export const CARD_STEPS = {
21
21
  6799: { steps: ["S0", "S1", "S2", "S3", "S4", "S5"], autoClose: false },
22
- 6533: { steps: ["S6-ask"], autoClose: false, recipe: "covered by in-app Drill Mode: open a live orchestrator mid-ask, answer from Chat, and confirm the terminal advances and the card closes" },
22
+ 6533: { steps: ["S6-ask"], autoClose: false, recipe: "run TRANTOR_ASK_DRILL=trantor on the installed app, answer from Chat, and confirm the terminal advances and the card closes" },
23
23
  6668: { steps: ["S6-handoff"], autoClose: true },
24
- 6317: { steps: ["S6-key-post", "S6-key-throw"], autoClose: false, recipe: "covered by in-app Drill Mode: open a real Workspace with a live terminal pane and exercise key dispatch in the terminal and composer" },
24
+ 6317: { steps: ["S6-key-post", "S6-key-throw"], autoClose: false, recipe: "run TRANTOR_KEY_DRILL=post and TRANTOR_KEY_DRILL=throw on the installed app and verify key dispatch and exception containment" },
25
25
  6667: { steps: ["S4b", "S7"], autoClose: true },
26
26
  // P9 (#6965): the Phase-1 handoff carries a WorkingState and it carries NO credit. Never
27
27
  // auto-closes — with the flag off the step SKIPs, and a skip must not be mistaken for proof.
28
28
  6965: { steps: ["S4c"], autoClose: false, recipe: "set TRANTOR_STATE_HANDOFF=1 on a dogfood card, run `trantor drill`, and read S4c: the carried state must show 0 credited paths" },
29
29
  6587: { steps: ["S8"], autoClose: false, recipe: "needs live duty probe: operator removes the trantor/trantor-duty link, DMs the idle orchestrator, and checks for a socket nudge within 3 minutes" },
30
30
  6481: { steps: ["S9"], autoClose: true },
31
- 6483: { steps: ["S10"], autoClose: false, recipe: "covered by in-app Drill Mode (#6800): operator checks Accounts with the CLI below the app minimum, then restores the CLI" },
31
+ 6483: { steps: ["S10"], autoClose: false, recipe: "operator checks Settings › About with the CLI below the app minimum, then restores the CLI" },
32
32
  };
33
33
 
34
34
  export function findHandoff(dir, project) {
package/bin/new.mjs CHANGED
@@ -1,24 +1,14 @@
1
1
  #!/usr/bin/env node
2
- // trantor new — project genesis, the CLI half (#5862). One command stands a project up:
3
- //
4
- // trantor new <name> [--from <git-url>] [--brief <file>] [--dir <parent>] [--adopt] [--json]
5
- //
6
- // It makes the project directory at <parent>/<name> — --dir names the PARENT, never the project
7
- // directory itself (default parent: TRANTOR_DEV_ROOT or ~/development). The name is always
8
- // appended under it, so `--dir P` with name N creates P/N. Starts git on main (or clones --from,
9
- // or adopts an existing folder with --adopt), stores the brief in docs/PRD.md and seeds a small
10
- // CLAUDE.md pointer plus the trantor conventions block, installs the same auto-card hook as
11
- // `trantor init-hooks`, posts the brief as the hub project brief (POST /project — the same call
12
- // relay_project_brief makes), and opens the first card "genesis: <name>" on the new board.
13
- //
14
- // It NEVER spawns a session: the wake is genesis-2, the app half. A hub that is down downgrades
15
- // the genesis to a warning (card: null) — the directory is real either way, and a dead hub must
16
- // not make a made project look unmade.
2
+ // trantor new — project genesis, the CLI half (#5862): one command stands a project up:
3
+ // trantor new <name> [--from <git-url>] [--brief <file>] [--dir <parent>] [--adopt] [--permissions ask|bypass] [--json]
4
+ // It makes <parent>/<name>, starts git, seeds docs/PRD.md + CLAUDE.md + the auto-card hook, posts
5
+ // the brief + first card to the hub, and asks once whether the agents ask before acting (#14563).
17
6
  import { spawnSync } from "node:child_process";
18
7
  import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync, appendFileSync } from "node:fs";
19
8
  import { homedir } from "node:os";
20
9
  import { basename, dirname, isAbsolute, join, resolve } from "node:path";
21
10
  import { fileURLToPath } from "node:url";
11
+ import { createInterface } from "node:readline";
22
12
  import { ensureEnrolled as enrollTofu, loadIdentity, signedPost } from "../hooks/lib/api.mjs";
23
13
  import { ensureEnrolled as enrollViaOwnerInvite } from "../lib/enroll.mjs";
24
14
  import { setAutonomy } from "../lib/autonomy.mjs";
@@ -55,7 +45,7 @@ const flag = (n) => { const i = args.indexOf("--" + n); return i >= 0 ? args[i +
55
45
  const has = (n) => args.includes("--" + n);
56
46
  const json = has("json");
57
47
  const name = args.find(a => !a.startsWith("--"));
58
- if (!name) die("usage: trantor new <name> [--from <git-url>] [--brief <file>] [--dir <parent>] [--adopt] [--json] — project lands at <parent>/<name>");
48
+ if (!name) die("usage: trantor new <name> [--from <git-url>] [--brief <file>] [--dir <parent>] [--adopt] [--permissions ask|bypass] [--json] — project lands at <parent>/<name>");
59
49
  if (!/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)) die(`invalid project name "${name}" — letters, digits, dot, dash, underscore`);
60
50
  const from = flag("from");
61
51
  const briefFile = flag("brief");
@@ -79,6 +69,35 @@ const existed = existsSync(dir);
79
69
  const occupied = existed && readdirSync(dir).length > 0;
80
70
  if (occupied && !adopt) die(`"${dir}" already exists and is not empty — pass --adopt to adopt it`);
81
71
  if (adopt && !existed) die(`--adopt: "${dir}" does not exist — nothing to adopt`);
72
+
73
+ // ── the permission mode (#14563): one plain question, answered before anything is created ────────
74
+ // User words are ask|bypass; the stored dial is the harness prompt|bypass. A non-TTY run must say
75
+ // the flag rather than guess — a refused genesis leaves no directory behind.
76
+ const permissionsArg = flag("permissions");
77
+ if (permissionsArg != null && permissionsArg !== "ask" && permissionsArg !== "bypass") {
78
+ die(`--permissions takes ask or bypass (got "${permissionsArg}")`);
79
+ }
80
+ let permissions;
81
+ if (permissionsArg != null) {
82
+ permissions = permissionsArg;
83
+ } else if (process.stdin.isTTY) {
84
+ const say = json ? console.error : console.log;
85
+ const rl = createInterface({ input: process.stdin, output: json ? process.stderr : process.stdout });
86
+ const choose = () => new Promise(res => rl.question("Choose [1]: ", res));
87
+ say(`How should ${name}'s agents work?`);
88
+ say(" 1) Ask before acting (recommended): they ask before commands, edits and installs");
89
+ say(" 2) Act without asking (bypass): they act on their own, as you");
90
+ let answer = (await choose()).trim();
91
+ while (answer !== "" && answer !== "1" && answer !== "2") {
92
+ say("1 = ask before acting · 2 = act without asking (bypass)");
93
+ answer = (await choose()).trim();
94
+ }
95
+ rl.close();
96
+ permissions = answer === "2" ? "bypass" : "ask";
97
+ } else {
98
+ die("no terminal to ask in; pass --permissions ask or --permissions bypass");
99
+ }
100
+
82
101
  if (!existed) mkdirSync(dir, { recursive: true });
83
102
 
84
103
  // ── git ─────────────────────────────────────────────────────────────────────────────────────────
@@ -119,9 +138,9 @@ if (existsSync(claude)) {
119
138
  const hook = spawnSync(process.execPath, [join(ROOT, "bin", "init-hooks.mjs")], { cwd: dir, encoding: "utf8" });
120
139
  if (hook.status !== 0) die(`hook install failed: ${(hook.stderr || "").trim()}`);
121
140
 
122
- // A new project is a new trust boundary. Pin its harness dial even when the machine-wide default
123
- // is bypass, so opening it can never inherit another project's permission choice.
124
- setAutonomy(name, { harness: "prompt" });
141
+ // A new project is a new trust boundary: its harness dial is the operator's explicit #14563
142
+ // answer, so opening it can never inherit another project's — or the machine default's — mode.
143
+ setAutonomy(name, { harness: permissions === "bypass" ? "bypass" : "prompt" });
125
144
 
126
145
  // ── the hub: pin + brief + first card, signed like every other client ──────────────────────────
127
146
  const hub = resolveHub(name);
@@ -134,12 +153,10 @@ const identity = loadIdentity(session);
134
153
  let card = null;
135
154
  let hubError = null;
136
155
  try {
137
- // The genesis identity is BRAND NEW — it cannot write to a project on an enforce hub until the
138
- // hub knows it. TOFU /enroll only works on a local loopback hub; a remote enforce hub refuses it
139
- // (403 "tofu enrollment refused") and the genesis silently records nothing (#6049). So enroll the
140
- // way crew seats do: the operator's owner key mints a project-scoped write invite and the genesis
141
- // identity spends it. Only when NO owner key is configured (a loopback hub with no owner identity)
142
- // do we fall back to the plain TOFU enroll.
156
+ // The genesis identity is BRAND NEW — TOFU /enroll only works on a loopback hub; a remote
157
+ // enforce hub refuses it (403) and the genesis silently records nothing (#6049). Enroll like
158
+ // crew seats: the owner key mints a project-scoped write invite, the genesis spends it; plain
159
+ // TOFU only when no owner key is configured (a loopback hub with no owner identity).
143
160
  const viaOwner = await enrollViaOwnerInvite(hub, identity, name, { timeoutMs: 8000, kind: "tool" });
144
161
  if (!viaOwner.ok && viaOwner.reason === "no-owner-key") await enrollTofu(session, identity, name, { kind: "tool" });
145
162
  else if (!viaOwner.ok) console.error(`genesis: enrollment via owner invite failed: ${viaOwner.reason}`);
@@ -169,8 +186,11 @@ try {
169
186
  // dir is the created project directory <parent>/<name>; parent is the --dir (or default) root the
170
187
  // name was appended under — the two together state the parent contract explicitly.
171
188
  if (json) {
172
- console.log(JSON.stringify({ name, parent: devRoot, dir, branch, hub, card }));
189
+ console.log(JSON.stringify({ name, parent: devRoot, dir, branch, hub, card, permissions }));
173
190
  } else {
191
+ // #14563: the artboard's confirmation — states the choice and the way to change it.
192
+ console.log(`✓ ${name} created · agents ${permissions === "bypass" ? "act without asking" : "ask before acting"} · change it with:`);
193
+ console.log(` trantor project permissions ${name} ask|bypass`);
174
194
  console.log(`✓ ${dir} (${branch}${from ? ", cloned" : adopt ? ", adopted" : ""})`);
175
195
  console.log(brief
176
196
  ? "✓ docs/PRD.md seeded from the brief; CLAUDE.md kept small"
@@ -490,9 +490,9 @@ try {
490
490
  // attended (default) = recap-then-WAIT; unattended = recap-then-RESUME — the handoff's OPEN
491
491
  // THREADS are the work order ("handoffs must never be a break").
492
492
  if (handoff.mode === "unattended") {
493
- additionalContext += `🔄 **You are taking over from a prior session that hit its context limit, in UNATTENDED (long-run) mode.** This is a fresh full window. Resume the work below — the prior session's summary, git state, and a pointer to its full transcript (searchable; Foundation/Gaia has it ingested) follow. Continue from "OPEN THREADS & NEXT STEPS"; do not restart from scratch.\n\n**READ BEFORE YOU BUILD (#8162).** This summary is a POINTER to the project's context, not a replacement for it. Open every file this handoff names as read-first — its memory files, its PRD and its TDD — BEFORE you touch code. Reading is not waiting, and it is not optional: three days running, successors recapped from this summary alone and went straight to code, burning a fifth of a context window rediscovering what was already written down. The ledger now checks which files you opened, not whether you replied.\n\nThen recap the task, state, and next step in at most 3 sentences, then RESUME the open threads — they are your work order. Do NOT wait for the user; keep building. Keep replies short: no status tables, no headers, no walls of text.\n\n`;
493
+ additionalContext += `🔄 **You are taking over from a prior session that hit its context limit, in UNATTENDED (long-run) mode.** This is a fresh full window. Resume the work below — the prior session's summary, git state, and a pointer to its full transcript (searchable) follow. Continue from "OPEN THREADS & NEXT STEPS"; do not restart from scratch.\n\n**READ BEFORE YOU BUILD (#8162).** This summary is a POINTER to the project's context, not a replacement for it. Open every file this handoff names as read-first — its memory files, its PRD and its TDD — BEFORE you touch code. Reading is not waiting, and it is not optional: three days running, successors recapped from this summary alone and went straight to code, burning a fifth of a context window rediscovering what was already written down. The ledger now checks which files you opened, not whether you replied.\n\nThen recap the task, state, and next step in at most 3 sentences, then RESUME the open threads — they are your work order. Do NOT wait for the user; keep building. Keep replies short: no status tables, no headers, no walls of text.\n\n`;
494
494
  } else {
495
- additionalContext += `🔄 **You are taking over from a prior session that hit its context limit.** This is a fresh full window. Resume the work below — the prior session's summary, git state, and a pointer to its full transcript (searchable; Foundation/Gaia has it ingested) follow. Continue from "OPEN THREADS & NEXT STEPS"; do not restart from scratch.\n\n**READ BEFORE YOU ANSWER (#8162).** This summary is a POINTER to the project's context, not a replacement for it. Open every file this handoff names as read-first — its memory files, its PRD and its TDD — before you recap. A 3-sentence recap is producible from this summary alone, which is exactly how three days of takeovers went straight to code without opening anything. The ledger now checks which files you opened, not whether you replied.\n\nThen recap the task, state, and next step in at most 3 sentences, then wait. Keep replies short: no status tables, no headers, no walls of text unless the user explicitly asks for detail.\n\n`;
495
+ additionalContext += `🔄 **You are taking over from a prior session that hit its context limit.** This is a fresh full window. Resume the work below — the prior session's summary, git state, and a pointer to its full transcript (searchable) follow. Continue from "OPEN THREADS & NEXT STEPS"; do not restart from scratch.\n\n**READ BEFORE YOU ANSWER (#8162).** This summary is a POINTER to the project's context, not a replacement for it. Open every file this handoff names as read-first — its memory files, its PRD and its TDD — before you recap. A 3-sentence recap is producible from this summary alone, which is exactly how three days of takeovers went straight to code without opening anything. The ledger now checks which files you opened, not whether you replied.\n\nThen recap the task, state, and next step in at most 3 sentences, then wait. Keep replies short: no status tables, no headers, no walls of text unless the user explicitly asks for detail.\n\n`;
496
496
  }
497
497
  // Verification gates FIRST — these are structured "must verify before shipping" claims the prior
498
498
  // session couldn't independently prove. They go above the summary on purpose: a safety-critical
package/kimi.plugin.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.139",
3
+ "version": "0.18.141",
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",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.139",
3
+ "version": "0.18.141",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"
@@ -32,7 +32,7 @@ PRD.md + TDD.md. The TDD MUST define one file-set per agent (no merge conflicts)
32
32
  explicit EVENT/INTERFACE CONTRACT — cross-agent bugs come from contract drift.
33
33
 
34
34
  ## Phase 1 — board setup
35
- 0. No project yet? `trantor new <name> --brief <file>` stands one up (dir, git main, CLAUDE.md
35
+ 0. No project yet? `trantor new <name> --brief <file> --permissions ask` stands one up (`--permissions` is required without a terminal: `ask` unless the operator said bypass) (dir, git main, CLAUDE.md
36
36
  from the brief, hooks, hub brief + first card) — it never spawns a session; firing the crew
37
37
  is this phase's job.
38
38
  1. `relay_project_brief("<what + why + goal>")`
@@ -1,205 +0,0 @@
1
- import test from "node:test";
2
- import assert from "node:assert/strict";
3
- import { mkdtempSync, mkdirSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
4
- import { join } from "node:path";
5
- import { createServer, createConnection } from "node:net";
6
- import { createServer as createHttpServer } from "node:http";
7
- import { DrillReport } from "./drill-report.mjs";
8
- import { CARD_STEPS, findHandoff } from "./drill-surface.mjs";
9
- import { appVerdict, startDrillHub, stopChild, checkSocketHome } from "./drill-seams.mjs";
10
- import { signedGet, signedPost } from "../hooks/lib/api.mjs";
11
-
12
- test("S4 waits for the hook ledger when relay_handoff arrives first", () => {
13
- const world = mkdtempSync(join(import.meta.dirname, "..", ".agent-bus-out", "ledger-"));
14
- try {
15
- assert.equal(findHandoff(join(world, "missing"), "trantor"), null);
16
- writeFileSync(join(world, "trantor-100.json"), JSON.stringify({ summary: "tool handoff" }));
17
- writeFileSync(join(world, "trantor-101.json"), "{");
18
- writeFileSync(join(world, "trantor-102.json"), JSON.stringify({ states: [] }));
19
- writeFileSync(join(world, "other-100.json"), JSON.stringify({ states: [{ state: "written" }] }));
20
- assert.equal(findHandoff(world, "trantor"), null);
21
- const ledger = join(world, "trantor-103.json");
22
- writeFileSync(ledger, JSON.stringify({ states: [{ state: "written" }] }));
23
- assert.equal(findHandoff(world, "trantor"), ledger);
24
- writeFileSync(ledger, JSON.stringify({ states: [{ state: "written" }, { state: "claimed" }, { state: "recapped" }] }));
25
- assert.equal(findHandoff(world, "trantor"), ledger);
26
- } finally { rmSync(world, { recursive: true, force: true }); }
27
- });
28
-
29
- test("signed closer on an enforce hub: complete evidence closes, partial/failure/skip never does", async () => {
30
- const out = join(import.meta.dirname, "..", ".agent-bus-out");
31
- mkdirSync(out, { recursive: true });
32
- const world = mkdtempSync(join(out, "closer-test-"));
33
- const bus = join(world, "bus");
34
- const hub = await startDrillHub(world, bus);
35
- const saved = { ...process.env };
36
- Object.assign(process.env, { RELAY_URL: hub.url, AGENT_BUS_DIR: bus, RELAY_SESSION: "drill:trantor", RELAY_PROJECT: "trantor" });
37
- const project = "trantor", session = "drill:trantor";
38
- const path = join(world, "drill-result.json");
39
- try {
40
- const create = await signedPost("/task", { project, by: session, title: "closer test", status: "testing" });
41
- assert.equal(create.ok, true, JSON.stringify(create));
42
- const id = create.json.task.id;
43
- const report = new DrillReport({ [id]: { steps: ["one", "two"], autoClose: true } }, path, { project, session });
44
- report.record("one", "pass", "first assertion", "real evidence A");
45
- await report.closePassed();
46
- assert.equal(report.results()[id].status, "fail");
47
- assert.equal((await signedGet("/tasks?project=trantor")).json.tasks[0].status, "testing");
48
- report.complete("one");
49
- report.record("two", "pass", "second assertion", "real evidence B");
50
- report.complete("two");
51
- assert.equal(await report.closePassed(), true);
52
- const card = (await signedGet("/tasks?project=trantor")).json.tasks[0];
53
- assert.equal(card.status, "done");
54
- assert.equal(card.workedBy, session);
55
- assert.match(card.log.at(-1).text, /^Drill: trantor drill PASS/); // #6452: the closer's note IS the drill line the hub gate requires
56
- assert.match(card.log.at(-1).text, /real evidence A/);
57
- assert.match(card.log.at(-1).text, /real evidence B/);
58
- assert.equal(JSON.parse(readFileSync(path, "utf8"))[id].closure, "done");
59
- const notes = card.log.length;
60
- await report.closePassed();
61
- assert.equal((await signedGet("/tasks?project=trantor")).json.tasks[0].log.length, notes);
62
- const unsigned = await fetch(`${hub.url}/task/update`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ id, status: "testing", by: session }) });
63
- assert.equal(unsigned.status, 401);
64
-
65
- for (const status of ["fail", "skip"]) {
66
- const created = await signedPost("/task", { project, by: session, title: status, status: "testing" });
67
- const blockedId = created.json.task.id;
68
- const blocked = new DrillReport({ [blockedId]: { steps: ["step"], autoClose: true } }, path, { project, session });
69
- blocked.record("step", "pass", "partial success");
70
- blocked.record("step", status, "missing proof");
71
- blocked.complete("step");
72
- await blocked.closePassed();
73
- assert.equal(blocked.results()[blockedId].status, status);
74
- assert.equal((await signedGet("/tasks?project=trantor")).json.tasks.find(row => row.id === blockedId).status, "testing");
75
- }
76
- // #11498: a green seam mapped to a card the board no longer has (the fleet cap deletes old
77
- // cards, #11142) — the hub's 404 "no such task" is a stale map, recorded as gone, never red.
78
- const missing = new DrillReport({ 999999: { steps: ["step"], autoClose: true } }, path, { project, session });
79
- missing.record("step", "pass", "proof");
80
- missing.complete("step");
81
- assert.equal(await missing.closePassed(), true);
82
- assert.equal(missing.results()[999999].closure, "gone: card no longer on the board");
83
- assert.equal(missing.exitCode(), 0);
84
- const fresh = new DrillReport({ [id]: { steps: ["one"], autoClose: true } }, path, { project, session });
85
- assert.equal(fresh.results()[id].status, "fail", "a rerun cannot inherit old PASS evidence");
86
- } finally {
87
- for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key];
88
- Object.assign(process.env, saved);
89
- await stopChild(hub.child);
90
- rmSync(world, { recursive: true, force: true });
91
- }
92
- });
93
-
94
- test("gone vs refused (#11498): a 404 no-such-task close is green, any other refusal stays red", async () => {
95
- const out = join(import.meta.dirname, "..", ".agent-bus-out");
96
- mkdirSync(out, { recursive: true });
97
- const world = mkdtempSync(join(out, "refusal-test-"));
98
- const bus = join(world, "bus");
99
- mkdirSync(bus, { recursive: true });
100
- // A stub hub that refuses per card id: 777 is gone (404 no-such-task, the fleet cap's answer,
101
- // #11142), 4242 is a cross-project refusal, 5150 a server error — the closes a drill must keep red.
102
- const answers = { 777: [404, "no such task"], 4242: [403, "cross-project writes are refused"], 5150: [500, "hub exploded"] };
103
- const stub = createHttpServer((req, res) => {
104
- let body = "";
105
- req.on("data", d => { body += d; });
106
- req.on("end", () => {
107
- let id = null; try { id = JSON.parse(body).id; } catch {}
108
- const [code, error] = answers[id] || [404, "no such task"];
109
- res.writeHead(code, { "content-type": "application/json" });
110
- res.end(JSON.stringify({ error }));
111
- });
112
- });
113
- await new Promise(resolve => stub.listen(0, "127.0.0.1", resolve));
114
- const saved = { ...process.env };
115
- Object.assign(process.env, { RELAY_URL: `http://127.0.0.1:${stub.address().port}`, AGENT_BUS_DIR: bus, RELAY_SESSION: "drill:trantor", RELAY_PROJECT: "trantor" });
116
- const ctx = { project: "trantor", session: "drill:trantor" };
117
- try {
118
- const report = (id) => {
119
- const r = new DrillReport({ [id]: { steps: ["step"], autoClose: true } }, join(world, `result-${id}.json`), ctx);
120
- r.record("step", "pass", "proof", "real evidence");
121
- r.complete("step");
122
- return r;
123
- };
124
- const gone = report(777);
125
- assert.equal(await gone.closePassed(), true, "404 no-such-task is a stale map, not a failed seam");
126
- assert.equal(gone.results()[777].closure, "gone: card no longer on the board");
127
- assert.equal(gone.exitCode(), 0);
128
-
129
- // gone + refused together: one real hub refusal among gones still reds the drill
130
- const mixed = new DrillReport({ 777: { steps: ["step"], autoClose: true }, 4242: { steps: ["step"], autoClose: true } }, join(world, "result-mixed.json"), ctx);
131
- for (const id of [777, 4242]) { mixed.record("step", "pass", "proof", "real evidence"); mixed.complete("step"); }
132
- assert.equal(await mixed.closePassed(), false);
133
- assert.equal(mixed.results()[777].closure, "gone: card no longer on the board");
134
- assert.match(mixed.results()[4242].closure, /^failed: hub 403/);
135
- assert.equal(mixed.exitCode(), 1);
136
-
137
- const dead = report(5150);
138
- assert.equal(await dead.closePassed(), false, "a server error is a real refusal");
139
- assert.match(dead.results()[5150].closure, /^failed: hub 500/);
140
- assert.equal(dead.exitCode(), 1);
141
- } finally {
142
- for (const key of Object.keys(process.env)) if (!(key in saved)) delete process.env[key];
143
- Object.assign(process.env, saved);
144
- stub.close();
145
- rmSync(world, { recursive: true, force: true });
146
- }
147
- });
148
-
149
- test("app proof requires every leg and rejects skipped key targets", () => {
150
- assert.deepEqual(CARD_STEPS[6317].steps, ["S6-key-post", "S6-key-throw"]);
151
- assert.equal(appVerdict("ask", "ask-drill PASS:"), false);
152
- assert.equal(appVerdict("ask", "ask-drill open PASS\nask-drill cold PASS\nask-drill PASS:"), true);
153
- const key = [1, 2, 3].map(pass => `key-drill pass=${pass} posted keyDown+keyUp`).join("\n") + "\nkey-drill verdict exit=0";
154
- assert.equal(appVerdict("key-post", key), true);
155
- assert.equal(appVerdict("key-post", key + "\npass=2 skipped"), false);
156
- assert.equal(appVerdict("key-throw", key), false);
157
- assert.equal(appVerdict("key-throw", key, "TaoObjcExceptionDrill"), true);
158
- assert.equal(appVerdict("handoff", "handoff-drill PASS:\nhandoff-drill verdict exit=3"), false);
159
- });
160
-
161
- test("manual probes remain SKIP even when the runner stops before reaching them", () => {
162
- const world = mkdtempSync(join(import.meta.dirname, "..", ".agent-bus-out", "skip-"));
163
- try {
164
- const report = new DrillReport(CARD_STEPS, join(world, "result.json"), { project: "trantor", session: "drill:trantor" });
165
- assert.deepEqual(Object.keys(CARD_STEPS).filter(id => CARD_STEPS[id].autoClose), ["6481", "6667", "6668"]);
166
- for (const id of [6317, 6533, 6587, 6483]) {
167
- assert.equal(report.results()[id].status, "skip");
168
- assert.equal(report.results()[id].closure, "not attempted");
169
- assert.match(report.results()[id].evidence.join(" "), id === 6587 ? /live duty probe/ : /covered by in-app Drill Mode/);
170
- }
171
- assert.equal(report.exitCode(), 1, "unrun seams still fail");
172
- for (const { steps, recipe } of Object.values(CARD_STEPS)) {
173
- if (recipe) continue;
174
- for (const step of steps) {
175
- report.record(step, step === "S5" ? "skip" : "pass", step === "S5" ? "interactive Terminal takeover probe" : "seam proof");
176
- report.complete(step);
177
- }
178
- }
179
- assert.equal(report.exitCode(), 0, "passing seams plus manual SKIPs exit zero");
180
- report.record("S4", "fail", "ledger missing");
181
- assert.equal(report.exitCode(), 1, "a real seam failure remains fatal");
182
- } finally { rmSync(world, { recursive: true, force: true }); }
183
- });
184
-
185
- test("short drill HOME connects through the native socket symlink; old staging is rejected", async () => {
186
- const world = mkdtempSync(`${join(import.meta.dirname, "..", ".agent-bus-out")}/`);
187
- const server = createServer(socket => socket.end("connected"));
188
- try {
189
- const path = checkSocketHome(world);
190
- assert.throws(() => checkSocketHome(join(world, "x".repeat(108))), /too long/);
191
- mkdirSync(join(world, ".config", "herdr"), { recursive: true });
192
- const target = join(world, "s");
193
- await new Promise((resolve, reject) => { server.once("error", reject); server.listen(target, resolve); });
194
- symlinkSync(target, path);
195
- const proof = await new Promise((resolve, reject) => {
196
- const socket = createConnection(path);
197
- socket.once("error", reject);
198
- socket.once("data", data => resolve(data.toString()));
199
- });
200
- assert.equal(proof, "connected");
201
- } finally {
202
- await new Promise(resolve => server.close(resolve));
203
- rmSync(world, { recursive: true, force: true });
204
- }
205
- });
@@ -1,34 +0,0 @@
1
- #!/usr/bin/env node
2
- // trantor seat-tokens (#11559) — per-provider token totals for the seat fleet from opencode's
3
- // session store, the 30-day shape compared week over week: sessions, assistant steps, tokens,
4
- // the single biggest step, and cost. Read-only; a missing or locked DB prints "no data".
5
- // node bin/seat-tokens.mjs [--days 30] [--db <path>] [--json]
6
- import { homedir } from "node:os";
7
- import { join } from "node:path";
8
- import { seatTokensReport } from "../lib/seat-tokens.mjs";
9
-
10
- const argv = process.argv.slice(2);
11
- const val = (k, d) => { const i = argv.indexOf(k); return i >= 0 && argv[i + 1] ? argv[i + 1] : d; };
12
- const DAYS = Math.max(1, Number(val("--days", 30)) || 30);
13
- const DB = val("--db", join(process.env.XDG_DATA_HOME || join(homedir(), ".local", "share"), "opencode", "opencode.db"));
14
- const since = Date.now() - DAYS * 24 * 60 * 60 * 1000;
15
- const rows = seatTokensReport({ dbPath: DB, sinceMs: since });
16
- const fmt = (n) => Number(n).toLocaleString("en-US");
17
-
18
- if (val("--json", "")) { console.log(JSON.stringify({ db: DB, days: DAYS, providers: rows }, null, 1)); process.exit(0); }
19
- if (!rows.length) { console.log(`no session data in ${DB} for the last ${DAYS} day(s)`); process.exit(0); }
20
- console.log(`opencode seat usage, last ${DAYS} day(s) — ${DB}\n`);
21
- console.log("provider sessions steps input output cache-read cache-write peak-step cost");
22
- for (const r of rows) {
23
- console.log(
24
- String(r.provider).padEnd(18),
25
- String(r.sessions).padStart(8),
26
- String(r.steps).padStart(8),
27
- fmt(r.input).padStart(12),
28
- fmt(r.output).padStart(10),
29
- fmt(r.cacheRead).padStart(14),
30
- fmt(r.cacheWrite).padStart(14),
31
- fmt(r.peakInput).padStart(12),
32
- fmt(Math.round(r.cost)).padStart(6),
33
- );
34
- }
@@ -1,72 +0,0 @@
1
- // #11559: the seat fleet's token burn was invisible — mined by hand from opencode's DB. This
2
- // reader makes it a command: per-provider 30-day session/step/token totals, read-only, so a
3
- // week-over-week comparison is one line. No DB at all is "no data", never zero. Read path
4
- // mirrors lib/turn-usage.mjs (sqlite3 CLI, -readonly, fail-open).
5
- import { spawnSync } from "node:child_process";
6
-
7
- const num = (v) => { const n = Number(v); return Number.isInteger(n) && n >= 0 ? n : 0; };
8
-
9
- /// "provider/model" → "provider"; a bare model reads "?" so the row still groups. The 1.16.x DB
10
- /// also stores whole JSON blobs ({"id":…,"providerID":…,"variant":…}) in session.model — the
11
- /// provider then lives at $.providerID. The SQL mirrors this in CASE/WHEN form.
12
- export function providerOf(model) {
13
- const s = String(model || "").trim();
14
- if (s.startsWith("{")) {
15
- try { return String(JSON.parse(s).providerID || "?"); } catch { return "?"; }
16
- }
17
- const at = s.indexOf("/");
18
- return at > 0 ? s.slice(0, at) : "?";
19
- }
20
-
21
- const PROVIDER_SQL = (col) => `CASE WHEN substr(${col},1,1)='{' THEN COALESCE(json_extract(${col},'$.providerID'),'?')`
22
- + ` WHEN instr(${col},'/')>1 THEN substr(${col},1,instr(${col},'/')-1) ELSE '?' END`;
23
-
24
- export const SESSIONS_SQL = (sinceMs) => `SELECT ${SESSION_COLS} FROM session`
25
- + ` WHERE time_updated>=${Math.floor(sinceMs)} GROUP BY p ORDER BY total DESC;`;
26
- const SESSION_COLS = `${PROVIDER_SQL("model")} AS p, COUNT(*) AS sessions,`
27
- + ` COALESCE(SUM(tokens_input),0), COALESCE(SUM(tokens_output),0), COALESCE(SUM(tokens_cache_read),0),`
28
- + ` COALESCE(SUM(tokens_cache_write),0), COALESCE(SUM(cost),0), COALESCE(MIN(time_created),0),`
29
- + ` COALESCE(MAX(time_updated),0), COALESCE(SUM(tokens_input+tokens_output+tokens_cache_read+tokens_cache_write),0) AS total`;
30
-
31
- export const STEPS_SQL = (sinceMs) => `SELECT ${PROVIDER_SQL("s.model")} AS p,`
32
- + ` COUNT(m.id), COALESCE(MAX(json_extract(m.data,'$.tokens.input')),0)`
33
- + ` FROM message m JOIN session s ON s.id=m.session_id`
34
- + ` WHERE json_extract(m.data,'$.role')='assistant' AND m.time_created>=${Math.floor(sinceMs)} GROUP BY p;`;
35
-
36
- const pipeRows = (text, cols) => String(text || "").split("\n").filter((l) => l.trim() !== "")
37
- .map((line) => {
38
- const parts = line.split("|");
39
- return parts.length === cols ? parts : null;
40
- })
41
- .filter(Boolean);
42
-
43
- /// { provider, sessions, input, output, cacheRead, cacheWrite, cost, firstAt, lastAt, tokens,
44
- /// steps, peakInput } per provider, tokens descending. [] when both queries return nothing —
45
- /// an empty fleet and an unreadable DB print the same "no data" line, never zeros that lie.
46
- export function seatTokensReport({ dbPath, sinceMs, run = spawnSync } = {}) {
47
- if (!dbPath || !Number.isFinite(sinceMs)) return [];
48
- const q = (sql) => {
49
- let r;
50
- try { r = run("sqlite3", ["-readonly", dbPath, sql], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: 15000 }); }
51
- catch { return null; }
52
- return !r || r.error || r.status !== 0 ? null : r.stdout;
53
- };
54
- const sessions = pipeRows(q(SESSIONS_SQL(sinceMs)), 10);
55
- const steps = pipeRows(q(STEPS_SQL(sinceMs)), 3);
56
- const byProvider = new Map(sessions.map((c) => [c[0], {
57
- provider: c[0],
58
- sessions: num(c[1]),
59
- input: num(c[2]), output: num(c[3]), cacheRead: num(c[4]), cacheWrite: num(c[5]),
60
- cost: Number(c[6]) || 0,
61
- firstAt: num(c[7]), lastAt: num(c[8]),
62
- tokens: num(c[9]),
63
- steps: 0, peakInput: 0,
64
- }]));
65
- for (const [p, count, peak] of steps) {
66
- const row = byProvider.get(p);
67
- if (!row) continue;
68
- row.steps = num(count);
69
- row.peakInput = num(peak);
70
- }
71
- return [...byProvider.values()].sort((a, b) => b.tokens - a.tokens);
72
- }