@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,159 @@
1
+ # Adversarial Architect — Zero-Trust Audit Report
2
+
3
+ ## Semantic Graph Master Execution Plan (`arc map` / `arc show map`)
4
+
5
+ ---
6
+
7
+ ## 1. VETO STATUS: **CONDITIONAL**
8
+
9
+ The plan is architecturally sound in its decomposition and phasing but contains **4 critical blockers**, **8 ambiguity traps**, and **6 resilience gaps** that will cause production failures if left unaddressed.
10
+
11
+ ---
12
+
13
+ ## 2. CRITICAL BLOCKERS (System Killers)
14
+
15
+ ### BLK-1: Tree-Sitter Native Binary + esbuild = Runtime Bomb
16
+
17
+ The plan installs `tree-sitter` (a native C++ addon via node-gyp) and marks it `--external` in esbuild. **The plan fails to account for** how the native `.node` binary will be located at runtime when the bundled `dist/cli.js` executes. esbuild externalizes the `require()` call, but Node.js resolves native modules relative to the *calling file*, which post-bundle is `dist/cli.js` — not `src/core/graph/parser.ts`. The `node_modules/tree-sitter/` binding must be discoverable from the dist directory.
18
+
19
+ **Impact**: `arc map` will crash with `MODULE_NOT_FOUND` in any environment that runs the built artifact (`npm run build && node dist/cli.js`). This includes every production and CI path.
20
+
21
+ **Mitigation**: The plan must add a step to verify `node dist/cli.js map --no-ai --help` post-build (not `npx tsx`). Additionally, a `postinstall` or `prepare` script should be considered, or switch to a WASM-based parser (`web-tree-sitter`) that bundles cleanly.
22
+
23
+ ### BLK-2: No File-Level Locking on `project_map.json` — Concurrent Corruption
24
+
25
+ Step 5.1 implements atomic write via `tmp → fsync → rename`. However, the existing codebase uses `proper-lockfile` in `src/core/state.ts` for good reason: **two concurrent `arc map` invocations** (e.g., a user runs it in two terminals, or a CI job overlaps with a local run) will both read the existing map, scan files independently, and race to rename their temp file. The last writer wins, silently discarding the other's work.
26
+
27
+ **The architecture is vulnerable to**: silent data loss under concurrent execution — the exact scenario `proper-lockfile` was added to prevent in `state.ts`.
28
+
29
+ **Mitigation**: The plan explicitly says "do not duplicate atomic write logic from `state.ts`" but then reinvents a weaker version of it. Use `proper-lockfile` on `project_map.json`. This is non-negotiable for a system that claims incremental updates.
30
+
31
+ ### BLK-3: `GraphBuilder.build()` Mutates In-Place Without Clearing Stale Data
32
+
33
+ Step 3.2 says `build()` mutates `FileNode` objects to populate `dependencies`, `dependents`, and `depth`. **The plan fails to account for** the incremental case: when `carried` FileNodes from a previous run already have populated `dependencies`/`dependents`/`depth` arrays from the *old* graph structure. If file B was removed from the project, file A's carried-forward `dependents` array will still reference B — a ghost edge.
34
+
35
+ **Impact**: Stale dependency data accumulates across runs, producing phantom edges in the visualization and incorrect `depth` calculations. The `core_modules` ranking becomes unreliable.
36
+
37
+ **Mitigation**: `build()` must reset `dependencies = []`, `dependents = []`, and `depth = 0` on every FileNode before computing the graph. The plan must explicitly state this.
38
+
39
+ ### BLK-4 (Downgraded): Kahn's Algorithm Direction — Misleading Description
40
+
41
+ Originally flagged as a blocker, reclassified as **AMB-1** after analysis confirmed the test expectations are internally consistent. See Ambiguity Traps section.
42
+
43
+ ---
44
+
45
+ ## 3. AMBIGUITY TRAPS
46
+
47
+ ### AMB-1: Kahn's Algorithm Direction
48
+
49
+ The plan says "Kahn's BFS topological sort" but means "reverse-dependency BFS." An implementer who Googles "Kahn's algorithm" will compute depth from *dependencies* (in-degree from imports), not *dependents* — yielding the opposite depth ordering. The test expectations will catch this, but only after hours of debugging. **State the direction explicitly**: "in-degree = number of files that import this node (dependents.length), not number of files this node imports."
50
+
51
+ ### AMB-2: `FileScanner.scan()` Return Type Carries Content, But Content is Never Persisted
52
+
53
+ `ScanResult.files` includes `content: string` for each file. This content is consumed by `ASTParser.parse()` in Step 5.1d. But the plan never specifies **when to release these content strings from memory**. For a large monorepo with 5,000 files averaging 10KB each, that's ~50MB of source strings held simultaneously.
54
+
55
+ More critically, `SemanticEnricher` (Phase 4) also needs file content for its prompts — and by then, the `ScanResult.files` map may have been consumed and discarded. Step 4.1.3b says "Truncate file content at `max_file_chars`" — **where does this content come from?** The `FileNode` interface has no `content` field. The enricher would need to re-read files from disk.
56
+
57
+ **Mitigation**: Explicitly state that the enricher reads file content from disk (not from the scan result), or add a `content` field to `FileNode` (which contradicts the `ProjectMap` schema).
58
+
59
+ ### AMB-3: `tree-sitter-typescript` Grammar Loading — ESM vs CJS Ambiguity
60
+
61
+ Step 2.1 says "Import `tree-sitter` and `tree-sitter-typescript` as external ESM modules." But `tree-sitter` and `tree-sitter-typescript` are native CJS modules with no ESM exports. The `import()` syntax will work via Node's CJS interop, but the grammar object extraction is CJS-specific:
62
+
63
+ ```javascript
64
+ // CJS: const { typescript, tsx } = require('tree-sitter-typescript');
65
+ // ESM: import TreeSitterTS from 'tree-sitter-typescript'; TreeSitterTS.typescript
66
+ ```
67
+
68
+ The plan does not specify which import pattern to use. An implementer using named ESM imports (`import { typescript } from 'tree-sitter-typescript'`) will get `undefined`.
69
+
70
+ ### AMB-4: `ImportResolver` Uses `fs.existsSync` — Contradicts Async Convention
71
+
72
+ Step 3.1 says "Do not use any external package — pure Node.js path manipulation + `fs.existsSync` for alias resolution file checks." But the `resolve()` method signature is synchronous (`resolve(...): ResolveResult`). Meanwhile, every other module in the codebase uses `fs/promises`. This creates an inconsistency, and `existsSync` blocks the event loop during resolution of potentially thousands of imports.
73
+
74
+ For a project with 2,000 files averaging 10 imports each, that's 20,000 synchronous filesystem calls. On NFS or slow I/O, this is a **DoS vector**.
75
+
76
+ **Mitigation**: Make `resolve()` async and use `fs.access()` with a Set-based cache, or accept the sync trade-off and document the performance ceiling.
77
+
78
+ ### AMB-5: `ContractWriter` Assumes Parent Directory Exists
79
+
80
+ Step 4.2 says "Do not create directories — source files already exist so their parent directories exist." This is true for the initial run, but what if a source file is in a directory that was created *after* the last `arc map` run and then the source file was deleted? The `.semantic.md` would target a non-existent directory. More practically: if `exclude_patterns` change between runs, a previously excluded file's directory may now be targeted.
81
+
82
+ This is a minor edge case but violates the plan's own "assume catastrophic failure from ambiguity" principle.
83
+
84
+ ### AMB-6: Exit Code 2 Semantics — Tooling Confusion
85
+
86
+ Step 5.2 defines exit code 2 as "AI failures occurred but map was written." Most Unix tooling interprets exit code 2 as "misuse of shell command" (per Bash convention). CI/CD pipelines may flag this as a configuration error rather than a partial success. The plan should use a higher exit code (e.g., 3 or 10) or document this convention prominently.
87
+
88
+ ### AMB-7: `readArchitecturalConstraints` Context File Resolution
89
+
90
+ Step 5.4b says the function takes `contextFiles: string[]` and looks them up in `map.files`. But the `contextFiles` in the existing codebase come from task frontmatter (BLK-3 fix in the codebase). **The plan fails to specify** whether these paths are absolute, relative to project root, or relative to the task file. If the task frontmatter uses `../src/core/state.ts` but the map keys are `src/core/state.ts`, the lookup silently fails.
91
+
92
+ ### AMB-8: HTML Template JSON Escaping — XSS Surface
93
+
94
+ Step 6.2a embeds `PROJECT_MAP` as `const PROJECT_MAP = ${mapJson};`. If any file path or symbol name contains `</script>` or `${...}`, this creates either a broken page or an XSS vector. The plan says "Template literal must properly escape embedded JSON" but does not specify *how*. `JSON.stringify()` alone does not escape `</script>` — you need to replace `</` with `<\/`.
95
+
96
+ ---
97
+
98
+ ## 4. RESILIENCE GAPS
99
+
100
+ ### GAP-1: No Timeout on Tree-Sitter Parse
101
+
102
+ A malformed or adversarial file (e.g., a minified 2MB JavaScript file) can cause tree-sitter to consume unbounded CPU. The plan specifies an error-node threshold (Step 2.1.4) but this is checked *after* parsing completes. There is no mechanism to abort parsing if it exceeds a time or size limit.
103
+
104
+ **Impact**: A single large file can freeze `arc map` indefinitely.
105
+
106
+ ### GAP-2: Gemini API Failure Does Not Trigger Partial Map Save
107
+
108
+ Step 5.1 writes `project_map.json` only at the end (Step 5.1j). If the process crashes during AI enrichment (Phase 4 — which is the longest phase due to network I/O), all scanning and parsing work is lost. The next run must re-scan and re-parse everything before re-attempting enrichment.
109
+
110
+ **Mitigation**: Write the map *before* AI enrichment (with `semantic: null`) and then update it after enrichment. This way, incremental runs can skip scanning/parsing even if enrichment failed.
111
+
112
+ ### GAP-3: No SIGINT/SIGTERM Handler for Graceful Shutdown
113
+
114
+ The pipeline can run for minutes during AI enrichment. If the user Ctrl+C's, the `p-limit` queue has in-flight Gemini requests that will complete asynchronously, potentially writing to a `FileNode` that's being serialized. The existing CLI has a SIGINT handler (sets `process.exitCode = 130`), but the pipeline has no awareness of it.
115
+
116
+ **Mitigation**: Check a cancellation flag between enrichment batches and write the partial map on shutdown.
117
+
118
+ ### GAP-4: CDN Dependency for Visualization — Offline Failure
119
+
120
+ Step 6.2a pins `cytoscape/3.28.1` from cdnjs. If the user is offline, on a corporate network that blocks CDNs, or if cloudflare deprecates this URL, the visualization silently renders a blank page with no error message.
121
+
122
+ **Mitigation**: Bundle Cytoscape.js inline (it's ~500KB minified) or add a `<noscript>` / `onerror` fallback that displays a text-based dependency list.
123
+
124
+ ### GAP-5: `migrateProjectMap()` Has No Forward Compatibility
125
+
126
+ Step 1.3 defines migrations as `Record<number, (raw: unknown) => unknown>` with `schema_version: 1`. If a newer version of the tool writes `schema_version: 2` and an older version tries to read it, `migrateProjectMap` will parse it with schema v1 validators, likely corrupting or rejecting valid data. **There is no version ceiling check.**
127
+
128
+ **Mitigation**: If `raw.schema_version > CURRENT_SCHEMA_VERSION`, throw a clear error: "Map was created by a newer version of arc. Please upgrade."
129
+
130
+ ### GAP-6: Circular Dependency Detection — Incomplete Cycle Reporting
131
+
132
+ Step 3.2c says "Find the max depth among nodes that have edges entering the cycle, assign cyclic nodes `depth = maxDepth + 1`." For disconnected cycles (A→B→A and C→D→C with no connection between them), both cycles get `depth = 0 + 1 = 1`, making them indistinguishable from depth-1 non-cyclic nodes. The log says "Circular dependency detected: {cycle path}" but **does not specify how to extract the cycle path** from Kahn's remnant nodes. Kahn's tells you *which* nodes are in cycles, not *which* cycles they form. Extracting distinct cycles requires Tarjan's SCC or equivalent — not mentioned.
133
+
134
+ ---
135
+
136
+ ## 5. MANDATORY MITIGATIONS
137
+
138
+ | # | Mitigation | Severity | Effort |
139
+ |---|-----------|----------|--------|
140
+ | M-1 | Add `proper-lockfile` to `project_map.json` writes (BLK-2) | **Critical** | Low |
141
+ | M-2 | Reset `dependencies`/`dependents`/`depth` before `build()` (BLK-3) | **Critical** | Trivial |
142
+ | M-3 | Add post-build verification step: `node dist/cli.js map --help` (BLK-1) | **Critical** | Low |
143
+ | M-4 | Evaluate `web-tree-sitter` (WASM) as alternative to native `tree-sitter` (BLK-1) | **Critical** | Medium |
144
+ | M-5 | Specify how `SemanticEnricher` obtains file content (AMB-2) | **High** | Low |
145
+ | M-6 | Add `schema_version` ceiling check in `migrateProjectMap()` (GAP-5) | **High** | Trivial |
146
+ | M-7 | Write map before AI enrichment; update after (GAP-2) | **High** | Medium |
147
+ | M-8 | Escape `</script>` in HTML template JSON embedding (AMB-8) | **High** | Trivial |
148
+ | M-9 | Add file size limit before tree-sitter parse (GAP-1) | **Medium** | Low |
149
+ | M-10 | Clarify Kahn's direction in plan text (AMB-1) | **Medium** | Trivial |
150
+ | M-11 | Make `ImportResolver.resolve()` async or document sync ceiling (AMB-4) | **Medium** | Low |
151
+ | M-12 | Add SIGINT-aware cancellation to enrichment loop (GAP-3) | **Medium** | Medium |
152
+
153
+ ---
154
+
155
+ ## 6. Summary
156
+
157
+ The plan is well-structured — the phased decomposition, per-step rollbacks, and verification criteria are significantly above average. The test coverage is thorough. However, **BLK-1 (native module bundling) and BLK-2 (no file locking) are production-unsafe as written**. BLK-3 (stale mutation) will cause silent data corruption on incremental runs — the exact scenario the plan optimizes for.
158
+
159
+ The plan earns a **CONDITIONAL** status: resolve M-1 through M-4 before execution begins. The remaining mitigations can be addressed during implementation without restructuring the phases.
@@ -0,0 +1,147 @@
1
+ هذه الميزة هي ما نسميه في هندسة البرمجيات **"Semantic Documentation Graph"**. هي ليست مجرد توثيق، بل هي "عقل" للمشروع يسهل عملية الـ Onboarding لأي مبرمج جديد ويمنع حدوث "Architectural Drift" (خروج الكود عن مساره المعماري).
2
+
3
+ بصفتي **CEO**، أرى أن تنفيذ هذه الفكرة باستخدام نماذج ذكية مجانية (مثل Gemini 1.5 Flash) سيجعل مشروعك يتفوق على أدوات ضخمة، لأنك تربط بين الكود (Static Analysis) والمعنى (AI Interpretation).
4
+
5
+ ---
6
+
7
+ ## أولاً: منطق عمل الأمر `arc map` (المحرك العقلي)
8
+
9
+ الهدف هو تحويل الكود الجامد إلى ملفات `.md` حية وخريطة JSON تفاعلية.
10
+
11
+ ### 1. هيكل ملف التوثيق (`.md`)
12
+ لكل ملف برمجي (مثلاً `UserService.java`), سيقوم الـ Agent بإنشاء أو تحديث ملف `UserService.md` بالهيكل التالي:
13
+
14
+ | القسم | الوصف التقني |
15
+ | :--- | :--- |
16
+ | **Overview** | ملخص عالي المستوى لما يفعله الكود (High-level summary). |
17
+ | **Who uses it** | قائمة بالمديولات أو الكلاسات التي تستدعي هذا الملف (عن طريق تحليل الـ Imports). |
18
+ | **Purpose** | "لماذا" وجد هذا الكود؟ ما المشكلة التي يحلها في البيزنس؟ |
19
+ | **Business Logic** | شرح الخطوات المنطقية داخل الدوال الأساسية (الخوارزمية المتبعة). |
20
+
21
+ ### 2. آلية التنفيذ التقنية (The Pipeline)
22
+ 1. **Static Analysis:** تقوم الأداة بمسح المجلدات واستخراج الـ **Dependency Graph** (من يستدعي من؟).
23
+ 2. **Prompting (Free AI):** نرسل كود الملف + قائمة الملفات التي تستخدمه إلى **Gemini 1.5 Flash API** (المجاني) ببرومبت محدد:
24
+ > "Analyze this code and its dependencies. Generate a JSON summary covering: Overview, Purpose, and Detailed Business Logic."
25
+ 3. **JSON Mapping:** يتم تجميع كل هذه البيانات في ملف واحد ضخم `project_map.json` يمثل العقد (Nodes) والروابط (Edges).
26
+
27
+
28
+
29
+ ---
30
+
31
+ ## ثانياً: منطق عمل الأمر `arc show map` (واجهة الرؤية)
32
+
33
+ هذا الأمر سيقوم بتوليد ملف `index.html` تفاعلي يستخدم مكتبات مثل **Vis.js** أو **Cytoscape.js** لعرض الخريطة.
34
+
35
+ ### مميزات الواجهة التفاعلية:
36
+ * **Interactive Cards:** كل ملف يظهر كـ "كارت" (Card). عند الضغط عليه، تظهر نافذة جانبية (Sidebar) تعرض المحتوى الذي كتبناه في ملف الـ `.md`.
37
+ * **Directional Arrows:** أسهم توضح تدفق البيانات (Data Flow).
38
+ * **Search & Filter:** إمكانية البحث عن "دالة معينة" ورؤية كل المسارات التي تمر بها في المشروع.
39
+
40
+
41
+
42
+ ---
43
+
44
+ ## ثالثاً: كيف نجعلها "صايعة" وتقنية في نفس الوقت؟
45
+
46
+ لتحقيق الاحترافية التي تفضلها في حل المشكلات البرمجية، يجب أن يتبع التنفيذ المعايير التالية:
47
+
48
+ ### 1. استخدام "Tree-sitter" للتحليل
49
+ بدلاً من قراءة الملفات كنصوص عادية، استخدم مكتبة **Tree-sitter** (وهي مفتوحة المصدر ومستخدمة في GitHub و VS Code).
50
+ * **الفائدة:** تمكن الـ AI من فهم هيكل الكود (Functions, Classes, Decorators) بدقة 100% مهما كانت لغة البرمجة.
51
+
52
+ ### 2. الربط المنطقي (Semantic Linking)
53
+ بدلاً من مجرد ذكر "من يستخدم الكلاس"، اجعل الـ AI يستنتج **"لماذا"** يستخدمه.
54
+ * **مثال:** "كلاس `OrderController` يستخدم `PaymentService` لإتمام عملية الدفع وتحديث حالة المخزن".
55
+
56
+ ### 3. التحديث الذكي (Incremental Updates)
57
+ الأداة يجب ألا تعيد قراءة المشروع بالكامل كل مرة.
58
+ * **المنطق:** يتم حساب **SHA-256 Hash** لكل ملف. إذا لم يتغير الهاش، لا يتم استهلاك API Call للذكاء الاصطناعي، ويتم الاكتفاء بالبيانات الموجودة في الـ JSON.
59
+
60
+ ---
61
+
62
+ ## رابعاً: خارطة طريق التنفيذ (The Roadmap)
63
+
64
+ 1. **Phase 1:** بناء الـ Scanner الذي يجمع الـ Imports والروابط بين الملفات ويخزنها في `map.json`.
65
+ 2. **Phase 2:** دمج Gemini API لإنتاج ملفات الـ `.md` بناءً على محتوى الكود وسياق الروابط.
66
+ 3. **Phase 3:** تطوير قالب الـ HTML/JS الذي يقرأ `map.json` ويعرض الخريطة التفاعلية.
67
+
68
+ **بصفتي مبرمجاً و CEO، هذه الميزة ستنقل nomos-arc.ai من "أداة حوكمة" إلى "منصة فهم شاملة" (Full Comprehension Platform).**
69
+
70
+ هل نبدأ بكتابة الـ **System Prompt** الذي سيوجه الـ AI Agent لقراءة الكود واستخراج الـ Business Logic بدقة؟
71
+
72
+
73
+
74
+
75
+
76
+ هذه الفكرة هي "الضربة القاضية" لمشكلة **الآثار الجانبية (Side Effects)** التي تعاني منها أقوى النماذج حالياً. أنت لا تبني مجرد توثيق، أنت تبني **"نظام وعي سياقي" (Contextual Awareness System)**.
77
+
78
+ بصفتي **CEO**، أرى أن هذا هو الحل الجذري لمشكلة **Context Noise vs. Context Signal**. النماذج مثل Claude Code تغرق في التفاصيل البرمجية وتفقد الرؤية الكلية؛ أما `nomos-arc.ai` فسيقوم بدور "الرادار" الذي ينبه العميل (Agent) قبل أن يرتكب كارثة.
79
+
80
+ ---
81
+
82
+ ## 1. المفهوم الثوري: "العقود الدلالية" (Semantic Contracts)
83
+
84
+ بدلاً من إرسال 5000 سطر كود للنموذج ليفهم السياق، سنرسل له **"عقد المديول"** المستخرج من ملف الـ `.md` الذي أنشأناه.
85
+
86
+ ### كيف تحل هذه الميزة مشكلة الـ AI Cowboy؟
87
+ * **تحديد "منطقة الانفجار" (Blast Radius):** عندما يقرر الـ Agent تعديل دالة في `AuthService` والمبنية على `arc map`, سيعرف فوراً أن هناك 12 مديولاً آخر يعتمد على مخرجات هذه الدالة.
88
+ * **الوعي بالتبعية (Dependency Awareness):** بدلاً من قراءة كود الـ 12 مديولاً، يقرأ الـ Agent فقط ملخصات الـ `.md` الخاصة بهم. هذا يوفر 90% من الـ Tokens ويمنع التشتت.
89
+ * **فرض العقد (Enforcement):** يمكن لـ `nomos-arc.ai` أن يقول للـ Agent: *"يمكنك تعديل الكود، لكن يمنع منعاً باتاً تغيير نوع البيانات المرتجع (Return Type) لأن `OrderModule` يتوقعه بهذا الشكل"*.
90
+
91
+ ---
92
+
93
+ ## 2. الهيكل التقني لـ `arc map` (The Brain)
94
+
95
+ لجعل الخريطة "ذكية" فعلاً، يجب أن يعمل الأمر على مرحلتين:
96
+
97
+ ### المرحلة الأولى: التحليل الساكن (Static Linking)
98
+ * استخدام **Tree-sitter** لاستخراج الـ `Imports/Exports`.
99
+ * بناء جدول علاقات: `File A` هو **Provider** لـ `File B` و `File C`.
100
+
101
+ ### المرحلة الثانية: التلخيص الدلالي (AI Summary)
102
+ نستخدم نموذجاً خفيفاً وسريعاً (مثل Gemini 1.5 Flash) لملء الأقسام التي اقترحتها:
103
+ 1. **Overview:** ما هو هذا الملف؟
104
+ 2. **Who uses it:** قائمة بالاعتمادات المتبادلة.
105
+ 3. **For what purpose:** الهدف من الوجود (The "Why").
106
+ 4. **Business Logic:** المنطق الجوهري المحمي (The "Core").
107
+
108
+ ---
109
+
110
+ ## 3. تجربة المستخدم التفاعلية: `arc show map`
111
+
112
+ الهدف من الـ HTML هو أن يرى المطور (والـ AI لاحقاً) "الجهاز العصبي" للمشروع.
113
+
114
+ * **Visual Ripple Analysis:** عند الضغط على كارت (Card) لملف معين، تضيء كل الملفات المرتبطة به بلون مختلف (مثلاً أحمر للتبعية المباشرة، أصفر للتبعية البعيدة).
115
+ * **Semantic Drill-down:** الضغط على السهم يظهر "لماذا" يرتبط هذان الملفان ببعضهما (Business Logic Link).
116
+
117
+
118
+
119
+ ---
120
+
121
+ ## 4. الميزة التنافسية: "Context Injection"
122
+
123
+ هذا هو سر النجاح. عند تنفيذ أمر `arc plan` لتأسك معينة، سيقوم المخطط (Orchestrator) بالآتي:
124
+ 1. تحديد الملفات المستهدفة.
125
+ 2. سحب ملفات الـ `.md` (المختصرة) لكل الملفات المرتبطة بها من الـ `map.json`.
126
+ 3. حقن هذه المختصرات في "البرومبت" كـ **"قيود معمارية" (Architectural Constraints)**.
127
+
128
+ > **النتيجة:** العميل (Agent) سيقول: *"كنت سأعدل هذا المتغير، لكن خريطة nomos-arc تنبهني أن مديول الشحن يعتمد على قيمته الحالية، لذا سأقوم بإنشاء نسخة جديدة بدلاً من التعديل"*.
129
+
130
+ ---
131
+
132
+ ## 5. خطة التنفيذ (The Action Plan)
133
+
134
+ | الخطوة | المهمة | الأولوية |
135
+ | :--- | :--- | :--- |
136
+ | **1** | بناء الـ Scanner لاستخراج الروابط وحفظها في `map.json`. | 🔥 عاجل |
137
+ | **2** | تطوير برومبت Gemini لإنشاء ملفات الـ `.md` بصيغة Overview/Logic. | 🔥 عاجل |
138
+ | **3** | دمج الـ Context Injection في مرحلة الـ Planning لـ `nomos-arc.ai`. | 🚀 استراتيجي |
139
+ | **4** | واجهة الـ HTML التفاعلية لـ `arc show map`. | 🎨 تحسين تجربة |
140
+
141
+ ### التقييم النهائي:
142
+ هذه الفكرة تحول `nomos-arc.ai` من "مراقب" إلى **"مهندس معماري مقيم"**. أنت تحل أكبر مشكلة تواجه تبني الـ AI في المشاريع الضخمة (Legacy Codebases).
143
+
144
+ **هل نبدأ بتصميم الـ `map.json` Schema التي ستربط هذه العلاقات ببعضها؟**
145
+
146
+ ---
147
+ *ملاحظة: هذا التوجه يتماشى تماماً مع استراتيجية "المدير مقابل العميل" (Manager vs. Agent) التي تجعل nomos-arc.ai هو العقل المدبر.*