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

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 (57) hide show
  1. package/.afyx-source-revision +1 -1
  2. package/afyx-context/src/budget.js +39 -153
  3. package/afyx-context/src/documentation.js +116 -0
  4. package/afyx-context/src/index.js +2 -0
  5. package/afyx-context/src/memory.js +122 -229
  6. package/afyx-context/src/usage.js +91 -0
  7. package/afyx-forge/src/cli.js +14 -1
  8. package/afyx-forge/src/index.js +3 -0
  9. package/afyx-forge/src/workflow-refiner.js +48 -15
  10. package/afyx-forge/src/workflow.js +226 -0
  11. package/afyx-graph/engine/release/RELEASE-MANIFEST.json +16 -6
  12. package/afyx-graph/engine/release/SHA256SUMS +4 -2
  13. package/afyx-graph/engine/release/afyx-graph-darwin-arm64.tar.gz +0 -0
  14. package/afyx-graph/engine/release/afyx-graph-darwin-x64.tar.gz +0 -0
  15. package/afyx-graph/engine/release/afyx-graph-linux-x64.tar.gz +0 -0
  16. package/afyx-graph/engine/release/afyx-graph-win32-x64.zip +0 -0
  17. package/bin/afyx-engineering-kit.mjs +14 -6
  18. package/install.ps1 +52 -6
  19. package/install.sh +21 -10
  20. package/package.json +3 -1
  21. package/scripts/afyx-capability-orchestrator.mjs +159 -41
  22. package/scripts/afyx-graph-artifact.mjs +1 -1
  23. package/scripts/afyx-graph-targets.mjs +8 -0
  24. package/scripts/afyx-host-adapters.mjs +52 -0
  25. package/scripts/afyx-host-bridge-lifecycle.mjs +4 -0
  26. package/scripts/afyx-host-bridge.mjs +25 -0
  27. package/scripts/afyx-install-backend.mjs +34 -13
  28. package/scripts/afyx-install-contract.mjs +5 -2
  29. package/scripts/afyx-install-progress.mjs +88 -0
  30. package/scripts/afyx-installer-environment.mjs +150 -0
  31. package/scripts/afyx-local-link-ownership.mjs +16 -0
  32. package/scripts/afyx-midnight-circuit.mjs +322 -79
  33. package/scripts/afyx-modular-integration.mjs +3 -0
  34. package/scripts/afyx-modular-runtime.mjs +3 -0
  35. package/scripts/afyx-native-execution.mjs +168 -0
  36. package/scripts/afyx-native-github.mjs +155 -0
  37. package/scripts/afyx-npm-installer.mjs +56 -28
  38. package/scripts/afyx-provider-inventory.mjs +6 -3
  39. package/scripts/afyx-security-auditor.mjs +61 -64
  40. package/scripts/afyx-skill-catalog.mjs +83 -0
  41. package/scripts/afyx-skill-engineering.mjs +2 -0
  42. package/scripts/afyx-universal-runtime.mjs +74 -12
  43. package/scripts/install-afyx-forge.ps1 +14 -10
  44. package/scripts/install-afyx-forge.sh +13 -10
  45. package/scripts/install-afyx-graph.sh +4 -4
  46. package/scripts/lib/AfyxInstallerProgress.psm1 +11 -0
  47. package/scripts/lib/AfyxSkillLifecycle.psm1 +42 -6
  48. package/scripts/lib/afyx-installer-progress.sh +30 -0
  49. package/scripts/link-global-dev.ps1 +10 -3
  50. package/scripts/link-global-dev.sh +10 -8
  51. package/scripts/prepare-g6-package.mjs +13 -28
  52. package/scripts/resolve-git-release-artifacts.mjs +5 -4
  53. package/scripts/stage-npm-release.mjs +3 -1
  54. package/scripts/validate-release-zip-graph.mjs +2 -2
  55. package/uninstall.ps1 +2 -0
  56. package/verify.ps1 +9 -2
  57. package/verify.sh +6 -4
