# SDK Python API 0.18.1

Import `SDK`, `Outcome`, `SDKError` and `__version__` from `pycforge_sdk`.
`SDK(engine_python=None, cache=None, timeout=30, cancel=None, progress=None)` creates
a session with no discovery or file writes. Omitted or None engine_python selects
the current Python interpreter; omitted or None cache selects
`Path.home()/".pycforge-sdk"/"cache"`, matching the CLI defaults. Local manual and
project guidance work with `SDK()` without an engine connection. Select the
installed engine explicitly when PyCForge is in another environment. Construction
does not search other installations, execute an interpreter or create the cache.

| Method | Result data | Effects |
| --- | --- | --- |
| `manual(topic=None)` | Installed guide, API and native diagnostic Markdown with hashes | Local read only; no engine connection |
| `connect()` | Engine identity, connection state, problem if unavailable | Discover and atomically refresh reference cache |
| `engine_reference(offline=False)` | Complete validated engine authoring reference, including optional sections | Read/reference refresh; offline mode never invokes an interpreter |
| `authoring_fields(directory, function=None, offline=False)` | Engine field definitions, paths, presence and stored values | Read project/reference only; no defaults, saves or semantic assessment |
| `methods(advanced=False)` | Task categories and explained method entries | Read/reference refresh only |
| `describe(method)` | One detailed method card | Read/reference refresh only |
| `coverage(profile=None)` | Versioned conversion coverage, authoring profiles, exact choices and starters | Read/reference refresh only; no fixture execution |
| `create_project(directory, author=..., template=...)` | Directory and project digest | Create a new directory from inert engine template data |
| `inspect(directory)` | Engine inspection and project digest | Validate a frozen candidate through public engine services |
| `scan(directory)` | Versioned scan object, project identity, readiness and field issues | Read-only structural and example checks; no native execution |
| `prepare_documentation(directory)` | Changed flag, updated project identity and next action | Explicit atomic project upgrade/field scaffolding; preserve author prose |
| `convert(directory, case)` | Engine result, diagnostics, generated C | Convert one fixture; no compilation/execution |
| `verify(directory, compiler="cc")` | Full fixture report and report path | Explicit compilation/execution; replace verification evidence |
| `build(directory, destination)` | Package path, hash and evidence identity | Write package only if current evidence passes |
| `register(package, store=None)` | PyCForge registration state | Explicit registry mutation; no test execution |

Build and register also return an additive `data.handoff` view of the completed
operation, described below. Existing result fields and evidence gates remain.

Each method returns `Outcome`. `ok` is true only for status `succeeded`.
`to_dict()` returns `pycforge-sdk.result/0.1` with SDK version, status, data and
structured diagnostics. Statuses distinguish `rejected`, `incomplete`, `canceled`
and `internal_failure`. A failed native comparison is rejected. Missing tools,
timeouts and unavailable connections are incomplete. Read the preserved engine
diagnostics inside conversion results for source codes and locations.

Pass a `threading.Event` for cancellation. Progress callbacks receive a dictionary
with schema, phase, case name, index and total. The callback runs on the caller's
thread; it must return promptly. SDK operations are synchronous. The desktop
runs them in a worker and relay events to its UI thread. A session is not
advertised as safe for concurrent mutation.

Project schema `pycforge-sdk.project/0.2` contains `declaration`, `metadata`,
`cases` and `documentation`. Schema 0.1 remains readable and is upgraded only
by the explicit document operation. Scalar declarations use the engine-owned
`crucible.scalar-declaration/0.1` or `/0.2` schema.
Each case contains `name`, a relative UTF-8 source `file`, and `expect`:

```json
{"kind":"run","stdout":"2.0\n","stderr":"","exit_code":0}
```

or

```json
{"kind":"reject","code":"PYC4706"}
```

Project snapshots reject duplicate JSON keys, nonfinite JSON numbers, unknown
project fields, missing files, path traversal and source symlinks. The first
budget is 256 KiB per source and 4 MiB total, including project JSON and sources.
There must be at least one case; there is no independent fixture-count ceiling.
Every declared case remains part of verification. Native processes have bounded
captured output and a per-process timeout of at most 300 seconds. A timeout is
not interpreted as successful conversion or verification.

Successful reports bind all explicit inputs. A build checks the complete report,
project, engine and compiler again. Editing a report does not create a signed
attestation; the caller and local environment remain trusted. This is a workflow
guarantee for honest authoring, not an anti-tampering security product.

Compatible reference additions, including families expressible through the
existing workbench contract, do not require new SDK code. New required fixture
kinds or incompatible execution protocols require explicit capability support;
they are never silently skipped.

Scalar 0.2 integration

`methods()` and `describe()` also expose engine-owned domain_contracts, so a
console or future method tree can explain each declared rule. `methods()` lists
supported_profiles. The math-scalar project template comes from the engine and
contains the extended declaration and tests; viewing it does not execute it.

Engine policy scalar-fixtures/0.2 adds required source-call coverage. Reports
include required/covered/missing operation IDs. SDK_INCOMPLETE_COVERAGE blocks
verification/build when an export is not called in a passing native fixture
program. This is not dynamic branch coverage, full-input proof or a signature.

The result envelope remains 0.1. Documented projects and verification reports
use independent schema 0.2 versions. Scalar
declaration schemas 0.1 and 0.2 are interpreted by the selected engine. Catalogue
0.1 and 0.2 are supported; incompatible versions and signature changes preserve
offline metadata and cannot authorize authoring. Reverify after upgrading the
SDK, engine, compiler or project; previous evidence is never silently promoted.

