@miadi/connector 0.1.35 → 0.1.37

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.
@@ -2,10 +2,11 @@
2
2
  * Reading what is on the inquiry shelf (jgwill/Miadi#879). save_research and the agents who work
3
3
  * on the shelf write here, and this reads it back from a later conversation without another mission.
4
4
  *
5
- * Who may read: the folder's owner, or Miadi's write tier. That is the same rule the shelf's other
6
- * doors keep, and a folder with no owner recorded is the write tier's alone. No one has defined who
7
- * sits in a circle for `visibility: circle`, so sharing with a circle admits no one new until that
8
- * is decided.
5
+ * Who may read: the folder's owner, a person the owner shared it with, a member of a talking circle
6
+ * the owner shared it with (for as long as they sit in it), or Miadi's write tier. A folder with no
7
+ * owner recorded is the write tier's alone. The legacy `visibility: circle` names one of the five
8
+ * accountable circles and admits no one; shares do (jgwill/Miadi#1005). Each answer says by which
9
+ * route the reader was admitted.
9
10
  *
10
11
  * What can be read: the text files the episode doors read, by their path in the folder. Hidden
11
12
  * paths, links, and anything outside the folder are never served. Each answer says whether the
@@ -16,7 +17,7 @@ import { createHash } from "node:crypto";
16
17
  import { existsSync, lstatSync, readdirSync, readFileSync, realpathSync, statSync } from "node:fs";
17
18
  import { join, relative, sep } from "node:path";
18
19
  import { promisify } from "node:util";
19
- import { artefactVisibility, readArtefactWeave } from "@miadi/inquiry-weave";
20
+ import { activeShares, artefactVisibility, readArtefactWeave } from "@miadi/inquiry-weave";
20
21
  import { FileRefusal, checkRelativePath, extensionOf, pageOf, TEXT_TYPES } from "./episode-files.js";
21
22
  import { digestReport, folderTitle } from "./research-digest.js";
22
23
  const run = promisify(execFile);
@@ -32,13 +33,51 @@ export class ShelfRefusal extends Error {
32
33
  this.code = code;
33
34
  }
34
35
  }
35
- /** Who may read a folder. `weave` is undefined for a folder no one saved through a door. */
36
+ const routeOf = (s) => ({
37
+ via: s.circle ? "circle" : "person",
38
+ ...(s.circle ? { circle: s.circle, ...(s.name ? { circle_name: s.name } : {}) } : {}),
39
+ by: { person_id: s.by.person_id, ...(s.by.name ? { name: s.by.name } : {}) },
40
+ at: s.at,
41
+ });
42
+ /** Whether a folder is shared with a circle, so its reader's circles are worth reading. */
43
+ export function sharedWithACircle(weave) {
44
+ return activeShares(weave).some((s) => s.circle);
45
+ }
46
+ /** How a reader is admitted to a folder, or null. Direct shares come before circle shares. `weave` is undefined for a folder no one saved through a door. */
47
+ export function shelfAccess(weave, reader) {
48
+ if (weave?.owner?.person_id === reader.id)
49
+ return { as: "owner", routes: [] };
50
+ const circles = new Set(reader.circles ?? []);
51
+ const shares = activeShares(weave);
52
+ const routes = [...shares.filter((s) => s.person_id === reader.id), ...shares.filter((s) => s.circle && circles.has(s.circle))].map(routeOf);
53
+ if (routes.length)
54
+ return { as: "shared", routes };
55
+ if (reader.api_tier === "write")
56
+ return { as: "write_tier", routes: [] };
57
+ return null;
58
+ }
59
+ /** Who may read a folder. */
36
60
  export function canReadShelf(weave, person) {
37
- if (person.api_tier === "write")
38
- return true;
39
- if (!weave)
40
- return false;
41
- return weave.owner?.person_id === person.id;
61
+ return shelfAccess(weave, person) !== null;
62
+ }
63
+ /**
64
+ * The reader with their circles read, when a folder needs them and the door can read them. The write
65
+ * tier reads every folder, so for it the circles only name the route: when they cannot be read it is
66
+ * still admitted, as the write tier, unless `strict` (listing what is shared with them, where the
67
+ * circles are the whole answer).
68
+ */
69
+ async function withCircles(reader, weave, load, strict = false) {
70
+ if (reader.circles || !load || !sharedWithACircle(weave) || weave?.owner?.person_id === reader.id)
71
+ return reader;
72
+ if (reader.api_tier === "write" && !strict) {
73
+ try {
74
+ return { ...reader, circles: await load() };
75
+ }
76
+ catch {
77
+ return { ...reader, circles: [] };
78
+ }
79
+ }
80
+ return { ...reader, circles: await load() };
42
81
  }
43
82
  function folderOf(root, name) {
44
83
  if (!/^[\w.-]+$/.test(name) || name.startsWith("."))
@@ -136,13 +175,17 @@ function defaultFile(files, saved) {
136
175
  export async function readShelfArtefact(root, name, person, opts = {}) {
137
176
  const dir = folderOf(root, name);
138
177
  const weave = await readArtefactWeave(dir).catch(() => undefined);
139
- if (!canReadShelf(weave, person)) {
140
- throw new ShelfRefusal("forbidden", weave ? "That folder belongs to another person. Its owner or a person with Miadi's write tier can read it." : "No owner is recorded for that folder, so only a person with Miadi's write tier can read it.");
178
+ const access = shelfAccess(weave, await withCircles(person, weave, opts.circles));
179
+ if (!access) {
180
+ throw new ShelfRefusal("forbidden", weave ? "That folder belongs to another person and is not shared with you or a circle you sit in." : "No owner is recorded for that folder, so only a person with Miadi's write tier can read it.");
141
181
  }
142
182
  const { files, truncated } = listFiles(dir);
143
183
  const manifest = {
144
184
  artefact: name,
145
185
  ...(weave?.owner ? { owner: { person_id: weave.owner.person_id, name: weave.owner.name } } : {}),
186
+ access,
187
+ // Whom it is shared with is its owner's to see, and the write tier's; a reader sees their own routes in access.
188
+ ...(access.as !== "shared" && weave?.shares?.length ? { shares: weave.shares } : {}),
146
189
  visibility: artefactVisibility(weave),
147
190
  ...(weave?.circle ? { circle: weave.circle } : {}),
148
191
  ...(weave?.issue ? { issue: weave.issue, issue_url: weave.issue_url } : {}),
@@ -178,6 +221,11 @@ export async function readShelfArtefact(root, name, person, opts = {}) {
178
221
  }
179
222
  const MAIN_DOCUMENTS = ["report.md", "README.md", "readme.md"];
180
223
  const AGENT_NOTES = /^(AGENTS|CLAUDE)\.md$/i;
224
+ /** A listing as one reader may see it: how they are admitted and, for the owner or the write tier, whom it is shared with. */
225
+ export function listingFor(listing, weave, access) {
226
+ const shares = access.as === "shared" ? [] : activeShares(weave);
227
+ return { ...listing, access, ...(shares.length ? { shares } : {}) };
228
+ }
181
229
  /** One folder's listing. A folder that cannot be read is listed by its name. */
182
230
  export function shelfListing(root, name, weave) {
183
231
  const dir = join(root, name);
@@ -266,18 +314,24 @@ export function sortListings(items, sort = "newest") {
266
314
  export async function listShelfArtefacts(root, person, opts = {}) {
267
315
  const scope = opts.scope ?? "mine";
268
316
  if (scope === "all" && person.api_tier !== "write")
269
- throw new ShelfRefusal("forbidden", "Listing the whole shelf needs Miadi's write tier. scope mine lists what you own.");
317
+ throw new ShelfRefusal("forbidden", "Listing the whole shelf needs Miadi's write tier. scope mine lists what you own, scope shared what is shared with you.");
270
318
  const limit = Math.min(Math.max(opts.limit ?? 50, 1), 200);
271
319
  const offset = Math.max(opts.offset ?? 0, 0);
272
320
  const q = opts.query?.trim().toLowerCase();
273
321
  const items = [];
322
+ let reader = person;
274
323
  for (const entry of existsSync(root) ? readdirSync(root, { withFileTypes: true }) : []) {
275
324
  if (!entry.isDirectory() || entry.name.startsWith("."))
276
325
  continue;
277
326
  const weave = await readArtefactWeave(join(root, entry.name)).catch(() => undefined);
278
- if (scope === "mine" ? weave?.owner?.person_id !== person.id : !canReadShelf(weave, person))
327
+ if (scope === "mine" && weave?.owner?.person_id !== person.id)
279
328
  continue;
280
- const item = shelfListing(root, entry.name, weave);
329
+ // The reader's circles are read once, at the first folder shared with a circle.
330
+ reader = await withCircles(reader, weave, opts.circles, scope === "shared");
331
+ const access = shelfAccess(weave, reader);
332
+ if (!access || (scope === "shared" && access.as !== "shared"))
333
+ continue;
334
+ const item = listingFor(shelfListing(root, entry.name, weave), weave, access);
281
335
  if (opts.kind && item.kind !== opts.kind)
282
336
  continue;
283
337
  if (q && ![item.title, item.excerpt, item.artefact, ...item.headings].some((t) => t?.toLowerCase().includes(q)))
@@ -295,3 +349,16 @@ export async function listShelfArtefacts(root, person, opts = {}) {
295
349
  read_with: "read_research_artifact takes an item's artefact, and its main file opens first",
296
350
  };
297
351
  }
352
+ /**
353
+ * What is shared with this reader: every folder another person shared with them or with a circle
354
+ * they sit in, each with the routes it reaches them by. Their own folders are not listed here.
355
+ */
356
+ export async function sharedWithReader(root, reader, circles) {
357
+ const items = [];
358
+ for (let offset = 0; offset !== null;) {
359
+ const page = await listShelfArtefacts(root, reader, { scope: "shared", limit: 200, offset, ...(circles ? { circles } : {}) });
360
+ items.push(...page.items);
361
+ offset = page.next_offset;
362
+ }
363
+ return items;
364
+ }
package/dist/server.d.ts CHANGED
@@ -43,6 +43,8 @@ export interface ConnectorDeps {
43
43
  steeringRuntime?: RuntimeDeps;
44
44
  /** Asks the factory runner for a pass now. Its timer is the net (jgwill/Miadi#942). */
45
45
  wakeRunner?: () => void;
46
+ /** Where a repository's clone lives on this host, for reading a completion's commits (jgwill/Miadi#993). Default: MIADI_CONNECTOR_CLONES, then the service's own checkout for jgwill/Miadi; tests pass their own. */
47
+ clones?: (repository: string) => string | undefined;
46
48
  /** Reads a video's captions for an approved create; the service passes youtubeCaptions, tests their own. */
47
49
  captions?: FetchCaptions;
48
50
  /** A transcription made on this host, tried for a released source whose captions are missing (jgwill/Miadi#995). */
package/dist/server.js CHANGED
@@ -151,6 +151,7 @@ export function createConnectorApp(config, deps) {
151
151
  steerSettleMs: deps.steerSettleMs,
152
152
  ...(deps.steeringRuntime ? { steeringRuntime: deps.steeringRuntime } : {}),
153
153
  ...(deps.wakeRunner ? { wakeRunner: deps.wakeRunner } : {}),
154
+ ...(deps.clones ? { clones: deps.clones } : {}),
154
155
  };
155
156
  const server = new McpServer({ name: "miadi", version: VERSION }, { instructions: INSTRUCTIONS });
156
157
  registerTools(server, ctx);
package/dist/tools.d.ts CHANGED
@@ -44,6 +44,8 @@ export interface ToolContext {
44
44
  draftReview?: DraftReviewService;
45
45
  /** Re-peek delay after a steer is typed (default 4000ms; tests pass 0). */
46
46
  steerSettleMs?: number;
47
+ /** Where a repository's clone lives on this host, for reading the commits of a completion (jgwill/Miadi#993). Default: MIADI_CONNECTOR_CLONES, then the service's own checkout for jgwill/Miadi. */
48
+ clones?: (repository: string) => string | undefined;
47
49
  }
48
50
  /**
49
51
  * Why GitHub did not answer a reference (jgwill/Miadi#913 B). A 404 without a
package/dist/tools.js CHANGED
@@ -32,7 +32,8 @@ import { DELIVERY_STATES, readSteerDelivery, revokeInInbox, settlementOf, transc
32
32
  import { ADAPTERS, readFactoryConfig, runSteering, STEERING_CONTRACT_ID, steeringSupport } from "./steering-adapters.js";
33
33
  import { checkGrant, isBusy, steerAttempts, steeringGrantOf, steeringRevoked, steerSession } from "./steer.js";
34
34
  import { factoryLedgerPath, readFactoryReceipts, receiptsForRecord, recordsForSession } from "./factory-receipt.js";
35
- import { missionResult, redactResult } from "./mission-result.js";
35
+ import { associationOf, missionResult, redactResult } from "./mission-result.js";
36
+ import { capabilitiesInput, clonesFromEnv, readChangedCapabilities, resolveCapabilities } from "./capabilities.js";
36
37
  import { factoryDir as defaultFactoryDir } from "./queue-state.js";
37
38
  import { join } from "node:path";
38
39
  import { readingScope, canonicalVideo, suppliedDialogue } from "./reading/contract.js";
@@ -124,6 +125,18 @@ const personWordsField = z.string().min(1).max(4000).optional().describe("The pe
124
125
  function withPrimary(refs, primary) {
125
126
  return primary ? [primary, ...refs.filter((r) => r !== primary)] : refs;
126
127
  }
128
+ /**
129
+ * What a mission names, resolved against the registry before anything is stored: an address the
130
+ * registry does not hold is refused by name (brings-into-being may name one with no row yet), and one
131
+ * refusal stores nothing (jgwill/Miadi#993).
132
+ */
133
+ function declareCapabilities(input) {
134
+ const { declared, refused } = resolveCapabilities(input);
135
+ if (refused.length) {
136
+ throw new ToolRefusal(refused.every((r) => r.code === "not_in_registry") ? "unknown_capability" : "invalid_capability", `${refused.map((r) => r.message).join(" ")} Nothing was stored.`, { refused });
137
+ }
138
+ return declared;
139
+ }
127
140
  /**
128
141
  * Why GitHub did not answer a reference (jgwill/Miadi#913 B). A 404 without a
129
142
  * token is a private repository as often as a missing issue, so nothing here is
@@ -216,7 +229,9 @@ export function registerTools(server, ctx) {
216
229
  let viewer;
217
230
  /**
218
231
  * The signed-in person, held to Miadi's read tier unless the tool says
219
- * otherwise: a person Miadi gives no API tier reaches only get_capabilities.
232
+ * otherwise: a person Miadi gives no API tier reaches get_capabilities,
233
+ * read_episode_file's foundation documents and the inquiry shelf's two reads,
234
+ * where the shelf's own rule decides (jgwill/Miadi#1005).
220
235
  */
221
236
  const who = (extra, minTier = "read") => {
222
237
  const found = personOf(extra);
@@ -532,9 +547,10 @@ export function registerTools(server, ctx) {
532
547
  const r = await reviews.get(id);
533
548
  if (!r)
534
549
  throw new ToolRefusal("not_found", "No review with this id.");
535
- if (typeof r.video_id !== "string")
550
+ const video = typeof r.video_id === "string" && r.video_id ? r.video_id : typeof r.video_url === "string" ? videoIdOf(r.video_url) : null;
551
+ if (!video)
536
552
  throw new ToolRefusal("invalid_ref", "This review names no YouTube video, so it has no transcript to acquire.");
537
- return { review_id: id, video_id: r.video_id };
553
+ return { review_id: id, video_id: video };
538
554
  }
539
555
  const video = videoIdOf(input);
540
556
  if (!video)
@@ -1543,6 +1559,7 @@ export function registerTools(server, ctx) {
1543
1559
  repo: z.string().max(120).optional(),
1544
1560
  delivery: deliveryField,
1545
1561
  person_words: personWordsField,
1562
+ capabilities: capabilitiesInput.optional(),
1546
1563
  ...launchModelFields,
1547
1564
  ...base,
1548
1565
  },
@@ -1557,6 +1574,7 @@ export function registerTools(server, ctx) {
1557
1574
  const plan = modelPlan(resolution.provider.id, a.model, modelConfig().permitted);
1558
1575
  if ("refusal" in plan)
1559
1576
  throw new ToolRefusal(plan.refusal.code, plan.refusal.message, { permitted: plan.refusal.permitted });
1577
+ const capabilities = a.capabilities?.length ? declareCapabilities(a.capabilities) : undefined;
1560
1578
  const r = append("work_proposal", person, auth, {
1561
1579
  circle: a.circle,
1562
1580
  refs: withPrimary(a.refs, a.primary_issue),
@@ -1576,6 +1594,7 @@ export function registerTools(server, ctx) {
1576
1594
  ...(a.primary_issue ? { primary_issue: a.primary_issue } : {}),
1577
1595
  ...(a.delivery ? { delivery: a.delivery } : {}),
1578
1596
  ...(a.person_words ? { person_words: a.person_words } : {}),
1597
+ ...(capabilities ? { capabilities } : {}),
1579
1598
  },
1580
1599
  });
1581
1600
  return { ...r, approval_url: approvalUrl(r.id), draft_review: await draftReviewOf(r) };
@@ -1650,18 +1669,55 @@ export function registerTools(server, ctx) {
1650
1669
  requireContribute(auth);
1651
1670
  const id = a.session_id.replace(/^session:/, "");
1652
1671
  const startedAt = new Date().toISOString();
1672
+ // The capabilities its commits changed, read from the commits themselves and set against what the mission declared (jgwill/Miadi#993).
1673
+ // A submission already waiting is handed back unchanged by append, so it is not read a second time.
1674
+ const idempotencyKey = a.mission ? `${id}:${a.ending}:${a.mission}` : `${id}:${a.ending}`;
1675
+ const waiting = all().some((x) => x.kind === "session_completion_proposal" && x.idempotency_key === idempotencyKey && x.actor.person_id === person.id && (x.approval_state === undefined || x.approval_state === "awaiting_approval" || x.approval_state === "not_required"));
1676
+ const named = [...(a.result?.outputs ?? []), ...(a.evidence_refs ?? []).map((ref) => ({ ref }))];
1677
+ let changedCapabilities;
1678
+ if (!waiting && named.length) {
1679
+ try {
1680
+ const mission = a.mission ? all().find((x) => x.id === a.mission) : undefined;
1681
+ // Holdings are filed only for a result read as verified by the rule a mission's result is read by: an approved
1682
+ // mission, a submission that names it from a session it is bound to, made with the write tier (#922 R3, R4).
1683
+ const bound = new Set(mission ? receiptsForRecord(receipts(), mission.id).flatMap((x) => (x.session_id ? [x.session_id] : [])) : []);
1684
+ if (mission && !bound.size)
1685
+ for (const ref of mission.refs)
1686
+ if (/^session:[0-9a-f-]{36}$/.test(ref))
1687
+ bound.add(ref.slice(8));
1688
+ const association = associationOf({ names: Boolean(mission), sessionId: id, boundSessions: bound, writeTier: person.id === "system:writer" || person.api_tier === "write" });
1689
+ const REASON = {
1690
+ no_binding: "the mission has no bound session to compare this one with",
1691
+ not_bound_session: "this session is not one the mission is bound to",
1692
+ submitter_below_write_tier: "the submission was made below Miadi's write tier",
1693
+ };
1694
+ const filing = !mission
1695
+ ? { allowed: false, reason: a.mission ? "the mission this completion names is not in the ledger" : "the completion names no mission" }
1696
+ : mission.approval_state !== "approved"
1697
+ ? { allowed: false, reason: `the mission is ${(mission.approval_state ?? "undecided").replace(/_/g, " ")}, not approved` }
1698
+ : association.association !== "verified"
1699
+ ? { allowed: false, reason: REASON[association.code ?? ""] ?? "the submission is not verified as the mission's result" }
1700
+ : { allowed: true };
1701
+ changedCapabilities = await readChangedCapabilities({ outputs: named, sessionId: id, ...(mission ? { mission } : {}), ...(a.mission ? { missionId: a.mission } : {}), filing, clones: ctx.clones ?? clonesFromEnv() });
1702
+ }
1703
+ catch {
1704
+ // A registry or a clone that cannot answer never refuses the ending: it is stored without the reading.
1705
+ changedCapabilities = undefined;
1706
+ }
1707
+ }
1653
1708
  const r = append("session_completion_proposal", person, auth, {
1654
1709
  circle: "continuity",
1655
1710
  refs: a.mission ? [`session:${id}`, a.mission] : [`session:${id}`],
1656
1711
  evidence_refs: a.evidence_refs,
1657
1712
  approval_state: "awaiting_approval",
1658
- idempotency_key: a.mission ? `${id}:${a.ending}:${a.mission}` : `${id}:${a.ending}`,
1713
+ idempotency_key: idempotencyKey,
1659
1714
  body: {
1660
1715
  session_id: id,
1661
1716
  ending: a.ending,
1662
1717
  reason: a.reason,
1663
1718
  ...(a.mission ? { mission: a.mission } : {}),
1664
1719
  ...(a.result ? { result: a.result } : {}),
1720
+ ...(changedCapabilities ? { changed_capabilities: changedCapabilities } : {}),
1665
1721
  // Set by the connector, never by the caller: a result is verified only when the write tier submits it (#922 R3).
1666
1722
  submitted_with_tier: person.api_tier ?? null,
1667
1723
  },
@@ -1754,6 +1810,7 @@ export function registerTools(server, ctx) {
1754
1810
  primary_issue: primaryIssue,
1755
1811
  delivery: deliveryField,
1756
1812
  person_words: personWordsField,
1813
+ capabilities: capabilitiesInput.optional(),
1757
1814
  session: z.string().regex(/^[A-Za-z0-9._-]{3,80}$/).optional().describe("An existing tmux session to hand it to, or a name for a new one."),
1758
1815
  cwd: z.string().max(300).optional().describe("Working folder for a new session (default: the factory runner's defaultCwd on the host)."),
1759
1816
  provider: z
@@ -1786,6 +1843,7 @@ export function registerTools(server, ctx) {
1786
1843
  const plan = modelPlan(resolution.provider.id, a.model, modelConfig().permitted);
1787
1844
  if ("refusal" in plan)
1788
1845
  throw new ToolRefusal(plan.refusal.code, plan.refusal.message, { permitted: plan.refusal.permitted });
1846
+ const capabilities = a.capabilities?.length ? declareCapabilities(a.capabilities) : undefined;
1789
1847
  const r = append("run_request", person, auth, {
1790
1848
  circle: a.circle,
1791
1849
  refs: withPrimary(a.refs, a.primary_issue),
@@ -1806,6 +1864,7 @@ export function registerTools(server, ctx) {
1806
1864
  ...(a.primary_issue ? { primary_issue: a.primary_issue } : {}),
1807
1865
  ...(a.delivery ? { delivery: a.delivery } : {}),
1808
1866
  ...(a.person_words ? { person_words: a.person_words } : {}),
1867
+ ...(capabilities ? { capabilities } : {}),
1809
1868
  ...(a.steering ? { steering: a.steering } : {}),
1810
1869
  },
1811
1870
  });
@@ -1864,6 +1923,7 @@ export function registerTools(server, ctx) {
1864
1923
  primary_issue: primaryIssue,
1865
1924
  delivery: deliveryField,
1866
1925
  person_words: personWordsField,
1926
+ capabilities: capabilitiesInput.optional().describe("The whole new list of capabilities the mission reaches, replacing the old one; an empty list names none. Each address is checked as request_authorized_run checks it."),
1867
1927
  session: z.string().regex(/^[A-Za-z0-9._-]{3,80}$/).optional(),
1868
1928
  cwd: z.string().max(300).optional(),
1869
1929
  provider: z.enum(["codex", "pi", "copilot", "claude"]).optional().describe("Verified installed on the connector host again, as request_authorized_run does."),
@@ -1933,6 +1993,13 @@ export function registerTools(server, ctx) {
1933
1993
  for (const k of ["delivery", "person_words"])
1934
1994
  if (c[k] !== undefined)
1935
1995
  body[k] = c[k];
1996
+ if (c.capabilities !== undefined && (live?.kind === "run_request" || live?.kind === "work_proposal")) {
1997
+ const declared = c.capabilities.length ? declareCapabilities(c.capabilities) : [];
1998
+ if (declared.length)
1999
+ body.capabilities = declared;
2000
+ else
2001
+ delete body.capabilities;
2002
+ }
1936
2003
  const nextRefs = withPrimary(c.refs ?? live?.refs ?? [], c.primary_issue ?? body.primary_issue);
1937
2004
  let record;
1938
2005
  try {
@@ -2452,11 +2519,18 @@ export function registerTools(server, ctx) {
2452
2519
  research_url: `${config.miadiPublicUrl}/research`,
2453
2520
  };
2454
2521
  }));
2522
+ /** The talking circles this person sits in now, through Miadi as them, read only when a folder is shared with a circle (jgwill/Miadi#1005). */
2523
+ const circlesOf = (token) => async () => {
2524
+ const b = await miadi.get(token, "/api/circles").catch((e) => {
2525
+ throw new ToolRefusal("unavailable", `Your circles could not be read from Miadi (${e instanceof MiadiError ? `HTTP ${e.status}` : "unreachable"}), so what reaches you through a circle cannot be decided now.`);
2526
+ });
2527
+ return (b?.circles ?? []).filter((c) => c?.member === true && typeof c.id === "string").map((c) => c.id);
2528
+ };
2455
2529
  server.registerTool("list_research_artifacts", {
2456
2530
  title: "List what is on the inquiry shelf",
2457
- description: "Reports and folders on Miadi's private inquiry shelf, as you may read them: each one's title, opening, words, sections, sources, files, date, owner, visibility, issue, episodes and, for a saved report, its sha256. All of it is computed from the files, never summarised. scope mine lists what you own; scope all, for Miadi's write tier, lists every folder. Search with query, narrow with kind, order with sort, and page with offset and next_offset. Read one with read_research_artifact. Read only: nothing is changed.",
2531
+ description: "Reports and folders on Miadi's private inquiry shelf, as you may read them: each one's title, opening, words, sections, sources, files, date, owner, visibility, issue, episodes and, for a saved report, its sha256. All of it is computed from the files, never summarised. Each says in access how it reaches you: as its owner, shared with you directly by a named person, through a talking circle you sit in (named), or as Miadi's write tier. scope mine lists what you own; scope shared lists what other people shared with you or with your circles; scope all, for Miadi's write tier, lists every folder. Search with query, narrow with kind, order with sort, and page with offset and next_offset. Read one with read_research_artifact. Read only: nothing is changed.",
2458
2532
  inputSchema: {
2459
- scope: z.enum(["mine", "all"]).default("mine"),
2533
+ scope: z.enum(["mine", "shared", "all"]).default("mine"),
2460
2534
  query: z.string().max(200).optional().describe("Words to find in a title, an opening, a heading or a folder's name."),
2461
2535
  kind: z.enum(["report", "folder", "notes"]).optional().describe("report: saved through a door. folder: holds a document. notes: agent instructions or unreadable files only."),
2462
2536
  sort: z.enum(["newest", "oldest", "longest", "title"]).default("newest"),
@@ -2465,12 +2539,14 @@ export function registerTools(server, ctx) {
2465
2539
  },
2466
2540
  annotations: READ,
2467
2541
  }, wrap(async (a, extra) => {
2468
- const { person } = who(extra);
2542
+ // No API tier needed: the shelf's own rule (shelfAccess) decides who reads what, and scope all stays the write tier's (jgwill/Miadi#1005).
2543
+ const { person } = who(extra, "none");
2469
2544
  if (!config.inquiryRoot)
2470
2545
  throw new ToolRefusal("unavailable", "This connector host has no inquiry shelf configured.");
2471
2546
  try {
2472
2547
  const { scope, query, kind, sort, limit, offset } = a;
2473
2548
  return await listShelfArtefacts(config.inquiryRoot, person, {
2549
+ circles: circlesOf(person.token),
2474
2550
  ...(scope ? { scope } : {}),
2475
2551
  ...(query ? { query } : {}),
2476
2552
  ...(kind ? { kind } : {}),
@@ -2487,7 +2563,7 @@ export function registerTools(server, ctx) {
2487
2563
  }));
2488
2564
  server.registerTool("read_research_artifact", {
2489
2565
  title: "Read a document on the inquiry shelf",
2490
- description: "Read back what is on Miadi's private inquiry shelf, as you: a folder's owner, visibility, its issue, its episodes, the commit that holds it, whether anything on disk differs from that commit, and every file with its bytes and sha256. With the folder's report, or the file you name, you also get its text, in pages when long: pass page.next back; joined, the pages hash to sha256. integrity says whether a saved report's bytes are still the bytes saved. Only the folder's owner or a person with Miadi's write tier can read it. Text files only; hidden files and links are never served. Read only: nothing is changed.",
2566
+ description: "Read back what is on Miadi's private inquiry shelf, as you: a folder's owner, visibility, its issue, its episodes, the commit that holds it, whether anything on disk differs from that commit, and every file with its bytes and sha256. With the folder's report, or the file you name, you also get its text, in pages when long: pass page.next back; joined, the pages hash to sha256. integrity says whether a saved report's bytes are still the bytes saved. Its owner reads it, and so does a person it is shared with, a member of a talking circle it is shared with (while they sit in it), and a person with Miadi's write tier; access says which of these you read it as, and through which circle or from whom. Text files only; hidden files and links are never served. Read only: nothing is changed.",
2491
2567
  inputSchema: {
2492
2568
  artefact: z.string().min(1).max(300).describe("The shelf folder's name, inquiry-artefact:<name> or the research_artifact record id save_research returned."),
2493
2569
  file: z.string().min(1).max(500).optional().describe("A path in the folder, as files lists it. Default: its saved report, if it has one."),
@@ -2497,7 +2573,8 @@ export function registerTools(server, ctx) {
2497
2573
  },
2498
2574
  annotations: READ,
2499
2575
  }, wrap(async (a, extra) => {
2500
- const { person } = who(extra);
2576
+ // No API tier needed: a participant reads what is shared with them; shelfAccess decides (jgwill/Miadi#1005).
2577
+ const { person } = who(extra, "none");
2501
2578
  if (!config.inquiryRoot)
2502
2579
  throw new ToolRefusal("unavailable", "This connector host has no inquiry shelf configured.");
2503
2580
  const ref = a.artefact.trim();
@@ -2512,6 +2589,7 @@ export function registerTools(server, ctx) {
2512
2589
  try {
2513
2590
  const { file, offset, revision, max_bytes: maxBytes } = a;
2514
2591
  return await readShelfArtefact(config.inquiryRoot, name, person, {
2592
+ circles: circlesOf(person.token),
2515
2593
  ...(file !== undefined ? { file } : {}),
2516
2594
  ...(offset !== undefined ? { offset } : {}),
2517
2595
  ...(revision !== undefined ? { revision } : {}),
@@ -2869,8 +2947,8 @@ export const TOOL_STATUS = {
2869
2947
  request_deep_diver: "live, contribute, needs_approval",
2870
2948
  link_review_to_episode: "live, contribute, needs_approval",
2871
2949
  save_research: "live, contribute (the whole report, in parts when long; saved on the inquiry shelf with its issue, pushed; private by default)",
2872
- list_research_artifacts: "live (the shelf as you may read it: yours, or every folder for the write tier; searched, sorted, paged)",
2873
- read_research_artifact: "live (a shelf folder's manifest and its text files, paged, with sha256 and the commit that holds them; its owner or Miadi's write tier)",
2950
+ list_research_artifacts: "live, no API tier needed (the shelf as you may read it: yours, what is shared with you or your circles, or every folder for the write tier; searched, sorted, paged)",
2951
+ read_research_artifact: "live, no API tier needed (a shelf folder's manifest and its text files, paged, with sha256 and the commit that holds them; its owner, whom it is shared with, the members of a circle it is shared with, or Miadi's write tier)",
2874
2952
  request_inquiry_episode: "live, contribute, needs_approval (weaves a shelf folder into an episode or starts one)",
2875
2953
  show_decisions: "live (cards in the conversation; deciding on them needs the write tier and the miadi:approve sign-in)",
2876
2954
  decide_request: "card only: the person's click on a decisions card; not offered to the assistant",
@@ -17,6 +17,7 @@
17
17
  import { existsSync, mkdirSync, readdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
18
18
  import { join } from "node:path";
19
19
  import { reviewCreatedOf } from "@miadi/hooks-core";
20
+ import { videoIdOf } from "./reviews.js";
20
21
  import { ensureTranscript } from "./transcript-job.js";
21
22
  /** How many facts one pass starts: each fetches captions from YouTube, so a burst is spread over passes. */
22
23
  export const INTAKE_PER_PASS = 3;
@@ -91,8 +92,10 @@ export async function settleTranscriptRequests(io, o) {
91
92
  result.kept += 1;
92
93
  continue;
93
94
  }
94
- if (review?.video_id !== fact.review.video_id) {
95
- reject(`The review's video is ${String(review?.video_id)}, not ${fact.review.video_id}.`);
95
+ // A review row may carry its video only as an address (video_id null), as the event's builder reads it too.
96
+ const reviewVideo = typeof review?.video_id === "string" && review.video_id ? review.video_id : typeof review?.video_url === "string" ? videoIdOf(review.video_url) : null;
97
+ if (reviewVideo !== fact.review.video_id) {
98
+ reject(`The review's video is ${String(reviewVideo)}, not ${fact.review.video_id}.`);
96
99
  continue;
97
100
  }
98
101
  const ensured = ensureTranscript(io, {
@@ -99,6 +99,13 @@ export interface TranscriptJobIo {
99
99
  local?: FetchCaptions;
100
100
  now?: () => number;
101
101
  log?: (event: Record<string, unknown>) => void;
102
+ /**
103
+ * A folder every process that runs transcript jobs on this host shares (the connector service, the worker
104
+ * script). An attempt holds `<lockDir>/<review id>` with its process id for as long as it runs, so two
105
+ * processes never run one review's job at once, however long an attempt takes. A lock whose process is
106
+ * gone is taken over. Without it, only this process's own attempts are known.
107
+ */
108
+ lockDir?: string;
102
109
  /** Told once each time a job reaches an ending (stored, held, failed), to announce it as a fact. Never fails the job. */
103
110
  outcome?: (job: ConnectorRecord, receipt: TranscriptJobReceipt) => void | Promise<unknown>;
104
111
  }
@@ -19,6 +19,8 @@
19
19
  * either holds the write tier or registered the source. No separate transcript decision exists.
20
20
  */
21
21
  import { createHash } from "node:crypto";
22
+ import { mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
23
+ import { join } from "node:path";
22
24
  import { TRANSCRIPT_RETRY_MS, TRANSCRIPT_WINDOW_MS, coverage, sourceOf } from "./captions.js";
23
25
  import { current, newRecordId } from "./records.js";
24
26
  /** The review service's own transcript door, as the connector's token reaches it. */
@@ -96,6 +98,61 @@ const runningOf = (io) => {
96
98
  running.set(io.ledger, (m = new Map()));
97
99
  return m;
98
100
  };
101
+ /**
102
+ * Takes the review's lock for this process, or answers null when a live process holds it. The release removes
103
+ * the lock only if it is still this process's.
104
+ */
105
+ function takeLock(io, reviewId) {
106
+ if (!io.lockDir)
107
+ return () => { };
108
+ mkdirSync(io.lockDir, { recursive: true, mode: 0o700 });
109
+ const file = join(io.lockDir, reviewId);
110
+ const mine = `${process.pid}\n`;
111
+ for (let tries = 0; tries < 2; tries += 1) {
112
+ try {
113
+ writeFileSync(file, mine, { flag: "wx", mode: 0o600 });
114
+ return () => {
115
+ try {
116
+ if (readFileSync(file, "utf8") === mine)
117
+ unlinkSync(file);
118
+ }
119
+ catch {
120
+ /* already gone */
121
+ }
122
+ };
123
+ }
124
+ catch (error) {
125
+ if (error.code !== "EEXIST")
126
+ throw error;
127
+ }
128
+ let holder = NaN;
129
+ try {
130
+ holder = Number(readFileSync(file, "utf8").trim());
131
+ }
132
+ catch {
133
+ continue; // released between the two calls: try again
134
+ }
135
+ if (Number.isSafeInteger(holder) && holder > 0 && processAlive(holder))
136
+ return null;
137
+ // Its process is gone (a stop or a crash): the lock is taken over.
138
+ try {
139
+ unlinkSync(file);
140
+ }
141
+ catch {
142
+ /* another taker removed it first */
143
+ }
144
+ }
145
+ return null;
146
+ }
147
+ function processAlive(pid) {
148
+ try {
149
+ process.kill(pid, 0);
150
+ return true;
151
+ }
152
+ catch (error) {
153
+ return error.code === "EPERM";
154
+ }
155
+ }
99
156
  function commit(io, job, receipt, note) {
100
157
  const before = receiptOf(job)?.state;
101
158
  const next = io.ledger.appendDurable({
@@ -387,6 +444,10 @@ export function ensureTranscript(io, input) {
387
444
  }
388
445
  }
389
446
  const start = job;
447
+ // Another process on this host runs this review's attempt now: this trigger joins it by waiting for nothing.
448
+ const release = takeLock(io, input.review_id);
449
+ if (!release)
450
+ return { job: start, joined: true, done: Promise.resolve(current(io.ledger.all()).find((r) => r.id === start.id) ?? start) };
390
451
  const run = (async () => {
391
452
  // A stored job is confirmed against the service and written again only if the service no longer holds the words.
392
453
  if (prior?.state === "stored") {
@@ -403,6 +464,7 @@ export function ensureTranscript(io, input) {
403
464
  return current(io.ledger.all()).find((r) => r.id === start.id) ?? start;
404
465
  });
405
466
  const tracked = run.finally(() => {
467
+ release();
406
468
  if (jobs.get(input.review_id) === tracked)
407
469
  jobs.delete(input.review_id);
408
470
  });
@@ -425,16 +487,21 @@ export async function settleTranscriptJobs(io, o = {}) {
425
487
  // An attempt that is not waiting for a retry and that this process does not run is one a restart interrupted, or one
426
488
  // a worker's own process runs. At start (resumeAll) the first is certain. Later, it is resumed only once its last
427
489
  // stage is older than STALE_MS, so a worker's attempt in its own process is left alone.
490
+ // With a lock folder, the lock says whether another process runs the attempt, so a free lock is resumed at once.
428
491
  const heartbeat = Date.parse(r.stages.at(-1)?.at ?? r.last_attempt_at ?? r.since);
429
- const interrupted = !r.next_attempt_at && (o.resumeAll === true || clock(io) - heartbeat >= STALE_MS);
492
+ const interrupted = !r.next_attempt_at && (o.resumeAll === true || Boolean(io.lockDir) || clock(io) - heartbeat >= STALE_MS);
430
493
  const due = (r.state === "acquiring" && (r.next_attempt_at ? Date.parse(r.next_attempt_at) <= clock(io) : interrupted)) ||
431
494
  (r.state === "held" && sourceStatus(io.ledger.all(), r.video_id) !== "withheld");
432
495
  if (!due)
433
496
  continue;
497
+ const release = takeLock(io, r.review_id);
498
+ if (!release)
499
+ continue; // another process on this host is running it
434
500
  const resumed = r.state === "held" ? { ...r, since: iso(clock(io)) } : r;
435
501
  const base = resumed === r ? job : commit(io, job, resumed);
436
502
  const run = attempt(io, base).catch(() => base);
437
503
  const tracked = run.finally(() => {
504
+ release();
438
505
  if (jobs.get(r.review_id) === tracked)
439
506
  jobs.delete(r.review_id);
440
507
  });
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.1.35";
1
+ export declare const VERSION = "0.1.37";
package/dist/version.js CHANGED
@@ -1 +1 @@
1
- export const VERSION = "0.1.35";
1
+ export const VERSION = "0.1.37";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@miadi/connector",
3
- "version": "0.1.35",
3
+ "version": "0.1.37",
4
4
  "description": "The Miadi connector: one remote MCP service through which a person signed in with their Miadi person token, from ChatGPT or any MCP client, reads sessions, reviews, episodes and circles and records observations, inquiries, handoffs and proposals with their name on each record.",
5
5
  "license": "MIT",
6
6
  "author": "Miadi",
@@ -16,6 +16,10 @@
16
16
  "types": "./dist/records.d.ts",
17
17
  "import": "./dist/records.js"
18
18
  },
19
+ "./capabilities": {
20
+ "types": "./dist/capabilities.d.ts",
21
+ "import": "./dist/capabilities.js"
22
+ },
19
23
  "./research-digest": {
20
24
  "types": "./dist/research-digest.d.ts",
21
25
  "import": "./dist/research-digest.js"
@@ -44,9 +48,10 @@
44
48
  ],
45
49
  "dependencies": {
46
50
  "@miadi/hooks-core": "^0.6.0",
47
- "@miadi/hooks-gateway": "^0.2.0",
48
- "@miadi/inquiry-weave": "0.18.13",
51
+ "@miadi/hooks-gateway": "^0.2.1",
52
+ "@miadi/inquiry-weave": "0.18.14",
49
53
  "@miadi/node-service-kit": "0.1.2",
54
+ "@miadi/relational-git-repository-mapper": "^0.7.0",
50
55
  "@modelcontextprotocol/sdk": "^1.30.0",
51
56
  "express": "^5.2.1",
52
57
  "express-rate-limit": "^8.2.1",