opencode-agent-orchestration-kit 1.0.39 → 1.0.41

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 (51) hide show
  1. package/README.md +12 -3
  2. package/docker/open-design/data/app.sqlite +0 -0
  3. package/docker/open-design/data/app.sqlite-shm +0 -0
  4. package/docker/open-design/data/app.sqlite-wal +0 -0
  5. package/docker/open-design/opencode-auth/log/2026-05-02T105802.log +17 -0
  6. package/docker/open-design/opencode-auth/log/2026-05-04T102127.log +16 -0
  7. package/docker/open-design/opencode-auth/opencode.db +0 -0
  8. package/docker/open-design/opencode-auth/opencode.db-shm +0 -0
  9. package/docker/open-design/opencode-auth/opencode.db-wal +0 -0
  10. package/docs/models.md +1 -1
  11. package/docs/performance/native-tools-benchmark.md +33 -0
  12. package/docs/releases/v1.0.40.md +55 -0
  13. package/docs/releases/v1.0.41.md +42 -0
  14. package/docs/sync-boundary.md +27 -0
  15. package/opencode/commands/loop-status.md +24 -0
  16. package/opencode/commands/loop.md +8 -0
  17. package/opencode/docs/ai/harness/agents.md +8 -0
  18. package/opencode/docs/ai/harness/checks.md +6 -0
  19. package/opencode/docs/ai/harness/commands.md +10 -0
  20. package/opencode/docs/ai/harness/orchestration-contracts.json +9 -1
  21. package/opencode/docs/ai/specs/mission-runtime.md +44 -0
  22. package/opencode/plugins/mission-runtime.test.mjs +46 -0
  23. package/opencode/plugins/mission-runtime.ts +41 -0
  24. package/opencode/scripts/check-harness.mjs +111 -0
  25. package/opencode/scripts/check-harness.test.mjs +37 -1
  26. package/opencode/scripts/loop-state.mjs +5 -0
  27. package/opencode/scripts/loop-state.test.mjs +13 -0
  28. package/opencode/scripts/mission-runtime-observer.d.mts +25 -0
  29. package/opencode/scripts/mission-runtime-observer.mjs +124 -0
  30. package/opencode/scripts/mission-runtime.test.mjs +97 -0
  31. package/opencode/scripts/mission-status.mjs +136 -0
  32. package/opencode/scripts/mission-status.test.mjs +196 -0
  33. package/opencode/scripts/project-capability-snapshot.mjs +2 -1
  34. package/opencode/scripts/project-capability-snapshot.test.mjs +17 -0
  35. package/opencode/scripts/runtime-permission-policy.mjs +72 -0
  36. package/opencode/scripts/runtime-permission-policy.test.mjs +89 -0
  37. package/opencode/tools/open_design.ts +1 -1
  38. package/package.json +3 -3
  39. package/scripts/benchmark-tool-paths.mjs +226 -0
  40. package/scripts/benchmark-tool-paths.test.mjs +29 -0
  41. package/scripts/check-public-boundary.mjs +89 -0
  42. package/scripts/check-public-boundary.test.mjs +32 -0
  43. package/scripts/check.sh +15 -10
  44. package/scripts/install-smoke.sh +17 -0
  45. package/scripts/manage-installation.mjs +90 -7
  46. package/scripts/manage-installation.test.mjs +36 -0
  47. package/scripts/oc-switch.mjs +2 -1
  48. package/scripts/oc-switch.test.mjs +38 -0
  49. package/scripts/package-smoke.mjs +52 -3
  50. package/scripts/package-smoke.test.mjs +6 -6
  51. package/scripts/version.test.mjs +2 -2
@@ -17,7 +17,7 @@ function makeFixture() {
17
17
  const rel = path.relative(root, source);
18
18
  if (rel === ".git" || rel.startsWith(`.git${path.sep}`)) return false;
19
19
  if (rel === ".codegraph" || rel.startsWith(`.codegraph${path.sep}`)) return false;
20
- if (rel === "node_modules" || rel.startsWith(`node_modules${path.sep}`)) return false;
20
+ if (rel.split(path.sep).includes("node_modules")) return false;
21
21
  return true;
22
22
  },
23
23
  });
@@ -107,6 +107,42 @@ test("shell export guard surfaces are required", () => {
107
107
  }
108
108
  });
109
109
 
