Skip to content

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

feat: protect literal-key prompt stages from deletion via a generated call-site manifest (#3335)

[._.]/ Adam Eivye2ad9810d5b1
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 8921b8a950..fc99a07ad4 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -142,3 +142,4 @@
## Internal
- **[issue-3313] The URL search-param patch helper is now one hook instead of three copies.** `updateParams(patch, { replace })` — merge a patch into the query string, dropping keys set to empty so a cleared filter leaves the URL clean — had been re-typed into Catalog, Media Collections, and (in a narrower single-key form) the 3D page. It now lives in `useUrlParams`, which reads the live params off a ref because react-router's functional updater hands the callback the params captured at the render that memoized it — a debounced `?q=` write armed before a sort change would otherwise navigate with the pre-change snapshot and silently drop the sort the user just picked. The hook is also referentially stable, so the debounce effects on those pages stop re-arming every time an unrelated param changes.
+- **[issue-3335] Deleting a prompt stage now checks the source, not a hand-written list of ten.** `DELETE /api/prompts/:stage` force-guarded exactly the ten curated CoS/Brain/Memory stages, so removing `pipeline-series-concept-judge` (or roughly a hundred others PortOS resolves by literal key) succeeded with no warning and left the feature naming it throwing `Stage <key> not found` on its next run. Adding them all to the curated table was the wrong fix — the same table drives the Prompt Manager's `SYSTEM` badge and its "System only" filter, and badging ~100 of 127 rows makes both meaningless. Deletion protection is now a second, generated set: a checked-in manifest indexes every stage key a `server/` source names, including the ones reached only through an interpolated prefix like `pipeline-panel-${personaId}`, and a drift test fails until a new call site is regenerated into it. The badge and the filter still show the same ten stages; the delete dialog now names the files that reference the one you're about to remove.
diff --git a/client/src/pages/PromptManager.jsx b/client/src/pages/PromptManager.jsx
index d6f6a5846a..17c70706dc 100644
--- a/client/src/pages/PromptManager.jsx
+++ b/client/src/pages/PromptManager.jsx
@@ -250,18 +250,24 @@ export default function PromptManager() {
};
const requestDeleteStage = async (stageName) => {
- // Check if stage is in use
+ // Check if stage is in use. On failure fall back to "deletable" rather
+ // than "protected" — a false `canDelete: false` would silently force-delete
+ // a user stage, while a false `true` just lets the server's own guard
+ // return SYSTEM_STAGE_PROTECTED, which the toast surfaces.
const usageRes = await getPromptUsage(stageName, { silent: true })
- .catch(() => ({ isSystemStage: false, usedBy: [] }));
+ .catch(() => ({ isSystemStage: false, usedBy: [], referencedBy: [], canDelete: true }));
setDeleteConfirm({ stageName, ...usageRes });
};
const confirmDeleteStage = async () => {
- const { stageName, isSystemStage } = deleteConfirm;
+ const { stageName, canDelete } = deleteConfirm;
setDeleteConfirm(null);
- const ok = await deletePrompt(stageName, { force: isSystemStage }, { silent: true })
+ // The server refuses without ?force=true for BOTH the curated system set
+ // and any stage its source references by name (#3335), so gate on
+ // `canDelete` — `isSystemStage` alone would 400 on a pipeline stage.
+ const ok = await deletePrompt(stageName, { force: canDelete === false }, { silent: true })
.then(() => true)
.catch((err) => { toast.error(`Failed to delete: ${err.message || 'Unknown error'}`); return false; });
@@ -1038,16 +1044,30 @@ export default function PromptManager() {
>
<div className="bg-port-card border border-port-border rounded-xl p-6">
<h3 id="delete-stage-title" className="text-lg font-medium text-white mb-3">
- {deleteConfirm?.isSystemStage ? 'Delete System Stage?' : 'Delete Stage?'}
+ {deleteConfirm?.canDelete === false
+ ? (deleteConfirm.isSystemStage ? 'Delete System Stage?' : 'Delete Referenced Stage?')
+ : 'Delete Stage?'}
</h3>
- {deleteConfirm?.isSystemStage ? (
+ {/* Protected covers both the curated SYSTEM set and any stage the
+ server's source references by name — the latter is badge-less but
+ just as breakable, so it gets the same warning plus the files
+ that name it (#3335). */}
+ {deleteConfirm?.canDelete === false ? (
<div className="space-y-2 mb-6">
<p className="text-port-warning text-sm font-medium">
- "{deleteConfirm.stageName}" is a system stage.
+ "{deleteConfirm.stageName}" is {deleteConfirm.isSystemStage ? 'a system stage' : 'referenced by PortOS source'}.
</p>
{deleteConfirm.usedBy?.length > 0 && (
<p className="text-gray-400 text-sm">Used by: {deleteConfirm.usedBy.join(', ')}</p>
)}
+ {deleteConfirm.referencedBy?.length > 0 && (
+ <div className="text-gray-400 text-sm">
+ <p className="mb-1">Referenced in:</p>
+ <ul className="max-h-32 overflow-y-auto space-y-0.5 font-mono text-xs break-all">
+ {deleteConfirm.referencedBy.map((path) => <li key={path}>{path}</li>)}
+ </ul>
+ </div>
+ )}
<p className="text-gray-400 text-sm">Deleting this will break PortOS functionality.</p>
</div>
) : (
diff --git a/client/src/pages/PromptManager.test.jsx b/client/src/pages/PromptManager.test.jsx
index d21e49fe81..9dee42611e 100644
--- a/client/src/pages/PromptManager.test.jsx
+++ b/client/src/pages/PromptManager.test.jsx
@@ -9,13 +9,14 @@ import PromptManager from './PromptManager';
const getPrompts = vi.fn();
const getPrompt = vi.fn();
const getPromptUsage = vi.fn();
+const deletePrompt = vi.fn();
vi.mock('../services/apiPrompts', () => ({
getPrompts: (...a) => getPrompts(...a),
getPrompt: (...a) => getPrompt(...a),
createPrompt: vi.fn(),
savePrompt: vi.fn(),
- deletePrompt: vi.fn(),
+ deletePrompt: (...a) => deletePrompt(...a),
previewPrompt: vi.fn(),
getPromptUsage: (...a) => getPromptUsage(...a),
getPromptVariables: vi.fn(() => Promise.resolve({ variables: {} })),
@@ -60,7 +61,9 @@ describe('PromptManager stage list', () => {
beforeEach(() => {
getPrompts.mockReset().mockResolvedValue({ stages: STAGES, systemStages: SYSTEM_STAGES });
getPrompt.mockReset().mockResolvedValue({ name: 'Pipeline — Prose Draft', template: 'body', variables: [] });
- getPromptUsage.mockReset().mockResolvedValue({ isSystemStage: false, usedBy: [] });
+ getPromptUsage.mockReset().mockResolvedValue({
+ isSystemStage: false, usedBy: [], referencedBy: [], canDelete: true,
+ });
});
it('shows collapsed groups and a stage count instead of a flat 100-row list', async () => {
@@ -277,7 +280,15 @@ describe('PromptManager delete demotion', () => {
beforeEach(() => {
getPrompts.mockReset().mockResolvedValue({ stages: STAGES, systemStages: SYSTEM_STAGES });
getPrompt.mockReset().mockResolvedValue({ name: 'Brain Classifier', template: 'body', variables: [] });
- getPromptUsage.mockReset().mockResolvedValue({ isSystemStage: true, usedBy: ['Brain thought classification'] });
+ // Mirrors the exact wire body of GET /api/prompts/:stage/usage — pinned
+ // server-side in server/routes/prompts.test.js.
+ getPromptUsage.mockReset().mockResolvedValue({
+ isSystemStage: true,
+ usedBy: ['Brain thought classification'],
+ referencedBy: ['server/services/brain.js'],
+ canDelete: false,
+ });
+ deletePrompt.mockReset().mockResolvedValue({ success: true });
});
it('keeps delete — or any other control — out of the list rows entirely', async () => {
@@ -302,4 +313,45 @@ describe('PromptManager delete demotion', () => {
await waitFor(() => expect(getPromptUsage).toHaveBeenCalledWith('brain-classifier', { silent: true }));
expect(await screen.findByText('Delete System Stage?')).toBeTruthy();
});
+
+ // #3335: protection is wider than the SYSTEM badge. A pipeline stage carries
+ // no badge but is still undeletable without ?force=true, so the dialog has to
+ // warn AND the confirm has to send force — otherwise every delete 400s.
+ it('warns and names the source files for a referenced non-system stage', async () => {
+ getPromptUsage.mockResolvedValue({
+ isSystemStage: false,
+ usedBy: [],
+ referencedBy: ['server/services/pipeline/textStages.js', 'server/services/pipeline/pipelineJudge.js'],
+ canDelete: false,
+ });
+ renderPage('/prompts?stage=pipeline-comic-script');
+ await screen.findByText('Prompt Stages');
+
+ fireEvent.click(await screen.findByRole('button', { name: /^delete$/i }));
+
+ expect(await screen.findByText('Delete Referenced Stage?')).toBeTruthy();
+ expect(screen.getByText('server/services/pipeline/textStages.js')).toBeTruthy();
+ expect(screen.getByText('server/services/pipeline/pipelineJudge.js')).toBeTruthy();
+
+ // The modal's confirm is the last "Delete" in the tree (the detail pane
+ // keeps its own trigger mounted behind the backdrop).
+ fireEvent.click(screen.getAllByRole('button', { name: /^delete$/i }).at(-1));
+ await waitFor(() => expect(deletePrompt).toHaveBeenCalledWith(
+ 'pipeline-comic-script', { force: true }, { silent: true },
+ ));
+ });
+
+ it('deletes a user-authored stage without force', async () => {
+ getPromptUsage.mockResolvedValue({ isSystemStage: false, usedBy: [], referencedBy: [], canDelete: true });
+ renderPage('/prompts?stage=pipeline-comic-script');
+ await screen.findByText('Prompt Stages');
+
+ fireEvent.click(await screen.findByRole('button', { name: /^delete$/i }));
+ expect(await screen.findByText('Delete Stage?')).toBeTruthy();
+
+ fireEvent.click(screen.getAllByRole('button', { name: /^delete$/i }).at(-1));
+ await waitFor(() => expect(deletePrompt).toHaveBeenCalledWith(
+ 'pipeline-comic-script', { force: false }, { silent: true },
+ ));
+ });
});
diff --git a/scripts/generate-prompt-stage-call-sites.js b/scripts/generate-prompt-stage-call-sites.js
new file mode 100644
index 0000000000..f6f9977156
--- /dev/null
+++ b/scripts/generate-prompt-stage-call-sites.js
@@ -0,0 +1,172 @@
+#!/usr/bin/env node
+/**
+ * Generate `server/lib/promptStageCallSites.generated.json` — the DERIVED
+ * deletion-protection set for prompt stages (#3335).
+ *
+ * Why a second set at all: `server/lib/promptSystemStages.js` holds the
+ * CURATED system-stage table, which drives the Prompt Manager's SYSTEM badge
+ * and its "System only" filter. Roughly 100 of the 127 shipped stages are also
+ * resolved by literal key somewhere in `server/`, and deleting one silently
+ * breaks the feature that names it — but badging ~100 of 127 rows would make
+ * the badge and the filter meaningless. So the two concerns are split: the
+ * curated table stays small and user-facing, and THIS manifest is the
+ * machine-derived "referenced by source" index the DELETE guard also consults.
+ *
+ * Why generated rather than hand-maintained: a hand list is exactly the drift
+ * this exists to end, and a runtime source scan on every DELETE is slow and
+ * unavailable in a packaged build. `scripts/generate-prompt-stage-call-sites.test.js`
+ * regenerates and fails on drift, so a new literal-key call site can't land
+ * without the manifest catching up.
+ *
+ * Usage: node scripts/generate-prompt-stage-call-sites.js
+ *
+ * Output shape: `{ "<stage-key>": ["server/services/foo.js", …] }`, keys and
+ * paths both sorted so the file is byte-stable across installs.
+ */
+
+import { execFileSync } from 'node:child_process';
+import { readFileSync, writeFileSync } from 'node:fs';
+import { dirname, join, resolve } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const HERE = dirname(fileURLToPath(import.meta.url));
+
+/** Repo root, resolved from this script's own location. */
+export const REPO_ROOT = resolve(HERE, '..');
+
+/** Manifest location, repo-relative (posix) so it reads the same on Windows. */
+export const MANIFEST_RELATIVE_PATH = 'server/lib/promptStageCallSites.generated.json';
+
+/** The command a failing drift test tells the author to run. */
+export const REGENERATE_COMMAND = 'node scripts/generate-prompt-stage-call-sites.js';
+
+/**
+ * Call shapes whose FIRST argument is a stage key. These are only used to
+ * discover keys that the shipped `stage-config.json` doesn't list (a call site
+ * for a stage whose config entry was never shipped); the reference index
+ * itself is built from string-literal matching, which is agnostic to how the
+ * key reaches the resolver (direct call, a `{ idea: 'pipeline-idea-expansion' }`
+ * lookup table, a `const STAGE = '…'` module constant, …).
+ */
+const LITERAL_CALL_RE =
+ /\b(?:getStage|getStageTemplate|buildPrompt|runStage|runStagedLLM|previewPrompt|resolveStageContext|resolveJudgeForStage)\(\s*(['"])([^'"\n]+)\1/g;
+
+/**
+ * Every quoted string literal in a JS source. Stage keys are plain
+ * `[a-z0-9-]` words, so a literal containing an escape, a newline, or a `${`
+ * interpolation is never one — excluding those keeps the match cheap and
+ * avoids mis-parsing multi-line template bodies.
+ */
+const STRING_LITERAL_RE = /'([^'\\\n]*)'|"([^"\\\n]*)"|`([^`\\\n$]*)`/g;
+
+/**
+ * A template literal with a static hyphenated prefix followed by an
+ * interpolation — `` `pipeline-panel-${personaId}` ``. Stages reached this way
+ * (the reader-panel personas) have NO literal key anywhere in source, so a
+ * literal-only scan would leave them unprotected. Every known key under the
+ * prefix counts as referenced by that file.
+ *
+ * This deliberately over-matches: a `source: `writers-room-${kind}`` telemetry
+ * tag counts too. Over-protection is the safe failure mode here — the cost is
+ * an extra path in the delete-confirm dialog, versus a silently deletable
+ * stage that breaks a feature.
+ */
+const TEMPLATE_PREFIX_RE = /`([A-Za-z][A-Za-z0-9]*(?:-[A-Za-z0-9]+)+-)\$\{/g;
+
+/**
+ * Files excluded from the scan. `promptSystemStages.js` is the curated
+ * registry (plus prose naming example stages) — listing itself as a "call
+ * site" for the ten curated keys is noise, not a reference.
+ */
+const EXCLUDED_SOURCES = new Set(['server/lib/promptSystemStages.js']);
+
+/** Stage keys PortOS ships, from the reference stage config. */
+export function readShippedStageKeys(repoRoot = REPO_ROOT) {
+ const configPath = join(repoRoot, 'data.reference', 'prompts', 'stage-config.json');
+ const config = JSON.parse(readFileSync(configPath, 'utf8'));
+ return Object.keys(config.stages || {});
+}
+
+/**
+ * Git-tracked, non-test `.js` sources under `server/`, read into memory.
+ *
+ * Scoped to `git ls-files` rather than a filesystem walk on purpose: a raw
+ * walk picks up `node_modules`, build output, and CoS-agent worktrees under
+ * `data/`, which would make the manifest non-deterministic across installs.
+ */
+export function collectServerSources(repoRoot = REPO_ROOT) {
+ const tracked = execFileSync('git', ['ls-files', '--', 'server'], {
+ cwd: repoRoot,
+ encoding: 'utf8',
+ maxBuffer: 32 * 1024 * 1024,
+ })
+ .split('\n')
+ .filter((p) => p.endsWith('.js') && !p.endsWith('.test.js') && !EXCLUDED_SOURCES.has(p));
+
+ return tracked.map((path) => ({ path, source: readFileSync(join(repoRoot, path), 'utf8') }));
+}
+
+/**
+ * Build the `stageKey -> [source paths]` index.
+ *
+ * @param {object} args
+ * @param {string[]} args.shippedStageKeys keys from the reference stage config
+ * @param {{path: string, source: string}[]} args.sources server sources to scan
+ * @returns {Record<string, string[]>} sorted keys, sorted paths, keys with zero
+ * references omitted
+ */
+export function buildStageCallSites({ shippedStageKeys, sources }) {
+ // A call site may name a stage whose config entry was never shipped; those
+ // keys still deserve protection if the user (or a migration) creates them.
+ const keys = new Set(shippedStageKeys);
+ for (const { source } of sources) {
+ for (const [, , key] of source.matchAll(LITERAL_CALL_RE)) keys.add(key);
+ }
+
+ const index = new Map();
+ const record = (key, path) => {
+ if (!index.has(key)) index.set(key, new Set());
+ index.get(key).add(path);
+ };
+
+ for (const { path, source } of sources) {
+ for (const match of source.matchAll(STRING_LITERAL_RE)) {
+ const literal = match[1] ?? match[2] ?? match[3];
+ if (keys.has(literal)) record(literal, path);
+ }
+ for (const [, prefix] of source.matchAll(TEMPLATE_PREFIX_RE)) {
+ for (const key of keys) {
+ if (key.length > prefix.length && key.startsWith(prefix)) record(key, path);
+ }
+ }
+ }
+
+ return Object.fromEntries(
+ [...index.keys()].sort().map((key) => [key, [...index.get(key)].sort()]),
+ );
+}
+
+/** Full generation pass against a checkout. */
+export function generateStageCallSites(repoRoot = REPO_ROOT) {
+ return buildStageCallSites({
+ shippedStageKeys: readShippedStageKeys(repoRoot),
+ sources: collectServerSources(repoRoot),
+ });
+}
+
+/** The manifest as currently checked in. */
+export function readStageCallSitesManifest(repoRoot = REPO_ROOT) {
+ return JSON.parse(readFileSync(join(repoRoot, MANIFEST_RELATIVE_PATH), 'utf8'));
+}
+
+/** Serialized form — one place so the writer and the drift test agree. */
+export const serializeManifest = (manifest) => `${JSON.stringify(manifest, null, 2)}\n`;
+
+function main() {
+ const manifest = generateStageCallSites();
+ writeFileSync(join(REPO_ROOT, MANIFEST_RELATIVE_PATH), serializeManifest(manifest), 'utf8');
+ const paths = new Set(Object.values(manifest).flat());
+ console.log(`📜 Wrote ${MANIFEST_RELATIVE_PATH}: ${Object.keys(manifest).length} stages across ${paths.size} files`);
+}
+
+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main();
diff --git a/scripts/generate-prompt-stage-call-sites.test.js b/scripts/generate-prompt-stage-call-sites.test.js
new file mode 100644
index 0000000000..6282cbd980
--- /dev/null
+++ b/scripts/generate-prompt-stage-call-sites.test.js
@@ -0,0 +1,160 @@
+import { describe, it, expect } from 'vitest';
+
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+
+import {
+ MANIFEST_RELATIVE_PATH,
+ REGENERATE_COMMAND,
+ REPO_ROOT,
+ buildStageCallSites,
+ generateStageCallSites,
+ readShippedStageKeys,
+ readStageCallSitesManifest,
+ serializeManifest,
+} from './generate-prompt-stage-call-sites.js';
+
+// Fixture sources exercise the scanner's contract without depending on the
+// real tree, so a legitimate refactor of `server/` can't turn these into
+// false failures.
+const src = (path, source) => ({ path, source });
+
+describe('prompt stage call-site scanner', () => {
+ const shippedStageKeys = ['demo-alpha', 'demo-beta', 'demo-panel-one', 'demo-panel-two', 'demo-unused'];
+
+ it('catches each direct call shape', () => {
+ const index = buildStageCallSites({
+ shippedStageKeys,
+ sources: [
+ src('server/services/a.js', "await getStage('demo-alpha');"),
+ src('server/services/b.js', 'await buildPrompt("demo-beta", {});'),
+ src('server/services/c.js', "await runStage('demo-alpha', {});"),
+ src('server/services/d.js', "await runStagedLLM('demo-beta', {});"),
+ ],
+ });
+
+ expect(index['demo-alpha']).toEqual(['server/services/a.js', 'server/services/c.js']);
+ expect(index['demo-beta']).toEqual(['server/services/b.js', 'server/services/d.js']);
+ });
+
+ it('catches keys reached indirectly through a lookup table or module constant', () => {
+ // The shapes a call-shape-only regex would miss: textStages.js's
+ // `{ idea: 'pipeline-idea-expansion' }` map and liveDirector.js's
+ // `const STAGE = 'writers-room-continue'`.
+ const index = buildStageCallSites({
+ shippedStageKeys,
+ sources: [
+ src('server/services/map.js', "const STAGES = { first: 'demo-alpha' };\nrunStage(STAGES[kind]);"),
+ src('server/services/const.js', "const STAGE = 'demo-beta';\nawait buildPrompt(STAGE, {});"),
+ ],
+ });
+
+ expect(index['demo-alpha']).toEqual(['server/services/map.js']);
+ expect(index['demo-beta']).toEqual(['server/services/const.js']);
+ });
+
+ it('catches stages reached only through an interpolated prefix', () => {
+ // `pipeline-panel-${personaId}` in readerPanel.js — no literal key exists
+ // anywhere, so a literal-only scan would leave these deletable.
+ const index = buildStageCallSites({
+ shippedStageKeys,
+ sources: [src('server/services/panel.js', 'const stage = (id) => `demo-panel-${id}`;')],
+ });
+
+ expect(index['demo-panel-one']).toEqual(['server/services/panel.js']);
+ expect(index['demo-panel-two']).toEqual(['server/services/panel.js']);
+ // The prefix itself is not a key, and unrelated stages stay untouched.
+ expect(index['demo-panel-']).toBeUndefined();
+ expect(index['demo-alpha']).toBeUndefined();
+ });
+
+ it('does not match a longer key that merely starts with a shorter one', () => {
+ const index = buildStageCallSites({
+ shippedStageKeys: ['demo-alpha', 'demo-alpha-extended'],
+ sources: [src('server/services/a.js', "getStage('demo-alpha-extended');")],
+ });
+
+ expect(index['demo-alpha']).toBeUndefined();
+ expect(index['demo-alpha-extended']).toEqual(['server/services/a.js']);
+ });
+
+ it('records a call site for a key the shipped stage config never listed', () => {
+ const index = buildStageCallSites({
+ shippedStageKeys,
+ sources: [src('server/services/a.js', "getStage('demo-unshipped');")],
+ });
+
+ expect(index['demo-unshipped']).toEqual(['server/services/a.js']);
+ });
+
+ it('omits keys nothing references and dedupes repeated references', () => {
+ const index = buildStageCallSites({
+ shippedStageKeys,
+ sources: [src('server/services/a.js', "getStage('demo-alpha');\nbuildPrompt('demo-alpha', {});")],
+ });
+
+ expect(index['demo-unused']).toBeUndefined();
+ expect(index['demo-alpha']).toEqual(['server/services/a.js']);
+ });
+
+ it('sorts keys and paths so the manifest is byte-stable', () => {
+ const index = buildStageCallSites({
+ shippedStageKeys,
+ sources: [
+ src('server/services/z.js', "getStage('demo-beta');\ngetStage('demo-alpha');"),
+ src('server/services/a.js', "getStage('demo-beta');"),
+ ],
+ });
+
+ expect(Object.keys(index)).toEqual(['demo-alpha', 'demo-beta']);
+ expect(index['demo-beta']).toEqual(['server/services/a.js', 'server/services/z.js']);
+ });
+});
+
+// The guard the whole generated-manifest posture exists for: adding a
+// literal-key call site (or renaming a file that has one) without rerunning
+// the generator leaves stages unprotected, and this fails until it's rerun.
+describe('prompt stage call-site manifest', () => {
+ it('matches a fresh scan of the tracked server sources', () => {
+ const stale = `${MANIFEST_RELATIVE_PATH} is stale — run \`${REGENERATE_COMMAND}\` and commit the result.`;
+ const fresh = generateStageCallSites();
+
+ // Structural first, so a genuine drift reports as a readable key diff…
+ expect(fresh, stale).toEqual(readStageCallSitesManifest());
+ // …then byte-exact, so a hand-edit that reformats the file is caught too.
+ expect(readFileSync(join(REPO_ROOT, MANIFEST_RELATIVE_PATH), 'utf8'), stale)
+ .toBe(serializeManifest(fresh));
+ });
+
+ it('covers the shipped stages that features resolve by name', () => {
+ const manifest = readStageCallSitesManifest();
+ // A sample from the four call paths #3335 named — a scanner regression
+ // that silently stopped matching one of them would still pass the drift
+ // test above (both sides regenerate), so pin the expectation here.
+ for (const key of [
+ 'pipeline-series-concept-judge',
+ 'pipeline-canon-describe-from-prose',
+ 'catalog-ideas-scenes-concepts',
+ 'soul-contradiction-detector',
+ 'pipeline-panel-editor',
+ ]) {
+ expect(manifest[key], `${key} lost its call-site entry`).toBeTruthy();
+ expect(manifest[key].length).toBeGreaterThan(0);
+ }
+
+ // Most of the shipped catalog is reachable by name; a large drop means the
+ // scan broke rather than that the code genuinely stopped calling stages.
+ const shipped = readShippedStageKeys();
+ const referenced = shipped.filter((key) => manifest[key]);
+ expect(referenced.length).toBeGreaterThan(shipped.length * 0.75);
+ });
+
+ it('lists only tracked, repo-relative server paths', () => {
+ for (const [key, paths] of Object.entries(readStageCallSitesManifest())) {
+ for (const path of paths) {
+ expect(path, `${key} -> ${path}`).toMatch(/^server\/[\w./-]+\.js$/);
+ expect(path.endsWith('.test.js')).toBe(false);
+ }
+ }
+ });
+});
diff --git a/server/lib/README.md b/server/lib/README.md
index 2fc9128eb6..b364fa9b08 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -97,7 +97,8 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `tuiHandshake.js` | Shared TUI invocation + paste-handshake constants. |
| `tuiUsageScrape.js` | `scrapeTuiUsage({ command, slashCommand, … })` + `USAGE_SANDBOX_DIR` — drive an agy/grok TUI in a sandbox PTY, send a slash command, return the ANSI-stripped screen (for quota panels `--print` can't reach). |
| `stageRunner.js` | Shared staged-LLM runner. |
-| `promptSystemStages.js` | Single source of truth for the prompt stages PortOS features resolve by literal key — `SYSTEM_STAGE_USAGE` (`key -> usedBy[]` feature-name copy), the derived `SYSTEM_STAGE_KEYS`, `isSystemStage(key)`, `systemStageUsedBy(key)`. Read by `GET /api/prompts` (ships the key list to the client), `GET /api/prompts/:stage/usage`, and the `DELETE /api/prompts/:stage` force-guard. The CURATED protected set (CoS / Brain / Memory / app-detection), not an index of every literal-key call site — adding a row means "protect this stage from deletion and badge it SYSTEM". |
+| `promptSystemStages.js` | Prompt-stage protection, split in two (#3335). CURATED (badging): `SYSTEM_STAGE_USAGE` (`key -> usedBy[]` feature-name copy), `SYSTEM_STAGE_KEYS`, `isSystemStage(key)`, `systemStageUsedBy(key)` — what `GET /api/prompts` ships and the Prompt Manager badges/filters; adding a row is a per-stage product decision. DERIVED (deletion): `STAGE_CALL_SITES` / `stageReferencedBy(key)` from the generated manifest, unioned with the curated set into `isProtectedStage(key)` / `PROTECTED_STAGE_KEYS` — what the `DELETE /api/prompts/:stage` force-guard and `canDelete` consult. |
+| `promptStageCallSites.generated.json` | Generated `stageKey -> [server source paths]` index of every prompt stage `server/` names by literal key (plus interpolated-prefix stages like `pipeline-panel-${id}`). Regenerate with `node scripts/generate-prompt-stage-call-sites.js`; `scripts/generate-prompt-stage-call-sites.test.js` fails on drift. Never hand-edit. |
| `promptTemplate.js` | Mustache-flavored, dot-notation-aware prompt template engine. |
| `promptPartials.js` | Mustache-style partial expansion. |
| `mediaModels.js` | Single source of truth for image/video model metadata. |
diff --git a/server/lib/promptStageCallSites.generated.json b/server/lib/promptStageCallSites.generated.json
new file mode 100644
index 0000000000..747e82425d
--- /dev/null
+++ b/server/lib/promptStageCallSites.generated.json
@@ -0,0 +1,405 @@
+{
+ "adversarial-boundary-scorer": [
+ "server/services/digital-twin-adversarial-testing.js"
+ ],
+ "brain-classifier": [
+ "server/services/brain.js"
+ ],
+ "brain-daily-digest": [
+ "server/services/brain.js"
+ ],
+ "brain-weekly-review": [
+ "server/services/brain.js"
+ ],
+ "catalog-ideas-scenes-concepts": [
+ "server/services/catalogExtraction.js"
+ ],
+ "cd-evaluate": [
+ "server/lib/creativeDirectorPrompts.js"
+ ],
+ "cd-plan": [
+ "server/lib/creativeDirectorPrompts.js",
+ "server/lib/creativeDirectorValidation.js",
+ "server/lib/schemaVersions.js"
+ ],
+ "cd-treatment": [
+ "server/lib/creativeDirectorPrompts.js"
+ ],
+ "cos-agent-briefing": [
+ "server/services/agentPromptBuilder.js"
+ ],
+ "cos-task-enhance": [
+ "server/services/taskEnhancer.js"
+ ],
+ "importer-arc-extract": [
+ "server/services/importer.js",
+ "server/services/pipeline/arcPlanner/manuscriptDerive.js"
+ ],
+ "importer-canon-extract": [
+ "server/services/importer.js"
+ ],
+ "importer-classify": [
+ "server/services/importer.js"
+ ],
+ "importer-issue-proposal": [
+ "server/services/importer.js"
+ ],
+ "manuscript-reformat": [
+ "server/services/pipeline/manuscriptFix.js"
+ ],
+ "memory-evaluate": [
+ "server/services/memoryClassifier.js"
+ ],
+ "model-personality-alignment-scorer": [
+ "server/services/modelPersonality.js"
+ ],
+ "model-personality-profile": [
+ "server/services/modelPersonality.js"
+ ],
+ "multi-turn-consistency-scorer": [
+ "server/services/digital-twin-multi-turn-testing.js"
+ ],
+ "pipeline-arc-overview": [
+ "server/services/pipeline/arcPlanner/arcCore.js",
+ "server/services/pipeline/foundationJudge.js",
+ "server/services/pipeline/seriesReview.js"
+ ],
+ "pipeline-arc-resolve": [
+ "server/services/pipeline/arcPlanner/arcCore.js"
+ ],
+ "pipeline-arc-verify": [
+ "server/services/pipeline/arcPlanner/arcCore.js"
+ ],
+ "pipeline-audio-cues": [
+ "server/services/pipeline/audioCues.js"
+ ],
+ "pipeline-beat-continuity": [
+ "server/services/pipeline/arcPlanner/beatContinuity.js"
+ ],
+ "pipeline-beat-continuity-resolve": [
+ "server/services/pipeline/arcPlanner/beatContinuity.js"
+ ],
+ "pipeline-canon-describe-from-prose": [
+ "server/services/universeCanon.js"
+ ],
+ "pipeline-character-differentiate-cast": [
+ "server/services/universeCanon.js"
+ ],
+ "pipeline-comic-cover-concepts": [
+ "server/services/pipeline/arcPlanner/coverConcepts.js"
+ ],
+ "pipeline-comic-page-refine-render": [
+ "server/services/pipeline/comicPages.js"
+ ],
+ "pipeline-comic-panel-image-prompt": [
+ "server/services/pipeline/comicPages.js"
+ ],
+ "pipeline-comic-script": [
+ "server/services/pipeline/pipelineJudge.js",
+ "server/services/pipeline/textStages.js"
+ ],
+ "pipeline-continuity-bible": [
+ "server/services/pipeline/continuityBible.js"
+ ],
+ "pipeline-editorial-adversarial-cuts": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-analysis": [
+ "server/services/pipeline/editorialAnalysis.js"
+ ],
+ "pipeline-editorial-appearance-continuity": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-arc-regression": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-arc-transitions": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-character-consistency": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-chekhov": [
+ "server/lib/editorial/checkInfra/revealForeshadowing.js"
+ ],
+ "pipeline-editorial-climax-agency": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-comic-page-turn": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-comic-prose-sync": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-dead-metaphor": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-dialogue-pleasantries": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-endings-cliffhanger": [
+ "server/lib/editorial/checkInfra/revealForeshadowing.js"
+ ],
+ "pipeline-editorial-eyeline-match": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-fact-accuracy": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-head-hopping": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-info-dumping": [
+ "server/lib/editorial/checkInfra/revealForeshadowing.js"
+ ],
+ "pipeline-editorial-interiority": [
+ "server/lib/editorial/checkInfra/revealForeshadowing.js"
+ ],
+ "pipeline-editorial-interiority-balance": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-kill-your-darlings": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-mirror-description": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-object-backstory": [
+ "server/lib/editorial/checkInfra/revealForeshadowing.js"
+ ],
+ "pipeline-editorial-object-motivation": [
+ "server/lib/editorial/checkInfra/revealForeshadowing.js"
+ ],
+ "pipeline-editorial-object-weight-proportionality": [
+ "server/lib/editorial/checkInfra/revealForeshadowing.js"
+ ],
+ "pipeline-editorial-on-the-nose": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-opening-start": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-pacing-escalation-curve": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-plot-structure": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-premature-reveal": [
+ "server/lib/editorial/checkInfra/revealForeshadowing.js"
+ ],
+ "pipeline-editorial-reaction-proportionality": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-secondary-arc": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-sensory-balance": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-style-conformance": [
+ "server/lib/editorial/checkInfra/revealForeshadowing.js"
+ ],
+ "pipeline-editorial-telling-emotion": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-theme-coherence": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-timeline-contradiction": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-unmodeled-names": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-voice-consistency": [
+ "server/lib/editorial/checkInfra/voiceCanon.js"
+ ],
+ "pipeline-editorial-voice-distinctiveness": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-white-room": [
+ "server/lib/editorial/checkInfra/craftStages.js"
+ ],
+ "pipeline-editorial-world-cost-free-power": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-editorial-world-unforeshadowed-solution": [
+ "server/lib/editorial/checkInfra/structureStages.js"
+ ],
+ "pipeline-extract-scenes": [
+ "server/lib/sceneExtractor.js",
+ "server/routes/pipeline/issues.js",
+ "server/services/importer.js"
+ ],
+ "pipeline-idea-expansion": [
+ "server/services/pipeline/textStages.js"
+ ],
+ "pipeline-judge-compare": [
+ "server/services/pipeline/editorial/comparativeRank.js"
+ ],
+ "pipeline-judge-foundation": [
+ "server/services/pipeline/foundationJudge.js"
+ ],
+ "pipeline-judge-issue": [
+ "server/services/pipeline/pipelineJudge.js"
+ ],
+ "pipeline-manuscript-completeness": [
+ "server/lib/promptRunner.js",
+ "server/services/pipeline/arcPlanner/completenessPass.js"
+ ],
+ "pipeline-manuscript-fix": [
+ "server/services/pipeline/manuscriptFix.js"
+ ],
+ "pipeline-panel-editor": [
+ "server/services/pipeline/readerPanel.js"
+ ],
+ "pipeline-panel-first-reader": [
+ "server/services/pipeline/readerPanel.js"
+ ],
+ "pipeline-panel-genre-reader": [
+ "server/services/pipeline/readerPanel.js"
+ ],
+ "pipeline-panel-writer": [
+ "server/services/pipeline/readerPanel.js"
+ ],
+ "pipeline-pov-analysis": [
+ "server/services/pipeline/perspectiveRewrite.js"
+ ],
+ "pipeline-pov-rewrite": [
+ "server/services/pipeline/perspectiveRewrite.js"
+ ],
+ "pipeline-prose": [
+ "server/services/pipeline/pipelineJudge.js",
+ "server/services/pipeline/textStages.js"
+ ],
+ "pipeline-reverse-outline": [
+ "server/services/pipeline/reverseOutline.js"
+ ],
+ "pipeline-script-verify": [
+ "server/services/pipeline/scriptVerify.js",
+ "server/services/pipeline/seriesAutopilot.js"
+ ],
+ "pipeline-season-episodes": [
+ "server/services/pipeline/arcPlanner/episodeSeedPass.js"
+ ],
+ "pipeline-series-concept-judge": [
+ "server/services/pipeline/seriesGenerate.js"
+ ],
+ "pipeline-series-generate": [
+ "server/services/pipeline/seriesGenerate.js"
+ ],
+ "pipeline-series-title-logo": [
+ "server/routes/pipeline/series.js",
+ "server/services/pipeline/seriesTitleLogo.js"
+ ],
+ "pipeline-series-voice-discover": [
+ "server/services/pipeline/seriesVoiceDiscover.js"
+ ],
+ "pipeline-storyboard-image-prompt": [
+ "server/services/pipeline/storyboards.js"
+ ],
+ "pipeline-teleplay": [
+ "server/services/pipeline/pipelineJudge.js",
+ "server/services/pipeline/textStages.js"
+ ],
+ "pipeline-volume-cover-concepts": [
+ "server/services/pipeline/arcPlanner/coverConcepts.js"
+ ],
+ "pipeline-volume-verify": [
+ "server/services/pipeline/arcPlanner/arcCore.js"
+ ],
+ "soul-contradiction-detector": [
+ "server/services/digital-twin-analysis.js"
+ ],
+ "soul-enrichment": [
+ "server/services/digital-twin-enrichment.js"
+ ],
+ "soul-enrichment-process": [
+ "server/services/digital-twin-enrichment.js"
+ ],
+ "soul-test-generator": [
+ "server/services/digital-twin-analysis.js"
+ ],
+ "soul-test-scorer": [
+ "server/services/digital-twin-testing.js"
+ ],
+ "soul-writing-analyzer": [
+ "server/services/digital-twin-analysis.js"
+ ],
+ "story-builder-arc-refine": [
+ "server/services/pipeline/arcPlanner/arcCore.js"
+ ],
+ "story-builder-idea-expand": [
+ "server/services/storyBuilder.js"
+ ],
+ "story-builder-reader-map": [
+ "server/services/pipeline/arcPlanner/arcCore.js"
+ ],
+ "story-builder-reader-map-refine": [
+ "server/services/pipeline/arcPlanner/arcCore.js"
+ ],
+ "twin-confidence-analyzer": [
+ "server/services/digital-twin-analysis.js"
+ ],
+ "twin-image-identity-analyze": [
+ "server/services/digital-twin-image-identity.js"
+ ],
+ "twin-import-analyzer": [
+ "server/services/digital-twin-import.js"
+ ],
+ "twin-interview-analyze": [
+ "server/services/digital-twin-import.js"
+ ],
+ "twin-spoken-written-compare": [
+ "server/services/digital-twin-style-comparison.js"
+ ],
+ "twin-trait-extractor": [
+ "server/services/digital-twin-analysis.js"
+ ],
+ "universe-character-expand": [
+ "server/services/universeCharacterExpand.js"
+ ],
+ "values-alignment-scorer": [
+ "server/services/digital-twin-values-testing.js"
+ ],
+ "writers-room-cd-bridge": [
+ "server/services/creativeDirector/bridgeFromIssue.js",
+ "server/services/writersRoom/evaluator.js",
+ "server/services/writersRoom/liveDirector.js"
+ ],
+ "writers-room-characters": [
+ "server/lib/bibleExtractor.js",
+ "server/services/writersRoom/evaluator.js"
+ ],
+ "writers-room-continue": [
+ "server/services/writersRoom/evaluator.js",
+ "server/services/writersRoom/liveDirector.js"
+ ],
+ "writers-room-cuts": [
+ "server/services/writersRoom/evaluator.js"
+ ],
+ "writers-room-evaluate": [
+ "server/lib/stageRunner.js",
+ "server/services/writersRoom/evaluator.js"
+ ],
+ "writers-room-format": [
+ "server/services/writersRoom/evaluator.js"
+ ],
+ "writers-room-objects": [
+ "server/lib/bibleExtractor.js",
+ "server/services/writersRoom/evaluator.js"
+ ],
+ "writers-room-places": [
+ "server/lib/bibleExtractor.js",
+ "server/services/writersRoom/evaluator.js"
+ ],
+ "writers-room-revise": [
+ "server/services/writersRoom/evaluator.js"
+ ],
+ "writers-room-script": [
+ "server/lib/sceneExtractor.js",
+ "server/routes/pipeline/issues.js",
+ "server/services/writersRoom/evaluator.js"
+ ]
+}
diff --git a/server/lib/promptSystemStages.js b/server/lib/promptSystemStages.js
index f7076fb9b5..20c5931dbb 100644
--- a/server/lib/promptSystemStages.js
+++ b/server/lib/promptSystemStages.js
@@ -8,14 +8,19 @@
* `DELETE /api/prompts/:stage` refuses without `?force=true`, and the Prompt
* Manager badges + filters them.
*
- * SCOPE: this is the CURATED protected set — the CoS / Brain / Memory /
- * app-detection stages the delete guard has always covered — not an exhaustive
- * index of every literal-key call site. Plenty of shipped stages are resolved
- * by literal key too (`pipeline-series-concept-judge`, `catalog-ideas-scenes-concepts`,
- * …) and are deliberately NOT here: force-guarding and badging ~100 pipeline
- * stages is a product decision, not a refactor, and is tracked separately.
- * Adding a row here means "this stage is now protected from deletion and
- * badged SYSTEM", which is a deliberate choice per stage.
+ * SCOPE: this is the CURATED set — the CoS / Brain / Memory / app-detection
+ * stages the delete guard has always covered — and it is what the UI badges
+ * and filters. It is NOT an exhaustive index of every literal-key call site:
+ * roughly 100 of the 127 shipped stages are resolved by literal key too, and
+ * badging all of them would make the SYSTEM badge and the "System only" filter
+ * meaningless (#3335). Adding a row here means "this stage is now badged
+ * SYSTEM", which is a deliberate choice per stage.
+ *
+ * Deletion protection is the OTHER half, and it is deliberately wider: the
+ * generated `promptStageCallSites.generated.json` indexes every stage key a
+ * `server/` source references, and `isProtectedStage()` unions it with this
+ * table. So `pipeline-series-concept-judge` is undeletable without `?force=true`
+ * while staying out of the badge. See `scripts/generate-prompt-stage-call-sites.js`.
*
* The map was previously restated three times — the usage handler's
* `key -> usedBy[]` table, the DELETE guard's bare key array, and a client-side
@@ -26,10 +31,12 @@
* server would refuse to delete it. `GET /api/prompts` now ships the key list
* so the client has nothing left to guess.
*
- * Pure data + predicates — no I/O, no toolkit dependency. Adding a feature that
- * resolves a stage by literal key means adding a row here.
+ * Data + predicates, no toolkit dependency. The only read is the generated
+ * call-site manifest, loaded once at module init.
*/
+import { readFileSync } from 'node:fs';
+
/**
* `stageKey -> human-readable feature names that call it`. The values are what
* `GET /api/prompts/:stage/usage` surfaces as `usedBy` in the delete-confirm
@@ -69,3 +76,50 @@ export function isSystemStage(key) {
export function systemStageUsedBy(key) {
return isSystemStage(key) ? SYSTEM_STAGE_USAGE[key] : [];
}
+
+/**
+ * `stageKey -> repo-relative source paths that reference it`, generated by
+ * `scripts/generate-prompt-stage-call-sites.js` and drift-guarded by its test.
+ * Read here rather than `import … with { type: 'json' }` so the module loads
+ * identically under node, vitest, and any bundler in the chain.
+ */
+export const STAGE_CALL_SITES = Object.freeze(
+ Object.fromEntries(
+ Object.entries(
+ JSON.parse(readFileSync(new URL('./promptStageCallSites.generated.json', import.meta.url), 'utf8')),
+ ).map(([key, paths]) => [key, Object.freeze(paths)]),
+ ),
+);
+
+const CALL_SITE_KEYS = new Set(Object.keys(STAGE_CALL_SITES));
+
+const EMPTY = Object.freeze([]);
+
+/**
+ * The `server/` source files that name `key` as a string literal, or an empty
+ * array when nothing does. Surfaced by `GET /api/prompts/:stage/usage` so the
+ * delete-confirm dialog can name what breaks.
+ *
+ * Gated on the Set for the same reason `systemStageUsedBy` is — `toString`
+ * must not resolve through `Object.prototype`.
+ */
+export function stageReferencedBy(key) {
+ return CALL_SITE_KEYS.has(key) ? STAGE_CALL_SITES[key] : EMPTY;
+}
+
+/**
+ * True when deleting `key` would break something: it is either a curated
+ * system stage or referenced by literal key somewhere in `server/`.
+ *
+ * This — not `isSystemStage` — is what the DELETE guard consults. The two are
+ * separate on purpose: `isSystemStage` drives user-facing badging and stays
+ * small; this one drives safety and covers every call site (#3335).
+ */
+export function isProtectedStage(key) {
+ return isSystemStage(key) || CALL_SITE_KEYS.has(key);
+}
+
+/** Every key the delete guard protects — the curated set unioned with the derived one. */
+export const PROTECTED_STAGE_KEYS = Object.freeze(
+ [...new Set([...SYSTEM_STAGE_KEYS, ...CALL_SITE_KEYS])].sort(),
+);
diff --git a/server/lib/promptSystemStages.test.js b/server/lib/promptSystemStages.test.js
index fc44d0d9db..60b5f85382 100644
--- a/server/lib/promptSystemStages.test.js
+++ b/server/lib/promptSystemStages.test.js
@@ -4,9 +4,13 @@ import { dirname, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import {
+ PROTECTED_STAGE_KEYS,
+ STAGE_CALL_SITES,
SYSTEM_STAGE_USAGE,
SYSTEM_STAGE_KEYS,
+ isProtectedStage,
isSystemStage,
+ stageReferencedBy,
systemStageUsedBy,
} from './promptSystemStages.js';
@@ -61,3 +65,51 @@ describe('shipped stage catalog parity', () => {
expect(missing).toEqual([]);
});
});
+
+// #3335 split deletion protection from the SYSTEM badge. The two sets must
+// stay distinguishable: widening protection is safe, widening the badge is a
+// product regression (it would badge ~100 of 127 rows and make the
+// "System only" filter useless).
+describe('derived call-site protection', () => {
+ const REFERENCED_NOT_CURATED = 'pipeline-series-concept-judge';
+
+ it('keeps the curated badge set to the ten hand-picked stages', () => {
+ expect(SYSTEM_STAGE_KEYS).toHaveLength(10);
+ expect(isSystemStage(REFERENCED_NOT_CURATED)).toBe(false);
+ expect(systemStageUsedBy(REFERENCED_NOT_CURATED)).toEqual([]);
+ });
+
+ it('protects a referenced stage the curated set never mentions', () => {
+ expect(stageReferencedBy(REFERENCED_NOT_CURATED).length).toBeGreaterThan(0);
+ expect(isProtectedStage(REFERENCED_NOT_CURATED)).toBe(true);
+ });
+
+ it('protects every curated stage even when no source references it by name', () => {
+ // Four curated keys (`cos-evaluate`, `app-detection`, …) have no literal
+ // call site in `server/` today; the union is what keeps them guarded.
+ for (const key of SYSTEM_STAGE_KEYS) expect(isProtectedStage(key)).toBe(true);
+ });
+
+ it('leaves user-authored stages deletable', () => {
+ expect(isProtectedStage('my-own-stage')).toBe(false);
+ expect(stageReferencedBy('my-own-stage')).toEqual([]);
+ expect(isProtectedStage(undefined)).toBe(false);
+ expect(isProtectedStage('')).toBe(false);
+ // Prototype keys must not resolve through Object.prototype here either.
+ expect(isProtectedStage('toString')).toBe(false);
+ expect(stageReferencedBy('constructor')).toEqual([]);
+ });
+
+ it('unions the curated and derived sets into PROTECTED_STAGE_KEYS', () => {
+ const expected = [...new Set([...SYSTEM_STAGE_KEYS, ...Object.keys(STAGE_CALL_SITES)])].sort();
+ expect(PROTECTED_STAGE_KEYS).toEqual(expected);
+ expect(PROTECTED_STAGE_KEYS.length).toBeGreaterThan(SYSTEM_STAGE_KEYS.length);
+ for (const key of PROTECTED_STAGE_KEYS) expect(isProtectedStage(key)).toBe(true);
+ });
+
+ it('reports call sites as repo-relative server paths', () => {
+ for (const path of stageReferencedBy(REFERENCED_NOT_CURATED)) {
+ expect(path).toMatch(/^server\//);
+ }
+ });
+});
diff --git a/server/routes/prompts.js b/server/routes/prompts.js
index 9312e280e1..89304699dc 100644
--- a/server/routes/prompts.js
+++ b/server/routes/prompts.js
@@ -1,7 +1,13 @@
import { Router } from 'express';
import { asyncHandler, ServerError } from '../lib/errorHandler.js';
import { stageConfigUpdateSchema, validateRequest } from '../lib/validation.js';
-import { SYSTEM_STAGE_KEYS, isSystemStage, systemStageUsedBy } from '../lib/promptSystemStages.js';
+import {
+ SYSTEM_STAGE_KEYS,
+ isProtectedStage,
+ isSystemStage,
+ stageReferencedBy,
+ systemStageUsedBy
+} from '../lib/promptSystemStages.js';
import {
listJobSkillTemplates,
loadJobSkillTemplate,
@@ -162,16 +168,28 @@ export function createPortOSPromptsRoutes(aiToolkit) {
res.json({ success: true });
}));
- // GET /api/prompts/:stage/usage - Check if stage is in use
+ // GET /api/prompts/:stage/usage - Check if stage is in use.
+ //
+ // `isSystemStage` stays the CURATED answer so the UI's SYSTEM copy/badge
+ // stays accurate, while `canDelete` reflects the WIDER protected set — a
+ // pipeline stage nothing badges is still undeletable because source names it
+ // (#3335). `referencedBy` is what the delete-confirm dialog lists.
router.get('/:stage/usage', asyncHandler(async (req, res) => {
const stageName = req.params.stage;
const isSystem = isSystemStage(stageName);
+ const referencedBy = stageReferencedBy(stageName);
+ const isProtected = isProtectedStage(stageName);
res.json({
isSystemStage: isSystem,
usedBy: systemStageUsedBy(stageName),
- canDelete: !isSystem,
- warning: isSystem ? 'This is a system stage used by PortOS features. Deleting it may break functionality.' : null
+ referencedBy,
+ canDelete: !isProtected,
+ warning: isProtected
+ ? (isSystem
+ ? 'This is a system stage used by PortOS features. Deleting it may break functionality.'
+ : `PortOS resolves this stage by name in ${referencedBy.length} source file${referencedBy.length === 1 ? '' : 's'}. Deleting it will break the feature that calls it.`)
+ : null
});
}));
@@ -179,9 +197,9 @@ export function createPortOSPromptsRoutes(aiToolkit) {
router.delete('/:stage', asyncHandler(async (req, res) => {
const stageName = req.params.stage;
- if (isSystemStage(stageName) && req.query.force !== 'true') {
+ if (isProtectedStage(stageName) && req.query.force !== 'true') {
throw new ServerError(
- 'Cannot delete system stage. This stage is used by PortOS features. Add ?force=true to delete anyway.',
+ 'Cannot delete protected stage. PortOS resolves this stage by name. Add ?force=true to delete anyway.',
{ status: 400, code: 'SYSTEM_STAGE_PROTECTED' }
);
}
diff --git a/server/routes/prompts.test.js b/server/routes/prompts.test.js
index e6665717f5..9cc30abe31 100644
--- a/server/routes/prompts.test.js
+++ b/server/routes/prompts.test.js
@@ -15,7 +15,11 @@ vi.mock('../services/autonomousJobs.js', () => ({
import { errorMiddleware } from '../lib/errorHandler.js';
import { createPortOSPromptsRoutes } from './prompts.js';
-import { SYSTEM_STAGE_KEYS } from '../lib/promptSystemStages.js';
+import { PROTECTED_STAGE_KEYS, SYSTEM_STAGE_KEYS, stageReferencedBy } from '../lib/promptSystemStages.js';
+
+// Referenced by `server/` source but deliberately NOT in the curated badge
+// set — the case #3335 exists for.
+const REFERENCED_STAGE = 'pipeline-series-concept-judge';
const STAGES = {
'brain-classifier': { name: 'Brain Classifier', description: 'Classify a thought' },
@@ -70,7 +74,26 @@ describe('prompts routes — system stages', () => {
it('GET /:stage/usage reports a user stage as deletable with no usage', async () => {
const r = await request(app).get('/api/prompts/my-own-stage/usage');
- expect(r.body).toMatchObject({ isSystemStage: false, canDelete: true, usedBy: [], warning: null });
+ expect(r.body).toMatchObject({
+ isSystemStage: false, canDelete: true, usedBy: [], referencedBy: [], warning: null,
+ });
+ });
+
+ it('GET /:stage/usage names the source files for a referenced non-system stage', async () => {
+ const r = await request(app).get(`/api/prompts/${REFERENCED_STAGE}/usage`);
+ expect(r.status).toBe(200);
+ // The badge stays curated-only; only protection widens.
+ expect(r.body.isSystemStage).toBe(false);
+ expect(r.body.usedBy).toEqual([]);
+ expect(r.body.canDelete).toBe(false);
+ expect(r.body.referencedBy).toEqual(stageReferencedBy(REFERENCED_STAGE));
+ expect(r.body.referencedBy.length).toBeGreaterThan(0);
+ expect(r.body.warning).toMatch(/resolves this stage by name/i);
+ });
+
+ it('GET /:stage/usage still lists call sites alongside a curated stage', async () => {
+ const r = await request(app).get('/api/prompts/brain-classifier/usage');
+ expect(r.body.referencedBy).toEqual(stageReferencedBy('brain-classifier'));
});
it('DELETE /:stage refuses a system stage without force', async () => {
@@ -92,14 +115,39 @@ describe('prompts routes — system stages', () => {
expect(deleteStage).toHaveBeenCalledWith('my-own-stage');
});
+ it('DELETE /:stage refuses a referenced non-system stage without force', async () => {
+ const r = await request(app).delete(`/api/prompts/${REFERENCED_STAGE}`);
+ expect(r.status).toBe(400);
+ expect(r.body.code).toBe('SYSTEM_STAGE_PROTECTED');
+ expect(deleteStage).not.toHaveBeenCalled();
+ });
+
+ it('DELETE /:stage honors ?force=true on a referenced non-system stage', async () => {
+ const r = await request(app).delete(`/api/prompts/${REFERENCED_STAGE}?force=true`);
+ expect(r.status).toBe(200);
+ expect(deleteStage).toHaveBeenCalledWith(REFERENCED_STAGE);
+ });
+
// The guard and the usage report must agree on the SAME list — the drift
- // between two hand-copied arrays is what #3314 removed.
- it('guards exactly the keys the usage endpoint calls system stages', async () => {
+ // between two hand-copied arrays is what #3314 removed. #3335 widened the
+ // guard past the badge, so `canDelete` (not `isSystemStage`) is what has to
+ // match it.
+ it('guards exactly the keys the usage endpoint reports as undeletable', async () => {
+ for (const key of PROTECTED_STAGE_KEYS) {
+ const usage = await request(app).get(`/api/prompts/${encodeURIComponent(key)}/usage`);
+ expect(usage.body.canDelete, `${key} usage`).toBe(false);
+ const del = await request(app).delete(`/api/prompts/${encodeURIComponent(key)}`);
+ expect(del.status, `${key} delete`).toBe(400);
+ }
+ });
+
+ it('still badges only the curated system stages', async () => {
for (const key of SYSTEM_STAGE_KEYS) {
const usage = await request(app).get(`/api/prompts/${key}/usage`);
expect(usage.body.isSystemStage).toBe(true);
- const del = await request(app).delete(`/api/prompts/${key}`);
- expect(del.status).toBe(400);
}
+ const badged = PROTECTED_STAGE_KEYS.filter((key) => SYSTEM_STAGE_KEYS.includes(key));
+ expect(badged).toHaveLength(SYSTEM_STAGE_KEYS.length);
+ expect(PROTECTED_STAGE_KEYS.length).toBeGreaterThan(SYSTEM_STAGE_KEYS.length * 5);
});
});