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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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,110 @@
1
+ #!/usr/bin/env node
2
+ import fs from 'node:fs';
3
+ import process from 'node:process';
4
+ import { ACE_LIMITS, AfyxContextEngine, validateContextRequest } from './engine.js';
5
+ import { AceError } from './errors.js';
6
+
7
+ const VERSION = '0.1.0';
8
+
9
+ function usage() {
10
+ return `Afyx Context Engine ${VERSION}
11
+
12
+ Usage:
13
+ afyx-context reduce --state <absolute-path> --owner <id> --session <id> --input <json-file|-> [--budget <chars>]
14
+ afyx-context get --state <absolute-path> --owner <id> --session <id> --reference <ace:v1:...>
15
+ afyx-context --version
16
+ `;
17
+ }
18
+
19
+ function options(args) {
20
+ const parsed = {};
21
+ for (let i = 0; i < args.length; i += 1) {
22
+ const current = args[i];
23
+ if (!current.startsWith('--')) throw new AceError('INVALID_CLI', `unexpected argument: ${current}`);
24
+ const value = args[++i];
25
+ if (value === undefined || value.startsWith('--')) throw new AceError('INVALID_CLI', `missing value for ${current}`);
26
+ parsed[current.slice(2)] = value;
27
+ }
28
+ return parsed;
29
+ }
30
+
31
+ function required(parsed, name) {
32
+ if (!parsed[name]) throw new AceError('INVALID_CLI', `--${name} is required`);
33
+ return parsed[name];
34
+ }
35
+
36
+ function engineFrom(parsed) {
37
+ return new AfyxContextEngine({
38
+ stateDir: required(parsed, 'state'),
39
+ ownerId: required(parsed, 'owner'),
40
+ sessionId: required(parsed, 'session'),
41
+ });
42
+ }
43
+
44
+ function readBoundedInput(inputPath) {
45
+ if (inputPath !== '-') {
46
+ let stat;
47
+ try {
48
+ stat = fs.statSync(inputPath);
49
+ } catch {
50
+ throw new AceError('INVALID_INPUT', `input file is unavailable: ${inputPath}`);
51
+ }
52
+ if (!stat.isFile()) throw new AceError('INVALID_INPUT', `input path is not a file: ${inputPath}`);
53
+ if (stat.size > ACE_LIMITS.maxCliInputBytes) {
54
+ throw new AceError('RESOURCE_LIMIT', `input exceeds the ${ACE_LIMITS.maxCliInputBytes} byte CLI limit`);
55
+ }
56
+ return fs.readFileSync(inputPath, 'utf8');
57
+ }
58
+ const chunks = [];
59
+ let size = 0;
60
+ while (true) {
61
+ const chunk = Buffer.allocUnsafe(65_536);
62
+ const count = fs.readSync(0, chunk, 0, chunk.length, null);
63
+ if (count === 0) break;
64
+ size += count;
65
+ if (size > ACE_LIMITS.maxCliInputBytes) {
66
+ throw new AceError('RESOURCE_LIMIT', `stdin exceeds the ${ACE_LIMITS.maxCliInputBytes} byte CLI limit`);
67
+ }
68
+ chunks.push(chunk.subarray(0, count));
69
+ }
70
+ return Buffer.concat(chunks, size).toString('utf8');
71
+ }
72
+
73
+ function main() {
74
+ const [command, ...rest] = process.argv.slice(2);
75
+ if (!command || command === '--help' || command === 'help') {
76
+ process.stdout.write(usage());
77
+ return;
78
+ }
79
+ if (command === '--version' || command === 'version') {
80
+ process.stdout.write(`${VERSION}\n`);
81
+ return;
82
+ }
83
+ const parsed = options(rest);
84
+ if (command === 'reduce') {
85
+ const inputPath = required(parsed, 'input');
86
+ const source = readBoundedInput(inputPath);
87
+ let request;
88
+ try { request = JSON.parse(source); } catch { throw new AceError('INVALID_INPUT', 'input must be valid JSON'); }
89
+ if (parsed.budget !== undefined) request.budgetChars = Number(parsed.budget);
90
+ validateContextRequest(request);
91
+ const engine = engineFrom(parsed);
92
+ process.stdout.write(`${JSON.stringify(engine.reduce(request), null, 2)}\n`);
93
+ return;
94
+ }
95
+ if (command === 'get') {
96
+ const engine = engineFrom(parsed);
97
+ process.stdout.write(engine.retrieve(required(parsed, 'reference')));
98
+ return;
99
+ }
100
+ throw new AceError('INVALID_CLI', `unknown command: ${command}`);
101
+ }
102
+
103
+ try {
104
+ main();
105
+ } catch (error) {
106
+ const code = error instanceof AceError ? error.code : 'INTERNAL';
107
+ const message = error instanceof Error ? error.message : String(error);
108
+ process.stderr.write(`afyx-context: ${code}: ${message}\n`);
109
+ process.exitCode = error instanceof AceError ? 2 : 1;
110
+ }
@@ -0,0 +1,343 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { AceError } from './errors.js';
6
+
7
+ const LOCK_FORMAT = 'ace.lock/v1';
8
+ const CLAIM_FORMAT = 'ace.lock-claim/v1';
9
+ const LOCK_NAME = '.ace-lock';
10
+ const OWNER_FILE = 'owner.json';
11
+ const CLAIM_FILE = 'recovery.json';
12
+ const MAX_COORDINATION_BYTES = 16_384;
13
+ const DEFAULT_TIMEOUT_MS = 5_000;
14
+ const DEFAULT_RETRY_MS = 25;
15
+ const MAX_TIMEOUT_MS = 60_000;
16
+ const MAX_RETRY_MS = 1_000;
17
+ const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}';
18
+ const ABANDONED = new RegExp(`^\\.ace-lock\\.abandoned\\.(${UUID})$`, 'i');
19
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
20
+
21
+ class MissingCoordinationError extends Error {}
22
+
23
+ function coordinationError(message) {
24
+ return new AceError('LOCK_RECOVERY_UNSAFE', message);
25
+ }
26
+
27
+ function boundedInteger(value, fallback, maximum, field) {
28
+ const selected = value ?? fallback;
29
+ if (!Number.isSafeInteger(selected) || selected < 1 || selected > maximum) {
30
+ throw new AceError('INVALID_INPUT', `${field} must be an integer from 1 through ${maximum}`);
31
+ }
32
+ return selected;
33
+ }
34
+
35
+ function sleep(milliseconds) {
36
+ Atomics.wait(sleeper, 0, 0, milliseconds);
37
+ }
38
+
39
+ function processPresence(pid) {
40
+ if (!Number.isSafeInteger(pid) || pid < 1) return 'unknown';
41
+ try {
42
+ process.kill(pid, 0);
43
+ return 'present';
44
+ } catch (error) {
45
+ if (error?.code === 'ESRCH') return 'absent';
46
+ return 'unknown';
47
+ }
48
+ }
49
+
50
+ function jsonText(value) {
51
+ const text = `${JSON.stringify(value, null, 2)}\n`;
52
+ if (Buffer.byteLength(text, 'utf8') > MAX_COORDINATION_BYTES) {
53
+ throw coordinationError('coordination metadata exceeds its bounded size');
54
+ }
55
+ return text;
56
+ }
57
+
58
+ function writeExclusiveJson(file, value) {
59
+ let handle;
60
+ try {
61
+ handle = fs.openSync(file, 'wx', 0o600);
62
+ fs.writeFileSync(handle, jsonText(value), { encoding: 'utf8' });
63
+ fs.fsyncSync(handle);
64
+ } finally {
65
+ if (handle !== undefined) fs.closeSync(handle);
66
+ }
67
+ }
68
+
69
+ function readRegularJson(file, description) {
70
+ try {
71
+ const stat = fs.lstatSync(file);
72
+ if (stat.isSymbolicLink() || !stat.isFile() || stat.size > MAX_COORDINATION_BYTES) {
73
+ throw coordinationError(`${description} is not a bounded owned regular file`);
74
+ }
75
+ return JSON.parse(fs.readFileSync(file, 'utf8'));
76
+ } catch (error) {
77
+ if (error instanceof AceError) throw error;
78
+ if (error?.code === 'ENOENT') throw new MissingCoordinationError(description);
79
+ throw coordinationError(`${description} is missing or unreadable`);
80
+ }
81
+ }
82
+
83
+ function validToken(value) {
84
+ return typeof value === 'string' && new RegExp(`^${UUID}$`, 'i').test(value);
85
+ }
86
+
87
+ export class StateCoordinator {
88
+ constructor({ stateDir, ownerHash, lockTimeoutMs, lockRetryMs }) {
89
+ this.stateDir = stateDir;
90
+ this.ownerHash = ownerHash;
91
+ this.stateRootHash = crypto.createHash('sha256').update(stateDir).digest('hex');
92
+ this.lockPath = path.join(stateDir, LOCK_NAME);
93
+ this.timeoutMs = boundedInteger(lockTimeoutMs, DEFAULT_TIMEOUT_MS, MAX_TIMEOUT_MS, 'lockTimeoutMs');
94
+ this.retryMs = boundedInteger(lockRetryMs, DEFAULT_RETRY_MS, MAX_RETRY_MS, 'lockRetryMs');
95
+ this.host = os.hostname();
96
+ }
97
+
98
+ isCoordinationEntry(name) {
99
+ return name === LOCK_NAME || ABANDONED.test(name);
100
+ }
101
+
102
+ withLock(action) {
103
+ const acquisition = this.#acquire();
104
+ let failure;
105
+ try {
106
+ return action({ recovered: acquisition.recovered });
107
+ } catch (error) {
108
+ failure = error;
109
+ throw error;
110
+ } finally {
111
+ try {
112
+ this.#release(acquisition.owner.token);
113
+ } catch (releaseError) {
114
+ if (failure) failure.cause ??= releaseError;
115
+ else throw releaseError;
116
+ }
117
+ }
118
+ }
119
+
120
+ #identity(format, token = crypto.randomUUID()) {
121
+ return {
122
+ format,
123
+ token,
124
+ stateRootHash: this.stateRootHash,
125
+ ownerHash: this.ownerHash,
126
+ host: this.host,
127
+ pid: process.pid,
128
+ createdAt: new Date().toISOString(),
129
+ };
130
+ }
131
+
132
+ #validateIdentity(value, format, description) {
133
+ if (!value || typeof value !== 'object' || Array.isArray(value)
134
+ || value.format !== format || !validToken(value.token)
135
+ || value.stateRootHash !== this.stateRootHash || value.ownerHash !== this.ownerHash
136
+ || typeof value.host !== 'string' || !Number.isSafeInteger(value.pid) || value.pid < 1
137
+ || typeof value.createdAt !== 'string') {
138
+ throw coordinationError(`${description} is malformed, foreign, or not bound to this state`);
139
+ }
140
+ return value;
141
+ }
142
+
143
+ #readDirectory(directory, { claim = 'optional', allowMissing = false } = {}) {
144
+ let entries;
145
+ try {
146
+ const stat = fs.lstatSync(directory);
147
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
148
+ throw coordinationError('coordination path is not an owned regular directory');
149
+ }
150
+ entries = fs.readdirSync(directory).sort();
151
+ } catch (error) {
152
+ if (error instanceof AceError) throw error;
153
+ if (allowMissing && error?.code === 'ENOENT') return null;
154
+ throw coordinationError('coordination directory is missing or unreadable');
155
+ }
156
+ const allowed = claim === 'required' ? [OWNER_FILE, CLAIM_FILE] : [OWNER_FILE];
157
+ if (claim === 'optional') {
158
+ if (entries.length < 1 || entries.length > 2 || entries[0] !== OWNER_FILE
159
+ || (entries.length === 2 && entries[1] !== CLAIM_FILE)) {
160
+ throw coordinationError('coordination directory contains unknown artifacts');
161
+ }
162
+ } else if (entries.length !== allowed.length || entries.some((entry, index) => entry !== allowed[index])) {
163
+ throw coordinationError('coordination directory contains unknown or missing artifacts');
164
+ }
165
+ let owner;
166
+ let recovery;
167
+ try {
168
+ owner = this.#validateIdentity(
169
+ readRegularJson(path.join(directory, OWNER_FILE), 'lock owner metadata'),
170
+ LOCK_FORMAT,
171
+ 'lock owner metadata',
172
+ );
173
+ recovery = entries.includes(CLAIM_FILE)
174
+ ? this.#validateIdentity(
175
+ readRegularJson(path.join(directory, CLAIM_FILE), 'lock recovery metadata'),
176
+ CLAIM_FORMAT,
177
+ 'lock recovery metadata',
178
+ )
179
+ : null;
180
+ } catch (error) {
181
+ if (allowMissing && error instanceof MissingCoordinationError) return null;
182
+ throw error;
183
+ }
184
+ return { owner, recovery };
185
+ }
186
+
187
+ #liveness(identity) {
188
+ if (identity.host !== this.host) return 'unknown';
189
+ const presence = processPresence(identity.pid);
190
+ if (presence === 'absent') return 'dead';
191
+ if (presence === 'present') return 'alive';
192
+ return 'unknown';
193
+ }
194
+
195
+ #removeDirectory(directory, ownerToken, recoveryToken = null) {
196
+ if (path.dirname(directory) !== this.stateDir) {
197
+ throw coordinationError('refusing to remove coordination data outside the state root');
198
+ }
199
+ const expectedClaim = recoveryToken ? 'required' : 'forbidden';
200
+ const metadata = this.#readDirectory(directory, { claim: expectedClaim });
201
+ if (metadata.owner.token !== ownerToken || (recoveryToken && metadata.recovery?.token !== recoveryToken)) {
202
+ throw coordinationError('coordination ownership changed before cleanup');
203
+ }
204
+ if (recoveryToken) fs.unlinkSync(path.join(directory, CLAIM_FILE));
205
+ fs.unlinkSync(path.join(directory, OWNER_FILE));
206
+ fs.rmdirSync(directory);
207
+ }
208
+
209
+ #tryAcquire() {
210
+ const owner = this.#identity(LOCK_FORMAT);
211
+ try {
212
+ fs.mkdirSync(this.lockPath, { mode: 0o700 });
213
+ } catch (error) {
214
+ if (error?.code === 'EEXIST') return null;
215
+ throw error;
216
+ }
217
+ const temporary = path.join(this.lockPath, `.owner.${owner.token}.tmp`);
218
+ try {
219
+ writeExclusiveJson(temporary, owner);
220
+ fs.renameSync(temporary, path.join(this.lockPath, OWNER_FILE));
221
+ return owner;
222
+ } catch (error) {
223
+ try {
224
+ if (fs.existsSync(temporary)) {
225
+ const stat = fs.lstatSync(temporary);
226
+ if (stat.isSymbolicLink() || !stat.isFile()) throw coordinationError('owned lock temporary changed type');
227
+ fs.unlinkSync(temporary);
228
+ }
229
+ fs.rmdirSync(this.lockPath);
230
+ } catch (cleanupError) {
231
+ throw coordinationError(`failed to clean an incomplete owned lock: ${cleanupError.message}`);
232
+ }
233
+ throw error;
234
+ }
235
+ }
236
+
237
+ #recoverAbandonedLock() {
238
+ const first = this.#readDirectory(this.lockPath, { allowMissing: true });
239
+ if (!first) return true;
240
+ const ownerState = this.#liveness(first.owner);
241
+ if (ownerState === 'alive') return false;
242
+ if (ownerState === 'unknown') {
243
+ throw coordinationError('lock owner liveness cannot be verified; manual inspection is required');
244
+ }
245
+ if (first.recovery) {
246
+ const claimantState = this.#liveness(first.recovery);
247
+ if (claimantState === 'alive') return false;
248
+ if (claimantState === 'unknown') {
249
+ throw coordinationError('lock recovery claimant liveness cannot be verified; manual inspection is required');
250
+ }
251
+ const current = this.#readDirectory(this.lockPath, { claim: 'required' });
252
+ if (current.owner.token !== first.owner.token || current.recovery.token !== first.recovery.token) return false;
253
+ fs.unlinkSync(path.join(this.lockPath, CLAIM_FILE));
254
+ }
255
+
256
+ const claim = this.#identity(CLAIM_FORMAT);
257
+ try {
258
+ writeExclusiveJson(path.join(this.lockPath, CLAIM_FILE), claim);
259
+ } catch (error) {
260
+ if (error?.code === 'EEXIST') return false;
261
+ if (error?.code === 'ENOENT') return true;
262
+ throw error;
263
+ }
264
+ const claimed = this.#readDirectory(this.lockPath, { claim: 'required' });
265
+ if (claimed.owner.token !== first.owner.token || claimed.recovery.token !== claim.token) {
266
+ throw coordinationError('lock ownership changed during abandoned-lock recovery');
267
+ }
268
+ const abandoned = path.join(this.stateDir, `.ace-lock.abandoned.${claim.token}`);
269
+ fs.renameSync(this.lockPath, abandoned);
270
+ this.#removeDirectory(abandoned, first.owner.token, claim.token);
271
+ return true;
272
+ }
273
+
274
+ #cleanupArtifacts() {
275
+ for (const entry of fs.readdirSync(this.stateDir).sort()) {
276
+ const abandonedMatch = ABANDONED.exec(entry);
277
+ if (!abandonedMatch) {
278
+ if (entry.startsWith('.ace-lock.') && entry !== LOCK_NAME) {
279
+ throw coordinationError(`unrecognized coordination artifact: ${entry}`);
280
+ }
281
+ continue;
282
+ }
283
+ const target = path.join(this.stateDir, entry);
284
+ const metadata = this.#readDirectory(target, {
285
+ claim: 'required',
286
+ allowMissing: true,
287
+ });
288
+ if (!metadata) continue;
289
+ if (metadata.recovery.token.toLowerCase() !== abandonedMatch[1].toLowerCase()) {
290
+ throw coordinationError('abandoned lock name does not match its recovery token');
291
+ }
292
+ const state = this.#liveness(metadata.recovery);
293
+ if (state === 'alive') continue;
294
+ if (state === 'unknown') {
295
+ throw coordinationError(`coordination artifact owner cannot be verified: ${entry}`);
296
+ }
297
+ this.#removeDirectory(target, metadata.owner.token, metadata.recovery.token);
298
+ }
299
+ }
300
+
301
+ #acquire() {
302
+ const started = Date.now();
303
+ let recovered = false;
304
+ while (true) {
305
+ const owner = this.#tryAcquire();
306
+ if (owner) {
307
+ try {
308
+ this.#cleanupArtifacts();
309
+ return { owner, recovered };
310
+ } catch (error) {
311
+ this.#release(owner.token);
312
+ throw error;
313
+ }
314
+ }
315
+ let recoveryError;
316
+ try {
317
+ if (this.#recoverAbandonedLock()) {
318
+ recovered = true;
319
+ continue;
320
+ }
321
+ } catch (error) {
322
+ if (!(error instanceof AceError) || error.code !== 'LOCK_RECOVERY_UNSAFE') throw error;
323
+ recoveryError = error;
324
+ }
325
+ if (Date.now() - started >= this.timeoutMs) {
326
+ if (recoveryError) throw recoveryError;
327
+ const metadata = this.#readDirectory(this.lockPath, { allowMissing: true });
328
+ const detail = metadata
329
+ ? `host ${metadata.owner.host}, pid ${metadata.owner.pid}`
330
+ : 'no stable lock owner could be observed';
331
+ throw new AceError(
332
+ 'LOCK_TIMEOUT',
333
+ `ACE state lock timed out after ${this.timeoutMs} ms (${detail})`,
334
+ );
335
+ }
336
+ sleep(Math.min(this.retryMs, Math.max(1, this.timeoutMs - (Date.now() - started))));
337
+ }
338
+ }
339
+
340
+ #release(token) {
341
+ this.#removeDirectory(this.lockPath, token);
342
+ }
343
+ }
@@ -0,0 +1,198 @@
1
+ import { AceError, assertNonEmpty } from './errors.js';
2
+ import { ContextStore, sha256 } from './storage.js';
3
+
4
+ const CLASSIFICATIONS = new Set(['normal', 'diagnostic', 'security', 'source-evidence']);
5
+ const PRESERVED = new Set(['diagnostic', 'security', 'source-evidence']);
6
+ export const ACE_LIMITS = Object.freeze({
7
+ maxSegments: 1_024,
8
+ maxSegmentBytes: 1_048_576,
9
+ maxRequestBytes: 8_388_608,
10
+ maxProvenanceBytes: 65_536,
11
+ maxIdBytes: 512,
12
+ maxCliInputBytes: 10_485_760,
13
+ });
14
+
15
+ /** Conservative classification: false positives retain bytes instead of losing them. */
16
+ export function classifyContent(content, hint, provenance = {}) {
17
+ if (hint !== undefined) {
18
+ if (!CLASSIFICATIONS.has(hint)) throw new AceError('INVALID_INPUT', `unsupported classification: ${hint}`);
19
+ if (hint !== 'normal') return hint;
20
+ }
21
+ if (provenance.exactSource === true) return 'source-evidence';
22
+ if (/\b(?:SECURITY|UNAUTHORIZED|PERMISSION DENIED|ACCESS DENIED|CREDENTIAL|SECRET)\b/i.test(content)) return 'security';
23
+ if (/\b(?:ERROR|FAIL(?:ED|URE)?|EXCEPTION|TRACEBACK|E_[A-Z0-9_]+)\b/i.test(content)) return 'diagnostic';
24
+ return 'normal';
25
+ }
26
+
27
+ function normalizeSegments(segments) {
28
+ if (!Array.isArray(segments) || segments.length === 0) {
29
+ throw new AceError('INVALID_INPUT', 'segments must be a non-empty array');
30
+ }
31
+ if (segments.length > ACE_LIMITS.maxSegments) {
32
+ throw new AceError('RESOURCE_LIMIT', `segments exceeds the ${ACE_LIMITS.maxSegments} item limit`);
33
+ }
34
+ const ids = new Set();
35
+ let requestBytes = 0;
36
+ return segments.map((segment, index) => {
37
+ if (!segment || typeof segment !== 'object') throw new AceError('INVALID_INPUT', `segments[${index}] must be an object`);
38
+ const id = assertNonEmpty(segment.id, `segments[${index}].id`);
39
+ if (/[\u0000-\u001f\u007f]/.test(id)) {
40
+ throw new AceError('INVALID_INPUT', `segments[${index}].id contains a control character`);
41
+ }
42
+ if (Buffer.byteLength(id, 'utf8') > ACE_LIMITS.maxIdBytes) {
43
+ throw new AceError('RESOURCE_LIMIT', `segments[${index}].id exceeds the ${ACE_LIMITS.maxIdBytes} byte limit`);
44
+ }
45
+ if (ids.has(id)) throw new AceError('INVALID_INPUT', `duplicate segment id: ${id}`);
46
+ ids.add(id);
47
+ if (typeof segment.content !== 'string') throw new AceError('INVALID_INPUT', `segments[${index}].content must be a string`);
48
+ const contentBytes = Buffer.byteLength(segment.content, 'utf8');
49
+ if (contentBytes > ACE_LIMITS.maxSegmentBytes) {
50
+ throw new AceError('RESOURCE_LIMIT', `segments[${index}].content exceeds the ${ACE_LIMITS.maxSegmentBytes} byte limit`);
51
+ }
52
+ requestBytes += contentBytes + Buffer.byteLength(id, 'utf8');
53
+ if (segment.provenance !== undefined && (segment.provenance === null || typeof segment.provenance !== 'object' || Array.isArray(segment.provenance))) {
54
+ throw new AceError('INVALID_INPUT', `segments[${index}].provenance must be an object`);
55
+ }
56
+ let provenance;
57
+ try {
58
+ const encoded = JSON.stringify(segment.provenance ?? {});
59
+ if (Buffer.byteLength(encoded, 'utf8') > ACE_LIMITS.maxProvenanceBytes) {
60
+ throw new AceError('RESOURCE_LIMIT', `segments[${index}].provenance exceeds the ${ACE_LIMITS.maxProvenanceBytes} byte limit`);
61
+ }
62
+ requestBytes += Buffer.byteLength(encoded, 'utf8');
63
+ if (requestBytes > ACE_LIMITS.maxRequestBytes) {
64
+ throw new AceError('RESOURCE_LIMIT', `segments exceed the ${ACE_LIMITS.maxRequestBytes} byte request limit`);
65
+ }
66
+ provenance = JSON.parse(encoded);
67
+ } catch (error) {
68
+ if (error instanceof AceError) throw error;
69
+ throw new AceError('INVALID_INPUT', `segments[${index}].provenance must be JSON-serializable`);
70
+ }
71
+ const classification = classifyContent(segment.content, segment.classification, provenance);
72
+ return { id, content: segment.content, classification, provenance };
73
+ });
74
+ }
75
+
76
+ function originalLine(segment) {
77
+ return `[${segment.id}] ${segment.classification}\n${segment.content}`;
78
+ }
79
+
80
+ function referenceLine(segment, reference, reason) {
81
+ return `[${segment.id}] ${reason} ${reference}`;
82
+ }
83
+
84
+ function passthrough(segments, reason) {
85
+ const renderedContext = segments.map(originalLine).join('\n\n');
86
+ return {
87
+ contract: 'ace.result/v1',
88
+ mode: 'passthrough',
89
+ reason,
90
+ renderedContext,
91
+ items: segments.map((segment) => ({
92
+ id: segment.id,
93
+ classification: segment.classification,
94
+ disposition: 'original',
95
+ digest: sha256(segment.content),
96
+ provenance: segment.provenance,
97
+ content: segment.content,
98
+ })),
99
+ metrics: {
100
+ rawChars: renderedContext.length,
101
+ outputChars: renderedContext.length,
102
+ savedChars: 0,
103
+ reductionRatio: 0,
104
+ },
105
+ };
106
+ }
107
+
108
+ function normalizeRequest({ segments, budgetChars = 32_000 } = {}) {
109
+ const normalized = normalizeSegments(segments);
110
+ if (!Number.isSafeInteger(budgetChars) || budgetChars < 1) {
111
+ throw new AceError('INVALID_INPUT', 'budgetChars must be a positive safe integer');
112
+ }
113
+ return { normalized, budgetChars };
114
+ }
115
+
116
+ export function validateContextRequest(request) {
117
+ normalizeRequest(request);
118
+ return true;
119
+ }
120
+
121
+ export class AfyxContextEngine {
122
+ constructor(options = {}) {
123
+ this.store = new ContextStore(options);
124
+ }
125
+
126
+ reduce(request = {}) {
127
+ const { normalized, budgetChars } = normalizeRequest(request);
128
+
129
+ // Validate everything before the first state mutation. Original bytes are
130
+ // persisted before reduction so every emitted reference is recoverable.
131
+ const knownBefore = this.store.snapshotAndPersist(normalized);
132
+ const mandatoryChars = normalized
133
+ .filter((segment) => PRESERVED.has(segment.classification))
134
+ .reduce((total, segment) => total + originalLine(segment).length + 2, 0);
135
+ if (mandatoryChars > budgetChars) return passthrough(normalized, 'protected-content-exceeds-budget');
136
+
137
+ const seen = new Set();
138
+ const rendered = [];
139
+ const items = [];
140
+ let used = 0;
141
+ for (const segment of normalized) {
142
+ const digest = sha256(segment.content);
143
+ const reference = this.store.reference(segment.content);
144
+ const original = originalLine(segment);
145
+ const repeated = seen.has(digest) || knownBefore.has(digest);
146
+ const preserve = PRESERVED.has(segment.classification);
147
+ const refReason = repeated ? 'repeated' : 'budgeted';
148
+ const reduced = referenceLine(segment, reference, refReason);
149
+ const separator = rendered.length === 0 ? 0 : 2;
150
+ const reservedLater = normalized.slice(items.length + 1)
151
+ .filter((candidate) => PRESERVED.has(candidate.classification))
152
+ .reduce((total, candidate) => total + originalLine(candidate).length + 2, 0);
153
+ const mayReference = !preserve && reduced.length < original.length;
154
+ const chooseReference = mayReference && (repeated || used + separator + original.length + reservedLater > budgetChars);
155
+ const selected = chooseReference ? reduced : original;
156
+ if (used + separator + selected.length + reservedLater > budgetChars) {
157
+ return passthrough(normalized, 'safe-budget-fallback');
158
+ }
159
+ rendered.push(selected);
160
+ used += separator + selected.length;
161
+ items.push({
162
+ id: segment.id,
163
+ classification: segment.classification,
164
+ disposition: chooseReference ? 'reference' : 'original',
165
+ digest,
166
+ reference,
167
+ provenance: segment.provenance,
168
+ ...(chooseReference ? { reason: refReason } : { content: segment.content }),
169
+ });
170
+ seen.add(digest);
171
+ }
172
+
173
+ const rawContext = normalized.map(originalLine).join('\n\n');
174
+ const renderedContext = rendered.join('\n\n');
175
+ return {
176
+ contract: 'ace.result/v1',
177
+ mode: 'optimized',
178
+ renderedContext,
179
+ items,
180
+ metrics: {
181
+ rawChars: rawContext.length,
182
+ outputChars: renderedContext.length,
183
+ savedChars: rawContext.length - renderedContext.length,
184
+ reductionRatio: rawContext.length === 0 ? 0 : (rawContext.length - renderedContext.length) / rawContext.length,
185
+ },
186
+ };
187
+ }
188
+
189
+ retrieve(reference) {
190
+ return this.store.retrieve(reference);
191
+ }
192
+
193
+ retrieveRecord(reference) {
194
+ return this.store.retrieveRecord(reference);
195
+ }
196
+ }
197
+
198
+ export const classifications = Object.freeze([...CLASSIFICATIONS]);
@@ -0,0 +1,14 @@
1
+ export class AceError extends Error {
2
+ constructor(code, message) {
3
+ super(message);
4
+ this.name = 'AceError';
5
+ this.code = code;
6
+ }
7
+ }
8
+
9
+ export function assertNonEmpty(value, field) {
10
+ if (typeof value !== 'string' || value.trim().length === 0) {
11
+ throw new AceError('INVALID_INPUT', `${field} must be a non-empty string`);
12
+ }
13
+ return value;
14
+ }