agent-lyceum 0.41.0 → 0.42.0

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.
@@ -7,7 +7,7 @@ export declare function buildClaudeSettings(project: ResolvedProject, agent: Res
7
7
  policy: WritePolicy;
8
8
  cwd: string;
9
9
  }): Record<string, unknown>;
10
- export declare function buildClaudeInvocation(input: WakeInput): Invocation;
10
+ export declare function buildClaudeInvocation(raw: WakeInput): Invocation;
11
11
  /**
12
12
  * The text the rules read: the result message (only when it is an error message: pass `result` for an `is_error` run), stderr, and the HTTP status
13
13
  * the CLI reports as `api_error_status`. With no `result` and no result in stdout, stdout itself, but only when it is plain text: structured
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { repoDirFor, scratchCwd, writePolicy } from "../policy.js";
4
4
  import { canonicalPath } from "../paths.js";
5
+ import { applyShipToWake } from "../ship-wire.js";
5
6
  /** Claude Code path rules: `//abs/path` — a leading "/" plus the absolute path. */
6
7
  const rule = (tool, p) => `${tool}(/${p})`;
7
8
  function denyRules(p) {
@@ -59,7 +60,8 @@ export function buildClaudeSettings(project, agent, override) {
59
60
  },
60
61
  };
61
62
  }
