k0ntext 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (239) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +623 -0
  3. package/bin/k0ntext.js +12 -0
  4. package/dist/agents/cleanup-agent.d.ts +39 -0
  5. package/dist/agents/cleanup-agent.d.ts.map +1 -0
  6. package/dist/agents/cleanup-agent.js +56 -0
  7. package/dist/agents/cleanup-agent.js.map +1 -0
  8. package/dist/agents/performance-agent.d.ts +37 -0
  9. package/dist/agents/performance-agent.d.ts.map +1 -0
  10. package/dist/agents/performance-agent.js +91 -0
  11. package/dist/agents/performance-agent.js.map +1 -0
  12. package/dist/analyzer/index.d.ts +5 -0
  13. package/dist/analyzer/index.d.ts.map +1 -0
  14. package/dist/analyzer/index.js +5 -0
  15. package/dist/analyzer/index.js.map +1 -0
  16. package/dist/analyzer/intelligent-analyzer.d.ts +111 -0
  17. package/dist/analyzer/intelligent-analyzer.d.ts.map +1 -0
  18. package/dist/analyzer/intelligent-analyzer.js +537 -0
  19. package/dist/analyzer/intelligent-analyzer.js.map +1 -0
  20. package/dist/cli/commands/cleanup.d.ts +3 -0
  21. package/dist/cli/commands/cleanup.d.ts.map +1 -0
  22. package/dist/cli/commands/cleanup.js +24 -0
  23. package/dist/cli/commands/cleanup.js.map +1 -0
  24. package/dist/cli/commands/export.d.ts +9 -0
  25. package/dist/cli/commands/export.d.ts.map +1 -0
  26. package/dist/cli/commands/export.js +72 -0
  27. package/dist/cli/commands/export.js.map +1 -0
  28. package/dist/cli/commands/import.d.ts +9 -0
  29. package/dist/cli/commands/import.d.ts.map +1 -0
  30. package/dist/cli/commands/import.js +62 -0
  31. package/dist/cli/commands/import.js.map +1 -0
  32. package/dist/cli/commands/performance.d.ts +9 -0
  33. package/dist/cli/commands/performance.d.ts.map +1 -0
  34. package/dist/cli/commands/performance.js +36 -0
  35. package/dist/cli/commands/performance.js.map +1 -0
  36. package/dist/cli/commands/validate.d.ts +9 -0
  37. package/dist/cli/commands/validate.d.ts.map +1 -0
  38. package/dist/cli/commands/validate.js +82 -0
  39. package/dist/cli/commands/validate.js.map +1 -0
  40. package/dist/cli/commands/watch.d.ts +9 -0
  41. package/dist/cli/commands/watch.d.ts.map +1 -0
  42. package/dist/cli/commands/watch.js +72 -0
  43. package/dist/cli/commands/watch.js.map +1 -0
  44. package/dist/cli/generate.d.ts +3 -0
  45. package/dist/cli/generate.d.ts.map +1 -0
  46. package/dist/cli/generate.js +194 -0
  47. package/dist/cli/generate.js.map +1 -0
  48. package/dist/cli/index.d.ts +9 -0
  49. package/dist/cli/index.d.ts.map +1 -0
  50. package/dist/cli/index.js +448 -0
  51. package/dist/cli/index.js.map +1 -0
  52. package/dist/cli/sync.d.ts +26 -0
  53. package/dist/cli/sync.d.ts.map +1 -0
  54. package/dist/cli/sync.js +163 -0
  55. package/dist/cli/sync.js.map +1 -0
  56. package/dist/config/cleanup-config.d.ts +26 -0
  57. package/dist/config/cleanup-config.d.ts.map +1 -0
  58. package/dist/config/cleanup-config.js +21 -0
  59. package/dist/config/cleanup-config.js.map +1 -0
  60. package/dist/db/client.d.ts +284 -0
  61. package/dist/db/client.d.ts.map +1 -0
  62. package/dist/db/client.js +688 -0
  63. package/dist/db/client.js.map +1 -0
  64. package/dist/db/index.d.ts +6 -0
  65. package/dist/db/index.d.ts.map +1 -0
  66. package/dist/db/index.js +6 -0
  67. package/dist/db/index.js.map +1 -0
  68. package/dist/db/schema.d.ts +41 -0
  69. package/dist/db/schema.d.ts.map +1 -0
  70. package/dist/db/schema.js +226 -0
  71. package/dist/db/schema.js.map +1 -0
  72. package/dist/embeddings/index.d.ts +5 -0
  73. package/dist/embeddings/index.d.ts.map +1 -0
  74. package/dist/embeddings/index.js +5 -0
  75. package/dist/embeddings/index.js.map +1 -0
  76. package/dist/embeddings/openrouter.d.ts +133 -0
  77. package/dist/embeddings/openrouter.d.ts.map +1 -0
  78. package/dist/embeddings/openrouter.js +455 -0
  79. package/dist/embeddings/openrouter.js.map +1 -0
  80. package/dist/index.d.ts +14 -0
  81. package/dist/index.d.ts.map +1 -0
  82. package/dist/index.js +18 -0
  83. package/dist/index.js.map +1 -0
  84. package/dist/mcp.d.ts +29 -0
  85. package/dist/mcp.d.ts.map +1 -0
  86. package/dist/mcp.js +257 -0
  87. package/dist/mcp.js.map +1 -0
  88. package/docs/ARCHIVE/MIGRATE_TO_NEW_REPO.md +222 -0
  89. package/docs/ARCHIVE/MIGRATE_TO_UNIFIED.md +220 -0
  90. package/docs/CLEANUP.md +76 -0
  91. package/docs/MCP_QUICKSTART.md +219 -0
  92. package/docs/QUICKSTART.md +119 -0
  93. package/docs/TROUBLESHOOTING.md +611 -0
  94. package/package.json +100 -0
  95. package/skills/context-optimize/SKILL.md +86 -0
  96. package/skills/implement/SKILL.md +150 -0
  97. package/skills/plan/SKILL.md +143 -0
  98. package/skills/research/SKILL.md +103 -0
  99. package/skills/validate/SKILL.md +62 -0
  100. package/skills/verify-docs/SKILL.md +77 -0
  101. package/src/agents/cleanup-agent.ts +96 -0
  102. package/src/agents/performance-agent.ts +117 -0
  103. package/src/analyzer/index.ts +10 -0
  104. package/src/analyzer/intelligent-analyzer.ts +640 -0
  105. package/src/cli/commands/cleanup.ts +26 -0
  106. package/src/cli/commands/export.ts +82 -0
  107. package/src/cli/commands/import.ts +73 -0
  108. package/src/cli/commands/performance.ts +40 -0
  109. package/src/cli/commands/validate.ts +98 -0
  110. package/src/cli/commands/watch.ts +83 -0
  111. package/src/cli/generate.ts +219 -0
  112. package/src/cli/index.ts +510 -0
  113. package/src/cli/sync.ts +194 -0
  114. package/src/config/cleanup-config.ts +42 -0
  115. package/src/db/client.ts +949 -0
  116. package/src/db/index.ts +19 -0
  117. package/src/db/schema.ts +241 -0
  118. package/src/embeddings/index.ts +11 -0
  119. package/src/embeddings/openrouter.ts +592 -0
  120. package/src/index.ts +57 -0
  121. package/src/mcp.ts +354 -0
  122. package/templates/AI_CONTEXT.md.template +245 -0
  123. package/templates/base/README.md +260 -0
  124. package/templates/base/RPI_WORKFLOW_PLAN.md +325 -0
  125. package/templates/base/agents/api-developer.md +76 -0
  126. package/templates/base/agents/context-engineer.md +525 -0
  127. package/templates/base/agents/core-architect.md +76 -0
  128. package/templates/base/agents/database-ops.md +76 -0
  129. package/templates/base/agents/deployment-ops.md +76 -0
  130. package/templates/base/agents/integration-hub.md +76 -0
  131. package/templates/base/analytics/README.md +114 -0
  132. package/templates/base/automation/config.json +58 -0
  133. package/templates/base/automation/generators/code-mapper.js +308 -0
  134. package/templates/base/automation/generators/index-builder.js +321 -0
  135. package/templates/base/automation/hooks/post-commit.sh +83 -0
  136. package/templates/base/automation/hooks/pre-commit.sh +103 -0
  137. package/templates/base/ci-templates/README.md +108 -0
  138. package/templates/base/ci-templates/github-actions/context-check.yml +144 -0
  139. package/templates/base/ci-templates/github-actions/validate-docs.yml +105 -0
  140. package/templates/base/commands/analytics.md +238 -0
  141. package/templates/base/commands/auto-sync.md +172 -0
  142. package/templates/base/commands/collab.md +194 -0
  143. package/templates/base/commands/context-optimize.md +226 -0
  144. package/templates/base/commands/help.md +485 -0
  145. package/templates/base/commands/rpi-implement.md +164 -0
  146. package/templates/base/commands/rpi-plan.md +147 -0
  147. package/templates/base/commands/rpi-research.md +145 -0
  148. package/templates/base/commands/session-resume.md +144 -0
  149. package/templates/base/commands/session-save.md +112 -0
  150. package/templates/base/commands/validate-all.md +77 -0
  151. package/templates/base/commands/verify-docs-current.md +86 -0
  152. package/templates/base/config/base.json +57 -0
  153. package/templates/base/config/environments/development.json +13 -0
  154. package/templates/base/config/environments/production.json +17 -0
  155. package/templates/base/config/environments/staging.json +13 -0
  156. package/templates/base/config/local.json.example +21 -0
  157. package/templates/base/context/.meta/generated-at.json +18 -0
  158. package/templates/base/context/ARCHITECTURE_SNAPSHOT.md +156 -0
  159. package/templates/base/context/CODE_TO_WORKFLOW_MAP.md +94 -0
  160. package/templates/base/context/FILE_OWNERSHIP.md +57 -0
  161. package/templates/base/context/INTEGRATION_POINTS.md +92 -0
  162. package/templates/base/context/KNOWN_GOTCHAS.md +195 -0
  163. package/templates/base/context/TESTING_MAP.md +95 -0
  164. package/templates/base/context/WORKFLOW_INDEX.md +129 -0
  165. package/templates/base/context/workflows/WORKFLOW_TEMPLATE.md +294 -0
  166. package/templates/base/indexes/agents/CAPABILITY_MATRIX.md +255 -0
  167. package/templates/base/indexes/agents/CATEGORY_INDEX.md +44 -0
  168. package/templates/base/indexes/code/CATEGORY_INDEX.md +38 -0
  169. package/templates/base/indexes/routing/CATEGORY_INDEX.md +39 -0
  170. package/templates/base/indexes/search/CATEGORY_INDEX.md +39 -0
  171. package/templates/base/indexes/workflows/CATEGORY_INDEX.md +38 -0
  172. package/templates/base/knowledge/README.md +98 -0
  173. package/templates/base/knowledge/sessions/README.md +88 -0
  174. package/templates/base/knowledge/sessions/TEMPLATE.md +150 -0
  175. package/templates/base/knowledge/shared/decisions/0001-adopt-context-engineering.md +144 -0
  176. package/templates/base/knowledge/shared/decisions/README.md +49 -0
  177. package/templates/base/knowledge/shared/decisions/TEMPLATE.md +123 -0
  178. package/templates/base/knowledge/shared/patterns/README.md +62 -0
  179. package/templates/base/knowledge/shared/patterns/TEMPLATE.md +120 -0
  180. package/templates/base/plans/PLAN_TEMPLATE.md +316 -0
  181. package/templates/base/plans/active/.gitkeep +0 -0
  182. package/templates/base/plans/completed/.gitkeep +0 -0
  183. package/templates/base/research/RESEARCH_TEMPLATE.md +245 -0
  184. package/templates/base/research/active/.gitkeep +0 -0
  185. package/templates/base/research/completed/.gitkeep +0 -0
  186. package/templates/base/schemas/agent.schema.json +141 -0
  187. package/templates/base/schemas/anchors.schema.json +54 -0
  188. package/templates/base/schemas/automation.schema.json +93 -0
  189. package/templates/base/schemas/command.schema.json +134 -0
  190. package/templates/base/schemas/hashes.schema.json +40 -0
  191. package/templates/base/schemas/manifest.schema.json +117 -0
  192. package/templates/base/schemas/plan.schema.json +136 -0
  193. package/templates/base/schemas/research.schema.json +115 -0
  194. package/templates/base/schemas/roles.schema.json +34 -0
  195. package/templates/base/schemas/session.schema.json +77 -0
  196. package/templates/base/schemas/settings.schema.json +244 -0
  197. package/templates/base/schemas/staleness.schema.json +53 -0
  198. package/templates/base/schemas/team-config.schema.json +42 -0
  199. package/templates/base/schemas/workflow.schema.json +126 -0
  200. package/templates/base/session/checkpoints/.gitkeep +2 -0
  201. package/templates/base/session/current/state.json +20 -0
  202. package/templates/base/session/history/.gitkeep +2 -0
  203. package/templates/base/settings.json +3 -0
  204. package/templates/base/standards/COMPATIBILITY.md +219 -0
  205. package/templates/base/standards/EXTENSION_GUIDELINES.md +280 -0
  206. package/templates/base/standards/QUALITY_CHECKLIST.md +211 -0
  207. package/templates/base/standards/README.md +66 -0
  208. package/templates/base/sync/anchors.json +6 -0
  209. package/templates/base/sync/hashes.json +6 -0
  210. package/templates/base/sync/staleness.json +10 -0
  211. package/templates/base/team/README.md +168 -0
  212. package/templates/base/team/config.json +79 -0
  213. package/templates/base/team/roles.json +145 -0
  214. package/templates/base/tools/bin/claude-context.js +151 -0
  215. package/templates/base/tools/lib/anchor-resolver.js +276 -0
  216. package/templates/base/tools/lib/config-loader.js +363 -0
  217. package/templates/base/tools/lib/detector.js +350 -0
  218. package/templates/base/tools/lib/diagnose.js +206 -0
  219. package/templates/base/tools/lib/drift-detector.js +373 -0
  220. package/templates/base/tools/lib/errors.js +199 -0
  221. package/templates/base/tools/lib/index.js +36 -0
  222. package/templates/base/tools/lib/init.js +192 -0
  223. package/templates/base/tools/lib/logger.js +230 -0
  224. package/templates/base/tools/lib/placeholder.js +201 -0
  225. package/templates/base/tools/lib/session-manager.js +354 -0
  226. package/templates/base/tools/lib/validate.js +521 -0
  227. package/templates/base/tools/package.json +49 -0
  228. package/templates/handlebars/aider-config.hbs +146 -0
  229. package/templates/handlebars/antigravity.hbs +377 -0
  230. package/templates/handlebars/claude.hbs +183 -0
  231. package/templates/handlebars/cline.hbs +62 -0
  232. package/templates/handlebars/continue-config.hbs +116 -0
  233. package/templates/handlebars/copilot.hbs +130 -0
  234. package/templates/handlebars/partials/gotcha-list.hbs +11 -0
  235. package/templates/handlebars/partials/header.hbs +3 -0
  236. package/templates/handlebars/partials/workflow-summary.hbs +16 -0
  237. package/templates/handlebars/windsurf-rules.hbs +69 -0
  238. package/templates/hooks/post-commit.hbs +28 -0
  239. package/templates/hooks/pre-commit.hbs +46 -0
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Claude Context Engineering - Diagnostics Module
3
+ *
4
+ * System health diagnostics and issue detection with optional auto-fix.
5
+ */
6
+
7
+ const fs = require('fs');
8
+ const path = require('path');
9
+ const chalk = require('chalk');
10
+ const { findClaudeDir, loadJsonFile } = require('./config-loader');
11
+ const { logger } = require('./logger');
12
+ const { validate } = require('./validate');
13
+
14
+ /**
15
+ * Diagnostic procedures for common issues
16
+ */
17
+ const DIAGNOSTIC_PROCEDURES = {
18
+ 'corrupted-settings': {
19
+ name: 'Corrupted Settings',
20
+ detect: async (claudeDir) => {
21
+ const settingsPath = path.join(claudeDir, 'settings.json');
22
+ if (!fs.existsSync(settingsPath)) return false;
23
+
24
+ try {
25
+ JSON.parse(fs.readFileSync(settingsPath, 'utf8'));
26
+ return false;
27
+ } catch {
28
+ return true;
29
+ }
30
+ },
31
+ fix: async (claudeDir) => {
32
+ const settingsPath = path.join(claudeDir, 'settings.json');
33
+ const backupPath = settingsPath + '.corrupted';
34
+
35
+ // Backup corrupted file
36
+ fs.renameSync(settingsPath, backupPath);
37
+
38
+ // Create default settings
39
+ const defaults = require('./config-loader').configLoader.getDefaults();
40
+ defaults.$schema = './schemas/settings.schema.json';
41
+ defaults.version = '1.1.0';
42
+
43
+ fs.writeFileSync(settingsPath, JSON.stringify(defaults, null, 2));
44
+
45
+ return `Settings restored from defaults. Backup saved to ${backupPath}`;
46
+ },
47
+ },
48
+
49
+ 'incomplete-init': {
50
+ name: 'Incomplete Initialization',
51
+ detect: async (claudeDir) => {
52
+ const progressPath = path.join(claudeDir, 'INIT_PROGRESS.json');
53
+ if (!fs.existsSync(progressPath)) return false;
54
+
55
+ const progress = loadJsonFile(progressPath);
56
+ return progress.status !== 'COMPLETED';
57
+ },
58
+ fix: async (claudeDir) => {
59
+ console.log(chalk.yellow(' To resume initialization, run:'));
60
+ console.log(chalk.cyan(' npx claude-context init --resume'));
61
+ return 'Manual action required';
62
+ },
63
+ },
64
+
65
+ 'missing-schemas': {
66
+ name: 'Missing Schema Directory',
67
+ detect: async (claudeDir) => {
68
+ return !fs.existsSync(path.join(claudeDir, 'schemas'));
69
+ },
70
+ fix: async (claudeDir) => {
71
+ const schemaDir = path.join(claudeDir, 'schemas');
72
+ fs.mkdirSync(schemaDir, { recursive: true });
73
+ return 'Created schemas directory';
74
+ },
75
+ },
76
+
77
+ 'missing-logs-dir': {
78
+ name: 'Missing Logs Directory',
79
+ detect: async (claudeDir) => {
80
+ return !fs.existsSync(path.join(claudeDir, 'logs'));
81
+ },
82
+ fix: async (claudeDir) => {
83
+ fs.mkdirSync(path.join(claudeDir, 'logs'), { recursive: true });
84
+ return 'Created logs directory';
85
+ },
86
+ },
87
+
88
+ 'orphaned-workflows': {
89
+ name: 'Orphaned Workflow Files',
90
+ detect: async (claudeDir) => {
91
+ const indexPath = path.join(claudeDir, 'context', 'WORKFLOW_INDEX.md');
92
+ const workflowDir = path.join(claudeDir, 'context', 'workflows');
93
+
94
+ if (!fs.existsSync(indexPath) || !fs.existsSync(workflowDir)) {
95
+ return false;
96
+ }
97
+
98
+ const indexContent = fs.readFileSync(indexPath, 'utf8');
99
+ const workflowFiles = fs.readdirSync(workflowDir).filter(f => f.endsWith('.md'));
100
+
101
+ for (const wf of workflowFiles) {
102
+ const baseName = wf.replace('.md', '');
103
+ if (!indexContent.includes(baseName)) {
104
+ return true;
105
+ }
106
+ }
107
+
108
+ return false;
109
+ },
110
+ fix: async (claudeDir) => {
111
+ return 'Orphaned workflows detected. Update WORKFLOW_INDEX.md to include all workflows.';
112
+ },
113
+ },
114
+ };
115
+
116
+ /**
117
+ * Run diagnostics
118
+ */
119
+ async function diagnose(options = {}) {
120
+ const { fix = false, verbose = false } = options;
121
+ const op = logger.startOperation('diagnose');
122
+
123
+ const claudeDir = findClaudeDir();
124
+
125
+ console.log(chalk.cyan('\n🔬 Running Diagnostics...\n'));
126
+
127
+ const results = {
128
+ timestamp: new Date().toISOString(),
129
+ issues: [],
130
+ fixed: [],
131
+ suggestions: [],
132
+ };
133
+
134
+ // Run all diagnostic procedures
135
+ for (const [key, procedure] of Object.entries(DIAGNOSTIC_PROCEDURES)) {
136
+ if (verbose) {
137
+ console.log(chalk.gray(` Checking: ${procedure.name}...`));
138
+ }
139
+
140
+ try {
141
+ const detected = await procedure.detect(claudeDir);
142
+
143
+ if (detected) {
144
+ console.log(chalk.yellow(` ⚠️ Issue detected: ${procedure.name}`));
145
+
146
+ results.issues.push({
147
+ key,
148
+ name: procedure.name,
149
+ fixable: !!procedure.fix,
150
+ });
151
+
152
+ if (fix && procedure.fix) {
153
+ console.log(chalk.cyan(` Attempting fix...`));
154
+ const fixResult = await procedure.fix(claudeDir);
155
+ console.log(chalk.green(` ✓ ${fixResult}`));
156
+ results.fixed.push({ key, result: fixResult });
157
+ } else if (procedure.fix) {
158
+ console.log(chalk.gray(` Run with --fix to attempt auto-repair`));
159
+ }
160
+ } else if (verbose) {
161
+ console.log(chalk.green(` ✓ ${procedure.name}: OK`));
162
+ }
163
+ } catch (error) {
164
+ console.log(chalk.red(` ✗ Error checking ${procedure.name}: ${error.message}`));
165
+ results.issues.push({
166
+ key,
167
+ name: procedure.name,
168
+ error: error.message,
169
+ });
170
+ }
171
+ }
172
+
173
+ // Run validation as part of diagnostics
174
+ console.log(chalk.white('\nRunning validation checks...'));
175
+ const validation = await validate({ all: true, claudeDir });
176
+
177
+ if (validation.summary.failed > 0) {
178
+ results.suggestions.push('Run validation to see detailed issues: npx claude-context validate');
179
+ }
180
+
181
+ // Summary
182
+ console.log(chalk.white('\n📋 Diagnostic Summary'));
183
+ console.log(chalk.gray('─'.repeat(50)));
184
+
185
+ if (results.issues.length === 0) {
186
+ console.log(chalk.green(' ✓ No issues detected'));
187
+ } else {
188
+ console.log(chalk.yellow(` Issues found: ${results.issues.length}`));
189
+ if (results.fixed.length > 0) {
190
+ console.log(chalk.green(` Issues fixed: ${results.fixed.length}`));
191
+ }
192
+ }
193
+
194
+ if (results.suggestions.length > 0) {
195
+ console.log(chalk.white('\n💡 Suggestions:'));
196
+ results.suggestions.forEach(s => console.log(chalk.gray(` - ${s}`)));
197
+ }
198
+
199
+ op.success();
200
+ return results;
201
+ }
202
+
203
+ module.exports = {
204
+ diagnose,
205
+ DIAGNOSTIC_PROCEDURES,
206
+ };
@@ -0,0 +1,373 @@
1
+ /**
2
+ * Drift Detector - Detects documentation drift from code
3
+ *
4
+ * Compares documentation references against current code state
5
+ * to identify outdated line numbers, renamed functions, etc.
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+ const crypto = require('crypto');
11
+ const { resolveAnchor, buildFileAnchors, loadAnchors } = require('./anchor-resolver');
12
+
13
+ const SYNC_DIR = path.join(__dirname, '..', '..', 'sync');
14
+ const HASHES_PATH = path.join(SYNC_DIR, 'hashes.json');
15
+ const STALENESS_PATH = path.join(SYNC_DIR, 'staleness.json');
16
+
17
+ /**
18
+ * Drift severity levels
19
+ */
20
+ const DRIFT_LEVEL = {
21
+ NONE: 'none',
22
+ LOW: 'low', // Line number shifted slightly
23
+ MEDIUM: 'medium', // Function renamed or moved
24
+ HIGH: 'high', // Logic changed significantly
25
+ CRITICAL: 'critical' // File deleted or major restructure
26
+ };
27
+
28
+ /**
29
+ * Calculate file hash
30
+ */
31
+ function hashFile(filePath) {
32
+ try {
33
+ const content = fs.readFileSync(filePath, 'utf-8');
34
+ return crypto.createHash('md5').update(content).digest('hex');
35
+ } catch (error) {
36
+ return null;
37
+ }
38
+ }
39
+
40
+ /**
41
+ * Load stored hashes
42
+ */
43
+ function loadHashes() {
44
+ try {
45
+ if (fs.existsSync(HASHES_PATH)) {
46
+ const content = fs.readFileSync(HASHES_PATH, 'utf-8');
47
+ return JSON.parse(content);
48
+ }
49
+ } catch (error) {
50
+ console.error('Failed to load hashes:', error.message);
51
+ }
52
+ return { version: '1.0.0', files: {} };
53
+ }
54
+
55
+ /**
56
+ * Save hashes
57
+ */
58
+ function saveHashes(data) {
59
+ try {
60
+ if (!fs.existsSync(SYNC_DIR)) {
61
+ fs.mkdirSync(SYNC_DIR, { recursive: true });
62
+ }
63
+ data.generatedAt = new Date().toISOString();
64
+ fs.writeFileSync(HASHES_PATH, JSON.stringify(data, null, 2));
65
+ return true;
66
+ } catch (error) {
67
+ console.error('Failed to save hashes:', error.message);
68
+ return false;
69
+ }
70
+ }
71
+
72
+ /**
73
+ * Load staleness tracking
74
+ */
75
+ function loadStaleness() {
76
+ try {
77
+ if (fs.existsSync(STALENESS_PATH)) {
78
+ const content = fs.readFileSync(STALENESS_PATH, 'utf-8');
79
+ return JSON.parse(content);
80
+ }
81
+ } catch (error) {
82
+ console.error('Failed to load staleness:', error.message);
83
+ }
84
+ return { version: '1.0.0', workflows: {}, thresholds: { warningDays: 30, staleDays: 90 } };
85
+ }
86
+
87
+ /**
88
+ * Save staleness tracking
89
+ */
90
+ function saveStaleness(data) {
91
+ try {
92
+ if (!fs.existsSync(SYNC_DIR)) {
93
+ fs.mkdirSync(SYNC_DIR, { recursive: true });
94
+ }
95
+ fs.writeFileSync(STALENESS_PATH, JSON.stringify(data, null, 2));
96
+ return true;
97
+ } catch (error) {
98
+ console.error('Failed to save staleness:', error.message);
99
+ return false;
100
+ }
101
+ }
102
+
103
+ /**
104
+ * Check if a file has changed since last recorded
105
+ */
106
+ function checkFileChange(filePath, projectRoot = process.cwd()) {
107
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(projectRoot, filePath);
108
+ const stored = loadHashes();
109
+
110
+ if (!fs.existsSync(fullPath)) {
111
+ return {
112
+ changed: true,
113
+ level: DRIFT_LEVEL.CRITICAL,
114
+ reason: 'File not found'
115
+ };
116
+ }
117
+
118
+ const currentHash = hashFile(fullPath);
119
+ const storedData = stored.files[filePath];
120
+
121
+ if (!storedData) {
122
+ return {
123
+ changed: true,
124
+ level: DRIFT_LEVEL.LOW,
125
+ reason: 'File not previously tracked'
126
+ };
127
+ }
128
+
129
+ if (storedData.hash !== currentHash) {
130
+ return {
131
+ changed: true,
132
+ level: DRIFT_LEVEL.MEDIUM,
133
+ reason: 'File content changed',
134
+ previousHash: storedData.hash,
135
+ currentHash
136
+ };
137
+ }
138
+
139
+ return {
140
+ changed: false,
141
+ level: DRIFT_LEVEL.NONE
142
+ };
143
+ }
144
+
145
+ /**
146
+ * Extract line references from markdown content
147
+ */
148
+ function extractLineReferences(content) {
149
+ const references = [];
150
+
151
+ // file:123 format
152
+ const linePattern = /([a-zA-Z0-9_\-./]+\.[a-zA-Z0-9]+):(\d+)/g;
153
+ let match;
154
+ while ((match = linePattern.exec(content)) !== null) {
155
+ references.push({
156
+ file: match[1],
157
+ line: parseInt(match[2]),
158
+ type: 'line',
159
+ original: match[0]
160
+ });
161
+ }
162
+
163
+ // file::function() format
164
+ const anchorPattern = /([a-zA-Z0-9_\-./]+\.[a-zA-Z0-9]+)::(\w+)\(\)/g;
165
+ while ((match = anchorPattern.exec(content)) !== null) {
166
+ references.push({
167
+ file: match[1],
168
+ anchor: match[2],
169
+ type: 'anchor',
170
+ original: match[0]
171
+ });
172
+ }
173
+
174
+ return references;
175
+ }
176
+
177
+ /**
178
+ * Check drift for a workflow file
179
+ */
180
+ function checkWorkflowDrift(workflowPath, projectRoot = process.cwd()) {
181
+ const fullPath = path.isAbsolute(workflowPath)
182
+ ? workflowPath
183
+ : path.join(projectRoot, '.claude', workflowPath);
184
+
185
+ if (!fs.existsSync(fullPath)) {
186
+ return {
187
+ workflow: workflowPath,
188
+ status: 'error',
189
+ error: 'Workflow file not found'
190
+ };
191
+ }
192
+
193
+ const content = fs.readFileSync(fullPath, 'utf-8');
194
+ const references = extractLineReferences(content);
195
+ const issues = [];
196
+
197
+ for (const ref of references) {
198
+ if (ref.type === 'line') {
199
+ // Check if file exists and line is valid
200
+ const filePath = path.join(projectRoot, ref.file);
201
+
202
+ if (!fs.existsSync(filePath)) {
203
+ issues.push({
204
+ ...ref,
205
+ level: DRIFT_LEVEL.CRITICAL,
206
+ issue: 'Referenced file not found'
207
+ });
208
+ continue;
209
+ }
210
+
211
+ const fileContent = fs.readFileSync(filePath, 'utf-8');
212
+ const lines = fileContent.split('\n');
213
+
214
+ if (ref.line > lines.length) {
215
+ issues.push({
216
+ ...ref,
217
+ level: DRIFT_LEVEL.HIGH,
218
+ issue: `Line ${ref.line} exceeds file length (${lines.length} lines)`
219
+ });
220
+ }
221
+
222
+ // Check if file has changed
223
+ const changeResult = checkFileChange(ref.file, projectRoot);
224
+ if (changeResult.changed && changeResult.level !== DRIFT_LEVEL.NONE) {
225
+ issues.push({
226
+ ...ref,
227
+ level: changeResult.level,
228
+ issue: changeResult.reason
229
+ });
230
+ }
231
+ } else if (ref.type === 'anchor') {
232
+ // Resolve semantic anchor
233
+ const result = resolveAnchor(`${ref.file}::${ref.anchor}()`, projectRoot);
234
+ if (!result.success) {
235
+ issues.push({
236
+ ...ref,
237
+ level: DRIFT_LEVEL.HIGH,
238
+ issue: result.error,
239
+ availableSymbols: result.availableSymbols
240
+ });
241
+ }
242
+ }
243
+ }
244
+
245
+ // Determine overall status
246
+ let status = 'healthy';
247
+ let maxLevel = DRIFT_LEVEL.NONE;
248
+
249
+ for (const issue of issues) {
250
+ if (issue.level === DRIFT_LEVEL.CRITICAL) {
251
+ status = 'critical';
252
+ maxLevel = DRIFT_LEVEL.CRITICAL;
253
+ } else if (issue.level === DRIFT_LEVEL.HIGH && maxLevel !== DRIFT_LEVEL.CRITICAL) {
254
+ status = 'stale';
255
+ maxLevel = DRIFT_LEVEL.HIGH;
256
+ } else if (issue.level === DRIFT_LEVEL.MEDIUM && maxLevel === DRIFT_LEVEL.NONE) {
257
+ status = 'needs_update';
258
+ maxLevel = DRIFT_LEVEL.MEDIUM;
259
+ }
260
+ }
261
+
262
+ return {
263
+ workflow: workflowPath,
264
+ status,
265
+ level: maxLevel,
266
+ totalReferences: references.length,
267
+ issues,
268
+ checkedAt: new Date().toISOString()
269
+ };
270
+ }
271
+
272
+ /**
273
+ * Update file hashes for tracking
274
+ */
275
+ function updateFileHashes(filePaths, projectRoot = process.cwd()) {
276
+ const stored = loadHashes();
277
+
278
+ for (const filePath of filePaths) {
279
+ const fullPath = path.isAbsolute(filePath) ? filePath : path.join(projectRoot, filePath);
280
+ const hash = hashFile(fullPath);
281
+
282
+ if (hash) {
283
+ stored.files[filePath] = {
284
+ hash,
285
+ updatedAt: new Date().toISOString()
286
+ };
287
+ }
288
+ }
289
+
290
+ saveHashes(stored);
291
+ return stored;
292
+ }
293
+
294
+ /**
295
+ * Mark workflow as verified
296
+ */
297
+ function markWorkflowVerified(workflowPath) {
298
+ const staleness = loadStaleness();
299
+
300
+ staleness.workflows[workflowPath] = {
301
+ lastVerified: new Date().toISOString(),
302
+ status: 'verified'
303
+ };
304
+
305
+ saveStaleness(staleness);
306
+ }
307
+
308
+ /**
309
+ * Check staleness of all workflows
310
+ */
311
+ function checkStaleness() {
312
+ const staleness = loadStaleness();
313
+ const now = Date.now();
314
+ const results = [];
315
+
316
+ for (const [workflow, data] of Object.entries(staleness.workflows)) {
317
+ const lastVerified = new Date(data.lastVerified).getTime();
318
+ const daysSince = (now - lastVerified) / (1000 * 60 * 60 * 24);
319
+
320
+ let status = 'fresh';
321
+ if (daysSince > staleness.thresholds.staleDays) {
322
+ status = 'stale';
323
+ } else if (daysSince > staleness.thresholds.warningDays) {
324
+ status = 'warning';
325
+ }
326
+
327
+ results.push({
328
+ workflow,
329
+ lastVerified: data.lastVerified,
330
+ daysSince: Math.round(daysSince),
331
+ status
332
+ });
333
+ }
334
+
335
+ return results;
336
+ }
337
+
338
+ /**
339
+ * Generate drift report
340
+ */
341
+ function generateReport(workflowPaths, projectRoot = process.cwd()) {
342
+ const results = [];
343
+
344
+ for (const workflow of workflowPaths) {
345
+ const result = checkWorkflowDrift(workflow, projectRoot);
346
+ results.push(result);
347
+ }
348
+
349
+ // Summary
350
+ const summary = {
351
+ total: results.length,
352
+ healthy: results.filter(r => r.status === 'healthy').length,
353
+ needsUpdate: results.filter(r => r.status === 'needs_update').length,
354
+ stale: results.filter(r => r.status === 'stale').length,
355
+ critical: results.filter(r => r.status === 'critical').length,
356
+ generatedAt: new Date().toISOString()
357
+ };
358
+
359
+ return { summary, results };
360
+ }
361
+
362
+ module.exports = {
363
+ checkFileChange,
364
+ checkWorkflowDrift,
365
+ updateFileHashes,
366
+ markWorkflowVerified,
367
+ checkStaleness,
368
+ generateReport,
369
+ extractLineReferences,
370
+ loadHashes,
371
+ saveHashes,
372
+ DRIFT_LEVEL
373
+ };