delegate-connector-slack 0.1.0__py3-none-any.whl

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,153 @@
1
+ Metadata-Version: 2.4
2
+ Name: delegate-connector-slack
3
+ Version: 0.1.0
4
+ Summary: OSS Slack connector for the Terrene Delegate substrate (kailash.delegate).
5
+ Project-URL: Homepage, https://github.com/terrene-foundation/delegate-connectors
6
+ Project-URL: Changelog, https://github.com/terrene-foundation/delegate-connectors/blob/main/CHANGELOG.md
7
+ Author: Terrene Foundation
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: chat,connector,delegate,kailash,messaging,slack
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: OS Independent
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: Topic :: Communications :: Chat
19
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
20
+ Requires-Python: >=3.10
21
+ Requires-Dist: aiohttp>=3.7.3
22
+ Requires-Dist: cryptography>=42.0
23
+ Requires-Dist: kailash>=2.28.0
24
+ Requires-Dist: slack-sdk>=3.27.0
25
+ Provides-Extra: test
26
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'test'
27
+ Requires-Dist: pytest>=8.0; extra == 'test'
28
+ Requires-Dist: python-dotenv>=1.0; extra == 'test'
29
+ Description-Content-Type: text/markdown
30
+
31
+ <!--
32
+ Copyright 2026 Terrene Foundation
33
+ SPDX-License-Identifier: Apache-2.0
34
+ -->
35
+
36
+ # delegate-connector-slack
37
+
38
+ An OSS Python connector for the Terrene Delegate substrate. Implements the
39
+ shipped `kailash.delegate.Connector` ABC (kailash 2.26.2) for Slack — the same
40
+ contract the email + WhatsApp connectors implement, with a Slack Web API
41
+ transport:
42
+
43
+ - **`write`** — `chat.postMessage` outbound send via the Slack Web API
44
+ (`AsyncWebClient`), executed under audit, returns a real
45
+ `SignedActionEnvelope`.
46
+ - **`read`** — a bounded `conversations.history` pull (one page per call),
47
+ executed under audit, returns `(messages, AttestedReadReceipt)`. The audited
48
+ manifest carries the channel + message `ts` ids + count only — never message
49
+ body bytes.
50
+ - **`authenticate`** — resolves a dispatch identity's `delegate_id` to a
51
+ `Principal` against a `SlackPrincipalResolver` (exact-match in v0; an unknown
52
+ identity resolves to `Reject`, fail-closed).
53
+ - **`invoke`** — single-method dispatch entry (used by the dispatch hot path);
54
+ authenticates FIRST (so an unknown sender's `Reject` fires before any Slack
55
+ API call), then posts via the audited `write` path and returns a
56
+ `ConnectorInvocationResult`.
57
+ - Trust properties — `auth_verifier` returns the supplied real
58
+ `Ed25519Verifier`; `ledger` returns an in-memory `InMemoryKnowledgeLedger`;
59
+ `revocation` returns a never-revoked `NeverRevokedChannel` (both
60
+ Protocol-satisfying deterministic concretes; framework-first, no custom trust
61
+ primitives).
62
+
63
+ It subclasses `Connector` **directly** (ADR-1) — NOT `LegacyInvokeConnector`,
64
+ whose proxied `read`/`write` emit empty, unverifiable receipts. This connector's
65
+ `read`/`write` produce non-empty receipts that verify under a real
66
+ `Ed25519Verifier`. It has no Rust-sibling dependency — it is a pure-Python
67
+ connector.
68
+
69
+ ## Inbound is a bounded `conversations.history` pull
70
+
71
+ Inbound messages are read via a bounded `conversations.history` pull, NOT Socket
72
+ Mode (ADR-S1). A persistent Socket Mode connection conflicts with the connector's
73
+ one-shot `read` thunk contract (one bounded fetch per audited read receipt), so
74
+ the connector pulls a single page per `read` call rather than holding an
75
+ event-streaming socket open.
76
+
77
+ ## Injection boundary
78
+
79
+ User-controlled message text is mrkdwn-escaped (`&`/`<`/`>`) and every id-bound
80
+ field is shape-validated at the `OutboundSlackMessage` construction boundary
81
+ (ADR-S3), so an injected `<@U…>` mention, `<!channel>` broadcast, or
82
+ `<url|label>` link cannot render live. Every outbound send route builds an
83
+ `OutboundSlackMessage` first, so the boundary covers all of them. Block Kit /
84
+ `attachments` / `blocks` are out of v0 scope — scoping them out removes the
85
+ structural-injection vector entirely (ADR-S3).
86
+
87
+ ## Install
88
+
89
+ ```bash
90
+ pip install -e connectors/slack
91
+ ```
92
+
93
+ ## Configure
94
+
95
+ All credentials come from the environment (see `.env.example`):
96
+ `SLACK_BOT_TOKEN` is the `xoxb-…` bot token (required; one bot-token credential
97
+ family covers both directions). `SLACK_API_BASE_URL` optionally overrides the
98
+ Web API base URL — used to point the client at the local in-process test server.
99
+ Nothing is hardcoded; nothing is logged.
100
+
101
+ ## Test
102
+
103
+ Tier-1 (unit, no I/O, no Slack Web API client required):
104
+
105
+ ```bash
106
+ pip install -e "connectors/slack[test]"
107
+ python -m pytest connectors/slack/tests/unit -q
108
+ ```
109
+
110
+ Tier-2/3 (real infra — an in-process protocol-faithful Slack Web API server over
111
+ a real socket; no mocks at the boundary):
112
+
113
+ ```bash
114
+ python -m pytest connectors/slack/tests/integration -q
115
+ ```
116
+
117
+ Because `slack_sdk`'s `AsyncWebClient` is aiohttp-based, the Tier-2 surrogate is
118
+ a **real in-process aiohttp server bound to an ephemeral port** (ADR-S4) — the
119
+ connector's real `AsyncWebClient` is pointed at it via `SLACK_API_BASE_URL`. This
120
+ is a Protocol-satisfying deterministic adapter over a real socket, not a mock at
121
+ the connector boundary, so the integration tests RUN (they do not skip). The
122
+ opt-in Tier-3 live-Slack test skips with a clear "cannot execute" reason unless
123
+ `SLACK_LIVE_E2E=1` plus real `SLACK_BOT_TOKEN` + `SLACK_LIVE_E2E_CHANNEL` are set
124
+ (it never falls back to a mock).
125
+
126
+ Conformance (canonical vector well-formedness + connector composition):
127
+
128
+ ```bash
129
+ python -m pytest connectors/slack/tests/conformance -q
130
+ ```
131
+
132
+ Regression (behavioral security guards — receipt identity binding,
133
+ authenticate-first fail-closed gate, outbound construction-boundary validation):
134
+
135
+ ```bash
136
+ python -m pytest connectors/slack/tests/regression -q
137
+ ```
138
+
139
+ ## Known limitation — runtime `execute()` audit gate
140
+
141
+ `compose.py` builds a real `DelegateRuntime` around the connector. However the
142
+ shipped `kailash.delegate` runtime/dispatch audit-emit path signs the event
143
+ payload bytes while `AuditChainEngine.emit_event` verifies the signature against
144
+ the full audit-entry signing bytes — so `runtime.execute()` fails at the first
145
+ audit emission under any real verifier (kailash-py#1182). This is an SDK bug in
146
+ `kailash.delegate`, not in this connector; the connector's own `read`/`write`
147
+ receipts verify correctly. The end-to-end `runtime.execute()` assertion is gated
148
+ on the SDK fix (a strict xfail in the conformance + e2e suites); the
149
+ connector-level post → history round-trip and receipt verification are not.
150
+
151
+ ## License
152
+
153
+ Apache 2.0. All open-source IP is owned by the Terrene Foundation.
@@ -0,0 +1,10 @@
1
+ delegate_connectors/slack/__init__.py,sha256=LSu8vxk-hCwkLLwf8YfyHBYxG1bgxY-JtMtzWNB6AcM,1155
2
+ delegate_connectors/slack/compose.py,sha256=a4vb3j0UtmtmUabJ1pgj_SBGMbmy182VoIdP-1ZqSLo,8998
3
+ delegate_connectors/slack/connector.py,sha256=CcoFXlbJ5he0Na5nNeb254qdgMiaFQGMNFqpG9Lakl0,20150
4
+ delegate_connectors/slack/directory.py,sha256=Ye0M9xaxzYFoYk8H0SYFgeSjWEfnxBbM2eAd94nWqVQ,6310
5
+ delegate_connectors/slack/messages.py,sha256=jeyz23ug61MZHk-k3PBLI9QsG98aBgPg-0uUpTCZ_-w,6584
6
+ delegate_connectors/slack/web_api.py,sha256=0_YpTyfzKj4QBOmyCAaELRWf4UpzJrWdT8699UTBJOE,12980
7
+ delegate_connector_slack-0.1.0.dist-info/METADATA,sha256=n8-DzWcY5lJ9VcHk-diU6s8D1shBKYK_25bqKNYtVLY,6638
8
+ delegate_connector_slack-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
9
+ delegate_connector_slack-0.1.0.dist-info/licenses/LICENSE,sha256=DKFbIQY8niGx_We4B50lQtmpWkQ7i0aLU8vRC5MGkx0,11290
10
+ delegate_connector_slack-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for describing the origin of the Work and
141
+ reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Support. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or support.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Terrene Foundation
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,38 @@
1
+ # Copyright 2026 Terrene Foundation
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Slack connector for the Terrene Delegate substrate.
4
+
5
+ Implements the shipped ``kailash.delegate.Connector`` ABC (kailash 2.26.2) for
6
+ Slack: ``chat.postMessage`` outbound (``write``) and ``conversations.history``
7
+ inbound (``read``), authenticated against a :class:`SlackPrincipalResolver`. See
8
+ the package README + ``specs/`` in the monorepo root for the full contract.
9
+
10
+ This module exports the pure-logic foundation (message types + injection
11
+ boundary, principal resolution). The transport + connector + runtime composition
12
+ land in later shards.
13
+ """
14
+
15
+ __version__ = "0.1.0"
16
+
17
+ from delegate_connectors.slack.directory import (
18
+ ResolutionOutcome,
19
+ SlackPrincipalResolver,
20
+ UnknownSenderDisposition,
21
+ )
22
+ from delegate_connectors.slack.messages import (
23
+ InboundSlackMessage,
24
+ OutboundSlackMessage,
25
+ SlackFieldError,
26
+ normalize_slack_id,
27
+ )
28
+
29
+ __all__ = [
30
+ "OutboundSlackMessage",
31
+ "InboundSlackMessage",
32
+ "SlackFieldError",
33
+ "normalize_slack_id",
34
+ "SlackPrincipalResolver",
35
+ "UnknownSenderDisposition",
36
+ "ResolutionOutcome",
37
+ "__version__",
38
+ ]
@@ -0,0 +1,246 @@
1
+ # Copyright 2026 Terrene Foundation
2
+ # SPDX-License-Identifier: Apache-2.0
3
+ """Compose a runnable ``DelegateRuntime`` around a :class:`SlackConnector`.
4
+
5
+ Builds the full shipped composition — ``PrincipalDirectory`` +
6
+ ``Ed25519Verifier``, in-memory ``AuditChainEngine`` over a ``TrustLineageChain``,
7
+ ``TenantScopedCascade`` (root grantee registered with a real Ed25519 grant
8
+ proof), ``Role``, ``DispatchSurface``, and ``DelegateRuntime`` — using the
9
+ spine-shipped concretes for everything except the connector. No mocks; no
10
+ Postgres; no PACT (the shipped runtime audit is in-memory).
11
+
12
+ The runtime is constructed with a real ``Ed25519Verifier`` (NOT ``NullVerifier``)
13
+ and a real Ed25519 ``signer``. All constructors succeed and the composition
14
+ passes the runtime's R2-composition gate.
15
+
16
+ ``runtime.execute()`` — end-to-end (fixed at kailash >= 2.28.0):
17
+ Previously gated on kailash-py#1182 — the runtime/dispatch audit-emit path
18
+ signed the event PAYLOAD bytes while ``AuditChainEngine.emit_event`` verified
19
+ the FULL audit-entry signing bytes, so ``execute()`` returned
20
+ ``taod_state.phase == "failed"`` under any real verifier at the first phase
21
+ transition. Fixed at kailash <= 2.28.1 (the connector floor is now
22
+ ``>=2.28.0``); ``runtime.execute()`` now completes end-to-end carrying a
23
+ verifiable signed action envelope. See
24
+ ``workspaces/whatsapp/journal/0008-DISCOVERY-F2-scope-correction-1182-fixed-but-flip-non-uniform.md``.
25
+ """
26
+
27
+ from __future__ import annotations
28
+
29
+ import uuid
30
+ from dataclasses import dataclass
31
+ from datetime import datetime, timezone
32
+
33
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey
34
+
35
+ from kailash.delegate import (
36
+ AuditChainEngine,
37
+ DelegateIdentity,
38
+ DelegateRuntime,
39
+ DispatchSurface,
40
+ Ed25519Verifier,
41
+ PrincipalDirectory,
42
+ )
43
+ from kailash.delegate.dispatch import Principal
44
+ from kailash.delegate.envelope import DelegateConstraintEnvelope
45
+ from kailash.delegate.trust import TenantScope, TenantScopedCascade
46
+ from kailash.delegate.types import (
47
+ CapabilitySet,
48
+ DelegateGenesisRecord,
49
+ Role,
50
+ RoleLifecycleState,
51
+ RoleScope,
52
+ )
53
+ from kailash.trust._json import canonical_json_dumps
54
+ from kailash.trust.chain import AuthorityType, GenesisRecord, TrustLineageChain
55
+ from kailash.trust.envelope import ConstraintEnvelope
56
+
57
+ from delegate_connectors.slack.connector import SlackConnector
58
+ from delegate_connectors.slack.directory import SlackPrincipalResolver
59
+ from delegate_connectors.slack.web_api import SlackTransport
60
+
61
+ __all__ = [
62
+ "SlackV0Signature",
63
+ "ComposedSlackRuntime",
64
+ "build_slack_runtime",
65
+ ]
66
+
67
+
68
+ @dataclass(frozen=True, slots=True)
69
+ class SlackV0Signature:
70
+ """Minimal application-supplied dispatch signature (v0 fixture).
71
+
72
+ Satisfies the shipped ``SignatureContract`` Protocol (``name`` +
73
+ ``input_schema`` + ``output_schema``). This is a DOCUMENTED v0 placeholder:
74
+ real applications supply their own structured signature. It is NOT a
75
+ stub-for-production — it is the genuine, minimal v0 dispatch contract for a
76
+ Slack post, and it is honored by the dispatch surface's input validation.
77
+ """
78
+
79
+ name: str = "slack-post"
80
+ input_schema: dict[str, type] | None = None
81
+ output_schema: dict[str, type] | None = None
82
+
83
+ def __post_init__(self) -> None:
84
+ if self.input_schema is None:
85
+ object.__setattr__(
86
+ self,
87
+ "input_schema",
88
+ {"channel": str, "text": str},
89
+ )
90
+ if self.output_schema is None:
91
+ object.__setattr__(
92
+ self,
93
+ "output_schema",
94
+ {"ok": bool, "ts": str, "channel": str},
95
+ )
96
+
97
+
98
+ @dataclass(frozen=True, slots=True)
99
+ class ComposedSlackRuntime:
100
+ """The composed runtime plus the handles a caller needs to drive it.
101
+
102
+ ``runtime.execute(payload)`` is the dispatch entry (see the module-level
103
+ KNOWN SDK BLOCKER). ``connector`` is the bound :class:`SlackConnector`;
104
+ ``verifier`` verifies every receipt the connector signs; ``identity`` is the
105
+ dispatch identity registered as the cascade root grantee.
106
+ """
107
+
108
+ runtime: DelegateRuntime
109
+ dispatch_surface: DispatchSurface
110
+ connector: SlackConnector
111
+ verifier: Ed25519Verifier
112
+ identity: DelegateIdentity
113
+ audit_engine: AuditChainEngine
114
+
115
+
116
+ def build_slack_runtime(
117
+ *,
118
+ transport: SlackTransport,
119
+ sender_slack_id: str,
120
+ sender_principal_tenant: str = "tenant-slack-v0",
121
+ signing_key: Ed25519PrivateKey | None = None,
122
+ ) -> ComposedSlackRuntime:
123
+ """Compose a real ``DelegateRuntime`` around a :class:`SlackConnector`.
124
+
125
+ All trust/audit/verifier concretes are the spine-shipped ones; only the
126
+ connector is connector-specific. The returned runtime is reusable and holds
127
+ no per-call global state.
128
+
129
+ Args:
130
+ transport: the connector's Slack Web API transport (point it at the
131
+ Tier-2 mock-server container in integration tests via
132
+ ``SLACK_API_BASE_URL``, the live Slack API in production).
133
+ sender_slack_id: the Slack id the dispatch identity authenticates as
134
+ (the primary resolver key is ``delegate_id`` per ADR-S2; this Slack
135
+ id is the SECONDARY index for payload attribution).
136
+ sender_principal_tenant: the tenant the connector operates under.
137
+ signing_key: optional Ed25519 key; generated if absent. The matching
138
+ public key is registered in the directory so the connector's
139
+ receipts verify under the composed verifier.
140
+ """
141
+ sk = signing_key or Ed25519PrivateKey.generate()
142
+ pk_bytes = sk.public_key().public_bytes_raw()
143
+
144
+ def signer(canonical_bytes: bytes) -> str:
145
+ # Ed25519 signature (64 bytes) -> 128-char lowercase hex, the
146
+ # audit-engine + dispatch-surface signer contract.
147
+ return sk.sign(canonical_bytes).hex()
148
+
149
+ delegate_id = uuid.uuid4()
150
+ identity = DelegateIdentity(
151
+ delegate_id=delegate_id,
152
+ sovereign_ref="slack-connector-sovereign",
153
+ role_binding_ref="slack-connector-role-binding",
154
+ genesis_ref="slack-connector-genesis",
155
+ principal_kind="delegate",
156
+ )
157
+
158
+ directory = PrincipalDirectory(
159
+ identities=(identity,),
160
+ verification_keys={delegate_id: pk_bytes},
161
+ )
162
+ verifier = Ed25519Verifier(directory)
163
+
164
+ # In-memory audit chain (no Postgres) gated by the same verifier class.
165
+ genesis_block = GenesisRecord(
166
+ id="slack-genesis-block",
167
+ agent_id=str(delegate_id),
168
+ authority_id="slack-connector-authority",
169
+ authority_type=AuthorityType.SYSTEM,
170
+ created_at=datetime.now(timezone.utc),
171
+ signature="00" * 64,
172
+ )
173
+ chain = TrustLineageChain(genesis=genesis_block)
174
+ audit_engine = AuditChainEngine(chain=chain, verifier=verifier)
175
+
176
+ delegate_genesis = DelegateGenesisRecord(
177
+ block=genesis_block, spec_version="0", capabilities=("slack.post",)
178
+ )
179
+ envelope = DelegateConstraintEnvelope.from_genesis(
180
+ ConstraintEnvelope(), delegate_genesis
181
+ )
182
+
183
+ # Tenant cascade; register the dispatch identity as root grantee with a
184
+ # real Ed25519 grant proof (a wired verifier refuses an unsigned seed).
185
+ tenant = TenantScope.for_tenant(sender_principal_tenant)
186
+ cascade = TenantScopedCascade(tenant=tenant, verifier=verifier)
187
+ grant_canonical = canonical_json_dumps(
188
+ {"delegate_id": str(delegate_id), "tenant": tenant.tenant_id}
189
+ ).encode("utf-8")
190
+ cascade.register_root_grantee(identity, grant_proof=sk.sign(grant_canonical).hex())
191
+
192
+ role = Role(
193
+ role_id=uuid.uuid4(),
194
+ display_name="slack-connector-role",
195
+ scope=RoleScope(
196
+ domain="slack",
197
+ capabilities=CapabilitySet(capabilities=("slack.post",)),
198
+ ),
199
+ lifecycle=RoleLifecycleState.ACTIVE,
200
+ )
201
+
202
+ resolver = SlackPrincipalResolver(
203
+ {
204
+ sender_slack_id: Principal(
205
+ delegate_id=str(delegate_id),
206
+ tenant_id=tenant.tenant_id,
207
+ claims={"slack_user_id": sender_slack_id},
208
+ )
209
+ }
210
+ )
211
+
212
+ connector = SlackConnector(
213
+ transport=transport,
214
+ resolver=resolver,
215
+ signing_key=sk,
216
+ verifier=verifier,
217
+ tenant_id=tenant.tenant_id,
218
+ )
219
+
220
+ dispatch_surface = DispatchSurface(
221
+ connector,
222
+ SlackV0Signature(),
223
+ envelope,
224
+ identity,
225
+ audit_engine=audit_engine,
226
+ trust_cascade=cascade,
227
+ role=role,
228
+ signer=signer,
229
+ verifier=verifier,
230
+ )
231
+ runtime = DelegateRuntime(
232
+ dispatch_surface=dispatch_surface,
233
+ audit_engine=audit_engine,
234
+ cascade=cascade,
235
+ envelope=envelope,
236
+ identity=identity,
237
+ signer=signer,
238
+ )
239
+ return ComposedSlackRuntime(
240
+ runtime=runtime,
241
+ dispatch_surface=dispatch_surface,
242
+ connector=connector,
243
+ verifier=verifier,
244
+ identity=identity,
245
+ audit_engine=audit_engine,
246
+ )