Compare commits

..
Author SHA1 Message Date
d8cba9a76b fix(context): read documented '## P1 — Today' plain tasks in live context (#2186)
resolveTodayTasks only matched a bare '## Today' heading and bold-prefixed
'- [ ] **task**' lines, while the daily-task-manager skill's documented
Output Format writes '## P1 — Today' with plain '- [ ] task' lines — so
documented writes surfaced zero tasks in live context.

Reader now accepts both heading forms and both line forms, two-step: the
legacy bold prefix extracts just the task name (dropping trailing metadata),
falling back to the plain full-line form.

Salvaged from PR #2188 (reader-side half). The skill-doc rewrites in that PR
are dropped: master #2938 kept ops/ synced and made put_page write-through
durable, so the 'gbrain get/put ops/tasks' docs are correct as-is. The PR's
single-regex line matcher is replaced with the two-step match because its
alternation captured '**name** — metadata' verbatim for bold lines.

Takeover of #2188. Fixes #2186.

Co-authored-by: caioribeiroclw-pixel <caioribeiroclw-pixel@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:36:51 -07:00
4 changed files with 45 additions and 68 deletions
+8 -40
View File
@@ -5,8 +5,8 @@
* checks if back-links exist, and optionally creates them.
*
* Usage:
* gbrain check-backlinks check [dir] [--dir <brain-dir>] # report missing back-links
* gbrain check-backlinks fix [dir] [--dir <brain-dir>] # create missing back-links
* gbrain check-backlinks check [--dir <brain-dir>] # report missing back-links
* gbrain check-backlinks fix [--dir <brain-dir>] # create missing back-links
* gbrain check-backlinks fix --dry-run # preview fixes
*/
@@ -201,40 +201,6 @@ export interface BacklinksResult {
dryRun: boolean;
}
export interface ParsedBacklinksArgs {
subcommand: string | undefined;
brainDir: string;
dryRun: boolean;
}
export function parseBacklinksArgs(args: string[]): ParsedBacklinksArgs {
const subcommand = args[0];
const dryRun = args.includes('--dry-run');
const dirIdx = args.indexOf('--dir');
const flagDir = dirIdx >= 0 && args[dirIdx + 1] && !args[dirIdx + 1].startsWith('--')
? args[dirIdx + 1]
: undefined;
let positionalDir: string | undefined;
for (let i = 1; i < args.length; i++) {
const arg = args[i];
if (arg === '--dir') {
i++;
continue;
}
if (arg === '--dry-run') continue;
if (arg.startsWith('--')) continue;
positionalDir = arg;
break;
}
return {
subcommand,
brainDir: flagDir ?? positionalDir ?? '.',
dryRun,
};
}
/**
* Library-level backlinks check/fix. Throws on validation errors; returns a
* structured result so Minions handlers + autopilot-cycle can surface counts.
@@ -270,14 +236,16 @@ export async function runBacklinksCore(opts: BacklinksOpts): Promise<BacklinksRe
}
export async function runBacklinks(args: string[]) {
const { subcommand, brainDir, dryRun } = parseBacklinksArgs(args);
const subcommand = args[0];
const dirIdx = args.indexOf('--dir');
const brainDir = dirIdx >= 0 ? args[dirIdx + 1] : '.';
const dryRun = args.includes('--dry-run');
if (!subcommand || !['check', 'fix'].includes(subcommand)) {
console.error('Usage: gbrain check-backlinks <check|fix> [dir] [--dir <brain-dir>] [--dry-run]');
console.error('Usage: gbrain check-backlinks <check|fix> [--dir <brain-dir>] [--dry-run]');
console.error(' check Report missing back-links');
console.error(' fix Create missing back-links (appends to Timeline)');
console.error(' dir Brain directory (default: current directory)');
console.error(' --dir Brain directory override');
console.error(' --dir Brain directory (default: current directory)');
console.error(' --dry-run Preview fixes without writing');
process.exit(1);
}
+15 -4
View File
@@ -453,7 +453,14 @@ function resolveActivity(
* every `assemble()` call. 1 MB is generous for a human-edited task list. */
const MAX_TASKS_MD_BYTES = 1_000_000;
/** Extract open tasks from ops/tasks.md "## Today" section. */
/** Extract open tasks from ops/tasks.md Today section.
*
* The daily-task-manager skill's documented Output Format uses priority
* headings (`## P1 — Today`) with plain `- [ ] task` lines; older fixtures
* used a bare `## Today` heading with bold task names. Accept both so the
* live-context reader matches the documented writer contract instead of
* silently surfacing no tasks (#2186).
*/
function resolveTodayTasks(workspaceDir: string): string[] {
try {
const path = join(workspaceDir, 'ops', 'tasks.md');
@@ -461,14 +468,18 @@ function resolveTodayTasks(workspaceDir: string): string[] {
// statSync throws if the file doesn't exist; that lands in the outer catch.
if (statSync(path).size > MAX_TASKS_MD_BYTES) return [];
const raw = readFileSync(path, 'utf8');
const todayMatch = raw.match(/## Today[\s\S]*?(?=\n## |$)/);
const todayMatch = raw.match(/^##\s+(?:P\d\s*[—–-]\s*)?Today\b[\s\S]*?(?=\n##\s|$(?![\s\S]))/m);
if (!todayMatch) return [];
const lines = todayMatch[0].split('\n');
const open: string[] = [];
for (const line of lines) {
// Match unchecked task lines: - [ ] **task name** ...
const m = line.match(/^\s*-\s*\[ \]\s*\*\*(.+?)\*\*/);
// Match unchecked task lines. Legacy bold form first (extracts just
// the task name, dropping trailing metadata), then the documented
// plain form (whole line body is the task).
const m =
line.match(/^\s*-\s*\[ \]\s*\*\*(.+?)\*\*/) ??
line.match(/^\s*-\s*\[ \]\s*(.+?)\s*$/);
if (m) open.push(sanitizeForPrompt(m[1].trim()));
}
return open.slice(0, 5); // cap at 5 to keep prompt lean
-24
View File
@@ -4,7 +4,6 @@ import {
extractPageTitle,
hasBacklink,
buildBacklinkEntry,
parseBacklinksArgs,
} from '../src/commands/backlinks.ts';
describe('extractEntityRefs', () => {
@@ -105,26 +104,3 @@ describe('findBacklinkGaps dedupe (v0.36.x #967 regression)', () => {
}
});
});
describe('parseBacklinksArgs', () => {
test('uses positional dir for check and fix subcommands', () => {
expect(parseBacklinksArgs(['check', '/tmp/brain']).brainDir).toBe('/tmp/brain');
expect(parseBacklinksArgs(['fix', '/tmp/brain']).brainDir).toBe('/tmp/brain');
});
test('defaults to cwd when no dir given', () => {
expect(parseBacklinksArgs(['check']).brainDir).toBe('.');
});
test('--dir overrides positional dir and preserves dry-run', () => {
const parsed = parseBacklinksArgs(['fix', '/tmp/ignored', '--dir', '/tmp/brain', '--dry-run']);
expect(parsed.subcommand).toBe('fix');
expect(parsed.brainDir).toBe('/tmp/brain');
expect(parsed.dryRun).toBe(true);
});
test('--dir missing its value falls back to positional dir', () => {
expect(parseBacklinksArgs(['check', '/tmp/brain', '--dir']).brainDir).toBe('/tmp/brain');
expect(parseBacklinksArgs(['check', '--dir', '--dry-run']).brainDir).toBe('.');
});
});
+22
View File
@@ -322,6 +322,28 @@ describe('gbrain-context engine', () => {
expect(result.systemPromptAddition).not.toContain('Something later');
});
it('injects documented "## P1 — Today" plain tasks from ops/tasks.md (#2186)', async () => {
tmpDir = makeWorkspace({
heartbeat: { garryAwake: true },
tasks: `# Tasks\n\n## P0 — Urgent\n- [ ] **Escalate outage**\n\n## P1 — Today\n- [ ] Call Alice about launch plan\n- [ ] **Review Bob contract** — due Friday\n- [x] Completed item\n\n## P2 — This Week\n- [ ] Should not surface`,
});
const engine = createGBrainContextEngine({ workspaceDir: tmpDir });
const result = await engine.assemble({
sessionId: 'test-session',
messages: [],
});
expect(result.systemPromptAddition).toContain('Open tasks');
expect(result.systemPromptAddition).toContain('Call Alice about launch plan');
// Bold form still extracts just the task name, not trailing metadata.
expect(result.systemPromptAddition).toContain('Review Bob contract');
expect(result.systemPromptAddition).not.toContain('due Friday');
expect(result.systemPromptAddition).not.toContain('Escalate outage');
expect(result.systemPromptAddition).not.toContain('Completed item');
expect(result.systemPromptAddition).not.toContain('Should not surface');
});
it('no activity section when calendar is empty and no tasks', async () => {
tmpDir = makeWorkspace({
heartbeat: { garryAwake: true },