@sedum-dev/core 0.1.0-alpha.0 → 0.1.0-alpha.10

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/README.md CHANGED
@@ -1,43 +1,43 @@
1
1
  # Core browser observation boundary
2
2
 
3
- ## Flow format boundary (SED-27)
3
+ ## Test file parsing
4
4
 
5
- `parseFlow(source, file, { repoRoot })` parses one `*.test.yaml` definition with the `yaml` document AST and a strict v1 schema. `validateFlows` also detects duplicate explicit ids across files. Neither reads environment variables, opens a browser, calls a provider, nor changes the classification cache. A missing `sedum` marker means v1; `sedum: 1` is optional. Diagnostics include `file:line:col`, a code, and a suggested fix. `discoverFlowFiles` recursively finds sorted `*.test.yaml` paths; `loadFlowFile` is the filesystem edge.
5
+ `parseFlow(source, file, { repoRoot })` parses one `*.test.yaml` definition with the `yaml` document AST and a strict schema for format version 1. `validateFlows` also detects duplicate explicit ids across files. Neither reads environment variables, opens a browser, calls a provider, nor changes the classification cache. A missing `sedum` marker means format version 1; `sedum: 1` is optional. Diagnostics include `file:line:col`, a code, and a suggested fix. `discoverFlowFiles` recursively finds sorted `*.test.yaml` paths; `loadFlowFile` is the filesystem edge.
6
6
 
7
- The typed definition retains original sentence text, declared `data`, and AST positions. `resolveData(declared, env)` is a separate runtime operation. It supports `$VAR`, `${VAR}`, and `$$` and returns `RuntimeValue` instances with secret provenance. Env-sourced data stays opaque in logs and JSON; only the executor should call `reveal()`. `tokenizeStep` preserves placeholder and quoted-literal spans. After SED-28 classifies a sentence as `type`, it must call `validateTypeOperand` before the step can be considered checked or executed; `resolveTypeOperand` gives the executor an opaque value. The model receives the source sentence with placeholder names, never substituted data values.
7
+ The typed definition retains original sentence text, declared `data`, and AST positions. `resolveData(declared, env)` is a separate runtime operation. It supports `$VAR`, `${VAR}`, and `$$` and returns `RuntimeValue` instances with secret provenance. Env-sourced data stays opaque in logs and JSON; only the executor should call `reveal()`. `tokenizeStep` preserves placeholder and quoted-literal spans. After classification identifies a sentence as `type`, the caller must call `validateTypeOperand` before the step can be considered checked or executed; `resolveTypeOperand` gives the executor an opaque value. The model receives the source sentence with placeholder names, never substituted data values.
8
8
 
9
- ## Walking-skeleton runner (SED-19)
9
+ ## Runner
10
10
 
11
11
  `runFlow(file, dependencies)` is the narrow composition boundary behind `sedum
12
12
  run <file.test.yaml>`. It accepts injected browser, provider, classification
13
13
  cache, environment, and repository-root dependencies; it does not read process
14
- state or expose SDK/Playwright types. The initial slice supports a flow URL and
15
- ordinary `steps` classified as `type`, `click`, and `verify`. A failed verify
14
+ state or expose SDK/Playwright types. It opens the flow URL and runs the classified
15
+ steps. A failed verify
16
16
  is a test failure; invalid data, browser/provider/locator/action failures, and
17
- unsupported operations are `could_not_run`. The SED-29 lifecycle executes
17
+ unsupported operations are `could_not_run`. The runner executes
18
18
  `before`, conditional `steps`, and exhaustive `after` within one browser
19
19
  context. Reusable modules are validated as a complete contained graph before
20
20
  classification and browser launch. Their arguments resolve lazily in an
21
21
  attempt-local scope. Runtime values remain opaque outside the executor.
22
22
 
23
- The loader reports `format` coverage and leaves `steps: not_checked`. `resolveFlowModules` resolves every reachable `use`, checks exact parameter bindings, canonical containment, cycles, and depth, then marks modules `checked` or `incomplete`. `classifyParsedFlow` classifies every expanded sentence, validates type operands, and marks steps checked only when the whole graph succeeds. SED-37's `sedum validate` can compose those checks through `isFullyValidated`; a format-only check never claims full validation. The public format and hook contract are described in [docs/format.md](../../docs/format.md).
23
+ The loader reports `format` coverage and leaves `steps: not_checked`. `resolveFlowModules` resolves every reachable `use`, checks exact parameter bindings, canonical containment, cycles, and depth, then marks modules `checked` or `incomplete`. `classifyParsedFlow` classifies every expanded sentence, validates type operands, and marks steps checked only when the whole graph succeeds. `sedum validate` composes those checks through `isFullyValidated`; a format-only check never claims full validation. The public format and hook contract are described in [docs/format.md](../../docs/format.md).
24
24
 
