Elnor Repo Reader

CD-A_4-1-26_DOC3_DOC24_CYCLE.md

OP-A and Operations and Trackers/CD Cross Docs/CD-A_4-1-26_DOC3_DOC24_CYCLE.md

Short text page 0212bc006e8e. Generated 2026-06-09T01:23:58.539Z from commit dbaa25962edc11ab30e8d4ca1715f9ae5bf77331. Worktree: clean.

Open readable HTML page · Open raw txt · Open path URL

ELNOR REPO READER TEXT MIRROR
Original path: OP-A and Operations and Trackers/CD Cross Docs/CD-A_4-1-26_DOC3_DOC24_CYCLE.md
Source repo: /Users/OpenClaw1/Elnor/Elnor Specs
Git branch: main
Git commit: dbaa25962edc11ab30e8d4ca1715f9ae5bf77331
Generated: 2026-06-09T01:23:58.539Z

---

# CD-A [4.1.26 from DOC3/24 Cycle]

**Full title:** Cross-Document Obligations & Staged Spec Content — DOC3 R11.3 / DOC24 KDA Work Cycle
**Date:** April 1, 2026
**Status:** Active staging document
**Scope:** All cross-document obligations, architectural additions, and spec content generated during the DOC3 R11.3 "Teach by Example" and DOC24 Knowledge Delivery Architecture work cycle that do NOT go directly into DOC3 R11.3 or DOC24 KDA revisions.
**Indexed in:** CD Master Integration Index R1

---

## How to use this document

This document is a staging area. It contains real spec content — schemas, algorithms, configuration values, architectural decisions — organized by the target document that must eventually absorb each item.

**For manual revision:** When you next revise DOC11, open this document, find the DOC11 section, and pull the items marked `pending` into the spec.

**For automated integration:** Claude Code / Codex reads this document, filters by target doc, reads each obligation + its spec text, and proposes insertion into the target doc's next revision.

**Lifecycle:** Items transition from `pending` → `accepted` (absorbed into target doc draft) → `integrated` (verified in canonical spec) → `closed`. When all items reach `closed`, this document is archived.

## Status vocabulary

- `pending` — not yet absorbed into target doc
- `accepted` — accepted into target doc draft, awaiting verification
- `integrated` — verified in canonical target spec
- `deferred` — intentionally postponed to a later cycle
- `superseded` — replaced by a later decision
- `closed` — fully done

## Source documents for this cycle

| Source | Description |
|---|---|
| DOC3_R11_3_RED_TEAM_ADJUDICATION_CARD.md | 96-item adjudication across 5 reviewers |
| DOC24_KNOWLEDGE_DELIVERY_SHARED_CONTRACTS_PROPOSAL.md | Shared contracts, rendering pipeline, neuroplasticity |
| DOC3_R11_3_STRESS_TEST_FOLLOWUP.md | 7 end-to-end user journey problems |
| DOC3_R11_3_RED_TEAM_REVIEW_CLAUDE.md | 30-item red team review |
| Gemini_DOC3_24_RT_Adjucation_Master_and_New_Ideas.md | Adjudication review + Four Pillars architecture |
| Knowledge_Deliv_RT_Broad_1.md | KDA broad comments from ChatGPT, Grok, Gemini |
| Google_Architectural_Decision_Record_ADR.md | ADR for cross-doc items |

---

# TARGET: DOC72 — Hyper Intelligence Overlay

## CD-A-001: Adopt shared knowledge contracts as payload schemas
- **Source:** Adjudication A1, DOC24 KDA §2
- **Target section:** DOC72 §4 (node payload definitions)
- **Priority:** High
- **Status:** pending
- **Depends on:** DOC24 KDA finalization
- **Obligation:** Replace per-node-type `Payload` type definitions with references to the shared knowledge contracts. The contracts subsume and extend existing fields. `ProcedureKnowledgeContract` becomes the authoritative `ProcedurePayload`. `MemoryDirectiveKnowledgeContract` becomes `MemoryDirectivePayload`. Similarly for domain concepts, goals, obligations, standing procedures.
- **Key change:** Add `annotations: KnowledgeAnnotation[]` field to all knowledge node payloads. Annotations use open vocabulary `annotation_type` string, not enum.
- **Ownership note (from ChatGPT KDA broad review):** The shared contracts are knowledge payload schemas and belong under DOC72 governance (or a shared contracts package governed by DOC72). DOC24 should own rendering tiers, composition, manifests, and delivery logic — NOT the payload schemas themselves. If DOC24 becomes the primary owner of payload contracts, it reopens the DOC72/DOC24 ownership drift.

## CD-A-002: Extend SemanticStep type
- **Source:** Adjudication A1
- **Target section:** DOC72 §4.2
- **Priority:** High
- **Status:** pending
- **Obligation:** Extend `SemanticStep` with: `detailed_instructions` (string, max 3000), `parameters` (structured array of name/value/context), `verification` (structured object with `check`, `method`, `query`), `conditional`, `rationale`, `capability_area`, `source_event_ids` (ephemeral).
- **Critical design decision (from ChatGPT KDA broad review):** Do NOT put `resolved_execution` (tool refs, tool directives, invalidation flags) in the canonical graph payload. This mixes durable semantic knowledge with runtime execution state. `resolved_execution` belongs in a derived execution-strategy cache owned by DOC24/OpenClaw-facing runtime logic. The canonical DOC72 payload stores semantic knowledge only.

## CD-A-003: Add 4 edge types to edge taxonomy
- **Source:** Adjudication A4
- **Target section:** DOC72 §7
- **Priority:** High
- **Status:** pending
- **Obligation:** Add to DOC72 edge taxonomy:
  1. `requires_preceding_procedure` — with `hard_order: boolean`, `rationale: string`, `ordering_context: string` (which composite)
  2. `conflicts_with` — with `conflict_kind: enum` (mutually_exclusive, superseded_ui_path, formatting_conflict, execution_mechanism_conflict)
  3. `platform_variant_of` — with `variant_reason: enum` (platform, app_version, execution_mechanism)
  4. `supersedes_procedure` — with `supersession_reason: enum` (user_correction, app_ui_change, import_replacement), `superseded_at: datetime`

