Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix three defects in the retired-model-pin and forge-issue surfaces (#7366)
[._.]/ Adam Eivy3fff9b9524d6
diff --git a/server/lib/persistentMindCapabilities.js b/server/lib/persistentMindCapabilities.jsindex 447e2bb8ef..06736b7018 100644--- a/server/lib/persistentMindCapabilities.js+++ b/server/lib/persistentMindCapabilities.js@@ -93,7 +93,7 @@ export const PERSISTENT_MIND_TOOL_CATALOG = Object.freeze(['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',+ 'Issue titles and bodies are the mind\'s own prose, with home-directory paths and credential-shaped strings stripped before filing; it is additionally instructed to keep private records out, which is guidance rather than an enforced filter',],}),Object.freeze({diff --git a/server/routes/imageGen.js b/server/routes/imageGen.jsindex f6c60d6be8..e90f887c82 100644--- a/server/routes/imageGen.js+++ b/server/routes/imageGen.js@@ -452,7 +452,9 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {}}const selected = mode === IMAGE_GEN_MODE.LOCAL ? selectLocalImageModel(params.modelId) : null;- const cloud = selected ? null : resolveCloudProviderConfig(settings, mode, { model: params.cloudModel });+ const cloud = selected ? null : resolveCloudProviderConfig(settings, mode, {+ model: params.cloudModel, modelIsShippedDefault: params.cloudModelIsShippedDefault,+ });const model = selected? { ...selected, loraCompatKey: loraCompatKey(selected) }: (cloud ? { id: cloud.modelId } : null);@@ -592,7 +594,8 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {// finished filename and work identically for a federated render.const {mediaProviderPeerId: _peerId, mediaProviderEngine: _engine,- mode: _mode, cloudModel: _cloudModel, ...jobParams+ mode: _mode, cloudModel: _cloudModel, cloudModelIsShippedDefault: _cloudModelProvenance,+ ...jobParams} = params;// The prompt and model ride only inside the versioned marker: enqueueJob// normalizes any job carrying one into the downgrade-safe shape, so this@@ -610,12 +613,15 @@ router.post('/generate', imageGenUploads, asyncHandler(async (req, res) => {}));}- // `cloudModel` is a dispatcher-level knob, not a provider param — the- // resolver folds it into the provider's own `model`, so drop the raw field- // before it rides into the persisted job params.+ // `cloudModel` and its provenance flag are dispatcher-level knobs, not+ // provider params — the resolver folds them into the provider's own `model`+ // and `modelIsShippedDefault`, so drop the raw fields before they ride into+ // the persisted job params.const cloudModel = params.cloudModel;+ const modelIsShippedDefault = params.cloudModelIsShippedDefault;delete params.cloudModel;- const cloud = resolveCloudProviderConfig(settings, mode, { model: cloudModel });+ delete params.cloudModelIsShippedDefault;+ const cloud = resolveCloudProviderConfig(settings, mode, { model: cloudModel, modelIsShippedDefault });if (cloud) {// Reject up-front rather than enqueueing a doomed job — the cloud CLIs are// gated behind an explicit toggle each (not every Codex account has accessdiff --git a/server/services/imageGen/cloudProviderConfig.js b/server/services/imageGen/cloudProviderConfig.jsindex 44f4cd994c..edc1224412 100644--- a/server/services/imageGen/cloudProviderConfig.js+++ b/server/services/imageGen/cloudProviderConfig.js@@ -93,16 +93,22 @@ export const CLOUD_PROVIDER_SPECS = Object.freeze({// sentinel, which resolves to "no --model" and lets agy pick a possibly// reasoning-heavy session default) — see AGY_IMAGEGEN_DEFAULT_MODEL.modelId: (a, override) => override || a.model || AGY_IMAGEGEN_DEFAULT_MODEL,- params: (a, override) => ({+ params: (a, override, overrideIsShippedDefault) => ({agyPath: a.agyPath,model: override || a.model || AGY_IMAGEGEN_DEFAULT_MODEL,- // Provenance, which the resolved `model` above erases: this is the only- // place that still knows whether the id is PortOS's own shipped pin or- // something a human chose. The agy provider re-points a shipped pin that- // the vendor has retired from its catalog, and must never do that to a- // user's — an id typed into Settings (or sent as a per-render override)- // is a deliberate choice, even when it happens to equal the shipped one.- modelIsShippedDefault: !override && !a.model,+ // Provenance, which the resolved `model` above erases: whether the id is+ // PortOS's own shipped pin or something a human chose. The agy provider+ // re-points a shipped pin that the vendor has retired from its catalog,+ // and must never do that to a user's — an id typed into Settings (or sent+ // as a per-render override) is a deliberate choice, even when it happens+ // to equal the shipped one.+ //+ // The absence of a value is only HALF the answer. A caller that already+ // walked the render-target ladder hands the resolved id back as an+ // override, so by the time it reaches here every id looks chosen — which+ // is exactly how the flag never fired for a record-tagged render (#7366).+ // Such a caller says so with `overrideIsShippedDefault` instead.+ modelIsShippedDefault: overrideIsShippedDefault || (!override && !a.model),}),}),});@@ -120,11 +126,17 @@ export const CLOUD_PROVIDER_SPECS = Object.freeze({* which strip the dispatcher-only field).* - `jobParams` — `{ mode, ...providerParams }` for `enqueueJob`, where* `mode` is the queue's lane discriminator.+ * - `modelIsShippedDefault` — whether `modelId` is PortOS's own shipped pin+ * rather than a choice, for the providers that re-point a+ * retired shipped default (agy). Always false elsewhere.* - `disabledError` — a ready-to-throw ServerError (null when enabled).* - `disabledReason` — `'<mode>-disabled'`, for callers that skip silently.* - `connectionReason` — reason string for `checkConnection` responses.** `overrides.model` is the per-render model id (the request's `cloudModel`).+ * `overrides.modelIsShippedDefault` is its PROVENANCE, set only by a caller+ * re-resolving a model id this resolver already produced from the shipped+ * default (see `prepareParams.js`) — it is ignored without an override.* It only applies to providers whose spec sets `supportsModelOverride` — a* value passed for grok is ignored rather than silently changing nothing at* spawn time. Blank/whitespace is treated as "inherit the saved default", so@@ -138,13 +150,22 @@ export function resolveCloudProviderConfig(settings, mode, overrides = {}) {const enabled = config.enabled === true;const requestedModel = typeof overrides.model === 'string' ? overrides.model.trim() : '';const modelOverride = spec.supportsModelOverride && requestedModel ? requestedModel : null;- const providerParams = spec.params(config, modelOverride);+ // Only meaningful ALONGSIDE an override: it says the id the caller handed in+ // is one this resolver itself produced from the shipped default a moment ago,+ // not a choice. Without an override the spec answers from the config as it+ // always did, so a stray marker can never invent provenance for a user's pin.+ const overrideIsShippedDefault = Boolean(modelOverride) && overrides.modelIsShippedDefault === true;+ const providerParams = spec.params(config, modelOverride, overrideIsShippedDefault);return {mode,config,enabled,supportsModelOverride: spec.supportsModelOverride === true,modelOverride,+ // Re-surfaced at the top level so a caller threading this bundle's model+ // onward can thread its provenance with it, without reaching into the+ // per-provider `providerParams` bag (only agy carries the field there).+ modelIsShippedDefault: providerParams.modelIsShippedDefault === true,modelId: spec.modelId(config, modelOverride),providerParams,jobParams: { mode, ...providerParams },diff --git a/server/services/imageGen/cloudProviderConfig.test.js b/server/services/imageGen/cloudProviderConfig.test.jsindex 1944b62e66..a5573a9bb5 100644--- a/server/services/imageGen/cloudProviderConfig.test.js+++ b/server/services/imageGen/cloudProviderConfig.test.js@@ -370,6 +370,68 @@ describe('resolveRenderTargetConfig (#3231)', () => {expect(cloud.modelId).toBe('record-model');});+ // #7366 — the shipped-default flag is what lets the agy provider re-point a+ // model the vendor retired. A record-tagged render resolves the ladder here,+ // stamps the resolved id onto `data.cloudModel`, and the dispatch re-resolves+ // from that id alone — at which point a materialized shipped default looked+ // exactly like a deliberate choice and the flag never fired. Music Video and+ // Universe Bible renders are unattended, so the symptom was a raw vendor+ // error where the re-point should have kept the render alive.+ describe('shipped-default provenance across the ladder round-trip', () => {+ const agySettings = settingsWith({ agy: { enabled: true, agyPath: '/bin/agy' } });++ // The ladder → stamp → dispatch round-trip prepareParams/routes perform.+ const roundTrip = (settings, target, options = {}) => {+ const resolved = resolveRenderTargetConfig(settings, target, options);+ return resolveCloudProviderConfig(settings, resolved.mode, {+ model: resolved.cloud.modelId,+ modelIsShippedDefault: resolved.cloud.modelIsShippedDefault,+ });+ };++ it('survives the round-trip when nothing anywhere pins a model', () => {+ const resolved = resolveRenderTargetConfig(agySettings, 'universe-bible', {+ mode: IMAGE_GEN_MODE.AGY,+ });+ expect(resolved.cloud.modelId).toBe(AGY_IMAGEGEN_DEFAULT_MODEL);+ expect(resolved.cloud.modelIsShippedDefault).toBe(true);++ const dispatched = roundTrip(agySettings, 'universe-bible', { mode: IMAGE_GEN_MODE.AGY });+ expect(dispatched.providerParams.model).toBe(AGY_IMAGEGEN_DEFAULT_MODEL);+ expect(dispatched.providerParams.modelIsShippedDefault).toBe(true);+ });++ it('stays false for a model the RECORD pinned, even when it equals the shipped one', () => {+ // A user who typed the shipped id made a deliberate choice; re-pointing it+ // would render something else under the model name they chose.+ const dispatched = roundTrip(agySettings, 'universe-bible', {+ recordMode: IMAGE_GEN_MODE.AGY,+ recordModel: AGY_IMAGEGEN_DEFAULT_MODEL,+ });+ expect(dispatched.providerParams.model).toBe(AGY_IMAGEGEN_DEFAULT_MODEL);+ expect(dispatched.providerParams.modelIsShippedDefault).toBe(false);+ });++ it('stays false for a saved install-wide default and a per-request override', () => {+ const saved = settingsWith({ agy: { enabled: true, model: AGY_IMAGEGEN_DEFAULT_MODEL } });+ expect(roundTrip(saved, 'universe-bible', { mode: IMAGE_GEN_MODE.AGY })+ .providerParams.modelIsShippedDefault).toBe(false);+ expect(roundTrip(agySettings, 'universe-bible', {+ mode: IMAGE_GEN_MODE.AGY, model: 'gemini-3.6-flash-high',+ }).providerParams.modelIsShippedDefault).toBe(false);+ });++ it('ignores the marker without an override, so it cannot invent provenance', () => {+ // The field is a hint ABOUT an override. Alone it must change nothing, or+ // a stray value would authorize re-pointing a user's saved pin.+ const saved = settingsWith({ agy: { enabled: true, model: 'user-pinned' } });+ const cloud = resolveCloudProviderConfig(saved, IMAGE_GEN_MODE.AGY, {+ modelIsShippedDefault: true,+ });+ expect(cloud.providerParams.modelIsShippedDefault).toBe(false);+ });+ });+it('recordRenderPin normalizes auto/blank/missing to null', () => {expect(recordRenderPin(null)).toEqual({ mode: null, modelId: null });expect(recordRenderPin({ imageMode: 'auto', imageModelId: ' ' })).toEqual({ mode: null, modelId: null });diff --git a/server/services/imageGen/index.js b/server/services/imageGen/index.jsindex 085a78bb6b..ec81d6e43d 100644--- a/server/services/imageGen/index.js+++ b/server/services/imageGen/index.js@@ -136,8 +136,14 @@ export async function generateImage(params) {// Per-render cloud-CLI model override. Dispatcher-only too: it is folded// into the provider's own `model` param by resolveCloudProviderConfig below,// so providers never see the raw field.+ // Its PROVENANCE rides beside it, for the same reason: a caller that already+ // walked the render-target ladder hands back a model id the resolver itself+ // produced, and without this marker a materialized shipped default would read+ // as a deliberate choice (#7366). Dispatcher-only, so stripped like the id.const cloudModel = normalized.cloudModel;+ const modelIsShippedDefault = normalized.cloudModelIsShippedDefault;delete normalized.cloudModel;+ delete normalized.cloudModelIsShippedDefault;// Input images are supported by local (mflux/diffusers --image-path plus// FLUX.2 --reference-images), codex (image_gen.referenced_image_paths via the// CLI's -i flag), grok (image_edit.image) and agy (generate_image.ImagePaths).@@ -164,7 +170,7 @@ export async function generateImage(params) {// knobs (codexPath/model/effort vs grokPath/aspectRatio) come from the// resolver's spec, so a saved override always wins over the provider's own// internal defaults.- const cloud = resolveCloudProviderConfig(s, mode, { model: cloudModel });+ const cloud = resolveCloudProviderConfig(s, mode, { model: cloudModel, modelIsShippedDefault });if (cloud) {if (!cloud.enabled) throw cloud.disabledError;return guardResolvedFrame(await CLOUD_PROVIDERS[mode].generateImage({ ...cloud.providerParams, cleanC2PA, denoise, ...normalized }));diff --git a/server/services/imageGen/prepareParams.js b/server/services/imageGen/prepareParams.jsindex e5f5aec137..47be68f251 100644--- a/server/services/imageGen/prepareParams.js+++ b/server/services/imageGen/prepareParams.js@@ -179,7 +179,15 @@ export async function prepareGenerateParams({ data, files, referenceImageFieldsfallbackMode: IMAGE_GEN_MODE.EXTERNAL,});mode = resolved.mode;- if (!data.cloudModel && resolved.cloud?.modelId) data.cloudModel = resolved.cloud.modelId;+ // Stamping the id ERASES where it came from, and the dispatch below+ // re-resolves from `data.cloudModel` alone — so a shipped default+ // materialized here would arrive there looking like a deliberate choice and+ // the retired-default re-point would never run for a record-tagged render+ // (#7366). The provenance rides along as its own dispatcher-level field.+ if (!data.cloudModel && resolved.cloud?.modelId) {+ data.cloudModel = resolved.cloud.modelId;+ data.cloudModelIsShippedDefault = resolved.cloud.modelIsShippedDefault === true;+ }}// The render's input images, counted once: the init image (uploaded this// request or named by an earlier one) plus every reference slot. Every gatediff --git a/server/services/imageGen/prepareParams.test.js b/server/services/imageGen/prepareParams.test.jsindex f4da1331ff..bf3591ad5d 100644--- a/server/services/imageGen/prepareParams.test.js+++ b/server/services/imageGen/prepareParams.test.js@@ -21,6 +21,7 @@ const getUniverseRenderPin = vi.fn(async () => null);vi.mock('../universeBuilder/crud.js', () => ({ getUniverseRenderPin: (...a) => getUniverseRenderPin(...a) }));const { prepareGenerateParams, selectLocalImageModel } = await import('./prepareParams.js');+const { AGY_IMAGEGEN_DEFAULT_MODEL } = await import('./modes.js');const CODEX_ON = { codex: { enabled: true, codexPath: '/bin/codex' } };const run = (data) => prepareGenerateParams({ data, files: undefined, referenceImageFields: [] });@@ -186,4 +187,30 @@ describe('universe render-target resolution', () => {expect(data.cloudModel).toBe('mv-model');expect(getUniverseRenderPin).not.toHaveBeenCalled();});++ // #7366 — stamping the resolved id erases where it came from, and the route's+ // dispatch re-resolves from that id alone. Without the provenance riding+ // beside it, a shipped default materialized here reads as a deliberate choice+ // downstream and the agy retired-default re-point never runs — on exactly the+ // unattended surfaces (Music Video, Universe Bible) it exists to protect.+ it('stamps the shipped-default provenance beside the model it materialized', async () => {+ getSettings.mockResolvedValue({ imageGen: { mode: 'local', ...AGY_ON } });+ getUniverseRenderPin.mockResolvedValue({ imageMode: 'agy', imageModelId: null });+ const { data, mode } = await run({ prompt: 'p', universeRun: tag });+ expect(mode).toBe('agy');+ expect(data.cloudModel).toBe(AGY_IMAGEGEN_DEFAULT_MODEL);+ expect(data.cloudModelIsShippedDefault).toBe(true);+ });++ it('stamps provenance FALSE for a model the record itself pinned', async () => {+ getSettings.mockResolvedValue({ imageGen: { mode: 'local', ...AGY_ON } });+ // The record pins the shipped id by hand — a choice, so it must never be+ // re-pointed out from under the render.+ getUniverseRenderPin.mockResolvedValue({+ imageMode: 'agy', imageModelId: AGY_IMAGEGEN_DEFAULT_MODEL,+ });+ const { data } = await run({ prompt: 'p', universeRun: tag });+ expect(data.cloudModel).toBe(AGY_IMAGEGEN_DEFAULT_MODEL);+ expect(data.cloudModelIsShippedDefault).toBe(false);+ });});diff --git a/server/services/modelPinAuditNotifier.js b/server/services/modelPinAuditNotifier.jsindex c3496a47f7..1ca5387c13 100644--- a/server/services/modelPinAuditNotifier.js+++ b/server/services/modelPinAuditNotifier.js@@ -18,11 +18,20 @@* **The card IS the dedupe state.** `providers.json` is written by a refresh, a* legacy `PATCH /api/providers/:id`, a migration and a boot seed alike, so an* install carrying one rotted pin would narrate on every one of them forever.- * `notifications.exists(type, 'pinId', id)` answers "has this pin already been- * announced?" from the durable record itself — so a restart cannot re-announce,- * which is exactly what an in-process transition set could not promise. The- * card is retracted when the pin is cleared (`modelPinAudit.clearModelPin`), so- * a pin that is re-created and rots again announces again.+ * The card answers "has this pin already been announced?" from the durable+ * record itself — so a restart cannot re-announce, which is exactly what an+ * in-process transition set could not promise.+ *+ * **What is deduped is the pin's VALUE, not its location** (#7366). `pin.id`+ * says where a pin lives; the retirement being announced is about the model it+ * holds. Keying on the id alone meant a user who repointed the pin in Settings+ * — rather than clearing it from the panel — kept a card naming the old model+ * forever, AND had the card permanently suppressed for the next model retired+ * at that same location, which is the case the feature exists for. So the+ * dedupe key is `pinId` + `model`, and every announced card whose pin no longer+ * names that model is retracted by `reconcile()` below on the next audit —+ * whatever path moved it. `clearModelPin` still retracts by `pinId` alone, so a+ * clear from the panel is immediate rather than waiting for the next refresh.** `data/notifications.json` is machine-local — nothing in `server/` federates* it — so this raises no privacy or sync question.@@ -76,6 +85,18 @@ let notificationsModule = null;const loadAuditModule = () => (auditModule ||= import('./modelPinAudit.js'));const loadNotificationsModule = () => (notificationsModule ||= import('./notifications.js'));+/**+ * The identity of what a card ANNOUNCES: this pin, holding this model.+ *+ * A NEWLINE rather than a printable separator — a pin id embeds dots, colons and+ * slashes (`settings:codeReview.providerModels.provider:x`) and so does a model+ * id, so any separator a user could type could be forged into a collision+ * between two different pins. A newline can appear in neither — every pin id is+ * built here from a settings path or a record id, and a model id is charset-+ * bounded well before it is stored.+ */+const pinCardKey = (pin) => `${pin.id}\n${pin.model}`;+/*** One card per pin, so each carries the pin's own `href`/`location` and can be* retracted independently when that one pin is cleared. A single rolled-up card@@ -85,7 +106,9 @@ async function announce(pin, providers) {const { addNotification, exists, NOTIFICATION_TYPES, PRIORITY_LEVELS } =await loadNotificationsModule();// The persisted card is the dedupe record: already announced, still true.- if (await exists(NOTIFICATION_TYPES.AGENT_WARNING, 'pinId', pin.id)) return false;+ // Keyed by the pin's VALUE, so a pin repointed to a DIFFERENT retired model+ // announces the new one instead of being silenced by the old card.+ if (await exists(NOTIFICATION_TYPES.AGENT_WARNING, 'pinKey', pinCardKey(pin))) return false;// Every record the pin was judged against, not just the first: a reviewer pin// spans several (#7339), and naming one would have this card disagree with the// panel about the same pin. `pinProviderNames` is what both call.@@ -97,14 +120,62 @@ async function announce(pin, providers) {+ ` — clear it in ${pin.location}.`,priority: PRIORITY_LEVELS.MEDIUM,link: pin.href || null,- metadata: { pinId: pin.id, kind: pin.kind, providerIds: pin.providerIds, model: pin.model },+ // `pinId` stays beside `pinKey`: it is what `clearModelPin` retracts by,+ // and what a surface linking back to the pin reads.+ metadata: {+ pinId: pin.id, pinKey: pinCardKey(pin),+ kind: pin.kind, providerIds: pin.providerIds, model: pin.model,+ },});return true;}+/**+ * Retract every announced card the current audit no longer earns.+ *+ * `clearModelPin` covers the ONE path that starts at the card, and covered only+ * that: a pin repointed anywhere else — Settings, a record edit, a template+ * save, a `PATCH` — left its card standing forever, naming a model the pin no+ * longer holds (#7366). The audit already knows the complete set of pins that+ * are stale right now, so every other announced card is stale BY DEFINITION,+ * whatever moved it: the pin was repointed to a live model, repointed to a+ * different retired one (announced again under its new key), or deleted+ * outright. Retracting from the derived set needs no change-detection and no+ * second source of truth, which is the same posture as the audit itself.+ *+ * Scoped to cards this module wrote — `AGENT_WARNING` carrying a `pinKey` — so+ * a warning raised by any other producer is never touched. A card predating+ * #7366 carries no `pinKey`; it is retracted here and re-announced under the+ * new key on the same pass if the pin is still stale, so an upgrading install+ * converges on the first audit rather than needing a migration.+ */+async function reconcile(stalePins) {+ const { getNotifications, removeNotification, NOTIFICATION_TYPES } = await loadNotificationsModule();+ const earned = new Set(stalePins.map(pinCardKey));+ const cards = await getNotifications({ type: NOTIFICATION_TYPES.AGENT_WARNING });+ // Sequential for the same reason the announcements are: these share one file.+ for (const card of cards) {+ if (!card.metadata?.pinId) continue;+ if (card.metadata.pinKey && earned.has(card.metadata.pinKey)) continue;+ await removeNotification(card.id).catch((error) => {+ console.error(`❌ Retracting stale retired-pin card ${card.id} failed: ${error.message}`);+ });+ }+}+async function reportOnce() {const { auditModelPins } = await loadAuditModule();const { pins, providers } = await auditModelPins();+ // BEFORE the early return below and before announcing: an install whose last+ // stale pin was just repointed to a live model has an empty pin set and a+ // card that must still come down.+ //+ // Non-fatal, like each individual announcement: a failed retraction must not+ // swallow the announcements behind it. The next audit re-derives the same set+ // and retries whatever is still standing.+ await reconcile(pins).catch((error) => {+ console.error(`❌ Reconciling retired-pin notifications failed: ${error.message}`);+ });if (pins.length === 0) return;// Sequential, not Promise.all: `addNotification` and `exists` share one file,// and two concurrent announcements of the same pin would both miss the carddiff --git a/server/services/modelPinAuditNotifier.test.js b/server/services/modelPinAuditNotifier.test.jsindex 17e61c8192..5644ba11fd 100644--- a/server/services/modelPinAuditNotifier.test.js+++ b/server/services/modelPinAuditNotifier.test.js@@ -19,12 +19,16 @@ vi.mock('./modelPinAudit.js', () => ({ auditModelPins: vi.fn() }));vi.mock('./notifications.js', () => ({addNotification: vi.fn(),exists: vi.fn(),+ getNotifications: vi.fn(),+ removeNotification: vi.fn(),NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },PRIORITY_LEVELS: { LOW: 'low', MEDIUM: 'medium', HIGH: 'high' },}));const { auditModelPins } = await import('./modelPinAudit.js');-const { addNotification, exists } = await import('./notifications.js');+const {+ addNotification, exists, getNotifications, removeNotification,+} = await import('./notifications.js');const {reportRetiredModelPins, resetModelPinReportState,} = await import('./modelPinAuditNotifier.js');@@ -46,15 +50,29 @@ const audited = (...pins) => ({});/**- * The persisted notification store, as the module sees it: `exists` answers- * from what `addNotification` has already written. Mocking the two independently- * would let the dedupe pass while the real round-trip is broken.+ * The persisted notification store, as the module sees it: every read answers+ * from what the writes have already put there. Mocking them independently would+ * let the dedupe and the retraction both pass while the real round-trip is+ * broken — which is exactly how a card keyed on the pin's LOCATION looked+ * correct for a release (#7366).*/function backNotificationsWithAStore() {const cards = [];+ let nextId = 1;exists.mockImplementation(async (type, field, value) =>cards.some((card) => card.type === type && card.metadata?.[field] === value));- addNotification.mockImplementation(async (card) => { cards.push(card); return card; });+ addNotification.mockImplementation(async (card) => {+ const stored = { id: `card-${nextId++}`, ...card };+ cards.push(stored);+ return stored;+ });+ getNotifications.mockImplementation(async ({ type } = {}) =>+ cards.filter((card) => !type || card.type === type));+ removeNotification.mockImplementation(async (id) => {+ const at = cards.findIndex((card) => card.id === id);+ if (at >= 0) cards.splice(at, 1);+ return { success: true };+ });return cards;}@@ -123,6 +141,75 @@ describe('reportRetiredModelPins', () => {expect(logged).not.toHaveBeenCalled();});+ // #7366 — the dedupe key was `pin.id`, which says where a pin LIVES, not what+ // it holds. These three pin the value-keyed behavior that replaced it.+ it('announces again when the pin is repointed to ANOTHER retired model', async () => {+ const cards = backNotificationsWithAStore();+ auditModelPins.mockResolvedValue(audited(pin('settings:imageGen.agy.model')));+ await reportRetiredModelPins();+ addNotification.mockClear();++ // The user repoints the pin in Settings rather than clearing it from the+ // panel, and the new id is retired too. Keying on the pin's location alone+ // suppressed this card permanently — the exact case the feature exists for.+ auditModelPins.mockResolvedValue(audited(+ pin('settings:imageGen.agy.model', { model: 'retired-model-9' }),+ ));+ await reportRetiredModelPins();++ expect(addNotification).toHaveBeenCalledTimes(1);+ expect(addNotification.mock.calls[0][0].description).toContain('retired-model-9');+ // And exactly ONE card stands: the one naming the model the pin holds now.+ expect(cards.map((card) => card.metadata.model)).toEqual(['retired-model-9']);+ });++ it('retracts the card when the pin is repointed to a LIVE model', async () => {+ const cards = backNotificationsWithAStore();+ auditModelPins.mockResolvedValue(audited(pin('settings:imageGen.agy.model')));+ await reportRetiredModelPins();+ expect(cards).toHaveLength(1);++ // Repointed in Settings, so `clearModelPin` — the only retraction path+ // before #7366 — never ran. The pin drops out of the stale set, and a card+ // naming a model the pin no longer holds is a loop the user cannot close.+ auditModelPins.mockResolvedValue(audited());+ await reportRetiredModelPins();++ expect(cards).toHaveLength(0);+ expect(removeNotification).toHaveBeenCalledTimes(1);+ });++ it('announces the new model even when retracting the old card FAILS', async () => {+ // The two guards are deliberately independent: `reconcile` normally takes+ // the superseded card down first, but it is non-fatal, so the dedupe key+ // must carry the pin's VALUE on its own. Keyed on `pin.id` alone, a failed+ // retraction silences the new retirement until someone clears the pin by+ // hand — which is the #7366 failure mode surviving its own fix.+ auditModelPins.mockResolvedValue(audited(pin('settings:imageGen.agy.model')));+ await reportRetiredModelPins();+ addNotification.mockClear();++ removeNotification.mockRejectedValueOnce(new Error('notifications.json unwritable'));+ auditModelPins.mockResolvedValue(audited(+ pin('settings:imageGen.agy.model', { model: 'retired-model-9' }),+ ));+ await reportRetiredModelPins();++ expect(addNotification).toHaveBeenCalledTimes(1);+ expect(addNotification.mock.calls[0][0].metadata.model).toBe('retired-model-9');+ });++ it('leaves an AGENT_WARNING raised by another producer alone', async () => {+ const cards = backNotificationsWithAStore();+ cards.push({ id: 'other-1', type: 'agent_warning', metadata: { runId: 'abc' } });+ auditModelPins.mockResolvedValue(audited());++ await reportRetiredModelPins();++ expect(cards).toHaveLength(1);+ expect(removeNotification).not.toHaveBeenCalled();+ });+it('stays silent across a RESTART, because the card is the dedupe record', async () => {auditModelPins.mockResolvedValue(audited(pin('settings:imageGen.agy.model')));await reportRetiredModelPins();diff --git a/server/services/persistentMindIssueCapability.js b/server/services/persistentMindIssueCapability.jsindex 8dae2353c5..2d63bc9cda 100644--- a/server/services/persistentMindIssueCapability.js+++ b/server/services/persistentMindIssueCapability.js@@ -29,6 +29,8 @@ import {import { forgeIssueCreateArgs, forgeLabelCreateArgs, parseCreatedForgeIssue } from '../lib/forgeIssueCli.js';import { boundedByJsonChars } from '../lib/objects.js';import { boundedErrorMessage } from '../lib/errorHandler.js';+import { scrubHomePath } from '../lib/homePath.js';+import { scrubSecretTokens } from '../lib/secretText.js';import {PERSISTENT_MIND_ISSUE_EXTRA_LABEL_SPECS,PERSISTENT_MIND_ISSUE_CATEGORY_LABELS,@@ -39,6 +41,28 @@ import {const MAX_CATALOG_PROMPT_CHARS = 2_000;+/**+ * The last thing that happens to a title/body before `gh`/`glab` sees it.+ *+ * The capability's Settings guardrail asserts that no repository paths or+ * credentials ride along, and a filed issue is world-readable the moment it+ * lands — so the assertion has to be ENFORCED here rather than trusted to the+ * prompt above. Both halves are mechanically decidable and already have one+ * definition in the tree: `scrubHomePath` collapses the running user's home+ * prefix (which is what embeds the OS username in `/Users/<name>/…`), and+ * `scrubSecretTokens` replaces credential-SHAPED substrings. Neither is a+ * content filter — "no private records" stays a prompt instruction, because no+ * regex can decide whether a sentence of the mind's own prose is one, and the+ * guardrail text now says exactly that rather than promising more.+ *+ * Applied to the TITLE as well as the body: the title is what a duplicate check+ * on any other machine reads back, and a leaked path there is just as public.+ *+ * Both helpers pass a non-string through untouched, so this adds no coercion of+ * its own — the tool schema already requires both fields to be strings.+ */+const scrubForgeText = (value) => scrubSecretTokens(scrubHomePath(value));+const labelSpec = (name) => dispatchLabelSpec(name)|| (PERSISTENT_MIND_ISSUE_EXTRA_LABEL_SPECS[name]? { name, ...PERSISTENT_MIND_ISSUE_EXTRA_LABEL_SPECS[name] }@@ -75,6 +99,8 @@ Read before you write. Call issues.list for the target app first and skip anythiFile 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.+A filed issue is world-readable. Write the title and body in your own prose and never paste in a secret, an absolute filesystem path, a hostname, network address, personal name, contact detail, or the contents of a private record — refer to a file by its repo-relative path instead. Home-directory prefixes and credential-shaped strings are stripped before filing, but that scrub cannot recognize a private record, so keeping one out is on you.+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.@@ -191,9 +217,15 @@ export async function filePersistentMindIssue(args) {if (existing.transient) {return { ok: false, error: `Could not read the existing ${app.forge} issues to check for duplicates (${existing.reason}); nothing was filed` };}+ // Scrubbed BEFORE the duplicate check, not just before the create: the title+ // that dedupes has to be the title that gets filed, or an issue whose only+ // leaked path was in its title would re-file itself on every wake.+ const title = scrubForgeText(args.title);+ const body = scrubForgeText(args.body);+// An all-punctuation title normalizes to the empty string, which would match// every other such title — only a title with real content can dedupe.- const titleKey = normalizeIssueTitleKey(args.title);+ const titleKey = normalizeIssueTitleKey(title);const duplicate = titleKey&& existing.issues.find((issue) => normalizeIssueTitleKey(issue.title) === titleKey);if (duplicate) {@@ -217,7 +249,7 @@ export async function filePersistentMindIssue(args) {].filter((name, index, all) => all.indexOf(name) === index);await ensureLabels({ app, names: labels });- const created = await createIssue({ app, title: args.title, body: args.body, labels });+ const created = await createIssue({ app, title, body, labels });if (!created.ok) return created;return {ok: true,diff --git a/server/services/persistentMindIssueCapability.test.js b/server/services/persistentMindIssueCapability.test.jsindex 7facb10f1b..eefc489daa 100644--- a/server/services/persistentMindIssueCapability.test.js+++ b/server/services/persistentMindIssueCapability.test.js@@ -1,4 +1,5 @@import { beforeEach, describe, expect, it, vi } from 'vitest';+import { homedir } from 'os';const mocks = vi.hoisted(() => ({root: {},@@ -196,6 +197,62 @@ describe('persistent mind issue capability', () => {.toMatchObject({ ok: false, error: expect.stringContaining('gh auth login') });});+ // #7366 — the Settings guardrail asserted that no repository paths or+ // credentials ride along, while title and body reached `gh issue create`+ // untouched. A filed issue is world-readable, so the assertion has to be+ // ENFORCED, not merely stated. `homedir()` is read at runtime rather than+ // written down: the value is the developer's own private data.+ describe('scrubs what the Settings guardrail promises', () => {+ const argValue = (args, flag) => args[args.indexOf(flag) + 1];++ it('strips the home-directory prefix and credential-shaped tokens before filing', async () => {+ const home = homedir();+ const result = await filePersistentMindIssue(fileRequest({+ title: `Sync fails under ${home}/work/demo`,+ body: `The poller retries with ghp_${'A'.repeat(36)} and dies.\nSee ${home}/logs/sync.log.`,+ }));+ expect(result.ok).toBe(true);++ const [args] = ghArgsFor('issue')[0] ? [ghArgsFor('issue')[0]] : [[]];+ const title = argValue(args, '--title');+ const body = argValue(args, '--body');+ expect(title).toBe('Sync fails under ~/work/demo');+ expect(title).not.toContain(home);+ expect(body).toContain('[REDACTED]');+ expect(body).not.toContain('ghp_');+ expect(body).not.toContain(home);+ expect(body).toContain('~/logs/sync.log');+ });++ it('dedupes on the SCRUBBED title, so a leaky title cannot re-file every wake', async () => {+ const home = homedir();+ mocks.listAppIssues.mockResolvedValue(okList([+ openIssue({ number: 12, title: 'Sync fails under ~/work/demo' }),+ ]));++ expect(await filePersistentMindIssue(fileRequest({+ title: `Sync fails under ${home}/work/demo`,+ }))).toMatchObject({ ok: true, duplicate: true, number: 12 });+ expect(ghArgsFor('issue')).toHaveLength(0);+ });++ it('leaves ordinary prose, repo-relative paths and short ids untouched', async () => {+ const body = 'server/services/sync.js drops job 4f2a on retry — see PR #118.';+ await filePersistentMindIssue(fileRequest({ title: 'Sync drops a job on retry', body }));+ expect(argValue(ghArgsFor('issue')[0], '--body')).toBe(body);+ });++ it('tells the model to keep private records out, since no filter can', () => {+ // The scrub is mechanical; "private record" is not decidable by regex, so+ // that half has to reach the model as an instruction or it is untrue.+ const prompt = buildPersistentMindIssueCapabilityPrompt({+ enabled: true, catalog: { apps: [{ id: 'demo-app', forge: 'github' }] },+ });+ expect(prompt).toContain('world-readable');+ expect(prompt).toContain('private record');+ });+ });+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');