## Scan and Help contracts

The `data.scan` object uses `pycforge-sdk.scan/0.1`: `project_sha256`, `engine`,
`reference`, `template`, `coverage`, `issues`, `state`, `verification` and
`checks`. States are `needs-authoring` and `ready-to-verify`. Verification is
`not-run`; reading an older report never promotes a scan to verified.
Issues carry code, JSON-pointer path, message and remedy. The generated author
template has blank required fields. UI clients must discard results whose
project fingerprint no longer matches their editor revision.

Author schema `pycforge.extension-author-help/0.1` has exactly: schema, overview,
usage, limitations, release_notes, functions and constants. Function keys must
match all exports exactly. Each function has parameters (one plain-text meaning
per positional argument), returns, details and example (a run-fixture name).
Constant keys exactly match the constant exports, with a plain-text meaning.
Text is bounded to 4000 characters per field; blank and standard placeholder
values are incomplete. Author documentation and examples together have a
512 KiB serialized budget. Unknown fields and schemas are refused.

Package format `pycforge.scalar-package/0.2` contains exactly manifest.json,
conversion.json and documentation.json. Help schema `pycforge.extension-help/0.1`
contains schema, engine-generated reference, author data and the exact referenced
fixture source/output/exit-code snapshots. The manifest and SDK statement bind
the Help hash as well as the conversion payload hash. The engine validates the
reference against the admitted scalar descriptor and renders escaped text.

Verification schema 0.2 adds documented-source-call coverage. Every function's
selected example must be a passing native case containing its operation ID.
Reports retain the existing scope limits: source-call coverage is not evidence
that every branch executed. There is no author HTML or executable help hook.
The SDK owns verification; PyCForge only admits and renders the package.


Scalar parameter profile 0.3 is supplied by the selected engine. Inspect
`ScalarParameter` for names, kinds and canonical defaults and `ScalarFunction`
for the native, log-ratio and symmetric-close choices. `named-scalar` is an
independent example template. No SDK method implements binding or numerical
lowering locally. Existing methods return the same Outcome envelope; scan
issues are in `outcome.data["scan"]["issues"]` with JSON-pointer field paths.
Changing a name, kind, default, or numerical kernel invalidates verification
through the complete project fingerprint. Offline caches authorize browsing
only. Re-run scan and verify for supplied examples in your selected environment.

## Starter choices and arrays

`SDK.templates()` returns small id/title/description/declaration_schema records,
connection state and the engine's workflow. It never runs template sources.
`methods()` includes `array_operations`: read-only descriptions, signatures,
result and allocation effects. `describe("ArrayFunction")` shows only four
normal author fields. Do not turn fixed dtype/shape/allocator/cleanup rules into
editable GUI controls. Advanced public API inventory remains opt-in.

The existing create_project, inspect, scan, verify, build and register methods
handle the array profile without a second service. Engine-worker dispatch uses
public ExtensionAuthoring when available and retains ScalarAuthoring for older
engines. No compiler, NumPy semantics or private adapters are copied into SDK.

## SDK 0.6 desktop and readiness

The optional PySide6 desktop uses these same public methods. The headless import
has no Qt or engine dependency. The desktop has no private converter.

* `readiness(directory, compiler=None)` returns data.readiness with schema
  pycforge-sdk.readiness/0.1. Only ready-to-package is a successful approval.
  Other states: needs-authoring, ready-to-verify, needs-verification, unavailable,
  canceled. Checks, issues (code/path/message/remedy), exact project/engine and
  evidence identities, fixture results, coverage and scope are structured data.
  No fixtures execute; matching evidence requires a compiler version query.
  After passing evidence, the engine also validates the bounded archive in
  memory. Readiness writes no package file.
* `build(directory, destination, compiler=None)` optionally requires evidence
  for the currently selected compiler. It independently repeats the same gate.
* `open_project(directory)` returns directory, project_sha256, document and a
  name-to-UTF-8-source map; it does not import project code.
* `validate_project(directory, document, expected_sha256=...)` validates a draft
  without saving, using the saved project's fixtures and data budgets.
* `save_project(directory, document, expected_sha256=...)` atomically writes
  project.json after validation and optimistic identity checks.
* `save_source(directory, filename, source, expected_sha256=...)` atomically
  writes an existing fixture. Both saves return a fresh editor snapshot. External
  conflicts reject with SDK_EDIT_CONFLICT and preserve saved files. Only one
  writer is assumed; these APIs are not an adversarial-filesystem transaction.

Existing scan/0.1 remains ready-to-verify, never native approval. New readiness
uses the same private evidence gate as Build. All clients receive the same
Outcome envelope. UI results must match both editor revision and loaded project
hash; a late result cannot approve unsaved or externally changed contents.


## PCFC11 backend evidence

SDK 0.6.4 records `report.compiler.backend` for PCFC11. Its fields include
the driver's selected command, the absolute invocation path in `executable`,
the resolved file, its SHA-256, target and schema. The supported Linux native
profile advertises `pcfc11_backend_identity` with value `pcfc11.backend/1`.
Direct GCC keeps its existing compiler record.

`readiness` returns `needs-verification` for stale PCFC11 evidence.
`SDK_STALE_COMPILER` includes the two backend identities when available.
`SDK_COMPILER_BACKEND` identifies a missing or unreadable selection.
`SDK_BACKEND_CAPABILITY` identifies an older engine, driver or unsupported
target. Fix the selection and call `verify` before building. Existing
package bytes are preserved on failure.

