opencode-agent-orchestration-kit 1.0.45 → 1.1.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.
Files changed (105) hide show
  1. package/CONTRIBUTING.md +0 -1
  2. package/NOTICE.md +1 -5
  3. package/README.md +37 -49
  4. package/compatibility.json +7 -0
  5. package/docs/cli.md +69 -1
  6. package/docs/commands.md +1 -1
  7. package/docs/comparison.md +3 -3
  8. package/docs/compatibility.md +33 -14
  9. package/docs/installation.md +2 -0
  10. package/docs/models.md +1 -1
  11. package/docs/open-design.md +2 -0
  12. package/docs/opencode-v2.md +190 -0
  13. package/docs/releases/v1.1.0.md +91 -0
  14. package/docs/supply-chain.md +4 -7
  15. package/docs/threat-model.md +16 -6
  16. package/docs/troubleshooting.md +7 -4
  17. package/docs/workflows.md +27 -4
  18. package/opencode/AGENTS.md +18 -10
  19. package/opencode/agents/designer.md +1 -1
  20. package/opencode/agents/developer.md +60 -6
  21. package/opencode/agents/lead.md +19 -9
  22. package/opencode/agents/reviewer.md +7 -0
  23. package/opencode/agents/scoper.md +1 -0
  24. package/opencode/agents/specifier.md +1 -0
  25. package/opencode/commands/autonomous.md +175 -24
  26. package/opencode/docs/ai/evolution/README.md +5 -4
  27. package/opencode/docs/ai/evolution/benchmarks/adversarial-scenarios.jsonl +3 -0
  28. package/opencode/docs/ai/evolution/session-sources.md +12 -0
  29. package/opencode/docs/ai/harness/agents.md +8 -6
  30. package/opencode/docs/ai/harness/checks.md +3 -2
  31. package/opencode/docs/ai/harness/commands.md +7 -4
  32. package/opencode/docs/ai/harness/skill_registry.json +107 -1
  33. package/opencode/docs/ai/harness/skill_registry.md +5 -0
  34. package/opencode/docs/ai/specs/mission-runtime.md +9 -0
  35. package/opencode/opencode.json +0 -1
  36. package/opencode/plugins/mission-runtime.test.mjs +15 -3
  37. package/opencode/plugins/mission-runtime.ts +11 -39
  38. package/opencode/plugins/oak-tui/server.ts +8 -0
  39. package/opencode/plugins/oak-tui/tui.tsx +81 -0
  40. package/opencode/plugins/open-design.ts +12 -0
  41. package/opencode/plugins/shell-export-guard.ts +13 -23
  42. package/opencode/plugins/token-tree-usage.tsx +4 -1
  43. package/opencode/runtime/v1/mission-runtime.ts +73 -0
  44. package/opencode/runtime/v1/shell-export-guard.ts +9 -0
  45. package/opencode/runtime/v2/mission-events.d.mts +13 -0
  46. package/opencode/runtime/v2/mission-events.mjs +64 -0
  47. package/opencode/runtime/v2/mission-events.test.mjs +120 -0
  48. package/opencode/runtime/v2/mission-runtime.ts +26 -0
  49. package/opencode/runtime/v2/open-design.ts +17 -0
  50. package/opencode/runtime/v2/shell-export-guard.ts +8 -0
  51. package/opencode/runtime/v2/token-usage.d.mts +15 -0
  52. package/opencode/runtime/v2/token-usage.mjs +35 -0
  53. package/opencode/runtime/v2/token-usage.test.mjs +30 -0
  54. package/opencode/scripts/adversarial-harness.test.mjs +50 -1
  55. package/opencode/scripts/check-harness.mjs +142 -33
  56. package/opencode/scripts/check-harness.test.mjs +81 -8
  57. package/opencode/scripts/collect-session-evidence.mjs +57 -39
  58. package/opencode/scripts/collect-session-evidence.test.mjs +164 -0
  59. package/opencode/scripts/deliver.d.mts +37 -0
  60. package/opencode/scripts/deliver.mjs +204 -0
  61. package/opencode/scripts/deliver.test.mjs +245 -0
  62. package/opencode/scripts/loop-state.mjs +50 -1
  63. package/opencode/scripts/loop-state.test.mjs +33 -0
  64. package/opencode/scripts/mission-runtime.test.mjs +1 -1
  65. package/opencode/scripts/mission-status.test.mjs +2 -0
  66. package/opencode/scripts/runtime-permission-policy.mjs +1 -1
  67. package/opencode/scripts/runtime-permission-policy.test.mjs +3 -2
  68. package/opencode/scripts/session-sources.d.mts +6 -0
  69. package/opencode/scripts/session-sources.mjs +49 -0
  70. package/opencode/scripts/shell-export-guard-core.d.mts +2 -0
  71. package/opencode/scripts/shell-export-guard-core.mjs +21 -0
  72. package/opencode/scripts/shell-export-guard-core.test.mjs +43 -0
  73. package/opencode/scripts/task-run.d.mts +63 -0
  74. package/opencode/scripts/task-run.mjs +224 -0
  75. package/opencode/scripts/task-run.test.mjs +178 -0
  76. package/opencode/skills/debugging-and-error-recovery/SKILL.md +20 -0
  77. package/opencode/skills/oak-adversarial-review/SKILL.md +138 -0
  78. package/opencode/skills/oak-commit/SKILL.md +69 -0
  79. package/opencode/skills/oak-enrich-task/SKILL.md +109 -0
  80. package/opencode/skills/oak-runtime-verification/SKILL.md +103 -0
  81. package/opencode/skills/oak-update-docs/SKILL.md +54 -0
  82. package/opencode/tools/open-design-tools.d.mts +17 -0
  83. package/opencode/tools/open-design-tools.mjs +254 -0
  84. package/opencode/tools/open_design.ts +26 -259
  85. package/package.json +4 -3
  86. package/scripts/benchmark-tool-paths.mjs +1 -1
  87. package/scripts/check-compatibility.mjs +58 -4
  88. package/scripts/check-compatibility.test.mjs +159 -11
  89. package/scripts/check-public-boundary.mjs +3 -0
  90. package/scripts/check-supply-chain.mjs +24 -57
  91. package/scripts/check-supply-chain.test.mjs +37 -35
  92. package/scripts/check.sh +42 -7
  93. package/scripts/manage-installation.mjs +34 -20
  94. package/scripts/manage-installation.test.mjs +29 -0
  95. package/scripts/oak.mjs +72 -2
  96. package/scripts/oak.test.mjs +69 -1
  97. package/scripts/open-design-http.test.mjs +1 -1
  98. package/scripts/open-design-tools.test.mjs +49 -0
  99. package/scripts/opencode-compat-smoke.sh +45 -4
  100. package/scripts/opencode-v2-smoke.mjs +197 -0
  101. package/scripts/opencode-v2-smoke.test.mjs +59 -0
  102. package/scripts/package-smoke.test.mjs +3 -3
  103. package/scripts/version.test.mjs +2 -2
  104. package/supply-chain.json +0 -4
  105. package/docs/superpowers.md +0 -41
