opencode-agent-orchestration-kit 1.0.44 → 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 (115) 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.0.45.md +77 -0
  14. package/docs/releases/v1.1.0.md +91 -0
  15. package/docs/supply-chain.md +4 -7
  16. package/docs/threat-model.md +16 -6
  17. package/docs/troubleshooting.md +7 -4
  18. package/docs/workflows.md +27 -4
  19. package/opencode/AGENTS.md +18 -10
  20. package/opencode/agents/designer.md +1 -1
  21. package/opencode/agents/developer.md +60 -6
  22. package/opencode/agents/lead.md +59 -10
  23. package/opencode/agents/reviewer.md +7 -0
  24. package/opencode/agents/scoper.md +1 -0
  25. package/opencode/agents/specifier.md +1 -0
  26. package/opencode/commands/autonomous.md +175 -24
  27. package/opencode/docs/ai/evolution/README.md +5 -4
  28. package/opencode/docs/ai/evolution/benchmarks/adversarial-scenarios.jsonl +3 -0
  29. package/opencode/docs/ai/evolution/session-sources.md +12 -0
  30. package/opencode/docs/ai/harness/agents.md +23 -6
  31. package/opencode/docs/ai/harness/checks.md +3 -2
  32. package/opencode/docs/ai/harness/commands.md +7 -4
  33. package/opencode/docs/ai/harness/skill_registry.json +107 -1
  34. package/opencode/docs/ai/harness/skill_registry.md +5 -0
  35. package/opencode/docs/ai/specs/mission-runtime.md +9 -0
  36. package/opencode/opencode.json +0 -1
  37. package/opencode/plugins/mission-runtime.test.mjs +15 -3
  38. package/opencode/plugins/mission-runtime.ts +11 -39
  39. package/opencode/plugins/oak-tui/server.ts +8 -0
  40. package/opencode/plugins/oak-tui/tui.tsx +81 -0
  41. package/opencode/plugins/open-design.ts +12 -0
  42. package/opencode/plugins/shell-export-guard.ts +13 -23
  43. package/opencode/plugins/token-tree-usage.tsx +4 -1
  44. package/opencode/runtime/v1/mission-runtime.ts +73 -0
  45. package/opencode/runtime/v1/shell-export-guard.ts +9 -0
  46. package/opencode/runtime/v2/mission-events.d.mts +13 -0
  47. package/opencode/runtime/v2/mission-events.mjs +64 -0
  48. package/opencode/runtime/v2/mission-events.test.mjs +120 -0
  49. package/opencode/runtime/v2/mission-runtime.ts +26 -0
  50. package/opencode/runtime/v2/open-design.ts +17 -0
  51. package/opencode/runtime/v2/shell-export-guard.ts +8 -0
  52. package/opencode/runtime/v2/token-usage.d.mts +15 -0
  53. package/opencode/runtime/v2/token-usage.mjs +35 -0
  54. package/opencode/runtime/v2/token-usage.test.mjs +30 -0
  55. package/opencode/scripts/adversarial-harness.test.mjs +50 -1
  56. package/opencode/scripts/check-harness.mjs +150 -33
  57. package/opencode/scripts/check-harness.test.mjs +81 -8
  58. package/opencode/scripts/collect-session-evidence.mjs +57 -39
  59. package/opencode/scripts/collect-session-evidence.test.mjs +164 -0
  60. package/opencode/scripts/deliver.d.mts +37 -0
  61. package/opencode/scripts/deliver.mjs +204 -0
  62. package/opencode/scripts/deliver.test.mjs +245 -0
  63. package/opencode/scripts/loop-state.mjs +50 -1
  64. package/opencode/scripts/loop-state.test.mjs +33 -0
  65. package/opencode/scripts/mission-runtime.test.mjs +1 -1
  66. package/opencode/scripts/mission-status.test.mjs +2 -0
  67. package/opencode/scripts/runtime-permission-policy.mjs +1 -1
  68. package/opencode/scripts/runtime-permission-policy.test.mjs +3 -2
  69. package/opencode/scripts/session-sources.d.mts +6 -0
  70. package/opencode/scripts/session-sources.mjs +49 -0
  71. package/opencode/scripts/shell-export-guard-core.d.mts +2 -0
  72. package/opencode/scripts/shell-export-guard-core.mjs +21 -0
  73. package/opencode/scripts/shell-export-guard-core.test.mjs +43 -0
  74. package/opencode/scripts/task-run.d.mts +63 -0
  75. package/opencode/scripts/task-run.mjs +224 -0
  76. package/opencode/scripts/task-run.test.mjs +178 -0
  77. package/opencode/skills/debugging-and-error-recovery/SKILL.md +20 -0
  78. package/opencode/skills/oak-adversarial-review/SKILL.md +138 -0
  79. package/opencode/skills/oak-commit/SKILL.md +69 -0
  80. package/opencode/skills/oak-enrich-task/SKILL.md +109 -0
  81. package/opencode/skills/oak-runtime-verification/SKILL.md +103 -0
  82. package/opencode/skills/oak-update-docs/SKILL.md +54 -0
  83. package/opencode/tools/open-design-tools.d.mts +17 -0
  84. package/opencode/tools/open-design-tools.mjs +254 -0
  85. package/opencode/tools/open_design.ts +26 -259
  86. package/package.json +6 -3
  87. package/scripts/benchmark-tool-paths.mjs +1 -1
  88. package/scripts/check-compatibility.mjs +58 -4
  89. package/scripts/check-compatibility.test.mjs +159 -11
  90. package/scripts/check-public-boundary.mjs +3 -0
  91. package/scripts/check-supply-chain.mjs +26 -58
  92. package/scripts/check-supply-chain.test.mjs +39 -36
  93. package/scripts/check.sh +42 -7
  94. package/scripts/manage-installation.mjs +34 -20
  95. package/scripts/manage-installation.test.mjs +29 -0
  96. package/scripts/oak.mjs +72 -2
  97. package/scripts/oak.test.mjs +69 -1
  98. package/scripts/open-design-http.test.mjs +1 -1
  99. package/scripts/open-design-tools.test.mjs +49 -0
  100. package/scripts/opencode-compat-smoke.sh +45 -4
  101. package/scripts/opencode-v2-smoke.mjs +197 -0
  102. package/scripts/opencode-v2-smoke.test.mjs +59 -0
  103. package/scripts/package-smoke.mjs +14 -0
  104. package/scripts/package-smoke.test.mjs +45 -2
  105. package/scripts/version.test.mjs +2 -2
  106. package/supply-chain.json +0 -4
  107. package/docker/open-design/data/app.sqlite +0 -0
  108. package/docker/open-design/data/app.sqlite-shm +0 -0
  109. package/docker/open-design/data/app.sqlite-wal +0 -0
  110. package/docker/open-design/opencode-auth/log/2026-05-02T105802.log +0 -17
  111. package/docker/open-design/opencode-auth/log/2026-05-04T102127.log +0 -16
  112. package/docker/open-design/opencode-auth/opencode.db +0 -0
  113. package/docker/open-design/opencode-auth/opencode.db-shm +0 -0
  114. package/docker/open-design/opencode-auth/opencode.db-wal +0 -0
  115. package/docs/superpowers.md +0 -41
