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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (208) hide show
  1. package/.afyx-source-revision +1 -0
  2. package/LICENSE +21 -0
  3. package/README.md +377 -2
  4. package/SECURITY.md +74 -0
  5. package/afyx-context/LICENSE +21 -0
  6. package/afyx-context/README.md +155 -0
  7. package/afyx-context/afyx-context.json +30 -0
  8. package/afyx-context/contracts/integration-v1.schema.json +34 -0
  9. package/afyx-context/package-lock.json +53 -0
  10. package/afyx-context/package.json +34 -0
  11. package/afyx-context/scripts/benchmark.mjs +39 -0
  12. package/afyx-context/scripts/build.mjs +15 -0
  13. package/afyx-context/scripts/comparative-benchmark.mjs +342 -0
  14. package/afyx-context/scripts/comparative-worker.mjs +74 -0
  15. package/afyx-context/scripts/graph-integration-e2e.mjs +188 -0
  16. package/afyx-context/scripts/integrated-dogfood.mjs +309 -0
  17. package/afyx-context/src/budget.js +166 -0
  18. package/afyx-context/src/cli.js +110 -0
  19. package/afyx-context/src/coordination.js +343 -0
  20. package/afyx-context/src/engine.js +198 -0
  21. package/afyx-context/src/errors.js +14 -0
  22. package/afyx-context/src/graph-integration-worker.js +70 -0
  23. package/afyx-context/src/graph-integration.js +373 -0
  24. package/afyx-context/src/graph-mcp-bridge.js +103 -0
  25. package/afyx-context/src/index.js +25 -0
  26. package/afyx-context/src/integrations.js +87 -0
  27. package/afyx-context/src/memory.js +255 -0
  28. package/afyx-context/src/storage.js +364 -0
  29. package/afyx-context/test-fixtures/coordination-worker.mjs +52 -0
  30. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__init__.py +1 -0
  31. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/__manifest__.py +4 -0
  32. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/__init__.py +1 -0
  33. package/afyx-context/test-fixtures/graph-consumer-repo/addons/sale_extension/models/sale_order.py +5 -0
  34. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__init__.py +1 -0
  35. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/__manifest__.py +10 -0
  36. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/__init__.py +2 -0
  37. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order.py +20 -0
  38. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/models/sale_order_audit.py +11 -0
  39. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/security/ir.model.access.csv +2 -0
  40. package/afyx-context/test-fixtures/integrated-dogfood-repo/addons/integrated_sales/views/sale_order_views.xml +14 -0
  41. package/afyx-forge/LICENSE +55 -0
  42. package/afyx-forge/README.md +126 -0
  43. package/afyx-forge/afyx-forge.json +28 -0
  44. package/afyx-forge/bin/afyx-forge +4 -0
  45. package/afyx-forge/bin/afyx-forge.cmd +3 -0
  46. package/afyx-forge/bin/afyx-forge.js +16 -0
  47. package/afyx-forge/contracts/forge-plan-v1.schema.json +172 -0
  48. package/afyx-forge/package.json +26 -0
  49. package/afyx-forge/src/classifier.js +190 -0
  50. package/afyx-forge/src/cli.js +111 -0
  51. package/afyx-forge/src/doctor.js +105 -0
  52. package/afyx-forge/src/guidance.js +120 -0
  53. package/afyx-forge/src/index.js +273 -0
  54. package/afyx-forge/src/planning.js +107 -0
  55. package/afyx-forge/src/policy.js +109 -0
  56. package/afyx-forge/src/workflow-refiner.js +151 -0
  57. package/afyx-graph/afyx-graph.json +20 -0
  58. package/afyx-graph/engine/LICENSE +21 -0
  59. package/afyx-graph/engine/README.md +104 -0
  60. package/afyx-graph/engine/release/RELEASE-MANIFEST.json +21 -0
  61. package/afyx-graph/engine/release/SHA256SUMS +2 -0
  62. package/afyx-graph/engine/release/afyx-graph-linux-x64.tar.gz +0 -0
  63. package/afyx-graph/engine/release/afyx-graph-win32-x64.zip +0 -0
  64. package/afyx-graph/engine/scripts/distribution-contract.mjs +212 -0
  65. package/afyx-graph/engine/scripts/distribution-product.json +33 -0
  66. package/bin/afyx-engineering-kit.mjs +61 -0
  67. package/install.ps1 +1053 -0
  68. package/install.sh +617 -0
  69. package/package.json +66 -4
  70. package/scripts/afyx-capability-orchestrator.mjs +752 -0
  71. package/scripts/afyx-claude-integration.mjs +547 -0
  72. package/scripts/afyx-context-artifact.mjs +105 -0
  73. package/scripts/afyx-credential-broker.mjs +75 -0
  74. package/scripts/afyx-doctor.ps1 +152 -0
  75. package/scripts/afyx-doctor.sh +146 -0
  76. package/scripts/afyx-forge-artifact.mjs +183 -0
  77. package/scripts/afyx-global-routing-policy.md +12 -0
  78. package/scripts/afyx-global-routing.mjs +168 -0
  79. package/scripts/afyx-graph-artifact.mjs +178 -0
  80. package/scripts/afyx-host-adapters.mjs +543 -0
  81. package/scripts/afyx-host-bridge-lifecycle.mjs +174 -0
  82. package/scripts/afyx-host-bridge.mjs +288 -0
  83. package/scripts/afyx-integration-contracts.mjs +825 -0
  84. package/scripts/afyx-mcp-integration.mjs +528 -0
  85. package/scripts/afyx-modular-integration.mjs +361 -0
  86. package/scripts/afyx-modular-runtime.mjs +451 -0
  87. package/scripts/afyx-native-skill-host.mjs +124 -0
  88. package/scripts/afyx-npm-installer.mjs +486 -0
  89. package/scripts/afyx-project.ps1 +205 -0
  90. package/scripts/afyx-project.sh +207 -0
  91. package/scripts/afyx-provider-backup.mjs +1206 -0
  92. package/scripts/afyx-provider-integration.mjs +724 -0
  93. package/scripts/afyx-provider-inventory.mjs +147 -0
  94. package/scripts/afyx-security-auditor.mjs +224 -0
  95. package/scripts/afyx-skill-engineering.mjs +354 -0
  96. package/scripts/afyx-tool-family-routing.mjs +64 -0
  97. package/scripts/afyx-universal-runtime.mjs +530 -0
  98. package/scripts/alpha_acceptance_preflight.py +240 -0
  99. package/scripts/benchmark-graph-memory.mjs +96 -0
  100. package/scripts/benchmark_capability_orchestrator.mjs +64 -0
  101. package/scripts/build-windows-installer.ps1 +259 -0
  102. package/scripts/build_forge_synthetic_image.py +328 -0
  103. package/scripts/check-reference-staleness.py +71 -0
  104. package/scripts/components.json +254 -0
  105. package/scripts/contracts/afyx-capability-request-v1.schema.json +189 -0
  106. package/scripts/contracts/afyx-capability-result-v1.schema.json +32 -0
  107. package/scripts/dogfood_engineering_comparison.mjs +303 -0
  108. package/scripts/engineering-assurance.json +28 -0
  109. package/scripts/install-afyx-context.ps1 +142 -0
  110. package/scripts/install-afyx-context.sh +126 -0
  111. package/scripts/install-afyx-forge.ps1 +265 -0
  112. package/scripts/install-afyx-forge.sh +273 -0
  113. package/scripts/install-afyx-graph.ps1 +571 -0
  114. package/scripts/install-afyx-graph.sh +438 -0
  115. package/scripts/install-codex-usage-tracker.ps1 +172 -0
  116. package/scripts/lib/AfyxComponents.psm1 +399 -0
  117. package/scripts/lib/AfyxSkillLifecycle.psm1 +289 -0
  118. package/scripts/lib/AfyxTerminal.psm1 +838 -0
  119. package/scripts/lib/afyx-components.sh +256 -0
  120. package/scripts/lib/afyx-skill-lifecycle.sh +271 -0
  121. package/scripts/link-global-dev.ps1 +193 -0
  122. package/scripts/link-global-dev.sh +130 -0
  123. package/scripts/phase8-paired-evidence.mjs +195 -0
  124. package/scripts/phase8-representative-workload.mjs +771 -0
  125. package/scripts/phase8-session-recorder.mjs +157 -0
  126. package/scripts/phase8_event_ledger.py +248 -0
  127. package/scripts/phase8_evidence_discovery.py +189 -0
  128. package/scripts/prepare-g6-package.mjs +349 -0
  129. package/scripts/resolve-git-release-artifacts.mjs +321 -0
  130. package/scripts/stage-npm-release.mjs +94 -0
  131. package/scripts/validate-afyx-graph.py +203 -0
  132. package/scripts/validate-components.py +194 -0
  133. package/scripts/validate-engineering-assurance.py +281 -0
  134. package/scripts/verify-graph-archive.mjs +64 -0
  135. package/skills/afyx-context/SKILL.md +26 -0
  136. package/skills/afyx-engineering-expert/README.md +42 -0
  137. package/skills/afyx-engineering-expert/SKILL.md +70 -0
  138. package/skills/afyx-engineering-expert/assets/result-template.md +15 -0
  139. package/skills/afyx-engineering-expert/references/ai-ml-engineer.md +17 -0
  140. package/skills/afyx-engineering-expert/references/business-analyst.md +17 -0
  141. package/skills/afyx-engineering-expert/references/clean-code-engineer.md +26 -0
  142. package/skills/afyx-engineering-expert/references/code-reviewer.md +24 -0
  143. package/skills/afyx-engineering-expert/references/cybersecurity-devsecops.md +17 -0
  144. package/skills/afyx-engineering-expert/references/data-analyst-bi.md +24 -0
  145. package/skills/afyx-engineering-expert/references/data-engineer.md +24 -0
  146. package/skills/afyx-engineering-expert/references/database-administrator.md +17 -0
  147. package/skills/afyx-engineering-expert/references/debugging-specialist.md +24 -0
  148. package/skills/afyx-engineering-expert/references/embedded-iot-engineer.md +24 -0
  149. package/skills/afyx-engineering-expert/references/erp-technical-specialist.md +17 -0
  150. package/skills/afyx-engineering-expert/references/hardware-diagnostics-auditor.md +24 -0
  151. package/skills/afyx-engineering-expert/references/hardware-electronics-engineer.md +24 -0
  152. package/skills/afyx-engineering-expert/references/integration-engineer.md +24 -0
  153. package/skills/afyx-engineering-expert/references/legacy-modernization-engineer.md +24 -0
  154. package/skills/afyx-engineering-expert/references/llmops-prompt-engineer.md +24 -0
  155. package/skills/afyx-engineering-expert/references/network-engineer.md +24 -0
  156. package/skills/afyx-engineering-expert/references/performance-benchmark-engineer.md +24 -0
  157. package/skills/afyx-engineering-expert/references/platform-engineer.md +24 -0
  158. package/skills/afyx-engineering-expert/references/product-manager.md +17 -0
  159. package/skills/afyx-engineering-expert/references/qa-engineer.md +17 -0
  160. package/skills/afyx-engineering-expert/references/site-reliability-engineer.md +17 -0
  161. package/skills/afyx-engineering-expert/references/software-engineer.md +17 -0
  162. package/skills/afyx-engineering-expert/references/solutions-architect.md +17 -0
  163. package/skills/afyx-engineering-expert/references/specialists-index.md +33 -0
  164. package/skills/afyx-engineering-expert/references/subject-matter-expert.md +17 -0
  165. package/skills/afyx-engineering-expert/references/system-analyst.md +17 -0
  166. package/skills/afyx-engineering-expert/references/technical-project-manager.md +24 -0
  167. package/skills/afyx-engineering-expert/references/technical-writer.md +24 -0
  168. package/skills/afyx-engineering-expert/references/ui-ux-designer.md +17 -0
  169. package/skills/afyx-engineering-expert/workflows/ai-data-erp.md +20 -0
  170. package/skills/afyx-engineering-expert/workflows/debugging.md +10 -0
  171. package/skills/afyx-engineering-expert/workflows/discovery-design.md +11 -0
  172. package/skills/afyx-engineering-expert/workflows/implementation.md +12 -0
  173. package/skills/afyx-engineering-expert/workflows/incident-reliability.md +12 -0
  174. package/skills/afyx-engineering-expert/workflows/review-audit.md +13 -0
  175. package/skills/afyx-forge/SKILL.md +43 -0
  176. package/skills/afyx-forge/references/adaptive-policy.md +19 -0
  177. package/skills/efficient-coding/SKILL.md +33 -0
  178. package/skills/efficient-coding/references/investigation.md +27 -0
  179. package/skills/efficient-coding/references/token-efficiency.md +25 -0
  180. package/skills/efficient-coding/references/tool-routing.md +13 -0
  181. package/skills/odoo-engineering/SKILL.md +33 -0
  182. package/skills/odoo-engineering/references/common.md +9 -0
  183. package/skills/odoo-engineering/references/odoo-10.md +32 -0
  184. package/skills/odoo-engineering/references/odoo-11.md +26 -0
  185. package/skills/odoo-engineering/references/odoo-12.md +31 -0
  186. package/skills/odoo-engineering/references/odoo-13.md +27 -0
  187. package/skills/odoo-engineering/references/odoo-14.md +31 -0
  188. package/skills/odoo-engineering/references/odoo-15.md +34 -0
  189. package/skills/odoo-engineering/references/odoo-16.md +37 -0
  190. package/skills/odoo-engineering/references/odoo-17.md +37 -0
  191. package/skills/odoo-engineering/references/odoo-18.md +48 -0
  192. package/skills/odoo-engineering/references/odoo-19.md +43 -0
  193. package/skills/odoo-engineering/references/odoo-20.md +39 -0
  194. package/skills/odoo-engineering/references/reference-schema.md +16 -0
  195. package/skills/odoo-engineering/references/version-detection.md +13 -0
  196. package/tools/codex-usage/CodexUsage.psm1 +496 -0
  197. package/tools/codex-usage/codex-usage-doctor.ps1 +150 -0
  198. package/tools/codex-usage/codex-usage-pricing.json +25 -0
  199. package/tools/codex-usage/codex-usage-stop.ps1 +167 -0
  200. package/tools/codex-usage/codex-usage-watch.ps1 +250 -0
  201. package/tools/codex-usage/vscode-user-task.json +31 -0
  202. package/tools/windows-setup/SetupBootstrapper.cs +258 -0
  203. package/uninstall.ps1 +189 -0
  204. package/uninstall.sh +167 -0
  205. package/update.ps1 +95 -0
  206. package/update.sh +67 -0
  207. package/verify.ps1 +411 -0
  208. package/verify.sh +265 -0
