hafez 1.0.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.
Files changed (58) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +190 -0
  3. package/dist/cli/batch-errors.d.ts +24 -0
  4. package/dist/cli/batch-errors.js +236 -0
  5. package/dist/cli/commands-schema.d.ts +3 -0
  6. package/dist/cli/commands-schema.js +80 -0
  7. package/dist/cli/commands.d.ts +133 -0
  8. package/dist/cli/commands.js +628 -0
  9. package/dist/cli/format.d.ts +9 -0
  10. package/dist/cli/format.js +158 -0
  11. package/dist/cli/help-agent.d.ts +6 -0
  12. package/dist/cli/help-agent.js +158 -0
  13. package/dist/cli/index.d.ts +1 -0
  14. package/dist/cli/index.js +304 -0
  15. package/dist/cli/resolve-vault.d.ts +13 -0
  16. package/dist/cli/resolve-vault.js +124 -0
  17. package/dist/cli/schema-introspect.d.ts +70 -0
  18. package/dist/cli/schema-introspect.js +372 -0
  19. package/dist/cli.d.ts +2 -0
  20. package/dist/cli.js +3 -0
  21. package/dist/contracts.d.ts +26 -0
  22. package/dist/contracts.js +87 -0
  23. package/dist/db.d.ts +68 -0
  24. package/dist/db.js +663 -0
  25. package/dist/digest.d.ts +29 -0
  26. package/dist/digest.js +94 -0
  27. package/dist/export-okf.d.ts +12 -0
  28. package/dist/export-okf.js +176 -0
  29. package/dist/git.d.ts +12 -0
  30. package/dist/git.js +355 -0
  31. package/dist/index.d.ts +7 -0
  32. package/dist/index.js +909 -0
  33. package/dist/knowledge-index.d.ts +3 -0
  34. package/dist/knowledge-index.js +135 -0
  35. package/dist/merge.d.ts +1 -0
  36. package/dist/merge.js +176 -0
  37. package/dist/migrate-knowledge-v2.d.ts +11 -0
  38. package/dist/migrate-knowledge-v2.js +158 -0
  39. package/dist/migrate-next-actions.d.ts +6 -0
  40. package/dist/migrate-next-actions.js +32 -0
  41. package/dist/migrate-types.d.ts +11 -0
  42. package/dist/migrate-types.js +142 -0
  43. package/dist/parser.d.ts +18 -0
  44. package/dist/parser.js +68 -0
  45. package/dist/query.d.ts +24 -0
  46. package/dist/query.js +167 -0
  47. package/dist/schema.d.ts +9 -0
  48. package/dist/schema.js +59 -0
  49. package/dist/sections.d.ts +54 -0
  50. package/dist/sections.js +297 -0
  51. package/dist/templates.d.ts +8 -0
  52. package/dist/templates.js +39 -0
  53. package/dist/types.d.ts +321 -0
  54. package/dist/types.js +11 -0
  55. package/dist/vault.d.ts +12 -0
  56. package/dist/vault.js +45 -0
  57. package/package.json +67 -0
  58. package/skill/SKILL.md +190 -0
