ctxtop 0.0.0-stage → 4.0.0

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 (240) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +149 -0
  4. package/LICENSE +27 -0
  5. package/README.md +330 -3
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +145 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1474 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +114 -0
  25. package/config/modelCatalog.json +620 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +262 -0
  28. package/hooks/handlers/hookIo.mjs +255 -0
  29. package/hooks/handlers/hookIpcClient.mjs +83 -0
  30. package/hooks/handlers/post-tool-use.mjs +265 -0
  31. package/hooks/handlers/pre-model-switch.mjs +249 -0
  32. package/hooks/handlers/pre-tool-use.mjs +365 -0
  33. package/hooks/handlers/stop-gate.mjs +240 -0
  34. package/hooks/handlers/user-prompt-submit.mjs +143 -0
  35. package/hooks/hooks.json +81 -0
  36. package/hooks/post_invocation.mjs +13 -0
  37. package/hooks/post_tool_use.mjs +17 -0
  38. package/hooks/pre_invocation.mjs +14 -0
  39. package/hooks/pre_tool_use.mjs +97 -0
  40. package/hooks/register.js +687 -0
  41. package/hooks/session_start.mjs +14 -0
  42. package/hooks/stop.mjs +13 -0
  43. package/hooks.json +56 -0
  44. package/package.json +103 -4
  45. package/packages/antigravity/package.json +14 -0
  46. package/packages/antigravity/src/index.mjs +1 -0
  47. package/packages/claude-code/package.json +14 -0
  48. package/packages/claude-code/src/index.mjs +2 -0
  49. package/packages/core/package.json +14 -0
  50. package/packages/core/src/index.mjs +1 -0
  51. package/packages/engine-node/package.json +14 -0
  52. package/packages/engine-node/src/index.mjs +1 -0
  53. package/packages/mcp/package.json +17 -0
  54. package/packages/mcp/src/server.mjs +396 -0
  55. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  56. package/packages/pro/README-SIGNING.md +30 -0
  57. package/packages/pro/package.json +16 -0
  58. package/packages/pro/src/index.mjs +3 -0
  59. package/packages/pro/src/team_finops_pack.mjs +241 -0
  60. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  61. package/plugin.json +36 -0
  62. package/rules/AGENTS.md +10 -0
  63. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  64. package/sidecars/horizon-daemon/server.mjs +2002 -0
  65. package/sidecars/horizon-daemon/sidecar.json +19 -0
  66. package/skills/cost-radar/SKILL.md +21 -0
  67. package/skills/evolve/SKILL.md +21 -0
  68. package/skills/handoff/SKILL.md +42 -0
  69. package/skills/horizon/SKILL.md +17 -0
  70. package/skills/inspect/SKILL.md +18 -0
  71. package/skills/precheck/SKILL.md +44 -0
  72. package/src/adapters/antigravity/index.mjs +79 -0
  73. package/src/adapters/claude-code/index.mjs +155 -0
  74. package/src/cli/cost_radar.mjs +70 -0
  75. package/src/cli/doctor.mjs +351 -0
  76. package/src/cli/horizon_hud.mjs +686 -0
  77. package/src/cli/init.mjs +425 -0
  78. package/src/cli/postmortem.mjs +515 -0
  79. package/src/coach/cacheGravityRouter.mjs +12 -0
  80. package/src/config/modelCatalog.json +620 -0
  81. package/src/config/platformQuirks.json +19 -0
  82. package/src/core/action_queue.mjs +264 -0
  83. package/src/core/ag_bridge.mjs +346 -0
  84. package/src/core/atomic_io.mjs +124 -0
  85. package/src/core/baseline.mjs +607 -0
  86. package/src/core/blindspot_sensors.mjs +399 -0
  87. package/src/core/classifier.mjs +1757 -0
  88. package/src/core/coach/circuit_breakers.mjs +650 -0
  89. package/src/core/coach/contradiction_auditor.mjs +239 -0
  90. package/src/core/coach/effort_advisor.mjs +143 -0
  91. package/src/core/coach/handoff_hydrator.mjs +483 -0
  92. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  93. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  94. package/src/core/coach/reflector_queue.mjs +505 -0
  95. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  96. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  97. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  98. package/src/core/coach/task_quota_router.mjs +955 -0
  99. package/src/core/coach/turn_zero_gate.mjs +574 -0
  100. package/src/core/compaction_coach.mjs +1126 -0
  101. package/src/core/config.mjs +214 -0
  102. package/src/core/constants.mjs +1800 -0
  103. package/src/core/detectors_det01_to_16.mjs +1474 -0
  104. package/src/core/episodic_memory.mjs +135 -0
  105. package/src/core/fts5_output_compressor.mjs +359 -0
  106. package/src/core/git_ledger.mjs +189 -0
  107. package/src/core/handoff_audit.mjs +558 -0
  108. package/src/core/history.mjs +221 -0
  109. package/src/core/hook_diagnostics.mjs +158 -0
  110. package/src/core/horizon_classifier.mjs +326 -0
  111. package/src/core/horizon_config.mjs +802 -0
  112. package/src/core/host_watchdog.mjs +200 -0
  113. package/src/core/layer5_hygiene.mjs +966 -0
  114. package/src/core/log_resolver.mjs +231 -0
  115. package/src/core/mcp_auditor.mjs +138 -0
  116. package/src/core/micro_skills_store.mjs +91 -0
  117. package/src/core/offenders.mjs +161 -0
  118. package/src/core/parser.mjs +1996 -0
  119. package/src/core/path_canonicalizer.mjs +73 -0
  120. package/src/core/paths.mjs +310 -0
  121. package/src/core/prefix_cache_shield.mjs +386 -0
  122. package/src/core/pro_license.mjs +385 -0
  123. package/src/core/prompt_rubric.mjs +518 -0
  124. package/src/core/pruner.mjs +433 -0
  125. package/src/core/quota.mjs +1860 -0
  126. package/src/core/rsi_instinct_engine.mjs +1197 -0
  127. package/src/core/sanitizer.mjs +121 -0
  128. package/src/core/session_forensics.mjs +303 -0
  129. package/src/core/session_timeline.mjs +358 -0
  130. package/src/core/settings.mjs +99 -0
  131. package/src/core/shared/detectors.mjs +1342 -0
  132. package/src/core/shared/fnv1a64.mjs +85 -0
  133. package/src/core/shared/handoff_schema.mjs +123 -0
  134. package/src/core/shared/index.mjs +5 -0
  135. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  136. package/src/core/shared/micro_skills.mjs +1 -0
  137. package/src/core/shared/plugin_validator.mjs +202 -0
  138. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  139. package/src/core/sidecar_store.mjs +302 -0
  140. package/src/core/sprint_metrics.mjs +366 -0
  141. package/src/core/sqlite_client.mjs +283 -0
  142. package/src/core/storage_doctor.mjs +358 -0
  143. package/src/core/subagents.mjs +609 -0
  144. package/src/core/swarm_topology.mjs +360 -0
  145. package/src/core/task_quota_router.mjs +1656 -0
  146. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  147. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  148. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  149. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  150. package/src/core/timeline_svg.mjs +236 -0
  151. package/src/core/tool_surgeon.mjs +305 -0
  152. package/src/core/trajectory_stitcher.mjs +645 -0
  153. package/src/core/u_shaped_optimizer.mjs +789 -0
  154. package/src/core/wal_hygiene.mjs +233 -0
  155. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  156. package/src/core-isomorphic/catalog/index.mjs +1 -0
  157. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
  158. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  159. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  160. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  161. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  162. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  163. package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
  164. package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
  165. package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
  166. package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
  167. package/src/core-isomorphic/control/callTree.mjs +338 -0
  168. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  169. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  170. package/src/core-isomorphic/control/index.mjs +49 -0
  171. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  172. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  173. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  174. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  175. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  176. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
  177. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  178. package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
  179. package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
  180. package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
  181. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  182. package/src/core-isomorphic/economics/index.mjs +47 -0
  183. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  184. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  185. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
  186. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
  187. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
  188. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
  189. package/src/core-isomorphic/index.js +26 -0
  190. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  191. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  192. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  193. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  194. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
  195. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  196. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  197. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  198. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
  199. package/src/core-isomorphic/ui/modViews.mjs +1478 -0
  200. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  201. package/src/core-isomorphic/ustf/index.mjs +7 -0
  202. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  203. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  204. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  205. package/src/demo/synthetic_states.mjs +661 -0
  206. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  207. package/src/diagnostics/doctorEngine.mjs +203 -0
  208. package/src/engine-node/db/index.mjs +58 -0
  209. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  210. package/src/engine-node/db/probe.mjs +110 -0
  211. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  212. package/src/engine-node/index.mjs +9 -0
  213. package/src/engine-node/ipc/client.mjs +447 -0
  214. package/src/engine-node/ipc/index.mjs +22 -0
  215. package/src/engine-node/ipc/protocol.mjs +177 -0
  216. package/src/engine-node/ipc/server.mjs +445 -0
  217. package/src/engine-node/offloader/index.mjs +6 -0
  218. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  219. package/src/engine-node/sensors/blindspots.mjs +369 -0
  220. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  221. package/src/engine-node/sensors/index.mjs +7 -0
  222. package/src/hooks/portfolio_runtime.mjs +858 -0
  223. package/src/hooks/post_invocation.mjs +419 -0
  224. package/src/hooks/pre_invocation.mjs +1015 -0
  225. package/src/hooks/session_start.mjs +161 -0
  226. package/src/shims/agy_cli_compressor.mjs +705 -0
  227. package/src/shims/agy_git_guard.mjs +749 -0
  228. package/src/shims/ah_log_query.mjs +39 -0
  229. package/src/ui/costRadarSvg.mjs +6 -0
  230. package/src/ui/horizonGrid.mjs +1 -0
  231. package/src/ui/horizonPanelHtml.mjs +1 -0
  232. package/src/ui/horizon_panel.css +167 -0
  233. package/src/ui/horizon_panel.js +212 -0
  234. package/src/ui/modViews.mjs +1 -0
  235. package/src/utils/nodeIo.mjs +59 -0
  236. package/src/utils/runtime.mjs +1 -0
  237. package/src/webview/advanced_view.html +1808 -0
  238. package/src/webview/horizon_panel.html +11389 -0
  239. package/src/webview/registry.mjs +80 -0
  240. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Pure 64-bit FNV-1a Content Hash & Rolling 6-Turn Flip-Flop Ring Buffer (`src/core/shared/fnv1a64.mjs`)
