@nomos-arc/arc 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 (160) hide show
  1. package/.claude/settings.local.json +10 -0
  2. package/.nomos-config.json +5 -0
  3. package/CLAUDE.md +108 -0
  4. package/LICENSE +190 -0
  5. package/README.md +569 -0
  6. package/dist/cli.js +21120 -0
  7. package/docs/auth/googel_plan.yaml +1093 -0
  8. package/docs/auth/google_task.md +235 -0
  9. package/docs/auth/hardened_blueprint.yaml +1658 -0
  10. package/docs/auth/red_team_report.yaml +336 -0
  11. package/docs/auth/session_state.yaml +162 -0
  12. package/docs/certificate/cer_enhance_plan.md +605 -0
  13. package/docs/certificate/certificate_report.md +338 -0
  14. package/docs/dev_overview.md +419 -0
  15. package/docs/feature_assessment.md +156 -0
  16. package/docs/how_it_works.md +78 -0
  17. package/docs/infrastructure/map.md +867 -0
  18. package/docs/init/master_plan.md +3581 -0
  19. package/docs/init/red_team_report.md +215 -0
  20. package/docs/init/report_phase_1a.md +304 -0
  21. package/docs/integrity-gate/enhance_drift.md +703 -0
  22. package/docs/integrity-gate/overview.md +108 -0
  23. package/docs/management/manger-task.md +99 -0
  24. package/docs/management/scafffold.md +76 -0
  25. package/docs/map/ATOMIC_BLUEPRINT.md +1349 -0
  26. package/docs/map/RED_TEAM_REPORT.md +159 -0
  27. package/docs/map/map_task.md +147 -0
  28. package/docs/map/semantic_graph_task.md +792 -0
  29. package/docs/map/semantic_master_plan.md +705 -0
  30. package/docs/phase7/TEAM_RED.md +249 -0
  31. package/docs/phase7/plan.md +1682 -0
  32. package/docs/phase7/task.md +275 -0
  33. package/docs/prompts/USAGE.md +312 -0
  34. package/docs/prompts/architect.md +165 -0
  35. package/docs/prompts/executer.md +190 -0
  36. package/docs/prompts/hardener.md +190 -0
  37. package/docs/prompts/red_team.md +146 -0
  38. package/docs/verification/goveranance-overview.md +396 -0
  39. package/docs/verification/governance-overview.md +245 -0
  40. package/docs/verification/verification-arc-ar.md +560 -0
  41. package/docs/verification/verification-architecture.md +560 -0
  42. package/docs/very_next.md +52 -0
  43. package/docs/whitepaper.md +89 -0
  44. package/overview.md +1469 -0
  45. package/package.json +63 -0
  46. package/src/adapters/__tests__/git.test.ts +296 -0
  47. package/src/adapters/__tests__/stdio.test.ts +70 -0
  48. package/src/adapters/git.ts +226 -0
  49. package/src/adapters/pty.ts +159 -0
  50. package/src/adapters/stdio.ts +113 -0
  51. package/src/cli.ts +83 -0
  52. package/src/commands/apply.ts +47 -0
  53. package/src/commands/auth.ts +301 -0
  54. package/src/commands/certificate.ts +89 -0
  55. package/src/commands/discard.ts +24 -0
  56. package/src/commands/drift.ts +116 -0
  57. package/src/commands/index.ts +78 -0
  58. package/src/commands/init.ts +121 -0
  59. package/src/commands/list.ts +75 -0
  60. package/src/commands/map.ts +55 -0
  61. package/src/commands/plan.ts +30 -0
  62. package/src/commands/review.ts +58 -0
  63. package/src/commands/run.ts +63 -0
  64. package/src/commands/search.ts +147 -0
  65. package/src/commands/show.ts +63 -0
  66. package/src/commands/status.ts +59 -0
  67. package/src/core/__tests__/budget.test.ts +213 -0
  68. package/src/core/__tests__/certificate.test.ts +385 -0
  69. package/src/core/__tests__/config.test.ts +191 -0
  70. package/src/core/__tests__/preflight.test.ts +24 -0
  71. package/src/core/__tests__/prompt.test.ts +358 -0
  72. package/src/core/__tests__/review.test.ts +161 -0
  73. package/src/core/__tests__/state.test.ts +362 -0
  74. package/src/core/auth/__tests__/manager.test.ts +166 -0
  75. package/src/core/auth/__tests__/server.test.ts +220 -0
  76. package/src/core/auth/gcp-projects.ts +160 -0
  77. package/src/core/auth/manager.ts +114 -0
  78. package/src/core/auth/server.ts +141 -0
  79. package/src/core/budget.ts +119 -0
  80. package/src/core/certificate.ts +502 -0
  81. package/src/core/config.ts +212 -0
  82. package/src/core/errors.ts +54 -0
  83. package/src/core/factory.ts +49 -0
  84. package/src/core/graph/__tests__/builder.test.ts +272 -0
  85. package/src/core/graph/__tests__/contract-writer.test.ts +175 -0
  86. package/src/core/graph/__tests__/enricher.test.ts +299 -0
  87. package/src/core/graph/__tests__/parser.test.ts +200 -0
  88. package/src/core/graph/__tests__/pipeline.test.ts +202 -0
  89. package/src/core/graph/__tests__/renderer.test.ts +128 -0
  90. package/src/core/graph/__tests__/resolver.test.ts +185 -0
  91. package/src/core/graph/__tests__/scanner.test.ts +231 -0
  92. package/src/core/graph/__tests__/show.test.ts +134 -0
  93. package/src/core/graph/builder.ts +303 -0
  94. package/src/core/graph/constraints.ts +94 -0
  95. package/src/core/graph/contract-writer.ts +93 -0
  96. package/src/core/graph/drift/__tests__/classifier.test.ts +215 -0
  97. package/src/core/graph/drift/__tests__/comparator.test.ts +335 -0
  98. package/src/core/graph/drift/__tests__/drift.test.ts +453 -0
  99. package/src/core/graph/drift/__tests__/reporter.test.ts +203 -0
  100. package/src/core/graph/drift/classifier.ts +165 -0
  101. package/src/core/graph/drift/comparator.ts +205 -0
  102. package/src/core/graph/drift/reporter.ts +77 -0
  103. package/src/core/graph/enricher.ts +251 -0
  104. package/src/core/graph/grammar-paths.ts +30 -0
  105. package/src/core/graph/html-template.ts +493 -0
  106. package/src/core/graph/map-schema.ts +137 -0
  107. package/src/core/graph/parser.ts +336 -0
  108. package/src/core/graph/pipeline.ts +209 -0
  109. package/src/core/graph/renderer.ts +92 -0
  110. package/src/core/graph/resolver.ts +195 -0
  111. package/src/core/graph/scanner.ts +145 -0
  112. package/src/core/logger.ts +46 -0
  113. package/src/core/orchestrator.ts +792 -0
  114. package/src/core/plan-file-manager.ts +66 -0
  115. package/src/core/preflight.ts +64 -0
  116. package/src/core/prompt.ts +173 -0
  117. package/src/core/review.ts +95 -0
  118. package/src/core/state.ts +294 -0
  119. package/src/core/worktree-coordinator.ts +77 -0
  120. package/src/search/__tests__/chunk-extractor.test.ts +339 -0
  121. package/src/search/__tests__/embedder-auth.test.ts +124 -0
  122. package/src/search/__tests__/embedder.test.ts +267 -0
  123. package/src/search/__tests__/graph-enricher.test.ts +178 -0
  124. package/src/search/__tests__/indexer.test.ts +518 -0
  125. package/src/search/__tests__/integration.test.ts +649 -0
  126. package/src/search/__tests__/query-engine.test.ts +334 -0
  127. package/src/search/__tests__/similarity.test.ts +78 -0
  128. package/src/search/__tests__/vector-store.test.ts +281 -0
  129. package/src/search/chunk-extractor.ts +167 -0
  130. package/src/search/embedder.ts +209 -0
  131. package/src/search/graph-enricher.ts +95 -0
  132. package/src/search/indexer.ts +483 -0
  133. package/src/search/lexical-searcher.ts +190 -0
  134. package/src/search/query-engine.ts +225 -0
  135. package/src/search/vector-store.ts +311 -0
  136. package/src/types/index.ts +572 -0
  137. package/src/utils/__tests__/ansi.test.ts +54 -0
  138. package/src/utils/__tests__/frontmatter.test.ts +79 -0
  139. package/src/utils/__tests__/sanitize.test.ts +229 -0
  140. package/src/utils/ansi.ts +19 -0
  141. package/src/utils/context.ts +44 -0
  142. package/src/utils/frontmatter.ts +27 -0
  143. package/src/utils/sanitize.ts +78 -0
  144. package/test/e2e/lifecycle.test.ts +330 -0
  145. package/test/fixtures/mock-planner-hang.ts +5 -0
  146. package/test/fixtures/mock-planner.ts +26 -0
  147. package/test/fixtures/mock-reviewer-bad.ts +8 -0
  148. package/test/fixtures/mock-reviewer-retry.ts +34 -0
  149. package/test/fixtures/mock-reviewer.ts +18 -0
  150. package/test/fixtures/sample-project/src/circular-a.ts +6 -0
  151. package/test/fixtures/sample-project/src/circular-b.ts +6 -0
  152. package/test/fixtures/sample-project/src/config.ts +15 -0
  153. package/test/fixtures/sample-project/src/main.ts +19 -0
  154. package/test/fixtures/sample-project/src/services/product-service.ts +20 -0
  155. package/test/fixtures/sample-project/src/services/user-service.ts +18 -0
  156. package/test/fixtures/sample-project/src/types.ts +14 -0
  157. package/test/fixtures/sample-project/src/utils/index.ts +14 -0
  158. package/test/fixtures/sample-project/src/utils/validate.ts +12 -0
  159. package/tsconfig.json +20 -0
  160. package/vitest.config.ts +12 -0
