@openplanr/protocol 0.18.0 → 0.19.0

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,71 @@
1
+ /** An authored reference field as a list: null or '' is none, a scalar is one reference. */
2
+ export function planningReferenceValues(value: unknown): readonly unknown[];
3
+
4
+ export type AttentionNode = Readonly<{
5
+ id: string;
6
+ type: string;
7
+ title: string;
8
+ status: 'outstanding' | 'in-progress' | 'blocked' | 'addressed' | 'done';
9
+ frontmatter: Readonly<Record<string, unknown>>;
10
+ }>;
11
+
12
+ export type AttentionGraph = Readonly<{
13
+ nodes: readonly AttentionNode[];
14
+ edges: readonly Readonly<{ from: string; to: string; kind: 'contains' | 'depends_on' }>[];
15
+ }>;
16
+
17
+ export type AttentionOptions = Readonly<{
18
+ quietDays?: number;
19
+ sprintLengthDays?: number;
20
+ }>;
21
+
22
+ export type AttentionItem = Readonly<{
23
+ id: string;
24
+ status: AttentionNode['status'] | 'unknown';
25
+ readiness: 'ready' | 'blocked' | 'unknown' | 'not-applicable';
26
+ dependencyIds: readonly string[];
27
+ openDependencyIds: readonly string[];
28
+ unresolvedDependencies: readonly Readonly<{
29
+ reference: string;
30
+ reason: 'missing' | 'ambiguous' | 'invalid';
31
+ candidates: readonly string[];
32
+ }>[];
33
+ downstreamUnblockCount: number;
34
+ }>;
35
+
36
+ export type AttentionProjection = Readonly<{
37
+ statusTotals: Readonly<{
38
+ total: number;
39
+ outstanding: number;
40
+ inProgress: number;
41
+ addressed: number;
42
+ done: number;
43
+ unknown: number;
44
+ blocked: number;
45
+ }>;
46
+ byId: Readonly<Record<string, AttentionItem>>;
47
+ waiting: readonly AttentionItem[];
48
+ stale: readonly Readonly<{ id: string; authoredAt: string; ageDays: number }>[];
49
+ unknownStaleIds: readonly string[];
50
+ quietDays: number;
51
+ highPriorityNotStarted: readonly string[];
52
+ changedToday: Readonly<{
53
+ date: string;
54
+ ids: readonly string[];
55
+ groups: readonly Readonly<{ specId: string | null; ids: readonly string[] }>[];
56
+ }>;
57
+ perSpec: readonly Readonly<{
58
+ id: string;
59
+ done: number;
60
+ total: number;
61
+ taskIds: readonly string[];
62
+ }>[];
63
+ dependencyCycleIds: readonly string[];
64
+ containmentCycleIds: readonly string[];
65
+ }>;
66
+
67
+ export function deriveAttention(
68
+ graph: AttentionGraph,
69
+ nowUTC: string,
70
+ options?: AttentionOptions,
71
+ ): AttentionProjection;
@@ -0,0 +1,324 @@
1
+ const DAY_MS = 86_400_000;
2
+ const STATUSES = new Set(['outstanding', 'in-progress', 'blocked', 'addressed', 'done']);
3
+ const PRIORITIES = new Map([
4
+ ['p0', 0],
5
+ ['critical', 0],
6
+ ['p1', 1],
7
+ ['high', 1],
8
+ ['p2', 2],
9
+ ['medium', 2],
10
+ ['p3', 3],
11
+ ['low', 3],
12
+ ]);
13
+
14
+ /** An authored reference field as a list: null or '' is none, a scalar is one reference. */
15
+ export function planningReferenceValues(value) {
16
+ if (Array.isArray(value)) return value;
17
+ return value == null || value === '' ? [] : [value];
18
+ }
19
+
20
+ function compareId(left, right) {
21
+ return left < right ? -1 : left > right ? 1 : 0;
22
+ }
23
+
24
+ function terminal(node) {
25
+ return node.status === 'done' || node.status === 'addressed';
26
+ }
27
+
28
+ function priority(node) {
29
+ return (
30
+ PRIORITIES.get(
31
+ String(node.frontmatter.priority ?? '')
32
+ .trim()
33
+ .toLowerCase(),
34
+ ) ?? 4
35
+ );
36
+ }
37
+
38
+ function timestamp(value) {
39
+ if (typeof value !== 'string') return null;
40
+ const match = /^(\d{4}-\d{2}-\d{2})(?:T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2}))?$/u.exec(
41
+ value,
42
+ );
43
+ if (!match) return null;
44
+ // Date.parse normalizes impossible calendar days, which would fabricate authored evidence.
45
+ const calendar = Date.parse(`${match[1]}T00:00:00.000Z`);
46
+ if (!Number.isFinite(calendar) || new Date(calendar).toISOString().slice(0, 10) !== match[1])
47
+ return null;
48
+ const parsed = Date.parse(value);
49
+ return Number.isFinite(parsed) ? parsed : null;
50
+ }
51
+
52
+ function freeze(value) {
53
+ if (value && typeof value === 'object') {
54
+ for (const child of Object.values(value)) freeze(child);
55
+ Object.freeze(value);
56
+ }
57
+ return value;
58
+ }
59
+
60
+ function reachable(start, adjacency) {
61
+ const seen = new Set([start]);
62
+ const pending = [...(adjacency.get(start) ?? [])];
63
+ while (pending.length) {
64
+ const id = pending.pop();
65
+ if (seen.has(id)) continue;
66
+ seen.add(id);
67
+ pending.push(...(adjacency.get(id) ?? []));
68
+ }
69
+ seen.delete(start);
70
+ return [...seen];
71
+ }
72
+
73
+ function findCycles(adjacency) {
74
+ const seen = new Set();
75
+ const order = [];
76
+ const reverse = new Map([...adjacency.keys()].map((id) => [id, new Set()]));
77
+ for (const [id, targets] of adjacency) for (const target of targets) reverse.get(target).add(id);
78
+ // Iterative component traversal handles long chains and overlapping cycles without stack limits.
79
+ for (const start of adjacency.keys()) {
80
+ if (seen.has(start)) continue;
81
+ seen.add(start);
82
+ const stack = [{ id: start, targets: adjacency.get(start).values() }];
83
+ while (stack.length) {
84
+ const frame = stack.at(-1);
85
+ const next = frame.targets.next();
86
+ if (next.done) {
87
+ order.push(frame.id);
88
+ stack.pop();
89
+ } else if (!seen.has(next.value)) {
90
+ seen.add(next.value);
91
+ stack.push({ id: next.value, targets: adjacency.get(next.value).values() });
92
+ }
93
+ }
94
+ }
95
+ seen.clear();
96
+ const cycles = new Set();
97
+ for (const start of order.reverse()) {
98
+ if (seen.has(start)) continue;
99
+ // Restrict this pass to unvisited nodes so earlier components cannot be merged.
100
+ const pending = [start];
101
+ const members = [];
102
+ while (pending.length) {
103
+ const id = pending.pop();
104
+ if (seen.has(id)) continue;
105
+ seen.add(id);
106
+ members.push(id);
107
+ pending.push(...reverse.get(id));
108
+ }
109
+ if (members.length > 1 || adjacency.get(start).has(start))
110
+ for (const id of members) cycles.add(id);
111
+ }
112
+ return [...cycles].sort(compareId);
113
+ }
114
+
115
+ export function deriveAttention(graph, nowUTC, options = {}) {
116
+ const now = timestamp(nowUTC);
117
+ if (now === null || !nowUTC.endsWith('Z')) throw new TypeError('nowUTC must be a UTC instant.');
118
+ const sprintLengthDays = options.sprintLengthDays ?? 14;
119
+ const quietDays = options.quietDays ?? Math.ceil(sprintLengthDays / 2);
120
+ if (!Number.isInteger(sprintLengthDays) || sprintLengthDays < 1 || sprintLengthDays > 366)
121
+ throw new RangeError('sprintLengthDays must be an integer from 1 to 366.');
122
+ if (!Number.isInteger(quietDays) || quietDays < 1 || quietDays > 365)
123
+ throw new RangeError('quietDays must be an integer from 1 to 365.');
124
+
125
+ const nodes = new Map();
126
+ for (const node of graph.nodes) {
127
+ const previous = nodes.get(node.id);
128
+ if (previous && JSON.stringify(previous) !== JSON.stringify(node))
129
+ throw new TypeError(`Conflicting graph identity: ${node.id}`);
130
+ nodes.set(node.id, node);
131
+ }
132
+ const ids = [...nodes.keys()].sort(compareId);
133
+ const aliases = new Map();
134
+ const dependencies = new Map(ids.map((id) => [id, new Set()]));
135
+ const parents = new Map(ids.map((id) => [id, new Set()]));
136
+ const dependents = new Map(ids.map((id) => [id, new Set()]));
137
+ const unresolved = new Map(ids.map((id) => [id, new Map()]));
138
+ for (const id of ids) {
139
+ const local = id.split('/').at(-1);
140
+ if (!aliases.has(local)) aliases.set(local, []);
141
+ aliases.get(local).push(id);
142
+ }
143
+ const resolve = (reference, sourceId) => {
144
+ if (typeof reference !== 'string') return { id: null, reason: 'invalid', candidates: [] };
145
+ if (reference.includes('/'))
146
+ return nodes.has(reference)
147
+ ? { id: reference }
148
+ : { id: null, reason: 'missing', candidates: [] };
149
+ const scope =
150
+ nodes.get(sourceId).frontmatter.specScope ??
151
+ (sourceId.includes('/') ? sourceId.slice(0, sourceId.lastIndexOf('/')) : null);
152
+ const scoped = typeof scope === 'string' && !/^SPEC-\d+/u.test(reference);
153
+ const target = scoped ? `${scope}/${reference}` : reference;
154
+ const candidates = nodes.has(target) ? [target] : scoped ? [] : (aliases.get(reference) ?? []);
155
+ return candidates.length === 1
156
+ ? { id: candidates[0] }
157
+ : { id: null, reason: candidates.length ? 'ambiguous' : 'missing', candidates };
158
+ };
159
+ const addDependency = (source, reference, canonical = false) => {
160
+ if (!nodes.has(source)) throw new TypeError(`Missing graph edge source: ${source}`);
161
+ const resolved =
162
+ canonical && nodes.has(reference) ? { id: reference } : resolve(reference, source);
163
+ if (resolved.id) dependencies.get(source).add(resolved.id);
164
+ else {
165
+ const ref = typeof reference === 'string' ? reference : String(reference);
166
+ unresolved.get(source).set(ref, {
167
+ reference: ref,
168
+ reason: resolved.reason,
169
+ candidates: resolved.candidates,
170
+ });
171
+ }
172
+ };
173
+ for (const edge of graph.edges) {
174
+ if (edge.kind === 'depends_on') addDependency(edge.from, edge.to, true);
175
+ else if (edge.kind === 'contains' && nodes.has(edge.from) && nodes.has(edge.to))
176
+ parents.get(edge.to).add(edge.from);
177
+ }
178
+ for (const node of nodes.values()) {
179
+ for (const reference of planningReferenceValues(node.frontmatter.dependsOn))
180
+ addDependency(node.id, reference);
181
+ }
182
+ for (const [id, targets] of dependencies) {
183
+ if (terminal(nodes.get(id))) continue;
184
+ for (const target of targets) if (!terminal(nodes.get(target))) dependents.get(target).add(id);
185
+ }
186
+
187
+ const specOf = (node) => {
188
+ if (node.type === 'spec') return node.id;
189
+ const scope = node.id.includes('/') ? node.id.split('/')[0] : null;
190
+ const explicit = scope ?? node.frontmatter.specScope ?? node.frontmatter.specId;
191
+ if (typeof explicit === 'string') return nodes.get(explicit)?.type === 'spec' ? explicit : null;
192
+ // Sprint membership and nested specs do not establish ownership of a task.
193
+ const owners = new Set();
194
+ const seen = new Set([node.id]);
195
+ const pending = [...parents.get(node.id)];
196
+ while (pending.length) {
197
+ const id = pending.pop();
198
+ if (seen.has(id)) continue;
199
+ seen.add(id);
200
+ const parent = nodes.get(id);
201
+ if (parent.type === 'spec') owners.add(id);
202
+ else if (parent.type !== 'sprint') pending.push(...parents.get(id));
203
+ }
204
+ return owners.size === 1 ? [...owners][0] : null;
205
+ };
206
+
207
+ const statusTotals = {
208
+ total: ids.length,
209
+ outstanding: 0,
210
+ inProgress: 0,
211
+ addressed: 0,
212
+ done: 0,
213
+ unknown: 0,
214
+ blocked: 0,
215
+ };
216
+ const byId = Object.create(null);
217
+ const waiting = [];
218
+ const stale = [];
219
+ const unknownStaleIds = [];
220
+ const highPriorityNotStarted = [];
221
+ const changedIds = [];
222
+ const changedGroups = new Map();
223
+ const specs = new Map(
224
+ ids
225
+ .filter((id) => nodes.get(id).type === 'spec')
226
+ .map((id) => [id, { id, done: 0, total: 0, taskIds: [] }]),
227
+ );
228
+ const today = new Date(now).toISOString().slice(0, 10);
229
+ for (const id of ids) {
230
+ const node = nodes.get(id);
231
+ const status = STATUSES.has(node.status) ? node.status : 'unknown';
232
+ // Blocked overlays open work, so it must not become an extra base-status bucket.
233
+ statusTotals[
234
+ status === 'blocked' ? 'outstanding' : status === 'in-progress' ? 'inProgress' : status
235
+ ] += 1;
236
+ const dependencyIds = [...dependencies.get(id)].sort(compareId);
237
+ const openDependencyIds = dependencyIds.filter((target) => !terminal(nodes.get(target)));
238
+ const unresolvedDependencies = [...unresolved.get(id).values()].sort((a, b) =>
239
+ compareId(a.reference, b.reference),
240
+ );
241
+ const readiness = terminal(node)
242
+ ? 'not-applicable'
243
+ : unresolvedDependencies.length ||
244
+ status === 'unknown' ||
245
+ (status === 'blocked' && !openDependencyIds.length)
246
+ ? 'unknown'
247
+ : openDependencyIds.length
248
+ ? 'blocked'
249
+ : 'ready';
250
+ const downstreamUnblockCount = reachable(id, dependents).filter(
251
+ (target) => nodes.get(target).type === 'task',
252
+ ).length;
253
+ const item = {
254
+ id,
255
+ status,
256
+ readiness,
257
+ dependencyIds,
258
+ openDependencyIds,
259
+ unresolvedDependencies,
260
+ downstreamUnblockCount,
261
+ };
262
+ byId[id] = item;
263
+ if (!terminal(node) && openDependencyIds.length) {
264
+ waiting.push(item);
265
+ statusTotals.blocked += 1;
266
+ }
267
+ if (status === 'outstanding' && priority(node) <= 1) highPriorityNotStarted.push(id);
268
+
269
+ const updated = timestamp(node.frontmatter.updated);
270
+ const created = timestamp(node.frontmatter.created);
271
+ const activity = node.frontmatter.updated == null ? created : updated;
272
+ if (status === 'in-progress') {
273
+ if (activity === null || activity > now) unknownStaleIds.push(id);
274
+ else if (now - activity >= quietDays * DAY_MS)
275
+ stale.push({
276
+ id,
277
+ authoredAt: new Date(activity).toISOString(),
278
+ ageDays: (now - activity) / DAY_MS,
279
+ });
280
+ }
281
+ const specId = specOf(node);
282
+ if (
283
+ activity !== null &&
284
+ activity <= now &&
285
+ new Date(activity).toISOString().slice(0, 10) === today
286
+ ) {
287
+ changedIds.push(id);
288
+ if (!changedGroups.has(specId)) changedGroups.set(specId, []);
289
+ changedGroups.get(specId).push(id);
290
+ }
291
+ if (node.type === 'task' && specs.has(specId)) {
292
+ const spec = specs.get(specId);
293
+ spec.taskIds.push(id);
294
+ spec.total += 1;
295
+ if (status === 'done') spec.done += 1;
296
+ }
297
+ }
298
+ const comparePriority = (left, right) =>
299
+ priority(nodes.get(left)) - priority(nodes.get(right)) || compareId(left, right);
300
+ waiting.sort(
301
+ (a, b) => b.downstreamUnblockCount - a.downstreamUnblockCount || comparePriority(a.id, b.id),
302
+ );
303
+ stale.sort((a, b) => b.ageDays - a.ageDays || compareId(a.id, b.id));
304
+ highPriorityNotStarted.sort(comparePriority);
305
+ return freeze({
306
+ statusTotals,
307
+ byId,
308
+ waiting,
309
+ stale,
310
+ unknownStaleIds,
311
+ quietDays,
312
+ highPriorityNotStarted,
313
+ changedToday: {
314
+ date: today,
315
+ ids: changedIds,
316
+ groups: [...changedGroups]
317
+ .sort(([a], [b]) => (a === null ? 1 : b === null ? -1 : compareId(a, b)))
318
+ .map(([specId, groupIds]) => ({ specId, ids: groupIds })),
319
+ },
320
+ perSpec: [...specs.values()],
321
+ dependencyCycleIds: findCycles(dependencies),
322
+ containmentCycleIds: findCycles(new Map(ids.map((id) => [id, parents.get(id)]))),
323
+ });
324
+ }
@@ -0,0 +1,47 @@
1
+ import type {
2
+ PlanningFileLinkContext,
3
+ PlanningFileLinkErrorCode,
4
+ } from './planning-file-link-contracts.mjs';
5
+
6
+ export const PLANNING_DIAGNOSTICS_MAX_BYTES: number;
7
+ export const PLANNING_DIAGNOSTICS_MAX_COUNT: 500;
8
+ export const PLANNING_DIAGNOSTIC_REASONS: readonly [
9
+ 'missing-reference',
10
+ 'ambiguous-reference',
11
+ 'invalid-date',
12
+ 'missing-date',
13
+ 'closed-before-start',
14
+ 'end-before-start',
15
+ 'dependency-cycle',
16
+ 'containment-cycle',
17
+ 'duplicate-identity',
18
+ 'unrecognized-identity',
19
+ ];
20
+ export type PlanningReadDiagnostic = Readonly<{
21
+ nodeId: string;
22
+ sourcePath: string;
23
+ field: string;
24
+ reason: (typeof PLANNING_DIAGNOSTIC_REASONS)[number];
25
+ classification: 'source-data';
26
+ }>;
27
+ export type PlanningDiagnosticsContext = Pick<PlanningFileLinkContext, 'binding' | 'cursor'>;
28
+ export type PlanningDiagnosticsEnvelope = Readonly<{
29
+ kind: 'planning-diagnostics';
30
+ schemaVersion: '1.0.0';
31
+ binding: PlanningDiagnosticsContext['binding'];
32
+ cursor: PlanningDiagnosticsContext['cursor'];
33
+ sourceViewHash: string;
34
+ state: 'available' | 'unavailable' | 'error';
35
+ reason: string | null;
36
+ errorCode: PlanningFileLinkErrorCode | null;
37
+ diagnostics: readonly PlanningReadDiagnostic[];
38
+ totalCount: number | null;
39
+ truncated: boolean;
40
+ }>;
41
+ /** A repository-relative source path for display; `:` and `%` are allowed, unlike file links. */
42
+ export function validPlanningSourcePath(value: unknown): value is string;
43
+ /** expected must come from a validated current Planning graph read. */
44
+ export function assertPlanningDiagnosticsEnvelope(
45
+ value: unknown,
46
+ expected: PlanningDiagnosticsContext,
47
+ ): PlanningDiagnosticsEnvelope;
@@ -0,0 +1,112 @@
1
+ import { deepFreeze, exactJson, safeDataClone } from './closed-json-contract.mjs';
2
+ import {
3
+ PLANNING_FILE_LINK_ERROR_CODES,
4
+ PLANNING_FILE_PATH_LIMIT,
5
+ } from './planning-file-link-contracts.mjs';
6
+
7
+ export const PLANNING_DIAGNOSTICS_MAX_BYTES = 256 * 1024;
8
+ export const PLANNING_DIAGNOSTICS_MAX_COUNT = 500;
9
+ export const PLANNING_DIAGNOSTIC_REASONS = Object.freeze([
10
+ 'missing-reference',
11
+ 'ambiguous-reference',
12
+ 'invalid-date',
13
+ 'missing-date',
14
+ 'closed-before-start',
15
+ 'end-before-start',
16
+ 'dependency-cycle',
17
+ 'containment-cycle',
18
+ 'duplicate-identity',
19
+ 'unrecognized-identity',
20
+ ]);
21
+ const FIELDS = new Set([
22
+ 'epicId',
23
+ 'featureId',
24
+ 'storyId',
25
+ 'specId',
26
+ 'dependsOn',
27
+ 'taskIds',
28
+ 'startDate',
29
+ 'endDate',
30
+ 'closedAt',
31
+ 'releaseCut',
32
+ 'parent',
33
+ 'id',
34
+ ]);
35
+ const keys = (record, expected) =>
36
+ record !== null &&
37
+ typeof record === 'object' &&
38
+ !Array.isArray(record) &&
39
+ Object.keys(record).sort().join(',') === [...expected].sort().join(',');
40
+ const text = (value, limit) =>
41
+ typeof value === 'string' &&
42
+ value.length > 0 &&
43
+ value.length <= limit &&
44
+ ![...value].some(
45
+ (character) => character.codePointAt(0) < 32 || character.codePointAt(0) === 127,
46
+ );
47
+
48
+ /** A repository-relative source path for display; `:` and `%` are allowed, unlike file links. */
49
+ export function validPlanningSourcePath(value) {
50
+ return (
51
+ text(value, PLANNING_FILE_PATH_LIMIT) &&
52
+ !value.startsWith('/') &&
53
+ !value.includes('\\') &&
54
+ !/^[A-Za-z]:/u.test(value) &&
55
+ !value.split('/').some((part) => part === '' || part === '.' || part === '..')
56
+ );
57
+ }
58
+
59
+ // The caller supplies the already verified graph identity so diagnostics cannot introduce new authority.
60
+ export function assertPlanningDiagnosticsEnvelope(value, expected) {
61
+ const record = safeDataClone(value);
62
+ if (
63
+ !keys(record, [
64
+ 'kind',
65
+ 'schemaVersion',
66
+ 'binding',
67
+ 'cursor',
68
+ 'sourceViewHash',
69
+ 'state',
70
+ 'reason',
71
+ 'errorCode',
72
+ 'diagnostics',
73
+ 'totalCount',
74
+ 'truncated',
75
+ ]) ||
76
+ record.kind !== 'planning-diagnostics' ||
77
+ record.schemaVersion !== '1.0.0' ||
78
+ !exactJson(record.binding, expected.binding) ||
79
+ !exactJson(record.cursor, expected.cursor) ||
80
+ record.sourceViewHash !== expected.cursor.viewHash ||
81
+ !['available', 'unavailable', 'error'].includes(record.state) ||
82
+ typeof record.truncated !== 'boolean' ||
83
+ !Array.isArray(record.diagnostics) ||
84
+ record.diagnostics.length > PLANNING_DIAGNOSTICS_MAX_COUNT ||
85
+ record.diagnostics.some(
86
+ (entry) =>
87
+ !keys(entry, ['nodeId', 'sourcePath', 'field', 'reason', 'classification']) ||
88
+ !text(entry.nodeId, 256) ||
89
+ !validPlanningSourcePath(entry.sourcePath) ||
90
+ !FIELDS.has(entry.field) ||
91
+ !PLANNING_DIAGNOSTIC_REASONS.includes(entry.reason) ||
92
+ entry.classification !== 'source-data',
93
+ ) ||
94
+ (record.state === 'available'
95
+ ? !Number.isSafeInteger(record.totalCount) ||
96
+ record.totalCount < record.diagnostics.length ||
97
+ record.truncated !== record.totalCount > record.diagnostics.length ||
98
+ (record.truncated ? !text(record.reason, 500) : record.reason !== null) ||
99
+ record.errorCode !== null
100
+ : record.diagnostics.length !== 0 ||
101
+ record.totalCount !== null ||
102
+ record.truncated ||
103
+ !text(record.reason, 500) ||
104
+ (record.state === 'error'
105
+ ? !PLANNING_FILE_LINK_ERROR_CODES.includes(record.errorCode)
106
+ : record.errorCode !== null)) ||
107
+ new TextEncoder().encode(JSON.stringify(record)).byteLength > PLANNING_DIAGNOSTICS_MAX_BYTES
108
+ ) {
109
+ throw new TypeError('Invalid Planning diagnostics envelope.');
110
+ }
111
+ return deepFreeze(record);
112
+ }
@@ -0,0 +1,53 @@
1
+ export const PLANNING_FILE_LINK_ERROR_CODES: readonly [
2
+ 'EACCES',
3
+ 'EPERM',
4
+ 'ENOENT',
5
+ 'ENOTDIR',
6
+ 'ELOOP',
7
+ 'ENAMETOOLONG',
8
+ 'EIO',
9
+ 'EBADF',
10
+ 'EINVAL',
11
+ 'EMFILE',
12
+ 'ENFILE',
13
+ 'ESTALE',
14
+ 'UNKNOWN',
15
+ ];
16
+ export type PlanningFileLinkErrorCode = (typeof PLANNING_FILE_LINK_ERROR_CODES)[number];
17
+ export const PLANNING_FILE_PATH_LIMIT: 1024;
18
+ export const PLANNING_FILE_LINK_MAX_BYTES: number;
19
+ export type PlanningFileLinkContext = Readonly<{
20
+ binding: Readonly<{
21
+ actorId: string;
22
+ projectId: string;
23
+ scopeId: string;
24
+ domainId: string;
25
+ domainVersion: string;
26
+ generation: number;
27
+ }>;
28
+ cursor: Readonly<{
29
+ eventHead: Readonly<{ sequence: number; hash: string | null }>;
30
+ viewHash: string;
31
+ }>;
32
+ nodeId: string;
33
+ path?: string;
34
+ }>;
35
+ export type PlanningFileLinkEnvelope = Readonly<{
36
+ kind: 'planning-file-link';
37
+ schemaVersion: '1.0.0';
38
+ binding: PlanningFileLinkContext['binding'];
39
+ cursor: PlanningFileLinkContext['cursor'];
40
+ sourceViewHash: string;
41
+ nodeId: string;
42
+ state: 'available' | 'unavailable' | 'error';
43
+ reason: string | null;
44
+ errorCode: PlanningFileLinkErrorCode | null;
45
+ path: string | null;
46
+ editorUrl: string | null;
47
+ }>;
48
+ export function validPlanningFilePath(value: unknown): value is string;
49
+ /** expected must come from a validated current Planning graph/detail read. */
50
+ export function assertPlanningFileLinkEnvelope(
51
+ value: unknown,
52
+ expected: PlanningFileLinkContext,
53
+ ): PlanningFileLinkEnvelope;
@@ -0,0 +1,91 @@
1
+ import { deepFreeze, exactJson, safeDataClone } from './closed-json-contract.mjs';
2
+
3
+ export const PLANNING_FILE_LINK_ERROR_CODES = Object.freeze([
4
+ 'EACCES',
5
+ 'EPERM',
6
+ 'ENOENT',
7
+ 'ENOTDIR',
8
+ 'ELOOP',
9
+ 'ENAMETOOLONG',
10
+ 'EIO',
11
+ 'EBADF',
12
+ 'EINVAL',
13
+ 'EMFILE',
14
+ 'ENFILE',
15
+ 'ESTALE',
16
+ 'UNKNOWN',
17
+ ]);
18
+
19
+ export const PLANNING_FILE_PATH_LIMIT = 1024;
20
+ export const PLANNING_FILE_LINK_MAX_BYTES = 16 * 1024;
21
+
22
+ function hasControl(value) {
23
+ return [...value].some(
24
+ (character) => character.codePointAt(0) < 32 || character.codePointAt(0) === 127,
25
+ );
26
+ }
27
+
28
+ export function validPlanningFilePath(value) {
29
+ if (
30
+ typeof value !== 'string' ||
31
+ value.length === 0 ||
32
+ value.length > PLANNING_FILE_PATH_LIMIT ||
33
+ /[\\:%]/u.test(value) ||
34
+ hasControl(value) ||
35
+ value.split('/').some((part) => part === '' || part === '.' || part === '..')
36
+ )
37
+ return false;
38
+ try {
39
+ encodeURIComponent(value);
40
+ return true;
41
+ } catch {
42
+ return false;
43
+ }
44
+ }
45
+
46
+ function validEditorUrl(value) {
47
+ if (typeof value !== 'string' || !value.startsWith('vscode://file/')) return false;
48
+ try {
49
+ const path = value.slice('vscode://file/'.length);
50
+ const decoded = path.split('/').map(decodeURIComponent);
51
+ return (
52
+ decoded.every(
53
+ (part) =>
54
+ part !== '' && part !== '.' && part !== '..' && !/[/\\]/u.test(part) && !hasControl(part),
55
+ ) && `vscode://file/${decoded.map(encodeURIComponent).join('/')}` === value
56
+ );
57
+ } catch {
58
+ return false;
59
+ }
60
+ }
61
+
62
+ // Identity comes from an already validated Planning read, so this cannot admit a second binding model.
63
+ export function assertPlanningFileLinkEnvelope(value, expected) {
64
+ const record = safeDataClone(value);
65
+ if (
66
+ Object.keys(record).sort().join(',') !==
67
+ 'binding,cursor,editorUrl,errorCode,kind,nodeId,path,reason,schemaVersion,sourceViewHash,state' ||
68
+ record.kind !== 'planning-file-link' ||
69
+ record.schemaVersion !== '1.0.0' ||
70
+ !exactJson(record.binding, expected.binding) ||
71
+ !exactJson(record.cursor, expected.cursor) ||
72
+ record.sourceViewHash !== expected.cursor.viewHash ||
73
+ record.nodeId !== expected.nodeId ||
74
+ !['available', 'unavailable', 'error'].includes(record.state) ||
75
+ (record.state === 'error'
76
+ ? !PLANNING_FILE_LINK_ERROR_CODES.includes(record.errorCode)
77
+ : record.errorCode !== null) ||
78
+ (record.path !== null && !validPlanningFilePath(record.path)) ||
79
+ (expected.path !== undefined && record.path !== null && record.path !== expected.path) ||
80
+ (record.state === 'available'
81
+ ? record.reason !== null || record.path === null || !validEditorUrl(record.editorUrl)
82
+ : typeof record.reason !== 'string' ||
83
+ record.reason.length === 0 ||
84
+ record.reason.length > 500 ||
85
+ record.editorUrl !== null) ||
86
+ new TextEncoder().encode(JSON.stringify(record)).byteLength > PLANNING_FILE_LINK_MAX_BYTES
87
+ ) {
88
+ throw new TypeError('Invalid Planning file link envelope.');
89
+ }
90
+ return deepFreeze(record);
91
+ }