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
feat: reference-watch files proposals into the app's configured task tracker, not just PLAN.md
[._.]/ Adam Eivyc3175d8539cc
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex e27e124f23..9b2d16a798 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -20,6 +20,7 @@## Chief of Staff+- **Reference-repo watches now file proposals into the app's configured task tracker — not just PLAN.md.** The weekly `reference-watch` task always appended its adoption-worthy `[ref-watch-…]` proposals to PLAN.md, even for an app configured to track work in GitHub (or GitLab/JIRA) issues — so the proposals landed where nothing would pick them up. The task now resolves each app's work tracker (`resolveAppWorkTracker`) and injects tracker-specific recording instructions into the prompt: PLAN.md apps get committed checklist items as before, GitHub/GitLab apps get a labeled `reference-watch` issue per proposal (`gh`/`glab issue create`), and JIRA apps get a ticket (falling back to PLAN.md when no JIRA credentials are present). The References tab note now states the real destination for the current app instead of hardcoding "PLAN.md". Prompt bumped to v3 with the prior default preserved for cross-install auto-upgrade. (`server/services/referenceRepos.js`, `server/services/taskPromptDefaults/prompts.js`, `server/services/taskPromptDefaults/versions.js`, `server/services/taskPromptDefaults/previousDefaults.js`, `client/src/components/apps/ReferenceReposPanel.jsx`)- **[issue-1683] CoS daily action-budget can no longer overshoot by one at the boundary.** `completeAgent()` emitted `agent:completed` — whose handler schedules `dequeueNextTask()` and its daily action-budget gate — *before* recording the just-finished action via `recordDomainUsage('cos', …)`. At the exact `maxActionsPerDay` boundary the dequeue read stale usage that didn't yet include the completing action (which was already `status: 'completed'`, so it wasn't counted as in-flight either), admitting one autonomous spawn past the cap. The usage ledger is now written before the `agent:completed` emit so the gate always counts the completing action. (`server/services/cosAgents.js`)- **[issue-1650] A task a federated peer is already working can no longer starve this machine's queue.** Now that peer claims/leases are visible via task-list federation (#1712), both spawn engines skip a task whose live lease belongs to *another* instance **during candidate selection** — before they emit `task:ready` and consume a spawn slot. Previously such a task (often the highest-priority pick) was selected each cycle, the lifecycle spawn guard then refused it (spawning nothing), and that wasted slot starved the next unclaimed task. The skip now runs in `dequeueNextTask` (cos.js) and `evaluateTasks` (cosTaskGenerator.js), across their user-task and auto-approved tiers and their dry-run plan, using the shared `isHeldByOther(task.metadata, instanceId)` predicate. This closes the last open acceptance criterion of #1650 (the dequeue-time peer-claim skip from the #1563 review). (`server/services/cos.js`, `server/services/cosTaskGenerator.js`)diff --git a/client/src/components/apps/ReferenceReposPanel.jsx b/client/src/components/apps/ReferenceReposPanel.jsxindex eb1aa20e89..2f5cf69606 100644--- a/client/src/components/apps/ReferenceReposPanel.jsx+++ b/client/src/components/apps/ReferenceReposPanel.jsx@@ -3,6 +3,25 @@ import { GitBranch, Plus, RefreshCw, Trash2, CheckCircle, AlertCircle, Edit3, Ximport toast from '../ui/Toast';import * as api from '../../services/api';+/**+ * Where reference-watch records its proposals, keyed by the app's RESOLVED work+ * tracker. Mirrors the server-side {trackerInstructions} block so the UID note+ * doesn't lie when an app tracks issues in GitHub/GitLab/JIRA instead of+ * PLAN.md. Falls back to the PLAN.md wording when the tracker is unresolved.+ */+function refWatchDestination(tracker) {+ switch (tracker) {+ case 'github':+ return (<><code>[ref-watch-…]</code> GitHub issues (labeled <code>reference-watch</code>) for <code>/claim --issues</code> to pick up</>);+ case 'gitlab':+ return (<><code>[ref-watch-…]</code> GitLab issues (labeled <code>reference-watch</code>) for <code>/claim --issues</code> to pick up</>);+ case 'jira':+ return (<><code>[ref-watch-…]</code> JIRA tickets for the <code>claim-issue-jira</code> flow to pick up</>);+ default:+ return (<><code>[ref-watch-…]</code> checklist items in <code>PLAN.md</code> for <code>/claim</code> / <code>plan-task</code> to pick up</>);+ }+}+/*** Per-app reference-repos manager. Embedded inside the app detail page's* "References" tab — the only surface for managing reference repos.@@ -29,6 +48,10 @@ export default function ReferenceReposPanel({ appId, appName }) {// spinner. RefRow reads checking via `checkingIds.has(ref.id)`.const [checkingIds, setCheckingIds] = useState(() => new Set());const [editingNotesId, setEditingNotesId] = useState(null);+ // Resolved work tracker so the description tells the truth about WHERE+ // reference-watch records proposals — PLAN.md vs the app's issue tracker.+ // Read-only; null until loaded (falls back to the generic PLAN.md wording).+ const [workTracker, setWorkTracker] = useState(null);// Track an explicit fetch error separately from `refs` so a transient// failure doesn't blank the list — stale-but-valid is far better UX@@ -51,6 +74,14 @@ export default function ReferenceReposPanel({ appId, appName }) {fetch();}, [fetch]);+ useEffect(() => {+ let cancelled = false;+ api.getAppWorkTracker(appId)+ .then((info) => { if (!cancelled) setWorkTracker(info?.resolved || null); })+ .catch(() => { if (!cancelled) setWorkTracker(null); });+ return () => { cancelled = true; };+ }, [appId]);+const handleAdd = async (form) => {const created = await api.addReferenceRepo(appId, form).catch((e) => { toast.error(e.message || 'Add failed'); return null; });if (!created) return;@@ -161,7 +192,7 @@ export default function ReferenceReposPanel({ appId, appName }) {{refreshing && <RefreshCw size={11} className="animate-spin text-gray-500" />}</h3><p className="text-xs text-gray-500 mt-0.5">- Upstream repos {appName} watches for clean-room reimplementation. The <code className="text-port-accent">reference-watch</code> task fetches each weekly, runs a security screen, and — for adoption-worthy commits — appends slug-tagged <code>[ref-watch-…]</code> checklist items to <code>PLAN.md</code> for <code>/claim</code> / <code>plan-task</code> to pick up. No source-code edits, no separate review file.+ Upstream repos {appName} watches for clean-room reimplementation. The <code className="text-port-accent">reference-watch</code> task fetches each weekly, runs a security screen, and — for adoption-worthy commits — records slug-tagged <code>[ref-watch-…]</code> proposals in {refWatchDestination(workTracker)}. No source-code edits, no separate review file.</p></div><buttondiff --git a/server/routes/referenceRepos.js b/server/routes/referenceRepos.jsindex ba557ae523..bdf73b43d1 100644--- a/server/routes/referenceRepos.js+++ b/server/routes/referenceRepos.js@@ -4,8 +4,9 @@* Per-app management of upstream repos we borrow code from. The* `reference-watch` scheduled task uses `checkReferenceRepo` to find* commits since each ref's `lastReviewedSha`, then dispatches a CoS- * sub-agent that appends slug-tagged `[ref-watch-…]` checklist items- * to the app's PLAN.md for `/claim` / `plan-task` to pick up.+ * sub-agent that records slug-tagged `[ref-watch-…]` proposals in the+ * app's CONFIGURED work tracker (PLAN.md / GitHub / GitLab / JIRA) for+ * `/claim` / `plan-task` / `claim-issue*` to pick up.** Mounted at /api/apps/:appId/reference-repos so it sits next to the* existing apps API surface.diff --git a/server/services/referenceRepos.js b/server/services/referenceRepos.jsindex e6d4da20d6..47e927ab4a 100644--- a/server/services/referenceRepos.js+++ b/server/services/referenceRepos.js@@ -7,9 +7,12 @@* copying upstream verbatim.* (e.g., PortOS itself watches `phosphene` for video-gen ideas). The* `reference-watch` scheduled task asks this service to fetch each ref- * and find commits since `lastReviewedSha`. The CoS sub-agent then- * appends slug-tagged `[ref-watch-…]` checklist items to PLAN.md in the- * target app's repo, which `/claim` / `plan-task` picks up later.+ * and find commits since `lastReviewedSha`. The CoS sub-agent then records+ * slug-tagged `[ref-watch-…]` proposals in the target app's CONFIGURED work+ * 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`.** Storage: refs live inline on each app in data/apps.json under the* `referenceRepos` array — fits the existing per-app config model and@@ -30,6 +33,7 @@ import {updateApp,} from './apps.js';import { DEFAULT_REVIEWER } from '../lib/validation.js';+import { resolveAppWorkTracker } from '../lib/workTracker.js';const REFERENCE_REPOS_ROOT = join(PATHS.data, 'cos', 'reference-repos');@@ -493,7 +497,8 @@ export async function checkReferenceRepo(appId, refId) {/*** Mark a ref as reviewed up to the given SHA — called after a CoS- * sub-agent finishes appending PLAN.md items for the new commits, or by+ * sub-agent finishes recording proposals (PLAN.md items / GitHub|GitLab+ * issues / JIRA tickets) for the new commits, or by* the UI's "mark as reviewed" button. SHA must match a real commit visible from* the ref's working tree (verified via `git cat-file -e <sha>^{commit}`* against the managed clone or the user-supplied local path).@@ -569,6 +574,60 @@ export function formatReferenceForPrompt(ref, snapshot) {return lines.join('\n');}+// The reference-watch prompt's {trackerInstructions} block — where the agent+// records its Adopt/Maybe proposals. v3 of the prompt no longer hardcodes+// 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).+const TRACKER_INSTRUCTIONS = {+ plan: `This app records autonomous work in **PLAN.md** at the repo root ({repoPath}).++- **Inventory:** Read PLAN.md from {repoPath}. Every existing checkbox carries a \`[<slug>]\` ID — collect the \`[ref-watch-…]\` ones so you don't duplicate. If PLAN.md does not exist, create it with a single top-level heading (\`# {appName} — Development Plan\`) and a \`## Next Up\` section before appending.+- **Record** each proposal as a slug-tagged checklist item appended to the \`## Next Up\` section:+ \`\`\`markdown+ - [ ] [<slug>] **<Short title.>** From \`reference-watch\` review of <ref name> (commit(s) \`<sha>\` [+ \`<sha>\` …], <today's date>). <1–2 sentences.> Fix: <files + functions in {appName}>. <Estimated scope.>+ \`\`\`+ Place **Maybe — needs human call** items in a \`### Trigger-gated (waiting for a precondition)\` subsection if one exists; otherwise append them under \`## Next Up\`.+- **Finalize:** Commit the PLAN.md edit with message \`docs(reference-watch): propose <N> item(s) from <ref names>\`. Do NOT create branches or PRs — \`/claim\` (or the \`plan-task\` agent) picks the slugs up later.`,++ github: `This app tracks autonomous work in **GitHub Issues** (via the \`gh\` CLI), NOT PLAN.md — do NOT edit PLAN.md.++- **Inventory:** From {repoPath}, resolve the repo (\`gh repo view --json nameWithOwner -q .nameWithOwner\`) and list existing reference-watch issues so you don't duplicate: \`gh issue list --state all --search "ref-watch in:title" --limit 100 --json number,title\`. Each carries a \`[ref-watch-…]\` slug in its title — collect them. If \`gh\` is not authenticated or the remote is not GitHub, exit cleanly.+- **Record** each proposal as a new GitHub issue. Ensure the label exists first (\`gh label create reference-watch --description "Proposed from a reference-repo watch" --force\`), then:+ \`\`\`bash+ gh issue create --title "[<slug>] <Short title>" --label reference-watch --body "<body>"+ \`\`\`+ The body must contain the provenance (ref + commit SHA(s) + today's date), the 1–2 sentence rationale, the \`Fix:\` line naming the {appName} files/functions to change, and the estimated scope. For **Maybe — needs human call** items, also add \`--label needs-decision\` (create it the same way if absent) and end the body with \`**Decision needed:** <one sentence>.\`.+- **Finalize:** No source-code edits, no PLAN.md, no branches, no PRs — the issues ARE the deliverable. \`/claim --issues\` (the \`claim-issue\` flow) picks them up later.`,++ gitlab: `This app tracks autonomous work in **GitLab Issues** (via the \`glab\` CLI), NOT PLAN.md — do NOT edit PLAN.md.++- **Inventory:** From {repoPath}, confirm the forge (\`glab repo view\`) and list existing reference-watch issues so you don't duplicate: \`glab issue list --label reference-watch --per-page 100 -F json\` (also scan titles for the \`[ref-watch-…]\` slug). Collect the existing slugs. If \`glab\` is not authenticated or the remote is not GitLab, exit cleanly.+- **Record** each proposal as a new GitLab issue:+ \`\`\`bash+ glab issue create --title "[<slug>] <Short title>" --label reference-watch --description "<body>"+ \`\`\`+ (Run \`glab issue create --help\` if a flag is rejected — glab's flags evolve.) The body must contain the provenance (ref + commit SHA(s) + today's date), the 1–2 sentence rationale, the \`Fix:\` line naming the {appName} files/functions to change, and the estimated scope. For **Maybe — needs human call** items, also add \`--label needs-decision\` and end the body with \`**Decision needed:** <one sentence>.\`.+- **Finalize:** No source-code edits, no PLAN.md, no branches, no MRs — the issues ARE the deliverable. \`/claim --issues\` (the \`claim-issue-gitlab\` flow) picks them up later.`,++ jira: `This app tracks autonomous work in **JIRA**. Create one JIRA issue per proposal in the app's configured project using whatever JIRA CLI/REST this environment provides. **If no JIRA credentials are available, fall back to recording proposals in PLAN.md at {repoPath} (slug-tagged \`- [ ] [<slug>] …\` checklist items under \`## Next Up\`, committed) and say so in your final summary.**++- **Inventory:** Search existing JIRA issues (and PLAN.md, if you fall back) for the \`[ref-watch-…]\` slug so you don't duplicate; collect the existing slugs.+- **Record** each proposal as a new JIRA issue whose summary starts with the \`[<slug>]\` tag. The description must contain the provenance (ref + commit SHA(s) + today's date), the 1–2 sentence rationale, the \`Fix:\` line naming the {appName} files/functions to change, and the estimated scope. For **Maybe — needs human call** items, end the description with \`**Decision needed:** <one sentence>.\`.+- **Finalize:** No source-code edits, no branches, no PRs — the tickets (or the committed PLAN.md fallback) ARE the deliverable. The \`claim-issue-jira\` flow picks them up later.`,+};++/**+ * Pick the {trackerInstructions} block for a resolved work tracker, falling back+ * to the PLAN.md block for an unknown/missing tracker (matches the v3 prompt's+ * read-only-on-source, write-to-tracker contract). Exported for tests.+ */+export function formatTrackerInstructions(tracker) {+ return TRACKER_INSTRUCTIONS[tracker] || TRACKER_INSTRUCTIONS.plan;+}+/*** Trigger a CoS analysis task for a single reference repo after a successful* check found new commits. Builds the reference-watch prompt with the snapshot@@ -587,9 +646,17 @@ export async function triggerReferenceAnalysis(app, ref, snapshot) {const { getTaskPrompt } = await import('./taskPromptService.js');const referenceDataBlock = formatReferenceForPrompt(ref, snapshot);+ // Resolve where THIS app records autonomous work (PLAN.md / GitHub / GitLab /+ // JIRA) so the agent files proposals into the configured tracker instead of+ // always appending to PLAN.md. Never throws — degrades to the PLAN.md block.+ const workTracker = await resolveAppWorkTracker(app).catch(() => ({ resolved: 'plan' }));+ const trackerInstructionsBlock = formatTrackerInstructions(workTracker.resolved);const promptTemplate = await getTaskPrompt('reference-watch');- // Use arrow replacers to avoid $& / $1 interpretation in replacement strings+ // Use arrow replacers to avoid $& / $1 interpretation in replacement strings.+ // {trackerInstructions} is substituted FIRST so the {appName}/{repoPath}+ // placeholders inside the injected block are expanded by the later replacers.const fullPrompt = promptTemplate+ .replace(/\{trackerInstructions\}/g, () => trackerInstructionsBlock).replace(/\{appName\}/g, () => app.name).replace(/\{repoPath\}/g, () => app.repoPath).replace(/\{appId\}/g, () => app.id)@@ -609,11 +676,15 @@ export async function triggerReferenceAnalysis(app, ref, snapshot) {repoPath: app.repoPath,analysisType: 'reference-watch',autoGenerated: true,- // The reference-watch prompt v2 instructs the agent to APPEND- // slug-tagged checklist items to PLAN.md (and commit). readOnly:true- // would inject the "do not modify or commit files" guard into the- // system prompt and the agent would refuse to write the PLAN- // entries — defeating the whole flow. Mark writable.+ // Resolved work tracker the prompt told the agent to file proposals into+ // (PLAN.md / GitHub / GitLab / JIRA) — recorded for traceability.+ workTracker: workTracker.resolved,+ // The reference-watch prompt v3 instructs the agent to record proposals in+ // the resolved tracker: the PLAN.md path APPENDS slug-tagged checklist+ // items (and commits); the GitHub/GitLab paths shell out to `gh`/`glab+ // issue create`. readOnly:true would inject the "do not modify or commit+ // files" guard into the system prompt and the agent would refuse to+ // write/commit/shell — defeating the whole flow. Mark writable.readOnly: false,context: fullPrompt,},diff --git a/server/services/referenceRepos.test.js b/server/services/referenceRepos.test.jsindex b5d7f7d113..35a2d027c9 100644--- a/server/services/referenceRepos.test.js+++ b/server/services/referenceRepos.test.js@@ -45,7 +45,7 @@ const addTaskMock = vi.fn(async (task) => task);vi.mock('./cos.js', () => ({addTask: (...args) => addTaskMock(...args),}));-const getTaskPromptMock = vi.fn(async () => 'Analyze {appName} at {repoPath} for {appId} reviewer={reviewers}\n{referenceData}\n{planConstraint}');+const getTaskPromptMock = vi.fn(async () => 'Analyze {appName} at {repoPath} for {appId} reviewer={reviewers}\n{referenceData}\n{planConstraint}\nTRACKER: {trackerInstructions}');vi.mock('./taskPromptService.js', () => ({getTaskPrompt: (...args) => getTaskPromptMock(...args),}));@@ -70,7 +70,7 @@ beforeEach(async () => {addTaskMock.mockReset();addTaskMock.mockImplementation(async (task) => task);getTaskPromptMock.mockReset();- getTaskPromptMock.mockImplementation(async () => 'Analyze {appName} at {repoPath} for {appId} reviewer={reviewers}\n{referenceData}\n{planConstraint}');+ getTaskPromptMock.mockImplementation(async () => 'Analyze {appName} at {repoPath} for {appId} reviewer={reviewers}\n{referenceData}\n{planConstraint}\nTRACKER: {trackerInstructions}');existsMock.mockReset();existsMock.mockReturnValue(false);svc = await import('./referenceRepos.js');@@ -395,11 +395,35 @@ describe('triggerReferenceAnalysis', () => {// Task type markersexpect(addTaskMock.mock.calls[0][1]).toBe('internal');expect(addTaskMock.mock.calls[0][2]).toEqual({ raw: true });- // readOnly must be false: the v2 reference-watch prompt appends slug-tagged- // [ref-watch-…] items to PLAN.md and commits them. readOnly:true would inject- // the "## Read-Only Task" guard into the system prompt and the agent would- // refuse to write the PLAN entries — defeating the whole flow.+ // readOnly must be false: the v3 reference-watch prompt records proposals in+ // the resolved tracker (PLAN.md commit, or gh/glab issue create). readOnly:true+ // would inject the "## Read-Only Task" guard into the system prompt and the+ // agent would refuse to write — defeating the whole flow.expect(taskArg.metadata.readOnly).toBe(false);+ // With no configured tracker and no resolvable git origin (execGit mock+ // returns empty stdout), the work tracker degrades to PLAN.md and the+ // {trackerInstructions} block reflects that.+ expect(taskArg.metadata.workTracker).toBe('plan');+ expect(taskArg.metadata.context).toContain('PLAN.md');+ });++ it('injects the GitHub-issue tracker instructions when the app is configured for github', async () => {+ const ghApp = { ...app, workTracker: 'github' };+ const result = await svc.triggerReferenceAnalysis(ghApp, ref, snapshot);+ expect(result.queued).toBe(true);+ const taskArg = addTaskMock.mock.calls[0][0];+ expect(taskArg.metadata.workTracker).toBe('github');+ // The injected block drives `gh issue create`, not a PLAN.md append.+ expect(taskArg.metadata.context).toContain('gh issue create');+ expect(taskArg.metadata.context).toContain('GitHub Issues');+ });++ it('exposes formatTrackerInstructions and falls back to PLAN.md for an unknown tracker', () => {+ expect(svc.formatTrackerInstructions('github')).toContain('gh issue create');+ expect(svc.formatTrackerInstructions('gitlab')).toContain('glab issue create');+ expect(svc.formatTrackerInstructions('jira')).toContain('JIRA');+ expect(svc.formatTrackerInstructions('plan')).toContain('PLAN.md');+ expect(svc.formatTrackerInstructions('nonsense')).toContain('PLAN.md');});it('returns duplicate when addTask signals a duplicate', async () => {diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex 0c3a4ca60e..0f28eb6574 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -27,7 +27,7 @@"pr-reviewer": "add27b67daa6aa2c75717ac96a6bd625","pr-reviewer-security": "2050297d1cdb081a8576a781828ee44f","pr-reviewer-review": "21ccd5d3a6f3eea16c479db9ed9aedaa",- "reference-watch": "722ca590fb4b6323c98850a176b9b309",+ "reference-watch": "e0e20754700fb08d5159b8437d9c260b","pr-watcher": "53ead8e26d396849bfa78f28550bd691","refresh-local-llm-catalog": "a9dce67bb9f0837ba904f3412b03637f"},@@ -40,7 +40,7 @@"pr-reviewer": 3,"code-reviewer-a": 1,"code-reviewer-b": 1,- "reference-watch": 2,+ "reference-watch": 3,"pr-watcher": 1,"refresh-local-llm-catalog": 1,"security": 2,@@ -54,7 +54,7 @@"mobile-responsive": 2,"release-check": 6},- "REFERENCE_WATCH_AUDITED_VERSION": 2,+ "REFERENCE_WATCH_AUDITED_VERSION": 3,"PREVIOUS_DEFAULT_PROMPTS": {"feature-ideas": ["d67a9028aeb8bb8348453951f878501b",@@ -77,7 +77,8 @@"f64e5d8176a871304fa691df812cda61"],"reference-watch": [- "f9322140bff7d3f603799c09ce468da9"+ "f9322140bff7d3f603799c09ce468da9",+ "722ca590fb4b6323c98850a176b9b309"],"pr-watcher": [],"claim-issue-gitlab": [diff --git a/server/services/taskPromptDefaults/previousDefaults.js b/server/services/taskPromptDefaults/previousDefaults.jsindex b07ab6d030..8f18c54a19 100644--- a/server/services/taskPromptDefaults/previousDefaults.js+++ b/server/services/taskPromptDefaults/previousDefaults.js@@ -1243,7 +1243,127 @@ For each reference above:6. Once REFERENCE_REVIEW.md is written, your final assistant message must be a2-3 sentence summary of how many commits you reviewed, how many security- flags you raised, and how many you marked Adopt vs. Maybe vs. Skip.`+ flags you raised, and how many you marked Adopt vs. Maybe vs. Skip.`,+ // v2 default prompt — appended slug-tagged [ref-watch-…] checklist items to+ // PLAN.md (Adopt + Maybe) and committed them; hardcoded PLAN.md as the only+ // destination regardless of the app's configured work tracker. Superseded by+ // v3, which records proposals in the app's resolved task tracker (PLAN.md /+ // GitHub / GitLab / JIRA) via the {trackerInstructions} block. Kept so a+ // stored v2 prompt auto-upgrades.+ `[Improvement: {appName}] Reference Repo Review++You are reviewing upstream commits from one or more reference repositories that+{appName} watches for clean-room reimplementation — meaning {appName} maintains+its OWN implementation of similar features and may benefit from re-building+the bug fixes or new capabilities those upstream commits introduce. Your job+is to PROPOSE which commits are worth re-implementing as slug-tagged checklist+items appended to PLAN.md — NOT to copy upstream code. Read-only mode for+{appName}'s source; the ONLY file you edit is PLAN.md. **Never paste+upstream code verbatim into recommendations**: describe what to change in our+own architecture, naming the files and functions in {appName} that need+edits. The user owns the actual implementation; \`/claim\`-style task runners+pick the items up later.++Repository: {repoPath}++## References++{referenceData}++## What to do++1. **Read PLAN.md** from {repoPath} so you know which slugs already exist.+ Every existing checkbox carries a \`[<slug>]\` ID — collect them so you+ don't duplicate. If PLAN.md does not exist, create it with a single+ top-level heading (\`# {appName} — Development Plan\`) and a \`## Next Up\`+ section before appending.++2. For each reference above, for every commit in the "Commits to review"+ list, read its diff via \`git -C <source clone path> show <sha>\` (the+ path is in the reference's block above). For commits with many files,+ focus on diffs that match the user-supplied "Context" block — that's+ the load-bearing intersection between this app and upstream, and the+ user has flagged what matters.++3. **SECURITY SCREEN — do this BEFORE deciding whether the commit is worth+ adopting.** Reference repos are third-party code we don't control; an+ upstream maintainer's account compromise, a malicious PR merge, or a+ typo-squatting branch name could ship malware or new vulnerabilities+ into a commit that *looks* useful. For every commit, scan the diff for:++ - **Malware indicators**: obfuscated/minified strings in source files,+ base64/hex blobs being decoded then \`eval\`'d / \`exec\`'d / piped to+ a shell, network calls to non-obvious hosts (anything that isn't the+ upstream's own infra or a well-known package registry), exfil of+ env vars / \`~/.ssh/\` / \`~/.aws/\` / browser cookie stores, new+ post-install / pre-publish hooks, dynamic-import patterns that+ fetch-then-execute remote code, suspicious file writes outside the+ repo root.+ - **New vulnerabilities introduced**: SQL/NoSQL/command injection on+ newly-added user-input paths, path traversal in newly-added file+ I/O, prototype pollution via unvalidated object merges, unsafe+ deserialization (eval, vm, pickle, Marshal, YAML.load without+ SafeLoader), deactivated security headers / CSP relaxations,+ authentication or authorization checks removed or weakened, secrets+ committed (tokens, keys, .env contents).+ - **Suspicious dependency changes**: newly added deps from publishers+ with no track record, dep-version downgrades to known-vulnerable+ ranges, lockfile-only changes that pull a different version than+ the manifest claims.++ If a commit shows ANY of these, **do NOT add a PLAN.md item for it** —+ security-flagged commits are not adoption candidates, period. Note them+ only in the final assistant summary so the user sees what tripped the+ screen.++4. Decide whether each (security-clean) commit is worth REIMPLEMENTING in+ {appName}. Use these criteria, in priority order:+ - Does it fix a bug we'd hit too? (high priority — re-implement the fix+ in our equivalent code path)+ - Does it expose a capability we artificially restrict? (e.g. our wrapper+ around a shared library uses a constrained subset of an API the upstream+ just opened up — we can do the same in our wrapper)+ - Does it improve performance / correctness on a code path we share?+ - Is it a docs / install / packaging fix specific to upstream's distribution+ model? (skip — those rarely apply)++5. **For each Adopt-worthy commit (or coherent group of commits), append a+ slug-tagged checklist item to PLAN.md.** Format:++ \`\`\`markdown+ - [ ] [ref-watch-<ref-name-slug>-<short-title-slug>] **<Short title.>** From \`reference-watch\` review of <ref name> (commit(s) \`<sha>\` [+ \`<sha>\` …], <today's date>). <1–2 sentences: what bug/capability the commit addresses, and why it matters for {appName} tied to our notes.> Fix: <specific files + functions in {appName} — e.g. \`server/services/foo.js#buildArgs()\` — describe the BEHAVIOR to add, not upstream's exact code (clean-room reimplementation).> <Estimated scope: small / medium / large.>+ \`\`\`++ Slug rules:+ - Lowercase kebab-case; start with \`ref-watch-\` so the user can grep+ them in bulk.+ - Include a short reference of the upstream repo so multiple watched+ refs don't collide (e.g. \`ref-watch-phosphene-lazy-eval-env-bootstrap\`).+ - ≤80 chars total, unique against every existing \`[<slug>]\` in PLAN.md+ (re-check before each append).+ - Place items in the \`## Next Up\` section (create the section if absent).++ For **Maybe — needs human call** items (real value but unclear fit, or+ gated on a decision/precondition), append the same slug-tagged line but+ add a final sentence stating the decision needed, and place the line in+ a \`### Trigger-gated (waiting for a precondition)\` subsection if one+ exists; otherwise append under \`## Next Up\` and end the description+ with \`**Decision needed:** <one sentence>.\`++ **Skip — not for us** items get no PLAN.md entry. Mention them only in+ the final summary.++6. Commit the PLAN.md edit. The commit message should be:+ \`docs(reference-watch): propose <N> item(s) from <ref names>\`+ Do NOT create branches, PRs, or any source-code edits — PLAN.md is the+ only file you touch. \`/claim\` (or the \`plan-task\` agent) picks the+ slugs up later.++7. Your final assistant message must be a 2–3 sentence summary of:+ - How many commits you reviewed (across all refs).+ - How many security flags you raised (with one-line reasons + SHAs).+ - How many slug-tagged PLAN.md items you appended (Adopt + Maybe) vs+ how many commits you skipped as not-for-us.`],// pr-watcher shipped at v1 — no prior defaults to recognize yet. Kept as andiff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 4f37a4753c..b5c1259615 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -1357,13 +1357,14 @@ You are reviewing upstream commits from one or more reference repositories that{appName} watches for clean-room reimplementation — meaning {appName} maintainsits OWN implementation of similar features and may benefit from re-buildingthe bug fixes or new capabilities those upstream commits introduce. Your job-is to PROPOSE which commits are worth re-implementing as slug-tagged checklist-items appended to PLAN.md — NOT to copy upstream code. Read-only mode for-{appName}'s source; the ONLY file you edit is PLAN.md. **Never paste-upstream code verbatim into recommendations**: describe what to change in our-own architecture, naming the files and functions in {appName} that need-edits. The user owns the actual implementation; \`/claim\`-style task runners-pick the items up later.+is to PROPOSE which commits are worth re-implementing as work items recorded in+{appName}'s configured task tracker (described under "Where to record proposals"+below) — NOT to copy upstream code. Read-only mode for {appName}'s source: you+do NOT edit application code, only the task tracker. **Never paste upstream code+verbatim into recommendations**: describe what to change in our own+architecture, naming the files and functions in {appName} that need edits. The+user owns the actual implementation; \`/claim\`-style task runners pick the items+up later.Repository: {repoPath}@@ -1371,13 +1372,16 @@ Repository: {repoPath}{referenceData}+## Where to record proposals++{trackerInstructions}+## What to do-1. **Read PLAN.md** from {repoPath} so you know which slugs already exist.- Every existing checkbox carries a \`[<slug>]\` ID — collect them so you- don't duplicate. If PLAN.md does not exist, create it with a single- top-level heading (\`# {appName} — Development Plan\`) and a \`## Next Up\`- section before appending.+1. **Inventory existing proposals so you don't duplicate.** Follow the+ "Inventory" step under "Where to record proposals" above for this app's+ tracker. Every prior reference-watch proposal carries a \`[ref-watch-…]\`+ slug — collect the existing slugs and skip any commit already proposed.2. For each reference above, for every commit in the "Commits to review"list, read its diff via \`git -C <source clone path> show <sha>\` (the@@ -1412,7 +1416,7 @@ Repository: {repoPath}ranges, lockfile-only changes that pull a different version thanthe manifest claims.- If a commit shows ANY of these, **do NOT add a PLAN.md item for it** —+ If a commit shows ANY of these, **do NOT propose it** —security-flagged commits are not adoption candidates, period. Note themonly in the final assistant summary so the user sees what tripped thescreen.@@ -1428,43 +1432,42 @@ Repository: {repoPath}- Is it a docs / install / packaging fix specific to upstream's distributionmodel? (skip — those rarely apply)-5. **For each Adopt-worthy commit (or coherent group of commits), append a- slug-tagged checklist item to PLAN.md.** Format:-- \`\`\`markdown- - [ ] [ref-watch-<ref-name-slug>-<short-title-slug>] **<Short title.>** From \`reference-watch\` review of <ref name> (commit(s) \`<sha>\` [+ \`<sha>\` …], <today's date>). <1–2 sentences: what bug/capability the commit addresses, and why it matters for {appName} tied to our notes.> Fix: <specific files + functions in {appName} — e.g. \`server/services/foo.js#buildArgs()\` — describe the BEHAVIOR to add, not upstream's exact code (clean-room reimplementation).> <Estimated scope: small / medium / large.>- \`\`\`-- Slug rules:- - Lowercase kebab-case; start with \`ref-watch-\` so the user can grep- them in bulk.- - Include a short reference of the upstream repo so multiple watched- refs don't collide (e.g. \`ref-watch-phosphene-lazy-eval-env-bootstrap\`).- - ≤80 chars total, unique against every existing \`[<slug>]\` in PLAN.md- (re-check before each append).- - Place items in the \`## Next Up\` section (create the section if absent).+5. **For each Adopt-worthy commit (or coherent group of commits), record a+ proposal in the task tracker** using the "Record" mechanics under "Where+ to record proposals" above. Each proposal must carry:++ - **A slug-tagged title.** Lowercase kebab-case starting with+ \`ref-watch-\` so the user can grep them in bulk; include a short+ reference of the upstream repo so multiple watched refs don't collide+ (e.g. \`ref-watch-phosphene-lazy-eval-env-bootstrap\`); ≤80 chars total;+ unique against every existing \`[ref-watch-…]\` slug (re-check before+ each record).+ - **A short title sentence.**+ - **Provenance:** From \`reference-watch\` review of <ref name>+ (commit(s) \`<sha>\` [+ \`<sha>\` …], <today's date>).+ - **1–2 sentences** on what bug/capability the commit addresses and why it+ matters for {appName} tied to our notes.+ - **A \`Fix:\` line** naming the specific files + functions in {appName}+ to change (e.g. \`server/services/foo.js#buildArgs()\`) — describe the+ BEHAVIOR to add, not upstream's exact code (clean-room reimplementation).+ - **Estimated scope:** small / medium / large.For **Maybe — needs human call** items (real value but unclear fit, or- gated on a decision/precondition), append the same slug-tagged line but- add a final sentence stating the decision needed, and place the line in- a \`### Trigger-gated (waiting for a precondition)\` subsection if one- exists; otherwise append under \`## Next Up\` and end the description- with \`**Decision needed:** <one sentence>.\`+ gated on a decision/precondition), record the same proposal but end the+ description with \`**Decision needed:** <one sentence>.\` (see the tracker+ instructions for where Maybe items go).- **Skip — not for us** items get no PLAN.md entry. Mention them only in- the final summary.+ **Skip — not for us** commits get no proposal. Mention them only in the+ final summary.-6. Commit the PLAN.md edit. The commit message should be:- \`docs(reference-watch): propose <N> item(s) from <ref names>\`- Do NOT create branches, PRs, or any source-code edits — PLAN.md is the- only file you touch. \`/claim\` (or the \`plan-task\` agent) picks the- slugs up later.+6. **Finalize** per the "Finalize" step under "Where to record proposals"+ above. Do NOT create branches, PRs, or any source-code edits.7. Your final assistant message must be a 2–3 sentence summary of:- How many commits you reviewed (across all refs).- How many security flags you raised (with one-line reasons + SHAs).- - How many slug-tagged PLAN.md items you appended (Adopt + Maybe) vs- how many commits you skipped as not-for-us.`,+ - How many proposals you recorded (Adopt + Maybe) vs how many commits you+ skipped as not-for-us.`,'pr-watcher': `[Improvement: {appName}] Pull Request Watcherdiff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex 5553017bae..776756e059 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -15,7 +15,7 @@ export const PROMPT_VERSIONS = {'pr-reviewer': 3, // v3: multi-stage pipeline (security scan → code review + merge)'code-reviewer-a': 1, // v1: 2-stage pipeline (codebase review → triage & implement)'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)- 'reference-watch': 2, // v2: append slug-tagged checklist items to PLAN.md (Adopt + Maybe) instead of writing REFERENCE_REVIEW.md; security-flagged commits get no PLAN entry (mentioned only in final summary)+ 'reference-watch': 3, // v3: record proposals in the app's RESOLVED work tracker (PLAN.md / GitHub / GitLab / JIRA) via the {trackerInstructions} block — no longer hardcodes PLAN.md, so an app configured for GitHub issues gets `gh issue create` proposals. v2: append slug-tagged checklist items to PLAN.md (Adopt + Maybe) instead of writing REFERENCE_REVIEW.md; security-flagged commits get no PLAN entry (mentioned only in final summary)'pr-watcher': 1, // v1: review-and-comment default for newly-opened PRs on the app's default branch'refresh-local-llm-catalog': 1, // v1: research current local models, refresh LOCAL_LLM_CATALOG + EDITORIAL_FAMILY_RANK, PR (PortOS repo only)@@ -38,12 +38,14 @@ export const PROMPT_VERSIONS = {// Audit anchor for reference-watch's read/write coupling.// The reference-watch schedule default (`taskMetadata.readOnly` in DEFAULT_TASK_INTERVALS)-// is derived from what the active prompt VERSION does: v2's prompt APPENDS slug-tagged-// `[ref-watch-…]` items to PLAN.md and commits them, so the default must be `readOnly: false`.-// A future v3 that returns to a propose-only flow would need `readOnly: true` again.-// `REFERENCE_WATCH_AUDITED_VERSION` records the PROMPT_VERSIONS['reference-watch'] value-// the current `readOnly` default was last audited against. A guard test in-// taskSchedule.test.js fails when PROMPT_VERSIONS['reference-watch'] moves past this anchor —-// forcing whoever bumps the prompt to re-confirm the default still matches the prompt's-// behavior and then advance this anchor in the same change. See issue #734.-export const REFERENCE_WATCH_AUDITED_VERSION = 2;+// is derived from what the active prompt VERSION does: v3's prompt records proposals in the+// app's resolved work tracker — the PLAN.md path appends + commits `[ref-watch-…]` items, and+// the forge paths (GitHub/GitLab) shell out to `gh`/`glab issue create`. Both need a writable+// agent (a read-only agent gets the "do not modify or commit files" guard and refuses), so the+// default stays `readOnly: false`. A future version that returns to a propose-only flow would+// need `readOnly: true` again. `REFERENCE_WATCH_AUDITED_VERSION` records the+// PROMPT_VERSIONS['reference-watch'] value the current `readOnly` default was last audited+// against. A guard test in taskSchedule.test.js fails when PROMPT_VERSIONS['reference-watch']+// moves past this anchor — forcing whoever bumps the prompt to re-confirm the default still+// matches the prompt's behavior and then advance this anchor in the same change. See issue #734.+export const REFERENCE_WATCH_AUDITED_VERSION = 3;diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.jsindex 8e9e4c82fb..d0fe4838fd 100644--- a/server/services/taskSchedule.test.js+++ b/server/services/taskSchedule.test.js@@ -329,12 +329,14 @@ describe('taskSchedule', () => {expect(interval.enabled).toBe(false)})- it('reference-watch default is writable so the v2 prompt can append [ref-watch-…] items to PLAN.md', async () => {- // The v2 reference-watch prompt instructs the agent to append slug-tagged- // checklist items to PLAN.md and commit them. If `readOnly` flips back to- // true, agentPromptBuilder injects the "## Read-Only Task" guard and the- // agent refuses to write the entries — silently breaking the flow. Pin- // the contract so a future "default to read-only" refactor surfaces here.+ it('reference-watch default is writable so the v3 prompt can record proposals (PLAN.md commit or gh/glab issue create)', async () => {+ // The v3 reference-watch prompt records proposals in the app's resolved+ // work tracker: the PLAN.md path appends slug-tagged checklist items and+ // commits them; the GitHub/GitLab paths shell out to `gh`/`glab issue+ // create`. Both need a writable agent — if `readOnly` flips back to true,+ // agentPromptBuilder injects the "## Read-Only Task" guard and the agent+ // refuses to write/commit/shell, silently breaking the flow. Pin the+ // contract so a future "default to read-only" refactor surfaces here.const interval = await getTaskInterval('reference-watch')expect(interval.taskMetadata?.readOnly).toBe(false)})@@ -348,12 +350,13 @@ describe('taskSchedule', () => {expect(PROMPT_VERSIONS['reference-watch']).toBe(REFERENCE_WATCH_AUDITED_VERSION)})- it('reference-watch v2 prompt requires a writable default so it can append + commit PLAN.md items (issue #734)', () => {- // The coupling the audit anchor protects: at the audited version (v2), the prompt- // writes to PLAN.md, so the raw default must be writable. If a future re-audit flips+ it('reference-watch v3 prompt requires a writable default so it can record proposals (PLAN.md commit or gh/glab issue create) (issue #734)', () => {+ // The coupling the audit anchor protects: at the audited version (v3), the prompt+ // writes to the resolved tracker (PLAN.md commit, or `gh`/`glab issue create`), so the+ // raw default must be writable. If a future re-audit flips// REFERENCE_WATCH_AUDITED_VERSION to a propose-only version, update this expectation// alongside the default and the anchor.- if (REFERENCE_WATCH_AUDITED_VERSION === 2) {+ if (REFERENCE_WATCH_AUDITED_VERSION === 3) {expect(DEFAULT_TASK_INTERVALS['reference-watch'].taskMetadata.readOnly).toBe(false)}})