Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

fix(node-services): keep Wiki consolidation merges when Claude stringifies actions

muterCcf41595a4dac
diff --git a/apps/node-services/src/llm-wiki/AGENTS.md b/apps/node-services/src/llm-wiki/AGENTS.md
index 6e2019fa..15e81719 100644
--- a/apps/node-services/src/llm-wiki/AGENTS.md
+++ b/apps/node-services/src/llm-wiki/AGENTS.md
@@ -70,7 +70,8 @@
the sources it never ran as deferred,
`agent-wiki-backend.ts` generates with the memory Agent (`src/memory-agent.ts`):
routing over candidate entities, meeting Session pages, one consolidation
- call that merges the new entities parallel routing named more than once,
+ call per entity type, run in parallel and retried once on failure, that
+ merges the new entities parallel routing named more than once,
entity pages written in batches, one correction round; `wiki-candidate-*.ts` validate and recover
candidates. Room chats get no Session page.
- `actor-wiki/` holds the operation directory state and the candidate tree
diff --git a/apps/node-services/src/llm-wiki/agent-wiki-backend.ts b/apps/node-services/src/llm-wiki/agent-wiki-backend.ts
index 1ca1447c..23f985e0 100644
--- a/apps/node-services/src/llm-wiki/agent-wiki-backend.ts
+++ b/apps/node-services/src/llm-wiki/agent-wiki-backend.ts
@@ -126,6 +126,8 @@ const MAX_BATCH_PAGES = 5;
const MAX_CANDIDATES = 40;
/** Existing entities the consolidation step sees. */
const MAX_CONSOLIDATION_PAGES = 300;
+/** Calls one type's consolidation may take when a call fails. */
+const CONSOLIDATION_ATTEMPTS = 2;
type EntityTypeId = Exclude<PersonalWikiNodeTypeId, "session">;
@@ -1217,18 +1219,51 @@ ${renderExcerpts(
return [...issues, ...inspection.issues];
}
- /** Records routed entities; a new name that matches a page joins that page. */
/**
* Parallel routing tasks name new entities without seeing each other, so
- * one entity can arrive under two names. Before any page is written, one
- * call reads every new entity routed this run beside the existing pages and
- * merges each group that names one entity, the way OpenWiki settles its
- * whole page plan before writing. It reports how many entities it merged
- * away; a failed call leaves the routing as it is.
+ * one entity can arrive under two names. Before any page is written, this
+ * merges each group that names one entity. It settles each type's new
+ * entities in its own call: types never merge, and a short list keeps each
+ * reply small. Types run in parallel; a type whose call fails is tried once
+ * more from the entities still unmerged.
*/
async #consolidate(): Promise<number> {
- const fresh = [...this.#todos.entries()].filter(([, todo]) => !todo.page);
- if (fresh.length < 2 || this.#expired()) return 0;
+ if (this.#expired()) return 0;
+ const types = PERSONAL_WIKI_ENTITY_TYPES.map(
+ (definition) => definition.id as EntityTypeId,
+ ).filter((type) => {
+ const fresh = this.#freshEntities(type).length;
+ return (
+ fresh > 1 ||
+ (fresh === 1 && this.entities.some((entry) => entry.type === type))
+ );
+ });
+ const merged = await Promise.all(
+ types.map(async (type) => {
+ let total = 0;
+ for (let attempt = 1; attempt <= CONSOLIDATION_ATTEMPTS; attempt += 1) {
+ const result = await this.#consolidateType(type, attempt);
+ total += result.merged;
+ if (!result.failed || this.#expired()) break;
+ }
+ return total;
+ }),
+ );
+ return merged.reduce((sum, count) => sum + count, 0);
+ }
+
+ /** New entities of one type that no page holds yet, in routing order. */
+ #freshEntities(type: EntityTypeId): Array<[string, EntityTodo]> {
+ return [...this.#todos.entries()].filter(
+ ([, todo]) => !todo.page && todo.type === type,
+ );
+ }
+
+ async #consolidateType(
+ type: EntityTypeId,
+ attempt: number,
+ ): Promise<{ merged: number; failed: boolean }> {
+ const fresh = this.#freshEntities(type);
const listing = fresh
.map(
([, todo], index) =>
@@ -1236,15 +1271,19 @@ ${renderExcerpts(
)
.join("\n");
const registry = renderEntityRegistry(
- this.entities.slice(0, MAX_CONSOLIDATION_PAGES),
+ this.entities
+ .filter((entry) => entry.type === type)
+ .slice(0, MAX_CONSOLIDATION_PAGES),
);
const merged = new Set<number>();
+ const step = `consolidate:${type}:${attempt}`;
const startedAt = Date.now();
+ let failed = false;
try {
- const result = await this.#chain!("consolidate", (model) =>
+ const result = await this.#chain!(step, (model) =>
runAgentTask({
model,
- step: "consolidate",
+ step,
task: consolidateTask(),
maxInputTokens: this.loopTokens,
deadline: this.request.deadline,
@@ -1262,16 +1301,25 @@ ${renderExcerpts(
signal: this.signal,
}),
);
- this.#logTask("wiki.consolidate", result, startedAt);
+ this.#logTask(`wiki.consolidate.${type}`, result, startedAt);
} catch (error) {
if (this.signal.aborted) throw error;
+ failed = true;
writeWikiLog(
"wiki_consolidate_skipped",
- { run_id: this.runId, error: String(error) },
+ { run_id: this.runId, type, attempt, error: String(error) },
"ERROR",
);
}
- return merged.size;
+ writeWikiLog("wiki_consolidate_type", {
+ run_id: this.runId,
+ type,
+ attempt,
+ listed_count: fresh.length,
+ merged_count: merged.size,
+ failed,
+ });
+ return { merged: merged.size, failed };
}
/** Merges listed new entities into one of them or into an existing page. */
@@ -1349,6 +1397,7 @@ ${renderExcerpts(
};
}
+ /** Records routed entities; a new name that matches a page joins that page. */
#addTodo(
args: Readonly<Record<string, unknown>>,
allowed: ReadonlySet<string>,
diff --git a/apps/node-services/src/memory-agent.ts b/apps/node-services/src/memory-agent.ts
index d763036c..3026883a 100644
--- a/apps/node-services/src/memory-agent.ts
+++ b/apps/node-services/src/memory-agent.ts
@@ -6,7 +6,11 @@ import path from "node:path";
import { isRecord } from "@linger/service-kit";
import { packageRoot } from "./paths.js";
-import type { ModelCallEffort, ModelChain } from "./runtime-model-call.js";
+import {
+ schemaProblem,
+ type ModelCallEffort,
+ type ModelChain,
+} from "./runtime-model-call.js";
/**
* The memory Agent: one controlled loop for every kind of memory upkeep
@@ -126,8 +130,8 @@ export function strictObject(
};
}
-/** The schema of one step: up to `maxActions` actions of this task. */
-export function agentStepSchema(task: AgentTask): Record<string, unknown> {
+/** Up to `maxActions` actions of this task, as an array. */
+function agentActionsSchema(task: AgentTask): Record<string, unknown> {
const branches = [
...task.tools.map((tool) =>
strictObject({
@@ -148,12 +152,23 @@ export function agentStepSchema(task: AgentTask): Record<string, unknown> {
summary: { type: "string", maxLength: 1_000 },
}),
];
+ return {
+ type: "array",
+ maxItems: task.maxActions,
+ items: { anyOf: branches },
+ };
+}
+
+/** The schema of one step: up to `maxActions` actions of this task. */
+export function agentStepSchema(
+ task: AgentTask,
+ actions: Record<string, unknown> = agentActionsSchema(task),
+): Record<string, unknown> {
return strictObject({
- actions: {
- type: "array",
- maxItems: task.maxActions,
- items: { anyOf: branches },
- },
+ // Claude's structured output can send a long array as its JSON text and
+ // then fail validation on every retry; parseActions reads either form,
+ // and the step checks the text against the array schema.
+ actions: { anyOf: [actions, { type: "string" }] },
});
}
@@ -209,7 +224,8 @@ export async function runAgentTask(request: {
}): Promise<AgentRunResult> {
const { task, environment } = request;
const instructions = agentInstructions(task);
- const schema = agentStepSchema(task);
+ const actionsSchema = agentActionsSchema(task);
+ const schema = agentStepSchema(task, actionsSchema);
const signal = request.signal ?? new AbortController().signal;
// Session keys of this run never meet a thread an earlier run left open.
const session = randomUUID();
@@ -226,6 +242,7 @@ export async function runAgentTask(request: {
session,
instructions,
schema,
+ actionsSchema,
steps,
index,
);
@@ -332,6 +349,7 @@ async function callStep(
session: string,
instructions: string,
schema: Record<string, unknown>,
+ actionsSchema: Record<string, unknown>,
steps: readonly AgentStepRecord[],
index: number,
): Promise<Record<string, unknown>> {
@@ -342,6 +360,16 @@ async function callStep(
input: stepInput(request, instructions, steps, index),
schemaName: STEP_SCHEMA_NAME,
outputSchema: schema,
+ validate: (output) => {
+ if (typeof output.actions !== "string") return undefined;
+ const actions = actionList(output.actions);
+ if (actions === undefined)
+ return "`actions` is text that is not a JSON array; send `actions` as an array of action objects";
+ const problem = schemaProblem(actionsSchema, actions);
+ return problem
+ ? `\`actions\` text does not match the action schema: ${problem}; send \`actions\` as an array of action objects`
+ : undefined;
+ },
timeoutMs: request.task.timeoutMs,
...(request.task.maxOutputChars === undefined
? {}
@@ -443,7 +471,7 @@ function parseActions(
output: Readonly<Record<string, unknown>>,
task: AgentTask,
): ParsedAction[] {
- const actions = Array.isArray(output.actions) ? output.actions : [];
+ const actions = actionList(output.actions) ?? [];
const tools = new Set(task.tools.map((tool) => tool.name));
const objects = new Set(task.objects.map((object) => object.type));
const parsed: ParsedAction[] = [];
@@ -474,6 +502,19 @@ function parseActions(
return parsed;
}
+/** A step's actions, given as an array or as the JSON text of one;
+ * undefined when the text is not a JSON array. */
+function actionList(value: unknown): unknown[] | undefined {
+ if (Array.isArray(value)) return value;
+ if (typeof value !== "string") return [];
+ try {
+ const parsed: unknown = JSON.parse(value);
+ return Array.isArray(parsed) ? parsed : undefined;
+ } catch {
+ return undefined;
+ }
+}
+
/** Cuts a step's results to one shared character budget. */
function fitResults(
results: readonly AgentObservation[],
diff --git a/apps/node-services/src/runtime-model-call.ts b/apps/node-services/src/runtime-model-call.ts
index 0ed94ab6..6f269590 100644
--- a/apps/node-services/src/runtime-model-call.ts
+++ b/apps/node-services/src/runtime-model-call.ts
@@ -365,6 +365,15 @@ function validatorFor(schema: object): ValidateFunction {
return validate;
}
+/** Why a value does not match a schema, or undefined when it does. */
+export function schemaProblem(
+ schema: object,
+ value: unknown,
+): string | undefined {
+ const validate = validatorFor(schema);
+ return validate(value) ? undefined : ajv.errorsText(validate.errors);
+}
+
const silentLogger: Pick<JsonLogger, "log"> = { log: () => undefined };
/** How long a finished call's answer waits for a caller that left. */
diff --git a/apps/node-services/tests/llm-wiki/agent-wiki-backend.llm-wiki.test.ts b/apps/node-services/tests/llm-wiki/agent-wiki-backend.llm-wiki.test.ts
index 8a3a0cb7..c729c600 100644
--- a/apps/node-services/tests/llm-wiki/agent-wiki-backend.llm-wiki.test.ts
+++ b/apps/node-services/tests/llm-wiki/agent-wiki-backend.llm-wiki.test.ts
@@ -487,10 +487,9 @@ describe("AgentWikiBackend", () => {
async (directory) => [await chatInput(directory)],
fakeModel(true),
);
- // Two new entities: one consolidation call settles them before writing.
+ // Two new entities of different types: nothing to consolidate.
expect(requests.map((entry) => entry.step)).toEqual([
"route:1/1",
- "consolidate/1",
"batch:1:write:0/1",
"batch:1:write:0/2",
]);
@@ -499,10 +498,10 @@ describe("AgentWikiBackend", () => {
const sessions = requests.map((entry) => entry.sessionKey);
expect(sessions.every(Boolean)).toBe(true);
expect(new Set(sessions).size).toBe(sessions.length);
- expect(requests[3]!.input).toContain("# Evidence");
+ expect(requests[2]!.input).toContain("# Evidence");
// Both pages are in the one task; its finish waits for the topic.
- expect(requests[2]!.input).toContain("topics/pilot-program.md (new page");
- expect(requests[3]!.input).toContain(
+ expect(requests[1]!.input).toContain("topics/pilot-program.md (new page");
+ expect(requests[2]!.input).toContain(
"Not done yet: propose or skip_page topics/pilot-program.md",
);
expect(files).toEqual([
@@ -745,11 +744,16 @@ ${filler}
function namingModel(
names: Record<string, { name: string; slug: string }>,
merges: ReadonlyArray<{ keep: string; merge: string[] }> = [],
+ failedConsolidations = 0,
) {
const requests: ModelChainCallRequest[] = [];
+ let consolidations = 0;
const call = vi.fn(async (request: ModelChainCallRequest) => {
requests.push(request);
if (request.instructions!.includes("Settle the new entities")) {
+ consolidations += 1;
+ if (consolidations <= failedConsolidations)
+ throw new Error("Runtime is unavailable");
const listed = new Map(
[...request.input.matchAll(/^- \[(\d+)\] \w+ "([^"]+)"/gmu)].map(
([, index, name]) => [name!, Number(index)],
@@ -867,6 +871,7 @@ ${filler}
async function generateNamed(
names: Record<string, { name: string; slug: string }>,
merges: ReadonlyArray<{ keep: string; merge: string[] }> = [],
+ failedConsolidations = 0,
) {
const root = await temporary();
const inputsDirectory = join(root, "inputs");
@@ -889,7 +894,7 @@ ${filler}
mode: "initialize",
outputDirectory: join(root, "output"),
};
- const model = namingModel(names, merges);
+ const model = namingModel(names, merges, failedConsolidations);
await new AgentWikiBackend({ modelCall: () => model.modelCall }).generate(
request,
);
@@ -965,6 +970,26 @@ ${filler}
expect(page).toContain("teamhub://rooms/roomb/messages/m1");
});
+ it("tries a type's consolidation once more when its call fails", async () => {
+ const { files, requests } = await generateNamed(
+ {
+ rooma: { name: "AWS", slug: "aws" },
+ roomb: {
+ name: "アマゾン ウェブ サービス",
+ slug: "amazon-web-services",
+ },
+ },
+ [{ keep: "AWS", merge: ["アマゾン ウェブ サービス"] }],
+ 1,
+ );
+ expect(
+ requests
+ .map((entry) => entry.step)
+ .filter((step) => step.startsWith("consolidate")),
+ ).toEqual(["consolidate:client:1/1", "consolidate:client:2/1"]);
+ expect(files).toEqual(["clients/aws.md"]);
+ });
+
it("keeps one of two new pages that still share an identity after correction", async () => {
const { files, requests } = await generateNamed({
rooma: { name: "AWS", slug: "aws" },
diff --git a/apps/node-services/tests/memory-agent.test.ts b/apps/node-services/tests/memory-agent.test.ts
index 8b6e6fe6..45248469 100644
--- a/apps/node-services/tests/memory-agent.test.ts
+++ b/apps/node-services/tests/memory-agent.test.ts
@@ -74,17 +74,19 @@ describe("agentStepSchema", () => {
const schema = agentStepSchema(task) as {
properties: {
actions: {
- maxItems: number;
- items: { anyOf: { required: string[] }[] };
+ anyOf: [
+ { maxItems: number; items: { anyOf: { required: string[] }[] } },
+ { type: string },
+ ];
};
};
required: string[];
};
+ const [list, text] = schema.properties.actions.anyOf;
expect(schema.required).toEqual(["actions"]);
- expect(schema.properties.actions.maxItems).toBe(5);
- expect(
- schema.properties.actions.items.anyOf.map((branch) => branch.required),
- ).toEqual([
+ expect(list.maxItems).toBe(5);
+ expect(text.type).toBe("string");
+ expect(list.items.anyOf.map((branch) => branch.required)).toEqual([
["tool", "arguments"],
["tool", "object", "target", "payload"],
["tool", "summary"],
@@ -248,6 +250,57 @@ describe("runAgentTask", () => {
expect(env.propose).not.toHaveBeenCalled();
});
+ it("reads actions a runtime sent as the JSON text of their array", async () => {
+ const model = stubChain({
+ call: vi.fn(async () => ({
+ output: {
+ actions: JSON.stringify([
+ { tool: "read", arguments: { source: "s1" } },
+ { tool: "read", arguments: { source: "s2" } },
+ { tool: "finish", summary: "read both" },
+ ]),
+ },
+ model: "test",
+ })),
+ });
+ const env = environment();
+ const result = await runAgentTask({
+ model,
+ step: "test",
+ task,
+ input: "",
+ environment: env,
+ });
+ expect(env.runTool).toHaveBeenCalledTimes(2);
+ expect(result).toMatchObject({ finished: true, summary: "read both" });
+ });
+
+ it("rejects actions text that is not a JSON array so the call corrects it", async () => {
+ const call = vi.fn().mockResolvedValue({
+ output: { actions: [{ tool: "finish", summary: "ok" }] },
+ model: "test",
+ });
+ await runAgentTask({
+ model: stubChain({ call }),
+ step: "test",
+ task,
+ input: "",
+ environment: environment(),
+ });
+ const { validate } = call.mock.calls[0]![0] as ModelChainCallRequest;
+ expect(validate!({ actions: '[{"tool":"finish"}}]' })).toContain(
+ "not a JSON array",
+ );
+ // Text gets the per-action checks the array form gets from the schema.
+ expect(
+ validate!({ actions: '[{"tool":"propose","object":"unknown"}]' }),
+ ).toContain("does not match the action schema");
+ expect(
+ validate!({ actions: '[{"tool":"finish","summary":"ok"}]' }),
+ ).toBeUndefined();
+ expect(validate!({ actions: [] })).toBeUndefined();
+ });
+
it("sends each step once with its cap in a session of its own", async () => {
const call = vi.fn().mockResolvedValue({
output: { actions: [{ tool: "finish", summary: "ok" }] },