afyx-engineering-kit 0.0.0-stage → 0.1.0-alpha.4

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 (208) hide show
  1. package/.afyx-source-revision +1 -0
  2. package/LICENSE +21 -0
  3. package/README.md +377 -2
  4. package/SECURITY.md +74 -0
  5. package/afyx-context/LICENSE +21 -0
  6. package/afyx-context/README.md +155 -0
  7. package/afyx-context/afyx-context.json +30 -0
  8. package/afyx-context/contracts/integration-v1.schema.json +34 -0
  9. package/afyx-context/package-lock.json +53 -0
  10. package/afyx-context/package.json +34 -0
  11. package/afyx-context/scripts/benchmark.mjs +39 -0
  12. package/afyx-context/scripts/build.mjs +15 -0
  13. package/afyx-context/scripts/comparative-benchmark.mjs +342 -0
  14. package/afyx-context/scripts/comparative-worker.mjs +74 -0
  15. package/afyx-context/scripts/graph-integration-e2e.mjs +188 -0
  16. package/afyx-context/scripts/integrated-dogfood.mjs +309 -0
  17. package/afyx-context/src/budget.js +166 -0
  18. package/afyx-context/src/cli.js +110 -0
  19. package/afyx-context/src/coordination.js +343 -0
  20. package/afyx-context/src/engine.js +198 -0
  21. package/afyx-context/src/errors.js +14 -0
  22. package/afyx-context/src/graph-integration-worker.js +70 -0
  23. package/afyx-context/src/graph-integration.js +373 -0
  24. package/afyx-context/src/graph-mcp-bridge.js +103 -0
  25. package/afyx-context/src/index.js +25 -0
  26. package/afyx-context/src/integrations.js +87 -0
  27. package/afyx-context/src/memory.js +255 -0
  28. package/afyx-context/src/storage.js +364 -0
  29. package/afyx-context/test-fixtures/coordination-worker.mjs +52 -0
  30. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__init__.py +1 -0
  31. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__manifest__.py +4 -0
  32. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/__init__.py +1 -0
  33. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/sale_order.py +5 -0
  34. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__init__.py +1 -0
  35. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__manifest__.py +10 -0
  36. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/__init__.py +2 -0
  37. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order.py +20 -0
  38. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order_audit.py +11 -0
  39. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/security/ir.model.access.csv +2 -0
  40. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/views/sale_order_views.xml +14 -0
  41. package/afyx-forge/LICENSE +55 -0
  42. package/afyx-forge/README.md +126 -0
  43. package/afyx-forge/afyx-forge.json +28 -0
  44. package/afyx-forge/bin/afyx-forge +4 -0
  45. package/afyx-forge/bin/afyx-forge.cmd +3 -0
  46. package/afyx-forge/bin/afyx-forge.js +16 -0
  47. package/afyx-forge/contracts/forge-plan-v1.schema.json +172 -0
  48. package/afyx-forge/package.json +26 -0
  49. package/afyx-forge/src/classifier.js +190 -0
  50. package/afyx-forge/src/cli.js +111 -0
  51. package/afyx-forge/src/doctor.js +105 -0
  52. package/afyx-forge/src/guidance.js +120 -0
  53. package/afyx-forge/src/index.js +273 -0
  54. package/afyx-forge/src/planning.js +107 -0
  55. package/afyx-forge/src/policy.js +109 -0
  56. package/afyx-forge/src/workflow-refiner.js +151 -0
  57. package/afyx-graph/afyx-graph.json +20 -0
  58. package/afyx-graph/engine/LICENSE +21 -0
  59. package/afyx-graph/engine/README.md +104 -0
  60. package/afyx-graph/engine/release/RELEASE-MANIFEST.json +21 -0
  61. package/afyx-graph/engine/release/SHA256SUMS +2 -0
  62. package/afyx-graph/engine/release/afyx-graph-linux-x64.tar.gz +0 -0
  63. package/afyx-graph/engine/release/afyx-graph-win32-x64.zip +0 -0
  64. package/afyx-graph/engine/scripts/distribution-contract.mjs +212 -0
  65. package/afyx-graph/engine/scripts/distribution-product.json +33 -0
  66. package/bin/afyx-engineering-kit.mjs +61 -0
  67. package/install.ps1 +1053 -0
  68. package/install.sh +617 -0
  69. package/package.json +66 -4
  70. package/scripts/afyx-capability-orchestrator.mjs +752 -0
  71. package/scripts/afyx-claude-integration.mjs +547 -0
  72. package/scripts/afyx-context-artifact.mjs +105 -0
  73. package/scripts/afyx-credential-broker.mjs +75 -0
  74. package/scripts/afyx-doctor.ps1 +152 -0
  75. package/scripts/afyx-doctor.sh +146 -0
  76. package/scripts/afyx-forge-artifact.mjs +183 -0
  77. package/scripts/afyx-global-routing-policy.md +12 -0
  78. package/scripts/afyx-global-routing.mjs +168 -0
  79. package/scripts/afyx-graph-artifact.mjs +178 -0
  80. package/scripts/afyx-host-adapters.mjs +543 -0
  81. package/scripts/afyx-host-bridge-lifecycle.mjs +174 -0
  82. package/scripts/afyx-host-bridge.mjs +288 -0
  83. package/scripts/afyx-integration-contracts.mjs +825 -0
  84. package/scripts/afyx-mcp-integration.mjs +528 -0
  85. package/scripts/afyx-modular-integration.mjs +361 -0
  86. package/scripts/afyx-modular-runtime.mjs +451 -0
  87. package/scripts/afyx-native-skill-host.mjs +124 -0
  88. package/scripts/afyx-npm-installer.mjs +486 -0
  89. package/scripts/afyx-project.ps1 +205 -0
  90. package/scripts/afyx-project.sh +207 -0
  91. package/scripts/afyx-provider-backup.mjs +1206 -0
  92. package/scripts/afyx-provider-integration.mjs +724 -0
  93. package/scripts/afyx-provider-inventory.mjs +147 -0
  94. package/scripts/afyx-security-auditor.mjs +224 -0
  95. package/scripts/afyx-skill-engineering.mjs +354 -0
  96. package/scripts/afyx-tool-family-routing.mjs +64 -0
  97. package/scripts/afyx-universal-runtime.mjs +530 -0
  98. package/scripts/alpha_acceptance_preflight.py +240 -0
  99. package/scripts/benchmark-graph-memory.mjs +96 -0
  100. package/scripts/benchmark_capability_orchestrator.mjs +64 -0
  101. package/scripts/build-windows-installer.ps1 +259 -0
  102. package/scripts/build_forge_synthetic_image.py +328 -0
  103. package/scripts/check-reference-staleness.py +71 -0
  104. package/scripts/components.json +254 -0
  105. package/scripts/contracts/afyx-capability-request-v1.schema.json +189 -0
  106. package/scripts/contracts/afyx-capability-result-v1.schema.json +32 -0
  107. package/scripts/dogfood_engineering_comparison.mjs +303 -0
  108. package/scripts/engineering-assurance.json +28 -0
  109. package/scripts/install-afyx-context.ps1 +142 -0
  110. package/scripts/install-afyx-context.sh +126 -0
  111. package/scripts/install-afyx-forge.ps1 +265 -0
  112. package/scripts/install-afyx-forge.sh +273 -0
  113. package/scripts/install-afyx-graph.ps1 +571 -0
  114. package/scripts/install-afyx-graph.sh +438 -0
  115. package/scripts/install-codex-usage-tracker.ps1 +172 -0
  116. package/scripts/lib/AfyxComponents.psm1 +399 -0
  117. package/scripts/lib/AfyxSkillLifecycle.psm1 +289 -0
  118. package/scripts/lib/AfyxTerminal.psm1 +838 -0
  119. package/scripts/lib/afyx-components.sh +256 -0
  120. package/scripts/lib/afyx-skill-lifecycle.sh +271 -0
  121. package/scripts/link-global-dev.ps1 +193 -0
  122. package/scripts/link-global-dev.sh +130 -0
  123. package/scripts/phase8-paired-evidence.mjs +195 -0
  124. package/scripts/phase8-representative-workload.mjs +771 -0
  125. package/scripts/phase8-session-recorder.mjs +157 -0
  126. package/scripts/phase8_event_ledger.py +248 -0
  127. package/scripts/phase8_evidence_discovery.py +189 -0
  128. package/scripts/prepare-g6-package.mjs +349 -0
  129. package/scripts/resolve-git-release-artifacts.mjs +321 -0
  130. package/scripts/stage-npm-release.mjs +94 -0
  131. package/scripts/validate-afyx-graph.py +203 -0
  132. package/scripts/validate-components.py +194 -0
  133. package/scripts/validate-engineering-assurance.py +281 -0
  134. package/scripts/verify-graph-archive.mjs +64 -0
  135. package/skills/afyx-context/SKILL.md +26 -0
  136. package/skills/afyx-engineering-expert/README.md +42 -0
  137. package/skills/afyx-engineering-expert/SKILL.md +70 -0
  138. package/skills/afyx-engineering-expert/assets/result-template.md +15 -0
  139. package/skills/afyx-engineering-expert/references/ai-ml-engineer.md +17 -0
  140. package/skills/afyx-engineering-expert/references/business-analyst.md +17 -0
  141. package/skills/afyx-engineering-expert/references/clean-code-engineer.md +26 -0
  142. package/skills/afyx-engineering-expert/references/code-reviewer.md +24 -0
  143. package/skills/afyx-engineering-expert/references/cybersecurity-devsecops.md +17 -0
  144. package/skills/afyx-engineering-expert/references/data-analyst-bi.md +24 -0
  145. package/skills/afyx-engineering-expert/references/data-engineer.md +24 -0
  146. package/skills/afyx-engineering-expert/references/database-administrator.md +17 -0
  147. package/skills/afyx-engineering-expert/references/debugging-specialist.md +24 -0
  148. package/skills/afyx-engineering-expert/references/embedded-iot-engineer.md +24 -0
  149. package/skills/afyx-engineering-expert/references/erp-technical-specialist.md +17 -0
  150. package/skills/afyx-engineering-expert/references/hardware-diagnostics-auditor.md +24 -0
  151. package/skills/afyx-engineering-expert/references/hardware-electronics-engineer.md +24 -0
  152. package/skills/afyx-engineering-expert/references/integration-engineer.md +24 -0
  153. package/skills/afyx-engineering-expert/references/legacy-modernization-engineer.md +24 -0
  154. package/skills/afyx-engineering-expert/references/llmops-prompt-engineer.md +24 -0
  155. package/skills/afyx-engineering-expert/references/network-engineer.md +24 -0
  156. package/skills/afyx-engineering-expert/references/performance-benchmark-engineer.md +24 -0
  157. package/skills/afyx-engineering-expert/references/platform-engineer.md +24 -0
  158. package/skills/afyx-engineering-expert/references/product-manager.md +17 -0
  159. package/skills/afyx-engineering-expert/references/qa-engineer.md +17 -0
  160. package/skills/afyx-engineering-expert/references/site-reliability-engineer.md +17 -0
  161. package/skills/afyx-engineering-expert/references/software-engineer.md +17 -0
  162. package/skills/afyx-engineering-expert/references/solutions-architect.md +17 -0
  163. package/skills/afyx-engineering-expert/references/specialists-index.md +33 -0
  164. package/skills/afyx-engineering-expert/references/subject-matter-expert.md +17 -0
  165. package/skills/afyx-engineering-expert/references/system-analyst.md +17 -0
  166. package/skills/afyx-engineering-expert/references/technical-project-manager.md +24 -0
  167. package/skills/afyx-engineering-expert/references/technical-writer.md +24 -0
  168. package/skills/afyx-engineering-expert/references/ui-ux-designer.md +17 -0
  169. package/skills/afyx-engineering-expert/workflows/ai-data-erp.md +20 -0
  170. package/skills/afyx-engineering-expert/workflows/debugging.md +10 -0
  171. package/skills/afyx-engineering-expert/workflows/discovery-design.md +11 -0
  172. package/skills/afyx-engineering-expert/workflows/implementation.md +12 -0
  173. package/skills/afyx-engineering-expert/workflows/incident-reliability.md +12 -0
  174. package/skills/afyx-engineering-expert/workflows/review-audit.md +13 -0
  175. package/skills/afyx-forge/SKILL.md +43 -0
  176. package/skills/afyx-forge/references/adaptive-policy.md +19 -0
  177. package/skills/efficient-coding/SKILL.md +33 -0
  178. package/skills/efficient-coding/references/investigation.md +27 -0
  179. package/skills/efficient-coding/references/token-efficiency.md +25 -0
  180. package/skills/efficient-coding/references/tool-routing.md +13 -0
  181. package/skills/odoo-engineering/SKILL.md +33 -0
  182. package/skills/odoo-engineering/references/common.md +9 -0
  183. package/skills/odoo-engineering/references/odoo-10.md +32 -0
  184. package/skills/odoo-engineering/references/odoo-11.md +26 -0
  185. package/skills/odoo-engineering/references/odoo-12.md +31 -0
  186. package/skills/odoo-engineering/references/odoo-13.md +27 -0
  187. package/skills/odoo-engineering/references/odoo-14.md +31 -0
  188. package/skills/odoo-engineering/references/odoo-15.md +34 -0
  189. package/skills/odoo-engineering/references/odoo-16.md +37 -0
  190. package/skills/odoo-engineering/references/odoo-17.md +37 -0
  191. package/skills/odoo-engineering/references/odoo-18.md +48 -0
  192. package/skills/odoo-engineering/references/odoo-19.md +43 -0
  193. package/skills/odoo-engineering/references/odoo-20.md +39 -0
  194. package/skills/odoo-engineering/references/reference-schema.md +16 -0
  195. package/skills/odoo-engineering/references/version-detection.md +13 -0
  196. package/tools/codex-usage/CodexUsage.psm1 +496 -0
  197. package/tools/codex-usage/codex-usage-doctor.ps1 +150 -0
  198. package/tools/codex-usage/codex-usage-pricing.json +25 -0
  199. package/tools/codex-usage/codex-usage-stop.ps1 +167 -0
  200. package/tools/codex-usage/codex-usage-watch.ps1 +250 -0
  201. package/tools/codex-usage/vscode-user-task.json +31 -0
  202. package/tools/windows-setup/SetupBootstrapper.cs +258 -0
  203. package/uninstall.ps1 +189 -0
  204. package/uninstall.sh +167 -0
  205. package/update.ps1 +95 -0
  206. package/update.sh +67 -0
  207. package/verify.ps1 +411 -0
  208. package/verify.sh +265 -0