A failed native fixture returns `SDK_FIXTURE_FAILED` at the first failing
`/cases/N`, plus a report path and the first compiler diagnostic when available.
The complete case results remain in the verification report. An invalid command
with the global `--json` flag returns the result envelope with `SDK_ARGUMENT`
and exit code 2. `methods` and `describe ValueFunction` return the connected
engine’s `value_operations` for machine clients.

## Conversion coverage

`SDK.coverage(profile=None)` returns `data.connection` and `data.coverage`.
The latter has schema `pycforge-sdk.coverage/0.1`, source, family_coverage,
authoring_coverage, profiles, templates, selected_profile, limits and scope.
Explicit engine family metadata is preserved in authoring_coverage. When absent,
that field is null and family_coverage is `not-reported`; forms and starters may
still be available. A catalogue-only engine without an authoring reference
returns the existing `SDK_CAPABILITY` diagnostic.

Each profile retains its engine fields and adds operations (the choices of its
operation_field) and starters with the same exact declaration schema. An empty
operation list is not zero capability: scalar profiles use authored fields and
their described choices. Compatibility profile revisions are not extra families.
The optional profile argument selects one exact declaration_schema; the family
overview and global limits remain the engine's full descriptions.

```python
result = sdk.coverage()
if not result.ok:
    raise RuntimeError(result.to_dict())
for profile in result.data["coverage"]["profiles"]:
    print(profile["declaration_schema"], profile["title"])
```

An unknown profile returns `SDK_COVERAGE_PROFILE`; details contains `/profile`,
available_profiles and remedy. Malformed or unsupported coverage metadata returns
`SDK_COVERAGE_REFERENCE` with a JSON pointer and remedy. During connection it
prevents replacement of the last compatible cache. Unknown optional metadata is
inert. Cached browsing can succeed while connection.state is offline and
execution_available is false; this never authorizes verification or packaging.

`methods()` now includes text_operations and authoring_coverage.
`describe("TextFunction")` includes text_operations; console descriptions show
their signatures and explanations. Existing array/value result fields remain.
Reverify projects after upgrading the SDK; older successful evidence and
packages are preserved when a stale build is refused.

## Starter customization

`SDK.template(template)` reads the complete inert starter. `SDK.customize_template(template, *, package_id, namespace, version="0.1.0", exports=None)` asks the selected engine to specialize it without writing files. `SDK.create_project` accepts those same optional customization keywords alongside `author` and `template`; package ID and namespace must both be supplied. Exports map existing function/constant names to new names. A mapping cannot remove or add operations. The result includes engine inspection, not fixture verification. Unaliased starter imports retain their old local name through an explicit alias. Strings, comments, native symbols, parameter contracts and fixture expectations remain unchanged. Inspect the generated Help and add tests for your intended use before scan, verify, build and explicit registration.

The CLI exposes `template ID`, and `new --package-id ID --namespace NAME --package-version VERSION --rename OLD=NEW` (repeat rename). Malformed or duplicate CLI mappings return SDK_ARGUMENT. Unsupported engines return SDK_CAPABILITY; offline customization returns SDK_OFFLINE. Existing folders and prior packages are preserved. The GUI New dialog uses exactly this service and disables customization when it is not advertised. Plain starters remain compatible with earlier engines.

## Fixture conversion preflight

`SDK.preflight(directory, *, case=None)` uses the selected engine's public
conversion service to check every saved fixture, or one exact case name. It
returns `data.preflight` with schema `pycforge-sdk.preflight/0.1`, project and
engine identities, selection, scope, state, matched/total counts and cases.
Each case retains its original index, name, validated project file, source hash,
expected result, engine conversion status, unchanged diagnostics and source spans.
`conversion_matches` reports whether conversion met the declared expectation:
a run case needs generated C and a successful conversion status; a reject case
needs Rejected, no C, and its exact expected diagnostic code. Warnings and
approximation diagnostics remain visible. Unknown or inconsistent result shapes
are refused explicitly, not treated as matches.

`succeeded` means all selected conversion expectations matched; `rejected` with
`SDK_PREFLIGHT_MISMATCH` findings identifies mismatches by `/cases/INDEX/expect`.
`native_verification` is always `not-run`. Preflight does not check stdout,
stderr, exit codes, dynamic coverage or native correctness. It does not replace
Scan, Verify, readiness, packaging or explicit registration. Existing source,
verification records and packages are never written. Engine metadata may be
refreshed through the ordinary connection workflow. Offline connections refuse
preflight. Cancellation, changed source/engine identity and a report exceeding
eight MiB return no completed report. Existing project bounds still apply.

```python
result = sdk.preflight("./cube-root")
for case in result.data.get("preflight", {}).get("cases", []):
    print(case["name"], case["conversion_matches"], case["diagnostics"])
```

CLI: `preflight DIRECTORY [--case NAME]`; add the global `--json` for structured
results. Human-readable locations use one-based lines and columns. Structured
engine spans retain their original one-based lines and zero-based character
columns. Desktop source navigation converts character columns to Qt UTF-16
positions and bounds every cursor move, including supplementary Unicode text.
The desktop's Check fixtures action uses this same service; a completed preflight
never enables Package. Save source corrections, then check and verify again.


## Incomplete project setup

`new_setup(template=..., author="", directory="", mode="guided")` returns a
`setup` document without creating files. Choose an exact ID from `templates()`.
Its schema is `pycforge-sdk.setup/0.1`; it carries incomplete entries, stable
starter IDs, per-starter edits and catalogue identity, a base for relative paths,
and separate mode/step. It contains no verification evidence.

