pi-para 0.6.7 → 0.7.1
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/ARCHITECTURE.md +4 -6
- package/CHANGELOG.md +19 -0
- package/CONFIGURATION.md +1 -16
- package/README.md +2 -13
- package/SETUP.md +1 -7
- package/STRUCTURE.md +7 -18
- package/dist/cli-legacy.d.ts +2 -1
- package/dist/cli-legacy.d.ts.map +1 -1
- package/dist/cli-legacy.js +13 -25
- package/dist/cli-legacy.js.map +1 -1
- package/dist/cli.d.ts +2 -24
- package/dist/cli.d.ts.map +1 -1
- package/dist/cli.js +29 -271
- package/dist/cli.js.map +1 -1
- package/dist/commands.d.ts.map +1 -1
- package/dist/commands.js +1 -28
- package/dist/commands.js.map +1 -1
- package/dist/config.d.ts +1 -5
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +0 -5
- package/dist/config.js.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -64
- package/dist/index.js.map +1 -1
- package/dist/link-utils.d.ts +1 -1
- package/dist/link-utils.js +1 -1
- package/dist/processor.d.ts +7 -0
- package/dist/processor.d.ts.map +1 -1
- package/dist/processor.js +29 -15
- package/dist/processor.js.map +1 -1
- package/dist/settings.d.ts +0 -3
- package/dist/settings.d.ts.map +1 -1
- package/dist/settings.js +0 -11
- package/dist/settings.js.map +1 -1
- package/dist/tools/edit-read.d.ts +18 -0
- package/dist/tools/edit-read.d.ts.map +1 -0
- package/dist/tools/edit-read.js +161 -0
- package/dist/tools/edit-read.js.map +1 -0
- package/dist/tools/ingest.d.ts +12 -0
- package/dist/tools/ingest.d.ts.map +1 -0
- package/dist/tools/ingest.js +48 -0
- package/dist/tools/ingest.js.map +1 -0
- package/dist/tools/lint.d.ts +10 -0
- package/dist/tools/lint.d.ts.map +1 -0
- package/dist/tools/lint.js +57 -0
- package/dist/tools/lint.js.map +1 -0
- package/dist/tools/migrate.d.ts +6 -0
- package/dist/tools/migrate.d.ts.map +1 -0
- package/dist/tools/migrate.js +36 -0
- package/dist/tools/migrate.js.map +1 -0
- package/dist/tools/move.d.ts +9 -0
- package/dist/tools/move.d.ts.map +1 -0
- package/dist/tools/move.js +61 -0
- package/dist/tools/move.js.map +1 -0
- package/dist/tools/query.d.ts +12 -0
- package/dist/tools/query.d.ts.map +1 -0
- package/dist/tools/query.js +47 -0
- package/dist/tools/query.js.map +1 -0
- package/dist/tools/schemas.d.ts +109 -0
- package/dist/tools/schemas.d.ts.map +1 -0
- package/dist/tools/schemas.js +80 -0
- package/dist/tools/schemas.js.map +1 -0
- package/dist/tools/shared.d.ts +14 -0
- package/dist/tools/shared.d.ts.map +1 -0
- package/dist/tools/shared.js +25 -0
- package/dist/tools/shared.js.map +1 -0
- package/dist/tools/summarize.d.ts +8 -0
- package/dist/tools/summarize.d.ts.map +1 -0
- package/dist/tools/summarize.js +82 -0
- package/dist/tools/summarize.js.map +1 -0
- package/dist/tools/write.d.ts +23 -0
- package/dist/tools/write.d.ts.map +1 -0
- package/dist/tools/write.js +215 -0
- package/dist/tools/write.js.map +1 -0
- package/dist/tools.d.ts +1 -8
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +13 -795
- package/dist/tools.js.map +1 -1
- package/dist/wiki.d.ts.map +1 -1
- package/dist/wiki.js +1 -0
- package/dist/wiki.js.map +1 -1
- package/package.json +2 -6
- package/src/cli-legacy.ts +14 -26
- package/src/cli.ts +29 -293
- package/src/commands.ts +0 -21
- package/src/config.ts +1 -6
- package/src/index.ts +5 -66
- package/src/link-utils.ts +1 -1
- package/src/processor.ts +28 -13
- package/src/settings.ts +0 -14
- package/src/tools/edit-read.ts +193 -0
- package/src/tools/ingest.ts +63 -0
- package/src/tools/lint.ts +74 -0
- package/src/tools/migrate.ts +44 -0
- package/src/tools/move.ts +79 -0
- package/src/tools/query.ts +63 -0
- package/src/tools/schemas.ts +157 -0
- package/src/tools/shared.ts +35 -0
- package/src/tools/summarize.ts +89 -0
- package/src/tools/write.ts +252 -0
- package/src/tools.ts +18 -1046
- package/src/wiki.ts +1 -0
- package/dist/daemon.d.ts +0 -49
- package/dist/daemon.d.ts.map +0 -1
- package/dist/daemon.js +0 -226
- package/dist/daemon.js.map +0 -1
- package/dist/link-discovery.d.ts +0 -40
- package/dist/link-discovery.d.ts.map +0 -1
- package/dist/link-discovery.js +0 -122
- package/dist/link-discovery.js.map +0 -1
- package/dist/maintainer.d.ts +0 -24
- package/dist/maintainer.d.ts.map +0 -1
- package/dist/maintainer.js +0 -358
- package/dist/maintainer.js.map +0 -1
- package/dist/watcher.d.ts +0 -25
- package/dist/watcher.d.ts.map +0 -1
- package/dist/watcher.js +0 -84
- package/dist/watcher.js.map +0 -1
- package/dist/webui/client/dist/index.html +0 -1885
- package/dist/webui/server.d.ts +0 -31
- package/dist/webui/server.d.ts.map +0 -1
- package/dist/webui/server.js +0 -566
- package/dist/webui/server.js.map +0 -1
- package/scripts/build-assets.mjs +0 -17
- package/src/daemon.ts +0 -288
- package/src/link-discovery.ts +0 -170
- package/src/maintainer.ts +0 -404
- package/src/python/__pycache__/minimax_lm.cpython-312.pyc +0 -0
- package/src/python/minimax_lm.py +0 -198
- package/src/python/rlm_capture.py +0 -215
- package/src/watcher.ts +0 -101
- package/src/webui/client/dist/index.html +0 -1885
- package/src/webui/server.ts +0 -765
package/src/daemon.ts
DELETED
|
@@ -1,288 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Main daemon loop — watches for completed sessions and processes them.
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
import { existsSync } from "node:fs";
|
|
6
|
-
import { join } from "node:path";
|
|
7
|
-
import { homedir } from "node:os";
|
|
8
|
-
|
|
9
|
-
import type { Model } from "@earendil-works/pi-ai";
|
|
10
|
-
import { openStore, closeStore } from "./store.js";
|
|
11
|
-
import type { QMDStore } from "qmd-engine";
|
|
12
|
-
|
|
13
|
-
import { StateDB } from "./state.js";
|
|
14
|
-
import { RegistryWatcher } from "./watcher.js";
|
|
15
|
-
import type { CompletedSession } from "./watcher.js";
|
|
16
|
-
import { processSession } from "./processor.js";
|
|
17
|
-
import { runMaintenance } from "./maintainer.js";
|
|
18
|
-
import { startServer } from "./webui/server.js";
|
|
19
|
-
import type { WebWikiConfig } from "./webui/server.js";
|
|
20
|
-
|
|
21
|
-
export interface DaemonConfig {
|
|
22
|
-
wikiDir: string;
|
|
23
|
-
model: Model<any>;
|
|
24
|
-
getApiKey: (provider: string) => Promise<string | undefined>;
|
|
25
|
-
pollIntervalMs?: number;
|
|
26
|
-
/** How often to run link discovery + lint (ms). Default: 30 minutes */
|
|
27
|
-
maintenanceIntervalMs?: number;
|
|
28
|
-
/** Web wiki server config. If enabled, the daemon hosts the web UI. */
|
|
29
|
-
webWiki?: WebWikiConfig;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
export class Daemon {
|
|
33
|
-
private config: DaemonConfig;
|
|
34
|
-
private state: StateDB;
|
|
35
|
-
private watcher: RegistryWatcher;
|
|
36
|
-
private store: QMDStore | null = null;
|
|
37
|
-
private queue: CompletedSession[] = [];
|
|
38
|
-
private processing = false;
|
|
39
|
-
private running = false;
|
|
40
|
-
private maintenanceTimer: ReturnType<typeof setInterval> | null = null;
|
|
41
|
-
private maintenanceRunning = false;
|
|
42
|
-
private webServer: { close: () => Promise<void>; url: string } | null = null;
|
|
43
|
-
|
|
44
|
-
constructor(config: DaemonConfig) {
|
|
45
|
-
this.config = config;
|
|
46
|
-
this.state = new StateDB(config.wikiDir);
|
|
47
|
-
this.watcher = new RegistryWatcher(
|
|
48
|
-
config.wikiDir,
|
|
49
|
-
(entries) => this.onNewEntries(entries),
|
|
50
|
-
config.pollIntervalMs ?? 5000,
|
|
51
|
-
);
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/** Start the daemon. */
|
|
55
|
-
async start(): Promise<void> {
|
|
56
|
-
console.log(`[daemon] Starting — wiki: ${this.config.wikiDir}`);
|
|
57
|
-
|
|
58
|
-
// Open qmd store
|
|
59
|
-
try {
|
|
60
|
-
this.store = await openStore(this.config.wikiDir);
|
|
61
|
-
console.log("[daemon] qmd store opened");
|
|
62
|
-
} catch (err) {
|
|
63
|
-
console.error(`[daemon] Failed to open store: ${err instanceof Error ? err.message : err}`);
|
|
64
|
-
this.store = null;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
this.running = true;
|
|
68
|
-
this.state.setState("daemon_started_at", new Date().toISOString());
|
|
69
|
-
this.state.setState("daemon_pid", String(process.pid));
|
|
70
|
-
|
|
71
|
-
// Start watching
|
|
72
|
-
this.watcher.start();
|
|
73
|
-
|
|
74
|
-
// Process any unprocessed sessions from registry
|
|
75
|
-
const existing = this.watcher.getAllEntries();
|
|
76
|
-
const unprocessed = existing.filter((e) => !this.state.isProcessed(e.sessionPath));
|
|
77
|
-
if (unprocessed.length > 0) {
|
|
78
|
-
console.log(`[daemon] Found ${unprocessed.length} unprocessed session(s)`);
|
|
79
|
-
this.onNewEntries(unprocessed);
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
// Start periodic maintenance (link discovery + lint)
|
|
83
|
-
const maintenanceMs = this.config.maintenanceIntervalMs ?? 30 * 60 * 1000;
|
|
84
|
-
this.maintenanceTimer = setInterval(() => this.runMaintenancePass(), maintenanceMs);
|
|
85
|
-
// Run first maintenance after a delay to let the store warm up
|
|
86
|
-
setTimeout(() => this.runMaintenancePass(), 60_000);
|
|
87
|
-
|
|
88
|
-
// Start web wiki server if enabled
|
|
89
|
-
if (this.config.webWiki?.enabled) {
|
|
90
|
-
try {
|
|
91
|
-
this.webServer = startServer(this.config.wikiDir, this.store, this.config.webWiki);
|
|
92
|
-
console.log(`[daemon] Web wiki: ${this.webServer.url}`);
|
|
93
|
-
} catch (err) {
|
|
94
|
-
console.error(`[daemon] Web wiki failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
95
|
-
}
|
|
96
|
-
}
|
|
97
|
-
|
|
98
|
-
console.log(`[daemon] Running (maintenance every ${Math.round(maintenanceMs / 60000)}m). Press Ctrl+C to stop.`);
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
/** Stop the daemon. */
|
|
102
|
-
async stop(): Promise<void> {
|
|
103
|
-
console.log("[daemon] Stopping...");
|
|
104
|
-
this.running = false;
|
|
105
|
-
this.watcher.stop();
|
|
106
|
-
if (this.maintenanceTimer) {
|
|
107
|
-
clearInterval(this.maintenanceTimer);
|
|
108
|
-
this.maintenanceTimer = null;
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
// Stop web wiki server
|
|
112
|
-
if (this.webServer) {
|
|
113
|
-
try {
|
|
114
|
-
await this.webServer.close();
|
|
115
|
-
console.log("[daemon] Web wiki stopped");
|
|
116
|
-
} catch {}
|
|
117
|
-
this.webServer = null;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
if (this.store) {
|
|
121
|
-
try {
|
|
122
|
-
await closeStore(this.store);
|
|
123
|
-
} catch {}
|
|
124
|
-
this.store = null;
|
|
125
|
-
}
|
|
126
|
-
|
|
127
|
-
this.state.close();
|
|
128
|
-
console.log("[daemon] Stopped.");
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
/** Get the web server URL (if running). */
|
|
132
|
-
getWebUrl(): string | null {
|
|
133
|
-
return this.webServer?.url ?? null;
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
/** Process a single session file (for CLI `process` command). */
|
|
137
|
-
async processOne(sessionPath: string): Promise<void> {
|
|
138
|
-
if (!existsSync(sessionPath)) {
|
|
139
|
-
console.error(`[daemon] Session file not found: ${sessionPath}`);
|
|
140
|
-
return;
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
if (!this.store) {
|
|
144
|
-
try {
|
|
145
|
-
this.store = await openStore(this.config.wikiDir);
|
|
146
|
-
} catch (err) {
|
|
147
|
-
console.error(`[daemon] Failed to open store: ${err instanceof Error ? err.message : err}`);
|
|
148
|
-
return;
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
const scope = detectScopeFromPath(sessionPath);
|
|
153
|
-
console.log(`[daemon] Processing: ${sessionPath} (scope: ${scope})`);
|
|
154
|
-
|
|
155
|
-
try {
|
|
156
|
-
const result = await processSession(
|
|
157
|
-
sessionPath,
|
|
158
|
-
this.config.wikiDir,
|
|
159
|
-
this.store,
|
|
160
|
-
scope,
|
|
161
|
-
this.config.model,
|
|
162
|
-
this.config.getApiKey,
|
|
163
|
-
);
|
|
164
|
-
|
|
165
|
-
if (result.skipped) {
|
|
166
|
-
console.log(`[daemon] Skipped: ${result.reason}`);
|
|
167
|
-
this.state.recordSuccess(sessionPath, scope, [], []);
|
|
168
|
-
} else {
|
|
169
|
-
console.log(`[daemon] Done: ${result.pagesCreated.length} created, ${result.pagesUpdated.length} updated`);
|
|
170
|
-
this.state.recordSuccess(sessionPath, scope, result.pagesCreated, result.pagesUpdated);
|
|
171
|
-
}
|
|
172
|
-
} catch (err) {
|
|
173
|
-
const msg = err instanceof Error ? err.message : String(err);
|
|
174
|
-
console.error(`[daemon] Failed: ${msg}`);
|
|
175
|
-
this.state.recordFailure(sessionPath, scope, msg);
|
|
176
|
-
}
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
/** Handle new entries from the registry watcher. */
|
|
180
|
-
private onNewEntries(entries: CompletedSession[]): void {
|
|
181
|
-
// Filter already-processed
|
|
182
|
-
const newEntries = entries.filter(
|
|
183
|
-
(e) => existsSync(e.sessionPath) && !this.state.isProcessed(e.sessionPath),
|
|
184
|
-
);
|
|
185
|
-
|
|
186
|
-
if (newEntries.length === 0) return;
|
|
187
|
-
|
|
188
|
-
console.log(`[daemon] Queued ${newEntries.length} session(s) for processing`);
|
|
189
|
-
this.queue.push(...newEntries);
|
|
190
|
-
this.processQueue();
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
/** Process queued sessions sequentially. */
|
|
194
|
-
private async processQueue(): Promise<void> {
|
|
195
|
-
if (this.processing || !this.running) return;
|
|
196
|
-
this.processing = true;
|
|
197
|
-
|
|
198
|
-
while (this.queue.length > 0 && this.running) {
|
|
199
|
-
const entry = this.queue.shift()!;
|
|
200
|
-
await this.processOne(entry.sessionPath);
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
this.processing = false;
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
/** Run periodic maintenance via LLM agent. */
|
|
207
|
-
private async runMaintenancePass(): Promise<void> {
|
|
208
|
-
if (this.maintenanceRunning || !this.running || !this.store) return;
|
|
209
|
-
this.maintenanceRunning = true;
|
|
210
|
-
|
|
211
|
-
try {
|
|
212
|
-
console.log("[daemon] Running maintenance agent...");
|
|
213
|
-
const result = await runMaintenance(
|
|
214
|
-
this.config.wikiDir,
|
|
215
|
-
this.store,
|
|
216
|
-
this.config.model,
|
|
217
|
-
this.config.getApiKey,
|
|
218
|
-
);
|
|
219
|
-
console.log(
|
|
220
|
-
`[daemon] Maintenance done: ${result.pagesUpdated} updated, ${result.pagesMerged} merged`,
|
|
221
|
-
);
|
|
222
|
-
if (result.summary) {
|
|
223
|
-
// Log first 200 chars of summary
|
|
224
|
-
console.log(`[daemon] Summary: ${result.summary.slice(0, 200)}`);
|
|
225
|
-
}
|
|
226
|
-
} catch (err) {
|
|
227
|
-
console.error(
|
|
228
|
-
`[daemon] Maintenance error: ${err instanceof Error ? err.message : String(err)}`,
|
|
229
|
-
);
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
this.maintenanceRunning = false;
|
|
233
|
-
}
|
|
234
|
-
|
|
235
|
-
/** Get processing history. */
|
|
236
|
-
getHistory(scope?: string, limit?: number) {
|
|
237
|
-
return this.state.getHistory(scope, limit);
|
|
238
|
-
}
|
|
239
|
-
|
|
240
|
-
/** Get failed sessions. */
|
|
241
|
-
getFailed() {
|
|
242
|
-
return this.state.getFailed();
|
|
243
|
-
}
|
|
244
|
-
|
|
245
|
-
/** Retry all failed sessions. */
|
|
246
|
-
async retryFailed(): Promise<void> {
|
|
247
|
-
const failed = this.state.getFailed();
|
|
248
|
-
if (failed.length === 0) {
|
|
249
|
-
console.log("[daemon] No failed sessions to retry.");
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
console.log(`[daemon] Retrying ${failed.length} failed session(s)...`);
|
|
253
|
-
for (const session of failed) {
|
|
254
|
-
await this.processOne(session.sessionPath);
|
|
255
|
-
}
|
|
256
|
-
}
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
/** Extract project scope from session path or header. */
|
|
260
|
-
function detectScopeFromPath(sessionPath: string): string {
|
|
261
|
-
// 1. Try reading the session header — most reliable, has the real cwd
|
|
262
|
-
try {
|
|
263
|
-
const { readFileSync } = require("node:fs");
|
|
264
|
-
const firstLine = readFileSync(sessionPath, "utf-8").split("\n")[0];
|
|
265
|
-
const header = JSON.parse(firstLine);
|
|
266
|
-
if (header.cwd) {
|
|
267
|
-
const parts = header.cwd.split("/");
|
|
268
|
-
return parts[parts.length - 1] ?? "unknown";
|
|
269
|
-
}
|
|
270
|
-
} catch {}
|
|
271
|
-
|
|
272
|
-
// 2. Fallback: decode from directory name
|
|
273
|
-
// Path format: ~/.pi/agent/sessions/--home-ubuntu-projects-pi-mono--/file.jsonl
|
|
274
|
-
// The dir name encodes the cwd path with / replaced by -
|
|
275
|
-
// But project names can contain hyphens, so we can't just replace all - with /
|
|
276
|
-
// Instead, find the last segment after "projects-" which is the project name
|
|
277
|
-
const dirName = sessionPath.split("/").slice(-2, -1)[0] ?? "";
|
|
278
|
-
if (dirName.startsWith("--") && dirName.endsWith("--")) {
|
|
279
|
-
const inner = dirName.slice(2, -2); // e.g. "home-ubuntu-projects-agent-board"
|
|
280
|
-
// Look for "projects-" marker — everything after it is the project name
|
|
281
|
-
const projectsIdx = inner.indexOf("projects-");
|
|
282
|
-
if (projectsIdx >= 0) {
|
|
283
|
-
return inner.slice(projectsIdx + "projects-".length); // "agent-board"
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
|
|
287
|
-
return "unknown";
|
|
288
|
-
}
|
package/src/link-discovery.ts
DELETED
|
@@ -1,170 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Link discovery — finds related wiki pages and adds [[wikilinks]].
|
|
3
|
-
*
|
|
4
|
-
* Uses BM25 search to find pages that are semantically related but
|
|
5
|
-
* not yet linked. Runs as a periodic daemon job or on-demand.
|
|
6
|
-
*
|
|
7
|
-
* Strategy:
|
|
8
|
-
* 1. For each page, search the wiki using its title + key terms
|
|
9
|
-
* 2. Filter results to pages not already linked
|
|
10
|
-
* 3. If a related page scores above threshold, add it to ## Connections
|
|
11
|
-
* 4. Sync frontmatter.links
|
|
12
|
-
*/
|
|
13
|
-
|
|
14
|
-
import {
|
|
15
|
-
listPages,
|
|
16
|
-
readPage,
|
|
17
|
-
writePage,
|
|
18
|
-
} from "./wiki.js";
|
|
19
|
-
import type { WikiPage } from "./wiki.js";
|
|
20
|
-
import { searchWiki } from "./store.js";
|
|
21
|
-
import type { QMDStore } from "./store.js";
|
|
22
|
-
import { extractWikilinks, syncFrontmatterLinks } from "./link-utils.js";
|
|
23
|
-
|
|
24
|
-
// -- Types -------------------------------------------------------------------
|
|
25
|
-
|
|
26
|
-
export interface LinkDiscoveryResult {
|
|
27
|
-
pagesUpdated: number;
|
|
28
|
-
linksAdded: number;
|
|
29
|
-
discoveries: Array<{
|
|
30
|
-
page: string;
|
|
31
|
-
newLinks: string[];
|
|
32
|
-
}>;
|
|
33
|
-
}
|
|
34
|
-
|
|
35
|
-
export interface LinkDiscoveryOptions {
|
|
36
|
-
/** Minimum BM25 score to consider a page related (0-1). Default 0.3 */
|
|
37
|
-
minScore?: number;
|
|
38
|
-
/** Max new links to add per page per run. Default 5 */
|
|
39
|
-
maxLinksPerPage?: number;
|
|
40
|
-
/** Dry run — report but don't write. Default false */
|
|
41
|
-
dryRun?: boolean;
|
|
42
|
-
}
|
|
43
|
-
|
|
44
|
-
// -- Discovery ---------------------------------------------------------------
|
|
45
|
-
|
|
46
|
-
/**
|
|
47
|
-
* Discover and add missing [[wikilinks]] between related pages.
|
|
48
|
-
*
|
|
49
|
-
* For each page:
|
|
50
|
-
* 1. Search wiki using the page's title as query
|
|
51
|
-
* 2. Find high-scoring pages not already linked
|
|
52
|
-
* 3. Add them to ## Connections section
|
|
53
|
-
* 4. Sync frontmatter.links
|
|
54
|
-
*/
|
|
55
|
-
export async function discoverLinks(
|
|
56
|
-
wikiDir: string,
|
|
57
|
-
store: QMDStore,
|
|
58
|
-
options?: LinkDiscoveryOptions,
|
|
59
|
-
): Promise<LinkDiscoveryResult> {
|
|
60
|
-
const minScore = options?.minScore ?? 0.3;
|
|
61
|
-
const maxLinksPerPage = options?.maxLinksPerPage ?? 5;
|
|
62
|
-
const dryRun = options?.dryRun ?? false;
|
|
63
|
-
|
|
64
|
-
const refs = await listPages(wikiDir);
|
|
65
|
-
const pages: WikiPage[] = [];
|
|
66
|
-
for (const ref of refs) {
|
|
67
|
-
const page = await readPage(wikiDir, ref.category, ref.slug);
|
|
68
|
-
if (page) pages.push(page);
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const allSlugs = new Set(pages.map(p => p.slug));
|
|
72
|
-
const result: LinkDiscoveryResult = {
|
|
73
|
-
pagesUpdated: 0,
|
|
74
|
-
linksAdded: 0,
|
|
75
|
-
discoveries: [],
|
|
76
|
-
};
|
|
77
|
-
|
|
78
|
-
for (const page of pages) {
|
|
79
|
-
// Get existing outgoing links
|
|
80
|
-
const existingLinks = new Set(extractWikilinks(page.body));
|
|
81
|
-
// Also include frontmatter links
|
|
82
|
-
for (const l of page.frontmatter.links) existingLinks.add(l);
|
|
83
|
-
|
|
84
|
-
// Search for related pages using title
|
|
85
|
-
const query = page.frontmatter.title;
|
|
86
|
-
let related;
|
|
87
|
-
try {
|
|
88
|
-
related = await searchWiki(store, query, { limit: 10 });
|
|
89
|
-
} catch {
|
|
90
|
-
continue; // search failure — skip this page
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
// Filter: not self, not already linked, above score threshold
|
|
94
|
-
const candidates = related
|
|
95
|
-
.filter(r =>
|
|
96
|
-
r.page.slug !== page.slug &&
|
|
97
|
-
!existingLinks.has(r.page.slug) &&
|
|
98
|
-
r.score >= minScore
|
|
99
|
-
)
|
|
100
|
-
.slice(0, maxLinksPerPage);
|
|
101
|
-
|
|
102
|
-
if (candidates.length === 0) continue;
|
|
103
|
-
|
|
104
|
-
const newLinks = candidates.map(c => c.page.slug);
|
|
105
|
-
|
|
106
|
-
// Build ## Connections addition
|
|
107
|
-
const connectionsLines = newLinks.map(slug => {
|
|
108
|
-
const targetPage = pages.find(p => p.slug === slug);
|
|
109
|
-
const title = targetPage?.frontmatter.title ?? slug;
|
|
110
|
-
return `- [[${slug}]] — ${title}`;
|
|
111
|
-
});
|
|
112
|
-
|
|
113
|
-
// Update page body
|
|
114
|
-
let newBody = page.body;
|
|
115
|
-
const hasConnections = /^## Connections/m.test(newBody);
|
|
116
|
-
|
|
117
|
-
if (hasConnections) {
|
|
118
|
-
// Append to existing Connections section
|
|
119
|
-
// Find the end of the Connections section (next ## heading or EOF)
|
|
120
|
-
const connectionsIdx = newBody.indexOf("## Connections");
|
|
121
|
-
const afterConnections = newBody.indexOf("\n## ", connectionsIdx + 1);
|
|
122
|
-
const insertPos = afterConnections === -1 ? newBody.length : afterConnections;
|
|
123
|
-
|
|
124
|
-
// Insert before the next section
|
|
125
|
-
const insertion = "\n" + connectionsLines.join("\n");
|
|
126
|
-
newBody = newBody.slice(0, insertPos) + insertion + newBody.slice(insertPos);
|
|
127
|
-
} else {
|
|
128
|
-
// Add new Connections section at the end (before ## Sources or ## Open Questions if they exist)
|
|
129
|
-
const sourcesIdx = newBody.indexOf("\n## Sources");
|
|
130
|
-
const questionsIdx = newBody.indexOf("\n## Open Questions");
|
|
131
|
-
const insertBefore = Math.min(
|
|
132
|
-
sourcesIdx === -1 ? Infinity : sourcesIdx,
|
|
133
|
-
questionsIdx === -1 ? Infinity : questionsIdx,
|
|
134
|
-
);
|
|
135
|
-
|
|
136
|
-
const section = "\n\n## Connections\n" + connectionsLines.join("\n");
|
|
137
|
-
|
|
138
|
-
if (insertBefore === Infinity) {
|
|
139
|
-
newBody = newBody.trimEnd() + section + "\n";
|
|
140
|
-
} else {
|
|
141
|
-
newBody = newBody.slice(0, insertBefore) + section + newBody.slice(insertBefore);
|
|
142
|
-
}
|
|
143
|
-
}
|
|
144
|
-
|
|
145
|
-
// Sync frontmatter.links
|
|
146
|
-
const updatedLinks = syncFrontmatterLinks(newBody);
|
|
147
|
-
|
|
148
|
-
if (!dryRun) {
|
|
149
|
-
const updatedPage: WikiPage = {
|
|
150
|
-
...page,
|
|
151
|
-
body: newBody,
|
|
152
|
-
frontmatter: {
|
|
153
|
-
...page.frontmatter,
|
|
154
|
-
links: updatedLinks,
|
|
155
|
-
updated: new Date().toISOString(),
|
|
156
|
-
},
|
|
157
|
-
};
|
|
158
|
-
await writePage(wikiDir, updatedPage);
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
result.pagesUpdated++;
|
|
162
|
-
result.linksAdded += newLinks.length;
|
|
163
|
-
result.discoveries.push({
|
|
164
|
-
page: `${page.category}/${page.slug}`,
|
|
165
|
-
newLinks,
|
|
166
|
-
});
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
return result;
|
|
170
|
-
}
|