## CD-A-004: Adopt per-node-kind lifecycle table
- **Source:** Adjudication B4
- **Target section:** DOC72 §27 (or new lifecycle policy section)
- **Priority:** High
- **Status:** pending
- **Obligation:** Adopt the merged lifecycle table from adjudication B4:
  - procedure (validated): event-driven decay, no time half-life, dormant after 1095d
  - procedure (candidate/mined): 365d half-life, archive after 180d unreviewed
  - standing_procedure: no time decay, trigger-health freshness
  - memory_directive (preference/constraint): no time decay
  - memory_directive (vocabulary_mapping): 730d review cycle
  - memory_directive (heuristic): 180d half-life, archive after 365d stale
  - domain_concept: 365d half-life
  - goal (explicit): no time decay; goal (inferred): 180d half-life
  - obligation: deadline-relative (infinite before, 90d after)

## CD-A-005: Add cross-doc enum alignment mapping
- **Source:** Adjudication A1 (Codex), Gemini Part 2 A.6
- **Target section:** DOC72 §4 or new appendix
- **Priority:** High
- **Status:** pending
- **Obligation:** Add `DemonstrationWriteCanonicalMap` that maps DOC3 values to DOC72 canonical values: `manual_demonstration` → `"manual"`, standing procedure initial state → `"candidate"`, memory directive lifecycle/maturity separation explicitly documented. Map `user_explicitly_stated` (from memory directives) to `heuristic` assertion class per Gemini fix A.6.

## CD-A-006: Add app_volatility field to ApplicationPayload
- **Source:** Adjudication B1 (Claude Code)
- **Target section:** DOC72 §4.1 ApplicationPayload
- **Priority:** Medium
- **Status:** pending
- **Obligation:** Add `app_volatility?: "stable_native" | "stable_web" | "volatile_web" | "custom_internal"` to `ApplicationPayload`. Default inferred from platform. User-overridable per app entity. Used for freshness evaluation intensity.

## CD-A-007: Add document_archetype to memory_directive.memory_type enum
- **Source:** Adjudication Grok Stress #3
- **Target section:** DOC72 §4 memory_directive payload
- **Priority:** Medium
- **Status:** pending
- **Obligation:** Add `document_archetype` to the `memory_type` enum. Procedures link to archetype directives via `constrained_by` edges. No new node kind — model as memory directive subtype.

## CD-A-008: Add denormalized node_annotations table for DOC8 performance
- **Source:** Gemini Part 2 D.3
- **Target section:** DOC72 database schema
- **Priority:** Medium
- **Status:** pending
- **Obligation:** `CREATE TABLE node_annotations (node_id TEXT, annotation_type TEXT, content TEXT)` maintained via SQLite triggers on the `nodes` table's `payload` JSON. Prevents full JSON table scans for DOC8's nightly annotation pattern detection.

## CD-A-009: Procedure versioning
- **Source:** Adjudication H2 (Claude), Missing item 2
- **Target section:** DOC72 procedure node payload
- **Priority:** Medium
- **Status:** pending
- **Obligation:** Add `version: number` (incremented on each enrichment) and `prior_version_snapshot?: { version, steps, updated_at }` to procedure payload.

## CD-A-010: Confidence model — app update rule
- **Source:** Adjudication A5
- **Target section:** DOC72 confidence/staleness policy
- **Priority:** High
- **Status:** pending
- **Obligation:** App version change sets `staleness_state = "verification_required"` and applies `execution_score_cap = 0.55` until next validated success. Does NOT change α or β. Gemini dissent: Gemini Part 2 A.1 argues against the 0.55 cap, preferring amber warning badge + `confirm_first` safety class while leaving routing confidence untouched. **Resolution: SR-01 accepts Gemini's position — no cap, use amber badge + confirm_first instead.**

## CD-A-010A: EC write-time Zod validation for node payloads
- **Source:** Adjudication SR-32, ChatGPT/Codex/Grok/Claude Code adjudication review #15, Gemini Part 2 D.2
- **Target section:** DOC72 EC write pipeline / DAO layer
- **Priority:** High
- **Status:** pending
- **Obligation:** EC's DAO layer MUST validate JSON payloads against the appropriate shared knowledge contract Zod schema (via `NodePayloadValidatorRegistry`) before executing SQLite INSERT/UPDATE. Invalid payloads are rejected at write time. Each payload carries `schema_version`. Nightly drift audits scan for payloads predating the current schema version. See SR-32 for full schema.

## CD-A-011: Confidence model — correction type split
- **Source:** Adjudication A5 (Codex)
- **Target section:** DOC72 confidence event weights
- **Priority:** High
- **Status:** pending
- **Obligation:** Differentiate: correction_during_review β +0.35 (mild), correction_after_runtime_failure β +1.0 (severe), correction_fix α +0.25.

---

# TARGET: DOC15 — Cognitive Infrastructure Layer

## CD-A-020: Procedure injection card position in CIL hierarchy
- **Source:** Adjudication Grok H29, DOC24 KDA §8.4
- **Target section:** DOC15 §4.2 injection hierarchy
- **Priority:** High
- **Status:** pending
- **Obligation:** Procedure injection cards sit below authority injections and standing orders, at the same level as entity cards. When a procedure is the direct target of the user's request, it elevates to just below authority injections.

## CD-A-021: Rendering tier awareness in CIL
- **Source:** DOC24 KDA §8.4
- **Target section:** DOC15 injection hierarchy
- **Priority:** Medium
- **Status:** pending
- **Obligation:** CIL's injection hierarchy should recognize the rendering tier system. Full-tier cards get higher injection priority than compact-tier cards for the same relevance score.

