pantheon-opencode 1.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 (128) hide show
  1. package/AGENTS.md +37 -0
  2. package/LICENSE +21 -0
  3. package/README.md +1013 -0
  4. package/bin/pantheon-init.mjs +183 -0
  5. package/commands/pantheon-audit.md +25 -0
  6. package/commands/pantheon-bg.md +10 -0
  7. package/commands/pantheon-consolidate.md +11 -0
  8. package/commands/pantheon-deepwork.md +128 -0
  9. package/commands/pantheon-doc.md +10 -0
  10. package/commands/pantheon-focus.md +9 -0
  11. package/commands/pantheon-forget.md +58 -0
  12. package/commands/pantheon-hash.md +11 -0
  13. package/commands/pantheon-optimize.md +79 -0
  14. package/commands/pantheon-remember.md +44 -0
  15. package/commands/pantheon-search.md +48 -0
  16. package/commands/pantheon-status.md +71 -0
  17. package/commands/pantheon-todo.md +11 -0
  18. package/commands/pantheon.md +49 -0
  19. package/docs/AGENT-MCP.md +194 -0
  20. package/docs/ARCHITECTURE.md +384 -0
  21. package/docs/BRANCH-PROTECTION.md +142 -0
  22. package/docs/INDEX.md +81 -0
  23. package/docs/INSTALLATION.md +217 -0
  24. package/docs/MCP.md +238 -0
  25. package/docs/MEMORY.md +471 -0
  26. package/docs/MIGRATION-MEMORY-BANK.md +139 -0
  27. package/docs/PLATFORMS.md +5 -0
  28. package/docs/QUICKSTART.md +49 -0
  29. package/docs/README.md +18 -0
  30. package/docs/RELEASING.md +256 -0
  31. package/docs/SETUP.md +5 -0
  32. package/docs/UPGRADING.md +41 -0
  33. package/docs/mcp-recommendations.md +439 -0
  34. package/docs/mcp-tools.md +156 -0
  35. package/docs/mcp-user-guide.md +204 -0
  36. package/docs/persistence-mcp.md +111 -0
  37. package/package.json +72 -0
  38. package/pantheon.schema.json +158 -0
  39. package/scripts/__init__.py +0 -0
  40. package/scripts/_pantheon_paths.py +68 -0
  41. package/scripts/check-version-consistency.sh +23 -0
  42. package/scripts/code_mode_server.py +202 -0
  43. package/scripts/doctor.mjs +763 -0
  44. package/scripts/generate-prompts.sh +222 -0
  45. package/scripts/generate-routing-docs.mjs +104 -0
  46. package/scripts/hash_verify.py +192 -0
  47. package/scripts/init-pantheon-mcp.sh +118 -0
  48. package/scripts/install/agents-md.mjs +214 -0
  49. package/scripts/install/health-check.mjs +196 -0
  50. package/scripts/install/migrate.mjs +209 -0
  51. package/scripts/install/opencode.mjs +645 -0
  52. package/scripts/install/shared.mjs +655 -0
  53. package/scripts/install/venv.mjs +116 -0
  54. package/scripts/install-mcp.mjs +885 -0
  55. package/scripts/install.mjs +26 -0
  56. package/scripts/manifest.mjs +622 -0
  57. package/scripts/mcp_persistence_server.py +459 -0
  58. package/scripts/mcp_resources_server.py +206 -0
  59. package/scripts/memory_cache.py +78 -0
  60. package/scripts/memory_mcp_server.py +605 -0
  61. package/scripts/paths.py +64 -0
  62. package/scripts/prune_context.py +72 -0
  63. package/scripts/release-bundle.mjs +109 -0
  64. package/scripts/scrub-secrets.py +282 -0
  65. package/scripts/scrub_secrets.py +281 -0
  66. package/scripts/test-context-compression.sh +166 -0
  67. package/scripts/themis_heuristic_scan.py +287 -0
  68. package/scripts/todo_enforcer.py +242 -0
  69. package/scripts/uninstall.mjs +1057 -0
  70. package/scripts/validate-routing.mjs +160 -0
  71. package/scripts/validate_agent_frontmatter.py +226 -0
  72. package/scripts/versioning.mjs +254 -0
  73. package/skills-lock.json +16 -0
  74. package/src/agents/aphrodite.md +162 -0
  75. package/src/agents/apollo.md +109 -0
  76. package/src/agents/athena.md +226 -0
  77. package/src/agents/demeter.md +146 -0
  78. package/src/agents/gaia.md +82 -0
  79. package/src/agents/hephaestus.md +105 -0
  80. package/src/agents/hermes.md +302 -0
  81. package/src/agents/iris.md +99 -0
  82. package/src/agents/mnemosyne.md +226 -0
  83. package/src/agents/nyx.md +87 -0
  84. package/src/agents/prometheus.md +199 -0
  85. package/src/agents/talos.md +93 -0
  86. package/src/agents/themis.md +187 -0
  87. package/src/agents/zeus.md +209 -0
  88. package/src/instructions/agent-return-format.instructions.md +26 -0
  89. package/src/instructions/backend-standards.instructions.md +45 -0
  90. package/src/instructions/documentation-standards.instructions.md +53 -0
  91. package/src/instructions/frontend-standards.instructions.md +46 -0
  92. package/src/instructions/memory-protocol.instructions.md +67 -0
  93. package/src/instructions/yagni.instructions.md +21 -0
  94. package/src/instructions/zeus-anti-stall.instructions.md +72 -0
  95. package/src/instructions/zeus-communication-rules.instructions.md +15 -0
  96. package/src/instructions/zeus-council-synthesis.instructions.md +105 -0
  97. package/src/instructions/zeus-timeout-retry.instructions.md +127 -0
  98. package/src/mcp/_pantheon_paths.py +67 -0
  99. package/src/mcp/code_mode_server.py +202 -0
  100. package/src/mcp/init-pantheon-mcp.sh +118 -0
  101. package/src/mcp/install-mcp.mjs +885 -0
  102. package/src/mcp/mcp_persistence_server.py +458 -0
  103. package/src/mcp/mcp_resources_server.py +205 -0
  104. package/src/mcp/memory_mcp_server.py +604 -0
  105. package/src/mcp/requirements-mcp-core.txt +5 -0
  106. package/src/mcp/requirements-mcp.txt +5 -0
  107. package/src/plugin.ts +19 -0
  108. package/src/plugins/tui/dist/tui.js +143 -0
  109. package/src/plugins/tui/dist/tui.tsx +144 -0
  110. package/src/plugins/tui/package.json +32 -0
  111. package/src/plugins/tui/src/index.tsx +144 -0
  112. package/src/plugins/tui/tsdown.config.ts +22 -0
  113. package/src/routing.yml +499 -0
  114. package/src/skills/README.md +230 -0
  115. package/src/skills/agent-coordination/SKILL.md +95 -0
  116. package/src/skills/artifact-management/SKILL.md +118 -0
  117. package/src/skills/auto-continue/SKILL.md +280 -0
  118. package/src/skills/code-review-checklist/SKILL.md +139 -0
  119. package/src/skills/context-compression/SKILL.md +861 -0
  120. package/src/skills/git-workflow-and-versioning/SKILL.md +32 -0
  121. package/src/skills/incremental-implementation/SKILL.md +27 -0
  122. package/src/skills/memory-bank/SKILL.md +165 -0
  123. package/src/skills/orchestration-workflow/SKILL.md +311 -0
  124. package/src/skills/security-hardening/SKILL.md +36 -0
  125. package/src/skills/session-goal/SKILL.md +138 -0
  126. package/src/skills/spec-driven-development/SKILL.md +23 -0
  127. package/src/skills/tdd-with-agents/SKILL.md +170 -0
  128. package/src/skills/visual-review-pipeline/SKILL.md +200 -0
