Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: expand {trackerInstructions} in the scheduled reference-watch prompt (#3140)
[._.]/ Adam Eivy9998fe37f656
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex 319588c6ff..88c8711176 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -98,6 +98,7 @@- **[issue-3110] A task that runs a bundled slashdo workflow no longer pastes the whole 250KB procedure into the agent's prompt.** Dispatching `/do:review` or `/do:better` handed the agent its fully-expanded command body — 258KB, roughly 65k tokens — on every single spawn, which on a smaller model could crowd out or overflow the context the actual work needed. Most of that bulk was never reachable: each of those commands carries all five of slashdo's reviewer loops (Copilot, arbitrary GitHub reviewer, local CLI agent, local model, and the multi-reviewer wrapper) though one run drives exactly one of them. When your reviewers are known — pinned on the task, or set in Code Review Defaults — the unreachable loops are now dropped, cutting 23% off `/do:review` (258KB down to 199KB) and 28% off `/do:depfree`; the run is given an explicit `--review-with` so it can't pick a reviewer whose procedure was left out. Whatever is still oversized is written to disk once and handed to the agent as a file path to read, instead of pasted. Nothing is pruned when the reviewer set isn't known — an over-trimmed prompt that drops the loop the agent needed would be worse than a fat one — and API providers, which have no file tools, still get the body inlined (now with a log line naming the command and its size, so the cost is visible rather than silent).- **Antigravity (agy) agents no longer die on the first-run folder-trust gate.** An agy agent launched in a fresh worktree could fail immediately with `Do you trust the contents of this project?` and a `paste-not-rendered` error, having done nothing. The spawner waits for a positive "input box is live" signal before pasting the task prompt, and for claude that signal — the terminal's bracketed-paste mode turning back on — arrives exactly when its composer appears. agy turns it on much earlier, when it enters full-screen mode, while it is still signing in and before its trust prompt has even drawn. So on any run where agy's sign-in outlasted the startup delay, the prompt was pasted into a screen that wasn't ready; the trust menu then appeared and swallowed it along with all three retries, and because the trust prompt hadn't been seen yet the auto-confirm never fired. agy now additionally waits for its composer footer, which only draws once the trust gate is resolved, so the trust prompt is confirmed first and the prompt lands in the input box. (`--dangerously-skip-permissions` does not bypass this gate, contrary to what the code previously assumed.)- Handshake markers are now matched against a rolling window of recent terminal output rather than a single read, so a prompt or footer that arrives split across two reads is still recognized.+- **[issue-3140] A scheduled reference-watch run is now told where to file its proposals.** The weekly run shipped the agent a prompt whose "Where to record proposals" section was the literal text `{trackerInstructions}` — only the on-commit trigger filled that section in — so the agent had to guess, and on an app that tracks work in GitHub/GitLab/JIRA issues it would fall back to editing PLAN.md, exactly what the instructions exist to prevent. The scheduled path now resolves the app's work tracker and injects the same block the on-commit path does, and stamps the matching "a clean worktree is success here" flag from that same resolution — so a scheduled forge-tracker run that correctly files issues and touches no code is no longer recorded as a failed run.## SongBook drumsdiff --git a/server/lib/workTracker.js b/server/lib/workTracker.jsindex 72ac4325fa..31f2f71892 100644--- a/server/lib/workTracker.js+++ b/server/lib/workTracker.js@@ -126,10 +126,12 @@ export function forgeCliForTracker(tracker) {* i.e. an agent that files a proposal there necessarily dirties the worktree.* The forge/ticket trackers (github/gitlab/jira) take their work out-of-band via* `gh`/`glab`/JIRA, so a successful run can legitimately leave a clean tree.- * Consumed by `triggerReferenceAnalysis` to stamp `worktreeChangesExpected` on- * the spawned task off the SAME resolved value that picks the prompt's- * {trackerInstructions} block, so the flag can't drift from the instructions the- * agent actually got (see agentTuiSpawning.js's idle-complete gate, #3102).+ * Consumed by BOTH reference-watch dispatch paths — `triggerReferenceAnalysis`+ * (on-commit) and `resolveReferenceWatchBlock` (the WEEKLY scheduled task) — to+ * stamp `worktreeChangesExpected` on the spawned task off the SAME resolved+ * value that picks the prompt's {trackerInstructions} block, so the flag can't+ * drift from the instructions the agent actually got (see agentTuiSpawning.js's+ * idle-complete gate, #3102/#3140).* An unknown/absent tracker is treated as file-based, matching* formatTrackerInstructions' PLAN.md fallback.*/diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 46c7686b1d..29bf8638dd 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -2075,13 +2075,23 @@ async function resolveIssueReconcileBlock(app, taskType, metadata, taskSchedule)/*** reference-watch: dynamically build {referenceData} — a Markdown chunk per ref- * configured on the app + commits since lastReviewedSha. The check persists- * status/lastError so a bad URL surfaces in the UI even when dispatch is skipped.+ * configured on the app + commits since lastReviewedSha — AND the+ * {trackerInstructions} block naming where the agent files its proposals. The+ * check persists status/lastError so a bad URL surfaces in the UI even when+ * dispatch is skipped.+ ** Returns `{ skip }` when no ref produced reviewable commits, else- * `{ skip: false, block }`. Empty block for every non-reference-watch type.+ * `{ skip: false, block, trackerInstructions, workTracker }`. Empty+ * block/instructions (and a null tracker) for every non-reference-watch type.+ *+ * The tracker resolution mirrors `triggerReferenceAnalysis` (the on-commit+ * trigger path) rather than restating its block table: both paths run+ * `resolveAppWorkTracker` → `formatTrackerInstructions` / `isFileTracker`, so+ * the prompt the agent gets and the `worktreeChangesExpected` flag stamped on+ * its task can never disagree (#3140, #3102).*/async function resolveReferenceWatchBlock(app, taskType) {- if (taskType !== 'reference-watch') return { skip: false, block: '' };+ if (taskType !== 'reference-watch') return { skip: false, block: '', trackerInstructions: '', workTracker: null };const refs = Array.isArray(app.referenceRepos) ? app.referenceRepos : [];if (refs.length === 0) {emitLog('info', `Skipping reference-watch for ${app.name}: no reference repos configured`, { appId: app.id });@@ -2109,7 +2119,19 @@ async function resolveReferenceWatchBlock(app, taskType) {emitLog('info', `Skipping reference-watch for ${app.name}: no refs produced reviewable commits`, { appId: app.id });return { skip: true };}- return { skip: false, block: blocks.join('\n\n---\n\n') };+ // Where THIS app records autonomous work (PLAN.md / GitHub / GitLab / JIRA).+ // Never throws — degrades to the PLAN.md block, same as the on-commit path.+ const { resolveAppWorkTracker, isFileTracker } = await import('../lib/workTracker.js');+ const workTracker = await resolveAppWorkTracker(app).catch(() => ({ resolved: 'plan' }));+ return {+ skip: false,+ block: blocks.join('\n\n---\n\n'),+ trackerInstructions: referenceRepos.formatTrackerInstructions(workTracker.resolved),+ workTracker: workTracker.resolved,+ // Derived here (not at the call site) so the flag and the instructions come+ // off the same resolved value in one place.+ worktreeChangesExpected: isFileTracker(workTracker.resolved),+ };}/**@@ -2218,6 +2240,10 @@ async function buildImprovementTaskDescription({ promptTemplate, app, promptTaskconst swarmBlock = resolveSwarmBlock(promptTaskType, metadata.swarmCount);return `${swarmBlock}${promptTemplate}`+ // {trackerInstructions} FIRST — the injected block itself carries+ // {appName}/{repoPath} placeholders that the replacers below expand. This+ // ordering is load-bearing (mirrors triggerReferenceAnalysis).+ .replace(/\{trackerInstructions\}/g, () => blocks.trackerInstructions).replace(/\{appName\}/g, app.name).replace(/\{repoPath\}/g, app.repoPath).replace(/\{appId\}/g, app.id)@@ -2337,10 +2363,24 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, st: await getTaskPrompt(promptKeyForBody));// reference-watch: dynamically inject {referenceData} — a Markdown chunk- // describing each ref configured on the app + commits since lastReviewedSha.+ // describing each ref configured on the app + commits since lastReviewedSha —+ // plus the {trackerInstructions} block for the app's resolved work tracker.const referenceWatch = await resolveReferenceWatchBlock(app, taskType);if (referenceWatch.skip) return null;const referenceDataBlock = referenceWatch.block;+ if (referenceWatch.workTracker) {+ // Traceability + the TUI idle-complete gate, derived from the SAME resolved+ // tracker that selected the {trackerInstructions} block above so the flag+ // can't drift from the instructions the agent actually got: the PLAN.md path+ // commits checklist items (dirty tree), while github/gitlab/jira file+ // issues/tickets and leave the tree CLEAN. Without this a scheduled+ // forge-tracker run is recorded as an `idle-no-changes` failure (#3102).+ metadata.workTracker = referenceWatch.workTracker;+ // Stamped unconditionally — a schedule/per-app `worktreeChangesExpected`+ // override would let the flag disagree with the instructions the agent+ // actually got, which is the exact drift this derivation exists to prevent.+ metadata.worktreeChangesExpected = referenceWatch.worktreeChangesExpected;+ }// pr-watcher: poll the app's GitHub repo for PRs newly opened against the// default branch; injects {prData}/{repoFullName}/{defaultBranch}.@@ -2364,6 +2404,7 @@ export async function generateManagedAppImprovementTaskForType(taskType, app, stpromptTemplate, app, promptTaskType, metadata,blocks: {referenceData: referenceDataBlock,+ trackerInstructions: referenceWatch.trackerInstructions,prData: prDataBlock,inFlightBranches: inFlightBranchesBlock,zombieIssues: zombieIssuesBlock,diff --git a/server/services/cosTaskGenerator.referenceWatch.test.js b/server/services/cosTaskGenerator.referenceWatch.test.jsnew file mode 100644index 0000000000..8abe517142--- /dev/null+++ b/server/services/cosTaskGenerator.referenceWatch.test.js@@ -0,0 +1,183 @@+/**+ * Scheduled `reference-watch` prompt assembly (#3140).+ *+ * `reference-watch` reaches an agent by two paths: the on-commit trigger+ * (`triggerReferenceAnalysis` in referenceRepos.js) and the WEEKLY scheduled+ * task (`generateManagedAppImprovementTaskForType` here). Only the former used+ * to expand the v3 prompt's `{trackerInstructions}` block, so every scheduled+ * run shipped the literal string `{trackerInstructions}` under "## Where to+ * record proposals" — leaving the agent to guess where to file, and on a+ * forge-tracker app defaulting back to the PLAN.md edit the v3 prompt exists to+ * stop. The same resolved tracker also feeds `worktreeChangesExpected`, so a+ * scheduled forge-tracker run kept hitting the `idle-no-changes` failure #3102+ * fixed for the on-commit path only.+ *+ * Isolated file so the mocked leaf graph (taskSchedule / taskPromptService /+ * appActivity) can't leak into the shared cosTaskGenerator suite.+ */++import { describe, it, expect, beforeEach, vi } from 'vitest';++// A stand-in for the shipped reference-watch template: the tokens whose+// ORDERING matters ({trackerInstructions} must expand before {appName}/+// {repoPath}, because the injected block carries those placeholders itself).+const REFERENCE_WATCH_TEMPLATE = [+ '# Reference watch for {appName}',+ '',+ 'Repository: {repoPath}',+ '',+ '## References',+ '',+ '{referenceData}',+ '',+ '## Where to record proposals',+ '',+ '{trackerInstructions}',+].join('\n');++vi.mock('./taskPromptService.js', () => ({+ getTaskPrompt: vi.fn(async () => REFERENCE_WATCH_TEMPLATE),+ getStagePrompt: vi.fn(async () => REFERENCE_WATCH_TEMPLATE),+}));++vi.mock('./taskSchedule.js', () => ({+ INTERVAL_TYPES: { PERPETUAL: 'perpetual', WEEKLY: 'weekly' },+ getTaskInterval: vi.fn(async () => ({ type: 'weekly', taskMetadata: { readOnly: false } })),+ stripManagedAgentOptionsFromOverride: vi.fn((_type, meta) => meta),+ recordExecution: vi.fn(async () => {}),+ clearPerpetualPark: vi.fn(async () => {}),+ parkPerpetual: vi.fn(async () => {}),+ getPerpetualSignature: vi.fn(async () => null),+ setPerpetualSignature: vi.fn(async () => {}),+}));++vi.mock('./appActivity.js', async (importActual) => ({+ ...(await importActual()),+ updateAppActivity: vi.fn(async () => {}),+}));++vi.mock('./apps.js', async (importActual) => ({+ ...(await importActual()),+ getAppTaskTypeOverrides: vi.fn(async () => ({})),+}));++vi.mock('./codeReview.js', async (importActual) => ({+ ...(await importActual()),+ getCodeReviewDefaults: vi.fn(async () => ({ reviewers: ['codex'], usernames: [], optionalReviewers: [] })),+}));++vi.mock('./taskLearning.js', async (importActual) => ({+ ...(await importActual()),+ getTaskTypeConfidence: vi.fn(async () => ({ autoApprove: true, tier: 'high', reason: 'test' })),+}));++// The tracker table + formatTrackerInstructions stay REAL (the point of the fix+// is that both paths share them) — only the network/disk-touching ref check is+// stubbed.+const checkReferenceRepoMock = vi.fn();+vi.mock('./referenceRepos.js', async (importActual) => ({+ ...(await importActual()),+ checkReferenceRepo: vi.fn((...args) => checkReferenceRepoMock(...args)),+}));++// workTracker.resolveAppWorkTracker stays real; only its `git remote get-url`+// probe is stubbed so an unconfigured app deterministically falls back to PLAN.md+// instead of shelling out against the fixture repoPath.+vi.mock('../lib/gitRemote.js', async (importActual) => ({+ ...(await importActual()),+ readOriginRemoteUrl: vi.fn(async () => null),+}));++import { generateManagedAppImprovementTaskForType } from './cosTaskGenerator.js';++const SNAPSHOT = {+ head: 'a'.repeat(40),+ headShort: 'aaaaaaaa',+ commitCount: 2,+ commits: [{ sha: 'b'.repeat(40), subject: 'add widget cache', author: 'Alice', date: '2026-07-01T00:00:00Z' }],+ cwd: '/tmp/example-clone',+ branch: 'main',+};++const makeApp = (overrides = {}) => ({+ id: 'app-1',+ name: 'Example App',+ repoPath: '/tmp/example-repo',+ referenceRepos: [{ id: 'ref-1', name: 'example-upstream', repoUrl: 'https://example.com/x/y.git', branch: 'main' }],+ ...overrides,+});++const STATE = { config: { confidenceAutoApproval: { enabled: false }, idleReviewPriority: 'MEDIUM' } };++const generate = (app, taskType = 'reference-watch') =>+ generateManagedAppImprovementTaskForType(taskType, app, STATE, { skipPreconditions: true });++describe('scheduled reference-watch prompt assembly (#3140)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ checkReferenceRepoMock.mockResolvedValue(SNAPSHOT);+ });++ it('expands {trackerInstructions} — no literal token survives into the prompt', async () => {+ const task = await generate(makeApp());+ expect(task).not.toBeNull();+ expect(task.description).not.toContain('{trackerInstructions}');+ // Unconfigured tracker + no resolvable origin → PLAN.md block.+ expect(task.description).toContain('PLAN.md');+ expect(task.metadata.workTracker).toBe('plan');+ // The PLAN.md path COMMITS checklist items, so the idle-complete gate stays armed.+ expect(task.metadata.worktreeChangesExpected).toBe(true);+ });++ it('injects the github block AND expands the {appName}/{repoPath} placeholders inside it', async () => {+ const app = makeApp({ workTracker: 'github' });+ const task = await generate(app);+ expect(task.description).not.toContain('{trackerInstructions}');+ expect(task.description).toContain('gh issue create');+ expect(task.description).toContain('GitHub Issues');+ // Ordering guard: the injected block's own placeholders must be expanded by+ // the {appName}/{repoPath} replacers that run AFTER the injection.+ expect(task.description).not.toContain('{appName}');+ expect(task.description).not.toContain('{repoPath}');+ expect(task.description).toContain(app.name);+ expect(task.description).toContain(app.repoPath);+ });++ it.each([+ ['github', false],+ ['gitlab', false],+ ['jira', false],+ ['plan', true],+ ])('stamps workTracker + worktreeChangesExpected off the same resolved tracker (%s → %s)', async (tracker, expected) => {+ const task = await generate(makeApp({ workTracker: tracker }));+ expect(task.metadata.workTracker).toBe(tracker);+ expect(task.metadata.worktreeChangesExpected).toBe(expected);+ });++ it('overrides a stale taskMetadata worktreeChangesExpected — the resolved tracker wins', async () => {+ // The flag must never disagree with the {trackerInstructions} block the+ // agent received, so the derivation beats a schedule/per-app override.+ const taskSchedule = await import('./taskSchedule.js');+ taskSchedule.getTaskInterval.mockResolvedValueOnce({+ type: 'weekly', taskMetadata: { readOnly: false, worktreeChangesExpected: true },+ });+ const task = await generate(makeApp({ workTracker: 'github' }));+ expect(task.metadata.workTracker).toBe('github');+ expect(task.metadata.worktreeChangesExpected).toBe(false);+ });++ it('leaves a non-reference-watch type untouched — no tracker resolution, no metadata stamp', async () => {+ const { readOriginRemoteUrl } = await import('../lib/gitRemote.js');+ const task = await generate(makeApp(), 'code-review');+ expect(task).not.toBeNull();+ expect(task.metadata.workTracker).toBeUndefined();+ expect(task.metadata.worktreeChangesExpected).toBeUndefined();+ expect(checkReferenceRepoMock).not.toHaveBeenCalled();+ expect(readOriginRemoteUrl).not.toHaveBeenCalled();+ });++ it('still skips dispatch when no ref produced reviewable commits', async () => {+ checkReferenceRepoMock.mockResolvedValue({ ...SNAPSHOT, commitCount: 0, commits: [] });+ expect(await generate(makeApp())).toBeNull();+ });+});diff --git a/server/services/referenceRepos.js b/server/services/referenceRepos.jsindex 4fcd441014..1b3d36236f 100644--- a/server/services/referenceRepos.js+++ b/server/services/referenceRepos.js@@ -12,7 +12,10 @@* tracker — PLAN.md, GitHub Issues, GitLab Issues, or JIRA (resolved via* `resolveAppWorkTracker`) — which `/claim` / `plan-task` / `claim-issue*`* picks up later. The destination-specific guidance is injected into the- * prompt's `{trackerInstructions}` block by `triggerReferenceAnalysis`.+ * prompt's `{trackerInstructions}` block by BOTH dispatch paths —+ * `triggerReferenceAnalysis` here (the on-commit trigger) and+ * `resolveReferenceWatchBlock` in cosTaskGenerator.js (the WEEKLY scheduled+ * task) — via the shared `formatTrackerInstructions` below (#3140).** Storage: refs live inline on each app in data/apps.json under the* `referenceRepos` array — fits the existing per-app config model and@@ -579,8 +582,9 @@ export function formatReferenceForPrompt(ref, snapshot) {// PLAN.md: it injects the block matching the app's RESOLVED work tracker, so an// app configured for GitHub issues gets `gh issue create` proposals instead of// a PLAN.md checklist. The blocks carry {appName}/{repoPath} placeholders that-// the shared replace chain in triggerReferenceAnalysis expands (it substitutes-// {trackerInstructions} FIRST so these inner placeholders are filled too).+// each dispatch path's replace chain expands — both triggerReferenceAnalysis+// (below) and buildImprovementTaskDescription (cosTaskGenerator.js) substitute+// {trackerInstructions} FIRST so these inner placeholders are filled too.const TRACKER_INSTRUCTIONS = {plan: `This app records autonomous work in **PLAN.md** at the repo root ({repoPath}).