Compare commits

..
Author SHA1 Message Date
06eeb2890b fix(skillopt): emit proposed.md in no-mutate mode (#2635)
writeProposed now writes both best.md (optimizer's current-best pointer)
and proposed.md (the stable review artifact documented by --no-mutate);
the orchestrator returns the real proposed.md path instead of aliasing
best.md. Fix lands in the shared helper so both accept-branch call sites
are covered.

Takeover of #2719.

Co-authored-by: RerankerGuo <RerankerGuo@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-21 14:30:19 -07:00
9 changed files with 52 additions and 113 deletions
@@ -233,13 +233,14 @@ keep it or `git checkout` to throw it away. Nothing is committed for you.
**For a skill that ships with gbrain** (anything under the gbrain repo's own
`skills/`): SkillOpt refuses to overwrite it by default and writes the winner to
`skills/<name>/skillopt/best.md` instead, so an optimization pass can never
silently mutate a skill other people depend on. Two ways to handle that:
`skills/<name>/skillopt/proposed.md` instead (while keeping `best.md` as the
optimizer's current-best pointer), so an optimization pass can never silently
mutate a skill other people depend on. Two ways to handle that:
```bash
# See the proposed improvement without touching SKILL.md (works for ANY skill):
gbrain skillopt meeting-prep --split 1:1:1 --no-mutate
# → writes skills/meeting-prep/skillopt/best.md (the proposed rewrite), prints its path. Copy what you want.
# → writes skills/meeting-prep/skillopt/proposed.md, updates best.md, and prints the proposal path.
# Actually rewrite a bundled skill (explicit opt-in + an independent held-out set):
gbrain skillopt brain-ops --split 1:1:1 --allow-mutate-bundled \
+1 -18
View File
@@ -509,12 +509,8 @@ export function extractTimelineFromContent(content: string, slug: string): Extra
// DB-level uniqueness cannot collapse.
const citationPattern = /\[Source:\s*([^\]]+?),\s*(\d{4}-\d{2}-\d{2})\s*\]/g;
const bulletLinePattern = /^-\s+\*\*\d{4}-\d{2}-\d{2}\*\*\s*\|/;
// Lines captured by Format 4 (plain bullet) are skipped for the same
// reason: quality.md mandates a trailing [Source: ...] on those bullets,
// and re-extracting the citation would double-count the event.
const plainBulletLinePattern = /^-\s+\d{4}-\d{2}-\d{2}\s*[—–-]/;
for (const line of content.split(/\r?\n/)) {
if (bulletLinePattern.test(line) || plainBulletLinePattern.test(line)) continue;
if (bulletLinePattern.test(line)) continue;
const lineMatches = [...line.matchAll(citationPattern)];
if (lineMatches.length === 0) continue;
// Strip every citation marker from the line to leave the annotated text.
@@ -530,19 +526,6 @@ export function extractTimelineFromContent(content: string, slug: string): Extra
}
}
// Format 4: Plain bullet — - YYYY-MM-DD — Summary
// This is the format gbrain's own enrich skill writes (no bold, no source
// pipe). Without it, every brain-authored timeline entry is invisible to
// extraction and timeline_coverage stays at 0%. Anchored at line start so a
// date inside a summary/link cannot start a spurious entry; a bold Format-1
// line (`- **…**`) cannot match here (a `*` follows the bullet, not a
// digit), and the citation loop above skips these lines, so a plain bullet
// carrying its own [Source: ...] files exactly one entry.
const plainBulletPattern = /^-\s+(\d{4}-\d{2}-\d{2})\s*[—–-]\s*(.+)$/gm;
while ((match = plainBulletPattern.exec(content)) !== null) {
entries.push({ slug, date: match[1], source: 'markdown', summary: match[2].trim() });
}
return entries;
}
+3 -8
View File
@@ -1103,11 +1103,6 @@ export interface TimelineCandidate {
// Match: `- **YYYY-MM-DD** | summary` or `- **YYYY-MM-DD** -- summary`
// or `- **YYYY-MM-DD** - summary` or just `**YYYY-MM-DD** | summary`.
const TIMELINE_LINE_RE = /^\s*-?\s*\*\*(\d{4}-\d{2}-\d{2})\*\*\s*[|\-–—]+\s*(.+?)\s*$/;
// Plain bullet: `- YYYY-MM-DD — summary` (no bold, no source pipe). Kept in
// sync with extractTimelineFromContent's Format 4 (the fs-source path).
// Anchored flush-left so a date inside an indented continuation line cannot
// start a spurious entry.
const PLAIN_TIMELINE_LINE_RE = /^-\s+(\d{4}-\d{2}-\d{2})\s*[—–-]\s*(.+?)\s*$/;
/**
* Parse timeline entries from content. Looks at:
@@ -1124,7 +1119,7 @@ export function parseTimelineEntries(content: string): TimelineCandidate[] {
let i = 0;
while (i < lines.length) {
const m = TIMELINE_LINE_RE.exec(lines[i]) ?? PLAIN_TIMELINE_LINE_RE.exec(lines[i]);
const m = TIMELINE_LINE_RE.exec(lines[i]);
if (!m) {
i++;
continue;
@@ -1141,7 +1136,7 @@ export function parseTimelineEntries(content: string): TimelineCandidate[] {
let j = i + 1;
while (j < lines.length) {
const next = lines[j];
if (TIMELINE_LINE_RE.test(next) || PLAIN_TIMELINE_LINE_RE.test(next)) break;
if (TIMELINE_LINE_RE.test(next)) break;
if (/^#{1,6}\s/.test(next)) break;
if (next.trim().length === 0 && detailLines.length === 0) {
// skip leading blank line; if we hit a blank after detail content
@@ -1171,7 +1166,7 @@ export function parseTimelineEntries(content: string): TimelineCandidate[] {
// bullet pass are skipped (a bullet often carries its own citation).
const citationRe = /\[Source:\s*([^\]]+?),\s*(\d{4}-\d{2}-\d{2})\s*\]/g;
for (const line of lines) {
if (TIMELINE_LINE_RE.test(line) || PLAIN_TIMELINE_LINE_RE.test(line)) continue;
if (TIMELINE_LINE_RE.test(line)) continue;
const matches = [...line.matchAll(citationRe)];
if (matches.length === 0) continue;
const summary = line
+10 -4
View File
@@ -93,7 +93,13 @@ import { resolveLrSchedule } from './lr-schedule.ts';
import { preflight, formatPreflightReport } from './preflight.ts';
import { isRejected, loadRejectedBuffer, makeRejectedEntry, saveRejectedBuffer } from './rejected-buffer.ts';
import { runReflect, runOneShotRewrite, describeJudges } from './reflect.ts';
import { acceptCandidate, bestPath, revertAllPending, skillPath, writeProposed } from './version-store.ts';
import {
acceptCandidate,
proposedPath as proposedFilePath,
revertAllPending,
skillPath,
writeProposed,
} from './version-store.ts';
import { runValidationGate, scoreSkillOnTasks } from './validate-gate.ts';
import { ROLLOUT_SUCCESS_THRESHOLD } from './types.ts';
import type { SkillOptOpts, EditOp, RunReceipt, BenchmarkTask } from './types.ts';
@@ -702,9 +708,9 @@ async function runOptimizationLoop(
// to the catch's assignment values only (it can't prove the async callback ran).
const finalOutcome = outcome as 'accepted' | 'no_improvement' | 'aborted' | 'errored';
if (!mutateDecision.mutate && finalOutcome === 'accepted') {
// best.md was written by writeProposed() in the accept branch (no-mutate
// path); it doubles as proposed.md for human review. SKILL.md untouched.
proposedPath = bestPath(skillsDir, skillName);
// writeProposed() emitted both the best pointer and the stable review
// artifact in the accept branch. SKILL.md remains untouched.
proposedPath = proposedFilePath(skillsDir, skillName);
} else if (mutateDecision.mutate) {
mutatedSkillFile = finalOutcome === 'accepted';
}
+15 -9
View File
@@ -23,6 +23,7 @@
*
* history.json
* best.md
* proposed.md
* versions/
* v0001_e1_s1.md
* v0002_e1_s2.md
@@ -52,6 +53,10 @@ export function bestPath(skillsDir: string, skillName: string): string {
return path.join(skilloptDir(skillsDir, skillName), 'best.md');
}
export function proposedPath(skillsDir: string, skillName: string): string {
return path.join(skilloptDir(skillsDir, skillName), 'proposed.md');
}
export function skillPath(skillsDir: string, skillName: string): string {
return path.join(skillsDir, skillName, 'SKILL.md');
}
@@ -171,17 +176,18 @@ export function acceptCandidate(input: AcceptInput): AcceptResult {
}
/**
* Write the candidate to `best.md` (which doubles as `proposed.md`) WITHOUT
* touching SKILL.md or the history ledger. Used by the `--no-mutate` /
* bundled-without-allow paths: the optimizer found a better candidate but the
* caller opted out of in-place mutation, so we surface it for human review.
* Returns the path written. Atomic (.tmp + rename).
* Write the candidate to both `best.md` and `proposed.md` WITHOUT touching
* SKILL.md or the history ledger. `best.md` remains the optimizer's current
* best pointer; `proposed.md` is the stable human-review artifact promised by
* `--no-mutate`. Returns the proposal path. Each write is atomic (.tmp + rename).
*/
export function writeProposed(skillsDir: string, skillName: string, candidateText: string): string {
const p = bestPath(skillsDir, skillName);
fs.mkdirSync(path.dirname(p), { recursive: true });
atomicWrite(p, candidateText);
return p;
const best = bestPath(skillsDir, skillName);
const proposed = proposedPath(skillsDir, skillName);
fs.mkdirSync(path.dirname(best), { recursive: true });
atomicWrite(best, candidateText);
atomicWrite(proposed, candidateText);
return proposed;
}
/**
+4 -4
View File
@@ -39,6 +39,7 @@ import { runSkillOpt } from '../../src/core/skillopt/orchestrator.ts';
import {
bestPath,
loadHistory,
proposedPath,
skillPath,
} from '../../src/core/skillopt/version-store.ts';
import { loadRejectedBuffer } from '../../src/core/skillopt/rejected-buffer.ts';
@@ -741,7 +742,7 @@ describe('skillopt T3 — F11 held-out gate, ablation opts, no-DB-pollution', ()
} finally { fixture.cleanup(); }
});
test('--no-mutate writes proposed.md (best.md), leaves SKILL.md untouched', async () => {
test('--no-mutate writes proposed.md and best.md, leaves SKILL.md untouched', async () => {
const fixture = setupFixture(SKILL_PEOPLE_ONLY, CITATIONS_BENCHMARK);
try {
installStub({
@@ -753,10 +754,9 @@ describe('skillopt T3 — F11 held-out gate, ablation opts, no-DB-pollution', ()
const result = await runOnce(fixture, { noMutate: true });
expect(result.outcome).toBe('accepted');
expect(result.mutatedSkillFile).toBe(false);
expect(result.proposedPath).toBeDefined();
// proposed.md (best.md) exists and carries the improvement.
expect(fs.existsSync(result.proposedPath!)).toBe(true);
expect(result.proposedPath).toBe(proposedPath(fixture.skillsDir, SKILL));
expect(fs.readFileSync(result.proposedPath!, 'utf8')).toContain('## Citations');
expect(fs.readFileSync(bestPath(fixture.skillsDir, SKILL), 'utf8')).toContain('## Citations');
// SKILL.md on disk is UNCHANGED (still People-only).
const skill = fs.readFileSync(skillPath(fixture.skillsDir, SKILL), 'utf8');
expect(skill).not.toContain('## Citations');
-43
View File
@@ -185,49 +185,6 @@ describe('extractTimelineFromContent', () => {
expect(entries).toHaveLength(1);
expect(entries[0].summary).toBe('Landed the enterprise pilot with acme-example.');
});
// Format 4: the plain bullet `- YYYY-MM-DD — Summary` that gbrain's own
// enrich skill writes. Before this was supported, every brain-authored
// timeline entry was invisible and timeline_coverage was stuck at 0%.
it('extracts plain bullet format (- YYYY-MM-DD — Summary)', () => {
const content = `## Timeline\n- 2026-06-01 — Catch-up call with alice-example; intros offered.`;
const entries = extractTimelineFromContent(content, 'people/alice-example');
expect(entries).toHaveLength(1);
expect(entries[0].date).toBe('2026-06-01');
expect(entries[0].source).toBe('markdown');
expect(entries[0].summary).toBe('Catch-up call with alice-example; intros offered.');
});
it('files exactly one entry for a plain bullet that carries its own citation', () => {
// quality.md mandates this shape; it must not double-count via the
// citation arm (Format 3) AND the plain-bullet arm (Format 4).
const content = `- 2026-05-31 — Confirmed full name. [Source: User, 2026-05-31]`;
const entries = extractTimelineFromContent(content, 'people/charlie-example');
expect(entries).toHaveLength(1);
expect(entries[0].date).toBe('2026-05-31');
expect(entries[0].source).toBe('markdown');
expect(entries[0].summary).toContain('Confirmed full name.');
});
it('does not double-count bold (Format 1) lines as plain bullets', () => {
const content = `- **2025-03-18** | Meeting — Discussed partnership`;
const entries = extractTimelineFromContent(content, 'test');
expect(entries).toHaveLength(1);
expect(entries[0].source).toBe('Meeting');
});
it('does not start a spurious entry from a date inside a summary', () => {
const content = `- 2026-06-01 — See [meeting](meetings/2026-06-01).`;
const entries = extractTimelineFromContent(content, 'people/alice-example');
expect(entries).toHaveLength(1);
expect(entries[0].date).toBe('2026-06-01');
});
it('handles en dash and hyphen separators in plain bullets', () => {
const content = `- 2026-06-01 First\n- 2026-06-02 - Second`;
const entries = extractTimelineFromContent(content, 'test');
expect(entries).toHaveLength(2);
});
});
describe('walkMarkdownFiles', () => {
-24
View File
@@ -720,30 +720,6 @@ More prose here.
const entries = parseTimelineEntries(content);
expect(entries.length).toBe(2);
});
// Plain bullet (extract.ts Format 4 parity — the db-source path must see
// the same entries as the fs-source path).
test('parses plain bullet: - YYYY-MM-DD — summary', () => {
const entries = parseTimelineEntries('## Timeline\n- 2026-06-01 — Catch-up call with alice-example');
expect(entries.length).toBe(1);
expect(entries[0].date).toBe('2026-06-01');
expect(entries[0].summary).toBe('Catch-up call with alice-example');
});
test('files exactly one entry for a plain bullet carrying its own citation', () => {
const entries = parseTimelineEntries('- 2026-05-31 — Confirmed full name. [Source: User, 2026-05-31]');
expect(entries.length).toBe(1);
expect(entries[0].date).toBe('2026-05-31');
});
test('skips invalid dates in plain bullets', () => {
expect(parseTimelineEntries('- 2026-13-45 — Bad date').length).toBe(0);
});
test('does not double-count a bold bullet as a plain bullet', () => {
const entries = parseTimelineEntries('- **2026-01-15** | Met with Alice');
expect(entries.length).toBe(1);
});
});
// ─── isAutoLinkEnabled ─────────────────────────────────────────
+15
View File
@@ -12,9 +12,11 @@ import {
bestPath,
historyPath,
loadHistory,
proposedPath,
revertAllPending,
skillPath,
versionsDir,
writeProposed,
} from '../../src/core/skillopt/version-store.ts';
let tmpDir: string;
@@ -79,6 +81,19 @@ describe('acceptCandidate (D8 two-phase commit)', () => {
});
});
describe('writeProposed', () => {
test('writes distinct best and proposed artifacts without mutating SKILL.md (#2635)', () => {
const candidate = '---\nname: test\n---\nproposed body\n';
const written = writeProposed(tmpDir, SKILL, candidate);
expect(written).toBe(proposedPath(tmpDir, SKILL));
expect(fs.readFileSync(bestPath(tmpDir, SKILL), 'utf8')).toBe(candidate);
expect(fs.readFileSync(proposedPath(tmpDir, SKILL), 'utf8')).toBe(candidate);
expect(fs.readFileSync(skillPath(tmpDir, SKILL), 'utf8')).toContain('baseline body');
});
});
describe('revertAllPending (D8 crash recovery)', () => {
test('no-op when no pending rows', () => {
const reverted = revertAllPending(tmpDir, SKILL);