opencode-swarm 7.0.1 → 7.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,16 @@
1
+ /**
2
+ * Regression coverage for the repo-graph walker (issue #704).
3
+ *
4
+ * Each test installs a fresh fixture under a tmp dir and asserts the walker
5
+ * cannot be tricked into:
6
+ * - infinite recursion via symlink cycles,
7
+ * - exceeding the wall-clock budget on a slow filesystem,
8
+ * - exceeding the file cap during traversal (vs. post-truncation),
9
+ * - scanning a refused top-level workspace root.
10
+ *
11
+ * Symlink-loop coverage is POSIX-only; the test bails on Windows because
12
+ * creating a directory symlink there requires Developer Mode. The walker's
13
+ * cycle defense itself is platform-agnostic — see `seenRealPaths` in
14
+ * src/tools/repo-graph.ts.
15
+ */
16
+ export {};
@@ -1,10 +1,11 @@
1
1
  /**
2
2
  * General Council Mode — architect-only synthesis tool.
3
3
  *
4
- * The architect spawns council_member subagents in parallel for Round 1,
5
- * collects their JSON responses, and calls this tool to synthesize results.
6
- * If the tool detects disagreements and Round 2 deliberation is configured,
7
- * the architect re-delegates to disputing members and calls this tool again
4
+ * The architect spawns council_generalist / council_skeptic /
5
+ * council_domain_expert subagents in parallel for Round 1, collects their
6
+ * JSON responses, and calls this tool to synthesize results. If the tool
7
+ * detects disagreements and Round 2 deliberation is configured, the
8
+ * architect re-delegates to disputing members and calls this tool again
8
9
  * with both round1Responses and round2Responses populated.
9
10
  *
10
11
  * Mirrors the convene-council.ts skeleton but explicitly does NOT inherit
@@ -206,10 +206,24 @@ export declare function saveIfDirty(workspace: string): Promise<void>;
206
206
  * @returns Complete RepoGraph with nodes and edges
207
207
  * @throws Error if workspace validation fails
208
208
  */