@@ -1,31 +1,52 @@
1
- import { spawnSync } from 'node:child_process';
1
+ import { spawn } from 'node:child_process';
2
2
  import { buildSubprocessCall, PACKAGE_ROOT, subprocessEnvironment } from './afyx-npm-installer.mjs';
3
3
  import { decodeContract } from './afyx-install-contract.mjs';
4
4
 
5
- function capture(call) {
6
- const invoke = (program) => spawnSync(program, call.args, {
7
- encoding: 'utf8', windowsHide: true, timeout: 300000, maxBuffer: 8 * 1024 * 1024,
8
- env: subprocessEnvironment(program, { ...call.env, CI: '1', NO_COLOR: '1' }),
5
+ function capture(call, { signal } = {}) {
6
+ return new Promise((resolve, reject) => {
7
+ const invoke = (program) => {
8
+ const child = spawn(program, call.args, { windowsHide: true, signal, stdio: ['ignore', 'pipe', 'pipe'],
9
+ env: subprocessEnvironment(program, { ...call.env, CI: '1', NO_COLOR: '1', AFYX_PLAIN_OUTPUT: '1' }) });
10
+ const chunks = [];
11
+ let bytes = 0, failed = false;
12
+ const timer = setTimeout(() => { failed = true; child.kill(); reject(new Error('Backend inspection exceeded 300 seconds')); }, 300_000);
13
+ child.on('error', (error) => {
14
+ failed = true; clearTimeout(timer);
15
+ if (error.code === 'ENOENT' && call.fallbackExecutable && program !== call.fallbackExecutable) invoke(call.fallbackExecutable);
16
+ else reject(error);
17
+ });
18
+ for (const stream of [child.stdout, child.stderr]) stream.on('data', (chunk) => {
19
+ if (failed) return;
20
+ bytes += chunk.length;
21
+ if (bytes > 8 * 1024 * 1024) { failed = true; child.kill(); clearTimeout(timer); reject(new Error('Backend inspection exceeded output limit')); }
22
+ else chunks.push(chunk);
23
+ });
24
+ child.on('close', (code) => {
25
+ clearTimeout(timer);
26
+ if (!failed) resolve({ exitCode: code ?? 1, output: Buffer.concat(chunks).toString('utf8'), executable: program });
27
+ });
28
+ };
29
+ invoke(call.executable);
9
30
  });
10
- let result = invoke(call.executable);
11
- if (result.error?.code === 'ENOENT' && call.fallbackExecutable) result = invoke(call.fallbackExecutable);
12
- if (result.error) throw result.error;
13
- return { exitCode: result.status ?? 1, output: `${result.stdout || ''}\n${result.stderr || ''}` };
14
31
  }
15
32
 
16
33
  export function createBackendAdapter({ platform = process.platform, pkgRoot = PACKAGE_ROOT } = {}) {
34
+ let executionShell = null;
17
35
  return {
18
- plan(options) {
36
+ get executionShell() { return executionShell; },
37
+ async plan(options, controls) {
19
38
  const { expectedPlan: _expectedPlan, ...query } = options;
20
- const result = capture(buildSubprocessCall('install', { ...query, planJson: true, nonInteractive: true }, platform, pkgRoot));
39
+ const result = await capture(buildSubprocessCall('install', { ...query, planJson: true, nonInteractive: true }, platform, pkgRoot), controls);
40
+ executionShell = result.executable;
21
41
  if (result.exitCode !== 0) throw new Error(`Backend plan failed (${result.exitCode}): ${result.output}`);
22
42
  return decodeContract(result.output, 'AfyxInstallPlan/v1');
23
43
  },
24
- verify(options) {
44
+ async verify(options, controls) {
25
45
  const allowed = ['preset', 'provider', 'providerScope', 'workspaceRoot', 'skillsRoot',
26
46
  'contextRuntimeRoot', 'forgeRuntimeRoot', 'graphRuntimeRoot', 'customComponents', 'skipProviderConfiguration'];
27
47
  const query = Object.fromEntries(allowed.filter((key) => options[key] !== undefined).map((key) => [key, options[key]]));
28
- const result = capture(buildSubprocessCall('verify', { ...query, reportJson: true }, platform, pkgRoot));
48
+ const result = await capture(buildSubprocessCall('verify', { ...query, reportJson: true }, platform, pkgRoot), controls);
49
+ executionShell = result.executable;
29
50
  return { ...decodeContract(result.output, 'AfyxVerification/v1'), exitCode: result.exitCode };
30
51
  },
31
52
  };
@@ -39,9 +39,12 @@ export function targetFingerprint(target, type) {
39
39
  } else throw new Error(`Unsupported component filesystem entry: ${path}`);
40
40
  };
41
41
  const root = resolve(target);
42
+ // Canonicalize parent aliases such as macOS /var -> /private/var, while
43
+ // retaining the existing rejection of a component root that is itself a link.
44
+ const boundary = existsSync(root) && !lstatSync(root).isSymbolicLink() ? realpathSync(root) : root;
42
45
  if (type === 'runtime') {
43
- for (const name of ['metadata.json', 'integrity.sha256', 'current']) visit(join(root, name), name, root);
44
- } else visit(root, '.', root);
46
+ for (const name of ['metadata.json', 'integrity.sha256', 'current']) visit(join(root, name), name, boundary);
47
+ } else visit(root, '.', boundary);
45
48
  return hash.digest('hex');
46
49
  }
47
50
 
@@ -0,0 +1,88 @@
1
+ import { performance } from 'node:perf_hooks';
2
+
3
+ export const INSTALL_PROGRESS_CONTRACT = 'AfyxInstallerProgress/v1';
4
+ export const INSTALL_PROGRESS_PREFIX = 'AFYX_PROGRESS ';
5
+ const phases = new Set(['discovery', 'validation', 'planning', 'revalidation', 'download', 'extract', 'install',
6
+ 'update', 'repair', 'configure', 'verify', 'cleanup', 'rollback', 'receipt']);
7
+ const states = new Set(['queued', 'running', 'completed', 'failed', 'cancelled']);
8
+
9
+ export function progressEvent(input) {
10
+ const event = { contract: INSTALL_PROGRESS_CONTRACT, operationId: input.operationId,
11
+ componentId: input.componentId ?? null, phase: input.phase, state: input.state,
12
+ completed: input.completed ?? null, total: input.total ?? null,
13
+ message: input.message ?? '', timestamp: input.timestamp ?? new Date().toISOString(), errorCode: input.errorCode ?? null };
14
+ if ((input.contract && input.contract !== INSTALL_PROGRESS_CONTRACT)
15
+ || typeof event.operationId !== 'string' || !/^[\w.:/-]{1,128}$/.test(event.operationId)
16
+ || (event.componentId !== null && (typeof event.componentId !== 'string' || !/^[a-z][a-z0-9-]{1,79}$/.test(event.componentId)))
17
+ || !phases.has(event.phase) || !states.has(event.state)
18
+ || typeof event.message !== 'string' || event.message.length > 8192
19
+ || typeof event.timestamp !== 'string' || !Number.isFinite(Date.parse(event.timestamp))
20
+ || (event.errorCode !== null && (typeof event.errorCode !== 'string' || event.errorCode.length > 128))) {
21
+ throw new Error('Invalid installer progress event');
22
+ }
23
+ if (event.completed !== null || event.total !== null) {
24
+ if (!Number.isSafeInteger(event.completed) || !Number.isSafeInteger(event.total)
25
+ || event.completed < 0 || event.total <= 0 || event.completed > event.total) throw new Error('Invalid installer progress units');
26
+ if (event.state === 'completed' && event.completed !== event.total) throw new Error('Completed progress must account for all units');
27
+ }
28
+ return Object.freeze(event);
29
+ }
30
+
31
+ export function elapsedLabel(milliseconds) {
32
+ const seconds = Math.floor(Math.max(0, milliseconds) / 1000);
33
+ return `${String(Math.floor(seconds / 60)).padStart(2, '0')}:${String(seconds % 60).padStart(2, '0')}`;
34
+ }
35
+
36
+ export class InstallerProgress {
37
+ constructor({ clock = () => performance.now(), reducedMotion = false } = {}) {
38
+ this.clock = clock; this.reducedMotion = reducedMotion; this.started = clock();
39
+ this.operations = new Map(); this.activity = []; this.sequence = 0;
40
+ }
41
+ accept(input) {
42
+ const event = progressEvent(input);
43
+ const previous = this.operations.get(event.operationId);
44
+ if (previous && ['completed', 'failed', 'cancelled'].includes(previous.state)) return previous;
45
+ if (!previous && this.operations.size >= 128) this.operations.delete(this.operations.keys().next().value);
46
+ const observed = { ...event, started: previous?.state === 'queued' && event.state === 'running' ? this.clock() : previous?.started ?? this.clock() };
47
+ this.operations.set(event.operationId, observed);
48
+ this.activity.push(`[${elapsedLabel(this.clock() - this.started)}] ${event.state.toUpperCase()} ${event.message}`);
49
+ if (this.activity.length > 64) this.activity.shift();
50
+ return observed;
51
+ }
52
+ begin(phase, message, componentId = null) {
53
+ const operationId = `ui:${phase}:${++this.sequence}`;
54
+ this.accept({ operationId, componentId, phase, state: 'running', message });
55
+ return operationId;
56
+ }
57
+ end(operationId, state = 'completed', message) {
58
+ const previous = this.operations.get(operationId);
59
+ if (previous) this.accept({ ...previous, state, message: message ?? previous.message });
60
+ }
61
+ stop(state) {
62
+ for (const operation of this.operations.values()) {
63
+ if (operation.state === 'running' || operation.state === 'queued') this.end(operation.operationId, operation.state === 'queued' ? 'cancelled' : state);
64
+ }
65
+ }
66
+ lines() {
67
+ const latest = new Map();
68
+ for (const operation of this.operations.values()) if (operation.componentId) latest.set(operation.componentId, operation);
69
+ return [...latest.values()].map((operation) =>
70
+ `${operation.componentId}: ${this.describe(operation)}`);
71
+ }
72
+ describe(operation) {
73
+ const elapsed = this.clock() - operation.started;
74
+ if (operation.total !== null) {
75
+ const percent = Math.floor(100 * operation.completed / operation.total);
76
+ const filled = Math.floor(12 * operation.completed / operation.total);
77
+ return `[${'='.repeat(filled)}${'-'.repeat(12 - filled)}] ${percent}% ${operation.completed}/${operation.total} ${operation.state.toUpperCase()}`;
78
+ }
79
+ if (operation.state !== 'running') return operation.state.toUpperCase();
80
+ const position = this.reducedMotion ? 0 : Math.floor(elapsed / 80) % 10;
81
+ const rail = `${'-'.repeat(position)}>`.padEnd(10, '-');
82
+ return `[${rail}] INDETERMINATE ${elapsedLabel(elapsed)}`;
83
+ }
84
+ current() {
85
+ const active = [...this.operations.values()].filter((operation) => operation.state === 'running').at(-1);
86
+ return active ? `${active.message} ${this.describe(active)}` : 'Waiting for the next confirmed operation';
87
+ }
88
+ }
@@ -0,0 +1,150 @@
1
+ import { execFile } from 'node:child_process';
2
+ import { readFile, readlink } from 'node:fs/promises';
3
+ import { existsSync } from 'node:fs';
4
+ import { basename, isAbsolute, join } from 'node:path';
5
+ import { release } from 'node:os';
6
+ import { promisify } from 'node:util';
7
+
8
+ export const INSTALLER_ENVIRONMENT_CONTRACT = 'AfyxInstallerEnvironment/v1';
9
+ const execute = promisify(execFile);
10
+ const clean = (value) => typeof value === 'string' ? value.replace(/[\x00-\x1f\x7f]/g, ' ').trim().slice(0, 160) : '';
11
+ const unknown = () => ({ name: 'Unknown', version: null, source: 'UNOBSERVED' });
12
+ async function run(program, args, { signal } = {}) {
13
+ const result = await execute(program, args, { encoding: 'utf8', timeout: 4000, maxBuffer: 32 * 1024, windowsHide: true, signal });
14
+ return result.stdout.trim();
15
+ }
16
+ export function terminalIdentity(env = {}) {
17
+ const names = { 'iTerm.app': 'iTerm2', Apple_Terminal: 'Terminal.app', vscode: 'Visual Studio Code Terminal' };
18
+ if (clean(env.TERM_PROGRAM)) return { name: names[env.TERM_PROGRAM] || clean(env.TERM_PROGRAM),
19
+ version: clean(env.TERM_PROGRAM_VERSION) || null, source: 'TERM_PROGRAM' };
20
+ return env.WT_SESSION ? { name: 'Windows Terminal', version: null, source: 'WT_SESSION' } : unknown();
21
+ }
22
+ export async function shellIdentity(program, executeCommand = run) {
23
+ const name = basename(program || '').toLowerCase().replace(/\.exe$/, '');
24
+ try {
25
+ if (name === 'pwsh' || name === 'powershell') {
26
+ const version = await executeCommand(program, ['-NoProfile', '-Command', '$PSVersionTable.PSVersion.ToString()']);
27
+ if (!/^\d+\.\d+(?:\.\d+){0,2}(?:[-\w.]*)?$/.test(version)) return unknown();
28
+ return { name: name === 'powershell' ? 'Windows PowerShell' : 'PowerShell', version, executable: program, source: 'EXECUTABLE_VERSION' };
29
+ }
30
+ if (name === 'bash' || name === 'zsh') {
31
+ const text = await executeCommand(program, ['--version']);
32
+ const version = text.match(name === 'bash' ? /version\s+(\d+\.\d+[^\s]*)/i : /zsh\s+(\d+\.\d+[^\s]*)/i)?.[1];
33
+ return version ? { name: name === 'bash' ? 'Bash' : 'Zsh', version, executable: program, source: 'EXECUTABLE_VERSION' } : unknown();
34
+ }
35
+ if (name === 'cmd') {
36
+ const text = await executeCommand(program, ['/d', '/c', 'ver']);
37
+ return { name: 'CMD', version: text.match(/\d+\.\d+\.\d+(?:\.\d+)?/)?.[0] || null, executable: program, source: 'EXECUTABLE_VERSION' };
38
+ }
39
+ } catch { /* An unavailable executable is not evidence of a shell version. */ }
40
+ return unknown();
41
+ }
42
+
43
+ async function observeWindows(parentPid, executeCommand) {
44
+ if (!Number.isSafeInteger(parentPid) || parentPid <= 0) return {};
45
+ const script = `$ErrorActionPreference='Stop'; $os=Get-CimInstance Win32_OperatingSystem; $shell=$null; $cursorPid=${parentPid}; ` +
46
+ `for($i=0;$i -lt 10 -and $cursorPid -gt 0;$i++){ ` +
47
+ `$p=Get-CimInstance Win32_Process -Filter ('ProcessId='+$cursorPid); if(-not $p){break}; ` +
48
+ `if($p.Name -match '^(powershell|pwsh|bash|zsh|cmd)\\.exe$' -and -not ($p.Name -eq 'cmd.exe' -and $p.CommandLine -match '(?i)\\s/c(?:\\s|$)')){ $shell=$p.ExecutablePath; break }; $cursorPid=[int]$p.ParentProcessId }; ` +
49
+ `[ordered]@{caption=$os.Caption; version=$os.Version; shell=$shell}|ConvertTo-Json -Compress`;
50
+ return JSON.parse(await executeCommand('powershell.exe', ['-NoProfile', '-Command', script]));
51
+ }
52
+ async function observePosixShell(parentPid, executeCommand, readLink, platform) {
53
+ let pid = parentPid;
54
+ for (let i = 0; i < 10 && Number.isSafeInteger(pid) && pid > 1; i++) {
55
+ const row = await executeCommand('ps', ['-p', String(pid), '-o', 'ppid=', '-o', 'comm=']);
56
+ const match = row.trim().match(/^(\d+)\s+(.+)$/);
57
+ if (!match) break;
58
+ const command = match[2].trim().replace(/^-/, '');
59
+ if (['bash', 'zsh'].includes(basename(command))) {
60
+ if (isAbsolute(command)) return command;
61
+ if (platform === 'darwin') {
62
+ // BSD ps can expose only argv[0]. Darwin has no /proc; identify the
63
+ // executable from this process's native text-file records instead.
64
+ const records = await executeCommand('/usr/sbin/lsof', ['-a', '-p', String(pid), '-d', 'txt', '-Fn']);
65
+ const candidates = [...new Set(records.split('\n').filter((line) => line.startsWith('n'))
66
+ .map((line) => line.slice(1)).filter((path) => isAbsolute(path) && basename(path) === basename(command)))];
67
+ return candidates.length === 1 ? candidates[0] : null;
68
+ }
69
+ return await readLink(`/proc/${pid}/exe`);
70
+ }
71
+ pid = Number(match[1]);
72
+ }
73
+ return null;
74
+ }
75
+
76
+ /** Read-only local observations. SHELL/ComSpec alone are not invoking-shell proof. */
77
+ export async function detectInstallerEnvironment({ platform = process.platform, arch = process.arch,
78
+ env = process.env, parentPid = process.ppid, pkgRoot, readText = (path) => readFile(path, 'utf8'),
79
+ executeCommand = run, readLink = readlink, signal } = {}) {
80
+ const command = (program, args) => executeCommand(program, args, { signal });
81
+ const state = { contract: INSTALLER_ENVIRONMENT_CONTRACT, platform, architecture: arch,
82
+ os: unknown(), invokingShell: unknown(), terminal: terminalIdentity(env), backendShell: unknown(),
83
+ package: { version: 'Unknown', sourceRevision: 'Unknown' } };
84
+ const jobs = [];
85
+ jobs.push((async () => {
86
+ try {
87
+ if (platform === 'win32') {
88
+ const observed = await observeWindows(parentPid, command);
89
+ if (clean(observed.caption)) state.os = { name: clean(observed.caption), version: clean(observed.version) || null, source: 'WIN32_OPERATING_SYSTEM' };
90
+ state.invokingShell = await shellIdentity(observed.shell, command);
91
+ } else {
92
+ if (platform === 'linux') {
93
+ const text = await readText('/etc/os-release');
94
+ const pretty = text.match(/^PRETTY_NAME=(?:"([^"\n]*)"|'([^'\n]*)'|([^\n]*))$/m);
95
+ if (pretty) state.os = { name: clean(pretty[1] ?? pretty[2] ?? pretty[3]), version: null, source: 'OS_RELEASE' };
96
+ state.subsystem = /wsl2/i.test(release()) ? 'WSL2' : /microsoft|wsl/i.test(release()) || env.WSL_DISTRO_NAME ? 'WSL' : null;
97
+ } else if (platform === 'darwin') {
98
+ const version = await command('sw_vers', ['-productVersion']);
99
+ if (/^\d+(?:\.\d+){1,2}$/.test(version)) state.os = { name: 'macOS', version, source: 'SW_VERS' };
100
+ }
101
+ state.invokingShell = await shellIdentity(await observePosixShell(parentPid, command, readLink, platform), command);
102
+ }
103
+ } catch { /* Leave only the fields not observed as Unknown. */ }
104
+ })());
105
+ jobs.push((async () => {
106
+ if (platform === 'win32') {
107
+ state.backendShell = await shellIdentity('pwsh', command);
108
+ if (state.backendShell.name === 'Unknown') state.backendShell = await shellIdentity('powershell.exe', command);
109
+ } else state.backendShell = await shellIdentity('bash', command);
110
+ state.backendShell.executed = false;
111
+ })());
112
+ jobs.push((async () => {
113
+ try { state.package.version = JSON.parse(await readText(join(pkgRoot, 'package.json'))).version || 'Unknown'; } catch { /* Unknown. */ }
114
+ if (pkgRoot && existsSync(join(pkgRoot, '.git'))) {
115
+ try {
116
+ const revision = await command('git', ['-C', pkgRoot, 'rev-parse', 'HEAD']);
117
+ if (/^[a-f0-9]{40}$/.test(revision)) {
118
+ state.package.sourceRevision = revision;
119
+ state.package.dirty = Boolean(await command('git', ['-C', pkgRoot, 'status', '--porcelain']));
120
+ state.package.source = 'GIT_CHECKOUT';
121
+ }
122
+ } catch { /* Git evidence remains Unknown if unreadable. */ }
123
+ return;
124
+ }
125
+ try {
126
+ const marker = (await readText(join(pkgRoot, '.afyx-source-revision'))).trim();
127
+ if (/^[a-f0-9]{40}$/.test(marker)) { state.package.sourceRevision = marker; state.package.source = 'PACKAGE_MARKER'; }
128
+ } catch { /* No ancestor repository may claim an unstamped package's identity. */ }
129
+ })());
130
+ await Promise.all(jobs);
131
+ if (signal?.aborted) throw new Error('Environment discovery canceled');
132
+ return state;
133
+ }
134
+
135
+ export function environmentLines(state) {
136
+ const display = (item) => `${clean(item?.name) || 'Unknown'}${item?.version ? ` ${clean(item.version)}` : ''}`;
137
+ return [
138
+ `OS: ${display(state?.os)} | ${state?.architecture || 'Unknown'}${state?.subsystem ? ` | ${state.subsystem}` : ''}`,
139
+ `Shell: ${display(state?.invokingShell)} | Terminal: ${display(state?.terminal)} | Backend: ${display(state?.backendShell)}`,
140
+ ];
141
+ }
142
+
143
+ export function recordBackendExecution(state, executable) {
144
+ if (!state || !executable) return;
145
+ const name = basename(executable).toLowerCase().replace(/\.exe$/, '');
146
+ const previous = basename(state.backendShell?.executable || '').toLowerCase().replace(/\.exe$/, '');
147
+ state.backendShell = name === previous ? { ...state.backendShell, executed: true }
148
+ : { name: { pwsh: 'PowerShell', powershell: 'Windows PowerShell', bash: 'Bash' }[name] || 'Unknown',
149
+ version: null, executable, executed: true, source: 'BACKEND_PROCESS' };
150
+ }
@@ -0,0 +1,16 @@
1
+ /** Read-only guard for the existing local npm link lifecycle. */
2
+ import { lstatSync, realpathSync } from 'node:fs';
3
+ import { join, resolve } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ export function inspectLocalLink(repositoryRoot, globalModules) {
6
+ const repository = realpathSync(repositoryRoot), entry = join(resolve(globalModules), 'afyx-engineering-kit');
7
+ try {
8
+ const stat = lstatSync(entry);
9
+ return { status: stat.isSymbolicLink() && realpathSync(entry) === repository ? 'OWNED_LINK' : 'FOREIGN_INSTALLATION', entry };
10
+ } catch (error) { if (error.code === 'ENOENT') return { status: 'NOT_INSTALLED', entry }; return { status: 'UNVERIFIED', entry }; }
11
+ }
12
+ if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
13
+ const result = inspectLocalLink(process.argv[2], process.argv[3]);
14
+ process.stdout.write(JSON.stringify(result) + '\n');
15
+ if (!['OWNED_LINK', 'NOT_INSTALLED'].includes(result.status)) process.exitCode = 1;
16
+ }