`save_setup(filename, document, expected_sha256=None)` and `open_setup(filename)`
need neither an engine nor Qt. Results contain `file`, `setup`, `setup_sha256`
and `verification="not-established"`. A new filename must not exist. Replacing
a loaded file requires its last observed hash. SDK_SETUP_EXISTS and
SDK_SETUP_CONFLICT preserve existing bytes. Save under a new name or reopen
the externally changed file; do not bypass the conflict by dropping its hash.
Malformed, duplicate-key, oversized, symlink or unsupported-schema setup is
rejected with SDK_SETUP. The budget is one MiB, 512 starter entries, 1,024 exports
per entry and 8,192 characters per text field. Invalid unfinished identifiers
can be saved; conversion-semantic validation remains the engine's responsibility.

```python
draft = sdk.new_setup(template="scalar-cube-root", directory="my-extension")
assert draft.ok, draft.to_dict()
saved = sdk.save_setup("work.pcfsetup", draft.data["setup"])
assert saved.ok, saved.to_dict()
opened = sdk.open_setup("work.pcfsetup")
assert opened.ok, opened.to_dict()
document = opened.data["setup"]
document["author"] = "Example author"
saved = sdk.save_setup("work.pcfsetup", document,
                       expected_sha256=opened.data["setup_sha256"])
assert saved.ok, saved.to_dict()
reviewed = sdk.review_setup(document)
assert reviewed.ok, reviewed.to_dict()
if reviewed.data["review"]["state"] == "current":
    created = sdk.create_from_setup(document)
    assert created.ok, created.to_dict()
```

`review_setup(document)` fetches fresh metadata and returns `connection`,
`templates` and `review`. A successful result means the comparison completed;
inspect `review.state`: current, review_required or unavailable. Each change
has a code, message and applicable before/after values. `current_setup` is a
proposal, never an automatic update. Review it before explicitly applying or
saving it. Surviving identity/export edits are retained; accepting current data
removes the retired export entries identified in the changes. A missing starter
has no proposal. Unsupported customization remains visible and must be adjusted.
Other visited starters retain their own snapshots and edits.

`create_from_setup(document)` requires complete creation inputs and a current
review. SDK_SETUP_REVIEW preserves choices when the engine/starter differs;
SDK_SETUP_ENGINE identifies an unavailable live engine. It calls the ordinary
`create_project` service and returns its normal project result. The optional
`create_project(..., expected_engine_sha256=...)` parameter pins a reviewed
catalogue SHA-256 and checks it again before committing the destination. A late
change returns SDK_STALE_ENGINE. Creation does not compile, run or register.

CLI equivalents use the same services:

```text
pycforge-sdk --engine-python ENGINE setup new work.pcfsetup --template scalar-cube-root
pycforge-sdk setup open work.pcfsetup
pycforge-sdk setup save work.pcfsetup --input edited.pcfsetup --expected-sha256 OBSERVED_HASH
pycforge-sdk --engine-python ENGINE setup review work.pcfsetup
pycforge-sdk --engine-python ENGINE setup review work.pcfsetup --accept-current
pycforge-sdk --engine-python ENGINE setup create work.pcfsetup
```

Use global `--json` for structured output. Run review before deciding whether
to use `--accept-current`; that explicit option saves the proposed starter data
with the file's observed hash. It never creates a project or verifies fixtures.
The input to setup save is a complete setup document, not a result envelope.
One writer per file is assumed. Optimistic saves are not a process-wide lock.


## Focused authoring guidance

`authoring_guide(directory, stage=None)` reads a saved project without an engine
connection, fixture execution or file writes. The ordinary result contains
`directory`, `project_sha256` and `authoring_guide`. Its schema is
`pycforge-sdk.authoring-guide/0.1`; `assessment` is always `not-performed`.

Stages contain stable `id`, `title`, `purpose`, concise `requirements` and a
section JSON-pointer `path`. They cover Project, Functions, Package Help,
Function Help, conditional Constant Help, Fixtures and Review. Stages without
relevant functions/constants are omitted. `inventory` counts declared functions,
constants and native/rejection fixtures; a malformed constants container yields
null instead of a guessed count. `documentation_present` indicates a nonempty
Help object, not complete documentation. No guide result authorizes packaging.

Pass one listed stage ID to return only that stage. Unknown IDs return
SDK_GUIDE_STAGE with the available identifiers. Saved project validation and
SDK_CANCELED keep their established meanings. Guidance is a view of saved data;
use open_project/save_project/save_source for explicit edits. The desktop uses
the same model with its current draft and the existing engine-driven forms.
Its position preferences do not alter project data or verification evidence.

```python
from pycforge_sdk import SDK

client = SDK()
guide = client.authoring_guide("my-extension", stage="fixtures")
assert guide.ok, guide.to_dict()
for step in guide.data["authoring_guide"]["stages"]:
    print(step["title"], step["purpose"])
```

```text
pycforge-sdk authoring-guide my-extension
pycforge-sdk --json authoring-guide my-extension --stage fixtures
```

No interpreter discovery occurs for either example. Scan, Check fixtures, Verify
fixtures, Package and registration remain separate explicit operations.

## Engine reference and focused fields

`engine_reference(offline=False)` returns `connection` and `reference`. The latter
is the complete validated engine authoring reference, including unknown optional
sections; it is not the selective `methods`/`describe` presentation. Its schema
belongs to the engine. No authoring or conversion call is made by this browse.

