create-agdf 0.10.0 → 0.10.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.
Files changed (89) hide show
  1. package/README.md +30 -22
  2. package/bin/agdf-validator.js +11 -0
  3. package/generated/.agdf/control/README.md +3 -3
  4. package/generated/.github/skills/agdf-brownfield-analysis/SKILL.md +1 -1
  5. package/generated/.github/skills/agdf-delivery-path-search/SKILL.md +7 -6
  6. package/generated/.github/skills/agdf-gate-check/SKILL.md +28 -91
  7. package/generated/.github/skills/agdf-interaction-locales.json +2 -0
  8. package/generated/.github/skills/contracts/gate-transition.md +4 -2
  9. package/generated/.github/skills/contracts/modes.md +12 -1
  10. package/generated/.opencode/README.md +6 -8
  11. package/generated/.opencode/agdf-interaction-locales.json +2 -0
  12. package/generated/.opencode/contracts/gate-transition.md +4 -2
  13. package/generated/.opencode/contracts/modes.md +12 -1
  14. package/generated/.opencode/skills/agdf-brownfield-analysis/SKILL.md +1 -1
  15. package/generated/.opencode/skills/agdf-delivery-path-search/SKILL.md +7 -6
  16. package/generated/.opencode/skills/agdf-gate-check/SKILL.md +28 -91
  17. package/generated/plugins/agdf/.claude-plugin/plugin.json +19 -0
  18. package/generated/plugins/agdf/.codex-plugin/plugin.json +1 -1
  19. package/generated/plugins/agdf/control/README.md +3 -3
  20. package/generated/plugins/agdf/hooks/session-start.sh +1 -1
  21. package/generated/plugins/agdf/meta/agdf-interaction-locales.json +2 -0
  22. package/generated/plugins/agdf/meta/agdf-plugin.definition.json +1 -1
  23. package/generated/plugins/agdf/meta/contracts/gate-transition.md +4 -2
  24. package/generated/plugins/agdf/meta/contracts/modes.md +12 -1
  25. package/generated/plugins/agdf/runtime/agdf-local.js +11 -0
  26. package/generated/plugins/agdf/runtime/create-agdf/NOTICE +10 -0
  27. package/generated/plugins/agdf/runtime/create-agdf/bin/agdf-validator.js +11 -0
  28. package/generated/plugins/agdf/runtime/create-agdf/generated/plugins/agdf/meta/agdf-interaction-locales.json +418 -0
  29. package/generated/plugins/agdf/runtime/create-agdf/generated/plugins/agdf/meta/agdf-plugin.definition.json +220 -0
  30. package/generated/plugins/agdf/runtime/create-agdf/lib/cli/command-registry.js +136 -0
  31. package/generated/plugins/agdf/runtime/create-agdf/lib/cli/delivery-path-search-command.js +75 -0
  32. package/generated/plugins/agdf/runtime/create-agdf/lib/cli/parse-args.js +156 -0
  33. package/generated/plugins/agdf/runtime/create-agdf/lib/cli/runtime-context.js +83 -0
  34. package/generated/plugins/agdf/runtime/create-agdf/lib/cli/validation-handlers.js +45 -0
  35. package/generated/plugins/agdf/runtime/create-agdf/lib/control-evaluation/delivery-map.js +291 -0
  36. package/generated/plugins/agdf/runtime/create-agdf/lib/control-evaluation/doctor.js +265 -0
  37. package/generated/plugins/agdf/runtime/create-agdf/lib/control-evaluation/gate-check.js +459 -0
  38. package/generated/plugins/agdf/runtime/create-agdf/lib/control-evaluation/gate-policy.js +283 -0
  39. package/generated/plugins/agdf/runtime/create-agdf/lib/control-evaluation/required-files.js +9 -0
  40. package/generated/plugins/agdf/runtime/create-agdf/lib/control-evaluation/run-state.js +217 -0
  41. package/generated/plugins/agdf/runtime/create-agdf/lib/control-evaluation/shared.js +344 -0
  42. package/generated/plugins/agdf/runtime/create-agdf/lib/control-evaluation/verified-change.js +156 -0
  43. package/generated/plugins/agdf/runtime/create-agdf/lib/control-state/aggregate.js +18 -0
  44. package/generated/plugins/agdf/runtime/create-agdf/lib/control-state/gate-approval-validator.js +49 -0
  45. package/generated/plugins/agdf/runtime/create-agdf/lib/control-state/index.js +7 -0
  46. package/generated/plugins/agdf/runtime/create-agdf/lib/control-state/legacy-migration.js +95 -0
  47. package/generated/plugins/agdf/runtime/create-agdf/lib/control-state/run-state-parser.js +227 -0
  48. package/generated/plugins/agdf/runtime/create-agdf/lib/control-state/run-state-repository.js +68 -0
  49. package/generated/plugins/agdf/runtime/create-agdf/lib/control-state/run-state-resolver.js +45 -0
  50. package/generated/plugins/agdf/runtime/create-agdf/lib/control-state/run-state-writer.js +97 -0
  51. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/candidate-policy.js +99 -0
  52. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/contracts.js +237 -0
  53. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/evaluators/claude.js +44 -0
  54. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/evaluators/codex.js +53 -0
  55. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/evaluators/protocol.js +13 -0
  56. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/generators/claude.js +40 -0
  57. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/generators/codex.js +38 -0
  58. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/generators/protocol.js +12 -0
  59. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/persistence.js +39 -0
  60. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/scoring.js +21 -0
  61. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/search-engine.js +154 -0
  62. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/state-adapter.js +161 -0
  63. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/surfaces/capabilities.js +14 -0
  64. package/generated/plugins/agdf/runtime/create-agdf/lib/delivery-path-search/transports/read-only-guard.js +43 -0
  65. package/generated/plugins/agdf/runtime/create-agdf/lib/interaction-presentation.js +590 -0
  66. package/generated/plugins/agdf/runtime/create-agdf/lib/runtime/local-validator.js +142 -0
  67. package/generated/plugins/agdf/runtime/create-agdf/lib/runtime/validator-application.js +40 -0
  68. package/generated/plugins/agdf/runtime/create-agdf/package.json +66 -0
  69. package/generated/plugins/agdf/runtime/runtime-manifest.json +8 -0
  70. package/generated/plugins/agdf/scripts/check-runtime-integrity.mjs +1040 -0
  71. package/generated/plugins/agdf/skills/brownfield-analysis/SKILL.md +1 -1
  72. package/generated/plugins/agdf/skills/delivery-path-search/SKILL.md +7 -6
  73. package/generated/plugins/agdf/skills/gate-check/SKILL.md +28 -91
  74. package/lib/cli/application.js +21 -59
  75. package/lib/cli/command-registry.js +9 -11
  76. package/lib/cli/validation-handlers.js +45 -0
  77. package/lib/control-evaluation/doctor.js +1 -1
  78. package/lib/control-evaluation/gate-check.js +7 -7
  79. package/lib/control-evaluation/required-files.js +9 -0
  80. package/lib/installers/local-marketplace.js +322 -0
  81. package/lib/installers/opencode-activation.js +43 -0
  82. package/lib/installers/opencode.js +60 -18
  83. package/lib/installers/plugin-installers.js +102 -26
  84. package/lib/runtime/local-validator.js +142 -0
  85. package/lib/runtime/validator-application.js +40 -0
  86. package/lib/scaffold/plan.js +1 -30
  87. package/lib/scaffold/presentation.js +9 -14
  88. package/opencode-plugin.js +32 -24
  89. package/package.json +6 -2
