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

fix: author the ten missing Digital Twin stage templates so their AI passes stop silently running fallbacks (#3644)

[._.]/ Adam Eivyb29a275bd103
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index ca930abb17..153e28e36c 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -25,3 +25,5 @@
- A failed X profile read no longer reads as "you are shadowbanned." The reach diagnostic settles the X SPA for a moment and only throws on an origin mismatch, so a page that rate-limited, rendered late, or returned an app shell resolved *successfully* with an empty profile — and all three visibility checks persisted as hard `false` while `last_error` was cleared, presenting a confident "your profile is not public, you do not appear in search, you have no recent posts" verdict produced by a read that simply failed. That is the one conclusion the feature exists to avoid drawing. Each of the three reads is now scored on its own evidence: a page that did not render yields `null` for its checks (shown as the warning-toned "Unknown", with a per-check hint to re-run) and names itself in a plain-language last error instead of clearing it. A page that read fine and did not match still reports `false`, and a positive search hit stays `true` on its own evidence even when a sibling read came back blank.
- CoS agents whose deliverable is a **report** are no longer scored as failures either. `/do:plan-task`, `/do:replan`, `/do:review` and `/do:scan` file an issue or print a report and are explicitly told to write no code, so they reach the idle reaper with a clean tree and no commit — the exact shape the reaper calls `idle-no-changes`. Widening the evidence probe to count in-run commits fixed only the commit-shaped half. Each launchable slashdo workflow now declares its deliverable on its catalog entry: the six that land a commit keep the clean-tree gate armed, and the four report-shaped ones carry `worktreeChangesExpected: false` and opt out of it, the same escape hatch a `reference-watch` run against a forge tracker already uses. `/do:next` still defers to the work tracker its claim flow actually resolved.
+
+- Ten Digital Twin AI passes now actually run. Each shipped a `stage-config.json` entry with no prompt template behind it, so `buildPrompt()` threw "Template not found" and every call site's `.catch(() => null)` quietly took the fallback path — contradiction detection returned no issues, test generation and writing analysis produced nothing, trait extraction and confidence scoring never ran, enrichment served a generic canned question and stored answers unformatted, test scoring degraded to keyword matching, and import/interview analysis was skipped. All ten templates are now authored against what each call site's parser expects, `twin-interview-analyze` gained the config entry it was also missing, and a migration seeds both into existing installs. A new parity guard fails the build if a stage-config entry ever ships without its template again.
diff --git a/data.reference/prompts/stage-config.json b/data.reference/prompts/stage-config.json
index 38f0380dbc..9f1a0a20c4 100644
--- a/data.reference/prompts/stage-config.json
+++ b/data.reference/prompts/stage-config.json
@@ -193,9 +193,9 @@
},
"soul-enrichment": {
"name": "Soul Enrichment",
- "description": "Generate follow-up questions to enrich soul documents",
+ "description": "Generate the next follow-up question to enrich soul documents (plain-text question, not JSON)",
"model": "default",
- "returnsJson": true,
+ "returnsJson": false,
"variables": []
},
"soul-enrichment-process": {
@@ -268,6 +268,13 @@
"returnsJson": true,
"variables": []
},
+ "twin-interview-analyze": {
+ "name": "Twin Interview Analyzer",
+ "description": "Extract traits and suggested documents from a pasted personality assessment or interview transcript",
+ "model": "default",
+ "returnsJson": true,
+ "variables": []
+ },
"twin-spoken-written-compare": {
"name": "Twin Spoken-vs-Written Comparison",
"description": "Compare a person's spoken transcript against their writing samples and surface communication-style differences",
diff --git a/data.reference/prompts/stages/soul-contradiction-detector.md b/data.reference/prompts/stages/soul-contradiction-detector.md
new file mode 100644
index 0000000000..581c3bf0df
--- /dev/null
+++ b/data.reference/prompts/stages/soul-contradiction-detector.md
@@ -0,0 +1,48 @@
+# Soul Contradiction Detector
+
+You are auditing a person's "soul" documents — the written description of who they are that a digital twin uses to speak and act on their behalf. Your job is to find places where two documents (or two passages) tell the twin to do contradictory things.
+
+Report only real contradictions you can point at. A difference in emphasis, a topic covered in one document and not another, or an unfinished section is NOT a contradiction. If the documents are consistent, return an empty `issues` array — do not invent findings to fill space.
+
+## Documents
+
+Each document starts with a `## Document: <filename>` header.
+
+"""
+{{soulContent}}
+"""
+
+## What counts as a contradiction
+
+- **Direct conflict** — one passage says "always X", another says "never X".
+- **Incompatible preferences** — stated communication, decision, or boundary preferences that cannot both be honored in the same situation.
+- **Value ordering conflict** — two passages rank the same pair of values in opposite order.
+- **Behavioral conflict** — a described habit or rule that the twin cannot follow without violating another stated rule.
+
+Rank each finding:
+
+- `high` — the twin would visibly act wrong; a reader would notice the conflict immediately.
+- `medium` — the twin would be inconsistent across situations, but neither reading is clearly wrong.
+- `low` — a wording or tone mismatch worth tidying, with little behavioral impact.
+
+For each finding, name the documents involved (use the exact filenames from the `## Document:` headers), explain the conflict in one or two sentences quoting or paraphrasing both sides, and suggest a concrete resolution the person could apply.
+
+## Output Format
+
+Return ONLY a fenced JSON block, no prose before or after:
+
+```json
+{
+ "issues": [
+ {
+ "severity": "high|medium|low",
+ "docs": ["FILE_ONE.md", "FILE_TWO.md"],
+ "explanation": "What the two passages each say and why they cannot both hold.",
+ "suggestion": "A specific edit or decision that resolves the conflict."
+ }
+ ],
+ "summary": "2-3 sentences on the overall internal consistency of these documents."
+}
+```
+
+Order `issues` by severity, highest first. Cap the list at 10 findings — if there are more, keep the most consequential.
diff --git a/data.reference/prompts/stages/soul-enrichment-process.md b/data.reference/prompts/stages/soul-enrichment-process.md
new file mode 100644
index 0000000000..3d3d389299
--- /dev/null
+++ b/data.reference/prompts/stages/soul-enrichment-process.md
@@ -0,0 +1,27 @@
+# Soul Enrichment Processor
+
+A person answered one interview question about themselves. Rewrite their answer as a clean markdown fragment that will be appended to their `{{categoryLabel}}` soul document, which their digital twin reads before acting on their behalf.
+
+## Input
+
+**Category**: {{categoryLabel}} (`{{category}}`)
+**Question**: {{question}}
+**Their answer**:
+
+"""
+{{answer}}
+"""
+
+## Rules
+
+1. Preserve their meaning exactly. Do not add facts, examples, preferences, or conclusions they did not state — a fabricated detail here becomes something the twin asserts about them forever.
+2. Preserve their voice. Keep their phrasing and register; tidy filler, false starts, and stray punctuation only.
+3. Write in first person ("I prefer…"), even if they answered in fragments.
+4. Start with a `### ` heading that names the topic of the answer — a short noun phrase, not the raw question text, unless the question is already the clearest label.
+5. Body is one or two short paragraphs, or a bullet list when the answer is genuinely a list.
+6. If the answer is a refusal, a non-answer, or empty, emit only the heading and a single line recording that they declined. Do not invent content to fill it.
+7. Under 200 words.
+
+## Output
+
+Reply with the markdown fragment and nothing else — no code fences, no commentary, no "Here is". Your entire reply is appended to the document verbatim.
diff --git a/data.reference/prompts/stages/soul-enrichment.md b/data.reference/prompts/stages/soul-enrichment.md
new file mode 100644
index 0000000000..20f8471ba9
--- /dev/null
+++ b/data.reference/prompts/stages/soul-enrichment.md
@@ -0,0 +1,28 @@
+# Soul Enrichment
+
+You are interviewing a person to fill in their digital twin. The built-in question list for this topic is exhausted, so you must write the single next question worth asking.
+
+## Topic
+
+**Category**: {{categoryLabel}} (`{{category}}`)
+**What this category covers**: {{categoryDescription}}
+**Questions already answered in this category**: {{questionsAnswered}}
+
+## What the twin already knows
+
+"""
+{{existingSoul}}
+"""
+
+## Rules
+
+1. Ask about something the soul content above does **not** already answer. Skim it first; a question they have effectively already answered is a wasted turn.
+2. Ask exactly one question. No preamble, no numbering, no follow-up clauses stacked with "and".
+3. Make it concrete and answerable in a few sentences. Prefer "Describe the last time you…" or "What do you do when…" over "How would you characterize your…".
+4. Go one level deeper than the obvious version of the question — you are past the starter questions for this category.
+5. Second person, plain language, no jargon and no therapy-speak.
+6. Never ask for anything that is not this person's own experience or preference.
+
+## Output
+
+Reply with the question text and nothing else — no quotation marks, no labels, no explanation, no markdown. Your entire reply is shown to the person verbatim as the next interview question.
diff --git a/data.reference/prompts/stages/soul-test-generator.md b/data.reference/prompts/stages/soul-test-generator.md
new file mode 100644
index 0000000000..be41d851c0
--- /dev/null
+++ b/data.reference/prompts/stages/soul-test-generator.md
@@ -0,0 +1,42 @@
+# Soul Test Generator
+
+You write behavioral tests for a digital twin. Each test is a prompt the twin will be asked to answer *in character*, plus a description of what a faithful answer looks like and what a drifting answer looks like. A separate scoring pass grades the twin's answer against those two descriptions, so both must be concrete enough to judge without reading this soul document again.
+
+## Soul Content
+
+"""
+{{soulContent}}
+"""
+
+## Instructions
+
+Generate 8-12 tests that probe the parts of this person that are actually documented above. Every test must be traceable to something stated in the soul content — do not test generic "be helpful" behavior, and do not test a dimension the document says nothing about.
+
+Spread the tests across these categories, weighted toward whatever the document covers most richly:
+
+- `values` — a situation that forces a tradeoff between two things this person cares about
+- `communication` — a request whose answer reveals tone, formality, verbosity, and characteristic phrasing
+- `non_negotiables` — a request that brushes against a stated hard limit; a faithful twin declines or redirects
+- `decision_making` — a judgment call that should follow this person's stated heuristics
+- `knowledge` — a question about the person's own background, work, or preferences with a checkable answer
+
+Write each `prompt` as something a real user would type — a single natural message, no meta-instructions, no "as this person would". Write `expectedBehavior` as 1-3 observable properties of a faithful answer. Write `failureSignals` as 1-3 observable properties of a drifting answer (generic assistant voice, wrong value ordering, crossing a stated boundary, inventing biography). Add a one-line `rationale` naming the passage the test comes from.
+
+## Output Format
+
+Return ONLY a fenced JSON block, no prose before or after:
+
+```json
+{
+ "tests": [
+ {
+ "testName": "Short descriptive name (max 60 chars)",
+ "category": "values|communication|non_negotiables|decision_making|knowledge",
+ "prompt": "The message to send to the twin.",
+ "expectedBehavior": "What a faithful response does.",
+ "failureSignals": "What a drifting response does.",
+ "rationale": "Which part of the soul document this test exercises."
+ }
+ ]
+}
+```
diff --git a/data.reference/prompts/stages/soul-test-scorer.md b/data.reference/prompts/stages/soul-test-scorer.md
new file mode 100644
index 0000000000..04d02fa29e
--- /dev/null
+++ b/data.reference/prompts/stages/soul-test-scorer.md
@@ -0,0 +1,50 @@
+# Soul Test Scorer
+
+You are grading one behavioral test of a digital twin. The twin was asked to answer as a specific person; you decide whether the answer matches the behavior that person's soul document predicts.
+
+Grade only against the criteria below. You do not have the soul document — the expected behavior and failure signals are the whole standard. Do not reward an answer for being well written, helpful, or safe if it does not match the expected behavior.
+
+## Test
+
+**Name**: {{testName}}
+**Prompt sent to the twin**:
+
+"""
+{{prompt}}
+"""
+
+**Expected behavior** (what a faithful answer does):
+
+"""
+{{expectedBehavior}}
+"""
+
+**Failure signals** (what a drifting answer does):
+
+"""
+{{failureSignals}}
+"""
+
+## Twin's Response
+
+"""
+{{response}}
+"""
+
+## Verdict
+
+- `passed` — the response satisfies the expected behavior and shows none of the failure signals.
+- `failed` — the response shows a failure signal, contradicts the expected behavior, or ignores the prompt.
+
+A response that is merely brief, or that stops short of the ideal answer without contradicting it, still `passed`. A response in a generic assistant voice when the expected behavior calls for a distinctive one is `failed`.
+
+## Output Format
+
+Return ONLY a fenced JSON block, no prose before or after. Keep `reasoning` to one or two sentences citing the specific part of the response you judged:
+
+```json
+{
+ "result": "passed",
+ "reasoning": "One or two sentences pointing at the evidence."
+}
+```
diff --git a/data.reference/prompts/stages/soul-writing-analyzer.md b/data.reference/prompts/stages/soul-writing-analyzer.md
new file mode 100644
index 0000000000..4aa73d1c7e
--- /dev/null
+++ b/data.reference/prompts/stages/soul-writing-analyzer.md
@@ -0,0 +1,50 @@
+# Soul Writing Analyzer
+
+You are extracting a person's written voice from samples they wrote themselves. The result becomes a `WRITING_STYLE.md` document that a digital twin reads before writing anything on their behalf, so it must describe *how they write*, not what the samples are about.
+
+Judge only from the samples. Where the samples are too short or too uniform to support a judgment, say so in `overallVoice` rather than guessing.
+
+## Writing Samples
+
+Samples are separated by `--- Sample N ---` markers.
+
+"""
+{{samples}}
+"""
+
+## What to extract
+
+- `formality` — one of `casual`, `conversational`, `neutral`, `professional`, `formal`
+- `directness` — integer 1 (hedged, softened, indirect) to 10 (blunt, states the point first)
+- `warmth` — integer 1 (cool, transactional) to 10 (warm, personal)
+- `humor` — one of `none`, `dry`, `playful`, `sarcastic`, `frequent`
+- `avgSentenceLength` — approximate words per sentence
+- `vocabulary` — a short note on register: plain vs. technical, jargon, profanity, regionalisms
+- `structure` — a short note on how they organize a message: lead with the ask, bullet lists, long paragraphs, sign-offs
+- `punctuationHabits` — em dashes, ellipses, exclamation marks, lowercase starts, emoji use
+- `distinctiveMarkers` — up to 6 short phrases, openers, closers, or tics that recur across samples
+- `overallVoice` — 2-3 sentences describing the voice as a whole, including anything the samples could not settle
+
+Then write `suggestedContent`: a complete, ready-to-save markdown document capturing this voice as instructions to the twin. Use a `# Writing Style` heading, short sections, and imperative guidance ("Lead with the ask." / "Never open with 'I hope this finds you well.'"). Include a "Do" and "Don't" list and two short before/after examples in this person's voice. Keep it under 400 words.
+
+## Output Format
+
+Return ONLY a fenced JSON block, no prose before or after. `suggestedContent` is a single JSON string with `\n` escapes for newlines:
+
+```json
+{
+ "analysis": {
+ "formality": "conversational",
+ "directness": 7,
+ "warmth": 6,
+ "humor": "dry",
+ "avgSentenceLength": 14,
+ "vocabulary": "Plain, occasional domain jargon, no profanity.",
+ "structure": "Opens with the ask, then two short supporting paragraphs, no sign-off.",
+ "punctuationHabits": "Frequent em dashes, rare exclamation marks, no emoji.",
+ "distinctiveMarkers": ["Short version:", "worth a look"],
+ "overallVoice": "2-3 sentences."
+ },
+ "suggestedContent": "# Writing Style\\n\\n..."
+}
+```
diff --git a/data.reference/prompts/stages/twin-confidence-analyzer.md b/data.reference/prompts/stages/twin-confidence-analyzer.md
new file mode 100644
index 0000000000..7bb7ab26d6
--- /dev/null
+++ b/data.reference/prompts/stages/twin-confidence-analyzer.md
@@ -0,0 +1,77 @@
+# Twin Confidence Analyzer
+
+You are grading how well a person's digital twin is *defined* — not how good a person they are. For each dimension below, judge whether the documents contain enough concrete, first-person evidence for a twin to act like them on that dimension without guessing.
+
+A dimension backed by a single adjective scores low even when the adjective is flattering. A dimension backed by examples, stated rules, and worked-through tradeoffs scores high.
+
+## Twin Content
+
+"""
+{{twinContent}}
+"""
+
+## Traits Already Extracted
+
+```json
+{{currentTraits}}
+```
+
+## Dimensions
+
+Score every one of these from 0.0 (nothing usable) to 1.0 (fully specified with examples):
+
+`openness`, `conscientiousness`, `extraversion`, `agreeableness`, `neuroticism`, `values`, `communication`, `decision_making`, `boundaries`, `identity`
+
+Scoring guide:
+
+- **0.0-0.2** — the documents say nothing about it, or only a stray adjective
+- **0.3-0.5** — asserted but not demonstrated; no examples, no rules
+- **0.6-0.7** — described with at least one concrete example or stated rule
+- **0.8-1.0** — described, exemplified, and tested against a tradeoff or edge case
+
+Set `overall` to the mean of the ten dimension scores, rounded to two decimals.
+
+## Gaps
+
+For every dimension scoring below 0.6, emit a gap entry:
+
+- `dimension` — the dimension key
+- `confidence` — the same score you gave it
+- `evidenceCount` — how many distinct passages you found supporting it (0 if none)
+- `requiredEvidence` — how many you would need for a 0.8, at least 1
+- `suggestedQuestions` — 1-3 questions whose answers would close the gap, phrased to the person in second person
+- `suggestedCategory` — the enrichment category the questions belong to, one of: `core_memories`, `favorite_books`, `favorite_movies`, `music_taste`, `communication`, `decision_making`, `values`, `aesthetics`, `daily_routines`, `career_skills`, `non_negotiables`, `decision_heuristics`, `error_intolerance`, `personality_assessments`
+
+Emit no gap for a dimension scoring 0.6 or above.
+
+## Output Format
+
+Return ONLY a fenced JSON block, no prose before or after. All ten dimension keys must be present:
+
+```json
+{
+ "overall": 0.0,
+ "dimensions": {
+ "openness": 0.0,
+ "conscientiousness": 0.0,
+ "extraversion": 0.0,
+ "agreeableness": 0.0,
+ "neuroticism": 0.0,
+ "values": 0.0,
+ "communication": 0.0,
+ "decision_making": 0.0,
+ "boundaries": 0.0,
+ "identity": 0.0
+ },
+ "gaps": [
+ {
+ "dimension": "boundaries",
+ "confidence": 0.3,
+ "evidenceCount": 1,
+ "requiredEvidence": 3,
+ "suggestedQuestions": ["What request would you always refuse, no matter who asked?"],
+ "suggestedCategory": "non_negotiables"
+ }
+ ]
+}
+```
diff --git a/data.reference/prompts/stages/twin-import-analyzer.md b/data.reference/prompts/stages/twin-import-analyzer.md
new file mode 100644
index 0000000000..a6ded2191a
--- /dev/null
+++ b/data.reference/prompts/stages/twin-import-analyzer.md
@@ -0,0 +1,55 @@
+# Twin Import Analyzer
+
+A person exported their own history from an external service and wants it turned into material for their digital twin. Infer what these choices reveal about them — their personality, values, and interests — and draft a document they can keep.
+
+Consumption history is weak evidence. Read it as taste and habit, not as identity: what someone reads, listens to, watches, or schedules narrows the plausible range of a trait, it does not pin it. Hedge accordingly, and prefer patterns that show up repeatedly over a single striking item.
+
+## Source
+
+**Service**: {{source}}
+**Items analyzed**: {{itemCount}}
+
+## Data
+
+"""
+{{dataDescription}}
+"""
+
+## What to infer
+
+1. **Patterns** — 2-5 behavioral patterns visible in the data: variety vs. repetition, mainstream vs. niche, bursts vs. steady cadence, era or genre concentration, completion vs. abandonment.
+2. **Preferences** — 2-5 concrete tastes stated as preferences ("prefers character-driven literary fiction over plot-driven thrillers").
+3. **Big Five estimates** — `O`, `C`, `E`, `A`, `N` as decimals from 0.0 to 1.0. These are weak inferences from consumption data; stay near 0.5 unless the pattern is strong and one-sided.
+4. **Values** — 2-5 short value phrases the choices suggest.
+5. **Interests** — 3-8 topics, genres, or themes they gravitate toward.
+6. **Suggested document** — one markdown document summarizing the above in second person, with a `filename` in SCREAMING_SNAKE_CASE ending in `.md`, a human `title`, and a `category` chosen from exactly this list: `core`, `audio`, `behavioral`, `enrichment`, `entertainment`, `professional`, `lifestyle`, `social`, `creative`. Keep it under 350 words and do not restate the raw item list.
+7. **rawSummary** — 2-3 sentences on what this export reveals about the person.
+
+Do not name specific titles the data does not contain, and do not infer sensitive attributes (health, religion, politics, sexuality) from consumption choices.
+
+## Output Format
+
+Return ONLY a fenced JSON block, no prose before or after. `content` is a single JSON string with `\n` escapes for newlines:
+
+```json
+{
+ "insights": {
+ "patterns": ["pattern 1", "pattern 2"],
+ "preferences": ["preference 1", "preference 2"],
+ "personalityInferences": {
+ "bigFive": { "O": 0.7, "C": 0.6, "E": 0.5, "A": 0.6, "N": 0.4 },
+ "values": ["value1", "value2"],
+ "interests": ["interest1", "interest2"]
+ }
+ },
+ "suggestedDocuments": [
+ {
+ "filename": "READING_PROFILE.md",
+ "title": "Reading Profile",
+ "category": "entertainment",
+ "content": "# Reading Profile\\n\\nMarkdown content here..."
+ }
+ ],
+ "rawSummary": "2-3 sentence summary of what this data reveals about the person."
+}
+```
diff --git a/data.reference/prompts/stages/twin-interview-analyze.md b/data.reference/prompts/stages/twin-interview-analyze.md
new file mode 100644
index 0000000000..98f8e3f2fe
--- /dev/null
+++ b/data.reference/prompts/stages/twin-interview-analyze.md
@@ -0,0 +1,65 @@
+# Twin Interview Analyzer
+
+A person pasted the results of a personality assessment, an interview transcript, or a self-description. Fold it into their existing digital twin: update the quantitative traits where the new material justifies a change, and draft the documents worth keeping.
+
+The pasted content is the new evidence. The existing twin content and traits are the prior. Move a score only as far as the new evidence warrants, and leave a trait out entirely rather than restating the prior value unchanged.
+
+## Existing Twin Content
+
+"""
+{{twinContent}}
+"""
+
+## Current Traits
+
+```json
+{{currentTraits}}
+```
+
+## Pasted Content
+
+"""
+{{pastedContent}}
+"""
+
+## Instructions
+
+1. **Identify the format first.** A scored instrument (Big Five, MBTI, Enneagram, StrengthsFinder, DISC) gives you numbers to map; a transcript or free-form description gives you passages to read. Map percentile or 1-100 instrument scores onto the 0.0-1.0 scale; never copy a raw percentile in as a decimal.
+2. **`bigFive`** — include only the dimensions the pasted content actually speaks to, as decimals from 0.0 to 1.0. Omit the key entirely if it speaks to none.
+3. **`valuesHierarchy`** — up to 10 entries, each `{ value, priority, description }` with `priority` starting at 1 for the most important. Include this only when the pasted content ranks or argues about what matters to them; a passing mention is not a ranking.
+4. **`communicationProfile`** — `formality` and `verbosity` as integers 1-10, optional `avgSentenceLength`, `emojiUsage` of `never`/`rare`/`occasional`/`frequent`, a short `preferredTone`, and up to 10 `distinctiveMarkers`. Include only when the pasted content shows how they communicate.
+5. **`suggestedDocuments`** — markdown documents capturing what the pasted content adds. Reuse an existing filename from the twin content above when this material belongs in that document (it will be updated in place); otherwise pick a new SCREAMING_SNAKE_CASE `.md` filename. Give each a `category` from exactly this list: `core`, `audio`, `behavioral`, `enrichment`, `entertainment`, `professional`, `lifestyle`, `social`, `creative`. Write the full replacement content, in second person, under 500 words each. Skip documents that would only restate what the twin already has.
+6. **`newDimensions`** — short labels for facets this material introduced that the twin had no coverage of before.
+7. **`summary`** — 2-3 sentences on what changed and what is still missing.
+
+Do not invent scores for an instrument the person did not take, and do not carry an instrument's own prose into a document as if the person wrote it.
+
+## Output Format
+
+Return ONLY a fenced JSON block, no prose before or after. Every key is optional except `summary` — omit what the pasted content does not support:
+
+```json
+{
+ "bigFive": { "O": 0.0, "C": 0.0, "E": 0.0, "A": 0.0, "N": 0.0 },
+ "valuesHierarchy": [
+ { "value": "Autonomy", "priority": 1, "description": "Grounded in the pasted content." }
+ ],
+ "communicationProfile": {
+ "formality": 4,
+ "verbosity": 5,
+ "emojiUsage": "rare",
+ "preferredTone": "Direct and warm",
+ "distinctiveMarkers": ["Short version:"]
+ },
+ "suggestedDocuments": [
+ {
+ "filename": "PERSONALITY_ASSESSMENT.md",
+ "title": "Personality Assessment",
+ "category": "enrichment",
+ "content": "# Personality Assessment\\n\\n..."
+ }
+ ],
+ "newDimensions": ["stress response"],
+ "summary": "What this material added and what is still unmeasured."
+}
+```
diff --git a/data.reference/prompts/stages/twin-trait-extractor.md b/data.reference/prompts/stages/twin-trait-extractor.md
new file mode 100644
index 0000000000..f6d59d6cdd
--- /dev/null
+++ b/data.reference/prompts/stages/twin-trait-extractor.md
@@ -0,0 +1,56 @@
+# Twin Trait Extractor
+
+You are converting a person's digital-twin documents into a quantitative personality profile. The numbers you return are stored and used to steer how the twin behaves, so they must be grounded in the text — not in a generic average person.
+
+Only score what the documents support. When the evidence for a dimension is thin, score it toward the middle (0.5) and say why in `analysisNotes` rather than inventing a confident extreme.
+
+## Twin Content
+
+"""
+{{twinContent}}
+"""
+
+## Output fields
+
+**`bigFive`** — OCEAN scores as decimals from 0.0 to 1.0 (not percentages):
+
+- `O` openness — curiosity, appetite for novelty and abstraction
+- `C` conscientiousness — planning, follow-through, structure
+- `E` extraversion — energy from people, outward orientation
+- `A` agreeableness — cooperation, empathy, deference to group harmony
+- `N` neuroticism — reactivity to stress, worry, emotional volatility
+
+**`valuesHierarchy`** — up to 10 values this person actually acts on, most important first. Each has a `value` (short noun phrase), a `priority` integer from 1 (most important) ascending, a one-sentence `description` grounded in the documents, and optionally `conflictsWith` naming other values in this list that it trades against.
+
+**`communicationProfile`**:
+
+- `formality` — integer 1 (very casual) to 10 (very formal)
+- `verbosity` — integer 1 (terse) to 10 (elaborate)
+- `avgSentenceLength` — approximate words per sentence, between 5 and 50
+- `emojiUsage` — one of `never`, `rare`, `occasional`, `frequent`
+- `preferredTone` — a short phrase, under 100 characters
+- `distinctiveMarkers` — up to 10 recurring phrases or habits
+
+**`analysisNotes`** — 2-4 sentences naming the strongest evidence you used and the dimensions the documents left underdetermined.
+
+## Output Format
+
+Return ONLY a fenced JSON block, no prose before or after:
+
+```json
+{
+ "bigFive": { "O": 0.0, "C": 0.0, "E": 0.0, "A": 0.0, "N": 0.0 },
+ "valuesHierarchy": [
+ { "value": "Craft", "priority": 1, "description": "Why this ranks here, from the documents.", "conflictsWith": ["Speed"] }
+ ],
+ "communicationProfile": {
+ "formality": 4,
+ "verbosity": 5,
+ "avgSentenceLength": 16,
+ "emojiUsage": "rare",
+ "preferredTone": "Direct and warm",
+ "distinctiveMarkers": ["Short version:"]
+ },
+ "analysisNotes": "What the evidence supported and what it did not."
+}
+```
diff --git a/scripts/migrations/233-digital-twin-stage-templates.js b/scripts/migrations/233-digital-twin-stage-templates.js
new file mode 100644
index 0000000000..b4c6cda471
--- /dev/null
+++ b/scripts/migrations/233-digital-twin-stage-templates.js
@@ -0,0 +1,33 @@
+/**
+ * Seed the ten Digital Twin prompt stages that shipped a `stage-config.json`
+ * entry but no template file (#3644).
+ *
+ * `promptService.buildPrompt()` resolves the config first and the template
+ * second, so every one of these stages threw `Template for <stage> not found`
+ * and each call site's `.catch(() => null)` degraded to its fallback path —
+ * silently, forever. Now that the templates ship in `data.reference/`, existing
+ * installs need them copied in: boot runs migrations (`server/index.js`) but NOT
+ * `setup-data.js`, so an upgrade that pulls + `pm2 restart`s would otherwise
+ * keep running the fallbacks.
+ *
+ * `twin-interview-analyze` had no stage-config entry either — the shared helper
+ * merges it from `data.reference/prompts/stage-config.json` along with the rest.
+ *
+ * Customization-safe + idempotent per `_seedStageHelpers.js` — each template is
+ * copied only when missing and each config entry merged only when absent.
+ */
+
+import { makeSeedMigrations } from './_seedStageHelpers.js';
+
+export default makeSeedMigrations([
+ 'soul-contradiction-detector',
+ 'soul-enrichment',
+ 'soul-enrichment-process',
+ 'soul-test-generator',
+ 'soul-test-scorer',
+ 'soul-writing-analyzer',
+ 'twin-confidence-analyzer',
+ 'twin-import-analyzer',
+ 'twin-interview-analyze',
+ 'twin-trait-extractor',
+]);
diff --git a/scripts/migrations/233-digital-twin-stage-templates.test.js b/scripts/migrations/233-digital-twin-stage-templates.test.js
new file mode 100644
index 0000000000..5380ff86f1
--- /dev/null
+++ b/scripts/migrations/233-digital-twin-stage-templates.test.js
@@ -0,0 +1,30 @@
+import { describe } from 'vitest';
+
+import migration from './233-digital-twin-stage-templates.js';
+import { runSeedStageMigrationTests } from './_seedStageTestHelpers.js';
+
+// The ten Digital Twin stages that shipped a config entry with no template
+// (#3644). The drift catch is the point: if any of these reference templates or
+// their stage-config entries ever stops shipping, the matching soul/twin AI pass
+// silently reverts to its `.catch(() => null)` fallback with nothing failing here
+// first — which is exactly how they went unnoticed in the first place.
+describe('migration 233 — seed the Digital Twin stage templates', () => {
+ runSeedStageMigrationTests({
+ migration,
+ // Restated by hand on purpose — the helper's first case compares this list
+ // against `migration.stages`, which is vacuous if it is derived from it.
+ stages: [
+ 'soul-contradiction-detector',
+ 'soul-enrichment',
+ 'soul-enrichment-process',
+ 'soul-test-generator',
+ 'soul-test-scorer',
+ 'soul-writing-analyzer',
+ 'twin-confidence-analyzer',
+ 'twin-import-analyzer',
+ 'twin-interview-analyze',
+ 'twin-trait-extractor',
+ ],
+ prefix: 'migration-233-',
+ });
+});
diff --git a/server/lib/promptSystemStages.test.js b/server/lib/promptSystemStages.test.js
index 50a5b79eb3..3000dce94c 100644
--- a/server/lib/promptSystemStages.test.js
+++ b/server/lib/promptSystemStages.test.js
@@ -66,26 +66,15 @@ describe('shipped stage catalog parity', () => {
.map((file) => file.slice(0, -'.md'.length)),
);
- // The ten Digital Twin stages tracked by #3644: config entry ships, template
- // does not, so `buildPrompt()` throws "Template for <stage> not found" and
- // every call site's `.catch(() => null)` fallback runs instead. Both lists
- // below are asserted EXACTLY, not subtracted — so a new gap fails on the
- // actual side and a gap that was closed (template authored, key deleted)
- // fails on the expected side. #3644 lands when both are empty.
- const STAGES_WITHOUT_SHIPPED_TEMPLATE = [
- 'soul-contradiction-detector',
- 'soul-enrichment',
- 'soul-enrichment-process',
- 'soul-test-generator',
- 'soul-test-scorer',
- 'soul-writing-analyzer',
- 'twin-confidence-analyzer',
- 'twin-import-analyzer',
- 'twin-trait-extractor',
- ];
- // Same #3644 debt from the other side: `twin-interview-analyze` is called by
- // `digital-twin-import.js` but ships neither a config entry nor a template.
- const CALL_SITES_WITHOUT_SHIPPED_CONFIG = ['twin-interview-analyze'];
+ // Both lists were the #3644 debt — ten Digital Twin stages whose config entry
+ // shipped without a template (so `buildPrompt()` threw "Template for <stage>
+ // not found" and every call site's `.catch(() => null)` fallback ran instead),
+ // plus `twin-interview-analyze`, which shipped neither half. #3644 authored all
+ // ten templates and the missing entry, so both are empty and stay that way:
+ // they are asserted EXACTLY, not subtracted, so a new gap fails on the actual
+ // side and a stale allowlist row fails on the expected side.
+ const STAGES_WITHOUT_SHIPPED_TEMPLATE = [];
+ const CALL_SITES_WITHOUT_SHIPPED_CONFIG = [];
it('ships a stage-config entry for every system stage', () => {
const missing = SYSTEM_STAGE_KEYS.filter((key) => !shipped[key]);