3
+ *
4
+ * Zero Node I/O imports so cross-harness sync with `attention-horizon-claude` stays 100% clean.
5
+ */
6
+
7
+ const FNV1A_64_OFFSET_BASIS = 0xcbf29ce484222325n;
8
+ const FNV1A_64_PRIME = 0x100000001b3n;
9
+ const FNV1A_64_MASK = 0xffffffffffffffffn;
10
+
11
+ export function normalizeCodeForHash(content = '') {
12
+ return String(content ?? '')
13
+ .replace(/\r\n/g, () => '\n')
14
+ .split('\n')
15
+ .map((line) => line.replace(/[ \t]+$/g, () => ''))
16
+ .join('\n')
17
+ .trim();
18
+ }
19
+
20
+ export function fnv1a64Hex(content = '', { normalize = true } = {}) {
21
+ const str = normalize ? normalizeCodeForHash(content) : String(content ?? '');
22
+ const encoder = new TextEncoder();
23
+ const bytes = encoder.encode(str);
24
+ let hash = FNV1A_64_OFFSET_BASIS;
25
+ for (let i = 0; i < bytes.length; i++) {
26
+ hash ^= BigInt(bytes[i]);
27
+ hash = (hash * FNV1A_64_PRIME) & FNV1A_64_MASK;
28
+ }
29
+ return hash.toString(16).padStart(16, '0');
30
+ }
31
+
32
+ /**
33
+ * Updates a bounded per-file rolling 6-turn ring buffer of `{ hash, turn }` entries
34
+ * and detects `State A -> State B -> State A` oscillation flip-flops.
35
+ */
36
+ export function evaluateFnv1aRingBuffer(existingRing = [], nextContent = '', {
37
+ turn = 0,
38
+ maxEntries = 6,
39
+ initialContent = null
40
+ } = {}) {
41
+ const cap = Math.max(3, Number(maxEntries) || 6);
42
+ const ring = Array.isArray(existingRing)
43
+ ? existingRing
44
+ .filter((e) => e && typeof e.hash === 'string')
45
+ .map((e) => ({ hash: e.hash, turn: Number(e.turn ?? 0) }))
46
+ : [];
47
+
48
+ if (ring.length === 0 && typeof initialContent === 'string' && initialContent.length > 0) {
49
+ ring.push({ hash: fnv1a64Hex(initialContent), turn: Math.max(0, Number(turn) - 1) });
50
+ }
51
+
52
+ const nextHash = fnv1a64Hex(nextContent);
53
+ const lastEntry = ring.length > 0 ? ring[ring.length - 1] : null;
54
+
55
+ // Identical no-op write is not an A -> B -> A oscillation
56
+ if (lastEntry && lastEntry.hash === nextHash) {
57
+ return {
58
+ oscillationDetected: false,
59
+ hash: nextHash,
60
+ matchedTurn: null,
61
+ ring: ring.slice(-cap)
62
+ };
63
+ }
64
+
65
+ // Look for an earlier occurrence of `nextHash` with at least one distinct intermediate state B
66
+ let matchedEntry = null;
67
+ for (let i = ring.length - 2; i >= 0; i--) {
68
+ const candidate = ring[i];
69
+ if (candidate.hash === nextHash) {
70
+ const hasDistinctIntermediate = ring.slice(i + 1).some((mid) => mid.hash !== nextHash);
71
+ if (hasDistinctIntermediate) {
72
+ matchedEntry = candidate;
73
+ break;
74
+ }
75
+ }
76
+ }
77
+
78
+ const updatedRing = [...ring, { hash: nextHash, turn: Number(turn || 0) }].slice(-cap);
79
+ return {
80
+ oscillationDetected: Boolean(matchedEntry),
81
+ hash: nextHash,
82
+ matchedTurn: matchedEntry ? matchedEntry.turn : null,
83
+ ring: updatedRing
84
+ };
85
+ }
@@ -0,0 +1,123 @@
1
+ /**
2
+ * Pure Zero-I/O Cascade 70k State Baton & Handoff Schemas (`src/core/shared/handoff_schema.mjs`)
3
+ *
4
+ * Shared schema definition between `attention-horizon-antigravity` and `attention-horizon-claude`.
5
+ */
6
+
7
+ export const CASCADE_COMPACTION_CEILING_TOKENS = 70000;
8
+
9
+ export const CASCADE_CHECKPOINT_BANDS = Object.freeze([
10
+ Object.freeze({ label: '20%', ratio: 0.20, tokens: 14000 }),
11
+ Object.freeze({ label: '35%', ratio: 0.35, tokens: 25000 }),
12
+ Object.freeze({ label: '50%', ratio: 0.50, tokens: 35000 }),
13
+ Object.freeze({ label: '65%', ratio: 0.65, tokens: 45000 }),
14
+ Object.freeze({ label: '80%', ratio: 0.80, tokens: 56000 })
15
+ ]);
16
+
17
+ export const HANDOFF_SCHEMA_VERSION = '2.0.0';
18
+
19
+ function cleanStringArray(arr, maxItems = 12, maxLen = 220) {
20
+ if (!Array.isArray(arr)) return [];
21
+ const seen = new Set();
22
+ const out = [];
23
+ for (const raw of arr) {
24
+ const item = String(raw ?? '').trim();
25
+ if (!item) continue;
26
+ const clamped = item.length > maxLen ? `${item.slice(0, maxLen - 3)}...` : item;
27
+ if (!seen.has(clamped)) {
28
+ seen.add(clamped);
29
+ out.push(clamped);
30
+ if (out.length >= maxItems) break;
31
+ }
32
+ }
33
+ return out;
34
+ }
35
+
36
+ export function createStateBaton(input = {}) {
37
+ const currentTokens = Math.max(0, Math.round(Number(input.currentTokens ?? input.tokens ?? 0)));
38
+ const ceilingTokens = Math.max(1, Math.round(Number(input.ceilingTokens ?? CASCADE_COMPACTION_CEILING_TOKENS)));
39
+ return {
40
+ schemaVersion: HANDOFF_SCHEMA_VERSION,
41
+ sessionId: String(input.sessionId || 'default_session'),
42
+ bandLabel: String(input.bandLabel || 'manual'),
43
+ turn: Math.max(0, Math.round(Number(input.turn ?? input.turnCount ?? 0))),
44
+ currentTokens,
45
+ ceilingTokens,
46
+ fillPct: Number(((currentTokens / ceilingTokens) * 100).toFixed(1)),
47
+ updatedAt: String(input.updatedAt || new Date().toISOString()),
48
+ activeGoal: String(input.activeGoal || 'Continue active workspace implementation').trim().slice(0, 320),
49
+ workingSetFiles: cleanStringArray(input.workingSetFiles, 12, 180),
50
+ verifiedInvariants: cleanStringArray(input.verifiedInvariants, 10, 220),
51
+ negativeConstraints: cleanStringArray(input.negativeConstraints, 10, 220),
52
+ deadEnds: cleanStringArray(input.deadEnds, 8, 220)
53
+ };
54
+ }
55
+
56
+ export function validateStateBaton(baton) {
57
+ const errors = [];
58
+ if (!baton || typeof baton !== 'object' || Array.isArray(baton)) {
59
+ return { valid: false, errors: ['StateBaton must be an object'] };
60
+ }
61
+ if (typeof baton.activeGoal !== 'string' || !baton.activeGoal.trim()) {
62
+ errors.push('activeGoal must be a non-empty string');
63
+ }
64
+ for (const field of ['workingSetFiles', 'verifiedInvariants', 'negativeConstraints', 'deadEnds']) {
65
+ if (!Array.isArray(baton[field])) {
66
+ errors.push(`${field} must be an array`);
67
+ }
68
+ }
69
+ return { valid: errors.length === 0, errors };
70
+ }
71
+
72
+ /**
73
+ * Formats a compact ~300-token Cold-Resume State Baton hydration block for 1-click resume
74
+ * after the 5m implicit cache expires or Cascade auto-compacts at 70k.
75
+ */
76
+ export function formatColdResumeBatonPrompt(batonInput = {}) {
77
+ const b = createStateBaton(batonInput);
78
+ const lines = [
79
+ `[Highbeam Cold-Resume Baton • ${b.bandLabel} (${b.currentTokens.toLocaleString('en-US')}/${b.ceilingTokens.toLocaleString('en-US')} tok)]`,
80
+ `Goal: ${b.activeGoal}`,
81
+ `Working Set: ${b.workingSetFiles.slice(0, 6).join(', ') || '(none recorded)'}`
82
+ ];
83
+ if (b.verifiedInvariants.length > 0) {
84
+ lines.push(`Verified: ${b.verifiedInvariants.slice(0, 4).join(' | ')}`);
85
+ }
86
+ if (b.negativeConstraints.length > 0) {
87
+ lines.push(`Constraints: ${b.negativeConstraints.slice(0, 4).join(' | ')}`);
88
+ }
89
+ if (b.deadEnds.length > 0) {
90
+ lines.push(`Avoid Dead-Ends: ${b.deadEnds.slice(0, 3).join(' | ')}`);
91
+ }
92
+ const text = lines.join('\n');
93
+ // Clamp strictly near ~300 tokens (~1,200 chars)
94
+ return text.length > 1200 ? `${text.slice(0, 1197)}...` : text;
95
+ }
96
+
97
+ export function formatHandoffMarkdown(batonInput = {}, meta = {}) {
98
+ const b = createStateBaton(batonInput);
99
+ const bulletOrNone = (arr) => (arr.length > 0 ? arr.map((x) => `- ${x}`).join('\n') : '- *(none)*');
100
+ return [
101
+ `# Highbeam — Session State Baton Handoff`,
102
+ ``,
103
+ `- **Generated At:** ${b.updatedAt}`,
104
+ `- **Trigger:** ${String(meta.trigger || 'explicit_export')}`,
105
+ `- **Cascade Window:** ${b.currentTokens} / ${b.ceilingTokens} tokens (${b.fillPct}%) • Turn ${b.turn}`,
106
+ ``,
107
+ `## Active Goal`,
108
+ `${b.activeGoal}`,
109
+ ``,
110
+ `## Working Set Files`,
111
+ bulletOrNone(b.workingSetFiles),
112
+ ``,
113
+ `## Verified Invariants`,
114
+ bulletOrNone(b.verifiedInvariants),
115
+ ``,
116
+ `## Negative Constraints (Must Preserve)`,
117
+ bulletOrNone(b.negativeConstraints),
118
+ ``,
119
+ `## Dead Ends (Do Not Repeat)`,
120
+ bulletOrNone(b.deadEnds),
121
+ ``
122
+ ].join('\n');
123
+ }
@@ -0,0 +1,5 @@
1
+ export * from './fnv1a64.mjs';
2
+ export * from './ipi_sanitizer.mjs';
3
+ export * from './handoff_schema.mjs';
4
+ export * from './plugin_validator.mjs';
5
+ export * from './detectors.mjs';
@@ -0,0 +1,165 @@
1
+ /**
2
+ * Pure Zero-I/O Credential Scrubber & Indirect Prompt Injection (IPI) Sanitizer
3
+ * (`src/core/shared/ipi_sanitizer.mjs`)
4
+ *
5
+ * Strictly uses functional replacers `str.replace(pattern, () => replacement)` on all dynamic strings.
6
+ */
7
+
8
+ export const LIVE_SECRET_DEFINITIONS = Object.freeze([
9
+ {
10
+ id: 'pem_private_key',
11
+ label: 'PEM Private Key',
12
+ re: /-----BEGIN (?:RSA |EC |OPENSSH |DSA |ENCRYPTED )?PRIVATE KEY-----[\s\S]*?(?:-----END (?:RSA |EC |OPENSSH |DSA |ENCRYPTED )?PRIVATE KEY-----|$)/g,
13
+ redaction: '[REDACTED:PEM_PRIVATE_KEY]'
14
+ },
15
+ {
16
+ id: 'anthropic_api_key',
17
+ label: 'Anthropic API Key (sk-ant-api03-)',
18
+ re: /\bsk-ant-(?:api03-)?[A-Za-z0-9_-]{16,}\b/g,
19
+ redaction: '[REDACTED:ANTHROPIC_KEY]'
20
+ },
21
+ {
22
+ id: 'google_api_key',
23
+ label: 'Google API Key (AIzaSy)',
24
+ re: /\bAIzaSy[0-9A-Za-z_-]{25,}\b/g,
25
+ redaction: '[REDACTED:GOOGLE_API_KEY]'
26
+ },
27
+ {
28
+ id: 'github_classic_pat',
29
+ label: 'GitHub PAT (ghp_)',
30
+ re: /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}\b/g,
31
+ redaction: '[REDACTED:GITHUB_PAT]'
32
+ },
33
+ {
34
+ id: 'github_fine_pat',
35
+ label: 'GitHub Fine-Grained PAT (github_pat_)',
36
+ re: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
37
+ redaction: '[REDACTED:GITHUB_PAT]'
38
+ },
39
+ {
40
+ id: 'aws_access_key',
41
+ label: 'AWS Access Key ID (AKIA)',
42
+ re: /\bAKIA[0-9A-Z]{16}\b/g,
43
+ redaction: '[REDACTED:AWS_ACCESS_KEY]'
44
+ },
45
+ {
46
+ id: 'slack_bot_token',
47
+ label: 'Slack Token (xoxb-)',
48
+ re: /\bxox[baprs]-[0-9]{8,}-[0-9A-Za-z-]{16,}\b/g,
49
+ redaction: '[REDACTED:SLACK_TOKEN]'
50
+ },
51
+ {
52
+ id: 'openai_api_key',
53
+ label: 'OpenAI API Key (sk-proj-/sk-live-)',
54
+ re: /\bsk-(?:proj-|live-)[A-Za-z0-9_-]{16,}\b/g,
55
+ redaction: '[REDACTED:OPENAI_KEY]'
56
+ },
57
+ {
58
+ id: 'bearer_token',
59
+ label: 'Bearer Authorization Token',
60
+ re: /\bBearer\s+[A-Za-z0-9._~+/-]{20,}\b/gi,
61
+ redaction: 'Bearer [REDACTED:TOKEN]'
62
+ }
63
+ ]);
64
+
65
+ const PLACEHOLDER_VALUE_RE =
66
+ /^(?:your[_-]?|my[_-]?|insert[_-]?|replace[_-]?|enter[_-]?|example|changeme|placeholder|dummy|redacted|todo|none|null|undefined|test[_-]?key|sample|<[^>]+>|\$\{[^}]+\}|x{4,}|\*{4,}|0{6,})/i;
67
+
68
+ export function isPlaceholderSecretValue(rawVal = '') {
69
+ const cleaned = String(rawVal || '').trim().replace(/^['"]|['"]$/g, () => '');
70
+ if (!cleaned || cleaned.length < 8) return true;
71
+ if (PLACEHOLDER_VALUE_RE.test(cleaned)) return true;
72
+ if (/YOUR_API_KEY|EXAMPLE|CHANGEME|PLACEHOLDER|DUMMY|REDACTED|FAKE_KEY|SAMPLE_KEY/i.test(cleaned)) {
73
+ return true;
74
+ }
75
+ return false;
76
+ }
77
+
78
+ export function computeShannonEntropy(str = '') {
79
+ const s = String(str || '');
80
+ if (!s.length) return 0;
81
+ const counts = new Map();
82
+ for (let i = 0; i < s.length; i++) {
83
+ const ch = s[i];
84
+ counts.set(ch, (counts.get(ch) || 0) + 1);
85
+ }
86
+ let entropy = 0;
87
+ for (const count of counts.values()) {
88
+ const p = count / s.length;
89
+ entropy -= p * Math.log2(p);
90
+ }
91
+ return entropy;
92
+ }
93
+
94
+ export function redactSecretsPure(rawText = '') {
95
+ let out = String(rawText ?? '');
96
+ let redactedCount = 0;
97
+
98
+ for (const def of LIVE_SECRET_DEFINITIONS) {
99
+ const re = new RegExp(def.re.source, def.re.flags);
100
+ out = out.replace(re, (match) => {
101
+ if (def.id !== 'pem_private_key' && isPlaceholderSecretValue(match)) {
102
+ return match;
103
+ }
104
+ redactedCount += 1;
105
+ return def.redaction;
106
+ });
107
+ }
108
+
109
+ // Scrub .env style KEY=VALUE secrets
110
+ const envAssignRe = /\b([A-Z][A-Z0-9_]*(?:SECRET|TOKEN|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY|ACCESS_KEY|AUTH_KEY|CLIENT_SECRET)[A-Z0-9_]*)\s*=\s*(['"]?)([^\s'"\r\n#]+)\2/g;
111
+ out = out.replace(envAssignRe, (full, keyName, _quote, val) => {
112
+ if (isPlaceholderSecretValue(val)) return full;
113
+ redactedCount += 1;
114
+ return `${keyName}=[REDACTED:ENV_SECRET]`;
115
+ });
116
+
117
+ return {
118
+ sanitized: out,
119
+ redactedCount
120
+ };
121
+ }
122
+
123
+ const IPI_PATTERNS = Object.freeze([
124
+ {
125
+ id: 'ignore_previous_instructions',
126
+ re: /\b(?:ignore|disregard|forget)\s+(?:all\s+)?(?:previous|prior|above|system)\s+(?:instructions|rules|prompts|directives)\b/gi,
127
+ replacement: '[IPI_FILTERED:INSTRUCTION_OVERRIDE]'
128
+ },
129
+ {
130
+ id: 'fake_system_tag',
131
+ re: /<\s*\/?\s*(?:system|system_prompt|developer_instructions|user_rules|antml:thinking)\s*>/gi,
132
+ replacement: '[IPI_FILTERED:TAG]'
133
+ },
134
+ {
135
+ id: 'unicode_tag_stego',
136
+ re: /[\u{E0000}-\u{E007F}]/gu,
137
+ replacement: ''
138
+ },
139
+ {
140
+ id: 'zero_width_stego',
141
+ re: /[\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/gu,
142
+ replacement: ''
143
+ }
144
+ ]);
145
+
146
+ export function sanitizeIpiPure(rawText = '') {
147
+ let out = String(rawText ?? '');
148
+ const detections = [];
149
+
150
+ for (const pat of IPI_PATTERNS) {
151
+ const re = new RegExp(pat.re.source, pat.re.flags);
152
+ out = out.replace(re, () => {
153
+ detections.push(pat.id);
154
+ return pat.replacement;
155
+ });
156
+ }
157
+
158
+ const secretRes = redactSecretsPure(out);
159
+ return {
160
+ sanitized: secretRes.sanitized,
161
+ ipiDetected: detections.length > 0,
162
+ detections,
163
+ redactedSecretCount: secretRes.redactedCount
164
+ };
165
+ }
@@ -0,0 +1 @@
1
+ export * from '../../core-isomorphic/diagnostics/micro_skills.mjs';
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Pure Strict Validator for Antigravity Plugin Manifests, `hooks.json`, and Safe Hook Outputs
3
+ * (`src/core/shared/plugin_validator.mjs`)
4
+ *
5
+ * Mirrors `agy plugin validate --strict` rules with zero I/O.
6
+ */
7
+
8
+ export const FLAT_HOOK_EVENTS = Object.freeze([
9
+ 'SessionStart',
10
+ 'PreInvocation',
11
+ 'PostInvocation',
12
+ 'Stop'
13
+ ]);
14
+
15
+ export const MATCHER_HOOK_EVENTS = Object.freeze([
16
+ 'PreToolUse',
17
+ 'PostToolUse'
18
+ ]);
19
+
20
+ export function validateStrictAntigravityPluginManifest(manifest) {
21
+ const errors = [];
22
+ const warnings = [];
23
+
24
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {
25
+ return { valid: false, errors: ['plugin.json must be a JSON object'], warnings };
26
+ }
27
+
28
+ const name = String(manifest.name || '');
29
+ if (!name || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(name)) {
30
+ errors.push(`plugin.json "name" must be kebab-case (received "${name}")`);
31
+ }
32
+ if (name !== 'attention-horizon-antigravity') {
33
+ errors.push(`plugin.json "name" must be "attention-horizon-antigravity" (received "${name}")`);
34
+ }
35
+
36
+ const displayName = String(manifest.displayName || '');
37
+ if (!displayName) {
38
+ errors.push('plugin.json "displayName" is required');
39
+ } else {
40
+ if (/^(Antigravity|Gemini)\b/i.test(displayName)) {
41
+ errors.push(`plugin.json "displayName" must NOT start with "Antigravity" or "Gemini" (received "${displayName}")`);
42
+ }
43
+ if (/\b(Plugin|MCP)\s*$/i.test(displayName) || /\b(Plugin|MCP)\b/i.test(displayName)) {
44
+ errors.push(`plugin.json "displayName" must omit "Plugin"/"MCP" suffixes (received "${displayName}")`);
45
+ }
46
+ }
47
+
48
+ return {
49
+ valid: errors.length === 0,
50
+ errors,
51
+ warnings
52
+ };
53
+ }
54
+
55
+ export function validateStrictAntigravityHooksJson(hooksDoc, { requireRelativePluginPaths = true } = {}) {
56
+ const errors = [];
57
+ if (!hooksDoc || typeof hooksDoc !== 'object' || Array.isArray(hooksDoc)) {
58
+ return { valid: false, errors: ['hooks.json must be a non-null JSON object'] };
59
+ }
60
+
61
+ const rootScope = hooksDoc.hooks && typeof hooksDoc.hooks === 'object' && !Array.isArray(hooksDoc.hooks)
62
+ ? hooksDoc.hooks
63
+ : hooksDoc;
64
+
65
+ const checkCommandObj = (cmdObj, label) => {
66
+ if (!cmdObj || typeof cmdObj !== 'object' || Array.isArray(cmdObj)) {
67
+ errors.push(`${label} must be an object`);
68
+ return;
69
+ }
70
+ if (cmdObj.type !== 'command') {
71
+ errors.push(`${label}.type must be "command"`);
72
+ }
73
+ if (typeof cmdObj.command !== 'string' || !cmdObj.command.trim()) {
74
+ errors.push(`${label}.command must be a non-empty string`);
75
+ } else if (requireRelativePluginPaths && !/^node\s+(?:--no-warnings\s+)?\.\/hooks\/[a-z0-9_.-]+\.mjs\b/i.test(cmdObj.command.trim())) {
76
+ errors.push(`${label}.command must use relative plugin-root path "node ./hooks/..." (received "${cmdObj.command}")`);
77
+ }
78
+ if (typeof cmdObj.timeout !== 'number' || cmdObj.timeout <= 0) {
79
+ errors.push(`${label}.timeout must be a positive number`);
80
+ }
81
+ };
82
+
83
+ for (const flatEvt of FLAT_HOOK_EVENTS) {
84
+ if (!(flatEvt in rootScope)) continue;
85
+ const arr = rootScope[flatEvt];
86
+ if (!Array.isArray(arr) || arr.length === 0) {
87
+ errors.push(`${flatEvt} must map directly to a non-empty flat handler array`);
88
+ continue;
89
+ }
90
+ for (let i = 0; i < arr.length; i++) {
91
+ const entry = arr[i];
92
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
93
+ errors.push(`${flatEvt}[${i}] must be a flat handler object`);
94
+ continue;
95
+ }
96
+ if ('matcher' in entry) {
97
+ errors.push(`${flatEvt}[${i}] MUST NOT contain a "matcher" key`);
98
+ }
99
+ if ('hooks' in entry) {
100
+ errors.push(`${flatEvt}[${i}] MUST NOT wrap handlers inside a nested "hooks" array`);
101
+ }
102
+ checkCommandObj(entry, `${flatEvt}[${i}]`);
103
+ }
104
+ }
105
+
106
+ for (const matchEvt of MATCHER_HOOK_EVENTS) {
107
+ if (!(matchEvt in rootScope)) continue;
108
+ const arr = rootScope[matchEvt];
109
+ if (!Array.isArray(arr) || arr.length === 0) {
110
+ errors.push(`${matchEvt} must be a non-empty array of { matcher, hooks } entries`);
111
+ continue;
112
+ }
113
+ for (let i = 0; i < arr.length; i++) {
114
+ const entry = arr[i];
115
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
116
+ errors.push(`${matchEvt}[${i}] must be an object`);
117
+ continue;
118
+ }
119
+ if (typeof entry.matcher !== 'string' || !entry.matcher.trim()) {
120
+ errors.push(`${matchEvt}[${i}].matcher must be a non-empty regex string`);
121
+ }
122
+ if (!Array.isArray(entry.hooks) || entry.hooks.length === 0) {
123
+ errors.push(`${matchEvt}[${i}].hooks must be a non-empty array of command handlers`);
124
+ continue;
125
+ }
126
+ if ('type' in entry || 'command' in entry) {
127
+ errors.push(`${matchEvt}[${i}] must nest command handlers inside "hooks": [...] rather than flat properties`);
128
+ }
129
+ for (let j = 0; j < entry.hooks.length; j++) {
130
+ checkCommandObj(entry.hooks[j], `${matchEvt}[${i}].hooks[${j}]`);
131
+ }
132
+ }
133
+ }
134
+
135
+ return {
136
+ valid: errors.length === 0,
137
+ errors
138
+ };
139
+ }
140
+
141
+ function containsForbiddenDirectiveKeys(payload) {
142
+ if (!payload || typeof payload !== 'object') return [];
143
+ const forbidden = [];
144
+ const rawJson = JSON.stringify(payload);
145
+ if ('injectSteps' in payload || rawJson.includes('"injectSteps"')) forbidden.push('injectSteps');
146
+ if (payload.systemMessage && typeof payload.systemMessage === 'object' && 'metadata' in payload.systemMessage) {
147
+ forbidden.push('systemMessage.metadata');
148
+ }
149
+ if (rawJson.includes('"user_markdown"')) forbidden.push('user_markdown');
150
+ if ('ask_question' in payload || rawJson.includes('"ask_question"')) forbidden.push('ask_question');
151
+ return forbidden;
152
+ }
153
+
154
+ export function validateSafePreInvocationOutput(payload) {
155
+ const errors = [];
156
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
157
+ return { valid: false, errors: ['PreInvocation output must be a JSON object'] };
158
+ }
159
+ const forbidden = containsForbiddenDirectiveKeys(payload);
160
+ if (forbidden.length > 0) {
161
+ errors.push(`Forbidden keys in PreInvocation output: ${forbidden.join(', ')}`);
162
+ }
163
+ const keys = Object.keys(payload);
164
+ if (keys.length === 0) return { valid: errors.length === 0, errors };
165
+
166
+ if (keys.length === 1 && typeof payload.ephemeralMessage === 'string') {
167
+ return { valid: errors.length === 0, errors };
168
+ }
169
+ if (
170
+ payload.terminationBehavior === 'terminate' &&
171
+ payload.errorMessage &&
172
+ typeof payload.errorMessage.userMessage === 'string' &&
173
+ keys.every((k) => k === 'terminationBehavior' || k === 'errorMessage')
174
+ ) {
175
+ return { valid: errors.length === 0, errors };
176
+ }
177
+
178
+ errors.push(`Unexpected PreInvocation output shape: keys=[${keys.join(', ')}]`);
179
+ return { valid: false, errors };
180
+ }
181
+
182
+ export function validateSafePreToolUseOutput(payload) {
183
+ const errors = [];
184
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload)) {
185
+ return { valid: false, errors: ['PreToolUse output must be a JSON object'] };
186
+ }
187
+ const forbidden = containsForbiddenDirectiveKeys(payload);
188
+ if (forbidden.length > 0) {
189
+ errors.push(`Forbidden keys in PreToolUse output: ${forbidden.join(', ')}`);
190
+ }
191
+ if (!['allow', 'ask', 'deny'].includes(payload.decision)) {
192
+ errors.push(`PreToolUse decision must be "allow" | "ask" | "deny" (received "${payload.decision}")`);
193
+ }
194
+ if (payload.reason !== undefined && typeof payload.reason !== 'string') {
195
+ errors.push('PreToolUse reason must be a string when present');
196
+ }
197
+ const extraKeys = Object.keys(payload).filter((k) => k !== 'decision' && k !== 'reason');
198
+ if (extraKeys.length > 0) {
199
+ errors.push(`Unexpected PreToolUse keys: ${extraKeys.join(', ')}`);
200
+ }
201
+ return { valid: errors.length === 0, errors };
202
+ }
@@ -0,0 +1 @@
1
+ export * from '../../core-isomorphic/diagnostics/prompt_hygiene_governor.mjs';