docorbit 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 (144) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +660 -0
  3. package/apps/cli/bin/docorbit.js +8 -0
  4. package/apps/cli/src/commands/add.ts +44 -0
  5. package/apps/cli/src/commands/api.ts +38 -0
  6. package/apps/cli/src/commands/context.ts +47 -0
  7. package/apps/cli/src/commands/dashboard.ts +55 -0
  8. package/apps/cli/src/commands/diff.ts +30 -0
  9. package/apps/cli/src/commands/evaluate.ts +133 -0
  10. package/apps/cli/src/commands/examples.ts +39 -0
  11. package/apps/cli/src/commands/export.ts +89 -0
  12. package/apps/cli/src/commands/impact.ts +31 -0
  13. package/apps/cli/src/commands/init.ts +69 -0
  14. package/apps/cli/src/commands/inspect.ts +30 -0
  15. package/apps/cli/src/commands/mcp.ts +72 -0
  16. package/apps/cli/src/commands/pitfalls.ts +38 -0
  17. package/apps/cli/src/commands/recipes.ts +35 -0
  18. package/apps/cli/src/commands/search.ts +48 -0
  19. package/apps/cli/src/commands/update.ts +73 -0
  20. package/apps/cli/src/commands/verify.ts +48 -0
  21. package/apps/cli/src/formatters/colors.ts +23 -0
  22. package/apps/cli/src/formatters/inspection.ts +102 -0
  23. package/apps/cli/src/formatters/knowledge.ts +272 -0
  24. package/apps/cli/src/formatters/retrieval.ts +74 -0
  25. package/apps/cli/src/formatters/terminal.ts +6 -0
  26. package/apps/cli/src/formatters/verification.ts +126 -0
  27. package/apps/cli/src/index.ts +409 -0
  28. package/bin/docorbit.js +8 -0
  29. package/package.json +46 -0
  30. package/packages/core/src/dashboard/server.ts +314 -0
  31. package/packages/core/src/dashboard/ui.ts +586 -0
  32. package/packages/core/src/implementation-service.ts +451 -0
  33. package/packages/core/src/index.ts +7 -0
  34. package/packages/core/src/inspector.ts +71 -0
  35. package/packages/core/src/pipeline.ts +331 -0
  36. package/packages/crawler/src/config.ts +12 -0
  37. package/packages/crawler/src/fetcher.ts +185 -0
  38. package/packages/crawler/src/index.ts +2 -0
  39. package/packages/discovery/src/index.ts +31 -0
  40. package/packages/discovery/src/provider.ts +47 -0
  41. package/packages/discovery/src/providers/generic.ts +98 -0
  42. package/packages/discovery/src/providers/github.ts +61 -0
  43. package/packages/discovery/src/providers/llms-txt.ts +73 -0
  44. package/packages/discovery/src/providers/markdown.ts +48 -0
  45. package/packages/discovery/src/providers/openapi.ts +91 -0
  46. package/packages/discovery/src/providers/sitemap.ts +62 -0
  47. package/packages/discovery/src/providers/skill.ts +54 -0
  48. package/packages/discovery/src/ranker.ts +123 -0
  49. package/packages/evaluation/src/dataset.ts +963 -0
  50. package/packages/evaluation/src/index.ts +8 -0
  51. package/packages/evaluation/src/runner.ts +241 -0
  52. package/packages/evaluation/src/strategies/context7-runner.ts +269 -0
  53. package/packages/evaluation/src/strategies/docorbit-runner.ts +228 -0
  54. package/packages/evaluation/src/strategies/firecrawl-runner.ts +172 -0
  55. package/packages/evaluation/src/strategies/web-search-runner.ts +194 -0
  56. package/packages/evaluation/src/types.ts +34 -0
  57. package/packages/evaluation/src/version-matcher.ts +73 -0
  58. package/packages/export/src/agents-md.ts +200 -0
  59. package/packages/export/src/claude-md.ts +141 -0
  60. package/packages/export/src/docs-map.ts +150 -0
  61. package/packages/export/src/index.ts +6 -0
  62. package/packages/export/src/llms-txt.ts +96 -0
  63. package/packages/export/src/service.ts +250 -0
  64. package/packages/export/src/skill-md.ts +128 -0
  65. package/packages/mcp/src/index.ts +46 -0
  66. package/packages/mcp/src/resources/index.ts +189 -0
  67. package/packages/mcp/src/server.ts +278 -0
  68. package/packages/mcp/src/tools/analyze-impact.ts +74 -0
  69. package/packages/mcp/src/tools/check-api.ts +86 -0
  70. package/packages/mcp/src/tools/diff-docs.ts +68 -0
  71. package/packages/mcp/src/tools/export-context.ts +73 -0
  72. package/packages/mcp/src/tools/find-api.ts +99 -0
  73. package/packages/mcp/src/tools/find-example.ts +100 -0
  74. package/packages/mcp/src/tools/find-pitfall.ts +94 -0
  75. package/packages/mcp/src/tools/find-recipe.ts +98 -0
  76. package/packages/mcp/src/tools/get-doc.ts +130 -0
  77. package/packages/mcp/src/tools/get-docs-map.ts +64 -0
  78. package/packages/mcp/src/tools/get-version.ts +118 -0
  79. package/packages/mcp/src/tools/implementation-context.ts +88 -0
  80. package/packages/mcp/src/tools/index.ts +59 -0
  81. package/packages/mcp/src/tools/list-sources.ts +85 -0
  82. package/packages/mcp/src/tools/search-docs.ts +123 -0
  83. package/packages/mcp/src/tools/types.ts +28 -0
  84. package/packages/mcp/src/transports/http.ts +256 -0
  85. package/packages/mcp/src/transports/stdio.ts +105 -0
  86. package/packages/mcp/src/transports/types.ts +6 -0
  87. package/packages/mcp/src/types.ts +102 -0
  88. package/packages/normalizer/src/example-indexer.ts +240 -0
  89. package/packages/normalizer/src/html.ts +253 -0
  90. package/packages/normalizer/src/index.ts +8 -0
  91. package/packages/normalizer/src/llms.ts +83 -0
  92. package/packages/normalizer/src/openapi/endpoint-parser.ts +406 -0
  93. package/packages/normalizer/src/openapi/schema-resolver.ts +111 -0
  94. package/packages/normalizer/src/openapi.ts +2 -0
  95. package/packages/normalizer/src/page.ts +184 -0
  96. package/packages/normalizer/src/pitfall-extractor.ts +190 -0
  97. package/packages/normalizer/src/slicer.ts +455 -0
  98. package/packages/retrieval/src/engine.ts +120 -0
  99. package/packages/retrieval/src/index.ts +7 -0
  100. package/packages/retrieval/src/intent.ts +43 -0
  101. package/packages/retrieval/src/packer.ts +145 -0
  102. package/packages/retrieval/src/recipe-engine.ts +313 -0
  103. package/packages/retrieval/src/scorer.ts +139 -0
  104. package/packages/retrieval/src/weights.ts +31 -0
  105. package/packages/security/src/annotations.ts +112 -0
  106. package/packages/security/src/index.ts +2 -0
  107. package/packages/security/src/ssrf.ts +153 -0
  108. package/packages/shared/src/errors.ts +53 -0
  109. package/packages/shared/src/hashing.ts +23 -0
  110. package/packages/shared/src/index.ts +3 -0
  111. package/packages/shared/src/types.ts +881 -0
  112. package/packages/storage/src/db.ts +72 -0
  113. package/packages/storage/src/index.ts +11 -0
  114. package/packages/storage/src/interfaces.ts +115 -0
  115. package/packages/storage/src/repositories/api-repository.ts +219 -0
  116. package/packages/storage/src/repositories/chunk-repository.ts +316 -0
  117. package/packages/storage/src/repositories/example-repository.ts +206 -0
  118. package/packages/storage/src/repositories/page-repository.ts +205 -0
  119. package/packages/storage/src/repositories/pitfall-repository.ts +188 -0
  120. package/packages/storage/src/repositories/source-repository.ts +205 -0
  121. package/packages/storage/src/repository.ts +256 -0
  122. package/packages/storage/src/schema.ts +269 -0
  123. package/packages/storage/src/search-tokens.ts +28 -0
  124. package/packages/verification/src/diff-engine.ts +258 -0
  125. package/packages/verification/src/extractor.ts +339 -0
  126. package/packages/verification/src/impact-scanner.ts +203 -0
  127. package/packages/verification/src/index.ts +5 -0
  128. package/packages/verification/src/services.ts +238 -0
  129. package/packages/verification/src/verifier.ts +375 -0
  130. package/packages/workspace/src/detector.ts +143 -0
  131. package/packages/workspace/src/ecosystems/cargo.ts +84 -0
  132. package/packages/workspace/src/ecosystems/composer.ts +42 -0
  133. package/packages/workspace/src/ecosystems/go.ts +54 -0
  134. package/packages/workspace/src/ecosystems/index.ts +34 -0
  135. package/packages/workspace/src/ecosystems/maven.ts +34 -0
  136. package/packages/workspace/src/ecosystems/npm.ts +83 -0
  137. package/packages/workspace/src/ecosystems/pub.ts +40 -0
  138. package/packages/workspace/src/ecosystems/pypi.ts +100 -0
  139. package/packages/workspace/src/ecosystems/rubygems.ts +30 -0
  140. package/packages/workspace/src/ecosystems/types.ts +18 -0
  141. package/packages/workspace/src/index.ts +5 -0
  142. package/packages/workspace/src/lockfile.ts +194 -0
  143. package/packages/workspace/src/resolver.ts +234 -0
  144. package/packages/workspace/src/semver.ts +259 -0
