Skip to content

feat: Agent Skills - #87

Open
XieX wants to merge 76 commits into
mainfrom
xie/agent-skills
Open

XieX wants to merge 76 commits into
mainfrom
xie/agent-skills

Conversation

@XieX

@XieX XieX commented Sep 15, 2026 •

Copy link
Copy Markdown
Contributor

Agent Skills

Skills are versioned SKILL.md documents managed in LaunchDarkly and attached to AI Config variations by reference. This adds the full server-side surface for them: the SDK reports which skills a resolved config references, retrieves their content over LaunchDarkly's FDv2 delivery channel, verifies it, and materializes it onto disk as <root>/<key>/SKILL.md — where the Claude Agent SDK and anything else following that convention discovers it.

⚠️ 🙏 Please remember to squash merge when this eventually does go onto main 🙏 ⚠️

Layers

Module Responsibility
types.py / types_validation.py Skill, SkillReference, SkillOutcome, ReconcileReport; the canonical key grammar (^[a-z0-9][a-z0-9-]*$) and version predicate
skills.py The accessors and InMemorySkillStore
skills_core.py The SkillStore interface, verification, and the structured integrity log record
skills_fdv2.py FDv2SkillStore — delivery over the SDK-facing GET /sdk/poll and GET /sdk/stream endpoints
skills_fs.py / safe_fs.py Manifest-scoped reconcile onto disk, on descriptor-pinned filesystem primitives
skills_watch.py watch_skills — re-reconcile on every delivery change

Dependencies flow downward only; nothing above the store can tell which store produced an object.

API

Export Description
skill_refs(config) Project a config's skills array into list[SkillReference]. Pure — no client, store, or network
get_skill(key, *, version=None) One verified skill, or None. version=None means newest available
get_skill_result(key, *, version=None) The same retrieval, reporting why: .skill, .reason (ok / absent / integrity_failure / store_unavailable / wrong_version), .detail
get_skills(refs) / all_skills() Batch forms. Unresolvable entries are omitted; a run that omitted anything logs a count at WARN
write_skills(skills, root, *, prune=True, timeout=10.0, on_unavailable="keep") Materialize under root, returning a ReconcileReport. Pass "*" for the whole library
watch_skills(skills, root, …, debounce=…) write_skills plus re-reconcile on delivery change. Returns (initial report, SkillWatcher)
SkillStore The structural interface content arrives through: get_object, all_objects, optional listeners
InMemorySkillStore(objects=None) Dict-backed store with put(raw), for tests and bring-your-own-content
FDv2SkillStore(sdk_key, *, base_uri=…, mode="stream", poll_interval=30.0, read_timeout=None, …) The delivery transport. start(), wait_for_skills(), close(), diagnostics, failed; also a context manager
StoreDiagnostics What the transport has seen: payloads, objects received/ignored/revoked, hashless objects, connection failures, last error

Plus the closed-set types (ReconcileActionKind, OnUnavailable, SkillOutcomeReason) and the fixed on-disk constants (SKILL_FILENAME, MANIFEST_FILENAME, MANIFEST_VERSION). init_client(options={"skillStore": store}) configures the store; shutdown() clears it.

The primary use case

import os

from launchdarkly_ai_server import (
    FDv2SkillStore, init_client, inspect_config, skill_refs, watch_skills,
)

store = FDv2SkillStore(os.environ["LD_SDK_KEY"]).start()
store.wait_for_skills(timeout=10)
await init_client(options={"skillStore": store})

# Which skills does this variation reference?
info = await inspect_config("doc-agent", {"kind": "user", "key": "user-123"})
refs = skill_refs(info["config"])       # [SkillReference(key='pdf-extraction', version=2)]

# Put exactly those on disk, and keep them in step with delivery.
report, watcher = await watch_skills(refs, ".claude/skills")
for action in report.errors:
    print(f"skill {action.key or '<run>'}: {action.error}")

try:
    ...          # run the agent; a revoked skill's SKILL.md leaves disk without a restart
finally:
    watcher.close()
    store.close()

Notes for reviewers

  • Behaviour change. parse_ai_config now fails closed on a skills value that is not a list of {key, version} objects, where before any value parsed and was ignored. A variation carrying its own differently-shaped skills field must rename it before upgrading.
  • Verification is unconditional. Content is returned only after its sha256 matches the delivered contentHash, its key and version revalidate, and its size is within 10 MiB. There is no fallback that skips it. Every withheld skill emits one structured ERROR record — ld.skills.integrity_failure, a stability commitment, byte-identical across LaunchDarkly's AI SDKs — on the SDK's own logger, independent of telemetry configuration.
  • write_skills touches only what it owns. It writes <root>/<key>/SKILL.md, records what it owns in <root>/.launchdarkly-skills.json, and will overwrite or delete only manifest-recorded paths. It treats that manifest as untrusted input and re-validates every entry. The one adoption exception — a byte-identical file at a managed path — is what makes a crashed reconcile recoverable.
  • Platform bound. The descriptor-pinned guarantee is POSIX-only; Windows falls back to a per-component lstat, which is a check-then-use race rather than a closed window. Write permission on the managed root or any ancestor is the security boundary on every platform, and on Windows the only one. The README's privilege-separation section is the deployment contract — the recommended shape runs the reconcile as a different identity than the agent.
  • write_skills blocks. It is async for parity with the other accessors and with the TypeScript SDK, but awaits nothing. Wrap it in asyncio.to_thread if a large reconcile holding the event loop matters.
  • Beta caveats. No payload signing on this channel yet, so delivery is TLS-only and the hash establishes self-consistency, not origin authenticity. FDv2 is opt-in per account (HTTP 403 while off, reported as a fatal error with instructions), and ld-relay does not speak the FDv2 endpoints.

Testing

403 skills tests across five files — test_skills (125), test_skills_fdv2 (139), test_skills_fs (107), test_safe_fs (22), test_skills_watch (10) — including a filesystem abuse matrix and root-swap race tests that fail outright rather than skip.

🤖 Generated with Claude Code, reviewed by @XieX.


Note

Overview
Adds Agent Skills to the Python server SDK: versioned SKILL.md content referenced from AI Config variations, retrieved through a pluggable SkillStore, verified (sha256 contentHash, key/version grammar, size cap), and materialized under <root>/<key>/SKILL.md with a manifest-scoped reconcile.

New public surface includes skill_refs, get_skill / get_skill_result, get_skills / all_skills, write_skills, watch_skills, InMemorySkillStore, FDv2SkillStore, and related types/constants; wiring is via init_client(options={"skillStore": ...}) (re-applied on later inits) and cleared on shutdown().

Config parsing now fail-closes on skills: it must be a list of {key, version} objects (explicit skills: null rejects the whole variation). parse_ai_config and skill_refs share the canonical key rules.

Implementation is split across skills_core (verification, telemetry seam, ld.skills.integrity_failure logging), skills_fdv2 (poll/stream delivery), skills_fs + safe_fs (descriptor-pinned atomic writes, prune/adopt rules), and skills_watch (debounced re-reconcile on store changes). Documentation in README.md and agents.md describes integrity outcomes, FDv2 beta limits, and privilege-separated deployments.

Reviewed by Cursor Bugbot for commit 43ff5c0. Bugbot is set up for automated code reviews on this repo. Configure here.

XieX and others added 30 commits August 28, 2026 13:40
First of five slices splitting the Agent Skills feature for review. This one
adds the layer with no I/O in it at all: the types, the validation, and the
projection from a resolved AI Config to the skills it references.

- `skill_refs(config)` projects a config's `skills` array into
  `list[SkillReference]`. Pure — no client, no store, no network, no telemetry.
- `Skill` and `SkillReference` are frozen dataclasses, exported from the package
  root. `Skill.content` is `bytes` — the verified verbatim bytes LaunchDarkly
  delivered, exactly what was hashed. Skills are opaque byte buffers by
  construction: the SDK never parses, decodes, or interprets skill content
  anywhere. `content_hash` is the sha256 (lowercase hex) over those bytes, and
  the optional display metadata comes from LaunchDarkly, never from the content.
- `parse_ai_config` now validates the optional `skills` array and fails closed
  on a malformed one. Key grammar, length bound, and the version predicate live
  in `types_validation.py` as one canonical rejection reason, so every layer
  added on top rejects a key for the same stated reason.

Note one behaviour change for existing users: `parse_ai_config` fails closed on
a `skills` value that is not a list of `{key, version}` objects, where before
any value parsed and was ignored. A variation carrying its own differently
shaped `skills` field must rename it before upgrading.

The two layers that follow — retrieval through a store seam, and
materialization onto disk — are separate slices. `agents.md` names all three
and the one-way dependencies between them.

Testing: `uv run pytest` → 1048 passed. `ruff check`,
`ruff format --check`, and `mypy packages/*/src` all clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Second of five slices. Adds the layer that turns a reference into content: an
injectable store seam, integrity verification of everything it serves, and a
body-free telemetry seam for the failures.

- `get_skill(key, *, version=None)` returns one verified skill, or None.
- `get_skills(refs)` is the batch form, accepting references and bare keys.
- `all_skills()` returns every verified skill the store holds, one per key.
- `SkillStore` is the structural interface content arrives through —
  `get_object(kind, key, version=None)`, `all_objects(kind)`, and an optional
  `add_listener(kind, fn)` — configured with
  `init_client(options={"skillStore": store})`. `InMemorySkillStore` ships for
  local development and testing. A delivery transport drops in behind the same
  seam with no public API change.

Store data is untrusted. Key and version are revalidated, size is bounded, and
the sha256 of the verbatim bytes must match the delivered `contentHash`;
anything that does not verify is withheld and treated as missing, so no
unverified content is ever returned. The wire object delivers content as a JSON
string; the UTF-8 encode happens exactly once, inside verification, and the
`Skill` handed to user code carries the verified verbatim bytes
(`Skill.content: bytes`) — the exact byte sequence that was hashed, never a
re-derived value. Content carrying an unpaired surrogate has no UTF-8 encoding
at all and is withheld too — `str.encode` is called strictly, never with an
error handler that would fabricate bytes a hash comparison could then accept.
`verified_bytes` also accepts already-bytes content, hashing it directly, for
the pre-write re-verification pass a later slice adds.

Integrity failures are reported through a private telemetry seam carrying
hashes and byte counts only, never the skill body. The two properties copied
off the wire, `skill_key` and `expected_hash`, are shape-checked and replaced
when malformed, so a hostile store cannot use either one to publish the body
through a signal that is otherwise body-free. The default emitter is a no-op:
nothing leaves the process in this release, and the three signal names are an
allowlist maintained in one section of one module.

