opencode-swarm 7.130.1 → 7.130.2
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.
- package/dist/cli/{curator-llm-factory-7rz7mvcr.js → curator-llm-factory-mxjcctn8.js} +2 -2
- package/dist/cli/{curator-by14m5fc.js → curator-s2ynewsr.js} +2 -2
- package/dist/cli/{guardrail-explain-mvct2n9f.js → guardrail-explain-s85kv81r.js} +3 -3
- package/dist/cli/{hive-promoter-trezcyrd.js → hive-promoter-qdgxajht.js} +2 -2
- package/dist/cli/{index-j0py44fv.js → index-6fqj8fcp.js} +1 -1
- package/dist/cli/{index-4qrbvrz5.js → index-etdgtk3m.js} +10 -10
- package/dist/cli/{index-f2y46pda.js → index-h3k62043.js} +20 -6
- package/dist/cli/{index-xdx5b4s1.js → index-jvwkxz8q.js} +3 -3
- package/dist/cli/index.js +2 -2
- package/dist/cli/{workspace-snapshot-jwkjg790.js → workspace-snapshot-35qc0y8a.js} +1 -1
- package/dist/index.js +2 -2
- package/package.json +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import {
|
|
3
3
|
createCuratorLLMDelegate
|
|
4
|
-
} from "./index-
|
|
4
|
+
} from "./index-etdgtk3m.js";
|
|
5
5
|
import"./index-hjar4crm.js";
|
|
6
6
|
import"./index-p6qgjkbt.js";
|
|
7
7
|
import"./index-kzvwb2se.js";
|
|
@@ -39,7 +39,7 @@ import"./index-s80bsjkj.js";
|
|
|
39
39
|
import"./index-z6xqpmqg.js";
|
|
40
40
|
import"./index-zjygnfay.js";
|
|
41
41
|
import"./index-zgwm4ryv.js";
|
|
42
|
-
import"./index-
|
|
42
|
+
import"./index-h3k62043.js";
|
|
43
43
|
import"./index-3x761jqv.js";
|
|
44
44
|
import"./index-7mkpsw6g.js";
|
|
45
45
|
import"./index-fsrp8wp3.js";
|
|
@@ -14,7 +14,7 @@ import {
|
|
|
14
14
|
runCuratorInit,
|
|
15
15
|
runCuratorPhase,
|
|
16
16
|
writeCuratorSummary
|
|
17
|
-
} from "./index-
|
|
17
|
+
} from "./index-etdgtk3m.js";
|
|
18
18
|
import"./index-hjar4crm.js";
|
|
19
19
|
import"./index-p6qgjkbt.js";
|
|
20
20
|
import"./index-kzvwb2se.js";
|
|
@@ -52,7 +52,7 @@ import"./index-s80bsjkj.js";
|
|
|
52
52
|
import"./index-z6xqpmqg.js";
|
|
53
53
|
import"./index-zjygnfay.js";
|
|
54
54
|
import"./index-zgwm4ryv.js";
|
|
55
|
-
import"./index-
|
|
55
|
+
import"./index-h3k62043.js";
|
|
56
56
|
import"./index-3x761jqv.js";
|
|
57
57
|
import"./index-7mkpsw6g.js";
|
|
58
58
|
import"./index-fsrp8wp3.js";
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import {
|
|
3
3
|
handleGuardrailExplain
|
|
4
|
-
} from "./index-
|
|
5
|
-
import"./index-
|
|
4
|
+
} from "./index-6fqj8fcp.js";
|
|
5
|
+
import"./index-etdgtk3m.js";
|
|
6
6
|
import"./index-hjar4crm.js";
|
|
7
7
|
import"./index-p6qgjkbt.js";
|
|
8
8
|
import"./index-kzvwb2se.js";
|
|
@@ -40,7 +40,7 @@ import"./index-s80bsjkj.js";
|
|
|
40
40
|
import"./index-z6xqpmqg.js";
|
|
41
41
|
import"./index-zjygnfay.js";
|
|
42
42
|
import"./index-zgwm4ryv.js";
|
|
43
|
-
import"./index-
|
|
43
|
+
import"./index-h3k62043.js";
|
|
44
44
|
import"./index-3x761jqv.js";
|
|
45
45
|
import"./index-7mkpsw6g.js";
|
|
46
46
|
import"./index-fsrp8wp3.js";
|
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
isHiveEligible,
|
|
8
8
|
promoteFromSwarm,
|
|
9
9
|
promoteToHive
|
|
10
|
-
} from "./index-
|
|
10
|
+
} from "./index-etdgtk3m.js";
|
|
11
11
|
import"./index-hjar4crm.js";
|
|
12
12
|
import"./index-p6qgjkbt.js";
|
|
13
13
|
import"./index-kzvwb2se.js";
|
|
@@ -47,7 +47,7 @@ import"./index-s80bsjkj.js";
|
|
|
47
47
|
import"./index-z6xqpmqg.js";
|
|
48
48
|
import"./index-zjygnfay.js";
|
|
49
49
|
import"./index-zgwm4ryv.js";
|
|
50
|
-
import"./index-
|
|
50
|
+
import"./index-h3k62043.js";
|
|
51
51
|
import"./index-3x761jqv.js";
|
|
52
52
|
import"./index-7mkpsw6g.js";
|
|
53
53
|
import"./index-fsrp8wp3.js";
|
|
@@ -285,7 +285,7 @@ import {
|
|
|
285
285
|
resolvePrWorkflowRevisionDigest,
|
|
286
286
|
resolveRemoteRefsContainingHead,
|
|
287
287
|
resolveRemoteRefsContainingHeadAsync
|
|
288
|
-
} from "./index-
|
|
288
|
+
} from "./index-h3k62043.js";
|
|
289
289
|
import {
|
|
290
290
|
atomicWriteFile
|
|
291
291
|
} from "./index-7mkpsw6g.js";
|
|
@@ -15592,11 +15592,11 @@ var _internals19 = {
|
|
|
15592
15592
|
}
|
|
15593
15593
|
},
|
|
15594
15594
|
applyCuratorKnowledgeUpdates: async (directory, recommendations, knowledgeConfig, generation) => {
|
|
15595
|
-
const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-
|
|
15595
|
+
const { applyCuratorKnowledgeUpdates: applyCuratorKnowledgeUpdates2 } = await import("./curator-s2ynewsr.js");
|
|
15596
15596
|
return applyCuratorKnowledgeUpdates2(directory, recommendations, knowledgeConfig, generation);
|
|
15597
15597
|
},
|
|
15598
15598
|
checkHivePromotions: async (entries, knowledgeConfig, directory) => {
|
|
15599
|
-
const { checkHivePromotions } = await import("./hive-promoter-
|
|
15599
|
+
const { checkHivePromotions } = await import("./hive-promoter-qdgxajht.js");
|
|
15600
15600
|
return checkHivePromotions(entries, knowledgeConfig, directory);
|
|
15601
15601
|
},
|
|
15602
15602
|
applyProposalTriage: async (directory, triage) => {
|
|
@@ -23501,8 +23501,8 @@ var _internals32 = {
|
|
|
23501
23501
|
loadCuratorDeps: async () => {
|
|
23502
23502
|
const [{ CuratorConfigSchema }, curator, { createCuratorLLMDelegate: createCuratorLLMDelegate2 }] = await Promise.all([
|
|
23503
23503
|
import("./schema-fkpn2r1s.js"),
|
|
23504
|
-
import("./curator-
|
|
23505
|
-
import("./curator-llm-factory-
|
|
23504
|
+
import("./curator-s2ynewsr.js"),
|
|
23505
|
+
import("./curator-llm-factory-mxjcctn8.js")
|
|
23506
23506
|
]);
|
|
23507
23507
|
return { CuratorConfigSchema, curator, createCuratorLLMDelegate: createCuratorLLMDelegate2 };
|
|
23508
23508
|
}
|
|
@@ -24001,7 +24001,7 @@ import { fileURLToPath } from "url";
|
|
|
24001
24001
|
// package.json
|
|
24002
24002
|
var package_default = {
|
|
24003
24003
|
name: "opencode-swarm",
|
|
24004
|
-
version: "7.130.
|
|
24004
|
+
version: "7.130.2",
|
|
24005
24005
|
description: "Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",
|
|
24006
24006
|
main: "dist/index.js",
|
|
24007
24007
|
types: "dist/index.d.ts",
|
|
@@ -44393,7 +44393,7 @@ function buildDetailedHelp(commandName, entry) {
|
|
|
44393
44393
|
async function handleHelpCommand(ctx) {
|
|
44394
44394
|
const targetCommand = ctx.args.join(" ");
|
|
44395
44395
|
if (!targetCommand) {
|
|
44396
|
-
const { buildHelpText } = await import("./index-
|
|
44396
|
+
const { buildHelpText } = await import("./index-jvwkxz8q.js");
|
|
44397
44397
|
return buildHelpText();
|
|
44398
44398
|
}
|
|
44399
44399
|
const tokens = targetCommand.split(/\s+/);
|
|
@@ -44402,7 +44402,7 @@ async function handleHelpCommand(ctx) {
|
|
|
44402
44402
|
return _internals9.buildDetailedHelp(resolved.key, resolved.entry);
|
|
44403
44403
|
}
|
|
44404
44404
|
const similar = _internals9.findSimilarCommands(targetCommand);
|
|
44405
|
-
const { buildHelpText: fullHelp } = await import("./index-
|
|
44405
|
+
const { buildHelpText: fullHelp } = await import("./index-jvwkxz8q.js");
|
|
44406
44406
|
if (similar.length > 0) {
|
|
44407
44407
|
return `Command '/swarm ${targetCommand}' not found.
|
|
44408
44408
|
|
|
@@ -44541,7 +44541,7 @@ var COMMAND_REGISTRY = {
|
|
|
44541
44541
|
},
|
|
44542
44542
|
"guardrail explain": {
|
|
44543
44543
|
handler: async (ctx) => {
|
|
44544
|
-
const { handleGuardrailExplain } = await import("./guardrail-explain-
|
|
44544
|
+
const { handleGuardrailExplain } = await import("./guardrail-explain-s85kv81r.js");
|
|
44545
44545
|
return handleGuardrailExplain(ctx.directory, ctx.args);
|
|
44546
44546
|
},
|
|
44547
44547
|
description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
|
|
@@ -44551,7 +44551,7 @@ var COMMAND_REGISTRY = {
|
|
|
44551
44551
|
},
|
|
44552
44552
|
"guardrail-explain": {
|
|
44553
44553
|
handler: async (ctx) => {
|
|
44554
|
-
const { handleGuardrailExplain } = await import("./guardrail-explain-
|
|
44554
|
+
const { handleGuardrailExplain } = await import("./guardrail-explain-s85kv81r.js");
|
|
44555
44555
|
return handleGuardrailExplain(ctx.directory, ctx.args);
|
|
44556
44556
|
},
|
|
44557
44557
|
description: "Dry-run: show what the guardrails would do to a command or write target (executes nothing)",
|
|
@@ -340,11 +340,14 @@ async function resolveIsWorkingTreeCleanAsync(directory) {
|
|
|
340
340
|
return status === null ? null : status.length === 0;
|
|
341
341
|
}
|
|
342
342
|
function resolveCommitCountSince(directory, baseHeadSha, currentHeadSha) {
|
|
343
|
+
if (!isSafeGitRevisionToken(baseHeadSha) || !isSafeGitRevisionToken(currentHeadSha))
|
|
344
|
+
return null;
|
|
343
345
|
const output = runGit(directory, [
|
|
344
346
|
"rev-list",
|
|
345
347
|
"--count",
|
|
346
348
|
"--ancestry-path",
|
|
347
|
-
`${baseHeadSha}..${currentHeadSha}
|
|
349
|
+
`${baseHeadSha}..${currentHeadSha}`,
|
|
350
|
+
"--"
|
|
348
351
|
]);
|
|
349
352
|
if (!output || !/^\d+$/.test(output))
|
|
350
353
|
return null;
|
|
@@ -352,11 +355,14 @@ function resolveCommitCountSince(directory, baseHeadSha, currentHeadSha) {
|
|
|
352
355
|
return Number.isSafeInteger(count) ? count : null;
|
|
353
356
|
}
|
|
354
357
|
async function resolveCommitCountSinceAsync(directory, baseHeadSha, currentHeadSha) {
|
|
358
|
+
if (!isSafeGitRevisionToken(baseHeadSha) || !isSafeGitRevisionToken(currentHeadSha))
|
|
359
|
+
return null;
|
|
355
360
|
const output = await runGitAsync(directory, [
|
|
356
361
|
"rev-list",
|
|
357
362
|
"--count",
|
|
358
363
|
"--ancestry-path",
|
|
359
|
-
`${baseHeadSha}..${currentHeadSha}
|
|
364
|
+
`${baseHeadSha}..${currentHeadSha}`,
|
|
365
|
+
"--"
|
|
360
366
|
]);
|
|
361
367
|
if (!output || !/^\d+$/.test(output))
|
|
362
368
|
return null;
|
|
@@ -364,15 +370,19 @@ async function resolveCommitCountSinceAsync(directory, baseHeadSha, currentHeadS
|
|
|
364
370
|
return Number.isSafeInteger(count) ? count : null;
|
|
365
371
|
}
|
|
366
372
|
function resolveIsExactSingleChildCommit(directory, baseHeadSha, currentHeadSha) {
|
|
373
|
+
if (!isSafeGitRevisionToken(baseHeadSha) || !isSafeGitRevisionToken(currentHeadSha))
|
|
374
|
+
return null;
|
|
367
375
|
const base = runGit(directory, [
|
|
368
376
|
"rev-parse",
|
|
369
377
|
"--verify",
|
|
370
|
-
`${baseHeadSha}^{commit}
|
|
378
|
+
`${baseHeadSha}^{commit}`,
|
|
379
|
+
"--"
|
|
371
380
|
]);
|
|
372
381
|
const current = runGit(directory, [
|
|
373
382
|
"rev-parse",
|
|
374
383
|
"--verify",
|
|
375
|
-
`${currentHeadSha}^{commit}
|
|
384
|
+
`${currentHeadSha}^{commit}`,
|
|
385
|
+
"--"
|
|
376
386
|
]);
|
|
377
387
|
if (!base || !current)
|
|
378
388
|
return null;
|
|
@@ -389,15 +399,19 @@ function resolveIsExactSingleChildCommit(directory, baseHeadSha, currentHeadSha)
|
|
|
389
399
|
return fields.length === 2 && fields[0]?.toLowerCase() === current.toLowerCase() && fields[1]?.toLowerCase() === base.toLowerCase();
|
|
390
400
|
}
|
|
391
401
|
async function resolveIsExactSingleChildCommitAsync(directory, baseHeadSha, currentHeadSha) {
|
|
402
|
+
if (!isSafeGitRevisionToken(baseHeadSha) || !isSafeGitRevisionToken(currentHeadSha))
|
|
403
|
+
return null;
|
|
392
404
|
const base = await runGitAsync(directory, [
|
|
393
405
|
"rev-parse",
|
|
394
406
|
"--verify",
|
|
395
|
-
`${baseHeadSha}^{commit}
|
|
407
|
+
`${baseHeadSha}^{commit}`,
|
|
408
|
+
"--"
|
|
396
409
|
]);
|
|
397
410
|
const current = await runGitAsync(directory, [
|
|
398
411
|
"rev-parse",
|
|
399
412
|
"--verify",
|
|
400
|
-
`${currentHeadSha}^{commit}
|
|
413
|
+
`${currentHeadSha}^{commit}`,
|
|
414
|
+
"--"
|
|
401
415
|
]);
|
|
402
416
|
if (!base || !current)
|
|
403
417
|
return null;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import {
|
|
3
3
|
handleGuardrailExplain
|
|
4
|
-
} from "./index-
|
|
4
|
+
} from "./index-6fqj8fcp.js";
|
|
5
5
|
import {
|
|
6
6
|
handleGuardrailLog
|
|
7
7
|
} from "./index-zft4hp35.js";
|
|
@@ -83,7 +83,7 @@ import {
|
|
|
83
83
|
handleWriteRetroCommand,
|
|
84
84
|
normalizeSwarmCommandInput,
|
|
85
85
|
resolveCommand
|
|
86
|
-
} from "./index-
|
|
86
|
+
} from "./index-etdgtk3m.js";
|
|
87
87
|
import"./index-hjar4crm.js";
|
|
88
88
|
import"./index-p6qgjkbt.js";
|
|
89
89
|
import"./index-kzvwb2se.js";
|
|
@@ -127,7 +127,7 @@ import"./index-s80bsjkj.js";
|
|
|
127
127
|
import"./index-z6xqpmqg.js";
|
|
128
128
|
import"./index-zjygnfay.js";
|
|
129
129
|
import"./index-zgwm4ryv.js";
|
|
130
|
-
import"./index-
|
|
130
|
+
import"./index-h3k62043.js";
|
|
131
131
|
import"./index-3x761jqv.js";
|
|
132
132
|
import"./index-7mkpsw6g.js";
|
|
133
133
|
import"./index-fsrp8wp3.js";
|
package/dist/cli/index.js
CHANGED
|
@@ -7,7 +7,7 @@ import {
|
|
|
7
7
|
getPluginLockFilePaths,
|
|
8
8
|
package_default,
|
|
9
9
|
resolveCommand
|
|
10
|
-
} from "./index-
|
|
10
|
+
} from "./index-etdgtk3m.js";
|
|
11
11
|
import"./index-hjar4crm.js";
|
|
12
12
|
import"./index-p6qgjkbt.js";
|
|
13
13
|
import"./index-kzvwb2se.js";
|
|
@@ -48,7 +48,7 @@ import"./index-s80bsjkj.js";
|
|
|
48
48
|
import"./index-z6xqpmqg.js";
|
|
49
49
|
import"./index-zjygnfay.js";
|
|
50
50
|
import"./index-zgwm4ryv.js";
|
|
51
|
-
import"./index-
|
|
51
|
+
import"./index-h3k62043.js";
|
|
52
52
|
import"./index-3x761jqv.js";
|
|
53
53
|
import"./index-7mkpsw6g.js";
|
|
54
54
|
import"./index-fsrp8wp3.js";
|
package/dist/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.130.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic","coder","test_engineer"]},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.130.2",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic","coder","test_engineer"]},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -169,7 +169,7 @@ GFS4: `),console.error(m)};if(!fs4[gracefulQueue]){if(queue=global[gracefulQueue
|
|
|
169
169
|
`)){let trimmed=line.trim();if(trimmed.length===0)continue;let fields=trimmed.split("\t");if(fields.length<3)return null;let added=fields[0]==="-"?0:Number.parseInt(fields[0],10),deleted=fields[1]==="-"?0:Number.parseInt(fields[1],10);if(Number.isNaN(added)||Number.isNaN(deleted))return null;changedFiles+=1,changedLines+=added+deleted}let rawOutput=runGit(directory,["diff","--raw",range]);if(rawOutput===null)return null;let hasSubmoduleChange=rawOutput.split(`
|
|
170
170
|
`).some((line)=>GITLINK_MODE_PATTERN.test(line.trim()));return{changedLines,changedFiles,hasSubmoduleChange}}async function resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=await runGitAsync(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
|
|
171
171
|
`)){let trimmed=line.trim();if(trimmed.length===0)continue;let fields=trimmed.split("\t");if(fields.length<3)return null;let added=fields[0]==="-"?0:Number.parseInt(fields[0],10),deleted=fields[1]==="-"?0:Number.parseInt(fields[1],10);if(Number.isNaN(added)||Number.isNaN(deleted))return null;changedFiles+=1,changedLines+=added+deleted}let rawOutput=await runGitAsync(directory,["diff","--raw",range]);if(rawOutput===null)return null;let hasSubmoduleChange=rawOutput.split(`
|
|
172
|
-
`).some((line)=>GITLINK_MODE_PATTERN.test(line.trim()));return{changedLines,changedFiles,hasSubmoduleChange}}function isSafeGitRevisionToken(value){return/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")}function resolveCurrentUpstreamRemoteRef(directory){let upstream=runGit(directory,["rev-parse","--symbolic-full-name","@{upstream}"]);if(!upstream?.startsWith("refs/remotes/")||upstream.endsWith("/HEAD"))return null;return upstream}function resolveCurrentUpstreamPushTarget(directory){let localBranchRef=runGit(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=runGit(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}async function resolveCurrentUpstreamPushTargetAsync(directory){let localBranchRef=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=await runGitAsync(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}function resolveExactRemoteBranchHead(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=runGit(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}async function resolveExactRemoteBranchHeadAsync(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=await runGitAsync(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}function resolveGitControlStateDigest(directory){let head=runGit(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=runGit(directory,["symbolic-ref","--quiet","HEAD"]),upstream=resolveCurrentUpstreamPushTarget(directory),refs=runGit(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=runGit(directory,["config","--null","--show-origin","--show-scope","--list"]),index=runGit(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}async function resolveGitControlStateDigestAsync(directory){let head=await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]),upstream=await resolveCurrentUpstreamPushTargetAsync(directory),refs=await runGitAsync(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=await runGitAsync(directory,["config","--null","--show-origin","--show-scope","--list"]),index=await runGitAsync(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}function resolveIsWorkingTreeClean(directory){let status=runGit(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}async function resolveIsWorkingTreeCleanAsync(directory){let status=await runGitAsync(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}function resolveCommitCountSince(directory,baseHeadSha,currentHeadSha){let output=runGit(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}async function resolveCommitCountSinceAsync(directory,baseHeadSha,currentHeadSha){let output=await runGitAsync(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}function resolveIsExactSingleChildCommit(directory,baseHeadSha,currentHeadSha){let base=runGit(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),current=runGit(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`]);if(!base||!current)return null;let commitAndParents=runGit(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}async function resolveIsExactSingleChildCommitAsync(directory,baseHeadSha,currentHeadSha){let base=await runGitAsync(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),current=await runGitAsync(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`]);if(!base||!current)return null;let commitAndParents=await runGitAsync(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}function resolveRemoteRefsContainingHead(directory,headSha){let output=runGit(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}async function resolveRemoteRefsContainingHeadAsync(directory,headSha){let output=await runGitAsync(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}function resolvePrWorkflowRevisionDigest(directory,baseHeadSha){let projectRoot=path10.resolve(directory),baseHead=runGit(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),diffNames=runGit(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha]),porcelain=runGit(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!baseHead||diffNames===null||porcelain===null)return null;let porcelainPaths=parsePorcelainPaths(porcelain);if(!porcelainPaths)return null;let changedPaths=[...new Set([...parseNulPaths(diffNames),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>REVISION_MAX_FILES)return null;let hash2=createHash4("sha256");hash2.update(`base\x00${baseHead}\x00`);let totalBytes=0;for(let relativePath of changedPaths){let resolvedPath=path10.resolve(projectRoot,relativePath),relativeToRoot=path10.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path10.isAbsolute(relativeToRoot))return null;hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=fs7.lstatSync(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return null}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${fs7.readlinkSync(resolvedPath)}\x00`);continue}catch{return null}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>REVISION_MAX_TOTAL_BYTES)return null;try{hash2.update(`file\x00${stats2.mode}\x00`),hash2.update(fs7.readFileSync(resolvedPath)),hash2.update("\x00")}catch{return null}}return hash2.digest("hex")}async function resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha){let projectRoot=path10.resolve(directory),[baseHead,diffNames,porcelain]=await Promise.all([runGitAsync(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),runGitAsync(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha]),runGitAsync(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])]);if(!baseHead||diffNames===null||porcelain===null)return null;let porcelainPaths=parsePorcelainPaths(porcelain);if(!porcelainPaths)return null;let changedPaths=[...new Set([...parseNulPaths(diffNames),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>REVISION_MAX_FILES)return null;let hash2=createHash4("sha256");hash2.update(`base\x00${baseHead}\x00`);let totalBytes=0,chunksSinceYield=0;for(let relativePath of changedPaths){let resolvedPath=path10.resolve(projectRoot,relativePath),relativeToRoot=path10.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path10.isAbsolute(relativeToRoot))return null;hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=await fs7.promises.lstat(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return null}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${await fs7.promises.readlink(resolvedPath)}\x00`);continue}catch{return null}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>REVISION_MAX_TOTAL_BYTES)return null;hash2.update(`file\x00${stats2.mode}\x00`);let handle;try{handle=await fs7.promises.open(resolvedPath,"r");let buffer=Buffer.allocUnsafe(REVISION_READ_CHUNK_BYTES);for(let position=0;position<stats2.size;){let length=Math.min(REVISION_READ_CHUNK_BYTES,stats2.size-position),{bytesRead}=await handle.read(buffer,0,length,position);if(bytesRead<=0)return null;if(hash2.update(buffer.subarray(0,bytesRead)),position+=bytesRead,chunksSinceYield++,chunksSinceYield>=REVISION_YIELD_EVERY_CHUNKS)chunksSinceYield=0,await _internals6.yieldControl()}hash2.update("\x00")}catch{return null}finally{await handle?.close().catch(()=>{return})}}return hash2.digest("hex")}function parseNulPaths(output){return output.split("\x00").filter((entry)=>entry.length>0)}function parsePorcelainPaths(output){let entries=parseNulPaths(output),paths=[];for(let index=0;index<entries.length;index++){let entry=entries[index];if(entry.length<4||entry[2]!==" ")return null;let status=entry.slice(0,2),changedPath=entry.slice(3);if(!changedPath)return null;if(paths.push(changedPath),status.includes("R")||status.includes("C")){let originalPath=entries[++index];if(!originalPath)return null;paths.push(originalPath)}}return[...new Set(paths)]}function parsePorcelainV2Snapshot(output){let records=output.split("\x00"),headers=[];while(records[0]?.startsWith("# "))headers.push(records.shift());let oidMatch=headers.join(`
|
|
172
|
+
`).some((line)=>GITLINK_MODE_PATTERN.test(line.trim()));return{changedLines,changedFiles,hasSubmoduleChange}}function isSafeGitRevisionToken(value){return/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")}function resolveCurrentUpstreamRemoteRef(directory){let upstream=runGit(directory,["rev-parse","--symbolic-full-name","@{upstream}"]);if(!upstream?.startsWith("refs/remotes/")||upstream.endsWith("/HEAD"))return null;return upstream}function resolveCurrentUpstreamPushTarget(directory){let localBranchRef=runGit(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=runGit(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}async function resolveCurrentUpstreamPushTargetAsync(directory){let localBranchRef=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=await runGitAsync(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}function resolveExactRemoteBranchHead(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=runGit(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}async function resolveExactRemoteBranchHeadAsync(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=await runGitAsync(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}function resolveGitControlStateDigest(directory){let head=runGit(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=runGit(directory,["symbolic-ref","--quiet","HEAD"]),upstream=resolveCurrentUpstreamPushTarget(directory),refs=runGit(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=runGit(directory,["config","--null","--show-origin","--show-scope","--list"]),index=runGit(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}async function resolveGitControlStateDigestAsync(directory){let head=await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]),upstream=await resolveCurrentUpstreamPushTargetAsync(directory),refs=await runGitAsync(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=await runGitAsync(directory,["config","--null","--show-origin","--show-scope","--list"]),index=await runGitAsync(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}function resolveIsWorkingTreeClean(directory){let status=runGit(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}async function resolveIsWorkingTreeCleanAsync(directory){let status=await runGitAsync(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}function resolveCommitCountSince(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let output=runGit(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`,"--"]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}async function resolveCommitCountSinceAsync(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let output=await runGitAsync(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`,"--"]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}function resolveIsExactSingleChildCommit(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let base=runGit(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`,"--"]),current=runGit(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`,"--"]);if(!base||!current)return null;let commitAndParents=runGit(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}async function resolveIsExactSingleChildCommitAsync(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let base=await runGitAsync(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`,"--"]),current=await runGitAsync(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`,"--"]);if(!base||!current)return null;let commitAndParents=await runGitAsync(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}function resolveRemoteRefsContainingHead(directory,headSha){let output=runGit(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}async function resolveRemoteRefsContainingHeadAsync(directory,headSha){let output=await runGitAsync(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}function resolvePrWorkflowRevisionDigest(directory,baseHeadSha){let projectRoot=path10.resolve(directory),baseHead=runGit(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),diffNames=runGit(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha]),porcelain=runGit(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"]);if(!baseHead||diffNames===null||porcelain===null)return null;let porcelainPaths=parsePorcelainPaths(porcelain);if(!porcelainPaths)return null;let changedPaths=[...new Set([...parseNulPaths(diffNames),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>REVISION_MAX_FILES)return null;let hash2=createHash4("sha256");hash2.update(`base\x00${baseHead}\x00`);let totalBytes=0;for(let relativePath of changedPaths){let resolvedPath=path10.resolve(projectRoot,relativePath),relativeToRoot=path10.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path10.isAbsolute(relativeToRoot))return null;hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=fs7.lstatSync(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return null}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${fs7.readlinkSync(resolvedPath)}\x00`);continue}catch{return null}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>REVISION_MAX_TOTAL_BYTES)return null;try{hash2.update(`file\x00${stats2.mode}\x00`),hash2.update(fs7.readFileSync(resolvedPath)),hash2.update("\x00")}catch{return null}}return hash2.digest("hex")}async function resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha){let projectRoot=path10.resolve(directory),[baseHead,diffNames,porcelain]=await Promise.all([runGitAsync(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`]),runGitAsync(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha]),runGitAsync(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"])]);if(!baseHead||diffNames===null||porcelain===null)return null;let porcelainPaths=parsePorcelainPaths(porcelain);if(!porcelainPaths)return null;let changedPaths=[...new Set([...parseNulPaths(diffNames),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>REVISION_MAX_FILES)return null;let hash2=createHash4("sha256");hash2.update(`base\x00${baseHead}\x00`);let totalBytes=0,chunksSinceYield=0;for(let relativePath of changedPaths){let resolvedPath=path10.resolve(projectRoot,relativePath),relativeToRoot=path10.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path10.isAbsolute(relativeToRoot))return null;hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=await fs7.promises.lstat(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return null}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${await fs7.promises.readlink(resolvedPath)}\x00`);continue}catch{return null}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>REVISION_MAX_TOTAL_BYTES)return null;hash2.update(`file\x00${stats2.mode}\x00`);let handle;try{handle=await fs7.promises.open(resolvedPath,"r");let buffer=Buffer.allocUnsafe(REVISION_READ_CHUNK_BYTES);for(let position=0;position<stats2.size;){let length=Math.min(REVISION_READ_CHUNK_BYTES,stats2.size-position),{bytesRead}=await handle.read(buffer,0,length,position);if(bytesRead<=0)return null;if(hash2.update(buffer.subarray(0,bytesRead)),position+=bytesRead,chunksSinceYield++,chunksSinceYield>=REVISION_YIELD_EVERY_CHUNKS)chunksSinceYield=0,await _internals6.yieldControl()}hash2.update("\x00")}catch{return null}finally{await handle?.close().catch(()=>{return})}}return hash2.digest("hex")}function parseNulPaths(output){return output.split("\x00").filter((entry)=>entry.length>0)}function parsePorcelainPaths(output){let entries=parseNulPaths(output),paths=[];for(let index=0;index<entries.length;index++){let entry=entries[index];if(entry.length<4||entry[2]!==" ")return null;let status=entry.slice(0,2),changedPath=entry.slice(3);if(!changedPath)return null;if(paths.push(changedPath),status.includes("R")||status.includes("C")){let originalPath=entries[++index];if(!originalPath)return null;paths.push(originalPath)}}return[...new Set(paths)]}function parsePorcelainV2Snapshot(output){let records=output.split("\x00"),headers=[];while(records[0]?.startsWith("# "))headers.push(records.shift());let oidMatch=headers.join(`
|
|
173
173
|
`).match(/^# branch\.oid (.+)$/m);if(!oidMatch)return null;let gitHead=/^[0-9a-f]{6,64}$/i.test(oidMatch[1])?oidMatch[1]:oidMatch[1]==="(initial)"?null:null,paths=[];for(let index=0;index<records.length;index++){let record2=records[index];if(!record2)continue;if(record2.startsWith("? ")){paths.push(record2.slice(2));continue}if(record2.startsWith("1 ")){let changedPath=porcelainV2PathAfterFields(record2,8);if(!changedPath)return null;paths.push(changedPath);continue}if(record2.startsWith("2 ")){let changedPath=porcelainV2PathAfterFields(record2,9),originalPath=records[++index];if(!changedPath||!originalPath)return null;paths.push(changedPath,originalPath);continue}if(record2.startsWith("u ")){let changedPath=porcelainV2PathAfterFields(record2,10);if(!changedPath)return null;paths.push(changedPath);continue}return null}return{gitHead,changedFiles:[...new Set(paths)]}}function porcelainV2PathAfterFields(record2,fields){let offset=0;for(let index=0;index<fields;index++){let delimiter=record2.indexOf(" ",offset);if(delimiter<0)return null;offset=delimiter+1}return record2.slice(offset)||null}function captureWorkspaceSnapshot(directory,optionsOrScope=null,prHeadShaArg=null){let scope=typeof optionsOrScope==="object"&&optionsOrScope!==null?optionsOrScope.scope??null:optionsOrScope,configuredPrHeadSha=(()=>{if(typeof optionsOrScope!=="object"||optionsOrScope===null)return prHeadShaArg;return optionsOrScope.prHeadSha??null})(),resolveCurrentPrHeadSha=typeof optionsOrScope==="object"&&optionsOrScope!==null&&optionsOrScope.resolveCurrentPrHeadSha===!0,upstreamBefore=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,porcelain=runGit(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),snapshot=porcelain===null?null:parsePorcelainV2Snapshot(porcelain),upstreamAfter=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,prHeadSha=resolveCurrentPrHeadSha?upstreamBefore&&upstreamBefore===upstreamAfter?upstreamBefore:null:configuredPrHeadSha;return{directory:path10.resolve(directory),gitHead:snapshot?.gitHead??null,dirtyHash:porcelain===null?null:digest(porcelain),changedFiles:snapshot?.changedFiles??null,prHeadSha,scope}}function changedFilesSinceSnapshot(directory,baseline){if(!baseline?.gitHead||baseline.changedFiles==null)return null;if(baseline.changedFiles.length>0)return null;let current=captureWorkspaceSnapshot(directory);if(!current.gitHead||current.changedFiles==null)return null;let changed=new Set(current.changedFiles);if(baseline.gitHead!==current.gitHead){let committed=runGit(directory,["diff","--name-only","-z",baseline.gitHead,current.gitHead]);if(committed===null)return null;for(let changedPath of parseNulPaths(committed))changed.add(changedPath)}return[...changed]}function workspaceSnapshotMatches(expected,current){if(!expected)return{ok:!0};if(path10.resolve(expected.directory)!==path10.resolve(current.directory))return{ok:!1,reason:`directory changed: expected ${expected.directory}, got ${current.directory}`};let checks3=["gitHead","dirtyHash","prHeadSha"];for(let key of checks3){let expectedValue=expected[key];if(expectedValue===null)continue;if(current[key]!==expectedValue)return{ok:!1,reason:`${key} changed: expected ${expectedValue}, got ${current[key]??"unknown"}`}}return{ok:!0}}function compareWorkspaceSnapshots(expected,current){let result=workspaceSnapshotMatches(expected,current);if(result.ok)return{stale:!1};return{stale:!0,reason:result.reason}}function digest(text){return createHash4("sha256").update(text).digest("hex")}var GIT_SNAPSHOT_TIMEOUT_MS=3000,GIT_SNAPSHOT_MAX_BUFFER=524288,REVISION_MAX_FILES=5000,REVISION_MAX_TOTAL_BYTES=67108864,REVISION_READ_CHUNK_BYTES=65536,REVISION_YIELD_EVERY_CHUNKS=16,GITLINK_MODE_PATTERN,compareWorkspaceSnapshot,_internals6;var init_workspace_snapshot=__esm(()=>{GITLINK_MODE_PATTERN=/^:\d{6} 160000 |^:160000 \d{6} /;compareWorkspaceSnapshot=workspaceSnapshotMatches;_internals6={spawnSync:child_process.spawnSync,yieldControl:()=>new Promise((resolve7)=>setImmediate(resolve7)),parsePorcelainV2Snapshot}});import{createHash as createHash5,randomUUID as randomUUID2}from"node:crypto";import{readFileSync as readFileSync6}from"node:fs";import*as fsp2 from"node:fs/promises";import*as path11 from"node:path";function computePrReviewDepthTier(stats2){if(!stats2)return"L";if(stats2.hasSubmoduleChange)return"L";if(stats2.changedLines<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.smallMaxChangedLines&&stats2.changedFiles<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.smallMaxChangedFiles)return"S";if(stats2.changedLines<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.mediumMaxChangedLines&&stats2.changedFiles<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.mediumMaxChangedFiles)return"M";return"L"}async function activatePrWorkflow(directory,sessionID,mode,options={}){let normalizedSessionID=normalizeSessionID(sessionID),existing=await readPrWorkflowGateState(directory,normalizedSessionID);if(existing?.mode===mode)return options.prHeadSha?bindPrWorkflowHead(directory,normalizedSessionID,options.prHeadSha):existing;if(existing)throw Error(`BLOCKED: session "${normalizedSessionID}" already has an active ${existing.mode} workflow; complete it before starting ${mode}`);let initialHead=options.prHeadSha?await assertCurrentCheckoutHead(directory,options.prHeadSha):void 0,timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:0,sessionID:normalizedSessionID,mode,activatedAt:timestamp,updatedAt:timestamp,...initialHead?{prHeadSha:initialHead}:{}};return await persistState(directory,nextState),nextState}async function readPrWorkflowGateState(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(state)rememberState(directory,state);else trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID));return state}async function withPrWorkflowCheckoutPreparationLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizedSessionID}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (which activates PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (which activates PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*". Run the appropriate command first, then retry checkout preparation.`);if(state.prHeadSha)throw Error(`BLOCKED: ${state.mode} checkout preparation is allowed only before the PR head is bound`);return action(state)})}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{if(expectedRevision!==void 0){let current=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!current||current.revision!==expectedRevision)throw Error("BLOCKED: PR workflow gate state changed during terminal completion; revalidate the current session state before retrying")}try{await fsp2.rm(workflowGateStatePath(directory,normalizedSessionID),{force:!0})}catch(error49){if(error49.code!=="ENOENT")throw error49}trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID))})}async function abortPrWorkflow(directory,sessionID,options={}){let state=await requireAnyActiveState(directory,sessionID);if(options.expectedMode&&state.mode!==options.expectedMode)throw wrongModeError(state,options.expectedMode);if(state.prFeedbackReadyToPublish)throw Error(`BLOCKED: ${state.mode} is armed for publication; abort is blocked. Complete the workflow with complete_pr_workflow (or push the bound commit first) before aborting.`);let openLanes=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(openLanes.length>0){let laneIds=openLanes.map((record2)=>record2.laneId??record2.subagentSessionId??"unknown").filter(Boolean).slice(0,10).join(", ");throw Error(`BLOCKED: ${state.mode} abort refused while ${openLanes.length} PR workflow lane(s) are still in flight (lane ids: ${laneIds}). Collect their results or let them settle before aborting.`)}let sanitizedReason=typeof options.reason==="string"?options.reason.trim().slice(0,500):void 0,abortEvent={type:"pr_workflow_aborted",timestamp:isoNow(),sessionID:state.sessionID,mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length,...sanitizedReason?{reason:sanitizedReason}:{}};try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp2.appendFile(eventsPath,`${JSON.stringify(abortEvent)}
|
|
174
174
|
`,"utf-8")}catch{}return await clearPrWorkflowGateState(directory,sessionID,state.revision),{mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length}}async function bindPrWorkflowHead(directory,sessionID,prHeadSha){let state=await requireAnyActiveState(directory,sessionID),normalizedHead=normalizePrHeadSha(prHeadSha);if(await assertCurrentCheckoutHead(directory,normalizedHead),!state.prHeadSha)await assertPrReviewCleanCheckout(directory,state.mode);if(!state.prHeadSha&&state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state.prHeadSha&&state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state.mode} workflow is bound to PR head "${state.prHeadSha}"; received "${normalizedHead}"`);if(state.prHeadSha===normalizedHead)return state;let nextState={...state,prHeadSha:normalizedHead,updatedAt:isoNow()};return await persistState(directory,nextState),nextState}async function bindPrReviewBase(directory,sessionID,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw Error("BLOCKED: only PR_REVIEW can bind a review merge base");let baseRef=options.baseRef.trim(),baseSha=normalizePrHeadSha(options.baseSha).toLowerCase();if(!baseRef)throw Error("BLOCKED: PR_REVIEW base_ref must not be empty");if(state.prReviewBaseRef&&state.prReviewBaseRef!==baseRef||state.prReviewBaseSha&&state.prReviewBaseSha!==baseSha)throw Error(`BLOCKED: active PR_REVIEW is bound to merge-base scope "${state.prReviewBaseRef??"(unbound)"}" at "${state.prReviewBaseSha??"(unbound)"}"; received "${baseRef}" at "${baseSha}"`);if(state.prReviewBaseRef===baseRef&&state.prReviewBaseSha===baseSha)return state;let prHeadSha=normalizePrHeadSha(options.prHeadSha).toLowerCase(),diffStats=await _test_exports.resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha);return state={...state,prReviewBaseRef:baseRef,prReviewBaseSha:baseSha,prReviewDepthTier:computePrReviewDepthTier(diffStats),...diffStats?{prReviewDiffStats:diffStats}:{},updatedAt:isoNow()},await persistState(directory,state),state}async function assertCurrentCheckoutHead(directory,expectedHead){let normalizedExpected=normalizePrHeadSha(expectedHead),currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error(`BLOCKED: cannot resolve the current Git HEAD in "${directory}" to verify against PR head "${normalizedExpected}". This means Git could not resolve HEAD (the working directory may not be a Git repository, HEAD may be unborn, the commit object may be missing in a shallow clone, the Git binary may not be on PATH, or the bounded Git invocation may have timed out). Verify with: git -C "${directory}" rev-parse --verify HEAD^{commit}`);if(currentHead.toLowerCase()!==normalizedExpected.toLowerCase())throw Error(`BLOCKED: current checkout HEAD "${currentHead}" does not match PR head "${normalizedExpected}" (working directory: "${directory}"). Run these bare, standalone commands from that directory: if the commit is not present locally, \`git fetch origin <pr-head-ref>\`; then \`git switch --detach ${normalizedExpected}\`. Do not prefix the switch with \`git -C\`; the read-only shell classifier refuses \`git -C ... switch\`.`);return normalizedExpected}async function assertPrReviewCleanCheckout(directory,mode="PR_REVIEW"){if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error(`BLOCKED: ${mode} requires a clean index and working tree at the exact PR head`)}async function assertPrFeedbackTrackingCheckout(directory,prHeadSha){let upstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!upstream)throw Error("BLOCKED: PR_FEEDBACK requires a current local branch bound to an exact remote name, remote branch ref, and remote-tracking ref before the first head bind; detached or non-tracking checkouts are not allowed");if(!(await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha))?.includes(upstream.remoteTrackingRef))throw Error(`BLOCKED: PR_FEEDBACK upstream "${upstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}" before the first head bind`)}async function enforcePrWorkflowDispatchLanesAsync(directory,sessionID,toolName){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return null;if(toolName===DISPATCH_TOOL_NAME)return state;if(toolName===BLOCKING_DISPATCH_TOOL_NAME)throw Error(`BLOCKED: active ${state.mode} workflow for session "${state.sessionID}" requires ${DISPATCH_TOOL_NAME}; ${BLOCKING_DISPATCH_TOOL_NAME} is not allowed`);return state}async function enforcePrReviewBaseDimensions(directory,sessionID,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");let normalizedLanes=normalizeWorkflowLanes(lanes),claimedDimensionIds=normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]);if(claimedDimensionIds.filter((laneId)=>!PR_REVIEW_BASE_DIMENSION_IDS.includes(laneId)).length>0){let expected=PR_REVIEW_BASE_DIMENSION_IDS.join(", "),received=claimedDimensionIds.join(", ")||"(none)";throw Error(`BLOCKED: PR_REVIEW base dispatch lane ids must be drawn from: ${expected}. Received: ${received}`)}if((state.prReviewDepthTier??"L")==="L"&&normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier L requires one dedicated lane per dimension; consolidated owned_workflow_lanes are allowed only at tiers S and M");let batchId=normalizeBatchId(options.batchId),previous=state.prReviewBaseDispatches??[];if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW base batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW base batch limit reached");let record2={batchId,lanes:normalizedLanes.map((lane)=>({laneId:lane.laneId,workflowLane:lane.workflowLane,...lane.ownedWorkflowLanes?{ownedWorkflowLanes:lane.ownedWorkflowLanes}:{}})),validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prReviewBaseDispatches:[...previous,record2],prReviewBaseDispatch:record2};return await persistState(directory,nextState),nextState}async function assertPrReviewBaseCoverageSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),batches=state.prReviewBaseDispatches??[];if(batches.length===0)throw Error("BLOCKED: PR_REVIEW requires at least one base batch");let covered=new Set;for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt);for(let obligation of successful)covered.add(obligation)}let missing=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!covered.has(dimension));if(missing.length>0||covered.size!==PR_REVIEW_BASE_DIMENSION_IDS.length)throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete; missing dimensions: ${missing.join(", ")||"(none)"}`);return state}async function recordPrReviewValidationBatch(directory,sessionID,phase,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW validation dispatch requires a completed trigger evaluation");if(phase==="reviewer"&&(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state=await assertPrReviewValidationSettled(directory,sessionID,"council");else if(phase==="critic")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer");let normalizedLanes=normalizeWorkflowLanes(lanes);if((phase==="reviewer"||phase==="critic")&&normalizedLanes.some((lane)=>!lane.reviewItemIds?.length))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes require non-empty review_item_ids ownership`);if(phase==="reviewer"||phase==="critic"){assertNoDuplicates(normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),`PR_REVIEW ${phase} review item ownership`);let assigned=normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),required2=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state):derivePrReviewCriticInventory(directory,state);assertExactStringSet(assigned,required2,`PR_REVIEW ${phase} ownership`)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewValidationBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW validation batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached");let record2={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"):previous,nextState={...state,updatedAt:isoNow(),prReviewValidationBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrReviewValidationSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),declaredPhases=new Set((state.prReviewValidationBatches??[]).map((batch)=>batch.phase)),phases=phase?[phase]:["council","reviewer","critic"].filter((candidate)=>declaredPhases.has(candidate));for(let requiredPhase of phases){let validationBatches=state.prReviewValidationBatches??[],forbiddenSubagentSessionIds=new Set;if(requiredPhase==="critic")for(let reviewerBatch of validationBatches.filter((batch)=>batch.phase==="reviewer"))for(let record2 of findByBatchId(directory,reviewerBatch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)forbiddenSubagentSessionIds.add(subagentSessionId)}let batches=validationBatches.filter((batch)=>batch.phase===requiredPhase);if(requiredPhase==="reviewer"){let latestCouncilIndex=-1;for(let index=0;index<validationBatches.length;index++)if(validationBatches[index]?.phase==="council")latestCouncilIndex=index;if(latestCouncilIndex>=0)batches=validationBatches.slice(latestCouncilIndex+1).filter((batch)=>batch.phase==="reviewer")}if(batches.length===0)throw Error(requiredPhase==="reviewer"&&declaredPhases.has("council")?"BLOCKED: PR_REVIEW requires at least one reviewer batch after the latest council batch":`BLOCKED: PR_REVIEW requires at least one ${requiredPhase} batch`);let allObligations=new Set(batches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane))),settled=new Set,hasFullySuccessfulExactBatch=!1;for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${requiredPhase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds);if(successful.size===batch.lanes.length&&batch.lanes.every((lane)=>successful.has(lane.workflowLane)))hasFullySuccessfulExactBatch=!0;for(let obligation of successful)settled.add(obligation)}if((requiredPhase==="reviewer"||requiredPhase==="critic")&&!hasFullySuccessfulExactBatch)throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} requires one fully successful exact batch; complementary partial retries are not a coherent verdict set`);let missing=[...allObligations].filter((obligation)=>!settled.has(obligation));if(missing.length>0)throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} obligations lack successful exact artifacts: ${missing.join(", ")}`)}return state}async function declarePrFeedbackInventory(directory,sessionID,inventoryIds,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let normalizedInventory=normalizeInventoryIds(inventoryIds);if(state.prFeedbackInventory){if(!sameStringArray(state.prFeedbackInventory,normalizedInventory))throw Error("BLOCKED: PR_FEEDBACK inventory is immutable after declaration");return state}let nextState={...state,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState(directory,nextState),nextState}async function enforcePrFeedbackVerificationOwnership(directory,sessionID,ownership,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory||inventory.length===0)throw Error(`BLOCKED: PR_FEEDBACK verification for session "${state.sessionID}" requires a declared feedback inventory before dispatch`);let normalizedOwnership=normalizeOwnership(ownership),inventorySet=new Set(inventory),claimedByItemId=new Map,previous=state.prFeedbackVerifications??[],batchId=normalizeBatchId(options.batchId);if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK verification batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached");for(let record3 of previous)for(let lane of record3.ownership)for(let itemId of lane.ownedItemIds)claimedByItemId.set(itemId,lane.laneId);for(let lane of normalizedOwnership)for(let itemId of lane.ownedItemIds){if(!inventorySet.has(itemId))throw Error(`BLOCKED: PR_FEEDBACK verification lane "${lane.laneId}" owns undeclared item "${itemId}"`);let previousLane=claimedByItemId.get(itemId);if(previousLane&&previousLane!==lane.laneId)throw Error(`BLOCKED: PR_FEEDBACK verification item "${itemId}" is owned by both "${previousLane}" and "${lane.laneId}"`);claimedByItemId.set(itemId,lane.laneId)}let record2={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record2],prFeedbackVerification:record2};return await persistState(directory,nextState),nextState}async function assertPrFeedbackVerificationSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state),inventory=state.prFeedbackInventory,batches=state.prFeedbackVerifications??[];if(!inventory||batches.length===0)throw Error("BLOCKED: PR_FEEDBACK requires an immutable inventory and verification batches");let covered=new Set;for(let batch of batches){let successfulLaneIds=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.ownership.map((lane)=>({laneId:lane.laneId,workflowLane:lane.laneId})),"swarm-pr-feedback:verification",batch.validatedAt,!1,new Set,currentDigest);for(let lane of batch.ownership){if(!successfulLaneIds.has(lane.laneId))continue;if(!feedbackArtifactCoversItems(directory,state,batch.batchId,lane.laneId,lane.ownedItemIds))continue;for(let itemId of lane.ownedItemIds)covered.add(itemId)}}let missing=inventory.filter((itemId)=>!covered.has(itemId));if(missing.length>0||covered.size!==inventory.length)throw Error(`BLOCKED: PR_FEEDBACK verification ownership is incomplete; missing inventory items: ${missing.join(", ")||"(none)"}`);return state}async function recordPrFeedbackStageA(directory,sessionID,revisionDigest,checks3,options={}){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK Stage A receipt is stale because the working-tree revision changed during validation");if(checks3.length<2||checks3.length>258)throw Error("BLOCKED: PR_FEEDBACK Stage A requires two to 258 controller-created check receipts");let optionalCategoryOrder=["build","typecheck","lint"],applicableCategories=options.applicableCategories??optionalCategoryOrder.filter((category)=>checks3.some((check2)=>check2.category===category));if(assertNoDuplicates(applicableCategories,"PR_FEEDBACK Stage A applicable categories"),applicableCategories.some((category)=>!optionalCategoryOrder.includes(category)))throw Error("BLOCKED: PR_FEEDBACK Stage A applicability may contain only build, typecheck, and lint");let required2=new Set(["diff-check","reproduction",...applicableCategories]),singletonSeen=new Set,applicableObligations=[...options.applicableObligations??[]];assertNoDuplicates(applicableObligations.map(({id})=>id),"PR_FEEDBACK Stage A applicable obligations");let requiredObligationIds=new Set(applicableObligations.map(({id})=>id)),commandDigests=new Set,reproductionFeedbackItemIds=[];for(let check2 of checks3){if(["diff-check","reproduction"].includes(check2.category)&&singletonSeen.has(check2.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check2.category}"`);if(singletonSeen.add(check2.category),required2.delete(check2.category),check2.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check2.obligationId);if(!obligation||obligation.category!==check2.category||obligation.workingDirectory!==(check2.workingDirectory??".")||!requiredObligationIds.delete(check2.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check2.obligationId}`);let sourceContract=obligation.source.includes(".pr-validation.json#")?{path:obligation.source.slice(0,obligation.source.lastIndexOf("#")),id:obligation.source.slice(obligation.source.lastIndexOf("#")+1)}:void 0,requiredContract=obligation.validatorContract??sourceContract;if(requiredContract&&(check2.validatorContract?.path!==requiredContract.path||check2.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash5("sha256").update(`${check2.obligationId??check2.category}\x00${check2.workingDirectory??"."}\x00${check2.command.join("\x00")}`).digest("hex");if(commandDigests.has(commandDigest))throw Error("BLOCKED: PR_FEEDBACK Stage A cannot reuse one command as multiple check receipts");if(commandDigests.add(commandDigest),check2.category==="diff-check"&&!sameStringArray(check2.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check2.category==="reproduction"&&(!check2.targets?.length||!check2.feedbackTargets?.length||check2.targets.some((target)=>!check2.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check2.category==="reproduction"){if(reproductionFeedbackItemIds=check2.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check2.feedbackTargets.some((mapping)=>!check2.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required2.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required2].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,state.prFeedbackInventory??[]))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction must map every immutable feedback item exactly once and in declared order");let nextState={...state,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks3],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:optionalCategoryOrder.filter((category)=>applicableCategories.includes(category)),applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:[],prFeedbackReadyToPublish:void 0};return await persistState(directory,nextState),nextState}async function recordPrFeedbackGateBatch(directory,sessionID,phase,lane,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory?.length)throw Error("BLOCKED: PR_FEEDBACK ordered gates require an immutable feedback inventory");let normalized=normalizeOwnership([lane])[0];if(!sameStringArray(normalized.ownedItemIds,inventory))throw Error(`BLOCKED: PR_FEEDBACK ${phase} must own every inventory item exactly once and in declared order`);let phaseIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(phase),prerequisite=PR_FEEDBACK_PHASE_ORDER[phaseIndex-1];if(prerequisite)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,prerequisite);let{prFeedbackStageA:stageA,prFeedbackInventory:refreshedInventory}=state,currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(!stageA||!refreshedInventory||stageA.revisionDigest!==currentDigest||!sameStringArray(stageA.feedbackItemIds??[],refreshedInventory)||options.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires fresh Stage A checks on the current revision`);let batchId=normalizeBatchId(options.batchId),previous=state.prFeedbackGateBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK gate batch id "${batchId}" is already recorded`);let retained=previous.filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<phaseIndex),record2={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrFeedbackGatePhaseSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(state.prFeedbackStageA?.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} cannot use stale Stage A evidence`);if(!sameStringArray(state.prFeedbackStageA?.feedbackItemIds??[],state.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} Stage A reproduction is not bound to the exact immutable feedback inventory`);let batch=[...state.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===phase);if(!batch||batch.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} has no validation batch on the current revision`);if(!successfulObligationsFromExactBatch(directory,state,batch.batchId,[{laneId:batch.laneId,workflowLane:phase,reviewItemIds:batch.itemIds}],`swarm-pr-feedback:${phase}`,batch.validatedAt,!0,new Set,currentDigest).has(phase))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires one complete, non-degraded positive verdict row per inventory item`);if(findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===batch.laneId)?.workspace?.dirtyHash!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} artifact is not bound to the current revision digest`);return assertIndependentFeedbackGateSessions(directory,state,phase),state}function assertIndependentFeedbackGateSessions(directory,state,throughPhase){let throughIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(throughPhase),batches=(state.prFeedbackGateBatches??[]).filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<=throughIndex),seenSessions=new Set;for(let batch of batches){let matching=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).filter((record3)=>record3.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record2=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record2.normalizedAgent===expectedRole||expectedRole==="critic"&&record2.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record2.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record2.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record2.subagentSessionId}"`);seenSessions.add(record2.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let state=await assertPrFeedbackVerificationSettled(directory,sessionID);for(let phase of PR_FEEDBACK_PHASE_ORDER)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,phase);return state}async function assertPrFeedbackPublicationArmed(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),armed=state.prFeedbackReadyToPublish;if(!armed)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK changed after publication was armed; rerun Stage A and every independent gate");if((await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim()!==armed.localHead)throw Error("BLOCKED: PR_FEEDBACK current Git HEAD changed after publication was armed");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK working tree changed after publication was armed");let currentTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!currentTarget||currentTarget.remoteName!==armed.remoteName||currentTarget.remoteBranchRef!==armed.remoteBranchRef||currentTarget.remoteTrackingRef!==armed.remoteRef)throw Error("BLOCKED: PR_FEEDBACK upstream publication target changed after publication was armed");return state}async function markPrReviewTriggerEvaluationComplete(directory,sessionID,artifactPath){let state=await assertPrReviewBaseCoverageSettled(directory,sessionID),normalizedPath=artifactPath.trim();if(!normalizedPath)throw Error("BLOCKED: PR_REVIEW trigger artifact path is required");let nextState={...state,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath};return await persistState(directory,nextState),nextState}async function assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW findings persistence requires the trigger evaluation artifact");let persistedBoundaries=state.prReviewArtifactBoundaries??[],boundaryOrder=["post_explorer","post_reviewer","post_critic"],boundaryIndex=boundaryOrder.indexOf(boundary),requiredPriorBoundary=boundaryOrder[boundaryIndex-1];if(requiredPriorBoundary&&!persistedBoundaries.includes(requiredPriorBoundary))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings require the prior ${requiredPriorBoundary} checkpoint`);if(persistedBoundaries.some((persisted)=>boundaryOrder.indexOf(persisted)>boundaryIndex))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings cannot be persisted after a later checkpoint`);if(boundary==="post_reviewer")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer");else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer"),derivePrReviewCriticInventory(directory,state).length>0)state=await assertPrReviewValidationSettled(directory,sessionID,"critic")}if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state.prReviewArtifactRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory(directory,state),normalizedFindingIds=[...new Set(findingIds)].sort();if(normalizedFindingIds.length!==findingIds.length||JSON.stringify(normalizedFindingIds)!==JSON.stringify([...expectedFindingIds].sort()))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings must exactly cover the discovered candidate inventory`);return state}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(boundary==="post_explorer"){for(let record2 of records)if(record2.status!=="PENDING"||record2.next_action!=="route_to_reviewer")throw Error(`BLOCKED: PR_REVIEW post_explorer record ${record2.finding_id} must remain PENDING and route_to_reviewer`);return}let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state),criticVerdicts=boundary==="post_critic"?deriveLatestPrReviewCriticVerdicts(directory,state):void 0;for(let record2 of records){let reviewer=reviewerVerdicts.get(record2.finding_id);if(!reviewer)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} has no authoritative reviewer verdict`);if(record2.severity&&record2.severity!==reviewer.severity)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} severity differs from its reviewer verdict`);let requiresCritic=reviewer.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(reviewer.severity);if(boundary==="post_reviewer"){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification;if(record2.status!==expectedStatus)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} status differs from its reviewer verdict`);let expectedAction=requiresCritic?"route_to_critic":reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} action does not match reviewer disposition`);continue}if(!requiresCritic){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification,expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.status!==expectedStatus||record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} cannot override its non-critic reviewer disposition`);continue}let critic=criticVerdicts?.get(record2.finding_id);if(!critic)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} has no authoritative critic verdict`);if(record2.severity&&record2.severity!==critic.severity)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} severity differs from its critic verdict`);if(critic.status==="DISPROVED"){if(record2.status!=="DISPROVED"||record2.next_action!=="suppress_with_reason")throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} must preserve the critic DISPROVED disposition`)}else if(record2.status!=="CONFIRMED"||!["report","handoff_to_feedback"].includes(record2.next_action))throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} action does not match its critic verdict`)}}async function markPrReviewArtifactBoundary(directory,sessionID,runId,boundary,artifactPath,findingIds,handoffRequired){let state=await assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds),boundaries=new Set(state.prReviewArtifactBoundaries??[]);boundaries.add(boundary);let nextState={...state,updatedAt:isoNow(),prReviewArtifactRunId:runId,prReviewFindingsPath:artifactPath,prReviewArtifactBoundaries:[...boundaries],prReviewHandoffRequired:handoffRequired};return await persistState(directory,nextState),nextState}async function markPrReviewHandoffComplete(directory,sessionID,runId,artifactPath){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(state.prReviewArtifactRunId!==runId||!(state.prReviewArtifactBoundaries??[]).includes("post_critic"))throw Error("BLOCKED: PR_REVIEW handoff requires the final findings boundary for the same run");let nextState={...state,updatedAt:isoNow(),prReviewHandoffPath:artifactPath};return await persistState(directory,nextState),nextState}async function declarePrFeedbackScope(directory,sessionID,taskId,files){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state),previous=state.prFeedbackScopes??[];if(previous.find((entry)=>entry.taskId===taskId)?.consumedByCallId)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed; use a fresh task_id for any retry`);let record2={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record2]};return await persistState(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_FEEDBACK")return null;let declaration=(state.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID){let declaration=await resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId);if(!declaration)return null;if(declaration.consumedByCallId&&declaration.consumedByCallId!==callID)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed by another Task call`);if(declaration.consumedByCallId===callID)return declaration;let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),nextState={...state,updatedAt:isoNow(),prFeedbackScopes:(state.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?{...entry,consumedByCallId:callID}:entry)};return await persistState(directory,nextState),{...declaration,consumedByCallId:callID}}async function validatePrFeedbackScopeBinding(directory,binding){if(!binding.workflowSessionId||!binding.workflowRevisionDigest)return!1;let declaration=await resolvePrFeedbackScopeDeclaration(directory,binding.workflowSessionId,binding.taskId);return Boolean(declaration&&declaration.consumedByCallId===binding.dispatchCallId&&declaration.revisionDigest===binding.workflowRevisionDigest&&JSON.stringify(declaration.files)===JSON.stringify(binding.files))}async function enforcePrWorkflowToolBefore(directory,sessionID,toolName,args2,generatedAgentNames=[]){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedRoles=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)).map((field)=>{let value=args2?.[field];if(typeof value!=="string"||!value.trim())return"";return resolveGeneratedAgentRole(value.trim(),generatedAgentNames)}),isDirectWrite=WRITE_TOOL_NAMES.includes(normalizedTool),command=typeof args2?.command==="string"?args2.command.trim():"",serializedArgs=JSON.stringify(args2??{}),referencesProtectedWorkflowEvidence=containsProtectedWorkflowPath(command||serializedArgs),isInternalWorkflowTool=isPrWorkflowControllerTool(state.mode,normalizedTool),isShellTool=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool&&command.length>0){let trackingFetchTarget=state.prHeadSha?await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state.prHeadSha,allowFetch:!state.prHeadSha,allowTrackingFetch:Boolean(state.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let isNamedReadOnlyTool=getPrWorkflowToolCapability(normalizedTool,state.mode)!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{});if(referencesProtectedWorkflowEvidence&&!isInternalWorkflowTool&&!isNamedReadOnlyTool&&!isReadOnlyShell)throw Error(`BLOCKED: active ${state.mode} workflow evidence under .swarm is controller-owned and cannot be modified directly`);let isShellCommandRequiringVerification=isShellTool&&command.length>0&&!isReadOnlyShell,isRemoteReviewTool=/(?:git|github|pull|(?:^|[_-])pr(?:[_-]|$)|issue|review)/i.test(normalizedTool),hasRemoteMutationVerb=/(?:^|[_-])(?:add|approve|cancel|close|comment|commit|convert|create|delete|dismiss|edit|mark|merge|push|ready|reopen|rerun|resolve|submit|transfer|unresolve|update)(?:[_-]|$)/i.test(normalizedTool),hasRemoteReadVerb=/(?:^|[_-])(?:github|git)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool)||/(?:^|[_-])(?:github|git)[_-]+(?:pull[_-]+request|pr|issue|review[_-]+thread)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool),isRemoteMutationTool=isRemoteReviewTool&&(hasRemoteMutationVerb||!hasRemoteReadVerb),isRemoteCheckoutTool=/(?:^|[_-])(?:github|git)[_-]+checkout(?:[_-]|$)/i.test(normalizedTool),isShellCheckout=(normalizedTool==="bash"||normalizedTool==="shell")&&(/\bgit\b(?:(?![;&|]).){0,200}\b(?:checkout|switch)\b/i.test(command)||/\bgh\s+pr\s+checkout\b/i.test(command)),stderrMergeNormalizedCommand=command.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"").trim(),isCanonicalReviewCheckout=/^git\s+switch\s+--detach\s+[0-9a-f]{40,64}$/i.test(stderrMergeNormalizedCommand),detachedFeedbackSwitchMatch=command.match(/^git\s+switch\s+--detach\s+(\S+)$/i),isDetachedFeedbackCheckout=Boolean(detachedFeedbackSwitchMatch?.[1]&&isSafeGitRefToken(detachedFeedbackSwitchMatch[1]))||/^gh\s+pr\s+checkout\b.*\s--detach(?:\s|$)/i.test(command),containsGitCommitShell=isShellCommandRequiringVerification&&/\bgit\b(?:(?![;&|]).){0,200}\bcommit\b/i.test(command),isStandaloneGitCommitShell=containsGitCommitShell&&isSafeStandaloneGitCommit(command),isPublicationShell=isShellCommandRequiringVerification&&(/\bgit\b(?:(?![;&|]).){0,200}\bpush\b/i.test(command)||/\bgh\s+(?:api|pr|issue|run)\b/i.test(command)),isPublicationTool=!isInternalWorkflowTool&&isRemoteMutationTool,isCoderTask=isDirectAgentTask&&requestedRoles.length>0&&requestedRoles.every((role)=>role==="coder"),blockedShellDiagnosis=isShellTool&&command&&!isReadOnlyShell&&shellPermissionEnvelope?` ${describeBlockedPrReviewShellCommand(command,shellPermissionEnvelope)}`:"";if(state.mode==="PR_REVIEW"){if(!(isInternalWorkflowTool||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_REVIEW checkout must use standalone commands: fetch the PR head, verify the full commit object with `git cat-file -e <full_pr_head_sha>^{commit}`, then run `git switch --detach <full_pr_head_sha>` and bind that exact head before dispatching explorer lanes. Do not use `--track FETCH_HEAD`."+blockedShellDiagnosis);throw Error("BLOCKED: PR_REVIEW is read-only and fail-closed; only controller tools and positively classified observation tools are allowed, and every agent lane requires structured dispatch_lanes_async"+blockedShellDiagnosis)}return}if(isDirectAgentTask&&!isCoderTask)throw Error("BLOCKED: PR_FEEDBACK reviewer, test, critic, explorer, and unknown agent lanes require structured dispatch_lanes_async provenance");if(!isInternalWorkflowTool&&!isDirectAgentTask&&!isDirectWrite&&!isShellTool&&!isNamedReadOnlyTool)throw Error("BLOCKED: PR_FEEDBACK rejects unclassified plugin/MCP tools; use positively classified observation tools, built-in structured write tools after verification, or the workflow controller");if(state.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK is armed for publication; the approved commit is immutable");if((containsGitCommitShell||isPublicationShell)&&hasUnsafeShellControlSyntax(command))throw Error("BLOCKED: PR_FEEDBACK publication commands must be standalone shell commands without control, redirection, or command-substitution syntax");if(containsGitCommitShell&&!isStandaloneGitCommitShell)throw Error("BLOCKED: PR_FEEDBACK commit must use a standalone git commit command after every ordered local gate passes");if(state.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(isNamedReadOnlyTool)return;if((normalizedTool==="bash"||normalizedTool==="shell")&&command.length>0&&isAllowedPrWorkflowReadOnlyShell(command,{allowCheckout:!1,allowFetch:!1,allowTrackingFetch:!1}))return;if(normalizedTool==="bash"||normalizedTool==="shell"){let armed=(await assertPrFeedbackPublicationArmed(directory,sessionID)).prFeedbackReadyToPublish;if(isSafeExactBoundPush(command,armed))return;throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed")}if(!state.prHeadSha&&isDetachedFeedbackCheckout)throw Error("BLOCKED: PR_FEEDBACK requires a tracked PR branch before the first head bind; detached checkout is valid for PR_REVIEW, not PR_FEEDBACK.");if(isStandaloneGitCommitShell){await assertPrFeedbackReadyToPublish(directory,sessionID);return}if(isPublicationShell||isPublicationTool)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; finish every ordered gate, create the one approved commit, and call complete_pr_workflow before publishing");if(isShellCommandRequiringVerification){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout must use a safe standalone pre-bind form: `gh pr checkout <number-or-url>` without force/submodule flags, or `git switch -c <local> --track <remote>/<branch>`. Detached checkouts are not allowed in PR_FEEDBACK. Then verify exact HEAD, a clean tree, and the intended upstream before dispatching feedback lanes.");throw Error("BLOCKED: PR_FEEDBACK shell commands fail closed unless they are explicit read-only intake or the one standalone approved git commit; use structured coder/write tools for fixes and run_pr_feedback_stage_a for validation")}if(!isDirectWrite&&!isShellCommandRequiringVerification&&!isRemoteMutationTool&&!isCoderTask&&normalizedTool!=="prepare_pr_feedback_scope")return;if(normalizedTool==="abort_pr_workflow")return;await assertPrFeedbackVerificationSettled(directory,sessionID)}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha){let state=await requireBoundState(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state.prHeadSha}"`);let open3=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(open3.length>0)throw Error(`BLOCKED: ${expectedMode} completion has ${open3.length} unsettled PR workflow lane(s)`);if(expectedMode==="PR_REVIEW"){if(await assertPrReviewCleanCheckout(directory),await assertPrReviewBaseCoverageSettled(directory,sessionID),!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW completion requires a persisted trigger evaluation artifact");if((state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council");await assertPrReviewValidationSettled(directory,sessionID,"reviewer");let criticInventory=derivePrReviewCriticInventory(directory,state);if(criticInventory.length>0){if(!(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic"))throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${criticInventory.join(", ")}`);await assertPrReviewValidationSettled(directory,sessionID,"critic")}let requiredArtifactBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state.prReviewArtifactBoundaries??[]),missingArtifactBoundaries=requiredArtifactBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state.prReviewFindingsPath||missingArtifactBoundaries.length>0)throw Error(`BLOCKED: PR_REVIEW completion requires durable findings checkpoints; missing: ${missingArtifactBoundaries.join(", ")||"findings path"}`);if(state.prReviewHandoffRequired&&!state.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact")}else{let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let localHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");if(await _test_exports.resolveCommitCountSinceAsync(directory,state.prHeadSha,localHead)!==1)throw Error("BLOCKED: PR_FEEDBACK publication requires exactly one descendant commit after the immutable intake head");if(await _test_exports.resolveIsExactSingleChildCommitAsync(directory,state.prHeadSha,localHead)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication commit must be a non-merge direct child of the immutable intake head");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication requires a clean index and working tree so all approved content is captured by the bound commit");let upstreamTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!upstreamTarget)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a current branch bound to an exact remote name, remote branch ref, and remote-tracking ref");return await persistState(directory,{...readyState,updatedAt:isoNow(),prFeedbackReadyToPublish:{revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,validatedAt:isoNow()}}),"ready-to-publish"}if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK publication revision differs from the independently approved content digest");let publishedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports.resolveExactRemoteBranchHeadAsync(directory,armed.remoteName,armed.remoteBranchRef);if(!publishedHead||publishedHead!==armed.localHead||!remoteRefs?.includes(armed.remoteRef)||remoteHead?.toLowerCase()!==armed.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK completion requires approved commit ${armed.localHead} at current Git HEAD and intended remote-tracking ref ${armed.remoteRef} at that exact commit`)}return await _test_exports.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,state.revision),"completed"}async function requireAnyActiveState(directory,sessionID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*".`);return state}async function requireBoundState(directory,sessionID,expectedMode){let state=await requireAnyActiveState(directory,sessionID);if(state.mode!==expectedMode)throw wrongModeError(state,expectedMode);if(!state.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state.prHeadSha),await assertPrReviewCleanCheckout(directory);return state}function wrongModeError(state,expectedMode){return Error(`BLOCKED: session "${state.sessionID}" is active in ${state.mode}, not ${expectedMode}`)}function normalizeWorkflowLanes(lanes){if(!Array.isArray(lanes)||lanes.length===0)throw Error("BLOCKED: PR workflow lane validation requires at least one lane");let normalized=lanes.map((lane)=>{let workflowLane=lane.workflowLane?.trim(),laneId=lane.laneId?.trim()||workflowLane;if(!workflowLane||!laneId)throw Error("BLOCKED: PR workflow lane validation requires every lane to have non-empty laneId and workflow_lane values");let reviewItemIds=lane.reviewItemIds?.map((itemId)=>itemId.trim());if(reviewItemIds?.some((itemId)=>!itemId))throw Error("BLOCKED: PR workflow review_item_ids must not contain empty values");if(reviewItemIds)assertNoDuplicates(reviewItemIds,"review item ids within one lane");let ownedWorkflowLanes=lane.ownedWorkflowLanes?.map((owned)=>owned.trim());if(ownedWorkflowLanes){if(ownedWorkflowLanes.some((owned)=>!owned))throw Error("BLOCKED: PR workflow owned_workflow_lanes must not contain empty values");if(assertNoDuplicates(ownedWorkflowLanes,"owned workflow lanes within one lane"),!ownedWorkflowLanes.includes(workflowLane))throw Error(`BLOCKED: PR workflow lane "${laneId}" must include its own workflow_lane "${workflowLane}" in owned_workflow_lanes`)}return{laneId,workflowLane,...reviewItemIds?{reviewItemIds}:{},...ownedWorkflowLanes?{ownedWorkflowLanes}:{}}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"lane ids"),assertNoDuplicates(normalized.map((lane)=>lane.workflowLane),"workflow lane ids"),assertNoDuplicates(normalized.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]),"owned workflow lane ids across lanes"),normalized}function normalizeInventoryIds(inventoryIds){if(!Array.isArray(inventoryIds)||inventoryIds.length===0)throw Error("BLOCKED: PR_FEEDBACK inventory declaration requires at least one feedback item id");let normalized=inventoryIds.map((inventoryId)=>{let itemId=inventoryId.trim();if(!itemId)throw Error("BLOCKED: PR_FEEDBACK inventory declaration contains an empty item id");return itemId});return assertNoDuplicates(normalized,"inventory item ids"),normalized.sort()}function normalizeOwnership(ownership){if(!Array.isArray(ownership)||ownership.length===0)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires at least one lane declaration");let normalized=ownership.map((lane)=>{let laneId=lane.laneId?.trim();if(!laneId)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires every lane to have a non-empty laneId");let ownedItemIds=normalizeInventoryIds(lane.ownedItemIds);return{laneId,ownedItemIds}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"PR_FEEDBACK verification lane ids"),normalized}function assertNoDuplicates(values,label){let seen=new Set;for(let value of values){if(seen.has(value))throw Error(`BLOCKED: duplicate ${label} are not allowed: ${value}`);seen.add(value)}}function containsProtectedWorkflowPath(value){return/(?:^|[^A-Za-z0-9_.-])\.swarm(?:[\\/]|$)/i.test(value.replace(/\\\\/g,"\\"))}function isPrWorkflowControllerTool(mode,toolName){if(PR_WORKFLOW_SHARED_CONTROLLER_TOOLS.has(toolName))return!0;return mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS.has(toolName):PR_FEEDBACK_CONTROLLER_TOOLS.has(toolName)}function isTrustedPrWorkflowToolInvocationSafe(toolName,args2){if(toolName==="lint")return args2.mode==="check";if(toolName==="sast_scan")return args2.capture_baseline!==!0;return!0}function isAllowedPrReviewReadOnlyToolName(toolName){if(PR_REVIEW_READ_ONLY_TOOL_NAMES.has(toolName))return!0;let tokens=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens.some((token)=>/^(?:add|alter|and|append|apply|approve|cancel|checkout|close|comment|commit|convert|create|delete|destroy|dismiss|drop|edit|execute|grant|insert|mark|merge|move|patch|prepend|publish|push|ready|remove|rename|replace|resolve|rerun|revoke|run|send|submit|then|transfer|truncate|unresolve|update|upload|write)$/i.test(token)))return!1;return tokens.some((token)=>/^(?:check|checks|diff|fetch|find|get|glob|grep|hover|inspect|list|lookup|open|read|references|scan|screenshot|search|show|status|symbols|tree|view)$/i.test(token))}function readOnlyToolArgumentsAreSafe(value,key="",depth=0){if(depth>8)return!1;let keyTokens=key.replace(/([a-z0-9])([A-Z])/g,"$1_$2").split(/[._:/-]+/).filter(Boolean);if(keyTokens.some((token)=>/^(?:append|body|content|create|data|delete|destination|destroy|edit|insert|mutation|output|patch|payload|prepend|remove|replace|save|set|truncate|update|upload|write)$/i.test(token)))return!1;if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim());if(keyTokens.length===1&&keyTokens.some((token)=>/^(?:action|operation)$/i.test(token)))return typeof value==="string"&&/^(?:check|diff|fetch|find|get|inspect|list|lookup|open|read|scan|search|show|status|view)$/i.test(value.trim());if(/^mode$/i.test(key)&&typeof value==="string")return/^(?:r|rb|read)$/i.test(value.trim());if(typeof value==="string"){if(keyTokens.some((token)=>/^(?:query|request|sql|statement)$/i.test(token))&&/(?:\b(?:alter|call|comment|create|delete|drop|exec(?:ute)?|grant|insert|merge|mutation|replace|revoke|truncate|update|upsert)\b|\bselect\b[\s\S]{0,4000}\binto\s+[A-Za-z_"'`])/i.test(value))return!1;return!/(?:^(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE|write|edit|patch|create|delete|destroy|remove|replace|truncate|update|upload)$|(?:^|[\r\n])\s*(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE)\s+\S+(?:\s+HTTP\/\d(?:\.\d)?)?|\bmutation\b|\b(?:create|drop|alter|truncate)\s+(?:or\s+replace\s+)?(?:table|database|schema|index|view|function|procedure|trigger|sequence)\b|\b(?:delete\s+from|insert\s+into|merge\s+into|replace\s+into|upsert\s+into)\b|\bupdate\s+[A-Za-z0-9_."'`-]+(?:\s+(?:AS\s+)?[A-Za-z0-9_"'`-]+)?\s+set\b|\b(?:grant|revoke)\s+\S+\s+(?:on|from|to)\b|\b(?:call|exec(?:ute)?)\s+[A-Za-z0-9_."'`-]+|\b(?:rm|rmdir|del|remove-item|move-item|set-content|add-content)\b)/i.test(value)}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return!0;if(Array.isArray(value))return value.every((entry)=>readOnlyToolArgumentsAreSafe(entry,key,depth+1));if(typeof value==="object")return Object.entries(value).every(([childKey,childValue])=>readOnlyToolArgumentsAreSafe(childValue,childKey,depth+1));return!1}function normalizePrWorkflowShellCommand(command){let normalized=command.trim(),withoutTrailingMerge=normalized.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"");if(withoutTrailingMerge!==normalized)normalized=withoutTrailingMerge.trim();let strippedCdPrefix=!1;for(let index=0;index<PR_WORKFLOW_MAX_CD_PREFIX_STRIPS;index+=1){let next=normalized.replace(PR_WORKFLOW_CD_PREFIX_PATTERN,"");if(next===normalized)break;normalized=next.trim(),strippedCdPrefix=!0}return{normalized,strippedCdPrefix}}function isAllowedPrWorkflowReadOnlyShell(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," ");if(!normalized)return!1;if(/[\r\n;&|<>`]/.test(inner)||/\$\(|@\(/.test(inner))return!1;if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))return!1;let gitMatch=normalized.match(/^git(?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/i);if(gitMatch?.[1]){if(/^git -C /i.test(normalized)&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))return!1;return isAllowedPrWorkflowGitIntake(gitMatch[1],options)}if(/^gh /i.test(normalized))return isAllowedPrFeedbackGhIntake(normalized);if(/^rg\b/i.test(normalized)&&/\s--pre(?:-glob)?(?:\s|=|$)/i.test(normalized))return!1;return/^(?:rg|grep|cat|Get-Content|Select-String|Test-Path|Get-ChildItem|ls|dir|pwd|which|where)(?:\s|$)/i.test(normalized)}function describeBlockedPrReviewShellCommand(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," "),gitMatch=normalized.match(/^git(?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/i),pointer=" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool.",detail;if(/[\r\n;&|<>`]/.test(inner)||/\$\(|@\(/.test(inner))detail="Reason: compound-syntax (;, &&, |, <, >, backtick, or $()/@()). Run ONE command per call; a single leading `cd <dir> &&` and a trailing `2>&1` are tolerated for reads only.";else if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))detail="Reason: cd-prefix-on-checkout-verb. Run fetch/checkout/switch/branch or `gh pr checkout` bare, with no `cd <dir> &&` prefix.";else if(/^git -C /i.test(normalized)&&gitMatch?.[1]&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))detail="Reason: git -C on a state transition. Run fetch/checkout/switch/branch from the target directory, not via `git -C <dir>`.";else if(!options.allowFetch&&gitMatch?.[1]&&/^fetch(?:\s|$)/i.test(gitMatch[1]))detail=options.allowTrackingFetch?"Reason: bound-fetch-restriction. After the PR head is bound only the exact bound remote-tracking fetch is allowed; read remote state via gh_evidence otherwise.":"Reason: bound-fetch-restriction. Fetch is not permitted in this bound state; read remote state via gh_evidence instead.";else if(gitMatch?.[1]||/^git(?:\s|$)/i.test(normalized))detail="Reason: unlisted git verb. Allowed git reads: status/log/show/diff/rev-parse/merge-base/ls-files/grep/blame/cat-file/for-each-ref, `branch` with listing flags only, `remote -v`, `config --get`.";else if(/^gh(?:\s|$)/i.test(normalized))detail="Reason: unlisted gh form. Allowed gh reads: pr view/diff/checks/status/list, run view/list/watch, issue view/list, search, api GET. If gh is missing, fetch the api.github.com REST URL with the web fetch tool.";else detail="Reason: unlisted binary. Allowed: rg/grep/cat/ls/dir/pwd/which/where plus read-only git/gh intake.";return detail+" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool."}function hasUnsafeShellControlSyntax(command){return/[;&|<>`\r\n]/.test(command)||/\$\(/.test(command)}function isSafeStandaloneGitCommit(command){if(hasUnsafeShellControlSyntax(command))return!1;if(/(?:^|\s)--(?:allow-empty|amend)(?:\s|=|$)/i.test(command))return!1;return/^git(?:\s+-C(?:=|\s+)(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>`]+))?\s+commit(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s;&|<>`]+))*\s*$/i.test(command.trim())}function boundPushTarget(armed){let remote=armed.remoteName,branch=armed.remoteBranchRef.slice(11);if(!armed.remoteBranchRef.startsWith("refs/heads/")||!branch)return null;if(/\s|[;&|<>`]/.test(remote)||/\s|[;&|<>`]/.test(branch))return null;return{remote,branch}}function expectedBoundPushCommand(armed){let target=boundPushTarget(armed);return target?`git push ${target.remote} ${armed.localHead}:refs/heads/${target.branch}`:"(invalid bound remote-tracking ref; restart the workflow)"}function isSafeExactBoundPush(command,armed){if(hasUnsafeShellControlSyntax(command))return!1;let target=boundPushTarget(armed);if(!target)return!1;let match=command.trim().match(/^git\s+push\s+([^\s;&|<>`]+)\s+([^\s;&|<>`]+)\s*$/i);if(!match)return!1;return match[1]===target.remote&&match[2]===`${armed.localHead}:refs/heads/${target.branch}`}function isAllowedPrWorkflowGitIntake(gitArgs,options){if(/(?:--ext-diff|--textconv|--open-files-in-pager|--output(?:=|\s)|--upload-pack(?:=|\s)|--exec(?:=|\s))/i.test(gitArgs))return!1;if(/^(?:status|log|show|diff|rev-parse|merge-base|ls-files|grep|blame|cat-file|for-each-ref|--version|version)(?:\s|$)/i.test(gitArgs))return!0;if(isAllowedReadOnlyGitBranchListing(gitArgs))return!0;if(options.allowFetch&&/^fetch(?:\s|$)/i.test(gitArgs))return!0;if(options.allowTrackingFetch&&isAllowedBoundRemoteTrackingFetch(gitArgs,options.trackingFetchTarget))return!0;if(/^remote(?:\s+-v)?$/i.test(gitArgs))return!0;if(options.allowCheckout&&isAllowedPreBindBranchSetup(gitArgs))return!0;if(options.allowCheckout&&/^(?:checkout|switch)\s+(?:--detach\s+)?[^\s-][^\s]*$/i.test(gitArgs))return!0;return/^config\s+(?:(?:--show-origin|--show-scope|--global|--local|--system|--worktree)\s+)*(?:--list|--get(?:-all)?\s+\S+)$/i.test(gitArgs)}function isAllowedBoundRemoteTrackingFetch(gitArgs,target){if(!target?.remoteName||!target.remoteBranchRef.startsWith("refs/heads/"))return!1;let tokens=gitArgs.trim().split(/\s+/);if(tokens.length!==3||tokens[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens,expectedBranch=target.remoteBranchRef.slice(11);return isSafeGitRefToken(remote)&&!remote.includes("/")&&isSafeGitRefToken(remoteBranch)&&!remoteBranch.startsWith("-")&&!remoteBranch.includes(":")&&remote===target.remoteName&&remoteBranch===expectedBranch}function isAllowedPreBindBranchSetup(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens.length===3&&tokens[0]==="branch"){let upstream=tokens[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens[2]))}return!1}function isAllowedReadOnlyGitBranchListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===0||tokens[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:--list|--contains|--merged|--no-merged|--points-at)$/i.test(token)){listingSelectorInEffect=!0;continue}if(/^(?:-a|--all|-r|--remotes|-v|-vv|--verbose|--show-current|--color|--no-color|--column|--no-column|-i|--ignore-case)$/i.test(token)||/^--(?:sort|format|color)=/i.test(token))continue;if(token.startsWith("-"))return!1;if(!listingSelectorInEffect)return!1}return!0}function isSafeGitRefToken(value){return/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")&&!value.endsWith("/")&&!value.endsWith(".")&&!value.endsWith(".lock")}function isAllowedPrFeedbackGhIntake(command){if(/^gh\s+pr\s+checkout(?:\s|$)/i.test(command))return isAllowedSafeGhPrCheckout(command);if(/^gh\s+--version$/i.test(command)||/^gh\s+pr\s+(?:view|diff|checks|status|list)(?:\s|$)/i.test(command)||/^gh\s+run\s+(?:view|list|watch)(?:\s|$)/i.test(command)||/^gh\s+issue\s+(?:view|list)(?:\s|$)/i.test(command)||/^gh\s+search\s+(?:code|commits|issues|prs|repos)(?:\s|$)/i.test(command)||/^gh\s+auth\s+status(?:\s|$)/i.test(command))return!0;if(!/^gh\s+api(?:\s|$)/i.test(command))return!1;if(/\bmutation\b/i.test(command))return!1;let method=command.match(/\s(?:--method(?:\s+|=)|-X(?:\s+|=)?)([A-Z]+)/i)?.[1];if(method&&method.toUpperCase()!=="GET")return!1;if(/\s(?:--input|--raw-field)(?:\s|=)/i.test(command)||/\s-F(?:\s|=|\S)/.test(command))return!1;return!/\s(?:--field|-f)(?:\s|=)(?!query=)/i.test(command)}function isAllowedSafeGhPrCheckout(command){if(/\s--(?:force|recurse-submodules)(?:\s|=|$)/i.test(command))return!1;let tokens=command.trim().split(/\s+/);if(tokens.length<4||tokens[0]!=="gh"||tokens[1]!=="pr"||tokens[2]!=="checkout")return!1;let target=tokens[3];if(!/^\d+$/.test(target)&&!/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/\d+$/.test(target))return!1;for(let index=4;index<tokens.length;index+=1){let token=tokens[index],repoEquals=token.match(/^--repo=(.+)$/)?.[1];if(repoEquals){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repoEquals))return!1;continue}let branchEquals=token.match(/^--branch=(.+)$/)?.[1];if(branchEquals){if(!isSafeGitRefToken(branchEquals))return!1;continue}if(token==="--repo"||token==="-R"){let repo=tokens[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens[++index];if(!branch||!isSafeGitRefToken(branch))return!1;continue}return!1}return!0}function normalizePrHeadSha(prHeadSha){let normalized=prHeadSha.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty pr_head_sha");return normalized}async function currentPrFeedbackRevisionDigest(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let digest2=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!digest2)throw Error("BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest");return digest2}async function resolvePrWorkflowRevisionDigestForGate(directory,baseHeadSha){if(_test_exports.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _test_exports.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha)}function normalizeBatchId(batchId){let normalized=batchId.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty batch id");return normalized}function sameStringArray(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function assertExactStringSet(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),missing=[...expectedSet].filter((value)=>!actualSet.has(value)),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length!==actualSet.size||actualSet.size!==expectedSet.size||missing.length>0||extra.length>0)throw Error(`BLOCKED: ${label} must exactly cover the mechanically derived inventory; missing: ${missing.join(", ")||"(none)"}; extra: ${extra.join(", ")||"(none)"}`)}function derivePrReviewCandidateInventory(directory,state){let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map;for(let batch of[...state.prReviewBaseDispatches??[]].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt);for(let lane of batch.lanes){let ownedDimensions=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!ownedDimensions.every((dimension)=>successful.has(dimension)))continue;let key=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key,ownedDimensions.length);for(let dimension of ownedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key))continue;seenBaseSourceKeys.add(key);let credited=baseSourceCreditedDimensions.get(key),fullOwnershipCount=baseSourceFullOwnershipCount.get(key)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;for(let batch of[...state.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt);for(let lane of batch.lanes)if(successful.has(lane.workflowLane)&&!selectedCouncilLanes.has(lane.workflowLane))sources.push({batchId:batch.batchId,laneId:lane.laneId,mode:"swarm-pr-review:council"}),selectedCouncilLanes.add(lane.workflowLane)}if(state.prReviewTriggerEvalPath){let triggerPath=validateSwarmPath(directory,state.prReviewTriggerEvalPath),triggerArtifact;try{triggerArtifact=JSON.parse(readFileSync6(triggerPath,"utf-8"))}catch{throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid")}let rows=triggerArtifact.rows;if(!Array.isArray(rows))throw Error("BLOCKED: PR_REVIEW trigger evaluation rows are invalid");let rowIds=rows.map((row)=>typeof row==="object"&&row!==null?row.trigger_id:void 0),provenanceTuples=rows.map((row)=>{if(typeof row!=="object"||row===null)return"";let{source_batch_id:batchId,source_lane_id:laneId}=row;return typeof batchId==="string"&&typeof laneId==="string"&&batchId.trim()&&laneId.trim()?`${batchId}\x00${laneId}`:""});if(!(rows.length===PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length&&new Set(rowIds).size===PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length&&provenanceTuples.every(Boolean)&&PR_REVIEW_REQUIRED_MICRO_LANE_IDS.every((id)=>rowIds.includes(id))&&rows.every((row)=>typeof row==="object"&&row!==null&&row.result==="MATCHED")))throw Error("BLOCKED: PR_REVIEW requires the exact all-MATCHED repository-agnostic micro-lane set with complete source provenance");for(let row of rows)if(typeof row==="object"&&row!==null&&row.result==="MATCHED"&&typeof row.source_batch_id==="string"&&typeof row.source_lane_id==="string")sources.push({batchId:row.source_batch_id,laneId:row.source_lane_id,mode:"swarm-pr-review:micro",workflowLane:row.trigger_id})}let candidateIds=[],extractedLaneKeys=new Set;for(let source of sources){let resolvedArtifact=!1;for(let record2 of findByBatchId(directory,source.batchId,{parentSessionId:state.sessionID})){if(record2.laneId!==source.laneId||record2.mode!==source.mode||record2.status!=="completed"||record2.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha||record2.result?.outputDegraded===!0||record2.result?.transcriptIncomplete===!0||record2.result?.truncated===!0)continue;let ref=record2.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record2.ownedWorkflowLanes?.length?record2.ownedWorkflowLanes:record2.workflowLane?[record2.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state,record2,source.mode,record2.workflowLane??source.workflowLane??source.laneId,void 0,void 0,recordOwnedLanes))continue;if(source.workflowLane&&(!recordOwnedLanes?.includes(source.workflowLane)||!prReviewDiscoveryArtifactCoversLane(artifact.text,source.workflowLane)))continue;resolvedArtifact=!0;let laneKey=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey))extractedLaneKeys.add(laneKey),candidateIds.push(...extractCandidateIds(artifact.text,source.creditedLanes))}if(source.mode==="swarm-pr-review:micro"&&!resolvedArtifact)throw Error(`BLOCKED: PR_REVIEW mandatory micro-lane provenance is missing or invalid for ${source.workflowLane??source.laneId}`)}return assertNoDuplicates(candidateIds,"PR_REVIEW discovery candidate ids"),candidateIds.length>0?candidateIds.sort():["CLEAN-REVIEW"]}function extractCandidateIds(text,scopeToLanes){let candidateIds=[],markerHeaderSeen=!1,inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);for(let line of text.split(/\r?\n/)){let fields=pipeFields(line);if(fields[0]==="[CANDIDATE]"&&fields[1]?.toLowerCase()==="candidate_id"){markerHeaderSeen=!0;continue}if(fields[0]==="[CANDIDATE]"&&fields.length>=10&&fields.slice(1,10).every(Boolean)){if(inScope(fields[2]))candidateIds.push(fields[1]);continue}if(markerHeaderSeen&&fields.length>=9&&fields[0]&&!fields[0].startsWith("[")&&fields.slice(0,9).every(Boolean)){if(inScope(fields[1]))candidateIds.push(fields[0])}}return candidateIds}function derivePrReviewCriticInventory(directory,state){return[...deriveLatestPrReviewReviewerVerdicts(directory,state).entries()].filter(([,verdict])=>verdict.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(verdict.severity)).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state){let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state),criticBatches=(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="critic");for(let batch of[...criticBatches].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:critic",batch.validatedAt);if(batch.lanes.some((lane)=>!successful.has(lane.workflowLane))||successful.size!==batch.lanes.length)continue;let required2=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]),verdicts=new Map;for(let lane of batch.lanes){let ref=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===lane.laneId)?.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0;if(!artifact)continue;for(let itemId of lane.reviewItemIds??[]){let verdict=parseCriticVerdict(artifact.text,itemId,reviewerVerdicts.get(itemId)?.severity);if(verdict)verdicts.set(itemId,verdict)}}if(required2.every((itemId)=>verdicts.has(itemId)))return verdicts}return new Map}function deriveLatestPrReviewReviewerVerdicts(directory,state){let reviewerBatches=(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer");for(let batch of[...reviewerBatches].reverse()){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:reviewer",batch.validatedAt);if(batch.lanes.some((lane)=>!successful.has(lane.workflowLane))||successful.size!==batch.lanes.length)continue;let required2=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]),verdicts=new Map;for(let lane of batch.lanes){let ref=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===lane.laneId)?.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0;if(!artifact)continue;for(let itemId of lane.reviewItemIds??[]){let verdict=parseReviewerVerdict(artifact.text,itemId);if(verdict)verdicts.set(itemId,verdict)}}if(required2.every((itemId)=>verdicts.has(itemId)))return verdicts}return new Map}function successfulObligationsFromExactBatch(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}),successful=new Set,validatedAtMs=Date.parse(validatedAt);if(!Number.isFinite(validatedAtMs))return successful;let expectedByLaneId=new Map(expectedLanes.map((lane)=>[lane.laneId,lane]));if(expectedByLaneId.size!==expectedLanes.length)return successful;let recordCountByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record2 of records){if(!record2.laneId||!expectedByLaneId.has(record2.laneId))continue;recordCountByLaneId.set(record2.laneId,(recordCountByLaneId.get(record2.laneId)??0)+1);let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)recordCountBySubagentSessionId.set(subagentSessionId,(recordCountBySubagentSessionId.get(subagentSessionId)??0)+1)}for(let record2 of records){let expectedLane=record2.laneId?expectedByLaneId.get(record2.laneId):void 0,expectedWorkflowLane=expectedLane?.workflowLane,expectedOwnedLanes=expectedLane?.ownedWorkflowLanes?.length?expectedLane.ownedWorkflowLanes:expectedWorkflowLane!==void 0?[expectedWorkflowLane]:void 0,subagentSessionId=record2.subagentSessionId?.trim();if(expectedWorkflowLane!==void 0&&expectedOwnedLanes!==void 0&&record2.laneId!==void 0&&recordCountByLaneId.get(record2.laneId)===1&&Boolean(subagentSessionId)&&recordCountBySubagentSessionId.get(subagentSessionId)===1&&!forbiddenSubagentSessionIds.has(subagentSessionId)&&record2.createdAt>=validatedAtMs&&(!checkWorkflowLane||record2.workflowLane===expectedWorkflowLane)&&(!checkWorkflowLane||ownedLaneSetsEqual(record2.ownedWorkflowLanes,expectedOwnedLanes))&&record2.mode===expectedMode&&record2.workspace?.prHeadSha===state.prHeadSha&&record2.workspace?.gitHead===state.prHeadSha&&record2.status==="completed"&&record2.result?.outputDegraded!==!0&&record2.result?.transcriptIncomplete!==!0&&record2.result?.truncated!==!0&&(record2.result?.chars??0)>0&&Boolean(record2.result?.digest?.trim())&&Boolean(record2.result?.outputRef?.trim())&&workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,expectedLane?.reviewItemIds,expectedRevisionDigest,expectedOwnedLanes))for(let obligation of expectedOwnedLanes)successful.add(obligation)}return successful}function ownedLaneSetsEqual(recordOwned,expectedOwned){if(!recordOwned||recordOwned.length===0)return expectedOwned.length===1;let recordSet=new Set(recordOwned),expectedSet=new Set(expectedOwned);if(recordSet.size!==recordOwned.length||recordSet.size!==expectedSet.size)return!1;return recordOwned.every((owned)=>expectedSet.has(owned))}function workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes){let ref=record2.result?.outputRef?.trim();if(!ref)return!1;let loaded=readLaneOutput(directory,ref);if(!loaded)return!1;let artifact=loaded.artifact,recordPrHeadSha=record2.workspace?.prHeadSha,recordGitHead=record2.workspace?.gitHead,resolvedRevisionDigest=expectedRevisionDigest??(recordPrHeadSha?_test_exports.resolvePrWorkflowRevisionDigest(directory,recordPrHeadSha):null),expectedReviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0;if(artifact.batchId!==record2.batchId||artifact.laneId!==record2.laneId||artifact.mode!==expectedMode||artifact.sessionId!==record2.subagentSessionId||artifact.parentSessionId!==record2.parentSessionId||artifact.agent!==record2.swarmPrefixedAgent||artifact.role!==record2.normalizedAgent||artifact.source!=="collect_lane_results"||artifact.workflowLane!==record2.workflowLane||artifact.workflowLane!==expectedWorkflowLane||!recordPrHeadSha||artifact.prHeadSha!==recordPrHeadSha||!recordGitHead||artifact.gitHead!==recordGitHead||!resolvedRevisionDigest||artifact.revisionDigest!==resolvedRevisionDigest||expectedReviewScope!==void 0&&(record2.workspace?.scope!==expectedReviewScope||artifact.scope!==expectedReviewScope)||artifact.digest!==record2.result?.digest||artifact.chars!==record2.result?.chars)return!1;if(expectedMode==="swarm-pr-review:reviewer")return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>Boolean(parseReviewerVerdict(artifact.text,itemId))));if(expectedMode==="swarm-pr-review:critic"){let reviewerVerdicts=deriveLatestPrReviewReviewerVerdicts(directory,state);return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>Boolean(parseCriticVerdict(artifact.text,itemId,reviewerVerdicts.get(itemId)?.severity))))}if(expectedMode==="swarm-pr-feedback:verification")return/^\[FEEDBACK-VERIFIED\]\s*\|/m.test(artifact.text);let feedbackVerdict={"swarm-pr-feedback:stage-b-reviewer":["[STAGE-B-REVIEW]","APPROVE"],"swarm-pr-feedback:stage-b-test":["[STAGE-B-TEST]","PASS"],"swarm-pr-feedback:closeout-reviewer":["[CLOSEOUT-REVIEW]","APPROVE"],"swarm-pr-feedback:closeout-critic":["[CLOSEOUT-CRITIC]","APPROVE"]}[expectedMode];if(feedbackVerdict)return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>artifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));let coveredLanes=ownedWorkflowLanes?.length?ownedWorkflowLanes:[expectedWorkflowLane];if(!coveredLanes.every((coveredLane)=>prReviewDiscoveryArtifactCoversLane(artifact.text,coveredLane)))return!1;if(coveredLanes.length>1){let seenEvidence=new Map;for(let coveredLane of coveredLanes){let evidence=extractLaneCoverageEvidenceText(artifact.text,coveredLane);if(evidence===null)continue;if(seenEvidence.get(evidence))return!1;seenEvidence.set(evidence,coveredLane)}}return!0}function prReviewDiscoveryArtifactCoversLane(text,expectedWorkflowLane){let lines=text.split(/\r?\n/),candidateHeaderSeen=!1;for(let line of lines){let fields=pipeFields(line);if(fields.length===0)continue;if(fields[0]==="[CLEAN]"&&fields.length>=4&&fields[1]===expectedWorkflowLane&&fields.slice(1,4).every(Boolean)&&fields[2].length>=12&&fields[3].length>=20)return!0;if(fields[0]==="[CANDIDATE]"){if(fields[1]?.toLowerCase()==="candidate_id"){candidateHeaderSeen=!0;continue}if(fields.length>=10&&fields[2]===expectedWorkflowLane&&fields.slice(1,10).every(Boolean))return!0;continue}if(candidateHeaderSeen&&fields.length>=9&&fields[0]?.toLowerCase()!=="candidate_id"&&fields[1]===expectedWorkflowLane&&fields.slice(0,9).every(Boolean))return!0}return!1}function extractLaneCoverageEvidenceText(text,expectedWorkflowLane){let lines=text.split(/\r?\n/),candidateHeaderSeen=!1;for(let line of lines){let fields=pipeFields(line);if(fields.length===0)continue;if(fields[0]==="[CLEAN]"&&fields.length>=4&&fields[1]===expectedWorkflowLane&&fields.slice(1,4).every(Boolean)&&fields[2].length>=12&&fields[3].length>=20)return`${fields[2]}\x00${fields[3]}`;if(fields[0]==="[CANDIDATE]"){if(fields[1]?.toLowerCase()==="candidate_id"){candidateHeaderSeen=!0;continue}if(fields.length>=10&&fields[2]===expectedWorkflowLane&&fields.slice(1,10).every(Boolean))return fields.slice(3,10).join("\x00");continue}if(candidateHeaderSeen&&fields.length>=9&&fields[0]?.toLowerCase()!=="candidate_id"&&fields[1]===expectedWorkflowLane&&fields.slice(0,9).every(Boolean))return fields.slice(2,9).join("\x00")}return null}function parseReviewerVerdict(text,itemId){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[REVIEWED]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==10||!fields.slice(1).every(Boolean))return null;let introduced=fields[5].replace(/^introduced_by_pr\s*:\s*/i,"").toUpperCase();if(!REVIEWER_CLASSIFICATIONS.has(fields[2])||!REVIEWER_EVIDENCE_TYPES.has(fields[3])||!REVIEW_SEVERITIES.has(fields[4])||!["YES","NO","UNKNOWN"].includes(introduced))return null;if(fields[7].length<8||fields[8].length<5||fields[9].length<3)return null;return{classification:fields[2],severity:fields[4]}}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[CRITIC]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==6||!fields.slice(1).every(Boolean)||!CRITIC_STATUSES.has(fields[2])||!REVIEW_SEVERITIES.has(fields[3]))return null;if(fields[2]==="NEEDS_MORE_EVIDENCE")return null;if(fields[2]==="DISPROVED"&&fields[3]!=="NONE")return null;if(fields[2]==="UPHELD"&&!["CRITICAL","HIGH","MEDIUM"].includes(fields[3]))return null;if(fields[2]==="DOWNGRADED"&&fields[3]==="CRITICAL")return null;if(reviewerSeverity){let severityRank=new Map([["NONE",0],["INFO",1],["LOW",2],["MEDIUM",3],["HIGH",4],["CRITICAL",5]]),reviewerRank=severityRank.get(reviewerSeverity),criticRank=severityRank.get(fields[3]);if(reviewerRank===void 0||criticRank===void 0)return null;if(fields[2]==="UPHELD"&&criticRank!==reviewerRank)return null;if(fields[2]==="DOWNGRADED"&&criticRank>=reviewerRank)return null}if(fields[4].length<6||fields[5].length<6)return null;return{status:fields[2],severity:fields[3]}}function artifactHasExactPositiveVerdictRow(text,marker,itemId,positiveVerdict){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]===marker&&fields[1]===itemId);return rows.length===1&&rows[0].length>=4&&rows[0][2]===positiveVerdict&&rows[0].slice(1,4).every(Boolean)}function pipeFields(line){if(!line.includes("|"))return[];return line.split("|").map((field)=>field.trim())}function feedbackArtifactCoversItems(directory,state,batchId,laneId,itemIds){let ref=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===laneId)?.result?.outputRef?.trim(),loaded=ref?readLaneOutput(directory,ref):null;if(!loaded)return!1;let rows=loaded.artifact.text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]==="[FEEDBACK-VERIFIED]");if(rows.length!==itemIds.length)return!1;return itemIds.every((itemId)=>{let matches=rows.filter((fields)=>fields[1]===itemId);return matches.length===1&&matches[0].length===4&&matches[0].slice(1,4).every(Boolean)&&FEEDBACK_CLASSIFICATIONS.has(matches[0][2])})}async function persistState(directory,state){let validated=PrWorkflowGateStateSchema.parse(state);await withSessionStateMutation(directory,validated.sessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk(directory,validated.sessionID);if(current?current.revision!==validated.revision:validated.revision!==0)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let nextRevision=validated.revision+1,nextState={...validated,revision:nextRevision},filePath=workflowGateStatePath(directory,validated.sessionID);await fsp2.mkdir(path11.dirname(filePath),{recursive:!0}),await writeAtomicJson2(filePath,nextState),Object.assign(state,nextState),rememberState(directory,nextState)})}async function withSessionStateMutation(directory,sessionID,action){let key=stateCacheKey(directory,sessionID),previous=pendingStateMutationsByProjectSession.get(key)??Promise.resolve(),release,current=new Promise((resolve8)=>{release=resolve8}),queued=previous.then(()=>current);pendingStateMutationsByProjectSession.set(key,queued),await previous;try{let lock=await acquireSessionStateMutationLock(directory,sessionID);try{return await action()}finally{await releaseSessionStateMutationLock(lock)}}finally{if(release(),pendingStateMutationsByProjectSession.get(key)===queued)pendingStateMutationsByProjectSession.delete(key)}}async function acquireSessionStateMutationLock(directory,sessionID){let lockPath=workflowGateStateLockPath(directory,sessionID);await fsp2.mkdir(path11.dirname(lockPath),{recursive:!0});for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await fsp2.open(lockPath,"wx"),lock={ownerToken:randomUUID2(),pid:process.pid,createdAtMs:_test_exports.nowMs()};try{await handle.writeFile(JSON.stringify(lock),"utf-8"),await handle.close()}catch(error49){throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),error49}return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedSessionStateMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow gate state is being mutated by another process; retry after that session transition finishes")}async function releaseSessionStateMutationLock(lock){try{await removeSessionStateMutationLockIfOwned(lock.path,lock.ownerToken)}catch{}}async function reclaimAbandonedSessionStateMutationLock(lockPath){let lock=await readSessionStateMutationLock(lockPath);if(lock){if(_test_exports.isProcessAlive(lock.pid))return!1;return removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp2.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp2.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp2.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeSessionStateMutationLockIfOwned(lockPath,ownerToken){let lock=await readSessionStateMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await fsp2.rm(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error49){return error49.code!=="ESRCH"}}async function readPrWorkflowGateStateFromDisk(directory,sessionID){let filePath=workflowGateStatePath(directory,sessionID),raw;try{raw=await fsp2.readFile(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is invalid`);return parsed.data}function rememberState(directory,state){let cacheKey=stateCacheKey(directory,state.sessionID);trackedStatesByProjectSession.delete(cacheKey),trackedStatesByProjectSession.set(cacheKey,state);while(trackedStatesByProjectSession.size>MAX_TRACKED_SESSIONS){let oldestKey=trackedStatesByProjectSession.keys().next().value;if(!oldestKey)break;trackedStatesByProjectSession.delete(oldestKey)}}function stateCacheKey(directory,sessionID){let resolved=path11.normalize(path11.resolve(directory));return`${process.platform==="win32"?resolved.toLowerCase():resolved}\x00${normalizeSessionID(sessionID)}`}function workflowGateStatePath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateRelativePath(sessionID))}function workflowGateStateLockPath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateLockRelativePath(sessionID))}function workflowGateStateLockRelativePath(sessionID){return path11.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path11.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.json`)}function prWorkflowSessionFileStem(sessionID){let normalized=normalizeSessionID(sessionID),slug=normalized.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)||"session",digest2=createHash5("sha256").update(normalized).digest("hex").slice(0,12);return`${slug}-${digest2}`}function normalizeSessionID(sessionID){let normalized=sessionID.trim();if(!normalized)throw Error("BLOCKED: PR workflow gate requires a non-empty sessionID");return normalized}async function writeAtomicJson2(filePath,value){let tempPath=`${filePath}.tmp.${process.pid}.${randomUUID2()}`,lastError;try{await fsp2.writeFile(tempPath,JSON.stringify(value,null,2),"utf-8");for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await _test_exports.rename(tempPath,filePath),lastError=void 0;break}catch(error49){lastError=error49;let code=error49.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}if(lastError)throw lastError}finally{try{await fsp2.rm(tempPath,{force:!0})}catch{}}}async function writePrWorkflowAtomicJson(filePath,value){await writeAtomicJson2(filePath,value)}function isoNow(){return new Date().toISOString()}function delay(ms){return new Promise((resolve8)=>setTimeout(resolve8,ms))}var PR_REVIEW_BASE_DIMENSION_IDS,PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_MICRO_LANE_FLOORS,GATE_SCHEMA_VERSION=1,MAX_TRACKED_SESSIONS=200,MAX_WORKFLOW_BATCHES=128,WINDOWS_RENAME_MAX_RETRIES3=3,RENAME_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_MAX_ATTEMPTS=50,STATE_MUTATION_LOCK_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS=30000,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",WORKFLOW_GATE_DIR="pr-workflow-gates",trackedStatesByProjectSession,pendingStateMutationsByProjectSession,PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrReviewValidationBatchRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowGateStateSchema,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,_test_exports,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,PR_WORKFLOW_CD_PREFIX_PATTERN,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,PR_WORKFLOW_MAX_CD_PREFIX_STRIPS=3,REVIEWER_CLASSIFICATIONS,REVIEWER_EVIDENCE_TYPES,REVIEW_SEVERITIES,CRITIC_STATUSES,FEEDBACK_CLASSIFICATIONS;var init_pr_workflow_gate=__esm(()=>{init_zod();init_lane_output_store();init_pending_delegations();init_workspace_snapshot();init_constants();init_schema();init_tool_metadata();init_utils2();PR_REVIEW_BASE_DIMENSION_IDS=["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"],PR_REVIEW_REQUIRED_MICRO_LANE_IDS=["auth-identity-secrets","untrusted-input-boundaries","subprocess-platform","concurrency-state","dependencies-build-release","api-schema-migrations","test-infrastructure","ui-accessibility-i18n","privacy-observability","generated-provenance","unclassified-risk"],PR_REVIEW_DEPTH_TIER_THRESHOLDS={smallMaxChangedLines:50,smallMaxChangedFiles:3,mediumMaxChangedLines:500,mediumMaxChangedFiles:20},PR_REVIEW_BASE_LANE_FLOORS={S:1,M:3,L:PR_REVIEW_BASE_DIMENSION_IDS.length},PR_REVIEW_MICRO_LANE_FLOORS={S:1,M:6,L:PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length};trackedStatesByProjectSession=new Map,pendingStateMutationsByProjectSession=new Map,PrReviewBaseDimensionIdSchema=exports_external.enum(["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"]),PrReviewBaseDispatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:PrReviewBaseDimensionIdSchema,ownedWorkflowLanes:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackLaneOwnershipSchema=exports_external.object({laneId:exports_external.string().min(1),ownedItemIds:exports_external.array(exports_external.string().min(1)).min(1)}).strict(),PrFeedbackVerificationRecordSchema=exports_external.object({batchId:exports_external.string().min(1),ownership:exports_external.array(PrFeedbackLaneOwnershipSchema).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackStageACheckReceiptSchema=exports_external.object({category:exports_external.enum(["build","typecheck","lint","diff-check","reproduction"]),workingDirectory:exports_external.string().min(1).optional(),obligationId:exports_external.string().min(1).optional(),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional(),command:exports_external.array(exports_external.string().min(1)).min(1),targets:exports_external.array(exports_external.string().min(1)).min(1).optional(),feedbackTargets:exports_external.array(exports_external.object({feedbackItemId:exports_external.string().min(1),target:exports_external.string().min(1),expectedBehavior:exports_external.string().min(8)}).strict()).min(1).optional(),durationMs:exports_external.number().nonnegative()}).strict(),PrFeedbackStageARecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),checks:exports_external.array(PrFeedbackStageACheckReceiptSchema).min(2).max(258),feedbackItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional(),applicableCategories:exports_external.array(exports_external.enum(["build","typecheck","lint"])).max(3).optional(),applicableObligations:exports_external.array(exports_external.object({id:exports_external.string().min(1),category:exports_external.enum(["build","typecheck","lint"]),workingDirectory:exports_external.string().min(1),source:exports_external.string().min(1),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional()}).strict()).max(256).optional(),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackGateBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),laneId:exports_external.string().min(1),itemIds:exports_external.array(exports_external.string().min(1)).min(1),revisionDigest:exports_external.string().min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackReadyToPublishRecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),validatedAt:exports_external.string().min(1)}).strict(),PrReviewValidationBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["council","reviewer","critic"]),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:exports_external.string().min(1),reviewItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackScopeDeclarationRecordSchema=exports_external.object({taskId:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/),files:exports_external.array(exports_external.string().min(1)).min(1).max(1e4),revisionDigest:exports_external.string().min(1),declaredAt:exports_external.string().min(1),consumedByCallId:exports_external.string().min(1).optional()}).strict(),PrWorkflowGateStateSchema=exports_external.object({schemaVersion:exports_external.literal(GATE_SCHEMA_VERSION),revision:exports_external.number().int().nonnegative().default(0),sessionID:exports_external.string().min(1),mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),activatedAt:exports_external.string().min(1),updatedAt:exports_external.string().min(1),prHeadSha:exports_external.string().min(1).optional(),prReviewBaseRef:exports_external.string().min(1).optional(),prReviewBaseSha:exports_external.string().min(1).optional(),prReviewDepthTier:exports_external.enum(["S","M","L"]).optional(),prReviewDiffStats:exports_external.object({changedLines:exports_external.number().int().nonnegative(),changedFiles:exports_external.number().int().nonnegative(),hasSubmoduleChange:exports_external.boolean().default(!1)}).strict().optional(),prReviewBaseDispatches:exports_external.array(PrReviewBaseDispatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBaseDispatch:PrReviewBaseDispatchRecordSchema.optional(),prReviewTriggerEvalPath:exports_external.string().min(1).optional(),prReviewValidationBatches:exports_external.array(PrReviewValidationBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewArtifactBoundaries:exports_external.array(exports_external.enum(["post_explorer","post_reviewer","post_critic"])).max(3).optional(),prReviewHandoffPath:exports_external.string().min(1).optional(),prReviewHandoffRequired:exports_external.boolean().optional(),prFeedbackInventory:exports_external.array(exports_external.string().min(1)).min(1).optional(),prFeedbackVerifications:exports_external.array(PrFeedbackVerificationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackVerification:PrFeedbackVerificationRecordSchema.optional(),prFeedbackStageA:PrFeedbackStageARecordSchema.optional(),prFeedbackGateBatches:exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackReadyToPublish:PrFeedbackReadyToPublishRecordSchema.optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();PR_FEEDBACK_PHASE_ORDER=["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"];PR_FEEDBACK_PHASE_ROLE={"stage-b-reviewer":"reviewer","stage-b-test":"test_engineer","closeout-reviewer":"reviewer","closeout-critic":"critic"};_test_exports={workflowGateStateRelativePath,workflowGateStateLockRelativePath,resetTrackedStateCache:()=>{trackedStatesByProjectSession.clear(),pendingStateMutationsByProjectSession.clear(),_test_exports.beforeTerminalClear=void 0},beforeTerminalClear:void 0,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,isProcessAlive,rename:fsp2.rename,nowMs:()=>Date.now()};PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","get_async_result","get_async_status","prepare_pr_workflow_checkout"]),PR_REVIEW_CONTROLLER_TOOLS=new Set(["parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["prepare_pr_feedback_scope","run_pr_feedback_stage_a"]);PR_REVIEW_READ_ONLY_TOOL_NAMES=new Set(["ast_grep_search","codesearch","glob","grep","list","lsp","open","read","search","skill","tree","view","web_fetch","web_search","webfetch","websearch"]);PR_WORKFLOW_CD_PREFIX_PATTERN=/^cd\s+(?:\/d\s+)?(?:"[A-Za-z0-9 _.\\/:~+-]+"|'[A-Za-z0-9 _.\\/:~+-]+'|[A-Za-z0-9_.\\/:~+-]+)\s*&&\s*/i,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN=/\s+2>&1\s*$/;REVIEWER_CLASSIFICATIONS=new Set(["CONFIRMED","DISPROVED","UNVERIFIED","PRE_EXISTING"]),REVIEWER_EVIDENCE_TYPES=new Set(["STRUCTURALLY_PROVEN","EXECUTION_PROVEN","STATIC_TRACE_PROVEN","PLAUSIBLE_BUT_UNVERIFIED"]),REVIEW_SEVERITIES=new Set(["CRITICAL","HIGH","MEDIUM","LOW","INFO","NONE"]),CRITIC_STATUSES=new Set(["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE"]),FEEDBACK_CLASSIFICATIONS=new Set(["CONFIRMED","PARTIAL","DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"])});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,reasonStartIndex=knownMode?1:0,reason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500)||void 0;if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
|
|
175
175
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "opencode-swarm",
|
|
3
|
-
"version": "7.130.
|
|
3
|
+
"version": "7.130.2",
|
|
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",
|