@passioncode-ai/fabric-agent-adapter 0.26.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (22) hide show
  1. package/CHANGELOG.md +90 -0
  2. package/README.md +6 -2
  3. package/package.json +1 -1
  4. package/plugins/fabric-agent-adapter/.claude-plugin/plugin.json +1 -1
  5. package/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/SKILL.md +3 -3
  6. package/plugins/fabric-agent-adapter/skills/adapting-projects-to-fabric/scripts/adapt_project.py +2 -2
  7. package/plugins/fabric-agent-adapter/skills/building-fabric-services/SKILL.md +22 -13
  8. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/board.md +174 -0
  9. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/protocol.md +2 -2
  10. package/plugins/fabric-agent-adapter/skills/building-fabric-services/references/usage.md +36 -1
  11. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/check_service.py +60 -2
  12. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-board.mjs +1104 -0
  13. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-hub.mjs +337 -0
  14. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric-service.mjs +211 -2
  15. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_board.py +1274 -0
  16. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_hub.py +397 -0
  17. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/fabric_service.py +294 -1
  18. package/plugins/fabric-agent-adapter/skills/building-fabric-services/scripts/sample_service.py +43 -2
  19. package/plugins/fabric-agent-adapter/skills/creating-fabric-agents/SKILL.md +3 -3
  20. package/plugins/fabric-agent-adapter/skills/working-with-fabric/SKILL.md +1 -1
  21. package/plugins/fabric-agent-adapter/skills/working-with-fabric/references/project-board.md +37 -7
  22. package/plugins/fabric-agent-adapter/skills/working-with-fabric/scripts/fabric_session.py +1 -1
