@verevoir/aigency-work 0.0.0-stage → 0.2.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,160 @@
1
+ // An in-memory `CardSource` and `CardSink` — a fake board, good enough to
2
+ // stand in for a real tracker in a demo or a test. A card moving needs
3
+ // something to move it on, and a tracker nobody has access to cannot be
4
+ // that thing.
5
+ export function createInMemoryBoard(initial = []) {
6
+ const cards = new Map();
7
+ const revisions = new Map();
8
+ for (const card of initial) {
9
+ revisions.set(card.id, 1);
10
+ cards.set(card.id, stripOwnRevision(card));
11
+ }
12
+ let unreachableReason;
13
+ // The only place this board's revision lives is `revisions`, above.
14
+ // A card handed to `put`/`createCard`, or read back from `cards` and
15
+ // re-stored by `writeState`/`annotate`, never carries its own
16
+ // `revision` field — so there is nothing on the stored `Card` itself
17
+ // that could ever disagree with what the guard checks. `withRevision`
18
+ // is the one place a revision is attached, on the way OUT, from the
19
+ // one map that tracks it.
20
+ function stripOwnRevision(card) {
21
+ if (card.revision === undefined) {
22
+ return card;
23
+ }
24
+ const copy = { ...card };
25
+ delete copy.revision;
26
+ return copy;
27
+ }
28
+ function withRevision(card, id) {
29
+ const revision = revisions.get(id);
30
+ return revision === undefined ? card : { ...card, revision: String(revision) };
31
+ }
32
+ // Bumps and returns the new revision for `id` — the one real,
33
+ // changing-on-every-write revision this board carries. `createCard`
34
+ // starts a card at revision 1; every accepted `writeState` or
35
+ // `annotate` call bumps it again, so a caller that just read a card's
36
+ // revision via `get`/`list` can hand it straight back as
37
+ // `expectedRevision` and know a concurrent write will be caught, not
38
+ // silently overwritten.
39
+ function bumpRevision(id) {
40
+ const next = (revisions.get(id) ?? 0) + 1;
41
+ revisions.set(id, next);
42
+ return String(next);
43
+ }
44
+ // Checks `options.expectedRevision` against this board's own revision
45
+ // for `id`, when one was supplied. `undefined` means the caller did
46
+ // not ask for the guard at all — last-write-wins, exactly as every
47
+ // write here behaved before this option existed. A mismatch is
48
+ // reported as `stale`, naming the id and this board's current
49
+ // revision — the board made a real decision and the caller is
50
+ // holding an old one, so the remedy is to re-read and decide again,
51
+ // not to blindly retry (see `board.ts`'s `WriteResult` doc for why
52
+ // that is a different fact from `contentionExhausted`).
53
+ function revisionMismatch(id, options) {
54
+ if (options?.expectedRevision === undefined) {
55
+ return undefined;
56
+ }
57
+ const actual = String(revisions.get(id) ?? 0);
58
+ if (actual !== options.expectedRevision) {
59
+ return {
60
+ outcome: 'stale',
61
+ id,
62
+ reason: `revision mismatch for card ${id}: expected ${options.expectedRevision}, found ${actual}`,
63
+ currentRevision: actual,
64
+ };
65
+ }
66
+ return undefined;
67
+ }
68
+ return {
69
+ async get(id) {
70
+ if (unreachableReason !== undefined) {
71
+ return { outcome: 'unreachable', reason: unreachableReason };
72
+ }
73
+ const card = cards.get(id);
74
+ if (card === undefined) {
75
+ return { outcome: 'absent' };
76
+ }
77
+ return { outcome: 'found', card: withRevision(card, id) };
78
+ },
79
+ async list() {
80
+ if (unreachableReason !== undefined) {
81
+ return { outcome: 'unreachable', reason: unreachableReason };
82
+ }
83
+ if (cards.size === 0) {
84
+ return { outcome: 'empty' };
85
+ }
86
+ // Every card in here was validated on the way in (see `put`'s
87
+ // caller obligations) and never stored any other way, so there is
88
+ // never anything to report as unparseable — the field exists
89
+ // because `ListResult` is shared with sources that store raw
90
+ // payloads (see `payload-board.ts`), not because this board can
91
+ // produce it. `danglingIds` is empty for the same class of reason:
92
+ // this board has no separately-maintained index that could name an
93
+ // id the board itself does not also hold — the map is the whole
94
+ // board (see `store-board.ts` for the board that does keep such an
95
+ // index, and can therefore disagree with itself).
96
+ return {
97
+ outcome: 'cards',
98
+ cards: Array.from(cards.entries()).map(([id, card]) => withRevision(card, id)),
99
+ unparseable: [],
100
+ danglingIds: [],
101
+ };
102
+ },
103
+ async writeState(id, state, options) {
104
+ if (unreachableReason !== undefined) {
105
+ return { outcome: 'unreachable', reason: unreachableReason };
106
+ }
107
+ const card = cards.get(id);
108
+ if (card === undefined) {
109
+ return { outcome: 'refused', reason: `no card with id ${id}` };
110
+ }
111
+ const mismatch = revisionMismatch(id, options);
112
+ if (mismatch !== undefined) {
113
+ return mismatch;
114
+ }
115
+ bumpRevision(id);
116
+ cards.set(id, { ...card, state });
117
+ return { outcome: 'applied' };
118
+ },
119
+ async createCard(card) {
120
+ if (unreachableReason !== undefined) {
121
+ return { outcome: 'unreachable', reason: unreachableReason };
122
+ }
123
+ if (cards.has(card.id)) {
124
+ return { outcome: 'refused', reason: `card ${card.id} already exists` };
125
+ }
126
+ revisions.set(card.id, 1);
127
+ cards.set(card.id, stripOwnRevision(card));
128
+ return { outcome: 'applied' };
129
+ },
130
+ async annotate(id, patch, options) {
131
+ if (unreachableReason !== undefined) {
132
+ return { outcome: 'unreachable', reason: unreachableReason };
133
+ }
134
+ const card = cards.get(id);
135
+ if (card === undefined) {
136
+ return { outcome: 'refused', reason: `no card with id ${id}` };
137
+ }
138
+ const mismatch = revisionMismatch(id, options);
139
+ if (mismatch !== undefined) {
140
+ return mismatch;
141
+ }
142
+ bumpRevision(id);
143
+ cards.set(id, {
144
+ ...card,
145
+ properties: { ...card.properties, ...patch.properties },
146
+ });
147
+ return { outcome: 'applied' };
148
+ },
149
+ setUnreachable(reason) {
150
+ unreachableReason = reason;
151
+ },
152
+ setReachable() {
153
+ unreachableReason = undefined;
154
+ },
155
+ put(card) {
156
+ revisions.set(card.id, revisions.get(card.id) ?? 1);
157
+ cards.set(card.id, stripOwnRevision(card));
158
+ },
159
+ };
160
+ }
@@ -0,0 +1,26 @@
1
+ import type { Store } from './store.js';
2
+ export interface InMemoryStore<V> extends Store<V> {
3
+ /**
4
+ * Makes the next `count` calls to `replace` report `conflict`
5
+ * unconditionally — even for a call whose `expected` genuinely
6
+ * matches what is stored. Models another writer winning the race this
7
+ * call would otherwise have won. Calls beyond `count` compare
8
+ * `expected` for real, exactly as `replace` always does once this
9
+ * budget is spent.
10
+ */
11
+ failNextReplace(count: number): void;
12
+ /**
13
+ * Sets the stored value at `key` directly, bypassing `create` and
14
+ * `replace` entirely — not part of `Store`, and not meant to model
15
+ * anything a real backend does. Test setup only: this is how a test
16
+ * puts a "concurrent writer's" change in place at a chosen moment,
17
+ * without needing this fake to be genuinely concurrent to prove a
18
+ * retry loop reads it on its next attempt.
19
+ */
20
+ forceSet(key: string, value: V): void;
21
+ /** Mirrors `InMemoryBoard.setUnreachable` — checked before content. */
22
+ setUnreachable(reason: string): void;
23
+ /** Undoes `setUnreachable`. */
24
+ setReachable(): void;
25
+ }
26
+ export declare function createInMemoryStore<V>(): InMemoryStore<V>;
@@ -0,0 +1,79 @@
1
+ // An in-memory, deliberately adversarial `Store` — a fake good enough to
2
+ // stand in for a real conditional-write backend in a test, the same way
3
+ // `InMemoryBoard` and `PayloadBoard` stand in for a real tracker.
4
+ //
5
+ // A fake that simply works is *more consistent than the real thing*: two
6
+ // calls to `replace` against a plain in-memory map, made one after
7
+ // another by a test, can never actually race — there is no window for a
8
+ // second writer to land between this fake's own read and its own write,
9
+ // because nothing here is concurrent. A store-backed board's retry loop
10
+ // exists to survive exactly the case a naive fake cannot produce, so a
11
+ // suite built only against a naive fake would prove nothing about the
12
+ // mechanism that exists to survive conflict — the retry loop would look
13
+ // safe having never once been exercised. This fake can therefore be told
14
+ // to misbehave on command: to report `conflict` on the next call to
15
+ // `replace` (or the next several) regardless of whether the caller's
16
+ // `expected` genuinely matches what is stored, and to have its stored
17
+ // value changed out from under a caller directly, simulating a
18
+ // concurrent writer's change landing at a chosen moment. Contention
19
+ // injected on purpose, not incidental, so the mechanism that exists to
20
+ // survive it is the thing actually being exercised.
21
+ function sameValue(a, b) {
22
+ // Value equality, not identity — see `store.ts`'s note on what this
23
+ // costs for values equality-by-JSON cannot describe honestly.
24
+ return JSON.stringify(a) === JSON.stringify(b);
25
+ }
26
+ export function createInMemoryStore() {
27
+ const values = new Map();
28
+ let unreachableReason;
29
+ let forcedConflicts = 0;
30
+ return {
31
+ async create(key, value) {
32
+ if (unreachableReason !== undefined) {
33
+ return { outcome: 'unreachable', reason: unreachableReason };
34
+ }
35
+ if (values.get(key) !== undefined) {
36
+ return { outcome: 'alreadyExists' };
37
+ }
38
+ values.set(key, value);
39
+ return { outcome: 'created' };
40
+ },
41
+ async read(key) {
42
+ if (unreachableReason !== undefined) {
43
+ return { outcome: 'unreachable', reason: unreachableReason };
44
+ }
45
+ const value = values.get(key);
46
+ return value === undefined ? { outcome: 'absent' } : { outcome: 'found', value };
47
+ },
48
+ async replace(key, value, expected) {
49
+ if (unreachableReason !== undefined) {
50
+ return { outcome: 'unreachable', reason: unreachableReason };
51
+ }
52
+ const current = values.get(key);
53
+ if (current === undefined) {
54
+ return { outcome: 'absent' };
55
+ }
56
+ if (forcedConflicts > 0) {
57
+ forcedConflicts -= 1;
58
+ return { outcome: 'conflict' };
59
+ }
60
+ if (!sameValue(current, expected)) {
61
+ return { outcome: 'conflict' };
62
+ }
63
+ values.set(key, value);
64
+ return { outcome: 'applied' };
65
+ },
66
+ failNextReplace(count) {
67
+ forcedConflicts = count;
68
+ },
69
+ forceSet(key, value) {
70
+ values.set(key, value);
71
+ },
72
+ setUnreachable(reason) {
73
+ unreachableReason = reason;
74
+ },
75
+ setReachable() {
76
+ unreachableReason = undefined;
77
+ },
78
+ };
79
+ }
@@ -0,0 +1,22 @@
1
+ export { parseCard } from './card.js';
2
+ export type { Card, Problem, ParseResult, State } from './card.js';
3
+ export type { CardSource, CardSink, GetResult, ListResult, WriteResult, UnparseableRecord, AnnotatePatch, WriteOptions, CardClaimer, ClaimResult, NominateClaimResult, CompletionOptions, CompletionResult, RunOutcome, } from './board.js';
4
+ export { createInMemoryBoard } from './in-memory-board.js';
5
+ export type { InMemoryBoard } from './in-memory-board.js';
6
+ export { createPayloadBoard } from './payload-board.js';
7
+ export type { PayloadBoard } from './payload-board.js';
8
+ export { createNotionBoard, NOTION_VERSION } from './notion-board.js';
9
+ export type { NotionBoard, NotionBoardConfig, NotionFetch, NotionFetchInit, NotionFetchResponse, } from './notion-board.js';
10
+ export { asfBoard } from './asf-board.js';
11
+ export type { AsfBoardOptions, AsfFetch, AsfFetchInit, AsfFetchResponse } from './asf-board.js';
12
+ export { parseCardPayload, renderCardPayload } from './payload.js';
13
+ export { moveCard } from './move-card.js';
14
+ export type { MoveCardRequest, MoveResult } from './move-card.js';
15
+ export { assessUnparseable } from './schema-change.js';
16
+ export type { UnparseableListing, SchemaChangeGroup, SchemaChangeAssessment, } from './schema-change.js';
17
+ export type { Store, CreateResult, ReadResult, ReplaceResult } from './store.js';
18
+ export { createInMemoryStore } from './in-memory-store.js';
19
+ export type { InMemoryStore } from './in-memory-store.js';
20
+ export { createStoreBoard } from './store-board.js';
21
+ export type { StoreBoard } from './store-board.js';
22
+ export { createMultiplexer, type Multiplexer, type RouteRefusal, type BoardScheme, } from './multiplexer.js';
package/dist/index.js ADDED
@@ -0,0 +1,15 @@
1
+ // The package surface. The scaffolding placeholder that used to live here —
2
+ // `packageName`, kept only so the toolchain had something real to
3
+ // typecheck, lint and test — is gone: this project's first real export has
4
+ // landed, which was the condition it was written to be removed on.
5
+ export { parseCard } from './card.js';
6
+ export { createInMemoryBoard } from './in-memory-board.js';
7
+ export { createPayloadBoard } from './payload-board.js';
8
+ export { createNotionBoard, NOTION_VERSION } from './notion-board.js';
9
+ export { asfBoard } from './asf-board.js';
10
+ export { parseCardPayload, renderCardPayload } from './payload.js';
11
+ export { moveCard } from './move-card.js';
12
+ export { assessUnparseable } from './schema-change.js';
13
+ export { createInMemoryStore } from './in-memory-store.js';
14
+ export { createStoreBoard } from './store-board.js';
15
+ export { createMultiplexer, } from './multiplexer.js';
@@ -0,0 +1,141 @@
1
+ import type { Card, Problem, State } from './card.js';
2
+ import type { CardSource, CardSink } from './board.js';
3
+ export interface MoveCardRequest {
4
+ readonly source: CardSource;
5
+ readonly sink: CardSink;
6
+ readonly id: string;
7
+ readonly to: State;
8
+ }
9
+ /**
10
+ * Nine outcomes, not two.
11
+ *
12
+ * `moved` and `alreadyInState` are both success, and are kept apart on
13
+ * purpose: a caller deciding whether to announce anything — post a
14
+ * comment, fire a webhook, tell a user "moved to Done" — needs to know
15
+ * whether anything actually changed. "The card moved to Done" and "the
16
+ * card was already in Done" are different sentences, even though both
17
+ * end with the same card in the same state.
18
+ *
19
+ * `moved` carries the card **as it now reads**, not as it was asked to
20
+ * become — see `moveCard`'s second read, below, for why that is not the
21
+ * same thing and not a redundant step.
22
+ *
23
+ * `noSuchCard`, `unreachable`, `unparseable`, `refused`,
24
+ * `contentionExhausted`, `stale` and `unsupported` are the seven ways
25
+ * not to move a card, and every one of them is a name this file
26
+ * borrows, not invents: `board.ts`
27
+ * already named `absent`, `unreachable` and `unparseable` on the read
28
+ * side, and `refused`, `unreachable`, `contentionExhausted`, `stale`
29
+ * and `unsupported` on the write side (`moveCard` renames `absent` to
30
+ * `noSuchCard` — the shape a source reports finding nothing is not the
31
+ * shape a caller of *this* use case is asking about; everything else
32
+ * keeps the underlying port's own word). A caller can tell a missing
33
+ * card from an unreachable board, or an unreachable board from a
34
+ * refused write, without reading this file's source — because the
35
+ * name it gets back is the name the port beneath already used for
36
+ * that fact.
37
+ *
38
+ * `contentionExhausted` is handled the same way, deliberately, rather
39
+ * than by retrying it away here. A sink that reports it has already
40
+ * retried its own compare-and-set loop up to its own bound (see
41
+ * `store-board.ts`) — a second retry at this layer would either
42
+ * busy-loop against data very likely still contended, with no backoff
43
+ * this generic use case has any basis to choose, or would require
44
+ * `moveCard` to own scheduling policy that varies by sink and does not
45
+ * belong in a use case written against any `CardSource`/`CardSink` pair.
46
+ * The caller that invoked `moveCard` has context this file does not —
47
+ * whether the move is urgent, whether it should be queued and retried
48
+ * later, whether a human should be told — so `contentionExhausted` is
49
+ * surfaced under its own name, not folded into `refused` (which would
50
+ * lose exactly the distinction this variant exists to keep) and not
51
+ * silently retried on the caller's behalf.
52
+ *
53
+ * `stale` is handled the same way, for the same reason — explicitly,
54
+ * rather than left to fall through to the confirming read as though
55
+ * the write had applied. `moveCard` never supplies `expectedRevision`
56
+ * to `writeState` itself, so this branch is not reachable through this
57
+ * file's own calls today; it is handled anyway, because a `WriteResult`
58
+ * variant this file does not recognise must never silently read as
59
+ * success.
60
+ *
61
+ * `unsupported` is handled the same way too, and for the same reason:
62
+ * a sink with no compare-and-set primitive underneath it answers any
63
+ * guarded write with `unsupported`, naming the card it concerns, and
64
+ * that name is relayed rather than read as success — the same
65
+ * discipline `stale` gets, and for the same reason this use case never
66
+ * supplies `expectedRevision` on its own account either.
67
+ */
68
+ export type MoveResult = {
69
+ readonly outcome: 'moved';
70
+ readonly card: Card;
71
+ } | {
72
+ readonly outcome: 'alreadyInState';
73
+ readonly card: Card;
74
+ } | {
75
+ readonly outcome: 'noSuchCard';
76
+ } | {
77
+ readonly outcome: 'unreachable';
78
+ readonly reason: string;
79
+ } | {
80
+ readonly outcome: 'unparseable';
81
+ readonly id: string;
82
+ readonly problems: readonly Problem[];
83
+ } | {
84
+ readonly outcome: 'refused';
85
+ readonly reason: string;
86
+ } | {
87
+ readonly outcome: 'contentionExhausted';
88
+ readonly reason: string;
89
+ } | {
90
+ readonly outcome: 'stale';
91
+ readonly id: string;
92
+ readonly reason: string;
93
+ readonly currentRevision?: string;
94
+ } | {
95
+ readonly outcome: 'unsupported';
96
+ readonly id: string;
97
+ readonly reason: string;
98
+ };
99
+ /**
100
+ * Moves one card to a target state, or reports why it could not.
101
+ *
102
+ * Reads before writing. If the card is already in `to`, the sink is
103
+ * never touched — the check happens before any write is attempted, not
104
+ * after a write that happened to be a no-op, so a caller watching a
105
+ * counting fake sees zero calls to `writeState` for an already-there
106
+ * card, not one.
107
+ *
108
+ * Reads again after a successful write, rather than trusting the
109
+ * write's own report. `WriteResult`'s `applied` carries no card — it
110
+ * cannot; `board.ts` defines the sink as writing one field and nothing
111
+ * else — so there is no way to know what the tracker now holds without
112
+ * asking it again. That second read costs a full round trip on every
113
+ * successful move, spent on purpose: `applied` is a claim the sink made
114
+ * about the request it received, not a claim about what the tracker now
115
+ * contains. A tracker that normalises the value it was given, or that
116
+ * accepts a write and silently keeps its old state, is a real tracker
117
+ * behaviour this file has no way to rule out from `applied` alone.
118
+ * `moved` reports whatever the second read finds, verbatim — including
119
+ * a state that does not equal `to` — rather than asserting the request
120
+ * succeeded and echoing `to` back as if it had been confirmed. Echoing
121
+ * the request back is how a system reports success it did not have.
122
+ *
123
+ * That second read can itself come back as anything `get` can report —
124
+ * the card gone, the board unreachable, the stored record unparseable —
125
+ * and each is passed through under its own name for the same reason the
126
+ * first read's outcomes are: they are real facts about a tracker this
127
+ * boundary does not control, not failures of this use case to paper
128
+ * over.
129
+ *
130
+ * Deliberately does not compare the confirmed state to `to` and does
131
+ * not invent a further outcome for a mismatch. Whether a state that
132
+ * doesn't match what was asked means "the tracker normalised it" or
133
+ * "the tracker silently ignored the write" is not a distinction this
134
+ * file, or the ports beneath it, has the evidence to make — guessing
135
+ * would be inventing a seventh outcome on no more information than
136
+ * `moved` already carries. A caller that cares compares
137
+ * `result.card.state` to what it asked for; `moveCard` hands over the
138
+ * truth and lets that comparison happen where the context to interpret
139
+ * it actually lives.
140
+ */
141
+ export declare function moveCard(request: MoveCardRequest): Promise<MoveResult>;
@@ -0,0 +1,104 @@
1
+ // moveCard: a task moving across a board — the demo this repository
2
+ // exists to make possible, and the first thing here that composes ports
3
+ // rather than defining one.
4
+ //
5
+ // Everything up to this file is a boundary: a card shape, a read half and
6
+ // a write half, two fakes, a parser. Nothing yet moves a card. moveCard
7
+ // takes a source, a sink, an id and a target state, and answers "what
8
+ // happened when I tried to move this card" — reading, deciding whether
9
+ // there is anything to do, writing, and confirming. It is written as a
10
+ // use case over `CardSource`/`CardSink`, not as a method on a board,
11
+ // because moving a card needs both halves of this boundary and neither
12
+ // half owns the other — this is exactly the shape an adapter for a real
13
+ // tracker plugs in underneath, the same way `InMemoryBoard` and
14
+ // `PayloadBoard` already do.
15
+ /**
16
+ * Moves one card to a target state, or reports why it could not.
17
+ *
18
+ * Reads before writing. If the card is already in `to`, the sink is
19
+ * never touched — the check happens before any write is attempted, not
20
+ * after a write that happened to be a no-op, so a caller watching a
21
+ * counting fake sees zero calls to `writeState` for an already-there
22
+ * card, not one.
23
+ *
24
+ * Reads again after a successful write, rather than trusting the
25
+ * write's own report. `WriteResult`'s `applied` carries no card — it
26
+ * cannot; `board.ts` defines the sink as writing one field and nothing
27
+ * else — so there is no way to know what the tracker now holds without
28
+ * asking it again. That second read costs a full round trip on every
29
+ * successful move, spent on purpose: `applied` is a claim the sink made
30
+ * about the request it received, not a claim about what the tracker now
31
+ * contains. A tracker that normalises the value it was given, or that
32
+ * accepts a write and silently keeps its old state, is a real tracker
33
+ * behaviour this file has no way to rule out from `applied` alone.
34
+ * `moved` reports whatever the second read finds, verbatim — including
35
+ * a state that does not equal `to` — rather than asserting the request
36
+ * succeeded and echoing `to` back as if it had been confirmed. Echoing
37
+ * the request back is how a system reports success it did not have.
38
+ *
39
+ * That second read can itself come back as anything `get` can report —
40
+ * the card gone, the board unreachable, the stored record unparseable —
41
+ * and each is passed through under its own name for the same reason the
42
+ * first read's outcomes are: they are real facts about a tracker this
43
+ * boundary does not control, not failures of this use case to paper
44
+ * over.
45
+ *
46
+ * Deliberately does not compare the confirmed state to `to` and does
47
+ * not invent a further outcome for a mismatch. Whether a state that
48
+ * doesn't match what was asked means "the tracker normalised it" or
49
+ * "the tracker silently ignored the write" is not a distinction this
50
+ * file, or the ports beneath it, has the evidence to make — guessing
51
+ * would be inventing a seventh outcome on no more information than
52
+ * `moved` already carries. A caller that cares compares
53
+ * `result.card.state` to what it asked for; `moveCard` hands over the
54
+ * truth and lets that comparison happen where the context to interpret
55
+ * it actually lives.
56
+ */
57
+ export async function moveCard(request) {
58
+ const { source, sink, id, to } = request;
59
+ const before = await source.get(id);
60
+ if (before.outcome === 'unreachable') {
61
+ return { outcome: 'unreachable', reason: before.reason };
62
+ }
63
+ if (before.outcome === 'unparseable') {
64
+ return { outcome: 'unparseable', id: before.id, problems: before.problems };
65
+ }
66
+ if (before.outcome === 'absent') {
67
+ return { outcome: 'noSuchCard' };
68
+ }
69
+ if (before.card.state === to) {
70
+ return { outcome: 'alreadyInState', card: before.card };
71
+ }
72
+ const write = await sink.writeState(id, to);
73
+ if (write.outcome === 'unreachable') {
74
+ return { outcome: 'unreachable', reason: write.reason };
75
+ }
76
+ if (write.outcome === 'contentionExhausted') {
77
+ return { outcome: 'contentionExhausted', reason: write.reason };
78
+ }
79
+ if (write.outcome === 'stale') {
80
+ return {
81
+ outcome: 'stale',
82
+ id: write.id,
83
+ reason: write.reason,
84
+ ...(write.currentRevision !== undefined ? { currentRevision: write.currentRevision } : {}),
85
+ };
86
+ }
87
+ if (write.outcome === 'unsupported') {
88
+ return { outcome: 'unsupported', id: write.id, reason: write.reason };
89
+ }
90
+ if (write.outcome === 'refused') {
91
+ return { outcome: 'refused', reason: write.reason };
92
+ }
93
+ const after = await source.get(id);
94
+ if (after.outcome === 'unreachable') {
95
+ return { outcome: 'unreachable', reason: after.reason };
96
+ }
97
+ if (after.outcome === 'unparseable') {
98
+ return { outcome: 'unparseable', id: after.id, problems: after.problems };
99
+ }
100
+ if (after.outcome === 'absent') {
101
+ return { outcome: 'noSuchCard' };
102
+ }
103
+ return { outcome: 'moved', card: after.card };
104
+ }
@@ -0,0 +1,55 @@
1
+ import type { CardSource, CardSink, GetResult, ListResult, WriteResult, WriteOptions, AnnotatePatch } from './board.js';
2
+ import type { Card, State } from './card.js';
3
+ export type BoardScheme = 'file' | 'trello' | 'notion' | 'obsidian' | 'asf';
4
+ export type Board = CardSource & CardSink;
5
+ /**
6
+ * A routing miss: no board was asked, so no tracker said anything.
7
+ *
8
+ * Kept apart from every `GetResult`/`ListResult`/`WriteResult` variant on
9
+ * purpose. `refused` means a tracker was reached and said no; `absent` means
10
+ * one was asked and holds nothing; `empty` means it answered with nothing on
11
+ * the board; `unreachable` means a registered board could not be contacted.
12
+ * A routing miss is none of those, and folding it into any of them would
13
+ * misreport what happened.
14
+ *
15
+ * - `unregisteredScheme`: the URL parsed, but no board is registered for its
16
+ * scheme (including schemes outside `BoardScheme`).
17
+ * - `malformedBoardUrl`: no `scheme://` prefix could be read.
18
+ */
19
+ export type RouteRefusal = {
20
+ readonly outcome: 'unregisteredScheme';
21
+ readonly scheme: string;
22
+ readonly boardUrl: string;
23
+ readonly reason: string;
24
+ } | {
25
+ readonly outcome: 'malformedBoardUrl';
26
+ readonly boardUrl: string;
27
+ readonly reason: string;
28
+ };
29
+ /**
30
+ * Dispatches by board URL to exactly one registered board per scheme.
31
+ *
32
+ * One board per scheme because a `CardSource`/`CardSink` is scoped to a
33
+ * single board when it is built (see `board.ts`), so the URL only selects
34
+ * which already-scoped board answers.
35
+ *
36
+ * Every method returns either `RouteRefusal` (nothing was called) or the
37
+ * resolved board's own result unchanged, including its `unreachable`,
38
+ * `unparseable`, `refused`, `contentionExhausted`, `stale` and
39
+ * `unsupported` outcomes. Nothing is caught here: a board's outcomes
40
+ * pass through untouched.
41
+ */
42
+ export interface Multiplexer {
43
+ get(boardUrl: string, id: string): Promise<GetResult | RouteRefusal>;
44
+ list(boardUrl: string): Promise<ListResult | RouteRefusal>;
45
+ writeState(boardUrl: string, id: string, state: State, options?: WriteOptions): Promise<WriteResult | RouteRefusal>;
46
+ createCard(boardUrl: string, card: Card): Promise<WriteResult | RouteRefusal>;
47
+ /**
48
+ * Routes a properties-only patch to the board registered for
49
+ * `boardUrl`'s scheme, exactly as every other method here does — a
50
+ * routing miss is `RouteRefusal`, never folded into the resolved
51
+ * board's own `refused`/`unreachable`/`contentionExhausted`/`stale`.
52
+ */
53
+ annotate(boardUrl: string, id: string, patch: AnnotatePatch, options?: WriteOptions): Promise<WriteResult | RouteRefusal>;
54
+ }
55
+ export declare function createMultiplexer(boards: Partial<Record<BoardScheme, Board>>): Multiplexer;
@@ -0,0 +1,54 @@
1
+ // Routes tracker calls to the one board registered for a board URL's scheme.
2
+ const SCHEME_PATTERN = /^([a-z][a-z0-9+.-]*):\/\//i;
3
+ export function createMultiplexer(boards) {
4
+ // Copied so a later mutation of the caller's object cannot reroute calls.
5
+ const registered = new Map();
6
+ for (const [scheme, board] of Object.entries(boards)) {
7
+ if (board !== undefined) {
8
+ registered.set(scheme.toLowerCase(), board);
9
+ }
10
+ }
11
+ function resolve(boardUrl) {
12
+ const match = SCHEME_PATTERN.exec(boardUrl);
13
+ if (match === null) {
14
+ return {
15
+ outcome: 'malformedBoardUrl',
16
+ boardUrl,
17
+ reason: `board url "${boardUrl}" has no scheme:// prefix`,
18
+ };
19
+ }
20
+ const scheme = match[1].toLowerCase();
21
+ const board = registered.get(scheme);
22
+ if (board === undefined) {
23
+ return {
24
+ outcome: 'unregisteredScheme',
25
+ scheme,
26
+ boardUrl,
27
+ reason: `no board registered for scheme "${scheme}"`,
28
+ };
29
+ }
30
+ return { board };
31
+ }
32
+ return {
33
+ async get(boardUrl, id) {
34
+ const r = resolve(boardUrl);
35
+ return 'board' in r ? r.board.get(id) : r;
36
+ },
37
+ async list(boardUrl) {
38
+ const r = resolve(boardUrl);
39
+ return 'board' in r ? r.board.list() : r;
40
+ },
41
+ async writeState(boardUrl, id, state, options) {
42
+ const r = resolve(boardUrl);
43
+ return 'board' in r ? r.board.writeState(id, state, options) : r;
44
+ },
45
+ async createCard(boardUrl, card) {
46
+ const r = resolve(boardUrl);
47
+ return 'board' in r ? r.board.createCard(card) : r;
48
+ },
49
+ async annotate(boardUrl, id, patch, options) {
50
+ const r = resolve(boardUrl);
51
+ return 'board' in r ? r.board.annotate(id, patch, options) : r;
52
+ },
53
+ };
54
+ }