25
25
  Build `@sedum-dev/core` before launching the Playwright driver. The package ships `./page-script.js` as a browser-only IIFE; `PlaywrightBrowserDriver` installs it as a context init script before pages are created. A missing asset produces `script-missing`; a missing or incompatible bridge produces `PageScriptError`.
26
26
 
27
- The versioned `window.__sedum` protocol exposes `collect`, `digest`, `pageVersion`, `quiet`, `findBySignals`, `clickTarget`, `checkAim`, and `clearRefs`. Use the typed functions exported from `@sedum-dev/core` rather than calling the global directly. A collection has a document/route/revision version, total count, and a continuation offset. An incomplete collection is not evidence of absence or a unique cache match. `findBySignals` rescans all eligible candidates; it does not pass an HMAC key into the page. Every rescan invalidates earlier refs. `quiet` reports an observation interval, not final page completion.
27
+ The versioned `window.__sedum` protocol exposes `collect`, `digest`, `visibleText`, `pageVersion`, `quiet`, `findBySignals`, `clickTarget`, `readTarget`, `controlState`, `checkAim`, `hoverElement`, and `clearRefs`. Use the typed functions exported from `@sedum-dev/core` rather than calling the global directly. A collection has a document/route/revision version, total count, and a continuation offset. An incomplete collection is not evidence of absence or a unique cache match. `findBySignals` rescans all eligible candidates; it does not pass an HMAC key into the page. Every rescan invalidates earlier refs. `quiet` reports an observation interval, not final page completion. `visibleText` uses the same readable-text projection as `digest` without its provider size limit; deterministic exact-text checks consume it locally.
28
28
 
29
- `projectCandidates` and `projectDigest` are the SED-12 provider boundary: they only admit the approved fields and reject over-limit or incomplete content. The later provider adapter must enforce the 512-code-point sentence/claim limits and the 64-KiB UTF-8 serialized request limit immediately before the SDK call. Allowed visible text, including secret-looking text, is sent unchanged; do not describe this projection as redaction. Never include internal candidate signals, page versions/routes, selectors, editable values, or raw HTML in a provider request.
29
+ `projectCandidates` and `projectDigest` are the provider boundary: they only admit the approved fields and reject over-limit or incomplete content. The provider adapter must enforce the 512-code-point sentence/claim limits and the 64-KiB UTF-8 serialized request limit immediately before the SDK call. Allowed visible text, including secret-looking text, is sent unchanged; do not describe this projection as redaction. Never include internal candidate signals, page versions/routes, selectors, editable values, or raw HTML in a provider request.
30
30
 