@@ -0,0 +1,825 @@
1
+ /** Versioned provider-capability and provider-neutral engineering contracts. */
2
+
3
+ import path from 'node:path';
4
+
5
+ export const PROVIDER_CAPABILITY_CONTRACT = 'ProviderCapability/v1';
6
+ export const PROVIDER_NEGOTIATION_CONTRACT = 'ProviderCapabilityNegotiation/v1';
7
+ export const ENGINEERING_TASK_CONTRACT = 'AfyxEngineeringTask/v1';
8
+ export const ENGINEERING_RESULT_CONTRACT = 'AfyxEngineeringResult/v1';
9
+ export const AGENT_GUARDRAILS_CONTRACT = 'AfyxAgentGuardrails/v1';
10
+
11
+ const ACCEPTANCE_STATES = new Set(['PASS', 'FAIL', 'BLOCKED', 'NOT_RUN']);
12
+ const COMPLETENESS_STATES = new Set(['COMPLETE', 'PARTIAL', 'UNKNOWN']);
13
+ const RESULT_STATES = new Set(['SUCCEEDED', 'FAILED', 'BLOCKED', 'UNSUPPORTED', 'NOT_RUN']);
14
+ const SEVERITIES = new Set(['INFO', 'WARNING', 'ERROR']);
15
+ const VERIFICATION_LEVELS = new Set(['DECLARED', 'RUNTIME']);
16
+ const INTEGRATION_COMPONENTS = new Set([
17
+ 'afyx-graph',
18
+ 'afyx-context',
19
+ 'afyx-engineering-expert',
20
+ 'odoo-engineering',
21
+ 'efficient-coding',
22
+ 'codex-usage-tracking',
23
+ 'afyx-forge',
24
+ ]);
25
+ const KNOWN_CAPABILITIES = Object.freeze([
26
+ 'configuration', 'hooks', 'instructions', 'lifecycle', 'mcp', 'provider-routing', 'skills',
27
+ 'scope:cli-global', 'scope:global', 'scope:ide-global', 'scope:workspace',
28
+ 'surface:cli', 'surface:ide',
29
+ ]);
30
+
31
+ export const EVIDENCE_CLASSES = Object.freeze([
32
+ 'DIRECT_EXECUTION',
33
+ 'VERIFIED_SOURCE',
34
+ 'GRAPH_INDEX',
35
+ 'EXTERNAL_DOCS',
36
+ 'INFERENCE',
37
+ 'UNAVAILABLE',
38
+ ]);
39
+ export const EXECUTION_TYPES = Object.freeze(['REAL', 'MOCK', 'SYNTHETIC', 'STATIC', 'NONE']);
40
+ export const FRESHNESS_STATES = Object.freeze(['FRESH', 'STALE', 'UNKNOWN']);
41
+ export const CONTROL_MODES = Object.freeze(['MECHANICAL', 'ADVISORY', 'HYBRID']);
42
+ export const AUTHORIZATION_LEVELS = Object.freeze([
43
+ 'READ_ONLY',
44
+ 'WORKSPACE_WRITE',
45
+ 'DESTRUCTIVE_APPROVED',
46
+ 'ADMIN',
47
+ ]);
48
+
49
+ export class ContractValidationError extends Error {
50
+ constructor(path, message) {
51
+ super(`${path}: ${message}`);
52
+ this.name = 'ContractValidationError';
53
+ this.code = 'INVALID_CONTRACT';
54
+ this.path = path;
55
+ }
56
+ }
57
+
58
+ function isObject(value) {
59
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
60
+ && (Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null);
61
+ }
62
+
63
+ function object(value, path, allowed) {
64
+ if (!isObject(value)) throw new ContractValidationError(path, 'must be an object');
65
+ const unknown = Object.keys(value).filter((key) => !allowed.includes(key));
66
+ if (unknown.length) throw new ContractValidationError(path, `contains unknown field ${unknown.sort()[0]}`);
67
+ return value;
68
+ }
69
+
70
+ function text(value, path, max = 512) {
71
+ if (typeof value !== 'string' || value.length === 0 || /[\u0000-\u001f\u007f]/u.test(value)) {
72
+ throw new ContractValidationError(path, 'must be a non-empty printable string');
73
+ }
74
+ if (Buffer.byteLength(value, 'utf8') > max) throw new ContractValidationError(path, `exceeds ${max} bytes`);
75
+ return value;
76
+ }
77
+
78
+ function optionalText(value, path, max = 512) {
79
+ return value === undefined || value === null ? null : text(value, path, max);
80
+ }
81
+
82
+ function choice(value, path, allowed) {
83
+ if (!allowed.has(value)) throw new ContractValidationError(path, `has unsupported value ${String(value)}`);
84
+ return value;
85
+ }
86
+
87
+ function boolean(value, path, fallback = undefined) {
88
+ if (value === undefined && fallback !== undefined) return fallback;
89
+ if (typeof value !== 'boolean') throw new ContractValidationError(path, 'must be boolean');
90
+ return value;
91
+ }
92
+
93
+ function list(value, path, maximum = 256) {
94
+ if (!Array.isArray(value)) throw new ContractValidationError(path, 'must be an array');
95
+ if (value.length > maximum) throw new ContractValidationError(path, `exceeds ${maximum} items`);
96
+ return value;
97
+ }
98
+
99
+ function split(value) {
100
+ return typeof value === 'string' ? value.split(';').filter(Boolean) : [];
101
+ }
102
+
103
+ function freeze(value) {
104
+ if (value && typeof value === 'object' && !Object.isFrozen(value)) {
105
+ Object.freeze(value);
106
+ for (const child of Object.values(value)) freeze(child);
107
+ }
108
+ return value;
109
+ }
110
+
111
+ function stableValue(value, path = '$') {
112
+ if (value === null || typeof value === 'string' || typeof value === 'boolean') return value;
113
+ if (typeof value === 'number' && Number.isFinite(value)) return value;
114
+ if (Array.isArray(value)) return value.map((item, index) => stableValue(item, `${path}[${index}]`));
115
+ if (isObject(value)) {
116
+ return Object.fromEntries(Object.keys(value).sort().map((key) => [key, stableValue(value[key], `${path}.${key}`)]));
117
+ }
118
+ throw new ContractValidationError(path, 'must contain only JSON-compatible values');
119
+ }
120
+
121
+ export function serializeContract(value) {
122
+ return JSON.stringify(stableValue(value));
123
+ }
124
+
125
+ function malformedDiscovery(definition, diagnostic) {
126
+ return freeze({
127
+ contract: PROVIDER_CAPABILITY_CONTRACT,
128
+ provider: { id: String(definition?.provider || 'unknown'), name: String(definition?.name || 'Unknown') },
129
+ status: 'BLOCKED',
130
+ host: { commands: [], detected: null, command: null, version: null, status: 'BLOCKED', evidence: 'NONE', runtimeVerified: false },
131
+ surfaces: [],
132
+ scopes: { lifecycle: [], mcp: [], skills: [] },
133
+ ownership: { class: 'USER', configurationPolicy: 'observe-only' },
134
+ capabilities: [],
135
+ acceptance: 'NOT_RUN',
136
+ mutationAuthorized: false,
137
+ diagnostics: [{ code: diagnostic, severity: 'ERROR', message: 'Capability metadata failed validation.' }],
138
+ });
139
+ }
140
+
141
+ function hostObservation(value) {
142
+ if (value === undefined) return { detected: null, command: null, version: null, evidence: 'NONE' };
143
+ const host = object(value, 'host', ['detected', 'command', 'version', 'evidence']);
144
+ const detected = host.detected === undefined ? null : boolean(host.detected, 'host.detected');
145
+ const command = optionalText(host.command, 'host.command', 256);
146
+ const version = optionalText(host.version, 'host.version', 256);
147
+ const evidence = host.evidence === undefined ? 'NONE' : choice(host.evidence, 'host.evidence', new Set(['NONE', 'CALLER', 'FILESYSTEM']));
148
+ if (detected === true && command === null) throw new ContractValidationError('host.command', 'is required when detected is true');
149
+ return { detected, command, version, evidence };
150
+ }
151
+
152
+ function capabilityRecord(id, declared, host) {
153
+ if (id === 'surface:cli' && declared) {
154
+ if (host.detected === false) return { id, declared: true, status: 'BLOCKED', runtimeVerified: false, evidence: host.evidence };
155
+ if (host.detected === null) return { id, declared: true, status: 'UNVERIFIED', runtimeVerified: false, evidence: 'DECLARED' };
156
+ return { id, declared: true, status: 'UNVERIFIED', runtimeVerified: false, evidence: host.evidence };
157
+ }
158
+ if (id === 'surface:ide' && declared) {
159
+ return { id, declared: true, status: 'UNVERIFIED', runtimeVerified: false, evidence: 'DECLARED' };
160
+ }
161
+ return declared
162
+ ? { id, declared: true, status: 'SUPPORTED', runtimeVerified: false, evidence: 'DECLARED' }
163
+ : { id, declared: false, status: 'UNSUPPORTED', runtimeVerified: false, evidence: 'REGISTRY' };
164
+ }
165
+
166
+ export function discoverProviderCapabilities(definition, adapterCapabilities, options = {}) {
167
+ try {
168
+ object(options, 'options', ['host']);
169
+ const provider = text(definition?.provider, 'provider.provider', 128);
170
+ const name = text(definition?.name, 'provider.name', 256);
171
+ const ownershipClass = choice(definition?.ownership_class, 'provider.ownership_class', new Set(['AFYX', 'EXTERNAL', 'USER']));
172
+ const configurationPolicy = choice(
173
+ definition?.configuration_policy,
174
+ 'provider.configuration_policy',
175
+ new Set(['merge-afyx-owned-entries-only', 'observe-only']),
176
+ );
177
+ const commands = split(definition?.host_commands).map((item, index) => text(item, `provider.host_commands[${index}]`, 256));
178
+ const surfaces = split(definition?.surfaces).map((item, index) => text(item, `provider.surfaces[${index}]`, 128));
179
+ const lifecycleScopes = (adapterCapabilities?.scopes || []).map((item, index) => text(item, `adapter.scopes[${index}]`, 128));
180
+ const mcpScopes = split(definition?.mcp_scopes).map((item, index) => text(item, `provider.mcp_scopes[${index}]`, 128));
181
+ const skillScopes = split(definition?.skill_scopes).map((item, index) => text(item, `provider.skill_scopes[${index}]`, 128));
182
+ const instructionScopes = split(definition?.instruction_scopes).map((item, index) => text(item, `provider.instruction_scopes[${index}]`, 128));
183
+ const host = hostObservation(options.host);
184
+ const declared = new Set([
185
+ ...split(definition?.capabilities),
186
+ ...surfaces.map((item) => `surface:${item}`),
187
+ ...[...new Set([...lifecycleScopes, ...mcpScopes, ...skillScopes, ...instructionScopes])].map((item) => `scope:${item}`),
188
+ 'configuration',
189
+ 'lifecycle',
190
+ ]);
191
+ const capabilities = KNOWN_CAPABILITIES.map((id) => capabilityRecord(id, declared.has(id), host));
192
+ const hostStatus = host.detected === false ? 'BLOCKED' : 'UNVERIFIED';
193
+ return freeze({
194
+ contract: PROVIDER_CAPABILITY_CONTRACT,
195
+ provider: { id: provider, name },
196
+ status: hostStatus,
197
+ host: { commands, ...host, status: hostStatus, runtimeVerified: false },
198
+ surfaces,
199
+ scopes: { lifecycle: lifecycleScopes, mcp: mcpScopes, skills: skillScopes, instructions: instructionScopes },
200
+ ownership: { class: ownershipClass, configurationPolicy },
201
+ capabilities,
202
+ acceptance: 'NOT_RUN',
203
+ mutationAuthorized: false,
204
+ diagnostics: [],
205
+ });
206
+ } catch (error) {
207
+ return malformedDiscovery(definition, error instanceof ContractValidationError ? 'MALFORMED_CAPABILITY_METADATA' : 'CAPABILITY_DISCOVERY_FAILED');
208
+ }
209
+ }
210
+
211
+ export function negotiateProviderCapabilities(discovery, requirements) {
212
+ const blocked = (code, message) => freeze({
213
+ contract: PROVIDER_NEGOTIATION_CONTRACT,
214
+ provider: typeof discovery?.provider?.id === 'string' ? discovery.provider.id : 'unknown',
215
+ status: 'BLOCKED',
216
+ requirements: [],
217
+ mutationAuthorized: false,
218
+ diagnostics: [{ code, severity: 'ERROR', message }],
219
+ });
220
+ try {
221
+ if (!isObject(discovery) || discovery.contract !== PROVIDER_CAPABILITY_CONTRACT || !Array.isArray(discovery.capabilities)) {
222
+ return blocked('MALFORMED_DISCOVERY', 'Capability discovery is invalid.');
223
+ }
224
+ if (discovery.status === 'BLOCKED') {
225
+ return blocked('DISCOVERY_BLOCKED', 'Capability discovery is blocked.');
226
+ }
227
+ const requested = list(requirements, 'requirements', 128).map((requirement, index) => {
228
+ const path = `requirements[${index}]`;
229
+ const item = object(requirement, path, ['capability', 'required', 'verification']);
230
+ return {
231
+ capability: text(item.capability, `${path}.capability`, 128),
232
+ required: boolean(item.required, `${path}.required`, true),
233
+ verification: item.verification === undefined ? 'DECLARED' : choice(item.verification, `${path}.verification`, VERIFICATION_LEVELS),
234
+ };
235
+ });
236
+ const available = new Map(discovery.capabilities.map((item) => [item.id, item]));
237
+ const evaluated = requested.map((requirement) => {
238
+ const capability = available.get(requirement.capability);
239
+ let status = 'BLOCKED';
240
+ let reason = capability ? '' : 'UNKNOWN_CAPABILITY';
241
+ if (capability) {
242
+ if (!capability.declared) status = 'UNSUPPORTED';
243
+ else if (requirement.verification === 'DECLARED') status = 'SUPPORTED';
244
+ else if (capability.runtimeVerified) status = 'SUPPORTED';
245
+ else if (capability.status === 'BLOCKED') status = 'BLOCKED';
246
+ else {
247
+ status = 'UNVERIFIED';
248
+ reason = 'RUNTIME_EVIDENCE_ABSENT';
249
+ }
250
+ }
251
+ return { ...requirement, status, ...(reason ? { reason } : {}) };
252
+ });
253
+ const required = evaluated.filter((item) => item.required);
254
+ const status = required.some((item) => item.status === 'BLOCKED') ? 'BLOCKED'
255
+ : required.some((item) => item.status === 'UNSUPPORTED') ? 'UNSUPPORTED'
256
+ : required.some((item) => item.status === 'UNVERIFIED') ? 'UNVERIFIED' : 'SUPPORTED';
257
+ return freeze({
258
+ contract: PROVIDER_NEGOTIATION_CONTRACT,
259
+ provider: discovery.provider.id,
260
+ status,
261
+ requirements: evaluated,
262
+ mutationAuthorized: false,
263
+ diagnostics: evaluated.filter((item) => item.reason).map((item) => ({ code: item.reason, severity: 'WARNING', message: `Capability ${item.capability} is not runtime-verified.` })),
264
+ });
265
+ } catch {
266
+ return blocked('MALFORMED_REQUIREMENTS', 'Capability requirements failed validation.');
267
+ }
268
+ }
269
+
270
+ function provenance(value, path) {
271
+ const item = object(value, path, ['source', 'reference', 'digest']);
272
+ return {
273
+ source: text(item.source, `${path}.source`, 256),
274
+ ...(item.reference === undefined ? {} : { reference: text(item.reference, `${path}.reference`, 32_767) }),
275
+ ...(item.digest === undefined ? {} : { digest: text(item.digest, `${path}.digest`, 256) }),
276
+ };
277
+ }
278
+
279
+ function capabilityRequirements(value, path) {
280
+ return list(value, path, 128).map((requirement, index) => {
281
+ const at = `${path}[${index}]`;
282
+ const item = object(requirement, at, ['capability', 'required', 'verification']);
283
+ return {
284
+ capability: text(item.capability, `${at}.capability`, 128),
285
+ required: boolean(item.required, `${at}.required`, true),
286
+ verification: item.verification === undefined ? 'DECLARED' : choice(item.verification, `${at}.verification`, VERIFICATION_LEVELS),
287
+ };
288
+ });
289
+ }
290
+
291
+ function integrations(value, path) {
292
+ if (value === undefined) return [];
293
+ return list(value, path, 8).map((integration, index) => {
294
+ const at = `${path}[${index}]`;
295
+ const item = object(integration, at, ['component', 'contract', 'status', 'reference']);
296
+ return {
297
+ component: choice(item.component, `${at}.component`, INTEGRATION_COMPONENTS),
298
+ contract: text(item.contract, `${at}.contract`, 256),
299
+ status: choice(item.status, `${at}.status`, new Set(['AVAILABLE', 'UNAVAILABLE', 'BLOCKED', 'NOT_RUN'])),
300
+ ...(item.reference === undefined ? {} : { reference: text(item.reference, `${at}.reference`, 32_767) }),
301
+ };
302
+ });
303
+ }
304
+
305
+ function policyDefinition(value, path) {
306
+ if (value === undefined || value === null) return null;
307
+ const item = object(value, path, [
308
+ 'contract',
309
+ 'controlMode',
310
+ 'allowedOperations',
311
+ 'allowedFiles',
312
+ 'excludedScope',
313
+ 'expectedOutcomes',
314
+ 'authorization',
315
+ ]);
316
+ const contract = item.contract === undefined
317
+ ? AGENT_GUARDRAILS_CONTRACT
318
+ : choice(item.contract, `${path}.contract`, new Set([AGENT_GUARDRAILS_CONTRACT]));
319
+ const controlMode = item.controlMode === undefined
320
+ ? 'HYBRID'
321
+ : choice(item.controlMode, `${path}.controlMode`, new Set(CONTROL_MODES));
322
+ const allowedOperations = item.allowedOperations === undefined
323
+ ? []
324
+ : list(item.allowedOperations, `${path}.allowedOperations`, 64).map((op, i) => text(op, `${path}.allowedOperations[${i}]`, 128));
325
+ const allowedFiles = item.allowedFiles === undefined
326
+ ? []
327
+ : list(item.allowedFiles, `${path}.allowedFiles`, 256).map((f, i) => text(f, `${path}.allowedFiles[${i}]`, 1024));
328
+ const excludedScope = item.excludedScope === undefined
329
+ ? []
330
+ : list(item.excludedScope, `${path}.excludedScope`, 256).map((f, i) => text(f, `${path}.excludedScope[${i}]`, 1024));
331
+ const expectedOutcomes = item.expectedOutcomes === undefined
332
+ ? []
333
+ : list(item.expectedOutcomes, `${path}.expectedOutcomes`, 64).map((o, i) => text(o, `${path}.expectedOutcomes[${i}]`, 1024));
334
+ const authorization = item.authorization === undefined
335
+ ? 'READ_ONLY'
336
+ : choice(item.authorization, `${path}.authorization`, new Set(AUTHORIZATION_LEVELS));
337
+ return {
338
+ contract,
339
+ controlMode,
340
+ allowedOperations,
341
+ allowedFiles,
342
+ excludedScope,
343
+ expectedOutcomes,
344
+ authorization,
345
+ };
346
+ }
347
+
348
+ export function createEngineeringTask(input) {
349
+ const root = object(input, 'taskContract', ['contract', 'task', 'workspace', 'context', 'requirements', 'integrations', 'policy']);
350
+ if (root.contract !== undefined && root.contract !== ENGINEERING_TASK_CONTRACT) {
351
+ throw new ContractValidationError('taskContract.contract', 'has an unsupported contract version');
352
+ }
353
+ const task = object(root.task, 'taskContract.task', ['id', 'operation', 'objective']);
354
+ const workspace = object(root.workspace, 'taskContract.workspace', ['id', 'root', 'revision']);
355
+ const context = object(root.context, 'taskContract.context', ['sources', 'completeness']);
356
+ const sources = list(context.sources, 'taskContract.context.sources', 256).map((source, index) => {
357
+ const at = `taskContract.context.sources[${index}]`;
358
+ const item = object(source, at, ['id', 'type', 'completeness', 'provenance']);
359
+ return {
360
+ id: text(item.id, `${at}.id`, 512),
361
+ type: text(item.type, `${at}.type`, 128),
362
+ completeness: choice(item.completeness, `${at}.completeness`, COMPLETENESS_STATES),
363
+ provenance: provenance(item.provenance, `${at}.provenance`),
364
+ };
365
+ });
366
+ const policy = root.policy === undefined ? null : policyDefinition(root.policy, 'taskContract.policy');
367
+ return freeze({
368
+ contract: ENGINEERING_TASK_CONTRACT,
369
+ task: {
370
+ id: text(task.id, 'taskContract.task.id', 512),
371
+ operation: text(task.operation, 'taskContract.task.operation', 256),
372
+ ...(task.objective === undefined ? {} : { objective: text(task.objective, 'taskContract.task.objective', 4096) }),
373
+ },
374
+ workspace: {
375
+ id: text(workspace.id, 'taskContract.workspace.id', 512),
376
+ ...(workspace.root === undefined ? {} : { root: text(workspace.root, 'taskContract.workspace.root', 32_767) }),
377
+ ...(workspace.revision === undefined ? {} : { revision: text(workspace.revision, 'taskContract.workspace.revision', 512) }),
378
+ },
379
+ context: { sources, completeness: choice(context.completeness, 'taskContract.context.completeness', COMPLETENESS_STATES) },
380
+ requirements: capabilityRequirements(root.requirements, 'taskContract.requirements'),
381
+ integrations: integrations(root.integrations, 'taskContract.integrations'),
382
+ ...(policy ? { policy } : {}),
383
+ });
384
+ }
385
+
386
+ export function validateEngineeringTask(value) {
387
+ if (!isObject(value) || value.contract !== ENGINEERING_TASK_CONTRACT) {
388
+ throw new ContractValidationError('taskContract.contract', 'must identify AfyxEngineeringTask/v1');
389
+ }
390
+ return createEngineeringTask(value);
391
+ }
392
+
393
+ export function createEngineeringResult(input) {
394
+ const root = object(input, 'resultContract', ['contract', 'taskId', 'status', 'output', 'evidence', 'diagnostics', 'integrations']);
395
+ if (root.contract !== undefined && root.contract !== ENGINEERING_RESULT_CONTRACT) {
396
+ throw new ContractValidationError('resultContract.contract', 'has an unsupported contract version');
397
+ }
398
+ const evidence = list(root.evidence, 'resultContract.evidence', 256).map((entry, index) => {
399
+ const at = `resultContract.evidence[${index}]`;
400
+ const item = object(entry, at, ['id', 'type', 'validation', 'provenance', 'evidenceClass', 'executionType', 'freshness']);
401
+ const validation = choice(item.validation, `${at}.validation`, ACCEPTANCE_STATES);
402
+ const evidenceClass = item.evidenceClass === undefined ? null : choice(item.evidenceClass, `${at}.evidenceClass`, new Set(EVIDENCE_CLASSES));
403
+ const executionType = item.executionType === undefined ? null : choice(item.executionType, `${at}.executionType`, new Set(EXECUTION_TYPES));
404
+ const freshness = item.freshness === undefined ? null : choice(item.freshness, `${at}.freshness`, new Set(FRESHNESS_STATES));
405
+
406
+ if (validation === 'PASS') {
407
+ if (evidenceClass === 'INFERENCE' || evidenceClass === 'UNAVAILABLE') {
408
+ throw new ContractValidationError(
409
+ `${at}.validation`,
410
+ `unsupported claim cannot receive verified PASS status (evidenceClass: ${evidenceClass})`
411
+ );
412
+ }
413
+ if (executionType === 'MOCK' && evidenceClass === 'DIRECT_EXECUTION') {
414
+ throw new ContractValidationError(
415
+ `${at}.validation`,
416
+ 'mock execution cannot receive verified direct execution PASS status'
417
+ );
418
+ }
419
+ }
420
+
421
+ return {
422
+ id: text(item.id, `${at}.id`, 512),
423
+ type: text(item.type, `${at}.type`, 128),
424
+ validation,
425
+ provenance: provenance(item.provenance, `${at}.provenance`),
426
+ ...(evidenceClass ? { evidenceClass } : {}),
427
+ ...(executionType ? { executionType } : {}),
428
+ ...(freshness ? { freshness } : {}),
429
+ };
430
+ });
431
+ const diagnostics = list(root.diagnostics, 'resultContract.diagnostics', 256).map((diagnostic, index) => {
432
+ const at = `resultContract.diagnostics[${index}]`;
433
+ const item = object(diagnostic, at, ['code', 'severity', 'message']);
434
+ return {
435
+ code: text(item.code, `${at}.code`, 128),
436
+ severity: choice(item.severity, `${at}.severity`, SEVERITIES),
437
+ message: text(item.message, `${at}.message`, 4096),
438
+ };
439
+ });
440
+ return freeze({
441
+ contract: ENGINEERING_RESULT_CONTRACT,
442
+ taskId: text(root.taskId, 'resultContract.taskId', 512),
443
+ status: choice(root.status, 'resultContract.status', RESULT_STATES),
444
+ ...(root.output === undefined ? {} : { output: stableValue(root.output, 'resultContract.output') }),
445
+ evidence,
446
+ diagnostics,
447
+ integrations: integrations(root.integrations, 'resultContract.integrations'),
448
+ });
449
+ }
450
+
451
+ export function validateEngineeringResult(value) {
452
+ if (!isObject(value) || value.contract !== ENGINEERING_RESULT_CONTRACT) {
453
+ throw new ContractValidationError('resultContract.contract', 'must identify AfyxEngineeringResult/v1');
454
+ }
455
+ return createEngineeringResult(value);
456
+ }
457
+
458
+ function isUnsafeAbsolutePath(rawPath) {
459
+ if (typeof rawPath !== 'string') return false;
460
+ const p = rawPath.trim();
461
+ if (p.startsWith('\\\\') || p.startsWith('//')) return true;
462
+ if (/^[a-zA-Z]:/u.test(p)) return true;
463
+ if (p.startsWith('/') || p.startsWith('\\')) return true;
464
+ return false;
465
+ }
466
+
467
+ function normalizePath(p) {
468
+ const replaced = String(p).replace(/\\/g, '/');
469
+ const posixNorm = path.posix.normalize(replaced);
470
+ return posixNorm.replace(/^\.\//, '');
471
+ }
472
+
473
+ function matchesScopePattern(filePath, pattern) {
474
+ const normFile = normalizePath(filePath);
475
+ const normPattern = normalizePath(pattern);
476
+ if (normPattern === '*' || normPattern === '**') return true;
477
+ if (normFile === normPattern) return true;
478
+ if (normPattern.endsWith('/**')) {
479
+ const prefix = normPattern.slice(0, -3);
480
+ return normFile === prefix || normFile.startsWith(prefix + '/');
481
+ }
482
+ if (normPattern.endsWith('/*')) {
483
+ const prefix = normPattern.slice(0, -2);
484
+ if (!normFile.startsWith(prefix + '/')) return false;
485
+ const rest = normFile.slice(prefix.length + 1);
486
+ return !rest.includes('/');
487
+ }
488
+ return normFile.startsWith(normPattern.endsWith('/') ? normPattern : normPattern + '/');
489
+ }
490
+
491
+ const READ_ONLY_OPERATIONS = new Set(['inspect', 'review', 'plan', 'verify', 'analyze', 'status', 'read']);
492
+
493
+ function isMutatingOperation(op) {
494
+ if (typeof op !== 'string' || !op.trim()) return false;
495
+ return !READ_ONLY_OPERATIONS.has(op.trim().toLowerCase());
496
+ }
497
+
498
+ export function validateTaskScope(task, requestedAction = {}) {
499
+ if (!isObject(task) || task.contract !== ENGINEERING_TASK_CONTRACT) {
500
+ throw new ContractValidationError('task', 'must be a valid AfyxEngineeringTask/v1');
501
+ }
502
+ const action = object(requestedAction, 'requestedAction', [
503
+ 'operation',
504
+ 'files',
505
+ 'revision',
506
+ 'mutation',
507
+ ]);
508
+
509
+ const violations = [];
510
+ const policy = task.policy;
511
+ const hasPolicy = Boolean(policy);
512
+ const isGuardedWrite = hasPolicy && policy.authorization !== 'READ_ONLY';
513
+
514
+ // 0. Field type validation & malformed context checks
515
+ if (action.operation !== undefined && action.operation !== null) {
516
+ if (typeof action.operation !== 'string' || !action.operation.trim()) {
517
+ violations.push({
518
+ code: 'MALFORMED_ACTION_FIELD',
519
+ message: "Field 'operation' must be a non-empty string.",
520
+ });
521
+ }
522
+ }
523
+
524
+ if (action.revision !== undefined && action.revision !== null) {
525
+ if (typeof action.revision !== 'string' || !action.revision.trim()) {
526
+ violations.push({
527
+ code: 'MALFORMED_ACTION_FIELD',
528
+ message: "Field 'revision' must be a non-empty string.",
529
+ });
530
+ }
531
+ }
532
+
533
+ if (action.mutation !== undefined && action.mutation !== null) {
534
+ if (typeof action.mutation !== 'boolean') {
535
+ violations.push({
536
+ code: 'MALFORMED_ACTION_FIELD',
537
+ message: "Field 'mutation' must be a boolean.",
538
+ });
539
+ }
540
+ }
541
+
542
+ if (action.files !== undefined && action.files !== null) {
543
+ if (!Array.isArray(action.files)) {
544
+ violations.push({
545
+ code: 'MALFORMED_ACTION_FIELD',
546
+ message: "Field 'files' must be an array of path strings.",
547
+ });
548
+ } else {
549
+ for (let i = 0; i < action.files.length; i++) {
550
+ const f = action.files[i];
551
+ if (typeof f !== 'string' || !f.trim()) {
552
+ violations.push({
553
+ code: 'INVALID_FILE_ENTRY',
554
+ message: `File entry at index ${i} must be a non-empty string.`,
555
+ });
556
+ }
557
+ }
558
+ }
559
+ }
560
+
561
+ // 1. Conservative mutation classification:
562
+ // Explicit mutation:false must not override evidence of an intended write
563
+ const hasMutatingOp = isMutatingOperation(action.operation);
564
+ const isExplicitMutation = action.mutation === true;
565
+ const isMutation = isExplicitMutation || hasMutatingOp
566
+ || (hasPolicy && Array.isArray(action.files) && action.files.length > 0 && action.operation === undefined);
567
+
568
+ // 2. Source revision check (Fail closed on missing/mismatched revision for guarded tasks)
569
+ const expectedRevision = task.workspace?.revision;
570
+ if (hasPolicy && isMutation && expectedRevision) {
571
+ if (action.revision === undefined || action.revision === null || action.revision === '') {
572
+ violations.push({
573
+ code: 'MISSING_SOURCE_REVISION',
574
+ message: 'Guarded mutation request must declare source revision matching task baseline.',
575
+ });
576
+ } else if (action.revision !== expectedRevision) {
577
+ violations.push({
578
+ code: 'SOURCE_REVISION_MISMATCH',
579
+ message: `Current revision '${action.revision}' does not match task baseline revision '${expectedRevision}'.`,
580
+ });
581
+ }
582
+ } else if (action.revision !== undefined && action.revision !== null) {
583
+ if (expectedRevision && action.revision !== expectedRevision) {
584
+ violations.push({
585
+ code: 'SOURCE_REVISION_MISMATCH',
586
+ message: `Current revision '${action.revision}' does not match task baseline revision '${expectedRevision}'.`,
587
+ });
588
+ }
589
+ }
590
+
591
+ // 3. Allowed operations check
592
+ if (hasPolicy && isMutation) {
593
+ if (action.operation === undefined || action.operation === null || action.operation === '') {
594
+ violations.push({
595
+ code: 'MISSING_OPERATION',
596
+ message: 'Guarded mutation request must declare an operation to evaluate allowedOperations.',
597
+ });
598
+ }
599
+ }
600
+
601
+ if (isGuardedWrite) {
602
+ // Explicit guarded write policy must not silently interpret missing allowedOperations as unrestricted
603
+ if (action.operation) {
604
+ if (!policy.allowedOperations || policy.allowedOperations.length === 0) {
605
+ violations.push({
606
+ code: 'UNAUTHORIZED_OPERATION',
607
+ message: `Guarded write policy does not authorize operation '${action.operation}'; allowedOperations is not configured. Use explicit wildcard or operation grants.`,
608
+ });
609
+ } else if (!policy.allowedOperations.includes('*') && !policy.allowedOperations.includes(action.operation)) {
610
+ violations.push({
611
+ code: 'UNAUTHORIZED_OPERATION',
612
+ message: `Operation '${action.operation}' is not within allowedOperations: [${policy.allowedOperations.join(', ')}].`,
613
+ });
614
+ }
615
+ }
616
+ } else if (action.operation !== undefined && policy?.allowedOperations?.length) {
617
+ if (!policy.allowedOperations.includes('*') && !policy.allowedOperations.includes(action.operation)) {
618
+ violations.push({
619
+ code: 'UNAUTHORIZED_OPERATION',
620
+ message: `Operation '${action.operation}' is not within allowedOperations: [${policy.allowedOperations.join(', ')}].`,
621
+ });
622
+ }
623
+ }
624
+
625
+ // 4. Mutation authorization check
626
+ if (isMutation) {
627
+ if (policy?.authorization === 'READ_ONLY') {
628
+ violations.push({
629
+ code: 'MUTATION_NOT_AUTHORIZED',
630
+ message: 'Task authorization is READ_ONLY; file mutations are not permitted.',
631
+ });
632
+ }
633
+ if (hasPolicy && (!Array.isArray(action.files) || action.files.length === 0)) {
634
+ violations.push({
635
+ code: 'MISSING_TARGET_FILES',
636
+ message: 'Guarded mutation requested without specifying target files.',
637
+ });
638
+ }
639
+ }
640
+
641
+ // 5. File scope checks (Absolute, UNC, drive paths rejected before allowlist matching; traversal and allowlist)
642
+ if (Array.isArray(action.files) && action.files.length > 0) {
643
+ for (const file of action.files) {
644
+ if (typeof file !== 'string' || !file.trim()) {
645
+ continue;
646
+ }
647
+ if (isUnsafeAbsolutePath(file)) {
648
+ violations.push({
649
+ code: 'ABSOLUTE_PATH_REJECTED',
650
+ message: `File '${file}' is an absolute or drive-qualified path; only workspace-relative paths are permitted.`,
651
+ });
652
+ continue;
653
+ }
654
+
655
+ const normFile = normalizePath(file);
656
+ if (normFile.startsWith('../') || normFile === '..') {
657
+ violations.push({
658
+ code: 'PATH_TRAVERSAL_DETECTED',
659
+ message: `File '${file}' attempts directory traversal outside workspace boundary.`,
660
+ });
661
+ continue;
662
+ }
663
+ if (policy?.excludedScope?.length) {
664
+ const isExcluded = policy.excludedScope.some((pattern) => matchesScopePattern(normFile, pattern));
665
+ if (isExcluded) {
666
+ violations.push({
667
+ code: 'EXCLUDED_SCOPE_VIOLATION',
668
+ message: `File '${file}' matches excluded scope pattern.`,
669
+ });
670
+ }
671
+ }
672
+ if (isGuardedWrite) {
673
+ // Explicit guarded write policy must not silently interpret missing allowedFiles as unrestricted
674
+ if (!policy.allowedFiles || policy.allowedFiles.length === 0) {
675
+ violations.push({
676
+ code: 'UNAUTHORIZED_FILE_SCOPE',
677
+ message: `File '${file}' is unauthorized; guarded write policy does not configure allowedFiles. Use explicit wildcard grants (e.g. ['**']) for broad access.`,
678
+ });
679
+ } else {
680
+ const isAllowed = policy.allowedFiles.some((pattern) => matchesScopePattern(normFile, pattern));
681
+ if (!isAllowed) {
682
+ violations.push({
683
+ code: 'UNAUTHORIZED_FILE_SCOPE',
684
+ message: `File '${file}' is outside allowedFiles scope.`,
685
+ });
686
+ }
687
+ }
688
+ } else if (policy?.allowedFiles?.length) {
689
+ const isAllowed = policy.allowedFiles.some((pattern) => matchesScopePattern(normFile, pattern));
690
+ if (!isAllowed) {
691
+ violations.push({
692
+ code: 'UNAUTHORIZED_FILE_SCOPE',
693
+ message: `File '${file}' is outside allowedFiles scope.`,
694
+ });
695
+ }
696
+ }
697
+ }
698
+ }
699
+
700
+ const allowed = violations.length === 0;
701
+ return freeze({
702
+ allowed,
703
+ status: allowed ? 'SCOPE_AUTHORIZED' : 'SCOPE_VIOLATION',
704
+ violations,
705
+ });
706
+ }
707
+
708
+ export function evaluateSearchEfficiency(input = {}) {
709
+ const options = object(input, 'searchEfficiencyOptions', [
710
+ 'query',
711
+ 'previousQueries',
712
+ 'indexFreshness',
713
+ 'newEvidenceAvailable',
714
+ 'unresolvedQuestion',
715
+ 'requiresRelationships',
716
+ 'knownPath',
717
+ ]);
718
+
719
+ const query = text(options.query, 'searchEfficiencyOptions.query', 1024);
720
+ const previousQueries = options.previousQueries === undefined ? [] : list(options.previousQueries, 'searchEfficiencyOptions.previousQueries', 128);
721
+ const indexFreshness = options.indexFreshness === undefined ? 'FRESH' : choice(options.indexFreshness, 'searchEfficiencyOptions.indexFreshness', new Set(FRESHNESS_STATES));
722
+ const newEvidenceAvailable = boolean(options.newEvidenceAvailable, 'searchEfficiencyOptions.newEvidenceAvailable', false);
723
+ const unresolvedQuestion = optionalText(options.unresolvedQuestion, 'searchEfficiencyOptions.unresolvedQuestion', 2048);
724
+ const requiresRelationships = boolean(options.requiresRelationships, 'searchEfficiencyOptions.requiresRelationships', false);
725
+ const knownPath = optionalText(options.knownPath, 'searchEfficiencyOptions.knownPath', 1024);
726
+
727
+ // Preference 1: If exact path is known and relationships are not required, direct source inspection is preferred
728
+ if (knownPath && !requiresRelationships) {
729
+ return freeze({
730
+ action: 'DIRECT_INSPECTION',
731
+ target: knownPath,
732
+ reason: 'DIRECT_INSPECTION_PREFERRED',
733
+ message: `Exact path '${knownPath}' is known and relationship exploration is not required; inspect source directly.`,
734
+ });
735
+ }
736
+
737
+ // Check duplicate equivalent queries
738
+ const normalizedQuery = query.trim().toLowerCase();
739
+ const isDuplicate = previousQueries.some((prev) => {
740
+ const prevText = typeof prev === 'string' ? prev : prev?.query;
741
+ return typeof prevText === 'string' && prevText.trim().toLowerCase() === normalizedQuery;
742
+ });
743
+
744
+ if (isDuplicate) {
745
+ if (newEvidenceAvailable) {
746
+ return freeze({
747
+ action: 'EXECUTE',
748
+ reason: 'REQUERY_JUSTIFIED_BY_NEW_EVIDENCE',
749
+ message: 'Re-query is justified because new evidence or modified files became available.',
750
+ });
751
+ }
752
+ if (indexFreshness === 'STALE') {
753
+ return freeze({
754
+ action: 'EXECUTE',
755
+ reason: 'REQUERY_JUSTIFIED_BY_INDEX_STALENESS',
756
+ message: 'Re-query is justified because Graph index is stale and requires refreshed exploration.',
757
+ });
758
+ }
759
+ if (unresolvedQuestion) {
760
+ return freeze({
761
+ action: 'EXECUTE',
762
+ reason: 'REQUERY_JUSTIFIED_BY_UNRESOLVED_QUESTION',
763
+ message: `Re-query is justified to resolve specific question: ${unresolvedQuestion}`,
764
+ });
765
+ }
766
+ return freeze({
767
+ action: 'REUSE_PREVIOUS',
768
+ reason: 'DUPLICATE_QUERY_REUSE',
769
+ message: 'Equivalent search was previously executed; reuse prior evidence instead of redundant tool invocation.',
770
+ });
771
+ }
772
+
773
+ if (requiresRelationships) {
774
+ if (indexFreshness === 'STALE') {
775
+ return freeze({
776
+ action: 'GRAPH_EXPLORE',
777
+ reason: 'STALE_INDEX_FALLBACK_RECOMMENDED',
778
+ message: 'Graph relationships needed, but index is stale; combine with direct source cross-check.',
779
+ });
780
+ }
781
+ return freeze({
782
+ action: 'GRAPH_EXPLORE',
783
+ reason: 'RELATIONSHIP_ANALYSIS_REQUIRED',
784
+ message: 'Graph exploration selected because structural relationship or impact analysis is required.',
785
+ });
786
+ }
787
+
788
+ return freeze({
789
+ action: 'EXECUTE',
790
+ reason: 'INITIAL_QUERY',
791
+ message: 'Initial query execution permitted.',
792
+ });
793
+ }
794
+
795
+ export function evaluateProviderGuardrailsPolicy(providerId, negotiation) {
796
+ const provider = text(providerId, 'providerId', 128);
797
+ const negotiationObj = object(negotiation, 'negotiation', [
798
+ 'contract',
799
+ 'provider',
800
+ 'status',
801
+ 'requirements',
802
+ 'mutationAuthorized',
803
+ 'diagnostics',
804
+ ]);
805
+
806
+ const requirements = negotiationObj.requirements || [];
807
+ const unsupported = requirements.filter((r) => r.status === 'UNSUPPORTED');
808
+ const unverified = requirements.filter((r) => r.status === 'UNVERIFIED');
809
+
810
+ return freeze({
811
+ contract: AGENT_GUARDRAILS_CONTRACT,
812
+ provider,
813
+ enforcementScope: 'VALIDATOR_ONLY',
814
+ contractValidatorsAvailable: true,
815
+ explicitInvocationValidation: true,
816
+ automaticMutationInterception: false,
817
+ automaticGraphInterception: false,
818
+ runtimeEnforcementActive: false,
819
+ osLevelEnforcement: false,
820
+ mechanicalEnforcement: false,
821
+ unsupportedCapabilities: unsupported.map((u) => u.capability),
822
+ unverifiedCapabilities: unverified.map((u) => u.capability),
823
+ gracefullyDegraded: unsupported.length > 0 || unverified.length > 0,
824
+ });
825
+ }