## CD-A-022: Procedural knowledge sub-budget
- **Source:** Gemini Part 2 C.2, Gemini ADR §3.2
- **Target section:** DOC15 token budgets
- **Priority:** High
- **Status:** pending
- **Obligation:** Create `Procedural_Knowledge_Sub_Budget` capped at 25% of dynamic context window. If the array of retrieved DOC24 procedure cards exceeds this budget, CIL must downgrade their rendering tiers (Full → Standard → Compact) or drop the lowest-relevance cards entirely. Procedure cards MUST NOT be allowed to starve entity cards or matter facts out of the LLM prompt. Total DOC24 rendering output must not exceed ~4,000 tokens. See SR-35 in the adjudication card for the two-pass `allocateRenderingTiers()` algorithm that implements this downgrade behavior.

## CD-A-023: Prefix-stable context caching (Pillar 1)
- **Source:** Gemini Master Synthesis Pillar 1, Gemini ADR §3.1
- **Target section:** DOC15 (new section)
- **Priority:** High — latency critical
- **Status:** pending
- **Obligation:** Restructure context assembly into three strict tiers for API provider prefix caching:
  - `os_immutable` (Tier 1): System rules, standing constraints — globally cached
  - `matter_pinned` (Tier 2): Current active case/project facts — session cached
  - `ephemeral_turn` (Tier 3): User prompt + dynamic DOC24 procedure cards — never cached

```ts
export const ContextTierSchema = z.enum([
  "os_immutable",
  "matter_pinned",
  "ephemeral_turn",
]);

export async function assembleContextWithCaching(
  request: UserRequest,
  dynamicCards: string[],
): Promise<LLMPromptPayload> {
  const osCore = await getOSCoreContext();
  const matterCore = await getActiveMatterContext(request.matter_id);
  const ephemeralContext = dynamicCards.join("\n\n");

  return {
    system_instruction: `${osCore.content}\n\n${matterCore.content}`,
    system_cache_hash: generateHash(osCore.hash + matterCore.hash),
    messages: [
      { role: "system", content: ephemeralContext },
      { role: "user", content: request.text },
    ],
  };
}
```

---

# TARGET: DOC11 — OpenClaw Gateway

## CD-A-030: Remove SKILL.md bridge for graph-backed procedures
- **Source:** Adjudication Problem 4, DOC24 KDA §8.5
- **Target section:** DOC11 bridge/ability exposure
- **Priority:** High
- **Status:** pending
- **Obligation:** The gateway no longer manages SKILL.md files for demonstrated procedures. Abilities are exposed through the DOC24 packet, not through OpenClaw's native skill registry. Graph-backed procedures execute through DOC24 injection + OpenClaw ReAct loop.

## CD-A-031: Emit RuntimeAbilityLoadReceipt
- **Source:** Adjudication Patch 9
- **Target section:** DOC11 receipt emission
- **Priority:** Medium
- **Status:** pending
- **Obligation:** DOC11 must emit a `RuntimeAbilityLoadReceipt` when OpenClaw loads a learned ability. Confirms that the procedure injection card was rendered and included in the packet. Surfaces in Q dispatch detail for proof-of-use.

## CD-A-032: CDP Execution Provider — "God Mode" (Pillar 2)
- **Source:** Gemini Master Synthesis Pillar 2, Gemini ADR §2.1
- **Target section:** DOC11 (new provider section)
- **Priority:** High — major capability addition
- **Status:** pending
- **Obligation:** New provider capable of attaching to Electron `WebContents` via the debugger API. Allows ELNOR to manipulate web app DOMs (Word Web, Outlook Web) directly and invisibly when running inside Q's internal browser.

```ts
export class CDPExecutionProvider {
  private debuggers = new Map<string, Electron.Debugger>();

  attachToTab(webContentsId: number) {
    const wc = webContents.fromId(webContentsId);
    if (!wc) throw new Error("Tab not found");
    wc.debugger.attach('1.3');
    this.debuggers.set(wc.id.toString(), wc.debugger);
  }

  async insertTextAtDomPath(
    webContentsId: string,
    domPath: string,
    text: string,
  ) {
    const dbg = this.debuggers.get(webContentsId);
    const script = `
      const target = document.querySelector('${domPath}');
      if (target) {
        target.focus();
        document.execCommand('insertText', false, \`${text}\`);
        return true;
      }
      return false;
    `;
    return await dbg.sendCommand('Runtime.evaluate', {
      expression: script,
      returnByValue: true,
    });
  }
}
```

## CD-A-033: Execution mechanism preference hierarchy
- **Source:** Gemini Master Synthesis Pillar 2/4, Gemini ADR §2.2
- **Target section:** DOC11 execution routing
- **Priority:** High
- **Status:** pending
- **Obligation:** DOC11 must enforce execution preference order:
  1. `api_direct` — 0ms, background (native APIs like Microsoft Graph)
  2. `cdp_headless` — DOM manipulation, background (Word Web via Q browser)
  3. `applescript` — native OS hooks (usually invisible, can block)
  4. `ax_physical` — steals physical mouse/keyboard (LAST RESORT)

```ts
export const ExecutionMechanismPreferenceSchema = z.enum([
  "api_direct",
  "cdp_headless",
  "applescript",
  "ax_physical",
]);
```

## CD-A-034: Physical execution mutex & ghost UI (Pillar 4)
- **Source:** Gemini Master Synthesis Pillar 4, Gemini ADR §2.3
- **Target section:** DOC11 (new section)
- **Priority:** High
- **Status:** pending
- **Obligation:** For `ax_physical` operations, ELNOR must never steal the cursor silently. Must implement `PhysicalExecutionMutex`:
  1. Render Ghost UI overlay with intent description + 2s countdown
  2. Monitor for user interrupts (mouse move, Esc key) during countdown
  3. If interrupted: abort with `EXECUTION_ABORTED_BY_USER`
  4. If not interrupted: acquire lock, optionally hide hardware cursor
  5. On completion: restore cursor, remove ghost UI

```ts
export class PhysicalExecutionMutex {
  async requestPhysicalControl(intentDescription: string): Promise<boolean> {
    await renderGhostUIOverlay({
      text: `ELNOR: ${intentDescription}`,
      countdown_ms: 2000,
      instruction: "Press Esc or move mouse to abort",
    });
    const userInterrupted = await monitorUserInterrupts(2000);
    if (userInterrupted) {
      removeGhostUI();
      throw new Error("EXECUTION_ABORTED_BY_USER");
    }
    hideCursorFromUser();
    return true;
  }

