Skip to content

Commit f223089

Browse files
committed
Align plan library and review identities with merged v1 contracts
1 parent d798e1c commit f223089

11 files changed

Lines changed: 485 additions & 56 deletions

File tree

‎core/approvals.ts‎

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { identityKey, type PlanIdentity } from './identity.ts';
12
import type { Plan, PlanItem } from './plan.ts';
23
import type { Segment } from './linking.ts';
34

@@ -11,16 +12,17 @@ function stable(value: unknown): string {
1112
const contentKey = (s: Segment) => stable({ path: s.path, oldPath: s.oldPath, kind: s.kind, operation: s.operation, content: s.content });
1213
export interface SegmentChoice { key: string; action: 'assign' | 'accept'; item: string | null }
1314
/** Position among identical segments and total copies prevent approval transfer. */
14-
export function choiceKeys(segments: readonly Segment[]): string[] {
15+
export function choiceKeys(segments: readonly Segment[], identity: PlanIdentity): string[] {
16+
const identityValue = identityKey(identity);
1517
const counts = new Map<string, number>(), seen = new Map<string, number>();
1618
for (const segment of segments) { const key = contentKey(segment); counts.set(key, (counts.get(key) ?? 0) + 1); }
1719
return segments.map(segment => {
1820
const key = contentKey(segment), copy = (seen.get(key) ?? 0) + 1; seen.set(key, copy);
19-
return stable([key, copy, counts.get(key)]);
21+
return stable([identityValue, key, copy, counts.get(key)]);
2022
});
2123
}
22-
export function applyChoices(plan: Plan, segments: readonly Segment[], choices: readonly SegmentChoice[]): Segment[] {
23-
const keys = choiceKeys(segments);
24+
export function applyChoices(plan: Plan, segments: readonly Segment[], choices: readonly SegmentChoice[], identity: PlanIdentity): Segment[] {
25+
const keys = choiceKeys(segments, identity);
2426
const byKey = new Map(choices.map(choice => [choice.key, choice]));
2527
return segments.map((segment, i) => {
2628
const choice = byKey.get(keys[i]!);
@@ -31,23 +33,23 @@ export function applyChoices(plan: Plan, segments: readonly Segment[], choices:
3133
});
3234
}
3335
export interface Approval { item: string; fingerprint: string }
34-
function fingerprint(item: PlanItem, segments: readonly Segment[]): string {
35-
return stable({ item, segments: segments.filter(s => s.row === item.id).map(s => ({
36+
function fingerprint(item: PlanItem, segments: readonly Segment[], identity: PlanIdentity): string {
37+
return stable({ identity: identityKey(identity), item, segments: segments.filter(s => s.row === item.id).map(s => ({
3638
path: s.path, oldPath: s.oldPath, kind: s.kind, operation: s.operation,
3739
content: s.content, context: s.context, owners: [...s.owners].sort(),
3840
})) });
3941
}
40-
export function approveItem(plan: Plan, segments: readonly Segment[], itemId: string, confirmNoChange = false): Approval {
42+
export function approveItem(plan: Plan, segments: readonly Segment[], itemId: string, identity: PlanIdentity, confirmNoChange = false): Approval {
4143
const item = plan.items.find(item => item.id === itemId);
4244
if (!item) throw new Error('Unknown item.');
4345
if (!segments.some(segment => segment.row === itemId) && !confirmNoChange) throw new Error('Confirm no change needed before approving.');
44-
return { item: itemId, fingerprint: fingerprint(item, segments) };
46+
return { item: itemId, fingerprint: fingerprint(item, segments, identity) };
4547
}
46-
export function approvalStates(plan: Plan, segments: readonly Segment[], approvals: readonly Approval[]): Record<string, 'unreviewed' | 'approved' | 'stale'> {
48+
export function approvalStates(plan: Plan, segments: readonly Segment[], approvals: readonly Approval[], identity: PlanIdentity): Record<string, 'unreviewed' | 'approved' | 'stale'> {
4749
const result: Record<string, 'unreviewed' | 'approved' | 'stale'> = Object.create(null);
4850
for (const item of plan.items) {
4951
const approval = approvals.find(approval => approval.item === item.id);
50-
result[item.id] = !approval ? 'unreviewed' : approval.fingerprint !== fingerprint(item, segments) ||
52+
result[item.id] = !approval ? 'unreviewed' : approval.fingerprint !== fingerprint(item, segments, identity) ||
5153
item.depends_on.some(dep => result[dep] === 'stale') ? 'stale' : 'approved';
5254
}
5355
return result;

‎core/identity.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/** Stable IDs from trusted application storage, never model output or UI selection. */
2+
export interface PlanIdentity { repositoryId: string; taskId: string; planId: string }
3+
export function identityKey(identity: PlanIdentity): string {
4+
const values = [identity?.repositoryId, identity?.taskId, identity?.planId];
5+
if (!values.every(v => typeof v === 'string' && v.length > 0)) throw new Error('Stable repository/task/plan identity is required.');
6+
return JSON.stringify(values);
7+
}

‎core/linking.ts‎

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ function classify(evidence: Evidence): Pick<Segment, 'row' | 'scope'> {
4545
}
4646

4747
/** Replays a linear history. Commit messages and Plan-Item trailers are never trusted. */
48-
export function linkHistory(plan: Plan, history: History, ledger: ReadonlyMap<string, string>): Segment[] {
48+
export function linkHistory(plan: Plan, history: History, ledger: ReadonlyMap<string, string | null>, pathKey: (path: string) => string): Segment[] {
49+
if (typeof pathKey !== 'function') throw new Error('Known checkout path identity is required.');
4950
const files = new Map<string, TrackedFile>();
5051
const removed = new Map<string, Evidence>();
5152
// Deletions retain metadata even after the file leaves the tree.
@@ -59,9 +60,9 @@ export function linkHistory(plan: Plan, history: History, ledger: ReadonlyMap<st
5960
for (const delta of commit.files) {
6061
const oldPath = delta.oldPath;
6162
const item = plan.items.find(item => item.id === owner);
62-
const declared = new Set(item?.files.flatMap(file => [file.path, ...(file.renamed_from ? [file.renamed_from] : [])]));
63+
const declared = new Set(item?.files.flatMap(file => [file.path, ...(file.renamed_from ? [file.renamed_from] : [])]).map(pathKey));
6364
const touched = [delta.oldPath, delta.newPath].filter((path): path is string => path !== null);
64-
const current: Evidence = { owners: [owner], outOfScope: owner !== null && touched.some(path => !declared.has(path)) ? [owner] : [] };
65+
const current: Evidence = { owners: [owner], outOfScope: owner !== null && touched.some(path => !declared.has(pathKey(path))) ? [owner] : [] };
6566
let previous = oldPath ? files.get(oldPath) : undefined;
6667
if (!previous) previous = {
6768
lines: lines(textFile(delta.before) ? delta.before!.text : '').map((text, i) => ({ text, evidence: empty(), origins: [origin(oldPath!, i)], moved: empty() })),
@@ -113,7 +114,8 @@ export function linkHistory(plan: Plan, history: History, ledger: ReadonlyMap<st
113114
operation: null, context: '', hunk: -1,
114115
content: JSON.stringify({ oldPath: delta.oldPath, newPath: delta.newPath,
115116
oldMode: delta.before?.mode ?? null, newMode: delta.after?.mode ?? null,
116-
oldOid: delta.before?.oid ?? null, newOid: delta.after?.oid ?? null }),
117+
oldObject: delta.before ? { kind: delta.before.mode === '160000' ? 'commit' : 'blob', oid: delta.before.oid } : null,
118+
newObject: delta.after ? { kind: delta.after.mode === '160000' ? 'commit' : 'blob', oid: delta.after.oid } : null }),
117119
}, evidence);
118120
}
119121
const finalChanges = diffArrays(oldLines, newLines, { timeout: 2000 });

‎core/parse-v1.ts‎

Lines changed: 118 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import { isAlias, isMap, isScalar, isSeq, parseDocument } from 'yaml';
2+
3+
const MAX_BYTES = 1024 * 1024;
4+
const number = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/u;
5+
function reject(message: string): never { throw new Error(message); }
6+
function numeric(text: string): number {
7+
if (!number.test(text)) reject('Non-JSON numeric scalar.');
8+
const n = Number(text);
9+
if (!Number.isFinite(n) || (Number.isInteger(n) && !Number.isSafeInteger(n))) reject('Number is outside the safe range.');
10+
if (Number.isInteger(n)) {
11+
const [mantissa, exponentText = '0'] = text.toLowerCase().split('e');
12+
const fractionLength = mantissa!.split('.')[1]?.length ?? 0;
13+
let digits = mantissa!.replace(/[-.]/gu, '').replace(/^0+/u, '');
14+
let exponent = Number(exponentText) - fractionLength;
15+
while (digits.endsWith('0')) { digits = digits.slice(0, -1); exponent++; }
16+
if (digits && (exponent < 0 || exponent > 16 || digits.length + exponent > 16 ||
17+
Number((text.startsWith('-') ? '-' : '') + digits + '0'.repeat(exponent)) !== n))
18+
reject('Integer is not exactly representable.');
19+
}
20+
return n;
21+
}
22+
/** Frozen v1 syntax contract. No runtime I/O or alias/object construction. */
23+
export function parseV1(input: string | Uint8Array, format: 'json' | 'yaml'): unknown {
24+
if (typeof input === 'string' && input.length > MAX_BYTES) reject('Input size exceeds 1 MiB.');
25+
const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : input;
26+
if (bytes.byteLength > MAX_BYTES) reject('Input size exceeds 1 MiB.');
27+
const source = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
28+
if (typeof input === 'string' && input !== source) reject('Invalid UTF-8 source string.');
29+
if (format === 'json') return parseJson(source);
30+
if (format !== 'yaml') reject('Unknown input format.');
31+
const doc = parseDocument(source, { uniqueKeys: false, version: '1.2', strict: true });
32+
if (doc.directives?.yaml.version !== '1.2') reject('Only YAML 1.2 is supported.');
33+
if (doc.errors.length || doc.warnings.length) reject([...doc.errors, ...doc.warnings].map(e => e.message).join('; '));
34+
function convert(node: unknown, depth: number): unknown {
35+
if (isAlias(node)) reject('Alias resolution is disabled.');
36+
if (!isScalar(node) && !isSeq(node) && !isMap(node)) reject('Empty or unsupported YAML scalar.');
37+
if (node.anchor || node.tag) reject('Anchors and explicit tags are prohibited.');
38+
if (isScalar(node)) {
39+
const raw = node.source ?? '';
40+
if (node.type !== 'PLAIN') {
41+
if (typeof node.value !== 'string') reject('Quoted scalar must be a string.');
42+
return node.value;
43+
}
44+
if (!raw) reject('Empty implicit YAML scalar.');
45+
if (raw === 'null') return null;
46+
if (raw === 'true' || raw === 'false') return raw === 'true';
47+
if (typeof node.value === 'number') return numeric(raw);
48+
if (typeof node.value !== 'string') reject('Only exact JSON literal scalars are permitted.');
49+
if (/^[+-]?0[bBoOxX][0-9a-fA-F_]+$/u.test(raw)) reject('Non-JSON numeric scalar.');
50+
// YAML implementations differ on numeric separators; v1 explicitly forbids them.
51+
if (/^[+-]?(?:[0-9][0-9_]*(?:\.[0-9_]*)?|\.[0-9_]+)(?:[eE][+-]?[0-9_]+)?$/u.test(raw) && raw.includes('_')) reject('Non-JSON numeric scalar.');
52+
return node.value;
53+
}
54+
if (depth >= 50) reject('Container depth exceeds 50.');
55+
if (isSeq(node)) return node.items.map(child => convert(child, depth + 1));
56+
const result: Record<string, unknown> = Object.create(null);
57+
for (const pair of node.items) {
58+
if (!isScalar(pair.key)) reject('Mapping keys must be strings.');
59+
const key = convert(pair.key, depth + 1);
60+
if (typeof key !== 'string') reject('Mapping keys must be strings.');
61+
if (key === '<<') reject('Merge keys are prohibited.');
62+
if (Object.hasOwn(result, key)) reject(`Duplicate key: ${key}`);
63+
result[key] = convert(pair.value, depth + 1);
64+
}
65+
return result;
66+
}
67+
return convert(doc.contents, 0);
68+
}
69+
70+
/** Recursive descent detects decoded duplicate keys before object creation. */
71+
function parseJson(source: string): unknown {
72+
let i = 0;
73+
const whitespace = () => { while (i < source.length && /[ \t\r\n]/u.test(source[i]!)) i++; };
74+
const string = (): string => {
75+
const start = i++;
76+
while (i < source.length) {
77+
const c = source[i++];
78+
if (c === '"') return JSON.parse(source.slice(start, i)) as string;
79+
if (c === '\\') i++;
80+
}
81+
return reject('Unterminated JSON string.');
82+
};
83+
function value(depth: number): unknown {
84+
whitespace();
85+
const c = source[i];
86+
if (c === '"') return string();
87+
if (c === '{' || c === '[') {
88+
if (depth >= 50) reject('Container depth exceeds 50.');
89+
i++; whitespace();
90+
const object = c === '{', close = object ? '}' : ']';
91+
const entries: Record<string, unknown> = Object.create(null), items: unknown[] = [];
92+
if (source[i] === close) { i++; return object ? entries : items; }
93+
while (true) {
94+
whitespace();
95+
if (object) {
96+
if (source[i] !== '"') reject('JSON object key must be a string.');
97+
const key = string(); whitespace();
98+
if (source[i++] !== ':') reject('Expected JSON colon.');
99+
if (Object.hasOwn(entries, key)) reject(`Duplicate key: ${key}`);
100+
entries[key] = value(depth + 1);
101+
} else items.push(value(depth + 1));
102+
whitespace();
103+
if (source[i] === close) { i++; return object ? entries : items; }
104+
if (source[i++] !== ',') reject('Expected JSON comma.');
105+
}
106+
}
107+
for (const [literal, parsed] of [['true', true], ['false', false], ['null', null]] as const) {
108+
if (source.startsWith(literal, i)) { i += literal.length; return parsed; }
109+
}
110+
const token = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/u.exec(source.slice(i));
111+
if (!token) reject('Invalid JSON value.');
112+
i += token[0].length;
113+
return numeric(token[0]);
114+
}
115+
const result = value(0); whitespace();
116+
if (i !== source.length) reject('Unexpected trailing JSON input.');
117+
return result;
118+
}

0 commit comments

Comments
 (0)