@joe-broadhead/opencode-mem 0.9.12 → 0.11.2
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/CHANGELOG.md +1934 -2
- package/README.md +29 -17
- package/SECURITY.md +3 -1
- package/docs/agent-instructions.md +17 -0
- package/docs/agent-protocol.md +8 -8
- package/docs/permissions.md +22 -4
- package/package.json +7923 -217
- package/shared/page-paths.js +44 -0
- package/skills/mem.pages/SKILL.md +8 -1
- package/skills/mem.usage/SKILL.md +15 -15
- package/src/action-grant-keys.js +159 -0
- package/src/action-grant.js +439 -0
- package/src/actions.js +1690 -0
- package/src/backend/records.js +25 -2
- package/src/backend/v3.js +76 -22
- package/src/call-shapes.js +17 -16
- package/src/collector-lock.js +533 -62
- package/src/collector-service.js +153 -26
- package/src/collector.js +627 -33
- package/src/config.js +79 -6
- package/src/connect.js +106 -8
- package/src/credentials.js +123 -25
- package/src/events.js +174 -3
- package/src/forget-turn.js +141 -0
- package/src/host-refusal.js +78 -0
- package/src/index.js +209 -22
- package/src/jobs/host.js +557 -0
- package/src/ops/codes.js +110 -0
- package/src/ops/copy-lineage.js +42 -0
- package/src/ops/index.js +28 -0
- package/src/ops/space-ops.js +1936 -0
- package/src/outlinks.js +103 -0
- package/src/p2-reservation.js +151 -0
- package/src/permissions.js +30 -0
- package/src/plugins/descriptor.js +62 -0
- package/src/plugins/discovery.js +318 -0
- package/src/plugins/grants.js +178 -0
- package/src/plugins/locate.js +319 -0
- package/src/plugins/manifest.js +1162 -0
- package/src/plugins/source-contract/index.js +34 -0
- package/src/plugins/source-contract/policy.js +102 -0
- package/src/plugins/source-contract/vendor/PROVENANCE.json +17 -0
- package/src/plugins/source-contract/vendor/RELEASE-SHA256SUMS +3 -0
- package/src/plugins/source-contract/vendor/RELEASE.json +17 -0
- package/src/plugins/source-contract/vendor/SHA256SUMS +41 -0
- package/src/plugins/source-contract/vendor/THIRD-PARTY-NOTICES.md +35 -0
- package/src/plugins/source-contract/vendor/broker-client.js +93 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-3M5PAKSS.js +84 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-4ERCA4TK.js +185 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-6HDIB2SA.js +183 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-ELPJD3ND.js +10 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-HLVAKAYG.js +10 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-I2RXJJJM.js +81 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-KWEWSZ4V.js +505 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-KYWBTAF4.js +182 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-Q3RQA5J2.js +249 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-RRUAIQ4I.js +156 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-RYNKNCPP.js +165 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-W5SHR7DQ.js +9477 -0
- package/src/plugins/source-contract/vendor/chunks/chunk-ZUKF7P6U.js +653 -0
- package/src/plugins/source-contract/vendor/cursor.js +26 -0
- package/src/plugins/source-contract/vendor/descriptor.js +34 -0
- package/src/plugins/source-contract/vendor/events.js +257 -0
- package/src/plugins/source-contract/vendor/index.js +10 -0
- package/src/plugins/source-contract/vendor/params.js +22 -0
- package/src/plugins/source-contract/vendor/permission.js +28 -0
- package/src/plugins/source-contract/vendor/pick.js +22 -0
- package/src/plugins/source-contract/vendor/read.js +29 -0
- package/src/plugins/source-contract/vendor/registry.js +23 -0
- package/src/plugins/source-contract/vendor/schema.js +17 -0
- package/src/plugins/source-contract/vendor/schemas/output.agenda.json +96 -0
- package/src/plugins/source-contract/vendor/schemas/output.countdown.json +28 -0
- package/src/plugins/source-contract/vendor/schemas/output.image.json +28 -0
- package/src/plugins/source-contract/vendor/schemas/output.inbox.json +84 -0
- package/src/plugins/source-contract/vendor/schemas/output.links.json +46 -0
- package/src/plugins/source-contract/vendor/schemas/output.list.json +57 -0
- package/src/plugins/source-contract/vendor/schemas/output.metric.json +61 -0
- package/src/plugins/source-contract/vendor/schemas/output.note.json +14 -0
- package/src/plugins/source-contract/vendor/schemas/output.progress.json +50 -0
- package/src/plugins/source-contract/vendor/schemas/output.record.json +38 -0
- package/src/plugins/source-contract/vendor/schemas/output.table.json +61 -0
- package/src/plugins/source-contract/vendor/schemas/output.thread.json +62 -0
- package/src/plugins/source-contract/vendor/schemas/sources.json +819 -0
- package/src/plugins/source-contract/vendor/schemas.js +19 -0
- package/src/plugins/source-contract/vendor/tools-rpc.js +42 -0
- package/src/plugins/verify.js +56 -0
- package/src/protocol.js +21 -5
- package/src/recall.js +104 -5
- package/src/records.js +61 -2
- package/src/requests.js +216 -0
- package/src/runtime.js +89 -7
- package/src/setup-time.js +68 -0
- package/src/skills.js +230 -8
- package/src/source-ids.js +25 -0
- package/src/sources/declaration.js +365 -0
- package/src/sources/reads.js +772 -0
- package/src/sources/rpc.js +151 -0
- package/src/sources.js +409 -90
- package/src/spaces.js +283 -11
- package/src/spool.js +61 -4
- package/src/stated.js +10 -5
- package/src/storable.js +139 -0
- package/src/tools/commitments.js +47 -5
- package/src/tools/held-write.js +36 -13
- package/src/tools/index.js +27 -0
- package/src/tools/ingest.js +27 -2
- package/src/tools/memory.js +52 -14
- package/src/tools/page.js +95 -9
- package/src/tools/recall.js +208 -4
- package/src/tools/records-kit.js +2 -1
- package/src/tools/share.js +42 -3
- package/src/tools/shared.js +44 -4
- package/src/tools/space-lifecycle.js +278 -0
- package/src/tools/spaces.js +373 -29
- package/src/tools/status.js +9 -2
- package/src/tools/wiki.js +34 -4
- package/src/util.js +110 -6
- package/src/vendor/source-contract/README.md +24 -0
- package/src/vendor/source-contract/THIRD-PARTY-NOTICES.md +35 -0
- package/src/vendor/source-contract/VENDOR.json +81 -0
- package/src/vendor/source-contract/chunks/chunk-3M5PAKSS.js +84 -0
- package/src/vendor/source-contract/chunks/chunk-6HDIB2SA.js +183 -0
- package/src/vendor/source-contract/chunks/chunk-HLVAKAYG.js +10 -0
- package/src/vendor/source-contract/chunks/chunk-I2RXJJJM.js +81 -0
- package/src/vendor/source-contract/chunks/chunk-KWEWSZ4V.js +505 -0
- package/src/vendor/source-contract/chunks/chunk-W5SHR7DQ.js +9477 -0
- package/src/vendor/source-contract/chunks/chunk-ZUKF7P6U.js +653 -0
- package/src/vendor/source-contract/cursor.js +26 -0
- package/src/vendor/source-contract/events.js +257 -0
- package/src/vendor/source-contract/registry.js +23 -0
- package/src/vendor/source-contract/tools-rpc.js +42 -0
- package/src/views/access-reads.js +256 -0
- package/src/views/communities.js +77 -0
- package/src/views/contracts.js +1183 -36
- package/src/views/inbox-bytes.js +103 -0
- package/src/views/overdue.js +1 -1
- package/src/views/profile.js +31 -0
- package/src/views/receipt.js +81 -0
- package/src/views/records-reads.js +869 -37
- package/src/views/rpc.js +159 -11
- package/src/views/shape.js +8 -5
- package/views/memory.html +16 -3
- package/views/pages.html +2 -2
- package/views/remembered.html +130 -0
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
// @we-the-rebel-alliance/source-contract 0.1.0. Built by scripts/build.mjs; do not edit.
|
|
2
|
+
import {
|
|
3
|
+
CURSOR_V1,
|
|
4
|
+
CURSOR_V2,
|
|
5
|
+
MAX_CURSOR_LENGTH,
|
|
6
|
+
RESERVED_STATE_KEYS,
|
|
7
|
+
bindingHash,
|
|
8
|
+
canonicalScope,
|
|
9
|
+
decodeBoundCursor,
|
|
10
|
+
decodeCursor,
|
|
11
|
+
encodeBoundCursor,
|
|
12
|
+
encodeCursor
|
|
13
|
+
} from "./chunks/chunk-I2RXJJJM.js";
|
|
14
|
+
import "./chunks/chunk-HLVAKAYG.js";
|
|
15
|
+
export {
|
|
16
|
+
CURSOR_V1,
|
|
17
|
+
CURSOR_V2,
|
|
18
|
+
MAX_CURSOR_LENGTH,
|
|
19
|
+
RESERVED_STATE_KEYS,
|
|
20
|
+
bindingHash,
|
|
21
|
+
canonicalScope,
|
|
22
|
+
decodeBoundCursor,
|
|
23
|
+
decodeCursor,
|
|
24
|
+
encodeBoundCursor,
|
|
25
|
+
encodeCursor
|
|
26
|
+
};
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// @we-the-rebel-alliance/source-contract 0.1.0. Built by scripts/build.mjs; do not edit.
|
|
2
|
+
import {
|
|
3
|
+
CONTRACT1_CODES,
|
|
4
|
+
ERROR_ALIASES,
|
|
5
|
+
ERROR_CODES,
|
|
6
|
+
EVENTS_LIST,
|
|
7
|
+
EVENT_KINDS,
|
|
8
|
+
EVENT_LIMITS,
|
|
9
|
+
EXTENSION_KIND,
|
|
10
|
+
EXTENSION_NAME,
|
|
11
|
+
EXTENSION_SEGMENT_MAX,
|
|
12
|
+
FIRST_RUN_HOURS,
|
|
13
|
+
GAP_REASONS,
|
|
14
|
+
MAX_BYTES,
|
|
15
|
+
MAX_PAGE_BYTES,
|
|
16
|
+
PAGE,
|
|
17
|
+
PROBE,
|
|
18
|
+
PROBE_LIMITS,
|
|
19
|
+
PROPOSED_CODES,
|
|
20
|
+
REFUSAL_REASONS,
|
|
21
|
+
SCOPE_KEY_PATTERN,
|
|
22
|
+
SINCE_PATTERN,
|
|
23
|
+
SOURCE_PATTERN,
|
|
24
|
+
SourceError,
|
|
25
|
+
TRUST,
|
|
26
|
+
canonicalCode,
|
|
27
|
+
cut,
|
|
28
|
+
eventHash,
|
|
29
|
+
eventProblems,
|
|
30
|
+
eventsListResult,
|
|
31
|
+
extensionNamespace,
|
|
32
|
+
fitPage,
|
|
33
|
+
isEventKind,
|
|
34
|
+
isEventKindIn,
|
|
35
|
+
isExtensionName,
|
|
36
|
+
makeEvent,
|
|
37
|
+
oldestFirst,
|
|
38
|
+
parseEventsListInput,
|
|
39
|
+
parseProbeInput,
|
|
40
|
+
parseSourceError,
|
|
41
|
+
probeResult,
|
|
42
|
+
probeResultProblems,
|
|
43
|
+
resultProblems,
|
|
44
|
+
scopeProblems,
|
|
45
|
+
screenEvents,
|
|
46
|
+
secretKinds,
|
|
47
|
+
sinceTime,
|
|
48
|
+
sourceNamespace,
|
|
49
|
+
startTime
|
|
50
|
+
} from "./chunks/chunk-ZUKF7P6U.js";
|
|
51
|
+
import {
|
|
52
|
+
decodeBoundCursor,
|
|
53
|
+
decodeCursor,
|
|
54
|
+
encodeBoundCursor,
|
|
55
|
+
encodeCursor
|
|
56
|
+
} from "./chunks/chunk-I2RXJJJM.js";
|
|
57
|
+
import "./chunks/chunk-HLVAKAYG.js";
|
|
58
|
+
|
|
59
|
+
// src/internal/events-conformance.ts
|
|
60
|
+
var describeError = (error) => error instanceof Error ? error.message.split("\n", 1)[0] : String(error);
|
|
61
|
+
async function eventsListConformance(list, fixtures) {
|
|
62
|
+
const problems = [];
|
|
63
|
+
const hooks = fixtures.hooks ?? {};
|
|
64
|
+
const maxBytes = fixtures.maxBytes ?? MAX_PAGE_BYTES;
|
|
65
|
+
const call = async (input, what) => {
|
|
66
|
+
try {
|
|
67
|
+
const result = await list(input);
|
|
68
|
+
hooks.onCall?.({ what, input, result });
|
|
69
|
+
return { result };
|
|
70
|
+
} catch (error) {
|
|
71
|
+
hooks.onCall?.({ what, input, error });
|
|
72
|
+
return { error };
|
|
73
|
+
}
|
|
74
|
+
};
|
|
75
|
+
const scope = {
|
|
76
|
+
...fixtures.account === void 0 ? {} : { account: fixtures.account },
|
|
77
|
+
...fixtures.sourceInput ? { source: fixtures.source } : {},
|
|
78
|
+
...fixtures.scope === void 0 ? {} : { scope: fixtures.scope }
|
|
79
|
+
};
|
|
80
|
+
const base = { ...fixtures.since === void 0 ? {} : { since: fixtures.since }, ...scope };
|
|
81
|
+
const after = (cursor) => ({ cursor, ...scope });
|
|
82
|
+
const pageSize = fixtures.pageSize ?? 2;
|
|
83
|
+
const since = fixtures.since === void 0 ? void 0 : sinceTime(fixtures.since);
|
|
84
|
+
const owners = /* @__PURE__ */ new Set();
|
|
85
|
+
const accounts = /* @__PURE__ */ new Set();
|
|
86
|
+
const hashes = /* @__PURE__ */ new Map();
|
|
87
|
+
const check = (listed, what, limit) => {
|
|
88
|
+
if (listed.error !== void 0) {
|
|
89
|
+
problems.push(`${what} failed: ${describeError(listed.error)}`);
|
|
90
|
+
return void 0;
|
|
91
|
+
}
|
|
92
|
+
const found = resultProblems(listed.result, limit, maxBytes);
|
|
93
|
+
problems.push(...found.map((problem) => `${what}: ${problem}`));
|
|
94
|
+
if (found.length > 0) return void 0;
|
|
95
|
+
const result = listed.result;
|
|
96
|
+
if (result.source !== fixtures.source) problems.push(`${what}: the result names the source ${result.source}, not ${fixtures.source}`);
|
|
97
|
+
if (fixtures.account !== void 0 && result.account !== fixtures.account) problems.push(`${what}: the result names the account ${result.account}, not ${fixtures.account}`);
|
|
98
|
+
accounts.add(result.account);
|
|
99
|
+
owners.add(JSON.stringify(result.owner));
|
|
100
|
+
if (fixtures.owner && JSON.stringify(result.owner) !== JSON.stringify({ id: fixtures.owner.id, label: fixtures.owner.label })) problems.push(`${what}: the owner is not the fixture's owner`);
|
|
101
|
+
if (fixtures.scopeEcho && fixtures.scope !== void 0) {
|
|
102
|
+
if (result.scope === void 0) problems.push(`${what}: the result does not echo the scope`);
|
|
103
|
+
else if (JSON.stringify(result.scope) !== JSON.stringify(sortedScope(fixtures.scope))) problems.push(`${what}: the result's scope is not the call's scope`);
|
|
104
|
+
}
|
|
105
|
+
for (const event of result.events) {
|
|
106
|
+
if (event.source !== fixtures.source) problems.push(`${what}: an event names the source ${event.source}, not ${fixtures.source}`);
|
|
107
|
+
if (fixtures.account !== void 0 && event.account !== fixtures.account) problems.push(`${what}: an event names the account ${event.account}, not ${fixtures.account}`);
|
|
108
|
+
if (since !== void 0 && Date.parse(event.occurred_at) < since) problems.push(`${what}: the event ${event.external_id} is from before since`);
|
|
109
|
+
if (fixtures.namespace !== void 0 && !isEventKindIn(event.kind, fixtures.namespace)) problems.push(`${what}: the event ${event.external_id} is a ${event.kind}, outside the namespace ${fixtures.namespace}`);
|
|
110
|
+
if (fixtures.kinds !== void 0 && !fixtures.kinds.includes(event.kind)) problems.push(`${what}: the event ${event.external_id} is a ${event.kind}, which the source does not declare`);
|
|
111
|
+
const secrets = secretKinds([event.title, event.text].filter(Boolean).join("\n"));
|
|
112
|
+
if (secrets.length > 0) problems.push(`${what}: the event ${event.external_id} holds a secret (${secrets.join(", ")}); it belongs in refused[]`);
|
|
113
|
+
const known = hashes.get(event.external_id);
|
|
114
|
+
if (known !== void 0 && known !== event.hash) problems.push(`${what}: the event ${event.external_id} has another hash than before`);
|
|
115
|
+
hashes.set(event.external_id, event.hash);
|
|
116
|
+
}
|
|
117
|
+
return result;
|
|
118
|
+
};
|
|
119
|
+
const ids = (result) => result?.events.map((event) => event.external_id) ?? [];
|
|
120
|
+
const whole = check(await call({ ...base, limit: PAGE.max }, "one call with the largest limit"), "one call with the largest limit", PAGE.max);
|
|
121
|
+
if (whole) {
|
|
122
|
+
if (JSON.stringify(ids(whole)) !== JSON.stringify(fixtures.expected)) problems.push(`one call with the largest limit lists [${ids(whole).join(", ")}], not [${fixtures.expected.join(", ")}]`);
|
|
123
|
+
if (fixtures.expected.length <= PAGE.max && whole.more) problems.push("one call with the largest limit lists everything but says more");
|
|
124
|
+
if (fixtures.refused !== void 0) {
|
|
125
|
+
const refusedIds = (whole.refused ?? []).map((entry) => entry.external_id);
|
|
126
|
+
if (JSON.stringify(refusedIds) !== JSON.stringify(fixtures.refused)) problems.push(`one call with the largest limit refuses [${refusedIds.join(", ")}], not [${fixtures.refused.join(", ")}]`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
const pages = [];
|
|
130
|
+
let page = check(await call({ ...base, limit: pageSize }, "the first page"), "the first page", pageSize);
|
|
131
|
+
const most = fixtures.expected.length + (fixtures.refused?.length ?? 0) + 10;
|
|
132
|
+
while (page) {
|
|
133
|
+
pages.push(page);
|
|
134
|
+
if (!page.more) break;
|
|
135
|
+
if (pages.length > most) {
|
|
136
|
+
problems.push(`the paged walk did not end after ${most} pages`);
|
|
137
|
+
break;
|
|
138
|
+
}
|
|
139
|
+
const what = `page ${pages.length + 1}`;
|
|
140
|
+
page = check(await call({ ...after(page.cursor), limit: pageSize }, what), what, pageSize);
|
|
141
|
+
}
|
|
142
|
+
const walked = pages.flatMap(ids);
|
|
143
|
+
if (JSON.stringify(walked) !== JSON.stringify(fixtures.expected)) problems.push(`the pages of ${pageSize} list [${walked.join(", ")}], not [${fixtures.expected.join(", ")}]`);
|
|
144
|
+
if (pages.length >= 2) {
|
|
145
|
+
const again = check(await call({ ...after(pages[0].cursor), limit: pageSize }, "the first cursor again"), "the first cursor again", pageSize);
|
|
146
|
+
if (again && JSON.stringify(again.events) !== JSON.stringify(pages[1].events)) problems.push("the first cursor, used again, does not list the second page again");
|
|
147
|
+
}
|
|
148
|
+
const last = pages.at(-1);
|
|
149
|
+
if (last && !last.more) {
|
|
150
|
+
const end = check(await call({ ...after(last.cursor), limit: pageSize }, "the last cursor"), "the last cursor", pageSize);
|
|
151
|
+
if (end && (end.events.length > 0 || end.more)) problems.push("the last cursor lists events again, or says more");
|
|
152
|
+
}
|
|
153
|
+
const empty = check(await call({ ...scope, since: "2999-01-01T00:00:00Z", limit: pageSize }, "an empty first page"), "an empty first page", pageSize);
|
|
154
|
+
if (empty && (empty.events.length > 0 || empty.more)) problems.push("a first page from a since in the future lists events, or says more");
|
|
155
|
+
if (owners.size > 1) problems.push("the owner changes between calls");
|
|
156
|
+
if (accounts.size > 1) problems.push("the account changes between calls");
|
|
157
|
+
const refused = async (input, what, codes) => {
|
|
158
|
+
const listed = await call(input, what);
|
|
159
|
+
if (listed.error === void 0) {
|
|
160
|
+
problems.push(`${what} was not refused`);
|
|
161
|
+
return;
|
|
162
|
+
}
|
|
163
|
+
if (fixtures.codes) {
|
|
164
|
+
const parsed = parseSourceError(listed.error);
|
|
165
|
+
if (!parsed?.canonical || !codes.includes(parsed.canonical)) problems.push(`${what} was refused without the code ${codes.join(" or ")}${parsed ? ` (it says ${parsed.code})` : ""}`);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
const INPUT = ["INPUT_INVALID"];
|
|
169
|
+
const CURSOR = ["CURSOR_INVALID"];
|
|
170
|
+
await refused({ ...base, limit: PAGE.max + 1 }, `a limit of ${PAGE.max + 1}`, INPUT);
|
|
171
|
+
await refused({ ...base, limit: 0 }, "a limit of 0", INPUT);
|
|
172
|
+
await refused({ ...after("not-a-cursor"), limit: pageSize }, "a malformed cursor", CURSOR);
|
|
173
|
+
await refused({ ...after(encodeCursor(`${fixtures.source}-other`, {})), limit: pageSize }, "another source's cursor", CURSOR);
|
|
174
|
+
await refused({ ...base, source: `${fixtures.source}-other`, limit: pageSize }, "a source the plugin does not have", ["SOURCE_UNKNOWN", "INPUT_INVALID"]);
|
|
175
|
+
const first = pages[0];
|
|
176
|
+
if (fixtures.binding !== void 0 && first) {
|
|
177
|
+
const binding = { plugin: fixtures.binding.plugin, source: fixtures.source, account: first.account, ...fixtures.scope === void 0 ? {} : { scope: fixtures.scope } };
|
|
178
|
+
const decoded = decodeBoundCursor(binding, first.cursor);
|
|
179
|
+
if (!decoded.ok) problems.push("the first page's cursor is not the library's cursor bound to this plugin, source, account and scope");
|
|
180
|
+
else {
|
|
181
|
+
const others = [
|
|
182
|
+
["another plugin's", { ...binding, plugin: `${binding.plugin}-other` }],
|
|
183
|
+
["another account's", { ...binding, account: `${binding.account}-other` }],
|
|
184
|
+
["another scope's", { ...binding, scope: { ...binding.scope ?? {}, conformance: ["other"] } }]
|
|
185
|
+
];
|
|
186
|
+
for (const [whose, other] of others) await refused({ ...after(encodeBoundCursor(other, decoded.state)), limit: pageSize }, `${whose} bound cursor`, CURSOR);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
if (hooks.after) problems.push(...await hooks.after({ ...whole ? { whole } : {}, pages }));
|
|
190
|
+
return problems;
|
|
191
|
+
}
|
|
192
|
+
function sortedScope(scope) {
|
|
193
|
+
const out = {};
|
|
194
|
+
for (const key of Object.keys(scope).sort()) {
|
|
195
|
+
const value = scope[key];
|
|
196
|
+
out[key] = Array.isArray(value) ? [...new Set(value)].sort() : value;
|
|
197
|
+
}
|
|
198
|
+
return out;
|
|
199
|
+
}
|
|
200
|
+
async function assertEventsListConformance(list, fixtures) {
|
|
201
|
+
const problems = await eventsListConformance(list, fixtures);
|
|
202
|
+
if (problems.length > 0) throw new Error(`events_list breaks the contract:
|
|
203
|
+
- ${problems.join("\n- ")}`);
|
|
204
|
+
}
|
|
205
|
+
export {
|
|
206
|
+
CONTRACT1_CODES,
|
|
207
|
+
ERROR_ALIASES,
|
|
208
|
+
ERROR_CODES,
|
|
209
|
+
EVENTS_LIST,
|
|
210
|
+
EVENT_KINDS,
|
|
211
|
+
EVENT_LIMITS,
|
|
212
|
+
EXTENSION_KIND,
|
|
213
|
+
EXTENSION_NAME,
|
|
214
|
+
EXTENSION_SEGMENT_MAX,
|
|
215
|
+
FIRST_RUN_HOURS,
|
|
216
|
+
GAP_REASONS,
|
|
217
|
+
MAX_BYTES,
|
|
218
|
+
MAX_PAGE_BYTES,
|
|
219
|
+
PAGE,
|
|
220
|
+
PROBE,
|
|
221
|
+
PROBE_LIMITS,
|
|
222
|
+
PROPOSED_CODES,
|
|
223
|
+
REFUSAL_REASONS,
|
|
224
|
+
SCOPE_KEY_PATTERN,
|
|
225
|
+
SINCE_PATTERN,
|
|
226
|
+
SOURCE_PATTERN,
|
|
227
|
+
SourceError,
|
|
228
|
+
TRUST,
|
|
229
|
+
assertEventsListConformance,
|
|
230
|
+
canonicalCode,
|
|
231
|
+
cut,
|
|
232
|
+
decodeCursor,
|
|
233
|
+
encodeCursor,
|
|
234
|
+
eventHash,
|
|
235
|
+
eventProblems,
|
|
236
|
+
eventsListConformance,
|
|
237
|
+
eventsListResult,
|
|
238
|
+
extensionNamespace,
|
|
239
|
+
fitPage,
|
|
240
|
+
isEventKind,
|
|
241
|
+
isEventKindIn,
|
|
242
|
+
isExtensionName,
|
|
243
|
+
makeEvent,
|
|
244
|
+
oldestFirst,
|
|
245
|
+
parseEventsListInput,
|
|
246
|
+
parseProbeInput,
|
|
247
|
+
parseSourceError,
|
|
248
|
+
probeResult,
|
|
249
|
+
probeResultProblems,
|
|
250
|
+
resultProblems,
|
|
251
|
+
scopeProblems,
|
|
252
|
+
screenEvents,
|
|
253
|
+
secretKinds,
|
|
254
|
+
sinceTime,
|
|
255
|
+
sourceNamespace,
|
|
256
|
+
startTime
|
|
257
|
+
};
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// @we-the-rebel-alliance/source-contract 0.1.0. Built by scripts/build.mjs; do not edit.
|
|
2
|
+
import {
|
|
3
|
+
EXTENSION_OUTPUT,
|
|
4
|
+
IMAGE_DATA_URI_MAX,
|
|
5
|
+
OUTPUTS,
|
|
6
|
+
OUTPUT_NAMES,
|
|
7
|
+
checkOutput,
|
|
8
|
+
isExtensionOutput,
|
|
9
|
+
isOutputName,
|
|
10
|
+
outputValidator
|
|
11
|
+
} from "./chunks/chunk-6HDIB2SA.js";
|
|
12
|
+
import "./chunks/chunk-W5SHR7DQ.js";
|
|
13
|
+
import "./chunks/chunk-HLVAKAYG.js";
|
|
14
|
+
export {
|
|
15
|
+
EXTENSION_OUTPUT,
|
|
16
|
+
IMAGE_DATA_URI_MAX,
|
|
17
|
+
OUTPUTS,
|
|
18
|
+
OUTPUT_NAMES,
|
|
19
|
+
checkOutput,
|
|
20
|
+
isExtensionOutput,
|
|
21
|
+
isOutputName,
|
|
22
|
+
outputValidator
|
|
23
|
+
};
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// @we-the-rebel-alliance/source-contract 0.1.0. Built by scripts/build.mjs; do not edit.
|
|
2
|
+
import {
|
|
3
|
+
CLASSES,
|
|
4
|
+
LOCATION_HEADER,
|
|
5
|
+
LOCATION_HINT,
|
|
6
|
+
PLUGIN_ID_PATTERN,
|
|
7
|
+
READ_VERBS,
|
|
8
|
+
RESOURCE_PATTERN,
|
|
9
|
+
TOOLS_RPC_SUFFIX,
|
|
10
|
+
defineRpc,
|
|
11
|
+
hidden,
|
|
12
|
+
isToolsRpcId,
|
|
13
|
+
pluginIdOf,
|
|
14
|
+
readOperation,
|
|
15
|
+
registerToolsRpc,
|
|
16
|
+
toolsRpcId,
|
|
17
|
+
toolsRpcIdProblems,
|
|
18
|
+
upstreamText
|
|
19
|
+
} from "./chunks/chunk-KWEWSZ4V.js";
|
|
20
|
+
import {
|
|
21
|
+
evaluate
|
|
22
|
+
} from "./chunks/chunk-3M5PAKSS.js";
|
|
23
|
+
import "./chunks/chunk-HLVAKAYG.js";
|
|
24
|
+
export {
|
|
25
|
+
CLASSES,
|
|
26
|
+
LOCATION_HEADER,
|
|
27
|
+
LOCATION_HINT,
|
|
28
|
+
PLUGIN_ID_PATTERN,
|
|
29
|
+
READ_VERBS,
|
|
30
|
+
RESOURCE_PATTERN,
|
|
31
|
+
TOOLS_RPC_SUFFIX,
|
|
32
|
+
defineRpc,
|
|
33
|
+
evaluate,
|
|
34
|
+
hidden,
|
|
35
|
+
isToolsRpcId,
|
|
36
|
+
pluginIdOf,
|
|
37
|
+
readOperation,
|
|
38
|
+
registerToolsRpc,
|
|
39
|
+
toolsRpcId,
|
|
40
|
+
toolsRpcIdProblems,
|
|
41
|
+
upstreamText
|
|
42
|
+
};
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import { ACCESS_PAGE } from "./contracts.js"
|
|
2
|
+
import { ANSWER_BYTES, clip, fitList, idOf, jsonBytes, refuse, spaceOf } from "./shape.js"
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* `members.list` and `grants.list`: who is in a space, and who one of its pages,
|
|
6
|
+
* folders or wikis is shared with (Jelly's ask 10, opencode-mem#57).
|
|
7
|
+
*
|
|
8
|
+
* Both read the same service operations Memory's sources already read —
|
|
9
|
+
* control's member roster (`mem.members`) and its grants (`mem.grants`) — and
|
|
10
|
+
* both **defer every access decision to control**, which is where the console's
|
|
11
|
+
* rules live:
|
|
12
|
+
*
|
|
13
|
+
* - **Members are a member's to see.** Control's `GET /v1/spaces/:id/members`
|
|
14
|
+
* needs the viewer role of the space (`control/src/service/spaces.js`
|
|
15
|
+
* `listMembers`, `auth.requireRole("viewer")`), so a space-wide grant is
|
|
16
|
+
* enough and a page grant is not: someone who reaches a space only through a
|
|
17
|
+
* grant on one of its pages is refused, as the console's own Members panel is.
|
|
18
|
+
* - **A page's grants are its owner's and the space admins'.** Control answers a
|
|
19
|
+
* page's grants to its owner or to an admin of it
|
|
20
|
+
* (`control/src/service/grants.js` `listGrantRows`), and the console's share
|
|
21
|
+
* sheet says the same in words ("Only its owner and space admins can see who it
|
|
22
|
+
* is shared with", `deploy/auth/console/kit/sharing.js`). A space editor who
|
|
23
|
+
* owns neither is refused.
|
|
24
|
+
* - **Another organisation, and an archived space, name nobody.** Control lists
|
|
25
|
+
* only the caller's organisation's active spaces (`accessibleSpaces`,
|
|
26
|
+
* `store.spaces.listForUser`: `s.org_id = ? AND s.status = 'active'`), so a
|
|
27
|
+
* space it does not list is refused here before either read, exactly as
|
|
28
|
+
* `loadSpace` would refuse it.
|
|
29
|
+
* - **A revoked grant takes the access with it**, because control reads the
|
|
30
|
+
* roster and the grants on every call and drops an inactive grant
|
|
31
|
+
* (`isGrantActive`): nothing is cached between calls or people.
|
|
32
|
+
*
|
|
33
|
+
* **Bounded and paged, like every other read.** At most `ACCESS_PAGE` rows an
|
|
34
|
+
* answer **and at most `ANSWER_BYTES` of JSON, its cursor included** (the limit
|
|
35
|
+
* `memories.recent` and the terms read use, well inside Jelly's 64 KB), because
|
|
36
|
+
* a person's name is up to 200 characters and may be multi-byte: fifty hostile
|
|
37
|
+
* rows can be more than one answer should carry. A page cut for room keeps a run
|
|
38
|
+
* from the top and hands back a `cursor` for the row after the last one it
|
|
39
|
+
* showed, so nothing is lost and nothing is listed twice; `more` says whether
|
|
40
|
+
* anything is left. The cursor is this read's own, bound to the space and target
|
|
41
|
+
* it was given for, and a list is walked to its end one page at a time, as
|
|
42
|
+
* `pages.list` is.
|
|
43
|
+
*
|
|
44
|
+
* **The space-wide grant list is not a key's to read.** Control's bearer route
|
|
45
|
+
* answers a page's grants by `resource_id`, and without one only the grants that
|
|
46
|
+
* name the caller (`deploy/auth/space-admin-api.mjs`, "the grants naming the
|
|
47
|
+
* caller"); the console's browser session is what lists every grant in a space.
|
|
48
|
+
* So `grants.list` without a `target` answers the caller's own grants and says
|
|
49
|
+
* so (`scope: "mine"`), with a `note` a page can show.
|
|
50
|
+
*
|
|
51
|
+
* @param {{
|
|
52
|
+
* runtime: any,
|
|
53
|
+
* personalScopes: () => Promise<Array<{ context: any, scope: any }>>,
|
|
54
|
+
* available: () => Promise<void>,
|
|
55
|
+
* }} input
|
|
56
|
+
*/
|
|
57
|
+
export function createAccessReads({ runtime, personalScopes, available }) {
|
|
58
|
+
const config = runtime.config ?? {}
|
|
59
|
+
|
|
60
|
+
/** The person a control read names: the gateway uses the credential's own identity. */
|
|
61
|
+
const caller = () => String(config.user ?? "")
|
|
62
|
+
|
|
63
|
+
/** Refuse in the view's own words when this server keeps no control plane. */
|
|
64
|
+
function controlOrRefuse() {
|
|
65
|
+
if (!runtime.control) refuse("Members and grants come from Memory's server, and this one keeps no roster.")
|
|
66
|
+
return runtime.control
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The spaces control lists for the caller now; nothing is kept between calls. */
|
|
70
|
+
async function listedSpaces(control) {
|
|
71
|
+
return ((await control.listSpaces({ userId: caller() })) ?? []).filter((space) => idOf(space?.space_id))
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** The space a call names, checked against control's own list; the personal one when it names none. */
|
|
75
|
+
async function namedSpace(control, value) {
|
|
76
|
+
const wanted = value === undefined || value === null ? "" : String(value).trim()
|
|
77
|
+
const spaces = await listedSpaces(control)
|
|
78
|
+
if (!wanted) {
|
|
79
|
+
const [first] = await personalScopes()
|
|
80
|
+
const personal = spaceOf(first?.context ?? null)
|
|
81
|
+
const own = spaces.find((space) => space.space_id === personal.id)
|
|
82
|
+
if (!own) refuse("Memory has no personal space for you.")
|
|
83
|
+
return { id: own.space_id, name: own.name || own.space_id }
|
|
84
|
+
}
|
|
85
|
+
if (!idOf(wanted)) refuse("That is not a space id.")
|
|
86
|
+
const found = spaces.find((space) => space.space_id === wanted)
|
|
87
|
+
if (!found) refuse("That space isn't one of yours.")
|
|
88
|
+
return { id: found.space_id, name: found.name || found.space_id }
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Whether a control refusal is one of its own access answers (403, or 404 for a space or target it will not name). */
|
|
92
|
+
const refusedByControl = (error) => [403, 404].includes(Number(error?.status))
|
|
93
|
+
|
|
94
|
+
/** The row a call starts at: no cursor is the top; a cursor this read gave is the row it names. */
|
|
95
|
+
function startOf(cursor, bound) {
|
|
96
|
+
if (cursor === undefined || cursor === null || String(cursor).trim() === "") return 0
|
|
97
|
+
const start = decodeCursor(String(cursor).trim(), bound)
|
|
98
|
+
if (start === null) refuse(CURSOR_REFUSAL)
|
|
99
|
+
return start
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Who is in one space, as control's own member roster lets the caller see it. */
|
|
103
|
+
async function membersList(input) {
|
|
104
|
+
await available()
|
|
105
|
+
const control = controlOrRefuse()
|
|
106
|
+
const space = await namedSpace(control, input?.space)
|
|
107
|
+
const start = startOf(input?.cursor, { space: space.id, target: null })
|
|
108
|
+
let roster
|
|
109
|
+
try {
|
|
110
|
+
roster = (await control.listMembers({ userId: caller(), spaceId: space.id })) ?? []
|
|
111
|
+
} catch (error) {
|
|
112
|
+
if (refusedByControl(error)) refuse("Only someone with a role in this space can see who is in it.")
|
|
113
|
+
throw error
|
|
114
|
+
}
|
|
115
|
+
const rows = roster
|
|
116
|
+
.filter((member) => idOf(member?.user_id))
|
|
117
|
+
.map((member) => ({
|
|
118
|
+
person: idOf(member.user_id),
|
|
119
|
+
label: clip(member.name || member.email || member.user_id, 200),
|
|
120
|
+
role: clip(member.role ?? "", 40),
|
|
121
|
+
...(member.added_at ? { added: clip(member.added_at, 40) } : {}),
|
|
122
|
+
}))
|
|
123
|
+
const answer = { space, members: [] }
|
|
124
|
+
const kept = fitAccessPage(answer, "members", rows, start)
|
|
125
|
+
const more = start + kept < rows.length
|
|
126
|
+
return { ...answer, more, ...(more ? { cursor: encodeCursor({ space: space.id, start: start + kept }) } : {}) }
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Control's principal types in the view's words: a person, a group, an org role, an agent. */
|
|
130
|
+
const SUBJECT = Object.freeze({ user: "person", group: "group", org_role: "role", agent: "agent" })
|
|
131
|
+
|
|
132
|
+
/** One grant as a view names it: who, how much access, and on what. */
|
|
133
|
+
function grantRow(grant) {
|
|
134
|
+
const kind = SUBJECT[String(grant?.principal_type ?? "")]
|
|
135
|
+
const principal = idOf(grant?.principal_id)
|
|
136
|
+
if (!kind || !principal) return null
|
|
137
|
+
const target = idOf(grant?.target_id)
|
|
138
|
+
return {
|
|
139
|
+
subject: { [kind]: principal },
|
|
140
|
+
access: clip(grant.role ?? "", 40),
|
|
141
|
+
target: { type: clip(grant.target_type ?? "", 20), id: target },
|
|
142
|
+
// A person's name where control gives one (its grant row carries it for a
|
|
143
|
+
// user principal); otherwise the id, never a guess.
|
|
144
|
+
label: clip(grant.principal_name || grant.principal_email || principal, 200),
|
|
145
|
+
...(grant.created_at ? { since: clip(grant.created_at, 40) } : {}),
|
|
146
|
+
...(grant.expires_at ? { expires: clip(grant.expires_at, 40) } : {}),
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Who one page, folder or wiki is shared with, or the grants that name the
|
|
152
|
+
* caller when the call names no target.
|
|
153
|
+
*/
|
|
154
|
+
async function grantsList(input) {
|
|
155
|
+
await available()
|
|
156
|
+
const control = controlOrRefuse()
|
|
157
|
+
const space = await namedSpace(control, input?.space)
|
|
158
|
+
const named = input?.target === undefined || input.target === null ? "" : String(input.target).trim()
|
|
159
|
+
const start = startOf(input?.cursor, { space: space.id, target: named || null })
|
|
160
|
+
let grants
|
|
161
|
+
if (named) {
|
|
162
|
+
if (!idOf(named)) refuse("That is not a page, folder or wiki id.")
|
|
163
|
+
try {
|
|
164
|
+
// Control's own route: the grants on one registered resource, for its
|
|
165
|
+
// owner or an admin of it (`resource_id`, what the gateway forwards to
|
|
166
|
+
// control's `target_type=resource`).
|
|
167
|
+
grants = (await control.listGrants({ userId: caller(), spaceId: space.id, resourceId: named })) ?? []
|
|
168
|
+
} catch (error) {
|
|
169
|
+
if (refusedByControl(error)) refuse("Only its owner and the space's admins can see who it is shared with.")
|
|
170
|
+
throw error
|
|
171
|
+
}
|
|
172
|
+
} else {
|
|
173
|
+
grants = (await control.listGrants({ userId: caller(), spaceId: space.id })) ?? []
|
|
174
|
+
}
|
|
175
|
+
const rows = grants.map(grantRow).filter(Boolean)
|
|
176
|
+
const answer = { space, scope: named ? "target" : "mine", target: named || null, grants: [] }
|
|
177
|
+
const kept = fitAccessPage(answer, "grants", rows, start)
|
|
178
|
+
const more = start + kept < rows.length
|
|
179
|
+
return {
|
|
180
|
+
...answer,
|
|
181
|
+
more,
|
|
182
|
+
...(more ? { cursor: encodeCursor({ space: space.id, ...(named ? { target: named } : {}), start: start + kept }) } : {}),
|
|
183
|
+
...(named
|
|
184
|
+
? {}
|
|
185
|
+
: {
|
|
186
|
+
note: "A key reads the grants that name you, not every grant in a space: a space's whole grant list is in Memory's console.",
|
|
187
|
+
}),
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return { "members.list": membersList, "grants.list": grantsList }
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Said when a cursor is not one this read gave, or names another list: a page's token, never a guess. */
|
|
195
|
+
export const CURSOR_REFUSAL = "That is not a cursor this list gave; read it again from the start."
|
|
196
|
+
|
|
197
|
+
/** The highest row a cursor may name: not a page size, only a guard against a nonsense token. */
|
|
198
|
+
const CURSOR_MAX_ROW = 100_000
|
|
199
|
+
|
|
200
|
+
/** The cursor a page hands back: the next row, bound to the space and target it belongs to. */
|
|
201
|
+
export function encodeCursor({ space, target, start }) {
|
|
202
|
+
return Buffer.from(JSON.stringify({ s: space, ...(target ? { t: target } : {}), o: start })).toString("base64url")
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* The row a cursor names, or null when it is not this list's or is not one this
|
|
207
|
+
* read could have given. A cursor is bound to its space (and target), so one
|
|
208
|
+
* from another list is refused rather than silently skipping rows.
|
|
209
|
+
*/
|
|
210
|
+
export function decodeCursor(cursor, { space, target }) {
|
|
211
|
+
let parsed
|
|
212
|
+
try {
|
|
213
|
+
parsed = JSON.parse(Buffer.from(cursor, "base64url").toString("utf8"))
|
|
214
|
+
} catch {
|
|
215
|
+
return null
|
|
216
|
+
}
|
|
217
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null
|
|
218
|
+
if (parsed.s !== space) return null
|
|
219
|
+
if ((parsed.t ?? null) !== (target ?? null)) return null
|
|
220
|
+
if (!Number.isInteger(parsed.o) || parsed.o < 0 || parsed.o >= CURSOR_MAX_ROW) return null
|
|
221
|
+
return parsed.o
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Room kept for the fields a page gains **after** its list: `more`, a cursor
|
|
226
|
+
* bound to a 200-character space and target id (a base64url of their JSON), and
|
|
227
|
+
* the `note` a "mine" answer carries. The declared row shapes bound them: a
|
|
228
|
+
* cursor is under 580 bytes and the note under 150, so 1,024 holds both.
|
|
229
|
+
*/
|
|
230
|
+
export const ACCESS_TAIL_BYTES = 1_024
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* One page of `rows` in `answer[key]`, from `start`, fitted to `ANSWER_BYTES`
|
|
234
|
+
* with `ACCESS_TAIL_BYTES` kept for the fields added after it: a run from the
|
|
235
|
+
* top, so the cursor that follows it loses nothing. Returns how many rows were
|
|
236
|
+
* kept; at least one whenever there is one to keep, because one row is far
|
|
237
|
+
* inside the limit and an empty page that says `more` would loop.
|
|
238
|
+
*
|
|
239
|
+
* @param {Record<string, any>} answer the answer built so far, with `answer[key]` an empty array
|
|
240
|
+
* @param {string} key "members" or "grants"
|
|
241
|
+
* @param {any[]} rows every row of the list, in control's order
|
|
242
|
+
* @param {number} start the row this page starts at
|
|
243
|
+
*/
|
|
244
|
+
export function fitAccessPage(answer, key, rows, start) {
|
|
245
|
+
const page = rows.slice(start, start + ACCESS_PAGE)
|
|
246
|
+
fitList(answer, key, page, ANSWER_BYTES - ACCESS_TAIL_BYTES)
|
|
247
|
+
if (answer[key].length === 0 && page.length > 0) {
|
|
248
|
+
// Only if a single row could not fit, which the declared row sizes make
|
|
249
|
+
// impossible: show it, and let the byte count say what it costs.
|
|
250
|
+
answer[key].push(page[0])
|
|
251
|
+
}
|
|
252
|
+
return answer[key].length
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Whether one answer is inside the byte limit the other reads hold to (a test's own check). */
|
|
256
|
+
export const withinAnswerBytes = (answer) => jsonBytes(answer) <= ANSWER_BYTES
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Communities in a graph: a grouping of the nodes a view's answer already
|
|
3
|
+
* carries, by their links (Jelly's ask 2, so its graph can colour by
|
|
4
|
+
* community). A community is computed here on every read and never stored:
|
|
5
|
+
* Memory keeps a page's links, not a clustering of them.
|
|
6
|
+
*
|
|
7
|
+
* **The algorithm.** Label propagation over the answer's own nodes, in node
|
|
8
|
+
* order, for at most `COMMUNITY_ROUNDS` rounds. Each node starts with its own
|
|
9
|
+
* index as its label; in one round each node takes the most common label among
|
|
10
|
+
* its neighbours and itself (the self vote keeps a node from flipping in a tie),
|
|
11
|
+
* the smallest label winning a tie, and the rounds stop early at the first round
|
|
12
|
+
* that changes nothing. The labels are then numbered by the first node that
|
|
13
|
+
* carries each, so communities are `0…n-1` in node order. Every step is ordered,
|
|
14
|
+
* so the same graph always gives the same answer, and the work is bounded by the
|
|
15
|
+
* answer's own caps (at most `GRAPH_NODES_MAX` nodes and `GRAPH_EDGES_MAX`
|
|
16
|
+
* edges, each round over the edges).
|
|
17
|
+
*
|
|
18
|
+
* **What it can never do.** It reads only the nodes and edges of the answer it
|
|
19
|
+
* is given. A page the caller cannot see is not a node, so no community counts
|
|
20
|
+
* it or is named for it: the grouping can reveal nothing the answer does not.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
/** Rounds of label propagation: a bound, not a target; most graphs settle in two or three. */
|
|
24
|
+
export const COMMUNITY_ROUNDS = 8
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The community of each node, in node order.
|
|
28
|
+
*
|
|
29
|
+
* @param {number} nodeCount how many nodes the answer lists
|
|
30
|
+
* @param {ReadonlyArray<{ from: number, to: number }>} edges edges by node index
|
|
31
|
+
* @param {number} [rounds] the most rounds to run (`COMMUNITY_ROUNDS`)
|
|
32
|
+
* @returns {number[]} one community number per node, from 0, numbered by first appearance
|
|
33
|
+
*/
|
|
34
|
+
export function communitiesOf(nodeCount, edges, rounds = COMMUNITY_ROUNDS) {
|
|
35
|
+
const count = Number.isInteger(nodeCount) && nodeCount > 0 ? nodeCount : 0
|
|
36
|
+
if (count === 0) return []
|
|
37
|
+
const neighbours = Array.from({ length: count }, () => [])
|
|
38
|
+
for (const edge of Array.isArray(edges) ? edges : []) {
|
|
39
|
+
const from = edge?.from
|
|
40
|
+
const to = edge?.to
|
|
41
|
+
if (!Number.isInteger(from) || !Number.isInteger(to) || from === to) continue
|
|
42
|
+
if (from < 0 || to < 0 || from >= count || to >= count) continue
|
|
43
|
+
neighbours[from].push(to)
|
|
44
|
+
neighbours[to].push(from)
|
|
45
|
+
}
|
|
46
|
+
const label = Array.from({ length: count }, (_, index) => index)
|
|
47
|
+
const limit = Number.isInteger(rounds) && rounds > 0 ? rounds : COMMUNITY_ROUNDS
|
|
48
|
+
for (let round = 0; round < limit; round += 1) {
|
|
49
|
+
let changed = false
|
|
50
|
+
for (let node = 0; node < count; node += 1) {
|
|
51
|
+
const around = neighbours[node]
|
|
52
|
+
if (around.length === 0) continue
|
|
53
|
+
const votes = new Map()
|
|
54
|
+
const vote = (value) => votes.set(value, (votes.get(value) ?? 0) + 1)
|
|
55
|
+
vote(label[node])
|
|
56
|
+
for (const near of around) vote(label[near])
|
|
57
|
+
let best = label[node]
|
|
58
|
+
let bestVotes = -1
|
|
59
|
+
for (const [value, tally] of votes) {
|
|
60
|
+
if (tally > bestVotes || (tally === bestVotes && value < best)) {
|
|
61
|
+
best = value
|
|
62
|
+
bestVotes = tally
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
if (best !== label[node]) {
|
|
66
|
+
label[node] = best
|
|
67
|
+
changed = true
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (!changed) break
|
|
71
|
+
}
|
|
72
|
+
const numbered = new Map()
|
|
73
|
+
return label.map((value) => {
|
|
74
|
+
if (!numbered.has(value)) numbered.set(value, numbered.size)
|
|
75
|
+
return numbered.get(value)
|
|
76
|
+
})
|
|
77
|
+
}
|