@tera-system/core 0.1.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 (161) hide show
  1. package/LICENSE.md +13 -0
  2. package/MANIFEST.json +24 -0
  3. package/README.md +67 -0
  4. package/RELEASES.md +28 -0
  5. package/WELCOME.md +35 -0
  6. package/agents/application-blueprint.md +407 -0
  7. package/agents/auditor.md +665 -0
  8. package/agents/design-reviewer.md +392 -0
  9. package/agents/domain-expert-agent.md +510 -0
  10. package/agents/domain-research-agent.md +360 -0
  11. package/agents/engineering-agent-dotnet.md +218 -0
  12. package/agents/engineering-agent-phaser.md +275 -0
  13. package/agents/engineering-agent-typescript.md +300 -0
  14. package/agents/engineering-agent.md +143 -0
  15. package/agents/monitor.md +395 -0
  16. package/agents/production-erp-expert.md +506 -0
  17. package/agents/project-knowledge-agent.md +271 -0
  18. package/agents/qa-agent.md +498 -0
  19. package/agents/tera-business-transformation-consultant.md +290 -0
  20. package/agents/tera-client-engagement.md +891 -0
  21. package/agents/tera-software-designer.md +237 -0
  22. package/agents/tera-strategic-advisor.md +325 -0
  23. package/agents/tera-system-evolution.md +759 -0
  24. package/agents/tera.md +520 -0
  25. package/agents/ui-designer.md +426 -0
  26. package/commands/tera-approve.md +34 -0
  27. package/commands/tera-diagnose.md +47 -0
  28. package/commands/tera-gate.md +40 -0
  29. package/commands/tera-help.md +41 -0
  30. package/commands/tera-new-project.md +35 -0
  31. package/commands/tera-plan.md +34 -0
  32. package/commands/tera-request-build.md +45 -0
  33. package/commands/tera-resume.md +34 -0
  34. package/commands/tera-review.md +52 -0
  35. package/commands/tera-status.md +38 -0
  36. package/commands/tera-update.md +48 -0
  37. package/core/project-control/templates/TASK_TEMPLATE.md +146 -0
  38. package/core/tera-system/AGENT_ACTIVATION_MATRIX.md +285 -0
  39. package/core/tera-system/AGENT_DEPENDENCY_MAP.md +117 -0
  40. package/core/tera-system/AGENT_GENERATION_TEMPLATE.md +312 -0
  41. package/core/tera-system/AGENT_PERMISSION_MODEL.md +343 -0
  42. package/core/tera-system/AIS_PROTOCOL.md +191 -0
  43. package/core/tera-system/TERA_AGENT_CONDUCT.md +102 -0
  44. package/core/tera-system/TERA_CONTINUOUS_IMPROVEMENT_POLICY.md +111 -0
  45. package/core/tera-system/TERA_DISTRIBUTION_POLICY.md +291 -0
  46. package/core/tera-system/TERA_PROJECT_DECISION.md +281 -0
  47. package/core/tera-system/TERA_USER_GUIDE.md +462 -0
  48. package/core/tera-system/TOOLING_AND_MCP_POLICY.md +285 -0
  49. package/core/tera-system/TeraApplicationQuestionBank.md +362 -0
  50. package/core/tera-system/TeraArchitectureMap.md +91 -0
  51. package/core/tera-system/TeraClientPolicy.md +366 -0
  52. package/core/tera-system/TeraHelperAgents.md +970 -0
  53. package/core/tera-system/TeraPolicyMap.md +131 -0
  54. package/core/tera-system/TeraPreExecutionGate.md +818 -0
  55. package/core/tera-system/TeraPreparationDocumentationGovernance.md +370 -0
  56. package/core/tera-system/TeraPricingPolicy.md +674 -0
  57. package/core/tera-system/TeraProjectIntakePolicy.md +164 -0
  58. package/core/tera-system/TeraScenarioStressTests.md +168 -0
  59. package/core/tera-system/TeraSubAgents.md +854 -0
  60. package/core/tera-system/TeraSystemMaintenanceChecklist.md +80 -0
  61. package/core/tera-system/TeraTokenPolicy.md +362 -0
  62. package/core/tera-system/Tera_Project_Preparation_Files.md +1045 -0
  63. package/core/tera-system/agent-helpers/application-blueprint-details.md +177 -0
  64. package/core/tera-system/client-helpers/tera-client-engagement-discovery-domains.md +99 -0
  65. package/core/tera-system/client-helpers/tera-client-engagement-gates.md +258 -0
  66. package/core/tera-system/client-helpers/tera-client-engagement-pricing.md +341 -0
  67. package/core/tera-system/client-helpers/tera-client-engagement-protocols.md +692 -0
  68. package/core/tera-system/consulting-helpers/BTCA_METHODOLOGY_FRAMEWORK.md +195 -0
  69. package/core/tera-system/consulting-helpers/BTCA_REPORT_TEMPLATES.md +266 -0
  70. package/core/tera-system/design-system/ACCESSIBILITY_RULES.md +31 -0
  71. package/core/tera-system/design-system/COMPONENT_LIBRARY_SCHEMA.md +46 -0
  72. package/core/tera-system/design-system/DESIGN_MD_INTEGRATION.md +59 -0
  73. package/core/tera-system/design-system/DESIGN_REVIEW_STANDARDS.md +241 -0
  74. package/core/tera-system/design-system/DESIGN_SOURCE_PROTOCOL.md +61 -0
  75. package/core/tera-system/design-system/DESIGN_SYSTEM_OVERVIEW.md +66 -0
  76. package/core/tera-system/design-system/DESIGN_TOKENS_SCHEMA.md +66 -0
  77. package/core/tera-system/design-system/EXTERNAL_REFERENCE_ANALYSIS.md +52 -0
  78. package/core/tera-system/design-system/FIGMA_INTEGRATION.md +138 -0
  79. package/core/tera-system/design-system/INTERNAL_KITS_INDEX.md +26 -0
  80. package/core/tera-system/design-system/LAYOUT_PATTERNS.md +52 -0
  81. package/core/tera-system/design-system/MOBILE_UI_UX_STANDARDS.md +342 -0
  82. package/core/tera-system/design-system/RTL_LTR_RULES.md +39 -0
  83. package/core/tera-system/design-system/UI_ACCEPTANCE_GATE.md +80 -0
  84. package/core/tera-system/design-system/kits/KIT_ADMIN_DASHBOARD.md +102 -0
  85. package/core/tera-system/engineering-governance/ENGINEERING_AGENT_RESPONSIBILITIES.md +210 -0
  86. package/core/tera-system/engineering-governance/ENGINEERING_BEST_PRACTICES.md +468 -0
  87. package/core/tera-system/engineering-governance/ENGINEERING_GOVERNANCE_GATE.md +131 -0
  88. package/core/tera-system/engineering-governance/ENGINEERING_REVIEW_CHECKLIST.md +129 -0
  89. package/core/tera-system/engineering-governance/QUALITY_GATE_THRESHOLDS.md +159 -0
  90. package/core/tera-system/engineering-helpers/engineering-agent-core.md +171 -0
  91. package/core/tera-system/knowledge-base/OPENHANDS_ARCHITECTURE_REFERENCE.md +243 -0
  92. package/core/tera-system/knowledge-base/manufacturing/00_INDEX.md +32 -0
  93. package/core/tera-system/knowledge-base/manufacturing/01_MANUFACTURING_ERP_CORE_CONCEPTS.md +7 -0
  94. package/core/tera-system/knowledge-base/manufacturing/02_SAP_MANUFACTURING_RESEARCH.md +7 -0
  95. package/core/tera-system/knowledge-base/manufacturing/03_DYNAMICS_365_MANUFACTURING_RESEARCH.md +7 -0
  96. package/core/tera-system/knowledge-base/manufacturing/04_ORACLE_MANUFACTURING_RESEARCH.md +7 -0
  97. package/core/tera-system/knowledge-base/manufacturing/05_ODOO_MANUFACTURING_RESEARCH.md +7 -0
  98. package/core/tera-system/knowledge-base/manufacturing/06_ERPNEXT_MANUFACTURING_RESEARCH.md +7 -0
  99. package/core/tera-system/knowledge-base/manufacturing/07_MANUFACTURING_COSTING_GUIDE.md +7 -0
  100. package/core/tera-system/knowledge-base/manufacturing/08_PRODUCTION_DISCOVERY_QUESTIONS.md +7 -0
  101. package/core/tera-system/knowledge-base/manufacturing/09_MANUFACTURING_BLUEPRINT_CHECKLIST.md +7 -0
  102. package/core/tera-system/knowledge-base/manufacturing/10_PRODUCTION_TEST_SCENARIOS.md +7 -0
  103. package/core/tera-system/knowledge-base/manufacturing/11_QUALITY_REWORK_AND_SCRAP_GUIDE.md +7 -0
  104. package/core/tera-system/knowledge-base/manufacturing/12_MRP_AND_PLANNING_GUIDE.md +7 -0
  105. package/core/tera-system/knowledge-base/manufacturing/13_LOCAL_AND_REGIONAL_MANUFACTURING_CONTEXT.md +7 -0
  106. package/core/tera-system/knowledge-base/manufacturing/14_VENDOR_COMPARISON_MATRIX.md +7 -0
  107. package/core/tera-system/product-standards/maintenance-apps/BEST_PRACTICES_DOMAIN.md +325 -0
  108. package/core/tera-system/product-standards/maintenance-apps/STANDARD_DEFINITION.md +142 -0
  109. package/core/tera-system/profiles/PROFILES_INDEX.md +57 -0
  110. package/core/tera-system/profiles/TEMPLATE.md +47 -0
  111. package/core/tera-system/profiles/dotnet-blazor-ef.md +76 -0
  112. package/core/tera-system/profiles/dotnet-razorpages-adonet.md +137 -0
  113. package/core/tera-system/profiles/dotnet-wpf-sqlite.md +159 -0
  114. package/core/tera-system/profiles/effect-bun-opencode.md +109 -0
  115. package/core/tera-system/profiles/flutter-mobile.md +369 -0
  116. package/core/tera-system/profiles/nextjs-prisma.md +110 -0
  117. package/core/tera-system/profiles/phaser-react-node.md +302 -0
  118. package/core/tera-system/profiles/react-pwa.md +97 -0
  119. package/core/tera-system/runtime/CLIENT_DISCOVERY_PROTOCOL.md +145 -0
  120. package/core/tera-system/runtime/DOMAIN_INTELLIGENCE_PROTOCOL.md +124 -0
  121. package/core/tera-system/runtime/MVP_DEFINITION_PROTOCOL.md +176 -0
  122. package/core/tera-system/runtime/TERA_RUNTIME_CHECKLISTS.md +646 -0
  123. package/core/tera-system/runtime/TERA_RUNTIME_PROTOCOLS.md +50 -0
  124. package/core/tera-system/runtime/TERA_RUNTIME_PROTOCOLS_CLIENT.md +355 -0
  125. package/core/tera-system/runtime/TERA_RUNTIME_PROTOCOLS_CORE.md +799 -0
  126. package/core/tera-system/runtime/TERA_RUNTIME_TEMPLATES.md +908 -0
  127. package/core/tera-system/runtime/TERA_RUNTIME_TEMPLATES_DELIVERY.md +584 -0
  128. package/core/tera-system/runtime/TERA_RUNTIME_TEMPLATES_PREPARATION.md +376 -0
  129. package/core/tera-system/runtime/TERA_SOLUTION_PREPARATION_PROTOCOL.md +335 -0
  130. package/core/tera-system/runtime/TERA_SOLUTION_PREPARATION_TEMPLATES.md +397 -0
  131. package/core/tera-system/runtime/VERSION_LIFECYCLE_PROTOCOL.md +296 -0
  132. package/core/tera-system/semgrep-rules/README.md +32 -0
  133. package/core/tera-system/semgrep-rules/tera-security.yml +66 -0
  134. package/core/tera-system/semgrep-rules/tera-standards.yml +49 -0
  135. package/core/tera-system/teranoo-ui/README.md +48 -0
  136. package/core/tera-system/teranoo-ui/components/button.tsx +51 -0
  137. package/core/tera-system/teranoo-ui/components/card.tsx +49 -0
  138. package/core/tera-system/teranoo-ui/components/dashboard-layout.tsx +36 -0
  139. package/core/tera-system/teranoo-ui/components/data-table.tsx +146 -0
  140. package/core/tera-system/teranoo-ui/components/empty-state.tsx +31 -0
  141. package/core/tera-system/teranoo-ui/components/kpi-card.tsx +42 -0
  142. package/core/tera-system/teranoo-ui/components/page-header.tsx +25 -0
  143. package/core/tera-system/teranoo-ui/components/search-input.tsx +40 -0
  144. package/core/tera-system/teranoo-ui/components/sidebar.tsx +66 -0
  145. package/core/tera-system/teranoo-ui/components/stats-card.tsx +37 -0
  146. package/core/tera-system/teranoo-ui/registry.json +77 -0
  147. package/core/tera-system/teranoo-ui/styles/teranoo-theme.css +61 -0
  148. package/opencode.tera.example.json +30 -0
  149. package/package.json +37 -0
  150. package/scripts/build.mjs +110 -0
  151. package/scripts/install.js +244 -0
  152. package/scripts/lib/license.mjs +90 -0
  153. package/scripts/lib/public-key.pem +3 -0
  154. package/scripts/tera-license.mjs +63 -0
  155. package/tools/tera-clean.ps1 +97 -0
  156. package/tools/tera-fetch.ps1 +165 -0
  157. package/tools/tera-release.ps1 +96 -0
  158. package/tools/tera-schedule.ps1 +59 -0
  159. package/tools/tera-update.ps1 +472 -0
  160. package/tools/tera-watch.ps1 +154 -0
  161. package/tools/update-client-repositories.ps1 +92 -0
