afyx-engineering-kit 0.1.0-alpha.4 → 0.1.0-alpha.6

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 (33) hide show
  1. package/.afyx-source-revision +1 -1
  2. package/README.md +12 -0
  3. package/afyx-graph/engine/release/RELEASE-MANIFEST.json +3 -3
  4. package/afyx-graph/engine/release/SHA256SUMS +2 -2
  5. package/afyx-graph/engine/release/afyx-graph-linux-x64.tar.gz +0 -0
  6. package/afyx-graph/engine/release/afyx-graph-win32-x64.zip +0 -0
  7. package/bin/afyx-engineering-kit.mjs +22 -1
  8. package/install.ps1 +84 -13
  9. package/install.sh +81 -1
  10. package/package.json +2 -1
  11. package/scripts/afyx-install-backend.mjs +46 -0
  12. package/scripts/afyx-install-contract.mjs +139 -0
  13. package/scripts/afyx-midnight-circuit.mjs +328 -0
  14. package/scripts/afyx-npm-installer.mjs +27 -5
  15. package/scripts/install-afyx-graph.ps1 +75 -29
  16. package/scripts/lib/AfyxPlatform.ps1 +133 -0
  17. package/scripts/lib/AfyxPlatform.psm1 +6 -0
  18. package/scripts/package-release-zip.ps1 +124 -0
  19. package/scripts/validate-release-zip-graph.mjs +55 -0
  20. package/verify.ps1 +25 -9
  21. package/verify.sh +9 -1
  22. package/afyx-context/test-fixtures/coordination-worker.mjs +0 -52
  23. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__init__.py +0 -1
  24. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__manifest__.py +0 -4
  25. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/__init__.py +0 -1
  26. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/sale_order.py +0 -5
  27. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__init__.py +0 -1
  28. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__manifest__.py +0 -10
  29. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/__init__.py +0 -2
  30. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order.py +0 -20
  31. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order_audit.py +0 -11
  32. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/security/ir.model.access.csv +0 -2
  33. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/views/sale_order_views.xml +0 -14
