hafez 1.2.0 → 1.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.
Files changed (52) hide show
  1. package/README.md +67 -9
  2. package/dist/apply.d.ts +30 -0
  3. package/dist/apply.js +582 -0
  4. package/dist/batch-ops.d.ts +470 -0
  5. package/dist/batch-ops.js +446 -0
  6. package/dist/cli/args.d.ts +19 -0
  7. package/dist/cli/args.js +53 -0
  8. package/dist/cli/batch-errors.js +6 -3
  9. package/dist/cli/commands.d.ts +24 -108
  10. package/dist/cli/commands.js +297 -313
  11. package/dist/cli/help-agent.d.ts +0 -5
  12. package/dist/cli/help-agent.js +44 -5
  13. package/dist/cli/index.d.ts +41 -0
  14. package/dist/cli/index.js +172 -172
  15. package/dist/cli/resolve-vault.js +2 -1
  16. package/dist/cli/schema-introspect.d.ts +1 -1
  17. package/dist/cli/schema-introspect.js +6 -22
  18. package/dist/cli/upgrade.d.ts +42 -0
  19. package/dist/cli/upgrade.js +305 -0
  20. package/dist/cli.js +0 -0
  21. package/dist/contracts.d.ts +55 -6
  22. package/dist/contracts.js +110 -23
  23. package/dist/dates.d.ts +10 -0
  24. package/dist/dates.js +27 -0
  25. package/dist/db.d.ts +27 -2
  26. package/dist/db.js +318 -56
  27. package/dist/digest.js +2 -0
  28. package/dist/document.d.ts +117 -0
  29. package/dist/document.js +578 -0
  30. package/dist/export-okf.js +48 -34
  31. package/dist/git.d.ts +7 -8
  32. package/dist/git.js +198 -63
  33. package/dist/index.d.ts +3 -4
  34. package/dist/index.js +302 -915
  35. package/dist/knowledge-index.d.ts +23 -1
  36. package/dist/knowledge-index.js +71 -13
  37. package/dist/merge.d.ts +1 -1
  38. package/dist/merge.js +106 -86
  39. package/dist/schema.js +4 -4
  40. package/dist/templates.d.ts +6 -0
  41. package/dist/templates.js +27 -27
  42. package/dist/types.d.ts +86 -12
  43. package/dist/vault.d.ts +51 -6
  44. package/dist/vault.js +114 -11
  45. package/package.json +2 -2
  46. package/skill/SKILL.md +51 -110
  47. package/dist/parser.d.ts +0 -18
  48. package/dist/parser.js +0 -68
  49. package/dist/query.d.ts +0 -24
  50. package/dist/query.js +0 -167
  51. package/dist/sections.d.ts +0 -54
  52. package/dist/sections.js +0 -297
@@ -1,3 +1,25 @@
1
+ /** One indexed document, as the SQLite index can hand it over. index.md needs
2
+ * nothing the index does not already hold, so a regeneration reads rows
3
+ * instead of re-reading and re-parsing every file in the vault. Declared here
4
+ * (not in db.ts) to keep the module edge pointing one way: db.ts already
5
+ * imports from this file. */
6
+ export interface VaultIndexRow {
7
+ slug: string;
8
+ kind: 'entity' | 'knowledge';
9
+ name: string;
10
+ type: string | null;
11
+ status: string | null;
12
+ confidence: string | null;
13
+ description: string | null;
14
+ domain: string[];
15
+ body: string;
16
+ }
1
17
  /** Ensure every generated local-only artifact is covered by .git/info/exclude. */
2
18
  export declare function ensureLocalExclude(vaultPath: string): void;
3
- export declare function generateVaultIndex(vaultPath: string): void;
19
+ /** Regenerate the vault-root index.md.
20
+ *
21
+ * `rows` is the SQLite index's view of the vault — every mutation refreshes
22
+ * those rows anyway, so passing them avoids a second full-vault read for the
23
+ * same content. Omitting them (standalone/one-off use) falls back to reading
24
+ * the files directly. */
25
+ export declare function generateVaultIndex(vaultPath: string, rows?: VaultIndexRow[]): void;
@@ -1,11 +1,29 @@
1
1
  // src/knowledge-index.ts
