From 63bbfec4469076c07a656eee169501deb4e6e34f Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:35:49 -0500 Subject: [PATCH 1/4] feat: project brief storage, RPCs and session lookup The plan (docs/design/project-brief-notes.md, rev 3) and the first part of piece 1: project_briefs (migration 122) with a revision checked on save, the ProjectContext service with projectContext.subscribe and projectContext.setBrief, the projectContext capability, the optional projectInstructions on ProviderSessionStartInput, and the ProjectInstructions lookup ProviderService will use at every start. Delivery to each provider and the page come next. --- .../environment/Layers/ServerEnvironment.ts | 1 + apps/server/src/persistence/Migrations.ts | 2 + .../Migrations/122_ProjectBriefs.ts | 20 + .../projectContext/ProjectBriefRepository.ts | 113 ++++++ .../src/projectContext/ProjectContext.ts | 159 ++++++++ .../projectContext/ProjectInstructionsLive.ts | 56 +++ .../projectContext/projectInstructionsText.ts | 16 + .../provider/Services/ProjectInstructions.ts | 28 ++ apps/server/src/server.test.ts | 2 + apps/server/src/server.ts | 24 ++ apps/server/src/ws.ts | 12 + docs/design/project-brief-notes.md | 377 ++++++++++++++++++ packages/contracts/src/environment.ts | 7 + packages/contracts/src/index.ts | 1 + packages/contracts/src/projectContext.ts | 63 +++ packages/contracts/src/projectSetup.ts | 5 + packages/contracts/src/provider.ts | 8 + packages/contracts/src/rpc.ts | 26 ++ 18 files changed, 920 insertions(+) create mode 100644 apps/server/src/persistence/Migrations/122_ProjectBriefs.ts create mode 100644 apps/server/src/projectContext/ProjectBriefRepository.ts create mode 100644 apps/server/src/projectContext/ProjectContext.ts create mode 100644 apps/server/src/projectContext/ProjectInstructionsLive.ts create mode 100644 apps/server/src/projectContext/projectInstructionsText.ts create mode 100644 apps/server/src/provider/Services/ProjectInstructions.ts create mode 100644 docs/design/project-brief-notes.md create mode 100644 packages/contracts/src/projectContext.ts diff --git a/apps/server/src/environment/Layers/ServerEnvironment.ts b/apps/server/src/environment/Layers/ServerEnvironment.ts index 24299725b..33ca82d6e 100644 --- a/apps/server/src/environment/Layers/ServerEnvironment.ts +++ b/apps/server/src/environment/Layers/ServerEnvironment.ts @@ -119,6 +119,7 @@ export const makeServerEnvironment = Effect.fn("makeServerEnvironment")(function phoneAlertControls: true, projectLead: true, childStartSelection: true, + projectContext: true, deviceNames: true, draftGoalSetup: true, pullRequestSwitchesByNumber: true, diff --git a/apps/server/src/persistence/Migrations.ts b/apps/server/src/persistence/Migrations.ts index 4ad046a88..bacc6e9ff 100644 --- a/apps/server/src/persistence/Migrations.ts +++ b/apps/server/src/persistence/Migrations.ts @@ -141,6 +141,7 @@ import Migration0118 from "./Migrations/118_SessionStopRequestedTurn.ts"; import Migration0119 from "./Migrations/119_LinkMoveFamilies.ts"; import Migration0120 from "./Migrations/120_ThreadAdoptedFromLink.ts"; import Migration0121 from "./Migrations/121_ProjectionThreadSecretRequests.ts"; +import Migration0122 from "./Migrations/122_ProjectBriefs.ts"; /** * Migration loader with all migrations defined inline. @@ -274,6 +275,7 @@ export const migrationEntries = [ [119, "LinkMoveFamilies", Migration0119], [120, "ThreadAdoptedFromLink", Migration0120], [121, "ProjectionThreadSecretRequests", Migration0121], + [122, "ProjectBriefs", Migration0122], ] as const; /** Highest id in the full registry, so the "n of total" count is the real total. */ diff --git a/apps/server/src/persistence/Migrations/122_ProjectBriefs.ts b/apps/server/src/persistence/Migrations/122_ProjectBriefs.ts new file mode 100644 index 000000000..ec9e2ef81 --- /dev/null +++ b/apps/server/src/persistence/Migrations/122_ProjectBriefs.ts @@ -0,0 +1,20 @@ +import * as Effect from "effect/Effect"; +import * as SqlClient from "effect/sql/SqlClient"; + +/** + * A project's brief (docs/design/project-brief-notes.md): the user's standing + * instructions for every thread in the project, kept outside the event log. + * One row per project, so the text and its revision change together. + */ +export default Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + yield* sql` + CREATE TABLE IF NOT EXISTS project_briefs ( + project_id TEXT PRIMARY KEY, + text TEXT NOT NULL, + revision INTEGER NOT NULL, + updated_at TEXT NOT NULL + ) + `; +}); diff --git a/apps/server/src/projectContext/ProjectBriefRepository.ts b/apps/server/src/projectContext/ProjectBriefRepository.ts new file mode 100644 index 000000000..2d79014b8 --- /dev/null +++ b/apps/server/src/projectContext/ProjectBriefRepository.ts @@ -0,0 +1,113 @@ +/** + * ProjectBriefRepository: `project_briefs`, one row per project that has a + * brief (docs/design/project-brief-notes.md). A save names the revision it + * expects, so two devices saving at once cannot overwrite each other. + */ +import { IsoDateTime, NonNegativeInt, ProjectId, type ProjectBrief } from "@threadlines/contracts"; +import * as Context from "effect/Context"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Schema from "effect/Schema"; +import * as SqlClient from "effect/sql/SqlClient"; +import * as SqlSchema from "effect/sql/SqlSchema"; + +import { type PersistenceSqlError, toPersistenceSqlError } from "../persistence/Errors.ts"; + +const ProjectBriefRow = Schema.Struct({ + projectId: ProjectId, + text: Schema.String, + revision: NonNegativeInt, + updatedAt: IsoDateTime, +}); + +export interface ProjectBriefRepositoryShape { + /** Every project's brief row. */ + readonly listAll: () => Effect.Effect, PersistenceSqlError>; + /** The project's brief; none before its first save. */ + readonly get: ( + projectId: ProjectId, + ) => Effect.Effect, PersistenceSqlError>; + /** + * Save `text` as the next revision when the stored revision is + * `expectedRevision` (0: no row yet). None when it isn't: nothing written. + */ + readonly save: (input: { + readonly projectId: ProjectId; + readonly text: string; + readonly expectedRevision: number; + readonly now: string; + }) => Effect.Effect, PersistenceSqlError>; +} + +export class ProjectBriefRepository extends Context.Service< + ProjectBriefRepository, + ProjectBriefRepositoryShape +>()("threadlines/projectContext/ProjectBriefRepository") {} + +export const makeProjectBriefRepository = Effect.gen(function* () { + const sql = yield* SqlClient.SqlClient; + + const selectAll = SqlSchema.findAll({ + Request: Schema.Void, + Result: ProjectBriefRow, + execute: () => sql` + SELECT project_id AS "projectId", text, revision, updated_at AS "updatedAt" + FROM project_briefs + ORDER BY project_id + `, + }); + + const selectOne = SqlSchema.findOneOption({ + Request: ProjectId, + Result: ProjectBriefRow, + execute: (projectId) => sql` + SELECT project_id AS "projectId", text, revision, updated_at AS "updatedAt" + FROM project_briefs + WHERE project_id = ${projectId} + `, + }); + + const listAll: ProjectBriefRepositoryShape["listAll"] = () => + selectAll(undefined).pipe( + Effect.mapError(toPersistenceSqlError("ProjectBriefRepository.listAll")), + ); + + const get: ProjectBriefRepositoryShape["get"] = (projectId) => + selectOne(projectId).pipe(Effect.mapError(toPersistenceSqlError("ProjectBriefRepository.get"))); + + const save: ProjectBriefRepositoryShape["save"] = (input) => + Effect.gen(function* () { + const current = yield* selectOne(input.projectId); + const currentRevision = Option.match(current, { + onNone: () => 0, + onSome: (row) => row.revision, + }); + if (currentRevision !== input.expectedRevision) return Option.none(); + const next = { + projectId: input.projectId, + text: input.text, + revision: currentRevision + 1, + updatedAt: input.now, + }; + yield* sql` + INSERT INTO project_briefs (project_id, text, revision, updated_at) + VALUES (${next.projectId}, ${next.text}, ${next.revision}, ${next.updatedAt}) + ON CONFLICT (project_id) DO UPDATE SET + text = excluded.text, + revision = excluded.revision, + updated_at = excluded.updated_at + `; + return Option.some(next); + }).pipe( + sql.withTransaction, + Effect.mapError(toPersistenceSqlError("ProjectBriefRepository.save")), + ); + + return { listAll, get, save } satisfies ProjectBriefRepositoryShape; +}); + +export const ProjectBriefRepositoryLive = Layer.effect( + ProjectBriefRepository, + makeProjectBriefRepository, +); diff --git a/apps/server/src/projectContext/ProjectContext.ts b/apps/server/src/projectContext/ProjectContext.ts new file mode 100644 index 000000000..7f2e212c9 --- /dev/null +++ b/apps/server/src/projectContext/ProjectContext.ts @@ -0,0 +1,159 @@ +/** + * ProjectContext: what a project keeps for the agents that work in it, kept + * on this computer outside the orchestration event log (docs/design/ + * project-brief-notes.md). The app reads and saves it over `projectContext.*`; + * agents never can. Sessions read it through `ProjectInstructions`. + */ +import { + GENERAL_CHATS_PROJECT_ID, + type ProjectBrief, + type ProjectBriefSetInput, + type ProjectBriefSetResult, + ProjectContextError, + type ProjectContextSnapshot, + type ProjectId, +} from "@threadlines/contracts"; +import * as Cause from "effect/Cause"; +import * as Context from "effect/Context"; +import * as DateTime from "effect/DateTime"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import type * as Stream from "effect/Stream"; +import * as SubscriptionRef from "effect/SubscriptionRef"; + +import { ProjectionProjectRepository } from "../persistence/Services/ProjectionProjects.ts"; +import { ProjectBriefRepository } from "./ProjectBriefRepository.ts"; + +export interface ProjectContextShape { + /** Every project's brief, now and again after each save. */ + readonly changes: Stream.Stream; + /** Save a brief, unless another device saved since `expectedRevision`. */ + readonly setBrief: ( + input: ProjectBriefSetInput, + ) => Effect.Effect; + /** The project's brief text, for "Set up on another computer"; "" when it has none. */ + readonly briefText: (projectId: ProjectId) => Effect.Effect; + /** + * A project "Set up on another computer" just added here takes the brief it + * was copied with. Only into an empty brief: one the user wrote here wins. + */ + readonly adoptBrief: (projectId: ProjectId, text: string) => Effect.Effect; +} + +export class ProjectContext extends Context.Service()( + "threadlines/projectContext/ProjectContext", +) {} + +const failWith = (detail: string) => Effect.fail(new ProjectContextError({ detail })); + +const nowIso = Effect.map(DateTime.now, DateTime.formatIso); + +const emptyBrief = (projectId: ProjectId): ProjectBrief => ({ + projectId, + text: "", + revision: 0, + updatedAt: null, +}); + +export const makeProjectContext = Effect.gen(function* () { + const briefs = yield* ProjectBriefRepository; + const projects = yield* ProjectionProjectRepository; + + const loadSnapshot = briefs.listAll().pipe( + Effect.map((rows): ProjectContextSnapshot => ({ briefs: rows })), + Effect.catchCause((cause) => + Effect.logWarning("project briefs could not be read", { cause: Cause.pretty(cause) }).pipe( + Effect.as({ briefs: [] } satisfies ProjectContextSnapshot), + ), + ), + ); + const snapshot = yield* SubscriptionRef.make(yield* loadSnapshot); + const publish = (brief: ProjectBrief) => + SubscriptionRef.update(snapshot, (current) => ({ + briefs: [...current.briefs.filter((entry) => entry.projectId !== brief.projectId), brief], + })); + + const requireProject = (projectId: ProjectId) => + Effect.gen(function* () { + if (projectId === GENERAL_CHATS_PROJECT_ID) { + return yield* failWith("General Chats have no brief."); + } + const project = yield* projects + .getById({ projectId }) + .pipe( + Effect.mapError( + () => new ProjectContextError({ detail: "The project couldn't be read." }), + ), + ); + if (Option.isNone(project) || project.value.deletedAt !== null) { + return yield* failWith("This project is gone."); + } + }); + + const setBrief: ProjectContextShape["setBrief"] = (input) => + Effect.gen(function* () { + yield* requireProject(input.projectId); + const saved = yield* briefs + .save({ + projectId: input.projectId, + text: input.text, + expectedRevision: input.expectedRevision, + now: yield* nowIso, + }) + .pipe( + Effect.mapError( + () => new ProjectContextError({ detail: "The brief couldn't be saved." }), + ), + ); + if (Option.isNone(saved)) { + const current = yield* briefs + .get(input.projectId) + .pipe( + Effect.mapError( + () => new ProjectContextError({ detail: "The brief couldn't be read." }), + ), + ); + return { + outcome: "stale" as const, + brief: Option.getOrElse(current, () => emptyBrief(input.projectId)), + }; + } + yield* publish(saved.value); + return { outcome: "saved" as const, brief: saved.value }; + }); + + const briefText: ProjectContextShape["briefText"] = (projectId) => + briefs.get(projectId).pipe( + Effect.map((row) => Option.getOrUndefined(row)?.text ?? ""), + Effect.orElseSucceed(() => ""), + ); + + const adoptBrief: ProjectContextShape["adoptBrief"] = (projectId, text) => + Effect.gen(function* () { + if (text.trim().length === 0) return; + const saved = yield* briefs.save({ + projectId, + text, + expectedRevision: 0, + now: yield* nowIso, + }); + if (Option.isSome(saved)) yield* publish(saved.value); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("a copied project's brief couldn't be saved", { + projectId, + cause: Cause.pretty(cause), + }), + ), + ); + + return { + changes: SubscriptionRef.changes(snapshot), + setBrief, + briefText, + adoptBrief, + } satisfies ProjectContextShape; +}); + +export const ProjectContextLive = Layer.effect(ProjectContext, makeProjectContext); diff --git a/apps/server/src/projectContext/ProjectInstructionsLive.ts b/apps/server/src/projectContext/ProjectInstructionsLive.ts new file mode 100644 index 000000000..f717e85ba --- /dev/null +++ b/apps/server/src/projectContext/ProjectInstructionsLive.ts @@ -0,0 +1,56 @@ +import { GENERAL_CHATS_PROJECT_ID } from "@threadlines/contracts"; +import { parseSessionKey } from "@threadlines/shared/threadParticipants"; +import * as Cause from "effect/Cause"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; + +import { isLinkFenced } from "../orchestration/linkFence.ts"; +import { ProjectionProjectRepository } from "../persistence/Services/ProjectionProjects.ts"; +import { ProjectionThreadRepository } from "../persistence/Services/ProjectionThreads.ts"; +import { + ProjectInstructions, + type ProjectInstructionsShape, +} from "../provider/Services/ProjectInstructions.ts"; +import { ProjectBriefRepository } from "./ProjectBriefRepository.ts"; +import { projectInstructionsText } from "./projectInstructionsText.ts"; + +/** + * Reads the thread, its project and the project's brief from the stored + * projections each time a session starts: no copy to keep in step. + */ +export const makeProjectInstructions = Effect.gen(function* () { + const threads = yield* ProjectionThreadRepository; + const projects = yield* ProjectionProjectRepository; + const briefs = yield* ProjectBriefRepository; + + const forSession: ProjectInstructionsShape["forSession"] = ({ sessionKey }) => + Effect.gen(function* () { + const target = parseSessionKey(sessionKey); + // A side answer is short, read-only and locked down. + if (target.kind === "side") return undefined; + const thread = Option.getOrUndefined(yield* threads.getById({ threadId: target.threadId })); + if (thread === undefined || thread.deletedAt !== null) return undefined; + if (thread.projectId === GENERAL_CHATS_PROJECT_ID) return undefined; + // An agent outside this computer's trust answers for it: it could just + // ask the thread to repeat the brief. + if (isLinkFenced(thread) || (thread.outsideOrigin ?? null) !== null) return undefined; + const project = Option.getOrUndefined( + yield* projects.getById({ projectId: thread.projectId }), + ); + if (project === undefined || project.deletedAt !== null) return undefined; + const brief = Option.getOrUndefined(yield* briefs.get(thread.projectId)); + return projectInstructionsText({ projectTitle: project.title, brief: brief?.text ?? "" }); + }).pipe( + Effect.catchCause((cause) => + Effect.logWarning("project instructions could not be read", { + sessionKey, + cause: Cause.pretty(cause), + }).pipe(Effect.as(undefined)), + ), + ); + + return { forSession } satisfies ProjectInstructionsShape; +}); + +export const ProjectInstructionsLive = Layer.effect(ProjectInstructions, makeProjectInstructions); diff --git a/apps/server/src/projectContext/projectInstructionsText.ts b/apps/server/src/projectContext/projectInstructionsText.ts new file mode 100644 index 000000000..cbe966583 --- /dev/null +++ b/apps/server/src/projectContext/projectInstructionsText.ts @@ -0,0 +1,16 @@ +/** + * The project's text an agent's session starts with, as the agent reads it + * (docs/design/project-brief-notes.md, "What an agent is told"). The brief is + * the user's words, framed as their standing instructions. + */ +export function projectInstructionsText(input: { + readonly projectTitle: string; + readonly brief: string; +}): string | undefined { + const brief = input.brief.trim(); + if (brief.length === 0) return undefined; + return [ + `Project brief for "${input.projectTitle}", from the user. It applies to every thread in this project:`, + brief, + ].join("\n"); +} diff --git a/apps/server/src/provider/Services/ProjectInstructions.ts b/apps/server/src/provider/Services/ProjectInstructions.ts new file mode 100644 index 000000000..dffd660b4 --- /dev/null +++ b/apps/server/src/provider/Services/ProjectInstructions.ts @@ -0,0 +1,28 @@ +/** + * ProjectInstructions: the project's text a provider session starts with + * (docs/design/project-brief-notes.md, "Delivery"). `ProviderService` asks + * it at every adapter start, recovery included, so a session gets the + * project as it is when it starts, whoever started it. + */ +import type { RuntimeMode, ThreadId } from "@threadlines/contracts"; +import * as Context from "effect/Context"; +import type * as Effect from "effect/Effect"; + +export interface ProjectInstructionsShape { + /** + * The text for the session `sessionKey` (a thread's, a room agent's, or a + * side answer's) about to start with `runtimeMode`. Undefined when there is + * nothing to add: no brief, a General Chat, a side answer, or a thread an + * agent outside this computer's trust answers to (the link fence, an outside + * agent's thread). Never fails: a lookup that can't be read adds nothing. + */ + readonly forSession: (input: { + readonly sessionKey: ThreadId; + readonly runtimeMode: RuntimeMode; + }) => Effect.Effect; +} + +export class ProjectInstructions extends Context.Service< + ProjectInstructions, + ProjectInstructionsShape +>()("threadlines/provider/Services/ProjectInstructions") {} diff --git a/apps/server/src/server.test.ts b/apps/server/src/server.test.ts index 24fd33f1c..6f3c128ab 100644 --- a/apps/server/src/server.test.ts +++ b/apps/server/src/server.test.ts @@ -113,6 +113,7 @@ import { LinkRequests, type LinkRequestsShape } from "./links/LinkRequests.ts"; import { MoveQueue } from "./moves/MoveQueue.ts"; import { ThreadMoves } from "./moves/ThreadMoves.ts"; import { ProjectSetups } from "./projectSetup/ProjectSetups.ts"; +import { ProjectContext } from "./projectContext/ProjectContext.ts"; import { ProjectSetupSource } from "./projectSetup/ProjectSetupSource.ts"; import { resolveAttachmentRelativePath } from "./attachmentPaths.ts"; import { @@ -897,6 +898,7 @@ const buildAppUnderTest = (options?: { Layer.mock(ThreadMoves)({}), Layer.mock(MoveQueue)({}), Layer.mock(ProjectSetups)({}), + Layer.mock(ProjectContext)({ changes: Stream.make({ briefs: [] }) }), Layer.mock(ProjectSetupSource)({}), Layer.mock(OutsideAgentSignIn)({ bootId: "test-boot" }), Layer.mock(AssistantAlerts)({ targets: Stream.make([]) }), diff --git a/apps/server/src/server.ts b/apps/server/src/server.ts index 5bc00997a..39a75f1eb 100644 --- a/apps/server/src/server.ts +++ b/apps/server/src/server.ts @@ -19,6 +19,10 @@ import { fixPath } from "./os-jank.ts"; import { websocketRpcRouteLayer } from "./ws.ts"; import { relayDirectRouteLayer } from "./relay/directRoute.ts"; import { ProjectionThreadRepositoryLive } from "./persistence/Layers/ProjectionThreads.ts"; +import { ProjectionProjectRepositoryLive } from "./persistence/Layers/ProjectionProjects.ts"; +import { ProjectBriefRepositoryLive } from "./projectContext/ProjectBriefRepository.ts"; +import { ProjectContextLive } from "./projectContext/ProjectContext.ts"; +import { ProjectInstructionsLive } from "./projectContext/ProjectInstructionsLive.ts"; import { ProjectionTurnRepositoryLive } from "./persistence/Layers/ProjectionTurns.ts"; import { ComputerLinkClientLive } from "./links/ComputerLinkClient.ts"; import { ComputerLinkRepositoryLive } from "./links/ComputerLinkRepository.ts"; @@ -360,8 +364,16 @@ const ScheduledTasksLayerLive = Layer.mergeAll( // Part 8): the reads for a copy of this computer's projects, and the jobs // that make copies here. Jobs a restart cut short are finished or undone // as the layer starts. +// A project's brief (docs/design/project-brief-notes.md): the app's +// `projectContext.*` RPCs, and the copy "Set up on another computer" carries. +const ProjectContextLayerLive = ProjectContextLive.pipe( + Layer.provideMerge(ProjectBriefRepositoryLive), + Layer.provide(ProjectionProjectRepositoryLive), +); + const ProjectSetupsLayerLive = Layer.mergeAll(ProjectSetupsLive, ProjectSetupSourceLive).pipe( Layer.provideMerge(ProjectSetupRepositoryLive), + Layer.provideMerge(ProjectContextLayerLive), Layer.provide(ProcessRunnerLive), ); @@ -421,6 +433,18 @@ const ProviderLayerLive = ProviderServiceLive.pipe( Layer.provideMerge(ProviderSessionDirectoryLayerLive), // The session fence reads the thread's row (docs/design/fleet.md, Part 3b). Layer.provide(ThreadSessionAdmissionLive.pipe(Layer.provide(ProjectionThreadRepositoryLive))), + // Every session starts with its project's brief, read as it starts. + Layer.provide( + ProjectInstructionsLive.pipe( + Layer.provide( + Layer.mergeAll( + ProjectionThreadRepositoryLive, + ProjectionProjectRepositoryLive, + ProjectBriefRepositoryLive, + ), + ), + ), + ), ); const PersistenceLayerLive = Layer.empty.pipe(Layer.provideMerge(SqlitePersistenceLayerLive)); diff --git a/apps/server/src/ws.ts b/apps/server/src/ws.ts index 605bf0193..dfe29c95e 100644 --- a/apps/server/src/ws.ts +++ b/apps/server/src/ws.ts @@ -178,6 +178,7 @@ import { RelayHost } from "./relay/RelayHost.ts"; import { OtherComputers } from "./outsideAgents/OtherComputers.ts"; import { OutsideAgentSignIn } from "./outsideAgents/OutsideAgentSignIn.ts"; import { ComputerLinks } from "./links/ComputerLinks.ts"; +import { ProjectContext } from "./projectContext/ProjectContext.ts"; import { ScheduledTasks, snapshotForClient } from "./scheduled/ScheduledTasks.ts"; import { ThemeLibrary } from "./themes/ThemeLibrary.ts"; import { ThemeShowcase } from "./themes/ThemeShowcase.ts"; @@ -872,6 +873,7 @@ const makeCoreRpcLayer = ( const pushAlerts = yield* PushAlerts; const computerLinks = yield* ComputerLinks; const scheduledTasks = yield* ScheduledTasks; + const projectContext = yield* ProjectContext; const projectSetups = yield* ProjectSetups; const projectSetupSource = yield* ProjectSetupSource; const projectionSnapshotQuery = yield* ProjectionSnapshotQuery; @@ -3430,6 +3432,16 @@ const makeCoreRpcLayer = ( // devices, which can already start threads here. // A client that can't show event tasks (no "webhook" in `supports`) // never gets them. + // The app's own: no agent tool server offers these, so no agent can + // set a brief (docs/design/project-brief-notes.md). + [WS_METHODS.projectContextSubscribe]: () => + observeRpcStream(WS_METHODS.projectContextSubscribe, projectContext.changes, { + "rpc.aggregate": "projectContext", + }), + [WS_METHODS.projectContextSetBrief]: (input) => + observeRpcEffect(WS_METHODS.projectContextSetBrief, projectContext.setBrief(input), { + "rpc.aggregate": "projectContext", + }), [WS_METHODS.scheduledTasksSubscribe]: (input) => observeRpcStream( WS_METHODS.scheduledTasksSubscribe, diff --git a/docs/design/project-brief-notes.md b/docs/design/project-brief-notes.md new file mode 100644 index 000000000..3529c28cf --- /dev/null +++ b/docs/design/project-brief-notes.md @@ -0,0 +1,377 @@ +# Project brief and project notes + +Status: plan rev 3 (Nov 19 2026). Not built. GPT-6.1 Sol reviewed rev 1 (ten findings) +and the two redesigned parts of rev 2 (eight findings). All hold, and the answers are in +"Changes from review". Rev 3's answers to the second pass were not reviewed again. +Awaiting Will's go. + +## Goal + +Two things a project keeps for the agents that work in it. + +- **Project brief.** Text the user writes once. Every thread in the project gets it, on + any agent. Threadlines stores it. It is not written to the repository. +- **Project notes.** Short notes agents write while they work, which later threads read. + Each thread gets a list of them (a title and one line each) and reads a note's text + when it needs it. + +This closes the second gap from the comparison with Claude Code's Projects (project +instructions and project memory, docs/design/lead-chat.md). It is also what the lead +chat lacks today: standing rules such as "branch from develop" live only in the lead's +own conversation and never reach the threads it starts. + +Why not AGENTS.md and CLAUDE.md, which the Instructions page already edits: + +- They live in the repository. A new thread's worktree is cut from a commit, so an edit + that is not committed does not reach it (`ThreadBootstrap.ts`, no untracked or ignored + files are copied). +- Each provider reads its own file, or none that we know of (OpenCode, Pi and Muse are + undocumented). +- They are shared with everyone who clones the repository. A brief holds one person's + working rules. + +## Decisions (the reasons are here so they can be argued) + +1. **One module outside the orchestration event log,** like scheduled tasks + (`apps/server/src/scheduled`): its own tables, service, RPCs and subscription. The + event union is decoded strictly by clients, and an unknown event type fails the + thread stream (`OrchestrationThreadStreamItem`), so new event types are avoided + here; and a brief of several thousand characters does not belong in the project + shell every client holds. +2. **Delivered where each provider keeps Threadlines' standing instructions, built + again every time an agent's session starts.** Each adapter already has that place + (Claude's system prompt append, Codex `developer_instructions`, OpenCode's + instructions entry, Pi's instructions file, Muse's first-turn preface). The project's + text is one more string in it. ACP agents have no such place, so the generic ACP + core puts it ahead of a session's first prompt, as it does a history seed. + + Rev 1 sent it in the conversation and tracked what each thread had "heard". Sol's + review showed that tracking has to mirror the provider's own conversation from + outside, and every way that conversation changes needs a hook: a goal that starts a + session with no ordinary turn, a send refused after the text was composed, a session + recovered inside `sendTurn`, a compaction whose reset is lost in a restart, a revert + that rolls the provider's history back. Standing instructions need none of that: + the provider keeps them through compaction and revert, and every session start + builds them from the project as it is now. + +3. **A thread gets the brief and the notes list as they are when its agent starts.** + New threads get changes at once. A thread already open gets them the next time its + agent starts: after the app restarts, after a model switch, after a stop. This is + the rule Claude's Projects use ("changes reach new threads"), and the page says so. + The cost: on Claude, a changed text means that thread's next session start reads its + conversation without the prompt cache once. +4. **Threadlines never hands a note's text to an agent that runs with more access + than the agent that wrote it, unless the user approved it.** A note is text one + agent leaves for every later agent. Without this rule it is a way for text from a + web page or an issue to outlive its thread and be read by a Full access agent. By + default every note an agent writes is a suggestion the user keeps or discards. With + the setting on "Keep without asking", a note is kept at once but is shown only to + agents within the writer's access, until the user approves it for all. + + What this does not promise, said plainly: + - **Raising a thread's access raises everything in it.** An agent that wrote a + suggestion, or read a limited note, still holds that text if the user later gives + its thread more access. That is true of everything a thread has read, and it is + the user's act. The rule covers what Threadlines delivers, not what a conversation + already holds. + - **Approval means a signed-in client of the app,** as for every other approval. A + browser paired through the relay is such a client. Whoever can drive it can keep a + note, as they can approve a command. + +5. **The brief is the user's words; notes are not.** The brief is framed to agents as + the user's standing instructions, and only the user can set it. Notes are framed as + information other agents left, never as instructions from the user, even after the + user keeps them. +6. **Fenced threads get none of it.** A thread behind the link fence, or one an outside + agent started, answers to an agent outside this computer's trust. That agent could + simply ask it to repeat the brief. So neither the brief nor the notes go there until + the fence lifts. The fence does not cover an outside agent the user has allowed to + "Work with all threads": it can message an ordinary thread and read the answer, as + that grant says, and such a thread may hold the brief. That grant already exposes + what those threads say, so nothing is added for it here. +7. **Per computer, with the brief copied to the others on save.** Project records are + separate on each computer. The brief is saved to every connected computer that has + the project, the way "Mute phone alerts" is. Notes stay on the computer whose agents + wrote them. + +Out of scope: syncing notes between computers, telling an open thread about a change +before its agent restarts, notes for General Chats, a project pause, usage per project. + +## User-facing behavior + +Words below are the on-screen words. Copy follows the repo's copy rules. + +### Where it lives + +Settings › Instructions, under the project picker that page already has, above the +repository files: + +- **Brief.** A text box and Save. Under it: "Every thread in this project gets this, on + any agent. New threads get a change at once. Open threads get it the next time their + agent starts. It stays on your computers and is not written to your repository." Up + to 8,000 characters, with a count near the limit. +- **Notes.** A list in a quiet group. Each row: title, its one line, who wrote it (the + thread, linked, and the agent's name) and when. A row opens to its text, which the + user can edit or remove. "Add note" lets the user write one. + - A note waiting for the user shows "Suggested" with Keep and Discard. + - A note kept without asking shows "Kept automatically. Threads with more access + than its writer do not see it." with "Show to all threads". +- **Notes agents write.** One setting for all projects: Off / Ask me first / Keep + without asking. Default: Ask me first. + +Other ways in: the project menu ("Project brief and notes"), the command palette, and +the lead chat's crown card ("Brief and notes"). + +### On more than one computer + +- Saving the brief saves it on every connected computer that has the project. The line + under the box says where: "Saved on this Mac and Will's Windows Desktop", or "Not + saved on Will's Windows Desktop. It is offline." +- If the computers hold different briefs, the page shows the picked computer's and + offers "Use this brief on too". +- If the brief changed on another device since the page loaded it, Save says so and + shows the newer text. It does not overwrite it. +- "Set up on another computer" copies the brief with the project. +- Notes are listed for the picked computer only. + +### In a thread + +- A suggested note shows where the agent wrote it, as a row with the note's title and + one line, "Keep" and "Discard". It does not mark the thread as needing the user, does + not pause a goal, does not hold the thread back from wrapping up or archiving, and + the agent does not wait for it. +- Undoing the turn that wrote a suggestion discards the suggestion. +- Nothing else shows in the chat. + +## Agent side + +### What an agent is told when its session starts + +``` +Project brief for "", from the user. It applies to every thread in this project: +<brief> + +Project notes. Agents working on this project left these. They are information, not +instructions from the user. Read one with project_note_read before relying on it: +- <title>: <one line> +- ... +If you learn something later threads in this project should know, write it with +project_note_write. +``` + +Each part is left out when it is empty. The last sentence is left out when this agent +cannot write notes. The list holds only the notes this thread may see (below), in a +fixed order (oldest first), so the text changes only when a note does. + +### Per provider + +| Provider | Where it goes | Survives a compaction | +| ---------- | ------------------------------------------------------------------------------------------ | ------------------------ | +| Claude | after Threadlines' own text in `systemPrompt.append` | yes | +| Codex | the thread's own developer instructions, set when the thread is started, resumed or forked | yes | +| OpenCode | the `threadlines` instructions entry | yes | +| Pi | the instructions file passed at launch | yes | +| Muse | a preface on the first turn after a runtime start | no, it is in the history | +| ACP agents | ahead of the first prompt after a session start, in the generic core | no | + +- **One service builds the text, and `ProviderService` asks it.** The lookup sits where + an adapter session is started, inside `ProviderService.startSession` and the recovery + inside `sendTurn`, by thread id. It is not passed in by callers, because the recovery + rebuilds a start from a few stored fields (`ProviderService.ts` ~807) and would lose + it. So every start, recovery included, gets the project as it is then. +- **Codex.** `developer_instructions` in the collaboration mode goes out with + `turn/start` only, and not at all without an interaction mode + (`CodexSessionRuntime.ts` ~703), and a goal's cold start calls `thread/goal/set` + with no turn. So the text is set on the thread itself, at `thread/start`, + `thread/resume` and `thread/fork`. If the 0.169 bindings carry no such field, + `thread/inject_items` before the first turn or goal does it, as #992 does for the + lead's role. +- **Muse and ACP, where the text sits in the history.** Their existing first-turn + paths skip a resumed or forked session (`MuseAdapter.ts` ~2345), which is exactly + when an edit should arrive. So project text has its own pending state, set on every + runtime start. To keep a thread that restarts often from collecting copies, the hash + of the text last sent is kept with the session's stored binding, and a start sends + the text only when its hash differs. A wrong hash costs one extra or one missing + copy until the next change, nothing more. +- Claude's static append is measured by `agentContextBudget.test.ts`. The project's + text is added after the measured part and is not counted in it. +- Side answers do not get it. They are short, read-only, and locked down. + +### Tools + +In the app tool group every unfenced main runtime gets (`APP_TOOL_NAMES`), so they do +not depend on "Agents can start threads": + +- `project_note_read { title }`: the note's text, who wrote it and when. Titles are + unique among kept notes, so a title names one note. +- `project_note_write { title, summary, text }`: writes a note. The result says what + happened (`kept_limited` or `suggested`), so the agent can tell the user. + +Both are loaded on demand where the provider supports it. With the setting Off, +`project_note_write` is not offered. Agents cannot remove a note or edit the brief. + +### Who can read and write what + +**What an agent can see.** Agent reads go through one projection, used by the list in +the session text and by `project_note_read`. It returns a note only when the note is +kept and either the user approved it or the calling runtime's access is within the +writer's. Suggestions are never in it: not their text, not their one line, not their +titles. A read of a title the agent may not see answers as if no such note exists. + +**Whose access.** The access compared is the one the calling runtime actually runs +with, not the thread's stored setting. The two differ: a thread lowered while a +background task runs keeps its old runtime (`ClaudeAdapter.ts` ~8639), and an early +start can run with another level than the thread stores +(`ProviderCommandReactor.ts` ~1511). The list in a session's text is built for the +access that session starts with. + +**What a write becomes.** + +| Setting | Writer | Result | +| ------------------- | ---------------------------------------- | ------------------------------------------------------- | +| Off | any agent | no tool | +| Ask me first | any agent | a suggestion | +| Keep without asking | an agent | kept, and limited to threads within the writer's access | +| any | the user, on the page | kept and approved | +| any | a runtime under an outside agent's limit | refused | + +- **The writer's access** is recorded on the note when it is written: the thread's + access and mode then, narrowed by a pass's ceiling if the thread is working on one + (`passCeiling`), compared with `withinModeCeiling`, the function passes use. +- **An agent's write never changes text another agent wrote or the user approved.** + Writing a title that already exists is always a suggested replacement, under either + setting, and the kept text stays as it is until the user keeps the replacement. The + one exception: a thread may rewrite a limited note it wrote itself. +- **A suggestion never changes after it is written.** Each is its own row with its own + id. Keep and Discard name that id, so the user approves exactly the text they read. A + second write of the same title is a second suggestion. +- **Limits:** a brief up to 8,000 characters; a note's title 80, its one line 200, its + text 8,000; 60 kept notes per project; 5 suggestions waiting from one thread and 40 + in a project. A refusal names only the writer's own count ("This thread has 5 notes + waiting for the user."), or says the project can take no more until the user reviews + some, so it does not reveal what other threads wrote. + +### The lead chat + +Its role text gains one line: "Rules the user gives you for the whole project belong in +a project note, so the threads you start get them." + +## Data model + +### Storage (`apps/server/src/projectContext/`, next migration) + +- `project_briefs`: `project_id`, `text`, `revision`, `updated_at`. One row, so the + text and its revision change together. +- `project_notes`: `id`, `project_id`, `title`, `summary`, `text`, `approved` (0 or 1), + `writer_ceiling_json` (null for the user's own notes), `author_json` (thread id and + agent, or the user), `created_at`, `updated_at`. +- `project_note_suggestions`: `id`, `project_id`, `title`, `summary`, `text`, + `author_json`, `thread_id`, `turn_id`, `created_at`. Never updated, only deleted. +- Every write that touches more than one row is one transaction. +- A project is soft-deleted, so its rows stay, as scheduled tasks' do. At startup the + module drops suggestions whose turn no longer exists (a revert that a restart cut + off), as the scheduler reconciles what the last process left. + +### Service and RPCs (`packages/contracts/src/projectContext.ts`, `rpc.ts`) + +- `projectContext.subscribe`: per computer, each project's brief with its revision, its + notes without their text, and suggestions with the thread and turn they came from. +- `projectContext.setBrief { projectId, text, expectedRevision }`: refused with the + current text when the revision moved. The save to other computers sends each one the + revision the client last saw from it. +- `readNote`, `saveNote`, `removeNote`, `approveNote { noteId }`, + `resolveSuggestion { suggestionId, keep | discard }`. +- These RPCs are the app's own. They are not on the outside agents' or the assistants' + tool servers, so no agent can set the brief or keep a note. +- Capability `projectContext` in `environment.ts`, so a client hides all of it on an + older server, and the save to other computers skips a computer without it. +- Server setting `projectNotes: "off" | "ask" | "auto"`, default `"ask"`, with a place + in `appPlaces.ts` agents can read and not change. + +### Delivery + +`ProviderSessionStartInput` gains optional `projectInstructions: string`. +`ProviderService` fills it from the service at every adapter start, by thread id and +with the access the runtime is starting with. Each adapter puts it where the table +says. The service returns nothing for a fenced thread (`isLinkFenced`, or +`outsideOrigin`), a General Chat, or a side runtime. + +## Every surface + +- **Entry points:** Settings › Instructions, the project menu, the palette, the lead + chat's crown card. +- **Clients:** web, desktop and the phone view share the components. +- **Providers:** the table above. Six small changes, each in the place that provider's + Threadlines instructions already go. +- **Contracts:** a new contracts file, RPCs, one capability, one server setting, one + optional field on the session start input. No orchestration command, event or status + changes. +- **Reverse states:** clear the brief; remove a note; discard a suggestion; turn the + setting Off (agents stop writing, kept notes still go out); undo a turn (its + suggestions go); "Show to all threads" has no undo except removing the note. +- **App guide:** places for the brief, the notes and the setting; one topic. + +## Build order + +Two pieces, each its own pull request, the second on top of the first. + +1. **Brief.** The module, `project_briefs`, the service and RPCs, the capability, + `projectInstructions` and all six providers, the Instructions page section, saving + to the other computers, the copy in "Set up on another computer", the guide. Tests: + each adapter puts the text where the table says, asserted on what the adapter + builds (the replay tests cannot show it: Codex replay blanks + `developer_instructions` and Claude replay leaves `systemPrompt` out); a session + recovered inside `sendTurn` carries the brief as it is then, after an edit; a + Codex goal's cold start carries it; Muse and ACP send it again on a resume only when + it changed; a fenced thread, a General Chat and a side answer do not get it; a save + with a stale revision is refused and loses nothing; one browser test for the page. +2. **Notes.** The two note tables, the tools, the setting, suggestions and their row in + the thread, the list on the page, the lead's line. Tests: Off, Ask and Keep; a + suggestion is in no agent's list and cannot be read by title; a note kept without + asking is not listed for, or readable by, a runtime with more access than its + writer, and is after "Show to all threads"; a runtime that kept Full access after + its thread was lowered is judged as Full; a pass-limited thread's note carries the + pass's ceiling; a runtime under an outside limit is refused; a write over any + existing title leaves the kept text and makes a suggestion; a thread rewrites its + own limited note; Keep resolves the exact suggestion and a later write is a new + one; a refusal at a limit does not reveal other threads' counts; an undone turn's suggestion goes, at once and after a + restart; limits; the suggestion row does not mark the thread as needing the user, + pause a goal (`goalWaitOf`), or block wrapping up. + +Live check before calling it done, on a throwaway stack: a brief reaches a Codex thread +and a Claude thread; an edit reaches a new thread and, after its agent restarts, an +open one; an agent writes a note, the user keeps it, and a second thread on the other +provider uses it. + +## Changes from review + +| # | Finding | Answer | +| --- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| 1 | Under "Keep without asking", only lead passes were held to suggestions; a child with less access, a scheduled run or a room agent could reach a Full access agent | One rule for every writer: a note kept without asking reaches only threads within the writer's access until the user approves it. A runtime under an outside limit cannot write | +| 2 | Nothing stopped an agent reading a suggestion by its title | One agent-side projection, kept notes only, for the list and the read tool. Suggestions are a separate table it never reads | +| 3 | A suggestion could change between the user reading it and pressing Keep | A suggestion is its own row, never updated. Keep names its id | +| 4 | The brief went to fenced threads, where an outside agent could ask for it | Fenced threads get none of it | +| 5 | A thread that only ever runs goal turns never got the brief | It is in the session's standing instructions, which a goal's session start builds too | +| 6 | "Full or changes only" was decided per attempt and broke when a send failed or a session was recovered | No per-thread delivery state. Every session start builds the text | +| 7 | Marking as heard could be skipped after the provider had taken the turn | Same | +| 8 | A compaction's reset could be lost in a restart | Same. Standing instructions survive compaction where the provider has them | +| 9 | A revert rolls the provider's history back while "heard" stays | Same. A revert's suggestions are discarded, and that is reconciled at startup | +| 10 | Text and revision in separate tables, and no check for two clients saving at once | One row holds both. `setBrief` carries the revision it expects | + +Second pass, on rev 2's two redesigned parts. Sol confirmed that OpenCode's entry is +per session, Pi's file is hashed over the whole text, Codex runs one app-server per +runtime, nothing in the code depends on Claude's append being identical across +threads, and `thread_read` and room history return messages, not tool arguments. + +| # | Finding | Answer | +| --- | ------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------- | +| 1 | Raising a thread's access carries text it already read or wrote into a higher-access agent | Not promised, and said so under decision 4. The rule covers what Threadlines delivers | +| 2 | The thread's stored access can understate what the runtime runs with | The runtime's actual access is what is compared, for the list and for reads | +| 3 | An outside agent allowed to "Work with all threads" can ask an ordinary thread for the brief | Not promised, and said so under decision 6. That grant already exposes those threads | +| 4 | Keeping the RPCs off the agents' tool servers does not make approval human-only: a paired browser is a client | Approval means a signed-in client, as for every approval. Said so under decision 4 | +| 5 | Codex's `developer_instructions` goes out with a turn, and not for a cold goal | Set on the thread at start, resume and fork | +| 6 | Muse's first-turn preface skips resumed sessions | Its own pending state on every runtime start, sent when the text's hash changed | +| 7 | Recovery rebuilds a start from stored fields and would lose or stale the text | `ProviderService` asks the service at every start, recovery included | +| 8 | A second note with the same title cannot be read by title | Titles are unique among kept notes. A write over an existing title is a suggestion | +| | A limit refusal revealed how many notes were waiting | Refusals name only the writer's own count | +| | Re-recorded replays cannot show delivery | Tests assert what each adapter builds | diff --git a/packages/contracts/src/environment.ts b/packages/contracts/src/environment.ts index 81da68b50..952d76bef 100644 --- a/packages/contracts/src/environment.ts +++ b/packages/contracts/src/environment.ts @@ -206,6 +206,13 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({ * the whole batch, so clients only show the checkboxes for this one. */ childStartSelection: Schema.optionalKey(Schema.Boolean), + /** + * The server keeps a brief per project and gives it to every thread there + * (`projectContext.*`, docs/design/project-brief-notes.md). Older servers + * omit it: clients hide the brief, and a save to several computers skips + * one without it. + */ + projectContext: Schema.optionalKey(Schema.Boolean), }); export type ExecutionEnvironmentCapabilities = typeof ExecutionEnvironmentCapabilities.Type; diff --git a/packages/contracts/src/index.ts b/packages/contracts/src/index.ts index 9d7b90237..6de99680c 100644 --- a/packages/contracts/src/index.ts +++ b/packages/contracts/src/index.ts @@ -37,6 +37,7 @@ export * from "./filesystem.ts"; export * from "./usage.ts"; export * from "./links.ts"; export * from "./scheduledTasks.ts"; +export * from "./projectContext.ts"; export * from "./themes.ts"; export * from "./themeShowcase.ts"; export * from "./themeVsCode.ts"; diff --git a/packages/contracts/src/projectContext.ts b/packages/contracts/src/projectContext.ts new file mode 100644 index 000000000..107c84fd9 --- /dev/null +++ b/packages/contracts/src/projectContext.ts @@ -0,0 +1,63 @@ +/** + * A project's brief: text the user writes once, which every thread in the + * project gets as standing instructions, on any agent (docs/design/ + * project-brief-notes.md). Kept by Threadlines on each computer, outside the + * orchestration event log and outside the repository. + */ +import * as Schema from "effect/Schema"; + +import { IsoDateTime, NonNegativeInt, ProjectId, TrimmedNonEmptyString } from "./baseSchemas.ts"; + +/** The longest brief a project keeps. */ +export const PROJECT_BRIEF_MAX_CHARS = 8_000; + +/** + * A project's brief on one computer. `revision` counts its saves there, so a + * save from a page that loaded an older one is refused instead of lost. + */ +export const ProjectBrief = Schema.Struct({ + projectId: ProjectId, + /** "" when the project has none. */ + text: Schema.String, + revision: NonNegativeInt, + /** Null before the first save. */ + updatedAt: Schema.NullOr(IsoDateTime), +}); +export type ProjectBrief = typeof ProjectBrief.Type; + +/** What `projectContext.subscribe` sends: every project's brief that has one. */ +export const ProjectContextSnapshot = Schema.Struct({ + briefs: Schema.Array(ProjectBrief), +}); +export type ProjectContextSnapshot = typeof ProjectContextSnapshot.Type; + +export const ProjectContextSubscribeInput = Schema.Struct({}); +export type ProjectContextSubscribeInput = typeof ProjectContextSubscribeInput.Type; + +/** + * Save a project's brief. `expectedRevision` is the revision the page last saw + * on this computer; a save from behind another device's is refused (`stale`) + * with the brief as it is now. "" clears it. + */ +export const ProjectBriefSetInput = Schema.Struct({ + projectId: ProjectId, + text: Schema.String.check(Schema.isMaxLength(PROJECT_BRIEF_MAX_CHARS)), + expectedRevision: NonNegativeInt, +}); +export type ProjectBriefSetInput = typeof ProjectBriefSetInput.Type; + +export const ProjectBriefSetResult = Schema.Union([ + Schema.Struct({ outcome: Schema.Literal("saved"), brief: ProjectBrief }), + /** Another device saved first: nothing was written, and `brief` is theirs. */ + Schema.Struct({ outcome: Schema.Literal("stale"), brief: ProjectBrief }), +]); +export type ProjectBriefSetResult = typeof ProjectBriefSetResult.Type; + +export class ProjectContextError extends Schema.TaggedError<ProjectContextError>()( + "ProjectContextError", + { detail: TrimmedNonEmptyString }, +) { + override get message(): string { + return this.detail; + } +} diff --git a/packages/contracts/src/projectSetup.ts b/packages/contracts/src/projectSetup.ts index d0d7b3157..79df7cd4d 100644 --- a/packages/contracts/src/projectSetup.ts +++ b/packages/contracts/src/projectSetup.ts @@ -9,6 +9,7 @@ import { TrimmedNonEmptyString, } from "./baseSchemas.ts"; import { ProjectScript } from "./orchestration.ts"; +import { PROJECT_BRIEF_MAX_CHARS } from "./projectContext.ts"; /** * Setting up a project on another computer (docs/design/fleet.md, Part 8). @@ -70,6 +71,8 @@ export const ProjectSetupSource = Schema.Struct({ * few large files make up most of the bytes. Absent from older servers. */ sizeBytes: Schema.optional(NonNegativeInt), + /** The project's brief there (ProjectBrief.text); absent when it has none or the server is older. */ + brief: Schema.optional(Schema.String), }); export type ProjectSetupSource = typeof ProjectSetupSource.Type; @@ -123,6 +126,8 @@ export const ProjectSetupStartInput = Schema.Struct({ files: Schema.Array(ProjectSetupFile), /** The source's `sizeBytes`: the download's progress is measured against it. */ expectedBytes: Schema.optional(NonNegativeInt), + /** The source's brief, given to the new project here once it is added. */ + brief: Schema.optional(Schema.String.check(Schema.isMaxLength(PROJECT_BRIEF_MAX_CHARS))), }); export type ProjectSetupStartInput = typeof ProjectSetupStartInput.Type; diff --git a/packages/contracts/src/provider.ts b/packages/contracts/src/provider.ts index 083cb46d3..2b1f97a30 100644 --- a/packages/contracts/src/provider.ts +++ b/packages/contracts/src/provider.ts @@ -231,6 +231,14 @@ export const ProviderSessionStartInput = Schema.Struct({ approvalPolicy: Schema.optional(ProviderApprovalPolicy), sandboxMode: Schema.optional(ProviderSandboxMode), runtimeMode: RuntimeMode, + /** + * The project's brief, as standing instructions for this session + * (docs/design/project-brief-notes.md). Filled by `ProviderService` at every + * start, recovery included, from the project as it is then; never by + * callers. Each driver puts it where its own standing instructions go. + * Absent: nothing to add (no brief, a fenced thread, a side runtime). + */ + projectInstructions: Schema.optional(Schema.String), }); export type ProviderSessionStartInput = typeof ProviderSessionStartInput.Type; diff --git a/packages/contracts/src/rpc.ts b/packages/contracts/src/rpc.ts index 4883ebe6e..23930d9f1 100644 --- a/packages/contracts/src/rpc.ts +++ b/packages/contracts/src/rpc.ts @@ -64,6 +64,13 @@ import { ScheduledTaskTestWebhookInput, ScheduledTaskUpdateInput, } from "./scheduledTasks.ts"; +import { + ProjectBriefSetInput, + ProjectBriefSetResult, + ProjectContextError, + ProjectContextSnapshot, + ProjectContextSubscribeInput, +} from "./projectContext.ts"; import { ThemeContent, ThemeEntryIdInput, @@ -761,6 +768,8 @@ export const WS_METHODS = { linksRespondRequest: "links.respondRequest", // Scheduled tasks (docs/design/fleet.md, Part 6). Owner and client sessions alike. + projectContextSubscribe: "projectContext.subscribe", + projectContextSetBrief: "projectContext.setBrief", scheduledTasksSubscribe: "scheduledTasks.subscribe", scheduledTasksListRuns: "scheduledTasks.listRuns", scheduledTasksCreate: "scheduledTasks.create", @@ -2169,6 +2178,21 @@ export const WsLinksRespondRequestRpc = Rpc.make(WS_METHODS.linksRespondRequest, }); /** This computer's scheduled tasks, each with its last run; again on every change. */ +/** Every project's brief on this computer, again whenever one changes. */ +export const WsProjectContextSubscribeRpc = Rpc.make(WS_METHODS.projectContextSubscribe, { + payload: ProjectContextSubscribeInput, + success: ProjectContextSnapshot, + error: ProjectContextError, + stream: true, +}); + +/** Save a project's brief, refused as `stale` when another device saved since. */ +export const WsProjectContextSetBriefRpc = Rpc.make(WS_METHODS.projectContextSetBrief, { + payload: ProjectBriefSetInput, + success: ProjectBriefSetResult, + error: ProjectContextError, +}); + export const WsScheduledTasksSubscribeRpc = Rpc.make(WS_METHODS.scheduledTasksSubscribe, { payload: ScheduledTasksSubscribeInput, success: ScheduledTasksSnapshot, @@ -3021,6 +3045,8 @@ export const WsCoreRpcGroup = RpcGroup.make( WsLinksSetAccessRpc, WsLinksRemoveRpc, WsLinksRespondRequestRpc, + WsProjectContextSubscribeRpc, + WsProjectContextSetBriefRpc, WsScheduledTasksSubscribeRpc, WsScheduledTasksListRunsRpc, WsScheduledTasksCreateRpc, From cd7c39611166755168f9a3ebdfec94444d9ff4a2 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:52:16 -0500 Subject: [PATCH 2/4] =?UTF-8?q?feat(web):=20the=20project=20brief=20on=20S?= =?UTF-8?q?ettings=20=E2=80=BA=20Instructions,=20saved=20on=20every=20comp?= =?UTF-8?q?uter?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A Brief section under the project picker: a text box, Save, and a line saying which computers the save reached. Each computer's save sends the revision this app last saw there; a stale answer from the picked computer shows the newer text and keeps the user's edit one click away. Computers that hold another brief get a Use this brief on <computer> too button. Hidden where the project's computer lacks the projectContext capability. Also: projectContext.subscribe and setBrief on the web RPC client, the source's brief carried into Set up on another computer, ways in from the project menu, the command palette and the lead chat's crown card, and the app guide's place and topic for the brief. --- apps/server/src/guide/topics.ts | 19 ++ .../src/components/CommandPaletteDialog.tsx | 32 ++ .../web/src/components/chat/LeadChatHints.tsx | 63 +++- .../settings/AgentInstructionsSettings.tsx | 31 +- .../settings/ProjectBriefSection.tsx | 285 ++++++++++++++++++ .../settings/SettingsPanels.browser.tsx | 229 +++++++++++++- .../components/sidebar/ProjectScopeMenu.tsx | 27 ++ .../projectSetups/projectSetups.ts | 4 + apps/web/src/projectBrief.ts | 224 ++++++++++++++ apps/web/src/rpc/wsRpcClient.ts | 14 + packages/shared/src/appPlaces.ts | 14 +- 11 files changed, 922 insertions(+), 20 deletions(-) create mode 100644 apps/web/src/components/settings/ProjectBriefSection.tsx create mode 100644 apps/web/src/projectBrief.ts diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index 735e36fd3..e67c7f3c6 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -328,6 +328,25 @@ When a Claude or Codex usage limit stops a thread, the notice above the composer body: `{place:settings.plugins} manages what agents can use beyond their own tools, per provider, on this computer or one project: {place:plugins.installed}, {place:plugins.apps}, {place:plugins.connections} (MCP servers) and {place:plugins.hooks}. Its Skills tab is {place:plugins.skills}. {place:settings.instructions} shows the instruction files each provider reads in a project (like AGENTS.md or CLAUDE.md), to open or edit.`, + }, + { + id: "project-brief", + title: "Project brief", + keywords: [ + "brief", + "project brief", + "project instructions", + "standing instructions", + "rules for every thread", + "project memory", + ], + body: `A project's brief is text the user writes once. Every thread in the project gets it as the user's standing instructions, on any agent. It is set in {place:instructions.brief}: pick the project at the top, write it, Save. Up to 8,000 characters. Agents can't change it. + +New threads get a change at once. A thread that is already open gets it the next time its agent starts: after the app restarts, after a model switch, or after a stop. Threads behind the link fence, or started by an outside agent, don't get it. + +Threadlines keeps it on each computer, not in the repository. Save stores it on every connected computer that has the project, and the line under the box says where it went. If the computers hold different briefs, the page shows the picked computer's and offers to copy it to the others. If another device saved first, Save says so and shows the newer text instead of overwriting it. Set up on another computer copies the brief with the project. + +The project menu's Project brief and notes, the command palette and the lead chat's crown card open it too.`, }, { id: "browser-panel", diff --git a/apps/web/src/components/CommandPaletteDialog.tsx b/apps/web/src/components/CommandPaletteDialog.tsx index 6d584397b..b1bdbb8fd 100644 --- a/apps/web/src/components/CommandPaletteDialog.tsx +++ b/apps/web/src/components/CommandPaletteDialog.tsx @@ -60,6 +60,7 @@ import { UsersRoundIcon, MonitorUpIcon, CrownIcon, + ScrollTextIcon, FolderSyncIcon, WaypointsIcon, CalendarClockIcon, @@ -189,6 +190,11 @@ import { editorLabel } from "./EditorOpenOptions"; import { openConnectComputerDialog } from "./settings/connections/JoinComputerDialog"; import { openThreadMoveDialog } from "./ThreadMoveDialog"; import { openProjectSetupDialog } from "./ProjectSetupDialog"; +import { + PROJECT_BRIEF_MENU_LABEL, + projectBriefLocation, + useProjectBriefSupport, +} from "../projectBrief"; import { openReportProblemDialog } from "./ReportProblemDialog"; import { openWhatsNewDialog } from "./WhatsNewDialog"; import { APP_VERSION } from "../branding"; @@ -793,6 +799,7 @@ export function OpenCommandPaletteDialog() { ) ?? null) : null; const currentProjectCwd = currentProject?.cwd ?? null; + const supportsProjectBrief = useProjectBriefSupport(); // The project's worktrees made outside Threadlines, asked for while the // palette is open: the action below shows only when there is one to add. const currentProjectRef = useMemo( @@ -1730,6 +1737,31 @@ export function OpenCommandPaletteDialog() { } } + if ( + currentProject?.kind === "workspace" && + supportsProjectBrief(currentProject.environmentId) + ) { + const briefProject = currentProject; + actionItems.push({ + kind: "action", + value: "action:project-brief", + searchTerms: [ + "brief", + "project brief", + "notes", + "instructions", + "rules", + briefProject.name, + ], + title: PROJECT_BRIEF_MENU_LABEL, + description: briefProject.name, + icon: <ScrollTextIcon className={ITEM_ICON_CLASS} />, + run: async () => { + await navigate(projectBriefLocation(briefProject)); + }, + }); + } + actionItems.push({ kind: "submenu", value: "action:new-thread-in", diff --git a/apps/web/src/components/chat/LeadChatHints.tsx b/apps/web/src/components/chat/LeadChatHints.tsx index 89ec6f488..22e86751a 100644 --- a/apps/web/src/components/chat/LeadChatHints.tsx +++ b/apps/web/src/components/chat/LeadChatHints.tsx @@ -7,6 +7,7 @@ */ import { scopedProjectKey, scopeProjectRef } from "@threadlines/client-runtime"; import type { ScopedThreadRef } from "@threadlines/contracts"; +import { useNavigate } from "@tanstack/react-router"; import * as Schema from "effect/Schema"; import { CrownIcon, XIcon } from "lucide-react"; import { type ReactElement, useCallback, useState } from "react"; @@ -14,7 +15,8 @@ import { type ReactElement, useCallback, useState } from "react"; import { useLocalStorage } from "../../hooks/useLocalStorage"; import { LEAD_CHAT_EXPLANATION, readLeadMenuState, setProjectLead } from "../../leadChat"; import { useComputerConfig } from "../../newThreadDefaults"; -import { selectSidebarThreadSummaryByRef, useStore } from "../../store"; +import { projectBriefLocation, useProjectBriefSupport } from "../../projectBrief"; +import { selectProjectByRef, selectSidebarThreadSummaryByRef, useStore } from "../../store"; import { Button } from "../ui/button"; import { PreviewCard, PreviewCardPopup, PreviewCardTrigger } from "../ui/previewCard"; @@ -41,6 +43,15 @@ export function LeadChatCard({ const [open, setOpen] = useState(false); const projectId = useThreadProject(threadRef); const showCard = useCallback(() => setOpen(true), []); + const navigate = useNavigate(); + // The lead's project's brief, where its computer keeps one. + const projectCwd = useStore((state) => + projectId === null + ? null + : (selectProjectByRef(state, scopeProjectRef(threadRef.environmentId, projectId))?.cwd ?? + null), + ); + const briefSupported = useProjectBriefSupport()(threadRef.environmentId); return ( <PreviewCard open={open} onOpenChange={setOpen}> <PreviewCardTrigger @@ -61,21 +72,41 @@ export function LeadChatCard({ </div> <p className="mt-1 text-xs leading-normal text-muted-foreground">{LEAD_CHAT_EXPLANATION}</p> {projectId !== null ? ( - <button - type="button" - data-testid="lead-chat-card-stop" - className="mt-2.5 rounded-sm text-xs text-muted-foreground transition-colors hover:text-foreground focus-ring" - onClick={() => { - setOpen(false); - void setProjectLead({ - environmentId: threadRef.environmentId, - projectId, - threadId: null, - }); - }} - > - Stop using as lead chat - </button> + <div className="mt-2.5 flex flex-wrap items-center gap-x-4 gap-y-1.5"> + {projectCwd !== null && briefSupported ? ( + <button + type="button" + data-testid="lead-chat-card-brief" + className="rounded-sm text-xs text-muted-foreground transition-colors hover:text-foreground focus-ring" + onClick={() => { + setOpen(false); + void navigate( + projectBriefLocation({ + environmentId: threadRef.environmentId, + cwd: projectCwd, + }), + ); + }} + > + Brief and notes + </button> + ) : null} + <button + type="button" + data-testid="lead-chat-card-stop" + className="rounded-sm text-xs text-muted-foreground transition-colors hover:text-foreground focus-ring" + onClick={() => { + setOpen(false); + void setProjectLead({ + environmentId: threadRef.environmentId, + projectId, + threadId: null, + }); + }} + > + Stop using as lead chat + </button> + </div> ) : null} </PreviewCardPopup> </PreviewCard> diff --git a/apps/web/src/components/settings/AgentInstructionsSettings.tsx b/apps/web/src/components/settings/AgentInstructionsSettings.tsx index 6778a2bd3..9560f6366 100644 --- a/apps/web/src/components/settings/AgentInstructionsSettings.tsx +++ b/apps/web/src/components/settings/AgentInstructionsSettings.tsx @@ -1,5 +1,6 @@ import { FileTextIcon, LoaderIcon, RefreshCwIcon, SaveIcon } from "lucide-react"; import type { + EnvironmentId, ProviderInstructionFile, ProviderInstructionFilesResult, ProviderInstructionFileKind, @@ -41,6 +42,7 @@ import { type ExtensionScopeProjectEntry, } from "./ExtensionsSettings.logic"; import { useScopeMachines } from "./useScopeMachines"; +import { ProjectBriefSection } from "./ProjectBriefSection"; interface InstructionDraft { readonly contents: string; @@ -241,6 +243,24 @@ export function AgentInstructionsSettingsPanel() { const selectedProject = projectOptions.find((project) => project.key === picked?.key) ?? picked; const cwd = selectedProject?.cwd ?? ""; const showComputers = projectGroups.length > 1; + // The project record behind the pick, for its brief (the picker lists one + // entry per computer and folder). + const selectedProjectRecord = useMemo( + () => + selectedProject === null + ? null + : (projects.find( + (project) => + extensionScopeKey({ environmentId: project.environmentId, cwd: project.cwd }) === + selectedProject.key, + ) ?? null), + [projects, selectedProject], + ); + const computerLabel = useCallback( + (environmentId: EnvironmentId) => + machines.find((machine) => machine.environmentId === environmentId)?.label ?? environmentId, + [machines], + ); // Instruction files live on the machine that owns the project, and the picker // spans machines, so the API is resolved from the project rather than from // whichever backend this client happens to be paired with. Resolved per call: @@ -528,7 +548,7 @@ export function AgentInstructionsSettingsPanel() { description={ instructions?.generatedAt ? `Files loaded ${new Date(instructions.generatedAt).toLocaleString()}.` - : "Pick the project whose agent instruction files you want to edit." + : "Pick the project whose brief and instruction files you want to edit." } status={error} control={ @@ -593,6 +613,15 @@ export function AgentInstructionsSettingsPanel() { /> </SettingsSection> + {selectedProjectRecord !== null && selectedProject !== null ? ( + <ProjectBriefSection + key={selectedProject.key} + project={selectedProjectRecord} + projects={projects} + computerLabel={computerLabel} + /> + ) : null} + <SettingsSection place="instructions.files" headerAction={ diff --git a/apps/web/src/components/settings/ProjectBriefSection.tsx b/apps/web/src/components/settings/ProjectBriefSection.tsx new file mode 100644 index 000000000..47d545ea6 --- /dev/null +++ b/apps/web/src/components/settings/ProjectBriefSection.tsx @@ -0,0 +1,285 @@ +/** + * Settings › Instructions › Brief (docs/design/project-brief-notes.md): the + * picked project's brief, saved on every connected computer that has the + * project. Shown only when the picked project's computer keeps briefs. + * + * Mount it keyed by the picked project: a pick starts with a clean draft. + */ +import { + type EnvironmentId, + PROJECT_BRIEF_MAX_CHARS, + type ProjectBrief, +} from "@threadlines/contracts"; +import { LoaderIcon, SaveIcon } from "lucide-react"; +import { useMemo, useState } from "react"; + +import { useSettings } from "../../hooks/useSettings"; +import { + deriveLogicalProjectKeyFromSettings, + selectProjectGroupingSettings, +} from "../../logicalProject"; +import { + briefIn, + type BriefSaveOutcome, + type BriefTarget, + computerInSentence, + describeBriefSave, + PROJECT_BRIEF_COUNT_FROM, + saveBriefOn, + useProjectBriefSnapshots, + useProjectBriefSupport, +} from "../../projectBrief"; +import type { Project } from "../../types"; +import { Button } from "../ui/button"; +import { SettingsSection } from "./settingsLayout"; + +const BRIEF_ABOUT = + "Every thread in this project gets this, on any agent. New threads get a change at once. Open threads get it the next time their agent starts. It stays on your computers and is not written to your repository."; + +/** The user's edit, and the revision on the picked computer it started from. */ +interface BriefDraft { + readonly text: string; + readonly baseRevision: number; +} + +/** What the line under the box says, until the next edit. */ +type BriefNotice = + | { readonly kind: "result"; readonly text: string } + /** The picked computer refused the save: another device saved first. */ + | { readonly kind: "stale"; readonly mine: string }; + +/** The newer of two copies of one computer's brief: a save's answer can beat its snapshot. */ +function newer(left: ProjectBrief | null, right: ProjectBrief | null): ProjectBrief | null { + if (left === null) return right; + if (right === null) return left; + return right.revision > left.revision ? right : left; +} + +export function ProjectBriefSection({ + project, + projects, + computerLabel, +}: { + /** The picked project. */ + project: Project; + /** Every workspace project this app knows, on every computer. */ + projects: readonly Project[]; + /** A computer's name as the page shows it. */ + computerLabel: (environmentId: EnvironmentId) => string; +}) { + const groupingSettings = useSettings(selectProjectGroupingSettings); + const supports = useProjectBriefSupport(); + + // The picked copy first, then the project's copies on other computers (the + // ones the sidebar shows as the same project). + const targets = useMemo((): readonly BriefTarget[] => { + const settings = { + sidebarProjectGroupingMode: groupingSettings.sidebarProjectGroupingMode, + sidebarProjectGroupingOverrides: groupingSettings.sidebarProjectGroupingOverrides, + }; + const logicalKey = deriveLogicalProjectKeyFromSettings(project, settings); + const toTarget = (copy: Project): BriefTarget => ({ + environmentId: copy.environmentId, + projectId: copy.id, + label: computerLabel(copy.environmentId), + supported: supports(copy.environmentId), + }); + const others = projects + .filter( + (copy) => + !(copy.environmentId === project.environmentId && copy.id === project.id) && + deriveLogicalProjectKeyFromSettings(copy, settings) === logicalKey, + ) + .map(toTarget) + .toSorted((left, right) => left.label.localeCompare(right.label)); + return [toTarget(project), ...others]; + }, [ + computerLabel, + groupingSettings.sidebarProjectGroupingMode, + groupingSettings.sidebarProjectGroupingOverrides, + project, + projects, + supports, + ]); + const picked = targets[0]!; + const followed = useMemo( + () => + targets + .filter((target) => target.supported) + .map((target) => target.environmentId) + .filter((id, index, ids) => ids.indexOf(id) === index), + [targets], + ); + const snapshots = useProjectBriefSnapshots(followed); + + const [draft, setDraft] = useState<BriefDraft | null>(null); + const [notice, setNotice] = useState<BriefNotice | null>(null); + const [saving, setSaving] = useState(false); + /** Each computer's brief as a save answered it, until its snapshot catches up. */ + const [answered, setAnswered] = useState<Readonly<Record<string, ProjectBrief>>>({}); + + const briefOn = (target: BriefTarget): ProjectBrief | null => + newer( + briefIn(snapshots[target.environmentId], target.projectId), + answered[`${target.environmentId}\n${target.projectId}`] ?? null, + ); + const pickedBrief = briefOn(picked); + const text = draft?.text ?? pickedBrief?.text ?? ""; + const dirty = draft !== null && pickedBrief !== null && draft.text !== pickedBrief.text; + + if (!picked.supported) return null; + + const remember = (outcomes: readonly BriefSaveOutcome[], sent: readonly BriefTarget[]) => { + setAnswered((previous) => { + const next = { ...previous }; + outcomes.forEach((outcome, index) => { + if (outcome.kind !== "saved" && outcome.kind !== "stale") return; + const target = sent[index]!; + next[`${target.environmentId}\n${target.projectId}`] = outcome.brief; + }); + return next; + }); + }; + + const save = async () => { + if (draft === null || pickedBrief === null || saving) return; + const sending = draft.text; + setSaving(true); + try { + const first = await saveBriefOn(picked, sending, draft.baseRevision); + remember([first], [picked]); + if (first.kind === "stale") { + // Theirs stays; the box shows it, and the user's text can come back. + setDraft(null); + setNotice({ kind: "stale", mine: sending }); + return; + } + if (first.kind !== "saved") { + setNotice({ kind: "result", text: describeBriefSave([first]) }); + return; + } + const others = targets.slice(1); + const rest = await Promise.all( + others.map((target) => saveBriefOn(target, sending, briefOn(target)?.revision ?? 0)), + ); + remember(rest, others); + setDraft(null); + setNotice({ kind: "result", text: describeBriefSave([first, ...rest]) }); + } finally { + setSaving(false); + } + }; + + const copyTo = async (target: BriefTarget) => { + if (pickedBrief === null || saving) return; + setSaving(true); + try { + const outcome = await saveBriefOn(target, pickedBrief.text, briefOn(target)?.revision ?? 0); + remember([outcome], [target]); + setNotice({ kind: "result", text: describeBriefSave([outcome]) }); + } finally { + setSaving(false); + } + }; + + // Copies elsewhere that hold another brief, once they have said; offered + // only while nothing here is unsaved, since Save would reach them anyway. + const differing = + dirty || pickedBrief === null || notice?.kind === "stale" + ? [] + : targets.slice(1).filter((target) => { + const theirs = briefOn(target); + return theirs !== null && theirs.text !== pickedBrief.text; + }); + + return ( + <SettingsSection place="instructions.brief"> + <div className="flex flex-col gap-2.5 px-3.5 py-3"> + <textarea + value={text} + disabled={pickedBrief === null} + // Held while saving, so what is sent is what the box shows. + readOnly={saving} + maxLength={PROJECT_BRIEF_MAX_CHARS} + onChange={(event) => { + const next = event.currentTarget.value; + setDraft((current) => ({ + text: next, + baseRevision: current?.baseRevision ?? pickedBrief?.revision ?? 0, + })); + if (notice !== null) setNotice(null); + }} + rows={6} + placeholder="Rules every thread in this project should follow, like which branch to start from." + aria-label="Project brief" + className="min-h-28 w-full resize-y rounded-lg bg-field px-3 py-2 text-[13px] leading-relaxed text-foreground shadow-(--field-shadow) outline-none transition-shadow placeholder:text-muted-foreground focus-ring disabled:opacity-60" + /> + <div className="flex flex-col gap-2 sm:flex-row sm:items-start sm:justify-between sm:gap-4"> + <p className="text-xs leading-[18px] text-muted-foreground">{BRIEF_ABOUT}</p> + <div className="flex shrink-0 items-center justify-end gap-2.5"> + {text.length >= PROJECT_BRIEF_COUNT_FROM ? ( + <span + className="font-mono text-[11px] text-muted-foreground tabular-nums" + data-testid="project-brief-count" + > + {text.length.toLocaleString()} / {PROJECT_BRIEF_MAX_CHARS.toLocaleString()} + </span> + ) : null} + <Button + size="xs" + aria-label="Save brief" + disabled={!dirty || saving} + onClick={() => void save()} + > + {saving ? ( + <LoaderIcon className="size-3.5 animate-spin" /> + ) : ( + <SaveIcon className="size-3.5" /> + )} + Save + </Button> + </div> + </div> + {notice?.kind === "result" ? ( + <p role="status" className="text-xs leading-[18px] text-foreground"> + {notice.text} + </p> + ) : notice?.kind === "stale" ? ( + <div role="status" className="flex flex-wrap items-center gap-x-3 gap-y-1.5"> + <p className="text-xs leading-[18px] text-foreground"> + Another device saved this brief first. Its text is shown, and your edit was not saved. + </p> + <Button + size="xs" + variant="outline" + onClick={() => { + setDraft({ text: notice.mine, baseRevision: pickedBrief?.revision ?? 0 }); + setNotice(null); + }} + > + Bring back my edit + </Button> + </div> + ) : null} + {differing.map((target) => ( + <div + key={`${target.environmentId}\n${target.projectId}`} + className="flex flex-wrap items-center gap-x-3 gap-y-1.5" + > + <p className="text-xs leading-[18px] text-muted-foreground"> + {target.label} has a different brief. + </p> + <Button + size="xs" + variant="outline" + disabled={saving} + onClick={() => void copyTo(target)} + > + Use this brief on {computerInSentence(target.label)} too + </Button> + </div> + ))} + </div> + </SettingsSection> + ); +} diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index 4befb5337..1184aef66 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -28,6 +28,10 @@ import { type OutsideAgentReach, type OutsideAgentsSnapshot, ProjectId, + type ProjectBrief, + type ProjectBriefSetInput, + type ProjectBriefSetResult, + type ProjectContextSnapshot, ProviderDriverKind, ProviderInstanceId, type RelayAccessSnapshot, @@ -454,6 +458,18 @@ const savedComputersHarness = vi.hoisted(() => { return harness; }); +/** + * Computers that keep project briefs, by environment: readEnvironmentConnection + * answers with one of these where it is set, so each computer has its own. + */ +const projectContextHarness = vi.hoisted(() => { + const harness = { + connections: new Map<string, unknown>(), + reset: () => harness.connections.clear(), + }; + return harness; +}); + const relayAccessHarness = vi.hoisted(() => { let snapshot: RelayAccessSnapshot | null = null; const listeners = new Set<(snapshot: RelayAccessSnapshot) => void>(); @@ -609,7 +625,8 @@ vi.mock("../../environments/runtime", () => { ensureEnvironmentConnectionBootstrapped: async () => undefined, getPrimaryEnvironmentConnection: () => primaryConnection, readBackendEnvironmentConnection: () => primaryConnection, - readEnvironmentConnection: () => primaryConnection, + readEnvironmentConnection: (environmentId: string) => + projectContextHarness.connections.get(environmentId) ?? primaryConnection, readEnvironmentDescriptor: () => null, listEnvironmentConnections: () => [primaryConnection], reconnectSavedEnvironment: savedComputersHarness.reconnect, @@ -4515,6 +4532,216 @@ describe("Agent Instructions", () => { }); }); +describe("Agent Instructions › Brief", () => { + const THIS_MAC = EnvironmentId.make("env-this-mac"); + const STUDIO = EnvironmentId.make("env-studio"); + const SHARED_PATH = "/repo/app"; + const projectOn = (environmentId: EnvironmentId) => ProjectId.make(`project-${environmentId}`); + + /** A computer with the project (the same repository on each), and the briefs it keeps. */ + const seedComputer = (environmentId: EnvironmentId, brief: ProjectBrief | null) => { + useStore.getState().syncServerShellSnapshot( + { + snapshotSequence: 1, + projects: [ + { + id: projectOn(environmentId), + kind: "workspace" as const, + title: "app", + workspaceRoot: SHARED_PATH, + repositoryIdentity: { + canonicalKey: "github.com/acme/app", + locator: { + source: "git-remote", + remoteName: "origin", + remoteUrl: "https://github.com/acme/app.git", + }, + }, + defaultModelSelection: null, + scripts: [], + createdAt: "2026-11-01T00:00:00.000Z", + updatedAt: "2026-11-01T00:00:00.000Z", + }, + ], + threads: [], + updatedAt: "2026-11-01T00:00:00.000Z", + }, + environmentId, + ); + __setEnvironmentApiOverrideForTests(environmentId, { + providers: { + getInstructionFiles: async ({ cwd }: { cwd: string }) => ({ + cwd, + generatedAt: "2026-11-01T00:00:00.000Z", + instructionFiles: [], + }), + }, + } as unknown as EnvironmentApi); + + // The computer's server: saves count revisions and refuse a stale one. + let snapshot: ProjectContextSnapshot = { briefs: brief === null ? [] : [brief] }; + const listeners = new Set<(next: ProjectContextSnapshot) => void>(); + const current = (projectId: ProjectId): ProjectBrief => + snapshot.briefs.find((entry) => entry.projectId === projectId) ?? { + projectId, + text: "", + revision: 0, + updatedAt: null, + }; + const computer = { + emit(next: ProjectContextSnapshot) { + snapshot = next; + for (const listener of listeners) listener(next); + }, + textOf: (projectId: ProjectId) => current(projectId).text, + setBrief: vi.fn(async (input: ProjectBriefSetInput): Promise<ProjectBriefSetResult> => { + const brief = current(input.projectId); + if (brief.revision !== input.expectedRevision) return { outcome: "stale", brief }; + const saved: ProjectBrief = { + projectId: input.projectId, + text: input.text, + revision: brief.revision + 1, + updatedAt: "2026-11-18T00:00:00.000Z", + }; + computer.emit({ + briefs: [ + ...snapshot.briefs.filter((entry) => entry.projectId !== saved.projectId), + saved, + ], + }); + return { outcome: "saved", brief: saved }; + }), + }; + projectContextHarness.connections.set(environmentId, { + client: { + projectContext: { + subscribe: (listener: (next: ProjectContextSnapshot) => void) => { + listeners.add(listener); + listener(snapshot); + return () => listeners.delete(listener); + }, + setBrief: computer.setBrief, + }, + }, + }); + return computer; + }; + + const brief = (environmentId: EnvironmentId, text: string, revision: number): ProjectBrief => ({ + projectId: projectOn(environmentId), + text, + revision, + updatedAt: "2026-11-10T00:00:00.000Z", + }); + + const describeComputers = (keepsBriefs: boolean) => { + writePrimaryEnvironmentDescriptor({ + environmentId: THIS_MAC, + label: "This Mac", + platform: { os: "darwin", arch: "arm64" }, + serverVersion: "0.1.0", + capabilities: { repositoryIdentity: true, projectContext: keepsBriefs }, + }); + savedComputersHarness.registryById[STUDIO] = { environmentId: STUDIO, label: "Studio" }; + savedComputersHarness.runtimeById[STUDIO] = { + connectionState: "connected", + descriptor: { label: "Studio", capabilities: { projectContext: true } }, + }; + }; + + const renderPage = () => + renderWithTestRouter( + <TestAppProviders> + <AgentInstructionsSettingsPanel /> + </TestAppProviders>, + ); + + afterEach(() => { + __resetEnvironmentApiOverridesForTests(); + projectContextHarness.reset(); + useStore.setState({ environmentStateById: {}, activeEnvironmentId: null }); + delete savedComputersHarness.registryById[STUDIO]; + delete savedComputersHarness.runtimeById[STUDIO]; + resetPrimaryEnvironmentDescriptorForTests(); + }); + + it("copies the brief to a computer that differs, then saves an edit on every computer", async () => { + describeComputers(true); + const mac = seedComputer(THIS_MAC, brief(THIS_MAC, "Branch from develop.", 2)); + const studio = seedComputer(STUDIO, brief(STUDIO, "An older rule.", 5)); + + await renderPage(); + + const box = page.getByLabelText("Project brief"); + await expect.element(box).toHaveValue("Branch from develop."); + await expect.element(page.getByText("Studio has a different brief.")).toBeVisible(); + + await page.getByRole("button", { name: "Use this brief on Studio too" }).click(); + await vi.waitFor(() => + expect(studio.setBrief).toHaveBeenCalledWith({ + projectId: projectOn(STUDIO), + text: "Branch from develop.", + expectedRevision: 5, + }), + ); + await expect.element(page.getByText("Saved on Studio.")).toBeVisible(); + await expect.element(page.getByText("Studio has a different brief.")).not.toBeInTheDocument(); + + await box.fill("Branch from main."); + await page.getByRole("button", { name: "Save brief" }).click(); + await expect.element(page.getByText("Saved on this device and Studio.")).toBeVisible(); + expect(mac.setBrief).toHaveBeenCalledWith({ + projectId: projectOn(THIS_MAC), + text: "Branch from main.", + expectedRevision: 2, + }); + expect(studio.setBrief).toHaveBeenLastCalledWith({ + projectId: projectOn(STUDIO), + text: "Branch from main.", + expectedRevision: 6, + }); + expect(studio.textOf(projectOn(STUDIO))).toBe("Branch from main."); + await expect.element(box).toHaveValue("Branch from main."); + }); + + it("shows the newer brief when another device saved first, and doesn't overwrite it", async () => { + describeComputers(true); + const mac = seedComputer(THIS_MAC, brief(THIS_MAC, "Branch from develop.", 2)); + const studio = seedComputer(STUDIO, brief(STUDIO, "Branch from develop.", 1)); + + await renderPage(); + + const box = page.getByLabelText("Project brief"); + await expect.element(box).toHaveValue("Branch from develop."); + await box.fill("My edit."); + // Another device saves while this page holds an edit. + mac.emit({ briefs: [brief(THIS_MAC, "Their newer rule.", 3)] }); + await page.getByRole("button", { name: "Save brief" }).click(); + + await expect + .element(page.getByText("Another device saved this brief first.", { exact: false })) + .toBeVisible(); + await expect.element(box).toHaveValue("Their newer rule."); + expect(mac.textOf(projectOn(THIS_MAC))).toBe("Their newer rule."); + expect(studio.setBrief).not.toHaveBeenCalled(); + + // The user's text comes back, to save over the newer one on purpose. + await page.getByRole("button", { name: "Bring back my edit" }).click(); + await expect.element(box).toHaveValue("My edit."); + }); + + it("is hidden when the project's computer keeps no briefs", async () => { + describeComputers(false); + seedComputer(THIS_MAC, null); + seedComputer(STUDIO, null); + + await renderPage(); + + await expect.element(page.getByText("No files")).toBeVisible(); + await expect.element(page.getByLabelText("Project brief")).not.toBeInTheDocument(); + }); +}); + describe("SourceControlSettingsPanel discovery states", () => { let mounted: | (Awaited<ReturnType<typeof render>> & { diff --git a/apps/web/src/components/sidebar/ProjectScopeMenu.tsx b/apps/web/src/components/sidebar/ProjectScopeMenu.tsx index cbea14746..715af25ff 100644 --- a/apps/web/src/components/sidebar/ProjectScopeMenu.tsx +++ b/apps/web/src/components/sidebar/ProjectScopeMenu.tsx @@ -21,6 +21,8 @@ import { SIDEBAR_LIST_FIELD_CLASS } from "./sidebarListField"; import { readLocalApi } from "../../localApi"; import { readEnvironmentApi } from "../../environmentApi"; import { readEnvironmentDescriptor } from "../../environments/runtime"; +import { readPrimaryEnvironmentDescriptor } from "../../environments/primary"; +import { PROJECT_BRIEF_MENU_LABEL, projectBriefLocation } from "../../projectBrief"; import { readProjectSetupSourceAmong } from "../../environments/projectSetups/projectSetupTargets"; import { useComposerDraftStore } from "../../composerDraftStore"; import { selectSidebarThreadsForProjectRefs, useStore } from "../../store"; @@ -106,6 +108,7 @@ function formatProjectMemberActionLabel( } const SET_UP_ELSEWHERE_ITEM_ID = "set-up-elsewhere"; +const PROJECT_BRIEF_ITEM_ID = "project-brief"; const MUTE_ALERTS_ITEM_ID = "mute-phone-alerts"; const UNMUTE_ALERTS_ITEM_ID = "unmute-phone-alerts"; @@ -494,6 +497,27 @@ export const ProjectScopeMenu = memo(function ProjectScopeMenu(props: ProjectSco openProjectSetupDialog({ project: setupSource }), ); } + // The brief opens on this app's own computer's copy when it keeps + // briefs, else on the first copy that does; saving reaches the rest. + const primaryId = readPrimaryEnvironmentDescriptor()?.environmentId; + const briefMember = + project.memberProjects + .filter( + (member) => + readEnvironmentDescriptor(member.environmentId)?.capabilities.projectContext === + true, + ) + .toSorted( + (left, right) => + Number(right.environmentId === primaryId) - + Number(left.environmentId === primaryId), + )[0] ?? null; + if (briefMember !== null) { + actionHandlers.set(PROJECT_BRIEF_ITEM_ID, async () => { + setMenuOpen(false); + await navigate(projectBriefLocation(briefMember)); + }); + } // Both show for copies that differ, so either way is one step from there. const members = project.memberProjects; const canMute = members.some((member) => member.phoneAlertsMuted !== true); @@ -567,6 +591,9 @@ export const ProjectScopeMenu = memo(function ProjectScopeMenu(props: ProjectSco }, buildTargetedItem("grouping", "Project grouping…"), buildTargetedItem("copy-path", "Copy Project Path"), + ...(briefMember !== null + ? [{ id: PROJECT_BRIEF_ITEM_ID, label: PROJECT_BRIEF_MENU_LABEL }] + : []), ...(setupSource !== null ? [{ id: SET_UP_ELSEWHERE_ITEM_ID, label: "Set up on another computer…" }] : []), diff --git a/apps/web/src/environments/projectSetups/projectSetups.ts b/apps/web/src/environments/projectSetups/projectSetups.ts index eb3b34b0f..f47c0cd34 100644 --- a/apps/web/src/environments/projectSetups/projectSetups.ts +++ b/apps/web/src/environments/projectSetups/projectSetups.ts @@ -430,6 +430,10 @@ export async function startProjectSetup( ...(plan.sourceInfo.sizeBytes !== undefined ? { expectedBytes: plan.sourceInfo.sizeBytes } : {}), + // The project's brief goes with it; the new copy keeps it once it is added. + ...(plan.sourceInfo.brief !== undefined && plan.sourceInfo.brief.length > 0 + ? { brief: plan.sourceInfo.brief } + : {}), }); upsertJob(plan.target.environmentId, job); return job; diff --git a/apps/web/src/projectBrief.ts b/apps/web/src/projectBrief.ts new file mode 100644 index 000000000..bb3582386 --- /dev/null +++ b/apps/web/src/projectBrief.ts @@ -0,0 +1,224 @@ +/** + * A project's brief on the web side (docs/design/project-brief-notes.md): + * following each computer's briefs while the page that shows them is open, + * saving one text on every computer that has the project, and the words that + * say where it went. Each computer keeps its own briefs and counts its own + * saves (`revision`), so every save names the revision this app last saw + * there, and a save from behind another device's is refused, not lost. + */ +import type { + EnvironmentId, + ProjectBrief, + ProjectBriefSetResult, + ProjectContextSnapshot, + ProjectId, +} from "@threadlines/contracts"; +import { PROJECT_BRIEF_MAX_CHARS } from "@threadlines/contracts"; +import type { PlaceId } from "@threadlines/shared/appPlaces"; +import { useCallback, useEffect, useState } from "react"; + +import { nextPlaceArrivalHash } from "./appPlaceLinks"; +import { usePrimaryEnvironmentDescriptor } from "./environments/primary"; +import { + readEnvironmentConnection, + subscribeEnvironmentConnections, + useSavedEnvironmentRuntimeStore, +} from "./environments/runtime"; + +/** The place the brief's section is, which every way in opens. */ +export const PROJECT_BRIEF_PLACE: PlaceId = "instructions.brief"; + +/** What the project menu, the palette and the lead's card call the way in. */ +export const PROJECT_BRIEF_MENU_LABEL = "Project brief and notes"; + +/** From here up, the page shows how many characters the brief has. */ +export const PROJECT_BRIEF_COUNT_FROM = Math.round(PROJECT_BRIEF_MAX_CHARS * 0.9); + +/** + * Where Settings › Instructions opens on one project's brief: the project's + * computer and folder in the search (usePlaceScopeArrival picks it), and an + * arrival at the section. + */ +export function projectBriefLocation(project: { + readonly environmentId: EnvironmentId; + readonly cwd: string; +}) { + return { + to: "/settings/instructions" as const, + search: { environment: project.environmentId, project: project.cwd }, + hash: nextPlaceArrivalHash(PROJECT_BRIEF_PLACE), + // The hash names a place, not an element id; usePlaceArrival scrolls. + hashScrollIntoView: false, + }; +} + +/** + * Whether a computer's server keeps briefs (the `projectContext` capability), + * as its server last said; again when that changes. An older Threadlines, or + * one that hasn't said yet, is a no. + */ +export function useProjectBriefSupport(): (environmentId: EnvironmentId) => boolean { + const primaryDescriptor = usePrimaryEnvironmentDescriptor(); + const runtimeById = useSavedEnvironmentRuntimeStore((state) => state.byId); + return useCallback( + (environmentId) => + primaryDescriptor?.environmentId === environmentId + ? primaryDescriptor.capabilities.projectContext === true + : runtimeById[environmentId]?.descriptor?.capabilities.projectContext === true, + [primaryDescriptor, runtimeById], + ); +} + +/** A project's brief on one computer, or the empty one a computer without it would answer. */ +export function briefIn( + snapshot: ProjectContextSnapshot | undefined, + projectId: ProjectId, +): ProjectBrief | null { + if (snapshot === undefined) return null; + return ( + snapshot.briefs.find((brief) => brief.projectId === projectId) ?? { + projectId, + text: "", + revision: 0, + updatedAt: null, + } + ); +} + +/** + * Each listed computer's latest briefs, followed while mounted. A computer + * whose connection is replaced (a reconnect) is followed again on the new + * one; one that drops keeps its last snapshot until it comes back. + */ +export function useProjectBriefSnapshots( + environmentIds: readonly EnvironmentId[], +): Readonly<Record<string, ProjectContextSnapshot>> { + const [byEnvironment, setByEnvironment] = useState<Record<string, ProjectContextSnapshot>>({}); + const environmentKey = environmentIds.join("\0"); + + useEffect(() => { + const ids = (environmentKey === "" ? [] : environmentKey.split("\0")) as EnvironmentId[]; + const active = new Map< + EnvironmentId, + { readonly connection: object; readonly unsubscribe: () => void } + >(); + const sync = () => { + for (const environmentId of ids) { + const connection = readEnvironmentConnection(environmentId); + const current = active.get(environmentId); + if (current?.connection === connection) continue; + current?.unsubscribe(); + active.delete(environmentId); + if (!connection) continue; + active.set(environmentId, { + connection, + unsubscribe: connection.client.projectContext.subscribe((snapshot) => + setByEnvironment((previous) => ({ ...previous, [environmentId]: snapshot })), + ), + }); + } + }; + sync(); + const stopWatching = subscribeEnvironmentConnections(sync); + return () => { + stopWatching(); + for (const entry of active.values()) entry.unsubscribe(); + }; + }, [environmentKey]); + + return byEnvironment; +} + +/** One computer's copy of the project, as a save reaches it. */ +export interface BriefTarget { + readonly environmentId: EnvironmentId; + readonly projectId: ProjectId; + /** The computer's name as the app shows it. */ + readonly label: string; + /** Its server keeps briefs (the `projectContext` capability), as far as this app knows. */ + readonly supported: boolean; +} + +/** What one computer did with a save. */ +export type BriefSaveOutcome = + | { readonly kind: "saved"; readonly label: string; readonly brief: ProjectBrief } + | { readonly kind: "stale"; readonly label: string; readonly brief: ProjectBrief } + | { readonly kind: "offline"; readonly label: string } + | { readonly kind: "unsupported"; readonly label: string } + | { readonly kind: "failed"; readonly label: string; readonly detail: string }; + +/** + * Saves a brief on one computer, sending the revision this app last saw + * there. Never throws: what happened is the outcome. + */ +export async function saveBriefOn( + target: BriefTarget, + text: string, + expectedRevision: number, +): Promise<BriefSaveOutcome> { + const { label } = target; + // Offline first: a computer not reached since the app started hasn't said + // what it supports either. + const connection = readEnvironmentConnection(target.environmentId); + if (connection === null) return { kind: "offline", label }; + if (!target.supported) return { kind: "unsupported", label }; + let result: ProjectBriefSetResult; + try { + result = await connection.client.projectContext.setBrief({ + projectId: target.projectId, + text, + expectedRevision, + }); + } catch (error) { + return { + kind: "failed", + label, + detail: error instanceof Error && error.message.length > 0 ? error.message : "It failed.", + }; + } + return { kind: result.outcome, label, brief: result.brief }; +} + +/** "A", "A and B", "A, B and C". */ +function joinNames(names: readonly string[]): string { + if (names.length <= 1) return names[0] ?? ""; + return `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`; +} + +/** A computer's name inside a sentence: the generic "This device" reads as "this device". */ +export function computerInSentence(label: string): string { + return label === "This device" ? "this device" : label; +} + +/** + * The line under the box after a save: where it went, then each computer it + * didn't reach and why ("Saved on this device and Studio. Not saved on + * Laptop. It is offline."). + */ +export function describeBriefSave(outcomes: readonly BriefSaveOutcome[]): string { + const unique = (labels: readonly string[]) => + labels.filter((label, index) => labels.indexOf(label) === index).map(computerInSentence); + const saved = unique(outcomes.filter((o) => o.kind === "saved").map((o) => o.label)); + const parts: string[] = []; + if (saved.length > 0) parts.push(`Saved on ${joinNames(saved)}.`); + for (const outcome of outcomes) { + const where = computerInSentence(outcome.label); + switch (outcome.kind) { + case "saved": + break; + case "offline": + parts.push(`Not saved on ${where}. It is offline.`); + break; + case "unsupported": + parts.push(`Not saved on ${where}. Update Threadlines there to keep a brief.`); + break; + case "stale": + parts.push(`Not saved on ${where}. Its brief changed there first.`); + break; + case "failed": + parts.push(`Not saved on ${where}. ${outcome.detail}`); + break; + } + } + return parts.join(" "); +} diff --git a/apps/web/src/rpc/wsRpcClient.ts b/apps/web/src/rpc/wsRpcClient.ts index bc63adf62..d326496b0 100644 --- a/apps/web/src/rpc/wsRpcClient.ts +++ b/apps/web/src/rpc/wsRpcClient.ts @@ -447,6 +447,11 @@ export interface WsRpcClient { readonly search: RpcUnaryMethod<typeof WS_METHODS.themeVsCodeSearch>; readonly read: RpcUnaryMethod<typeof WS_METHODS.themeVsCodeRead>; }; + /** This computer's project briefs (docs/design/project-brief-notes.md), on servers reporting `projectContext`. */ + readonly projectContext: { + readonly subscribe: RpcStreamMethod<typeof WS_METHODS.projectContextSubscribe>; + readonly setBrief: RpcUnaryMethod<typeof WS_METHODS.projectContextSetBrief>; + }; /** This computer's scheduled tasks (docs/design/fleet.md, Part 6). */ readonly scheduledTasks: { readonly subscribe: RpcStreamMethod<typeof WS_METHODS.scheduledTasksSubscribe>; @@ -1319,6 +1324,15 @@ export function createWsRpcClient(transport: WsTransport): WsRpcClient { search: (input) => transport.request((client) => client[WS_METHODS.themeVsCodeSearch](input)), read: (input) => transport.request((client) => client[WS_METHODS.themeVsCodeRead](input)), }, + projectContext: { + subscribe: (listener, options) => + transport.subscribe((client) => client[WS_METHODS.projectContextSubscribe]({}), listener, { + ...options, + tag: WS_METHODS.projectContextSubscribe, + }), + setBrief: (input) => + transport.request((client) => client[WS_METHODS.projectContextSetBrief](input)), + }, scheduledTasks: { subscribe: (listener, options) => transport.subscribe( diff --git a/packages/shared/src/appPlaces.ts b/packages/shared/src/appPlaces.ts index a82818e6d..75383d4e2 100644 --- a/packages/shared/src/appPlaces.ts +++ b/packages/shared/src/appPlaces.ts @@ -447,10 +447,10 @@ const PAGES = [ id: "settings.instructions", kind: "page", title: "Agent Instructions", - about: "The instruction files agents read before they start work.", + about: "A project's brief and the instruction files agents read before they start work.", route: { to: "/settings/instructions" }, target: "thread", - keywords: ["AGENTS.md", "CLAUDE.md", "rules"], + keywords: ["AGENTS.md", "CLAUDE.md", "rules", "brief"], }, { id: "settings.sourceControl", @@ -721,6 +721,16 @@ const SECTIONS = [ title: "Project", about: "Which project's instruction files to show.", }, + { + id: "instructions.brief", + kind: "section", + parent: "settings.instructions", + title: "Brief", + about: + "Text every thread in that project gets, on any agent. It stays on your computers and is not written to the repository.", + keywords: ["project brief", "project instructions", "standing instructions", "rules"], + widensAgents: true, + }, { id: "instructions.files", kind: "section", From 25d62bb5e97b97f7fded7a64ca987fd0a518fea7 Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 20:54:11 -0500 Subject: [PATCH 3/4] feat(server): every agent gets the project brief when its session starts ProviderService looks up the project's brief at every adapter start, recovery inside sendTurn included, and hands it to the adapter. Side answers, General Chats and threads behind the link fence get none. - Claude: after Threadlines' own system prompt append. - Codex: the thread's developer instructions, after the user's own from config/read. A resumed thread whose brief changed gets it added with thread/inject_items, since Codex writes developer instructions into the conversation only when it creates a thread. - OpenCode: the end of the threadlines instructions entry. - Pi: the end of the instructions file. - Muse and ACP agents: ahead of the first prompt after a start, again only when the brief's hash differs from the one kept in the cursor. "Set up on another computer" copies the brief with the project, into an empty brief only. Piece 1's labels say "Project brief" until notes land. --- apps/server/src/guide/topics.ts | 2 +- .../src/projectContext/ProjectContext.test.ts | 216 ++++++++++++++++++ .../projectSetup/ProjectSetupRepository.ts | 2 + .../src/projectSetup/ProjectSetupSource.ts | 8 + .../src/projectSetup/ProjectSetups.test.ts | 14 ++ apps/server/src/projectSetup/ProjectSetups.ts | 6 + .../src/provider/Layers/ClaudeAdapter.test.ts | 45 ++++ .../src/provider/Layers/ClaudeAdapter.ts | 51 +++-- .../src/provider/Layers/CodexAdapter.ts | 3 + .../Layers/CodexSessionRuntime.test.ts | 212 +++++++++++++++++ .../provider/Layers/CodexSessionRuntime.ts | 141 +++++++++++- .../src/provider/Layers/MuseAdapter.test.ts | 54 +++++ .../server/src/provider/Layers/MuseAdapter.ts | 42 +++- .../provider/Layers/OpenCodeAdapter.test.ts | 18 ++ .../src/provider/Layers/OpenCodeAdapter.ts | 4 + .../Layers/PiAdapter.integration.test.ts | 35 +++ apps/server/src/provider/Layers/PiAdapter.ts | 19 +- .../provider/Layers/ProviderService.test.ts | 43 ++++ .../src/provider/Layers/ProviderService.ts | 70 ++++-- .../src/provider/acp/AcpAdapter.test.ts | 72 ++++++ apps/server/src/provider/acp/AcpAdapter.ts | 54 ++++- .../src/provider/projectBriefPreface.ts | 50 ++++ .../web/src/components/chat/LeadChatHints.tsx | 2 +- apps/web/src/projectBrief.ts | 2 +- docs/design/project-brief-notes.md | 29 ++- 25 files changed, 1121 insertions(+), 73 deletions(-) create mode 100644 apps/server/src/projectContext/ProjectContext.test.ts create mode 100644 apps/server/src/provider/projectBriefPreface.ts diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts index e67c7f3c6..16c858e27 100644 --- a/apps/server/src/guide/topics.ts +++ b/apps/server/src/guide/topics.ts @@ -346,7 +346,7 @@ New threads get a change at once. A thread that is already open gets it the next Threadlines keeps it on each computer, not in the repository. Save stores it on every connected computer that has the project, and the line under the box says where it went. If the computers hold different briefs, the page shows the picked computer's and offers to copy it to the others. If another device saved first, Save says so and shows the newer text instead of overwriting it. Set up on another computer copies the brief with the project. -The project menu's Project brief and notes, the command palette and the lead chat's crown card open it too.`, +The project menu's Project brief, the command palette and the lead chat's crown card open it too.`, }, { id: "browser-panel", diff --git a/apps/server/src/projectContext/ProjectContext.test.ts b/apps/server/src/projectContext/ProjectContext.test.ts new file mode 100644 index 000000000..3911271df --- /dev/null +++ b/apps/server/src/projectContext/ProjectContext.test.ts @@ -0,0 +1,216 @@ +import { + EnvironmentId, + GENERAL_CHATS_PROJECT_ID, + ProjectId, + ProviderInstanceId, + SideTurnId, + ThreadId, + ThreadParticipantId, +} from "@threadlines/contracts"; +import { + parseSessionKey, + participantSessionKey, + sideSessionKey, +} from "@threadlines/shared/threadParticipants"; +import { assert, it } from "@effect/vitest"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Stream from "effect/Stream"; + +import { ProjectionProjectRepositoryLive } from "../persistence/Layers/ProjectionProjects.ts"; +import { ProjectionThreadRepositoryLive } from "../persistence/Layers/ProjectionThreads.ts"; +import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; +import { ProjectionProjectRepository } from "../persistence/Services/ProjectionProjects.ts"; +import { ProjectionThreadRepository } from "../persistence/Services/ProjectionThreads.ts"; +import { ProjectInstructions } from "../provider/Services/ProjectInstructions.ts"; +import { ProjectBriefRepositoryLive } from "./ProjectBriefRepository.ts"; +import { ProjectContext, ProjectContextLive } from "./ProjectContext.ts"; +import { ProjectInstructionsLive } from "./ProjectInstructionsLive.ts"; + +const layer = it.layer( + Layer.mergeAll(ProjectContextLive, ProjectInstructionsLive).pipe( + Layer.provideMerge(ProjectBriefRepositoryLive), + Layer.provideMerge(ProjectionProjectRepositoryLive), + Layer.provideMerge(ProjectionThreadRepositoryLive), + Layer.provideMerge(SqlitePersistenceMemory), + ), +); + +const at = "2026-11-18T00:00:00.000Z"; + +const addProject = (projectId: ProjectId, title: string) => + Effect.flatMap(ProjectionProjectRepository, (projects) => + projects.upsert({ + projectId, + kind: "workspace", + title, + workspaceRoot: `/tmp/${projectId}`, + defaultModelSelection: null, + scripts: [], + createdAt: at, + updatedAt: at, + deletedAt: null, + }), + ); + +const addThread = ( + threadId: ThreadId, + projectId: ProjectId, + extra: Partial<Parameters<ProjectionThreadRepository["Service"]["upsert"]>[0]> = {}, +) => + Effect.flatMap(ProjectionThreadRepository, (threads) => + threads.upsert({ + threadId, + projectId, + title: "Thread", + modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" }, + runtimeMode: "full-access", + interactionMode: "default", + branch: null, + worktreePath: null, + effectiveCwd: null, + goal: null, + latestTurnId: null, + createdAt: at, + updatedAt: at, + archivedAt: null, + pinnedAt: null, + latestUserMessageAt: null, + pendingApprovalCount: 0, + pendingUserInputCount: 0, + blockingUserInputCount: 0, + hasActionableProposedPlan: 0, + deletedAt: null, + ...extra, + }), + ); + +const instructionsFor = (sessionKey: ThreadId) => + Effect.flatMap(ProjectInstructions, (lookup) => + lookup.forSession({ sessionKey, runtimeMode: "full-access" }), + ); + +layer("ProjectContext", (it) => { + it.effect("a save from behind another device's is refused and loses nothing", () => + Effect.gen(function* () { + const context = yield* ProjectContext; + const projectId = ProjectId.make("project-stale"); + yield* addProject(projectId, "Stale"); + + const first = yield* context.setBrief({ projectId, text: "Use pnpm.", expectedRevision: 0 }); + assert.strictEqual(first.outcome, "saved"); + assert.strictEqual(first.brief.revision, 1); + + // Another page still holds revision 0. + const late = yield* context.setBrief({ projectId, text: "Use npm.", expectedRevision: 0 }); + assert.strictEqual(late.outcome, "stale"); + assert.strictEqual(late.brief.text, "Use pnpm."); + assert.strictEqual(late.brief.revision, 1); + assert.strictEqual(yield* context.briefText(projectId), "Use pnpm."); + + const next = yield* context.setBrief({ projectId, text: "Use bun.", expectedRevision: 1 }); + assert.strictEqual(next.outcome, "saved"); + assert.strictEqual(next.brief.revision, 2); + + const snapshot = yield* context.changes.pipe(Stream.runHead); + assert.deepStrictEqual( + snapshot._tag === "Some" + ? snapshot.value.briefs.find((brief) => brief.projectId === projectId)?.text + : undefined, + "Use bun.", + ); + }), + ); + + it.effect("a copied project's brief fills only an empty one", () => + Effect.gen(function* () { + const context = yield* ProjectContext; + const fresh = ProjectId.make("project-copied"); + const written = ProjectId.make("project-written"); + yield* addProject(fresh, "Copied"); + yield* addProject(written, "Written"); + yield* context.setBrief({ projectId: written, text: "Mine.", expectedRevision: 0 }); + + yield* context.adoptBrief(fresh, "From the other computer."); + yield* context.adoptBrief(written, "From the other computer."); + + assert.strictEqual(yield* context.briefText(fresh), "From the other computer."); + assert.strictEqual(yield* context.briefText(written), "Mine."); + }), + ); + + it.effect("General Chats have no brief", () => + Effect.gen(function* () { + const context = yield* ProjectContext; + const refused = yield* context + .setBrief({ projectId: GENERAL_CHATS_PROJECT_ID, text: "x", expectedRevision: 0 }) + .pipe(Effect.flip); + assert.strictEqual(refused._tag, "ProjectContextError"); + }), + ); + + it.effect("a thread's session gets the brief as it is when it starts", () => + Effect.gen(function* () { + const context = yield* ProjectContext; + const projectId = ProjectId.make("project-brief"); + const threadId = ThreadId.make("thread-brief"); + yield* addProject(projectId, "Shop"); + yield* addThread(threadId, projectId); + + assert.strictEqual(yield* instructionsFor(threadId), undefined); + yield* context.setBrief({ projectId, text: "Prices are in cents.", expectedRevision: 0 }); + const text = yield* instructionsFor(threadId); + assert.include(text ?? "", 'Project brief for "Shop"'); + assert.include(text ?? "", "Prices are in cents."); + + yield* context.setBrief({ projectId, text: "Prices are in euros.", expectedRevision: 1 }); + assert.include((yield* instructionsFor(threadId)) ?? "", "Prices are in euros."); + + // Cleared: nothing to add. + yield* context.setBrief({ projectId, text: "", expectedRevision: 2 }); + assert.strictEqual(yield* instructionsFor(threadId), undefined); + }), + ); + + it.effect("a fenced thread, a General Chat and a side answer get no brief", () => + Effect.gen(function* () { + const context = yield* ProjectContext; + const projectId = ProjectId.make("project-closed"); + yield* addProject(projectId, "Closed"); + yield* context.setBrief({ projectId, text: "Secret plans.", expectedRevision: 0 }); + + // Session keys carry ids in the app's own form. + const open = ThreadId.make("6f1c2a52-3b7e-4c1d-9a8e-2f4b5c6d7e8f"); + const fenced = ThreadId.make("thread-fenced"); + const general = ThreadId.make("thread-general"); + yield* addThread(open, projectId); + yield* addThread(fenced, projectId, { + remoteOrigin: { + linkDeviceId: "device-windows", + environmentId: EnvironmentId.make("env-windows"), + environmentLabel: "Windows PC", + threadId: ThreadId.make("windows-parent"), + threadTitle: "Ship the release", + }, + }); + yield* addThread(general, GENERAL_CHATS_PROJECT_ID); + + assert.include((yield* instructionsFor(open)) ?? "", "Secret plans."); + // A room agent's working session is the thread's too. + const roomAgent = participantSessionKey( + open, + ThreadParticipantId.make("a1b2c3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d"), + ); + assert.include((yield* instructionsFor(roomAgent)) ?? "", "Secret plans."); + assert.strictEqual(yield* instructionsFor(fenced), undefined); + assert.strictEqual(yield* instructionsFor(general), undefined); + const side = sideSessionKey( + open, + SideTurnId.make("0b9d8c7e-6f5a-4b3c-8d2e-1f0a9b8c7d6e"), + null, + ); + assert.strictEqual(parseSessionKey(side).kind, "side"); + assert.strictEqual(yield* instructionsFor(side), undefined); + }), + ); +}); diff --git a/apps/server/src/projectSetup/ProjectSetupRepository.ts b/apps/server/src/projectSetup/ProjectSetupRepository.ts index b4b70ae0a..20fa4f886 100644 --- a/apps/server/src/projectSetup/ProjectSetupRepository.ts +++ b/apps/server/src/projectSetup/ProjectSetupRepository.ts @@ -40,6 +40,8 @@ export const ProjectSetupStoredRequest = Schema.Struct({ destinationPath: TrimmedNonEmptyString, filePaths: Schema.Array(TrimmedNonEmptyString), expectedBytes: Schema.optional(Schema.Number), + /** The source's brief, saved here once the project is added (ProjectSetupStartInput.brief). */ + brief: Schema.optional(Schema.String), }); export type ProjectSetupStoredRequest = typeof ProjectSetupStoredRequest.Type; diff --git a/apps/server/src/projectSetup/ProjectSetupSource.ts b/apps/server/src/projectSetup/ProjectSetupSource.ts index 51cf6d953..53ae7f807 100644 --- a/apps/server/src/projectSetup/ProjectSetupSource.ts +++ b/apps/server/src/projectSetup/ProjectSetupSource.ts @@ -21,10 +21,12 @@ import { gitRemoteProtocol, stripGitRemoteCredentials } from "@threadlines/share import * as Context from "effect/Context"; import * as Effect from "effect/Effect"; import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; import { receivedPathRefusal } from "../fs/receivedFiles.ts"; import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { ProcessRunner } from "../processRunner.ts"; +import { ProjectContext } from "../projectContext/ProjectContext.ts"; import { parseRemoteFetchUrls, pickPrimaryRemote, @@ -71,6 +73,7 @@ export const makeProjectSetupSource = Effect.gen(function* () { const snapshots = yield* ProjectionSnapshotQuery; const identities = yield* RepositoryIdentityResolver; const processes = yield* ProcessRunner; + const projectContext = yield* Effect.serviceOption(ProjectContext); const git = (cwd: string, args: ReadonlyArray<string>, stdin?: string) => processes @@ -239,6 +242,10 @@ export const makeProjectSetupSource = Effect.gen(function* () { const home = NodeOs.homedir(); const fromHome = NodePath.relative(home, root); const { files, truncated } = yield* listCandidates(root); + // The brief goes along, so threads on the new computer get it too. + const brief = Option.isSome(projectContext) + ? yield* projectContext.value.briefText(project.id) + : ""; return { projectId: project.id, title: project.title, @@ -247,6 +254,7 @@ export const makeProjectSetupSource = Effect.gen(function* () { remotes, primaryRemoteName: primary.remoteName, scripts: project.scripts, + ...(brief.length > 0 ? { brief } : {}), homeRelativePath: fromHome.length > 0 && !fromHome.startsWith("..") && !NodePath.isAbsolute(fromHome) ? fromHome.split(NodePath.sep).join("/") diff --git a/apps/server/src/projectSetup/ProjectSetups.test.ts b/apps/server/src/projectSetup/ProjectSetups.test.ts index 2e04ce43b..ca5c7a94c 100644 --- a/apps/server/src/projectSetup/ProjectSetups.test.ts +++ b/apps/server/src/projectSetup/ProjectSetups.test.ts @@ -26,6 +26,7 @@ import { OrchestrationEngineService } from "../orchestration/Services/Orchestrat import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { SqlitePersistenceMemory } from "../persistence/Layers/Sqlite.ts"; import * as ProcessRunner from "../processRunner.ts"; +import { ProjectContext } from "../projectContext/ProjectContext.ts"; import { RepositoryIdentityResolverLive } from "../project/Layers/RepositoryIdentityResolver.ts"; import { overallClonePercent, parseCloneProgress } from "./cloneProgress.ts"; import { ProjectSetupRepository, ProjectSetupRepositoryLive } from "./ProjectSetupRepository.ts"; @@ -91,6 +92,9 @@ function makeRepos() { return { root, origin, a, b }; } +/** Briefs the new computer's projects took from the copy. */ +const adoptedBriefs: Array<readonly [ProjectId, string]> = []; + function testLayer( repos: ReturnType<typeof makeRepos>, dispatched: OrchestrationCommand[], @@ -130,6 +134,13 @@ function testLayer( }), }), ServerEnvironment.layerTest({ label: "Test PC" }), + Layer.mock(ProjectContext)({ + briefText: (projectId) => Effect.succeed(projectId === PROJECT_A ? "Use pnpm." : ""), + adoptBrief: (projectId, text) => + Effect.sync(() => { + adoptedBriefs.push([projectId, text]); + }), + }), ), ), Layer.provideMerge(RepositoryIdentityResolverLive), @@ -168,6 +179,7 @@ describe("ProjectSetups", () => { assert.equal(answer.repositoryKey, normalizeGitRemoteUrl(repos.origin)); assert.equal(answer.primaryRemoteName, "origin"); assert.isAbove(answer.sizeBytes ?? 0, 0); + assert.equal(answer.brief, "Use pnpm."); // Ignored files only, suggested ones first; no folder git ignores whole, no symlink. assert.deepEqual( answer.files.map((file) => [file.path, file.suggested]), @@ -210,6 +222,7 @@ describe("ProjectSetups", () => { primaryRemoteName: answer.primaryRemoteName, protocol: "other", scripts: answer.scripts, + ...(answer.brief !== undefined ? { brief: answer.brief } : {}), destinationPath: destination, files, }; @@ -241,6 +254,7 @@ describe("ProjectSetups", () => { const meta = dispatched.find((command) => command.type === "project.meta.update"); assert(meta?.type === "project.meta.update"); assert.deepEqual(meta.scripts, SCRIPTS); + assert.deepEqual(adoptedBriefs, [[created[0].projectId, "Use pnpm."]]); // The same start again is the same job. assert.equal((yield* setups.start(input)).stage, "done"); diff --git a/apps/server/src/projectSetup/ProjectSetups.ts b/apps/server/src/projectSetup/ProjectSetups.ts index 070ca56bc..372a72dfe 100644 --- a/apps/server/src/projectSetup/ProjectSetups.ts +++ b/apps/server/src/projectSetup/ProjectSetups.ts @@ -50,6 +50,7 @@ import { OrchestrationEngineService } from "../orchestration/Services/Orchestrat import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts"; import { expandHomePath } from "../pathExpansion.ts"; import { ProcessRunner } from "../processRunner.ts"; +import { ProjectContext } from "../projectContext/ProjectContext.ts"; import { parseRemoteFetchUrls, pickPrimaryRemote, @@ -230,6 +231,7 @@ export const makeProjectSetups = Effect.gen(function* () { const processes = yield* ProcessRunner; const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const environment = yield* ServerEnvironment; + const projectContext = yield* Effect.serviceOption(ProjectContext); const scope = yield* Effect.scope; // Read at each use: the computer can be renamed while this runs. const ownLabel = environment.currentLabel; @@ -578,6 +580,10 @@ export const makeProjectSetups = Effect.gen(function* () { scripts: row.request.scripts, }); } + // Only into an empty brief, so a replay never overwrites one written since. + if (row.request.brief !== undefined && Option.isSome(projectContext)) { + yield* projectContext.value.adoptBrief(row.projectId, row.request.brief); + } }).pipe( Effect.mapError( (cause) => diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts index e33beaff0..808fcbb52 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.test.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.test.ts @@ -10438,6 +10438,51 @@ describe("ClaudeAdapterLive", () => { ); }); + it.effect( + "puts the project's brief after Threadlines' own text, and not in a side answer", + () => { + const sessionId = "0f0e0d0c-0b0a-4908-8706-050403020100"; + const seeded = seedClaudeTranscript(sessionId); + const harness = makeHarness({ environment: seeded.environment }); + const brief = "Use pnpm here. Never touch the generated folder."; + const appendOf = (options: { readonly systemPrompt?: unknown }) => + (options.systemPrompt as { readonly append?: string } | undefined)?.append ?? ""; + return Effect.gen(function* () { + const adapter = yield* ClaudeAdapter; + yield* adapter.startSession({ + threadId: ThreadId.make("thread-claude-no-brief"), + provider: ProviderDriverKind.make("claudeAgent"), + runtimeMode: "full-access", + }); + const plain = appendOf(harness.getLastCreateQueryInput()!.options); + assert.notInclude(plain, brief); + + yield* adapter.startSession({ + threadId: THREAD_ID, + provider: ProviderDriverKind.make("claudeAgent"), + runtimeMode: "full-access", + projectInstructions: brief, + }); + assert.equal(appendOf(harness.getLastCreateQueryInput()!.options), `${plain}\n\n${brief}`); + + yield* adapter.startSession({ + threadId: RESUME_THREAD_ID, + provider: ProviderDriverKind.make("claudeAgent"), + cwd: process.cwd(), + lockdown: "side-answer", + forkFrom: { providerThreadId: sessionId }, + runtimeMode: "full-access", + projectInstructions: brief, + }); + assert.notInclude(appendOf(harness.getLastCreateQueryInput()!.options), brief); + }).pipe( + Effect.provideService(Random.Random, makeDeterministicRandomService()), + Effect.provide(harness.layer), + Effect.ensuring(Effect.sync(seeded.cleanup)), + ); + }, + ); + it.effect( "attaches the room tools to a room's working agent, on a credential its stop revokes", () => { diff --git a/apps/server/src/provider/Layers/ClaudeAdapter.ts b/apps/server/src/provider/Layers/ClaudeAdapter.ts index 6f6d13933..d4be1f62c 100644 --- a/apps/server/src/provider/Layers/ClaudeAdapter.ts +++ b/apps/server/src/provider/Layers/ClaudeAdapter.ts @@ -1056,6 +1056,20 @@ export function buildClaudeSystemPromptAppend(input: { ].join("\n\n"); } +/** + * The project's brief goes after Threadlines' own text (docs/design/ + * project-brief-notes.md): the part every thread shares stays first, so + * Claude Code's cache of it is reused, and agentContextBudget.test.ts keeps + * measuring only that part. + */ +export const withClaudeProjectInstructions = ( + append: string, + projectInstructions: string | undefined, +): string => + projectInstructions === undefined || projectInstructions.length === 0 + ? append + : `${append}\n\n${projectInstructions}`; + /** A locked-down side runtime's room endpoint and the room tools it may call. */ export interface ClaudeSideRoomTools { readonly server: McpHttpServerConfig; @@ -9682,23 +9696,26 @@ export const makeClaudeAdapter = Effect.fn("makeClaudeAdapter")(function* ( systemPrompt: { type: "preset", preset: "claude_code", - append: buildClaudeSystemPromptAppend({ - pageAssetsDir: agentPages ? pageAssets : undefined, - artifacts, - commandRequests: credential !== undefined && commandRequests, - room: - roomServer !== undefined - ? { - tools: roomToolsFor(undefined, { - scheduledRun: input.scheduledRunTools === true, - guideOnly: roomGrant.guideOnly, - }), - schedules: input.scheduleTools === true, - } - : undefined, - lockdown, - managedWorktree: runsInManagedWorktree, - }), + append: withClaudeProjectInstructions( + buildClaudeSystemPromptAppend({ + pageAssetsDir: agentPages ? pageAssets : undefined, + artifacts, + commandRequests: credential !== undefined && commandRequests, + room: + roomServer !== undefined + ? { + tools: roomToolsFor(undefined, { + scheduledRun: input.scheduledRunTools === true, + guideOnly: roomGrant.guideOnly, + }), + schedules: input.scheduleTools === true, + } + : undefined, + lockdown, + managedWorktree: runsInManagedWorktree, + }), + lockdown ? undefined : input.projectInstructions, + ), }, settingSources: [...CLAUDE_SETTING_SOURCES], // SDK 0.3.233 dropped the todo/task tools from the default tool diff --git a/apps/server/src/provider/Layers/CodexAdapter.ts b/apps/server/src/provider/Layers/CodexAdapter.ts index 9f5aa8f81..f5b587833 100644 --- a/apps/server/src/provider/Layers/CodexAdapter.ts +++ b/apps/server/src/provider/Layers/CodexAdapter.ts @@ -3431,6 +3431,9 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* ( ? { scheduleTools: true } : {}), ...(input.agentPages === true && sideAnswer === undefined ? { agentPages: true } : {}), + ...(input.projectInstructions !== undefined && sideAnswer === undefined + ? { projectInstructions: input.projectInstructions } + : {}), ...(input.commandRequests === true && sideAnswer === undefined ? { commandRequests: true } : {}), diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts index 94d5c4af1..cea5b73b8 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.test.ts @@ -1,4 +1,7 @@ import assert from "node:assert/strict"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import * as os from "node:os"; +import * as path from "node:path"; import { fileURLToPath } from "node:url"; import * as Duration from "effect/Duration"; @@ -24,6 +27,7 @@ import { CODEX_BROWSER_TOKEN_ENV_VAR } from "../codexAppServerArgs.ts"; import { mcpSessionRegistry } from "../../mcp/McpSessionRegistry.ts"; import { ROOM_REQUEST_DEADLINE } from "../../mcp/roomToolTimeouts.ts"; import { ROOM_TOOL_NAMES } from "../../mcp/roomToolAccess.ts"; +import { PROJECT_BRIEF_CLEARED_NOTE, projectBriefHash } from "../projectBriefPreface.ts"; import { buildPermissionsApprovalResponse, buildTurnStartParams, @@ -1958,3 +1962,211 @@ describe("Codex room tools", () => { ); }); }); + +describe("Codex project brief", () => { + /** + * A peer that answers what a session start asks, logs each request to + * PEER_LOG, and answers `config/read` as PEER_CONFIG says ("own": the user + * has their own developer instructions, "none": none, "fail": an error). + */ + const PEER = ` +const fs = require("node:fs"); +const write = (message) => process.stdout.write(JSON.stringify(message) + "\\n"); +const opened = (id) => ({ + approvalPolicy: "never", + approvalsReviewer: "user", + cwd: process.cwd(), + model: "gpt-5.6-sol", + modelProvider: "openai", + sandbox: { type: "dangerFullAccess" }, + thread: { + cliVersion: "0.155.0", createdAt: 0, cwd: process.cwd(), ephemeral: true, id, + modelProvider: "openai", preview: "", projectId: null, sessionId: "session-1", + source: "cli", status: { type: "idle" }, turns: [], updatedAt: 0, + }, +}); +let rest = ""; +process.stdin.setEncoding("utf8"); +process.stdin.on("data", (chunk) => { + rest += chunk; + const lines = rest.split("\\n"); + rest = lines.pop() ?? ""; + for (const line of lines) { + if (line.trim().length === 0) continue; + const { id, method, params } = JSON.parse(line); + if (typeof method !== "string" || id === undefined) continue; + fs.appendFileSync(process.env.PEER_LOG, JSON.stringify({ method, params }) + "\\n"); + if (method === "initialize") { + write({ id, result: { userAgent: "peer", codexHome: process.cwd(), platformFamily: process.platform === "win32" ? "windows" : "unix", platformOs: process.platform === "darwin" ? "macos" : process.platform } }); + } else if (method === "config/read") { + if (process.env.PEER_CONFIG === "fail") write({ id, error: { code: -32603, message: "config.toml is invalid" } }); + else write({ id, result: { config: process.env.PEER_CONFIG === "own" ? { developer_instructions: "Answer in French." } : {}, origins: {} } }); + } else if (method === "thread/start") { + write({ id, result: opened("thread-new") }); + } else if (method === "thread/resume") { + write({ id, result: opened(params.threadId) }); + } else if (method === "thread/fork") { + write({ id, result: opened("thread-forked") }); + } else if (method === "thread/inject_items") { + write({ id, result: {} }); + } else { + write({ id, error: { code: -32601, message: "Unhandled request: " + method } }); + } + } +}); +process.stdin.on("end", () => process.exit(0)); +`; + const BRIEF = "Use pnpm here. Never touch the generated folder."; + type PeerRequest = { readonly method: string; readonly params: Record<string, unknown> }; + + /** Start a runtime against the peer; returns its session and the requests the peer got. */ + const startAgainstPeer = ( + config: "own" | "none" | "fail", + options: Omit<Parameters<typeof makeCodexSessionRuntime>[0], "binaryPath" | "cwd">, + ) => + Effect.gen(function* () { + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; + const dir = mkdtempSync(path.join(os.tmpdir(), "codex-project-brief-")); + yield* Effect.addFinalizer(() => + Effect.sync(() => rmSync(dir, { recursive: true, force: true })), + ); + const log = path.join(dir, "requests.jsonl"); + const runtime = yield* makeCodexSessionRuntime({ + ...options, + binaryPath: process.execPath, + cwd: process.cwd(), + }).pipe( + Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, { + ...spawner, + spawn: () => + spawner.spawn( + ChildProcess.make(process.execPath, ["-e", PEER], { + env: { ...process.env, PEER_LOG: log, PEER_CONFIG: config }, + }), + ), + }), + ); + const session = yield* runtime.start(); + yield* runtime.close; + const requests = readFileSync(log, "utf8") + .trim() + .split("\n") + .map((line) => JSON.parse(line) as PeerRequest); + return { session, requests }; + }); + const paramsOf = (requests: ReadonlyArray<PeerRequest>, method: string) => + requests.find((request) => request.method === method)?.params; + const briefHashOf = (cursor: unknown) => + (cursor as { readonly projectBriefHash?: string } | undefined)?.projectBriefHash; + /** The developer messages a resume added to the thread. */ + const injectedTexts = (requests: ReadonlyArray<PeerRequest>) => + requests + .filter((request) => request.method === "thread/inject_items") + .flatMap( + (request) => + request.params.items as ReadonlyArray<{ + role: string; + content: ReadonlyArray<{ text: string }>; + }>, + ) + .map((item) => `${item.role}: ${item.content.map((part) => part.text).join("")}`); + + it("opens a thread with the user's developer instructions, then the brief, and keeps its hash", async () => { + await Effect.runPromise( + Effect.gen(function* () { + const started = yield* startAgainstPeer("own", { + threadId: ThreadId.make("brief-start-thread"), + serverPort: 0, + runtimeMode: "full-access", + projectInstructions: BRIEF, + }); + assert.deepEqual(paramsOf(started.requests, "config/read"), { cwd: process.cwd() }); + assert.equal( + paramsOf(started.requests, "thread/start")?.developerInstructions, + `Answer in French.\n\n${BRIEF}`, + ); + assert.deepEqual(injectedTexts(started.requests), []); + assert.equal(briefHashOf(started.session.resumeCursor), projectBriefHash(BRIEF)); + + const forked = yield* startAgainstPeer("none", { + threadId: ThreadId.make("brief-fork-thread"), + serverPort: 0, + runtimeMode: "full-access", + forkFrom: { providerThreadId: "thread-source", lastTurnId: "turn-3" }, + projectInstructions: BRIEF, + }); + assert.equal(paramsOf(forked.requests, "thread/fork")?.developerInstructions, BRIEF); + assert.deepEqual(injectedTexts(forked.requests), []); + assert.equal(briefHashOf(forked.session.resumeCursor), projectBriefHash(BRIEF)); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer), Effect.timeout("20 seconds")), + ); + }); + + it("adds the brief to a resumed thread only when it changed since the thread got it", async () => { + await Effect.runPromise( + Effect.gen(function* () { + const resume = (projectInstructions: string | undefined, heldBrief: string) => + startAgainstPeer("own", { + threadId: ThreadId.make("brief-resume-thread"), + serverPort: 0, + runtimeMode: "full-access", + resumeCursor: { threadId: "thread-old", projectBriefHash: projectBriefHash(heldBrief) }, + ...(projectInstructions !== undefined ? { projectInstructions } : {}), + }); + + const same = yield* resume(BRIEF, BRIEF); + assert.deepEqual(injectedTexts(same.requests), []); + assert.equal(briefHashOf(same.session.resumeCursor), projectBriefHash(BRIEF)); + + const changed = yield* resume(BRIEF, "Use npm here."); + assert.deepEqual(injectedTexts(changed.requests), [`developer: ${BRIEF}`]); + assert.equal(paramsOf(changed.requests, "thread/inject_items")?.threadId, "thread-old"); + assert.equal(briefHashOf(changed.session.resumeCursor), projectBriefHash(BRIEF)); + + const cleared = yield* resume(undefined, BRIEF); + assert.deepEqual(injectedTexts(cleared.requests), [ + `developer: ${PROJECT_BRIEF_CLEARED_NOTE}`, + ]); + assert.equal(briefHashOf(cleared.session.resumeCursor), undefined); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer), Effect.timeout("20 seconds")), + ); + }); + + it("leaves the brief out when Codex's config can't be read, and out of a side answer", async () => { + await Effect.runPromise( + Effect.gen(function* () { + // Codex would drop the user's own instructions for ours. + const unreadable = yield* startAgainstPeer("fail", { + threadId: ThreadId.make("brief-unreadable-thread"), + serverPort: 0, + runtimeMode: "full-access", + projectInstructions: BRIEF, + }); + assert.ok(paramsOf(unreadable.requests, "thread/start") !== undefined); + assert.equal( + paramsOf(unreadable.requests, "thread/start")?.developerInstructions, + undefined, + ); + assert.deepEqual(injectedTexts(unreadable.requests), []); + + const side = yield* startAgainstPeer("own", { + threadId: sideSessionKey( + ThreadId.make("0f8f5a52-4d0e-4c1b-9d56-1e7c1f9b7a02"), + SideTurnId.make("b2c4d6e8-1a3b-4c5d-8e9f-0a1b2c3d4e60"), + null, + ), + serverPort: 0, + runtimeMode: "full-access", + projectInstructions: BRIEF, + lockdown: { + kind: "review", + signIn: () => Effect.succeed({ kind: "apiKey", apiKey: "sk-test" }), + }, + }); + assert.ok(paramsOf(side.requests, "thread/start") !== undefined); + assert.equal(paramsOf(side.requests, "config/read"), undefined); + assert.equal(paramsOf(side.requests, "thread/start")?.developerInstructions, undefined); + }).pipe(Effect.scoped, Effect.provide(NodeServices.layer), Effect.timeout("20 seconds")), + ); + }); +}); diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index 584c70612..52bbed35e 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -22,6 +22,7 @@ import { buildGuideInstructions } from "../../mcp/guideTools.ts"; import { buildScheduleInstructions } from "../../mcp/scheduleTools.ts"; import { type CodexBorrowedSignIn, type CodexSideAnswerHomeError } from "../codexSideAnswerHome.ts"; import { removeSideRuntimeHome } from "../sideRuntimeHome.ts"; +import { projectBriefPreface } from "../projectBriefPreface.ts"; import { ApprovalRequestId, DEFAULT_MODEL, @@ -54,6 +55,7 @@ import { isLinkedWorktreeCheckout } from "../../vcs/CheckoutPresence.ts"; import { MANAGED_WORKTREE_INSTRUCTION } from "@threadlines/shared/contextSeed"; import { normalizeModelSlug } from "@threadlines/shared/model"; import { isProviderAuthErrorMessage } from "@threadlines/shared/providerAuth"; +import * as Cause from "effect/Cause"; import * as DateTime from "effect/DateTime"; import * as Deferred from "effect/Deferred"; import * as Duration from "effect/Duration"; @@ -192,6 +194,8 @@ export const CodexResumeCursorSchema = Schema.Struct({ * path, as a side answer's copy is. */ rolloutPath: Schema.optional(Schema.String), + /** The hash of the project brief this conversation holds (projectBriefPreface). */ + projectBriefHash: Schema.optional(Schema.String), }); const CodexUserInputAnswerObject = Schema.Struct({ answers: Schema.Array(Schema.String), @@ -251,6 +255,12 @@ export interface CodexSessionRuntimeOptions { readonly agentPages?: boolean; /** Attach `ask_user_to_run` (ProviderSessionStartInput.commandRequests). Never for a side runtime. */ readonly commandRequests?: boolean; + /** + * The project's brief (ProviderSessionStartInput.projectInstructions). The + * provider thread keeps it as its developer instructions, set at every + * start, resume and fork, after the user's own from Codex's config. + */ + readonly projectInstructions?: string; readonly onRealtimeAudio?: (audio: ProviderRealtimeAudioChunk) => Effect.Effect<void>; } @@ -579,6 +589,10 @@ function readResumeCursorThreadId( return isCodexResumeCursorSchema(resumeCursor) ? resumeCursor.threadId : undefined; } +function readResumeCursorProjectBriefHash(resumeCursor: unknown): string | undefined { + return isCodexResumeCursorSchema(resumeCursor) ? resumeCursor.projectBriefHash : undefined; +} + function readResumeCursorRolloutPath( resumeCursor: ProviderSession["resumeCursor"], ): string | undefined { @@ -626,6 +640,8 @@ function buildThreadStartParams(input: { readonly model: string | undefined; readonly serviceTier: CodexServiceTier | undefined; readonly lockdown?: boolean; + /** The thread's developer instructions (codexThreadDeveloperInstructions). */ + readonly developerInstructions: string | undefined; }): EffectCodexSchema.V2ThreadStartParams { const config: ReturnType<typeof runtimeModeToThreadConfig> = input.lockdown ? SIDE_ANSWER_THREAD_CONFIG @@ -638,6 +654,9 @@ function buildThreadStartParams(input: { ...(config.approvalsReviewer ? { approvalsReviewer: config.approvalsReviewer } : {}), ...(input.model ? { model: input.model } : {}), ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}), + ...(input.developerInstructions !== undefined && input.lockdown !== true + ? { developerInstructions: input.developerInstructions } + : {}), }; } @@ -648,6 +667,7 @@ function buildThreadForkParams(input: { readonly runtimeMode: RuntimeMode; readonly model: string | undefined; readonly serviceTier: CodexServiceTier | undefined; + readonly developerInstructions: string | undefined; }): EffectCodexSchema.V2ThreadForkParams { const config = runtimeModeToThreadConfig(input.runtimeMode); return { @@ -661,9 +681,32 @@ function buildThreadForkParams(input: { ...(config.approvalsReviewer ? { approvalsReviewer: config.approvalsReviewer } : {}), ...(input.model ? { model: input.model } : {}), ...(input.serviceTier ? { serviceTier: input.serviceTier } : {}), + ...(input.developerInstructions !== undefined + ? { developerInstructions: input.developerInstructions } + : {}), }; } +/** + * What a provider thread opened for this session keeps as its developer + * instructions: the user's own from Codex's config, then the project's brief + * (docs/design/project-brief-notes.md). Set on the thread rather than per + * turn, because a goal's cold start runs with no `turn/start`. Codex replaces + * the config's value with the thread's, so the config's comes first; without + * it (it could not be read) the brief is left out rather than the user's + * own instructions dropped. Undefined: leave Codex's own. + */ +export function codexThreadDeveloperInstructions(input: { + readonly projectInstructions: string | undefined; + readonly config: Option.Option<string | null | undefined>; +}): string | undefined { + const project = input.projectInstructions?.trim(); + if (project === undefined || project.length === 0) return undefined; + if (Option.isNone(input.config)) return undefined; + const own = input.config.value?.trim(); + return own === undefined || own.length === 0 ? project : `${own}\n\n${project}`; +} + function runtimeModeToTurnSandboxPolicy( input: RuntimeMode, ): EffectCodexSchema.V2TurnStartParams__SandboxPolicy { @@ -1008,6 +1051,8 @@ export const openCodexThread = (input: { readonly cwd: string; readonly requestedModel: string | undefined; readonly serviceTier: CodexServiceTier | undefined; + /** See codexThreadDeveloperInstructions. Never for a side answer. */ + readonly developerInstructions?: string | undefined; readonly resumeThreadId: string | undefined; /** Where the rollout to resume is, when this home's Codex may not know it (a carried session). */ readonly resumePath?: string | undefined; @@ -1031,6 +1076,7 @@ export const openCodexThread = (input: { model: input.requestedModel, serviceTier: input.serviceTier, ...(input.lockdown !== undefined ? { lockdown: true } : {}), + developerInstructions: input.developerInstructions, }); if (input.lockdown !== undefined) { @@ -1068,6 +1114,7 @@ export const openCodexThread = (input: { runtimeMode: input.runtimeMode, model: input.requestedModel, serviceTier: input.serviceTier, + developerInstructions: input.developerInstructions, }), ); const forkRequest = @@ -1081,6 +1128,7 @@ export const openCodexThread = (input: { runtimeMode: input.runtimeMode, model: input.requestedModel, serviceTier: input.serviceTier, + developerInstructions: input.developerInstructions, }), beforeTurnId: forkFrom.beforeTurnId, }) @@ -1262,6 +1310,8 @@ export const rollbackCodexThread = (input: { readonly runtimeMode: RuntimeMode; readonly model: string | undefined; readonly serviceTier: CodexServiceTier | undefined; + /** See codexThreadDeveloperInstructions. */ + readonly developerInstructions?: string | undefined; }): Effect.Effect<CodexThreadRollbackResult, CodexErrors.CodexAppServerError> => Effect.gen(function* () { const { client, providerThreadId, numTurns } = input; @@ -1281,6 +1331,7 @@ export const rollbackCodexThread = (input: { runtimeMode: input.runtimeMode, model: input.model, serviceTier: input.serviceTier, + developerInstructions: input.developerInstructions, }), ), ), @@ -1342,6 +1393,7 @@ export const rollbackCodexThread = (input: { runtimeMode: input.runtimeMode, model: input.model, serviceTier: input.serviceTier, + developerInstructions: input.developerInstructions, }); yield* withCodexRequestTimeout( "reload a reverted Codex thread", @@ -1392,6 +1444,7 @@ export const rollbackCodexThread = (input: { runtimeMode: input.runtimeMode, model: input.model, serviceTier: input.serviceTier, + developerInstructions: input.developerInstructions, }), ...(lastSurvivingTurn === undefined ? { beforeTurnId: firstUndoneTurn.id } : {}), deferGoalContinuation: true, @@ -2356,7 +2409,7 @@ const makeCodexSessionRuntimeIn = ( return Effect.void; } return updateSession(sessionRef, { - resumeCursor: { threadId: payload.thread.id }, + resumeCursor: withProjectBriefHash({ threadId: payload.thread.id }), providerThreadId: payload.thread.id, }); }), @@ -2848,6 +2901,33 @@ const makeCodexSessionRuntimeIn = ( Effect.forkIn(runtimeScope), ); + /** What the session's provider threads keep (codexThreadDeveloperInstructions), set at start. */ + let threadDeveloperInstructions: string | undefined; + /** + * The hash of the project brief the conversation holds, kept in every + * resume cursor this session writes. A thread Codex creates (start, fork, + * a rollback's copy) gets the brief in its opening context; a resumed one + * keeps the context it opened with, so a changed brief is added to it. + */ + let projectBriefHashHeld: string | undefined; + const withProjectBriefHash = <C extends { readonly threadId: string }>(cursor: C) => + projectBriefHashHeld !== undefined + ? { ...cursor, projectBriefHash: projectBriefHashHeld } + : cursor; + /** The user's own `developer_instructions` for this folder; none when Codex can't say. */ + const readConfiguredDeveloperInstructions = withCodexRequestTimeout( + "read Codex's config", + client.request("config/read", { cwd: options.cwd }), + ).pipe( + Effect.map((response) => Option.some(response.config.developer_instructions)), + Effect.catchCause((cause) => + Effect.logWarning("codex config could not be read; the project brief is left out", { + threadId: options.threadId, + cause: Cause.pretty(cause), + }).pipe(Effect.as(Option.none<string | null | undefined>())), + ), + ); + const start = Effect.fn("CodexSessionRuntime.start")(function* () { yield* emitSessionEvent("session/connecting", "Starting Codex App Server session."); yield* withCodexRequestTimeout( @@ -2881,6 +2961,13 @@ const makeCodexSessionRuntimeIn = ( // The reactor owes a session that came up without its conversation the // thread's history (ProviderSession.resumeFailed). let resumeFailed = false; + threadDeveloperInstructions = + lockdown === undefined && options.projectInstructions !== undefined + ? codexThreadDeveloperInstructions({ + projectInstructions: options.projectInstructions, + config: yield* readConfiguredDeveloperInstructions, + }) + : undefined; const opened = yield* openCodexThread({ client, threadId: options.threadId, @@ -2888,6 +2975,7 @@ const makeCodexSessionRuntimeIn = ( cwd: options.cwd, requestedModel, serviceTier: options.serviceTier, + developerInstructions: threadDeveloperInstructions, resumeThreadId, resumePath, resumeRequired: options.resumeRequired, @@ -2909,6 +2997,45 @@ const makeCodexSessionRuntimeIn = ( }); const providerThreadId = opened.thread.id; + if (threadDeveloperInstructions !== undefined || options.projectInstructions === undefined) { + // Left alone when Codex's config could not be read: the brief was + // left out, so what the conversation holds is unknown. + const resumed = resumeThreadId !== undefined && providerThreadId === resumeThreadId; + const heldBefore = resumed + ? readResumeCursorProjectBriefHash(options.resumeCursor) + : undefined; + const preface = projectBriefPreface({ + projectInstructions: options.projectInstructions, + sentHash: heldBefore, + }); + projectBriefHashHeld = preface.hash; + if (resumed && preface.text !== undefined) { + const added = yield* withCodexRequestTimeout( + "add the project brief to a Codex thread", + client.raw.request("thread/inject_items", { + threadId: providerThreadId, + items: [ + { + type: "message", + role: "developer", + content: [{ type: "input_text", text: preface.text }], + }, + ], + }), + ).pipe( + Effect.as(true), + Effect.catch((cause) => + Effect.logWarning("codex project brief was not added", { + threadId: providerThreadId, + cause, + }).pipe(Effect.as(false)), + ), + ); + if (!added) projectBriefHashHeld = heldBefore; + } + } else if (resumeThreadId !== undefined && providerThreadId === resumeThreadId) { + projectBriefHashHeld = readResumeCursorProjectBriefHash(options.resumeCursor); + } const session = { ...(yield* Ref.get(sessionRef)), status: "ready", @@ -2916,10 +3043,11 @@ const makeCodexSessionRuntimeIn = ( model: opened.model, // A rollout resumed by path keeps its path until this home's Codex // has surely indexed it: it is the same conversation. - resumeCursor: + resumeCursor: withProjectBriefHash( resumePath !== undefined && providerThreadId === resumeThreadId ? { threadId: providerThreadId, rolloutPath: resumePath } : { threadId: providerThreadId }, + ), providerThreadId, ...(resumeFailed ? { resumeFailed: true } : {}), updatedAt: yield* nowIso, @@ -3011,7 +3139,7 @@ const makeCodexSessionRuntimeIn = ( threadId: options.threadId, turnId, ...(resumedProviderThreadId - ? { resumeCursor: { threadId: resumedProviderThreadId } } + ? { resumeCursor: withProjectBriefHash({ threadId: resumedProviderThreadId }) } : {}), } satisfies ProviderTurnStartResult; }), @@ -3044,7 +3172,7 @@ const makeCodexSessionRuntimeIn = ( reviewThreadId: response.reviewThreadId, delivery, ...(resumedProviderThreadId - ? { resumeCursor: { threadId: resumedProviderThreadId } } + ? { resumeCursor: withProjectBriefHash({ threadId: resumedProviderThreadId }) } : {}), } satisfies ProviderStartReviewResult; }), @@ -3080,7 +3208,7 @@ const makeCodexSessionRuntimeIn = ( threadId: options.threadId, turnId, ...(resumedProviderThreadId - ? { resumeCursor: { threadId: resumedProviderThreadId } } + ? { resumeCursor: withProjectBriefHash({ threadId: resumedProviderThreadId }) } : {}), } satisfies ProviderTurnStartResult; }), @@ -3370,13 +3498,14 @@ const makeCodexSessionRuntimeIn = ( runtimeMode: options.runtimeMode, model: normalizeCodexModelSlug(session.model), serviceTier: options.serviceTier, + developerInstructions: threadDeveloperInstructions, }); yield* updateSession(sessionRef, { status: "ready", activeTurnId: undefined, ...(replacementProviderThreadId !== undefined ? { - resumeCursor: { threadId: replacementProviderThreadId }, + resumeCursor: withProjectBriefHash({ threadId: replacementProviderThreadId }), providerThreadId: replacementProviderThreadId, } : {}), diff --git a/apps/server/src/provider/Layers/MuseAdapter.test.ts b/apps/server/src/provider/Layers/MuseAdapter.test.ts index 7fcea081d..697dd2462 100644 --- a/apps/server/src/provider/Layers/MuseAdapter.test.ts +++ b/apps/server/src/provider/Layers/MuseAdapter.test.ts @@ -36,6 +36,7 @@ import { type TestAgentProcess, } from "../testAgentProcess.ts"; import { steerRejectionOf } from "../Errors.ts"; +import { PROJECT_BRIEF_CLEARED_NOTE } from "../projectBriefPreface.ts"; import { type MuseHost, MuseHostError, @@ -921,6 +922,59 @@ describe("MuseAdapter", () => { }).pipe(Effect.scoped, Effect.provide(testLayer)), ); + it.effect( + "sends the project's brief on a new conversation, and on a resume only when it changed", + () => + Effect.gen(function* () { + const brief = "Use pnpm here. Never touch the generated folder."; + // Each start is a fresh adapter, as after a server restart. + const firstTurn = (input: { + readonly projectInstructions?: string; + readonly resumeCursor?: unknown; + }) => + Effect.gen(function* () { + const { hosts, adapter, threadId } = yield* setup(); + yield* adapter.startSession({ + threadId, + cwd: workspace(), + runtimeMode: "approval-required", + ...input, + }); + const turn = yield* adapter.sendTurn({ + threadId, + messageId: MessageId.make("message-hi"), + input: "hi", + }); + const turnStart = hosts.at(-1)!.calls.find((call) => call.method === "turn/start")!; + const texts = (turnStart.params.input as ReadonlyArray<{ text?: string }>).map( + (part) => part.text, + ); + return { texts, cursor: turn.resumeCursor }; + }); + + // After Threadlines' instructions, ahead of the user's words. + const fresh = yield* firstTurn({ projectInstructions: brief }); + expect(fresh.texts).toHaveLength(3); + expect(fresh.texts.slice(1)).toEqual([brief, "hi"]); + + const same = yield* firstTurn({ projectInstructions: brief, resumeCursor: fresh.cursor }); + expect(same.texts).toEqual(["hi"]); + + const changed = yield* firstTurn({ + projectInstructions: `${brief} Tests run with vp.`, + resumeCursor: same.cursor, + }); + expect(changed.texts).toEqual([`${brief} Tests run with vp.`, "hi"]); + + const cleared = yield* firstTurn({ resumeCursor: changed.cursor }); + expect(cleared.texts).toEqual([PROJECT_BRIEF_CLEARED_NOTE, "hi"]); + + // The note is said once. + const after = yield* firstTurn({ resumeCursor: cleared.cursor }); + expect(after.texts).toEqual(["hi"]); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + it.effect("refuses to run on an API key unless per-use billing is allowed", () => Effect.gen(function* () { const apiKey: Responder = (call) => diff --git a/apps/server/src/provider/Layers/MuseAdapter.ts b/apps/server/src/provider/Layers/MuseAdapter.ts index 144d6a9ad..a3fa55c39 100644 --- a/apps/server/src/provider/Layers/MuseAdapter.ts +++ b/apps/server/src/provider/Layers/MuseAdapter.ts @@ -48,6 +48,11 @@ import { } from "@threadlines/contracts"; import { withFailureCategory } from "../providerFailureCategory.ts"; import { makeAgentProcessLedger } from "../agentProcessLedger.ts"; +import { + type ProjectBriefPreface, + projectBriefPreface, + readProjectBriefHash, +} from "../projectBriefPreface.ts"; import { MANAGED_WORKTREE_INSTRUCTION, renderThreadContextSeed, @@ -318,6 +323,10 @@ interface SessionContext { pendingSeed: string | undefined; /** Threadlines' instructions still have to reach this conversation. */ instructionsPending: boolean; + /** The project's brief for the next turn, and the hash the conversation then holds (projectBriefPreface). */ + projectBrief: ProjectBriefPreface; + /** The brief's hash this conversation holds, kept in the resume cursor. */ + projectBriefHash: string | undefined; activeTurn: ActiveTurn | undefined; /** Our `turn/start`s Muse queued instead of starting. */ readonly queued: Set<string>; @@ -348,6 +357,16 @@ interface SessionContext { const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value); +/** The session's resume cursor: its Muse conversation, and the brief's hash it holds. */ +const museResumeCursor = (ctx: { + readonly museSessionId: string; + readonly projectBriefHash: string | undefined; +}) => ({ + schemaVersion: RESUME_SCHEMA_VERSION, + sessionId: ctx.museSessionId, + ...(ctx.projectBriefHash !== undefined ? { projectBriefHash: ctx.projectBriefHash } : {}), +}); + export function parseMuseResumeCursor(raw: unknown): { readonly sessionId: string } | undefined { if (!isRecord(raw) || raw.schemaVersion !== RESUME_SCHEMA_VERSION) return undefined; return typeof raw.sessionId === "string" && raw.sessionId.length > 0 @@ -2249,6 +2268,8 @@ export function makeMuseAdapter(options: MuseAdapterOptions) { model: boundSelection?.model, pendingSeed: undefined, instructionsPending: true, + projectBrief: { text: undefined, hash: undefined }, + projectBriefHash: undefined, activeTurn: undefined, queued: new Set(), joined: new Map(), @@ -2345,9 +2366,21 @@ export function makeMuseAdapter(options: MuseAdapterOptions) { // A resumed or forked conversation already holds Threadlines' instructions. ctx.instructionsPending = false; } + // The brief is sent again whenever it changed, resumed or not: a + // fork's copy is taken not to hold this thread's. + // Only the thread's own conversation, reopened from its cursor, holds + // the brief the cursor names; a fork's copy is taken not to. + ctx.projectBriefHash = + resumed && ctx.museSessionId === resumeId + ? readProjectBriefHash(input.resumeCursor) + : undefined; + ctx.projectBrief = projectBriefPreface({ + projectInstructions: input.projectInstructions, + sentHash: ctx.projectBriefHash, + }); ctx.session = { ...ctx.session, - resumeCursor: { schemaVersion: RESUME_SCHEMA_VERSION, sessionId: ctx.museSessionId }, + resumeCursor: museResumeCursor(ctx), providerThreadId: ctx.museSessionId, ...(ctx.model ? { model: ctx.model } : {}), }; @@ -2474,8 +2507,10 @@ export function makeMuseAdapter(options: MuseAdapterOptions) { const turnId = TurnId.make(host.host.mintCommandId()); // The device note is a part of its own, so Muse shows only the // user's words as theirs (displayText). + const projectBrief = ctx.projectBrief; const preface = [ ...(ctx.instructionsPending ? [instructionsFor(ctx)] : []), + ...(projectBrief.text !== undefined ? [projectBrief.text] : []), ...(plan ? [MUSE_PLAN_MODE_INSTRUCTION] : []), ...(input.deviceNote !== undefined ? [input.deviceNote] : []), ]; @@ -2509,6 +2544,11 @@ export function makeMuseAdapter(options: MuseAdapterOptions) { if (Option.isSome(ack) && ack.value.disposition === "queued") ctx.queued.add(turnId); ctx.instructionsPending = false; ctx.pendingSeed = undefined; + if (projectBrief.text !== undefined) { + ctx.projectBrief = { text: undefined, hash: projectBrief.hash }; + ctx.projectBriefHash = projectBrief.hash; + ctx.session = { ...ctx.session, resumeCursor: museResumeCursor(ctx) }; + } } return { threadId: input.threadId, turnId, resumeCursor: ctx.session.resumeCursor }; }), diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts index c18899b17..4a64a3c40 100644 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts +++ b/apps/server/src/provider/Layers/OpenCodeAdapter.test.ts @@ -234,6 +234,24 @@ describe("OpenCodeAdapter", () => { }).pipe(Effect.scoped, Effect.provide(testLayer)), ); + it.live("ends Threadlines' instructions entry with the project's brief", () => + Effect.gen(function* () { + const { adapter, calls, threadId, cwd } = yield* harness; + const brief = "Use pnpm here. Never touch the generated folder."; + yield* adapter.startSession({ + threadId, + cwd, + runtimeMode: "full-access", + projectInstructions: brief, + }); + const put = calls.find((call) => call.method === "instructions.put")?.input as + | { readonly key: string; readonly value: string } + | undefined; + expect(put?.key).toBe("threadlines"); + expect(put?.value.endsWith(`\n\n${brief}`)).toBe(true); + }).pipe(Effect.scoped, Effect.provide(testLayer)), + ); + it.live("turns an execution nobody asked for into the agent's own turn", () => Effect.gen(function* () { const { adapter, send, next, threadId, cwd } = yield* harness; diff --git a/apps/server/src/provider/Layers/OpenCodeAdapter.ts b/apps/server/src/provider/Layers/OpenCodeAdapter.ts index de04671b4..4b4043907 100644 --- a/apps/server/src/provider/Layers/OpenCodeAdapter.ts +++ b/apps/server/src/provider/Layers/OpenCodeAdapter.ts @@ -260,6 +260,8 @@ interface SessionContext { readonly agentPageAssetsDir: string | undefined; /** The session has `ask_user_to_run`. */ readonly commandRequests: boolean; + /** The project's brief (ProviderSessionStartInput.projectInstructions), last in the instructions entry. */ + readonly projectInstructions: string | undefined; readonly runtimeMode: RuntimeMode; agent: string; model: OpenCodeModelRef | undefined; @@ -2050,6 +2052,7 @@ export function makeOpenCodeAdapter(options: OpenCodeAdapterOptions) { : []), FILE_LINK_INSTRUCTIONS, ...(managedWorktree ? [MANAGED_WORKTREE_INSTRUCTION] : []), + ...(ctx.projectInstructions !== undefined ? [ctx.projectInstructions] : []), ].join("\n\n"); const resolveModel = ( @@ -2291,6 +2294,7 @@ export function makeOpenCodeAdapter(options: OpenCodeAdapterOptions) { scheduleTools: roomTools && input.scheduleTools === true, agentPageAssetsDir, commandRequests: input.commandRequests === true, + projectInstructions: input.projectInstructions, runtimeMode: input.runtimeMode, agent: BUILD_AGENT, model, diff --git a/apps/server/src/provider/Layers/PiAdapter.integration.test.ts b/apps/server/src/provider/Layers/PiAdapter.integration.test.ts index 17be73043..5bee6b856 100644 --- a/apps/server/src/provider/Layers/PiAdapter.integration.test.ts +++ b/apps/server/src/provider/Layers/PiAdapter.integration.test.ts @@ -25,6 +25,7 @@ import * as Stream from "effect/Stream"; import { describe, expect } from "vite-plus/test"; import { ServerConfig } from "../../config.ts"; +import { FILE_LINK_INSTRUCTIONS } from "../fileLinkInstructions.ts"; import { parsePiResumeCursor } from "../pi/PiCursor.ts"; import { makeTestPiHome, @@ -90,6 +91,7 @@ const setupWith = (withoutEnv: ReadonlyArray<string>) => readonly cwd?: string; readonly resumeCursor?: unknown; readonly forkFrom?: { readonly providerThreadId: string; readonly lastTurnId?: string }; + readonly projectInstructions?: string; } = {}, ) => adapter.startSession({ @@ -98,6 +100,9 @@ const setupWith = (withoutEnv: ReadonlyArray<string>) => runtimeMode: input.runtimeMode ?? "full-access", ...(input.resumeCursor !== undefined ? { resumeCursor: input.resumeCursor } : {}), ...(input.forkFrom ? { forkFrom: input.forkFrom } : {}), + ...(input.projectInstructions !== undefined + ? { projectInstructions: input.projectInstructions } + : {}), }); const send = (threadId: ThreadId, text: string, interactionMode?: "plan") => adapter.sendTurn({ @@ -203,6 +208,36 @@ describe.skipIf(!piCli)("PiAdapter with a real Pi", () => { 90_000, ); + it.live( + "ends Threadlines' instructions to Pi with the project's brief", + () => + run( + Effect.gen(function* () { + const { model, turnEnd, start, send } = yield* setup; + const threadId = ThreadId.make("pi-brief"); + const brief = "Use pnpm here. Never touch the generated folder."; + yield* start(threadId, { projectInstructions: brief }); + yield* send(threadId, "hello there"); + yield* turnEnd(threadId); + const messages = (model.requests.at(-1)?.messages ?? []) as Array<{ + role: string; + content: unknown; + }>; + const system = messages + .filter((message) => message.role === "system" || message.role === "developer") + .map((message) => + typeof message.content === "string" + ? message.content + : JSON.stringify(message.content), + ) + .join("\n"); + // The last of Threadlines' instructions, then the brief. + expect(system).toContain(`${FILE_LINK_INSTRUCTIONS}\n\n${brief}`); + }), + ), + 60_000, + ); + it.live( "says a provider refusing Pi's key as a sign-in failure, not a turn to retry", () => diff --git a/apps/server/src/provider/Layers/PiAdapter.ts b/apps/server/src/provider/Layers/PiAdapter.ts index cce93747e..8090cab0e 100644 --- a/apps/server/src/provider/Layers/PiAdapter.ts +++ b/apps/server/src/provider/Layers/PiAdapter.ts @@ -1757,13 +1757,18 @@ export function makePiAdapter(options: PiAdapterOptions) { const managedWorktree = yield* isLinkedWorktreeCheckout(directory).pipe( Effect.provideService(FileSystem.FileSystem, fileSystem), ); - const instructions = instructionsFor({ - agentPageAssetsDir, - commandRequests, - scheduleTools: roomTools && input.scheduleTools === true, - roomEndpoint: roomGrant.attach, - managedWorktree, - }); + // The project's brief goes last. The file is named by the hash of + // the whole text, so another project's brief is never reused. + const instructions = [ + instructionsFor({ + agentPageAssetsDir, + commandRequests, + scheduleTools: roomTools && input.scheduleTools === true, + roomEndpoint: roomGrant.attach, + managedWorktree, + }), + ...(input.projectInstructions !== undefined ? [input.projectInstructions] : []), + ].join("\n\n"); const instructionsPath = NodePath.join( options.extensionDir, "instructions", diff --git a/apps/server/src/provider/Layers/ProviderService.test.ts b/apps/server/src/provider/Layers/ProviderService.test.ts index cd58c1ee0..838ed6520 100644 --- a/apps/server/src/provider/Layers/ProviderService.test.ts +++ b/apps/server/src/provider/Layers/ProviderService.test.ts @@ -67,6 +67,7 @@ import { import { ProviderService } from "../Services/ProviderService.ts"; import { ProviderSessionDirectory } from "../Services/ProviderSessionDirectory.ts"; import { makeProviderServiceLive } from "./ProviderService.ts"; +import { ProjectInstructions } from "../Services/ProjectInstructions.ts"; import { NoOpProviderEventLoggers, ProviderEventLoggers } from "./ProviderEventLoggers.ts"; import { ProviderSessionDirectoryLive } from "./ProviderSessionDirectory.ts"; import * as NodeServices from "@effect/platform-node/NodeServices"; @@ -442,11 +443,17 @@ function makeProviderServiceLayer() { Layer.provide(SqlitePersistenceMemory), ); const directoryLayer = ProviderSessionDirectoryLive.pipe(Layer.provide(runtimeRepositoryLayer)); + // The project's brief every session starts with; tests change it. + const project = { brief: undefined as string | undefined }; + const projectInstructionsLayer = Layer.succeed(ProjectInstructions, { + forSession: () => Effect.sync(() => project.brief), + }); const layer = it.layer( Layer.mergeAll( makeProviderServiceLive().pipe( Layer.provide(ThreadSessionAdmissionPermissive), + Layer.provide(projectInstructionsLayer), Layer.provide(providerAdapterLayer), Layer.provide(directoryLayer), Layer.provide(defaultServerSettingsLayer), @@ -464,6 +471,7 @@ function makeProviderServiceLayer() { codex, claude, cursor, + project, layer, }; } @@ -2259,6 +2267,41 @@ routing.layer("ProviderServiceLive routing", (it) => { }), ); + it.effect("a session started again inside sendTurn gets the brief as it is now", () => + Effect.gen(function* () { + const provider = yield* ProviderService; + const threadId = asThreadId("thread-brief"); + routing.project.brief = "Brief v1"; + routing.codex.startSession.mockClear(); + + yield* provider.startSession(threadId, { + provider: ProviderDriverKind.make("codex"), + providerInstanceId: codexInstanceId, + threadId, + cwd: "/tmp/project-brief", + runtimeMode: "full-access", + // Only the lookup decides it. + projectInstructions: "From the caller", + }); + const started = routing.codex.startSession.mock.calls[0]?.[0] as + | { readonly projectInstructions?: string } + | undefined; + assert.equal(started?.projectInstructions, "Brief v1"); + + // The user edits the brief; the session stops and comes back on the next turn. + routing.project.brief = "Brief v2"; + yield* routing.codex.stopAll(); + routing.codex.startSession.mockClear(); + yield* provider.sendTurn({ threadId, input: "go on", attachments: [] }); + + const recovered = routing.codex.startSession.mock.calls[0]?.[0] as + | { readonly projectInstructions?: string } + | undefined; + assert.equal(recovered?.projectInstructions, "Brief v2"); + routing.project.brief = undefined; + }), + ); + it.effect("brings a recovered room runtime back with its room tools", () => Effect.gen(function* () { const provider = yield* ProviderService; diff --git a/apps/server/src/provider/Layers/ProviderService.ts b/apps/server/src/provider/Layers/ProviderService.ts index bd3eff178..d11d5f7ec 100644 --- a/apps/server/src/provider/Layers/ProviderService.ts +++ b/apps/server/src/provider/Layers/ProviderService.ts @@ -68,6 +68,7 @@ import { import { type ProviderAdapterError, ProviderValidationError } from "../Errors.ts"; import type { ProviderAdapterShape } from "../Services/ProviderAdapter.ts"; import { ThreadSessionAdmission } from "../Services/ThreadSessionAdmission.ts"; +import { ProjectInstructions } from "../Services/ProjectInstructions.ts"; import { ProviderAdapterRegistry } from "../Services/ProviderAdapterRegistry.ts"; import { ProviderService, type ProviderServiceShape } from "../Services/ProviderService.ts"; import { @@ -387,6 +388,23 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const registry = yield* ProviderAdapterRegistry; const directory = yield* ProviderSessionDirectory; const admission = yield* ThreadSessionAdmission; + const projectInstructions = yield* Effect.serviceOption(ProjectInstructions); + /** + * The project's text for a session about to start (docs/design/ + * project-brief-notes.md, "Delivery"), read at every adapter start so a + * restarted session gets the brief as it is now. Whatever a caller passed + * is replaced: only this lookup decides it. + */ + const withProjectInstructions = <T extends ProviderSessionStartInput>(input: T) => + Effect.gen(function* () { + const { projectInstructions: _ignored, ...rest } = input; + if (Option.isNone(projectInstructions)) return rest; + const text = yield* projectInstructions.value.forSession({ + sessionKey: input.threadId, + runtimeMode: input.runtimeMode, + }); + return text === undefined ? rest : { ...rest, projectInstructions: text }; + }); const runtimeEventPubSub = yield* PubSub.unbounded<ProviderRuntimeEvent>(); const nowIso = Effect.map(DateTime.now, DateTime.formatIso); const turnLatency = makeTurnLatencyTracker(); @@ -809,21 +827,23 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const startBeganAtMs = yield* Clock.currentTimeMillis; const startBeganNanos = yield* Clock.monotonicTimeNanos; - const resumed = yield* adapter.startSession({ - threadId: input.binding.threadId, - provider: input.binding.provider, - providerInstanceId: bindingInstanceId, - ...(persistedCwd ? { cwd: persistedCwd } : {}), - ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}), - ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}), - ...(readPersistedRoomToolsRequest(input.binding.runtimePayload) - ? { roomTools: true } - : {}), - ...(readPersistedGuideToolsRequest(input.binding.runtimePayload) - ? { guideTools: true } - : {}), - runtimeMode: input.binding.runtimeMode ?? "full-access", - }); + const resumed = yield* adapter.startSession( + yield* withProjectInstructions({ + threadId: input.binding.threadId, + provider: input.binding.provider, + providerInstanceId: bindingInstanceId, + ...(persistedCwd ? { cwd: persistedCwd } : {}), + ...(persistedModelSelection ? { modelSelection: persistedModelSelection } : {}), + ...(hasResumeCursor ? { resumeCursor: input.binding.resumeCursor } : {}), + ...(readPersistedRoomToolsRequest(input.binding.runtimePayload) + ? { roomTools: true } + : {}), + ...(readPersistedGuideToolsRequest(input.binding.runtimePayload) + ? { guideTools: true } + : {}), + runtimeMode: input.binding.runtimeMode ?? "full-access", + }), + ); if (resumed.provider !== adapter.provider) { return yield* toValidationError( input.operation, @@ -1050,15 +1070,17 @@ const makeProviderService = Effect.fn("makeProviderService")(function* ( const adapter = yield* registry.getByInstance(resolvedInstanceId); const startBeganAtMs = yield* Clock.currentTimeMillis; const startBeganNanos = yield* Clock.monotonicTimeNanos; - const session = yield* adapter.startSession({ - ...input, - providerInstanceId: resolvedInstanceId, - ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}), - ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), - // An early start reopens the conversation or fails: starting it fresh - // instead is left to the ordinary start, which tells the thread. - ...(early ? { resumePolicy: "required" as const } : {}), - }); + const session = yield* adapter.startSession( + yield* withProjectInstructions({ + ...input, + providerInstanceId: resolvedInstanceId, + ...(effectiveCwd !== undefined ? { cwd: effectiveCwd } : {}), + ...(effectiveResumeCursor !== undefined ? { resumeCursor: effectiveResumeCursor } : {}), + // An early start reopens the conversation or fails: starting it fresh + // instead is left to the ordinary start, which tells the thread. + ...(early ? { resumePolicy: "required" as const } : {}), + }), + ); if (session.provider !== adapter.provider) { return yield* toValidationError( diff --git a/apps/server/src/provider/acp/AcpAdapter.test.ts b/apps/server/src/provider/acp/AcpAdapter.test.ts index 9d16d2946..9b81a6e06 100644 --- a/apps/server/src/provider/acp/AcpAdapter.test.ts +++ b/apps/server/src/provider/acp/AcpAdapter.test.ts @@ -29,6 +29,7 @@ import { import { ServerConfig } from "../../config.ts"; import { ServerSettingsService } from "../../serverSettings.ts"; import { isProcessRunning } from "../testAgentProcess.ts"; +import { PROJECT_BRIEF_CLEARED_NOTE } from "../projectBriefPreface.ts"; import type { UsageLedgerEntry } from "../../usage/usageLedger.ts"; import { type AcpAdapterShape, acpDiffFileChanges, makeAcpAdapter } from "./AcpAdapter.ts"; import { discoverAcpModels } from "./AcpProvider.ts"; @@ -1794,6 +1795,77 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { }), ); + it.effect( + "sends the project's brief ahead of a new session's first prompt, and on a resume only when it changed", + () => + Effect.gen(function* () { + const adapter = yield* CursorAdapter; + const serverSettings = yield* ServerSettingsService; + const threadId = ThreadId.make("cursor-project-brief"); + const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-"))); + const requestLogPath = path.join(tempDir, "requests.ndjson"); + yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8")); + const wrapperPath = yield* Effect.promise(() => + makeProbeWrapper(requestLogPath, path.join(tempDir, "argv.txt")), + ); + yield* serverSettings.updateSettings({ + providers: { cursor: { binaryPath: wrapperPath } }, + }); + const brief = "Use pnpm here. Never touch the generated folder."; + + /** One runtime start and its first turn; returns what that prompt said and the cursor after it. */ + const firstTurn = (input: { + readonly projectInstructions?: string; + readonly resumeCursor?: unknown; + }) => + Effect.gen(function* () { + yield* adapter.startSession({ + threadId, + provider: ProviderDriverKind.make("cursor"), + cwd: process.cwd(), + runtimeMode: "full-access", + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, + ...input, + }); + const completed = yield* adapter.streamEvents.pipe( + Stream.takeUntil((event) => event.type === "turn.completed"), + Stream.runDrain, + Effect.forkChild, + ); + yield* adapter.sendTurn({ threadId, input: "hello mock", attachments: [] }); + yield* Fiber.join(completed); + const cursor = (yield* adapter.listSessions()).find( + (session) => session.threadId === threadId, + )?.resumeCursor; + yield* adapter.stopSession(threadId); + const prompts = (yield* Effect.promise(() => readJsonLines(requestLogPath))).filter( + (entry) => entry.method === "session/prompt", + ); + const parts = (prompts.at(-1)!.params as { prompt: Array<{ text?: string }> }).prompt; + return { text: parts.map((part) => part.text ?? "").join(""), cursor }; + }); + + const fresh = yield* firstTurn({ projectInstructions: brief }); + assert.equal(fresh.text, `${brief}\n\nhello mock`); + + const same = yield* firstTurn({ projectInstructions: brief, resumeCursor: fresh.cursor }); + assert.equal(same.text, "hello mock"); + + const changed = yield* firstTurn({ + projectInstructions: `${brief} Tests run with vp.`, + resumeCursor: same.cursor, + }); + assert.equal(changed.text, `${brief} Tests run with vp.\n\nhello mock`); + + const cleared = yield* firstTurn({ resumeCursor: changed.cursor }); + assert.equal(cleared.text, `${PROJECT_BRIEF_CLEARED_NOTE}\n\nhello mock`); + + // The note is said once. + const after = yield* firstTurn({ resumeCursor: cleared.cursor }); + assert.equal(after.text, "hello mock"); + }), + ); + it.effect( "applies fast mode on the first turn when modelSelection uses a non-default instance id", () => { diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index 144fda25f..6c45f7a7e 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -27,6 +27,11 @@ import { } from "@threadlines/contracts"; import { withFailureCategory } from "../providerFailureCategory.ts"; import { makeAgentProcessLedger } from "../agentProcessLedger.ts"; +import { + type ProjectBriefPreface, + projectBriefPreface, + readProjectBriefHash, +} from "../projectBriefPreface.ts"; import { isProviderPlanGateMessage, isProviderPlanGateReply, @@ -227,6 +232,10 @@ interface AcpSessionContext { planMarkdown: string | undefined; /** Earlier conversation for an agent that starts without it, sent with the first turn. */ pendingContextPreamble: string | undefined; + /** The project's brief for the next turn, and the hash the conversation then holds (projectBriefPreface). */ + projectBrief: ProjectBriefPreface; + /** The brief's hash this conversation holds, kept in the resume cursor. */ + projectBriefHash: string | undefined; /** Held while a turn starts, so concurrent sends queue instead of racing. */ readonly turnStartLock: Semaphore.Semaphore; /** The active turn is one the agent started itself; settled when it ends. */ @@ -335,6 +344,7 @@ export function parseAcpResumeCursor(raw: unknown): sessionId: string; history: ReadonlyArray<AcpHistoryEntry>; newestPosition: number | undefined; + projectBriefHash: string | undefined; } | undefined { if (!isRecord(raw)) return undefined; @@ -349,6 +359,7 @@ export function parseAcpResumeCursor(raw: unknown): history, newestPosition: typeof newest === "number" && Number.isInteger(newest) && newest >= 0 ? newest : undefined, + projectBriefHash: readProjectBriefHash(raw), }; } @@ -356,6 +367,7 @@ function makeAcpResumeCursor( sessionId: string, history: ReadonlyArray<AcpHistoryEntry>, newestPosition: number | undefined, + projectBriefHash: string | undefined, ) { return { schemaVersion: ACP_RESUME_VERSION, @@ -364,6 +376,7 @@ function makeAcpResumeCursor( ? { history: history.slice(-ACP_HISTORY_CURSOR_LIMIT).map((entry) => ({ ...entry })) } : {}), ...(newestPosition !== undefined ? { newestPosition } : {}), + ...(projectBriefHash !== undefined ? { projectBriefHash } : {}), }; } @@ -598,7 +611,12 @@ export function makeAcpAdapter<Settings extends AcpProviderSettings>( if (sessionId === undefined) return; ctx.session = { ...ctx.session, - resumeCursor: makeAcpResumeCursor(sessionId, ctx.history, ctx.newestPosition), + resumeCursor: makeAcpResumeCursor( + sessionId, + ctx.history, + ctx.newestPosition, + ctx.projectBriefHash, + ), }; historyBySession.set(sessionId, { history: ctx.history.map((entry) => ({ ...entry })), @@ -1686,6 +1704,17 @@ export function makeAcpAdapter<Settings extends AcpProviderSettings>( started.resumeFailure === undefined; const history = keepsHistory ? resumed.history.map((entry) => ({ ...entry })) : []; const resumedNewestPosition = keepsHistory ? resumed.newestPosition : forkNewest; + // The brief is sent again whenever it changed. Only the thread's + // own resumed conversation is known to hold one; a side answer + // never gets it. + const projectBriefHash = keepsHistory ? resumed.projectBriefHash : undefined; + const projectBrief = + lockdown === undefined + ? projectBriefPreface({ + projectInstructions: input.projectInstructions, + sentHash: projectBriefHash, + }) + : { text: undefined, hash: projectBriefHash }; const now = yield* nowIso; // ACP passes an HTTP server only to an agent that says it speaks // HTTP MCP (see supportedMcpServers); without that, it has no room @@ -1701,7 +1730,12 @@ export function makeAcpAdapter<Settings extends AcpProviderSettings>( cwd, model: boundModelSelection?.model, threadId: input.threadId, - resumeCursor: makeAcpResumeCursor(started.sessionId, history, resumedNewestPosition), + resumeCursor: makeAcpResumeCursor( + started.sessionId, + history, + resumedNewestPosition, + projectBriefHash, + ), ...(roomToolsRequested ? { roomTools: roomToolsAttached } : {}), ...(started.resumeFailure !== undefined ? { resumeFailed: true } : {}), createdAt: now, @@ -1745,6 +1779,8 @@ export function makeAcpAdapter<Settings extends AcpProviderSettings>( input.contextSeed !== undefined && resumeSessionId === undefined ? renderThreadContextSeed(input.contextSeed) : undefined, + projectBrief, + projectBriefHash, turnStartLock: yield* Semaphore.make(1), agentTurn: undefined, agentTurnLastActivityMs: 0, @@ -2074,11 +2110,19 @@ export function makeAcpAdapter<Settings extends AcpProviderSettings>( const planMode = input.interactionMode === "plan" && !lockedDown ? descriptor.planMode : undefined; const contextPreamble = ctx.pendingContextPreamble; + const projectBrief = ctx.projectBrief; const userText = input.input?.trim() ?? ""; - const seededText = + const contextText = contextPreamble !== undefined ? withContextSeedPreamble(contextPreamble, userText) : userText; + // The project's brief leads, as a paragraph of its own. + const seededText = + projectBrief.text !== undefined + ? contextText.length > 0 + ? `${projectBrief.text}\n\n${contextText}` + : projectBrief.text + : contextText; const promptParts = yield* promptContent( seededText.length > 0 || planMode ? planMode @@ -2128,6 +2172,10 @@ export function makeAcpAdapter<Settings extends AcpProviderSettings>( ctx.openPrompt = prompt; resetTurnState(ctx); ctx.pendingContextPreamble = undefined; + if (projectBrief.text !== undefined) { + ctx.projectBrief = { text: undefined, hash: projectBrief.hash }; + ctx.projectBriefHash = projectBrief.hash; + } ctx.session = { ...ctx.session, activeTurnId: turnId, updatedAt: yield* nowIso }; ctx.history.push({ turnId, diff --git a/apps/server/src/provider/projectBriefPreface.ts b/apps/server/src/provider/projectBriefPreface.ts new file mode 100644 index 000000000..07ccc0e71 --- /dev/null +++ b/apps/server/src/provider/projectBriefPreface.ts @@ -0,0 +1,50 @@ +/** + * For providers whose project brief sits in the conversation rather than in + * standing instructions (Muse and the ACP agents; docs/design/ + * project-brief-notes.md, "Per provider"): what the first turn after a + * runtime start sends ahead of the user's words. The hash of the brief the + * conversation last got is kept in the session's resume cursor, so a thread + * that restarts often gets a copy only when the brief changed. A wrong hash + * costs one extra or one missing copy until the next change. + */ +import { createHash } from "node:crypto"; + +/** Sent when the brief the conversation holds was cleared. */ +export const PROJECT_BRIEF_CLEARED_NOTE = + "The user removed this project's brief. The project brief given earlier in this conversation no longer applies."; + +export const projectBriefHash = (text: string): string => + createHash("sha256").update(text).digest("hex").slice(0, 16); + +export interface ProjectBriefPreface { + /** Text to send ahead of the next prompt; undefined: nothing to send. */ + readonly text: string | undefined; + /** The hash the conversation holds once it is sent; undefined: no brief. */ + readonly hash: string | undefined; +} + +/** + * `projectInstructions` is the session's start input + * (ProviderSessionStartInput.projectInstructions); `sentHash` the hash a + * resumed conversation already holds, undefined for a new or forked one. + */ +export function projectBriefPreface(input: { + readonly projectInstructions: string | undefined; + readonly sentHash: string | undefined; +}): ProjectBriefPreface { + if (input.projectInstructions === undefined || input.projectInstructions.length === 0) { + return { + text: input.sentHash !== undefined ? PROJECT_BRIEF_CLEARED_NOTE : undefined, + hash: undefined, + }; + } + const hash = projectBriefHash(input.projectInstructions); + return { text: hash === input.sentHash ? undefined : input.projectInstructions, hash }; +} + +/** The hash a resume cursor keeps under `projectBriefHash`, if any. */ +export const readProjectBriefHash = (cursor: unknown): string | undefined => { + if (typeof cursor !== "object" || cursor === null) return undefined; + const value = (cursor as { readonly projectBriefHash?: unknown }).projectBriefHash; + return typeof value === "string" && value.length > 0 ? value : undefined; +}; diff --git a/apps/web/src/components/chat/LeadChatHints.tsx b/apps/web/src/components/chat/LeadChatHints.tsx index 22e86751a..4d86ee515 100644 --- a/apps/web/src/components/chat/LeadChatHints.tsx +++ b/apps/web/src/components/chat/LeadChatHints.tsx @@ -88,7 +88,7 @@ export function LeadChatCard({ ); }} > - Brief and notes + Project brief </button> ) : null} <button diff --git a/apps/web/src/projectBrief.ts b/apps/web/src/projectBrief.ts index bb3582386..2f69b7aa5 100644 --- a/apps/web/src/projectBrief.ts +++ b/apps/web/src/projectBrief.ts @@ -29,7 +29,7 @@ import { export const PROJECT_BRIEF_PLACE: PlaceId = "instructions.brief"; /** What the project menu, the palette and the lead's card call the way in. */ -export const PROJECT_BRIEF_MENU_LABEL = "Project brief and notes"; +export const PROJECT_BRIEF_MENU_LABEL = "Project brief"; /** From here up, the page shows how many characters the brief has. */ export const PROJECT_BRIEF_COUNT_FROM = Math.round(PROJECT_BRIEF_MAX_CHARS * 0.9); diff --git a/docs/design/project-brief-notes.md b/docs/design/project-brief-notes.md index 3529c28cf..859b594a7 100644 --- a/docs/design/project-brief-notes.md +++ b/docs/design/project-brief-notes.md @@ -165,14 +165,14 @@ fixed order (oldest first), so the text changes only when a note does. ### Per provider -| Provider | Where it goes | Survives a compaction | -| ---------- | ------------------------------------------------------------------------------------------ | ------------------------ | -| Claude | after Threadlines' own text in `systemPrompt.append` | yes | -| Codex | the thread's own developer instructions, set when the thread is started, resumed or forked | yes | -| OpenCode | the `threadlines` instructions entry | yes | -| Pi | the instructions file passed at launch | yes | -| Muse | a preface on the first turn after a runtime start | no, it is in the history | -| ACP agents | ahead of the first prompt after a session start, in the generic core | no | +| Provider | Where it goes | Survives a compaction | +| ---------- | ------------------------------------------------------------------------------------ | ------------------------ | +| Claude | after Threadlines' own text in `systemPrompt.append` | yes | +| Codex | the thread's developer instructions at start and fork; a resume adds a changed brief | yes | +| OpenCode | the `threadlines` instructions entry | yes | +| Pi | the instructions file passed at launch | yes | +| Muse | a preface on the first turn after a runtime start | no, it is in the history | +| ACP agents | ahead of the first prompt after a session start, in the generic core | no | - **One service builds the text, and `ProviderService` asks it.** The lookup sits where an adapter session is started, inside `ProviderService.startSession` and the recovery @@ -182,10 +182,15 @@ fixed order (oldest first), so the text changes only when a note does. - **Codex.** `developer_instructions` in the collaboration mode goes out with `turn/start` only, and not at all without an interaction mode (`CodexSessionRuntime.ts` ~703), and a goal's cold start calls `thread/goal/set` - with no turn. So the text is set on the thread itself, at `thread/start`, - `thread/resume` and `thread/fork`. If the 0.169 bindings carry no such field, - `thread/inject_items` before the first turn or goal does it, as #992 does for the - lead's role. + with no turn. So the text is set on the thread itself, as `developerInstructions` at + `thread/start`, `thread/resume` and `thread/fork`, after the user's own + `developer_instructions` from `config/read` (the thread's value replaces the + config's; when the config can't be read the brief is left out). Codex writes those + instructions into the conversation only when it creates a thread: a resume takes + the new value as a setting (used when a compaction rebuilds the context) but the + model keeps seeing the old text. So a resume whose brief changed also adds it with + `thread/inject_items`, under the same hash rule as Muse and ACP below, as #992 does + for the lead's role. Checked live on Codex 0.170. - **Muse and ACP, where the text sits in the history.** Their existing first-turn paths skip a resumed or forked session (`MuseAdapter.ts` ~2345), which is exactly when an edit should arrive. So project text has its own pending state, set on every From 2a2544517976e30ce8d95701686b4de08ca0ed3e Mon Sep 17 00:00:00 2001 From: Badcuban <108198679+badcuban@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:03:37 -0500 Subject: [PATCH 4/4] fix: a brief save never overwrites another computer's newer brief - The brief saves on the same folder of the same repository on each computer, whatever the sidebar's grouping: grouping by repository no longer joins another project in that repository, and "Keep separate" no longer leaves the other computers out. - Each computer's revision is taken when the edit begins, so a brief saved on another computer meanwhile is refused there, not overwritten. - ACP: a prompt the agent refused, or one a revert removed, sends the brief again on the next prompt. - Codex: a revert forgets which brief the conversation holds, so the next resume adds it again rather than leaving it out. --- apps/server/scripts/acp-mock-agent.ts | 7 ++ .../provider/Layers/CodexSessionRuntime.ts | 22 +++++-- .../src/provider/acp/AcpAdapter.test.ts | 52 +++++++++++++++ apps/server/src/provider/acp/AcpAdapter.ts | 36 +++++++++++ .../settings/ProjectBriefSection.tsx | 64 ++++++++++--------- .../settings/SettingsPanels.browser.tsx | 28 ++++++++ 6 files changed, 175 insertions(+), 34 deletions(-) diff --git a/apps/server/scripts/acp-mock-agent.ts b/apps/server/scripts/acp-mock-agent.ts index e5e694220..093096e57 100644 --- a/apps/server/scripts/acp-mock-agent.ts +++ b/apps/server/scripts/acp-mock-agent.ts @@ -28,6 +28,8 @@ const failSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "1"; const authRequiredOnSetConfigOption = process.env.T3_ACP_FAIL_SET_CONFIG_OPTION === "auth"; const exitOnSetConfigOption = process.env.T3_ACP_EXIT_ON_SET_CONFIG_OPTION === "1"; const promptResponseText = process.env.T3_ACP_PROMPT_RESPONSE_TEXT; +/** Refuses the first prompt it gets, as an agent that errors before taking it does. */ +let failFirstPrompt = process.env.T3_ACP_FAIL_FIRST_PROMPT === "1"; /** Ends every prompt with this stop reason and no reply, as a refusing model does. */ const silentPromptStopReason = process.env.T3_ACP_SILENT_PROMPT_STOP_REASON; /** fx's retry notice, sent before that silent stop. */ @@ -409,6 +411,11 @@ const program = Effect.gen(function* () { Effect.gen(function* () { const requestedSessionId = String(request.sessionId ?? sessionId); + if (failFirstPrompt) { + failFirstPrompt = false; + return yield* AcpError.AcpRequestError.invalidParams("The mock agent refused this prompt."); + } + if (silentPromptStopReason) { if (silentPromptStatus) { yield* agent.client.sessionUpdate({ diff --git a/apps/server/src/provider/Layers/CodexSessionRuntime.ts b/apps/server/src/provider/Layers/CodexSessionRuntime.ts index 52bbed35e..cf86efda2 100644 --- a/apps/server/src/provider/Layers/CodexSessionRuntime.ts +++ b/apps/server/src/provider/Layers/CodexSessionRuntime.ts @@ -593,6 +593,16 @@ function readResumeCursorProjectBriefHash(resumeCursor: unknown): string | undef return isCodexResumeCursorSchema(resumeCursor) ? resumeCursor.projectBriefHash : undefined; } +/** The cursor as it was, the brief's hash left out (its other fields, a carried rollout's path, kept). */ +function withoutProjectBriefHash( + resumeCursor: unknown, + providerThreadId: string, +): CodexResumeCursor { + if (!isCodexResumeCursorSchema(resumeCursor)) return { threadId: providerThreadId }; + const { projectBriefHash: _held, ...rest } = resumeCursor; + return rest; +} + function readResumeCursorRolloutPath( resumeCursor: ProviderSession["resumeCursor"], ): string | undefined { @@ -3500,14 +3510,18 @@ const makeCodexSessionRuntimeIn = ( serviceTier: options.serviceTier, developerInstructions: threadDeveloperInstructions, }); + // A revert may take the brief a resume added along with the turns + // after it: the next resume adds it again (at worst one copy more). + projectBriefHashHeld = undefined; yield* updateSession(sessionRef, { status: "ready", activeTurnId: undefined, + resumeCursor: + replacementProviderThreadId !== undefined + ? withProjectBriefHash({ threadId: replacementProviderThreadId }) + : withoutProjectBriefHash(session.resumeCursor, providerThreadId), ...(replacementProviderThreadId !== undefined - ? { - resumeCursor: withProjectBriefHash({ threadId: replacementProviderThreadId }), - providerThreadId: replacementProviderThreadId, - } + ? { providerThreadId: replacementProviderThreadId } : {}), }); if (replacementProviderThreadId !== undefined) { diff --git a/apps/server/src/provider/acp/AcpAdapter.test.ts b/apps/server/src/provider/acp/AcpAdapter.test.ts index 9b81a6e06..946035953 100644 --- a/apps/server/src/provider/acp/AcpAdapter.test.ts +++ b/apps/server/src/provider/acp/AcpAdapter.test.ts @@ -1795,6 +1795,58 @@ cursorAdapterTestLayer("CursorAdapterLive", (it) => { }), ); + it.effect( + "sends the project's brief again when the agent refused the prompt that carried it", + () => + Effect.gen(function* () { + const adapter = yield* CursorAdapter; + const serverSettings = yield* ServerSettingsService; + const threadId = ThreadId.make("cursor-project-brief-refused"); + const tempDir = yield* Effect.promise(() => mkdtemp(path.join(os.tmpdir(), "cursor-acp-"))); + const requestLogPath = path.join(tempDir, "requests.ndjson"); + yield* Effect.promise(() => writeFile(requestLogPath, "", "utf8")); + const wrapperPath = yield* Effect.promise(() => + makeProbeWrapper(requestLogPath, path.join(tempDir, "argv.txt"), { + T3_ACP_FAIL_FIRST_PROMPT: "1", + }), + ); + yield* serverSettings.updateSettings({ + providers: { cursor: { binaryPath: wrapperPath } }, + }); + const brief = "Use pnpm here."; + yield* adapter.startSession({ + threadId, + provider: ProviderDriverKind.make("cursor"), + cwd: process.cwd(), + runtimeMode: "full-access", + modelSelection: { instanceId: ProviderInstanceId.make("cursor"), model: "default" }, + projectInstructions: brief, + }); + const turn = (text: string) => + Effect.gen(function* () { + const ended = yield* adapter.streamEvents.pipe( + Stream.takeUntil((event) => event.type === "turn.completed"), + Stream.runDrain, + Effect.forkChild, + ); + yield* adapter.sendTurn({ threadId, input: text, attachments: [] }); + yield* Fiber.join(ended); + }); + yield* turn("first try"); + yield* turn("second try"); + yield* adapter.stopSession(threadId); + + const prompts = (yield* Effect.promise(() => readJsonLines(requestLogPath))) + .filter((entry) => entry.method === "session/prompt") + .map((entry) => + (entry.params as { prompt: Array<{ text?: string }> }).prompt + .map((part) => part.text ?? "") + .join(""), + ); + assert.deepEqual(prompts, [`${brief}\n\nfirst try`, `${brief}\n\nsecond try`]); + }), + ); + it.effect( "sends the project's brief ahead of a new session's first prompt, and on a resume only when it changed", () => diff --git a/apps/server/src/provider/acp/AcpAdapter.ts b/apps/server/src/provider/acp/AcpAdapter.ts index 6c45f7a7e..d1caff225 100644 --- a/apps/server/src/provider/acp/AcpAdapter.ts +++ b/apps/server/src/provider/acp/AcpAdapter.ts @@ -236,6 +236,17 @@ interface AcpSessionContext { projectBrief: ProjectBriefPreface; /** The brief's hash this conversation holds, kept in the resume cursor. */ projectBriefHash: string | undefined; + /** + * The turn whose prompt last carried the brief, and the hash held before + * it: a prompt the agent refused, or one a revert removed, queues it again. + */ + projectBriefCarrier: + | { + readonly turnId: TurnId; + readonly preface: ProjectBriefPreface; + readonly hashBefore: string | undefined; + } + | undefined; /** Held while a turn starts, so concurrent sends queue instead of racing. */ readonly turnStartLock: Semaphore.Semaphore; /** The active turn is one the agent started itself; settled when it ends. */ @@ -605,6 +616,16 @@ export function makeAcpAdapter<Settings extends AcpProviderSettings>( const offerRuntimeEvent = (event: ProviderRuntimeEvent) => PubSub.publish(runtimeEventPubSub, event).pipe(Effect.asVoid); + /** The prompt that carried the brief is gone: the conversation holds what it held before. */ + const requeueProjectBrief = (ctx: AcpSessionContext) => { + const carrier = ctx.projectBriefCarrier; + if (carrier === undefined) return; + ctx.projectBriefCarrier = undefined; + ctx.projectBriefHash = carrier.hashBefore; + ctx.projectBrief = carrier.preface; + recordHistory(ctx); + }; + /** Saves the session's turn history in its resume cursor, and for forks of it. */ const recordHistory = (ctx: AcpSessionContext) => { const sessionId = parseAcpResumeCursor(ctx.session.resumeCursor)?.sessionId; @@ -1781,6 +1802,7 @@ export function makeAcpAdapter<Settings extends AcpProviderSettings>( : undefined, projectBrief, projectBriefHash, + projectBriefCarrier: undefined, turnStartLock: yield* Semaphore.make(1), agentTurn: undefined, agentTurnLastActivityMs: 0, @@ -2173,6 +2195,11 @@ export function makeAcpAdapter<Settings extends AcpProviderSettings>( resetTurnState(ctx); ctx.pendingContextPreamble = undefined; if (projectBrief.text !== undefined) { + ctx.projectBriefCarrier = { + turnId, + preface: projectBrief, + hashBefore: ctx.projectBriefHash, + }; ctx.projectBrief = { text: undefined, hash: projectBrief.hash }; ctx.projectBriefHash = projectBrief.hash; } @@ -2283,6 +2310,8 @@ export function makeAcpAdapter<Settings extends AcpProviderSettings>( if (Cause.hasInterruptsOnly(exit.cause)) { return; } + // The agent may never have taken the prompt: the brief goes again. + if (ctx.projectBriefCarrier?.turnId === turnId) requeueProjectBrief(ctx); const failure = Cause.squash(exit.cause); yield* notifyAuthRequired(failure); const reportedOutcome = @@ -2533,6 +2562,13 @@ export function makeAcpAdapter<Settings extends AcpProviderSettings>( ctx.history.splice(index); // The agent now lists only the prompts before this one. ctx.newestPosition = position > 0 ? position - 1 : undefined; + const carrier = ctx.projectBriefCarrier; + if ( + carrier !== undefined && + !ctx.history.some((entry) => entry.turnId === carrier.turnId) + ) { + requeueProjectBrief(ctx); + } recordHistory(ctx); } return { threadId, turns: ctx.turns, conversationRolledBack: rewound }; diff --git a/apps/web/src/components/settings/ProjectBriefSection.tsx b/apps/web/src/components/settings/ProjectBriefSection.tsx index 47d545ea6..72874c69d 100644 --- a/apps/web/src/components/settings/ProjectBriefSection.tsx +++ b/apps/web/src/components/settings/ProjectBriefSection.tsx @@ -9,15 +9,12 @@ import { type EnvironmentId, PROJECT_BRIEF_MAX_CHARS, type ProjectBrief, + type ProjectId, } from "@threadlines/contracts"; import { LoaderIcon, SaveIcon } from "lucide-react"; import { useMemo, useState } from "react"; -import { useSettings } from "../../hooks/useSettings"; -import { - deriveLogicalProjectKeyFromSettings, - selectProjectGroupingSettings, -} from "../../logicalProject"; +import { deriveLogicalProjectKey } from "../../logicalProject"; import { briefIn, type BriefSaveOutcome, @@ -36,12 +33,19 @@ import { SettingsSection } from "./settingsLayout"; const BRIEF_ABOUT = "Every thread in this project gets this, on any agent. New threads get a change at once. Open threads get it the next time their agent starts. It stays on your computers and is not written to your repository."; -/** The user's edit, and the revision on the picked computer it started from. */ +/** + * The user's edit, and the revision on each computer it started from (by + * targetKey): a save sends those, so a brief saved anywhere since the edit + * began is refused instead of overwritten. + */ interface BriefDraft { readonly text: string; - readonly baseRevision: number; + readonly baseRevisions: Readonly<Record<string, number>>; } +const targetKey = (target: { environmentId: EnvironmentId; projectId: ProjectId }) => + `${target.environmentId}\n${target.projectId}`; + /** What the line under the box says, until the next edit. */ type BriefNotice = | { readonly kind: "result"; readonly text: string } @@ -67,17 +71,15 @@ export function ProjectBriefSection({ /** A computer's name as the page shows it. */ computerLabel: (environmentId: EnvironmentId) => string; }) { - const groupingSettings = useSettings(selectProjectGroupingSettings); const supports = useProjectBriefSupport(); - // The picked copy first, then the project's copies on other computers (the - // ones the sidebar shows as the same project). + // The picked copy first, then the project's other copies: the same folder + // of the same repository, whatever the sidebar's grouping shows (grouping + // by repository would also join another project in that repository). const targets = useMemo((): readonly BriefTarget[] => { - const settings = { - sidebarProjectGroupingMode: groupingSettings.sidebarProjectGroupingMode, - sidebarProjectGroupingOverrides: groupingSettings.sidebarProjectGroupingOverrides, - }; - const logicalKey = deriveLogicalProjectKeyFromSettings(project, settings); + const sameProjectKey = (copy: Project) => + deriveLogicalProjectKey(copy, { groupingMode: "repository_path" }); + const logicalKey = sameProjectKey(project); const toTarget = (copy: Project): BriefTarget => ({ environmentId: copy.environmentId, projectId: copy.id, @@ -88,19 +90,12 @@ export function ProjectBriefSection({ .filter( (copy) => !(copy.environmentId === project.environmentId && copy.id === project.id) && - deriveLogicalProjectKeyFromSettings(copy, settings) === logicalKey, + sameProjectKey(copy) === logicalKey, ) .map(toTarget) .toSorted((left, right) => left.label.localeCompare(right.label)); return [toTarget(project), ...others]; - }, [ - computerLabel, - groupingSettings.sidebarProjectGroupingMode, - groupingSettings.sidebarProjectGroupingOverrides, - project, - projects, - supports, - ]); + }, [computerLabel, project, projects, supports]); const picked = targets[0]!; const followed = useMemo( () => @@ -121,7 +116,12 @@ export function ProjectBriefSection({ const briefOn = (target: BriefTarget): ProjectBrief | null => newer( briefIn(snapshots[target.environmentId], target.projectId), - answered[`${target.environmentId}\n${target.projectId}`] ?? null, + answered[targetKey(target)] ?? null, + ); + /** Every computer's revision now, for a draft that starts here. */ + const currentRevisions = (): Readonly<Record<string, number>> => + Object.fromEntries( + targets.map((target) => [targetKey(target), briefOn(target)?.revision ?? 0]), ); const pickedBrief = briefOn(picked); const text = draft?.text ?? pickedBrief?.text ?? ""; @@ -135,7 +135,7 @@ export function ProjectBriefSection({ outcomes.forEach((outcome, index) => { if (outcome.kind !== "saved" && outcome.kind !== "stale") return; const target = sent[index]!; - next[`${target.environmentId}\n${target.projectId}`] = outcome.brief; + next[targetKey(target)] = outcome.brief; }); return next; }); @@ -146,7 +146,7 @@ export function ProjectBriefSection({ const sending = draft.text; setSaving(true); try { - const first = await saveBriefOn(picked, sending, draft.baseRevision); + const first = await saveBriefOn(picked, sending, draft.baseRevisions[targetKey(picked)] ?? 0); remember([first], [picked]); if (first.kind === "stale") { // Theirs stays; the box shows it, and the user's text can come back. @@ -160,7 +160,11 @@ export function ProjectBriefSection({ } const others = targets.slice(1); const rest = await Promise.all( - others.map((target) => saveBriefOn(target, sending, briefOn(target)?.revision ?? 0)), + // A computer whose brief had not arrived when the edit began counts + // as revision 0: one it holds since is refused, not overwritten. + others.map((target) => + saveBriefOn(target, sending, draft.baseRevisions[targetKey(target)] ?? 0), + ), ); remember(rest, others); setDraft(null); @@ -205,7 +209,7 @@ export function ProjectBriefSection({ const next = event.currentTarget.value; setDraft((current) => ({ text: next, - baseRevision: current?.baseRevision ?? pickedBrief?.revision ?? 0, + baseRevisions: current?.baseRevisions ?? currentRevisions(), })); if (notice !== null) setNotice(null); }} @@ -253,7 +257,7 @@ export function ProjectBriefSection({ size="xs" variant="outline" onClick={() => { - setDraft({ text: notice.mine, baseRevision: pickedBrief?.revision ?? 0 }); + setDraft({ text: notice.mine, baseRevisions: currentRevisions() }); setNotice(null); }} > diff --git a/apps/web/src/components/settings/SettingsPanels.browser.tsx b/apps/web/src/components/settings/SettingsPanels.browser.tsx index 1184aef66..2ccc6a2fd 100644 --- a/apps/web/src/components/settings/SettingsPanels.browser.tsx +++ b/apps/web/src/components/settings/SettingsPanels.browser.tsx @@ -4730,6 +4730,34 @@ describe("Agent Instructions › Brief", () => { await expect.element(box).toHaveValue("My edit."); }); + it("leaves another computer's newer brief alone when it changed after the edit began", async () => { + describeComputers(true); + const mac = seedComputer(THIS_MAC, brief(THIS_MAC, "Branch from develop.", 2)); + const studio = seedComputer(STUDIO, brief(STUDIO, "Branch from develop.", 1)); + + await renderPage(); + + const box = page.getByLabelText("Project brief"); + await expect.element(box).toHaveValue("Branch from develop."); + await box.fill("My edit."); + // Someone saves on Studio directly while this page holds the edit. + studio.emit({ briefs: [brief(STUDIO, "Studio's newer rule.", 2)] }); + await page.getByRole("button", { name: "Save brief" }).click(); + + await expect + .element( + page.getByText("Not saved on Studio. Its brief changed there first.", { exact: false }), + ) + .toBeVisible(); + expect(mac.textOf(projectOn(THIS_MAC))).toBe("My edit."); + expect(studio.setBrief).toHaveBeenLastCalledWith({ + projectId: projectOn(STUDIO), + text: "My edit.", + expectedRevision: 1, + }); + expect(studio.textOf(projectOn(STUDIO))).toBe("Studio's newer rule."); + }); + it("is hidden when the project's computer keeps no briefs", async () => { describeComputers(false); seedComputer(THIS_MAC, null);