Version is part of the lookup identity rather than a filter applied to the
answer. A delivery payload carries the newest version of every skill plus every
version any variation currently pins, so two versions of one key coexist
routinely; a seam keyed by key alone would answer a pinned reference with the
newest object and then reject it, turning the primary use case into a missing
skill. `InMemorySkillStore` holds several versions of a key, `get_object` takes
the wanted version, and `version=None` means "the newest you hold". The
equality check afterwards is kept as a defense — the store is untrusted, so an
answer that is not the version asked for is withheld.

`all_objects` returns one entry per key-and-version under keys that are opaque
to this SDK; identity is read off each object's own fields. `newest_by_key` is
the single place that collapses the result to one object per key.

A run that withheld anything now logs a count at WARN. Every individual
withholding already records a signal and an error line, but a caller reading
logs at WARN saw neither, and a payload where nothing verifies otherwise
returns an empty result indistinguishable from "this project has no skills".

`SKILL_OBJECT_KIND` is deliberately **not** exported from the package root. It
is the string this SDK hands a store, and an adapter maps whatever the transport
underneath calls a skill onto it; publishing it would advertise an SDK-side seam
value as the wire contract. An adapter that needs to agree with it reaches it
through `skills_core`. `MAX_SKILL_CONTENT_BYTES` stays internal for the
adjacent reason.

Note one behaviour change: `shutdown()` clears the configured skill store along
with the client. `init_client` applies `skillStore` on every successful call,
even the idempotent ones, which is what lets a lazily auto-initialized client be
given a store afterwards.

Testing: `uv run pytest` → 1145 passed. `ruff check`,
`ruff format --check`, and `mypy packages/*/src` all clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
An integrity failure now writes a structured, machine-parseable ERROR record
on the SDK's own logger, designed to be ingested by a SIEM and alerted on.

This is the detection path that works when telemetry is off, and the only one
that exists at all in an instance with no telemetry destination — so it is a
documented contract rather than a debugging aid. The LD-side counter is left
exactly as designed: opt-out respecting, no-op by default, property set
unchanged. `reason_code` lives in the log record only.

- `ld.skills.integrity_failure` is the stable event name, and it appears in the
  message text rather than only in `extra`. Severity cannot discriminate — a
  raising store also logs ERROR from this module — and the stdlib's default
  formatter drops `extra`, so an `extra`-only record is invisible under a plain
  `logging.basicConfig()`.
- The message is the event name plus compact key-sorted JSON, so the line is
  greppable, `jq`-able, and byte-identical across LaunchDarkly's AI SDKs for
  the same input. The same mapping is attached as `extra["ld_skills"]`.
- `reason_code` is a closed vocabulary of eight tokens, one per
  `record_integrity_failure` call site, typed as a `Literal` so a typo at a
  call site is a type error.
- The record spreads the signal's properties rather than rebuilding them, so
  the two cannot drift on which fields are redacted or omitted. Optional
  fields are omitted, never nulled. No new untrusted value, and no path.

Documented for customers in the README and for contributors in agents.md,
including the full vocabulary, so a ninth reason cannot land in one language
only.
Third of five slices. Adds `safe_fs.py`, the "write a file under a directory
something else may be racing you for" problem solved once. Nothing here knows
what a skill is; the materialization layer is its only caller, and it lands
next.

A path check is only as good as the last path resolution after it. Every
`lstat` and containment check validates an inode, but a following
`os.replace(tmp, dir / name)` re-resolves `dir` from its name — so anything
holding write permission there can move the validated directory aside, leave a
symlink in its place, and redirect the write or the unlink somewhere else.
Narrowing that window is not a fix; the race is winnable at any width. So the
checks hand off to a descriptor and nothing re-resolves a path afterwards.

- `open_directory_nofollow` opens with `O_RDONLY | O_DIRECTORY | O_NOFOLLOW`
  and confirms `S_ISDIR` on the `fstat`, since not every platform defines
  `O_DIRECTORY`. `open_or_create_directory` adds `os.mkdir` plus an `lstat` on
  the `FileExistsError` path, because `Path.mkdir(exist_ok=True)` accepts a
  symlink-to-directory as "already there" and would reopen the hole the
  caller's check just closed. `pinned_directory` holds either for a block, so a
  caller states the platform split once and cannot forget the close.
- `atomic_write` creates its temp file with `O_CREAT | O_EXCL | O_NOFOLLOW` at
  that descriptor, `fchmod`s the descriptor rather than a path, writes, fsyncs,
  renames, and fsyncs the directory so the rename survives a crash. Mode is set
  explicitly at 0644, never inherited from the umask and never executable.
  `os.replace` is the single rename call site and `os.rename` must not be
  substituted for it.
- `unlink_file` probes and unlinks descriptor-relative. `unlink` never follows a
  trailing symlink but it does resolve the directory above it, so the same swap
  turns a removal into a delete of an arbitrary file. A symlink found where this
  SDK expects its own file raises `SymlinkRefused` rather than being tidied
  away — the state on disk is not what the caller believes, and that is the
  caller's to report.

`SUPPORTS_DIR_FD` gates all of it, and the probe deliberately names
`os.rename`/`os.stat` rather than the `os.replace`/`os.lstat` this module calls:
`os.supports_dir_fd` is populated per underlying syscall, and CPython registers
`renameat` under `rename` only and `fstatat` under `stat` only. Probing the
names actually called reports "unsupported" on every POSIX platform and
silently turns the defense off. Where the family is absent, every operation
falls back to the identical full-path sequence.

The tests here exercise the module directly, on its own terms. The TOCTOU races
these primitives exist to close are proved through the materialization layer,
which is what holds a descriptor across a sequence of operations.

Testing: `uv run pytest` → 1260 passed, 11 skipped. `ruff check`,
`ruff format --check`, and `mypy packages/*/src` all clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Fifth and last of five slices. The adversary. Every filesystem defense the
previous two slices introduced now has a test that fails if the defense is
removed, plus the materialization telemetry allowlist.

- **Path traversal.** A key that escapes the root, a key that is the manifest
  filename, an over-long key, and a key that resolves outside after
  `realpath` — each refused before any filesystem call, and the resolved
  containment check asserted on inode identity rather than on path strings.
- **Symlink attacks.** A symlinked skill directory, a symlinked target file, and
  the `<root>/<key>` directory swapped for a symlink at the exact instant of the
  rename and of the unlink — the narrowest version of the window the descriptor
  pinning exists to close, fired from the interception point rather than from
  implementation internals.
- **The no-`*at()` shape.** The path fallback Windows takes for every operation,
  exercised with the capability probe forced off, so the platform that cannot
  pin a descriptor is not the untested one. The TOCTOU tests skip off that same
  flag deliberately: a probe that wrongly reported "unsupported" cannot also
  silently skip the tests that would have caught it.
- **Non-regular files and clobber protection.** A fifo or a directory where
  `SKILL.md` belongs, and a file at a managed path with no matching manifest
  entry — reported and left alone, never overwritten and never removed.
- **Corrupt manifests.** Unreadable, unparseable, not an object, malformed
  entries, and a `manifestVersion` this release cannot read: no overwrites, no
  prunes, an error action naming the manifest, and the manifest itself left as
  it was found.
- **Atomicity.** A crash injected between the write and the rename leaves
  neither a partial file nor a temp file, and the one recorded rename is proved
  to have moved `SKILL.md` within the target's own directory — by descriptor
  identity where the platform has `renameat`, which also rules out the
  descriptor having been redirected between the check and the rename.
- **Telemetry.** The three signal names are asserted as an allowlist rather than
  a floor: any other name reaching the emitter fails, the two deliberately
  excluded names are called out by name, no signal carries a filesystem path or
  the skill body, an emitter that raises never fails the reconcile, and
  `client.track()` is never reached.

Two of these are worth naming, because the obvious test does not reach the
guard. The unencodable-content cases pin `contentHash` to the sha256 of the
bytes a non-strict encoder would have fabricated, since an arbitrary wrong hash
is rejected by the mismatch check first and never exercises the encoder guard.
The redaction cases smuggle the body through `contentHash` and through `key`,
since a sweep using a well-formed digest under a valid key reaches neither
replacement branch.

Testing: `uv run pytest` → 1280 passed. `ruff check`,
`ruff format --check`, and `mypy packages/*/src` all clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Fourth of five slices. Adds `write_skills`, which writes
`<root>/<key>/SKILL.md` and reconciles against a manifest recording what the
SDK owns, so it overwrites or removes only files it wrote — a file you placed
yourself is reported and left untouched.

    report = await write_skills(refs, ".claude/skills")

`skills` accepts `Skill` values, references, bare keys, or the literal `"*"` for
everything the store holds. Every outcome is visible in the returned
`ReconcileReport`: one `ReconcileAction` per skill, carrying `written`,
`updated`, `skipped_current`, `removed` or `error`, plus `.ok` and `.errors`.
A failure belonging to the run rather than to one skill — an unreadable
manifest, a retrieval that failed before any key was known — carries the empty
string as its key.

Writes are atomic, at mode 0644, and every destructive step runs against a
descriptor pinned to a directory that was already checked, so a path swapped
after the check cannot redirect a write or an unlink out of the managed root.
Where the platform has no `*at()` family the identical sequence runs against
full paths.

The defenses, all of them deliberate and all of them tested:

- The key is re-validated here regardless of upstream validation, before any
  filesystem call, because a key becomes a directory name. The data model
  allows 256 characters and `NAME_MAX` is 255 bytes, so an over-long key is
  refused too.
- Never write or unlink through a symlink, on the write path or the prune path.
- Destruction only on manifest-listed paths whose key matches.
- A corrupt manifest fails closed: no overwrites and no prunes, brand-new paths
  may still be written, an error action names the manifest, and the manifest is
  not rewritten.
- An incomplete retrieval suppresses pruning, so a transport outage cannot read
  as "everything was revoked".
- Content is re-verified immediately before the write, because a `Skill` can
  also be constructed directly by a caller.

Pruning removes formerly-managed skills that are no longer referenced, which is
how revocation takes effect. `timeout` bounds retrieval, the writes and the
pruning; only the final manifest rewrite runs past it, so files already written
are never orphaned.

