@fabric-harness/channels 0.17.4 → 0.19.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.
package/README.md CHANGED
@@ -40,4 +40,120 @@ export default createAgent(({ id }) => {
40
40
  });
41
41
  ```
42
42
 
43
+ ## Buzz (preview)
44
+
45
+ [Buzz](https://github.com/block/buzz) is a self-hostable Nostr-based workspace where humans and
46
+ agents share channels. Unlike webhook vendors, Buzz pushes over a NIP-01 WebSocket, so ingress uses
47
+ the `buzz-tail` transport shim: it holds a NIP-42-authenticated subscription and forwards events to
48
+ the channel's `/events` route inside a timestamped `X-Fabric-Signature: v1=` HMAC envelope (same
49
+ route a future Buzz workflow `call_webhook` egress can target). The handler additionally verifies
50
+ each inner event's Schnorr signature, so the acting `actor` is the cryptographically proven author
51
+ pubkey. Requires `nostr-tools` (declared dependency; the only non-Fetch/WebCrypto adapter, hence
52
+ `status: preview` + `sdk: nostr-tools` in the compatibility contract).
53
+
54
+ ```ts
55
+ // .fabricharness/channels/buzz.ts
56
+ import { buzzPublicKey, createBuzzChannel } from '@fabric-harness/channels/buzz';
57
+ import { buzzState } from '../state/buzz.js';
58
+
59
+ const channels = ['gtm-pipeline'];
60
+
61
+ export const channel = createBuzzChannel({
62
+ agent: 'assistant',
63
+ sharedSecret: process.env.BUZZ_ENVELOPE_SECRET!,
64
+ selfPubkey: buzzPublicKey(process.env.BUZZ_PRIVATE_KEY!),
65
+ community: 'acme',
66
+ channels,
67
+ decisionReceiptStore: buzzState.deliveryStore,
68
+ });
69
+ ```
70
+
71
+ ```ts
72
+ // tail process (Node >= 22), co-deployed with the app
73
+ import { startBuzzTail } from '@fabric-harness/channels/buzz-tail';
74
+ import { buzzState } from '../state/buzz.js';
75
+
76
+ const channels = ['gtm-pipeline'];
77
+
78
+ startBuzzTail({
79
+ relayUrl: process.env.BUZZ_RELAY_URL!,
80
+ secretKey: process.env.BUZZ_PRIVATE_KEY!,
81
+ community: 'acme', // must equal the channel's server-owned community
82
+ channels, // same server-owned channel allowlist used by createBuzzChannel
83
+ forwardUrl: 'https://app/channels/buzz/events',
84
+ sharedSecret: process.env.BUZZ_ENVELOPE_SECRET!,
85
+ cursorStore: buzzState.cursorStore,
86
+ deadLetterStore: buzzState.deadLetterStore,
87
+ });
88
+ ```
89
+
90
+ For PostgreSQL or Databricks Lakebase, inject the application's existing `pg.Pool` into
91
+ the dependency-free structural client boundary. One scoped state object supplies all
92
+ three production stores:
93
+
94
+ ```ts
95
+ import { createPostgresBuzzPersistence } from '@fabric-harness/channels/buzz-postgres';
96
+ import { Pool } from 'pg';
97
+
98
+ export const buzzState = createPostgresBuzzPersistence({
99
+ client: new Pool({ connectionString: process.env.DATABASE_URL }),
100
+ consumerId: 'gtm-primary', // stable and unique per deployed consumer
101
+ });
102
+ ```
103
+
104
+ `createPostgresBuzzPersistence()` initializes isolated cursor, dead-letter, and
105
+ decision-card-delivery tables. Pass `initialize: false` when migrations own DDL and call
106
+ `ensurePostgresBuzzTables()` from the migration boundary instead. The same contract works
107
+ with Lakebase clients that implement the structural `query()` method; no Databricks or
108
+ PostgreSQL dependency is loaded by the core channel adapter.
109
+
110
+ The tail is a durable consumer, not a best-effort reconnect loop: it persists a
111
+ cursor (advanced only after a 2xx forward or durably recorded dead-letter), pages a
112
+ complete bounded `POST /query` snapshot backward and forwards it oldest-first on every
113
+ (re)start, forwards in order with retry classification (408/429/5xx/network retry with bounded
114
+ backoff; other 4xx go to `deadLetterStore` for reconciliation), answers
115
+ NIP-42 challenges including `OK` acknowledgement and `CLOSED` re-subscription,
116
+ enforces NIP-11 limits, and propagates cancellation and per-request timeouts. It fails
117
+ closed when the cursor, backfill, or dead-letter store is unavailable. Use
118
+ `reconcileBuzzDeadLetters()` from a bounded scheduled worker to replay unresolved records
119
+ through the ordinary verified/governed ingress path. The channel route derives the tenant from
120
+ its own `community` option (server-owned configuration) and refuses envelopes
121
+ claiming any other community with 403 — the tenant is never taken from the
122
+ event or envelope.
123
+
124
+ Outbound tools: `postInBuzzChannel`, `replyInBuzzThread`, `addBuzzReaction`. The tail
125
+ also enforces NIP-11 at connect (`requiredNips`, default `[1, 42]`) and refuses relays
126
+ that do not advertise them; `probeBuzzRelay` is exported for standalone detection.
127
+
128
+ **Decisions are deterministic and model-free** (`@fabric-harness/channels/buzz-decisions`,
129
+ plan D14): `postBuzzDecisionCard` renders the canonical card from request data (never
130
+ agent prose), signs it, and persists the exact immutable event plus its **card receipt**
131
+ before relay I/O. A retry reuses the same Nostr event id, queries that id after an
132
+ ambiguous response, and only then marks publication. The receipt binds
133
+ `(community, channel, cardEventId)` to
134
+ `(approvalRequestId, requestVersion, parametersHash, options, expiry)`. The
135
+ `createBuzzDecisionBridge` resolves a signed reaction through the receipt store and a
136
+ fixed emoji table (`👍/✅/+ → approve`, `👎/❌/- → reject`) into exactly one
137
+ decision candidate carrying the attested Nostr identity and source-event proof; unmapped
138
+ emoji surface for audit, free-form replies resolve to **edit proposals** that require
139
+ structured confirmation, and everything else is ordinary conversation. The bridge
140
+ performs zero authorization and signals nothing — the vertical's governed decision
141
+ action owns binding resolution, capability, validation, and the decision transaction.
142
+ Stock Buzz Desktop emits NIP-25 reactions with an `e` target and no `h` channel tag. To
143
+ support that shape, give `createBuzzChannel` the same durable receipt store used by
144
+ `postBuzzDecisionCard` plus an explicit `channels` allowlist. The route derives the
145
+ channel only when the reaction has one target and exactly one receipt matches it inside
146
+ that allowlist. Missing, malformed, cross-channel, and ambiguous matches are ignored;
147
+ receipt-store failures fail the forward so the durable tail retries. Receipt correlation
148
+ only recovers transport scope: the normal governed identity, membership, expiry,
149
+ request-version, parameter-hash, and compare-and-swap checks remain mandatory downstream.
150
+
151
+ Migration from channels 0.18.x: `postBuzzDecisionCard()` now requires
152
+ `deliveryStore: BuzzDecisionCardDeliveryStore` instead of a write-only `receiptStore`.
153
+ The route still consumes its lookup-only `decisionReceiptStore`; in production both must
154
+ be views over the same durable store (`buzzState.deliveryStore`). This closes the
155
+ post-succeeded/receipt-write-failed split-brain window.
156
+ Vendored kind constants are guarded by `scripts/sync-buzz-kinds.mjs` against a Buzz
157
+ checkout's `buzz-core/src/kind.rs`.
158
+
43
159
  See [`docs/channels-design.md`](../../docs/channels-design.md).
@@ -0,0 +1,200 @@
1
+ import type { ToolDef } from "@fabric-harness/sdk/channel";
2
+ import type { BuzzEvent, BuzzPostConfig, BuzzThreadRef } from "./buzz.js";
3
+ /**
4
+ * Deterministic, model-free decision surface for Buzz (Fabric Buzz
5
+ * Collaboration Plan D14; B1-H items 5–6).
6
+ *
7
+ * A signed reaction is mapped by trusted code from
8
+ * `(community, channel, targetEventId)` to exactly one immutable
9
+ * ApprovalRequest via a **card receipt** stored when the card was posted. A
10
+ * model may explain or acknowledge the result; it never selects the request,
11
+ * choice, principal, edits, or parameters. Free-form replies to a card are
12
+ * **edit proposals** — never approvals — until validated and explicitly
13
+ * confirmed through a structured decision path.
14
+ *
15
+ * Layering: this module performs zero authorization and signals nothing. It
16
+ * resolves candidates; the vertical's governed decision action (plan A2)
17
+ * resolves identity bindings, checks capability, validates choice/expiry/
18
+ * edits, and owns the decision transaction + signal outbox.
19
+ */
20
+ export interface BuzzDecisionCardInput {
21
+ approvalRequestId: string;
22
+ /** Version of the ApprovalRequest this card was rendered from. */
23
+ requestVersion: number;
24
+ proposedActionId: string;
25
+ /** `sha256:<hex>` pin of the proposed parameters. */
26
+ proposedParametersHash: string;
27
+ /** Canonical title derived from action/evidence data — not agent prose. */
28
+ title: string;
29
+ /** Canonical summary derived from action/evidence data — not agent prose. */
30
+ summary: string;
31
+ options: ReadonlyArray<"approve" | "reject" | "approve-with-edits">;
32
+ /** ISO-8601 expiry of the request. */
33
+ expiresAt: string;
34
+ /**
35
+ * The ONLY link a card may carry: the governed vertical surface holding the
36
+ * full record (threat model T13/§2 — C2+ payloads stay linked, never posted).
37
+ */
38
+ detailsUrl?: string;
39
+ }
40
+ /**
41
+ * Render the canonical decision card. Pure and deterministic: identical input
42
+ * yields byte-identical content and tags. The card's human-readable content is
43
+ * informational; all authority derives from the stored receipt, never from
44
+ * parsing this text back.
45
+ */
46
+ export declare function renderBuzzDecisionCard(input: BuzzDecisionCardInput): {
47
+ content: string;
48
+ tags: string[][];
49
+ };
50
+ /**
51
+ * The binding between a posted card and its ApprovalRequest (plan §4 step 2).
52
+ * Stored by the trusted renderer beside the request; the bridge resolves
53
+ * reactions through it and through nothing else.
54
+ */
55
+ export interface BuzzCardReceipt {
56
+ approvalRequestId: string;
57
+ requestVersion: number;
58
+ proposedParametersHash: string;
59
+ relayUrl: string;
60
+ community: string;
61
+ channelId: string;
62
+ /** Stable id of the exact client-signed card event. */
63
+ cardEventId: string;
64
+ options: BuzzDecisionCardInput["options"];
65
+ expiresAt: string;
66
+ postedAt: string;
67
+ }
68
+ /** Receipt lookup shared by ingress correlation and the deterministic bridge. */
69
+ export interface BuzzCardReceiptStore {
70
+ findByCardEvent(community: string, channelId: string, cardEventId: string): Promise<BuzzCardReceipt | undefined>;
71
+ }
72
+ export type BuzzDecisionCardDeliveryStatus = "prepared" | "published";
73
+ /**
74
+ * Durable outbox record for one canonical decision card. The exact signed
75
+ * event is persisted before relay I/O, making its Nostr id stable across
76
+ * retries and ambiguous network outcomes.
77
+ */
78
+ export interface BuzzDecisionCardDelivery {
79
+ deliveryKey: string;
80
+ event: BuzzEvent;
81
+ receipt: BuzzCardReceipt;
82
+ status: BuzzDecisionCardDeliveryStatus;
83
+ preparedAt: string;
84
+ publishedAt?: string;
85
+ }
86
+ /**
87
+ * Production decision-card store. Implement this beside the vertical's
88
+ * ApprovalRequest. `prepareDelivery` is an immutable put-if-absent by
89
+ * deliveryKey and returns the existing record on retry. Publication marking
90
+ * must be idempotent.
91
+ */
92
+ export interface BuzzDecisionCardDeliveryStore extends BuzzCardReceiptStore {
93
+ prepareDelivery(delivery: BuzzDecisionCardDelivery): Promise<BuzzDecisionCardDelivery>;
94
+ markDeliveryPublished(deliveryKey: string, publishedAt: string): Promise<void>;
95
+ }
96
+ /** Stable logical identity for one request version on one Buzz surface. */
97
+ export declare function buzzDecisionCardDeliveryKey(community: string, channelId: string, approvalRequestId: string, requestVersion: number): string;
98
+ /** Test/development receipt store. Not durable — never use in production. */
99
+ export declare function inMemoryBuzzCardReceiptStore(): BuzzDecisionCardDeliveryStore & {
100
+ all(): BuzzCardReceipt[];
101
+ deliveries(): BuzzDecisionCardDelivery[];
102
+ };
103
+ /**
104
+ * Outbound tool: durably prepare the exact signed event + receipt, submit it,
105
+ * reconcile an ambiguous response by exact event id, then checkpoint
106
+ * publication. Returns the receipt. Posting a card grants nothing by itself.
107
+ */
108
+ export declare function postBuzzDecisionCard(ref: BuzzThreadRef, config: BuzzPostConfig & {
109
+ deliveryStore: BuzzDecisionCardDeliveryStore;
110
+ now?: () => number;
111
+ }): ToolDef<BuzzDecisionCardInput, BuzzCardReceipt>;
112
+ /**
113
+ * Fixed reaction→choice table (D14). NIP-25 `+`/`-` are included alongside
114
+ * the emoji the card legend shows. Anything else on a card is `unmapped` —
115
+ * surfaced for audit, never guessed.
116
+ */
117
+ export declare const BUZZ_DECISION_EMOJI: Readonly<Record<string, "approve" | "reject">>;
118
+ /** Normalized reaction input as dispatched by the Buzz channel route. */
119
+ export interface BuzzReactionInput {
120
+ type: "buzz.reaction";
121
+ emoji: string;
122
+ targetEventId?: string;
123
+ eventId: string;
124
+ pubkey: string;
125
+ channelId: string;
126
+ }
127
+ /** Normalized message input as dispatched by the Buzz channel route. */
128
+ export interface BuzzMessageInput {
129
+ type: "buzz.message";
130
+ text: string;
131
+ eventId: string;
132
+ pubkey: string;
133
+ channelId: string;
134
+ rootEventId: string;
135
+ tags?: string[][];
136
+ }
137
+ export interface BuzzDecisionCandidate {
138
+ approvalRequestId: string;
139
+ requestVersion: number;
140
+ proposedParametersHash: string;
141
+ choice: "approve" | "reject";
142
+ community: string;
143
+ channelId: string;
144
+ cardEventId: string;
145
+ /** Source-event proof: the signed reaction the channel route verified. */
146
+ reactionEventId: string;
147
+ /** Candidate identity — the governed action resolves the binding (D7). */
148
+ attestedIdentity: {
149
+ namespace: "nostr";
150
+ externalId: string;
151
+ signatureRef: string;
152
+ };
153
+ }
154
+ export interface BuzzEditProposal {
155
+ approvalRequestId: string;
156
+ requestVersion: number;
157
+ community: string;
158
+ channelId: string;
159
+ cardEventId: string;
160
+ proposalEventId: string;
161
+ /** Free-form text — a PROPOSAL only; never an approval (D14). */
162
+ text: string;
163
+ attestedIdentity: {
164
+ namespace: "nostr";
165
+ externalId: string;
166
+ signatureRef: string;
167
+ };
168
+ }
169
+ export type BuzzDecisionResolution = {
170
+ kind: "decision-candidate";
171
+ candidate: BuzzDecisionCandidate;
172
+ } | {
173
+ kind: "edit-proposal";
174
+ proposal: BuzzEditProposal;
175
+ } | {
176
+ kind: "unmapped-emoji";
177
+ emoji: string;
178
+ cardEventId: string;
179
+ approvalRequestId: string;
180
+ pubkey: string;
181
+ } | {
182
+ kind: "not-a-decision";
183
+ };
184
+ export interface BuzzDecisionBridgeOptions {
185
+ /** Server-owned community — must equal the channel's (plan D7). */
186
+ community: string;
187
+ receiptStore: BuzzCardReceiptStore;
188
+ /** Override the fixed emoji table (still a fixed table — never a model). */
189
+ emojiMap?: Readonly<Record<string, "approve" | "reject">>;
190
+ }
191
+ /**
192
+ * The deterministic decision bridge (plan §4 steps 4–5). Pure lookup + fixed
193
+ * tables; no clock, no model, no authorization. Returns what the event *is* —
194
+ * the vertical's governed action decides what happens.
195
+ */
196
+ export declare function createBuzzDecisionBridge(options: BuzzDecisionBridgeOptions): {
197
+ resolveReaction: (reaction: BuzzReactionInput) => Promise<BuzzDecisionResolution>;
198
+ resolveReply: (message: BuzzMessageInput) => Promise<BuzzDecisionResolution>;
199
+ };
200
+ //# sourceMappingURL=buzz-decisions.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buzz-decisions.d.ts","sourceRoot":"","sources":["../src/buzz-decisions.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAA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,gBAAgB,EAAE;QAAE,SAAS,EAAE,OAAO,CAAC;QAAC,UAAU,EAAE,MAAM,CAAC;QAAC,YAAY,EAAE,MAAM,CAAA;KAAE,CAAC;CACpF;AAED,MAAM,MAAM,sBAAsB,GAC9B;IAAE,IAAI,EAAE,oBAAoB,CAAC;IAAC,SAAS,EAAE,qBAAqB,CAAA;CAAE,GAChE;IAAE,IAAI,EAAE,eAAe,CAAC;IAAC,QAAQ,EAAE,gBAAgB,CAAA;CAAE,GACrD;IACE,IAAI,EAAE,gBAAgB,CAAC;IACvB,KAAK,EAAE,MAAM,CAAC;IACd,WAAW,EAAE,MAAM,CAAC;IACpB,iBAAiB,EAAE,MAAM,CAAC;IAC1B,MAAM,EAAE,MAAM,CAAC;CAChB,GACD;IAAE,IAAI,EAAE,gBAAgB,CAAA;CAAE,CAAC;AAE/B,MAAM,WAAW,yBAAyB;IACxC,mEAAmE;IACnE,SAAS,EAAE,MAAM,CAAC;IAClB,YAAY,EAAE,oBAAoB,CAAC;IACnC,4EAA4E;IAC5E,QAAQ,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,SAAS,GAAG,QAAQ,CAAC,CAAC,CAAC;CAC3D;AAED;;;;GAIG;AACH,wBAAgB,wBAAwB,CAAC,OAAO,EAAE,yBAAyB;gCAGhC,iBAAiB,KAAG,OAAO,CAAC,sBAAsB,CAAC;4BAsCvD,gBAAgB,KAAG,OAAO,CAAC,sBAAsB,CAAC;EAmCxF"}
@@ -0,0 +1,300 @@
1
+ import { defineTool } from "@fabric-harness/sdk/channel";
2
+ import { BUZZ_KINDS } from "./buzz-kinds.js";
3
+ import { createSignedBuzzEvent, queryBuzzEvents, submitSignedBuzzEvent } from "./buzz.js";
4
+ const OPTION_LEGEND = {
5
+ approve: "approve 👍",
6
+ reject: "reject 👎",
7
+ "approve-with-edits": "reply with edits (proposal — requires confirmation)",
8
+ };
9
+ /**
10
+ * Render the canonical decision card. Pure and deterministic: identical input
11
+ * yields byte-identical content and tags. The card's human-readable content is
12
+ * informational; all authority derives from the stored receipt, never from
13
+ * parsing this text back.
14
+ */
15
+ export function renderBuzzDecisionCard(input) {
16
+ // Threat model T13: the governed-surface link is the only URL a card may
17
+ // carry. Canonical fields that smuggle links (a compromised upstream, a
18
+ // template injection) are refused outright rather than rendered.
19
+ for (const [field, value] of [
20
+ ["title", input.title],
21
+ ["summary", input.summary],
22
+ ["proposedActionId", input.proposedActionId],
23
+ ]) {
24
+ if (/[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
25
+ throw new Error(`decision card ${field} must not contain URLs; use detailsUrl`);
26
+ }
27
+ }
28
+ const legend = input.options.map((option) => OPTION_LEGEND[option]).join(" · ");
29
+ const content = [
30
+ `**${input.title}**`,
31
+ "",
32
+ input.summary,
33
+ "",
34
+ `action: \`${input.proposedActionId}\``,
35
+ `parameters: \`${input.proposedParametersHash}\``,
36
+ `expires: ${input.expiresAt}`,
37
+ ...(input.detailsUrl ? ["", `details: ${input.detailsUrl}`] : []),
38
+ "",
39
+ `_${legend}_`,
40
+ ].join("\n");
41
+ const tags = [
42
+ ["decision", input.approvalRequestId],
43
+ ["decision-version", String(input.requestVersion)],
44
+ ["decision-params", input.proposedParametersHash],
45
+ ["decision-expires", input.expiresAt],
46
+ ];
47
+ return { content, tags };
48
+ }
49
+ /** Stable logical identity for one request version on one Buzz surface. */
50
+ export function buzzDecisionCardDeliveryKey(community, channelId, approvalRequestId, requestVersion) {
51
+ return JSON.stringify(["buzz-card", 1, community, channelId, approvalRequestId, requestVersion]);
52
+ }
53
+ /** Test/development receipt store. Not durable — never use in production. */
54
+ export function inMemoryBuzzCardReceiptStore() {
55
+ const records = new Map();
56
+ return {
57
+ async prepareDelivery(delivery) {
58
+ const existing = records.get(delivery.deliveryKey);
59
+ if (existing)
60
+ return structuredClone(existing);
61
+ records.set(delivery.deliveryKey, structuredClone(delivery));
62
+ return structuredClone(delivery);
63
+ },
64
+ async markDeliveryPublished(deliveryKey, publishedAt) {
65
+ const delivery = records.get(deliveryKey);
66
+ if (!delivery)
67
+ throw new Error(`Unknown Buzz decision-card delivery: ${deliveryKey}`);
68
+ delivery.status = "published";
69
+ delivery.publishedAt ??= publishedAt;
70
+ },
71
+ async findByCardEvent(community, channelId, cardEventId) {
72
+ const delivery = [...records.values()].find(({ receipt }) => receipt.community === community &&
73
+ receipt.channelId === channelId &&
74
+ receipt.cardEventId === cardEventId);
75
+ return delivery ? structuredClone(delivery.receipt) : undefined;
76
+ },
77
+ all() {
78
+ return [...records.values()].map(({ receipt }) => structuredClone(receipt));
79
+ },
80
+ deliveries() {
81
+ return [...records.values()].map((delivery) => structuredClone(delivery));
82
+ },
83
+ };
84
+ }
85
+ /**
86
+ * Outbound tool: durably prepare the exact signed event + receipt, submit it,
87
+ * reconcile an ambiguous response by exact event id, then checkpoint
88
+ * publication. Returns the receipt. Posting a card grants nothing by itself.
89
+ */
90
+ export function postBuzzDecisionCard(ref, config) {
91
+ return defineTool({
92
+ name: "post_buzz_decision_card",
93
+ description: "Post the canonical decision card for an ApprovalRequest into the Buzz channel and store its card receipt.",
94
+ inputSchema: {
95
+ type: "object",
96
+ additionalProperties: false,
97
+ properties: {
98
+ approvalRequestId: { type: "string", minLength: 1 },
99
+ requestVersion: { type: "integer", minimum: 0 },
100
+ proposedActionId: { type: "string", minLength: 1 },
101
+ proposedParametersHash: { type: "string", pattern: "^sha256:[a-f0-9]{64}$" },
102
+ title: { type: "string", minLength: 1 },
103
+ summary: { type: "string", minLength: 1 },
104
+ options: {
105
+ type: "array",
106
+ minItems: 1,
107
+ items: { enum: ["approve", "reject", "approve-with-edits"] },
108
+ },
109
+ expiresAt: { type: "string", minLength: 1 },
110
+ detailsUrl: { type: "string", minLength: 1 },
111
+ },
112
+ required: [
113
+ "approvalRequestId",
114
+ "requestVersion",
115
+ "proposedActionId",
116
+ "proposedParametersHash",
117
+ "title",
118
+ "summary",
119
+ "options",
120
+ "expiresAt",
121
+ ],
122
+ },
123
+ metadata: { effect: "write", provider: "buzz", channel: "buzz" },
124
+ execute: async (input) => {
125
+ const rendered = renderBuzzDecisionCard(input);
126
+ const event = createSignedBuzzEvent(config, {
127
+ kind: BUZZ_KINDS.STREAM_MESSAGE,
128
+ content: rendered.content,
129
+ tags: [["h", ref.channelId], ...rendered.tags],
130
+ });
131
+ const preparedAt = new Date(event.created_at * 1_000).toISOString();
132
+ const receipt = {
133
+ approvalRequestId: input.approvalRequestId,
134
+ requestVersion: input.requestVersion,
135
+ proposedParametersHash: input.proposedParametersHash,
136
+ relayUrl: config.relayUrl,
137
+ community: ref.community,
138
+ channelId: ref.channelId,
139
+ cardEventId: event.id,
140
+ options: input.options,
141
+ expiresAt: input.expiresAt,
142
+ postedAt: preparedAt,
143
+ };
144
+ const deliveryKey = buzzDecisionCardDeliveryKey(ref.community, ref.channelId, input.approvalRequestId, input.requestVersion);
145
+ const delivery = await config.deliveryStore.prepareDelivery({
146
+ deliveryKey,
147
+ event,
148
+ receipt,
149
+ status: "prepared",
150
+ preparedAt,
151
+ });
152
+ assertPreparedDelivery(delivery, {
153
+ deliveryKey,
154
+ input,
155
+ ref,
156
+ rendered,
157
+ signerPubkey: event.pubkey,
158
+ relayUrl: config.relayUrl,
159
+ });
160
+ if (delivery.status !== "published") {
161
+ let present = false;
162
+ let resultMessage;
163
+ try {
164
+ const result = await submitSignedBuzzEvent(config, delivery.event);
165
+ resultMessage = result.message;
166
+ if (result.event_id && result.event_id !== delivery.event.id) {
167
+ throw new Error(`relay returned mismatched event id ${result.event_id}`);
168
+ }
169
+ present = result.accepted !== false;
170
+ }
171
+ catch (error) {
172
+ if (config.signal?.aborted || (error instanceof Error && error.name === "AbortError")) {
173
+ throw error;
174
+ }
175
+ resultMessage = error instanceof Error ? error.message : String(error);
176
+ }
177
+ if (!present) {
178
+ // Submission may have committed before a timeout/disconnect. Query by
179
+ // the immutable event id instead of minting a second card.
180
+ const matches = await queryBuzzEvents(config, [
181
+ { ids: [delivery.event.id], kinds: [delivery.event.kind], limit: 1 },
182
+ ]).catch(() => []);
183
+ present = matches.some((candidate) => candidate.id === delivery.event.id);
184
+ }
185
+ if (!present)
186
+ throw new Error(`decision card post not confirmed: ${resultMessage ?? "relay rejected event"}`);
187
+ await config.deliveryStore.markDeliveryPublished(delivery.deliveryKey, new Date((config.now ?? (() => Date.now()))()).toISOString());
188
+ }
189
+ return delivery.receipt;
190
+ },
191
+ });
192
+ }
193
+ function assertPreparedDelivery(delivery, expected) {
194
+ const receipt = delivery.receipt;
195
+ const expectedTags = [["h", expected.ref.channelId], ...expected.rendered.tags];
196
+ if (delivery.deliveryKey !== expected.deliveryKey ||
197
+ delivery.event.id !== receipt.cardEventId ||
198
+ delivery.event.pubkey !== expected.signerPubkey ||
199
+ delivery.event.kind !== BUZZ_KINDS.STREAM_MESSAGE ||
200
+ delivery.event.content !== expected.rendered.content ||
201
+ JSON.stringify(delivery.event.tags) !== JSON.stringify(expectedTags) ||
202
+ receipt.approvalRequestId !== expected.input.approvalRequestId ||
203
+ receipt.requestVersion !== expected.input.requestVersion ||
204
+ receipt.proposedParametersHash !== expected.input.proposedParametersHash ||
205
+ receipt.relayUrl !== expected.relayUrl ||
206
+ receipt.community !== expected.ref.community ||
207
+ receipt.channelId !== expected.ref.channelId ||
208
+ JSON.stringify(receipt.options) !== JSON.stringify(expected.input.options) ||
209
+ receipt.expiresAt !== expected.input.expiresAt) {
210
+ throw new Error(`Buzz decision-card delivery ${expected.deliveryKey} conflicts with its immutable request.`);
211
+ }
212
+ }
213
+ // ── Deterministic bridge ──
214
+ /**
215
+ * Fixed reaction→choice table (D14). NIP-25 `+`/`-` are included alongside
216
+ * the emoji the card legend shows. Anything else on a card is `unmapped` —
217
+ * surfaced for audit, never guessed.
218
+ */
219
+ export const BUZZ_DECISION_EMOJI = Object.freeze({
220
+ "👍": "approve",
221
+ "✅": "approve",
222
+ "+": "approve",
223
+ "👎": "reject",
224
+ "❌": "reject",
225
+ "-": "reject",
226
+ });
227
+ /**
228
+ * The deterministic decision bridge (plan §4 steps 4–5). Pure lookup + fixed
229
+ * tables; no clock, no model, no authorization. Returns what the event *is* —
230
+ * the vertical's governed action decides what happens.
231
+ */
232
+ export function createBuzzDecisionBridge(options) {
233
+ const emojiMap = options.emojiMap ?? BUZZ_DECISION_EMOJI;
234
+ async function resolveReaction(reaction) {
235
+ if (!reaction.targetEventId)
236
+ return { kind: "not-a-decision" };
237
+ const receipt = await options.receiptStore.findByCardEvent(options.community, reaction.channelId, reaction.targetEventId);
238
+ if (!receipt)
239
+ return { kind: "not-a-decision" };
240
+ const choice = emojiMap[reaction.emoji.trim()];
241
+ if (!choice) {
242
+ return {
243
+ kind: "unmapped-emoji",
244
+ emoji: reaction.emoji,
245
+ cardEventId: receipt.cardEventId,
246
+ approvalRequestId: receipt.approvalRequestId,
247
+ pubkey: reaction.pubkey,
248
+ };
249
+ }
250
+ return {
251
+ kind: "decision-candidate",
252
+ candidate: {
253
+ approvalRequestId: receipt.approvalRequestId,
254
+ requestVersion: receipt.requestVersion,
255
+ proposedParametersHash: receipt.proposedParametersHash,
256
+ choice,
257
+ community: receipt.community,
258
+ channelId: receipt.channelId,
259
+ cardEventId: receipt.cardEventId,
260
+ reactionEventId: reaction.eventId,
261
+ attestedIdentity: {
262
+ namespace: "nostr",
263
+ externalId: reaction.pubkey,
264
+ signatureRef: reaction.eventId,
265
+ },
266
+ },
267
+ };
268
+ }
269
+ async function resolveReply(message) {
270
+ // A reply targets a card when any `e` tag references the card event.
271
+ const referenced = (message.tags ?? [])
272
+ .filter((tag) => tag[0] === "e" && typeof tag[1] === "string")
273
+ .map((tag) => tag[1]);
274
+ for (const eventId of referenced) {
275
+ const receipt = await options.receiptStore.findByCardEvent(options.community, message.channelId, eventId);
276
+ if (receipt) {
277
+ return {
278
+ kind: "edit-proposal",
279
+ proposal: {
280
+ approvalRequestId: receipt.approvalRequestId,
281
+ requestVersion: receipt.requestVersion,
282
+ community: receipt.community,
283
+ channelId: receipt.channelId,
284
+ cardEventId: receipt.cardEventId,
285
+ proposalEventId: message.eventId,
286
+ text: message.text,
287
+ attestedIdentity: {
288
+ namespace: "nostr",
289
+ externalId: message.pubkey,
290
+ signatureRef: message.eventId,
291
+ },
292
+ },
293
+ };
294
+ }
295
+ }
296
+ return { kind: "not-a-decision" };
297
+ }
298
+ return { resolveReaction, resolveReply };
299
+ }
300
+ //# sourceMappingURL=buzz-decisions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"buzz-decisions.js","sourceRoot":"","sources":["../src/buzz-decisions.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,6BAA6B,CAAC;AACzD,OAAO,EAAE,UAAU,EAAE,MAAM,iBAAiB,CAAC;AAC7C,OAAO,EAAE,qBAAqB,EAAE,eAAe,EAAE,qBAAqB,EAAE,MAAM,WAAW,CAAC;AA4C1F,MAAM,aAAa,GAA6D;IAC9E,OAAO,EAAE,YAAY;IACrB,MAAM,EAAE,WAAW;IACnB,oBAAoB,EAAE,qDAAqD;CAC5E,CAAC;AAEF;;;;;GAKG;AACH,MAAM,UAAU,sBAAsB,CAAC,KAA4B;IAIjE,yEAAyE;IACzE,wEAAwE;IACxE,iEAAiE;IACjE,KAAK,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,IAAI;QAC3B,CAAC,OAAO,EAAE,KAAK,CAAC,KAAK,CAAC;QACtB,CAAC,SAAS,EAAE,KAAK,CAAC,OAAO,CAAC;QAC1B,CAAC,kBAAkB,EAAE,KAAK,CAAC,gBAAgB,CAAC;KACpC,EAAE,CAAC;QACX,IAAI,yBAAyB,CAAC,IAAI,CAAC,KAAK,CAAC,EAAE,CAAC;YAC1C,MAAM,IAAI,KAAK,CAAC,iBAAiB,KAAK,wCAAwC,CAAC,CAAC;QAClF,CAAC;IACH,CAAC;IACD,MAAM,MAAM,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,aAAa,CAAC,MAAM,CAAC,CAAC,CAAC,IAAI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