# Shifu coding-harness connector

`@useshifu/coding-harness` connects Codex, Claude Code, OpenCode, or Cursor to Shifu. Local capture requires reviewed history/project scope; one optional input folder can be enabled separately. Session sync includes coding work and non-coding work chats: research, planning, writing, marketing, career development, leadership, and learning discussions. It prepares version-five context from bounded original human messages and completed assistant reports through the matching native CLI, then sends only validated redacted activity to Shifu. Folder files are sent over TLS for server-side parsing, sanitization, and user-attribution checks; the local runner does not redact file contents.

## Connect

Use the bundled local wizard for capture setup:

```sh
npx --yes @useshifu/coding-harness onboard --harness codex
```

Choose `codex`, `claude_code`, `opencode` or `cursor` on the local device. The wizard reuses saved settings and credentials, collects history (15 days recommended, 30, custom or zero), selected projects or an explicit all-project choice, optional files/folder, schedule and independent feedback preferences. Review shows metadata counts and configured-model usage before Start grants scope. Selected source uses the coding tool’s configured provider; Shifu receives redacted work records. Existing retained context can be retrieved independently of local capture.

Files are off until enabled for the reviewed canonical directory. Once enabled, `.txt`, `.md`, `.rtf` and `.docx` files up to 20 MB upload as provided for server-side parsing and sanitization, separately from manual session approval. The folder scanner ignores its `README.md`, subfolders and symlinks; images and screenshots are unsupported. Changing the folder disables file approval until reviewed again. Named transcripts use the Shifu Profile display name for attribution; unsupported ownership does not become a personal claim.

Start authorizes the reviewed history/projects/file scope and freezes the initial backfill manifest. Zero days skips historical work. The recommended future policy is hourly automatic session sync, with manual approval available. Closing the wizard does not revoke an accepted Start; pause when processing should stop. Missing or ambiguous legacy grants require wizard review, preserving checkpoints and frozen retry bodies.

`connect --harness <harness>` is the lower-level credential/preferences command. It verifies the tool-specific key entered through the local wizard or terminal; do not paste it in chat. A new connection does not activate capture or a schedule. Missing noninteractive history does not silently become 15 days. An interval, approval mode, history preference or `syncPolicy.onboardingComplete` is not a capture grant. Key or endpoint replacement requires new review before capture, with old state quarantined rather than silently replayed.

MCP-only `mcp-setup --harness <harness>` connects existing Shifu context tools. A fresh connection leaves local capture disabled, and history flags cannot expand capture. Existing approved sync settings are preserved. Work capture requires the wizard’s own reviewed Start.

To pause or resume the existing grant:

```sh
npx --yes @useshifu/coding-harness pause --harness codex
npx --yes @useshifu/coding-harness resume --harness codex
```

Pause blocks new preparation, uploads and backfill and cancels active local work. Accepted requests and checkpoints remain. `config update --schedule off` also pauses capture. Resume does not grant missing scope or broaden projects/history. Explicit prepare, recover and force requests also remain within the grant; use the wizard to expand it.

Change interval, manual/automatic session approval or independent feedback with requested `config update` flags. A changed history preference cannot widen the authorized cutoff. Feedback changes update installed guidance without altering capture; reload the coding tool or start a new chat afterwards. Historical retrieval remains available even when proactive feedback is off.

`purge-local --harness <harness>` previews Shifu-managed caches, captured journals, dictionaries and outboxes while capture is paused. Only `--approved` after review removes those artifacts. It preserves original coding-tool history, input documents and hosted work. Purge is not part of ordinary setup or an upgrade.

`disconnect --harness <harness>` removes the local connection and configured schedule; revoke the key in Shifu if it should no longer be usable. Disconnect and local purge are separate from hosted deletion requests.

## Operate

Current scope and pause rules above apply to all commands. Release notes below describe earlier changes; they do not grant upload authority.

Version `0.3.32` preserves failed and pending source status during preparation, distinguishes people by their original source occurrences, and keeps the two-attempt review limit across metadata changes. Existing queues, V5 payloads and receipts remain compatible.

