@gate-forge/plugin-protocol 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 UKD
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,187 @@
1
+ # @gate-forge/plugin-protocol — GPP/3
2
+
3
+ The hardened Gateforge Plugin Protocol (version 3): newline-delimited JSON
4
+ framing over a plugin subprocess's stdin/stdout, with a pinned handshake,
5
+ per-message digests, schema-generated payload validation, and fail-closed
6
+ single-cause diagnostics on every violation (ADR 0002, decision D3).
7
+
8
+ Lineage: GPP/1 spike (`spikes/plugin-protocol/spec.md`, `host/host.py`,
9
+ `plugins/_lib.js`) proved the transport; GPP/2 added `pluginVersion` pinning,
10
+ the per-message `digest`, and zod-generated validation; GPP/3 (ADR 0003 D6)
11
+ adds the mandatory `classificationSignals` array to every `result` payload —
12
+ inside the digest-checked envelope. There is no GPP/2 compatibility path: a
13
+ GPP/2 peer fails closed at the handshake with `E_PROTOCOL_VERSION` naming both
14
+ versions, before any discovery runs.
15
+
16
+ ## Envelope (pin #5)
17
+
18
+ Every frame is one line (`\n`-delimited, UTF-8, 8 MiB cap per line):
19
+
20
+ ```json
21
+ {
22
+ "protocolVersion": 3,
23
+ "pluginId": "pack-sqlalchemy",
24
+ "pluginVersion": "1.0.0",
25
+ "type": "result",
26
+ "seq": 2,
27
+ "payload": { "…": "…" },
28
+ "digest": "<64 lowercase hex chars>"
29
+ }
30
+ ```
31
+
32
+ `digest = sha256(canonical({type, seq, payload}))` over GF-canonical-JSON
33
+ (`@gate-forge/core`'s `sha256Canonical`): UTF-8, recursively key-sorted, no
34
+ whitespace, integers plain. The handshake (`hello`/`ready`) pins
35
+ `protocolVersion`, `pluginId`, and `pluginVersion`; every later frame is
36
+ checked against the pinned identity. `seq` is per-direction, 1-based,
37
+ strictly sequential.
38
+
39
+ ## Message catalog
40
+
41
+ | type | direction | payload |
42
+ | ---------- | -------------- | -------------------------------------------------------------------- |
43
+ | `hello` | plugin → host | `{capabilities: string[]}` (non-empty; host requires `"discover"`) |
44
+ | `ready` | host → plugin | `{}` |
45
+ | `discover` | host → plugin | `{requestId: string, paths: string[]}` (repo-relative, no `..`) |
46
+ | `result` | plugin → host | `{requestId, resources[], unresolved[], findings[], classificationSignals[]}` |
47
+ | `error` | both | `{requestId?, code, message}` — with `requestId`: request-scoped; without: session-fatal |
48
+ | `shutdown` | host → plugin | `{}` |
49
+ | `bye` | plugin → host | `{}` — then the plugin exits 0 |
50
+
51
+ Session shape: one spawn, one handshake, many lock-step discovers (at most
52
+ one outstanding request), one shutdown handshake. `result.resources`
53
+ matches `@gate-forge/core`'s `ResourceSchema`; `result.unresolved` matches
54
+ `UnresolvedReasonSchema`; `findings` are `{code, detail, locations[]}`
55
+ (e.g. `DUPLICATE_TABLE_NAME`); `result.classificationSignals` matches
56
+ `@gate-forge/core`'s `ClassificationSignalSchema` (ADR 0003 D1). The field is
57
+ mandatory since the version bump — a detector without signal support sends
58
+ `[]`, and its resources fall back to conservative classification defaults. A
59
+ result omitting the field fails `E_SCHEMA` (no unversioned optional-field
60
+ compatibility). Payload zod schemas live in `src/schema.ts` and are enforced
61
+ on receive. Signals never travel outside the digest-checked envelope.
62
+
63
+ ## Capabilities
64
+
65
+ `hello.capabilities` is a non-empty list; the host requires `"discover"`.
66
+ GPP/3 defines one additional capability a plugin MAY declare:
67
+
68
+ - `classification-signals` — the plugin's discovery handler emits
69
+ classification-signal facts. The host does NOT require it; the capability
70
+ states what the `result` payload may contain, never less.
71
+
72
+ ## Failure codes
73
+
74
+ Every violation is a distinct error class (`src/codes.ts`), fails the
75
+ session closed (plugin killed), and renders one actionable diagnostic —
76
+ frame number, message type, offending field, expected vs got — never a
77
+ stack dump:
78
+
79
+ ```
80
+ [plugin-protocol] FAIL E_PROTOCOL_VERSION: frame 1: envelope protocolVersion=2 but the host speaks 3
81
+ [plugin-protocol] offending frame: {"protocolVersion":2,…}
82
+ ```
83
+
84
+ | code | trigger |
85
+ | -------------------- | -------------------------------------------------------------------- |
86
+ | `E_PROTOCOL_VERSION` | envelope/handshake `protocolVersion` ≠ 3 (a GPP/2 peer fails here, before discovery) |
87
+ | `E_UNKNOWN_PLUGIN` | `pluginId`/`pluginVersion` differs from the pinned registration (GF-18) |
88
+ | `E_FRAME_JSON` | empty line, invalid JSON, non-object frame, or line over the 8 MiB cap |
89
+ | `E_UNKNOWN_TYPE` | envelope `type` not in the catalog |
90
+ | `E_SCHEMA` | missing/mistyped field, digest mismatch, seq gap, wrong phase, wrong `requestId`, missing `classificationSignals` |
91
+ | `E_EOF` | plugin stream ended before the expected frame (exit code reported) |
92
+ | `E_TIMEOUT` | no expected frame within the watchdog budget; plugin killed (SIGKILL) |
93
+ | `E_PLUGIN_ERROR` | plugin answered a request (or the session) with an `error` frame |
94
+ | `E_EXIT_STATUS` | plugin exited nonzero (or hung) after a clean `bye` |
95
+
96
+ ## Migrating a GPP/2 plugin
97
+
98
+ 1. Bump every envelope your plugin builds to `protocolVersion: 3` (the SDKs
99
+ export the pinned `PROTOCOL_VERSION` — use it instead of literals).
100
+ 2. Return `classificationSignals: []` (or real signal facts) from your
101
+ discover handler. The TS SDK type and the Python `serve()` docstring pin
102
+ the shape; the wire rejects the field's absence.
103
+ 3. Optionally declare the `classification-signals` capability.
104
+
105
+ A pre-migration plugin fails with
106
+ `E_PROTOCOL_VERSION: envelope protocolVersion=2 but the host speaks 3` —
107
+ the expected-versus-received diagnostic names the exact version delta.
108
+
109
+ ## Writing a plugin
110
+
111
+ ### TypeScript
112
+
113
+ ```ts
114
+ import { servePlugin } from '@gate-forge/plugin-protocol';
115
+
116
+ await servePlugin(
117
+ async (paths) => ({
118
+ resources: scanForResources(paths),
119
+ unresolved: [],
120
+ findings: [],
121
+ classificationSignals: emitSignals(paths), // [] when unsupported
122
+ }),
123
+ { pluginId: 'my-detector', pluginVersion: '1.0.0' },
124
+ );
125
+ ```
126
+
127
+ `servePlugin` performs the handshake, validates host frames (digest, seq,
128
+ identity), answers `discover` through your handler (a throw becomes a
129
+ request-scoped `error` frame), and completes the shutdown handshake. I/O is
130
+ injectable (`input`/`output`) for tests.
131
+
132
+ ### Python (stdlib only)
133
+
134
+ ```python
135
+ from gateforge_plugin import serve
136
+
137
+ def discover(paths):
138
+ return {"resources": scan(paths), "unresolved": [], "findings": [],
139
+ "classificationSignals": signals(paths)} # [] when unsupported
140
+
141
+ raise SystemExit(serve("my-detector", "1.0.0", discover))
142
+ ```
143
+
144
+ `python/gateforge_plugin/__init__.py` is the client module; the package
145
+ ships the Python side as source (`python/`) — plugins add it to `sys.path`
146
+ (see `python/plugins/reference_detector.py`) or install it.
147
+
148
+ ## Driving plugins (engine side)
149
+
150
+ ```ts
151
+ import { PluginSession } from '@gate-forge/plugin-protocol';
152
+
153
+ const session = new PluginSession({
154
+ command: ['node', 'plugin.js', repoRoot],
155
+ pluginId: 'my-detector', // pinned at the handshake
156
+ pluginVersion: '1.0.0',
157
+ timeouts: { handshakeMs: 10_000, requestMs: 10_000, shutdownMs: 5_000 },
158
+ });
159
+ await session.start();
160
+ const outcome = await session.discover(['src/routes.py']); // repeatable, lock-step
161
+ await session.shutdown(); // bye + exit 0
162
+ ```
163
+
164
+ Watchdogs run per read; any failure kills the plugin. `dispose()` is a
165
+ best-effort kill that never throws. For tests, `maxLineBytes` and all three
166
+ timeouts are overridable.
167
+
168
+ ## Layout
169
+
170
+ - `src/host.ts` — engine-side host (`PluginSession`)
171
+ - `src/plugin.ts` — TypeScript plugin SDK (`servePlugin`)
172
+ - `src/schema.ts` — message catalog + zod payload schemas
173
+ - `src/framing.ts` — line framing, envelope verify/build (shared by both sides)
174
+ - `src/codes.ts` — failure classes + `formatDiagnostic`
175
+ - `python/gateforge_plugin/` — Python client (stdlib only)
176
+ - `python/plugins/reference_detector.py` — Python reference detector
177
+ - `test/fixtures/` — one-fault-per-plugin fixtures powering the E_* tests
178
+ (`app/routes.gfx` is the shared trivial fixture format; `plugin_gpp2_peer.mjs`
179
+ is the pre-cutover peer used to prove the fail-closed handshake)
180
+ - `test/host.test.ts` — GF-12 + GF-18 mechanics: every E_* code with
181
+ diagnostic assertions, green multi-discover session, determinism
182
+ - `test/cross-language.test.ts` — TS host x Python plugin interop
183
+ (byte-identical discovery documents incl. signals)
184
+ - `test/plugin-sdk.test.ts` — SDK envelope/digest correctness
185
+
186
+ Requires Node >= 20 (TS side), Python >= 3.12 (Python side); no network at
187
+ any point.
@@ -0,0 +1,77 @@
1
+ /**
2
+ * GPP/3 failure codes and their error classes (ADR 0002 D3).
3
+ *
4
+ * Every failure is a distinct class extending {@link ProtocolFailure} and
5
+ * carries a single-cause, actionable detail naming (where applicable) the
6
+ * frame number, message type, offending field, and expected vs got — never
7
+ * a stack dump. Consumers render diagnostics via {@link formatDiagnostic};
8
+ * `error.stack` is a JS-runtime artifact and must never be printed by the
9
+ * host.
10
+ */
11
+ /** Every fail-closed GPP/3 diagnostic code. */
12
+ export declare const FAILURE_CODES: readonly ["E_PROTOCOL_VERSION", "E_UNKNOWN_PLUGIN", "E_FRAME_JSON", "E_UNKNOWN_TYPE", "E_SCHEMA", "E_EOF", "E_TIMEOUT", "E_PLUGIN_ERROR", "E_EXIT_STATUS"];
13
+ /** Union of all GPP/3 failure codes. */
14
+ export type ProtocolFailureCode = (typeof FAILURE_CODES)[number];
15
+ /** Rendering context attached to a failure for the offending-frame line. */
16
+ export interface FailureContext {
17
+ /** 1-based ordinal of the received frame that caused the failure. */
18
+ frameNo?: number;
19
+ /** Raw stdout line (truncated to 200 chars by formatDiagnostic). */
20
+ rawLine?: string;
21
+ }
22
+ /**
23
+ * Base class for every fail-closed protocol failure. The `message` is the
24
+ * single-cause detail; `code`/`frameNo`/`rawLine` are structured fields.
25
+ */
26
+ export declare class ProtocolFailure extends Error {
27
+ readonly code: ProtocolFailureCode;
28
+ readonly frameNo: number | undefined;
29
+ readonly rawLine: string | undefined;
30
+ constructor(code: ProtocolFailureCode, detail: string, context?: FailureContext);
31
+ }
32
+ /** Handshake or envelope declared a protocol version other than 3. */
33
+ export declare class ProtocolVersionError extends ProtocolFailure {
34
+ constructor(detail: string, context?: FailureContext);
35
+ }
36
+ /** Plugin identity (pluginId or pluginVersion) differs from the pinned registration. */
37
+ export declare class UnknownPluginError extends ProtocolFailure {
38
+ constructor(detail: string, context?: FailureContext);
39
+ }
40
+ /** Framing violation: empty line, invalid JSON, non-object frame, or over the line cap. */
41
+ export declare class FrameJsonError extends ProtocolFailure {
42
+ constructor(detail: string, context?: FailureContext);
43
+ }
44
+ /** Envelope `type` is not in the message catalog. */
45
+ export declare class UnknownTypeError extends ProtocolFailure {
46
+ constructor(detail: string, context?: FailureContext);
47
+ }
48
+ /** Missing/mistyped mandatory field, digest mismatch, seq gap, or state violation. */
49
+ export declare class SchemaError extends ProtocolFailure {
50
+ constructor(detail: string, context?: FailureContext);
51
+ }
52
+ /** Plugin stream ended (plugin exited) before the expected frame arrived. */
53
+ export declare class EofError extends ProtocolFailure {
54
+ constructor(detail: string, context?: FailureContext);
55
+ }
56
+ /** No expected frame within the watchdog budget; the plugin is killed. */
57
+ export declare class TimeoutError extends ProtocolFailure {
58
+ constructor(detail: string, context?: FailureContext);
59
+ }
60
+ /** Plugin answered a request (or the session) with an `error` frame. */
61
+ export declare class PluginError extends ProtocolFailure {
62
+ constructor(detail: string, context?: FailureContext);
63
+ }
64
+ /** Plugin exited nonzero (or had to be killed) after a clean `bye`. */
65
+ export declare class ExitStatusError extends ProtocolFailure {
66
+ constructor(detail: string, context?: FailureContext);
67
+ }
68
+ /** Narrows an unknown thrown value to a {@link ProtocolFailure}, optionally by code. */
69
+ export declare function isProtocolFailure(value: unknown, code?: ProtocolFailureCode): value is ProtocolFailure;
70
+ /**
71
+ * Renders the two-line host diagnostic (spec §5 lineage):
72
+ * `[plugin-protocol] FAIL <CODE>: <detail>` plus, when the offending raw
73
+ * frame is known, `[plugin-protocol] offending frame: <raw, ≤200 chars>`.
74
+ * Never includes stack frames.
75
+ */
76
+ export declare function formatDiagnostic(failure: ProtocolFailure): string;
77
+ //# sourceMappingURL=codes.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codes.d.ts","sourceRoot":"","sources":["../src/codes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,+CAA+C;AAC/C,eAAO,MAAM,aAAa,4JAUhB,CAAC;AAEX,wCAAwC;AACxC,MAAM,MAAM,mBAAmB,GAAG,CAAC,OAAO,aAAa,CAAC,CAAC,MAAM,CAAC,CAAC;AAEjE,4EAA4E;AAC5E,MAAM,WAAW,cAAc;IAC7B,qEAAqE;IACrE,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,oEAAoE;IACpE,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,qBAAa,eAAgB,SAAQ,KAAK;IACxC,QAAQ,CAAC,IAAI,EAAE,mBAAmB,CAAC;IACnC,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;IACrC,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,SAAS,CAAC;gBAEzB,IAAI,EAAE,mBAAmB,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;CAOpF;AAED,sEAAsE;AACtE,qBAAa,oBAAqB,SAAQ,eAAe;gBAC3C,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;CAGzD;AAED,wFAAwF;AACxF,qBAAa,kBAAmB,SAAQ,eAAe;gBACzC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;CAGzD;AAED,2FAA2F;AAC3F,qBAAa,cAAe,SAAQ,eAAe;gBACrC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;CAGzD;AAED,qDAAqD;AACrD,qBAAa,gBAAiB,SAAQ,eAAe;gBACvC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;CAGzD;AAED,sFAAsF;AACtF,qBAAa,WAAY,SAAQ,eAAe;gBAClC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;CAGzD;AAED,6EAA6E;AAC7E,qBAAa,QAAS,SAAQ,eAAe;gBAC/B,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;CAGzD;AAED,0EAA0E;AAC1E,qBAAa,YAAa,SAAQ,eAAe;gBACnC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;CAGzD;AAED,wEAAwE;AACxE,qBAAa,WAAY,SAAQ,eAAe;gBAClC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;CAGzD;AAED,uEAAuE;AACvE,qBAAa,eAAgB,SAAQ,eAAe;gBACtC,MAAM,EAAE,MAAM,EAAE,OAAO,GAAE,cAAmB;CAGzD;AAED,wFAAwF;AACxF,wBAAgB,iBAAiB,CAAC,KAAK,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,mBAAmB,GAAG,KAAK,IAAI,eAAe,CAGtG;AAMD;;;;;GAKG;AACH,wBAAgB,gBAAgB,CAAC,OAAO,EAAE,eAAe,GAAG,MAAM,CAMjE"}
package/dist/codes.js ADDED
@@ -0,0 +1,115 @@
1
+ /**
2
+ * GPP/3 failure codes and their error classes (ADR 0002 D3).
3
+ *
4
+ * Every failure is a distinct class extending {@link ProtocolFailure} and
5
+ * carries a single-cause, actionable detail naming (where applicable) the
6
+ * frame number, message type, offending field, and expected vs got — never
7
+ * a stack dump. Consumers render diagnostics via {@link formatDiagnostic};
8
+ * `error.stack` is a JS-runtime artifact and must never be printed by the
9
+ * host.
10
+ */
11
+ /** Every fail-closed GPP/3 diagnostic code. */
12
+ export const FAILURE_CODES = [
13
+ 'E_PROTOCOL_VERSION',
14
+ 'E_UNKNOWN_PLUGIN',
15
+ 'E_FRAME_JSON',
16
+ 'E_UNKNOWN_TYPE',
17
+ 'E_SCHEMA',
18
+ 'E_EOF',
19
+ 'E_TIMEOUT',
20
+ 'E_PLUGIN_ERROR',
21
+ 'E_EXIT_STATUS',
22
+ ];
23
+ /**
24
+ * Base class for every fail-closed protocol failure. The `message` is the
25
+ * single-cause detail; `code`/`frameNo`/`rawLine` are structured fields.
26
+ */
27
+ export class ProtocolFailure extends Error {
28
+ code;
29
+ frameNo;
30
+ rawLine;
31
+ constructor(code, detail, context = {}) {
32
+ super(detail);
33
+ this.name = new.target.name;
34
+ this.code = code;
35
+ this.frameNo = context.frameNo;
36
+ this.rawLine = context.rawLine;
37
+ }
38
+ }
39
+ /** Handshake or envelope declared a protocol version other than 3. */
40
+ export class ProtocolVersionError extends ProtocolFailure {
41
+ constructor(detail, context = {}) {
42
+ super('E_PROTOCOL_VERSION', detail, context);
43
+ }
44
+ }
45
+ /** Plugin identity (pluginId or pluginVersion) differs from the pinned registration. */
46
+ export class UnknownPluginError extends ProtocolFailure {
47
+ constructor(detail, context = {}) {
48
+ super('E_UNKNOWN_PLUGIN', detail, context);
49
+ }
50
+ }
51
+ /** Framing violation: empty line, invalid JSON, non-object frame, or over the line cap. */
52
+ export class FrameJsonError extends ProtocolFailure {
53
+ constructor(detail, context = {}) {
54
+ super('E_FRAME_JSON', detail, context);
55
+ }
56
+ }
57
+ /** Envelope `type` is not in the message catalog. */
58
+ export class UnknownTypeError extends ProtocolFailure {
59
+ constructor(detail, context = {}) {
60
+ super('E_UNKNOWN_TYPE', detail, context);
61
+ }
62
+ }
63
+ /** Missing/mistyped mandatory field, digest mismatch, seq gap, or state violation. */
64
+ export class SchemaError extends ProtocolFailure {
65
+ constructor(detail, context = {}) {
66
+ super('E_SCHEMA', detail, context);
67
+ }
68
+ }
69
+ /** Plugin stream ended (plugin exited) before the expected frame arrived. */
70
+ export class EofError extends ProtocolFailure {
71
+ constructor(detail, context = {}) {
72
+ super('E_EOF', detail, context);
73
+ }
74
+ }
75
+ /** No expected frame within the watchdog budget; the plugin is killed. */
76
+ export class TimeoutError extends ProtocolFailure {
77
+ constructor(detail, context = {}) {
78
+ super('E_TIMEOUT', detail, context);
79
+ }
80
+ }
81
+ /** Plugin answered a request (or the session) with an `error` frame. */
82
+ export class PluginError extends ProtocolFailure {
83
+ constructor(detail, context = {}) {
84
+ super('E_PLUGIN_ERROR', detail, context);
85
+ }
86
+ }
87
+ /** Plugin exited nonzero (or had to be killed) after a clean `bye`. */
88
+ export class ExitStatusError extends ProtocolFailure {
89
+ constructor(detail, context = {}) {
90
+ super('E_EXIT_STATUS', detail, context);
91
+ }
92
+ }
93
+ /** Narrows an unknown thrown value to a {@link ProtocolFailure}, optionally by code. */
94
+ export function isProtocolFailure(value, code) {
95
+ if (!(value instanceof ProtocolFailure))
96
+ return false;
97
+ return code === undefined || value.code === code;
98
+ }
99
+ function truncate(text, max) {
100
+ return text.length <= max ? text : `${text.slice(0, max)}…`;
101
+ }
102
+ /**
103
+ * Renders the two-line host diagnostic (spec §5 lineage):
104
+ * `[plugin-protocol] FAIL <CODE>: <detail>` plus, when the offending raw
105
+ * frame is known, `[plugin-protocol] offending frame: <raw, ≤200 chars>`.
106
+ * Never includes stack frames.
107
+ */
108
+ export function formatDiagnostic(failure) {
109
+ const lines = [`[plugin-protocol] FAIL ${failure.code}: ${failure.message}`];
110
+ if (failure.rawLine !== undefined) {
111
+ lines.push(`[plugin-protocol] offending frame: ${truncate(failure.rawLine, 200)}`);
112
+ }
113
+ return lines.join('\n');
114
+ }
115
+ //# sourceMappingURL=codes.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"codes.js","sourceRoot":"","sources":["../src/codes.ts"],"names":[],"mappings":"AAAA;;;;;;;;;GASG;AAEH,+CAA+C;AAC/C,MAAM,CAAC,MAAM,aAAa,GAAG;IAC3B,oBAAoB;IACpB,kBAAkB;IAClB,cAAc;IACd,gBAAgB;IAChB,UAAU;IACV,OAAO;IACP,WAAW;IACX,gBAAgB;IAChB,eAAe;CACP,CAAC;AAaX;;;GAGG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAC/B,IAAI,CAAsB;I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,IAAI,OAAO,CAAC,OAAO,KAAK,SAAS,EAAE,CAAC;QAClC,KAAK,CAAC,IAAI,CAAC,sCAAsC,QAAQ,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE,CAAC,CAAC;IACrF,CAAC;IACD,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;AAC1B,CAAC"}
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Line framing + envelope construction/verification shared by the host and
3
+ * the TS plugin SDK (spec §1–§2 lineage, hardened per ADR 0002 D3).
4
+ *
5
+ * Framing: one JSON object per line, `\n`-delimited, UTF-8, 8 MiB cap.
6
+ * Envelope: `{protocolVersion, pluginId, pluginVersion, type, seq, payload,
7
+ * digest}` with `digest = sha256(canonical({type, seq, payload}))`.
8
+ */
9
+ import { type JsonValue } from '@gate-forge/core';
10
+ import { type MessageType } from './schema.js';
11
+ /** A fully decoded and verified GPP/3 frame. */
12
+ export interface GppEnvelope {
13
+ protocolVersion: 3;
14
+ pluginId: string;
15
+ pluginVersion: string;
16
+ type: MessageType;
17
+ seq: number;
18
+ payload: unknown;
19
+ digest: string;
20
+ }
21
+ /** Splits an accumulated stdout buffer into complete lines. */
22
+ export declare function extractLines(buffer: Buffer): {
23
+ lines: Buffer[];
24
+ rest: Buffer;
25
+ };
26
+ /**
27
+ * Parses one raw stdout line into a JSON object. Fails closed with
28
+ * `E_FRAME_JSON` on empty lines, invalid JSON, and non-object frames.
29
+ */
30
+ export declare function parseLine(raw: Buffer, frameNo: number, expect: string): Record<string, unknown>;
31
+ /** Context for verifying a received envelope. */
32
+ export interface EnvelopeContext {
33
+ /** pluginId this side pinned at the handshake. */
34
+ pinnedId: string;
35
+ /** pluginVersion this side pinned at the handshake. */
36
+ pinnedVersion: string;
37
+ /** Next legal `seq` of the peer (starts at 1, strictly sequential). */
38
+ expectedSeq: number;
39
+ }
40
+ /**
41
+ * Verifies the transport envelope of a received frame: mandatory fields,
42
+ * protocol version, catalog membership, pinned identity, seq order, and
43
+ * digest. Fails closed with the code matching the first violated rule.
44
+ * Returns the narrowed envelope (payload still unvalidated).
45
+ */
46
+ export declare function verifyEnvelope(frame: Record<string, unknown>, frameNo: number, ctx: EnvelopeContext): GppEnvelope;
47
+ /**
48
+ * Validates a verified envelope's payload against the per-type schema.
49
+ * Throws `E_SCHEMA` with the first failing field path on mismatch.
50
+ */
51
+ export declare function verifyPayload(envelope: GppEnvelope, frameNo: number): unknown;
52
+ /**
53
+ * Builds one outgoing frame (this side's identity + seq) and serializes it
54
+ * as a newline-terminated JSON line with the canonical digest.
55
+ */
56
+ export declare function encodeFrame(identity: {
57
+ pluginId: string;
58
+ pluginVersion: string;
59
+ }, type: MessageType, seq: number, payload: JsonValue): string;
60
+ //# sourceMappingURL=framing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"framing.d.ts","sourceRoot":"","sources":["../src/framing.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAgC,KAAK,SAAS,EAAE,MAAM,kBAAkB,CAAC;AAShF,OAAO,EAAoE,KAAK,WAAW,EAAE,MAAM,aAAa,CAAC;AAEjH,gDAAgD;AAChD,MAAM,WAAW,WAAW;IAC1B,eAAe,EAAE,CAAC,CAAC;IACnB,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,MAAM,CAAC;IACtB,IAAI,EAAE,WAAW,CAAC;IAClB,GAAG,EAAE,MAAM,CAAC;IACZ,OAAO,EAAE,OAAO,CAAC;IACjB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,+DAA+D;AAC/D,wBAAgB,YAAY,CAAC,MAAM,EAAE,MAAM,GAAG;IAAE,KAAK,EAAE,MAAM,EAAE,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,CAU9E;AAED;;;GAGG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,CAAC,M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