@@ -728,3 +728,167 @@ test("phase-0 telemetry measures diff size for a real local git repo", async ()
728
728
  fs.rmSync(tmp, { recursive: true, force: true });
729
729
  }
730
730
  });
731
+
732
+ test("collector tags execution trees with the run that recorded their sessions", () => {
733
+ const tmp = makeTempDir();
734
+ try {
735
+ const dbPath = path.join(tmp, "opencode.db");
736
+ createFixtureDb(dbPath);
737
+ const summaryPath = path.join(tmp, "run-summary.json");
738
+ writeJson(summaryPath, {
739
+ schema: "oak.run.summary/1",
740
+ run: { run_id: "oak_20260926T100000Z_a1b2c3d4" },
741
+ events: [{ type: "agent_session", session_id: "ses_child_1" }],
742
+ });
743
+ const outDir = path.join(tmp, "out");
744
+ run(process.execPath, ["scripts/collect-session-evidence.mjs", "--output-dir", outDir, "--source", dbPath, "--full-rescan", "--run", summaryPath], { cwd: root });
745
+ const trees = fs.readFileSync(path.join(outDir, "execution-trees.jsonl"), "utf8").trim().split("\n").map((line) => JSON.parse(line));
746
+ assert.equal(trees.find((tree) => tree.root_session_id === "ses_root_1").run_id, "oak_20260926T100000Z_a1b2c3d4");
747
+ assert.equal(trees.find((tree) => tree.root_session_id === "ses_root_2").run_id, null);
748
+ } finally {
749
+ fs.rmSync(tmp, { recursive: true, force: true });
750
+ }
751
+ });
752
+
753
+ function createV2FixtureDb(dbPath, { withV1Tables = false, v1CopyUpdated = 1900 } = {}) {
754
+ if (withV1Tables) {
755
+ // OpenCode 2 imported ses_v2_root from these tables; ses_root_1 was created by
756
+ // OpenCode 1 after switching back, so it exists only here.
757
+ createFixtureDb(dbPath);
758
+ run("sqlite3", [
759
+ dbPath,
760
+ `
761
+ insert into session (id, project_id, parent_id, slug, directory, title, version, time_created, time_updated, path, agent, model) values
762
+ ('ses_v2_root', 'proj_1', null, 'calm-otter', '/tmp/repo', 'V1 copy', '1.18.4', 1000, ${v1CopyUpdated}, '', 'lead', '{"id":"m","providerID":"p"}');
763
+ insert into message (id, session_id, time_created, time_updated, data) values
764
+ ('msg_v1_copy_user', 'ses_v2_root', 1000, 1000, '{"role":"user"}');
765
+ insert into part (id, message_id, session_id, time_created, time_updated, data) values
766
+ ('prt_v1_copy_user', 'msg_v1_copy_user', 'ses_v2_root', 1000, 1000, '{"type":"text","text":"OpenCode 1 copy."}');
767
+ `,
768
+ ]);
769
+ }
770
+ const content = Array.from({ length: 11 }, (_, index) =>
771
+ index === 2 ? { type: "text", text: "First text part." }
772
+ : index === 10 ? { type: "text", text: "Eleventh content part." }
773
+ : { type: "reasoning", text: "hidden" },
774
+ );
775
+ run("sqlite3", [
776
+ dbPath,
777
+ `
778
+ create table session_v2 (
779
+ id text primary key, project_id text not null, workspace_id text, parent_id text,
780
+ slug text not null, directory text not null, path text, title text, version text not null,
781
+ cost real default 0 not null, tokens_input integer default 0 not null,
782
+ tokens_output integer default 0 not null, tokens_reasoning integer default 0 not null,
783
+ tokens_cache_read integer default 0 not null, tokens_cache_write integer default 0 not null,
784
+ agent text, model text, time_created integer not null, time_updated integer not null
785
+ );
786
+ create table session_message (
787
+ id text primary key, session_id text not null, type text not null, seq integer not null,
788
+ time_created integer not null, time_updated integer not null, data text not null
789
+ );
790
+ insert into session_v2 (id, project_id, parent_id, slug, directory, path, title, version, agent, model, cost, tokens_input, tokens_output, time_created, time_updated) values
791
+ ('ses_v2_root', 'proj_1', null, 'calm-otter', '/tmp/repo', '', 'V2 root', '2.0.18', 'lead', '{"id":"m","providerID":"p"}', 1, 100, 20, 1000, 2000),
792
+ ('ses_v2_child', 'proj_1', 'ses_v2_root', 'keen-otter', '/tmp/repo', '', 'V2 child (@researcher subagent)', '2.0.18', 'researcher', '{"id":"m","providerID":"p"}', 0.5, 10, 5, 1100, 2100),
793
+ ('ses_v2_many', 'proj_1', null, 'busy-otter', '/tmp/repo', '', 'V2 many parts', '2.0.18', 'lead', '{"id":"m","providerID":"p"}', 0, 1, 1, 5000, 5100);
794
+ insert into session_message (id, session_id, type, seq, time_created, time_updated, data) values
795
+ ('msg_v2_user_root', 'ses_v2_root', 'user', 1, 1000, 1000, '{"text":"Investigate the v2 issue.","time":{"created":1000}}'),
796
+ ('msg_v2_reasoning_root', 'ses_v2_root', 'assistant', 2, 1200, 1300, '{"agent":"lead","content":[{"type":"reasoning","text":"hidden"},{"type":"text","text":"Lead summary for the v2 issue."}]}'),
797
+ ('msg_v2_shell_root', 'ses_v2_root', 'shell', 3, 1250, 1250, '{"command":"ls"}'),
798
+ ('msg_v2_user_child', 'ses_v2_child', 'user', 1, 1100, 1100, '{"text":"Research the v2 issue."}'),
799
+ ('msg_v2_assistant_child', 'ses_v2_child', 'assistant', 2, 1400, 1500, '{"agent":"researcher","content":[{"type":"text","text":"Research findings for v2."}]}'),
800
+ ('msg_v2_many', 'ses_v2_many', 'assistant', 1, 5000, 5100, '${JSON.stringify({ agent: "lead", content })}');
801
+ `,
802
+ ]);
803
+ }
804
+
805
+ test("exact root collector reads an OpenCode 2 database", async () => {
806
+ const tmp = makeTempDir();
807
+ try {
808
+ const dbPath = path.join(tmp, "opencode.db");
809
+ createV2FixtureDb(dbPath);
810
+ const tree = await collectExecutionTreeByRoot(dbPath, "ses_v2_root");
811
+ assert.equal(tree.root_session_id, "ses_v2_root");
812
+ assert.deepEqual(tree.child_sessions.map((row) => row.session_id), ["ses_v2_child"]);
813
+ assert.equal(tree.root_session.user_prompt, "Investigate the v2 issue.");
814
+ assert.equal(tree.root_session.assistant_summary, "Lead summary for the v2 issue.");
815
+ } finally {
816
+ fs.rmSync(tmp, { recursive: true, force: true });
817
+ }
818
+ });
819
+
820
+ test("OpenCode 2 rows win for a session that is in both schemas", async () => {
821
+ const tmp = makeTempDir();
822
+ try {
823
+ const dbPath = path.join(tmp, "opencode.db");
824
+ createV2FixtureDb(dbPath, { withV1Tables: true });
825
+ const tree = await collectExecutionTreeByRoot(dbPath, "ses_v2_root");
826
+ assert.equal(tree.root_session_id, "ses_v2_root");
827
+ assert.equal(tree.root_session.title, "V2 root");
828
+ assert.equal(tree.root_session.version, "2.0.18");
829
+ assert.equal(tree.root_session.user_prompt, "Investigate the v2 issue.");
830
+ assert.equal(tree.root_session.message_count, 2);
831
+ assert.deepEqual(tree.child_sessions.map((row) => row.session_id), ["ses_v2_child"]);
832
+ } finally {
833
+ fs.rmSync(tmp, { recursive: true, force: true });
834
+ }
835
+ });
836
+
837
+ test("an imported session that OpenCode 1 kept using is read from the OpenCode 1 tables", async () => {
838
+ const tmp = makeTempDir();
839
+ try {
840
+ const dbPath = path.join(tmp, "opencode.db");
841
+ createV2FixtureDb(dbPath, { withV1Tables: true, v1CopyUpdated: 9000 });
842
+ const tree = await collectExecutionTreeByRoot(dbPath, "ses_v2_root");
843
+ assert.equal(tree.root_session.title, "V1 copy");
844
+ assert.equal(tree.root_session.user_prompt, "OpenCode 1 copy.");
845
+ assert.equal(tree.root_session.message_count, 1);
846
+ } finally {
847
+ fs.rmSync(tmp, { recursive: true, force: true });
848
+ }
849
+ });
850
+
851
+ test("a database with more parts than a call can spread is collected", async () => {
852
+ const tmp = makeTempDir();
853
+ try {
854
+ const dbPath = path.join(tmp, "opencode.db");
855
+ createFixtureDb(dbPath);
856
+ run("sqlite3", [
857
+ dbPath,
858
+ `
859
+ with recursive n(i) as (select 1 union all select i + 1 from n where i < 200000)
860
+ insert into part (id, message_id, session_id, time_created, time_updated, data)
861
+ select 'prt_bulk_' || i, 'msg_assistant_root_2', 'ses_root_2', 3300, 3300, '{"type":"step-start"}' from n;
862
+ `,
863
+ ]);
864
+ const tree = await collectExecutionTreeByRoot(dbPath, "ses_root_1");
865
+ assert.equal(tree.root_session.user_prompt, "Investigate the harness issue carefully.");
866
+ } finally {
867
+ fs.rmSync(tmp, { recursive: true, force: true });
868
+ }
869
+ });
870
+
871
+ test("OpenCode 1 sessions missing from the OpenCode 2 tables are still collected", async () => {
872
+ const tmp = makeTempDir();
873
+ try {
874
+ const dbPath = path.join(tmp, "opencode.db");
875
+ createV2FixtureDb(dbPath, { withV1Tables: true });
876
+ const tree = await collectExecutionTreeByRoot(dbPath, "ses_root_1");
877
+ assert.equal(tree.root_session.user_prompt, "Investigate the harness issue carefully.");
878
+ assert.deepEqual(tree.child_sessions.map((row) => row.session_id).sort(), ["ses_child_1", "ses_grandchild_1"]);
879
+ } finally {
880
+ fs.rmSync(tmp, { recursive: true, force: true });
881
+ }
882
+ });
883
+
884
+ test("OpenCode 2 content parts keep their numeric order", async () => {
885
+ const tmp = makeTempDir();
886
+ try {
887
+ const dbPath = path.join(tmp, "opencode.db");
888
+ createV2FixtureDb(dbPath);
889
+ const tree = await collectExecutionTreeByRoot(dbPath, "ses_v2_many");
890
+ assert.equal(tree.root_session.assistant_summary, "First text part.");
891
+ } finally {
892
+ fs.rmSync(tmp, { recursive: true, force: true });
893
+ }
894
+ });
@@ -0,0 +1,37 @@
1
+ export type DeliverErrorCode =
2
+ | "not_completed"
3
+ | "attestation_missing"
4
+ | "default_branch"
5
+ | "unsafe_branch"
6
+ | "dirty_tree"
7
+ | "no_commits"
8
+ | "unsafe_body"
9
+ | "command_failed"
10
+ | "invalid_argument";
11
+
12
+ export class DeliverError extends Error {
13
+ constructor(code: DeliverErrorCode, message: string);
14
+ code: DeliverErrorCode;
15
+ }
16
+
17
+ export type CommandRunner = (
18
+ command: string,
19
+ args: string[],
20
+ root: string,
21
+ ) => { status: number | null; stdout?: string; stderr?: string };
22
+
23
+ export function deliver(options: {
24
+ root: string;
25
+ slug: string;
26
+ title: string;
27
+ bodyFile: string;
28
+ runner?: CommandRunner;
29
+ }): { branch: string; base: string; pr_url: string };
30
+
31
+ export function prChecks(options: {
32
+ root: string;
33
+ pr: number | string;
34
+ runner?: CommandRunner;
35
+ }): Array<{ name: string; state: string; bucket: string; link: string; reason?: string }>;
36
+
37
+ export function main(argv?: string[]): void;
@@ -0,0 +1,204 @@
1
+ #!/usr/bin/env node
2
+
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { spawnSync } from "node:child_process";
7
+ import { fileURLToPath } from "node:url";
8
+ import { inspectLoopState } from "./loop-state.mjs";
9
+ import { appendRunEvent } from "./task-run.mjs";
10
+
11
+ const PRIVATE_PATHS = [
12
+ /(?:^|[\s("'`/:<[|=])\/(?:Users|home|root)\/[^\s)"'`]+/,
13
+ /(?:^|[\s("'`])~\//,
14
+ /[A-Za-z]:\\users\\/i,
15
+ ];
16
+ // A conservative subset of git branch names. It rejects a leading "+" (a
17
+ // force refspec) or "-" (an option), and every sequence git gives meaning to.
18
+ const SAFE_BRANCH = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
19
+ // OAK's own durable state may stay uncommitted; everything else must be clean.
20
+ const STATE_EXCLUDES = [":(exclude).opencode/loops", ":(exclude).opencode/runs"];
21
+
22
+ export class DeliverError extends Error {
23
+ constructor(code, message) {
24
+ super(message);
25
+ this.name = "DeliverError";
26
+ this.code = code;
27
+ }
28
+ }
29
+
30
+ function fail(code, message) {
31
+ throw new DeliverError(code, message);
32
+ }
33
+
34
+ function defaultRunner(command, args, root) {
35
+ return spawnSync(command, args, { cwd: root, shell: false, encoding: "utf8", timeout: 120_000, maxBuffer: 8 * 1024 * 1024 });
36
+ }
37
+
38
+ function run(runner, root, command, args) {
39
+ const result = runner(command, args, root);
40
+ if (result.status !== 0) {
41
+ const reason = String(result.stderr ?? "").trim().split("\n")[0];
42
+ fail("command_failed", `${command} ${args[0]} failed${reason ? `: ${reason}` : ""}`);
43
+ }
44
+ return String(result.stdout ?? "").trim();
45
+ }
46
+
47
+ function defaultBranch(runner, root) {
48
+ const result = runner("git", ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"], root);
49
+ return result.status === 0 ? String(result.stdout).trim().replace(/^origin\//, "") : "main";
50
+ }
51
+
52
+ function readAttestation(file) {
53
+ try {
54
+ if (!fs.lstatSync(file).isFile()) return null;
55
+ return JSON.parse(fs.readFileSync(file, "utf8"));
56
+ } catch {
57
+ return null;
58
+ }
59
+ }
60
+
61
+ function isSafeBranch(branch) {
62
+ return SAFE_BRANCH.test(branch)
63
+ && !branch.includes("..")
64
+ && !branch.includes("//")
65
+ && !branch.endsWith("/")
66
+ && !branch.endsWith(".")
67
+ && !branch.endsWith(".lock");
68
+ }
69
+
70
+ // Resolve the body through every symlink, keep it inside the root, and return
71
+ // its validated text so gh never re-reads a file that could change.
72
+ function readSafeBody(root, bodyFile) {
73
+ if (typeof bodyFile !== "string" || bodyFile.length === 0) fail("unsafe_body", "body file is required");
74
+ let real;
75
+ try {
76
+ real = fs.realpathSync(path.resolve(root, bodyFile));
77
+ } catch {
78
+ fail("unsafe_body", "body file must be a regular file inside the root");
79
+ }
80
+ const relative = path.relative(root, real);
81
+ if (relative.startsWith("..") || path.isAbsolute(relative) || !fs.statSync(real).isFile()) {
82
+ fail("unsafe_body", "body file must be a regular file inside the root");
83
+ }
84
+ const text = fs.readFileSync(real, "utf8");
85
+ if (PRIVATE_PATHS.some((pattern) => pattern.test(text))) fail("unsafe_body", "body file contains an absolute home path");
86
+ return text;
87
+ }
88
+
89
+ export function deliver({ root, slug, title, bodyFile, runner = defaultRunner }) {
90
+ const resolved = fs.realpathSync(path.resolve(root));
91
+ const state = inspectLoopState({ root: resolved, slug });
92
+ if (state.status !== "completed") fail("not_completed", "the loop must be completed before delivery");
93
+ const attestation = readAttestation(path.join(resolved, ".opencode", "loops", `${slug}.review.json`));
94
+ if (
95
+ attestation?.schema_version !== 1
96
+ || attestation.reviewer_agent !== "reviewer"
97
+ || attestation.reviewer_verdict !== "APPROVE"
98
+ || attestation.contract_hash !== state.approval.contract_hash
99
+ ) {
100
+ fail("attestation_missing", "delivery requires the reviewer attestation for this contract");
101
+ }
102
+ const branch = run(runner, resolved, "git", ["rev-parse", "--abbrev-ref", "HEAD"]);
103
+ if (branch !== "HEAD" && !isSafeBranch(branch)) fail("unsafe_branch", "branch name must be a plain feature branch name");
104
+ const base = defaultBranch(runner, resolved);
105
+ if (branch === base || branch === "main" || branch === "master" || branch === "HEAD") {
106
+ fail("default_branch", "delivery never pushes the default branch");
107
+ }
108
+ if (run(runner, resolved, "git", ["status", "--porcelain", "--", ".", ...STATE_EXCLUDES]) !== "") {
109
+ fail("dirty_tree", "commit or discard changes first");
110
+ }
111
+ if (Number(run(runner, resolved, "git", ["rev-list", "--count", `origin/${base}..HEAD`])) < 1) {
112
+ fail("no_commits", "the branch has no commits ahead of its base");
113
+ }
114
+ const bodyText = readSafeBody(resolved, bodyFile);
115
+ if (typeof title !== "string" || title.length === 0 || title.length > 200) fail("unsafe_body", "title must be 1-200 characters");
116
+
117
+ // An explicit destination refspec: the branch name is never parsed as one.
118
+ run(runner, resolved, "git", ["push", "--set-upstream", "origin", `HEAD:refs/heads/${branch}`]);
119
+ // A later delivery (for example a CI fix) updates the open pull request.
120
+ const existing = runner("gh", ["pr", "list", "--head", branch, "--state", "open", "--json", "url,isCrossRepository", "--jq", ".[] | select(.isCrossRepository | not) | .url"], resolved);
121
+ const existingUrl = existing.status === 0 ? String(existing.stdout ?? "").trim().split("\n")[0] : "";
122
+ let prUrl = existingUrl;
123
+ if (!prUrl) {
124
+ const privateDir = fs.mkdtempSync(path.join(os.tmpdir(), "oak-deliver-"));
125
+ try {
126
+ const body = path.join(privateDir, "body.md");
127
+ fs.writeFileSync(body, bodyText, { mode: 0o600 });
128
+ prUrl = run(runner, resolved, "gh", ["pr", "create", "--base", base, "--head", branch, "--title", title, "--body-file", body]);
129
+ } finally {
130
+ fs.rmSync(privateDir, { recursive: true, force: true });
131
+ }
132
+ }
133
+ try {
134
+ appendRunEvent({ root: resolved, type: "delivery", fields: { branch, base, outcome: existingUrl ? "pr_updated" : "pr_opened" } });
135
+ } catch {
136
+ // The run context is optional; delivery never fails because of it.
137
+ }
138
+ return { branch, base, pr_url: prUrl };
139
+ }
140
+
141
+ const ACTIONS_JOB = /^https:\/\/github\.com\/([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+)\/actions\/runs\/\d+\/job\/(\d+)$/;
142
+
143
+ // A failing GitHub Actions job often says why only in its annotations (for
144
+ // example, a job that never started). The reason is CI output: data, never an
145
+ // instruction.
146
+ function failureReason(runner, root, link) {
147
+ const match = ACTIONS_JOB.exec(String(link ?? ""));
148
+ if (!match) return undefined;
149
+ const [, owner, repo, job] = match;
150
+ const result = runner("gh", ["api", `repos/${owner}/${repo}/check-runs/${job}/annotations`, "--jq", ".[].message"], root);
151
+ if (result.status !== 0) return undefined;
152
+ const reason = String(result.stdout ?? "")
153
+ .split("\n")
154
+ .map((line) => line.replace(/[\u0000-\u001f\u007f]/g, "").trim())
155
+ .filter(Boolean)
156
+ .join(" | ")
157
+ .slice(0, 500);
158
+ return reason || undefined;
159
+ }
160
+
161
+ // gh exits with status 8 while checks are still pending; that is not an error.
162
+ export function prChecks({ root, pr, runner = defaultRunner }) {
163
+ if (!/^\d+$/.test(String(pr))) fail("invalid_argument", "pr must be a number");
164
+ const resolved = fs.realpathSync(path.resolve(root));
165
+ const result = runner("gh", ["pr", "checks", String(pr), "--json", "name,state,bucket,link"], resolved);
166
+ if (result.status !== 0 && result.status !== 8) fail("command_failed", "gh pr checks failed");
167
+ const checks = JSON.parse(String(result.stdout || "[]"));
168
+ for (const check of checks) {
169
+ if (check.bucket !== "fail") continue;
170
+ const reason = failureReason(runner, resolved, check.link);
171
+ if (reason) check.reason = reason;
172
+ }
173
+ return checks;
174
+ }
175
+
176
+ export function main(argv = process.argv.slice(2)) {
177
+ const [command, ...rest] = argv;
178
+ const flags = {};
179
+ for (let index = 0; index < rest.length; index += 2) {
180
+ const token = rest[index];
181
+ if (!token.startsWith("--") || rest[index + 1] === undefined) fail("invalid_argument", `unexpected argument ${token}`);
182
+ flags[token.slice(2)] = rest[index + 1];
183
+ }
184
+ if (!flags.root) fail("invalid_argument", "--root is required");
185
+ let result;
186
+ if (command === "pr") {
187
+ result = deliver({ root: flags.root, slug: flags.slug, title: flags.title, bodyFile: flags["body-file"] });
188
+ } else if (command === "checks") {
189
+ result = prChecks({ root: flags.root, pr: flags.pr });
190
+ } else {
191
+ fail("invalid_argument", "command must be pr or checks");
192
+ }
193
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`);
194
+ }
195
+
196
+ if (process.argv[1] && fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) {
197
+ try {
198
+ main();
199
+ } catch (error) {
200
+ const known = error instanceof DeliverError || error?.name === "LoopStateError";
201
+ process.stderr.write(`${known ? error.code : "error"}: ${error.message}\n`);
202
+ process.exit(known ? 2 : 1);
203
+ }
204
+ }
@@ -0,0 +1,245 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "node:path";
5
+ import test from "node:test";
6
+ import { acquireLoop, attestReview, initLoopState, recordLoopAction } from "./loop-state.mjs";
7
+ import { DeliverError, deliver, prChecks } from "./deliver.mjs";
8
+
9
+ function completedLoop({ attest = true, complete = true } = {}) {
10
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "oak-deliver-"));
11
+ fs.mkdirSync(path.join(root, ".opencode/loops"), { recursive: true });
12
+ const contractPath = path.join(root, ".opencode/loops/task.md");
13
+ fs.writeFileSync(contractPath, "# Contract\n");
14
+ initLoopState({ root, slug: "task", contractPath, gitBaseline: "abc", sessionId: "s1", actionId: "a1", plannedIterations: 2 });
15
+ acquireLoop({ root, slug: "task", contractPath, sessionId: "s1", actionId: "a2" });
16
+ if (attest) attestReview({ root, slug: "task", reviewerSessionId: "child", reviewerAgent: "reviewer", reviewerVerdict: "APPROVE" });
17
+ if (complete) recordLoopAction({ root, slug: "task", sessionId: "s1", actionId: "a3", iteration: 1, completedStep: "reviewer_approved", blockingCause: null, status: "completed" });
18
+ fs.writeFileSync(path.join(root, "pr-body.md"), "## What\nA change.\n");
19
+ return root;
20
+ }
21
+
22
+ function fakeRunner(overrides = {}) {
23
+ const calls = [];
24
+ const replies = {
25
+ "git rev-parse": "feat/x",
26
+ "git symbolic-ref": "origin/main",
27
+ "git status": "",
28
+ "git rev-list": "2",
29
+ "git push": "",
30
+ "gh pr create": "https://github.com/example/repo/pull/7",
31
+ ...overrides,
32
+ };
33
+ const runner = (command, args) => {
34
+ calls.push([command, args]);
35
+ const key = command === "gh" ? `${command} ${args[0]} ${args[1]}` : `${command} ${args[0]}`;
36
+ const reply = replies[key];
37
+ return reply === undefined ? { status: 1, stdout: "", stderr: "unexpected" } : { status: 0, stdout: `${reply}\n`, stderr: "" };
38
+ };
39
+ return { runner, calls };
40
+ }
41
+
42
+ const pushedOrOpened = (calls) => calls.some(([command, args]) => (command === "git" && args[0] === "push") || command === "gh");
43
+
44
+ function refusal(t, code, { loop = {}, runner = {}, input = {} } = {}) {
45
+ const root = completedLoop(loop);
46
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
47
+ const fake = fakeRunner(runner);
48
+ assert.throws(
49
+ () => deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner: fake.runner, ...input }),
50
+ (error) => error instanceof DeliverError && error.code === code,
51
+ );
52
+ assert.equal(pushedOrOpened(fake.calls), false);
53
+ }
54
+
55
+ test("refuses when the loop is not completed", (t) => {
56
+ const root = completedLoop({ complete: false });
57
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
58
+ const fake = fakeRunner();
59
+ assert.throws(() => deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner: fake.runner }), (error) => error.code === "not_completed");
60
+ assert.equal(fake.calls.length, 0);
61
+ });
62
+ test("refuses on the default branch", (t) => refusal(t, "default_branch", { runner: { "git rev-parse": "main" } }));
63
+ test("refuses master even when origin/HEAD is unknown", (t) => refusal(t, "default_branch", { runner: { "git rev-parse": "master", "git symbolic-ref": undefined } }));
64
+ test("refuses a dirty tree", (t) => refusal(t, "dirty_tree", { runner: { "git status": " M src/a.js" } }));
65
+ test("refuses a branch with no commits ahead of base", (t) => refusal(t, "no_commits", { runner: { "git rev-list": "0" } }));
66
+ test("refuses a body file outside the root", (t) => refusal(t, "unsafe_body", { input: { bodyFile: "../outside.md" } }));
67
+
68
+ test("refuses a body that leaks an absolute home path", (t) => {
69
+ const root = completedLoop();
70
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
71
+ fs.writeFileSync(path.join(root, "pr-body.md"), "Evidence at /home/someone/tmp/shot.png\n");
72
+ const fake = fakeRunner();
73
+ assert.throws(() => deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner: fake.runner }), (error) => error.code === "unsafe_body");
74
+ assert.equal(pushedOrOpened(fake.calls), false);
75
+ });
76
+
77
+ test("pushes without force and opens the PR against the default branch", (t) => {
78
+ const root = completedLoop();
79
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
80
+ const fake = fakeRunner();
81
+ const result = deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner: fake.runner });
82
+ assert.deepEqual(result, { branch: "feat/x", base: "main", pr_url: "https://github.com/example/repo/pull/7" });
83
+ assert.deepEqual(fake.calls.find(([command, args]) => command === "git" && args[0] === "push"), ["git", ["push", "--set-upstream", "origin", "HEAD:refs/heads/feat/x"]]);
84
+ const pr = fake.calls.find(([command, args]) => command === "gh" && args[1] === "create");
85
+ assert.deepEqual(pr[1].slice(0, 8), ["pr", "create", "--base", "main", "--head", "feat/x", "--title", "Add x"]);
86
+ const flat = fake.calls.flatMap(([command, args]) => [command, ...args]);
87
+ for (const forbidden of ["--force", "--force-with-lease", "merge", "--auto"]) assert.equal(flat.includes(forbidden), false, forbidden);
88
+ });
89
+
90
+ test("checks returns gh JSON, tolerates pending status 8 and never merges", (t) => {
91
+ const root = completedLoop();
92
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
93
+ const calls = [];
94
+ const runner = (command, args) => {
95
+ calls.push([command, args]);
96
+ return { status: 8, stdout: '[{"name":"check","state":"PENDING","bucket":"pending","link":"https://example.test"}]', stderr: "" };
97
+ };
98
+ assert.deepEqual(prChecks({ root, pr: 7, runner }), [{ name: "check", state: "PENDING", bucket: "pending", link: "https://example.test" }]);
99
+ assert.deepEqual(calls, [["gh", ["pr", "checks", "7", "--json", "name,state,bucket,link"]]]);
100
+ assert.throws(() => prChecks({ root, pr: "7; rm -rf /", runner }), /pr must be a number/);
101
+ });
102
+
103
+ test("the dirty-tree check ignores OAK's own loop and run state", (t) => {
104
+ const root = completedLoop();
105
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
106
+ const fake = fakeRunner();
107
+ deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner: fake.runner });
108
+ const status = fake.calls.find(([command, args]) => command === "git" && args[0] === "status");
109
+ assert.deepEqual(status[1], ["status", "--porcelain", "--", ".", ":(exclude).opencode/loops", ":(exclude).opencode/runs"]);
110
+ });
111
+
112
+ test("refuses a malformed attestation file", (t) => {
113
+ const root = completedLoop();
114
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
115
+ fs.writeFileSync(path.join(root, ".opencode/loops/task.review.json"), "{not json");
116
+ const fake = fakeRunner();
117
+ assert.throws(() => deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner: fake.runner }), (error) => error.code === "attestation_missing");
118
+ assert.equal(fake.calls.length, 0);
119
+ });
120
+
121
+ test("refuses a missing body file", (t) => refusal(t, "unsafe_body", { input: { bodyFile: "missing.md" } }));
122
+
123
+ test("a second delivery pushes to the existing pull request instead of opening another", (t) => {
124
+ const root = completedLoop();
125
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
126
+ const fake = fakeRunner({ "gh pr list": "https://github.com/example/repo/pull/7" });
127
+ const result = deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner: fake.runner });
128
+ assert.equal(result.pr_url, "https://github.com/example/repo/pull/7");
129
+ assert.equal(fake.calls.some(([command, args]) => command === "gh" && args[1] === "create"), false);
130
+ assert.deepEqual(fake.calls.find(([command, args]) => command === "gh" && args[1] === "list")[1], ["pr", "list", "--head", "feat/x", "--state", "open", "--json", "url,isCrossRepository", "--jq", ".[] | select(.isCrossRepository | not) | .url"]);
131
+ assert.ok(fake.calls.some(([command, args]) => command === "git" && args[0] === "push"));
132
+ });
133
+
134
+ for (const branch of ["+main", "-f", "feat/../main", "feat x", "feat/x.lock", "feat//x", "feat/x/", "@{-1}"]) {
135
+ test(`refuses the unsafe branch name ${JSON.stringify(branch)}`, (t) => refusal(t, "unsafe_branch", { runner: { "git rev-parse": branch } }));
136
+ }
137
+
138
+ test("refuses a body file reached through a symlinked directory outside the root", (t) => {
139
+ const root = completedLoop();
140
+ const outside = fs.mkdtempSync(path.join(os.tmpdir(), "oak-deliver-outside-"));
141
+ t.after(() => {
142
+ fs.rmSync(root, { recursive: true, force: true });
143
+ fs.rmSync(outside, { recursive: true, force: true });
144
+ });
145
+ fs.writeFileSync(path.join(outside, "body.md"), "## What\nOutside.\n");
146
+ fs.symlinkSync(outside, path.join(root, "sub"));
147
+ const fake = fakeRunner();
148
+ assert.throws(() => deliver({ root, slug: "task", title: "Add x", bodyFile: "sub/body.md", runner: fake.runner }), (error) => error.code === "unsafe_body");
149
+ assert.equal(pushedOrOpened(fake.calls), false);
150
+ });
151
+
152
+ for (const leak of ["file:///home/someone/x.png", "see ~/notes.md", "at /root/secret", "C:\\Users\\someone\\x"]) {
153
+ test(`refuses a body that leaks ${JSON.stringify(leak)}`, (t) => {
154
+ const root = completedLoop();
155
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
156
+ fs.writeFileSync(path.join(root, "pr-body.md"), `Evidence ${leak}\n`);
157
+ const fake = fakeRunner();
158
+ assert.throws(() => deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner: fake.runner }), (error) => error.code === "unsafe_body");
159
+ assert.equal(pushedOrOpened(fake.calls), false);
160
+ });
161
+ }
162
+
163
+ test("gh receives a private copy of the validated body, not the repository file", (t) => {
164
+ const root = completedLoop();
165
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
166
+ let seen = null;
167
+ const fake = fakeRunner();
168
+ const runner = (command, args, cwd) => {
169
+ if (command === "gh" && args[1] === "create") {
170
+ const file = args[args.indexOf("--body-file") + 1];
171
+ seen = { file, text: fs.readFileSync(file, "utf8") };
172
+ }
173
+ return fake.runner(command, args, cwd);
174
+ };
175
+ deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner });
176
+ assert.equal(seen.text, "## What\nA change.\n");
177
+ assert.notEqual(path.dirname(seen.file), root);
178
+ assert.equal(fs.existsSync(seen.file), false, "the private copy is removed after delivery");
179
+ });
180
+
181
+ test("refuses an attestation with the wrong schema or reached through a symlink", (t) => {
182
+ const root = completedLoop();
183
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
184
+ const file = path.join(root, ".opencode/loops/task.review.json");
185
+ const valid = JSON.parse(fs.readFileSync(file, "utf8"));
186
+ fs.writeFileSync(file, JSON.stringify({ ...valid, schema_version: 2 }));
187
+ assert.throws(() => deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner: fakeRunner().runner }), (error) => error.code === "attestation_missing");
188
+ const elsewhere = path.join(root, "elsewhere.json");
189
+ fs.writeFileSync(elsewhere, JSON.stringify(valid));
190
+ fs.rmSync(file);
191
+ fs.symlinkSync(elsewhere, file);
192
+ assert.throws(() => deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner: fakeRunner().runner }), (error) => error.code === "attestation_missing");
193
+ });
194
+
195
+ test("a failed command reports its first stderr line", (t) => {
196
+ const root = completedLoop();
197
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
198
+ const runner = (command, args) => (command === "git" && args[0] === "rev-parse"
199
+ ? { status: 128, stdout: "", stderr: "fatal: not a git repository\nmore" }
200
+ : { status: 0, stdout: "" });
201
+ assert.throws(() => deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner }), /git rev-parse failed: fatal: not a git repository$/);
202
+ });
203
+
204
+ for (const leak of ["[shot](/home/someone/x.png)", "</home/someone/x>", "path=/home/someone", "|/home/someone|", "C:\\users\\someone"]) {
205
+ test(`refuses a body that leaks ${JSON.stringify(leak)} in markup`, (t) => {
206
+ const root = completedLoop();
207
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
208
+ fs.writeFileSync(path.join(root, "pr-body.md"), `Evidence ${leak}\n`);
209
+ assert.throws(() => deliver({ root, slug: "task", title: "Add x", bodyFile: "pr-body.md", runner: fakeRunner().runner }), (error) => error.code === "unsafe_body");
210
+ });
211
+ }
212
+
213
+ test("checks attaches the reason of a failing GitHub Actions job from its annotations", (t) => {
214
+ const root = completedLoop();
215
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
216
+ const calls = [];
217
+ const link = "https://github.com/example/repo/actions/runs/36336266127/job/108667575936";
218
+ const runner = (command, args) => {
219
+ calls.push([command, args]);
220
+ if (args[0] === "pr") {
221
+ return { status: 0, stdout: JSON.stringify([
222
+ { name: "test", state: "FAILURE", bucket: "fail", link },
223
+ { name: "lint", state: "SUCCESS", bucket: "pass", link: "https://github.com/example/repo/actions/runs/1/job/2" },
224
+ ]) };
225
+ }
226
+ return { status: 0, stdout: "The job was not started because recent account payments have failed.\nThe ubuntu-latest label will migrate.\n" };
227
+ };
228
+ const checks = prChecks({ root, pr: 7, runner });
229
+ assert.equal(checks[0].reason, "The job was not started because recent account payments have failed. | The ubuntu-latest label will migrate.");
230
+ assert.equal(Object.hasOwn(checks[1], "reason"), false);
231
+ assert.deepEqual(calls[1], ["gh", ["api", "repos/example/repo/check-runs/108667575936/annotations", "--jq", ".[].message"]]);
232
+ assert.equal(calls.length, 2, "annotations are fetched only for failing checks");
233
+ });
234
+
235
+ test("checks never builds an API path from an unexpected link", (t) => {
236
+ const root = completedLoop();
237
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
238
+ const calls = [];
239
+ const runner = (command, args) => {
240
+ calls.push(args);
241
+ return { status: 0, stdout: JSON.stringify([{ name: "x", state: "FAILURE", bucket: "fail", link: "https://evil.test/a/b/actions/runs/1/job/2" }]) };
242
+ };
243
+ assert.equal(prChecks({ root, pr: 7, runner })[0].reason, undefined);
244
+ assert.equal(calls.length, 1);
245
+ });