@@ -0,0 +1,142 @@
1
+ [CmdletBinding(SupportsShouldProcess)]
2
+ param(
3
+ [string]$RuntimeRoot = $(if ($env:AFYX_CONTEXT_RUNTIME_ROOT) { $env:AFYX_CONTEXT_RUNTIME_ROOT } else { Join-Path $env:USERPROFILE '.afyx\context' }),
4
+ [switch]$Update,
5
+ [switch]$Repair,
6
+ [switch]$Verify,
7
+ [switch]$Uninstall,
8
+ [switch]$ValidateOnly
9
+ )
10
+
11
+ Set-StrictMode -Version Latest
12
+ $ErrorActionPreference = 'Stop'
13
+ $packageRoot = Split-Path -Parent $PSScriptRoot
14
+ $sourceRoot = Join-Path $packageRoot 'afyx-context'
15
+ $artifactTool = Join-Path $PSScriptRoot 'afyx-context-artifact.mjs'
16
+ $recoveryRoot = "$RuntimeRoot.afyx-old"
17
+
18
+ function Resolve-Full([string]$Path) { return [System.IO.Path]::GetFullPath($Path) }
19
+ function Test-IsFullyQualified([string]$Path) {
20
+ if (-not [System.IO.Path]::IsPathRooted($Path)) { return $false }
21
+ $root = [System.IO.Path]::GetPathRoot($Path)
22
+ if (-not $root -or $root -eq '\' -or $root -eq '/') { return $false }
23
+ return $true
24
+ }
25
+ function Assert-SafeRoot {
26
+ if (-not (Test-IsFullyQualified $RuntimeRoot)) { throw 'Afyx Context RuntimeRoot must be absolute.' }
27
+ if (($RuntimeRoot -split '[\\/]') -contains '..') { throw 'Afyx Context RuntimeRoot must not contain traversal segments.' }
28
+ $resolved = Resolve-Full $RuntimeRoot
29
+ $root = [System.IO.Path]::GetPathRoot($resolved)
30
+ if ($resolved.TrimEnd('\','/') -eq $root.TrimEnd('\','/')) { throw 'Afyx Context RuntimeRoot cannot be a filesystem root.' }
31
+ $source = (Resolve-Full $sourceRoot).TrimEnd('\','/')
32
+ if ($resolved.TrimEnd('\','/') -eq $source -or $resolved.StartsWith("$source\", [System.StringComparison]::OrdinalIgnoreCase) -or $source.StartsWith("$($resolved.TrimEnd('\','/'))\", [System.StringComparison]::OrdinalIgnoreCase)) {
33
+ throw 'Afyx Context RuntimeRoot must not overlap the bundled source.'
34
+ }
35
+ foreach ($candidate in @($RuntimeRoot, $recoveryRoot)) {
36
+ $probe = Resolve-Full $candidate
37
+ while ($probe) {
38
+ if (Test-Path -LiteralPath $probe) {
39
+ $item = Get-Item -LiteralPath $probe -Force
40
+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { throw "Refusing reparse-point runtime path: $probe" }
41
+ }
42
+ $parent = [IO.Directory]::GetParent($probe)
43
+ if (-not $parent) { break }
44
+ $probe = $parent.FullName
45
+ }
46
+ }
47
+ }
48
+ function Get-Sha256([string]$Path) { return (Get-FileHash -LiteralPath $Path -Algorithm SHA256).Hash.ToLowerInvariant() }
49
+ function Test-OwnedRuntime([string]$Root, [switch]$AllowModified) {
50
+ try {
51
+ $metadataPath = Join-Path $Root 'metadata.json'
52
+ $manifestPath = Join-Path $Root 'integrity.sha256'
53
+ $metadata = Get-Content -Raw -LiteralPath $metadataPath -Encoding utf8 | ConvertFrom-Json -ErrorAction Stop
54
+ $identity = Get-Content -Raw -LiteralPath (Join-Path $Root 'current\identity.json') -Encoding utf8 | ConvertFrom-Json -ErrorAction Stop
55
+ if ($metadata.product_name -ne 'Afyx Context Engine' -or $metadata.ownership_class -ne 'AFYX') { return $false }
56
+ foreach ($field in @('product_name','product_version','source_revision','ownership_class','build_provenance','release_channel','integration_default')) {
57
+ if ([string]$metadata.$field -ne [string]$identity.$field) { return $false }
58
+ }
59
+ if ($AllowModified) { return $true }
60
+ if ((Get-Sha256 $manifestPath) -ne [string]$metadata.artifact_digest) { return $false }
61
+ foreach ($line in (Get-Content -LiteralPath $manifestPath -Encoding utf8)) {
62
+ if ($line -notmatch '^([0-9a-f]{64}) (current/[A-Za-z0-9._/-]+)$' -or $Matches[2] -match '(^|/)\.\.(/|$)') { return $false }
63
+ $file = Join-Path $Root ($Matches[2] -replace '/', [IO.Path]::DirectorySeparatorChar)
64
+ if (-not (Test-Path -LiteralPath $file -PathType Leaf)) { return $false }
65
+ $item = Get-Item -LiteralPath $file -Force
66
+ if ($item.Attributes -band [IO.FileAttributes]::ReparsePoint) { return $false }
67
+ if ((Get-Sha256 $file) -ne $Matches[1]) { return $false }
68
+ }
69
+ return $true
70
+ } catch { return $false }
71
+ }
72
+ function Recover-Interrupted {
73
+ if (-not (Test-Path -LiteralPath $recoveryRoot)) { return }
74
+ if (Test-Path -LiteralPath $RuntimeRoot) { throw 'Interrupted Afyx Context transaction is ambiguous; runtime and recovery both exist.' }
75
+ if (-not (Test-OwnedRuntime $recoveryRoot)) { throw 'Interrupted Afyx Context recovery ownership or integrity is invalid.' }
76
+ if ($ValidateOnly -or $Verify -or $Uninstall -or $WhatIfPreference) { throw 'Afyx Context recovery is pending; read-only/uninstall operation will not mutate it.' }
77
+ Move-Item -LiteralPath $recoveryRoot -Destination $RuntimeRoot
78
+ Write-Host "Recovered interrupted Afyx Context transaction at $RuntimeRoot."
79
+ }
80
+
81
+ Assert-SafeRoot
82
+ Recover-Interrupted
83
+ $state = if (-not (Test-Path -LiteralPath $RuntimeRoot)) { 'NOT INSTALLED' } elseif (Test-OwnedRuntime $RuntimeRoot) { 'HEALTHY' } elseif (Test-OwnedRuntime $RuntimeRoot -AllowModified) { 'DRIFTED' } else { 'UNKNOWN' }
84
+ if ($ValidateOnly -or $Verify) {
85
+ Write-Host "Product: Afyx Context Engine`nState: $state`nRuntimeRoot: $RuntimeRoot"
86
+ if ($Verify -and $state -ne 'HEALTHY') { exit 1 }
87
+ exit 0
88
+ }
89
+ if ($Uninstall) {
90
+ if ($state -eq 'NOT INSTALLED') { Write-Host 'Afyx Context Engine is not installed.'; exit 0 }
91
+ if ($state -ne 'HEALTHY') { throw "Refusing to uninstall Afyx Context runtime with state $state." }
92
+ if ($PSCmdlet.ShouldProcess($RuntimeRoot, 'Remove Afyx-owned Context runtime')) { Remove-Item -LiteralPath $RuntimeRoot -Recurse -Force }
93
+ Write-Host 'Afyx Context runtime removed; user state was not changed.'
94
+ exit 0
95
+ }
96
+ if (-not (Get-Command node -ErrorAction SilentlyContinue)) { throw 'Node.js >=22.5.0 is required for Afyx Context.' }
97
+ $nodeVersion = (& node -p "process.versions.node") -join ''
98
+ if ([version]$nodeVersion -lt [version]'22.5.0') { throw "Node.js >=22.5.0 is required; found $nodeVersion." }
99
+ if ($state -eq 'UNKNOWN') { throw 'Refusing to replace foreign or unverified Afyx Context destination.' }
100
+ if ($state -eq 'DRIFTED' -and -not $Repair) { throw 'Modified Afyx Context runtime requires explicit repair.' }
101
+ if ($state -eq 'HEALTHY' -and -not ($Update -or $Repair)) { Write-Host 'Afyx Context runtime is already healthy; unchanged.'; exit 0 }
102
+ if ($state -eq 'NOT INSTALLED' -and ($Update -or $Repair)) { throw 'Update/repair requires an existing Afyx Context runtime.' }
103
+ if ($WhatIfPreference) { Write-Host "WhatIf: would stage and install Afyx Context at $RuntimeRoot"; exit 0 }
104
+
105
+ $revision = if (Test-Path -LiteralPath (Join-Path $packageRoot '.git')) { (& git -C $packageRoot rev-parse HEAD 2>$null) -join '' } else { '' }
106
+ $fromPackageMarker = $false
107
+ if (-not $revision -or $revision -notmatch '^[0-9a-f]{40}$') {
108
+ $revFile = Join-Path $packageRoot '.afyx-source-revision'
109
+ if (Test-Path -LiteralPath $revFile -PathType Leaf) {
110
+ $revision = (Get-Content -Raw -LiteralPath $revFile -Encoding utf8).Trim()
111
+ $fromPackageMarker = $true
112
+ }
113
+ }
114
+ if ($revision -notmatch '^[0-9a-f]{40}$') { throw 'Exact Git source revision is required to install Afyx Context.' }
115
+ $dirty = if ($fromPackageMarker) { '' } else { (& git -C $packageRoot status --porcelain --untracked-files=no 2>$null) -join '' }
116
+ $provenance = if ($fromPackageMarker) { 'RELEASE_CANDIDATE_SNAPSHOT' } elseif ($dirty) { 'LOCAL_SOURCE_DIRTY' } else { 'LOCAL_SOURCE_CLEAN' }
117
+ $parent = Split-Path -Parent $RuntimeRoot
118
+ New-Item -ItemType Directory -Force -Path $parent | Out-Null
119
+ $prepared = Join-Path $parent ".afyx-context-stage-$([guid]::NewGuid().ToString('N'))"
120
+ $swapped = $false
121
+ try {
122
+ New-Item -ItemType Directory -Path $prepared | Out-Null
123
+ & node $artifactTool prepare --source $sourceRoot --target (Join-Path $prepared 'current') --metadata (Join-Path $prepared 'metadata.json') --manifest (Join-Path $prepared 'integrity.sha256') --revision $revision --provenance $provenance
124
+ if ($LASTEXITCODE -ne 0 -or -not (Test-OwnedRuntime $prepared)) { throw 'Prepared Afyx Context artifact failed integrity validation.' }
125
+ if ($state -eq 'HEALTHY') {
126
+ $oldDigest = (Get-Content -Raw -LiteralPath (Join-Path $RuntimeRoot 'metadata.json') | ConvertFrom-Json).artifact_digest
127
+ $newDigest = (Get-Content -Raw -LiteralPath (Join-Path $prepared 'metadata.json') | ConvertFrom-Json).artifact_digest
128
+ if ($oldDigest -eq $newDigest) { Remove-Item -LiteralPath $prepared -Recurse -Force; Write-Host 'Afyx Context runtime already matches the candidate; unchanged.'; exit 0 }
129
+ }
130
+ if (Test-Path -LiteralPath $RuntimeRoot) { Move-Item -LiteralPath $RuntimeRoot -Destination $recoveryRoot }
131
+ Move-Item -LiteralPath $prepared -Destination $RuntimeRoot
132
+ $swapped = $true
133
+ if (-not (Test-OwnedRuntime $RuntimeRoot)) { throw 'Installed Afyx Context runtime failed post-swap verification.' }
134
+ if (Test-Path -LiteralPath $recoveryRoot) { Remove-Item -LiteralPath $recoveryRoot -Recurse -Force }
135
+ } catch {
136
+ if ($swapped -and (Test-Path -LiteralPath $RuntimeRoot)) { Remove-Item -LiteralPath $RuntimeRoot -Recurse -Force }
137
+ if ((Test-Path -LiteralPath $recoveryRoot) -and -not (Test-Path -LiteralPath $RuntimeRoot)) { Move-Item -LiteralPath $recoveryRoot -Destination $RuntimeRoot }
138
+ throw
139
+ } finally {
140
+ if (Test-Path -LiteralPath $prepared) { Remove-Item -LiteralPath $prepared -Recurse -Force -ErrorAction SilentlyContinue }
141
+ }
142
+ Write-Host "Afyx Context Engine installed at $RuntimeRoot; source revision $revision; PATH and user state unchanged."
@@ -0,0 +1,126 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ PACKAGE_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
5
+ SOURCE_ROOT="$PACKAGE_ROOT/afyx-context"
6
+ ARTIFACT_TOOL="$PACKAGE_ROOT/scripts/afyx-context-artifact.mjs"
7
+ runtime_root="${AFYX_CONTEXT_RUNTIME_ROOT:-$HOME/.afyx/context}"
8
+ update=false; repair=false; verify=false; uninstall=false; validate_only=false
9
+ while (($#)); do
10
+ case "$1" in
11
+ --runtime-root) (($# >= 2)) || { printf '%s\n' '--runtime-root requires a value.' >&2; exit 2; }; runtime_root="$2"; shift 2 ;;
12
+ --update) update=true; shift ;;
13
+ --repair) repair=true; shift ;;
14
+ --verify) verify=true; shift ;;
15
+ --uninstall) uninstall=true; shift ;;
16
+ --validate-only) validate_only=true; shift ;;
17
+ -h|--help) printf '%s\n' 'Usage: install-afyx-context.sh [--runtime-root PATH] [--update|--repair|--verify|--uninstall|--validate-only]'; exit 0 ;;
18
+ *) printf 'Unknown option: %s\n' "$1" >&2; exit 2 ;;
19
+ esac
20
+ done
21
+ recovery_root="${runtime_root}.afyx-old"
22
+
23
+ case "$runtime_root" in /*) ;; *) printf '%s\n' 'Afyx Context runtime root must be absolute.' >&2; exit 1 ;; esac
24
+ [[ "$runtime_root" != / ]] || { printf '%s\n' 'Afyx Context runtime root cannot be /.' >&2; exit 1; }
25
+ case "/$runtime_root/" in */../*) printf '%s\n' 'Afyx Context runtime root must not contain traversal segments.' >&2; exit 1 ;; esac
26
+ case "$runtime_root/" in "$SOURCE_ROOT/"*) printf '%s\n' 'Afyx Context runtime root must not overlap bundled source.' >&2; exit 1 ;; esac
27
+ case "$SOURCE_ROOT/" in "$runtime_root/"*) printf '%s\n' 'Afyx Context runtime root must not contain bundled source.' >&2; exit 1 ;; esac
28
+ for candidate in "$runtime_root" "$recovery_root"; do
29
+ probe="$candidate"
30
+ while [[ "$probe" != / && -n "$probe" ]]; do
31
+ [[ ! -L "$probe" ]] || { printf 'Afyx Context runtime path must not traverse a symbolic link: %s\n' "$probe" >&2; exit 1; }
32
+ probe="$(dirname "$probe")"
33
+ done
34
+ done
35
+
36
+ sha256_file() { if command -v sha256sum >/dev/null 2>&1; then sha256sum "$1" | awk '{print $1}'; else shasum -a 256 "$1" | awk '{print $1}'; fi; }
37
+ json_value() { sed -n 's/.*"'"$2"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$1" | head -n 1; }
38
+ owned_runtime() {
39
+ local root="$1" allow_modified="${2:-false}" metadata="$1/metadata.json" manifest="$1/integrity.sha256" identity="$1/current/identity.json" expected relative actual field
40
+ [[ -f "$metadata" && -f "$manifest" && -f "$identity" ]] || return 1
41
+ grep -q '"product_name"[[:space:]]*:[[:space:]]*"Afyx Context Engine"' "$metadata" || return 1
42
+ grep -q '"ownership_class"[[:space:]]*:[[:space:]]*"AFYX"' "$metadata" || return 1
43
+ for field in product_name product_version source_revision ownership_class build_provenance release_channel integration_default; do
44
+ [[ "$(json_value "$metadata" "$field")" == "$(json_value "$identity" "$field")" ]] || return 1
45
+ done
46
+ [[ "$allow_modified" == true ]] && return 0
47
+ expected="$(sed -n 's/.*"artifact_digest"[[:space:]]*:[[:space:]]*"\([0-9a-f]*\)".*/\1/p' "$metadata")"
48
+ [[ ${#expected} -eq 64 && "$(sha256_file "$manifest")" == "$expected" ]] || return 1
49
+ while IFS= read -r line; do
50
+ expected="${line%% *}"; relative="${line#* }"
51
+ [[ "$expected" =~ ^[0-9a-f]{64}$ && "$relative" == current/* && "$relative" != *../* ]] || return 1
52
+ [[ -f "$root/$relative" && ! -L "$root/$relative" ]] || return 1
53
+ actual="$(sha256_file "$root/$relative")"; [[ "$actual" == "$expected" ]] || return 1
54
+ done < "$manifest"
55
+ }
56
+
57
+ if [[ -e "$recovery_root" ]]; then
58
+ [[ ! -e "$runtime_root" ]] || { printf '%s\n' 'Interrupted Afyx Context transaction is ambiguous; runtime and recovery both exist.' >&2; exit 1; }
59
+ owned_runtime "$recovery_root" || { printf '%s\n' 'Interrupted Afyx Context recovery ownership or integrity is invalid.' >&2; exit 1; }
60
+ if "$validate_only" || "$verify" || "$uninstall"; then printf '%s\n' 'Afyx Context recovery is pending; read-only/uninstall operation will not mutate it.' >&2; exit 1; fi
61
+ mv -- "$recovery_root" "$runtime_root"
62
+ printf 'Recovered interrupted Afyx Context transaction at %s.\n' "$runtime_root"
63
+ fi
64
+ if [[ ! -e "$runtime_root" ]]; then state='NOT INSTALLED'
65
+ elif owned_runtime "$runtime_root"; then state=HEALTHY
66
+ elif owned_runtime "$runtime_root" true; then state=DRIFTED
67
+ else state=UNKNOWN; fi
68
+ if "$validate_only" || "$verify"; then
69
+ printf 'Product: Afyx Context Engine\nState: %s\nRuntimeRoot: %s\n' "$state" "$runtime_root"
70
+ "$verify" && [[ "$state" != HEALTHY ]] && exit 1
71
+ exit 0
72
+ fi
73
+ if "$uninstall"; then
74
+ [[ "$state" == 'NOT INSTALLED' ]] && { printf '%s\n' 'Afyx Context Engine is not installed.'; exit 0; }
75
+ [[ "$state" == HEALTHY ]] || { printf 'Refusing to uninstall Afyx Context runtime with state %s.\n' "$state" >&2; exit 1; }
76
+ rm -rf -- "$runtime_root"
77
+ printf '%s\n' 'Afyx Context runtime removed; user state was not changed.'
78
+ exit 0
79
+ fi
80
+ command -v node >/dev/null 2>&1 || { printf '%s\n' 'Node.js >=22.5.0 is required for Afyx Context.' >&2; exit 1; }
81
+ node -e 'const [major,minor]=process.versions.node.split(".").map(Number);process.exit(major>22||(major===22&&minor>=5)?0:1)' || { printf 'Node.js >=22.5.0 is required; found %s.\n' "$(node --version)" >&2; exit 1; }
82
+ [[ "$state" != UNKNOWN ]] || { printf '%s\n' 'Refusing to replace foreign or unverified Afyx Context destination.' >&2; exit 1; }
83
+ [[ "$state" != DRIFTED || "$repair" == true ]] || { printf '%s\n' 'Modified Afyx Context runtime requires explicit repair.' >&2; exit 1; }
84
+ [[ "$state" != HEALTHY || "$update" == true || "$repair" == true ]] || { printf '%s\n' 'Afyx Context runtime is already healthy; unchanged.'; exit 0; }
85
+ if [[ "$state" == 'NOT INSTALLED' ]] && { "$update" || "$repair"; }; then
86
+ printf '%s\n' 'Update/repair requires an existing Afyx Context runtime.' >&2
87
+ exit 1
88
+ fi
89
+ revision=""
90
+ if [[ -e "$PACKAGE_ROOT/.git" ]]; then revision="$(git -C "$PACKAGE_ROOT" rev-parse HEAD 2>/dev/null || true)"; fi
91
+ if [[ ! "$revision" =~ ^[0-9a-f]{40}$ && -f "$PACKAGE_ROOT/.afyx-source-revision" ]]; then
92
+ revision="$(tr -d '\r\n' < "$PACKAGE_ROOT/.afyx-source-revision")"
93
+ fi
94
+ [[ "$revision" =~ ^[0-9a-f]{40}$ ]] || { printf '%s\n' 'Exact Git source revision is required to install Afyx Context.' >&2; exit 1; }
95
+ provenance=RELEASE_CANDIDATE_SNAPSHOT
96
+ if [[ ! -f "$PACKAGE_ROOT/.afyx-source-revision" ]]; then
97
+ provenance=LOCAL_SOURCE_CLEAN
98
+ [[ -n "$(git -C "$PACKAGE_ROOT" status --porcelain --untracked-files=no)" ]] && provenance=LOCAL_SOURCE_DIRTY
99
+ fi
100
+ parent="$(dirname "$runtime_root")"; mkdir -p -- "$parent"
101
+ prepared="$(mktemp -d "$parent/.afyx-context-stage.XXXXXX")"; swapped=false
102
+ cleanup() {
103
+ local status=$?
104
+ if [[ -e "$prepared" ]]; then
105
+ rm -rf -- "$prepared" || return $?
106
+ fi
107
+ return "$status"
108
+ }
109
+ trap cleanup EXIT
110
+ node "$ARTIFACT_TOOL" prepare --source "$SOURCE_ROOT" --target "$prepared/current" --metadata "$prepared/metadata.json" --manifest "$prepared/integrity.sha256" --revision "$revision" --provenance "$provenance"
111
+ owned_runtime "$prepared" || { printf '%s\n' 'Prepared Afyx Context artifact failed integrity validation.' >&2; exit 1; }
112
+ if [[ "$state" == HEALTHY ]]; then
113
+ old_digest="$(sed -n 's/.*"artifact_digest"[[:space:]]*:[[:space:]]*"\([0-9a-f]*\)".*/\1/p' "$runtime_root/metadata.json")"
114
+ new_digest="$(sed -n 's/.*"artifact_digest"[[:space:]]*:[[:space:]]*"\([0-9a-f]*\)".*/\1/p' "$prepared/metadata.json")"
115
+ [[ "$old_digest" != "$new_digest" ]] || { printf '%s\n' 'Afyx Context runtime already matches the candidate; unchanged.'; exit 0; }
116
+ fi
117
+ [[ ! -e "$runtime_root" ]] || mv -- "$runtime_root" "$recovery_root"
118
+ if mv -- "$prepared" "$runtime_root"; then swapped=true; prepared="$parent/.afyx-context-stage-consumed"
119
+ else [[ ! -e "$recovery_root" ]] || mv -- "$recovery_root" "$runtime_root"; exit 1; fi
120
+ if ! owned_runtime "$runtime_root"; then
121
+ "$swapped" && rm -rf -- "$runtime_root"
122
+ [[ ! -e "$recovery_root" ]] || mv -- "$recovery_root" "$runtime_root"
123
+ printf '%s\n' 'Installed Afyx Context runtime failed post-swap verification.' >&2; exit 1
124
+ fi
125
+ [[ ! -e "$recovery_root" ]] || rm -rf -- "$recovery_root"
126
+ printf 'Afyx Context Engine installed at %s; source revision %s; PATH and user state unchanged.\n' "$runtime_root" "$revision"
@@ -0,0 +1,265 @@
1
+ [CmdletBinding(SupportsShouldProcess)]
2
+ param(
3
+ [string]$RuntimeRoot = $(if ($env:AFYX_FORGE_RUNTIME_ROOT) { $env:AFYX_FORGE_RUNTIME_ROOT } else { Join-Path $env:USERPROFILE '.afyx\forge' }),
4
+ [string]$SourceRevision = '',
5
+ [switch]$Update,
6
+ [switch]$Repair,
7
+ [switch]$Verify,
8
+ [switch]$Uninstall,
9
+ [switch]$ValidateOnly
10
+ )
11
+
12
+ Set-StrictMode -Version Latest
13
+ $ErrorActionPreference = 'Stop'
14
+ $packageRoot = Split-Path -Parent $PSScriptRoot
15
+ $sourceRoot = Join-Path $packageRoot 'afyx-forge'
16
+ $artifactStager = Join-Path $PSScriptRoot 'afyx-forge-artifact.mjs'
17
+ $recoveryRoot = "$RuntimeRoot.afyx-old"
18
+
19
+ function Resolve-Full([string]$Path) { return [System.IO.Path]::GetFullPath($Path) }
20
+ function Test-IsFullyQualified([string]$Path) {
21
+ if (-not [System.IO.Path]::IsPathRooted($Path)) { return $false }
22
+ $root = [System.IO.Path]::GetPathRoot($Path)
23
+ if (-not $root -or $root -eq '\' -or $root -eq '/') { return $false }
24
+ return $true
25
+ }
26
+
27
+ function Assert-NoReparsePoints([string]$CandidatePath) {
28
+ $probe = $CandidatePath
29
+ while ($probe) {
30
+ if (Test-Path -LiteralPath $probe) {
31
+ $item = Get-Item -LiteralPath $probe -Force
32
+ if ($item.Attributes -band [System.IO.FileAttributes]::ReparsePoint) {
33
+ throw "Afyx Forge runtime path must not traverse a reparse point or symbolic link: $probe"
34
+ }
35
+ }
36
+ $parent = Split-Path -Parent $probe
37
+ if (-not $parent -or $parent -eq $probe) { break }
38
+ $probe = $parent
39
+ }
40
+ }
41
+
42
+ function Assert-SafeRoot {
43
+ if (-not (Test-IsFullyQualified $RuntimeRoot)) { throw 'Afyx Forge RuntimeRoot must be absolute.' }
44
+ if (($RuntimeRoot -split '[\\/]') -contains '..') { throw 'Afyx Forge RuntimeRoot must not contain traversal segments.' }
45
+ $resolved = Resolve-Full $RuntimeRoot
46
+ $root = [System.IO.Path]::GetPathRoot($resolved)
47
+ if ($resolved.TrimEnd('\','/') -eq $root.TrimEnd('\','/')) { throw 'Afyx Forge RuntimeRoot cannot be a filesystem root.' }
48
+ $source = (Resolve-Full $sourceRoot).TrimEnd('\','/')
49
+ if ($resolved.TrimEnd('\','/') -eq $source -or $resolved.StartsWith("$source\", [System.StringComparison]::OrdinalIgnoreCase) -or $source.StartsWith("$($resolved.TrimEnd('\','/'))\", [System.StringComparison]::OrdinalIgnoreCase)) {
50
+ throw 'Afyx Forge RuntimeRoot must not overlap the bundled source.'
51
+ }
52
+ Assert-NoReparsePoints $resolved
53
+ Assert-NoReparsePoints (Resolve-Full $recoveryRoot)
54
+ }
55
+
56
+ function Resolve-SourceRevision {
57
+ if ($SourceRevision) { return $SourceRevision }
58
+ $revFile = Join-Path $packageRoot '.afyx-source-revision'
59
+ if (Test-Path -LiteralPath $revFile -PathType Leaf) {
60
+ $fromFile = (Get-Content -Raw -LiteralPath $revFile -Encoding utf8).Trim()
61
+ if ($fromFile) { return $fromFile }
62
+ }
63
+ $gitCmd = Get-Command git -ErrorAction SilentlyContinue
64
+ if ($gitCmd) {
65
+ $rev = ((& $gitCmd.Source -C $packageRoot rev-parse HEAD 2>$null) -join '').Trim()
66
+ if ($LASTEXITCODE -eq 0 -and $rev) { return $rev }
67
+ }
68
+ return 'unknown'
69
+ }
70
+
71
+ function Resolve-SourceProvenance {
72
+ $revFile = Join-Path $packageRoot '.afyx-source-revision'
73
+ if (Test-Path -LiteralPath $revFile -PathType Leaf) { return 'RELEASE_CANDIDATE_SNAPSHOT' }
74
+ $gitCmd = Get-Command git -ErrorAction SilentlyContinue
75
+ if ($gitCmd) {
76
+ $dirty = ((& $gitCmd.Source -C $packageRoot status --porcelain -- afyx-forge 2>$null) -join '').Trim()
77
+ if ($LASTEXITCODE -eq 0) {
78
+ return $(if ($dirty) { 'LOCAL_SOURCE_DIRTY' } else { 'LOCAL_SOURCE_CLEAN' })
79
+ }
80
+ }
81
+ return 'LOCAL_SOURCE_UNVERIFIED'
82
+ }
83
+
84
+ function Test-OwnedRuntime([string]$Root) {
85
+ try {
86
+ $metadataPath = Join-Path $Root 'metadata.json'
87
+ if (-not (Test-Path -LiteralPath $metadataPath -PathType Leaf)) { return $false }
88
+ $metadata = Get-Content -Raw -LiteralPath $metadataPath -Encoding utf8 | ConvertFrom-Json -ErrorAction Stop
89
+ return ($metadata.product_name -eq 'Afyx Forge Core' -and $metadata.ownership_class -eq 'AFYX')
90
+ } catch {
91
+ return $false
92
+ }
93
+ }
94
+
95
+ function Test-HealthyRuntime([string]$Root) {
96
+ if (-not (Test-OwnedRuntime $Root)) { return $false }
97
+ try {
98
+ $metadataPath = Join-Path $Root 'metadata.json'
99
+ $identityPath = Join-Path $Root 'current\identity.json'
100
+ $integrityPath = Join-Path $Root 'integrity.sha256'
101
+ $launcherCmd = Join-Path $Root 'current\bin\afyx-forge.cmd'
102
+ $launcherJs = Join-Path $Root 'current\bin\afyx-forge.js'
103
+ $publicLauncherCmd = Join-Path $Root 'bin\afyx-forge.cmd'
104
+ $packageJson = Join-Path $Root 'current\package.json'
105
+ $licenseFile = Join-Path $Root 'current\LICENSE'
106
+ foreach ($required in @($metadataPath, $identityPath, $integrityPath, $launcherCmd, $launcherJs, $publicLauncherCmd, $packageJson, $licenseFile)) {
107
+ if (-not (Test-Path -LiteralPath $required -PathType Leaf)) { return $false }
108
+ }
109
+ $metadata = Get-Content -Raw -LiteralPath $metadataPath -Encoding utf8 | ConvertFrom-Json -ErrorAction Stop
110
+ $identity = Get-Content -Raw -LiteralPath $identityPath -Encoding utf8 | ConvertFrom-Json -ErrorAction Stop
111
+ if ($identity.product_name -ne 'Afyx Forge Core' -or $identity.ownership_class -ne 'AFYX') { return $false }
112
+ if ($identity.product_version -ne $metadata.product_version) { return $false }
113
+ if (-not $metadata.source_revision -or $identity.source_revision -ne $metadata.source_revision) { return $false }
114
+ if (-not $metadata.artifact_digest) { return $false }
115
+
116
+ $actualIntegrityDigest = (Get-FileHash -LiteralPath $integrityPath -Algorithm SHA256).Hash.ToLowerInvariant()
117
+ if ($actualIntegrityDigest -ne ([string]$metadata.artifact_digest).ToLowerInvariant()) { return $false }
118
+
119
+ $lines = @(Get-Content -LiteralPath $integrityPath -Encoding utf8 | Where-Object { $_.Trim() })
120
+ if (-not $lines.Count) { return $false }
121
+ foreach ($line in $lines) {
122
+ if ($line -notmatch '^([0-9a-fA-F]{64})\s\s(current/.+)$') { return $false }
123
+ $expectedHash = $Matches[1].ToLowerInvariant()
124
+ $relPath = $Matches[2] -replace '/', '\'
125
+ $fullPath = Join-Path $Root $relPath
126
+ if (-not (Test-Path -LiteralPath $fullPath -PathType Leaf)) { return $false }
127
+ $actualHash = (Get-FileHash -LiteralPath $fullPath -Algorithm SHA256).Hash.ToLowerInvariant()
128
+ if ($actualHash -ne $expectedHash) { return $false }
129
+ }
130
+ return $true
131
+ } catch {
132
+ return $false
133
+ }
134
+ }
135
+
136
+ function Get-State {
137
+ if (-not (Test-Path -LiteralPath $RuntimeRoot)) { return 'NOT INSTALLED' }
138
+ if (-not (Test-OwnedRuntime $RuntimeRoot)) { return 'DRIFTED' }
139
+ if (Test-HealthyRuntime $RuntimeRoot) { return 'HEALTHY' }
140
+ return 'BROKEN'
141
+ }
142
+
143
+ Assert-SafeRoot
144
+
145
+ if (Test-Path -LiteralPath $recoveryRoot) {
146
+ if (Test-Path -LiteralPath $RuntimeRoot) {
147
+ throw 'Interrupted Afyx Forge transaction is ambiguous; runtime and recovery both exist.'
148
+ }
149
+ if (-not (Test-OwnedRuntime $recoveryRoot)) {
150
+ throw 'Interrupted Afyx Forge recovery ownership is invalid.'
151
+ }
152
+ if ($ValidateOnly -or $Verify -or $Uninstall) {
153
+ throw 'Afyx Forge recovery is pending; read-only/uninstall operation will not mutate it.'
154
+ }
155
+ Move-Item -LiteralPath $recoveryRoot -Destination $RuntimeRoot
156
+ Write-Host "Recovered interrupted Afyx Forge transaction at $RuntimeRoot."
157
+ }
158
+
159
+ $currentState = Get-State
160
+
161
+ if ($ValidateOnly -or $Verify) {
162
+ $metadataPath = Join-Path $RuntimeRoot 'metadata.json'
163
+ $metadata = if ($currentState -in @('HEALTHY', 'BROKEN') -and (Test-Path -LiteralPath $metadataPath)) {
164
+ Get-Content -Raw -LiteralPath $metadataPath -Encoding utf8 | ConvertFrom-Json
165
+ } else { $null }
166
+ [pscustomobject]@{
167
+ Component = 'afyx-forge'
168
+ State = $currentState
169
+ RuntimeRoot = $RuntimeRoot
170
+ Version = if ($metadata) { $metadata.product_version } else { '0.1.0' }
171
+ SourceRevision = if ($metadata -and $metadata.PSObject.Properties['source_revision']) { $metadata.source_revision } else { $null }
172
+ ArtifactDigest = if ($metadata -and $metadata.PSObject.Properties['artifact_digest']) { $metadata.artifact_digest } else { $null }
173
+ BuildProvenance = if ($metadata -and $metadata.PSObject.Properties['build_provenance']) { $metadata.build_provenance } else { $null }
174
+ Ownership = if ($currentState -in @('HEALTHY', 'BROKEN')) { 'afyx' } else { 'unknown' }
175
+ }
176
+ if ($Verify -and $currentState -ne 'HEALTHY') { exit 1 }
177
+ exit 0
178
+ }
179
+
180
+ if ($Uninstall) {
181
+ if ($currentState -eq 'NOT INSTALLED') {
182
+ Write-Host 'Afyx Forge: already not installed.'
183
+ exit 0
184
+ }
185
+ if ($currentState -eq 'DRIFTED') {
186
+ throw "Refusing to uninstall $($RuntimeRoot): Afyx Forge ownership could not be verified."
187
+ }
188
+ if ($WhatIfPreference) {
189
+ Write-Host "WhatIf: would uninstall Afyx Forge at $RuntimeRoot"
190
+ exit 0
191
+ }
192
+ Remove-Item -LiteralPath $RuntimeRoot -Recurse -Force
193
+ Write-Host "Afyx Forge: uninstalled from $RuntimeRoot"
194
+ exit 0
195
+ }
196
+
197
+ if ($currentState -eq 'DRIFTED') {
198
+ throw "Refusing to replace or modify unowned directory at $($RuntimeRoot): Afyx Forge ownership could not be verified."
199
+ }
200
+
201
+ if ($currentState -eq 'NOT INSTALLED' -and ($Update -or $Repair)) {
202
+ throw "Update or repair requires an existing Afyx Forge runtime at $RuntimeRoot."
203
+ }
204
+
205
+ if ($currentState -eq 'BROKEN' -and -not $Update -and -not $Repair) {
206
+ throw "Installed Afyx Forge at $RuntimeRoot is BROKEN (integrity or file drift detected). Use -Repair or -Update to restore it."
207
+ }
208
+
209
+ if ($currentState -eq 'HEALTHY' -and -not $Update -and -not $Repair) {
210
+ Write-Host "Afyx Forge: already installed and HEALTHY at $RuntimeRoot. Use -Update or -Repair to reinstall."
211
+ exit 0
212
+ }
213
+
214
+ if ($WhatIfPreference) {
215
+ Write-Host "WhatIf: would stage and install Afyx Forge Core at $RuntimeRoot"
216
+ exit 0
217
+ }
218
+
219
+ $nodeCmd = Get-Command node -ErrorAction SilentlyContinue
220
+ if (-not $nodeCmd) {
221
+ throw 'Node.js is required for Afyx Forge Core installation.'
222
+ }
223
+
224
+ $resolvedRevision = Resolve-SourceRevision
225
+ $resolvedProvenance = Resolve-SourceProvenance
226
+ $installedAt = (Get-Date).ToUniversalTime().ToString('yyyy-MM-ddTHH:mm:ssZ')
227
+
228
+ $parentDir = Split-Path -Parent $RuntimeRoot
229
+ New-Item -ItemType Directory -Force -Path $parentDir | Out-Null
230
+ $transactionId = [guid]::NewGuid().ToString('N')
231
+ $stageDir = Join-Path $parentDir ".forge-stage-$transactionId"
232
+
233
+ try {
234
+ & $nodeCmd.Source $artifactStager --source-root $sourceRoot --stage-dir $stageDir --runtime-root (Resolve-Full $RuntimeRoot) --revision $resolvedRevision --provenance $resolvedProvenance --installed-at $installedAt
235
+ if ($LASTEXITCODE -ne 0) {
236
+ throw 'Failed to stage Afyx Forge Core artifact.'
237
+ }
238
+ if (-not (Test-HealthyRuntime $stageDir)) {
239
+ throw 'Staged Afyx Forge runtime failed pre-swap integrity validation.'
240
+ }
241
+
242
+ if (Test-Path -LiteralPath $RuntimeRoot) {
243
+ if (Test-Path -LiteralPath $recoveryRoot) { Remove-Item -LiteralPath $recoveryRoot -Recurse -Force }
244
+ Move-Item -LiteralPath $RuntimeRoot -Destination $recoveryRoot
245
+ }
246
+ try {
247
+ Move-Item -LiteralPath $stageDir -Destination $RuntimeRoot
248
+
249
+ if ((Get-State) -ne 'HEALTHY') {
250
+ throw 'Installed Afyx Forge failed post-installation health check.'
251
+ }
252
+ $verifyOutput = (& (Join-Path $RuntimeRoot 'bin\afyx-forge.cmd') --version 2>&1) -join ' '
253
+ if ($LASTEXITCODE -ne 0 -or $verifyOutput -notmatch 'afyx-forge 0\.1\.0') {
254
+ throw "Installed Afyx Forge CLI verification failed: $verifyOutput"
255
+ }
256
+ } catch {
257
+ if (Test-Path -LiteralPath $RuntimeRoot) { Remove-Item -LiteralPath $RuntimeRoot -Recurse -Force }
258
+ if (Test-Path -LiteralPath $recoveryRoot) { Move-Item -LiteralPath $recoveryRoot -Destination $RuntimeRoot }
259
+ throw
260
+ }
261
+ if (Test-Path -LiteralPath $recoveryRoot) { Remove-Item -LiteralPath $recoveryRoot -Recurse -Force }
262
+ Write-Host "Afyx Forge Core 0.1.0: successfully installed at $RuntimeRoot (revision=$resolvedRevision)"
263
+ } finally {
264
+ if (Test-Path -LiteralPath $stageDir) { Remove-Item -LiteralPath $stageDir -Recurse -Force }
265
+ }