`write_skills` performs synchronous filesystem I/O and does not yield — it is
`async` for signature parity with the other accessors. Reconcile one root at a
time: a run is atomic against the rest of the loop today, so wrapping it to run
concurrently makes two runs against one root race on the manifest.

The `"*"` form collapses to one object per key at its newest version, since
`<root>/<key>/SKILL.md` is a single path and writing it twice in one run is a
bug rather than a policy, and it reports a withholding count at WARN for the
same reason the accessors do.

The security abuse matrix — path traversal, symlink attacks, clobber
protection, corrupt manifests, atomicity under an injected crash, and the
materialization telemetry allowlist — is the next slice. The guards it exercises
are all here; what lands next is the adversary that proves each one fails
without them.

Testing: `uv run pytest` → 1216 passed. `ruff check`,
`ruff format --check`, and `mypy packages/*/src` all clean.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
``test_key_at_the_data_model_bound_is_reported_not_raised`` read
``dst_dir_id`` directly, but that field is only populated when
``os.replace`` is called with ``dir_fd`` kwargs. On the path fallback
(``SUPPORTS_DIR_FD`` false — the shape Windows takes) it stays ``None``,
so the assertion failed even though the valid skill had been renamed
correctly into its own directory.

``_assert_atomic_rename_of`` already branches on both call shapes and
asserts the same containment property, plus the single-rename count the
list comparison implied. Use it.

Verified by forcing the probe off for a whole session: this was the only
test in the module that broke under the no-``*at()`` shape, and the
helper-based check passes under both.

Reported by Cursor Bugbot on #54.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…esystem can hold

Two gaps from the Agent Skills security design review, both in `skills_fs.py`:
AV-3 (partial reconciles are unrecoverable) and DV-2 (the key grammar admits
Windows device names).

**AV-3 — adopt a file whose bytes already are the resolved content.**
`_write_all` reconciles every skill and only then rewrites the manifest, once,
last. A process killed in that window leaves a skill file at a managed path with
no manifest entry — exactly the condition `_write_one` treats as an unmanaged-file
collision, so the skill was wedged permanently: every later reconcile took the
same refusal branch. Boot-time execution under a ten-second budget makes the
crash window realistic.

`_write_one` now reads and hashes first and decides from the bytes. Content
byte-identical to what LaunchDarkly resolved is adopted — manifest entry
recorded, reported `skipped_current` — and anything else falls through to the
same refusal as before. This cannot weaken the clobber guarantee: differing
unmanaged bytes are never overwritten, and the existing clobber tests pass
unchanged. Three details carry the safety:

- A read that fails is a refusal, never an overwrite, with a message
  distinguishable from the byte-mismatch refusal — it is the comparison that
  would otherwise authorize the write, and a file that could not be read has not
  been shown to be ours.
- The read stays on `_read_regular_file`. Adoption widens it to genuinely foreign
  files, so its refusal of FIFOs and other non-regular files is now load-bearing
  rather than defensive. It gains a `max_bytes` bound of `len(content) + 1` —
  enough to prove inequality for anything longer, and what keeps a foreign file
  of arbitrary size out of memory. A bound of exactly `len(content)` would adopt
  every file that merely begins with the resolved content.
- `skipped_current` is reused rather than adding an `adopted` action kind, so
  `ReconcileActionKind` — public, and owned by an approved PR — does not change.
  Its documented meaning already fits.

Adoption also makes the file prunable later. That is correct rather than a
weakening: only byte-identical LaunchDarkly content is ever adopted, so a later
prune removes content LaunchDarkly delivered anyway — what would have happened
had the crash not occurred.

The review also floats a write-intent journal. Assessed as over-engineered; not
built.

**AV-3, secondary — sweep orphaned temp files.** `atomic_write` unlinks its temp
file on any exception but not after a `SIGKILL`, and `_prune` walks manifest
entries, which an orphan never has, so nothing would ever notice one. The
second-order effect is worse than the disk: `_prune_one`'s `rmdir` only succeeds
on an empty directory, so a single orphan pins a skill's directory forever.

The sweep runs on both the write and the prune path, and is the one place this
SDK removes a file the manifest does not list, so it is bounded on every axis:
inside `<root>/<key>/` only, for a key that passes `_key_rejection_reason`; only
names `safe_fs` itself recognizes, via a new `is_temp_name` beside the naming
code rather than a copy of the format string that could drift from it; only
regular files, with the type read off the descriptor; unlinked through the pinned
descriptor. It never raises and never aborts a run.

**DV-2 — reject the 22 Windows reserved device names.** `con`, `prn`, `aux`,
`nul`, `com1`–`com9`, `lpt1`–`lpt9` are all valid skill keys and none can be a
directory name on Windows. Rejected in `_key_rejection_reason`, which the write
and prune paths already share, and *not* in the key grammar: `parse_ai_config`
fails closed, so a grammar-level rejection would invalidate an entire AI Config
for a Linux customer over a Windows-only constraint, and would silently shrink
`skill_refs` — which is what authorizes a prune, turning "fails to write on
Windows" into "gets deleted on Linux". The 255-byte component bound is in this
layer for the same reason.

Unconditional, not platform-gated: a root written from a Linux container is
routinely read from a Windows host, and neither repository has a Windows CI
runner, so a gated branch would be untestable — the condition that produced the
gap. No suffix stripping and no case folding: the grammar admits no `.` and no
`$`, so `con.txt` and `CONIN$` are unreachable, and keys are lowercase-only.
`com0` and `lpt0` are not reserved and are not included. The trade is real and
belongs in the release notes: a customer who legitimately names a skill `aux`
now gets a reported `error` action on Linux where it previously worked.

Neither gap emits the integrity-failure log record. A key rejection and a clobber
refusal are `ReconcileAction` errors, not integrity failures.

Tests cover crash-mid-reconcile recovery end to end (adopted, reported, recorded,
and the next reconcile an ordinary no-op), byte-differing content still refused
untouched, an unmanaged FIFO refused without hanging, a read failure refusing
rather than overwriting, the `len + 1` off-by-one, the sweep and the `rmdir` it
unblocks, lookalike temp names and a symlink wearing one left alone, all 22
reserved names through both destructive paths, and — the point of the layer
choice — each reserved name still valid to `is_valid_skill_key`,
`parse_ai_config`, and `skill_refs`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…failure

``get_skill`` returns ``None`` for four unrelated outcomes: no such skill, the
store raised, the requested version is not the one held, and content that failed
hash verification. A caller cannot fail closed on suspected tampering while
tolerating a merely-absent skill, so no automated customer-side response is
possible — finding LA-2 of the Agent Skills security design review.

The information already existed internally, as prose in ``Resolution.error``.
This gives it a token: ``Resolution`` grows a typed ``reason``, set explicitly at
every construction site and declared without a default so a sixth outcome added
later has to choose which public token it maps to. ``get_skill_result`` maps that
straight through to a frozen ``SkillOutcome`` (``skill``, ``reason``,
``detail``). Deriving the public reason by matching the error string is the
fragility LA-2 is about, so the mapping is readable in one table.

``get_skill`` is untouched — its ``None``-for-every-failure contract is
documented in its docstring and in the README, and a test now pins that all four
failures still collapse to ``None`` and still never raise.

Nothing new is emitted: Gap 1's integrity record already fired inside
verification before ``resolve_from_store`` returned, and a test asserts one
failed retrieval still produces exactly one record and one signal.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
… remainder

The four items left open in the response to the Agent Skills security design
review. Three are documentation, one is tests; no behavior changes, and the
code halves of rows 9 and 2 are deliberately untouched.

**Privilege separation** (row 9 docs half, and the agreed counter-proposal for
row 26). The recommended deployment runs the reconcile as a different identity
than the agent, which is the whole reason the ``0644``/``0755`` modes deny
anything: the agent reads its instructions and cannot rewrite them, or the
manifest. That is the mitigation for AZ-1, a prompt-injected agent editing its
own skills. Write access to the manifest is the worse half — it is what tells
the *next* reconcile which paths the SDK may delete — which is why
``_prune`` re-validates every entry from scratch rather than trusting it.

The README documents the pattern and hands the operator the check to run,
because the SDK cannot run it: it knows only its own identity, which trivially
has write access, having just written there. So ``ReconcileReport`` grows no
writability field — the review asked for one and we declined, since any check
the SDK could make would answer a different question than the one asked and
manufacture false confidence exactly where caution is wanted. ``agents.md``
records that reasoning so the field is not added later by someone reading its
absence as an oversight.

**Three hostile-manifest prune tests** (row 12 remainder): a well-formed
manifest listing ``/etc/passwd``, ``../../../etc/passwd``, and a path under a
parent that has since become a symlink. ``_prune`` already refuses all three,
so these turn asserted into verified. Two things make them worth more than
their line count. They are deliberately *well-formed* — the corrupt-manifest
suite above them proves nothing here, because a corrupt manifest suppresses
every destructive action wholesale, whereas these manifests give the
implementation everything it needs to prune. And "deleted nothing" is asserted
through an unlink spy rather than by checking that ``/etc/passwd`` still
exists: the test process cannot delete that file anyway, so the obvious
assertion would pass against an implementation with no path check at all.

**One sentence on** ``"*"`` (row 16 remainder). It materializes the whole
project library, so every skill's ``description`` enters the agent's context —
including skills no AI Config references and skills belonging to other teams.

**The Windows platform bound is now explicit** (row 2 residual), in
``safe_fs.py``, ``agents.md`` and the README. Reparse-point checks
(``GetFileAttributesW`` / ``FILE_FLAG_OPEN_REPARSE_POINT``) are not
implemented, by decision: Windows is not a supported or tested platform for
this release, neither repository has a Windows CI runner so the checks would
ship unverified, and the TypeScript SDK could not match them in any case
because Node exposes no ``*at()`` family on *any* platform. Implementing them
in Python alone would break cross-language parity and trade a documented bound
for an unverified one. Two consequences are recorded rather than left to be
rediscovered: on Windows, write permission on the managed root is the only
boundary, which is what makes privilege separation the mitigation and not
merely advice; and this retroactively lowers the priority of the row 25
reserved-device-name work, noted where that code lives.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…does not close

Three expected-failure tests (TestRootSwapRaces) for SEC-8985 row 2. The SDR response says every destructive operation runs relative to a descriptor held for the duration of the reconcile. The code pins <root>/<key> per operation and never holds the root: _resolve_root validates it once and returns a path, and each write and prune re-opens <root>/<key> by path with O_NOFOLLOW, which guards only the final component. A root swapped for a symlink after validation redirects the open, and every descriptor-relative step behind it, into the attacker's directory. Precondition is write permission on the root's parent, which the README checklist does not mention.