62
- export function buildClaudeInvocation(input) {
63
+ export function buildClaudeInvocation(raw) {
64
+ const { input, ship } = applyShipToWake(raw);
63
65
  const { project, agent, workDir } = input;
64
66
  fs.mkdirSync(workDir, { recursive: true });
65
67
  const settingsFile = path.join(workDir, "claude-settings.json");
@@ -72,6 +74,9 @@ export function buildClaudeInvocation(input) {
72
74
  fs.writeFileSync(systemFile, input.systemPrompt);
73
75
  const pol = input.policy ?? writePolicy(project, agent);
74
76
  const addDirs = [...pol.allowDirs, ...pol.readDirs, ...pol.allowFiles.map((f) => path.dirname(f))].filter((d) => !(d === repo || d.startsWith(repo + path.sep)));
77
+ // So Bash can read the ship session file under the run's agent workDir.
78
+ if (ship)
79
+ addDirs.push(workDir);
75
80
  const args = [
76
81
  "-p",
77
82
  "--output-format",
@@ -3,7 +3,7 @@ import type { Invocation, WakeInput } from "./types.js";
3
3
  export declare function codexWritableRoots(input: WakeInput): string[];
4
4
  /** Sum `output_tokens` over `turn.completed` events in `codex exec --json` output. */
5
5
  export declare function codexOutputTokens(jsonl: string): number | undefined;
6
- export declare function buildCodexInvocation(input: WakeInput): Invocation;
6
+ export declare function buildCodexInvocation(raw: WakeInput): Invocation;
7
7
  export declare function classifyCodexError(out: {
8
8
  code: number | null;
9
9
  stdout: string;
@@ -1,6 +1,7 @@
1
1
  import fs from "node:fs";
2
2
  import path from "node:path";
3
3
  import { projectCommonDir, projectCommonDirAllowed, repoDirFor, scratchCwd, writePolicy } from "../policy.js";
4
+ import { applyShipToWake } from "../ship-wire.js";
4
5
  export function codexWritableRoots(input) {
5
6
  const pol = input.policy ?? writePolicy(input.project, input.agent);
6
7
  const work = input.policy ? scratchCwd(input.workDir) : repoDirFor(input.project, input.agent.name);
@@ -53,13 +54,15 @@ export function codexOutputTokens(jsonl) {
53
54
  }
54
55
  /** Codex has one `web_search` setting: `cached` answers from an index, `live` browses. */
55
56
  const CODEX_WEB_SEARCH = { none: "disabled", search: "cached", fetch: "live" };
56
- export function buildCodexInvocation(input) {
57
+ export function buildCodexInvocation(raw) {
58
+ const { input } = applyShipToWake(raw);
57
59
  const { project, agent, workDir } = input;
58
60
  const repo = input.policy ? scratchCwd(workDir) : repoDirFor(project, agent.name);
59
61
  fs.mkdirSync(workDir, { recursive: true });
60
62
  if (input.policy)
61
63
  fs.mkdirSync(repo, { recursive: true });
62
64
  const lastFile = path.join(workDir, "codex-last-message.txt");
65
+ // Do not add workDir to writable_roots: the ship session must not become agent-writable.
63
66
  const roots = codexWritableRoots(input);
64
67
  const common = [
65
68
  "-c",
package/dist/cli.js CHANGED
@@ -19,7 +19,7 @@ import { exitCodeForOutcome, RUNTIMES } from "./schema.js";
19
19
  import { absPath, assertName, NAME_RE, projectPaths, resolveHome } from "./paths.js";
20
20
  import { addProject, initHome, removeProject } from "./scaffold.js";
21
21
  import { buildStatusReport, buildTaskListReport, formatMonitor, formatRunDetail, formatStatusWithLog, formatTaskList, latestUnfinishedRun, listRuns, reopenCandidates, runIsAlive } from "./status.js";
22
- import { prepareTask, readTaskFile, taskMessageBody } from "./task.js";
22
+ import { lintTaskContent, prepareTask, readTaskFile, taskMessageBody } from "./task.js";
23
23
  import { callAgent, callProject, callsDir, resolveCallAgent } from "./call.js";
24
24
  import { formatEnforcement, validateProject } from "./validate.js";
25
25
  import { must } from "./assert.js";
@@ -307,6 +307,9 @@ program
307
307
  const prepared = prepareTask({ text: task, file: opts.taskFile, cwd: process.cwd(), runDir });
308
308
  console.log(`Project ${pr.name} — repo ${pr.dir}${opts.agent ? ` — solo: ${opts.agent}` : ""}`);
309
309
  console.log(`Task: ${prepared.source === "file" ? `file ${prepared.sourcePath}` : "text"} (${prepared.bytes} bytes${prepared.inline ? "" : ", passed by reference"})`);
310
+ if (prepared.source === "file")
311
+ for (const w of lintTaskContent(prepared.content))
312
+ console.error(`warning: task file ${w}`);
310
313
  const name = opts.name ?? uniqueName(slugify(taskMessageBody(prepared).subject), taken);
311
314
  summary = await runTeam({ project: pr, name, plan, task: prepared, runDir, soloAgent: opts.agent, signal: cancel.signal });
312
315
  }
@@ -566,7 +569,8 @@ program
566
569
  let taskError;
567
570
  if (opts.taskFile) {
568
571
  try {
569
- readTaskFile(absPath(opts.taskFile, process.cwd()));
572
+ for (const w of lintTaskContent(readTaskFile(absPath(opts.taskFile, process.cwd()))))
573
+ report.checks.push({ level: "warn", subject: "task", message: `task file ${w}` });
570
574
  }
571
575
  catch (e) {
572
576
  taskError = e.message;
@@ -979,6 +983,21 @@ program
979
983
  fail(e.message);
980
984
  }
981
985
  });
986
+ program
987
+ .command("ship")
988
+ .description("Apply search/replace edits with verify+rollback (Claude Code and Codex; session from the wake)")
989
+ .requiredOption("--session <file>", "ship-session.json written for this wake")
990
+ .option("--edits <file>", "edits JSON file (default: stdin)")
991
+ .action(async (opts) => {
992
+ try {
993
+ const { runShipCli } = await import("./ship-cli.js");
994
+ const code = await runShipCli({ session: opts.session, editsFile: opts.edits });
995
+ process.exitCode = code;
996
+ }
997
+ catch (e) {
998
+ fail(e.message);
999
+ }
1000
+ });
982
1001
  // `--help` lists the commands in three layers.
983
1002
  const HELP_LAYERS = {
984
1003
  "Project:": ["init", "project"],
package/dist/config.d.ts CHANGED
@@ -53,6 +53,11 @@ export interface ResolvedAgent {
53
53
  global?: string;
54
54
  project?: string;
55
55
  };
56
+ /** Opt-in ship CLI on Claude Code and Codex wakes; absent = off. */
57
+ ship?: {
58
+ verify?: string;
59
+ timeoutSec?: number;
60
+ };
56
61
  }
57
62
  export interface ResolvedProject {
58
63
  home: string;
@@ -118,6 +123,10 @@ export declare function loadGlobal(home: string): {
118
123
  local_binding?: boolean | undefined;
119
124
  unix_sockets?: string[] | undefined;
120
125
  } | undefined;
126
+ ship?: boolean | {
127
+ verify?: string | undefined;
128
+ timeout_sec?: number | undefined;
129
+ } | undefined;
121
130
  owns?: unknown;
122
131
  }>;
123
132
  };
@@ -180,6 +189,10 @@ export declare function loadProjectRaw(home: string, name: string): {
180
189
  local_binding?: boolean | undefined;
181
190
  unix_sockets?: string[] | undefined;
182
191
  } | undefined;
192
+ ship?: boolean | {
193
+ verify?: string | undefined;
194
+ timeout_sec?: number | undefined;
195
+ } | undefined;
183
196
  owns?: unknown;
184
197
  }>;
185
198
  };
package/dist/config.js CHANGED
@@ -169,6 +169,20 @@ export function resolveProjectFrom(home, name, g, p) {
169
169
  const canAsk = pick("can_ask_user");
170
170
  const allowWeb = pick("allow_web");
171
171
  const sandbox = resolveSandbox(agentName, pick("sandbox"));
172
+ const shipRaw = pick("ship");
173
+ const ship = shipRaw === true
174
+ ? {}
175
+ : shipRaw && typeof shipRaw === "object"
176
+ ? {
177
+ ...(shipRaw.verify ? { verify: shipRaw.verify } : {}),
178
+ ...(shipRaw.timeout_sec !== undefined ? { timeoutSec: shipRaw.timeout_sec } : {}),
179
+ }
180
+ : undefined;
181
+ if (!ship)
182
+ delete sources.ship;
183
+ // `ship: false` is explicit off (same as unset for resolution): `pick` recorded a source but no
184
+ // `ship` value is flattened, so drop it to keep "sources ⊆ values". Do not invent a `sources.ship`
185
+ // default when unset: doctor --resolved fixtures and "sources ⊆ values" assume absent optional keys stay absent.
172
186
  for (const [k, v] of [
173
187
  ["resume", resume],
174
188
  ["can_message", canMessage],
@@ -191,6 +205,7 @@ export function resolveProjectFrom(home, name, g, p) {
191
205
  canAskUser: canAsk ?? isLead,
192
206
  allowWeb,
193
207
  ...(sandbox ? { sandbox } : {}),
208
+ ...(ship ? { ship } : {}),
194
209
  fallback,
195
210
  fallbackShared,
196
211
  fallbackInvalid,
@@ -283,7 +298,7 @@ export function findProjectForCwd(home, cwd) {
283
298
  }
284
299
  return best?.name;
285
300
  }
286
- const AGENT_FIELDS = ["runtime", "model", "effort", "agent_md", "memory.global", "memory.project", "resume", "can_message", "can_edit_agent_md", "can_ask_user", "allow_web", "fallback", "sandbox"];
301
+ const AGENT_FIELDS = ["runtime", "model", "effort", "agent_md", "memory.global", "memory.project", "resume", "can_message", "can_edit_agent_md", "can_ask_user", "allow_web", "fallback", "sandbox", "ship"];
287
302
  /** Claude pattern metacharacters and control characters: refused in sandbox paths instead of escaped (spec 25.4.1). */
288
303
  const PATH_CHARS = /[*?[\]{}()!\\]/;
289
304
  const PATH_META = { test: (p) => PATH_CHARS.test(p) || [...p].some((c) => c.charCodeAt(0) < 32 || c.charCodeAt(0) === 127) };
@@ -400,6 +415,8 @@ export function flattenResolved(project) {
400
415
  v[`${p}.can_edit_agent_md`] = a.canEditAgentMd;
401
416
  v[`${p}.can_ask_user`] = a.canAskUser;
402
417
  v[`${p}.allow_web`] = a.allowWeb;
418
+ if (a.ship)
419
+ v[`${p}.ship`] = a.ship;
403
420
  if (a.fallback.length)
404
421
  v[`${p}.fallback`] = a.fallback;
405
422
  if (a.sandbox)
package/dist/doctor.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import type { ResolvedProject } from "./config.js";
2
2
  import type { Runtime } from "./schema.js";
3
+ /** A ready-to-paste `verify:` block built from the project's package.json scripts; undefined when there is nothing to suggest. Never throws. */
4
+ export declare function suggestVerify(dir: string): string | undefined;
3
5
  export type Cap = "yes" | "no" | "unknown";
4
6
  export interface RuntimeCapabilities {
5
7
  runtime: Runtime;
package/dist/doctor.js CHANGED
@@ -9,6 +9,25 @@ import { runInvocation } from "./process-runner.js";
9
9
  import { validateProject } from "./validate.js";
10
10
  import { diagnoseInstances } from "./doctor-instances.js";
11
11
  import { dirtyPaths, git, isolationBlocker } from "./worktree.js";
12
+ /** A ready-to-paste `verify:` block built from the project's package.json scripts; undefined when there is nothing to suggest. Never throws. */
13
+ export function suggestVerify(dir) {
14
+ let scripts;
15
+ try {
16
+ const pkg = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8"));
17
+ if (!pkg || typeof pkg.scripts !== "object" || pkg.scripts === null || Array.isArray(pkg.scripts))
18
+ return undefined;
19
+ scripts = pkg.scripts;
20
+ }
21
+ catch {
22
+ return undefined;
23
+ }
24
+ const lines = ["typecheck", "lint", "test"]
25
+ .filter((n) => typeof scripts[n] === "string")
26
+ .map((n) => ` - { name: ${n}, run: "${n === "test" ? "npm test" : `npm run ${n}`}" }`);
27
+ if (!lines.length)
28
+ return undefined;
29
+ return `\`verify\` is not set, so a lead's \`done\` is not checked. To check it, add to project.yaml:\n verify:\n commands:\n${lines.map((l) => ` ${l}`).join("\n")}\nSee docs/configuration.md#verify. These commands run outside the sandbox.`;
30
+ }
12
31
  const BINARY = { "claude-code": "claude", codex: "codex" };
13
32
  /** Run a read-only CLI query (`--version`, `--help`): bounded in time and output, never an agent task. */
14
33
  async function query(cmd, args, opts) {
@@ -166,6 +185,11 @@ export async function diagnoseProject(project, opts = {}) {
166
185
  message: `Before it accepts a lead's \`completed\` done, the dispatcher runs ${project.verify.commands.length} verify command(s), up to ${project.verify.max_rejections} rejection(s): ${cmds}. They run OUTSIDE the agents' sandbox with your permissions and execute code the agents wrote, in the lead's worktree, or directly in ${project.dir} when runs do not use worktrees. Only you can change them (project.yaml).`,
167
186
  });
168
187
  }
188
+ else {
189
+ const suggestion = suggestVerify(project.dir);
190
+ if (suggestion)
191
+ checks.push({ level: "info", subject: "verify", message: suggestion });
192
+ }
169
193
  for (const lock of listRunLocks(project.paths.root)) {
170
194
  const alive = lockHolderAlive(lock);
171
195
  checks.push({
package/dist/schema.d.ts CHANGED
@@ -45,6 +45,12 @@ export declare const SandboxPartial: z.ZodObject<{
45
45
  unix_sockets: z.ZodOptional<z.ZodArray<z.ZodString>>;
46
46
  }, z.core.$strict>;
47
47
  export type SandboxPartialT = z.infer<typeof SandboxPartial>;
48
+ /** Per-agent ship tool (search/replace + verify + rollback). `true` = on with defaults; object may set verify. */
49
+ export declare const ShipPartial: z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
50
+ verify: z.ZodOptional<z.ZodString>;
51
+ timeout_sec: z.ZodOptional<z.ZodNumber>;
52
+ }, z.core.$strict>]>;
53
+ export type ShipPartialT = z.infer<typeof ShipPartial>;
48
54
  export declare const AgentPartial: z.ZodObject<{
49
55
  runtime: z.ZodOptional<z.ZodEnum<{
50
56
  "claude-code": "claude-code";
@@ -94,6 +100,10 @@ export declare const AgentPartial: z.ZodObject<{
94
100
  local_binding: z.ZodOptional<z.ZodBoolean>;
95
101
  unix_sockets: z.ZodOptional<z.ZodArray<z.ZodString>>;
96
102
  }, z.core.$strict>>;
103
+ ship: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
104
+ verify: z.ZodOptional<z.ZodString>;
105
+ timeout_sec: z.ZodOptional<z.ZodNumber>;
106
+ }, z.core.$strict>]>>;
97
107
  owns: z.ZodOptional<z.ZodUnknown>;
98
108
  }, z.core.$strict>;
99
109
  export type AgentPartialT = z.infer<typeof AgentPartial>;
@@ -188,6 +198,10 @@ export declare const GlobalConfig: z.ZodObject<{
188
198
  local_binding: z.ZodOptional<z.ZodBoolean>;
189
199
  unix_sockets: z.ZodOptional<z.ZodArray<z.ZodString>>;
190
200
  }, z.core.$strict>>;
201
+ ship: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
202
+ verify: z.ZodOptional<z.ZodString>;
203
+ timeout_sec: z.ZodOptional<z.ZodNumber>;
204
+ }, z.core.$strict>]>>;
191
205
  owns: z.ZodOptional<z.ZodUnknown>;
192
206
  }, z.core.$strict>>>;
193
207
  }, z.core.$strict>;
@@ -310,6 +324,10 @@ export declare const ProjectConfig: z.ZodObject<{
310
324
  local_binding: z.ZodOptional<z.ZodBoolean>;
311
325
  unix_sockets: z.ZodOptional<z.ZodArray<z.ZodString>>;
312
326
  }, z.core.$strict>>;
327
+ ship: z.ZodOptional<z.ZodUnion<readonly [z.ZodBoolean, z.ZodObject<{
328
+ verify: z.ZodOptional<z.ZodString>;
329
+ timeout_sec: z.ZodOptional<z.ZodNumber>;
330
+ }, z.core.$strict>]>>;
313
331
  owns: z.ZodOptional<z.ZodUnknown>;
314
332
  }, z.core.$strict>>>;
315
333
  }, z.core.$strict>;
package/dist/schema.js CHANGED
@@ -48,6 +48,16 @@ export const SandboxPartial = z
48
48
  unix_sockets: z.array(z.string().trim().min(1)).optional(),
49
49
  })
50
50
  .strict();
51
+ /** Per-agent ship tool (search/replace + verify + rollback). `true` = on with defaults; object may set verify. */
52
+ export const ShipPartial = z.union([
53
+ z.boolean(),
54
+ z
55
+ .object({
56
+ verify: z.string().min(1).optional(),
57
+ timeout_sec: z.number().int().min(1).max(7200).optional(),
58
+ })
59
+ .strict(),
60
+ ]);
51
61
  export const AgentPartial = z
52
62
  .object({
53
63
  runtime: z.enum(RUNTIMES).optional(),
@@ -62,6 +72,8 @@ export const AgentPartial = z
62
72
  allow_web: z.enum(WEB_LEVELS).optional(),
63
73
  fallback: z.array(FallbackEntryPartial).optional(),
64
74
  sandbox: SandboxPartial.optional(),
75
+ /** Opt-in: wake writes a ship session and documents the `agent-lyceum ship` CLI (Claude Code and Codex). */
76
+ ship: ShipPartial.optional(),
65
77
  /** Removed setting: still accepted (any value) so old files load; ignored, with a warning from `validate`. */
66
78
  owns: z.unknown().optional(),
67
79
  })
@@ -0,0 +1,12 @@
1
+ import { type ShipEdit } from "./ship.js";
2
+ export declare function parseShipEditsPayload(raw: unknown): ShipEdit[];
3
+ /** Read stdin fully as UTF-8. */
4
+ export declare function readStdinText(): Promise<string>;
5
+ /**
6
+ * CLI entry for both Claude Code and Codex: `agent-lyceum ship --session <file>` with edits JSON on stdin
7
+ * (or `--edits <file>`). Exit 0 only on SHIPPED_AND_VERIFIED.
8
+ */
9
+ export declare function runShipCli(opts: {
10
+ session: string;
11
+ editsFile?: string;
12
+ }): Promise<number>;
@@ -0,0 +1,84 @@
1
+ import fs from "node:fs";
2
+ import { runShip } from "./ship.js";
3
+ import { readShipSession } from "./ship-wire.js";
4
+ function isRecord(x) {
5
+ return typeof x === "object" && x !== null && !Array.isArray(x);
6
+ }
7
+ export function parseShipEditsPayload(raw) {
8
+ if (!isRecord(raw))
9
+ throw new Error("ship input must be a JSON object with edits");
10
+ const edits = raw.edits;
11
+ if (!Array.isArray(edits) || edits.length === 0)
12
+ throw new Error("edits must be a non-empty array");
13
+ const out = [];
14
+ for (let i = 0; i < edits.length; i++) {
15
+ const e = edits[i];
16
+ if (!isRecord(e))
17
+ throw new Error(`edits[${i}] must be an object`);
18
+ if (typeof e.path !== "string" || typeof e.search !== "string" || typeof e.replace !== "string") {
19
+ throw new Error(`edits[${i}] needs string path, search, replace`);
20
+ }
21
+ if ("verify" in e)
22
+ throw new Error("per-edit verify is not allowed; verify is fixed in the ship session");
23
+ if ("replace_all" in e && e.replace_all !== true && e.replace_all !== false) {
24
+ throw new Error(`edits[${i}].replace_all must be a boolean when set`);
25
+ }
26
+ out.push({
27
+ path: e.path,
28
+ search: e.search,
29
+ replace: e.replace,
30
+ ...(e.replace_all === true ? { replace_all: true } : {}),
31
+ });
32
+ }
33
+ if ("verify" in raw) {
34
+ throw new Error("verify in the request body is not allowed; it is fixed in the ship session");
35
+ }
36
+ return out;
37
+ }
38
+ /** Read stdin fully as UTF-8. */
39
+ export async function readStdinText() {
40
+ const chunks = [];
41
+ for await (const chunk of process.stdin)
42
+ chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
43
+ return Buffer.concat(chunks).toString("utf8");
44
+ }
45
+ /**
46
+ * CLI entry for both Claude Code and Codex: `agent-lyceum ship --session <file>` with edits JSON on stdin
47
+ * (or `--edits <file>`). Exit 0 only on SHIPPED_AND_VERIFIED.
48
+ */
49
+ export async function runShipCli(opts) {
50
+ const session = readShipSession(opts.session);
51
+ const text = opts.editsFile ? fs.readFileSync(opts.editsFile, "utf8") : await readStdinText();
52
+ if (!text.trim())
53
+ throw new Error("edits JSON is empty (pass on stdin or --edits)");
54
+ let raw;
55
+ try {
56
+ raw = JSON.parse(text);
57
+ }
58
+ catch (e) {
59
+ throw new Error(`edits JSON is invalid: ${e instanceof Error ? e.message : String(e)}`);
60
+ }
61
+ const edits = parseShipEditsPayload(raw);
62
+ // Interrupted ship must roll back: abort verify (kills its process group), then runShip restores the files.
63
+ const controller = new AbortController();
64
+ const onSignal = () => controller.abort();
65
+ const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
66
+ for (const sig of signals)
67
+ process.on(sig, onSignal);
68
+ let result;
69
+ try {
70
+ result = await runShip({
71
+ root: session.root,
72
+ edits,
73
+ commands: session.commands,
74
+ deny: session.deny,
75
+ signal: controller.signal,
76
+ });
77
+ }
78
+ finally {
79
+ for (const sig of signals)
80
+ process.off(sig, onSignal);
81
+ }
82
+ process.stdout.write(`${result.status}\n${result.summary}\nfiles: ${result.filesModified.join(", ") || "(none)"}\n`);
83
+ return result.status === "SHIPPED_AND_VERIFIED" ? 0 : 1;
84
+ }
@@ -0,0 +1,44 @@
1
+ import type { ResolvedAgent, ResolvedProject } from "./config.js";
2
+ import type { ShipCommand } from "./ship.js";
3
+ export interface ShipSession {
4
+ root: string;
5
+ commands: ShipCommand[];
6
+ deny: string[];
7
+ }
8
+ export interface ShipWakeInfo {
9
+ sessionPath: string;
10
+ /** Exact argv a runtime should run (node + cli + ship --session …). */
11
+ argv: string[];
12
+ /** One-line shell form for prompts. */
13
+ shellCommand: string;
14
+ /** Sum of the verify command timeouts: the longest one ship call can take. */
15
+ totalTimeoutSec: number;
16
+ }
17
+ /** True when the agent opted into ship (boolean true or an object). */
18
+ export declare function shipEnabled(agent: ResolvedAgent): boolean;
19
+ /**
20
+ * Verify chain for ship: agent.ship.verify (one command) → the whole project.verify.commands chain → none.
21
+ * An explicit agent.ship.timeoutSec overrides every command's timeout; unset keeps each command's own.
22
+ */
23
+ export declare function shipCommands(project: ResolvedProject, agent: ResolvedAgent): ShipCommand[];
24
+ export declare function shipTotalTimeoutSec(commands: ShipCommand[]): number;
25
+ /** How to re-enter this package's CLI (`ship` subcommand). Works for dist and tsx/dev. */
26
+ export declare function shipCliArgv(): string[];
27
+ export declare function shellQuote(s: string): string;
28
+ /**
29
+ * Write a per-wake ship session (root / commands / deny) for Claude Code and Codex.
30
+ * Returns undefined when ship is off or verify cannot be resolved.
31
+ */
32
+ export declare function writeShipSession(project: ResolvedProject, agent: ResolvedAgent, workDir: string): ShipWakeInfo | undefined;
33
+ export declare function readShipSession(file: string): ShipSession;
34
+ import type { WakeInput } from "./adapters/types.js";
35
+ /** Prompt block for both Claude Code and Codex (exact CLI; no MCP). */
36
+ export declare function formatShipPrompt(shellCommand: string, sessionPath: string, totalTimeoutSec: number): string;
37
+ /**
38
+ * For Claude Code and Codex wakes: write the session and append the exact CLI to the system prompt.
39
+ * Policy wakes (tidy, etc.) skip ship. Call from both adapters.
40
+ */
41
+ export declare function applyShipToWake(input: WakeInput): {
42
+ input: WakeInput;
43
+ ship?: ShipWakeInfo;
44
+ };
@@ -0,0 +1,134 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { repoDirFor, writePolicy } from "./policy.js";
5
+ const SHIP_DEFAULT_TIMEOUT_SEC = 120;
6
+ /** True when the agent opted into ship (boolean true or an object). */
7
+ export function shipEnabled(agent) {
8
+ return agent.ship !== undefined;
9
+ }
10
+ /**
11
+ * Verify chain for ship: agent.ship.verify (one command) → the whole project.verify.commands chain → none.
12
+ * An explicit agent.ship.timeoutSec overrides every command's timeout; unset keeps each command's own.
13
+ */
14
+ export function shipCommands(project, agent) {
15
+ const override = agent.ship?.timeoutSec;
16
+ const own = agent.ship?.verify?.trim();
17
+ if (own)
18
+ return [{ name: "verify", run: own, timeout_sec: override ?? SHIP_DEFAULT_TIMEOUT_SEC }];
19
+ return (project.verify?.commands ?? [])
20
+ .filter((c) => c.run.trim())
21
+ .map((c) => ({ name: c.name, run: c.run.trim(), timeout_sec: override ?? c.timeout_sec }));
22
+ }
23
+ export function shipTotalTimeoutSec(commands) {
24
+ return commands.reduce((n, c) => n + c.timeout_sec, 0);
25
+ }
26
+ /** How to re-enter this package's CLI (`ship` subcommand). Works for dist and tsx/dev. */
27
+ export function shipCliArgv() {
28
+ const cliJs = path.join(path.dirname(fileURLToPath(import.meta.url)), "cli.js");
29
+ if (fs.existsSync(cliJs))
30
+ return [process.execPath, cliJs];
31
+ const cli = process.argv[1];
32
+ if (cli)
33
+ return [process.execPath, ...process.execArgv, cli];
34
+ return [process.execPath, cliJs];
35
+ }
36
+ export function shellQuote(s) {
37
+ if (/^[A-Za-z0-9_./:@%+=,-]+$/.test(s))
38
+ return s;
39
+ return `'${s.replace(/'/g, `'\\''`)}'`;
40
+ }
41
+ /**
42
+ * Write a per-wake ship session (root / commands / deny) for Claude Code and Codex.
43
+ * Returns undefined when ship is off or verify cannot be resolved.
44
+ */
45
+ export function writeShipSession(project, agent, workDir) {
46
+ if (!shipEnabled(agent))
47
+ return undefined;
48
+ const commands = shipCommands(project, agent);
49
+ if (!commands.length)
50
+ return undefined;
51
+ const root = repoDirFor(project, agent.name);
52
+ const pol = writePolicy(project, agent);
53
+ const session = {
54
+ root,
55
+ commands,
56
+ deny: pol.deny,
57
+ };
58
+ fs.mkdirSync(workDir, { recursive: true });
59
+ const sessionPath = path.join(workDir, "ship-session.json");
60
+ fs.writeFileSync(sessionPath, `${JSON.stringify(session, null, 2)}\n`);
61
+ const argv = [...shipCliArgv(), "ship", "--session", sessionPath];
62
+ const shellCommand = argv.map(shellQuote).join(" ");
63
+ return { sessionPath, argv, shellCommand, totalTimeoutSec: shipTotalTimeoutSec(commands) };
64
+ }
65
+ export function readShipSession(file) {
66
+ const raw = JSON.parse(fs.readFileSync(file, "utf8"));
67
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
68
+ throw new Error("ship session must be a JSON object");
69
+ const o = raw;
70
+ if (typeof o.root !== "string" || !o.root.trim())
71
+ throw new Error("ship session.root is required");
72
+ if (!Array.isArray(o.deny) || o.deny.some((x) => typeof x !== "string"))
73
+ throw new Error("ship session.deny must be a string array");
74
+ return { root: o.root, commands: readCommands(o), deny: o.deny };
75
+ }
76
+ /** `commands` array, or the old single `verify` string (+ optional `timeoutSec`) as one command. */
77
+ function readCommands(o) {
78
+ if (o.commands !== undefined) {
79
+ if (!Array.isArray(o.commands) || o.commands.length === 0)
80
+ throw new Error("ship session.commands must be a non-empty array");
81
+ return o.commands.map((c, i) => {
82
+ const r = c;
83
+ if (!r || typeof r !== "object" || typeof r.name !== "string" || typeof r.run !== "string" || !r.run.trim()) {
84
+ throw new Error(`ship session.commands[${i}] needs string name and run`);
85
+ }
86
+ if (typeof r.timeout_sec !== "number" || !Number.isInteger(r.timeout_sec) || r.timeout_sec <= 0) {
87
+ throw new Error(`ship session.commands[${i}].timeout_sec must be a positive integer`);
88
+ }
89
+ return { name: r.name, run: r.run.trim(), timeout_sec: r.timeout_sec };
90
+ });
91
+ }
92
+ if (typeof o.verify !== "string" || !o.verify.trim())
93
+ throw new Error("ship session.commands is required");
94
+ const t = typeof o.timeoutSec === "number" && Number.isInteger(o.timeoutSec) && o.timeoutSec > 0 ? o.timeoutSec : SHIP_DEFAULT_TIMEOUT_SEC;
95
+ return [{ name: "verify", run: o.verify.trim(), timeout_sec: t }];
96
+ }
97
+ /** Prompt block for both Claude Code and Codex (exact CLI; no MCP). */
98
+ export function formatShipPrompt(shellCommand, sessionPath, totalTimeoutSec) {
99
+ return [
100
+ "## Ship (tested edits)",
101
+ "Use the agent-lyceum `ship` CLI (not a separate product) for multi-file or must-pass-tests edits: it applies search/replace, runs the fixed verify command from your session, and restores every file byte-for-byte if verify fails.",
102
+ "- Changing 2+ files, or any change that must pass a test or typecheck: run the command below once with every edit in the JSON on stdin.",
103
+ `- Verify can take up to ${totalTimeoutSec} seconds in total. Set your shell tool timeout above ${totalTimeoutSec} seconds for this command, or it may be killed mid-verify.`,
104
+ "- Do not pass a different verify command; it is fixed in the session file.",
105
+ "- If verify fails, fix the edit and ship again; do not leave a half-edited tree.",
106
+ "- For one small edit to a file you already have open, your normal edit tool is fine.",
107
+ "",
108
+ "Command (stdin = JSON object with `edits` only):",
109
+ "```",
110
+ `${shellCommand} <<'EOF'`,
111
+ `{"edits":[{"path":"relative/file.ts","search":"old","replace":"new"}]}`,
112
+ "EOF",
113
+ "```",
114
+ `Session file (do not edit): \`${sessionPath}\``,
115
+ ].join("\n");
116
+ }
117
+ /**
118
+ * For Claude Code and Codex wakes: write the session and append the exact CLI to the system prompt.
119
+ * Policy wakes (tidy, etc.) skip ship. Call from both adapters.
120
+ */
121
+ export function applyShipToWake(input) {
122
+ if (input.policy)
123
+ return { input };
124
+ const ship = writeShipSession(input.project, input.agent, input.workDir);
125
+ if (!ship)
126
+ return { input };
127
+ return {
128
+ ship,
129
+ input: {
130
+ ...input,
131
+ systemPrompt: `${input.systemPrompt}\n\n${formatShipPrompt(ship.shellCommand, ship.sessionPath, ship.totalTimeoutSec)}`,
132
+ },
133
+ };
134
+ }
package/dist/ship.d.ts ADDED
@@ -0,0 +1,62 @@
1
+ export interface ShipEdit {
2
+ path: string;
3
+ search: string;
4
+ replace: string;
5
+ replace_all?: boolean;
6
+ }
7
+ export type ShipStatus = "SHIPPED_AND_VERIFIED" | "ABORTED_BEFORE_WRITE" | "FAILED_AND_ROLLED_BACK" | "FAILED_ROLLBACK_PARTIAL";
8
+ export interface ShipResult {
9
+ status: ShipStatus;
10
+ summary: string;
11
+ filesModified: string[];
12
+ }
13
+ export interface ShipVerifyOutcome {
14
+ ok: boolean;
15
+ exit: number | null;
16
+ output: string;
17
+ /** The verify run was cancelled through the signal; its verdict is withheld and the edits are rolled back. */
18
+ cancelled?: boolean;
19
+ }
20
+ export type ShipVerifyRunner = (cmd: string, cwd: string, timeoutSec: number, signal?: AbortSignal) => Promise<ShipVerifyOutcome>;
21
+ export interface ShipCommand {
22
+ name: string;
23
+ run: string;
24
+ timeout_sec: number;
25
+ }
26
+ export interface RunShipArgs {
27
+ root: string;
28
+ edits: ShipEdit[];
29
+ /** Verify chain, run in order and fail-fast; every command must pass. */
30
+ commands: ShipCommand[];
31
+ /** Absolute paths (and their descendants) ship must not write. */
32
+ deny?: string[];
33
+ /** Injected for tests; default runs `sh -c` via `runCommand`. */
34
+ runVerify?: ShipVerifyRunner;
35
+ /** Aborts a running verify; ship then rolls every edit back. Process signal handlers belong to the CLI, not here. */
36
+ signal?: AbortSignal;
37
+ }
38
+ /** True when `abs` equals or sits under a deny entry (canonical comparison). */
39
+ export declare function isDeniedPath(abs: string, deny: string[] | undefined): boolean;
40
+ /** Resolve `rel` under `root`; reject escapes, leaf symlinks, and deny-list hits. */
41
+ export declare function resolveUnderRoot(root: string, rel: string, deny?: string[]): {
42
+ ok: true;
43
+ abs: string;
44
+ rel: string;
45
+ } | {
46
+ ok: false;
47
+ reason: string;
48
+ };
49
+ /** Exact search/replace; ambiguous without `replace_all` is a miss. */
50
+ export declare function applyExactEdit(text: string, search: string, replace: string, replaceAll?: boolean): {
51
+ ok: true;
52
+ text: string;
53
+ count: number;
54
+ } | {
55
+ ok: false;
56
+ message: string;
57
+ };
58
+ /**
59
+ * Apply multi-file exact edits under `root`, run verify, roll back on failure.
60
+ * Pure relative to injected `runVerify` (tests); production uses `runCommand`.
61
+ */
62
+ export declare function runShip(args: RunShipArgs): Promise<ShipResult>;
package/dist/ship.js ADDED
@@ -0,0 +1,275 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { canonicalPath } from "./paths.js";
4
+ import { runCommand, tailText, VERIFY_TAIL_BYTES } from "./verify.js";
5
+ /** True when `abs` equals or sits under a deny entry (canonical comparison). */
6
+ export function isDeniedPath(abs, deny) {
7
+ if (!deny?.length)
8
+ return false;
9
+ let target;
10
+ try {
11
+ target = canonicalPath(abs);
12
+ }
13
+ catch {
14
+ target = path.resolve(abs);
15
+ }
16
+ for (const d of deny) {
17
+ let denied;
18
+ try {
19
+ denied = canonicalPath(d);
20
+ }
21
+ catch {
22
+ denied = path.resolve(d);
23
+ }
24
+ // Case-folded: on case-insensitive filesystems `SECRET/x` is the same file as `secret/x`.
25
+ const t = target.toLowerCase();
26
+ const dl = denied.toLowerCase();
27
+ if (t === dl || t.startsWith(dl + path.sep))
28
+ return true;
29
+ }
30
+ return false;
31
+ }
32
+ function defaultVerify(cmd, cwd, timeoutSec, signal) {
33
+ return runCommand(cmd, { cwd, timeoutSec, signal }).then((r) => {
34
+ if (r.cancelled)
35
+ return { ok: false, exit: null, output: "(cancelled)", cancelled: true };
36
+ const output = tailText(r.output, VERIFY_TAIL_BYTES);
37
+ if (r.timedOut)
38
+ return { ok: false, exit: r.exit, output: `${output}\n(timed out)` };
39
+ if (r.error)
40
+ return { ok: false, exit: r.exit, output: r.error };
41
+ return { ok: r.exit === 0, exit: r.exit, output };
42
+ });
43
+ }
44
+ /** Resolve `rel` under `root`; reject escapes, leaf symlinks, and deny-list hits. */
45
+ export function resolveUnderRoot(root, rel, deny) {
46
+ if (!rel || rel.includes("\0"))
47
+ return { ok: false, reason: "path is empty or invalid" };
48
+ if (path.isAbsolute(rel))
49
+ return { ok: false, reason: `path must be relative to the ship root: ${rel}` };
50
+ const rootReal = canonicalPath(root);
51
+ const abs = path.resolve(rootReal, rel);
52
+ const relPosix = path.relative(rootReal, abs);
53
+ if (relPosix === ".." || relPosix.startsWith(`..${path.sep}`) || path.isAbsolute(relPosix)) {
54
+ return { ok: false, reason: `path escapes the ship root: ${rel}` };
55
+ }
56
+ // Refuse editing through symlinks (aliases to the same inode / escape). Missing path is fine.
57
+ let check = abs;
58
+ while (check !== rootReal && check !== path.dirname(check)) {
59
+ try {
60
+ if (fs.lstatSync(check).isSymbolicLink()) {
61
+ return { ok: false, reason: `path must not be a symlink: ${rel}` };
62
+ }
63
+ }
64
+ catch {
65
+ /* missing */
66
+ }
67
+ check = path.dirname(check);
68
+ }
69
+ if (isDeniedPath(abs, deny))
70
+ return { ok: false, reason: `path is denied by write policy: ${rel}` };
71
+ // Also refuse `.git` anywhere under the ship root (defence in depth).
72
+ const parts = relPosix.split(path.sep);
73
+ if (parts.some((part) => part.toLowerCase() === ".git"))
74
+ return { ok: false, reason: `path must not touch .git: ${rel}` };
75
+ return { ok: true, abs, rel: relPosix.split(path.sep).join("/") };
76
+ }
77
+ function countExact(hay, needle) {
78
+ if (!needle)
79
+ return 0;
80
+ let n = 0;
81
+ let from = 0;
82
+ for (;;) {
83
+ const at = hay.indexOf(needle, from);
84
+ if (at === -1)
85
+ return n;
86
+ n++;
87
+ from = at + needle.length;
88
+ }
89
+ }
90
+ /** Exact search/replace; ambiguous without `replace_all` is a miss. */
91
+ export function applyExactEdit(text, search, replace, replaceAll) {
92
+ if (!search)
93
+ return { ok: false, message: "search must not be empty" };
94
+ const n = countExact(text, search);
95
+ if (n === 0)
96
+ return { ok: false, message: "search text not found" };
97
+ if (n > 1 && !replaceAll) {
98
+ return { ok: false, message: `search text matches ${n} places (ambiguous). Pass replace_all: true or add neighbouring context.` };
99
+ }
100
+ if (replaceAll)
101
+ return { ok: true, text: text.split(search).join(replace), count: n };
102
+ return { ok: true, text: text.replace(search, () => replace), count: 1 };
103
+ }
104
+ function snapshot(abs, rel) {
105
+ try {
106
+ const st = fs.statSync(abs);
107
+ const bytes = fs.readFileSync(abs);
108
+ return { rel, abs, existed: true, bytes, mode: st.mode };
109
+ }
110
+ catch (e) {
111
+ if (e.code === "ENOENT")
112
+ return { rel, abs, existed: false, bytes: Buffer.alloc(0) };
113
+ throw e;
114
+ }
115
+ }
116
+ function restore(snaps) {
117
+ const errors = [];
118
+ for (const s of snaps) {
119
+ try {
120
+ if (s.existed) {
121
+ fs.mkdirSync(path.dirname(s.abs), { recursive: true });
122
+ fs.writeFileSync(s.abs, s.bytes, s.mode !== undefined ? { mode: s.mode } : undefined);
123
+ if (s.mode !== undefined)
124
+ fs.chmodSync(s.abs, s.mode);
125
+ }
126
+ else if (fs.existsSync(s.abs)) {
127
+ fs.unlinkSync(s.abs);
128
+ }
129
+ }
130
+ catch (e) {
131
+ errors.push(`${s.rel}: ${e.message}`);
132
+ }
133
+ }
134
+ return errors;
135
+ }
136
+ /**
137
+ * Apply multi-file exact edits under `root`, run verify, roll back on failure.
138
+ * Pure relative to injected `runVerify` (tests); production uses `runCommand`.
139
+ */
140
+ export async function runShip(args) {
141
+ const root = canonicalPath(args.root);
142
+ if (!args.commands?.length || args.commands.some((c) => !c.run?.trim())) {
143
+ return { status: "ABORTED_BEFORE_WRITE", summary: "at least one verify command is required", filesModified: [] };
144
+ }
145
+ if (!args.edits.length) {
146
+ return { status: "ABORTED_BEFORE_WRITE", summary: "edits must not be empty", filesModified: [] };
147
+ }
148
+ const byFile = new Map();
149
+ const foldedSpelling = new Map();
150
+ for (const edit of args.edits) {
151
+ const resolved = resolveUnderRoot(root, edit.path, args.deny);
152
+ if (!resolved.ok)
153
+ return { status: "ABORTED_BEFORE_WRITE", summary: resolved.reason, filesModified: [] };
154
+ const folded = resolved.rel.toLowerCase();
155
+ const prior = foldedSpelling.get(folded);
156
+ if (prior !== undefined && prior !== resolved.rel) {
157
+ return {
158
+ status: "ABORTED_BEFORE_WRITE",
159
+ summary: `paths differ only in letter case and may name one file on a case-insensitive filesystem: ${prior} vs ${resolved.rel}`,
160
+ filesModified: [],
161
+ };
162
+ }
163
+ foldedSpelling.set(folded, resolved.rel);
164
+ const cur = byFile.get(resolved.rel) ?? { abs: resolved.abs, rel: resolved.rel, edits: [] };
165
+ cur.edits.push(edit);
166
+ byFile.set(resolved.rel, cur);
167
+ }
168
+ const planned = [];
169
+ for (const file of byFile.values()) {
170
+ const label = file.rel || ".";
171
+ let snap;
172
+ try {
173
+ const st = fs.existsSync(file.abs) ? fs.statSync(file.abs) : undefined;
174
+ if (st && !st.isFile()) {
175
+ return { status: "ABORTED_BEFORE_WRITE", summary: `${label}: target is not a regular file`, filesModified: [] };
176
+ }
177
+ snap = snapshot(file.abs, file.rel);
178
+ }
179
+ catch (e) {
180
+ return { status: "ABORTED_BEFORE_WRITE", summary: `${label}: cannot read target (${e.message})`, filesModified: [] };
181
+ }
182
+ let text = snap.existed ? snap.bytes.toString("utf8") : "";
183
+ if (snap.existed && Buffer.from(text, "utf8").compare(snap.bytes) !== 0) {
184
+ return { status: "ABORTED_BEFORE_WRITE", summary: `${file.rel}: file is not valid UTF-8 text`, filesModified: [] };
185
+ }
186
+ for (const edit of file.edits) {
187
+ const out = applyExactEdit(text, edit.search, edit.replace, edit.replace_all);
188
+ if (!out.ok) {
189
+ return { status: "ABORTED_BEFORE_WRITE", summary: `${file.rel}: ${out.message}`, filesModified: [] };
190
+ }
191
+ text = out.text;
192
+ }
193
+ planned.push({ rel: file.rel, abs: file.abs, next: Buffer.from(text, "utf8"), snap });
194
+ }
195
+ // Track every file we intend to touch *before* mutating it, so a mid-write failure still rolls back.
196
+ const written = [];
197
+ const tmps = [];
198
+ try {
199
+ for (const p of planned) {
200
+ written.push(p.snap);
201
+ fs.mkdirSync(path.dirname(p.abs), { recursive: true });
202
+ const tmp = `${p.abs}.agent-lyceum-ship.${process.pid}.${Date.now()}.tmp`;
203
+ tmps.push(tmp);
204
+ const writeOpts = p.snap.mode !== undefined ? { mode: p.snap.mode } : undefined;
205
+ fs.writeFileSync(tmp, p.next, writeOpts);
206
+ // `mode` in writeFileSync is filtered by the umask; chmod sets the original permission bits exactly.
207
+ if (p.snap.mode !== undefined)
208
+ fs.chmodSync(tmp, p.snap.mode & 0o7777);
209
+ fs.renameSync(tmp, p.abs);
210
+ tmps.pop();
211
+ }
212
+ }
213
+ catch (e) {
214
+ for (const t of tmps) {
215
+ try {
216
+ fs.unlinkSync(t);
217
+ }
218
+ catch {
219
+ /* best-effort */
220
+ }
221
+ }
222
+ const rollbackErrors = restore(written);
223
+ const why = e instanceof Error ? e.message : String(e);
224
+ if (rollbackErrors.length) {
225
+ return {
226
+ status: "FAILED_ROLLBACK_PARTIAL",
227
+ summary: `Write failed (${why}); rollback incomplete: ${rollbackErrors.join("; ")}`,
228
+ filesModified: written.map((s) => s.rel),
229
+ };
230
+ }
231
+ return {
232
+ status: "FAILED_AND_ROLLED_BACK",
233
+ summary: `FAILED_AND_ROLLED_BACK: write failed (${why}). Restored ${written.length} file(s).`,
234
+ filesModified: written.map((s) => s.rel),
235
+ };
236
+ }
237
+ const filesModified = planned.map((p) => p.rel);
238
+ const runVerify = args.runVerify ?? defaultVerify;
239
+ // Fail-fast chain. An abort that arrived before a command started (or that a runner did not report) still ends in a restored tree.
240
+ let verified = { ok: true, exit: 0, output: "" };
241
+ let failedName;
242
+ for (const c of args.commands) {
243
+ verified = args.signal?.aborted
244
+ ? { ok: false, exit: null, output: "", cancelled: true }
245
+ : await runVerify(c.run, root, c.timeout_sec, args.signal);
246
+ if (!verified.ok || verified.cancelled || args.signal?.aborted) {
247
+ failedName = c.name;
248
+ break;
249
+ }
250
+ }
251
+ const cancelled = verified.cancelled === true || args.signal?.aborted === true;
252
+ if (verified.ok && !cancelled) {
253
+ return {
254
+ status: "SHIPPED_AND_VERIFIED",
255
+ summary: `Shipped ${filesModified.length} file(s); verify passed (${args.commands.length} command(s)).\n${verified.output}`.trim(),
256
+ filesModified,
257
+ };
258
+ }
259
+ const rollbackErrors = restore(planned.map((p) => p.snap));
260
+ const what = cancelled
261
+ ? `ship was interrupted (verify command "${failedName}" cancelled)`
262
+ : `verify command "${failedName}" failed (exit ${verified.exit})`;
263
+ if (rollbackErrors.length) {
264
+ return {
265
+ status: "FAILED_ROLLBACK_PARTIAL",
266
+ summary: `${what[0].toUpperCase()}${what.slice(1)}; rollback incomplete: ${rollbackErrors.join("; ")}\n${verified.output}`.trim(),
267
+ filesModified,
268
+ };
269
+ }
270
+ return {
271
+ status: "FAILED_AND_ROLLED_BACK",
272
+ summary: `FAILED_AND_ROLLED_BACK: ${what}. Restored ${filesModified.length} file(s).\n${verified.output}`.trim(),
273
+ filesModified,
274
+ };
275
+ }
package/dist/task.d.ts CHANGED
@@ -22,3 +22,5 @@ export declare function taskMessageBody(task: PreparedTask): {
22
22
  subject: string;
23
23
  body: string;
24
24
  };