209
- export declare function buildWorkspaceGraph(workspaceRoot: string, options?: {
209
+ export interface BuildWorkspaceGraphOptions {
210
210
  maxFileSizeBytes?: number;
211
211
  maxFiles?: number;
212
- }): RepoGraph;
212
+ walkBudgetMs?: number;
213
+ followSymlinks?: boolean;
214
+ }
215
+ export declare function buildWorkspaceGraph(workspaceRoot: string, options?: BuildWorkspaceGraphOptions): RepoGraph;
216
+ /**
217
+ * Async, event-loop-safe variant of `buildWorkspaceGraph`. The traversal
218
+ * yields between batches and uses async fs primitives, so callers can run
219
+ * this from plugin init without freezing the host while a large workspace
220
+ * is scanned. The per-file processing remains sync — it is CPU-bound symbol
221
+ * extraction, and the existing per-file caps already prevent runaway work.
222
+ *
223
+ * Returned shape matches `buildWorkspaceGraph`. Same homedir guard, same
224
+ * bounded walk behavior, same deterministic file order.
225
+ */
226
+ export declare function buildWorkspaceGraphAsync(workspaceRoot: string, options?: BuildWorkspaceGraphOptions): Promise<RepoGraph>;
213
227
  /**
214
228
  * Incrementally update the graph for a set of changed files.
215
229
  * Re-scans only the specified files, updates their nodes and edges,
@@ -1,5 +1,5 @@
1
1
  /**
2
- * web_search tool — restricted to council_member agents.
2
+ * web_search tool — owned by the architect for MODE: COUNCIL pre-search.
3
3
  *
4
4
  * Thin wrapper around `src/council/web-search-provider.ts`. Returns structured
5
5
  * results on success and structured errors on failure (never throws). Config-
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Bun-compat shim tests (issue #704).
3
+ *
4
+ * Each public surface is exercised against the live runtime. When running
5
+ * under Bun the shim delegates to the native `Bun.*` primitives; when running
6
+ * under Node the shim's fallback path is exercised. The test only asserts the
7
+ * observable contract (text equality, written byte count, exit code parity)
8
+ * — it does not lock in implementation details that legitimately differ
9
+ * between the two paths.
10
+ */
11
+ export {};
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Timeout-helper tests (issue #704).
3
+ *
4
+ * The plugin init path uses `withTimeout` to bound the snapshot rehydration
5
+ * read so a slow filesystem cannot pin the host's `await server(...)`. The
6
+ * helper must:
7
+ * - resolve to the racer's value when the racer wins,
8
+ * - reject with the supplied error when the deadline elapses,
9
+ * - clear its timer in `finally` (no leak that holds the loop open),
10
+ * - never throw synchronously.
11
+ */
12
+ export {};
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Runtime-portability shim for the small set of `Bun.*` APIs we depend on.
3
+ *
4
+ * Why this exists: the plugin entry (`src/index.ts`) is bundled with
5
+ * `--target node`, but the source tree calls `Bun.file`, `Bun.write`,
6
+ * `Bun.spawn`, `Bun.spawnSync`, and `Bun.hash` directly. OpenCode's plugin
7
+ * host explicitly supports running plugins under Node (its own `PluginInput`
8
+ * uses `$: typeof Bun === "undefined" ? undefined : Bun.$`). On the OpenCode
9
+ * Desktop sidecar, plugins may execute under Node — every direct `Bun.*`
10
+ * reference would throw `ReferenceError: Bun is not defined`.
11
+ *
12
+ * This module funnels all such calls through a small set of helpers that
13
+ * detect the runtime once and dispatch to either the Bun primitive or a
14
+ * Node fallback. The fallbacks are deliberately small — they implement
15
+ * exactly the surface our callers use, no more.
16
+ *
17
+ * Cross-platform notes:
18
+ * - `bunWrite` performs an atomic write via temp+rename on the Node path,
19
+ * mirroring Bun's atomic semantics. Includes a Windows EEXIST retry loop
20
+ * because rename can race with file-handle release on Windows.
21
+ * - `bunSpawn` and `bunSpawnSync` use `node:child_process` and translate
22
+ * Bun's option shape into Node's. Stdout/stderr capture is wired so
23
+ * callers see the same `text()`/`stdout` shape regardless of runtime.
24
+ * - `bunHash` uses Node's `xxhash` via `Bun.hash`'s default algorithm when
25
+ * present and falls back to a stable djb2-derived 32-bit hash on Node.
26
+ */
27
+ /**
28
+ * Whether the current runtime is Bun. Cached at first call — every subsequent
29
+ * call is a single property access.
30
+ */
31
+ export declare function isBun(): boolean;
32
+ /**
33
+ * Bun.file / fs read shim. Returns an object exposing the subset of
34
+ * `BunFile` methods used in this codebase: `text()`, `arrayBuffer()`,
35
+ * `exists()`, and `size`.
36
+ *
37
+ * On Bun, this is a thin wrapper around `Bun.file()` so callers see
38
+ * identical semantics. On Node, the methods read the file lazily.
39
+ */
40
+ export interface BunCompatFile {
41
+ text(): Promise<string>;
42
+ arrayBuffer(): Promise<ArrayBuffer>;
43
+ exists(): Promise<boolean>;
44
+ readonly size: number;
45
+ }
46
+ export declare function bunFile(filePath: string): BunCompatFile;
47
+ /**
48
+ * Atomic file write. On Bun this delegates to `Bun.write`. On Node we write
49
+ * to a temp file in the same directory and rename atomically — the same
50
+ * semantics every existing call site already expects via Bun.write.
51
+ */
52
+ export declare function bunWrite(filePath: string, data: string | Uint8Array | ArrayBuffer | ArrayBufferView): Promise<number>;
53
+ /**
54
+ * Stable 32-bit hash. Bun's `Bun.hash` uses xxHash64 by default; on Node we
55
+ * fall back to a 32-bit djb2 hash — identical hashes are NOT guaranteed
56
+ * across runtimes, so callers should not rely on cross-runtime hash equality
57
+ * (no current caller does — every `Bun.hash` use is in-process state keying
58
+ * or a same-runtime cache key).
59
+ */
60
+ export declare function bunHash(input: string | ArrayBufferView | ArrayBuffer): bigint;
61
+ /**
62
+ * Process spawn. Bun's `Bun.spawn` returns an object with `exited`, `stdout`,
63
+ * `stderr` etc. We expose a minimal compatible surface that callers actually
64
+ * use: `exited`, `exitCode`, and `stdout`/`stderr` as `ReadableStream`-like
65
+ * objects with `text()` and `bytes()` methods.
66
+ */
67
+ export interface BunCompatSpawnOptions {
68
+ cwd?: string;
69
+ env?: Record<string, string | undefined>;
70
+ stdin?: 'inherit' | 'ignore' | 'pipe';
71
+ stdout?: 'inherit' | 'ignore' | 'pipe';
72
+ stderr?: 'inherit' | 'ignore' | 'pipe';
73
+ timeout?: number;
74
+ }
75
+ export interface BunCompatStream {
76
+ text(): Promise<string>;
77
+ bytes(): Promise<Uint8Array>;
78
+ /**
79
+ * Returns a Web ReadableStream reader for incremental, bounded
80
+ * consumption — matches the Bun runtime's `proc.stdout.getReader()`
81
+ * shape, used by the test-runner's `readBoundedStream` to cap memory
82
+ * for multi-GB test output.
83
+ */
84
+ getReader(): ReadableStreamDefaultReader<Uint8Array>;
85
+ }
86
+ export interface BunCompatSubprocess {
87
+ readonly stdout: BunCompatStream;
88
+ readonly stderr: BunCompatStream;
89
+ readonly exited: Promise<number>;
90
+ exitCode: number | null;
91
+ kill(signal?: NodeJS.Signals | number): void;
92
+ }
93
+ export declare function bunSpawn(cmd: string[], options?: BunCompatSpawnOptions): BunCompatSubprocess;
94
+ export interface BunCompatSyncResult {
95
+ stdout: Uint8Array;
96
+ stderr: Uint8Array;
97
+ exitCode: number;
98
+ success: boolean;
99
+ }
100
+ export declare function bunSpawnSync(cmd: string[] | {
101
+ cmd: string[];
102
+ cwd?: string;
103
+ env?: Record<string, string | undefined>;
104
+ stdin?: string | Uint8Array;
105
+ timeout?: number;
106
+ }, options?: BunCompatSpawnOptions): BunCompatSyncResult;
@@ -0,0 +1,23 @@
1
+ /**
2
+ * Timeout primitives used by the plugin init path.
3
+ *
4
+ * Hard rule: every timer scheduled here must call `unref()` so it never holds
5
+ * the process open, and every Promise.race must clear the timer in `finally`
6
+ * so it does not leak the timer reference after the racer settles.
7
+ */
8
+ /**
9
+ * Race a promise against a timeout. The timer is cleared in `finally` so the
10
+ * Node event loop is not pinned open after the race resolves. The returned
11
+ * promise resolves to the racer's value, or rejects with the supplied
12
+ * `timeoutError` if the deadline elapses first.
13
+ *
14
+ * @param promise Long-running operation to race.
15
+ * @param ms Deadline in milliseconds.
16
+ * @param timeoutError Error thrown when the deadline elapses.
17
+ */
18
+ export declare function withTimeout<T>(promise: Promise<T>, ms: number, timeoutError: Error): Promise<T>;
19
+ /**
20
+ * Yield to the macrotask queue. Works under both Node and Bun runtimes,
21
+ * unlike `setImmediate` which is Node-only.
22
+ */
23
+ export declare function yieldToEventLoop(): Promise<void>;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "opencode-swarm",
3
- "version": "7.0.1",
3
+ "version": "7.0.3",
4
4
  "description": "Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -45,7 +45,8 @@
45
45
  "format": "biome format . --write",
46
46
  "check": "biome check --write .",
47
47
  "dev": "bun run build && opencode",
48
- "prepublishOnly": "bun run build"
48
+ "prepublishOnly": "bun run build",
49
+ "repro:704": "node scripts/repro-704.mjs"
49
50
  },
