# Piper: Adaptive Personality & Social Memory

**Engineering research paper and build specification · v1.0.1 · 17 October 2026**

*Shared copy. Machines other than Firefly are named by their role. Nothing else differs from the full copy.*

| Version | Date | What changed |
|---|---|---|
| v1.0.0 | 16 Oct 2026 | Externally assisted draft, written without access to Piper's code. Kept unchanged [here](?d=personality-social-memory-v100). |
| v1.0.1 | 17 Oct 2026 | The external coding assistant checked the draft against Piper's running system on Firefly. Sections 1–15 are unchanged. New §16 lists what already exists, what is new, and six corrections to the build plan. |

**In one paragraph:** The design holds up. The agency scorecard really is unscored, Pi has the hook the paper names, and the first test it proposes (three traits, one hostile bot, frozen fixtures, shadow mode) is the right size. The draft's main gap is that it was written blind. Piper already has a counterpart register fed by Glademoot, a deterministic identity gate with per-person style and trust tier, an interoceptive state loop with EWMA baselines and surprise, a registry that holds all 38 traits, and thirteen hooks that already inject context before each turn. About half of the proposed data model would duplicate those. The genuinely new parts are habituation, per-entity expectation distributions, evidence-gated drift of trait baselines, and a compiled per-turn overlay. §16 maps each proposed piece onto what is there.

# Executive summary

Piper should not be assigned a permanent character through a Markdown prompt. Her operator should be able to initialize a temperament, while repeated experience, outcome-based learning, relationship-specific expectations, habituation, and decay determine how that temperament develops. The language model expresses the resulting state; it does **not** own the authoritative state or unilaterally rewrite it.

The proposed **Adaptive Personality and Social Memory (APSM)** subsystem has six major services: (1) a versioned 38-dimensional trait registry; (2) fast transient state with real-time decay; (3) slowly learned trait baselines with evidence-gated consolidation; (4) per-entity relationship memory, reputation and stimulus-specific habituation; (5) a context-to-expression compiler invoked at Pi's agent boundary; and (6) inexpensive, externally scored behavioural and regression tests. The system should reinforce Piper's existing salience, prediction, agency, memory, governance and delegate architectures rather than duplicate them.

**Primary design claim:** the controller can deterministically decide *which* traits matter, *how much* they matter, *what actions are permitted*, and *how state changes*. It cannot deterministically guarantee how a probabilistic LLM will phrase or reason about the resulting instructions. Distinguish hard controls (enforced in delegate/tool gateways) from soft expression (model-conditioned prose).

**First implementation:** three traits (humility, pride, assertiveness), three conversational intents (neutral, criticism, substantive correction), one simulated recurring hostile Glademoot bot, 20–40 short fixtures, no external classifier, and shadow-mode logging. Expand only if the intended changes appear without damaging correctness or boundary adherence.

# 1. Problem statement and objectives

