Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
feat(skills): learnings and skills never repeat or contradict each other
Shrish Dwivedi42e7d41b1c47
diff --git a/src/claude/format.ts b/src/claude/format.tsindex ee9d0759..af64c8dc 100644--- a/src/claude/format.ts+++ b/src/claude/format.ts@@ -244,7 +244,7 @@ export function formatRetrieval(ask: AskJson, cap = 5): string | null {export const INJECT_MIN_COVERAGE = 0.15;/** How many recently-injected pointers the novelty gate remembers per session. */-const INJECTED_POINTERS_CAP = 40;+export const INJECTED_POINTERS_CAP = 40;/** How many weak-match nudges one session may spend. A line that shows up every* turn stops being read; two is enough to land the habit without becomingdiff --git a/src/claude/prompt-hook.ts b/src/claude/prompt-hook.tsindex ee4e3fb9..1bf59ca2 100644--- a/src/claude/prompt-hook.ts+++ b/src/claude/prompt-hook.ts@@ -16,7 +16,7 @@ import { brand, tag } from '../brand.js';import { scopeOf, scopesOfGraph } from '../graph/scopes.js';import { keepsNotes } from '../notes/home.js';import { findNotes, listNotes, type NoteHit } from '../notes/notes.js';-import { notesForPrompt, relevantRetrieval, type AskJson } from './format.js';+import { INJECTED_POINTERS_CAP, notesForPrompt, relevantRetrieval, type AskJson } from './format.js';import { CHILD_TIMEOUT_MS, emitHook, graftJsonWithin, payloadSessionId, withContextDirArg } from './hook-io.js';import { promptPart } from './skills-wiring.js';import { readSession, readStats, writeSession } from './state.js';@@ -270,12 +270,26 @@ export async function handlePrompt(input: any, dir: string, opts: { budgetMs?: nconst id = payloadSessionId(input);const s = readSession(dir, id);// What an earlier session worked out matters more than where code is.- const learnings = underTrail ? promptLearnings(dir, prompt, ask, byWords) : [];+ // Part 7: a learning the run block already says (its step repeats it, or it wins over a step) is said once, there.+ const said = new Set(skills.said ?? []);+ const all = underTrail ? promptLearnings(dir, prompt, ask, byWords) : [];+ const learnings = all.filter((h) => !said.has(h.note.id));+ // The session's one shown list, which on-touch reads too: a learning the block said is not shown again on a file open.+ if (said.size) s.injectedNotes = [...(s.injectedNotes ?? []), ...saidPaths(dir, said)].slice(-INJECTED_POINTERS_CAP);const notes = learnings.length ? notesForPrompt({ query: prompt, mode: 'learnings', hits: [], notes: learnings }, s) : null;const retrieval = ask ? relevantRetrieval(ask, s) : null;// A count, never the prompt: nothing the person typed is kept (spec section 6).if (ask) s.promptAsks = (s.promptAsks ?? 0) + 1;// Teammates' branches on the same code come after an edit instead (hooks.ts editOverlap).say([notes, retrieval].filter(Boolean).join('\n\n'));- if (ask || notes) writeSession(dir, id, s);+ if (ask || notes || said.size) writeSession(dir, id, s);+}++/** The paths the session's shown list knows the learnings `ids` by (as `listNotes` gives them). [] on a read failure. */+function saidPaths(dir: string, ids: ReadonlySet<string>): string[] {+ try {+ return listNotes(dir, { branches: false }).filter((n) => ids.has(n.id)).map((n) => n.path || n.title);+ } catch {+ return [];+ }}diff --git a/src/claude/prompt-skills.ts b/src/claude/prompt-skills.tsindex 5f1d1212..915eea61 100644--- a/src/claude/prompt-skills.ts+++ b/src/claude/prompt-skills.ts@@ -44,6 +44,9 @@ import { lastResult, lastResultLine } from '../skills/check-result.js';import { noteCodexPrompt } from '../trace/codex.js';import { useFor } from '../trace/dialect.js';import { stopBlockReason } from '../skills/offer-words.js';+import { recallMarks, saidIn, shownFiles, stepLearnings, withFixes } from '../skills/follow-learnings.js';+import { readSession } from './state.js';+import { payloadSessionId } from './hook-io.js';export { sessionStartSkills } from './start-skills.js';@@ -59,6 +62,8 @@ export interface PromptDeps {gate: (input: unknown, dir: string, env?: NodeJS.ProcessEnv) => ReturnType<typeof skillsGate>;probes: ProbeOpts;clock: () => number;+ /** Part 7: the file names of the learnings this session showed already (the prompt hook's and on-touch's one list). */+ shown: () => ReadonlySet<string>;}/** The telemetry answer for each class g5 reports (stale and not-shown were never answered: nothing is sent). */@@ -81,6 +86,9 @@ export function promptSkills(input: any, dir: string, env: NodeJS.ProcessEnv = pgate: deps.gate ?? skillsGate,probes: deps.probes ?? {},clock,+ shown: deps.shown ?? (() => {+ try { return shownFiles(readSession(dir, payloadSessionId(input)).injectedNotes); } catch { return new Set<string>(); }+ }),};// Phase 2 (3.2 step 1, P30, R7): on Codex the prompt's keyed hash goes into the session first, before the catch-up// reads the rollout, so the typed line already there counts as the person's. A prompt that is Trail's own Stop@@ -144,6 +152,7 @@ function inside(ctx: GateCtx, st: SkillSessionState, fold: FoldResult | null, ty// 8. The cue, while there is time for it.let notice: string | undefined;+ let said: string[] | undefined;if (d.clock() < deadline) {const mine = [...st.injected].reverse().find((i) => i.cue !== 'check');// A block this session counts as used just now; otherwise the newest use here, within 24 hours.@@ -168,6 +177,7 @@ function inside(ctx: GateCtx, st: SkillSessionState, fold: FoldResult | null, tyif (r) {context.push(r.context);notice = r.notice;+ if (r.said?.length) said = r.said;}}}@@ -176,6 +186,7 @@ function inside(ctx: GateCtx, st: SkillSessionState, fold: FoldResult | null, tyconst out: HookOut = {};if (context.length) out.context = context.join('\n');if (notice) out.notice = notice;+ if (said) out.said = said;return out;}@@ -202,6 +213,7 @@ function saveAsk(ctx: GateCtx, st: SkillSessionState, fold: FoldResult | null, trepoRoot: root, home: env.HOME || homedir(), platform: process.platform,prior: findPriorSheet(sheet, env), moment: 'asked', applies: scope === 'every repo' ? 'every repo' : run.repoKey, now: ctx.now, askedWith: typed,readSheet: (id) => readRunSheet(id, env), taken: (n) => nameTaken(n, { repoKeys: keys, checkout: root || ctx.checkout, env }) !== null,+ learnings: stepLearnings({ repoKeys: [sheet.repoKey], checkout: root, env }),});if (!compiled.ok) {const words = refusalWords(compiled.reason, compiled.detail);@@ -260,7 +272,7 @@ function askRun(st: SkillSessionState, fold: FoldResult | null, typed: string):return run && Date.parse(run.lastAt) >= Date.parse(last.at) ? run : null;}-function bring(ctx: GateCtx, st: SkillSessionState, cue: CueResult, d: PromptDeps, deadline: number, run: RunState | null): { context: string; notice?: string } | null {+function bring(ctx: GateCtx, st: SkillSessionState, cue: CueResult, d: PromptDeps, deadline: number, run: RunState | null): { context: string; notice?: string; said?: string[] } | null {const { env, now } = ctx;const c = cue.cand;// The risk rules on the steps as the block would show them, values filled in (a default can be edited by hand).@@ -277,13 +289,16 @@ function bring(ctx: GateCtx, st: SkillSessionState, cue: CueResult, d: PromptDepif (run) run.skillId = c.ref.id;return { context: `[trail] Same job as before: start from the steps of skill ${nameOf(c)} above.` };}+ // Part 7: what the person's live learnings say of these steps; the block says each once, and its steps are what credit reads.+ // Read before the probes, so their budget is what is left. Past the deadline the block goes without them, and the prompt's learnings lines still say them.+ const marks = d.clock() < deadline ? recallMarks(c.skill.steps, stepLearnings({ repoKeys: scopeKeys(ctx, st), checkout: ctx.checkout, env }), d.shown()) : [];const budgetMs = Math.max(0, Math.min(PROBE_BUDGET_MS, deadline - d.clock()));const probes = runProbes(c.skill, ctx.checkout, now, env, { ...d.probes, budgetMs });const lastFail = c.state?.lastFails?.length ? c.state.lastFails[c.state.lastFails.length - 1]! : null;// Phase 2 (3.2 step 5): the anchors' CLI scan gets only what the 400 ms leave after the probes (the hook's clock may be a test's).const anchorDeadline = Date.now() + Math.max(0, deadline - d.clock());- const block = runBlock(c, { values: cue.values, notes: cue.notes, probes, canAsk: canAsk(ctx), header: 'job', lastFail, anchorDeadline });- const inj = withReadyFailed(injectionFor(c, cue.values, cue.kind, st.epoch, now), probes);+ const block = runBlock(c, { values: cue.values, notes: cue.notes, probes, canAsk: canAsk(ctx), header: 'job', lastFail, anchorDeadline, marks });+ const inj = withReadyFailed(injectionFor({ ...c, skill: withFixes(c.skill, marks) }, cue.values, cue.kind, st.epoch, now), probes);if (run) {inj.runId = run.id;run.skillId = c.ref.id;@@ -291,7 +306,8 @@ function bring(ctx: GateCtx, st: SkillSessionState, cue: CueResult, d: PromptDep// New values: the full block replaces that injection's values and steps (same injId, a fresh run).if (prior) st.injected[st.injected.indexOf(prior)] = { ...inj, injId: prior.injId };else st.injected.push(inj);- return { context: block, ...(hostFacts(env, ctx.host as Host).promptNotice ? { notice: useNotice(c) } : {}) };+ const said = saidIn(block, marks);+ return { context: block, ...(hostFacts(env, ctx.host as Host).promptNotice ? { notice: useNotice(c) } : {}), ...(said.length ? { said } : {}) };}/** The check uses the values of the block it checks, and any the question itself names. */diff --git a/src/claude/start-skills.ts b/src/claude/start-skills.tsindex 6b6420d9..87b1d0d5 100644--- a/src/claude/start-skills.ts+++ b/src/claude/start-skills.ts@@ -32,6 +32,7 @@ import { creditCalls, creditRun } from '../skills/ledger.js';import { listHeld, markHeldShown, type HeldItem } from '../skills/store-held.js';import { candidatesHere, indexLine, refusedAtRecall, type Candidate } from '../skills/recall.js';import { injectionFor, runBlock, runProbes, withReadyFailed, type ProbeOpts } from '../skills/runblock.js';+import { recallMarks, stepLearnings, withFixes } from '../skills/follow-learnings.js';import { flatLine } from '../notes/flatten.js';import { FROM_TRAIL } from '../skills/directive-words.js';import { canAsk, hookError, syncGate, trimInjected, type Sent } from './skills-hook-util.js';@@ -259,7 +260,9 @@ function reinject(ctx: GateCtx, st: SkillSessionState, openAtBoundary: string[],const c = cands.find((x) => x.ref.id === inj.skillId);if (!c || refusedAtRecall(c.skill, inj.params)) return null;const results = runProbes(c.skill, ctx.checkout, ctx.now, ctx.env, probes);- const block = runBlock(c, { values: inj.params, notes: [], probes: results, canAsk: canAsk(ctx), header: 'compact', lastFail: null });- st.injected.push(withReadyFailed(injectionFor(c, inj.params, 'compact', st.epoch, ctx.now), results));+ // Part 7: the same say of the person's learnings as the block it re-sends.+ const marks = recallMarks(c.skill.steps, stepLearnings({ repoKeys: st.scopeKeys, checkout: ctx.checkout, env: ctx.env }));+ const block = runBlock(c, { values: inj.params, notes: [], probes: results, canAsk: canAsk(ctx), header: 'compact', lastFail: null, marks });+ st.injected.push(withReadyFailed(injectionFor({ ...c, skill: withFixes(c.skill, marks) }, inj.params, 'compact', st.epoch, ctx.now), results));return block;}diff --git a/src/init/keep.ts b/src/init/keep.tsindex 45a8c6a7..0b83e035 100644--- a/src/init/keep.ts+++ b/src/init/keep.ts@@ -46,13 +46,19 @@ import { KEEP_LINE, RELAY_LINE } from './relay.js';import { afterKeepLines, type ScreenFacts } from './review-screen.js';import { applyName } from './name-call.js';import { prefText } from './prefs.js';+import { lessonRefused, newLessonId, writeLesson } from '../skills/lessons.js';+import { onlyRepeats } from '../skills/follow-learnings.js';import { recompileInitSkill, typedAt } from './replay-runs.js';import { dayWords } from './review-screen.js';import type { InitItem, KeepAnswer } from './types.js';export { leadWords, parseKeepAnswer, replyNamesList } from './keep-answer.js';-export interface KeepResult { kept: InitItem[]; notKept: InitItem[]; refused: Array<{ item: InitItem; why: string }> }+export interface KeepResult {+ kept: InitItem[]; notKept: InitItem[]; refused: Array<{ item: InitItem; why: string }>;+ /** Part 7: kept preferences that only repeat a step of a skill kept with them, kept as a lesson on that skill instead. */+ folded?: Array<{ item: InitItem; skill: string }>;+}/** Where a keep writes: the checkout (phase 0's notes) and its repo key; the run it answers; PR-review findings in memory. */export interface KeepPlace {@@ -80,7 +86,7 @@ export function prefLine(item: Pick<InitItem, 'pref'>, env: NodeJS.ProcessEnv):return line || null;}-function keepSkill(item: InitItem, how: 'tty' | 'yes' | 'keep', place: KeepPlace, env: NodeJS.ProcessEnv, now: Date): { id: string; name: string } | string {+function keepSkill(item: InitItem, how: 'tty' | 'yes' | 'keep', place: KeepPlace, env: NodeJS.ProcessEnv, now: Date): { id: string; name: string; steps: string[] } | string {const s = item.skill;if (!s) return 'gone';let compiled = s.compiled;@@ -95,7 +101,7 @@ function keepSkill(item: InitItem, how: 'tty' | 'yes' | 'keep', place: KeepPlacetry {const ref = savePersonal(compiled, { from: 'init', runId: compiled.source.runId, consent: 'init', stepsVerified: stepsTotal(compiled), env, now });track('skill_saved', { from: 'init', scope: 'personal' });- return { id: ref.id, name: compiled.name };+ return { id: ref.id, name: compiled.name, steps: compiled.steps.map((s) => s.cmd) };} catch (e) {return e instanceof Error && /name|taken|exists/i.test(e.message) ? 'taken' : 'failed';}@@ -132,6 +138,26 @@ function keepPreference(item: InitItem, place: KeepPlace, env: NodeJS.ProcessEnvreturn { id: n.id ?? '', name: '' };}+/**+ * Part 7: the skill kept here whose steps a preference only repeats ("run scripts/gen_schema.py" beside a skill whose+ * step runs it), so the agent hears it once, with the skill. Only a preference for this repo just for the person: one+ * for every repo or added to the repo says more than one skill's step, and keeps its own place.+ */+function foldInto(item: InitItem, skills: Array<{ name: string; steps: string[] }>, env: NodeJS.ProcessEnv): { name: string; line: string } | null {+ if (item.scope === 'repo' || item.applies === 'every repo' || !skills.length) return null;+ const line = prefLine(item, env);+ if (!line || lessonRefused(line)) return null;+ const s = skills.find((k) => onlyRepeats(line, k.steps));+ return s ? { name: s.name, line } : null;+}++/** The preference as a lesson on the skill: the person's own words, dated the day they first said it. */+function keepAsLesson(item: InitItem, into: { name: string; line: string }, place: KeepPlace, env: NodeJS.ProcessEnv, now: Date): { id: string; name: string } {+ const id = newLessonId();+ writeLesson({ id, skill: into.name, at: firstDay(item.count, now), text: into.line, kind: 'lesson', src: 'correction', wall: null }, place.repoKey, env);+ return { id, name: '' };+}+function keepReview(item: InitItem, place: KeepPlace): { id: string; name: string } | string {const f = place.reviews?.get(item.id);if (!f) return 'gone';@@ -150,13 +176,20 @@ export function keepItems(picked: InitItem[], all: InitItem[], how: 'tty' | 'yesconst kept: InitItem[] = [];const refused: KeepResult['refused'] = [];const names: KeptName[] = [];- for (const item of picked) {+ // Part 7: skills first, so a preference that only repeats a step of one kept here goes into it as a lesson.+ const skills: Array<{ name: string; steps: string[] }> = [];+ const folded: NonNullable<KeepResult['folded']> = [];+ for (const item of [...picked].sort((a, b) => Number(b.kind === 'skill') - Number(a.kind === 'skill'))) {let r: { id: string; name: string } | string;try {+ const into = item.kind === 'preference' ? foldInto(item, skills, env) : null;r = item.kind === 'skill' ? keepSkill(item, how, at, env, now): item.kind === 'guardrail' ? keepGuardrail(item, at, env, now)- : item.kind === 'preference' ? keepPreference(item, at, env, now)- : keepReview(item, at);+ : into ? keepAsLesson(item, into, at, env, now)+ : item.kind === 'preference' ? keepPreference(item, at, env, now)+ : keepReview(item, at);+ if (typeof r !== 'string' && 'steps' in r) skills.push({ name: r.name, steps: r.steps as string[] });+ if (into && typeof r !== 'string') folded.push({ item, skill: into.name });} catch {r = 'failed';}@@ -204,7 +237,7 @@ export function keepItems(picked: InitItem[], all: InitItem[], how: 'tty' | 'yes}, env);}track('cold_start', { source: how === 'keep' ? 'keep' : 'sessions', outcome: 'kept' });- return { kept, notKept, refused };+ return { kept, notKept, refused, ...(folded.length ? { folded } : {}) };}/* -------------------------------------------------------------------------- */diff --git a/src/init/replay-runs.ts b/src/init/replay-runs.tsindex 49ffad75..5545f4a9 100644--- a/src/init/replay-runs.ts+++ b/src/init/replay-runs.ts@@ -36,6 +36,7 @@ import { claudeTranscript, openPlain } from './plain-file.js';import { tamperedBefore, turnOnly, writeMarkIn } from './replay-tamper.js';import { dayOf, eachLine } from './transcript.js';import type { SkillSource, TypedRef } from './types.js';+import { stepLearnings } from '../skills/follow-learnings.js';/** A session's replay stops at this many runs (4.2 cost control). */export const MAX_REPLAY_RUNS = 200;@@ -366,6 +367,7 @@ export function compileInitSkill(entry: ReplaySheet, prior: ReplaySheet | null,const r = compileRun(entry.sheet, {repoRoot: entry.root, home: env.HOME || homedir(), platform: process.platform, prior: prior?.sheet ?? null, moment: 'repeated',applies: repoKey, now, readSheet: () => null, taken: (n) => nameTaken(n, scope) !== null,+ learnings: stepLearnings({ repoKeys: [...new Set([repoKey, entry.sheet.repoKey])], checkout: entry.root, env }),});if (!r.ok) return { ok: false, why: r.reason, detail: r.detail };if (r.skill.steps.length < 2) return { ok: false, why: 'one-step' };diff --git a/src/init/review-screen.ts b/src/init/review-screen.tsindex 8ca4b1b8..794f74fa 100644--- a/src/init/review-screen.ts+++ b/src/init/review-screen.ts@@ -17,6 +17,7 @@ import type { KeepResult } from './keep.js';import { nameLine } from './name-call.js';import { DRAFT_LINE, KEEP_LINE, RELAY_LINE } from './relay.js';import type { InitItem, InitKind, LookBack } from './types.js';+import { onlyRepeats } from '../skills/follow-learnings.js';export interface ScreenFacts {lookBack: LookBack;@@ -75,8 +76,19 @@ export const INIT_COPY: Record<string, string> = {rLater: 'adding skills and guardrails to the repo comes in a later version',yesAgent: 'found {found}. Kept nothing: an agent ran this. The person picks with trail keep <numbers> after seeing the list, or trail init --look-back in their own terminal',yesScript: 'found {found}. Kept only the preferences (your own words). To pick the rest: trail init --look-back',+ foldHint: 'kept with skill {n}, it goes into that skill as a lesson, since a step of it already does this',+ folded: '· {pref} went into {skill} as a lesson, since a step of it already does that',};+/**+ * Part 7: the skill on this screen a preference only repeats a step of (keep.ts folds it in when both are kept), or+ * null. Only a preference just for the person in this repo, as keep.ts folds.+ */+export function foldTarget(item: InitItem, items: InitItem[]): InitItem | null {+ if (item.kind !== 'preference' || item.scope === 'repo' || item.applies === 'every repo' || !item.title) return null;+ return items.find((s) => s.kind === 'skill' && s.skill?.compiled && onlyRepeats(item.title, s.skill.compiled.steps.map((x) => x.cmd))) ?? null;+}+/** `{x}` filled from `v`. */export function fill(t: string, v: Record<string, string | number>): string {return t.replace(/\{(\w+)\}/g, (m, k: string) => (k in v ? String(v[k]) : m));@@ -194,7 +206,9 @@ export function screenLines(items: InitItem[], state: { cursor: number; open: nuconst desc = item.description ? ` · ${plain(item.description)}` : '';out.push(`${cur} [${item.ticked ? 'x' : ' '}] ${item.n} ${quoted(item)}${desc}`);const ev = item.evidence.map(plain).map((e) => ` ${e.charAt(0).toUpperCase()}${e.slice(1)}.`).join('');- out.push(` ${countSentence(item, facts.repoName)}${ev} · ${scopeWords(item)}`);+ const into = foldTarget(item, items);+ const fold = into ? ` · ${fill(INIT_COPY.foldHint!, { n: into.n })}` : '';+ out.push(` ${countSentence(item, facts.repoName)}${ev} · ${scopeWords(item)}${fold}`);if (state.open === at) for (const l of state.openLines ?? []) out.push(` ${spaced(l)}`);});out.push('');@@ -249,6 +263,7 @@ export function afterKeepLines(r: KeepResult & { how?: 'enter' | 'n' | 'esc' | 'out.push(inRepo ? fill(INIT_COPY.keptMixed!, { k: kept, j: kept - inRepo, r: inRepo }) : fill(INIT_COPY.kept!, { k: kept }));}for (const x of r.refused) out.push(fill(INIT_COPY.refused!, { name: plain(x.item.title) }));+ for (const f of r.folded ?? []) out.push(fill(INIT_COPY.folded!, { pref: quoted(f.item), skill: plain(f.skill) }));if (r.notKept.length) out.push(fill(INIT_COPY.notKept!, { names: r.notKept.map((i) => quoted(i)).join(', '), them: r.notKept.length === 1 ? 'it' : 'them' }));if (facts.skills) out.push(facts.offers === 'off' ? fill(INIT_COPY.offersOff!, { date: dayWords(facts.offersOffAt) || 'an earlier day' }) : INIT_COPY.offersOn!);return out;diff --git a/src/notes/notes.ts b/src/notes/notes.tsindex c6a7e632..ea9c8ed1 100644--- a/src/notes/notes.ts+++ b/src/notes/notes.ts@@ -153,7 +153,7 @@ function rebaseTouch(t: string, checkout: string, here: string): string {}/** Every `.md` in `notesDir` that parses as a note, with touches rebased onto `here`. */-function readNotesIn(notesDir: string, checkout: string, here: string, scope: LearningScope): Note[] {+export function readNotesIn(notesDir: string, checkout: string, here: string, scope: LearningScope): Note[] {let files: string[];try {files = readdirSync(notesDir).filter((f) => f.endsWith(".md"));diff --git a/src/skills/cli-skills.ts b/src/skills/cli-skills.tsindex 0b0398c5..a87cab9f 100644--- a/src/skills/cli-skills.ts+++ b/src/skills/cli-skills.ts@@ -28,6 +28,7 @@ import { runCheckout } from './run-checkout.js';import { forgetLearning, initDraftCommand, lessonCommand, type CliOut } from './cli-skills-1b.js';import { noteAgentForget, type Dropped } from './forget-notice.js';import { draftFoldText, liftRestoreVersion, restoreVersionCommand, updateCommand, versionsLine } from './cli-skills-2.js';+import { stepLearnings } from './follow-learnings.js';/** Seams for tests; production passes nothing. */export interface SkillCliDeps {@@ -202,6 +203,7 @@ function draft(x: Io, runId: string, print: boolean): void {repoRoot: root, home: x.env.HOME || '', platform: process.platform,prior: findPriorSheet(sheet, x.env), applies: sheet.repoKey, now: x.now(), readSheet: (id: string) => readRunSheet(id, x.env),taken: (n: string) => nameTaken(n, scope) !== null,+ learnings: stepLearnings({ repoKeys: [sheet.repoKey], checkout: root, env: x.env }),};// An offer keeps a repeated job; a run with no check (an asked save) is shown the way an ask keeps it.let c = compileRun(sheet, { ...opts, moment: 'repeated' });diff --git a/src/skills/compile-words.ts b/src/skills/compile-words.tsindex 792a8f69..bf0eec65 100644--- a/src/skills/compile-words.ts+++ b/src/skills/compile-words.ts@@ -351,6 +351,8 @@ export function draftText(c: CompiledSkill, sheet: RunSheet): string {// D58 b: what ran elsewhere, so the person sees it before saying yes.for (const e of away.slice(0, 6)) out.push(` elsewhere ${e.cmd} (${e.where})`);if (away.length > 6) out.push(` elsewhere and ${away.length - 6} more`);+ // Part 7: steps that follow the person's learnings rather than the run.+ if (c.followed) out.push(` learnings ${flatLine(c.followed, 400)}`);out.push(` just for you, ${c.meta.applies === 'every repo' ? 'in every repo' : 'in this repo'} · nothing is shared or uploaded`);return out.join('\n');}diff --git a/src/skills/compile.ts b/src/skills/compile.tsindex 45dd7c5f..940b9fd3 100644--- a/src/skills/compile.ts+++ b/src/skills/compile.ts@@ -38,6 +38,7 @@ import { type LoopWait, splitSheet, stripScratchLog } from './compile-split.js';import { answersPrompt, loginFeed } from './answers-prompt.js';import { checkShowsFor, shownVersion, versionShaped, versionTie } from './compile-version.js';import { findWaits } from './compile-waits.js';+import { followAtSave, type StepLearning } from './follow-learnings.js';export { BUILT_IN_NAMES, NAME_RE, askPhrases, draftText, proposeName, refusalWords, type CompileRefusal } from './compile-words.js';@@ -65,6 +66,12 @@ export interface CompileOpts {* it (`askPhrases`: phrases of 2+ words) and from nothing else. Read, never stored beyond those asks.*/askedWith?: string | null;+ /**+ * Part 7: the person's live preferences, decisions and guardrails about commands (`stepLearnings`). A step one of+ * them goes against is written its way when that is safe, else left out, and `followed` says so. Every half of a+ * save passes the same ones, read from disk, so they compile the same skill. Absent: none.+ */+ learnings?: readonly StepLearning[];}class Refused extends Error {@@ -329,6 +336,19 @@ function build(sheet: RunSheet, opts: CompileOpts): CompiledSkill {if (k.items.every((it) => !it.wait && !it.bg && plain(it.text))) refuse('trivial', k.items.map((it) => it.text).join(' ; '));}+ // Part 7: the steps follow the person's learnings about commands; the check can't be left out.+ const follow = followAtSave(k.items.map((it, n) => ({ cmd: found.cmds[n]!, gated: it.gated !== null, isCheck: k.checkIsStep && it.isCheck })), [...(opts.learnings ?? [])]);+ if (follow.refuse) refuse('never-save', follow.refuse);+ if (follow.line) {+ const was = k.items;+ k.items = follow.keep.map(({ i, cmd }) => (cmd === found.cmds[i] ? was[i]! : { ...was[i]!, core: /^\(cd \S+ && (.*)\)$/.exec(cmd)?.[1] ?? cmd }));+ const cmds = follow.keep.map(({ cmd }) => cmd);+ const checkAt = follow.keep.findIndex(({ i }) => k.checkIsStep && was[i]!.isCheck);+ if (checkAt >= 0) found.check = cmds[checkAt]!;+ found.cmds = cmds;+ if (!k.items.length) refuse('no-steps');+ }+// Step 13: name and words.let steps: SkillStep[] = k.items.map((it, n) => ({ n: n + 1, cmd: found.cmds[n]!, gated: it.gated, bg: it.bg, wait: it.wait, from: it.from }));const sourceCalls = k.items.map((it) => it.call);@@ -411,6 +431,7 @@ function build(sheet: RunSheet, opts: CompileOpts): CompiledSkill {helpers: k.helpers, leftOut, ...(k.elsewhere.length ? { elsewhere: elsewhereLines(k.elsewhere, sheet.repoKey, (t) => relativizePaths(cleanText(t, opts.platform), opts.repoRoot, opts.home)) } : {}),...(sheet.joined?.length ? { carried: carriedSteps(sheet, steps) } : {}),source: { runId: sheet.id, commands: sheet.counts.commands, failed: sheet.counts.failed, at: sheet.endedAt },+ ...(follow.line ? { followed: follow.line } : {}),};const text = renderSkillMd(c);const problems = skillProblems(text, name);diff --git a/src/skills/fold.ts b/src/skills/fold.tsindex 577c4d35..0a82bd71 100644--- a/src/skills/fold.ts+++ b/src/skills/fold.ts@@ -26,13 +26,18 @@ import { MAX_RUN_LINES, MAX_STEP_CHARS, gatedKind } from './risk.js';import { parseSkillMd, renderSkillMd } from './skillmd.js';import { refusedAtRecall } from './recall.js';import { rebuildCompiled } from './skill-rebuild.js';-import { printDiff, sizeGate } from './skill-diff.js';+import { FOLD_MAX_CHARS, printDiff, sizeGate } from './skill-diff.js';import { goodName } from './compile-words.js';import { bareCommand, simpleCommands } from '../trace/shell.js';import { sameGatedCommand } from './fold-gated.js';export type FoldPlan =| { op: 'update'; step: number; cmd: SkillStep; why: 'failed-then-worked' }+ /**+ * Part 7: the block showed step `step` the way a live learning says (`follows`: whose, "your preference"), and it+ * worked; `more`: the other steps the same learning changed that ran that way too, changed with it.+ */+ | { op: 'update'; step: number; cmd: SkillStep; why: 'preference'; follows: string; more?: SkillStep[] }| { op: 'extend'; at: number; cmds: SkillStep[]; why: 'lesson' | 'two-uses'; lessonIds: string[] }| { op: 'split'; from: number; to: number; name: string }| { op: 'none'; why: FoldNone };@@ -54,6 +59,11 @@ export interface FoldInput {splitName?: string;/** Whether a skill name is taken (the store's nameTaken): the split's name is never one (review). */taken?: (name: string) => boolean;+ /**+ * Part 7: steps the block showed the way a live learning says rather than as the skill has them (`cmd` with the+ * skill's params, `follows` whose learning it was). An update to that way is offered once it ran and checked out.+ */+ preferred?: Array<{ step: number; cmd: string; follows: string }>;}const MAX_EXTEND = 2;@@ -122,6 +132,23 @@ function planOf(i: FoldInput, base: CompiledSkill): FoldPlan {const { cands: all, matched } = candidates(base, fresh, vals);const cands = all.filter((c) => passedHere(c, i.fid));+ // Part 7: steps the block showed the person's way, that ran that way: the change is from the fresh compile (P4).+ const fv = freshValues(fresh);+ const changes: Array<{ cmd: SkillStep; follows: string }> = [];+ for (const p of i.preferred ?? []) {+ const old = base.steps[p.step - 1];+ if (!old || old.gated || !i.fid.ran.includes(p.step) || (changes.length && changes[0]!.follows !== p.follows)) continue;+ const hit = fresh.steps.find((s) => !s.gated && ranAs(fillParams(p.cmd, vals), fillParams(s.cmd, fv), vals));+ if (!hit) continue;+ const cmd = inSkillTerms(hit.cmd, fresh, base, vals);+ if (cmd === null) return none('new-param');+ if (cmd !== old.cmd) changes.push({ cmd: { ...old, cmd, n: p.step }, follows: p.follows });+ }+ if (changes.length) {+ const [first, ...rest] = changes.sort((a, b) => a.cmd.n - b.cmd.n);+ return { op: 'update', step: first!.cmd.n, cmd: first!.cmd, why: 'preference', follows: first!.follows, ...(rest.length ? { more: rest.map((c) => c.cmd) } : {}) };+ }+// 3. update: a step that failed and was done another way, the same program and verb.for (const c of [...i.fid.changed].sort((a, b) => a.step - b.step)) {const old = base.steps[c.step - 1];@@ -208,7 +235,10 @@ export function planFold(i: FoldInput): FoldPlan {if (plan.op !== 'update' && plan.op !== 'extend') return plan;const next = applyWhy(base, plan);if ('why' in next) return none(next.why);- if (!sizeGate(renderSkillMd(base), renderSkillMd(next.skill)).ok) return none('too-big');+ // Part 7: a change to follow a learning swaps a program in the steps it names and nothing else, so on a small skill+ // it can touch most of the file; only the size in characters holds it back.+ const size = sizeGate(renderSkillMd(base), renderSkillMd(next.skill));+ if (!(plan.op === 'update' && plan.why === 'preference' ? size.chars <= FOLD_MAX_CHARS : size.ok)) return none('too-big');return plan;} catch {return none('no-change');@@ -252,8 +282,12 @@ function applyWhy(base: CompiledSkill, plan: Exclude<FoldPlan, { op: 'none' | 'sif (plan.op === 'update') {const old = steps[plan.step - 1];if (!old || !plan.cmd?.cmd) return { why: 'layout' };- if (base.checkIsStep && old.cmd === base.check) check = plan.cmd.cmd;- steps[plan.step - 1] = { ...plan.cmd };+ for (const next of [plan.cmd, ...(plan.why === 'preference' ? plan.more ?? [] : [])]) {+ const was = steps[next.n - 1];+ if (!was) return { why: 'layout' };+ if (base.checkIsStep && was.cmd === base.check) check = next.cmd;+ steps[next.n - 1] = { ...next };+ }} else {if (!Number.isInteger(plan.at) || plan.at < 0 || plan.at > steps.length || !plan.cmds?.length) return { why: 'layout' };steps.splice(plan.at, 0, ...plan.cmds.map((s) => ({ ...s })));diff --git a/src/skills/follow-learnings.ts b/src/skills/follow-learnings.tsnew file mode 100644index 00000000..8282294d--- /dev/null+++ b/src/skills/follow-learnings.ts@@ -0,0 +1,307 @@+/**+ * Learnings and skills, said once and never against each other (part 7).+ *+ * A person's live preferences, decisions and guardrails are read for what+ * they say about commands (learning-steps.ts, no model), then:+ *+ * - at a skill's save or offer, the steps follow them: a step a learning+ * forbids is written its way when Trail can do that safely, else left+ * out, and the offer names either in one plain line (`followAtSave`);+ * - at recall, a learning that only repeats a step is said once, in the run+ * block, and the prompt's learnings lines leave it out; one that goes+ * against a step wins, and the block marks the step (`recallMarks`,+ * `markLines`). The update offer then proposes the change, with its usual+ * consent (fold.ts, why `preference`).+ *+ * Retired, replaced and held learnings never count (`liveLearnings`), nor+ * one on a teammate's unmerged branch, nor a lesson. Reading fails open:+ * no learnings, nothing changes.+ */+import { readNotesIn, type Note } from '../notes/notes.js';+import { everyRepoLearnings } from '../notes/every-repo.js';+import { EVERY_REPO, learningFileName, liveLearnings, type LearningKind, type Scope } from '../notes/learning-fields.js';+import { repoNotesDir } from '../notes/repo-notes-dir.js';+import { learningsDir } from '../notes/repo-trail.js';+import { flatLine } from '../notes/flatten.js';+import { gatedKind } from './risk.js';+import { neverSave } from './never-save.js';+import { matchSteps, rulesOf, type StepRule } from './learning-steps.js';++export interface StepLearning {+ id: string;+ /** Its file name: one learning wherever it sits, as the session's shown list knows it (`shownFiles`). */+ file: string;+ kind: LearningKind | null;+ scope: Scope;+ /** The learning's words as a line quotes them. */+ quote: string;+ /** The quote is the whole learning and every sentence of it was read: a line that says it leaves nothing out. */+ whole: boolean;+ rules: StepRule[];+}++/** Where a save or a block reads learnings: the run's repo, its checkout's committed ones, and every-repo ones. */+export interface LearningsWhere { repoKeys: string[]; checkout: string; env: NodeJS.ProcessEnv }++export const QUOTE_MAX = 160;+const MARKS_MAX = 3;++/** The words the person and the agent read. No em dashes; never notes, rules or the like (the words test reads these). */+export const FOLLOW_COPY = {+ savedOne: 'Step {n} runs {next} rather than this run\'s {old}, as {whose} "{quote}" says.',+ savedMany: 'Steps {list} follow {whose} "{quote}" rather than this run\'s commands.',+ leftOne: 'Trail left out {old}: it goes against {whose} "{quote}", and Trail can\'t change it safely.',+ leftMany: 'Trail left out {k} steps: they go against {whose} "{quote}", and Trail can\'t change them safely.',+ refuse: 'goes against {whose} "{quote}", and it is the check',+ short: 'Some steps follow your learnings rather than this run; say show me to see them.',+ counts: 'To follow your learnings, Trail {did}; say show me to see them.',+ stepFixed: ' ({whose_s} way; the skill has {old})',+ stepAgainst: ' (against {whose}: see below)',+ wins: '{Whose} wins over the skill: "{quote}". {Steps} {are} written its way; run {them} as shown.',+ against: '{Whose} "{quote}" goes against {steps}: leave {it} out, do that part its way, and tell the person.',+ follows: '{Steps} {follow} {whose}: "{quote}".',+} as const;++const fill = (t: string, v: Record<string, string | number>) => t.replace(/\{(\w+)\}/g, (m, k: string) => (v[k] === undefined ? m : String(v[k])));+const cap = (t: string) => t.charAt(0).toUpperCase() + t.slice(1);+const quoteText = (l: StepLearning) => l.quote.replace(/"/g, "'");+/** A command as a line shows it: one line, at most 60 characters, its single quotes made double, in single quotes. */+export const cmdWords = (cmd: string) => `'${flatLine(String(cmd ?? '').replace(/'/g, '"'), 60)}'`;+const listWords = (ns: number[]) => (ns.length < 2 ? ns.join('') : `${ns.slice(0, -1).join(', ')} and ${ns[ns.length - 1]}`);++const OWNER: Record<Scope, string> = { personal: 'your', repo: "this repo's", team: "your team's" };+/** 'your preference', "this repo's decision", "your team's learning". */+export function whose(l: Pick<StepLearning, 'kind' | 'scope'>): string {+ return `${OWNER[l.scope] ?? 'your'} ${l.kind && l.kind !== 'lesson' ? l.kind : 'learning'}`;+}++/* ------------------------------------------------------------ reading */++/** The lines a learning's commands are read from: its title and body, headings and the tried-and-ruled-out part left out. */+function linesOf(n: Pick<Note, 'title' | 'body'>): string[] {+ const out: string[] = [];+ let skip = false;+ for (const raw of [n.title, ...String(n.body ?? '').split('\n')]) {+ const l = flatLine(raw, 4000);+ const h = /^#{1,6}\s+(.*)$/.exec(l);+ if (h) {+ skip = /tried|ruled out/i.test(h[1]!);+ continue;+ }+ if (l && !skip && !out.includes(l)) out.push(l);+ }+ return out;+}++/** What one learning says about commands; null when it says nothing a step could repeat or go against. */+export function stepLearningOf(n: Pick<Note, 'id' | 'kind' | 'scope' | 'title' | 'body'> & { path?: string }): StepLearning | null {+ if (n.kind === 'lesson') return null;+ const lines = linesOf(n);+ const read = rulesOf(lines.join('\n'));+ if (!read.rules.length) return null;+ const only = lines.length === 1 ? lines[0]! : null;+ const quote = flatLine(only ?? n.title, QUOTE_MAX);+ return { id: n.id, file: n.path ? learningFileName(n.path) : '', kind: n.kind ?? null, scope: n.scope ?? 'repo', quote, whole: read.whole && only !== null && quote === only, rules: read.rules };+}++/** The file names of the learnings a session has shown already (its `injectedNotes`: paths, or a title for one with none). */+export function shownFiles(injected: readonly string[] | undefined): Set<string> {+ return new Set((injected ?? []).map((p) => learningFileName(p)).filter(Boolean));+}++/** The live learnings that say something about commands, for a run in `where`. [] on any read failure. */+export function stepLearnings(where: LearningsWhere): StepLearning[] {+ const notes: Note[] = [];+ const add = (f: () => Note[]) => {+ try { notes.push(...f()); } catch { /* none from there this time */ }+ };+ add(() => everyRepoLearnings(where.env));+ for (const key of [...new Set(where.repoKeys.filter(Boolean))]) {+ const k = key.toLowerCase();+ add(() => readNotesIn(repoNotesDir(key, where.env), '', '', 'personal').filter((n) => !n.applies || n.applies === EVERY_REPO || n.applies === k));+ }+ if (where.checkout) add(() => readNotesIn(learningsDir(where.checkout), where.checkout, where.checkout, 'repo'));+ try {+ const seen = new Set<string>();+ const unique = notes.filter((n) => !seen.has(n.id) && (seen.add(n.id), true));+ return liveLearnings(unique).flatMap((n) => stepLearningOf(n) ?? []);+ } catch {+ return [];+ }+}++/**+ * The learning's words only repeat what the steps do: every sentence read, at least one step repeats it, none goes+ * against it. What init folds into a skill as a lesson (part 7).+ */+export function onlyRepeats(text: string, steps: string[]): boolean {+ const l = stepLearningOf({ id: 'l-000000', kind: 'preference', scope: 'personal', title: text, body: text });+ if (!l || !l.whole) return false;+ const v = matchSteps(l.rules, steps);+ return v.repeats.length > 0 && v.contradicts.length === 0;+}++/* ------------------------------------------------------------ at a save */++export interface SaveItem { cmd: string; gated: boolean; isCheck: boolean }+export interface SaveFollow {+ /** The steps kept, by their index in the input, with the command they keep. */+ keep: Array<{ i: number; cmd: string }>;+ /** The one plain line the offer and the save name it in; '' when nothing changed. */+ line: string;+ /** Why the skill can't be kept: the check itself goes against a learning and can't follow it. */+ refuse: string | null;+}++/** A fix the save or the block may use: a step that can be undone stays one, and nothing the risk rules refuse. */+const safeFix = (fix: string | null, gated: boolean) => (fix && !gated && !gatedKind(fix) && !neverSave(fix) ? fix : null);++/** The first learning that goes against each step, and the step its way when that is safe. */+function against(cmds: string[], gated: boolean[], ls: StepLearning[]): Map<number, { l: StepLearning; fix: string | null }> {+ const out = new Map<number, { l: StepLearning; fix: string | null }>();+ for (const l of ls) {+ for (const c of matchSteps(l.rules, cmds).contradicts) if (!out.has(c.step)) out.set(c.step, { l, fix: safeFix(c.fix, gated[c.step - 1] ?? true) });+ }+ return out;+}++/** The steps as a save keeps them: each one a learning goes against written its way, or left out, and the line that says so. */+export function followAtSave(items: SaveItem[], ls: StepLearning[]): SaveFollow {+ const same: SaveFollow = { keep: items.map((it, i) => ({ i, cmd: it.cmd })), line: '', refuse: null };+ if (!ls.length || !items.length) return same;+ const hit = against(items.map((it) => it.cmd), items.map((it) => it.gated), ls);+ if (!hit.size) return same;+ const keep: SaveFollow['keep'] = [];+ const fixed = new Map<StepLearning, Array<{ n: number; old: string; next: string }>>();+ const left = new Map<StepLearning, string[]>();+ for (const [i, it] of items.entries()) {+ const h = hit.get(i + 1);+ if (!h) {+ keep.push({ i, cmd: it.cmd });+ } else if (h.fix) {+ keep.push({ i, cmd: h.fix });+ fixed.set(h.l, [...(fixed.get(h.l) ?? []), { n: keep.length, old: it.cmd, next: h.fix }]);+ } else if (it.isCheck) {+ return { ...same, refuse: fill(FOLLOW_COPY.refuse, { whose: whose(h.l), quote: flatLine(quoteText(h.l), 80) }) };+ } else {+ left.set(h.l, [...(left.get(h.l) ?? []), it.cmd]);+ }+ }+ const said: string[] = [];+ for (const [l, fs] of fixed) {+ const v = { whose: whose(l), quote: flatLine(quoteText(l), 80) };+ said.push(fs.length === 1 ? fill(FOLLOW_COPY.savedOne, { ...v, n: fs[0]!.n, next: cmdWords(fs[0]!.next), old: cmdWords(fs[0]!.old) })+ : fill(FOLLOW_COPY.savedMany, { ...v, list: listWords(fs.map((f) => f.n)) }));+ }+ for (const [l, olds] of left) {+ const v = { whose: whose(l), quote: flatLine(quoteText(l), 80) };+ said.push(olds.length === 1 ? fill(FOLLOW_COPY.leftOne, { ...v, old: cmdWords(olds[0]!) }) : fill(FOLLOW_COPY.leftMany, { ...v, k: olds.length }));+ }+ const all = said.join(' ');+ const changed = [...fixed.values()].reduce((n, fs) => n + fs.length, 0);+ const dropped = [...left.values()].reduce((n, olds) => n + olds.length, 0);+ const n = (k: number) => (k === 1 ? '1 step' : `${k} steps`);+ const did = [changed ? `changed ${n(changed)}` : '', dropped ? `left out ${n(dropped)}` : ''].filter(Boolean).join(' and ');+ const counts = fill(FOLLOW_COPY.counts, { did });+ return { keep, line: flatLine(all.length <= LINE_ROOM ? all : counts, 400), refuse: null };+}++/** Room an offer's line 1 leaves for the follow line (offer lines are at most 400 characters). */+const LINE_ROOM = 240;+const OFFER_LINE_MAX = 400;++/** An offer's 2 lines with the follow line at the end of line 1 (a shorter one when both don't fit). */+export function withFollowLine(lines: [string, string], followed: string | undefined): [string, string] {+ if (!followed) return lines;+ const both = `${lines[0]} ${followed}`;+ return [both.length <= OFFER_LINE_MAX ? both : flatLine(`${lines[0]} ${FOLLOW_COPY.short}`, OFFER_LINE_MAX), lines[1]];+}++/* ------------------------------------------------------------ at recall */++/** One learning's say in a run block: the steps it repeats, or the steps it goes against (written its way, or to leave out). */+export interface RecallMark {+ l: StepLearning;+ against: boolean;+ steps: number[];+ /** Against: each step's command its way (with the skill's {params}), or null for a step to leave out. */+ fixes: Map<number, string | null>;+}++/**+ * What the live learnings say of a skill's steps, at most 3 learnings. A learning that goes against a step wins over+ * one that repeats it. A repeat is said only for a preference or decision (or a plain learning) the line can quote in+ * full, so leaving it out of the prompt's learnings lines loses nothing, and only once a session: one the session showed+ * already (`shown`, file names: on a file the agent opened, or with an earlier prompt) is not said again. A learning+ * that goes against a step is always marked, since the step is shown its way.+ */+export function recallMarks(steps: Array<{ n: number; cmd: string; gated?: unknown }>, ls: StepLearning[], shown: ReadonlySet<string> = new Set()): RecallMark[] {+ if (!ls.length || !steps.length) return [];+ const cmds = steps.map((s) => s.cmd);+ const hit = against(cmds, steps.map((s) => !!s.gated), ls);+ const out: RecallMark[] = [];+ for (const l of ls) {+ const mine = [...hit].filter(([, h]) => h.l === l).map(([n]) => n);+ if (mine.length) {+ out.push({ l, against: true, steps: mine, fixes: new Map(mine.map((n) => [n, hit.get(n)!.fix])) });+ continue;+ }+ if (!l.whole || (l.kind !== null && l.kind !== 'preference' && l.kind !== 'decision')) continue;+ // Shown this session already (on a file the agent opened, or with an earlier prompt): not said again here.+ if (l.file && shown.has(l.file)) continue;+ const reps = matchSteps(l.rules, cmds).repeats.filter((n) => !hit.has(n));+ if (reps.length) out.push({ l, against: false, steps: reps, fixes: new Map() });+ }+ return out.slice(0, MARKS_MAX);+}++/** The step texts and check as the block shows them: each fix in place of its step (and of the check it is). */+export function withFixes<T extends { steps: Array<{ n: number; cmd: string }>; check: string | null }>(skill: T, marks: RecallMark[]): T {+ const fixes = new Map<number, string>();+ for (const m of marks) for (const [n, f] of m.fixes) if (f) fixes.set(n, f);+ if (!fixes.size) return skill;+ let check = skill.check;+ const steps = skill.steps.map((s) => {+ const f = fixes.get(s.n);+ if (!f) return s;+ if (check !== null && check === s.cmd) check = f;+ return { ...s, cmd: f };+ });+ return { ...skill, steps, check };+}++/** What a marked step's line ends with in the block (`n` is the step, `old` the skill's own command, filled). */+export function stepNote(marks: RecallMark[], n: number, old: string): string {+ const m = marks.find((x) => x.against && x.steps.includes(n));+ if (!m) return '';+ return m.fixes.get(n) ? fill(FOLLOW_COPY.stepFixed, { whose_s: `${whose(m.l)}'s`, old: flatLine(old, 120) }) : fill(FOLLOW_COPY.stepAgainst, { whose: whose(m.l) });+}++/** The lines after a block's steps, one per learning, each quoting it once. */+export function markLines(marks: RecallMark[]): string[] {+ return marks.map((m) => {+ const one = m.steps.length === 1;+ const steps = `${one ? 'step' : 'steps'} ${listWords(m.steps)}`;+ const v = { whose: whose(m.l), Whose: cap(whose(m.l)), quote: quoteText(m.l), steps, Steps: cap(steps) };+ if (!m.against) return fill(FOLLOW_COPY.follows, { ...v, follow: one ? 'follows' : 'follow' });+ const fixed = m.steps.filter((n) => m.fixes.get(n));+ const out = m.steps.filter((n) => !m.fixes.get(n));+ const parts: string[] = [];+ if (fixed.length) {+ const s = `${fixed.length === 1 ? 'Step' : 'Steps'} ${listWords(fixed)}`;+ parts.push(fill(FOLLOW_COPY.wins, { ...v, Steps: s, are: fixed.length === 1 ? 'is' : 'are', them: fixed.length === 1 ? 'it' : 'them' }));+ }+ if (out.length) {+ const s = `${out.length === 1 ? 'step' : 'steps'} ${listWords(out)}`;+ parts.push(fill(FOLLOW_COPY.against, { ...v, steps: s, it: out.length === 1 ? 'it' : 'them' }));+ }+ // Both kinds from one learning: its words once, in the first sentence.+ return parts.length === 2 ? `${parts[0]} ${parts[1]!.replace(/^.+? goes against /, 'It goes against ')}` : parts[0]!;+ });+}++/** The ids of the learnings a block says (its lines are in the block as it went out). */+export function saidIn(block: string, marks: RecallMark[]): string[] {+ const lines = markLines(marks);+ return marks.filter((_, k) => block.includes(lines[k]!)).map((m) => m.l.id);+}diff --git a/src/skills/learning-steps.ts b/src/skills/learning-steps.tsnew file mode 100644index 00000000..f17b2c3c--- /dev/null+++ b/src/skills/learning-steps.ts@@ -0,0 +1,291 @@+/**+ * What a learning says about the commands a skill runs, read without a model:+ * the tool and command preferences a person writes ("use pnpm, not npm",+ * "never run npx prisma db push", "always run make lint before git push",+ * "don't edit _schema.py by hand, run scripts/gen_schema.py"), matched+ * against a step's program and arguments.+ *+ * Precision over recall. A clause counts only when it has one of a few fixed+ * shapes and each command in it is a command for sure: in backticks, or+ * starting with a program Trail knows or a script path, with nothing but+ * arguments after it ("always run the tests" names no command, so it says+ * nothing). Whatever doesn't parse says nothing.+ *+ * Out: repeats (the learning says what a step does) and contradicts (a step+ * does what the learning forbids, or uses the tool it replaces), with the+ * step's command the learning's way when Trail can write it safely (a swap+ * between npm, pnpm, yarn and bun it knows, or a whole command for a whole+ * command), else null. Pure: no disk, no clock.+ */+import { bareCommand, simpleCommands } from '../trace/shell.js';++export interface Cmd { prog: string; args: string[] }+export type StepRule =+ | { t: 'swap'; use: Cmd; not: Cmd }+ | { t: 'never'; cmd: Cmd }+ | { t: 'never-edit'; file: string }+ | { t: 'always'; cmd: Cmd }+ | { t: 'before'; first: Cmd; then: Cmd };++/** `whole`: every sentence of the text read as rules, so a line that quotes it in full leaves nothing out. */+export interface ReadRules { rules: StepRule[]; whole: boolean }++export interface StepVerdict {+ repeats: number[];+ /** `fix`: the step's command the learning's way (its folder kept), or null when Trail can't write it safely. */+ contradicts: Array<{ step: number; fix: string | null }>;+}++/** Programs a command phrase may start with when it is not in backticks. */+const KNOWN = new Set(`npm npx pnpm pnpx yarn bun bunx deno node tsx ts-node python python3 pip pip3 pipx uv poetry pytest tox nox make cmake+cargo rustc go gradle gradlew mvn ant git gh docker podman kubectl helm terraform tofu ansible rg grep sed awk jq curl wget brew ruby bundle+rake rails gem php composer dotnet swift xcodebuild jest vitest mocha playwright tsc eslint prettier biome ruff black flake8 mypy pylint isort+pre-commit nx turbo lerna vite webpack next prisma alembic flask uvicorn gunicorn psql mysql sqlite3 aws gcloud az vercel netlify fly flyctl+heroku firebase wrangler supabase just task`.split(/\s+/));+/** Words that end a command phrase: English, never an argument. */+const STOP = new Set(`a an the to for when before after instead rather than not over by hand it them this that here there in on with so+because if unless first always never every time please then and or anymore again locally directly manually yourself any my your our their+of is are be was were tests test-suite suite`.split(/\s+/));+const SCRIPT = /^(?:\.{0,2}\/)?(?:[\w.-]+\/)+[\w.-]+$|^[\w-][\w.-]*\.(?:py|sh|bash|js|mjs|cjs|ts|rb|pl)$/;+const FILE = /^(?:\.{0,2}\/)?(?:[\w.-]+\/)*[\w-][\w.-]*\.[A-Za-z0-9]{1,8}$|^(?:\.{0,2}\/)?(?:[\w.-]+\/)+[\w.-]+$/;+const ARG = /^[\w@./:=+,%{}-]+$/;+const INTERPRETERS = new Set(['python', 'python3', 'node', 'bash', 'sh', 'zsh', 'ruby', 'perl', 'tsx', 'ts-node']);+const EDITORS = new Set(['vim', 'vi', 'nvim', 'nano', 'emacs', 'code', 'ed']);+const PMS = new Set(['npm', 'pnpm', 'yarn', 'bun']);+const MAX_SENTENCE = 240;+const MAX_TEXT = 2000;++const BT = '\u0001';+const P = '(.+?)';+const RUN = String.raw`(?:use|run|call)`;+const NOT = String.raw`(?:don'?t|do not|never|avoid)`;+const EDIT = String.raw`(?:hand[- ]?edit|edit|modify|change|touch|write to)`;+const BY_HAND = String.raw`(?:\s+(?:by hand|manually|directly|yourself))?`;+const TAIL = String.raw`(?:\s+(?:here|in this repo|anymore|any more|again|instead|first|always|every time))*`;+const re = (s: string) => new RegExp(`^${s}$`, 'i');++/** One phrase as a command, or null when any word of it isn't one. Backticked text (`\u0001n\u0001`) is the person's own command. */+function cmdOf(phrase: string, ticks: string[]): Cmd | null {+ const p = phrase.trim().replace(/^["']|["']$/g, '').trim();+ const tick = new RegExp(`^${BT}(\\d+)${BT}$`).exec(p);+ const words = (tick ? ticks[Number(tick[1])] ?? '' : p).trim().split(/\s+/).filter(Boolean);+ if (!words.length || words.length > 8) return null;+ const [prog, ...args] = words;+ const known = KNOWN.has(prog!) || SCRIPT.test(prog!);+ if (!(tick ? ARG.test(prog!) : known)) return null;+ if (!args.every((a) => ARG.test(a) && (tick || !STOP.has(a.toLowerCase())))) return null;+ return { prog: plainPath(prog!), args };+}++function fileOf(phrase: string, ticks: string[]): string | null {+ const p = phrase.trim().replace(/^["']|["']$/g, '').trim();+ const tick = new RegExp(`^${BT}(\\d+)${BT}$`).exec(p);+ const f = (tick ? ticks[Number(tick[1])] ?? '' : p).trim();+ return FILE.test(f) ? plainPath(f) : null;+}++const plainPath = (p: string) => p.replace(/^\.\//, '');++type Shape = { re: RegExp; make: (m: RegExpExecArray, t: string[]) => StepRule[] | null };+const both = <T>(a: T | null, b: T | null): [T, T] | null => (a && b ? [a, b] : null);++/** Shapes a whole sentence can have (the ones with a comma of their own come first). */+const SENTENCE: Shape[] = [+ // "use pnpm, not npm", "run make test instead of pytest", "prefer rg over grep"+ { re: re(String.raw`(?:always\s+)?(?:use|run|prefer)\s+${P}\s*,?\s+(?:not|never|and not|instead of|rather than|over)\s+(?:using\s+|running\s+)?${P}${TAIL}`),+ make: (m, t) => {+ const f = /^(?:hand[- ]?)?(?:editing|changing|modifying|touching)\s+(.+?)(?:\s+(?:by hand|manually|directly))?$/i.exec(m[2]!);+ if (f) {+ const c = cmdOf(m[1]!, t);+ const file = fileOf(f[1]!, t);+ return c && file ? [{ t: 'always', cmd: c }, { t: 'never-edit', file }] : null;+ }+ const p = both(cmdOf(m[1]!, t), cmdOf(m[2]!, t));+ return p ? [{ t: 'swap', use: p[0], not: p[1] }] : null;+ } },+ { re: re(String.raw`prefer\s+${P}\s+to\s+${P}`), make: (m, t) => {+ const p = both(cmdOf(m[1]!, t), cmdOf(m[2]!, t));+ return p ? [{ t: 'swap', use: p[0], not: p[1] }] : null;+ } },+ // "don't use npm, use pnpm"+ { re: re(String.raw`${NOT}\s+(?:use|run)\s+${P}\s*[,;:]?\s+(?:but\s+)?(?:use|run)\s+${P}${TAIL}`), make: (m, t) => {+ const p = both(cmdOf(m[2]!, t), cmdOf(m[1]!, t));+ return p ? [{ t: 'swap', use: p[0], not: p[1] }] : null;+ } },+ // "don't edit _schema.py by hand, run scripts/gen_schema.py"+ { re: re(String.raw`${NOT}\s+${EDIT}\s+${P}${BY_HAND}\s*[,;:]?\s+(?:but\s+|instead\s+)*${RUN}\s+${P}${TAIL}`), make: (m, t) => {+ const file = fileOf(m[1]!, t);+ const c = cmdOf(m[2]!, t);+ return file && c ? [{ t: 'never-edit', file }, { t: 'always', cmd: c }] : null;+ } },+ // "always run make lint before git push", "run lint before pushing"+ { re: re(String.raw`(?:always\s+)?run\s+${P}\s+(?:before|ahead of|prior to)\s+(?:you\s+)?(?:run\s+|running\s+)?${P}`), make: (m, t) => {+ const p = both(cmdOf(m[1]!, t), cmdOf(m[2]!, t));+ return p ? [{ t: 'before', first: p[0], then: p[1] }] : null;+ } },+ // "before git push, always run make lint"+ { re: re(String.raw`before\s+(?:you\s+)?(?:run\s+|running\s+)?${P}\s*,?\s+(?:always\s+)?run\s+${P}(?:\s+first)?`), make: (m, t) => {+ const p = both(cmdOf(m[2]!, t), cmdOf(m[1]!, t));+ return p ? [{ t: 'before', first: p[0], then: p[1] }] : null;+ } },+];++/** Shapes one clause can have once a sentence is cut at its commas. */+const CLAUSE: Shape[] = [+ { re: re(String.raw`${NOT}\s+(?:ever\s+)?(?:use|run|using|running|call)\s+${P}${TAIL}`), make: (m, t) => {+ const c = cmdOf(m[1]!, t);+ return c ? [{ t: 'never', cmd: c }] : null;+ } },+ { re: re(String.raw`${NOT}\s+${EDIT}\s+${P}${BY_HAND}`), make: (m, t) => {+ const file = fileOf(m[1]!, t);+ return file ? [{ t: 'never-edit', file }] : null;+ } },+ { re: re(String.raw`(?:always\s+)?${RUN}\s+${P}${TAIL}`), make: (m, t) => {+ const c = cmdOf(m[1]!, t);+ return c ? [{ t: 'always', cmd: c }] : null;+ } },+];++function shaped(s: string, shapes: Shape[], ticks: string[]): StepRule[] | null {+ for (const sh of shapes) {+ const m = sh.re.exec(s);+ if (!m) continue;+ const r = sh.make(m, ticks);+ if (r) return r;+ }+ return null;+}++/** The rules a learning's text says, and whether every sentence of it was read. */+export function rulesOf(text: string): ReadRules {+ const ticks: string[] = [];+ const raw = String(text ?? '').slice(0, MAX_TEXT).replace(/[‘’]/g, "'").replace(/[“”]/g, '"')+ .replace(/`([^`\n]{1,200})`/g, (_, c: string) => `${BT}${ticks.push(c) - 1}${BT}`);+ const sentences = raw.split(/\n+|(?<=[.!?;])\s+/)+ .map((s) => s.replace(/^\s*(?:[-*·]|\d+[.)])\s+/, '').replace(/^please,?\s+/, '').replace(/[\s.!;:]+$/, '').trim()).filter(Boolean);+ const rules: StepRule[] = [];+ let whole = sentences.length > 0;+ for (const s of sentences) {+ if (s.length > MAX_SENTENCE) { whole = false; continue; }+ const one = shaped(s, SENTENCE, ticks);+ if (one) { rules.push(...one); continue; }+ const parts = s.split(/\s*,\s*|\s+and then\s+|\s+then\s+/).filter(Boolean);+ const read = parts.map((c) => shaped(c, CLAUSE, ticks));+ if (read.some((r) => r === null)) whole = false;+ for (const r of read) if (r) rules.push(...r);+ }+ return { rules, whole: whole && rules.length > 0 };+}++/* ----------------------------------------------------------- the steps */++interface Simple { prog: string; args: string[]; text: string }++/** A step's folder (`(cd api && ...)`) and the rest. */+function inFolder(cmd: string): { dir: string | null; core: string } {+ const m = /^\(cd (\S+) && (.*)\)$/.exec(cmd.trim());+ return m ? { dir: m[1]!, core: m[2]! } : { dir: null, core: cmd.trim() };+}++function simplesOf(cmd: string): Simple[] {+ return simpleCommands(inFolder(cmd).core).flatMap((text) => {+ const words = bareCommand(text).split(/\s+/).filter(Boolean).map((w) => w.replace(/^(["'])(.*)\1$/, '$2'));+ if (!words.length || words[0] === 'cd') return [];+ const [prog, ...args] = words;+ const out: Simple[] = [{ prog: plainPath(prog!), args, text }];+ // `python scripts/gen.py` is also the script run on its own.+ const at = args.findIndex((a) => !a.startsWith('-'));+ if (INTERPRETERS.has(prog!) && at >= 0 && SCRIPT.test(args[at]!)) out.push({ prog: plainPath(args[at]!), args: args.slice(at + 1), text });+ return out;+ });+}++const samePath = (a: string, b: string) => a === b || (b.includes('/') && b.endsWith(`/${a}`)) || (a.includes('/') && a.endsWith(`/${b}`));+const positional = (args: string[]) => args.filter((a) => !a.startsWith('-'));+const flags = (args: string[]) => args.filter((a) => a.startsWith('-'));++/** The simple command runs `c`: the same program, `c`'s arguments first in the same order, and every flag `c` names. */+function runs(s: Simple, c: Cmd): boolean {+ if (!(s.prog === c.prog || ((SCRIPT.test(s.prog) || SCRIPT.test(c.prog)) && samePath(s.prog, c.prog)))) return false;+ const want = positional(c.args);+ const have = positional(s.args);+ return want.every((w, i) => have[i] === w) && flags(c.args).every((f) => s.args.includes(f));+}++/** The simple command writes `file`: an in-place edit, an editor, a copy or move onto it, or a redirect into it. */+function edits(s: Simple, file: string): boolean {+ const hits = (a: string) => samePath(plainPath(a), file);+ if ((s.prog === 'sed' || s.prog === 'perl') && s.args.some((a) => /^-[a-zA-Z]*i/.test(a))) return s.args.some(hits);+ if (EDITORS.has(s.prog)) return s.args.some(hits);+ if (['cp', 'mv', 'install', 'tee'].includes(s.prog)) return s.args.length > 0 && hits(s.args[s.args.length - 1]!);+ return [...s.text.matchAll(/(?:^|[^<>&\d])\d?>>?\|?\s*([^\s&|;<>]+)/g)].some((m) => hits(m[1]!));+}++const anyRuns = (cmd: string, c: Cmd) => simplesOf(cmd).some((s) => runs(s, c));++/** `npm test` as pnpm, yarn or bun runs it; null for anything else (a flag, a sub-command Trail doesn't know the twin of). */+function pmTwin(args: string[], to: string): string[] | null {+ const [sub, ...rest] = args;+ // `bun test` is bun's own test runner, not the package's script: bun runs the script with `bun run test`.+ if ((sub === 'test' || sub === 'start') && rest.length === 0) return to === 'bun' ? ['run', sub] : [sub];+ if (sub === 'run' && rest.length >= 1 && /^[\w:.-]+$/.test(rest[0]!) && rest.slice(1).every((a) => ARG.test(a))) return ['run', ...rest];+ if ((sub === 'install' || sub === 'i') && rest.length === 0) return ['install'];+ // yarn's flag for a locked install changed between versions: no twin.+ if (sub === 'ci' && rest.length === 0) return to === 'npm' ? ['ci'] : to === 'yarn' ? null : ['install', '--frozen-lockfile'];+ return null;+}++/** The step the swap's way, or null when Trail can't write it safely: one simple command, nothing piped or chained. */+function swapFix(cmd: string, use: Cmd, not: Cmd): string | null {+ const { dir, core } = inFolder(cmd);+ // Nothing piped, chained, redirected or substituted, and no env prefix or wrapper: the words are the whole command.+ if (simpleCommands(core).length !== 1 || /[<>`$|&;]/.test(core.replace(/\{\w+\}/g, ''))) return null;+ if (core.replace(/\s+/g, ' ').trim() !== bareCommand(core)) return null;+ const s = simplesOf(core)[0];+ if (!s) return null;+ let next: string[] | null = null;+ if (!use.args.length && !not.args.length && PMS.has(use.prog) && PMS.has(not.prog) && s.prog === not.prog) {+ const twin = pmTwin(s.args, use.prog);+ next = twin ? [use.prog, ...twin] : null;+ } else if (s.prog === not.prog && s.args.join(' ') === not.args.join(' ') && (use.args.length || not.args.length)) {+ next = [use.prog, ...use.args];+ }+ if (!next) return null;+ const text = next.join(' ');+ return dir ? `(cd ${dir} && ${text})` : text;+}++/**+ * Each rule against the steps (step `n` is `steps[n - 1]`, with its {params}). A step that does what a rule forbids+ * is a contradiction, whatever another rule says of it; one that does what a rule says, a repeat.+ */+export function matchSteps(rules: StepRule[], steps: string[]): StepVerdict {+ const repeats = new Set<number>();+ const against = new Map<number, string | null>();+ // Two rules that would write one step two ways write it neither way.+ const contradict = (n: number, fix: string | null) => {+ if (!against.has(n)) against.set(n, fix);+ else if (against.get(n) !== fix) against.set(n, null);+ };+ for (const r of rules) {+ steps.forEach((cmd, i) => {+ const n = i + 1;+ if (r.t === 'swap') {+ if (anyRuns(cmd, r.not)) contradict(n, swapFix(cmd, r.use, r.not));+ else if (anyRuns(cmd, r.use)) repeats.add(n);+ } else if (r.t === 'never') {+ if (anyRuns(cmd, r.cmd)) contradict(n, null);+ } else if (r.t === 'never-edit') {+ if (simplesOf(cmd).some((s) => edits(s, r.file))) contradict(n, null);+ } else if (r.t === 'always') {+ if (anyRuns(cmd, r.cmd)) repeats.add(n);+ } else if (anyRuns(cmd, r.then)) {+ const first = steps.findIndex((x, j) => j < i && anyRuns(x, r.first));+ if (first >= 0) repeats.add(first + 1);+ else if (!anyRuns(cmd, r.first)) contradict(n, null);+ }+ });+ }+ for (const n of against.keys()) repeats.delete(n);+ return { repeats: [...repeats].sort((a, b) => a - b), contradicts: [...against].sort((a, b) => a[0] - b[0]).map(([step, fix]) => ({ step, fix })) };+}diff --git a/src/skills/offer-moment.ts b/src/skills/offer-moment.tsindex a1322588..71873380 100644--- a/src/skills/offer-moment.ts+++ b/src/skills/offer-moment.ts@@ -45,6 +45,7 @@ import { repoKnown } from '../trace/known-repo.js';import type { FoldPlanner } from './offer-update.js';import type { Fired, Settled } from './credit.js';import { useFor, type DialectUse } from '../trace/dialect.js';+import { stepLearnings, withFollowLine } from './follow-learnings.js';const SAME_LINE_MS = 5000;@@ -236,6 +237,7 @@ export function compileOffered(sheet: RunSheet, st: SkillSessionState, ctx: OfferepoRoot: root, home: env.HOME || homedir(), platform: process.platform,prior: findPriorSheet(sheet, env), moment: 'repeated', applies: sheet.repoKey, now: ctx.now, readSheet: read,taken: (n) => nameTaken(n, { ...scope, checkout: root || scope.checkout }) !== null,+ learnings: stepLearnings({ repoKeys: [sheet.repoKey], checkout: root, env }),});}@@ -277,11 +279,11 @@ export function repeatedOfferDue(i: OfferInput): OfferDue {const joined = joinCarriedSheet(sheet, read);const ownDates = rep.dates === rep.sessionDays;const seen = { n: ownDates ? rep.dates : rep.sessionDays, unit: ownDates ? 'day' as const : 'time' as const };- const lines = offerLines({+ const lines = withFollowLine(offerLines({job, check: hit, ordinal: seen.n, unit: seen.unit,commands: joined.counts.commands, failed: joined.counts.failed, steps: stepsTotal(compiled.skill), where: 'this repo',branches: job === 'ship' ? stableBranches(joined.calls, joined.jobWords) : [],- });+ }), compiled.skill.followed);return {due: true,offer: {diff --git a/src/skills/offer-repair.ts b/src/skills/offer-repair.tsindex 2543f94f..85e4d7c2 100644--- a/src/skills/offer-repair.ts+++ b/src/skills/offer-repair.ts@@ -28,6 +28,7 @@ import { lessonRefused, lessonSha, LESSON_MAX, wallLessons } from './lessons.js'import { checkLine, ordinalWord } from './offer-words.js';import { newOfferId, offerBudget } from './offers.js';import { compileOffered, skillSha, type OfferDue, type OfferInput } from './offer-moment.js';+import { withFollowLine } from './follow-learnings.js';/** The words of a moment-3 offer (4.13, J06) and of its saved wall lesson (4.15). Said as they are. */export const REPAIR_COPY: Record<string, string> = {@@ -182,10 +183,10 @@ export function repairOfferDue(i: OfferInput): OfferDue | { due: false; why: Whyconst branches = joined && run.job === 'ship' ? stableBranches(joined.calls, joined.jobWords) : [];const nth = seen.epochs + 1;const where = lessonWhere(r.cls);- const lines = repairLines({+ const lines = withFollowLine(repairLines({checkLine: hit ? checkLine(hit, branches) : 'Done: the check passed.', nth, days: daysSince(seen.firstAt, now), cls: r.cls, delta: r.delta,program, as: asSkill ? 'skill' : 'lesson', steps: asSkill ? stepsTotal(compiled.skill) : 1, lessonText: lesson, where,- });+ }), asSkill && compiled.ok ? compiled.skill.followed : undefined);const offer: PendingOffer = {offerId: newOfferId(), moment: 'repaired', runId: run.id, name: asSkill ? compiled.skill.name : r.cls, key, lines, channel,shownAt: channel === 'post-tool' ? null : now.toISOString(), showMe: false, yes: null, typedAfter: [], repo: run.repoKey,diff --git a/src/skills/offer-update.ts b/src/skills/offer-update.tsindex 551fdc26..1e8a961e 100644--- a/src/skills/offer-update.ts+++ b/src/skills/offer-update.ts@@ -122,11 +122,13 @@ export function updateOfferDue(i: OfferInput): OfferDue | { due: false; why: Whyconst r = i.plan.replan(skillId, run.id, plan.op, env, o);if (!r || (r.plan && r.plan.op !== plan.op)) return { due: false, why: 'replan' };const vals = block.params ?? {};- const cmds = plan.op === 'update' ? [fillParams(plan.cmd.cmd, vals)] : plan.cmds.map((c) => fillParams(c.cmd, vals));+ const more = plan.op === 'update' && plan.why === 'preference' ? plan.more ?? [] : [];+ const cmds = plan.op === 'update' ? [plan.cmd, ...more].map((c) => fillParams(c.cmd, vals)) : plan.cmds.map((c) => fillParams(c.cmd, vals));const lessonIds = plan.op === 'extend' && plan.why === 'lesson' ? plan.lessonIds : [];const lessonDate = fi.lessons.find((l) => lessonIds.includes(l.id))?.at;const lines = updateLines({- op: plan.op, why: plan.why, check, name: ref.name, job: run.job ?? skill.meta.job ?? 'job', at: plan.op === 'update' ? plan.step : plan.at,+ op: plan.op, why: plan.why, ...(plan.op === 'update' && plan.why === 'preference' ? { follows: plan.follows, steps: [plan.step, ...more.map((c) => c.n)] } : {}),+ check, name: ref.name, job: run.job ?? skill.meta.job ?? 'job', at: plan.op === 'update' ? plan.step : plan.at,cmds, changes: runLinesChanged(r.base, r.next), ...(lessonDate ? { lessonDate } : {}), handEdited: r.handEdited,});return {diff --git a/src/skills/offer-words-2.ts b/src/skills/offer-words-2.tsindex 8db5b575..4f756723 100644--- a/src/skills/offer-words-2.ts+++ b/src/skills/offer-words-2.ts@@ -27,6 +27,8 @@ import { notSaved } from './offer-words.js';/** Moment 5 (4.7). `line2*` end with the keys the person answers with. */export const UPDATE_COPY = {line1Update: '{check} This time step {step} of {name} failed and {cmds} worked instead.',+ line1Preference: '{check} This time {steps} of {name} ran as {cmds}, the way {follows} says.',+ line2Preference: 'Change {steps} of {name} to match? {size} (yes / show me / no)',line1Extend: '{check} This time {name} also needed {cmds} {where}.',line1Split: '{check} This time {name} ran only steps {from} to {to}, as it did last time.',line2Lesson: 'Fold your {date} lesson into {name} as {steps}? {size} (yes / show me / no)',@@ -77,7 +79,10 @@ const pairOf = (a: string, b: string): [string, string] => [flatLine(a, LINE_MAXexport interface UpdateFacts {op: 'update' | 'extend' | 'split';- why?: 'failed-then-worked' | 'lesson' | 'two-uses';+ why?: 'failed-then-worked' | 'lesson' | 'two-uses' | 'preference';+ /** Part 7, why 'preference': whose learning the steps followed ("your preference"), and every step it changes. */+ follows?: string;+ steps?: number[];/** The job's check as 1a's `checkLine` says it ("Published 0.22.4: npm shows it."). */check: string;name: string;@@ -105,6 +110,13 @@ export function updateLines(f: UpdateFacts): [string, string] {return pairOf(fill(C.line1Split, { check, name, ...s }), fill(C.line2Split, { ...s, name, new: one(f.split.name) }));}if (f.op === 'update') {+ if (f.why === 'preference' && f.follows) {+ const ns = f.steps?.length ? f.steps : [f.at];+ const steps = ns.length === 1 ? `step ${ns[0]}` : `steps ${both(ns.map(String))}`;+ const all = f.cmds.map(quoted);+ const ran = all.length > 2 ? `${all.slice(0, 2).join(', ')} and ${all.length - 2} more` : both(all);+ return pairOf(fill(C.line1Preference, { check, name, steps, cmds: ran, follows: one(f.follows) }), fill(C.line2Preference, { steps, name, size }));+ }return pairOf(fill(C.line1Update, { check, name, step: f.at, cmds }), fill(C.line2Update, { step: f.at, name, size }));}const n = Math.min(2, Math.max(1, f.cmds.length));diff --git a/src/skills/runblock.ts b/src/skills/runblock.tsindex fce26920..98119e3f 100644--- a/src/skills/runblock.ts+++ b/src/skills/runblock.ts@@ -32,6 +32,7 @@ import { probePassWords, type ProbeResult } from './probes.js';import { isGuardrailLesson, lessonLines, lessonRefused, readLessons, type Lesson } from './lessons.js';import { goneAnchors, outOfDateLine, type Anchor } from './anchors.js';import { WIDE_SCAN_MS } from './anchors-wide.js';+import { markLines, stepNote, withFixes, type RecallMark } from './follow-learnings.js';export { runProbes, probePassWords, readyProbes, PROBE_BUDGET_MS, type ProbeResult, type ProbeOpts, type ProbeGit } from './probes.js';@@ -76,8 +77,8 @@ function gatedNote(steps: number[], canAsk: boolean): string {/** What a tests or query check shows by default: "step n passing" already says it. */const PLAIN_SHOWS = new Set(['the tests pass', 'rows come back']);-function checkText(c: Candidate, values: Record<string, string>): { text: string; shows: string | null } | null {- const s = c.skill;+function checkText(c: Candidate, values: Record<string, string>, skill: Pick<ParsedSkill, 'check' | 'checkShows' | 'meta'> = c.skill): { text: string; shows: string | null } | null {+ const s = skill;if (!s.check) return null;const shows = s.checkShows ? prose(fillParams(s.checkShows, values)) : s.meta['check-tool'] ? 'READY' : null;return { text: flat(fillParams(s.check, values)), shows };@@ -99,8 +100,10 @@ function goneOf(c: Candidate, scan: boolean, until?: number): Anchor[] {* anchors gone where the candidate was found) opens it with the out-of-date line (4.18). Both count toward 1,200:* lessons are the second thing cut, oldest first; guardrail-kind lessons and the out-of-date line never are.*/-export function runBlock(c: Candidate, ctx: { values: Record<string, string>; notes: string[]; probes: ProbeResult[]; canAsk: boolean; header: 'job' | 'compact'; lastFail: { step: number; at: string } | null; lessons?: Lesson[]; gone?: Anchor[]; anchorDeadline?: number }): string {- const s = c.skill;+export function runBlock(c: Candidate, ctx: { values: Record<string, string>; notes: string[]; probes: ProbeResult[]; canAsk: boolean; header: 'job' | 'compact'; lastFail: { step: number; at: string } | null; lessons?: Lesson[]; gone?: Anchor[]; anchorDeadline?: number; marks?: RecallMark[] }): string {+ // Part 7: a step the person's learning goes against shows its way (or is marked to leave out); never cut.+ const marks = ctx.marks ?? [];+ const s = withFixes(c.skill, marks);const name = nameOf(c);const ood = outOfDateLine(name, ctx.gone ?? goneOf(c, ctx.header === 'job', ctx.anchorDeadline));const opening = ood ? [`[trail] ${ood}`] : [];@@ -125,12 +128,13 @@ export function runBlock(c: Candidate, ctx: { values: Record<string, string>; noconst steps: string[] = [];for (const st of s.steps) {const note = st.wait ? ' (a wait: run it in the background if it may take over 2 minutes)' : st.bg ? ' (in the background)' : '';- steps.push(` ${st.n} ${flat(fillParams(st.cmd, ctx.values))}${note}`);+ const own = c.skill.steps.find((x) => x.n === st.n)?.cmd ?? st.cmd;+ steps.push(` ${st.n} ${flat(fillParams(st.cmd, ctx.values))}${note}${stepNote(marks, st.n, fillParams(own, ctx.values))}`);const g = groups.find((x) => x.steps[x.steps.length - 1] === st.n);if (g) steps.push(gatedNote(g.steps, ctx.canAsk));}- const chk = checkText(c, ctx.values);+ const chk = checkText(c, ctx.values, s);let check: string | null = null;if (chk) {const asStep = [...s.steps].reverse().find((x) => x.cmd === s.check);@@ -142,9 +146,10 @@ export function runBlock(c: Candidate, ctx: { values: Record<string, string>; noconst fails = s.ifFails.filter((l) => !neverSave(l)).slice(0, 2).map((l) => ` If it fails: ${prose(l)}`);const notes = ctx.notes.map((n) => ` ${prose(n)}`);const footer = ` If a step fails, fix that step and say so. End with "Used skill ${name}".`;+ const follow = markLines(marks).map((l) => ` ${prose(l, 400)}`);const build = (o: { notes: boolean; fails: number; passed: boolean; lessons: number }) => [- ...opening, header, ...failed, ...(o.passed && passed ? [passed] : []), ...before, ...checkFirst, ...steps, ...(check ? [check] : []),+ ...opening, header, ...failed, ...(o.passed && passed ? [passed] : []), ...before, ...checkFirst, ...steps, ...(check ? [check] : []), ...follow,...fails.slice(0, o.fails), ...(o.notes ? notes : []), footer, ...guardLines, ...lessonRest.slice(lessonRest.length - o.lessons),].join('\n');const all = lessonRest.length;diff --git a/src/skills/save-gate.ts b/src/skills/save-gate.tsindex a06368bf..62449a25 100644--- a/src/skills/save-gate.ts+++ b/src/skills/save-gate.ts@@ -38,6 +38,7 @@ import { DENY, isSplitOffer, tamperDeny, verifySave, type SaveVerdict } from './import { heldRunId, nameTaken, readSkillsStateSafe } from './save-store.js';import { hookError } from '../claude/skills-hook-util.js';import { codexSandboxRefusal } from './codex-sandbox.js';+import { stepLearnings } from './follow-learnings.js';export { parseSkillsAdd, parseSkillsLesson, SAVE_GATE_RE, SKILLS_ADD_RE, SKILLS_LESSON_RE, type SkillsAddCmd, type SkillsLessonCmd } from './save-parse.js';export { DENY, verifySave, type SaveVerdict } from './save-verify.js';@@ -213,9 +214,11 @@ export function savedLines(c: CompiledSkill, n: number, endedAt: string, asked:const count = apart ? `${steps(n - 1)} and its check` : steps(n);const later = asked === 'repo' ? ' Saving it for the whole repo comes later, so for now it\'s just yours.': asked === 'team' ? ' Saving it for the team comes later, so for now it\'s just yours.' : '';+ // Part 7: steps that follow the person's learnings rather than the run, said in the same one line.+ const follow = c.followed ? ` ${flatLine(c.followed, 400)}` : '';return [- `✓ saved ${name}, ${where} · ${count}, each one ran here ${when}`,- `Tell the person what Trail kept: Saved ${name}, ${where}: ${count}, each one ran here ${when}. Next time you ask ${ask}, I start from them.${later} See them: trail skills show ${name} · undo: trail forget ${name}`,+ `✓ saved ${name}, ${where} · ${count}, each one ran here ${when}${follow ? ` ·${follow}` : ''}`,+ `Tell the person what Trail kept: Saved ${name}, ${where}: ${count}, each one ran here ${when}.${follow} Next time you ask ${ask}, I start from them.${later} See them: trail skills show ${name} · undo: trail forget ${name}`,];}@@ -263,6 +266,7 @@ function holdUnbacked(cmd: SkillsAddCmd, env: NodeJS.ProcessEnv, now: Date, why:const c = compileRun(sheet, {repoRoot: root, home: env.HOME || '', platform: process.platform, now,readSheet: (id) => readRunSheet(id, env), name: cmd.name, moment: 'asked', applies: sheet.repoKey, taken: (n) => n !== cmd.name && nameTaken(n, scope) !== null,+ learnings: stepLearnings({ repoKeys: [sheet.repoKey], checkout: root, env }),});if (!c.ok) return fail(`trail · not saved: ${refusalWords(c.reason, c.detail)}.`);try {diff --git a/src/skills/save-verify.ts b/src/skills/save-verify.tsindex 29452f08..459d68b1 100644--- a/src/skills/save-verify.ts+++ b/src/skills/save-verify.ts@@ -42,6 +42,7 @@ import { skillSha } from './offer-moment.js';import { hostFacts } from './host-facts.js';import { offerLinesOf } from './offer-lines.js';import { runCheckout } from './run-checkout.js';+import { stepLearnings } from './follow-learnings.js';export interface SaveVerdict {deny?: string; // set: refuse, nothing saved@@ -340,6 +341,7 @@ export function verifySave(cmd: SkillsAddCmd | null, ctx: GateCtx, st: SkillSessapplies: c.consent === 'asked' && sr?.scope === 'every repo' ? 'every repo' : own.repoKey,// The asked name is free here so compile keeps it; step 9 says where it is taken.taken: (n) => n !== cmd.name && nameTaken(n, scope) !== null,+ learnings: stepLearnings({ repoKeys: [own.repoKey], checkout: root, env }),});if (!compiled.ok) return denied(`${NOT}${refusalWords(compiled.reason, compiled.detail)}.`, pick(c));const skill = compiled.skill;diff --git a/src/skills/types.ts b/src/skills/types.tsindex e88e715d..18ba39fe 100644--- a/src/skills/types.ts+++ b/src/skills/types.ts@@ -346,3 +346,18 @@ export interface UpdateReceipt {at: string;usedAt: string | null;}++/* -------------------------------------------------------------------------- */+/* Part 7: learnings and skills said once. As above, optional fields in a */+/* further declaration of the interface they widen. */+/* -------------------------------------------------------------------------- */++export interface CompiledSkill {+ /** The one line saying which steps follow the person's learnings rather than the run, or were left out. */+ followed?: string;+}++export interface HookOut {+ /** UserPromptSubmit: ids of the learnings the run block already says, left out of this prompt's learnings lines. */+ said?: string[];+}diff --git a/src/skills/update-plan.ts b/src/skills/update-plan.tsindex a6744b99..f07ceab9 100644--- a/src/skills/update-plan.ts+++ b/src/skills/update-plan.ts@@ -33,6 +33,8 @@ import { getSkillState } from './state.js';import { listAllPersonal, nameTaken } from './store.js';import { MAX_SKILL_BYTES } from './store-fs.js';import { nextVersion } from './versions.js';+import { fillParams } from './params.js';+import { recallMarks, stepLearnings, whose } from './follow-learnings.js';export type PlanInj = Pick<SkillInjection, 'params' | 'steps' | 'at' | 'check'>;/** `inj`: the block's injection (Stop passes the live one); else it is found in `st`, else in the run's session file. */@@ -151,8 +153,11 @@ function gather(skillId: string, runId: string, env: NodeJS.ProcessEnv, o: PlanOtry {if (fresh) splitName = proposeName(sheet, fresh.steps, (n) => nameTaken(n, scope) !== null);} catch { /* no split name: no split */ }+ // Part 7: the steps the block showed the way a live learning says, as it showed them (the injection's steps).+ const preferred = inj ? recallMarks(skill.steps, stepLearnings({ repoKeys: [sheet.repoKey], checkout: repoRoot, env })).flatMap((m) =>+ [...m.fixes].flatMap(([step, cmd]) => (cmd && inj.steps?.[step - 1] === fillParams(cmd, inj.params ?? {}) ? [{ step, cmd, follows: whose(m.l) }] : []))) : [];const input: FoldInput = {- skill, text, fresh, fid, inj: { params: inj?.params ?? {} }, taken: (n) => nameTaken(n, scope) !== null,+ skill, text, fresh, fid, inj: { params: inj?.params ?? {} }, taken: (n) => nameTaken(n, scope) !== null, ...(preferred.length ? { preferred } : {}),earlierExtraShas: earlier.map((u) => u.extraShas ?? []), lessons: readLessons(ref.dir),earlierRan: earlier.map((u) => u.stepsRan), earlierChecks: earlier.map((u) => u.check), base, ...(splitName ? { splitName } : {}),};diff --git a/test/claude-journeys-learnings.test.ts b/test/claude-journeys-learnings.test.tsnew file mode 100644index 00000000..f0208e19--- /dev/null+++ b/test/claude-journeys-learnings.test.ts@@ -0,0 +1,196 @@+/**+ * Part 7 through the real hooks: learnings and skills never repeat or+ * contradict each other in what the agent hears. A preference that only+ * repeats a step is said once, in the run block (the schema example's+ * "don't edit _schema.py by hand, run scripts/gen_schema.py"); one that+ * goes against a step wins at the offer, at the save and at recall, where+ * the update offer then proposes the change. Made-up repo and prompts only.+ */+import { test } from 'node:test';+import assert from 'node:assert/strict';+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { renderNote } from '../src/notes/notes.js';+import {+ agentRuns, at, box, cli, done, finish, hook, lastCli, one, promptHook, sayOfferLines, session, skillsKept, stateOf, testsJob, type Box, type Session,+} from './claude-skills-journey-fixtures.js';++const ctxOf = (out: Record<string, any> | null): string => out?.hookSpecificOutput?.additionalContext ?? '';+const count = (text: string, part: string) => text.split(part).length - 1;++/** A learning of the person's own for acme/shop, as `trail note --personal` or init's keep writes one. */+function learning(b: Box, file: string, title: string, kind: 'preference' | 'decision', id: string, touches: string[] = []): void {+ const dir = join(b.trail, 'repos', 'github.com', 'acme', 'shop', 'notes');+ mkdirSync(dir, { recursive: true });+ // One that lists a file comes on that file's open; a standing one is left to the session-start list.+ writeFileSync(join(dir, file), renderNote({ title, body: title, author: '', date: '2026-10-15', touches, id, kind, applies: 'github.com/acme/shop', ...(touches.length ? {} : { standing: true }) }));+}++/** The agent opens `file` in the checkout: PostToolUse on a Read, where on-touch learnings come. */+const opens = async (s: Session, iso: string, file: string) =>+ ctxOf(one(await hook(s, 'tool-savings', { hook_event_name: 'PostToolUse', tool_name: 'Read', tool_input: { file_path: join(s.b.repo, file) }, tool_response: 'x' }, iso)));++const skillFile = (b: Box, name: string) => readFileSync(join(b.trail, 'skills', name, 'SKILL.md'), 'utf8');++/** The schema is generated, then the suite runs: the schema example's job. */+async function schemaTests(s: Session, day: number): Promise<void> {+ await promptHook(s, at(day, 0), 'run the test suite');+ await agentRuns(s, at(day, 10), 'python scripts/gen_schema.py', () => ({ out: 'wrote src/_schema.py' }));+ await agentRuns(s, at(day, 20), 'pytest -q', () => ({ out: 'Exit code 1\n1 failed, 11 passed in 0.41s', failed: true }));+ await agentRuns(s, at(day, 30), 'pytest -q', () => ({ out: '12 passed in 0.40s' }));+}++/** Kept because the person asked: "save this as a skill" after the job. */+async function askedSave(s: Session, day: number, said: string): Promise<string> {+ await finish(s, day, said);+ const ctx = ctxOf(one(await promptHook(s, at(day, 60), 'save this as a skill')));+ const [, name, runId] = /trail skills add (\S+) --run (\S+)\./.exec(ctx) ?? [];+ assert.ok(name, ctx);+ const command = `trail skills add ${name} --run ${runId}`;+ await agentRuns(s, at(day, 70), command, cli(s.b, at(day, 70), command));+ assert.equal(lastCli()?.exit, 0, lastCli()?.lines.join('\n'));+ return name!;+}++test('the schema example: the preference and the skill step that runs gen_schema are said once, in the run block', async () => {+ const b = box('p7-once');+ // The prompt hook's learnings are read for the checkout the session is in, under trail.+ Object.assign(b.env, { CLAUDE_PROJECT_DIR: b.repo, TRAIL_INVOKED_AS: 'trail' });+ try {+ const pref = "don't edit _schema.py by hand, run scripts/gen_schema.py";+ learning(b, '2026-10-15-schema.md', pref, 'preference', 'l-5c4e3a21');+ const s1 = session(b);+ await schemaTests(s1, 20);+ const name = await askedSave(s1, 20, 'All 12 tests pass.');+ assert.match(skillFile(b, name), /python scripts\/gen_schema\.py/, 'a repeat changes nothing at the save');+ assert.doesNotMatch(lastCli()!.lines.join('\n'), /follow/, 'and the save line has nothing to say about it');++ const s = session(b);+ const ctx = ctxOf(one(await promptHook(s, at(22, 5), 'run the test suite, I touched the _schema file')));+ assert.match(ctx, new RegExp(`\\[trail\\] Skill ${name} fits`), ctx);+ assert.equal(count(ctx, pref), 1, `one mention, not two:\n${ctx}`);+ assert.match(ctx, /\n {2}Step 1 follows your preference: "don't edit _schema\.py by hand, run scripts\/gen_schema\.py"\.\n/);+ assert.doesNotMatch(ctx, /learnings earlier sessions left on this/, 'no learnings lines repeat it');++ // Without the skill the same prompt still brings the preference as a learning: the dedupe is the block's, not a loss.+ const b2 = box('p7-once-b');+ Object.assign(b2.env, { CLAUDE_PROJECT_DIR: b2.repo, TRAIL_INVOKED_AS: 'trail' });+ try {+ learning(b2, '2026-10-15-schema.md', pref, 'preference', 'l-5c4e3a21');+ const alone = ctxOf(one(await promptHook(session(b2), at(22, 5), 'run the test suite, I touched the _schema file')));+ assert.equal(count(alone, pref), 1, alone);+ assert.match(alone, /learnings earlier sessions left on this/);+ } finally {+ done(b2);+ }+ } finally {+ done(b);+ }+});++test('the schema example with a learning on file open: whichever comes first, the other does not say it again', async () => {+ const b = box('p7-touch');+ Object.assign(b.env, { CLAUDE_PROJECT_DIR: b.repo, TRAIL_INVOKED_AS: 'trail' });+ try {+ const pref = "don't edit _schema.py by hand, run scripts/gen_schema.py";+ learning(b, '2026-10-15-schema.md', pref, 'preference', 'l-5c4e3a21', ['src/_schema.py']);+ const s1 = session(b);+ await schemaTests(s1, 20);+ const name = await askedSave(s1, 20, 'All 12 tests pass.');++ // The block says it first: opening the file later brings nothing more.+ const s = session(b);+ const ctx = ctxOf(one(await promptHook(s, at(22, 5), 'run the test suite, I touched the _schema file')));+ assert.match(ctx, new RegExp(`\\[trail\\] Skill ${name} fits`), ctx);+ assert.equal(count(ctx, pref), 1, ctx);+ assert.match(ctx, /Step 1 follows your preference/);+ assert.doesNotMatch(await opens(s, at(22, 20), 'src/_schema.py'), /_schema\.py by hand/, 'the block already said it');++ // The file is opened first: the block keeps its steps and drops the follows line.+ const t = session(b);+ assert.match(await opens(t, at(23, 0), 'src/_schema.py'), /_schema\.py by hand/, 'on-touch shows it, as before');+ const later = ctxOf(one(await promptHook(t, at(23, 10), 'run the test suite')));+ assert.match(later, new RegExp(`\\[trail\\] Skill ${name} fits`), later);+ assert.match(later, /python scripts\/gen_schema\.py/);+ assert.equal(count(later, pref), 0, `already shown on file open:\n${later}`);+ } finally {+ done(b);+ }+});++test('pnpm vs npm: the offer names it in one line, the yes keeps the steps the preference\'s way', async () => {+ const b = box('p7-offer');+ try {+ learning(b, '2026-10-15-pnpm.md', 'use pnpm, not npm', 'preference', 'l-7d2f9a10');+ for (const day of [28, 29]) {+ const t = session(b);+ await testsJob(t, day, { failedFirst: true });+ assert.equal(await finish(t, day, 'All 12 tests pass.'), null, `day ${day}: no offer yet`);+ }+ const t = session(b);+ await testsJob(t, 30, { failedFirst: true });+ const blocked = await finish(t, 30, 'All 12 tests pass.');+ assert.equal(blocked?.decision, 'block', JSON.stringify(blocked));+ const offer = stateOf(t).pendingOffer!;+ assert.match(offer.lines[0]!, / Steps 1, 2 and 3 follow your preference "use pnpm, not npm" rather than this run's commands\.$/, offer.lines[0]);+ assert.match(offer.lines[1]!, /^Keep the 3 that worked as a skill/);+ assert.ok(offer.lines[0]!.length <= 400);+ assert.ok(blocked!.reason.includes(offer.lines[0]!), 'the agent says the line as Trail wrote it');++ await sayOfferLines(t, 30, offer.lines);+ const yes = ctxOf(one(await promptHook(t, at(30, 80), 'yes')));+ const command = `trail skills add ${offer.name} --run ${offer.runId}`;+ assert.ok(yes.includes(command), yes);+ await agentRuns(t, at(30, 82), command, cli(b, at(30, 82), command));+ assert.equal(lastCli()?.exit, 0, lastCli()?.lines.join('\n'));+ assert.deepEqual(skillsKept(b), [offer.name]);+ const file = skillFile(b, offer.name);+ assert.match(file, /pnpm install --frozen-lockfile/);+ assert.match(file, /pnpm run build/);+ assert.match(file, /pnpm test/);+ assert.doesNotMatch(file, /(?:^|[\s`(])npm (?:ci|test|run)\b/m, file);+ assert.match(lastCli()!.lines[1]!, /Steps 1, 2 and 3 follow your preference "use pnpm, not npm" rather than this run's commands\./);+ } finally {+ done(b);+ }+});++test('pnpm vs npm at recall: the preference wins in the block, and the update offer proposes the change', async () => {+ const b = box('p7-recall');+ try {+ // Kept on Oct 20 with npm, before the person said they use pnpm.+ const s1 = session(b);+ await testsJob(s1, 20, { failedFirst: true });+ const name = await askedSave(s1, 20, 'All 12 tests pass.');+ assert.match(skillFile(b, name), /npm test/);+ learning(b, '2026-10-21-pnpm.md', 'use pnpm, not npm', 'preference', 'l-7d2f9a10');++ const s = session(b);+ const ctx = ctxOf(one(await promptHook(s, at(22, 0), 'run the test suite')));+ assert.match(ctx, new RegExp(`^\\[trail\\] Skill ${name} fits`), ctx);+ assert.match(ctx, /\n {2}1 pnpm install --frozen-lockfile \(your preference's way; the skill has npm ci\)\n/, ctx);+ assert.match(ctx, /\n {2}3 pnpm test \(your preference's way; the skill has npm test\)\n/);+ assert.match(ctx, /\n {2}Your preference wins over the skill: "use pnpm, not npm"\. Steps 1, 2 and 3 are written its way; run them as shown\.\n/);+ const inj = stateOf(s).injected.at(-1)!;+ assert.deepEqual(inj.steps, ['pnpm install --frozen-lockfile', 'pnpm run build', 'pnpm test'], 'credit reads the steps as the block showed them');+ assert.equal(inj.check, 'pnpm test');++ // The agent runs them as shown; the suite passes.+ await agentRuns(s, at(22, 10), 'pnpm install --frozen-lockfile', () => ({ out: 'Done in 3.1s' }));+ await agentRuns(s, at(22, 15), 'pnpm run build', () => ({ out: 'built in 2.1s' }));+ await agentRuns(s, at(22, 30), 'pnpm test', () => ({ out: 'Tests: 12 passed, 12 total' }));+ const stop = await finish(s, 22, `All 12 tests pass.\nUsed skill ${name}`);+ assert.equal(stop?.decision, 'block', JSON.stringify(stop));+ const offer = stateOf(s).pendingOffer!;+ assert.equal(offer.moment, 'update');+ assert.equal(offer.fold?.op, 'update');+ assert.deepEqual(offer.lines, [+ `Tests pass (12 passed). This time steps 1, 2 and 3 of ${name} ran as 'pnpm install --frozen-lockfile', 'pnpm run build' and 1 more, the way your preference says.`,+ `Change steps 1, 2 and 3 of ${name} to match? 3 line changes. (yes / show me / no)`,+ ]);+ assert.match(offer.fold!.proposalSha, /^[0-9a-f]{16}$/, 'pinned to the text a yes would write, as every update offer is');+ assert.match(skillFile(b, name), /npm test/, 'nothing changes before the yes');+ } finally {+ done(b);+ }+});diff --git a/test/init-fold-lessons.test.ts b/test/init-fold-lessons.test.tsnew file mode 100644index 00000000..496b243e--- /dev/null+++ b/test/init-fold-lessons.test.ts@@ -0,0 +1,120 @@+/**+ * Part 7 at init: a preference that only repeats a step of a skill the person+ * keeps on the same screen goes into that skill as a lesson, not listed+ * twice. Each kept item keeps its own consent: the fold happens only when the+ * person kept both, and only for a preference just for them in this repo.+ * The schema example's words; made-up repo only.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { existsSync, readdirSync } from "node:fs";+import { spawnSync } from "node:child_process";+import { join } from "node:path";+import { keepItems } from "../src/init/keep.js";+import { afterKeepLines, foldTarget, screenLines } from "../src/init/review-screen.js";+import { repoPlace } from "../src/notes/home.js";+import { repoNotesDir } from "../src/notes/repo-notes-dir.js";+import { readLessons } from "../src/skills/lessons.js";+import { runBlock } from "../src/skills/runblock.js";+import { recallMarks, stepLearnings } from "../src/skills/follow-learnings.js";+import { compiled } from "./skills-store-fixtures.js";+import { cand } from "./skills-recall-fixtures.js";+import { factsOf, prefCandidate, projectTranscript, skillCandidate, withHome } from "./init-screen-fixtures.js";+import { typed as typedLine } from "./trace-fixtures.js";+import type { InitItem } from "../src/init/types.js";++const PREF = "don't edit _schema.py by hand, run scripts/gen_schema.py";+const NOW = new Date("2026-10-22T10:00:00Z");++function repoIn(home: string, env: NodeJS.ProcessEnv): { dir: string; repoKey: string } {+ const dir = join(home, "syncsvc");+ spawnSync("mkdir", ["-p", dir]);+ spawnSync("git", ["init", "-q"], { cwd: dir });+ // A remote, so the key is short wherever the temp folder is (a local key from a deep TMPDIR is not a folder name).+ spawnSync("git", ["remote", "add", "origin", "[email protected]:acme/syncsvc.git"], { cwd: dir });+ return { dir, repoKey: repoPlace(dir, env).key };+}++const runTests = () => compiled("run-tests", { job: "tests", asks: "run the tests", params: undefined, check: "pytest -q", "check-shows": undefined }, {+ title: "Run the tests", description: "Runs the tests from the steps that worked on Oct 2. Use when asked to run the tests.",+ steps: [+ { n: 1, cmd: "python scripts/gen_schema.py", gated: null, bg: false, wait: false, from: ["toolu_01"] },+ { n: 2, cmd: "pytest -q", gated: null, bg: false, wait: false, from: ["toolu_02"] },+ ],+ check: "pytest -q", checkShows: null, checkIsStep: true, params: [],+});++function items(home: string, repoKey: string, pref: { line?: string; applies?: string } = {}): InitItem[] {+ const { refs } = projectTranscript(home, [typedLine("run the tests"), typedLine(pref.line ?? PREF)]);+ return [+ { ...skillCandidate("i-1f0e2a9c41", runTests()), applies: repoKey, key: `${repoKey}|job:tests`, n: 1, title: "run-tests", description: "" },+ { ...prefCandidate(refs[1]!), applies: pref.applies ?? repoKey, n: 2, title: pref.line ?? PREF, description: "" },+ ];+}++const prefFiles = (env: NodeJS.ProcessEnv, repoKey: string) => [join(env.TRAIL_HOME!, "learnings"), repoNotesDir(repoKey, env)]+ .flatMap((d) => (existsSync(d) ? readdirSync(d) : []));++test("the schema example: kept together, the preference goes into run-tests as a lesson, and the agent hears it once", async () => {+ await withHome("p7-fold", ({ home, env }) => {+ const place = repoIn(home, env);+ const all = items(home, place.repoKey);+ // The screen says so before the keep, on the preference's own line.+ const screen = screenLines(all, { cursor: 0, open: null }, factsOf());+ assert.ok(screen.some((l) => l.endsWith("· kept with skill 1, it goes into that skill as a lesson, since a step of it already does this")), screen.join("\n"));++ const r = keepItems(all, all, "tty", env, NOW, place);+ assert.deepEqual(r.kept.map((i) => i.n), [1, 2]);+ assert.deepEqual(r.folded?.map((f) => [f.item.n, f.skill]), [[2, "run-tests"]]);+ assert.deepEqual(prefFiles(env, place.repoKey), [], "no learning of its own: it is a lesson on the skill");+ const lessons = readLessons(join(env.TRAIL_HOME!, "skills", "run-tests"));+ assert.deepEqual(lessons.map((l) => [l.text, l.at]), [[PREF, "2026-07-03"]]);+ const after = afterKeepLines({ ...r, how: "enter" }, factsOf());+ assert.ok(after.includes(`· "${PREF.replace(/"/g, "'")}" went into run-tests as a lesson, since a step of it already does that`), after.join("\n"));++ // What the agent hears when the skill comes back: the lesson, once, and no learning says it again.+ const c = cand(runTests(), { lastWorked: "2026-10-02" });+ c.ref.dir = join(env.TRAIL_HOME!, "skills", "run-tests");+ const marks = recallMarks(c.skill.steps, stepLearnings({ repoKeys: [place.repoKey], checkout: place.dir, env }));+ assert.deepEqual(marks, []);+ const block = runBlock(c, { values: {}, notes: [], probes: [], canAsk: true, header: "job", lastFail: null, gone: [], marks });+ assert.equal(block.split(PREF).length - 1, 1, block);+ });+});++test("each item keeps its own consent: the preference alone is kept as a preference, the skill alone gets no lesson", async () => {+ await withHome("p7-fold-own", ({ home, env }) => {+ const place = repoIn(home, env);+ const all = items(home, place.repoKey);+ const onlyPref = keepItems([all[1]!], all, "tty", env, NOW, place);+ assert.equal(onlyPref.folded, undefined);+ assert.equal(prefFiles(env, place.repoKey).length, 1, "kept as its own learning");+ });+ await withHome("p7-fold-skill", ({ home, env }) => {+ const place = repoIn(home, env);+ const all = items(home, place.repoKey);+ const onlySkill = keepItems([all[0]!], all, "tty", env, NOW, place);+ assert.equal(onlySkill.folded, undefined);+ assert.deepEqual(readLessons(join(env.TRAIL_HOME!, "skills", "run-tests")), []);+ });+});++test("never folded: a preference for every repo, one added to the repo, one that says more than the step, or one against it", async () => {+ await withHome("p7-fold-not", ({ home, env }) => {+ const place = repoIn(home, env);+ const every = items(home, place.repoKey, { applies: "every repo" });+ assert.equal(foldTarget(every[1]!, every), null);+ const repo = items(home, place.repoKey);+ repo[1] = { ...repo[1]!, scope: "repo" };+ assert.equal(foldTarget(repo[1]!, repo), null);+ const more = items(home, place.repoKey, { line: "run scripts/gen_schema.py, then tell me what changed" });+ assert.equal(foldTarget(more[1]!, more), null);+ const against = items(home, place.repoKey, { line: "never run pytest, use make test" });+ assert.equal(foldTarget(against[1]!, against), null);+ // The transcript the items point into holds the last line written: build them again for the keep.+ const again = items(home, place.repoKey, { line: "run scripts/gen_schema.py, then tell me what changed" });+ const r = keepItems(again, again, "tty", env, NOW, place);+ assert.equal(r.folded, undefined);+ assert.equal(prefFiles(env, place.repoKey).length, 1);+ });+});diff --git a/test/skills-follow-learnings.test.ts b/test/skills-follow-learnings.test.tsnew file mode 100644index 00000000..d62a554b--- /dev/null+++ b/test/skills-follow-learnings.test.ts@@ -0,0 +1,223 @@+/**+ * Part 7: learnings and skills never repeat or contradict each other in what+ * the agent hears. Which learnings count (live ones only), how a save+ * follows them and names it in one line, how a run block says each once,+ * and how the update offer proposes the change. Made-up acme/shop only.+ */+process.env.TZ = "UTC";+import { after, test } from "node:test";+import assert from "node:assert/strict";+import { mkdirSync, writeFileSync } from "node:fs";+import { join } from "node:path";+import { compileRun, type CompileOpts } from "../src/skills/compile.js";+import { skillSha } from "../src/skills/offer-moment.js";+import { parseSkillMd, renderSkillMd } from "../src/skills/skillmd.js";+import { callKind } from "../src/trace/checks.js";+import { renderNote, type Note } from "../src/notes/notes.js";+import { writeEveryRepo } from "../src/notes/every-repo.js";+import { repoNotesDir } from "../src/notes/repo-notes-dir.js";+import { runBlock } from "../src/skills/runblock.js";+import {+ followAtSave, markLines, onlyRepeats, recallMarks, saidIn, stepLearningOf, stepLearnings, withFixes, withFollowLine, type StepLearning,+} from "../src/skills/follow-learnings.js";+import type { RunCall, RunSheet } from "../src/trace/types.js";+import { cand } from "./skills-recall-fixtures.js";+import { box, SHOP } from "./skills-store-fixtures.js";+import { rmSync } from "node:fs";++const homes: string[] = [];+after(() => { for (const h of homes) rmSync(h, { recursive: true, force: true }); });++let seq = 0;+const call = (cmd: string, o: Partial<RunCall> = {}): RunCall => {+ seq++;+ return { id: `toolu_f${seq}`, at: new Date(Date.UTC(2026, 9, 27, 10, 0, 0) + seq * 20_000).toISOString(), cmd, key: SHOP, cwd: "", bg: false, failed: false,+ isError: false, kind: callKind(cmd, "tests"), src: { use: seq * 1000, result: seq * 1000 + 400 }, ...o };+};+/** The test suite, the way the person's agent ran it: a failed run first, then install, build and the passing suite. */+function testsSheet(cmds = ["npm ci", "npm run build"], check = "npm test"): RunSheet {+ const calls = [call(check, { failed: true, isError: true, errorLine: "Tests: 1 failed" }), ...cmds.map((c) => call(c)),+ call(check, { check: { family: "tests", passed: true, facts: { passedCount: 12 } } })];+ return {+ v: 1, id: "r-1027-7c1d", session: "e76b4ca7f1a0", repoKey: SHOP, branch: "main", host: "claude", tier: "A", epoch: 0,+ startedAt: calls[0]!.at, endedAt: calls.at(-1)!.at, job: "tests", jobWords: ["test"], sharedWords: [], promptParams: {}, calls,+ checkIndex: calls.length - 1, checked: true, end: "done", counts: { commands: calls.length, failed: 1, toolCalls: calls.length, edits: 0 }, helpers: [], skillId: null,+ };+}+const OPTS: CompileOpts = { repoRoot: "/home/dev/shop", home: "/home/dev", platform: "linux", moment: "repeated", applies: SHOP, taken: () => false, name: "run-tests" };+const learning = (title: string, o: Partial<Note> = {}): StepLearning => stepLearningOf({ id: "l-1a2b3c4d", kind: "preference", scope: "personal", title, body: title, ...o })!;+const PNPM = learning("use pnpm, not npm");+const SCHEMA = learning("don't edit _schema.py by hand, run scripts/gen_schema.py");++function compiled(sheet: RunSheet, ls: StepLearning[] = []) {+ const r = compileRun(sheet, { ...OPTS, learnings: ls });+ if (!r.ok) assert.fail(`refused ${r.reason}: ${r.detail}`);+ return r.skill;+}++/* ------------------------------------------------------------ which learnings count */++function note(dir: string, file: string, title: string, o: Partial<Note> = {}): void {+ mkdirSync(dir, { recursive: true });+ writeFileSync(join(dir, file), renderNote({ title, author: "", date: "2026-10-20", touches: [], body: title, id: "l-00000000", ...o }));+}++test("only live learnings count: retired, replaced, held and lesson ones never do, nor another repo's", () => {+ const b = box("follow-live");+ homes.push(b.home);+ const mine = repoNotesDir(SHOP, b.env);+ note(mine, "a.md", "use pnpm, not npm", { id: "l-aaaaaaa1", kind: "preference", applies: SHOP });+ note(mine, "b.md", "never run npx prisma db push", { id: "l-aaaaaaa2", kind: "decision", status: "retired" });+ note(mine, "c.md", "use yarn, not npm", { id: "l-aaaaaaa3", kind: "preference", date: "2026-10-01" });+ note(mine, "d.md", "use bun, not npm", { id: "l-aaaaaaa4", kind: "preference", date: "2026-10-02", replaces: "l-aaaaaaa3" });+ note(mine, "e.md", "don't use npx", { id: "l-aaaaaaa5", kind: "preference", status: "held" });+ note(mine, "f.md", "never run make deploy", { id: "l-aaaaaaa6", kind: "lesson" });+ note(mine, "g.md", "never run make clean", { id: "l-aaaaaaa7", kind: "preference", applies: "github.com/acme/other" });+ note(mine, "h.md", "The staging database is read-only on Fridays.", { id: "l-aaaaaaa8", kind: "decision" });+ note(join(b.checkout, ".trail", "learnings"), "r.md", "always run make lint before git push", { id: "l-bbbbbbb1", kind: "decision" });+ writeEveryRepo({ title: "run `pytest -q` instead of `npm test`", body: "run `pytest -q` instead of `npm test`", author: "", date: "2026-10-20", kind: "preference" }, "pref-pytest.md", b.env);+ const got = stepLearnings({ repoKeys: [SHOP], checkout: b.checkout, env: b.env });+ assert.deepEqual(got.map((l) => [l.quote, l.kind, l.scope]).sort(), [+ ["always run make lint before git push", "decision", "repo"],+ ["run `pytest -q` instead of `npm test`", "preference", "personal"],+ ["use bun, not npm", "preference", "personal"],+ ["use pnpm, not npm", "preference", "personal"],+ ]);+ // Nothing to read is no learning, never an error.+ assert.deepEqual(stepLearnings({ repoKeys: ["github.com/acme/none"], checkout: "", env: { HOME: b.home, TRAIL_HOME: join(b.home, "nowhere") } }), []);+});++test("a learning's tried-and-ruled-out part is never read as what to do", () => {+ const l = stepLearningOf({ id: "l-1", kind: undefined, scope: "repo", title: "Test setup", body: "## Decided\nuse pnpm, not npm\n## Tried and ruled out\nuse yarn instead of pnpm" });+ assert.deepEqual(l?.rules, [{ t: "swap", use: { prog: "pnpm", args: [] }, not: { prog: "npm", args: [] } }]);+ assert.equal(l?.whole, false, "the quote is the title, not the whole learning");+});++/* ------------------------------------------------------------ at a save */++test("pnpm vs npm at a save: the steps follow the preference, the check too, and one line says so", () => {+ const sheet = testsSheet();+ const plain = compiled(sheet);+ assert.deepEqual(plain.steps.map((s) => s.cmd), ["npm ci", "npm run build", "npm test"]);+ assert.equal(plain.followed, undefined);+ const c = compiled(sheet, [PNPM]);+ assert.deepEqual(c.steps.map((s) => s.cmd), ["pnpm install --frozen-lockfile", "pnpm run build", "pnpm test"]);+ assert.equal(c.check, "pnpm test");+ assert.equal(c.checkIsStep, true);+ assert.equal(c.meta.needs, "pnpm");+ assert.deepEqual(c.steps.map((s) => s.from), plain.steps.map((s) => s.from), "each step still points at the call it was copied from");+ assert.equal(c.followed, 'Steps 1, 2 and 3 follow your preference "use pnpm, not npm" rather than this run\'s commands.');+ // The same learnings give the same skill: both halves of a save agree on what the yes was to.+ assert.equal(skillSha(compiled(sheet, [PNPM])), skillSha(c));+ assert.notEqual(skillSha(c), skillSha(plain));+ const back = parseSkillMd(renderSkillMd(c), c.name)!;+ assert.deepEqual(back.steps.map((s) => s.cmd), c.steps.map((s) => s.cmd));+});++test("a step that can't follow safely is left out, and the line says which and why", () => {+ const c = compiled(testsSheet(["npm ci", "npx prisma db push", "npm run build"]), [learning("never run npx prisma db push", { kind: "decision" })]);+ assert.deepEqual(c.steps.map((s) => s.cmd), ["npm ci", "npm run build", "npm test"]);+ assert.equal(c.followed, "Trail left out 'npx prisma db push': it goes against your decision \"never run npx prisma db push\", and Trail can't change it safely.");+ // The check itself can't be left out: no skill.+ const r = compileRun(testsSheet(), { ...OPTS, learnings: [learning("never run npm test", { scope: "repo" })] });+ assert.equal(r.ok, false);+ assert.match(!r.ok ? r.detail : "", /^goes against this repo's preference "never run npm test", and it is the check$/);+});++test("a learning that only repeats a step changes nothing at a save", () => {+ const c = compiled(testsSheet(["python scripts/gen_schema.py", "npm run build"]), [SCHEMA]);+ assert.deepEqual(c.steps.map((s) => s.cmd), ["python scripts/gen_schema.py", "npm run build", "npm test"]);+ assert.equal(c.followed, undefined);+});++test("the offer names it at the end of line 1; line 2 is the question as always", () => {+ const lines: [string, string] = ["Tests pass (12 passed). That's the 3rd day I've worked out the tests from scratch (5 commands this time, 1 failed).", "Keep the 3 that worked as a skill, just for you in this repo? (yes / show me / no)"];+ const f = 'Steps 1, 2 and 3 follow your preference "use pnpm, not npm" rather than this run\'s commands.';+ assert.deepEqual(withFollowLine(lines, f), [`${lines[0]} ${f}`, lines[1]]);+ assert.deepEqual(withFollowLine(lines, undefined), lines);+ const long = withFollowLine(lines, "x".repeat(300));+ assert.equal(long[0], `${lines[0]} Some steps follow your learnings rather than this run; say show me to see them.`);+ assert.ok(long[0].length <= 400);+});++test("followAtSave keeps a gated step as it is: it never rewrites a step that can't be undone", () => {+ const f = followAtSave([{ cmd: "npm run build", gated: false, isCheck: false }, { cmd: "npm publish --access public", gated: true, isCheck: false }], [PNPM]);+ assert.deepEqual(f.keep, [{ i: 0, cmd: "pnpm run build" }]);+ // Both sentences are too long for an offer's line 1 together: the counts instead.+ assert.equal(f.line, "To follow your learnings, Trail changed 1 step and left out 1 step; say show me to see them.");+ const short = learning("use bun, not npm");+ assert.equal(followAtSave([{ cmd: "npm test", gated: false, isCheck: false }, { cmd: "npm pack", gated: false, isCheck: false }], [short]).line,+ "Step 1 runs 'bun run test' rather than this run's 'npm test', as your preference \"use bun, not npm\" says. Trail left out 'npm pack': it goes against your preference \"use bun, not npm\", and Trail can't change it safely.");+});++/* ------------------------------------------------------------ at recall */++const skillOf = (cmds: string[]) => cand(compiled(testsSheet(cmds)), { lastWorked: "2026-10-27" });+const blockCtx = { values: {}, notes: [], probes: [], canAsk: true, header: "job" as const, lastFail: null, lessons: [], gone: [] };++test("recall, a repeat: the block says the preference once, under its steps, and the prompt leaves it out", () => {+ const c = skillOf(["python scripts/gen_schema.py", "npm run build"]);+ const marks = recallMarks(c.skill.steps, [SCHEMA]);+ const block = runBlock(c, { ...blockCtx, marks });+ assert.deepEqual(block.split("\n"), [+ "[trail] Skill run-tests fits (yours, v1, last worked Oct 27). Start from these exact steps, in order:",+ " 1 python scripts/gen_schema.py",+ " 2 npm run build",+ " 3 npm test",+ " check: step 3 passing is the check.",+ " Step 1 follows your preference: \"don't edit _schema.py by hand, run scripts/gen_schema.py\".",+ " If a step fails, fix that step and say so. End with \"Used skill run-tests\".",+ ]);+ assert.deepEqual(saidIn(block, marks), ["l-1a2b3c4d"]);+});++test("recall, a contradiction: the preference wins, the block marks each step and shows it the preference's way", () => {+ const c = skillOf(["npm ci", "npm run build"]);+ const marks = recallMarks(c.skill.steps, [PNPM]);+ const block = runBlock(c, { ...blockCtx, marks });+ assert.deepEqual(block.split("\n").slice(1), [+ " 1 pnpm install --frozen-lockfile (your preference's way; the skill has npm ci)",+ " 2 pnpm run build (your preference's way; the skill has npm run build)",+ " 3 pnpm test (your preference's way; the skill has npm test)",+ " check: step 3 passing is the check.",+ " Your preference wins over the skill: \"use pnpm, not npm\". Steps 1, 2 and 3 are written its way; run them as shown.",+ " If a step fails, fix that step and say so. End with \"Used skill run-tests\".",+ ]);+ // What credit and fidelity read: the steps as the block showed them.+ const shown = withFixes(c.skill, marks);+ assert.deepEqual(shown.steps.map((s) => s.cmd), ["pnpm install --frozen-lockfile", "pnpm run build", "pnpm test"]);+ assert.equal(shown.check, "pnpm test");+ assert.deepEqual(saidIn(block, marks), ["l-1a2b3c4d"]);+});++test("recall, a step to leave out: marked on its line, and why after the steps", () => {+ const c = skillOf(["npm ci", "npx prisma db push"]);+ const never = learning("never run npx prisma db push", { kind: "decision", scope: "repo", id: "l-2b3c4d5e" });+ const lines = runBlock(c, { ...blockCtx, marks: recallMarks(c.skill.steps, [never]) }).split("\n");+ assert.equal(lines[2], " 2 npx prisma db push (against this repo's decision: see below)");+ assert.ok(lines.includes(" This repo's decision \"never run npx prisma db push\" goes against step 2: leave it out, do that part its way, and tell the person."), lines.join("\n"));+});++test("a contradiction wins over a repeat; a plain learning quoted only in part repeats nothing; at most 3 learnings", () => {+ const c = skillOf(["npm ci", "npm run build"]);+ const marks = recallMarks(c.skill.steps, [learning("use npm"), PNPM]);+ assert.deepEqual(marks.map((m) => [m.l.quote, m.against, m.steps]), [["use pnpm, not npm", true, [1, 2, 3]]]);+ const partly = learning("use npm. Also the staging database is read-only.");+ assert.equal(partly.whole, false);+ assert.deepEqual(recallMarks(c.skill.steps, [partly]), []);+ const guard = learning("always run npm ci", { kind: "guardrail" });+ assert.deepEqual(recallMarks(c.skill.steps, [guard]), [], "a guardrail is enforced where the command runs; a repeat of one is not said here");+ const many = ["use npm", "always run npm ci", "always run npm test", "always run npm run build"].map((t, k) => learning(t, { id: `l-0000000${k}` }));+ assert.equal(recallMarks(c.skill.steps, many).length, 3);+ assert.deepEqual(markLines([]), []);+});++/* ------------------------------------------------------------ init's fold */++test("onlyRepeats: what init folds into a kept skill as a lesson", () => {+ const steps = ["python scripts/gen_schema.py", "pytest -q"];+ assert.equal(onlyRepeats("don't edit _schema.py by hand, run scripts/gen_schema.py", steps), true);+ assert.equal(onlyRepeats("run scripts/gen_schema.py, then tell me what changed", steps), false, "part of it isn't a step");+ assert.equal(onlyRepeats("use pnpm, not npm", ["npm test"]), false, "a contradiction is no repeat");+ assert.equal(onlyRepeats("explain it simply", steps), false);+});diff --git a/test/skills-follow-words.test.ts b/test/skills-follow-words.test.tsnew file mode 100644index 00000000..ba5fb9c5--- /dev/null+++ b/test/skills-follow-words.test.ts@@ -0,0 +1,67 @@+/**+ * The words rule for part 7 (learnings and skills said once): every line the+ * person or the agent reads about a learning and a skill says learnings,+ * skills, lessons, guardrails, preferences or decisions, never notes, rules,+ * memory, remember or workflows, and has no em dash. Checked by value (the+ * copy constants) and on the lines as they come out. A directive opens with+ * who it is from; a block's lines never open a `[trail]` line of their own.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { FOLLOW_COPY, followAtSave, markLines, recallMarks, stepLearningOf, stepNote, whose, withFollowLine } from "../src/skills/follow-learnings.js";+import { INIT_COPY } from "../src/init/review-screen.js";+import { UPDATE_COPY, updateLines } from "../src/skills/offer-words-2.js";+import { stopBlockReason } from "../src/skills/offer-words.js";+import type { PendingOffer } from "../src/trace/types.js";++const BANNED = /\b(?:notes?|rules?|memory|memories|remember\w*|workflows?)\b/i;+const EM_DASH = /—/;+const clean = (t: string, what: string) => {+ assert.doesNotMatch(t, BANNED, `${what}: ${t}`);+ assert.doesNotMatch(t, EM_DASH, `${what}: ${t}`);+};++const L = (title: string, kind: "preference" | "decision" | "guardrail" | null = "preference", scope: "personal" | "repo" | "team" = "personal") =>+ stepLearningOf({ id: "l-1a2b3c4d", kind: kind ?? undefined, scope, title, body: title })!;++test("the copy, by value", () => {+ for (const [k, v] of Object.entries(FOLLOW_COPY)) clean(v, `FOLLOW_COPY.${k}`);+ for (const k of ["foldHint", "folded"]) clean(INIT_COPY[k]!, `INIT_COPY.${k}`);+ for (const k of ["line1Preference", "line2Preference"] as const) clean(UPDATE_COPY[k], `UPDATE_COPY.${k}`);+});++test("the lines as they come out, for each kind and owner", () => {+ const kinds = [L("use pnpm, not npm"), L("never run npx prisma db push", "decision", "repo"), L("don't use npx", "guardrail", "team"), L("always run make lint before git push", null, "repo"),+ L("don't edit _schema.py by hand, run scripts/gen_schema.py")];+ assert.deepEqual(kinds.map(whose), ["your preference", "this repo's decision", "your team's guardrail", "this repo's learning", "your preference"]);+ const steps = ["npm ci", "npx prisma db push", "python scripts/gen_schema.py", "git push origin main", "npm test"].map((cmd, k) => ({ n: k + 1, cmd, gated: null }));+ for (const l of kinds) {+ const marks = recallMarks(steps, [l]);+ for (const line of markLines(marks)) {+ clean(line, l.quote);+ assert.ok(!line.startsWith("[trail]"));+ }+ for (const s of steps) clean(stepNote(marks, s.n, s.cmd), l.quote);+ const f = followAtSave(steps.map((s) => ({ cmd: s.cmd, gated: false, isCheck: false })), [l]);+ clean(f.line, l.quote);+ clean(withFollowLine(["Tests pass.", "Keep the 3 that worked as a skill, just for you in this repo? (yes / show me / no)"], f.line || undefined)[0], l.quote);+ }+ const [a, b] = updateLines({ op: "update", why: "preference", follows: "your preference", steps: [1, 2, 3], check: "Tests pass (12 passed).", name: "run-tests", job: "tests", at: 1,+ cmds: ["pnpm install --frozen-lockfile", "pnpm run build", "pnpm test"], changes: 3, handEdited: false });+ assert.equal(a, "Tests pass (12 passed). This time steps 1, 2 and 3 of run-tests ran as 'pnpm install --frozen-lockfile', 'pnpm run build' and 1 more, the way your preference says.");+ assert.equal(b, "Change steps 1, 2 and 3 of run-tests to match? 3 line changes. (yes / show me / no)");+ clean(a, "update line 1");+ clean(b, "update line 2");+ assert.equal(updateLines({ op: "update", why: "preference", follows: "this repo's decision", check: "Tests pass.", name: "run-tests", job: "tests", at: 2, cmds: ["pnpm test"], changes: 1, handEdited: false })[0],+ "Tests pass. This time step 2 of run-tests ran as 'pnpm test', the way this repo's decision says.");+ // The update offer's reason, which the agent reads, opens with who it is from.+ const offer = {+ offerId: "o-1a2b3c", moment: "update", runId: "r-1022-b6c1", name: "run-tests", key: "s-21ce56|update|v1", lines: [a, b], channel: "stop",+ shownAt: "2026-10-22T12:00:41.000Z", showMe: false, yes: null, typedAfter: [], repo: "github.com/acme/shop",+ fold: { op: "update", skillId: "s-21ce56", baseHash: "sha256:x", proposalSha: "0123456789abcdef", handEdited: false, version: 1 },+ } as unknown as PendingOffer;+ const reason = stopBlockReason(offer);+ assert.match(reason, /^\[trail\] From Trail, the tool this person installed to keep commands that worked as skills\. /);+ assert.ok(reason.includes(a) && reason.includes(b));+ clean(reason, "the update offer's reason");+});diff --git a/test/skills-learning-steps.test.ts b/test/skills-learning-steps.test.tsnew file mode 100644index 00000000..6f5ba506--- /dev/null+++ b/test/skills-learning-steps.test.ts@@ -0,0 +1,112 @@+/**+ * Part 7: the matcher between a learning's words and a skill's steps, with+ * no model. It catches tool and command preferences against a step's program+ * and arguments, and says nothing when it isn't sure: the near-misses here+ * must match nothing. Made-up commands and repos only.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { matchSteps, rulesOf } from "../src/skills/learning-steps.js";++const STEPS = [+ "npm ci",+ "python scripts/gen_schema.py",+ "(cd api && npm run build)",+ "npm test",+ "sed -i 's/v1/v2/' src/_schema.py",+ "npx prisma db push",+ "git push origin {branch}",+ "make lint",+];+const verdict = (text: string, steps = STEPS) => matchSteps(rulesOf(text).rules, steps);++test("use pnpm, not npm: every npm step goes against it, each written pnpm's way", () => {+ for (const text of ["use pnpm, not npm", "Use pnpm instead of npm.", "use `pnpm` rather than `npm`", "don't use npm, use pnpm", "prefer pnpm over npm", "prefer pnpm to npm"]) {+ assert.deepEqual(verdict(text), {+ repeats: [],+ contradicts: [+ { step: 1, fix: "pnpm install --frozen-lockfile" },+ { step: 3, fix: "(cd api && pnpm run build)" },+ { step: 4, fix: "pnpm test" },+ ],+ }, text);+ }+});++test("the same preference repeats the steps that already use pnpm", () => {+ assert.deepEqual(verdict("use pnpm, not npm", ["pnpm install", "pnpm test"]), { repeats: [1, 2], contradicts: [] });+});++test("bun runs a package's test script with bun run test; yarn has no safe twin for npm ci", () => {+ assert.deepEqual(verdict("use bun, not npm", ["npm test", "npm ci"]).contradicts, [{ step: 1, fix: "bun run test" }, { step: 2, fix: "bun install --frozen-lockfile" }]);+ assert.deepEqual(verdict("use yarn, not npm", ["npm ci", "npm test"]).contradicts, [{ step: 1, fix: null }, { step: 2, fix: "yarn test" }]);+});++test("a step Trail can't rewrite safely (a pipe, an env prefix, flags it doesn't know) still goes against it, with no fix", () => {+ assert.deepEqual(verdict("use pnpm, not npm", ["npm test | tee out.log", "CI=1 npm test", "npm publish --access public", "npm test -- --watch"]).contradicts,+ [{ step: 1, fix: null }, { step: 2, fix: null }, { step: 3, fix: null }, { step: 4, fix: null }]);+});++test("the schema example: don't edit _schema.py by hand, run scripts/gen_schema.py repeats the step that runs it", () => {+ for (const text of ["don't edit _schema.py by hand, run scripts/gen_schema.py", "run scripts/gen_schema.py instead of editing _schema.py",+ "Don't hand-edit `_schema.py`; run `scripts/gen_schema.py`."]) {+ const r = rulesOf(text);+ assert.equal(r.whole, true, text);+ assert.deepEqual(matchSteps(r.rules, ["python scripts/gen_schema.py", "pytest -q"]), { repeats: [1], contradicts: [] }, text);+ assert.deepEqual(matchSteps(r.rules, ["./scripts/gen_schema.py && pytest -q"]), { repeats: [1], contradicts: [] }, text);+ }+ // A step that writes the file itself goes against it.+ assert.deepEqual(verdict("don't edit _schema.py by hand, run scripts/gen_schema.py").contradicts, [{ step: 5, fix: null }]);+ assert.deepEqual(verdict("never edit src/_schema.py", ["cp /tmp/x.py src/_schema.py", "echo x > src/_schema.py", "cat src/_schema.py"]).contradicts,+ [{ step: 1, fix: null }, { step: 2, fix: null }]);+});++test("never and don't: the program, or the program with its arguments first", () => {+ assert.deepEqual(verdict("never run npx prisma db push").contradicts, [{ step: 6, fix: null }]);+ assert.deepEqual(verdict("don't use npx").contradicts, [{ step: 6, fix: null }]);+ assert.deepEqual(verdict("avoid running npx prisma migrate").contradicts, [], "another subcommand is not this one");+});++test("always run Y before Z: in order repeats, Z without Y first goes against it", () => {+ assert.deepEqual(verdict("always run make lint before git push", ["make lint", "git push origin main"]), { repeats: [1], contradicts: [] });+ assert.deepEqual(verdict("run `make lint` before `git push`", ["git push origin main", "make lint"]).contradicts, [{ step: 1, fix: null }]);+ assert.deepEqual(verdict("before git push, always run make lint", ["make build", "git push origin main"]).contradicts, [{ step: 2, fix: null }]);+});++test("a whole command for a whole command is written the person's way", () => {+ assert.deepEqual(verdict("run `pytest -q` instead of `npm test`").contradicts, [{ step: 4, fix: "pytest -q" }]);+ assert.deepEqual(verdict("run `pytest -q` instead of `npm test`", ["npm test -- --ci"]).contradicts, [{ step: 1, fix: null }], "more than the named command: no fix");+});++test("near-misses say nothing", () => {+ const nothing = [+ "always run the tests before pushing", // no command named+ "npm is slow here", // no shape+ "we decided not to use npm here", // a decision's words, not a command shape+ "use pnpm not npm in CI", // a qualifier the matcher doesn't read+ "use the staging database", // no program+ "prefer small PRs over big ones", // English, not commands+ "run it again", // no program+ "never run git push --force", // the steps push without --force+ "don't use npm ci, it wipes node_modules", // npm ci has args the steps' npm calls don't+ ];+ const steps = ["pnpm install", "git push origin main", "npm test", "make lint"];+ for (const text of nothing) assert.deepEqual(matchSteps(rulesOf(text).rules, steps), { repeats: [], contradicts: [] }, text);+});++test("a program name inside another word or argument never matches", () => {+ assert.deepEqual(verdict("never run npm", ["pnpm test", "npmx run", "node scripts/npm-check.js", "echo npm"]), { repeats: [], contradicts: [] });+ assert.deepEqual(verdict("never run git push", ["git pushx", "git status", "gh pr create"]), { repeats: [], contradicts: [] });+});++test("whole is false when part of the learning isn't read, so a line can't quote it as if it were all of it", () => {+ assert.equal(rulesOf("use pnpm, not npm").whole, true);+ assert.equal(rulesOf("use pnpm, not npm. The lockfile is pnpm-lock.yaml.").whole, false);+ assert.equal(rulesOf("don't use npm, it is slow").whole, false);+ assert.equal(rulesOf("").whole, false);+});++test("two rules that would write one step two ways write it neither way", () => {+ const rules = [...rulesOf("use pnpm, not npm").rules, ...rulesOf("use yarn, not npm").rules];+ assert.deepEqual(matchSteps(rules, ["npm test"]).contradicts, [{ step: 1, fix: null }]);+});