  releasePhysicalControl() {
    restoreCursorToUser();
    removeGhostUI();
  }
}
```

---

# TARGET: DOC20 — Browser/Notes/Document Viewer

## CD-A-040: WebBrowserContentAdapter for Electron browser
- **Source:** Gemini Master Synthesis Pillar 2, Gemini ADR §1.1
- **Target section:** DOC20 (new subsection under embedded browser §6.19)
- **Priority:** High
- **Status:** pending
- **Obligation:** Q's internal Electron browser must inject a preload script into `WebContents` that monitors DOM text selections and pipes data back to ELNOR's native interface via IPC. When text is highlighted in the Q browser, Q must render the DOC20 Floating Action Menu (Comment / Explain / Rewrite / Draft Here) adjacent to the selection's bounding rect. This menu must behave identically to how it behaves in ELNOR's native Tiptap Notes surface.

```ts
export const BrowserSelectionStateSchema = z.object({
  has_selection: z.boolean(),
  selected_text: z.string().optional(),
  dom_path: z.string().optional(),
  bounding_rect: z.object({
    x: z.number(),
    y: z.number(),
    width: z.number(),
    height: z.number(),
  }).optional(),
  source_url: z.string(),
});

export const WebBrowserContentAdapter = z.object({
  inject_selection_listener: z.boolean().default(true),
  on_selection_change: z.function().args(BrowserSelectionStateSchema),
});
```

## CD-A-041: CDP observation adapter for DOC3
- **Source:** Gemini Master Synthesis Pillar 2B
- **Target section:** DOC20 / DOC3 observation adapters
- **Priority:** Medium
- **Status:** pending
- **Obligation:** When demonstrating inside Q's internal browser, bypass AX and use CDP DOM mutation observation instead. New adapter kind: `cdp_dom_mutation`. Recorded events: DOMNodeInserted, DOMNodeRemoved, InputFieldValueChanged, CSSClassToggled.

```ts
// DOC3: CDP Observation Adapter (Bypasses AX for Q-Browser tabs)
export const CDPObservationAdapterSchema = z.object({
  adapter_kind: z.literal("cdp_dom_mutation"),
  target_web_contents_id: z.number(),
  recorded_events: z.array(z.enum([
    "DOMNodeInserted",
    "DOMNodeRemoved",
    "InputFieldValueChanged",
    "CSSClassToggled",
  ])),
});
```

Add `cdp_dom_mutation` to `DemonstrationAdapterSourceSchema` enum in DOC3. When Q's internal browser is the target, the adapter manager selects this adapter instead of `accessibility_bridge`.

## CD-A-042: DOC24 execution variant resolver for CDP / native duality
- **Source:** Gemini Master Synthesis Pillar 2C
- **Target section:** DOC24 execution strategy resolution (§23.1 area)
- **Priority:** High
- **Status:** pending
- **Obligation:** DOC24's execution strategy resolver must select the correct procedure variant based on the current execution environment. When working inside Q's internal browser, prioritize the web variant and mount CDP tools. When working in a native Mac app, prioritize the Mac variant with AppleScript/AX. This ties into the `platform_variant_of` edge type — the resolver traverses variants to find the best match.

```ts
// apps/ec-service/src/delivery/resolve-execution-variant.ts

export function resolveExecutionVariant(
  procedureVariants: ProcedureNode[],
  currentEnvironment: ActiveEnvironmentState,
): ProcedureNode | null {
  // If working inside Q's Internal Browser, prioritize the Web variant + CDP
  if (currentEnvironment.active_window === "q_internal_browser") {
    const webVariant = procedureVariants.find(
      p => p.payload.environment.platform === "web"
    );
    if (webVariant) {
      mountCDPCapabilityToContext(); // Expose CDP tools to LLM
      return webVariant;
    }
  }

  // If working in native Mac app, prioritize the Mac variant
  if (currentEnvironment.active_window === "mac_native") {
    return procedureVariants.find(
      p => p.payload.environment.platform === "mac"
    ) || null;
  }

  // Fallback: first available variant
  return procedureVariants[0] || null;
}
```

This function runs BEFORE the per-step execution strategy resolution (§23.1). It selects WHICH procedure to use; §23.1 then resolves HOW to execute each step within that procedure. The variant selection uses `platform_variant_of` edges to find alternatives when the primary variant doesn't match the current environment.

---

# TARGET: DOC23 — Task System

## CD-A-050: Level 5 Skill Auto-Compilation (Pillar 3)
- **Source:** Gemini Master Synthesis Pillar 3, Gemini ADR §4
- **Target section:** DOC23 (new section)
- **Priority:** Medium — post-launch capability
- **Status:** pending
- **Obligation:** When a semantic procedure reaches high reliability (execution_count ≥ 20, success_rate ≥ 0.95), a background agent writes deterministic code for it. The compiled script is stored on the procedure node's payload. If the app updates and the code throws, ELNOR seamlessly downgrades to the slow semantic path, completes the user's task, and triggers background repair.

```ts
export const CompiledToolContractSchema = z.object({
  procedure_id: z.string().uuid(),
  native_code: z.string(),
  execution_environment: z.enum(["node", "applescript", "cdp"]),
  health_status: z.enum(["healthy", "failing", "recompiling"]),
  success_rate: z.number().min(0).max(1),
  last_compiled_at: z.string().datetime(),
});

