@peer2peer/ext-ix 0.0.0-stage → 0.1.1

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,64 @@
1
+ import { type IxRunner } from "./ix.js";
2
+ export type Relation = "caller" | "user" | "test" | "importer";
3
+ /** Files that depend on a file, each with how. */
4
+ export type Neighbourhood = Map<string, Set<Relation>>;
5
+ export type NeighbourhoodFn = (file: string) => Promise<Neighbourhood>;
6
+ export interface PeerChanges {
7
+ address: string;
8
+ own: string;
9
+ sid: string;
10
+ ref: string;
11
+ repo?: string;
12
+ files: readonly string[];
13
+ }
14
+ export interface SemanticConflict {
15
+ peer: {
16
+ address: string;
17
+ own: string;
18
+ sid: string;
19
+ ref: string;
20
+ };
21
+ /** My file and theirs. */
22
+ mine: string;
23
+ theirs: string;
24
+ direction: "mine-affects-theirs" | "theirs-affects-mine";
25
+ via: Relation[];
26
+ message: string;
27
+ }
28
+ export interface ConflictOptions {
29
+ mine: readonly string[];
30
+ peers: readonly PeerChanges[];
31
+ neighbourhood: NeighbourhoodFn;
32
+ /** My repo, as statuses carry it; peers in another repo are skipped. */
33
+ repo?: string;
34
+ /** At most this many of my files and of theirs are looked up (default 25 and 50). */
35
+ maxMine?: number;
36
+ maxTheirs?: number;
37
+ /** Total time for every lookup (default 40 s, inside p2p's 60 s command deadline). */
38
+ budgetMs?: number;
39
+ now?: () => number;
40
+ }
41
+ /** Default total lookup time. */
42
+ export declare const CONFLICT_BUDGET_MS = 40000;
43
+ /**
44
+ * L5: the "theirs" slots shared fairly: round-robin over peers, one file each
45
+ * per round, so one peer listing many files can't crowd the others out.
46
+ */
47
+ export declare function shareSlots(peers: readonly {
48
+ files: readonly string[];
49
+ }[], skip: ReadonlySet<string>, max: number): string[];
50
+ /** Reads `ix around <file> --format json` (AroundResult) into a neighbourhood. */
51
+ export declare function parseAround(json: unknown, self: string): Neighbourhood;
52
+ /** The neighbourhood function backed by the local Ix (`ix around`). Cached per file. */
53
+ export declare function ixNeighbourhood(ix: IxRunner, opts?: {
54
+ limit?: number;
55
+ }): NeighbourhoodFn;
56
+ /**
57
+ * Possible semantic conflicts between my changed files and each live peer
58
+ * session's. Lookups that fail are skipped (reported in `errors`); the same
59
+ * file on both sides is left to core's same-file conflict.
60
+ */
61
+ export declare function semanticConflicts(o: ConflictOptions): Promise<{
62
+ conflicts: SemanticConflict[];
63
+ errors: string[];
64
+ }>;
@@ -0,0 +1,188 @@
1
+ // Copyright 2026 Ix Infrastructure Inc.
2
+ //
3
+ // Semantic conflicts (SPEC.md §7): core flags two sessions changing the
4
+ // *same* file; with Ix, two sessions changing *connected* files are flagged
5
+ // too. For each file I'm changing, the local Ix says who depends on it
6
+ // (`ix around <file> --format json`: callers, users, tests and importers, by
7
+ // repo-relative path); where that meets a file a peer's session says it is
8
+ // changing, my change may break theirs. The same question about their files
9
+ // catches the other direction.
10
+ //
11
+ // Only the local graph is asked, about files named in statuses the peer
12
+ // already shared (protocol §4.3 `files`); nothing is sent. The result is
13
+ // information for the user and their agent, never an authorisation decision.
14
+ import { isSafeRelativePath } from "@peer2peer/core/v3";
15
+ import { ixJson } from "./ix.js";
16
+ import { isObj, line } from "./text.js";
17
+ /** Default total lookup time. */
18
+ export const CONFLICT_BUDGET_MS = 40_000;
19
+ /**
20
+ * L5: the "theirs" slots shared fairly: round-robin over peers, one file each
21
+ * per round, so one peer listing many files can't crowd the others out.
22
+ */
23
+ export function shareSlots(peers, skip, max) {
24
+ const queues = peers.map((p) => p.files.filter((f) => isSafeRelativePath(f) && !skip.has(f)));
25
+ const out = new Set();
26
+ for (let round = 0; out.size < max && queues.some((q) => q.length > round); round++) {
27
+ for (const q of queues) {
28
+ if (out.size >= max)
29
+ break;
30
+ if (round < q.length)
31
+ out.add(q[round]);
32
+ }
33
+ }
34
+ return [...out];
35
+ }
36
+ const ORDER = ["caller", "user", "importer", "test"];
37
+ /** Reads `ix around <file> --format json` (AroundResult) into a neighbourhood. */
38
+ export function parseAround(json, self) {
39
+ const out = new Map();
40
+ const add = (p, rel) => {
41
+ if (typeof p !== "string")
42
+ return;
43
+ const path = p.replace(/^\.\//, "");
44
+ if (path === self || !isSafeRelativePath(path))
45
+ return;
46
+ const set = out.get(path) ?? new Set();
47
+ set.add(rel);
48
+ out.set(path, set);
49
+ };
50
+ const rows = (sec) => (isObj(sec) && Array.isArray(sec.rows) ? sec.rows : []);
51
+ if (!isObj(json))
52
+ return out;
53
+ const j = json;
54
+ for (const sym of Array.isArray(j.symbols) ? j.symbols : []) {
55
+ if (!isObj(sym))
56
+ continue;
57
+ for (const r of rows(sym.callers))
58
+ if (isObj(r))
59
+ add(r.path, "caller");
60
+ for (const r of rows(sym.users))
61
+ if (isObj(r))
62
+ add(r.path, "user");
63
+ for (const r of rows(sym.tests))
64
+ if (isObj(r))
65
+ add(r.path, "test");
66
+ }
67
+ for (const r of rows(j.importers))
68
+ if (isObj(r))
69
+ add(r.path, "importer");
70
+ return out;
71
+ }
72
+ /** The neighbourhood function backed by the local Ix (`ix around`). Cached per file. */
73
+ export function ixNeighbourhood(ix, opts = {}) {
74
+ const cache = new Map();
75
+ return (file) => {
76
+ let p = cache.get(file);
77
+ if (!p) {
78
+ if (!isSafeRelativePath(file) || file.startsWith("-"))
79
+ return Promise.resolve(new Map());
80
+ p = ixJson(ix, ["around", file, "--format", "json", "--limit", String(opts.limit ?? 20)]).then((j) => parseAround(j, file));
81
+ cache.set(file, p);
82
+ }
83
+ return p;
84
+ };
85
+ }
86
+ function relWord(via) {
87
+ const r = via[0];
88
+ return r === "caller" ? "calls into" : r === "user" ? "uses" : r === "importer" ? "imports" : "tests";
89
+ }
90
+ /**
91
+ * Possible semantic conflicts between my changed files and each live peer
92
+ * session's. Lookups that fail are skipped (reported in `errors`); the same
93
+ * file on both sides is left to core's same-file conflict.
94
+ */
95
+ export async function semanticConflicts(o) {
96
+ const errors = [];
97
+ const mine = [...new Set(o.mine.filter((f) => isSafeRelativePath(f)))].slice(0, o.maxMine ?? 25);
98
+ const mineSet = new Set(mine);
99
+ const peers = o.peers.filter((p) => !o.repo || !p.repo || p.repo.toLowerCase() === o.repo.toLowerCase());
100
+ const theirsAll = shareSlots(peers, mineSet, o.maxTheirs ?? 50);
101
+ const now = o.now ?? Date.now;
102
+ const deadline = now() + (o.budgetMs ?? CONFLICT_BUDGET_MS);
103
+ let skipped = 0;
104
+ const look = async (f) => {
105
+ const left = deadline - now();
106
+ if (left <= 0) {
107
+ skipped++;
108
+ return undefined;
109
+ }
110
+ let timer;
111
+ try {
112
+ // A lookup that would overrun the budget is abandoned (its result ignored).
113
+ return await Promise.race([
114
+ o.neighbourhood(f),
115
+ new Promise((resolve) => {
116
+ timer = setTimeout(() => {
117
+ skipped++;
118
+ resolve(undefined);
119
+ }, left);
120
+ }),
121
+ ]);
122
+ }
123
+ catch (e) {
124
+ errors.push(`${line(f, 120)}: ${line(e.message, 200)}`);
125
+ return undefined;
126
+ }
127
+ finally {
128
+ clearTimeout(timer);
129
+ }
130
+ };
131
+ const nMine = new Map();
132
+ for (const f of mine)
133
+ nMine.set(f, await look(f));
134
+ const nTheirs = new Map();
135
+ for (const f of theirsAll)
136
+ nTheirs.set(f, await look(f));
137
+ if (skipped > 0)
138
+ errors.push(`time budget (${Math.round((o.budgetMs ?? CONFLICT_BUDGET_MS) / 1000)} s) reached: ${skipped} file(s) not checked`);
139
+ const out = [];
140
+ const seen = new Set();
141
+ for (const p of peers) {
142
+ const peer = { address: line(p.address, 80), own: p.own, sid: p.sid, ref: p.ref };
143
+ const theirs = p.files.filter((f) => nTheirs.has(f));
144
+ for (const m of mine) {
145
+ const hood = nMine.get(m);
146
+ for (const t of theirs) {
147
+ const via = hood?.get(t);
148
+ if (!via)
149
+ continue;
150
+ const key = `${p.own}|${p.sid}|${m}|${t}|m`;
151
+ if (seen.has(key))
152
+ continue;
153
+ seen.add(key);
154
+ const v = ORDER.filter((r) => via.has(r));
155
+ out.push({
156
+ peer,
157
+ mine: m,
158
+ theirs: t,
159
+ direction: "mine-affects-theirs",
160
+ via: v,
161
+ message: `possible semantic conflict with ${peer.address}: your change to ${m} affects ${line(t, 300)} they're editing (it ${relWord(v)} ${m})`,
162
+ });
163
+ }
164
+ }
165
+ for (const t of theirs) {
166
+ const hood = nTheirs.get(t);
167
+ for (const m of mine) {
168
+ const via = hood?.get(m);
169
+ if (!via)
170
+ continue;
171
+ const key = `${p.own}|${p.sid}|${m}|${t}|t`;
172
+ if (seen.has(key))
173
+ continue;
174
+ seen.add(key);
175
+ const v = ORDER.filter((r) => via.has(r));
176
+ out.push({
177
+ peer,
178
+ mine: m,
179
+ theirs: t,
180
+ direction: "theirs-affects-mine",
181
+ via: v,
182
+ message: `possible semantic conflict with ${peer.address}: their change to ${line(t, 300)} affects ${m} you're editing (it ${relWord(v)} ${line(t, 300)})`,
183
+ });
184
+ }
185
+ }
186
+ }
187
+ return { conflicts: out, errors };
188
+ }
@@ -0,0 +1,45 @@
1
+ import type { ExtCommand, ExtContext, ExtReceived, ExtReceiveInput, P2PExtension } from "@peer2peer/cli";
2
+ import { type IxRunner, type TargetFn } from "./ix.js";
3
+ import { type ListenerCheck } from "./listener.js";
4
+ import { type NoteBody } from "./note.js";
5
+ import { type RepoRef } from "./repo.js";
6
+ export declare const VERSION = "0.1.1";
7
+ export declare const KINDS: readonly ["x:ix.note", "x:ix.subgraph", "x:ix.impact"];
8
+ /** Cap on local Ix output a command hands back (resolve). */
9
+ export declare const MAX_RESOLVE_OUTPUT: number;
10
+ /** Validates and renders one inbound kind. Never runs Ix, never writes. */
11
+ export declare function receiveIx(input: ExtReceiveInput): ExtReceived;
12
+ /** A received note in full, framed as data from the named peer (L4): what `show` prints and `import` asks about. */
13
+ export declare function noteFull(b: NoteBody, address: string): string;
14
+ /** Test seam: the runner and the git environment the commands use. */
15
+ export interface Deps {
16
+ ix?: (ctx: ExtContext) => IxRunner;
17
+ /** The clock (footprint debounce and timestamps). */
18
+ now?: () => number;
19
+ /** Who listens on the local endpoint's port (listener.ts); tests stand in for the operating system. */
20
+ listener?: ListenerCheck;
21
+ }
22
+ /**
23
+ * The graph target of a call (packages/p2p/src/projects.ts graphTarget, through ExtContext): the
24
+ * only place an `ix` endpoint comes from. A p2p from before graph targets has none to give: local.
25
+ * Any failure is local too.
26
+ */
27
+ export declare function targetOf(ctx: ExtContext, sid?: string, extra?: readonly string[]): TargetFn;
28
+ /**
29
+ * The `ix` a command runs: each call pinned to the graph target of session `sid` (when the command
30
+ * has one), its folders, the paths the call names (callPaths) and `extra` (the command's own path
31
+ * arguments: --changed, --file), and limited to the commands that target allows.
32
+ */
33
+ export declare function runner(ctx: ExtContext, deps: Deps, sid?: string, extra?: readonly string[]): IxRunner;
34
+ export interface Here {
35
+ /** git's spelling of the root (local only, never sent). */
36
+ root?: string;
37
+ /** Every spelling of the root: git's, its realpath, and the one the cwd uses (symlinked dirs). */
38
+ roots: string[];
39
+ ref?: RepoRef;
40
+ }
41
+ export declare function repoOf(ctx: ExtContext): Promise<Here>;
42
+ export declare function ixCommands(deps?: Deps): ExtCommand[];
43
+ export declare function createIxExtension(deps?: Deps): P2PExtension;
44
+ /** What `p2p` loads. */
45
+ export declare const extension: P2PExtension;