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.
- package/.afyx-source-revision +1 -0
- package/LICENSE +21 -0
- package/README.md +377 -2
- package/SECURITY.md +74 -0
- package/afyx-context/LICENSE +21 -0
- package/afyx-context/README.md +155 -0
- package/afyx-context/afyx-context.json +30 -0
- package/afyx-context/contracts/integration-v1.schema.json +34 -0
- package/afyx-context/package-lock.json +53 -0
- package/afyx-context/package.json +34 -0
- package/afyx-context/scripts/benchmark.mjs +39 -0
- package/afyx-context/scripts/build.mjs +15 -0
- package/afyx-context/scripts/comparative-benchmark.mjs +342 -0
- package/afyx-context/scripts/comparative-worker.mjs +74 -0
- package/afyx-context/scripts/graph-integration-e2e.mjs +188 -0
- package/afyx-context/scripts/integrated-dogfood.mjs +309 -0
- package/afyx-context/src/budget.js +166 -0
- package/afyx-context/src/cli.js +110 -0
- package/afyx-context/src/coordination.js +343 -0
- package/afyx-context/src/engine.js +198 -0
- package/afyx-context/src/errors.js +14 -0
- package/afyx-context/src/graph-integration-worker.js +70 -0
- package/afyx-context/src/graph-integration.js +373 -0
- package/afyx-context/src/graph-mcp-bridge.js +103 -0
- package/afyx-context/src/index.js +25 -0
- package/afyx-context/src/integrations.js +87 -0
- package/afyx-context/src/memory.js +255 -0
- package/afyx-context/src/storage.js +364 -0
- package/afyx-context/test-fixtures/coordination-worker.mjs +52 -0
- package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__init__.py +1 -0
- package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__manifest__.py +4 -0
- package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/__init__.py +1 -0
- package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/sale_order.py +5 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__init__.py +1 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__manifest__.py +10 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/__init__.py +2 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order.py +20 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order_audit.py +11 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/security/ir.model.access.csv +2 -0
- package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/views/sale_order_views.xml +14 -0
- package/afyx-forge/LICENSE +55 -0
- package/afyx-forge/README.md +126 -0
- package/afyx-forge/afyx-forge.json +28 -0
- package/afyx-forge/bin/afyx-forge +4 -0
- package/afyx-forge/bin/afyx-forge.cmd +3 -0
- package/afyx-forge/bin/afyx-forge.js +16 -0
- package/afyx-forge/contracts/forge-plan-v1.schema.json +172 -0
- package/afyx-forge/package.json +26 -0
- package/afyx-forge/src/classifier.js +190 -0
- package/afyx-forge/src/cli.js +111 -0
- package/afyx-forge/src/doctor.js +105 -0
- package/afyx-forge/src/guidance.js +120 -0
- package/afyx-forge/src/index.js +273 -0
- package/afyx-forge/src/planning.js +107 -0
- package/afyx-forge/src/policy.js +109 -0
- package/afyx-forge/src/workflow-refiner.js +151 -0
- package/afyx-graph/afyx-graph.json +20 -0
- package/afyx-graph/engine/LICENSE +21 -0
- package/afyx-graph/engine/README.md +104 -0
- package/afyx-graph/engine/release/RELEASE-MANIFEST.json +21 -0
- package/afyx-graph/engine/release/SHA256SUMS +2 -0
- package/afyx-graph/engine/release/afyx-graph-linux-x64.tar.gz +0 -0
- package/afyx-graph/engine/release/afyx-graph-win32-x64.zip +0 -0
- package/afyx-graph/engine/scripts/distribution-contract.mjs +212 -0
- package/afyx-graph/engine/scripts/distribution-product.json +33 -0
- package/bin/afyx-engineering-kit.mjs +61 -0
- package/install.ps1 +1053 -0
- package/install.sh +617 -0
- package/package.json +66 -4
- package/scripts/afyx-capability-orchestrator.mjs +752 -0
- package/scripts/afyx-claude-integration.mjs +547 -0
- package/scripts/afyx-context-artifact.mjs +105 -0
- package/scripts/afyx-credential-broker.mjs +75 -0
- package/scripts/afyx-doctor.ps1 +152 -0
- package/scripts/afyx-doctor.sh +146 -0
- package/scripts/afyx-forge-artifact.mjs +183 -0
- package/scripts/afyx-global-routing-policy.md +12 -0
- package/scripts/afyx-global-routing.mjs +168 -0
- package/scripts/afyx-graph-artifact.mjs +178 -0
- package/scripts/afyx-host-adapters.mjs +543 -0
- package/scripts/afyx-host-bridge-lifecycle.mjs +174 -0
- package/scripts/afyx-host-bridge.mjs +288 -0
- package/scripts/afyx-integration-contracts.mjs +825 -0
- package/scripts/afyx-mcp-integration.mjs +528 -0
- package/scripts/afyx-modular-integration.mjs +361 -0
- package/scripts/afyx-modular-runtime.mjs +451 -0
- package/scripts/afyx-native-skill-host.mjs +124 -0
- package/scripts/afyx-npm-installer.mjs +486 -0
- package/scripts/afyx-project.ps1 +205 -0
- package/scripts/afyx-project.sh +207 -0
- package/scripts/afyx-provider-backup.mjs +1206 -0
- package/scripts/afyx-provider-integration.mjs +724 -0
- package/scripts/afyx-provider-inventory.mjs +147 -0
- package/scripts/afyx-security-auditor.mjs +224 -0
- package/scripts/afyx-skill-engineering.mjs +354 -0
- package/scripts/afyx-tool-family-routing.mjs +64 -0
- package/scripts/afyx-universal-runtime.mjs +530 -0
- package/scripts/alpha_acceptance_preflight.py +240 -0
- package/scripts/benchmark-graph-memory.mjs +96 -0
- package/scripts/benchmark_capability_orchestrator.mjs +64 -0
- package/scripts/build-windows-installer.ps1 +259 -0
- package/scripts/build_forge_synthetic_image.py +328 -0
- package/scripts/check-reference-staleness.py +71 -0
- package/scripts/components.json +254 -0
- package/scripts/contracts/afyx-capability-request-v1.schema.json +189 -0
- package/scripts/contracts/afyx-capability-result-v1.schema.json +32 -0
- package/scripts/dogfood_engineering_comparison.mjs +303 -0
- package/scripts/engineering-assurance.json +28 -0
- package/scripts/install-afyx-context.ps1 +142 -0
- package/scripts/install-afyx-context.sh +126 -0
- package/scripts/install-afyx-forge.ps1 +265 -0
- package/scripts/install-afyx-forge.sh +273 -0
- package/scripts/install-afyx-graph.ps1 +571 -0
- package/scripts/install-afyx-graph.sh +438 -0
- package/scripts/install-codex-usage-tracker.ps1 +172 -0
- package/scripts/lib/AfyxComponents.psm1 +399 -0
- package/scripts/lib/AfyxSkillLifecycle.psm1 +289 -0
- package/scripts/lib/AfyxTerminal.psm1 +838 -0
- package/scripts/lib/afyx-components.sh +256 -0
- package/scripts/lib/afyx-skill-lifecycle.sh +271 -0
- package/scripts/link-global-dev.ps1 +193 -0
- package/scripts/link-global-dev.sh +130 -0
- package/scripts/phase8-paired-evidence.mjs +195 -0
- package/scripts/phase8-representative-workload.mjs +771 -0
- package/scripts/phase8-session-recorder.mjs +157 -0
- package/scripts/phase8_event_ledger.py +248 -0
- package/scripts/phase8_evidence_discovery.py +189 -0
- package/scripts/prepare-g6-package.mjs +349 -0
- package/scripts/resolve-git-release-artifacts.mjs +321 -0
- package/scripts/stage-npm-release.mjs +94 -0
- package/scripts/validate-afyx-graph.py +203 -0
- package/scripts/validate-components.py +194 -0
- package/scripts/validate-engineering-assurance.py +281 -0
- package/scripts/verify-graph-archive.mjs +64 -0
- package/skills/afyx-context/SKILL.md +26 -0
- package/skills/afyx-engineering-expert/README.md +42 -0
- package/skills/afyx-engineering-expert/SKILL.md +70 -0
- package/skills/afyx-engineering-expert/assets/result-template.md +15 -0
- package/skills/afyx-engineering-expert/references/ai-ml-engineer.md +17 -0
- package/skills/afyx-engineering-expert/references/business-analyst.md +17 -0
- package/skills/afyx-engineering-expert/references/clean-code-engineer.md +26 -0
- package/skills/afyx-engineering-expert/references/code-reviewer.md +24 -0
- package/skills/afyx-engineering-expert/references/cybersecurity-devsecops.md +17 -0
- package/skills/afyx-engineering-expert/references/data-analyst-bi.md +24 -0
- package/skills/afyx-engineering-expert/references/data-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/database-administrator.md +17 -0
- package/skills/afyx-engineering-expert/references/debugging-specialist.md +24 -0
- package/skills/afyx-engineering-expert/references/embedded-iot-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/erp-technical-specialist.md +17 -0
- package/skills/afyx-engineering-expert/references/hardware-diagnostics-auditor.md +24 -0
- package/skills/afyx-engineering-expert/references/hardware-electronics-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/integration-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/legacy-modernization-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/llmops-prompt-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/network-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/performance-benchmark-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/platform-engineer.md +24 -0
- package/skills/afyx-engineering-expert/references/product-manager.md +17 -0
- package/skills/afyx-engineering-expert/references/qa-engineer.md +17 -0
- package/skills/afyx-engineering-expert/references/site-reliability-engineer.md +17 -0
- package/skills/afyx-engineering-expert/references/software-engineer.md +17 -0
- package/skills/afyx-engineering-expert/references/solutions-architect.md +17 -0
- package/skills/afyx-engineering-expert/references/specialists-index.md +33 -0
- package/skills/afyx-engineering-expert/references/subject-matter-expert.md +17 -0
- package/skills/afyx-engineering-expert/references/system-analyst.md +17 -0
- package/skills/afyx-engineering-expert/references/technical-project-manager.md +24 -0
- package/skills/afyx-engineering-expert/references/technical-writer.md +24 -0
- package/skills/afyx-engineering-expert/references/ui-ux-designer.md +17 -0
- package/skills/afyx-engineering-expert/workflows/ai-data-erp.md +20 -0
- package/skills/afyx-engineering-expert/workflows/debugging.md +10 -0
- package/skills/afyx-engineering-expert/workflows/discovery-design.md +11 -0
- package/skills/afyx-engineering-expert/workflows/implementation.md +12 -0
- package/skills/afyx-engineering-expert/workflows/incident-reliability.md +12 -0
- package/skills/afyx-engineering-expert/workflows/review-audit.md +13 -0
- package/skills/afyx-forge/SKILL.md +43 -0
- package/skills/afyx-forge/references/adaptive-policy.md +19 -0
- package/skills/efficient-coding/SKILL.md +33 -0
- package/skills/efficient-coding/references/investigation.md +27 -0
- package/skills/efficient-coding/references/token-efficiency.md +25 -0
- package/skills/efficient-coding/references/tool-routing.md +13 -0
- package/skills/odoo-engineering/SKILL.md +33 -0
- package/skills/odoo-engineering/references/common.md +9 -0
- package/skills/odoo-engineering/references/odoo-10.md +32 -0
- package/skills/odoo-engineering/references/odoo-11.md +26 -0
- package/skills/odoo-engineering/references/odoo-12.md +31 -0
- package/skills/odoo-engineering/references/odoo-13.md +27 -0
- package/skills/odoo-engineering/references/odoo-14.md +31 -0
- package/skills/odoo-engineering/references/odoo-15.md +34 -0
- package/skills/odoo-engineering/references/odoo-16.md +37 -0
- package/skills/odoo-engineering/references/odoo-17.md +37 -0
- package/skills/odoo-engineering/references/odoo-18.md +48 -0
- package/skills/odoo-engineering/references/odoo-19.md +43 -0
- package/skills/odoo-engineering/references/odoo-20.md +39 -0
- package/skills/odoo-engineering/references/reference-schema.md +16 -0
- package/skills/odoo-engineering/references/version-detection.md +13 -0
- package/tools/codex-usage/CodexUsage.psm1 +496 -0
- package/tools/codex-usage/codex-usage-doctor.ps1 +150 -0
- package/tools/codex-usage/codex-usage-pricing.json +25 -0
- package/tools/codex-usage/codex-usage-stop.ps1 +167 -0
- package/tools/codex-usage/codex-usage-watch.ps1 +250 -0
- package/tools/codex-usage/vscode-user-task.json +31 -0
- package/tools/windows-setup/SetupBootstrapper.cs +258 -0
- package/uninstall.ps1 +189 -0
- package/uninstall.sh +167 -0
- package/update.ps1 +95 -0
- package/update.sh +67 -0
- package/verify.ps1 +411 -0
- package/verify.sh +265 -0
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* AFYX Context Engine - Native Persistent Engineering Memory
|
|
3
|
+
*
|
|
4
|
+
* Provides deterministic, project-scoped, bounded persistent memory
|
|
5
|
+
* for technical architecture decisions, constraints, and conventions.
|
|
6
|
+
* Standalone by design; stores structured evidence in a local JSON store
|
|
7
|
+
* without external databases, background daemons, or cloud telemetry.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
12
|
+
import { dirname, join, resolve } from 'node:path';
|
|
13
|
+
|
|
14
|
+
export const MEMORY_CONTRACT_VERSION = 'afyx-memory-v1';
|
|
15
|
+
export const DEFAULT_MAX_ITEMS = 100;
|
|
16
|
+
export const MEMORY_DIR_NAME = '.afyx-context';
|
|
17
|
+
export const MEMORY_FILE_NAME = 'engineering-memory.json';
|
|
18
|
+
|
|
19
|
+
export const MEMORY_CATEGORIES = Object.freeze([
|
|
20
|
+
'architecture',
|
|
21
|
+
'decision',
|
|
22
|
+
'pattern',
|
|
23
|
+
'constraint',
|
|
24
|
+
'convention',
|
|
25
|
+
'fact',
|
|
26
|
+
]);
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Creates a unique content hash for memory item deduplication.
|
|
30
|
+
*/
|
|
31
|
+
function hashText(text) {
|
|
32
|
+
return createHash('sha256').update(String(text).trim().toLowerCase()).digest('hex').slice(0, 16);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Project-Scoped Engineering Memory Manager.
|
|
37
|
+
*/
|
|
38
|
+
export class AfyxEngineeringMemory {
|
|
39
|
+
/**
|
|
40
|
+
* @param {Object} options
|
|
41
|
+
* @param {string} options.projectRoot - Absolute path to workspace root
|
|
42
|
+
* @param {string} [options.storagePath] - Custom absolute storage file path
|
|
43
|
+
* @param {boolean} [options.enabled] - Explicit enable flag (defaults to env AFYX_CONTEXT_MEMORY !== '0')
|
|
44
|
+
* @param {number} [options.maxItems] - Maximum items to retain (bounds local storage)
|
|
45
|
+
*/
|
|
46
|
+
constructor({ projectRoot, storagePath, enabled, maxItems } = {}) {
|
|
47
|
+
this.projectRoot = resolve(projectRoot || process.cwd());
|
|
48
|
+
this.storagePath = storagePath || join(this.projectRoot, MEMORY_DIR_NAME, MEMORY_FILE_NAME);
|
|
49
|
+
this.enabled = enabled !== undefined ? Boolean(enabled) : process.env.AFYX_CONTEXT_MEMORY !== '0';
|
|
50
|
+
this.maxItems = Number.isInteger(maxItems) && maxItems > 0 ? maxItems : DEFAULT_MAX_ITEMS;
|
|
51
|
+
this.items = [];
|
|
52
|
+
this.load();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Loads memory entries from persistent local storage.
|
|
57
|
+
*/
|
|
58
|
+
load() {
|
|
59
|
+
if (!this.enabled) return;
|
|
60
|
+
if (!existsSync(this.storagePath)) {
|
|
61
|
+
this.items = [];
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
try {
|
|
65
|
+
const raw = readFileSync(this.storagePath, 'utf8');
|
|
66
|
+
const parsed = JSON.parse(raw);
|
|
67
|
+
if (parsed?.schema === MEMORY_CONTRACT_VERSION && Array.isArray(parsed.items)) {
|
|
68
|
+
this.items = parsed.items;
|
|
69
|
+
} else {
|
|
70
|
+
this.items = [];
|
|
71
|
+
}
|
|
72
|
+
} catch {
|
|
73
|
+
this.items = [];
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Persists memory entries atomically to disk.
|
|
79
|
+
*/
|
|
80
|
+
save() {
|
|
81
|
+
if (!this.enabled) return;
|
|
82
|
+
try {
|
|
83
|
+
const dir = dirname(this.storagePath);
|
|
84
|
+
if (!existsSync(dir)) {
|
|
85
|
+
mkdirSync(dir, { recursive: true });
|
|
86
|
+
}
|
|
87
|
+
// Bound retention
|
|
88
|
+
if (this.items.length > this.maxItems) {
|
|
89
|
+
this.items.sort((a, b) => b.updatedAt - a.updatedAt);
|
|
90
|
+
this.items = this.items.slice(0, this.maxItems);
|
|
91
|
+
}
|
|
92
|
+
const payload = {
|
|
93
|
+
schema: MEMORY_CONTRACT_VERSION,
|
|
94
|
+
projectRoot: this.projectRoot,
|
|
95
|
+
updatedAt: Date.now(),
|
|
96
|
+
count: this.items.length,
|
|
97
|
+
items: this.items,
|
|
98
|
+
};
|
|
99
|
+
writeFileSync(this.storagePath, JSON.stringify(payload, null, 2), 'utf8');
|
|
100
|
+
} catch {
|
|
101
|
+
// Storage failure must fail gracefully without halting the agent turn
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Records or updates a technical memory item.
|
|
107
|
+
*
|
|
108
|
+
* @param {Object} item
|
|
109
|
+
* @param {string} item.key - Canonical identifier for the technical fact
|
|
110
|
+
* @param {string} item.category - One of MEMORY_CATEGORIES
|
|
111
|
+
* @param {string} item.content - Detailed engineering note or decision
|
|
112
|
+
* @param {string[]} [item.tags] - Search tags or symbol references
|
|
113
|
+
* @param {string} [item.source] - Provenance file path or task identifier
|
|
114
|
+
* @returns {Object|null} The recorded memory item
|
|
115
|
+
*/
|
|
116
|
+
record({ key, category, content, tags = [], source = 'manual' }) {
|
|
117
|
+
if (!this.enabled) return null;
|
|
118
|
+
if (!key || typeof key !== 'string' || !content || typeof content !== 'string') {
|
|
119
|
+
throw new Error('Memory item requires non-empty "key" and "content" strings.');
|
|
120
|
+
}
|
|
121
|
+
const cat = MEMORY_CATEGORIES.includes(category) ? category : 'fact';
|
|
122
|
+
const contentHash = hashText(content);
|
|
123
|
+
const now = Date.now();
|
|
124
|
+
|
|
125
|
+
const existingIndex = this.items.findIndex(
|
|
126
|
+
(m) => m.key === key || (m.contentHash === contentHash && m.category === cat)
|
|
127
|
+
);
|
|
128
|
+
|
|
129
|
+
const memoryEntry = {
|
|
130
|
+
key: key.trim(),
|
|
131
|
+
category: cat,
|
|
132
|
+
content: content.trim(),
|
|
133
|
+
contentHash,
|
|
134
|
+
tags: Array.isArray(tags) ? [...new Set(tags.map((t) => String(t).trim()).filter(Boolean))] : [],
|
|
135
|
+
source: String(source).trim(),
|
|
136
|
+
createdAt: existingIndex >= 0 ? this.items[existingIndex].createdAt : now,
|
|
137
|
+
updatedAt: now,
|
|
138
|
+
accessCount: existingIndex >= 0 ? (this.items[existingIndex].accessCount || 0) + 1 : 1,
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
if (existingIndex >= 0) {
|
|
142
|
+
this.items[existingIndex] = memoryEntry;
|
|
143
|
+
} else {
|
|
144
|
+
this.items.unshift(memoryEntry);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
this.save();
|
|
148
|
+
return memoryEntry;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Retrieves relevant memory entries matching a query string, symbols, or category filter.
|
|
153
|
+
*
|
|
154
|
+
* @param {Object} options
|
|
155
|
+
* @param {string} [options.query] - Natural language search query or keywords
|
|
156
|
+
* @param {string} [options.category] - Filter by specific category
|
|
157
|
+
* @param {string[]} [options.symbols] - Related symbol names or file paths
|
|
158
|
+
* @param {number} [options.limit] - Max items to return
|
|
159
|
+
* @returns {Array<Object>} Relevant memory items sorted by score
|
|
160
|
+
*/
|
|
161
|
+
retrieve({ query = '', category = null, symbols = [], limit = 5 } = {}) {
|
|
162
|
+
if (!this.enabled || this.items.length === 0) return [];
|
|
163
|
+
|
|
164
|
+
const queryTokens = query
|
|
165
|
+
? query.toLowerCase().split(/[\s,._\-/]+/).filter((t) => t.length > 2)
|
|
166
|
+
: [];
|
|
167
|
+
const symbolTokens = Array.isArray(symbols)
|
|
168
|
+
? symbols.map((s) => String(s).toLowerCase().trim()).filter(Boolean)
|
|
169
|
+
: [];
|
|
170
|
+
|
|
171
|
+
const scored = this.items
|
|
172
|
+
.filter((item) => !category || item.category === category)
|
|
173
|
+
.map((item) => {
|
|
174
|
+
let score = 0;
|
|
175
|
+
const keyLower = item.key.toLowerCase();
|
|
176
|
+
const contentLower = item.content.toLowerCase();
|
|
177
|
+
const tagsLower = item.tags.map((t) => t.toLowerCase());
|
|
178
|
+
|
|
179
|
+
// Exact symbol match in key or tags carries high weight
|
|
180
|
+
for (const sym of symbolTokens) {
|
|
181
|
+
if (keyLower.includes(sym)) score += 10;
|
|
182
|
+
if (tagsLower.includes(sym)) score += 8;
|
|
183
|
+
if (contentLower.includes(sym)) score += 4;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
// Query token matches
|
|
187
|
+
for (const token of queryTokens) {
|
|
188
|
+
if (keyLower.includes(token)) score += 5;
|
|
189
|
+
if (tagsLower.includes(token)) score += 3;
|
|
190
|
+
if (contentLower.includes(token)) score += 1;
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Slight recency bias
|
|
194
|
+
const ageHours = (Date.now() - item.updatedAt) / (1000 * 60 * 60);
|
|
195
|
+
if (ageHours < 24) score += 1;
|
|
196
|
+
|
|
197
|
+
return { item, score };
|
|
198
|
+
})
|
|
199
|
+
.filter((entry) => (queryTokens.length === 0 && symbolTokens.length === 0) || entry.score > 0)
|
|
200
|
+
.sort((a, b) => b.score - a.score || b.item.updatedAt - a.item.updatedAt)
|
|
201
|
+
.slice(0, Math.max(1, limit))
|
|
202
|
+
.map((entry) => {
|
|
203
|
+
entry.item.accessCount = (entry.item.accessCount || 0) + 1;
|
|
204
|
+
return entry.item;
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
this.save();
|
|
208
|
+
return scored;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Deletes a specific memory entry by key.
|
|
213
|
+
*/
|
|
214
|
+
remove(key) {
|
|
215
|
+
if (!this.enabled) return false;
|
|
216
|
+
const initialLen = this.items.length;
|
|
217
|
+
this.items = this.items.filter((m) => m.key !== key);
|
|
218
|
+
if (this.items.length !== initialLen) {
|
|
219
|
+
this.save();
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
return false;
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Completely purges all stored memory for this project.
|
|
227
|
+
*/
|
|
228
|
+
clear() {
|
|
229
|
+
this.items = [];
|
|
230
|
+
this.save();
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Formats retrieved memories as compact Markdown for LLM prompt injection.
|
|
235
|
+
*/
|
|
236
|
+
formatForContext(retrievedItems) {
|
|
237
|
+
if (!Array.isArray(retrievedItems) || retrievedItems.length === 0) return '';
|
|
238
|
+
const lines = [
|
|
239
|
+
'<!-- AFYX-ENGINEERING-MEMORY:START -->',
|
|
240
|
+
'## Project Engineering Memory (Verified Local Facts)',
|
|
241
|
+
];
|
|
242
|
+
for (const mem of retrievedItems) {
|
|
243
|
+
lines.push(`- **[${mem.category.toUpperCase()}] ${mem.key}**: ${mem.content}`);
|
|
244
|
+
}
|
|
245
|
+
lines.push('<!-- AFYX-ENGINEERING-MEMORY:END -->');
|
|
246
|
+
return lines.join('\n');
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/**
|
|
251
|
+
* Factory helper for creating memory manager.
|
|
252
|
+
*/
|
|
253
|
+
export function createEngineeringMemory(options = {}) {
|
|
254
|
+
return new AfyxEngineeringMemory(options);
|
|
255
|
+
}
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
import crypto from 'node:crypto';
|
|
2
|
+
import fs from 'node:fs';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { StateCoordinator } from './coordination.js';
|
|
5
|
+
import { AceError, assertNonEmpty } from './errors.js';
|
|
6
|
+
|
|
7
|
+
const STATE_FORMAT = 'ace.state/v1';
|
|
8
|
+
const SESSION_FORMAT = 'ace.session/v1';
|
|
9
|
+
const MAX_STATE_METADATA_BYTES = 65_536;
|
|
10
|
+
const MAX_SESSION_METADATA_BYTES = 16_777_216;
|
|
11
|
+
const MAX_SESSION_CONTENT = 100_000;
|
|
12
|
+
const MAX_OBSERVATIONS_PER_CONTENT = 256;
|
|
13
|
+
const MAX_IDENTITY_BYTES = 512;
|
|
14
|
+
const MAX_CONTENT_BLOB_BYTES = 1_048_576;
|
|
15
|
+
const TEMP_UUID = '[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}';
|
|
16
|
+
const STATE_TEMP = new RegExp(`^state\\.json\\.[0-9]+\\.${TEMP_UUID}\\.tmp$`, 'i');
|
|
17
|
+
const SESSION_TEMP = new RegExp(`^session\\.json\\.[0-9]+\\.${TEMP_UUID}\\.tmp$`, 'i');
|
|
18
|
+
const CONTENT_TEMP = new RegExp(`^([0-9a-f]{64})\\.txt\\.[0-9]+\\.${TEMP_UUID}\\.tmp$`, 'i');
|
|
19
|
+
|
|
20
|
+
export const sha256 = (value) => crypto.createHash('sha256').update(value).digest('hex');
|
|
21
|
+
|
|
22
|
+
function jsonText(value, maxBytes) {
|
|
23
|
+
const text = `${JSON.stringify(value, null, 2)}\n`;
|
|
24
|
+
if (Buffer.byteLength(text, 'utf8') > maxBytes) {
|
|
25
|
+
throw new AceError('RESOURCE_LIMIT', `ACE metadata exceeds the ${maxBytes} byte limit`);
|
|
26
|
+
}
|
|
27
|
+
return text;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function atomicText(file, content) {
|
|
31
|
+
const temporary = `${file}.${process.pid}.${crypto.randomUUID()}.tmp`;
|
|
32
|
+
let handle;
|
|
33
|
+
try {
|
|
34
|
+
handle = fs.openSync(temporary, 'wx', 0o600);
|
|
35
|
+
fs.writeFileSync(handle, content, { encoding: 'utf8' });
|
|
36
|
+
fs.fsyncSync(handle);
|
|
37
|
+
fs.closeSync(handle);
|
|
38
|
+
handle = undefined;
|
|
39
|
+
fs.renameSync(temporary, file);
|
|
40
|
+
} finally {
|
|
41
|
+
if (handle !== undefined) fs.closeSync(handle);
|
|
42
|
+
fs.rmSync(temporary, { force: true });
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function atomicJson(file, value, maxBytes) {
|
|
47
|
+
atomicText(file, jsonText(value, maxBytes));
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function assertNoAliases(target) {
|
|
51
|
+
// Reject an aliased state root itself. Ancestors are intentionally not
|
|
52
|
+
// rejected: macOS commonly exposes /var as a system alias to /private/var.
|
|
53
|
+
if (fs.existsSync(target) && fs.lstatSync(target).isSymbolicLink()) {
|
|
54
|
+
throw new AceError('UNSAFE_STATE_PATH', `state path is a symbolic link: ${target}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function ensureDirectory(target) {
|
|
59
|
+
if (fs.existsSync(target)) {
|
|
60
|
+
const stat = fs.lstatSync(target);
|
|
61
|
+
if (stat.isSymbolicLink() || !stat.isDirectory()) {
|
|
62
|
+
throw new AceError('UNSAFE_STATE_PATH', `ACE directory is not an owned regular directory: ${target}`);
|
|
63
|
+
}
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
fs.mkdirSync(target, { recursive: true });
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
function assertRegularFile(target) {
|
|
70
|
+
const stat = fs.lstatSync(target);
|
|
71
|
+
if (stat.isSymbolicLink() || !stat.isFile()) {
|
|
72
|
+
throw new AceError('UNSAFE_STATE_PATH', `ACE file is not an owned regular file: ${target}`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function readContentFile(target) {
|
|
77
|
+
assertRegularFile(target);
|
|
78
|
+
if (fs.statSync(target).size > MAX_CONTENT_BLOB_BYTES) {
|
|
79
|
+
throw new AceError('RESOURCE_LIMIT', `stored content exceeds the ${MAX_CONTENT_BLOB_BYTES} byte limit`);
|
|
80
|
+
}
|
|
81
|
+
return fs.readFileSync(target, 'utf8');
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
export class ContextStore {
|
|
85
|
+
constructor({ stateDir, ownerId, sessionId, lockTimeoutMs, lockRetryMs } = {}) {
|
|
86
|
+
assertNonEmpty(stateDir, 'stateDir');
|
|
87
|
+
assertNonEmpty(ownerId, 'ownerId');
|
|
88
|
+
assertNonEmpty(sessionId, 'sessionId');
|
|
89
|
+
if (stateDir.includes('\0')) throw new AceError('UNSAFE_STATE_PATH', 'stateDir contains a NUL character');
|
|
90
|
+
if (Buffer.byteLength(stateDir, 'utf8') > 32_767) throw new AceError('RESOURCE_LIMIT', 'stateDir exceeds the 32767 byte limit');
|
|
91
|
+
if (Buffer.byteLength(ownerId, 'utf8') > MAX_IDENTITY_BYTES || Buffer.byteLength(sessionId, 'utf8') > MAX_IDENTITY_BYTES) {
|
|
92
|
+
throw new AceError('RESOURCE_LIMIT', `ownerId and sessionId are limited to ${MAX_IDENTITY_BYTES} bytes each`);
|
|
93
|
+
}
|
|
94
|
+
if (!path.isAbsolute(stateDir)) {
|
|
95
|
+
throw new AceError('UNSAFE_STATE_PATH', 'stateDir must be absolute');
|
|
96
|
+
}
|
|
97
|
+
this.stateDir = path.resolve(stateDir);
|
|
98
|
+
this.ownerHash = sha256(ownerId);
|
|
99
|
+
this.sessionHash = sha256(sessionId);
|
|
100
|
+
assertNoAliases(this.stateDir);
|
|
101
|
+
this.coordinator = new StateCoordinator({
|
|
102
|
+
stateDir: this.stateDir,
|
|
103
|
+
ownerHash: this.ownerHash,
|
|
104
|
+
lockTimeoutMs,
|
|
105
|
+
lockRetryMs,
|
|
106
|
+
});
|
|
107
|
+
ensureDirectory(this.stateDir);
|
|
108
|
+
this.coordinator.withLock(({ recovered }) => {
|
|
109
|
+
this.#recoverStateManifestTemporary();
|
|
110
|
+
this.#initialize();
|
|
111
|
+
if (recovered) this.#recoverOwnedTemporaries();
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
withExclusiveAccess(action) {
|
|
116
|
+
if (typeof action !== 'function') throw new AceError('INVALID_INPUT', 'exclusive action must be a function');
|
|
117
|
+
return this.coordinator.withLock(({ recovered }) => {
|
|
118
|
+
if (recovered) this.#recoverOwnedTemporaries();
|
|
119
|
+
return action();
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
#recoverStateManifestTemporary() {
|
|
124
|
+
const manifestPath = path.join(this.stateDir, 'state.json');
|
|
125
|
+
const temporaries = fs.readdirSync(this.stateDir).filter((entry) => STATE_TEMP.test(entry)).sort();
|
|
126
|
+
if (temporaries.length > 1) {
|
|
127
|
+
throw new AceError('INVALID_STATE', 'multiple interrupted state manifests require manual inspection');
|
|
128
|
+
}
|
|
129
|
+
if (temporaries.length === 0) return;
|
|
130
|
+
const temporary = path.join(this.stateDir, temporaries[0]);
|
|
131
|
+
const manifest = this.#readJson(temporary, 'INVALID_STATE', MAX_STATE_METADATA_BYTES);
|
|
132
|
+
if (manifest.format !== STATE_FORMAT || manifest.ownerHash !== this.ownerHash) {
|
|
133
|
+
throw new AceError('INVALID_STATE', 'interrupted state manifest is foreign or invalid');
|
|
134
|
+
}
|
|
135
|
+
if (fs.existsSync(manifestPath)) {
|
|
136
|
+
const committed = this.#readJson(manifestPath, 'INVALID_STATE', MAX_STATE_METADATA_BYTES);
|
|
137
|
+
if (committed.format !== STATE_FORMAT || committed.ownerHash !== this.ownerHash) {
|
|
138
|
+
throw new AceError('FOREIGN_STATE', 'state belongs to a different owner or format');
|
|
139
|
+
}
|
|
140
|
+
fs.unlinkSync(temporary);
|
|
141
|
+
} else {
|
|
142
|
+
fs.renameSync(temporary, manifestPath);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
#initialize() {
|
|
147
|
+
const manifestPath = path.join(this.stateDir, 'state.json');
|
|
148
|
+
if (fs.existsSync(manifestPath)) {
|
|
149
|
+
const manifest = this.#readJson(manifestPath, 'INVALID_STATE', MAX_STATE_METADATA_BYTES);
|
|
150
|
+
if (manifest.format !== STATE_FORMAT || manifest.ownerHash !== this.ownerHash) {
|
|
151
|
+
throw new AceError('FOREIGN_STATE', 'state belongs to a different owner or format');
|
|
152
|
+
}
|
|
153
|
+
} else {
|
|
154
|
+
const entries = fs.readdirSync(this.stateDir)
|
|
155
|
+
.filter((entry) => !this.coordinator.isCoordinationEntry(entry));
|
|
156
|
+
if (entries.length !== 0) {
|
|
157
|
+
throw new AceError('AMBIGUOUS_STATE', 'state directory is non-empty and has no ACE ownership manifest');
|
|
158
|
+
}
|
|
159
|
+
atomicJson(manifestPath, { format: STATE_FORMAT, ownerHash: this.ownerHash }, MAX_STATE_METADATA_BYTES);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
this.contentDir = path.join(this.stateDir, 'content');
|
|
163
|
+
this.sessionDir = path.join(this.stateDir, 'sessions', this.sessionHash);
|
|
164
|
+
ensureDirectory(this.contentDir);
|
|
165
|
+
ensureDirectory(path.dirname(this.sessionDir));
|
|
166
|
+
ensureDirectory(this.sessionDir);
|
|
167
|
+
this.sessionPath = path.join(this.sessionDir, 'session.json');
|
|
168
|
+
if (fs.existsSync(this.sessionPath)) {
|
|
169
|
+
this.#readSession();
|
|
170
|
+
} else {
|
|
171
|
+
atomicJson(this.sessionPath, {
|
|
172
|
+
format: SESSION_FORMAT,
|
|
173
|
+
ownerHash: this.ownerHash,
|
|
174
|
+
sessionHash: this.sessionHash,
|
|
175
|
+
content: [],
|
|
176
|
+
records: {},
|
|
177
|
+
}, MAX_SESSION_METADATA_BYTES);
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
#readJson(file, code, maxBytes) {
|
|
182
|
+
try {
|
|
183
|
+
assertRegularFile(file);
|
|
184
|
+
if (fs.statSync(file).size > maxBytes) {
|
|
185
|
+
throw new AceError('RESOURCE_LIMIT', `${path.basename(file)} exceeds the ${maxBytes} byte limit`);
|
|
186
|
+
}
|
|
187
|
+
return JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
188
|
+
} catch (error) {
|
|
189
|
+
if (error instanceof AceError) throw error;
|
|
190
|
+
throw new AceError(code, `ACE metadata is unreadable: ${path.basename(file)}`);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
#readSession() {
|
|
195
|
+
const session = this.#readJson(this.sessionPath, 'INVALID_SESSION', MAX_SESSION_METADATA_BYTES);
|
|
196
|
+
return this.#validateSession(session);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
#validateSession(session) {
|
|
200
|
+
if (session.format !== SESSION_FORMAT || session.ownerHash !== this.ownerHash || session.sessionHash !== this.sessionHash
|
|
201
|
+
|| !Array.isArray(session.content) || !session.records || typeof session.records !== 'object' || Array.isArray(session.records)) {
|
|
202
|
+
throw new AceError('INVALID_SESSION', 'session metadata is invalid or does not match this owner/session');
|
|
203
|
+
}
|
|
204
|
+
if (session.content.length > MAX_SESSION_CONTENT) {
|
|
205
|
+
throw new AceError('RESOURCE_LIMIT', `session exceeds the ${MAX_SESSION_CONTENT} content limit`);
|
|
206
|
+
}
|
|
207
|
+
const known = new Set();
|
|
208
|
+
for (const digest of session.content) {
|
|
209
|
+
if (typeof digest !== 'string' || !/^[0-9a-f]{64}$/.test(digest) || known.has(digest)) {
|
|
210
|
+
throw new AceError('INVALID_SESSION', 'session content identities are malformed or duplicated');
|
|
211
|
+
}
|
|
212
|
+
known.add(digest);
|
|
213
|
+
}
|
|
214
|
+
for (const [digest, observations] of Object.entries(session.records)) {
|
|
215
|
+
if (!known.has(digest) || !Array.isArray(observations) || observations.length > MAX_OBSERVATIONS_PER_CONTENT) {
|
|
216
|
+
throw new AceError('INVALID_SESSION', 'session provenance records are malformed');
|
|
217
|
+
}
|
|
218
|
+
for (const observation of observations) {
|
|
219
|
+
if (!observation || typeof observation !== 'object' || typeof observation.id !== 'string'
|
|
220
|
+
|| typeof observation.classification !== 'string' || !observation.provenance
|
|
221
|
+
|| typeof observation.provenance !== 'object' || Array.isArray(observation.provenance)) {
|
|
222
|
+
throw new AceError('INVALID_SESSION', 'session provenance observation is malformed');
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
return session;
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
#recoverOwnedTemporaries() {
|
|
230
|
+
for (const entry of fs.readdirSync(this.contentDir).sort()) {
|
|
231
|
+
const match = CONTENT_TEMP.exec(entry);
|
|
232
|
+
if (!match) continue;
|
|
233
|
+
const temporary = path.join(this.contentDir, entry);
|
|
234
|
+
const content = readContentFile(temporary);
|
|
235
|
+
const digest = match[1].toLowerCase();
|
|
236
|
+
if (sha256(content) !== digest) {
|
|
237
|
+
throw new AceError('CONTENT_INTEGRITY', `interrupted content artifact failed integrity validation: ${entry}`);
|
|
238
|
+
}
|
|
239
|
+
const target = path.join(this.contentDir, `${digest}.txt`);
|
|
240
|
+
if (fs.existsSync(target)) {
|
|
241
|
+
const committed = readContentFile(target);
|
|
242
|
+
if (committed !== content || sha256(committed) !== digest) {
|
|
243
|
+
throw new AceError('CONTENT_INTEGRITY', 'committed content conflicts with an interrupted artifact');
|
|
244
|
+
}
|
|
245
|
+
fs.unlinkSync(temporary);
|
|
246
|
+
} else {
|
|
247
|
+
fs.renameSync(temporary, target);
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
for (const entry of fs.readdirSync(this.sessionDir).sort()) {
|
|
252
|
+
if (!SESSION_TEMP.test(entry)) continue;
|
|
253
|
+
const temporary = path.join(this.sessionDir, entry);
|
|
254
|
+
const session = this.#readJson(temporary, 'INVALID_SESSION', MAX_SESSION_METADATA_BYTES);
|
|
255
|
+
this.#validateSession(session);
|
|
256
|
+
fs.unlinkSync(temporary);
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
knownDigests() {
|
|
261
|
+
return this.withExclusiveAccess(() => new Set(this.#readSession().content));
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
snapshotAndPersist(segments) {
|
|
265
|
+
return this.withExclusiveAccess(() => {
|
|
266
|
+
const knownBefore = new Set(this.#readSession().content);
|
|
267
|
+
this.#persist(segments);
|
|
268
|
+
return knownBefore;
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
persist(segments) {
|
|
273
|
+
return this.withExclusiveAccess(() => this.#persist(segments));
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
#persist(segments) {
|
|
277
|
+
const session = this.#readSession();
|
|
278
|
+
const known = new Set(session.content);
|
|
279
|
+
const records = { ...session.records };
|
|
280
|
+
const pending = [];
|
|
281
|
+
for (const segment of segments) {
|
|
282
|
+
const { content } = segment;
|
|
283
|
+
const digest = sha256(content);
|
|
284
|
+
known.add(digest);
|
|
285
|
+
const observation = {
|
|
286
|
+
id: segment.id,
|
|
287
|
+
classification: segment.classification,
|
|
288
|
+
provenance: segment.provenance,
|
|
289
|
+
};
|
|
290
|
+
const observations = Array.isArray(records[digest]) ? records[digest] : [];
|
|
291
|
+
const encoded = JSON.stringify(observation);
|
|
292
|
+
if (!observations.some((item) => JSON.stringify(item) === encoded)) {
|
|
293
|
+
if (observations.length >= MAX_OBSERVATIONS_PER_CONTENT) {
|
|
294
|
+
throw new AceError('RESOURCE_LIMIT', `content provenance exceeds the ${MAX_OBSERVATIONS_PER_CONTENT} observation limit`);
|
|
295
|
+
}
|
|
296
|
+
observations.push(observation);
|
|
297
|
+
}
|
|
298
|
+
records[digest] = observations;
|
|
299
|
+
pending.push({ content, digest, target: path.join(this.contentDir, `${digest}.txt`) });
|
|
300
|
+
}
|
|
301
|
+
if (known.size > MAX_SESSION_CONTENT) {
|
|
302
|
+
throw new AceError('RESOURCE_LIMIT', `session exceeds the ${MAX_SESSION_CONTENT} content limit`);
|
|
303
|
+
}
|
|
304
|
+
const nextSession = { ...session, content: [...known].sort(), records };
|
|
305
|
+
jsonText(nextSession, MAX_SESSION_METADATA_BYTES);
|
|
306
|
+
const missing = [];
|
|
307
|
+
for (const { content, digest, target } of pending) {
|
|
308
|
+
if (fs.existsSync(target)) {
|
|
309
|
+
const existing = readContentFile(target);
|
|
310
|
+
if (sha256(existing) !== digest || existing !== content) {
|
|
311
|
+
throw new AceError('CONTENT_INTEGRITY', 'stored original content failed integrity validation');
|
|
312
|
+
}
|
|
313
|
+
} else {
|
|
314
|
+
missing.push({ content, target });
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
for (const { content, target } of missing) atomicText(target, content);
|
|
318
|
+
atomicJson(this.sessionPath, nextSession, MAX_SESSION_METADATA_BYTES);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
reference(content) {
|
|
322
|
+
return `ace:v1:${this.ownerHash.slice(0, 16)}:${this.sessionHash.slice(0, 16)}:${sha256(content)}`;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
retrieve(reference) {
|
|
326
|
+
return this.withExclusiveAccess(() => this.#retrieve(reference));
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
#retrieve(reference) {
|
|
330
|
+
const match = /^ace:v1:([0-9a-f]{16}):([0-9a-f]{16}):([0-9a-f]{64})$/.exec(reference);
|
|
331
|
+
if (!match) throw new AceError('INVALID_REFERENCE', 'reference is not an ACE v1 reference');
|
|
332
|
+
if (match[1] !== this.ownerHash.slice(0, 16) || match[2] !== this.sessionHash.slice(0, 16)) {
|
|
333
|
+
throw new AceError('REFERENCE_BOUNDARY', 'reference belongs to a different owner or session');
|
|
334
|
+
}
|
|
335
|
+
const known = new Set(this.#readSession().content);
|
|
336
|
+
if (!known.has(match[3])) throw new AceError('REFERENCE_BOUNDARY', 'reference is not owned by this session');
|
|
337
|
+
const target = path.join(this.contentDir, `${match[3]}.txt`);
|
|
338
|
+
let content;
|
|
339
|
+
try {
|
|
340
|
+
content = readContentFile(target);
|
|
341
|
+
} catch (error) {
|
|
342
|
+
if (error instanceof AceError) throw error;
|
|
343
|
+
throw new AceError('MISSING_ORIGINAL', 'referenced original content is unavailable');
|
|
344
|
+
}
|
|
345
|
+
if (sha256(content) !== match[3]) {
|
|
346
|
+
throw new AceError('CONTENT_INTEGRITY', 'referenced original content failed integrity validation');
|
|
347
|
+
}
|
|
348
|
+
return content;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
retrieveRecord(reference) {
|
|
352
|
+
return this.withExclusiveAccess(() => {
|
|
353
|
+
const content = this.#retrieve(reference);
|
|
354
|
+
const digest = sha256(content);
|
|
355
|
+
const session = this.#readSession();
|
|
356
|
+
return {
|
|
357
|
+
reference,
|
|
358
|
+
digest,
|
|
359
|
+
content,
|
|
360
|
+
observations: session.records[digest] ?? [],
|
|
361
|
+
};
|
|
362
|
+
});
|
|
363
|
+
}
|
|
364
|
+
}
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import { AfyxContextEngine } from '../src/engine.js';
|
|
3
|
+
import { ContextStore } from '../src/storage.js';
|
|
4
|
+
|
|
5
|
+
const sleeper = new Int32Array(new SharedArrayBuffer(4));
|
|
6
|
+
const [mode, stateDir, ownerId, sessionId, readyPath, gatePath, outputPath, payload = '', id = 'worker', timeout = '5000'] = process.argv.slice(2);
|
|
7
|
+
|
|
8
|
+
function waitForGate() {
|
|
9
|
+
fs.writeFileSync(readyPath, `${process.pid}\n`, { flag: 'wx' });
|
|
10
|
+
const deadline = Date.now() + 15_000;
|
|
11
|
+
while (!fs.existsSync(gatePath)) {
|
|
12
|
+
if (Date.now() >= deadline) throw new Error('coordination fixture gate timed out');
|
|
13
|
+
Atomics.wait(sleeper, 0, 0, 10);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
try {
|
|
18
|
+
if (mode === 'hold') {
|
|
19
|
+
const store = new ContextStore({ stateDir, ownerId, sessionId, lockTimeoutMs: Number(timeout) });
|
|
20
|
+
store.withExclusiveAccess(() => {
|
|
21
|
+
waitForGate();
|
|
22
|
+
Atomics.wait(sleeper, 0, 0, 30_000);
|
|
23
|
+
});
|
|
24
|
+
} else if (mode === 'interrupt-write') {
|
|
25
|
+
const engine = new AfyxContextEngine({ stateDir, ownerId, sessionId, lockTimeoutMs: Number(timeout) });
|
|
26
|
+
const renameSync = fs.renameSync;
|
|
27
|
+
fs.renameSync = (source, destination) => {
|
|
28
|
+
if (destination === engine.store.sessionPath) {
|
|
29
|
+
fs.writeFileSync(readyPath, `${process.pid}\n`, { flag: 'wx' });
|
|
30
|
+
Atomics.wait(sleeper, 0, 0, 30_000);
|
|
31
|
+
}
|
|
32
|
+
return renameSync(source, destination);
|
|
33
|
+
};
|
|
34
|
+
engine.reduce({ segments: [{ id, content: payload }] });
|
|
35
|
+
} else if (mode === 'reduce') {
|
|
36
|
+
waitForGate();
|
|
37
|
+
const engine = new AfyxContextEngine({ stateDir, ownerId, sessionId, lockTimeoutMs: Number(timeout) });
|
|
38
|
+
const result = engine.reduce({ segments: [{ id, content: payload }] });
|
|
39
|
+
fs.writeFileSync(outputPath, JSON.stringify({ ok: true, result }), { flag: 'wx' });
|
|
40
|
+
} else {
|
|
41
|
+
throw new Error(`unknown coordination fixture mode: ${mode}`);
|
|
42
|
+
}
|
|
43
|
+
} catch (error) {
|
|
44
|
+
if (outputPath) {
|
|
45
|
+
fs.writeFileSync(outputPath, JSON.stringify({
|
|
46
|
+
ok: false,
|
|
47
|
+
code: error?.code ?? 'INTERNAL',
|
|
48
|
+
message: error?.message ?? String(error),
|
|
49
|
+
}), { flag: 'wx' });
|
|
50
|
+
}
|
|
51
|
+
process.exitCode = 2;
|
|
52
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from . import models
|
package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from . import sale_order
|
package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
from . import models
|