export async function executeWithAutoHealing(
  procedure: ProcedureNode,
  context: ExecutionContext,
) {
  const tool = await db.getCompiledTool(procedure.id);

  // 1. Attempt fast path (deterministic code)
  if (tool && tool.health_status === "healthy") {
    try {
      return await executeNativeCode(tool.native_code, context);
    } catch (error) {
      await db.markToolFailing(tool.id, error);
    }
  }

  // 2. Fallback to slow path (LLM semantic navigation)
  const trace = await executeSemanticStepsWithLLM(
    procedure.payload.steps,
    context,
  );

  // 3. Background repair
  if (trace.status === "success") {
    dispatchBackgroundJob("recompile_tool", {
      procedure_id: procedure.id,
      failed_code: tool?.native_code,
      new_successful_trace: trace,
    });
  }

  return trace;
}
```

---

# TARGET: DOC8 — Self-Learning, Prediction, Regression, Friction

## CD-A-060: Annotation pattern detection nightly job
- **Source:** DOC24 KDA §5.2, Adjudication H3
- **Target section:** DOC8 (new section)
- **Priority:** Medium
- **Status:** pending
- **Obligation:** DOC8 gains a nightly job that scans annotations across all nodes (using the denormalized `node_annotations` table from CD-A-008). When an annotation type appears across 5+ nodes with parent node confidence ≥ 0.70 (Gemini gate from Part 2 D.4), DOC8 proposes: (a) extraction hints for the interpretation prompt, (b) rendering specializations for DOC24. Promotions are proposal-only, requiring canary success before global use (ChatGPT KDA review governance tightening). Promoted types get rollback capability.

## CD-A-061: Extraction hint proposal pipeline
- **Source:** DOC24 KDA §5.4
- **Target section:** DOC8 proposal/canary pipeline
- **Priority:** Medium
- **Status:** pending
- **Obligation:** When DOC8 promotes an annotation type, it proposes an extraction hint — an addition to the interpretation prompt that tells the LLM to look for and structure this type of annotation. Stored at `ELNOR_MEMORY/system/knowledge/extraction_hints.json`. Loaded by the interpretation prompt builder. Includes `last_used` timestamp; DOC8 auto-demotes hints not triggered in 60 days (Gemini KDA broad review "use it or lose it" decay).

## CD-A-062: Procedure co-occurrence tracking
- **Source:** Adjudication H3 (Claude Code Improvement 2)
- **Target section:** DOC8 pattern detection
- **Priority:** Low — Phase 3
- **Status:** pending
- **Obligation:** DOC8 tracks procedure co-occurrence in execution traces. When procedure A has been followed by procedure B in >70% of traces (minimum 5 traces), DOC8 emits `pattern.procedure_co_occurrence` signal. Feeds DOC24 routing as a "frequently followed by" suggestion.

---

# TARGET: DOC1 — Memory Resilience

## CD-A-070: Validate maturity bypass for demonstration-sourced directives
- **Source:** Adjudication A1 (Codex), Gemini Part 2 A.6
- **Target section:** DOC1 maturity governance
- **Priority:** High
- **Status:** pending
- **Obligation:** Memory directives from demonstrations enter at `observation` maturity by default. Maturity bypass to `active` requires: user explicitly confirmed + confidence ≥ 0.85 + durable_fact assertion class. Per Gemini: `user_explicitly_stated` source maps to `heuristic` assertion class, NOT `durable_fact`. User-stated preferences can change; they are not durable facts. Standard execution validation required for bypass.

---

# TARGET: DOC21/DOC22 — Master UI Spec / Page Inventory

## CD-A-080: Register new Q components from DOC3 R11.3
- **Source:** Adjudication Patch 12
- **Target section:** DOC21 component registry, DOC22 page inventory
- **Priority:** Medium
- **Status:** pending
- **Obligation:** Register: `LearnCaptureOverlay` (sidebar panel + menu bar status item), `QuickPromoteDrawer`, `AbilityProofDrawer`, `BundleReviewPanel` (summary + detail views), `DemonstrationCapturePanel`. Include loading/empty/degraded/error states per component. Register in DOC20 §6.18.2 content registry.

## CD-A-081: Overlay behavioral rules
- **Source:** Adjudication D5, ChatGPT D5
- **Target section:** DOC21 component specs
- **Priority:** Medium
- **Status:** pending
- **Obligation:** Menu bar status item for observation banner. Q sidebar panel (320px) for full capture controls. Auto-collapse after 3s no hover. Never occlude target-app center. Hotkeys: ⌘⌥L expand/collapse, ⌘⌥P pause/resume, ⌘⌥S stop. TCC missing or adapter degraded: compact amber banner, no fake healthy badge.

---

# TARGET: DOC10 — Unified Engagement Orchestration

## CD-A-090: Learned ability selection receipt
- **Source:** Adjudication Patch 9
- **Target section:** DOC10 route planner receipts
- **Priority:** Medium
- **Status:** pending
- **Obligation:** DOC10 must emit a `LearnedAbilitySelectionReceipt` when it chooses a learned ability during routing. Includes ability_id, install_lane, matched_by, matched_terms. Paired with DOC11's `RuntimeAbilityLoadReceipt` for complete proof chain.

---

# TARGET: Knowledge Store Integration Map

## CD-A-095: Update DOC3 section
- **Source:** Adjudication Problem 4
- **Target section:** Knowledge Store Integration Map DOC3 section
- **Priority:** Low
- **Status:** pending
- **Obligation:** DOC3 store entry for "Installed SKILL.md files" changes from "Layer 2 projection" to "Layer 2 export-only, not runtime dependency."

---

# INTERNAL AMENDMENT MATRICES — Must update during spec revisions

## CD-A-096: Update DOC24 §22 Cross-Doc Amendment Matrix
- **Source:** This entire work cycle
- **Target section:** DOC24 §22
- **Priority:** High — part of DOC24 KDA revision (Step 3)
- **Status:** pending
- **Obligation:** DOC24 §22 must be updated to reflect all new cross-doc obligations generated by the KDA additions: shared contracts → DOC72 payload adoption, rendering pipeline → DOC15 tier awareness and sub-budget, neuroplasticity → DOC8 annotation detection job, procedure injection → DOC11 bridge removal and receipt emission, inspectability → DOC21/22 component registration. Every item in CD-A that has a DOC24 origin must be reflected in §22.

## CD-A-097: Update DOC3 Companion Delta Plan to R9.3+
- **Source:** DOC3 R11.3 adjudication
- **Target section:** DOC3 Companion Doc Delta Plan
- **Priority:** High — part of DOC3 R11.3 revision (Step 4)
- **Status:** pending
- **Obligation:** DOC3 Companion Delta Plan R9.2 must be updated to reflect all new route families, schemas, UI contracts, and cross-doc obligations from R11.3 (Quick Promote route, bundle-edits route, undo-promote route, capture-capability route, observation-evidence route, install-sagas route, ability-proof route, feature-support route).

---

# FUTURE-STATE ITEMS (from KDA broad review + improvements)

These are high-leverage architectural upgrades proposed by reviewers. Not day-one obligations. Tracked here so they don't get lost.

## CD-A-F01: Compiled delivery IR for hot-path performance
- **Source:** ChatGPT KDA broad review upgrade 1
- **Priority:** High — performance critical
- **Status:** deferred to post-launch
- **Description:** Don't render from raw graph payloads on the hot path. Add a background compiler that produces precomputed delivery fragments per node: compact/standard/full text, per-client render variants, provenance snippets. Hot-path packet assembly is mostly selecting and stitching prebuilt fragments. Satisfies 50ms prompt-time constraint.

## CD-A-F02: Contract quality gate before injection eligibility
- **Source:** ChatGPT KDA broad review upgrade 5
- **Priority:** Medium
- **Status:** deferred
- **Description:** Every extracted shared contract scored for completeness, provenance sufficiency, contradiction state, scope confidence, freshness risk, renderability. Structurally weak candidates stored as low-confidence but not graduated to hot-path injection until quality gate cleared.

## CD-A-F03: Rendering variant A/B testing (DOC8-driven)
- **Source:** Grok KDA broad review improvement 1
- **Priority:** Low — Phase 3
- **Status:** deferred
- **Description:** `RenderingVariant` table in DOC72. Each variant = JSON template + weight. DOC8 nightly reinforcement: for every injection, record whether LLM used the card. Variants with higher usage/correctness get higher weight. Evolves better explanations over time.

## CD-A-F04: Vector-augmented annotation clustering
- **Source:** Grok KDA broad review improvement 2
- **Priority:** Low — Phase 3
- **Status:** deferred
- **Description:** When DOC8 detects a new annotation_type, store 384-dim embedding of first 10 examples. At render time, unknown annotation types fuzzy-match to nearest promoted specialization instead of falling back to generic rendering.

## CD-A-F05: Field-level provenance + correction tracing
- **Source:** Grok KDA broad review improvement 3
- **Priority:** Medium
- **Status:** deferred
- **Description:** Extend every contract field with optional `provenance` object: source_event_id, interpretation_model, interpretation_timestamp, last_corrected_by, correction_reason. Perfect inspectability and lets DOC8 learn which models produce highest-quality contracts.

## CD-A-F06: Counterfactual packet evaluator
- **Source:** ChatGPT KDA broad review upgrade 7
- **Priority:** Low — beyond cutting edge
- **Status:** deferred
- **Description:** For a slice of turns, build shadow packets with different compositions. Compare downstream utility signals. Learn not just "what knowledge exists" but "what delivery shape actually helps this model/user combination."

## CD-A-F07: Semantic sub-card trimming
- **Source:** Gemini KDA broad review upgrade A
- **Priority:** Medium
- **Status:** deferred
- **Description:** Instead of downgrading entire cards, use local embedding model to compare user's query against individual step intents. Inject only the relevant steps from a long procedure, keeping full fidelity on the needed step at compact token cost.

## CD-A-F08: AST-based prompt assembly
- **Source:** Gemini KDA broad review upgrade B
- **Priority:** Low — architectural
- **Status:** deferred
- **Description:** Treat LLM prompt as Abstract Syntax Tree. Renderers output JSON nodes instead of strings. DOC15 can programmatically prune, reorder, or compress nodes before compiling to final text. Prevents accidental truncation of critical constraints.

## CD-A-F09: Pre-flight UI state validation
- **Source:** Gemini KDA broad review upgrade D
- **Priority:** Medium
- **Status:** deferred
- **Description:** Before rendering a procedure card for a local client, use OpenClaw to check active app state against procedure's preconditions. If preconditions not met, prepend injection with guidance to navigate there first.

## CD-A-F10: Self-compiling procedure graphs
- **Source:** Grok KDA broad review improvement 5
- **Priority:** Low — Phase 3
- **Status:** deferred
- **Description:** When DOC8 detects a composite being used frequently, propose a synthetic merged procedure node. User gets "merge these N steps into one reusable skill?" prompt. Evolves from "list of skills" to "personal programming language."

---

# ARCHITECTURAL EVOLUTION IDEAS (from ChatGPT adjudication review extended analysis)

These are significant architectural proposals that go beyond corrections. They represent the next evolution of the system. Not v1 scope but should be tracked for future planning.

## CD-A-F20: Three-part node payload architecture
- **Source:** ChatGPT adjudication review (lines 880-890)
- **Priority:** High — architectural evolution
- **Status:** deferred
- **Description:** Replace single-blob payload with three-part structure: `semantic_core` (canonical durable truth for dedup/routing/governance), `delivery_projection` (LLM-friendly phrasing, tiered summaries, annotations specialized for injection), `execution_cache` (resolved_execution, verification strategies, remote-rendering compatibility, invalidation state). Only `semantic_core` is canonical and confidence-bearing. `delivery_projection` and `execution_cache` are rebuildable and invalidatable. Keeps DOC72 truth layer smaller and cleaner. NOTE: SR-19 partially implements this by moving resolved_execution to a derived cache, but this proposal goes further by also separating delivery prose from semantic truth.

## CD-A-F21: Shadow ability lane (ephemeral pre-promotion)
- **Source:** ChatGPT adjudication review (lines 897-901)
- **Priority:** Medium — UX evolution
- **Status:** deferred
- **Description:** After a stop boundary, ELNOR creates a session-scoped `ShadowAbility` or `ProcedureOverlay` usable immediately in the same app/context, without pretending it's durable knowledge. If it works and user likes it, promoted to graph. Separates "give me help now" from "make this durable." Quick Promote currently does both jobs — this separates them. Would make teach-by-example feel magical instead of bureaucratic.

## CD-A-F22: OperatingStateSnapshot — single "what's live" object
- **Source:** ChatGPT adjudication review (lines 893-897)
- **Priority:** Medium — system coherence
- **Status:** deferred
- **Description:** Top-level object owned by DOC24, consumed by DOC10/DOC15/DOC11/Q. Includes: current focus/work context, focused app/artifact, active obligations, recent receipts, mounted capabilities, blocked actions, active cautions, candidate entities, currently routable learned procedures. Becomes the main "Why?" inspector and the main seed for runtime packet assembly. Represents not just what ELNOR knows and can do, but what it believes is currently live.

## CD-A-F23: Multi-dimensional confidence vector
- **Source:** ChatGPT adjudication review (lines 903-911)
- **Priority:** Medium — trust evolution
- **Status:** deferred
- **Description:** Replace single scalar confidence with `AbilityConfidenceVectorSchema`: `understanding_confidence` (did Elnor get the teaching right), `routing_confidence` (can it find it later), `execution_confidence` (can it do it right now), `freshness_confidence` (is it still valid), `governance_confidence` (is it allowed to apply automatically). Quick Promote keys off understanding + capture quality. Lookup keys off routing + freshness. Auto-apply requires execution + governance. Gives Q truthful badges and avoids misleading green states.

## CD-A-F24: Constraint resolution engine
- **Source:** ChatGPT adjudication review (lines 912-915)
- **Priority:** Medium — coherence evolution
- **Status:** deferred
- **Description:** Pre-render `ConstraintResolutionPlan` that computes effective rules for this dispatch before any injection card is rendered. Procedure cards show only effective, dispatch-scoped rules; raw conflicting candidates belong in the inspector. Centralizes resolution of transient instructions, authority memory, memory directives, procedure constraints, and app/runtime restrictions.

## CD-A-F25: Promotion ladder — explicit capability maturity model
- **Source:** ChatGPT adjudication review (lines 926-928)
- **Priority:** Low — long-term evolution
- **Status:** deferred
- **Description:** Shadow overlay → graph-backed learned procedure → routable learned ability → deterministic operator macro / tool policy → standing automation / DOC23 task. Makes explicit the growth path from "I can help with this" to "I can reliably do this for you." DOC72's compounding philosophy already points here.

---

# NOTE: Stray DOC24 R2.4 Second-Pass Addendum

The uploaded review file (`DOC3_R11_3_ADJUDICATION_AND_DOC24_DELIVERY_RED_TEAM_REVIEWS_FULL.md`) contains a "DOC24 R2.4 Adjudication Card — Second-Pass Addendum" starting at approximately line 2095, referencing ADJ-04, ADJ-06, ADJ-31, ADJ-45, ADJ-82, ADJ-83, ADJ-85, etc. This belongs to a SEPARATE adjudication cycle (DOC24 R2.4 red team) and is NOT part of the DOC3 R11.3 work. Those items should be tracked and resolved in the DOC24 R2.4 adjudication context, not here.

---

# APPENDIX: ELNOR Electron Pivot Manifest (Verbatim)

**Source:** `Google_Architectural_Decision_Record_ADR.md` (Gemini)
**Included verbatim to prevent editorial loss. CD-A items 022, 023, 032, 033, 034, 040, 041, 042, 050 serve as the structured tracking index into this content.**

---

# ELNOR_ELECTRON_PIVOT_MANIFEST.md
**Status:** Architecture Decision Record (ADR) / Cross-Doc Integration Backlog
**Date:** April 2026
**Purpose:** This document captures the architectural additions required to support the Electron/CDP "God Mode" pivot, Context Caching, and Level 5 Skill Auto-Compilation. Because active drafting is focused on DOC3 and DOC24, these items—which belong in DOC11, DOC15, DOC20, and DOC23—are parked here as authoritative specifications for the upcoming cross-document integration pass.

---

## 1. TARGET: DOC20 (UI & BROWSER SURFACES)
**Objective:** Upgrade Q's UI specifications to account for the internal Electron browser, allowing ELNOR to read text selections inside web apps (like Word Web) and render native ELNOR UI overlays directly on top of the web content.

### 1.1 The WebBrowserContentAdapter
Q's internal Electron browser must inject a preload script into its `WebContents`. This script acts as a bridge, monitoring the DOM for user text selections and piping that data back to ELNOR's native interface via IPC.

```typescript
// packages/contracts/src/q-ui/browser-adapter-schema.ts
import { z } from "zod";