25
+ /** Warn-only lint for task FILES: does it say how the work is checked? Headings only; fenced code does not count. */
26
+ export declare function lintTaskContent(content: string): string[];
package/dist/task.js CHANGED
@@ -69,3 +69,31 @@ export function taskMessageBody(task) {
69
69
  `First lines:\n\n${task.content.split("\n").slice(0, 10).join("\n")}\n`,
70
70
  };
71
71
  }
72
+ /** Warn-only lint for task FILES: does it say how the work is checked? Headings only; fenced code does not count. */
73
+ export function lintTaskContent(content) {
74
+ const headings = [];
75
+ let fence;
76
+ for (const line of content.split(/\r?\n/)) {
77
+ const f = /^ {0,3}(`{3,}|~{3,})/.exec(line);
78
+ if (f) {
79
+ const mark = f[1][0];
80
+ if (fence === undefined)
81
+ fence = mark;
82
+ else if (fence === mark)
83
+ fence = undefined;
84
+ continue;
85
+ }
86
+ if (fence !== undefined)
87
+ continue;
88
+ const h = /^#{1,6}\s+(.*)$/.exec(line);
89
+ if (h)
90
+ headings.push(h[1].toLowerCase());
91
+ }
92
+ const has = (...words) => headings.some((h) => words.some((w) => h.includes(w)));
93
+ const out = [];
94
+ if (!has("acceptance", "驗收"))
95
+ out.push("has no Acceptance criteria section: say how the work is checked, or the lead cannot tell when it is done. See docs/task-template.md.");
96
+ if (!has("verification", "驗證"))
97
+ out.push("has no Verification section: give the exact command(s) that must pass. See docs/task-template.md.");
98
+ return out;
99
+ }
package/dist/validate.js CHANGED
@@ -2,6 +2,7 @@ import fs from "node:fs";
2
2
  import { enforcementFor, memoryDirs } from "./policy.js";
3
3
  import { describeConflict, fallbackCapExcess, sandboxConflictsOf } from "./sandbox-invocation.js";
4
4
  import { isInside } from "./paths.js";
5
+ import { shipCommands, shipEnabled } from "./ship-wire.js";
5
6
  import { inferRuntime, RUNTIME_EFFORTS, RUNTIMES } from "./schema.js";
6
7
  import { ladderIndex } from "./tiers.js";
7
8
  import { must } from "./assert.js";
@@ -57,6 +58,10 @@ export function validateProject(project) {
57
58
  err(`agent ${a.name}: fallback ${f.label} would apply more sandbox allowance than the primary (${f.excess.join("; ")}).`);
58
59
  if (!fs.existsSync(a.agentMd))
59
60
  err(`Agent "${a.name}": AGENT.md not found at ${a.agentMd}`);
61
+ // Warning, like other "setting has no effect" checks: the run still works, but ship is silently not offered to the agent.
62
+ if (shipEnabled(a) && !shipCommands(project, a).length) {
63
+ warn(`Agent "${a.name}" has ship enabled but nothing to verify with, so ship is NOT offered to it. Set agents.${a.name}.ship.verify or add a project-level verify: block (commands).`);
64
+ }
60
65
  if (!a.memory.global && !a.memory.project)
61
66
  warn(`Agent "${a.name}" has no long-term memory configured.`);
62
67
  if (a.canMessage !== "all") {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-lyceum",
3
- "version": "0.41.0",
3
+ "version": "0.42.0",
4
4
  "description": "Config + dispatcher for teams of Claude Code / Codex agents with scoped context and file-based mailboxes",
5
5
  "keywords": [
6
6
  "ai",