commitlayer 0.1.0__tar.gz → 0.1.3__tar.gz

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.
@@ -0,0 +1,212 @@
1
+ Metadata-Version: 2.4
2
+ Name: commitlayer
3
+ Version: 0.1.3
4
+ Summary: CommitLayer Python SDK: record agent actions, push facts, read verdicts, draft contracts
5
+ Author-email: "Asterfold Labs, Inc." <hello@commitlayer.ai>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://commitlayer.ai
8
+ Project-URL: Documentation, https://commitlayer.ai/docs
9
+ Project-URL: Changelog, https://commitlayer.ai/changelog
10
+ Project-URL: Source, https://github.com/commitlayer/commitlayer/tree/main/sdk/python
11
+ Keywords: ai-agents,verification,audit,mcp,observability
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.10
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Topic :: Software Development :: Libraries
20
+ Requires-Python: >=3.10
21
+ Description-Content-Type: text/markdown
22
+ License-File: LICENSE
23
+ Dynamic: license-file
24
+
25
+ # commitlayer (Python)
26
+
27
+ Record agent actions, push facts from systems of record, read verdicts and draft contracts. Standard library
28
+ only; Python 3.10+.
29
+
30
+ ```bash
31
+ pip install commitlayer
32
+ export COMMITLAYER_API_KEY=spk_... # the agent runtime's key: a *recorder* key (records actions, nothing else)
33
+ export COMMITLAYER_EVIDENCE_KEY=spk_... # the pipeline's key: an *evidence* key bound to the sources it pushes for
34
+ # COMMITLAYER_API_URL defaults to https://api.commitlayer.ai. One credential per side of the line: the key that
35
+ # records an action can never also supply the facts that verify it.
36
+ ```
37
+
38
+ ## Record an action where it happens
39
+
40
+ ```python
41
+ from commitlayer import Client
42
+
43
+ cl = Client(agent_id="support-bot")
44
+
45
+
46
+ @cl.action(
47
+ "refund_workflow",
48
+ subject=lambda order_id, **_: order_id,
49
+ params=lambda amount, **_: {"amount": amount},
50
+ subject_kind="order",
51
+ action_id=lambda order_id, **_: f"refund:{order_id}", # retries update one claim instead of recording two
52
+ )
53
+ def refund(order_id: str, amount: float) -> dict:
54
+ return payments.refund(order_id, amount) # the agent's own work, unchanged
55
+
56
+
57
+ refund("order_10231", 180.0)
58
+ print(refund.last_recorded["verification"]["summary"]["headline"])
59
+ ```
60
+
61
+ The action is recorded **before** the function runs, so its request time precedes every effect. The function's
62
+ return value is never changed and never consulted: verification reads the systems of record. If the API cannot
63
+ be reached the function still runs and a warning is logged (`fail_open=True`); pass `fail_open=False` to raise.
64
+
65
+ ## Push facts, with a watermark
66
+
67
+ Use an **evidence** key here, bound to the sources it pushes for (Settings → API keys). The key your agent runtime records actions with is a **recorder** key and cannot push facts: the credential that records an action never also supplies the facts that verify it.
68
+
69
+ ```python
70
+ import os
71
+
72
+ evidence = Client(api_key=os.environ["COMMITLAYER_EVIDENCE_KEY"]) # the pipeline's own client, not the runtime's
73
+
74
+ evidence.push_facts(
75
+ [
76
+ {
77
+ "source": "crm",
78
+ "subject_id": "order_10231",
79
+ "fact_type": "note_added",
80
+ "occurred_at": "2026-10-13T10:42:09Z",
81
+ }
82
+ ],
83
+ watermarks={"crm": "2026-10-13T10:45:00Z"}, # everything up to here has been sent for crm
84
+ )
85
+ ```
86
+
87
+ A verdict that is not yet a PASS settles only when its window has closed **and** every source it reads has a
88
+ watermark past the end of the window. Declare one when your feed lags; a source that never declares one is taken
89
+ as current.
90
+
91
+ ## Draft a contract from what was recorded
92
+
93
+ ```python
94
+ d = cl.draft_contract("refund_order", lookback_days=30)
95
+ print(d["yaml"]) # expected effects, window, preconditions, limits, from the sample
96
+ print(d["stats"]["effects"])
97
+ v = cl.validate_contract(d["yaml"]) # errors, and weakening warnings against the version it would replace
98
+ cl.save_contract(d["yaml"]) # the response carries the same warnings
99
+ ```
100
+
101
+ Every value in a draft is what the sample showed, not what the policy says. Review it before saving.
102
+
103
+ ## Read a verdict
104
+
105
+ ```python
106
+ v = cl.get_action("refund:order_10231")
107
+ v["status"] # pending | settled
108
+ v["settlement"]["waiting_on"] # sources still behind the window, if any
109
+ v["reversal"] # the later record that undid the action, if any
110
+ v["sources"] # trust level and watermark per source the contract read
111
+ ```
112
+
113
+ ## Wait for the verdict before saying "done"
114
+
115
+ ```python
116
+ v = cl.wait_for_settlement("refund:order_10231", timeout=300) # blocks until settled or 5 minutes
117
+ if v["timed_out"]:
118
+ ... # still pending: your policy, never "success"
119
+ elif v["lenses"]["outcome"]["verdict"] == "PASS":
120
+ notify_customer("Your order is cancelled and refunded.")
121
+ else:
122
+ open_recovery(v) # FAIL: the reasons name what is missing or forbidden
123
+ ```
124
+
125
+ The API holds each call for up to 60 seconds; the SDK loops. The gate reads evidence; it never changes a verdict.
126
+
127
+ ## Install a workflow pack (drafts, never activation)
128
+
129
+ ```python
130
+ packs = cl.packs.list()["items"] # Stripe Customer Operations, x402, Coinbase
131
+ detail = cl.packs.get("stripe_customer_operations") # contracts, requirements, templates, versions
132
+ effective = cl.packs.configure("stripe_customer_operations", {"refund_order": {"approved_limit": 100}})
133
+ report = cl.packs.dry_run("stripe_customer_operations", {"refund_order": {"approved_limit": 100}})
134
+ assert report["summary"]["ok"] == report["summary"]["total"] # every fixture case holds under your limits
135
+ out = cl.packs.install("stripe_customer_operations", {"refund_order": {"approved_limit": 100}}, confirm=True)
136
+ print(out["activation"]["how"]) # POST /v1/contracts/<id>/select, by a person
137
+ mapping = cl.packs.recorder_mapping("stripe_customer_operations") # contract versions pinned
138
+ ```
139
+
140
+ `configure` and `dry_run` write nothing. `install` saves the configured contracts as **drafts**: nothing governs a
141
+ live action until a person activates a version in the app or with `POST /v1/contracts/{id}/select`. Below the
142
+ pack's minimum plan the service answers `402 plan_required` with `upgrade_to`.
143
+
144
+ ## What is retried
145
+
146
+ When the API cannot admit a request it answers `503 busy` (the service is at its limit) or `429` (`workspace_busy`:
147
+ this workspace already has its share of writes in progress; `rate_limited`: its requests a minute are spent) with a
148
+ `Retry-After` header. The client waits the time the header states and sends the same request again, so a burst
149
+ that the API spreads over a few seconds never reaches your code as an error. Since 0.1.3.
150
+
151
+ | | |
152
+ |---|---|
153
+ | Retried | An answer of **429 or 503 that carries `Retry-After`**, as seconds (`1`, `1.5`) or an HTTP-date, for any method of the client. |
154
+ | Not retried | Every other status (400, 402, 404, 409, 500 and the rest), a 429 or 503 **without** the header (the API's limit on requests in flight answers a plain `503` like that), a timeout and a network error: after those the client cannot know whether the request arrived. |
155
+ | How often | `max_retries=3` times after the first attempt. `max_retries=0` turns retrying off. |
156
+ | How long | Never less than the header states, plus a random addition of up to twice as much, so the calls of a burst that were refused together come back spread out, and never more than `max_retry_wait`. A stated wait above `max_retry_wait=10.0` seconds is not waited at all: the error is raised at once (the Developer plan's daily cap, `429 fair_use_exceeded`, states the seconds to midnight). |
157
+ | Worst case | One call waits at most `max_retries * max_retry_wait` seconds, 30 by default, on top of its requests. The API states one second today, so each retry waits between one and three seconds: a call refused once adds one to three seconds, a call that uses all three retries adds three to nine. |
158
+ | The request | Identical on every attempt, byte for byte. `record_action` chooses the `action_id` before the first attempt, so every attempt names the same action and the API records it once. |
159
+
160
+ ```python
161
+ from commitlayer import Client, CommitLayerError
162
+
163
+ cl = Client(max_retries=3, max_retry_wait=10.0) # the defaults
164
+ single = Client(max_retries=0) # never retry: the first refusal is raised
165
+
166
+ try:
167
+ cl.record_action("refund_workflow", "order_10231", action_id="refund:order_10231")
168
+ except CommitLayerError as e:
169
+ e.status, e.code # 429, "workspace_busy": the last answer, as before
170
+ e.retry_after # seconds the last answer asked to wait, or None when it stated none
171
+ e.attempts # how many times the request was sent (4 once three retries are used up)
172
+ ```
173
+
174
+ One request is the exception. `POST /v1/actions` is idempotent on `action_id`, and the API may answer `503 busy`
175
+ after the action itself is stored, so a recording that names no `action_id` is sent once and never repeated.
176
+ `record_action` and the `@cl.action` decorator always name one; this only concerns a body you build yourself for
177
+ `cl.request("POST", "/v1/actions", ...)` or an inline `cl.verify(action=...)` that is stored.
178
+
179
+ For the same reason a `503` that `record_action` still raises, after its retries or without any, does not prove
180
+ the action is absent: the API may have stored it and failed only to verify it in time. Recording it again with the
181
+ same `action_id` is safe, and `cl.get_action(action_id)` says whether it is there.
182
+
183
+ Every attempt is a request to the API, and today a write the API refuses as `workspace_busy` or `busy` has already
184
+ been counted against the plan's write requests a minute (60 on the Developer plan). A large burst that is mostly
185
+ refused and retried can therefore spend that minute's budget and end in `429 rate_limited`. Retries make a burst
186
+ succeed, not go faster: a caller that sends its writes a few at a time is seldom refused in the first place.
187
+
188
+ The wait blocks the calling thread (`time.sleep`), the decorator included, and a retried poll can add up to the
189
+ same bound to `wait_for_settlement(timeout=...)`. In an event loop, call the client from a worker thread
190
+ (`await asyncio.to_thread(cl.record_action, ...)`) or pass `max_retries=0` and schedule the retry yourself from
191
+ `e.retry_after`. Each retry writes one line at INFO level to the `commitlayer` logger: method, path, status, code and
192
+ the wait, never the key or the body.
193
+
194
+ A custom `transport` is a function `(method, path, body)` that returns `(status, payload)` or
195
+ `(status, payload, headers)`. Only the second form can be retried: without response headers there is no stated
196
+ wait, so the first refusal is raised as it always was. `headers` is a dict or another mapping, the headers object
197
+ of `urllib` and `http.client` (`response.headers`), or a list of `(name, value)` pairs; the name is matched in any
198
+ case, and a header that is there twice counts at the longer wait.
199
+
200
+ ## Correct a failed action
201
+
202
+ ```python
203
+ cl.record_action(
204
+ "refund_workflow",
205
+ "order_10231",
206
+ params={"amount": 180.0},
207
+ action_id="refund:order_10231:fix",
208
+ compensates="refund:order_10231",
209
+ )
210
+ ```
211
+
212
+ Once the correction settles PASS, the failed action carries `resolution.state == "compensated"`; its own verdict never changes.
@@ -0,0 +1,188 @@
1
+ # commitlayer (Python)
2
+
3
+ Record agent actions, push facts from systems of record, read verdicts and draft contracts. Standard library
4
+ only; Python 3.10+.
5
+
6
+ ```bash
7
+ pip install commitlayer
8
+ export COMMITLAYER_API_KEY=spk_... # the agent runtime's key: a *recorder* key (records actions, nothing else)
9
+ export COMMITLAYER_EVIDENCE_KEY=spk_... # the pipeline's key: an *evidence* key bound to the sources it pushes for
10
+ # COMMITLAYER_API_URL defaults to https://api.commitlayer.ai. One credential per side of the line: the key that
11
+ # records an action can never also supply the facts that verify it.
12
+ ```
13
+
14
+ ## Record an action where it happens
15
+
16
+ ```python
17
+ from commitlayer import Client
18
+
19
+ cl = Client(agent_id="support-bot")
20
+
21
+
22
+ @cl.action(
23
+ "refund_workflow",
24
+ subject=lambda order_id, **_: order_id,
25
+ params=lambda amount, **_: {"amount": amount},
26
+ subject_kind="order",
27
+ action_id=lambda order_id, **_: f"refund:{order_id}", # retries update one claim instead of recording two
28
+ )
29
+ def refund(order_id: str, amount: float) -> dict:
30
+ return payments.refund(order_id, amount) # the agent's own work, unchanged
31
+
32
+
33
+ refund("order_10231", 180.0)
34
+ print(refund.last_recorded["verification"]["summary"]["headline"])
35
+ ```
36
+
37
+ The action is recorded **before** the function runs, so its request time precedes every effect. The function's
38
+ return value is never changed and never consulted: verification reads the systems of record. If the API cannot
39
+ be reached the function still runs and a warning is logged (`fail_open=True`); pass `fail_open=False` to raise.
40
+
41
+ ## Push facts, with a watermark
42
+
43
+ Use an **evidence** key here, bound to the sources it pushes for (Settings → API keys). The key your agent runtime records actions with is a **recorder** key and cannot push facts: the credential that records an action never also supplies the facts that verify it.
44
+
45
+ ```python
46
+ import os
47
+
48
+ evidence = Client(api_key=os.environ["COMMITLAYER_EVIDENCE_KEY"]) # the pipeline's own client, not the runtime's
49
+
50
+ evidence.push_facts(
51
+ [
52
+ {
53
+ "source": "crm",
54
+ "subject_id": "order_10231",
55
+ "fact_type": "note_added",
56
+ "occurred_at": "2026-10-13T10:42:09Z",
57
+ }
58
+ ],
59
+ watermarks={"crm": "2026-10-13T10:45:00Z"}, # everything up to here has been sent for crm
60
+ )
61
+ ```
62
+
63
+ A verdict that is not yet a PASS settles only when its window has closed **and** every source it reads has a
64
+ watermark past the end of the window. Declare one when your feed lags; a source that never declares one is taken
65
+ as current.
66
+
67
+ ## Draft a contract from what was recorded
68
+
69
+ ```python
70
+ d = cl.draft_contract("refund_order", lookback_days=30)
71
+ print(d["yaml"]) # expected effects, window, preconditions, limits, from the sample
72
+ print(d["stats"]["effects"])
73
+ v = cl.validate_contract(d["yaml"]) # errors, and weakening warnings against the version it would replace
74
+ cl.save_contract(d["yaml"]) # the response carries the same warnings
75
+ ```
76
+
77
+ Every value in a draft is what the sample showed, not what the policy says. Review it before saving.
78
+
79
+ ## Read a verdict
80
+
81
+ ```python
82
+ v = cl.get_action("refund:order_10231")
83
+ v["status"] # pending | settled
84
+ v["settlement"]["waiting_on"] # sources still behind the window, if any
85
+ v["reversal"] # the later record that undid the action, if any
86
+ v["sources"] # trust level and watermark per source the contract read
87
+ ```
88
+
89
+ ## Wait for the verdict before saying "done"
90
+
91
+ ```python
92
+ v = cl.wait_for_settlement("refund:order_10231", timeout=300) # blocks until settled or 5 minutes
93
+ if v["timed_out"]:
94
+ ... # still pending: your policy, never "success"
95
+ elif v["lenses"]["outcome"]["verdict"] == "PASS":
96
+ notify_customer("Your order is cancelled and refunded.")
97
+ else:
98
+ open_recovery(v) # FAIL: the reasons name what is missing or forbidden
99
+ ```
100
+
101
+ The API holds each call for up to 60 seconds; the SDK loops. The gate reads evidence; it never changes a verdict.
102
+
103
+ ## Install a workflow pack (drafts, never activation)
104
+
105
+ ```python
106
+ packs = cl.packs.list()["items"] # Stripe Customer Operations, x402, Coinbase
107
+ detail = cl.packs.get("stripe_customer_operations") # contracts, requirements, templates, versions
108
+ effective = cl.packs.configure("stripe_customer_operations", {"refund_order": {"approved_limit": 100}})
109
+ report = cl.packs.dry_run("stripe_customer_operations", {"refund_order": {"approved_limit": 100}})
110
+ assert report["summary"]["ok"] == report["summary"]["total"] # every fixture case holds under your limits
111
+ out = cl.packs.install("stripe_customer_operations", {"refund_order": {"approved_limit": 100}}, confirm=True)
112
+ print(out["activation"]["how"]) # POST /v1/contracts/<id>/select, by a person
113
+ mapping = cl.packs.recorder_mapping("stripe_customer_operations") # contract versions pinned
114
+ ```
115
+
116
+ `configure` and `dry_run` write nothing. `install` saves the configured contracts as **drafts**: nothing governs a
117
+ live action until a person activates a version in the app or with `POST /v1/contracts/{id}/select`. Below the
118
+ pack's minimum plan the service answers `402 plan_required` with `upgrade_to`.
119
+
120
+ ## What is retried
121
+
122
+ When the API cannot admit a request it answers `503 busy` (the service is at its limit) or `429` (`workspace_busy`:
123
+ this workspace already has its share of writes in progress; `rate_limited`: its requests a minute are spent) with a
124
+ `Retry-After` header. The client waits the time the header states and sends the same request again, so a burst
125
+ that the API spreads over a few seconds never reaches your code as an error. Since 0.1.3.
126
+
127
+ | | |
128
+ |---|---|
129
+ | Retried | An answer of **429 or 503 that carries `Retry-After`**, as seconds (`1`, `1.5`) or an HTTP-date, for any method of the client. |
130
+ | Not retried | Every other status (400, 402, 404, 409, 500 and the rest), a 429 or 503 **without** the header (the API's limit on requests in flight answers a plain `503` like that), a timeout and a network error: after those the client cannot know whether the request arrived. |
131
+ | How often | `max_retries=3` times after the first attempt. `max_retries=0` turns retrying off. |
132
+ | How long | Never less than the header states, plus a random addition of up to twice as much, so the calls of a burst that were refused together come back spread out, and never more than `max_retry_wait`. A stated wait above `max_retry_wait=10.0` seconds is not waited at all: the error is raised at once (the Developer plan's daily cap, `429 fair_use_exceeded`, states the seconds to midnight). |
133
+ | Worst case | One call waits at most `max_retries * max_retry_wait` seconds, 30 by default, on top of its requests. The API states one second today, so each retry waits between one and three seconds: a call refused once adds one to three seconds, a call that uses all three retries adds three to nine. |
134
+ | The request | Identical on every attempt, byte for byte. `record_action` chooses the `action_id` before the first attempt, so every attempt names the same action and the API records it once. |
135
+
136
+ ```python
137
+ from commitlayer import Client, CommitLayerError
138
+
139
+ cl = Client(max_retries=3, max_retry_wait=10.0) # the defaults
140
+ single = Client(max_retries=0) # never retry: the first refusal is raised
141
+
142
+ try:
143
+ cl.record_action("refund_workflow", "order_10231", action_id="refund:order_10231")
144
+ except CommitLayerError as e:
145
+ e.status, e.code # 429, "workspace_busy": the last answer, as before
146
+ e.retry_after # seconds the last answer asked to wait, or None when it stated none
147
+ e.attempts # how many times the request was sent (4 once three retries are used up)
148
+ ```
149
+
150
+ One request is the exception. `POST /v1/actions` is idempotent on `action_id`, and the API may answer `503 busy`
151
+ after the action itself is stored, so a recording that names no `action_id` is sent once and never repeated.
152
+ `record_action` and the `@cl.action` decorator always name one; this only concerns a body you build yourself for
153
+ `cl.request("POST", "/v1/actions", ...)` or an inline `cl.verify(action=...)` that is stored.
154
+
155
+ For the same reason a `503` that `record_action` still raises, after its retries or without any, does not prove
156
+ the action is absent: the API may have stored it and failed only to verify it in time. Recording it again with the
157
+ same `action_id` is safe, and `cl.get_action(action_id)` says whether it is there.
158
+
159
+ Every attempt is a request to the API, and today a write the API refuses as `workspace_busy` or `busy` has already
160
+ been counted against the plan's write requests a minute (60 on the Developer plan). A large burst that is mostly
161
+ refused and retried can therefore spend that minute's budget and end in `429 rate_limited`. Retries make a burst
162
+ succeed, not go faster: a caller that sends its writes a few at a time is seldom refused in the first place.
163
+
164
+ The wait blocks the calling thread (`time.sleep`), the decorator included, and a retried poll can add up to the
165
+ same bound to `wait_for_settlement(timeout=...)`. In an event loop, call the client from a worker thread
166
+ (`await asyncio.to_thread(cl.record_action, ...)`) or pass `max_retries=0` and schedule the retry yourself from
167
+ `e.retry_after`. Each retry writes one line at INFO level to the `commitlayer` logger: method, path, status, code and
168
+ the wait, never the key or the body.
169
+
170
+ A custom `transport` is a function `(method, path, body)` that returns `(status, payload)` or
171
+ `(status, payload, headers)`. Only the second form can be retried: without response headers there is no stated
172
+ wait, so the first refusal is raised as it always was. `headers` is a dict or another mapping, the headers object
173
+ of `urllib` and `http.client` (`response.headers`), or a list of `(name, value)` pairs; the name is matched in any
174
+ case, and a header that is there twice counts at the longer wait.
175
+
176
+ ## Correct a failed action
177
+
178
+ ```python
179
+ cl.record_action(
180
+ "refund_workflow",
181
+ "order_10231",
182
+ params={"amount": 180.0},
183
+ action_id="refund:order_10231:fix",
184
+ compensates="refund:order_10231",
185
+ )
186
+ ```
187
+
188
+ Once the correction settles PASS, the failed action carries `resolution.state == "compensated"`; its own verdict never changes.