`authoring_fields(directory, function=None, offline=False)` returns `directory`,
`project_sha256`, `connection` and `authoring_fields`. The field report schema is
`pycforge-sdk.authoring-fields/0.1`, with `assessment="not-performed"`.
Select a function by its exact operation_id or export; the identifier must match
one function unambiguously. Omit it for declaration fields. `functions` lists
available identifiers. Bad selections return SDK_FIELD_TARGET; invalid argument
types return SDK_ARGUMENT.

Each field contains its complete engine `definition`, JSON-pointer `path`,
`present` flag and, only when present, its stored `value`. Absence is distinct
from explicit null and is not a validation failure. Choices preserve JSON types:
true, 1, 1.0, "1" and null are distinct identities. `unrepresented_fields` lists
stored keys outside the advertised form; use open_project/save_project to retain
and edit those values. Unknown profiles return `source="no-advertised-form"`;
the SDK does not infer a family or generate semantic defaults.

Both methods accept `offline=True` to read a compatible cached reference without
invoking an interpreter. No cache yields SDK_ENGINE_UNAVAILABLE and an incomplete
result. Normal mode follows the usual connection/discovery behavior. Cached
reference is labeled offline and cannot authorize execution. Field reports have
an eight-MiB serialized budget; project byte limits also apply.

```python
fields = sdk.authoring_fields("my-extension", function="my_export")
assert fields.ok, fields.to_dict()
for field in fields.data["authoring_fields"]["fields"]:
    print(field["path"], field["definition"], field["present"])
# Inspect the engine definition before explicitly choosing and saving a value.
```

```text
pycforge-sdk --json --engine-python ENGINE reference
pycforge-sdk --json --engine-python ENGINE fields my-extension --function my_export
pycforge-sdk --json --cache CACHE reference --offline
pycforge-sdk --json --cache CACHE fields my-extension --offline
```

Connection descriptions retain the human `problem` and additive
`problem_diagnostic` (null on success). Failures preserve `code`, `message` and
`details.stage`: discovery, catalogue, authoring-reference, workbench or cache.
`connect()` also returns that diagnostic in its ordinary Outcome. Inspect status
and connection state; preserved offline reference is not a successful live
connection.

## Shared next actions

`readiness(directory, compiler=None)` retains its established state, readiness,
issues and evidence checks. Its `data.readiness.guidance` adds schema
`pycforge-sdk.next-actions/0.1`, `advisory_only=true`, a title, summary and actions.
Each action has an ID, label, SDK `method` (null for UI navigation),
`required_inputs`, `effects`, description and `explicit_action_required=true`.
These describe existing workspace operations; they are not engine conversion
capabilities, a task scheduler or authority to execute.

Unknown/inconsistent states suggest reviewing the report and rescanning. Only
an actual ready result suggests packaging; the build method still independently
checks the evidence. Editing, refresh, compiler changes or failed verification
cannot inherit approval from guidance. CLI readiness text renders this same
model; global `--json` preserves the full result. The desktop's next-action
buttons invoke its existing actions with the existing busy/unsaved/readiness
gates. Arrival of a result never invokes an action automatically.

## Package handoff and registration receipts

Successful `build` returns `data.handoff` with schema
`pycforge-sdk.package-handoff/0.1` and stage `packaged`. It records the artifact
path/hash/size/format, full engine-inspected `extension` data, engine identity,
project/evidence hashes, an import statement and concise continuation steps.
`registration.state` is `not-requested`; building never registers a package.
`example`, when present, is the first named native Help example in the package,
copied from the verified project with its exact source, stdout, stderr and exit
code. It is not generated or executed by the handoff view. Other project fixtures
remain available through open_project and the ordinary editor.

`register` retains its original raw `data.registration` result. The additive
handoff contains that same complete row under `registration.engine_result`, plus
the actual engine identity and artifact path/hash. Engine status Ready produces
stage `registered` and an import statement for that row's namespace. All other
engine statuses produce `registration-failed`, preserve the message/data, and
omit a usable import statement. A transport/connection failure may have no
handoff. Registration receipts have no project/evidence association or example;
they must not inherit those from another open project or an earlier package.

The statement uses `*import NAMESPACE as extension`, where the namespace comes
from the validated engine result. No calls, signatures or conversion limits are
inferred. Missing namespace data yields no statement. Unknown additive extension
and registration fields are preserved. No package-format/family allowlist is
introduced by this presentation.

These are recorded operation results, not fresh evidence for later file changes.
Keep using readiness/build for current project approval and register explicitly
for registry changes. CLI build/register prose renders the same handoff; global
`--json` retains all original fields and the complete added model. The desktop
displays the same data and retains normal package selection and confirmation.

```python
result = sdk.build("my-extension", "my-extension.pcfplugin", compiler="gcc")
assert result.ok, result.to_dict()
print(result.data["handoff"]["import_statement"])
# Register explicitly after reviewing the intended package and engine.
receipt = sdk.register(result.data["package"])
assert receipt.ok, receipt.to_dict()
print(receipt.data["registration"]["namespace"])
```

## Reviewed fixture editing and recorded results (SDK 0.16)

These engine-independent methods return the normal Outcome envelope:

| Python method | CLI command | Data key |
| --- | --- | --- |
| `sdk.fixtures(directory)` | `fixtures DIRECTORY` | `fixtures` |
| `sdk.plan_fixture_change(directory, request, expected_sha256=HASH)` | `fixture-plan DIRECTORY --request FILE --expected-sha256 HASH` | `fixture_plan` |
| `sdk.apply_fixture_change(directory, request, expected_sha256=HASH, expected_plan_sha256=PLAN)` | `fixture-apply DIRECTORY --request FILE --expected-sha256 HASH --plan-sha256 PLAN` | Snapshot plus `fixture_plan`, `changed`, `committed` |
| `sdk.fixture_results(directory, case=None)` | `fixture-results DIRECTORY [--case NAME]` | `fixture_results` |