@@ -0,0 +1,560 @@
1
+ # nomos-arc.ai Verification Architecture
2
+
3
+ > ### *Compiler for AI Intent*
4
+ >
5
+ > **Engineering Integrity over Stochastic Generation**
6
+ > Specification Version: 1.0 — Draft
7
+ > Status: Phase 2 Architectural Manifesto
8
+ > Last Updated: 2026-04-12
9
+
10
+ ---
11
+
12
+ ## 0. Document Purpose
13
+
14
+ هذا المستند يوثّق **الميثاق المعماري** لمرحلة Phase 2 من `nomos-arc.ai`. ينقل المشروع من كونه أداة CLI مساعدة إلى **نظام حوكمة هندسية (Engineering Governance System)** يوفّر طبقة تحقق حتمية (Verifiable Layer) فوق المولدات الاحتمالية (LLMs).
15
+
16
+ هذا المستند ليس خطة تنفيذ. هو **Specification** يحدد الحدود الدلالية والرياضية للنظام، ويُستخدم كمرجع لأي قرار تصميمي أو تنفيذي لاحق.
17
+
18
+ ---
19
+
20
+ ## 1. Foundational Philosophy
21
+
22
+ ### 1.1 The Stochastic-Deterministic Duality
23
+
24
+ المولدات اللغوية الكبرى (LLMs) هي بطبيعتها أنظمة **Stochastic**:
25
+
26
+ $$P(t_n \mid t_1, t_2, \ldots, t_{n-1})$$
27
+
28
+ حيث كل توكن ناتج هو توزيع احتمالي مشروط بما سبقه. هذا يعني أن أي مخرَج من نموذج LLM هو **عيّنة (sample)** من فضاء ممكنات، وليس إثباتاً.
29
+
30
+ `nomos-arc.ai` يُبنى على مسلّمة معاكسة: **الهندسة البرمجية تتطلب ضمانات قابلة للتحقق**. لذلك، دور nomos-arc ليس توليد الكود، بل **فرض قيود حتمية على المخرجات الاحتمالية**:
31
+
32
+ $$\text{Output}_{\text{final}} = \mathcal{V}(\text{LLM}(\text{Intent}))$$
33
+
34
+ حيث $\mathcal{V}$ هو **Verifier Function** حتمية لا تقبل إلا ما يحقق مجموعة القيود $\mathcal{C}$.
35
+
36
+ ### 1.2 Terminology: "Verifiable" not "Exact"
37
+
38
+ الـ **Exactness** في علم الحاسوب مفهوم مقيّد بـ Formal Methods (Coq, Agda, TLA+)، ومكلفة عملياً. بدلاً من ذلك، يتبنى هذا النظام مصطلح **Verifiable**، أي:
39
+
40
+ > إن كل مخرَج يخضع لمجموعة قيود قابلة للتحقق آلياً، ويُرفض ما يخالفها.
41
+
42
+ هذا يعني أن ما نضمنه ليس "الصحة الدلالية المطلقة"، بل **Constraint Conformance**.
43
+
44
+ ### 1.3 Role Assignment
45
+
46
+ | الدور | الكيان | الطبيعة |
47
+ |------|--------|---------|
48
+ | **Generator** | LLM (Gemini 1.5 Pro) | Stochastic |
49
+ | **Validator** | nomos-arc Governance Core | Deterministic |
50
+ | **Profiler** | Risk Profiler (async) | Statistical (separated) |
51
+
52
+ الانفصال الصارم بين هذه الأدوار هو **العمود الفقري** للمعمارية.
53
+
54
+ ---
55
+
56
+ ## 2. Core Architectural Principles
57
+
58
+ ### 2.1 Principle I — Constraint Conformance over Output Correctness
59
+
60
+ النظام لا يحكم على "صحة" الكود، بل على **مطابقته للقيود المعلنة** (structural, syntactic, behavioral).
61
+
62
+ ### 2.2 Principle II — Separation of Planning and Execution
63
+
64
+ الفشل التقليدي لأدوات AI البرمجية ينبع من دمج **التخطيط** و **التنفيذ** في طلب واحد. `nomos-arc` يفصلهما:
65
+
66
+ - **Planning Phase**: يُنتج **Contract** (عقد نية).
67
+ - **Validation Gate**: يتحقق من العقد قبل أي توليد كود.
68
+ - **Execution Phase**: لا يبدأ إلا بعد إجازة العقد.
69
+
70
+ ### 2.3 Principle III — Baseline-Relative Verification
71
+
72
+ النظام لا يطلب "الكمال المطلق"، بل **ألّا يُسوَّأ الوضع**:
73
+
74
+ $$\text{Accept}(S_{\text{after}}) \iff \Delta(S_{\text{before}}, S_{\text{after}}) \leq 0$$
75
+
76
+ حيث $\Delta$ دالة تقيس تدهور الحالة (errors, warnings, failing tests). هذا يسمح باستخدام nomos-arc لإصلاح مشاريع مكسورة أصلاً دون أن يرفضها الـ Preflight.
77
+
78
+ ### 2.4 Principle IV — Probabilistic Inputs, Deterministic Gates
79
+
80
+ البيانات الإحصائية (Risk Profiler, Pattern Mining) تُستخدم كـ **مدخلات** لضبط العتبات، لكن **البوابات نفسها** تبقى حتمية. لا مكان للعشوائية في مسار القرار النهائي.
81
+
82
+ ---
83
+
84
+ ## 3. Confidence-Tiered Rule System
85
+
86
+ ### 3.1 Rule Source Taxonomy
87
+
88
+ | Source | Authority | Example |
89
+ |--------|-----------|---------|
90
+ | **Declared** | المستخدم يكتبها يدوياً (`rules/global.md`, `rules/domain/*.md`) | "ممنوع استخدام `any`" |
91
+ | **Derived** | nomos-arc يستخرجها من `project_map.json` عبر Pattern Mining | "كل Controllers ترجع `ResponseDTO`" |
92
+ | **Inferred** | nomos-arc يستنتجها من Co-Change History | "هذا الملف يتغير مع ذاك دائماً" |
93
+
94
+ ### 3.2 Confidence Function
95
+
96
+ لأي نمط مرشح $p$، تُحسب درجة الثقة عبر:
97
+
98
+ $$\text{Conf}(p) = \frac{|\{x \in \mathcal{X} : p(x) = \text{true}\}|}{|\mathcal{X}|}$$
99
+
100
+ حيث $\mathcal{X}$ هو مجموعة الكيانات ذات الصلة (مثلاً: كل دوال الـ Controllers).
101
+
102
+ ### 3.3 Tier Assignment
103
+
104
+ $$\text{Tier}(p) = \begin{cases}
105
+ \text{Hard Rule} & \text{if } \text{Conf}(p) \geq 0.90 \\
106
+ \text{Soft Rule} & \text{if } 0.70 \leq \text{Conf}(p) < 0.90 \\
107
+ \text{Observation} & \text{if } \text{Conf}(p) < 0.70
108
+ \end{cases}$$
109
+
110
+ | Tier | Enforcement | Effect on Score |
111
+ |------|-------------|-----------------|
112
+ | **Hard Rule** | Auto-enforced | Violation → Hard Fail |
113
+ | **Soft Rule** | Warned + penalized | Violation → $-0.1$ to $-0.2$ per occurrence |
114
+ | **Observation** | Informational only | No scoring impact — feeds Planner context |
115
+
116
+ هذا التدرج يمنع **Architectural Stagnation**: أنماط الأقلية المشروعة (refactors) لا تُكبت، لكنها تُوثَّق.
117
+
118
+ ### 3.4 Threshold Calibration
119
+
120
+ عتبات 0.90 و 0.70 افتراضية. يجب أن تكون قابلة للضبط عبر `.nomos-config.json`:
121
+
122
+ ```json
123
+ {
124
+ "governance": {
125
+ "hard_rule_threshold": 0.90,
126
+ "soft_rule_threshold": 0.70,
127
+ "min_sample_size": 10
128
+ }
129
+ }
130
+ ```
131
+
132
+ `min_sample_size` يمنع اشتقاق قواعد من عينات صغيرة جداً (ضجيج إحصائي).
133
+
134
+ ---
135
+
136
+ ## 4. AST Projection Model
137
+
138
+ ### 4.1 Problem Statement
139
+
140
+ الـ Pre-Execution Validation على الخطة يواجه مشكلة **Chicken-and-Egg**: الخطة قد تشير إلى رموز (symbols) غير موجودة بعد لأنها ستُنشَأ ضمن نفس الخطة.
141
+
142
+ ### 4.2 Symbol Reference Classification
143
+
144
+ عند تحليل العقد (Contract)، يُصنَّف كل مرجع إلى رمز في إحدى ثلاث فئات:
145
+
146
+ $$\text{Ref}(s) \in \{\text{Existing}, \text{Declared}, \text{Forward}\}$$
147
+
148
+ | Category | Validation Source |
149
+ |----------|-------------------|
150
+ | **Existing** | يُتحقق منه في الـ **Current AST** (من `project_map.json`) |
151
+ | **Declared** | تعريف جديد ضمن نفس الخطة — يُضاف إلى **Projected AST** |
152
+ | **Forward** | مرجع إلى رمز سيُعرَّف لاحقاً ضمن نفس الخطة — يُتحقق منه مقابل الـ **Projected AST** |
153
+
154
+ ### 4.3 Projected AST Construction
155
+
156
+ $$\text{AST}_{\text{projected}} = \text{AST}_{\text{current}} \oplus \text{Declared}(\text{Plan})$$
157
+
158
+ حيث $\oplus$ عملية دمج تُضيف التعريفات الجديدة قبل تحقق المراجع الأمامية. هذه البنية تشبه فلسفياً **Virtual DOM** في React — طبقة وسيطة بين النية والتطبيق الفعلي.
159
+
160
+ ### 4.4 Hallucination Detection
161
+
162
+ $$\text{Hallucinated}(s) \iff \text{Ref}(s) = \text{Existing} \land s \notin \text{AST}_{\text{current}}$$
163
+
164
+ عند اكتشاف هلوسة، يُعاد العقد إلى الـ Planner مع رسالة محددة:
165
+
166
+ ```
167
+ Planner claimed: AuthService.validate()
168
+ AST evidence: AuthService has methods [verify, revoke, refresh]
169
+ Action: Re-plan with corrected symbol reference
170
+ ```
171
+
172
+ ---
173
+
174
+ ## 5. Dynamic Convergence Threshold
175
+
176
+ ### 5.1 Blast Radius Definition
177
+
178
+ لأي ملف $f$، الـ Blast Radius هو عدد الكيانات التي تعتمد عليه بشكل مباشر أو غير مباشر:
179
+
180
+ $$BR(f) = |\{g \in \mathcal{G} : g \xrightarrow{*} f\}|$$
181
+
182
+ حيث $\mathcal{G}$ هو Dependency Graph و $\xrightarrow{*}$ هو الإغلاق التعدّي (transitive closure) لعلاقة الاعتماد.
183
+
184
+ ### 5.2 Convergence Threshold Formula
185
+
186
+ $$\theta(f) = \theta_{\text{base}} + \alpha \cdot \log(1 + BR(f)) + \beta \cdot R(f)$$
187
+
188
+ | Symbol | Meaning | Default |
189
+ |--------|---------|---------|
190
+ | $\theta_{\text{base}}$ | العتبة الأساسية | $0.85$ |
191
+ | $\alpha$ | معامل حساسية الـ Blast Radius | $0.02$ |
192
+ | $\beta$ | معامل حساسية الـ Risk Profile | $0.05$ |
193
+ | $R(f)$ | درجة الخطر من Risk Profiler (انظر §7) | $\in [0, 1]$ |
194
+
195
+ مع تطبيق سقف: $\theta(f) \leq 0.99$ لتجنب الاستحالة العملية.
196
+
197
+ **المعنى العملي:**
198
+ - ملف بلا dependents ومستقر → $\theta \approx 0.85$
199
+ - ملف بـ 50 dependent ومستقر → $\theta \approx 0.93$
200
+ - ملف بـ 50 dependent وغير مستقر → $\theta \approx 0.98$
201
+
202
+ ---
203
+
204
+ ## 6. The 8-Step Orchestration Pipeline
205
+
206
+ ### 6.1 Pipeline Overview
207
+
208
+ $$\text{Task} \xrightarrow{S_1} \text{Baseline} \xrightarrow{S_2} \text{Contract} \xrightarrow{S_3} \text{Validated Contract} \xrightarrow{S_4} \text{Candidate} \xrightarrow{S_5} \text{Runnable} \xrightarrow{S_6} \text{Scored} \xrightarrow{S_7} \text{Delta-Checked} \xrightarrow{S_8} \text{Certified}$$
209
+
210
+ ### 6.2 Step-by-Step Specification
211
+
212
+ #### **Step 1: Baseline Capture**
213
+
214
+ **Input:** Current repository state
215
+ **Output:** `baseline.json`
216
+
217
+ يلتقط snapshot حتمي للحالة الراهنة:
218
+
219
+ ```json
220
+ {
221
+ "timestamp": "ISO-8601",
222
+ "compile_errors": 0,
223
+ "type_errors": 3,
224
+ "lint_warnings": 12,
225
+ "lint_errors": 0,
226
+ "test_pass_rate": 0.87,
227
+ "test_count": 367,
228
+ "hash": "sha256:..."
229
+ }
230
+ ```
231
+
232
+ لا يقرأ Git history. سريع، خفيف، deterministic.
233
+
234
+ #### **Step 2: Contract Drafting**
235
+
236
+ **Input:** Task + Rules + Context + Risk Profile
237
+ **Output:** Structured Contract (JSON)
238
+
239
+ الـ LLM يُنتج "نية" مهيكلة، لا كود:
240
+
241
+ ```json
242
+ {
243
+ "intent": "Add rate limiting to auth endpoints",
244
+ "affected_modules": ["src/auth/*.ts"],
245
+ "symbol_changes": [
246
+ { "type": "add", "symbol": "RateLimiter", "kind": "class" },
247
+ { "type": "modify", "symbol": "AuthService.login", "kind": "method" }
248
+ ],
249
+ "expected_delta": {
250
+ "files_modified": 2,
251
+ "files_added": 1
252
+ }
253
+ }
254
+ ```
255
+
256
+ #### **Step 3: Contract Validation Gate**
257
+
258
+ **Input:** Contract + Current AST + Derived Rules
259
+ **Output:** Pass / Fail-with-feedback
260
+
261
+ يُطبّق:
262
+ 1. **AST Projection** (§4) للتحقق من صحة المراجع
263
+ 2. **Hard Rules Check** (§3) لرفض الانتهاكات المعلومة مسبقاً
264
+ 3. **Structural Feasibility**: هل الـ `affected_modules` موجودة فعلاً؟
265
+
266
+ إن فشل → إعادة للـ Planner مع Feedback محدد (max $N$ iterations).
267
+
268
+ #### **Step 4: Execution**
269
+
270
+ **Input:** Validated Contract
271
+ **Output:** Shadow Worktree with generated code
272
+
273
+ يحدث في **git worktree** معزول. لا تأثير على الـ main branch.
274
+
275
+ #### **Step 5: Hard Gates**
276
+
277
+ **Input:** Candidate code
278
+ **Output:** Compiler + Critical Linter verdict
279
+
280
+ $$\text{Gate}_{\text{hard}} = \bigwedge_{g \in G_H} g(\text{code})$$
281
+
282
+ حيث $G_H$ هي البوابات الصارمة: `tsc --noEmit`, `eslint --max-warnings=0 --rule-severity=error`, critical static analysis.
283
+
284
+ **فشل → عودة للـ Planner أو Discard.** لا يُصرف توكنز على Soft Gates.
285
+
286
+ #### **Step 6: Soft Gates + Scoring**
287
+
288
+ **Input:** Code that passed Hard Gates
289
+ **Output:** Composite Score $\in [0, 1]$
290
+
291
+ $$\text{Score} = w_1 \cdot S_{\text{AI}} + w_2 \cdot S_{\text{lint}} + w_3 \cdot S_{\text{coverage}} + w_4 \cdot S_{\text{style}}$$
292
+
293
+ مع:
294
+ - $S_{\text{AI}}$: Reviewer AI score $\in [0, 1]$
295
+ - $S_{\text{lint}} = 1 - \frac{\text{warnings}}{\text{warning\_budget}}$
296
+ - $S_{\text{coverage}}$: نسبة التغطية للكود الجديد
297
+ - $S_{\text{style}}$: مطابقة الـ Soft Rules
298
+ - $\sum w_i = 1$
299
+
300
+ #### **Step 7: Delta Comparison**
301
+
302
+ **Input:** Baseline + Candidate state + Original Contract
303
+ **Output:** Delta verdict
304
+
305
+ يُتحقق من ثلاثة أبعاد:
306
+
307
+ **(أ) No Regression:**
308
+ $$\Delta_{\text{state}} = S_{\text{after}} - S_{\text{baseline}} \leq 0$$
309
+
310
+ **(ب) Plan Conformance:**
311
+ $$\Delta_{\text{plan}} = |\text{expected\_delta} - \text{actual\_delta}| \leq \epsilon$$
312
+
313
+ انحراف كبير عن `expected_delta` في العقد → فشل (ربما الـ AI فعل أكثر أو أقل مما وعد).
314
+
315
+ **(ج) Improvement Direction:** إن كانت المهمة إصلاحية (fix task)، يجب أن يكون $\Delta_{\text{state}} < 0$ فعلياً، لا مجرد $\leq 0$.
316
+
317
+ #### **Step 8: Certificate Issuance**
318
+
319
+ **Input:** All prior step artifacts
320
+ **Output:** `certificate.json` (signed)
321
+
322
+ ```json
323
+ {
324
+ "task_hash": "sha256:...",
325
+ "contract_hash": "sha256:...",
326
+ "diff_hash": "sha256:...",
327
+ "gates_passed": ["ast_projection", "hard_gates", "soft_gates", "delta"],
328
+ "score": 0.94,
329
+ "threshold_required": 0.91,
330
+ "iterations": 3,
331
+ "baseline_ref": "sha256:...",
332
+ "verifiable_claims": [
333
+ "No new compile errors",
334
+ "No hard rule violations",
335
+ "Expected delta matches actual delta (±1 file)"
336
+ ]
337
+ }
338
+ ```
339
+
340
+ الشهادة **لا تدّعي صحة دلالية**. تدّعي **مطابقة قيود محددة**.
341
+
342
+ ### 6.3 Conditional Execution Invariant
343
+
344
+ **قاعدة صارمة:** Step $S_{i+1}$ لا يُنفَّذ إلا إذا نجح $S_i$. هذا يحمي من صرف موارد (API calls, compute) على مخرجات معطوبة.
345
+
346
+ ---
347
+
348
+ ## 7. Risk Profiler (Asynchronous Layer)
349
+
350
+ ### 7.1 Separation Rationale
351
+
352
+ الـ Risk Profiler **ليس جزءاً من الـ Pipeline التنفيذي**. هو طبقة مستقلة:
353
+
354
+ - **Pipeline** = synchronous, per-task, deterministic
355
+ - **Risk Profiler** = asynchronous, periodic, statistical
356
+
357
+ الدمج بينهما يُحوّل كل `arc run` إلى عملية Git log analysis، وهذا يهدم تجربة المستخدم على المشاريع الكبيرة.
358
+
359
+ ### 7.2 Architecture
360
+
361
+ ```
362
+ ┌─────────────────────┐
363
+ │ Risk Profiler │ Async, periodic (daily / on-demand)
364
+ │ │ Outputs: risk_profile.json
365
+ └──────────┬──────────┘
366
+ │ consumed by
367
+
368
+ ┌─────────────────────────────────────────────┐
369
+ │ 8-Step Pipeline (Sync) │
370
+ │ S2: Planner reads risk context │
371
+ │ S3: Threshold $\theta(f)$ uses $R(f)$ │
372
+ │ S6: Scoring weights modulated │
373
+ └─────────────────────────────────────────────┘
374
+ ```
375
+
376
+ ### 7.3 Core Metrics
377
+
378
+ | Metric | Formula | Data Source |
379
+ |--------|---------|-------------|
380
+ | **Churn Rate** | $C(f) = \frac{\|\text{commits}_{f, \Delta t}\|}{\Delta t}$ | `git log --follow` |
381
+ | **Revert Density** | $RD(f) = \frac{\|\text{reverted commits}_f\|}{\|\text{commits}_f\|}$ | `git log --grep=revert` |
382
+ | **Bug-Fix Ratio** | $BF(f) = \frac{\|\text{fix-tagged commits}_f\|}{\|\text{commits}_f\|}$ | commit message parsing |
383
+ | **Co-Change Coupling** | $CC(f_i, f_j) = \frac{\|\text{commits containing both}\|}{\|\text{commits containing either}\|}$ (Jaccard) | `git log` pair analysis |
384
+ | **Ownership Dilution** | $OD(f) = \frac{H(\text{authors}_f)}{\log\|\text{authors}_f\|}$ (normalized entropy) | `git blame` |
385
+
386
+ ### 7.4 Composite Risk Score
387
+
388
+ $$R(f) = \sigma\left( \gamma_1 \cdot C(f) + \gamma_2 \cdot RD(f) + \gamma_3 \cdot BF(f) + \gamma_4 \cdot OD(f) \right)$$
389
+
390
+ حيث $\sigma$ هي دالة sigmoid للحصول على $R(f) \in [0, 1]$. أوزان $\gamma_i$ قابلة للضبط.
391
+
392
+ ### 7.5 Co-Change as Implicit Coupling Detector
393
+
394
+ $CC(f_i, f_j) > 0.80$ دون وجود `import` أو dependency ظاهر في الـ AST يُشير إلى **اعتماد ضمني خفي** — غالباً اتفاقيات غير مصرَّح بها، مخطط بيانات مشترك، أو ثابت مكرر. هذا النوع من الاقتران لا يراه الـ AST، لكنه يكسر عند التعديل.
395
+
396
+ ### 7.6 Probabilistic Outputs, Never Verdicts
397
+
398
+ النتائج تُصاغ كـ **احتمالات**، لا أحكام:
399
+
400
+ > ❌ "Module X is fragile"
401
+ > ✅ "Module X has 73% regression likelihood based on 6-month history (n=47 commits)"
402
+
403
+ هذا يحفظ وعد **Verifiable**: الحقائق الحتمية تبقى في الـ Pipeline، الإحصائيات في الـ Profiler، ولكل دوره.
404
+
405
+ ---
406
+
407
+ ## 8. Incremental Map Invalidation
408
+
409
+ ### 8.1 Problem
410
+
411
+ الـ `project_map.json` يُبنى حالياً عبر `arc map` كعملية كاملة (full scan). بعد Phase 2، بعد كل `arc apply` ناجح، يجب تحديث الخريطة. إعادة الـ scan الكامل على مشروع كبير = **seconds to minutes latency**.
412
+
413
+ ### 8.2 Incremental Scanner Design
414
+
415
+ $$\text{AST}_{\text{new}} = (\text{AST}_{\text{old}} \setminus \text{Nodes}(F_{\text{changed}})) \cup \text{Parse}(F_{\text{changed}})$$
416
+
417
+ حيث $F_{\text{changed}}$ هي الملفات المُعدَّلة في الـ apply.
418
+
419
+ **Invalidation Cascade:**
420
+ 1. احذف العُقد الخاصة بـ $F_{\text{changed}}$ من الـ Graph
421
+ 2. أعد parsing لهذه الملفات فقط
422
+ 3. أعد بناء الـ edges الصادرة من/إلى هذه الملفات
423
+ 4. أعد حساب الـ Blast Radius للعُقد المتأثرة فقط (لا الكل)
424
+
425
+ ### 8.3 Cache Consistency Guarantee
426
+
427
+ بعد أي `arc apply`:
428
+ $$\text{Hash}(\text{AST}_{\text{new}}) = \text{Hash}(\text{FullScan}(\text{repo}))$$
429
+
430
+ يجب أن يكون هناك **integrity test** دوري يُقارن المخرجين للتأكد من عدم انحراف الـ incremental update عن الـ full scan.
431
+
432
+ ---
433
+
434
+ ## 9. System-Level Invariants
435
+
436
+ النظام يُلزَم بهذه الثوابت تحت كل الظروف:
437
+
438
+ **I1 — No Generation Without Validation:**
439
+ $$\nexists\, \text{code output} \text{ such that } \text{Contract Validation} = \text{Fail} \land \text{Generation proceeds}$$
440
+
441
+ **I2 — No Scoring Without Hard Gates:**
442
+ $$\text{Score computed} \implies \text{Hard Gates} = \text{Pass}$$
443
+
444
+ **I3 — No Apply Without Delta Check:**
445
+ $$\text{Merge to main} \implies \Delta_{\text{state}} \leq 0 \land \Delta_{\text{plan}} \leq \epsilon$$
446
+
447
+ **I4 — No Certificate Without Full Pipeline:**
448
+ $$\text{Certificate issued} \implies \bigwedge_{i=1}^{8} S_i = \text{Pass}$$
449
+
450
+ **I5 — Probabilistic ∉ Decision Path:**
451
+ القرارات الحتمية (pass/fail, merge/reject) لا تعتمد مباشرة على قيم احتمالية. الإحصائيات تُعدّل **عتبات** البوابات، لا تستبدلها.
452
+
453
+ ---
454
+
455
+ ## 10. Implementation Roadmap
456
+
457
+ ### Phase 2.1 — Governance Core (MVP)
458
+ - [ ] Step 1: Baseline Capture (`arc baseline`)
459
+ - [ ] Step 7: Delta Comparison
460
+ - [ ] Basic Certificate fields extension
461
+ - **Rationale:** أصغر scope، قيمة فورية، يحوّل الـ apply من "trust" إلى "evidence-based".
462
+
463
+ ### Phase 2.2 — Contract Validation
464
+ - [ ] Step 2: Structured Contract schema
465
+ - [ ] Step 3: AST Projection + Hard Rule checking
466
+ - [ ] Hallucination feedback loop
467
+ - **Rationale:** يمنع ~80% من أخطاء LLM قبل توليد الكود.
468
+
469
+ ### Phase 2.3 — Dynamic Thresholds
470
+ - [ ] Blast Radius computation from existing graph
471
+ - [ ] $\theta(f)$ formula integration
472
+ - **Rationale:** يستخدم بيانات متوفرة أصلاً؛ تعديل scoring logic فقط.
473
+
474
+ ### Phase 2.4 — Auto-Derived Rules
475
+ - [ ] Pattern Mining engine on `project_map.json`
476
+ - [ ] Confidence-tiered rule emission
477
+ - [ ] Soft/Hard/Observation categorization
478
+ - **Rationale:** يقلل الحاجة لكتابة rules يدوياً.
479
+
480
+ ### Phase 2.5 — Risk Profiler
481
+ - [ ] Git history analyzer
482
+ - [ ] Core metrics computation
483
+ - [ ] `risk_profile.json` emission
484
+ - [ ] Integration with $R(f)$ in $\theta(f)$
485
+ - **Rationale:** أكبر scope، يتطلب استقرار باقي الطبقات.
486
+
487
+ ### Phase 2.6 — Incremental Map
488
+ - [ ] Incremental AST scanner
489
+ - [ ] Invalidation cascade
490
+ - [ ] Consistency verification tests
491
+ - **Rationale:** optimization؛ لا يُحسّن الوظيفة، يُحسّن الأداء.
492
+
493
+ ---
494
+
495
+ ## 11. What This System Does *Not* Claim
496
+
497
+ الصدق الهندسي يتطلب تحديد الحدود:
498
+
499
+ - **لا يضمن الصحة الدلالية** (semantic correctness). كود يمر بكل البوابات قد يكون منطقياً خاطئاً.
500
+ - **لا يستبدل المراجعة البشرية** للمهام عالية المخاطر.
501
+ - **لا يُزيل الـ hallucination** تماماً — يقلله بشكل ملموس عبر AST Projection.
502
+ - **لا يُنتج proofs رياضية** بمعنى Formal Verification. يُنتج **evidence** قابل للتدقيق.
503
+ - **لا يصلح لمشاريع بلا tests ولا lint rules** — النظام يتغذى على مخرجات أدوات قائمة.
504
+
505
+ ---
506
+
507
+ ## 12. Positioning & Terminology
508
+
509
+ ### 12.1 Headline
510
+
511
+ `nomos-arc.ai` في ضوء هذا الميثاق ليس "أداة AI برمجية أخرى". هو:
512
+
513
+ > # **Compiler for AI Intent**
514
+ >
515
+ > طبقة تحقق تجبر المخرجات الاحتمالية للـ LLMs على الالتزام بعقود هندسية قابلة للتحقق آلياً، بحيث يصبح كل تغيير كود **evidence-backed** لا **trust-based**.
516
+
517
+ فئة المنتج الأقرب: **Professional Tooling** (بجوار debuggers, profilers, static analyzers)، لا **AI Assistants**.
518
+
519
+ ### 12.2 Layered Terminology
520
+
521
+ المصطلحات ليست قابلة للتبديل. كل طبقة لها مفرداتها:
522
+
523
+ | Layer | Term | Usage |
524
+ |-------|------|-------|
525
+ | **Marketing / Positioning** | *Engineering Integrity System* | يوصّل القيمة للمطور: "كودك نزيه، موثق، غير ملوث بهلوسة AI" |
526
+ | **Technical / Architectural** | *Verification Layer* / *Verifiable Pipeline* | يوصّل الدقة التقنية للمهندسين؛ يطابق ما يفعله النظام فعلاً |
527
+ | **Code / Internal** | `src/core/governance/` | اسم موديول داخلي يجمع rules + validators + audit emitter |
528
+ | **Conceptual / Headline** | *Compiler for AI Intent* | metaphor تواصلية تخلق توقعات صحيحة (deterministic, error-before-runtime, toolchain-native) |
529
+
530
+ **قاعدة الاستخدام:** لا تستخدم "Governance" في التواصل الخارجي (مستندات، README، pitch). احتفظ بها كاسم subsystem داخلي فقط. استخدم **Verification** للأوصاف التقنية، و **Integrity** للقيمة، و **Compiler for AI Intent** كعنوان رئيسي.
531
+
532
+ ---
533
+
534
+ ## Appendix A — Symbol Reference Table
535
+
536
+ | Symbol | Meaning |
537
+ |--------|---------|
538
+ | $\mathcal{V}$ | Verifier Function |
539
+ | $\mathcal{C}$ | Constraint Set |
540
+ | $\text{Conf}(p)$ | Rule confidence score |
541
+ | $BR(f)$ | Blast Radius of file $f$ |
542
+ | $R(f)$ | Risk score of file $f$ from Risk Profiler |
543
+ | $\theta(f)$ | Convergence threshold for file $f$ |
544
+ | $\Delta$ | Delta between two states |
545
+ | $\oplus$ | AST merge operator |
546
+ | $S_i$ | Pipeline Step $i$ |
547
+
548
+ ---
549
+
550
+ ## Appendix B — Related Documents
551
+
552
+ - [governance-overview.md](./governance-overview.md) — Original philosophical framing
553
+ - [../dev_overview.md](../dev_overview.md) — Project overview
554
+ - [../how_it_works.md](../how_it_works.md) — Current Phase 1 mechanics
555
+ - [../integrity-gate/](../integrity-gate/) — Existing integrity certificate design
556
+ - [../map/](../map/) — Dependency graph specification
557
+
558
+ ---
559
+
560
+ *End of Specification v1.0*