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,438 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+
4
+ PACKAGE_ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
5
+ METADATA="$PACKAGE_ROOT/afyx-graph/afyx-graph.json"
6
+ DISTRIBUTION_PRODUCT="$PACKAGE_ROOT/afyx-graph/engine/scripts/distribution-product.json"
7
+ ARTIFACT_IDENTITY="$PACKAGE_ROOT/scripts/afyx-graph-artifact.mjs"
8
+ RELEASE_ROOT="${AFYX_GRAPH_RELEASE_ROOT:-$PACKAGE_ROOT/afyx-graph/engine/release}"
9
+ RUNTIME_ROOT="${AFYX_GRAPH_RUNTIME_ROOT:-$HOME/.afyx/graph}"
10
+ RECOVERY_ROOT="${RUNTIME_ROOT}.afyx-old"
11
+ BIN_DIR="${AFYX_GRAPH_BIN_DIR:-$HOME/.local/bin}"
12
+ mode=install
13
+ archive_path=
14
+ offline=false
15
+ no_build_fallback=false
16
+ allow_dirty_source=false
17
+ configure_mcp=false
18
+ skip_mcp=false
19
+ artifact_source=
20
+ source_revision=
21
+ requested_revision=UNKNOWN
22
+ artifact_revision=UNKNOWN
23
+ artifact_revision_status=UNKNOWN
24
+
25
+ usage() {
26
+ printf '%s\n' 'Usage: scripts/install-afyx-graph.sh [--replace|--update|--validate-only|--uninstall] [--archive PATH] [--offline] [--no-build-fallback] [--allow-dirty-source] [--configure-mcp|--skip-mcp]'
27
+ }
28
+
29
+ while (($#)); do
30
+ case "$1" in
31
+ --replace) mode=replace; shift ;;
32
+ --update) mode=update; shift ;;
33
+ --validate-only) mode=validate; shift ;;
34
+ --uninstall) mode=uninstall; shift ;;
35
+ --archive) archive_path="$2"; shift 2 ;;
36
+ --offline) offline=true; shift ;;
37
+ --no-build-fallback) no_build_fallback=true; shift ;;
38
+ --allow-dirty-source) allow_dirty_source=true; shift ;;
39
+ --configure-mcp) configure_mcp=true; shift ;;
40
+ --skip-mcp) skip_mcp=true; shift ;;
41
+ -h|--help) usage; exit 0 ;;
42
+ *) printf 'Unknown option: %s\n' "$1" >&2; usage >&2; exit 2 ;;
43
+ esac
44
+ done
45
+
46
+ json_value() {
47
+ sed -n 's/^[[:space:]]*"'"$1"'"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$METADATA" | head -n 1
48
+ }
49
+
50
+ VERSION="$(json_value product_version)"
51
+ CHANNEL="$(sed -n 's/^[[:space:]]*"releaseChannel"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$DISTRIBUTION_PRODUCT" | head -n 1)"
52
+ if [ -e "$PACKAGE_ROOT/.git" ] && command -v git >/dev/null 2>&1 && git -C "$PACKAGE_ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
53
+ requested_revision="$(git -C "$PACKAGE_ROOT" rev-parse HEAD 2>/dev/null || printf UNKNOWN)"
54
+ elif [ -f "$PACKAGE_ROOT/.afyx-source-revision" ]; then
55
+ requested_revision="$(cat "$PACKAGE_ROOT/.afyx-source-revision")"
56
+ case "$requested_revision" in *[!0-9a-f]*|'') printf 'Packaged source revision marker is invalid.\n' >&2; exit 1 ;; esac
57
+ [ "${#requested_revision}" -eq 40 ] || { printf 'Packaged source revision marker is invalid.\n' >&2; exit 1; }
58
+ fi
59
+
60
+ node_version() {
61
+ command -v node >/dev/null 2>&1 || return 1
62
+ node --version 2>/dev/null | sed -n 's/^v\{0,1\}\([0-9][0-9.]*\).*/\1/p'
63
+ }
64
+
65
+ node_compatible() {
66
+ local version major minor
67
+ version="$(node_version)" || return 1
68
+ major="${version%%.*}"; version="${version#*.}"; minor="${version%%.*}"
69
+ [[ "$major" -gt 22 || ("$major" -eq 22 && "$minor" -ge 5) ]]
70
+ }
71
+
72
+ require_host_runtime() {
73
+ local version
74
+ version="$(node_version 2>/dev/null || true)"
75
+ if [[ -z "$version" ]]; then
76
+ printf 'REQUIRED: Node.js was not found on PATH. Afyx Graph requires Node.js 22.5.0 or newer. Install it from https://nodejs.org/ and retry.\n' >&2
77
+ return 1
78
+ fi
79
+ if ! node_compatible; then
80
+ printf 'REQUIRED: Node.js %s is incompatible. Afyx Graph requires Node.js 22.5.0 or newer.\n' "$version" >&2
81
+ return 1
82
+ fi
83
+ }
84
+
85
+ build_local_archive() {
86
+ "$no_build_fallback" && { printf 'COMPONENT_REQUIRED: no matching verified release artifact is available and local build fallback was disabled.\n' >&2; return 1; }
87
+ require_host_runtime
88
+ command -v npm >/dev/null 2>&1 || { printf 'BUILD_ONLY: npm was not found on PATH. It is required only because no verified release artifact was available.\n' >&2; return 1; }
89
+ command -v git >/dev/null 2>&1 || { printf 'BUILD_ONLY: Git is required to validate the local source revision.\n' >&2; return 1; }
90
+ [ -e "$PACKAGE_ROOT/.git" ] && git -C "$PACKAGE_ROOT" rev-parse --is-inside-work-tree >/dev/null 2>&1 || { printf 'BUILD_ONLY: local fallback requires a validated Git checkout.\n' >&2; return 1; }
91
+ source_revision="$(git -C "$PACKAGE_ROOT" rev-parse HEAD)"
92
+ local branch dirty engine release
93
+ branch="$(git -C "$PACKAGE_ROOT" branch --show-current)"
94
+ dirty="$(git -C "$PACKAGE_ROOT" status --porcelain)"
95
+ if [[ -n "$dirty" && "$allow_dirty_source" != true ]]; then
96
+ printf 'BUILD_ONLY: local source has uncommitted changes. Refusing to build an unverifiable Technical Alpha artifact; commit the changes or explicitly use --allow-dirty-source.\n' >&2
97
+ return 1
98
+ fi
99
+ engine="$PACKAGE_ROOT/afyx-graph/engine"
100
+ [[ -f "$engine/package-lock.json" ]] || { printf 'BUILD_ONLY: afyx-graph/engine/package-lock.json is missing; local source is incomplete.\n' >&2; return 1; }
101
+ printf 'Verified release unavailable; building Afyx Graph locally from %s on %s.\n' "$source_revision" "$branch"
102
+ (cd "$engine" && npm ci && npm run build:clean && AFYX_SOURCE_REVISION="$source_revision" bash scripts/build-bundle.sh "$target") || {
103
+ printf 'BUILD_ONLY: Afyx Graph local build failed; the existing installation was not changed.\n' >&2
104
+ return 1
105
+ }
106
+ release="$RELEASE_ROOT"
107
+ archive_path="$release/$asset"
108
+ [[ -f "$archive_path" ]] || { printf 'BUILD_ONLY: local build did not produce %s.\n' "$asset" >&2; return 1; }
109
+ if command -v shasum >/dev/null 2>&1; then
110
+ (cd "$release" && shasum -a 256 "$asset" > SHA256SUMS)
111
+ else
112
+ (cd "$release" && sha256sum "$asset" > SHA256SUMS)
113
+ fi
114
+ artifact_source=local-build
115
+ }
116
+
117
+ archive_checksum_valid() {
118
+ local path="$1" sums expected actual
119
+ sums="$(dirname "$path")/SHA256SUMS"
120
+ [[ -f "$path" && -f "$sums" ]] || return 1
121
+ expected="$(awk -v asset="$asset" '$2 == asset || $2 == "*" asset { print $1; exit }' "$sums")"
122
+ [[ ${#expected} -eq 64 && "$expected" != *[!0-9a-fA-F]* ]] || return 1
123
+ if command -v shasum >/dev/null 2>&1; then
124
+ actual="$(shasum -a 256 "$path" | awk '{print $1}')"
125
+ else
126
+ actual="$(sha256sum "$path" | awk '{print $1}')"
127
+ fi
128
+ [[ "$(printf '%s' "$actual" | tr '[:upper:]' '[:lower:]')" == "$(printf '%s' "$expected" | tr '[:upper:]' '[:lower:]')" ]]
129
+ }
130
+
131
+ archive_bundle_identity_valid() {
132
+ local path="$1" probe bundle
133
+ probe="$(mktemp -d "${TMPDIR:-/tmp}/afyx-graph-probe.XXXXXX")" || return 1
134
+ if ! tar -xzf "$path" -C "$probe" >/dev/null 2>&1; then rm -rf -- "$probe"; return 1; fi
135
+ bundle="$probe/afyx-graph-$target"
136
+ [[ -f "$bundle/bin/afyx-graph" && -f "$bundle/metadata.json" && -f "$bundle/LICENSE" ]] &&
137
+ grep -q '"product_name"[[:space:]]*:[[:space:]]*"Afyx Graph"' "$bundle/metadata.json" &&
138
+ grep -q '"product_version"[[:space:]]*:[[:space:]]*"'"$VERSION"'"' "$bundle/metadata.json" &&
139
+ grep -q '"release_channel"[[:space:]]*:[[:space:]]*"'"$CHANNEL"'"' "$bundle/metadata.json" &&
140
+ grep -q '"'"$target"'"' "$bundle/metadata.json"
141
+ local valid=$?
142
+ rm -rf -- "$probe"
143
+ return "$valid"
144
+ }
145
+
146
+ read_archive_identity() {
147
+ local path="$1" probe bundle json
148
+ probe="$(mktemp -d "${TMPDIR:-/tmp}/afyx-graph-identity.XXXXXX")" || return 1
149
+ if ! tar -xzf "$path" -C "$probe" >/dev/null 2>&1; then rm -rf -- "$probe"; return 1; fi
150
+ bundle="$probe/afyx-graph-$target"
151
+ json="$(node "$ARTIFACT_IDENTITY" inspect --metadata "$bundle/metadata.json" --requested-revision "$requested_revision")" || {
152
+ rm -rf -- "$probe"; return 1;
153
+ }
154
+ artifact_revision="$(printf '%s' "$json" | sed -n 's/.*"sourceRevision":"\([^"]*\)".*/\1/p')"
155
+ artifact_revision_status="$(printf '%s' "$json" | sed -n 's/.*"revisionStatus":"\([^"]*\)".*/\1/p')"
156
+ rm -rf -- "$probe"
157
+ }
158
+
159
+ graph_state() {
160
+ if [[ ! -e "$RUNTIME_ROOT" ]]; then printf '%s' 'NOT INSTALLED'; return; fi
161
+ if [[ ! -f "$RUNTIME_ROOT/metadata.json" || ! -x "$RUNTIME_ROOT/current/bin/afyx-graph" ]]; then
162
+ printf '%s' 'INCOMPLETE'; return
163
+ fi
164
+ if ! grep -q '"product_name"[[:space:]]*:[[:space:]]*"Afyx Graph"' "$RUNTIME_ROOT/metadata.json"; then
165
+ printf '%s' 'INVALID'; return
166
+ fi
167
+ printf '%s' 'HEALTHY'
168
+ }
169
+
170
+ graph_owned_at() {
171
+ local root="$1"
172
+ [[ -f "$root/metadata.json" ]] &&
173
+ grep -q '"product_name"[[:space:]]*:[[:space:]]*"Afyx Graph"' "$root/metadata.json"
174
+ }
175
+
176
+ graph_owned() { graph_owned_at "$RUNTIME_ROOT"; }
177
+
178
+ if [[ -e "$RECOVERY_ROOT" ]]; then
179
+ if [[ -e "$RUNTIME_ROOT" ]]; then
180
+ printf 'Interrupted Graph transaction is ambiguous: both %s and %s exist. Refusing to modify either path.\n' "$RUNTIME_ROOT" "$RECOVERY_ROOT" >&2
181
+ exit 1
182
+ fi
183
+ if [[ "$mode" == validate || "$mode" == uninstall ]]; then
184
+ printf 'Interrupted Graph transaction found at %s. Retry the original install/update operation to restore it before validation or removal.\n' "$RECOVERY_ROOT" >&2
185
+ exit 1
186
+ fi
187
+ graph_owned_at "$RECOVERY_ROOT" || {
188
+ printf 'Refusing to restore %s because Afyx Graph ownership cannot be verified.\n' "$RECOVERY_ROOT" >&2
189
+ exit 1
190
+ }
191
+ mv "$RECOVERY_ROOT" "$RUNTIME_ROOT"
192
+ printf 'Recovered interrupted Afyx Graph transaction at %s.\n' "$RUNTIME_ROOT"
193
+ fi
194
+
195
+ state="$(graph_state)"
196
+ if [[ "$mode" == validate ]]; then
197
+ installed_revision=
198
+ installed_extraction=
199
+ installed_provenance=
200
+ installed_manifest_status=
201
+ installed_publisher_authenticity=
202
+ installed_build_provenance=
203
+ installed_revision_status=
204
+ if [[ -f "$RUNTIME_ROOT/metadata.json" ]]; then
205
+ installed_revision="$(sed -n 's/.*"source_revision"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$RUNTIME_ROOT/metadata.json" | head -n 1)"
206
+ installed_extraction="$(sed -n 's/.*"extraction_version"[[:space:]]*:[[:space:]]*\([0-9][0-9]*\).*/\1/p' "$RUNTIME_ROOT/metadata.json" | head -n 1)"
207
+ installed_provenance="$(sed -n 's/.*"artifact_provenance"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$RUNTIME_ROOT/metadata.json" | head -n 1)"
208
+ installed_manifest_status="$(sed -n 's/.*"release_manifest_status"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$RUNTIME_ROOT/metadata.json" | head -n 1)"
209
+ installed_publisher_authenticity="$(sed -n 's/.*"publisher_authenticity"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$RUNTIME_ROOT/metadata.json" | head -n 1)"
210
+ installed_build_provenance="$(sed -n 's/.*"build_provenance"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$RUNTIME_ROOT/metadata.json" | head -n 1)"
211
+ installed_revision_status="$(sed -n 's/.*"revision_status"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' "$RUNTIME_ROOT/metadata.json" | head -n 1)"
212
+ fi
213
+ if [[ -n "$installed_revision" && "$requested_revision" != UNKNOWN ]]; then
214
+ if [[ "$installed_revision" == "$requested_revision" ]]; then installed_revision_status=MATCH; else installed_revision_status=REVISION_MISMATCH; fi
215
+ else installed_revision_status=UNKNOWN; fi
216
+ printf 'Product: Afyx Graph\nState: %s\nRuntimeRoot: %s\nVersion: %s\nSourceRevision: %s\nExtractionVersion: %s\nProvenance: %s\nReleaseManifestStatus: %s\nPublisherAuthenticity: %s\nBuildProvenance: %s\nCurrentCheckoutRevision: %s\nRevisionStatus: %s\nUpdateAvailable: %s\n' "$state" "$RUNTIME_ROOT" "$VERSION" "${installed_revision:-UNKNOWN}" "${installed_extraction:-UNKNOWN}" "${installed_provenance:-UNKNOWN}" "${installed_manifest_status:-MISSING}" "${installed_publisher_authenticity:-UNVERIFIED}" "${installed_build_provenance:-UNVERIFIED}" "$requested_revision" "$installed_revision_status" "$([[ "$installed_revision_status" == REVISION_MISMATCH ]] && printf true || printf false)"
217
+ if [[ "$installed_revision_status" == REVISION_MISMATCH ]]; then printf 'UPDATE AVAILABLE — REVISION MISMATCH\n'; fi
218
+ [[ "$state" != INCOMPLETE && "$state" != INVALID ]]
219
+ exit $?
220
+ fi
221
+
222
+ if [[ "$mode" == uninstall ]]; then
223
+ if [[ "$state" == 'NOT INSTALLED' ]]; then printf 'Afyx Graph: not installed\n'; exit 0; fi
224
+ graph_owned || { printf 'Refusing to remove %s because Afyx Graph ownership cannot be verified.\n' "$RUNTIME_ROOT" >&2; exit 1; }
225
+ rm -rf -- "$RUNTIME_ROOT"
226
+ if [[ -L "$BIN_DIR/afyx-graph" ]]; then
227
+ link_target="$(readlink "$BIN_DIR/afyx-graph")"
228
+ case "$link_target" in "$RUNTIME_ROOT"/*) rm -f -- "$BIN_DIR/afyx-graph" ;; esac
229
+ fi
230
+ printf 'Afyx Graph: removed; project .afyx-graph indexes were not changed.\n'
231
+ exit 0
232
+ fi
233
+
234
+ if [[ "$state" != 'NOT INSTALLED' && "$mode" == install ]]; then
235
+ printf 'Afyx Graph already exists at %s. Use --replace after inspecting it.\n' "$RUNTIME_ROOT" >&2
236
+ exit 1
237
+ fi
238
+ if [[ "$state" != 'NOT INSTALLED' ]] && ! graph_owned; then
239
+ printf 'Refusing to replace %s because Afyx Graph ownership cannot be verified.\n' "$RUNTIME_ROOT" >&2
240
+ exit 1
241
+ fi
242
+
243
+ case "$(uname -s)" in
244
+ Darwin) os=darwin ;;
245
+ Linux) os=linux ;;
246
+ *) printf 'Unsupported operating system: %s\n' "$(uname -s)" >&2; exit 1 ;;
247
+ esac
248
+ case "$(uname -m)" in
249
+ x86_64|amd64) arch=x64 ;;
250
+ arm64|aarch64) arch=arm64 ;;
251
+ *) printf 'Unsupported architecture: %s\n' "$(uname -m)" >&2; exit 1 ;;
252
+ esac
253
+ target="$os-$arch"
254
+ if [[ "$target" != linux-x64 ]]; then
255
+ printf 'Afyx Graph prebuilt runtime is unavailable for %s. Minimal and Recommended Kit presets remain available; consumer source compilation is disabled.\n' "$target" >&2
256
+ exit 2
257
+ fi
258
+ asset="afyx-graph-$target.tar.gz"
259
+
260
+ require_host_runtime
261
+
262
+ parent="$(dirname "$RUNTIME_ROOT")"
263
+ mkdir -p "$parent"
264
+ transaction="$(mktemp -d "$parent/.graph-stage.XXXXXX")"
265
+ backup="$RECOVERY_ROOT"
266
+ cleanup() { rm -rf -- "$transaction"; }
267
+ trap cleanup EXIT
268
+
269
+ if [[ -z "$archive_path" ]]; then
270
+ local_archive="$RELEASE_ROOT/$asset"
271
+ if [[ -f "$local_archive" ]]; then
272
+ if archive_checksum_valid "$local_archive" && archive_bundle_identity_valid "$local_archive" && read_archive_identity "$local_archive"; then
273
+ if [[ "$requested_revision" != UNKNOWN && "$artifact_revision_status" != MATCH ]]; then
274
+ printf 'Ignoring valid but stale local release cache (requested %s; artifact %s); rebuilding from validated source.\n' "$requested_revision" "$artifact_revision" >&2
275
+ build_local_archive
276
+ else
277
+ archive_path="$local_archive"
278
+ artifact_source=local-release-cache
279
+ source_revision="$artifact_revision"
280
+ fi
281
+ else
282
+ printf 'Ignoring invalid local release cache; rebuilding from validated source.\n' >&2
283
+ build_local_archive
284
+ fi
285
+ else
286
+ if [[ "$offline" != true ]] && command -v curl >/dev/null 2>&1; then
287
+ archive_path="$transaction/$asset"
288
+ url="https://github.com/a5zero7/afyx-engineering-kit/releases/download/afyx-graph-v$VERSION/$asset"
289
+ if curl -fsSL "$url" -o "$archive_path" &&
290
+ curl -fsSL "https://github.com/a5zero7/afyx-engineering-kit/releases/download/afyx-graph-v$VERSION/SHA256SUMS" -o "$transaction/SHA256SUMS" &&
291
+ curl -fsSL "https://github.com/a5zero7/afyx-engineering-kit/releases/download/afyx-graph-v$VERSION/RELEASE-MANIFEST.json" -o "$transaction/RELEASE-MANIFEST.json"; then
292
+ artifact_source=github-release
293
+ if ! archive_checksum_valid "$archive_path" || ! archive_bundle_identity_valid "$archive_path" || ! read_archive_identity "$archive_path"; then
294
+ printf 'Downloaded release artifact failed integrity or identity validation; trying bounded local build fallback.\n' >&2
295
+ rm -f -- "$archive_path" "$transaction/SHA256SUMS" "$transaction/RELEASE-MANIFEST.json"
296
+ build_local_archive
297
+ elif [[ "$requested_revision" != UNKNOWN && "$artifact_revision_status" != MATCH ]]; then
298
+ printf 'Downloaded release revision %s does not match requested checkout %s; trying bounded local build fallback.\n' "$artifact_revision" "$requested_revision" >&2
299
+ rm -f -- "$archive_path" "$transaction/SHA256SUMS" "$transaction/RELEASE-MANIFEST.json"
300
+ build_local_archive
301
+ else
302
+ source_revision="$artifact_revision"
303
+ fi
304
+ else
305
+ printf 'Verified GitHub release unavailable; trying bounded local build fallback.\n' >&2
306
+ rm -f -- "$archive_path" "$transaction/SHA256SUMS" "$transaction/RELEASE-MANIFEST.json"
307
+ archive_path=
308
+ build_local_archive
309
+ fi
310
+ else
311
+ [[ "$offline" == true ]] && printf 'Offline mode: skipping GitHub release lookup.\n'
312
+ [[ "$offline" != true ]] && printf 'COMPONENT_REQUIRED: curl is unavailable; trying bounded local build fallback.\n' >&2
313
+ build_local_archive
314
+ fi
315
+ fi
316
+ else
317
+ artifact_source=explicit-archive
318
+ fi
319
+ [[ -f "$archive_path" ]] || { printf 'Archive not found: %s\n' "$archive_path" >&2; exit 1; }
320
+ sums="$(dirname "$archive_path")/SHA256SUMS"
321
+ [[ -f "$sums" ]] || { printf 'SHA256SUMS is required beside %s\n' "$archive_path" >&2; exit 1; }
322
+ expected="$(awk -v asset="$asset" '$2 == asset || $2 == "*" asset { print $1; exit }' "$sums")"
323
+ [[ ${#expected} -eq 64 && "$expected" != *[!0-9a-fA-F]* ]] || { printf 'No valid SHA256SUMS entry for %s\n' "$asset" >&2; exit 1; }
324
+ if command -v shasum >/dev/null 2>&1; then actual="$(shasum -a 256 "$archive_path" | awk '{print $1}')"; else actual="$(sha256sum "$archive_path" | awk '{print $1}')"; fi
325
+ actual_lower="$(printf '%s' "$actual" | tr '[:upper:]' '[:lower:]')"
326
+ expected_lower="$(printf '%s' "$expected" | tr '[:upper:]' '[:lower:]')"
327
+ [[ "$actual_lower" == "$expected_lower" ]] || { printf 'Checksum mismatch for %s\n' "$asset" >&2; exit 1; }
328
+
329
+ mkdir -p "$transaction/extract" "$transaction/prepared"
330
+ tar -xzf "$archive_path" -C "$transaction/extract"
331
+ bundle="$transaction/extract/afyx-graph-$target"
332
+ for required in bin/afyx-graph metadata.json LICENSE; do
333
+ [[ -f "$bundle/$required" ]] || { printf 'Staged Afyx Graph bundle is incomplete: %s\n' "$required" >&2; exit 1; }
334
+ done
335
+ grep -q '"product_version"[[:space:]]*:[[:space:]]*"'"$VERSION"'"' "$bundle/metadata.json" || {
336
+ printf 'Staged Afyx Graph version does not match metadata.\n' >&2; exit 1;
337
+ }
338
+ grep -q '"product_name"[[:space:]]*:[[:space:]]*"Afyx Graph"' "$bundle/metadata.json" || { printf 'Staged Afyx Graph identity is invalid.\n' >&2; exit 1; }
339
+ grep -q '"release_channel"[[:space:]]*:[[:space:]]*"'"$CHANNEL"'"' "$bundle/metadata.json" || { printf 'Staged Afyx Graph release channel is invalid.\n' >&2; exit 1; }
340
+ grep -q '"'"$target"'"' "$bundle/metadata.json" || { printf 'Staged Afyx Graph does not support %s.\n' "$target" >&2; exit 1; }
341
+ node "$PACKAGE_ROOT/afyx-graph/engine/scripts/distribution-contract.mjs" verify-bundle --root "$bundle" --target "$target" >/dev/null || {
342
+ printf 'Afyx Graph staged bundle failed the distribution contract.\n' >&2
343
+ exit 1
344
+ }
345
+ identity_json="$(node "$ARTIFACT_IDENTITY" inspect --metadata "$bundle/metadata.json" --requested-revision "$requested_revision")"
346
+ identity_extraction="$(printf '%s' "$identity_json" | sed -n 's/.*"extractionVersion":\([0-9][0-9]*\).*/\1/p')"
347
+ if [[ -n "$identity_extraction" ]]; then
348
+ compiled_extraction="$(node -e 'process.stdout.write(String(require(process.argv[1]).EXTRACTION_VERSION))' "$bundle/lib/dist/extraction/extraction-version.js")"
349
+ [[ "$compiled_extraction" == "$identity_extraction" ]] || { printf 'Installed artifact extraction identity mismatch: metadata %s, compiled runtime %s.\n' "$identity_extraction" "$compiled_extraction" >&2; exit 1; }
350
+ fi
351
+ release_manifest="$(dirname "$archive_path")/RELEASE-MANIFEST.json"
352
+ manifest_status=MISSING
353
+ publisher_authenticity=UNVERIFIED
354
+ build_provenance=UNVERIFIED
355
+ if [[ -f "$release_manifest" ]]; then
356
+ node "$ARTIFACT_IDENTITY" verify-release-manifest --manifest "$release_manifest" --archive "$archive_path" --metadata "$bundle/metadata.json" >/dev/null || {
357
+ printf 'Release manifest verification failed.\n' >&2; exit 1;
358
+ }
359
+ manifest_status=VERIFIED
360
+ build_provenance=COMMIT_BOUND_MANIFEST
361
+ elif [[ "$artifact_source" == github-release ]]; then
362
+ printf 'GitHub release is missing RELEASE-MANIFEST.json.\n' >&2
363
+ exit 1
364
+ fi
365
+ if [[ "$artifact_source" == github-release ]] && command -v gh >/dev/null 2>&1; then
366
+ gh attestation verify "$archive_path" --repo a5zero7/afyx-engineering-kit >/dev/null 2>&1 || {
367
+ printf 'GitHub publisher/build attestation verification failed.\n' >&2; exit 1;
368
+ }
369
+ publisher_authenticity=GITHUB_ATTESTED
370
+ build_provenance=GITHUB_ATTESTED
371
+ fi
372
+ node "$ARTIFACT_IDENTITY" record-install --metadata "$bundle/metadata.json" --archive "$archive_path" --provenance "$artifact_source" --requested-revision "$requested_revision" --release-manifest-status "$manifest_status" --publisher-authenticity "$publisher_authenticity" --build-provenance "$build_provenance" >/dev/null
373
+ mv "$bundle" "$transaction/prepared/current"
374
+ cp "$transaction/prepared/current/metadata.json" "$transaction/prepared/metadata.json"
375
+
376
+ had_existing=false
377
+ if [[ -e "$RUNTIME_ROOT" ]]; then mv "$RUNTIME_ROOT" "$backup"; had_existing=true; fi
378
+ if ! mv "$transaction/prepared" "$RUNTIME_ROOT"; then
379
+ "$had_existing" && mv "$backup" "$RUNTIME_ROOT"
380
+ exit 1
381
+ fi
382
+ if [[ "$(graph_state)" != HEALTHY ]]; then
383
+ rm -rf -- "$RUNTIME_ROOT"
384
+ "$had_existing" && mv "$backup" "$RUNTIME_ROOT"
385
+ printf 'Installed Afyx Graph failed post-swap validation; previous runtime restored.\n' >&2
386
+ exit 1
387
+ fi
388
+ if ! version_output="$($RUNTIME_ROOT/current/bin/afyx-graph --version 2>&1)" || [[ "$version_output" != *"$VERSION"* ]]; then
389
+ rm -rf -- "$RUNTIME_ROOT"
390
+ "$had_existing" && mv "$backup" "$RUNTIME_ROOT"
391
+ printf 'Installed Afyx Graph CLI verification failed: %s\n' "$version_output" >&2
392
+ exit 1
393
+ fi
394
+ if ! "$RUNTIME_ROOT/current/bin/afyx-graph" help >/dev/null 2>&1; then
395
+ rm -rf -- "$RUNTIME_ROOT"
396
+ "$had_existing" && mv "$backup" "$RUNTIME_ROOT"
397
+ printf 'Installed Afyx Graph help command failed; previous runtime restored.\n' >&2
398
+ exit 1
399
+ fi
400
+ "$had_existing" && rm -rf -- "$backup"
401
+
402
+ mkdir -p "$BIN_DIR"
403
+ destination="$BIN_DIR/afyx-graph"
404
+ if [[ -e "$destination" && ! -L "$destination" ]]; then
405
+ printf 'Existing afyx-graph executable left untouched at %s\n' "$destination"
406
+ elif [[ -L "$destination" ]]; then
407
+ link_target="$(readlink "$destination")"
408
+ case "$link_target" in
409
+ "$RUNTIME_ROOT"/*) ln -sfn "$RUNTIME_ROOT/current/bin/afyx-graph" "$destination" ;;
410
+ *) printf 'External afyx-graph symlink left untouched at %s\n' "$destination" ;;
411
+ esac
412
+ else
413
+ ln -s "$RUNTIME_ROOT/current/bin/afyx-graph" "$destination"
414
+ fi
415
+
416
+ mcp_state=MCP_NOT_CONFIGURED
417
+ if "$skip_mcp"; then
418
+ printf 'Afyx Graph MCP: skipped explicitly.\n'
419
+ else
420
+ codex_home="${CODEX_HOME:-$HOME/.codex}"
421
+ mcp_args=("$PACKAGE_ROOT/scripts/afyx-mcp-integration.mjs" --node "$(command -v node)" --entry "$RUNTIME_ROOT/current/lib/dist/bin/afyx-graph.js" --codex-home "$codex_home")
422
+ if command -v codex >/dev/null 2>&1; then mcp_args+=(--codex "$(command -v codex)"); fi
423
+ "$configure_mcp" && mcp_args+=(--apply)
424
+ set +e
425
+ mcp_json="$(node "${mcp_args[@]}" 2>/dev/null)"; mcp_exit=$?
426
+ set -e
427
+ mcp_state="$(printf '%s' "$mcp_json" | sed -n 's/.*"mcp":"\([^"]*\)".*/\1/p')"
428
+ mcp_detail="$(printf '%s' "$mcp_json" | sed -n 's/.*"detail":"\([^"]*\)".*/\1/p')"
429
+ [[ -n "$mcp_state" ]] || mcp_state=MCP_BLOCKED
430
+ printf 'Afyx Graph MCP: %s — %s\n' "$mcp_state" "$mcp_detail"
431
+ if [[ "$configure_mcp" != true && "$mcp_state" == MCP_NOT_CONFIGURED ]]; then
432
+ printf 'Registration available: rerun the selected Graph lifecycle with --configure-mcp (or use the main installer selection).\n'
433
+ fi
434
+ : "$mcp_exit"
435
+ fi
436
+
437
+ printf 'Afyx Graph %s [%s]: installed at %s\nArtifact source: %s; source revision: %s\nCLI: %s/afyx-graph\n' "$VERSION" "$CHANNEL" "$RUNTIME_ROOT" "$artifact_source" "${source_revision:-UNKNOWN}" "$BIN_DIR"
438
+ if "$skip_mcp"; then printf 'MCP configuration was not changed.\n'; fi
@@ -0,0 +1,172 @@
1
+ [CmdletBinding(SupportsShouldProcess)]
2
+ param(
3
+ [string]$CodexHome = $(if ($env:CODEX_HOME) { $env:CODEX_HOME } else { Join-Path $env:USERPROFILE '.codex' }),
4
+ [string]$VSCodeUserTasksPath = (Join-Path $env:APPDATA 'Code\User\tasks.json'),
5
+ [string]$HooksPath,
6
+ [switch]$SkipVSCodeTask,
7
+ [switch]$Uninstall
8
+ )
9
+
10
+ Set-StrictMode -Version Latest
11
+ $ErrorActionPreference = 'Stop'
12
+ if ($PSVersionTable.PSVersion.Major -lt 7) {
13
+ throw 'Codex Usage Tracker requires PowerShell 7+. Core Afyx installation compatibility is separate.'
14
+ }
15
+
16
+ $sourceRoot = Join-Path (Split-Path -Parent $PSScriptRoot) 'tools\codex-usage'
17
+ $toolsRoot = Join-Path $CodexHome 'tools'
18
+ if (-not $HooksPath) { $HooksPath = Join-Path $CodexHome 'hooks.json' }
19
+ $runtimeFiles = @('CodexUsage.psm1', 'codex-usage-stop.ps1', 'codex-usage-watch.ps1', 'codex-usage-doctor.ps1', 'codex-usage-pricing.json')
20
+ $taskLabel = 'Codex: Watch Token Usage'
21
+ $hookMarker = 'Afyx Codex Usage Tracking'
22
+
23
+ function Read-JsonDocument {
24
+ param([string]$Path, [string]$Kind)
25
+
26
+ if (-not (Test-Path -LiteralPath $Path -PathType Leaf)) { return $null }
27
+ try { return Get-Content -Raw -LiteralPath $Path | ConvertFrom-Json -Depth 50 -ErrorAction Stop }
28
+ catch { throw "Existing $Kind is not strict JSON; refusing to overwrite it: $Path" }
29
+ }
30
+
31
+ function Write-JsonDocument {
32
+ param([string]$Path, [object]$Document, [string]$Action)
33
+
34
+ $json = $Document | ConvertTo-Json -Depth 50
35
+ if ((Test-Path -LiteralPath $Path -PathType Leaf) -and (Get-Content -Raw -LiteralPath $Path) -eq $json) { return $false }
36
+ if (-not $PSCmdlet.ShouldProcess($Path, $Action)) { return $false }
37
+ $parent = Split-Path -Parent $Path
38
+ if ($parent) { [IO.Directory]::CreateDirectory($parent) | Out-Null }
39
+ if (Test-Path -LiteralPath $Path -PathType Leaf) {
40
+ Copy-Item -LiteralPath $Path -Destination "$Path.bak-$(Get-Date -Format 'yyyyMMdd-HHmmss-fff')"
41
+ }
42
+ $temporary = "$Path.tmp-$PID"
43
+ [IO.File]::WriteAllText($temporary, $json, [Text.UTF8Encoding]::new($false))
44
+ Move-Item -Force -LiteralPath $temporary -Destination $Path
45
+ return $true
46
+ }
47
+
48
+ function Test-AfyxHookHandler {
49
+ param([object]$Handler)
50
+
51
+ if ($null -eq $Handler) { return $false }
52
+ if ($Handler.PSObject.Properties['statusMessage'] -and [string]$Handler.statusMessage -eq $hookMarker) { return $true }
53
+ foreach ($property in @('command', 'commandWindows')) {
54
+ if ($Handler.PSObject.Properties[$property] -and [string]$Handler.$property -match '(?i)codex-usage-stop\.ps1') { return $true }
55
+ }
56
+ return $false
57
+ }
58
+
59
+ function Update-HooksDocument {
60
+ param([switch]$Remove)
61
+
62
+ $document = Read-JsonDocument -Path $HooksPath -Kind 'Codex hooks file'
63
+ if ($Remove -and $null -eq $document) { return }
64
+ if ($null -eq $document) { $document = [pscustomobject]@{ hooks = [pscustomobject]@{} } }
65
+ if (-not $document.PSObject.Properties['hooks']) { $document | Add-Member -NotePropertyName hooks -NotePropertyValue ([pscustomobject]@{}) }
66
+ if ($null -eq $document.hooks) { $document.hooks = [pscustomobject]@{} }
67
+
68
+ $stopGroups = if ($document.hooks.PSObject.Properties['Stop']) { @($document.hooks.Stop) } else { @() }
69
+ $keptGroups = [System.Collections.Generic.List[object]]::new()
70
+ foreach ($group in $stopGroups) {
71
+ $handlers = if ($group.PSObject.Properties['hooks']) { @($group.hooks) } else { @() }
72
+ $ownedCount = @($handlers | Where-Object { Test-AfyxHookHandler $_ }).Count
73
+ if ($ownedCount -eq 0) { $keptGroups.Add($group); continue }
74
+ $remaining = @($handlers | Where-Object { -not (Test-AfyxHookHandler $_) })
75
+ if ($remaining.Count -gt 0) {
76
+ $group.hooks = $remaining
77
+ $keptGroups.Add($group)
78
+ }
79
+ }
80
+
81
+ if (-not $Remove) {
82
+ $stopScript = Join-Path $toolsRoot 'codex-usage-stop.ps1'
83
+ $quotedPath = '"' + $stopScript.Replace('"', '\"') + '"'
84
+ $command = "pwsh -NoProfile -ExecutionPolicy Bypass -File $quotedPath"
85
+ $handler = [pscustomobject]@{
86
+ type = 'command'
87
+ command = $command
88
+ commandWindows = $command
89
+ timeout = 3
90
+ statusMessage = $hookMarker
91
+ }
92
+ $keptGroups.Add([pscustomobject]@{ hooks = @($handler) })
93
+ }
94
+
95
+ if ($document.hooks.PSObject.Properties['Stop']) {
96
+ $document.hooks.Stop = $keptGroups.ToArray()
97
+ } elseif ($keptGroups.Count -gt 0) {
98
+ $document.hooks | Add-Member -NotePropertyName Stop -NotePropertyValue $keptGroups.ToArray()
99
+ }
100
+ if ($Remove -and $keptGroups.Count -eq 0 -and $document.hooks.PSObject.Properties['Stop']) {
101
+ $document.hooks.PSObject.Properties.Remove('Stop')
102
+ }
103
+ [void](Write-JsonDocument -Path $HooksPath -Document $document -Action $(if ($Remove) { 'Remove Afyx usage Stop hook' } else { 'Configure Afyx usage Stop hook' }))
104
+ }
105
+
106
+ function Update-VSCodeTaskDocument {
107
+ param([switch]$Remove)
108
+
109
+ $document = Read-JsonDocument -Path $VSCodeUserTasksPath -Kind 'VS Code tasks file'
110
+ if ($Remove) {
111
+ if ($null -eq $document -or -not $document.PSObject.Properties['tasks']) { return }
112
+ $document.tasks = @($document.tasks | Where-Object { [string]$_.label -ne $taskLabel })
113
+ } else {
114
+ $template = Get-Content -Raw -LiteralPath (Join-Path $sourceRoot 'vscode-user-task.json') | ConvertFrom-Json -Depth 20
115
+ $newTask = $template.tasks[0]
116
+ if ($null -eq $document) { $document = $template }
117
+ else {
118
+ if (-not $document.PSObject.Properties['tasks']) { $document | Add-Member -NotePropertyName tasks -NotePropertyValue @() }
119
+ $document.tasks = @($document.tasks | Where-Object { [string]$_.label -ne $taskLabel }) + $newTask
120
+ }
121
+ }
122
+ [void](Write-JsonDocument -Path $VSCodeUserTasksPath -Document $document -Action $(if ($Remove) { 'Remove Afyx VS Code usage task' } else { 'Install global VS Code usage task' }))
123
+ }
124
+
125
+ if ($Uninstall) {
126
+ Update-HooksDocument -Remove
127
+ if (-not $SkipVSCodeTask) { Update-VSCodeTaskDocument -Remove }
128
+ foreach ($file in $runtimeFiles) {
129
+ $target = Join-Path $toolsRoot $file
130
+ if ((Test-Path -LiteralPath $target -PathType Leaf) -and $PSCmdlet.ShouldProcess($target, 'Remove Afyx usage tracker runtime file')) {
131
+ Remove-Item -LiteralPath $target -Force
132
+ }
133
+ }
134
+ Write-Host 'Codex Usage Tracking: removed (unrelated hooks and tasks preserved)'
135
+ return
136
+ }
137
+
138
+ # Validate user-owned JSON before copying runtime files so malformed configuration
139
+ # cannot leave a partially updated installation.
140
+ [void](Read-JsonDocument -Path $HooksPath -Kind 'Codex hooks file')
141
+ if (-not $SkipVSCodeTask) { [void](Read-JsonDocument -Path $VSCodeUserTasksPath -Kind 'VS Code tasks file') }
142
+
143
+ if ($PSCmdlet.ShouldProcess($toolsRoot, 'Install Codex usage tracker runtime')) {
144
+ [IO.Directory]::CreateDirectory($toolsRoot) | Out-Null
145
+ foreach ($file in $runtimeFiles) {
146
+ $source = Join-Path $sourceRoot $file
147
+ if (-not (Test-Path -LiteralPath $source -PathType Leaf)) { throw "Missing tracker file: $source" }
148
+ Copy-Item -Force -LiteralPath $source -Destination (Join-Path $toolsRoot $file)
149
+ }
150
+ }
151
+
152
+ Update-HooksDocument
153
+ if (-not $SkipVSCodeTask) { Update-VSCodeTaskDocument }
154
+
155
+ if (-not $WhatIfPreference) {
156
+ $missingRuntime = @($runtimeFiles | Where-Object { -not (Test-Path -LiteralPath (Join-Path $toolsRoot $_) -PathType Leaf) })
157
+ if ($missingRuntime.Count -gt 0) { throw "Usage Tracker installation incomplete: $($missingRuntime -join ', ')" }
158
+ $verifiedHooks = Read-JsonDocument -Path $HooksPath -Kind 'Codex hooks file'
159
+ $verifiedHandlers = @($verifiedHooks.hooks.Stop | ForEach-Object { $_.hooks } | Where-Object { Test-AfyxHookHandler $_ })
160
+ if ($verifiedHandlers.Count -ne 1) { throw "Expected exactly one Afyx Stop hook after installation; found $($verifiedHandlers.Count)." }
161
+ $expectedStopPath = [IO.Path]::GetFullPath((Join-Path $toolsRoot 'codex-usage-stop.ps1'))
162
+ $verifiedCommand = if ($verifiedHandlers[0].PSObject.Properties['commandWindows']) { [string]$verifiedHandlers[0].commandWindows } else { [string]$verifiedHandlers[0].command }
163
+ if ($verifiedCommand -notmatch [regex]::Escape($expectedStopPath)) { throw 'Installed Stop hook command does not point to the expected runtime script.' }
164
+ }
165
+
166
+ Write-Host 'Codex Usage Tracking: installed'
167
+ Write-Host 'Automatic UI usage message: configured'
168
+ Write-Host 'Terminal watcher fallback: installed'
169
+ Write-Host 'Usage doctor: installed'
170
+ if (-not $SkipVSCodeTask) { Write-Host 'VS Code User Task: installed' }
171
+ Write-Host 'Hook trust: review required via /hooks'
172
+ Write-Host 'Start a fresh Codex CLI session or reload VS Code after hook installation or changes.'