Use global `--json` for the same versioned models. Request files are bounded JSON
objects; no source import or execution occurs while reading or applying them.

| Request action | Required keys beyond action | Optional keys |
| --- | --- | --- |
| `add` | `name`, `file`, `source`, `expect` | None |
| `duplicate` | `case`, `name`, `file` | None |
| `rename` | `case`, `name` | None |
| `remove` | `case` | `replacement` |

`case` is the current exact fixture name. New names follow the existing unique
identifier rule. Add and duplicate require new canonical project-relative source
filenames; no extension/family restriction is added. Add's UTF-8 `source` is text,
and `expect` is the existing full run (`kind`, `stdout`, `stderr`, `exit_code`) or
reject (`kind`, `code`) object. Duplicate copies source bytes and expectations.
Rename changes logical identity and known Help example links, retaining source
path and bytes. Remove retains source files; linked Help needs an explicit
different native `replacement`. At least one fixture must remain.

```python
from pycforge_sdk import SDK

sdk = SDK()  # These local authoring operations do not connect to an engine.
observed = sdk.fixtures("my-extension")
assert observed.ok, observed.to_dict()
inventory = observed.data["fixtures"]
request = {
    "action": "add", "name": "custom", "file": "tests/custom.py",
    "source": "def main():\n    print(7)\n    return 0\n",
    "expect": {"kind": "run", "stdout": "7\n", "stderr": "", "exit_code": 0},
}
review = sdk.plan_fixture_change(
    inventory["directory"], request, expected_sha256=inventory["project_sha256"])
assert review.ok, review.to_dict()
plan = review.data["fixture_plan"]
# Present/review plan's case changes, exact new sources and Help changes first.
saved = sdk.apply_fixture_change(
    inventory["directory"], request,
    expected_sha256=inventory["project_sha256"],
    expected_plan_sha256=plan["plan_sha256"])
assert saved.ok, saved.to_dict()
# Save creates no verification. Select an engine/compiler and verify explicitly.
```

Inventory schema is `pycforge-sdk.fixtures/0.1`; the plan schema is
`pycforge-sdk.fixture-plan/0.1`. A plan includes old/resulting project hashes,
before/after cases, `help_changes`, `create_sources` (source, SHA-256, byte length),
`retained_sources` and scope. `plan_sha256` hashes canonical plan JSON before the
digest field is added. Apply recomputes it and rejects a changed review/project
or occupied destination. The hash binds content, not user authorization.

New source creation precedes a single atomic project.json commit. Precommit
failure/cancellation cleans only unchanged files this operation created. An
external edit or cleanup failure returns incomplete `SDK_FIXTURE_RECOVERY` with
retained paths. Abrupt process death can leave unreferenced new files; the old
project remains valid. This is optimistic single-writer editing, not a locked
multi-file transaction. Cancellation after commit reports the saved result.
Unknown engine declaration/documentation metadata is retained.

Result schema `pycforge-sdk.fixture-results/0.1` reports saved report identity,
`project_matches`, `sdk_matches`, `engine_currentness: not-checked`, original
status/problem, case summaries and optional `comparison`. Comparison schema
`pycforge-sdk.fixture-comparison/0.1` preserves the complete `recorded_case` and
original outcome. Checks distinguish observed/unobserved, matches and the first
different character. JSON offsets/columns are zero-based Unicode code points;
lines are one-based. Escaped context/diffs are bounded, complete records retained.

New native output identities compare expected UTF-8 bytes with recorded raw byte
hashes/lengths. Invalid UTF-8 display replacements never establish a byte match.
Older reports use labeled displayed-text comparison; a text match cannot replace
their original failed outcome. Missing execution output remains unobserved.
Rejection comparisons retain full diagnostics and compare the expected code.
No expectation is changed, no execution occurs and no packaging approval is
created by these views. Existing readiness/build gates remain authoritative.


## Fixture source repair and recovery

These local operations use the ordinary Outcome envelope and never invoke the
engine, run fixtures, change expectations or create verification. A repair is an
explicit checkpoint of one source buffer; project-form edits and unsubmitted
fixture-add dialogs are outside this checkpoint.

| Python method | CLI equivalent | Result fields |
| --- | --- | --- |
| `new_source_repair(snapshot, filename, source=None)` | `repair new DIRECTORY --fixture-file FILE --source EDITED.py --output NEW.pcfrepair` | `repair` |
| `open_source_repair(filename)` | `repair open FILE` | `file`, `repair_sha256`, `repair` |
| `save_source_repair(filename, repair, expected_sha256=None)` | `repair save FILE --input DOCUMENT.json [--expected-sha256 HASH]` | `file`, `repair_sha256`, `repair` |
| `review_source_repair(repair)` | `repair review FILE` | `source_repair_review` |
| `apply_source_repair(repair, expected_sha256=..., expected_review_sha256=...)` | `repair apply FILE --expected-sha256 HASH --review-sha256 HASH` | editor snapshot, `committed`, `changed`, `source_repair_review` |

`new_source_repair` takes the `data` of a previously successful `open_project`.
It does not reread the project, so a client can preserve its original observation
after external changes. `source` is the author's edited text; omission copies
the original. CLI `new` opens the current project first and omits `--source` for
an unchanged draft. Use an existing repair object to retain an older observation.

