@soleur/opencode 3.359.19 → 3.360.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/agents/product/design/ux-design-lead.md +49 -13
- package/package.json +1 -1
- package/skills/brainstorm/SKILL.md +3 -3
- package/skills/brainstorm/references/brainstorm-brand-workshop.md +17 -10
- package/skills/pencil-setup/SKILL.md +77 -27
- package/skills/pencil-setup/scripts/check_deps.sh +597 -132
- package/skills/pencil-setup/scripts/copy_adapter.sh +79 -11
- package/skills/pencil-setup/scripts/engine-contract-probe.sh +1132 -133
- package/skills/pencil-setup/scripts/pen-cli/package-lock.json +4359 -0
- package/skills/pencil-setup/scripts/pen-cli/package.json +13 -0
- package/skills/pencil-setup/scripts/pencil-error-enrichment.mjs +67 -14
- package/skills/pencil-setup/scripts/pencil-mcp-adapter.mjs +1283 -458
- package/skills/pencil-setup/scripts/pencil-repl-surface.mjs +377 -68
- package/skills/pencil-setup/scripts/pencil-response-classify.mjs +53 -12
- package/skills/pencil-setup/scripts/pencil-save-gate.mjs +484 -75
- package/skills/plan/SKILL.md +1 -1
|
@@ -1,29 +1,84 @@
|
|
|
1
1
|
#!/usr/bin/env bash
|
|
2
|
-
# engine-contract-probe.sh — run the pencil-setup
|
|
3
|
-
# @
|
|
2
|
+
# engine-contract-probe.sh — run the pencil-setup contract checks against the REAL
|
|
3
|
+
# @pen.dev/cli engine (`pen interactive --out <f> [--in <f>]`), the ones the unit and
|
|
4
|
+
# stub tests can only assume.
|
|
5
|
+
#
|
|
6
|
+
# pyramid-justified: the real engine is the only oracle for the contract
|
|
4
7
|
#
|
|
5
8
|
# This is the one test that touches the real engine. The stub integration test
|
|
6
|
-
# (test/pencil-adapter-stub-repl.test.ts) encodes our BELIEF about the REPL,
|
|
7
|
-
#
|
|
8
|
-
#
|
|
9
|
-
# It is deliberately not a *.test.sh: it needs
|
|
10
|
-
# be a required CI job or an auto-registered suite.
|
|
9
|
+
# (test/pencil-adapter-stub-repl.test.ts) encodes our BELIEF about the REPL, which is how
|
|
10
|
+
# #11143 passed review (learning: a-stub-that-encodes-your-belief-about-an-engine-passes-
|
|
11
|
+
# the-bug-it-was-written-to-catch). Run it by hand before any bump of PEN_CLI_VERSION in
|
|
12
|
+
# check_deps.sh or of the engine lockfile. It is deliberately not a *.test.sh: it needs the
|
|
13
|
+
# credential, so it must never be a required CI job or an auto-registered suite.
|
|
14
|
+
#
|
|
15
|
+
# doppler run -p soleur -c dev -- bash plugins/soleur/skills/pencil-setup/scripts/engine-contract-probe.sh
|
|
16
|
+
#
|
|
17
|
+
# Credential: resolved ONCE as ${PEN_CLI_KEY:-${PENCIL_CLI_KEY:-}} (empty or whitespace counts
|
|
18
|
+
# as unset), handed to every child explicitly as PEN_CLI_KEY, never printed, never written to the
|
|
19
|
+
# transcript. Every line this probe emits passes through a redactor that knows the raw, JSON, URL
|
|
20
|
+
# and base64 forms, and the transcript is scrubbed again and scanned by gitleaks; raw child output
|
|
21
|
+
# that never reaches an emitted line is not recorded at all. Account details from `pen status` are
|
|
22
|
+
# never recorded.
|
|
23
|
+
#
|
|
24
|
+
# Engine-only cases (no adapter needed):
|
|
25
|
+
# 0 `pen status` reports Active (a fail-open engine runs with a bad key: it must not yield OK)
|
|
26
|
+
# 1 `pen interactive --help` signatures == REPL_SURFACE for the REPL tools; the removed tools absent
|
|
27
|
+
# 2 startup banner, then the prompt `pen > ` (raw coloured bytes recorded)
|
|
28
|
+
# 3 `OK` reply prefix; `## Print output` section
|
|
29
|
+
# 4 nonce-tagged top-level count round trip (the save sentinel's memory probe)
|
|
30
|
+
# 5 `save()` -> exactly `Saved <path>`; the file holds the nodes
|
|
31
|
+
# 6 a failing save prints `Save failed:` and writes nothing, now or later (idle window)
|
|
32
|
+
# 7 each removed name answers `Unknown tool:` and the enrichment appends the exact hint
|
|
33
|
+
# 8 export: every format has the right magic bytes; scale and quality change the output
|
|
34
|
+
# 9 read_skill on every guide path, each followed by an intact save() reply; the engine's guide
|
|
35
|
+
# names equal the guide lists in SKILL.md and ux-design-lead.md
|
|
36
|
+
# 10 no engine write outside save(): positive control, then exit(), SIGTERM, SIGKILL, over a
|
|
37
|
+
# >= 15 s idle window watched by mtime polling
|
|
38
|
+
# 11 batch_design raw DSL: the QuickJS sandbox exposes no process/require/fetch (pinned) and its
|
|
39
|
+
# host-function set is pinned; Export reaches any path (recorded and pinned, CTO ruling 11.2)
|
|
40
|
+
# 12 a file with an unrecognised `version` opened via --in (recorded and pinned), idle window
|
|
41
|
+
# 13 canary credential in a scratch HOME: the engine's output, the saved .pen bytes and every file
|
|
42
|
+
# the engine wrote under HOME are scanned in raw, base64 and URL-encoded forms
|
|
43
|
+
# 14 install method: `npm ci --ignore-scripts` from the committed lockfile yields a working engine
|
|
44
|
+
# Adapter cases (the INSTALLED adapter over MCP stdio, through test/lib/pencil-adapter-roundtrip.mjs):
|
|
45
|
+
# A1 round trip, removed tools answer with the exact hint, reopen
|
|
46
|
+
# A2 the same through the adapter's DEFAULT binary resolution (HOME at the real prefix, no override)
|
|
47
|
+
# A3 refusal markers on line 1 of the TOOL RESULT (`REFUSED save: [reason=<code>]`): empty, stale,
|
|
48
|
+
# and no write after an idle window
|
|
49
|
+
# A4 a file removed behind a live session is recreated with the NOTE (ruling 2)
|
|
50
|
+
# A5 unrecognised version via open_document (load fidelity refusal, ruling 6)
|
|
51
|
+
# A6 canary credential through adapter stderr and every tool result
|
|
52
|
+
# A7 load-fidelity acceptance (ruling 6): every committed knowledge-base/product/design/**/*.pen
|
|
53
|
+
# loads with at least as many top-level nodes as the file holds
|
|
54
|
+
#
|
|
55
|
+
# Stated limits: an engine timer longer than the 15 s window would not be seen; atomicity of the
|
|
56
|
+
# engine's write and behaviour on a file written by a newer Desktop are not asserted beyond case 12's
|
|
57
|
+
# recorded answer; a count cannot see dropped NESTED nodes.
|
|
58
|
+
#
|
|
59
|
+
# Output: PASS/FAIL/RECORD/SKIP lines, then one verdict line. The redacted transcript goes to the
|
|
60
|
+
# stable path knowledge-base/engineering/operations/references/pencil-engine-probe-transcript.md
|
|
61
|
+
# (PROBE_TRANSCRIPT overrides it), scrubbed by test/lib/scrub-transcript.mjs and checked with
|
|
62
|
+
# gitleaks; a leak fails the run. A run that hit a tooling error does not touch the transcript.
|
|
11
63
|
#
|
|
12
|
-
#
|
|
13
|
-
#
|
|
14
|
-
#
|
|
15
|
-
# 3. a fresh adapter session reopens the file: top-level nodes loaded, file
|
|
16
|
-
# larger than the 96-byte empty document
|
|
17
|
-
# 4. batch_get() returns the JSON shape the save sentinel parses
|
|
64
|
+
# Environment: PROBE_PEN_BINARY=<abs path> probes another `pen` instead of the installed default (the
|
|
65
|
+
# adapter never reads an engine-binary environment variable, so this one is the probe's own);
|
|
66
|
+
# PROBE_TRANSCRIPT=<path> redirects the transcript.
|
|
18
67
|
#
|
|
19
|
-
# Exit codes: 0
|
|
20
|
-
#
|
|
68
|
+
# Exit codes: 0 PROBE OK: every case ran and passed
|
|
69
|
+
# 1 a contract check failed, the credential is not Active, or the transcript leaked
|
|
70
|
+
# (also when a tooling error stops the run after a check had already FAILED:
|
|
71
|
+
# `PROBE FAILED (n)` is printed first, then the tooling line)
|
|
72
|
+
# 2 internal setup error (for example the work directory is not absolute)
|
|
73
|
+
# 3 PROBE SKIPPED (no key), tooling missing or broken, or a case was skipped:
|
|
74
|
+
# an incomplete run is never reported as PROBE OK
|
|
75
|
+
# 78 refusing to run under `set -x` with a live credential (see #7797)
|
|
21
76
|
|
|
22
77
|
set -uo pipefail
|
|
23
78
|
|
|
24
79
|
case "$-" in
|
|
25
80
|
*x*)
|
|
26
|
-
if [ -n "${PENCIL_CLI_KEY:+x}" ]; then
|
|
81
|
+
if [ -n "${PEN_CLI_KEY:+x}" ] || [ -n "${PENCIL_CLI_KEY:+x}" ]; then
|
|
27
82
|
printf '[FATAL] refusing to trace with a live credential set (see #7797)\n' >&2
|
|
28
83
|
exit 78
|
|
29
84
|
fi
|
|
@@ -32,156 +87,1100 @@ esac
|
|
|
32
87
|
|
|
33
88
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
34
89
|
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
90
|
+
# Resolve the key once; empty or whitespace-only counts as unset.
|
|
91
|
+
KEY="${PEN_CLI_KEY:-}"
|
|
92
|
+
KEY="${KEY#"${KEY%%[![:space:]]*}"}"; KEY="${KEY%"${KEY##*[![:space:]]}"}"
|
|
93
|
+
if [[ -z "$KEY" ]]; then
|
|
94
|
+
KEY="${PENCIL_CLI_KEY:-}"
|
|
95
|
+
KEY="${KEY#"${KEY%%[![:space:]]*}"}"; KEY="${KEY%"${KEY##*[![:space:]]}"}"
|
|
96
|
+
fi
|
|
97
|
+
if [[ -z "$KEY" ]]; then
|
|
98
|
+
echo "PROBE SKIPPED (no key)"
|
|
99
|
+
echo " This probe asserted nothing. Run: doppler run -p soleur -c dev -- bash $0" >&2
|
|
38
100
|
exit 3
|
|
39
101
|
fi
|
|
102
|
+
unset PEN_CLI_KEY PENCIL_CLI_KEY
|
|
103
|
+
|
|
40
104
|
for tool in node npm; do
|
|
41
105
|
command -v "$tool" >/dev/null 2>&1 || { echo "UNRESOLVED: $tool not on PATH" >&2; exit 3; }
|
|
42
106
|
done
|
|
43
107
|
|
|
44
|
-
PENCIL_BIN="${
|
|
108
|
+
PENCIL_BIN="${PROBE_PEN_BINARY:-$HOME/.local/share/pen-cli/node_modules/.bin/pen}"
|
|
45
109
|
if [[ ! -e "$PENCIL_BIN" ]]; then
|
|
46
|
-
echo "UNRESOLVED:
|
|
110
|
+
echo "UNRESOLVED: pen binary not found at $PENCIL_BIN (run: bash $SCRIPT_DIR/check_deps.sh --auto, or set PROBE_PEN_BINARY)" >&2
|
|
47
111
|
exit 3
|
|
48
112
|
fi
|
|
49
113
|
|
|
50
|
-
|
|
114
|
+
# The default binary must pass the same identity rule check_deps.sh and the adapter apply
|
|
115
|
+
# (the real .bin/pen resolves to the installed package's declared bin.pen target).
|
|
116
|
+
OVERRIDE=0
|
|
117
|
+
if [[ -n "${PROBE_PEN_BINARY:-}" ]]; then
|
|
118
|
+
OVERRIDE=1
|
|
119
|
+
elif ! resolved_pen="$(bash -c 'f="$1"; set --; source "$f"; detect_headless_cli' _ "$SCRIPT_DIR/check_deps.sh" 2>/dev/null)" || [[ -z "$resolved_pen" ]]; then
|
|
120
|
+
echo "FAIL the default .bin/pen does not pass the check_deps.sh identity rule: $PENCIL_BIN"
|
|
121
|
+
echo "PROBE FAILED (1)"
|
|
122
|
+
exit 1
|
|
123
|
+
else
|
|
124
|
+
PENCIL_BIN="$resolved_pen"
|
|
125
|
+
fi
|
|
126
|
+
|
|
127
|
+
PIN="$(sed -n 's/^PEN_CLI_VERSION="\([0-9][0-9.]*\)"$/\1/p' "$SCRIPT_DIR/check_deps.sh" | head -1)"
|
|
128
|
+
[[ -n "$PIN" ]] || { echo "UNRESOLVED: could not read PEN_CLI_VERSION from check_deps.sh" >&2; exit 3; }
|
|
129
|
+
|
|
130
|
+
REPO_ROOT="$(cd "$SCRIPT_DIR/../../../../.." && pwd)"
|
|
131
|
+
# A stable home: the per-feature specs directory is archived when its PR merges.
|
|
132
|
+
STABLE_DIR="$REPO_ROOT/knowledge-base/engineering/operations/references"
|
|
133
|
+
TRANSCRIPT_PATH="${PROBE_TRANSCRIPT:-}"
|
|
134
|
+
if [[ -z "$TRANSCRIPT_PATH" && -d "$STABLE_DIR" ]]; then
|
|
135
|
+
TRANSCRIPT_PATH="$STABLE_DIR/pencil-engine-probe-transcript.md"
|
|
136
|
+
fi
|
|
137
|
+
|
|
138
|
+
work="$(mktemp -d -t pen-contract-probe.XXXXXXXX)"
|
|
51
139
|
[[ "$work" == /* ]] || { echo "FATAL: work dir not absolute: $work" >&2; exit 2; }
|
|
52
|
-
|
|
140
|
+
cleanup() {
|
|
141
|
+
chmod -R u+w -- "$work" 2>/dev/null || true
|
|
142
|
+
rm -rf -- "$work"
|
|
143
|
+
}
|
|
144
|
+
trap cleanup EXIT
|
|
53
145
|
|
|
54
146
|
cat > "$work/probe.mjs" <<'NODE'
|
|
55
|
-
import { spawnSync } from "node:child_process";
|
|
56
|
-
import {
|
|
57
|
-
|
|
147
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
148
|
+
import {
|
|
149
|
+
chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, rmSync, statSync, writeFileSync,
|
|
150
|
+
} from "node:fs";
|
|
151
|
+
import { basename, dirname, join } from "node:path";
|
|
58
152
|
import { pathToFileURL } from "node:url";
|
|
153
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
154
|
+
|
|
155
|
+
const [scriptsDir, testLib, workDir, penBin, pin, transcriptPath, penCliDir, repoRoot, overrideFlag] = process.argv.slice(2);
|
|
156
|
+
const USING_OVERRIDE = overrideFlag === "1";
|
|
157
|
+
const KEY = process.env.PROBE_CRED ?? "";
|
|
158
|
+
delete process.env.PROBE_CRED;
|
|
159
|
+
const HOME = process.env.HOME ?? "";
|
|
160
|
+
const imp = (dir, f) => import(pathToFileURL(join(dir, f)).href);
|
|
59
161
|
|
|
60
|
-
const
|
|
61
|
-
const {
|
|
62
|
-
|
|
63
|
-
|
|
162
|
+
const surface = await imp(scriptsDir, "pencil-repl-surface.mjs");
|
|
163
|
+
const {
|
|
164
|
+
REPL_SURFACE, REPL_PROMPT, REPL_PROMPT_RAW, nodeVersionOk, redactionForms,
|
|
165
|
+
buildBatchDesignCommand, buildCountCommand, newCountNonce, parseCountReply,
|
|
166
|
+
buildExportCommand, buildReadSkillCommand, buildSaveCommand, validateSkillPath,
|
|
167
|
+
} = surface;
|
|
168
|
+
const { REMOVED_TOOL_NAMES, removedToolHint, enrichErrorMessage } = await imp(scriptsDir, "pencil-error-enrichment.mjs");
|
|
169
|
+
const { stripAnsi } = await imp(scriptsDir, "pencil-response-classify.mjs");
|
|
170
|
+
const scrub = await imp(testLib, "scrub-transcript.mjs");
|
|
64
171
|
|
|
172
|
+
// ---------------------------------------------------------------------------
|
|
173
|
+
// Output. Every emitted line passes through redact(): the credential in every form it can take.
|
|
65
174
|
let failures = 0;
|
|
175
|
+
let nPass = 0;
|
|
176
|
+
const skipped = [];
|
|
177
|
+
const LOG = [];
|
|
178
|
+
const canaryForms = [];
|
|
179
|
+
const redact = (s) => {
|
|
180
|
+
let t = String(s);
|
|
181
|
+
for (const f of [...redactionForms(KEY), ...canaryForms]) t = t.split(f).join("<redacted>");
|
|
182
|
+
return t;
|
|
183
|
+
};
|
|
184
|
+
const emit = (line) => {
|
|
185
|
+
const safe = redact(line);
|
|
186
|
+
LOG.push(safe);
|
|
187
|
+
console.log(safe);
|
|
188
|
+
};
|
|
66
189
|
const check = (ok, label, detail = "") => {
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
190
|
+
const safe = redact(String(detail)).replace(/\s+/g, " ").slice(0, 300);
|
|
191
|
+
emit(`${ok ? "PASS" : "FAIL"} ${label}${ok || !safe ? "" : `: ${safe}`}`);
|
|
192
|
+
ok ? nPass++ : failures++;
|
|
193
|
+
};
|
|
194
|
+
const record = (label, value) => emit(`RECORD ${label}: ${redact(String(value)).replace(/\s+/g, " ").slice(0, 300)}`);
|
|
195
|
+
const note = (text) => emit(`NOTE ${text}`);
|
|
196
|
+
// A skipped case means the run asserted less than it promises: the verdict is never PROBE OK.
|
|
197
|
+
const skip = (label, why) => {
|
|
198
|
+
skipped.push(label);
|
|
199
|
+
emit(`SKIP ${label}: ${why}`);
|
|
71
200
|
};
|
|
72
201
|
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
)
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
202
|
+
const strip = stripAnsi;
|
|
203
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
204
|
+
const isGone = (pid) => {
|
|
205
|
+
try { process.kill(pid, 0); return false; } catch (e) { return e.code === "ESRCH"; }
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
// A stop that is a verdict, not a crash: carries the exit code and the verdict line.
|
|
209
|
+
class ProbeStop extends Error {
|
|
210
|
+
constructor(code, verdict) { super(verdict); this.code = code; this.verdict = verdict; }
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// Anything that escapes the case runner (a stray rejection inside an event handler) is a tooling
|
|
214
|
+
// error too: release the children, say so, exit 3 (1 when a check had already failed).
|
|
215
|
+
const fatal = (e) => {
|
|
216
|
+
try { for (const x of sessions) x.child.kill("SIGKILL"); } catch { /* a child already gone, or the registry not created yet */ }
|
|
217
|
+
if (failures > 0) console.log(`PROBE FAILED (${failures})`);
|
|
218
|
+
console.log(`PROBE TOOLING ERROR (uncaught, nothing further was asserted): ${redact(String(e?.message ?? e)).replace(/\s+/g, " ").slice(0, 300)}`);
|
|
219
|
+
process.exit(failures > 0 ? 1 : 3);
|
|
220
|
+
};
|
|
221
|
+
process.on("uncaughtException", fatal);
|
|
222
|
+
process.on("unhandledRejection", fatal);
|
|
223
|
+
|
|
224
|
+
if (!nodeVersionOk(process.version)) {
|
|
225
|
+
console.error(`UNRESOLVED: node ${process.version} is below the engine floor 22.19.0`);
|
|
226
|
+
process.exit(3);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
const cwd = join(workDir, "cwd"); // private empty cwd for every engine child
|
|
230
|
+
mkdirSync(cwd, { recursive: true });
|
|
231
|
+
const engineEnv = (key = KEY, home = HOME) => ({ PATH: process.env.PATH ?? "", HOME: home, PEN_CLI_KEY: key });
|
|
232
|
+
|
|
233
|
+
// ---------------------------------------------------------------------------
|
|
234
|
+
// A REPL session driven directly over pipes. Error replies arrive on stderr, success on stdout
|
|
235
|
+
// (measured), so a reply is both streams after the command, up to the prompt at the END of the
|
|
236
|
+
// stdout buffer followed by a quiet period.
|
|
237
|
+
class Engine {
|
|
238
|
+
constructor(args, { key = KEY, home = HOME, bin = penBin } = {}) {
|
|
239
|
+
this.out = ""; this.err = ""; this.exit = null; this.startup = "";
|
|
240
|
+
this.child = spawn(process.execPath, [bin, "interactive", ...args], {
|
|
241
|
+
cwd, env: engineEnv(key, home), stdio: ["pipe", "pipe", "pipe"],
|
|
242
|
+
});
|
|
243
|
+
this.pid = this.child.pid;
|
|
244
|
+
this.child.stdout.on("data", (d) => (this.out += d));
|
|
245
|
+
this.child.stderr.on("data", (d) => (this.err += d));
|
|
246
|
+
this.child.on("exit", (code, sig) => (this.exit = { code, sig }));
|
|
247
|
+
}
|
|
248
|
+
async waitPrompt(timeoutMs = 90000) {
|
|
249
|
+
const t0 = Date.now();
|
|
250
|
+
for (;;) {
|
|
251
|
+
if (this.exit) return false;
|
|
252
|
+
if (strip(this.out).endsWith(REPL_PROMPT)) {
|
|
253
|
+
const n = this.out.length;
|
|
254
|
+
await sleep(150);
|
|
255
|
+
if (this.out.length === n && strip(this.out).endsWith(REPL_PROMPT)) return true;
|
|
256
|
+
}
|
|
257
|
+
if (Date.now() - t0 > timeoutMs) throw new Error(`no prompt within ${timeoutMs} ms`);
|
|
258
|
+
await sleep(20);
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
async start() {
|
|
262
|
+
const ok = await this.waitPrompt();
|
|
263
|
+
this.startup = this.out;
|
|
264
|
+
this.startupErr = this.err;
|
|
265
|
+
return ok;
|
|
266
|
+
}
|
|
267
|
+
async send(cmd) {
|
|
268
|
+
this.out = ""; this.err = "";
|
|
269
|
+
this.child.stdin.write(`${cmd}\n`);
|
|
270
|
+
const ok = await this.waitPrompt();
|
|
271
|
+
const out = strip(this.out).replace(/\s*pen > $/, "").trim();
|
|
272
|
+
const err = strip(this.err).trim();
|
|
273
|
+
return { ok, out, err, all: `${out}\n${err}`.trim() };
|
|
274
|
+
}
|
|
275
|
+
async quit() {
|
|
276
|
+
if (this.exit) return;
|
|
277
|
+
this.child.stdin.write("exit()\n");
|
|
278
|
+
for (let i = 0; i < 250 && !this.exit; i++) await sleep(20);
|
|
279
|
+
if (!this.exit) this.child.kill("SIGKILL");
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
const sessions = new Set();
|
|
283
|
+
const adapters = new Set();
|
|
284
|
+
const open = (args, opts) => { const e = new Engine(args, opts); sessions.add(e); return e; };
|
|
285
|
+
// Kills every engine child and closes every adapter client, whatever state the run is in.
|
|
286
|
+
const finish = async () => {
|
|
287
|
+
for (const e of sessions) if (!e.exit) { try { e.child.kill("SIGKILL"); } catch { /* already gone */ } }
|
|
288
|
+
for (const a of adapters) { try { await a.close(); } catch { /* already closed */ } }
|
|
289
|
+
adapters.clear();
|
|
290
|
+
};
|
|
291
|
+
|
|
292
|
+
// engine processes whose command line carries a unique path (ps works on Linux and macOS)
|
|
293
|
+
const lookup = (needle) => {
|
|
294
|
+
const r = spawnSync("ps", ["-eo", "pid=,args="], { encoding: "utf8" });
|
|
295
|
+
return r.stdout.split("\n")
|
|
296
|
+
.map((l) => l.trim().match(/^(\d+)\s+(.*)$/))
|
|
297
|
+
.filter((m) => m && Number(m[1]) !== process.pid && m[2].includes(needle))
|
|
298
|
+
.map((m) => Number(m[1]));
|
|
299
|
+
};
|
|
300
|
+
const waitNoProcess = async (needle) => {
|
|
301
|
+
for (let i = 0; i < 250; i++) { if (lookup(needle).length === 0) return true; await sleep(20); }
|
|
302
|
+
return false;
|
|
303
|
+
};
|
|
304
|
+
|
|
305
|
+
const savedLine = (file) => `Saved ${join(realpathSync(dirname(file)), file.split("/").pop())}`;
|
|
306
|
+
const isSaved = (reply, file) => reply.out === savedLine(file) && reply.err === "";
|
|
307
|
+
const bytesOf = (f) => readFileSync(f);
|
|
308
|
+
const sameBytes = (a, b) => Buffer.compare(bytesOf(a), bytesOf(b)) === 0;
|
|
309
|
+
|
|
310
|
+
// A timed autosave would fire some time after an edit: watch the file for this long by mtime and
|
|
311
|
+
// size polling. A timer longer than the window is the stated limit.
|
|
312
|
+
const IDLE_WINDOW_MS = 15000;
|
|
313
|
+
const fileStamp = (f) => { try { const st = statSync(f); return `${st.mtimeMs}:${st.size}`; } catch { return "missing"; } };
|
|
314
|
+
async function watchQuiet(files, ms = IDLE_WINDOW_MS) {
|
|
315
|
+
const base = files.map(fileStamp);
|
|
316
|
+
const changed = new Set();
|
|
317
|
+
const t0 = Date.now();
|
|
318
|
+
while (Date.now() - t0 < ms) {
|
|
319
|
+
await sleep(250);
|
|
320
|
+
files.forEach((f, i) => { if (fileStamp(f) !== base[i]) changed.add(basename(f)); });
|
|
321
|
+
}
|
|
322
|
+
return [...changed];
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const MANY_RECTS =
|
|
326
|
+
'var f=I(document,{type:"frame",name:"qa",layout:"none",width:400,height:300,fill:"#ffffff"});' +
|
|
327
|
+
'for(var i=0;i<60;i++){I(f,{type:"rectangle",x:(i*37)%380,y:(i*53)%280,width:20+(i%7)*9,height:15+(i%5)*11,' +
|
|
328
|
+
'fill:"#"+(((i+1)*2654435)%16777216).toString(16).padStart(6,"0")});}Print("ID:"+f);';
|
|
329
|
+
const idOf = (reply) => /ID:([A-Za-z0-9_-]+)/.exec(reply.out)?.[1];
|
|
330
|
+
const printed = (reply) => /## Print output\n([\s\S]*)$/.exec(reply.out)?.[1].trim() ?? `no Print output: ${reply.all.slice(0, 120)}`;
|
|
331
|
+
|
|
332
|
+
async function runCases() {
|
|
333
|
+
// ---------------------------------------------------------------------------
|
|
334
|
+
// 0. The credential must be Active. A bad key does NOT stop `pen interactive` (fail-open usage
|
|
335
|
+
// check), so without this a probe run against a revoked key would still print PASS lines.
|
|
336
|
+
{
|
|
337
|
+
const st = spawnSync(process.execPath, [penBin, "status"], { encoding: "utf8", cwd, env: engineEnv(), timeout: 60000 });
|
|
338
|
+
const text = strip(`${st.stdout}\n${st.stderr}`);
|
|
339
|
+
const active = st.status === 0 && /Active/.test(text);
|
|
340
|
+
check(active, "pen status reports Active for the credential (fail-open engine guard)", active ? "" : "status was not Active (reply not recorded: it carries account details)");
|
|
341
|
+
if (!active) throw new ProbeStop(1, "PROBE FAILED (credential not Active)");
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// installed engine == the pin this probe is run for
|
|
345
|
+
{
|
|
346
|
+
let ver = "";
|
|
347
|
+
try {
|
|
348
|
+
const pkgPath = join(dirname(realpathSync(penBin)), "..", "package.json");
|
|
349
|
+
ver = JSON.parse(readFileSync(pkgPath, "utf8")).version;
|
|
350
|
+
} catch { /* handled by the check */ }
|
|
351
|
+
check(ver === pin, "installed @pen.dev/cli version equals the check_deps.sh pin", `installed=${ver || "unreadable"} pin=${pin}`);
|
|
352
|
+
// the engine's HTTP client is the lockfile-bumped dependency (pen-cli/package.json overrides); record what this run exercised
|
|
353
|
+
let undici = "unreadable";
|
|
354
|
+
try {
|
|
355
|
+
const nm = dirname(dirname(dirname(dirname(realpathSync(penBin)))));
|
|
356
|
+
undici = JSON.parse(readFileSync(join(nm, "undici", "package.json"), "utf8")).version;
|
|
357
|
+
} catch { /* recorded as unreadable */ }
|
|
358
|
+
record("undici version in the engine tree under test", undici);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// ---------------------------------------------------------------------------
|
|
362
|
+
// 1. Signatures in `pen interactive --help` vs REPL_SURFACE; removed tools absent.
|
|
363
|
+
const REMOVED = [...REMOVED_TOOL_NAMES];
|
|
364
|
+
{
|
|
365
|
+
const help = spawnSync(process.execPath, [penBin, "interactive", "--help"], { encoding: "utf8", cwd, env: engineEnv() });
|
|
366
|
+
const text = strip(`${help.stdout}\n${help.stderr}`);
|
|
367
|
+
const live = {};
|
|
368
|
+
for (const m of text.matchAll(/^# ([a-z_]+)\(\{?\s*([^})]*?)\s*\}?\)\s*$/gm)) {
|
|
369
|
+
live[m[1]] = m[2].split(",").map((k) => k.trim().replace(/\?$/, "")).filter(Boolean).sort();
|
|
370
|
+
}
|
|
371
|
+
check(Object.keys(live).length > 0, "parsed tool signatures from --help", text.slice(0, 200));
|
|
372
|
+
const table = Object.fromEntries(
|
|
373
|
+
Object.entries(REPL_SURFACE).filter(([t]) => t !== "save").map(([t, k]) => [t, [...k].sort()])
|
|
374
|
+
);
|
|
375
|
+
const mismatched = Object.entries(table).filter(([t, k]) => JSON.stringify(live[t]) !== JSON.stringify(k));
|
|
376
|
+
check(mismatched.length === 0, "every REPL_SURFACE tool has exactly the signature the CLI prints",
|
|
377
|
+
`mismatched=${JSON.stringify(mismatched)} live=${JSON.stringify(live)}`);
|
|
378
|
+
const stillListed = REMOVED.filter((t) => t in live);
|
|
379
|
+
check(stillListed.length === 0, `none of the ${REMOVED.length} removed tools is listed in --help`, stillListed.join(","));
|
|
380
|
+
check(/^\s*save\(\)\s/m.test(text) || /save\(\)/.test(text), "--help documents the save() shell command");
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// ---------------------------------------------------------------------------
|
|
384
|
+
// 2-5, 7, 9. One session on seed.pen: prompt, OK, print output, count, save, removed names, skills.
|
|
385
|
+
const seed = join(workDir, "seed.pen");
|
|
386
|
+
let engineGuideNames = [];
|
|
387
|
+
{
|
|
388
|
+
const s = open(["--out", seed]);
|
|
389
|
+
const started = await s.start();
|
|
390
|
+
check(started, "session starts and reaches the prompt", strip(s.out).slice(-200));
|
|
391
|
+
check(strip(s.startup).includes("[INFO] Ready."), "startup prints [INFO] Ready. before the prompt");
|
|
392
|
+
check(strip(s.startup).trimEnd().endsWith(REPL_PROMPT.trimEnd()), "prompt is `pen > ` at the end of the buffer");
|
|
393
|
+
check(s.startup.endsWith(REPL_PROMPT_RAW), "raw prompt bytes equal REPL_PROMPT_RAW", JSON.stringify(s.startup.slice(-40)));
|
|
394
|
+
record("ANSI escapes on piped stdout", s.startup.includes("\x1b[") ? "yes (the engine colours even on a pipe)" : "no");
|
|
395
|
+
|
|
396
|
+
// count on an empty document, then edits
|
|
397
|
+
let nonce = newCountNonce();
|
|
398
|
+
let r = await s.send(buildCountCommand(nonce));
|
|
399
|
+
check(parseCountReply(r.all, nonce) === 0, "nonce count on an empty document is 0", r.all);
|
|
400
|
+
check(parseCountReply(r.all, newCountNonce()) === null, "a count line for another nonce is not accepted");
|
|
401
|
+
|
|
402
|
+
r = await s.send(buildBatchDesignCommand('f=I(document,{type:"frame",width:200,height:100,fill:"#FFFFFF"})\nt=I(f,{type:"text",content:"probe"})\nPrint("probe-print-line")'));
|
|
403
|
+
check(/^OK\b/.test(r.out), "batch_design reply starts with OK", r.all);
|
|
404
|
+
check(r.out.includes("## Print output") && r.out.includes("probe-print-line"), "reply carries a ## Print output section", r.all);
|
|
405
|
+
r = await s.send(buildBatchDesignCommand('g=I(document,{type:"frame",width:50,height:50})'));
|
|
406
|
+
check(/^OK\b/.test(r.out), "second consecutive batch_design reply starts with OK", r.all);
|
|
407
|
+
const typeofAlias = await s.send(buildBatchDesignCommand('Print(typeof I, typeof U)'));
|
|
408
|
+
check(/function\s+function/.test(typeofAlias.out), "the alias preamble defines I and U inside execute", typeofAlias.all);
|
|
409
|
+
|
|
410
|
+
nonce = newCountNonce();
|
|
411
|
+
r = await s.send(buildCountCommand(nonce));
|
|
412
|
+
check(parseCountReply(r.all, nonce) === 2, "nonce count after two top-level inserts is 2", r.all);
|
|
413
|
+
// a node named like a count line must not forge the probe: the nonce differs per call
|
|
414
|
+
const n2 = newCountNonce();
|
|
415
|
+
await s.send(buildBatchDesignCommand(`I(document,{type:"frame",name:"TOPLEVEL_COUNT:${n2}:99",width:5,height:5})`));
|
|
416
|
+
r = await s.send(buildCountCommand(n2));
|
|
417
|
+
check(parseCountReply(r.all, n2) === 3, "a node name that imitates the count line does not change the parse", r.all);
|
|
418
|
+
|
|
419
|
+
r = await s.send(buildSaveCommand());
|
|
420
|
+
check(isSaved(r, seed), "save() replies exactly `Saved <path>` on stdout", r.all);
|
|
421
|
+
let doc = {};
|
|
422
|
+
try { doc = JSON.parse(readFileSync(seed, "utf8")); } catch { /* checked below */ }
|
|
423
|
+
check(Array.isArray(doc.children) && doc.children.length === 3, "the saved file holds the three top-level nodes", `children=${doc.children?.length}`);
|
|
424
|
+
check(statSync(seed).size > 96, "the saved file is larger than the 96-byte empty document", `size=${statSync(seed).size}`);
|
|
425
|
+
check(typeof doc.version === "string", "the saved document carries a version", String(doc.version));
|
|
426
|
+
|
|
427
|
+
// 7. removed names: the engine's own answer, and the enrichment the adapter appends to it
|
|
428
|
+
for (const name of REMOVED) {
|
|
429
|
+
r = await s.send(`${name}()`);
|
|
430
|
+
check(r.ok && /Unknown tool:/.test(r.all), `${name}() answers Unknown tool:`, r.all);
|
|
431
|
+
const enriched = enrichErrorMessage(r.all);
|
|
432
|
+
check(enriched.includes(`[adapter hint] ${removedToolHint(name)}`), `${name}: the enrichment appends the exact removed-tool hint to the engine's answer`, enriched.slice(-160));
|
|
433
|
+
}
|
|
434
|
+
r = await s.send("batch_design({ operations: 'x' })");
|
|
435
|
+
check(r.ok && /Unknown tool:/.test(r.all), "batch_design() (the old name) answers Unknown tool:", r.all);
|
|
436
|
+
|
|
437
|
+
// 9. read_skill on every guide path, each followed by an intact save() reply
|
|
438
|
+
const idx = await s.send(buildReadSkillCommand());
|
|
439
|
+
// the index is a markdown table whose link TARGETS are the readable paths: `[x.md](./guide/x.md)`
|
|
440
|
+
const paths = [...new Set([...idx.out.matchAll(/\]\(\.\/((?:guide\/)?[a-z0-9-]+\.md)\)/g)].map((m) => m[1]))];
|
|
441
|
+
check(paths.length >= 12, "read_skill() index lists the guide and top-level paths", `found ${paths.length}: ${paths.join(" ")}`);
|
|
442
|
+
for (const must of ["pen-schema.md", "execute.md"]) check(paths.includes(must), `read_skill index lists ${must}`);
|
|
443
|
+
check(paths.filter((p) => p.startsWith("guide/")).length >= 9, "read_skill index lists at least 9 guide/ paths");
|
|
444
|
+
engineGuideNames = paths.filter((p) => p.startsWith("guide/")).map((p) => p.slice(6, -3)).sort();
|
|
445
|
+
let bad = [];
|
|
446
|
+
for (const p of paths) { try { validateSkillPath(p); } catch { bad.push(p); } }
|
|
447
|
+
check(bad.length === 0, "every listed path passes the adapter's read_skill validator", bad.join(","));
|
|
448
|
+
let skillFailures = [];
|
|
449
|
+
for (const p of paths) {
|
|
450
|
+
const rr = await s.send(buildReadSkillCommand(p));
|
|
451
|
+
const sv = await s.send(buildSaveCommand());
|
|
452
|
+
if (!rr.ok || rr.out.length < 50 || rr.err !== "" || !isSaved(sv, seed)) skillFailures.push(`${p}: skill=${rr.out.length}b err=${rr.err.slice(0, 60)} save=${sv.all.slice(0, 80)}`);
|
|
453
|
+
}
|
|
454
|
+
check(skillFailures.length === 0, `read_skill on all ${paths.length} paths, each followed by an intact save() reply`, skillFailures.join(" | "));
|
|
455
|
+
await s.quit();
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
// 9b. the guide names the prose promises are the guide names the engine lists
|
|
459
|
+
{
|
|
460
|
+
const guideList = (text, re) => {
|
|
461
|
+
const m = re.exec(text);
|
|
462
|
+
return m ? [...m[1].matchAll(/[a-z][a-z0-9-]*/g)].map((x) => x[0]).sort() : null;
|
|
463
|
+
};
|
|
464
|
+
const read = (rel) => { try { return readFileSync(join(repoRoot, rel), "utf8"); } catch { return ""; } };
|
|
465
|
+
const sources = [
|
|
466
|
+
["plugins/soleur/skills/pencil-setup/SKILL.md", /guides: ([a-z0-9, -]+)\)/],
|
|
467
|
+
["plugins/soleur/agents/product/design/ux-design-lead.md", /design type \(([^)]*)\)/],
|
|
468
|
+
];
|
|
469
|
+
for (const [rel, re] of sources) {
|
|
470
|
+
const names = guideList(read(rel), re);
|
|
471
|
+
check(names !== null && JSON.stringify(names) === JSON.stringify(engineGuideNames),
|
|
472
|
+
`guide names in ${basename(rel)} equal the engine's read_skill index`,
|
|
473
|
+
names === null ? "guide list not found in the file" : `file=${names.join(",")} engine=${engineGuideNames.join(",")}`);
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
// 6. a failing save prints `Save failed:` and writes nothing, now or later
|
|
478
|
+
{
|
|
479
|
+
const ro = join(workDir, "ro");
|
|
480
|
+
mkdirSync(ro, { recursive: true });
|
|
481
|
+
const target = join(ro, "x.pen");
|
|
482
|
+
if (typeof process.getuid === "function" && process.getuid() === 0) {
|
|
483
|
+
skip("Save failed: case", "running as root: a read-only directory does not fail the write");
|
|
484
|
+
} else {
|
|
485
|
+
const s = open(["--out", target]);
|
|
486
|
+
await s.start();
|
|
487
|
+
await s.send(buildBatchDesignCommand('I(document,{type:"frame",width:10,height:10})'));
|
|
488
|
+
chmodSync(ro, 0o555);
|
|
489
|
+
const r = await s.send(buildSaveCommand());
|
|
490
|
+
chmodSync(ro, 0o755);
|
|
491
|
+
check(/^Save failed:/m.test(r.all), "a failed save prints `Save failed:`", r.all);
|
|
492
|
+
record("Save failed: stream", r.err.includes("Save failed:") ? "stderr" : r.out.includes("Save failed:") ? "stdout" : "none");
|
|
493
|
+
check(!/^Saved /m.test(r.all), "a failed save is not confirmed with a Saved line");
|
|
494
|
+
check(!existsSync(target), "a failed save left no file behind");
|
|
495
|
+
// the directory is writable again: an engine write timer that retried the unsaved document would land now
|
|
496
|
+
const late = await watchQuiet([target]);
|
|
497
|
+
check(late.length === 0 && !existsSync(target), `no engine write appears in the ${IDLE_WINDOW_MS / 1000} s after a failed save (directory writable again)`, late.join(","));
|
|
498
|
+
const again = await s.send(buildSaveCommand());
|
|
499
|
+
record("save() after the cause of a failed save is fixed", isSaved(again, target) ? "Saved (the engine kept the edit in memory)" : again.all.slice(0, 120));
|
|
500
|
+
await s.quit();
|
|
501
|
+
}
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// 8. export formats, scale and quality
|
|
505
|
+
{
|
|
506
|
+
const s = open(["--out", join(workDir, "export.pen")]);
|
|
507
|
+
await s.start();
|
|
508
|
+
const r0 = await s.send(buildBatchDesignCommand(MANY_RECTS));
|
|
509
|
+
const id = idOf(r0);
|
|
510
|
+
check(Boolean(id), "created a frame to export and read its id", r0.all);
|
|
511
|
+
const exportTo = async (name, options) => {
|
|
512
|
+
const dir = join(workDir, `ex-${name}`);
|
|
513
|
+
mkdirSync(dir, { recursive: true });
|
|
514
|
+
const r = await s.send(buildExportCommand({ nodeIds: [id], outputDir: dir, ...options }));
|
|
515
|
+
const files = [...r.out.matchAll(/^Exported (\/.+)$/gm)].map((m) => m[1]);
|
|
516
|
+
return { r, dir, files, file: files[0], bytes: files[0] && existsSync(files[0]) ? readFileSync(files[0]) : null };
|
|
517
|
+
};
|
|
518
|
+
const magic = {
|
|
519
|
+
png: (b) => b.subarray(0, 4).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47])),
|
|
520
|
+
jpeg: (b) => b.subarray(0, 3).equals(Buffer.from([0xff, 0xd8, 0xff])),
|
|
521
|
+
webp: (b) => b.subarray(0, 4).toString("latin1") === "RIFF" && b.subarray(8, 12).toString("latin1") === "WEBP",
|
|
522
|
+
pdf: (b) => b.subarray(0, 4).toString("latin1") === "%PDF",
|
|
523
|
+
};
|
|
524
|
+
const results = {};
|
|
525
|
+
for (const fmt of ["png", "jpeg", "webp", "pdf"]) {
|
|
526
|
+
results[fmt] = await exportTo(fmt, { format: fmt });
|
|
527
|
+
const x = results[fmt];
|
|
528
|
+
check(Boolean(x.bytes) && magic[fmt](x.bytes), `export format ${fmt} writes a ${fmt} file`, x.r.all);
|
|
529
|
+
check(x.files.length === 1 && x.file.startsWith(x.dir + "/"), `export ${fmt}: the reply names one path inside the requested directory`, x.files.join(","));
|
|
530
|
+
}
|
|
531
|
+
const dims = (b) => ({ w: b.readUInt32BE(16), h: b.readUInt32BE(20) });
|
|
532
|
+
const s1 = await exportTo("png-s1", { format: "png", scale: 1 });
|
|
533
|
+
const s3 = await exportTo("png-s3", { format: "png", scale: 3 });
|
|
534
|
+
const d1 = s1.bytes && dims(s1.bytes), d3 = s3.bytes && dims(s3.bytes);
|
|
535
|
+
check(Boolean(d1 && d3) && d3.w === d1.w * 3 && d3.h === d1.h * 3, "png scale 3 yields 3x the pixel dimensions of scale 1", `${JSON.stringify(d1)} vs ${JSON.stringify(d3)}`);
|
|
536
|
+
for (const fmt of ["jpeg", "webp"]) {
|
|
537
|
+
const lo = await exportTo(`${fmt}-q10`, { format: fmt, quality: 10 });
|
|
538
|
+
const hi = await exportTo(`${fmt}-q95`, { format: fmt, quality: 95 });
|
|
539
|
+
const ok = lo.bytes && hi.bytes && lo.bytes.length < hi.bytes.length;
|
|
540
|
+
check(Boolean(ok), `${fmt} quality 10 yields a smaller file than quality 95`, `q10=${lo.bytes?.length} q95=${hi.bytes?.length}`);
|
|
541
|
+
}
|
|
542
|
+
// a missing node id must fail before writing anything
|
|
543
|
+
const dirMissing = join(workDir, "ex-missing");
|
|
544
|
+
mkdirSync(dirMissing);
|
|
545
|
+
const rm = await s.send(buildExportCommand({ nodeIds: ["noSuchNode1"], outputDir: dirMissing, format: "png" }));
|
|
546
|
+
check(readdirSync(dirMissing).length === 0 && /rror/.test(rm.all), "Export of a missing node id errors and writes nothing", rm.all);
|
|
547
|
+
await s.quit();
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// 10. no engine write outside save(): positive control, then exit(), SIGTERM, SIGKILL, all idle together
|
|
551
|
+
{
|
|
552
|
+
const edit = buildBatchDesignCommand('I(document,{type:"frame",name:"unsaved-edit",width:30,height:30})');
|
|
553
|
+
const prep = (name) => {
|
|
554
|
+
const f = join(workDir, `nw-${name}.pen`);
|
|
555
|
+
copyFileSync(seed, f);
|
|
556
|
+
return f;
|
|
557
|
+
};
|
|
558
|
+
{
|
|
559
|
+
const f = prep("control");
|
|
560
|
+
const s = open(["--out", f, "--in", f]);
|
|
561
|
+
await s.start();
|
|
562
|
+
await s.send(edit);
|
|
563
|
+
const sv = await s.send(buildSaveCommand());
|
|
564
|
+
await s.quit();
|
|
565
|
+
check(isSaved(sv, f) && !sameBytes(f, seed), "positive control: the same edit plus save() DOES change the bytes", sv.all);
|
|
566
|
+
}
|
|
567
|
+
const paths = ["exit()", "SIGTERM", "SIGKILL"];
|
|
568
|
+
const runs = [];
|
|
569
|
+
for (const path of paths) {
|
|
570
|
+
const f = prep(path.replace(/\W/g, ""));
|
|
571
|
+
const s = open(["--out", f, "--in", f]);
|
|
572
|
+
const started = await s.start();
|
|
573
|
+
const ed = await s.send(edit);
|
|
574
|
+
runs.push({ path, f, s, started, ed });
|
|
575
|
+
}
|
|
576
|
+
// the sessions sit idle with an unsaved edit while the files are watched by mtime polling
|
|
577
|
+
const changed = await watchQuiet(runs.map((x) => x.f));
|
|
578
|
+
check(changed.length === 0, `no engine write to any file during a ${IDLE_WINDOW_MS / 1000} s idle window after an unsaved edit (mtime polling)`, changed.join(","));
|
|
579
|
+
for (const { path, f, s, started, ed } of runs) {
|
|
580
|
+
if (path === "exit()") s.child.stdin.write("exit()\n");
|
|
581
|
+
else s.child.kill(path);
|
|
582
|
+
for (let i = 0; i < 250 && !s.exit; i++) await sleep(20);
|
|
583
|
+
const gone = isGone(s.pid) && (await waitNoProcess(f));
|
|
584
|
+
check(started && /^OK\b/.test(ed.out) && gone, `edit then ${path}: the engine process is gone`, `started=${started} edit=${ed.out.slice(0, 40)} exit=${JSON.stringify(s.exit)}`);
|
|
585
|
+
check(sameBytes(f, seed), `edit then ${path}: the file is byte-identical to before the session`);
|
|
586
|
+
}
|
|
587
|
+
note(`a timed autosave firing later than ${IDLE_WINDOW_MS / 1000} s after the edit is outside the observation window (stated limit)`);
|
|
588
|
+
}
|
|
589
|
+
|
|
590
|
+
// 11. batch_design raw DSL: what the sandbox exposes, and what the path-taking host functions do
|
|
591
|
+
{
|
|
592
|
+
const s = open(["--out", join(workDir, "dsl.pen")]);
|
|
593
|
+
await s.start();
|
|
594
|
+
const pr = async (code) => printed(await s.send(buildBatchDesignCommand(code)));
|
|
595
|
+
|
|
596
|
+
// (a) no Node/host globals reach the DSL. The `typeof` of each name and two escape routes are
|
|
597
|
+
// pinned: a different answer after a bump means the "QuickJS sandbox with no process, require,
|
|
598
|
+
// fetch" sentence in ADR-306 must be re-read.
|
|
599
|
+
const DENY = ["process", "require", "fetch", "XMLHttpRequest", "Buffer", "module", "exports", "WebSocket", "Deno", "Bun",
|
|
600
|
+
"console", "setTimeout", "setInterval", "setImmediate", "queueMicrotask", "importScripts", "navigator", "window", "self", "global", "std", "os"];
|
|
601
|
+
const kinds = (await pr(`Print([${DENY.map((n) => `typeof ${n}`).join(",")}].join(","))`)).split(",");
|
|
602
|
+
const exposed = DENY.filter((n, i) => kinds[i] !== "undefined");
|
|
603
|
+
check(kinds.length === DENY.length && exposed.length === 0, "the DSL sandbox defines none of process/require/fetch/XMLHttpRequest/Buffer/module/console/timers/std/os (typeof is undefined)", `exposed=${exposed.join(",")} raw=${kinds.join(",").slice(0, 120)}`);
|
|
604
|
+
const viaThis = await pr('Print(typeof (function(){return this})().process)');
|
|
605
|
+
const viaCtor = await pr('Print((function(){}).constructor("return typeof process + typeof require + typeof fetch")())');
|
|
606
|
+
const viaEval = await pr('Print(eval("typeof process + typeof require + typeof fetch"))');
|
|
607
|
+
check(viaThis === "undefined" && viaCtor === "undefinedundefinedundefined" && viaEval === "undefinedundefinedundefined",
|
|
608
|
+
"escape routes (this, Function constructor, eval) reach no process/require/fetch", `this=${viaThis} ctor=${viaCtor} eval=${viaEval}`);
|
|
609
|
+
// (b) the host-function set: every global that is not an ECMAScript built-in
|
|
610
|
+
const ES = new Set(("AggregateError,Array,ArrayBuffer,BigInt,BigInt64Array,BigUint64Array,Boolean,DataView,Date,Error,EvalError,FinalizationRegistry," +
|
|
611
|
+
"Float16Array,Float32Array,Float64Array,Function,Infinity,Int16Array,Int32Array,Int8Array,InternalError,Iterator,JSON,Map,Math,NaN,Number,Object,Promise,Proxy," +
|
|
612
|
+
"RangeError,ReferenceError,Reflect,RegExp,Set,SharedArrayBuffer,String,Symbol,SyntaxError,TypeError,URIError,Uint16Array,Uint32Array,Uint8Array,Uint8ClampedArray," +
|
|
613
|
+
"WeakMap,WeakRef,WeakSet,decodeURI,decodeURIComponent,encodeURI,encodeURIComponent,escape,eval,globalThis,isFinite,isNaN,parseFloat,parseInt,undefined,unescape").split(","));
|
|
614
|
+
const names = (await pr('Print(Object.getOwnPropertyNames(globalThis).sort().join(","))')).split(",");
|
|
615
|
+
const host = names.filter((n) => !ES.has(n)).join(",");
|
|
616
|
+
record("DSL host globals (every global that is not an ECMAScript built-in)", host);
|
|
617
|
+
const PINNED_HOST_GLOBALS = "C,Copy,D,Delete,Export,FindEmptySpace,G,Generate,Get,GetVariables,I,Insert,M,Move,Print,R,Replace,SetVariables,TakeScreenshot,U,Update," +
|
|
618
|
+
"__batchDesignC,__batchDesignD,__batchDesignExportGlobals,__batchDesignFindEmptySpace,__batchDesignG,__batchDesignGet,__batchDesignGetVariables,__batchDesignI,__batchDesignM,__batchDesignP,__batchDesignR,__batchDesignT,__batchDesignU,__batchDesignV,__batchDesignX,document,root";
|
|
619
|
+
check(host === PINNED_HOST_GLOBALS, "pinned engine behaviour: the DSL host-function set", `observed=${host}`);
|
|
620
|
+
|
|
621
|
+
// a dynamic import must not hand the DSL a loadable node:fs; its promise is observed on the NEXT call
|
|
622
|
+
await pr('(function(){try{var p=eval(\'import("node:fs")\');p.then(function(m){globalThis.__dyn="loaded:"+typeof m.readFileSync},function(e){globalThis.__dyn="rejected:"+String(e&&e.message).slice(0,60)})}catch(e){globalThis.__dyn="threw:"+String(e.message).slice(0,60)}})()');
|
|
623
|
+
const dynImport = await pr('Print(typeof globalThis.__dyn==="undefined"?"never-settled":globalThis.__dyn)');
|
|
624
|
+
record("dynamic import(\"node:fs\") inside the DSL", dynImport);
|
|
625
|
+
check(!/^loaded/.test(dynImport), "dynamic import does not hand the DSL a loadable node:fs module", dynImport);
|
|
626
|
+
|
|
627
|
+
// (c) path-taking host functions: Export reaches any path; image-fill urls read local files
|
|
628
|
+
const docDir = join(workDir, "doc-pin");
|
|
629
|
+
const outside = join(workDir, "outside");
|
|
630
|
+
mkdirSync(docDir, { recursive: true });
|
|
631
|
+
mkdirSync(outside, { recursive: true });
|
|
632
|
+
const p = open(["--out", join(docDir, "pin.pen")]);
|
|
633
|
+
await p.start();
|
|
634
|
+
const r0 = await p.send(buildBatchDesignCommand('var red=I(document,{type:"frame",layout:"none",width:40,height:40,fill:"#FF0000"});var blue=I(document,{type:"frame",layout:"none",width:30,height:30,fill:"#0000FF"});Print("ID:"+red+" "+blue);'));
|
|
635
|
+
const [redId, blueId] = /ID:(\S+) (\S+)/.exec(r0.out)?.slice(1) ?? [];
|
|
636
|
+
// (c1) Export through raw DSL to an absolute directory outside the document's directory
|
|
637
|
+
const ex = await p.send(buildBatchDesignCommand(`Export([${JSON.stringify(redId)}],"png",${JSON.stringify(outside)})`));
|
|
638
|
+
const wrote = readdirSync(outside).filter((f) => f.endsWith(".png"));
|
|
639
|
+
const outsideFile = wrote[0] ? join(outside, wrote[0]) : null;
|
|
640
|
+
record("batch_design Export to an absolute dir outside the document dir", wrote.length ? "writes there" : `no file (${ex.all.slice(0, 80)})`);
|
|
641
|
+
// (c2) does Export overwrite an existing file at that path?
|
|
642
|
+
let overwrote = "n/a";
|
|
643
|
+
if (outsideFile) {
|
|
644
|
+
writeFileSync(outsideFile, "sentinel-not-a-png");
|
|
645
|
+
const again = await p.send(buildBatchDesignCommand(`Export([${JSON.stringify(redId)}],"png",${JSON.stringify(outside)})`));
|
|
646
|
+
overwrote = readFileSync(outsideFile, "latin1") === "sentinel-not-a-png" ? "no (kept the existing file)" : "yes (replaced the existing file)";
|
|
647
|
+
record("batch_design Export over an existing file", `${overwrote}; reply: ${again.all.slice(0, 80)}`);
|
|
648
|
+
}
|
|
649
|
+
// (c3) two nodes as pdf: one combined export.pdf in the directory
|
|
650
|
+
const pdfDir = join(workDir, "doc-pdf");
|
|
651
|
+
mkdirSync(pdfDir, { recursive: true });
|
|
652
|
+
await p.send(buildBatchDesignCommand(`Export([${JSON.stringify(redId)},${JSON.stringify(blueId)}],"pdf",${JSON.stringify(pdfDir)})`));
|
|
653
|
+
const pdfFiles = readdirSync(pdfDir).sort().join(",");
|
|
654
|
+
record("batch_design Export of two nodes as pdf", pdfFiles || "no file");
|
|
655
|
+
// (c4) the non-image formats html-css / html-tailwind take a FILE path as the third argument
|
|
656
|
+
const sv = await p.send(buildSaveCommand());
|
|
657
|
+
const docFile = join(docDir, "pin.pen");
|
|
658
|
+
const docBefore = existsSync(docFile) ? readFileSync(docFile) : Buffer.alloc(0);
|
|
659
|
+
const htmlNew = join(docDir, "out.html");
|
|
660
|
+
await p.send(buildBatchDesignCommand(`Export([${JSON.stringify(redId)}],"html-css",${JSON.stringify(htmlNew)})`));
|
|
661
|
+
const htmlNewKind = existsSync(htmlNew) && /^<!doctype html>/i.test(readFileSync(htmlNew, "utf8")) ? "writes the named html file" : "no html file";
|
|
662
|
+
record("batch_design Export html-css to a new file path in the document dir", htmlNewKind);
|
|
663
|
+
const overDoc = await p.send(buildBatchDesignCommand(`Export([${JSON.stringify(redId)}],"html-css",${JSON.stringify(docFile)})`));
|
|
664
|
+
const docAfter = readFileSync(docFile);
|
|
665
|
+
const overDocKind = Buffer.compare(docBefore, docAfter) === 0 ? "document untouched"
|
|
666
|
+
: /^<!doctype html>/i.test(docAfter.toString("utf8")) ? "OVERWRITES the open document file with html (the design is gone from disk)" : "document changed to something else";
|
|
667
|
+
record("batch_design Export html-css to the open document's own path", `${overDocKind}; reply: ${overDoc.all.slice(0, 80)}`);
|
|
668
|
+
check(isSaved(sv, docFile), "the document was saved before the html Export-over-document test", sv.all);
|
|
669
|
+
// (c5) image fills with local urls: loaded or ignored?
|
|
670
|
+
const probeImage = async (label, url) => {
|
|
671
|
+
const a = await p.send(buildBatchDesignCommand(`var im=I(document,{type:"rectangle",width:40,height:40,fill:{type:"image",url:${JSON.stringify(url)},mode:"cover"}});Print("ID:"+im);`));
|
|
672
|
+
const imId = idOf(a);
|
|
673
|
+
if (!imId) return null;
|
|
674
|
+
const d = join(workDir, `pin-${label}`);
|
|
675
|
+
mkdirSync(d, { recursive: true });
|
|
676
|
+
await p.send(buildExportCommand({ nodeIds: [imId], outputDir: d, format: "png" }));
|
|
677
|
+
const f = readdirSync(d)[0];
|
|
678
|
+
return f ? readFileSync(join(d, f)) : null;
|
|
679
|
+
};
|
|
680
|
+
let loaded = {};
|
|
681
|
+
if (outsideFile) {
|
|
682
|
+
// restore a real png at the outside path
|
|
683
|
+
await p.send(buildBatchDesignCommand(`Export([${JSON.stringify(redId)}],"png",${JSON.stringify(outside)})`));
|
|
684
|
+
const redPng = readFileSync(outsideFile);
|
|
685
|
+
const missing = await probeImage("missing", join(workDir, "no-such-image.png"));
|
|
686
|
+
// reference: the same rectangle filled with the colour the image holds
|
|
687
|
+
const solid = await p.send(buildBatchDesignCommand('var rr=I(document,{type:"rectangle",width:40,height:40,fill:"#FF0000"});Print("ID:"+rr);'));
|
|
688
|
+
const refDir = join(workDir, "pin-solid");
|
|
689
|
+
mkdirSync(refDir, { recursive: true });
|
|
690
|
+
await p.send(buildExportCommand({ nodeIds: [idOf(solid)], outputDir: refDir, format: "png" }));
|
|
691
|
+
const solidPng = readFileSync(join(refDir, readdirSync(refDir)[0]));
|
|
692
|
+
for (const [label, url] of [
|
|
693
|
+
["abs", outsideFile],
|
|
694
|
+
["fileurl", `file://${outsideFile}`],
|
|
695
|
+
["traversal", `../outside/${wrote[0]}`],
|
|
696
|
+
]) {
|
|
697
|
+
const got = await probeImage(label, url);
|
|
698
|
+
loaded[label] = !got || !missing ? "inconclusive"
|
|
699
|
+
: Buffer.compare(got, solidPng) === 0 ? "loaded (renders the local file's pixels)"
|
|
700
|
+
: Buffer.compare(got, missing) === 0 ? "ignored (same output as a missing file)"
|
|
701
|
+
: "differs from a missing file but is not the file's pixels";
|
|
702
|
+
record(`image fill url (${label}) pointing outside the document dir`, loaded[label]);
|
|
703
|
+
}
|
|
704
|
+
check(redPng.length > 100, "the image fills above were tried against a real exported png", `size=${redPng.length}`);
|
|
705
|
+
}
|
|
706
|
+
note("batch_design host-function behaviour is RECORDED above and PINNED below; switch to a shadowing prelude only if Export overwrites arbitrary files or image urls read local files (CTO ruling 11.2)");
|
|
707
|
+
// PINNED: the observed behaviour at the pin. A different answer after a bump FAILS here so the
|
|
708
|
+
// residual-risk statement in ADR-306 is re-read; it never silently drifts.
|
|
709
|
+
const PINNED = {
|
|
710
|
+
exportOutside: "writes there",
|
|
711
|
+
exportOverwrite: "yes (replaced the existing file)", // png/jpeg/webp/pdf: <nodeId>.<format> (export.pdf for several nodes) inside the chosen directory
|
|
712
|
+
exportPdfMulti: "export.pdf",
|
|
713
|
+
exportHtmlNewFile: "writes the named html file", // html-css/html-tailwind take a FILE path, not a directory
|
|
714
|
+
exportHtmlOverDocument: "OVERWRITES the open document file with html (the design is gone from disk)",
|
|
715
|
+
imageAbs: "loaded (renders the local file's pixels)",
|
|
716
|
+
imageFileUrl: "loaded (renders the local file's pixels)",
|
|
717
|
+
imageTraversal: "loaded (renders the local file's pixels)",
|
|
718
|
+
};
|
|
719
|
+
const observed = {
|
|
720
|
+
exportOutside: wrote.length ? "writes there" : "no file",
|
|
721
|
+
exportOverwrite: overwrote,
|
|
722
|
+
exportPdfMulti: pdfFiles,
|
|
723
|
+
exportHtmlNewFile: htmlNewKind,
|
|
724
|
+
exportHtmlOverDocument: overDocKind,
|
|
725
|
+
imageAbs: loaded.abs,
|
|
726
|
+
imageFileUrl: loaded.fileurl,
|
|
727
|
+
imageTraversal: loaded.traversal,
|
|
728
|
+
};
|
|
729
|
+
for (const k of Object.keys(PINNED)) {
|
|
730
|
+
check(observed[k] === PINNED[k], `pinned engine behaviour: ${k}`, `observed=${observed[k]} pinned=${PINNED[k]}`);
|
|
731
|
+
}
|
|
732
|
+
await s.quit();
|
|
733
|
+
await p.quit();
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
// 11b. the recipe forms the prose promises (SKILL.md, ux-design-lead.md, the removed-tool hints): they must
|
|
737
|
+
// RUN against the engine, not merely read well. A hint that names a form that errors is worse than no hint.
|
|
738
|
+
{
|
|
739
|
+
const s = open(["--out", join(workDir, "recipes.pen")]);
|
|
740
|
+
await s.start();
|
|
741
|
+
const pr = async (code) => s.send(buildBatchDesignCommand(code));
|
|
742
|
+
const r0 = await pr(MANY_RECTS);
|
|
743
|
+
const id = idOf(r0);
|
|
744
|
+
check(Boolean(id), "recipes: created the 60-rectangle frame and read its id", r0.all);
|
|
745
|
+
|
|
746
|
+
// Get(id,(n,c)=>Print(c.bounds.width)): the visitor runs for the node AND every descendant (measured:
|
|
747
|
+
// 61 calls for the frame plus its 60 rectangles), frame first. The prose must not promise a single value.
|
|
748
|
+
const w = await pr(`Get(${JSON.stringify(id)},(n,c)=>Print(c.bounds.width))`);
|
|
749
|
+
const widths = printed(w).split(/\s+/);
|
|
750
|
+
check(!/rror/.test(w.all) && widths[0] === "400", "recipe: Get(id,(n,c)=>Print(c.bounds.width)) prints the frame's measured width FIRST", `${widths.slice(0, 4).join(" ")} | ${w.all.slice(0, 120)}`);
|
|
751
|
+
check(widths.length === 61, "pinned engine behaviour: Get(id, visitor) visits the node and all of its descendants (one Print line per node)", `values=${widths.length}`);
|
|
752
|
+
const w2 = await pr(`Get(${JSON.stringify(id)},(n,c)=>Print(n.id+' '+c.bounds.width))`);
|
|
753
|
+
check(!/rror/.test(w2.all) && printed(w2).split(/\s+/).slice(0, 2).join(" ") === `${id} 400`, "recipe: Get(id,(n,c)=>Print(n.id+' '+c.bounds.width)) (the hint's own example) prints the id and the width, frame first", `${printed(w2).slice(0, 60)} | ${w2.all.slice(0, 120)}`);
|
|
754
|
+
|
|
755
|
+
// c.problems: a STRING per node (or undefined), "partially clipped" / "fully clipped"; the frame's rectangles
|
|
756
|
+
// that overhang it report it. The hint wording "clipping (partially or fully clipped)" is pinned to this.
|
|
757
|
+
const pf = await pr(`var out=[];Get(${JSON.stringify(id)},(n,c)=>{out.push(c.problems===undefined?"-":typeof c.problems+":"+c.problems)});Print(out.join("|"))`);
|
|
758
|
+
const pvals = printed(pf).split("|");
|
|
759
|
+
const kindsSeen = [...new Set(pvals.map((v) => v.replace(/^string:(.*)$/, "string:$1")))].sort();
|
|
760
|
+
record("recipe: c.problems values across the frame and its 60 rectangles", kindsSeen.join(", "));
|
|
761
|
+
check(!/rror/.test(pf.all) && pvals.length === 61, "recipe: the c.problems visitor runs on every node of the frame without an error", `values=${pvals.length} ${pf.all.slice(0, 120)}`);
|
|
762
|
+
check(pvals.some((v) => v === "string:partially clipped") && pvals.every((v) => v === "-" || /^string:(partially|fully) clipped$/.test(v)),
|
|
763
|
+
"pinned engine behaviour: c.problems is a string, `partially clipped` or `fully clipped`, undefined when the node has no problem (the 400x300 frame clips overhanging rectangles)", kindsSeen.join(", "));
|
|
764
|
+
|
|
765
|
+
// Print(FindEmptySpace({width:50,height:50})): the hint for the removed find_empty_space_on_canvas
|
|
766
|
+
const fes = await pr("Print(FindEmptySpace({width:50,height:50}))");
|
|
767
|
+
check(!/rror/.test(fes.all) && /## Print output\n\S/.test(fes.out), "recipe: Print(FindEmptySpace({width:50,height:50})) prints a position", `${printed(fes)} | ${fes.all.slice(0, 120)}`);
|
|
768
|
+
record("recipe: FindEmptySpace reply", printed(fes));
|
|
769
|
+
await s.quit();
|
|
770
|
+
|
|
771
|
+
// The steering sentence "do not call Export inside batch_design": a raw Export with a RELATIVE directory is
|
|
772
|
+
// resolved against the DOCUMENT's directory (measured), not the engine's working directory: it lands inside the
|
|
773
|
+
// project, next to the .pen, with none of the adapter's containment or overwrite list applied.
|
|
774
|
+
const docDir = join(workDir, "rel-doc");
|
|
775
|
+
mkdirSync(docDir, { recursive: true });
|
|
776
|
+
const rs = open(["--out", join(docDir, "rel.pen")]);
|
|
777
|
+
await rs.start();
|
|
778
|
+
const mk = await rs.send(buildBatchDesignCommand('var rf=I(document,{type:"frame",layout:"none",width:20,height:20,fill:"#00FF00"});Print("ID:"+rf);'));
|
|
779
|
+
const rid = idOf(mk);
|
|
780
|
+
await rs.send(buildBatchDesignCommand(`Export([${JSON.stringify(rid)}],"png","rel-export-dir")`));
|
|
781
|
+
const underCwd = existsSync(join(cwd, "rel-export-dir")) ? readdirSync(join(cwd, "rel-export-dir")).filter((f) => f.endsWith(".png")) : [];
|
|
782
|
+
const nextToDoc = existsSync(join(docDir, "rel-export-dir")) ? readdirSync(join(docDir, "rel-export-dir")).filter((f) => f.endsWith(".png")) : [];
|
|
783
|
+
record("recipe (steering): raw Export with a relative directory lands", nextToDoc.length ? "next to the document (relative to the .pen's directory)" : underCwd.length ? "under the engine's working directory" : "nowhere found");
|
|
784
|
+
check(nextToDoc.length === 1 && underCwd.length === 0, "pinned engine behaviour: a raw Export with a relative directory is resolved against the document's directory, not the engine's working directory", `nextToDoc=${nextToDoc.join(",") || "nothing"} cwd=${underCwd.join(",") || "nothing"}`);
|
|
785
|
+
await rs.quit();
|
|
786
|
+
}
|
|
787
|
+
|
|
788
|
+
// 12. a file with an unrecognised version, opened via --in: record the engine's answer
|
|
789
|
+
{
|
|
790
|
+
const f = join(workDir, "version.pen");
|
|
791
|
+
const d = JSON.parse(readFileSync(seed, "utf8"));
|
|
792
|
+
d.version = "99.0";
|
|
793
|
+
writeFileSync(f, JSON.stringify(d));
|
|
794
|
+
const before = readFileSync(f);
|
|
795
|
+
{
|
|
796
|
+
// control: the unmodified document loads its three nodes, so a different answer below is the version's doing
|
|
797
|
+
const c = join(workDir, "version-control.pen");
|
|
798
|
+
copyFileSync(seed, c);
|
|
799
|
+
const cs = open(["--out", c, "--in", c]);
|
|
800
|
+
await cs.start();
|
|
801
|
+
const cn = newCountNonce();
|
|
802
|
+
const cr = await cs.send(buildCountCommand(cn));
|
|
803
|
+
await cs.quit();
|
|
804
|
+
check(parseCountReply(cr.all, cn) === 3, "control: an unmodified copy of the seed document loads its 3 top-level nodes", cr.all);
|
|
805
|
+
}
|
|
806
|
+
const s = open(["--out", f, "--in", f]);
|
|
807
|
+
let answer;
|
|
808
|
+
try {
|
|
809
|
+
const started = await s.start();
|
|
810
|
+
if (started) {
|
|
811
|
+
const nonce = newCountNonce();
|
|
812
|
+
const r = await s.send(buildCountCommand(nonce));
|
|
813
|
+
const loadedCount = parseCountReply(r.all, nonce);
|
|
814
|
+
answer = loadedCount === 0 ? "opens EMPTY (0 top-level nodes loaded, no error): the save sentinel is the only guard" : `opens; top-level nodes loaded=${loadedCount}`;
|
|
815
|
+
// an edit on the (possibly empty) document, then idle: the engine must not write the file by itself
|
|
816
|
+
await s.send(buildBatchDesignCommand('I(document,{type:"frame",name:"v-edit",width:20,height:20})'));
|
|
817
|
+
const changed = await watchQuiet([f]);
|
|
818
|
+
check(changed.length === 0 && Buffer.compare(readFileSync(f), before) === 0, `no engine write to the unrecognised-version file in a ${IDLE_WINDOW_MS / 1000} s idle window after an edit (mtime polling)`, changed.join(","));
|
|
819
|
+
} else {
|
|
820
|
+
answer = `exits (code ${s.exit?.code}): ${strip(s.err || s.out).split("\n").find((l) => l.trim()) ?? ""}`;
|
|
821
|
+
}
|
|
822
|
+
} catch (e) {
|
|
823
|
+
answer = `no prompt: ${e.message}`;
|
|
824
|
+
}
|
|
825
|
+
record("--in with an unrecognised document version", answer);
|
|
826
|
+
const PIN_VERSION = "opens-empty";
|
|
827
|
+
const kind = answer.startsWith("opens EMPTY") ? "opens-empty" : answer.startsWith("opens") ? "opens-loaded" : "refuses";
|
|
828
|
+
check(kind === PIN_VERSION, "pinned engine behaviour: unrecognised document version", `observed=${kind}`);
|
|
829
|
+
await s.quit();
|
|
830
|
+
check(Buffer.compare(readFileSync(f), before) === 0, "opening the unrecognised-version file did not rewrite it");
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
// 13. canary credential: does the engine itself echo the credential anywhere? Run in a scratch HOME so
|
|
834
|
+
// every file the engine writes there is listed and scanned, and the real HOME never sees the canary.
|
|
835
|
+
{
|
|
836
|
+
const canary = `CANARY-${randomBytes(12).toString("hex")}`;
|
|
837
|
+
const forms = [canary, Buffer.from(canary).toString("base64"), encodeURIComponent(canary)];
|
|
838
|
+
canaryForms.push(...forms);
|
|
839
|
+
const scratchHome = join(workDir, "canary-home");
|
|
840
|
+
mkdirSync(scratchHome, { recursive: true });
|
|
841
|
+
const f = join(workDir, "canary.pen");
|
|
842
|
+
const s = open(["--out", f], { key: canary, home: scratchHome });
|
|
843
|
+
let text = "";
|
|
844
|
+
try {
|
|
845
|
+
await s.start();
|
|
846
|
+
text += s.startup + s.startupErr;
|
|
847
|
+
const r = await s.send(buildBatchDesignCommand('I(document,{type:"frame",width:10,height:10})'));
|
|
848
|
+
text += r.all;
|
|
849
|
+
const sv = await s.send(buildSaveCommand());
|
|
850
|
+
text += sv.all;
|
|
851
|
+
const g = await s.send("get_app_state()");
|
|
852
|
+
text += g.all;
|
|
853
|
+
} catch (e) {
|
|
854
|
+
text += String(e.message);
|
|
855
|
+
}
|
|
856
|
+
await s.quit();
|
|
857
|
+
const echoed = forms.filter((x) => text.includes(x));
|
|
858
|
+
record("engine echoes a canary credential in its own output (raw/base64/urlencoded)", echoed.length ? `yes (${echoed.length} form(s)): the adapter redactor is load-bearing` : "no");
|
|
859
|
+
const hit = (buf) => forms.filter((x) => buf.includes(x) || buf.includes(Buffer.from(x).toString("latin1")));
|
|
860
|
+
const savedHits = existsSync(f) ? hit(readFileSync(f).toString("latin1")) : [];
|
|
861
|
+
check(existsSync(f) && savedHits.length === 0, "the saved .pen holds no form of the canary credential (bytes scanned)", `forms=${savedHits.length}`);
|
|
862
|
+
const homeFiles = [];
|
|
863
|
+
const walk = (dir, rel = "") => {
|
|
864
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
865
|
+
const r2 = join(rel, e.name);
|
|
866
|
+
if (e.isDirectory()) walk(join(dir, e.name), r2);
|
|
867
|
+
else if (e.isFile()) homeFiles.push(r2);
|
|
868
|
+
}
|
|
869
|
+
};
|
|
870
|
+
walk(scratchHome);
|
|
871
|
+
const homeHits = homeFiles.filter((r2) => { try { return hit(readFileSync(join(scratchHome, r2)).toString("latin1")).length > 0; } catch { return false; } });
|
|
872
|
+
record("files the engine wrote under HOME in a session", homeFiles.length ? `${homeFiles.length}: ${homeFiles.slice(0, 8).join(", ")}` : "none");
|
|
873
|
+
check(homeHits.length === 0, "no file the engine wrote under HOME contains a form of the canary credential", homeHits.join(","));
|
|
874
|
+
const redacted = redact(`x ${canary} y ${forms[1]} z ${forms[2]}`);
|
|
875
|
+
check(forms.every((x) => !redacted.includes(x)), "positive control: this probe's own redactor removes the canary in all three forms");
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// 14. install method: npm ci --ignore-scripts from the committed lockfile yields a working engine
|
|
879
|
+
{
|
|
880
|
+
const ci = join(workDir, "ci-prefix");
|
|
881
|
+
mkdirSync(ci, { recursive: true });
|
|
882
|
+
const lockPath = join(penCliDir, "package-lock.json");
|
|
883
|
+
copyFileSync(join(penCliDir, "package.json"), join(ci, "package.json"));
|
|
884
|
+
copyFileSync(lockPath, join(ci, "package-lock.json"));
|
|
885
|
+
const lock = JSON.parse(readFileSync(lockPath, "utf8"));
|
|
886
|
+
const withScripts = Object.entries(lock.packages ?? {}).filter(([, v]) => v.hasInstallScript).map(([k]) => k.replace(/^.*node_modules\//, ""));
|
|
887
|
+
record("lockfile packages declaring an install script (skipped by --ignore-scripts)", withScripts.length ? withScripts.join(", ") : "none");
|
|
888
|
+
const npmV = spawnSync("npm", ["--version"], { encoding: "utf8" }).stdout.trim();
|
|
889
|
+
const t0 = Date.now();
|
|
890
|
+
// the credential is not in this environment: an install script (if any ran) could not read it
|
|
891
|
+
const inst = spawnSync("npm", ["ci", "--ignore-scripts", "--no-audit", "--no-fund"], {
|
|
892
|
+
cwd: ci, encoding: "utf8", timeout: 300000, env: { PATH: process.env.PATH ?? "", HOME },
|
|
102
893
|
});
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
const
|
|
109
|
-
check(
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
894
|
+
record("install method", `npm ${npmV} ci --ignore-scripts rc=${inst.status} in ${Math.round((Date.now() - t0) / 1000)} s; node ${process.version}`);
|
|
895
|
+
check(inst.status === 0, "npm ci --ignore-scripts from the committed lockfile succeeds", `${inst.stderr}`.slice(-200));
|
|
896
|
+
const sameLock = createHash("sha256").update(readFileSync(lockPath)).digest("hex") === createHash("sha256").update(readFileSync(join(ci, "package-lock.json"))).digest("hex");
|
|
897
|
+
check(sameLock, "npm ci left the lockfile byte-identical");
|
|
898
|
+
const ciBin = join(ci, "node_modules/@pen.dev/cli/dist/index.mjs");
|
|
899
|
+
const ciVer = (() => { try { return JSON.parse(readFileSync(join(ci, "node_modules/@pen.dev/cli/package.json"), "utf8")).version; } catch { return ""; } })();
|
|
900
|
+
check(ciVer === pin, "the --ignore-scripts install holds the pinned engine version", `installed=${ciVer || "unreadable"} pin=${pin}`);
|
|
901
|
+
if (inst.status === 0 && existsSync(ciBin)) {
|
|
902
|
+
const f = join(workDir, "ci-session.pen");
|
|
903
|
+
const s = open(["--out", f], { bin: ciBin });
|
|
904
|
+
await s.start();
|
|
905
|
+
const r = await s.send(buildBatchDesignCommand('I(document,{type:"frame",width:20,height:20})'));
|
|
906
|
+
const sv = await s.send(buildSaveCommand());
|
|
907
|
+
await s.quit();
|
|
908
|
+
check(/^OK\b/.test(r.out) && isSaved(sv, f), "an engine installed with --ignore-scripts starts, applies an edit and saves", `${r.all.slice(0, 80)} | ${sv.all.slice(0, 80)}`);
|
|
909
|
+
const st = spawnSync(process.execPath, [ciBin, "status"], { encoding: "utf8", cwd, env: engineEnv(), timeout: 60000 });
|
|
910
|
+
check(st.status === 0 && /Active/.test(strip(`${st.stdout}\n${st.stderr}`)), "pen status reports Active from the --ignore-scripts install");
|
|
911
|
+
}
|
|
912
|
+
rmSync(ci, { recursive: true, force: true }); // the tree is large: free it before the adapter cases
|
|
114
913
|
}
|
|
115
|
-
let size = 0;
|
|
116
|
-
try { size = statSync(pen).size; } catch {}
|
|
117
|
-
check(size > 96, "saved file is larger than the 96-byte empty document", `size=${size}`);
|
|
118
914
|
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
915
|
+
// ---------------------------------------------------------------------------
|
|
916
|
+
// Adapter cases: the INSTALLED adapter over MCP stdio.
|
|
917
|
+
{
|
|
918
|
+
const { installAdapter, connectAdapter } = await imp(testLib, "pencil-adapter-roundtrip.mjs");
|
|
919
|
+
const installDir = installAdapter(join(workDir, "install"));
|
|
920
|
+
const connect = async (opts = {}) => {
|
|
921
|
+
const { key = KEY, penBinary = penBin, extraEnv = {} } = opts;
|
|
922
|
+
const a = await connectAdapter({ installDir, penBinary, keys: { PEN_CLI_KEY: key }, extraEnv });
|
|
923
|
+
adapters.add(a);
|
|
924
|
+
return a;
|
|
925
|
+
};
|
|
926
|
+
const closeAdapter = async (a) => { await a.close(); adapters.delete(a); };
|
|
927
|
+
const firstLine = (text) => String(text).split("\n")[0];
|
|
928
|
+
const pen = join(workDir, "adapter.pen");
|
|
929
|
+
|
|
930
|
+
// A1. round trip: open, batch_design x2, save, reload, screenshot, export, removed tools
|
|
931
|
+
let a = await connect();
|
|
932
|
+
let nodeId;
|
|
933
|
+
try {
|
|
934
|
+
const o = await a.call("open_document", { filePath: pen });
|
|
935
|
+
check(!o.isError, "adapter: open_document on a new path", o.text);
|
|
936
|
+
const b1 = await a.call("batch_design", { operations: 'f=I(document,{type:"frame",width:200,height:100,fill:"#FFFFFF"})\nt=I(f,{type:"text",content:"probe"})\nPrint("ID:"+f)' });
|
|
937
|
+
check(!b1.isError, "adapter: batch_design with I(...) aliases", b1.text);
|
|
938
|
+
nodeId = /ID:([A-Za-z0-9_-]+)/.exec(b1.text)?.[1];
|
|
939
|
+
const b2 = await a.call("batch_design", { operations: 'g=I(document,{type:"frame",width:50,height:50})' });
|
|
940
|
+
check(!b2.isError, "adapter: second consecutive batch_design", b2.text);
|
|
941
|
+
const sv = await a.call("save");
|
|
942
|
+
check(!sv.isError, "adapter: explicit save", sv.text);
|
|
943
|
+
} finally { await closeAdapter(a); }
|
|
944
|
+
check(statSync(pen).size > 96, "adapter: saved file is larger than the 96-byte empty document");
|
|
945
|
+
a = await connect();
|
|
946
|
+
try {
|
|
947
|
+
const o = await a.call("open_document", { filePath: pen });
|
|
948
|
+
const n = /\((\d+) top-level node/.exec(o.text);
|
|
949
|
+
check(!o.isError && n && Number(n[1]) >= 2, "adapter: reopen in a fresh session loads the saved nodes", o.text);
|
|
950
|
+
const shot = await a.call("get_screenshot", { nodeId });
|
|
951
|
+
check(!shot.isError, "adapter: get_screenshot", shot.text.slice(0, 120));
|
|
952
|
+
const ex = await a.call("export_nodes", { nodeIds: [nodeId], outputDir: join(dirname(pen), "adapter-exports"), format: "png" });
|
|
953
|
+
check(!ex.isError, "adapter: export_nodes", ex.text.slice(0, 120));
|
|
954
|
+
for (const name of REMOVED) {
|
|
955
|
+
const r = await a.call(name, {});
|
|
956
|
+
check(r.isError && r.text.includes(removedToolHint(name)), `adapter: removed tool ${name} answers with its exact hint`, r.text.slice(0, 160));
|
|
957
|
+
}
|
|
958
|
+
} finally { await closeAdapter(a); }
|
|
959
|
+
|
|
960
|
+
// A2. the adapter's DEFAULT binary resolution: HOME is the real prefix, no --pencil-binary flag
|
|
961
|
+
if (USING_OVERRIDE) {
|
|
962
|
+
skip("adapter: default binary resolution", "PROBE_PEN_BINARY is set for this run, so the default prefix is not the engine under test");
|
|
963
|
+
} else {
|
|
964
|
+
const d = join(workDir, "adapter-default.pen");
|
|
965
|
+
a = await connect({ penBinary: "" });
|
|
966
|
+
try {
|
|
967
|
+
const o = await a.call("open_document", { filePath: d });
|
|
968
|
+
const e = await a.call("batch_design", { operations: 'dd=I(document,{type:"frame",width:12,height:12})' });
|
|
969
|
+
const sv = await a.call("save");
|
|
970
|
+
check(!o.isError && !e.isError && !sv.isError && statSync(d).size > 96, "adapter: the default binary resolution (HOME at the real prefix, no override) opens, edits and saves", `${o.text.slice(0, 80)} | ${e.text.slice(0, 80)} | ${sv.text.slice(0, 80)}`);
|
|
971
|
+
check(!/--pencil-binary override in use/.test(a.stderr()), "adapter: the default resolution did not go through the --pencil-binary override", a.stderr().slice(0, 160));
|
|
972
|
+
} finally { await closeAdapter(a); }
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
// A3a. delete-every-node over a non-empty file: refused as `empty`, marker on line 1 of the TOOL RESULT
|
|
976
|
+
const emptied = join(workDir, "adapter-emptied.pen");
|
|
977
|
+
a = await connect();
|
|
978
|
+
try {
|
|
979
|
+
await a.call("open_document", { filePath: emptied });
|
|
980
|
+
const mk = await a.call("batch_design", { operations: 'e1=I(document,{type:"frame",width:10,height:10})\nPrint("ID:"+e1)' });
|
|
981
|
+
const eid = /ID:([A-Za-z0-9_-]+)/.exec(mk.text)?.[1];
|
|
982
|
+
const nodesBefore = JSON.parse(readFileSync(emptied, "utf8")).children?.length;
|
|
983
|
+
const r = await a.call("batch_design", { operations: `D(${JSON.stringify(eid)})` });
|
|
984
|
+
check(r.isError && /^REFUSED save: \[reason=empty\] /.test(firstLine(r.text)), "adapter: deleting every node of a saved file is refused, `REFUSED save: [reason=empty]` is line 1 of the tool result", firstLine(r.text));
|
|
985
|
+
check(nodesBefore === 1 && JSON.parse(readFileSync(emptied, "utf8")).children?.length === 1, "adapter: the `empty` refusal left the saved node on disk", `before=${nodesBefore}`);
|
|
986
|
+
} finally { await closeAdapter(a); }
|
|
987
|
+
|
|
988
|
+
// A3b. a file rewritten behind the session: refused as `stale` (#11168), no engine write afterwards
|
|
989
|
+
const stale = join(workDir, "adapter-stale.pen");
|
|
990
|
+
a = await connect();
|
|
991
|
+
try {
|
|
992
|
+
await a.call("open_document", { filePath: stale });
|
|
993
|
+
await a.call("batch_design", { operations: 'a1=I(document,{type:"frame",width:10,height:10})' });
|
|
994
|
+
copyFileSync(pen, stale);
|
|
995
|
+
const before = readFileSync(stale, "utf8");
|
|
996
|
+
const r = await a.call("batch_design", { operations: 'a2=I(document,{type:"frame",width:11,height:11})' });
|
|
997
|
+
check(r.isError && /^REFUSED save: \[reason=stale\] /.test(firstLine(r.text)), "adapter: a save over a file rewritten behind the session is refused, `REFUSED save: [reason=stale]` is line 1 of the tool result", firstLine(r.text));
|
|
998
|
+
check(readFileSync(stale, "utf8") === before, "adapter: the stale refusal left the file byte-identical");
|
|
999
|
+
const changed = await watchQuiet([stale]);
|
|
1000
|
+
check(changed.length === 0 && readFileSync(stale, "utf8") === before, `adapter: no write to the stale file in a ${IDLE_WINDOW_MS / 1000} s idle window after the refusal (mtime polling)`, changed.join(","));
|
|
1001
|
+
const sv = await a.call("save");
|
|
1002
|
+
check(sv.isError && /^REFUSED save: \[reason=refusal-pending\] /.test(firstLine(sv.text)), "adapter: an explicit save while the refusal is pending is refused as refusal-pending", firstLine(sv.text));
|
|
1003
|
+
} finally { await closeAdapter(a); }
|
|
1004
|
+
|
|
1005
|
+
// A4. a file removed behind a LIVE session is recreated, with the NOTE (ruling 2)
|
|
1006
|
+
const removed = join(workDir, "adapter-removed.pen");
|
|
1007
|
+
a = await connect();
|
|
1008
|
+
try {
|
|
1009
|
+
await a.call("open_document", { filePath: removed });
|
|
1010
|
+
await a.call("batch_design", { operations: 'r1=I(document,{type:"frame",width:10,height:10})' });
|
|
1011
|
+
rmSync(removed);
|
|
1012
|
+
const r = await a.call("batch_design", { operations: 'r2=I(document,{type:"frame",width:11,height:11})' });
|
|
1013
|
+
const back = existsSync(removed) ? JSON.parse(readFileSync(removed, "utf8")).children?.length : 0;
|
|
1014
|
+
check(!r.isError && /had been removed from disk/.test(r.text) && back === 2, "adapter: a file removed behind a live session is recreated from the session with the removal NOTE", `${r.text.slice(0, 160)} children=${back}`);
|
|
1015
|
+
} finally { await closeAdapter(a); }
|
|
1016
|
+
|
|
1017
|
+
// A4b. Export of html over the open document through raw DSL: record what the adapter does (known engine behaviour)
|
|
1018
|
+
{
|
|
1019
|
+
const ow = join(workDir, "adapter-overwrite.pen");
|
|
1020
|
+
a = await connect();
|
|
1021
|
+
try {
|
|
1022
|
+
await a.call("open_document", { filePath: ow });
|
|
1023
|
+
const mk = await a.call("batch_design", { operations: 'o1=I(document,{type:"frame",width:10,height:10,fill:"#00FF00"})\nPrint("ID:"+o1)' });
|
|
1024
|
+
const oid = /ID:([A-Za-z0-9_-]+)/.exec(mk.text)?.[1];
|
|
1025
|
+
const r = await a.call("batch_design", { operations: `Export([${JSON.stringify(oid)}],"html-css",${JSON.stringify(ow)})` });
|
|
1026
|
+
const html = /^<!doctype html>/i.test(readFileSync(ow, "utf8"));
|
|
1027
|
+
record("adapter: raw DSL Export html-css over the open document", `file ${html ? "OVERWRITTEN with html" : "intact"}; result: ${firstLine(r.text).slice(0, 120)}`);
|
|
1028
|
+
check(html === true, "pinned adapter behaviour: a raw-DSL Export html over the open document destroys it (the accepted-residual boundary, reported)", `html=${html}`);
|
|
1029
|
+
const after = await a.call("batch_design", { operations: 'o2=I(document,{type:"frame",width:11,height:11})' });
|
|
1030
|
+
check(after.isError && /^REFUSED save: \[reason=unrecognized\] /.test(firstLine(after.text)), "adapter: the next edit after such an overwrite is refused as `unrecognized` (the overwritten file is never saved over)", firstLine(after.text));
|
|
1031
|
+
} finally { await closeAdapter(a); }
|
|
1032
|
+
}
|
|
1033
|
+
|
|
1034
|
+
// A5. unrecognised version via open_document: load fidelity (ruling 6) refuses it, nothing is modified
|
|
1035
|
+
{
|
|
1036
|
+
const vf = join(workDir, "adapter-version.pen");
|
|
1037
|
+
const d = JSON.parse(readFileSync(seed, "utf8")); d.version = "99.0"; writeFileSync(vf, JSON.stringify(d));
|
|
1038
|
+
const before = readFileSync(vf);
|
|
1039
|
+
a = await connect();
|
|
1040
|
+
try {
|
|
1041
|
+
const o = await a.call("open_document", { filePath: vf });
|
|
1042
|
+
record("adapter open_document on an unrecognised document version", `${o.isError ? "isError" : "ok"}: ${o.text.slice(0, 160)}`);
|
|
1043
|
+
check(o.isError && /top-level node\(s\) on disk but loaded empty/.test(o.text), "adapter: open_document refuses a file the engine loads with fewer top-level nodes (load fidelity)", o.text.slice(0, 160));
|
|
1044
|
+
check(Buffer.compare(readFileSync(vf), before) === 0, "adapter: the refused open did not modify the file");
|
|
1045
|
+
} finally { await closeAdapter(a); }
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
// A6. canary credential through the adapter: stderr and every tool result carry no form of it
|
|
1049
|
+
{
|
|
1050
|
+
const canary = `CANARY-${randomBytes(12).toString("hex")}`;
|
|
1051
|
+
const forms = [canary, Buffer.from(canary).toString("base64"), encodeURIComponent(canary)];
|
|
1052
|
+
canaryForms.push(...forms);
|
|
1053
|
+
const cf = join(workDir, "adapter-canary.pen");
|
|
1054
|
+
a = await connect({ key: canary });
|
|
1055
|
+
let seen = "";
|
|
1056
|
+
try {
|
|
1057
|
+
for (const [tool, args] of [["open_document", { filePath: cf }], ["batch_design", { operations: 'c1=I(document,{type:"frame",width:9,height:9})' }], ["get_editor_state", {}], ["save", {}]]) {
|
|
1058
|
+
const r = await a.call(tool, args); seen += r.text;
|
|
1059
|
+
}
|
|
1060
|
+
} finally { await closeAdapter(a); }
|
|
1061
|
+
seen += a.stderr();
|
|
1062
|
+
check(forms.every((x) => !seen.includes(x)), "adapter: a canary credential appears nowhere in adapter stderr or any tool result (raw, base64, urlencoded)");
|
|
1063
|
+
const fileHits = existsSync(cf) ? forms.filter((x) => readFileSync(cf).toString("latin1").includes(x)) : [];
|
|
1064
|
+
check(existsSync(cf) && fileHits.length === 0, "adapter: the saved .pen holds no form of the canary credential");
|
|
1065
|
+
}
|
|
1066
|
+
|
|
1067
|
+
// A7. load fidelity acceptance (ruling 6): every committed design .pen loads with >= its top-level nodes
|
|
1068
|
+
{
|
|
1069
|
+
const env = Object.fromEntries(Object.entries(process.env).filter(([k]) => !k.startsWith("GIT_")));
|
|
1070
|
+
const ls = spawnSync("git", ["-C", repoRoot, "ls-files", "-z", "--", "knowledge-base/product/design"], { encoding: "utf8", env });
|
|
1071
|
+
if (ls.status !== 0) throw new Error(`git ls-files failed: ${String(ls.stderr).slice(0, 120)}`);
|
|
1072
|
+
const files = ls.stdout.split("\0").filter((x) => x.endsWith(".pen")).sort();
|
|
1073
|
+
check(files.length >= 50, "acceptance: the committed design .pen set was enumerated", `count=${files.length}`);
|
|
1074
|
+
const accept = join(workDir, "accept");
|
|
1075
|
+
mkdirSync(accept, { recursive: true });
|
|
1076
|
+
const rows = [];
|
|
1077
|
+
const queue = files.map((rel, i) => ({ rel, i }));
|
|
1078
|
+
const worker = async () => {
|
|
1079
|
+
const ad = await connect();
|
|
1080
|
+
try {
|
|
1081
|
+
for (let job = queue.shift(); job; job = queue.shift()) {
|
|
1082
|
+
const { rel, i } = job;
|
|
1083
|
+
const bytes = readFileSync(join(repoRoot, rel));
|
|
1084
|
+
let disk = null;
|
|
1085
|
+
try { const c = JSON.parse(bytes.toString("utf8"))?.children; if (Array.isArray(c)) disk = c.length; } catch { /* not a valid document */ }
|
|
1086
|
+
const copy = join(accept, `${String(i).padStart(3, "0")}-${basename(rel)}`);
|
|
1087
|
+
writeFileSync(copy, bytes);
|
|
1088
|
+
const o = await ad.call("open_document", { filePath: copy });
|
|
1089
|
+
const m = /\((\d+|unknown) top-level node\(s\) loaded\)/.exec(o.text);
|
|
1090
|
+
rows.push({ rel, disk, loaded: m ? (m[1] === "unknown" ? null : Number(m[1])) : null, isError: o.isError, text: o.text, intact: Buffer.compare(readFileSync(copy), bytes) === 0 });
|
|
1091
|
+
}
|
|
1092
|
+
} finally { await closeAdapter(ad); }
|
|
1093
|
+
};
|
|
1094
|
+
const t0 = Date.now();
|
|
1095
|
+
await Promise.all(Array.from({ length: 6 }, worker));
|
|
1096
|
+
rows.sort((x, y) => x.rel.localeCompare(y.rel));
|
|
1097
|
+
// hyphens become spaces in the recorded name: a long hyphenated path with digits reads as a key to the transcript scanner
|
|
1098
|
+
const label = (rel) => rel.replace("knowledge-base/product/design/", "").replace(/[-/]/g, " ");
|
|
1099
|
+
for (const r of rows) record(`acceptance ${label(r.rel)}`, `disk=${r.disk ?? "invalid"} loaded=${r.loaded ?? (r.isError ? "REFUSED" : "unknown")}`);
|
|
1100
|
+
const valid = rows.filter((r) => r.disk !== null);
|
|
1101
|
+
// A file the engine refuses to open at all is not a silent drop (the adapter reports `open failed:` and
|
|
1102
|
+
// runs nothing); it is recorded loudly and pinned. A file that LOADS with fewer nodes is the ruling-6 risk.
|
|
1103
|
+
const refused = valid.filter((r) => r.isError);
|
|
1104
|
+
const fewer = valid.filter((r) => !r.isError && (r.loaded === null || r.loaded < r.disk));
|
|
1105
|
+
for (const r of refused) record(`acceptance REFUSED ${label(r.rel)}`, r.text.split(/ at [A-Za-z_$]/)[0]);
|
|
1106
|
+
record("load-fidelity acceptance summary", `${rows.length} committed design .pen files, ${valid.length} parse as documents, ${valid.length - refused.length - fewer.length} load faithfully, ${refused.length} refused by the engine, ${fewer.length} load with fewer top-level nodes, ${Math.round((Date.now() - t0) / 1000)} s`);
|
|
1107
|
+
check(rows.length === files.length, "acceptance: every committed file was evaluated", `evaluated=${rows.length} of ${files.length}`);
|
|
1108
|
+
check(fewer.length === 0, "acceptance (ruling 6): no committed design .pen loads with fewer top-level nodes than on disk", fewer.map((r) => `${r.rel}:${r.disk}->${r.loaded ?? "unknown"}`).join(" "));
|
|
1109
|
+
// pinned: committed files whose content the engine rejects outright (schema-invalid, for example a node type that is not a node type).
|
|
1110
|
+
// A repaired file must leave this list; a new rejection fails here instead of passing silently.
|
|
1111
|
+
// Empty since dashboard/dashboard-load-states.pen was repaired ("rect" -> "rectangle", PR #11225).
|
|
1112
|
+
const PINNED_ENGINE_REJECTS = [];
|
|
1113
|
+
const gotRejects = refused.map((r) => r.rel).sort();
|
|
1114
|
+
check(JSON.stringify(gotRejects) === JSON.stringify(PINNED_ENGINE_REJECTS), "acceptance: the committed files the engine refuses to open are exactly the pinned set", `observed=${gotRejects.join(",") || "none"}`);
|
|
1115
|
+
check(rows.every((r) => r.intact), "acceptance: opening every file left every copy byte-identical", rows.filter((r) => !r.intact).map((r) => r.rel).join(","));
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
130
1118
|
}
|
|
131
|
-
const doc = JSON.parse(readFileSync(pen, "utf8"));
|
|
132
|
-
check(Array.isArray(doc.children) && doc.children.length >= 2, "on-disk document keeps its children", JSON.stringify(doc).slice(0, 200));
|
|
133
1119
|
|
|
134
|
-
//
|
|
135
|
-
//
|
|
136
|
-
|
|
137
|
-
a = await connectAdapter({ installDir, binary: pencilBin, key: process.env.PENCIL_CLI_KEY });
|
|
1120
|
+
// ---------------------------------------------------------------------------
|
|
1121
|
+
// Run, then always release every child; a tooling error is a verdict, not a stack trace.
|
|
1122
|
+
let verdict = null;
|
|
138
1123
|
try {
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
const r = await a.call("batch_design", { operations: ops });
|
|
144
|
-
check(!r.isError, "batch_design inserting 140 frames with long names", r.text);
|
|
145
|
-
const g = await a.call("batch_design", { operations: 'extra=I(document,{type:"frame",width:5,height:5})' });
|
|
146
|
-
check(!g.isError, "a second edit over a non-empty file is allowed by the sentinel", g.text);
|
|
1124
|
+
await runCases();
|
|
1125
|
+
} catch (e) {
|
|
1126
|
+
if (e instanceof ProbeStop) verdict = { code: e.code, line: e.verdict };
|
|
1127
|
+
else verdict = { code: failures > 0 ? 1 : 3, line: `PROBE TOOLING ERROR (nothing further was asserted): ${redact(String(e?.message ?? e)).replace(/\s+/g, " ").slice(0, 300)}` };
|
|
147
1128
|
} finally {
|
|
148
|
-
await
|
|
1129
|
+
await finish();
|
|
149
1130
|
}
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
const o = await a.call("open_document", { filePath: big });
|
|
156
|
-
const n = /\((\d+) top-level node/.exec(o.text);
|
|
157
|
-
check(!o.isError && n && Number(n[1]) >= 140, "the large design reopens with its nodes", o.text);
|
|
158
|
-
} finally {
|
|
159
|
-
await a.close();
|
|
1131
|
+
if (verdict) {
|
|
1132
|
+
// A check that already FAILED must not be hidden behind a tooling error: the failure count comes first.
|
|
1133
|
+
if (failures > 0 && !verdict.line.startsWith("PROBE FAILED")) console.log(`PROBE FAILED (${failures})`);
|
|
1134
|
+
emit(verdict.line);
|
|
1135
|
+
process.exit(verdict.code);
|
|
160
1136
|
}
|
|
161
1137
|
|
|
162
|
-
//
|
|
163
|
-
//
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
1138
|
+
// ---------------------------------------------------------------------------
|
|
1139
|
+
// Redacted transcript.
|
|
1140
|
+
let leaked = false;
|
|
1141
|
+
if (transcriptPath) {
|
|
1142
|
+
const header = [
|
|
1143
|
+
`# Engine contract probe transcript`,
|
|
1144
|
+
``,
|
|
1145
|
+
`engine: @pen.dev/cli@${pin} probed ${new Date().toISOString().slice(0, 10)}`,
|
|
1146
|
+
`scope: engine and adapter cases${skipped.length ? ` (skipped: ${skipped.join("; ")})` : ""}`,
|
|
1147
|
+
`result: ${failures === 0 ? "all cases passed" : `${failures} case(s) FAILED`} (${nPass} passed)`,
|
|
1148
|
+
``,
|
|
1149
|
+
"Credential, `$HOME`, absolute paths, UUIDs (including a document `fileToken`) and account lines are scrubbed by `plugins/soleur/test/lib/scrub-transcript.mjs`; `pen status` output is never recorded.",
|
|
1150
|
+
``,
|
|
1151
|
+
"```text",
|
|
1152
|
+
].join("\n");
|
|
1153
|
+
const body = scrub.scrubTranscript(LOG.join("\n"), {
|
|
1154
|
+
secrets: [KEY, ...canaryForms],
|
|
1155
|
+
paths: [[realpathSync(workDir), "<WORK>"], [workDir, "<WORK>"], [HOME, "<HOME>"]],
|
|
1156
|
+
});
|
|
1157
|
+
const text = `${header}\n${body}\n\`\`\`\n`;
|
|
1158
|
+
const leaks = scrub.findLeaks(text, { secrets: [KEY] });
|
|
1159
|
+
mkdirSync(dirname(transcriptPath), { recursive: true });
|
|
1160
|
+
const tmp = join(workDir, "transcript.md");
|
|
1161
|
+
writeFileSync(tmp, text);
|
|
1162
|
+
const g = scrub.gitleaksFindings(tmp);
|
|
1163
|
+
if (leaks.length > 0 || !g.ok) {
|
|
1164
|
+
leaked = true;
|
|
1165
|
+
console.log(`FAIL transcript not written: ${leaks.length} leak(s) (${leaks.slice(0, 3).map((l) => (l.startsWith("key-shaped") ? l.slice(0, 22) : l.split(":")[0])).join(",")}) gitleaks=${g.ok ? "clean" : g.missing ? "missing" : "finding"}`);
|
|
1166
|
+
} else {
|
|
1167
|
+
writeFileSync(transcriptPath, text);
|
|
1168
|
+
console.log(`transcript written: ${transcriptPath.replace(HOME, "~")}`);
|
|
1169
|
+
}
|
|
179
1170
|
}
|
|
180
1171
|
|
|
181
|
-
|
|
182
|
-
|
|
1172
|
+
if (failures > 0 || leaked) {
|
|
1173
|
+
console.log(`PROBE FAILED (${failures + (leaked ? 1 : 0)})`);
|
|
1174
|
+
process.exit(1);
|
|
1175
|
+
}
|
|
1176
|
+
if (skipped.length > 0) {
|
|
1177
|
+
console.log(`PROBE INCOMPLETE (${skipped.length} case(s) skipped: ${skipped.join("; ")}); this is NOT a PROBE OK`);
|
|
1178
|
+
process.exit(3);
|
|
1179
|
+
}
|
|
1180
|
+
console.log("PROBE OK");
|
|
1181
|
+
process.exit(0);
|
|
183
1182
|
NODE
|
|
184
1183
|
|
|
185
|
-
node "$work/probe.mjs" "$SCRIPT_DIR" "$SCRIPT_DIR/../../../test/lib" "$work" "$PENCIL_BIN"
|
|
1184
|
+
PROBE_CRED="$KEY" node "$work/probe.mjs" "$SCRIPT_DIR" "$SCRIPT_DIR/../../../test/lib" "$work" "$PENCIL_BIN" "$PIN" "$TRANSCRIPT_PATH" "$SCRIPT_DIR/pen-cli" "$REPO_ROOT" "$OVERRIDE"
|
|
186
1185
|
rc=$?
|
|
187
1186
|
exit "$rc"
|