110
+ for (const [label, mutate, diagnostic] of [
111
+ [
112
+ "missing the Open Design project URL guard",
113
+ (source) => source.replace(
114
+ 'if (/\\/projects(?:\\/|$)/.test(url)) {',
115
+ "if (false) {",
116
+ ),
117
+ /tools\/open_design\.ts: missing Open Design project-path guard/,
118
+ ],
119
+ [
120
+ "using randomUUID",
121
+ (source) => `${source}\nconst randomUUID = true\n`,
122
+ /tools\/open_design\.ts: Open Design tool must not depend on randomUUID/,
123
+ ],
124
+ [
125
+ "containing a private endpoint",
126
+ (source) => `${source}\nconst endpoint = "https://private.synology.example"\n`,
127
+ /tools\/open_design\.ts: Open Design tool contains a private endpoint or local path/,
128
+ ],
129
+ ]) {
130
+ test(`Open Design contract rejects ${label}`, () => {
131
+ const cwd = makeFixture();
132
+ try {
133
+ const rel = "tools/open_design.ts";
134
+ const source = fs.readFileSync(path.join(cwd, rel), "utf8");
135
+ write(rel, mutate(source), cwd);
136
+
137
+ const result = runHarness(cwd);
138
+ assert.notEqual(result.status, 0, `checker accepted Open Design source ${label}`);
139
+ assert.match(result.stderr, diagnostic);
140
+ } finally {
141
+ fs.rmSync(cwd, { recursive: true, force: true });
142
+ }
143
+ });
144
+ }
145
+
110
146
  test("orchestration contract file must be regular and non-symlink", () => {
111
147
  const cwd = makeFixture();
112
148
  const external = path.join(cwd, "external-contract.json");
@@ -787,6 +787,11 @@ export function inspectLoopState({ root, slug }) {
787
787
  return structuredClone(state);
788
788
  }
789
789
 
790
+ export function readLoopHistory({ root, slug }) {
791
+ const paths = pathsFor(root, slug);
792
+ return structuredClone(readHistory(paths).events);
793
+ }
794
+
790
795
  export function acquireLoop({
791
796
  root,
792
797
  slug,
@@ -12,6 +12,7 @@ import {
12
12
  initLoopState,
13
13
  inspectLoopState,
14
14
  migrateLoopState,
15
+ readLoopHistory,
15
16
  recordLoopAction,
16
17
  releaseLoop,
17
18
  repairLoopState,
@@ -588,6 +589,18 @@ test("exposes the durable operations through the portable CLI", () => {
588
589
  });
589
590
  });
590
591
 
592
+ test("readLoopHistory returns validated append-only events without changing state", () => {
593
+ withRepo(({ root, contractPath }) => {
594
+ const before = initExample(root, contractPath, 1);
595
+ const history = readLoopHistory({ root, slug: "example" });
596
+
597
+ assert.equal(history.length, 1);
598
+ assert.equal(history[0].type, "initialized");
599
+ assert.equal(history[0].state_after.last_action_id, before.last_action_id);
600
+ assert.deepEqual(inspectLoopState({ root, slug: "example" }), before);
601
+ });
602
+ });
603
+
591
604
  test("rejects a symlinked state ancestor that escapes the root", () => {
592
605
  const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-loop-root-"));
593
606
  const outside = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-loop-outside-"));
@@ -0,0 +1,25 @@
1
+ export type MissionActivity = "running" | "idle" | "blocked";
2
+
3
+ export type MissionObservation = {
4
+ activity: MissionActivity;
5
+ event_type: string;
6
+ session_id: string;
7
+ event_count: number;
8
+ };
9
+
10
+ export type MissionObserver = {
11
+ observe(event: unknown): Promise<MissionObservation | { ignored: string; session_id?: string }>;
12
+ stats(): {
13
+ root_session_id?: string;
14
+ child_session_ids: string[];
15
+ event_count: number;
16
+ unique_event_count: number;
17
+ };
18
+ };
19
+
20
+ export function createMissionObserver(options?: {
21
+ notify?: (observation: MissionObservation) => Promise<void>;
22
+ log?: (message: string) => void;
23
+ }): MissionObserver;
24
+
25
+ export const ACTIVITIES: ReadonlySet<MissionActivity>;
@@ -0,0 +1,124 @@
1
+ const ACTIVITIES = new Set(["running", "idle", "blocked"]);
2
+
3
+ function isObject(value) {
4
+ return value !== null && typeof value === "object" && !Array.isArray(value);
5
+ }
6
+
7
+ function stable(value) {
8
+ if (Array.isArray(value)) return value.map(stable);
9
+ if (!isObject(value)) return value;
10
+ return Object.fromEntries(
11
+ Object.keys(value).sort().map((key) => [key, stable(value[key])]),
12
+ );
13
+ }
14
+
15
+ function sessionIdFrom(event) {
16
+ const properties = event?.properties;
17
+ if (typeof properties?.sessionID === "string" && properties.sessionID) {
18
+ return properties.sessionID;
19
+ }
20
+ if (typeof properties?.info?.id === "string" && properties.info.id) {
21
+ return properties.info.id;
22
+ }
23
+ return undefined;
24
+ }
25
+
26
+ function activityFrom(event) {
27
+ const type = event?.type;
28
+ if (type === "session.status") {
29
+ const status = event.properties?.status;
30
+ if (status?.type === "idle") return "idle";
31
+ if (status?.type === "busy" || status?.type === "retry") return "running";
32
+ }
33
+ if (type === "session.idle") return "idle";
34
+ if (type === "session.error") return "blocked";
35
+ if (
36
+ type === "tool.execute.before"
37
+ || type === "tool.execute.after"
38
+ || type === "session.compacted"
39
+ || type === "chat.message"
40
+ ) {
41
+ return "running";
42
+ }
43
+ return undefined;
44
+ }
45
+
46
+ function eventKey(event, sessionId) {
47
+ return JSON.stringify(stable({
48
+ type: event?.type ?? null,
49
+ session_id: sessionId ?? null,
50
+ properties: event?.properties ?? null,
51
+ }));
52
+ }
53
+
54
+ export function createMissionObserver({ notify = async () => {}, log = () => {} } = {}) {
55
+ const childSessions = new Set();
56
+ const seenEvents = new Set();
57
+ let rootSessionId;
58
+ let eventCount = 0;
59
+
60
+ const observe = async (event) => {
61
+ eventCount += 1;
62
+ const properties = isObject(event?.properties) ? event.properties : {};
63
+ const info = properties.info;
64
+ if (isObject(info) && typeof info.id === "string" && info.parentID) {
65
+ childSessions.add(info.id);
66
+ } else if (
67
+ event?.type === "session.created"
68
+ && isObject(info)
69
+ && typeof info.id === "string"
70
+ && !info.parentID
71
+ && !rootSessionId
72
+ ) {
73
+ rootSessionId = info.id;
74
+ }
75
+
76
+ const sessionId = sessionIdFrom(event);
77
+ if (sessionId && childSessions.has(sessionId)) {
78
+ return { ignored: "child_session", session_id: sessionId };
79
+ }
80
+
81
+ const key = eventKey(event, sessionId);
82
+ if (seenEvents.has(key)) {
83
+ return { ignored: "duplicate", session_id: sessionId };
84
+ }
85
+ seenEvents.add(key);
86
+
87
+ const activity = activityFrom(event);
88
+ if (!activity || !sessionId) {
89
+ return { ignored: "unobservable", session_id: sessionId };
90
+ }
91
+
92
+ const observation = {
93
+ activity,
94
+ event_type: event.type,
95
+ session_id: sessionId,
96
+ event_count: eventCount,
97
+ };
98
+ try {
99
+ await notify(observation);
100
+ } catch (error) {
101
+ try {
102
+ log(`[mission-runtime] notification failed: ${error instanceof Error ? error.name : "unknown"}`);
103
+ } catch {
104
+ // Logging is best effort and must not affect the loop.
105
+ }
106
+ return { ...observation, notification_error: true };
107
+ }
108
+ return observation;
109
+ };
110
+
111
+ return {
112
+ observe,
113
+ stats() {
114
+ return {
115
+ root_session_id: rootSessionId,
116
+ child_session_ids: [...childSessions].sort(),
117
+ event_count: eventCount,
118
+ unique_event_count: seenEvents.size,
119
+ };
120
+ },
121
+ };
122
+ }
123
+
124
+ export { ACTIVITIES };
@@ -0,0 +1,97 @@
1
+ import assert from "node:assert/strict";
2
+ import fs from "node:fs";
3
+ import path from "node:path";
4
+ import test from "node:test";
5
+ import { fileURLToPath } from "node:url";
6
+
7
+ import { createMissionObserver } from "./mission-runtime-observer.mjs";
8
+
9
+ const root = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
10
+
11
+ function rootCreated(id = "root-1") {
12
+ return {
13
+ type: "session.created",
14
+ properties: { info: { id, parentID: null } },
15
+ };
16
+ }
17
+
18
+ function status(sessionID, type) {
19
+ return {
20
+ type: "session.status",
21
+ properties: { sessionID, status: { type } },
22
+ };
23
+ }
24
+
25
+ test("derives running to idle without touching durable loop state", async () => {
26
+ const observations = [];
27
+ const observer = createMissionObserver({ notify: async value => observations.push(value) });
28
+
29
+ await observer.observe(rootCreated());
30
+ await observer.observe(status("root-1", "busy"));
31
+ await observer.observe({ type: "session.idle", properties: { sessionID: "root-1" } });
32
+
33
+ assert.deepEqual(observations.map(item => item.activity), ["running", "idle"]);
34
+ assert.equal(observer.stats().root_session_id, "root-1");
35
+ });
36
+
37
+ test("maps errors to blocked and compaction back to running for the same session", async () => {
38
+ const observations = [];
39
+ const observer = createMissionObserver({ notify: async value => observations.push(value) });
40
+
41
+ await observer.observe(rootCreated("root-2"));
42
+ await observer.observe({ type: "session.error", properties: { sessionID: "root-2" } });
43
+ await observer.observe({ type: "session.compacted", properties: { sessionID: "root-2" } });
44
+
45
+ assert.deepEqual(observations.map(item => [item.activity, item.session_id]), [
46
+ ["blocked", "root-2"],
47
+ ["running", "root-2"],
48
+ ]);
49
+ });
50
+
51
+ test("ignores child sessions and duplicate events", async () => {
52
+ const observations = [];
53
+ const observer = createMissionObserver({ notify: async value => observations.push(value) });
54
+ const childCreated = {
55
+ type: "session.created",
56
+ properties: { info: { id: "child-1", parentID: "root-3" } },
57
+ };
58
+
59
+ await observer.observe(rootCreated("root-3"));
60
+ await observer.observe(childCreated);
61
+ await observer.observe(status("child-1", "busy"));
62
+ const rootStatus = status("root-3", "busy");
63
+ await observer.observe(rootStatus);
64
+ await observer.observe(rootStatus);
65
+
66
+ assert.equal(observations.length, 1);
67
+ assert.equal(observations[0].session_id, "root-3");
68
+ assert.deepEqual(observer.stats(), {
69
+ root_session_id: "root-3",
70
+ child_session_ids: ["child-1"],
71
+ event_count: 5,
72
+ unique_event_count: 2,
73
+ });
74
+ });
75
+
76
+ test("notification failures are logged and never escape the observer", async () => {
77
+ const logs = [];
78
+ const observer = createMissionObserver({
79
+ notify: async () => { throw new Error("transport down"); },
80
+ log: message => logs.push(message),
81
+ });
82
+
83
+ await observer.observe(rootCreated("root-4"));
84
+ const result = await observer.observe(status("root-4", "busy"));
85
+
86
+ assert.equal(result.notification_error, true);
87
+ assert.deepEqual(logs, ["[mission-runtime] notification failed: Error"]);
88
+ });
89
+
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");
92
+ assert.match(source, /event:/);
93
+ assert.match(source, /chat\.message/);
94
+ assert.match(source, /showToast/);
95
+ assert.doesNotMatch(source, /fs\.|writeFile|appendFile|rename|\.opencode\/loops/);
96
+ assert.match(source, /mission-runtime-observer\.mjs/);
97
+ });
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ import {
7
+ LoopStateError,
8
+ inspectLoopState,
9
+ readLoopHistory,
10
+ } from "./loop-state.mjs";
11
+
12
+ const slugPattern = /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/;
13
+
14
+ const NEXT_ACTIONS = Object.freeze({
15
+ approved: "resume after confirming the approved contract",
16
+ running: "continue only within the persisted iteration budget",
17
+ paused: "validate the contract and lock, then resume explicitly",
18
+ blocked: "inspect the blocking cause and resolve it before resuming",
19
+ completed: "no further action; start a new loop if more work is needed",
20
+ });
21
+
22
+ function fail(code, message) {
23
+ throw new LoopStateError(code, message);
24
+ }
25
+
26
+ function requireSlug(slug) {
27
+ if (typeof slug !== "string" || !slugPattern.test(slug)) {
28
+ fail("invalid_argument", "slug is invalid");
29
+ }
30
+ }
31
+
32
+ export function parseArguments(argv = []) {
33
+ let root = process.cwd();
34
+ let slug;
35
+ let json = false;
36
+ let rootProvided = false;
37
+
38
+ for (let index = 0; index < argv.length; index += 1) {
39
+ const token = argv[index];
40
+ if (token === "--json") {
41
+ if (json) fail("invalid_argument", "--json was provided more than once");
42
+ json = true;
43
+ continue;
44
+ }
45
+ if (token === "--slug" || token === "--root") {
46
+ const value = argv[index + 1];
47
+ if (value === undefined || value.startsWith("--")) {
48
+ fail("invalid_argument", `${token} requires a value`);
49
+ }
50
+ index += 1;
51
+ if (token === "--slug") {
52
+ if (slug !== undefined) fail("invalid_argument", "--slug was provided more than once");
53
+ slug = value;
54
+ } else {
55
+ if (rootProvided) fail("invalid_argument", "--root was provided more than once");
56
+ if (!path.isAbsolute(value)) fail("invalid_argument", "--root must be an absolute path");
57
+ root = value;
58
+ rootProvided = true;
59
+ }
60
+ continue;
61
+ }
62
+ fail("invalid_argument", `unknown argument ${token}`);
63
+ }
64
+
65
+ if (slug === undefined) fail("invalid_argument", "--slug is required");
66
+ requireSlug(slug);
67
+ return { root, slug, json };
68
+ }
69
+
70
+ export function projectMission(state, events) {
71
+ if (!Array.isArray(events) || events.length === 0) {
72
+ fail("history_corrupt", "loop history is empty");
73
+ }
74
+ const latest = events.at(-1);
75
+ if (latest.state_after.last_action_id !== state.last_action_id) {
76
+ fail("history_corrupt", "latest history event does not match canonical state");
77
+ }
78
+ return {
79
+ schema_version: 1,
80
+ slug: state.slug,
81
+ status: state.status,
82
+ current_iteration: state.current_iteration,
83
+ planned_iterations: state.planned_iterations,
84
+ last_completed_step: state.last_completed_step,
85
+ blocking_cause: state.blocking_cause,
86
+ session_id: state.lease?.session_id ?? state.session_id,
87
+ updated_at: latest.recorded_at,
88
+ next_action: NEXT_ACTIONS[state.status],
89
+ };
90
+ }
91
+
92
+ export function readMissionStatus({ root, slug }) {
93
+ const state = inspectLoopState({ root, slug });
94
+ const events = readLoopHistory({ root, slug });
95
+ return projectMission(state, events);
96
+ }
97
+
98
+ function display(value) {
99
+ return value === null || value === undefined || value === "" ? "—" : value;
100
+ }
101
+
102
+ export function renderHuman(mission) {
103
+ return [
104
+ `Mission: ${mission.slug}`,
105
+ `Status: ${mission.status}`,
106
+ `Iteration: ${mission.current_iteration}/${mission.planned_iterations}`,
107
+ `Last step: ${display(mission.last_completed_step)}`,
108
+ `Blocking cause: ${display(mission.blocking_cause)}`,
109
+ `Session: ${display(mission.session_id)}`,
110
+ `Updated: ${mission.updated_at}`,
111
+ `Next action: ${mission.next_action}`,
112
+ ].join("\n");
113
+ }
114
+
115
+ export function main(argv = process.argv.slice(2), output = process.stdout) {
116
+ const options = parseArguments(argv);
117
+ const mission = readMissionStatus(options);
118
+ output.write(`${options.json ? JSON.stringify(mission, null, 2) : renderHuman(mission)}\n`);
119
+ return mission;
120
+ }
121
+
122
+ const isDirect = process.argv[1]
123
+ && fileURLToPath(import.meta.url) === path.resolve(process.argv[1]);
124
+
125
+ if (isDirect) {
126
+ try {
127
+ main();
128
+ } catch (error) {
129
+ if (error instanceof LoopStateError) {
130
+ process.stderr.write(`${error.code}: ${error.message}\n`);
131
+ process.exitCode = 1;
132
+ } else {
133
+ throw error;
134
+ }
135
+ }
136
+ }
@@ -0,0 +1,196 @@
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 { spawnSync } from "node:child_process";
6
+ import test from "node:test";
7
+ import { fileURLToPath } from "node:url";
8
+
9
+ import {
10
+ LoopStateError,
11
+ acquireLoop,
12
+ initLoopState,
13
+ recordLoopAction,
14
+ releaseLoop,
15
+ } from "./loop-state.mjs";
16
+ import {
17
+ parseArguments,
18
+ readMissionStatus,
19
+ renderHuman,
20
+ } from "./mission-status.mjs";
21
+
22
+ const scriptPath = fileURLToPath(new URL("./mission-status.mjs", import.meta.url));
23
+
24
+ function withRepo(callback, plannedIterations = 3) {
25
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-mission-status-"));
26
+ const loopsDir = path.join(root, ".opencode", "loops");
27
+ fs.mkdirSync(loopsDir, { recursive: true });
28
+ const contractPath = path.join(loopsDir, "example.md");
29
+ fs.writeFileSync(contractPath, "# Approved loop\n\nObjective: ship safely.\n");
30
+ initLoopState({
31
+ root,
32
+ slug: "example",
33
+ contractPath,
34
+ gitBaseline: "abc123",
35
+ sessionId: "session-1",
36
+ actionId: "approve-1",
37
+ plannedIterations,
38
+ });
39
+ try {
40
+ return callback({
41
+ root,
42
+ contractPath,
43
+ statePath: path.join(loopsDir, "example.json"),
44
+ historyPath: path.join(loopsDir, "example.history.jsonl"),
45
+ });
46
+ } finally {
47
+ fs.rmSync(root, { recursive: true, force: true });
48
+ }
49
+ }
50
+
51
+ function runStatus(root, args) {
52
+ return spawnSync(process.execPath, [scriptPath, "--root", root, ...args], {
53
+ encoding: "utf8",
54
+ timeout: 10000,
55
+ });
56
+ }
57
+
58
+ test("projects approved state without writing canonical files", () => {
59
+ withRepo(({ root, statePath, historyPath }) => {
60
+ const before = [fs.readFileSync(statePath), fs.readFileSync(historyPath)];
61
+ const mission = readMissionStatus({ root, slug: "example" });
62
+
63
+ assert.equal(mission.schema_version, 1);
64
+ assert.equal(mission.slug, "example");
65
+ assert.equal(mission.status, "approved");
66
+ assert.equal(mission.current_iteration, 0);
67
+ assert.equal(mission.planned_iterations, 3);
68
+ assert.equal(mission.last_completed_step, null);
69
+ assert.equal(mission.blocking_cause, null);
70
+ assert.equal(mission.session_id, "session-1");
71
+ assert.equal(typeof mission.updated_at, "string");
72
+ assert.equal(mission.next_action, "resume after confirming the approved contract");
73
+ assert.deepEqual([fs.readFileSync(statePath), fs.readFileSync(historyPath)], before);
74
+ });
75
+ });
76
+
77
+ test("projects running, blocked, paused, and completed transitions", () => {
78
+ withRepo(({ root, contractPath }) => {
79
+ acquireLoop({
80
+ root,
81
+ slug: "example",
82
+ contractPath,
83
+ sessionId: "session-1",
84
+ actionId: "resume-1",
85
+ });
86
+ assert.equal(readMissionStatus({ root, slug: "example" }).status, "running");
87
+
88
+ recordLoopAction({
89
+ root,
90
+ slug: "example",
91
+ sessionId: "session-1",
92
+ actionId: "blocked-1",
93
+ iteration: 1,
94
+ completedStep: "developer_change",
95
+ blockingCause: "reviewer requested a focused fix",
96
+ status: "blocked",
97
+ });
98
+ let mission = readMissionStatus({ root, slug: "example" });
99
+ assert.equal(mission.status, "blocked");
100
+ assert.equal(mission.blocking_cause, "reviewer requested a focused fix");
101
+ assert.match(mission.next_action, /blocking cause/);
102
+
103
+ recordLoopAction({
104
+ root,
105
+ slug: "example",
106
+ sessionId: "session-1",
107
+ actionId: "paused-1",
108
+ iteration: 1,
109
+ completedStep: "developer_change",
110
+ blockingCause: null,
111
+ status: "paused",
112
+ });
113
+ mission = readMissionStatus({ root, slug: "example" });
114
+ assert.equal(mission.status, "paused");
115
+ assert.match(mission.next_action, /resume explicitly/);
116
+
117
+ recordLoopAction({
118
+ root,
119
+ slug: "example",
120
+ sessionId: "session-1",
121
+ actionId: "completed-1",
122
+ iteration: 3,
123
+ completedStep: "review_passed",
124
+ blockingCause: null,
125
+ status: "completed",
126
+ });
127
+ releaseLoop({ root, slug: "example", sessionId: "session-1", actionId: "release-1" });
128
+ mission = readMissionStatus({ root, slug: "example" });
129
+ assert.equal(mission.status, "completed");
130
+ assert.equal(mission.current_iteration, 3);
131
+ assert.match(mission.next_action, /no further action/);
132
+ });
133
+ });
134
+
135
+ test("JSON and human CLI output expose the same projection", () => {
136
+ withRepo(({ root }) => {
137
+ const jsonResult = runStatus(root, ["--slug", "example", "--json"]);
138
+ assert.equal(jsonResult.status, 0, jsonResult.stderr);
139
+ const json = JSON.parse(jsonResult.stdout);
140
+ assert.equal(json.status, "approved");
141
+ assert.equal(json.current_iteration, 0);
142
+
143
+ const humanResult = runStatus(root, ["--slug", "example"]);
144
+ assert.equal(humanResult.status, 0, humanResult.stderr);
145
+ assert.match(humanResult.stdout, /Mission: example/);
146
+ assert.match(humanResult.stdout, /Iteration: 0\/3/);
147
+ assert.match(humanResult.stdout, /Next action:/);
148
+ assert.equal(renderHuman(json), humanResult.stdout.trim());
149
+ });
150
+ });
151
+
152
+ test("corrupt history and stale snapshots remain visible errors", () => {
153
+ withRepo(({ root, statePath, historyPath }) => {
154
+ fs.appendFileSync(historyPath, "not-json\n");
155
+ assert.throws(
156
+ () => readMissionStatus({ root, slug: "example" }),
157
+ (error) => error instanceof LoopStateError && error.code === "history_corrupt",
158
+ );
159
+ });
160
+
161
+ withRepo(({ root, contractPath, statePath }) => {
162
+ const initial = JSON.parse(fs.readFileSync(statePath, "utf8"));
163
+ acquireLoop({
164
+ root,
165
+ slug: "example",
166
+ contractPath,
167
+ sessionId: "session-1",
168
+ actionId: "resume-1",
169
+ });
170
+ fs.writeFileSync(statePath, `${JSON.stringify(initial, null, 2)}\n`);
171
+ assert.throws(
172
+ () => readMissionStatus({ root, slug: "example" }),
173
+ (error) => error instanceof LoopStateError && error.code === "snapshot_stale",
174
+ );
175
+ });
176
+ });
177
+
178
+ test("CLI rejects missing loops, invalid slugs, and relative roots", () => {
179
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), "opencode-mission-cli-"));
180
+ try {
181
+ const missing = runStatus(root, ["--slug", "example"]);
182
+ assert.equal(missing.status, 1);
183
+ assert.match(missing.stderr, /^state_missing:/);
184
+
185
+ assert.throws(
186
+ () => parseArguments(["--slug", "../unsafe"]),
187
+ (error) => error instanceof LoopStateError && error.code === "invalid_argument",
188
+ );
189
+ assert.throws(
190
+ () => parseArguments(["--root", ".", "--slug", "example"]),
191
+ (error) => error instanceof LoopStateError && error.code === "invalid_argument",
192
+ );
193
+ } finally {
194
+ fs.rmSync(root, { recursive: true, force: true });
195
+ }
196
+ });
@@ -37,6 +37,7 @@ const SKIP_DIRS = new Set([
37
37
 
38
38
  const STACK_RULES = [
39
39
  { file: "package.json", id: "node", confidence: "high" },
40
+ { glob: "scripts/*.mjs", id: "node", confidence: "medium" },
40
41
  { file: "tsconfig.json", id: "typescript", confidence: "high" },
41
42
  { file: "next.config.mjs", id: "nextjs", confidence: "high" },
42
43
  { file: "next.config.js", id: "nextjs", confidence: "high" },
@@ -241,7 +242,7 @@ export function detectStacks(repoRoot) {
241
242
  const seen = new Map();
242
243
 
243
244
  for (const rule of STACK_RULES) {
244
- const matches = matchGlobs(files, [rule.file]);
245
+ const matches = matchGlobs(files, [rule.file ?? rule.glob]);
245
246
  if (matches.length > 0) {
246
247
  const existing = seen.get(rule.id);
247
248
  if (!existing) {