@miadi/connector 0.1.36 → 0.1.38

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,429 @@
1
+ /**
2
+ * Capabilities in a mission and in its completion (jgwill/Miadi#993, C6 to C10).
3
+ *
4
+ * A mission names the capabilities it reaches: `uses`, `revises`,
5
+ * `brings-into-being`, each by its `miadi-capability://` address, checked against
6
+ * the registry (`@miadi/relational-git-repository-mapper`'s `findCapability`).
7
+ * Its completion names the capabilities its commits changed, read from the
8
+ * commits themselves (`capabilitiesOfCommit` on a clone of the repository) and
9
+ * set against what the mission declared, never from the agent's own account.
10
+ * Approving a completion files the holdings in the episode the mission names.
11
+ *
12
+ * This file holds the pure parts: resolving, comparing, the sentences a person
13
+ * reads before the click, and the missions a capability has. The ledger and the
14
+ * Miadi door are the callers' (tools.ts, approve.ts, Miadi's /research).
15
+ */
16
+ import { z } from "zod";
17
+ import { capabilitiesOfCommit, CommitReadError, findCapability, impactOf, readCapabilities, readPackages } from "@miadi/relational-git-repository-mapper";
18
+ import { capabilityCitation, capabilityPageRoute, parseCapabilityUri } from "@miadi/inquiry-weave/references";
19
+ import { classifyOutput } from "./mission-result.js";
20
+ export const CAPABILITY_RELATIONS = ["uses", "revises", "brings-into-being"];
21
+ export const MAX_CAPABILITIES = 20;
22
+ /** What a tool accepts: the address and how the mission reaches it. */
23
+ export const capabilitiesInput = z
24
+ .array(z.object({
25
+ address: z.string().min(1).max(400).describe("miadi-capability://<owner>/<repo>/<kind>/<name>, as the capability's page and the registry spell it."),
26
+ relation: z.enum(CAPABILITY_RELATIONS).describe("uses: the mission depends on it as it is. revises: its commits change it. brings-into-being: it has no row in the registry yet and the mission makes it."),
27
+ }))
28
+ .max(MAX_CAPABILITIES)
29
+ .describe("The capabilities this mission reaches, up to 20. Each address is checked against the registry: one it does not hold is refused by name and nothing is stored, except under brings-into-being. The person sees them before deciding, and the completion's commits are read against them.");
30
+ /** The key two spellings of one address share: owner and repository are case-folded, as the registry compares them. */
31
+ export function capabilityKey(address) {
32
+ const p = parseCapabilityUri(address);
33
+ return p ? `${p.owner.toLowerCase()}/${p.repo.toLowerCase()}/${p.kind}/${p.name}` : undefined;
34
+ }
35
+ /**
36
+ * Each declared address resolved against the registry. A refusal names the address;
37
+ * the caller stores nothing when any exists. A capability named twice is refused, so
38
+ * a mission says once how it reaches each.
39
+ */
40
+ export function resolveCapabilities(input, find = (parts) => findCapability(parts)) {
41
+ const declared = [];
42
+ const refused = [];
43
+ const seen = new Set();
44
+ for (const item of input) {
45
+ const parsed = parseCapabilityUri(item.address);
46
+ if (!parsed) {
47
+ refused.push({ address: item.address, code: "not_an_address", message: `${item.address} is not miadi-capability://<owner>/<repo>/<kind>/<name>.` });
48
+ continue;
49
+ }
50
+ const key = capabilityKey(item.address);
51
+ const address = capabilityCitation(parsed);
52
+ if (seen.has(key)) {
53
+ refused.push({ address, code: "named_twice", message: `${address} is named twice: say once how the mission reaches it.` });
54
+ continue;
55
+ }
56
+ seen.add(key);
57
+ let held = false;
58
+ let registered;
59
+ let unreadable;
60
+ try {
61
+ const found = find({ owner: parsed.owner, repo: parsed.repo, kind: parsed.kind, name: parsed.name });
62
+ held = Boolean(found);
63
+ // The registry's own spelling is what an episode keys a holding by and a capability's page matches holders by.
64
+ registered = found?.capability?.address;
65
+ }
66
+ catch (error) {
67
+ unreadable = error instanceof Error ? error.message : String(error);
68
+ }
69
+ if (!held && item.relation !== "brings-into-being") {
70
+ refused.push(unreadable !== undefined
71
+ ? { address, code: "registry_unreadable", message: `The registry could not be read, so ${address} is not checked: ${unreadable}` }
72
+ : { address, code: "not_in_registry", message: `The registry holds no row for ${address}. Name it as brings-into-being if the mission makes it, or correct the address.` });
73
+ continue;
74
+ }
75
+ declared.push({ address: registered ?? address, relation: item.relation, kind: parsed.kind, name: parsed.name, in_registry: held });
76
+ }
77
+ return { declared, refused };
78
+ }
79
+ /** The declared capabilities a request record stores, read back tolerantly. */
80
+ export function declaredOf(record) {
81
+ const raw = record?.body?.capabilities;
82
+ if (!Array.isArray(raw))
83
+ return [];
84
+ const out = [];
85
+ for (const c of raw) {
86
+ const r = c;
87
+ if (!r || typeof r.address !== "string" || !CAPABILITY_RELATIONS.includes(r.relation))
88
+ continue;
89
+ const p = parseCapabilityUri(r.address);
90
+ if (!p)
91
+ continue;
92
+ out.push({ address: capabilityCitation(p), relation: r.relation, kind: p.kind, name: p.name, in_registry: r.in_registry !== false });
93
+ }
94
+ return out;
95
+ }
96
+ /** The brief's line for the worker: how the mission reaches each capability. Undefined when it names none. */
97
+ export function capabilitiesLine(declared) {
98
+ return declared.length ? declared.map((d) => `${d.relation.replace(/-/g, " ")} ${d.address}${d.in_registry ? "" : " (no row yet)"}`).join(", ") : undefined;
99
+ }
100
+ export function routeOf(address) {
101
+ const p = parseCapabilityUri(address);
102
+ return p ? capabilityPageRoute(p) : undefined;
103
+ }
104
+ /** Each declared capability as a chip: its page, its relation and, for a revised package, its dependents. */
105
+ export function chipsOf(declared, o = {}) {
106
+ let packages;
107
+ const read = () => (packages ??= (o.packages ?? (() => readPackages().packages))());
108
+ return declared.flatMap((d) => {
109
+ const parts = parseCapabilityUri(d.address);
110
+ if (!parts)
111
+ return [];
112
+ const chip = { address: d.address, relation: d.relation, kind: d.kind, name: d.name, route: capabilityPageRoute(parts), in_registry: d.in_registry };
113
+ if (d.kind === "package" && d.relation === "revises" && d.in_registry) {
114
+ try {
115
+ const all = read();
116
+ const repository = `repository:${parts.owner}/${parts.repo}`.toLowerCase();
117
+ const own = all.find((p) => p.name === d.name && p.repository.toLowerCase() === repository);
118
+ const impact = own ? impactOf(d.name, [...all], "minor", { repository: own.repository }) : undefined;
119
+ if (impact)
120
+ chip.dependents = impact.consumers.length;
121
+ }
122
+ catch {
123
+ // dependents are an aid: a registry that cannot answer leaves the chip without them
124
+ }
125
+ }
126
+ return [chip];
127
+ });
128
+ }
129
+ const SHA = /^[0-9a-f]{7,40}$/i;
130
+ const OWNER_REPO_SHA = /^([\w.-]+)\/([\w.-]+)@([0-9a-f]{7,40})$/i;
131
+ const EVIDENCE_OK = /^[^\s\u0000-\u001f\u007f-\u009f]{1,200}$/;
132
+ const VERSION_OK = /^[0-9A-Za-z][0-9A-Za-z.+-]{0,63}$/;
133
+ const GITHUB_COMMIT = /^https:\/\/github\.com\/([\w.-]+)\/([\w.-]+)\/(?:pull\/\d+\/)?commits?\/([0-9a-f]{7,40})\/?$/i;
134
+ const GITHUB_PULL = /^https:\/\/github\.com\/[\w.-]+\/[\w.-]+\/pull\/\d+\/?$/i;
135
+ /** A reference without its query or fragment. */
136
+ const bare = (ref) => ref.trim().split(/[#?]/)[0] ?? "";
137
+ /** The outputs that name a commit: a commit URL (also one inside a pull request), `owner/repo@sha`, or a pull request or issue with the commit's sha in `git_sha`. A file's blob sha names no commit. */
138
+ export function commitOutputsOf(outputs) {
139
+ const out = [];
140
+ const seen = new Set();
141
+ for (const o of outputs) {
142
+ const ref = bare(o.ref ?? "");
143
+ let found;
144
+ const explicit = OWNER_REPO_SHA.exec(ref);
145
+ const url = GITHUB_COMMIT.exec(ref);
146
+ if (explicit)
147
+ found = { repository: `${explicit[1]}/${explicit[2]}`, sha: explicit[3] };
148
+ else if (url)
149
+ found = { repository: `${url[1]}/${url[2]}`, sha: url[3] };
150
+ else {
151
+ const c = classifyOutput(ref);
152
+ if (c.type === "commit" && c.repository && c.commit)
153
+ found = { repository: c.repository, sha: c.commit };
154
+ else if (c.type === "issue_or_pr" && c.repository && o.git_sha && SHA.test(o.git_sha))
155
+ found = { repository: c.repository, sha: o.git_sha };
156
+ }
157
+ if (!found)
158
+ continue;
159
+ const key = `${found.repository.toLowerCase()}@${found.sha.slice(0, 7).toLowerCase()}`;
160
+ if (seen.has(key))
161
+ continue;
162
+ seen.add(key);
163
+ out.push({ ref: o.ref, ...found });
164
+ }
165
+ return out;
166
+ }
167
+ /** Where each repository's clone lives on this host: `MIADI_CONNECTOR_CLONES="owner/repo=/path,…"`; jgwill/Miadi defaults to `MIADI_SRC`, else the service's working folder. */
168
+ export function clonesFromEnv(env = process.env) {
169
+ const map = new Map();
170
+ const fallback = env.MIADI_SRC?.trim() || process.cwd();
171
+ map.set("jgwill/miadi", fallback);
172
+ for (const pair of (env.MIADI_CONNECTOR_CLONES ?? "").split(",")) {
173
+ const at = pair.indexOf("=");
174
+ if (at > 0 && pair.slice(at + 1).trim())
175
+ map.set(pair.slice(0, at).trim().toLowerCase(), pair.slice(at + 1).trim());
176
+ }
177
+ return (repository) => map.get(repository.toLowerCase());
178
+ }
179
+ const REASONS = {
180
+ "not-a-commit-ref": "the reference is not owner/repo@sha",
181
+ "clone-not-of-repository": "the host's clone has an origin that names another repository",
182
+ "commit-not-in-clone": "the host's clone does not hold the commit",
183
+ "merge-commit": "the commit is a merge, which counts everything it brought in as its own",
184
+ "not-on-origin": "no origin branch holds the commit yet: push it, then submit again",
185
+ "too-many": "more commits were named than one submission reads",
186
+ };
187
+ /** One submission reads at most this many commits: each is a handful of git calls on this host. */
188
+ export const MAX_COMMITS_READ = 10;
189
+ /** A version as numbers, for choosing the newest of several. */
190
+ const versionParts = (v) => (v.match(/\d+/g) ?? []).map(Number);
191
+ const newerVersion = (a, b) => {
192
+ const x = versionParts(a);
193
+ const y = versionParts(b);
194
+ for (let i = 0; i < Math.max(x.length, y.length); i++)
195
+ if ((x[i] ?? 0) !== (y[i] ?? 0))
196
+ return (x[i] ?? 0) > (y[i] ?? 0);
197
+ return false;
198
+ };
199
+ /**
200
+ * What the commits of a completion changed, set against what its mission declared.
201
+ * Undefined when no output names a commit. Each commit is read by the mapper from the
202
+ * clone; a commit it cannot read is `unread` with the reason, and the comparison says
203
+ * it is not whole.
204
+ */
205
+ export async function readChangedCapabilities(i) {
206
+ const named = commitOutputsOf(i.outputs);
207
+ if (!named.length)
208
+ return undefined;
209
+ let rows;
210
+ const readCommit = i.readCommit ?? ((ref, clone) => capabilitiesOfCommit(ref, clone, { rows: (rows ??= readCapabilities().capabilities), onOrigin: true }));
211
+ // Each commit is a handful of git calls made synchronously: between commits the event loop is given back, so a long
212
+ // list never holds every other request of the connector for its whole length.
213
+ const readings = [];
214
+ for (const [index, c] of named.entries()) {
215
+ if (index > 0)
216
+ await new Promise((resolve) => setImmediate(resolve));
217
+ readings.push(readOne(c, index));
218
+ }
219
+ function readOne(c, index) {
220
+ const commit = `${c.repository}@${c.sha}`;
221
+ if (index >= MAX_COMMITS_READ)
222
+ return { ref: c.ref, commit, state: "unread", reason_code: "too-many", reason: REASONS["too-many"], capabilities: [] };
223
+ const clone = i.clones(c.repository);
224
+ if (!clone)
225
+ return { ref: c.ref, commit, state: "unread", reason_code: "no-clone", reason: `this host holds no clone of ${c.repository}`, capabilities: [] };
226
+ try {
227
+ const r = readCommit(commit, clone);
228
+ const capabilities = r.capabilities.map((x) => ({
229
+ address: x.address,
230
+ kind: x.kind,
231
+ name: x.name,
232
+ ...(x.version ? { version: x.version } : {}),
233
+ ...(x.versionChanged ? { version_changed: true } : {}),
234
+ files: x.files,
235
+ }));
236
+ return {
237
+ ref: c.ref,
238
+ commit,
239
+ sha: r.sha,
240
+ state: capabilities.length ? "read" : "no capability row",
241
+ ...(r.skipped ? { skipped: r.skipped } : {}),
242
+ files: r.files.length,
243
+ capabilities,
244
+ };
245
+ }
246
+ catch (error) {
247
+ if (error instanceof CommitReadError)
248
+ return { ref: c.ref, commit, state: "unread", reason_code: error.code, reason: REASONS[error.code] ?? error.code, capabilities: [] };
249
+ return { ref: c.ref, commit, state: "unread", reason_code: "read-failed", reason: "the commit could not be read", capabilities: [] };
250
+ }
251
+ }
252
+ // What the read commits changed, by capability. A version is filed only from a commit that moved it: the release this change shipped in.
253
+ const changed = new Map();
254
+ for (const r of readings) {
255
+ if (r.state !== "read")
256
+ continue;
257
+ const short = `${r.commit.split("@")[0]}@${(r.sha ?? r.commit.split("@")[1]).slice(0, 12)}`;
258
+ for (const c of r.capabilities) {
259
+ const key = capabilityKey(c.address);
260
+ if (!key)
261
+ continue;
262
+ const held = changed.get(key) ?? { address: c.address, commits: [] };
263
+ if (!held.commits.includes(short))
264
+ held.commits.push(short);
265
+ if (c.version_changed && c.version && VERSION_OK.test(c.version) && (!held.version || newerVersion(c.version, held.version)))
266
+ held.version = c.version;
267
+ changed.set(key, held);
268
+ }
269
+ }
270
+ const declared = declaredOf(i.mission);
271
+ const declaredKeys = new Map(declared.map((d) => [capabilityKey(d.address), d]));
272
+ const flagged = (d) => ({ address: d.address, relation: d.relation, ...(d.in_registry ? {} : { in_registry: false }) });
273
+ const declared_and_changed = declared.filter((d) => changed.has(capabilityKey(d.address))).map(flagged);
274
+ const declared_not_changed = declared.filter((d) => !changed.has(capabilityKey(d.address))).map(flagged);
275
+ const changed_not_declared = [...changed.entries()].filter(([k]) => !declaredKeys.has(k)).map(([, v]) => ({ address: v.address }));
276
+ // The one episode the mission names, and what approving files in it. A bare miadi-chronicle://<n> only: a file of an episode is not the episode.
277
+ const episodes = [...new Set((i.mission?.refs ?? []).map((r) => /^miadi-chronicle:(?:\/\/)?(\d+)\/?$/.exec(r.trim())?.[1]).filter((n) => Boolean(n)))];
278
+ const allowed = i.filing?.allowed ?? true;
279
+ const episode = allowed && episodes.length === 1 ? `miadi-chronicle://${episodes[0]}` : undefined;
280
+ const episode_note = !allowed
281
+ ? (i.filing?.reason ?? "this submission is not verified as the mission's result")
282
+ : !i.mission
283
+ ? i.missionId
284
+ ? "the mission this completion names is not in the ledger, so no episode"
285
+ : "the completion names no mission, so no episode"
286
+ : episodes.length === 0
287
+ ? "the mission names no episode"
288
+ : episodes.length > 1
289
+ ? `the mission names ${episodes.length} episodes (${episodes.map((n) => `miadi-chronicle://${n}`).join(", ")}): none is chosen for it`
290
+ : undefined;
291
+ const session = EVIDENCE_OK.test(`session:${i.sessionId}`) ? [`session:${i.sessionId.replace(/^session:/, "")}`] : [];
292
+ const holdings = [];
293
+ const not_filed = [];
294
+ if (episode) {
295
+ for (const [key, c] of changed) {
296
+ const d = declaredKeys.get(key);
297
+ holdings.push({
298
+ capability: c.address,
299
+ relation: d?.relation === "brings-into-being" ? "brings-into-being" : "revises",
300
+ ...(c.version ? { version: c.version } : {}),
301
+ evidence: [...c.commits, ...session],
302
+ basis: "changed",
303
+ });
304
+ }
305
+ for (const d of declared) {
306
+ if (changed.has(capabilityKey(d.address)))
307
+ continue;
308
+ // A revision or a creation no read commit shows is claimed by the agent alone: it is listed, never filed.
309
+ if (d.relation === "uses")
310
+ holdings.push({ capability: d.address, relation: "uses", evidence: session, basis: "declared" });
311
+ else
312
+ not_filed.push({ address: d.address, relation: d.relation, ...(d.in_registry ? {} : { in_registry: false }) });
313
+ }
314
+ }
315
+ const wholeChange = i.outputs.some((o) => GITHUB_PULL.test(bare(o.ref ?? "")));
316
+ return {
317
+ read_at: (i.now?.() ?? new Date()).toISOString(),
318
+ ...(i.mission ? { mission: i.mission.id } : i.missionId ? { mission: i.missionId } : {}),
319
+ commits: readings,
320
+ complete: readings.every((r) => r.state !== "unread") && !wholeChange,
321
+ ...(wholeChange ? { partial_reason: "A pull request names its commits through GitHub, which this does not consult: only the commits named one by one were read." } : {}),
322
+ declared_and_changed,
323
+ declared_not_changed,
324
+ changed_not_declared,
325
+ ...(episode ? { episode } : {}),
326
+ ...(episode_note ? { episode_note } : {}),
327
+ holdings,
328
+ not_filed,
329
+ };
330
+ }
331
+ /** The stored `changed_capabilities` of a completion record, when it has a readable one. */
332
+ export function changedOf(record) {
333
+ const c = record?.body?.changed_capabilities;
334
+ return c && Array.isArray(c.commits) && Array.isArray(c.holdings) ? c : undefined;
335
+ }
336
+ const nameOf = (address) => parseCapabilityUri(address)?.name ?? address;
337
+ /** One sentence: what approving files in the episode, before the person clicks. Empty when nothing is filed. */
338
+ export function holdingsSentence(changed) {
339
+ if (!changed || !changed.episode || !changed.holdings.length)
340
+ return "";
341
+ const list = changed.holdings.map((h) => `${h.relation.replace(/-/g, " ")} ${nameOf(h.capability)}${h.version ? ` ${h.version}` : ""}`).join(", ");
342
+ const n = changed.holdings.length;
343
+ const commits = changed.holdings.some((h) => h.basis === "changed");
344
+ const skipped = changed.not_filed.length ? ` ${changed.not_filed.map((x) => nameOf(x.address)).join(", ")} ${changed.not_filed.length === 1 ? "is" : "are"} declared but shown by no commit, so not filed.` : "";
345
+ return `Approving also files ${n} capability holding${n === 1 ? "" : "s"} in ${changed.episode} (${list}), each with the session as evidence${commits ? " and, where a commit changed it, that commit" : ""}.${skipped}${changed.complete ? "" : " Some commits could not be read, so a capability they changed is not in this list."}`;
346
+ }
347
+ /** What approving a completion does, for the card, the approval page and /research. */
348
+ export function completionEffect(record, base) {
349
+ const more = holdingsSentence(changedOf(record));
350
+ return more ? `${base} ${more}` : base;
351
+ }
352
+ const titleOfRecord = (r) => {
353
+ const b = r.body;
354
+ const text = (v) => (typeof v === "string" && v.trim() ? v.replace(/\s+/g, " ").trim().slice(0, 140) : "");
355
+ return text(b.title) || (r.kind === "session_completion_proposal" ? text(b.reason) : "") || text(b.task) || r.kind.replace(/_/g, " ");
356
+ };
357
+ /** The connector's records that declared or changed one capability, newest first, each with its approval state. */
358
+ export function missionsOfCapability(records, address) {
359
+ const key = capabilityKey(address);
360
+ if (!key)
361
+ return [];
362
+ const out = [];
363
+ for (const r of records) {
364
+ if (r.kind === "run_request" || r.kind === "work_proposal") {
365
+ const d = declaredOf(r).find((x) => capabilityKey(x.address) === key);
366
+ if (d)
367
+ out.push({ record: r.id, kind: r.kind, title: titleOfRecord(r), approval_state: r.approval_state ?? "awaiting_approval", ...(r.state ? { state: r.state } : {}), at: r.created_at, declared: d.relation });
368
+ }
369
+ else if (r.kind === "session_completion_proposal") {
370
+ const c = changedOf(r);
371
+ if (c?.commits.some((x) => x.capabilities.some((y) => capabilityKey(y.address) === key))) {
372
+ out.push({ record: r.id, kind: r.kind, title: titleOfRecord(r), approval_state: r.approval_state ?? "awaiting_approval", ...(r.state ? { state: r.state } : {}), at: r.created_at, changed: true, ...(c.mission ? { mission: c.mission } : {}) });
373
+ }
374
+ }
375
+ }
376
+ return out.sort((a, b) => b.at.localeCompare(a.at));
377
+ }
378
+ /** The three lists of a completion as chips, each with its page. */
379
+ export function changedViewOf(changed) {
380
+ const chip = (address, relation, registered) => {
381
+ const p = parseCapabilityUri(address);
382
+ return p ? { address, relation: relation ?? "revises", kind: p.kind, name: p.name, route: capabilityPageRoute(p), in_registry: registered !== false } : undefined;
383
+ };
384
+ const chips = (list) => list.flatMap((x) => chip(x.address, x.relation, x.in_registry) ?? []);
385
+ return {
386
+ commits: changed.commits,
387
+ complete: changed.complete,
388
+ declared_and_changed: chips(changed.declared_and_changed),
389
+ declared_not_changed: chips(changed.declared_not_changed),
390
+ changed_not_declared: chips(changed.changed_not_declared),
391
+ ...(changed.episode ? { episode: changed.episode } : {}),
392
+ ...(changed.episode_note ? { episode_note: changed.episode_note } : {}),
393
+ holdings: changed.holdings,
394
+ not_filed: chips(changed.not_filed),
395
+ ...(changed.partial_reason ? { partial_reason: changed.partial_reason } : {}),
396
+ };
397
+ }
398
+ /** A door's error as words a person below the write tier may read: a file path on this host is cut. */
399
+ export const plainDoorMessage = (text) => text.replace(/(?<![\w:/.])\/(?:srv|home|a|src|tmp|var|workspace|g|opt|usr|etc)\/[^\s'"),;]+/g, "…");
400
+ /**
401
+ * Files each holding through POST /api/chronicle/episodes/<ref>/capabilities, one by one: the door
402
+ * lands each in the chronicle. `post` is the approver's own call to Miadi, so Miadi applies their
403
+ * permissions. A holding the door refuses is reported, the rest still land. The door answers 201 with
404
+ * `ok: false` when the holding is written and the wheel's node or edge is still pending: that is not landed,
405
+ * so the decision can be run again.
406
+ */
407
+ export async function landHoldings(changed, post) {
408
+ const number = changed.episode ? /(\d+)$/.exec(changed.episode)?.[1] : undefined;
409
+ if (!number || !changed.holdings.length)
410
+ return { ...(changed.episode ? { episode: changed.episode } : {}), landed: [], failed: [] };
411
+ const landed = [];
412
+ const failed = [];
413
+ for (const h of changed.holdings) {
414
+ const base = { capability: h.capability, relation: h.relation, ...(h.version ? { version: h.version } : {}) };
415
+ try {
416
+ const answer = (await post(`/api/chronicle/episodes/${number}/capabilities`, { capability: h.capability, relation: h.relation, ...(h.version ? { version: h.version } : {}), evidence: h.evidence }));
417
+ if (answer && answer.ok === false)
418
+ failed.push({ ...base, ok: false, message: "the door wrote the holding and its wheel node or edge is still pending" });
419
+ else
420
+ landed.push({ ...base, ok: true });
421
+ }
422
+ catch (error) {
423
+ const status = error.status;
424
+ const body = error.body;
425
+ failed.push({ ...base, ok: false, ...(typeof status === "number" ? { status } : {}), message: plainDoorMessage(body?.message ?? body?.error ?? (error instanceof Error ? error.message : String(error))) });
426
+ }
427
+ }
428
+ return { episode: changed.episode, landed, failed };
429
+ }
@@ -2,9 +2,9 @@
2
2
  * A transcription made on this host, for a video whose captions are missing (jgwill/Miadi#995).
3
3
  *
4
4
  * It is the second reader a transcript job tries, after YouTube's captions, and only where the host's
5
- * operator enabled it (`MIADI_TRANSCRIPT_LOCAL=faster-whisper`) and the source is released: it downloads the
6
- * video's audio, which a withheld or unregistered source does not allow. It calls no model service and costs
7
- * no money. The resources are bounded: one transcription at a time, a longest video
5
+ * operator enabled it (`MIADI_TRANSCRIPT_LOCAL=faster-whisper`). It downloads the video's audio, which a
6
+ * withheld source does not allow: the job holds such a source before it reaches this reader. It calls no
7
+ * model service and costs no money. The resources are bounded: one transcription at a time, a longest video
8
8
  * (`MIADI_TRANSCRIPT_LOCAL_MAX_MINUTES`, default 90) and a time limit.
9
9
  */
10
10
  import { execFile } from "node:child_process";
@@ -128,6 +128,21 @@ export declare function classifyOutput(ref: string): Omit<MissionOutput, "check"
128
128
  * The result a mission's agent submitted, checked. `boundSessions` are the Claude
129
129
  * Code session ids the mission is bound to (empty when the viewer may not see them).
130
130
  */
131
+ /**
132
+ * Whether a submission is verified: it names the mission, ends one of the sessions the mission is bound to,
133
+ * and was made with the write tier. The one rule `missionResult` reads a result by, and the one a completion's
134
+ * capability holdings are filed by (jgwill/Miadi#993): a session id is a field anyone can type (#922 R3).
135
+ */
136
+ export declare function associationOf(i: {
137
+ names: boolean;
138
+ sessionId: string;
139
+ boundSessions: ReadonlySet<string>;
140
+ writeTier: boolean;
141
+ }): {
142
+ association: ResultSubmission["association"];
143
+ code?: AssociationReason;
144
+ };
145
+ export declare const ASSOCIATION_REASON_TEXT: Record<AssociationReason, string>;
131
146
  export declare function missionResult(mission: ConnectorRecord, records: ConnectorRecord[], boundSessions: Set<string>, deps?: MissionResultDeps): Promise<MissionResult>;
132
147
  /** Endings made before 0.1.16 carry no recorded tier; from this time on every ending carries one (#922 R18). */
133
148
  export declare const TIER_RECORDED_SINCE = "2026-11-05T00:00:00.000Z";
@@ -133,6 +133,23 @@ async function checkOutput(out, ctx) {
133
133
  * The result a mission's agent submitted, checked. `boundSessions` are the Claude
134
134
  * Code session ids the mission is bound to (empty when the viewer may not see them).
135
135
  */
136
+ /**
137
+ * Whether a submission is verified: it names the mission, ends one of the sessions the mission is bound to,
138
+ * and was made with the write tier. The one rule `missionResult` reads a result by, and the one a completion's
139
+ * capability holdings are filed by (jgwill/Miadi#993): a session id is a field anyone can type (#922 R3).
140
+ */
141
+ export function associationOf(i) {
142
+ if (!i.names)
143
+ return { association: "cited_only", code: "cited_only" };
144
+ if (!i.boundSessions.size)
145
+ return { association: "unverified_association", code: "no_binding" };
146
+ if (!i.sessionId || !i.boundSessions.has(i.sessionId))
147
+ return { association: "unverified_association", code: "not_bound_session" };
148
+ if (!i.writeTier)
149
+ return { association: "unverified_association", code: "submitter_below_write_tier" };
150
+ return { association: "verified" };
151
+ }
152
+ export const ASSOCIATION_REASON_TEXT = REASON_TEXT;
136
153
  export async function missionResult(mission, records, boundSessions, deps = {}) {
137
154
  const now = deps.now?.() ?? new Date();
138
155
  const notes = [];
@@ -145,27 +162,7 @@ export async function missionResult(mission, records, boundSessions, deps = {})
145
162
  if (!names && !cites)
146
163
  continue;
147
164
  const sessionId = str(b.session_id).replace(/^session:/, "");
148
- let association;
149
- let code;
150
- if (!names) {
151
- association = "cited_only";
152
- code = "cited_only";
153
- }
154
- else if (!boundSessions.size) {
155
- association = "unverified_association";
156
- code = "no_binding";
157
- }
158
- else if (!sessionId || !boundSessions.has(sessionId)) {
159
- association = "unverified_association";
160
- code = "not_bound_session";
161
- }
162
- else if (!(deps.submittedWithWriteTier ?? submittedWithWriteTier)(r)) {
163
- association = "unverified_association";
164
- code = "submitter_below_write_tier";
165
- }
166
- else {
167
- association = "verified";
168
- }
165
+ const { association, code } = associationOf({ names, sessionId, boundSessions, writeTier: (deps.submittedWithWriteTier ?? submittedWithWriteTier)(r) });
169
166
  const receipt = (r.completion_receipt ?? {});
170
167
  submissions.push({
171
168
  r,
@@ -0,0 +1,48 @@
1
+ /**
2
+ * A connector record shared through a talking circle or with one person: the rule jgwill/Miadi#1005 gives a
3
+ * shelf report, for a record (an inquiry, a handoff, a proposal).
4
+ *
5
+ * A share is a `link` record its author makes, from the record, to `miadi-circle:<circle id>` (or the bare
6
+ * `circle:<id>`) or a person's node id, with the relation `shared_with`. A later link from the author with
7
+ * the relation `share_withdrawn`, from the same record to the same reader, ends it. The ledger keeps both, so
8
+ * who shared what with whom, and when it ended, stays readable. A link anyone else makes shares nothing: the
9
+ * author decides each share.
10
+ *
11
+ * Ref: jgwill/Miadi#1005, jgwill/Miadi#879
12
+ */
13
+ import type { ConnectorRecord } from "./records.js";
14
+ export declare const SHARE_RELATION = "shared_with";
15
+ export declare const WITHDRAW_RELATION = "share_withdrawn";
16
+ export interface RecordShare {
17
+ /** The person's node id or the talking circle's id, as the share names it. */
18
+ to: string;
19
+ person_id?: string;
20
+ circle?: string;
21
+ /** Who shared it, and when: the author, by name. */
22
+ by: string;
23
+ at: string;
24
+ /** The link record that made the share. */
25
+ link: string;
26
+ }
27
+ export interface RecordReader {
28
+ id: string;
29
+ api_tier?: string | null;
30
+ /** The talking circles the reader sits in now; read only when a record is shared with a circle. */
31
+ circles?: Iterable<string>;
32
+ }
33
+ export interface RecordAccess {
34
+ as: "author" | "shared" | "read_tier";
35
+ /** For a share: every share that reaches this reader. */
36
+ routes: RecordShare[];
37
+ }
38
+ /** Whom a share link names: a talking circle or a person, else nobody. */
39
+ export declare function shareTarget(to: string): {
40
+ person_id?: string;
41
+ circle?: string;
42
+ } | null;
43
+ export declare function isShareRelation(relation: unknown): boolean;
44
+ /** The shares of a record that stand now, oldest first. */
45
+ export declare function recordShares(record: ConnectorRecord, ledger: readonly ConnectorRecord[]): RecordShare[];
46
+ export declare function recordSharedWithACircle(record: ConnectorRecord, ledger: readonly ConnectorRecord[]): boolean;
47
+ /** How a reader may read a record: as its author, through a share (each one named), or with Miadi's read tier; null when not at all. */
48
+ export declare function recordAccess(record: ConnectorRecord, ledger: readonly ConnectorRecord[], reader: RecordReader): RecordAccess | null;
@@ -0,0 +1,60 @@
1
+ /**
2
+ * A connector record shared through a talking circle or with one person: the rule jgwill/Miadi#1005 gives a
3
+ * shelf report, for a record (an inquiry, a handoff, a proposal).
4
+ *
5
+ * A share is a `link` record its author makes, from the record, to `miadi-circle:<circle id>` (or the bare
6
+ * `circle:<id>`) or a person's node id, with the relation `shared_with`. A later link from the author with
7
+ * the relation `share_withdrawn`, from the same record to the same reader, ends it. The ledger keeps both, so
8
+ * who shared what with whom, and when it ended, stays readable. A link anyone else makes shares nothing: the
9
+ * author decides each share.
10
+ *
11
+ * Ref: jgwill/Miadi#1005, jgwill/Miadi#879
12
+ */
13
+ export const SHARE_RELATION = "shared_with";
14
+ export const WITHDRAW_RELATION = "share_withdrawn";
15
+ /** Whom a share link names: a talking circle or a person, else nobody. */
16
+ export function shareTarget(to) {
17
+ const t = to.trim().replace(/^miadi-circle:(?:\/\/)?/i, "");
18
+ if (/^circle:[A-Za-z0-9._~:-]+$/.test(t))
19
+ return { circle: t };
20
+ if (/^(?:node:)?(?:human|agent|person)[:A-Za-z0-9._~-]*$/.test(t) && t.includes(":"))
21
+ return { person_id: t };
22
+ return null;
23
+ }
24
+ export function isShareRelation(relation) {
25
+ return relation === SHARE_RELATION || relation === WITHDRAW_RELATION;
26
+ }
27
+ /** The shares of a record that stand now, oldest first. */
28
+ export function recordShares(record, ledger) {
29
+ const active = new Map();
30
+ const links = ledger
31
+ .filter((l) => l.kind === "link" && l.actor?.person_id === record.actor?.person_id && l.body?.from === record.id)
32
+ .sort((a, b) => a.created_at.localeCompare(b.created_at));
33
+ for (const l of links) {
34
+ const b = l.body;
35
+ const who = typeof b.to === "string" ? shareTarget(b.to) : null;
36
+ if (!who)
37
+ continue;
38
+ const key = who.circle ?? who.person_id;
39
+ if (b.relation === SHARE_RELATION)
40
+ active.set(key, { to: key, ...who, by: l.actor.name, at: l.created_at, link: l.id });
41
+ else if (b.relation === WITHDRAW_RELATION)
42
+ active.delete(key);
43
+ }
44
+ return [...active.values()];
45
+ }
46
+ export function recordSharedWithACircle(record, ledger) {
47
+ return recordShares(record, ledger).some((s) => s.circle);
48
+ }
49
+ /** How a reader may read a record: as its author, through a share (each one named), or with Miadi's read tier; null when not at all. */
50
+ export function recordAccess(record, ledger, reader) {
51
+ if (record.actor?.person_id === reader.id)
52
+ return { as: "author", routes: [] };
53
+ const circles = new Set(reader.circles ?? []);
54
+ const routes = recordShares(record, ledger).filter((s) => s.person_id === reader.id || (s.circle !== undefined && circles.has(s.circle)));
55
+ if (routes.length)
56
+ return { as: "shared", routes };
57
+ if (reader.api_tier)
58
+ return { as: "read_tier", routes: [] };
59
+ return null;
60
+ }