@@ -380,6 +380,7 @@ function pathsFor(root, slug) {
380
380
  lockOwner: path.join(loopsDir, `${slug}.lock`, "owner.json"),
381
381
  transitionLock: path.join(loopsDir, `${slug}.lock`, "transition.lock"),
382
382
  markdown: path.join(loopsDir, `${slug}.md`),
383
+ review: path.join(loopsDir, `${slug}.review.json`),
383
384
  };
384
385
  }
385
386
 
@@ -787,6 +788,46 @@ export function inspectLoopState({ root, slug }) {
787
788
  return structuredClone(state);
788
789
  }
789
790
 
791
+ export function attestReview({ root, slug, reviewerSessionId, reviewerAgent, reviewerVerdict, now = () => new Date() }) {
792
+ requireString(reviewerSessionId, "reviewer_session_id");
793
+ if (reviewerAgent !== "reviewer") fail("invalid_argument", "reviewer_agent must be reviewer");
794
+ if (reviewerVerdict !== "APPROVE") fail("invalid_argument", "reviewer_verdict must be APPROVE");
795
+ const paths = pathsFor(root, slug);
796
+ const state = inspectLoopState({ root, slug });
797
+ const attestation = {
798
+ schema_version: 1,
799
+ slug,
800
+ contract_hash: state.approval.contract_hash,
801
+ reviewer_session_id: reviewerSessionId,
802
+ reviewer_agent: reviewerAgent,
803
+ reviewer_verdict: reviewerVerdict,
804
+ attested_at: now().toISOString(),
805
+ };
806
+ const temporary = `${paths.review}.${process.pid}.tmp`;
807
+ fs.writeFileSync(temporary, `${JSON.stringify(attestation, null, 2)}\n`, { flag: "wx" });
808
+ fs.renameSync(temporary, paths.review);
809
+ return attestation;
810
+ }
811
+
812
+ function requireReviewAttestation(paths, state) {
813
+ let attestation;
814
+ try {
815
+ const stat = fs.lstatSync(paths.review);
816
+ if (!stat.isFile()) throw new Error("not a regular file");
817
+ attestation = JSON.parse(fs.readFileSync(paths.review, "utf8"));
818
+ } catch {
819
+ fail("review_attestation_required", "completion requires oak state attest-review");
820
+ }
821
+ if (
822
+ attestation?.schema_version !== 1
823
+ || attestation.reviewer_agent !== "reviewer"
824
+ || attestation.reviewer_verdict !== "APPROVE"
825
+ || attestation.contract_hash !== state.approval.contract_hash
826
+ ) {
827
+ fail("review_attestation_required", "reviewer attestation is missing, invalid, or bound to another contract");
828
+ }
829
+ }
830
+
790
831
  export function readLoopHistory({ root, slug }) {
791
832
  const paths = pathsFor(root, slug);
792
833
  return structuredClone(readHistory(paths).events);
@@ -920,6 +961,7 @@ export function recordLoopAction({
920
961
  if (iteration > state.planned_iterations) {
921
962
  fail("iteration_budget_exceeded", "iteration exceeds the planned iteration budget");
922
963
  }
964
+ if (status === "completed") requireReviewAttestation(paths, state);
923
965
  try {
924
966
  return commitTransition({
925
967
  paths,
@@ -1202,10 +1244,17 @@ export function main(argv = process.argv.slice(2)) {
1202
1244
  });
1203
1245
  } else if (command === "migrate") {
1204
1246
  result = migrateLoopState(common);
1247
+ } else if (command === "attest-review") {
1248
+ result = attestReview({
1249
+ ...common,
1250
+ reviewerSessionId: options.reviewer_session_id,
1251
+ reviewerAgent: options.reviewer_agent,
1252
+ reviewerVerdict: options.reviewer_verdict,
1253
+ });
1205
1254
  } else {
1206
1255
  fail(
1207
1256
  "invalid_argument",
1208
- "command must be init, resume, record, release, inspect, repair, or migrate",
1257
+ "command must be init, resume, record, release, inspect, attest-review, repair, or migrate",
1209
1258
  );
1210
1259
  }
1211
1260
  process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
@@ -9,6 +9,7 @@ import { fileURLToPath } from "node:url";
9
9
  import {
10
10
  LoopStateError,
11
11
  acquireLoop,
12
+ attestReview,
12
13
  initLoopState,
13
14
  inspectLoopState,
14
15
  migrateLoopState,
@@ -216,6 +217,7 @@ test("records actions idempotently and rejects action-id reuse with different co
216
217
  const duplicate = recordLoopAction(action);
217
218
  assert.deepEqual(duplicate, first);
218
219
 
220
+ attestReview({ root, slug: "example", reviewerSessionId: "child-1", reviewerAgent: "reviewer", reviewerVerdict: "APPROVE" });
219
221
  const later = recordLoopAction({
220
222
  ...action,
221
223
  actionId: "iteration-2",
@@ -665,3 +667,34 @@ test("does not follow a broken history symlink during initialization", () => {
665
667
  fs.rmSync(outside, { recursive: true, force: true });
666
668
  }
667
669
  });
670
+
671
+ test("completion fails closed without a reviewer attestation bound to the contract", () => {
672
+ withRepo(({ root, contractPath }) => {
673
+ initExample(root, contractPath);
674
+ acquireLoop({ root, slug: "example", contractPath, sessionId: "session-1", actionId: "resume-1" });
675
+ const complete = { root, slug: "example", sessionId: "session-1", actionId: "done-1", iteration: 1, completedStep: "reviewer_approved", blockingCause: null, status: "completed" };
676
+ assert.throws(() => recordLoopAction(complete), (error) => error instanceof LoopStateError && error.code === "review_attestation_required");
677
+
678
+ assert.throws(() => attestReview({ root, slug: "example", reviewerSessionId: "child-9", reviewerAgent: "developer", reviewerVerdict: "APPROVE" }), /reviewer_agent/);
679
+ assert.throws(() => attestReview({ root, slug: "example", reviewerSessionId: "child-9", reviewerAgent: "reviewer", reviewerVerdict: "REJECT" }), /reviewer_verdict/);
680
+
681
+ const attestation = attestReview({ root, slug: "example", reviewerSessionId: "child-9", reviewerAgent: "reviewer", reviewerVerdict: "APPROVE" });
682
+ assert.equal(attestation.contract_hash, inspectLoopState({ root, slug: "example" }).approval.contract_hash);
683
+ assert.equal(recordLoopAction(complete).status, "completed");
684
+ });
685
+ });
686
+
687
+ test("an attestation for another contract does not complete the loop", () => {
688
+ withRepo(({ root, contractPath }) => {
689
+ initExample(root, contractPath);
690
+ acquireLoop({ root, slug: "example", contractPath, sessionId: "session-1", actionId: "resume-1" });
691
+ attestReview({ root, slug: "example", reviewerSessionId: "child-9", reviewerAgent: "reviewer", reviewerVerdict: "APPROVE" });
692
+ const file = path.join(root, ".opencode/loops/example.review.json");
693
+ const tampered = { ...JSON.parse(fs.readFileSync(file, "utf8")), contract_hash: `sha256:${"0".repeat(64)}` };
694
+ fs.writeFileSync(file, JSON.stringify(tampered));
695
+ assert.throws(
696
+ () => recordLoopAction({ root, slug: "example", sessionId: "session-1", actionId: "done-1", iteration: 1, completedStep: "reviewer_approved", blockingCause: null, status: "completed" }),
697
+ (error) => error.code === "review_attestation_required",
698
+ );
699
+ });
700
+ });
@@ -88,7 +88,7 @@ test("notification failures are logged and never escape the observer", async ()
88
88
  });
89
89
 
90
90
  test("plugin is an observer only and uses an optional TUI notification", () => {
91
- const source = fs.readFileSync(path.join(root, "plugins/mission-runtime.ts"), "utf8");
91
+ const source = fs.readFileSync(path.join(root, "runtime/v1/mission-runtime.ts"), "utf8");
92
92
  assert.match(source, /event:/);
93
93
  assert.match(source, /chat\.message/);
94
94
  assert.match(source, /showToast/);
@@ -9,6 +9,7 @@ import { fileURLToPath } from "node:url";
9
9
  import {
10
10
  LoopStateError,
11
11
  acquireLoop,
12
+ attestReview,
12
13
  initLoopState,
13
14
  recordLoopAction,
14
15
  releaseLoop,
@@ -114,6 +115,7 @@ test("projects running, blocked, paused, and completed transitions", () => {
114
115
  assert.equal(mission.status, "paused");
115
116
  assert.match(mission.next_action, /resume explicitly/);
116
117
 
118
+ attestReview({ root, slug: "example", reviewerSessionId: "child-1", reviewerAgent: "reviewer", reviewerVerdict: "APPROVE" });
117
119
  recordLoopAction({
118
120
  root,
119
121
  slug: "example",
@@ -40,7 +40,7 @@ const common = {
40
40
  export const AGENT_POLICIES = Object.freeze({
41
41
  debugger: Object.freeze({ ...common, repository_write: "unspecified", task_default: "unspecified", write: "ask", network: "allow", delegate_to: [] }),
42
42
  designer: Object.freeze({ ...common, repository_write: "ask", task_default: "unspecified", write: "ask", network: "allow", delegate_to: [] }),
43
- developer: Object.freeze({ ...common, repository_write: "allow", task_default: "unspecified", write: "allow", network: "ask", commit: "ask", delegate_to: [] }),
43
+ developer: Object.freeze({ ...common, repository_write: "allow", task_default: "unspecified", write: "allow", network: "ask", commit: "ask", push: "ask", delegate_to: [] }),
44
44
  evaluator: Object.freeze({ ...common, repository_write: "unspecified", task_default: "unspecified", write: "ask", network: "ask", delegate_to: [] }),
45
45
  evolver: Object.freeze({ ...common, repository_write: "unspecified", task_default: "unspecified", write: "ask", network: "ask", delegate_to: [] }),
46
46
  lead: Object.freeze({ ...common, repository_write: "deny", task_default: "deny", write: "deny", network: "allow", delegate_to: ["debugger", "designer", "developer", "evaluator", "evolver", "researcher", "reviewer", "specifier"] }),
@@ -67,9 +67,10 @@ test("delegation is restricted to the declared task allowlist", () => {
67
67
  );
68
68
  });
69
69
 
70
- test("publication and deployment operations are denied for every role", () => {
70
+ test("push asks only for developer delivery and deployment is denied for every role", () => {
71
71
  for (const agentId of AGENT_IDS) {
72
- assert.equal(decideToolAccess({ agentId, operation: "push" }), "deny", agentId);
72
+ const expectedPush = agentId === "developer" ? "ask" : "deny";
73
+ assert.equal(decideToolAccess({ agentId, operation: "push" }), expectedPush, agentId);
73
74
  assert.equal(decideToolAccess({ agentId, operation: "deploy" }), "deny", agentId);
74
75
  }
75
76
  });
@@ -0,0 +1,6 @@
1
+ export const SESSION_TABLES_SQL: string;
2
+ export function pickSessionSchemas(rows: ReadonlyArray<{ name: string }>): Array<"v1" | "v2">;
3
+ export function sessionQueries(
4
+ schema: "v1" | "v2",
5
+ options: { fullRescan: boolean; cutoffFilter: string },
6
+ ): { sessions: string; messages: string; parts: string };
@@ -0,0 +1,49 @@
1
+ // OpenCode 1 stores sessions in `session`, `message` and `part`. OpenCode 2 stores
2
+ // them in `session_v2` and one `session_message` row per message. The OpenCode 2
3
+ // queries reshape rows into the OpenCode 1 row shape that summarizeSqlite consumes.
4
+ export const SESSION_TABLES_SQL =
5
+ "select name from sqlite_master where type = 'table' and name in ('session', 'session_v2');";
6
+
7
+ const SESSION_COLUMNS = [
8
+ "id", "project_id", "parent_id", "slug", "directory", "title", "version", "time_created",
9
+ "time_updated", "workspace_id", "path", "agent", "model", "cost", "tokens_input",
10
+ "tokens_output", "tokens_reasoning", "tokens_cache_read", "tokens_cache_write",
11
+ ].join(", ");
12
+
13
+ // Schemas present in the database, OpenCode 2 first. OpenCode 2 imports
14
+ // OpenCode 1 sessions on first start, so a database can hold both.
15
+ export function pickSessionSchemas(rows) {
16
+ const names = new Set(rows.map((row) => row.name));
17
+ const schemas = [];
18
+ if (names.has("session_v2")) schemas.push("v2");
19
+ if (names.has("session")) schemas.push("v1"); // oak:v1-only
20
+ if (schemas.length === 0) throw new Error("OpenCode database has neither a session nor a session_v2 table");
21
+ return schemas;
22
+ }
23
+
24
+ export function sessionQueries(schema, { fullRescan, cutoffFilter }) {
25
+ // oak:v1-only — start
26
+ if (schema === "v1") {
27
+ return {
28
+ sessions: `select ${SESSION_COLUMNS} from session order by time_updated desc, id desc;`,
29
+ messages: fullRescan
30
+ ? "select id, session_id, time_created, time_updated, data from message order by session_id, time_created, id;"
31
+ : `select id, session_id, time_created, time_updated, json_extract(data, '$.role') as role from message where 1=1 ${cutoffFilter} order by session_id, time_created, id;`,
32
+ parts: `select id, message_id, session_id, time_created, time_updated, data from part where 1=1 ${cutoffFilter} order by session_id, time_created, id;`,
33
+ };
34
+ }
35
+ // oak:v1-only — end
36
+ return {
37
+ sessions: `select ${SESSION_COLUMNS} from session_v2 order by time_updated desc, id desc;`,
38
+ messages: `select id, session_id, time_created, time_updated, type as role${fullRescan ? ", data" : ""} from session_message where type in ('user', 'assistant') ${cutoffFilter} order by session_id, time_created, id;`,
39
+ parts: `
40
+ select id, id as message_id, session_id, time_created, time_updated,
41
+ json_object('type', 'text', 'text', json_extract(data, '$.text')) as data
42
+ from session_message where type = 'user' ${cutoffFilter}
43
+ union all
44
+ select m.id || ':' || printf('%06d', c.key), m.id, m.session_id, m.time_created, m.time_updated, c.value
45
+ from session_message m, json_each(m.data, '$.content') c
46
+ where m.type = 'assistant' and json_extract(c.value, '$.type') = 'text' ${cutoffFilter.replace("time_created", "m.time_created")}
47
+ order by 3, 4, 1;`,
48
+ };
49
+ }
@@ -0,0 +1,2 @@
1
+ export const BLOCK_MESSAGE: string;
2
+ export function assertShellCallAllowed(toolName: unknown, args: unknown): void;
@@ -0,0 +1,21 @@
1
+ import { classifyShellExport } from "./shell-export-policy.mjs";
2
+
3
+ export const BLOCK_MESSAGE =
4
+ "Sensitive shell export blocked by policy; use an explicit non-secret value or a scoped secret-aware tool.";
5
+
6
+ // OpenCode 1 names the shell tool `bash`; OpenCode 2 names it `shell`.
7
+ const SHELL_TOOLS = new Set(["bash", "shell"]);
8
+
9
+ export function assertShellCallAllowed(toolName, args) {
10
+ const tool = String(toolName ?? "").toLowerCase();
11
+ if (!SHELL_TOOLS.has(tool)) return;
12
+ if (!args || typeof args !== "object") return;
13
+
14
+ const command = args.command;
15
+ if (typeof command !== "string") return;
16
+
17
+ const decision = classifyShellExport(command);
18
+ if (decision.blocked) {
19
+ throw new Error(`[shell-export-guard:${decision.rule}] ${BLOCK_MESSAGE}`);
20
+ }
21
+ }
@@ -0,0 +1,43 @@
1
+ import assert from "node:assert/strict";
2
+ import test from "node:test";
3
+ import { BLOCK_MESSAGE, assertShellCallAllowed } from "./shell-export-guard-core.mjs";
4
+
5
+ test("blocks environment enumeration from the OpenCode 1 bash tool", () => {
6
+ assert.throws(
7
+ () => assertShellCallAllowed("bash", { command: "export -p" }),
8
+ /^Error: \[shell-export-guard:shell-export-environment-enumeration\] /,
9
+ );
10
+ });
11
+
12
+ test("blocks environment enumeration from the OpenCode 2 shell tool", () => {
13
+ assert.throws(
14
+ () => assertShellCallAllowed("shell", { command: "export" }),
15
+ /\[shell-export-guard:shell-export-environment-enumeration\]/,
16
+ );
17
+ });
18
+
19
+ test("matches tool names case-insensitively", () => {
20
+ assert.throws(() => assertShellCallAllowed("Bash", { command: "export -p" }), /shell-export-guard/);
21
+ });
22
+
23
+ test("allows safe exports", () => {
24
+ assert.doesNotThrow(() => assertShellCallAllowed("shell", { command: "export NODE_ENV=test" }));
25
+ });
26
+
27
+ test("ignores other tools and malformed input", () => {
28
+ for (const [tool, args] of [
29
+ ["read", { command: "export" }],
30
+ ["shell", null],
31
+ ["shell", { command: 42 }],
32
+ [undefined, undefined],
33
+ ]) {
34
+ assert.doesNotThrow(() => assertShellCallAllowed(tool, args));
35
+ }
36
+ });
37
+
38
+ test("never echoes the command in the error", () => {
39
+ assert.throws(
40
+ () => assertShellCallAllowed("bash", { command: "export -p" }),
41
+ (error) => error.message.endsWith(BLOCK_MESSAGE) && !error.message.includes("export -p"),
42
+ );
43
+ });
@@ -0,0 +1,63 @@
1
+ export type RunKind = "production" | "benchmark";
2
+
3
+ export type TaskRun = {
4
+ schema: "oak.run/1";
5
+ run_id: string;
6
+ kind: RunKind;
7
+ change: string;
8
+ branch: string;
9
+ repo: string;
10
+ started_at: string;
11
+ };
12
+
13
+ export type RunEvent = {
14
+ schema: "oak.event/1";
15
+ run_id: string;
16
+ at: string;
17
+ type: string;
18
+ [key: string]: string | number;
19
+ };
20
+
21
+ export type RunSummary = {
22
+ schema: "oak.run.summary/1";
23
+ run: TaskRun;
24
+ closed_at: string;
25
+ events: RunEvent[];
26
+ };
27
+
28
+ export const RUN_EVENT_TYPES: readonly string[];
29
+
30
+ export class TaskRunError extends Error {
31
+ constructor(code: string, message: string);
32
+ code: string;
33
+ }
34
+
35
+ export function startRun(options: {
36
+ root: string;
37
+ slug: string;
38
+ branch: string;
39
+ kind?: RunKind;
40
+ now?: () => Date;
41
+ random?: () => Uint8Array;
42
+ }): TaskRun;
43
+
44
+ export function runStatus(options: {
45
+ root: string;
46
+ branch?: string;
47
+ now?: () => Date;
48
+ }): { active: false } | { active: true; run: TaskRun; stale: boolean; events: number };
49
+
50
+ export function appendRunEvent(options: {
51
+ root: string;
52
+ type: string;
53
+ fields?: Record<string, string | number>;
54
+ now?: () => Date;
55
+ }): RunEvent | null;
56
+
57
+ export function closeRun(options: {
58
+ root: string;
59
+ output?: string;
60
+ now?: () => Date;
61
+ }): { active: false } | { run_id: string; path: string } | { run_id: string; summary: RunSummary };
62
+
63
+ export function currentBranch(root: string): string;
@@ -0,0 +1,224 @@
1
+ #!/usr/bin/env node
2
+
3
+ import crypto from "node:crypto";
4
+ import fs from "node:fs";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+
8
+ export const RUN_EVENT_TYPES = Object.freeze(["agent_session", "review", "runtime_verification", "verify", "delivery", "ci"]);
9
+ const SLUG = /^[A-Za-z0-9._-]{1,120}$/;
10
+ const KEY = /^[a-z][a-z0-9_]{0,40}$/;
11
+ // Events carry counts and symbolic values only: ids, enums, branch names.
12
+ const INTEGER = /^-?\d+$/;
13
+ const VALUE = /^(?:|[A-Za-z0-9][A-Za-z0-9._:/+-]{0,199})$/;
14
+ const KINDS = new Set(["production", "benchmark"]);
15
+ const STALE_MS = 7 * 24 * 60 * 60 * 1000;
16
+
17
+ export class TaskRunError extends Error {
18
+ constructor(code, message) {
19
+ super(message);
20
+ this.name = "TaskRunError";
21
+ this.code = code;
22
+ }
23
+ }
24
+
25
+ function fail(code, message) {
26
+ throw new TaskRunError(code, message);
27
+ }
28
+
29
+ function paths(root) {
30
+ const resolved = fs.realpathSync(path.resolve(root));
31
+ const dir = path.join(resolved, ".opencode", "runs");
32
+ for (const candidate of [path.join(resolved, ".opencode"), dir]) {
33
+ if (fs.existsSync(candidate) && (fs.lstatSync(candidate).isSymbolicLink() || !fs.lstatSync(candidate).isDirectory())) {
34
+ fail("unsafe_path", `${path.relative(resolved, candidate)} must be a real directory`);
35
+ }
36
+ }
37
+ return { root: resolved, dir, run: path.join(dir, "active.json"), events: path.join(dir, "active.events.jsonl") };
38
+ }
39
+
40
+ // lstat, not exists: a dangling symlink must be refused, not written through.
41
+ function requireRegularFile(file) {
42
+ const stat = fs.lstatSync(file, { throwIfNoEntry: false });
43
+ if (stat && !stat.isFile()) fail("unsafe_path", `${path.basename(file)} must be a regular file`);
44
+ return stat !== undefined;
45
+ }
46
+
47
+ function readRun(p) {
48
+ requireRegularFile(p.events);
49
+ if (!requireRegularFile(p.run)) return null;
50
+ try {
51
+ return JSON.parse(fs.readFileSync(p.run, "utf8"));
52
+ } catch {
53
+ fail("run_corrupt", ".opencode/runs/active.json is not valid JSON; a human must inspect and remove it");
54
+ }
55
+ }
56
+
57
+ function readEvents(p) {
58
+ if (!fs.existsSync(p.events)) return [];
59
+ const lines = fs.readFileSync(p.events, "utf8").split("\n").filter(Boolean);
60
+ try {
61
+ return lines.map((line) => JSON.parse(line));
62
+ } catch {
63
+ fail("run_corrupt", ".opencode/runs/active.events.jsonl is not valid JSON lines");
64
+ }
65
+ }
66
+
67
+ // The summary is written inside the root, never through a symlink that leaves
68
+ // it, and never into git's own directory.
69
+ // Case-insensitive: on macOS and Windows ".GIT" is the same directory as ".git".
70
+ const inGitDir = (relative) => relative.split(path.sep).some((segment) => segment.toLowerCase() === ".git");
71
+
72
+ function safeOutput(root, output) {
73
+ const target = path.resolve(root, output);
74
+ const relative = path.relative(root, target);
75
+ if (relative === "" || relative.startsWith("..") || path.isAbsolute(relative) || inGitDir(relative)) {
76
+ fail("unsafe_path", "output must stay inside the root and outside .git");
77
+ }
78
+ let existing = path.dirname(target);
79
+ while (!fs.existsSync(existing)) existing = path.dirname(existing);
80
+ const realExisting = path.relative(root, fs.realpathSync(existing));
81
+ if (realExisting.startsWith("..") || path.isAbsolute(realExisting) || inGitDir(realExisting)) {
82
+ fail("unsafe_path", "output must stay inside the root and outside .git");
83
+ }
84
+ requireRegularFile(target);
85
+ return { target, relative };
86
+ }
87
+
88
+ function stamp(date) {
89
+ return date.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
90
+ }
91
+
92
+ function clean(value) {
93
+ // Strip control characters so each event stays on one line.
94
+ return String(value).replace(/[\u0000-\u001f\u007f]/g, "");
95
+ }
96
+
97
+ export function startRun({ root, slug, branch, kind = "production", now = () => new Date(), random = () => crypto.randomBytes(4) }) {
98
+ if (typeof slug !== "string" || !SLUG.test(slug)) fail("invalid_argument", "slug must match [A-Za-z0-9._-]");
99
+ if (!KINDS.has(kind)) fail("invalid_argument", "kind must be production or benchmark");
100
+ if (typeof branch !== "string" || branch.length === 0) fail("invalid_argument", "branch is required");
101
+ const p = paths(root);
102
+ const existing = readRun(p);
103
+ if (existing) {
104
+ if (existing.branch === branch && existing.change === slug) return existing;
105
+ if (existing.branch === branch) fail("run_open_for_other_change", `a run for change ${existing.change} is open on this branch; close it first`);
106
+ fail("run_open_on_other_branch", `a run for branch ${existing.branch} is open; close it first`);
107
+ }
108
+ const date = now();
109
+ const run = {
110
+ schema: "oak.run/1",
111
+ run_id: `oak_${stamp(date)}_${Buffer.from(random()).toString("hex").slice(0, 8)}`,
112
+ kind,
113
+ change: slug,
114
+ branch,
115
+ repo: path.basename(p.root),
116
+ started_at: date.toISOString(),
117
+ };
118
+ fs.mkdirSync(p.dir, { recursive: true });
119
+ // The run context is local state: keep it out of git in any repository.
120
+ const ignore = path.join(p.dir, ".gitignore");
121
+ if (!requireRegularFile(ignore)) fs.writeFileSync(ignore, "*\n", { flag: "wx" });
122
+ fs.writeFileSync(p.run, `${JSON.stringify(run, null, 2)}\n`, { flag: "wx" });
123
+ fs.writeFileSync(p.events, "");
124
+ return run;
125
+ }
126
+
127
+ export function runStatus({ root, branch, now = () => new Date() }) {
128
+ const p = paths(root);
129
+ const run = readRun(p);
130
+ if (!run) return { active: false };
131
+ const age = now().getTime() - Date.parse(run.started_at);
132
+ const stale = (branch !== undefined && branch !== run.branch) || (Number.isFinite(age) && age > STALE_MS);
133
+ const events = readEvents(p).length;
134
+ return { active: true, run, stale, events };
135
+ }
136
+
137
+ export function appendRunEvent({ root, type, fields = {}, now = () => new Date() }) {
138
+ if (!RUN_EVENT_TYPES.includes(type)) fail("invalid_argument", `event type must be one of ${RUN_EVENT_TYPES.join(", ")}`);
139
+ for (const key of Object.keys(fields)) {
140
+ if (!KEY.test(key)) fail("invalid_argument", `event key ${key} must start with a lowercase letter`);
141
+ }
142
+ const p = paths(root);
143
+ const run = readRun(p);
144
+ if (!run) return null;
145
+ const event = { schema: "oak.event/1", run_id: run.run_id, at: now().toISOString(), type };
146
+ for (const [key, raw] of Object.entries(fields)) {
147
+ const value = clean(raw);
148
+ if (INTEGER.test(value)) {
149
+ event[key] = Number(value);
150
+ continue;
151
+ }
152
+ if (!VALUE.test(value)) fail("invalid_argument", `event value for ${key} must be a count or a symbolic value`);
153
+ event[key] = value;
154
+ }
155
+ fs.appendFileSync(p.events, `${JSON.stringify(event)}\n`);
156
+ return event;
157
+ }
158
+
159
+ export function closeRun({ root, output, now = () => new Date() }) {
160
+ const p = paths(root);
161
+ const run = readRun(p);
162
+ if (!run) return { active: false };
163
+ const events = readEvents(p);
164
+ const summary = { schema: "oak.run.summary/1", run, closed_at: now().toISOString(), events };
165
+ let written = null;
166
+ if (output !== undefined) {
167
+ const { target, relative } = safeOutput(p.root, output);
168
+ fs.mkdirSync(path.dirname(target), { recursive: true });
169
+ fs.writeFileSync(target, `${JSON.stringify(summary, null, 2)}\n`);
170
+ written = relative;
171
+ }
172
+ fs.rmSync(p.run, { force: true });
173
+ fs.rmSync(p.events, { force: true });
174
+ return written ? { run_id: run.run_id, path: written } : { run_id: run.run_id, summary };
175
+ }
176
+
177
+ // Read HEAD directly instead of spawning git. In a linked worktree `.git` is a
178
+ // file that points at the worktree's own git directory.
179
+ export function currentBranch(root) {
180
+ let gitDir = path.join(root, ".git");
181
+ if (fs.statSync(gitDir).isFile()) {
182
+ const pointer = fs.readFileSync(gitDir, "utf8").trim();
183
+ if (!pointer.startsWith("gitdir: ")) fail("invalid_repository", ".git file must start with gitdir:");
184
+ gitDir = path.resolve(root, pointer.slice("gitdir: ".length));
185
+ }
186
+ const head = fs.readFileSync(path.join(gitDir, "HEAD"), "utf8").trim();
187
+ return head.startsWith("ref: refs/heads/") ? head.slice("ref: refs/heads/".length) : head;
188
+ }
189
+
190
+ export function main(argv = process.argv.slice(2)) {
191
+ const [command, ...rest] = argv;
192
+ const flags = {};
193
+ const pairs = {};
194
+ for (let index = 0; index < rest.length; index += 1) {
195
+ const token = rest[index];
196
+ if (token.startsWith("--")) {
197
+ flags[token.slice(2)] = rest[index + 1];
198
+ index += 1;
199
+ } else {
200
+ const eq = token.indexOf("=");
201
+ if (eq <= 0) fail("invalid_argument", `expected key=value, got ${token}`);
202
+ pairs[token.slice(0, eq)] = token.slice(eq + 1);
203
+ }
204
+ }
205
+ const root = flags.root;
206
+ if (!root) fail("invalid_argument", "--root is required");
207
+ let result;
208
+ if (command === "start") result = startRun({ root, slug: flags.slug, branch: currentBranch(path.resolve(root)), kind: flags.kind });
209
+ else if (command === "status") result = runStatus({ root, branch: currentBranch(path.resolve(root)) });
210
+ else if (command === "event") result = appendRunEvent({ root, type: flags.type, fields: pairs });
211
+ else if (command === "close") result = closeRun({ root, output: flags.output });
212
+ else fail("invalid_argument", "command must be start, status, event or close");
213
+ if (result?.stale) process.stderr.write("warning: run context is stale\n");
214
+ process.stdout.write(`${JSON.stringify(result ?? null, null, 2)}\n`);
215
+ }
216
+
217
+ if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
218
+ try {
219
+ main();
220
+ } catch (error) {
221
+ process.stderr.write(`${error instanceof TaskRunError ? error.code : "error"}: ${error.message}\n`);
222
+ process.exit(error instanceof TaskRunError ? 2 : 1);
223
+ }
224
+ }