Version `0.3.30` adds separately versioned episode and entity continuity without changing the V5 sync body or older queued payloads. Preparation uses bounded prior-turn references, source coverage checks and durable two-attempt review holds. Base acceptance and attachment completion have separate status. See [V5 continuity](#continuity-beside-version-five) below for privacy, recovery and mixed-version operation.

Version `0.3.29` verifies native v5 sync across Codex, Claude Code, OpenCode 1 and OpenCode 2. Codex now loads a private allowlisted configuration and home instead of an ignored profile, with executable tools disabled. OpenCode 2 uses its standalone CLI, native provider/agent configuration, typed session database and isolated account storage. Native CI tests exercise original-source discovery, extraction, redaction, frozen retries and matching receipt checkpoints against local synthetic endpoints, without live credentials or paid models.

Version `0.3.28` adds one isolated, pre-queue correction attempt for invalid v5 preparation, with field-specific reference and privacy diagnostics. Both attempts share the 180-second deadline. Privacy rules, trusted source binding, accepted checkpoints and exact queued retries remain unchanged.

Version `0.3.27` adds a concrete topic-and-relationship retrieval playbook. Execution is the default for project work, first-person decision history and technical feedback; Growth requires explicit personal-development intent. The caller omits optional lexical query filters by default, accounts for Pi's internal expansion attempts, and preserves source authorship separately from contribution credit. Server retrieval reserves candidates for reformulation, ranks Execution without attribution metadata, and reports observed source groups without presenting repeated copies as independent confirmations.


Version `0.3.26` adds branded onboarding, independent growth-feedback and decision-alignment preferences, and an initial-history choice. `sessions --initial-history` uses the saved selection date when a backfill resumes instead of shifting a rolling days window. Publish this package version before deploying app setup prompts that reference it.

Version `0.3.25` moves scheduled and pending preparation to the source-grounded v5 path across Codex, Claude Code and OpenCode. It caches each redacted payload before upload, preserves exact retries and queued legacy payloads, and leaves unfinished or failed ranges pending. The matching native CLI must support the required isolation flags; OpenCode 1 requires 1.18.30 or newer. OpenCode 2 requires harness 0.3.29 or newer and `sqlite3` for local source/account access.

Version `0.3.23` introduced the context guidance below. It retrieves context at substantive task starts and new topics, tracks current topic coverage, and surfaces Shifu-attributed support or discrepancies alongside proposals and actions. Current user instructions take precedence over historical context; adopted choices and rationale remain available to existing session sync.

Version `0.3.21` adds meaningful decision and reflection checkpoints to the managed context guidance: historical reinforcement, discrepancies and goal-aware coaching, with current-context reuse and optional clarification. Existing managed blocks refresh on upgrade.

Version `0.3.20` expands the shared extractor to capture recognized work discussions and explanatory final answers without requiring code changes or completed-action wording. Discussion evidence uses neutral wording and excludes measured outcomes from explanations; proposals remain separate from adopted decisions. Automatic extraction uses controlled topics and details, so unfamiliar subjects may still need semantic review through the sync skill. Previously checkpointed chats are not replayed by an upgrade; an explicit force sync can re-review missed content.

Version `0.3.11` adds rolling days-based windows and explicit force replacement of reviewed segments. Force replacement requires backend migration 049 and the matching connector endpoints to be deployed first.

Version `0.3.12` makes force sync independent of local and server checkpoints, creates missing work, and protects automatic retries from overwriting a newer force sync. Deploy backend migrations 049 and 050 before using it.

Version `0.3.13` requires reviewed evidence for force sync. Empty replacements fail before changing existing work, and the harness instructions require semantic review of final notes instead of the scheduled keyword projection.

Historical version `0.3.14` introduced first-connection backfill. Current capture instead requires the wizard’s history/project/file preview and explicit Start; 15 days is only a recommended choice. Interrupted initial backfills resume from accepted checkpoints; upgrades and key replacement alone do not trigger another backfill. The saved approval policy and schedule stay unchanged.

```sh
npx --yes @useshifu/coding-harness status --harness codex
npx --yes @useshifu/coding-harness sessions --harness codex --hours 24
npx --yes @useshifu/coding-harness review --harness codex --session-ref opaque-session-id
npx --yes @useshifu/coding-harness pending --harness codex
npx --yes @useshifu/coding-harness approve --harness codex
npx --yes @useshifu/coding-harness sync-files --harness codex
```

To select by session count instead of a time window, run `sessions --harness codex --count 5`. It selects the five most recently updated eligible sessions, newest first, without an hours cutoff. Current and setup sessions are excluded. `selectedSessionRefs` fixes that selection; `sessions` contains pending segments and `skippedSessions` reports already-synced sessions. Skipped sessions are not replaced with older ones. Inspect each pending range with `review-source --harness codex --session-ref <sessionRef> --from-turn <fromTurn> --to-turn <toTurn>`, then prepare its redacted version-five payload in the current native harness. After an accepted segment, request the next with `sessions --harness codex --session-ref <sessionRef> --all` until that selected session is exhausted. Keep the original references instead of selecting another five.

Time-window selection accepts any positive whole number of days or hours. `sessions --harness codex --days 3` uses the same window as `--hours 72`; pass the same window to `review`. `--days 7` also works. Mixed, missing, invalid, or unsupported options fail explicitly. A recently active session with older unsynced turns appears in `blockedSessions`: sync cannot skip those turns. Use `--session-ref <sessionRef> --all` only within the existing approved history/projects; wider prefixes require wizard re-review. Backfill stays chronological in segments of at most 12 turns.

Manual session sync runs immediately, independently of the hourly schedule. If a segment fails, report it as failed/pending; a checkpoint advances only after a matching server receipt. Report completed, already-synced, and failed session counts separately.

To upgrade an existing installation, run `npx --yes @useshifu/coding-harness@latest install --harness codex` (or `claude_code` / `opencode`). It replaces the local runner and harness instruction while preserving the connection, checkpoints, and schedule. Reconnecting is unnecessary. `status` includes `runnerVersion` so you can verify the installed version.

Scheduled runs and `pending` prepare version-five payloads using the matching Codex, Claude Code, or OpenCode CLI and its existing account and model configuration. The selected raw source is processed by that native model provider in an isolated temporary invocation; it is never uploaded to Shifu or appended to the original conversation. Tools, project instructions, plugins, and MCP access are disabled during preparation, and temporary preparation files are removed afterwards. No separate extraction API key is required. Unattended native preparation currently requires macOS or Linux.

Native sync gates pin Codex 0.163.0, Claude Code 2.1.301, OpenCode 1.18.30 and OpenCode 2.0.31. Other releases are checked for the required capabilities rather than assumed compatible. Codex file-backed authentication is shared without copying its session history; an explicit keyring-only store remains pending with an authentication remedy because its keyring namespace is tied to the original home. OpenCode 2 copies only native credentials into private temporary storage and conditionally preserves rotated OAuth values without overwriting concurrent account changes. No accepted history is replayed by this upgrade.

OpenCode 2 account finalization has a separate 10-second recovery budget after model preparation ends. If native account write-back fails, an owner-only credential recovery artifact is retained outside session discovery and replayed safely before the next preparation; source storage is removed. If credentials cannot be read or the recovery artifact cannot be saved, private preparation storage is retained locally for assisted account recovery instead of deleting potentially rotated credentials. Neither recovery path uploads source or credentials. Legacy OAuth accounts must first be migrated by opening OpenCode 2 normally; reconnecting Shifu is unnecessary.

Each preparation invocation handles at most four ranges, each covering up to 12 original turns, 128 source messages, and 256 KiB. Oversized automatic ranges are shortened before preparation rather than silently truncating text. A native preparation has a 180-second deadline. Unfinished trailing turns stay pending regardless of age; partial assistant text and intermediate tool calls do not count as final reports. An unsupported native CLI, missing required isolation flags, unavailable account, timeout, or invalid model output leaves the range pending. Update or repair the matching CLI and retry; the runner does not fall back to the old keyword projection.

Codex extraction normally inherits the native model and reasoning settings. `config update --harness codex --background-reasoning medium` saves a Medium reasoning override for isolated background extraction only; it leaves Codex chat configuration, the history cutoff, sync schedule and frozen payloads unchanged. The flag also accepts `high`. Both overrides use a ten-minute preparation limit inside a fifteen-minute run budget; changing reasoning does not shorten that allowance. Inherited settings retain their three-minute preparation and five-minute run limits. Use `--background-reasoning inherit` to remove the override. Safe `status` output reports the saved choice. A longer allowance does not guarantee completion.

Before queueing, invalid structured preparation receives at most one isolated correction attempt using only privacy-safe validator diagnostics and the same source packet. Both attempts share the invocation deadline. If too little time remains for a useful correction, safe guidance is saved and the remaining attempt resumes in a later bounded invocation. Reference errors identify the evidence position and decision or verification field without exposing source text. Native invocation failures are not retried through this correction path. If correction still fails, the range remains pending.

The runner saves each validated redacted payload in its owner-readable pending queue before the first upload. Transport retries reuse that exact payload instead of asking the model to prepare another version. Previously queued payloads retain their version and are drained before the same session switches to version five. Accepted legacy ranges are reconciled with the server before new preparation; upgrades do not replay them.

Automatic mode sends prepared payloads and advances checkpoints only after matching server receipts. Manual mode prepares the same redacted queue without uploading its work content or advancing checkpoints; `pending` can prepare another bounded batch. Show the complete returned queue and approve it once with `approve --approved`. Approval sends only already-prepared payloads, in order, and does not create unseen ones. Scheduled notifications are content-free. Preparation failures, unprepared ranges, and failed uploads remain pending rather than counting as completed work.

When file uploads are enabled for the approved canonical folder and capture is unpaused, the same scheduled run checks it. `sync-files` checks it immediately inside that grant without changing the schedule. Before sending new or changed files, the runner polls unfinished jobs from its local checkpoints. It sends supported file bytes over the configured HTTPS connection (or localhost HTTP for development). The server accepts each file as a background job and processes its text in chunks; upload does not wait for claim extraction. A later scheduled or manual sync polls the job's result. Only `processed`, `no_claims`, or `duplicate` finalizes the local checkpoint; `partial` reopens failed chunks on the next sync. On this upgrade, completed file checkpoints are replayed once so the new extraction can retain suggestions; in-flight jobs are polled first and replayed after finishing. Server-side idempotency prevents already published claims from being duplicated. Files larger than 20 MB remain pending with an error. The scanner reads regular files directly in the chosen folder and ignores symlinks and subfolders. Unknown formats are reported as unsupported rather than treated as successful syncs.

The file-job result reports published claims separately from needs-evidence suggestions. A `no_claims` result can still contain suggestions: these are possible contributions awaiting evidence or attribution, not verified claims. The runner reports the suggestion count but never labels those suggestions as established work. It does not print the file's text, candidate statements, or source excerpts to logs. Use Shifu to inspect the suggestions and their evidence status. A result with zero claims and zero suggestions means no user-attributable contribution was extracted; it does not mean the upload failed.

The connector captures supported harness work in engineering, product discovery, writing, interview feedback, research, and planning. Native preparation preserves supported constraints, corrections, reasons, rejected options, provisional conditions, and pending verification alongside work descriptions. Per-item source roles and available original timestamps distinguish a human request from an assistant report and original event time from sync time. Pasted actors are not automatically the uploader, and reported outcomes are not independent verification. Version-five items enter as contextual records until explicitly approved as personal claims in Shifu. A successfully prepared segment with no durable context may advance its checkpoint without creating a claim. Versions one through four remain accepted for existing clients and exact queued retries.

## Sync a prepared payload

```sh
printf '%s' '{"harness":"codex","sessionRef":"thread_example","fromTurn":1,"toTurn":1,"title":"Requested scoped context behavior","summary":"Requested stable existing chats for now; verification remains pending.","evidence":[{"kind":"activity","title":"Existing chat continuity","statement":"Requested stable existing chats for now; verification remains pending.","itemRef":"t1_context","workContext":"Existing chat continuity while checks are pending.","decisionRefs":[0],"sources":[{"role":"user","turn":1,"locator":"source_example","excerptMode":"synthesized"}]}],"verification":[],"decisions":["For now preserve existing chat context."],"redactionVersion":5}' | npx --yes @useshifu/coding-harness sync --harness codex
```

This illustrates the payload shape; real source locators and timestamps must come from the reviewed source packet. Automatic mode sends an explicitly prepared payload immediately. Manual mode asks once unless the calling harness already obtained approval and passes `--approved`.

## AI Profile observations

AI Profile observations are created automatically with each coding-session activity sync, under the same sync policy. The local runner reads user turns to detect a small set of behavioral signals, then sends only fixed, redacted statements and turn numbers. It never sends prompts, transcripts, tool output, code, file paths, names, or secrets for AI Profile. Model and thinking labels are included only when recognized in local harness metadata. If an observation fails, its redacted payload remains in a local retry queue while activity sync continues; an already accepted observation is kept.

The category is one of `system_design`, `detailed_design`, `implementation`, `debugging_testing`, `production_support`, `research_analysis`, `product_planning`, `writing_communication`, `marketing_growth`, `learning`, or `other`. Evidence dimensions are `task_selection`, `goal_clarity`, `context_sharing`, `constraint_setting`, `work_decomposition`, `iterative_steering`, `critical_judgment`, `verification`, `application`, and `responsible_use`. Automatic observations cite the relevant turn and never infer a limiting behavior from silence. Unsupported dimensions remain unscored.

The AI Profile page shows detected categories, model and thinking labels, and Jev scores supported by these limited observations. Local signals do not prove work quality or establish that another model setting would have performed better. Identical retries are safe.

## Recommended package updates

The connection endpoint returns `recommendedPackageVersion`, pinned to a published release. Before `sync`, `sync-files`, `approve`, or `scheduled-sync`, the runner compares its embedded release version with that property. An older runner installs the exact recommended release through npm and resumes the original command with the updated runner. Equal or newer runners continue unchanged. Explicitly recommended major releases follow the same comparison rule. Missing or invalid recommendations, connection failures, and npm failures do not block sync. The connection, pending work, checkpoints, and schedule are preserved.

This update mechanism first ships in `0.3.10`. Runners from earlier releases need a one-time installation of a release containing it (`npx --yes @useshifu/coding-harness install --harness codex`). Raise the server recommendation only after the target release is published and its backend requirements are deployed.

## Force sync local work

An explicit force request selects local work independently of checkpoints, within the approved projects and history. A stored replacement range crossing the approved cutoff requires wider wizard review before force; do not trim the stored range. It includes already synced sessions and ranges the server has never accepted. It creates missing ranges or replaces their current work evidence and claims while retaining history. Force never resets or lowers checkpoints and does not change scheduled sync or AI Profile observations.

1. Discover ranges with `sessions --harness codex --days 3 --force` (or a requested hours/count selection). Keep that initial target list fixed. Complete stored ranges touching selected turns are preserved, including older turns across a window boundary; uncovered selected turns are split into ranges of at most 12.
2. Re-review each range with `review --harness codex --session-ref <sessionRef> --days 3 --force --from-turn <fromTurn> --to-turn <toTurn>`. The original local turns must exist. Explicit backfill/count selections use `--all`. No old receipt ID is required.
3. Have the coding harness read the final notes semantically and prepare meaningful redacted evidence about attributable work. Preserve supported technologies, patterns, problem, approach, and verified results, including work described with bold Markdown actions or inline-code technology names. Keep the exact session reference and turn range and add `force: true`. Pipe it to `sync --harness codex --force`, following the saved manual/automatic approval policy.

Force requires at least one supported evidence item. Do not use the unattended `payloadForSegment` keyword projection, empty evidence, or a title-only payload for force. When final notes support no work items, report the range as not replaced; its existing work and checkpoints stay untouched. Ordinary scheduled sync can still accept a claim-free checkpoint.

Missing local turns are reported in `unavailableSegments`. A partial overlap with accepted work is rejected; re-discover and re-review complete ranges before retrying. Automatic retries preserve the accepted result even if another force sync finishes meanwhile. A new invocation is a new explicit force request. Existing conversations retain their context; start a new chat in Shifu to use the latest context.

Scheduled native preparation retains supported choices, rejections, proposals, reasons, tradeoffs, and lessons without the former controlled-vocabulary restriction. It remains bounded and model-generated: missing original sources, failed preparations, and unsupported facts are not reconstructed or treated as verified work.

For an explicitly selected original-message review, run `review-source --harness codex --session-ref <sessionRef> --from-turn <first> --to-turn <last>`. This local-only command prints selected human instructions and corrections alongside final assistant notes, with roles, event times when available, and opaque locators. It accepts at most 12 turns and fails above 128 messages or 256 KiB instead of truncating. It makes no network or model requests, writes no packet files, and changes no checkpoint, approval queue or schedule. The stdout packet contains raw local text: keep it outside the Shifu input folder and never submit it as a sync payload. The packaged sync skill explains how to prepare separate redacted statements that preserve pending checks and provisional conditions without treating requests or assistant advice as completed work.

Version-five payloads carry per-item `workContext`, `decisionRefs`, and synthesized source metadata. Deploy backend migration 068 and matching API and context readers before recommending this runner. Original-source synthesis must not be submitted as legacy version four. Manual source inspection remains available independently of automatic preparation, and historical replacement still requires an explicit force request.

## Proactive context in every supported harness

Run `mcp-setup --harness <codex|claude_code|opencode>` to install the MCP connection, usage skill and managed policy in the native global instructions. At the start of substantive work and whenever a new topic enters the task, the harness identifies topics, entities, themes and their relationships, then retrieves relevant work context before choosing an approach. It does not need to recognize missing history first or skip a familiar topic: a known pattern can still have project-specific adoption or rejection history. A combined task query starts retrieval; focused searches expand insufficiently covered topics within the existing bounds. Requests use the advertised schema and exclude source code, secrets, raw repository paths and unrelated private text.

The harness tracks topic coverage in its working context: current source context retrieved, no useful match, partial or stale. It reuses sufficient current evidence and refreshes for new topics, changed scope or stale sources. A no-match result is not proof that no history exists, and bounded search is not exhaustive recall. Summaries retain useful topic continuity, not independent evidence. This first version adds no persistent topic cache or classification API.

Alongside substantive proposals, confirmation requests, implementation and completion reports, the harness can surface specific support or discrepancy attributed to Shifu with its source and date. It compares scope and changed circumstances; consistency is not proof of correctness and a difference is not automatically a mistake. Current user instructions take precedence over history as an authority rule, not a relevance score. Useful unanswered clarification does not require repeated approval or let history veto an authorized action. Goal-aware coaching uses observable behavior, explicitly stated goals and personal-eligible context; `includeBackground: true` requests profile, memory and stored insights when useful. User choices, rationale and disagreement belong in final notes for existing sync, without automatic memory writes or reconciliation claims. Generic praise, routine tool-call commentary and repetitive feedback are skipped.

Setup preserves other instruction text and MCP settings. Package installation refreshes an existing well-formed managed Shifu instruction block without changing surrounding text, credentials, checkpoints or MCP settings. It does not create a new global policy before MCP setup. If refresh is unavailable or the markers are malformed, the runner reports the setup remedy and preserves the file. Existing connections can re-run setup to verify connectivity and update instructions, then reload the harness and start a new chat. The client still controls tool invocation; setup verifies connectivity and installs guidance rather than enforcing tool calls. See [instruction paths and behavior](../../docs/shifu-context-mcp.md#proactive-context-across-harnesses). Context lookup does not itself authorize memory or correction writes.

## Codex context and memory

The context branch adds a remote MCP connection using the same saved Codex key:

```sh
npx --yes @useshifu/coding-harness mcp-setup --harness codex --mcp-url https://YOUR-BRANCH-HOST/mcp
```

For development, install dependencies and run from the checkout root:

```sh
npm ci --prefix packages/shifu-coding-harness --ignore-scripts
node packages/shifu-coding-harness/bin/shifu-harness.js mcp-setup --harness codex --mcp-url https://YOUR-BRANCH-HOST/mcp
```

The installer validates the existing sync connection and checks MCP `initialize` and `tools/list`. It configures `shifu` in Codex without changing other servers or the sync API URL, and installs the `shifu-context` usage skill. Existing connections do not need another key. A missing connection prompts for a key in the terminal. HTTPS is required except for loopback development URLs.

The local `mcp-headers --harness codex` helper supplies credentials from the private connection file; do not run or print its output in a chat. No secret is written to Codex config or command arguments. macOS/Linux local Codex connections require a client supporting `http_headers_helper`. Remote execution environments and Windows credential-helper setup are currently unsupported; there is no plaintext fallback.

Reload Codex or start a new chat after setup, then confirm `get_work_context`, `inspect_context_evidence`, and `update_memory` are available. A setup probe confirms endpoint connectivity; it does not load tools into an already running chat. Memory corrections and durable context can be saved through `update_memory`; ordinary coding-session sync continues separately.

`get_work_context` retrieves structured context directly, without an inference-runner session. Codex interprets and cites claims with signed references, titles, confidence, decisions, dimensions, evidence spans, attribution and status; receipts are grouped under their supporting claim. Profile, memory, and stored insights accompany those records. Insights carry signed `supportingReferences`, `generatedAt`, and caveats, and are returned only while their supporting sources remain current, approved and eligible. They are stored model interpretations that may omit newer work; retrieval does not generate new insights.

Keep the truthful full question in `question` and reuse a stable `requestId` for retries. On updated servers, `mode: search` enables bounded semantic matching through the existing Jev provider; optional `query` supplies lexical terms (up to 160 Unicode characters). `mode: inventory` lists records. `detail: compact` defaults to 30 cards and accepts up to 60; full defaults remain eight. Filters include `area`, `sourceCategory`, `sourceType`, `kind` and UTC RFC3339 date bounds. Search ranges with both date bounds cannot exceed 366 days; undated records are excluded. Follow signed `coverage.nextCursor` on either path with unchanged question, mode, query, cutoff and filters. Semantic results expose `relevanceScore` and `relevanceBasis`, rank by relevance, and apply `minScore` (default 0.75, range 0–1) to every scored candidate. Lexical fallback has a different score basis and does not apply the semantic cutoff. Equivalent statements expose bounded signed `groupedReferences`, total `groupedCount` and partial flags without merging different claims. Candidate counts and `partialReason` explain the 60-record pool selected using lexical hits and source/category/day diversity. `hasMore: false` is the end of selected matches, not exhaustive semantic coverage. Compact continuation pages omit background by default; `includeBackground` controls it. `inventoryCategoryCounts` covers eligible filtered inventory. Expand signed references through `inspect_context_evidence`; expanded receipts are bounded to 12 per claim with precise `receiptsPartial`. Disclose `semanticCandidatesPartial`, `semanticUnavailable` and other coverage limits. Each page reads a fresh snapshot. Older server defaults remain supported.

`correct_context_claim` persists explicit user corrections to statement, attribution or date using a current signed reference, `versionId`, stable `requestId`, `origin: user_requested` and source provenance. It preserves original evidence and approval state, marks correction origin, and prevents automatic re-extraction of the same source from overwriting the correction. It does not use general memory slots. Migration 064 must precede the updated backend; application rollback retains its correction history. Separate action items and decision entities are deferred.

This retrieval path is specific to MCP. Ask Shifu in the UI and background insight generation retain their existing inference flow.

Official configuration reference: https://learn.chatgpt.com/docs/config-file/config-reference

## OpenCode context and memory

OpenCode uses the same `/mcp` endpoint and three tools, authenticated with its own saved OpenCode connection key:

```sh
npx --yes @useshifu/coding-harness mcp-setup --harness opencode --mcp-url https://YOUR-SHIFU-HOST/mcp
```

For checkout usage, install dependencies with `npm ci --prefix packages/shifu-coding-harness --ignore-scripts` from the checkout root, then run the checkout CLI with the same arguments. Setup preserves existing sync settings and other MCP servers, checks authenticated initialization and tool discovery, and installs the `shifu-context` usage instructions. A missing OpenCode connection prompts for its key in the terminal. A Codex key cannot authorize an OpenCode connection.

The installer detects OpenCode 1.x or 2.x and validates configuration through that installed client before changing files. V1 uses `mcp.shifu`; V2 uses `mcp.servers.shifu`, direct tool exposure (`codemode: false`), and separate startup/catalog (30 seconds) and execution (300 seconds) budgets. Older V2 builds that discard these options fail validation with an update instruction. Existing unrelated settings and comments are preserved. A managed V1 Shifu entry in the selected file moves to the V2 location during setup.

The installer adds a remote `shifu` entry with `oauth: false` to OpenCode's JSON or JSONC configuration, preserving existing content and comments. Its Authorization header uses OpenCode's `{file:...}` substitution to read a protected local credential file; the key stays out of configuration, command arguments and chat. Replacing the saved connection key refreshes that file; disconnect removes it. Restart OpenCode and start a new session after setup. For V2, run `opencode service stop` before reopening it so the background service loads the new connection. Project-specific configuration can override global MCP settings; inspect `opencode mcp list` in the project if tools do not appear.

The API derives the harness and tenant from the authenticated connector key. Memory updates from OpenCode carry `opencode` provenance; personal eligibility, general retrieval and evidence verification use the same rules as Codex. Coding-session sync remains separate. No additional local MCP server or OpenCode plugin is required.

Official references: [V1 MCP servers](https://opencode.ai/docs/mcp-servers/), [V2 MCP servers](https://opencode.ai/v2/docs/mcp-servers/) and [V2 migration](https://opencode.ai/v2/docs/migrate-v1/).

For the optional native integration gate, set `SHIFU_TEST_OPENCODE_BIN` to a temporary official OpenCode 2.x binary and run `node --test test/opencode-native.test.js` from this package. It uses isolated configuration, a synthetic credential and local MCP/model fixtures; it checks setup, native credential-file authentication, discovery and a model-driven tool call without a user key or paid model.

## Claude Code context and memory

Claude Code connects to the same `/mcp` endpoint and three tools with its own saved connection key:

```sh
npx --yes @useshifu/coding-harness mcp-setup --harness claude_code --mcp-url https://YOUR-SHIFU-HOST/mcp
```

For checkout usage, install dependencies as above and run the checkout CLI with these arguments. Setup checks the existing Claude Code key, authenticated initialization and tool discovery, and installs the `shifu-context` skill. It preserves the sync endpoint, schedule, checkpoints and other MCP servers. A missing connection prompts for a Claude Code key in the terminal; do not substitute a Codex or OpenCode key.

The user-scope HTTP connection uses Claude Code's `headersHelper` to read the protected local Shifu connection file. The key is absent from MCP configuration and command arguments. Replacing the saved key is picked up when the helper runs on reconnection. Restart Claude Code or start a new session after setup; use `/mcp` to inspect or reconnect Shifu. Local or project MCP configuration can override a user-scope server with the same name.

The API records memory provenance as `claude_code` from the authenticated key. Context retrieval and memory behavior match Codex and OpenCode; ordinary session sync continues independently. This setup requires local macOS/Linux and a Claude Code CLI supporting HTTP `headersHelper`, verified with Claude Code 2.1.295. Unsupported or broken older clients need an update using Claude Code's official installation instructions; there is no plaintext credential fallback. `CLAUDE_CONFIG_DIR` is honored for MCP configuration, installed skills and session discovery.

Official reference: [Claude Code MCP connections](https://code.claude.com/docs/en/mcp).

The same proactive context policy is installed for Codex, Claude Code and OpenCode through their native global instructions.

## Cursor context and work capture

Cursor support ships in `0.3.31` and requires backend migration `071_cursor_harness` before new Cursor keys or uploads can be accepted. Deploy the backend first, publish the package, then expose the dashboard's version-pinned setup commands. Do not recommend an unpublished package to existing installations.

Install [Cursor Agent CLI](https://cursor.com/docs/cli/installation) and sign in with `agent login`. The desktop app's login does not necessarily authenticate the CLI. Then create a dedicated Cursor key in Shifu and run:

```sh
npx --yes @useshifu/coding-harness connect --harness cursor
npx --yes @useshifu/coding-harness mcp-setup --harness cursor
```

For a checkout before publication, run `npm ci --prefix packages/shifu-coding-harness --ignore-scripts` and replace `npx --yes @useshifu/coding-harness` with `node packages/shifu-coding-harness/bin/shifu-harness.js`. `connect` installs the runner, skills and work-capture hooks and verifies the Cursor-specific key. Capture remains disabled until the wizard’s reviewed Start; installing hooks is not capture authorization. MCP setup verifies authenticated initialization and discovery, preserves those choices and other MCP entries, and adds a local stdio bridge in `~/.cursor/mcp.json`. The bridge reads the protected Shifu connection file; no key is copied into Cursor configuration or process arguments. A conflicting existing `shifu` entry is preserved with a rename instruction. Other harness keys cannot authorize Cursor.

Reload Cursor and start a new chat. Enable the Shifu MCP server if Cursor requests approval; CLI users can run `agent mcp enable shifu` and `agent mcp list-tools shifu`. Normal tool approvals still apply. Setup's HTTP probe is separate from native-client discovery and a model-driven tool call.

Global `~/.cursor/hooks.json` entries observe `beforeSubmitPrompt`, `afterAgentResponse` and `stop`. They store only original human text, assistant messages and completion metadata in an owner-only local journal. They do not send source text, tool output, attachments, email addresses or reasoning to Shifu. All completed assistant messages in a generation are retained. Duplicate hook delivery is idempotent; a trailing turn waits for a successful `stop`. Failed or aborted assistant responses are not used as completed reports. Journal identities stay independent of historical transcript turn numbering.

A `sessionStart` hook supplies the managed `cursor-context.md` policy in the Shifu configuration directory through Cursor's documented `additional_context` field and identifies the control chat for exclusion from its own sync. This is advisory guidance; Cursor controls when tools run. Skills are installed in `~/.cursor/skills`. Custom `CURSOR_CONFIG_DIR` or `SHIFU_CURSOR_HOME` locations are supported. Existing hook entries, other MCP servers and surrounding policy text are preserved. `disconnect --harness cursor` removes only this installation's hooks and MCP entry; it preserves captured local source files.

New capture works through hooks even when Cursor transcripts are disabled. Historical discovery reads local main-agent JSONL transcripts when available. Untimestamped history remains unavailable to automatic time-window selection and is reported by `status.initialHistoryBlocked`; no timestamps or missing conversations are invented. Explicit `sessions --count N` and selected `review-source` can inspect available originals locally. This does not recover sessions absent from local storage.

Scheduled preparation uses the authenticated Cursor Agent CLI in a temporary isolated configuration with no user MCP servers or lifecycle hooks, deny-all tool permissions, and a fail-closed tool hook. The matching schema is supplied locally; strict result parsing rejects tool activity, errors and malformed output. Existing source bounds, redaction validation, manual approval, frozen retries, continuity attachments and receipt-matched checkpoints apply. Preparation failure leaves work pending. Manual approval uses a content-free desktop notification (`osascript` on macOS, `notify-send` on Linux), without creating another model conversation.

Optional installed-client proof, using synthetic credentials, an isolated home and a local endpoint:

```sh
SHIFU_TEST_CURSOR_BIN="$HOME/.local/bin/agent" node --test packages/shifu-coding-harness/test/cursor-client-native.test.js
```

Official references: [MCP](https://cursor.com/docs/mcp), [hooks](https://cursor.com/docs/hooks), [CLI configuration](https://cursor.com/docs/cli/reference/configuration) and [CLI permissions](https://cursor.com/docs/cli/reference/permissions).

## Continuity beside version five

New scheduled preparation includes up to six preceding completed human turns as local reference context. Whole oldest turns are dropped to keep references within 64 KiB and the combined packet within 128 messages and 256 KiB. Saved history cutoffs and excluded sessions still apply. Earlier messages explain a current request; they do not become another upload of earlier work. Version-five source links retain only current-range authors and timestamps.

Native preparation uses a separate internal schema with source coverage, episode stage and entity placeholders. Code permits the public technology labels Turbopuffer, PostgreSQL, Go, TypeScript, React and Node.js. Other named identities use neutral scoped aliases. A public technology permission does not authorize a confidential customer relationship. The private name dictionary stays in an owner-readable local file, scoped to the connection and trusted original workspace; unknown workspaces use a session-specific scope. Existing dictionary candidates must be selected explicitly; equal names alone do not merge identities. Cross-device private-name lookup and dictionary sharing are not provided.

A useful summary or decision cannot be silently accepted with no evidence. Legitimate empty results remain possible with an explicit local reason and neutral summary. Each unchanged input has at most two native attempts, reserved durably before invocation and shared across restarts. Unresolved ranges block later ranges in that session while other sessions continue. `status` reports preparation, base acceptance and continuity attachment separately. To retry a selected unqueued hold after reviewing its reason:

```sh
coding-harness retry-preparation --harness codex --session-ref <opaque-session> --from-turn <original-start>
```

That command cannot regenerate a frozen or accepted payload. Historical recovery remains separate.

For explicitly authorized missed history, select each session with `sessions --harness codex --session-ref <opaque-session> --all`, inspect its exact range with `review-source`, then run `prepare --harness codex --session-ref <opaque-session> --from-turn <first> --to-turn <last> --all`. Preparation uses the same isolated native extraction and privacy checks and queues only the next completed contiguous range, at most 12 turns. It does not upload or change saved history settings. Existing queued payloads are reused exactly; exhausted holds require a separately reviewed `retry-preparation` with the same selected session, original start and `--all`. Omit `--all` to keep the saved history cutoff. The same commands support `claude_code` and `opencode`.

For multi-session recovery inside an existing approved project/history grant, freeze the selected opaque references and upper turn bounds in a private JSON selection with `harness`, `selectedAt`, and `sessions` containing `sessionRef`, `fromTurn`, and `throughTurn`. Run `recover --harness codex --selection <file>` once under saved automatic approval, then `recover --harness codex` to resume bounded batches. The runner saves a connection-bound recovery manifest; scheduled runs resume that exact selection without changing the initial-history cutoff or adding new sessions or turns. New ranges contain at most four completed turns; frozen queued payloads and existing hold boundaries remain exact. Existing unqueued holds receive at most one explicitly authorized retry reset, recorded before extraction. Unfinished tails, exhausted retries, rejected receipts and pending continuity attachments prevent completion. `status` reports recovery progress separately from ordinary sync.

Continuity uses separate `*-continuity.json` and `*-entity-dictionary.json` files; the version-five body, hash, receipt and base queue stay unchanged. Semantic metadata is frozen before the base POST. The exact matching receipt ID is durably saved before checkpoint advancement or base queue removal. A lost response retries the frozen base payload, including after an older runner has advanced the local checkpoint; range equality is never used to pick an attachment target.

The companion endpoint is used only when the authenticated connection advertises `capabilities.continuityAttachment: 1`. An older backend can still accept the base upload while metadata waits locally. Attachment retries reuse one frozen request ID and body, back off, and stop for review after ten attempts. Authorization, target and body conflicts stop immediately. Replacing either the connection key or API endpoint quarantines old checkpoints, base queue, outbox and dictionary before committing the new configuration. An interrupted replacement holds sync until connect resumes with the same selected target. Source text and private names never enter the companion request or status output. Atomic file replacement and file flushing apply on every platform; directory flushing and owner permission enforcement apply on POSIX.

Use only compatible preparation writers on a shared configuration directory. An older runner can read and transport the unchanged base queue, but cannot enforce new preparation holds. Stop its preparation schedule or use a compatible rollback build. Never delete checkpoints or replay accepted history to repair missing continuity.

## Set up Shifu

Use the `shifu-onboarding` skill in your coding assistant, or open Shifu setup yourself:

```sh
npx --yes @useshifu/coding-harness onboard --harness codex
```

Choose `codex`, `claude_code`, `opencode`, or `cursor`. Run this on the local macOS/Linux device whose coding history you want to connect. A remote/headless assistant cannot open this device's setup page: run the command in your own local terminal instead. The launcher prints a local URL if opening the browser fails. That URL carries a per-launch capability in its fragment; do not share it. It is not your Shifu connection key.

The setup page collects history, projects, optional file uploads/folder, schedule and independent feedback choices. Files start off. Saved choices and the original cutoff are reused; keys go directly to the local runner. Review shows counts and model-account usage before explicit Start authorizes that scope. Merely connecting or saving choices cannot capture work. Manual session approval remains separate from the enabled folder-file path.

Accepted ranges use existing checkpoints and exact frozen payloads. Initial discovery freezes session boundaries for this run; later activity follows ordinary sync. Closing the browser does not stop the detached worker after Start; pause stops further processing. The scheduled runner resumes unfinished ranges on its next tick; **Resume unfinished backfill** retries immediately. Older unsynced turns outside the saved window remain blocked rather than silently expanding scope. A zero-day selection skips historical work. Empty history is reported honestly, not counted as captured context.

Setup checks saved-work availability before offering **Copy a question**. Reload the assistant as instructed and paste that short prompt. The non-secret run reference only identifies local state; it never grants account access. The skill checks status without reinstalling, reasking choices or replaying accepted history:

```sh
npx --yes @useshifu/coding-harness onboard --harness codex --status --run <reference>
```

Only after explicit user confirmation that the sourced answer helped may the assistant add `--helpful`. The backend requires saved evidence and a real context retrieval before recording activation. Assistant usefulness telemetry is not user confirmation.

To change choices after a completed, skipped or empty run, use **Change preferences**, or explicitly launch with `--new`. This preserves accepted sync checkpoints. An active selection cannot be discarded with `--new`. If a key was revoked, replace it through the interactive `connect` flow, then use `onboard --new` to review the changed connection. Old state is quarantined; capture requires a new grant. A key replacement or package upgrade alone does not authorize another backfill.

The setup page and skill ship in package `0.3.37`, with the same light theme and bundled fonts as the dashboard. The dashboard intentionally has no onboarding entry points. Deploy the backend requirements, publish the tested package, then promote the release recommendation. The existing progress API remains compatible. No package is published merely by changing this checkout.

For an unfinished selection that you explicitly want to leave, **Change preferences** asks for confirmation and preserves accepted records/checkpoints. The equivalent terminal operation is `onboard --harness codex --new --abandon`. Ordinary `--new` refuses to discard an active run. After wider wizard review authorizes any older prefix, Resume rechecks only the frozen blocked targets and can finish without importing later appended turns.
