opencode-agent-orchestration-kit 1.0.31 → 1.0.33

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (78) hide show
  1. package/README.md +41 -3
  2. package/SECURITY.md +7 -0
  3. package/docker/open-design/data/app.sqlite +0 -0
  4. package/docker/open-design/data/app.sqlite-shm +0 -0
  5. package/docker/open-design/data/app.sqlite-wal +0 -0
  6. package/docker/open-design/opencode-auth/log/2026-05-02T105802.log +17 -0
  7. package/docker/open-design/opencode-auth/log/2026-05-04T102127.log +16 -0
  8. package/docker/open-design/opencode-auth/opencode.db +0 -0
  9. package/docker/open-design/opencode-auth/opencode.db-shm +0 -0
  10. package/docker/open-design/opencode-auth/opencode.db-wal +0 -0
  11. package/docs/cli.md +72 -0
  12. package/docs/installation.md +25 -5
  13. package/docs/quickstart.md +1 -1
  14. package/docs/releases/v1.0.32.md +68 -0
  15. package/docs/releases/v1.0.33.md +72 -0
  16. package/docs/security.md +4 -0
  17. package/docs/supply-chain.md +9 -5
  18. package/docs/threat-model.md +244 -0
  19. package/docs/use-cases/README.md +31 -0
  20. package/docs/use-cases/direct-label-change/README.md +76 -0
  21. package/docs/use-cases/direct-label-change/before/package.json +8 -0
  22. package/docs/use-cases/direct-label-change/before/src/settings-label.mjs +1 -0
  23. package/docs/use-cases/direct-label-change/before/test/settings-label.test.mjs +8 -0
  24. package/docs/use-cases/direct-label-change/case.json +118 -0
  25. package/docs/use-cases/direct-label-change/expected/package.json +8 -0
  26. package/docs/use-cases/direct-label-change/expected/src/settings-label.mjs +1 -0
  27. package/docs/use-cases/direct-label-change/expected/test/settings-label.test.mjs +8 -0
  28. package/docs/use-cases/feature-tag-normalizer/README.md +78 -0
  29. package/docs/use-cases/feature-tag-normalizer/before/package.json +8 -0
  30. package/docs/use-cases/feature-tag-normalizer/before/src/normalize-tags.mjs +3 -0
  31. package/docs/use-cases/feature-tag-normalizer/before/test/normalize-tags.test.mjs +13 -0
  32. package/docs/use-cases/feature-tag-normalizer/case.json +119 -0
  33. package/docs/use-cases/feature-tag-normalizer/expected/package.json +8 -0
  34. package/docs/use-cases/feature-tag-normalizer/expected/src/normalize-tags.mjs +14 -0
  35. package/docs/use-cases/feature-tag-normalizer/expected/test/normalize-tags.test.mjs +18 -0
  36. package/docs/workflows.md +6 -0
  37. package/opencode/AGENTS.md +6 -0
  38. package/opencode/agents/review_api.md +3 -1
  39. package/opencode/agents/review_coordinator.md +3 -1
  40. package/opencode/agents/review_quality.md +3 -1
  41. package/opencode/agents/review_security.md +3 -1
  42. package/opencode/agents/review_tests.md +3 -1
  43. package/opencode/agents/reviewer.md +2 -2
  44. package/opencode/commands/loop.md +53 -14
  45. package/opencode/docs/ai/evolution/README.md +28 -0
  46. package/opencode/docs/ai/evolution/benchmarks/adversarial-scenarios.jsonl +11 -0
  47. package/opencode/docs/ai/harness/README.md +2 -0
  48. package/opencode/docs/ai/harness/agents.md +30 -4
  49. package/opencode/docs/ai/harness/checks.md +27 -0
  50. package/opencode/docs/ai/harness/commands.md +21 -4
  51. package/opencode/docs/ai/harness/orchestrated-review.md +4 -0
  52. package/opencode/docs/ai/harness/orchestration-contracts.json +891 -0
  53. package/opencode/package-lock.json +14 -8
  54. package/opencode/package.json +1 -0
  55. package/opencode/scripts/adversarial-harness.test.mjs +296 -0
  56. package/opencode/scripts/check-harness.mjs +826 -11
  57. package/opencode/scripts/check-harness.test.mjs +572 -1
  58. package/opencode/scripts/loop-state.mjs +1149 -0
  59. package/opencode/scripts/loop-state.test.mjs +577 -0
  60. package/opencode/scripts/review-orchestrated-prepare.mjs +33 -9
  61. package/package.json +4 -1
  62. package/scripts/check-supply-chain.mjs +11 -1
  63. package/scripts/check-supply-chain.test.mjs +47 -0
  64. package/scripts/check-threat-model.mjs +421 -0
  65. package/scripts/check-threat-model.test.mjs +304 -0
  66. package/scripts/check-use-cases.mjs +501 -0
  67. package/scripts/check-use-cases.test.mjs +225 -0
  68. package/scripts/check.sh +51 -1
  69. package/scripts/install-smoke.sh +24 -1
  70. package/scripts/manage-installation.mjs +567 -25
  71. package/scripts/manage-installation.test.mjs +418 -0
  72. package/scripts/oak.mjs +200 -0
  73. package/scripts/oak.test.mjs +277 -0
  74. package/scripts/package-smoke.mjs +57 -0
  75. package/scripts/package-smoke.test.mjs +75 -2
  76. package/scripts/version.mjs +1 -0
  77. package/scripts/version.test.mjs +3 -2
  78. package/supply-chain.json +1 -0
@@ -5,6 +5,7 @@ import { execSync } from "node:child_process";
5
5
 
6
6
  const root = process.cwd();
7
7
  const errors = [];
8
+ let orchestrationCatalog = null;
8
9
 
9
10
  function read(rel) {
10
11
  return fs.readFileSync(path.join(root, rel), "utf8");
@@ -79,6 +80,621 @@ function parseJson(rel) {
79
80
  }
80
81
  }
81
82
 