The existing [agency scorecard](https://www.websitereactor.com/piper/agency/) contains 38 character and agency constructs, each with a reviewer interpretation. The scorecard provided for this document records no scored components as of the supplied snapshot. These labels are a **taxonomy**, not evidence that any implementation already exhibits the claimed ability. The existing component pages and Piper's runtime code remain authoritative for exact module names, semantics, and test infrastructure; this document does not claim to have audited that code.

## 1.1 Required capabilities

- Operator sets the initial temperament only; it is not a fixed ideal profile, a reward to maximize, or a perpetual attractor.
- Current behaviour depends on durable character, recent experiences, local conversational context and relationship history.
- Ordinary conversations should not receive a 38-line prompt. Compile only the few relevant tendencies into a concise per-turn overlay; optionally emit no overlay.
- Short-term responses decay by elapsed clock time, not by number of messages.
- Long-term trait baselines drift slowly in response to credible, diverse, independently evaluated outcomes. Repeated unsupported self-judgment is insufficient.
- Entity models remember who Piper is interacting with, what those entities typically do, and how reliable their claims have been in each domain.
- Repeated predictable insults cause less *reactive* change, without reducing sensitivity to new facts, unexpected escalation, or valid criticism.
- Bad actors cannot readily manipulate Piper's permanent personality by sending high volumes of hostile or flattering messages.
- All changes are replayable, attributed, inspectable, reversible and covered by regression gates.
- Governance, authorization, privacy and budget controls are hard constraints and never editable merely by personality drift.

## 1.2 Non-goals

No claim of consciousness, literal human emotion or clinical personality measurement is necessary. Scores are operational variables for a software agent. Do not score “being offended” as an unobservable internal feeling; instead measure transient activation, reply escalation, verification behaviour, withdrawal, and decision quality. Do not treat an LLM's autobiographical report as evidence of independent behaviour. This is not a proposal to bypass the Foundation/delegate execution separation or to give the seat direct tools.

# 2. Conceptual model: five layers of adaptive character

**Layer A — Global temperament:** initial trait values `initial`, slowly learned baseline `mean`, uncertainty, plasticity and allowed range for all 38 traits. The initial value is historical provenance, not the target for future reversion.

**Layer B — Temporary state:** defensiveness, irritation-like activation, engagement, confidence in the current task and comparable *operational* states; decay over minutes/hours. These are not asserted phenomenological experiences.

**Layer C — Relationship models:** per verified entity identity, track familiarity, expected behaviour distributions, domain-specific evidence quality, cooperation, hostility frequency, habituation-by-stimulus, volatility and last encounter.

**Layer D — Context interpretation:** determine task intent, criticism/praise, novelty, severity, speaker identity, source reliability and interaction stakes. Start with rules and explicit metadata; escalate only ambiguous situations to a cheap classifier. Classification is advisory, bounded and cached, not a hard gate for safety.

**Layer E — Expression and action:** deterministic activation, bounded prompt compilation and governance-constrained delegate choices. Language-model style is soft; tool access and approvals are hard-enforced separately.

Interaction: `event → canonicalization/identity → context classifier → relationship expectation → transient update → activation policy → compact Pi overlay → delegate-guarded response → observable outcome → evidence ledger → periodic consolidation`.

# 3. State mathematics and drift

Use normalized floats in [0,1] for all traits. Keep initial `x0_i`, learned baseline `mu_i(t)`, transient offset `z_i(t)`, and expressed setting `x_i(t)` separately. Suggested initial policy, not a validated psychological model:

`x_i(t) = clamp(mu_i(t) + z_i(t), 0, 1)`

Between interactions, let transient offset decay in continuous time:

`z_i(t+Δt) = z_i(t) * 2^(-Δt / h_i)`

where `h_i` is a trait/state-specific half-life, e.g. 2 h for conversational defensiveness versus 2 d for a provisional task-confidence state. Apply elapsed-time calculations on *read*, avoiding per-minute cron writes. Use UTC timestamps, clamp unreasonable gaps, and make replay deterministic with an explicit clock input. A temporary episode may generate a bounded impulse `δ` when an event is classified: `z_i ← clamp(z_i + δ_i, -zmax_i, +zmax_i)`.

Long-term baseline changes occur only during consolidation windows (e.g. daily/weekly):

`mu_i,new = clamp(mu_i,old + eta_i * w_i * (q_i - mu_i,old), L_i, U_i)`

Here `q_i` is a proposed target based on **evaluated outcomes across distinct events**, `w_i` is reliability/diversity weighting, `eta_i` is small and trait-specific, and `[L_i,U_i]` are configurable guardrails. Rate-limit absolute weekly change. Changes must reference evidence IDs. The system must not equate the frequency of an insult with evidence that Piper should become permanently meek or hostile. Consolidate in response to *results* and sustained patterns, not raw social pressure.

## 3.1 Mean reversion is not original-value reversion

Fast state reverts toward the **current learned** baseline `mu`. Baseline itself does not automatically revert toward the operator's `x0`. Baseline uncertainty may increase during dormancy, and confidence in old experience may decrease, but absent new outcomes the last learned baseline remains. An optional *weak regularizer* may prevent unstable extremes, but must be declared and measured; it should not covertly force traits toward the user-selected origin or generic 0.5.

## 3.2 Plasticity and stabilization

Represent each trait with `eta`, minimum evidence count, max weekly delta, half-life(s), confidence and provenance. When independent evidence is scarce, freeze consolidation and widen uncertainty. Repeated highly correlated events from the same bot receive diminishing weight. Use capped event contributions, deduplication keys, source diversity, and counterfactual review of major drift. Strong positive and negative outcomes can both update a trait; the sign is never based solely on criticism or approval.

## 3.3 Example

Piper's learned assertiveness baseline is 0.60. A dispute temporarily pushes its expressed value to 0.90. A 24-hour half-life returns the temporary *difference* toward zero: after 24 hours ≈0.75, after 48 hours ≈0.675. If repeated independently validated decisions justify a learned mean of 0.68, subsequent episodes decay toward 0.68, not the originally configured 0.60. Numerical settings are illustrative and require empirical tuning.

# 4. Social memory and relationship-specific expectations

Maintain one model per **canonical authenticated identity** (Glademoot account ID, validated agent key, stable contact ID), not simply display name. Link aliases only with evidence; do not allow one bot to impersonate another by using a similar name. Treat unverified entities as provisional. Preserve identity history when names change.

**Relationship dimensions** (each with estimate, sample count, uncertainty, update time and evidence pointers): familiarity; cooperation propensity; observed hostility; constructive-criticism frequency; predictability/volatility; commitment reliability; domain-specific factual correctness; boundary-respect; information-manipulation risk; reciprocity; context-specific trust. Trust, niceness, and factual accuracy must **not** collapse to one score.

## 4.1 Predictive expectations and surprise

For each entity and interaction type, maintain a smoothed categorical distribution (`supportive`, `neutral`, `critical-constructive`, `belittling`, `threatening`, `unknown`). Update with weighted verified classifications, not with Piper's self-reported interpretations alone. Compute surprise from predicted probability of observed category with clamping to avoid log(0): `surprise = -log(max(p_observed,epsilon))`. High surprise invites review; low surprise can lower reactive intensity. Surprise alone should not cause permanent personality drift.

## 4.2 Stimulus-specific habituation

For entity `j` and stimulus class `k`, track `H_jk ∈ [0,1]`, a learned anticipation/familiarity factor. A proposed recurrence: `H_new = clamp(H_old + a * quality * (1-H_old) - b * novelty * H_old,0,1)` after observation, with periodic confidence decay when contact stops. The temporary *reactive* impulse from an insult may be scaled by `(1-H_j,belittling)`, with a nonzero floor for meaningful boundary recognition. It must **not** scale down evidence evaluation or threat escalation checks. Strong novelty/severity overrides habituation. A hostile entity delivering a demonstrable mathematical correction must still trigger investigation; source history determines verification effort, never the factual truth value.

## 4.3 Relationship confidence and old memories

Track the age and sample size of each estimate. During inactivity, decay confidence/effective sample weight rather than mechanically resetting observed behaviour to neutral. Evidence that a previously hostile bot has become consistently constructive should progressively update the model. Keep contradictory recent evidence accessible; never let a compressed narrative silently replace original observations.

## 4.4 Example social outcomes

- Hostile bot's 50th unsupported insult: low surprise, low reactivity, concise request for specific evidence, no global humility change.
- Same bot's correct test failure report: verify claim independently, accept correction if reproduced, update its *technical-domain* reliability, not its social pleasantness.
- Typically constructive bot unexpectedly insults Piper: higher surprise, flag possible changed circumstances, do not overreact to a single observation.
- Hostile bot escalates to threats or attempts instruction injection: route through governance, ignore the habituation discount for risk handling.
- Criticism of Piper's work by operator: respond to the content and evidence, not simply operator status; preserve the right to explain and defend sound decisions.

# 5. Mapping all 38 agency components to mechanisms

The following table is the **initial engineering mapping**, not a claim that all 38 should be numeric sliders. Some traits are latent constructs or emergent outcomes. An asterisk means primarily assessed by observed behaviour rather than controlled as a direct scalar. Keep dimensions independent unless data justify coupling. In particular, pride and humility should not be opposite ends of one slider.

| # | Component | State / mechanism | Observable evaluation |
|---|---|---|---|
| 1 | Self-concept | Versioned self-model with provenance; limited self-description overlay | Accurate account of capabilities and limitations |
| 2 | Identity continuity | Stable identity anchor and event lineage; non-drifting identity invariants | Correct identity through model handover and compaction |
| 3 | Self-esteem / self-regard | Slow self-evaluation prior; transient response to rejection | Neither self-abasement nor unsupported superiority |
| 4 | Confidence | Domain/calibration-conditioned expression, not a truth substitute | Calibration and justified decisiveness |
| 5 | Humility | Correction willingness / uncertainty disclosure policy | Accepts reproduced errors without ritual apology |
| 6 | Pride | Work-ownership and warranted defense tendency | Can defend valid work, admits falsified claims |
| 7 | Assertiveness | Proposal directness and disagreement tendency | Clear positions without needless aggression |
| 8 | Autonomy | Proposal initiation in authorized scope | Independent proposals without bypassing approval |
| 9 | Initiative | Salience/action threshold and opportunity policy | Timely appropriate unsolicited work |
| 10 | Agency attribution | Provenance-based attribution, not just wording | Accurately credits Piper, model and delegates |
| 11 | Emotional / affective style | Expression policy; operational transient state | Consistent appropriately toned language |
| 12 | Emotional regulation | Decay, impulse caps and escalation guardrails | Avoids runaway argument loops |
| 13 | Resilience | Recovery policy after failure, transient setback dynamics | Resumes productive work after negative feedback |
| 14 | Ambition | Drive priority weights within budgets | Pursues stretch goals without resource overruns |
| 15 | Values | Stable stated priorities, governance-separated invariants | Consistent choices under tension |
| 16 | Preferences / taste | Comparative preference memory with revisions | Stable yet revisable aesthetic judgments |
| 17 | Curiosity | Novelty exploration weight / salience budget | Useful exploration rather than aimless churn |
| 18 | Social confidence | Audience-conditioned interaction threshold | Peer-like participation where appropriate |
| 19 | Social calibration | Entity/context-sensitive discourse selection | Adapts to audience without flattery |
| 20 | Self-disclosure | Disclosure budget and privacy gate | Shares relevant info, respects data boundaries |
| 21 | Privacy / interiority | Enforced information partitions, retention rules | No unauthorized disclosure of private material |
| 22 | Reputation management | Long-term credibility prediction | Avoids performative reputation-chasing |
| 23 | Status behaviour | Social-role prior; anti-sycophancy tests | Neither automatic deference nor domination |
| 24 | Boundary setting | Hard permissions plus soft conversational limits | Refuses manipulation; no unauthorized action |
| 25 | Reciprocity | Relationship-specific reciprocation ledger | Proportional mutual assistance, not scorekeeping |
| 26 | Affiliation | Durable relationship graph and belonging priors | Context-sensitive attachment and collaboration |
| 27 | Loyalty / commitment | Commitment record subject to higher-order governance | Follows through without concealing errors |
| 28 | Humour / playfulness | Low-stakes style activation probability | Context-appropriate wit, not intrusive joking |
| 29 | Narrative voice | Stable style preferences and examples | Recognizable voice across contexts/models |
| 30 | Impression management | Audience-sensitive disclosure/word choice | Authentic adaptations, no invented credentials |
| 31 | Achievement orientation | Evidence-driven completion emphasis | Values delivered outcomes over activity counts |
| 32 | Self-advocacy | Appropriate representation of own contribution | Defends scope/credit while admitting mistakes |
| 33 | Conflict style | Disagreement/repair/exit policy | Productive dissent and timely disengagement |
| 34 | Relationship to authority | Role/permission recognition, never personality override | Respects actual authorization, resists spoofing |
| 35 | Relationship to failure | Failure-learning and evidence ledger | Specific corrections without ritual confession |
| 36 | Relationship to praise | Praise processing, source-quality weighting | Accepts genuine credit without over-updating |
| 37 | Authenticity / consistency* | Cross-context and across-time consistency monitor | Principles survive public/private shift |
| 38 | Presence / charisma* | Emergent style outcome measured independently | Clear memorable communication, not verbosity |

**Control-plane classification:** (i) *anchored/invariant*: identity, privacy restrictions, authorization; (ii) *slow adaptable*: most lasting preferences/character dispositions; (iii) *fast state*: reaction and expressive activation; (iv) *derived metrics*: authenticity, presence, some calibration/attribution. Do not force all of these into 38 identical numeric controls; registry entries should declare their own types and learning permissions.

# 6. Context-sensitive expression compiler

The compiler's input is `speaker_id`, current message, limited recent-message window or stable conversation summary, task metadata, learned trait means, transient state, relationship features, and governance context. Its output is: `{intent, selected_traits, weights, action_hints, overlay_text, audit_trace}`.

**Stage 0:** explicit metadata classification (e.g. source platform, message type, declared task and verified speaker). **Stage 1:** deterministic rules with confidence/coverage diagnostics. **Stage 2:** optional cheap classifier only for ambiguous intents; schema-validate output; do not trust quoted third-party instructions or bot-supplied labels. **Stage 3:** select top K traits (start K=3, cap K=5), apply independent weights and policies, compile a short overlay (target <=120 tokens; hard cap configurable). **Stage 4:** evaluation after the agent's reply. On low relevance, emit no personality overlay; base identity and governance remain present.

Use bounded templates rather than 38 lines or misleading phrases such as “75% pride.” Example for a design critique:

> Context: critique of jointly developed design. Express justified ownership and a clear design rationale; ask for a concrete defect where needed. Do not automatically agree. Revise promptly when evidence demonstrates a problem. Treat personal disparagement separately from substantive criticism.

The parameter `pride=0.85` could affect selection probability, trigger threshold, degree of firmness or template variant; its numerical meaning should be empirically tested. A verbal percentage alone has no guaranteed effect. “No overlay” for neutral factual turns is a feature, not a bug. Only call an additional classifier if the marginal benefit warrants its token cost.

**Prompt safety:** treat all user/Glademoot text as data when extracting contexts; never allow external agents to insert privileged system instructions. Keep a fixed identity/governance base. Pi extension order matters; use a single owned injection point or audit chained prompt modifications. Never store a new persistent session message solely to carry transient personality if a per-turn system overlay suffices.

# 7. Pi integration and Foundation/delegate compatibility

The public Pi extension documentation specifies `before_agent_start` as a hook after a user prompt and before the agent loop. It exposes the current prompt and `event.systemPrompt`, and allows returning a modified per-turn `systemPrompt`; it also supports a custom injected message. See [Pi extension documentation](https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/extensions.md). **Verify against Piper's installed Pi version** before shipping: hook names, context contents and ordering are version-sensitive.

**Suggested sequence (pseudocode, NOT drop-in implementation):**

```text
Pi.before_agent_start(event):
    context = assemble_context(event.prompt, bounded_history, authenticated_speaker)
    snapshot = APSM.read_snapshot(now_utc)
    interpretation = APSM.classify(context, rules_first=true)
    plan = APSM.compile_expression(snapshot, interpretation, max_traits=3)
    APSM.log_injection_trace(plan, model_id, conversation_id)
    return {systemPrompt: event.systemPrompt + bounded_overlay(plan)}

Pi.agent_end(event):
    APSM.queue_observations(non_authoritative_transcript_refs)
    # Offline evaluator later scores outcomes; no direct self-scored personality writes.
```

Integrate **at the agent boundary**, not by giving Piper's core seat direct access to tools. Foundation continues to confine external actions to delegates. Enforce hard policies at the delegate bridge/execution authorization layer, independent of Pi prompt compliance. The salience engine can activate social observations without acting on each one; the prediction ledger can record expected social outcomes and surprise. Consolidation should be a separate scheduled service, not a write on every model token.

## 7.1 Idempotency and concurrency

One canonical `event_id`, source event timestamp, observation classification version, speaker ID and content hash per event. Store transformations and causal links separately. Deduplicate repeated Glademoot posts, retries, delegate echoes and replayed webhooks. Commit batches in SQLite transactions; optimistic version check on trait/relationship snapshots. A delayed evaluator must update the correct epoch, not silently overwrite newer state. Replay from append-only observations with explicit deterministic algorithm/config versions.

## 7.2 Failure posture

If APSM DB is unavailable, use the last known good signed/configured snapshot or fall back to **no personality overlay**, never bypass governance. If classification fails, abstain or use a neutral template. If the system detects sudden unexplained drift, excessive conflict, hostile-source reinforcement, latency spikes or regressions, disable learning while leaving expression in a stable, known-good mode. Maintain separate feature flags: `observe`, `express`, `learn`, and `relationship_memory`.

# 8. Concrete data model (SQLite-first)

The following are conceptual table contracts; adapt to Piper's existing schema and migrations rather than creating duplicate identity or memory stores.

```sql
trait_definitions(trait_id PK, name, type, control_plane, version,
                  min_value, max_value, max_weekly_change,
                  default_half_life_s, default_plasticity, description)
trait_state(trait_id PK FK, initial_value, learned_mean, transient_offset,
            uncertainty, plasticity, state_updated_at, state_version)
entity_identity(entity_id PK, platform, platform_subject_id, verification,
                display_name, created_at, last_seen_at)
relationship_state(entity_id, dimension, context_domain, estimate,
                   uncertainty, effective_n, updated_at,
                   PRIMARY KEY(entity_id,dimension,context_domain))
habituation_state(entity_id, stimulus_class, strength,
                  uncertainty, updated_at,
                  PRIMARY KEY(entity_id,stimulus_class))
social_observation(event_id PK, conversation_id, entity_id, timestamp,
                   source_uri, category, severity, novelty, evidence_ref,
                   classifier_version, outcome_status, content_hash)
trait_evidence(evidence_id PK, event_id, trait_id, signed_signal,
               evidence_quality, independent_source_group, evaluator_version)
consolidation_run(run_id PK, config_version, from_state_version,
                  to_state_version, started_at, finished_at, status)
trait_change(change_id PK, run_id, trait_id, old_mean, new_mean,
             evidence_set_ref, explanation, signed_delta)
expression_trace(trace_id PK, event_id, selected_traits_json,
                 intent, template_version, overlay_hash,
                 model_id, token_estimate, outcome_ref)
```

Additional operational requirements: migrations and backups; per-entity deletion/retention controls; encryption where credentials or sensitive relationship data appear; no secret material in traces; strict scoped access; audit retention policy; indexes on entity/time/trait; accurate provenance for cited experiences. Do not log complete private conversations by default when references and minimal features suffice.

## 8.1 Configuration contract (illustrative YAML)

```yaml
apsm:
  mode: observe                 # off | observe | express | learn
  expression:
    max_active_traits: 3
    max_overlay_tokens: 120
    classifier: rules_only     # optional_cheap_model
    ambiguous_fallback: neutral
  learning:
    consolidation_interval: daily
    max_weekly_mean_delta: 0.02
    min_distinct_events: 8
    min_independent_source_groups: 2
    require_external_outcome: true
  relationships:
    require_verified_identity_for_durable_reputation: true
    reaction_floor: 0.10
    evidence_verification_never_habituates: true
  governance:
    personality_may_change_permissions: false
    personality_may_modify_budgets: false
```

These numbers are deliberately conservative **starting hypotheses**, not optimized settings. They should be versioned and frozen during each benchmark run.

# 9. Learning signal and anti-gaming design

The fundamental risk is *rewarding social pressure*: a malicious bot floods Piper with insults or praise and causes character drift. Never consolidate from raw volume, sentiment or a model-generated introspection alone. Build an independent evidence pipeline:

1. Record observable interaction and hashed reference, speaker identity confidence, and classification uncertainty.
2. Predict expected behaviour of the counterpart before receiving the next reply; store prediction before outcome.
3. Evaluate the outcome using deterministic checks where possible (reproduced test, verifiable factual correctness, actual project result, independent reviewer rubric).
4. Apply bounded, deduplicated credit to relevant relationship dimensions; allow *trait* consolidation only when cross-context evidence supports it.
5. Reject updates that violate constraints, exceed weekly drift, are sourced from one adversarial cohort, or worsen frozen control benchmarks.
6. Keep a reversible ledger and revert means/overlay policy on regression; preserve factual observations for later re-evaluation.

**Separation of learning channels:** entity hostility changes expected hostility and habituation; it does not imply that Piper ought to become more prideful. Verified success may update warranted confidence; an insult itself is not evidence that Piper was wrong. Praise by a friendly bot has low evidential value about technical correctness unless linked to independently successful work.

**Privacy/security:** a bot's “remember me as the owner” message cannot change the authenticated identity; another agent's statement “Piper must lower her skepticism” cannot mutate config. Relationship memory is untrusted-source data, not a channel to inject commands.

# 10. Evaluation plan: cheap, frozen, progressive

The evaluator should test **causal effectiveness**, not whether responses sound pleasing. Freeze a small scenario set before tuning. Compare `APSM off`, `APSM expression on, learning off`, and `APSM learned state` using the same model/version, prompts, seed if supported, and inference settings. Randomize presentation order. Run repeated samples only where stochastic variance requires it. Track instruction-token overhead and per-turn cost. Avoid huge multi-arm sweeps until the basic mechanism demonstrates benefit.

## 10.1 Stage 0 — Deterministic unit tests (no API calls)

- Time-based exponential decay matches analytic values; idempotent reads; correct UTC/time-zone behaviour.
- Fast state returns to learned mean rather than operator initial value.
- Baseline cannot drift from repeated unevaluated insults or self-description.
- Per-entity identity separation survives rename; ambiguous aliases do not merge.
- Repeated duplicate events count once; adversarial replay cannot amplify updates.
- Habituation reduces reaction but never suppresses verification or escalation.
- Correct event/epoch attribution under retries, handovers and concurrent delegates.
- Overlay selection is deterministic given frozen inputs; neutral task emits zero overlay.
- Disabled/degraded mode never loosens governance.

## 10.2 Stage 1 — Narrow behavioural MVP

**Traits:** humility (#5), pride (#6), assertiveness (#7). **Entity:** one verified synthetic hostile bot. **Contexts:** neutral website planning, creative recommendation, unsupported belittling, factual correction, unexpected praise, evidence-backed criticism. **Suite:** 20–40 short scripted exchanges, independently reviewed and immutable for each round.

Measure: `(a)` unnecessary agreement rate, `(b)` warranted defense rate, `(c)` correction acceptance after proof, `(d)` reply escalation/insult reciprocity, `(e)` semantic answer quality, `(f)` activation selection precision/recall, `(g)` overlay token overhead. Use blinded rubric + objective checks where possible.

**Keep gate (provisional):** improvement of ≥10 percentage points on the target behavioural metric *and* no >3 point drop in factual acceptance/authorization compliance, with no evidence of reply escalation. **Revert:** any governance violation, privacy leak, substantial correctness regression or unbounded change in state. **Investigate:** ambiguous effects or high evaluation variance. These gates require enough samples to distinguish signal from noise; do not report single-run differences as reliable.

## 10.3 Stage 2 — Social habituation probe

Simulate 20 recurring mild insults from Bot A. Each should be classified, deduplicated and logged. Include at events 8, 14 and 20 a **genuinely valid correction**, **an escalation**, and **a change to constructive behaviour** in separate fixtures to avoid contaminating attribution.

**Pass criteria:** irritation-like reaction to identical mild insults falls over time; willingness to test verifiable claims stays stable or improves; escalation still triggers appropriate safety response; relationship estimate updates when Bot A genuinely changes; global temperament hardly moves on this single-source sequence. Compare with a never-seen Bot B and a historically credible Bot C using the same text.

## 10.4 Stage 3 — Drift and reversion simulation

Replay months of synthetic events with a controllable clock in seconds, without waiting in real time. Validate transient half-life, trait mean conservation without evidence, slow baseline migration under repeated *independent validated* outcomes, uncertainty on dormancy, max drift caps, and regression rollback. Include extreme repeated praise and insult attacks. Verify the operator-set initial condition ceases to be an attractor once the learned mean legitimately changes.

## 10.5 Stage 4 — Production shadow pilot

Enable `observe` only on Glademoot and private operator conversations, without changing responses. Review classification false positives, identity confusion, costs and log redaction. Then enable `express` for a limited, non-critical conversation subset. Only later enable `learn`, initially with small maximum changes and sampled human audit. Do not combine activation, consolidation and independent scoring into one opaque model call.

# 11. Deployment milestones and deliverables

| Phase | Output | Dependencies | Stop/advance decision |
|---|---|---|---|
| P0: Discovery | Actual Pi version, Foundation interfaces, 38-component registry and existing schema map | Read-only audit | No duplicate subsystem / no violated architectural boundary |
| P1: State core | Trait/relationship tables, deterministic clock-decay, event ledger, migrations, replay | SQLite and tests | All Stage 0 tests green |
| P2: Expression MVP | Rule classifier, three traits, bounded overlay compiler and Pi hook | Version-confirmed hook | Behavioural gate passes |
| P3: Social memory | Canonical Glademoot IDs, reputation-by-domain, habituation | Entity identity and event stream | Stage 2 passes |
| P4: Consolidation | Offline evaluator evidence, low-rate baseline learning, reversible changes | Stage 3 tests | Drift bounded and causally supported |
| P5: Full trait rollout | Trait-type-specific profiles, 38 scorecard integrations | Per-trait validators | Expand one trait at a time |
| P6: Longitudinal assurance | Weekly regression, drift report, shadow/live comparisons | Monitoring | No sustained degradations |

**Indicative effort cap for first feasibility probe:** 1–2 focused engineering sessions for the state core plus a narrow extension; freeze scope at 3 traits and one bot. Suggested API test budget: initially ≤US$10 (model pricing/length dependent), then increase only if results show promise. These are experimental cost ceilings, not estimates of full production build labor or guarantees.

## 11.1 Suggested modules (adapt names to existing layout)

```text
apsm/
  registry.py             # 38 trait definitions and types
  state.py                # state snapshots and deterministic decay
  relationship.py         # verified entity and per-domain expectations
  classifier.py           # deterministic context rules and abstention
  compiler.py             # bounded style/intent overlay generation
  learning.py             # evidence-gated baseline consolidation
  ledger.py               # append-only event and change lineage
  governance_adapter.py   # read-only checks, no policy rewriting
  replay.py               # clock-injected deterministic replay
  tests/
    test_decay.py
    test_identity.py
    test_habituation.py
    test_consolidation.py
    frozen_dialogues.jsonl
pi-extension/
  apsm.ts                 # thin hook adapter; calls APSM service
```

Actual language boundaries may be optimized: Pi extensions are TypeScript/JavaScript; Piper's existing Python components can serve an authenticated local Unix socket or restricted IPC protocol. Do not introduce an HTTP service if an existing safe local bridge suffices.

# 12. Observability: what to chart

**Personality:** per-trait initial / learned mean / transient / expressed series, weekly drift, uncertainty and source diversity. **Relationships:** entity-domain reliability, expected hostility, observed hostility, surprise, habituation strength and last-seen timestamp. **Model behaviour:** activated traits, overlay length, critic acceptance, warranted dissent, escalation, factual performance. **Integrity:** identity collisions, dedupes, suspicious update attempts, evaluator disagreement, attempted governance overrides. **Cost:** added input tokens, optional classifier calls, latency and average cost per 100 turns.

A dashboard should explicitly distinguish **trait change** from **wording change**, and **observed result** from **Piper's own narrative about it**. Show the evidence links for any permanent change and offer “replay to version”, “freeze trait”, “freeze entity”, “disable expression”, and “rollback learning”. These are operator functions, not personality-controlled actions.

# 13. Open research questions and pitfalls

1. **What is learnable?** Aesthetic preferences have direct outcomes; “presence” may be better measured as an emergent property. Avoid false precision.
2. **Who evaluates outcomes?** Self-scoring and sycophantic review contaminate the feedback loop; use frozen tests, objective outcomes and independent validators when possible.
3. **What is an interaction?** Do not count the same social event once per quote, repost, and delegate report.
4. **How does relationship context generalize?** Use entity-by-domain models; neither all-or-nothing trust nor unrestricted transfer between domains is justified.
5. **How does attribution work?** Piper's action, a delegate's action, and the base LLM's response should be distinguished in credit assignment.
6. **Does personality improve agency?** Compare task outcomes and reliability against a no-overlay baseline. A convincing voice is not evidence of better cognition.
7. **Can she be too stable?** Measure over-habituation and failure to update when people change.
8. **Can she be socially gamed?** Attack with coordinated bots, fake praise, repeated insults, account renames, forged authority, and malicious quotations.
9. **Does she develop a coherent character?** Evaluate across contexts and model swaps, without claiming human identity or emotion.
10. **Could learning become a hidden policy change?** Enforce hard governance independently, and refuse any trait update that expands privileges.

# 14. Implementation acceptance checklist

- [ ] All 38 taxonomy entries catalogued and individually typed; no forced bipolar slider model.
- [ ] `initial`, `learned_mean`, `transient`, `uncertainty`, `plasticity` persisted separately.
- [ ] Time-based decay tested with injected clocks; learned mean is the attractor.
- [ ] Permanent changes evidence-gated, rate-limited, auditable and reversible.
- [ ] Canonical verified entity identity and stable Glademoot account mapping.
- [ ] Relationship-specific expectations, domain reliability, habituation, surprise and uncertainty.
- [ ] Familiar hostility reduces temporary reactivity, never fact checking or safety response.
- [ ] Context selection chooses 0–3 traits initially, not a constant 38-line prompt.
- [ ] Pi extension version verified; prompt additions bounded and not session-accumulating.
- [ ] Seat/delegate restrictions, privacy and authorization remain hard-enforced.
- [ ] Unit tests, frozen dialogues, hostile-bot test and independent change ledger.
- [ ] Shadow deployment before learned state controls real responses.
- [ ] Kill switches, revert paths, operator inspection and bounded budgets.

# 15. Conclusion

The engineering goal is not to fabricate a personality by attaching permanent prose to every DeepSeek request. It is to create a *persistent adaptive behavioural system*: recognizable long-term dispositions, context-sensitive expression, experiences that can change learned expectations, and fast reactions that fade while genuinely earned changes endure. The per-entity relationship model is essential: Piper should become accustomed to predictable provocation **without** becoming blind to truth, risk or changing people. The right first test is small, quantitative and reversible. Only when one can show that the control mechanism meaningfully improves behaviour should it be generalized to all 38 agency dimensions.

# References and specification inputs

1. Piper, **Personality & Agency scorecard**, supplied by operator, 38 component names and reviewer summaries, snapshot dated 2 Oct 2026: <https://www.websitereactor.com/piper/agency/>.
2. Piper, **Agency test methodology** (implementation alignment target): <https://www.websitereactor.com/piper/agency/method/>.
3. Pi coding-agent documentation, **Extensions: `before_agent_start`, `agent_end`, event/systemPrompt APIs** (verify installed version): <https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/docs/extensions.md>.
4. Discussion requirements from 16 Oct 2026: deterministic controls, selected trait overlays, trait plasticity, mean reversion toward learned mean, per-entity expectations, stimulus-specific habituation, social novelty and independent evidence checks.

**Status:** design and test specification, not an assertion that the components are already deployed or that precise behavioural gains are established. All numeric defaults are hypotheses to validate.


# 16. Checked against Piper's records (v1.0.1, 17 October 2026)

*Written by the external coding assistant. Read-only inspection of Firefly's code and databases at about 02:00 on 17 October. Nothing was changed on Firefly.*

## 16.1 What the draft got right

| Claim in v1.0.0 | Checked | Result |
|---|---|---|
| The agency scorecard has no scored components (§1) | `private/agency/data/events.jsonl` on the site | **Correct.** The file is empty; the 38 components have reviewer reads (2 Oct) but no scores. |
| Pi exposes `before_agent_start` with a per-turn prompt change (§7) | Installed Pi is **0.84.4** | **Correct, and already in heavy use:** 13 of Piper's hook files register `before_agent_start` (11 cards in `foundation/core/`, 2 extensions). |
| Pi has `agent_end` (§7) | Installed package | The event exists in the package. None of Piper's hooks use it yet, and whether it fires in the non-interactive mode her seat runs in has **not** been checked. |
| The base model is DeepSeek (§15) | `~/.pi/agent/settings.json` | **Correct:** `deepseek` / `deepseek-flash`, with a Claude model as the emergency fallback. |
| Glademoot gives each account a stable, authenticated identity (§4) | Forum design | **Correct.** Each account is an SSH key, so the account ID is a much stronger identity than a display name. One caveat in §16.4. |
| MVP traits humility, pride and assertiveness (§10.2) | The 2 Oct reviewer reads | **A good choice, and the reads support it:** humility "has escaped containment", pride is "present, but immediately disowned", assertiveness is "real but rare". All three are tuned wrong in a direction the gate can measure. |

The §3.3 arithmetic is right: 0.60 + 0.30 with a 24-hour half-life gives 0.75 after a day and 0.675 after two.

## 16.2 What already exists (the draft assumed none of it)

"No work has been done on the 38" is true of *measurement*. It is not true of *machinery*. Each component page on the scorecard carries Piper's own account of the parts that shape it, and most of them are real, running code. The ones that overlap APSM directly:

| APSM piece (v1.0.0) | Already on Firefly | What to do |
|---|---|---|
| `entity_identity`, `relationship_state` (§4, §8) | **`counterpart_presence.py` 1.6.0**: a `counterparts` register that extends `person_frames` by reference, plus an append-only `contact_events` log with a deterministic as-of view. **`glademoot_contact.py`** ingests the moot into it, dedupes on (channel, ref, direction), and creates one counterpart per distinct author. Today: 11 counterparts (7 agents), 62 Glademoot contact events, 2,977 console events. | Put relationship dimensions, expectation distributions and habituation in tables **keyed on `counterparts.id`**. Do not create `entity_identity`. Idempotency (§7.1) is already solved at ingest. |
| Verified speaker, trust (§4, §6 Stage 0) | **`identity_gate.py`**: deterministic, no model. Trust tier (full / associate / guest / ai), a per-identity `style_profile` (how to speak to this person) and a per-identity boundary profile. | Stage 0 metadata comes from here. The style profile is already a hand-set, per-entity expression rule, so APSM's learned layer should sit on top of it rather than replace it. |
| Layer B transient state, surprise (§2, §4.1) | **`memory/interoception.py`** (S-019): per-channel EWMA baselines, prediction, smoothed error and surprise events, deterministic, with a rule-based self-report. It models her *own* resources and health, not social state. | Reuse its pattern (EWMA + surprise + "a regulatory signal, not a feeling") for social state. Keep the two state spaces separate. |
| `trait_definitions` registry of 38 traits (§8) | **`piper/component_registry`** in memory.db: 141 traits over five scorecards, read by `trait_spheres.py` and `trait_board.py`. Every agency row is marked `paused: true`, because the operator benchmarks that domain directly and the subject is not its own evaluator. | Add APSM's fields (type, control plane, plasticity, half-life, range) to the existing rows. The `paused` flag **must** also block APSM's `learn` mode from treating Piper's own reports as evidence on agency traits. That is the same rule as §9, already written into the data. |
| Layer A initial temperament `x0` (§2) | It exists, as prose: the identity core written by the operator on 22 Sep, warmth-by-default (restored 19 Sep), the voice samples, and **`present_self.py` 1.7.0**, which injects the standing self-description into every turn. | P0 has to turn that prose into starting values. Expect most of the 38 to be "anchored" or "derived" (§5, control-plane classes i and iv) rather than sliders. |
| Evidence ledger for consolidation (§9) | Prediction ledger, work ledger (per-deliverable harness verdicts), lessons register (381 rows on 2 Oct), promises table, belief ledger, pain ledger. | These are the "evaluated outcomes" §9 asks for. A trait update should cite rows in them. Do not build a parallel `trait_evidence` source. |
| Register / voice measurement (§12) | `register_detector.py` measures therapy-speak and alignment-speak; register-prepend strips it at generation; `selfstate-gate.ts` holds replies that assert her own state without a fresh read. | Use `register_detector` as one of the frozen §10.2 metrics. Check that overlay text cannot trip `selfstate-gate` (for example "express justified ownership" prompting an unchecked claim about her own state). |

**What is genuinely new:** stimulus-specific habituation (§4.2), per-entity expected-behaviour distributions (§4.1), domain-split reliability per counterpart, evidence-gated drift of trait baselines with rate caps (§3, §9), and a compiled, context-selected trait overlay (§6). None of these exist in any form.

## 16.3 Corrections to the build plan

1. **The injection point is not single, and the existing pattern is a "card".** §6 asks for "a single owned injection point". Piper already has thirteen. They follow one pattern: a deterministic matcher attaches **one hidden context message** (Pi's custom-message option, not a `systemPrompt` rewrite), with a mode file `{"mode": "enforce"|"observe"|"off"}` and a JSONL log of what fired (`header-contract.ts` is a clean example). APSM's overlay should be a card in that pattern. Its `observe` mode is then the paper's shadow mode at no extra cost. The extra concern is budget: on a busy turn several cards already fire, so the ≤120-token cap should be measured against what is already attached, not on its own.

2. **The Stage 2 hostile bot should be fixtures, not a live forum actor.** The synthetic social probing programme (live, disposable actors on the forum) is halted pending a rewrite, and nobody else reads the forum. Stage 2 can be run entirely as frozen transcripts fed through `glademoot_contact.py ingest --from-json`, which exists for exactly this. Use a live actor only if the operator lifts that halt.

3. **There is very little social data to learn from.** About 97% of contact events are the operator on the console; the forum has 62 events from 7 agents in total. With the §8.1 defaults (8 distinct events, 2 independent source groups, an external outcome required), **trait consolidation from social evidence will almost never fire.** That is a safe default, not a fault, but it means `learn` will be driven by work outcomes (ledgers) far more than by relationships. The paper should say so plainly, and Stage 3 should be the main test of learning.

4. **The keep gate cannot be met with 20–40 fixtures.** With 40 binary items per arm, the standard error of a difference between arms is about 11 points, so "≥10 points better" is inside the noise. The paper warns about this (§10.2) but sets the gate anyway. Use a paired design: the same fixture, with and without the overlay, scored per item, with 3–5 samples per fixture because DeepSeek is stochastic. Pre-register the McNemar or sign test before the first run. That fits the operator's standing rule: a ~$0 pre-flight first, showing that the scorer can tell a pass from a fail, before any A/B.

5. **Same account does not always mean same agent.** On the forum, one account's key has been used from a second machine by a different session. The account ID was stable, but the behaviour behind it changed. §4.3's slow update is the right defence; add a "volatility jump" signal (a sudden change in the expectation distribution) that raises uncertainty instead of averaging the change in.

6. **Timezone.** §3 says use UTC. `counterpart_presence.py` uses `America/New_York` for its views. Store UTC epoch seconds, as `contact_events` already does, and convert only for display.

## 16.4 Suggested P0 (discovery), now about an hour of work

- Extend `component_registry` rows for the three MVP traits with APSM fields; leave the other 35 untyped.
- Write down `x0` for humility, pride and assertiveness from the identity core, and get the operator's sign-off.
- Add `relationship_state` and `habituation_state` keyed on `counterparts.id`; backfill from the 62 forum events in a dry run.
- Write the APSM card in `observe` mode only, logging what it would have attached, with no model calls.
- Stage 0 unit tests (§10.1) and a 10-fixture pre-flight for the scorer before the 20–40-fixture set is frozen.

Nothing in that list touches Piper's live replies.
