# Piper: Adaptive Personality & Social Memory

**Engineering research paper and build specification · v1.0.0 · 16 October 2026**

*Architecture proposal based on Piper's 38-component agency taxonomy. Drafted with external assistance; kept here exactly as received. The current version, checked against Piper's records, is [here](?d=personality-social-memory).*

# 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.