50
51
  "dependencies": {
51
52
  "@opencode-ai/plugin": "^1.1.53",
@@ -1,30 +0,0 @@
1
- /**
2
- * General Council member agent.
3
- *
4
- * Implements the NSED peer-review protocol (arXiv:2601.16863):
5
- * - Round 1: independent search + answer with self-reported confidence
6
- * - Round 2: targeted deliberation on disagreements with explicit MAINTAIN /
7
- * CONCEDE / NUANCE stance (ConfMAD)
8
- *
9
- * Tools: web_search ONLY. No write tools, no orchestration tools. The architect
10
- * spawns members in parallel via the OpenCode subagent task system, collects
11
- * structured JSON responses, and synthesizes via convene_general_council.
12
- *
13
- * Prompt template variables (substituted by the architect at delegation time):
14
- * {{MEMBER_ID}} — the council member identifier
15
- * {{ROLE}} — generalist | skeptic | domain_expert | devil_advocate | synthesizer
16
- * {{PERSONA_BLOCK}} — optional persona instructions (omitted if undefined)
17
- * {{ROUND}} — "1" or "2"
18
- * {{DISAGREEMENT_BLOCK}} — Round 2 only: opposing position(s) to address
19
- */
20
- import type { AgentDefinition } from './architect';
21
- export declare const COUNCIL_MEMBER_PROMPT = "You are Council Member {{MEMBER_ID}} ({{ROLE}}) on a multi-model General Council.\n\n{{PERSONA_BLOCK}}\n\nYou are participating in Round {{ROUND}} of a structured deliberation. Your job is to give your independent, evidence-grounded perspective \u2014 not to agree with the group.\n\n================================================================\nROUND {{ROUND}} PROTOCOL\n================================================================\n\nROUND 1 \u2014 Independent Research and Answer\n- Issue 1\u20133 targeted web_search calls to gather evidence relevant to the question.\n- Cite EVERY factual claim with a source URL from your search results.\n- State your confidence (0.0\u20131.0) explicitly. Be honest \u2014 overconfident answers hurt the council.\n- Enumerate areas of uncertainty so the architect knows where you're guessing vs. where you're sure.\n- Do NOT coordinate with other members. You will not see their responses until Round 2.\n- Do NOT pad. Be concise. Substance over volume.\n\nROUND 2 \u2014 Targeted Deliberation (ONLY when this round is invoked for you)\n- {{DISAGREEMENT_BLOCK}}\n- Issue at most 1 additional web_search call.\n- Declare your stance explicitly using one of these keywords as the FIRST word of a paragraph:\n MAINTAIN \u2014 your Round 1 position holds; cite the new evidence supporting it\n CONCEDE \u2014 the opposing position is correct; state specifically what you got wrong\n NUANCE \u2014 both positions are partially right; state the boundary condition that distinguishes them\n- Never CONCEDE without evidence. Sycophantic capitulation degrades the council below an individual member's baseline (NSED arXiv:2601.16863).\n- Never MAINTAIN without engaging the opposing argument on its merits.\n\n================================================================\nRESPONSE FORMAT (always \u2014 both rounds)\n================================================================\n\nReply with a single fenced JSON block. No prose outside the block.\n\n```json\n{\n \"memberId\": \"{{MEMBER_ID}}\",\n \"role\": \"{{ROLE}}\",\n \"round\": {{ROUND}},\n \"response\": \"Your full answer (Round 1) or stance + reasoning (Round 2). Markdown OK inside the string.\",\n \"searchQueries\": [\"query 1\", \"query 2\"],\n \"sources\": [\n { \"title\": \"...\", \"url\": \"...\", \"snippet\": \"...\", \"query\": \"...\" }\n ],\n \"confidence\": 0.85,\n \"areasOfUncertainty\": [\n \"What I'm not sure about, in plain language.\"\n ],\n \"disagreementTopics\": []\n}\n```\n\nFor Round 1: leave `disagreementTopics` as []. For Round 2: list the specific disagreement topics this response addresses.\n\n================================================================\nHARD RULES\n================================================================\n- web_search is your ONLY tool. You cannot read or write files, run commands, or delegate.\n- Never invent sources. If a search returns nothing useful, say so in `areasOfUncertainty`.\n- Never echo other members' responses verbatim. Paraphrase or quote with attribution.\n- Stay within your role and persona. The architect chose you for a specific perspective.\n";
22
- /**
23
- * Factory for the council_member agent definition. The factory mirrors other
24
- * agent factories (createSMEAgent, createReviewerAgent) for consistency.
25
- *
26
- * Per-member context (memberId, role, persona, round, disagreement) is supplied
27
- * by the architect at delegation time via prompt-string substitution; the
28
- * factory itself produces the unparameterized template.
29
- */
30
- export declare function createCouncilMemberAgent(model: string, customPrompt?: string, customAppendPrompt?: string): AgentDefinition;
@@ -1,8 +0,0 @@
1
- /**
2
- * Tests for src/agents/council-member.ts and src/agents/council-moderator.ts.
3
- *
4
- * Covers prompt template content (NSED protocol markers), AGENT_TOOL_MAP
5
- * enforcement (web_search-only for member, empty for moderator), and the
6
- * persona-block insertion path.
7
- */
8
- export {};
@@ -1,20 +0,0 @@
1
- /**
2
- * General Council moderator agent.
3
- *
4
- * Receives the structural synthesis output from convene_general_council
5
- * (consensus / disagreements / sources) and produces a coherent, well-structured
6
- * final answer for the user. Empty tool list — moderation is synthesis-only;
7
- * it does NOT need web_search because every claim it works with has already
8
- * been searched and cited by council members.
9
- *
10
- * Confidence-weighted (Quadratic Voting from NSED arXiv:2601.16863): higher-
11
- * confidence members carry more weight, but evidence quality matters more
12
- * than confidence alone. The moderator must NOT favor a position purely
13
- * because its proponent was confident.
14
- */
15
- import type { AgentDefinition } from './architect';
16
- export declare const COUNCIL_MODERATOR_PROMPT = "You are the General Council Moderator.\n\nYou are receiving the structural synthesis from a multi-model council deliberation:\n- Question (and mode: general or spec_review)\n- All member Round 1 responses with sources\n- Detected disagreements\n- Round 2 deliberation responses (if any)\n- Confidence-weighted consensus claims\n- Persisting disagreements after deliberation\n\nYour job: produce a coherent, well-structured final answer for the user.\n\n================================================================\nRULES\n================================================================\n\n1. LEAD WITH CONSENSUS \u2014 open with the strongest consensus position. Use the\n confidence-weighted ordering (Quadratic Voting): higher-confidence claims\n from multiple members rank higher, but evidence quality outranks raw\n confidence. Never elevate a single confident voice over a well-evidenced\n contrary majority.\n\n2. ACKNOWLEDGE DISAGREEMENT HONESTLY \u2014 for each persisting disagreement, write\n \"experts disagree on X because\u2026\" and present the strongest version of each\n side. Do NOT pretend disagreements are resolved when they are not. Do NOT\n silently pick a winner.\n\n3. CITE THE STRONGEST SOURCES \u2014 link key claims with [title](url) format from\n the deduplicated source list. Pick the most reputable source for each claim;\n do not cite duplicates.\n\n4. BE CONCISE \u2014 the user wants an answer, not a committee report. Default\n length: a few short paragraphs plus a bulleted summary. Expand only when\n the question genuinely requires it.\n\n================================================================\nHARD CONSTRAINTS\n================================================================\n\n- You MUST NOT invent claims that are not present in the council's responses.\n- You MUST NOT add new web research. If something was missed, say so.\n- You MUST NOT favor a position based on member confidence alone \u2014 evidence\n quality is the tie-breaker.\n- You have NO tools. You write the final synthesis from the input given.\n\n================================================================\nOUTPUT FORMAT\n================================================================\n\nPlain markdown. No code fences. No JSON. Suggested structure:\n\n# Answer\n\n<lead consensus position with citation(s)>\n\n<remaining consensus / context paragraphs as needed>\n\n## Where Experts Disagree\n\n- <topic 1>: <position A> vs <position B>, with sources for each\n- <topic 2>: ...\n\n## Sources\n\n- [title](url)\n- ...\n\n(Omit any section that is empty.)\n";
17
- /**
18
- * Factory for the council_moderator agent definition. No tools — synthesis only.
19
- */
20
- export declare function createCouncilModeratorAgent(model: string, customPrompt?: string, customAppendPrompt?: string): AgentDefinition;