The tests state the contract (nothing lands outside the root, no outside file is overwritten, no outside file is removed) and are marked xfail(strict=True, raises=AssertionError) so the suite stays green, the gap is recorded next to the other race tests, and the fix cannot land without removing the marker. Run with --runxfail to see the three escapes.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit c22688b)
The expected-failure marker made the suite green while the contract was violated. A red run is the demonstration: the tests assert the contract, the code does not meet it, and they go green when the root is pinned for the reconcile, with nothing to remove.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
(cherry picked from commit 37ddb6a)
SEC-8985 row 2. The SDR response says every destructive operation runs relative to a descriptor held for the duration of the reconcile. It did not. `_resolve_root` validated the root and returned a plain `Path`; nothing held it open. Each write and each prune then opened `<root>/<key>` by path with `O_NOFOLLOW|O_DIRECTORY` and pinned that — and `O_NOFOLLOW` guards only the final component, so the root and every ancestor were re-resolved on every such open. A root renamed aside and replaced with a symlink after validation redirected the open, and with it every descriptor-relative step behind it, into the attacker's directory; on the create path `os.mkdir(<root>/<key>)` followed the link as well, and `mkdir` follows a symlink at its parent. The manifest write was the one operation that pinned the root, and it ran last, by which time the skill files were already outside it. The attacker precondition is write access to the root's *parent* — `.claude` for a root of `.claude/skills` — which the README checklist did not mention.

`write_skills` now opens the root once, immediately after `_resolve_root`, with `O_RDONLY|O_DIRECTORY|O_NOFOLLOW`, confirms `S_ISDIR` on the descriptor, and holds it until the call returns. The descriptor is threaded through `_write_all`, `_prune`, `_rewrite_manifest`, the orphan sweep and the per-skill helpers, and every destructive step names a bare component against it: `os.mkdir(key, dir_fd=root_fd)`, `os.open(key, ..., dir_fd=root_fd)` for the skill directory, `os.rmdir(key, dir_fd=root_fd)`, and `atomic_write(..., dir_fd=root_fd)` for the manifest. A root swapped in the one interval left — after validation, before the open — fails `O_NOFOLLOW` and is reported as a run-level error with nothing touched, rather than as the `ValueError` an unusable root raises.

`safe_fs`'s three openers take a `dir_fd` for the *parent* rather than growing a parallel API, and `SUPPORTS_DIR_FD` now probes `os.mkdir` and `os.rmdir` alongside the four it already named. Where the `*at()` family is absent the per-component `lstat` floor runs exactly as before: the root open returns `None` there, and every call site keeps its full-path branch.

`_unsafe_path_reason` stays and still runs, but it is documented as defense in depth rather than the boundary — every check in it inspects a path, so each is a check-then-use against anything that can rename a component of that path.

Security's three tests fired only when the intercepted `os.mkdir`/`os.open` was handed the absolute `<root>/<key>`, which the fix stops passing — they would have gone green while asserting nothing. The trigger now matches the bare key as well, so the swap fires in both worlds and the tests fail before the fix and pass after it. Two tests added: the root swapped before the pin is refused at the run level, and an audit that across a full reconcile no destructive call names an absolute path.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The privilege-separation checklist denied the agent identity the managed root, the per-skill directories, the files and the manifest, and said nothing about the root's parent. That was the precondition for the SEC-8985 row 2 root swap: renaming any ancestor is what lets the root be replaced with a symlink, and in the documented `<app>/.claude/skills` layout the parent is `.claude`, which an agent identity is otherwise likely to own outright.

The checklist and its shell snippet now walk every ancestor up to `/`. Write access to one of them is a strictly larger capability than racing the reconcile — no timing is involved, it persists until someone notices, and descriptor pinning inside `write_skills` cannot address it, because the substituted tree is what the agent reads rather than what the SDK wrote.

The platform-bound paragraph claimed a descriptor held for the whole reconcile before that was true of the root; it now describes what is actually held and for how long, and names the root's ancestors alongside the root as the security boundary on every platform.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
write_skills is a one-shot reconcile, so a revocation takes effect at the
next process restart. watch_skills runs that reconcile now and again
whenever the configured store reports a change, so a revoked skill's
files leave the disk within a debounce interval of the store learning
about it. It is wired to the SkillStore interface, not to any one
transport: it needs a store that implements add_listener and nothing
more, and refuses loudly when the store does not, since a watcher that
silently never fires looks exactly like one whose skills never changed.

Above the interface, remove_listener joins add_listener as the optional
second half of change notification, on the SkillStore contract and on
InMemorySkillStore. SkillWatcher.close needs it to detach; without it a
store held every watcher ever created for the rest of its life. The
watcher probes for it, so a store without it keeps working.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…network

The half of the delivery transport that has no I/O: identifying a skill
object on the wire by kind inline-resource plus category skill, translating
it into the raw object shape the SkillStore interface defines, holding it
by (key, objectVersion), and applying a payload's events as one commit at
payload-transferred. The store that puts a connection underneath this
follows separately, so the three decisions that matter most can be
reviewed on their own:

- objectVersion is the skill's version; version is the payload's. The
  translation happens in one place and TestVersionTranslation asserts it
  in both directions, because confusing them fails silently.
- Changes commit at payload-transferred, not per object. A half-applied
  full transfer would briefly empty the store, which with pruning on is
  the difference between a reconcile and deleting a customer's files.
- A hashless object is held, not dropped, so verification withholds it
  with a reason code rather than the transport reporting it absent.

Flag and segment objects share the connection and are skipped and
counted, not rejected. Nothing here is exported yet; the store exports
it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
``InMemorySkillStore.get_object`` consulted the version-less entry on any
pinned miss, while the unpinned path consulted it only when nothing
well-formed was filed under the key. A key holding both well-formed
versions and one malformed object therefore answered a pin for an
undelivered version with the malformed object, and verification recorded
an integrity failure — an alert pointed at a skill whose integrity was
never in question — where the honest answer is that the version is not
held.

Both paths now follow the one rule: the version-less entry answers only
when nothing well-formed is filed under the key, which is the case it
exists for. A malformed object that is all the store holds still reaches
verification and is still withheld with a signal, so tampering cannot
read as a skill that was never delivered.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Two untrusted-store answers were read as data rather than as failures.

``list_raw_objects`` collapsed a non-mapping listing to ``{}`` with no
error, so a store that served nothing usable was indistinguishable from
one holding no skills. ``resolve_from_store`` read identity off the
object without checking it against the key that was asked for, so an
answer served under a different key came back under the caller's key
while carrying its own.

Both are now withheld and reported, alongside the version check that
already guarded the same way.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…oncile

watch_skills awaited write_skills and only then constructed SkillWatcher,
which is where the store listener attaches. The reconcile snapshots the
store as its first step and then spends the rest of its time on the
filesystem, so every write, fsync, prune and manifest rewrite in that
first pass ran with nothing listening. A change delivered in that window
was never seen, and since nothing re-reconciles on a timer, a revocation
that landed there waited for the next unrelated change — on a quiet root,
the next restart. Exactly the gap watch_skills exists to close.

The watcher now attaches its listener before the initial reconcile and
starts its worker after. notify only sets an event, so a change arriving
mid-reconcile is recorded and picked up by the worker's first pass, while
holding the thread back keeps write_skills's one-root-one-reconcile
contract: the worker cannot race the caller's own reconcile over the same
manifest. A reconcile that raises detaches the listener on the way out,
since the caller is handed an exception rather than a watcher to close.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Brings in the withheld-answer fix for broken store answers, which the
materialization path above this branch has regression tests for.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Brings in the withheld-answer fix the reconcile regression tests below
depend on.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Covers the reconcile side of the withheld-answer fix: a listing that is
not a mapping leaves every managed file alone rather than reading as a
full revocation, and an answer served under a different key writes
nothing, is reported against the key that was asked for, and does not
reach that other key's file.

Each one previously deleted a file and reported a clean run.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The protocol reader took payloads[0]'s intentCode and applied it to the
skill object set, which is what the delivery protocol requires — one
payload per credential, read the first intent, tolerate the rest — but it
left the assumption behind that rule undocumented and unguarded. If the
one-payload guarantee ever widens, an xfer-full for another payload would
start an empty pending set and the next payload-transferred would publish
it: every skill reported revoked, and with pruning on, a customer's files
deleted.

The first payload is still the payload that is read. What is new is that
the reader now knows which payload skills actually arrive on — learnt from
the intent's id, or from the (p:<id>:<version>) selector, since no object
or transfer event carries a payload id of its own — and declines to apply
a transfer of any other, holding last known good, warning once, and
counting it in diagnostics.payloads_ignored. An intent describing more
than one payload warns once on its own, because that is the one case the
comparison cannot catch: another payload's transfer arriving before any
skill has been seen has nothing to be compared against.

Behaviour under one-payload delivery is unchanged, and a full transfer of
the skill payload still empties it — every skill deleted is a real state
the guard must not mask.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The SDK-facing FDv2 channel now delivers skills the way streamer #4681 and
gonfalon #70638 spell them: object kinds are open strings, the agent-skill
payload is classified `generic`, and every generic object carries only `key`,
`kind`, `version` and `object`, exactly like a flag. A skill arrives under
kind `skill` with its own version folded into the key as `<key>:<version>`.
There is no `category` field and no `objectVersion` field; both came from an
earlier streamer draft that never shipped.

Identification is now the kind alone. The wire key is split in one place,
`_split_wire_key`, and both the put and the delete translation go through it.
A key that will not split cleanly is held rather than dropped — version-less,
or with the offending text as its version — so verification withholds it with
`invalid_version` under a key the caller recognises; only a key with nothing
before the delimiter is dropped, since there is no identity to hold it under.

`SDK_DATA_MODEL_VERSION` goes with it: the connection's `mv` parameter only
accepts flag model versions, and generic payloads ignore it. The transport
stops sending it in the following change.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
FDv2SkillStore puts LaunchDarkly's SDK-facing FDv2 channel underneath the
protocol layer: GET /sdk/poll and GET /sdk/stream, authenticated with the
environment's server-side SDK key, streaming by default. It carries
basis across requests, sends If-None-Match and treats 304 as a current
answer, retries with capped jittered backoff, honours Retry-After only up
to max_backoff, gives up after a bounded run of consecutive failures
where a committed payload resets the count, and keeps serving last known
good through every failure. A mobile key or client-side environment ID
is refused in the constructor. Standard library only.

