@toon-protocol/rig 4.0.0 → 4.1.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/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
- import { d as GitObjectType, P as Publisher, F as FeeRates, c as PublishReceipt, b as UnsignedEvent } from './publisher-CcL96ugq.js';
2
- export { C as COMMENT_KIND, e as GitObject, G as GitObjectUpload, M as MAINTAINERS_TAG, f as MAX_OBJECT_SIZE, R as REPOSITORY_STATE_KIND, g as StatusKind, U as UploadReceipt, h as authorizedStatusAuthors, i as buildComment, j as buildIssue, k as buildPatch, l as buildRepoAnnouncement, m as buildRepoRefs, n as buildStatus, o as createGitBlob, p as createGitCommit, q as createGitTag, r as createGitTree, s as hashGitObject, t as parseMaintainers } from './publisher-CcL96ugq.js';
1
+ import { d as GitObjectType, e as PayoutPointer, P as Publisher, F as FeeRates, c as PublishReceipt, b as UnsignedEvent } from './publisher-DMJ06cuL.js';
2
+ export { C as COMMENT_KIND, f as GitObject, G as GitObjectUpload, M as MAINTAINERS_TAG, g as MAX_OBJECT_SIZE, h as PAYOUT_TAG, i as PayoutChain, R as REPOSITORY_STATE_KIND, j as StatusKind, U as UploadReceipt, k as authorizedStatusAuthors, l as buildComment, m as buildIssue, n as buildPatch, o as buildRepoAnnouncement, p as buildRepoRefs, q as buildStatus, r as createGitBlob, s as createGitCommit, t as createGitTag, u as createGitTree, v as hashGitObject, w as isValidEvmPayoutAddress, x as parseMaintainers, y as parsePayout } from './publisher-DMJ06cuL.js';
3
3
  import '@toon-protocol/core/nip34';
4
4
 
5
5
  /**
@@ -210,6 +210,7 @@ declare class GitRepoReader {
210
210
  * double-JSON-encoded string (devnet relay quirk: a JSON string containing
211
211
  * the event JSON), or as a TOON-encoded string. All three are tolerated.
212
212
  */
213
+
213
214
  /** A signed Nostr event as seen on a relay (read side). */