export const BrowserSelectionStateSchema = z.object({
  has_selection: z.boolean(),
  selected_text: z.string().optional(),
  dom_path: z.string().optional(), // Critical for CDP injection/editing later (e.g., "body > div#editor > p:nth-child(4)")
  bounding_rect: z.object({ 
    x: z.number(), 
    y: z.number(), 
    width: z.number(), 
    height: z.number() 
  }).optional(),
  source_url: z.string(),
});

export const WebBrowserContentAdapter = z.object({
  inject_selection_listener: z.boolean().default(true),
  on_selection_change: z.function().args(BrowserSelectionStateSchema),
});
```

### 1.2 UX Contract for Web Selection

- **Rule:** "When text is highlighted inside the Q Browser (e.g., in Word Web or Outlook Web), Q MUST render the DOC20 Floating Action Menu (Comment / Explain / Rewrite / Draft Here) adjacent to the `bounding_rect`. This menu must behave identically to how it behaves in ELNOR's native Tiptap Notes surface."

------

## 2. TARGET: DOC11 (OPENCLAW GATEWAY & PROVIDERS)

**Objective:** Expand OpenClaw's capabilities to include headless Chrome DevTools Protocol (CDP) execution and mandate strict safety locks for physical mouse/keyboard takeovers.

### 2.1 CDP Execution Provider ("God Mode")

OpenClaw requires a new provider capable of attaching to Electron `WebContents` via the debugger API. This allows ELNOR to manipulate web app DOMs instantly and invisibly.

```typescript
// apps/openclaw-mac-companion/src/providers/cdp-provider.ts
export class CDPExecutionProvider {
  private debuggers = new Map<string, Electron.Debugger>();

