trantor 0.18.149 → 0.18.152

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.
@@ -0,0 +1,181 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { existsSync, mkdirSync, readFileSync, realpathSync, renameSync, writeFileSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { checkoutFor, PROJECT_MARKER, resolveHub, resolveProject, worktreeProject } from "./project.mjs";
6
+ import { ownerIdentity } from "./enroll.mjs";
7
+ import { z } from "zod";
8
+ import { sfetch } from "./signed-fetch.mjs";
9
+
10
+ const landing = z.enum(["auto", "review", "click"]);
11
+ const actions = z.strictObject({ land: landing, integrate: landing, push: z.enum(["autonomy", "click"]) });
12
+ const overrides = z.strictObject({
13
+ orchestrator: actions.partial().optional(), mixed: actions.partial().optional(), developer: actions.partial().optional(),
14
+ });
15
+ const mode = z.enum(["orchestrator", "mixed", "developer"]);
16
+ export const gitPolicyUpdate = z.strictObject({ mode, overrides, revision: z.number().int().nonnegative() });
17
+ const storedPolicy = gitPolicyUpdate.extend({ updatedBy: z.string().nullable(), updatedAtMs: z.number().int().nonnegative().nullable() });
18
+ const policyEnvelope = storedPolicy.extend({ effective: actions.optional() });
19
+ const defaults = {
20
+ orchestrator: { land: "auto", integrate: "auto", push: "autonomy" },
21
+ mixed: { land: "review", integrate: "review", push: "click" },
22
+ developer: { land: "click", integrate: "click", push: "click" },
23
+ };
24
+
25
+ export function gitPolicy(value) {
26
+ const parsed = policyEnvelope.safeParse(value);
27
+ const policy = parsed.success ? storedPolicy.parse({ mode: parsed.data.mode, overrides: parsed.data.overrides,
28
+ revision: parsed.data.revision, updatedBy: parsed.data.updatedBy, updatedAtMs: parsed.data.updatedAtMs })
29
+ : { mode: "developer", overrides: {}, revision: 0, updatedBy: null, updatedAtMs: null };
30
+ return { ...policy, effective: { ...defaults[policy.mode], ...policy.overrides[policy.mode] } };
31
+ }
32
+
33
+ export async function readGitPolicy({ hub, project, identity, fetchImpl = sfetch }) {
34
+ try {
35
+ const res = await fetchImpl(`${hub}/projects/${encodeURIComponent(project)}/git-policy`, {
36
+ signal: AbortSignal.timeout(10000),
37
+ }, identity);
38
+ if (!res.ok) return gitPolicy(null);
39
+ const parsed = storedPolicy.extend({ effective: actions }).safeParse(await res.json());
40
+ return gitPolicy(parsed.success ? storedPolicy.parse({ mode: parsed.data.mode, overrides: parsed.data.overrides,
41
+ revision: parsed.data.revision, updatedBy: parsed.data.updatedBy, updatedAtMs: parsed.data.updatedAtMs }) : null);
42
+ } catch {
43
+ // A hub outage must never grant permission to change the operator's checkout.
44
+ return gitPolicy(null);
45
+ }
46
+ }
47
+
48
+ export const GIT_POLICY_CACHE_MS = 60_000;
49
+ const guardConfig = z.strictObject({ project: z.string().min(1), checkout: z.string().min(1) });
50
+ const cacheSchema = z.strictObject({ project: z.string(), fetchedAtMs: z.number().int(), policy: policyEnvelope });
51
+ const marker = "# Trantor managed git landing guard";
52
+ const modulePath = fileURLToPath(import.meta.url);
53
+ const shellQuote = value => "'" + value.replaceAll("'", "'\"'\"'") + "'";
54
+ const runGit = (repo, args) => execFileSync("git", ["-C", repo, ...args], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
55
+ const commonDir = repo => runGit(repo, ["rev-parse", "--path-format=absolute", "--git-common-dir"]);
56
+ const rootDir = repo => realpathSync(runGit(repo, ["rev-parse", "--show-toplevel"]));
57
+ const isSeat = repo => worktreeProject(repo) && runGit(repo, ["rev-parse", "--abbrev-ref", "HEAD"]).startsWith("seat/");
58
+ const configPath = repo => join(commonDir(repo), "trantor-git-guard.json");
59
+ const cachePath = repo => join(commonDir(repo), "trantor-git-policy.json");
60
+
61
+ function readGuard(repo) {
62
+ try { return guardConfig.parse(JSON.parse(readFileSync(configPath(repo), "utf8"))); }
63
+ catch { return null; }
64
+ }
65
+
66
+ function atomicJson(path, value) {
67
+ const temp = `${path}.${process.pid}.tmp`;
68
+ writeFileSync(temp, JSON.stringify(value) + "\n", { mode: 0o600 });
69
+ renameSync(temp, path);
70
+ }
71
+
72
+ function operatorCheckout(repo) {
73
+ const config = readGuard(repo);
74
+ const root = rootDir(repo);
75
+ const common = commonDir(repo);
76
+ for (const candidate of new Set([root, config?.checkout, dirname(common)])) {
77
+ if (!candidate) continue;
78
+ try {
79
+ const marker = z.object({ operatorCheckout: z.string().min(1) }).parse(
80
+ JSON.parse(readFileSync(join(candidate, PROJECT_MARKER), "utf8")));
81
+ if (!isAbsolute(marker.operatorCheckout)) continue;
82
+ const checkout = realpathSync(marker.operatorCheckout);
83
+ if (commonDir(checkout) === common) return checkout;
84
+ } catch { /* Missing registration leaves the reference hook off. */ }
85
+ }
86
+ return null;
87
+ }
88
+
89
+ export function checkoutRole(repo) {
90
+ const root = rootDir(repo);
91
+ const checkout = operatorCheckout(repo);
92
+ if (checkout === root) return "operator";
93
+ if (isSeat(root)) return "seat";
94
+ return checkout ? "integration" : "unknown";
95
+ }
96
+
97
+ export function cacheGitPolicy(repo, project, policy, now = Date.now()) {
98
+ atomicJson(cachePath(repo), { project, policy: gitPolicy(policy), fetchedAtMs: now });
99
+ }
100
+
101
+ export function cachedGitPolicy(repo, now = Date.now()) {
102
+ try {
103
+ const config = readGuard(repo);
104
+ const cached = cacheSchema.parse(JSON.parse(readFileSync(cachePath(repo), "utf8")));
105
+ if (!config || cached.project !== config.project || cached.fetchedAtMs > now || now - cached.fetchedAtMs > GIT_POLICY_CACHE_MS) return gitPolicy(null);
106
+ return gitPolicy(cached.policy);
107
+ } catch {
108
+ return gitPolicy(null);
109
+ }
110
+ }
111
+
112
+ export function installGitGuard(repo, project) {
113
+ const checkout = rootDir(repo);
114
+ if (isSeat(checkout)) throw new Error("Install the git guard in the operator's checkout, not a seat worktree");
115
+ const existing = readGuard(repo);
116
+ if (existing && existing.checkout !== checkout) throw new Error("Git guard already belongs to another operator checkout");
117
+ const version = /git version (\d+)\.(\d+)/.exec(runGit(repo, ["--version"]));
118
+ if (!version || Number(version[1]) < 2 || (Number(version[1]) === 2 && Number(version[2]) < 28)) {
119
+ throw new Error("Git landing guard requires Git 2.28 or newer");
120
+ }
121
+ const common = commonDir(repo);
122
+ const hook = resolve(repo, runGit(repo, ["rev-parse", "--git-path", "hooks/reference-transaction"]));
123
+ if (!hook.startsWith(common + sep) && !hook.startsWith(checkout + sep)) {
124
+ throw new Error("Git guard cannot replace a shared external core.hooksPath");
125
+ }
126
+ mkdirSync(dirname(hook), { recursive: true });
127
+ const previous = existsSync(hook) ? readFileSync(hook, "utf8") : "";
128
+ const backup = `${hook}.trantor-original`;
129
+ if (previous && !previous.includes(marker)) {
130
+ if (existsSync(backup)) throw new Error("Git guard hook backup already exists; preserve it before reinstalling");
131
+ renameSync(hook, backup);
132
+ }
133
+ atomicJson(configPath(repo), { project, checkout });
134
+ const script = `#!/bin/sh\n${marker}\nif [ "$1" = prepared ] && [ -n "\${TRANTOR_AGENT_IDENTITY:-}\${RELAY_SESSION:-}" ]; then\n ${shellQuote(process.execPath)} ${shellQuote(modulePath)} hook "$1" || exit $?\nfi\nif [ -x ${shellQuote(backup)} ]; then exec ${shellQuote(backup)} "$@"; fi\n`;
135
+ const temp = `${hook}.${process.pid}.tmp`;
136
+ writeFileSync(temp, script, { mode: 0o755 });
137
+ renameSync(temp, hook);
138
+ return { checkout, hook };
139
+ }
140
+
141
+ export function refreshLocalGitPolicy(project, policy, repo = checkoutFor(project)) {
142
+ if (!repo) return;
143
+ installGitGuard(repo, project);
144
+ cacheGitPolicy(repo, project, policy);
145
+ }
146
+
147
+ export function landingVerdict(policy, { action = "land", review = null, tip = null } = {}) {
148
+ const current = gitPolicy(policy);
149
+ const rule = current.effective[action];
150
+ const label = current.mode[0].toUpperCase() + current.mode.slice(1);
151
+ if (rule === "click") return { allowed: false, reason: `${label} mode: land from the sidebar (${action})` };
152
+ if (rule === "review" && !(review?.reviewed && review.merge && tip && review.tip === tip)) {
153
+ return { allowed: false, reason: `${label} mode: ${action} requires every hunk approved at the current tip` };
154
+ }
155
+ return { allowed: true };
156
+ }
157
+
158
+ export function referenceVerdict(repo, phase, env = process.env) {
159
+ if (phase !== "prepared" || !(env.TRANTOR_AGENT_IDENTITY || env.RELAY_SESSION)) return { allowed: true };
160
+ if (checkoutRole(repo) !== "operator") return { allowed: true };
161
+ const policy = cachedGitPolicy(repo);
162
+ if (policy.effective.land === "click") return landingVerdict(policy);
163
+ return { allowed: true };
164
+ }
165
+
166
+ async function main() {
167
+ const [command, phase] = process.argv.slice(2);
168
+ const repo = process.cwd();
169
+ if (command === "hook") {
170
+ const result = referenceVerdict(repo, phase);
171
+ if (!result.allowed) { console.error(result.reason); process.exitCode = 1; }
172
+ } else if (command === "refresh") {
173
+ const project = resolveProject(repo);
174
+ const policy = await readGitPolicy({ hub: resolveHub(project), project, identity: ownerIdentity() });
175
+ refreshLocalGitPolicy(project, policy, repo);
176
+ console.log(JSON.stringify(policy));
177
+ } else throw new Error("usage: node lib/git-guard.mjs refresh");
178
+ }
179
+ if (process.argv[1] && resolve(process.argv[1]) === modulePath) {
180
+ await main().catch(error => { console.error(error.message); process.exitCode = 1; });
181
+ }
package/lib/integrate.mjs CHANGED
@@ -4,6 +4,7 @@ import { execFileSync } from "node:child_process";
4
4
  import { existsSync, readdirSync } from "node:fs";
5
5
  import { join } from "node:path";
6
6
  import { homedir } from "node:os";
7
+ import { cachedGitPolicy, checkoutRole, landingVerdict } from "./git-guard.mjs";
7
8
 
8
9
  const busDir = () => process.env.AGENT_BUS_DIR || join(homedir(), ".agent-bus");
9
10
 
@@ -53,10 +54,17 @@ export function seatAhead(w, base = "main") {
53
54
 
54
55
  /** Merge one seat's branch into the current checkout. A conflict is the collision the overseer exists
55
56
  * to surface, so the merge is aborted and reported rather than left half-done. */
56
- export function mergeSeat(repo, branch) {
57
+ export function mergeSeat(repo, branch, { policy = cachedGitPolicy(repo), review = null, action = "land" } = {}) {
58
+ const tip = git(repo, ["rev-parse", `${branch}^{commit}`]);
59
+ const role = checkoutRole(repo);
60
+ if (role !== "seat" && role !== "integration") {
61
+ const land = landingVerdict(policy, { review, tip });
62
+ const gate = land.allowed ? landingVerdict(policy, { action, review, tip }) : land;
63
+ if (!gate.allowed) return { branch, merged: false, conflict: false, refused: true, detail: gate.reason };
64
+ }
57
65
  const before = git(repo, ["rev-parse", "HEAD"]);
58
66
  try {
59
- git(repo, ["merge", "--no-edit", branch]);
67
+ git(repo, ["merge", "--no-edit", tip]);
60
68
  const after = git(repo, ["rev-parse", "HEAD"]);
61
69
  return { branch, merged: before !== after, conflict: false };
62
70
  } catch (e) {
@@ -238,6 +238,11 @@ CREATE TABLE IF NOT EXISTS dispatcher_cards (
238
238
  ready_since_ms BIGINT, row JSONB NOT NULL,
239
239
  PRIMARY KEY(org_id,project,card)
240
240
  );
241
+ CREATE TABLE IF NOT EXISTS dispatcher_board_revisions (
242
+ org_id TEXT NOT NULL, project TEXT NOT NULL, card BIGINT NOT NULL,
243
+ revision BIGINT NOT NULL, content_hash TEXT NOT NULL,
244
+ PRIMARY KEY(org_id,project,card)
245
+ );
241
246
  CREATE TABLE IF NOT EXISTS dispatcher_integration_migrations (
242
247
  id TEXT PRIMARY KEY, completed_at_ms BIGINT NOT NULL
243
248
  );
@@ -250,7 +255,8 @@ BEGIN
250
255
  IF current_setting('trantor.dispatcher_card_write',true) = 'on' THEN
251
256
  IF TG_OP='DELETE' THEN RETURN OLD; ELSE RETURN NEW; END IF;
252
257
  END IF;
253
- IF EXISTS(SELECT 1 FROM dispatcher_cards WHERE org_id=organization AND card=card_id) THEN
258
+ IF EXISTS(SELECT 1 FROM dispatcher_cards WHERE org_id=organization AND card=card_id
259
+ AND row->>'depsBasis' IS DISTINCT FROM 'board') THEN
254
260
  IF TG_OP='DELETE' OR NEW IS DISTINCT FROM OLD THEN
255
261
  RAISE EXCEPTION 'managed card requires dispatcher transaction' USING ERRCODE='40001';
256
262
  END IF;
package/mcp.mjs CHANGED
@@ -9,7 +9,7 @@ import { homedir, hostname } from "node:os";
9
9
  import { execSync, spawnSync } from "node:child_process";
10
10
  import { randomUUID } from "node:crypto";
11
11
  import { advise, loadWorld } from "./bin/advise.mjs";
12
- import { buildAdviceRequest, dispatchDecision, packagesToDrafts, parseCards, preflight, readCachedAdvice, readCapacity, requestAdvice } from "./lib/dispatcher/preflight.mjs";
12
+ import { adviseCards, buildAdviceRequest, dispatchDecision, packagesToDrafts, parseCards, preflight, readCachedAdvice, readCapacity, requestAdvice } from "./lib/dispatcher/preflight.mjs";
13
13
  import { loadRegistry } from "./lib/canary/registry.mjs";
14
14
  import { loadSeatRecord } from "./lib/seat-record.mjs";
15
15
  import { resolveProject, hostId, resolveHubInfo, nonSeatReason, handoffDir, orchWriterSid, busDir } from "./lib/project.mjs";
@@ -330,17 +330,16 @@ server.tool("relay_project_brief", "Set a one-paragraph project brief shown on t
330
330
  const dispatcherCards = z.array(z.record(z.string(), z.any()));
331
331
  const hubPost = (path, body) => signedPost(path, body, { session: SESSION, instance: INSTANCE_ID, project: PROJECT, timeoutMs: 10000 });
332
332
  const hubGet = (path) => signedGet(path, { session: SESSION, instance: INSTANCE_ID, project: PROJECT, timeoutMs: 5000 });
333
- server.tool("relay_advise", "Ask how to execute work before spending tokens. With cards (dispatcher work cards) it returns the hub planner's decision, the same one `trantor advise --json` gives; with the old task+packages shape it returns the legacy recommendation plus the hub's draft decision. Present the summary to the user before starting.",
333
+ server.tool("relay_advise", "Ask how to execute work before spending tokens. With cards (card numbers) it fetches each card's current WorkCard from the hub and returns the hub planner's decision, the same one `trantor advise --json` gives; with the old task+packages shape it returns the legacy recommendation plus the hub's draft decision. Present the summary to the user before starting.",
334
334
  { task: z.string().optional(),
335
335
  packages: z.array(z.object({ title: z.string(), difficulty: z.enum(["easy","medium","hard"]).optional(), kind: z.string().optional() })).optional(),
336
336
  horizon: z.enum(["short","medium","long"]).optional(),
337
- cards: dispatcherCards.optional().describe("work cards to plan (dispatchable)"),
337
+ cards: z.array(z.union([z.number().int().positive(), z.record(z.string(), z.any())])).optional().describe("card numbers to plan (dispatchable); the hub's current WorkCard is fetched for each"),
338
338
  drafts: dispatcherCards.optional().describe("unsaved cards with client-local ids (advice only)"),
339
339
  snapshotId: z.string().optional(), policyVersion: z.string().optional() },
340
340
  async ({ task, packages, horizon, cards, drafts, snapshotId, policyVersion }) => {
341
341
  if (cards || drafts) {
342
- const request = await buildAdviceRequest({ project: PROJECT, cards: cards || [], drafts: drafts || [], snapshotId, policyVersion });
343
- const result = await requestAdvice({ post: hubPost, busDir: busDir(), request });
342
+ const result = await adviseCards({ get: hubGet, post: hubPost, busDir: busDir(), project: PROJECT, cards: cards || [], drafts: drafts || [], snapshotId, policyVersion });
344
343
  return { content: [{ type: "text", text: JSON.stringify(result, null, 2) }], isError: result.source === "refused" };
345
344
  }
346
345
  // #7762: the advisor reads THIS project's seat record (derived, fail-open) so a seat whose
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "trantor",
3
- "version": "0.18.149",
3
+ "version": "0.18.152",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "trantor": "bin/cli.mjs"
@@ -60,7 +60,7 @@
60
60
  "node": ">=18"
61
61
  },
62
62
  "devDependencies": {
63
- "@oxlint/plugins": "^1.79.0",
64
- "oxlint": "^1.79.0"
63
+ "@oxlint/plugins": "1.79.0",
64
+ "oxlint": "1.79.0"
65
65
  }
66
66
  }