Files
loki/scripts/test/inject-context-boundaries.ts
CatoandClaude adfbdcfe07 fix(session): the builder updates, the sheet changes things, one box, a preview is the site (#1305)
The owner used Loki from a phone (2026-10-18) and could not tell whether
anything worked. Four separate faults, each passing every check:

The cloud builder ran code days behind the app. Its restart waits for
every agent to be idle, and autopilot refilled the queue the instant one
finished: ten consecutive deploys (23:38 → 09:12) found "2 agent(s)
working — deferring restart". Hence "Model: not known yet" of an answer
the screen was showing. Now, while the cloud runner's heartbeat version is
behind the deploy's, the commands route hands it no work-starting
commands (dispatch, launch_agent, auto_continue, browser_task) — a
person's own words into a session still go through — so the idle moment
comes, the restart lands, the queue resumes on the new code. Server-side
on purpose: a runner-side rule would have waited for the very restart it
was meant to allow. Control's builder line says "a newer version waits
for its agents to finish" meanwhile.

An agent renamed a preview site, committed, and reported "the work lives
only on this machine — tell Loki where this preview's remote should
live". The box contract says push or fail loudly; a preview folder is
served from disk and has no remote by design, so the change had been live
since the save and the owner read a failure and a chore. Every dispatch
to a preview folder now carries "Where this goes" (lib/previews/
delivery-note), and the contract has the same section.

The session sheet's Change and Set typed /model and /effort into the
terminal and closed; Claude Code drew its picker behind the conversation
and nothing on screen moved. Each row now lists its choices; a tap sends
the command with the choice named (/model sonnet, /effort high), the
sheet stays open and says what is changing, and settles when the log
names it. The sheet is built like the Settings sheet.

The session box had a 26px library button beside 44px round ones, a 36px
chip and a 34px Keys pill, the microphone second from the left in one
view and beside Send in the other, and "claude" on the tab beside
"Message Claude…". One row, one size, one order in both views; the
agent's name everywhere (terminal-strip-tabs badgeNames).

Widget: the owner's change list reads what needs them first (the line
counted nine, the list showed none); "9 needs you" → "9 need you"; a
failed call is named ("my call to Loki to save your note failed… Your
words are still here — press it again") instead of "one of my calls to
Loki failed — nothing for you to do".

Tests: runner-update-hold, preview-delivery-note, owner-changes-order,
session-sheet-browser (new); builder-presence, widget-changes,
widget-self-report, inject-context-boundaries extended.


Claude-Session: https://claude.ai/code/session_01NZqZujmXpupVDC1Hi5Jbsx

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-18 13:37:05 +02:00

186 lines
7.0 KiB
TypeScript

import assert from "node:assert/strict";
import fs from "node:fs";
import ts from "typescript";
import { exitContractFor } from "@/lib/agent-config";
import { renderTaskForAdapter } from "@/lib/orchestration/renderers";
import { previewDeliveryNote } from "@/lib/previews/delivery-note";
async function main() {
const source = fs.readFileSync("src/lib/inject-prompt.ts", "utf8");
const parsed = ts.createSourceFile("inject.ts", source, ts.ScriptTarget.Latest, true);
const fn = parsed.statements.find(
(s) => ts.isFunctionDeclaration(s) && s.name?.text === "assembleInjectPrompt",
)!;
const js = ts.transpileModule(fn.getText(parsed).replace(/^export /, ""), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
}).outputText;
const retrievals: string[] = [];
let projectContextReads = 0;
let fleetBriefReads = 0;
const bindings = {
getProjectContext: async () => {
projectContextReads++;
return "Project-specific goals";
},
retrieveFleetContextBlock: async (_user: string, query: string) => {
retrievals.push(query);
return "Relevant project pattern";
},
getOpenEscalationBlock: async () => "",
fleetBriefForProject: async () => {
fleetBriefReads++;
return "## bitbaum house rules\nBULK SHARED PACKAGE CATALOG\nEnd of bitbaum house rules.";
},
FLEET_SESSIONS_DISPLAY_PATH: "~/.loki/sessions",
// A preview folder is the site: the real note, against a fixed root.
previewDeliveryNote,
previewsRoot: () => "/workspace/previews",
exitContractFor: () => "Handoff contract",
renderTaskForAdapter: (request: { customInstructions?: string; projectContext?: string }) =>
request.customInstructions
? `## Task\n${request.customInstructions.trim()}`
: `${request.projectContext ?? ""}\nChoose a useful next project task.`,
isOrchestrationIntent: (key: string) => key === "next_best",
getOrchestrationIntent: () => ({ name: "Next best" }),
buildOperatorContextSection: () => {
throw Error("Personal context must not be read");
},
};
const assemble = new Function(...Object.keys(bindings), js + ";return assembleInjectPrompt;")(
...Object.values(bindings),
);
const base = {
userId: "owner",
projectKey: "petvity",
projectPath: "/workspace/petvity",
projectId: "entity",
adapter: "claude",
};
const automatic = await assemble({ ...base, promptKey: "next_best" });
assert(automatic.ok);
assert.deepEqual(retrievals, [], "an intent key must not retrieve unrelated project documents");
assert(automatic.prompt.includes("Project-specific goals"));
assert(automatic.prompt.includes("Handoff contract"));
const explicit = await assemble({ ...base, customPrompt: "Fix mobile checkout" });
assert(explicit.ok);
assert(
!explicit.prompt.includes("## Where this goes"),
"a repository keeps the push contract — no preview note",
);
const preview = await assemble({
...base,
projectPath: "/workspace/previews/tsentr-som",
liveUrl: "https://tsentr-som.orangecat.ch",
customPrompt: "Rename the site",
});
assert(preview.ok);
assert(
preview.prompt.includes("## Where this goes") &&
preview.prompt.includes("https://tsentr-som.orangecat.ch"),
"a dispatch to a preview folder says the folder is the site",
);
assert(
preview.prompt.indexOf("## Where this goes") < preview.prompt.indexOf("Handoff contract"),
"the delivery note comes before the handoff contract",
);
assert.match(explicit.prompt, /^## Task\nFix mobile checkout/m);
assert(explicit.prompt.includes("Handoff contract"));
assert(!explicit.prompt.includes("Project-specific goals"));
assert(!explicit.prompt.includes("BULK SHARED PACKAGE CATALOG"));
assert(!explicit.prompt.includes("other projects"));
assert.deepEqual(retrievals, [], "explicit tasks must not search unrelated project notes");
assert.equal(projectContextReads, 1, "only broad intents read the full project profile");
assert.equal(fleetBriefReads, 0, "dispatches do not inject the fleet package/stack catalog");
const actualDirectPrompt = [
renderTaskForAdapter({
projectKey: "petvity",
projectPath: "/workspace/petvity",
adapter: "claude",
intent: "custom",
customInstructions: "Fix the /de homepage headline.",
}),
exitContractFor("~/.loki/sessions/petvity.md"),
].join("\n\n");
assert(actualDirectPrompt.includes("Fix the /de homepage headline."));
assert(
actualDirectPrompt.length < 800,
`direct dispatch must stay concise (${actualDirectPrompt.length})`,
);
for (const file of [
"src/lib/inject-core.ts",
"src/lib/inject-prompt.ts",
"src/app/api/orchestration/run/route.ts",
]) {
const tree = ts.createSourceFile(
file,
fs.readFileSync(file, "utf8"),
ts.ScriptTarget.Latest,
true,
);
const visit = (node: ts.Node) => {
if (ts.isCallExpression(node) && ts.isIdentifier(node.expression))
assert.notEqual(
node.expression.text,
"buildOperatorContextSection",
`${file} must not inject personal life data`,
);
ts.forEachChild(node, visit);
};
visit(tree);
}
const knowledgeFile = "src/db/queries/knowledge-embeddings.ts";
const knowledgeTree = ts.createSourceFile(
knowledgeFile,
fs.readFileSync(knowledgeFile, "utf8"),
ts.ScriptTarget.Latest,
true,
);
const retrieveFn = knowledgeTree.statements.find(
(s) => ts.isFunctionDeclaration(s) && s.name?.text === "retrieveFleetContextBlock",
)!;
const retrieveJs = ts.transpileModule(retrieveFn.getText(knowledgeTree).replace(/^export /, ""), {
compilerOptions: { target: ts.ScriptTarget.ES2022, module: ts.ModuleKind.CommonJS },
}).outputText;
const retrieve = new Function(
"embeddingsEnabled",
"searchKnowledge",
retrieveJs + ";return retrieveFleetContextBlock;",
)(
() => true,
async (_actor: string, _query: string, opts: { sourceTypes: string[] }) => {
assert.deepEqual(opts.sourceTypes, [
"project_profile",
"dev_log",
"orchestration_outcome",
"repo_doc",
]);
return [
{ sourceType: "goal", sourceId: "private", chunk: "PRIVATE GOAL", metadata: {} },
{ sourceType: "commitment", sourceId: "private", chunk: "PRIVATE CONTACT", metadata: {} },
{
sourceType: "repo_doc",
sourceId: "ours",
chunk: "Same project",
metadata: { project: "petvity" },
},
{
sourceType: "repo_doc",
sourceId: "other",
chunk: "Checkout pattern",
metadata: { project: "other" },
},
];
},
);
const retrieved = await retrieve("owner", "mobile checkout", { excludeProject: "petvity" });
assert(retrieved.includes("Checkout pattern"));
assert(!retrieved.includes("PRIVATE"));
assert(!retrieved.includes("Same project"));
console.log(
"✓ explicit coding tasks carry only the task and compact handoff; broad intents retain project context",
);
}
main().catch((e) => {
console.error(e);
process.exitCode = 1;
});