2
2
  // Generates the vault-root index.md covering entities (grouped by status) and
3
3
  // knowledge (grouped by domain) — local-only, auto-regenerated on every entity/knowledge write.
4
- import { readdirSync, readFileSync, writeFileSync, existsSync, statSync, mkdirSync } from 'fs';
5
- import { join, basename } from 'path';
6
- import { parseFilePath } from './vault.js';
7
- import { deriveSummary } from './sections.js';
4
+ import { readFileSync, writeFileSync, existsSync, statSync, mkdirSync } from 'fs';
5
+ import { join, basename, resolve } from 'path';
6
+ import { parseFilePath, scanVaultDir, kindDir } from './vault.js';
7
+ import { deriveSummary } from './document.js';
8
8
  import { ENTITY_STATUSES } from './contracts.js';
9
+ /** Index rows in the shape the renderer below expects — the same
10
+ * {slug, fm, body} triple scanParsed produces from disk. */
11
+ function fromRows(rows, kind) {
12
+ return rows
13
+ .filter(r => r.kind === kind)
14
+ .map(r => ({
15
+ slug: r.slug,
16
+ body: r.body,
17
+ fm: {
18
+ name: r.name,
19
+ type: r.type ?? undefined,
20
+ status: r.status ?? undefined,
21
+ confidence: r.confidence ?? undefined,
22
+ description: r.description ?? undefined,
23
+ domain: r.domain,
24
+ },
25
+ }));
26
+ }
9
27
  function truncate(s) {
10
28
  return s.length > 100 ? s.slice(0, 97) + '...' : s;
11
29
  }