@@ -0,0 +1,861 @@
1
+ ---
2
+ name: context-compression
3
+ description: "Level 2 — Pantheon-native context compression with priority scoring, semantic summarization, downstream-aware compression, budget allocation, and cross-references"
4
+ context: fork
5
+ globs: ["**/01-active-context.md", "**/02-progress-log.md"]
6
+ alwaysApply: false
7
+ ---
8
+
9
+ # Context Compression — Level 2 (Intelligent Compression)
10
+
11
+ Level 2 replaces Level 1 with priority-aware compression: scoring, semantic summarization for critical/high entries, downstream-aware field masks, budget allocation, and automatic cross-references. Zeus triggers, Mnemosyne executes.
12
+
13
+ ---
14
+
15
+ ## 1. Overview
16
+
17
+ Level 2 adds four capabilities beyond Level 1:
18
+
19
+ 1. **Priority Scoring Engine** — Deterministic keyword-driven scoring (no LLM) for each subtask_summary across 5 dimensions. Outputs CRITICAL/HIGH/MEDIUM/LOW.
20
+ 2. **Semantic Summarization** — Template-generated contextual summaries for CRITICAL/HIGH entries, tailored to the downstream agent pair. MEDIUM/LOW get standard mechanical 1-line compression.
21
+ 3. **Downstream-Aware Compression** — Field masks preserve the most relevant fields per (from_agent, to_agent) pair. Themis gets all fields; Mnemosyne gets minimal.
22
+ 4. **Cross-Reference Mechanism** — Auto-generated `_xref/index.md` with entity references for endpoints, tables, migrations, components, and decisions, surviving sprint boundaries.
23
+
24
+ Budget allocation is priority-greedy. CRITICAL entries are always expanded. Overflow escalates to Zeus.
25
+
26
+ ---
27
+
28
+ ## 2. Compression Triggers
29
+
30
+ Same 7 triggers as Level 1, with Level 2 behavior:
31
+
32
+ | Trigger | Fires | Level 2 Behavior |
33
+ |---------|-------|------------------|
34
+ | **C1 Phase Gate** | Themis APPROVED | Priority-score subtask_summary → semantic summary (CRITICAL/HIGH) or 1-line (MEDIUM/LOW) → `01-active-context.md` |
35
+ | **C2 Phase Gate** | Themis APPROVED | IMPL artifact → scored, archived to `02-progress-log.md`; `.tmp/` deleted |
36
+ | **C3 Phase Gate** | Themis APPROVED | REVIEW summary line → `02-progress-log.md`; `.tmp/` deleted |
37
+ | **C4 Feature Complete** | Last phase APPROVED | PLAN reference → `01-active-context.md`; `.tmp/` deleted |
38
+ | **C5 Sprint Close** | `@mnemosyne Close sprint` | Bulk cleanup + cross-ref archive + flag unresolved |
39
+ | **C6 Explicit** | `/compress` | Per-type compression with priority scoring |
40
+ | **C7 Size-based** | `01-active-context.md` Completed Phases > 100 lines | Priority-greedy trim: oldest LOW entries first, preserving CRITICAL and HIGH |
41
+
42
+ ### Inline Compression Triggers (C8-C11 — Active Session)
43
+
44
+ These triggers fire DURING an active agent session. They call the Pantheon-native inline compressor (`compress-inline.py` MCP, "L1"). Scrubbing is automatic in the MCP layer — agents must NOT scrub manually.
45
+
46
+ | Trigger | Fires | Layer | Action |
47
+ |---------|-------|-------|--------|
48
+ | **C8 CRITICAL/HIGH subtask_summary** | A returned `subtask_summary` contains CRITICAL/HIGH findings | L1 Inline | `execute_code_script("compress-inline.py", args=["compress", "--text", "<content>"])` before the next phase |
49
+ | **C9 Pre-Delegation** | About to delegate a large context block to another agent | L1 Inline | Compress the block first to cut tokens |
50
+ | **C10 Context Pressure** | Context near limit / platform compaction signal | — (cross-ref) | OpenCode native compaction already handles this. No separate Pantheon mechanism — see §12. |
51
+ | **C11 Phase Boundary / Handoff** | Phase boundary or session handoff reached | L1 Inline | Compress completed work before promotion |
52
+
53
+ ---
54
+
55
+ ## 3. Priority Scoring Engine
56
+
57
+ The algorithm is DETERMINISTIC (keyword-driven, no LLM needed). Zeus scores each subtask_summary before compression using 5 dimensions. Total score is weighted sum.
58
+
59
+ ### Scoring Dimensions
60
+
61
+ | Dimension | Weight | Range | Description |
62
+ |-----------|--------|-------|-------------|
63
+ | Impact | 0.30 | 0.0–1.0 | How broadly the change affects the system |
64
+ | Risk | 0.25 | 0.0–1.0 | Likelihood of breakage or subtle bugs |
65
+ | Novelty | 0.20 | 0.0–1.0 | New pattern, architecture, or files |
66
+ | Blockers | 0.15 | 0.0–1.0 | Whether this unblocked others or was blocked |
67
+ | Downstream relevance | 0.10 | 0.0–1.0 | How relevant to the next agent (from agent-pair table) |
68
+
69
+ ### Full Keyword Scoring Map
70
+
71
+ | Keyword / Pattern | Impact | Risk | Novelty | Category |
72
+ |-------------------|--------|------|---------|----------|
73
+ | `schema` | 1.0 | 1.0 | 0.6 | schema/migration |
74
+ | `migration` | 1.0 | 1.0 | 0.4 | schema/migration |
75
+ | `auth` | 1.0 | 1.0 | 0.5 | auth/security |
76
+ | `login` | 1.0 | 1.0 | 0.4 | auth/security |
77
+ | `permission` | 0.8 | 1.0 | 0.5 | auth/security |
78
+ | `role` | 0.8 | 0.8 | 0.4 | auth/security |
79
+ | `JWT` | 0.8 | 1.0 | 0.4 | auth/security |
80
+ | `OAuth` | 0.8 | 1.0 | 0.5 | auth/security |
81
+ | `password` | 0.7 | 1.0 | 0.3 | auth/security |
82
+ | `encrypt` | 0.7 | 1.0 | 0.5 | auth/security |
83
+ | `token` | 0.7 | 0.8 | 0.3 | auth/security |
84
+ | `security` | 0.8 | 1.0 | 0.4 | auth/security |
85
+ | `new table` | 1.0 | 0.8 | 0.9 | schema/migration |
86
+ | `new column` | 0.7 | 0.8 | 0.6 | schema/migration |
87
+ | `index` | 0.5 | 0.6 | 0.3 | database |
88
+ | `foreign key` | 0.8 | 0.9 | 0.5 | database |
89
+ | `constraint` | 0.6 | 0.7 | 0.3 | database |
90
+ | `endpoint` | 0.9 | 0.6 | 0.5 | api |
91
+ | `route` | 0.8 | 0.5 | 0.4 | api |
92
+ | `API` | 0.8 | 0.5 | 0.4 | api |
93
+ | `service` | 0.7 | 0.4 | 0.4 | architecture |
94
+ | `new file` | 0.6 | 0.3 | 0.8 | structure |
95
+ | `refactor` | 0.5 | 0.7 | 0.6 | code-quality |
96
+ | `rename` | 0.4 | 0.6 | 0.3 | code-quality |
97
+ | `delete` | 0.5 | 0.7 | 0.2 | code-quality |
98
+ | `deprecat` | 0.4 | 0.4 | 0.3 | code-quality |
99
+ | `config` | 0.5 | 0.6 | 0.3 | infrastructure |
100
+ | `Docker` | 0.7 | 0.6 | 0.3 | infrastructure |
101
+ | `deploy` | 0.8 | 0.8 | 0.2 | infrastructure |
102
+ | `CSS` | 0.2 | 0.1 | 0.2 | style |
103
+ | `style` | 0.2 | 0.1 | 0.2 | style |
104
+ | `typo` | 0.0 | 0.0 | 0.0 | trivial |
105
+ | `comment` | 0.1 | 0.0 | 0.0 | trivial |
106
+ | `README` | 0.2 | 0.0 | 0.1 | documentation |
107
+ | `docstring` | 0.2 | 0.0 | 0.1 | documentation |
108
+ | `5+ files` | — | — | 0.8 | novelty (file count) |
109
+ | `10+ files` | — | — | 1.0 | novelty (file count) |
110
+
111
+ **Scoring rules:**
112
+ - For each dimension, find the **maximum** matching keyword score among all keywords found in the summary.
113
+ - If multiple keywords match in the same category, take the max per dimension.
114
+ - Novelty bonus: `files_changed` overrides keyword score — if >5 files, set novelty to 0.8; if >10 files, set to 1.0.
115
+ - If no keywords match, default to 0.0 for that dimension.
116
+
117
+ ### Downstream Relevance Table
118
+
119
+ The relevance score is computed from the agent-pair lookup:
120
+
121
+ | From ↓ → To → | Hermes | Aphrodite | Demeter | Themis | Mnemosyne | Hephaestus | Prometheus |
122
+ |---------------|--------|-----------|---------|-------|-----------|------------|------------|
123
+ | **Hermes** | 1.0 | 0.9 | 0.8 | 0.7 | 0.3 | 0.6 | 0.5 |
124
+ | **Aphrodite** | 0.9 | 1.0 | 0.3 | 0.7 | 0.3 | 0.5 | 0.3 |
125
+ | **Demeter** | 0.9 | 0.3 | 1.0 | 0.7 | 0.3 | 0.6 | 0.6 |
126
+ | **Themis** | 0.8 | 0.8 | 0.8 | 1.0 | 0.5 | 0.8 | 0.8 |
127
+ | **Hephaestus** | 0.6 | 0.5 | 0.6 | 0.7 | 0.3 | 1.0 | 0.4 |
128
+ | **Prometheus** | 0.6 | 0.4 | 0.6 | 0.7 | 0.3 | 0.4 | 1.0 |
129
+ | **Mnemosyne** | 0.3 | 0.3 | 0.3 | 0.5 | 1.0 | 0.3 | 0.3 |
130
+
131
+ **Rows = from agent, Columns = to agent.** Score = `table[from_agent][to_agent]` scaled to 0.0–1.0 (already in range).
132
+
133
+ When the next-phase agent is unknown, default downstream relevance to 0.5.
134
+
135
+ ### Priority Bands
136
+
137
+ | Band | Score Range | Storage Mode |
138
+ |------|-------------|--------------|
139
+ | CRITICAL | ≥ 0.75 | Expanded (3 lines, semantic summary) |
140
+ | HIGH | 0.50 – 0.74 | Expanded (2 lines) or Standard (1 line) per budget |
141
+ | MEDIUM | 0.25 – 0.49 | Standard (1 line) |
142
+ | LOW | < 0.25 | Aggressive (0.5 lines, filename only) |
143
+
144
+ ### Scoring Example
145
+
146
+ ```
147
+ subtask_summary:
148
+ summary: "Added JWT auth endpoint with refresh token rotation"
149
+ files_changed: ["backend/routers/auth.py", "backend/services/auth_service.py"]
150
+ status: complete
151
+
152
+ Keywords found: JWT (auth/security), endpoint (api), token (auth/security)
153
+ → Impact = max(0.8, 0.9, 0.7) = 0.9
154
+ → Risk = max(1.0, 0.6, 0.8) = 1.0
155
+ → Novelty = max(0.4, 0.5, 0.3) = 0.5 | files=2, no bonus
156
+ → Blockers = 0.0 (no blockers mentioned)
157
+ → Downstream = 0.9 (Hermes→Aphrodite)
158
+
159
+ Score = 0.9×0.30 + 1.0×0.25 + 0.5×0.20 + 0.0×0.15 + 0.9×0.10
160
+ = 0.27 + 0.25 + 0.10 + 0.00 + 0.09
161
+ = 0.71 → HIGH
162
+ ```
163
+
164
+ ---
165
+
166
+ ## 4. Semantic Summarization
167
+
168
+ Zeus generates contextual summaries for CRITICAL and HIGH entries using the semantic-summarize prompt template.
169
+ Each summary costs ~50 input tokens per entry (uses the same model as Zeus). MEDIUM/LOW entries get mechanical 1-line compression without summarization.
170
+
171
+ ### Template: CRITICAL (3 lines)
172
+
173
+ ```
174
+ 1 sentence: What changed (include API/contract details if relevant to next agent)
175
+ 1 sentence: Why it matters to the NEXT agent (from downstream table)
176
+ 1 sentence: Gotcha/decision/trade-off
177
+ ```
178
+
179
+ ### Template: HIGH (2 lines)
180
+
181
+ ```
182
+ 1 sentence: What changed (include API/contract details if relevant to next agent)
183
+ 1 sentence: Why it matters to the NEXT agent (from downstream table)
184
+ ```
185
+
186
+ ### Template: MEDIUM (1 line)
187
+
188
+ ```
189
+ [agent] — <summary first sentence, ≤80 chars> — <files>
190
+ ```
191
+
192
+ ### Template: LOW (filename only)
193
+
194
+ ```
195
+ [agent] — <files>
196
+ ```
197
+
198
+ ### Variants Per Agent Pair
199
+
200
+ | Agent Pair | What to Include |
201
+ |------------|-----------------|
202
+ | Hermes → Aphrodite | Endpoint path, request/response shape, status codes |
203
+ | Hermes → Demeter | Model/table names, relationships, foreign keys |
204
+ | Demeter → Hermes | Table/column names, migration version, data types |
205
+ | Demeter → Aphrodite | New fields added, field types, defaults |
206
+ | Aphrodite → Hermes | Component name, data requirements, event handlers |
207
+ | Aphrodite → Demeter | UI state shape, fields displayed |
208
+ | Themis → * | Verdict, critical issues count, coverage delta |
209
+ | * → Themis | Preserve ALL fields (full context for review) |
210
+ | * → Mnemosyne | Summary, status only (archive: minimal) |
211
+ | Hephaestus → Hermes | Pipeline inputs/outputs, model endpoints |
212
+ | Prometheus → Hermes | Deploy target, env vars, config changes |
213
+
214
+ For MEDIUM and LOW entries, skip variant templates — use standard 1-line or aggressive compression.
215
+
216
+ ---
217
+
218
+ ## 5. Downstream-Aware Compression
219
+
220
+ Each entry type uses a field mask based on (from_agent, to_agent). The field mask determines which subtask_summary fields survive compression.
221
+
222
+ ### Available Fields
223
+
224
+ | Field | Type | Description |
225
+ |-------|------|-------------|
226
+ | `date` | string | YYYY-MM-DD |
227
+ | `agent` | string | Agent name |
228
+ | `files` | string | Comma-separated file paths |
229
+ | `summary` | string | Full summary text |
230
+ | `summary_semantic` | string | Generated semantic summary (CRITICAL/HIGH only) |
231
+ | `tests` | string | Test status + count |
232
+ | `status` | string | complete / partial / escalated |
233
+ | `coverage` | string | Coverage percentage |
234
+ | `verdict` | string | Themis verdict (APPROVED/NEEDS_REVISION/FAILED) |
235
+ | `critical_issues` | int | Count of critical issues found |
236
+ | `blockers` | string | Blocker description |
237
+
238
+ ### Field Masks Per Agent Pair
239
+
240
+ | From → To | Fields Preserved | Notes |
241
+ |-----------|-----------------|-------|
242
+ | hermes → aphrodite | date, agent, files, summary_semantic, tests, status | Endpoint + schema only |
243
+ | hermes → demeter | date, agent, files, summary_semantic, tests, status | Models + relationships only |
244
+ | hermes → * (default) | date, agent, files, summary_semantic, tests, status | |
245
+ | demeter → hermes | date, agent, files, summary_semantic, tests, status | Tables + migrations only |
246
+ | demeter → aphrodite | date, agent, files, summary_semantic, tests, status | New fields only |
247
+ | demeter → * (default) | date, agent, files, summary_semantic, tests, status | |
248
+ | aphrodite → hermes | date, agent, files, summary_semantic, tests, status | Component + data needs |
249
+ | aphrodite → demeter | date, agent, files, summary_semantic, tests, status | UI state + fields |
250
+ | aphrodite → * (default) | date, agent, files, summary_semantic, tests, status | |
251
+ | themis → * | date, agent, verdict, critical_issues, coverage, files | Review context |
252
+ | * → themis | date, agent, files, summary (full), tests, status, coverage | Full context |
253
+ | * → mnemosyne | date, agent, summary (first 60 chars), status | Minimal |
254
+ | hephaestus → * | date, agent, files, summary_semantic, tests, status | Pipeline + model info |
255
+ | prometheus → * | date, agent, files, summary_semantic, tests, status | Deploy + config info |
256
+
257
+ ### Implementation
258
+
259
+ Zeus applies the mask before generating the compressed entry:
260
+
261
+ ```python
262
+ def apply_mask(entry: dict, from_agent: str, to_agent: str) -> dict:
263
+ mask = FIELD_MASKS.get((from_agent, to_agent), FIELD_MASKS[("*", "*")])
264
+ return {k: v for k, v in entry.items() if k in mask}
265
+ ```
266
+
267
+ ---
268
+
269
+ ## 6. Budget Allocation Algorithm
270
+
271
+ Compressed entries live in the `## Completed Phases` section of `01-active-context.md`. The total budget is managed to prevent unbounded growth.
272
+
273
+ ### Budget
274
+
275
+ ```
276
+ TOTAL_BUDGET = 100 lines for ## Completed Phases section
277
+ PER_PHASE_BUDGET = TOTAL_BUDGET / estimated_phases (floor 5 lines)
278
+ ```
279
+
280
+ Estimated_phases is the total number of phases planned for the current feature. If unknown, default to 8 phases → PER_PHASE_BUDGET = 12 lines.
281
+
282
+ ### Line Cost Table
283
+
284
+ | Priority | Expanded | Standard | Aggressive |
285
+ |----------|----------|----------|------------|
286
+ | CRITICAL | 3 lines | N/A | N/A |
287
+ | HIGH | 2 lines | 1 line | N/A |
288
+ | MEDIUM | N/A | 1 line | N/A |
289
+ | LOW | N/A | N/A | 0.5 lines |
290
+
291
+ ### Priority-Greedy Algorithm
292
+
293
+ 1. Sort all entries by `priority_score` descending.
294
+ 2. CRITICAL entries always get EXPANDED (3 lines each) — non-negotiable.
295
+ 3. For remaining budget (TOTAL_BUDGET − sum(CRITICAL×3)):
296
+ - HIGH entries: EXPANDED (2 lines) if budget allows, else STANDARD (1 line).
297
+ - MEDIUM entries: STANDARD (1 line).
298
+ - LOW entries: AGGRESSIVE (0.5 lines, filename only).
299
+ 4. If at any point CRITICAL entries would exceed TOTAL_BUDGET → **escalate to Zeus** (see Budget Guardrails, §18).
300
+
301
+ ### Example
302
+
303
+ ```
304
+ Feature has 8 phases. TOTAL_BUDGET = 100, PER_PHASE_BUDGET = 12.
305
+
306
+ Phase 1 submits:
307
+ - Entry A: score 0.82 → CRITICAL (3 lines)
308
+ - Entry B: score 0.45 → MEDIUM (1 line)
309
+ Total: 4 lines (of 12 budget). 8 lines carried to next phase.
310
+
311
+ Phase 2 submits:
312
+ - Entry C: score 0.91 → CRITICAL (3 lines)
313
+ - Entry D: score 0.67 → HIGH — budget has 20 remaining lines, so EXPANDED (2 lines)
314
+ - Entry E: score 0.21 → LOW (0.5 lines)
315
+ Total: 5.5 lines. Cumulative 9.5 of 24 budget.
316
+ ```
317
+
318
+ ---
319
+
320
+ ## 7. Cross-Reference Mechanism
321
+
322
+ Auto-generated `_xref/index.md` provides persistent entity references that survive sprint boundaries and feature completions.
323
+
324
+ ### Cross-Reference File Location
325
+
326
+ `.pantheon/memory-bank/_xref/index.md` (created if absent; committed like `_notes/`)
327
+
328
+ ### Reference ID Format
329
+
330
+ | Prefix | Type | Example | Generated When |
331
+ |--------|------|---------|----------------|
332
+ | `D{NNNN}` | Decision | D0001 | REVIEW with decision note |
333
+ | `E{NNNN}` | Endpoint | E0001 | CRITICAL entry mentions new endpoint |
334
+ | `M{NNNN}` | Migration | M0001 | CRITICAL entry mentions new table/column |
335
+ | `C{NNNN}` | Component | C0001 | CRITICAL entry mentions new component |
336
+
337
+ IDs are monotonic integers pulled from `_xref/_next_id.json` and incremented.
338
+
339
+ ### Auto-Generation Rules
340
+
341
+ | Condition | Action |
342
+ |-----------|--------|
343
+ | CRITICAL entry mentions a new endpoint (keywords: `POST`, `GET`, `PUT`, `DELETE`, `/api/`, `/v1/`, `/v2/`, `endpoint`, `route`) | Add to **By Entity** table with agent, phase, file reference |
344
+ | CRITICAL entry mentions new table/column (keywords: `new table`, `new column`, `migration`, `ALTER TABLE`, `CREATE TABLE`) | Add to **By Entity** table with migration reference |
345
+ | Entry that was previously `blocked` now completes | Link from blocking entry → unblocking entry in cross-refs |
346
+ | REVIEW with decision note (`## Decision` or ADR reference) | Add to **Decision Links** table |
347
+
348
+ ### Cross-Reference Index File Structure
349
+
350
+ ```markdown
351
+ # Cross-Reference Index
352
+
353
+ ## By Feature
354
+
355
+ | Feature | Phase(s) | Agent(s) | Priority | Summary |
356
+ |---------|----------|----------|----------|---------|
357
+ | auth-jwt | 1, 2 | Hermes, Aphrodite | HIGH | JWT login + refresh token UI |
358
+
359
+ ## By Entity
360
+
361
+ | Entity ID | Type | Name | Location | Phase | Agent |
362
+ |-----------|------|------|----------|-------|-------|
363
+ | E0001 | endpoint | POST /auth/login | backend/routers/auth.py:42 | P1 | Hermes |
364
+ | M0001 | migration | add refresh_tokens table | backend/migrations/0012_... | P1 | Demeter |
365
+
366
+ ## Decision Links
367
+
368
+ | Ref ID | Type | Summary | Links To | Phase |
369
+ |--------|------|---------|----------|-------|
370
+ | D0001 | ADR | Use refresh token rotation instead of opaque tokens | _notes/ADR-auth-strategy.md | P1 |
371
+ ```
372
+
373
+ ---
374
+
375
+ ## 8. ZZ Artifact Format
376
+
377
+ A compressed context artifact `ZZ-phase{N}-context.md` is generated after each phase and injected into the next phase's agent prompt. It lives in `.pantheon/memory-bank/.tmp/`.
378
+
379
+ ### Location
380
+
381
+ `.pantheon/memory-bank/.tmp/ZZ-phase{N}-context.md`
382
+
383
+ ### Format
384
+
385
+ ```markdown
386
+ # Phase N → Phase N+1 Context
387
+ **From:** @agent_A (Phase N)
388
+ **To:** @agent_B (Phase N+1)
389
+
390
+ ## Budget
391
+ - Allocated: 12 lines
392
+ - Used: 4 lines
393
+ - Carried: 8 lines
394
+
395
+ ## Priority Entries
396
+
397
+ ### CRITICAL (expanded)
398
+
399
+ **Entry:** Auth JWT endpoint
400
+ **Agent:** Hermes | **Score:** 0.82
401
+ **What changed:** Added POST /auth/login and POST /auth/refresh endpoints with JWT rotation. Access token lives 15 min, refresh token 7 days.
402
+ **To next agent:** Aphrodite needs to implement login form and token storage (httpOnly cookies), auto-refresh on 401.
403
+ **Gotcha:** Refresh tokens are stored in DB as hashed — no raw token access after issue. Rotate on every use.
404
+
405
+ **Entry:** Refresh token table
406
+ **Agent:** Demeter | **Score:** 0.91
407
+ **What changed:** Created `refresh_tokens` table with FK to `users`, hashed token, expires_at, revoked_at.
408
+ **To next agent:** Hermes needs the TokenService to call `create_refresh_token()` + `rotate_refresh_token()`.
409
+ **Gotcha:** Migration includes a unique composite index on (user_id, token_hash). Two-phase rollout — read-old/write-new first.
410
+
411
+ ### HIGH (2-line)
412
+
413
+ **Entry:** Login page component
414
+ **Agent:** Aphrodite | **Score:** 0.62
415
+ **What changed:** Login form with email + password, validation, error display. Hits POST /auth/login.
416
+ **To next agent:** Hermes can test the full flow once Aphrodite's form is wired.
417
+
418
+ ### STANDARD (1-line)
419
+
420
+ | Date | Agent | Summary | Status |
421
+ |------|-------|---------|--------|
422
+ | 2026-06-20 | Prometheus | Dockerized auth service with nginx | complete |
423
+
424
+ ## Cross-References
425
+
426
+ | ID | Type | Name | File |
427
+ |----|------|------|------|
428
+ | E0001 | endpoint | POST /auth/login | backend/routers/auth.py |
429
+ | M0001 | migration | refresh_tokens table | backend/migrations/0012_... |
430
+ ```
431
+
432
+ ---
433
+
434
+ ## 9. Delegation Flow (Level 2)
435
+
436
+ ```
437
+ Zeus receives Themis APPROVED for Phase N
438
+
439
+ ├─ [COGNITIVE] Score each subtask_summary (priority scoring engine, no LLM)
440
+ │ 5 dimensions: Impact, Risk, Novelty, Blockers, Downstream relevance
441
+ │ → CRITICAL / HIGH / MEDIUM / LOW per entry
442
+
443
+ ├─ [COGNITIVE] Determine next phase agents + downstream relevance
444
+ │ Look up (from_agent, to_agent) in agent-pair table
445
+
446
+ ├─ [COGNITIVE] Run budget allocation (priority-greedy)
447
+ │ CRITICAL always expanded → HIGH → MEDIUM → LOW
448
+ │ Check overflow: if CRITICAL > budget → escalate
449
+
450
+ ├─ [COGNITIVE] Generate semantic summaries (CRITICAL/HIGH only, ~50 tok each)
451
+ │ Template variants per (from_agent, to_agent)
452
+
453
+ ├─ [COGNITIVE] Identify cross-references
454
+ │ New endpoints → E{NNNN}, new tables → M{NNNN}, decisions → D{NNNN}
455
+
456
+ ├─ DELEGATE @mnemosyne Compress batch (enhanced):
457
+ │ a) Write ZZ-phase{N}-context.md to .tmp/
458
+ │ b) Write compressed entries to 01-active-context.md (priority-aware)
459
+ │ - CRITICAL: expanded (3 lines, semantic summary)
460
+ │ - HIGH: expanded (2 lines) or standard (1 line) per budget
461
+ │ - MEDIUM: standard (1 line)
462
+ │ - LOW: aggressive (0.5 lines)
463
+ │ c) Archive IMPL/REVIEW to 02-progress-log.md
464
+ │ d) Update _xref/index.md
465
+ │ - CRITICAL mentions of endpoints → By Entity
466
+ │ - CRITICAL mentions of tables → By Entity
467
+ │ - Decision notes → Decision Links
468
+ │ - Blocked→unblocked links
469
+ │ e) Increment _xref/_next_id.json
470
+
471
+ └─ Zeus injects ZZ-phase{N}-context.md into Phase N+1 agent prompts
472
+ Included in the prompt preamble: "Previous phase context: <ZZ content>"
473
+ ```
474
+
475
+ ### Standard Flow (C1 + C2 + C3 fire together)
476
+
477
+ ```
478
+ Zeus receives Themis APPROVED for Phase N
479
+
480
+ ├─ [COGNITIVE] Score + summarize + budget + cross-refs (as above)
481
+
482
+ ├─ @mnemosyne Compress (enhanced):
483
+ │ a) Write ZZ-phase{N}-context.md to .tmp/
484
+ │ b) Priority-aware write to 01-active-context.md
485
+ │ c) Archive IMPL/REVIEW to 02-progress-log.md
486
+ │ d) Update _xref/index.md
487
+ │ e) Increment _xref/_next_id.json
488
+
489
+ ├─ @mnemosyne Confirm: "Compression complete: N entries compressed (M CRITICAL, P HIGH), K cross-refs added"
490
+
491
+ ├─ [COGNITIVE] Zeus checks: are there pending learnings? (Wisdom Bridge)
492
+ │ If yes → inject into next agent's prompt
493
+
494
+ └─ Zeus continues orchestration → dispatches next phase with ZZ artifact
495
+ ```
496
+
497
+ ### Safety Preflight
498
+
499
+ Before ANY compression, Zeus MUST run this check:
500
+
501
+ ```python
502
+ def can_compress(artifact_type, status, verdict):
503
+ if artifact_type == "subtask_summary":
504
+ return status == "complete" # NOT in_progress, escalated, blocked
505
+ if artifact_type == "IMPL":
506
+ return True # Themis APPROVED already verified
507
+ if artifact_type == "REVIEW":
508
+ return verdict == "APPROVED" # NOT NEEDS_REVISION, FAILED
509
+ if artifact_type == "PLAN":
510
+ return all_phases_complete
511
+ if artifact_type == "DISC":
512
+ return user_approved
513
+ if artifact_type == "ADR":
514
+ return False # NEVER compress ADRs
515
+ return False
516
+ ```
517
+
518
+ ---
519
+
520
+ ## 10. Safety Rules — NEVER Compress
521
+
522
+ Same as Level 1. Never compress the following:
523
+
524
+ | Artifact / Condition | Action |
525
+ |----------------------|--------|
526
+ | subtask_summary with `in_progress` / `escalated` / `blocked` | Skip. Flag to Zeus. |
527
+ | REVIEW with `NEEDS_REVISION` / `FAILED` | Skip. Leave in `.tmp/`. |
528
+ | Current active PLAN | Skip. Archive only at feature completion. |
529
+ | ADR notes (`_notes/`) — permanent, immutable | **NEVER touch.** |
530
+ | Any artifact with active blockers | Skip. Flag to Zeus. |
531
+
532
+ ### Partial Compress — Warnlist
533
+
534
+ | Artifact / Condition | Action |
535
+ |----------------------|--------|
536
+ | subtask_summary with status `partial` | Compress BUT mark status as ⚠️ and score as MEDIUM minimum |
537
+ | DISC with `REQUEST CHANGES` | Flag to user, do not archive |
538
+ | DISC with `DISCARD` | Delete artifact, do not archive |
539
+ | Unrecognized `.tmp/` artifact | Flag to user, leave in place |
540
+
541
+ ---
542
+
543
+ ## 11. Transactional Write Protocol (C1 mitigation)
544
+
545
+ Same as Level 1. Atomic write prevents corruption from crashes during compression:
546
+
547
+ 1. Write to target file + `.tmp` suffix (same directory)
548
+ 2. `fsync()` the file descriptor — ensures data flushed to disk
549
+ 3. **Validate:** file > 0 bytes, has a heading (`#` or `##` line)
550
+ 4. `os.rename(.tmp, target)` — POSIX atomic rename on same filesystem
551
+ 5. If crash during write: stale `.tmp` cleaned on next startup (>5 min old)
552
+
553
+ ```python
554
+ import os
555
+
556
+ def atomic_write(path: str, content: str):
557
+ tmp_path = path + ".tmp"
558
+ with open(tmp_path, "w") as f:
559
+ f.write(content)
560
+ f.flush()
561
+ os.fsync(f.fileno())
562
+ if os.path.getsize(tmp_path) == 0:
563
+ raise RuntimeError(f"Write validation failed: {tmp_path} is empty")
564
+ os.rename(tmp_path, path)
565
+ ```
566
+
567
+ ---
568
+
569
+ ## 12. Inline Compression — Active Session Protocol
570
+
571
+ "Inline compression" (L1) is the Pantheon-native mechanism agents use DURING an active session to shrink working context. It is distinct from "L2" batch promotion — the file-based Memory Bank writes Mnemosyne performs at phase boundaries (see §9). These are NOT a mandatory 3-layer trigger model: agents invoke L1 only; L2 happens automatically at gates.
572
+
573
+ ### L1 — Inline Compression (the only agent-triggered step)
574
+ Call the compressor via the MCP tool. Scrubbing is AUTOMATIC in the MCP layer — never scrub manually and never embed raw secrets beyond what the tool scrubs:
575
+
576
+ ```
577
+ execute_code_script("compress-inline.py", args=["compress", "--text", "<content>"])
578
+ ```
579
+
580
+ Modes: `score` (preview priority), `compress` (scrub + score + compress), `stats`, `batch` (multiple files).
581
+
582
+ ### L2 — Batch Promotion (automatic, not an agent trigger)
583
+ At phase gates / handoffs, Mnemosyne promotes compressed entries into the file-based Memory Bank (`01-active-context.md`, etc.). Agents do NOT invoke L2 — it runs automatically. Inline compression (L1) and batch promotion (L2) are NOT a mandatory 3-layer trigger model.
584
+
585
+ ### Triggers (full table in §2)
586
+
587
+ - **C8**: after a CRITICAL/HIGH `subtask_summary` → L1 compress before next phase.
588
+ - **C9**: before delegating a large context block → L1 compress to cut tokens.
589
+ - **C10**: context pressure → handled by OpenCode native compaction (cross-reference only; no Pantheon mechanism).
590
+ - **C11**: phase boundary / handoff → L1 compress completed work.
591
+
592
+ ### Promotion Pipeline (context flow, not a trigger model)
593
+
594
+ The Flow below shows how compressed context PROMOTES from live session → inline → batch. Agents run L1 only; L2 is automatic at gates:
595
+
596
+ ```
597
+ Agent produces context (subtask_summary, large block, phase work)
598
+
599
+ ├─ [L1 INLINE] execute_code_script("compress-inline.py", args=["compress", "--text", "..."])
600
+ │ → scrubbed + scored + compressed output (MCP layer scrubs automatically)
601
+
602
+ └─ [L2 PROMOTE] At phase gate / handoff, Mnemosyne promotes compressed
603
+ entries into the file-based Memory Bank (01-active-context.md, etc.)
604
+ → batch promotion, NOT an agent trigger
605
+ ```
606
+
607
+ ### Safety Rules
608
+
609
+ | Rule | Description |
610
+ |------|-------------|
611
+ | Scrubbing is automatic in the MCP layer | Never run a manual scrub; never embed raw secrets beyond what the tool scrubs |
612
+ | `compress-inline.py` always scrubs before scoring | Built-in security — no agent action needed |
613
+ | Inline compression (L1) is non-destructive to source files | Output is returned; originals untouched |
614
+
615
+ ### Agent Responsibilities
616
+
617
+ **Implementation agents (Hermes, Aphrodite, Demeter, Hephaestus, Prometheus):**
618
+ - After a CRITICAL/HIGH `subtask_summary` → trigger C8 (L1 compress)
619
+ - Before delegating a large context block → trigger C9 (L1 compress)
620
+ - At a phase boundary / handoff → trigger C11 (L1 compress)
621
+ - Do NOT implement a separate context-pressure mechanism (C10 is OpenCode-native)
622
+
623
+ ---
624
+
625
+ ## 13. Security Scrubbing (H1 mitigation)
626
+
627
+ Scrubbing is automatic — the `memory_store` MCP server applies Layer 2 regex scrub before persisting content. No manual steps required.
628
+
629
+ ### Layer 1 — Structural (metadata only)
630
+
631
+ Only promote structured metadata. NEVER promote:
632
+
633
+ - Raw stdout or stderr output
634
+ - Test output or command results
635
+ - Stack traces or error details
636
+ - Environment variables or configuration values
637
+
638
+ Allowed fields: file paths, status, pass/fail verdicts, phase names, agent names, dates.
639
+
640
+ ### Layer 2 — Regex pattern scrub (automatic via MCP layer)
641
+
642
+ **Source of truth:** `scripts/scrub-secrets.py` — the single canonical scrubber. Both `memory_mcp_server.py` and `compress-inline.py` load it via `importlib` (the filename has a hyphen and cannot be `import`ed normally). Do NOT maintain a separate inline pattern list.
643
+
644
+ **Real signature:**
645
+
646
+ ```python
647
+ def scrub(content: str) -> tuple[str, list[dict]]:
648
+ # returns (scrubbed_text, redactions)
649
+ # each redaction dict: {"type": str, "position": (start, end), "replacement": str}
650
+ ```
651
+
652
+ **Secret types covered** (see `scripts/scrub-secrets.py` for the actual patterns): SSH private key, private key, certificate, Bearer token, JWT, GitHub PAT (`ghp_`), OpenAI key (`sk-...`), generic `api_key`/`token`/`secret`/`password`, AWS access key (`AKIA`), Google API key (`AIza`), Slack token (`xox`), Heroku API key (UUID), PostgreSQL/MySQL/Redis connection strings, and `.env` export statements.
653
+
654
+ > Scrubbing is AUTOMATIC in the MCP layer — `memory_store` and compress-inline both call `scrub()` before persistence. Agents never scrub manually.
655
+
656
+ ---
657
+
658
+ ## 14. Concurrency (M1 mitigation)
659
+
660
+ Same as Level 1. Zeus batches parallel phase completions into a single compression call. Lockfile safety net.
661
+
662
+ **Batching rule:** When multiple parallel phases complete simultaneously, Zeus collects all subtask_summaries and dispatches a single compression request to Mnemosyne:
663
+
664
+ ```
665
+ @mnemosyne Compress batch (enhanced): [
666
+ { type: subtask, phase: "2a", agent: Hermes, from: Hermes, to: Aphrodite, ... },
667
+ { type: subtask, phase: "2b", agent: Aphrodite, from: Aphrodite, to: Hermes, ... },
668
+ ...
669
+ ]
670
+ ```
671
+
672
+ Each entry is independently scored and budget-allocated.
673
+
674
+ **Lockfile safety net:** A lockfile at `.pantheon/memory-bank/.tmp/compress.lock` with `flock` as a safety net for the rare case of overlapping manual `/compress` and automatic compression.
675
+
676
+ ---
677
+
678
+ ## 15. Wisdom Bridge
679
+
680
+ Same as Level 1. Extraction BEFORE compression, non-blocking failures.
681
+
682
+ ```
683
+ Phase N Themis APPROVED
684
+
685
+ ├─ 1. Agent extracts learnings → .pantheon/learnings/<feature>/learnings.md
686
+ ├─ 2. Compression fires (scored + archived)
687
+ └─ 3. Next agent dispatched with ZZ artifact + learnings injected
688
+ ```
689
+
690
+ **Extraction is advisory, compression is mandatory.** If the agent fails to extract learnings (timeout, error), compression proceeds anyway.
691
+
692
+ ### Injection
693
+
694
+ Zeus reads `.pantheon/learnings/<feature>/learnings.md` and includes in the next agent's prompt:
695
+
696
+ ```
697
+ ## Previous Wave Learnings
698
+ <contents of learnings.md>
699
+
700
+ ## Compressed Context (Phase N → Phase N+1)
701
+ <contents of ZZ-phase{N}-context.md>
702
+
703
+ Apply these learnings and context to your implementation.
704
+ ```
705
+
706
+ ### Cleanup
707
+
708
+ At feature merge or sprint close:
709
+ 1. Promote surviving learnings (those not already in `/memories/repo/`) to atomic facts
710
+ 2. Delete `.pantheon/learnings/<feature>/learnings.md`
711
+
712
+ ---
713
+
714
+ ## 16. Rollback (C2 — use git)
715
+
716
+ Same as Level 1.
717
+
718
+ ```bash
719
+ # View history of compressed file
720
+ git log -p .pantheon/memory-bank/01-active-context.md | less
721
+
722
+ # Restore pre-compression state
723
+ git show HEAD~1:.pantheon/memory-bank/01-active-context.md > .pantheon/memory-bank/01-active-context.md
724
+
725
+ # Or revert specific commit
726
+ git revert <commit-sha>
727
+ ```
728
+
729
+ Pre-compression content is always available in git history.
730
+
731
+ ---
732
+
733
+ ## 17. Idempotency
734
+
735
+ Updated for Level 2 with content hashing and cross-ref dedup.
736
+
737
+ | Target | Idempotency Key | Behavior |
738
+ |--------|----------------|----------|
739
+ | `01-active-context.md` table row | (date, phase, agent) + content hash of summary | Skip if exact match exists; overwrite if same key but different hash |
740
+ | `02-progress-log.md` section | `### YYYY-MM-DD — <phase>: <agent>` | Skip append if heading exists |
741
+ | `02-progress-log.md` REVIEW line | `**Review:**` in same section | Skip if line exists |
742
+ | `01-active-context.md` Plans row | (date, feature) | Skip if exists |
743
+ | `_xref/index.md` | `| E{NNNN}` reference ID | Skip if ID exists; error if ID already used for different entity |
744
+ | `_xref/_next_id.json` | File path | Overwrite with incremented value |
745
+ | `ZZ-phase{N}-context.md` | Phase number | Overwrite if same phase (last write wins) |
746
+ | `.tmp/` file deletion | File path | File not found → silent skip |
747
+
748
+ ### Content Hash
749
+
750
+ ```python
751
+ import hashlib
752
+
753
+ def entry_hash(entry: dict) -> str:
754
+ canonical = f"{entry['date']}|{entry['phase']}|{entry['agent']}|{entry.get('summary', '')}"
755
+ return hashlib.sha256(canonical.encode()).hexdigest()[:16]
756
+ ```
757
+
758
+ When checking for duplicates, both the idempotency key AND the content hash must match for a skip. Same key but different hash → overwrite (entry was updated).
759
+
760
+ ---
761
+
762
+ ## 18. Budget Guardrails
763
+
764
+ Prevent budget abuse and ensure CRITICAL entries are never lost.
765
+
766
+ ### Rules
767
+
768
+ | Guardrail | Threshold | Action |
769
+ |-----------|-----------|--------|
770
+ | **CRITICAL floor** | CRITICAL entries always expanded | Non-negotiable. Never compress to standard or aggressive. |
771
+ | **Overflow** | >5 CRITICAL entries per phase | Flag Zeus: "Phase N has M > 5 CRITICAL entries. Budget risk." |
772
+ | **Exceed budget** | CRITICAL entries alone exceed TOTAL_BUDGET (100 lines) | Escalate to Zeus: "CRITICAL entries require N lines but budget is 100. Options: (1) increase budget, (2) increase TOTAL_BUDGET permanently, (3) split phase." |
773
+ | **Carryover** | Unused PER_PHASE_BUDGET | 20% of unused budget rolls to next phase (round down). Remaining 80% is released (does not carry forward). |
774
+ | **Ceiling** | `## Completed Phases` section | Hard cap at 100 lines. Overflows trigger C7 size-based trim on LOW entries first. |
775
+
776
+ ### Carryover Formula
777
+
778
+ ```
779
+ carryover = floor(remaining_budget * 0.20)
780
+ next_phase_budget = PER_PHASE_BUDGET + carryover
781
+ ```
782
+
783
+ Example: Phase 1 had 12-line budget, used 4 lines. Remaining = 8 lines. Carryover = floor(8 × 0.20) = 1 line. Phase 2 starts with 12 + 1 = 13 lines.
784
+
785
+ ### C7 Trim Priority (Size-Based Auto-Trim)
786
+
787
+ When `01-active-context.md` exceeds 100 lines:
788
+
789
+ 1. Sort entries by priority_score ascending (lowest first).
790
+ 2. Trim LOW entries first (remove entire 0.5-line rows).
791
+ 3. If still over budget, trim MEDIUM entries to 0.5 lines each.
792
+ 4. Never trim CRITICAL or HIGH.
793
+ 5. Trimmed entries are archived to `_notes/archive/YYYY-MM-compressed-entries.md`.
794
+ 6. Log: "C7 trim: removed N low-priority entries, archived to _notes/archive/..."
795
+
796
+ ---
797
+
798
+ ## Quick Reference
799
+
800
+ ```
801
+ ┌────────────────────────────────────────────────────────────────────┐
802
+ │ CONTEXT COMPRESSION — LEVEL 2 │
803
+ │ │
804
+ │ Priority Scoring (deterministic, no LLM): │
805
+ │ Score = 0.30×Impact + 0.25×Risk + 0.20×Novelty + 0.15×Blockers │
806
+ │ + 0.10×Downstream_relevance │
807
+ │ CRITICAL ≥ 0.75 | HIGH ≥ 0.50 | MEDIUM ≥ 0.25 | LOW < 0.25 │
808
+ │ │
809
+ │ Semantic Summarization (CRITICAL/HIGH only): │
810
+ │ Template per agent pair, ~50 tok each │
811
+ │ CRITICAL: 3 lines (what + why + gotcha) │
812
+ │ HIGH: 2 lines (what + why) │
813
+ │ │
814
+ │ Downstream-Aware Field Masks: │
815
+ │ (from_agent, to_agent) → field set │
816
+ │ *→Themis: preserve ALL | *→Mnemosyne: preserve MINIMAL │
817
+ │ │
818
+ │ Budget Allocation (priority-greedy): │
819
+ │ TOTAL = 100 lines | PER_PHASE = floor(100 / phases) │
820
+ │ CRITICAL always expanded → HIGH → MEDIUM → LOW │
821
+ │ 20% of unused budget carries to next phase │
822
+ │ │
823
+ │ Cross-References: │
824
+ │ E{NNNN} endpoints | M{NNNN} migrations | D{NNNN} decisions │
825
+ │ C{NNNN} components | Auto-generated in _xref/index.md │
826
+ │ │
827
+ │ ZZ Artifact: │
828
+ │ .pantheon/memory-bank/.tmp/ZZ-phase{N}-context.md │
829
+ │ Injected into next phase agent prompt │
830
+ │ │
831
+ │ Safety: NEVER compress in_progress/escalated/ │
832
+ │ blocked/NEEDS_REVISION/FAILED/ADR │
833
+ │ Write safety: atomic .tmp + fsync + rename │
834
+ │ Security: Layer 1 (structural) + Layer 2 (regex) │
835
+ │ Concurrency: Zeus batches, lockfile as safety net │
836
+ │ Rollback: git log -p │
837
+ │ Idempotent: keyed by (date, phase, agent) + content hash │
838
+ │ Budget guardrails: CRITICAL floor, overflow flag, carryover │
839
+ │ Inline Compression (C8-C11 - Active Session, L1 = Pantheon-native): │
840
+ │ C8: CRITICAL/HIGH subtask_summary → compress (L1) │
841
+ │ C9: pre-delegation large block → compress (L1) │
842
+ │ C10: context pressure → OpenCode native compaction (x-ref only) │
843
+ │ C11: phase boundary / handoff → compress (L1) │
844
+ │ L1 = compress-inline.py MCP | L2 = batch promotion (Mnemosyne) │
845
+ │ Scrubbing automatic in MCP layer — never scrub manually │
846
+ │ │
847
+ │ Zeus: cognitive scoring + summarization + budget + cross-refs │
848
+ │ Mnemosyne: file I/O (write ZZ, active context, progress log, │
849
+ │ xref index, next_id.json, delete .tmp) │
850
+ └────────────────────────────────────────────────────────────────────┘
851
+ ```
852
+
853
+ ---
854
+
855
+ **References:**
856
+ - `skill: artifact-management` — artifact lifecycle
857
+ - `instructions/agent-return-format.instructions.md` — subtask_summary format
858
+ - `skill: memory-bank` — memory bank structure
859
+ - `skills/wisdom-accumulation/SKILL.md` — learning extraction
860
+ - `skills/memory-bank/SKILL.md` — memory bank maintenance
861
+ - `instructions/backend-standards.instructions.md` — zeus scoring reference