@@ -0,0 +1,328 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { readFileSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import readline from 'node:readline';
5
+ import { PACKAGE_ROOT } from './afyx-npm-installer.mjs';
6
+ import { createBackendAdapter, summarizeExecution } from './afyx-install-backend.mjs';
7
+
8
+ const stages = ['DETECT', 'SELECT', 'CONFIGURE', 'REVIEW / APPLY', 'FINISH'];
9
+ const supported = ['antigravity', 'claude', 'codex'];
10
+
11
+ export function terminalMode({ input = process.stdin, output = process.stdout, env = process.env, requested = 'auto' } = {}) {
12
+ const interactive = Boolean(input.isTTY && output.isTTY && !env.CI);
13
+ const ansi = interactive && !env.NO_COLOR && !env.AFYX_PLAIN_OUTPUT && env.TERM !== 'dumb' &&
14
+ (output.columns || 80) >= 80 && (output.rows || 24) >= 24;
15
+ if (requested === 'tui' && !ansi) throw new Error('--ui tui requires an interactive ANSI terminal at least 80 columns by 24 rows. Use --ui plain.');
16
+ return requested === 'plain' ? 'plain' : ansi ? 'tui' : 'plain';
17
+ }
18
+
19
+ export function discoverHosts(pkgRoot = PACKAGE_ROOT) {
20
+ try {
21
+ const raw = execFileSync(process.execPath, [join(pkgRoot, 'scripts', 'afyx-provider-inventory.mjs'), '--json'], { encoding: 'utf8', timeout: 10000 });
22
+ return JSON.parse(raw).filter((entry) => supported.includes(entry.id));
23
+ } catch { return []; }
24
+ }
25
+
26
+ export function providerSelectable(entry, platform = process.platform) {
27
+ const types = new Set((entry.products || []).map((product) => product.type));
28
+ if (entry.id === 'antigravity') return types.has('CLI') || (platform === 'win32' && types.has('IDE/Desktop'));
29
+ if (entry.id === 'codex' || entry.id === 'claude') return types.has('CLI') || types.has('VS Code Extension');
30
+ return false;
31
+ }
32
+
33
+ export function presetComponents(preset, selected = [], pkgRoot = PACKAGE_ROOT) {
34
+ const contract = JSON.parse(readFileSync(join(pkgRoot, 'scripts', 'components.json'), 'utf8'));
35
+ return contract.components.filter((component) => preset === 'custom'
36
+ ? selected.includes(component.id)
37
+ : component.presets.split(';').includes(preset)).map((component) => component.id);
38
+ }
39
+
40
+ export function runtimeSupport(preset, platform = process.platform, arch = process.arch) {
41
+ if (preset !== 'full') return { supported: true, reason: '' };
42
+ if (platform === 'darwin') return { supported: false, reason: 'Full requires a verified macOS Graph archive; choose Recommended or Minimal.' };
43
+ if (arch !== 'x64') return { supported: false, reason: `Full Graph archive is unavailable for ${platform}/${arch}.` };
44
+ return { supported: true, reason: '' };
45
+ }
46
+
47
+ function fit(value, width) {
48
+ const text = String(value).replace(/[\r\n\t]/g, ' ');
49
+ return text.length > width ? `${text.slice(0, Math.max(0, width - 1))}…` : text;
50
+ }
51
+
52
+ function wrapLines(lines, inner) {
53
+ return lines.flatMap((line) => {
54
+ const text = String(line).replace(/[\r\n\t]/g, ' ');
55
+ if (!text) return [''];
56
+ const chunks = [];
57
+ for (let index = 0; index < text.length; index += inner) chunks.push(text.slice(index, index + inner));
58
+ return chunks;
59
+ });
60
+ }
61
+
62
+ function panel(title, lines, width, limit, offset = 0) {
63
+ const inner = Math.max(16, width - 4);
64
+ const top = `┌ ${fit(title, inner)} ${'─'.repeat(Math.max(0, inner - title.length))}┐`;
65
+ let wrapped = wrapLines(lines, inner);
66
+ if (limit && wrapped.length > limit) {
67
+ const start = Math.max(0, Math.min(offset, wrapped.length - Math.max(1, limit - 1)));
68
+ const total = wrapped.length;
69
+ wrapped = [...wrapped.slice(start, start + Math.max(1, limit - 1)), fit(`Tab: focus activity; ↑/↓ scroll (${start + 1}/${total})`, inner)];
70
+ }
71
+ return [top, ...wrapped.map((line) => `│ ${line.padEnd(inner)} │`), `└${'─'.repeat(inner + 2)}┘`];
72
+ }
73
+
74
+ export function renderFrame({ stage = 0, providers = [], providerSummary, selection = [], activity = [], width = 80, height = 24, activityOffset = 0, hint = '' } = {}) {
75
+ const safeWidth = Math.max(40, width);
76
+ const stepLine = stages.map((name, index) => `${index + 1} ${name}${index === stage ? ' ●' : ''}`).join(' → ');
77
+ const providerLines = providerSummary || (providers.length ? providers.flatMap((entry) => {
78
+ const products = (entry.products || []).map((product) => `${product.type}${product.version ? ` ${product.version}` : ''}`);
79
+ const compact = `${entry.name}: ${products.join(', ') || 'not detected'}`;
80
+ if (safeWidth < 112 && compact.length <= safeWidth - 4) return [compact];
81
+ return [`${entry.name}: ${products.length ? 'detected' : 'not detected'}`, ...products.map((product) => ` ${product}`)];
82
+ }) : ['No supported provider detected']);
83
+ let body;
84
+ if (safeWidth >= 112) {
85
+ const columnWidth = Math.floor((safeWidth - 4) / 3);
86
+ const panelLimit = Math.max(3, height - 8);
87
+ const pad = (lines) => [...lines, ...Array(Math.max(0, panelLimit - lines.length)).fill('')];
88
+ const columns = [
89
+ panel('PROVIDERS / HOST', pad(providerLines), columnWidth, panelLimit),
90
+ panel('SELECTION / STATUS', pad(selection), columnWidth, panelLimit),
91
+ panel('PLAN / ACTIVITY', pad(activity), columnWidth, panelLimit, activityOffset),
92
+ ];
93
+ body = columns[0].map((_, index) => columns.map((column) => column[index]).join(' '));
94
+ } else {
95
+ const activityLimit = Math.max(3, height - 14 - wrapLines(providerLines, safeWidth - 4).length - wrapLines(selection, safeWidth - 4).length);
96
+ body = [panel('PROVIDERS / HOST', providerLines, safeWidth), panel('SELECTION / STATUS', selection, safeWidth), panel('PLAN / ACTIVITY', activity, safeWidth, activityLimit, activityOffset)].flatMap((lines) => [...lines, '']);
97
+ }
98
+ return [
99
+ 'AFYX / ENGINEERING KIT',
100
+ 'MIDNIGHT CIRCUIT | ALPHA INSTALLER',
101
+ fit(stepLine, safeWidth),
102
+ '',
103
+ ...body,
104
+ fit(hint, safeWidth),
105
+ ].join('\n');
106
+ }
107
+
108
+ async function choose({ input, output, frame, options, selected = 0, multiple = false }) {
109
+ readline.emitKeypressEvents(input);
110
+ input.setRawMode(true);
111
+ input.resume();
112
+ const checks = new Set();
113
+ let cursor = selected;
114
+ let activityOffset = 0;
115
+ let activityFocus = false;
116
+ const tooSmall = () => (output.columns || 80) < 80 || (output.rows || 24) < 24;
117
+ const draw = () => {
118
+ if (tooSmall()) {
119
+ output.write('\x1b[H\x1b[0JResize the terminal to at least 80 columns by 24 rows. Esc cancels safely.\n');
120
+ return;
121
+ }
122
+ const capacity = Math.max(3, Math.min(8, (output.rows || 24) - 21));
123
+ const start = Math.max(0, Math.min(cursor - Math.floor(capacity / 2), options.length - capacity));
124
+ const rows = options.slice(start, start + capacity).map((option, offset) => {
125
+ const index = start + offset;
126
+ return `${index === cursor ? '›' : ' '} ${multiple ? checks.has(index) ? '[x]' : '[ ]' : index === cursor ? '●' : '○'} ${option.label}`;
127
+ });
128
+ const screen = frame(rows, cursor, { activityOffset, activityFocus })
129
+ .replace(/^›[^\n]*/gm, (line) => `\x1b[1;36m${line}\x1b[0m`)
130
+ .replace(/\b(PASS|FAILED|SKIPPED|NOT SUPPORTED)\b/g, (status) => `\x1b[${status === 'PASS' ? '32' : status === 'FAILED' ? '31' : '33'}m${status}\x1b[0m`);
131
+ output.write(`\x1b[H\x1b[0J${screen}`);
132
+ };
133
+ draw();
134
+ try {
135
+ return await new Promise((resolve, reject) => {
136
+ const onKey = (_text, key = {}) => {
137
+ if (key.ctrl && key.name === 'c') { cleanup(); reject(new Error('Installer canceled (Ctrl+C).')); return; }
138
+ if (key.name === 'escape') { cleanup(); resolve(null); return; }
139
+ if (tooSmall()) return;
140
+ if (key.name === 'tab' || key.name === 'left' || key.name === 'right') activityFocus = !activityFocus;
141
+ else if (activityFocus && (key.name === 'up' || key.name === 'k')) activityOffset = Math.max(0, activityOffset - 1);
142
+ else if (activityFocus && (key.name === 'down' || key.name === 'j')) activityOffset++;
143
+ else if (key.name === 'up' || key.name === 'k') { cursor = (cursor - 1 + options.length) % options.length; activityOffset = 0; }
144
+ else if (key.name === 'down' || key.name === 'j') { cursor = (cursor + 1) % options.length; activityOffset = 0; }
145
+ else if (multiple && key.name === 'space') { checks.has(cursor) ? checks.delete(cursor) : checks.add(cursor); }
146
+ else if (key.name === 'return') { if (activityFocus) activityFocus = false; else { cleanup(); resolve(multiple ? [...checks].map((index) => options[index].id) : options[cursor].id); return; } }
147
+ draw();
148
+ };
149
+ const onResize = () => draw();
150
+ const onEnd = () => { cleanup(); reject(new Error('Terminal input closed before confirmation.')); };
151
+ const onTerm = () => { cleanup(); reject(new Error('Installer interrupted (SIGTERM).')); };
152
+ const cleanup = () => {
153
+ input.off('keypress', onKey);
154
+ input.off('end', onEnd);
155
+ output.off('resize', onResize);
156
+ process.off('SIGTERM', onTerm);
157
+ };
158
+ input.on('keypress', onKey);
159
+ input.on('end', onEnd);
160
+ output.on('resize', onResize);
161
+ process.on('SIGTERM', onTerm);
162
+ });
163
+ } finally {
164
+ input.setRawMode(false);
165
+ input.pause();
166
+ output.write('\n');
167
+ }
168
+ }
169
+
170
+ export async function runMidnightCircuit({ input = process.stdin, output = process.stdout, pkgRoot = PACKAGE_ROOT, platform = process.platform, arch = process.arch, hosts, options = {}, backend = createBackendAdapter({ platform, pkgRoot }) } = {}) {
171
+ const providers = hosts ?? discoverHosts(pkgRoot);
172
+ const available = providers.filter((entry) => providerSelectable(entry, platform)).map((entry) => entry.id);
173
+ const frame = (stage, selection, activity, hint, view = {}) => renderFrame({ stage, providers,
174
+ providerSummary: stage >= 3 ? [`Selected: ${provider.join(', ') || 'skipped'}; scope: ${scope}`] : undefined,
175
+ selection, activity, width: output.columns || 80, height: output.rows || 24, ...view,
176
+ hint: `${hint}${view.activityFocus ? ' [ACTIVITY FOCUS]' : ''}` });
177
+ let providerMode = available.length ? 'all' : 'skip';
178
+ let preset = 'recommended';
179
+ let provider = [];
180
+ let scope = 'global';
181
+ let custom = [];
182
+ let step = 0;
183
+ let reviewedPlan;
184
+ let reviewNotice = '';
185
+ const backendOptions = () => ({ ...options, preset, provider: provider.join(','), providerScope: scope,
186
+ customComponents: custom, skipProviderConfiguration: provider.length === 0, nonInteractive: true });
187
+ const selectedComponents = () => presetComponents(preset, custom, pkgRoot)
188
+ .filter((id) => id !== 'codex-usage-tracking' || (platform === 'win32' && provider.includes('codex')));
189
+ output.write('\x1b[2J\x1b[H');
190
+ while (true) {
191
+ if (step === 0) {
192
+ const result = await choose({ input, output, frame: (rows) => frame(0, rows, ['Inspecting supported host installations.', 'No configuration changes before confirmation.'], 'Enter: continue Esc: cancel Ctrl+C: cancel'), options: [{ id: 'continue', label: 'Continue to selection' }] });
193
+ if (result === null) return null;
194
+ step = 1;
195
+ } else if (step === 1) {
196
+ const options = [
197
+ { id: 'all', label: `All detected (${available.join(', ') || 'none'})` },
198
+ { id: 'recommended', label: 'Recommended provider' },
199
+ { id: 'custom', label: 'Custom provider selection' },
200
+ { id: 'skip', label: 'Skip provider integration' },
201
+ ];
202
+ const chosen = await choose({ input, output, frame: (rows) => frame(1, rows, ['Provider selection is separate from component installation.'], '↑/↓: move Enter: choose Esc: back'), options, selected: options.findIndex((x) => x.id === providerMode) });
203
+ if (chosen === null) { step = 0; continue; }
204
+ providerMode = chosen;
205
+ if (chosen === 'custom' && available.length) {
206
+ const customHosts = await choose({ input, output, frame: (rows) => frame(1, rows, ['Space: toggle available providers.'], '↑/↓: move Space: toggle Enter: confirm Esc: back'), options: providers.filter((entry) => providerSelectable(entry, platform)).map((entry) => ({ id: entry.id, label: entry.name })), multiple: true });
207
+ if (customHosts === null) continue;
208
+ provider = customHosts;
209
+ } else provider = chosen === 'skip' ? [] : chosen === 'recommended' ? available.slice(0, 1) : [...available];
210
+ step = 2;
211
+ } else if (step === 2) {
212
+ const choices = ['recommended', 'minimal', 'full', 'custom'].map((id) => ({ id, label: `${id[0].toUpperCase()}${id.slice(1)} — ${id === 'full' ? 'all applicable components' : id === 'custom' ? 'select exact components' : id === 'recommended' ? 'core skills + Engineering Expert' : 'core engineering skills'}` }));
213
+ const chosen = await choose({ input, output, frame: (rows) => frame(2, rows, ['Choose a component preset.'], '↑/↓: move Enter: choose Esc: back'), options: choices, selected: choices.findIndex((x) => x.id === preset) });
214
+ if (chosen === null) { step = 1; continue; }
215
+ preset = chosen;
216
+ const support = runtimeSupport(preset, platform, arch);
217
+ if (!support.supported) { output.write(`${support.reason}\n`); continue; }
218
+ if (preset === 'custom') {
219
+ const all = JSON.parse(readFileSync(join(pkgRoot, 'scripts', 'components.json'), 'utf8')).components
220
+ .filter((entry) => (entry.platforms === 'all' || (platform === 'win32' && entry.platforms === 'windows')) &&
221
+ (entry.id !== 'codex-usage-tracking' || provider.includes('codex')));
222
+ const selected = await choose({ input, output, frame: (rows) => frame(2, rows, ['Space: toggle components.'], '↑/↓: move Space: toggle Enter: confirm Esc: back'), options: all.map((entry) => ({ id: entry.id, label: entry.name || entry.id })), multiple: true });
223
+ if (selected === null || selected.length === 0) continue;
224
+ if (selected.includes('afyx-graph') && !runtimeSupport('full', platform, arch).supported) {
225
+ output.write(`${runtimeSupport('full', platform, arch).reason}\n`);
226
+ continue;
227
+ }
228
+ custom = selected;
229
+ }
230
+ step = 3;
231
+ } else if (step === 3) {
232
+ const scopeOptions = [{ id: 'global', label: 'Global provider scope' }];
233
+ if (!provider.includes('codex')) scopeOptions.push({ id: 'workspace', label: 'Workspace provider scope' });
234
+ const chosen = await choose({ input, output, frame: (rows) => frame(2, rows, [`Preset: ${preset}`, `Components: ${selectedComponents().join(', ')}`, `Provider: ${provider.join(', ') || 'skipped'}`], '↑/↓: move Enter: choose Esc: back'), options: scopeOptions, selected: Math.max(0, scopeOptions.findIndex((item) => item.id === scope)) });
235
+ if (chosen === null) { step = 2; continue; }
236
+ scope = chosen;
237
+ step = 4;
238
+ } else if (step === 4) {
239
+ output.write(`\x1b[H\x1b[0J${frame(3, ['Reading the backend installation plan…'], ['Read-only inspection; no installation changes yet.'], '')}`);
240
+ reviewedPlan = await backend.plan(backendOptions());
241
+ const items = reviewedPlan.components;
242
+ const choices = items.map((item) => ({ id: item.id, label: `${item.name}: ${item.backendAction.toUpperCase()} (${item.currentState})` }));
243
+ choices.push({ id: 'apply', label: 'Apply exactly this reviewed plan' }, { id: 'cancel', label: 'Cancel without changes' });
244
+ const confirmation = await choose({ input, output, frame: (rows, cursor, view) => {
245
+ const item = items[cursor];
246
+ const details = item ? [
247
+ `${item.id}: current=${item.currentState}; desired=${item.desired}; action=${item.backendAction}`,
248
+ `Target: ${item.target}`,
249
+ ...(reviewedPlan.additionalTargets || []).filter((target) => target.id === item.id).map((target) => `Provider target: ${target.target}`),
250
+ `Ownership: ${item.ownership}; platform: ${item.compatibility}`,
251
+ `Version: ${item.version || 'none'} → ${item.availableVersion || 'n/a'}; ${item.detail}`,
252
+ `Prerequisites: ${(item.prerequisites || []).map((requirement) => requirement.key).join(', ') || 'none declared'}`,
253
+ ] : [reviewNotice || 'Backend state and owned files are fingerprinted before confirmation.',
254
+ ...(reviewedPlan.blockers || []).map((reason) => `BLOCK: ${reason}`),
255
+ ...items.filter((entry) => entry.desired && entry.backendAction === 'blocked').map((entry) => `BLOCK: ${entry.name}: ${entry.detail}`)];
256
+ return frame(3, rows, details, '↑/↓: inspect Tab: focus activity Enter: choose Esc: back', view);
257
+ }, options: choices, selected: items.length });
258
+ if (confirmation === null) { step = 3; continue; }
259
+ if (confirmation === 'cancel') return null;
260
+ if (confirmation !== 'apply') continue;
261
+ if ((reviewedPlan.blockers || []).length || items.some((item) => item.desired && item.backendAction === 'blocked')) {
262
+ reviewNotice = 'The backend plan is BLOCKED. Resolve the displayed ownership/prerequisite issue first.';
263
+ continue;
264
+ }
265
+ output.write(`\x1b[H\x1b[0J${frame(3, ['Revalidating the reviewed plan…'], ['Owned program files and provider configuration must still match.'], '')}`);
266
+ const currentPlan = await backend.plan(backendOptions());
267
+ if (currentPlan.fingerprint !== reviewedPlan.fingerprint) {
268
+ reviewNotice = 'PLAN CHANGED: installation state changed. Inspect and confirm the updated plan.';
269
+ continue;
270
+ }
271
+ break;
272
+ }
273
+ }
274
+ output.write(`\x1b[2J\x1b[H${frame(3, ['Applying confirmed plan…'], ['Platform installer output follows.'], '')}\n`);
275
+ const finish = async (exitCode) => {
276
+ try {
277
+ output.write(`\x1b[H\x1b[0J${frame(4, ['Verifying installed components…'], [`Installer exit: ${exitCode}; awaiting backend verification.`], '')}`);
278
+ const actual = await backend.plan(backendOptions());
279
+ const verification = await backend.verify(backendOptions());
280
+ const result = summarizeExecution(actual, verification, exitCode, reviewedPlan);
281
+ const checks = verification.rows.filter((row) => /^(Afyx Graph MCP|Antigravity MCP|Claude Code MCP|Afyx workflow MCP|Provider MCP|Afyx Context Engine|Afyx Forge Core|Core readiness)$/.test(row.name));
282
+ const receiptChoices = [
283
+ ...result.components.map((item, index) => ({ id: `component:${index}`, label: `${item.name}: ${item.outcome}; ${item.version || 'n/a'}` })),
284
+ ...checks.map((row, index) => ({ id: `check:${index}`, label: `${row.name}: ${row.state}` })),
285
+ { id: 'close', label: `Finish — ${result.status}; verify exit=${verification.exitCode}` },
286
+ ];
287
+ const summary = [`Result: ${result.status}; installer exit=${exitCode}; verify exit=${verification.exitCode}`,
288
+ `Provider configuration: ${provider.length ? 'see backend checks' : 'SKIPPED by user'}`,
289
+ 'Inspect component versions and backend checks with ↑/↓.',
290
+ result.status === 'PASS' ? 'Maintenance: use verify, update, or selective uninstall.'
291
+ : 'Recovery: resolve the displayed backend failures, repair the affected component, then verify.'];
292
+ if (input.isTTY && output.isTTY) {
293
+ let selected = receiptChoices.length - 1;
294
+ try {
295
+ while (true) {
296
+ const choice = await choose({ input, output, options: receiptChoices, selected,
297
+ frame: (rows, cursor, view) => {
298
+ let detail = summary;
299
+ if (cursor < result.components.length) {
300
+ const item = result.components[cursor];
301
+ const state = actual.components[cursor];
302
+ detail = [`${item.name}: ${item.status}; outcome=${item.outcome}; version=${item.version || 'none'}`,
303
+ `Target: ${state.target}`, `Ownership: ${state.ownership}; state=${state.currentState}`, state.detail];
304
+ } else if (cursor < receiptChoices.length - 1) {
305
+ const row = checks[cursor - result.components.length];
306
+ detail = [`${row.name}: ${row.state}`, row.detail];
307
+ }
308
+ return frame(4, rows, detail, '↑/↓: inspect Tab: focus activity Enter: select Esc: finish', view);
309
+ } });
310
+ if (choice === null || choice === 'close') break;
311
+ selected = receiptChoices.findIndex((item) => item.id === choice);
312
+ }
313
+ } catch (error) {
314
+ output.write(`\nReceipt closed: ${error.message} Verified result: ${result.status}.\n`);
315
+ return /Ctrl\+C|SIGTERM/.test(error.message) ? 130 : 1;
316
+ }
317
+ } else output.write(`${frame(4, result.components.map((item) => `${item.name}: ${item.status}; ${item.version || 'n/a'}`), summary, '')}\n`);
318
+ return result.status === 'PASS' ? 0 : 1;
319
+ } catch (error) {
320
+ output.write(`\x1b[2J\x1b[H${frame(4, ['Verification: NOT TESTED / FAILED'],
321
+ [`Installer exit: ${exitCode}`, error.message, 'Run verify and resolve the backend diagnostic before retrying.'], '')}\n`);
322
+ return 1;
323
+ }
324
+ };
325
+ return { preset, provider: provider.join(','), providerScope: scope, customComponents: custom,
326
+ skipProviderConfiguration: provider.length === 0, nonInteractive: true,
327
+ expectedPlan: reviewedPlan.fingerprint, finish };
328
+ }
@@ -10,7 +10,7 @@
10
10
  */
11
11
 
12
12
  import { existsSync, readFileSync } from 'node:fs';
13
- import { dirname, join, resolve } from 'node:path';
13
+ import { basename, dirname, join, resolve } from 'node:path';
14
14
  import { fileURLToPath } from 'node:url';
15
15
  import { spawn } from 'node:child_process';
16
16
 
@@ -18,6 +18,15 @@ const __filename = fileURLToPath(import.meta.url);
18
18
  const __dirname = dirname(__filename);
19
19
  export const PACKAGE_ROOT = resolve(__dirname, '..');
20
20
 
21
+ export function subprocessEnvironment(executable, env = process.env) {
22
+ if (!/^powershell(?:\.exe)?$/i.test(basename(executable))) return env;
23
+ const windowsRoot = env.SystemRoot || env.SYSTEMROOT || env.windir || env.WINDIR;
24
+ if (!windowsRoot) return env;
25
+ const nativeModules = join(windowsRoot, 'System32', 'WindowsPowerShell', 'v1.0', 'Modules');
26
+ const modulePaths = [nativeModules, ...(env.PSModulePath || '').split(';').filter(Boolean)];
27
+ return { ...env, PSModulePath: [...new Set(modulePaths)].join(';') };
28
+ }
29
+
21
30
  let cachedVersion = null;
22
31
  export function getPackageVersion() {
23
32
  if (cachedVersion) return cachedVersion;
@@ -43,7 +52,7 @@ export const COMMAND_ALLOWED_OPTIONS = {
43
52
  'contextRuntimeRoot', 'forgeRuntimeRoot', 'graphRuntimeRoot',
44
53
  'customComponents', 'componentActions',
45
54
  'dryRun', 'validateOnly', 'force', 'allowDowngrade', 'offline', 'noBuildFallback',
46
- 'skipProviderConfiguration', 'nonInteractive'
55
+ 'skipProviderConfiguration', 'nonInteractive', 'ui'
47
56
  ]),
48
57
  verify: new Set([
49
58
  'preset', 'provider', 'providerScope', 'workspaceRoot', 'skillsRoot',
@@ -86,6 +95,7 @@ Commands:
86
95
 
87
96
  Options:
88
97
  --preset <name> Component preset (minimal, recommended, full, custom)
98
+ --ui <auto|tui|plain> Installer terminal interface (install only)
89
99
  --provider <names> Target AI provider host(s) (codex, antigravity, claude)
90
100
  --provider-scope <scope> Integration scope (global, workspace)
91
101
  --workspace-root <path> Target project workspace root for local configuration
@@ -209,6 +219,10 @@ export function parseCliArgs(rawArgs) {
209
219
  if (recordOption('removeAfyxForge', arg)) result.options.removeAfyxForge = true;
210
220
  } else if (arg === '--non-interactive' || arg === '-y' || arg === '--yes') {
211
221
  if (recordOption('nonInteractive', arg)) result.options.nonInteractive = true;
222
+ } else if (arg === '--ui' || arg.startsWith('--ui=')) {
223
+ const val = arg.includes('=') ? arg.split('=')[1] : args[++i];
224
+ if (!['auto', 'tui', 'plain'].includes(val)) result.errors.push('--ui requires auto, tui, or plain');
225
+ else if (recordOption('ui', '--ui')) result.options.ui = val;
212
226
  } else if (arg === '--preset' || arg.startsWith('--preset=')) {
213
227
  const val = arg.includes('=') ? arg.split('=')[1] : args[++i];
214
228
  if (!val) result.errors.push('--preset requires a value');
@@ -301,6 +315,9 @@ export function buildSubprocessCall(command, options = {}, platform = process.pl
301
315
  }
302
316
 
303
317
  if (effectiveOptions.preset) psArgs.push('-Preset', effectiveOptions.preset);
318
+ if (effectiveOptions.planJson && command === 'install') psArgs.push('-PlanJson');
319
+ if (effectiveOptions.expectedPlan && command === 'install') psArgs.push('-ExpectedPlan', effectiveOptions.expectedPlan);
320
+ if (effectiveOptions.reportJson && command === 'verify') psArgs.push('-ReportJson');
304
321
  if (effectiveOptions.provider) psArgs.push('-Provider', effectiveOptions.provider);
305
322
  if (effectiveOptions.providerScope) psArgs.push('-ProviderScope', effectiveOptions.providerScope);
306
323
  if (effectiveOptions.workspaceRoot) psArgs.push('-WorkspaceRoot', effectiveOptions.workspaceRoot);
@@ -330,7 +347,9 @@ export function buildSubprocessCall(command, options = {}, platform = process.pl
330
347
  psArgs.push('-WhatIf');
331
348
  }
332
349
  if (effectiveOptions.nonInteractive && (command === 'install' || command === 'update' || command === 'uninstall')) {
333
- psArgs.push('-Confirm:$false');
350
+ // Windows PowerShell 5.1 -File cannot bind a string Boolean to a switch.
351
+ // These entrypoints use CI for prompt suppression and retain ShouldProcess.
352
+ env.CI = '1';
334
353
  }
335
354
 
336
355
  if (effectiveOptions.validateOnly && command === 'install') psArgs.push('-ValidateOnly');
@@ -338,7 +357,7 @@ export function buildSubprocessCall(command, options = {}, platform = process.pl
338
357
  if (effectiveOptions.allowDowngrade && (command === 'install' || command === 'update')) psArgs.push('-AllowDowngrade');
339
358
  if (effectiveOptions.offline && (command === 'install' || command === 'update')) psArgs.push('-Offline');
340
359
  if (effectiveOptions.noBuildFallback && (command === 'install' || command === 'update')) psArgs.push('-NoBuildFallback');
341
- if (effectiveOptions.skipProviderConfiguration && (command === 'install' || command === 'update')) psArgs.push('-SkipProviderConfiguration');
360
+ if (effectiveOptions.skipProviderConfiguration && (command === 'install' || command === 'update' || command === 'verify')) psArgs.push('-SkipProviderConfiguration');
342
361
  if (effectiveOptions.skipSelfUpdate && command === 'update' && isGitRepo) psArgs.push('-SkipSelfUpdate');
343
362
  if (effectiveOptions.removeProviderConfiguration && command === 'uninstall') psArgs.push('-RemoveProviderConfiguration');
344
363
  if (effectiveOptions.removeAfyxGraph && command === 'uninstall') psArgs.push('-RemoveAfyxGraph');
@@ -377,6 +396,9 @@ export function buildSubprocessCall(command, options = {}, platform = process.pl
377
396
  }
378
397
 
379
398
  if (effectiveOptions.preset) shArgs.push('--preset', effectiveOptions.preset);
399
+ if (effectiveOptions.planJson && command === 'install') shArgs.push('--plan-json');
400
+ if (effectiveOptions.expectedPlan && command === 'install') shArgs.push('--expected-plan', effectiveOptions.expectedPlan);
401
+ if (effectiveOptions.reportJson && command === 'verify') shArgs.push('--report-json');
380
402
  if (effectiveOptions.provider) shArgs.push('--provider', effectiveOptions.provider);
381
403
  if (effectiveOptions.providerScope) shArgs.push('--provider-scope', effectiveOptions.providerScope);
382
404
  if (effectiveOptions.workspaceRoot) shArgs.push('--workspace-root', effectiveOptions.workspaceRoot);
@@ -445,7 +467,7 @@ export function executeSubprocess(callInfo, { onExit = null } = {}) {
445
467
  child = spawn(exe, args, {
446
468
  stdio: 'inherit',
447
469
  cwd: process.cwd(),
448
- env: callInfo.env || process.env,
470
+ env: subprocessEnvironment(exe, callInfo.env || process.env),
449
471
  });
450
472
  } catch (err) {
451
473
  if (callInfo.fallbackExecutable && exe !== callInfo.fallbackExecutable) {
@@ -21,13 +21,21 @@ $kitRoot = Split-Path -Parent $PSScriptRoot
21
21
  $metadataPath = Join-Path $kitRoot 'afyx-graph\afyx-graph.json'
22
22
  $metadata = Get-Content -Raw -LiteralPath $metadataPath -Encoding utf8 | ConvertFrom-Json
23
23
  $distributionProductPath = Join-Path $kitRoot 'afyx-graph\engine\scripts\distribution-product.json'
24
- $releaseChannel = (Get-Content -Raw -LiteralPath $distributionProductPath -Encoding utf8 | ConvertFrom-Json).releaseChannel
25
- $architecture = switch ([System.Runtime.InteropServices.RuntimeInformation]::OSArchitecture.ToString()) {
26
- 'Arm64' { 'arm64' }
27
- 'X64' { 'x64' }
28
- default { throw "Unsupported Windows architecture: $_" }
24
+ $releaseChannel = if (Test-Path -LiteralPath $distributionProductPath -PathType Leaf) {
25
+ (Get-Content -Raw -LiteralPath $distributionProductPath -Encoding utf8 | ConvertFrom-Json).releaseChannel
26
+ } elseif ($metadata.PSObject.Properties['release_channel']) {
27
+ [string]$metadata.release_channel
28
+ } else {
29
+ 'technical-alpha'
30
+ }
31
+ . (Join-Path $PSScriptRoot 'lib\AfyxPlatform.ps1')
32
+ $target = Get-AfyxGraphTarget
33
+ if ($target -ne 'win32-x64') { throw "Afyx Graph prebuilt runtime is unavailable for $target. Minimal and Recommended Kit presets remain available; consumer source compilation is disabled." }
34
+ $architecture = switch ($target) {
35
+ 'win32-x64' { 'x64' }
36
+ 'win32-arm64' { 'arm64' }
37
+ default { throw "Unsupported Windows architecture: $target" }
29
38
  }
30
- $target = "win32-$architecture"
31
39
  if ($target -ne 'win32-x64') { throw "Afyx Graph prebuilt runtime is unavailable for $target. Minimal and Recommended Kit presets remain available; consumer source compilation is disabled." }
32
40
  $assetName = "afyx-graph-$target.zip"
33
41
  $current = Join-Path $RuntimeRoot 'current'
@@ -105,12 +113,11 @@ function Get-SourceRevision {
105
113
  function Get-RequestedRevision {
106
114
  $source = Get-SourceRevision
107
115
  if ($source) { return $source.Commit }
108
- $marker = Join-Path $kitRoot '.afyx-source-revision'
109
- if (Test-Path -LiteralPath $marker -PathType Leaf) {
110
- $revision = (Get-Content -Raw -LiteralPath $marker -Encoding utf8).Trim()
111
- if ($revision -notmatch '^[0-9a-f]{40}$') { throw 'Packaged source revision marker is invalid.' }
112
- return $revision
113
- }
116
+ $marker = Join-Path $kitRoot '.afyx-source-revision'
117
+ if (Test-Path -LiteralPath $marker -PathType Leaf) {
118
+ $revision = (Get-Content -Raw -LiteralPath $marker -Encoding utf8).Trim()
119
+ if ($revision -match '^[0-9a-f]{40}$') { return $revision }
120
+ }
114
121
  return $null
115
122
  }
116
123
 
@@ -290,25 +297,64 @@ function Resolve-Archive {
290
297
  }
291
298
  if (-not $Offline) {
292
299
  $downloadRoot = Join-Path ([System.IO.Path]::GetTempPath()) "afyx-graph-download-$([guid]::NewGuid().ToString('N'))"
293
- try {
294
- New-Item -ItemType Directory -Path $downloadRoot | Out-Null
295
- $download = Join-Path $downloadRoot $assetName
296
- $tag = "afyx-graph-v$($metadata.product_version)"
297
- $repoBase = 'https://github.com/a5zero7/afyx-engineering-kit'
298
- $url = "$repoBase/releases/download/$tag/$assetName"
299
- Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $download
300
- Invoke-WebRequest -UseBasicParsing -Uri "$repoBase/releases/download/$tag/SHA256SUMS" -OutFile (Join-Path $downloadRoot 'SHA256SUMS')
301
- Invoke-WebRequest -UseBasicParsing -Uri "$repoBase/releases/download/$tag/RELEASE-MANIFEST.json" -OutFile (Join-Path $downloadRoot 'RELEASE-MANIFEST.json')
302
- Test-ArchiveChecksum -Path $download
303
- Test-ArchiveBundle -Path $download
304
- $identity = Get-ArchiveIdentity -Path $download -RequestedRevision $requestedRevision
305
- if ($requestedRevision -and $identity.revisionStatus -ne 'MATCH') {
306
- throw "Downloaded release revision is $($identity.sourceRevision), requested checkout is $requestedRevision."
300
+ $candidateTags = @()
301
+ if ($requestedRevision) {
302
+ $shortSha = if ($requestedRevision.Length -ge 12) { $requestedRevision.Substring(0, 12) } else { $requestedRevision }
303
+ $candidateTags += "afyx-dev-$requestedRevision"
304
+ $candidateTags += "dev-$requestedRevision"
305
+ $candidateTags += "afyx-dev-$shortSha"
306
+ $candidateTags += "dev-$shortSha"
307
+ }
308
+ $candidateTags += "afyx-graph-v$($metadata.product_version)"
309
+ $candidateTags += "v$($metadata.product_version)"
310
+ $candidateTags += "afyx-dev-snapshot"
311
+
312
+ $repoBase = 'https://github.com/a5zero7/afyx-engineering-kit'
313
+ $downloadedArchive = $null
314
+ $lastDownloadErr = $null
315
+
316
+ foreach ($tag in $candidateTags) {
317
+ try {
318
+ if (Test-Path -LiteralPath $downloadRoot) { Remove-Item -LiteralPath $downloadRoot -Recurse -Force }
319
+ New-Item -ItemType Directory -Path $downloadRoot | Out-Null
320
+ $download = Join-Path $downloadRoot $assetName
321
+ $sumsFile = Join-Path $downloadRoot 'SHA256SUMS'
322
+ $manifestFile = Join-Path $downloadRoot 'RELEASE-MANIFEST.json'
323
+
324
+ Invoke-WebRequest -UseBasicParsing -Uri "$repoBase/releases/download/$tag/RELEASE-MANIFEST.json" -OutFile $manifestFile -ErrorAction Stop
325
+ $manifestData = Get-Content -Raw -LiteralPath $manifestFile -Encoding utf8 | ConvertFrom-Json
326
+ if ($requestedRevision -and $manifestData.source_revision -ne $requestedRevision) {
327
+ continue
328
+ }
329
+
330
+ Invoke-WebRequest -UseBasicParsing -Uri "$repoBase/releases/download/$tag/SHA256SUMS" -OutFile $sumsFile -ErrorAction Stop
331
+ Invoke-WebRequest -UseBasicParsing -Uri "$repoBase/releases/download/$tag/$assetName" -OutFile $download -ErrorAction Stop
332
+
333
+ Test-ArchiveChecksum -Path $download
334
+ Test-ArchiveBundle -Path $download
335
+ $identity = Get-ArchiveIdentity -Path $download -RequestedRevision $requestedRevision
336
+ if ($requestedRevision -and $identity.revisionStatus -ne 'MATCH') {
337
+ continue
338
+ }
339
+ $downloadedArchive = [pscustomobject]@{
340
+ Path = $download
341
+ Source = 'github-release'
342
+ Commit = $identity.sourceRevision
343
+ RevisionStatus = $identity.revisionStatus
344
+ BuildProvenance = 'GITHUB_RELEASE'
345
+ }
346
+ break
347
+ } catch {
348
+ $lastDownloadErr = $_
307
349
  }
308
- return [pscustomobject]@{ Path = $download; Source = 'github-release'; Commit = $identity.sourceRevision; RevisionStatus = $identity.revisionStatus; BuildProvenance = 'GITHUB_RELEASE' }
309
- } catch {
310
- Write-Warning "Verified GitHub release unavailable ($($_.Exception.Message)); trying bounded local build fallback."
311
350
  }
351
+
352
+ if ($downloadedArchive) {
353
+ return $downloadedArchive
354
+ }
355
+
356
+ $diag = if ($lastDownloadErr) { $lastDownloadErr.Exception.Message } else { 'No matching release tag found' }
357
+ Write-Warning "Verified GitHub release unavailable ($diag); trying bounded local build fallback."
312
358
  } else { Write-Host 'Offline mode: skipping GitHub release lookup.' }
313
359
  return Build-LocalArchive
314
360
  }