31
- `stageEntry`, `pageKey`, and `matchLiveEntry` supply SED-14's transient cache-signal contract. The checkout key is supplied by the later CacheStore implementation; it must be a random 256-bit secret stored in worktree-resolved Git metadata, never in the page script or a provider payload. `stageEntry` requires the complete eligible candidate set, complete bounded item context with a target-specific word, and a unique match. It refuses caching when that evidence is unavailable, even if the page supplies a hook or ID. Call it only after a successful action. Store only `CacheEntry`'s keyed digests and bounded metadata. No entry is a hit until all current eligible candidates are checked. A hit still requires a fresh `clickTarget` aim and `BrowserPage.clickRef` action; a miss remains visible to the caller. `clickRef` asks Playwright to settle the exact snapshot target without dispatching pointer events, revalidates it after that wait, then delegates actionability, event dispatch, cancellation, and same-frame HTTP(S) navigation to Playwright and the browser. Sedum does not hold or replay a link's default action, and page code may change the result of a native click just as it can for a user. Download, new-tab, and non-HTTP(S) links remain non-actionable because they are outside the current single-page driver contract. A `clickRef` result with `reason: "action_started"` and `retryable: false` means the final click was handed to Playwright but failed, so a page handler may already have caused an effect and the executor must not repeat it automatically. SED-24 owns persistence and post-success staging, SED-23 the provider paging/ranking strategy, SED-26 action orchestration, and SED-65 observation retries.
31
+ `stageEntry`, `pageKey`, and `matchLiveEntry` supply the transient cache-signal contract. The checkout key is supplied by the cache store; it must be a random 256-bit secret stored in worktree-resolved Git metadata, never in the page script or a provider payload. `stageEntry` requires the complete eligible candidate set, complete bounded item context with a target-specific word, and a unique match. It refuses caching when that evidence is unavailable, even if the page supplies a hook or ID. Call it only after a successful action. Store only `CacheEntry`'s keyed digests and bounded metadata. No entry is a hit until all current eligible candidates are checked. A hit still requires a fresh `clickTarget` aim and `BrowserPage.clickRef` action; a miss remains visible to the caller. `clickRef` asks Playwright to settle the exact snapshot target without dispatching pointer events, revalidates it after that wait, then delegates actionability, event dispatch, cancellation, and same-frame HTTP(S) navigation to Playwright and the browser. For a CSS-hover-revealed target, discovery only inspects stylesheet rules whose winning author declarations it can prove; `clickRef` retrieves and hovers the exact snapshot host, waits for the exact target, and revalidates it before clicking. Once hover pointer dispatch starts, any failure is non-retryable because a page handler may already have caused an effect. Sedum does not hold or replay a link's default action, and page code may change the result of a native click just as it can for a user. Download, new-tab, and non-HTTP(S) links remain non-actionable because they are outside the current single-page driver contract. A `clickRef` result with `reason: "action_started"` and `retryable: false` means pointer or click dispatch started but did not safely complete, so the executor must not repeat it automatically.
32
32
 
33
- `executeStep` is SED-26's narrow action boundary. It takes a classified operation and a snapshot-scoped target from the later resolver; it never classifies or re-resolves itself. `type` replaces text with Playwright `fill` on the exact element from a `fill` candidate snapshot, while click reuses PR #2's aim and `clickRef`. Press is page-level and scroll emits one vertical wheel event. A stale target or failed pre-dispatch action is retryable; once browser dispatch may have begun, failure is non-retryable. A click or press compares the immediate page version and settles only a change already observed. SED-65 owns delayed content, fresh observation, and whole-test retry policy. Keep substituted values in `RuntimeValue`/`RuntimeUrl` and route-bearing targets in `ResolvedStepTarget` rather than interpolating them into a command sentence or literal URL; only trusted URL segments and placeholder labels are displayable. Public executor results and errors contain no raw runtime value, full route, Playwright cause, or stack. `goto` uses the driver's safe-diagnostics option, and all uncertain Playwright call-log lines are replaced wholesale.
33
+ `executeStep` is the narrow action boundary. It takes a classified operation and a snapshot-scoped target from the resolver; it never classifies or re-resolves itself. `type` replaces text with Playwright `fill` on the exact element from a `fill` candidate snapshot, while click reuses the `clickTarget` aim and `clickRef`. Press is page-level and scroll emits one vertical wheel event. A stale target or failed pre-dispatch action is retryable; once browser dispatch may have begun, failure is non-retryable. A click or press compares the immediate page version and settles only a change already observed. Keep substituted values in `RuntimeValue`/`RuntimeUrl` and route-bearing targets in `ResolvedStepTarget` rather than interpolating them into a command sentence or literal URL; only trusted URL segments and placeholder labels are displayable. Public executor results and errors contain no raw runtime value, full route, Playwright cause, or stack. `goto` uses the driver's safe-diagnostics option, and all uncertain Playwright call-log lines are replaced wholesale.
34
34
 
35
35
  ## Sentence locator
36
36
 
37
- `resolveTarget(page, resolver, { operation, sentence, signal?, timeoutMs? })` accepts `click`, `fill`, or `read` and returns either a `ResolvedStepTarget` or a typed unresolved reason. It performs no browser action. The caller passes its remaining step deadline; SED-65 decides when to retry a stale or incomplete observation. The locator follows every 128-candidate cursor page, requires one stable document/route/revision and an exact total, and stops above 4,096 candidates. Fill first scans only enabled text inputs, textareas, and contenteditable controls that `fillRef` can execute. If that set is empty, a complete click scan supplies diagnostic candidates; a selected label or nonfillable control returns `not_fillable` and is never handed to the fill executor.
37
+ `resolveTarget(page, resolver, { operation, sentence, signal?, timeoutMs? })` accepts `click`, `fill`, or `read` and returns either a `ResolvedStepTarget` or a typed unresolved reason. It performs no browser action. The caller passes its remaining step deadline and decides when to retry a stale or incomplete observation. The locator follows every 128-candidate cursor page, requires one stable document/route/revision and an exact total, and stops above 4,096 candidates. Fill first scans only enabled text inputs, textareas, and contenteditable controls that `fillRef` can execute. If that set is empty, a complete click scan supplies diagnostic candidates; a selected label or nonfillable control returns `not_fillable` and is never handed to the fill executor.
38
38
 
