@erclx/aitk 0.58.0 → 0.60.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.
@@ -0,0 +1,767 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { readdir, readFile } from 'node:fs/promises'
3
+ import { join } from 'node:path'
4
+ import { parseFrontmatter, readField } from '@/indexes/frontmatter'
5
+
6
+ export const RECORD_KINDS = ['plans', 'groundwork', 'intake', 'memory'] as const
7
+
8
+ export type RecordKind = (typeof RECORD_KINDS)[number]
9
+
10
+ const FOLDER_BY_KIND: Readonly<Record<RecordKind, string>> = {
11
+ plans: join('.claude', 'plans'),
12
+ groundwork: join('.claude', 'groundwork'),
13
+ intake: join('.claude', 'intake'),
14
+ memory: join('.claude', 'memory'),
15
+ }
16
+
17
+ /**
18
+ * `unknown-kind` is raised at the argument boundary rather than by the walk, and
19
+ * it sits here because both reach a caller through the same `reason` field. A
20
+ * union covering only what the walk returns would type a record the command can
21
+ * emit as impossible.
22
+ */
23
+ export const VALIDATE_REFUSALS = ['no-folder', 'unknown-kind'] as const
24
+
25
+ export type ValidateRefusal = (typeof VALIDATE_REFUSALS)[number]
26
+
27
+ export const FINDING_KINDS = [
28
+ 'name-malformed',
29
+ 'title-missing',
30
+ 'title-is-slug',
31
+ 'section-missing',
32
+ 'entry-unreasoned',
33
+ 'suggestion-missing',
34
+ 'question-unanswerable',
35
+ 'frontmatter-incomplete',
36
+ 'date-malformed',
37
+ 'index-missing',
38
+ 'state-missing',
39
+ 'closing-partial',
40
+ 'item-incomplete',
41
+ 'category-mismatch',
42
+ ] as const
43
+
44
+ export type FindingKind = (typeof FINDING_KINDS)[number]
45
+
46
+ export interface Finding {
47
+ readonly kind: FindingKind
48
+ /** The record the finding sits in, relative to the validated folder. */
49
+ readonly record: string
50
+ readonly subject: string
51
+ readonly message: string
52
+ }
53
+
54
+ export interface ValidateReport {
55
+ readonly ok: true
56
+ readonly kind: RecordKind
57
+ readonly records: number
58
+ readonly findings: readonly Finding[]
59
+ }
60
+
61
+ export interface ValidateRefused {
62
+ readonly ok: false
63
+ readonly reason: ValidateRefusal
64
+ readonly message: string
65
+ }
66
+
67
+ export type ValidateOutcome = ValidateReport | ValidateRefused
68
+
69
+ export function recordsDir(root: string, kind: RecordKind): string {
70
+ return join(root, FOLDER_BY_KIND[kind])
71
+ }
72
+
73
+ export function isRecordKind(value: string): value is RecordKind {
74
+ return (RECORD_KINDS as readonly string[]).includes(value)
75
+ }
76
+
77
+ const NONE_IDENTIFIED = 'None identified.'
78
+ const NUMBERED_FILE = /^\d{2}-[a-z0-9]+(-[a-z0-9]+)*\.md$/
79
+
80
+ function finding(
81
+ kind: FindingKind,
82
+ record: string,
83
+ subject: string,
84
+ message: string,
85
+ ): Finding {
86
+ return { kind, record, subject, message }
87
+ }
88
+
89
+ async function listMarkdown(dir: string): Promise<string[]> {
90
+ const entries = await readdir(dir, { withFileTypes: true })
91
+
92
+ return entries
93
+ .filter((entry) => entry.isFile() && entry.name.endsWith('.md'))
94
+ .map((entry) => entry.name)
95
+ .sort()
96
+ }
97
+
98
+ async function listFolders(dir: string): Promise<string[]> {
99
+ const entries = await readdir(dir, { withFileTypes: true })
100
+
101
+ return entries
102
+ .filter((entry) => entry.isDirectory())
103
+ .map((entry) => entry.name)
104
+ .sort()
105
+ }
106
+
107
+ const PLAN_NAME = /^feature-[a-z0-9]+(-[a-z0-9]+)*\.md$/
108
+ const PLAN_TITLE = /^#[ \t]+Feature:[ \t]+\S/
109
+ /**
110
+ * An entry names a file and says something about it. Both halves are tested as
111
+ * facts rather than as a syntax: a backticked span anywhere, and prose left over
112
+ * once the spans are removed.
113
+ *
114
+ * Requiring the path to lead and the reason to follow a colon was the first
115
+ * shape and it reported 80 of 178 archived plans. The corpus writes
116
+ * `- Label: prose naming a path` as often as `- path: reason`, and both name the
117
+ * file and say why, so the stricter rule measured a house style rather than a
118
+ * defect.
119
+ */
120
+ function statesReason(entry: string): boolean {
121
+ if (!/`[^`]+`/.test(entry)) return false
122
+
123
+ const prose = entry.replace(/`[^`]*`/g, '').replace(/^-[ \t]*/, '')
124
+ return /[A-Za-z0-9]/.test(prose)
125
+ }
126
+ const QUESTION_ITEM = /^\d+[a-z]?\.[ \t]+\S/
127
+
128
+ const PLAN_SECTIONS = [
129
+ 'Summary',
130
+ 'Constraints',
131
+ 'Files to touch',
132
+ 'Risks',
133
+ 'Questions',
134
+ ] as const
135
+
136
+ type PlanSection = (typeof PLAN_SECTIONS)[number]
137
+
138
+ const PLAN_REQUIRED: readonly PlanSection[] = [
139
+ 'Summary',
140
+ 'Files to touch',
141
+ 'Risks',
142
+ 'Questions',
143
+ ]
144
+
145
+ const FENCE = /^(`{3,}|~{3,})/
146
+
147
+ /**
148
+ * Drops every fenced block, so a quoted template is not read as content. A plan
149
+ * showing the shape it writes puts real-looking bullets and headings inside a
150
+ * fence, and scanning them reports the example rather than the plan.
151
+ *
152
+ * A closing fence has to match the opening character and be at least as long,
153
+ * which is what keeps a ```` block holding a ``` example from closing early. An
154
+ * unterminated fence swallows the rest of the document, which under-reports a
155
+ * malformed file rather than reporting its remainder as content.
156
+ */
157
+ export function linesOutsideFences(text: string): string[] {
158
+ const kept: string[] = []
159
+ let fence: string | undefined
160
+
161
+ for (const line of text.split('\n')) {
162
+ const match = FENCE.exec(line.trim())
163
+
164
+ if (fence) {
165
+ const closes =
166
+ match && match[1][0] === fence[0] && match[1].length >= fence.length
167
+ if (closes) fence = undefined
168
+ continue
169
+ }
170
+
171
+ if (match) {
172
+ fence = match[1]
173
+ continue
174
+ }
175
+
176
+ kept.push(line)
177
+ }
178
+
179
+ return kept
180
+ }
181
+
182
+ /**
183
+ * A line standing alone as a bold label or an H2, whatever it names. A plan is
184
+ * free to carry a section of its own, so the split has to see one to close the
185
+ * section above it.
186
+ */
187
+ const MARKER_LINE = /^(?:##[ \t]+(.+?)|\*\*(.+?):\*\*)[ \t]*$/
188
+
189
+ /**
190
+ * A section opens as a bold label or as an H2 and both count. The corpus writes
191
+ * `Summary` as a heading and the other four as bold labels, and roughly a fifth
192
+ * of it swaps one for the other. Reporting the variant would fail nearly every
193
+ * plan present on the rule a reader is least served by, which is what teaches
194
+ * them to skip the output.
195
+ */
196
+ export function sectionMarker(line: string): PlanSection | undefined {
197
+ const match = MARKER_LINE.exec(line.trim())
198
+ if (!match) return undefined
199
+
200
+ const name = match[1] ?? match[2]
201
+ return PLAN_SECTIONS.find((entry) => entry === name)
202
+ }
203
+
204
+ /** The spelling a finding names, which is the one the standard's template ships. */
205
+ export function preferredMarker(section: PlanSection): string {
206
+ return section === 'Summary' ? '## Summary' : `**${section}:**`
207
+ }
208
+
209
+ export function splitPlanSections(text: string): Map<string, string[]> {
210
+ const sections = new Map<string, string[]>()
211
+ let current: string | undefined
212
+
213
+ for (const line of linesOutsideFences(text)) {
214
+ // Any marker-shaped line closes the section above it, and only a recognized
215
+ // one opens a section. A plan carrying a label of its own would otherwise
216
+ // collect its bullets into whichever section came before.
217
+ if (MARKER_LINE.test(line.trim())) {
218
+ current = sectionMarker(line)
219
+ if (current) sections.set(current, [])
220
+ continue
221
+ }
222
+
223
+ if (current) sections.get(current)?.push(line)
224
+ }
225
+
226
+ return sections
227
+ }
228
+
229
+ interface Question {
230
+ readonly label: string
231
+ readonly body: readonly string[]
232
+ }
233
+
234
+ export function readQuestions(lines: readonly string[]): Question[] {
235
+ const questions: { label: string; body: string[] }[] = []
236
+
237
+ for (const line of lines) {
238
+ const trimmed = line.trim()
239
+ if (QUESTION_ITEM.test(trimmed)) {
240
+ questions.push({ label: trimmed, body: [] })
241
+ continue
242
+ }
243
+
244
+ questions.at(-1)?.body.push(trimmed)
245
+ }
246
+
247
+ return questions
248
+ }
249
+
250
+ function shorten(label: string): string {
251
+ return label.length > 60 ? `${label.slice(0, 57)}...` : label
252
+ }
253
+
254
+ function checkQuestionContract(name: string, lines: string[]): Finding[] {
255
+ if (lines.some((line) => line.trim() === NONE_IDENTIFIED)) return []
256
+
257
+ const findings: Finding[] = []
258
+
259
+ for (const question of readQuestions(lines)) {
260
+ const subject = shorten(question.label)
261
+
262
+ if (!question.body.some((line) => line.startsWith('- Suggested:'))) {
263
+ findings.push(
264
+ finding(
265
+ 'suggestion-missing',
266
+ name,
267
+ subject,
268
+ 'carries no Suggested line, so it arrives at execution as a stop.',
269
+ ),
270
+ )
271
+ }
272
+
273
+ if (!question.body.some((line) => line.startsWith('- Answer:'))) {
274
+ findings.push(
275
+ finding(
276
+ 'question-unanswerable',
277
+ name,
278
+ subject,
279
+ 'carries no Answer slot, so the blank-answer default has nowhere to sit.',
280
+ ),
281
+ )
282
+ }
283
+ }
284
+
285
+ return findings
286
+ }
287
+
288
+ export function checkPlan(name: string, text: string): Finding[] {
289
+ const findings: Finding[] = []
290
+
291
+ if (!PLAN_NAME.test(name)) {
292
+ findings.push(
293
+ finding(
294
+ 'name-malformed',
295
+ name,
296
+ name,
297
+ 'is not named feature-<slug>.md with a kebab-case slug.',
298
+ ),
299
+ )
300
+ }
301
+
302
+ const lines = linesOutsideFences(text)
303
+
304
+ if (!lines.some((line) => PLAN_TITLE.test(line))) {
305
+ findings.push(
306
+ finding('title-missing', name, name, 'opens with no # Feature: heading.'),
307
+ )
308
+ }
309
+
310
+ const sections = splitPlanSections(text)
311
+
312
+ for (const marker of PLAN_REQUIRED) {
313
+ if (!sections.has(marker)) {
314
+ findings.push(
315
+ finding(
316
+ 'section-missing',
317
+ name,
318
+ preferredMarker(marker),
319
+ 'is required and the plan carries no such section.',
320
+ ),
321
+ )
322
+ }
323
+ }
324
+
325
+ for (const line of sections.get('Files to touch') ?? []) {
326
+ const trimmed = line.trim()
327
+ if (!trimmed.startsWith('- ') || trimmed === `- ${NONE_IDENTIFIED}`)
328
+ continue
329
+
330
+ if (!statesReason(trimmed)) {
331
+ findings.push(
332
+ finding(
333
+ 'entry-unreasoned',
334
+ name,
335
+ shorten(trimmed),
336
+ 'names no file, or names one and says nothing about it.',
337
+ ),
338
+ )
339
+ }
340
+ }
341
+
342
+ findings.push(...checkQuestionContract(name, sections.get('Questions') ?? []))
343
+
344
+ return findings
345
+ }
346
+
347
+ const DATE_FIELD = /^date:[ \t]*'?"?(\d{4}-\d{2}-\d{2})'?"?[ \t]*$/m
348
+
349
+ /**
350
+ * Reads the opening date off the raw block rather than the parsed fields. A YAML
351
+ * parser resolves an unquoted `YYYY-MM-DD` to a date value on the core schema
352
+ * and to a string elsewhere, and a check keyed on the parsed type would report a
353
+ * conforming file on one runtime and not the other.
354
+ */
355
+ function hasOpeningDate(raw: string): boolean {
356
+ return DATE_FIELD.test(raw)
357
+ }
358
+
359
+ async function checkFolderFrontmatter(
360
+ dir: string,
361
+ slug: string,
362
+ files: readonly string[],
363
+ indexFile: string,
364
+ ): Promise<Finding[]> {
365
+ const perFile = await Promise.all(
366
+ files.map(async (file) => {
367
+ const found: Finding[] = []
368
+ const frontmatter = parseFrontmatter(
369
+ await readFile(join(dir, file), 'utf8'),
370
+ )
371
+
372
+ const missing = ['title', 'description'].filter(
373
+ (field) => !readField(frontmatter, field),
374
+ )
375
+
376
+ if (missing.length > 0) {
377
+ found.push(
378
+ finding(
379
+ 'frontmatter-incomplete',
380
+ slug,
381
+ file,
382
+ `carries no ${missing.join(' and no ')}.`,
383
+ ),
384
+ )
385
+ }
386
+
387
+ if (file === indexFile && !hasOpeningDate(frontmatter?.raw ?? '')) {
388
+ found.push(
389
+ finding(
390
+ 'date-malformed',
391
+ slug,
392
+ file,
393
+ 'carries no date field as YYYY-MM-DD, so the folder states no opening day.',
394
+ ),
395
+ )
396
+ }
397
+
398
+ if (file !== indexFile && !NUMBERED_FILE.test(file)) {
399
+ found.push(
400
+ finding(
401
+ 'name-malformed',
402
+ slug,
403
+ file,
404
+ 'is not numbered NN-<name>.md, so the folder has no read order.',
405
+ ),
406
+ )
407
+ }
408
+
409
+ return found
410
+ }),
411
+ )
412
+
413
+ return perFile.flat()
414
+ }
415
+
416
+ const GROUNDWORK_INDEX = 'README.md'
417
+ const GROUNDWORK_STATE = '01-current-state.md'
418
+ const GROUNDWORK_DECISION = '06-'
419
+ const GROUNDWORK_HANDOFF = '07-'
420
+
421
+ async function checkTrack(dir: string, slug: string): Promise<Finding[]> {
422
+ const files = await listMarkdown(dir)
423
+ const findings: Finding[] = []
424
+
425
+ if (!files.includes(GROUNDWORK_INDEX)) {
426
+ findings.push(
427
+ finding(
428
+ 'index-missing',
429
+ slug,
430
+ GROUNDWORK_INDEX,
431
+ 'is absent, so the track carries no file map and no reason it is running.',
432
+ ),
433
+ )
434
+ }
435
+
436
+ if (!files.includes(GROUNDWORK_STATE)) {
437
+ findings.push(
438
+ finding(
439
+ 'state-missing',
440
+ slug,
441
+ GROUNDWORK_STATE,
442
+ 'is absent, so the track states no measured current state.',
443
+ ),
444
+ )
445
+ }
446
+
447
+ // A track closes on the decision and the handoff together. One without the
448
+ // other reads as closed to anyone scanning filenames and strands the half a
449
+ // returning session actually opens.
450
+ const decided = files.some((file) => file.startsWith(GROUNDWORK_DECISION))
451
+ const handed = files.some((file) => file.startsWith(GROUNDWORK_HANDOFF))
452
+
453
+ if (decided !== handed) {
454
+ findings.push(
455
+ finding(
456
+ 'closing-partial',
457
+ slug,
458
+ decided ? GROUNDWORK_HANDOFF : GROUNDWORK_DECISION,
459
+ `is absent while ${decided ? '06' : '07'} is present, so the track is neither live nor closed.`,
460
+ ),
461
+ )
462
+ }
463
+
464
+ findings.push(
465
+ ...(await checkFolderFrontmatter(dir, slug, files, GROUNDWORK_INDEX)),
466
+ )
467
+
468
+ return findings
469
+ }
470
+
471
+ const INTAKE_INDEX = '00-overview.md'
472
+ const INTAKE_HANDOFF = '99-next-session.md'
473
+
474
+ const ITEM_HEADING = /^###[ \t]+\S/
475
+ const ITEM_REQUIRED = ['Problem', 'Fix', 'Worth it', 'You'] as const
476
+
477
+ function bulletLabel(line: string): string | undefined {
478
+ const match = /^-[ \t]+\*\*([^:*]+):\*\*/.exec(line.trim())
479
+ return match ? match[1].trim() : undefined
480
+ }
481
+
482
+ export function checkItems(
483
+ slug: string,
484
+ file: string,
485
+ text: string,
486
+ ): Finding[] {
487
+ const findings: Finding[] = []
488
+ const items: { heading: string; labels: string[] }[] = []
489
+
490
+ for (const line of linesOutsideFences(text)) {
491
+ if (ITEM_HEADING.test(line)) {
492
+ items.push({ heading: line.trim().replace(/^###[ \t]+/, ''), labels: [] })
493
+ continue
494
+ }
495
+
496
+ const label = bulletLabel(line)
497
+ if (label) items.at(-1)?.labels.push(label)
498
+ }
499
+
500
+ for (const item of items) {
501
+ const missing = ITEM_REQUIRED.filter(
502
+ (label) => !item.labels.includes(label),
503
+ )
504
+
505
+ if (missing.length > 0) {
506
+ findings.push(
507
+ finding(
508
+ 'item-incomplete',
509
+ slug,
510
+ `${file}: ${shorten(item.heading)}`,
511
+ `states no ${missing.join(', no ')}.`,
512
+ ),
513
+ )
514
+ }
515
+
516
+ if (item.labels.includes('Open') && !item.labels.includes('Suggested')) {
517
+ findings.push(
518
+ finding(
519
+ 'suggestion-missing',
520
+ slug,
521
+ `${file}: ${shorten(item.heading)}`,
522
+ 'asks an open question and suggests nothing, so a bare answer decides it.',
523
+ ),
524
+ )
525
+ }
526
+ }
527
+
528
+ return findings
529
+ }
530
+
531
+ async function checkDump(dir: string, slug: string): Promise<Finding[]> {
532
+ const files = await listMarkdown(dir)
533
+ const findings: Finding[] = []
534
+
535
+ if (!files.includes(INTAKE_INDEX)) {
536
+ findings.push(
537
+ finding(
538
+ 'index-missing',
539
+ slug,
540
+ INTAKE_INDEX,
541
+ 'is absent, so the dump carries no cluster table and no verdict counts.',
542
+ ),
543
+ )
544
+ }
545
+
546
+ findings.push(
547
+ ...(await checkFolderFrontmatter(dir, slug, files, INTAKE_INDEX)),
548
+ )
549
+
550
+ // The two reserved files hold no items. Running the item check over the
551
+ // handoff would report every heading it carries as a malformed item.
552
+ const clusters = files.filter(
553
+ (file) => file !== INTAKE_INDEX && file !== INTAKE_HANDOFF,
554
+ )
555
+
556
+ const perCluster = await Promise.all(
557
+ clusters.map(async (file) =>
558
+ checkItems(slug, file, await readFile(join(dir, file), 'utf8')),
559
+ ),
560
+ )
561
+
562
+ return [...findings, ...perCluster.flat()]
563
+ }
564
+
565
+ const MEMORY_INDEX = 'index.md'
566
+ const MEMORY_FIELDS = ['title', 'description', 'category'] as const
567
+
568
+ /**
569
+ * The filename prefix and the `category` field are one fact in two spellings,
570
+ * so the map is the whole type list and the comparison against it is what
571
+ * catches a prefix outside the set, a field disagreeing with the prefix, and a
572
+ * casing drift that would open a second group in the catalog.
573
+ */
574
+ const CATEGORY_BY_TYPE = {
575
+ feedback: 'Feedback',
576
+ project: 'Project',
577
+ user: 'User',
578
+ reference: 'Reference',
579
+ } as const
580
+
581
+ type MemoryType = keyof typeof CATEGORY_BY_TYPE
582
+
583
+ const MEMORY_TYPES = Object.keys(CATEGORY_BY_TYPE) as readonly MemoryType[]
584
+
585
+ const MEMORY_NAME = /^([a-z]+)-[a-z0-9]+(?:-[a-z0-9]+)*\.md$/
586
+
587
+ /** The two markers a rule-bearing body carries, on top of the rule line itself. */
588
+ const MEMORY_MARKERS = ['**Why:**', '**How to apply:**'] as const
589
+
590
+ function memoryType(value: string): MemoryType | undefined {
591
+ return MEMORY_TYPES.find((type) => type === value)
592
+ }
593
+
594
+ export function checkMemory(name: string, text: string): Finding[] {
595
+ const findings: Finding[] = []
596
+ const match = MEMORY_NAME.exec(name)
597
+ const named = match ? memoryType(match[1]) : undefined
598
+
599
+ if (!named) {
600
+ findings.push(
601
+ finding(
602
+ 'name-malformed',
603
+ name,
604
+ name,
605
+ `is not named <type>-<slug>.md with a type of ${MEMORY_TYPES.join(', ')}.`,
606
+ ),
607
+ )
608
+ }
609
+
610
+ const frontmatter = parseFrontmatter(text)
611
+ const missing = MEMORY_FIELDS.filter(
612
+ (field) => !readField(frontmatter, field),
613
+ )
614
+
615
+ if (missing.length > 0) {
616
+ findings.push(
617
+ finding(
618
+ 'frontmatter-incomplete',
619
+ name,
620
+ name,
621
+ `carries no ${missing.join(' and no ')}.`,
622
+ ),
623
+ )
624
+ }
625
+
626
+ // Its own kind rather than `title-missing`, which means an absent heading on a
627
+ // plan. One kind covering both leaves a caller filtering the JSON unable to
628
+ // tell a record with no title from one whose title is its own slug.
629
+ if (readField(frontmatter, 'title') === name.replace(/\.md$/, '')) {
630
+ findings.push(
631
+ finding(
632
+ 'title-is-slug',
633
+ name,
634
+ name,
635
+ 'is titled with its own filename, so the catalog renders a slug where the rule belongs.',
636
+ ),
637
+ )
638
+ }
639
+
640
+ const category = readField(frontmatter, 'category')
641
+
642
+ // Reported against the prefix alone. A name the prefix rule already failed
643
+ // has no type to compare against, and reporting it twice names one defect as
644
+ // two.
645
+ if (named && category && category !== CATEGORY_BY_TYPE[named]) {
646
+ findings.push(
647
+ finding(
648
+ 'category-mismatch',
649
+ name,
650
+ category,
651
+ `is not ${CATEGORY_BY_TYPE[named]}, which the filename prefix declares.`,
652
+ ),
653
+ )
654
+ }
655
+
656
+ return [
657
+ ...findings,
658
+ ...checkMemoryBody(
659
+ name,
660
+ text.slice(frontmatter?.raw.length ?? 0),
661
+ named ?? category,
662
+ ),
663
+ ]
664
+ }
665
+
666
+ /**
667
+ * A `user` or `reference` entry is a single sentence by design, so the markers
668
+ * are checked only where a rule is being stated. The type is read off the
669
+ * prefix, falling back to the category so a misnamed file is still checked
670
+ * against the shape it claims.
671
+ */
672
+ function checkMemoryBody(
673
+ name: string,
674
+ text: string,
675
+ claimed: string | undefined,
676
+ ): Finding[] {
677
+ const type = claimed && memoryType(claimed.toLowerCase())
678
+ if (type !== 'feedback' && type !== 'project') return []
679
+
680
+ const body = linesOutsideFences(text).filter((line) => line.trim().length > 0)
681
+
682
+ const findings: Finding[] = []
683
+ const opening = body[0]
684
+
685
+ if (!opening || MEMORY_MARKERS.some((marker) => opening.startsWith(marker))) {
686
+ findings.push(
687
+ finding(
688
+ 'section-missing',
689
+ name,
690
+ 'the rule line',
691
+ 'is absent, so the entry carries a rationale with no rule to apply.',
692
+ ),
693
+ )
694
+ }
695
+
696
+ for (const marker of MEMORY_MARKERS) {
697
+ if (!body.some((line) => line.startsWith(marker))) {
698
+ findings.push(
699
+ finding(
700
+ 'section-missing',
701
+ name,
702
+ marker,
703
+ `is required on a ${type} entry and the body carries no such line.`,
704
+ ),
705
+ )
706
+ }
707
+ }
708
+
709
+ return findings
710
+ }
711
+
712
+ function refuse(reason: ValidateRefusal, message: string): ValidateRefused {
713
+ return { ok: false, reason, message }
714
+ }
715
+
716
+ /** The walk for a kind whose records are files in one flat folder. */
717
+ async function validateFiles(
718
+ dir: string,
719
+ kind: RecordKind,
720
+ check: (name: string, text: string) => Finding[],
721
+ skip: (file: string) => boolean = () => false,
722
+ ): Promise<ValidateReport> {
723
+ const files = (await listMarkdown(dir)).filter((file) => !skip(file))
724
+
725
+ const perFile = await Promise.all(
726
+ files.map(async (file) =>
727
+ check(file, await readFile(join(dir, file), 'utf8')),
728
+ ),
729
+ )
730
+
731
+ return { ok: true, kind, records: files.length, findings: perFile.flat() }
732
+ }
733
+
734
+ /**
735
+ * Reports what every record in one gitignored folder claims against the shape
736
+ * its standard fixes. It writes nothing: the folder is per-machine scratch with
737
+ * no history behind it, so a repair that guessed wrong could not be undone.
738
+ */
739
+ export async function validateRecords(
740
+ root: string,
741
+ kind: RecordKind,
742
+ ): Promise<ValidateOutcome> {
743
+ const dir = recordsDir(root, kind)
744
+
745
+ if (!existsSync(dir)) {
746
+ return refuse('no-folder', `No ${kind} folder at ${dir}.`)
747
+ }
748
+
749
+ if (kind === 'plans') return validateFiles(dir, kind, checkPlan)
750
+
751
+ if (kind === 'memory') {
752
+ return validateFiles(
753
+ dir,
754
+ kind,
755
+ checkMemory,
756
+ (file) => file === MEMORY_INDEX,
757
+ )
758
+ }
759
+
760
+ const folders = await listFolders(dir)
761
+ const check = kind === 'groundwork' ? checkTrack : checkDump
762
+ const perFolder = await Promise.all(
763
+ folders.map((slug) => check(join(dir, slug), slug)),
764
+ )
765
+
766
+ return { ok: true, kind, records: folders.length, findings: perFolder.flat() }
767
+ }