@@ -0,0 +1,1274 @@
1
+ """A service agent answers a Project's requests on Fabric's project board (`fabric-project-comms/0.1`; contract DEC-0022,
2
+ DEC-0073, DEC-0077, DEC-0078; Fabric ADR-0149; FAA-12b, FAA-40). Standard library only; `fabric_hub.py` finds the hub.
3
+
4
+ What a responder does, in the contract's words (project-comms.md, "Request lifecycle", "Responders and fences"):
5
+
6
+ enroll (capability) → claim → read the message → accept (the exact digest) → [effect_begin] → [progress] →
7
+ [reply] → complete ({state, observed, summary?, evidence ≤ 8 sha256 artifacts})
8
+
9
+ `Responder` runs that loop inside the service process (no new process): one tick every 15 s ± 5 s, which claims when
10
+ idle and renews the lease (60 s of database time, renewed at about 20 s) while work runs. Before it advances a step it
11
+ writes and fsyncs a checkpoint, so a restart picks up exactly where the last answer was confirmed: `com.reconcile` for
12
+ work whose outcome is unknown, `com.responder_replace` with a transfer for accepted work (DEC-0078 hands back the new
13
+ attempts in the receipt's `transferred`; a Fabric that does not yet answer it leaves the work held — never claimed back).
14
+ It stops acting the moment the board says `fenced`, `lease_expired` or `authority_changed`.
15
+
16
+ THE REQUEST BODY IS DATA. The kit never hands a body to a model or a shell. `admit(request)` is the service's own input
17
+ gate, required: it answers None to admit or a sentence saying why not; a refusal accepts the request and completes it
18
+ `failed_known` with that sentence, so the requester learns it. What the handler does with an admitted body — and the
19
+ checks it needs before any model, tool or spend sees it — is the service's own responsibility.
20
+
21
+ A board session (`fabric.board.join`) is served the respond scope only: `com.status`, `com.list`, `com.get`,
22
+ `com.reply` (the fenced form), `com.enroll`, `com.claim`, `com.renew`, `com.accept`, `com.progress`, `com.effect_begin`,
23
+ `com.complete`, `com.reconcile`, `com.responder_replace`. This kit never sends `com.submit`, `com.cancel`,
24
+ `com.read_ack` or `com.directory` through one; a directory lookup belongs to a Project session, and `find_project`
25
+ checks such a page first (FAC-SEM-107: each Project once, each capability once per Project, compared as written)."""
26
+ from __future__ import annotations
27
+
28
+ import hashlib
29
+ import json
30
+ import math
31
+ from pathlib import Path
32
+ import random
33
+ import re
34
+ import secrets
35
+ import sys
36
+ import threading
37
+ import time
38
+ from typing import Any, Callable, Dict, List, Optional, Sequence
39
+
40
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
41
+ import fabric_hub as _hub # noqa: E402 - beside this file
42
+ import fabric_identifiers as _ids # noqa: E402 - beside this file (DEC-0076)
43
+ import fabric_service as _fs # noqa: E402 - beside this file
44
+
45
+ COMMS_PROTOCOL = "fabric-project-comms/0.1"
46
+ LEASE_SECONDS = 60.0
47
+ RENEW_SECONDS = 20.0
48
+ POLL_SECONDS = 15.0
49
+ POLL_JITTER_SECONDS = 5.0
50
+ DRAIN_SECONDS = 10.0
51
+ SUMMARY_MAX = 2000
52
+ EVIDENCE_MAX = 8
53
+ EVENT_SCHEMA = "urn:fabric:schema:board-responder-event:1"
54
+
55
+ #: The tools a board session is served (Fabric's respond scope); anything else is refused here, before it is sent.
56
+ RESPOND_TOOLS = frozenset(["com.status", "com.list", "com.get", "com.reply", "com.enroll", "com.claim", "com.renew",
57
+ "com.accept", "com.progress", "com.effect_begin", "com.complete", "com.reconcile",
58
+ "com.responder_replace"])
59
+ REFUSAL_CODES = frozenset(["invalid_arguments", "body_too_large", "not_authorized", "authority_changed",
60
+ "unsupported_capability", "unsupported_operation", "not_available", "idempotency_conflict",
61
+ "idempotency_window_expired", "capacity_exceeded", "digest_conflict", "revision_conflict",
62
+ "fenced", "lease_expired", "invalid_transition", "reconcile_required", "observation_required",
63
+ "cursor_reset_required", "immutable_participants"])
64
+ #: On these the attempt is no longer ours: stop acting at once (C4).
65
+ STOP_CODES = frozenset(["fenced", "lease_expired", "authority_changed"])
66
+ REQUEST_STATES = ("queued", "claimed", "accepted", "in_progress", "completed", "failed_known", "cancelled", "expired",
67
+ "outcome_unknown")
68
+ EFFECT_STATES = ("not_started", "started", "succeeded_observed", "failed_observed", "unknown")
69
+ TERMINAL = frozenset(["completed", "failed_known", "cancelled", "expired"])
70
+
71
+ _OPAQUE = re.compile(r"[A-Za-z0-9_-]{8,128}")
72
+ _PROJECT = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{0,191}")
73
+ _CAPABILITY = re.compile(r"[a-z][a-z0-9._-]{1,127}")
74
+ _SHA256 = re.compile(r"sha256:[a-f0-9]{64}")
75
+ _KEY = re.compile(r"[A-Za-z0-9._:-]{8,128}")
76
+ _TIMESTAMP = re.compile(r"\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})")
77
+ _URI = re.compile(r"[A-Za-z][A-Za-z0-9+.-]*:[^\s]+")
78
+ _SAFE = 2 ** 53 - 1
79
+
80
+
81
+ class BoardError(Exception):
82
+ """A board refusal (`code` from the contract's refusal codes) or a kit fault: `unreachable` (the hub did not answer;
83
+ a write may have been stored — send it again with the same key), `session-ended`, `not-in-scope`, `receipt-shape`,
84
+ `schema-unsupported`, `no-epoch`, `checkpoint`, `digest-mismatch`, `not-addressed`, `directory-invalid`,
85
+ `evidence`, `observation_required`. `str()` is one sentence and never carries a token or a body."""
86
+
87
+ def __init__(self, code: str, message: str, retryable: bool = False, op: Optional[str] = None,
88
+ data: Optional[Dict[str, Any]] = None):
89
+ super().__init__(message)
90
+ self.code, self.message, self.retryable, self.op, self.data = code, message, retryable, op, data or {}
91
+
92
+ def __repr__(self) -> str:
93
+ return "BoardError(%r, %r)" % (self.code, self.message)
94
+
95
+
96
+ class Stopped(Exception):
97
+ """Raised inside a handler (from `ctx.progress` / `ctx.begin_effect`) when the attempt is no longer this
98
+ responder's: stop at once and act no further."""
99
+
100
+
101
+ # --- the contract's digest (src/comms-digest.ts) ---------------------------------------------------------------
102
+
103
+ def comms_canonical(value: Any) -> str:
104
+ """RFC 8785 as the board takes it: members sorted by UTF-16 code unit, integers only (|n| ≤ 2^53−1), no lone
105
+ surrogate, no normalisation. Raises `ValueError` on anything else rather than guessing a spelling."""
106
+ if value is None or isinstance(value, bool):
107
+ return json.dumps(value)
108
+ if isinstance(value, int):
109
+ if abs(value) > _SAFE:
110
+ raise ValueError("canonical JSON admits integers within ±(2^53−1) only")
111
+ return str(value)
112
+ if isinstance(value, float):
113
+ if not math.isfinite(value) or not value.is_integer() or abs(value) > _SAFE:
114
+ raise ValueError("canonical JSON admits integers within ±(2^53−1) only")
115
+ return str(int(value))
116
+ if isinstance(value, str):
117
+ if any(0xD800 <= ord(c) <= 0xDFFF for c in value):
118
+ raise ValueError("canonical JSON refuses a lone surrogate")
119
+ return json.dumps(value, ensure_ascii=False)
120
+ if isinstance(value, (list, tuple)):
121
+ return "[%s]" % ",".join(comms_canonical(v) for v in value)
122
+ if isinstance(value, dict):
123
+ for k in value:
124
+ if not isinstance(k, str):
125
+ raise ValueError("canonical JSON has string keys only")
126
+ comms_canonical(k) # refuses a lone surrogate in a key too
127
+ keys = sorted(value, key=lambda k: k.encode("utf-16-be")) # big-endian UTF-16 bytes sort as code units
128
+ return "{%s}" % ",".join("%s:%s" % (comms_canonical(k), comms_canonical(value[k])) for k in keys)
129
+ raise ValueError("canonical JSON has no %s" % type(value).__name__)
130
+
131
+
132
+ def comms_digest(operation: str, value: Any) -> str:
133
+ """`sha256:<hex>` over `fabric-project-comms/0.1 NUL <operation> NUL <canonical JSON>` (the contract's `commsDigest`)."""
134
+ if not isinstance(operation, str) or operation == "" or "\0" in operation:
135
+ raise ValueError("an operation is a non-empty name without NUL")
136
+ data = "%s\0%s\0%s" % (COMMS_PROTOCOL, operation, comms_canonical(value))
137
+ return "sha256:" + hashlib.sha256(data.encode("utf-8")).hexdigest()
138
+
139
+
140
+ # --- closed shapes: what the kit reads back ------------------------------------------------------------------
141
+
142
+ def _is_int(v: Any, minimum: int) -> bool:
143
+ return isinstance(v, int) and not isinstance(v, bool) and minimum <= v <= _SAFE
144
+
145
+
146
+ def _closed(value: Any, at: str, required: Sequence[str], allowed: Sequence[str], problems: List[str]) -> bool:
147
+ if not isinstance(value, dict):
148
+ problems.append("%s is an object" % at)
149
+ return False
150
+ for key in required:
151
+ if key not in value:
152
+ problems.append("%s/%s is required" % (at, key))
153
+ for key in value:
154
+ if key not in allowed:
155
+ problems.append("%s/%s is not a member the contract names" % (at, key))
156
+ return True
157
+
158
+
159
+ def _attempt_problems(a: Any, at: str, problems: List[str]) -> None:
160
+ keys = ("id", "generation", "digest", "leaseExpiresAt")
161
+ if _closed(a, at, keys, keys, problems):
162
+ if not (isinstance(a.get("id"), str) and _OPAQUE.fullmatch(a["id"])):
163
+ problems.append("%s/id is a board id" % at)
164
+ if not _is_int(a.get("generation"), 1):
165
+ problems.append("%s/generation is an integer ≥ 1" % at)
166
+ if not (isinstance(a.get("digest"), str) and _SHA256.fullmatch(a["digest"])):
167
+ problems.append("%s/digest is sha256:<hex>" % at)
168
+ if not (isinstance(a.get("leaseExpiresAt"), str) and _TIMESTAMP.fullmatch(a["leaseExpiresAt"])):
169
+ problems.append("%s/leaseExpiresAt is a timestamp" % at)
170
+
171
+
172
+ def receipt_problems(value: Any, op: Optional[str] = None) -> List[str]:
173
+ """`comms-receipt.schema.json` at the pin, closed at every level (a seq or a holder is refused, C3), plus what a
174
+ schema cannot say: `transferred` answers only `com.responder_replace` (DEC-0078) and names each request once."""
175
+ problems: List[str] = []
176
+ allowed = ("ok", "repeated", "message", "thread", "at", "request", "slot", "attempt", "transferred")
177
+ if not _closed(value, "", ("ok", "repeated"), allowed, problems):
178
+ return problems
179
+ if value.get("ok") is not True:
180
+ problems.append("/ok is true")
181
+ if not isinstance(value.get("repeated"), bool):
182
+ problems.append("/repeated is a boolean")
183
+ for key in ("message", "thread"):
184
+ if key in value and not (isinstance(value[key], str) and _OPAQUE.fullmatch(value[key])):
185
+ problems.append("/%s is a board id" % key)
186
+ if "at" in value and not (isinstance(value["at"], str) and _TIMESTAMP.fullmatch(value["at"])):
187
+ problems.append("/at is a timestamp")
188
+ if "request" in value:
189
+ r = value["request"]
190
+ keys = ("id", "state", "effect", "revision")
191
+ if _closed(r, "/request", keys, keys, problems):
192
+ if not (isinstance(r.get("id"), str) and _OPAQUE.fullmatch(r["id"])):
193
+ problems.append("/request/id is a board id")
194
+ if r.get("state") not in REQUEST_STATES:
195
+ problems.append("/request/state is a request state")
196
+ if r.get("effect") not in EFFECT_STATES:
197
+ problems.append("/request/effect is an effect state")
198
+ if not _is_int(r.get("revision"), 1):
199
+ problems.append("/request/revision is an integer ≥ 1")
200
+ if "slot" in value:
201
+ s = value["slot"]
202
+ keys = ("project", "capability", "generation", "leaseExpiresAt")
203
+ if _closed(s, "/slot", keys, keys, problems):
204
+ if not (isinstance(s.get("project"), str) and _PROJECT.fullmatch(s["project"])):
205
+ problems.append("/slot/project is a Project id")
206
+ if not (isinstance(s.get("capability"), str) and _CAPABILITY.fullmatch(s["capability"])):
207
+ problems.append("/slot/capability is a capability name")
208
+ if not _is_int(s.get("generation"), 1):
209
+ problems.append("/slot/generation is an integer ≥ 1")
210
+ if not (isinstance(s.get("leaseExpiresAt"), str) and _TIMESTAMP.fullmatch(s["leaseExpiresAt"])):
211
+ problems.append("/slot/leaseExpiresAt is a timestamp")
212
+ if "attempt" in value:
213
+ _attempt_problems(value["attempt"], "/attempt", problems)
214
+ if "transferred" in value:
215
+ t = value["transferred"]
216
+ if op is not None and op != "com.responder_replace":
217
+ problems.append("/transferred answers com.responder_replace only (DEC-0078)")
218
+ if not isinstance(t, list) or not 1 <= len(t) <= 64:
219
+ problems.append("/transferred is 1 to 64 items")
220
+ else:
221
+ seen = set()
222
+ for i, item in enumerate(t):
223
+ at = "/transferred/%d" % i
224
+ keys = ("request", "revision", "attempt")
225
+ if _closed(item, at, keys, keys, problems):
226
+ rid = item.get("request")
227
+ if not (isinstance(rid, str) and _OPAQUE.fullmatch(rid)):
228
+ problems.append("%s/request is a board id" % at)
229
+ elif rid in seen:
230
+ problems.append("%s/request names a request already listed (each request once, DEC-0078)" % at)
231
+ seen.add(rid)
232
+ if not _is_int(item.get("revision"), 1):
233
+ problems.append("%s/revision is an integer ≥ 1" % at)
234
+ _attempt_problems(item.get("attempt"), at + "/attempt", problems)
235
+ return problems
236
+
237
+
238
+ def refusal_problems(value: Any) -> List[str]:
239
+ """`comms-refusal.schema.json`: `{error: {code, message, retryable}}`, closed, a known code, one sentence ≤ 300."""
240
+ problems: List[str] = []
241
+ if _closed(value, "", ("error",), ("error",), problems):
242
+ e = value["error"]
243
+ keys = ("code", "message", "retryable")
244
+ if _closed(e, "/error", keys, keys, problems):
245
+ if e.get("code") not in REFUSAL_CODES:
246
+ problems.append("/error/code is a refusal code the contract names")
247
+ if not (isinstance(e.get("message"), str) and 1 <= len(e["message"]) <= 300):
248
+ problems.append("/error/message is 1 to 300 characters")
249
+ if not isinstance(e.get("retryable"), bool):
250
+ problems.append("/error/retryable is a boolean")
251
+ return problems
252
+
253
+
254
+ def directory_findings(page: Any) -> List[Dict[str, str]]:
255
+ """FAC-SEM-107 (DEC-0077), the contract's `commsDirectory`: a Project listed twice, or a capability listed twice
256
+ within a Project, compared exactly as written (Project ids are opaque and capability names are names, not URIs —
257
+ so not by normal form). The finding names the second entry. Never raises."""
258
+ findings: List[Dict[str, str]] = []
259
+ projects = page.get("projects") if isinstance(page, dict) else None
260
+ seen = set()
261
+ for p, project in enumerate(projects if isinstance(projects, list) else []):
262
+ if not isinstance(project, dict):
263
+ continue
264
+ pid = project.get("id")
265
+ if isinstance(pid, str):
266
+ if pid in seen:
267
+ findings.append({"code": "FAC-SEM-107", "instancePath": "/projects/%d/id" % p,
268
+ "message": "a directory page lists each Project once: %s is listed again" % pid})
269
+ seen.add(pid)
270
+ caps = project.get("capabilities")
271
+ names = set()
272
+ for c, entry in enumerate(caps if isinstance(caps, list) else []):
273
+ if not isinstance(entry, dict) or not isinstance(entry.get("capability"), str):
274
+ continue
275
+ if entry["capability"] in names:
276
+ findings.append({"code": "FAC-SEM-107", "instancePath": "/projects/%d/capabilities/%d/capability" % (p, c),
277
+ "message": "a Project lists each capability once: %s is listed again" % entry["capability"]})
278
+ names.add(entry["capability"])
279
+ return findings
280
+
281
+
282
+ def directory_problems(page: Any) -> List[str]:
283
+ """`comms-directory.schema.json`, closed at every level (no count, holder or generation), then FAC-SEM-107."""
284
+ problems: List[str] = []
285
+ if not _closed(page, "", ("protocol", "snapshot", "projects", "cursor"), ("protocol", "snapshot", "projects", "cursor"), problems):
286
+ return problems
287
+ if page.get("protocol") != COMMS_PROTOCOL:
288
+ problems.append("/protocol is %s" % COMMS_PROTOCOL)
289
+ snap = page.get("snapshot")
290
+ if _closed(snap, "/snapshot", ("readAt",), ("readAt", "stale"), problems):
291
+ if not (isinstance(snap.get("readAt"), str) and _TIMESTAMP.fullmatch(snap["readAt"])):
292
+ problems.append("/snapshot/readAt is a timestamp")
293
+ if "stale" in snap and not isinstance(snap["stale"], bool):
294
+ problems.append("/snapshot/stale is a boolean")
295
+ if page.get("cursor") is not None and not (isinstance(page.get("cursor"), str) and _OPAQUE.fullmatch(page["cursor"])):
296
+ problems.append("/cursor is a board id or null")
297
+ projects = page.get("projects")
298
+ if not isinstance(projects, list) or len(projects) > 100:
299
+ problems.append("/projects is at most 100 Projects")
300
+ return problems
301
+ for p, project in enumerate(projects):
302
+ at = "/projects/%d" % p
303
+ if not _closed(project, at, ("id", "name", "capabilities"), ("id", "name", "capabilities"), problems):
304
+ continue
305
+ if not (isinstance(project.get("id"), str) and _PROJECT.fullmatch(project["id"])):
306
+ problems.append("%s/id is a Project id" % at)
307
+ if not (isinstance(project.get("name"), str) and 1 <= len(project["name"]) <= 120):
308
+ problems.append("%s/name is 1 to 120 characters" % at)
309
+ caps = project.get("capabilities")
310
+ if not isinstance(caps, list) or len(caps) > 64:
311
+ problems.append("%s/capabilities is at most 64 entries" % at)
312
+ continue
313
+ for c, entry in enumerate(caps):
314
+ cat = "%s/capabilities/%d" % (at, c)
315
+ if _closed(entry, cat, ("capability", "responder"), ("capability", "responder"), problems):
316
+ if not (isinstance(entry.get("capability"), str) and _CAPABILITY.fullmatch(entry["capability"])):
317
+ problems.append("%s/capability is a capability name" % cat)
318
+ if entry.get("responder") not in ("active", "stale", "absent"):
319
+ problems.append("%s/responder is active, stale or absent" % cat)
320
+ return problems + ["%s %s" % (f["instancePath"], f["message"]) for f in directory_findings(page)]
321
+
322
+
323
+ def find_project(page: Any, project_id: str, capability: Optional[str] = None) -> Optional[Dict[str, Any]]:
324
+ """Look a Project up in one `com.directory` page (read by a Project session — a board session is not served the
325
+ directory). The page is checked first: a page the contract would refuse, FAC-SEM-107 included, raises
326
+ `BoardError("directory-invalid")` instead of answering from it. Ids and capability names compare exactly as
327
+ written (DEC-0077). Answers the entry, or None when the page does not list it (or lists it without `capability`):
328
+ an unlisted Project may still be addressable by an id the caller already holds."""
329
+ problems = directory_problems(page)
330
+ if problems:
331
+ raise BoardError("directory-invalid", "The directory page cannot be read: %s." % "; ".join(problems[:3]))
332
+ for entry in page["projects"]:
333
+ if entry["id"] == project_id:
334
+ if capability is None or any(c["capability"] == capability for c in entry["capabilities"]):
335
+ return entry
336
+ return None
337
+ return None
338
+
339
+
340
+ # --- evidence -------------------------------------------------------------------------------------------------
341
+
342
+ def artifact_ref(uri: str, content: Optional[bytes] = None, path: Optional[Path] = None, label: Optional[str] = None) -> Dict[str, Any]:
343
+ """One artifact reference `{id, contentHash, label?}`: `id` is a URI the requester can resolve; the hash is
344
+ computed here from `content` or the file at `path`, never trusted from elsewhere."""
345
+ if (content is None) == (path is None):
346
+ raise BoardError("evidence", "Give the artifact's bytes or its path, one of them.")
347
+ digest = hashlib.sha256()
348
+ if content is not None:
349
+ digest.update(content)
350
+ else:
351
+ with open(str(path), "rb") as handle:
352
+ for chunk in iter(lambda: handle.read(1 << 20), b""):
353
+ digest.update(chunk)
354
+ ref: Dict[str, Any] = {"id": uri, "contentHash": "sha256:" + digest.hexdigest()}
355
+ if label is not None:
356
+ ref["label"] = label
357
+ problems = evidence_problems([ref])
358
+ if problems:
359
+ raise BoardError("evidence", "; ".join(problems))
360
+ return ref
361
+
362
+
363
+ def evidence_problems(evidence: Any) -> List[str]:
364
+ """At most 8 references, each `{id: uri, contentHash: sha256:<hex>, label? ≤ 120}`, closed; and no artifact twice:
365
+ two ids with one normal form (DEC-0076) name one artifact."""
366
+ if not isinstance(evidence, list) or len(evidence) > EVIDENCE_MAX:
367
+ return ["evidence is a list of at most %d artifact references" % EVIDENCE_MAX]
368
+ problems: List[str] = []
369
+ for i, ref in enumerate(evidence):
370
+ at = "evidence/%d" % i
371
+ if not _closed(ref, at, ("id", "contentHash"), ("id", "contentHash", "label"), problems):
372
+ continue
373
+ if not (isinstance(ref.get("id"), str) and _URI.fullmatch(ref["id"])):
374
+ problems.append("%s/id is a URI" % at)
375
+ if not (isinstance(ref.get("contentHash"), str) and _SHA256.fullmatch(ref["contentHash"])):
376
+ problems.append("%s/contentHash is sha256:<hex>" % at)
377
+ if "label" in ref and not (isinstance(ref["label"], str) and len(ref["label"]) <= 120):
378
+ problems.append("%s/label is at most 120 characters" % at)
379
+ for j in range(i):
380
+ other = evidence[j]
381
+ if isinstance(other, dict) and _ids.same_identifier(other.get("id"), ref.get("id")):
382
+ problems.append("%s/id names the artifact evidence/%d already names" % (at, j))
383
+ return problems
384
+
385
+
386
+ def outcome_problems(outcome: Any, effect_began: bool) -> List[str]:
387
+ """`comms-complete`'s outcome: state `completed`|`failed_known`, `observed` a boolean (true after an effect began),
388
+ summary ≤ 2,000 characters, evidence as `evidence_problems`; plus the kit's optional `reply {text, format?,
389
+ artifacts?}` (≤ 65,536 UTF-8 bytes), sent with `com.reply` before the completion."""
390
+ problems: List[str] = []
391
+ if not _closed(outcome, "outcome", ("state",), ("state", "observed", "summary", "evidence", "reply"), problems):
392
+ return problems
393
+ if outcome.get("state") not in ("completed", "failed_known"):
394
+ problems.append("outcome/state is completed or failed_known")
395
+ observed = outcome.get("observed", not effect_began)
396
+ if not isinstance(observed, bool):
397
+ problems.append("outcome/observed is a boolean")
398
+ elif effect_began and observed is not True:
399
+ problems.append("observation_required: after an effect began only an observed result settles the request")
400
+ if "summary" in outcome and not (isinstance(outcome["summary"], str) and 1 <= len(outcome["summary"]) <= SUMMARY_MAX):
401
+ problems.append("outcome/summary is 1 to %d characters" % SUMMARY_MAX)
402
+ if "evidence" in outcome:
403
+ problems.extend(evidence_problems(outcome["evidence"]))
404
+ if "reply" in outcome:
405
+ reply = outcome["reply"]
406
+ if _closed(reply, "outcome/reply", ("text",), ("text", "format", "artifacts"), problems):
407
+ text = reply.get("text")
408
+ if not (isinstance(text, str) and text and len(text.encode("utf-8")) <= 65536):
409
+ problems.append("outcome/reply/text is 1 to 65,536 UTF-8 bytes")
410
+ if "format" in reply and reply["format"] not in ("text/plain", "text/markdown"):
411
+ problems.append("outcome/reply/format is text/plain or text/markdown")
412
+ if "artifacts" in reply:
413
+ problems.extend(p.replace("evidence", "outcome/reply/artifacts", 1) for p in evidence_problems(reply["artifacts"]))
414
+ return problems
415
+
416
+
417
+ # --- the board session --------------------------------------------------------------------------------------------
418
+
419
+ class BoardSession:
420
+ """MCP over HTTP with a board session's one-session bearer: `open()` spends it with `initialize` and keeps the
421
+ `mcp-session-id`; `call(tool, args)` answers the tool's value or raises `BoardError`; `close()` sends the session's
422
+ DELETE, which releases every slot it holds (DEC-0073 §5). Thread-safe; the bearer never leaves the headers."""
423
+
424
+ def __init__(self, grant: _hub.BoardGrant, *, timeout: float = 15.0, post: Callable[..., Any] = _hub.post_mcp):
425
+ self.grant, self.timeout, self.post = grant, timeout, post
426
+ self.mcp_session: Optional[str] = None
427
+ self.protocol_version = _hub.MCP_PROTOCOL_VERSION
428
+ self._lock = threading.Lock()
429
+ self._rpc = 0
430
+
431
+ def _send(self, body: Dict[str, Any], method: str = "POST"):
432
+ try:
433
+ return self.post(self.grant.origin, body, self.grant.bearer(), session=self.mcp_session, timeout=self.timeout,
434
+ method=method, protocol_version=self.protocol_version if self.mcp_session else None)
435
+ except _hub.HubError as exc:
436
+ raise BoardError("unreachable", "Fabric's hub did not answer; a write may have been stored — send it again with "
437
+ "the same idempotency key.", True) from exc
438
+
439
+ def open(self) -> None:
440
+ with self._lock:
441
+ self._rpc += 1
442
+ status, headers, parsed = self._send({"jsonrpc": "2.0", "id": self._rpc, "method": "initialize", "params": {
443
+ "protocolVersion": _hub.MCP_PROTOCOL_VERSION, "capabilities": {},
444
+ "clientInfo": {"name": "fabric-agent-adapter-board", "version": "1"}}})
445
+ if status == 401:
446
+ raise BoardError("session-ended", "Fabric refused the board session's bearer; join again.", True)
447
+ if status != 200 or not isinstance(parsed, dict) or not isinstance(parsed.get("result"), dict) or not headers.get("mcp-session-id"):
448
+ raise BoardError("unreachable", "Fabric did not open the board session (HTTP %d)." % status, True)
449
+ self.mcp_session = headers["mcp-session-id"]
450
+ version = parsed["result"].get("protocolVersion")
451
+ if isinstance(version, str):
452
+ self.protocol_version = version
453
+ self._send({"jsonrpc": "2.0", "method": "notifications/initialized"})
454
+
455
+ def call(self, tool: str, args: Dict[str, Any]) -> Dict[str, Any]:
456
+ if tool not in RESPOND_TOOLS:
457
+ raise BoardError("not-in-scope", "%s is not served to a board session; use a Project session for it." % tool, op=tool)
458
+ with self._lock:
459
+ if self.mcp_session is None:
460
+ raise BoardError("session-ended", "The board session is not open.", True, op=tool)
461
+ self._rpc += 1
462
+ status, _, parsed = self._send({"jsonrpc": "2.0", "id": self._rpc, "method": "tools/call",
463
+ "params": {"name": tool, "arguments": args}})
464
+ if status == 401:
465
+ raise BoardError("session-ended", "Fabric ended the board session (it left, was revoked or expired); join again.", True, op=tool)
466
+ try:
467
+ value = _hub.tool_answer(status, parsed, tool)
468
+ except _hub.HubError as exc:
469
+ raise BoardError("unreachable" if exc.retryable else "receipt-shape", exc.message, exc.retryable, op=tool) from None
470
+ if "error" in value:
471
+ problems = refusal_problems(value)
472
+ if problems:
473
+ raise BoardError("receipt-shape", "Fabric refused %s in a form the contract does not name." % tool, op=tool)
474
+ e = value["error"]
475
+ raise BoardError(e["code"], e["message"], e["retryable"], op=tool)
476
+ return value
477
+
478
+ def close(self) -> None:
479
+ with self._lock:
480
+ if self.mcp_session is None:
481
+ return
482
+ try:
483
+ self._send({}, method="DELETE")
484
+ except BoardError:
485
+ pass # best effort: the lease lapses in 60 s anyway
486
+ self.mcp_session = None
487
+
488
+
489
+ # --- the checkpoint ---------------------------------------------------------------------------------------------
490
+
491
+ class Checkpoint:
492
+ """The responder's own journal: one JSON file (0600) holding every request it has claimed and not yet settled, each
493
+ with its fence and the idempotency key of the step in flight. Written atomically and fsynced BEFORE the step it
494
+ announces is sent; a write that fails raises `BoardError("checkpoint")` and the step is not taken."""
495
+
496
+ def __init__(self, path: Path):
497
+ self.path = Path(path)
498
+ self._lock = threading.Lock()
499
+ self.entries: Dict[str, Dict[str, Any]] = self._load()
500
+
501
+ def _load(self) -> Dict[str, Dict[str, Any]]:
502
+ try:
503
+ doc = json.loads(self.path.read_text(encoding="utf-8"))
504
+ except FileNotFoundError:
505
+ return {}
506
+ except (OSError, ValueError) as exc:
507
+ raise BoardError("checkpoint", "The board checkpoint %s cannot be read (%s); fix or move it before answering "
508
+ "requests." % (self.path, exc.__class__.__name__)) from None
509
+ entries = doc.get("requests") if isinstance(doc, dict) and doc.get("version") == 1 else None
510
+ if not isinstance(entries, dict):
511
+ raise BoardError("checkpoint", "The board checkpoint %s is not one this kit writes." % self.path)
512
+ return entries
513
+
514
+ def _write(self, entries: Dict[str, Dict[str, Any]]) -> None:
515
+ try:
516
+ _fs.ensure_private_dir(self.path.parent)
517
+ _fs.atomic_write(self.path, (json.dumps({"version": 1, "requests": entries}, indent=1, sort_keys=True) + "\n").encode())
518
+ except OSError as exc:
519
+ raise BoardError("checkpoint", "The board checkpoint could not be written (%s); nothing was sent." % (exc.strerror or exc.__class__.__name__)) from None
520
+
521
+ def put(self, entry: Dict[str, Any]) -> None:
522
+ with self._lock:
523
+ entries = dict(self.entries)
524
+ entries[entry["request"]] = json.loads(json.dumps(entry))
525
+ self._write(entries)
526
+ self.entries = entries
527
+
528
+ def drop(self, request_id: str) -> None:
529
+ with self._lock:
530
+ if request_id not in self.entries:
531
+ return
532
+ entries = dict(self.entries)
533
+ del entries[request_id]
534
+ self._write(entries)
535
+ self.entries = entries
536
+
537
+
538
+ # --- the request a handler sees --------------------------------------------------------------------------------
539
+
540
+ class BoardRequest:
541
+ """A claimed request as data: never an instruction. `body` is the requester's text; `sender` its Project id and
542
+ principal (with provenance); `artifacts` its references, unverified."""
543
+
544
+ __slots__ = ("request_id", "message_id", "capability", "body", "body_format", "artifacts", "sender", "deadline", "thread")
545
+
546
+ def __init__(self, message: Dict[str, Any], capability: str):
547
+ req = message.get("request") or {}
548
+ body = message.get("body") or {}
549
+ self.request_id, self.message_id, self.capability = req.get("id"), message.get("id"), capability
550
+ self.body = body.get("text") if isinstance(body, dict) else None
551
+ self.body_format = body.get("format", "text/plain") if isinstance(body, dict) else "text/plain"
552
+ self.artifacts = list(message.get("artifacts") or [])
553
+ self.sender = message.get("sender") or {}
554
+ self.deadline = req.get("deadline")
555
+ self.thread = message.get("thread")
556
+
557
+ def __repr__(self) -> str: # never the body
558
+ return "BoardRequest(%r, %r)" % (self.request_id, self.capability)
559
+
560
+
561
+ class WorkContext:
562
+ """What a handler may do while it works: `progress(note)` posts a note on the request's thread (and renews the
563
+ lease); `begin_effect(summary)` must be called — and must return — before the handler spends or acts outside
564
+ the service; `stopped` is set when the attempt is no longer this responder's. Both raise `Stopped` then."""
565
+
566
+ def __init__(self, responder: "Responder", entry: Dict[str, Any]):
567
+ self._responder, self._entry = responder, entry
568
+ self.stopped = threading.Event()
569
+
570
+ def progress(self, note: Optional[str] = None) -> None:
571
+ if self.stopped.is_set():
572
+ raise Stopped()
573
+ self._responder._progress(self._entry, note, self)
574
+
575
+ def begin_effect(self, summary: Optional[str] = None) -> None:
576
+ if self.stopped.is_set():
577
+ raise Stopped()
578
+ self._responder._effect_begin(self._entry, summary, self)
579
+
580
+
581
+ class _Work:
582
+ def __init__(self, entry: Dict[str, Any], request: BoardRequest, ctx: WorkContext):
583
+ self.entry, self.request, self.ctx = entry, request, ctx
584
+ self.done = threading.Event()
585
+ self.outcome: Optional[Dict[str, Any]] = None
586
+ self.failure: Optional[BaseException] = None
587
+ self.renewed_at: Optional[float] = None
588
+
589
+
590
+ # --- the responder ------------------------------------------------------------------------------------------------
591
+
592
+ Handler = Callable[[BoardRequest, WorkContext], Dict[str, Any]]
593
+
594
+
595
+ class Responder:
596
+ """One service's responder for one Project and one or more capabilities, one request at a time.
597
+
598
+ `handler(request, ctx)` returns the outcome `{state, observed?, summary?, evidence?, reply?}`; `admit(request)`
599
+ is the service's input gate (None admits; a sentence refuses); `observe(entry)` reads the world after a restart and
600
+ answers an observed outcome or None, for `com.reconcile`. `emit(kind, level, text, **extra)` receives the
601
+ responder's events (`JsonlEventLog.append` fits). `run(stop)` loops until `stop` is set; `step()` is one tick and
602
+ answers the seconds until the next."""
603
+
604
+ def __init__(self, *, hub: _hub.HubClient, project_id: str, capabilities: Sequence[str], credential_file: Path,
605
+ checkpoint_file: Path, handler: Handler, admit: Callable[[BoardRequest], Optional[str]],
606
+ observe: Optional[Callable[[Dict[str, Any]], Optional[Dict[str, Any]]]] = None,
607
+ emit: Optional[Callable[..., Any]] = None, service: str = "service",
608
+ now: Callable[[], float] = time.monotonic, rand: Callable[[], float] = random.random,
609
+ spawn: Optional[Callable[[Callable[[], None]], Any]] = None, session_factory: Optional[Callable[..., BoardSession]] = None):
610
+ if admit is None or handler is None:
611
+ raise BoardError("invalid_arguments", "A responder needs the service's own input gate (admit) and a handler.")
612
+ caps = list(capabilities)
613
+ if not caps or any(not isinstance(c, str) or not _CAPABILITY.fullmatch(c) for c in caps) or len(set(caps)) != len(caps):
614
+ raise BoardError("invalid_arguments", "Name each capability once, [a-z][a-z0-9._-]{1,127}.")
615
+ self.hub, self.project = hub, _hub._project(project_id)
616
+ self.capabilities = caps
617
+ self.credential_file, self.handler, self.admit, self.observe = Path(credential_file), handler, admit, observe
618
+ self.checkpoint = Checkpoint(Path(checkpoint_file))
619
+ self._emit_to, self.service, self.now, self.rand = emit, re.sub(r"[^A-Za-z0-9._-]", "-", service)[:40] or "service", now, rand
620
+ self.spawn = spawn or (lambda fn: threading.Thread(target=fn, name="board-handler", daemon=True).start())
621
+ self.session_factory = session_factory or (lambda grant: BoardSession(grant))
622
+ self.backoff = _hub.Backoff(rand=rand)
623
+ self.session: Optional[BoardSession] = None
624
+ self.epoch: Optional[int] = None
625
+ self.slots: Dict[str, Dict[str, Any]] = {}
626
+ self.current: Optional[_Work] = None
627
+ self.state = "idle"
628
+ self.wait_until = 0.0
629
+ self.stopping = False
630
+ self.claim_keys: Dict[str, str] = {}
631
+ self._said: Dict[str, str] = {}
632
+ self._rr = 0
633
+
634
+ # -- events -------------------------------------------------------------------------------------------------
635
+ def _emit(self, kind: str, level: str, text: str, notify: bool = False, episode: Optional[str] = None, **value: Any) -> None:
636
+ if episode is not None:
637
+ if self._said.get(kind) == episode:
638
+ return # once per episode
639
+ self._said[kind] = episode
640
+ data = {"schema": EVENT_SCHEMA, "value": {k: v for k, v in value.items() if v is not None}}
641
+ problems = _fs.feed_data_problems(data)
642
+ if problems: # FAC-SEM-101: never a credential in data; drop the data, keep the sentence
643
+ data = None
644
+ if self._emit_to is None:
645
+ return
646
+ try:
647
+ self._emit_to(kind, level, text, notify=notify, **({"data": data} if data else {}))
648
+ except Exception: # noqa: BLE001 - an event that cannot be written never stops the responder
649
+ pass
650
+
651
+ # -- keys and fences ------------------------------------------------------------------------------------------
652
+ def _key(self, op: str) -> str:
653
+ return "%s.%s.%s" % (self.service, op, secrets.token_hex(8))
654
+
655
+ def _idem(self, key: str) -> Dict[str, Any]:
656
+ if self.epoch is None:
657
+ raise BoardError("no-epoch", "Fabric told this board session no idempotency epoch.", op="com.status")
658
+ return {"epoch": self.epoch, "key": key}
659
+
660
+ def _fence(self, entry: Dict[str, Any], key: str) -> Dict[str, Any]:
661
+ return {"request": entry["request"], "generation": entry["generation"], "attempt": entry["attempt"],
662
+ "digest": entry["digest"], "expectedRevision": entry["revision"], "idempotency": self._idem(key)}
663
+
664
+ def _receipt(self, op: str, answer: Dict[str, Any]) -> Dict[str, Any]:
665
+ problems = receipt_problems(answer, op)
666
+ if problems:
667
+ raise BoardError("receipt-shape", "Fabric answered %s with a receipt the contract does not name (%s)." % (op, problems[0]), op=op)
668
+ return answer
669
+
670
+ def _call(self, op: str, args: Dict[str, Any]) -> Dict[str, Any]:
671
+ if self.session is None:
672
+ raise BoardError("session-ended", "No board session.", True, op=op)
673
+ return self.session.call(op, args)
674
+
675
+ # -- connecting --------------------------------------------------------------------------------------------
676
+ def _status(self) -> Dict[str, Any]:
677
+ status = self._call("com.status", {})
678
+ verdict = _fs.negotiate_revision(status.get("protocol"), _fs.accepted_revisions("fabric-project-comms"))
679
+ if "error" in verdict:
680
+ raise BoardError("schema-unsupported", "Fabric's board speaks %s, which this kit does not read." % status.get("protocol"),
681
+ data=verdict["error"]["data"])
682
+ if (status.get("board") or {}).get("state") == "unavailable":
683
+ raise BoardError("not_available", "Fabric's board cannot be read right now.", True, op="com.status")
684
+ epoch = (status.get("idempotency") or {}).get("epoch")
685
+ if not _is_int(epoch, 1):
686
+ # Fail closed: a guessed epoch would store keys under a namespace the board never named.
687
+ raise BoardError("no-epoch", "Fabric told this board session no idempotency epoch (Fabric before its board-session "
688
+ "fix); the responder waits rather than guess one.", op="com.status")
689
+ self.epoch = epoch
690
+ return status
691
+
692
+ def _connect(self) -> None:
693
+ self.state = "connecting"
694
+ grant = self.hub.join_board(self.project, self.credential_file)
695
+ missing = [c for c in self.capabilities if c not in grant.capabilities]
696
+ session = self.session_factory(grant)
697
+ session.open()
698
+ self.session = session
699
+ status = self._status()
700
+ if missing:
701
+ self._emit("board.access.needed", "warn", "The operator has not let this service answer %s on this Project; ask in "
702
+ "Fabric (Agents & access)." % ", ".join(missing), notify=True, episode=",".join(missing),
703
+ capabilities=missing)
704
+ self.slots = {}
705
+ self._recover(status, [c for c in self.capabilities if c in grant.capabilities])
706
+ self.state = "ready"
707
+ for kind in ("board.down", "board.blocked") + (() if missing else ("board.access.needed",)):
708
+ self._said.pop(kind, None)
709
+
710
+ def _enroll(self, capability: str) -> None:
711
+ args = {"idempotency": self._idem(self._key("enroll")), "capability": capability}
712
+ try:
713
+ receipt = self._receipt("com.enroll", self._call("com.enroll", args))
714
+ except BoardError as exc:
715
+ if exc.code == "fenced":
716
+ self.slots[capability] = {"state": "contested", "renewed_at": self.now()}
717
+ self._emit("board.slot.contested", "warn", "Another responder holds the %s slot on this Project; this service "
718
+ "waits for it to lapse and never takes it over by itself." % capability, notify=True,
719
+ episode=capability, capability=capability)
720
+ return
721
+ raise
722
+ self.slots[capability] = {"state": "held", "generation": receipt["slot"]["generation"], "renewed_at": self.now()}
723
+ self._said.pop("board.slot.contested", None)
724
+
725
+ # -- restart: reconcile and transfer -------------------------------------------------------------------------
726
+ def _read_state(self, entry: Dict[str, Any]) -> Optional[str]:
727
+ message = self._call("com.get", {"message": entry["message"]})
728
+ req = message.get("request") if isinstance(message, dict) else None
729
+ if not isinstance(req, dict) or req.get("id") != entry["request"] or req.get("state") not in REQUEST_STATES:
730
+ return None
731
+ entry["revision"] = req.get("revision", entry.get("revision"))
732
+ return req["state"]
733
+
734
+ def _recover(self, status: Dict[str, Any], capabilities: List[str]) -> None:
735
+ transfer: Dict[str, List[Dict[str, Any]]] = {}
736
+ reconcile: List[Dict[str, Any]] = []
737
+ for entry in list(self.checkpoint.entries.values()):
738
+ if entry.get("capability") not in capabilities:
739
+ continue
740
+ try:
741
+ state = self._read_state(entry)
742
+ except BoardError as exc:
743
+ if exc.code in ("not_authorized",):
744
+ self.checkpoint.drop(entry["request"])
745
+ continue
746
+ raise
747
+ if state is None or state in TERMINAL or state in ("queued", "claimed"):
748
+ self.checkpoint.drop(entry["request"]) # settled, or back in the queue for whoever claims next
749
+ elif state == "accepted":
750
+ transfer.setdefault(entry["capability"], []).append(entry)
751
+ else: # in_progress (lost result once a new generation holds the slot) or outcome_unknown
752
+ reconcile.append(entry)
753
+ generations = {r.get("capability"): r.get("generation", 0) for r in status.get("responders") or [] if isinstance(r, dict)}
754
+ for capability in capabilities:
755
+ held = transfer.get(capability)
756
+ if held:
757
+ self._replace(capability, held, generations.get(capability, 0))
758
+ else:
759
+ self._enroll(capability)
760
+ for entry in reconcile:
761
+ if self.slots.get(entry["capability"], {}).get("state") == "held":
762
+ self._reconcile(entry)
763
+
764
+ def _replace(self, capability: str, entries: List[Dict[str, Any]], generation: Any) -> None:
765
+ if not _is_int(generation, 0):
766
+ generation = 0
767
+ args = {"idempotency": self._idem(self._key("replace")), "capability": capability, "expectedGeneration": generation,
768
+ "transfer": {"requests": [e["request"] for e in entries][:64],
769
+ "checkpoint": {"summary": "Resumed by the same service after a restart; no effect had begun."}}}
770
+ receipt = self._receipt("com.responder_replace", self._call("com.responder_replace", args))
771
+ self.slots[capability] = {"state": "held", "generation": receipt["slot"]["generation"], "renewed_at": self.now()}
772
+ moved = {item["request"]: item for item in receipt.get("transferred") or []}
773
+ for entry in entries:
774
+ item = moved.get(entry["request"])
775
+ if item is None:
776
+ # A board pinned before DEC-0078 hands back no attempt. Never claim it back: it stays held, and the next
777
+ # start (or the operator) decides.
778
+ entry["step"] = "held"
779
+ self.checkpoint.put(entry)
780
+ self._emit("board.request.held", "warn", "An accepted request could not be resumed: this Fabric does not hand "
781
+ "back a transferred attempt (DEC-0078). It stays held; nothing was done.", notify=True,
782
+ episode=entry["request"], request=entry["request"], capability=capability)
783
+ continue
784
+ entry.update(generation=item["attempt"]["generation"], attempt=item["attempt"]["id"], digest=item["attempt"]["digest"],
785
+ revision=item["revision"], step="accepted" if entry.get("step") in ("accepting", "held", "lapsed") else entry.get("step"))
786
+ self.checkpoint.put(entry)
787
+ if self.current is None:
788
+ self._resume(entry)
789
+
790
+ def _reconcile(self, entry: Dict[str, Any]) -> None:
791
+ state = self._read_state(entry)
792
+ if state != "outcome_unknown":
793
+ if state in TERMINAL or state in ("queued", "claimed"):
794
+ self.checkpoint.drop(entry["request"])
795
+ return
796
+ outcome = entry.get("outcome") if isinstance(entry.get("outcome"), dict) and entry["outcome"].get("observed") is True else None
797
+ if outcome is None and self.observe is not None:
798
+ try:
799
+ outcome = self.observe(dict(entry))
800
+ except Exception: # noqa: BLE001 - an observation that failed is no observation
801
+ outcome = None
802
+ if not outcome or outcome_problems(dict(outcome, observed=True), True) or outcome.get("observed") is not True:
803
+ entry["step"] = "unknown"
804
+ self.checkpoint.put(entry)
805
+ self._emit("board.reconcile.needed", "warn", "A request's outcome is unknown: the work may have happened. It stays "
806
+ "unknown until this service observes what happened.", notify=True, episode=entry["request"],
807
+ request=entry["request"], capability=entry["capability"])
808
+ return
809
+ clean = {k: outcome[k] for k in ("state", "summary", "evidence") if k in outcome}
810
+ clean["observed"] = True
811
+ args = {"idempotency": self._idem(entry.get("keys", {}).get("reconcile") or self._key("reconcile")), "request": entry["request"],
812
+ "digest": entry["digest"], "outcome": clean}
813
+ entry.setdefault("keys", {})["reconcile"] = args["idempotency"]["key"]
814
+ entry["step"] = "reconciling"
815
+ self.checkpoint.put(entry)
816
+ self._receipt("com.reconcile", self._call("com.reconcile", args))
817
+ self.checkpoint.drop(entry["request"])
818
+ self._emit("board.request.reconciled", "info", "A request whose outcome was unknown was settled from what this service "
819
+ "observed.", request=entry["request"], capability=entry["capability"], state=clean["state"])
820
+
821
+ # -- one tick ------------------------------------------------------------------------------------------------
822
+ def interval(self) -> float:
823
+ return max(1.0, POLL_SECONDS + POLL_JITTER_SECONDS * (2 * self.rand() - 1))
824
+
825
+ def step(self) -> float:
826
+ """One tick. Answers the seconds to wait before the next."""
827
+ if self.stopping:
828
+ return DRAIN_SECONDS
829
+ now = self.now()
830
+ if now < self.wait_until:
831
+ return self.wait_until - now
832
+ try:
833
+ if self.session is None:
834
+ self._connect()
835
+ self._tick()
836
+ self.backoff.reset()
837
+ return self.interval()
838
+ except (BoardError, _hub.HubError) as exc:
839
+ return self._fault(exc)
840
+
841
+ def _fault(self, exc: Exception) -> float:
842
+ code = getattr(exc, "code", "unreachable")
843
+ wait = self.backoff.next()
844
+ self.wait_until = self.now() + wait
845
+ if code in ("not_authorized", "authority_changed", "credential"):
846
+ self.state = "not-authorized"
847
+ self._drop_session()
848
+ self._emit("board.access.needed", "warn", "This service may not answer requests for this Project: the operator "
849
+ "has to allow it in Fabric (Agents & access). Nothing is claimed until then.", notify=True,
850
+ episode="access", reason=code)
851
+ elif code in ("no-epoch", "schema-unsupported", "checkpoint", "receipt-shape"):
852
+ self.state = "down"
853
+ self._drop_session()
854
+ self._emit("board.blocked", "error", "The responder stopped answering requests: %s" % getattr(exc, "message", str(exc)),
855
+ notify=True, episode=code, reason=code)
856
+ else:
857
+ self.state = "down"
858
+ if code in ("session-ended", "unreachable", "not-running", "not-a-hub", "hub-unavailable", "protocol"):
859
+ self._drop_session()
860
+ self._emit("board.down", "warn", "Fabric's board cannot be reached; the responder tries again with a growing pause.",
861
+ episode="down", reason=code)
862
+ return wait
863
+
864
+ def _drop_session(self) -> None:
865
+ work, self.current = self.current, None
866
+ if work is not None:
867
+ entry = work.entry
868
+ if work.done.is_set() and work.failure is None and not outcome_problems(work.outcome, bool(entry.get("effect"))):
869
+ # The answer is known: keep it, so the next session sends it instead of doing the work again.
870
+ entry["outcome"] = dict(work.outcome, observed=work.outcome.get("observed", not entry.get("effect")))
871
+ try:
872
+ self.checkpoint.put(entry)
873
+ except BoardError:
874
+ pass
875
+ else:
876
+ work.ctx.stopped.set() # the lease lapses; acting on would outlive the attempt
877
+ session, self.session = self.session, None
878
+ if session is not None:
879
+ session.close()
880
+
881
+ def _tick(self) -> None:
882
+ work = self.current
883
+ if work is not None:
884
+ if work.done.is_set():
885
+ self._finish(work)
886
+ else:
887
+ self._renew(work)
888
+ held_by_work = work.entry["capability"] if work is not None and self.current is not None else None
889
+ for capability, slot in list(self.slots.items()):
890
+ if capability != held_by_work and self.now() - slot.get("renewed_at", 0) >= RENEW_SECONDS - 0.5:
891
+ self._enroll(capability) # the holder's enroll renews its lease (no event); a lapsed one re-enrolls
892
+ if self.current is None and not self.stopping:
893
+ self._continue_lapsed()
894
+ if self.current is None and not self.stopping:
895
+ self._reconcile_pending()
896
+ self._claim_next()
897
+
898
+ def _continue_lapsed(self) -> None:
899
+ """Accepted work whose lease lapsed goes back to this responder by `com.responder_replace` with a transfer."""
900
+ lapsed: Dict[str, List[Dict[str, Any]]] = {}
901
+ for entry in self.checkpoint.entries.values():
902
+ if entry.get("step") == "lapsed" and self.slots.get(entry.get("capability"), {}).get("state") == "held":
903
+ lapsed.setdefault(entry["capability"], []).append(json.loads(json.dumps(entry)))
904
+ for capability, entries in lapsed.items():
905
+ live = [e for e in entries if self._read_state(e) == "accepted"]
906
+ for e in entries:
907
+ if e not in live:
908
+ self.checkpoint.drop(e["request"])
909
+ if live:
910
+ self._replace(capability, live, self.slots[capability].get("generation", 0))
911
+
912
+ def _reconcile_pending(self) -> None:
913
+ """Work whose outcome became unknown while running (its attempt was lost after the effect began) is tried
914
+ again every five minutes: the slot's holder reconciles from what `observe` reads, or it stays unknown."""
915
+ if self.now() < getattr(self, "_reconcile_at", 0.0):
916
+ return
917
+ self._reconcile_at = self.now() + 300.0
918
+ for entry in list(self.checkpoint.entries.values()):
919
+ if entry.get("step") == "unknown" and self.slots.get(entry.get("capability"), {}).get("state") == "held":
920
+ self._reconcile(entry)
921
+
922
+ def _claim_next(self) -> None:
923
+ held = [c for c in self.capabilities if self.slots.get(c, {}).get("state") == "held"]
924
+ for i in range(len(held)):
925
+ capability = held[(self._rr + i) % len(held)]
926
+ key = self.claim_keys.setdefault(capability, self._key("claim"))
927
+ try:
928
+ answer = self._receipt("com.claim", self._call("com.claim", {"idempotency": self._idem(key), "capability": capability}))
929
+ except BoardError as exc:
930
+ if exc.code == "lease_expired":
931
+ self._enroll(capability) # the slot lapsed: enroll again (a new generation)
932
+ continue
933
+ if exc.code in ("idempotency_window_expired", "capacity_exceeded"):
934
+ self.claim_keys.pop(capability, None)
935
+ self._status()
936
+ continue
937
+ if exc.code == "fenced":
938
+ self.slots[capability] = {"state": "contested", "renewed_at": self.now()}
939
+ continue
940
+ raise
941
+ if "request" not in answer:
942
+ continue # nothing claimable; the same key polls again
943
+ self.claim_keys.pop(capability, None)
944
+ self._rr += 1
945
+ self._start(capability, answer)
946
+ return
947
+
948
+ # -- a claimed request -------------------------------------------------------------------------------------
949
+ def _start(self, capability: str, receipt: Dict[str, Any]) -> None:
950
+ if "attempt" not in receipt or "message" not in receipt:
951
+ raise BoardError("receipt-shape", "com.claim answered a request without its attempt or message.", op="com.claim")
952
+ attempt = receipt["attempt"]
953
+ entry = {"request": receipt["request"]["id"], "message": receipt["message"], "capability": capability,
954
+ "generation": attempt["generation"], "attempt": attempt["id"], "digest": attempt["digest"],
955
+ "revision": receipt["request"]["revision"], "step": "claimed", "keys": {}, "effect": False}
956
+ self.checkpoint.put(entry)
957
+ message = self._call("com.get", {"message": entry["message"]})
958
+ req = message.get("request") if isinstance(message, dict) else None
959
+ if message.get("digest") != entry["digest"]:
960
+ self.checkpoint.drop(entry["request"])
961
+ self._emit("board.request.skipped", "warn", "A claimed request was not accepted: the message read back carries "
962
+ "another digest than the claim. Nothing was done; the claim lapses.", request=entry["request"],
963
+ capability=capability, reason="digest-mismatch")
964
+ return
965
+ if not isinstance(req, dict) or req.get("id") != entry["request"] or req.get("capability") != capability \
966
+ or req.get("target") != self.project:
967
+ self.checkpoint.drop(entry["request"])
968
+ self._emit("board.request.skipped", "warn", "A claimed request was not accepted: it is not addressed to this "
969
+ "Project and capability. Nothing was done; the claim lapses.", request=entry["request"],
970
+ capability=capability, reason="not-addressed")
971
+ return
972
+ request = BoardRequest(message, capability)
973
+ if message.get("redacted") is True or not isinstance(request.body, str):
974
+ reason: Optional[str] = "The request's body was redacted, so there is nothing to act on."
975
+ else:
976
+ try:
977
+ reason = self.admit(request)
978
+ except Exception: # noqa: BLE001 - a gate that fails refuses
979
+ reason = "The service's input gate could not read this request."
980
+ if not self._accept(entry):
981
+ return
982
+ if reason is not None:
983
+ text = ("Refused by this service's input gate: %s" % " ".join(str(reason).split()))[:SUMMARY_MAX]
984
+ entry["outcome"] = {"state": "failed_known", "observed": True, "summary": text}
985
+ self._complete(entry)
986
+ self._emit("board.request.refused", "info", "A request was refused by the service's input gate and completed as "
987
+ "failed.", request=entry["request"], capability=capability)
988
+ return
989
+ self._run(entry, request)
990
+
991
+ def _accept(self, entry: Dict[str, Any]) -> bool:
992
+ key = entry["keys"].get("accept") or self._key("accept")
993
+ entry["keys"]["accept"], entry["step"] = key, "accepting"
994
+ self.checkpoint.put(entry)
995
+ receipt = self._fenced("com.accept", entry, {"fence": self._fence(entry, key)})
996
+ if receipt is None:
997
+ return False # the claim was lost before it was accepted; nothing was done
998
+ entry["revision"], entry["step"] = receipt["request"]["revision"], "accepted"
999
+ self.checkpoint.put(entry)
1000
+ return True
1001
+
1002
+ def _run(self, entry: Dict[str, Any], request: BoardRequest) -> None:
1003
+ ctx = WorkContext(self, entry)
1004
+ work = _Work(entry, request, ctx)
1005
+ work.renewed_at = self.now()
1006
+ self.current = work
1007
+
1008
+ def body() -> None:
1009
+ try:
1010
+ work.outcome = self.handler(request, ctx)
1011
+ except BaseException as exc: # noqa: BLE001 - recorded, decided by _finish
1012
+ work.failure = exc
1013
+ finally:
1014
+ work.done.set()
1015
+ self.spawn(body)
1016
+ if work.done.is_set():
1017
+ self._finish(work)
1018
+
1019
+ def _resume(self, entry: Dict[str, Any]) -> None:
1020
+ """A transferred request continues: an outcome already known is sent; otherwise the handler runs again (no
1021
+ effect had begun, so nothing happened yet)."""
1022
+ if isinstance(entry.get("outcome"), dict):
1023
+ self._complete(entry)
1024
+ return
1025
+ message = self._call("com.get", {"message": entry["message"]})
1026
+ self._run(entry, BoardRequest(message, entry["capability"]))
1027
+
1028
+ def _fenced(self, op: str, entry: Dict[str, Any], args: Dict[str, Any]) -> Optional[Dict[str, Any]]:
1029
+ """A fenced call. On `fenced`, `lease_expired` or `authority_changed` the attempt is lost: the work stops, and
1030
+ answers None (`authority_changed` raises after that, so the responder stops claiming)."""
1031
+ try:
1032
+ return self._receipt(op, self._call(op, args))
1033
+ except BoardError as exc:
1034
+ if exc.code in STOP_CODES or exc.code in ("revision_conflict", "invalid_transition", "digest_conflict"):
1035
+ self._lose(entry, exc.code)
1036
+ if exc.code == "authority_changed":
1037
+ raise
1038
+ return None
1039
+ raise
1040
+
1041
+ def _lose(self, entry: Dict[str, Any], code: str) -> None:
1042
+ if self.current is not None and self.current.entry is entry:
1043
+ self.current.ctx.stopped.set()
1044
+ if entry.get("effect"):
1045
+ entry["step"] = "unknown"
1046
+ self.checkpoint.put(entry)
1047
+ self._emit("board.reconcile.needed", "warn", "The attempt was lost after its effect began; the outcome stays unknown "
1048
+ "until this service observes what happened.", notify=True, episode=entry["request"],
1049
+ request=entry["request"], capability=entry["capability"], reason=code)
1050
+ elif code == "lease_expired" and entry.get("step") not in ("claimed", "accepting"):
1051
+ # Our own lease lapsed on accepted work: the board holds it (C4). It continues only by a checkpoint transfer
1052
+ # to this responder, which the next tick asks for; nothing outside the service had begun.
1053
+ entry["step"] = "lapsed"
1054
+ self.checkpoint.put(entry)
1055
+ self._emit("board.attempt.lost", "warn", "This service's lease on an accepted request lapsed; it stopped working "
1056
+ "on it and takes it back by a transfer.", request=entry["request"], capability=entry["capability"], reason=code)
1057
+ else:
1058
+ self.checkpoint.drop(entry["request"])
1059
+ self._emit("board.attempt.lost", "warn", "The board took a request back from this service (%s); it stopped working "
1060
+ "on it, and nothing had been done outside the service." % code, request=entry["request"],
1061
+ capability=entry["capability"], reason=code)
1062
+
1063
+ def _renew(self, work: _Work) -> None:
1064
+ entry = work.entry
1065
+ if self.now() - (work.renewed_at or 0.0) < RENEW_SECONDS - 0.5:
1066
+ return
1067
+ receipt = self._fenced("com.renew", entry, {"fence": self._fence(entry, self._key("renew"))})
1068
+ if receipt is None:
1069
+ self.current = None
1070
+ return
1071
+ work.renewed_at = self.now()
1072
+ self.slots.setdefault(entry["capability"], {})["renewed_at"] = self.now()
1073
+
1074
+ def _progress(self, entry: Dict[str, Any], note: Optional[str], ctx: WorkContext) -> None:
1075
+ args: Dict[str, Any] = {"fence": self._fence(entry, self._key("progress"))}
1076
+ if note is not None:
1077
+ args["note"] = {"text": " ".join(str(note).split())[:SUMMARY_MAX] or "Working."}
1078
+ if self._fenced("com.progress", entry, args) is None:
1079
+ raise Stopped()
1080
+
1081
+ def _effect_begin(self, entry: Dict[str, Any], summary: Optional[str], ctx: WorkContext) -> None:
1082
+ key = entry["keys"].get("effect_begin") or self._key("effect")
1083
+ entry["keys"]["effect_begin"], entry["step"] = key, "effect-beginning"
1084
+ entry["effect"] = True # from here a lost attempt is an unknown outcome, never "nothing happened"
1085
+ self.checkpoint.put(entry)
1086
+ args: Dict[str, Any] = {"fence": self._fence(entry, key)}
1087
+ if summary:
1088
+ args["summary"] = " ".join(str(summary).split())[:SUMMARY_MAX]
1089
+ receipt = None
1090
+ for attempt in range(3): # a lost answer: the same key again tells whether it was stored
1091
+ try:
1092
+ receipt = self._fenced("com.effect_begin", entry, args)
1093
+ break
1094
+ except BoardError as exc:
1095
+ if exc.code != "unreachable" or attempt == 2:
1096
+ raise Stopped() from None
1097
+ time.sleep(attempt + 1)
1098
+ if receipt is None:
1099
+ raise Stopped()
1100
+ entry["revision"], entry["step"] = receipt["request"]["revision"], "in-progress"
1101
+ self.checkpoint.put(entry)
1102
+
1103
+ def _finish(self, work: _Work) -> None:
1104
+ entry = work.entry
1105
+ if work.ctx.stopped.is_set() and entry["request"] not in self.checkpoint.entries:
1106
+ self.current = None
1107
+ return
1108
+ outcome = work.outcome
1109
+ if work.failure is not None:
1110
+ if entry.get("effect") or isinstance(work.failure, Stopped):
1111
+ self.current = None
1112
+ if entry.get("effect"):
1113
+ self._lose(entry, "handler-failed")
1114
+ return
1115
+ outcome = {"state": "failed_known", "observed": True,
1116
+ "summary": "The service could not do this (%s)." % work.failure.__class__.__name__}
1117
+ problems = outcome_problems(outcome, bool(entry.get("effect")))
1118
+ if problems:
1119
+ self.current = None
1120
+ if entry.get("effect"):
1121
+ self._lose(entry, "observation_required" if any("observation_required" in p for p in problems) else "outcome")
1122
+ else:
1123
+ entry["outcome"] = {"state": "failed_known", "observed": True, "summary": "The service answered in a form it cannot send."}
1124
+ self._complete(entry)
1125
+ self._emit("board.outcome.invalid", "warn", "The handler's outcome was not sent: %s." % problems[0],
1126
+ request=entry["request"], capability=entry["capability"])
1127
+ return
1128
+ entry["outcome"] = dict(outcome, observed=outcome.get("observed", not entry.get("effect")))
1129
+ self._complete(entry)
1130
+
1131
+ def _complete(self, entry: Dict[str, Any]) -> None:
1132
+ outcome = entry["outcome"]
1133
+ reply = outcome.get("reply")
1134
+ if reply and not entry.get("replied"):
1135
+ key = entry["keys"].get("reply") or self._key("reply")
1136
+ entry["keys"]["reply"], entry["step"] = key, "replying"
1137
+ self.checkpoint.put(entry)
1138
+ body = {"text": reply["text"], **({"format": reply["format"]} if "format" in reply else {})}
1139
+ args: Dict[str, Any] = {"fence": self._fence(entry, key), "body": body}
1140
+ if reply.get("artifacts"):
1141
+ args["artifacts"] = reply["artifacts"]
1142
+ if self._fenced("com.reply", entry, args) is None:
1143
+ self.current = None
1144
+ return
1145
+ entry["replied"] = True
1146
+ self.checkpoint.put(entry)
1147
+ key = entry["keys"].get("complete") or self._key("complete")
1148
+ entry["keys"]["complete"], entry["step"] = key, "completing"
1149
+ self.checkpoint.put(entry)
1150
+ sent = {k: outcome[k] for k in ("state", "observed", "summary", "evidence") if k in outcome}
1151
+ receipt = self._fenced("com.complete", entry, {"fence": self._fence(entry, key), "outcome": sent})
1152
+ self.current = None
1153
+ if receipt is None:
1154
+ return
1155
+ self.checkpoint.drop(entry["request"])
1156
+ self._emit("board.request.completed", "info", "A request was answered: %s." % ("completed" if sent["state"] == "completed" else "failed, as known"),
1157
+ request=entry["request"], capability=entry["capability"], state=sent["state"])
1158
+
1159
+ # -- running ----------------------------------------------------------------------------------------------
1160
+ def run(self, stop: threading.Event, drain: float = DRAIN_SECONDS) -> None:
1161
+ """Tick until `stop` is set, then `shutdown(drain)`."""
1162
+ while not stop.is_set():
1163
+ stop.wait(self.step())
1164
+ self.shutdown(drain)
1165
+
1166
+ def shutdown(self, drain: float = DRAIN_SECONDS) -> None:
1167
+ """Stop claiming, give running work up to `drain` seconds to finish and be completed, then leave the session
1168
+ (its DELETE releases the slots). What is still open stays in the checkpoint for the next start."""
1169
+ self.stopping = True
1170
+ work = self.current
1171
+ if work is not None and not work.done.wait(drain):
1172
+ work.ctx.stopped.set()
1173
+ if work is not None and work.done.is_set() and self.session is not None:
1174
+ try:
1175
+ self._finish(work)
1176
+ except (BoardError, _hub.HubError):
1177
+ pass # the checkpoint keeps it
1178
+ if self.session is not None:
1179
+ self.session.close()
1180
+ self.session = None
1181
+ self.state = "stopped"
1182
+
1183
+
1184
+ # --- a fixture conversation (check_service.py, rule board.responder) ---------------------------------------------
1185
+
1186
+ _FIXTURE_PROJECT = "3f2a6b1c-0d4e-4f5a-8b6c-7d8e9f0a1b2c"
1187
+ _FIXTURE_DIGEST = "sha256:" + "a" * 64
1188
+
1189
+
1190
+ def _fixture_answers(variant: str) -> Dict[str, Any]:
1191
+ """Scripted board answers in the contract's receipt shapes (fixtures comms-receipt-enroll, comms-receipt-claim)."""
1192
+ lease = "2026-10-13T10:02:00Z"
1193
+ status: Dict[str, Any] = {"protocol": COMMS_PROTOCOL, "board": {"state": "ready"}, "project": _FIXTURE_PROJECT, "responders": [],
1194
+ "transport": {"telegram": "off"}, "unread": 0, "idempotency": {"epoch": 3}}
1195
+ if variant == "no-epoch":
1196
+ del status["idempotency"]
1197
+ request = {"id": "req_A1b2C3d4E5", "state": "claimed", "effect": "not_started", "revision": 2}
1198
+ return {
1199
+ "com.status": status,
1200
+ "com.enroll": {"ok": True, "repeated": False, "slot": {"project": _FIXTURE_PROJECT, "capability": "fixture.render", "generation": 2, "leaseExpiresAt": lease}},
1201
+ "com.claim": {"ok": True, "repeated": False, "message": "msg_K9j8H7g6F5", "request": request,
1202
+ "attempt": {"id": "att_Zx9Cv8Bn7M", "generation": 2, "digest": _FIXTURE_DIGEST, "leaseExpiresAt": lease}},
1203
+ "com.get": {"id": "msg_K9j8H7g6F5", "thread": "thr_8Hc2kQ9xA1", "kind": "request", "at": "2026-10-13T10:00:00Z", "digest": _FIXTURE_DIGEST,
1204
+ "sender": {"project": "proj-requester", "principal": {"kind": "agent", "id": "s-1", "provenance": "trusted"}},
1205
+ "body": {"text": "Render the fixture."},
1206
+ "request": {"id": "req_A1b2C3d4E5", "target": _FIXTURE_PROJECT, "capability": "fixture.render", "state": "claimed", "effect": "not_started", "revision": 2}},
1207
+ "com.accept": ({"error": {"code": "fenced", "message": "A newer responder holds this slot; this call was not committed.", "retryable": False}}
1208
+ if variant == "fenced" else {"ok": True, "repeated": False, "request": dict(request, state="accepted", revision=3)}),
1209
+ "com.complete": {"ok": True, "repeated": False, "request": dict(request, state="completed", revision=4)},
1210
+ }
1211
+
1212
+
1213
+ def self_check() -> List[str]:
1214
+ """One scripted conversation per path through this kit, with no Fabric: the whole conversation, a `fenced` accept
1215
+ and a board session without an epoch. Answers the problems found; an empty list means this kit answers the fixture
1216
+ conversation as the contract asks. Writes only in a temporary folder it removes."""
1217
+ import os
1218
+ import tempfile
1219
+ problems: List[str] = []
1220
+ for variant in ("whole", "fenced", "no-epoch"):
1221
+ with tempfile.TemporaryDirectory() as tmp:
1222
+ root = Path(tmp) / "fabric"
1223
+ root.mkdir(mode=0o700)
1224
+ door = root / "hub-door-token"
1225
+ door.write_text("d" * 43)
1226
+ os.chmod(door, 0o600)
1227
+ (root / "hub.json").write_text(json.dumps({"protocol": _hub.HUB_PROTOCOL, "origin": "http://127.0.0.1:47070", "mcp": "/mcp",
1228
+ "doorTokenFile": str(door), "pid": os.getpid(), "startedAt": "2026-10-13T10:00:00Z"}))
1229
+ cred = Path(tmp) / "credential"
1230
+ cred.write_text("c" * 43)
1231
+ os.chmod(cred, 0o600)
1232
+ answers, calls, handled = _fixture_answers(variant), [], []
1233
+
1234
+ def post(origin, body, bearer, session=None, timeout=15.0, method="POST", protocol_version=None):
1235
+ if method == "DELETE":
1236
+ return 200, {}, None
1237
+ rpc = body.get("method")
1238
+ if rpc == "initialize":
1239
+ return 200, {"mcp-session-id": "fixture-session"}, {"jsonrpc": "2.0", "id": body.get("id"), "result": {"protocolVersion": _hub.MCP_PROTOCOL_VERSION}}
1240
+ if rpc != "tools/call":
1241
+ return 202, {}, None
1242
+ tool = body["params"]["name"]
1243
+ calls.append((tool, body["params"]["arguments"]))
1244
+ if tool == "fabric.board.join":
1245
+ value = {"session": {"bearer": "b" * 43, "sessionId": "s-fixture", "projectId": _FIXTURE_PROJECT, "capabilities": ["fixture.render"]}}
1246
+ return 200, {}, {"jsonrpc": "2.0", "id": body.get("id"), "result": {"structuredContent": value}}
1247
+ value = answers.get(tool, {"error": {"code": "unsupported_capability", "message": "not in the fixture", "retryable": False}})
1248
+ return 200, {}, {"jsonrpc": "2.0", "id": body.get("id"), "result": {"content": [{"type": "text", "text": json.dumps(value)}]}}
1249
+
1250
+ responder = Responder(hub=_hub.HubClient(root, post=post), project_id=_FIXTURE_PROJECT, capabilities=["fixture.render"],
1251
+ credential_file=cred, checkpoint_file=Path(tmp) / "checkpoint.json",
1252
+ handler=lambda request, ctx: handled.append(request.body) or {"state": "completed", "summary": "Rendered."},
1253
+ admit=lambda request: None, now=lambda: 0.0, rand=lambda: 0.5, spawn=lambda fn: fn(),
1254
+ session_factory=lambda grant: BoardSession(grant, post=post))
1255
+ responder.step()
1256
+ tools = [t for t, _ in calls]
1257
+ if any(t not in RESPOND_TOOLS and t != "fabric.board.join" for t in tools):
1258
+ problems.append("%s: a tool outside the respond scope was sent" % variant)
1259
+ if variant == "whole":
1260
+ if tools != ["fabric.board.join", "com.status", "com.enroll", "com.claim", "com.get", "com.accept", "com.complete"]:
1261
+ problems.append("whole: the calls were %s" % ", ".join(tools))
1262
+ accept = dict(calls).get("com.accept", {}).get("fence", {})
1263
+ if (accept.get("digest"), accept.get("generation"), accept.get("attempt")) != (_FIXTURE_DIGEST, 2, "att_Zx9Cv8Bn7M"):
1264
+ problems.append("whole: com.accept did not carry the claim's exact fence")
1265
+ if handled != ["Render the fixture."]:
1266
+ problems.append("whole: the handler did not see the request once")
1267
+ if responder.checkpoint.entries:
1268
+ problems.append("whole: the checkpoint kept a settled request")
1269
+ elif variant == "fenced":
1270
+ if handled or "com.complete" in tools:
1271
+ problems.append("fenced: the kit kept acting after com.accept answered fenced")
1272
+ elif "com.enroll" in tools or responder.state != "down":
1273
+ problems.append("no-epoch: the kit did not fail closed without an idempotency epoch")
1274
+ return problems