39
- Every model Choice includes `none`. Sets larger than 128 are divided into bounded heats; each heat retains its top two non-`none` candidates, including when `none` wins. The locator repeats bounded heats until one final Choice fits, including when valid long Unicode candidate text makes the finalist set too large for one request. Scores from separate heats are never compared. The model request contains only SED-12's approved candidate fields. An over-limit name or peer excerpt returns `request_too_large` before any model call; candidate text is never silently clipped. The adapter remains the final 64-KiB request-size authority.
39
+ Every model Choice includes `none`. Sets larger than 128 are divided into bounded heats; each heat retains its top two non-`none` candidates, including when `none` wins. The locator repeats bounded heats until one final Choice fits, including when valid long Unicode candidate text makes the finalist set too large for one request. Scores from separate heats are never compared. The model request contains only the approved candidate fields. An over-limit name or peer excerpt returns `request_too_large` before any model call; candidate text is never silently clipped. The adapter remains the final 64-KiB request-size authority.
40
40
 
41
- A selected candidate must clear the confidence and probability-margin gate. Repeated labels or destinations require a distinguishing candidate name or peer phrase in the sentence even when model confidence is high; a generic category or control word alone cannot establish identity. A first-story rank combined with a uniquely matching link purpose can distinguish repeated story links. Low-confidence groups get at most one narrower Choice. Explicit “article body” and “first story” requests require local region/rank evidence even when model confidence is high. After the decision, a full rescan must identify exactly one equivalent live target on the same document and route; a changed route, incomplete scan, or duplicate match returns stale. SED-26 rechecks the returned exact snapshot target immediately before action and never replays an uncertain action. Diagnostics expose only a bounded top-four name/role/probability list, gate reason, candidate count, round count, and provider call metadata; they omit routes, selectors, DOM signals, request bodies, and input values. SED-24 owns cache persistence and SED-39 owns result persistence.
41
+ A selected candidate must clear the confidence and probability-margin gate. Repeated labels or destinations require a distinguishing candidate name or peer phrase in the sentence even when model confidence is high; a generic category or control word alone cannot establish identity. A first-story rank combined with a uniquely matching link purpose can distinguish repeated story links. Low-confidence groups get at most one narrower Choice. Explicit “article body” and “first story” requests require local region/rank evidence even when model confidence is high. After the decision, a full rescan must identify exactly one equivalent live target on the same document and route; a changed route, incomplete scan, or duplicate match returns stale. The executor rechecks the returned exact snapshot target immediately before action and never replays an uncertain action. Diagnostics expose only a bounded top-four name/role/probability list, gate reason, candidate count, round count, and provider call metadata; they omit routes, selectors, DOM signals, request bodies, and input values.
42
42
 