@@ -0,0 +1,34 @@
1
+ import type { EcosystemStrategy } from './types.ts';
2
+ import { NpmStrategy } from './npm.ts';
3
+ import { CargoStrategy } from './cargo.ts';
4
+ import { GoStrategy } from './go.ts';
5
+ import { PyPiStrategy } from './pypi.ts';
6
+ import { ComposerStrategy } from './composer.ts';
7
+ import { RubyGemsStrategy } from './rubygems.ts';
8
+ import { PubStrategy } from './pub.ts';
9
+ import { MavenStrategy } from './maven.ts';
10
+
11
+ export type { EcosystemStrategy } from './types.ts';
12
+ export {
13
+ NpmStrategy,
14
+ CargoStrategy,
15
+ GoStrategy,
16
+ PyPiStrategy,
17
+ ComposerStrategy,
18
+ RubyGemsStrategy,
19
+ PubStrategy,
20
+ MavenStrategy,
21
+ };
22
+
23
+ export function getDefaultStrategies(): EcosystemStrategy[] {
24
+ return [
25
+ new NpmStrategy(),
26
+ new CargoStrategy(),
27
+ new GoStrategy(),
28
+ new PyPiStrategy(),
29
+ new ComposerStrategy(),
30
+ new RubyGemsStrategy(),
31
+ new PubStrategy(),
32
+ new MavenStrategy(),
33
+ ];
34
+ }
@@ -0,0 +1,34 @@
1
+ import type { ProjectDependency } from '../../../shared/src/index.ts';
2
+ import type { EcosystemStrategy } from './types.ts';
3
+
4
+ export class MavenStrategy implements EcosystemStrategy {
5
+ readonly ecosystem = 'maven';
6
+ readonly manifestNames = ['pom.xml'];
7
+
8
+ parseManifest(_fileName: string, content: string, relPath: string, packageDir: string): ProjectDependency[] {
9
+ const deps: ProjectDependency[] = [];
10
+ const depRegex = /<dependency>([\s\S]*?)<\/dependency>/g;
11
+ let match: RegExpExecArray | null;
12
+
13
+ while ((match = depRegex.exec(content)) !== null) {
14
+ const block = match[1];
15
+ const groupMatch = block.match(/<groupId>([^<]+)<\/groupId>/);
16
+ const artifactMatch = block.match(/<artifactId>([^<]+)<\/artifactId>/);
17
+ const verMatch = block.match(/<version>([^<]+)<\/version>/);
18
+
19
+ if (artifactMatch) {
20
+ const name = groupMatch ? `${groupMatch[1]}:${artifactMatch[1]}` : artifactMatch[1];
21
+ deps.push({
22
+ name,
23
+ ecosystem: 'maven',
24
+ requestedVersion: verMatch ? verMatch[1].trim() : '*',
25
+ resolvedVersion: verMatch ? verMatch[1].trim() : undefined,
26
+ sourceFile: relPath,
27
+ packagePath: packageDir,
28
+ isDev: block.includes('<scope>test</scope>'),
29
+ });
30
+ }
31
+ }
32
+ return deps;
33
+ }
34
+ }
@@ -0,0 +1,83 @@
1
+ import { join } from 'node:path';
2
+ import type { ProjectDependency } from '../../../shared/src/index.ts';
3
+ import type { EcosystemStrategy } from './types.ts';
4
+
5
+ export class NpmStrategy implements EcosystemStrategy {
6
+ readonly ecosystem = 'npm';
7
+ readonly manifestNames = ['package.json'];
8
+ readonly lockfileNames = ['package-lock.json'];
9
+
10
+ parseManifest(_fileName: string, content: string, relPath: string, packageDir: string): ProjectDependency[] {
11
+ const deps: ProjectDependency[] = [];
12
+ try {
13
+ const pkg = JSON.parse(content);
14
+
15
+ const addSection = (section: Record<string, string> | undefined, isDev: boolean) => {
16
+ if (!section) return;
17
+ for (const [name, version] of Object.entries(section)) {
18
+ deps.push({
19
+ name,
20
+ ecosystem: 'npm',
21
+ requestedVersion: String(version),
22
+ sourceFile: relPath,
23
+ packagePath: packageDir,
24
+ isDev,
25
+ });
26
+ }
27
+ };
28
+
29
+ addSection(pkg.dependencies, false);
30
+ addSection(pkg.devDependencies, true);
31
+ addSection(pkg.peerDependencies, false);
32
+ } catch {
33
+ // Malformed JSON
34
+ }
35
+ return deps;
36
+ }
37
+
38
+ parseLockfile(_fileName: string, content: string): Map<string, string> {
39
+ const resolved = new Map<string, string>();
40
+ try {
41
+ const lock = JSON.parse(content);
42
+ // npm v2/v3 lockfile format
43
+ if (lock.packages && typeof lock.packages === 'object') {
44
+ for (const [key, val] of Object.entries(lock.packages)) {
45
+ if (val && typeof val === 'object' && (val as any).version) {
46
+ const pkgName = key.replace(/^node_modules\//, '');
47
+ if (pkgName && !pkgName.includes('node_modules')) {
48
+ resolved.set(pkgName, String((val as any).version));
49
+ }
50
+ }
51
+ }
52
+ }
53
+ // npm v1 lockfile format fallback
54
+ if (lock.dependencies && typeof lock.dependencies === 'object') {
55
+ for (const [name, val] of Object.entries(lock.dependencies)) {
56
+ if (val && typeof val === 'object' && (val as any).version) {
57
+ resolved.set(name, String((val as any).version));
58
+ }
59
+ }
60
+ }
61
+ } catch {
62
+ // Malformed lockfile
63
+ }
64
+ return resolved;
65
+ }
66
+
67
+ resolveVersions(
68
+ deps: ProjectDependency[],
69
+ pkgDir: string,
70
+ lockfileCache: Map<string, Map<string, string>>
71
+ ): void {
72
+ const lockMap =
73
+ lockfileCache.get('package-lock.json') ||
74
+ lockfileCache.get(join(pkgDir, 'package-lock.json'));
75
+
76
+ if (lockMap) {
77
+ for (const dep of deps) {
78
+ const resolved = lockMap.get(dep.name);
79
+ if (resolved) dep.resolvedVersion = resolved;
80
+ }
81
+ }
82
+ }
83
+ }
@@ -0,0 +1,40 @@
1
+ import type { ProjectDependency } from '../../../shared/src/index.ts';
2
+ import type { EcosystemStrategy } from './types.ts';
3
+
4
+ export class PubStrategy implements EcosystemStrategy {
5
+ readonly ecosystem = 'pub';
6
+ readonly manifestNames = ['pubspec.yaml'];
7
+
8
+ parseManifest(_fileName: string, content: string, relPath: string, packageDir: string): ProjectDependency[] {
9
+ const deps: ProjectDependency[] = [];
10
+ const lines = content.split('\n');
11
+ let inDependencies = false;
12
+
13
+ for (const line of lines) {
14
+ const trimmed = line.trim();
15
+ if (trimmed === 'dependencies:' || trimmed === 'dev_dependencies:') {
16
+ inDependencies = true;
17
+ continue;
18
+ }
19
+ if (inDependencies && /^[a-zA-Z0-9_]+:/.test(line) && !line.startsWith(' ')) {
20
+ inDependencies = false;
21
+ continue;
22
+ }
23
+
24
+ if (inDependencies && trimmed && !trimmed.startsWith('#')) {
25
+ const match = trimmed.match(/^([a-zA-Z0-9_]+)\s*:\s*(.+)$/);
26
+ if (match && match[1] !== 'sdk' && match[1] !== 'flutter') {
27
+ deps.push({
28
+ name: match[1],
29
+ ecosystem: 'pub',
30
+ requestedVersion: match[2]?.trim() || '*',
31
+ sourceFile: relPath,
32
+ packagePath: packageDir,
33
+ isDev: false,
34
+ });
35
+ }
36
+ }
37
+ }
38
+ return deps;
39
+ }
40
+ }
@@ -0,0 +1,100 @@
1
+ import type { ProjectDependency } from '../../../shared/src/index.ts';
2
+ import type { EcosystemStrategy } from './types.ts';
3
+
4
+ export class PyPiStrategy implements EcosystemStrategy {
5
+ readonly ecosystem = 'pypi';
6
+ readonly manifestNames = ['requirements.txt', 'pyproject.toml'];
7
+
8
+ parseManifest(fileName: string, content: string, relPath: string, packageDir: string): ProjectDependency[] {
9
+ const lower = fileName.toLowerCase();
10
+ if (lower === 'requirements.txt') {
11
+ return this.parseRequirementsTxt(content, relPath, packageDir);
12
+ }
13
+ if (lower === 'pyproject.toml') {
14
+ return this.parsePyprojectToml(content, relPath, packageDir);
15
+ }
16
+ return [];
17
+ }
18
+
19
+ private parseRequirementsTxt(content: string, relPath: string, packageDir: string): ProjectDependency[] {
20
+ const deps: ProjectDependency[] = [];
21
+ const lines = content.split('\n');
22
+
23
+ for (const line of lines) {
24
+ const trimmed = line.trim();
25
+ if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('-')) continue;
26
+
27
+ // Match name and version specifier (e.g. requests==2.31.0, flask>=3.0.0, numpy)
28
+ const match = trimmed.match(/^([a-zA-Z0-9_.-]+)\s*([=><~^!].*)?$/);
29
+ if (match) {
30
+ const name = match[1];
31
+ const spec = match[2]?.trim() || '*';
32
+ const exactMatch = spec.match(/^==\s*([a-zA-Z0-9_.-]+)$/);
33
+ deps.push({
34
+ name,
35
+ ecosystem: 'pypi',
36
+ requestedVersion: spec,
37
+ resolvedVersion: exactMatch ? exactMatch[1] : undefined,
38
+ sourceFile: relPath,
39
+ packagePath: packageDir,
40
+ isDev: false,
41
+ });
42
+ }
43
+ }
44
+ return deps;
45
+ }
46
+
47
+ private parsePyprojectToml(content: string, relPath: string, packageDir: string): ProjectDependency[] {
48
+ const deps: ProjectDependency[] = [];
49
+ const lines = content.split('\n');
50
+ let inDependencies = false;
51
+
52
+ for (const line of lines) {
53
+ const trimmed = line.trim();
54
+ if (trimmed.startsWith('[') && trimmed.endsWith(']')) {
55
+ const sec = trimmed.slice(1, -1).trim();
56
+ inDependencies =
57
+ sec === 'project.dependencies' ||
58
+ sec === 'tool.poetry.dependencies' ||
59
+ sec === 'project.optional-dependencies';
60
+ continue;
61
+ }
62
+
63
+ if (inDependencies && trimmed && !trimmed.startsWith('#')) {
64
+ // Poetry format: name = "^1.2.3" or name = { version = "1.2.3" }
65
+ const eqIdx = trimmed.indexOf('=');
66
+ if (eqIdx !== -1) {
67
+ const name = trimmed.slice(0, eqIdx).trim();
68
+ if (name.toLowerCase() === 'python') continue;
69
+ const val = trimmed.slice(eqIdx + 1).trim();
70
+ let ver = '*';
71
+ const vMatch = val.match(/"([^"]+)"/);
72
+ if (vMatch) ver = vMatch[1];
73
+ deps.push({
74
+ name,
75
+ ecosystem: 'pypi',
76
+ requestedVersion: ver,
77
+ sourceFile: relPath,
78
+ packagePath: packageDir,
79
+ isDev: false,
80
+ });
81
+ } else if (trimmed.startsWith('"') || trimmed.startsWith("'")) {
82
+ // Standard PEP 621: "requests>=2.28.0",
83
+ const clean = trimmed.replace(/^[",']|[",']$/g, '');
84
+ const match = clean.match(/^([a-zA-Z0-9_.-]+)\s*([=><~^!].*)?$/);
85
+ if (match) {
86
+ deps.push({
87
+ name: match[1],
88
+ ecosystem: 'pypi',
89
+ requestedVersion: match[2]?.trim() || '*',
90
+ sourceFile: relPath,
91
+ packagePath: packageDir,
92
+ isDev: false,
93
+ });
94
+ }
95
+ }
96
+ }
97
+ }
98
+ return deps;
99
+ }
100
+ }
@@ -0,0 +1,30 @@
1
+ import type { ProjectDependency } from '../../../shared/src/index.ts';
2
+ import type { EcosystemStrategy } from './types.ts';
3
+
4
+ export class RubyGemsStrategy implements EcosystemStrategy {
5
+ readonly ecosystem = 'rubygems';
6
+ readonly manifestNames = ['gemfile'];
7
+
8
+ parseManifest(_fileName: string, content: string, relPath: string, packageDir: string): ProjectDependency[] {
9
+ const deps: ProjectDependency[] = [];
10
+ const lines = content.split('\n');
11
+
12
+ for (const line of lines) {
13
+ const trimmed = line.trim();
14
+ if (trimmed.startsWith('gem ') || trimmed.startsWith("gem\t")) {
15
+ const match = trimmed.match(/^gem\s+['"]([^'"]+)['"](?:\s*,\s*['"]([^'"]+)['"])?/);
16
+ if (match) {
17
+ deps.push({
18
+ name: match[1],
19
+ ecosystem: 'rubygems',
20
+ requestedVersion: match[2] || '*',
21
+ sourceFile: relPath,
22
+ packagePath: packageDir,
23
+ isDev: false,
24
+ });
25
+ }
26
+ }
27
+ }
28
+ return deps;
29
+ }
30
+ }
@@ -0,0 +1,18 @@
1
+ import type {
2
+ Ecosystem,
3
+ ProjectDependency,
4
+ } from '../../../shared/src/index.ts';
5
+
6
+ export interface EcosystemStrategy {
7
+ readonly ecosystem: Ecosystem;
8
+ readonly manifestNames: string[];
9
+ readonly lockfileNames?: string[];
10
+
11
+ parseManifest(fileName: string, content: string, relPath: string, packageDir: string): ProjectDependency[];
12
+ parseLockfile?(fileName: string, content: string): Map<string, string>;
13
+ resolveVersions?(
14
+ deps: ProjectDependency[],
15
+ pkgDir: string,
16
+ lockfileCache: Map<string, Map<string, string>>
17
+ ): void;
18
+ }
@@ -0,0 +1,5 @@
1
+ export * from './semver.ts';
2
+ export * from './detector.ts';
3
+ export * from './lockfile.ts';
4
+ export * from './resolver.ts';
5
+ export * from './ecosystems/index.ts';
@@ -0,0 +1,194 @@
1
+ import { readFileSync, writeFileSync, existsSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import type {
4
+ DocsLock,
5
+ LockedDoc,
6
+ WorkspaceScanResult,
7
+ ProjectDependency,
8
+ DocVersionMatch,
9
+ } from '../../shared/src/index.ts';
10
+ import type { DocOrbitRepository } from '../../storage/src/index.ts';
11
+ import { resolveDocVersion } from './semver.ts';
12
+
13
+ export const DOCS_LOCK_FILENAME = 'docs.lock';
14
+
15
+ /**
16
+ * Reads and parses docs.lock from a project directory if present.
17
+ */
18
+ export function readDocsLock(projectDir: string): DocsLock | null {
19
+ const filePath = join(projectDir, DOCS_LOCK_FILENAME);
20
+ if (!existsSync(filePath)) return null;
21
+
22
+ try {
23
+ const raw = readFileSync(filePath, 'utf-8');
24
+ const parsed = JSON.parse(raw);
25
+ if (parsed && parsed.version === 1 && typeof parsed.dependencies === 'object') {
26
+ return parsed as DocsLock;
27
+ }
28
+ } catch {
29
+ // Malformed lockfile
30
+ }
31
+ return null;
32
+ }
33
+
34
+ /**
35
+ * Deterministically writes a docs.lock file to project directory.
36
+ * Sorts dependency keys alphabetically and uses 2-space indentation.
37
+ */
38
+ export function writeDocsLock(projectDir: string, lock: DocsLock): void {
39
+ const filePath = join(projectDir, DOCS_LOCK_FILENAME);
40
+
41
+ // Sort dependency keys alphabetically
42
+ const sortedDeps: Record<string, LockedDoc> = {};
43
+ for (const key of Object.keys(lock.dependencies).sort()) {
44
+ sortedDeps[key] = lock.dependencies[key];
45
+ }
46
+
47
+ const deterministicLock: DocsLock = {
48
+ version: 1,
49
+ workspaceRoot: lock.workspaceRoot,
50
+ dependencies: sortedDeps,
51
+ };
52
+
53
+ const serialized = JSON.stringify(deterministicLock, null, 2) + '\n';
54
+ writeFileSync(filePath, serialized, 'utf-8');
55
+ }
56
+
57
+ /**
58
+ * Helper to match a project dependency to an ingested source in the repository.
59
+ */
60
+ function findMatchingSource(dep: ProjectDependency, repo: DocOrbitRepository) {
61
+ const sources = repo.listSources();
62
+ const depClean = dep.name.toLowerCase().replace(/^@[^/]+\//, ''); // e.g. @stripe/stripe-js -> stripe-js
63
+
64
+ for (const src of sources) {
65
+ const srcUrl = src.url.toLowerCase();
66
+ // Direct match: URL or metadata contains dependency name
67
+ if (
68
+ srcUrl.includes(depClean) ||
69
+ srcUrl.includes(dep.name.toLowerCase()) ||
70
+ (src.metadata && String(src.metadata.name || '').toLowerCase() === depClean)
71
+ ) {
72
+ return src;
73
+ }
74
+ }
75
+ return null;
76
+ }
77
+
78
+ /**
79
+ * Generates a DocsLock manifest from workspace scan result and repository state.
80
+ * Preserves timestamps for unchanged documentation snapshots to prevent lockfile churn.
81
+ */
82
+ export function generateDocsLock(
83
+ scanResult: WorkspaceScanResult,
84
+ repo: DocOrbitRepository,
85
+ existingLock?: DocsLock | null
86
+ ): DocsLock {
87
+ const lockedDeps: Record<string, LockedDoc> = {};
88
+ const allSnapshots = repo.listSnapshots();
89
+
90
+ // Detect duplicate package names across monorepo packages
91
+ const nameCounts = new Map<string, number>();
92
+ for (const dep of scanResult.dependencies) {
93
+ nameCounts.set(dep.name, (nameCounts.get(dep.name) || 0) + 1);
94
+ }
95
+
96
+ for (const dep of scanResult.dependencies) {
97
+ // Monorepo key disambiguation
98
+ const isMulti = (nameCounts.get(dep.name) || 0) > 1;
99
+ const depKey = isMulti && dep.packagePath && dep.packagePath !== '.'
100
+ ? `${dep.packagePath}:${dep.name}`
101
+ : dep.name;
102
+
103
+ // Check if we have documentation for this dependency
104
+ const matchingSource = findMatchingSource(dep, repo);
105
+ if (!matchingSource) continue;
106
+
107
+ // Find snapshots for matching source
108
+ const sourceSnapshots = allSnapshots.filter(s => s.sourceId === matchingSource.id);
109
+ if (sourceSnapshots.length === 0) continue;
110
+
111
+ // Gather available versions from snapshots
112
+ const versionToSnapshot = new Map<string, typeof sourceSnapshots[0]>();
113
+ for (const snap of sourceSnapshots) {
114
+ const v = snap.docVersion || 'latest';
115
+ if (!versionToSnapshot.has(v)) {
116
+ versionToSnapshot.set(v, snap);
117
+ }
118
+ }
119
+
120
+ const availableVersions = Array.from(versionToSnapshot.keys());
121
+ const projectVersion = dep.resolvedVersion || dep.requestedVersion;
122
+ const resolution = resolveDocVersion(projectVersion, availableVersions, dep.name);
123
+
124
+ const selectedSnapshot = versionToSnapshot.get(resolution.selectedDocVersion) || sourceSnapshots[0];
125
+ const snapshotHash = selectedSnapshot.snapshotHash;
126
+
127
+ // Deterministic timestamp preservation:
128
+ // If existingLock already has this dependency with identical snapshotHash and resolvedVersion, keep the timestamp
129
+ const existing = existingLock?.dependencies[depKey];
130
+ const isUnchanged =
131
+ existing &&
132
+ existing.snapshotHash === snapshotHash &&
133
+ existing.resolvedDependencyVersion === (dep.resolvedVersion || dep.requestedVersion) &&
134
+ existing.docVersion === resolution.selectedDocVersion;
135
+
136
+ const retrievedAt = isUnchanged ? existing.retrievedAt : new Date().toISOString();
137
+
138
+ lockedDeps[depKey] = {
139
+ name: dep.name,
140
+ ecosystem: dep.ecosystem,
141
+ requestedVersion: dep.requestedVersion,
142
+ resolvedDependencyVersion: dep.resolvedVersion || dep.requestedVersion,
143
+ sourceFile: dep.sourceFile,
144
+ docSourceUrl: matchingSource.url,
145
+ docVersion: resolution.selectedDocVersion,
146
+ matchType: resolution.matchType,
147
+ confidence: resolution.confidence,
148
+ snapshotId: selectedSnapshot.id,
149
+ snapshotHash,
150
+ retrievedAt,
151
+ };
152
+ }
153
+
154
+ return {
155
+ version: 1,
156
+ workspaceRoot: scanResult.workspaceRoot,
157
+ dependencies: lockedDeps,
158
+ };
159
+ }
160
+
161
+ /**
162
+ * Selectively or globally updates docs.lock for a project.
163
+ */
164
+ export function updateDocsLock(
165
+ scanResult: WorkspaceScanResult,
166
+ repo: DocOrbitRepository,
167
+ existingLock: DocsLock,
168
+ specificDependency?: string
169
+ ): DocsLock {
170
+ if (!specificDependency) {
171
+ // Full update: regenerate with existing lock as baseline for unchanged items
172
+ return generateDocsLock(scanResult, repo, existingLock);
173
+ }
174
+
175
+ // Selective update: only force refresh of specific dependency
176
+ const updated = generateDocsLock(scanResult, repo, existingLock);
177
+ const resultDeps = { ...existingLock.dependencies };
178
+
179
+ for (const [key, doc] of Object.entries(updated.dependencies)) {
180
+ if (doc.name === specificDependency || key === specificDependency) {
181
+ // Force new timestamp for the target dependency being updated
182
+ resultDeps[key] = {
183
+ ...doc,
184
+ retrievedAt: new Date().toISOString(),
185
+ };
186
+ }
187
+ }
188
+
189
+ return {
190
+ version: 1,
191
+ workspaceRoot: scanResult.workspaceRoot,
192
+ dependencies: resultDeps,
193
+ };
194
+ }