  attachToTab(webContentsId: number) {
    const wc = webContents.fromId(webContentsId);
    if (!wc) throw new Error("Tab not found");
    
    wc.debugger.attach('1.3'); // Attach CDP version 1.3
    this.debuggers.set(wc.id.toString(), wc.debugger);
  }

  async insertTextAtDomPath(webContentsId: string, domPath: string, text: string) {
    const dbg = this.debuggers.get(webContentsId);
    
    // Execute JS directly in the page context to modify the DOM invisibly
    const script = `
      const target = document.querySelector('${domPath}');
      if (target) { 
        target.focus(); 
        document.execCommand('insertText', false, \`${text}\`); 
        return true; 
      }
      return false;
    `;
    return await dbg.sendCommand('Runtime.evaluate', { expression: script, returnByValue: true });
  }
}
```

### 2.2 Execution Mechanism Preference Hierarchy

DOC11 must enforce an execution preference order to maximize speed and minimize user disruption.

```typescript
// packages/contracts/src/execution/mechanism-preference-schema.ts
export const ExecutionMechanismPreferenceSchema = z.enum([
  "api_direct",     // Rank 1: 0ms, background (e.g., native Microsoft Graph APIs)
  "cdp_headless",   // Rank 2: DOM manipulation, background (e.g., Word Web via Q)
  "applescript",    // Rank 3: Native OS hooks (usually invisible, but can block)
  "ax_physical"     // Rank 4: Steals physical mouse/keyboard (Last resort)
]);
```

### 2.3 Physical Execution Mutex & Ghost UI

For `ax_physical` operations, ELNOR must never steal the cursor silently. It must implement a `PhysicalExecutionMutex`.

```typescript
// apps/openclaw-mac-companion/src/hid/execution-mutex.ts
export class PhysicalExecutionMutex {
  async requestPhysicalControl(intentDescription: string): Promise<boolean> {
    // 1. Render Ghost UI Overlay
    await renderGhostUIOverlay({
      text: `ELNOR: ${intentDescription}`,
      countdown_ms: 2000, 
      instruction: "Press Esc or move mouse to abort"
    });

    // 2. Monitor for interrupts during countdown
    const userInterrupted = await monitorUserInterrupts(2000); // Listens for HID events
    if (userInterrupted) {
      removeGhostUI();
      throw new Error("EXECUTION_ABORTED_BY_USER");
    }

    // 3. Lock acquired
    hideCursorFromUser(); // Optional: hides hardware cursor during automation
    return true; 
  }