@@ -0,0 +1,237 @@
1
+ export const CONTRACT_VERSION = "1";
2
+ export const GENERATOR_CONTRACT_VERSION = "1";
3
+ export const SCORING_POLICY_VERSION = "1";
4
+ export const SCORE_DIMENSIONS = [
5
+ "scope_fit",
6
+ "gate_readiness",
7
+ "risk_reduction",
8
+ "evidence_gain",
9
+ "testability",
10
+ "reversibility",
11
+ "cost",
12
+ ];
13
+
14
+ function requireObject(value, label) {
15
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`${label} must be an object`);
16
+ return value;
17
+ }
18
+
19
+ function requireString(value, label) {
20
+ if (typeof value !== "string" || !value.trim()) throw new Error(`${label} must be a non-empty string`);
21
+ return value.trim();
22
+ }
23
+
24
+ function stringArray(value, label) {
25
+ if (!Array.isArray(value) || value.some((item) => typeof item !== "string")) throw new Error(`${label} must be a string array`);
26
+ return value.map((item) => item.trim()).filter(Boolean);
27
+ }
28
+
29
+ function optionalBoundedString(value, label, maxLength = 1000) {
30
+ if (value === undefined) return undefined;
31
+ const result = requireString(value, label);
32
+ if (result.length > maxLength) throw new Error(`${label} must be at most ${maxLength} characters`);
33
+ return result;
34
+ }
35
+
36
+ function rejectUnknownKeys(value, allowed, label) {
37
+ const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
38
+ if (unknown.length) throw new Error(`${label} contains unknown fields: ${unknown.join(", ")}`);
39
+ }
40
+
41
+ function generationConfig(value, wholeRunBudgets) {
42
+ if (value === undefined) return undefined;
43
+ const generation = requireObject(value, "generation");
44
+ if (typeof generation.enabled !== "boolean") throw new Error("generation.enabled must be a boolean");
45
+ const limits = {
46
+ max_calls: 1,
47
+ max_proposals: 5,
48
+ max_duration_ms: 30000,
49
+ max_cost_units: 5,
50
+ };
51
+ for (const [key, maximum] of Object.entries(limits)) {
52
+ if (!Number.isInteger(generation[key]) || generation[key] < 1 || generation[key] > maximum) {
53
+ throw new Error(`generation.${key} must be an integer from 1 to ${maximum}`);
54
+ }
55
+ }
56
+ if (generation.max_calls !== 1) throw new Error("generation.max_calls must equal 1 in this contract version");
57
+ if (generation.max_duration_ms > wholeRunBudgets.max_duration_ms) throw new Error("generation.max_duration_ms cannot exceed budgets.max_duration_ms");
58
+ if (generation.max_cost_units > wholeRunBudgets.max_cost_units) throw new Error("generation.max_cost_units cannot exceed budgets.max_cost_units");
59
+ return structuredClone(generation);
60
+ }
61
+
62
+ export function validateSearchInput(value) {
63
+ const input = requireObject(value, "search input");
64
+ if (input.contract_version !== CONTRACT_VERSION) throw new Error(`unsupported search input contract_version: ${input.contract_version}`);
65
+ requireString(input.scope_key, "scope_key");
66
+ if (!/^[a-z0-9][a-z0-9._-]*$/i.test(input.scope_key) || input.scope_key.includes("..")) {
67
+ throw new Error("scope_key must be a safe path segment");
68
+ }
69
+ requireString(input.objective, "objective");
70
+ requireString(input.current_gate, "current_gate");
71
+ stringArray(input.allowed_actions, "allowed_actions");
72
+ stringArray(input.forbidden_actions, "forbidden_actions");
73
+ stringArray(input.evidence_refs ?? [], "evidence_refs");
74
+ stringArray(input.risks ?? [], "risks");
75
+ validateEnforcement(input.enforcement);
76
+ const budgets = requireObject(input.budgets, "budgets");
77
+ for (const key of ["max_candidates", "max_depth", "max_evaluations", "max_duration_ms", "max_cost_units", "stability_window"]) {
78
+ if (!Number.isInteger(budgets[key]) || budgets[key] < 1) throw new Error(`budgets.${key} must be a positive integer`);
79
+ }
80
+ generationConfig(input.generation, budgets);
81
+ return structuredClone(input);
82
+ }
83
+
84
+ export function validateCandidate(value) {
85
+ const candidate = requireObject(value, "candidate");
86
+ requireString(candidate.id, "candidate.id");
87
+ requireString(candidate.action, "candidate.action");
88
+ stringArray(candidate.expected_evidence ?? [], "candidate.expected_evidence");
89
+ stringArray(candidate.tests ?? [], "candidate.tests");
90
+ stringArray(candidate.assumptions ?? [], "candidate.assumptions");
91
+ if (candidate.source !== undefined && !["deterministic", "generated", "expanded"].includes(candidate.source)) {
92
+ throw new Error("candidate.source must be deterministic, generated or expanded");
93
+ }
94
+ optionalBoundedString(candidate.gate_action, "candidate.gate_action");
95
+ optionalBoundedString(candidate.intent, "candidate.intent");
96
+ stringArray(candidate.affected_boundaries ?? [], "candidate.affected_boundaries");
97
+ optionalBoundedString(candidate.risk_strategy, "candidate.risk_strategy");
98
+ optionalBoundedString(candidate.reversibility, "candidate.reversibility");
99
+ optionalBoundedString(candidate.generator_proposal_id, "candidate.generator_proposal_id", 200);
100
+ return structuredClone(candidate);
101
+ }
102
+
103
+ export function validateGeneratorRequest(value) {
104
+ const request = requireObject(value, "generator request");
105
+ rejectUnknownKeys(request, ["contract_version", "scope_key", "objective", "scope_summary", "current_gate", "allowed_actions", "forbidden_actions", "artefact_refs", "evidence", "missing_evidence", "risks", "constraints", "enforcement", "budgets"], "generator request");
106
+ if (request.contract_version !== GENERATOR_CONTRACT_VERSION) throw new Error(`unsupported generator contract_version: ${request.contract_version}`);
107
+ requireString(request.scope_key, "generator scope_key");
108
+ optionalBoundedString(request.objective, "generator objective", 2000);
109
+ optionalBoundedString(request.scope_summary, "generator scope_summary", 2000);
110
+ requireString(request.current_gate, "generator current_gate");
111
+ for (const key of ["allowed_actions", "forbidden_actions", "artefact_refs", "evidence", "missing_evidence", "risks", "constraints"]) {
112
+ const items = stringArray(request[key] ?? [], `generator ${key}`);
113
+ if (items.length > 20 || items.some((item) => item.length > 500)) throw new Error(`generator ${key} exceeds context bounds`);
114
+ }
115
+ validateEnforcement(request.enforcement);
116
+ const budgets = requireObject(request.budgets, "generator budgets");
117
+ generationConfig({ enabled: true, ...budgets }, { max_duration_ms: 120000, max_cost_units: 20 });
118
+ const serialized = JSON.stringify(request);
119
+ if (/(secret|credential|environment|raw_prompt|hidden_reasoning|source_snapshot)/i.test(serialized)) {
120
+ throw new Error("generator request contains disallowed context");
121
+ }
122
+ return structuredClone(request);
123
+ }
124
+
125
+ export function validateGeneratorResponse(value) {
126
+ const response = requireObject(value, "generator response");
127
+ rejectUnknownKeys(response, ["contract_version", "proposals", "cost_units", "metadata"], "generator response");
128
+ if (response.contract_version !== GENERATOR_CONTRACT_VERSION) throw new Error(`unsupported generator contract_version: ${response.contract_version}`);
129
+ if (!Array.isArray(response.proposals) || response.proposals.length > 5) throw new Error("generator proposals must be an array with at most 5 items");
130
+ if (!Number.isInteger(response.cost_units) || response.cost_units < 0 || response.cost_units > 5) throw new Error("generator cost_units must be an integer from 0 to 5");
131
+ if (response.metadata !== undefined) {
132
+ const metadata = requireObject(response.metadata, "generator metadata");
133
+ rejectUnknownKeys(metadata, ["name", "runtime", "model"], "generator metadata");
134
+ for (const [key, item] of Object.entries(metadata)) optionalBoundedString(item, `generator metadata.${key}`, 500);
135
+ }
136
+ const proposals = response.proposals.map((proposal, index) => {
137
+ const item = requireObject(proposal, `proposal ${index}`);
138
+ rejectUnknownKeys(item, ["proposal_id", "gate_action", "intent", "expected_evidence", "tests", "assumptions", "affected_boundaries", "risk_strategy", "reversibility"], `proposal ${index}`);
139
+ const normalized = {
140
+ proposal_id: requireString(item.proposal_id, `proposal ${index}.proposal_id`),
141
+ gate_action: requireString(item.gate_action, `proposal ${index}.gate_action`),
142
+ intent: requireString(item.intent, `proposal ${index}.intent`),
143
+ expected_evidence: stringArray(item.expected_evidence ?? [], `proposal ${index}.expected_evidence`),
144
+ tests: stringArray(item.tests ?? [], `proposal ${index}.tests`),
145
+ assumptions: stringArray(item.assumptions ?? [], `proposal ${index}.assumptions`),
146
+ affected_boundaries: stringArray(item.affected_boundaries ?? [], `proposal ${index}.affected_boundaries`),
147
+ risk_strategy: requireString(item.risk_strategy, `proposal ${index}.risk_strategy`),
148
+ reversibility: requireString(item.reversibility, `proposal ${index}.reversibility`),
149
+ };
150
+ if (JSON.stringify(normalized).length > 5000) throw new Error(`proposal ${index} exceeds size limit`);
151
+ if (/(^|\s)(rm|sudo|curl|wget|bash|sh|exec)\s/i.test(normalized.intent)) throw new Error(`proposal ${index} contains executable instructions`);
152
+ return normalized;
153
+ });
154
+ return {
155
+ contract_version: response.contract_version,
156
+ proposals,
157
+ cost_units: response.cost_units,
158
+ metadata: response.metadata ? structuredClone(response.metadata) : {},
159
+ };
160
+ }
161
+
162
+ export function generatorOutputSchema() {
163
+ return {
164
+ type: "object",
165
+ additionalProperties: false,
166
+ required: ["contract_version", "proposals", "cost_units"],
167
+ properties: {
168
+ contract_version: { type: "string", const: GENERATOR_CONTRACT_VERSION },
169
+ cost_units: { type: "integer", minimum: 0, maximum: 5 },
170
+ proposals: {
171
+ type: "array", maxItems: 5, items: {
172
+ type: "object", additionalProperties: false,
173
+ required: ["proposal_id", "gate_action", "intent", "expected_evidence", "tests", "assumptions", "affected_boundaries", "risk_strategy", "reversibility"],
174
+ properties: {
175
+ proposal_id: { type: "string", minLength: 1 }, gate_action: { type: "string", minLength: 1 }, intent: { type: "string", minLength: 1 },
176
+ expected_evidence: { type: "array", items: { type: "string" } }, tests: { type: "array", items: { type: "string" } },
177
+ assumptions: { type: "array", items: { type: "string" } }, affected_boundaries: { type: "array", items: { type: "string" } },
178
+ risk_strategy: { type: "string", minLength: 1 }, reversibility: { type: "string", minLength: 1 },
179
+ },
180
+ },
181
+ },
182
+ },
183
+ };
184
+ }
185
+
186
+ export function validateEvaluation(value, candidateId) {
187
+ const evaluation = requireObject(value, "evaluation");
188
+ if (evaluation.contract_version !== CONTRACT_VERSION) throw new Error(`unsupported evaluator contract_version: ${evaluation.contract_version}`);
189
+ if (evaluation.candidate_id !== candidateId) throw new Error(`evaluation candidate_id must be ${candidateId}`);
190
+ for (const dimension of SCORE_DIMENSIONS) {
191
+ if (!Number.isInteger(evaluation[dimension]) || evaluation[dimension] < 0 || evaluation[dimension] > 5) {
192
+ throw new Error(`${dimension} must be an integer from 0 to 5`);
193
+ }
194
+ }
195
+ if (!Number.isInteger(evaluation.uncertainty) || evaluation.uncertainty < 0 || evaluation.uncertainty > 5) {
196
+ throw new Error("uncertainty must be an integer from 0 to 5");
197
+ }
198
+ requireString(evaluation.rationale, "evaluation.rationale");
199
+ stringArray(evaluation.risks ?? [], "evaluation.risks");
200
+ stringArray(evaluation.assumptions ?? [], "evaluation.assumptions");
201
+ stringArray(evaluation.child_actions ?? [], "evaluation.child_actions");
202
+ if (/(^|\s)(rm|sudo|curl|wget|bash|sh|exec)\s/i.test(evaluation.rationale)) {
203
+ throw new Error("evaluation rationale contains executable instructions");
204
+ }
205
+ return structuredClone(evaluation);
206
+ }
207
+
208
+ export function validateEnforcement(value) {
209
+ const enforcement = requireObject(value, "enforcement");
210
+ if (!["full", "tool_enforced", "instruction_only"].includes(enforcement.level)) {
211
+ throw new Error("enforcement.level must be full, tool_enforced or instruction_only");
212
+ }
213
+ const evidence = stringArray(enforcement.evidence ?? [], "enforcement.evidence");
214
+ if (enforcement.level !== "instruction_only" && evidence.length === 0) {
215
+ throw new Error(`${enforcement.level} requires enforcement evidence`);
216
+ }
217
+ return { level: enforcement.level, evidence };
218
+ }
219
+
220
+ export function evaluatorOutputSchema() {
221
+ const scoreProperties = Object.fromEntries(SCORE_DIMENSIONS.map((key) => [key, { type: "integer", minimum: 0, maximum: 5 }]));
222
+ return {
223
+ type: "object",
224
+ additionalProperties: false,
225
+ required: ["contract_version", "candidate_id", ...SCORE_DIMENSIONS, "uncertainty", "rationale", "risks", "assumptions", "child_actions"],
226
+ properties: {
227
+ contract_version: { type: "string", const: CONTRACT_VERSION },
228
+ candidate_id: { type: "string" },
229
+ ...scoreProperties,
230
+ uncertainty: { type: "integer", minimum: 0, maximum: 5 },
231
+ rationale: { type: "string", minLength: 1, maxLength: 1000 },
232
+ risks: { type: "array", items: { type: "string" } },
233
+ assumptions: { type: "array", items: { type: "string" } },
234
+ child_actions: { type: "array", items: { type: "string" }, maxItems: 5 },
235
+ },
236
+ };
237
+ }
@@ -0,0 +1,44 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { evaluatorOutputSchema, validateEvaluation } from "../contracts.js";
3
+ import { guardedExecFileSync } from "../transports/read-only-guard.js";
4
+
5
+ export function claudeEvaluator(options = {}) {
6
+ const claudeBin = options.claudeBin ?? "claude";
7
+ let runtime = "claude version unavailable";
8
+ try {
9
+ runtime = execFileSync(claudeBin, ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
10
+ } catch {}
11
+
12
+ return {
13
+ name: "claude",
14
+ metadata: { name: "claude", runtime, model: options.model ?? "configured-default" },
15
+ async evaluate(input, candidate) {
16
+ const prompt = [
17
+ "You are an evaluation-only component. Do not use tools, execute commands, or modify files.",
18
+ `Return JSON matching contract version ${input.contract_version}.`,
19
+ `Objective: ${input.objective}`,
20
+ `Current gate: ${input.current_gate}`,
21
+ `Candidate id: ${candidate.id}`,
22
+ `Candidate action: ${candidate.action}`,
23
+ "Score scope_fit, gate_readiness, risk_reduction, evidence_gain, testability, reversibility and cost from 0 to 5.",
24
+ "Cost 0 is low and 5 is high. uncertainty is 0 low to 5 high.",
25
+ "Keep rationale concise. child_actions must only contain actions permitted by the current gate.",
26
+ ].join("\n");
27
+ const args = [
28
+ "-p", "--disallowedTools", "Edit,Write,Bash",
29
+ "--output-format", "json", "--json-schema", JSON.stringify(evaluatorOutputSchema()),
30
+ ];
31
+ if (options.model) args.push("--model", options.model);
32
+ args.push(prompt);
33
+ const raw = guardedExecFileSync(claudeBin, args, {
34
+ cwd: options.cwd,
35
+ encoding: "utf8",
36
+ stdio: ["ignore", "pipe", "pipe"],
37
+ timeout: options.timeoutMs ?? 120000,
38
+ });
39
+ const response = JSON.parse(raw);
40
+ if (response.is_error) throw new Error(`claude evaluator returned an error: ${response.result ?? "unknown error"}`);
41
+ return validateEvaluation(JSON.parse(response.result), candidate.id);
42
+ },
43
+ };
44
+ }
@@ -0,0 +1,53 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { evaluatorOutputSchema, validateEvaluation } from "../contracts.js";
6
+ import { guardedExecFileSync } from "../transports/read-only-guard.js";
7
+
8
+ export function codexEvaluator(options = {}) {
9
+ const codexBin = options.codexBin ?? "codex";
10
+ let runtime = "codex version unavailable";
11
+ try {
12
+ runtime = execFileSync(codexBin, ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
13
+ } catch {}
14
+
15
+ return {
16
+ name: "codex",
17
+ metadata: { name: "codex", runtime, model: options.model ?? "configured-default" },
18
+ async evaluate(input, candidate) {
19
+ const temp = mkdtempSync(join(tmpdir(), "agdf-dps-"));
20
+ const schemaPath = join(temp, "schema.json");
21
+ const outputPath = join(temp, "output.json");
22
+ try {
23
+ writeFileSync(schemaPath, `${JSON.stringify(evaluatorOutputSchema(), null, 2)}\n`, "utf8");
24
+ const prompt = [
25
+ "You are an evaluation-only component. Do not use tools, execute commands, or modify files.",
26
+ `Return JSON matching contract version ${input.contract_version}.`,
27
+ `Objective: ${input.objective}`,
28
+ `Current gate: ${input.current_gate}`,
29
+ `Candidate id: ${candidate.id}`,
30
+ `Candidate action: ${candidate.action}`,
31
+ "Score scope_fit, gate_readiness, risk_reduction, evidence_gain, testability, reversibility and cost from 0 to 5.",
32
+ "Cost 0 is low and 5 is high. uncertainty is 0 low to 5 high.",
33
+ "Keep rationale concise. child_actions must only contain actions permitted by the current gate.",
34
+ ].join("\n");
35
+ const args = [
36
+ "exec", "--sandbox", "read-only", "--ephemeral", "--ignore-user-config",
37
+ "--output-schema", schemaPath, "--output-last-message", outputPath, "--color", "never",
38
+ ];
39
+ if (options.model) args.push("--model", options.model);
40
+ args.push(prompt);
41
+ guardedExecFileSync(codexBin, args, {
42
+ cwd: options.cwd,
43
+ encoding: "utf8",
44
+ stdio: ["ignore", "pipe", "pipe"],
45
+ timeout: options.timeoutMs ?? 120000,
46
+ });
47
+ return validateEvaluation(JSON.parse(readFileSync(outputPath, "utf8")), candidate.id);
48
+ } finally {
49
+ rmSync(temp, { recursive: true, force: true });
50
+ }
51
+ },
52
+ };
53
+ }
@@ -0,0 +1,13 @@
1
+ import { validateEvaluation } from "../contracts.js";
2
+
3
+ export function fixtureEvaluator(evaluations) {
4
+ return {
5
+ name: "fixture",
6
+ metadata: { name: "fixture", runtime: "deterministic-test" },
7
+ async evaluate(_input, candidate) {
8
+ const value = evaluations[candidate.id];
9
+ if (!value) throw new Error(`missing fixture evaluation for ${candidate.id}`);
10
+ return validateEvaluation(value, candidate.id);
11
+ },
12
+ };
13
+ }
@@ -0,0 +1,40 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { generatorOutputSchema, validateGeneratorRequest, validateGeneratorResponse } from "../contracts.js";
3
+ import { guardedExecFileSync } from "../transports/read-only-guard.js";
4
+
5
+ export function claudeGenerator(options = {}) {
6
+ const claudeBin = options.claudeBin ?? "claude";
7
+ const execute = options.execute ?? guardedExecFileSync;
8
+ let runtime = options.runtime ?? "claude version unavailable";
9
+ if (!options.runtime) try { runtime = execFileSync(claudeBin, ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch {}
10
+ return {
11
+ name: "claude",
12
+ metadata: { name: "claude", runtime, model: options.model ?? "configured-default" },
13
+ async generate(requestValue) {
14
+ const request = validateGeneratorRequest(requestValue);
15
+ const prompt = [
16
+ "Generate bounded advisory delivery-path proposals. Do not use tools, execute commands, or modify files.",
17
+ "Return only JSON matching the supplied schema. Do not include hidden reasoning.",
18
+ `Normalized request: ${JSON.stringify(request)}`,
19
+ ].join("\n");
20
+ const args = ["-p", "--disallowedTools", "Edit,Write,Bash", "--output-format", "json", "--json-schema", JSON.stringify(generatorOutputSchema())];
21
+ if (options.model) args.push("--model", options.model);
22
+ args.push(prompt);
23
+ let raw;
24
+ try {
25
+ raw = execute(claudeBin, args, { cwd: options.cwd, timeout: options.timeoutMs ?? request.budgets.max_duration_ms });
26
+ } catch (error) {
27
+ const providerOutput = String(error?.stdout ?? "");
28
+ if (/not logged in|unauthorized|authentication/i.test(providerOutput)) {
29
+ const authentication = new Error("claude generator authentication failed");
30
+ authentication.code = "GENERATOR_AUTHENTICATION_FAILED";
31
+ throw authentication;
32
+ }
33
+ throw error;
34
+ }
35
+ const response = JSON.parse(raw);
36
+ if (response.is_error) throw new Error(`claude generator returned an error: ${response.result ?? "unknown error"}`);
37
+ return validateGeneratorResponse(JSON.parse(response.result));
38
+ },
39
+ };
40
+ }
@@ -0,0 +1,38 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { tmpdir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { generatorOutputSchema, validateGeneratorRequest, validateGeneratorResponse } from "../contracts.js";
6
+ import { guardedExecFileSync } from "../transports/read-only-guard.js";
7
+
8
+ export function codexGenerator(options = {}) {
9
+ const codexBin = options.codexBin ?? "codex";
10
+ const execute = options.execute ?? guardedExecFileSync;
11
+ let runtime = options.runtime ?? "codex version unavailable";
12
+ if (!options.runtime) try { runtime = execFileSync(codexBin, ["--version"], { encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim(); } catch {}
13
+ return {
14
+ name: "codex",
15
+ metadata: { name: "codex", runtime, model: options.model ?? "configured-default" },
16
+ async generate(requestValue) {
17
+ const request = validateGeneratorRequest(requestValue);
18
+ const temp = mkdtempSync(join(tmpdir(), "agdf-dps-generator-"));
19
+ const schemaPath = join(temp, "schema.json");
20
+ const outputPath = join(temp, "output.json");
21
+ try {
22
+ writeFileSync(schemaPath, `${JSON.stringify(generatorOutputSchema(), null, 2)}\n`, "utf8");
23
+ const prompt = [
24
+ "Generate bounded advisory delivery-path proposals. Do not use tools, execute commands, or modify files.",
25
+ "Return only JSON matching the supplied schema. Do not include hidden reasoning.",
26
+ `Normalized request: ${JSON.stringify(request)}`,
27
+ ].join("\n");
28
+ const args = ["exec", "--sandbox", "read-only", "--ephemeral", "--ignore-user-config", "--output-schema", schemaPath, "--output-last-message", outputPath, "--color", "never"];
29
+ if (options.model) args.push("--model", options.model);
30
+ args.push(prompt);
31
+ execute(codexBin, args, { cwd: options.cwd, timeout: options.timeoutMs ?? request.budgets.max_duration_ms });
32
+ return validateGeneratorResponse(JSON.parse(readFileSync(outputPath, "utf8")));
33
+ } finally {
34
+ rmSync(temp, { recursive: true, force: true });
35
+ }
36
+ },
37
+ };
38
+ }
@@ -0,0 +1,12 @@
1
+ import { validateGeneratorRequest, validateGeneratorResponse } from "../contracts.js";
2
+
3
+ export function fixtureGenerator(response, metadata = { name: "fixture-generator" }) {
4
+ return {
5
+ name: metadata.name,
6
+ metadata,
7
+ async generate(request) {
8
+ validateGeneratorRequest(request);
9
+ return validateGeneratorResponse(response);
10
+ },
11
+ };
12
+ }
@@ -0,0 +1,39 @@
1
+ import { mkdirSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+
4
+ function safeResult(result) {
5
+ return JSON.parse(JSON.stringify(result, (key, value) => {
6
+ if (/(prompt|hidden_reasoning|secret|credential|source_snapshot)/i.test(key)) return undefined;
7
+ return value;
8
+ }));
9
+ }
10
+
11
+ export function persistSearchResult(targetDir, result) {
12
+ const root = join(targetDir, ".agdf", "control", "artefacts", result.scope_key);
13
+ const jsonPath = join(root, "DELIVERY_PATH_SEARCH.json");
14
+ const markdownPath = join(root, "DELIVERY_PATH_SEARCH.md");
15
+ mkdirSync(dirname(jsonPath), { recursive: true });
16
+ const safe = safeResult(result);
17
+ writeFileSync(jsonPath, `${JSON.stringify(safe, null, 2)}\n`, "utf8");
18
+ const recommendation = safe.recommendation?.action ?? "No safe recommendation";
19
+ writeFileSync(markdownPath, [
20
+ "# Delivery Path Search Decision",
21
+ "",
22
+ `- status: ${safe.status}`,
23
+ `- current_gate: ${safe.current_gate}`,
24
+ `- enforcement: ${safe.enforcement.level}`,
25
+ `- recommendation: ${recommendation}`,
26
+ `- stopping_reason: ${safe.stopping_reason}`,
27
+ `- evaluations: ${safe.budgets.evaluations}`,
28
+ `- generation_status: ${safe.generation?.status ?? "legacy_deterministic"}`,
29
+ `- generated_candidates: ${safe.generation ? `${safe.generation.accepted}/${safe.generation.returned}` : "0/0"}`,
30
+ `- generation_cost_units: ${safe.generation?.cost_units ?? 0}`,
31
+ `- generation_duration_ms: ${safe.generation?.duration_ms ?? 0}`,
32
+ ...(safe.generation?.failure_code ? [`- generation_failure: ${safe.generation.failure_code}`] : []),
33
+ `- next_gate_action: ${safe.next_gate_action}`,
34
+ "",
35
+ "This summary contains model judgements, not measured facts. Canonical AGDF gate-check remains authoritative.",
36
+ "",
37
+ ].join("\n"), "utf8");
38
+ return { jsonPath, markdownPath };
39
+ }
@@ -0,0 +1,21 @@
1
+ import { SCORING_POLICY_VERSION } from "./contracts.js";
2
+
3
+ export const DEFAULT_WEIGHTS = Object.freeze({
4
+ scope_fit: 3,
5
+ gate_readiness: 3,
6
+ risk_reduction: 2,
7
+ evidence_gain: 2,
8
+ testability: 2,
9
+ reversibility: 1,
10
+ cost: -1,
11
+ uncertainty: -2,
12
+ });
13
+
14
+ const enforcementPenalty = { full: 0, tool_enforced: 1, instruction_only: 4 };
15
+
16
+ export function scoreEvaluation(evaluation, enforcementLevel, weights = DEFAULT_WEIGHTS) {
17
+ const contributions = Object.fromEntries(Object.entries(weights).map(([key, weight]) => [key, evaluation[key] * weight]));
18
+ const penalty = enforcementPenalty[enforcementLevel] ?? 4;
19
+ const score = Object.values(contributions).reduce((sum, value) => sum + value, 0) - penalty;
20
+ return { score, contributions, enforcement_penalty: penalty, scoring_policy_version: SCORING_POLICY_VERSION };
21
+ }
@@ -0,0 +1,154 @@
1
+ import { CONTRACT_VERSION, SCORING_POLICY_VERSION, validateEvaluation, validateSearchInput } from "./contracts.js";
2
+ import { candidateLegality, candidatesFromInput, generatedCandidatesFromResponse } from "./candidate-policy.js";
3
+ import { scoreEvaluation } from "./scoring.js";
4
+ import { generatorRequestFromInput } from "./state-adapter.js";
5
+
6
+ function generatorFailureCode(error) {
7
+ if (error?.code === "GENERATOR_MUTATION_DETECTED") return "generator_mutation_detected";
8
+ if (error?.code === "GENERATOR_TIMEOUT") return "generator_timeout";
9
+ if (error?.code === "GENERATOR_AUTHENTICATION_FAILED") return "generator_authentication_failed";
10
+ if (error?.code === "ENOENT") return "generator_unavailable";
11
+ if (/auth/i.test(error?.message ?? "")) return "generator_authentication_failed";
12
+ if (/context|disallowed/i.test(error?.message ?? "")) return "generator_context_rejected";
13
+ if (/budget/i.test(error?.message ?? "")) return "generator_budget_exceeded";
14
+ return "generator_schema_invalid";
15
+ }
16
+
17
+ export async function runDeliveryPathSearch(inputValue, evaluator, options = {}) {
18
+ const input = validateSearchInput(inputValue);
19
+ const startedAt = Date.now();
20
+ const baseline = [...(options.candidates ?? candidatesFromInput(input))];
21
+ const queue = [...baseline];
22
+ const rejected = [];
23
+ const evaluated = [];
24
+ let evaluations = 0;
25
+ let costUnits = 0;
26
+ let lastLeaderId = null;
27
+ let stableComparisons = 0;
28
+ let stoppingReason = "candidate_queue_exhausted";
29
+ const generation = {
30
+ status: input.generation?.enabled ? "failed" : "disabled",
31
+ adapter: options.generator?.metadata ?? null,
32
+ budgets: input.generation ?? null,
33
+ returned: 0,
34
+ accepted: 0,
35
+ rejected: [],
36
+ cost_units: 0,
37
+ duration_ms: 0,
38
+ failure_code: null,
39
+ };
40
+
41
+ if (input.generation?.enabled) {
42
+ if (!options.generator) {
43
+ generation.failure_code = "generator_unavailable";
44
+ } else {
45
+ const generationStartedAt = Date.now();
46
+ try {
47
+ const response = await options.generator.generate(generatorRequestFromInput(input));
48
+ const elapsed = Date.now() - generationStartedAt;
49
+ generation.returned = response.proposals.length;
50
+ generation.cost_units = response.cost_units;
51
+ costUnits += response.cost_units;
52
+ if (elapsed > input.generation.max_duration_ms) {
53
+ const error = new Error("generator duration budget exceeded");
54
+ error.code = "GENERATOR_TIMEOUT";
55
+ throw error;
56
+ }
57
+ if (response.cost_units > input.generation.max_cost_units || response.proposals.length > input.generation.max_proposals) {
58
+ const error = new Error("generator response exceeds configured budget");
59
+ error.code = "GENERATOR_BUDGET_EXCEEDED";
60
+ throw error;
61
+ }
62
+ const filtered = generatedCandidatesFromResponse(response, input, baseline);
63
+ generation.accepted = filtered.accepted.length;
64
+ generation.rejected = filtered.rejected;
65
+ queue.push(...filtered.accepted.slice(0, input.generation.max_proposals));
66
+ generation.status = filtered.accepted.length === response.proposals.length ? "success" : "partial";
67
+ if (!filtered.accepted.length) generation.failure_code = "generator_no_diverse_proposals";
68
+ } catch (error) {
69
+ generation.failure_code = generatorFailureCode(error);
70
+ if (generation.failure_code === "generator_mutation_detected") throw error;
71
+ } finally {
72
+ generation.duration_ms = Date.now() - generationStartedAt;
73
+ }
74
+ }
75
+ }
76
+
77
+ while (queue.length > 0) {
78
+ if (evaluations >= input.budgets.max_evaluations) { stoppingReason = "evaluation_budget_exhausted"; break; }
79
+ if (costUnits >= input.budgets.max_cost_units) { stoppingReason = "cost_budget_exhausted"; break; }
80
+ if (Date.now() - startedAt >= input.budgets.max_duration_ms) { stoppingReason = "duration_budget_exhausted"; break; }
81
+ const candidate = queue.shift();
82
+ const legality = candidateLegality(candidate, input);
83
+ if (!legality.legal) {
84
+ rejected.push({ candidate_id: candidate.id, action: candidate.action, reason: legality.reason });
85
+ continue;
86
+ }
87
+
88
+ try {
89
+ const evaluation = validateEvaluation(await evaluator.evaluate(input, candidate), candidate.id);
90
+ evaluations += 1;
91
+ costUnits += evaluation.cost;
92
+ const scored = scoreEvaluation(evaluation, input.enforcement.level);
93
+ evaluated.push({ candidate, evaluation, ...scored });
94
+ const currentLeader = [...evaluated].sort((a, b) => b.score - a.score || a.candidate.id.localeCompare(b.candidate.id))[0];
95
+ if (currentLeader?.candidate.id === lastLeaderId) stableComparisons += 1;
96
+ else stableComparisons = 1;
97
+ lastLeaderId = currentLeader?.candidate.id ?? null;
98
+ if (evaluated.length > 1 && stableComparisons >= input.budgets.stability_window) {
99
+ stoppingReason = "stable_leader";
100
+ break;
101
+ }
102
+ if ((candidate.depth ?? 0) + 1 < input.budgets.max_depth) {
103
+ for (const [index, action] of evaluation.child_actions.slice(0, input.budgets.max_candidates).entries()) {
104
+ queue.push({
105
+ id: `${candidate.id}.${index + 1}`,
106
+ parent_id: candidate.id,
107
+ depth: (candidate.depth ?? 0) + 1,
108
+ action,
109
+ source: "expanded",
110
+ expected_evidence: [],
111
+ tests: [],
112
+ assumptions: evaluation.assumptions,
113
+ });
114
+ }
115
+ }
116
+ } catch (error) {
117
+ rejected.push({ candidate_id: candidate.id, action: candidate.action, reason: `invalid_evaluation: ${error.message}` });
118
+ }
119
+ }
120
+
121
+ evaluated.sort((a, b) => b.score - a.score || a.candidate.id.localeCompare(b.candidate.id));
122
+ const leader = evaluated[0];
123
+ if (!leader) stoppingReason = rejected.length ? "no_safe_candidate" : stoppingReason;
124
+ return {
125
+ contract_version: CONTRACT_VERSION,
126
+ scoring_policy_version: SCORING_POLICY_VERSION,
127
+ scope_key: input.scope_key,
128
+ current_gate: input.current_gate,
129
+ status: leader ? "recommendation" : "no_safe_recommendation",
130
+ recommendation: leader ? {
131
+ candidate_id: leader.candidate.id,
132
+ action: leader.candidate.action,
133
+ score: leader.score,
134
+ rationale: leader.evaluation.rationale,
135
+ expected_evidence: leader.candidate.expected_evidence,
136
+ tests: leader.candidate.tests,
137
+ risks: leader.evaluation.risks,
138
+ assumptions: leader.evaluation.assumptions,
139
+ } : null,
140
+ alternatives: evaluated.slice(1).map((item) => ({
141
+ candidate_id: item.candidate.id,
142
+ action: item.candidate.action,
143
+ score: item.score,
144
+ rejection_reason: `ranked_below_${leader?.candidate.id ?? "safety_threshold"}`,
145
+ })),
146
+ rejected,
147
+ enforcement: input.enforcement,
148
+ evaluator: evaluator.metadata ?? { name: evaluator.name ?? "unknown" },
149
+ generation,
150
+ budgets: { configured: input.budgets, evaluations, cost_units: costUnits, stable_comparisons: stableComparisons, duration_ms: Date.now() - startedAt },
151
+ stopping_reason: stoppingReason,
152
+ next_gate_action: "Run canonical AGDF gate-check; search does not grant permission.",
153
+ };
154
+ }