`pycforge-sdk.source-repair/0.1` contains exactly `schema`, `directory`, `file`,
`base_project_sha256`, `original` and `edited`. The directory is absolute; the
file is a project-relative fixture path. Each source is valid UTF-8 and at most
256 KiB. JSON is bounded at 4 MiB, including escape expansion. Unknown required
repair schema/fields, duplicate keys, invalid paths and malformed text are
refused. Engine declaration data is not copied into or interpreted by this
format. The base hash describes an observation, not authentication or approval.

Save uses a `.pcfrepair` path outside its project's directory. New destinations
must be unoccupied. Replacement requires the exact checkpoint hash returned by
open/save; the hash covers saved file bytes, not a result envelope. `--input`
contains the complete repair object. Open/save needs no live project or engine.
A saved foreign-platform project path remains readable; review requires an
appropriate absolute path for this host. Edit a copy explicitly to relocate it.

Review returns schema `pycforge-sdk.source-repair-review/0.1`, exact original,
edited and current source, `project_changed`, `source_changed`, `draft_changed`,
`diverged`, `would_change`, current `affected_cases` (including expectations),
`project_sha256`, `repair_sha256` and `review_sha256`. Diverged means both disk
and draft differ from the original and from each other. Review never merges or
chooses between texts. Reconcile in `edited`, then review again. The digest binds
the complete review excluding its own digest; it is not verification evidence.

Applying requires the current project hash and review hash returned by review.
Any change to the repair, sources, expectations or other project inputs requires
another review. Apply replaces only the named source with the exact `edited`
text, using the existing single-file editor validation and optimistic checks.
It leaves the current project document, other sources, checkpoints, reports and
packages intact. An intentional replacement of externally edited text is only
possible through explicit apply of the newly reviewed text. Preserve a checkpoint
of any alternative you wish to retain. Readiness/build still independently check
evidence; fresh native verification is required after a meaning change.

```python
from pycforge_sdk import SDK
sdk = SDK()
opened = sdk.open_project(project_dir)
assert opened.ok, opened.to_dict()
filename = opened.data['document']['cases'][0]['file']
draft = sdk.new_source_repair(opened.data, filename,
    opened.data['sources'][filename] + '\n# author revision\n')
assert draft.ok, draft.to_dict()
saved = sdk.save_source_repair(repair_path, draft.data['repair'])
assert saved.ok, saved.to_dict()
reviewed = sdk.review_source_repair(saved.data['repair'])
assert reviewed.ok, reviewed.to_dict()
view = reviewed.data['source_repair_review']
# Inspect original, edited, current and affected_cases before choosing to apply.
applied = sdk.apply_source_repair(saved.data['repair'],
    expected_sha256=view['project_sha256'],
    expected_review_sha256=view['review_sha256'])
assert applied.ok, applied.to_dict()
```

`SDK_REPAIR` identifies invalid checkpoint data, `SDK_REPAIR_EXISTS` an occupied
new destination, `SDK_REPAIR_CONFLICT` a changed saved checkpoint,
`SDK_REPAIR_TARGET` an unavailable fixture reference or incompatible host path,
`SDK_REPAIR_REVIEW` a changed review, and `SDK_EDIT_CONFLICT`/`SDK_STALE_PROJECT`
changed project inputs. Existing project-loader errors explain missing or invalid
projects. `SDK_IO` reports filesystem failure. Failed operations keep the in-memory
repair; explicitly save it to retain it across process exit.

New checkpoints publish complete flushed bytes through an exclusive hard link;
filesystems without this facility fail with SDK_IO. Existing checkpoints use an
observed-hash, atomic one-file replacement. Cancellation before commit preserves
the old file; no cancellation check follows commit. Abrupt process death may
leave a private `.sdk-repair-*` temporary file. There is no autosave, automatic
merge, global lock, multi-file transaction or universal power-loss guarantee.
Only explicitly saved checkpoints can recover an interrupted session.

## Project authoring drafts and recovery

These services need no engine and never infer expectations or execute sources.
They use the normal Outcome envelope. A draft is separate from the live project
and from setup/source-repair checkpoints.

| Python service | CLI equivalent | Successful result |
| --- | --- | --- |
| `new_project_draft(snapshot, document=None, document_text=None, fixture=None, navigation=None)` | `draft new DIRECTORY [--document BUFFER.json] [--fixture STATE.json] --output NEW.pcfdraft` | `draft` |
| `open_project_draft(filename)` | `draft open FILE` | `file`, `draft_sha256`, `draft` |
| `save_project_draft(filename, draft, expected_sha256=None)` | `draft save FILE --input OBJECT.json [--expected-sha256 HASH]` | `file`, `draft_sha256`, `draft` |
| `review_project_draft(draft)` | `draft review FILE` | `project_draft_review` |
| `resume_project_draft(draft, expected_sha256=..., expected_review_sha256=...)` | `draft resume FILE --expected-sha256 HASH --review-sha256 HASH` | `snapshot`, `document`, `fixture`, `navigation`, `project_draft_review`, `committed: false` |
| `apply_project_draft(draft, expected_sha256=..., expected_review_sha256=...)` | `draft apply FILE --expected-sha256 HASH --review-sha256 HASH` | fresh editor snapshot, retained `fixture`, review and `committed: true` |

Supply `document` or `document_text`, not both; omit both to capture the observed
snapshot's document. `snapshot` is the data returned by `open_project`, retained
from the author's original observation. Capture does not reread disk. CLI new
observes the current disk; editing an existing checkpoint preserves an older base.
Raw document text can contain incomplete or invalid JSON and is retained exactly.

