@sagmans/dsh-plannotator 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 sagmans
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,174 @@
1
+ # dsh-plannotator
2
+
3
+ Browser review for the DeepSeek Harness terminal profile: read a plan, a
4
+ document, or a code change in [Plannotator](https://github.com/plannotator/plannotator)'s
5
+ interface, then send what you think back to the agent — without leaving the TUI.
6
+
7
+ ```
8
+ /plannotator-plan review this session's plan
9
+ /plannotator-review review the worktree or a pull request
10
+ /plannotator-annotate annotate a file, a folder, or a URL
11
+ /plannotator-last annotate the agent's last answer
12
+ ```
13
+
14
+ Each command opens the browser, waits for your decision, prints one line in the
15
+ terminal, and forwards your words to the model as a steering message. The agent
16
+ can then act on them in the same session.
17
+
18
+ ## Why commands instead of plan-mode integration
19
+
20
+ Plan mode keeps its own review path. This plugin adds a second, on-demand one,
21
+ because that path is not always reachable: a session on a remote host without a
22
+ forwarded port cannot open a browser at all, and a reader often wants to review
23
+ something that is not the plan they just wrote. Nothing here replaces or patches
24
+ the shipped plan-mode review; if the profile cannot use this plugin, plan mode
25
+ still works exactly as before.
26
+
27
+ ## Requirements
28
+
29
+ - DeepSeek Harness `0.1.5-rc.1` or newer, `0.1.6` or older.
30
+ - The `plannotator` CLI on `PATH`, or pointed at by configuration. Install it
31
+ the way its own documentation describes; this plugin never downloads it.
32
+ - A browser on the machine that runs the CLI. For a remote host, either forward
33
+ the port or set `tailscale: true` and reach the session over the tailnet.
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ dsh plugin --profile tui add @sagmans/dsh-plannotator
39
+ ```
40
+
41
+ The profile loads every bundle listed in its `package.json`; confirm the bundle
42
+ is listed there after the install. From a checkout, install the directory
43
+ instead:
44
+
45
+ ```bash
46
+ dsh plugin --profile tui add link:/path/to/dsh-plannotator
47
+ ```
48
+
49
+ ## Commands
50
+
51
+ | Command | Runs | Notes |
52
+ | --- | --- | --- |
53
+ | `/plannotator-plan [file.md]` | `annotate <plan> --gate --json --require-approval` | With no argument, the newest plan in the session is snapshotted and reviewed. |
54
+ | `/plannotator-review [options] [PR_URL]` | `review <options> --json` | Reviews the worktree by default. |
55
+ | `/plannotator-annotate <file\|folder\|URL>` | `annotate <target> --gate --json --require-approval` | The target must exist, or be an `http(s)` URL. |
56
+ | `/plannotator-last` | `annotate-last --stdin --gate --json` | The message is piped on stdin and never written to disk. |
57
+
58
+ `review` accepts `--git`, `--gitbutler`, `--base <ref>`, `--diff-type <type>`,
59
+ `--local`, `--no-local`, `--no-git-remote-check`, and `--tailscale`. `annotate`
60
+ accepts `--markdown`, `--no-jina`, `--app`, `--static`, `--render-html`, and
61
+ `--tailscale`. Any other flag is refused with usage text instead of being passed
62
+ to the CLI.
63
+
64
+ ## How a decision comes back
65
+
66
+ The plugin reads the CLI's own verdict, never the wording of a message:
67
+
68
+ | Surface | Verdict source | Feedback field |
69
+ | --- | --- | --- |
70
+ | `annotate` | exit `0` approved, `1` not approved, `2` gate failure | `feedback` |
71
+ | `review` | `decision` in the JSON record | `message` |
72
+ | `annotate-last` | `decision` in the JSON record | `feedback` |
73
+
74
+ An approval is reported as an approval. Notes attached to an approval are
75
+ forwarded as non-blocking guidance, which is how Plannotator frames them; set
76
+ `approveNotes: ignore` to keep them out of the conversation, or
77
+ `steerFeedback: false` to keep every review local.
78
+
79
+ ## Configuration
80
+
81
+ Every key is optional. Restate the ones you keep when you patch the row, because
82
+ an id-targeted patch replaces the whole config block.
83
+
84
+ | Key | Default | Meaning |
85
+ | --- | --- | --- |
86
+ | `binary` | `''` | Absolute path to the executable. Empty means `$PLANNOTATOR_BIN`, then `PATH`. |
87
+ | `dataDir` | `''` | Where plan snapshots are written. Empty means `$PLANNOTATOR_DATA_DIR`, then `~/.plannotator`. |
88
+ | `reviewTimeoutMs` | `0` | Hard ceiling on one review. `0` waits as long as the browser session lives. |
89
+ | `tailscale` | `false` | Publish each review over the tailnet. |
90
+ | `steerFeedback` | `true` | Forward reviewer feedback to the model. |
91
+ | `approveNotes` | `steer` | `steer` or `ignore` notes that arrive with an approval. |
92
+ | `allowUntrustedBinary` | `false` | Accept an executable this user does not own, or that others can rewrite. |
93
+ | `maxInputBytes` | `1048576` | Largest plan or transcript handed to a review. |
94
+
95
+ ```yaml
96
+ # ~/.dsh/profiles/tui/cordis.patch.yml
97
+ - id: plannotator
98
+ config:
99
+ reviewTimeoutMs: 900000
100
+ tailscale: true
101
+ ```
102
+
103
+ ## Security
104
+
105
+ - **No shell.** The executable is spawned with an argv array and `shell: false`,
106
+ so no path, branch name, or reviewer's word is ever parsed as syntax.
107
+ - **Vetted executable.** The resolved binary must be executable, owned by this
108
+ user, and not writable by others; a file that fails is refused by name unless
109
+ `allowUntrustedBinary` is set.
110
+ - **Private plans.** A plan snapshot is written under
111
+ `<dataDir>/dsh/plans/<session-id>.md` with mode `0600`, its directory with
112
+ `0700`, and it is renamed into place so a reader never sees a partial file.
113
+ Plans stay out of your repository.
114
+ - **Allowlisted flags.** Each subcommand has its own flag list. An unknown flag
115
+ fails the command; it is never forwarded.
116
+ - **Bounded capture.** Each stream is capped, and a cancelled or over-long
117
+ review is terminated with SIGTERM and then SIGKILL after two seconds.
118
+ - **One review at a time.** A second command is refused while a review is open,
119
+ and unloading the plugin stops the one that is running.
120
+ - **No runtime dependencies.** The bundle uses harness packages it receives by
121
+ injection and Node builtins only.
122
+
123
+ ## Development
124
+
125
+ ```bash
126
+ pnpm install
127
+ pnpm run check # typecheck, unit tests, build, built-artefact tests, pack smoke
128
+ pnpm run drive # drive a real TUI in a PTY (see tools/pty-drive.mjs --help)
129
+ ```
130
+
131
+ `tests/fixtures/fake-plannotator.mjs` stands in for the CLI. It implements the
132
+ documented contract — argv, stdin, JSON records, strict exit codes — so the
133
+ suite covers the whole spawn path without a browser.
134
+
135
+ ### End-to-end check with a real browser
136
+
137
+ The suite stops at the CLI boundary. To prove the whole loop, mount the bundle
138
+ in a scratch profile, make the CLI publish its URL instead of opening a browser,
139
+ and drive that page:
140
+
141
+ Copy the profile you already work in — it carries the bundles and the patch that
142
+ register your model route and credentials — then add this plugin to the copy.
143
+ Dropping those rows leaves the profile without an adapter for the model its
144
+ settings name, and the surface then answers from whichever provider it does
145
+ have, which is a failure that looks like a plugin problem and is not one.
146
+
147
+ ```bash
148
+ PROFILE=tui-plannotator-e2e
149
+ cp -R ~/.dsh/profiles/tui ~/.dsh/profiles/$PROFILE
150
+ cd ~/.dsh/profiles/$PROFILE
151
+ # Add the plugin to dsh.profile.bundles and to dependencies, then:
152
+ dsh plugin --profile $PROFILE install
153
+
154
+ # Drive the surface, and let the CLI report where its review page lives.
155
+ PLANNOTATOR_SKIP_BROWSER_OPEN=1 \
156
+ PLANNOTATOR_READY_FILE=/tmp/plannotator-ready.json \
157
+ PLANNOTATOR_DATA_DIR=/tmp/plannotator-data \
158
+ pnpm run drive -- --profile tui-plannotator-e2e --cwd /tmp/scratch \
159
+ --prelude "/plannotator-annotate notes.md" --seconds 120 \
160
+ --expect "annotation feedback sent to the agent"
161
+ ```
162
+
163
+ Open the URL from `/tmp/plannotator-ready.json`, annotate, and send feedback.
164
+ The terminal shows one notice, and the reviewer's words appear in the transcript
165
+ as a `[plannotator]` user message — which is what the model then answers.
166
+
167
+ Symptom to recognise: a turn that fails with `Insufficient Balance` or `no
168
+ adapter registered for provider "<route>"` right after the notice means the
169
+ profile in use cannot reach the model its settings name. It is a profile
170
+ composition fault, not a review fault: the reviewer's words did arrive.
171
+
172
+ ## License
173
+
174
+ MIT
@@ -0,0 +1,26 @@
1
+ # dsh-plannotator — browser review surfaces for the terminal profile.
2
+ #
3
+ # The row is self-inserting so `dsh plugin --profile tui add` is the whole
4
+ # install: the loader composes this patch as one bundle layer, and the plugin's
5
+ # package manifest owns the row's identity. Nothing in the base is replaced,
6
+ # because this plugin registers commands only and serves no service of its own.
7
+ #
8
+ # Every value here is a default a reader can override from the profile's own
9
+ # cordis.patch.yml (an id-targeted patch replaces the whole config block, so
10
+ # restate the fields you keep).
11
+ - insert:
12
+ - id: plannotator
13
+ name: '@sagmans/dsh-plannotator'
14
+ config:
15
+ # Empty means the resolver's own order: $PLANNOTATOR_BIN, then PATH.
16
+ binary: ''
17
+ # Empty means $PLANNOTATOR_DATA_DIR, then ~/.plannotator.
18
+ dataDir: ''
19
+ # 0 waits as long as the CLI server lives; a browser tab left open is
20
+ # the human's decision, not a timeout.
21
+ reviewTimeoutMs: 0
22
+ tailscale: false
23
+ steerFeedback: true
24
+ approveNotes: steer
25
+ allowUntrustedBinary: false
26
+ maxInputBytes: 1048576
package/dist/args.d.ts ADDED
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Build the argv this plugin hands to the CLI.
3
+ *
4
+ * Two rules shape this module. First, the reviewer's input never becomes shell
5
+ * syntax: argv is an array handed to `spawn` with `shell: false`, and the
6
+ * plugin's own flags are appended here rather than accepted from the command
7
+ * line, so a typed flag cannot change what the plugin means to run. Second,
8
+ * the CLI's flag surface is allowlisted per subcommand: an unknown dashed token
9
+ * is refused with usage text instead of being forwarded, because the CLI's own
10
+ * argument tolerance would otherwise turn a typo into a different review.
11
+ *
12
+ * @module dsh-plannotator/args
13
+ */
14
+ /** One accepted flag: whether it consumes the following token as its value. */
15
+ export interface FlagSpec {
16
+ readonly flag: string;
17
+ readonly takesValue: boolean;
18
+ }
19
+ /** Flags `plannotator review` accepts from a typed line. */
20
+ export declare const REVIEW_FLAGS: readonly FlagSpec[];
21
+ /** Flags `plannotator annotate` accepts from a typed line. */
22
+ export declare const ANNOTATE_FLAGS: readonly FlagSpec[];
23
+ /** Parsed typed line: recognized flags in order, plus the non-flag tokens. */
24
+ export interface ParsedLine {
25
+ readonly flags: readonly string[];
26
+ readonly positionals: readonly string[];
27
+ }
28
+ /** A parse either yields the line's parts or the text telling the reader what is accepted. */
29
+ export type ParseResult = {
30
+ readonly ok: true;
31
+ readonly value: ParsedLine;
32
+ } | {
33
+ readonly ok: false;
34
+ readonly error: string;
35
+ };
36
+ /** Options shared by every builder. */
37
+ export interface BuildOptions {
38
+ /** `config.tailscale`: publish the session over the tailnet. */
39
+ readonly tailscale: boolean;
40
+ }
41
+ /**
42
+ * Parse a typed command line against one allowlist.
43
+ *
44
+ * Only `--flag` tokens are validated; anything else is a positional the caller
45
+ * resolves (a path, a folder, a URL). A `--` terminator is not honoured: the
46
+ * CLI has no use for one, and accepting it would let an unknown token through.
47
+ *
48
+ * @param tokens - whitespace-split typed input.
49
+ * @param allowlist - flags this subcommand accepts.
50
+ * @returns the flags and positionals, or usage text naming the first bad token.
51
+ */
52
+ export declare function parseTypedLine(tokens: readonly string[], allowlist: readonly FlagSpec[]): ParseResult;
53
+ /**
54
+ * Build the gated-annotate argv used for plan review and file annotation.
55
+ *
56
+ * `--require-approval` is what makes the exit code a verdict, so a review that
57
+ * ends in a browser crash is distinguishable from one the human declined.
58
+ *
59
+ * @param target - a file, folder, or URL already vetted by the caller.
60
+ * @param options - shared build options.
61
+ * @returns argv for `plannotator annotate`.
62
+ */
63
+ export declare function buildAnnotateArgs(target: string, options: BuildOptions): string[];
64
+ /**
65
+ * Build the argv for annotating the newest assistant message.
66
+ *
67
+ * The message travels on stdin because it exists only in this process' session
68
+ * log; `--stdin` is the CLI's documented way to hand it over without writing a
69
+ * copy to disk. `--require-approval` is deliberately absent: the CLI documents
70
+ * the strict exit-code contract for `annotate` only.
71
+ *
72
+ * @param options - shared build options.
73
+ * @returns argv for `plannotator annotate-last`.
74
+ */
75
+ export declare function buildAnnotateLastArgs(options: BuildOptions): string[];
76
+ /**
77
+ * Build the argv for a code review of the working tree or a pull request.
78
+ *
79
+ * @param parsed - the allowlisted flags and positionals from the typed line.
80
+ * @param options - shared build options.
81
+ * @returns argv for `plannotator review`.
82
+ */
83
+ export declare function buildReviewArgs(parsed: ParsedLine, options: BuildOptions): string[];
84
+ /**
85
+ * Decide whether a positional target is a URL or a filesystem path.
86
+ *
87
+ * The distinction matters because only paths are existence-checked, and only
88
+ * `http(s)` reaches the CLI's fetcher: another scheme would make the CLI open a
89
+ * resource the reviewer did not name.
90
+ *
91
+ * @param token - the candidate target.
92
+ * @returns the target kind, or `undefined` for a token that is neither.
93
+ */
94
+ export declare function classifyTarget(token: string): 'url' | 'path' | undefined;
package/dist/args.js ADDED
@@ -0,0 +1,142 @@
1
+ /**
2
+ * Build the argv this plugin hands to the CLI.
3
+ *
4
+ * Two rules shape this module. First, the reviewer's input never becomes shell
5
+ * syntax: argv is an array handed to `spawn` with `shell: false`, and the
6
+ * plugin's own flags are appended here rather than accepted from the command
7
+ * line, so a typed flag cannot change what the plugin means to run. Second,
8
+ * the CLI's flag surface is allowlisted per subcommand: an unknown dashed token
9
+ * is refused with usage text instead of being forwarded, because the CLI's own
10
+ * argument tolerance would otherwise turn a typo into a different review.
11
+ *
12
+ * @module dsh-plannotator/args
13
+ */
14
+ import { CLI_ANNOTATE, CLI_ANNOTATE_LAST, CLI_REVIEW, FLAG_APP, FLAG_BASE, FLAG_DIFF_TYPE, FLAG_GATE, FLAG_GIT, FLAG_GITBUTLER, FLAG_JSON, FLAG_LOCAL, FLAG_MARKDOWN, FLAG_NO_GIT_REMOTE_CHECK, FLAG_NO_JINA, FLAG_NO_LOCAL, FLAG_RENDER_HTML, FLAG_REQUIRE_APPROVAL, FLAG_STATIC, FLAG_STDIN, FLAG_TAILSCALE, } from "./constants.js";
15
+ /** Flags `plannotator review` accepts from a typed line. */
16
+ export const REVIEW_FLAGS = [
17
+ { flag: FLAG_GIT, takesValue: false },
18
+ { flag: FLAG_GITBUTLER, takesValue: false },
19
+ { flag: FLAG_BASE, takesValue: true },
20
+ { flag: FLAG_DIFF_TYPE, takesValue: true },
21
+ { flag: FLAG_LOCAL, takesValue: false },
22
+ { flag: FLAG_NO_LOCAL, takesValue: false },
23
+ { flag: FLAG_NO_GIT_REMOTE_CHECK, takesValue: false },
24
+ { flag: FLAG_TAILSCALE, takesValue: false },
25
+ ];
26
+ /** Flags `plannotator annotate` accepts from a typed line. */
27
+ export const ANNOTATE_FLAGS = [
28
+ { flag: FLAG_MARKDOWN, takesValue: false },
29
+ { flag: FLAG_NO_JINA, takesValue: false },
30
+ { flag: FLAG_APP, takesValue: false },
31
+ { flag: FLAG_STATIC, takesValue: false },
32
+ { flag: FLAG_RENDER_HTML, takesValue: false },
33
+ { flag: FLAG_TAILSCALE, takesValue: false },
34
+ ];
35
+ /**
36
+ * Parse a typed command line against one allowlist.
37
+ *
38
+ * Only `--flag` tokens are validated; anything else is a positional the caller
39
+ * resolves (a path, a folder, a URL). A `--` terminator is not honoured: the
40
+ * CLI has no use for one, and accepting it would let an unknown token through.
41
+ *
42
+ * @param tokens - whitespace-split typed input.
43
+ * @param allowlist - flags this subcommand accepts.
44
+ * @returns the flags and positionals, or usage text naming the first bad token.
45
+ */
46
+ export function parseTypedLine(tokens, allowlist) {
47
+ const byName = new Map(allowlist.map((spec) => [spec.flag, spec]));
48
+ const flags = [];
49
+ const positionals = [];
50
+ for (let index = 0; index < tokens.length; index += 1) {
51
+ const token = tokens[index];
52
+ if (token === undefined || token === '')
53
+ continue;
54
+ if (!token.startsWith('-')) {
55
+ positionals.push(token);
56
+ continue;
57
+ }
58
+ const spec = byName.get(token);
59
+ if (spec === undefined) {
60
+ const accepted = allowlist.map((entry) => entry.flag).join(' ');
61
+ return { ok: false, error: 'unknown option ' + token + '; accepted: ' + accepted };
62
+ }
63
+ flags.push(token);
64
+ if (spec.takesValue) {
65
+ const value = tokens[index + 1];
66
+ if (value === undefined)
67
+ return { ok: false, error: token + ' requires a value' };
68
+ flags.push(value);
69
+ index += 1;
70
+ }
71
+ }
72
+ return { ok: true, value: { flags, positionals } };
73
+ }
74
+ /**
75
+ * Build the gated-annotate argv used for plan review and file annotation.
76
+ *
77
+ * `--require-approval` is what makes the exit code a verdict, so a review that
78
+ * ends in a browser crash is distinguishable from one the human declined.
79
+ *
80
+ * @param target - a file, folder, or URL already vetted by the caller.
81
+ * @param options - shared build options.
82
+ * @returns argv for `plannotator annotate`.
83
+ */
84
+ export function buildAnnotateArgs(target, options) {
85
+ return withTailscale([CLI_ANNOTATE, target, FLAG_GATE, FLAG_JSON, FLAG_REQUIRE_APPROVAL], options);
86
+ }
87
+ /**
88
+ * Build the argv for annotating the newest assistant message.
89
+ *
90
+ * The message travels on stdin because it exists only in this process' session
91
+ * log; `--stdin` is the CLI's documented way to hand it over without writing a
92
+ * copy to disk. `--require-approval` is deliberately absent: the CLI documents
93
+ * the strict exit-code contract for `annotate` only.
94
+ *
95
+ * @param options - shared build options.
96
+ * @returns argv for `plannotator annotate-last`.
97
+ */
98
+ export function buildAnnotateLastArgs(options) {
99
+ return withTailscale([CLI_ANNOTATE_LAST, FLAG_STDIN, FLAG_GATE, FLAG_JSON], options);
100
+ }
101
+ /**
102
+ * Build the argv for a code review of the working tree or a pull request.
103
+ *
104
+ * @param parsed - the allowlisted flags and positionals from the typed line.
105
+ * @param options - shared build options.
106
+ * @returns argv for `plannotator review`.
107
+ */
108
+ export function buildReviewArgs(parsed, options) {
109
+ return withTailscale([CLI_REVIEW, ...parsed.flags, ...parsed.positionals, FLAG_JSON], options);
110
+ }
111
+ /**
112
+ * Append the tailnet flag only when it is in force, so the default argv stays minimal.
113
+ *
114
+ * A typed `--tailscale` and a configured one mean the same thing; appending a
115
+ * second copy would make the flag's arity the CLI's problem rather than ours.
116
+ */
117
+ function withTailscale(argv, options) {
118
+ if (!options.tailscale || argv.includes(FLAG_TAILSCALE))
119
+ return [...argv];
120
+ return [...argv, FLAG_TAILSCALE];
121
+ }
122
+ /**
123
+ * Decide whether a positional target is a URL or a filesystem path.
124
+ *
125
+ * The distinction matters because only paths are existence-checked, and only
126
+ * `http(s)` reaches the CLI's fetcher: another scheme would make the CLI open a
127
+ * resource the reviewer did not name.
128
+ *
129
+ * @param token - the candidate target.
130
+ * @returns the target kind, or `undefined` for a token that is neither.
131
+ */
132
+ export function classifyTarget(token) {
133
+ if (token === '')
134
+ return undefined;
135
+ if (token.startsWith('-'))
136
+ return undefined;
137
+ if (/^https?:\/\//u.test(token))
138
+ return 'url';
139
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:/u.test(token))
140
+ return undefined;
141
+ return 'path';
142
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Locate and vet the `plannotator` executable.
3
+ *
4
+ * The binary is a user-installed artefact this plugin spawns, so resolution is
5
+ * the one place where a wrong answer becomes code execution. Every candidate is
6
+ * checked for executability and ownership before it is returned, and a file
7
+ * another user could rewrite is refused unless the profile says otherwise.
8
+ *
9
+ * @module dsh-plannotator/binary
10
+ */
11
+ /** Outcome of resolving the executable. */
12
+ export type BinaryResolution = {
13
+ readonly ok: true;
14
+ readonly path: string;
15
+ } | {
16
+ readonly ok: false;
17
+ readonly reason: string;
18
+ };
19
+ /** The filesystem facts resolution reads, injectable so tests need no real files. */
20
+ export interface BinaryProbe {
21
+ /** Whether the path exists and carries an execute bit. */
22
+ readonly isExecutable: (path: string) => boolean;
23
+ /** Mode bits and owner of an existing path. */
24
+ readonly stat: (path: string) => {
25
+ readonly mode: number;
26
+ readonly uid: number;
27
+ };
28
+ }
29
+ /** What resolution needs to know about the request. */
30
+ export interface BinaryRequest {
31
+ /** `config.binary`; empty means "use the search order". */
32
+ readonly configured: string;
33
+ /** `config.allowUntrustedBinary`. */
34
+ readonly allowUntrusted: boolean;
35
+ /** Environment holding {@link BINARY_ENV} and `PATH`. */
36
+ readonly env: NodeJS.ProcessEnv;
37
+ /** Working directory a relative `config.binary` resolves against. */
38
+ readonly cwd: string;
39
+ /** Owner every candidate should belong to; `undefined` where the platform has no such notion. */
40
+ readonly uid: number | undefined;
41
+ /** Filesystem probe. */
42
+ readonly probe: BinaryProbe;
43
+ }
44
+ /**
45
+ * Resolve the executable to spawn.
46
+ *
47
+ * Order: an explicitly configured path, then {@link BINARY_ENV}, then the first
48
+ * executable named `plannotator` on `PATH`. An explicit candidate that exists
49
+ * but fails the trust check is refused rather than skipping to the next
50
+ * candidate: silently running a different binary would hide the substitution.
51
+ *
52
+ * @param request - configured path, policy, environment, and probe.
53
+ * @returns the vetted absolute path, or the reason none could be used.
54
+ */
55
+ export declare function resolveBinary(request: BinaryRequest): BinaryResolution;
56
+ /** The production probe: real `access`/`stat`, with no policy of its own. */
57
+ export declare const NODE_BINARY_PROBE: BinaryProbe;
package/dist/binary.js ADDED
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Locate and vet the `plannotator` executable.
3
+ *
4
+ * The binary is a user-installed artefact this plugin spawns, so resolution is
5
+ * the one place where a wrong answer becomes code execution. Every candidate is
6
+ * checked for executability and ownership before it is returned, and a file
7
+ * another user could rewrite is refused unless the profile says otherwise.
8
+ *
9
+ * @module dsh-plannotator/binary
10
+ */
11
+ import { constants as fsConstants, statSync } from 'node:fs';
12
+ import { accessSync } from 'node:fs';
13
+ import { delimiter, isAbsolute, resolve } from 'node:path';
14
+ import { BINARY_ENV } from "./constants.js";
15
+ /** The environment name the resolved binary is reported under, so a failure is actionable. */
16
+ const SEARCH_ORDER = `config.binary, $${BINARY_ENV}, then PATH`;
17
+ /** True when anyone but the owner may write the file. */
18
+ function isWorldWritable(mode) {
19
+ // 0o002 is the "others may write" bit; the owner-write bit is expected.
20
+ return (mode & 0o002) !== 0;
21
+ }
22
+ /**
23
+ * Decide whether a candidate is safe to execute.
24
+ *
25
+ * @param path - absolute candidate path.
26
+ * @param request - the resolution request carrying the trust policy.
27
+ * @returns `undefined` when the candidate is acceptable, else the reason to refuse it.
28
+ */
29
+ function trustProblem(path, request) {
30
+ let facts;
31
+ try {
32
+ facts = request.probe.stat(path);
33
+ }
34
+ catch {
35
+ return `${path} cannot be inspected`;
36
+ }
37
+ if (request.allowUntrusted)
38
+ return undefined;
39
+ if (isWorldWritable(facts.mode)) {
40
+ return `${path} is writable by other users (mode ${facts.mode.toString(8)}); set allowUntrustedBinary, or install a per-user copy`;
41
+ }
42
+ if (request.uid !== undefined && facts.uid !== request.uid) {
43
+ return `${path} is owned by uid ${facts.uid}, not by this user; set allowUntrustedBinary to accept it`;
44
+ }
45
+ return undefined;
46
+ }
47
+ /**
48
+ * Resolve the executable to spawn.
49
+ *
50
+ * Order: an explicitly configured path, then {@link BINARY_ENV}, then the first
51
+ * executable named `plannotator` on `PATH`. An explicit candidate that exists
52
+ * but fails the trust check is refused rather than skipping to the next
53
+ * candidate: silently running a different binary would hide the substitution.
54
+ *
55
+ * @param request - configured path, policy, environment, and probe.
56
+ * @returns the vetted absolute path, or the reason none could be used.
57
+ */
58
+ export function resolveBinary(request) {
59
+ const configured = request.configured.trim();
60
+ const fromEnv = (request.env[BINARY_ENV] ?? '').trim();
61
+ const explicit = configured !== '' ? configured : fromEnv;
62
+ if (explicit !== '') {
63
+ const path = isAbsolute(explicit) ? explicit : resolve(request.cwd, explicit);
64
+ if (!request.probe.isExecutable(path)) {
65
+ return { ok: false, reason: `${path} is not an executable file` };
66
+ }
67
+ const problem = trustProblem(path, request);
68
+ if (problem !== undefined)
69
+ return { ok: false, reason: problem };
70
+ return { ok: true, path };
71
+ }
72
+ const searchPath = request.env['PATH'] ?? '';
73
+ for (const directory of searchPath.split(delimiter)) {
74
+ if (directory === '')
75
+ continue;
76
+ const candidate = resolve(directory, 'plannotator');
77
+ if (!request.probe.isExecutable(candidate))
78
+ continue;
79
+ const problem = trustProblem(candidate, request);
80
+ if (problem !== undefined)
81
+ return { ok: false, reason: problem };
82
+ return { ok: true, path: candidate };
83
+ }
84
+ return { ok: false, reason: `plannotator was not found (${SEARCH_ORDER})` };
85
+ }
86
+ /** The production probe: real `access`/`stat`, with no policy of its own. */
87
+ export const NODE_BINARY_PROBE = {
88
+ isExecutable: (path) => {
89
+ try {
90
+ accessSync(path, fsConstants.X_OK);
91
+ return statSync(path).isFile();
92
+ }
93
+ catch {
94
+ return false;
95
+ }
96
+ },
97
+ stat: (path) => {
98
+ const facts = statSync(path);
99
+ return { mode: facts.mode, uid: facts.uid };
100
+ },
101
+ };
package/dist/cli.d.ts ADDED
@@ -0,0 +1,66 @@
1
+ /**
2
+ * Run the CLI and capture what it decided.
3
+ *
4
+ * A review is a long-lived child: it blocks until a human acts, and this
5
+ * process must stay responsive and cancellable meanwhile. The runner therefore
6
+ * owns exactly four things — argv-only spawning, bounded capture, cancellation
7
+ * with a kill ladder, and an optional timeout — and reports the outcome as the
8
+ * CLI's own exit code plus its two streams, so decision mapping stays a pure
9
+ * function over that result.
10
+ *
11
+ * @module dsh-plannotator/cli
12
+ */
13
+ /** Everything one invocation needs. */
14
+ export interface RunRequest {
15
+ /** Vetted absolute path to the executable. */
16
+ readonly binary: string;
17
+ /** Full argv, including the subcommand; never shell-interpreted. */
18
+ readonly argv: readonly string[];
19
+ /** Working directory the review runs in — the session's own. */
20
+ readonly cwd: string;
21
+ /** Environment handed to the child. */
22
+ readonly env: NodeJS.ProcessEnv;
23
+ /** Text to write to the child's stdin before closing it, when the surface takes one. */
24
+ readonly stdin: string | undefined;
25
+ /** Hard ceiling in milliseconds; 0 waits as long as the child lives. */
26
+ readonly timeoutMs: number;
27
+ /** Cancellation owned by the dispatching command. */
28
+ readonly signal: AbortSignal | undefined;
29
+ }
30
+ /** A captured stream: text, whether it was cut, and the tail a human should read. */
31
+ export interface CapturedStream {
32
+ readonly text: string;
33
+ readonly truncated: boolean;
34
+ }
35
+ /** How one run ended. */
36
+ export type RunResult = {
37
+ readonly kind: 'exited';
38
+ readonly code: number;
39
+ readonly cancelled: boolean;
40
+ readonly stdout: CapturedStream;
41
+ readonly stderr: CapturedStream;
42
+ } | {
43
+ readonly kind: 'signalled';
44
+ readonly signal: NodeJS.Signals | null;
45
+ readonly cancelled: boolean;
46
+ readonly stdout: CapturedStream;
47
+ readonly stderr: CapturedStream;
48
+ } | {
49
+ readonly kind: 'timed-out';
50
+ readonly stdout: CapturedStream;
51
+ readonly stderr: CapturedStream;
52
+ } | {
53
+ readonly kind: 'spawn-failed';
54
+ readonly message: string;
55
+ };
56
+ /**
57
+ * Spawn the CLI and settle once it has exited, failed, been cancelled, or hit
58
+ * the timeout.
59
+ *
60
+ * The returned promise never rejects: a missing or unspawnable binary is an
61
+ * outcome the command reports, not an exception the registry has to survive.
62
+ *
63
+ * @param request - argv, directory, environment, stdin, timeout, and signal.
64
+ * @returns how the run ended.
65
+ */
66
+ export declare function runPlannotator(request: RunRequest): Promise<RunResult>;