session-peer 0.3.2 → 0.3.3

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,142 @@
1
+ // A local, bounded string-map inspection. No instructions, references, tools or
2
+ // network are executed. Body bytes are read, but never interpreted as commands.
3
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync } from 'node:fs';
4
+ import { TextDecoder } from 'node:util';
5
+ import { canonical } from './discovery.js';
6
+ import { VERSION } from './protocol.js';
7
+ const unknown = (code = 'skill_metadata_missing') => ({ status: 'unknown', code });
8
+ const verdict = (compatible) => ({ status: compatible ? 'compatible' : 'incompatible',
9
+ code: compatible ? 'skill_contract_compatible' : 'skill_contract_mismatch', verification: 'metadata_only' });
10
+ export const SKILL_METADATA_LIMIT = 65536;
11
+ const keys = ['version', 'runtime-implementation', 'runtime-min-version', 'runtime-full-version', 'runtime-capability-policy'];
12
+ // Finite source proposal for #118; 0.3.3 successor support requires companion
13
+ // exact review before merge/release. VERSION identifies this 0.3.3 candidate;
14
+ // it does not establish companion approval or public runtime availability.
15
+ const matrix = { '0.3.2': ['0.1.0'], '0.3.3': ['0.1.0', '0.2.0'] };
16
+ const profiles = {
17
+ '0.1.0': ['0.1.0', 'typescript', '0.1.0', '0.1.0', 'probe-help'],
18
+ '0.2.0': ['0.2.0', 'typescript', '0.1.0', '0.3.2', 'probe-help']
19
+ };
20
+ // Deliberately not general YAML: plain ASCII tokens or unescaped quoted strings,
21
+ // followed by an optional comment. YAML tags, aliases, maps and sequences fail.
22
+ function scalar(value) {
23
+ const match = /^(?:"([^"\\\r\n]*)"|'([^'\\\r\n]*)'|([A-Za-z0-9][A-Za-z0-9._/-]*))(?:[ ]+(?:#.*)?)?$/.exec(value);
24
+ const result = match ? match[1] ?? match[2] ?? match[3] : undefined;
25
+ return result?.length ? result : undefined;
26
+ }
27
+ export function validateSkillMetadata(text, runtime = VERSION) {
28
+ if (text.length > SKILL_METADATA_LIMIT || Buffer.byteLength(text, 'utf8') > SKILL_METADATA_LIMIT)
29
+ return unknown('skill_metadata_unreadable');
30
+ if (typeof runtime !== 'string' || !/^(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)$/.test(runtime))
31
+ return unknown();
32
+ // BOM and controls are rejected explicitly; whole-file fatal UTF-8 happens in
33
+ // the reader. LF/CRLF and body tabs are supported; lone CR is not.
34
+ // Map indentation and value separators use spaces rather than tabs.
35
+ if (text.startsWith('\uFEFF') || /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]|\r(?!\n)/.test(text))
36
+ return unknown();
37
+ const front = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(text)?.[1];
38
+ if (!front)
39
+ return unknown();
40
+ const lines = front.split(/\r?\n/), names = [], sections = [];
41
+ let rootOwner;
42
+ for (let i = 0; i < lines.length; i++) {
43
+ const line = lines[i];
44
+ if (/^[ ]*(?:#.*)?$/.test(line))
45
+ continue;
46
+ if (line.startsWith(' ')) {
47
+ // Comments/blank lines do not end a root scalar. Only metadata and
48
+ // ignored unrelated fields can own indented content; name cannot.
49
+ if (rootOwner === undefined || rootOwner === 'name')
50
+ return unknown();
51
+ continue;
52
+ }
53
+ const root = /^([a-z][a-z0-9-]*):/.exec(line);
54
+ if (!root)
55
+ return unknown();
56
+ rootOwner = root[1];
57
+ if (/^name:/.test(line)) {
58
+ if (!/^name:[ ]+/.test(line))
59
+ return unknown();
60
+ const name = scalar(line.slice(5).trimStart());
61
+ if (name === undefined)
62
+ return unknown();
63
+ names.push(name);
64
+ }
65
+ if (/^metadata:/.test(line)) {
66
+ if (!/^metadata:(?:[ ]+(?:#.*)?)?$/.test(line))
67
+ return unknown();
68
+ sections.push(i);
69
+ }
70
+ }
71
+ if (names.length !== 1 || sections.length !== 1)
72
+ return unknown();
73
+ const fields = new Map();
74
+ for (let i = sections[0] + 1; i < lines.length; i++) {
75
+ const line = lines[i];
76
+ if (/^[ ]*(?:#.*)?$/.test(line))
77
+ continue;
78
+ if (!line.startsWith(' '))
79
+ break;
80
+ const match = /^ ([a-z][a-z0-9-]*):[ ]+(.*)$/.exec(line);
81
+ if (!match || fields.has(match[1]))
82
+ return unknown();
83
+ const value = scalar(match[2]);
84
+ if (value === undefined)
85
+ return unknown();
86
+ fields.set(match[1], value);
87
+ }
88
+ if (keys.some(key => !fields.has(key)))
89
+ return unknown();
90
+ const values = keys.map(key => fields.get(key));
91
+ const profile = Object.hasOwn(profiles, values[0]) ? profiles[values[0]] : undefined;
92
+ return verdict(names[0] === 'session-peer-ts' && !!profile && profile.every((value, i) => value === values[i]) &&
93
+ !!matrix[runtime]?.includes(values[0]));
94
+ }
95
+ function stable(a, b) {
96
+ return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
97
+ }
98
+ export function inspectSkill(original) {
99
+ let path = original, established = false;
100
+ try {
101
+ path = canonical(original); // Preserve separately managed symlink installations.
102
+ const before = lstatSync(path, { bigint: true });
103
+ if (!before.isFile() || before.size > BigInt(SKILL_METADATA_LIMIT))
104
+ return { path, ...unknown('skill_metadata_unreadable') };
105
+ established = true;
106
+ const flags = constants.O_RDONLY | (process.platform === 'win32' ? 0 : constants.O_NONBLOCK | constants.O_NOFOLLOW);
107
+ const fd = openSync(path, flags);
108
+ try {
109
+ const opened = fstatSync(fd, { bigint: true });
110
+ if (!opened.isFile() || !stable(before, opened))
111
+ return { path, ...unknown('skill_metadata_unreadable') };
112
+ const bytes = Buffer.alloc(SKILL_METADATA_LIMIT + 1);
113
+ let length = 0;
114
+ while (length < bytes.length) {
115
+ const count = readSync(fd, bytes, length, bytes.length - length, length);
116
+ if (!count)
117
+ break;
118
+ length += count;
119
+ }
120
+ const after = fstatSync(fd, { bigint: true }), current = lstatSync(path, { bigint: true });
121
+ if (length > SKILL_METADATA_LIMIT || BigInt(length) !== before.size || !after.isFile() || !current.isFile() ||
122
+ !stable(before, after) || !stable(before, current) || canonical(original) !== path)
123
+ return { path, ...unknown('skill_metadata_unreadable') };
124
+ let text;
125
+ try {
126
+ text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes.subarray(0, length));
127
+ }
128
+ catch {
129
+ return { path, ...unknown('skill_metadata_unreadable') };
130
+ }
131
+ return { path, ...validateSkillMetadata(text) };
132
+ }
133
+ finally {
134
+ closeSync(fd);
135
+ }
136
+ }
137
+ catch (error) {
138
+ const code = error.code;
139
+ return { path, ...(!established && (code === 'ENOENT' || code === 'ENOTDIR') ? { status: 'missing', code: 'skill_missing' } :
140
+ code === 'EACCES' || code === 'EPERM' ? { status: 'permission_denied', code: 'permission_denied' } : unknown('skill_metadata_unreadable')) };
141
+ }
142
+ }
@@ -0,0 +1,18 @@
1
+ import type { Done } from './process.js';
2
+ export declare const RESPONSE_BYTES: number;
3
+ export declare const RESPONSE_DEPTH = 64;
4
+ export declare const RESPONSE_NODES = 65536;
5
+ export declare function parseResponse(bytes: Uint8Array): Record<string, unknown>;
6
+ export type ResponseRequest = {
7
+ command: string;
8
+ to?: string;
9
+ dryRun?: boolean;
10
+ returnTo?: string;
11
+ home?: string;
12
+ allowInactive?: boolean;
13
+ };
14
+ export declare function validateResponse(value: Record<string, unknown>, request: ResponseRequest): void;
15
+ export declare function responseOutcome(done: Done, request: ResponseRequest): {
16
+ value: Record<string, unknown>;
17
+ exitCode: number;
18
+ };
@@ -0,0 +1,201 @@
1
+ // Ordinary SSH response protocol. Internal helpers, not a package-root API.
2
+ import { casefold } from './casefold.js';
3
+ import { uuid } from './writer.js';
4
+ export const RESPONSE_BYTES = 1024 * 1024;
5
+ export const RESPONSE_DEPTH = 64;
6
+ export const RESPONSE_NODES = 65536;
7
+ function invalid() { throw new Error('remote_response_unverified'); }
8
+ // A finite-depth scanner validates the whole frame and decoded object keys
9
+ // before JSON.parse can overwrite duplicates. Each key/value consumes a node;
10
+ // both allocations and recursion are bounded independently of field semantics.
11
+ export function parseResponse(bytes) {
12
+ if (bytes.byteLength > RESPONSE_BYTES)
13
+ return invalid();
14
+ let text;
15
+ try {
16
+ text = new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
17
+ }
18
+ catch {
19
+ return invalid();
20
+ }
21
+ let at = 0, nodes = 0;
22
+ const number = /-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?/y;
23
+ const space = () => { while (at < text.length && /[\x20\t\r\n]/.test(text[at]))
24
+ at++; };
25
+ const count = () => { if (++nodes > RESPONSE_NODES)
26
+ invalid(); };
27
+ const string = () => {
28
+ const start = at++;
29
+ while (at < text.length) {
30
+ const char = text[at++];
31
+ if (char === '\\') {
32
+ at++;
33
+ continue;
34
+ }
35
+ if (char === '"') {
36
+ try {
37
+ return JSON.parse(text.slice(start, at));
38
+ }
39
+ catch {
40
+ return invalid();
41
+ }
42
+ }
43
+ }
44
+ return invalid();
45
+ };
46
+ const value = (depth) => {
47
+ count();
48
+ space();
49
+ const char = text[at];
50
+ if (char === '{' || char === '[') {
51
+ if (depth >= RESPONSE_DEPTH)
52
+ invalid();
53
+ const object = char === '{', close = object ? '}' : ']';
54
+ const keys = new Set();
55
+ at++;
56
+ space();
57
+ if (text[at] === close) {
58
+ at++;
59
+ return;
60
+ }
61
+ while (true) {
62
+ if (object) {
63
+ space();
64
+ if (text[at] !== '"')
65
+ invalid();
66
+ count();
67
+ const key = string();
68
+ if (keys.has(key))
69
+ invalid();
70
+ keys.add(key);
71
+ space();
72
+ if (text[at++] !== ':')
73
+ invalid();
74
+ }
75
+ value(depth + 1);
76
+ space();
77
+ if (text[at] === close) {
78
+ at++;
79
+ return;
80
+ }
81
+ if (text[at++] !== ',')
82
+ invalid();
83
+ }
84
+ }
85
+ if (char === '"') {
86
+ string();
87
+ return;
88
+ }
89
+ for (const literal of ['true', 'false', 'null']) {
90
+ if (text.startsWith(literal, at)) {
91
+ at += literal.length;
92
+ return;
93
+ }
94
+ }
95
+ number.lastIndex = at;
96
+ const matched = number.exec(text);
97
+ if (!matched)
98
+ invalid();
99
+ at = number.lastIndex;
100
+ };
101
+ space();
102
+ if (text[at] !== '{')
103
+ return invalid();
104
+ value(0);
105
+ space();
106
+ if (at !== text.length)
107
+ return invalid();
108
+ try {
109
+ return JSON.parse(text);
110
+ }
111
+ catch {
112
+ return invalid();
113
+ }
114
+ }
115
+ const record = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
116
+ // Bind supported native facts to the original command, dry-run and exact
117
+ // target. Home aliases are resolved on the destination; this does not resolve
118
+ // remote paths on the caller or authenticate a remote process/incarnation.
119
+ export function validateResponse(value, request) {
120
+ if (value.schemaVersion !== 1 || value.command !== request.command || typeof value.ok !== 'boolean' ||
121
+ typeof value.host !== 'string' || !value.host || ('error' in value && (value.ok || typeof value.error !== 'string')))
122
+ invalid();
123
+ if (request.command === 'list' && value.ok && !Array.isArray(value.sessions))
124
+ invalid();
125
+ if (request.command === 'doctor' && value.ok && (value.diagnosticCompleted !== true || typeof value.ready !== 'boolean' ||
126
+ value.implementation !== 'typescript' || !record(value.agents)))
127
+ invalid();
128
+ if (request.command === 'doctor' && value.ok && request.returnTo && (!record(value.returnRoute) ||
129
+ !['verified', 'failed'].includes(value.returnRoute.status) || value.returnRoute.transport !== 'ssh' ||
130
+ value.returnRoute.host !== request.returnTo))
131
+ invalid();
132
+ if (request.command !== 'send')
133
+ return;
134
+ if (!value.ok && typeof value.error !== 'string')
135
+ invalid();
136
+ const codex = request.to?.startsWith('codex:') === true;
137
+ const expected = request.dryRun ? 'validated' : codex ? 'queued' : 'posted';
138
+ if (value.consumptionConfirmed !== false ||
139
+ (value.ok && (value.submitted !== !request.dryRun || value.status !== expected)) ||
140
+ (!value.ok && !((value.submitted === false && value.status === 'refused') ||
141
+ (!request.dryRun && value.submitted === null && value.status === 'unknown'))) ||
142
+ ('dryRun' in value && value.dryRun !== !!request.dryRun) || ('retryAllowed' in value && value.retryAllowed !== false))
143
+ invalid();
144
+ if (!value.ok) {
145
+ if ('queueId' in value)
146
+ invalid();
147
+ return;
148
+ }
149
+ const target = value.target;
150
+ if (!record(target) || (target.agent !== undefined && target.agent !== (codex ? 'codex' : 'claude')))
151
+ invalid();
152
+ if (codex) {
153
+ if (typeof target.id !== 'string' || !uuid(target.id) || target.id.toLowerCase() !== request.to.slice(6).toLowerCase())
154
+ invalid();
155
+ if ('queueId' in value && (request.dryRun || typeof value.queueId !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(value.queueId)))
156
+ invalid();
157
+ if (typeof value.codexHome !== 'string' || !/^(?:\/|[A-Za-z]:[\\/]|[\\/]{2})/.test(value.codexHome))
158
+ invalid();
159
+ // A receiver can canonicalize a remote alias. It echoes the explicit home
160
+ // it actually parsed, rather than asking the caller to resolve remote paths.
161
+ if ('requestedCodexHome' in value && (request.home === undefined || value.requestedCodexHome !== request.home))
162
+ invalid();
163
+ if (request.home !== undefined && value.codexHome !== request.home && value.requestedCodexHome !== request.home)
164
+ invalid();
165
+ if ('codexHomeResolution' in value && (!record(value.codexHomeResolution) || value.codexHomeResolution.schemaVersion !== 1 ||
166
+ value.codexHomeResolution.status !== (request.home === undefined ? 'selected' : 'explicit') ||
167
+ value.codexHomeResolution.selected !== value.codexHome ||
168
+ (value.codexHomeResolution.reason === 'explicit_inactive_opt_in' && !request.allowInactive)))
169
+ invalid();
170
+ }
171
+ else {
172
+ if (!Number.isSafeInteger(target.pid) || target.pid <= 0 || !(typeof target.name === 'string' || target.name === null) || 'queueId' in value)
173
+ invalid();
174
+ const requested = request.to.replace(/^claude:/, '');
175
+ if (/^\d+$/.test(requested) ? target.pid !== Number(requested) :
176
+ typeof target.name !== 'string' || casefold(target.name) !== casefold(requested))
177
+ invalid();
178
+ }
179
+ }
180
+ // Transport failure is not a second submission. A fully validated response
181
+ // keeps native ok/status/submitted unchanged; local exit 1 reports transport
182
+ // failure. Overflow never establishes a complete frame, even with a prefix.
183
+ export function responseOutcome(done, request) {
184
+ if (!done.spawned || done.stopReason === 'output_limit' || !done.stdoutBytes)
185
+ return invalid();
186
+ const value = parseResponse(done.stdoutBytes);
187
+ validateResponse(value, request);
188
+ // Reserved client-owned diagnosis; retain unrelated additive native fields.
189
+ delete value.sshTransport;
190
+ delete value.requestedCodexHome;
191
+ const ordinary = !done.interrupted && [0, 1, 2].includes(done.code ?? -1);
192
+ if (ordinary) {
193
+ if (value.ok !== (done.code === 0))
194
+ return invalid();
195
+ return { value, exitCode: done.code };
196
+ }
197
+ return { value: { ...value, ...(request.command === 'send' ? { retryAllowed: false } : {}),
198
+ sshTransport: { status: done.stopReason === 'timeout' ? 'timed_out' : 'failed',
199
+ reason: done.stopReason === 'timeout' ? 'ssh_timeout' : done.stopReason === 'process_error' ? 'ssh_process_error' : 'ssh_exit_nonzero',
200
+ exitCode: done.code } }, exitCode: 1 };
201
+ }
package/docs/api.md CHANGED
@@ -1,18 +1,18 @@
1
1
  # API reference
2
2
 
3
- This reference describes source/package version **0.3.2**. Version-pinned npm commands require that version to be available in the registry; check `npm view session-peer@0.3.2 version` before installing. Before publication, use the reviewed source artifact.
3
+ This reference describes source/package version **0.3.3 candidate (unpublished at the 2026-10-09 KST preparation checkpoint)**. Public npm `latest` verified at that checkpoint is **0.3.2**, with unchanged `preview=0.1.0-preview.1`. The 0.3.3 install example is conditional on separately approved publication; check `npm view session-peer@0.3.3 version` first. Before publication, use the reviewed candidate source artifact.
4
4
 
5
5
  [Back to README](../README.md) · [User guide](guide.md)
6
6
 
7
7
  The package exposes a small ESM API with TypeScript declarations. Install it
8
- locally with `npm install --ignore-scripts session-peer@0.3.2` before importing it.
8
+ locally with `npm install --ignore-scripts session-peer@0.3.3` before importing it.
9
9
  Importing the package does not execute the CLI or submit a message.
10
10
 
11
11
  ```js
12
12
  import { VERSION, VERSION_LINE, reply, envelope } from 'session-peer';
13
13
 
14
- console.log(VERSION); // 0.3.2
15
- console.log(VERSION_LINE); // session-peer 0.3.2 (typescript)
14
+ console.log(VERSION); // 0.3.3
15
+ console.log(VERSION_LINE); // session-peer 0.3.3 (typescript)
16
16
  const address = 'session-peer://v1/reply?agent=claude&session=12345&transport=local';
17
17
  console.log(reply(address)); // { to: '12345' }
18
18
  console.log(envelope('Please review and reply.', true, address));
@@ -30,3 +30,6 @@ not verify a live writer, establish a return route, or confirm consumption.
30
30
  Only the exports above form the public package API; internal `dist` modules are
31
31
  not package subpath exports. Use the [CLI guide](guide.md#use) for sending and
32
32
  [CONTRIBUTING.md](../CONTRIBUTING.md) for development and test setup.
33
+
34
+
35
+ The ordinary SSH response correction is documented separately as the [0.3.3 ordinary SSH response correction](design/ordinary-ssh-responses.md); its internal parser is not a package-root export.
@@ -0,0 +1,37 @@
1
+ <a id="ordinary-ssh-response-validation--033-release-candidate"></a>
2
+
3
+ # Ordinary SSH response validation — 0.3.3
4
+
5
+ This describes the source correction for [#116](https://github.com/abruption/session-peer-ts/issues/116) and [#115](https://github.com/abruption/session-peer-ts/issues/115). It is not a claim that the immutable npm 0.3.2 artifact contains it. Both endpoints still require the same TypeScript client version. The Python 1.0.2 development oracle and the separate 0.4.0 handoff proposals are unchanged.
6
+
7
+ ## Bounded protocol
8
+
9
+ - Request stdout is collected as raw bytes, with a **1,048,576-byte** limit including whitespace and line endings. An overflow invalidates the entire response; a retained valid prefix is not accepted.
10
+ - UTF-8 decoding is fatal, including sequences split across process chunks. An actual UTF-8 U+FFFD character is legal; invalid bytes are not repaired into one.
11
+ - The frame contains exactly one top-level JSON object, surrounded only by JSON space, tab, CR and LF. BOM, banners, trailing material, multiple frames and non-JSON constants are rejected.
12
+ - A pre-parse scanner rejects duplicate decoded keys in every object, including escaped-equivalent keys. Containers have a maximum depth of **64**, and values plus object keys have a combined budget of **65,536 nodes**. The scanner's recursion and allocations are bounded by these limits and the byte limit; it does not evaluate input. Legacy JSON number spellings are not replaced with the separate handoff proposal's integer grammar.
13
+ - Diagnostic stderr is independent of protocol stdout: at most **4,096 raw bytes** are retained and replacement decoded. Excess is drained, and raw diagnostics are never printed in the result. Malformed stderr alone does not invalidate a complete stdout response.
14
+ - Version preflight and other non-protocol tool consumers keep their text interfaces and existing timeouts. The SSH request deadline remains 90 seconds. POSIX cleanup kills only the owned process group; escaped descendants and Windows descendant cleanup retain their documented limits.
15
+
16
+ ## Native facts and transport completion
17
+
18
+ The same parser and command/request validator apply to normal and abnormal transport completion. Send responses must match the requested agent, Codex UUID or Claude PID/casefolded name, dry-run/status/submitted facts, and `consumptionConfirmed:false`. Claude `name:null`, an omitted target agent, and an omitted Codex queue ID remain supported. A present queue ID must match the native bounded identifier grammar. Returned Codex home and selected-home metadata must agree, the selected/explicit mode must match the request, and an inactive opt-in reason requires the caller's opt-in. If a canonical returned home differs from the explicit input, the receiver must echo its parsed `requestedCodexHome`; the caller validates and removes this wire-only scalar. Legacy same-path results do not need the scalar. Home aliases and canonicalization belong to the destination, not the caller's local filesystem. This check does not authenticate the remote native process or prove an independent mapping of a remote path alias.
19
+
20
+ | Transport / frame | Local result |
21
+ | --- | --- |
22
+ | Verified ordinary exit 0/1/2 | Preserve native fields and the existing exit/`ok` consistency contract. |
23
+ | Complete independently validated response followed by SSH 255, shutdown or collection timeout | Preserve native `ok`, `status`, `submitted`, target and optional queue ID; return **exit 1** and an additive `sshTransport` diagnostic. |
24
+ | Missing, partial, malformed, polluted, overflowed or mismatched response after a possible send effect | `outcome_unknown`, `submitted:null`, `retryAllowed:false`, exit 1. |
25
+ | Unverified dry-run or non-send response | `remote_response_unverified`, exit 1; no native submission is performed by those commands. |
26
+
27
+ `sshTransport` is client-owned and contains `status` (`failed` or `timed_out`), `reason` (`ssh_exit_nonzero`, `ssh_timeout` or `ssh_process_error`) and the observed `exitCode` (integer or null). A peer cannot supply this client diagnosis. It is omitted for ordinary verified exits. An abnormal transport send adds `retryAllowed:false` and never resubmits, falls back or fails over.
28
+
29
+ Consequently **native `ok:true` can coexist with local exit 1**. Consumers must inspect native submission facts and the transport diagnostic rather than assume a nonzero exit means nothing was submitted. Text output keeps the native result and adds the transport warning. Definite remote refusal facts are retained when a complete verified response establishes them. Missing native fields are not synthesized as false or null.
30
+
31
+ Ordered fanout preserves each destination's result and has exit 1 if any destination has a nonzero local exit. `posted`/`queued` and `submitted:true` remain submission evidence only: no injection, receipt ACK, task completion or retry authority is established.
32
+
33
+ ## Validation boundaries
34
+
35
+ The fixtures use synthetic response objects and owned fake processes/SSH endpoints, not live agent delivery. They cover complete versus partial output, exit 0/255, actual process collection timeout, invalid diagnostic bytes, byte/depth/node limits, escaped duplicate keys, nullable Claude names, request mismatches, ordered mixed-host results and one request per host. A test-only import shortens the production request timer in the POSIX CLI fixture; production has no new timeout setting. The portable parser/process tests run in the Windows suite; the native Windows fixture exercises a complete Codex response followed by SSH 255 through encoded PowerShell. CI results and exact commits are recorded in the PR, not inferred from fixture names.
36
+
37
+ At dependency [PR #127](https://github.com/abruption/session-peer-ts/pull/127) head `8c882fa`, 13 portable parser/process fixtures passed. POSIX fake SSH exercised complete/partial frames with exits 0/255 and a real shortened collection timeout, plus ordered fanout and one attempt per host. The encoded PowerShell Windows fixture retained a complete `queued` native stand-in result (`ok:true`, `submitted:true`) after SSH 255 and invalid diagnostic stderr, while returning local exit 1 with `sshTransport`; it made exactly one queue stand-in call. [CI run 37863835806](https://github.com/abruption/session-peer-ts/actions/runs/37863835806) passed 12/12 checks including macOS/Ubuntu Node 22/24 and Windows native Node 22/24; [CodeQL run 37863832399](https://github.com/abruption/session-peer-ts/actions/runs/37863832399) also passed. This qualifies that dependency head's bounded fixtures, not a future merged main release SHA. It adds no actual agent ACK, real SSH-host, delivery/crash or fleet verification. Final combined candidate checks and exact artifact evidence belong in [VALIDATION.md](../../VALIDATION.md).
@@ -0,0 +1,73 @@
1
+ # TypeScript skill metadata guard proposal
2
+
3
+ This is the TS source implementation proposal for [#118](https://github.com/abruption/session-peer-ts/issues/118), based on the companion [Draft #20 at `963c3d7`](https://github.com/abruption/session-peer-skill/blob/963c3d748a11b1164013ee26c9c0ef285c52b285/docs/typescript-compatibility.md). Companion [design acceptance at `699a325`](https://github.com/abruption/session-peer-skill/blob/699a3251830c30c62d0f812363faf4d0eb0c8e0c/docs/typescript-compatibility.md) records the full static review of the exact candidates below on 2026-10-09. This design-only acceptance does not authorize runtime merge/release, successor skill metadata/publication, installation or pin changes, content authenticity, or live delivery support.
4
+
5
+ ## Separate version meanings
6
+
7
+ The skill repository tag, Python skill revision, TS skill revision, and npm runtime version are independent. `runtime-min-version` describes the skill's baseline CLI compatibility floor; `runtime-full-version` describes its documented published CLI feature coverage reference. Neither is a security recommendation, a doctor-acceptance rule, permission to send, or evidence of platform/native compatibility. Optional operations still need their actual resolved TS executable's version/help and prerequisites.
8
+
9
+ The finite source proposal is:
10
+
11
+ | Inspecting runtime | Skill version | Implementation | Minimum | Full | Policy | Verdict |
12
+ |---|---|---|---|---|---|---|
13
+ | `0.3.2` | `0.1.0` | `typescript` | `0.1.0` | `0.1.0` | `probe-help` | compatible |
14
+ | `0.3.2` | `0.2.0` | `typescript` | `0.1.0` | `0.3.2` | `probe-help` | incompatible |
15
+ | `0.3.3` (source proposal) | `0.1.0` | `typescript` | `0.1.0` | `0.1.0` | `probe-help` | compatible, exact design accepted (dated record below) |
16
+ | `0.3.3` (source proposal) | `0.2.0` | `typescript` | `0.1.0` | `0.3.2` | `probe-help` | compatible, exact design accepted (dated record below) |
17
+ | Other valid runtime/profile | Any | Any | Any | Any | Any | incompatible |
18
+ | Unavailable/malformed runtime identity | Any | Any | Any | Any | Any | unknown |
19
+
20
+ All compatible rows also require exactly one `name: session-peer-ts`. Inspection uses this runtime's compiled `VERSION`, without executing a binary. Version 0.3.3 builds `VERSION=0.3.3`, so its production doctor inspection path can exercise the proposed successor row as well as the legacy row. The immutable public 0.3.2 artifact remains legacy-only; design acceptance does not establish published compatibility or approve runtime merge/release. Pure validator fixtures also exercise the finite matrix. Every later runtime/profile row needs explicit review; no generic future-version guarantee is implied.
21
+
22
+ ## Limited grammar and results
23
+
24
+ This is a bounded frontmatter string-map grammar, not a generic YAML parser. The file begins with `---` and LF/CRLF, and closes its frontmatter with `---`. Exactly one root `name` scalar and one root `metadata:` map are required. The root `name` occupies one line; an indented non-comment continuation is malformed even across blank/comment lines or when the name follows the metadata map. Indented non-comment content before any root field is also malformed. Metadata entries have two-space indentation, lowercase ASCII keys, and no duplicates. Required metadata keys are `version`, `runtime-implementation`, `runtime-min-version`, `runtime-full-version`, and `runtime-capability-policy`.
25
+
26
+ Values are unescaped single/double-quoted strings or plain ASCII tokens beginning with a letter/digit and continuing with letters, digits, `.`, `_`, `/`, or `-`. A scalar value is separated from its colon by at least one literal ASCII space; comments require a separating space. For root `name`, the parser first requires that literal space and then removes leading whitespace with JavaScript `trimStart()` before parsing the scalar: `name:` followed by a literal space, a tab and the scalar is accepted, while a tab immediately after the colon is malformed. Metadata scalar separators retain their spaces-only grammar. Plain and quoted root names can occur before or after the metadata map. Quoted or noncanonical root key spellings are rejected rather than ignored as possibly ambiguous protected fields. Within `name` and `metadata`, YAML escape interpretation, tags, aliases, sequences, nested maps and block scalars are unsupported. Unrelated root fields and their indented content are ignored until the next root field; this does not permit a continuation of `name`. Protected name/map/scalar grammar does not parse or validate ignored field contents. Instruction bodies are never interpreted. The whole file must be valid UTF-8. A leading BOM, lone CR, and forbidden control characters are rejected. Body bytes are read; `metadata_only` is not a promise to avoid reading them.
27
+
28
+ | Evidence | Status / code | `verification` |
29
+ |---|---|---|
30
+ | Absent entrypoint (`ENOENT`/`ENOTDIR` before established file evidence) | missing / skill_missing | absent |
31
+ | Raw `EACCES`/`EPERM` reaching reader catch | permission_denied / permission_denied | absent |
32
+ | I/O failure, non-regular, overflow, invalid UTF-8, conflicting file evidence | unknown / skill_metadata_unreadable | absent |
33
+ | Missing/duplicate required name or scalar, missing/multiple map, unsupported syntax, BOM/control error | unknown / skill_metadata_missing | absent |
34
+ | Healthy bounded legacy/successor metadata; unavailable/malformed inspecting runtime identity, including ambiguous non-scalar evidence (proposed G04) | unknown / skill_metadata_missing | absent |
35
+ | Well-formed but unsupported name, tuple, or valid runtime | incompatible / skill_contract_mismatch | metadata_only |
36
+ | Exact supported runtime/profile/name | compatible / skill_contract_compatible | metadata_only |
37
+
38
+ The proposed **G04** expectation is fixed as exactly `{ status: 'unknown', code: 'skill_metadata_missing' }`, with no `verification` property, when the inspecting runtime identity is unavailable or malformed, including ambiguous non-scalar identity evidence. Its precondition is healthy bounded legacy/successor metadata: a readable regular file within the byte budget, valid UTF-8, stable file/path evidence, and valid frontmatter/name/profile. Earlier reader failures retain their own envelopes. The existing [`test/skill-metadata.test.ts`](https://github.com/abruption/session-peer-ts/blob/3cd52c166638e4833798e979a55ac71a0405d740/test/skill-metadata.test.ts) test `finite runtime/profile matrix preserves public 0.3.2 and checks the 0.3.3 candidate proposal` asserts this exact object for both profiles with explicit `null`, `{}`, `0`, `''`, `'0.3.3-preview.1'`, and `'00.3.3'` runtime arguments. An omitted or explicitly `undefined` helper argument uses the compiled `VERSION` default and is not an unavailable-identity fixture; the candidate test asserts both omitted and explicit `undefined` arguments use that compiled default. A valid but unsupported stable runtime (for example, `0.3.4`) instead returns exactly `{ status: 'incompatible', code: 'skill_contract_mismatch', verification: 'metadata_only' }`. This documents the TS proposal's G04 expectation covered by the exact static design acceptance below; it does not establish runtime publication or live delivery.
39
+
40
+ The proposed **G07** result for missing, duplicated, or syntactically malformed required frontmatter name/map/scalar evidence is exactly `{ status: 'unknown', code: 'skill_metadata_missing' }`, with no `verification` property. This applies after bounded regular-file evidence, valid UTF-8, and file/path stability have been established; earlier reader failures retain their own envelopes. A well-formed unsupported name or scalar remains `incompatible / skill_contract_mismatch / metadata_only`. The static grammar fixtures and `root name forbids continuations across comments or map boundaries while ignored fields retain their scope` establish this distinction. Both profiles are tested with plain/quoted names before or after metadata, one/two/four-space continuations, blank/comment-separated continuations, orphan indentation, and exact outer inspection results. Controls preserve comments, CRLF, unrelated field content, instruction bodies, and well-formed unsupported name results. This documents the TS proposal's G07 expectation covered by the exact static design acceptance below; it does not establish runtime publication or live delivery.
41
+
42
+ Path canonicalization preserves managed symlink installations. As before, wrapped canonicalization errors can reach the checker as `home_resolution_failed` and therefore `unknown`, rather than a raw permission result. No raw error message or instruction text is returned.
43
+
44
+ These are intentional changes from public TS `0.3.2` at [`f335f07`](https://github.com/abruption/session-peer-ts/blob/f335f07352c842f2f6ceb12bd2ca6274b52f69f7/src/diagnostics.ts): its checker does not validate root name and classifies missing/duplicate/malformed required metadata scalars as incompatible. Its missing/permission/unknown outputs already omit `verification`; this proposal preserves that placement. Public 0.3.2 historical behavior is not re-described as the future source grammar. Neither `compatible` verdict authenticates bytes, approves a send, or proves consumption/ACK.
45
+
46
+ ## Reader bound and file evidence
47
+
48
+ The budget is **65,536 whole-file raw UTF-8 bytes**, including BOM, whitespace, line endings and body. The reader allocates and reads at most **65,537 bytes**, with one overflow-detection byte. Pre-read size checks are an early rejection, not the only bound. Fatal UTF-8 decoding happens after the bounded read.
49
+
50
+ The original entrypoint is canonicalized so a separately managed symlink installation remains usable. The canonical target is inspected with `lstat`, then opened read-only (POSIX also uses `O_NONBLOCK` and `O_NOFOLLOW`). The descriptor must be a regular file and match pre-open device/inode/size/mtime/ctime. After bounded reading, descriptor and path evidence must still match and the original entrypoint must resolve to the same canonical target. Length must match the initial size. Growth, truncation, replacement, alias change, and same-size timestamp changes produce unknown, never a tuple verdict. Disappearance after initial file evidence is conflicting evidence, not a fresh absent-entrypoint result. Every opened descriptor is closed by `finally`.
51
+
52
+ The proposed **B04** fixture `reader rejects observed malformed-content rewrites during bounded chunked reads and closes its descriptor` rewrites the same file after the first real four-byte read, preserving its inode and size. Separate cases replace a protected scalar with malformed syntax or introduce invalid UTF-8. The first returned nonempty chunk is explicitly asserted to contain four bytes, outside reader error handling. Captured read chunks, including that unchanged first chunk, must concatenate to the actual malformed payload; an explicitly observable timestamp change establishes conflicting file evidence. Each case asserts exactly `unknown / skill_metadata_unreadable`, preserved path, no `verification` property, bounded read requests/allocation, and closure of the inspected descriptor exactly once. Fixture failures and assertions are checked outside the reader's error handling. This tests rejection of an observed mutation before parsing or decoding; it does not claim that either parser ran on the malformed bytes. Static malformed/UTF-8 fixtures separately establish their classifications. No atomic snapshot or malicious same-user writer guarantee follows from these tests.
53
+
54
+ These checks detect observed changes; they do not authenticate content against a malicious same-user writer capable of restoring identical metadata, atomically freeze a file, or impose an I/O deadline on arbitrary filesystems. Windows uses read-only opens and regular-file checks; POSIX special-file and symlink replacement cases are exercised on POSIX. Windows fixtures cover portable reader, profile, grammar, resource, and growth/truncation behavior through the native CI suite.
55
+
56
+ ## Fixtures and rollout
57
+
58
+ `test/skill-metadata.test.ts` exercises exact legacy/candidate matrix rows, unknown and future runtimes, every required scalar's missing/equal-duplicate/conflicting-duplicate/malformed/unsupported cases, wrong name/implementation, comments/quoting/CRLF, exact and overflow byte bounds, invalid UTF-8/BOM, regular files/FIFO, growth/truncation/replacement/alias changes including post-EOF changes, descriptor cleanup, bounded read allocation, raw error envelopes and zero runtime/network/write side effects. These are isolated local/CI fixtures, not installed-skill or delivery experiments. `test/diagnostics.test.ts` retains production doctor integration coverage.
59
+
60
+ ### Exact companion design acceptance — 2026-10-09 KST
61
+
62
+ Companion [Draft #20 acceptance at `699a3251830c30c62d0f812363faf4d0eb0c8e0c`](https://github.com/abruption/session-peer-skill/blob/699a3251830c30c62d0f812363faf4d0eb0c8e0c/docs/typescript-compatibility.md) accepts the finite runtime/profile matrix, limited parser/status envelopes, G07 root-name rule, and B04 reader fixtures for these exact reviewed candidates:
63
+
64
+ | Candidate | Reviewed source head | Reviewed design document SHA-256 |
65
+ | --- | --- | --- |
66
+ | TS #126 | [`ba18bb806a6ba503381259b4255211af3adc0336`](https://github.com/abruption/session-peer-ts/blob/ba18bb806a6ba503381259b4255211af3adc0336/docs/design/typescript-skill-compatibility.md) | `3d003cb3541add314941a8d72dc03648f4cabf7ab5a6d3a83d60ff8cc24fb8ea` |
67
+ | Release Draft #129 | [`bfb3d6f1256ab076a76660e08a7bf1ad071a6c6c`](https://github.com/abruption/session-peer-ts/blob/bfb3d6f1256ab076a76660e08a7bf1ad071a6c6c/docs/design/typescript-skill-compatibility.md) | `43244535795e22e720516415d79766cffa017b59daf9f070e1cfae632d19fbd1` |
68
+
69
+ This was read-only source, test and document review with CI-status confirmation; no tests were rerun in that review. At this dated checkpoint, the runtime and successor skill were unpublished. Acceptance applies to design and fixture profiles at the named heads; it does not authorize runtime merge/release, final successor skill metadata, publication, installation or pin changes, and establishes no live delivery, consumption or ACK. The two nonblocking syntax-precision follow-ups recorded in that acceptance are clarified here and covered by added plain-name-after-map and root whitespace fixtures, without changing parser behavior.
70
+
71
+ At the earlier 2026-10-09 coordination checkpoint, a dry-run found an inactive companion session and queued nothing, and a later authorized request was queued without established consumption or a review response. Those attempts remain historical evidence only; the immutable acceptance record above supplies the subsequent design review. Final skill metadata/publication/pin changes still require their own approval.
72
+
73
+ After separate merge/release authorization, the guard runtime must actually be published and its exact source/artifact/profile evidence recorded **before** finalizing and separately publishing successor skill metadata. Only then may the reviewed immutable skill pin and four-language guidance/PARITY change together. This PR does not modify the companion/Python repository, existing skill pin, Python runtime/reference/parity, global installation, PATH, or metadata release. No postinstall or automatic deployment is introduced. Unshipped 0.4 handoff/ACK/observation and unsupported wake/Antigravity/Relay/MCP remain outside this work.