@@ -19,9 +37,11 @@ function formatEntry(item) {
19
37
  /** Parse every .md directly in dir (non-recursive — auto-excludes archive/), skipping malformed files. */
20
38
  function scanParsed(dir) {
21
39
  const docs = [];
22
- for (const file of readdirSync(dir).filter(f => f.endsWith('.md'))) {
40
+ for (const file of scanVaultDir(dir)) {
23
41
  try {
24
- const { frontmatter: fm, body } = parseFilePath(join(dir, file));
42
+ const parsed = parseFilePath(file);
43
+ const fm = parsed.frontmatter;
44
+ const body = parsed.body;
25
45
  if (!fm.name)
26
46
  continue;
27
47
  docs.push({ slug: basename(file, '.md'), fm, body });
@@ -36,11 +56,42 @@ function scanParsed(dir) {
36
56
  * show up in the user's `git status`, but forcing a tracked .gitignore entry
37
57
  * would dirty their vault — so they go into .git/info/exclude instead. */
38
58
  const LOCAL_EXCLUDES = ['/index.md', '/.hafez.db', '/.hafez.db-shm', '/.hafez.db-wal'];
59
+ /** Locate the git directory that owns `info/exclude` for this vault.
60
+ * `.git` is a directory in a normal clone, but a *gitfile* (`gitdir: <path>`)
61
+ * in a linked worktree or submodule — treating that file as "not a repo" is
62
+ * what let index.md and .hafez.db pollute `git status` there. Git reads
63
+ * `info/exclude` from the COMMON dir, so for a linked worktree the pointed-at
64
+ * per-worktree dir is one more hop from the answer: its `commondir` file names
65
+ * the shared dir (writing the exclude in the per-worktree dir has no effect).
66
+ * Returns null when the vault is not a git repo at all. */
67
+ function resolveExcludeGitDir(vaultPath) {
68
+ const dotGit = join(vaultPath, '.git');
69
+ if (!existsSync(dotGit))
70
+ return null;
71
+ const stat = statSync(dotGit);
72
+ if (stat.isDirectory())
73
+ return dotGit;
74
+ if (!stat.isFile())
75
+ return null;
76
+ const pointer = /^gitdir:\s*(.+)$/m.exec(readFileSync(dotGit, 'utf-8'));
77
+ if (!pointer)
78
+ return null;
79
+ const gitDir = resolve(vaultPath, pointer[1].trim());
80
+ if (!existsSync(gitDir))
81
+ return null;
82
+ const commonDirFile = join(gitDir, 'commondir');
83
+ if (existsSync(commonDirFile)) {
84
+ const commonDir = resolve(gitDir, readFileSync(commonDirFile, 'utf-8').trim());
85
+ if (existsSync(commonDir))
86
+ return commonDir;
87
+ }
88
+ return gitDir;
89
+ }
39
90
  /** Ensure every generated local-only artifact is covered by .git/info/exclude. */
40
91
  export function ensureLocalExclude(vaultPath) {
41
92
  try {
42
- const gitDir = join(vaultPath, '.git');
43
- if (!existsSync(gitDir) || !statSync(gitDir).isDirectory())
93
+ const gitDir = resolveExcludeGitDir(vaultPath);
94
+ if (!gitDir)
44
95
  return;
45
96
  const excludePath = join(gitDir, 'info', 'exclude');
46
97
  const existing = existsSync(excludePath) ? readFileSync(excludePath, 'utf-8') : '';
@@ -54,17 +105,24 @@ export function ensureLocalExclude(vaultPath) {
54
105
  }
55
106
  catch { /* best effort — never fail a vault write over ignore hygiene */ }
56
107
  }
57
- export function generateVaultIndex(vaultPath) {
58
- const entitiesDir = join(vaultPath, 'entities');
59
- const knowledgeDir = join(vaultPath, 'knowledge');
108
+ /** Regenerate the vault-root index.md.
109
+ *
110
+ * `rows` is the SQLite index's view of the vault — every mutation refreshes
111
+ * those rows anyway, so passing them avoids a second full-vault read for the
112
+ * same content. Omitting them (standalone/one-off use) falls back to reading
113
+ * the files directly. */
114
+ export function generateVaultIndex(vaultPath, rows) {
115
+ const entitiesDir = join(vaultPath, kindDir('entity'));
116
+ const knowledgeDir = join(vaultPath, kindDir('knowledge'));
60
117
  const hasEntities = existsSync(entitiesDir);
61
118
  const hasKnowledge = existsSync(knowledgeDir);
62
119
  if (!hasEntities && !hasKnowledge)
63
120
  return;
121
+ const docsFor = (kind, dir) => rows ? fromRows(rows, kind) : scanParsed(dir);
64
122
  const lines = ['# Vault Index', '', '> Auto-generated by hafez. Do not edit manually.', ''];
65
123
  if (hasEntities) {
66
124
  const byStatus = new Map();
67
- for (const { slug, fm, body } of scanParsed(entitiesDir)) {
125
+ for (const { slug, fm, body } of docsFor('entity', entitiesDir)) {
68
126
  const status = fm.status ?? 'active';
69
127
  const list = byStatus.get(status) ?? [];
70
128
  list.push({ slug, name: fm.name, summary: truncate(deriveSummary('entity', fm, body)), suffix: fm.type ?? 'entity' });
@@ -90,7 +148,7 @@ export function generateVaultIndex(vaultPath) {
90
148
  }
91
149
  if (hasKnowledge) {
92
150
  const entries = [];
93
- for (const { slug, fm, body } of scanParsed(knowledgeDir)) {
151
+ for (const { slug, fm, body } of docsFor('knowledge', knowledgeDir)) {
94
152
  entries.push({
95
153
  slug,
96
154
  name: fm.name,
package/dist/merge.d.ts CHANGED
@@ -1 +1 @@
1
- export declare function mergeVaultContent(remote: string, local: string): string;
1
+ export declare function mergeVaultContent(remote: string, local: string, kind: 'entity' | 'knowledge' | 'session'): string;
package/dist/merge.js CHANGED
@@ -1,13 +1,13 @@
1
1
  // src/merge.ts
2
- import { parseContent, serializeFile } from './vault.js';
3
- import { parseSessionLogHeading } from './parser.js';
2
+ import { parseContent, serializeFile, ARRAY_FIELDS } from './vault.js';
3
+ import { parseSessionLogHeading, splitLogEntries, documentFor } from './document.js';
4
+ import { APPEND_ONLY_SECTIONS } from './contracts.js';
4
5
  // Fields that are ISO date strings — latest date wins
5
6
  const DATE_FIELDS = ['last-touched', 'last-reinforced', 'created'];
6
7
  // Fields that are numeric counters — max wins
7
8
  const COUNT_FIELDS = ['reinforcement-count', 'staleness-days'];
8
- // Fields that are always arrays — union with dedup
9
- const ARRAY_FIELDS_UNCAPPED = ['tags', 'domain', 'related'];
10
- export function mergeVaultContent(remote, local) {
9
+ // Array fields (vault.ARRAY_FIELDS — the same set parsing coerces) union with dedup
10
+ export function mergeVaultContent(remote, local, kind) {
11
11
  const r = parseContent(remote);
12
12
  const l = parseContent(local);
13
13
  // Scalar policy: the side with the newer last-touched wins; local on tie.
@@ -15,7 +15,18 @@ export function mergeVaultContent(remote, local) {
15
15
  // array/date/count frontmatter fields are always unioned regardless.
16
16
  const localWins = String(l.frontmatter?.['last-touched'] ?? '') >= String(r.frontmatter?.['last-touched'] ?? '');
17
17
  const fm = mergeFrontmatter(r.frontmatter, l.frontmatter, localWins);
18
- const body = mergeBody(r.body, l.body, localWins);
18
+ // The Document binds by kind — the same binding every write path uses (see
19
+ // DocContext), so a section this merge preserves stays structural for the
20
+ // next update too. The two sides come from divergent histories whose type
21
+ // may differ (a promote race leaves one side 'capture' and the other
22
+ // 'project'); the kind-level set keeps every same-kind section structural,
23
+ // while cross-KIND headings (a session-only ## Decisions quoted in an
24
+ // entity Brief) are not boundaries. Known residual: a same-kind heading
25
+ // quoted at line start in one side's section splits at that false boundary
26
+ // and can survive the merge as its own section — the fix is fence/quote
27
+ // awareness in Document's splitter, not a narrower binding here.
28
+ const doc = documentFor({ kind });
29
+ const body = mergeBody(doc, r.body, l.body, localWins);
19
30
  return serializeFile(fm, body);
20
31
  }
21
32
  function mergeFrontmatter(remote, local, localWins) {
@@ -38,7 +49,7 @@ function mergeFrontmatter(remote, local, localWins) {
38
49
  merged[key] = r;
39
50
  }
40
51
  // Array fields: union
41
- for (const key of ARRAY_FIELDS_UNCAPPED) {
52
+ for (const key of ARRAY_FIELDS) {
42
53
  merged[key] = unionArrays(remote[key], local[key]);
43
54
  if (merged[key].length === 0)
44
55
  delete merged[key];
@@ -46,46 +57,34 @@ function mergeFrontmatter(remote, local, localWins) {
46
57
  return merged;
47
58
  }
48
59
  function unionArrays(a, b) {
49
- // Local (b) items first so they survive cap truncation
60
+ // Local (b) items first: nothing is truncated, but the local side's order is
61
+ // the one the user last saw, so it stays the order they get back.
50
62
  const arrA = Array.isArray(a) ? a : a ? [a] : [];
51
63
  const arrB = Array.isArray(b) ? b : b ? [b] : [];
52
64
  return [...new Set([...arrB, ...arrA])];
53
65
  }
54
- function splitSections(body) {
55
- const parts = body.split(/\n(?=## )/g);
56
- const sections = [];
57
- let preamble = '';
58
- for (const part of parts) {
59
- if (part.startsWith('## ')) {
60
- const nlIdx = part.indexOf('\n');
61
- const heading = nlIdx === -1 ? part : part.slice(0, nlIdx);
62
- const content = nlIdx === -1 ? '' : part.slice(nlIdx + 1);
63
- sections.push({ heading: heading.trim(), content: content.trim() });
64
- }
65
- else {
66
- preamble = part.trim();
67
- }
68
- }
69
- return { preamble, sections };
70
- }
71
- function mergeBody(remoteBody, localBody, localWins) {
66
+ // --- Body merge ---
67
+ function mergeBody(doc, remoteBody, localBody, localWins) {
72
68
  if (remoteBody === localBody)
73
69
  return localBody;
74
- const remote = splitSections(remoteBody);
75
- const local = splitSections(localBody);
70
+ // Structural split (see document.ts): sections are atomic — a user ##
71
+ // heading inside a Brief or a session-log entry body stays with its
72
+ // section instead of being split out and merged under its own policy.
73
+ const remote = doc.splitStructural(remoteBody);
74
+ const local = doc.splitStructural(localBody);
76
75
  // Build merged sections starting from local (local section order is canonical)
77
76
  const localHeadings = new Set(local.sections.map(s => s.heading));
78
77
  const mergedSections = [];
79
78
  for (const ls of local.sections) {
80
79
  const rs = remote.sections.find(s => s.heading === ls.heading);
81
- if (ls.heading === '## Session Log' && rs) {
80
+ if (ls.heading === 'Session Log' && rs) {
82
81
  mergedSections.push({ heading: ls.heading, content: mergeSessionLogs(rs.content, ls.content) });
83
82
  }
84
- else if (ls.heading === '## Next Actions' && rs) {
83
+ else if (ls.heading === 'Next Actions' && rs) {
85
84
  mergedSections.push({ heading: ls.heading, content: mergeNextActions(rs.content, ls.content) });
86
85
  }
87
- else if ((ls.heading === '## Evidence' || ls.heading === '## Sources') && rs) {
88
- // Append-only sections: union lines from both sides, dedup identical
86
+ else if (APPEND_ONLY_SECTIONS.has(ls.heading) && rs) {
87
+ // Append-only sections (contracts.ts): union lines from both sides, dedup identical
89
88
  mergedSections.push({ heading: ls.heading, content: mergeAppendOnlyLines(rs.content, ls.content) });
90
89
  }
91
90
  else if (rs && !localWins) {
@@ -102,11 +101,17 @@ function mergeBody(remoteBody, localBody, localWins) {
102
101
  mergedSections.push(rs);
103
102
  }
104
103
  }
105
- // Reassemble
106
- const preamble = localWins
107
- ? (local.preamble || remote.preamble)
108
- : (remote.preamble || local.preamble);
109
- const parts = [preamble, ...mergedSections.map(s => `${s.heading}\n\n${s.content}`)].filter(Boolean);
104
+ // Reassemble. A preamble that is itself a session-log entry stream is
105
+ // append-only content living outside any heading — the archive-log files
106
+ // under entities/archive/ are exactly this shape. Merging those by the
107
+ // scalar wins policy drops one machine's archived entries wholesale, so
108
+ // union them by the same entry policy the Session Log section uses.
109
+ const preamble = isLogEntryStream(remote.preamble) && isLogEntryStream(local.preamble)
110
+ ? mergeSessionLogs(remote.preamble, local.preamble)
111
+ : localWins
112
+ ? (local.preamble || remote.preamble)
113
+ : (remote.preamble || local.preamble);
114
+ const parts = [preamble, ...mergedSections.map(s => `## ${s.heading}\n\n${s.content}`)].filter(Boolean);
110
115
  return parts.join('\n\n');
111
116
  }
112
117
  /** Union merge for append-only free-text sections: local lines first, then
@@ -123,6 +128,12 @@ function mergeAppendOnlyLines(remoteContent, localContent) {
123
128
  return localContent;
124
129
  return [...localLines, ...remoteOnly].join('\n');
125
130
  }
131
+ /** True when a block is nothing but session-log entries — it starts with an
132
+ * entry heading, so splitLogEntries drops no leading prose. */
133
+ function isLogEntryStream(text) {
134
+ const first = text.trim().split('\n')[0];
135
+ return first !== '' && parseSessionLogHeading(first) !== null;
136
+ }
126
137
  function mergeSessionLogs(remoteContent, localContent) {
127
138
  const remoteEntries = parseLogEntries(remoteContent);
128
139
  const localEntries = parseLogEntries(localContent);
@@ -140,64 +151,73 @@ function mergeSessionLogs(remoteContent, localContent) {
140
151
  return merged.map(e => e.raw).join('\n\n');
141
152
  }
142
153
  function parseLogEntries(content) {
143
- const entries = [];
144
- const blocks = content.split(/\n(?=### \d{4}-\d{2}-\d{2})/);
145
- for (const block of blocks) {
146
- const trimmed = block.trim();
147
- if (!trimmed)
148
- continue;
149
- const firstLine = trimmed.split('\n')[0];
150
- const parsed = parseSessionLogHeading(firstLine);
151
- if (parsed) {
152
- entries.push({
153
- key: `${parsed.date}|${parsed.agent}|${parsed.type}`,
154
- date: parsed.date,
155
- raw: trimmed,
156
- });
157
- }
158
- }
159
- return entries;
154
+ // Document owns entry block splitting; the identity key and dedup/sort
155
+ // policy stay here — merge semantics, not document structure.
156
+ //
157
+ // Identity is the entry's whole content. Date+agent+type is not an identity:
158
+ // two machines each running a digest on the same day produce two entries with
159
+ // the same heading and different bodies, and keying on the heading collapses
160
+ // them to one — the other machine's session history is gone. Entries the two
161
+ // sides share came from the same commit, so they are byte-identical and still
162
+ // dedup.
163
+ return splitLogEntries(content).map(raw => {
164
+ const parsed = parseSessionLogHeading(raw.split('\n')[0]);
165
+ return { key: raw, date: parsed.date, raw };
166
+ });
160
167
  }
161
168
  function mergeNextActions(remoteContent, localContent) {
162
- const remoteItems = parseActionItems(remoteContent);
163
- const localItems = parseActionItems(localContent);
164
- // Build merged set: start with local items
165
- const seen = new Set();
166
- const merged = [];
167
- // Add all local items
168
- for (const item of localItems) {
169
- seen.add(item.text);
170
- merged.push(item);
171
- }
172
- // Add remote items not in local
173
- for (const item of remoteItems) {
174
- if (!seen.has(item.text)) {
175
- seen.add(item.text);
176
- merged.push(item);
177
- }
178
- else {
179
- // If remote has it checked but local has it unchecked, upgrade to checked
180
- const existing = merged.find(m => m.text === item.text);
181
- if (existing && item.checked && !existing.checked) {
182
- existing.checked = true;
183
- }
169
+ const remote = parseActionItems(remoteContent);
170
+ const local = parseActionItems(localContent);
171
+ // Start with local items; index by action text for the remote pass
172
+ const merged = local.items.map(i => ({ ...i, notes: [...i.notes] }));
173
+ const byText = new Map(merged.map(i => [i.text, i]));
174
+ for (const item of remote.items) {
175
+ const existing = byText.get(item.text);
176
+ if (!existing) {
177
+ merged.push({ ...item, notes: [...item.notes] });
178
+ byText.set(item.text, merged[merged.length - 1]);
179
+ continue;
184
180
  }
181
+ // Checked on either side means done
182
+ if (item.checked)
183
+ existing.checked = true;
184
+ // Union the item's own notes/sub-bullets — they are authored content, not
185
+ // re-derivable from the checkbox line
186
+ existing.notes.push(...unionLines(item.notes, existing.notes));
185
187
  }
186
- return merged.map(i => `- [${i.checked ? 'x' : ' '}] ${i.text}`).join('\n');
188
+ const lines = [...local.preamble, ...unionLines(remote.preamble, local.preamble)];
189
+ for (const item of merged) {
190
+ lines.push(`- [${item.checked ? 'x' : ' '}] ${item.text}`);
191
+ lines.push(...item.notes);
192
+ }
193
+ return lines.join('\n').replace(/\n+$/, '');
194
+ }
195
+ /** Lines of `from` not already present in `into` (blank lines only from `into`). */
196
+ function unionLines(from, into) {
197
+ const seen = new Set(into.map(l => l.trim()).filter(Boolean));
198
+ return from.filter(l => l.trim() && !seen.has(l.trim()));
187
199
  }
200
+ /**
201
+ * Split a Next Actions section into its leading non-item lines and its items,
202
+ * each item carrying the lines that follow it (indented sub-bullets, notes)
203
+ * until the next checkbox. Non-checkbox lines are authored content — parsing
204
+ * checkbox lines alone and re-rendering from them deletes everything else.
205
+ * `- [X]` is the same as `- [x]`: a completed action, not an unknown line.
206
+ */
188
207
  function parseActionItems(content) {
208
+ const preamble = [];
189
209
  const items = [];
190
210
  for (const line of content.split('\n')) {
191
- const unchecked = line.match(/^- \[ \] (.+)$/);
192
- if (unchecked) {
193
- items.push({ checked: false, text: unchecked[1] });
194
- continue;
211
+ const match = line.match(/^- \[([ xX])\] (.+)$/);
212
+ if (match) {
213
+ items.push({ checked: match[1].toLowerCase() === 'x', text: match[2], notes: [] });
195
214
  }
196
- const checked = line.match(/^- \[x\] (.+)$/);
197
- if (checked) {
198
- items.push({ checked: true, text: checked[1] });
199
- continue;
215
+ else if (items.length === 0) {
216
+ preamble.push(line);
217
+ }
218
+ else {
219
+ items[items.length - 1].notes.push(line);
200
220
  }
201
221
  }
202
- return items;
222
+ return { preamble, items };
203
223
  }
package/dist/schema.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/schema.ts
2
- import { ENTITY_TYPES, ENTITY_STATUSES, CONFIDENCE_LEVELS, SESSION_LOG_TYPES, VALID_SUBTYPES, } from './contracts.js';
2
+ import { ENTITY_TYPES, ENTITY_STATUSES, CONFIDENCE_LEVELS, SESSION_LOG_TYPES, VALID_SUBTYPES, PLAN_STATUSES, } from './contracts.js';
3
3
  export function validateEntityFrontmatter(fm) {
4
4
  const errors = [];
5
5
  if (!fm.name || typeof fm.name !== 'string')
@@ -35,9 +35,9 @@ export function validateKnowledgeSubtype(fm) {
35
35
  if (fm.subtype && !VALID_SUBTYPES.includes(fm.subtype)) {
36
36
  errors.push(`invalid subtype: ${fm.subtype} (expected: ${VALID_SUBTYPES.join(', ')})`);
37
37
  }
38
- // Plan-specific: status must be active or done
39
- if (fm.subtype === 'plan' && fm.status && !['active', 'done'].includes(fm.status)) {
40
- errors.push(`invalid plan status: ${fm.status} (expected: active, done)`);
38
+ // Plan-specific: status must be one of the plan lifecycle statuses
39
+ if (fm.subtype === 'plan' && fm.status && !PLAN_STATUSES.includes(fm.status)) {
40
+ errors.push(`invalid plan status: ${fm.status} (expected: ${PLAN_STATUSES.join(', ')})`);
41
41
  }
42
42
  return errors;
43
43
  }
@@ -6,3 +6,9 @@ export declare function bodyTemplate(type: EntityType, fields?: {
6
6
  export declare function knowledgeBodyTemplate(subtype?: KnowledgeSubtype, fields?: {
7
7
  synthesis?: string;
8
8
  }): string;
9
+ /** Session bodies. Sessions have no TypeContract, but their headings are
10
+ * structural for Document splitting — so the list lives in contracts with
11
+ * every other section set, and this renders it. */
12
+ export declare function sessionBodyTemplate(fields?: {
13
+ synthesis?: string;
14
+ }): string;
package/dist/templates.js CHANGED
@@ -1,39 +1,39 @@
1
- import { SUBTYPE_SECTIONS } from './contracts.js';
2
- const ITEM_TEMPLATES = {
3
- capture: ['## Notes'],
4
- entity: ['## Context', '## Session Log'],
5
- project: ['## Purpose', '## Goals', '## Session Log'],
6
- };
7
- export function bodyTemplate(type, fields) {
8
- const sections = ITEM_TEMPLATES[type];
9
- if (!sections)
10
- throw new Error(`Unknown item type: ${type}`);
1
+ import { SUBTYPE_SECTIONS, DEFAULT_KNOWLEDGE_SUBTYPE, SESSION_SECTIONS, ENTITY_TYPES, getContract } from './contracts.js';
2
+ /** Render a body from a section list, injecting each field's text under the
3
+ * section that field writes into (contracts.CREATE_FIELD_SECTIONS names the
4
+ * pairs; a field whose section this template lacks is rejected upstream by
5
+ * `unreachableFields`, so an unplaced value never reaches here). */
6
+ function render(sections, content) {
11
7
  const lines = [];
12
8
  for (const section of sections) {
13
- lines.push(section);
14
- if (section === '## Purpose' && fields?.purpose) {
15
- lines.push('', fields.purpose);
16
- }
17
- if (section === '## Notes' && fields?.notes) {
18
- lines.push('', fields.notes);
19
- }
9
+ lines.push(`## ${section}`);
10
+ const text = content[section];
11
+ if (text)
12
+ lines.push('', text);
20
13
  lines.push('');
21
14
  }
22
15
  return lines.join('\n');
23
16
  }
17
+ export function bodyTemplate(type, fields) {
18
+ // The template IS the contract's default sections — the Document module
19
+ // derives its structural set from the same place, so the two can't drift.
20
+ if (!ENTITY_TYPES.includes(type))
21
+ throw new Error(`Unknown item type: ${type}`);
22
+ return render(getContract(type).defaultSections, { Purpose: fields?.purpose, Notes: fields?.notes });
23
+ }
24
24
  export function knowledgeBodyTemplate(subtype, fields) {
25
25
  if (subtype === 'session') {
26
26
  throw new Error("subtype 'session' is no longer supported for knowledge notes. " +
27
27
  "Use batch kind: 'session' instead. See knowledge-v2 migration.");
28
28
  }
29
- const sections = SUBTYPE_SECTIONS[subtype ?? 'insight'];
30
- const lines = [];
31
- for (const section of sections) {
32
- lines.push(`## ${section}`);
33
- if ((section === 'Synthesis' || section === 'Summary') && fields?.synthesis) {
34
- lines.push('', fields.synthesis);
35
- }
36
- lines.push('');
37
- }
38
- return lines.join('\n');
29
+ // 'Summary' was a second injection target here until sessions stopped being
30
+ // a knowledge subtype; no SUBTYPE_SECTIONS entry has carried it since — the
31
+ // session body is its own template below.
32
+ return render(SUBTYPE_SECTIONS[subtype ?? DEFAULT_KNOWLEDGE_SUBTYPE], { Synthesis: fields?.synthesis });
33
+ }
34
+ /** Session bodies. Sessions have no TypeContract, but their headings are
35
+ * structural for Document splitting — so the list lives in contracts with
36
+ * every other section set, and this renders it. */
37
+ export function sessionBodyTemplate(fields) {
38
+ return render([...SESSION_SECTIONS], { Summary: fields?.synthesis });
39
39
  }