43
- The recorded locator tests run in normal CI. After `pnpm build`, run browser fixtures with `SEDUM_BROWSER_INTEGRATION=1 pnpm exec vitest run packages/core/src/page-script.integration.test.ts`. The optional live target suite uses `SEDUM_LOCATOR_LIVE=1` and `TYPESAFE_API_KEY` to check Saucedemo login and Hacker News with real model calls, and strict candidate-text rejection on Saucedemo's product page and Wikipedia's current Ada Lovelace page. The Wikipedia page currently has over-limit citation text and several indistinguishable article-body Charles Babbage links, so the original PoC sentence is not an actionable target under this contract. The suite prints bounded target and usage evidence without printing the key.
43
+ The recorded locator tests run in normal CI. After `pnpm build`, run browser fixtures with `SEDUM_BROWSER_INTEGRATION=1 pnpm exec vitest run packages/core/src/page-script.integration.test.ts`. The optional live target suite uses `SEDUM_LOCATOR_LIVE=1` and `TYPESAFE_API_KEY` to check Saucedemo login and Hacker News with real model calls, and strict candidate-text rejection on Saucedemo's product page and Wikipedia's current Ada Lovelace page. The Wikipedia page currently has over-limit citation text and several indistinguishable article-body Charles Babbage links, so a sentence naming one of those links is not an actionable target. The suite prints bounded target and usage evidence without printing the key.
@@ -0,0 +1,100 @@
1
+ // src/script-registry.ts
2
+ import { realpathSync } from "fs";
3
+ import path from "path";
4
+ import { fileURLToPath } from "url";
5
+ import { inspect } from "util";
6
+ var REGISTRY = /* @__PURE__ */ Symbol.for("sedum.script.registry");
7
+ var SECRET = /* @__PURE__ */ Symbol.for("sedum.script.secret");
8
+ var Secret = class {
9
+ #value;
10
+ [SECRET];
11
+ constructor(value) {
12
+ this.#value = value;
13
+ this[SECRET] = () => this.#value;
14
+ }
15
+ toString() {
16
+ return "[secret]";
17
+ }
18
+ toJSON() {
19
+ return "[secret]";
20
+ }
21
+ [inspect.custom]() {
22
+ return "[secret]";
23
+ }
24
+ };
25
+ function secret(value) {
26
+ if (typeof value !== "string")
27
+ throw new TypeError("secret() takes a string value.");
28
+ return new Secret(value);
29
+ }
30
+ function isSecret(value) {
31
+ return typeof value === "object" && value !== null && typeof value[SECRET] === "function";
32
+ }
33
+ function revealSecret(value) {
34
+ return value[SECRET]();
35
+ }
36
+ function scriptRegistry() {
37
+ const holder = globalThis;
38
+ return holder[REGISTRY] ??= { pending: [] };
39
+ }
40
+ function test(title, optionsOrBody, maybeBody) {
41
+ const body = typeof optionsOrBody === "function" ? optionsOrBody : maybeBody;
42
+ const options = typeof optionsOrBody === "function" ? {} : optionsOrBody;
43
+ scriptRegistry().pending.push({
44
+ title,
45
+ options: options ?? {},
46
+ body,
47
+ callSite: testFileFrame(new Error().stack)
48
+ });
49
+ }
50
+ var TOP_LEVEL = /^\s*at (?:async )?(?:Object\.<anonymous> \()?(?:file:\/\/)?[^()\s][^()]*:\d+:\d+\)?\s*$/u;
51
+ function testFileFrame(stack) {
52
+ const frames = stack?.split("\n").slice(2) ?? [];
53
+ const inTests = frames.filter(
54
+ (frame) => parseFrame(frame)?.file.endsWith(".test.ts")
55
+ );
56
+ return inTests.find((frame) => TOP_LEVEL.test(frame)) ?? inTests[0] ?? frames[0];
57
+ }
58
+ function parseFrame(frame) {
59
+ const match = /(?:\(|at\s)([^()\s][^()]*?):(\d+):(\d+)\)?\s*$/u.exec(
60
+ frame.trim()
61
+ );
62
+ if (!match) return void 0;
63
+ let file = match[1];
64
+ if (file.startsWith("file://"))
65
+ try {
66
+ file = fileURLToPath(file);
67
+ } catch {
68
+ }
69
+ return { file, line: Number(match[2]), col: Number(match[3]) };
70
+ }
71
+ function pathKey(file) {
72
+ let resolved = path.resolve(file);
73
+ try {
74
+ resolved = realpathSync.native(resolved);
75
+ } catch {
76
+ }
77
+ return process.platform === "win32" ? resolved.toLowerCase() : resolved;
78
+ }
79
+ function samePath(a, b) {
80
+ return a === b || pathKey(a) === pathKey(b);
81
+ }
82
+ function sourceInFile(stack, file) {
83
+ for (const frame of stack?.split("\n").slice(1) ?? []) {
84
+ const source = parseFrame(frame);
85
+ if (source && samePath(source.file, file)) return { ...source, file };
86
+ }
87
+ return void 0;
88
+ }
89
+
90
+ export {
91
+ secret,
92
+ isSecret,
93
+ revealSecret,
94
+ scriptRegistry,
95
+ test,
96
+ parseFrame,
97
+ pathKey,
98
+ samePath,
99
+ sourceInFile
100
+ };