@@ -0,0 +1,297 @@
1
+ // src/sections.ts
2
+ // Pure string→string functions for Brief and Next Actions section manipulation.
3
+ import { ALL_CONTRACTS, SUBTYPE_SECTIONS } from './contracts.js';
4
+ const UNCHECKED_RE = /^- \[ \] (.+)$/gm;
5
+ /**
6
+ * Known structural section headings in Hafez entities and knowledge notes.
7
+ * Derived from contracts.ts (defaultSections + optionalSections) plus
8
+ * auto-generated sections not tracked in contracts (Related, Summary).
9
+ * Only these are treated as section boundaries. Any other `## ` heading
10
+ * inside section content (e.g. in a brief or session log) is preserved as-is.
11
+ */
12
+ export const STRUCTURAL_SECTIONS = new Set([
13
+ ...ALL_CONTRACTS.flatMap(c => [...c.defaultSections, ...c.optionalSections]),
14
+ ...Object.values(SUBTYPE_SECTIONS).flat(),
15
+ 'Related', // auto-generated by syncRelatedSection
16
+ 'Summary', // used in session files
17
+ ]);
18
+ /**
19
+ * Find the next structural `## Heading` boundary after a given position.
20
+ * Skips `## ` headings that are not known structural sections (content headings).
21
+ * Returns the index of the `\n` before the `## `, or -1 if no structural heading found.
22
+ */
23
+ export function findNextStructuralHeading(body, from) {
24
+ const re = /\n## ([^\n]+)/g;
25
+ re.lastIndex = from;
26
+ let match;
27
+ while ((match = re.exec(body)) !== null) {
28
+ const headingName = match[1].trim();
29
+ if (STRUCTURAL_SECTIONS.has(headingName)) {
30
+ return match.index;
31
+ }
32
+ }
33
+ return -1;
34
+ }
35
+ // --- Internal helpers ---
36
+ /**
37
+ * Find a ## Heading section and its content.
38
+ * Returns { start, end, content } or null if not found.
39
+ * Matches heading exactly (e.g. "## Brief" won't match "## Briefing").
40
+ * Only treats known structural headings as section boundaries -- content
41
+ * inside a section may contain arbitrary `## ` headings without corruption.
42
+ */
43
+ export function findSection(body, heading) {
44
+ const re = new RegExp(`(^|\\n)(## ${escapeRegex(heading)})(?:\\n|$)`);
45
+ const match = re.exec(body);
46
+ if (!match)
47
+ return null;
48
+ const start = match.index + match[1].length;
49
+ const afterHeading = start + match[2].length + 1;
50
+ // Find the next structural ## heading or EOF
51
+ const nextHeading = findNextStructuralHeading(body, afterHeading);
52
+ const end = nextHeading === -1 ? body.length : nextHeading;
53
+ const rawContent = body.slice(afterHeading, end);
54
+ const content = rawContent.replace(/^\n+/, '').replace(/\n+$/, '');
55
+ return { start, end, content };
56
+ }
57
+ function escapeRegex(s) {
58
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
59
+ }
60
+ /**
61
+ * Remove a section (heading + content) from body, cleaning up extra whitespace.
62
+ */
63
+ function removeSection(body, heading) {
64
+ const section = findSection(body, heading);
65
+ if (!section)
66
+ return body;
67
+ const before = body.slice(0, section.start);
68
+ const after = body.slice(section.end);
69
+ // Clean up: avoid triple+ newlines at the splice point
70
+ const trimmedBefore = before.replace(/\n+$/, '');
71
+ const trimmedAfter = after.replace(/^\n+/, '');
72
+ if (!trimmedBefore)
73
+ return trimmedAfter;
74
+ if (!trimmedAfter)
75
+ return trimmedBefore;
76
+ return trimmedBefore + '\n\n' + trimmedAfter;
77
+ }
78
+ /**
79
+ * Insert a new section before a target heading, or at EOF.
80
+ * `before` is an array of headings to try inserting before (first found wins).
81
+ */
82
+ function insertSectionBefore(body, heading, content, before) {
83
+ const sectionBlock = `## ${heading}\n\n${content}`;
84
+ for (const target of before) {
85
+ const targetSection = findSection(body, target);
86
+ if (targetSection) {
87
+ const insertPoint = targetSection.start;
88
+ const textBefore = body.slice(0, insertPoint).replace(/\n+$/, '');
89
+ const textAfter = body.slice(insertPoint);
90
+ if (!textBefore)
91
+ return sectionBlock + '\n\n' + textAfter;
92
+ return textBefore + '\n\n' + sectionBlock + '\n\n' + textAfter;
93
+ }
94
+ }
95
+ // No target found — append at EOF
96
+ const trimmed = body.replace(/\n+$/, '');
97
+ return trimmed + '\n\n' + sectionBlock;
98
+ }
99
+ /**
100
+ * Insert a new section after a target heading (and its content), or fall back to inserting before fallbacks.
101
+ */
102
+ function insertSectionAfter(body, heading, content, after, beforeFallbacks) {
103
+ const afterSection = findSection(body, after);
104
+ if (afterSection) {
105
+ const insertPoint = afterSection.end;
106
+ const textBefore = body.slice(0, insertPoint).replace(/\n+$/, '');
107
+ const textAfter = body.slice(insertPoint).replace(/^\n+/, '');
108
+ const sectionBlock = `## ${heading}\n\n${content}`;
109
+ if (!textAfter)
110
+ return textBefore + '\n\n' + sectionBlock;
111
+ return textBefore + '\n\n' + sectionBlock + '\n\n' + textAfter;
112
+ }
113
+ // After-target not found — fall back to insertBefore logic
114
+ return insertSectionBefore(body, heading, content, beforeFallbacks);
115
+ }
116
+ /**
117
+ * Normalize text for matching: trim whitespace, replace smart quotes with
118
+ * straight equivalents, normalize em-dashes to regular dashes.
119
+ * Applied to both query and action text before comparison only — stored text is unchanged.
120
+ */
121
+ function normalizeForMatch(s) {
122
+ return s
123
+ .trim()
124
+ .replace(/[\u2018\u2019]/g, "'")
125
+ .replace(/[\u201C\u201D]/g, '"')
126
+ .replace(/\u2014/g, '-');
127
+ }
128
+ /**
129
+ * Match an action by case-insensitive substring against unchecked items.
130
+ * Throws on 0 or >1 matches.
131
+ */
132
+ function matchAction(body, query) {
133
+ const section = findSection(body, 'Next Actions');
134
+ if (!section)
135
+ throw new Error(`No matching action for "${query}"`);
136
+ const normalizedQuery = normalizeForMatch(query).toLowerCase();
137
+ const matches = [];
138
+ const allActions = [];
139
+ let m;
140
+ const re = new RegExp(UNCHECKED_RE.source, 'gm');
141
+ while ((m = re.exec(section.content)) !== null) {
142
+ allActions.push(m[1]);
143
+ if (normalizeForMatch(m[1]).toLowerCase().includes(normalizedQuery)) {
144
+ matches.push(m[1]);
145
+ }
146
+ }
147
+ if (matches.length === 0) {
148
+ throw new Error(`No matching action for "${query}". Actions: ${JSON.stringify(allActions)}`);
149
+ }
150
+ if (matches.length > 1)
151
+ throw new Error(`Ambiguous match for "${query}": ${matches.join(', ')}`);
152
+ return matches[0];
153
+ }
154
+ // --- Brief functions ---
155
+ export function getBrief(body) {
156
+ const section = findSection(body, 'Brief');
157
+ if (!section)
158
+ return null;
159
+ return section.content || null;
160
+ }
161
+ export function setBrief(body, content) {
162
+ const existing = findSection(body, 'Brief');
163
+ if (existing) {
164
+ // Replace existing brief content
165
+ const updated = removeSection(body, 'Brief');
166
+ return setBrief(updated, content);
167
+ }
168
+ // Insert before: Next Actions > Current State > Session Log > EOF
169
+ return insertSectionBefore(body, 'Brief', content, ['Next Actions', 'Current State', 'Session Log']);
170
+ }
171
+ export function removeBrief(body) {
172
+ return removeSection(body, 'Brief');
173
+ }
174
+ // --- Next Actions functions ---
175
+ export function getNextActions(body) {
176
+ const section = findSection(body, 'Next Actions');
177
+ if (!section)
178
+ return [];
179
+ const actions = [];
180
+ let m;
181
+ const re = new RegExp(UNCHECKED_RE.source, 'gm');
182
+ while ((m = re.exec(section.content)) !== null) {
183
+ actions.push(m[1]);
184
+ }
185
+ return actions;
186
+ }
187
+ export function addNextAction(body, action) {
188
+ const section = findSection(body, 'Next Actions');
189
+ if (section) {
190
+ // Add the new item at the end of unchecked items (before any checked items)
191
+ const lines = section.content.split('\n');
192
+ const lastUncheckedIdx = lines.reduce((last, line, i) => line.startsWith('- [ ] ') ? i : last, -1);
193
+ const insertIdx = lastUncheckedIdx === -1 ? 0 : lastUncheckedIdx + 1;
194
+ lines.splice(insertIdx, 0, `- [ ] ${action}`);
195
+ const newContent = lines.join('\n');
196
+ const before = body.slice(0, section.start).replace(/\n+$/, '');
197
+ const after = body.slice(section.end).replace(/^\n+/, '');
198
+ const sectionBlock = `## Next Actions\n\n${newContent}`;
199
+ const parts = [before, sectionBlock, after].filter(Boolean);
200
+ return parts.join('\n\n');
201
+ }
202
+ // No section — insert after Brief if present, otherwise before Session Log
203
+ return insertSectionAfter(body, 'Next Actions', `- [ ] ${action}`, 'Brief', ['Session Log']);
204
+ }
205
+ export function completeNextAction(body, query) {
206
+ const matched = matchAction(body, query);
207
+ // Replace the unchecked item with checked
208
+ const updatedBody = body.replace(`- [ ] ${matched}`, `- [x] ${matched}`);
209
+ // Check if any unchecked items remain
210
+ const remaining = getNextActions(updatedBody);
211
+ if (remaining.length === 0) {
212
+ return { matched, body: clearNextActions(updatedBody) };
213
+ }
214
+ return { matched, body: updatedBody };
215
+ }
216
+ export function removeNextAction(body, query) {
217
+ const matched = matchAction(body, query);
218
+ // Remove the line
219
+ const line = `- [ ] ${matched}`;
220
+ const updatedBody = body.split('\n').filter(l => l !== line).join('\n');
221
+ // Check if any unchecked items remain
222
+ const remaining = getNextActions(updatedBody);
223
+ if (remaining.length === 0) {
224
+ return { matched, body: clearNextActions(updatedBody) };
225
+ }
226
+ return { matched, body: updatedBody };
227
+ }
228
+ export function clearNextActions(body) {
229
+ return removeSection(body, 'Next Actions');
230
+ }
231
+ // --- Summary derivation ---
232
+ export function firstNonEmptyLine(s) {
233
+ return s?.split('\n').find(l => l.trim())?.trim() ?? '';
234
+ }
235
+ /**
236
+ * One-line summary for a doc: frontmatter description first, then the first
237
+ * non-empty line of the kind's primary section (entity: Brief; knowledge:
238
+ * Synthesis, falling back to Goal for plans; session: Summary).
239
+ * Shared by the vault index and the OKF export so the two surfaces agree.
240
+ */
241
+ export function deriveSummary(kind, fm, body) {
242
+ if (fm.description)
243
+ return fm.description;
244
+ if (kind === 'entity')
245
+ return firstNonEmptyLine(getBrief(body));
246
+ if (kind === 'knowledge') {
247
+ const synthesis = findSection(body, 'Synthesis');
248
+ if (synthesis?.content)
249
+ return firstNonEmptyLine(synthesis.content);
250
+ return firstNonEmptyLine(findSection(body, 'Goal')?.content);
251
+ }
252
+ return firstNonEmptyLine(findSection(body, 'Summary')?.content);
253
+ }
254
+ // --- Related section functions ---
255
+ /** Matches [[slug]] or [[slug|display text]], capturing slug in group 1. Non-global — wrap with `new RegExp(WIKI_LINK_RE.source, 'g')` for iteration. */
256
+ export const WIKI_LINK_RE = /\[\[([^\]|]+)(?:\|[^\]]+)?\]\]/;
257
+ export function syncRelatedSection(body, frontmatter) {
258
+ const targets = [];
259
+ if (frontmatter.parent)
260
+ targets.push({ slug: frontmatter.parent, label: 'parent' });
261
+ for (const slug of frontmatter.related ?? [])
262
+ targets.push({ slug });
263
+ if (targets.length === 0) {
264
+ // No frontmatter links — remove Related section if present
265
+ const existing = findSection(body, 'Related');
266
+ if (!existing)
267
+ return body;
268
+ const before = body.slice(0, existing.start).replace(/\n+$/, '');
269
+ const after = body.slice(existing.end).replace(/^\n+/, '');
270
+ return [before, after].filter(Boolean).join('\n\n');
271
+ }
272
+ // Strip existing Related section before checking coverage
273
+ let authoredBody = body;
274
+ const existingRelated = findSection(body, 'Related');
275
+ if (existingRelated) {
276
+ const before = body.slice(0, existingRelated.start);
277
+ const after = body.slice(existingRelated.end);
278
+ authoredBody = (before + after).replace(/\n{3,}/g, '\n\n');
279
+ }
280
+ // Find which targets are NOT mentioned in authored body
281
+ const mentionedSlugs = new Set();
282
+ let match;
283
+ const re = new RegExp(WIKI_LINK_RE.source, 'g');
284
+ while ((match = re.exec(authoredBody)) !== null) {
285
+ mentionedSlugs.add(match[1]);
286
+ }
287
+ const uncovered = targets.filter(t => !mentionedSlugs.has(t.slug));
288
+ if (uncovered.length === 0) {
289
+ // All covered inline — return body without Related section
290
+ return authoredBody.replace(/\n+$/, '');
291
+ }
292
+ // Build Related section
293
+ const lines = uncovered.map(t => t.label ? `- [[${t.slug}]] (${t.label})` : `- [[${t.slug}]]`);
294
+ const section = `## Related\n\n${lines.join('\n')}`;
295
+ // Append at end
296
+ return authoredBody.replace(/\n+$/, '') + '\n\n' + section;
297
+ }
@@ -0,0 +1,8 @@
1
+ import type { EntityType, KnowledgeSubtype } from './types.js';
2
+ export declare function bodyTemplate(type: EntityType, fields?: {
3
+ purpose?: string;
4
+ notes?: string;
5
+ }): string;
6
+ export declare function knowledgeBodyTemplate(subtype?: KnowledgeSubtype, fields?: {
7
+ synthesis?: string;
8
+ }): string;
@@ -0,0 +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}`);
11
+ const lines = [];
12
+ 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
+ }
20
+ lines.push('');
21
+ }
22
+ return lines.join('\n');
23
+ }
24
+ export function knowledgeBodyTemplate(subtype, fields) {
25
+ if (subtype === 'session') {
26
+ throw new Error("subtype 'session' is no longer supported for knowledge notes. " +
27
+ "Use batch kind: 'session' instead. See knowledge-v2 migration.");
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');
39
+ }
@@ -0,0 +1,321 @@
1
+ export type EntityType = 'capture' | 'entity' | 'project';
2
+ export type EntityStatus = 'active' | 'paused' | 'done';
3
+ export type ConfidenceLevel = 'observation' | 'pattern' | 'principle';
4
+ export type SessionLogType = 'progress' | 'decision' | 'blocker' | 'research';
5
+ export type ReadDepth = 'frontmatter' | 'summary' | 'full';
6
+ export type QueryFilter = 'active' | 'paused' | 'done' | 'all' | 'stale' | 'capture';
7
+ export type LinkRelation = 'parent' | 'related';
8
+ export type KnowledgeSubtype = 'insight' | 'plan';
9
+ export interface EntityQueryOpts {
10
+ filter?: QueryFilter;
11
+ type?: EntityType;
12
+ parent?: string;
13
+ domain?: string;
14
+ confidence?: ConfidenceLevel;
15
+ since?: string;
16
+ before?: string;
17
+ createdSince?: string;
18
+ createdBefore?: string;
19
+ tags?: string[];
20
+ sort_by?: 'last_touched' | 'created' | 'name' | 'staleness' | 'last_reinforced' | 'reinforcement_count';
21
+ sort_order?: 'asc' | 'desc';
22
+ limit?: number;
23
+ offset?: number;
24
+ }
25
+ export interface KnowledgeQueryOpts {
26
+ domain?: string;
27
+ confidence?: ConfidenceLevel;
28
+ subtype?: KnowledgeSubtype;
29
+ tags?: string[];
30
+ sort_by?: 'last_touched' | 'created' | 'name' | 'staleness' | 'last_reinforced' | 'reinforcement_count';
31
+ sort_order?: 'asc' | 'desc';
32
+ limit?: number;
33
+ offset?: number;
34
+ }
35
+ export interface EntityFrontmatter {
36
+ name: string;
37
+ type: EntityType;
38
+ status: EntityStatus;
39
+ description?: string;
40
+ resource?: string;
41
+ domain?: string[];
42
+ parent?: string;
43
+ related?: string[];
44
+ created: string;
45
+ 'last-touched': string;
46
+ 'staleness-days'?: number;
47
+ tags?: string[];
48
+ }
49
+ export interface KnowledgeFrontmatter {
50
+ name: string;
51
+ subtype?: KnowledgeSubtype;
52
+ description?: string;
53
+ domain?: string[];
54
+ confidence?: ConfidenceLevel;
55
+ related?: string[];
56
+ created: string;
57
+ 'last-reinforced'?: string;
58
+ 'reinforcement-count'?: number;
59
+ tags?: string[];
60
+ 'session-date'?: string;
61
+ status?: 'active' | 'done';
62
+ 'last-touched'?: string;
63
+ }
64
+ export interface ParsedFile<T = EntityFrontmatter | KnowledgeFrontmatter> {
65
+ frontmatter: T;
66
+ body: string;
67
+ }
68
+ export interface SessionLogEntry {
69
+ type: SessionLogType;
70
+ summary: string;
71
+ body?: string;
72
+ agent: string;
73
+ }
74
+ export interface ParsedSessionLogEntry {
75
+ date: string;
76
+ agent: string;
77
+ type: SessionLogType;
78
+ summary: string;
79
+ body: string;
80
+ }
81
+ export interface UpdateFields {
82
+ status?: EntityStatus;
83
+ next_action?: string | null;
84
+ current_state?: string;
85
+ session_log?: SessionLogEntry;
86
+ brief?: string | null;
87
+ add_action?: string;
88
+ add_actions?: string[];
89
+ complete_action?: string;
90
+ remove_action?: string;
91
+ clear_actions?: boolean;
92
+ description?: string | null;
93
+ resource?: string | null;
94
+ domain?: string[];
95
+ confidence?: ConfidenceLevel;
96
+ tags?: string[];
97
+ related?: string[];
98
+ synthesis?: string;
99
+ add_evidence?: string;
100
+ add_source?: string;
101
+ }
102
+ export interface UpdateResult {
103
+ previous_next_action?: string | null;
104
+ matched_action?: string;
105
+ }
106
+ export interface CreateEntityFields {
107
+ type: EntityType;
108
+ purpose?: string;
109
+ description?: string;
110
+ resource?: string;
111
+ domain?: string[];
112
+ parent?: string;
113
+ related?: string[];
114
+ tags?: string[];
115
+ brief?: string;
116
+ add_action?: string;
117
+ }
118
+ export interface CreateKnowledgeFields {
119
+ subtype?: KnowledgeSubtype;
120
+ synthesis?: string;
121
+ description?: string;
122
+ domain?: string[];
123
+ related?: string[];
124
+ tags?: string[];
125
+ 'session-date'?: string;
126
+ }
127
+ export interface QueryResult {
128
+ slug: string;
129
+ name: string;
130
+ type: EntityType;
131
+ status: EntityStatus;
132
+ description: string | null;
133
+ resource: string | null;
134
+ domain: string[];
135
+ last_touched: string;
136
+ next_action: string | null;
137
+ next_action_count: number;
138
+ parent: string | null;
139
+ related: string[];
140
+ staleness_days: number | null;
141
+ tags: string[];
142
+ brief: string | null;
143
+ session_log_count: number;
144
+ last_session_date: string | null;
145
+ last_session_type: string | null;
146
+ last_session_summary: string | null;
147
+ }
148
+ export interface KnowledgeQueryResult {
149
+ slug: string;
150
+ name: string;
151
+ description: string | null;
152
+ domain: string[];
153
+ confidence: ConfidenceLevel;
154
+ related: string[];
155
+ reinforcement_count: number;
156
+ last_reinforced: string | null;
157
+ last_touched: string | null;
158
+ }
159
+ export type UnifiedResult = (QueryResult & {
160
+ kind: 'entity';
161
+ }) | (KnowledgeQueryResult & {
162
+ kind: 'knowledge';
163
+ });
164
+ export interface ValidationIssue {
165
+ slug: string;
166
+ field: string;
167
+ issue: string;
168
+ }
169
+ export interface ValidationReport {
170
+ broken_slugs: ValidationIssue[];
171
+ orphaned_knowledge: string[];
172
+ oversized_related: ValidationIssue[];
173
+ missing_fields: ValidationIssue[];
174
+ total_entities: number;
175
+ total_knowledge: number;
176
+ }
177
+ export interface SearchResult {
178
+ slug: string;
179
+ kind: 'entity' | 'knowledge';
180
+ name: string;
181
+ snippet: string;
182
+ type?: EntityType;
183
+ status?: EntityStatus;
184
+ confidence?: ConfidenceLevel;
185
+ }
186
+ export interface VaultStats {
187
+ counts: Record<EntityStatus, number>;
188
+ by_type: Record<EntityType, number>;
189
+ knowledge_count: number;
190
+ stale: Array<{
191
+ slug: string;
192
+ name: string;
193
+ type: EntityType;
194
+ days_since_touched: number;
195
+ }>;
196
+ no_next_action: Array<{
197
+ slug: string;
198
+ name: string;
199
+ type: EntityType;
200
+ }>;
201
+ recently_touched: Array<{
202
+ slug: string;
203
+ name: string;
204
+ last_touched: string;
205
+ }>;
206
+ recently_created: Array<{
207
+ slug: string;
208
+ name: string;
209
+ created: string;
210
+ }>;
211
+ }
212
+ export interface ChangelogEntry {
213
+ slug: string;
214
+ kind: 'entity' | 'knowledge';
215
+ operation: 'created' | 'updated' | 'deleted';
216
+ timestamp: string;
217
+ commit_message: string;
218
+ }
219
+ export interface BatchResult {
220
+ op: string;
221
+ slug: string;
222
+ status: 'ok' | 'error';
223
+ error?: string;
224
+ created?: boolean;
225
+ }
226
+ export type BatchOperation = {
227
+ op: 'update';
228
+ slug: string;
229
+ fields: UpdateFields;
230
+ } | {
231
+ op: 'create';
232
+ kind: 'entity';
233
+ name: string;
234
+ fields: CreateEntityFields;
235
+ } | {
236
+ op: 'create';
237
+ kind: 'knowledge';
238
+ name: string;
239
+ fields?: CreateKnowledgeFields;
240
+ } | {
241
+ op: 'create';
242
+ kind: 'session';
243
+ name: string;
244
+ fields?: CreateKnowledgeFields;
245
+ } | {
246
+ op: 'capture';
247
+ name: string;
248
+ notes?: string;
249
+ } | {
250
+ op: 'link';
251
+ slug: string;
252
+ target: string;
253
+ relation: LinkRelation;
254
+ } | {
255
+ op: 'unlink';
256
+ slug: string;
257
+ target: string;
258
+ relation: LinkRelation;
259
+ } | {
260
+ op: 'promote';
261
+ slug: string;
262
+ target: 'entity' | 'project' | 'knowledge';
263
+ };
264
+ export type HafezErrorCode = 'NOT_FOUND' | 'SLUG_EXISTS' | 'VALIDATION_FAILED' | 'GIT_PUSH_FAILED';
265
+ export declare class HafezError extends Error {
266
+ code: HafezErrorCode;
267
+ details?: string[] | undefined;
268
+ constructor(code: HafezErrorCode, message: string, details?: string[] | undefined);
269
+ }
270
+ export interface GitConfig {
271
+ push?: boolean;
272
+ }
273
+ export interface HafezConfig {
274
+ vaultPath: string;
275
+ readOnly?: boolean;
276
+ git?: GitConfig;
277
+ onWrite?: (slug: string, operation: string) => void;
278
+ }
279
+ export interface Hafez {
280
+ read(slug: string, depth?: ReadDepth): Promise<ParsedFile>;
281
+ update(slug: string, fields: UpdateFields): Promise<UpdateResult>;
282
+ query(opts?: EntityQueryOpts): Promise<{
283
+ items: QueryResult[];
284
+ total: number;
285
+ }>;
286
+ queryUnified(opts?: EntityQueryOpts & {
287
+ kind?: 'entity' | 'knowledge' | 'all';
288
+ }): Promise<{
289
+ items: UnifiedResult[];
290
+ total: number;
291
+ }>;
292
+ create(kind: 'entity', name: string, fields: CreateEntityFields): Promise<string>;
293
+ create(kind: 'knowledge', name: string, fields?: CreateKnowledgeFields): Promise<string>;
294
+ capture(name: string, notes?: string): Promise<string>;
295
+ link(slug: string, target: string, relation: LinkRelation): Promise<void>;
296
+ unlink(slug: string, target: string, relation: LinkRelation): Promise<void>;
297
+ promote(slug: string, target: 'entity' | 'project' | 'knowledge'): Promise<string>;
298
+ batch(operations: BatchOperation[]): Promise<BatchResult[]>;
299
+ sync(): Promise<{
300
+ pulled: boolean;
301
+ pushed: boolean;
302
+ remote: boolean;
303
+ }>;
304
+ children(slug: string): Promise<{
305
+ items: QueryResult[];
306
+ total: number;
307
+ }>;
308
+ related_to(slug: string, relation?: string): Promise<{
309
+ items: (QueryResult | KnowledgeQueryResult)[];
310
+ total: number;
311
+ }>;
312
+ query_knowledge(opts?: KnowledgeQueryOpts): Promise<{
313
+ items: KnowledgeQueryResult[];
314
+ total: number;
315
+ }>;
316
+ validate(): Promise<ValidationReport>;
317
+ search(query: string, kind?: 'entity' | 'knowledge' | 'all'): Promise<SearchResult[]>;
318
+ rebuildIndex(): Promise<void>;
319
+ stats(): Promise<VaultStats>;
320
+ changelog(since: string): Promise<ChangelogEntry[]>;
321
+ }
package/dist/types.js ADDED
@@ -0,0 +1,11 @@
1
+ // src/types.ts
2
+ export class HafezError extends Error {
3
+ code;
4
+ details;
5
+ constructor(code, message, details) {
6
+ super(message);
7
+ this.code = code;
8
+ this.details = details;
9
+ this.name = 'HafezError';
10
+ }
11
+ }
@@ -0,0 +1,12 @@
1
+ export declare function slugify(name: string): string;
2
+ export declare function resolveFilePath(vaultPath: string, slug: string, kind: 'entity' | 'knowledge'): string;
3
+ export declare function slugExists(vaultPath: string, slug: string): boolean;
4
+ export declare function parseFilePath(path: string): {
5
+ frontmatter: Record<string, any>;
6
+ body: string;
7
+ };
8
+ export declare function parseContent(content: string): {
9
+ frontmatter: Record<string, any>;
10
+ body: string;
11
+ };
12
+ export declare function serializeFile(frontmatter: Record<string, any>, body: string): string;