learn-anything-cli 0.3.0 → 0.4.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.
- package/README.md +6 -0
- package/README.zh-CN.md +6 -0
- package/dist/cli/index.js +3 -0
- package/dist/core/init.d.ts +6 -0
- package/dist/core/init.js +67 -2
- package/dist/core/learn-protocol/index.d.ts +8 -0
- package/dist/core/learn-protocol/index.js +5 -0
- package/dist/core/learn-protocol/migrate.d.ts +52 -0
- package/dist/core/learn-protocol/migrate.js +259 -0
- package/dist/core/learn-protocol/parser.d.ts +33 -0
- package/dist/core/learn-protocol/parser.js +150 -0
- package/dist/core/learn-protocol/schema.d.ts +38 -0
- package/dist/core/learn-protocol/schema.js +43 -0
- package/dist/core/learn-protocol/slug.d.ts +13 -0
- package/dist/core/learn-protocol/slug.js +28 -0
- package/dist/core/learn-protocol/types.d.ts +63 -0
- package/dist/core/learn-protocol/types.js +2 -0
- package/dist/core/templates/context7-guidance.d.ts +13 -0
- package/dist/core/templates/context7-guidance.js +24 -0
- package/dist/core/templates/workflows/learn-explain.js +56 -139
- package/dist/core/templates/workflows/learn-practice.js +88 -284
- package/dist/core/templates/workflows/learn-review.js +35 -93
- package/dist/core/templates/workflows/learn-status.js +26 -69
- package/dist/core/templates/workflows/learn-topic.js +73 -82
- package/dist/i18n/locales/en.js +4 -0
- package/dist/i18n/locales/zh-CN.js +4 -0
- package/dist/i18n/types.d.ts +4 -0
- package/dist/scripts/render.d.mts +13 -0
- package/dist/scripts/render.mjs +112 -0
- package/dist/scripts/status.d.mts +31 -0
- package/dist/scripts/status.mjs +418 -0
- package/dist/scripts/utils.d.mts +43 -0
- package/dist/scripts/utils.mjs +124 -0
- package/package.json +4 -1
package/README.md
CHANGED
|
@@ -23,6 +23,12 @@ npm install -g learn-anything-cli
|
|
|
23
23
|
learn-anything init
|
|
24
24
|
```
|
|
25
25
|
|
|
26
|
+
### Context7 Integration (Optional)
|
|
27
|
+
|
|
28
|
+
When running `init` or `update`, you'll be prompted to enable **Context7** for documentation verification. When enabled, the AI will fetch official documentation and verify its explanations against authoritative sources — improving teaching accuracy.
|
|
29
|
+
|
|
30
|
+
If you haven't set up Context7 yet, run `npx ctx7 setup` or visit the [Context7 docs](https://context7.com/docs/resources/all-clients) for your specific AI tool.
|
|
31
|
+
|
|
26
32
|
After init, your AI assistant gains five learning commands:
|
|
27
33
|
|
|
28
34
|
| Command | What it does |
|
package/README.zh-CN.md
CHANGED
|
@@ -21,6 +21,12 @@ npm install -g learn-anything-cli
|
|
|
21
21
|
learn-anything init
|
|
22
22
|
```
|
|
23
23
|
|
|
24
|
+
### Context7 集成(可选)
|
|
25
|
+
|
|
26
|
+
在执行 `init` 或 `update` 时,会提示是否启用 **Context7** 文档验证。启用后,AI 会获取官方文档并对照权威来源验证其教学内容——提高教学准确性。
|
|
27
|
+
|
|
28
|
+
如果你还没有配置 Context7,运行 `npx ctx7 setup` 或访问 [Context7 文档](https://context7.com/docs/resources/all-clients) 查看你使用的 AI 工具的配置方式。
|
|
29
|
+
|
|
24
30
|
初始化后,你的 AI 助手获得五个学习命令:
|
|
25
31
|
|
|
26
32
|
| 命令 | 功能 |
|
package/dist/cli/index.js
CHANGED
|
@@ -24,6 +24,8 @@ program
|
|
|
24
24
|
.option('--tools <tools>', m.cli.toolsOptionDescription(availableToolIds.join(', ')))
|
|
25
25
|
.option('--force', m.cli.forceOption)
|
|
26
26
|
.option('--lang <locale>', m.cli.langOption)
|
|
27
|
+
.option('--context7', 'Enable Context7 documentation verification')
|
|
28
|
+
.option('--no-context7', 'Disable Context7 documentation verification')
|
|
27
29
|
.action(async (targetPath = '.', options) => {
|
|
28
30
|
const cliLocale = resolveLocale(options?.lang);
|
|
29
31
|
const mc = cliLocale !== earlyLocale ? getMessages(cliLocale).cli : m.cli;
|
|
@@ -51,6 +53,7 @@ program
|
|
|
51
53
|
tools: options?.tools,
|
|
52
54
|
force: options?.force,
|
|
53
55
|
locale: cliLocale,
|
|
56
|
+
context7: options?.context7,
|
|
54
57
|
});
|
|
55
58
|
await initCommand.execute(targetPath);
|
|
56
59
|
}
|
package/dist/core/init.d.ts
CHANGED
|
@@ -4,18 +4,24 @@ type InitCommandOptions = {
|
|
|
4
4
|
force?: boolean;
|
|
5
5
|
locale?: SupportedLocale;
|
|
6
6
|
update?: boolean;
|
|
7
|
+
context7?: boolean;
|
|
7
8
|
};
|
|
8
9
|
export declare class InitCommand {
|
|
9
10
|
private readonly toolsArg?;
|
|
10
11
|
private readonly force;
|
|
11
12
|
private readonly locale;
|
|
12
13
|
private readonly isUpdate;
|
|
14
|
+
private readonly context7Arg?;
|
|
15
|
+
private context7Enabled;
|
|
13
16
|
constructor(options?: InitCommandOptions);
|
|
14
17
|
execute(targetPath?: string): Promise<void>;
|
|
18
|
+
private promptContext7;
|
|
15
19
|
private detectTools;
|
|
16
20
|
private hasToolDir;
|
|
17
21
|
private interactiveSelect;
|
|
18
22
|
private generateSkillsForTool;
|
|
23
|
+
/** Read a compiled script from dist/scripts/ (bundled alongside this module). */
|
|
24
|
+
private readCompiledScript;
|
|
19
25
|
private generateCommandsForTool;
|
|
20
26
|
}
|
|
21
27
|
export {};
|
package/dist/core/init.js
CHANGED
|
@@ -2,12 +2,14 @@ import path from 'path';
|
|
|
2
2
|
import chalk from 'chalk';
|
|
3
3
|
import * as fs from 'fs';
|
|
4
4
|
import { createRequire } from 'module';
|
|
5
|
+
import { fileURLToPath } from 'url';
|
|
5
6
|
import { FileSystemUtils } from '../utils/file-system.js';
|
|
6
7
|
import { AI_TOOLS, LEARN_DIR } from './config.js';
|
|
7
8
|
import { isInteractive } from '../utils/interactive.js';
|
|
8
9
|
import { generateCommands, CommandAdapterRegistry } from './command-generation/index.js';
|
|
9
10
|
import { getSkillTemplates, getCommandContents, generateSkillContent } from './shared/index.js';
|
|
10
11
|
import { getMessages } from '../i18n/index.js';
|
|
12
|
+
import { CONTEXT7_GUIDANCE } from './templates/context7-guidance.js';
|
|
11
13
|
const require = createRequire(import.meta.url);
|
|
12
14
|
const { version: VERSION } = require('../../package.json');
|
|
13
15
|
export class InitCommand {
|
|
@@ -15,11 +17,14 @@ export class InitCommand {
|
|
|
15
17
|
force;
|
|
16
18
|
locale;
|
|
17
19
|
isUpdate;
|
|
20
|
+
context7Arg;
|
|
21
|
+
context7Enabled = false;
|
|
18
22
|
constructor(options = {}) {
|
|
19
23
|
this.toolsArg = options.tools;
|
|
20
24
|
this.force = options.force ?? false;
|
|
21
25
|
this.locale = options.locale ?? 'en';
|
|
22
26
|
this.isUpdate = options.update ?? false;
|
|
27
|
+
this.context7Arg = options.context7;
|
|
23
28
|
}
|
|
24
29
|
async execute(targetPath = '.') {
|
|
25
30
|
const resolvedPath = path.resolve(targetPath);
|
|
@@ -28,7 +33,14 @@ export class InitCommand {
|
|
|
28
33
|
await FileSystemUtils.ensureDir(resolvedPath);
|
|
29
34
|
// Create .learn/ directory in the target project
|
|
30
35
|
const learnDir = path.join(resolvedPath, LEARN_DIR);
|
|
31
|
-
|
|
36
|
+
const topicsDir = path.join(learnDir, 'topics');
|
|
37
|
+
await FileSystemUtils.ensureDir(topicsDir);
|
|
38
|
+
// Run v0→v1 migration for any existing learning data
|
|
39
|
+
const { migrateAll } = await import('./learn-protocol/index.js');
|
|
40
|
+
const report = await migrateAll(topicsDir);
|
|
41
|
+
if (report.migratedCount > 0) {
|
|
42
|
+
console.log(chalk.green(m.init.migrationComplete(report.migratedCount)));
|
|
43
|
+
}
|
|
32
44
|
console.log(chalk.bold(m.init.header));
|
|
33
45
|
// Detect available tools
|
|
34
46
|
const availableTools = await this.detectTools(resolvedPath);
|
|
@@ -59,6 +71,12 @@ export class InitCommand {
|
|
|
59
71
|
.join(', '))));
|
|
60
72
|
return;
|
|
61
73
|
}
|
|
74
|
+
// Context7 setup
|
|
75
|
+
this.context7Enabled = await this.promptContext7();
|
|
76
|
+
if (this.context7Enabled) {
|
|
77
|
+
console.log(chalk.dim(m.init.context7Enabled));
|
|
78
|
+
}
|
|
79
|
+
console.log('');
|
|
62
80
|
// Generate skill files for each tool
|
|
63
81
|
for (const tool of selectedTools) {
|
|
64
82
|
if (!tool.skillsDir)
|
|
@@ -79,6 +97,21 @@ export class InitCommand {
|
|
|
79
97
|
console.log(cmd(chalk.cyan('/learn:review [topic-name]'), chalk.dim(' — Review progress, spaced repetition recommendations')));
|
|
80
98
|
console.log(cmd(chalk.cyan('/learn:status [topic-name]'), chalk.dim(' — Visualize learning state as knowledge map heatmap')));
|
|
81
99
|
console.log('');
|
|
100
|
+
if (this.context7Enabled) {
|
|
101
|
+
console.log(chalk.dim(m.init.context7SetupHint));
|
|
102
|
+
console.log('');
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
async promptContext7() {
|
|
106
|
+
const m = getMessages(this.locale);
|
|
107
|
+
if (this.context7Arg === true)
|
|
108
|
+
return true;
|
|
109
|
+
if (this.context7Arg === false)
|
|
110
|
+
return false;
|
|
111
|
+
if (!isInteractive())
|
|
112
|
+
return true;
|
|
113
|
+
const { confirm } = await import('@inquirer/prompts');
|
|
114
|
+
return confirm({ message: m.init.context7Prompt, default: true });
|
|
82
115
|
}
|
|
83
116
|
async detectTools(_resolvedPath) {
|
|
84
117
|
return AI_TOOLS;
|
|
@@ -117,10 +150,31 @@ export class InitCommand {
|
|
|
117
150
|
for (const entry of skillTemplates) {
|
|
118
151
|
const skillDir = path.join(resolvedPath, tool.skillsDir, 'skills', entry.dirName);
|
|
119
152
|
const skillFile = path.join(skillDir, 'SKILL.md');
|
|
120
|
-
const content = generateSkillContent(entry.template, VERSION)
|
|
153
|
+
const content = generateSkillContent(entry.template, VERSION, this.context7Enabled && isDocVerificationTemplate(entry.workflowId)
|
|
154
|
+
? injectContext7Guidance
|
|
155
|
+
: undefined);
|
|
121
156
|
await FileSystemUtils.writeFile(skillFile, content);
|
|
157
|
+
const scriptsDir = path.join(skillDir, 'scripts');
|
|
158
|
+
// topic / explain / practice → utils.mjs + render.mjs
|
|
159
|
+
if (entry.dirName === 'learn-anything-topic' ||
|
|
160
|
+
entry.dirName === 'learn-anything-explain' ||
|
|
161
|
+
entry.dirName === 'learn-anything-practice') {
|
|
162
|
+
await FileSystemUtils.writeFile(path.join(scriptsDir, 'utils.mjs'), this.readCompiledScript('utils.mjs'));
|
|
163
|
+
await FileSystemUtils.writeFile(path.join(scriptsDir, 'render.mjs'), this.readCompiledScript('render.mjs'));
|
|
164
|
+
}
|
|
165
|
+
// status → utils.mjs + status.mjs
|
|
166
|
+
if (entry.dirName === 'learn-anything-status') {
|
|
167
|
+
await FileSystemUtils.writeFile(path.join(scriptsDir, 'utils.mjs'), this.readCompiledScript('utils.mjs'));
|
|
168
|
+
await FileSystemUtils.writeFile(path.join(scriptsDir, 'status.mjs'), this.readCompiledScript('status.mjs'));
|
|
169
|
+
}
|
|
170
|
+
// review → no scripts needed
|
|
122
171
|
}
|
|
123
172
|
}
|
|
173
|
+
/** Read a compiled script from dist/scripts/ (bundled alongside this module). */
|
|
174
|
+
readCompiledScript(filename) {
|
|
175
|
+
const scriptPath = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', 'scripts', filename);
|
|
176
|
+
return fs.readFileSync(scriptPath, 'utf-8');
|
|
177
|
+
}
|
|
124
178
|
async generateCommandsForTool(resolvedPath, tool) {
|
|
125
179
|
const adapter = CommandAdapterRegistry.get(tool.value);
|
|
126
180
|
if (!adapter)
|
|
@@ -133,4 +187,15 @@ export class InitCommand {
|
|
|
133
187
|
}
|
|
134
188
|
}
|
|
135
189
|
}
|
|
190
|
+
const DOC_VERIFICATION_WORKFLOWS = new Set(['topic', 'explain', 'practice']);
|
|
191
|
+
function isDocVerificationTemplate(workflowId) {
|
|
192
|
+
return DOC_VERIFICATION_WORKFLOWS.has(workflowId);
|
|
193
|
+
}
|
|
194
|
+
function injectContext7Guidance(instructions) {
|
|
195
|
+
const marker = '\n## Command:';
|
|
196
|
+
const index = instructions.indexOf(marker);
|
|
197
|
+
if (index === -1)
|
|
198
|
+
return instructions + CONTEXT7_GUIDANCE;
|
|
199
|
+
return instructions.slice(0, index) + CONTEXT7_GUIDANCE + instructions.slice(index);
|
|
200
|
+
}
|
|
136
201
|
//# sourceMappingURL=init.js.map
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export type { ConceptStatus, Concept, Domain, StateV1, Detail, V0Concept, V0State, ParsedConcept, ParsedDomain, ParsedKnowledgeMap, } from './types.js';
|
|
2
|
+
export { stateV1Schema, validateStateV1 } from './schema.js';
|
|
3
|
+
export type { StateV1Schema, ValidationResult } from './schema.js';
|
|
4
|
+
export { generateSlug } from './slug.js';
|
|
5
|
+
export { parseKnowledgeMap } from './parser.js';
|
|
6
|
+
export { isV0State, migrateV0ToV1, migrateAll } from './migrate.js';
|
|
7
|
+
export type { MigrationResult, MigrationReport } from './migrate.js';
|
|
8
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v0 -> v1 migration logic.
|
|
3
|
+
*
|
|
4
|
+
* Detects v0 state.yaml format and merges it with knowledge-map.md
|
|
5
|
+
* to produce a state.json v1 file. Migration is idempotent and
|
|
6
|
+
* creates .bak backups before writing.
|
|
7
|
+
*
|
|
8
|
+
* Migration chain:
|
|
9
|
+
* state.yaml (v0) + knowledge-map.md (v0)
|
|
10
|
+
* -> migrateV0ToV1()
|
|
11
|
+
* -> state.json (v1) + state.yaml.v0.bak + knowledge-map.md.v0.bak
|
|
12
|
+
*/
|
|
13
|
+
import type { V0State } from './types.js';
|
|
14
|
+
/**
|
|
15
|
+
* Check if a parsed YAML object matches the v0 state format.
|
|
16
|
+
*
|
|
17
|
+
* v0 is identified by having `topic` and `concepts` fields but
|
|
18
|
+
* NO `version` field. Returns `true` when the data matches v0.
|
|
19
|
+
*/
|
|
20
|
+
export declare function isV0State(data: unknown): data is V0State;
|
|
21
|
+
export interface MigrationResult {
|
|
22
|
+
migrated: boolean;
|
|
23
|
+
topic: string;
|
|
24
|
+
reason?: 'already_migrated' | 'already_v1' | 'not_v0' | 'no_state_yaml' | 'error';
|
|
25
|
+
error?: string;
|
|
26
|
+
}
|
|
27
|
+
export interface MigrationReport {
|
|
28
|
+
migratedCount: number;
|
|
29
|
+
skippedCount: number;
|
|
30
|
+
results: MigrationResult[];
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Migrate a single topic directory from v0 to v1.
|
|
34
|
+
*
|
|
35
|
+
* Reads `state.yaml` and `knowledge-map.md`, merges them into `state.json`,
|
|
36
|
+
* and creates `.bak` backup files. Idempotent — skips if already migrated.
|
|
37
|
+
*
|
|
38
|
+
* @param topicDir — Absolute path to the topic directory (e.g. `.learn/topics/javascript`)
|
|
39
|
+
* @returns A MigrationResult describing what happened
|
|
40
|
+
*/
|
|
41
|
+
export declare function migrateV0ToV1(topicDir: string): Promise<MigrationResult>;
|
|
42
|
+
/**
|
|
43
|
+
* Migrate ALL topics under a base directory from v0 to v1.
|
|
44
|
+
*
|
|
45
|
+
* Scans `.learn/topics/` for topic subdirectories and runs
|
|
46
|
+
* migrateV0ToV1 on each one. Returns a summary report.
|
|
47
|
+
*
|
|
48
|
+
* @param baseDir — Path to the topics directory (e.g. `.learn/topics`)
|
|
49
|
+
* @returns MigrationReport with counts and per-topic results
|
|
50
|
+
*/
|
|
51
|
+
export declare function migrateAll(baseDir: string): Promise<MigrationReport>;
|
|
52
|
+
//# sourceMappingURL=migrate.d.ts.map
|
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* v0 -> v1 migration logic.
|
|
3
|
+
*
|
|
4
|
+
* Detects v0 state.yaml format and merges it with knowledge-map.md
|
|
5
|
+
* to produce a state.json v1 file. Migration is idempotent and
|
|
6
|
+
* creates .bak backups before writing.
|
|
7
|
+
*
|
|
8
|
+
* Migration chain:
|
|
9
|
+
* state.yaml (v0) + knowledge-map.md (v0)
|
|
10
|
+
* -> migrateV0ToV1()
|
|
11
|
+
* -> state.json (v1) + state.yaml.v0.bak + knowledge-map.md.v0.bak
|
|
12
|
+
*/
|
|
13
|
+
import { promises as fs } from 'fs';
|
|
14
|
+
import path from 'path';
|
|
15
|
+
import { parse as parseYaml } from 'yaml';
|
|
16
|
+
import { parseKnowledgeMap } from './parser.js';
|
|
17
|
+
import { generateSlug } from './slug.js';
|
|
18
|
+
import { stateV1Schema } from './schema.js';
|
|
19
|
+
import { render } from '../../scripts/render.mjs';
|
|
20
|
+
import { FileSystemUtils } from '../../utils/file-system.js';
|
|
21
|
+
// ---- Public API ---------------------------------------------------------
|
|
22
|
+
/**
|
|
23
|
+
* Check if a parsed YAML object matches the v0 state format.
|
|
24
|
+
*
|
|
25
|
+
* v0 is identified by having `topic` and `concepts` fields but
|
|
26
|
+
* NO `version` field. Returns `true` when the data matches v0.
|
|
27
|
+
*/
|
|
28
|
+
export function isV0State(data) {
|
|
29
|
+
if (!data || typeof data !== 'object')
|
|
30
|
+
return false;
|
|
31
|
+
const obj = data;
|
|
32
|
+
// v0: has topic (string) and concepts (array), no version field
|
|
33
|
+
if (typeof obj.topic !== 'string' || !obj.topic)
|
|
34
|
+
return false;
|
|
35
|
+
if (!Array.isArray(obj.concepts))
|
|
36
|
+
return false;
|
|
37
|
+
if (obj.version !== undefined)
|
|
38
|
+
return false;
|
|
39
|
+
return true;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Migrate a single topic directory from v0 to v1.
|
|
43
|
+
*
|
|
44
|
+
* Reads `state.yaml` and `knowledge-map.md`, merges them into `state.json`,
|
|
45
|
+
* and creates `.bak` backup files. Idempotent — skips if already migrated.
|
|
46
|
+
*
|
|
47
|
+
* @param topicDir — Absolute path to the topic directory (e.g. `.learn/topics/javascript`)
|
|
48
|
+
* @returns A MigrationResult describing what happened
|
|
49
|
+
*/
|
|
50
|
+
export async function migrateV0ToV1(topicDir) {
|
|
51
|
+
const stateYamlPath = path.join(topicDir, 'state.yaml');
|
|
52
|
+
const knowledgeMapPath = path.join(topicDir, 'knowledge-map.md');
|
|
53
|
+
const stateJsonPath = path.join(topicDir, 'state.json');
|
|
54
|
+
const stateYamlBackup = path.join(topicDir, 'state.yaml.v0.bak');
|
|
55
|
+
const knowledgeMapBackup = path.join(topicDir, 'knowledge-map.md.v0.bak');
|
|
56
|
+
// 1. Skip if state.json already exists (already migrated)
|
|
57
|
+
if (await FileSystemUtils.fileExists(stateJsonPath)) {
|
|
58
|
+
try {
|
|
59
|
+
const existing = JSON.parse(await fs.readFile(stateJsonPath, 'utf-8'));
|
|
60
|
+
return {
|
|
61
|
+
migrated: false,
|
|
62
|
+
topic: existing.topic || path.basename(topicDir),
|
|
63
|
+
reason: 'already_migrated',
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
return {
|
|
68
|
+
migrated: false,
|
|
69
|
+
topic: path.basename(topicDir),
|
|
70
|
+
reason: 'already_migrated',
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
// 2. Check state.yaml exists
|
|
75
|
+
if (!(await FileSystemUtils.fileExists(stateYamlPath))) {
|
|
76
|
+
return {
|
|
77
|
+
migrated: false,
|
|
78
|
+
topic: path.basename(topicDir),
|
|
79
|
+
reason: 'no_state_yaml',
|
|
80
|
+
};
|
|
81
|
+
}
|
|
82
|
+
// 3. Read and parse state.yaml
|
|
83
|
+
let v0Data;
|
|
84
|
+
try {
|
|
85
|
+
const yamlContent = await fs.readFile(stateYamlPath, 'utf-8');
|
|
86
|
+
v0Data = parseYaml(yamlContent);
|
|
87
|
+
}
|
|
88
|
+
catch (err) {
|
|
89
|
+
return {
|
|
90
|
+
migrated: false,
|
|
91
|
+
topic: path.basename(topicDir),
|
|
92
|
+
reason: 'error',
|
|
93
|
+
error: `Failed to parse state.yaml: ${err.message}`,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
// 4. Check v0 format (has topic + concepts, no version field)
|
|
97
|
+
if (!isV0State(v0Data)) {
|
|
98
|
+
return {
|
|
99
|
+
migrated: false,
|
|
100
|
+
topic: path.basename(topicDir),
|
|
101
|
+
reason: 'not_v0',
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
const v0State = v0Data;
|
|
105
|
+
// 7. Read and parse knowledge-map.md
|
|
106
|
+
let parsedMap;
|
|
107
|
+
if (await FileSystemUtils.fileExists(knowledgeMapPath)) {
|
|
108
|
+
try {
|
|
109
|
+
const kmContent = await fs.readFile(knowledgeMapPath, 'utf-8');
|
|
110
|
+
parsedMap = parseKnowledgeMap(kmContent);
|
|
111
|
+
}
|
|
112
|
+
catch (err) {
|
|
113
|
+
return {
|
|
114
|
+
migrated: false,
|
|
115
|
+
topic: v0State.topic,
|
|
116
|
+
reason: 'error',
|
|
117
|
+
error: `Failed to parse knowledge-map.md: ${err.message}`,
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
// Without knowledge-map.md we can't build the hierarchy; skip
|
|
123
|
+
return {
|
|
124
|
+
migrated: false,
|
|
125
|
+
topic: v0State.topic,
|
|
126
|
+
reason: 'error',
|
|
127
|
+
error: 'knowledge-map.md not found',
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
// 8. Merge: build a lookup from v0 path -> V0Concept
|
|
131
|
+
const conceptLookup = new Map();
|
|
132
|
+
for (const c of v0State.concepts) {
|
|
133
|
+
conceptLookup.set(c.path, c);
|
|
134
|
+
}
|
|
135
|
+
// 9. Build StateV1 from parsed hierarchy + v0 state data
|
|
136
|
+
const domains = parsedMap.domains.map((pd) => ({
|
|
137
|
+
name: pd.name,
|
|
138
|
+
slug: generateSlug(pd.name),
|
|
139
|
+
concepts: pd.concepts.map((pc) => {
|
|
140
|
+
const v0Path = `${pd.name}/${pc.name}`;
|
|
141
|
+
const v0Concept = conceptLookup.get(v0Path);
|
|
142
|
+
return {
|
|
143
|
+
name: pc.name,
|
|
144
|
+
slug: generateSlug(pc.name),
|
|
145
|
+
status: mapStatus(v0Concept?.status),
|
|
146
|
+
confidence: v0Concept?.confidence ?? 0,
|
|
147
|
+
practice_count: v0Concept?.practice_count ?? 0,
|
|
148
|
+
explain_count: v0Concept?.explain_count ?? 0,
|
|
149
|
+
last_explained: v0Concept?.last_session ?? null,
|
|
150
|
+
last_practiced: v0Concept?.last_practiced ?? null,
|
|
151
|
+
details: pc.children,
|
|
152
|
+
};
|
|
153
|
+
}),
|
|
154
|
+
}));
|
|
155
|
+
const stateV1 = {
|
|
156
|
+
version: 1,
|
|
157
|
+
topic: v0State.topic,
|
|
158
|
+
slug: generateSlug(v0State.topic),
|
|
159
|
+
created: v0State.created,
|
|
160
|
+
domains,
|
|
161
|
+
};
|
|
162
|
+
// 10. Validate the generated state against the schema
|
|
163
|
+
const validation = stateV1Schema.safeParse(stateV1);
|
|
164
|
+
if (!validation.success) {
|
|
165
|
+
return {
|
|
166
|
+
migrated: false,
|
|
167
|
+
topic: v0State.topic,
|
|
168
|
+
reason: 'error',
|
|
169
|
+
error: `Generated state.json failed validation: ${validation.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join('; ')}`,
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
// 11. Write state.json
|
|
173
|
+
try {
|
|
174
|
+
await FileSystemUtils.writeFile(stateJsonPath, JSON.stringify(stateV1, null, 2) + '\n');
|
|
175
|
+
}
|
|
176
|
+
catch (err) {
|
|
177
|
+
return {
|
|
178
|
+
migrated: false,
|
|
179
|
+
topic: v0State.topic,
|
|
180
|
+
reason: 'error',
|
|
181
|
+
error: `Failed to write state.json: ${err.message}`,
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
// 12. Create backup files, then remove originals
|
|
185
|
+
// After migration, state.json is the single source of truth,
|
|
186
|
+
// so the v0 files should not remain alongside it.
|
|
187
|
+
try {
|
|
188
|
+
await fs.copyFile(stateYamlPath, stateYamlBackup);
|
|
189
|
+
await fs.copyFile(knowledgeMapPath, knowledgeMapBackup);
|
|
190
|
+
await fs.rm(stateYamlPath, { force: true });
|
|
191
|
+
await fs.rm(knowledgeMapPath, { force: true });
|
|
192
|
+
}
|
|
193
|
+
catch (err) {
|
|
194
|
+
// Backup/cleanup failure is non-fatal — state.json was already written
|
|
195
|
+
console.error(`Warning: Failed to create backup files or clean up originals in ${topicDir}: ${err.message}`);
|
|
196
|
+
}
|
|
197
|
+
// 13. Regenerate knowledge-map.md from state.json (v1 format)
|
|
198
|
+
try {
|
|
199
|
+
const rendered = render(stateV1);
|
|
200
|
+
await FileSystemUtils.writeFile(knowledgeMapPath, rendered);
|
|
201
|
+
}
|
|
202
|
+
catch (err) {
|
|
203
|
+
// Render failure is non-fatal — migration itself succeeded
|
|
204
|
+
console.error(`Warning: Failed to regenerate knowledge-map.md in ${topicDir}: ${err.message}`);
|
|
205
|
+
}
|
|
206
|
+
return {
|
|
207
|
+
migrated: true,
|
|
208
|
+
topic: v0State.topic,
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* Migrate ALL topics under a base directory from v0 to v1.
|
|
213
|
+
*
|
|
214
|
+
* Scans `.learn/topics/` for topic subdirectories and runs
|
|
215
|
+
* migrateV0ToV1 on each one. Returns a summary report.
|
|
216
|
+
*
|
|
217
|
+
* @param baseDir — Path to the topics directory (e.g. `.learn/topics`)
|
|
218
|
+
* @returns MigrationReport with counts and per-topic results
|
|
219
|
+
*/
|
|
220
|
+
export async function migrateAll(baseDir) {
|
|
221
|
+
const results = [];
|
|
222
|
+
let entryNames;
|
|
223
|
+
try {
|
|
224
|
+
entryNames = await fs.readdir(baseDir);
|
|
225
|
+
}
|
|
226
|
+
catch {
|
|
227
|
+
// Directory doesn't exist — nothing to migrate
|
|
228
|
+
return { migratedCount: 0, skippedCount: 0, results: [] };
|
|
229
|
+
}
|
|
230
|
+
// Check each entry to see if it's a directory
|
|
231
|
+
const topicDirs = [];
|
|
232
|
+
for (const name of entryNames) {
|
|
233
|
+
const fullPath = path.join(baseDir, name);
|
|
234
|
+
try {
|
|
235
|
+
const stat = await fs.stat(fullPath);
|
|
236
|
+
if (stat.isDirectory())
|
|
237
|
+
topicDirs.push(fullPath);
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
// Skip entries we can't stat
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
for (const dir of topicDirs) {
|
|
244
|
+
const result = await migrateV0ToV1(dir);
|
|
245
|
+
results.push(result);
|
|
246
|
+
}
|
|
247
|
+
const migratedCount = results.filter((r) => r.migrated).length;
|
|
248
|
+
const skippedCount = results.filter((r) => !r.migrated).length;
|
|
249
|
+
return { migratedCount, skippedCount, results };
|
|
250
|
+
}
|
|
251
|
+
// ---- Helpers -----------------------------------------------------------
|
|
252
|
+
/** Map v0 status string to v1 ConceptStatus; default to 'unexplored'. */
|
|
253
|
+
function mapStatus(status) {
|
|
254
|
+
if (status === 'in_progress' || status === 'needs_practice' || status === 'mastered') {
|
|
255
|
+
return status;
|
|
256
|
+
}
|
|
257
|
+
return 'unexplored';
|
|
258
|
+
}
|
|
259
|
+
//# sourceMappingURL=migrate.js.map
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Markdown parser for v0 knowledge-map.md.
|
|
3
|
+
*
|
|
4
|
+
* Uses unified + remark-parse to extract the hierarchical structure
|
|
5
|
+
* (domains -> concepts -> details) from the v0 knowledge-map format.
|
|
6
|
+
*
|
|
7
|
+
* This is used ONLY during migration (init/update), not at AI runtime.
|
|
8
|
+
*
|
|
9
|
+
* v0 knowledge-map.md format:
|
|
10
|
+
*
|
|
11
|
+
* ```md
|
|
12
|
+
* # Topic Name
|
|
13
|
+
* ## Domain 1
|
|
14
|
+
* - Concept A
|
|
15
|
+
* - Detail A1
|
|
16
|
+
* - Detail A2
|
|
17
|
+
* - Concept B
|
|
18
|
+
* ## Domain 2
|
|
19
|
+
* - Concept C
|
|
20
|
+
* ```
|
|
21
|
+
*/
|
|
22
|
+
import type { ParsedKnowledgeMap } from './types.js';
|
|
23
|
+
/**
|
|
24
|
+
* Parse a v0 knowledge-map.md file content into a structured representation.
|
|
25
|
+
*
|
|
26
|
+
* The parser walks the mdast tree:
|
|
27
|
+
* - `# Title` (h1) -> topic name
|
|
28
|
+
* - `## DomainName` (h2) -> start a new domain
|
|
29
|
+
* - `- Concept` (top-level list item) -> add concept to current domain
|
|
30
|
+
* - ` - Detail` (nested list item) -> add detail to preceding concept
|
|
31
|
+
*/
|
|
32
|
+
export declare function parseKnowledgeMap(markdown: string): ParsedKnowledgeMap;
|
|
33
|
+
//# sourceMappingURL=parser.d.ts.map
|