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
let the persistent mind file GitHub/GitLab issues as its queueing lane
[._.]/ Adam Eivy7c8314384b7d
diff --git a/client/src/components/cos/PersistentMindTaskAccessControls.jsx b/client/src/components/cos/PersistentMindTaskAccessControls.jsxindex ba54470f3a..fcbe3b9cdb 100644--- a/client/src/components/cos/PersistentMindTaskAccessControls.jsx+++ b/client/src/components/cos/PersistentMindTaskAccessControls.jsx@@ -3,8 +3,9 @@ import * as api from '../../services/api';import toast from '../ui/Toast';const normalizeCapabilities = (value) => ({- schemaVersion: 9,+ schemaVersion: 10,createTasks: value?.createTasks === true,+ fileIssues: value?.fileIssues === true,manageMind: value?.manageMind === true,manageToolRecipes: value?.manageToolRecipes === true,manageEidoverse: value?.manageEidoverse === true,@@ -41,6 +42,11 @@ const OPTIONS = [label: 'Allow mind to queue CoS agent tasks',hint: 'Queues typed tasks through isolated worktrees, capacity, budget, review, CI, and landing-policy gates.',},+ {+ key: 'fileIssues',+ label: 'Allow mind to read and file GitHub/GitLab issues',+ hint: 'Lets the mind read an authorized app\'s open issues and file new ones with the required dispatch labels. This is the queueing lane that still works when no coding agent is attached to this machine — no editing, closing, or commenting on existing issues.',+ },{key: 'visitEidoversePeers',label: 'Allow guest travel and chat with federated worlds',@@ -68,9 +74,18 @@ const OPTIONS = [},];+/** What each grant can actually do with one managed app, for its row's sub-label. */+const managedAppLanes = (app) => [+ app.planOnly ? 'Implementation or Plan & File Issue' : 'Implementation delivery',+ app.forge ? `Issue filing (${app.forge})` : 'No forge tracker — issues cannot be filed',+].join(' · ');+export default function PersistentMindTaskAccessControls({capabilities,- taskCatalog,+ // The server's single roster: every runnable app, forge-tracked or not, so+ // narrowing the shared allowlist here can never silently revoke an app one+ // grant needs because the other grant could not see it.+ managedApps,disabled = false,onSaved,onSavingChange,@@ -78,12 +93,12 @@ export default function PersistentMindTaskAccessControls({const idPrefix = useId();const [draft, setDraft] = useState(() => normalizeCapabilities(capabilities));const [saving, setSaving] = useState(false);- const taskApps = Array.isArray(taskCatalog?.apps) ? taskCatalog.apps : [];+ const apps = Array.isArray(managedApps) ? managedApps : [];const allowedAppIds = Array.isArray(draft.allowedAppIds) ? draft.allowedAppIds : null;useEffect(() => {if (!saving) setDraft(normalizeCapabilities(capabilities));- }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.manageMind, capabilities?.manageToolRecipes, capabilities?.manageEidoverse, capabilities?.visitEidoversePeers, capabilities?.callUser, capabilities?.adjustLocalContext, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);+ }, [capabilities?.schemaVersion, capabilities?.createTasks, capabilities?.fileIssues, capabilities?.manageMind, capabilities?.manageToolRecipes, capabilities?.manageEidoverse, capabilities?.visitEidoversePeers, capabilities?.callUser, capabilities?.adjustLocalContext, capabilities?.readPortos, capabilities?.writePortos, capabilities?.taskModelAllowlist, capabilities?.taskModelAllowlistInvalid, capabilities?.allowedAppIds?.join('\0'), saving]);const save = async (key, enabled) => {const previous = draft;@@ -109,7 +124,7 @@ export default function PersistentMindTaskAccessControls({};const saveAllowedAppIds = async (appId, enabled) => {- const current = allowedAppIds || taskApps.map((app) => app.id);+ const current = allowedAppIds || apps.map((app) => app.id);const next = enabled? [...new Set([...current, appId])]: current.filter((id) => id !== appId);@@ -123,7 +138,7 @@ export default function PersistentMindTaskAccessControls({try {await api.updateCosConfig({ persistentMindCapabilities: nextCapabilities }, { silent: true });onSaved?.(nextCapabilities);- toast.success(`${taskApps.find((app) => app.id === appId)?.name || 'Managed app'} task access ${enabled ? 'enabled' : 'disabled'}`);+ toast.success(`${apps.find((app) => app.id === appId)?.name || 'Managed app'} access ${enabled ? 'enabled' : 'disabled'}`);} catch (error) {setDraft(previous);toast.error(error.message);@@ -154,28 +169,28 @@ export default function PersistentMindTaskAccessControls({</div>);})}- {taskCatalog && (+ {managedApps && (<div className="border-t border-port-border pt-4"><div><p className="text-sm text-port-text">Managed app access</p>- <p className="mt-0.5 text-xs text-port-text-muted">Choose which configured apps the task grant may target. Existing installs start with every runnable app allowed.</p>+ <p className="mt-0.5 text-xs text-port-text-muted">Choose which configured apps the task and issue grants may target. One list covers both. Existing installs start with every runnable app allowed.</p></div>- {taskApps.length > 0 ? (+ {apps.length > 0 ? (<div className="mt-3 space-y-3">- {taskApps.map((app) => {+ {apps.map((app) => {const id = `${idPrefix}-app-${app.id}`;const checked = allowedAppIds ? allowedAppIds.includes(app.id) : app.granted !== false;return (<div key={app.id} className="flex items-start justify-between gap-4"><div><label htmlFor={id} className="text-sm text-port-text">{app.name}</label>- <p className="mt-0.5 text-xs text-port-text-muted">{app.planOnly ? 'Implementation or Plan & File Issue' : 'Implementation delivery'}</p>+ <p className="mt-0.5 text-xs text-port-text-muted">{managedAppLanes(app)}</p></div><inputid={id}type="checkbox"checked={checked}- disabled={disabled || saving || !draft.createTasks}+ disabled={disabled || saving || (!draft.createTasks && !draft.fileIssues)}onChange={(event) => saveAllowedAppIds(app.id, event.target.checked)}className="mt-1 h-4 w-4 accent-port-accent disabled:opacity-50"/>@@ -186,7 +201,7 @@ export default function PersistentMindTaskAccessControls({) : (<p className="mt-3 rounded border border-dashed border-port-border p-3 text-xs text-port-text-muted">No runnable managed apps are currently configured.</p>)}- {!draft.createTasks && <p className="mt-3 text-xs text-port-text-muted">Enable the task capability above before selecting managed apps.</p>}+ {!draft.createTasks && !draft.fileIssues && <p className="mt-3 text-xs text-port-text-muted">Enable the task or issue capability above before selecting managed apps.</p>}</div>)}<div className="rounded border border-port-border bg-port-bg/40 px-3 py-2 text-xs text-port-text-muted">diff --git a/client/src/components/cos/tabs/MindTab.test.jsx b/client/src/components/cos/tabs/MindTab.test.jsxindex 3af970aef5..05223e0508 100644--- a/client/src/components/cos/tabs/MindTab.test.jsx+++ b/client/src/components/cos/tabs/MindTab.test.jsx@@ -407,7 +407,7 @@ describe('MindTab', () => {await user.click(taskAccess);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- { persistentMindCapabilities: { schemaVersion: 9, createTasks: true, manageMind: false, manageToolRecipes: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },+ { persistentMindCapabilities: { schemaVersion: 10, createTasks: true, fileIssues: false, manageMind: false, manageToolRecipes: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },{ silent: true },));expect(screen.getAllByText(/code review then merge/i).length).toBeGreaterThan(0);diff --git a/client/src/pages/PersistentMindTools.jsx b/client/src/pages/PersistentMindTools.jsxindex 39217c7c62..228bc42407 100644--- a/client/src/pages/PersistentMindTools.jsx+++ b/client/src/pages/PersistentMindTools.jsx@@ -38,6 +38,7 @@ export default function PersistentMindTools({ onCapabilitiesChange, onSavingChanconst tools = Array.isArray(data?.tools) ? data.tools : [];const taskCatalog = data?.taskCatalog;+ const managedApps = data?.managedApps;const grantedCount = tools.filter((tool) => tool.granted === true).length;const handleCapabilitiesSavingChange = (saving) => {setCapabilitiesSaving(saving);@@ -48,13 +49,13 @@ export default function PersistentMindTools({ onCapabilitiesChange, onSavingChansetData((current) => current ? {...current,capabilities,- taskCatalog: capabilities.createTasks && current.taskCatalog ? {- ...current.taskCatalog,- apps: (current.taskCatalog.apps || []).map((app) => ({+ taskCatalog: capabilities.createTasks ? current.taskCatalog : null,+ managedApps: (capabilities.createTasks || capabilities.fileIssues) && current.managedApps+ ? current.managedApps.map((app) => ({...app,granted: Array.isArray(capabilities.allowedAppIds) ? capabilities.allowedAppIds.includes(app.id) : true,- })),- } : null,+ }))+ : null,semanticTools: (current.semanticTools || []).map((tool) => ({...tool,granted: tool.recipe?.available !== false@@ -66,8 +67,10 @@ export default function PersistentMindTools({ onCapabilitiesChange, onSavingChan})),} : current);onCapabilitiesChange?.(capabilities);- if (capabilities.createTasks && !data?.taskCatalog) load();- else if (!capabilities.createTasks) setLoading(false);+ // A grant the page has no catalog for yet needs a real reload; turning both+ // off leaves nothing to fetch.+ if ((capabilities.createTasks && !data?.taskCatalog) || (capabilities.fileIssues && !data?.managedApps)) load();+ else if (!capabilities.createTasks && !capabilities.fileIssues) setLoading(false);};return (@@ -122,7 +125,7 @@ export default function PersistentMindTools({ onCapabilitiesChange, onSavingChan<PersistentMindTaskAccessControlscapabilities={data.capabilities}disabled={capabilitiesSaving}- taskCatalog={taskCatalog}+ managedApps={managedApps}onSaved={updateCapabilities}onSavingChange={handleCapabilitiesSavingChange}/>@@ -148,7 +151,7 @@ export default function PersistentMindTools({ onCapabilitiesChange, onSavingChan<div><h3 className="text-xs font-semibold uppercase tracking-wide text-port-text-muted">Target apps</h3><ul className="mt-2 space-y-2 text-sm text-port-text">- {(taskCatalog.apps || []).map((app) => (+ {(managedApps || []).map((app) => (<li key={app.id} className="rounded border border-port-border px-3 py-2"><Link to={`/apps/${encodeURIComponent(app.id)}/automation`} className="text-port-accent hover:underline">{app.name}</Link><span className={`ml-2 rounded-full border px-2 py-0.5 text-[11px] ${app.granted === false ? 'border-port-border text-port-text-muted' : 'border-port-success/40 text-port-success'}`}>{app.granted === false ? 'Not authorized' : 'Authorized'}</span>diff --git a/client/src/pages/PersistentMindTools.test.jsx b/client/src/pages/PersistentMindTools.test.jsxindex feaf2f22f4..406f22545a 100644--- a/client/src/pages/PersistentMindTools.test.jsx+++ b/client/src/pages/PersistentMindTools.test.jsx@@ -32,6 +32,7 @@ const response = (overrides = {}) => ({}],boundaries: ['No arbitrary shell or file-system access'],taskCatalog: null,+ managedApps: null,...overrides,});@@ -57,7 +58,7 @@ describe('PersistentMindTools', () => {expect(screen.getByRole('button', { name: 'New recipe' })).toBeEnabled();await user.click(grant);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({- persistentMindCapabilities: expect.objectContaining({ schemaVersion: 9, manageToolRecipes: true, readPortos: false }),+ persistentMindCapabilities: expect.objectContaining({ schemaVersion: 10, manageToolRecipes: true, readPortos: false }),}, { silent: true }));await user.click(screen.getByRole('checkbox', { name: 'Allow bounded PortOS reads' }));await waitFor(() => expect(api.updateCosConfig).toHaveBeenLastCalledWith({@@ -82,7 +83,7 @@ describe('PersistentMindTools', () => {expect(toggle).not.toBeChecked();await userEvent.setup().click(toggle);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({- persistentMindCapabilities: expect.objectContaining({ schemaVersion: 9, visitEidoversePeers: true, manageEidoverse: false }),+ persistentMindCapabilities: expect.objectContaining({ schemaVersion: 10, visitEidoversePeers: true, manageEidoverse: false }),}, { silent: true }));});@@ -102,10 +103,8 @@ describe('PersistentMindTools', () => {.mockResolvedValueOnce(response({capabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false },tools: [{ ...response().tools[0], granted: true }],- taskCatalog: {- apps: [{ id: 'example-app', name: 'Example App', planOnly: true }],- providers: [{ id: 'codex', name: 'Codex', type: 'cli', models: [{ id: 'gpt-5', efforts: ['low', 'high'] }] }],- },+ taskCatalog: { providers: [{ id: 'codex', name: 'Codex', type: 'cli', models: [{ id: 'gpt-5', efforts: ['low', 'high'] }] }] },+ managedApps: [{ id: 'example-app', name: 'Example App', planOnly: true, forge: 'github', granted: true }],}));renderPage();@@ -113,7 +112,7 @@ describe('PersistentMindTools', () => {await user.click(toggle);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(- { persistentMindCapabilities: { schemaVersion: 9, createTasks: true, manageMind: false, manageToolRecipes: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },+ { persistentMindCapabilities: { schemaVersion: 10, createTasks: true, fileIssues: false, manageMind: false, manageToolRecipes: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] } },{ silent: true },));expect(await screen.findByText(/persistent-mind capabilities granted/)).toHaveTextContent('1 of 1');@@ -133,8 +132,9 @@ describe('PersistentMindTools', () => {await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({ persistentMindCapabilities: {- schemaVersion: 9,+ schemaVersion: 10,createTasks: false,+ fileIssues: false,manageMind: true,manageToolRecipes: false,manageEidoverse: false,@@ -155,13 +155,11 @@ describe('PersistentMindTools', () => {api.getPersistentMindTools.mockResolvedValueOnce(response({capabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false },tools: [{ ...response().tools[0], granted: true }],- taskCatalog: {- apps: [- { id: 'example-app', name: 'Example App', planOnly: false, granted: true },- { id: 'second-app', name: 'Second App', planOnly: true, granted: true },- ],- providers: [],- },+ taskCatalog: { providers: [] },+ managedApps: [+ { id: 'example-app', name: 'Example App', planOnly: false, forge: null, granted: true },+ { id: 'second-app', name: 'Second App', planOnly: true, forge: 'github', granted: true },+ ],}));renderPage();@@ -171,8 +169,9 @@ describe('PersistentMindTools', () => {await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({ persistentMindCapabilities: {- schemaVersion: 9,+ schemaVersion: 10,createTasks: true,+ fileIssues: false,manageMind: false,manageToolRecipes: false,manageEidoverse: false,@@ -210,13 +209,47 @@ describe('PersistentMindTools', () => {resolveCatalog(response({capabilities: { schemaVersion: 3, createTasks: true, manageMind: false, readPortos: false, writePortos: false },tools: [{ ...response().tools[0], granted: true }],- taskCatalog: { apps: [{ id: 'stale-app', name: 'Stale App', planOnly: false }], providers: [] },+ taskCatalog: { providers: [] },+ managedApps: [{ id: 'stale-app', name: 'Stale App', planOnly: false, forge: null, granted: true }],}));await waitFor(() => expect(toggle).not.toBeChecked());expect(screen.queryByText('Available task filing choices')).not.toBeInTheDocument();});+ it('grants issue filing independently and scopes it with the shared managed-app roster', async () => {+ const user = userEvent.setup();+ api.getPersistentMindTools+ .mockResolvedValueOnce(response())+ .mockResolvedValueOnce(response({+ capabilities: { schemaVersion: 10, createTasks: false, fileIssues: true },+ // The roster carries the PLAN.md app too, so narrowing the allowlist+ // here cannot silently revoke an app the task grant would need.+ managedApps: [+ { id: 'example-app', name: 'Example App', planOnly: true, forge: 'github', granted: true },+ { id: 'plan-app', name: 'Plan App', planOnly: false, forge: null, granted: true },+ ],+ }));+ renderPage();++ const toggle = await screen.findByRole('checkbox', { name: /Allow mind to read and file GitHub\/GitLab issues/ });+ expect(toggle).not.toBeChecked();+ await user.click(toggle);++ await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith(+ { persistentMindCapabilities: expect.objectContaining({ schemaVersion: 10, fileIssues: true, createTasks: false }) },+ { silent: true },+ ));++ const planApp = await screen.findByRole('checkbox', { name: 'Plan App' });+ expect(screen.getByText(/No forge tracker/)).toBeInTheDocument();+ await user.click(planApp);+ await waitFor(() => expect(api.updateCosConfig).toHaveBeenLastCalledWith(+ { persistentMindCapabilities: expect.objectContaining({ fileIssues: true, allowedAppIds: ['example-app'] }) },+ { silent: true },+ ));+ });+it('keeps the failure visible instead of presenting an empty inventory', async () => {api.getPersistentMindTools.mockRejectedValue(new Error('Server unreachable'));renderPage();@@ -238,8 +271,9 @@ describe('PersistentMindTools', () => {await user.click(callToggle);await waitFor(() => expect(api.updateCosConfig).toHaveBeenCalledWith({ persistentMindCapabilities: {- schemaVersion: 9,+ schemaVersion: 10,createTasks: false,+ fileIssues: false,manageMind: false,manageToolRecipes: false,manageEidoverse: false,diff --git a/docs/API_TOOL_CONTRACT.md b/docs/API_TOOL_CONTRACT.mdindex 0ee6e50cbb..a4c1bf6353 100644--- a/docs/API_TOOL_CONTRACT.md+++ b/docs/API_TOOL_CONTRACT.md@@ -18,8 +18,9 @@ The current source contains:for the lifetime of the server process.- A Socket.IO inventory derived from server and client call sites on first use,then cached the same way.-- 22 provider-neutral semantic tools: one `cos.create-task` tool and 21- semantic adapters inherited from the voice registry.+- 24 provider-neutral semantic tools: one `cos.create-task` tool, the+ `issues.list` / `issues.file` forge pair, and 21 semantic adapters+ inherited from the voice registry.- Five read-only context tools on the Agent Tools MCP transport. The MCPtransport may additionally advertise the 21 semantic adapters and eligiblemachine-local saved read recipes when their independent grants are enabled.@@ -151,10 +152,23 @@ is authoritative for descriptions and JSON Schema.| `catalog.search` | `catalog_lookup` | `query`; optional `type`, `limit` | read |All 21 entries are scope-eligible for `agent`, `ui`, and `voice`; the-Persistent Mind `mind` scope additionally includes `cos.create-task`. The-task tool is not in the Agent MCP catalog. It is a Persistent Mind-only-capability and validates its app, provider, model, effort, mode, required-checks, tracker, readiness, and landing policy before queueing.+Persistent Mind `mind` scope additionally includes `cos.create-task`,+`issues.list`, and `issues.file`. None of the three is in the Agent MCP+catalog. The task tool validates its app, provider, model, effort, mode,+required checks, tracker, readiness, and landing policy before queueing.++### Forge issues++`issues.list` and `issues.file` are gated on the separate default-off+`fileIssues` grant and are the queueing lane for an install with no coding+agent attached. Both re-check the grant after inference and accept only a+managed app that is in the mind's shared `allowedAppIds` allowlist AND whose+resolved work tracker is GitHub or GitLab. `issues.file` requires both+dispatch axes (`model`, `effort`), applies the `persistent-mind` and+`planner:<model>` attribution labels, accepts only a closed category-label+vocabulary, and refuses to file when the tracker could not be read — an+unreadable tracker never reads as an empty backlog. Editing, closing,+commenting on, assigning, and relabeling an existing issue are out of scope.### Saved read recipes@@ -262,7 +276,7 @@ REST/OpenAPI route inventory ──> discovery only; raw routes are never tools| Caller | Server-derived authority | Default | Allowed mutation path ||---|---|---|---|-| Persistent Mind | `scope: mind`, persisted capability grant | off | `cos.create-task`, semantic writes when separately granted |+| Persistent Mind | `scope: mind`, persisted capability grant | off | `cos.create-task`, `issues.file`, semantic writes when separately granted || Agent MCP | `scope: agent`, Agent Tools action and saved-recipe grants | off | semantic writes when separately granted; saved recipes can orchestrate only granted agent-scope reads || HTTP registry | `scope: ui`, PortOS auth context | reads may be anonymous on a passwordless install | writes require an authenticated PortOS session || Voice adapter | existing voice pipeline context | existing voice policy | existing voice-side confirmation/pipeline controls |@@ -278,7 +292,8 @@ exposable merely because they appear in the internal OpenAPI inventory.1. **Resolved documentation drift.** The prior unified spec said 2,066 HTTPoperations, 23 Persistent Mind tools, 22 semantic tools, and a `cursor`catalog query. The current generated inventory is 2,069 operations; the- runtime registry is 22 tools total (21 semantic plus `cos.create-task`),+ runtime registry is 24 tools total (21 semantic plus `cos.create-task`,+ `issues.list`, and `issues.file`),and the implemented catalog query is `scope`, `intent`, and `format`.The point-in-time spec's implemented-foundation text is corrected in thisPR.diff --git a/server/lib/README.md b/server/lib/README.mdindex 3e34a1a340..35324a439c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -60,6 +60,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `persistentMind.js` | Pure persistent-CoS-mind runtime state: default-off durable shape, normalization, FIFO-message/self-wake selection, interrupted-wake requeue, accepted-route fingerprints/receipts, image-work rollback guard, bounded exponential backoff, watchdog staleness, and next-wake projection. || `persistentMindCapabilities.js` | Default-off persistent-mind action grants plus bounded typed CoS-task, private-Eidoverse, and self-cleanup contracts (app/provider/model/effort, PR completion policy, the optional exact provider/model task allowlist, and mind-owned context scopes). || `cosToolContracts.js` | Provider-neutral `portos_tool` catalog/call schema version, request-id and per-turn bounds, catalog query formats, and Persistent Mind tool-call shape. |+| `persistentMindIssues.js` | Persistent-mind forge-issue contracts: bounded list/file schemas, the required-both dispatch axes, the closed category-label vocabulary with its lazily-created colors, the `persistent-mind` attribution label, and the title key the duplicate guard compares on. || `persistentMindTrajectory.js` | Pure persistent-mind trajectory vocabulary, sequence cursor parsing, replay projection, provenance-tagged rollup validation, bounded strictly-allowlisted per-provider-call execution receipts (route, run id, elapsed time, outcome, usage that stays `unknown` rather than zero) with their safe public projection, and hard-budget context assembly with explicit empty/missing/failed/stale summary states. || `persistentMindProfile.js` | Versioned, default-off persistent-mind provider profile (`enabled`, provider/model/effort, text interface, maximum quiet interval), its strict API schema, duration resolver, and safe partial-update merge that clears model/effort on a provider switch. || `persistentMindMemory.js` | Persistent Mind memory protection schema, durable tag encoding, public projection, and protected-first context ordering. |@@ -308,6 +309,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `createKeyCachedQueue.js` | Per-KEY serialized async work queue (sibling to `fileWriteQueue.js`'s single tail). `createKeyCachedQueue()` returns `queue(key, work)` that chains each `work` thunk onto the prior in-flight promise for that `key` — same-key work runs one-after-another (later sees earlier's committed result), different keys run concurrently. Self-pruning tail Map; `work` runs on both fulfil and reject so one failure can't stall the chain; carries `.clear()` for test reset. Used by the media-job completion hooks (writers-room / catalog / music-video scene-image attach) to serialize per-record. || `createNewestWinsGuard.js` | Newest-render-wins ordering guard for out-of-order async completions. `createNewestWinsGuard()` returns `{ isStale(key, at), mark(key, at), clear() }` — tracks the newest applied `queuedAt` per slot `key` so an older render completing after a newer one is dropped (`isStale` true) instead of clobbering the newer frame. ISO timestamps compare as strings; absent `at` is never stale. Used by `createMediaJobImageHook`'s opt-in guard and the catalog hook's portrait slot. || `fileWriteQueue.js` | Serialize read-modify-write cycles so they don't interleave. `createFileWriteQueue()` → single-tail `queue(fn)` for one shared file; `createRecordWriteQueue(assertId?)` → id-keyed `queueRecordWrite(id, fn)` where same-id cycles serialize and different-id cycles run in parallel (the queue the PG/file store facades use for `collectionStore.queueRecordWrite` parity); `createKeyedFileWriteQueue()` → `queueKeyedWrite(key, fn)` that collapses the pipeline stage stores' hand-rolled `Map` + per-key `createFileWriteQueue` factory (falsy keys → shared `'__unknown__'` tail; self-pruning via `createKeyCachedQueue`). |+| `forgeIssueCli.js` | Pure `gh`/`glab` issue-filing argument shapes and output parsing — `forgeLabelCreateArgs`, `forgeIssueCreateArgs`, `parseCreatedForgeIssue` — so the two CLIs' body-flag, label-attachment, and label-create disagreements have one definition. || `forgeIssueState.js` | `normalizeIssueState(state)` — collapse a forge issue/PR/MR state string to `open`/`closed`. GitHub reports `OPEN`/`CLOSED`; GitLab reports `opened`/`closed`/`locked`; anything unrecognized is treated as open so an unfamiliar state can never read as "already resolved". Shared by `layeredIntelligence/forgeFiler.js` and `services/blockedIssueReconcile.js`. || `imageClean.js` | `cleanImageBuffer(buf, { metadata, denoise })` (composable opt-in pipeline: lossless metadata/C2PA strip + optional median/sharpen denoise) · `stripPngMetadataChunks` / `stripPngC2PAChunk` (lossless PNG-chunk removers) · `compositeIgnoreZone(base, original, mask, { feather })` (preserve-region compositing: restore original pixels into a feathered mask over a diffused result) · `autoCleanGeneratedImage` (in-place clean for post-generation hook). HTTP route in `routes/imageClean.js` wraps `cleanImageBuffer` and appends a CPU light diffusion pass (`applyLightRegen` from `services/imageGen/regen.js`) for the `diffusion=light` SynthID-disruption step. || `imageFrameStats.js` | Degenerate-frame classifier (#4173) — `describeFrameStats(bufferOrPath)` runs one `sharp` `.stats()` decode and returns `{ ok, reason, perChannel }`, rejecting `solid-fill` (every colour channel stdev under `SOLID_FILL_STDEV_EPSILON`), `fully-transparent` (alpha max 0) and `near-empty` (greyscale entropy under `NEAR_EMPTY_ENTROPY_FLOOR`), except when a non-opaque alpha channel carries a substantial silhouette itself. Deliberately NOT a quality judge: a legitimately dark or minimalist render keeps real per-channel variance and is accepted. `ok` is three-valued — `true`/`false`/`null`, where `null` means could-not-measure (undecodable buffer, or under `MIN_JUDGEABLE_PIXELS`) and must never read as degenerate; gate on `isDegenerateFrame(stats)` / `ok === false`, never `!ok`. Called by the Image Gen provider completion seams, sprite reference normalization, and `visionTest.js` (so a paid vision call is never spent on a blank frame). A **buffer** verdict is memoized on the sha256 of its bytes (#6004) — the probe costs ~4ms regardless of pixel count and the sprite compiler re-probes identical frames dozens of times per run; a **path** is never memoized (the file behind it can change), so hand it bytes you already read. `stats-unavailable` is never memoized either — that branch catches transient probe failures too, and pinning `ok: null` on valid bytes would disable the gate for them. `__resetFrameStatsCache()` drops the memo in tests. |@@ -571,7 +573,7 @@ pm` default, `NPM_CONFIG_PREFIX`, nvm/Volta) installed `codex` successfully and| `syncManifest.js` | Wire contract for the snapshot-sync MANIFEST leg — the fix for a category that is always dirty AND a map of per-instance slots (`usage`), where one instance advancing dragged every other instance's digest across the wire. `isManifestEnvelope(value)` validates a `{ data: { instances }, checksum }` response (a legacy peer that 404s the endpoint fails it, and the puller falls back to the whole snapshot); `diffManifestSlots(remoteInstances, localInstances)` returns the sorted slot ids whose REMOTE LWW stamp is strictly newer than ours — exactly the slots worth fetching. Comparison goes through `lwwTimestamp.js`, so a tie breaks to what we already hold. Consumed by `syncOrchestrator.syncDataCategoryFromPeer`; served by `dataSync.getManifest`. || `mapWithConcurrency.js` | Generic bounded-concurrency async mapper that preserves input order while capping in-flight work. || `markedSection.js` | Marker-delimited section replacement (pure). `buildMarkers(id)` → `{ start, end }` HTML-comment marker pair; `replaceMarkedSection(content, body, markers)` splices/replaces/removes an auto-generated region without touching surrounding user content (idempotent); `extractMarkedSection` / `hasMarkedSection` read it back. Powers the daily-log activity-digest auto-drafts (#2155) via `brainJournal.upsertAutoSection()`. |-| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate). |+| `objects.js` | Object utilities — `deepMerge` (recursive merge w/ array replacement), `isPlainObject` (non-null, non-array `object` guard for JSON / LLM payloads), `POLLUTING_KEYS` (shared `__proto__`/`constructor`/`prototype` denylist for sanitizers), `canonicalStringify` (recursive sorted-key JSON serialization for cross-machine content hashing), `isEmptyScalar` (true for null/undefined/whitespace-string/empty-array — merge gap-fill gate), `boundedByJsonChars` (longest prefix of a list whose JSON encoding fits a character budget — the shared prompt-catalog truncation loop). || `openapiSpec.js` | Builds two OpenAPI 3.0.3 documents: the Settings-controlled exposed public surface and the complete internal HTTP inventory. Detailed operations reuse canonical Zod contracts; generated operations are visibly labeled rather than claiming unmodeled schemas. || `openapiDowngrade.js` | `OPENAPI_VERSION` plus `toOpenApi30Schema` / `toOpenApi30Operation`, which rewrite Zod's draft-2020-12 output (null unions, numeric exclusive bounds, `const`, tuples, `propertyNames`) into the OpenAPI 3.0.3 dialect. Apply ONLY at the OpenAPI document boundary — the AsyncAPI payloads, CoS provider tool definitions, and tool resource read the same schemas as plain JSON Schema, where these rewrites silently widen bounds and drop null branches. || `orchestrationProfile.js` | Orchestrated CoS execution (#5992) — `ORCHESTRATION_MODES` / `ORCHESTRATION_ROLES` (architect, implementer, reviewer), `normalizeOrchestrationProfile` / `normalizeOrchestrationMode`, `isOrchestratedTask` / `roleAssignment` (both inert on a `direct` task, so a stored profile stays opt-in), the six-part `SPEC_PARTS` contract a delegated context-free lane needs, plus `parseReasoningDirective` (an unsupported rung is an error, never a silent downgrade). |diff --git a/server/lib/errorHandler.js b/server/lib/errorHandler.jsindex c3e3a4ebaa..ea3f10b382 100644--- a/server/lib/errorHandler.js+++ b/server/lib/errorHandler.js@@ -80,6 +80,17 @@ export class ServerError extends Error {* ServerError shape that the rest of PortOS speaks. Pass the result of* `schema.safeParse(...)` after confirming `.success === false`.*/+/**+ * A thrown value reduced to one bounded, model-safe sentence.+ *+ * Typed capability results carry the failure reason back into a prompt, so the+ * string has to be short and has to exist even when what was thrown is not an+ * Error. Shared rather than re-declared per capability: the cap and the+ * fallback are the contract, not a local detail.+ */+export const boundedErrorMessage = (error, fallback = 'Request failed', maxChars = 300) =>+ String(error?.message || error || fallback).slice(0, maxChars);+export function failValidation(parsed) {throw new ServerError(`Validation failed: ${parsed.error.issues.map((i) => `${i.path.join('.')}: ${i.message}`).join(', ')}`,diff --git a/server/lib/forgeIssueCli.js b/server/lib/forgeIssueCli.jsnew file mode 100644index 0000000000..6224d1fdbf--- /dev/null+++ b/server/lib/forgeIssueCli.js@@ -0,0 +1,42 @@+/**+ * Pure argument shapes and output parsing for `gh` / `glab` issue filing.+ *+ * Two CLIs disagree about the same three things, and every filer that has+ * rediscovered that disagreement has re-encoded it: the body flag+ * (`--body` vs `--description`), how labels attach (repeated `--label` flags vs+ * one comma-joined value), and how a label is created (gh takes the name+ * positionally with a bare hex color and `--force`; glab needs `--name` and a+ * `#`-prefixed color). Keeping those here means a new filer inherits the rules+ * instead of learning them from a failed 422.+ *+ * No child-process or network access — callers own the exec (`runCli` in the+ * Layered Intelligence loop, `execGh`/`execGlab` elsewhere).+ */++/** `label create` arguments for one `{ name, color, description }` spec. */+export const forgeLabelCreateArgs = (cli, spec, { repo = null } = {}) => (cli === 'glab'+ ? ['label', 'create', '--name', spec.name, '--color', `#${spec.color}`, '--description', spec.description]+ : ['label', 'create', spec.name, ...(repo ? ['--repo', repo] : []),+ '--color', spec.color, '--description', spec.description, '--force']);++/** `issue create` arguments for one issue. */+export const forgeIssueCreateArgs = (cli, { title, body, labels = [], repo = null } = {}) => (cli === 'glab'+ ? ['issue', 'create', '--title', title, '--description', body,+ ...(labels.length ? ['--label', labels.join(',')] : [])]+ : ['issue', 'create', ...(repo ? ['--repo', repo] : []), '--title', title, '--body', body,+ ...labels.flatMap((name) => ['--label', name])]);++/**+ * The created issue's `{ url, number }` from a successful `issue create` stdout.+ *+ * Both CLIs print the web URL. `number` is null when the trailing path segment+ * is not a number, and `url` falls back to the raw trimmed stdout — the issue+ * exists either way, so an unparseable line must not turn a real creation into+ * a reported failure.+ */+export const parseCreatedForgeIssue = (stdout) => {+ const text = String(stdout || '').trim();+ const url = text.match(/(https?:\/\/\S+)/)?.[1] || text;+ const number = Number(url.match(/(\d+)\s*$/)?.[1]);+ return { url, number: Number.isInteger(number) ? number : null };+};diff --git a/server/lib/importScoping.test.js b/server/lib/importScoping.test.jsindex 32955a2d6c..3fb560019c 100644--- a/server/lib/importScoping.test.js+++ b/server/lib/importScoping.test.js@@ -617,7 +617,17 @@ describe('deferred imports stay deferred (#6156)', () => {// three pure lines the write-back path was importing the whole 81-module// `services/appListEnrichment.js` for — down into that leaf, which// re-exports it for its existing callers.-const MAX_STATIC_INSTANTIATIONS = 104705;+//+// Raised to 106,200 for the Persistent Mind forge-issue capability, and to+// restore the documented ~1.5k of headroom. The capability's own net share is+// +34, because the new suite's closure (~94) is most of the way offset by the+// managed-app roster it shares with the task capability, which replaced a second+// app/tracker reader. The headroom is the larger half of this raise: #7357 above+// had already landed the number at EXACTLY the measured total, so any addition+// at all failed it — the same zero-headroom state #6305 raised it out of, and+// that is what makes this a budget rather than a high-water mark. Measured after+// both changes: 104,739.+const MAX_STATIC_INSTANTIATIONS = 106200;const SKIP_DIRS = new Set(['node_modules', 'coverage', 'dist', 'data']);diff --git a/server/lib/index.js b/server/lib/index.jsindex 54e22e4afd..3e589bb273 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -270,6 +270,7 @@ export * from './agentInstructionsFile.js';export * from './fileCore.js';export * as fileUtils from './fileUtils.js';export * from './fileWriteQueue.js';+export * from './forgeIssueCli.js';export * from './forgeIssueState.js';export * from './portosEnv.js';export * from './portosRootPlaceholder.js';@@ -307,6 +308,7 @@ export * from './agentRunReconcile.js';export * from './agentRegistrationRecord.js';export * from './persistentMind.js';export * from './persistentMindCapabilities.js';+export * from './persistentMindIssues.js';export * from './persistentMindTrajectory.js';export * from './persistentMindProfile.js';export * from './persistentMindMemory.js';diff --git a/server/lib/mindToolRecipes.test.js b/server/lib/mindToolRecipes.test.jsindex 859e547270..b46982e908 100644--- a/server/lib/mindToolRecipes.test.js+++ b/server/lib/mindToolRecipes.test.js@@ -74,6 +74,6 @@ describe('closed, governed recipe definition boundary', () => {it('defaults the definition grant off and preserves it across old capability updates', () => {expect(createDefaultPersistentMindCapabilities().manageToolRecipes).toBe(false);expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 8, readPortos: true }).success).toBe(true);- expect(mergePersistentMindCapabilities({ manageToolRecipes: true }, { schemaVersion: 3, readPortos: false })).toMatchObject({ schemaVersion: 9, manageToolRecipes: true, readPortos: false });+ expect(mergePersistentMindCapabilities({ manageToolRecipes: true }, { schemaVersion: 3, readPortos: false })).toMatchObject({ schemaVersion: 10, manageToolRecipes: true, readPortos: false });});});diff --git a/server/lib/objects.js b/server/lib/objects.jsindex b610c16c8d..14cbae0744 100644--- a/server/lib/objects.js+++ b/server/lib/objects.js@@ -110,3 +110,27 @@ export const canonicalStringify = (value) => {}return JSON.stringify(value);};++/**+ * The longest prefix of `items` whose JSON encoding fits `maxChars`.+ *+ * The shape every prompt-catalog builder needs: fill until the serialized form+ * would exceed a character budget, then stop. `wrap` lets a caller measure the+ * envelope the items will actually be embedded in rather than the bare array,+ * so a budget covering a whole catalog object stays accurate.+ *+ * Measured on the growing prefix, not estimated per item: an item's cost+ * depends on the separators and escaping around it, and a prompt budget that+ * under-counts is a truncated payload the model reads as complete.+ */+export const boundedByJsonChars = (items, maxChars, wrap = (kept) => kept) => {+ const kept = [];+ for (const item of Array.isArray(items) ? items : []) {+ kept.push(item);+ if (JSON.stringify(wrap(kept)).length > maxChars) {+ kept.pop();+ break;+ }+ }+ return kept;+};diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.jsindex d581139968..447e2bb8ef 100644--- a/server/lib/persistentMindCapabilities.js+++ b/server/lib/persistentMindCapabilities.js@@ -14,12 +14,12 @@ import {portosSemanticToolGrantsSchema,} from './cosToolContracts.js';-export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 9;+export const PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION = 10;// Every wire version this server still accepts on input. Installs upgrade on// their own schedule, so a browser bundle (or a route caller) pinned at an// older version must keep being able to toggle the grants it already knows// about; normalization always writes the current version forward.-const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4, 5, 6, 7, 8, 9]);+const ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS = Object.freeze([2, 3, 4, 5, 6, 7, 8, 9, 10]);export const PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS = Object.freeze({MAX_ENTRIES: 200,@@ -81,6 +81,21 @@ export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze(['Plan & File Issue requests use the existing issue-only planning contract',],}),+ Object.freeze({+ id: 'forge.file-issue',+ capability: 'fileIssues',+ name: 'Read and file GitHub/GitLab issues',+ description: 'Read a managed app\'s open issues and file new ones on its GitHub or GitLab tracker — the queueing lane that still works when no coding agent is attached to this machine.',+ kind: 'typed-action',+ defaultEnabled: false,+ guardrails: [+ 'Only managed apps in the Managed app access list whose resolved work tracker is GitHub or GitLab',+ 'Read and create only — no editing, closing, commenting, assigning, or labeling existing issues',+ 'Every filed issue carries both required dispatch axes plus the persistent-mind and planner attribution labels',+ 'An unreadable tracker refuses the file instead of risking a duplicate, and an exact title match reuses the existing issue',+ 'Issue bodies are the mind\'s own prose; no repository paths, credentials, or private records are attached',+ ],+ }),Object.freeze({id: 'portos.read',capability: 'readPortos',@@ -212,6 +227,7 @@ export const persistentMindCapabilitiesSchema = portosSemanticToolGrantsSchema.e.refine((value) => ACCEPTED_CAPABILITIES_SCHEMA_VERSIONS.includes(value), 'unsupported persistent mind capabilities schema version').optional(),createTasks: z.boolean().optional(),+ fileIssues: z.boolean().optional(),manageMind: z.boolean().optional(),manageToolRecipes: z.boolean().optional(),callUser: z.boolean().optional(),@@ -222,9 +238,11 @@ export const persistentMindCapabilitiesSchema = portosSemanticToolGrantsSchema.e// entries are configured, requests must name one of these exact pairs.taskModelAllowlist: z.array(persistentMindTaskModelAllowlistEntrySchema).max(PERSISTENT_MIND_TASK_MODEL_ALLOWLIST_LIMITS.MAX_ENTRIES).optional(),- // Omitted preserves the legacy grant to every runnable managed app. An- // explicit list lets the user narrow that grant without changing the typed- // task capability itself.+ // The mind's managed-app allowlist, honored by BOTH the task grant and the+ // issue grant — one control over "which repositories is this mind allowed to+ // touch at all", rather than a second list that could silently disagree.+ // Omitted preserves the legacy grant to every runnable managed app, so an+ // upgrading install keeps the task scope it already had.allowedAppIds: z.array(z.string().trim().min(1).max(PERSISTENT_MIND_TASK_LIMITS.appIdChars)).max(PERSISTENT_MIND_TASK_LIMITS.maxAllowedAppIds).optional(),});@@ -282,6 +300,7 @@ export function createDefaultPersistentMindCapabilities() {return {schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,createTasks: false,+ fileIssues: false,manageMind: false,manageToolRecipes: false,manageEidoverse: false,@@ -342,6 +361,7 @@ export function normalizePersistentMindCapabilities(raw) {return {schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,createTasks: source.createTasks === true,+ fileIssues: source.fileIssues === true,manageMind: source.manageMind === true,manageToolRecipes: source.manageToolRecipes === true,callUser: source.callUser === true,diff --git a/server/lib/persistentMindCapabilities.test.js b/server/lib/persistentMindCapabilities.test.jsindex 00e4b963e8..2a627d2bed 100644--- a/server/lib/persistentMindCapabilities.test.js+++ b/server/lib/persistentMindCapabilities.test.js@@ -18,6 +18,7 @@ describe('persistent mind capabilities', () => {expect.objectContaining({ capability: 'manageToolRecipes', defaultEnabled: false }),expect.objectContaining({ capability: 'chooseThinkingPreset', defaultEnabled: false }),expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', defaultEnabled: false }),+ expect.objectContaining({ id: 'forge.file-issue', capability: 'fileIssues', kind: 'typed-action', defaultEnabled: false }),expect.objectContaining({ id: 'portos.read', capability: 'readPortos', defaultEnabled: false }),expect.objectContaining({ id: 'portos.write', capability: 'writePortos', defaultEnabled: false }),expect.objectContaining({ id: 'eidoverse.travel', capability: 'visitEidoversePeers', defaultEnabled: false }),@@ -40,7 +41,7 @@ describe('persistent mind capabilities', () => {expect(createDefaultPersistentMindCapabilities()).toMatchObject({ createTasks: false, manageMind: false, manageEidoverse: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false });// An install upgrading with the mind already running must gain no new// authority: stored config that predates the grant reads as false.- expect(normalizePersistentMindCapabilities({ schemaVersion: 3, createTasks: true })).toMatchObject({ callUser: false });+ expect(normalizePersistentMindCapabilities({ schemaVersion: 3, createTasks: true })).toMatchObject({ callUser: false, fileIssues: false });expect(normalizePersistentMindCapabilities(null)).toMatchObject({ createTasks: false, manageMind: false, manageEidoverse: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false });expect(normalizePersistentMindCapabilities({ createTasks: 'true', readPortos: 'true' })).toMatchObject({ createTasks: false, readPortos: false });});@@ -51,10 +52,11 @@ describe('persistent mind capabilities', () => {expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 3, callUser: true }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 5 }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 8 }).success).toBe(true);- expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 10 }).success).toBe(false);+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 10 }).success).toBe(true);+ expect(persistentMindCapabilitiesSchema.safeParse({ schemaVersion: 11 }).success).toBe(false);expect(persistentMindCapabilitiesSchema.safeParse({ taskModelAllowlist: [{ providerId: 'ollama', model: 'example-local' }] }).success).toBe(true);expect(normalizePersistentMindCapabilities({ schemaVersion: 2, createTasks: true }))- .toMatchObject({ schemaVersion: 9, createTasks: true, manageMind: false, manageEidoverse: false, callUser: false, adjustLocalContext: false });+ .toMatchObject({ schemaVersion: 10, createTasks: true, fileIssues: false, manageMind: false, manageEidoverse: false, callUser: false, adjustLocalContext: false });expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: ['example-app', 'second-app'] }).success).toBe(true);expect(persistentMindCapabilitiesSchema.safeParse({ allowedAppIds: Array.from({ length: 51 }, (_, index) => `app-${index}`) }).success).toBe(false);expect(persistentMindCapabilitiesSchema.safeParse({ createTasks: true, shell: true }).success).toBe(false);diff --git a/server/lib/persistentMindIssues.js b/server/lib/persistentMindIssues.jsnew file mode 100644index 0000000000..547521bb20--- /dev/null+++ b/server/lib/persistentMindIssues.js@@ -0,0 +1,101 @@+/**+ * Contracts for the persistent mind's forge-issue capability.+ *+ * Filing an issue is the queueing lane that works on an install with no coding+ * agent attached: the mind cannot dispatch a CoS task there, but it can still+ * read the open backlog and write down work for whoever (or whatever) picks the+ * tracker up next. Keeping the schemas beside the capability catalog means the+ * tool registry, the route, and the settings UI describe one contract.+ *+ * Dispatch labels are REQUIRED on a filed issue, exactly as they are for a human+ * planner (AGENTS.md "Capture deferred work"): an issue with no `model:`/`effort:`+ * axis is not dispatchable, so the schema refuses to file one rather than letting+ * the backlog fill with work no runner can size.+ */++import { z } from 'zod';+import { DISPATCH_EFFORT_LEVELS, DISPATCH_MODEL_TIERS } from './dispatchLabels.js';++export const PERSISTENT_MIND_ISSUE_LIMITS = Object.freeze({+ appIdChars: 128,+ titleChars: 200,+ bodyChars: 12_000,+ labelChars: 60,+ maxCategoryLabels: 4,+ maxListLimit: 50,+ defaultListLimit: 20,+ // The listing is prompt context, not an issue reader: enough body to judge+ // overlap with what the mind is about to file, never the whole thread.+ bodyPreviewChars: 600,+ searchChars: 200,+});++/**+ * The marker label every mind-filed issue carries, so the backlog can be read by+ * author and a later wake can find its own earlier proposals without guessing+ * from prose.+ */+export const PERSISTENT_MIND_ISSUE_LABEL = 'persistent-mind';++/**+ * The category labels a mind-filed issue may carry, with the colors used to+ * create them lazily.+ *+ * A closed vocabulary rather than free text: `gh issue create --label` fails the+ * WHOLE call with a 422 when the repo has never defined the label, so an invented+ * name would not file a mislabeled issue — it would file nothing, and the mind+ * would read a forge error it cannot act on. Every name here is either a PortOS+ * convention label (`plan`) or a GitHub default.+ */+export const PERSISTENT_MIND_ISSUE_CATEGORY_LABELS = Object.freeze({+ plan: { color: '0E8A16', description: 'Committed backlog item' },+ bug: { color: 'D73A4A', description: "Something isn't working" },+ tests: { color: 'C5DEF5', description: 'Test coverage or harness work' },+ ux: { color: 'D4C5F9', description: 'User-experience change' },+ docs: { color: '0075CA', description: 'Documentation change' },+ chore: { color: 'FEF2C0', description: 'Maintenance work with no user-facing change' },+});++/**+ * Every label this capability may create, keyed by name, in the+ * `{ color, description }` shape `dispatchLabelSpec` returns for the labels IT+ * owns. The filer chains the two, so a label has exactly one definition and+ * neither table needs to know about the other.+ */+export const PERSISTENT_MIND_ISSUE_EXTRA_LABEL_SPECS = Object.freeze({+ [PERSISTENT_MIND_ISSUE_LABEL]: { color: '5319E7', description: 'Filed by the PortOS persistent mind' },+ ...PERSISTENT_MIND_ISSUE_CATEGORY_LABELS,+});++const appIdSchema = z.string().trim().min(1).max(PERSISTENT_MIND_ISSUE_LIMITS.appIdChars);++export const persistentMindIssueListSchema = z.object({+ appId: appIdSchema,+ limit: z.number().int().min(1).max(PERSISTENT_MIND_ISSUE_LIMITS.maxListLimit).optional(),+ // Substring match over title and body, applied locally to the fetched page —+ // the forge query stays one plain open-issue listing on both CLIs.+ search: z.string().trim().min(1).max(PERSISTENT_MIND_ISSUE_LIMITS.searchChars).optional(),+ label: z.string().trim().min(1).max(PERSISTENT_MIND_ISSUE_LIMITS.labelChars).optional(),+}).strict();++export const persistentMindIssueFileSchema = z.object({+ appId: appIdSchema,+ title: z.string().trim().min(1).max(PERSISTENT_MIND_ISSUE_LIMITS.titleChars),+ body: z.string().trim().min(1).max(PERSISTENT_MIND_ISSUE_LIMITS.bodyChars),+ // Two independent dispatch axes. Neither is derived from the other, and both+ // are required — see the module comment.+ model: z.enum([...DISPATCH_MODEL_TIERS]),+ effort: z.enum([...DISPATCH_EFFORT_LEVELS]),+ labels: z.array(z.enum(Object.keys(PERSISTENT_MIND_ISSUE_CATEGORY_LABELS)))+ .max(PERSISTENT_MIND_ISSUE_LIMITS.maxCategoryLabels).optional(),+}).strict();++/**+ * A title reduced to its comparable identity, for the duplicate guard: case,+ * punctuation, and spacing carry no meaning when deciding whether the mind is+ * about to re-file work already in the tracker.+ */+export const normalizeIssueTitleKey = (title) => String(title || '')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, ' ')+ .trim();diff --git a/server/routes/cosMindRoutes.js b/server/routes/cosMindRoutes.jsindex 381db6575e..67707f7b0c 100644--- a/server/routes/cosMindRoutes.js+++ b/server/routes/cosMindRoutes.js@@ -261,24 +261,31 @@ router.get('/mind/context', asyncHandler(async (_req, res) => {router.get('/mind/tools', asyncHandler(async (_req, res) => {const root = await loadState();const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);- const taskCatalog = capabilities.createTasks- ? await readPersistentMindTaskCatalog({ includeAllApps: true })- : null;- if (taskCatalog && Array.isArray(taskCatalog.apps)) {- const allowed = Array.isArray(capabilities.allowedAppIds) ? new Set(capabilities.allowedAppIds) : null;- taskCatalog.apps = taskCatalog.apps.map((app) => ({- ...app,- granted: !allowed || allowed.has(app.id),- }));- }const { getCosToolCatalog, readCosToolRecipeCatalog } = await import('../services/cosToolRegistry.js');- const recipes = await readCosToolRecipeCatalog({ scope: 'mind' });+ // The allowlist is shared by the task and issue grants, so the page gets ONE+ // roster carrying what each grant needs — `planOnly` for tasks, `forge` for+ // issues, `granted` for both. Loading it per grant would let either editor+ // narrow the list from a partial view and silently revoke the other's apps.+ const managedApps = capabilities.createTasks || capabilities.fileIssues+ ? import('../services/persistentMindManagedApps.js')+ .then(({ readPersistentMindManagedApps }) => readPersistentMindManagedApps())+ : null;+ const [taskCatalog, recipes, roster] = await Promise.all([+ capabilities.createTasks ? readPersistentMindTaskCatalog() : null,+ readCosToolRecipeCatalog({ scope: 'mind' }),+ managedApps,+ ]);res.json({semanticTools: getCosToolCatalog({ scope: 'mind', capabilities, recipes }).tools,schemaVersion: PERSISTENT_MIND_CAPABILITIES_SCHEMA_VERSION,capabilities,boundaries: PERSISTENT_MIND_TOOL_BOUNDARIES,- taskCatalog,+ // Providers and readiness only: the apps the mind may target come from the+ // roster, so the page never shows two lists that could disagree.+ taskCatalog: taskCatalog && { providers: taskCatalog.providers, providerReadiness: taskCatalog.providerReadiness },+ managedApps: roster && roster.map(({ id, name, planOnly, forge, fullName, granted }) => ({+ id, name, planOnly, forge, fullName, granted,+ })),tools: PERSISTENT_MIND_TOOL_CATALOG.map((tool) => ({...tool,granted: capabilities[tool.capability] === true,diff --git a/server/routes/cosMindRoutes.test.js b/server/routes/cosMindRoutes.test.jsindex 12df5e7164..18695a9f71 100644--- a/server/routes/cosMindRoutes.test.js+++ b/server/routes/cosMindRoutes.test.js@@ -28,6 +28,7 @@ const mocks = vi.hoisted(() => ({inspectPersistentMindRuntime: vi.fn(),readPersistentMindVisibility: vi.fn(),readPersistentMindTaskCatalog: vi.fn(),+ readPersistentMindManagedApps: vi.fn(),listMindToolRecipes: vi.fn(),resolveImageCapability: vi.fn(),cleanupPersistentMind: vi.fn(),@@ -66,6 +67,9 @@ vi.mock('../services/persistentMindMaintenance.js', () => ({vi.mock('../services/persistentMindTaskCapability.js', () => ({readPersistentMindTaskCatalog: mocks.readPersistentMindTaskCatalog,}));+vi.mock('../services/persistentMindManagedApps.js', () => ({+ readPersistentMindManagedApps: mocks.readPersistentMindManagedApps,+}));vi.mock('../services/mindToolRecipes.js', () => ({listRecipes: mocks.listMindToolRecipes,}));@@ -194,6 +198,9 @@ describe('persistent mind routes', () => {providers: [{ id: 'codex', name: 'Codex', type: 'cli', models: [{ id: 'gpt-5', efforts: ['low', 'high'] }] }],});mocks.listMindToolRecipes.mockResolvedValue({ recipes: [] });+ mocks.readPersistentMindManagedApps.mockResolvedValue([+ { id: 'demo-app', name: 'Demo App', planOnly: true, forge: 'github', fullName: 'example/demo', granted: true, repoPath: '/repos/demo' },+ ]);});it('requests an immediate manual wake', async () => {@@ -218,7 +225,7 @@ describe('persistent mind routes', () => {thinkingInterface: 'text',wakeIntervalMinutes: 30,},- capabilities: { schemaVersion: 9, createTasks: true, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },+ capabilities: { schemaVersion: 10, createTasks: true, fileIssues: false, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },harness: { type: 'api', recommendation: 'recommended' },imageCapability: { status: 'unknown' },autonomyMode: 'execute',@@ -312,8 +319,8 @@ describe('persistent mind routes', () => {expect.objectContaining({ name: 'eidoverse.status', granted: false, input_schema: expect.any(Object) }),expect.objectContaining({ name: 'cos.create-task', granted: true }),]),- schemaVersion: 9,- capabilities: { schemaVersion: 9, createTasks: true, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },+ schemaVersion: 10,+ capabilities: { schemaVersion: 10, createTasks: true, fileIssues: false, manageMind: false, manageEidoverse: false, visitEidoversePeers: false, callUser: false, adjustLocalContext: false, readPortos: false, writePortos: false, taskModelAllowlist: [] },boundaries: expect.arrayContaining([expect.stringMatching(/arbitrary shell/i)]),tools: expect.arrayContaining([expect.objectContaining({ id: 'cos.create-task', capability: 'createTasks', granted: true, defaultEnabled: false }),@@ -322,30 +329,52 @@ describe('persistent mind routes', () => {expect.objectContaining({ id: 'mind.cleanup', capability: 'manageMind', granted: false, defaultEnabled: false }),expect.objectContaining({ id: 'voice.call-user', capability: 'callUser', granted: false, defaultEnabled: false }),]),- taskCatalog: {- apps: [{ id: 'demo-app', planOnly: true }],- providers: [{ id: 'codex' }],- },+ // Providers only: the apps live on the one shared roster, so the page+ // cannot render two managed-app lists that disagree.+ taskCatalog: { providers: [{ id: 'codex' }] },+ managedApps: [{ id: 'demo-app', name: 'Demo App', planOnly: true, forge: 'github', granted: true }],});+ expect(res.body.taskCatalog.apps).toBeUndefined();+ // The roster never leaks a filesystem path to the browser.+ expect(res.body.managedApps[0].repoPath).toBeUndefined();expect(res.body.tools.find((tool) => tool.id === 'cos.create-task').guardrails).toEqual(expect.arrayContaining([expect.stringMatching(/isolated-worktree/i),]));});- it('marks revoked managed apps without removing them from the settings inventory', async () => {+ it('keeps revoked managed apps in the settings roster so they can be restored', async () => {mocks.loadState.mockResolvedValue({ config: {persistentMindCapabilities: { schemaVersion: 3, createTasks: true, allowedAppIds: [] },} });- mocks.readPersistentMindTaskCatalog.mockResolvedValue({- apps: [{ id: 'demo-app', name: 'Demo App', planOnly: true }],- providers: [],- });+ mocks.readPersistentMindManagedApps.mockResolvedValue([+ { id: 'demo-app', name: 'Demo App', planOnly: true, forge: 'github', fullName: 'example/demo', granted: false },+ ]);++ const res = await get('/mind/tools');++ expect(res.status).toBe(200);+ expect(res.body.managedApps).toEqual([+ { id: 'demo-app', name: 'Demo App', planOnly: true, forge: 'github', fullName: 'example/demo', granted: false },+ ]);+ });++ it('loads the shared roster for the issue grant alone, so its allowlist edits see every app', async () => {+ mocks.loadState.mockResolvedValue({ config: {+ persistentMindCapabilities: { schemaVersion: 10, createTasks: false, fileIssues: true },+ } });+ mocks.readPersistentMindManagedApps.mockResolvedValue([+ { id: 'demo-app', name: 'Demo App', planOnly: true, forge: 'github', fullName: 'example/demo', granted: true },+ { id: 'plan-app', name: 'Plan App', planOnly: false, forge: null, fullName: null, granted: true },+ ]);const res = await get('/mind/tools');expect(res.status).toBe(200);- expect(res.body.taskCatalog.apps).toEqual([{ id: 'demo-app', name: 'Demo App', planOnly: true, granted: false }]);- expect(mocks.readPersistentMindTaskCatalog).toHaveBeenCalledWith({ includeAllApps: true });+ expect(res.body.taskCatalog).toBeNull();+ // The PLAN.md app is present even though it can never take an issue: the+ // allowlist is shared, so a forge-only roster would silently revoke it.+ expect(res.body.managedApps.map((app) => app.id)).toEqual(['demo-app', 'plan-app']);+ expect(mocks.readPersistentMindTaskCatalog).not.toHaveBeenCalled();});it('exposes live context, system, inference, and model-residency telemetry', async () => {diff --git a/server/services/cosToolRegistry.js b/server/services/cosToolRegistry.jsindex 1891cec123..5254da2e7d 100644--- a/server/services/cosToolRegistry.js+++ b/server/services/cosToolRegistry.js@@ -18,6 +18,10 @@ import {persistentMindCleanupRequestSchema,persistentMindTaskRequestSchema,} from '../lib/persistentMindCapabilities.js';+import {+ persistentMindIssueFileSchema,+ persistentMindIssueListSchema,+} from '../lib/persistentMindIssues.js';import {eidoverseWorldAugmentSchema,eidoverseWorldSaySchema,@@ -135,6 +139,50 @@ const taskTool = Object.freeze({adapter: { kind: 'persistent-mind-task' },});+// Read and file, deliberately as two tools: the read is idempotent and free to+// repeat, the file is not, and collapsing them would give one grant a single+// side-effect policy that is honest about neither.+const issueTools = Object.freeze([+ {+ type: 'portos_tool',+ name: 'issues.list',+ version: COS_TOOL_SCHEMA_VERSION,+ providerName: providerToolName('issues.list'),+ aliases: [],+ description: "List a managed app's open GitHub/GitLab issues, newest activity first, with labels and a body preview. Read this before filing so you do not re-file work already tracked.",+ input_schema: zodToOpenApiSchema(persistentMindIssueListSchema),+ output_schema: objectOutputSchema,+ policy: {+ scopes: ['mind'],+ requiredCapabilities: ['fileIssues'],+ sideEffect: 'read',+ idempotent: true,+ async: false,+ confirmation: 'capability-grant',+ },+ adapter: { kind: 'persistent-mind-issue-list' },+ },+ {+ type: 'portos_tool',+ name: 'issues.file',+ version: COS_TOOL_SCHEMA_VERSION,+ providerName: providerToolName('issues.file'),+ aliases: [],+ description: "File one issue on a managed app's GitHub/GitLab tracker to queue concrete work. Write a body someone can pick up cold, and choose the model and effort dispatch axes independently. An exact title match reuses the existing issue instead of filing a duplicate.",+ input_schema: zodToOpenApiSchema(persistentMindIssueFileSchema),+ output_schema: objectOutputSchema,+ policy: {+ scopes: ['mind'],+ requiredCapabilities: ['fileIssues'],+ sideEffect: 'write',+ idempotent: false,+ async: false,+ confirmation: 'capability-grant',+ },+ adapter: { kind: 'persistent-mind-issue-file' },+ },+]);+const mindCleanupTool = Object.freeze({type: 'portos_tool',name: 'mind.cleanup',@@ -348,13 +396,14 @@ const localContextTools = (() => {},];})();-const toolCatalog = (intent) => [...recipeManagementTools, ...thinkingTools, ...localContextTools, taskTool, mindCleanupTool, mindProtectMemoryTool, mindChooseNameTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];+const toolCatalog = (intent) => [...recipeManagementTools, ...thinkingTools, ...localContextTools, taskTool, ...issueTools, mindCleanupTool, mindProtectMemoryTool, mindChooseNameTool, userActionsQueryTool, ...eidoverseTools, ...voiceTools(intent)];const toolCalls = new Map();const toolCallFingerprints = new Map();const normalizeToolCapabilities = (raw) => ({...normalizePortosSemanticToolGrants(raw),createTasks: raw?.createTasks === true,+ fileIssues: raw?.fileIssues === true,manageToolRecipes: raw?.manageToolRecipes === true,manageMind: raw?.manageMind === true,chooseThinkingPreset: raw?.chooseThinkingPreset === true,@@ -520,6 +569,12 @@ const executeAdapter = async (tool, args, context, authority) => {if (tool.adapter.kind === 'voice-tool') {return dispatchTool(tool.adapter.legacyName, args, { sideEffects: [], signal: context.signal });}+ if (tool.adapter.kind.startsWith('persistent-mind-issue-')) {+ const { filePersistentMindIssue, listPersistentMindIssues } = await import('./persistentMindIssueCapability.js');+ return tool.adapter.kind === 'persistent-mind-issue-list'+ ? listPersistentMindIssues(args)+ : filePersistentMindIssue(args);+ }if (tool.adapter.kind === 'persistent-mind-name') {const { choosePersistentMindName } = await import('./persistentMindContext.js');return choosePersistentMindName(args);diff --git a/server/services/cosToolRegistry.test.js b/server/services/cosToolRegistry.test.jsindex 5880742afb..02524087cd 100644--- a/server/services/cosToolRegistry.test.js+++ b/server/services/cosToolRegistry.test.js@@ -11,6 +11,8 @@ const mocks = vi.hoisted(() => ({worldAugment: vi.fn(),worldSay: vi.fn(),listUserActions: vi.fn(),+ fileIssue: vi.fn(),+ listIssues: vi.fn(),}));const specs = [@@ -48,6 +50,10 @@ vi.mock('./voice/tools.js', () => ({vi.mock('./persistentMindTaskCapability.js', () => ({executePersistentMindTaskRequests: (...args) => mocks.executeTasks(...args),}));+vi.mock('./persistentMindIssueCapability.js', () => ({+ filePersistentMindIssue: (...args) => mocks.fileIssue(...args),+ listPersistentMindIssues: (...args) => mocks.listIssues(...args),+}));vi.mock('./persistentMindContext.js', () => ({ choosePersistentMindName: (...args) => mocks.chooseName(...args), protectPersistentMindMemory: (...args) => mocks.protectMemory(...args) }));vi.mock('./persistentMindMaintenance.js', () => ({cleanupPersistentMind: (...args) => mocks.cleanupMind(...args),@@ -107,6 +113,23 @@ describe('cosToolRegistry', () => {expect(getCosToolCatalog({ scope: 'mind', capabilities: { chooseThinkingPreset: true } }).tools.filter((tool) => tool.granted).map((tool) => tool.name)).toEqual(['mind.thinking-presets', 'mind.request-thinking-preset']);});+ it('gates the forge-issue tools on their own grant and routes them to the issue adapter', async () => {+ const call = { requestId: 'issue-1', name: 'issues.file', arguments: { appId: 'demo-app', title: 'Add a retry', body: 'Why and where.', model: 'medium', effort: 'high' } };+ // Task authority is NOT issue authority: a mind granted one must not+ // inherit the other.+ await expect(executeCosToolCall({ call, authority: { scope: 'mind', capabilities: { createTasks: true, writePortos: true } } }))+ .rejects.toMatchObject({ code: 'TOOL_CAPABILITY_DENIED' });+ await expect(executeCosToolCall({ call: { ...call, requestId: 'issue-2', arguments: { ...call.arguments, model: 'enormous' } }, authority: { scope: 'mind', capabilities: { fileIssues: true } } }))+ .rejects.toMatchObject({ code: 'TOOL_VALIDATION_ERROR' });++ mocks.fileIssue.mockResolvedValue({ ok: true, number: 42, url: 'https://example.com/example/demo/issues/42' });+ const result = await executeCosToolCall({ call: { ...call, requestId: 'issue-3' }, authority: { scope: 'mind', capabilities: { fileIssues: true } } });+ expect(result).toMatchObject({ name: 'issues.file', state: 'completed', result: { number: 42 } });+ expect(mocks.fileIssue).toHaveBeenCalledWith(call.arguments);+ expect(getCosToolCatalog({ scope: 'mind', capabilities: { fileIssues: true } }).tools.filter((tool) => tool.granted).map((tool) => tool.name))+ .toEqual(['issues.list', 'issues.file']);+ });+it('exports a compact canonical catalog and provider translations', () => {const catalog = getCosToolCatalog({ scope: 'mind', capabilities: { readPortos: true } });expect(catalog.tools.map((tool) => tool.name)).toEqual([@@ -116,6 +139,8 @@ describe('cosToolRegistry', () => {'mind.local-context','mind.adjust-local-context','cos.create-task',+ 'issues.list',+ 'issues.file','mind.cleanup','mind.protect-memory','mind.choose-name',diff --git a/server/services/layeredIntelligence/forgeFiler.js b/server/services/layeredIntelligence/forgeFiler.jsindex e311e74367..5518720938 100644--- a/server/services/layeredIntelligence/forgeFiler.js+++ b/server/services/layeredIntelligence/forgeFiler.js@@ -12,6 +12,7 @@ import { LI_LABEL, LI_BLOCKING_LABEL } from './constants.js';import { slugMarker, extractSlugFromBody } from './dedup.js';import { runCli } from './runCli.js';import { withGlabJson } from '../../lib/glabArgs.js';+import { forgeIssueCreateArgs, forgeLabelCreateArgs, parseCreatedForgeIssue } from '../../lib/forgeIssueCli.js';export { normalizeIssueState };@@ -230,11 +231,7 @@ export async function ensureForgeLabels({ cli, cwd, env, extraLabels = [], exec}))];for (const l of labels) {- if (cli === 'glab') {- await exec(cli, ['label', 'create', '--name', l.name, '--color', `#${l.color}`, '--description', l.desc], { cwd, env });- } else {- await exec(cli, ['label', 'create', l.name, '--color', l.color, '--description', l.desc, '--force'], { cwd, env });- }+ await exec(cli, forgeLabelCreateArgs(cli, { name: l.name, color: l.color, description: l.desc }), { cwd, env });}}@@ -257,16 +254,10 @@ export async function fileProposalToForge({const extras = forgeIssueLabels({ model, effort, goodFirstIssue, helpWanted, planner });await ensureForgeLabels({ cli, cwd, env, extraLabels: extras, exec });const fullBody = `${body}\n\n${slugMarker(slug)}`;- const labelArgs = [LI_LABEL, ...extras].flatMap((name) => ['--label', name]);- const args = cli === 'glab'- ? ['issue', 'create', '--title', title, '--description', fullBody, ...labelArgs]- : ['issue', 'create', '--title', title, '--body', fullBody, ...labelArgs];+ const args = forgeIssueCreateArgs(cli, { title, body: fullBody, labels: [LI_LABEL, ...extras] });const { code, stdout, stderr } = await exec(cli, args, { cwd, env });if (code !== 0) return { success: false, error: stderr || `${cli} exited with code ${code}` };- const urlMatch = stdout.trim().match(/(https?:\/\/\S+)/);- const url = urlMatch ? urlMatch[1] : stdout.trim();- const numMatch = url.match(/(\d+)\s*$/);- return { success: true, number: numMatch ? Number(numMatch[1]) : null, url };+ return { success: true, ...parseCreatedForgeIssue(stdout) };}/**diff --git a/server/services/persistentMindAdapter.js b/server/services/persistentMindAdapter.jsindex 68fcebf037..4cb4a346b6 100644--- a/server/services/persistentMindAdapter.js+++ b/server/services/persistentMindAdapter.js@@ -38,6 +38,10 @@ import {readPersistentMindTaskCatalog,readPersistentMindTaskInventory,} from './persistentMindTaskCapability.js';+import {+ buildPersistentMindIssueCapabilityPrompt,+ readPersistentMindIssueCatalog,+} from './persistentMindIssueCapability.js';import {buildPersistentMindCallCapabilityPrompt,executePersistentMindCallRequest,@@ -237,7 +241,7 @@ const currentWakeText = (wake) => {return `This is a self-directed wake. There is NO human message and NO implied user request this turn — do not invent one (no workouts, weather, inbox triage, or phone calls unless tools/capabilities explicitly require them for the playbook). Continue the standing playbook: prefer eidoverse.status then one concrete Eidoverse/PortOS action, then a short working note.\nreason=${wake?.reason || 'scheduled reflection'}`;};-export function buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, toolCapabilityPrompt = '# PortOS semantic tools\nSemantic tool access is OFF.', visibilityPrompt = '# Persistent Mind environment visibility\nWorkspace and runtime visibility is unknown.', userActionsPrompt = '', callCapabilityPrompt = buildPersistentMindCallCapabilityPrompt({ enabled: false }) }) {+export function buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, issueCapabilityPrompt = buildPersistentMindIssueCapabilityPrompt({ enabled: false }), toolCapabilityPrompt = '# PortOS semantic tools\nSemantic tool access is OFF.', visibilityPrompt = '# Persistent Mind environment visibility\nWorkspace and runtime visibility is unknown.', userActionsPrompt = '', callCapabilityPrompt = buildPersistentMindCallCapabilityPrompt({ enabled: false }) }) {return `${context.text}${visibilityPrompt}@@ -247,6 +251,8 @@ ${currentWakeText(wake)}${taskCapabilityPrompt}+${issueCapabilityPrompt}+${toolCapabilityPrompt}${callCapabilityPrompt}@@ -388,6 +394,12 @@ export function createPersistentMindTurnAdapter() {catalog: taskCatalog,inventory: taskInventory,});+ const issueCapabilityPrompt = buildPersistentMindIssueCapabilityPrompt({+ enabled: taskAccess.fileIssues,+ catalog: taskAccess.fileIssues+ ? await readPersistentMindIssueCatalog({ allowedAppIds: taskAccess.allowedAppIds })+ : undefined,+ });const visibilityPrompt = buildPersistentMindVisibilityPrompt(visibility);// Deterministic and always included (epic #5593 decision 14): bounded,// already redacted, no grant required. Deeper lookbacks use the@@ -404,6 +416,7 @@ export function createPersistentMindTurnAdapter() {context,wake,taskCapabilityPrompt,+ issueCapabilityPrompt,toolCapabilityPrompt,visibilityPrompt,userActionsPrompt,@@ -545,7 +558,7 @@ export function createPersistentMindTurnAdapter() {});completedToolResults.push(...toolResults);const liveCapabilities = normalizePersistentMindCapabilities((await loadState()).config?.persistentMindCapabilities);- basePrompt = buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, visibilityPrompt, userActionsPrompt, callCapabilityPrompt,+ basePrompt = buildPersistentMindTurnPrompt({ context, wake, taskCapabilityPrompt, issueCapabilityPrompt, visibilityPrompt, userActionsPrompt, callCapabilityPrompt,toolCapabilityPrompt: buildPersistentMindToolPrompt(liveCapabilities, await readPersistentMindRecipeCatalog(liveCapabilities)),});const budgetExhausted = toolBudget.used >= COS_TOOL_CALL_LIMITS.maxCallsPerTurn || round === MAX_TOOL_PROVIDER_ROUNDS - 2;diff --git a/server/services/persistentMindIssueCapability.js b/server/services/persistentMindIssueCapability.jsnew file mode 100644index 0000000000..78f0ba4a93--- /dev/null+++ b/server/services/persistentMindIssueCapability.js@@ -0,0 +1,230 @@+/**+ * Forge-issue capability for the persistent mind.+ *+ * Queueing work through `cos.create-task` needs a coding agent on this machine.+ * Plenty of installs have none — but almost every install can still reach a+ * GitHub or GitLab tracker, and an issue filed there is durable, reviewable, and+ * claimable later by `/do:next`, a human, or a peer machine that DOES have an+ * agent. So this capability is the preferred queueing lane whenever the mind is+ * not itself going to dispatch the work.+ *+ * The grant is re-checked after inference (like every other typed action), and+ * the target app is re-validated against the mind's managed-app allowlist and+ * its resolved work tracker through `persistentMindManagedApps` — the same+ * roster the task grant reads, so the tracker the mind writes to is the tracker+ * a claim would read from.+ */++import { execGh, ensureForgeReachable } from './github.js';+import { execGlab } from './gitlab.js';+import { loadState } from './cosState.js';+import { listAppIssues } from './appIssues.js';+import { readPersistentMindManagedApps } from './persistentMindManagedApps.js';+import { normalizePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';+import { normalizePersistentMindProfile } from '../lib/persistentMindProfile.js';+import {+ DISPATCH_EFFORT_LEVELS, DISPATCH_MODEL_TIERS,+ dispatchLabelSpec, forgeIssueLabels, resolvePlannerId,+} from '../lib/dispatchLabels.js';+import { forgeIssueCreateArgs, forgeLabelCreateArgs, parseCreatedForgeIssue } from '../lib/forgeIssueCli.js';+import { boundedByJsonChars } from '../lib/objects.js';+import { boundedErrorMessage } from '../lib/errorHandler.js';+import {+ PERSISTENT_MIND_ISSUE_EXTRA_LABEL_SPECS,+ PERSISTENT_MIND_ISSUE_CATEGORY_LABELS,+ PERSISTENT_MIND_ISSUE_LABEL,+ PERSISTENT_MIND_ISSUE_LIMITS,+ normalizeIssueTitleKey,+} from '../lib/persistentMindIssues.js';++const MAX_CATALOG_PROMPT_CHARS = 2_000;++const labelSpec = (name) => dispatchLabelSpec(name)+ || (PERSISTENT_MIND_ISSUE_EXTRA_LABEL_SPECS[name]+ ? { name, ...PERSISTENT_MIND_ISSUE_EXTRA_LABEL_SPECS[name] }+ : null);++/**+ * The apps this mind may file against: granted by the managed-app allowlist AND+ * resolving to a forge. A `plan`/`jira` app is omitted rather than+ * listed-and-refused — the mind should not spend a call discovering that.+ */+export async function readPersistentMindIssueCatalog({ allowedAppIds } = {}) {+ const apps = await readPersistentMindManagedApps({ allowedAppIds });+ return {+ apps: apps+ .filter((app) => app.forge && app.granted)+ .map(({ id, name, forge, fullName }) => ({ id, name, forge, fullName })),+ };+}++export function buildPersistentMindIssueCapabilityPrompt({ enabled, catalog = { apps: [] } } = {}) {+ if (!enabled) {+ return `# Issue tracker capability+Issue filing access is OFF. Do not call issues.list or issues.file, and never claim an issue was filed.`;+ }+ const apps = boundedByJsonChars(catalog.apps, MAX_CATALOG_PROMPT_CHARS);+ if (apps.length === 0) {+ return `# Issue tracker capability+Issue filing access is ON, but no authorized managed app currently resolves to a GitHub or GitLab tracker, so there is nothing you can file against this wake. Say so rather than claiming work was queued.`;+ }+ return `# Issue tracker capability+Issue filing access is ON. Filing an issue is the PREFERRED way to queue concrete work: an issue is durable, a human can read and re-scope it, and a coding agent can claim it later even on a machine that has none attached right now. Prefer it over describing work only in conversation, and use it instead of a CoS task whenever you are not the one dispatching the work.++Read before you write. Call issues.list for the target app first and skip anything already tracked; duplicates are refused on an exact title match, but a near-duplicate still wastes the backlog.++File with issues.file. Write the body so someone can pick it up cold: what is wrong or missing, where in the repo, why it matters now, and the chosen fix. Do not file speculative or future-only refactors.++Both dispatch axes are required and independent — never derive one from the other, and do not stamp medium on both by reflex:+- model: ${DISPATCH_MODEL_TIERS.join(', ')} — the CAPABILITY the work needs, from mechanical (a rename, a config change, a well-specified single-file edit) through routine multi-file work and genuinely hard reasoning (concurrency, schema/compatibility design, redesign) to exceptional frontier reasoning.+- effort: ${DISPATCH_EFFORT_LEVELS.join(', ')} — the REASONING BUDGET per step, independent of the model. A mechanical sweep across many call sites is the lowest model tier at the highest effort; a two-line change hinging on one idea is a high model tier at low effort.++Optional category labels: ${Object.keys(PERSISTENT_MIND_ISSUE_CATEGORY_LABELS).join(', ')}. Every issue you file is additionally marked '${PERSISTENT_MIND_ISSUE_LABEL}' and attributed to the model that planned it.++Authorized apps (ids are authoritative; do not invent ids):+${JSON.stringify(apps)}`;+}++/**+ * Re-check the live grant and resolve the forge for one request. Returns+ * `{ error }` for every refusal so the caller renders one bounded message.+ */+const resolveTarget = async (appId) => {+ const root = await loadState();+ const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);+ if (!capabilities.fileIssues) return { error: 'Persistent mind issue access is disabled' };+ const app = (await readPersistentMindManagedApps()).find((candidate) => candidate.id === appId);+ if (!app) return { error: `App '${appId}' has no configured repository` };+ if (!app.granted) {+ return { error: `Managed app '${appId}' is not authorized for Persistent Mind work; update Persistent Mind Tools permissions` };+ }+ if (!app.forge) {+ return { error: `App '${appId}' has no GitHub or GitLab issue list; check its work tracker and git remote` };+ }+ return { app, root };+};++/** Open issues on the app's tracker, projected down to what a prompt can use. */+export async function listPersistentMindIssues(args) {+ const { app, error } = await resolveTarget(args.appId);+ if (error) return { ok: false, error };+ const result = await listAppIssues(app);+ if (result.transient) {+ return { ok: false, error: `Could not read the ${app.forge} issue list (${result.reason}); ${result.remedy || 'retry once the forge CLI is reachable'}` };+ }+ const search = args.search ? args.search.toLowerCase() : null;+ const limit = args.limit || PERSISTENT_MIND_ISSUE_LIMITS.defaultListLimit;+ const issues = result.issues+ .filter((issue) => !args.label || issue.labels.some((label) => label.name === args.label))+ .filter((issue) => !search || `${issue.title}\n${issue.body}`.toLowerCase().includes(search))+ .slice(0, limit)+ .map((issue) => ({+ number: issue.number,+ title: issue.title,+ url: issue.url,+ labels: issue.labels.map((label) => label.name),+ assignees: issue.assignees,+ updatedAt: issue.updatedAt,+ bodyPreview: String(issue.body || '').slice(0, PERSISTENT_MIND_ISSUE_LIMITS.bodyPreviewChars),+ }));+ return {+ ok: true,+ appId: args.appId,+ forge: app.forge,+ repository: result.fullName,+ issues,+ // The tracker's real open count, so a truncated page never reads as the+ // whole backlog when the mind checks for an existing item.+ totalOpen: result.issues.length,+ truncated: result.issues.length > issues.length,+ };+}++/**+ * Create the labels this issue needs before creating the issue. Both CLIs fail+ * the whole `issue create` with a 422 when a named label does not exist, and+ * creation is idempotent, so this always runs first. The calls are independent+ * and every failure is swallowed — a label we could not create resurfaces as+ * the create's own error if it actually mattered — so they run concurrently+ * rather than adding a serial spawn per label to every file.+ */+const ensureLabels = async ({ app, names }) => {+ await Promise.all(names.map((name) => {+ const spec = labelSpec(name);+ if (!spec) return null;+ return (app.forge === 'gitlab'+ ? execGlab(forgeLabelCreateArgs('glab', spec), app.repoPath)+ : execGh(forgeLabelCreateArgs('gh', spec, { repo: app.repoSpec }))).catch(() => null);+ }));+};++const createIssue = ({ app, title, body, labels }) => {+ const args = forgeIssueCreateArgs(app.forge === 'gitlab' ? 'glab' : 'gh', {+ title, body, labels, repo: app.forge === 'gitlab' ? null : app.repoSpec,+ });+ const run = app.forge === 'gitlab'+ ? execGlab(args, app.repoPath, undefined, { rejectOnError: true })+ : execGh(args);+ return run.then(+ (stdout) => ({ ok: true, ...parseCreatedForgeIssue(stdout) }),+ (error) => ({ ok: false, error: boundedErrorMessage(error, 'Issue creation failed') }),+ );+};++/** File one issue on the app's tracker. */+export async function filePersistentMindIssue(args) {+ const { app, root, error } = await resolveTarget(args.appId);+ if (error) return { ok: false, error };++ // The reachability probe runs before anything is created: on an unreachable+ // forge this is one failing call instead of a whole label fan-out that each+ // has to time out first.+ if (app.forge === 'github') {+ const forge = await ensureForgeReachable('mind-issue-file', { hostname: app.apiHost });+ if (!forge.ok) return { ok: false, error: `GitHub is not reachable (${forge.status}); ${forge.remedy || 'check `gh auth status`'}` };+ }++ // Duplicate guard. A failed read must NOT read as "nothing is tracked" — that+ // is exactly how a transient `gh` blip files the same issue twice — so an+ // unreadable tracker refuses the file rather than proceeding blind.+ const existing = await listAppIssues(app);+ if (existing.transient) {+ return { ok: false, error: `Could not read the existing ${app.forge} issues to check for duplicates (${existing.reason}); nothing was filed` };+ }+ const titleKey = normalizeIssueTitleKey(args.title);+ const duplicate = existing.issues.find((issue) => normalizeIssueTitleKey(issue.title) === titleKey);+ if (duplicate) {+ return {+ ok: true, duplicate: true, number: duplicate.number, url: duplicate.url,+ summary: `Issue #${duplicate.number} already tracks this work; nothing new was filed`,+ };+ }++ const profile = normalizePersistentMindProfile(root.config?.persistentMindProfile);+ const labels = [+ PERSISTENT_MIND_ISSUE_LABEL,+ ...forgeIssueLabels({+ model: args.model,+ effort: args.effort,+ // The planner axis records who WROTE the plan — this mind's own model —+ // and is independent of the model:/effort: dispatch hints above.+ planner: resolvePlannerId({ providerId: profile.providerId, model: profile.model }),+ }),+ ...(args.labels || []),+ ];+ await ensureLabels({ app, names: labels });++ const created = await createIssue({ app, title: args.title, body: args.body, labels });+ if (!created.ok) return created;+ return {+ ok: true,+ duplicate: false,+ appId: args.appId,+ forge: app.forge,+ repository: app.fullName,+ number: created.number,+ url: created.url,+ labels,+ summary: `Filed ${created.number ? `#${created.number}` : 'an issue'} on ${app.fullName || app.forge}`,+ };+}diff --git a/server/services/persistentMindIssueCapability.test.js b/server/services/persistentMindIssueCapability.test.jsnew file mode 100644index 0000000000..5bdb50b2d3--- /dev/null+++ b/server/services/persistentMindIssueCapability.test.js@@ -0,0 +1,200 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mocks = vi.hoisted(() => ({+ root: {},+ apps: [],+ resolveAppForgeTarget: vi.fn(),+ listAppIssues: vi.fn(),+ execGh: vi.fn(),+ execGlab: vi.fn(),+ ensureForgeReachable: vi.fn(),+}));++vi.mock('./cosState.js', () => ({ loadState: vi.fn(async () => mocks.root) }));+vi.mock('./apps.js', () => ({ getActiveApps: vi.fn(async () => mocks.apps) }));+vi.mock('./appIssues.js', () => ({ listAppIssues: (...args) => mocks.listAppIssues(...args) }));+vi.mock('../lib/workTracker.js', () => ({+ resolveAppForgeTarget: (...args) => mocks.resolveAppForgeTarget(...args),+}));+vi.mock('./github.js', () => ({+ execGh: (...args) => mocks.execGh(...args),+ ensureForgeReachable: (...args) => mocks.ensureForgeReachable(...args),+}));+vi.mock('./gitlab.js', () => ({ execGlab: (...args) => mocks.execGlab(...args) }));++const managedApps = await import('./persistentMindManagedApps.js');+const {+ buildPersistentMindIssueCapabilityPrompt,+ filePersistentMindIssue,+ listPersistentMindIssues,+ readPersistentMindIssueCatalog,+} = await import('./persistentMindIssueCapability.js');++const GITHUB_APP = { id: 'demo-app', name: 'Demo App', repoPath: '/repos/demo' };+const PLAN_APP = { id: 'plan-app', name: 'Plan App', repoPath: '/repos/plan' };+const githubTarget = { forge: 'github', repoSpec: 'github.com/example/demo', apiHost: 'github.com', fullName: 'example/demo' };++const setCapabilities = (capabilities) => {+ mocks.root = {+ config: {+ persistentMindCapabilities: { schemaVersion: 10, ...capabilities },+ persistentMindProfile: { enabled: true, providerId: 'ollama', model: 'claude-opus-5' },+ },+ };+};++const openIssue = (overrides = {}) => ({+ number: 7,+ title: 'Existing tracked work',+ body: 'Already filed.',+ url: 'https://github.com/example/demo/issues/7',+ labels: [{ name: 'plan' }],+ assignees: [],+ updatedAt: '2026-09-01T00:00:00.000Z',+ ...overrides,+});++const okList = (issues) => ({ issues, reason: 'ok', transient: false, fullName: 'example/demo' });++const fileRequest = (overrides = {}) => ({+ appId: 'demo-app', title: 'Add a retry to the sync poller', body: 'Body prose.',+ model: 'medium', effort: 'high', ...overrides,+});++const ghArgsFor = (verb) => mocks.execGh.mock.calls.map(([args]) => args).filter((args) => args[0] === verb);++beforeEach(() => {+ vi.clearAllMocks();+ managedApps.__testing.resolveCache.clear();+ setCapabilities({ fileIssues: true });+ mocks.apps = [GITHUB_APP, PLAN_APP];+ mocks.resolveAppForgeTarget.mockImplementation(async (app) => (app.id === 'demo-app'+ ? { tracker: 'github', target: githubTarget }+ : { tracker: 'plan', target: null }));+ mocks.listAppIssues.mockResolvedValue(okList([]));+ mocks.ensureForgeReachable.mockResolvedValue({ ok: true });+ mocks.execGh.mockResolvedValue('https://github.com/example/demo/issues/42\n');+});++describe('persistent mind issue capability', () => {+ it('offers only granted, forge-tracked apps to the model', async () => {+ expect((await readPersistentMindIssueCatalog()).apps).toEqual([+ { id: 'demo-app', name: 'Demo App', forge: 'github', fullName: 'example/demo' },+ ]);+ expect((await readPersistentMindIssueCatalog({ allowedAppIds: ['plan-app'] })).apps).toEqual([]);+ });++ it('names the grant state and the authorized ids in the prompt', () => {+ expect(buildPersistentMindIssueCapabilityPrompt({ enabled: false })).toContain('OFF');+ const on = buildPersistentMindIssueCapabilityPrompt({ enabled: true, catalog: { apps: [{ id: 'demo-app', forge: 'github' }] } });+ expect(on).toContain('demo-app');+ expect(on).toMatch(/PREFERRED/);+ // The dispatch vocabulary is interpolated from the label registry, so a new+ // tier cannot leave the mind describing the old set.+ expect(on).toContain('light, medium, heavy, ultra');+ expect(on).toContain('low, medium, high, xhigh, max');+ expect(buildPersistentMindIssueCapabilityPrompt({ enabled: true, catalog: { apps: [] } }))+ .toMatch(/no authorized managed app/i);+ });++ it('refuses every request when the grant is off or the app is out of scope', async () => {+ setCapabilities({ fileIssues: false });+ expect(await filePersistentMindIssue(fileRequest())).toMatchObject({ ok: false, error: expect.stringMatching(/disabled/i) });+ expect(await listPersistentMindIssues({ appId: 'demo-app' })).toMatchObject({ ok: false });++ setCapabilities({ fileIssues: true, allowedAppIds: ['other-app'] });+ expect(await filePersistentMindIssue(fileRequest())).toMatchObject({ ok: false, error: expect.stringMatching(/not authorized/i) });++ setCapabilities({ fileIssues: true });+ expect(await filePersistentMindIssue(fileRequest({ appId: 'plan-app' })))+ .toMatchObject({ ok: false, error: expect.stringMatching(/no GitHub or GitLab issue list/i) });+ expect(mocks.execGh).not.toHaveBeenCalled();+ });++ it('files with both dispatch axes, the attribution labels, and the chosen category', async () => {+ const result = await filePersistentMindIssue(fileRequest({ labels: ['plan'] }));++ expect(result).toMatchObject({ ok: true, duplicate: false, number: 42, url: 'https://github.com/example/demo/issues/42', forge: 'github' });+ expect(ghArgsFor('issue')).toEqual([[+ 'issue', 'create', '--repo', 'github.com/example/demo',+ '--title', 'Add a retry to the sync poller', '--body', 'Body prose.',+ '--label', 'persistent-mind',+ '--label', 'model:medium',+ '--label', 'effort:high',+ // The planner axis records the model that WROTE the plan, independently+ // of the model:/effort: hints about how to RUN it.+ '--label', 'planner:opus-5',+ '--label', 'plan',+ ]]);+ // Both CLIs 422 the whole create on an undefined label, so every label is+ // created first.+ expect(ghArgsFor('label').map((args) => args[2])).toEqual(+ expect.arrayContaining(['persistent-mind', 'model:medium', 'effort:high', 'planner:opus-5', 'plan']),+ );+ });++ it('reuses an existing issue with the same title instead of filing a duplicate', async () => {+ mocks.listAppIssues.mockResolvedValue(okList([openIssue({ title: 'Add a Retry to the SYNC poller!' })]));++ expect(await filePersistentMindIssue(fileRequest())).toMatchObject({ ok: true, duplicate: true, number: 7 });+ expect(ghArgsFor('issue')).toEqual([]);+ });++ it('refuses to file when the tracker could not be read, rather than risking a duplicate', async () => {+ mocks.listAppIssues.mockResolvedValue({ issues: [], reason: 'fetch-failed', transient: true, remedy: 'check gh auth' });++ expect(await filePersistentMindIssue(fileRequest())).toMatchObject({ ok: false, error: expect.stringMatching(/nothing was filed/) });+ expect(ghArgsFor('issue')).toEqual([]);+ });++ it('stops at the reachability probe before spawning any label or issue call', async () => {+ mocks.ensureForgeReachable.mockResolvedValue({ ok: false, status: 'unauthenticated', remedy: 'run `gh auth login`' });++ expect(await filePersistentMindIssue(fileRequest())).toMatchObject({ ok: false, error: expect.stringContaining('gh auth login') });+ expect(mocks.execGh).not.toHaveBeenCalled();+ expect(mocks.listAppIssues).not.toHaveBeenCalled();+ });++ it('reports a forge create failure instead of claiming the issue exists', async () => {+ mocks.execGh.mockImplementation(async (args) => {+ if (args[0] === 'issue') throw new Error('GraphQL: Resource not accessible');+ return '';+ });++ expect(await filePersistentMindIssue(fileRequest())).toMatchObject({ ok: false, error: expect.stringContaining('Resource not accessible') });+ });++ it('lists open issues with a truncation signal and a working local filter', async () => {+ mocks.listAppIssues.mockResolvedValue(okList([+ openIssue({ number: 1, title: 'Sync poller retry', labels: [{ name: 'plan' }] }),+ openIssue({ number: 2, title: 'Unrelated', labels: [{ name: 'bug' }] }),+ ]));++ const all = await listPersistentMindIssues({ appId: 'demo-app' });+ expect(all).toMatchObject({ ok: true, forge: 'github', repository: 'example/demo', totalOpen: 2, truncated: false });+ expect(all.issues.map((issue) => issue.number)).toEqual([1, 2]);++ expect((await listPersistentMindIssues({ appId: 'demo-app', label: 'bug' })).issues.map((i) => i.number)).toEqual([2]);+ expect((await listPersistentMindIssues({ appId: 'demo-app', search: 'POLLER' })).issues.map((i) => i.number)).toEqual([1]);+ // A page cut short must say so — otherwise a partial read reads as the+ // whole backlog when the mind checks for an existing item.+ expect(await listPersistentMindIssues({ appId: 'demo-app', limit: 1 })).toMatchObject({ truncated: true, totalOpen: 2 });+ });++ it('surfaces an unreadable tracker as a failed read, never as an empty backlog', async () => {+ mocks.listAppIssues.mockResolvedValue({ issues: [], reason: 'gh-unauthenticated', transient: true, remedy: 'run `gh auth login`' });++ expect(await listPersistentMindIssues({ appId: 'demo-app' }))+ .toMatchObject({ ok: false, error: expect.stringContaining('gh auth login') });+ });++ it('files through glab for a GitLab-tracked app', async () => {+ mocks.resolveAppForgeTarget.mockResolvedValue({ tracker: 'gitlab', target: { forge: 'gitlab', fullName: 'example/demo' } });+ mocks.execGlab.mockResolvedValue('https://gitlab.com/example/demo/-/issues/11');++ expect(await filePersistentMindIssue(fileRequest())).toMatchObject({ ok: true, number: 11, forge: 'gitlab' });+ const create = mocks.execGlab.mock.calls.map(([args]) => args).find((args) => args[0] === 'issue');+ expect(create).toEqual(expect.arrayContaining(['--label', 'persistent-mind,model:medium,effort:high,planner:opus-5']));+ expect(mocks.execGh).not.toHaveBeenCalled();+ });+});diff --git a/server/services/persistentMindManagedApps.js b/server/services/persistentMindManagedApps.jsnew file mode 100644index 0000000000..e24d85c5ad--- /dev/null+++ b/server/services/persistentMindManagedApps.js@@ -0,0 +1,89 @@+/**+ * The managed apps a persistent-mind grant may target, with their work tracker+ * resolved once.+ *+ * Both mind grants that name a repository — CoS tasks and forge issues — need+ * the same three facts about every active app: is it runnable, is it in the+ * user's allowlist, and what does its work tracker resolve to. Resolving that+ * tracker is not free: `resolveAppForgeTarget` shells out to `git` for the+ * origin remote (twice, once per resolver), and this list is rebuilt on EVERY+ * persistent-mind wake as well as on every settings-page load. Two readers+ * deriving it separately meant up to 50 apps × 2 resolutions per wake, and two+ * places where "which forge is this app on" could drift.+ *+ * So there is one roster, one cache, and one resolution serving both grants.+ * Each caller projects the fields it needs.+ */++import { resolveAppForgeTarget } from '../lib/workTracker.js';+import { getActiveApps } from './apps.js';+import { loadState } from './cosState.js';+import { normalizePersistentMindCapabilities } from '../lib/persistentMindCapabilities.js';++const MAX_ROSTER_APPS = 50;+const APP_ID_CHARS = 128;+const RESOLVE_CACHE_TTL_MS = 30_000;+const FORGE_TRACKERS = new Set(['github', 'gitlab']);++// Promise-valued, so concurrent builders share one in-flight resolution rather+// than each spawning their own `git`.+const resolveCache = new Map();++const cachedResolve = (app) => {+ const key = `${app.id}\0${app.repoPath}\0${app.workTracker || 'auto'}`;+ const cached = resolveCache.get(key);+ if (cached && cached.expiresAt > Date.now()) return cached.promise;+ const promise = resolveAppForgeTarget(app).catch(() => ({ tracker: null, target: null }));+ resolveCache.set(key, { expiresAt: Date.now() + RESOLVE_CACHE_TTL_MS, promise });+ return promise;+};++const isRunnableApp = (app) => typeof app?.id === 'string' && app.id+ && app.id.length <= APP_ID_CHARS+ && typeof app?.repoPath === 'string' && app.repoPath.trim().length > 0;++/**+ * Every runnable active app, annotated with what each grant needs to know.+ *+ * - `planOnly` — the tracker is a forge, so the task grant may use its+ * issue-only "Plan & File Issue" mode.+ * - `forge` — the tracker is a forge AND the app's remote actually resolves to+ * that forge, so an issue can be filed against it. Null otherwise, including+ * for an app explicitly pinned to one forge from the other's remote: nothing+ * there could be filed, so the issue grant must not offer it. `fullName`,+ * `repoSpec` (gh's host-qualified selector) and `apiHost` ride with it, so a+ * caller never re-resolves the target just to address it.+ * - `granted` — the app is in the mind's `allowedAppIds` allowlist. Always true+ * when no allowlist is stored, which is the legacy grant to every app.+ *+ * Revoked apps are included: the settings page must see one to offer it back,+ * and the allowlist it edits is shared by both grants, so filtering the roster+ * per grant would let one editor silently narrow the other. Model-facing+ * callers filter for themselves.+ */+export async function readPersistentMindManagedApps({ allowedAppIds } = {}) {+ const [root, apps] = await Promise.all([loadState(), getActiveApps()]);+ const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);+ const effectiveAllowed = Array.isArray(allowedAppIds) ? allowedAppIds : capabilities.allowedAppIds;+ const allowed = Array.isArray(effectiveAllowed) ? new Set(effectiveAllowed) : null;+ const runnable = apps.filter(isRunnableApp).slice(0, MAX_ROSTER_APPS);+ return Promise.all(runnable.map(async (app) => {+ const { tracker, target } = await cachedResolve(app);+ const onForge = FORGE_TRACKERS.has(tracker);+ const filable = onForge && target?.forge === tracker;+ return {+ id: app.id,+ name: String(app.name || app.id).slice(0, 100),+ repoPath: app.repoPath,+ workTracker: app.workTracker,+ planOnly: onForge,+ forge: filable ? tracker : null,+ fullName: filable ? target.fullName || null : null,+ repoSpec: filable ? target.repoSpec || null : null,+ apiHost: filable ? target.apiHost || null : null,+ granted: !allowed || allowed.has(app.id),+ };+ }));+}++export const __testing = { resolveCache };diff --git a/server/services/persistentMindTaskCapability.js b/server/services/persistentMindTaskCapability.jsindex db26905505..c5eea09eec 100644--- a/server/services/persistentMindTaskCapability.js+++ b/server/services/persistentMindTaskCapability.js@@ -15,14 +15,15 @@ import {persistentMindTaskRequestSchema,} from '../lib/persistentMindCapabilities.js';import { PERSISTENT_MIND_ID } from '../lib/persistentMindTrajectory.js';-import { canonicalStringify } from '../lib/objects.js';+import { boundedByJsonChars, canonicalStringify } from '../lib/objects.js';import { antigravityBaseModels, effortLevelsForProvider, filterSelectableModels } from '../lib/providerModels.js';import { PR_COMPLETIONS } from '../lib/prDisposition.js';import { sha256Text } from '../lib/fileUtils.js';+import { boundedErrorMessage } from '../lib/errorHandler.js';import { MANAGED_ASSESSMENT_BACKENDS, localRuntimeKind } from '../lib/localProviderRuntime.js';import { PORTOS_APP_ID } from '../lib/appIdentity.js';-import { resolveAppWorkTracker } from '../lib/workTracker.js';import { getActiveApps, getAppWorkTracker } from './apps.js';+import { readPersistentMindManagedApps } from './persistentMindManagedApps.js';import { loadState } from './cosState.js';import { addTask, firstLine, getCosTasks, getTaskById } from './cosTaskStore.js';import { getProviderPrerequisiteReadinessMap } from './providerPrerequisites.js';@@ -33,7 +34,6 @@ import {readPersistentMindWorkspacePreflight,} from './persistentMindWorkspacePreflight.js';-const MAX_CATALOG_APPS = 50;const MAX_CATALOG_PROVIDERS = 50;const MAX_CATALOG_MODELS = 60;const MAX_CATALOG_PROMPT_CHARS = 16_000;@@ -42,10 +42,10 @@ const MIND_TASK_ID_PREFIX = 'sys-mind-';const MAX_INVENTORY_TASKS = 25;const MAX_INVENTORY_PROMPT_CHARS = 4_000;const MAX_INVENTORY_DESCRIPTION_CHARS = 160;-const APP_TRACKER_CACHE_TTL_MS = 30_000;const ISSUE_TRACKERS = new Set(['github', 'gitlab']);-const appTrackerCache = new Map();+// The queue path still walks raw app records; the catalog path gets its apps+// pre-filtered from the shared managed-app roster.const isRunnableApp = (app) => typeof app?.repoPath === 'string' && app.repoPath.trim().length > 0;const isRunnableAgentProvider = (provider) => provider?.enabled !== false&& isProcessProvider(provider);@@ -146,46 +146,31 @@ const providerCatalogEntry = async (provider, capabilities) => {};};-const catalogTrackerFor = (app) => {- const key = `${app.id}\0${app.repoPath}\0${app.workTracker || 'auto'}`;- const cached = appTrackerCache.get(key);- if (cached && cached.expiresAt > Date.now()) return cached.promise;- const promise = resolveAppWorkTracker(app);- appTrackerCache.set(key, { expiresAt: Date.now() + APP_TRACKER_CACHE_TTL_MS, promise });- return promise;-};--const appCatalogEntry = async (app) => {- const tracker = await catalogTrackerFor(app);- return {- id: app.id,- name: String(app.name || app.id).slice(0, 100),- planOnly: ISSUE_TRACKERS.has(tracker?.resolved),- // Only the baseline entry carries the flag, so the prompt catalog stays- // small and the mind has one unambiguous answer to "which repo is mine".- ...(app.id === PORTOS_APP_ID ? { self: true } : {}),- };-};+const appCatalogEntry = (app) => ({+ id: app.id,+ name: app.name,+ planOnly: app.planOnly,+ // Only the baseline entry carries the flag, so the prompt catalog stays+ // small and the mind has one unambiguous answer to "which repo is mine".+ ...(app.id === PORTOS_APP_ID ? { self: true } : {}),+});export async function readPersistentMindTaskCatalog({ allowedAppIds, includeAllApps = false } = {}) {- const [apps, providers, root] = await Promise.all([getActiveApps(), listProviders(), loadState()]);+ const [managedApps, providers, root] = await Promise.all([+ readPersistentMindManagedApps({ allowedAppIds }),+ listProviders(),+ loadState(),+ ]);const capabilities = normalizePersistentMindCapabilities(root.config?.persistentMindCapabilities);- const effectiveAllowedAppIds = Array.isArray(allowedAppIds) ? allowedAppIds : capabilities.allowedAppIds;- const runnableApps = apps- .filter((app) => isRunnableApp(app) && typeof app?.id === 'string' && app.id- && app.id.length <= PERSISTENT_MIND_TASK_LIMITS.appIdChars)- .slice(0, MAX_CATALOG_APPS);const candidates = boundedProviderCandidates(providers);const readiness = await getProviderPrerequisiteReadinessMap(providers, {candidates,deferCwdDependent: true,});- const appCatalog = await Promise.all(runnableApps.map(appCatalogEntry));- const allowed = Array.isArray(effectiveAllowedAppIds) ? new Set(effectiveAllowedAppIds) : null;return {// The tools settings page needs to see revoked apps so it can restore them;// the model-facing catalog remains narrowed to the granted set.- apps: includeAllApps || !allowed ? appCatalog : appCatalog.filter((app) => allowed.has(app.id)),+ apps: (includeAllApps ? managedApps : managedApps.filter((app) => app.granted)).map(appCatalogEntry),providers: (await Promise.all(candidates.filter((provider) => readiness[provider.id]?.status === 'ready').map((provider) => providerCatalogEntry(provider, capabilities))))@@ -209,13 +194,7 @@ const boundedPromptCatalog = (catalog) => {unknownReasonCodes: boundedReadinessReasonCodes(catalog?.providerReadiness?.unknownReasonCodes),},};- for (const app of Array.isArray(catalog?.apps) ? catalog.apps : []) {- bounded.apps.push(app);- if (JSON.stringify({ apps: bounded.apps }).length > MAX_CATALOG_APP_PROMPT_CHARS) {- bounded.apps.pop();- break;- }- }+ bounded.apps = boundedByJsonChars(catalog?.apps, MAX_CATALOG_APP_PROMPT_CHARS, (apps) => ({ apps }));for (const provider of Array.isArray(catalog?.providers) ? catalog.providers : []) {const kept = { ...provider, models: [] };bounded.providers.push(kept);@@ -223,13 +202,12 @@ const boundedPromptCatalog = (catalog) => {bounded.providers.pop();break;}- for (const model of Array.isArray(provider.models) ? provider.models : []) {- kept.models.push(model);- if (JSON.stringify(bounded).length > MAX_CATALOG_PROMPT_CHARS) {- kept.models.pop();- break;- }- }+ // Measured through `bounded`, so each model counts against the whole+ // catalog's budget rather than its own provider's slice.+ kept.models = boundedByJsonChars(provider.models, MAX_CATALOG_PROMPT_CHARS, (models) => {+ kept.models = models;+ return bounded;+ });}return bounded;};@@ -262,17 +240,7 @@ export async function readPersistentMindTaskInventory() {.filter((entry) => entry.id && entry.description);}-const boundedPromptInventory = (inventory) => {- const bounded = [];- for (const entry of Array.isArray(inventory) ? inventory : []) {- bounded.push(entry);- if (JSON.stringify(bounded).length > MAX_INVENTORY_PROMPT_CHARS) {- bounded.pop();- break;- }- }- return bounded;-};+const boundedPromptInventory = (inventory) => boundedByJsonChars(inventory, MAX_INVENTORY_PROMPT_CHARS);export function buildPersistentMindTaskCapabilityPrompt({ enabled, catalog = { apps: [], providers: [] }, inventory = [] } = {}) {if (!enabled) {@@ -325,7 +293,7 @@ const taskIdFor = (wakeId, fingerprint) => (`${MIND_TASK_ID_PREFIX}${sha256Text(`${PERSISTENT_MIND_ID}:${wakeId}:${fingerprint}`).slice(0, 24)}`);-const boundedError = (error) => String(error?.message || error || 'Task creation failed').slice(0, 300);+const boundedError = (error) => boundedErrorMessage(error, 'Task creation failed');const readinessError = (providerId, verdict) => {const reasonCodes = (verdict?.reasonCodes || []).slice(0, 5).join(', ') || 'prerequisites';diff --git a/server/services/persistentMindTaskCapability.test.js b/server/services/persistentMindTaskCapability.test.jsindex cdf5405049..409633c238 100644--- a/server/services/persistentMindTaskCapability.test.js+++ b/server/services/persistentMindTaskCapability.test.js@@ -12,7 +12,7 @@ const mocks = vi.hoisted(() => ({addTask: vi.fn(),getTaskById: vi.fn(),getAppWorkTracker: vi.fn(),- resolveAppWorkTracker: vi.fn(),+ resolveAppForgeTarget: vi.fn(),getProviderPrerequisiteReadinessMap: vi.fn(),listManagedBackendModels: vi.fn(),workspacePreflight: vi.fn(),@@ -38,7 +38,7 @@ vi.mock('./providerPrerequisites.js', () => ({getProviderPrerequisiteReadinessMap: (...args) => mocks.getProviderPrerequisiteReadinessMap(...args),}));vi.mock('../lib/workTracker.js', () => ({- resolveAppWorkTracker: (...args) => mocks.resolveAppWorkTracker(...args),+ resolveAppForgeTarget: (...args) => mocks.resolveAppForgeTarget(...args),}));vi.mock('./persistentMindWorkspacePreflight.js', () => ({readPersistentMindWorkspacePreflight: (...args) => mocks.workspacePreflight(...args),@@ -46,6 +46,7 @@ vi.mock('./persistentMindWorkspacePreflight.js', () => ({}));const { PORTOS_APP_ID } = await import('../lib/appIdentity.js');+const managedApps = await import('./persistentMindManagedApps.js');const {buildPersistentMindTaskCapabilityPrompt,@@ -77,7 +78,10 @@ beforeEach(() => {mocks.existing = null;mocks.cosTasks = [];mocks.getAppWorkTracker.mockResolvedValue({ resolved: 'plan' });- mocks.resolveAppWorkTracker.mockResolvedValue({ resolved: 'plan' });+ mocks.resolveAppForgeTarget.mockResolvedValue({ tracker: 'plan', target: null });+ // The roster caches its forge resolution for 30s, which would otherwise carry+ // one test's tracker into the next.+ managedApps.__testing.resolveCache.clear();mocks.getTaskById.mockImplementation(async () => mocks.existing);mocks.addTask.mockResolvedValue({ id: 'sys-mind-stable', status: 'pending', autoApproved: true });mocks.listManagedBackendModels.mockResolvedValue({ models: null, error: 'no daemon in tests' });@@ -325,7 +329,7 @@ describe('persistent mind CoS-task capability', () => {await readPersistentMindTaskCatalog();await readPersistentMindTaskCatalog();- expect(mocks.resolveAppWorkTracker).toHaveBeenCalledTimes(1);+ expect(mocks.resolveAppForgeTarget).toHaveBeenCalledTimes(1);});it('queues an auto-approved isolated task with the chosen run and PR policy', async () => {