dsh-plugin-memory 0.5.2 → 0.7.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/lib/graph.js ADDED
@@ -0,0 +1,249 @@
1
+ /**
2
+ * Memory graph: turn the store's *relationships* into nodes and edges.
3
+ *
4
+ * The graph DSH renders from markdown alone is a star: `index.md` links to every
5
+ * page and pages link back to almost nothing (measured on a real store: 29 pages,
6
+ * 1 page-to-page link). That shape is true but uninformative — it says "the index
7
+ * lists everything", not "these memories belong together".
8
+ *
9
+ * This module recovers the relationships the store already encodes but nobody
10
+ * drew:
11
+ *
12
+ * - `link` — an explicit markdown link between two pages (the strongest signal);
13
+ * - `tag` — pages sharing a frontmatter tag (`#dsh`, `#plugin`, …);
14
+ * - `type` — pages of the same kind (all `projects`, all `skills`), a weak
15
+ * grouping edge that is off by default.
16
+ *
17
+ * Read-only and dependency-free: it derives everything from frontmatter and
18
+ * bodies, never writes, and degrades to an empty graph instead of throwing.
19
+ *
20
+ * @module dsh-plugin-memory/graph
21
+ */
22
+
23
+ import { existsSync, readFileSync } from 'node:fs'
24
+ import { basename, dirname, join, normalize } from 'node:path'
25
+ import { listPagePaths } from './pages.js'
26
+ import { parseFrontmatter } from './insights.js'
27
+ import { layoutGraph, typeColor } from './graph-layout.js'
28
+
29
+ /** Edge kinds, strongest first; the client decides which to draw. */
30
+ export const EDGE_KINDS = ['link', 'tag', 'type']
31
+
32
+ /** Root meta files are not memory pages, but they anchor the graph visibly. */
33
+ const META_FILES = ['SOUL.md', 'MEMORY.md', 'index.md', 'log.md']
34
+
35
+ /** Tokens so generic they connect everything and therefore explain nothing. */
36
+ const STOP_TAGS = new Set([
37
+ 'project', 'projects', 'skill', 'skills', 'decision', 'decisions',
38
+ 'concept', 'concepts', 'user', 'identity', 'fact',
39
+ ])
40
+
41
+
42
+ /** Stable-ish id for a node: the store-relative path. */
43
+ const nodeId = (path) => path.replace(/^\.\//, '')
44
+
45
+ /**
46
+ * Resolve a markdown link target to a node id. Links in a memory page are
47
+ * usually *relative to that page* (`../skills/foo.md`), so anchor them before
48
+ * normalising — otherwise every cross-folder link silently disappears.
49
+ * @param {string} fromId the linking page's id
50
+ * @param {string} target the raw href
51
+ * @returns {string} candidate node id
52
+ */
53
+ function resolveLink(fromId, target) {
54
+ const clean = target.trim().replace(/^<|>$/g, '')
55
+ if (clean.startsWith('/')) return nodeId(clean)
56
+ return normalize(join(dirname(fromId), clean)).split('\\').join('/')
57
+ }
58
+
59
+ /** Parse `tags: [a, b]` (frontmatter is flat in this store by convention). */
60
+ function parseTags(frontmatter) {
61
+ const raw = frontmatter.tags
62
+ if (typeof raw !== 'string') return []
63
+ const inner = /^\[(.*)\]$/.exec(raw.trim())
64
+ const body = inner ? inner[1] : raw
65
+ return body
66
+ .split(',')
67
+ .map((tag) => tag.trim().replace(/^#/, ''))
68
+ .filter((tag) => tag.length > 0)
69
+ }
70
+
71
+ /** The first sentence of the body, used as hover text when nothing else fits. */
72
+ function bodyPreview(text) {
73
+ const body = text.replace(/^---[\s\S]*?\n---\n?/, '')
74
+ for (const line of body.split('\n')) {
75
+ const clean = line.trim()
76
+ if (clean.length === 0 || clean.startsWith('#') || clean.startsWith('>')) continue
77
+ return clean.replace(/[*`[\]]/g, '').slice(0, 120)
78
+ }
79
+ return ''
80
+ }
81
+
82
+ /**
83
+ * Build the memory graph.
84
+ *
85
+ * @param {string} memoryDir absolute path of the memory store
86
+ * @param {{ includeMeta?: boolean, includeTypeEdges?: boolean, stopTags?: Set<string> }} [options]
87
+ * @returns {{
88
+ * nodes: Array<{ id: string, label: string, kind: string, type: string, tags: string[],
89
+ * degree: number, salience?: number, lastAccess?: string, preview: string, hub: boolean }>,
90
+ * edges: Array<{ source: string, target: string, kind: string, weight: number, label?: string }>,
91
+ * stats: { pages: number, links: number, tagEdges: number, typeEdges: number, isolated: string[] },
92
+ * }}
93
+ */
94
+ export function buildMemoryGraph(memoryDir, options = {}) {
95
+ const stopTags = options.stopTags ?? STOP_TAGS
96
+ const paths = listPagePaths(memoryDir)
97
+ const nodes = []
98
+ const edges = []
99
+ const byId = new Map()
100
+
101
+ for (const rel of paths) {
102
+ const id = nodeId(rel)
103
+ let text = ''
104
+ try {
105
+ text = readFileSync(join(memoryDir, rel), 'utf8')
106
+ } catch {
107
+ continue
108
+ }
109
+ const fm = parseFrontmatter(text)
110
+ const salience = Number(fm.salience)
111
+ const node = {
112
+ id,
113
+ label: fm.title || basename(rel, '.md'),
114
+ kind: 'page',
115
+ type: fm.type || 'unknown',
116
+ tags: parseTags(fm),
117
+ salience: [1, 2, 3].includes(salience) ? salience : undefined,
118
+ lastAccess: typeof fm.last_access === 'string' ? fm.last_access : undefined,
119
+ preview: bodyPreview(text),
120
+ degree: 0,
121
+ hub: false,
122
+ }
123
+ nodes.push(node)
124
+ byId.set(id, node)
125
+ }
126
+
127
+ if (options.includeMeta !== false) {
128
+ for (const name of META_FILES) {
129
+ if (!existsSync(join(memoryDir, name))) continue
130
+ const node = {
131
+ id: name,
132
+ label: name.replace(/\.md$/, ''),
133
+ kind: 'meta',
134
+ type: 'meta',
135
+ tags: [],
136
+ preview: '',
137
+ degree: 0,
138
+ hub: true,
139
+ }
140
+ nodes.push(node)
141
+ byId.set(name, node)
142
+ }
143
+ }
144
+
145
+ const seen = new Set()
146
+ const addEdge = (source, target, kind, weight, label) => {
147
+ if (!byId.has(source) || !byId.has(target) || source === target) return
148
+ const [a, b] = source < target ? [source, target] : [target, source]
149
+ const key = `${kind}:${a}|${b}`
150
+ if (seen.has(key)) return
151
+ seen.add(key)
152
+ edges.push({ source: a, target: b, kind, weight, ...(label ? { label } : {}) })
153
+ byId.get(a).degree += 1
154
+ byId.get(b).degree += 1
155
+ }
156
+
157
+ // 1. explicit links, from every node — root meta files included. index.md is
158
+ // the routing table: 33 links to every page in the store. A previous
159
+ // version skipped meta files entirely, which left the index node floating
160
+ // alone in the picture while it is in fact the busiest node in the store.
161
+ let links = 0
162
+ let indexLinks = 0
163
+ for (const node of [...nodes]) {
164
+ let text = ''
165
+ try {
166
+ text = readFileSync(join(memoryDir, node.id), 'utf8')
167
+ } catch {
168
+ continue
169
+ }
170
+ for (const match of text.matchAll(/\]\(([^)]+\.md)\)/g)) {
171
+ const target = resolveLink(node.id, match[1])
172
+ if (target === node.id || !byId.has(target)) continue
173
+ // The routing table's own rows are their own kind of relationship: an
174
+ // index→page edge means "listed here", not "these two belong together".
175
+ const fromMeta = node.kind === 'meta'
176
+ addEdge(node.id, target, fromMeta ? 'index' : 'link', fromMeta ? 0.4 : 1)
177
+ if (fromMeta) indexLinks += 1
178
+ else links += 1
179
+ }
180
+ }
181
+
182
+ // 2. shared tags — one edge per tag, labelled with it, weight = how many pages
183
+ const tagGroups = new Map()
184
+ for (const node of nodes) {
185
+ if (node.kind !== 'page') continue
186
+ for (const tag of node.tags) {
187
+ if (stopTags.has(tag)) continue
188
+ if (!tagGroups.has(tag)) tagGroups.set(tag, [])
189
+ tagGroups.get(tag).push(node.id)
190
+ }
191
+ }
192
+ let tagEdges = 0
193
+ for (const [tag, members] of tagGroups) {
194
+ if (members.length < 2) continue
195
+ // Keep dense tags readable: a tag shared by 20 pages becomes a chain through
196
+ // the first member rather than 190 edges.
197
+ const anchor = members[0]
198
+ for (const member of members.slice(1)) {
199
+ addEdge(anchor, member, 'tag', 1, tag)
200
+ tagEdges += 1
201
+ }
202
+ }
203
+
204
+ // 3. same-type edges (off by default: weak, and can overwhelm the picture)
205
+ let typeEdges = 0
206
+ if (options.includeTypeEdges) {
207
+ const typeGroups = new Map()
208
+ for (const node of nodes) {
209
+ if (node.kind !== 'page') continue
210
+ const key = node.type
211
+ if (!typeGroups.has(key)) typeGroups.set(key, [])
212
+ typeGroups.get(key).push(node.id)
213
+ }
214
+ for (const [type, members] of typeGroups) {
215
+ for (let i = 1; i < members.length; i += 1) {
216
+ addEdge(members[i - 1], members[i], 'type', 0.5, type)
217
+ typeEdges += 1
218
+ }
219
+ }
220
+ }
221
+
222
+ // Layout is computed here (once, server-side) rather than in the browser half:
223
+ // the client bundle cannot import local modules, and shipping coordinates keeps
224
+ // both sides from drifting apart.
225
+ const { positions, radius } = layoutGraph(nodes, edges)
226
+ for (const node of nodes) {
227
+ const p = positions.get(node.id)
228
+ if (p !== undefined) {
229
+ node.x = Math.round(p.x * 10) / 10
230
+ node.y = Math.round(p.y * 10) / 10
231
+ }
232
+ node.r = Math.round(radius(node.id) * 10) / 10 + (node.hub ? 4 : 0)
233
+ node.color = typeColor(node.type)
234
+ }
235
+
236
+ const isolated = nodes.filter((node) => node.degree === 0 && node.kind === 'page').map((node) => node.id)
237
+ return {
238
+ nodes,
239
+ edges,
240
+ stats: {
241
+ pages: nodes.filter((node) => node.kind === 'page').length,
242
+ links,
243
+ indexLinks,
244
+ tagEdges,
245
+ typeEdges,
246
+ isolated,
247
+ },
248
+ }
249
+ }
@@ -0,0 +1,399 @@
1
+ /**
2
+ * Index-page compiler: keep `index.md` a routing table instead of a summary dump.
3
+ *
4
+ * The index is injected into every session in full, so its size is a hard
5
+ * context cost — yet the discipline ("one line per page, a short summary") lived
6
+ * only in prose. Measured on a real store, 85% of its lines had drifted into
7
+ * half-paragraph status reports. This module makes the discipline mechanical:
8
+ *
9
+ * - a summary is **declared** by the page (`summary:` in frontmatter): the
10
+ * compiler never invents prose, which is why a rewrite cannot lower quality;
11
+ * **declared** by the page (`summary:` in frontmatter) — the compiler never
12
+ * invents prose, so a rewrite can never lower the summary's quality;
13
+ * - lines are *rewritten in place*: sections, ordering and the funnel list stay
14
+ * exactly as the agent left them, so an automated pass can never reorder the
15
+ * user's mental map of their own memory;
16
+ * - pages the index has never mentioned are only **reported**, never inserted —
17
+ * which section and which order a new page belongs to is editorial judgement,
18
+ * and that stays with the agent and the user.
19
+ *
20
+ * Everything is derived and dry-run first: `planIndex` never writes, and the CLI
21
+ * requires an explicit `--write`.
22
+ *
23
+ * Depends only on `node:*` builtins plus {@link ./insights.js}.
24
+ *
25
+ * @module dsh-plugin-memory/index-page
26
+ */
27
+
28
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs'
29
+ import { join } from 'node:path'
30
+ import { collectInsights, parseFrontmatter } from './insights.js'
31
+
32
+ /** Cap for the link label. A routing line is scanned, not read: a
33
+ * page's full title (often a whole clause) belongs in the page, not here. */
34
+ export const INDEX_LABEL_MAX = 32
35
+
36
+ /** Hard cap for one routing line (link + label + summary + salience). */
37
+ export const INDEX_LINE_MAX = 132
38
+ /** Nominal cap for the summary text; long labels shrink it further. */
39
+ export const INDEX_SUMMARY_MAX = 48
40
+
41
+ const LINE_RE = /^(\s*-\s+)\[([^\]]*)\]\(([^)]+)\)\s*(.*)$/
42
+ const HEADING_RE = /^##\s+(.*)$/
43
+
44
+ /** Strip the markdown scaffolding that would only add noise to a one-liner. */
45
+ function stripMarkup(text) {
46
+ return text
47
+ .replace(/`([^`]*)`/g, '$1')
48
+ .replace(/\*\*([^*]*)\*\*/g, '$1')
49
+ .replace(/\*([^*]*)\*/g, '$1')
50
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
51
+ .replace(/^\s*[-*+]\s+/, '')
52
+ .replace(/^\s*>\s?/, '')
53
+ .trim()
54
+ }
55
+
56
+ /**
57
+ * The first real sentence of a page body (skips headings, quotes and blanks).
58
+ * Exported for previews and tooling only — the index compiler does **not** use
59
+ * it, because derived prose measured worse than a declared summary.
60
+ */
61
+ export function firstSentence(text) {
62
+ const body = String(text ?? '').replace(/^---[\s\S]*?\n---\n?/, '')
63
+ for (const rawLine of body.split('\n')) {
64
+ const line = rawLine.trim()
65
+ if (line.length === 0 || line.startsWith('#') || line.startsWith('>')) continue
66
+ const clean = stripMarkup(line)
67
+ if (clean.length === 0) continue
68
+ const end = clean.search(/[。!?!?.](?:\s|$)/)
69
+ return (end >= 0 ? clean.slice(0, end + 1) : clean).trim()
70
+ }
71
+ return ''
72
+ }
73
+
74
+ /** Clamp to `max` characters, appending an ellipsis when it had to cut. */
75
+ export function clampSummary(text, max = INDEX_SUMMARY_MAX) {
76
+ const flat = String(text ?? '').replace(/\s+/g, ' ').trim()
77
+ if (flat.length <= max) return flat
78
+ const head = flat.slice(0, Math.max(1, max - 1))
79
+ // Prefer a natural break (sentence end, then clause) over a hard cut.
80
+ const boundary = Math.max(head.lastIndexOf('。'), head.lastIndexOf(';'), head.lastIndexOf(','))
81
+ if (boundary >= Math.floor(head.length / 2)) return head.slice(0, boundary + 1)
82
+ return `${head.trimEnd()}…`
83
+ }
84
+
85
+ /**
86
+ * Clamp a link label. Labels come from the page title, which is often a full
87
+ * clause ("macOS 下 dsh web 开机自启(LaunchAgent)+ 本机网络/安装坑"); the index
88
+ * needs the gist, the page keeps the full wording.
89
+ * @param {string} title
90
+ * @param {number} [max]
91
+ * @returns {string}
92
+ */
93
+ export function clampLabel(title, max = INDEX_LABEL_MAX) {
94
+ const flat = String(title ?? '').replace(/\s+/g, ' ').trim()
95
+ if (flat.length <= max) return flat
96
+ return `${flat.slice(0, Math.max(1, max - 1)).trimEnd()}…`
97
+ }
98
+
99
+ /**
100
+ * How much room a summary has on one line, given its label. A long label must
101
+ * not push the line past {@link INDEX_LINE_MAX}, so the summary yields first.
102
+ * @param {string} target store-relative page path
103
+ * @param {string} title link label (clamped internally)
104
+ * @param {number} [lineMax]
105
+ * @returns {number} character budget for the summary
106
+ */
107
+ export function summaryBudget(target, title, lineMax = INDEX_LINE_MAX) {
108
+ // Rendered markup around the words: "- [" + "](" + ") — " + " `salience:N`".
109
+ const MARKUP_CHARS = 24
110
+ const overhead = MARKUP_CHARS + clampLabel(title).length + String(target ?? '').length
111
+ return Math.max(16, Math.min(INDEX_SUMMARY_MAX, lineMax - overhead))
112
+ }
113
+
114
+ /**
115
+ * The summary a page declares about itself. **Declaration only** — the first
116
+ * sentence of the body is deliberately not used as a fallback: measured against
117
+ * a real store, derived prose summarised "the setup" instead of the point
118
+ * (a preferences page became "confirm the time first", not "code changes are
119
+ * not committed"), which is worse than no summary at all. An undeclared page
120
+ * contributes its title and nothing else.
121
+ * @param {Record<string, string>} frontmatter parsed frontmatter
122
+ * @returns {string} clamped summary, or '' when the page declares none
123
+ */
124
+ export function declaredSummary(frontmatter = {}, max = INDEX_SUMMARY_MAX) {
125
+ const value = frontmatter.summary
126
+ if (typeof value !== 'string' || value.trim().length === 0) return ''
127
+ return clampSummary(value, max)
128
+ }
129
+
130
+ /** Render one routing line exactly the way the compiler would. */
131
+ export function renderIndexLine({ target, title, salience, summary }) {
132
+ const label = clampLabel(title) || String(target ?? '')
133
+ const badge = salience === undefined ? '' : ` \`salience:${salience}\``
134
+ const text = summary && summary.length > 0 ? ` — ${summary}` : ''
135
+ return `- [${label}](${target})${text}${badge}`
136
+ }
137
+
138
+ /** Parse an index file into its funnel (title + intro) and its sections. */
139
+ export function parseIndexPage(text) {
140
+ const lines = String(text ?? '').split('\n')
141
+ let title = ''
142
+ const intro = []
143
+ const sections = []
144
+ let current
145
+
146
+ // Flat indexes exist: entries before the first `##` still have to parse, so
147
+ // they land in an implicit section instead of being mistaken for funnel prose.
148
+ const ensureSection = () => {
149
+ if (current === undefined) current = { heading: '', name: '', intro: [], items: [] }
150
+ if (sections.length === 0) sections.push(current)
151
+ else if (sections[sections.length - 1] !== current) sections.push(current)
152
+ return current
153
+ }
154
+
155
+ for (const line of lines) {
156
+ const heading = HEADING_RE.exec(line)
157
+ if (heading !== null) {
158
+ current = { heading: line, name: heading[1].trim(), intro: [], items: [] }
159
+ sections.push(current)
160
+ continue
161
+ }
162
+ const item = LINE_RE.exec(line)
163
+ if (item !== null) {
164
+ ensureSection().items.push({ label: item[2], target: item[3], rest: item[4].trim(), raw: line })
165
+ continue
166
+ }
167
+ if (current === undefined) {
168
+ if (title === '' && line.startsWith('# ')) {
169
+ title = line
170
+ continue
171
+ }
172
+ // Once the title is known, everything up to the first section is funnel
173
+ // prose and is preserved verbatim (blank lines included).
174
+ if (title !== '') intro.push(line)
175
+ continue
176
+ }
177
+ if (line.trim().length > 0 || current.items.length === 0) current.intro.push(line)
178
+ }
179
+ return { title, intro, sections }
180
+ }
181
+
182
+ /** Every page the index currently mentions, in file order. */
183
+ export function indexTargets(parsed) {
184
+ const targets = new Set()
185
+ for (const section of parsed.sections) {
186
+ for (const item of section.items) targets.add(item.target)
187
+ }
188
+ return targets
189
+ }
190
+
191
+ /** Compare content, not spacing: a whitespace-only re-render is not a change. */
192
+ const normalise = (value) => value.replace(/\s+/g, ' ').trim()
193
+
194
+ /**
195
+ * Compare the index against the store without touching anything.
196
+ *
197
+ * @param {string} memoryDir absolute path of the memory store
198
+ * @returns {{
199
+ * parsed: object,
200
+ * lines: Array<{ target: string, section: string, current: string, next: string,
201
+ * summary: string, title: string, salience?: number,
202
+ * source: 'declared'|'derived', changed: boolean }>,
203
+ * stale: number,
204
+ * missing: string[],
205
+ * removed: string[],
206
+ * }}
207
+ */
208
+ export function planIndex(memoryDir) {
209
+ const indexPath = join(memoryDir, 'index.md')
210
+ const text = existsSync(indexPath) ? readFileSync(indexPath, 'utf8') : ''
211
+ const parsed = parseIndexPage(text)
212
+ const insights = collectInsights(memoryDir)
213
+ const pageByPath = new Map((insights.pages ?? []).map((page) => [page.path, page]))
214
+ const targets = indexTargets(parsed)
215
+
216
+ const lines = []
217
+ let stale = 0
218
+ for (const section of parsed.sections) {
219
+ for (const item of section.items) {
220
+ const page = pageByPath.get(item.target)
221
+ // Root meta files (SOUL.md / MEMORY.md / log.md …) are not "pages": they
222
+ // have no frontmatter and are not derived, so they are never rewritten.
223
+ if (page === undefined) continue
224
+ let pageText = ''
225
+ try {
226
+ pageText = readFileSync(join(memoryDir, item.target), 'utf8')
227
+ } catch {
228
+ continue
229
+ }
230
+ const fm = parseFrontmatter(pageText)
231
+ const summary = declaredSummary(fm, summaryBudget(item.target, page.title))
232
+ const declared = summary.length > 0
233
+ const declaredChars = typeof fm.summary === 'string' ? fm.summary.trim().length : 0
234
+ const next = renderIndexLine({
235
+ target: item.target,
236
+ title: page.title,
237
+ salience: page.salience,
238
+ summary,
239
+ })
240
+ const changed = normalise(next) !== normalise(item.raw)
241
+ if (changed) stale += 1
242
+ lines.push({
243
+ target: item.target,
244
+ section: section.name,
245
+ current: item.raw,
246
+ next,
247
+ summary,
248
+ declaredChars,
249
+ title: page.title,
250
+ salience: page.salience,
251
+ source: declared ? 'declared' : 'derived',
252
+ changed,
253
+ })
254
+ }
255
+ }
256
+
257
+ // Only *derived pages* are candidates for the missing/removed reports: a root
258
+ // meta file listed in the index (SOUL.md …) is neither an orphan nor a page.
259
+ const listed = new Set(lines.map((line) => line.target))
260
+ const missing = [...pageByPath.keys()].filter((path) => !listed.has(path)).sort()
261
+ const removed = [...targets]
262
+ .filter((path) => !existsSync(join(memoryDir, path)))
263
+ .sort()
264
+ return { parsed, lines, stale, missing, removed }
265
+ }
266
+
267
+ /**
268
+ * Rewrite the lines the plan marked stale. Sections, ordering and any content
269
+ * the plan did not touch are preserved byte-for-byte; nothing is added or
270
+ * deleted, so the blast radius is exactly the lines reported by `--check`.
271
+ *
272
+ * @param {string} memoryDir absolute path of the memory store
273
+ * @param {{ parsed: object, lines: Array<object> }} plan from {@link planIndex}
274
+ * @returns {{ written: number, bytesBefore: number, bytesAfter: number }}
275
+ */
276
+ export function applyIndex(memoryDir, plan) {
277
+ const indexPath = join(memoryDir, 'index.md')
278
+ const before = existsSync(indexPath) ? readFileSync(indexPath, 'utf8') : ''
279
+ const replacement = new Map()
280
+ for (const line of plan.lines) {
281
+ if (line.changed) replacement.set(normalise(line.current), line.next)
282
+ }
283
+ let written = 0
284
+ const out = before.split('\n').map((raw) => {
285
+ const next = replacement.get(normalise(raw))
286
+ if (next === undefined) return raw
287
+ written += 1
288
+ return next
289
+ }).join('\n')
290
+ if (written > 0) writeFileSync(indexPath, out, 'utf8')
291
+ return { written, bytesBefore: before.length, bytesAfter: out.length }
292
+ }
293
+
294
+ /**
295
+ * One-shot migration: copy a summary that already lives in an index line back
296
+ * into the page's frontmatter, so the index and the declaration can never drift
297
+ * again. Pages that already declare `summary:` are left alone.
298
+ *
299
+ * @param {string} memoryDir absolute path of the memory store
300
+ * @param {{ lines: Array<{ target: string, summary: string, current: string }> }} plan
301
+ * @returns {{ synced: string[], skipped: string[] }}
302
+ */
303
+ export function syncDeclaredSummaries(memoryDir, plan) {
304
+ const synced = []
305
+ const skipped = []
306
+ for (const line of plan.lines) {
307
+ // Prefer an explicit "— summary" tail; fall back to nothing (never invent).
308
+ const tail = /\s+[—–-]\s+(.+?)(?:\s+`salience:[^`]*`)?\s*$/.exec(line.current)
309
+ const summary = (tail ? tail[1] : '').trim()
310
+ if (summary.length === 0) {
311
+ skipped.push(line.target)
312
+ continue
313
+ }
314
+ const abs = join(memoryDir, line.target)
315
+ let text = ''
316
+ try {
317
+ text = readFileSync(abs, 'utf8')
318
+ } catch {
319
+ skipped.push(line.target)
320
+ continue
321
+ }
322
+ if (/^summary:/m.test(text)) {
323
+ skipped.push(line.target)
324
+ continue
325
+ }
326
+ const end = text.indexOf('\n---', 3)
327
+ if (!text.startsWith('---') || end < 0) {
328
+ skipped.push(line.target)
329
+ continue
330
+ }
331
+ const next = `${text.slice(0, end)}\nsummary: ${clampSummary(summary)}${text.slice(end)}`
332
+ try {
333
+ writeFileSync(abs, next, 'utf8')
334
+ synced.push(line.target)
335
+ } catch {
336
+ skipped.push(line.target)
337
+ }
338
+ }
339
+ return { synced, skipped }
340
+ }
341
+
342
+ /**
343
+ * Issues the index has, for `lint` and `index --check`. Kept in one place so
344
+ * the CLI, the lint command and the dashboard cannot disagree.
345
+ *
346
+ * @param {string} memoryDir absolute path of the memory store
347
+ * @param {{ includeNoSummary?: boolean }} [options] `no-summary` is advisory, so
348
+ * `lint` opts out (it stays a quality nudge, not a failure)
349
+ * @returns {Array<{ kind: string, target?: string, detail: string }>}
350
+ */
351
+ export function indexIssues(memoryDir, options = {}) {
352
+ const plan = planIndex(memoryDir)
353
+ const issues = []
354
+ for (const line of plan.lines) {
355
+ // Scope: what is wrong with the *index*. "This line no longer matches its
356
+ // page" is `index --check`'s job (a rewrite fixes it), so lint stays free of
357
+ // duplicate reporting.
358
+ if (line.current.length > INDEX_LINE_MAX) {
359
+ issues.push({
360
+ kind: 'line-too-long',
361
+ target: line.target,
362
+ detail: `index 行 ${line.current.length} 字符(上限 ${INDEX_LINE_MAX}):${line.target}`,
363
+ })
364
+ } else if (line.declaredChars > INDEX_SUMMARY_MAX) {
365
+ // The header cap: rewrite will clamp it, so say so instead of silently
366
+ // trimming the author's words on the next `--write`.
367
+ issues.push({
368
+ kind: 'summary-too-long',
369
+ target: line.target,
370
+ detail: `summary 声明 ${line.declaredChars} 字(上限 ${INDEX_SUMMARY_MAX}):${line.target}`,
371
+ })
372
+ }
373
+ }
374
+ for (const path of plan.missing) {
375
+ issues.push({
376
+ kind: 'missing',
377
+ target: path,
378
+ detail: `页面未收录进 index(分节与顺序需人工决定):${path}`,
379
+ })
380
+ }
381
+ for (const path of plan.removed) {
382
+ issues.push({
383
+ kind: 'removed',
384
+ target: path,
385
+ detail: `index 指向已不存在的页(是否删行需人工确认):${path}`,
386
+ })
387
+ }
388
+ if (options.includeNoSummary === false) return issues
389
+ for (const line of plan.lines) {
390
+ if (line.summary.length === 0) {
391
+ issues.push({
392
+ kind: 'no-summary',
393
+ target: line.target,
394
+ detail: `页面未声明 summary(index 只有标题;补 frontmatter \`summary:\` 后会自动同步):${line.target}`,
395
+ })
396
+ }
397
+ }
398
+ return issues
399
+ }