close interrupts the socket rather than only setting a flag, because the
delivery thread lives in a read no flag can reach; without that every
shutdown of a healthy stream waited out the full join timeout.

The no-store message now names FDv2SkillStore first, and watch_skills
points at it as the store with a delivery transport.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
_Requester.stream wrapped only the connect as recoverable, so a read
timeout, reset or truncated chunk in the body reached the delivery loop
as whatever the socket raised. The loop read that as a bug and gave up:
delivery stopped for the process lifetime, taking updates and
revocations with it, the first time a socket died. read_timeout exists
to bound a stream that has gone quiet so the loop can reconnect, and
tripping it did the opposite.

The body now carries the same promise the connect already did. Wrapping
the line source rather than the whole read keeps protocol reader errors
out of it: those are raised from the consumer's loop body, where they
still surface as the bugs they are.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The client-side cap was 64 KiB, close enough to the platform's own limit
that any backend increase would force an SDK release. Raise it to 10 MiB
so the guard stays a backstop against absurd input rather than a second
enforcement of a bound this side does not own, and the real limit can
grow without the SDKs moving.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…n promptly

Three faults in the delivery loop, all of which left the store reporting
itself healthy while doing less than it claimed.

**An up-to-date stream tripped the failure cap.** The consecutive-failure
count reset only at a commit, and an environment whose skills are not
changing answers every reconnect with `intentCode: "none"` and transfers
nothing. A stream only ever ends by being dropped, so each recycle of a
perfectly healthy idle connection counted as a failure — announced with a
`goodbye` or not — and `max_consecutive_failures + 1` of them stopped
delivery for the process lifetime, revocations included. The reset on
commit covered only the case where content had changed, which is the case
that was easy to test and not the case that runs in production.

`_TransferOutcome` now reports `up_to_date`, and a complete answer that
transfers nothing breaks the row of failures exactly as a commit does. An
intent this module does not recognise is still not an answer.

**`close` could not interrupt a poll.** The interrupt reached the streaming
connection only, so polling parked in its request with nothing to reach and
`close` returned when its join timed out — on a 300s-class request, long
after the process meant to exit. `_Requester` now tracks the response of a
poll in flight and offers `interrupt`, which `close` calls alongside the
stream's own. A request still inside its connect has no response to reach;
that one is bounded by `read_timeout`, and `start` no longer leaves the
store inert when a join times out around it. An interrupt we asked for is
no longer recorded as a delivery failure.

**`close` left a waiter parked.** `wait_for_skills` waited on the first
payload alone, so a shutdown racing a waiter added the waiter's whole
timeout to it. Delivery ending is now its own event: a waiter is released
by a payload, a give-up or a close, and reports whether a payload actually
arrived rather than merely that it was let go. That also settles what
`_give_up` had been quietly asserting — it set the first-payload flag to
unblock waiters, which made `wait_for_skills` answer `True` for a store
holding nothing.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A stream only ever ends by being dropped, and LaunchDarkly — and any proxy
in between — recycles a long-lived one. Every reconnect therefore logged
"Skill delivery failed" at WARNING, for as long as the process ran. Until
the previous commit that noise was bounded, because an idle stream gave up
after eleven recycles and went quiet; now that delivery correctly survives
them, it would run forever and describe a healthy store as failing.

A connection that got a complete answer before it ended — a committed
payload, or an up-to-date intent — delivered everything it was asked for,
so its reconnect is now DEBUG and says so. A connection that ended without
answering is the case the warning exists for and still gets it: a connect
that never landed, or a transfer that died part-way through.

Filling a customer's logs with a fault they do not have is not merely
untidy; it teaches them that the level which means something can be
ignored.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Stacked on the protocol-layer PR (`xie/skills-fdv2-protocol`). Third of
three PRs split out of #69, and the one that makes the feature real: the
network underneath the protocol reader, exported as `FDv2SkillStore`.

## Why this shape

Skill content arrives over `GET /sdk/poll` and `GET /sdk/stream`,
authenticated with the environment's server-side SDK key. These are the
SDK-facing endpoints the base SDK's FDv2 data source uses, and the
channel that payload signing will eventually cover. No private route is
involved, and no credential other than the environment's own SDK key
ships to a customer host. Standard library only, so the content path
adds no dependency to a package whose sole runtime dependency is
`opentelemetry-api`.

## What's here

**`FDv2SkillStore`.** Authenticates, streams (default) or polls, carries
`basis` across requests, sends `If-None-Match` and treats 304 as a
first-class current answer, and serves `get_object` / `all_objects` /
`add_listener` / `remove_listener` from what the protocol reader has
committed. Capped jittered backoff; `Retry-After` honoured but clamped
to `max_backoff` and rejected when non-finite; bounded
consecutive-failure retries, where a committed payload resets the count.
One network timeout, `read_timeout`, whose default follows the mode: 10s
for a whole poll, 300s between reads on a stream. A mobile key or
client-side environment ID raises from the constructor. Last known good
survives every failure; `diagnostics` and `failed` report the
degradation.

**`close` interrupts the socket.** The delivery thread parks in a read
no flag can reach, and closing a urllib response from another thread
does not unblock CPython's buffered reader, so `_interrupt_read` shuts
the socket down underneath it. Without that every shutdown of a
*healthy* stream blocked for the full join timeout.

**Above the interface**, two strings: `NO_STORE_MESSAGE` now names
`FDv2SkillStore` first, since it is the first thing a user sees on a
missing store and offering only the development store was wrong once a
production transport existed; and `watch_skills`' refusal message names
it as the store with a delivery transport.

## Bugs found and fixed while testing the loop

Five, all sharing one shape: the store stopped delivering while
continuing to report itself healthy.

- **The consecutive-failure counter never reset in stream mode.**
`_stream_once` always ends by raising, so a reset on return was
unreachable and `failures` grew for the whole process lifetime. Eleven
*fully successful* payload transfers were enough to trip
`max_consecutive_failures` and stop delivery for good, revocations
included. A commit now resets the count, in `_apply`.
- **A non-finite `Retry-After` killed the delivery thread.**
`float("inf")` parses, and `Event.wait(inf)` raises `OverflowError` from
inside the recoverable-error handler. Non-finite values are rejected and
every honoured delay is clamped to `max_backoff`.
- **`close()` during the initial connect waited out its full join
timeout.** `self._connection` was assigned after the connect returned,
so a `close()` in that window found nothing to interrupt. The stop flag
is re-checked immediately after the assignment.
- **`close()` blocked for the full join timeout on every healthy
stream.** See `_interrupt_read` above.
- **A stream interrupted by our own `close` was reported as a delivery
failure.**

Also: `connect_timeout` was accepted and never used, so a poll against a
black-holed host hung for 300s rather than 10. It is gone, with the
request timeout now chosen by mode, and `TestTimeouts` measures the
bound against a socket that accepts and never answers.

## Tests

> **Rebase note.** The previous push of this branch had silently
reverted the protocol PR's last commit (payload identity:
`payloads_ignored`, `_is_foreign_payload`, `TestPayloadIdentity`).
Rebasing onto the updated protocol branch restored it; the full suite
passes with it present.

`_FakeFDv2Endpoint` is an in-process `ThreadingHTTPServer` implementing
the wire contract, so request construction and header handling are
exercised over real sockets rather than mocked. Covers skill put/delete
over the wire, mixed payloads, 304, `basis` round-tripping,
reconnect/backoff in both modes, `Retry-After` including non-finite and
oversized values, bounded retries and the reset on commit, prompt
shutdown during connect and during a healthy stream, hashless envelopes
end to end through the accessors, server-side-only credentials,
timeouts, and `watch_skills` over the transport: a wire-level revocation
pruning a file without a restart.

Full suite 1629 passing, 11 skipped; `ruff`, `ruff format`, and `mypy`
clean.

## Open items, none in this PR's scope