Draft schema `pycforge-sdk.project-draft/0.1` has exactly `schema`, `directory`,
`base_project_sha256`, `original_document`, `source_sha256`, `document_text`,
`fixture` and `navigation`. Directory is absolute; source_sha256 maps original
fixture paths to their SHA-256 values, not their source contents. Original opaque
engine values and edited data are preserved, including optional unknown metadata.
Navigation is an inert JSON object; the desktop uses its ordinary mode/stage/tab
and function/help/constant/fixture selection keys. No navigation value approves
project meaning or executes an action.

`fixture` is null or an unfinished dialog state with exactly these keys:

```json
{
  "action": "add", "case": "", "name": "", "file": "tests/new.py",
  "source": "", "kind": "run", "stdout": "", "stderr": "", "exit_code": 0,
  "code": "", "replacement": null, "tab": 0
}
```

Action is add/duplicate/rename/remove. Case is the selected existing case for
non-add operations; name/file/source/code may remain incomplete. Kind is run or
reject; both sets of expectation inputs survive switching modes. Exit_code is an
integer 0–255; replacement is null or a case name; tab is 0–3. This state is not a
fixture plan or permission to create a file. On continuation, construct the normal
fixture change request from the selected action and expectation kind, review it
with `plan_fixture_change`, then explicitly call `apply_fixture_change`.

Open/save requires no project or engine. Save outside the project with a
`.pcfdraft` suffix. Replacement requires the observed saved-file `draft_sha256`.
Do not substitute the canonical review's draft digest for this byte-level file
hash. `--input` contains the complete draft object, not an Outcome envelope.
New destinations must be unoccupied. Conflicts preserve the existing file.

Review schema `pycforge-sdk.project-draft-review/0.1` reports `project_changed`,
`document_changed`, `source_changes`, `draft_changed`, `diverged`, original/current
documents, exact edited text, any parse_problem, pending fixture, current project
hash and canonical draft/review hashes. Source_changes contains changed, added or
removed referenced paths; it is not a source backup or automatic restoration plan.
The complete draft (including navigation and pending fixture) binds the review.
`engine_currentness: not-checked` and `verification: not-established` remain explicit.

Resume recomputes review and requires its exact current project/review hashes.
It checks form structure, allowing incomplete values such as an empty author,
and returns buffers without writing live files. Invalid JSON or form structure
must be corrected in the raw buffer before form resume. Apply adds normal project
validation and a final cancellation/currentness check, then commits project.json
only. It never applies the pending fixture, changes source files, merges external
edits, copies observed output into expectations or updates evidence. It uses the
same save path as ordinary editor Save. New verification remains explicit.

```python
from pycforge_sdk import SDK
sdk = SDK()
opened = sdk.open_project(project_dir)
assert opened.ok, opened.to_dict()
document = opened.data['document'].copy()
document['metadata'] = {**document['metadata'], 'author': 'Revised author'}
created = sdk.new_project_draft(opened.data, document,
    navigation={'mode': 'guided', 'stage': 'project'})
assert created.ok, created.to_dict()
saved = sdk.save_project_draft(draft_path, created.data['draft'])
assert saved.ok, saved.to_dict()
loaded = sdk.open_project_draft(draft_path)
assert loaded.ok, loaded.to_dict()
draft = loaded.data['draft']
reviewed = sdk.review_project_draft(draft)
assert reviewed.ok, reviewed.to_dict()
review = reviewed.data['project_draft_review']
# Inspect/reconcile original, edited and current data; review again after edits.
resumed = sdk.resume_project_draft(draft,
    expected_sha256=review['project_sha256'],
    expected_review_sha256=review['review_sha256'])
assert resumed.ok and not resumed.data['committed']
# Only an explicit save writes the resumed document; external changes still block it.
committed = sdk.save_project(resumed.data['snapshot']['directory'], resumed.data['document'],
    expected_sha256=resumed.data['snapshot']['project_sha256'])
assert committed.ok, committed.to_dict()
```

Diagnostics: SDK_DRAFT for unsupported/malformed checkpoint data or capacity;
SDK_DRAFT_EXISTS for an occupied new destination; SDK_DRAFT_CONFLICT for a saved
checkpoint conflict; SDK_DRAFT_TARGET for a foreign host path; SDK_DRAFT_REVIEW
for a changed reviewed draft; SDK_DRAFT_EDITOR/SDK_EDITOR_DATA for form structure;
SDK_EDIT_CONFLICT/SDK_STALE_PROJECT for outside changes. SDK_PROJECT reports normal
JSON/project validation; SDK_IO reports I/O failures; SDK_CANCELED is cooperative
precommit cancellation. A postcommit cancellation does not undo or deny a save.

Budgets: four MiB raw UTF-8 project text, four MiB canonical original document,
256 KiB pending source and 32 MiB serialized checkpoint (including JSON escaping).
There is no fixture-count limit. Existing live-project and per-source budgets
remain authoritative at apply. Strict JSON rejects duplicate keys and nonfinite
numbers in checkpoint structure; incomplete edited text remains data until resume.

Recovery is explicit, not autosave. Missing project/source files need separate
restoration. A moved/foreign project path can be edited in a checkpoint copy and
must be reviewed against the new target. Unapplied individual Set value dialog
entries are not captured by a workspace checkpoint. Source buffers and setup
retain their own formats. Later unsaved edits cannot be recovered after death.
New checkpoints require exclusive same-volume hard links; unsupported filesystems
fail. Process death may leave a private .sdk-draft-* temporary file. Replacements
and apply are optimistic one-file operations with no global lock, directory fsync,
multi-file transaction or universal power-loss guarantee. Retain alternative
external values before intentionally replacing a reviewed project document.