  releasePhysicalControl() {
    restoreCursorToUser();
    removeGhostUI();
  }
}
```

------

## 3. TARGET: DOC15 (COGNITIVE INFRASTRUCTURE LAYER)

**Objective:** Restructure context assembly to support prefix caching and strict token budgeting for the new procedural knowledge injections.

### 3.1 Prefix-Stable Context Caching

To achieve ~0ms latency on repeated turns, CIL must assemble the prompt into three strict tiers so the API provider can cache the frozen headers.

```typescript
// packages/contracts/src/cil/context-caching-schema.ts
export const ContextTierSchema = z.enum([
  "os_immutable",       // Tier 1: System rules, standing constraints (Globally Cached)
  "matter_pinned",      // Tier 2: Current active case/project facts (Session Cached)
  "ephemeral_turn",     // Tier 3: User prompt + dynamic DOC24 procedure cards (Uncached)
]);
```

### 3.2 Procedural Knowledge Sub-Budget

- **Rule:** "CIL MUST create a `Procedural_Knowledge_Sub_Budget` capped at **25%** of the dynamic context window. If the array of retrieved DOC24 procedure cards exceeds this budget, CIL must downgrade their rendering tiers (Full -> Standard -> Compact) or drop the lowest-relevance cards entirely. Procedure cards MUST NOT be allowed to starve `entity` cards or matter facts out of the LLM prompt."

------

## 4. TARGET: DOC23 (TASK SYSTEM & AUTO-COMPILATION)

**Objective:** Define the lifecycle engine that promotes semantic procedures (LLM-driven) into Level 5 compiled tools (Code-driven), including the self-healing loop for when apps update.

### 4.1 The Level 5 Skill Auto-Compiler

When a procedure reaches a high success threshold, a background OpenClaw agent writes deterministic code for it.

- **Compilation Trigger:** `execution_count >= 20` AND `success_rate >= 0.95`.
- **Storage Contract:** The compiled script is stored directly inside the `procedure` node's payload.

```typescript
// packages/contracts/src/skills/compiled-tool-contract.ts
export const CompiledToolContractSchema = z.object({
  procedure_id: z.string().uuid(),
  native_code: z.string(), // Auto-generated TypeScript/AppleScript/JavaScript
  execution_environment: z.enum(["node", "applescript", "cdp"]),
  health_status: z.enum(["healthy", "failing", "recompiling"]),
  success_rate: z.number().min(0).max(1),
  last_compiled_at: z.string().datetime(),
});
```

### 4.2 The Tool Healer (Self-Healing Loop)

If an app's UI updates and the `native_code` throws an exception, ELNOR must seamlessly downgrade to the slow semantic path, complete the user's task, and trigger a background repair.

```typescript
// apps/ec-service/src/execution/tool-healer.ts
export async function executeWithAutoHealing(procedure: ProcedureNode, context: ExecutionContext) {
  const tool = await db.getCompiledTool(procedure.id);

  // 1. Attempt Fast Path (Deterministic Code)
  if (tool && tool.health_status === "healthy") {
    try {
      return await executeNativeCode(tool.native_code, context); 
    } catch (error) {
      await db.markToolFailing(tool.id, error); // Tool broke (e.g., UI changed)
      console.log("Native tool failed. Downgrading to semantic UI navigation...");
    }
  }

  // 2. Fallback to Slow Path (LLM Semantic Navigation)
  const trace = await executeSemanticStepsWithLLM(procedure.payload.steps, context);

  // 3. Background Repair
  if (trace.status === "success") {
    // If the semantic path succeeded, use that trace to rewrite the broken code
    dispatchBackgroundJob("recompile_tool", { 
      procedure_id: procedure.id, 
      failed_code: tool?.native_code,
      new_successful_trace: trace 
    });
  }

  return trace;
}
```