- 🔴 **`contentHash` is not on the wire yet.** Against a real environment
today every skill resolves to nothing. This PR makes that loud (an error
per hashless object, a summary per wholly-hashless payload,
`diagnostics.hashless_objects`) rather than surviving it.
- 🔴 **Server-side skill delivery is not deployed.** The wire shape this
store reads — kind `skill`, key `<key>:<version>`, generic payload — is
what [streamer
#4681](launchdarkly/streamer#4681) and [gonfalon
#70638](launchdarkly/gonfalon#70638) emit; both
are still open. No account can receive skill objects until they ship and
the producer is enabled.
- 🟡 **FDv2 is opt-in per account.** A real environment returns 403
today; the store reports it as fatal and explains what to do.
- ~~🟡 **`mv` is a guess.**~~ Resolved: the request sends no `mv`. That
parameter selects the *flag* data model and the connection rejects any
value but the flag default, while the generic agent-skill payload is
served regardless of it. The `data_model_version` constructor argument
is gone with it.
- 🟡 **No payload signing** on this channel yet, so Beta is TLS-only.
- 🟡 **The connection also carries the environment's flags.** Skipped and
counted; a transport property, not fixable here.
- 🟡 **`ld-relay` does not speak the FDv2 endpoints**, so relay-only
deployments cannot receive skills in Beta.

**Nothing here has touched a real LaunchDarkly environment**, because it
cannot yet.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Overview**
> Adds **`FDv2SkillStore`**, a production `SkillStore` that pulls agent
skills over LaunchDarkly’s SDK FDv2 **`/sdk/poll`** and
**`/sdk/stream`** endpoints (stdlib HTTP, background delivery thread,
stream-by-default). It implements **`SkillStore`** (`get_object`,
listeners, etc.) on top of the existing protocol reader, plus
**`StoreDiagnostics`**, **`wait_for_skills`**, capped backoff with
**`Retry-After`**, and **`close`** that interrupts blocked socket reads
so shutdown is prompt.
> 
> **Public surface:** `FDv2SkillStore` and `StoreDiagnostics` are
exported from the package; README documents production setup with
`init_client` and `watch_skills`. Server-side SDK keys only;
mobile/client credentials are rejected. Outages keep last-known-good
content; accessors above the store are unchanged.
> 
> **Delivery-loop fixes** bundled here: reset consecutive-failure counts
on successful commits / up-to-date answers (so healthy stream recycling
does not stop delivery), safe handling of non-finite **`Retry-After`**,
and not treating intentional **`close`** interrupts as transport
failures. Removed unused **`connect_timeout`**; **`read_timeout`** is
the single knob with mode-specific defaults.
> 
> **Tests:** in-process fake FDv2 server exercises poll/stream,
basis/ETag/304, revocations, retries, timeouts, hashless payloads, and
**`watch_skills`** over the transport.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
88c225e. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
XieX and others added 3 commits September 16, 2026 12:35
These modules ship in a public package and customers read them to learn how to
consume the SDK, so the comments should explain the code, not the project.

Removed: references to CI runners and sibling SDK repositories; roadmap and
prioritization notes; cross-language parity used as justification (the
constraints those defended, such as `sort_keys` on the integrity record, are
kept and restated in terms of what they guarantee); pointers to `agents.md`,
which customers do not have; a test class name cited as a guarantee; notes about
what tests intercept or inject; and a local "verified on CPython 3.12" aside.

Also removed the development history — "this used to be", "no longer does",
"before this check existed" — which a reader who never saw the earlier version
cannot use. Replaced "seam" with "interface" throughout, including in section
headings, and the first-person plural with "the SDK" or "the application".

Compressed the essay-length rationale on internal helpers and module-private
constants down to the invariant plus its reason. The public API reference —
`SkillStore`, `write_skills`, `FDv2SkillStore`, the accessors and the exported
types — is kept thorough, since that is what a consumer reads first; the
`FDv2SkillStore` example now checks `wait_for_skills`, matching the README.

No behavior change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…in code

The security rationale in `safe_fs.py`, `skills_fs.py` and `skills_core.py` was
a threat model written as comments: why a path check cannot hold, what a swapped
root redirects, what each flag defends against, what breaks if a bound moves.
It is knowledge worth keeping, but a customer reading these modules to learn how
to consume the SDK is not its audience, and `agents.md` already had the sections
for it — `Security posture`, `Descriptor-pinned filesystem access`, `Telemetry`
and `The integrity-failure log record`.

So the argument moves there and the code keeps the invariant plus a one-line
reason, with the booby-trapped spots still warned about in place: do not
"correct" the `os.supports_dir_fd` probe names, do not reach for
`errors="surrogatepass"`, do not carry the first verification pass forward, do
not drop `sort_keys`, do not widen the adoption exception or the temp sweep.
Each module docstring names its invariants and points once at the note, rather
than arguing at every call site.

`skills_fs.py` goes from 37% comment lines to 33%, `safe_fs.py` from 51% to 46%,
against a 22% baseline for the package's other modules. The rest is public API
reference, which stays.

Also folds two facts from the earlier fixes into the note (the manifest read cap
and the two-sided `manifestVersion` bound), and removes the last two internal
references, both in the README: a CI-runner aside and a sibling-SDK parity
mention that the source sweep did not cover.

No behavior change.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`test_no_ld_track_calls_from_write_skills` and
`test_no_ld_track_calls_from_accessors` assert that `track` was never called,
but `init_client` flushes `$ld:ai:sdk:info` on the first client of a process and
`reset_skill_state` does not reset that reporting state. Whether the event fires
therefore depends on what ran earlier in the session: both tests passed in a
full run and failed when their file ran alone, which also makes them fragile
under any test sharding.

Reset the mock after `init_client`, since the flush belongs to it rather than to
the code under test. Every skills test file now passes both in isolation and in
the full suite.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

@cursor cursor Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 4bc12c0. Configure here.

Comment thread packages/client/src/launchdarkly_ai_server/skills_fdv2.py
XieX and others added 12 commits September 16, 2026 12:55
Every FDv2 request carries the server-side SDK key in Authorization. A
plain http:// base URI sent it in cleartext, and urllib's default
redirect handler copied it onto any 3xx target, so a redirecting proxy or
misconfigured private instance would forward the key to an arbitrary host.

FDv2SkillStore now refuses a base URI that is not https://, except plain
http:// to a loopback host (localhost, 127.0.0.1, ::1) for local test
doubles. The requester's opener installs a redirect handler that follows
nothing, so any 3xx other than 304 surfaces as a fatal, non-retried
failure that says redirects are not followed. The poll's 304 path is
unchanged and now pinned by a test.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
… them

Verification caps a skill's content at 10 MiB, but the FDv2 transport read a
whole poll body and accumulated a whole SSE event before that cap could run,
so a large or hostile response was buffered unbounded in memory.

MAX_RESPONSE_BYTES (64 MiB) is a memory backstop for the transport, deliberately
far above any legitimate payload and independent of the per-skill content cap.
Poll bodies are read in chunks up to the bound; stream lines are read with a
size argument and each event's bytes are totalled. Crossing it raises
_RecoverableTransportError: nothing from the body or event is applied, the
reader abandons the in-flight payload, the failure is recorded in
connection_failures/last_error, and delivery retries while the committed set
stays served.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
The managed root and every destructive operation under it were already
descriptor-relative, but three reads that decide which branch runs still
resolved paths after the pin: the existence probe and compare read in
_write_one, the directory check and listing in the orphan sweep, and the
existence probe in _prune_one. A root or skill directory swapped after the
pin could therefore choose the branch. For the prune that meant the probe
could be answered "absent" from the attacker's tree, the unlink skipped,
the manifest entry dropped and `removed` reported while the revoked skill
stayed on disk.

Each of _write_one and _prune_one now pins <root>/<key> relative to the
root descriptor before deciding anything and holds it through the action:
the probe is a follow_symlinks=False stat on the skill descriptor, the
compare read goes through _read_regular_file with dir_fd, and the sweep
lists os.listdir(fd). open_directory_nofollow raises the new
DirectoryMissing (a ValueError subclass) on ENOENT/ENOTDIR so absence is
learned from the pin itself rather than a separate path probe. The path
checks in _unsafe_path_reason stay as defense in depth; the lstat floor
keeps its path-based code.

Tests add root-swap races fired the instant before each decision read and
extend the no-absolute-path audit to stat, open and listdir. Docs no longer
describe a residual for reads under the root.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
``_give_up`` published the terminal reason under the lock but ended delivery
after the log line, outside it, leaving the dying thread observable in a
half-published state. A ``start`` that landed in that window re-armed the
waiters, saw a thread that was alive but no longer delivering, and returned
without spawning a replacement — a store reporting no failure with nothing
left to deliver, and a waiter that could only time out.

Publish the reason and the end of delivery together under the lock, so the
only work left outside it is the log line, and have ``start`` read the reason
before the re-arm clears it: a thread that has given up is not a delivering
one, however alive it looks.

Return the retry budget on a re-arm as well. A store that gave up at its
failure limit carried the spent count into the restarted run and gave up
again on its first recoverable failure, without retrying once.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`FDv2SkillStore` built both `/sdk/poll` and `/sdk/stream` from a single
`base_uri`, so the default configuration sent its streaming request to
`sdk.launchdarkly.com`. LaunchDarkly serves streaming from a separate
host, and `mode="stream"` is this store's default (TESTING.md §3.25), so
this was the default path rather than an edge case: the first contact
with a real environment would have gone to the wrong host.

Both base server-side SDKs ship the two as distinct defaults, which is
the evidence this follows:

  ldclient.config.Config        base_uri='https://app.launchdarkly.com'
                                stream_uri='https://stream.launchdarkly.com'
  @launchdarkly/js-server-sdk-common
                                baseUri: 'https://sdk.launchdarkly.com'
                                streamUri: 'https://stream.launchdarkly.com'

`DEFAULT_BASE_URI` here already pointed at the FDv2 polling host
(`sdk.launchdarkly.com`, not `ldclient`'s older `app.` value), so only
the streaming host is new. Adds `DEFAULT_STREAM_URI` and a `stream_uri`
keyword, mirroring `skills-fdv2.ts`: a `base_uri` given on its own still
applies to both endpoints, so a relay or a private instance serving both
from one host needs only the one option, and naming both overrides them
independently. `_require_https_base_uri` becomes `_require_https_uri`
and takes the option name, so a cleartext `stream_uri` is refused under
its own name.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Two independent transport defects.

**`Retry-After: 0` had no floor.** `_retry_after_seconds` returns
`max(0.0, seconds)`, and the retry site capped the value but never
floored it, so a server — or an intermediate proxy — answering `0` had
the delivery loop reconnect as fast as it could schedule, spending the
whole of `max_consecutive_failures` in milliseconds and hammering the
endpoint on the way. It is bounded, so nothing runs away, but the retry
budget is gone and `Retry-After` is honoured in the least useful
direction. Floored at `initial_backoff`, the same floor our own backoff
starts from, matching `skills-fdv2.ts`.

A short `Retry-After` is therefore raised to `initial_backoff`, which is
what made `test_a_retry_after_header_is_honoured` discriminate before:
it asked for 0.25s against a 5s initial backoff. Rewritten to ask for
*longer* than our own backoff instead, so honouring the header is still
the only way the assertion can pass, and
`test_a_retry_after_header_is_parsed_off_the_wire` likewise — it was
passing only because `poll_store`'s 0.05s `max_backoff` capped the
floored value, so it no longer told the two apart.

**`objects_revoked` counted tombstones for keys the store never held.**
The increment fired whenever a `delete-object` parsed, whether or not it
took anything away. The counter is operator-facing and gets read exactly
when somebody is working out whether a revocation landed (TESTING.md
§3.25, "Counters are assertable facts"), so an inflated figure misleads
at the worst moment. Gated on `_SkillObjectSet.delete` having returned
something. `changes` still carries every tombstone, so listeners are
unaffected.

Note this is a divergence from TypeScript rather than a port of it:
`skills-fdv2.ts`'s `deleteObject` increments unconditionally too, and
its `keysFullyRevoked` applies to the full-transfer revoke-by-omission
diff, which this side does not implement. The same fix is owed there.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Three §3.25 deviations, all in the transport's lifecycle and reconnection
rules. Grouped because each one's existing test pinned the old answer and
had to move in the same change.

**`close()` is final** (§3.25 lifecycle). A subsequent `start()` now
raises instead of resuming delivery. Finality is what gives `close()` a
postcondition a caller can rely on — delivery has stopped — including
when the join times out on a thread parked somewhere no interrupt
reaches. A store that could be restarted from there leaves the caller
unable to tell whether delivery stopped, and a restart that silently
never delivered again is the failure this forecloses. To resume, build a
new store. Giving up at the failure bound is *not* closing, so a store
that gave up can still be restarted and the re-arm path is unchanged.
`test_a_restarted_store_waits_again` therefore drives the give-up path
now, and `test_a_close_that_timed_out_leaves_the_store_restartable`
becomes `..._is_still_final` — it was asserting exactly the behaviour
finality removes.

**HTTP 404 is fatal** (§3.25 reconnection). A 404 on `/sdk/poll` or
`/sdk/stream` means the endpoint does not exist for this credential or
instance — a mistyped base URI, typically — and no reconnect produces
one. It was recoverable, so it burned the whole retry budget first.

**HTTP 400 is retried exactly once, then fatal** (§3.25 reconnection). A
400 is what a stale `basis` selector looks like: the request carried
state the server no longer recognises, and a connection built from
nothing fixes it. It was fatal, so that repair never ran. Implemented as
`_StaleRequestStateError`, a `_RecoverableTransportError` subclass whose
handling drops `basis` and `etag` and asks for a full transfer — and
gives up when there was neither to drop, since a request carrying no
client state was refused on its own terms. That bound is what keeps this
from being "400 is recoverable", and it needs no counter.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`add_listener` recorded a registration for any kind and then never
notified it, on both shipped stores — `InMemorySkillStore`, whose `put`
only accepts skill objects, and `FDv2SkillStore`, which only ever
delivers `SKILL_OBJECT_KIND`. TESTING.md §3.21 now requires both to
raise.

The argument is §3.26's own, the one that already makes `watch_skills`
refuse a store with no `add_listener` at all rather than degrading to a
one-shot reconcile: a listener that silently never fires "looks exactly
like a watcher whose skills never changed". Registering on a kind the
store will never deliver is the same failure with the same signature,
and a store that accepted the registration has promised something it
cannot keep.

`ValueError` rather than `TypeError`: `kind` is a `str`, which is the
accepted type, carrying a value the store cannot serve — the same
distinction A.12 records for `write_skills` versus `get_skills`.
`remove_listener` for an unregistered kind stays a no-op, so a caller
tearing down need not track what it attached.

`test_put_does_not_notify_other_kind_listeners` pinned the old
behaviour and is replaced by the raise assertion.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…window

**`debounce=float("nan")` defeated the guard** (TESTING.md §3.26). `nan
< 0` is `False`, so it passed `if debounce < 0` and then collapsed the
coalescing window to nothing: `threading.Event().wait(nan)` returns
immediately, so every delivered object reconciled on its own with no
coalescing at all — the opposite of what the option is for. Now
`math.isfinite` is checked alongside the sign, matching how
`write_skills` already guards its `timeout`. `inf` is refused for the
same reason it is refused there: a window nothing ever leaves.

Also fills the §3.26 test gaps, which had no coverage either way:
negative and non-finite debounce, `on_reconcile` firing for subsequent
reports and not the initial one, a reconcile that raises not killing the
watcher, `prune` / `on_unavailable` pass-through, and an invalid root
raising out of `watch_skills` rather than into a worker thread's log.

**The coalescing test was one of the vacuous shapes §3.26 warns about**
— twelve puts inside a single synchronous listener pass, asserted with
an upper bound (`reconciles <= 2`). A burst that arrives before the
worker has woken collapses to one reconcile whether or not the debounce
exists, so that shape passes against an implementation with the
debouncing deleted. Replaced with six puts spread across one window, an
exact figure, and an assertion that the counter moved at all; verified
by mutation — removing the debounce sleep turns it red.

The exact figure is two, not one, and that is a real deviation from
§3.26's "exactly one reconcile per debounce window": this watcher clears
its wake flag *before* the window rather than after, so a change
arriving inside the window schedules a further pass instead of merging
into the reconcile that is about to run. TypeScript restarts its timer
on each notification and so does merge them. The behaviour is
deliberate and documented in `_run` (a redundant reconcile converges;
a missed one does not) and it avoids the starvation a restart-the-timer
debounce admits, so it is left alone here and raised separately rather
than changed under a test-coverage commit.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`parse_ai_config` gated on `if skills is not None`, so `skills: null`
was accepted and read as absent. TESTING.md §3.5 now calls this case out
specifically, and the reason is the reason it is worth a commit of its
own: read as absent, it makes `skill_refs` return `[]`, and a
`prune=True` reconcile then **deletes** previously-materialized skill
files on the strength of a field the SDK could not parse.

§3.21 establishes exactly this principle on the store path — reading a
malformed thing as absent "would let a tampered object look like a
deleted one … and would let prune delete the last known-good copy on
disk" — and it applies identically here. Failing the whole parse is the
louder and safer outcome, and it is what TypeScript already does.

Gated on key presence instead, so `_parse_skills` sees the `None` and
rejects it as a non-array, with `skills` in the message. There was no
Python test either way; both halves are now pinned, including that an
*absent* `skills` key is still valid, since rejecting `null` must not
cost backward compatibility for configs that simply have no `skills`.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`verified_bytes` encoded before checking the size cap, so content that
is both over the cap and carries a lone surrogate reported `not_utf8`.
TESTING.md §3.21 fixes the order as shape, then **size**, then
**encoding**, then hash, and that input is the one boundary where the
order is observable: without it, the code is whichever check the
implementation happens to reach first, and §3.21's "one code per failure
class" rule cannot be tested against it. Size first is also the cheap
check — running an encoding pass over a 10 MiB body before rejecting it
for being 10 MiB is a DoS foothold rather than a nicety.

Python cannot reorder these literally, because the size is a count of
encoded bytes and `str.encode("utf-8")` raises on an unpaired surrogate
rather than substituting. So the unencodable case now encodes a second
time with `errors="replace"`, purely to measure, and reports
`over_size_cap` or `not_utf8` in that order. Those replacement bytes are
never hashed and never returned — the `not_utf8` branch returns before
the hash comparison — which is what makes `errors="replace"` safe here
where `errors="surrogatepass"` is not safe anywhere: fabricated bytes
that reached the comparison could satisfy it. TypeScript arrives at the
same order for free, since `TextEncoder` substitutes U+FFFD silently
and its guard is an explicit round-trip check (A.12).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…README

`agents.md`'s POSIX-only justification claimed the TypeScript SDK "could
not match them at all — Node exposes no `*at()` family on *any*
platform, so its racy floor is universal rather than Windows-only." The
first half is still true; the second is not. TypeScript commit `0a15b10`
added a `SUPPORTS_PROC_FD` probe and `/proc/self/fd/<fd>/<name>`
addressing, which the Linux kernel resolves from the inode a descriptor
holds rather than from the name it was opened under — closing the swap
window there exactly as `*at()` does here. TypeScript's `lstat` floor
now applies on macOS and Windows only, the same shape as this side's.

The passage is load-bearing — it is why the Windows reparse-point checks
are not implemented — so the rewrite says explicitly that the decision
is unchanged and why: it never rested on TypeScript being equally
exposed, it rests on there being no Windows CI runner to verify the
checks against, which is still true of both repositories.

README, for the behaviour changes in this branch: the two transport
hosts and the `stream_uri` option, `close()` being final, `watch_skills`'
`debounce` unit and bound and its `on_reconcile` contract,
`add_listener` refusing a kind it will never deliver, and a non-array
`skills` field failing the config parse rather than reading as absent.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
`_ProtocolReader` built a fresh empty `_pending` for `xfer-full`, so a skill
the full transfer omitted was correctly dropped at `_payload_transferred` —
but `_changes` only ever accumulated from `_put_object` and `_delete_object`,
so nothing was published for the omitted skill.

A full transfer carrying other puts still wakes a watcher through those puts,
so the observable gap was the transfer carrying no puts at all: the
environment's last skill revoked. The store emptied while `changes` stayed
empty and `objects_revoked` stayed zero, `watch_skills` never reconciled, and
the skill's `SKILL.md` survived on disk until some unrelated change — in
exactly the case pruning exists for.

Port TypeScript's `revocationsBetween` / `keysFullyRevoked`: diff the
committed set against the incoming one before the swap, at `(key, version)`
granularity so a key whose version moved yields both a put for the arrival and
a tombstone for the departure, and count only keys that left the payload
entirely toward `objects_revoked` — the same rule `_delete_object` follows in
counting only a tombstone that took something away.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
XieX and others added 8 commits September 17, 2026 13:06
An HTTP 400 for a request carrying a `basis` selector or an etag means that
state may be one the server no longer accepts, so the transport drops it and
asks for a full transfer once before treating the status as fatal. That one
request was not guaranteed to go out: it was prepared and then measured against
the consecutive-failure bound like any other retry, so a 400 arriving on a
budget an outage had already spent gave up while holding the only request known
to repair it, and delivery stopped for the process lifetime over state the
store had just dropped.

The repair is now exempt from the bound. It cannot unbound the loop: the
repaired request carries no state, so a second 400 is fatal on its own, and any
other failure after it meets a budget still over the bound.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Tests for TESTING.md §3.21/§3.24 as just reconciled: a store answering
under a different key records the `ld.skills.integrity_failure` log record
with `reason_code: key_mismatch` and records no product signal.

`key_mismatch` cannot join `REASON_CODE_CASES` — that table is uniformly
driven through `all_skills`, and this code is decided at the retrieval
boundary after `verify_raw_skill` has passed, so it is unreachable from a
listing. It gets its own test and is unioned into the vocabulary
assertion, with the reason recorded there so the next reader does not try
to move it into the table.

Adds the redaction guard, called directly since no store can drive it, and
the listing-path case: an object listed under a disagreeing map key is
filed under its own key with neither surface firing. That one passes
already; it is a regression guard against a "fix" that would break every
multi-version store.

3 failing: no record is emitted yet, the vocabulary is short a token, and
`record_key_mismatch` does not exist. The no-signal half already passes —
the implementation is additive.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Implements the §3.21/§3.24 decision the previous commit's tests pin: a
store answering under a different key now writes the
`ld.skills.integrity_failure` log record with `reason_code: key_mismatch`,
and still records no product signal.

Adds `record_key_mismatch` beside `record_integrity_failure`, so the
single-emission-site rule still holds by reading one module, and widens
`IntegrityReasonCode` to nine tokens. The check stays where it was, at the
retrieval boundary: `verify_raw_skill` is unary and this comparison is
relational, so moving it inside would mean an optional expected-key
parameter that silently disables the check when a caller omits it.

The record carries both keys. `skill_key` keeps the meaning it has
everywhere else — the key requested — and the key the store answered under
goes in `served_key`, the one record-only field beyond the four, since it
is what makes a broken adapter diagnosable and prose in `reason` is not
parseable. No hash fields and no `version`: verification passed, so
neither the hashes nor the version is what disqualified the answer, and
reporting a served version beside a requested key would mix two frames in
one record.

Docs corrected in the same change: the README's `reason_code` table and
record field table gain rows, `skill_key` is described as the *requested*
key, and `AGENTS.md` records why `key_mismatch` cannot join
`REASON_CODE_CASES` — that table is driven uniformly through `all_skills`,
which cannot reach a code decided after verification passes.

Verified the emitted JSON is byte-identical to the TypeScript SDK's for
the same input, modulo `language`.

1875 tests passing, mypy and ruff clean.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A transfer this layer declines as foreign kept its contents out of the
store but still handed its selector up as the new basis, so the next poll
or stream resumed from someone else's payload while every diagnostic read
healthy. The check was also gated on a pending set, which a `none` intent
never builds — so a `none` for another payload was not even recognised as
foreign, and its selector was adopted outright.

Ask the question unconditionally and drop the basis of a payload whose
contents were thrown away, matching js-ai-sdk#67.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
``_poll_once`` held one ``_etag`` with no record of which request produced
it, and adopted it before the body was applied. Two consequences:

An ETag validates one representation of one resource, and the ``basis``
selector is part of the request that names it. Once a payload moved the
basis on, the etag from the response before it was still offered, so a
server validating it would be answering the question the store had stopped
asking. Held as a pair now, and offered only while the pair holds — the
base SDK keys its etag cache by request URL for the same reason. The cost
is one unconditional request after each commit, which was never going to be
a 304.

A body that broke off partway — an ``error`` or ``goodbye`` after an
announced transfer — left the payload it described unapplied, but its etag
was already stored. The next 304 then reported that store as current and
reset the failure count, where the 200 it replaced would have been retried
and eventually given up on. Adopted after the body is applied in full.

Ports js-ai-sdk#67.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The branch was two commits behind its base, which blocked CI: GitHub could
not build a merge ref, so no workflow ran on the head.

One conflict, in the stale-selector repair, where both sides added a line to
the same block and both belong — the base's `repairing_state = True`, which
keeps the one-shot repair out of the retry budget, and this branch's
`self._etag_basis = None`, which drops the etag's pairing along with the
etag. Resolved by keeping both.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Closes row 18 (AV-1, Beta revocation propagation bound) of the security design
review. The README already states the fast path: with the watcher running, a
delete-object removes a revoked SKILL.md within the debounce interval on a stream,
or within one poll interval. This adds the other half: a deployment that
reconciles once at boot and never runs the watcher has a revocation bound of
process lifetime, restart or an explicit re-run is the incident-response action,
and content an agent has already read into a conversation is out of reach at
this layer. The same pitfall is added to agents.md.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
…94)

Stacks on #93 -> #87

This should be the last of the python SDK fixes, ported over from the
Typescript SDK work.

## The gap

`_ProtocolReader._server_intent` builds a fresh empty `_pending` for
`xfer-full`, so a skill the full transfer omits is correctly dropped
from the committed set at `_payload_transferred`. But `_changes` only
ever accumulated from `_put_object` and `_delete_object`, so nothing was
published for an omitted skill.

Verified against the reader directly before the fix: after a full
transfer carrying a put for `pdf:3`, a second `xfer-full` carrying
**no** objects emptied the store while `outcome.changes` was `[]` and
`diagnostics.objects_revoked` stayed `0`.

A full transfer that carries other puts still wakes a watcher through
those puts, so the observable gap is the transfer carrying no puts at
all — the environment's last skill revoked. `watch_skills` then never
reconciles and the skill's `SKILL.md` stays on disk until some unrelated
change, which contradicts TESTING.md §3.26 ("a revocation delivered over
a live stream prunes the skill's files within `debounce` of arriving")
in exactly the case pruning exists for.

## The fix

Ports the shape TypeScript already has (`revocationsBetween` /
`keysFullyRevoked` in `typescript/packages/client/src/skills-fdv2.ts`,
called from `payloadTransferred` under `intent ===
INTENT_TRANSFER_FULL`):

- `_identity_of`, `_revocations_between`, `_keys_fully_revoked` —
module-level, placed where TypeScript has them, just above
`_ProtocolReader`.
- `_payload_transferred` diffs the committed set against the incoming
one **before** the swap when the intent is `xfer-full`, extends
`_changes` with the tombstones, and adds `_keys_fully_revoked(...)` to
`objects_revoked`.
- The diff is at `(key, version)` granularity to match `delete-object`,
so a key whose version moved yields both a put for the arrival and a
tombstone for the departure.

The two counting rules stay consistent: **per key** for the omission
diff (a version move counts zero), **per applied revocation** for
`delete-object` (#93's change, where `objects_revoked` only increments
when `_SkillObjectSet.delete` actually removed something).
`_keys_fully_revoked`'s docstring names that as the shared rule.

One doc touch: `add_listener` now says both ways of stating a revocation
arrive as a tombstone — a `delete-object`, and a full transfer that
stopped carrying the object.

## Tests

Four protocol-reader cases:

- a full transfer omitting a previously-held skill publishes a `{key,
version}` tombstone and increments `objects_revoked`;
- an omitted version-less object is reported with `version: None`, the
way a `delete-object` naming no version spells it;
- a version move publishes both ends and increments `objects_revoked` by
zero;
- an `xfer-changes` that mentions nothing revokes nothing — diffing a
delta would drop every skill it simply had no reason to mention.

Plus an end-to-end `test_a_full_transfer_that_omits_every_skill_prunes`
over the fake FDv2 endpoint: queue a put, then
`full_payload(state="basis-2")` with no objects, and assert the
`SKILL.md` is pruned.

These discriminate — with the source reverted, all four of the new cases
fail. (The `xfer-changes` guard passes either way, as it should; it
guards against applying the diff to the wrong intent.) The e2e case was
run five times for flakiness.

## Gate

From `python/`: `make test` (1872 passed, 11 skipped), `make typecheck`
(clean, 51 source files), `make lint`, `make format-check` — all clean.

🤖 Generated with [Claude Code](https://claude.com/claude-code), edited
by @XieX


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Overview**
> **FDv2 full transfers now surface revocations-by-omission** so
`watch_skills` and pruning behave like explicit `delete-object` events:
on `xfer-full`, the reader diffs committed vs pending at `(key,
version)`, extends `changes` with tombstones, and counts true key
removals in `objects_revoked` (version bumps emit both put and tombstone
but do not count as revoked).
> 
> **Polling/stream resume state is tightened** — declined or foreign
payloads no longer advance `basis`; ETags are only sent when they match
the current basis and are adopted only after a payload fully applies,
avoiding false `304` “healthy” states.
> 
> **Store key substitution is a first-class integrity outcome**: new
`key_mismatch` `reason_code` with `served_key` on the
`ld.skills.integrity_failure` log line only (no product signal), wired
from `resolve_from_store` when verification passed but the object’s key
≠ the requested key. Docs and tests cover the nine-token vocabulary,
listing vs pinned asymmetry, and boot-only `write_skills` revocation
limits.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
1ce4e53. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
…the TypeScript review (#93)

Fixes surfaced by the TypeScript code review that needed fixing on the
Python side. Includes bugs discovered with the Python implementation,
and contract changes made during the review that needed to be ported
over to Python.

| Commit | What |
| --- | --- |
| `6ac1577` | Streaming host and `stream_uri`, above |
| `c69d880` | `Retry-After: 0` floored at `initial_backoff`;
`objects_revoked` counts only revocations that removed something |
| `86fd04c` | `close()` is final; HTTP 404 fatal; HTTP 400 retried
exactly once from scratch, then fatal (§3.25) |
| `2f59b9a` | `add_listener` on a kind the store never delivers raises,
on both shipped stores (§3.21) |
| `daeedec` | Non-finite `debounce` rejected; the §3.26 watcher test
gaps filled and the coalescing test de-vacuumed (§3.26) |
| `4a204f8` | `skills: null` fails the config parse instead of reading
as absent (§3.5) |
| `030e8c3` | Verification checks size before encoding, so over-cap
content with a lone surrogate reports `over_size_cap` (§3.21) |
| `4092de7` | `agents.md`'s stale cross-language parity claim, and the
README |

## Behaviour changes worth a second look

- **`close()` no longer resumes.** `start()` on a closed store raises;
construct
a new one. Giving up at the failure bound is *not* closing, so that
restart
path is unchanged. Three existing tests pinned the old answer and moved
with
  the change.
- **`add_listener("flag", fn)` now raises `ValueError`** where it used
to record
  a listener that never fired.
- **`skills: null` now fails the whole config parse.** Previously
accepted.

🤖 Generated with [Claude Code](https://claude.com/claude-code), updated
by @XieX


<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Overview**
> Ports TypeScript review fixes into the Python **Agent Skills** stack:
**FDv2 delivery**, **store lifecycle**, **integrity telemetry**, and
**config parsing**, with matching README/`agents.md` updates.
> 
> **FDv2SkillStore** now treats polling and streaming as separate HTTPS
origins (`base_uri` / `stream_uri`, defaulting to `sdk.launchdarkly.com`
vs `stream.launchdarkly.com`). Transport behavior is tightened: HTTP
**404** is fatal; **400** with client state triggers one full reconnect
with state cleared, then fatals; declined foreign payloads no longer
advance the resume `basis`; full transfers synthesize revocation
tombstones when skills drop by omission; **`objects_revoked`** counts
only keys actually removed; poll **ETags** are tied to the `basis` they
were issued for; **`Retry-After: 0`** is floored at `initial_backoff`.
**`close()` is final** — **`start()`** on a closed store raises
(construct a new store to resume).
> 
> **Integrity and retrieval:** new **`key_mismatch`** reason when a
store returns verified content under the wrong key — emits the
**`ld.skills.integrity_failure`** log (with **`served_key`**) but
**not** the product integrity signal. **`verified_bytes`** uses a fixed
order (**size → encoding → hash**) so over-cap surrogate content reports
**`over_size_cap`**. **`add_listener`** on non-skill kinds **raises** on
both shipped stores instead of registering a no-op listener.
> 
> **Config / watcher:** explicit **`skills: null`** fails the whole AI
config parse (avoids prune deleting materialized files).
**`watch_skills`** rejects non-finite **`debounce`**; tests and docs
cover debouncing, **`on_reconcile`**, and boot-only revocation limits.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
6776390. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants