Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Keep active agent sessions through write completion (#5568)
Nick Gomezf912d4b5b647
diff --git a/.changeset/tidy-mugs-smell.md b/.changeset/tidy-mugs-smell.mdnew file mode 100644index 000000000..dc700ab6e--- /dev/null+++ b/.changeset/tidy-mugs-smell.md@@ -0,0 +1,5 @@+---+"@inkeep/open-knowledge": patch+---++Agent edits and lint fixes no longer fail with a server error when many documents are being edited at once.diff --git a/packages/app/tests/integration/project-sweep-capacity.test.ts b/packages/app/tests/integration/project-sweep-capacity.test.tsindex d24785aa6..6dc3f7f4a 100644--- a/packages/app/tests/integration/project-sweep-capacity.test.ts+++ b/packages/app/tests/integration/project-sweep-capacity.test.ts@@ -1,6 +1,7 @@+import { randomUUID } from 'node:crypto';import { mkdirSync, writeFileSync } from 'node:fs';import { dirname, join } from 'node:path';-import { afterEach, describe, expect, test } from 'vitest';+import { afterEach, describe, expect, test, vi } from 'vitest';import {CAPACITY_PROBLEM_TYPE,isCapacityRefusal,@@ -9,7 +10,9 @@ import {sweepSleep,} from '@/components/problems-sweep';import { fixLintDoc } from '@/editor/lint-config-client';-import { agentWriteMd, createTestServer, type TestServer } from './test-harness';+import * as agentSessions from '../../../server/src/agent-sessions';+import * as lintAudit from '../../../server/src/lint/audit';+import { createTestServer, type TestServer } from './test-harness';type FetchFn = typeof globalThis.fetch;@@ -19,12 +22,348 @@ let server: TestServer | undefined;let restoreFetch: (() => void) | undefined;afterEach(async () => {+ vi.restoreAllMocks();restoreFetch?.();restoreFetch = undefined;await server?.cleanup();server = undefined;});+describe('agent-session operation lifetime', () => {+ const startCappedServer = async (minEvictableIdleMs: number) => {+ server = await createTestServer({+ markdownlintEnabled: true,+ agentSessionOptions: { maxSessions: 2, minEvictableIdleMs },+ });+ const { baseUrl, contentDir, instance } = server;+ const post = (route: string, body: object): Promise<Response> =>+ fetch(`${baseUrl}${route}`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ });+ return {+ contentDir,+ sessionManager: instance.sessionManager,+ debouncer: instance.hocuspocus.debouncer,+ post,+ };+ };++ const freezeClock = () => {+ let clock = Date.now();+ vi.spyOn(Date, 'now').mockImplementation(() => clock);+ return (ms: number): void => {+ clock += ms;+ };+ };++ test.each([+ { label: 'markdown write below the idle floor', kind: 'markdown', floor: 700, advance: 0 },+ { label: 'markdown write past the idle floor', kind: 'markdown', floor: 700, advance: 701 },+ {+ label: 'markdown write past the default floor',+ kind: 'markdown',+ floor: agentSessions.MIN_EVICTABLE_IDLE_MS,+ advance: agentSessions.MIN_EVICTABLE_IDLE_MS + 1,+ },+ { label: 'frontmatter patch', kind: 'frontmatter', floor: 700, advance: 701 },+ { label: 'text patch', kind: 'patch', floor: 700, advance: 701 },+ { label: 'lint fix', kind: 'lint', floor: 700, advance: 701 },+ { label: 'batched markdown write', kind: 'batch', floor: 700, advance: 701 },+ ] as const)(+ 'an accepted $label retains its session across capacity admission',+ async ({ kind, floor, advance }) => {+ const { contentDir, sessionManager, post } = await startCappedServer(floor);+ const docPrefix = `session-lifetime-${randomUUID()}`;+ const writerDoc = `${docPrefix}/writer`;+ const [firstDoc, nextDoc] = [`${docPrefix}/first`, `${docPrefix}/next`];+ for (const docName of [firstDoc, nextDoc]) seedFixableDoc(contentDir, docName);+ const identity = { agentId: 'held-writer', agentName: 'Held writer' };+ const advanceClock = freezeClock();+ expect(+ (+ await post('/api/agent-write-md', {+ ...identity,+ docName: writerDoc,+ markdown: FIXABLE_BODY,+ position: 'replace',+ })+ ).status,+ ).toBe(200);++ const entered = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const prepareMarkdown = agentSessions.prepareAgentMarkdownParse;+ const prepareFrontmatter = agentSessions.prepareFrontmatterPatchParse;+ const lintAndFix = lintAudit.lintAndFixSource;+ vi.spyOn(agentSessions, 'prepareAgentMarkdownParse').mockImplementation(async (...args) => {+ const parsed = await prepareMarkdown(...args);+ if (args[0].name === writerDoc) {+ entered.resolve();+ await release.promise;+ }+ return parsed;+ });+ vi.spyOn(agentSessions, 'prepareFrontmatterPatchParse').mockImplementation(+ async (...args) => {+ const parsed = await prepareFrontmatter(...args);+ if (args[0].name === writerDoc) {+ entered.resolve();+ await release.promise;+ }+ return parsed;+ },+ );+ vi.spyOn(lintAudit, 'lintAndFixSource').mockImplementation(async (...args) => {+ const fixed = await lintAndFix(...args);+ if (args[0].docRelPath === `${writerDoc}.md`) {+ entered.resolve();+ await release.promise;+ }+ return fixed;+ });+ const requests = {+ markdown: {+ route: '/api/agent-write-md',+ body: { ...identity, docName: writerDoc, markdown: 'After\n', position: 'append' },+ },+ frontmatter: {+ route: '/api/frontmatter-patch',+ body: { ...identity, docName: writerDoc, patch: { title: 'Updated title' } },+ },+ patch: {+ route: '/api/agent-patch',+ body: { ...identity, docName: writerDoc, find: '# Doc', replace: '# Updated doc' },+ },+ lint: { route: '/api/lint/fix', body: { ...identity, docName: writerDoc } },+ batch: {+ route: '/api/agent-write-batch',+ body: {+ ...identity,+ docs: [{ docName: writerDoc, markdown: 'After\n', position: 'append' }],+ },+ },+ };+ const request = requests[kind];+ const writing = post(request.route, request.body);+ try {+ await Promise.race([+ entered.promise,+ writing.then((response) => {+ throw new Error(`Operation returned before its barrier: ${response.status}`);+ }),+ ]);+ expect((await post('/api/lint/fix', { docName: firstDoc })).status).toBe(200);+ advanceClock(advance);+ const admission = await post('/api/lint/fix', { docName: nextDoc });+ expect(admission.status).toBe(advance === 0 ? 503 : 200);+ expect.soft(sessionManager.hasSession(writerDoc, 'agent-held-writer')).toBe(true);+ expect(sessionManager.liveSessionCount).toBe(2);+ release.resolve();+ const response = await writing;+ expect(response.status).toBe(200);+ if (kind === 'batch') {+ expect(await response.json()).toMatchObject({+ written: 1,+ failed: 0,+ results: [{ docName: writerDoc, status: 'written' }],+ });+ }+ advanceClock(floor + 1);+ for (const suffix of ['released-first', 'released-next']) {+ const docName = `${docPrefix}/${suffix}`;+ seedFixableDoc(contentDir, docName);+ expect((await post('/api/lint/fix', { docName })).status).toBe(200);+ }+ expect(sessionManager.hasSession(writerDoc, 'agent-held-writer')).toBe(false);+ expect(sessionManager.liveSessionCount).toBe(2);+ } finally {+ release.resolve();+ await writing;+ }+ },+ );++ test('an accepted batched markdown write retains its session while its write is flushed', async () => {+ const { contentDir, sessionManager, debouncer, post } = await startCappedServer(700);+ const docPrefix = `session-batch-flush-${randomUUID()}`;+ const writerDoc = `${docPrefix}/writer`;+ const [firstDoc, nextDoc] = [`${docPrefix}/first`, `${docPrefix}/next`];+ for (const docName of [firstDoc, nextDoc]) seedFixableDoc(contentDir, docName);+ const advanceClock = freezeClock();+ expect(+ (+ await post('/api/agent-write-md', {+ agentId: 'flushed-writer',+ docName: writerDoc,+ markdown: '# Doc\n',+ position: 'replace',+ })+ ).status,+ ).toBe(200);+ const flushing = Promise.withResolvers<void>();+ const release = Promise.withResolvers<void>();+ const executeNow = debouncer.executeNow;+ vi.spyOn(debouncer, 'executeNow').mockImplementation(async (id: string) => {+ const stored = await executeNow(id);+ if (id === `onStoreDocument-${writerDoc}`) {+ flushing.resolve();+ await release.promise;+ }+ return stored;+ });+ const writing = post('/api/agent-write-batch', {+ agentId: 'flushed-writer',+ docs: [{ docName: writerDoc, markdown: 'After\n', position: 'append' }],+ });+ try {+ await Promise.race([+ flushing.promise,+ writing.then((response) => {+ throw new Error(`Batch returned before its flush barrier: ${response.status}`);+ }),+ ]);+ expect((await post('/api/lint/fix', { docName: firstDoc })).status).toBe(200);+ advanceClock(701);+ expect((await post('/api/lint/fix', { docName: nextDoc })).status).toBe(200);+ expect.soft(sessionManager.hasSession(writerDoc, 'agent-flushed-writer')).toBe(true);+ expect(sessionManager.liveSessionCount).toBe(2);+ release.resolve();+ const response = await writing;+ expect(response.status).toBe(200);+ expect(await response.json()).toMatchObject({+ written: 1,+ failed: 0,+ results: [{ docName: writerDoc, status: 'written' }],+ });+ } finally {+ release.resolve();+ await writing;+ }+ });++ test('overlapping operations keep the session held until the last operation completes', async () => {+ const { contentDir, sessionManager, post } = await startCappedServer(700);+ const docPrefix = `session-overlap-${randomUUID()}`;+ const writerDoc = `${docPrefix}/writer`;+ const advanceClock = freezeClock();+ expect(+ (+ await post('/api/agent-write-md', {+ agentId: 'overlap-writer',+ docName: writerDoc,+ markdown: '# Doc\n',+ position: 'replace',+ })+ ).status,+ ).toBe(200);+ const firstEntered = Promise.withResolvers<void>();+ const secondEntered = Promise.withResolvers<void>();+ const firstRelease = Promise.withResolvers<void>();+ const secondRelease = Promise.withResolvers<void>();+ const prepare = agentSessions.prepareFrontmatterPatchParse;+ let preparation = 0;+ vi.spyOn(agentSessions, 'prepareFrontmatterPatchParse').mockImplementation(async (...args) => {+ const parsed = await prepare(...args);+ if (args[0].name === writerDoc) {+ preparation += 1;+ if (preparation === 1) {+ firstEntered.resolve();+ await firstRelease.promise;+ } else {+ secondEntered.resolve();+ await secondRelease.promise;+ }+ }+ return parsed;+ });+ const body = { agentId: 'overlap-writer', docName: writerDoc, patch: {} };+ const first = post('/api/frontmatter-patch', body);+ const second = firstEntered.promise.then(() => post('/api/frontmatter-patch', body));+ try {+ await secondEntered.promise;+ firstRelease.resolve();+ expect((await first).status).toBe(200);+ for (const suffix of ['first', 'next', 'last']) {+ const docName = `${docPrefix}/${suffix}`;+ seedFixableDoc(contentDir, docName);+ advanceClock(701);+ expect((await post('/api/lint/fix', { docName })).status).toBe(200);+ expect(sessionManager.liveSessionCount).toBe(2);+ }+ expect.soft(sessionManager.hasSession(writerDoc, 'agent-overlap-writer')).toBe(true);+ secondRelease.resolve();+ expect((await second).status).toBe(200);+ const nextDoc = `${docPrefix}/after-overlap`;+ seedFixableDoc(contentDir, nextDoc);+ advanceClock(701);+ expect((await post('/api/lint/fix', { docName: nextDoc })).status).toBe(200);+ expect(sessionManager.hasSession(writerDoc, 'agent-overlap-writer')).toBe(false);+ expect(sessionManager.liveSessionCount).toBe(2);+ } finally {+ firstRelease.resolve();+ secondRelease.resolve();+ await Promise.allSettled([first, second]);+ }+ });++ test('a refused text patch releases its session for later idle reclamation', async () => {+ const { contentDir, sessionManager, post } = await startCappedServer(700);+ const docPrefix = `session-refusal-${randomUUID()}`;+ const writerDoc = `${docPrefix}/writer`;+ const advanceClock = freezeClock();+ const identity = { agentId: 'refused-writer', docName: writerDoc };+ expect(+ (await post('/api/agent-write-md', { ...identity, markdown: '# Doc\n', position: 'replace' }))+ .status,+ ).toBe(200);+ expect(+ (await post('/api/agent-patch', { ...identity, find: 'absent target', replace: 'new text' }))+ .status,+ ).toBe(404);+ const firstDoc = `${docPrefix}/first`;+ seedFixableDoc(contentDir, firstDoc);+ expect((await post('/api/lint/fix', { docName: firstDoc })).status).toBe(200);+ advanceClock(701);+ const nextDoc = `${docPrefix}/next`;+ seedFixableDoc(contentDir, nextDoc);+ expect((await post('/api/lint/fix', { docName: nextDoc })).status).toBe(200);+ expect(sessionManager.hasSession(writerDoc, 'agent-refused-writer')).toBe(false);+ expect(sessionManager.liveSessionCount).toBe(2);+ });++ test('a write refused at capacity leaves its later session reclaimable once idle', async () => {+ const { contentDir, sessionManager, post } = await startCappedServer(700);+ const docPrefix = `session-capacity-refusal-${randomUUID()}`;+ const writerDoc = `${docPrefix}/writer`;+ const advanceClock = freezeClock();+ for (const suffix of ['first', 'second']) {+ const docName = `${docPrefix}/${suffix}`;+ seedFixableDoc(contentDir, docName);+ expect((await post('/api/lint/fix', { docName })).status).toBe(200);+ }+ const write = {+ agentId: 'capacity-writer',+ docName: writerDoc,+ markdown: '# Doc\n',+ position: 'replace',+ };+ expect((await post('/api/agent-write-md', write)).status).toBe(503);+ advanceClock(701);+ expect((await post('/api/agent-write-md', write)).status).toBe(200);+ expect(sessionManager.hasSession(writerDoc, 'agent-capacity-writer')).toBe(true);+ advanceClock(701);+ for (const suffix of ['released-first', 'released-next']) {+ const docName = `${docPrefix}/${suffix}`;+ seedFixableDoc(contentDir, docName);+ expect((await post('/api/lint/fix', { docName })).status).toBe(200);+ }+ expect(sessionManager.hasSession(writerDoc, 'agent-capacity-writer')).toBe(false);+ expect(sessionManager.liveSessionCount).toBe(2);+ });+});+function seedFixableDoc(contentDir: string, docName: string): void {const filePath = join(contentDir, `${docName}.md`);mkdirSync(dirname(filePath), { recursive: true });@@ -89,28 +428,49 @@ describe('project-scope Fix all under agent-session capacity', () => {const COLLATERAL_DOC = 'capacity-collateral/agent-doc';const WRITER_INTERVAL_MS = 50;- const writeCollateral = (): Promise<void> =>- agentWriteMd(port, 'concurrent agent line\n', {- docName: COLLATERAL_DOC,- position: 'append',- agentId: 'collateral-writer',- agentName: 'Collateral',+ const conflicts = server.instance.conflicts;+ const raise = conflicts.raise.bind(conflicts);+ let firstConflict:+ | { input: Parameters<typeof raise>[0]; stack: string | undefined }+ | undefined;+ vi.spyOn(conflicts, 'raise').mockImplementation((input) => {+ const trace =+ !firstConflict && input.file === `${COLLATERAL_DOC}.md`+ ? { input, stack: new Error().stack }+ : undefined;+ raise(input);+ if (trace && conflicts.has(COLLATERAL_DOC)) firstConflict = trace;+ });+ const writeCollateral = (): Promise<Response> =>+ fetch(`http://127.0.0.1:${port}/api/agent-write-md`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ markdown: 'concurrent agent line\n',+ docName: COLLATERAL_DOC,+ position: 'append',+ agentId: 'collateral-writer',+ agentName: 'Collateral',+ }),});- await writeCollateral();+ expect((await writeCollateral()).status).toBe(200);let sweepDone = false;let collateralWrites = 0;- const collateralFailures: Array<{ status: number | null }> = [];+ const collateralFailures: Array<+ { status: number; body: string } | { status: null; error: unknown }+ > = [];const runWriterLoop = async (): Promise<void> => {while (!sweepDone) {await sweepSleep(WRITER_INTERVAL_MS);if (sweepDone) break;try {- await writeCollateral();- collateralWrites += 1;+ const response = await writeCollateral();+ if (response.ok) collateralWrites += 1;+ else collateralFailures.push({ status: response.status, body: await response.text() });} catch (err) {- collateralFailures.push({ status: (err as { status?: number }).status ?? null });+ collateralFailures.push({ status: null, error: err });}}};@@ -138,7 +498,11 @@ describe('project-scope Fix all under agent-session capacity', () => {expect(capacityRefusals).toBeGreaterThan(0);- expect(collateralWrites).toBeGreaterThan(0);- expect(collateralFailures).toEqual([]);+ const failureContext = JSON.stringify({+ firstConflict,+ evictions: server.instance.sessionManager.evictionCount,+ });+ expect(collateralWrites, failureContext).toBeGreaterThan(0);+ expect(collateralFailures, failureContext).toEqual([]);}, 30_000);});diff --git a/packages/server/src/agent-sessions.ts b/packages/server/src/agent-sessions.tsindex 1c8aa33ed..b0ba82f3f 100644--- a/packages/server/src/agent-sessions.ts+++ b/packages/server/src/agent-sessions.ts@@ -562,6 +562,7 @@ function evictionCounter(): ReturnType<ReturnType<typeof getMeter>['createCounteexport class AgentSessionManager {private sessions = new Map<string, SessionRecord>();private pendingSessions = new Map<string, Promise<SessionRecord>>();+ private activeOperations = new Map<string, { count: number }>();private hocuspocus: Hocuspocus;private readonly maxSessions: number;private readonly minEvictableIdleMs: number;@@ -622,6 +623,39 @@ export class AgentSessionManager {return session;}+ async withSessions<T>(+ operation: (getSession: AgentSessionManager['getSession']) => Promise<T>,+ ): Promise<T> {+ const releases: Array<() => void> = [];+ const getSession: AgentSessionManager['getSession'] = async (+ docName,+ agentId = UNIDENTIFIED_WRITER_ID,+ identity,+ ) => {+ const key = this.sessionKey(docName, agentId);+ const active = this.activeOperations.get(key) ?? { count: 0 };+ active.count += 1;+ this.activeOperations.set(key, active);+ const release = (): void => {+ active.count -= 1;+ if (active.count === 0) this.activeOperations.delete(key);+ };+ try {+ const session = await this.getSession(docName, agentId, identity);+ releases.push(release);+ return session;+ } catch (error) {+ release();+ throw error;+ }+ };+ try {+ return await operation(getSession);+ } finally {+ for (const release of releases) release();+ }+ }+/*** Presence is published on the `__system__` Y.Doc via `AgentPresenceBroadcaster` instead* (precedent #3).@@ -736,26 +770,27 @@ export class AgentSessionManager {}private async evictLruIdleSession(): Promise<string | null> {- const first = this.sessions.entries().next();- if (first.done) return null;- const [key, session] = first.value;- const idleMs = Date.now() - session.lastUsedAt;- if (idleMs < this.minEvictableIdleMs) return null;+ for (const [key, session] of this.sessions) {+ if (this.activeOperations.has(key)) continue;+ const idleMs = Date.now() - session.lastUsedAt;+ if (idleMs < this.minEvictableIdleMs) return null;- this.sessions.delete(key);- await this.cleanupSession(key, session, {- docName: session.docName,- agentId: session.agentId,- evicted: true,- });- this.evictions++;- incrementAgentSessionEvictions();- evictionCounter().add(1);- log.info(- { docName: session.docName, agentId: session.agentId, idleMs },- '[agent-session] Evicted LRU idle session under capacity pressure',- );- return key;+ this.sessions.delete(key);+ await this.cleanupSession(key, session, {+ docName: session.docName,+ agentId: session.agentId,+ evicted: true,+ });+ this.evictions++;+ incrementAgentSessionEvictions();+ evictionCounter().add(1);+ log.info(+ { docName: session.docName, agentId: session.agentId, idleMs },+ '[agent-session] Evicted LRU idle session under capacity pressure',+ );+ return key;+ }+ return null;}hasSession(docName: string, agentId = UNIDENTIFIED_WRITER_ID): boolean {diff --git a/packages/server/src/api-extension.ts b/packages/server/src/api-extension.tsindex 31a675ff7..2795a8ff5 100644--- a/packages/server/src/api-extension.ts+++ b/packages/server/src/api-extension.ts@@ -3665,205 +3665,207 @@ export function createApiExtension(options: ApiExtensionOptions): Extension & {ts: Date.now(),});- for (let i = 0; i < body.docs.length; i++) {- const entry = body.docs[i];- const resolvedDocName = resolveAlias(entry.docName);-- if (isSystemDoc(resolvedDocName) || isConfigDoc(resolvedDocName)) {- results[i] = entryError(- resolvedDocName,- 'urn:ok:error:reserved-doc-name',- `'${resolvedDocName}' is a reserved document name.`,- );- continue;- }-- try {- if (- entry.extension !== undefined &&- !docNameExistsWithAnySupportedExtension(contentDir, resolvedDocName)- ) {- registerDocExtension(resolvedDocName, entry.extension);+ await sessionManager.withSessions(async (getSession) => {+ for (let i = 0; i < body.docs.length; i++) {+ const entry = body.docs[i];+ const resolvedDocName = resolveAlias(entry.docName);++ if (isSystemDoc(resolvedDocName) || isConfigDoc(resolvedDocName)) {+ results[i] = entryError(+ resolvedDocName,+ 'urn:ok:error:reserved-doc-name',+ `'${resolvedDocName}' is a reserved document name.`,+ );+ continue;}- const normalizedSummary = normalizeSummary(entry.summary);- const { response: summaryResponse, stored: storedSummary } =- summaryResponseFields(normalizedSummary);- const session = await sessionManager.getSession(resolvedDocName, agentId, {- displayName: agentName,- colorSeed,- clientName,- });+ try {+ if (+ entry.extension !== undefined &&+ !docNameExistsWithAnySupportedExtension(contentDir, resolvedDocName)+ ) {+ registerDocExtension(resolvedDocName, entry.extension);+ }- const reconcile = reconcileDiskBeforeAgentWrite(- durabilityState,- hocuspocus,- resolvedDocName,- contentDir,- options.resolveEmbed,- getBridgeLossReporter?.(),- conflicts,- );+ const normalizedSummary = normalizeSummary(entry.summary);+ const { response: summaryResponse, stored: storedSummary } =+ summaryResponseFields(normalizedSummary);+ const session = await getSession(resolvedDocName, agentId, {+ displayName: agentName,+ colorSeed,+ clientName,+ });- const entryEmbedResolver = options.resolveEmbed- ? { resolveEmbed: options.resolveEmbed, sourcePath: resolvedDocName }- : undefined;- const entryPrecomputed = await prepareAgentMarkdownParse(- session.dc.document,- entry.markdown,- entry.position ?? 'append',- entryEmbedResolver,- );+ const reconcile = reconcileDiskBeforeAgentWrite(+ durabilityState,+ hocuspocus,+ resolvedDocName,+ contentDir,+ options.resolveEmbed,+ getBridgeLossReporter?.(),+ conflicts,+ );- let writeDivergence: AgentWriteContentDivergence | undefined;- const disposeEntryEffectCapture = captureEffect(- session.dc.document.getText('source'),- agentId,- session.origin,- colorSeed,- clientName,- );- agentWritePreDrain(session.dc.document, entry.markdown, entry.position ?? 'append');- try {- session.dc.document.transact(() => {- const beforeBlocks = snapshotBlocks(session.dc.document);- writeDivergence = applyAgentMarkdownWrite(- session.dc.document,- entry.markdown,- entry.position ?? 'append',- entryEmbedResolver,- entryPrecomputed,- agentWriteLossDetect(session),- suppliedWriterId,- );+ const entryEmbedResolver = options.resolveEmbed+ ? { resolveEmbed: options.resolveEmbed, sourcePath: resolvedDocName }+ : undefined;+ const entryPrecomputed = await prepareAgentMarkdownParse(+ session.dc.document,+ entry.markdown,+ entry.position ?? 'append',+ entryEmbedResolver,+ );- const changedBlocks =- changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ??- undefined;- const activityMap = session.dc.document.getMap('agent-flash');- activityMap.set(agentId, {- agentId,- timestamp: Date.now(),- type: 'insert',- description: `Added (${agentName}): ${entry.markdown.trim().slice(0, 50)}`,- ...(changedBlocks !== undefined ? { changedBlocks } : {}),- });- }, session.origin);- } finally {- disposeEntryEffectCapture();- }+ let writeDivergence: AgentWriteContentDivergence | undefined;+ const disposeEntryEffectCapture = captureEffect(+ session.dc.document.getText('source'),+ agentId,+ session.origin,+ colorSeed,+ clientName,+ );+ agentWritePreDrain(session.dc.document, entry.markdown, entry.position ?? 'append');+ try {+ session.dc.document.transact(() => {+ const beforeBlocks = snapshotBlocks(session.dc.document);+ writeDivergence = applyAgentMarkdownWrite(+ session.dc.document,+ entry.markdown,+ entry.position ?? 'append',+ entryEmbedResolver,+ entryPrecomputed,+ agentWriteLossDetect(session),+ suppliedWriterId,+ );++ const changedBlocks =+ changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ??+ undefined;+ const activityMap = session.dc.document.getMap('agent-flash');+ activityMap.set(agentId, {+ agentId,+ timestamp: Date.now(),+ type: 'insert',+ description: `Added (${agentName}): ${entry.markdown.trim().slice(0, 50)}`,+ ...(changedBlocks !== undefined ? { changedBlocks } : {}),+ });+ }, session.origin);+ } finally {+ disposeEntryEffectCapture();+ }- recordContentDivergenceGate('agent-write-batch', writeDivergence);- recordContributor(- resolvedDocName,- agentId,- agentName,- colorSeed,- undefined,- buildAgentActor({ clientName, clientVersion, label }),- storedSummary,- );- incrementAgentWriteCalls();- countNormalizedSummary(normalizedSummary);-- const reconcileWarning = buildReconcileWarning(reconcile);- const warnings: AdvisoryWarning[] = [- ...(writeDivergence !== undefined- ? [toContentDivergenceWarning(writeDivergence)]- : []),- ...(reconcileWarning ? [reconcileWarning] : []),- ];- pending.push({- index: i,- docName: resolvedDocName,- session,- summaryResponse,- warnings,- });- } catch (e) {- results[i] = classifyEntryFailure(resolvedDocName, e);+ recordContentDivergenceGate('agent-write-batch', writeDivergence);+ recordContributor(+ resolvedDocName,+ agentId,+ agentName,+ colorSeed,+ undefined,+ buildAgentActor({ clientName, clientVersion, label }),+ storedSummary,+ );+ incrementAgentWriteCalls();+ countNormalizedSummary(normalizedSummary);++ const reconcileWarning = buildReconcileWarning(reconcile);+ const warnings: AdvisoryWarning[] = [+ ...(writeDivergence !== undefined+ ? [toContentDivergenceWarning(writeDivergence)]+ : []),+ ...(reconcileWarning ? [reconcileWarning] : []),+ ];+ pending.push({+ index: i,+ docName: resolvedDocName,+ session,+ summaryResponse,+ warnings,+ });+ } catch (e) {+ results[i] = classifyEntryFailure(resolvedDocName, e);+ }}- }- const flushErrors = new Map<string, BatchErrorResult['error'] | undefined>();- for (const p of pending) {- if (flushErrors.has(p.docName)) continue;- const flushOutcome = await flushDiskAndDetectOutcome(p.docName);- if (flushOutcome?.kind === 'failure') {- if (flushOutcome.failure.code === OK_DOC_REMOVED) {- flushErrors.set(p.docName, removedDocProblem(flushOutcome.failure));- } else if (flushOutcome.failure.code === OK_PATH_UNRESOLVABLE) {- flushErrors.set(p.docName, pathFaultProblem(flushOutcome.failure));- } else if (flushOutcome.failure.code === OK_STORE_REFUSED) {- flushErrors.set(p.docName, refusedStoreProblem(flushOutcome.failure));- } else {- const reason = classifyUploadErrno({- code: flushOutcome.failure.code,- } as NodeJS.ErrnoException);+ const flushErrors = new Map<string, BatchErrorResult['error'] | undefined>();+ for (const p of pending) {+ if (flushErrors.has(p.docName)) continue;+ const flushOutcome = await flushDiskAndDetectOutcome(p.docName);+ if (flushOutcome?.kind === 'failure') {+ if (flushOutcome.failure.code === OK_DOC_REMOVED) {+ flushErrors.set(p.docName, removedDocProblem(flushOutcome.failure));+ } else if (flushOutcome.failure.code === OK_PATH_UNRESOLVABLE) {+ flushErrors.set(p.docName, pathFaultProblem(flushOutcome.failure));+ } else if (flushOutcome.failure.code === OK_STORE_REFUSED) {+ flushErrors.set(p.docName, refusedStoreProblem(flushOutcome.failure));+ } else {+ const reason = classifyUploadErrno({+ code: flushOutcome.failure.code,+ } as NodeJS.ErrnoException);+ flushErrors.set(p.docName, {+ type: reason,+ title: 'Write applied in memory but failed to persist to disk.',+ detail: `${flushOutcome.failure.code ?? 'unknown error'}: ${flushOutcome.failure.message}. The content was NOT saved and will be lost if the server restarts.`,+ });+ }+ } else if (flushOutcome?.kind === 'divergence') {flushErrors.set(p.docName, {- type: reason,- title: 'Write applied in memory but failed to persist to disk.',- detail: `${flushOutcome.failure.code ?? 'unknown error'}: ${flushOutcome.failure.message}. The content was NOT saved and will be lost if the server restarts.`,+ type: 'urn:ok:error:disk-divergence',+ title:+ 'The document changed on disk after your edit was prepared; your edit was NOT applied. Re-read the document and retry.',});+ } else if (flushOutcome?.kind === 'stale-external-write') {+ flushErrors.set(p.docName, staleExternalWriteProblem(p.docName));+ } else {+ flushErrors.set(p.docName, undefined);}- } else if (flushOutcome?.kind === 'divergence') {- flushErrors.set(p.docName, {- type: 'urn:ok:error:disk-divergence',- title:- 'The document changed on disk after your edit was prepared; your edit was NOT applied. Re-read the document and retry.',- });- } else if (flushOutcome?.kind === 'stale-external-write') {- flushErrors.set(p.docName, staleExternalWriteProblem(p.docName));- } else {- flushErrors.set(p.docName, undefined);}- }- const admittedForLinks = await collectAdmittedDocNames();- for (const p of pending) {- if (flushErrors.get(p.docName) === undefined) admittedForLinks.add(p.docName);- }- const linkedFileExists = createLinkedFileExists();- const linkedFolderExists = createLinkedFolderExists();-- let lastWrittenDoc: string | undefined;- for (const p of pending) {- const flushError = flushErrors.get(p.docName);- if (flushError !== undefined) {- results[p.index] = { status: 'error', docName: p.docName, error: flushError };- continue;+ const admittedForLinks = await collectAdmittedDocNames();+ for (const p of pending) {+ if (flushErrors.get(p.docName) === undefined) admittedForLinks.add(p.docName);}- const writtenSource = p.session.dc.document.getText('source').toString();- registerWrittenDocInFileIndex(p.docName, writtenSource);- results[p.index] = {- status: 'written',- docName: p.docName,- ...(p.summaryResponse ? { summary: p.summaryResponse } : {}),- ...(p.warnings.length > 0 ? { warnings: p.warnings } : {}),- ...projectWriteAdvisoryLinks(- computeWriteAdvisoryLinks(- writtenSource,+ const linkedFileExists = createLinkedFileExists();+ const linkedFolderExists = createLinkedFolderExists();++ let lastWrittenDoc: string | undefined;+ for (const p of pending) {+ const flushError = flushErrors.get(p.docName);+ if (flushError !== undefined) {+ results[p.index] = { status: 'error', docName: p.docName, error: flushError };+ continue;+ }+ const writtenSource = p.session.dc.document.getText('source').toString();+ registerWrittenDocInFileIndex(p.docName, writtenSource);+ results[p.index] = {+ status: 'written',+ docName: p.docName,+ ...(p.summaryResponse ? { summary: p.summaryResponse } : {}),+ ...(p.warnings.length > 0 ? { warnings: p.warnings } : {}),+ ...projectWriteAdvisoryLinks(+ computeWriteAdvisoryLinks(+ writtenSource,+ p.docName,+ admittedForLinks,+ linkedFileExists,+ linkedFolderExists,+ ),p.docName,- admittedForLinks,- linkedFileExists,- linkedFolderExists,+ linkPolicy.suppressLogLinkAdvisories,),- p.docName,- linkPolicy.suppressLogLinkAdvisories,- ),- };- lastWrittenDoc = p.docName;- }+ };+ lastWrittenDoc = p.docName;+ }- if (lastWrittenDoc !== undefined) {- agentFocusBroadcaster?.setFocus(agentId, {- agentName,- currentDoc: lastWrittenDoc,- writeKind: 'write',- ts: Date.now(),- });- onAgentWrite?.();- }+ if (lastWrittenDoc !== undefined) {+ agentFocusBroadcaster?.setFocus(agentId, {+ agentName,+ currentDoc: lastWrittenDoc,+ writeKind: 'write',+ ts: Date.now(),+ });+ onAgentWrite?.();+ }+ });} finally {agentPresenceBroadcaster?.touchMode(agentId, 'idle');}diff --git a/packages/server/src/http/agent-write-routes.ts b/packages/server/src/http/agent-write-routes.tsindex 7cdbc8fc3..eac1bb442 100644--- a/packages/server/src/http/agent-write-routes.ts+++ b/packages/server/src/http/agent-write-routes.ts@@ -329,177 +329,179 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupconst normalizedSummary = normalizeSummary(body.summary);const { response: summaryResponse, stored: storedSummary } =summaryResponseFields(normalizedSummary);- const session = await sessionManager.getSession(resolvedDocName, agentId, {- displayName: agentName,- colorSeed,- clientName,- });- const writeMdReconcile = reconcileDiskBeforeAgentWrite(- durabilityState,- hocuspocus,- resolvedDocName,- contentDir,- options.resolveEmbed,- getBridgeLossReporter?.(),- conflicts,- );- const writeMdEmbedResolver = options.resolveEmbed- ? { resolveEmbed: options.resolveEmbed, sourcePath: resolvedDocName }- : undefined;- const writeMdPrecomputed = await prepareAgentMarkdownParse(- session.dc.document,- body.markdown,- position,- writeMdEmbedResolver,- );- const timestamp = new Date().toISOString();- let writeDivergence: AgentWriteContentDivergence | undefined;- let disposeEffectCapture: (() => void) | undefined;- try {- const icon = iconFromClientName(clientName);- const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(colorSeed ?? agentId);- agentPresenceBroadcaster?.setPresence(agentId, {+ await sessionManager.withSessions(async (getSession) => {+ const session = await getSession(resolvedDocName, agentId, {displayName: agentName,- icon,- color,- currentDoc: resolvedDocName,- mode: 'writing',- ts: Date.now(),- });- disposeEffectCapture = captureEffect(- session.dc.document.getText('source'),- agentId,- session.origin,colorSeed,clientName,+ });+ const writeMdReconcile = reconcileDiskBeforeAgentWrite(+ durabilityState,+ hocuspocus,+ resolvedDocName,+ contentDir,+ options.resolveEmbed,+ getBridgeLossReporter?.(),+ conflicts,);- agentWritePreDrain(session.dc.document, body.markdown, position);- session.dc.document.transact(() => {- const beforeBlocks = snapshotBlocks(session.dc.document);- writeDivergence = applyAgentMarkdownWrite(- session.dc.document,- body.markdown,- position,- writeMdEmbedResolver,- writeMdPrecomputed,- agentWriteLossDetect(session),- suppliedWriterId,- );- const changedBlocks =- changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;- const activityMap = session.dc.document.getMap('agent-flash');- activityMap.set(agentId, {- agentId,- timestamp: Date.now(),- type: 'insert',- description: `Added (${agentName}): ${body.markdown.trim().slice(0, 50)}`,- ...(changedBlocks !== undefined ? { changedBlocks } : {}),+ const writeMdEmbedResolver = options.resolveEmbed+ ? { resolveEmbed: options.resolveEmbed, sourcePath: resolvedDocName }+ : undefined;+ const writeMdPrecomputed = await prepareAgentMarkdownParse(+ session.dc.document,+ body.markdown,+ position,+ writeMdEmbedResolver,+ );+ const timestamp = new Date().toISOString();+ let writeDivergence: AgentWriteContentDivergence | undefined;+ let disposeEffectCapture: (() => void) | undefined;+ try {+ const icon = iconFromClientName(clientName);+ const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(colorSeed ?? agentId);+ agentPresenceBroadcaster?.setPresence(agentId, {+ displayName: agentName,+ icon,+ color,+ currentDoc: resolvedDocName,+ mode: 'writing',+ ts: Date.now(),});- }, session.origin);- if (writeDivergence !== undefined) {- console.warn(- JSON.stringify({- event: 'agent-write-content-divergence',- 'doc.name': resolvedDocName,+ disposeEffectCapture = captureEffect(+ session.dc.document.getText('source'),+ agentId,+ session.origin,+ colorSeed,+ clientName,+ );+ agentWritePreDrain(session.dc.document, body.markdown, position);+ session.dc.document.transact(() => {+ const beforeBlocks = snapshotBlocks(session.dc.document);+ writeDivergence = applyAgentMarkdownWrite(+ session.dc.document,+ body.markdown,position,- intendedBytes: writeDivergence.intendedBytes,- actualBytes: writeDivergence.actualBytes,- byteDelta: writeDivergence.byteDelta,- 'agent.id': agentId,- 'agent.client_name': clientName,- }),+ writeMdEmbedResolver,+ writeMdPrecomputed,+ agentWriteLossDetect(session),+ suppliedWriterId,+ );+ const changedBlocks =+ changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;+ const activityMap = session.dc.document.getMap('agent-flash');+ activityMap.set(agentId, {+ agentId,+ timestamp: Date.now(),+ type: 'insert',+ description: `Added (${agentName}): ${body.markdown.trim().slice(0, 50)}`,+ ...(changedBlocks !== undefined ? { changedBlocks } : {}),+ });+ }, session.origin);+ if (writeDivergence !== undefined) {+ console.warn(+ JSON.stringify({+ event: 'agent-write-content-divergence',+ 'doc.name': resolvedDocName,+ position,+ intendedBytes: writeDivergence.intendedBytes,+ actualBytes: writeDivergence.actualBytes,+ byteDelta: writeDivergence.byteDelta,+ 'agent.id': agentId,+ 'agent.client_name': clientName,+ }),+ );+ }+ recordContentDivergenceGate('agent-write-md', writeDivergence);+ recordContributor(+ resolvedDocName,+ agentId,+ agentName,+ colorSeed,+ undefined,+ buildAgentActor({ clientName, clientVersion, label }),+ storedSummary,);+ incrementAgentWriteCalls();+ countNormalizedSummary(normalizedSummary);+ } finally {+ disposeEffectCapture?.();+ agentPresenceBroadcaster?.touchMode(agentId, 'idle');}- recordContentDivergenceGate('agent-write-md', writeDivergence);- recordContributor(- resolvedDocName,- agentId,+ const flushOutcome = await flushDiskAndDetectOutcome(resolvedDocName);+ if (flushOutcome?.kind === 'failure') {+ respondPersistenceFailure(res, flushOutcome.failure, 'agent-write-md');+ return;+ }+ if (flushOutcome?.kind === 'divergence') {+ respondDiskDivergence(res, 'agent-write-md');+ return;+ }+ if (flushOutcome?.kind === 'stale-external-write') {+ respondStaleExternalWrite(res, 'agent-write-md', resolvedDocName);+ return;+ }+ flushDocToDisk(resolvedDocName, 'agent-write-md');+ agentFocusBroadcaster?.setFocus(agentId, {agentName,- colorSeed,- undefined,- buildAgentActor({ clientName, clientVersion, label }),- storedSummary,- );- incrementAgentWriteCalls();- countNormalizedSummary(normalizedSummary);- } finally {- disposeEffectCapture?.();- agentPresenceBroadcaster?.touchMode(agentId, 'idle');- }- const flushOutcome = await flushDiskAndDetectOutcome(resolvedDocName);- if (flushOutcome?.kind === 'failure') {- respondPersistenceFailure(res, flushOutcome.failure, 'agent-write-md');- return;- }- if (flushOutcome?.kind === 'divergence') {- respondDiskDivergence(res, 'agent-write-md');- return;- }- if (flushOutcome?.kind === 'stale-external-write') {- respondStaleExternalWrite(res, 'agent-write-md', resolvedDocName);- return;- }- flushDocToDisk(resolvedDocName, 'agent-write-md');- agentFocusBroadcaster?.setFocus(agentId, {- agentName,- currentDoc: resolvedDocName,- writeKind: 'write',- ts: Date.now(),- });- onAgentWrite?.();- const hints = await computeOrphanHints(resolvedDocName);- const writtenSource = session.dc.document.getText('source').toString();- registerWrittenDocInFileIndex(resolvedDocName, writtenSource);- const renderWarnings = await validateMermaidFences(writtenSource, resolvedDocName);- const admittedForLinks = await collectAdmittedDocNames();- admittedForLinks.add(resolvedDocName);- const linkAdvisory = projectWriteAdvisoryLinks(- computeWriteAdvisoryLinks(- writtenSource,- resolvedDocName,- admittedForLinks,- createLinkedFileExists(),- createLinkedFolderExists(),- ),- resolvedDocName,- linkPolicy.suppressLogLinkAdvisories,- );- const subscriberCount = getSubscriberCount(resolvedDocName);- const systemSubscriberCount = getSystemSubscriberCount();- if (systemSubscriberCount === 0) {- hintEmittedCounter().add(1, {- 'shadow.writer': 'agent',- 'agent.type': resolveAgentType(clientName),+ currentDoc: resolvedDocName,+ writeKind: 'write',+ ts: Date.now(),});- }- const writeMdWarning = buildReconcileWarning(writeMdReconcile);- const writeMdDivergenceEntry =- writeDivergence !== undefined ? toContentDivergenceWarning(writeDivergence) : undefined;- const writeMdAdvisories = [- ...(writeMdDivergenceEntry ? [writeMdDivergenceEntry] : []),- ...(writeMdWarning ? [writeMdWarning] : []),- ...(renderWarnings ?? []),- ...(await computeLintViolations(- session.dc.document.getText('source').toString(),+ onAgentWrite?.();+ const hints = await computeOrphanHints(resolvedDocName);+ const writtenSource = session.dc.document.getText('source').toString();+ registerWrittenDocInFileIndex(resolvedDocName, writtenSource);+ const renderWarnings = await validateMermaidFences(writtenSource, resolvedDocName);+ const admittedForLinks = await collectAdmittedDocNames();+ admittedForLinks.add(resolvedDocName);+ const linkAdvisory = projectWriteAdvisoryLinks(+ computeWriteAdvisoryLinks(+ writtenSource,+ resolvedDocName,+ admittedForLinks,+ createLinkedFileExists(),+ createLinkedFolderExists(),+ ),resolvedDocName,- linkPolicy,- )),- ];- successResponse(- res,- 200,- AgentWriteMdSuccessSchema,- {- timestamp,- subscriberCount,- systemSubscriberCount,- ...(hints ? { hints } : {}),- ...(summaryResponse ? { summary: summaryResponse } : {}),- ...(writeMdAdvisories.length > 0 ? { warnings: writeMdAdvisories } : {}),- ...linkAdvisory,- },- { handler: 'agent-write-md' },- );+ linkPolicy.suppressLogLinkAdvisories,+ );+ const subscriberCount = getSubscriberCount(resolvedDocName);+ const systemSubscriberCount = getSystemSubscriberCount();+ if (systemSubscriberCount === 0) {+ hintEmittedCounter().add(1, {+ 'shadow.writer': 'agent',+ 'agent.type': resolveAgentType(clientName),+ });+ }+ const writeMdWarning = buildReconcileWarning(writeMdReconcile);+ const writeMdDivergenceEntry =+ writeDivergence !== undefined ? toContentDivergenceWarning(writeDivergence) : undefined;+ const writeMdAdvisories = [+ ...(writeMdDivergenceEntry ? [writeMdDivergenceEntry] : []),+ ...(writeMdWarning ? [writeMdWarning] : []),+ ...(renderWarnings ?? []),+ ...(await computeLintViolations(+ session.dc.document.getText('source').toString(),+ resolvedDocName,+ linkPolicy,+ )),+ ];+ successResponse(+ res,+ 200,+ AgentWriteMdSuccessSchema,+ {+ timestamp,+ subscriberCount,+ systemSubscriberCount,+ ...(hints ? { hints } : {}),+ ...(summaryResponse ? { summary: summaryResponse } : {}),+ ...(writeMdAdvisories.length > 0 ? { warnings: writeMdAdvisories } : {}),+ ...linkAdvisory,+ },+ { handler: 'agent-write-md' },+ );+ });} catch (e) {if (e instanceof DocInConflictError) {respondDocInConflict(@@ -563,211 +565,213 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupconst normalizedSummary = normalizeSummary(body.summary);const { response: summaryResponse, stored: storedSummary } =summaryResponseFields(normalizedSummary);- const session = await sessionManager.getSession(resolvedDocName, agentId, {- displayName: agentName,- colorSeed,- clientName,- });- const fmReconcile = reconcileDiskBeforeAgentWrite(- durabilityState,- hocuspocus,- resolvedDocName,- contentDir,- options.resolveEmbed,- getBridgeLossReporter?.(),- conflicts,- );- const fmPatchPrecomputed = await prepareFrontmatterPatchParse(session.dc.document, patch);- const timestamp = new Date().toISOString();- let editError: import('@inkeep/open-knowledge-core').FmEditError | undefined;- let applied = false;- let bodyMutated = false;- const appliedKeys: string[] = [];- try {- const icon = iconFromClientName(clientName);- const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(colorSeed ?? agentId);- agentPresenceBroadcaster?.setPresence(agentId, {+ await sessionManager.withSessions(async (getSession) => {+ const session = await getSession(resolvedDocName, agentId, {displayName: agentName,- icon,- color,- currentDoc: resolvedDocName,- mode: 'writing',- ts: Date.now(),+ colorSeed,+ clientName,});- withSpanSync(- 'ok.frontmatter_patch',- {- attributes: {- 'doc.name': resolvedDocName,- 'frontmatter_patch.keys': patchKeys.length,- },- },- () => {- session.dc.document.transact(() => {- const ytext = session.dc.document.getText('source');- const currentFull = ytext.toString();- const { fenced: currentFenced, body: currentBody } = detectFmRegion(currentFull);- const result = applyPatchToFm(currentFenced, patch);- if (!result.ok) {- editError = result.error;- return;- }- for (const key of Object.keys(patch)) {- appliedKeys.push(key);- }- if (result.nextFenced !== currentFenced) {- /**- * Routed through the sanctioned `composeAndWriteRawBody` primitive- * (precedent #38) so paired-write semantics survive.- */- const needsFenceSeparator =- currentFenced === '' && currentBody !== '' && !currentBody.startsWith('\n');- const newFull = composeWithDerivedFrontmatter(- result.nextFenced,- (needsFenceSeparator ? '\n' : '') + currentBody,- ).md;- composeAndWriteRawBody(- session.dc.document,- newFull,- 'agent',- undefined,- fmPatchPrecomputed,- );- recordFrontmatterEditSurface('mcp-write');- bodyMutated = true;- }- applied = true;- }, session.origin);- },- );- } finally {- agentPresenceBroadcaster?.touchMode(agentId, 'idle');- }- if (editError) {- let fieldErrors: Record<string, string>;- switch (editError.kind) {- case 'invalid_value':- fieldErrors = { [editError.key]: editError.reason };- break;- case 'reserved_key':- fieldErrors = { [editError.key]: `'${editError.key}' is reserved` };- break;- case 'unknown_key':- fieldErrors = { [editError.key]: `'${editError.key}' is not a recognized key` };- break;- case 'duplicate_target':- fieldErrors = { [editError.key]: `'${editError.key}' appears more than once` };- break;- case 'reorder_mismatch':- fieldErrors = {- __region__: `frontmatter reorder mismatch (expected: ${editError.expected.join(', ')}; got: ${editError.got.join(', ')})`,- };- break;- case 'region_too_large':- fieldErrors = {- __region__: `frontmatter region too large (${editError.bytes} > ${editError.limit} bytes)`,- };- break;- case 'parse_failed':- fieldErrors = { __region__: `frontmatter region unparseable: ${editError.reason}` };- break;- case 'invalid_path':- fieldErrors = {- [editError.path.map(String).join('.') || '__path__']: editError.reason,- };- break;- default: {- const _exhaustive: never = editError;- fieldErrors = {- __region__: `unhandled frontmatter edit error (${String(_exhaustive)})`,- };- }- }- errorResponse(- res,- 400,- 'urn:ok:error:invalid-frontmatter-patch',- 'Frontmatter patch rejected: schema validation failed.',- { handler: 'frontmatter-patch', extensions: { fieldErrors } },- );- return;- }- if (applied && appliedKeys.length > 0) {- recordContributor(+ const fmReconcile = reconcileDiskBeforeAgentWrite(+ durabilityState,+ hocuspocus,resolvedDocName,- agentId,- agentName,- colorSeed,- undefined,- buildAgentActor({ clientName, clientVersion, label }),- storedSummary,+ contentDir,+ options.resolveEmbed,+ getBridgeLossReporter?.(),+ conflicts,);- incrementAgentWriteCalls();- countNormalizedSummary(normalizedSummary);- if (bodyMutated) {- const flushOutcome = await flushDiskAndDetectOutcome(resolvedDocName);- if (flushOutcome?.kind === 'failure') {- respondPersistenceFailure(res, flushOutcome.failure, 'frontmatter-patch');- return;- }- if (flushOutcome?.kind === 'divergence') {- respondDiskDivergence(res, 'frontmatter-patch');- return;+ const fmPatchPrecomputed = await prepareFrontmatterPatchParse(session.dc.document, patch);+ const timestamp = new Date().toISOString();+ let editError: import('@inkeep/open-knowledge-core').FmEditError | undefined;+ let applied = false;+ let bodyMutated = false;+ const appliedKeys: string[] = [];+ try {+ const icon = iconFromClientName(clientName);+ const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(colorSeed ?? agentId);+ agentPresenceBroadcaster?.setPresence(agentId, {+ displayName: agentName,+ icon,+ color,+ currentDoc: resolvedDocName,+ mode: 'writing',+ ts: Date.now(),+ });+ withSpanSync(+ 'ok.frontmatter_patch',+ {+ attributes: {+ 'doc.name': resolvedDocName,+ 'frontmatter_patch.keys': patchKeys.length,+ },+ },+ () => {+ session.dc.document.transact(() => {+ const ytext = session.dc.document.getText('source');+ const currentFull = ytext.toString();+ const { fenced: currentFenced, body: currentBody } = detectFmRegion(currentFull);+ const result = applyPatchToFm(currentFenced, patch);+ if (!result.ok) {+ editError = result.error;+ return;+ }+ for (const key of Object.keys(patch)) {+ appliedKeys.push(key);+ }+ if (result.nextFenced !== currentFenced) {+ /**+ * Routed through the sanctioned `composeAndWriteRawBody` primitive+ * (precedent #38) so paired-write semantics survive.+ */+ const needsFenceSeparator =+ currentFenced === '' && currentBody !== '' && !currentBody.startsWith('\n');+ const newFull = composeWithDerivedFrontmatter(+ result.nextFenced,+ (needsFenceSeparator ? '\n' : '') + currentBody,+ ).md;+ composeAndWriteRawBody(+ session.dc.document,+ newFull,+ 'agent',+ undefined,+ fmPatchPrecomputed,+ );+ recordFrontmatterEditSurface('mcp-write');+ bodyMutated = true;+ }+ applied = true;+ }, session.origin);+ },+ );+ } finally {+ agentPresenceBroadcaster?.touchMode(agentId, 'idle');+ }+ if (editError) {+ let fieldErrors: Record<string, string>;+ switch (editError.kind) {+ case 'invalid_value':+ fieldErrors = { [editError.key]: editError.reason };+ break;+ case 'reserved_key':+ fieldErrors = { [editError.key]: `'${editError.key}' is reserved` };+ break;+ case 'unknown_key':+ fieldErrors = { [editError.key]: `'${editError.key}' is not a recognized key` };+ break;+ case 'duplicate_target':+ fieldErrors = { [editError.key]: `'${editError.key}' appears more than once` };+ break;+ case 'reorder_mismatch':+ fieldErrors = {+ __region__: `frontmatter reorder mismatch (expected: ${editError.expected.join(', ')}; got: ${editError.got.join(', ')})`,+ };+ break;+ case 'region_too_large':+ fieldErrors = {+ __region__: `frontmatter region too large (${editError.bytes} > ${editError.limit} bytes)`,+ };+ break;+ case 'parse_failed':+ fieldErrors = { __region__: `frontmatter region unparseable: ${editError.reason}` };+ break;+ case 'invalid_path':+ fieldErrors = {+ [editError.path.map(String).join('.') || '__path__']: editError.reason,+ };+ break;+ default: {+ const _exhaustive: never = editError;+ fieldErrors = {+ __region__: `unhandled frontmatter edit error (${String(_exhaustive)})`,+ };+ }}- if (flushOutcome?.kind === 'stale-external-write') {- respondStaleExternalWrite(res, 'frontmatter-patch', resolvedDocName);- return;+ errorResponse(+ res,+ 400,+ 'urn:ok:error:invalid-frontmatter-patch',+ 'Frontmatter patch rejected: schema validation failed.',+ { handler: 'frontmatter-patch', extensions: { fieldErrors } },+ );+ return;+ }+ if (applied && appliedKeys.length > 0) {+ recordContributor(+ resolvedDocName,+ agentId,+ agentName,+ colorSeed,+ undefined,+ buildAgentActor({ clientName, clientVersion, label }),+ storedSummary,+ );+ incrementAgentWriteCalls();+ countNormalizedSummary(normalizedSummary);+ if (bodyMutated) {+ const flushOutcome = await flushDiskAndDetectOutcome(resolvedDocName);+ if (flushOutcome?.kind === 'failure') {+ respondPersistenceFailure(res, flushOutcome.failure, 'frontmatter-patch');+ return;+ }+ if (flushOutcome?.kind === 'divergence') {+ respondDiskDivergence(res, 'frontmatter-patch');+ return;+ }+ if (flushOutcome?.kind === 'stale-external-write') {+ respondStaleExternalWrite(res, 'frontmatter-patch', resolvedDocName);+ return;+ }}+ flushDocToDisk(resolvedDocName, 'frontmatter-patch');}- flushDocToDisk(resolvedDocName, 'frontmatter-patch');- }- agentFocusBroadcaster?.setFocus(agentId, {- agentName,- currentDoc: resolvedDocName,- writeKind: 'write',- ts: Date.now(),- });- onAgentWrite?.();- const subscriberCount = getSubscriberCount(resolvedDocName);- const systemSubscriberCount = getSystemSubscriberCount();- if (systemSubscriberCount === 0) {- hintEmittedCounter().add(1, {- 'shadow.writer': 'agent',- 'agent.type': resolveAgentType(clientName),+ agentFocusBroadcaster?.setFocus(agentId, {+ agentName,+ currentDoc: resolvedDocName,+ writeKind: 'write',+ ts: Date.now(),});- }- const fmWarning = buildReconcileWarning(fmReconcile);- registerWrittenDocInFileIndex(- resolvedDocName,- session.dc.document.getText('source').toString(),- );- const admittedForLinks = await collectAdmittedDocNames();- admittedForLinks.add(resolvedDocName);- const linkAdvisory = projectWriteAdvisoryLinks(- computeWriteAdvisoryLinks(+ onAgentWrite?.();+ const subscriberCount = getSubscriberCount(resolvedDocName);+ const systemSubscriberCount = getSystemSubscriberCount();+ if (systemSubscriberCount === 0) {+ hintEmittedCounter().add(1, {+ 'shadow.writer': 'agent',+ 'agent.type': resolveAgentType(clientName),+ });+ }+ const fmWarning = buildReconcileWarning(fmReconcile);+ registerWrittenDocInFileIndex(+ resolvedDocName,session.dc.document.getText('source').toString(),+ );+ const admittedForLinks = await collectAdmittedDocNames();+ admittedForLinks.add(resolvedDocName);+ const linkAdvisory = projectWriteAdvisoryLinks(+ computeWriteAdvisoryLinks(+ session.dc.document.getText('source').toString(),+ resolvedDocName,+ admittedForLinks,+ createLinkedFileExists(),+ ),resolvedDocName,- admittedForLinks,- createLinkedFileExists(),- ),- resolvedDocName,- linkPolicy.suppressLogLinkAdvisories,- );- successResponse(- res,- 200,- FrontmatterPatchSuccessSchema,- {- timestamp,- subscriberCount,- systemSubscriberCount,- appliedKeys,- ...(summaryResponse ? { summary: summaryResponse } : {}),- ...(fmWarning ? { warnings: [fmWarning] } : {}),- ...linkAdvisory,- },- { handler: 'frontmatter-patch' },- );+ linkPolicy.suppressLogLinkAdvisories,+ );+ successResponse(+ res,+ 200,+ FrontmatterPatchSuccessSchema,+ {+ timestamp,+ subscriberCount,+ systemSubscriberCount,+ appliedKeys,+ ...(summaryResponse ? { summary: summaryResponse } : {}),+ ...(fmWarning ? { warnings: [fmWarning] } : {}),+ ...linkAdvisory,+ },+ { handler: 'frontmatter-patch' },+ );+ });} catch (e) {if (e instanceof AgentSessionCapacityError) {errorResponse(@@ -818,278 +822,286 @@ export function createAgentWriteRoutes(deps: AgentWriteRouteDeps): ApiRouteGroupreturn;}const normalizedSummary = normalizeSummary(body.summary);- const session = await sessionManager.getSession(docName, agentId, {- displayName: agentName,- colorSeed,- clientName,- });- const patchReconcile = reconcileDiskBeforeAgentWrite(- durabilityState,- hocuspocus,- docName,- contentDir,- options.resolveEmbed,- getBridgeLossReporter?.(),- conflicts,- );- const patchEmbedResolver = options.resolveEmbed- ? { resolveEmbed: options.resolveEmbed, sourcePath: docName }- : undefined;- let patchPrecomputed: PrecomputedParse | undefined;- {- const preSnapshot = session.dc.document.getText('source').toString();- const { frontmatter: preFm, body: preBody } = stripFrontmatter(preSnapshot);- const preFull = prependFrontmatter(preFm, preBody);- const prePos =- offset == null- ? preFull.indexOf(find)- : preFull.slice(offset, offset + find.length) === find- ? offset- : -1;- if (prePos !== -1 && prePos >= preFm.length) {- const guessFull =- preFull.slice(0, prePos) + replace + preFull.slice(prePos + find.length);- patchPrecomputed = await prepareAgentMarkdownParse(- session.dc.document,- stripFrontmatter(guessFull).body,- 'patch',- patchEmbedResolver,- );- }- }- const timestamp = new Date().toISOString();- let notFound = false;- let staleTarget = false;- let fmIntersect = false;- let fmPromoted = false;- let patchDivergence: AgentWriteContentDivergence | undefined;- let disposeEffectCapture: (() => void) | undefined;- try {- const icon = iconFromClientName(clientName);- const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(colorSeed ?? agentId);- agentPresenceBroadcaster?.setPresence(agentId, {+ await sessionManager.withSessions(async (getSession) => {+ const session = await getSession(docName, agentId, {displayName: agentName,- icon,- color,- currentDoc: docName,- mode: 'writing',- ts: Date.now(),- });- disposeEffectCapture = captureEffect(- session.dc.document.getText('source'),- agentId,- session.origin,colorSeed,clientName,+ });+ const patchReconcile = reconcileDiskBeforeAgentWrite(+ durabilityState,+ hocuspocus,+ docName,+ contentDir,+ options.resolveEmbed,+ getBridgeLossReporter?.(),+ conflicts,);- session.dc.document.transact(() => {- /**- * Read current authoritative state from Y.Text, the user's intended source-form bytes- * (Y.Text-is-truth, precedent #38); `serialize(fragment)` would compute offsets against- * canonical bytes instead.- */- const ytextSnapshot = session.dc.document.getText('source').toString();- const { frontmatter: currentFm, body: currentBody } = stripFrontmatter(ytextSnapshot);- const currentFull = prependFrontmatter(currentFm, currentBody);- const pos =+ const patchEmbedResolver = options.resolveEmbed+ ? { resolveEmbed: options.resolveEmbed, sourcePath: docName }+ : undefined;+ let patchPrecomputed: PrecomputedParse | undefined;+ {+ const preSnapshot = session.dc.document.getText('source').toString();+ const { frontmatter: preFm, body: preBody } = stripFrontmatter(preSnapshot);+ const preFull = prependFrontmatter(preFm, preBody);+ const prePos =offset == null- ? currentFull.indexOf(find)- : currentFull.slice(offset, offset + find.length) === find+ ? preFull.indexOf(find)+ : preFull.slice(offset, offset + find.length) === find? offset: -1;- if (pos === -1) {- if (offset == null) {- notFound = true;- } else {- staleTarget = true;+ if (prePos !== -1 && prePos >= preFm.length) {+ const guessFull =+ preFull.slice(0, prePos) + replace + preFull.slice(prePos + find.length);+ patchPrecomputed = await prepareAgentMarkdownParse(+ session.dc.document,+ stripFrontmatter(guessFull).body,+ 'patch',+ patchEmbedResolver,+ );+ }+ }+ const timestamp = new Date().toISOString();+ let notFound = false;+ let staleTarget = false;+ let fmIntersect = false;+ let fmPromoted = false;+ let patchDivergence: AgentWriteContentDivergence | undefined;+ let disposeEffectCapture: (() => void) | undefined;+ try {+ const icon = iconFromClientName(clientName);+ const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(colorSeed ?? agentId);+ agentPresenceBroadcaster?.setPresence(agentId, {+ displayName: agentName,+ icon,+ color,+ currentDoc: docName,+ mode: 'writing',+ ts: Date.now(),+ });+ disposeEffectCapture = captureEffect(+ session.dc.document.getText('source'),+ agentId,+ session.origin,+ colorSeed,+ clientName,+ );+ session.dc.document.transact(() => {+ /**+ * Read current authoritative state from Y.Text, the user's intended source-form bytes+ * (Y.Text-is-truth, precedent #38); `serialize(fragment)` would compute offsets against+ * canonical bytes instead.+ */+ const ytextSnapshot = session.dc.document.getText('source').toString();+ const { frontmatter: currentFm, body: currentBody } = stripFrontmatter(ytextSnapshot);+ const currentFull = prependFrontmatter(currentFm, currentBody);+ const pos =+ offset == null+ ? currentFull.indexOf(find)+ : currentFull.slice(offset, offset + find.length) === find+ ? offset+ : -1;+ if (pos === -1) {+ if (offset == null) {+ notFound = true;+ } else {+ staleTarget = true;+ }+ console.warn(+ JSON.stringify({+ event: 'agent-patch-find-mismatch',+ 'doc.name': docName,+ findLength: find.length,+ replaceLength: replace.length,+ hadOffset: offset != null,+ }),+ );+ incrementAgentPatchFindMismatches();+ return;+ }+ if (pos < currentFm.length) {+ fmIntersect = true;+ return;}+ const newFull =+ currentFull.slice(0, pos) + replace + currentFull.slice(pos + find.length);+ if (currentFm === '' && stripFrontmatter(newFull).frontmatter !== '') {+ fmPromoted = true;+ return;+ }+ const { body: newBody } = stripFrontmatter(newFull);+ const beforeBlocks = snapshotBlocks(session.dc.document);+ patchDivergence = applyAgentMarkdownWrite(+ session.dc.document,+ newBody,+ 'patch',+ patchEmbedResolver,+ patchPrecomputed,+ agentWriteLossDetect(session),+ suppliedWriterId,+ );+ const changedBlocks =+ changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;+ const activityMap = session.dc.document.getMap('agent-flash');+ activityMap.set(agentId, {+ agentId,+ timestamp: Date.now(),+ type: 'insert',+ description: `Patched (${agentName}): ${find.slice(0, 50)}`,+ ...(changedBlocks !== undefined ? { changedBlocks } : {}),+ });+ }, session.origin);+ if (patchDivergence !== undefined) {console.warn(JSON.stringify({- event: 'agent-patch-find-mismatch',+ event: 'agent-write-content-divergence','doc.name': docName,- findLength: find.length,- replaceLength: replace.length,- hadOffset: offset != null,+ position: 'patch',+ intendedBytes: patchDivergence.intendedBytes,+ actualBytes: patchDivergence.actualBytes,+ byteDelta: patchDivergence.byteDelta,+ 'agent.id': agentId,+ 'agent.client_name': clientName,}),);- incrementAgentPatchFindMismatches();- return;}- if (pos < currentFm.length) {- fmIntersect = true;- return;- }- const newFull =- currentFull.slice(0, pos) + replace + currentFull.slice(pos + find.length);- if (currentFm === '' && stripFrontmatter(newFull).frontmatter !== '') {- fmPromoted = true;- return;+ if (!notFound && !staleTarget && !fmIntersect && !fmPromoted) {+ const { stored: storedSummary } = summaryResponseFields(normalizedSummary);+ recordContributor(+ docName,+ agentId,+ agentName,+ colorSeed,+ undefined,+ buildAgentActor({ clientName, clientVersion, label }),+ storedSummary,+ );+ incrementAgentWriteCalls();+ countNormalizedSummary(normalizedSummary);+ recordContentDivergenceGate('agent-patch', patchDivergence);}- const { body: newBody } = stripFrontmatter(newFull);- const beforeBlocks = snapshotBlocks(session.dc.document);- patchDivergence = applyAgentMarkdownWrite(- session.dc.document,- newBody,- 'patch',- patchEmbedResolver,- patchPrecomputed,- agentWriteLossDetect(session),- suppliedWriterId,+ } finally {+ disposeEffectCapture?.();+ agentPresenceBroadcaster?.touchMode(agentId, 'idle');+ }+ if (staleTarget) {+ errorResponse(+ res,+ 409,+ 'urn:ok:error:stale-target',+ 'Target text no longer matches at the requested offset.',+ { handler: 'agent-patch' },);- const changedBlocks =- changedBlockRange(beforeBlocks, snapshotBlocks(session.dc.document)) ?? undefined;- const activityMap = session.dc.document.getMap('agent-flash');- activityMap.set(agentId, {- agentId,- timestamp: Date.now(),- type: 'insert',- description: `Patched (${agentName}): ${find.slice(0, 50)}`,- ...(changedBlocks !== undefined ? { changedBlocks } : {}),- });- }, session.origin);- if (patchDivergence !== undefined) {- console.warn(- JSON.stringify({- event: 'agent-write-content-divergence',- 'doc.name': docName,- position: 'patch',- intendedBytes: patchDivergence.intendedBytes,- actualBytes: patchDivergence.actualBytes,- byteDelta: patchDivergence.byteDelta,- 'agent.id': agentId,- 'agent.client_name': clientName,- }),+ return;+ }+ if (notFound) {+ errorResponse(+ res,+ 404,+ 'urn:ok:error:target-not-found',+ 'Text not found in document.',+ {+ handler: 'agent-patch',+ },);+ return;}- if (!notFound && !staleTarget && !fmIntersect && !fmPromoted) {- const { stored: storedSummary } = summaryResponseFields(normalizedSummary);- recordContributor(- docName,- agentId,- agentName,- colorSeed,- undefined,- buildAgentActor({ clientName, clientVersion, label }),- storedSummary,+ if (fmIntersect) {+ agentPatchFmTouchCounter().add(1, { result: 'rejected', reason: 'intersect' });+ errorResponse(+ res,+ 400,+ 'urn:ok:error:frontmatter-edit-not-supported',+ 'Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.',+ { handler: 'agent-patch' },);- incrementAgentWriteCalls();- countNormalizedSummary(normalizedSummary);- recordContentDivergenceGate('agent-patch', patchDivergence);+ return;}- } finally {- disposeEffectCapture?.();- agentPresenceBroadcaster?.touchMode(agentId, 'idle');- }- if (staleTarget) {- errorResponse(- res,- 409,- 'urn:ok:error:stale-target',- 'Target text no longer matches at the requested offset.',- { handler: 'agent-patch' },- );- return;- }- if (notFound) {- errorResponse(res, 404, 'urn:ok:error:target-not-found', 'Text not found in document.', {- handler: 'agent-patch',+ if (fmPromoted) {+ agentPatchFmTouchCounter().add(1, { result: 'rejected', reason: 'promoted' });+ errorResponse(+ res,+ 400,+ 'urn:ok:error:frontmatter-edit-not-supported',+ "This edit would turn the replacement text into the document's frontmatter: the document has no frontmatter, the match starts at byte 0, and `replace` opens a `---` fence pair — so the composed document would re-read that block as its YAML region. Use edit({ document: { path, frontmatter } }) to set frontmatter, or keep the `---` out of the first line (a leading blank line, or `***` / `___` for a thematic break).",+ { handler: 'agent-patch' },+ );+ return;+ }+ const flushOutcome = await flushDiskAndDetectOutcome(docName);+ if (flushOutcome?.kind === 'failure') {+ respondPersistenceFailure(res, flushOutcome.failure, 'agent-patch');+ return;+ }+ if (flushOutcome?.kind === 'divergence') {+ respondDiskDivergence(res, 'agent-patch');+ return;+ }+ if (flushOutcome?.kind === 'stale-external-write') {+ respondStaleExternalWrite(res, 'agent-patch', docName);+ return;+ }+ flushDocToDisk(docName, 'agent-patch');+ agentFocusBroadcaster?.setFocus(agentId, {+ agentName,+ currentDoc: docName,+ writeKind: 'edit',+ ts: Date.now(),});- return;- }- if (fmIntersect) {- agentPatchFmTouchCounter().add(1, { result: 'rejected', reason: 'intersect' });- errorResponse(- res,- 400,- 'urn:ok:error:frontmatter-edit-not-supported',- 'Frontmatter edits are not supported via a body find/replace. Use edit({ document: { path, frontmatter } }) to change frontmatter, or write({ document: { path, content, position: "replace" } }) to rewrite the whole document including its YAML block.',- { handler: 'agent-patch' },+ onAgentWrite?.();+ const subscriberCount = getSubscriberCount(docName);+ const systemSubscriberCount = getSystemSubscriberCount();+ if (systemSubscriberCount === 0) {+ hintEmittedCounter().add(1, {+ 'shadow.writer': 'agent',+ 'agent.type': resolveAgentType(clientName),+ });+ }+ const { response: summaryResponse } = summaryResponseFields(normalizedSummary);+ const patchedSource = session.dc.document.getText('source').toString();+ registerWrittenDocInFileIndex(docName, patchedSource);+ const renderWarnings = await validateMermaidFences(patchedSource, docName);+ const admittedForLinks = await collectAdmittedDocNames();+ admittedForLinks.add(docName);+ const linkAdvisory = projectWriteAdvisoryLinks(+ computeWriteAdvisoryLinks(+ patchedSource,+ docName,+ admittedForLinks,+ createLinkedFileExists(),+ ),+ docName,+ linkPolicy.suppressLogLinkAdvisories,);- return;- }- if (fmPromoted) {- agentPatchFmTouchCounter().add(1, { result: 'rejected', reason: 'promoted' });- errorResponse(+ const patchWarning = buildReconcileWarning(patchReconcile);+ const patchDivergenceEntry =+ patchDivergence !== undefined ? toContentDivergenceWarning(patchDivergence) : undefined;+ const patchAdvisories = [+ ...(patchDivergenceEntry ? [patchDivergenceEntry] : []),+ ...(patchWarning ? [patchWarning] : []),+ ...(renderWarnings ?? []),+ ...(await computeLintViolations(+ session.dc.document.getText('source').toString(),+ docName,+ linkPolicy,+ )),+ ];+ successResponse(res,- 400,- 'urn:ok:error:frontmatter-edit-not-supported',- "This edit would turn the replacement text into the document's frontmatter: the document has no frontmatter, the match starts at byte 0, and `replace` opens a `---` fence pair — so the composed document would re-read that block as its YAML region. Use edit({ document: { path, frontmatter } }) to set frontmatter, or keep the `---` out of the first line (a leading blank line, or `***` / `___` for a thematic break).",+ 200,+ AgentPatchSuccessSchema,+ {+ timestamp,+ subscriberCount,+ systemSubscriberCount,+ ...(summaryResponse ? { summary: summaryResponse } : {}),+ ...(patchAdvisories.length > 0 ? { warnings: patchAdvisories } : {}),+ ...linkAdvisory,+ },{ handler: 'agent-patch' },);- return;- }- const flushOutcome = await flushDiskAndDetectOutcome(docName);- if (flushOutcome?.kind === 'failure') {- respondPersistenceFailure(res, flushOutcome.failure, 'agent-patch');- return;- }- if (flushOutcome?.kind === 'divergence') {- respondDiskDivergence(res, 'agent-patch');- return;- }- if (flushOutcome?.kind === 'stale-external-write') {- respondStaleExternalWrite(res, 'agent-patch', docName);- return;- }- flushDocToDisk(docName, 'agent-patch');- agentFocusBroadcaster?.setFocus(agentId, {- agentName,- currentDoc: docName,- writeKind: 'edit',- ts: Date.now(),});- onAgentWrite?.();- const subscriberCount = getSubscriberCount(docName);- const systemSubscriberCount = getSystemSubscriberCount();- if (systemSubscriberCount === 0) {- hintEmittedCounter().add(1, {- 'shadow.writer': 'agent',- 'agent.type': resolveAgentType(clientName),- });- }- const { response: summaryResponse } = summaryResponseFields(normalizedSummary);- const patchedSource = session.dc.document.getText('source').toString();- registerWrittenDocInFileIndex(docName, patchedSource);- const renderWarnings = await validateMermaidFences(patchedSource, docName);- const admittedForLinks = await collectAdmittedDocNames();- admittedForLinks.add(docName);- const linkAdvisory = projectWriteAdvisoryLinks(- computeWriteAdvisoryLinks(- patchedSource,- docName,- admittedForLinks,- createLinkedFileExists(),- ),- docName,- linkPolicy.suppressLogLinkAdvisories,- );- const patchWarning = buildReconcileWarning(patchReconcile);- const patchDivergenceEntry =- patchDivergence !== undefined ? toContentDivergenceWarning(patchDivergence) : undefined;- const patchAdvisories = [- ...(patchDivergenceEntry ? [patchDivergenceEntry] : []),- ...(patchWarning ? [patchWarning] : []),- ...(renderWarnings ?? []),- ...(await computeLintViolations(- session.dc.document.getText('source').toString(),- docName,- linkPolicy,- )),- ];- successResponse(- res,- 200,- AgentPatchSuccessSchema,- {- timestamp,- subscriberCount,- systemSubscriberCount,- ...(summaryResponse ? { summary: summaryResponse } : {}),- ...(patchAdvisories.length > 0 ? { warnings: patchAdvisories } : {}),- ...linkAdvisory,- },- { handler: 'agent-patch' },- );} catch (e) {if (e instanceof DocInConflictError) {respondDocInConflict(diff --git a/packages/server/src/http/lint-write-routes.ts b/packages/server/src/http/lint-write-routes.tsindex efd606075..4a9c01363 100644--- a/packages/server/src/http/lint-write-routes.ts+++ b/packages/server/src/http/lint-write-routes.ts@@ -318,164 +318,166 @@ export function createLintWriteRoutes(deps: LintWriteRouteDeps): ApiRouteGroup {const baseConfig = getLinterBaseConfig?.() ?? DEFAULT_LINTER_CONFIG;const { stored: storedSummary } = summaryResponseFields(actor.summary);- const session = await sessionManager.getSession(resolvedDocName, agentId, {- displayName: agentName,- colorSeed,- clientName,- });+ await sessionManager.withSessions(async (getSession) => {+ const session = await getSession(resolvedDocName, agentId, {+ displayName: agentName,+ colorSeed,+ clientName,+ });- const source = session.dc.document.getText('source').toString();- const configWarnings: string[] = [];- const { cfg, before, fixed, ran, failures } = await lintAndFixSource({- projectDir: projectDir ?? contentDir,- contentDir,- baseConfig,- docRelPath,- source,- onConfigProblem: (problem) => configWarnings.push(problem),- });+ const source = session.dc.document.getText('source').toString();+ const configWarnings: string[] = [];+ const { cfg, before, fixed, ran, failures } = await lintAndFixSource({+ projectDir: projectDir ?? contentDir,+ contentDir,+ baseConfig,+ docRelPath,+ source,+ onConfigProblem: (problem) => configWarnings.push(problem),+ });- let after = before;- let reLintFailure: ReLintFailure | undefined;- const reLintFailures: LintPluginFailure[] = [];- if (fixed !== source) {- try {- const icon = iconFromClientName(clientName);- const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(colorSeed ?? agentId);- agentPresenceBroadcaster?.setPresence(agentId, {- displayName: agentName,- icon,- color,- currentDoc: resolvedDocName,- mode: 'writing',- ts: Date.now(),- });- const suppliedWriterId = sessionWriterId(session);- session.dc.document.transact(() => {- applyAgentMarkdownWrite(- session.dc.document,- fixed,- 'patch',- options.resolveEmbed- ? { resolveEmbed: options.resolveEmbed, sourcePath: resolvedDocName }- : undefined,- undefined,- agentWriteLossDetect(session),- suppliedWriterId,- );- }, session.origin);+ let after = before;+ let reLintFailure: ReLintFailure | undefined;+ const reLintFailures: LintPluginFailure[] = [];+ if (fixed !== source) {+ try {+ const icon = iconFromClientName(clientName);+ const color = AGENT_ICON_COLORS[icon] ?? colorFromSeed(colorSeed ?? agentId);+ agentPresenceBroadcaster?.setPresence(agentId, {+ displayName: agentName,+ icon,+ color,+ currentDoc: resolvedDocName,+ mode: 'writing',+ ts: Date.now(),+ });+ const suppliedWriterId = sessionWriterId(session);+ session.dc.document.transact(() => {+ applyAgentMarkdownWrite(+ session.dc.document,+ fixed,+ 'patch',+ options.resolveEmbed+ ? { resolveEmbed: options.resolveEmbed, sourcePath: resolvedDocName }+ : undefined,+ undefined,+ agentWriteLossDetect(session),+ suppliedWriterId,+ );+ }, session.origin);- if (actor.kind !== 'anonymous') {- recordContributor(- resolvedDocName,- agentId,- agentName,- colorSeed,- undefined,- actor.kind === 'agent'- ? buildAgentActor({- clientName: actor.clientName,- clientVersion: actor.clientVersion,- label: actor.label,- })- : actor.actor,- storedSummary,- );+ if (actor.kind !== 'anonymous') {+ recordContributor(+ resolvedDocName,+ agentId,+ agentName,+ colorSeed,+ undefined,+ actor.kind === 'agent'+ ? buildAgentActor({+ clientName: actor.clientName,+ clientVersion: actor.clientVersion,+ label: actor.label,+ })+ : actor.actor,+ storedSummary,+ );+ }+ } finally {+ agentPresenceBroadcaster?.touchMode(agentId, 'idle');}- } finally {- agentPresenceBroadcaster?.touchMode(agentId, 'idle');- }- const flushOutcome = await flushDiskAndDetectOutcome(resolvedDocName);- if (flushOutcome?.kind === 'failure') {- respondPersistenceFailure(res, flushOutcome.failure, 'lint-fix');- return;- }- if (flushOutcome?.kind === 'divergence') {- respondDiskDivergence(res, 'lint-fix');- return;- }- if (flushOutcome?.kind === 'stale-external-write') {- respondStaleExternalWrite(res, 'lint-fix', resolvedDocName);- return;+ const flushOutcome = await flushDiskAndDetectOutcome(resolvedDocName);+ if (flushOutcome?.kind === 'failure') {+ respondPersistenceFailure(res, flushOutcome.failure, 'lint-fix');+ return;+ }+ if (flushOutcome?.kind === 'divergence') {+ respondDiskDivergence(res, 'lint-fix');+ return;+ }+ if (flushOutcome?.kind === 'stale-external-write') {+ respondStaleExternalWrite(res, 'lint-fix', resolvedDocName);+ return;+ }+ flushDocToDisk(resolvedDocName, 'lint-fix');++ try {+ after = await lintDocument(+ session.dc.document.getText('source').toString(),+ cfg,+ docRelPath,+ (failure) => reLintFailures.push(failure),+ );+ } catch (relintErr) {+ const relintMessage =+ relintErr instanceof Error ? relintErr.message : String(relintErr);+ reLintFailure = {+ reason: 're-lint-threw',+ message:+ relintMessage.trim().length > 0+ ? relintMessage+ : `${relintErr instanceof Error ? relintErr.name : 'non-Error value'} thrown with no message`,+ };+ log.warn(+ { err: relintErr, handler: 'lint-fix', doc: resolvedDocName, agentId },+ 'post-write re-lint failed; reporting pre-fix diagnostics',+ );+ after = before;+ }}- flushDocToDisk(resolvedDocName, 'lint-fix');- try {- after = await lintDocument(- session.dc.document.getText('source').toString(),- cfg,- docRelPath,- (failure) => reLintFailures.push(failure),- );- } catch (relintErr) {- const relintMessage =- relintErr instanceof Error ? relintErr.message : String(relintErr);+ const blindBeforeFix = new Set(+ failures.filter((f) => f.phase === 'lint').map((f) => f.source),+ );+ const blindOnlyAfterFix = [+ ...new Set(+ reLintFailures+ .filter((f) => f.phase === 'lint' && !blindBeforeFix.has(f.source))+ .map((f) => f.source),+ ),+ ];+ if (reLintFailure === undefined && blindOnlyAfterFix.length > 0) {reLintFailure = {- reason: 're-lint-threw',- message:- relintMessage.trim().length > 0- ? relintMessage- : `${relintErr instanceof Error ? relintErr.name : 'non-Error value'} thrown with no message`,+ reason: 'source-went-blind',+ message: `${blindOnlyAfterFix.join(', ')} linted the pre-fix text and failed on the post-fix text, so the re-lint is short their diagnostics and cannot be compared against the pre-fix run`,};log.warn(- { err: relintErr, handler: 'lint-fix', doc: resolvedDocName, agentId },- 'post-write re-lint failed; reporting pre-fix diagnostics',+ { handler: 'lint-fix', doc: resolvedDocName, agentId, sources: blindOnlyAfterFix },+ 'post-write re-lint lost a source that linted before the fix; reporting pre-fix diagnostics',);after = before;}- }- const blindBeforeFix = new Set(- failures.filter((f) => f.phase === 'lint').map((f) => f.source),- );- const blindOnlyAfterFix = [- ...new Set(- reLintFailures- .filter((f) => f.phase === 'lint' && !blindBeforeFix.has(f.source))- .map((f) => f.source),- ),- ];- if (reLintFailure === undefined && blindOnlyAfterFix.length > 0) {- reLintFailure = {- reason: 'source-went-blind',- message: `${blindOnlyAfterFix.join(', ')} linted the pre-fix text and failed on the post-fix text, so the re-lint is short their diagnostics and cannot be compared against the pre-fix run`,- };- log.warn(- { handler: 'lint-fix', doc: resolvedDocName, agentId, sources: blindOnlyAfterFix },- 'post-write re-lint lost a source that linted before the fix; reporting pre-fix diagnostics',+ const errorCount = after.filter((d) => d.severity === 'error').length;+ const warningCount = after.length - errorCount;+ const comparable = (d: (typeof before)[number]) => !blindBeforeFix.has(d.source);+ const fixedCount = Math.max(+ 0,+ before.filter(comparable).length - after.filter(comparable).length,);- after = before;- }-- const errorCount = after.filter((d) => d.severity === 'error').length;- const warningCount = after.length - errorCount;- const comparable = (d: (typeof before)[number]) => !blindBeforeFix.has(d.source);- const fixedCount = Math.max(- 0,- before.filter(comparable).length - after.filter(comparable).length,- );- const responseWarnings = [- ...configWarnings,- ...summarizeLintPluginFailures([...failures, ...reLintFailures]),- ];+ const responseWarnings = [+ ...configWarnings,+ ...summarizeLintPluginFailures([...failures, ...reLintFailures]),+ ];- successResponse(- res,- 200,- LintFixResultSchema,- {- file: docRelPath,- fixedCount,- diagnostics: after,- errorCount,- warningCount,- ran,- ...(responseWarnings.length > 0 ? { warnings: responseWarnings } : {}),- ...(reLintFailure ? { diagnosticsArePreFix: true, reLintFailure } : {}),- },- { handler: 'lint-fix' },- );+ successResponse(+ res,+ 200,+ LintFixResultSchema,+ {+ file: docRelPath,+ fixedCount,+ diagnostics: after,+ errorCount,+ warningCount,+ ran,+ ...(responseWarnings.length > 0 ? { warnings: responseWarnings } : {}),+ ...(reLintFailure ? { diagnosticsArePreFix: true, reLintFailure } : {}),+ },+ { handler: 'lint-fix' },+ );+ });} catch (e) {if (isContainmentRejection(e)) {errorResponse(res, 400, 'urn:ok:error:path-escape', 'Path escape detected.', {