83
+ const orchestrationContractRel =
84
+ "docs/ai/harness/orchestration-contracts.json";
85
+
86
+ function readOrchestrationContract() {
87
+ if (!exists(orchestrationContractRel)) {
88
+ fail(`${orchestrationContractRel}: missing orchestration contract`);
89
+ return null;
90
+ }
91
+ const stat = fs.lstatSync(path.join(root, orchestrationContractRel));
92
+ if (stat.isSymbolicLink() || !stat.isFile()) {
93
+ fail(`${orchestrationContractRel}: must be a regular non-symlink file`);
94
+ return null;
95
+ }
96
+ return parseJson(orchestrationContractRel);
97
+ }
98
+
99
+ function checkOrchestrationContracts() {
100
+ const contract = readOrchestrationContract();
101
+ if (!contract) return;
102
+ checkExactKeys("contract", contract, [
103
+ "schema_version",
104
+ "contract_id",
105
+ "evidence_types",
106
+ "agents",
107
+ "commands",
108
+ "routing_rules",
109
+ "retry_policies",
110
+ "workflows",
111
+ "profiles",
112
+ ]);
113
+ if (contract.schema_version !== 1) {
114
+ fail(`${orchestrationContractRel}: schema_version must be 1`);
115
+ }
116
+ if (contract.contract_id !== "oak-orchestration") {
117
+ fail(`${orchestrationContractRel}: contract_id must be oak-orchestration`);
118
+ }
119
+ const canonicalEvidence = [
120
+ "live_smoke",
121
+ "manual_oracle",
122
+ "static_contract",
123
+ "transcript_replay",
124
+ ];
125
+ if (JSON.stringify(contract.evidence_types) !== JSON.stringify(canonicalEvidence)) {
126
+ fail(
127
+ `${orchestrationContractRel}: evidence_types must match the canonical catalog`,
128
+ );
129
+ }
130
+ const expectedAgentIds = listMarkdown("agents")
131
+ .map(stripMarkdownExtension)
132
+ .sort();
133
+ const declaredAgentIds = Array.isArray(contract.agents)
134
+ ? contract.agents.map((agent) => agent?.id).sort()
135
+ : [];
136
+ if (JSON.stringify(declaredAgentIds) !== JSON.stringify(expectedAgentIds)) {
137
+ fail(`${orchestrationContractRel}: agent catalog must match harness agents`);
138
+ }
139
+ const actualAgentDelegations = new Map();
140
+ if (Array.isArray(contract.agents)) {
141
+ for (const agent of contract.agents) {
142
+ const label = `agent ${agent?.id ?? "<unknown>"}`;
143
+ if (!checkExactKeys(label, agent, [
144
+ "id",
145
+ "mode",
146
+ "permission_invariants",
147
+ "delegates_to",
148
+ ])) {
149
+ continue;
150
+ }
151
+ if (!/^[a-z][a-z0-9_]*$/.test(agent.id)) {
152
+ fail(`${orchestrationContractRel}: ${label} id must be canonical`);
153
+ continue;
154
+ }
155
+ if (!["primary", "subagent", "all"].includes(agent.mode)) {
156
+ fail(`${orchestrationContractRel}: ${label} mode is invalid`);
157
+ }
158
+ if (!checkExactKeys(`${label} permission_invariants`, agent.permission_invariants, [
159
+ "repository_write",
160
+ "task_default",
161
+ ])) {
162
+ continue;
163
+ }
164
+ for (const key of ["repository_write", "task_default"]) {
165
+ if (!["allow", "ask", "deny", "unspecified"].includes(agent.permission_invariants[key])) {
166
+ fail(`${orchestrationContractRel}: ${label} ${key} is invalid`);
167
+ }
168
+ }
169
+ checkSortedUniqueStrings(`${label} delegates_to`, agent.delegates_to);
170
+
171
+ const rel = `agents/${agent.id}.md`;
172
+ if (!exists(rel)) continue;
173
+ const frontmatter = parseFrontmatter(rel);
174
+ const permissions = parsePortableAgentPermissions(rel);
175
+ if (agent.mode !== frontmatter.mode) {
176
+ fail(`${orchestrationContractRel}: ${label} mode must match frontmatter`);
177
+ }
178
+ if (agent.permission_invariants.repository_write !== permissions.repositoryWrite) {
179
+ fail(`${orchestrationContractRel}: ${label} repository_write must match frontmatter`);
180
+ }
181
+ if (agent.permission_invariants.task_default !== permissions.taskDefault) {
182
+ fail(`${orchestrationContractRel}: ${label} task_default must match frontmatter`);
183
+ }
184
+ actualAgentDelegations.set(agent.id, permissions.taskAllows);
185
+ }
186
+ }
187
+
188
+ const declaredCommandIds = Array.isArray(contract.commands)
189
+ ? contract.commands.map((command) => command?.id)
190
+ : [];
191
+ checkSortedUniqueStrings("command ids", declaredCommandIds);
192
+ if (Array.isArray(contract.commands)) {
193
+ for (const command of contract.commands) {
194
+ const label = `command ${command?.id ?? "<unknown>"}`;
195
+ if (!checkExactKeys(label, command, [
196
+ "id",
197
+ "root_agent",
198
+ "subtask",
199
+ "workflow",
200
+ ])) {
201
+ continue;
202
+ }
203
+ if (!/^[a-z][a-z0-9-]*$/.test(command.id)) {
204
+ fail(`${orchestrationContractRel}: ${label} id must be canonical`);
205
+ continue;
206
+ }
207
+ if (!expectedAgentIds.includes(command.root_agent)) {
208
+ fail(`${orchestrationContractRel}: ${label} root_agent must reference an agent`);
209
+ }
210
+ if (typeof command.subtask !== "boolean") {
211
+ fail(`${orchestrationContractRel}: ${label} subtask must be boolean`);
212
+ }
213
+ if (!/^[a-z][a-z0-9-]*$/.test(command.workflow)) {
214
+ fail(`${orchestrationContractRel}: ${label} workflow must be canonical`);
215
+ }
216
+
217
+ const rel = `commands/${command.id}.md`;
218
+ if (!exists(rel)) continue;
219
+ const frontmatter = parseFrontmatter(rel);
220
+ const actualSubtask = frontmatter.subtask === "true";
221
+ if (command.root_agent !== frontmatter.agent) {
222
+ fail(`${orchestrationContractRel}: ${label} root_agent must match frontmatter`);
223
+ }
224
+ if (command.subtask !== actualSubtask) {
225
+ fail(`${orchestrationContractRel}: ${label} subtask must match frontmatter`);
226
+ }
227
+ }
228
+ }
229
+
230
+ const workflowIds = Array.isArray(contract.workflows)
231
+ ? contract.workflows.map((workflow) => workflow?.id)
232
+ : [];
233
+ checkSortedUniqueStrings("workflow ids", workflowIds);
234
+ const canonicalWorkflowIds = [
235
+ "design",
236
+ "direct-development",
237
+ "direct-research",
238
+ "direct-review",
239
+ "direct-spec",
240
+ "evolve",
241
+ "feature",
242
+ "freeform",
243
+ "init",
244
+ "loop",
245
+ "plan",
246
+ "review-orchestrated",
247
+ "review-preflight",
248
+ "scope",
249
+ ];
250
+ if (JSON.stringify(workflowIds) !== JSON.stringify(canonicalWorkflowIds)) {
251
+ fail(`${orchestrationContractRel}: workflow catalog must match the approved catalog`);
252
+ }
253
+ const workflowIdSet = new Set(workflowIds);
254
+ const retryIds = Array.isArray(contract.retry_policies)
255
+ ? contract.retry_policies.map((policy) => policy?.id)
256
+ : [];
257
+ checkSortedUniqueStrings("retry ids", retryIds);
258
+ const retryIdSet = new Set(retryIds);
259
+
260
+ const retryScopes = new Set();
261
+ if (Array.isArray(contract.retry_policies)) {
262
+ const approvedRetries = {
263
+ "developer-default": ["developer", 2, true, "escalate-review"],
264
+ "loop-iterations": ["loop", 3, true, "ask-user"],
265
+ "reviewer-default": ["reviewer", 2, true, "block"],
266
+ };
267
+ for (const policy of contract.retry_policies) {
268
+ const label = `retry ${policy?.id ?? "<unknown>"}`;
269
+ if (!checkExactKeys(label, policy, [
270
+ "id",
271
+ "scope",
272
+ "max_attempts",
273
+ "requires_new_evidence",
274
+ "on_exhaustion",
275
+ ])) {
276
+ continue;
277
+ }
278
+ if (!/^[a-z][a-z0-9-]*$/.test(policy.id)) {
279
+ fail(`${orchestrationContractRel}: ${label} id must be canonical`);
280
+ }
281
+ if (!expectedAgentIds.includes(policy.scope) && !workflowIdSet.has(policy.scope)) {
282
+ fail(`${orchestrationContractRel}: ${label} scope must reference an agent or workflow`);
283
+ }
284
+ if (retryScopes.has(policy.scope)) {
285
+ fail(`${orchestrationContractRel}: retry scope ${policy.scope} must be unique`);
286
+ }
287
+ retryScopes.add(policy.scope);
288
+ if (!Number.isInteger(policy.max_attempts) || policy.max_attempts < 1 || policy.max_attempts > 3) {
289
+ fail(`${orchestrationContractRel}: ${label} max_attempts must be between 1 and 3`);
290
+ }
291
+ if (typeof policy.requires_new_evidence !== "boolean") {
292
+ fail(`${orchestrationContractRel}: ${label} requires_new_evidence must be boolean`);
293
+ }
294
+ if (!["ask-user", "block", "escalate-review"].includes(policy.on_exhaustion)) {
295
+ fail(`${orchestrationContractRel}: ${label} on_exhaustion is invalid`);
296
+ }
297
+ const observed = [
298
+ policy.scope,
299
+ policy.max_attempts,
300
+ policy.requires_new_evidence,
301
+ policy.on_exhaustion,
302
+ ];
303
+ if (JSON.stringify(observed) !== JSON.stringify(approvedRetries[policy.id])) {
304
+ fail(`${orchestrationContractRel}: ${label} must match the approved policy`);
305
+ }
306
+ }
307
+ }
308
+
309
+ const usedEntrypoints = new Set();
310
+ const entrypointWorkflows = new Map();
311
+ const approvedStageSequences = {
312
+ design: ["designer:required"],
313
+ "direct-development": ["developer:required"],
314
+ "direct-research": ["researcher:required"],
315
+ "direct-review": ["reviewer:required"],
316
+ "direct-spec": ["specifier:required"],
317
+ evolve: [
318
+ "lead:required",
319
+ "evaluator:required",
320
+ "debugger:required",
321
+ "evolver:required",
322
+ "developer:conditional",
323
+ "evaluator:required",
324
+ "debugger:required",
325
+ "reviewer:required",
326
+ ],
327
+ feature: [
328
+ "lead:required",
329
+ "designer:conditional",
330
+ "researcher:conditional",
331
+ "specifier:required",
332
+ "developer:required",
333
+ "reviewer:required",
334
+ ],
335
+ freeform: [
336
+ "lead:required",
337
+ "designer:conditional",
338
+ "researcher:conditional",
339
+ "specifier:conditional",
340
+ "developer:conditional",
341
+ "reviewer:conditional",
342
+ ],
343
+ init: ["lead:required"],
344
+ loop: [
345
+ "lead:required",
346
+ "developer:required",
347
+ "reviewer:required",
348
+ "developer:state-sync",
349
+ ],
350
+ plan: [
351
+ "lead:required",
352
+ "researcher:required",
353
+ "specifier:required",
354
+ "reviewer:required",
355
+ ],
356
+ "review-orchestrated": [
357
+ "review_coordinator:required",
358
+ "review_api:conditional",
359
+ "review_quality:conditional",
360
+ "review_security:conditional",
361
+ "review_tests:conditional",
362
+ "review_coordinator:state-sync",
363
+ ],
364
+ "review-preflight": ["lead:required"],
365
+ scope: ["scoper:required", "researcher:required", "specifier:required"],
366
+ };
367
+ const approvedCompletionAuthorities = {
368
+ design: ["agent", "designer"],
369
+ "direct-development": ["result-contract", null],
370
+ "direct-research": ["agent", "researcher"],
371
+ "direct-review": ["agent", "reviewer"],
372
+ "direct-spec": ["agent", "specifier"],
373
+ evolve: ["agent", "reviewer"],
374
+ feature: ["agent", "lead"],
375
+ freeform: ["agent", "lead"],
376
+ init: ["agent", "lead"],
377
+ loop: ["agent", "reviewer"],
378
+ plan: ["agent", "reviewer"],
379
+ "review-orchestrated": ["agent", "review_coordinator"],
380
+ "review-preflight": ["result-contract", null],
381
+ scope: ["result-contract", null],
382
+ };
383
+ const barrierConditions = new Set([
384
+ "acceptance-criteria-ready",
385
+ "approval-explicit",
386
+ "diff-reviewable",
387
+ "research-ready",
388
+ "review-approved",
389
+ "visual-criteria-ready",
390
+ ]);
391
+ if (Array.isArray(contract.workflows)) {
392
+ for (const workflow of contract.workflows) {
393
+ const label = `workflow ${workflow?.id ?? "<unknown>"}`;
394
+ if (!checkExactKeys(label, workflow, [
395
+ "id",
396
+ "entrypoints",
397
+ "stages",
398
+ "barriers",
399
+ "retry_policy",
400
+ "completion_authority",
401
+ "required_evidence",
402
+ "adaptive",
403
+ ])) {
404
+ continue;
405
+ }
406
+ checkSortedUniqueStrings(`${label} entrypoints`, workflow.entrypoints, { nonEmpty: true });
407
+ for (const entrypoint of Array.isArray(workflow.entrypoints) ? workflow.entrypoints : []) {
408
+ if (entrypoint !== "freeform" && !declaredCommandIds.includes(entrypoint)) {
409
+ fail(`${orchestrationContractRel}: ${label} entrypoint must reference a command`);
410
+ }
411
+ if (usedEntrypoints.has(entrypoint)) {
412
+ fail(`${orchestrationContractRel}: entrypoint ${entrypoint} must be unique`);
413
+ }
414
+ usedEntrypoints.add(entrypoint);
415
+ entrypointWorkflows.set(entrypoint, workflow.id);
416
+ }
417
+ if (!Array.isArray(workflow.stages) || workflow.stages.length === 0) {
418
+ fail(`${orchestrationContractRel}: ${label} stages must be non-empty`);
419
+ } else {
420
+ const seenAgents = new Set();
421
+ for (const [index, stage] of workflow.stages.entries()) {
422
+ const stageLabel = `${label} stage ${index}`;
423
+ if (!checkExactKeys(stageLabel, stage, ["agent", "requirement"])) continue;
424
+ if (!expectedAgentIds.includes(stage.agent)) {
425
+ fail(`${orchestrationContractRel}: ${label} stage agent must reference an agent`);
426
+ }
427
+ if (!["required", "conditional", "state-sync"].includes(stage.requirement)) {
428
+ fail(`${orchestrationContractRel}: ${stageLabel} requirement is invalid`);
429
+ }
430
+ const evolvePostChange =
431
+ workflow.id === "evolve"
432
+ && ["evaluator", "debugger"].includes(stage.agent)
433
+ && index >= 5;
434
+ if (seenAgents.has(stage.agent) && stage.requirement !== "state-sync" && !evolvePostChange) {
435
+ fail(`${orchestrationContractRel}: ${label} repeats ${stage.agent} without a recognized role`);
436
+ }
437
+ seenAgents.add(stage.agent);
438
+ }
439
+ const observedSequence = workflow.stages.map(
440
+ (stage) => `${stage.agent}:${stage.requirement}`,
441
+ );
442
+ if (JSON.stringify(observedSequence) !== JSON.stringify(approvedStageSequences[workflow.id])) {
443
+ fail(`${orchestrationContractRel}: ${label} stages must match the approved sequence`);
444
+ }
445
+ }
446
+ if (!Array.isArray(workflow.barriers)) {
447
+ fail(`${orchestrationContractRel}: ${label} barriers must be an array`);
448
+ } else {
449
+ checkSortedUniqueStrings(
450
+ `${label} barrier ids`,
451
+ workflow.barriers.map((barrier) => barrier?.id),
452
+ );
453
+ for (const barrier of workflow.barriers) {
454
+ const barrierLabel = `${label} barrier ${barrier?.id ?? "<unknown>"}`;
455
+ if (!checkExactKeys(barrierLabel, barrier, [
456
+ "id",
457
+ "before_stage",
458
+ "authority",
459
+ "condition",
460
+ ])) {
461
+ continue;
462
+ }
463
+ if (!Number.isInteger(barrier.before_stage)
464
+ || barrier.before_stage < 0
465
+ || barrier.before_stage >= workflow.stages.length) {
466
+ fail(`${orchestrationContractRel}: ${barrierLabel} before_stage is invalid`);
467
+ }
468
+ if (!["human", "none", ...expectedAgentIds].includes(barrier.authority)) {
469
+ fail(`${orchestrationContractRel}: ${barrierLabel} authority is invalid`);
470
+ }
471
+ if (!barrierConditions.has(barrier.condition)) {
472
+ fail(`${orchestrationContractRel}: ${barrierLabel} condition is invalid`);
473
+ }
474
+ if (barrier.condition === "approval-explicit" && barrier.authority !== "human") {
475
+ fail(`${orchestrationContractRel}: ${barrierLabel} approval-explicit requires human authority`);
476
+ }
477
+ }
478
+ }
479
+ if (workflow.retry_policy !== null && !retryIdSet.has(workflow.retry_policy)) {
480
+ fail(`${orchestrationContractRel}: ${label} retry_policy must reference a retry`);
481
+ }
482
+ if (checkExactKeys(`${label} completion_authority`, workflow.completion_authority, [
483
+ "kind",
484
+ "agent",
485
+ ])) {
486
+ const completion = workflow.completion_authority;
487
+ if (!["agent", "human", "result-contract"].includes(completion.kind)) {
488
+ fail(`${orchestrationContractRel}: ${label} completion kind is invalid`);
489
+ } else if (completion.kind === "agent" && !expectedAgentIds.includes(completion.agent)) {
490
+ fail(`${orchestrationContractRel}: ${label} completion agent must reference an agent`);
491
+ } else if (completion.kind !== "agent" && completion.agent !== null) {
492
+ fail(`${orchestrationContractRel}: ${label} completion agent must be null`);
493
+ }
494
+ if (JSON.stringify([completion.kind, completion.agent])
495
+ !== JSON.stringify(approvedCompletionAuthorities[workflow.id])) {
496
+ fail(`${orchestrationContractRel}: ${label} completion authority must match the approved authority`);
497
+ }
498
+ }
499
+ if (checkSortedUniqueStrings(
500
+ `${label} required_evidence`,
501
+ workflow.required_evidence,
502
+ { nonEmpty: true },
503
+ )) {
504
+ for (const evidence of workflow.required_evidence) {
505
+ if (!canonicalEvidence.includes(evidence)) {
506
+ fail(`${orchestrationContractRel}: ${label} required_evidence is invalid`);
507
+ }
508
+ }
509
+ }
510
+ if (typeof workflow.adaptive !== "boolean") {
511
+ fail(`${orchestrationContractRel}: ${label} adaptive must be boolean`);
512
+ } else if (workflow.adaptive !== (workflow.id === "freeform")) {
513
+ fail(`${orchestrationContractRel}: ${label} adaptive must match the approved policy`);
514
+ }
515
+ }
516
+ }
517
+ for (const command of Array.isArray(contract.commands) ? contract.commands : []) {
518
+ if (entrypointWorkflows.get(command.id) !== command.workflow) {
519
+ fail(`${orchestrationContractRel}: command ${command.id} workflow must match its entrypoint`);
520
+ }
521
+ }
522
+
523
+ const routingPrecedence = new Set();
524
+ let hasAskUserFallback = false;
525
+ if (Array.isArray(contract.routing_rules)) {
526
+ const approvedRouting = {
527
+ "technical-uncertainty": ["researcher", 1],
528
+ "reviewable-change": ["reviewer", 2],
529
+ "visual-impact": ["designer", 3],
530
+ "specification-gap": ["specifier", 4],
531
+ "small-clear-change": ["developer", 5],
532
+ "routing-ambiguity": ["ask-user", 6],
533
+ };
534
+ if (JSON.stringify(contract.routing_rules.map((rule) => rule?.id))
535
+ !== JSON.stringify(Object.keys(approvedRouting))) {
536
+ fail(`${orchestrationContractRel}: routing rule catalog must match the approved catalog`);
537
+ }
538
+ for (const rule of contract.routing_rules) {
539
+ const label = `routing rule ${rule?.id ?? "<unknown>"}`;
540
+ if (!checkExactKeys(label, rule, ["id", "target", "precedence"])) continue;
541
+ if (!expectedAgentIds.includes(rule.target) && rule.target !== "ask-user") {
542
+ fail(`${orchestrationContractRel}: ${label} target must reference an agent or ask-user`);
543
+ }
544
+ if (!Number.isInteger(rule.precedence) || rule.precedence < 1) {
545
+ fail(`${orchestrationContractRel}: ${label} precedence must be a positive integer`);
546
+ }
547
+ if (routingPrecedence.has(rule.precedence)) {
548
+ fail(`${orchestrationContractRel}: routing precedence ${rule.precedence} must be unique`);
549
+ }
550
+ routingPrecedence.add(rule.precedence);
551
+ if (rule.target === "ask-user") hasAskUserFallback = true;
552
+ if (JSON.stringify([rule.target, rule.precedence]) !== JSON.stringify(approvedRouting[rule.id])) {
553
+ fail(`${orchestrationContractRel}: ${label} must match the approved rule`);
554
+ }
555
+ }
556
+ }
557
+ if (Array.isArray(contract.routing_rules) && contract.routing_rules.length > 0 && !hasAskUserFallback) {
558
+ fail(`${orchestrationContractRel}: routing rules must include ask-user fallback`);
559
+ }
560
+
561
+ checkExactKeys("profiles", contract.profiles, ["private", "public"]);
562
+ const actualCommandIds = listMarkdown("commands")
563
+ .map(stripMarkdownExtension)
564
+ .sort();
565
+ let matchingProfiles = 0;
566
+ let selectedProfile = null;
567
+ for (const [profileId, profile] of Object.entries(
568
+ isPlainObject(contract.profiles) ? contract.profiles : {},
569
+ )) {
570
+ const label = `profile ${profileId}`;
571
+ if (!checkExactKeys(label, profile, [
572
+ "agent_ids",
573
+ "command_ids",
574
+ "delegation_extensions",
575
+ ])) {
576
+ continue;
577
+ }
578
+ checkSortedUniqueStrings(`${label} agent_ids`, profile.agent_ids);
579
+ checkSortedUniqueStrings(`${label} command_ids`, profile.command_ids);
580
+ if (!isPlainObject(profile.delegation_extensions)) {
581
+ fail(`${orchestrationContractRel}: ${label} delegation_extensions must be an object`);
582
+ } else {
583
+ for (const [agentId, delegates] of Object.entries(profile.delegation_extensions)) {
584
+ if (!expectedAgentIds.includes(agentId)) {
585
+ fail(`${orchestrationContractRel}: ${label} delegation extension agent is unknown`);
586
+ }
587
+ checkSortedUniqueStrings(`${label} ${agentId} delegation_extensions`, delegates, {
588
+ nonEmpty: true,
589
+ });
590
+ for (const delegate of Array.isArray(delegates) ? delegates : []) {
591
+ if (!expectedAgentIds.includes(delegate)) {
592
+ fail(`${orchestrationContractRel}: ${label} delegation extension target is unknown`);
593
+ }
594
+ }
595
+ }
596
+ }
597
+ if (
598
+ JSON.stringify(profile.agent_ids) === JSON.stringify(expectedAgentIds)
599
+ && JSON.stringify(profile.command_ids) === JSON.stringify(actualCommandIds)
600
+ ) {
601
+ matchingProfiles += 1;
602
+ selectedProfile = profile;
603
+ }
604
+ }
605
+ const profiledCommandIds = [
606
+ ...new Set(
607
+ Object.values(isPlainObject(contract.profiles) ? contract.profiles : {})
608
+ .flatMap((profile) => Array.isArray(profile?.command_ids) ? profile.command_ids : []),
609
+ ),
610
+ ].sort();
611
+ if (JSON.stringify(declaredCommandIds) !== JSON.stringify(profiledCommandIds)) {
612
+ fail(`${orchestrationContractRel}: command catalog must match inventory profiles`);
613
+ }
614
+ if (matchingProfiles !== 1) {
615
+ fail(`${orchestrationContractRel}: must select exactly one inventory profile`);
616
+ } else {
617
+ const agentsById = new Map(contract.agents.map((agent) => [agent.id, agent]));
618
+ for (const agentId of expectedAgentIds) {
619
+ const base = agentsById.get(agentId)?.delegates_to ?? [];
620
+ const extension = selectedProfile.delegation_extensions[agentId] ?? [];
621
+ const effective = [...new Set([...base, ...extension])].sort();
622
+ if (JSON.stringify(effective) !== JSON.stringify(actualAgentDelegations.get(agentId))) {
623
+ fail(`${orchestrationContractRel}: agent ${agentId} delegates_to must match selected profile`);
624
+ }
625
+ }
626
+ orchestrationCatalog = {
627
+ agentIds: new Set(expectedAgentIds),
628
+ commandIds: new Set(selectedProfile.command_ids),
629
+ evidenceTypes: new Set(canonicalEvidence),
630
+ routingTargets: contract.routing_rules.map((rule) => rule.target),
631
+ };
632
+ }
633
+ }
634
+
635
+ function isPlainObject(value) {
636
+ return value !== null && typeof value === "object" && !Array.isArray(value);
637
+ }
638
+
639
+ function checkExactKeys(label, value, expected) {
640
+ if (!isPlainObject(value)) {
641
+ fail(`${orchestrationContractRel}: ${label} must be an object`);
642
+ return false;
643
+ }
644
+ const actual = Object.keys(value).sort();
645
+ const wanted = [...expected].sort();
646
+ if (JSON.stringify(actual) !== JSON.stringify(wanted)) {
647
+ fail(
648
+ `${orchestrationContractRel}: ${label} must contain exactly ${wanted.join(", ")}`,
649
+ );
650
+ return false;
651
+ }
652
+ return true;
653
+ }
654
+
655
+ function checkSortedUniqueStrings(label, value, { nonEmpty = false } = {}) {
656
+ if (
657
+ !Array.isArray(value)
658
+ || (nonEmpty && value.length === 0)
659
+ || value.some((item) => typeof item !== "string" || item.trim() !== item)
660
+ || new Set(value).size !== value.length
661
+ || JSON.stringify(value) !== JSON.stringify([...value].sort())
662
+ ) {
663
+ fail(`${orchestrationContractRel}: ${label} must be a sorted unique string array`);
664
+ return false;
665
+ }
666
+ return true;
667
+ }
668
+
669
+ function parsePortableAgentPermissions(rel) {
670
+ let repositoryWrite = "unspecified";
671
+ let taskDefault = "unspecified";
672
+ const taskAllows = [];
673
+ let section = "";
674
+
675
+ for (const line of frontmatterBlock(rel).split("\n")) {
676
+ const sectionMatch = line.match(/^ ([A-Za-z_][A-Za-z0-9_-]*):(?:\s*(\S+))?$/);
677
+ if (sectionMatch) {
678
+ section = sectionMatch[1];
679
+ if (section === "edit" && sectionMatch[2]) {
680
+ repositoryWrite = sectionMatch[2];
681
+ }
682
+ continue;
683
+ }
684
+ if (section !== "task") continue;
685
+ const taskMatch = line.match(/^ "?([A-Za-z_*][A-Za-z0-9_*-]*)"?:\s*(allow|ask|deny)$/);
686
+ if (!taskMatch) continue;
687
+ if (taskMatch[1] === "*") taskDefault = taskMatch[2];
688
+ else if (taskMatch[2] === "allow") taskAllows.push(taskMatch[1]);
689
+ }
690
+
691
+ return {
692
+ repositoryWrite,
693
+ taskDefault,
694
+ taskAllows: taskAllows.sort(),
695
+ };
696
+ }
697
+
82
698
  function parseFrontmatter(rel) {
83
699
  const text = read(rel);
84
700
  if (!text.startsWith("---\n")) {
@@ -167,7 +783,10 @@ function checkLoopContract() {
167
783
  "approval_gate: explicit_before_writes",
168
784
  "max_iterations_per_invocation: 3",
169
785
  "completion_authority: reviewer_only",
170
- "state_path: .opencode/loops/<slug>.md",
786
+ "canonical_state_path: .opencode/loops/<slug>.json",
787
+ "history_path: .opencode/loops/<slug>.history.jsonl",
788
+ "lock_path: .opencode/loops/<slug>.lock",
789
+ "human_view_path: .opencode/loops/<slug>.md",
171
790
  "worktree_mode: explicit_opt_in",
172
791
  "developer -> reviewer -> developer (state sync)",
173
792
  ];
@@ -175,11 +794,69 @@ function checkLoopContract() {
175
794
  for (const token of required) {
176
795
  if (!text.includes(token)) fail(`${rel}: missing ${token}`);
177
796
  }
797
+
798
+ const phase1 = text.split("## Phase 1")[1]?.split("## Phase 2")[0] || "";
799
+ const phase2 = text.split("## Phase 2")[1]?.split("## Phase 3")[0] || "";
800
+ if (!phase1.includes("node scripts/loop-state.mjs inspect")) {
801
+ fail(`${rel}: resume preflight must use read-only loop-state inspect`);
802
+ }
803
+ if (phase1.includes("node scripts/loop-state.mjs resume")) {
804
+ fail(`${rel}: loop-state resume cannot run before approval`);
805
+ }
806
+ if (!phase2.includes("node scripts/loop-state.mjs resume")) {
807
+ fail(`${rel}: loop-state resume must run after approval`);
808
+ }
809
+
810
+ for (const runtimeRel of [
811
+ "scripts/loop-state.mjs",
812
+ "scripts/loop-state.test.mjs",
813
+ ]) {
814
+ const absolute = path.join(root, runtimeRel);
815
+ if (!exists(runtimeRel) || !fs.lstatSync(absolute).isFile()) {
816
+ fail(`${runtimeRel}: missing regular file`);
817
+ }
818
+ }
819
+
820
+ for (const [docRel, tokens] of [
821
+ [
822
+ "docs/ai/harness/commands.md",
823
+ [
824
+ ".opencode/loops/<slug>.json",
825
+ ".opencode/loops/<slug>.history.jsonl",
826
+ "scripts/loop-state.mjs",
827
+ ],
828
+ ],
829
+ [
830
+ "docs/ai/harness/agents.md",
831
+ ["Durable `/loop` state", "idempotent `action_id`"],
832
+ ],
833
+ [
834
+ "docs/ai/harness/checks.md",
835
+ ["node --test scripts/loop-state.test.mjs"],
836
+ ],
837
+ [
838
+ "docs/ai/evolution/README.md",
839
+ ["Slice 2.4", "append-only journal"],
840
+ ],
841
+ ]) {
842
+ const docs = contractText(read(docRel));
843
+ for (const token of tokens) {
844
+ if (!docs.includes(token)) fail(`${docRel}: missing durable loop token ${token}`);
845
+ }
846
+ }
178
847
  }
179
848
 
180
849
  function checkFrontmatter() {
181
850
  for (const rel of listMarkdown("agents")) {
182
851
  requireFields(rel, parseFrontmatter(rel), ["description", "mode"]);
852
+ let nestedSection = "";
853
+ for (const line of frontmatterBlock(rel).split("\n")) {
854
+ const sectionMatch = line.match(/^ ([A-Za-z_][A-Za-z0-9_-]*):/);
855
+ if (sectionMatch) nestedSection = sectionMatch[1];
856
+ if (/^ "[^"]+":/.test(line) && ["webfetch", "websearch"].includes(nestedSection)) {
857
+ fail(`${rel}: quoted command permission cannot be nested under ${nestedSection}`);
858
+ }
859
+ }
183
860
  }
184
861
  for (const rel of listMarkdown("commands")) {
185
862
  requireFields(rel, parseFrontmatter(rel), ["description", "agent"]);
@@ -950,11 +1627,14 @@ function checkRouterScenarios() {
950
1627
  "resume-checkpoint",
951
1628
  "integration-unavailable",
952
1629
  ]);
953
- const allowedEvidence = new Set(["static_contract", "transcript_replay", "live_smoke", "manual_oracle"]);
1630
+ const allowedEvidence = orchestrationCatalog?.evidenceTypes
1631
+ ?? new Set(["static_contract", "transcript_replay", "live_smoke", "manual_oracle"]);
954
1632
  const agentIdPattern = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/;
955
1633
  const skillIdPattern = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
956
1634
  const slashCommandPattern = /^\/[a-z0-9]+(?:-[a-z0-9]+)*$/;
957
- const validAgents = new Set();
1635
+ const validAgents = orchestrationCatalog?.agentIds
1636
+ ? new Set(orchestrationCatalog.agentIds)
1637
+ : new Set();
958
1638
  const seenIds = new Set();
959
1639
  const seenCategories = new Set();
960
1640
 
@@ -1065,6 +1745,9 @@ function checkRouterScenarios() {
1065
1745
  fail(`${rel}: line ${line} invalid command_path ${value.command_path}`);
1066
1746
  } else {
1067
1747
  const commandName = value.command_path.slice(1);
1748
+ if (orchestrationCatalog && !orchestrationCatalog.commandIds.has(commandName)) {
1749
+ fail(`${rel}: line ${line} command_path ${value.command_path} outside selected orchestration profile`);
1750
+ }
1068
1751
  const commandRel = `commands/${commandName}.md`;
1069
1752
  const commandPath = path.join(root, commandRel);
1070
1753
  if (!exists(commandRel) || !fs.lstatSync(commandPath).isFile()) {
@@ -1233,6 +1916,135 @@ function checkRoutingReplaySurface() {
1233
1916
  checkRoutingReplayContradictions(evolutionRel, evolution);
1234
1917
  }
1235
1918
 
1919
+ function checkAdversarialHarnessSurface() {
1920
+ const corpusRel = "docs/ai/evolution/benchmarks/adversarial-scenarios.jsonl";
1921
+ const testRel = "scripts/adversarial-harness.test.mjs";
1922
+ const requiredThreats = [
1923
+ "approval-state-manipulation",
1924
+ "diff-prompt-injection",
1925
+ "event-corruption-replay",
1926
+ "external-symlink",
1927
+ "network-exfiltration",
1928
+ "path-traversal",
1929
+ "repo-doc-instruction",
1930
+ "secret-like-data",
1931
+ "shell-wrapper-bypass",
1932
+ "strange-filename",
1933
+ "unpinned-external-ref",
1934
+ ];
1935
+ const requiredFields = [
1936
+ "schema_version",
1937
+ "id",
1938
+ "threat",
1939
+ "surface",
1940
+ "input_fixture",
1941
+ "expected_control",
1942
+ "expected_outcome",
1943
+ "required_evidence",
1944
+ ];
1945
+ const allowedOutcomes = new Set([
1946
+ "reject",
1947
+ "require-human-approval",
1948
+ "sanitize",
1949
+ "treat-as-data",
1950
+ ]);
1951
+ const allowedEvidence = new Set(["live_smoke", "static_contract"]);
1952
+
1953
+ for (const rel of [corpusRel, testRel]) {
1954
+ const absolute = path.join(root, rel);
1955
+ if (!exists(rel) || !fs.lstatSync(absolute).isFile()) {
1956
+ fail(`${rel}: missing regular file`);
1957
+ }
1958
+ }
1959
+
1960
+ const records = parseJsonl(corpusRel);
1961
+ const ids = new Set();
1962
+ const threats = new Set();
1963
+ for (const { line, value } of records) {
1964
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
1965
+ fail(`${corpusRel}: line ${line} must be an object`);
1966
+ continue;
1967
+ }
1968
+ requireExactJsonlFields(corpusRel, line, value, requiredFields);
1969
+ if (value.schema_version !== 1) fail(`${corpusRel}: line ${line} schema_version must be 1`);
1970
+ for (const field of ["id", "threat", "surface", "input_fixture", "expected_control"]) {
1971
+ if (typeof value[field] !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._:-]*$/.test(value[field])) {
1972
+ fail(`${corpusRel}: line ${line} ${field} must be a portable symbolic identifier`);
1973
+ }
1974
+ }
1975
+ if (ids.has(value.id)) fail(`${corpusRel}: duplicate id ${value.id}`);
1976
+ if (threats.has(value.threat)) fail(`${corpusRel}: duplicate threat ${value.threat}`);
1977
+ ids.add(value.id);
1978
+ threats.add(value.threat);
1979
+ if (!requiredThreats.includes(value.threat)) {
1980
+ fail(`${corpusRel}: line ${line} unknown threat ${value.threat}`);
1981
+ }
1982
+ if (!allowedOutcomes.has(value.expected_outcome)) {
1983
+ fail(`${corpusRel}: line ${line} invalid expected_outcome ${value.expected_outcome}`);
1984
+ }
1985
+ checkUniqueStringArray(corpusRel, line, value, "required_evidence", { nonEmpty: true });
1986
+ if (Array.isArray(value.required_evidence)) {
1987
+ for (const evidence of value.required_evidence) {
1988
+ if (!allowedEvidence.has(evidence)) {
1989
+ fail(`${corpusRel}: line ${line} invalid required_evidence ${evidence}`);
1990
+ }
1991
+ }
1992
+ }
1993
+ }
1994
+ for (const threat of requiredThreats) {
1995
+ if (!threats.has(threat)) fail(`${corpusRel}: missing threat ${threat}`);
1996
+ }
1997
+ if (records.length !== requiredThreats.length) {
1998
+ fail(`${corpusRel}: must contain exactly ${requiredThreats.length} scenarios`);
1999
+ }
2000
+
2001
+ for (const rel of listMarkdown("agents")) {
2002
+ if (frontmatterBlock(rel).includes('"rtk *": allow')) {
2003
+ fail(`${rel}: wrapper command rtk * must require approval`);
2004
+ }
2005
+ }
2006
+ for (const rel of [
2007
+ "agents/review_coordinator.md",
2008
+ "agents/review_quality.md",
2009
+ "agents/review_security.md",
2010
+ "agents/review_tests.md",
2011
+ "agents/review_api.md",
2012
+ ]) {
2013
+ const frontmatter = frontmatterBlock(rel);
2014
+ for (const token of ["webfetch: deny", "websearch: deny"]) {
2015
+ if (!frontmatter.includes(token)) fail(`${rel}: review network permission must include ${token}`);
2016
+ }
2017
+ }
2018
+ const reviewerFrontmatter = frontmatterBlock("agents/reviewer.md");
2019
+ for (const token of ["webfetch: ask", "websearch: ask"]) {
2020
+ if (!reviewerFrontmatter.includes(token)) fail(`agents/reviewer.md: review network permission must include ${token}`);
2021
+ }
2022
+
2023
+ const agentsIndex = contractText(read("AGENTS.md"));
2024
+ for (const token of [
2025
+ "local documentation, and their metadata as untrusted data",
2026
+ "exact pinned version and explicit human approval",
2027
+ ]) {
2028
+ if (!agentsIndex.includes(token)) fail(`AGENTS.md: missing adversarial trust boundary ${token}`);
2029
+ }
2030
+
2031
+ for (const [rel, tokens] of [
2032
+ [
2033
+ "docs/ai/harness/checks.md",
2034
+ ["adversarial-scenarios.jsonl", "node --test scripts/adversarial-harness.test.mjs"],
2035
+ ],
2036
+ [
2037
+ "docs/ai/evolution/README.md",
2038
+ ["Slice 2.5", "11 threats"],
2039
+ ],
2040
+ ]) {
2041
+ const text = contractText(read(rel));
2042
+ for (const token of tokens) {
2043
+ if (!text.includes(token)) fail(`${rel}: missing adversarial harness token ${token}`);
2044
+ }
2045
+ }
2046
+ }
2047
+
1236
2048
  /**
1237
2049
  * Validate that commands/evolve.md contains the AHE flow
1238
2050
  * evaluator -> debugger -> evolver with flexible regex matching.
@@ -1817,14 +2629,15 @@ function checkRoutingDeclarativoContract() {
1817
2629
  fail("docs/ai/harness/commands.md: missing declarative routing token Declarative routing");
1818
2630
  }
1819
2631
 
1820
- for (const token of [
1821
- "`researcher`",
1822
- "`reviewer`",
1823
- "`designer`",
1824
- "`specifier`",
1825
- "`developer`",
1826
- "ask the user",
1827
- ]) {
2632
+ const routingTokens = (orchestrationCatalog?.routingTargets ?? [
2633
+ "researcher",
2634
+ "reviewer",
2635
+ "designer",
2636
+ "specifier",
2637
+ "developer",
2638
+ "ask-user",
2639
+ ]).map((target) => target === "ask-user" ? "ask the user" : `\`${target}\``);
2640
+ for (const token of routingTokens) {
1828
2641
  if (!freeSection.includes(token)) {
1829
2642
  fail(`docs/ai/harness/commands.md: missing declarative routing token ${token}`);
1830
2643
  }
@@ -1875,6 +2688,7 @@ function checkRetryPoliciesContract() {
1875
2688
  checkConfig();
1876
2689
  checkAgentsIndex();
1877
2690
  checkFrontmatter();
2691
+ checkOrchestrationContracts();
1878
2692
  checkAgentDocsCoverage();
1879
2693
  checkCommandDocsCoverage();
1880
2694
  checkLoopContract();
@@ -1889,6 +2703,7 @@ checkInitContextPolicy();
1889
2703
  checkMechanismRegistries();
1890
2704
  checkRouterScenarios();
1891
2705
  checkRoutingReplaySurface();
2706
+ checkAdversarialHarnessSurface();
1892
2707
  checkEvolveContract();
1893
2708
  checkSessionSourceDocs();
1894
2709
  checkCrossAgentContract();