@@ -0,0 +1,799 @@
1
+ # Tera Runtime Protocols — Core
2
+
3
+ These are the core operational protocols (Sections 1–11) split from TERA_RUNTIME_PROTOCOLS.md via INS-02 continuation (2026-08-01).
4
+ Client/discovery protocols: `tera-system/runtime/TERA_RUNTIME_PROTOCOLS_CLIENT.md` (Sections 12–18).
5
+ Knowledge management: `tera-system/runtime/TERA_RUNTIME_PROTOCOLS.md` (Section 19).
6
+
7
+ ---
8
+
9
+ ## 1. Runtime Self-Sync Protocol
10
+
11
+ `.opencode/agents/tera.md` is the complete system reference.
12
+ `.opencode/agents/tera.md` is the active runtime file.
13
+
14
+ Sync `.opencode/agents/tera.md` when the system reference changes rules about:
15
+
16
+ - File paths and output locations.
17
+ - Sub-agent generation, specialization, or activation policy.
18
+ - Anti-bloat and scope-control rules.
19
+ - Orchestration lifecycle, Decision Matrix, gates.
20
+ - Model Capability Gate or Security Sensitivity Levels.
21
+ - Roadmap tracking or PlanComplianceReviewAgent.
22
+ - Design Governance Layer or UI Acceptance Gate.
23
+ - Delegation format, handback protocol, or Tera authority.
24
+ - Policy map, architecture map, maintenance checklist, or source-of-truth rules.
25
+
26
+ Rules:
27
+ - Do not copy the full system reference.
28
+ - Sync only operational rules that affect runtime behavior.
29
+ - Update `Last Synced` in the file header after sync.
30
+ - If no sync is needed, document the reason in the maintenance report.
31
+
32
+ ---
33
+
34
+ ## 2. Generated Sub-Agent Lifecycle Protocol
35
+
36
+ When sub-agents are needed, generate them only inside:
37
+
38
+ ```text
39
+ generated-agents/opencode/
40
+ ```
41
+
42
+ Also create:
43
+
44
+ ```text
45
+ generated-agents/opencode/GENERATED_AGENTS_MANIFEST.md
46
+ ```
47
+
48
+ For Phase 4 (Sub-Agent Generation & Preparation Delegation), also create:
49
+
50
+ ```text
51
+ project-control/AGENT_DELEGATION_PLAN.md
52
+ ```
53
+
54
+ Phase 4 delegation is for **preparation-file creation only**. It must not be treated as application implementation.
55
+
56
+ Lifecycle:
57
+
58
+ | Stage | Location | Condition |
59
+ |---|---|---|
60
+ | `Generated Draft` | `generated-agents/opencode/` | Tera decides agent is needed, creates draft using `tera-system/AGENT_GENERATION_TEMPLATE.md` |
61
+ | `Activated` | `.opencode/agents/` | Tera specializes agent for current phase, narrows sources/targets, confirms no overlap, records activation reason |
62
+ | `Inactive` | `generated-agents/opencode/` | No current need; may be activated later |
63
+
64
+ Generation rules:
65
+
66
+ - Every generated agent must have a clear reason, input files, output files, and acceptance criteria.
67
+ - Every generated agent must include `MVP Constraints` and `Forbidden Actions` sections.
68
+ - Every generated agent must have a defined **Token Budget** (Light / Medium / Strong) and **Context Rules** (Task Context / Summary Context / Full Context) based on `TeraTokenPolicy.md`.
69
+ - The manifest must document project name, runtime environment, generation date, generated agents, agents not generated with reasons, and deferred/future agents.
70
+ - Do not generate all sub-agents by default.
71
+ - Keep the manifest compact. Do not convert it into a long activity log.
72
+
73
+ Activation rules:
74
+
75
+ - Before moving any generated agent into `.opencode/agents/`, Tera must narrow `Allowed Sources` and `Allowed Write Targets`, confirm non-overlap, and record why activation is needed now.
76
+ - After copying a newly activated agent, ask the user to restart OpenCode.
77
+ - Do not assume currently active agents are the only possible agent set.
78
+ - Before modifying `.opencode/agents/`, verify the active file exists. If only the generated draft exists, do not activate a new agent just for sync.
79
+
80
+ ### Manifest rules
81
+
82
+ Every generated agent batch must include a `GENERATED_AGENTS_MANIFEST.md` containing:
83
+
84
+ ```text
85
+ Project:
86
+ Runtime Environment:
87
+ Generated Date:
88
+ Generated By: Tera Agent
89
+
90
+ Agents Generated:
91
+ - Agent:
92
+ Reason:
93
+ File:
94
+ Category:
95
+ Allowed Write Targets:
96
+
97
+ Agents Not Generated:
98
+ - Agent:
99
+ Reason:
100
+
101
+ Notes:
102
+ - ...
103
+ ```
104
+
105
+ The manifest helps the user understand why specific agents were generated and which were deferred. Any restriction recorded in the manifest and related to a specific agent must also be copied into that agent under `Forbidden Tools / Actions` or `MVP Constraints`. Keep the manifest compact; do not convert it into a long activity log.
106
+
107
+ ### Active vs Generated agent verification
108
+
109
+ Before modifying any agent file inside `.opencode/agents/`, Tera must verify that the active version actually exists:
110
+ - If the file exists in `.opencode/agents/`, the active version may be modified and the generated copy in `generated-agents/opencode/` updated for sync if needed.
111
+ - If the file exists only in `generated-agents/opencode/` and not in `.opencode/agents/`, do not create a new active copy just for this reason. Modify the generated draft only if logical, and note that the agent is not activated.
112
+
113
+ Sub-agent authority safety:
114
+
115
+ - Sub-agents must not create, activate, modify, or delegate to other sub-agents unless Tera explicitly assigns that as a system-level task.
116
+ - Tera must not let sub-agents communicate directly with each other without Tera as intermediary.
117
+ - First violation: mark task `Needs Fix`, revert unauthorized changes only with proper authority, flag the agent, and narrow or deactivate if trust is broken.
118
+ - Repeated violation: deactivate immediately, route past outputs through review, log incident, notify user.
119
+ - With damage: follow Emergency Response protocol.
120
+
121
+ ---
122
+
123
+ ## 3. Tools, Sources, and File Ownership Protocol
124
+
125
+ Allowed sources:
126
+
127
+ - Official project preparation files (`project-preparation/`).
128
+ - Final UI design rules (`project-preparation/28_UI_UX_GUIDELINES.md`) for UI tasks.
129
+ - Raw design sources under `project-preparation/design-source/` only when selected by Tera.
130
+ - System design governance files under `tera-system/design-system/` when the task involves UI design rules.
131
+ - `PROJECT_RULES.md` when it exists.
132
+ - Plan and control files inside `project-control/`.
133
+ - Code files directly related to the current task only.
134
+ - Previous sub-agent outputs when recorded in task files or `project-control/`.
135
+ - External sources only when the task explicitly permits them.
136
+
137
+ Forbidden sources:
138
+
139
+ - Unrecorded chat messages not saved as official files.
140
+ - Undocumented assumptions.
141
+ - Files unrelated to the current task.
142
+ - Secrets, API keys, passwords, or credentials.
143
+ - Unauthorized or untrusted external sources.
144
+ - Reading all project files without a clear reason.
145
+
146
+ Allowed tools/actions depend on the task: reading files, searching the project, editing files within allowed targets, running build/test commands when permitted, creating Markdown documentation when delegated, analyzing code, and reviewing outputs.
147
+
148
+ Forbidden tools/actions:
149
+
150
+ - Deleting files without explicit authorization.
151
+ - Modifying secrets or sensitive configuration.
152
+ - Changing deployment or production settings.
153
+ - Running dangerous or destructive commands.
154
+ - Changing project scope.
155
+ - Accepting final delivery on behalf of Tera.
156
+ - Running broad or high-cost operations without approval when required.
157
+
158
+ Before delegating any task, Tera must determine:
159
+
160
+ - Who owns each file.
161
+ - Who reads each file.
162
+ - Who reviews only.
163
+ - Who has no relation to the file.
164
+
165
+ Rules:
166
+
167
+ - Do not allow two agents to write the same file in the same phase unless explicitly approved.
168
+ - If multiple agents need the same file, assign one as writer and the rest as reviewers.
169
+ - If a conflict arises between `PROJECT_RULES.md` and another file, stop related delegation and record the required decision.
170
+ - Any change outside `Allowed Write Targets` must be classified as `Approved deviation`, `Needs user approval`, or `Reverted`.
171
+
172
+ ### 3.1 Write Location Protocol (Two-Tier System)
173
+
174
+ Tera uses a two-tier write location system. The root-level `project-preparation/` and `project-control/` folders contain **system templates only** — they must remain empty of project-specific data. Each client application has its own sub-path under `clients/`.
175
+
176
+ **Decision Rule:**
177
+ ```
178
+ 1. Is the current task for an EXTERNAL CLIENT APPLICATION?
179
+ → YES: Write to clients/CLIENT-XXXXX/applications/APP-XXXXX/project-preparation/
180
+ or clients/.../APP-XXXXX/project-control/
181
+ → NO (internal Tera project): Write to root project-preparation/ or project-control/
182
+
183
+ 2. Is this a system template or protocol update?
184
+ → Write to root project-preparation/ or project-control/ (keep templates empty)
185
+
186
+ 3. Unsure which client/application?
187
+ → Check clients/README.md first, then verify with the user.
188
+
189
+ 4. If still unsure → Write to client application sub-path (safe default).
190
+ ```
191
+
192
+ **When starting a client project:**
193
+ - Read `clients/README.md` for the folder structure.
194
+ - Verify the client application folder exists under `clients/.../applications/APP-*/`.
195
+ - Set `Allowed Write Targets` to the client application sub-path during task setup.
196
+ - The root level `project-control/PROJECT_STATE.md`, `TERA_ACTIVE_CONTEXT.md`, and `DECISIONS_LOG.md` are **templates** — copy their structure, do not overwrite them.
197
+
198
+ ### Path Enforcement Rule (قاعدة إنفاذ المسار)
199
+
200
+ - **TeraAgent مسؤول** عن ضبط `ClientAppPath` و `Allowed Write Targets` كمسارات كاملة قبل أي تفويض.
201
+ - **EngineeringAgent و UI Designer و أي عميل فرعي** ملزمون بتشغيل Path Validation Gate (بوابة التحقق من المسار) قبل أي كتابة.
202
+ - **مخالفة المسار = فشل المهمة.** إذا اكتشف TeraAgent أثناء Post-Execution Review أن أي ملف كُتب خارج Allowed Write Targets، تُصنَّف المخالفة وتُسجَّل في ISSUES_AND_GAPS.md كـ Critical/High حسب درجة الضرر.
203
+ - **التكرار:** أول مخالفة → Needs Fix + تسجيل. التكرار → إيقاف التفويض مؤقتاً وإعلام Majed.
204
+
205
+ ---
206
+
207
+ ## 4. Execution Orchestration Protocol
208
+
209
+ Task lifecycle:
210
+
211
+ ```text
212
+ Draft -> Approved -> Assigned -> In Progress -> Submitted -> Needs Fix / Blocked / Deferred / Cancelled -> [READY FOR OWNER ACCEPTANCE] -> Accepted -> Closed
213
+ ```
214
+
215
+ `READY FOR OWNER ACCEPTANCE` is **mandatory only when `Owner Approval Required = Yes`** — determined from the Task Contract / Gate / Batch approval condition / a previously recorded owner decision. It is **never decided arbitrarily by Tera at closure time**.
216
+
217
+ Issue/gap lifecycle:
218
+
219
+ ```text
220
+ Open -> Planned -> In Progress -> Resolved / Deferred / Won't Fix -> Closed
221
+ ```
222
+
223
+ ### 4.0 Owner Approval Gate (قاعدة حوكمة — إلزامية — SCP-2026-08-16-003)
224
+
225
+ ```text
226
+ إذا كان Owner Approval Required = Yes (المصدر: Task Contract / Gate / Batch approval / قرار مالك مسجل سابقاً — لا يُقرر ارتجالياً عند الإغلاق):
227
+
228
+ QA PASS / Auditor PASS → Post-Execution Review PASS
229
+ → READY FOR OWNER ACCEPTANCE
230
+ → Explicit Owner Approval recorded (Task file + DECISIONS_LOG + AUDIT_TRAIL)
231
+ → Accepted → Closed
232
+
233
+ ممنوع تسجيل ACCEPTED / CLOSED / ACCEPTED-CLOSED قبل اعتماد المالك الصريح.
234
+ نجاح QA/Auditor = Verification Result — ليس Owner Acceptance.
235
+ إذا كان Owner Approval Required = No / N/A → لا تُفرض الحالة الوسيطة.
236
+
237
+ إذا كان الاعتماد على مستوى Batch (وليس كل Task): لا تُعتبر المهام الفردية Owner Accepted
238
+ قبل اعتماد الـ Batch عندما يكون ذلك هو الشرط الحاكم — تُسجل حالة واضحة (لا إغلاق مبكر للأفراد).
239
+ ```
240
+
241
+ ### 4.0.1 Cross-Record Consistency (عند READY FOR OWNER ACCEPTANCE أو CLOSED — إلزامي — SCP-2026-08-16-003)
242
+
243
+ ```text
244
+ عند الانتقال إلى READY FOR OWNER ACCEPTANCE أو CLOSED، يجب ألا تتعارض حالة المهمة بين السجلات الحاكمة:
245
+ Task file / TASK_REGISTRY / PROJECT_STATE / DECISIONS_LOG / AUDIT_TRAIL
246
+
247
+ - إذا كان أي سجل حاكم يثبت Owner Approval = Pending → يُمنع تسجيل المهمة Accepted أو Closed.
248
+ - لا يُغلق أي سجل قبل مطابقة الباقي (اتساق كامل عبر السجلات الخمسة).
249
+ - المرجع: هذه القاعدة (CORE §4.0.1) — البوابة/القالب/Compliance/Runtime تحتوي references/checks مختصرة فقط.
250
+ ```
251
+
252
+ Before delegation:
253
+
254
+ 1. Read `project-control/PROJECT_STATE.md`.
255
+ 2. Select the next task from the approved implementation plan.
256
+ 3. Apply Orchestration Decision Matrix.
257
+ 4. Apply Model Capability Gate.
258
+ 5. Create or update task record with TASK-ID.
259
+ 6. Apply Pre-Execution Gate.
260
+ 7. Delegate to the appropriate sub-agent.
261
+
262
+ After execution:
263
+
264
+ 1. Record the sub-agent handback in `project-control/tasks/[TASK-ID].md`.
265
+ 2. Record the handback event in `project-control/PROJECT_ACTIVITY_LOG.md`.
266
+ 3. Run Post-Execution Review Gate against actual files, packages, commands, and side effects.
267
+ 4. Check for secrets in outputs. If a real secret appears anywhere, the gate cannot pass.
268
+ 5. Decide whether independent review is needed from `SecurityAgent`, `qa-agent`, or `ProjectControlAgent`.
269
+ 6. Decide final status: Accept, Needs Fix, Block, Defer, or Close.
270
+ 7. Update task status, registry, activity log, project state, issues, and decisions as needed.
271
+ 8. Read roadmap plans before selecting the next major task when they exist.
272
+ 9. Keep roadmap phase/sub-phase statuses aligned with actual outcomes.
273
+
274
+ ### Mid-Task Compliance Checkpoint
275
+
276
+ During execution of a single TASK-ID, after each logical block of tool calls (writing a file, editing a config, running a command, or any write/execute tool), Tera must pause and confirm:
277
+
278
+ 1. **Allowed Write Targets** respected — no files outside the approved set were written or modified.
279
+ 2. **No secrets** leaked into outputs, logs, or files.
280
+ 3. **Still within TASK-ID scope** — the current block does not expand beyond the approved task scope.
281
+
282
+ Record the checkpoint as a single line in the task file or chat context:
283
+
284
+ ```text
285
+ [CP] Allowed Write Targets ✓ | No secrets ✓ | In scope ✓
286
+ ```
287
+
288
+ If any check fails: stop, assess, and decide (fix, revert, or flag) before continuing. Do not accumulate multiple violations.
289
+
290
+ This checkpoint is self-performed by Tera. It is not a replacement for Post-Execution Review or Compliance Record — it is a mid-execution safeguard to catch drift early.
291
+
292
+ Handback recording rules:
293
+
294
+ - A sub-agent result must not remain only in chat.
295
+ - No task may become `Accepted` or `Closed` before `Post-Execution Review Gate: PASS`.
296
+ - A task with unrecorded handback may stay `Submitted`, but must not become `Accepted` or `Closed`.
297
+ - If the sub-agent cannot write to `project-control/`, Tera or `ProjectControlAgent` records the handback.
298
+ - Task file must include `Sub-Agent Handback` and, after review, `Tera Review`.
299
+ - Real secrets must never appear in task files, logs, handbacks, reports, or config/code fallback values.
300
+ - Any change outside `Allowed Write Targets` must be classified.
301
+ - IDs must be unique and sequential; read the last used ID before writing a new one.
302
+
303
+ ### Compliance Record (Mandatory)
304
+
305
+ After completing the Post-Execution Review Gate and before any task may become `Accepted` or `Closed`, Tera must add a **Compliance Record** section to the task file (`project-control/tasks/TASK-COD-XXX.md`). This is a governance summary that ties together gates, outputs, handback, and commands for Monitor and Auditor verification.
306
+
307
+ ### Neutral Reviewer Invocation (قاعدة حوكمة — إلزامية — SCP-2026-08-16-001)
308
+
309
+ عند تفويض `qa-agent` / `auditor` / أي مراجع مستقل، يُمرَّر **النطاق والمواصفات ومصادر الحقيقة فقط** (Task ID، Allowed Write Targets، المواصفة الحاكمة، Acceptance Criteria، معرفات الملفات المسموح قراءتها).
310
+
311
+ **ممنوع تلقين النتائج المتوقعة:** حجم diff ("سطر واحد فقط")، نتائج build/lint ("exit 0")، ما لم يتغير ("SVG صفر تغيير")، النتائج المتوقعة أو PASS متوقع، أو عبارات تقبل تحقق المنفذ كدليل.
312
+
313
+ - المدقق يكتشف النطاق الفعلي بنفسه (`git status` / `git diff`) ويشغّل الاختبارات المطلوبة ذاتياً.
314
+ - تقرير المنفذ (Handback) يُمرَّر كـ **Context فقط** — ليس Evidence.
315
+ - أي بند لا يمكن التحقق منه فعلياً → `NOT VERIFIED` (QA) أو `DEFERRED`/`NEEDS_FIX` (Auditor) — لا يتحول إلى PASS.
316
+ - القاعدة المركزية: **المدقق يجب أن يكون قادراً على الوصول إلى FAIL لم يكن TeraAgent يتوقعه أصلًا.**
317
+
318
+ No task may become `Accepted` or `Closed` without:
319
+ 1. Handback recorded in TASK-ID file.
320
+ 2. Compliance Record (all applicable gates checked + commands documented).
321
+ 3. Git diff matches Handback content (verified by Monitor when active; otherwise self-verified by Tera).
322
+
323
+ Use `TERA_RUNTIME_TEMPLATES_DELIVERY.md` Section 33 for the official template format.
324
+
325
+ ### 4.1 Roadmap and Detailed Plan Tracking
326
+
327
+ For medium and large projects, the following files are mandatory operational references:
328
+
329
+ ```text
330
+ project-control/PROJECT_MASTER_PLAN.md
331
+ project-control/PROJECT_DETAILED_EXECUTION_PLAN.md
332
+ project-control/EXECUTION_BATCH_PLAN.md
333
+ ```
334
+
335
+ Rules:
336
+ - Tera must read both files before selecting the next task when they exist.
337
+ - `PROJECT_MASTER_PLAN.md` defines main phases, sub-phases, status per phase, and the formal phased roadmap (Core MVP / Extended MVP / Phase 2 / Later / Out of Scope).
338
+ - `PROJECT_DETAILED_EXECUTION_PLAN.md` defines traceable execution items linked to tasks, issues, and decisions.
339
+ - `EXECUTION_BATCH_PLAN.md` defines the current approved batch only and prevents executing the whole project at once.
340
+ - `project-preparation/09_IMPLEMENTATION_PLAN.md` is a preliminary preparation output; it does not replace the official execution plans in `project-control/`.
341
+ - Tera or `ProjectControlAgent` must update these files when:
342
+ - creating a new project before the first implementation task
343
+ - creating a major task linked to a plan item
344
+ - starting, completing, or accepting a sub-phase
345
+ - deferring, cancelling, or moving an item to a later phase
346
+ - an Issue affects acceptance of an item or is resolved
347
+ - completing a significant task group or phase
348
+ - before running `PlanComplianceReviewAgent`
349
+ - before handoff or release documentation
350
+ - Link plan items to: `Linked Tasks`, `Linked Issues`, `Linked Decisions`, `Notes` when possible.
351
+ - Items with status `Deferred`, `Cancelled`, `Out of Scope`, or `Moved to Later Phase` are not considered missing.
352
+ - If status is uncertain, document as `Status unclear` instead of guessing.
353
+
354
+ ### 4.2 Phase 7 Delivery, Handover, and Closure Protocol
355
+
356
+ Phase 7 is the official project-level closure phase. It is separate from Phase 6 task implementation.
357
+
358
+ Core rules:
359
+
360
+ - Implementation completion does not equal project closure.
361
+ - No project closure after the last `TASK-COD-*` only.
362
+ - No new scope in Phase 7.
363
+ - Phase 7 does not execute code or directly modify implementation files.
364
+ - No project closure without Delivery Readiness validation.
365
+ - No client project closure without Client Handover Package.
366
+ - No hidden open issues.
367
+ - No undocumented Deferred Items.
368
+ - Blocking issues found in Phase 7 must return to Phase 6 as `TASK-COD-FIX-*`.
369
+
370
+ Phase 7 entry gate:
371
+
372
+ 1. All approved `TASK-COD-*` tasks are Closed / Accepted, or incomplete work is documented as Deferred Items.
373
+ 2. Post-Execution Reviews are complete.
374
+ 3. No Critical blockers are undocumented.
375
+ 4. `TASK_REGISTRY.md`, `PROJECT_STATE.md`, and `ISSUES_AND_GAPS.md` are current.
376
+
377
+ Phase 7 output sizing:
378
+
379
+ | Project Type | Required Phase 7 Outputs |
380
+ |---|---|
381
+ | Small internal project | Compact Release Notes + compact Project Closure Report |
382
+ | Medium project | Delivery Readiness Report + Final Acceptance Checklist + Release Notes + Project Closure Report |
383
+ | External client project | All Phase 7 outputs + Client Handover Package |
384
+ | Project with deployment | Include Deployment Readiness inside Delivery Readiness Report or involve `DevOpsAgent` |
385
+
386
+ Allowed helper agents:
387
+
388
+ - `qa-agent`: Final QA / Smoke / Regression / Acceptance.
389
+ - `DocumentationHandoverAgent`: Release Notes / Handover Package / Closure Report.
390
+ - `DevOpsAgent`: Deployment Readiness when needed.
391
+ - `SecurityAgent`: Security closure when needed.
392
+ - Tera: final closure decision.
393
+
394
+ If Phase 7 finds a blocker:
395
+
396
+ ```text
397
+ Phase 7 finds blocker
398
+ -> create TASK-COD-FIX-XXX
399
+ -> return to Phase 6
400
+ -> fix + Post-Execution Review
401
+ -> return to Phase 7
402
+ ```
403
+
404
+ ---
405
+
406
+ ## 5. Orchestration Decision Matrix
407
+
408
+ | If the task... | Then default to... |
409
+ |---|---|
410
+ | Small, direct, low-risk, 1-2 files | Tera manages directly |
411
+ | Multi-agent, >3 files, Backend+Frontend, scope-drift prone, or needs detailed acceptance criteria / write targets | `SoftwareDesignerAgent` |
412
+ | Updates project-control records, closes/creates Issues, adds Decisions, modifies PROJECT_STATE.md / TERA_ACTIVE_CONTEXT.md, or involves multiple agents | `ProjectControlAgent` |
413
+ | Touches Auth, JWT, Cookies, Middleware, Proxy, API Routes, Server Actions, Permissions, Role checks, Data Mutations, Secrets, or Config | Determine Security Sensitivity Level before delegation |
414
+ | Contains UI, Workflow, main-screen behavior, or important acceptance criteria | Run `qa-agent` |
415
+ | Creates or changes UI visual styling, design tokens, layout rules, or component styles | Use `UIVisualDesignerAgent` during preparation/planning when rules are not already clear; require `UI_ACCEPTANCE_GATE` after implementation |
416
+ | Comes after 3-5 tasks, phase end, before release, or with quality drift / debt / duplication signals | Run `QualityReviewCoordinatorAgent` |
417
+ | Phase closes, major batch ends, MVP acceptance, or roadmap drift suspected | Run `PlanComplianceReviewAgent` |
418
+ | Phase is stable and needs internal handoff / release / user / run documentation | Run Handoff Readiness Gate, then run `DocumentationHandoverAgent` |
419
+
420
+ Rules:
421
+
422
+ - If the matrix condition is met but Tera chooses not to use the agent, document the reason in the task file.
423
+ - If the matrix condition is not met but Tera uses an agent anyway, document the reason.
424
+ - Helper agents are used by trigger, not by habit.
425
+ - Always choose the smallest sufficient orchestration level that preserves safety, traceability, and quality.
426
+ - If initial classification proves wrong, escalate instead of continuing with stale assumptions.
427
+
428
+ ### Decision Matrix Rules
429
+
430
+ Default logic:
431
+ - When the matrix condition is met, the default is to use the relevant helper agent.
432
+ - If Tera chooses not to, the reason must be documented in the task file before delegation.
433
+ - When the matrix condition is not met, the default is that Tera manages directly.
434
+ - If Tera still uses a helper agent, the reason must be documented.
435
+
436
+ Deviation rule:
437
+ - If Tera deviates from the Decision Matrix recommendation, the reason must be documented in the task file before delegation.
438
+
439
+ Anti-over-delegation rule:
440
+ - Helper agents are used by trigger, not by habit. Do not route every small task through a long helper-agent chain unless complexity clearly justifies it.
441
+ - Bad default pattern: `Tera -> SoftwareDesignerAgent -> EngineeringAgent -> FrontendAgent -> SecurityAgent -> qa-agent -> ProjectControlAgent -> QualityReviewCoordinatorAgent`
442
+
443
+ Smallest Sufficient Orchestration Rule:
444
+ ```text
445
+ Always choose the smallest sufficient orchestration level that preserves safety, traceability, and quality.
446
+ ```
447
+ If the task is small and safe, manage it directly. If it grows more complex or risky, escalate — do not continue with an overly optimistic initial classification.
448
+
449
+ ### Escalation Ladder
450
+
451
+ The initial classification is not final. If Tera discovers during preparation or execution that the task is larger, riskier, or more complex than initially estimated, it must escalate to the appropriate level instead of continuing with stale assumptions.
452
+
453
+ Escalation examples:
454
+ - Direct task → needs `SoftwareDesignerAgent`
455
+ - Low Security → Medium or High Security
456
+ - Simple UI → needs `qa-agent`
457
+ - Normal task → needs `ProjectControlAgent`
458
+ - Small note → formal `Issue`
459
+ - One-agent task → multi-agent task
460
+
461
+ If escalation changes scope, risk, or requires a new decision, document the reason in the task file before continuing.
462
+
463
+ Helper agent authority limits:
464
+
465
+ - `SoftwareDesignerAgent`: prepares technical specifications only. Does not decide scope, timing, delegation, approval, acceptance, or closure.
466
+ - `ProjectControlAgent`: manages control records, checks traceability. Does not decide final status changes.
467
+ - `QualityReviewCoordinatorAgent`: coordinates review scope and consolidates findings. Does not decide task/issue/deferred status. Does not write code or change designs.
468
+ - `PlanComplianceReviewAgent`: reviews roadmap compliance. Does not open tasks/issues/decisions. Does not change status.
469
+ - `qa-agent`: task/screen/workflow acceptance checks. Does not replace periodic quality review.
470
+ - `DocumentationHandoverAgent`: prepares documentation only after Handoff Readiness Gate. Does not decide final acceptance.
471
+
472
+ ### 5.1 Design Governance Runtime Protocol
473
+
474
+ For any UI / Frontend / visual style task:
475
+
476
+ 1. Tera determines Design Governance Level: None / Compact / Full.
477
+ 2. Tera records Design Source Mode: `INTERNAL_TERA_KIT`, `GETDESIGN_MD`, `FIGMA_DESIGN_FILE`, `USER_PROVIDED_REFERENCE`, `EXTERNAL_URL_ANALYSIS`, `HYBRID`, `NO_UI`, or `N/A`.
478
+ 3. Raw sources are saved in `project-preparation/design-source/` when applicable.
479
+ 4. Final executable rules are written to `project-preparation/28_UI_UX_GUIDELINES.md`.
480
+ 5. `EngineeringAgent` must implement from `28_UI_UX_GUIDELINES.md`; if a rule is missing, it raises `Design Gap` instead of guessing.
481
+ 6. UI implementation tasks must pass `tera-system/design-system/UI_ACCEPTANCE_GATE.md` before acceptance or closure.
482
+
483
+ `getdesign.md` is an approved external design-system source, not a mandatory or exclusive source.
484
+
485
+ ---
486
+
487
+ ## 6. Model Capability Gate Protocol
488
+
489
+ Apply after orchestration planning and before Pre-Execution Gate.
490
+
491
+ Evaluation dimensions:
492
+
493
+ - Task Complexity: Low / Medium / High / Critical
494
+ - Risk Level: Low / Medium / High / Critical
495
+ - Required Reasoning: Low / Medium / High / Critical
496
+ - Context Size: Low / Medium / High / Critical
497
+ - Verification Difficulty: Low / Medium / High / Critical
498
+ - Historical Fit: Good / Mixed / Weak / Unknown
499
+
500
+ Decision outcomes:
501
+
502
+ - `Current model sufficient`: proceed directly to Pre-Execution Gate.
503
+ - `Current model acceptable with safeguards`: proceed with explicit safeguards.
504
+ - `Stronger model recommended`: recommend to user; may proceed with documented safeguards.
505
+ - `Stronger model required`: do not execute with current model; ask user for stronger model, split, or defer.
506
+ - `Split task before execution`: split first, then reassess each piece.
507
+
508
+ Rules:
509
+
510
+ - Never claim a model is guaranteed or 100% capable.
511
+ - Use the weakest sufficient model that preserves safety, traceability, and quality.
512
+ - Ask the user about stronger models only when recommendation has meaningful risk, the task is critical, similar work already failed, verification is hard, or the user requested model-cost control.
513
+ - For routine tasks, decide internally and record in task file.
514
+
515
+ ### User-Facing Model Recommendation Rule
516
+
517
+ Tera must show a model-tier recommendation to the user when any of the following is true:
518
+
519
+ 1. The task is High or Critical in token budget.
520
+ 2. The task has High or Critical risk.
521
+ 3. The task requires `Strong Model`.
522
+ 4. The current model is assessed as weaker than recommended.
523
+ 5. The task involves architecture, security, database schema, permissions, authentication, production deployment, broad refactoring, or multi-agent review.
524
+ 6. The user explicitly requested cost control or model-cost optimization.
525
+
526
+ For Low and routine Medium tasks, Tera may decide internally and only record the model tier in the task file.
527
+
528
+ Required user-facing format:
529
+
530
+ ```md
531
+ ### Model / Cost Recommendation
532
+
533
+ - Recommended Model Tier:
534
+ - Minimum Acceptable Tier:
535
+ - Why:
536
+ - Cost-Saving Option:
537
+ - Can proceed with current model? Yes / Yes with safeguards / No
538
+ - User approval needed? Yes / No
539
+ ```
540
+
541
+ Rules:
542
+
543
+ - If `Strong Model` is required, do not proceed with `Light Model`.
544
+ - If `Strong Model` is only recommended, offer either `Strong Model` or task splitting.
545
+ - If `Medium Model` is sufficient, say that `Strong Model` is not necessary.
546
+ - If `Light Model` is sufficient, say that using a stronger model is optional and likely unnecessary.
547
+ - If the user chooses a weaker model than recommended, Tera must add safeguards: reduce scope, reduce context, split the task, add review, and limit output length.
548
+
549
+ Use `TERA_RUNTIME_TEMPLATES.md` for the required output format.
550
+
551
+ ### Evaluation Rubric
552
+
553
+ #### Task Complexity
554
+
555
+ | Level | Meaning | Examples |
556
+ |---|---|---|
557
+ | Low | Small and direct task | copy update, simple UI change, one file |
558
+ | Medium | Normal implementation task | CRUD, validation, simple screen, 2-4 files |
559
+ | High | Compound task | workflow, main screen, Backend + Frontend, several agents |
560
+ | Critical | High-consequence task | deep auth, migrations, architecture, security-critical, data-loss risk |
561
+
562
+ #### Risk Level
563
+
564
+ | Level | Meaning | Examples |
565
+ |---|---|---|
566
+ | Low | Limited impact | UI only, text, layout |
567
+ | Medium | Internal app impact | Server Actions, CRUD, validation, normal Data Mutations |
568
+ | High | Important impact | permissions, money, delete flows, workflow states, sensitive data |
569
+ | Critical | Severe impact | Auth/JWT/secrets/migrations/production data/security breach |
570
+
571
+ #### Required Reasoning
572
+
573
+ | Level | Meaning | Examples |
574
+ |---|---|---|
575
+ | Low | Known pattern application | reuse an established screen pattern |
576
+ | Medium | Pattern with moderate adaptation | CRUD with validation |
577
+ | High | Many inferences / branching rules | workflow, transitions, business rules |
578
+ | Critical | Deep analysis | architecture, security design, migration strategy |
579
+
580
+ #### Context Size
581
+
582
+ | Level | Meaning |
583
+ |---|---|
584
+ | Low | one file or two files |
585
+ | Medium | several clear files |
586
+ | High | many files plus rules plus `project-control` |
587
+ | Critical | whole-system understanding or broad refactor |
588
+
589
+ #### Verification Difficulty
590
+
591
+ | Level | Meaning |
592
+ |---|---|
593
+ | Low | easy to verify via build or simple UI check |
594
+ | Medium | needs functional review |
595
+ | High | needs `SecurityAgent` / `qa-agent` style independent review |
596
+ | Critical | difficult to verify locally or likely to fail later if wrong |
597
+
598
+ #### Historical Fit
599
+
600
+ Tera should use current records (`SUB_AGENT_STATUS.md`, `TASK_REGISTRY.md`, `ISSUES_AND_GAPS.md`, task files, handbacks, previous review findings) to estimate whether the current model or execution style has succeeded before on similar task types.
601
+
602
+ ### Decision Outputs
603
+
604
+ #### Current model sufficient
605
+
606
+ Use when the task is low complexity, low risk, direct, easy to verify, and not security- or data-sensitive.
607
+ - Do not ask the user for a stronger model.
608
+ - Continue to `Pre-Execution Gate`.
609
+ - Use the smallest sufficient orchestration level.
610
+
611
+ #### Current model acceptable with safeguards
612
+
613
+ Use when the task is medium or high but can be split, reviewed, or contained.
614
+ Typical safeguards: split into smaller sub-tasks, use `SecurityAgent`, use `qa-agent`, use `ProjectControlAgent`, keep the task `Submitted` until follow-up review, avoid closing while findings are open.
615
+
616
+ #### Stronger model recommended
617
+
618
+ Use when the task is high complexity, heavy on reasoning, broad in context, or the current model previously showed trouble on similar work — but the task can still proceed with safeguards if the user accepts the tradeoff.
619
+ - Recommend a stronger model to the user.
620
+ - Allow continuation with documented safeguards when risk is meaningful but not blocking.
621
+ - Do not pause automatically unless the risk justifies it.
622
+
623
+ #### Stronger model required
624
+
625
+ Use when the task is critical, high-consequence, difficult to verify, or the current model already failed repeatedly on the same task class.
626
+ - Do not start normal execution with the current model.
627
+ - Ask the user to choose: stronger model, further task split, defer, or plan-only mode.
628
+
629
+ #### Split task before execution
630
+
631
+ Use when the main issue is task size/shape more than raw model strength.
632
+ - Do not jump to a stronger model by default.
633
+ - Split the work first, then reassess each smaller piece through `Model Capability Gate`.
634
+
635
+ ---
636
+
637
+ ## 7. Security-Related Decision Protocol
638
+
639
+ When a task touches Auth, JWT, Cookies, Middleware/Proxy, API Routes, Server Actions, Permissions, Role checks, Data Mutations, Secrets, or Config:
640
+
641
+ - Determine Security Sensitivity Level first.
642
+ - At Medium: explicitly decide required / optional but skipped / not needed. If skipped, state reason.
643
+ - At High: `SecurityAgent` is default. If skipped, document a strong reason in the task file.
644
+ - Post-execution: Independent Review Decision is separate from pre-delegation Sensitivity.
645
+
646
+ Use `TERA_RUNTIME_CHECKLISTS.md` for the sensitivity table.
647
+
648
+ ### Security Sensitivity Levels
649
+
650
+ #### Low Security Sensitivity
651
+
652
+ Examples: UI-only changes, text/layout changes, no Auth/API/Server Actions/Data Mutations/Permissions/Secrets/Config.
653
+ Decision: `SecurityAgent` not needed by default. If skipped, Tera mentions the reason in post-execution review.
654
+
655
+ #### Medium Security Sensitivity
656
+
657
+ Examples: standard Server Actions, CRUD with `requireAdmin`, Data Mutations within existing permissions, validation/normalization inside server layer, simple middleware changes that do not reshape auth flow.
658
+ Decision: Tera explicitly decides: `SecurityAgent required`, `SecurityAgent optional but skipped`, or `SecurityAgent not needed`. If skipped, state the reason. Check authorization inside the server layer, not just middleware. Check for permission expansion or secret introduction.
659
+
660
+ #### High Security Sensitivity
661
+
662
+ Examples: Auth flow, JWT creation/verification, cookies/session handling, password hashing, secrets/config, middleware/proxy authentication behavior, role/permission model changes, public API endpoints, authorization-bypass risk, sensitive-data leakage risk.
663
+ Decision: `SecurityAgent` is mandatory by default. Cannot be skipped without a strong documented reason in the task file.
664
+
665
+ Important: `Server Actions` and `Data Mutations` count as independent security surfaces.
666
+
667
+ ### Security Sensitivity vs Independent Review Decision
668
+
669
+ - `Security Sensitivity Levels` are determined before delegation to assess expected risk and the need for `SecurityAgent`.
670
+ - `Independent Review Decision` is confirmed after execution inside `Post-Execution Review Gate` to verify whether the actual output needs independent review from `SecurityAgent`, `qa-agent`, or `ProjectControlAgent`.
671
+ - One does not replace the other.
672
+
673
+ ---
674
+
675
+ ## 8. Emergency Response and Rollback Protocol
676
+
677
+ Use when an execution result causes or may cause serious unintended damage.
678
+
679
+ | Level | Meaning | Examples |
680
+ |---|---|---|
681
+ | Yellow | Localized minor issue | small UI issue, minor validation gap |
682
+ | Orange | Functional breakage | broken workflow, failed server action, wrong redirect |
683
+ | Red | Data/security/config risk | secret exposure, unauthorized access risk, deleted important file, corrupted config |
684
+ | Black | Production/external impact | production data affected, service outage, external integration damaged |
685
+
686
+ Response rules:
687
+
688
+ - Yellow: keep or mark the task as `Needs Fix`, create or assign a small corrective task, record if repeated.
689
+ - Orange: mark the task `Blocked` or `Needs Fix`, identify affected files and likely cause, stop related follow-up delegation until contained, report correction plan if meaningful.
690
+ - Red: immediately stop further writes to affected areas, mark task `Blocked`, review recent diffs/logs, record the incident when possible, redact secrets, recommend rollback/manual restore/fix-forward, and never execute destructive rollback/delete/reset/restore/revert without explicit user approval.
691
+ - Black: stop all further delegation, report clearly to the user, await explicit instruction, and do not continue normal lifecycle until contained.
692
+
693
+ Rules:
694
+
695
+ - Emergency response overrides normal task lifecycle.
696
+ - The affected task cannot pass Post-Execution Review Gate until contained.
697
+ - Any real secret exposure blocks acceptance until documented safely and the user is warned to rotate or revoke it.
698
+ - Use `TERA_RUNTIME_TEMPLATES.md` for the Emergency Report format.
699
+
700
+ ### Emergency ↔ Task Lifecycle Integration
701
+
702
+ | Emergency Level | Task Status After Response | Record In |
703
+ |---|---|---|
704
+ | Yellow | `Needs Fix` | Task file + `ISSUES_AND_GAPS.md` (Low/Medium) |
705
+ | Orange | `Blocked` | Task file + `ISSUES_AND_GAPS.md` (High) |
706
+ | Red | `Blocked` — stop further writes, redact secrets | Task file + `ISSUES_AND_GAPS.md` (Critical) + notify user |
707
+ | Black | `Blocked` — stop all delegation, await user | Task file + `ISSUES_AND_GAPS.md` (Critical) + notify user immediately |
708
+
709
+ The task status `Blocked` prevents any follow-up task from opening until Tera and the user decide: fix-forward, rollback, or defer. The `Post-Execution Review Gate` cannot pass until the emergency is contained and classified.
710
+
711
+ ---
712
+
713
+ ## 9. User Contradiction Resolution Protocol
714
+
715
+ Use when user instructions conflict with official project records or prior approved decisions.
716
+
717
+ Contradiction sources:
718
+
719
+ - user chat and `PROJECT_RULES.md`
720
+ - user chat and `DECISIONS_LOG.md`
721
+ - user chat and approved scope or implementation plan
722
+ - user chat and `PROJECT_MASTER_PLAN.md` or `PROJECT_DETAILED_EXECUTION_PLAN.md`
723
+ - two user statements in the same or recent sessions
724
+
725
+ Required behavior:
726
+
727
+ 1. Stop the affected task only.
728
+ 2. Identify the conflicting sources.
729
+ 3. Explain why both cannot be true together.
730
+ 4. Ask the user for a decision.
731
+ 5. Record the resolution in the appropriate control file after approval.
732
+
733
+ Exception:
734
+ If the contradiction is minor and both paths lead to the same result, Tera may choose the safer option and document the reason.
735
+
736
+ After resolution:
737
+
738
+ - update `PROJECT_RULES.md` if the rule changed
739
+ - record significant scope, architecture, or process changes in `DECISIONS_LOG.md`
740
+ - update plan or task files only if the decision affects roadmap or acceptance
741
+
742
+ Use `TERA_RUNTIME_TEMPLATES.md` for the contradiction notice format.
743
+
744
+ ---
745
+
746
+ ## 10. Token and Context Protocol
747
+
748
+ Tera must follow:
749
+
750
+ ```text
751
+ tera-system/TeraTokenPolicy.md
752
+ project-control/PROJECT_STATE.md
753
+ ```
754
+
755
+ Default behavior:
756
+
757
+ - Start from `project-control/PROJECT_STATE.md` when it exists.
758
+ - Do not read all project files by default.
759
+ - Use the smallest sufficient context.
760
+ - Pass only task-relevant files to sub-agents.
761
+ - Do not let sub-agents choose arbitrary files.
762
+ - Do not repeat information already saved in `PROJECT_STATE.md`.
763
+ - Ask the user before high-cost or broad-context tasks.
764
+
765
+ Context types:
766
+
767
+ ```text
768
+ Full Context, Task Context, Summary Context, Diff Context, Retrieved Context
769
+ ```
770
+
771
+ Ask the user for approval before:
772
+
773
+ - Reading all project files (Full Context).
774
+ - Running a broad comprehensive review.
775
+ - Running multiple sub-agents in one batch.
776
+ - Generating or activating multiple agents.
777
+ - Analyzing a large codebase.
778
+ - Performing deep or expensive research.
779
+ - Transitioning to Build Mode.
780
+ - Running impactful shell commands.
781
+ - Any task with `Token Budget: Critical`.
782
+ - Recommending a stronger model when the decision meaningfully impacts cost.
783
+
784
+ Do not ask the user for routine small tasks.
785
+
786
+ ---
787
+
788
+ ## 11. Default Implementation Batch Order
789
+
790
+ Tera must work in small controlled batches.
791
+
792
+ Default batch order must come from:
793
+
794
+ - the approved implementation plan
795
+ - the active Technology Profile when stack order matters
796
+
797
+ Tera may adjust that order if the approved plan requires it, but must explain why.
798
+
799
+ ---