214
215
  interface NostrEvent {
215
216
  id: string;
@@ -292,6 +293,12 @@ interface RemoteState {
292
293
  * when unannounced or owner-only.
293
294
  */
294
295
  maintainers: string[];
296
+ /**
297
+ * Declared payout pointer (rig#92) from the announcement `payout` tag, or
298
+ * `null` when unannounced or no pointer is declared — no pointer means the
299
+ * serving node keeps 100% of repo-scoped write fees (toon-meta#391).
300
+ */
301
+ payout: PayoutPointer | null;
295
302
  /**
296
303
  * Resolve SHAs to Arweave txIds: served from the `arweave` tag map when
297
304
  * present, otherwise via the GraphQL Git-SHA resolver. SHAs that resolve
@@ -1408,4 +1415,4 @@ interface FactoryJobExecution {
1408
1415
  */
1409
1416
  declare function executeFactoryJob(options: ExecuteFactoryJobOptions): Promise<FactoryJobExecution>;
1410
1417
 
1411
- export { type BuildIncrementOfferOptions, type BuildNarrationOptions, type BuildResultEventOptions, type ClosureResult, type CollectRepoObjectsOptions, type CollectRepoObjectsResult, DEFAULT_CONCURRENCY, type DownloadOptions, type DownloadResult, type EncryptedArtifact, type EncryptedArtifactRef, type ExecuteFactoryJobOptions, type ExecutePushOptions, FACTORY_JOB_FEEDBACK_KIND, FACTORY_JOB_REQUEST_KIND, FACTORY_JOB_RESULT_KIND, type FactoryJobExecution, type FactoryJobHooks, type FactoryJobOutcome, type FactoryJobRequest, type FactoryJobWork, type FactoryMilestone, type FactoryTicket, FeeRates, type FetchLike, type FetchRemoteStateOptions, type FetchedObject, type GateCheck, type GateResult, type GatewayFetchOptions, type GitCommentRequest, GitError, type GitErrorEnvelope, type GitEstimateRequest, type GitEstimateResponse, type GitEventResponse, type GitFeeEstimate, type GitIssueRequest, GitObjectType, type GitPatchRequest, type GitPlannedObject, type GitPublishReceipt, type GitPushRequest, type GitPushResponse, type GitRef, type GitRefUpdate, type GitRepoAddr, GitRepoReader, type GitStatusRequest, type GitStatusValue, type GitUploadStep, type IncrementSpec, type JobDeliveryPort, type MissingObject, NonFastForwardError, type NostrEvent, type NostrFilter, ObjectIntegrityError, type ObjectStat, type ObjectWithPath, ObjectWriteMismatchError, type OfferedIncrement, type OversizeObject, OversizeObjectsError, type PlanPushOptions, type PlannedObject, PublishReceipt, Publisher, type PushFeeEstimate, type PushPlan, type PushResult, type ReadGitObject, type ReadObjectsResult, type RefUpdate, type RefUpdateKind, type RejectedRefUpdate, type RelayEvent, type RemoteState, type RepoRefs, type StatObjectsResult, UnsignedEvent, type UploadStepResult, type WebSocketFactory, type WebSocketLike, buildIncrementOfferEvent, buildNarrationEvent, buildQuoteEvent, buildResultEvent, collectRepoObjects, downloadGitObjects, executeFactoryJob, executePush, fetchRemoteState, fetchTxBytes, gatePassed, hexToNpub, isSafeRefname, missingObjectsMessage, npubToHex, ownerToHex, parseFactoryJobRequest, planFactoryJob, planPush, queryRelay, referencedShas, serializeEventReceipt, serializeFeeEstimate, serializePushPlan, serializePushResult, setHeadSymref, updateRef, verifyObjectBody, walkClosure, writeGitObject, writeGitObjects };
1418
+ export { type BuildIncrementOfferOptions, type BuildNarrationOptions, type BuildResultEventOptions, type ClosureResult, type CollectRepoObjectsOptions, type CollectRepoObjectsResult, DEFAULT_CONCURRENCY, type DownloadOptions, type DownloadResult, type EncryptedArtifact, type EncryptedArtifactRef, type ExecuteFactoryJobOptions, type ExecutePushOptions, FACTORY_JOB_FEEDBACK_KIND, FACTORY_JOB_REQUEST_KIND, FACTORY_JOB_RESULT_KIND, type FactoryJobExecution, type FactoryJobHooks, type FactoryJobOutcome, type FactoryJobRequest, type FactoryJobWork, type FactoryMilestone, type FactoryTicket, FeeRates, type FetchLike, type FetchRemoteStateOptions, type FetchedObject, type GateCheck, type GateResult, type GatewayFetchOptions, type GitCommentRequest, GitError, type GitErrorEnvelope, type GitEstimateRequest, type GitEstimateResponse, type GitEventResponse, type GitFeeEstimate, type GitIssueRequest, GitObjectType, type GitPatchRequest, type GitPlannedObject, type GitPublishReceipt, type GitPushRequest, type GitPushResponse, type GitRef, type GitRefUpdate, type GitRepoAddr, GitRepoReader, type GitStatusRequest, type GitStatusValue, type GitUploadStep, type IncrementSpec, type JobDeliveryPort, type MissingObject, NonFastForwardError, type NostrEvent, type NostrFilter, ObjectIntegrityError, type ObjectStat, type ObjectWithPath, ObjectWriteMismatchError, type OfferedIncrement, type OversizeObject, OversizeObjectsError, PayoutPointer, type PlanPushOptions, type PlannedObject, PublishReceipt, Publisher, type PushFeeEstimate, type PushPlan, type PushResult, type ReadGitObject, type ReadObjectsResult, type RefUpdate, type RefUpdateKind, type RejectedRefUpdate, type RelayEvent, type RemoteState, type RepoRefs, type StatObjectsResult, UnsignedEvent, type UploadStepResult, type WebSocketFactory, type WebSocketLike, buildIncrementOfferEvent, buildNarrationEvent, buildQuoteEvent, buildResultEvent, collectRepoObjects, downloadGitObjects, executeFactoryJob, executePush, fetchRemoteState, fetchTxBytes, gatePassed, hexToNpub, isSafeRefname, missingObjectsMessage, npubToHex, ownerToHex, parseFactoryJobRequest, planFactoryJob, planPush, queryRelay, referencedShas, serializeEventReceipt, serializeFeeEstimate, serializePushPlan, serializePushResult, setHeadSymref, updateRef, verifyObjectBody, walkClosure, writeGitObject, writeGitObjects };
package/dist/index.js CHANGED
@@ -27,10 +27,11 @@ import {
27
27
  walkClosure,
28
28
  writeGitObject,
29
29
  writeGitObjects
30
- } from "./chunk-ZZBA5VVL.js";
30
+ } from "./chunk-7VCVR4GK.js";
31
31
  import {
32
32
  COMMENT_KIND,
33
33
  MAINTAINERS_TAG,
34
+ PAYOUT_TAG,
34
35
  REPOSITORY_STATE_KIND,
35
36
  authorizedStatusAuthors,
36
37
  buildComment,
@@ -40,9 +41,11 @@ import {
40
41
  buildRepoRefs,
41
42
  buildStatus,
42
43
  fetchRemoteState,
44
+ isValidEvmPayoutAddress,
43
45
  parseMaintainers,
46
+ parsePayout,
44
47
  queryRelay
45
- } from "./chunk-2KJJ7LSO.js";
48
+ } from "./chunk-NCEMQUPA.js";
46
49
  import {
47
50
  MAX_OBJECT_SIZE,
48
51
  createGitBlob,
@@ -339,6 +342,7 @@ export {
339
342
  ObjectIntegrityError,
340
343
  ObjectWriteMismatchError,
341
344
  OversizeObjectsError,
345
+ PAYOUT_TAG,
342
346
  REPOSITORY_STATE_KIND,
343
347
  authorizedStatusAuthors,
344
348
  buildComment,
@@ -365,11 +369,13 @@ export {
365
369
  hashGitObject,
366
370
  hexToNpub,
367
371
  isSafeRefname,
372
+ isValidEvmPayoutAddress,
368
373
  missingObjectsMessage,
369
374
  npubToHex,
370
375
  ownerToHex,
371
376
  parseFactoryJobRequest,
372
377
  parseMaintainers,
378
+ parsePayout,
373
379
  planFactoryJob,
374
380
  planPush,
375
381
  queryRelay,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/factory-job-gate.ts","../src/factory-job-events.ts","../src/factory-job-plan.ts","../src/factory-job-execute.ts"],"sourcesContent":["/**\n * Factory job protocol — reproducible gate result per increment (#53).\n *\n * Decision 5 of toon-meta#262 splits trust into three layers: delivery (the\n * hashlock), the objective floor (this — \"did this increment pass the\n * repo's own gate?\"), and quality (reputation, out of scope here). Per\n * `FACTORY.md`, the pinned pipeline's gate is lint/typecheck/test/build run\n * before a PR is opened; this module is the pure, network-free shape for\n * recording exactly what ran, not a summary verdict.\n *\n * This proves conformance, not fitness for purpose — a gate-passing\n * increment can still completely miss the brief. Reputation is what\n * distinguishes those, never this.\n */\n\n/** One command the gate ran, and whether it passed. */\nexport interface GateCheck {\n /** e.g. \"lint\", \"typecheck\", \"test\", \"build\" — whatever actually ran,\n * never a canonical list (gates differ per repo and drift over time). */\n name: string;\n /** The literal command, e.g. \"eslint .\", so a buyer can reproduce it verbatim. */\n command: string;\n pass: boolean;\n}\n\n/**\n * A reproducible gate result: enough for a buyer to re-run the gate\n * themselves and get the same answer. Omitting the commit or the command\n * set turns this from a reproducible result into a provider's unverifiable\n * claim of having done well — both are required, not advisory.\n */\nexport interface GateResult {\n /** The commit this gate ran against. */\n commit: string;\n /** Toolchain versions relevant to reproducing the result, e.g. `{ node: \"20.11.0\", pnpm: \"9.1.0\" }`. */\n toolchain: Record<string, string>;\n checks: GateCheck[];\n}\n\n/** Overall pass/fail — every recorded check passed. A failing gate is not a protocol violation (it is still published, just visibly failing) — this is only the aggregate the `gate` tag and reputation's gate-pass rate read. */\nexport function gatePassed(gate: GateResult): boolean {\n return gate.checks.every((check) => check.pass);\n}\n","/**\n * Factory job protocol — pure NIP-90 event builders/parser (#52).\n *\n * Wire format per toon-meta's `docs/factory-job-protocol.md`\n * (toon-meta#263), fixed 2026-08-03: kind:5097 job request, kind:6097 job\n * result, kind:7000 job feedback (quote / increment offer / narration,\n * disambiguated by the `status` tag). Mirrors nip34-events.ts: every builder\n * returns an UnsignedEvent — the caller signs and publishes (e.g. through a\n * Publisher, publisher.ts) elsewhere. No crypto, no network, no payment.\n */\n\nimport type { UnsignedEvent } from './nip34-events.js';\nimport type { IncrementSpec } from './factory-job-plan.js';\nimport { gatePassed, type GateResult } from './factory-job-gate.js';\n\n// ---------------------------------------------------------------------------\n// Kinds\n// ---------------------------------------------------------------------------\n\n/** Factory job request (the brief). */\nexport const FACTORY_JOB_REQUEST_KIND = 5097;\n/** Factory job result — terminal state (completed/abandoned-*). */\nexport const FACTORY_JOB_RESULT_KIND = 6097;\n/** Factory job feedback — quote, increment offer, or free narration. */\nexport const FACTORY_JOB_FEEDBACK_KIND = 7000;\n\n/** The three §5.2 terminal outcomes — decision 8 has no fourth. */\nexport type FactoryJobOutcome =\n | 'completed'\n | 'abandoned-provider'\n | 'abandoned-buyer';\n\n// ---------------------------------------------------------------------------\n// kind:5097 — job request\n// ---------------------------------------------------------------------------\n\n/** A parsed kind:5097 job request (§2). */\nexport interface FactoryJobRequest {\n /** The requesting kind:5097 event's id. */\n requestEventId: string;\n /** The requesting kind:5097 event's pubkey (who to reply/bill). */\n buyerPubkey: string;\n /** The brief — free text or a chained milestone reference (§2.3). */\n brief: string;\n /** Maximum the buyer will pay across the whole job (micro-USDC, §2.1). */\n bidMicroUsdc: string;\n /** `param repo` — target repo, e.g. `toon-protocol/buzz`. */\n repo?: string;\n /** `param target` — the ticket/issue this job resolves. */\n target?: string;\n /** `param constraints` — gate requirements / scope limits. */\n constraints?: string;\n /** `output` — expected deliverable MIME type. */\n outputMime?: string;\n}\n\n/** Minimal shape of a relay event this module reads/builds — no signing. */\nexport interface RelayEvent {\n id: string;\n pubkey: string;\n tags: string[][];\n content: string;\n}\n\n/**\n * Parse a kind:5097 job request event's tags into a {@link FactoryJobRequest}.\n * Throws if the required `i` (brief) or `bid` tag is missing — both are\n * REQUIRED per §2.1.\n */\nexport function parseFactoryJobRequest(event: RelayEvent): FactoryJobRequest {\n const briefTag = event.tags.find((t) => t[0] === 'i' && t[2] === 'text');\n if (!briefTag?.[1]) {\n throw new Error(\n `kind:${FACTORY_JOB_REQUEST_KIND} event ${event.id} is missing its required brief (\"i\", \"<brief>\", \"text\") tag`\n );\n }\n const bidTag = event.tags.find((t) => t[0] === 'bid');\n if (!bidTag?.[1]) {\n throw new Error(\n `kind:${FACTORY_JOB_REQUEST_KIND} event ${event.id} is missing its required \"bid\" tag`\n );\n }\n\n const params = event.tags.filter((t) => t[0] === 'param');\n const paramValue = (name: string): string | undefined =>\n params.find((t) => t[1] === name)?.[2];\n\n const repo = paramValue('repo');\n const target = paramValue('target');\n const constraints = paramValue('constraints');\n const outputMime = event.tags.find((t) => t[0] === 'output')?.[1];\n\n return {\n requestEventId: event.id,\n buyerPubkey: event.pubkey,\n brief: briefTag[1],\n bidMicroUsdc: bidTag[1],\n ...(repo !== undefined ? { repo } : {}),\n ...(target !== undefined ? { target } : {}),\n ...(constraints !== undefined ? { constraints } : {}),\n ...(outputMime !== undefined ? { outputMime } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:7000 status:\"quote\" — the RFQ reply (§3)\n// ---------------------------------------------------------------------------\n\n/**\n * Build the `kind:7000 status:\"quote\"` reply: the proposed increment\n * schedule, committing nothing (§3.3 — there is no accept message; payment\n * of increment 1 is acceptance).\n */\nexport function buildQuoteEvent(\n job: FactoryJobRequest,\n schedule: IncrementSpec[]\n): UnsignedEvent {\n return {\n kind: FACTORY_JOB_FEEDBACK_KIND,\n content: JSON.stringify({\n increments: schedule.map((s) => ({\n n: s.n,\n of: s.of,\n milestone: s.milestone,\n priceUsdc: s.priceUsdc,\n })),\n }),\n tags: [\n ['e', job.requestEventId, '', 'root'],\n ['p', job.buyerPubkey],\n ['status', 'quote'],\n ],\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:7000 status:\"partial\" — the increment offer (§4)\n// ---------------------------------------------------------------------------\n\n/** Where the encrypted increment artifact lives, and its hashlock condition. */\nexport interface EncryptedArtifactRef {\n /** Arweave tx id the ciphertext was uploaded to. */\n arweaveTxId: string;\n /** sha256 of the ciphertext, hex — lets the buyer detect a bad fetch. */\n ciphertextSha256: string;\n /** `sha256(key)` hex, where `key` decrypts the artifact (§4.2 — the join). */\n conditionHex: string;\n}\n\nexport interface BuildIncrementOfferOptions {\n job: FactoryJobRequest;\n /** The quote event's id for increment 1, else the previous offer's id. */\n parentEventId: string;\n increment: IncrementSpec;\n artifact: EncryptedArtifactRef;\n /**\n * The reproducible gate result for this increment's work (#53 — the\n * objective floor), when one ran. Omitted for milestones with nothing to\n * gate (e.g. `plan` — there is no code to lint against a brief).\n */\n gate?: GateResult;\n}\n\n/** A gate result missing its commit or check list cannot be reproduced by the buyer — reject it here rather than publish an unverifiable claim. */\nfunction assertReproducible(gate: GateResult): void {\n if (gate.checks.length === 0) {\n throw new Error(\n 'gate result must record at least one check for the offer to be reproducible'\n );\n }\n if (!gate.commit) {\n throw new Error(\n 'gate result must record the commit it ran against for the offer to be reproducible'\n );\n }\n}\n\n/**\n * Build the `kind:7000 status:\"partial\"` increment offer — published once\n * the provider has done that increment's work and uploaded the encrypted\n * artifact. This is the join between the relay plane and the connector\n * plane (§4.2): `condition` here MUST equal the paying PREPARE's\n * `executionCondition`, byte for byte.\n *\n * When `gate` is supplied, the offer also carries a `[\"gate\", \"pass\"|\"fail\"]`\n * tag (cheap to scan for a gate-pass rate, decision 8) and the full\n * reproducible result in `content` — visible to the buyer before they pay,\n * per the issue: a gate-failing increment is still offered, never hidden.\n */\nexport function buildIncrementOfferEvent(\n options: BuildIncrementOfferOptions\n): UnsignedEvent {\n const { job, parentEventId, increment, artifact, gate } = options;\n if (gate) assertReproducible(gate);\n\n const tags: string[][] = [\n ['e', job.requestEventId, '', 'root'],\n ['e', parentEventId, '', 'reply'],\n ['p', job.buyerPubkey],\n ['status', 'partial'],\n ['increment', String(increment.n), String(increment.of)],\n ['i', artifact.arweaveTxId, 'url'],\n ['i', artifact.ciphertextSha256, 'text', '', 'hash'],\n ['amount', increment.priceUsdc, 'usdc'],\n ['condition', artifact.conditionHex],\n ];\n if (gate) tags.push(['gate', gatePassed(gate) ? 'pass' : 'fail']);\n\n return {\n kind: FACTORY_JOB_FEEDBACK_KIND,\n content: gate ? JSON.stringify({ gate }) : '',\n tags,\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:7000 status:\"processing\" — free narration (§6)\n// ---------------------------------------------------------------------------\n\nexport interface BuildNarrationOptions {\n job: FactoryJobRequest;\n /** The prior event in the thread (quote, offer, or narration). */\n parentEventId: string;\n message: string;\n}\n\n/**\n * Build a free narration event — no artifact, no `amount`/`condition`, MUST\n * NOT be paid against (§6). This is what makes a provider look alive between\n * increments.\n */\nexport function buildNarrationEvent(\n options: BuildNarrationOptions\n): UnsignedEvent {\n const { job, parentEventId, message } = options;\n return {\n kind: FACTORY_JOB_FEEDBACK_KIND,\n content: message,\n tags: [\n ['e', job.requestEventId, '', 'root'],\n ['e', parentEventId, '', 'reply'],\n ['p', job.buyerPubkey],\n ['status', 'processing'],\n ],\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:6097 — job result (§5)\n// ---------------------------------------------------------------------------\n\nexport interface BuildResultEventOptions {\n job: FactoryJobRequest;\n /** The original kind:5097 request event, verbatim (the `request` tag). */\n requestEvent: RelayEvent;\n /** The last kind:7000 event in the thread (offer or narration). */\n lastEventId: string;\n outcome: FactoryJobOutcome;\n /** How far the job got — `n-reached == of` only when outcome is completed. */\n reachedIncrement: number;\n totalIncrements: number;\n /** Required (and only meaningful) when outcome is `\"completed\"` (§5.2). */\n finalArtifact?: { arweaveTxId: string };\n}\n\n/**\n * Build the terminal `kind:6097` job result. Reputation (decision 8) is\n * computed from exactly this event and nothing else.\n */\nexport function buildResultEvent(\n options: BuildResultEventOptions\n): UnsignedEvent {\n const {\n job,\n requestEvent,\n lastEventId,\n outcome,\n reachedIncrement,\n totalIncrements,\n finalArtifact,\n } = options;\n\n const tags: string[][] = [\n ['e', job.requestEventId, '', 'root'],\n ['e', lastEventId, '', 'reply'],\n ['p', job.buyerPubkey],\n ['request', JSON.stringify(requestEvent)],\n ['outcome', outcome],\n ['increment', String(reachedIncrement), String(totalIncrements)],\n ];\n if (outcome === 'completed' && finalArtifact) {\n tags.push(['i', finalArtifact.arweaveTxId, 'url']);\n }\n\n return {\n kind: FACTORY_JOB_RESULT_KIND,\n content: '',\n tags,\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n","/**\n * Factory job protocol — increment schedule planner (#52).\n *\n * `planFactoryJob` is the network-free half of the adapter (mirrors\n * `planPush`'s split from `executePush` in push.ts): given a job's `bid` and\n * the ticket list the factory's plan phase produced, it prices the\n * milestone boundaries decision 6 of toon-meta#262 fixed as increments —\n * plan → implement ×N tickets → review — and returns the schedule that\n * becomes the `kind:7000 status:\"quote\"` content (§3.2 of\n * `docs/factory-job-protocol.md`).\n *\n * Per the issue gotcha, `implement` must be many increments, not one: this\n * always emits one increment per ticket rather than a single lump-sum\n * implement increment, using the factory's existing parallel per-issue\n * fan-out (`.sandcastle/main.ts`'s Plan phase output — `{issues: [{id,\n * title, branch}]}`) as the boundary.\n */\n\n/** One ticket the factory's plan phase fanned the implement milestone into. */\nexport interface FactoryTicket {\n id: string;\n title: string;\n branch: string;\n}\n\nexport type FactoryMilestone = 'plan' | 'implement' | 'review';\n\n/** One priced increment in the schedule (§3.2's `increments[]` shape). */\nexport interface IncrementSpec {\n n: number;\n of: number;\n milestone: FactoryMilestone;\n /** Set only for `milestone: \"implement\"` increments. */\n ticket?: FactoryTicket;\n priceUsdc: string;\n}\n\n/** Plan milestone's share of the bid, in basis points. */\nconst PLAN_SHARE_BPS = 1000n; // 10%\n/** Review milestone's share of the bid, in basis points. */\nconst REVIEW_SHARE_BPS = 1000n; // 10%\nconst BPS_DENOM = 10000n;\n\n/**\n * Build the increment schedule for a job, given the tickets its plan phase\n * produced. Plan and review each get a fixed 10% of the bid; the remaining\n * 80% (\"implement\") splits evenly across tickets, with the integer-division\n * remainder distributed one micro-USDC at a time to the earliest tickets —\n * so `sum(priceUsdc) === bid` exactly (§3.2 only requires `<=`, but an exact\n * match avoids \"where did the leftover micro-USDC go\" questions).\n *\n * Per decision 7, this schedule is agreed before any paid work starts and is\n * never repriced — a job that runs larger than `tickets` implied is a\n * lesson, not a renegotiation.\n *\n * Throws if `tickets` is empty (a job with no implementation work has no\n * increments to schedule) or `bidMicroUsdc` is not a positive integer.\n */\nexport function planFactoryJob(\n bidMicroUsdc: string,\n tickets: FactoryTicket[]\n): IncrementSpec[] {\n if (tickets.length === 0) {\n throw new Error(\n 'planFactoryJob requires at least one implementation ticket from the plan phase'\n );\n }\n\n let bid: bigint;\n try {\n bid = BigInt(bidMicroUsdc);\n } catch {\n throw new Error(`bidMicroUsdc must be an integer string, got ${bidMicroUsdc}`);\n }\n if (bid <= 0n) {\n throw new Error(`bidMicroUsdc must be positive, got ${bidMicroUsdc}`);\n }\n\n const planPrice = (bid * PLAN_SHARE_BPS) / BPS_DENOM;\n const reviewPrice = (bid * REVIEW_SHARE_BPS) / BPS_DENOM;\n const implementTotal = bid - planPrice - reviewPrice;\n\n const ticketCount = BigInt(tickets.length);\n const base = implementTotal / ticketCount;\n const remainder = implementTotal % ticketCount;\n\n const total = tickets.length + 2;\n const schedule: IncrementSpec[] = [\n { n: 1, of: total, milestone: 'plan', priceUsdc: planPrice.toString() },\n ];\n\n tickets.forEach((ticket, i) => {\n const price = base + (BigInt(i) < remainder ? 1n : 0n);\n schedule.push({\n n: i + 2,\n of: total,\n milestone: 'implement',\n ticket,\n priceUsdc: price.toString(),\n });\n });\n\n schedule.push({\n n: total,\n of: total,\n milestone: 'review',\n priceUsdc: reviewPrice.toString(),\n });\n\n return schedule;\n}\n","/**\n * executeFactoryJob — the adapter's imperative shell (#52): runs the\n * factory's own milestones (`.sandcastle/main.ts`'s plan → per-ticket\n * implement+review → merge phases) through `hooks`, and turns each\n * milestone boundary into a paid increment via `publisher` (existing,\n * publisher.ts — upload + event publish) and `delivery` (new,\n * factory-job-delivery.ts — encrypt + payment wait).\n *\n * Mirrors `executePush`'s split from `planPush`: `planFactoryJob` is the\n * network-free planning half; this is the half that spends money.\n *\n * Decision 6 (toon-meta#262): work happens BEFORE the packet, so every\n * increment's artifact is produced and uploaded before that increment is\n * offered for payment. Decision 7: the schedule is fixed once the quote is\n * published — this never reprices mid-job. Per the issue: \"Stop on\n * non-payment. One unpaid increment and work halts\" — the symmetric\n * protection that neither side is ever exposed for more than one increment.\n */\n\nimport type { Publisher } from './publisher.js';\nimport type { JobDeliveryPort } from './factory-job-delivery.js';\nimport {\n buildIncrementOfferEvent,\n buildQuoteEvent,\n buildResultEvent,\n type FactoryJobOutcome,\n type FactoryJobRequest,\n type RelayEvent,\n} from './factory-job-events.js';\nimport type { GateResult } from './factory-job-gate.js';\nimport {\n planFactoryJob,\n type FactoryTicket,\n type IncrementSpec,\n} from './factory-job-plan.js';\n\n/** One milestone's deliverable, plus the gate result that ran against it, when one did. */\nexport interface FactoryJobWork {\n artifact: Uint8Array;\n /**\n * The reproducible gate result (#53) for this milestone's work, per\n * `FACTORY.md`'s pinned pipeline (lint/typecheck/test/build). Omitted for\n * `plan` — there is no code to gate against a brief.\n */\n gate?: GateResult;\n}\n\n/** Runs one factory milestone and returns its deliverable, plus that milestone's gate result. */\nexport interface FactoryJobHooks {\n /**\n * Runs the factory's plan phase for `job` (mirrors `.sandcastle/main.ts`'s\n * Phase 1): returns the per-ticket fan-out the implement milestone splits\n * into, plus the plan document itself as increment 1's artifact. No gate\n * result — planning produces no code to lint/typecheck/test/build.\n */\n plan(\n job: FactoryJobRequest\n ): Promise<{ tickets: FactoryTicket[]; artifact: Uint8Array }>;\n /**\n * Runs one ticket's implement sandbox pipeline (mirrors Phase 2's\n * per-issue `sandbox.run`, which ends in the gate per `FACTORY.md`) and\n * returns its deliverable (e.g. the ticket's diff) plus that run's gate\n * result.\n */\n implement(ticket: FactoryTicket): Promise<FactoryJobWork>;\n /**\n * Runs the factory's merge/review phase over every completed ticket\n * (mirrors Phase 3, which re-runs the gate per `merge-prompt.md`) and\n * returns the final deliverable plus that run's gate result.\n */\n review(tickets: FactoryTicket[]): Promise<FactoryJobWork>;\n}\n\nexport interface ExecuteFactoryJobOptions {\n job: FactoryJobRequest;\n /** The original kind:5097 request event, verbatim — carried in the result's `request` tag. */\n requestEvent: RelayEvent;\n hooks: FactoryJobHooks;\n publisher: Publisher;\n delivery: JobDeliveryPort;\n relayUrls: string[];\n}\n\nexport interface FactoryJobExecution {\n outcome: FactoryJobOutcome;\n /** The last increment successfully paid for (0 if the buyer never paid increment 1). */\n reachedIncrement: number;\n totalIncrements: number;\n /** The published kind:6097 result event's id. */\n resultEventId: string;\n}\n\nasync function workFor(\n spec: IncrementSpec,\n tickets: FactoryTicket[],\n planArtifact: Uint8Array,\n hooks: FactoryJobHooks\n): Promise<FactoryJobWork> {\n if (spec.milestone === 'plan') return { artifact: planArtifact };\n if (spec.milestone === 'implement') {\n if (!spec.ticket) {\n throw new Error(\n `internal: implement increment ${spec.n} is missing its ticket`\n );\n }\n return hooks.implement(spec.ticket);\n }\n return hooks.review(tickets);\n}\n\n/**\n * Run a job end to end: plan → quote → one increment per milestone boundary\n * (encrypt, upload, offer, wait for payment) → terminal kind:6097 result.\n * Halts at the first unpaid increment (`abandoned-buyer`) or the first\n * hook failure once work is underway (`abandoned-provider`) — see §5.2 of\n * `docs/factory-job-protocol.md` for the three terminal outcomes.\n *\n * Throws if `hooks.plan` itself fails — with no quote ever published, there\n * is no prior kind:7000 event for a result's `reply` e-tag to reference, so\n * no protocol event can be honestly emitted for that failure.\n */\nexport async function executeFactoryJob(\n options: ExecuteFactoryJobOptions\n): Promise<FactoryJobExecution> {\n const { job, requestEvent, hooks, publisher, delivery, relayUrls } =\n options;\n\n if (!publisher.uploadBlob) {\n throw new Error(\n 'the active publisher cannot upload an encrypted increment artifact ' +\n '(uploadBlob unavailable) — executeFactoryJob requires the standalone publisher'\n );\n }\n const uploadBlob = publisher.uploadBlob.bind(publisher);\n\n const { tickets, artifact: planArtifact } = await hooks.plan(job);\n const schedule = planFactoryJob(job.bidMicroUsdc, tickets);\n const totalIncrements = schedule.length;\n\n const quoteEvent = buildQuoteEvent(job, schedule);\n const quoteReceipt = await publisher.publishEvent(quoteEvent, relayUrls);\n\n let parentEventId = quoteReceipt.eventId;\n let reachedIncrement = 0;\n let finalArtifactTxId: string | undefined;\n\n const haltWith = async (\n outcome: FactoryJobOutcome\n ): Promise<FactoryJobExecution> => {\n const resultEvent = buildResultEvent({\n job,\n requestEvent,\n lastEventId: parentEventId,\n outcome,\n reachedIncrement,\n totalIncrements,\n ...(outcome === 'completed' && finalArtifactTxId\n ? { finalArtifact: { arweaveTxId: finalArtifactTxId } }\n : {}),\n });\n const resultReceipt = await publisher.publishEvent(\n resultEvent,\n relayUrls\n );\n return {\n outcome,\n reachedIncrement,\n totalIncrements,\n resultEventId: resultReceipt.eventId,\n };\n };\n\n for (const spec of schedule) {\n let work: FactoryJobWork;\n try {\n work = await workFor(spec, tickets, planArtifact, hooks);\n } catch {\n // Provider-side failure mid-job: stop where we are, no renegotiation.\n return haltWith('abandoned-provider');\n }\n\n const encrypted = await delivery.encryptArtifact(work.artifact);\n const uploadReceipt = await uploadBlob({\n body: Buffer.from(encrypted.ciphertext),\n contentType: 'application/octet-stream',\n ...(job.repo ? { repoId: job.repo } : {}),\n });\n\n const offerEvent = buildIncrementOfferEvent({\n job,\n parentEventId,\n increment: spec,\n artifact: {\n arweaveTxId: uploadReceipt.txId,\n ciphertextSha256: encrypted.ciphertextSha256,\n conditionHex: encrypted.conditionHex,\n },\n ...(work.gate ? { gate: work.gate } : {}),\n });\n const offerReceipt = await publisher.publishEvent(offerEvent, relayUrls);\n\n const paid = await delivery.waitForPayment({\n offerEventId: offerReceipt.eventId,\n conditionHex: encrypted.conditionHex,\n priceUsdc: spec.priceUsdc,\n });\n if (!paid) {\n parentEventId = offerReceipt.eventId;\n return haltWith('abandoned-buyer');\n }\n\n reachedIncrement = spec.n;\n parentEventId = offerReceipt.eventId;\n if (spec.milestone === 'review') finalArtifactTxId = uploadReceipt.txId;\n }\n\n return haltWith('completed');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCO,SAAS,WAAW,MAA2B;AACpD,SAAO,KAAK,OAAO,MAAM,CAAC,UAAU,MAAM,IAAI;AAChD;;;ACtBO,IAAM,2BAA2B;AAEjC,IAAM,0BAA0B;AAEhC,IAAM,4BAA4B;AA6ClC,SAAS,uBAAuB,OAAsC;AAC3E,QAAM,WAAW,MAAM,KAAK,KAAK,CAAC,MAAM,EAAE,CAAC,MAAM,OAAO,EAAE,CAAC,MAAM,MAAM;AACvE,MAAI,CAAC,WAAW,CAAC,GAAG;AAClB,UAAM,IAAI;AAAA,MACR,QAAQ,wBAAwB,UAAU,MAAM,EAAE;AAAA,IACpD;AAAA,EACF;AACA,QAAM,SAAS,MAAM,KAAK,KAAK,CAAC,MAAM,EAAE,CAAC,MAAM,KAAK;AACpD,MAAI,CAAC,SAAS,CAAC,GAAG;AAChB,UAAM,IAAI;AAAA,MACR,QAAQ,wBAAwB,UAAU,MAAM,EAAE;AAAA,IACpD;AAAA,EACF;AAEA,QAAM,SAAS,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,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eAAe;AAAA,MACzC,cAAc,aAAa;AAAA,MAC3B,cAAc,UAAU;AAAA,MACxB,WAAW,KAAK;AAAA,IAClB,CAAC;AACD,QAAI,CAAC,MAAM;AACT,sBAAgB,aAAa;AAC7B,aAAO,SAAS,iBAAiB;AAAA,IACnC;AAEA,uBAAmB,KAAK;AACxB,oBAAgB,aAAa;AAC7B,QAAI,KAAK,cAAc,SAAU,qBAAoB,cAAc;AAAA,EACrE;AAEA,SAAO,SAAS,WAAW;AAC7B;","names":[]}
1
+ {"version":3,"sources":["../src/factory-job-gate.ts","../src/factory-job-events.ts","../src/factory-job-plan.ts","../src/factory-job-execute.ts"],"sourcesContent":["/**\n * Factory job protocol — reproducible gate result per increment (#53).\n *\n * Decision 5 of toon-meta#262 splits trust into three layers: delivery (the\n * hashlock), the objective floor (this — \"did this increment pass the\n * repo's own gate?\"), and quality (reputation, out of scope here). Per\n * `FACTORY.md`, the pinned pipeline's gate is lint/typecheck/test/build run\n * before a PR is opened; this module is the pure, network-free shape for\n * recording exactly what ran, not a summary verdict.\n *\n * This proves conformance, not fitness for purpose — a gate-passing\n * increment can still completely miss the brief. Reputation is what\n * distinguishes those, never this.\n */\n\n/** One command the gate ran, and whether it passed. */\nexport interface GateCheck {\n /** e.g. \"lint\", \"typecheck\", \"test\", \"build\" — whatever actually ran,\n * never a canonical list (gates differ per repo and drift over time). */\n name: string;\n /** The literal command, e.g. \"eslint .\", so a buyer can reproduce it verbatim. */\n command: string;\n pass: boolean;\n}\n\n/**\n * A reproducible gate result: enough for a buyer to re-run the gate\n * themselves and get the same answer. Omitting the commit or the command\n * set turns this from a reproducible result into a provider's unverifiable\n * claim of having done well — both are required, not advisory.\n */\nexport interface GateResult {\n /** The commit this gate ran against. */\n commit: string;\n /** Toolchain versions relevant to reproducing the result, e.g. `{ node: \"20.11.0\", pnpm: \"9.1.0\" }`. */\n toolchain: Record<string, string>;\n checks: GateCheck[];\n}\n\n/** Overall pass/fail — every recorded check passed. A failing gate is not a protocol violation (it is still published, just visibly failing) — this is only the aggregate the `gate` tag and reputation's gate-pass rate read. */\nexport function gatePassed(gate: GateResult): boolean {\n return gate.checks.every((check) => check.pass);\n}\n","/**\n * Factory job protocol — pure NIP-90 event builders/parser (#52).\n *\n * Wire format per toon-meta's `docs/factory-job-protocol.md`\n * (toon-meta#263), fixed 2026-08-03: kind:5097 job request, kind:6097 job\n * result, kind:7000 job feedback (quote / increment offer / narration,\n * disambiguated by the `status` tag). Mirrors nip34-events.ts: every builder\n * returns an UnsignedEvent — the caller signs and publishes (e.g. through a\n * Publisher, publisher.ts) elsewhere. No crypto, no network, no payment.\n */\n\nimport type { UnsignedEvent } from './nip34-events.js';\nimport type { IncrementSpec } from './factory-job-plan.js';\nimport { gatePassed, type GateResult } from './factory-job-gate.js';\n\n// ---------------------------------------------------------------------------\n// Kinds\n// ---------------------------------------------------------------------------\n\n/** Factory job request (the brief). */\nexport const FACTORY_JOB_REQUEST_KIND = 5097;\n/** Factory job result — terminal state (completed/abandoned-*). */\nexport const FACTORY_JOB_RESULT_KIND = 6097;\n/** Factory job feedback — quote, increment offer, or free narration. */\nexport const FACTORY_JOB_FEEDBACK_KIND = 7000;\n\n/** The three §5.2 terminal outcomes — decision 8 has no fourth. */\nexport type FactoryJobOutcome =\n | 'completed'\n | 'abandoned-provider'\n | 'abandoned-buyer';\n\n// ---------------------------------------------------------------------------\n// kind:5097 — job request\n// ---------------------------------------------------------------------------\n\n/** A parsed kind:5097 job request (§2). */\nexport interface FactoryJobRequest {\n /** The requesting kind:5097 event's id. */\n requestEventId: string;\n /** The requesting kind:5097 event's pubkey (who to reply/bill). */\n buyerPubkey: string;\n /** The brief — free text or a chained milestone reference (§2.3). */\n brief: string;\n /** Maximum the buyer will pay across the whole job (micro-USDC, §2.1). */\n bidMicroUsdc: string;\n /** `param repo` — target repo, e.g. `toon-protocol/buzz`. */\n repo?: string;\n /** `param target` — the ticket/issue this job resolves. */\n target?: string;\n /** `param constraints` — gate requirements / scope limits. */\n constraints?: string;\n /** `output` — expected deliverable MIME type. */\n outputMime?: string;\n}\n\n/** Minimal shape of a relay event this module reads/builds — no signing. */\nexport interface RelayEvent {\n id: string;\n pubkey: string;\n tags: string[][];\n content: string;\n}\n\n/**\n * Parse a kind:5097 job request event's tags into a {@link FactoryJobRequest}.\n * Throws if the required `i` (brief) or `bid` tag is missing — both are\n * REQUIRED per §2.1.\n */\nexport function parseFactoryJobRequest(event: RelayEvent): FactoryJobRequest {\n const briefTag = event.tags.find((t) => t[0] === 'i' && t[2] === 'text');\n if (!briefTag?.[1]) {\n throw new Error(\n `kind:${FACTORY_JOB_REQUEST_KIND} event ${event.id} is missing its required brief (\"i\", \"<brief>\", \"text\") tag`\n );\n }\n const bidTag = event.tags.find((t) => t[0] === 'bid');\n if (!bidTag?.[1]) {\n throw new Error(\n `kind:${FACTORY_JOB_REQUEST_KIND} event ${event.id} is missing its required \"bid\" tag`\n );\n }\n\n const params = event.tags.filter((t) => t[0] === 'param');\n const paramValue = (name: string): string | undefined =>\n params.find((t) => t[1] === name)?.[2];\n\n const repo = paramValue('repo');\n const target = paramValue('target');\n const constraints = paramValue('constraints');\n const outputMime = event.tags.find((t) => t[0] === 'output')?.[1];\n\n return {\n requestEventId: event.id,\n buyerPubkey: event.pubkey,\n brief: briefTag[1],\n bidMicroUsdc: bidTag[1],\n ...(repo !== undefined ? { repo } : {}),\n ...(target !== undefined ? { target } : {}),\n ...(constraints !== undefined ? { constraints } : {}),\n ...(outputMime !== undefined ? { outputMime } : {}),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:7000 status:\"quote\" — the RFQ reply (§3)\n// ---------------------------------------------------------------------------\n\n/**\n * Build the `kind:7000 status:\"quote\"` reply: the proposed increment\n * schedule, committing nothing (§3.3 — there is no accept message; payment\n * of increment 1 is acceptance).\n */\nexport function buildQuoteEvent(\n job: FactoryJobRequest,\n schedule: IncrementSpec[]\n): UnsignedEvent {\n return {\n kind: FACTORY_JOB_FEEDBACK_KIND,\n content: JSON.stringify({\n increments: schedule.map((s) => ({\n n: s.n,\n of: s.of,\n milestone: s.milestone,\n priceUsdc: s.priceUsdc,\n })),\n }),\n tags: [\n ['e', job.requestEventId, '', 'root'],\n ['p', job.buyerPubkey],\n ['status', 'quote'],\n ],\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:7000 status:\"partial\" — the increment offer (§4)\n// ---------------------------------------------------------------------------\n\n/** Where the encrypted increment artifact lives, and its hashlock condition. */\nexport interface EncryptedArtifactRef {\n /** Arweave tx id the ciphertext was uploaded to. */\n arweaveTxId: string;\n /** sha256 of the ciphertext, hex — lets the buyer detect a bad fetch. */\n ciphertextSha256: string;\n /** `sha256(key)` hex, where `key` decrypts the artifact (§4.2 — the join). */\n conditionHex: string;\n}\n\nexport interface BuildIncrementOfferOptions {\n job: FactoryJobRequest;\n /** The quote event's id for increment 1, else the previous offer's id. */\n parentEventId: string;\n increment: IncrementSpec;\n artifact: EncryptedArtifactRef;\n /**\n * The reproducible gate result for this increment's work (#53 — the\n * objective floor), when one ran. Omitted for milestones with nothing to\n * gate (e.g. `plan` — there is no code to lint against a brief).\n */\n gate?: GateResult;\n}\n\n/** A gate result missing its commit or check list cannot be reproduced by the buyer — reject it here rather than publish an unverifiable claim. */\nfunction assertReproducible(gate: GateResult): void {\n if (gate.checks.length === 0) {\n throw new Error(\n 'gate result must record at least one check for the offer to be reproducible'\n );\n }\n if (!gate.commit) {\n throw new Error(\n 'gate result must record the commit it ran against for the offer to be reproducible'\n );\n }\n}\n\n/**\n * Build the `kind:7000 status:\"partial\"` increment offer — published once\n * the provider has done that increment's work and uploaded the encrypted\n * artifact. This is the join between the relay plane and the connector\n * plane (§4.2): `condition` here MUST equal the paying PREPARE's\n * `executionCondition`, byte for byte.\n *\n * When `gate` is supplied, the offer also carries a `[\"gate\", \"pass\"|\"fail\"]`\n * tag (cheap to scan for a gate-pass rate, decision 8) and the full\n * reproducible result in `content` — visible to the buyer before they pay,\n * per the issue: a gate-failing increment is still offered, never hidden.\n */\nexport function buildIncrementOfferEvent(\n options: BuildIncrementOfferOptions\n): UnsignedEvent {\n const { job, parentEventId, increment, artifact, gate } = options;\n if (gate) assertReproducible(gate);\n\n const tags: string[][] = [\n ['e', job.requestEventId, '', 'root'],\n ['e', parentEventId, '', 'reply'],\n ['p', job.buyerPubkey],\n ['status', 'partial'],\n ['increment', String(increment.n), String(increment.of)],\n ['i', artifact.arweaveTxId, 'url'],\n ['i', artifact.ciphertextSha256, 'text', '', 'hash'],\n ['amount', increment.priceUsdc, 'usdc'],\n ['condition', artifact.conditionHex],\n ];\n if (gate) tags.push(['gate', gatePassed(gate) ? 'pass' : 'fail']);\n\n return {\n kind: FACTORY_JOB_FEEDBACK_KIND,\n content: gate ? JSON.stringify({ gate }) : '',\n tags,\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:7000 status:\"processing\" — free narration (§6)\n// ---------------------------------------------------------------------------\n\nexport interface BuildNarrationOptions {\n job: FactoryJobRequest;\n /** The prior event in the thread (quote, offer, or narration). */\n parentEventId: string;\n message: string;\n}\n\n/**\n * Build a free narration event — no artifact, no `amount`/`condition`, MUST\n * NOT be paid against (§6). This is what makes a provider look alive between\n * increments.\n */\nexport function buildNarrationEvent(\n options: BuildNarrationOptions\n): UnsignedEvent {\n const { job, parentEventId, message } = options;\n return {\n kind: FACTORY_JOB_FEEDBACK_KIND,\n content: message,\n tags: [\n ['e', job.requestEventId, '', 'root'],\n ['e', parentEventId, '', 'reply'],\n ['p', job.buyerPubkey],\n ['status', 'processing'],\n ],\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:6097 — job result (§5)\n// ---------------------------------------------------------------------------\n\nexport interface BuildResultEventOptions {\n job: FactoryJobRequest;\n /** The original kind:5097 request event, verbatim (the `request` tag). */\n requestEvent: RelayEvent;\n /** The last kind:7000 event in the thread (offer or narration). */\n lastEventId: string;\n outcome: FactoryJobOutcome;\n /** How far the job got — `n-reached == of` only when outcome is completed. */\n reachedIncrement: number;\n totalIncrements: number;\n /** Required (and only meaningful) when outcome is `\"completed\"` (§5.2). */\n finalArtifact?: { arweaveTxId: string };\n}\n\n/**\n * Build the terminal `kind:6097` job result. Reputation (decision 8) is\n * computed from exactly this event and nothing else.\n */\nexport function buildResultEvent(\n options: BuildResultEventOptions\n): UnsignedEvent {\n const {\n job,\n requestEvent,\n lastEventId,\n outcome,\n reachedIncrement,\n totalIncrements,\n finalArtifact,\n } = options;\n\n const tags: string[][] = [\n ['e', job.requestEventId, '', 'root'],\n ['e', lastEventId, '', 'reply'],\n ['p', job.buyerPubkey],\n ['request', JSON.stringify(requestEvent)],\n ['outcome', outcome],\n ['increment', String(reachedIncrement), String(totalIncrements)],\n ];\n if (outcome === 'completed' && finalArtifact) {\n tags.push(['i', finalArtifact.arweaveTxId, 'url']);\n }\n\n return {\n kind: FACTORY_JOB_RESULT_KIND,\n content: '',\n tags,\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n","/**\n * Factory job protocol — increment schedule planner (#52).\n *\n * `planFactoryJob` is the network-free half of the adapter (mirrors\n * `planPush`'s split from `executePush` in push.ts): given a job's `bid` and\n * the ticket list the factory's plan phase produced, it prices the\n * milestone boundaries decision 6 of toon-meta#262 fixed as increments —\n * plan → implement ×N tickets → review — and returns the schedule that\n * becomes the `kind:7000 status:\"quote\"` content (§3.2 of\n * `docs/factory-job-protocol.md`).\n *\n * Per the issue gotcha, `implement` must be many increments, not one: this\n * always emits one increment per ticket rather than a single lump-sum\n * implement increment, using the factory's existing parallel per-issue\n * fan-out (`.sandcastle/main.ts`'s Plan phase output — `{issues: [{id,\n * title, branch}]}`) as the boundary.\n */\n\n/** One ticket the factory's plan phase fanned the implement milestone into. */\nexport interface FactoryTicket {\n id: string;\n title: string;\n branch: string;\n}\n\nexport type FactoryMilestone = 'plan' | 'implement' | 'review';\n\n/** One priced increment in the schedule (§3.2's `increments[]` shape). */\nexport interface IncrementSpec {\n n: number;\n of: number;\n milestone: FactoryMilestone;\n /** Set only for `milestone: \"implement\"` increments. */\n ticket?: FactoryTicket;\n priceUsdc: string;\n}\n\n/** Plan milestone's share of the bid, in basis points. */\nconst PLAN_SHARE_BPS = 1000n; // 10%\n/** Review milestone's share of the bid, in basis points. */\nconst REVIEW_SHARE_BPS = 1000n; // 10%\nconst BPS_DENOM = 10000n;\n\n/**\n * Build the increment schedule for a job, given the tickets its plan phase\n * produced. Plan and review each get a fixed 10% of the bid; the remaining\n * 80% (\"implement\") splits evenly across tickets, with the integer-division\n * remainder distributed one micro-USDC at a time to the earliest tickets —\n * so `sum(priceUsdc) === bid` exactly (§3.2 only requires `<=`, but an exact\n * match avoids \"where did the leftover micro-USDC go\" questions).\n *\n * Per decision 7, this schedule is agreed before any paid work starts and is\n * never repriced — a job that runs larger than `tickets` implied is a\n * lesson, not a renegotiation.\n *\n * Throws if `tickets` is empty (a job with no implementation work has no\n * increments to schedule) or `bidMicroUsdc` is not a positive integer.\n */\nexport function planFactoryJob(\n bidMicroUsdc: string,\n tickets: FactoryTicket[]\n): IncrementSpec[] {\n if (tickets.length === 0) {\n throw new Error(\n 'planFactoryJob requires at least one implementation ticket from the plan phase'\n );\n }\n\n let bid: bigint;\n try {\n bid = BigInt(bidMicroUsdc);\n } catch {\n throw new Error(`bidMicroUsdc must be an integer string, got ${bidMicroUsdc}`);\n }\n if (bid <= 0n) {\n throw new Error(`bidMicroUsdc must be positive, got ${bidMicroUsdc}`);\n }\n\n const planPrice = (bid * PLAN_SHARE_BPS) / BPS_DENOM;\n const reviewPrice = (bid * REVIEW_SHARE_BPS) / BPS_DENOM;\n const implementTotal = bid - planPrice - reviewPrice;\n\n const ticketCount = BigInt(tickets.length);\n const base = implementTotal / ticketCount;\n const remainder = implementTotal % ticketCount;\n\n const total = tickets.length + 2;\n const schedule: IncrementSpec[] = [\n { n: 1, of: total, milestone: 'plan', priceUsdc: planPrice.toString() },\n ];\n\n tickets.forEach((ticket, i) => {\n const price = base + (BigInt(i) < remainder ? 1n : 0n);\n schedule.push({\n n: i + 2,\n of: total,\n milestone: 'implement',\n ticket,\n priceUsdc: price.toString(),\n });\n });\n\n schedule.push({\n n: total,\n of: total,\n milestone: 'review',\n priceUsdc: reviewPrice.toString(),\n });\n\n return schedule;\n}\n","/**\n * executeFactoryJob — the adapter's imperative shell (#52): runs the\n * factory's own milestones (`.sandcastle/main.ts`'s plan → per-ticket\n * implement+review → merge phases) through `hooks`, and turns each\n * milestone boundary into a paid increment via `publisher` (existing,\n * publisher.ts — upload + event publish) and `delivery` (new,\n * factory-job-delivery.ts — encrypt + payment wait).\n *\n * Mirrors `executePush`'s split from `planPush`: `planFactoryJob` is the\n * network-free planning half; this is the half that spends money.\n *\n * Decision 6 (toon-meta#262): work happens BEFORE the packet, so every\n * increment's artifact is produced and uploaded before that increment is\n * offered for payment. Decision 7: the schedule is fixed once the quote is\n * published — this never reprices mid-job. Per the issue: \"Stop on\n * non-payment. One unpaid increment and work halts\" — the symmetric\n * protection that neither side is ever exposed for more than one increment.\n */\n\nimport type { Publisher } from './publisher.js';\nimport type { JobDeliveryPort } from './factory-job-delivery.js';\nimport {\n buildIncrementOfferEvent,\n buildQuoteEvent,\n buildResultEvent,\n type FactoryJobOutcome,\n type FactoryJobRequest,\n type RelayEvent,\n} from './factory-job-events.js';\nimport type { GateResult } from './factory-job-gate.js';\nimport {\n planFactoryJob,\n type FactoryTicket,\n type IncrementSpec,\n} from './factory-job-plan.js';\n\n/** One milestone's deliverable, plus the gate result that ran against it, when one did. */\nexport interface FactoryJobWork {\n artifact: Uint8Array;\n /**\n * The reproducible gate result (#53) for this milestone's work, per\n * `FACTORY.md`'s pinned pipeline (lint/typecheck/test/build). Omitted for\n * `plan` — there is no code to gate against a brief.\n */\n gate?: GateResult;\n}\n\n/** Runs one factory milestone and returns its deliverable, plus that milestone's gate result. */\nexport interface FactoryJobHooks {\n /**\n * Runs the factory's plan phase for `job` (mirrors `.sandcastle/main.ts`'s\n * Phase 1): returns the per-ticket fan-out the implement milestone splits\n * into, plus the plan document itself as increment 1's artifact. No gate\n * result — planning produces no code to lint/typecheck/test/build.\n */\n plan(\n job: FactoryJobRequest\n ): Promise<{ tickets: FactoryTicket[]; artifact: Uint8Array }>;\n /**\n * Runs one ticket's implement sandbox pipeline (mirrors Phase 2's\n * per-issue `sandbox.run`, which ends in the gate per `FACTORY.md`) and\n * returns its deliverable (e.g. the ticket's diff) plus that run's gate\n * result.\n */\n implement(ticket: FactoryTicket): Promise<FactoryJobWork>;\n /**\n * Runs the factory's merge/review phase over every completed ticket\n * (mirrors Phase 3, which re-runs the gate per `merge-prompt.md`) and\n * returns the final deliverable plus that run's gate result.\n */\n review(tickets: FactoryTicket[]): Promise<FactoryJobWork>;\n}\n\nexport interface ExecuteFactoryJobOptions {\n job: FactoryJobRequest;\n /** The original kind:5097 request event, verbatim — carried in the result's `request` tag. */\n requestEvent: RelayEvent;\n hooks: FactoryJobHooks;\n publisher: Publisher;\n delivery: JobDeliveryPort;\n relayUrls: string[];\n}\n\nexport interface FactoryJobExecution {\n outcome: FactoryJobOutcome;\n /** The last increment successfully paid for (0 if the buyer never paid increment 1). */\n reachedIncrement: number;\n totalIncrements: number;\n /** The published kind:6097 result event's id. */\n resultEventId: string;\n}\n\nasync function workFor(\n spec: IncrementSpec,\n tickets: FactoryTicket[],\n planArtifact: Uint8Array,\n hooks: FactoryJobHooks\n): Promise<FactoryJobWork> {\n if (spec.milestone === 'plan') return { artifact: planArtifact };\n if (spec.milestone === 'implement') {\n if (!spec.ticket) {\n throw new Error(\n `internal: implement increment ${spec.n} is missing its ticket`\n );\n }\n return hooks.implement(spec.ticket);\n }\n return hooks.review(tickets);\n}\n\n/**\n * Run a job end to end: plan → quote → one increment per milestone boundary\n * (encrypt, upload, offer, wait for payment) → terminal kind:6097 result.\n * Halts at the first unpaid increment (`abandoned-buyer`) or the first\n * hook failure once work is underway (`abandoned-provider`) — see §5.2 of\n * `docs/factory-job-protocol.md` for the three terminal outcomes.\n *\n * Throws if `hooks.plan` itself fails — with no quote ever published, there\n * is no prior kind:7000 event for a result's `reply` e-tag to reference, so\n * no protocol event can be honestly emitted for that failure.\n */\nexport async function executeFactoryJob(\n options: ExecuteFactoryJobOptions\n): Promise<FactoryJobExecution> {\n const { job, requestEvent, hooks, publisher, delivery, relayUrls } =\n options;\n\n if (!publisher.uploadBlob) {\n throw new Error(\n 'the active publisher cannot upload an encrypted increment artifact ' +\n '(uploadBlob unavailable) — executeFactoryJob requires the standalone publisher'\n );\n }\n const uploadBlob = publisher.uploadBlob.bind(publisher);\n\n const { tickets, artifact: planArtifact } = await hooks.plan(job);\n const schedule = planFactoryJob(job.bidMicroUsdc, tickets);\n const totalIncrements = schedule.length;\n\n const quoteEvent = buildQuoteEvent(job, schedule);\n const quoteReceipt = await publisher.publishEvent(quoteEvent, relayUrls);\n\n let parentEventId = quoteReceipt.eventId;\n let reachedIncrement = 0;\n let finalArtifactTxId: string | undefined;\n\n const haltWith = async (\n outcome: FactoryJobOutcome\n ): Promise<FactoryJobExecution> => {\n const resultEvent = buildResultEvent({\n job,\n requestEvent,\n lastEventId: parentEventId,\n outcome,\n reachedIncrement,\n totalIncrements,\n ...(outcome === 'completed' && finalArtifactTxId\n ? { finalArtifact: { arweaveTxId: finalArtifactTxId } }\n : {}),\n });\n const resultReceipt = await publisher.publishEvent(\n resultEvent,\n relayUrls\n );\n return {\n outcome,\n reachedIncrement,\n totalIncrements,\n resultEventId: resultReceipt.eventId,\n };\n };\n\n for (const spec of schedule) {\n let work: FactoryJobWork;\n try {\n work = await workFor(spec, tickets, planArtifact, hooks);\n } catch {\n // Provider-side failure mid-job: stop where we are, no renegotiation.\n return haltWith('abandoned-provider');\n }\n\n const encrypted = await delivery.encryptArtifact(work.artifact);\n const uploadReceipt = await uploadBlob({\n body: Buffer.from(encrypted.ciphertext),\n contentType: 'application/octet-stream',\n ...(job.repo ? { repoId: job.repo } : {}),\n });\n\n const offerEvent = buildIncrementOfferEvent({\n job,\n parentEventId,\n increment: spec,\n artifact: {\n arweaveTxId: uploadReceipt.txId,\n ciphertextSha256: encrypted.ciphertextSha256,\n conditionHex: encrypted.conditionHex,\n },\n ...(work.gate ? { gate: work.gate } : {}),\n });\n const offerReceipt = await publisher.publishEvent(offerEvent, relayUrls);\n\n const paid = await delivery.waitForPayment({\n offerEventId: offerReceipt.eventId,\n conditionHex: encrypted.conditionHex,\n priceUsdc: spec.priceUsdc,\n });\n if (!paid) {\n parentEventId = offerReceipt.eventId;\n return haltWith('abandoned-buyer');\n }\n\n reachedIncrement = spec.n;\n parentEventId = offerReceipt.eventId;\n if (spec.milestone === 'review') finalArtifactTxId = uploadReceipt.txId;\n }\n\n return haltWith('completed');\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCO,SAAS,WAAW,MAA2B;AACpD,SAAO,KAAK,OAAO,MAAM,CAAC,UAAU,MAAM,IAAI;AAChD;;;ACtBO,IAAM,2BAA2B;AAEjC,IAAM,0BAA0B;AAEhC,IAAM,4BAA4B;AA6ClC,SAAS,uBAAuB,OAAsC;AAC3E,QAAM,WAAW,MAAM,KAAK,KAAK,CAAC,MAAM,EAAE,CAAC,MAAM,OAAO,EAAE,CAAC,MAAM,MAAM;AACvE,MAAI,CAAC,WAAW,CAAC,GAAG;AAClB,UAAM,IAAI;AAAA,MACR,QAAQ,wBAAwB,UAAU,MAAM,EAAE;AAAA,IACpD;AAAA,EACF;AACA,QAAM,SAAS,MAAM,KAAK,KAAK,CAAC,MAAM,EAAE,CAAC,MAAM,KAAK;AACpD,MAAI,CAAC,SAAS,CAAC,GAAG;AAChB,UAAM,IAAI;AAAA,MACR,QAAQ,wBAAwB,UAAU,MAAM,EAAE;AAAA,IACpD;AAAA,EACF;AAEA,QAAM,SAAS,MAAM,KAAK,OAAO,CAAC,MAAM,EAAE,CAAC,MAAM,OAAO;AACxD,QAAM,aAAa,CA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AA,MAC3B,cAAc,UAAU;AAAA,MACxB,WAAW,KAAK;AAAA,IAClB,CAAC;AACD,QAAI,CAAC,MAAM;AACT,sBAAgB,aAAa;AAC7B,aAAO,SAAS,iBAAiB;AAAA,IACnC;AAEA,uBAAmB,KAAK;AACxB,oBAAgB,aAAa;AAC7B,QAAI,KAAK,cAAc,SAAU,qBAAoB,cAAc;AAAA,EACrE;AAEA,SAAO,SAAS,WAAW;AAC7B;","names":[]}
@@ -126,6 +126,42 @@ declare function parseMaintainers(tags: string[][]): string[];
126
126
  * `maintainers` tag). All values are lowercased hex.
127
127
  */
128
128
  declare function authorizedStatusAuthors(ownerPubkey: string, repoAnnouncementTags: string[][]): Set<string>;
129
+ /**
130
+ * NIP-34 tag naming the repo's declared payout pointer: a single
131
+ * `["payout", "<chain>", "<address>"]` tag on the kind:30617 announcement.
132
+ * No pointer → no split, the serving node keeps 100% of repo-scoped write
133
+ * fees (toon-meta#391 decision 2). The tag carries the chain label so the
134
+ * shape survives future chains, but v1 accepts exactly one: `evm` — the
135
+ * payout accrual ledger is EVM-only today
136
+ * (`crates/connector-client-edge/src/btp.rs:270-272`).
137
+ */
138
+ declare const PAYOUT_TAG = "payout";
139
+ /** Chains the payout pointer can target. v1: `evm` only (toon-meta#391). */
140
+ type PayoutChain = 'evm';
141
+ /** A repo's declared payout pointer (parsed from / built into the `payout` tag). */
142
+ interface PayoutPointer {
143
+ chain: PayoutChain;
144
+ /** EIP-55 checksummed address (never a raw lowercase/mixed-case echo). */
145
+ address: string;
146
+ }
147
+ /**
148
+ * True when `address` is a structurally valid, correctly-checksummed EVM
149
+ * address: `0x` + 40 hex chars, and — when mixed-case — a valid EIP-55
150
+ * checksum (an all-lowercase address is accepted as "unchecksummed").
151
+ */
152
+ declare function isValidEvmPayoutAddress(address: string): boolean;
153
+ /**
154
+ * Collect the repo's declared payout pointer from a kind:30617 event's tags.
155
+ * Only `["payout", "evm", <address>]` with a shape- and checksum-valid
156
+ * address is accepted; the address is normalized to its EIP-55 checksummed
157
+ * form. Tolerant of relay noise: an unsupported chain or malformed address
158
+ * is skipped (not thrown). The relay is permissionless and 30617 is
159
+ * replaceable, so a legacy/hand-crafted event could carry more than one
160
+ * `payout` tag — the first valid one wins and the rest are ignored (a
161
+ * `console.warn` notes the drop so a stray extra tag isn't silently
162
+ * mysterious).
163
+ */
164
+ declare function parsePayout(tags: string[][]): PayoutPointer | null;
129
165
  /**
130
166
  * Build a kind:30617 repository announcement event.
131
167
  *
@@ -137,8 +173,11 @@ declare function authorizedStatusAuthors(ownerPubkey: string, repoAnnouncementTa
137
173
  * values are dropped. The owner (the signer) is an implicit maintainer and
138
174
  * need not be listed — if passed it is emitted, which is harmless since the
139
175
  * owner is authorized regardless. See {@link MAINTAINERS_TAG}.
176
+ * @param payout - Optional declared payout pointer (rig#92). Emitted as a
177
+ * single `["payout", "evm", <address>]` tag when given; omit (or pass
178
+ * `null`) to leave the repo with no payout pointer. See {@link PAYOUT_TAG}.
140
179
  */
141
- declare function buildRepoAnnouncement(repoId: string, name: string, description: string, maintainers?: string[]): UnsignedEvent;
180
+ declare function buildRepoAnnouncement(repoId: string, name: string, description: string, maintainers?: string[], payout?: PayoutPointer | null): UnsignedEvent;
142
181
  /**
143
182
  * Build a kind:30618 repository refs/state event.
144
183
  *
@@ -392,4 +431,4 @@ interface Publisher {
392
431
  publishEvent(event: UnsignedEvent, relayUrls: string[]): Promise<PublishReceipt>;
393
432
  }
394
433
 
395
- export { type BlobUpload as B, COMMENT_KIND as C, type FeeRates as F, type GitObjectUpload as G, MAINTAINERS_TAG as M, type Publisher as P, REPOSITORY_STATE_KIND as R, type StoreJobRequest as S, type UploadReceipt as U, type StoreJobResponse as a, type UnsignedEvent as b, type PublishReceipt as c, type GitObjectType as d, type GitObject as e, MAX_OBJECT_SIZE as f, type StatusKind as g, authorizedStatusAuthors as h, buildComment as i, buildIssue as j, buildPatch as k, buildRepoAnnouncement as l, buildRepoRefs as m, buildStatus as n, createGitBlob as o, createGitCommit as p, createGitTag as q, createGitTree as r, hashGitObject as s, parseMaintainers as t };
434
+ export { type BlobUpload as B, COMMENT_KIND as C, type FeeRates as F, type GitObjectUpload as G, MAINTAINERS_TAG as M, type Publisher as P, REPOSITORY_STATE_KIND as R, type StoreJobRequest as S, type UploadReceipt as U, type StoreJobResponse as a, type UnsignedEvent as b, type PublishReceipt as c, type GitObjectType as d, type PayoutPointer as e, type GitObject as f, MAX_OBJECT_SIZE as g, PAYOUT_TAG as h, type PayoutChain as i, type StatusKind as j, authorizedStatusAuthors as k, buildComment as l, buildIssue as m, buildPatch as n, buildRepoAnnouncement as o, buildRepoRefs as p, buildStatus as q, createGitBlob as r, createGitCommit as s, createGitTag as t, createGitTree as u, hashGitObject as v, isValidEvmPayoutAddress as w, parseMaintainers as x, parsePayout as y };
@@ -1,4 +1,4 @@
1
- import { P as Publisher, F as FeeRates, G as GitObjectUpload, U as UploadReceipt, B as BlobUpload, S as StoreJobRequest, a as StoreJobResponse, b as UnsignedEvent, c as PublishReceipt } from '../publisher-CcL96ugq.js';
1
+ import { P as Publisher, F as FeeRates, G as GitObjectUpload, U as UploadReceipt, B as BlobUpload, S as StoreJobRequest, a as StoreJobResponse, b as UnsignedEvent, c as PublishReceipt } from '../publisher-DMJ06cuL.js';
2
2
  import '@toon-protocol/core/nip34';
3
3
 
4
4
  /**
@@ -3,7 +3,7 @@ import {
3
3
  } from "./chunk-LTFMPOHU.js";
4
4
  import {
5
5
  fetchRemoteState
6
- } from "./chunk-2KJJ7LSO.js";
6
+ } from "./chunk-NCEMQUPA.js";
7
7
  import {
8
8
  ConnectorPublisher
9
9
  } from "./chunk-CDSFVZDV.js";
@@ -387,4 +387,4 @@ export {
387
387
  resolveConnectorSettings,
388
388
  resolveDestinations
389
389
  };
390
- //# sourceMappingURL=standalone-mode-LEAC4A2L.js.map
390
+ //# sourceMappingURL=standalone-mode-KTYRTUS6.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@toon-protocol/rig",
3
- "version": "4.0.0",
3
+ "version": "4.1.0",
4
4
  "description": "Git-to-TOON write path core — build git objects and NIP-34 events for the Rig control plane",
5
5
  "license": "MIT",
6
6
  "author": "Jonathan Green",
@@ -47,7 +47,8 @@
47
47
  "@toon-format/toon": "^1.0.0",
48
48
  "@toon-protocol/client": "^2.1.1",
49
49
  "@toon-protocol/core": "^3.2.0",
50
- "nostr-tools": "^2.20.0"
50
+ "nostr-tools": "^2.20.0",
51
+ "viem": "^2.0.0"
51
52
  },
52
53
  "optionalDependencies": {
53
54
  "@ar.io/sdk": "^4.0.3",
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/nip34-events.ts","../src/remote-state.ts","../../../node_modules/.pnpm/@toon-protocol+arweave@0.2.0/node_modules/@toon-protocol/arweave/src/gateways.ts","../../../node_modules/.pnpm/@toon-protocol+arweave@0.2.0/node_modules/@toon-protocol/arweave/src/git-sha.ts"],"sourcesContent":["/**\n * Pure NIP-34 event builders for the Git-to-TOON write path.\n *\n * Promoted from `packages/rig-web/tests/e2e/seed/lib/event-builders.ts` (#223).\n * All builders return UnsignedEvent — the caller signs with their keypair\n * via finalizeEvent() and publishes through a Publisher (#226). Tag\n * structures follow the NIP-34 spec and `@toon-protocol/core/nip34`.\n */\n\nimport {\n ISSUE_KIND,\n PATCH_KIND,\n REPOSITORY_ANNOUNCEMENT_KIND,\n} from '@toon-protocol/core/nip34';\nimport type {\n STATUS_APPLIED_KIND,\n STATUS_CLOSED_KIND,\n STATUS_DRAFT_KIND,\n STATUS_OPEN_KIND,\n} from '@toon-protocol/core/nip34';\n\n// Kinds not (yet) exported by @toon-protocol/core/nip34:\n/** Repository State (refs) — replaceable, pairs with kind:30617 via `d` tag. */\nexport const REPOSITORY_STATE_KIND = 30618;\n/** Comment on an issue or patch (NIP-22 style threading within NIP-34). */\nexport const COMMENT_KIND = 1622;\n\n// ---------------------------------------------------------------------------\n// UnsignedEvent type (subset of nostr-tools — no id, sig, or pubkey)\n// ---------------------------------------------------------------------------\n\nexport interface UnsignedEvent {\n kind: number;\n content: string;\n tags: string[][];\n created_at: number;\n}\n\n// ---------------------------------------------------------------------------\n// kind:30617 — Repository Announcement (+ maintainer authority, #287)\n// ---------------------------------------------------------------------------\n\n/**\n * NIP-34 tag naming the repo's declared maintainers: one multi-valued tag\n * `[\"maintainers\", \"<hex-pubkey>\", \"<hex-pubkey>\", …]` on the kind:30617\n * announcement (mirrors the spec's multi-valued `relays` tag). The repo\n * OWNER — the announcement event's own pubkey — is ALWAYS an implicit\n * maintainer and need not be listed. Consumers derive an issue/PR's status\n * ONLY from kind:1630-1633 events signed by owner ∪ maintainers (#287): the\n * relay is permissionless, so this is the CONSUMER-side authority filter.\n */\nexport const MAINTAINERS_TAG = 'maintainers';\n\nconst HEX64 = /^[0-9a-f]{64}$/;\n\n/**\n * Collect the declared maintainer pubkeys (lowercased hex) from a kind:30617\n * event's tags. Tolerant of repeated `maintainers` tags and non-hex noise —\n * only 64-char hex values survive. Does NOT include the owner (implicit).\n */\nexport function parseMaintainers(tags: string[][]): string[] {\n const out: string[] = [];\n const seen = new Set<string>();\n for (const tag of tags) {\n if (tag[0] !== MAINTAINERS_TAG) continue;\n for (const value of tag.slice(1)) {\n const hex = value.toLowerCase();\n if (HEX64.test(hex) && !seen.has(hex)) {\n seen.add(hex);\n out.push(hex);\n }\n }\n }\n return out;\n}\n\n/**\n * The set of pubkeys whose kind:1630-1633 status events are authoritative for\n * a repo: the owner (always) ∪ the declared maintainers (from the 30617's\n * `maintainers` tag). All values are lowercased hex.\n */\nexport function authorizedStatusAuthors(\n ownerPubkey: string,\n repoAnnouncementTags: string[][]\n): Set<string> {\n return new Set([\n ownerPubkey.toLowerCase(),\n ...parseMaintainers(repoAnnouncementTags),\n ]);\n}\n\n/**\n * Build a kind:30617 repository announcement event.\n *\n * @param repoId - Repository identifier (d tag)\n * @param name - Human-readable repository name\n * @param description - Repository description\n * @param maintainers - Optional declared maintainer pubkeys (hex). Emitted as\n * a single `[\"maintainers\", …]` tag when non-empty; duplicate and non-64-hex\n * values are dropped. The owner (the signer) is an implicit maintainer and\n * need not be listed — if passed it is emitted, which is harmless since the\n * owner is authorized regardless. See {@link MAINTAINERS_TAG}.\n */\nexport function buildRepoAnnouncement(\n repoId: string,\n name: string,\n description: string,\n maintainers: string[] = []\n): UnsignedEvent {\n const tags: string[][] = [\n ['d', repoId],\n ['name', name],\n ['description', description],\n ];\n const declared: string[] = [];\n const seen = new Set<string>();\n for (const value of maintainers) {\n const hex = value.toLowerCase();\n if (HEX64.test(hex) && !seen.has(hex)) {\n seen.add(hex);\n declared.push(hex);\n }\n }\n if (declared.length > 0) {\n tags.push([MAINTAINERS_TAG, ...declared]);\n }\n return {\n kind: REPOSITORY_ANNOUNCEMENT_KIND,\n content: '',\n tags,\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:30618 — Repository Refs/State\n// ---------------------------------------------------------------------------\n\n/**\n * Build a kind:30618 repository refs/state event.\n *\n * @param repoId - Repository identifier (d tag, matches kind:30617)\n * @param refs - Map of ref paths to commit SHAs (e.g., { 'refs/heads/main': 'abc123' })\n * @param arweaveMap - Map of git SHAs to Arweave transaction IDs\n */\nexport function buildRepoRefs(\n repoId: string,\n refs: Record<string, string>,\n arweaveMap: Record<string, string> = {}\n): UnsignedEvent {\n const tags: string[][] = [['d', repoId]];\n\n // Add ref tags\n for (const [refPath, commitSha] of Object.entries(refs)) {\n tags.push(['r', refPath, commitSha]);\n }\n\n // Default HEAD to first ref (typically refs/heads/main)\n const firstRef = Object.keys(refs)[0];\n if (firstRef) {\n tags.push(['HEAD', `ref: ${firstRef}`]);\n }\n\n // Add arweave SHA-to-txId mapping tags\n for (const [sha, txId] of Object.entries(arweaveMap)) {\n tags.push(['arweave', sha, txId]);\n }\n\n return {\n kind: REPOSITORY_STATE_KIND,\n content: '',\n tags,\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:1621 — Issue\n// ---------------------------------------------------------------------------\n\n/**\n * Build a kind:1621 issue event.\n *\n * @param repoOwnerPubkey - Pubkey of the repository owner\n * @param repoId - Repository identifier\n * @param title - Issue title (subject tag)\n * @param body - Issue body (Markdown content)\n * @param labels - Optional labels (t tags)\n */\nexport function buildIssue(\n repoOwnerPubkey: string,\n repoId: string,\n title: string,\n body: string,\n labels: string[] = []\n): UnsignedEvent {\n const tags: string[][] = [\n ['a', `${REPOSITORY_ANNOUNCEMENT_KIND}:${repoOwnerPubkey}:${repoId}`],\n ['p', repoOwnerPubkey],\n ['subject', title],\n ...labels.map((label) => ['t', label]),\n ];\n\n return {\n kind: ISSUE_KIND,\n content: body,\n tags,\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:1622 — Comment (on issue or PR)\n// ---------------------------------------------------------------------------\n\n/**\n * Build a kind:1622 comment event.\n *\n * @param repoOwnerPubkey - Pubkey of the repository owner\n * @param repoId - Repository identifier\n * @param issueOrPrEventId - Event ID of the issue or PR being commented on\n * @param authorPubkey - Pubkey of the issue/PR author (NIP-34 `p` tag for threading), NOT the comment author\n * @param body - Comment body (Markdown content)\n * @param marker - Event reference marker: 'root' or 'reply' (default: 'reply')\n */\nexport function buildComment(\n repoOwnerPubkey: string,\n repoId: string,\n issueOrPrEventId: string,\n authorPubkey: string,\n body: string,\n marker: 'root' | 'reply' = 'reply'\n): UnsignedEvent {\n return {\n kind: COMMENT_KIND,\n content: body,\n tags: [\n ['a', `${REPOSITORY_ANNOUNCEMENT_KIND}:${repoOwnerPubkey}:${repoId}`],\n ['e', issueOrPrEventId, '', marker],\n ['p', authorPubkey],\n ],\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:1617 — Patch / PR\n// ---------------------------------------------------------------------------\n\n/**\n * Build a kind:1617 patch event.\n *\n * The PR body/description travels in a dedicated `description` tag, NEVER in\n * `content` (#280): `content` is real `git format-patch` output that readers\n * pipe straight into `git am`, and git's patch-format detection hard-fails on\n * any leading prose (verified: \"Patch format detection failed.\"). The tag\n * route keeps `git am` consumption intact while `rig pr show` and the\n * rig-web/views `parsePR` renderers surface the description.\n *\n * @param repoOwnerPubkey - Pubkey of the repository owner\n * @param repoId - Repository identifier\n * @param title - Patch/PR title (subject tag)\n * @param commits - Array of { sha, parentSha } for commit and parent-commit tags\n * @param branchTag - Branch name for the t tag\n * @param content - Real `git format-patch` text (NIP-34 patch body); defaults\n * to '' for callers that only reference commits by tag\n * @param description - PR body/cover text (`description` tag) — kept out of\n * `content` so `git am` still applies it\n */\nexport function buildPatch(\n repoOwnerPubkey: string,\n repoId: string,\n title: string,\n commits: { sha: string; parentSha: string }[],\n branchTag?: string,\n content = '',\n description?: string\n): UnsignedEvent {\n const tags: string[][] = [\n ['a', `${REPOSITORY_ANNOUNCEMENT_KIND}:${repoOwnerPubkey}:${repoId}`],\n ['p', repoOwnerPubkey],\n ['subject', title],\n ];\n\n if (description !== undefined && description !== '') {\n tags.push(['description', description]);\n }\n\n for (const commit of commits) {\n tags.push(['commit', commit.sha]);\n tags.push(['parent-commit', commit.parentSha]);\n }\n\n if (branchTag) {\n tags.push(['t', branchTag]);\n }\n\n return {\n kind: PATCH_KIND,\n content,\n tags,\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n\n// ---------------------------------------------------------------------------\n// kind:1630-1633 — Status\n// ---------------------------------------------------------------------------\n\n/** Status kinds: 1630 open, 1631 applied/merged, 1632 closed, 1633 draft. */\nexport type StatusKind =\n | typeof STATUS_OPEN_KIND\n | typeof STATUS_APPLIED_KIND\n | typeof STATUS_CLOSED_KIND\n | typeof STATUS_DRAFT_KIND;\n\n/**\n * Build a status event (kind 1630-1633).\n *\n * @param targetEventId - Event ID of the patch, PR, or issue being updated\n * @param statusKind - One of 1630 (open), 1631 (applied), 1632 (closed), 1633 (draft)\n * @param targetPubkey - Optional pubkey of the target event author (p tag per NIP-34 StatusEvent)\n */\nexport function buildStatus(\n targetEventId: string,\n statusKind: StatusKind,\n targetPubkey?: string\n): UnsignedEvent {\n const tags: string[][] = [['e', targetEventId]];\n if (targetPubkey) {\n tags.push(['p', targetPubkey]);\n }\n return {\n kind: statusKind,\n content: '',\n tags,\n created_at: Math.floor(Date.now() / 1000),\n };\n}\n","/**\n * Remote repository state reader — the \"what does the remote have?\" half of\n * `rig push` (epic #222, ticket #225).\n *\n * Queries relay(s) over NIP-01 WebSocket for the repository's NIP-34 state:\n * - kind:30618 (repository state): `r` tags → ref map, `HEAD` symref,\n * `arweave` tags → git SHA → Arweave txId hints.\n * - kind:30617 (repository announcement): presence = the repo exists on\n * TOON (first-push detection) + name/description/relays metadata.\n *\n * Both kinds are NIP-33 parameterized-replaceable: per relay only the latest\n * event per (kind, author, d) survives, but we still pick the newest across\n * relays (highest created_at, ties broken by lowest id per NIP-01).\n *\n * SHAs missing from the `arweave` tag map can be resolved via the shared\n * Arweave GraphQL Git-SHA resolver (@toon-protocol/arweave — the same module\n * the rig SPA uses) through {@link RemoteState.resolveMissing}.\n *\n * Relay payload encodings (mirrors rig's `web/relay-client.ts` decode logic):\n * EVENT payloads arrive as an inline JSON object (standard NIP-01), as a\n * double-JSON-encoded string (devnet relay quirk: a JSON string containing\n * the event JSON), or as a TOON-encoded string. All three are tolerated.\n */\n\nimport { decode as decodeToon } from '@toon-format/toon';\nimport {\n resolveGitSha,\n seedShaCache,\n shaCacheKey,\n} from '@toon-protocol/arweave';\nimport { REPOSITORY_ANNOUNCEMENT_KIND } from '@toon-protocol/core/nip34';\n\nimport { REPOSITORY_STATE_KIND, parseMaintainers } from './nip34-events.js';\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\n/** A signed Nostr event as seen on a relay (read side). */\nexport interface NostrEvent {\n id: string;\n pubkey: string;\n created_at: number;\n kind: number;\n tags: string[][];\n content: string;\n sig: string;\n}\n\n/** NIP-01 subscription filter (only the fields rig's readers send). */\nexport interface NostrFilter {\n ids?: string[];\n kinds?: number[];\n authors?: string[];\n '#d'?: string[];\n /** Repo address tag filter, e.g. `30617:<owner>:<repoId>` (#278 tracker). */\n '#a'?: string[];\n /** Event-reference tag filter (#278 tracker: statuses + comments). */\n '#e'?: string[];\n limit?: number;\n}\n\n/**\n * Minimal structural WebSocket type — satisfied by the WHATWG WebSocket\n * global (Node >= 22 / undici, browsers) and by the `ws` package.\n */\nexport interface WebSocketLike {\n readyState: number;\n send(data: string): void;\n close(): void;\n addEventListener(type: string, listener: (event: never) => void): void;\n}\n\n/** Factory for WebSocket connections (injectable for tests / `ws` fallback). */\nexport type WebSocketFactory = (url: string) => WebSocketLike;\n\nexport interface FetchRemoteStateOptions {\n /**\n * Relay WebSocket URLs to query. Plural from day one (forward-compat with\n * multi-relay routing); size 1 is typical today. Results are merged and the\n * newest replaceable event across all relays wins.\n */\n relayUrls: string[];\n /** Repository owner's pubkey (hex) — the author of 30617/30618. */\n ownerPubkey: string;\n /** Repository identifier (NIP-34 `d` tag). */\n repoId: string;\n /** Per-relay timeout in milliseconds (default 10000). On timeout the relay contributes whatever it sent so far. */\n timeoutMs?: number;\n /**\n * Git-SHA → Arweave txId resolver used by {@link RemoteState.resolveMissing}.\n * Defaults to the shared GraphQL resolver from @toon-protocol/arweave;\n * injectable for tests.\n */\n resolveSha?: (sha: string, repo: string) => Promise<string | null>;\n /** WebSocket constructor override (defaults to the global WebSocket). */\n webSocketFactory?: WebSocketFactory;\n}\n\n/** Remote repository state assembled from relay events. */\nexport interface RemoteState {\n /** True when a kind:30617 announcement exists (false ⇒ first push). */\n announced: boolean;\n /** Ref map from the latest kind:30618: refname → commit SHA. */\n refs: Map<string, string>;\n /** HEAD symref target (e.g. `refs/heads/main`), or null if unset. */\n headSymref: string | null;\n /** Git SHA → Arweave txId hints from the latest kind:30618 `arweave` tags. */\n shaToTxId: Map<string, string>;\n /** The latest kind:30618 event, or null if the repo has no state yet. */\n refsEvent: NostrEvent | null;\n /** The latest kind:30617 event, or null if the repo is unannounced. */\n announceEvent: NostrEvent | null;\n /** Repository name from the announcement `name` tag. */\n name: string | null;\n /** Announcement `description` tag (falls back to event content). */\n description: string | null;\n /** Relay URLs advertised in the announcement `relays` tag(s). */\n relays: string[];\n /**\n * Declared maintainer pubkeys (hex) from the announcement `maintainers`\n * tag (#287). Does NOT include the owner (an implicit maintainer). Empty\n * when unannounced or owner-only.\n */\n maintainers: string[];\n /**\n * Resolve SHAs to Arweave txIds: served from the `arweave` tag map when\n * present, otherwise via the GraphQL Git-SHA resolver. SHAs that resolve\n * nowhere are omitted from the returned map.\n */\n resolveMissing(shas: string[]): Promise<Map<string, string>>;\n}\n\n// ---------------------------------------------------------------------------\n// Relay query (NIP-01 REQ → EVENT* → EOSE)\n// ---------------------------------------------------------------------------\n\n/** Validate that a relay URL uses a WebSocket scheme (mirrors rig's url-utils). */\nfunction isValidRelayUrl(url: string): boolean {\n return /^wss?:\\/\\//i.test(url);\n}\n\n/** WHATWG WebSocket OPEN ready state. */\nconst WS_OPEN = 1;\n\nfunction defaultWebSocketFactory(url: string): WebSocketLike {\n const ctor = (\n globalThis as { WebSocket?: new (url: string) => WebSocketLike }\n ).WebSocket;\n if (!ctor) {\n throw new Error(\n 'No global WebSocket constructor (Node >= 22 required) — pass webSocketFactory'\n );\n }\n return new ctor(url);\n}\n\n/**\n * Decode a relay EVENT payload, tolerating every encoding seen in the wild:\n * inline object (standard NIP-01), double-JSON-encoded string (devnet relay\n * serves the event as a JSON string containing the event JSON), or a\n * TOON-encoded string (rig's `decodeToonMessage` path).\n */\nfunction decodeEventPayload(payload: unknown): NostrEvent | null {\n if (payload !== null && typeof payload === 'object') {\n return payload as NostrEvent;\n }\n if (typeof payload !== 'string') {\n return null;\n }\n try {\n const parsed: unknown = JSON.parse(payload);\n if (parsed !== null && typeof parsed === 'object') {\n return parsed as NostrEvent;\n }\n } catch {\n // Not JSON — fall through to TOON\n }\n try {\n return decodeToon(payload) as unknown as NostrEvent;\n } catch {\n return null;\n }\n}\n\n/**\n * Query one relay: send a REQ, collect EVENTs until EOSE, then CLOSE.\n * Mirrors rig's `queryRelay` (partial results on timeout / early close).\n * Exported for reuse by the network-bootstrap discovery (kind:10032).\n */\nexport function queryRelay(\n relayUrl: string,\n filter: NostrFilter,\n timeoutMs: number,\n webSocketFactory: WebSocketFactory\n): Promise<NostrEvent[]> {\n return new Promise((resolve, reject) => {\n const events: NostrEvent[] = [];\n const subId = `git-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n let ws: WebSocketLike;\n // eslint-disable-next-line prefer-const -- assigned after `settle` is defined\n let timeoutHandle: ReturnType<typeof setTimeout>;\n let settled = false;\n\n const settle = (outcome: 'resolve' | 'reject', error?: Error) => {\n if (settled) return;\n settled = true;\n clearTimeout(timeoutHandle);\n try {\n if (ws.readyState === WS_OPEN) {\n ws.send(JSON.stringify(['CLOSE', subId]));\n }\n ws.close();\n } catch {\n // Ignore close errors\n }\n if (outcome === 'reject') {\n reject(error);\n } else {\n resolve(events);\n }\n };\n\n if (!isValidRelayUrl(relayUrl)) {\n reject(\n new Error(\n `Invalid relay URL protocol (must be ws:// or wss://): ${relayUrl}`\n )\n );\n return;\n }\n\n try {\n ws = webSocketFactory(relayUrl);\n } catch (err) {\n reject(new Error(`Failed to connect to relay ${relayUrl}: ${String(err)}`));\n return;\n }\n\n timeoutHandle = setTimeout(() => {\n // Resolve with whatever we collected so far (partial results)\n settle('resolve');\n }, timeoutMs);\n\n ws.addEventListener('open', () => {\n ws.send(JSON.stringify(['REQ', subId, filter]));\n });\n\n ws.addEventListener('message', (msgEvent: { data?: unknown }) => {\n try {\n const msg = JSON.parse(String(msgEvent.data)) as unknown[];\n if (!Array.isArray(msg) || msg.length < 2) return;\n\n const msgType = msg[0];\n if (msgType === 'EVENT' && msg[1] === subId && msg[2] !== undefined) {\n const event = decodeEventPayload(msg[2]);\n if (event) events.push(event);\n } else if (msgType === 'EOSE' && msg[1] === subId) {\n settle('resolve');\n }\n } catch {\n // Ignore parse errors for individual messages\n }\n });\n\n ws.addEventListener('error', (event: { message?: unknown }) => {\n const detail =\n typeof event === 'object' && event !== null && 'message' in event\n ? String(event.message)\n : 'unknown';\n settle(\n 'reject',\n new Error(`WebSocket error connecting to ${relayUrl}: ${detail}`)\n );\n });\n\n ws.addEventListener('close', () => {\n // If we haven't settled yet, resolve with what we have\n settle('resolve');\n });\n });\n}\n\n// ---------------------------------------------------------------------------\n// NIP-33 replaceable selection + tag parsing\n// ---------------------------------------------------------------------------\n\n/**\n * Pick the winning replaceable event: highest created_at, ties broken by\n * lowest id (NIP-01 replaceable-event convention).\n */\nfunction latestReplaceable(events: NostrEvent[]): NostrEvent | null {\n let winner: NostrEvent | null = null;\n for (const event of events) {\n if (\n winner === null ||\n event.created_at > winner.created_at ||\n (event.created_at === winner.created_at && event.id < winner.id)\n ) {\n winner = event;\n }\n }\n return winner;\n}\n\n/** Get the first value for a tag name. */\nfunction getTagValue(tags: string[][], name: string): string | undefined {\n const tag = tags.find((t) => t[0] === name);\n return tag?.[1];\n}\n\n/** Maximum number of refs parsed from a single kind:30618 event (mirrors views). */\nconst MAX_REFS_PER_EVENT = 1000;\n\n/** Symref prefix used in `HEAD` tags: `[\"HEAD\", \"ref: refs/heads/main\"]`. */\nconst SYMREF_PREFIX = 'ref: ';\n\ninterface ParsedRefs {\n refs: Map<string, string>;\n headSymref: string | null;\n shaToTxId: Map<string, string>;\n}\n\n/** Parse a kind:30618 event's `r` / `HEAD` / `arweave` tags. */\nfunction parseRefsEvent(event: NostrEvent): ParsedRefs {\n const refs = new Map<string, string>();\n const shaToTxId = new Map<string, string>();\n let headSymref: string | null = null;\n\n for (const tag of event.tags) {\n const [tagName, v1, v2] = tag;\n if (tagName === 'r' && v1 && v2) {\n if (v1 === 'HEAD' && v2.startsWith(SYMREF_PREFIX)) {\n // Alternate symref spelling: [\"r\", \"HEAD\", \"ref: refs/heads/main\"]\n headSymref = v2.slice(SYMREF_PREFIX.length);\n continue;\n }\n if (refs.size >= MAX_REFS_PER_EVENT) continue;\n refs.set(v1, v2);\n } else if (tagName === 'HEAD' && v1?.startsWith(SYMREF_PREFIX)) {\n // NIP-34 symref tag: [\"HEAD\", \"ref: refs/heads/main\"]\n headSymref = v1.slice(SYMREF_PREFIX.length);\n } else if (tagName === 'arweave' && v1 && v2) {\n shaToTxId.set(v1, v2);\n }\n }\n\n return { refs, headSymref, shaToTxId };\n}\n\n// ---------------------------------------------------------------------------\n// fetchRemoteState\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch the remote repository state from the relay(s).\n *\n * Sends one REQ per relay for kind:30617 + kind:30618 with\n * `authors=[ownerPubkey]`, `#d=[repoId]`, collects until EOSE (or timeout),\n * and reduces to the latest replaceable event per kind.\n *\n * Resolves as long as at least one relay answers; throws only when every\n * relay fails. Events from other authors / repos are ignored (defense\n * against misbehaving relays that over-return).\n */\nexport async function fetchRemoteState(\n options: FetchRemoteStateOptions\n): Promise<RemoteState> {\n const {\n relayUrls,\n ownerPubkey,\n repoId,\n timeoutMs = 10000,\n resolveSha = resolveGitSha,\n webSocketFactory = defaultWebSocketFactory,\n } = options;\n\n if (relayUrls.length === 0) {\n throw new Error('fetchRemoteState: relayUrls must not be empty');\n }\n if (!ownerPubkey) {\n throw new Error('fetchRemoteState: ownerPubkey is required');\n }\n if (!repoId) {\n throw new Error('fetchRemoteState: repoId is required');\n }\n\n const filter: NostrFilter = {\n kinds: [REPOSITORY_ANNOUNCEMENT_KIND, REPOSITORY_STATE_KIND],\n authors: [ownerPubkey],\n '#d': [repoId],\n };\n\n const results = await Promise.allSettled(\n relayUrls.map((url) => queryRelay(url, filter, timeoutMs, webSocketFactory))\n );\n\n const failures: string[] = [];\n const byId = new Map<string, NostrEvent>();\n for (const result of results) {\n if (result.status === 'rejected') {\n failures.push(String((result.reason as Error)?.message ?? result.reason));\n continue;\n }\n for (const event of result.value) {\n // Only trust events from the repo owner for this repo — relays are\n // untrusted and may over-return.\n if (event.pubkey !== ownerPubkey) continue;\n if (getTagValue(event.tags, 'd') !== repoId) continue;\n if (typeof event.id === 'string' && !byId.has(event.id)) {\n byId.set(event.id, event);\n }\n }\n }\n\n if (failures.length === relayUrls.length) {\n throw new Error(\n `fetchRemoteState: all ${relayUrls.length} relay(s) failed: ${failures.join('; ')}`\n );\n }\n\n const events = [...byId.values()];\n const refsEvent = latestReplaceable(\n events.filter((e) => e.kind === REPOSITORY_STATE_KIND)\n );\n const announceEvent = latestReplaceable(\n events.filter((e) => e.kind === REPOSITORY_ANNOUNCEMENT_KIND)\n );\n\n const { refs, headSymref, shaToTxId } = refsEvent\n ? parseRefsEvent(refsEvent)\n : {\n refs: new Map<string, string>(),\n headSymref: null,\n shaToTxId: new Map<string, string>(),\n };\n\n // Seed the shared resolver cache so later resolveGitSha calls (here or in\n // any other consumer of @toon-protocol/arweave) skip GraphQL for known SHAs.\n if (shaToTxId.size > 0) {\n seedShaCache(\n [...shaToTxId].map(\n ([sha, txId]) => [shaCacheKey(sha, repoId), txId] as [string, string]\n )\n );\n }\n\n // Announcement metadata (mirrors views' parseRepoAnnouncement defaults).\n const name = announceEvent\n ? (getTagValue(announceEvent.tags, 'name') ?? null)\n : null;\n const description = announceEvent\n ? (getTagValue(announceEvent.tags, 'description') ?? announceEvent.content)\n : null;\n // NIP-34 announcement relays tag is multi-valued: [\"relays\", url1, url2, …]\n const relays: string[] = [];\n if (announceEvent) {\n for (const tag of announceEvent.tags) {\n if (tag[0] === 'relays') {\n relays.push(...tag.slice(1).filter((url) => url.length > 0));\n }\n }\n }\n // Declared maintainers (#287): the `maintainers` tag on the 30617. Owner is\n // an implicit maintainer and is NOT listed here.\n const maintainers = announceEvent\n ? parseMaintainers(announceEvent.tags)\n : [];\n\n const resolveMissing = async (\n shas: string[]\n ): Promise<Map<string, string>> => {\n const resolved = new Map<string, string>();\n const missing: string[] = [];\n for (const sha of new Set(shas)) {\n const known = shaToTxId.get(sha);\n if (known !== undefined) {\n resolved.set(sha, known);\n } else {\n missing.push(sha);\n }\n }\n const lookups = await Promise.all(\n missing.map(\n async (sha) => [sha, await resolveSha(sha, repoId)] as const\n )\n );\n for (const [sha, txId] of lookups) {\n if (txId) resolved.set(sha, txId);\n }\n return resolved;\n };\n\n return {\n announced: announceEvent !== null,\n refs,\n headSymref,\n shaToTxId,\n refsEvent,\n announceEvent,\n name,\n description,\n relays,\n maintainers,\n resolveMissing,\n };\n}\n",null,null],"mappings":";AASA;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,OACK;AAUA,IAAM,wBAAwB;AAE9B,IAAM,eAAe;AA0BrB,IAAM,kBAAkB;AAE/B,IAAM,QAAQ;AAOP,SAAS,iBAAiB,MAA4B;AAC3D,QAAM,MAAgB,CAAC;AACvB,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAW,OAAO,MAAM;AACtB,QAAI,IAAI,CAAC,MAAM,gBAAiB;AAChC,eAAW,SAAS,IAAI,MAAM,CAAC,GAAG;AAChC,YAAM,MAAM,MAAM,YAAY;AAC9B,UAAI,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,IAAI,GAAG,GAAG;AACrC,aAAK,IAAI,GAAG;AACZ,YAAI,KAAK,GAAG;AAAA,MACd;AAAA,IACF;AAAA,EACF;AACA,SAAO;AACT;AAOO,SAAS,wBACd,aACA,sBACa;AACb,SAAO,oBAAI,IAAI;AAAA,IACb,YAAY,YAAY;AAAA,IACxB,GAAG,iBAAiB,oBAAoB;AAAA,EAC1C,CAAC;AACH;AAcO,SAAS,sBACd,QACA,MACA,aACA,cAAwB,CAAC,GACV;AACf,QAAM,OAAmB;AAAA,IACvB,CAAC,KAAK,MAAM;AAAA,IACZ,CAAC,QAAQ,IAAI;AAAA,IACb,CAAC,eAAe,WAAW;AAAA,EAC7B;AACA,QAAM,WAAqB,CAAC;AAC5B,QAAM,OAAO,oBAAI,IAAY;AAC7B,aAAW,SAAS,aAAa;AAC/B,UAAM,MAAM,MAAM,YAAY;AAC9B,QAAI,MAAM,KAAK,GAAG,KAAK,CAAC,KAAK,IAAI,GAAG,GA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