@kentwynn/kgraph 0.2.35 → 0.2.36

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.
@@ -8,7 +8,7 @@ export interface HistoryEntry {
8
8
  author?: string;
9
9
  }
10
10
  export declare function registerHistoryCommand(program: Command): void;
11
- export declare function readHistoryEntries(processedPath: string, rootPath: string): Promise<HistoryEntry[]>;
11
+ export declare function readHistoryEntries(processedPath: string, rootPath: string, cognitionPath?: string): Promise<HistoryEntry[]>;
12
12
  /**
13
13
  * Parses the UTC timestamp embedded in a processed interaction filename.
14
14
  * Filename format: 2026-05-09T09-36-06-247Z-slug.md
@@ -3,8 +3,8 @@ import { execFile } from 'node:child_process';
3
3
  import { readFile, readdir } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
  import { promisify } from 'node:util';
6
- import { assertWorkspace, pathExists } from '../../storage/kgraph-paths.js';
7
6
  import { rankByFields } from '../../context/ranking.js';
7
+ import { assertWorkspace, pathExists } from '../../storage/kgraph-paths.js';
8
8
  import { KGraphError, runCommand } from '../errors.js';
9
9
  const execFileAsync = promisify(execFile);
10
10
  export function registerHistoryCommand(program) {
@@ -15,7 +15,7 @@ export function registerHistoryCommand(program) {
15
15
  .option('--json', 'Print JSON output')
16
16
  .action((queryParts = [], options) => runCommand(async () => {
17
17
  const workspace = await assertWorkspace(process.cwd());
18
- const entries = await readHistoryEntries(workspace.processedInteractionsPath, workspace.rootPath);
18
+ const entries = await readHistoryEntries(workspace.processedInteractionsPath, workspace.rootPath, workspace.cognitionPath);
19
19
  const query = queryParts.join(' ').trim();
20
20
  const limit = options.last !== undefined ? parseInt(options.last, 10) : 0;
21
21
  if (options.last !== undefined && (isNaN(limit) || limit < 1)) {
@@ -44,29 +44,73 @@ export function registerHistoryCommand(program) {
44
44
  }
45
45
  }));
46
46
  }
47
- export async function readHistoryEntries(processedPath, rootPath) {
48
- if (!(await pathExists(processedPath))) {
49
- return [];
50
- }
51
- const dirents = await readdir(processedPath, { withFileTypes: true });
52
- const filenames = dirents
53
- .filter((e) => e.isFile() && e.name.endsWith('.md'))
54
- .map((e) => e.name)
55
- .sort(); // ISO-prefixed filenames sort chronologically
47
+ export async function readHistoryEntries(processedPath, rootPath, cognitionPath) {
56
48
  const entries = [];
57
- for (const filename of filenames) {
58
- const timestamp = parseTimestampFromFilename(filename);
59
- if (!timestamp)
60
- continue;
61
- const filePath = path.join(processedPath, filename);
62
- const content = await readFile(filePath, 'utf8');
63
- const title = content.match(/^#\s+(.+)$/m)?.[1]?.trim() ?? filename;
64
- const summary = content.match(/^## Summary\s+([\s\S]*?)(?:\n## |\n# |$)/m)?.[1]?.trim();
65
- const relPath = path.relative(rootPath, filePath);
66
- const author = await getGitAuthor(rootPath, relPath);
67
- entries.push({ timestamp, filename, title, summary, text: content, author });
49
+ // Read inbox-processed interactions (raw notes archived from inbox by `kgraph update`)
50
+ if (await pathExists(processedPath)) {
51
+ const dirents = await readdir(processedPath, { withFileTypes: true });
52
+ const filenames = dirents
53
+ .filter((e) => e.isFile() && e.name.endsWith('.md'))
54
+ .map((e) => e.name)
55
+ .sort();
56
+ for (const filename of filenames) {
57
+ const timestamp = parseTimestampFromFilename(filename);
58
+ if (!timestamp)
59
+ continue;
60
+ const filePath = path.join(processedPath, filename);
61
+ const content = await readFile(filePath, 'utf8');
62
+ const title = content.match(/^#\s+(.+)$/m)?.[1]?.trim() ?? filename;
63
+ const summary = content
64
+ .match(/^## Summary\s+([\s\S]*?)(?:\n## |\n# |$)/m)?.[1]
65
+ ?.trim();
66
+ const relPath = path.relative(rootPath, filePath);
67
+ const author = await getGitAuthor(rootPath, relPath);
68
+ entries.push({
69
+ timestamp,
70
+ filename,
71
+ title,
72
+ summary,
73
+ text: content,
74
+ author,
75
+ });
76
+ }
77
+ }
78
+ // Also include conclude/session-conclude notes from the cognition store.
79
+ // These bypass the inbox → update pipeline so they never land in interactions/processed/,
80
+ // but they are still durable knowledge events that belong in the history timeline.
81
+ if (cognitionPath && (await pathExists(cognitionPath))) {
82
+ const dirents = await readdir(cognitionPath, { withFileTypes: true });
83
+ const filenames = dirents
84
+ .filter((e) => e.isFile() && e.name.endsWith('.md'))
85
+ .map((e) => e.name)
86
+ .sort();
87
+ for (const filename of filenames) {
88
+ // inbox-source notes are already represented via interactions/processed/
89
+ const filePath = path.join(cognitionPath, filename);
90
+ const content = await readFile(filePath, 'utf8');
91
+ const source = content.match(/^Source:\s*(.+)$/m)?.[1]?.trim();
92
+ if (source === 'inbox')
93
+ continue;
94
+ const timestamp = parseTimestampFromFilename(filename);
95
+ if (!timestamp)
96
+ continue;
97
+ const title = content.match(/^#\s+(.+)$/m)?.[1]?.trim() ?? filename;
98
+ const summary = content
99
+ .match(/^## Summary\s+([\s\S]*?)(?:\n## |\n# |$)/m)?.[1]
100
+ ?.trim();
101
+ const relPath = path.relative(rootPath, filePath);
102
+ const author = await getGitAuthor(rootPath, relPath);
103
+ entries.push({
104
+ timestamp,
105
+ filename,
106
+ title,
107
+ summary,
108
+ text: content,
109
+ author,
110
+ });
111
+ }
68
112
  }
69
- return entries;
113
+ return entries.sort((a, b) => a.timestamp.getTime() - b.timestamp.getTime());
70
114
  }
71
115
  /**
72
116
  * Parses the UTC timestamp embedded in a processed interaction filename.
@@ -85,7 +129,7 @@ export function renderHistory(entries, useColor = supportsColor(), query = '') {
85
129
  const chalk = new Chalk({ level: useColor ? 3 : 0 });
86
130
  if (entries.length === 0) {
87
131
  return ('\n' +
88
- chalk.dim(' No processed cognition notes found. Write Markdown notes to .kgraph/inbox/ and run `kgraph update`.') +
132
+ chalk.dim(' No cognition history found. Capture knowledge with `kgraph conclude` or write notes to .kgraph/inbox/ and run `kgraph update`.') +
89
133
  '\n');
90
134
  }
91
135
  const header = ` ${chalk.bold('KGraph History')} ${chalk.dim(`· ${entries.length} ${entries.length === 1 ? 'entry' : 'entries'}${query ? ` matching "${query}"` : ''}`)}`;
@@ -104,6 +104,13 @@ export function renderPackText(pack) {
104
104
  lines.push(` ◌ ${pack.omitted.length - omitted.length} more omitted items`);
105
105
  }
106
106
  }
107
+ if (pack.warnings.length > 0) {
108
+ lines.push('● Warnings');
109
+ for (const warning of pack.warnings) {
110
+ lines.push(` ⚠ ${warning}`);
111
+ }
112
+ lines.push('');
113
+ }
107
114
  lines.push('', '● Next', ' agents should consume this command with --json for the full ContextPack contract');
108
115
  return lines.join('\n');
109
116
  }
@@ -116,6 +123,12 @@ function appendGroup(lines, title, items) {
116
123
  for (const item of items.slice(0, 6)) {
117
124
  lines.push(` ● ${item.title} (~${item.tokenEstimate} tokens)`);
118
125
  lines.push(` because ${formatReasons(item.reasons)}`);
126
+ if (item.kind === 'file') {
127
+ const data = item.data;
128
+ if (data.content !== undefined) {
129
+ lines.push(` content inline (~${item.tokenEstimate} tokens)`);
130
+ }
131
+ }
119
132
  if (item.kind === 'file-range') {
120
133
  const data = item.data;
121
134
  if (data.path && data.startLine != null && data.endLine != null) {
@@ -33,6 +33,7 @@ export const DEFAULT_CONFIG = {
33
33
  '.windsurf',
34
34
  '.clinerules',
35
35
  '.github/copilot-instructions.md',
36
+ '.github/agents',
36
37
  '.github/prompts',
37
38
  'AGENTS.md',
38
39
  'CLAUDE.md',
@@ -63,6 +63,23 @@ export function buildContextPack(response, budget, rootPath) {
63
63
  omitted.push(candidate);
64
64
  }
65
65
  }
66
+ // Enrich selected file items with inline content so agents have the source without
67
+ // a second read. This mirrors how symbol and file-range items already embed excerpts.
68
+ // Only files that passed the budget check are read — omitted files are left as metadata.
69
+ if (rootPath) {
70
+ for (const item of items) {
71
+ if (item.kind !== 'file')
72
+ continue;
73
+ const data = item.data;
74
+ try {
75
+ const content = readFileSync(path.join(rootPath, data.path), 'utf8');
76
+ item.data = { ...data, content };
77
+ }
78
+ catch {
79
+ // best-effort — leave as metadata-only if file cannot be read
80
+ }
81
+ }
82
+ }
66
83
  return {
67
84
  task: response.query,
68
85
  budget,
@@ -1,9 +1,8 @@
1
- import { getRecentlyCommittedFiles, getWorkingTreeChangesDetailed, isGitRepo, } from '../scanner/git-utils.js';
2
- import { readDomainRecords } from '../storage/cognition-store.js';
3
- import { readSessionState } from '../session/session-store.js';
4
1
  import { atomToCognitionNote, refreshKnowledgeAtomStatuses, } from '../knowledge/atom-store.js';
5
- import { rankByFields } from './ranking.js';
6
- import { tokenize } from './ranking.js';
2
+ import { getCurrentCommit, getRecentlyCommittedFiles, getWorkingTreeChangesDetailed, isGitRepo, } from '../scanner/git-utils.js';
3
+ import { readSessionState } from '../session/session-store.js';
4
+ import { readDomainRecords } from '../storage/cognition-store.js';
5
+ import { rankByFields, tokenize } from './ranking.js';
7
6
  export async function queryContext(workspace, config, maps, query) {
8
7
  const refreshedAtoms = await refreshKnowledgeAtomStatuses(workspace, {
9
8
  fileMap: maps.fileMap,
@@ -22,6 +21,7 @@ export async function queryContext(workspace, config, maps, query) {
22
21
  // Collect git changes before file ranking so dirty files can influence ranking,
23
22
  // not just appear later as a low-token pack item.
24
23
  const knownFilePaths = new Set(maps.fileMap.files.map((f) => f.path));
24
+ const warnings = [];
25
25
  const gitChanges = [];
26
26
  if (await isGitRepo(workspace.rootPath)) {
27
27
  const workingTreeChanges = await getWorkingTreeChangesDetailed(workspace.rootPath);
@@ -54,6 +54,14 @@ export async function queryContext(workspace, config, maps, query) {
54
54
  reason: 'changed in recent commits',
55
55
  });
56
56
  }
57
+ const currentCommit = await getCurrentCommit(workspace.rootPath);
58
+ if (currentCommit &&
59
+ maps.fileMap.scannedAtCommit &&
60
+ currentCommit !== maps.fileMap.scannedAtCommit) {
61
+ const shortCurrent = currentCommit.slice(0, 7);
62
+ const shortScanned = maps.fileMap.scannedAtCommit.slice(0, 7);
63
+ warnings.push(`Structural maps were last scanned at commit ${shortScanned}; HEAD is now ${shortCurrent}. Run \`kgraph scan\` to refresh file and symbol relationships.`);
64
+ }
57
65
  }
58
66
  const gitChangedPaths = new Set(gitChanges.map((change) => change.path));
59
67
  const relevantCognition = rankByFields(query, atoms.filter((atom) => atom.status !== 'archived'), [
@@ -263,7 +271,7 @@ export async function queryContext(workspace, config, maps, query) {
263
271
  nearbySymbolExplanations,
264
272
  gitChanges,
265
273
  staleReferences,
266
- warnings: [],
274
+ warnings,
267
275
  };
268
276
  }
269
277
  function applyFileRankAdjustments(ranked, context) {
@@ -45,7 +45,7 @@ name: kgraph-pack
45
45
  description: Build a budget-aware KGraph context pack
46
46
  ---
47
47
 
48
- Run \`kgraph pack "<topic>" --budget 8000 --json --agent $AGENT\` to build a machine-readable context pack and record lightweight session context. Summarize token use, included files, symbols, relationships, git changes, session history, atoms, and omitted items with the inclusion reasons. When a symbol item includes an \`excerpt\` field, you already have the source — do not read that file for the symbol.
48
+ Run \`kgraph pack "<topic>" --budget 8000 --json --agent $AGENT\` to build a machine-readable context pack and record lightweight session context. Summarize token use, included files, symbols, relationships, git changes, session history, atoms, and omitted items with the inclusion reasons. When a symbol item includes an \`excerpt\` field or a file item includes a \`content\` field, you already have the source inline — do not read that file separately.
49
49
  `,
50
50
  },
51
51
  {
@@ -36,7 +36,7 @@ export function applyContextPolicy(content, mode, agentName) {
36
36
  .replaceAll(KGRAPH_CAPTURE_POLICY_PLACEHOLDER, renderCapturePolicy(agentName));
37
37
  }
38
38
  export function renderContextPolicy(mode, agentName) {
39
- const useResultBoundary = 'Use the returned KGraph ContextPack items as the first-pass source of truth. Prefer source ranges, atoms, git changes, and inclusion reasons from the pack before broad repository search. Do not rerun the same KGraph query just to tail or reformat output, do not continue broad repository search after the target file or range is identified, do not retry malformed shell commands with broader variants, and do not run broad `find`, recursive `grep`, or repeated full-file dumps after KGraph has narrowed the target.';
39
+ const useResultBoundary = 'Use the returned KGraph ContextPack items as the first-pass source of truth. Prefer source ranges, atoms, git changes, and inclusion reasons from the pack before broad repository search. When a file item includes a `content` field or a symbol item includes an `excerpt` field, that IS the source — do not read the file separately. Do not rerun the same KGraph query just to tail or reformat output, do not continue broad repository search after the target file or range is identified, do not retry malformed shell commands with broader variants, and do not run broad `find`, recursive `grep`, or repeated full-file dumps after KGraph has narrowed the target.';
40
40
  const packCommand = agentName
41
41
  ? `kgraph pack "<topic>" --budget 8000 --json --agent ${agentName}`
42
42
  : 'kgraph pack "<topic>" --budget 8000 --json';
@@ -20,12 +20,16 @@ const DECISION_CONTEXT = `## Feature intent — choose based on the situation
20
20
 
21
21
  **compact** exists to merge redundant knowledge. Consider it when you store something that feels overlapping with what pack already showed.
22
22
 
23
- **scan** exists to refresh maps after structural changes. The root workflow handles this automatically unless you created, deleted, or renamed many files outside of kgraph commands.`;
23
+ **scan** exists to refresh maps after structural changes. The root workflow handles this automatically unless you created, deleted, or renamed many files outside of kgraph commands.
24
+
25
+ **history** exists to answer "what did we do" and "when did this happen" questions. Use \`kgraph history "<topic>"\` when the user asks about prior work, decisions, or the sequence of changes — it covers the full timeline regardless of whether knowledge was captured via \`conclude\`, \`--capture\`, or inbox notes. Use \`kgraph knowledge list\` when the user wants the structured claim and evidence for an atom. Use \`kgraph pack\` when the user needs context to start or continue coding work. These three serve different intents: timeline vs. structured memory vs. coding context.
26
+
27
+ **budget** exists to control how much source context pack delivers. On large or complex projects, raise \`--budget\` (e.g. \`--budget 16000\`) when pack omits files or symbols that feel relevant — the default 8000 was tuned for small projects. When pack includes file items with a \`content\` field, the budget was already spent delivering that source inline; do not re-read those files.`;
24
28
  const DOCTOR_STEP = `Run \`kgraph doctor\` when setup, maps, inbox processing, or integrations look wrong. Run \`kgraph doctor --quality\` when context shows stale/noisy cognition references.`;
25
- const IMPACT_STEP = `Run \`kgraph impact "<file-or-symbol>"\` when the user asks what a change may affect. Run \`kgraph history "<topic>"\` when prior work or decisions matter.`;
29
+ const IMPACT_STEP = `Run \`kgraph impact "<file-or-symbol>"\` when the user asks what a change may affect. Run \`kgraph history "<topic>"\` when the user asks what was done before, who made a decision, or what the sequence of changes was.`;
26
30
  const REPAIR_STEP = `Run \`kgraph repair --dry-run\` before cleanup when stale/noisy atom refs need fixing. Run \`kgraph repair\` only when the user asks to apply that cleanup.`;
27
31
  const COMPACT_STEP = `Run \`kgraph compact --dry-run\` when cognition looks duplicated, noisy, or stale. Run \`kgraph compact\` only when the user asks to merge/archive cognition.`;
28
- const HISTORY_STEP = `Run \`kgraph history\` or \`kgraph history "<topic>"\` to review past cognition sessions with git author attribution.`;
32
+ const HISTORY_STEP = `Run \`kgraph history "<topic>"\` when the user asks what was done, decided, or changed — it covers the full timeline including notes captured via \`conclude\`, \`--capture\`, and inbox. Prefer history over \`knowledge list\` when the question is about sequence, timing, or authorship rather than atom details.`;
29
33
  const KNOWLEDGE_STEP = `Run \`kgraph knowledge list --topic "<topic>"\` or \`kgraph knowledge get <atom-id>\` when the user asks what KGraph remembers or atom provenance/lifecycle matters.`;
30
34
  const STALE_STEP = `Run \`kgraph stale\` when changed or deleted code may have invalidated durable knowledge. Run \`kgraph blame <atom-id>\` when provenance or evidence for a memory matters.`;
31
35
  const EXPLORATION_BOUNDARY_STEP = `Keep exploration bounded by the task. For simple edits, use KGraph to identify the likely file, then read only that file or a narrow range and make the edit. Do not keep searching after the target file is found, do not retry malformed shell commands with broader variants, and do not run broad \`find\`, recursive \`grep\`, or repeated full-file dumps after KGraph already returned candidate files.`;
@@ -45,7 +49,7 @@ function sessionStep(agentName, qualifier) {
45
49
  export function numberedWorkflow(agentName, options = {}) {
46
50
  return `1. Infer the topic from the user's request.
47
51
  2. {{KGRAPH_CONTEXT_POLICY}}
48
- 3. When the pack includes a symbol with an \`excerpt\` field, you already have the source code — do not read that file again for that symbol. Items in the \`omitted\` array were evaluated and excluded — do not manually search for them unless the user explicitly asks.
52
+ 3. When a pack item includes an \`excerpt\` field (symbol) or a \`content\` field (file), you already have the source code inline — do not read that file separately. Items in the \`omitted\` array were evaluated and excluded — do not manually search for them unless the user explicitly asks.
49
53
  4. ${EXPLORATION_BOUNDARY_STEP}
50
54
  5. ${VERIFY_EDIT_STEP}
51
55
  6. ${smartRootStep(agentName)}
@@ -71,7 +75,7 @@ ${DECISION_CONTEXT}`;
71
75
  */
72
76
  export function bulletWorkflow(agentName, options = {}) {
73
77
  return `- {{KGRAPH_CONTEXT_POLICY}}
74
- - When the pack includes a symbol with an \`excerpt\` field, you already have the source code — do not read that file again for that symbol. Items in the \`omitted\` array were evaluated and excluded — do not manually search for them unless the user explicitly asks.
78
+ - When a pack item includes an \`excerpt\` field (symbol) or a \`content\` field (file), you already have the source code inline — do not read that file separately. Items in the \`omitted\` array were evaluated and excluded — do not manually search for them unless the user explicitly asks.
75
79
  - ${EXPLORATION_BOUNDARY_STEP}
76
80
  - ${VERIFY_EDIT_STEP}
77
81
  - ${smartRootStep(agentName)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kentwynn/kgraph",
3
- "version": "0.2.35",
3
+ "version": "0.2.36",
4
4
  "description": "Persistent repo intelligence for AI coding assistants.",
5
5
  "type": "module",
6
6
  "bin": {