diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 33fd6b1..e2941bc 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,8 +11,7 @@ permissions: jobs: platforms: name: test (${{ matrix.os }}) - # Windows: where DevEco users work, and where the LSP client's drive-letter URIs, node.exe lookup and process - # handling differ. + # Windows: where DevEco users work, and where file paths (drive letters, backslashes) and the ripgrep lookup differ. strategy: fail-fast: false matrix: diff --git a/AGENTS.md b/AGENTS.md index 341e3fe..d65d9dd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -54,7 +54,7 @@ This file is the map for every coding agent (opencode and Codex read `AGENTS.md` | `docs/exec-plans/tech-debt-tracker.md` | known gaps (`@ObjectLink`, nested-write citation, unimplemented judge chain, ...) | | `docs/design-docs/index.md` | design docs with status: decisions, core beliefs, agentic plugin, parked ideas | | `docs/design-docs/decisions.md` | decisions made (judge chain, scope, repos, docs) | -| `sandbox/demo/` | the demo project (R1, R2 and R3 pages) and `DEMO.md`, the demo kit for opencode and DevEco Code; the rest of `sandbox/` is ignored scratch | +| `sandbox/demo/` | the demo project (R1–R4 pages) and `DEMO.md`, the demo kit for opencode and DevEco Code; the rest of `sandbox/` is ignored scratch | | `bench/` (private) | `bench/README.md` (layout), `bench/docs/RESULTS.md` (results, evaluation status), `bench/docs/evaluation-method.md`, eval scripts | ## Keeping docs fresh diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 559bd17..74b6121 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -38,7 +38,7 @@ sandbox/demo/ the demo project (opencode): R1 pages i sandbox/* everything else is local scratch (ignored), e.g. a DevEco Code copy of the demo arkui-sem/ the linter (opencode plugin, package arkui-sem 0.2.0, ESM, TypeScript) README.md, AGENTS.md - src/opencode.ts plugin: tool.execute.after feedback, session.idle gate, tool arkui_check, language server lifecycle + src/opencode.ts plugin: tool.execute.after feedback, session.idle gate, tool arkui_check src/facts.ts the fact model: what the extractor records per file, and the cross-file lookup interfaces src/queries.ts queries derived from the facts: paths, rendering reads, declared types, class hierarchies src/files.ts .ets discovery under a path; the files an agent's edit touched @@ -64,7 +64,7 @@ arkui-sem/ the linter (opencode plugin, package ar src/ets/types.ts type annotations → TypeRef, object literals, per-type records (classes, interfaces, aliases) src/ets/syntax.ts, scan.ts, modules.ts, directives.ts, lifecycle.ts node helpers, file context, imports/exports, disable comments, lifecycle hook names - src/sdk.ts DevEco Studio and HarmonyOS SDK lookup (parser options, ace-server) + src/sdk.ts DevEco Studio and HarmonyOS SDK lookup (parser options) src/project.ts project index for the rules: imported name → declaring file (relative imports, packages from oh-package.json5 local dependencies and build-profile.json5 modules, Index.ets re-exports), caches; call-site edges: a project scan resolving each file's component uses (callSites), or for one @@ -75,13 +75,10 @@ arkui-sem/ the linter (opencode plugin, package ar src/engine.ts candidates → slices → judge → finding/question bands (thresholds 0.8 / 0.5); agent formatting; KINDS: one entry per candidate kind (judge or facts-only, evidence and fix, disable-comment hint) src/config.ts defaults < ~/.config/arkui-sem/config.json < .opencode/arkui-sem.json < env < plugin options - src/cli.ts arkui-sem check | config | lsp (default backend: clef) - src/lsp/ utility client for ace-server (ArkTS language server): definition, references, call hierarchy; - warm.ts keeps one server per project running for the plugin (started on the first .ets edit, - sent each edited file, asked within a time budget, stopped on dispose; setting lsp: auto | off) - test/ node:test, run from src/ via tsx (npm test, offline): rules/R.test.ts, one file - per module (config, engine, deepseek, openrouter, opencode, lsp, project, callsites, search, loops, inputs), helpers.ts; test/fixtures/: - Counter, Feed, Profile (R1), Ticker (R3), fake-ace-server.mjs (both LSP protocols), project/ + src/cli.ts arkui-sem check | config (default backend: clef) + test/ node:test, run from src/ via tsx (npm test, offline): rules/R*.test.ts, one file + per module or feature (test/.test.ts), helpers.ts; test/fixtures/: + Counter, Feed, Profile (R1), Ticker (R3), project/ (two-module DevEco project: entry imports common by package name) scripts/install.mjs scripts/compare-callsites.mjs searched call sites against the whole-project scan on a project or a generated one, with timings diff --git a/README.md b/README.md index 217e64e..550909e 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,8 @@ # arkui-sem Semantic linting of ArkTS/ArkUI declarative state inside coding agents. A fact extractor finds candidate bugs -(a field that is written and rendered but not reactive, a nested write the state decorator does not observe, a -resource that is never released), and a small "System One" decision model (Cloudflare Clef, TypeSafe Jev, DeepSeek +(a field that is written and rendered but not reactive, a nested write the state decorator does not observe, a list +row that keeps stale content, an event or input wired one way only, a resource that is never released), and a small "System One" decision model (Cloudflare Clef, TypeSafe Jev, DeepSeek flash as System One, ...) judges each one. Confident verdicts go back to the agent as findings, uncertain ones as questions. It ships as an [opencode](https://opencode.ai) plugin and a CLI. **Prototype.** diff --git a/arkui-sem/AGENTS.md b/arkui-sem/AGENTS.md index 8edf1f0..409917f 100644 --- a/arkui-sem/AGENTS.md +++ b/arkui-sem/AGENTS.md @@ -22,14 +22,13 @@ Semantic lint for ArkTS/ArkUI declarative state (opencode v1 plugin + CLI). See - `src/facts.ts`: the fact model (of the linter's model and rules, `src/ets/` imports only this); `src/queries.ts`: queries derived from facts (`rowReads`: what a loop row renders, through builders and children); `src/files.ts`: `.ets` discovery. - `src/rules/`: one module per rule (`R1.ts`, `R2.ts`, `R3.ts`, `R4.ts`), `candidate.ts` (kinds, fingerprint), `index.ts` (`candidates()`). R2 event-unwired takes call sites from the engine. - `src/ets/`: the ArkTS parser (ohos-typescript, options from the SDK or `options.json`, regenerated by `scripts/ets-options.mjs`) and the fact extractor on its syntax tree (`extract.ts` orchestrates; `component.ts`, `resources.ts`, `types.ts`, `uses.ts`, `loops.ts`, `rebuilt.ts`, `inputs.ts` hold the facts; `callbacks.ts` tells handler closures from drawing ones). -- `src/sdk.ts`: DevEco Studio and HarmonyOS SDK lookup, shared by the parser and the LSP client. +- `src/sdk.ts`: DevEco Studio and HarmonyOS SDK lookup, for the parser. - `src/project.ts`: project index for cross-file rules (package lookup from oh-package.json5 and build-profile.json5, re-exports, file cache) and call-site edges (`callSites`: whole-project scan; `searchCallSites`: one struct, from a text search). - `src/search.ts`: the text search behind `searchCallSites` (ripgrep, else Node). `scripts/compare-callsites.mjs` checks the search against the scan. - `src/judge.ts`: System One backends, questions, slices; the backend registry (`BACKENDS`). - `src/engine.ts`: candidates → slices → judge → findings (≥ 0.8) and questions (0.5–0.8). A kind is the rule that emits it plus one entry in `KINDS` and one in `FIELD_SLICE` (`judge.ts`); the compiler checks both. -- `src/opencode.ts`: the plugin (post-edit feedback, idle gate, tool `arkui_check`, language server lifecycle). -- `src/config.ts`: settings merge order; `src/cli.ts`: `check`, `config`, `lsp`. -- `src/lsp/`: ace-server client (definition, references, call hierarchy) and `warm.ts`, which keeps one server per project running for the plugin (started on the first edit, stopped on dispose); tests use `test/fixtures/fake-ace-server.mjs`. +- `src/opencode.ts`: the plugin (post-edit feedback, idle gate, tool `arkui_check`). +- `src/config.ts`: settings merge order; `src/cli.ts`: `check`, `config`. - `scripts/install.mjs`: installs the plugin into an opencode or DevEco Code project, or globally. ## Conventions diff --git a/arkui-sem/README.md b/arkui-sem/README.md index 6d1a69e..24983eb 100644 --- a/arkui-sem/README.md +++ b/arkui-sem/README.md @@ -4,12 +4,15 @@ Semantic lint for ArkTS/ArkUI declarative state, built for the coding-agent loop [opencode](https://opencode.ai) v1 plugin and a CLI. Prototype. It targets UI state desynchronization: a field that is written and rendered but not reactive, a nested write -that V1 `@State` does not observe, a callback or `@Event` a child calls and no parent passes, a resource that +that V1 `@State` does not observe, a list that doesn't redraw what changed (a `ForEach` that replaces items +under an unchanged key or keys rows by index over items that change, a `LazyForEach` whose data source is +created while drawing or reassigned), a callback or `@Event` a child calls and no parent passes, a resource that is never released, a text input wired to its field one way (the field is set by code but not shown, or -typed into but read nowhere). A fact extractor finds candidates; a small "System One" judge model scores each one; scores -of 0.8 and above become findings, scores from 0.5 to 0.8 become questions back to the agent. The unwired -callback and the input wiring are decided by the facts alone, with no judge call; an input nothing reads is asked -as a question. +typed into but read nowhere), a selection the rows compare against that nothing sets. A fact extractor finds +candidates; a small "System One" judge model scores each one; scores of 0.8 and above become findings, scores +from 0.5 to 0.8 become questions back to the agent. The list kinds, the unwired callback and the input and +selection wiring are decided by the facts alone, with no judge call; some of them are asked as questions (an +input nothing reads, a selection nothing sets). ## Build and test @@ -37,21 +40,8 @@ edits after each tool call, gates the session once on idle while findings remain ```sh node dist/cli.js check ... [--format agent|json] [--backend ] node dist/cli.js config [--init] # prints masked key fragments -node dist/cli.js lsp [--project ] [--ace-server ] [--sdk ] [--node ] [--verbose] ``` -`lsp` queries Huawei's ArkTS language server (ace-server, not bundled): DevEco Studio's own (default install on Windows -and macOS), or the build `ARKUI_SEM_ACE_SERVER` / `--ace-server` points to; a build with `out/standardIndex/index.js` -(DevEco 26+) is driven over standard LSP. The SDK comes from DevEco Studio or `ARKUI_SEM_SDK`; `ARKUI_SEM_LSP_NODE` -picks the node that runs the server. - -The plugin starts the same server in the background on the first `.ets` edit of a project, sends it each edited -file, and stops it when opencode disposes the plugin. Nothing waits for it: without a server, or while it starts, checks -run as before. No rule asks it anything so far. `"lsp": "off"` in a config file, or `ARKUI_SEM_LSP=off`, keeps it -from starting (default `auto`); on a large project the server takes minutes and several GB to start. -The server follows imports by package name only in a project with `oh_modules` links (after a DevEco sync or -`ohpm install`); the rules don't depend on that, they use the project index. - ## Backends and configuration | Backend | What it is | @@ -69,3 +59,5 @@ Any backend can be tried on your own files: `node dist/cli.js check - Settings merge in this order: defaults < `~/.config/arkui-sem/config.json` < `.opencode/arkui-sem.json` (or `.deveco/arkui-sem.json` when only that one exists) < environment (`ARKUI_SEM_*`; `ARKUI_SEM_CONFIG` points at another config file) < plugin options. API keys belong in the user config file only; `node dist/cli.js config --init` writes a starter file. +The parser takes its ArkTS options from the HarmonyOS SDK: `ARKUI_SEM_SDK`, else DevEco Studio's (default install, or +`DEVECO_STUDIO`); without one it uses the options bundled with the linter. diff --git a/arkui-sem/src/cli.ts b/arkui-sem/src/cli.ts index a64db5e..1b52060 100644 --- a/arkui-sem/src/cli.ts +++ b/arkui-sem/src/cli.ts @@ -10,14 +10,10 @@ import { import { checkFiles, formatForAgent } from './engine.js'; import { absolute, etsFiles } from './files.js'; import { createBackend } from './judge.js'; -import { type ArktsLsp, startArktsLsp } from './lsp/client.js'; -import { projectRootFor } from './lsp/project.js'; const USAGE = `usage: arkui-sem check ... [--format agent|json] [--backend ] arkui-sem config [--init] - arkui-sem lsp [--project ] [--ace-server ] - [--sdk ] [--node ] [--verbose] `; const FORMATS = new Set(['agent', 'json']); @@ -89,76 +85,11 @@ function config(rest: string[]) { ); } -const LSP_ACTIONS = ['definition', 'references', 'callers', 'callees'] as const; -type LspAction = (typeof LSP_ACTIONS)[number]; -const LSP_VALUE_FLAGS = ['--project', '--ace-server', '--sdk', '--node']; - -function isLspAction(a: string | undefined): a is LspAction { - return LSP_ACTIONS.some((action) => action === a); -} - -// Asks ace-server (ArkTS language server); line:col are 1-based, output is JSON. -async function lsp(rest: string[]) { - const args: string[] = []; - const flags = new Map(); - for (let i = 0; i < rest.length; i++) { - const arg = rest[i]; - if (arg === '--verbose') { - flags.set(arg, ''); - continue; - } - if (!LSP_VALUE_FLAGS.includes(arg)) { - args.push(arg); - continue; - } - const value = rest[++i]; - if (value === undefined) { - process.stderr.write(`arkui-sem: ${arg} needs a value\n${USAGE}`); - process.exit(2); - } - flags.set(arg, value); - } - const [action, file, at] = args; - const position = /^(\d+):(\d+)$/.exec(at ?? ''); - if (!isLspAction(action) || !file || !position || Number(position[1]) < 1 || Number(position[2]) < 1) { - process.stderr.write(USAGE); - process.exit(2); - } - const started = Date.now(); - let server: ArktsLsp | undefined; - try { - server = await startArktsLsp(flags.get('--project') ?? projectRootFor(file), { - aceServer: flags.get('--ace-server'), - sdk: flags.get('--sdk'), - node: flags.get('--node'), - log: flags.has('--verbose') ? (line) => process.stderr.write(`${line}\n`) : undefined, - }); - const initMs = Date.now() - started; - server.open(file); - const result = await server[action](file, { line: Number(position[1]) - 1, character: Number(position[2]) - 1 }); - const output = { - protocol: server.protocol, - server: server.paths.server.entry, - initMs, - totalMs: Date.now() - started, - result, - }; - process.stdout.write(`${JSON.stringify(output, null, 2)}\n`); - } catch (e) { - process.stderr.write(`arkui-sem lsp: ${(e as Error).message}\n`); - process.exitCode = 1; - } finally { - await server?.stop(); - } -} - const [command, ...rest] = process.argv.slice(2); if (command === 'check') { await check(rest); } else if (command === 'config') { config(rest); -} else if (command === 'lsp') { - await lsp(rest); } else { process.stderr.write(USAGE); process.exit(2); diff --git a/arkui-sem/src/config.ts b/arkui-sem/src/config.ts index 82ce338..d9d0c2f 100644 --- a/arkui-sem/src/config.ts +++ b/arkui-sem/src/config.ts @@ -23,19 +23,14 @@ export interface Settings { gate: boolean; thresholds: { finding: number; question: number }; judgeTimeoutMs: number; - /** auto: the plugin starts ace-server on the first .ets edit when one is installed; off: never. */ - lsp: LspMode; dataDir: string; credentials: Credentials; sources: string[]; warnings: string[]; } -export type LspMode = 'auto' | 'off'; - export interface ConfigFile { backend?: string; - lsp?: string; gate?: boolean; findingThreshold?: number; questionThreshold?: number; @@ -55,7 +50,6 @@ const SCHEMA: Record = {}, projectDir: const user = read(userConfigPath(), 'user'); const project = read(projectConfigPath(projectDir), 'project'); const o = options as ConfigFile; - const lsp = first(o.lsp, env('ARKUI_SEM_LSP'), project.lsp, user.lsp) ?? 'auto'; - if (lsp !== 'auto' && lsp !== 'off') { - warnings.push(`lsp should be "auto" or "off", not "${lsp}"; using "auto"`); - } - return { backend: first(o.backend, env('ARKUI_SEM_BACKEND'), project.backend, user.backend) ?? 'clef', gate: first(bool(o.gate), bool(env('ARKUI_SEM_GATE')), project.gate, user.gate) ?? true, @@ -190,7 +179,6 @@ export function loadSettings(options: Record = {}, projectDir: project.judgeTimeoutMs, user.judgeTimeoutMs, ) ?? 8000, - lsp: lsp === 'off' ? 'off' : 'auto', dataDir: first(o.dataDir, env('ARKUI_SEM_DATA_DIR'), project.dataDir, user.dataDir) ?? join(homedir(), '.cache', 'arkui-sem'), @@ -261,7 +249,6 @@ export function describeSettings(s: Settings): Record { gate: s.gate, thresholds: s.thresholds, judgeTimeoutMs: s.judgeTimeoutMs, - lsp: s.lsp, dataDir: s.dataDir, credentials: { deepseekApiKey: mask(c.deepseekApiKey), diff --git a/arkui-sem/src/lsp/client.ts b/arkui-sem/src/lsp/client.ts deleted file mode 100644 index 049f7e7..0000000 --- a/arkui-sem/src/lsp/client.ts +++ /dev/null @@ -1,443 +0,0 @@ -// Headless client for ace-server: definition, references and call hierarchy over the standard (LSP 3.17) and legacy -// (`aceProject/*`) protocols, for cross-file facts the single-file extractor can't see. -import { randomUUID } from 'node:crypto'; -import { readFileSync } from 'node:fs'; -import { extname, resolve } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { JsonRpc } from './jsonrpc.js'; -import { initializeParams, toFileUri } from './project.js'; -import { type LspPathOptions, type LspPaths, type Protocol, resolvePaths, spawnServer, workDir } from './server.js'; - -export interface Position { - line: number; - character: number; -} -export interface Range { - start: Position; - end: Position; -} -export interface Location { - file: string; - range: Range; -} -/** A function or method: `range` spans its body, `selection` its name. */ -export interface CallItem { - name: string; - container?: string; - file: string; - range: Range; - selection: Range; -} -/** A function calling the queried one, with the call sites inside it. */ -export interface Caller { - item: CallItem; - calls: Range[]; -} - -export interface ArktsLsp { - readonly protocol: Protocol; - readonly paths: LspPaths; - /** Sends a file's current text (from disk unless given); needed before querying a file that changed. */ - open(file: string, text?: string): void; - definition(file: string, at: Position): Promise; - references(file: string, at: Position): Promise; - /** Functions that call the function at `at` (one level); a call inside an arrow callback counts for its enclosing method. */ - callers(file: string, at: Position): Promise; - /** Functions the function at `at` calls (one level); without call sites, which ace-server reports wrong. */ - callees(file: string, at: Position): Promise; - close(file: string): void; - stop(): Promise; -} - -export interface StartOptions extends LspPathOptions { - /** Initialization may index for long; it fails only after this long without any server message. */ - initTimeoutMs?: number; - /** Per request; legacy servers: without any server message, at most five times this in all. */ - requestTimeoutMs?: number; - maxOldSpaceMb?: number; - /** Aborting ends a start still in progress; a started server is ended with `stop()`. */ - signal?: AbortSignal; - /** Server stderr and notifications, for debugging. */ - log?: (line: string) => void; -} - -const DEFAULTS = { initTimeoutMs: 120_000, requestTimeoutMs: 60_000, maxOldSpaceMb: 8192 }; -const NO_TIMEOUT = 2 ** 31 - 1; -/** A legacy answer may take this many `requestTimeoutMs` in all while the server keeps sending other messages. */ -const LEGACY_ANSWER_CAP = 5; - -export async function startArktsLsp(projectRoot: string, options: StartOptions = {}): Promise { - const opts: Opts = { - ...options, - initTimeoutMs: options.initTimeoutMs ?? DEFAULTS.initTimeoutMs, - requestTimeoutMs: options.requestTimeoutMs ?? DEFAULTS.requestTimeoutMs, - maxOldSpaceMb: options.maxOldSpaceMb ?? DEFAULTS.maxOldSpaceMb, - }; - const paths = resolvePaths(options); - // A build without `standardIndex` falls back to the legacy protocol; say which one runs. - opts.log?.(`[start] ${paths.server.protocol} ${paths.server.entry} (node ${paths.node})`); - const params = initializeParams(projectRoot, paths, workDir()); - opts.signal?.throwIfAborted(); - const child = spawnServer(paths, opts.maxOldSpaceMb); - const abort = () => child.kill(); - opts.signal?.addEventListener('abort', abort, { once: true }); - child.stderr.setEncoding('utf8').on('data', (s: string) => opts.log?.(`[stderr] ${s.trimEnd()}`)); - const rpc = new JsonRpc(child); - const log = opts.log; - if (log) { - rpc.on('notification', (method, p) => log(`[notification] ${method} ${JSON.stringify(p ?? null).slice(0, 300)}`)); - } - const session = - paths.server.protocol === 'standard' ? new StandardSession(rpc, paths, opts) : new LegacySession(rpc, paths, opts); - try { - await session.initialize(params); - } catch (e) { - await session.stop(); - throw e; - } finally { - opts.signal?.removeEventListener('abort', abort); - } - return session; -} - -type Opts = typeof DEFAULTS & StartOptions; -interface TextDocument { - uri: string; - languageId: string; - version: number; - text: string; -} -/** LSP CallHierarchyItem, as both protocols send it. */ -interface RawItem { - name: string; - containerName?: string; - uri: string; - range: Range; - selectionRange: Range; -} - -/** LSP CallHierarchyIncomingCall. */ -interface IncomingCall { - from: RawItem; - fromRanges: Range[]; -} - -/** LSP CallHierarchyOutgoingCall; its `fromRanges` are wrong in ace-server, so they're not read. */ -interface OutgoingCall { - to: RawItem; -} - -interface InitializeResult { - capabilities?: object; -} - -/** The legacy server's answer: both directions; each entry's `info` nests the next level, which isn't read. */ -interface LegacyHierarchy { - incoming?: Array>; - outgoing?: Array>; -} - -interface LegacyEntry { - item: T; -} - -/** Fields of legacy notifications this client reads: answers carry `requestId`, module loading `isSuccess`. */ -interface LegacyNotice { - requestId?: unknown; - result?: unknown; - isSuccess?: boolean; -} - -abstract class Session implements ArktsLsp { - private readonly versions = new Map(); - abstract readonly protocol: Protocol; - - constructor( - protected readonly rpc: JsonRpc, - readonly paths: LspPaths, - protected readonly opts: Opts, - ) {} - - abstract initialize(params: ReturnType): Promise; - protected abstract send(doc: TextDocument, first: boolean): void; - abstract definition(file: string, at: Position): Promise; - abstract references(file: string, at: Position): Promise; - abstract callers(file: string, at: Position): Promise; - abstract callees(file: string, at: Position): Promise; - - open(file: string, text?: string): void { - const content = text ?? readFileSync(resolve(file), 'utf8'); - const uri = toFileUri(file); - const version = (this.versions.get(uri) ?? 0) + 1; - this.versions.set(uri, version); - this.send( - { uri, languageId: `deveco.apptool.${extname(file).slice(1) || 'ts'}`, version, text: content }, - version === 1, - ); - } - - close(file: string): void { - const uri = toFileUri(file); - if (this.versions.delete(uri)) { - this.rpc.notify('textDocument/didClose', { textDocument: { uri } }); - } - } - - protected isOpen(file: string): boolean { - return this.versions.has(toFileUri(file)); - } - - async stop(): Promise { - if (!this.rpc.alive) { - return; - } - const exited = new Promise((r) => this.rpc.once('exit', () => r())); - try { - await this.rpc.request('shutdown', undefined, 3000); - } catch { - /* ends with kill below */ - } - this.rpc.notify('exit', undefined); - let grace: NodeJS.Timeout | undefined; - await Promise.race([exited, new Promise((r) => (grace = setTimeout(r, 3000)))]); - clearTimeout(grace); - if (this.rpc.alive) { - this.rpc.kill(); - } - } - - /** Resolves with `done`; rejects once the server has sent nothing for `idleMs`, after `maxMs` in all, or on exit. */ - protected untilQuiet(done: Promise, idleMs: number, what: string, maxMs = NO_TIMEOUT): Promise { - const rpc = this.rpc; - if (!rpc.alive) { - return Promise.reject(new Error(`${what}: language server is not running`)); - } - return new Promise((resolve, reject) => { - let timer = setTimeout(fail, idleMs); - const deadline = setTimeout(fail, maxMs); - function fail() { - cleanup(); - reject(new Error(`${what}: no answer in time`)); - } - function bump() { - clearTimeout(timer); - timer = setTimeout(fail, idleMs); - } - function exited(code: number | null) { - cleanup(); - reject(new Error(`${what}: language server exited (${code})`)); - } - function cleanup() { - clearTimeout(timer); - clearTimeout(deadline); - rpc.off('message', bump); - rpc.off('exit', exited); - } - rpc.on('message', bump); - rpc.on('exit', exited); - done.then( - (v) => { - cleanup(); - resolve(v); - }, - (e) => { - cleanup(); - reject(e); - }, - ); - }); - } -} - -class StandardSession extends Session { - readonly protocol = 'standard' as const; - - async initialize(params: ReturnType): Promise { - const response = this.rpc.request('initialize', params, NO_TIMEOUT); - const { capabilities } = (await this.untilQuiet( - response, - this.opts.initTimeoutMs, - 'initialize', - )) as InitializeResult; - // Invalid initializationOptions get empty capabilities instead of an error. - if (!capabilities || Object.keys(capabilities).length === 0) { - throw new Error(`ace-server rejected the initialize params (see its log in ${workDir()})`); - } - this.rpc.notify('initialized', {}); - } - - protected send(doc: TextDocument, first: boolean): void { - if (first) { - this.rpc.notify('textDocument/didOpen', { textDocument: doc }); - } else { - this.rpc.notify('textDocument/didChange', { - textDocument: { uri: doc.uri, version: doc.version }, - contentChanges: [{ text: doc.text }], - }); - } - } - - async definition(file: string, at: Position): Promise { - return locations(await this.request('textDocument/definition', position(file, at))); - } - - async references(file: string, at: Position): Promise { - return locations( - await this.request('textDocument/references', { ...position(file, at), context: { includeDeclaration: true } }), - ); - } - - async callers(file: string, at: Position): Promise { - const item = await this.prepare(file, at); - const calls = item - ? ((await this.request('callHierarchy/incomingCalls', { item })) as IncomingCall[] | null) - : null; - return (calls ?? []).map((c) => ({ item: callItem(c.from), calls: c.fromRanges })); - } - - async callees(file: string, at: Position): Promise { - const item = await this.prepare(file, at); - const calls = item - ? ((await this.request('callHierarchy/outgoingCalls', { item })) as OutgoingCall[] | null) - : null; - return (calls ?? []).map((c) => callItem(c.to)); - } - - private async prepare(file: string, at: Position): Promise { - return ((await this.request('textDocument/prepareCallHierarchy', position(file, at))) as RawItem[] | null)?.[0]; - } - - private request(method: string, params: unknown): Promise { - return this.rpc.request(method, params, this.opts.requestTimeoutMs); - } -} - -/** - * Requests are notifications carrying a `requestId`; the answer is a notification of the same method echoing it. - * Find-usages and callers see usages in open documents only: like the standard session, only queried and edited files - * are opened, so usages in other files may be missing (opening more stalls the server on large projects). - */ -class LegacySession extends Session { - readonly protocol = 'legacy' as const; - private readonly waiting = new Map void>(); - private modulesLoaded?: (ok: boolean) => void; - - constructor(rpc: JsonRpc, paths: LspPaths, opts: Opts) { - super(rpc, paths, opts); - rpc.on('notification', (method, params) => { - const p = params as LegacyNotice | undefined; - if (method === 'aceProject/onModuleInitFinish') { - this.modulesLoaded?.(p?.isSuccess !== false); - } else if (typeof p?.requestId === 'string') { - this.waiting.get(p.requestId)?.(p.result); - } - }); - } - - async initialize(params: ReturnType): Promise { - const loaded = new Promise((r) => { - this.modulesLoaded = r; - }); - this.rpc.request('initialize', params, NO_TIMEOUT).catch(() => undefined); - if (!(await this.untilQuiet(loaded, this.opts.initTimeoutMs, 'initialize'))) { - throw new Error(`ace-server could not load the project modules (see its log in ${workDir()})`); - } - this.rpc.notify('initialized', { editors: [] }); - } - - protected send(doc: TextDocument, first: boolean): void { - const params = first - ? { textDocument: doc } - : { textDocument: { uri: doc.uri, version: doc.version }, contentChanges: [{ text: doc.text }] }; - this.rpc.notify(first ? 'aceProject/onAsyncDidOpen' : 'aceProject/onAsyncDidChange', this.payload(params, doc.uri)); - } - - async definition(file: string, at: Position): Promise { - return locations(await this.ask('aceProject/onAsyncDefinition', file, at)); - } - - async references(file: string, at: Position): Promise { - this.ensureOpen(file); - return locations(await this.ask('aceProject/onAsyncFindUsages', file, at)); - } - - async callers(file: string, at: Position): Promise { - const { incoming } = await this.hierarchy(file, at); - return (incoming ?? []).map((c) => ({ item: callItem(c.item.from), calls: c.item.fromRanges })); - } - - async callees(file: string, at: Position): Promise { - const { outgoing } = await this.hierarchy(file, at); - return (outgoing ?? []).map((c) => callItem(c.item.to)); - } - - private async hierarchy(file: string, at: Position): Promise { - this.ensureOpen(file); - return ((await this.ask('aceProject/onAsyncCallHierarchy', file, at)) ?? {}) as LegacyHierarchy; - } - - /** The server answers call hierarchy only for open documents; an open file stays open with its last text. */ - private ensureOpen(file: string): void { - if (!this.isOpen(file)) { - this.open(file); - } - } - - /** Server traffic (diagnostics of opened files) keeps a slow answer alive, up to a cap. */ - private ask(method: string, file: string, at: Position): Promise { - const payload = this.payload(position(file, at), toFileUri(file)); - const answer = new Promise((r) => this.waiting.set(payload.requestId, r)); - this.rpc.notify(method, payload); - const idle = this.opts.requestTimeoutMs; - return this.untilQuiet(answer, idle, method, idle * LEGACY_ANSWER_CAP).finally(() => - this.waiting.delete(payload.requestId), - ); - } - - /** `editorFiles` are file system paths: the server runs `URI.file()` on them. */ - private payload(params: unknown, uri: string) { - return { requestId: randomUUID(), traceId: randomUUID(), params, editorFiles: [fileURLToPath(uri)] }; - } -} - -function position(file: string, at: Position) { - return { textDocument: { uri: toFileUri(file) }, position: at }; -} - -function toFile(uri: string): string { - const file = uri.startsWith('file:') ? fileURLToPath(uri) : uri; - return file.replace(/^[a-z]:/, (d) => d.toUpperCase()); -} - -function callItem(raw: RawItem): CallItem { - return { - name: raw.name, - container: raw.containerName, - file: toFile(raw.uri), - range: raw.range, - selection: raw.selectionRange, - }; -} - -/** LSP Location or LocationLink. */ -interface RawLocation { - uri?: unknown; - targetUri?: unknown; - range?: Range; - targetSelectionRange?: Range; - targetRange?: Range; -} - -/** Location | Location[] | LocationLink[] (or null) → plain locations with file paths. */ -export function locations(result: unknown): Location[] { - const list: unknown[] = Array.isArray(result) ? result : result ? [result] : []; - return list.flatMap((entry) => { - if (typeof entry !== 'object' || entry === null) { - return []; - } - const l: RawLocation = entry; - const uri = l.uri ?? l.targetUri; - const range = l.range ?? l.targetSelectionRange ?? l.targetRange; - return typeof uri === 'string' && range ? [{ file: toFile(uri), range }] : []; - }); -} diff --git a/arkui-sem/src/lsp/jsonrpc.ts b/arkui-sem/src/lsp/jsonrpc.ts deleted file mode 100644 index 49d83c2..0000000 --- a/arkui-sem/src/lsp/jsonrpc.ts +++ /dev/null @@ -1,164 +0,0 @@ -// JSON-RPC 2.0 over a child process's stdio with LSP Content-Length framing. -import type { ChildProcessWithoutNullStreams } from 'node:child_process'; -import { EventEmitter } from 'node:events'; - -const HEADER_END = '\r\n\r\n'; - -interface Pending { - resolve: (v: unknown) => void; - reject: (e: Error) => void; - timer: NodeJS.Timeout; -} - -/** Any incoming message: a request has `method` and `id`, a notification only `method`, a response only `id`. */ -interface Message { - id?: number | string; - method?: string; - params?: unknown; - result?: unknown; - error?: ResponseError; -} - -interface ResponseError { - message: string; -} - -export interface JsonRpcEvents { - notification: [method: string, params: unknown]; - message: []; - exit: [code: number | null]; -} - -export class JsonRpc extends EventEmitter { - private buffer = Buffer.alloc(0); - private nextId = 1; - private readonly pending = new Map(); - private closed = false; - - constructor(private readonly child: ChildProcessWithoutNullStreams) { - super(); - this.setMaxListeners(0); // every in-flight request watches for progress and exit - child.stdout.on('data', (chunk: Buffer) => this.receive(chunk)); - // A write racing the server's exit fails with EPIPE; `exit` reports the end, so the write error is dropped. - child.stdin.on('error', () => undefined); - child.on('error', (e) => { - if (!this.closed) { - this.finish(new Error(`language server failed to start: ${e.message}`), null); - } - }); - child.on('exit', (code) => { - if (!this.closed) { - this.finish(new Error(`language server exited (${code})`), code); - } - }); - } - - private finish(error: Error, code: number | null): void { - this.closed = true; - for (const p of this.pending.values()) { - clearTimeout(p.timer); - p.reject(error); - } - this.pending.clear(); - this.emit('exit', code); - } - - get alive(): boolean { - return !this.closed; - } - - kill(): void { - this.child.kill(); - } - - request(method: string, params: unknown, timeoutMs: number): Promise { - const id = this.nextId++; - return new Promise((resolve, reject) => { - if (this.closed) { - return reject(new Error('language server is not running')); - } - const timer = setTimeout(() => { - this.pending.delete(id); - // Otherwise the server keeps working on it and later requests queue behind. - this.notify('$/cancelRequest', { id }); - reject(new Error(`${method} timed out after ${timeoutMs} ms`)); - }, timeoutMs); - this.pending.set(id, { resolve, reject, timer }); - this.write({ jsonrpc: '2.0', id, method, params }); - }); - } - - notify(method: string, params: unknown): void { - if (!this.closed) { - this.write({ jsonrpc: '2.0', method, params }); - } - } - - private write(message: object): void { - const body = Buffer.from(JSON.stringify(message), 'utf8'); - this.child.stdin.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}${HEADER_END}`, 'ascii'), body])); - } - - private receive(chunk: Buffer): void { - this.buffer = Buffer.concat([this.buffer, chunk]); - for (;;) { - const headerEnd = this.buffer.indexOf(HEADER_END); - if (headerEnd < 0) { - return; - } - const length = /Content-Length:\s*(\d+)/i.exec(this.buffer.subarray(0, headerEnd).toString('ascii'))?.[1]; - const start = headerEnd + HEADER_END.length; - if (length === undefined) { - this.buffer = this.buffer.subarray(start); - continue; - } - const end = start + Number(length); - if (this.buffer.length < end) { - return; - } - const body = this.buffer.subarray(start, end).toString('utf8'); - this.buffer = this.buffer.subarray(end); - try { - this.dispatch(JSON.parse(body)); - } catch { - /* a malformed message must not stop the stream */ - } - } - } - - private dispatch(msg: Message): void { - this.emit('message'); - if (msg.method !== undefined && msg.id !== undefined) { - // Server requests (client/registerCapability, workspace/configuration, ...): this client offers nothing back. - this.write({ jsonrpc: '2.0', id: msg.id, result: emptyAnswer(msg) }); - return; - } - if (msg.method !== undefined) { - this.emit('notification', msg.method, msg.params); - return; - } - const p = typeof msg.id === 'number' ? this.pending.get(msg.id) : undefined; - if (p && typeof msg.id === 'number') { - this.pending.delete(msg.id); - clearTimeout(p.timer); - if (msg.error) { - p.reject(new Error(msg.error.message)); - } else { - p.resolve(msg.result); - } - } - } -} - -interface ConfigurationParams { - items?: unknown[]; -} - -/** `workspace/configuration` expects one entry per requested item; other requests take null. */ -function emptyAnswer(msg: Message): unknown { - if (msg.method !== 'workspace/configuration') { - return null; - } - const items = (msg.params as ConfigurationParams | undefined)?.items; - return Array.isArray(items) ? items.map(() => null) : []; -} diff --git a/arkui-sem/src/lsp/project.ts b/arkui-sem/src/lsp/project.ts deleted file mode 100644 index 5509e01..0000000 --- a/arkui-sem/src/lsp/project.ts +++ /dev/null @@ -1,140 +0,0 @@ -// The `initialize` params ace-server requires: project root, server dir, and one record per ArkTS module. -// Modules come from the root build-profile.json5, else from the directories holding src/main/ets. -import { createHash } from 'node:crypto'; -import { existsSync, mkdirSync, readdirSync, readFileSync } from 'node:fs'; -import { basename, dirname, join, resolve } from 'node:path'; -import { pathToFileURL } from 'node:url'; -import { type ProjectModule, profileModules } from '../project.js'; -import type { LspPaths } from './server.js'; - -const MODULE_SOURCES = join('src', 'main', 'ets'); -const SCAN_DEPTH = 4; -const SKIP_DIRS = new Set(['node_modules', 'oh_modules', 'build']); -const DEVICE_PHONE = 5; - -/** `file:///D%3A/...` on Windows: the form ace-server keys documents by for `clientType: "intellij"`. */ -export function toFileUri(file: string): string { - const uri = pathToFileURL(resolve(file)).href; - const drive = /^file:\/\/\/([A-Za-z]):/.exec(uri); - return drive ? `file:///${drive[1].toUpperCase()}%3A${uri.slice(drive[0].length)}` : uri; -} - -export function findModuleDirs(projectRoot: string): string[] { - const found: string[] = []; - function walk(dir: string, depth: number) { - if (existsSync(join(dir, MODULE_SOURCES))) { - found.push(dir); - return; - } - if (depth === SCAN_DEPTH) { - return; - } - for (const e of readdirSync(dir, { withFileTypes: true })) { - if (e.isDirectory() && !SKIP_DIRS.has(e.name) && !e.name.startsWith('.')) { - walk(join(dir, e.name), depth + 1); - } - } - } - walk(resolve(projectRoot), 0); - return found; -} - -/** - * Nearest ancestor whose build-profile.json5 lists modules (a module has a build profile of its own, without them), else - * the parent of the module holding the file. - */ -export function projectRootFor(file: string): string { - let moduleDir: string | undefined; - for (let dir = dirname(resolve(file)); ; dir = dirname(dir)) { - if (profileModules(dir)) { - return dir; - } - if (!moduleDir && existsSync(join(dir, MODULE_SOURCES))) { - moduleDir = dir; - } - if (dirname(dir) === dir) { - return moduleDir ? dirname(moduleDir) : dirname(resolve(file)); - } - } -} - -function unix(p: string): string { - return p.replace(/\\/g, '/'); -} - -interface SdkVersion { - version: string; - level: string; -} - -/** `default/sdk-pkg.json` in a HarmonyOS SDK. */ -interface SdkPkg { - data?: SdkPkgData; -} - -interface SdkPkgData { - version?: unknown; - apiVersion?: unknown; -} - -/** API level and full version from the SDK's `default/sdk-pkg.json`. */ -function sdkVersion(sdk: string): SdkVersion { - const file = join(sdk, 'default', 'sdk-pkg.json'); - const pkg: SdkPkg = existsSync(file) ? JSON.parse(readFileSync(file, 'utf8')) : {}; - return { version: String(pkg.data?.version ?? ''), level: String(pkg.data?.apiVersion ?? '') }; -} - -function projectModules(root: string): ProjectModule[] { - const listed = profileModules(root); - return listed?.length ? listed : findModuleDirs(root).map((dir) => ({ name: basename(dir), dir })); -} - -export function initializeParams(projectRoot: string, paths: LspPaths, workDir: string) { - const root = resolve(projectRoot); - const { version, level } = sdkVersion(paths.sdk); - const ets = join(paths.sdk, 'default', 'openharmony', 'ets'); - const modules = projectModules(root).map(({ name, dir }) => ({ - moduleName: name, - modulePath: unix(dir), - jsComponentType: 'declarative', // ArkTS UI module (server enum ComponentType) - apiType: 'stageMode', - deviceType: [DEVICE_PHONE], - sdkJsPath: unix(join(ets, 'api')), - aceLoaderPath: unix(join(ets, 'build-tools', 'ets-loader')), - hosSdkPath: unix(join(paths.sdk, 'default', 'hms')), - compileSdkVersion: version, - compileSdkLevel: level, - compatibleSdkVersion: version, - compatibleSdkLevel: level, - })); - if (modules.length === 0) { - throw new Error(`no ArkTS module (a build-profile.json5 module or a dir with ${MODULE_SOURCES}) under ${root}`); - } - const rootUri = toFileUri(root); - const indexDir = join( - workDir, - 'index', - createHash('sha1') - .update(process.platform === 'win32' ? root.toLowerCase() : root) - .digest('hex') - .slice(0, 12), - ); - mkdirSync(indexDir, { recursive: true }); - return { - // Required in LSP InitializeParams. - processId: process.pid, - rootUri, - capabilities: {}, - // The server refuses to start without rootUri, lspServerWorkspacePath and modules. - initializationOptions: { - rootUri, - // Its bundled config (CSS, HML) resolves relative to this directory. - lspServerWorkspacePath: unix(dirname(paths.server.entry)), - modules, - clientType: 'intellij', - indexingDataLocation: unix(indexDir), - // The legacy server replaces its completion defaults with this object and fails on undefined. - completionSortSetting: { enableCodePreloadForCheckBox: false }, - }, - }; -} diff --git a/arkui-sem/src/lsp/server.ts b/arkui-sem/src/lsp/server.ts deleted file mode 100644 index 839127b..0000000 --- a/arkui-sem/src/lsp/server.ts +++ /dev/null @@ -1,99 +0,0 @@ -// Finds ace-server (Huawei's ArkTS language server) and node, and spawns the server. -import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'; -import { existsSync, mkdirSync } from 'node:fs'; -import { tmpdir, userInfo } from 'node:os'; -import { dirname, join } from 'node:path'; -import { findSdk, findStudio } from '../sdk.js'; - -/** standard: LSP 3.17 (`out/standardIndex/index.js`, DevEco ≥ 26.0.0.610); legacy: private `aceProject/*` protocol. */ -export type Protocol = 'standard' | 'legacy'; - -export interface ServerEntry { - entry: string; - protocol: Protocol; -} - -export interface LspPaths { - server: ServerEntry; - /** HarmonyOS SDK root: the directory holding `default/openharmony` and `default/hms`. */ - sdk: string; - node: string; -} - -export interface LspPathOptions { - /** ace-server root: a DevEco Studio install, its `plugins/openharmony`, an `ace-server` dir, or a dir holding `out/`. */ - aceServer?: string; - sdk?: string; - node?: string; -} - -/** The server entry under any accepted root; the standard one when the build ships it. */ -export function locateServer(root: string): ServerEntry | undefined { - for (const out of [ - join(root, 'plugins', 'openharmony', 'ace-server', 'out'), - join(root, 'ace-server', 'out'), - join(root, 'out'), - ]) { - const standard = join(out, 'standardIndex', 'index.js'); - if (existsSync(standard)) { - return { entry: standard, protocol: 'standard' }; - } - if (existsSync(join(out, 'index.js'))) { - return { entry: join(out, 'index.js'), protocol: 'legacy' }; - } - } - return undefined; -} - -/** The server comes from `aceServer`, else `ARKUI_SEM_ACE_SERVER`, else DevEco Studio's own install. */ -export function resolvePaths(options: LspPathOptions = {}, env = process.env): LspPaths { - const studio = findStudio(env); - const root = options.aceServer || env.ARKUI_SEM_ACE_SERVER || studio; - if (!root) { - throw new Error('ace-server not found: install DevEco Studio or set ARKUI_SEM_ACE_SERVER'); - } - const server = locateServer(root); - if (!server) { - throw new Error(`no ace-server entry under ${root}`); - } - const sdk = findSdk(options.sdk, env); - if (!sdk) { - throw new Error('HarmonyOS SDK not found: set ARKUI_SEM_SDK to the directory holding default/openharmony'); - } - return { server, sdk, node: options.node || env.ARKUI_SEM_LSP_NODE || defaultNode(studio) }; -} - -/** Inside opencode `process.execPath` is its Bun-built binary, not node: use DevEco's node, else node from PATH. */ -export function defaultNode(studio: string | undefined, isBun = !!process.versions.bun): string { - if (!isBun) { - return process.execPath; - } - const bundled = studio && join(studio, 'tools', 'node', process.platform === 'win32' ? 'node.exe' : 'bin/node'); - return bundled && existsSync(bundled) ? bundled : 'node'; -} - -/** Shared by all runs: the server's logs and its per-project index cache. */ -export function workDir(): string { - // Per user: on a shared POSIX host another user's directory isn't writable. - const dir = join(tmpdir(), `arkui-sem-lsp-${userInfo().username}`); - mkdirSync(join(dir, 'logs'), { recursive: true }); - return dir; -} - -/** The server reads its log path from argv and calls `gc()`, which needs `--expose-gc`. */ -export function spawnServer(paths: LspPaths, maxOldSpaceMb: number): ChildProcessWithoutNullStreams { - const logs = join(workDir(), 'logs'); - const args = [ - '--expose-gc', - `--max-old-space-size=${maxOldSpaceMb}`, - paths.server.entry, - '--stdio', - `--logger-path=${logs}`, - '--logger-level=INFO', - ]; - return spawn(paths.node, args, { - cwd: dirname(paths.server.entry), - stdio: ['pipe', 'pipe', 'pipe'], - windowsHide: true, - }); -} diff --git a/arkui-sem/src/lsp/warm.ts b/arkui-sem/src/lsp/warm.ts deleted file mode 100644 index b8c2123..0000000 --- a/arkui-sem/src/lsp/warm.ts +++ /dev/null @@ -1,98 +0,0 @@ -// Keeps one ace-server per project running for the plugin: started in the background on the first edit, sent each -// edited file, asked within a time budget, so the caller never waits on a missing, slow or dead server. -import { type ArktsLsp, type StartOptions, startArktsLsp } from './client.js'; -import { projectRootFor } from './project.js'; - -interface Server { - /** Undefined when the server did not start. */ - started: Promise; - lsp?: ArktsLsp; - /** Files edited while the server was starting. */ - unsent: Set; -} - -export class WarmLsp { - private readonly servers = new Map(); - private readonly stopping = new AbortController(); - - constructor( - private readonly log: (message: string) => void, - private readonly options: StartOptions = {}, - private readonly start = startArktsLsp, - ) {} - - /** Sends the file's text on disk to its project's server, starting that server on the project's first edit. */ - edited(file: string): void { - if (this.stopping.signal.aborted) { - return; - } - const root = projectRootFor(file); - const server = this.servers.get(root) ?? this.launch(root); - if (server.lsp) { - this.open(server.lsp, file); - } else { - server.unsent.add(file); - } - } - - /** - * The answer of the file's server, which has every edit reported before this call. Undefined when the project has no - * running server or the answer takes longer than budgetMs, counted from the call, startup included. - */ - async ask(file: string, budgetMs: number, query: (lsp: ArktsLsp) => Promise): Promise { - const server = this.servers.get(projectRootFor(file)); - if (!server) { - return undefined; - } - const answer = server.started.then((lsp) => lsp && query(lsp)).catch(() => undefined); - let timer: NodeJS.Timeout | undefined; - const late = new Promise((r) => { - timer = setTimeout(() => r(undefined), budgetMs); - }); - try { - return await Promise.race([answer, late]); - } finally { - clearTimeout(timer); - } - } - - /** Ends every server, also one still starting; later edits start none. */ - async stop(): Promise { - this.stopping.abort(); - await Promise.all([...this.servers.values()].map(async (s) => (await s.started)?.stop())); - } - - private launch(root: string): Server { - const server: Server = { - unsent: new Set(), - started: this.start(root, { ...this.options, signal: this.stopping.signal }).then( - (lsp) => { - server.lsp = lsp; - for (const file of server.unsent) { - this.open(lsp, file); - } - server.unsent.clear(); - this.log(`language server ready for ${root} (${lsp.protocol})`); - return lsp; - }, - (e: Error) => { - if (!this.stopping.signal.aborted) { - this.log(`no language server for ${root}: ${e.message}`); - } - return undefined; - }, - ), - }; - this.servers.set(root, server); - return server; - } - - /** A file deleted since its edit can't be read: the server drops its copy. */ - private open(lsp: ArktsLsp, file: string): void { - try { - lsp.open(file); - } catch { - lsp.close(file); - } - } -} diff --git a/arkui-sem/src/opencode.ts b/arkui-sem/src/opencode.ts index 0f63a1d..53dd80e 100644 --- a/arkui-sem/src/opencode.ts +++ b/arkui-sem/src/opencode.ts @@ -3,7 +3,6 @@ import { cachePath, loadSettings } from './config.js'; import { checkFiles, type Finding, formatForAgent } from './engine.js'; import { absolute, editedFiles, etsFiles } from './files.js'; import { createBackend, type SystemOneBackend } from './judge.js'; -import { WarmLsp } from './lsp/warm.js'; import { ProjectIndex } from './project.js'; const EDIT_TOOLS = new Set(['edit', 'write', 'multiedit', 'patch', 'apply_patch']); @@ -11,8 +10,6 @@ const MAX_GATE_FOLLOWUPS = 3; /** The wait for call sites after an edit, which holds the agent up, and at the idle gate, which doesn't. */ const EDIT_CALL_SITE_BUDGET_MS = 1000; const GATE_CALL_SITE_BUDGET_MS = 10_000; -/** ace-server can index a large project for minutes without a message; the start runs in the background. */ -const LSP_INIT_TIMEOUT_MS = 600_000; interface SessionState { touched: Set; @@ -40,10 +37,6 @@ export const ArkuiSemPlugin: Plugin = async ({ client, directory }, options) => } const project = new ProjectIndex(); - const lsp = - settings.lsp === 'off' - ? undefined - : new WarmLsp((message) => void log('info', message), { initTimeoutMs: LSP_INIT_TIMEOUT_MS }); async function run(files: string[], callSiteBudgetMs?: number): Promise { backend ??= await createBackend(settings.backend, settings.credentials); @@ -64,7 +57,7 @@ export const ArkuiSemPlugin: Plugin = async ({ client, directory }, options) => await log( 'info', - `loaded (backend=${settings.backend}, gate=${settings.gate}, lsp=${settings.lsp}, config=${settings.sources.join(', ') || 'none'})`, + `loaded (backend=${settings.backend}, gate=${settings.gate}, config=${settings.sources.join(', ') || 'none'})`, ); for (const w of settings.warnings) { await log('warn', w); @@ -83,7 +76,6 @@ export const ArkuiSemPlugin: Plugin = async ({ client, directory }, options) => const s = session(input.sessionID); for (const f of files) { s.touched.add(f); - lsp?.edited(f); } const fresh = (await run(files, EDIT_CALL_SITE_BUDGET_MS)).filter((f) => !s.reported.has(f.fingerprint)); for (const f of fresh) { @@ -139,14 +131,10 @@ export const ArkuiSemPlugin: Plugin = async ({ client, directory }, options) => } }, - dispose: async () => { - await lsp?.stop(); - }, - tool: { arkui_check: tool({ description: - "Check ArkTS/ArkUI .ets files for state-management and lifecycle defects: state that won't re-render the UI, nested mutation of unobserved classes, callbacks and @Event a child calls that no parent passes, listeners and timers that are never released. Pass files or directories; defaults to the project.", + "Check ArkTS/ArkUI .ets files for state-management and lifecycle defects: state that won't re-render the UI, nested mutation of unobserved classes, ForEach/LazyForEach lists that don't redraw changed items, text inputs and selections wired one way, callbacks and @Event a child calls that no parent passes, listeners and timers that are never released. Pass files or directories; defaults to the project.", args: { paths: tool.schema .array(tool.schema.string()) diff --git a/arkui-sem/src/project.ts b/arkui-sem/src/project.ts index 901e276..3bc94f9 100644 --- a/arkui-sem/src/project.ts +++ b/arkui-sem/src/project.ts @@ -29,7 +29,7 @@ interface Aliases { } /** A module as the root build-profile.json5 lists it. */ -export interface ProjectModule { +interface ProjectModule { name: string; dir: string; } @@ -71,15 +71,6 @@ function readProfileModules(path: string): ProjectModule[] | undefined { })); } -/** The modules a project root's build-profile.json5 lists; undefined without a readable profile. */ -export function profileModules(root: string): ProjectModule[] | undefined { - try { - return readProfileModules(join(root, BUILD_PROFILE)); - } catch { - return undefined; - } -} - function mtime(path: string): number | undefined { try { const s = statSync(path, { throwIfNoEntry: false }); diff --git a/arkui-sem/src/sdk.ts b/arkui-sem/src/sdk.ts index 58441c6..3b61a51 100644 --- a/arkui-sem/src/sdk.ts +++ b/arkui-sem/src/sdk.ts @@ -1,4 +1,4 @@ -// Finds DevEco Studio and the HarmonyOS SDK on this machine. +// Finds the HarmonyOS SDK on this machine: a given directory or DevEco Studio's. import { existsSync } from 'node:fs'; import { join } from 'node:path'; @@ -7,19 +7,26 @@ const STUDIO_CANDIDATES: Record = { darwin: ['/Applications/DevEco-Studio.app/Contents', '/Applications/DevEco Studio.app/Contents'], }; -export function findStudio(env = process.env): string | undefined { - const candidates = [env.DEVECO_STUDIO, ...(STUDIO_CANDIDATES[process.platform] ?? [])].filter( - (p): p is string => !!p, - ); - return candidates.find((p) => existsSync(join(p, 'plugins', 'openharmony', 'ace-server'))); +function hasSdk(dir: string): boolean { + return existsSync(join(dir, 'default', 'openharmony')); +} + +/** The SDK of the first DevEco Studio install that has one: `DEVECO_STUDIO`, then the default install paths. */ +function studioSdk(env: NodeJS.ProcessEnv): string | undefined { + return [env.DEVECO_STUDIO, ...(STUDIO_CANDIDATES[process.platform] ?? [])] + .filter((p): p is string => !!p) + .map((p) => join(p, 'sdk')) + .find(hasSdk); } /** The HarmonyOS SDK root, the directory holding `default/openharmony` and `default/hms`: `explicit`, else - * `ARKUI_SEM_SDK`, else DevEco Studio's. */ + * `ARKUI_SEM_SDK`, else DevEco Studio's. A given directory without an SDK gives none, with no fallback. */ export function findSdk(explicit?: string, env = process.env): string | undefined { - const studio = findStudio(env); - const sdk = explicit || env.ARKUI_SEM_SDK || (studio && join(studio, 'sdk')); - return sdk && existsSync(join(sdk, 'default', 'openharmony')) ? sdk : undefined; + const given = explicit || env.ARKUI_SEM_SDK; + if (given) { + return hasSdk(given) ? given : undefined; + } + return studioSdk(env); } /** ets-loader's directory in one SDK kit (`openharmony`, `hms`): the ArkTS compiler's options and component lists. */ diff --git a/arkui-sem/test/config.test.ts b/arkui-sem/test/config.test.ts index 1a0381c..217b3af 100644 --- a/arkui-sem/test/config.test.ts +++ b/arkui-sem/test/config.test.ts @@ -14,7 +14,6 @@ const VARS = [ 'ARKUI_SEM_QUESTION_THRESHOLD', 'ARKUI_SEM_JUDGE_TIMEOUT_MS', 'ARKUI_SEM_DATA_DIR', - 'ARKUI_SEM_LSP', 'DEEPSEEK_API_KEY', 'DEEPSEEK_BASE_URL', 'TYPESAFE_API_KEY', @@ -47,16 +46,6 @@ describe('loadSettings', () => { assert.deepEqual(s.warnings, []); }); - test('lsp is auto unless switched off; another value warns and stays auto', () => { - assert.equal(loadSettings({}, project).lsp, 'auto'); - put(projectFile, { lsp: 'off' }); - assert.equal(loadSettings({}, project).lsp, 'off'); - process.env.ARKUI_SEM_LSP = 'on'; - const s = loadSettings({}, project); - assert.equal(s.lsp, 'auto'); - assert.match(s.warnings.join(' '), /lsp should be "auto" or "off"/); - }); - test('the user config supplies the backend and the DeepSeek key', () => { put(userFile, { backend: 'deepseek-flash', deepseek: { apiKey: 'sk-user-1234567890' }, gate: false }); const s = loadSettings({}, project); diff --git a/arkui-sem/test/fixtures/fake-ace-server.mjs b/arkui-sem/test/fixtures/fake-ace-server.mjs deleted file mode 100644 index 63b7fca..0000000 --- a/arkui-sem/test/fixtures/fake-ace-server.mjs +++ /dev/null @@ -1,88 +0,0 @@ -// Stand-in for ace-server in tests: speaks the standard protocol when run as `standardIndex/index.js`, else the legacy one. -// usage: node /out[/standardIndex]/index.js --stdio -import { isAbsolute } from "node:path"; - -const standard = /standardIndex/.test(process.argv[1]); -let buffer = Buffer.alloc(0); - -const send = (msg) => { - const body = Buffer.from(JSON.stringify({ jsonrpc: "2.0", ...msg }), "utf8"); - process.stdout.write(Buffer.concat([Buffer.from(`Content-Length: ${body.length}\r\n\r\n`), body])); -}; -const location = (uri, line) => ({ uri, range: { start: { line, character: 2 }, end: { line, character: 6 } } }); -// Last version sent per document: definition answers on that line, so tests can see didChange arrive. -const versions = new Map(); -const ANSWERS = { - definition: (p) => location(p.textDocument.uri, versions.get(p.textDocument.uri) ?? 1), - references: (p) => [location(p.textDocument.uri, 1), location(p.textDocument.uri, 7)], -}; -// Call hierarchy around `rename` (lines 3-5): called from `build` at line 9, calls `save`. -const item = (uri, name, line) => ({ name, kind: 6, containerName: "P", uri, ...location(uri, line), selectionRange: location(uri, line).range }); -const INCOMING = (uri) => [{ from: item(uri, "build", 8), fromRanges: [location(uri, 9).range] }]; -const OUTGOING = (uri) => [{ to: item(uri, "save", 12), fromRanges: [location(uri, 99).range] }]; - -function standardMessage({ id, method, params }) { - if (method === "initialize") { - const o = params.initializationOptions; - if (!o?.rootUri || !o.lspServerWorkspacePath || !o.modules?.length) return send({ id, result: { capabilities: {} } }); - send({ method: "$/progress", params: { token: "index", value: { kind: "report" } } }); - send({ id: 1000, method: "client/registerCapability", params: { registrations: [] } }); - return send({ id, result: { capabilities: { definitionProvider: true, referencesProvider: true } } }); - } - if (method === "textDocument/didOpen" || method === "textDocument/didChange") return versions.set(params.textDocument.uri, params.textDocument.version); - if (method === "textDocument/definition") return send({ id, result: ANSWERS.definition(params) }); - if (method === "textDocument/references") return send({ id, result: ANSWERS.references(params) }); - if (method === "textDocument/prepareCallHierarchy") return send({ id, result: [item(params.textDocument.uri, "rename", 3)] }); - if (method === "callHierarchy/incomingCalls") return send({ id, result: INCOMING(params.item.uri) }); - if (method === "callHierarchy/outgoingCalls") return send({ id, result: OUTGOING(params.item.uri) }); - if (method === "shutdown") return send({ id, result: null }); - if (method === "exit") process.exit(0); -} - -// Like the real legacy server, find-usages sees open documents only. -const opened = new Set(); -const LEGACY_QUERIES = { - "aceProject/onAsyncDefinition": ANSWERS.definition, - "aceProject/onAsyncFindUsages": () => [...opened].map((uri) => location(uri, 1)), - // One answer for both directions; `info` nests the next level. - "aceProject/onAsyncCallHierarchy": (p) => ({ - incoming: INCOMING(p.textDocument.uri).map((c) => ({ item: c, info: [{ item: { from: item(p.textDocument.uri, "aboutToAppear", 20), fromRanges: [] }, info: [] }] })), - outgoing: OUTGOING(p.textDocument.uri).map((c) => ({ item: c, info: [] })), - definition: [item(p.textDocument.uri, "rename", 3)], - }), -}; - -function legacyMessage({ id, method, params }) { - if (method === "aceProject/onAsyncDidOpen" || method === "aceProject/onAsyncDidChange") { - versions.set(params.params.textDocument.uri, params.params.textDocument.version); - return opened.add(params.params.textDocument.uri); - } - if (method === "textDocument/didClose") return opened.delete(params.textDocument.uri); - if (method === "initialize") { - send({ id, result: { capabilities: {} } }); - send({ method: "aceProject/onIndexingProgressUpdate", params: { done: 1, total: 2 } }); - const ok = params.initializationOptions?.completionSortSetting !== undefined && params.initializationOptions?.modules?.length > 0; - return setTimeout(() => send({ method: "aceProject/onModuleInitFinish", params: { isSuccess: ok, isCache: false } }), 50); - } - if (LEGACY_QUERIES[method]) { - // The real server reads editorFiles as file system paths. - if (!params.editorFiles?.every((f) => isAbsolute(f) && !f.startsWith("file:"))) return; - return send({ method, params: { requestId: params.requestId, result: LEGACY_QUERIES[method](params.params), traceId: params.traceId } }); - } - if (method === "shutdown") return send({ id, result: null }); - if (method === "exit") process.exit(0); -} - -process.stdin.on("data", (chunk) => { - buffer = Buffer.concat([buffer, chunk]); - for (;;) { - const end = buffer.indexOf("\r\n\r\n"); - if (end < 0) return; - const length = Number(/Content-Length: (\d+)/.exec(buffer.subarray(0, end).toString())[1]); - if (buffer.length < end + 4 + length) return; - const msg = JSON.parse(buffer.subarray(end + 4, end + 4 + length).toString("utf8")); - buffer = buffer.subarray(end + 4 + length); - if (msg.method === undefined) continue; - (standard ? standardMessage : legacyMessage)(msg); - } -}); diff --git a/arkui-sem/test/lsp.test.ts b/arkui-sem/test/lsp.test.ts deleted file mode 100644 index cdfd69f..0000000 --- a/arkui-sem/test/lsp.test.ts +++ /dev/null @@ -1,224 +0,0 @@ -// The ArkTS LSP client against test/fixtures/fake-ace-server.mjs, installed in Studio (legacy) and CLT (standard) -// layouts under a temp dir. - -import assert from 'node:assert/strict'; -import { spawn } from 'node:child_process'; -import { copyFileSync } from 'node:fs'; -import { join } from 'node:path'; -import { test } from 'node:test'; -import { type ArktsLsp, locations, startArktsLsp } from '../src/lsp/client.js'; -import { JsonRpc } from '../src/lsp/jsonrpc.js'; -import { findModuleDirs, initializeParams, projectRootFor, toFileUri } from '../src/lsp/project.js'; -import { defaultNode, locateServer, resolvePaths } from '../src/lsp/server.js'; -import { WarmLsp } from '../src/lsp/warm.js'; -import { put, ROOT, tempDir } from './helpers.js'; - -const tmp = tempDir(); -const at = (rel: string) => join(tmp, rel); -for (const entry of ['clt/out/standardIndex/index.js', 'studio/plugins/openharmony/ace-server/out/index.js']) { - copyFileSync(join(ROOT, 'test', 'fixtures', 'fake-ace-server.mjs'), put(at(entry), '')); -} -put(at('sdk/default/openharmony/ets/api/.keep'), ''); -put(at('sdk/default/sdk-pkg.json'), { data: { apiVersion: '24', version: '6.1.1.125' } }); -const page = put(at('proj/entry/src/main/ets/pages/P.ets'), '@Component\nstruct P {\n build() {}\n}\n'); -// Explicit paths everywhere, so ARKUI_SEM_* variables on the machine can't change the outcome. -// maxOldSpaceMb: undefined must keep the default, as optional settings are passed through that way. -const base = { - sdk: at('sdk'), - node: process.execPath, - initTimeoutMs: 10_000, - requestTimeoutMs: 10_000, - maxOldSpaceMb: undefined, -}; - -test('modules are the */src/main/ets dirs; the project root is above them', () => { - put(at('proj/features/lib/src/main/ets/A.ets'), 'P()'); - assert.deepEqual(findModuleDirs(at('proj')).sort(), [at('proj/entry'), at('proj/features/lib')]); - assert.equal(projectRootFor(page), at('proj')); - put(at('proj2/build-profile.json5'), "{ modules: [{ name: 'entry', srcPath: './entry' }] }"); - put(at('proj2/entry/build-profile.json5'), "{ apiType: 'stageMode' }"); - assert.equal(projectRootFor(put(at('proj2/entry/src/main/ets/B.ets'), '')), at('proj2')); -}); - -test('the server is told the modules of the build profile, else the scanned ones', () => { - const paths = resolvePaths({ aceServer: at('clt'), sdk: at('sdk'), node: process.execPath }, {}); - const names = (root: string) => - initializeParams(root, paths, at('work')).initializationOptions.modules.map((m) => m.moduleName); - assert.deepEqual(names(at('proj')).sort(), ['entry', 'lib']); - put(at('proj3/build-profile.json5'), "{ modules: [{ name: 'feature_lib', srcPath: './features/lib' }] }"); - put(at('proj3/features/lib/Index.ets'), ''); - put(at('proj3/unlisted/src/main/ets/A.ets'), ''); - assert.deepEqual(names(at('proj3')), ['feature_lib']); -}); - -test('file URIs use the upper-case drive form and round-trip through locations', () => { - const uri = toFileUri(page); - if (process.platform === 'win32') { - assert.match(uri, /^file:\/\/\/[A-Z]%3A\//); - } - const range = { start: { line: 1, character: 0 }, end: { line: 1, character: 3 } }; - assert.deepEqual(locations(null), []); - assert.equal(locations({ uri, range })[0].file, page); - assert.equal(locations([{ targetUri: uri, targetSelectionRange: range }])[0].range, range); -}); - -test('locateServer finds Studio and CLT layouts and prefers the standard entry', () => { - assert.equal(locateServer(at('clt'))?.protocol, 'standard'); - assert.equal(locateServer(at('studio'))?.protocol, 'legacy'); - assert.throws(() => resolvePaths({ aceServer: at('clt'), sdk: at('no-sdk') }, {}), /SDK not found/); - assert.throws(() => resolvePaths({ aceServer: at('nothing'), sdk: at('sdk') }, {}), /no ace-server entry/); -}); - -test('the server comes from the option, else ARKUI_SEM_ACE_SERVER', () => { - const options = { sdk: at('sdk'), node: process.execPath }; - const env = { ARKUI_SEM_ACE_SERVER: at('studio') }; - assert.equal(resolvePaths(options, env).server.protocol, 'legacy'); - assert.equal(resolvePaths({ ...options, aceServer: at('clt') }, env).server.protocol, 'standard'); -}); - -test('under Bun (opencode) the server runs on node, not on process.execPath', () => { - assert.equal(defaultNode(undefined, false), process.execPath); - assert.equal(defaultNode(undefined, true), 'node'); - const bundled = put( - at(process.platform === 'win32' ? 'studio/tools/node/node.exe' : 'studio/tools/node/bin/node'), - '', - ); - assert.equal(defaultNode(at('studio'), true), bundled); -}); - -test('a server that cannot start rejects instead of hanging', async () => { - await assert.rejects( - () => startArktsLsp(at('proj'), { ...base, aceServer: at('clt'), node: at('no-node') }), - /failed to start|exited/, - ); - await assert.rejects(() => startArktsLsp(at('sdk'), { ...base, aceServer: at('clt') }), /no ArkTS module/); -}); - -test('writing to a server that just exited does not crash the client', async () => { - const child = spawn(process.execPath, ['-e', 'setTimeout(() => process.exit(0), 50)'], { - stdio: ['pipe', 'pipe', 'pipe'], - }); - const rpc = new JsonRpc(child); - const exited = new Promise((r) => rpc.once('exit', r)); - const timer = setInterval(() => child.stdin.writable && child.stdin.write('x'.repeat(65536)), 5); - await exited; - clearInterval(timer); - assert.equal(rpc.alive, false); - await assert.rejects(() => rpc.request('shutdown', null, 1000), /not running/); -}); - -for (const [protocol, server] of [ - ['standard', 'clt'], - ['legacy', 'studio'], -]) { - test(`${protocol} protocol: initialize, open, change, definition, references, callers, callees, stop`, async () => { - const lsp = await startArktsLsp(at('proj'), { ...base, aceServer: at(server) }); - const pos = { line: 1, character: 8 }; - try { - assert.equal(lsp.protocol, protocol); - lsp.open(page); - lsp.open(page, '@Component\nstruct P {}\n'); - // The fake answers on the line of the document's last version: 2 means the change arrived. - assert.deepEqual( - (await lsp.definition(page, pos)).map((l) => [l.file, l.range.start.line]), - [[page, 2]], - ); - const refs = await lsp.references(page, pos); - if (protocol === 'standard') { - assert.deepEqual( - refs.map((l) => l.range.start.line), - [1, 7], - ); - } - // Legacy find-usages sees open documents only, and only the queried file is opened: A.ets stays closed. - else { - assert.deepEqual( - refs.map((l) => l.file), - [page], - ); - } - const callers = await lsp.callers(page, { line: 3, character: 3 }); - assert.deepEqual( - callers.map((c) => [c.item.name, c.item.container, c.item.file, c.calls.map((r) => r.start.line)]), - [['build', 'P', page, [9]]], - ); - assert.deepEqual( - (await lsp.callees(page, { line: 3, character: 3 })).map((c) => [c.name, c.selection.start.line]), - [['save', 12]], - ); - assert.throws(() => lsp.open(at('missing.ets')), /ENOENT/); - lsp.close(page); - if (protocol === 'legacy') { - // A queried file that was closed is opened again. - assert.ok((await lsp.references(page, pos)).some((l) => l.file === page)); - } - } finally { - await lsp.stop(); - } - const started = Date.now(); - await assert.rejects(() => lsp.definition(page, { line: 0, character: 0 }), /not running/); - assert.ok(Date.now() - started < 1000, 'a query after stop fails at once'); - }); -} - -const definitionLine = (lsp: ArktsLsp) => - lsp.definition(page, { line: 1, character: 8 }).then((l) => l[0].range.start.line); - -test('warm server: edits made while it starts reach it before the first answer, later ones as they come', async () => { - const logs: string[] = []; - const warm = new WarmLsp((m) => logs.push(m), { ...base, aceServer: at('clt') }); - try { - assert.equal(await warm.ask(page, 10_000, definitionLine), undefined, 'no edit, no server'); - warm.edited(page); - assert.equal(await warm.ask(page, 10_000, definitionLine), 1); - warm.edited(page); - assert.equal(await warm.ask(page, 10_000, definitionLine), 2); - assert.match(logs.join(' '), /language server ready .*standard/); - } finally { - await warm.stop(); - } -}); - -test('warm server: a missing, slow or dead server gives no answer and never throws', async () => { - const logs: string[] = []; - const missing = new WarmLsp((m) => logs.push(m), { ...base, aceServer: at('nothing') }); - missing.edited(page); - assert.equal(await missing.ask(page, 10_000, definitionLine), undefined); - assert.match(logs.join(' '), /no language server for .*no ace-server entry/); - await missing.stop(); - - const warm = new WarmLsp(() => undefined, { ...base, aceServer: at('studio') }); - try { - warm.edited(page); - const started = Date.now(); - assert.equal(await warm.ask(page, 1, definitionLine), undefined, 'still starting'); - assert.ok(Date.now() - started < 1000); - assert.equal(await warm.ask(page, 10_000, definitionLine), 1); - await warm.ask(page, 10_000, (lsp) => lsp.stop()); - assert.equal(await warm.ask(page, 10_000, definitionLine), undefined, 'dead'); - warm.edited(page); - warm.edited(at('missing.ets')); - } finally { - await warm.stop(); - } -}); - -test('warm server: stop ends a running server and one still starting, and later edits start none', async () => { - const starts: Promise[] = []; - const warm = new WarmLsp( - () => undefined, - { ...base, aceServer: at('clt') }, - (root, options) => { - starts.push(startArktsLsp(root, options)); - return starts[starts.length - 1]; - }, - ); - warm.edited(page); - const running = await starts[0]; - warm.edited(put(at('proj2/entry/src/main/ets/C.ets'), '')); - await warm.stop(); - await assert.rejects(() => running.definition(page, { line: 0, character: 0 }), /not running/); - await assert.rejects(starts[1], /exited|not running|aborted/i); - warm.edited(page); - assert.equal(starts.length, 2); -}); diff --git a/arkui-sem/test/opencode.test.ts b/arkui-sem/test/opencode.test.ts index e35ce1f..246e5ca 100644 --- a/arkui-sem/test/opencode.test.ts +++ b/arkui-sem/test/opencode.test.ts @@ -1,37 +1,21 @@ -// The opencode plugin with a mock client, the heuristic backend and test/fixtures/fake-ace-server.mjs as the language -// server. Tests run in order: later ones depend on what earlier ones reported. +// The opencode plugin with a mock client and the heuristic backend. Tests run in order: later ones depend on +// what earlier ones reported. import assert from 'node:assert/strict'; -import { copyFileSync } from 'node:fs'; import { join } from 'node:path'; import { test } from 'node:test'; import { ArkuiSemPlugin } from '../src/opencode.js'; -import { put, ROOT, tempDir } from './helpers.js'; +import { ROOT, tempDir } from './helpers.js'; const data = tempDir(); process.env.ARKUI_SEM_DATA_DIR = data; process.env.ARKUI_SEM_BACKEND = 'heuristic'; process.env.ARKUI_SEM_CONFIG = join(data, 'no-user-config.json'); // ignore any real user config -copyFileSync( - join(ROOT, 'test', 'fixtures', 'fake-ace-server.mjs'), - put(join(data, 'server', 'out', 'standardIndex', 'index.js'), ''), -); -process.env.ARKUI_SEM_ACE_SERVER = join(data, 'server'); -// No ets-loader inside, so the parser keeps its bundled options. -process.env.ARKUI_SEM_SDK = join(data, 'sdk'); -put(join(data, 'sdk', 'default', 'openharmony', '.keep'), ''); -process.env.ARKUI_SEM_LSP_NODE = process.execPath; -delete process.env.ARKUI_SEM_LSP; - const prompts: any[] = []; -const logs: string[] = []; -const serverLogs = () => logs.filter((m) => m.includes('language server')); const client = { app: { - log: async (opts: { body: { message: string } }) => { - logs.push(opts.body.message); - }, + log: async () => undefined, }, session: { promptAsync: async (opts: unknown) => { @@ -115,25 +99,3 @@ test('arkui_check tool scans a directory', async () => { assert.match(out, /6 finding\(s\), 1 question\(s\)/); assert.match(out, /NotePage\.ets:\d+ NotePage\.note/); }); - -test('the first .ets edit started the language server; dispose stops it and later edits start none', async () => { - for (let waited = 0; serverLogs().length === 0 && waited < 10_000; waited += 20) { - await new Promise((r) => setTimeout(r, 20)); - } - assert.match(serverLogs().join(' '), /language server ready for .*fixtures \(standard\)/); - await hooks.dispose(); - assert.match(await after('edit', { filePath: 'test/fixtures/Counter.ets' }, 's2'), /Counter/); - assert.equal(serverLogs().length, 1); -}); - -test('lsp: off starts no language server', async () => { - const off: any = await ArkuiSemPlugin(input, { lsp: 'off' }); - const output = { title: '', output: 'ok', metadata: {} }; - await off['tool.execute.after']( - { tool: 'edit', sessionID: 's3', callID: 'c', args: { filePath: 'test/fixtures/Counter.ets' } }, - output, - ); - await off.dispose(); - assert.match(output.output, /Counter/); - assert.equal(serverLogs().length, 1); -}); diff --git a/arkui-sem/test/rules/R1.test.ts b/arkui-sem/test/rules/R1.test.ts index 402314e..8525665 100644 --- a/arkui-sem/test/rules/R1.test.ts +++ b/arkui-sem/test/rules/R1.test.ts @@ -759,7 +759,7 @@ test('an Array subclass used without type arguments leaves the element type unkn assert.deepEqual(nestedHits(src), ['rows']); }); -// Owners declared in other files are skipped until cross-file facts come from ace-server. +// V2 owners are resolved only within the file; owners declared in other files are skipped. test('V2: a class declared in another file is skipped', () => { const dir = tempDir(); put(join(dir, 'model', 'User.ets'), "export class User {\n name: string = ''\n}"); diff --git a/docs/PLANS.md b/docs/PLANS.md index 05241f7..bf55954 100644 --- a/docs/PLANS.md +++ b/docs/PLANS.md @@ -13,13 +13,13 @@ The user sets direction; agents plan and execute. Plans live in the repo so ever | Plan | About | |---|---| | [roadmap.md](exec-plans/active/roadmap.md) | the one forward plan: plugin status and P-A roadmap, rule coverage R1–R5 and phases 0–6 (evaluation status: `bench/docs/RESULTS.md`) | -| [coverage-extensions.md](exec-plans/active/coverage-extensions.md) | list rendering (ForEach/LazyForEach keys and sources) and R4 wiring kinds: kinds and PR sequence | ## Completed | Plan | About | |---|---| -| [cross-file-facts.md](exec-plans/completed/cross-file-facts.md) | handoff: project index, cross-file R1 nested write, call-site edges (scan and per-struct search), R2 event unwired, the language server's lifecycle in the plugin (roadmap phase 2) | +| [coverage-extensions.md](exec-plans/completed/coverage-extensions.md) | list rendering (ForEach/LazyForEach keys and sources) and R4 wiring kinds: the kinds and the PR per step | +| [cross-file-facts.md](exec-plans/completed/cross-file-facts.md) | handoff: project index, cross-file R1 nested write, call-site edges (scan and per-struct search), R2 event unwired, the language server's lifecycle in the plugin, since removed (roadmap phase 2) | The dataset plans are in the private bench, `bench/docs/plans/`. diff --git a/docs/design-docs/agentic-plugin.md b/docs/design-docs/agentic-plugin.md index 553c6ae..f112743 100644 --- a/docs/design-docs/agentic-plugin.md +++ b/docs/design-docs/agentic-plugin.md @@ -39,7 +39,7 @@ flowchart LR subgraph ENGINE["Engine (one code path)"] FX["Facts
fact extractor (ohos-typescript tree)"] - RU["Rules R1/R3 (→ R2, R4)"] + RU["Rules R1–R4"] SL["Slice builder
(+ task context, opt-in)"] JU{{"Judge
heuristic · Jev · Clef-flash · Laya-FT · DeepSeek"}} PO["Policy: finding ≥ τ_hi · question ≥ τ_lo"] diff --git a/docs/design-docs/core-beliefs.md b/docs/design-docs/core-beliefs.md index 33f0308..c68e4f1 100644 --- a/docs/design-docs/core-beliefs.md +++ b/docs/design-docs/core-beliefs.md @@ -226,7 +226,7 @@ sequenceDiagram | **R1 Under-reactive state** | Value read in `build()` (directly or via `@Builder` / `ForEach`). Written after construction (handler / async / lifecycle). No reactive path. Includes nested write into a non-`@Observed` / non-`@Trace` class. | Is it meant to change what the user sees? Is it intentionally static/debug/cache? Verdict choice. | 1→2 | | **R2 Ownership mismatch** | Child field initialised from ancestor state. Child writes it. Sync direction ≠ needed direction. | Intent choice: `child_local_copy` / `shared_with_parent` / `parent_display_only` | 1→2 | | **R3 Lifecycle obligation** | Acquire API (from pair table) in `aboutToAppear` / `onPageShow` / handler. No matching release on some path to `aboutToDisappear`. | Is the resource intended to outlive the component (app-scope singleton, EntryAbility)? Is the release elsewhere (owner object)? Severity score. | 1→2 | -| **R4 State that doesn't do its job** *(new; widened from over-reactive state)* | Wiring gaps: a text input that writes a field no input shows while code sets it, or that nothing reads; a selection nothing sets. Over-reactive: decorated state never written after init, **or** large `@State` object mutated at high frequency (cascading re-render). | Wiring gaps: none, decided by the facts alone. Over-reactive: is reactivity needed (e.g. written by a parent / storage)? Perf severity score. | 1→2 | +| **R4 State that doesn't do its job** *(widened from over-reactive state)* | Wiring gaps: a text input that writes a field no input shows while code sets it, or that nothing reads; a selection nothing sets. Over-reactive: decorated state never written after init, **or** large `@State` object mutated at high frequency (cascading re-render). | Wiring gaps: none, decided by the facts alone. Over-reactive: is reactivity needed (e.g. written by a parent / storage)? Perf severity score. | 1→2 | | **R5 Issue→component mapping** *(new)* | Component/file list + summaries (≤255 options). | `choice`: which component most plausibly owns the reported behaviour? | 3 | The over-reactive part of R4 matters for evaluation. It creates *hard negatives* for R1 (and vice versa), so a model can't win by flagging everything. It also matches OpenHarmony's own state-management performance best-practice docs. @@ -322,6 +322,8 @@ LSP facts are less precise than ArkAnalyzer + APAK: no pointer analysis, and clo - For the **IDE path**, LSP facts can drive L2 directly, keeping ArkAnalyzer for CI and full scans. - For **cross-checking**, where LSP and ArkAnalyzer disagree on a fact (e.g. resolved type), mark the slice `fact_conflict` and route it to escalation instead of trusting either. +In the prototype, a client for DevEco's ace-server was built for this role and then removed: no rule needed it, it cost minutes of start-up and GBs of memory per project, and the project index gives the cross-file facts the rules use (decisions.md, "LSP client removed"). + **Role 3 — Baseline arm A in every experiment.** - Arm A = compile + tslinter + codelinter. - Arm B = A + our deterministic R1–R4 preconditions. diff --git a/docs/design-docs/decisions.md b/docs/design-docs/decisions.md index 789231a..aa3580f 100644 --- a/docs/design-docs/decisions.md +++ b/docs/design-docs/decisions.md @@ -25,8 +25,8 @@ `ForEach(this.store.items, …)` counts): an untraced property nothing renders is the point of per-property `@Trace`. Interface-typed objects are flagged only when known to be literals, since they may hold class instances. Writes into a container nested in another (`grid[i][j]`) are flagged. An object-literal initializer counts only for `@Local` (and class fields nothing reassigns), and only while every reassignment also assigns a literal. - Owners not declared in the file are skipped; cross-file owners will come from ace-server (`definition` on the written - property), not from a resolver of our own. + Owners not declared in the file are skipped; cross-file owners are a follow-up through the project index (planned + through ace-server `definition` until the LSP client was removed, see "LSP client removed"). - **Disable comments** (2026-10-13): `// arkui-sem-disable-next-line ` works above the field name, above its decorator lines, and above a single write (that write only, for nested-write findings); R1 and R3 share one parser. - **Fact extractor on ohos-typescript** (2026-11-06): facts come from the syntax tree of OpenHarmony's TypeScript fork @@ -72,10 +72,24 @@ - Results live for one check, keyed by struct. A new caller can only be seen by searching again, so nothing is reused across checks. - An import's local name is not an alias: only ArkTS that doesn't compile can import it from another file. This is the one place where the scan lists a site the search doesn't. - Asynchronous, unlike `callSites`: a refresh during the search is tolerated, not prevented. -- **No overlapping fact sources: call sites come from the index only** (2026-11-11). LSP `references` on a struct would only confirm what `searchCallSites` already finds (complete for the struct asked about), and on legacy ace-server it would need the open-files workaround. Cross-file-facts PR 3 keeps the LSP for what the index can't give: server lifecycle, dependency records at `initialize`, and later field writers and readers (phase 4). -- **The language server in the plugin: lifecycle only, no dependency records, no hvigor map** (2026-11-11, cross-file-facts PR 3; details in its Result). +- **No overlapping fact sources: call sites come from the index only** (2026-11-11). LSP `references` on a struct would only confirm what `searchCallSites` already finds (complete for the struct asked about), and on legacy ace-server it would need the open-files workaround. Cross-file-facts PR 3 keeps the LSP for what the index can't give: server lifecycle, dependency records at `initialize`, and later field writers and readers (phase 4). The LSP part is superseded by "LSP client removed" (2026-11-27). +- **The language server in the plugin: lifecycle only, no dependency records, no hvigor map** (2026-11-11, cross-file-facts PR 3; details in its Result). Superseded by "LSP client removed" (2026-11-27); kept as history. - One ace-server per project, started in the background on the project's first `.ets` edit, sent each edited file, stopped on dispose. A check never waits for it: an answer is asked for within a budget and a missing, starting, slow or dead server gives none. - Setting `lsp`: `auto` (default) or `off`. The server is found as before (`ARKUI_SEM_ACE_SERVER`, else DevEco Studio); no new path settings. - No dependency records at `initialize`. Tried on a two-module project with both servers (standard 26, legacy 6.1.1): with the `oh_modules` links of a synced project, `definition` and `references` cross modules with and without the records; without the links the records don't help, as the server resolves a package name through `oh_modules`. A record without `version` also stops the legacy server at `initialize`. - hvigor's dependency map is not read. By its own freshness rule it counts only when it lists the same modules and the same `oh-package.json5` content as the project's files, so it can't change an answer the index gives: a second source for the same fact. - The server's module list comes from the root `build-profile.json5` (the folder scan stays as the fallback for a folder without one), and the project root is the nearest build profile that lists modules: a module's own `build-profile.json5` was taken for the root before. +- **LSP client removed** (2026-11-27). The ace-server client (`src/lsp/`), the `arkui-sem lsp` command, the plugin's + warm server and the `lsp` setting are gone. The last commit that has them is `7490f1d`; it comes back from git history + if it is ever needed. Supersedes the 2026-11-11 entries on the language server above. + - Why: no rule asked the server anything, yet under the default `lsp: auto` the plugin started it on the first `.ets` + edit: minutes of start-up and several GB of memory on a large project, for nothing (numbers in + `bench/docs/RESULTS.md` and `bench/docs/plans/lsp-edit-timing.md`). + - The cross-file facts that are built (class lookup, call sites) come from the project index (`src/project.ts`), so + the server was never a source the rules relied on ("No overlapping fact sources" above). + - Facts the index doesn't give yet (field writers and readers across files, V2 owners in other files) start from the + index or the ohos-typescript checker. A local comparison found the checker answers the same questions as ace-server + at a fraction of its memory, start-up and query time, and the index costs least. + - No migration (no users yet): a config that still has `"lsp"` gets the unknown-key warning. The parser still needs the SDK: it + finds a DevEco Studio install by its `sdk/default/openharmony` folder, no longer by its `ace-server` folder. + P-A4 on the roadmap, arkui-sem serving LSP diagnostics to the agent, is a different idea and stays. diff --git a/docs/exec-plans/active/coverage-extensions.md b/docs/exec-plans/active/coverage-extensions.md deleted file mode 100644 index edfe2a7..0000000 --- a/docs/exec-plans/active/coverage-extensions.md +++ /dev/null @@ -1,66 +0,0 @@ -# Coverage extensions: list rendering and input wiring (exec plan) - -Goal: catch the state bugs agents write that R1–R3 miss today. Most are in list rendering (`ForEach`, `LazyForEach`) -and in how inputs and selections are wired to state. Each kind below is decided by facts alone (p null, like R2 -event-unwired) and comes with fixtures written from scratch. The working plan with its evidence, per-case analysis and -evaluation steps is private: `bench/docs/plans/coverage-extensions.md`. - -## Kinds - -| Kind | Rule | Bug | Band | -|---|---|---|---| -| nested-write fix text aware of ForEach keys | R1 (text only) | The nested-write fix tells the agent to rebuild the element; done under an unchanged ForEach key, that is the next bug. | unchanged | -| `foreach-key-stale` | R1 | Elements replaced with new objects under an unchanged ForEach key, while the row renders a changed property: ForEach keeps the old row. | finding | -| `foreach-index-key` | R1 | ForEach keyed by position while the items at a position can change: rows keep their old content. | finding (question for some writers) | -| `lazyforeach-source-rebuilt` | R1 | A LazyForEach data source created while drawing, or reassigned: LazyForEach updates only through its listener. | finding or question | -| `input-unbound` | R4 | A text input whose state is written by code but not bound to the input, so the input never shows it. | finding | -| `input-never-read` | R4 | State an input writes that nothing renders or reads. | question | -| `selection-never-written` | R4 | A selection the rows compare against that nothing sets. | question | - -R4 is widened from "over-reactive state" to "state that doesn't do its job" when its first kinds land: wiring gaps -plus the original over-reactive cases. All new kinds are V1-only until ForEach and LazyForEach under V2 are checked. - -## Sequence - -One branch and PR per step, each after an explicit go. - -1. **Refactor (no behaviour change).** Fact model, derived queries and one module per rule; one per-kind entry in - the engine; disable comments that attach to a statement. -2. **Loop fact and `@Builder` parameter reads** (no new rule): one fact per `ForEach`/`LazyForEach` call in a drawing - method (source, key, what the row renders, disable comment above the call). -3. **`foreach-key-stale`** and the ForEach-aware nested-write fix text. -4. **R4 widened**, `input-unbound`, `input-never-read` (needs an input fact; can run in parallel with 2–3). -5. **`foreach-index-key`**, then **`lazyforeach-source-rebuilt`**: two PRs, the second stacked on the first. -6. **`selection-never-written`** (needs 2 and 4). -7. **Cleanup (no behaviour change)**, once every kind above has landed, so code kept for a later kind isn't taken for - dead: unused files, exports and dependencies (`knip`; `tsc --noUnusedLocals --noUnusedParameters` once), duplicated - walks over rows, builders and children, the tech-debt items that are cleanups, and the docs (`ARCHITECTURE.md`, the - code map, roadmap rows). The bench regression and noise check must show no difference, fingerprints included. - -Each PR: offline tests and fixtures; no change in the existing kinds' findings unless the PR is about them. The bench -evaluates each PR on its committed tree (regression over recorded agent sessions, noise over open-source corpora). - -## Status - -- Step 1: done (#32). -- Step 2: done (#33). -- Step 3: done (#34). -- Step 4: done (branch `r4-input-kinds`): `InputFact`, field reads in any method, constant writes, `input-unbound` - (a finding) and `input-never-read` (a question); R4 widened in the roadmap and design docs; demo page `Notes.ets`. -- Step 5a: done (branch `foreach-index-lazy`, stacked on #36): `foreach-index-key` (finding; a question when only - methods move the list); write facts gain the array call, reassignments that keep positions, initial loads and the `if` - arms in build(); loop facts gain their `if` arms. Compacted afterwards (branch `compact-foreach-index-key`): the - source shapes review fixes added for rare code were cut and are listed in the tech-debt tracker. -- Step 5b: done (branch `lazyforeach-source-rebuilt`, stacked on #37): `lazyforeach-source-rebuilt` (a finding when a - state change redraws the source, else a question); loop sources gain the field a getter returns as is, write facts - mark a reassignment that repeats the initializer's call. The empty-`registerDataChangeListener` evidence clause was - left out (tech-debt tracker). -- Step 6: done (branch `selection-never-written`, stacked on #38): `selection-never-written` (a question); loop facts - gain the row's comparisons of a field with the item or index, field facts gain two-way bindings (`$$this.f`, - `this.f!!`) and writes in callbacks another field's initializer registers, component arguments gain the parent field - they pass. -- Step 7: not started. - -## Open decisions - -- None for step 4 (`input-unbound` became a finding; evidence in `bench/docs/plans/coverage-extensions.md`). diff --git a/docs/exec-plans/active/roadmap.md b/docs/exec-plans/active/roadmap.md index f3c4c5a..f73acd6 100644 --- a/docs/exec-plans/active/roadmap.md +++ b/docs/exec-plans/active/roadmap.md @@ -7,22 +7,21 @@ The one forward plan: plugin status and roadmap, rule coverage and phases. Desig The linter lives in `arkui-sem/` (package `arkui-sem` 0.2.0); see `ARCHITECTURE.md` for the layout and `arkui-sem/README.md` for install and usage. Coverage by rule, and what is still missing, is tracked under Rule coverage below. **Status:** -- Rules: R1 undecorated-mutated-rendered, R1 nested-write-unobserved (depth-aware, V1/V2), R1 foreach-key-stale, foreach-index-key and lazyforeach-source-rebuilt (V1, from facts alone), R3 unreleased-resource, R2 event-unwired (shape d, from facts alone, no judge call). The other R2 shapes have a judge slice (used by the bench) but are not emitted yet. +- Rules: R1 undecorated-mutated-rendered, R1 nested-write-unobserved (depth-aware, V1/V2), R1 foreach-key-stale, foreach-index-key and lazyforeach-source-rebuilt (V1, from facts alone), R3 unreleased-resource, R2 event-unwired (shape d, from facts alone, no judge call), R4 input-unbound, input-never-read and selection-never-written (V1, from facts alone). The other R2 shapes have a judge slice (used by the bench) but are not emitted yet. - Backends: Jev, Clef, Clef-flash (also through OpenRouter: `or-clef`, `or-clef-flash`), DeepSeek flash (structured output), heuristic, Laya. The fallback chain is not implemented. - Tests: `npm test` (offline). The plugin and its `arkui_check` tool load in opencode 1.18.30 and in DevEco Code 0.1.12 (an opencode fork; plugin under `.deveco/`; 0.2.x refuses to run outside Mainland China). - DevEco demo (2026-10-08, `sandbox/demo/DEMO.md`): Clef flagged the agent's nested write, the idle gate re-sent it for the old button, and the agent fixed both. The DevEco TUI hides tool output, so the demo prompt asks the agent to quote findings verbatim. - Live opencode runs 1–4 (logs removed 2026-10-08; run 4 called DeepSeek and found the @Observed-only false negative that led to the depth-aware rule). **Known limits:** -- **The language server is not used by any rule.** The plugin starts ace-server on the first `.ets` edit, keeps it in step with the edits and stops it on dispose (`lsp: auto | off`); the facts it is meant for (field writers and readers, V2 owners in other files) are phases 3–4. -- **Mostly single-file analysis.** No aliasing. Across files: class lookups for the V1 nested write, and call sites for R2 event-unwired; the parent-side facts the other R2 shapes need are missing. +- **Mostly single-file analysis.** No aliasing. Across files: class lookups for the V1 nested write, child components and builders for foreach-key-stale, and call sites for R2 event-unwired; the parent-side facts the other R2 shapes need are missing. - **The heuristic judge's probabilities are placeholders.** - **The gate under `opencode run`.** The non-interactive run may exit at idle before the follow-up is processed [I]. Use the TUI or `opencode serve` + SDK for gate tests. --- ## Prototype roadmap -P-A2…P-A4 (intent tool, cross-file facts, LSP) are broken down further under Rule coverage below. +P-A2 and P-A3 (intent tool, cross-file facts) are broken down further under Rule coverage below. | Step | Deliverable | Effort | Exit criterion | |---|---|---|---| @@ -48,14 +47,14 @@ The localizer (P5) becomes an `arkui_locate(issue_text)` tool. ## Rule coverage -Status as of 2026-11-10. Scope: ArkEval v1 category 1, "UI state desynchronization" (plus R3 for category 3). +Status as of 2026-11-27. Scope: ArkEval v1 category 1, "UI state desynchronization" (plus R3 for category 3). Background: `docs/design-docs/core-beliefs.md` §3–§4 (rungs, rule families, architecture), `docs/design-docs/agentic-plugin.md`. ### Rules (RN) | Rule | Name | Detects (facts) | Question for the judge or agent | Status | |---|---|---|---|---| -| **R1** | Under-reactive state | A value rendered in `build()` and written after construction with no reactive path. Kinds: an undecorated field, a nested write the decorator can't see, new objects under an unchanged ForEach key, and other items at the positions of an index-keyed ForEach. | Q_R1: is it UI state or intentionally static? Verdict, severity. | Implemented, single file | +| **R1** | Under-reactive state | A value rendered in `build()` and written after construction with no reactive path. Kinds: an undecorated field, a nested write the decorator can't see, new objects under an unchanged ForEach key, other items at the positions of an index-keyed ForEach, and a LazyForEach data source created while drawing or reassigned. | Q_R1: is it UI state or intentionally static? Verdict, severity. | Implemented. Across files through the project index: V1 nested-write owners, ForEach rows in child components and builders; the rest single file (coverage table below) | | **R2** | Ownership mismatch | A child field initialised from parent state, where the sync direction the code gives ≠ the direction needed. | Q_R2: `child_local_copy` / `shared_with_parent` / `parent_display_only`. The engine maps intent × V1/V2 → decorator. | Shape d (event unwired) implemented, facts only. Shapes a–c: Q_R2 slice + spec cards, evaluated in the bench (`bench/docs/RESULTS.md`), not emitted by the plugin | | **R3** | Lifecycle obligation | A resource acquired with no release in `aboutToDisappear`. | Q_R3: app-lifetime? Released elsewhere? | Implemented (category 3): timers, listeners, constant-event `on`/`off`, register/subscribe pairs, helper-called releases. Evaluated in the bench (`bench/docs/RESULTS.md`) | | **R4** | State that doesn't do its job | Wiring gaps: a text input that writes a field no input shows while code sets it (`input-unbound`), or that nothing reads (`input-never-read`); a selection nothing sets. Over-reactive state: decorated state never written after init, or a large `@State` mutated at high frequency. | Wiring kinds: none, facts alone (`input-unbound` a finding, the others questions). Over-reactive: is reactivity needed? Perf severity. | `input-unbound` (finding), `input-never-read` and `selection-never-written` (questions) implemented, V1; over-reactive not started | @@ -76,34 +75,34 @@ The compiler already rejects writes to a V2 `@Param` and `@Link` without `$` (ca ### Coverage table -✅ done · ⚠️ partial · ❌ missing. The LSP column assumes the spike (phase 1) passes. +✅ done · ⚠️ partial · ❌ missing. -| Item | Today | With an LSP server | Left after LSP | -|---|---|---|---| -| R1 undecorated field, mutated and rendered (V1/V2) | ✅ Facts + Q_R1; MDP runs in the bench | – | Intent verdict (judge/agent) | -| R1 ForEach: elements replaced under an unchanged key (`foreach-key-stale`) | ✅ V1, single file plus child components and builders across files; facts alone | – | Aliases beyond one local, V2 | -| R1 ForEach keyed by index over changing items (`foreach-index-key`) | ✅ V1, single file; facts alone (a question when only methods move the list) | – | Sources written by a parent (`@Prop`, `@Link`), V2 | -| R1 LazyForEach source rebuilt or reassigned (`lazyforeach-source-rebuilt`) | ✅ V1, single file; facts alone (a finding when a state change redraws the source) | – | Cached or switched sources, nested holders, parent writes, V2 | -| R4 wiring: `input-unbound`, `input-never-read` | ✅ V1, single file; facts alone (`input-unbound` a finding, `input-never-read` a question) | – | Path writes (`this.form.name = value`), V2 | -| R4 wiring: `selection-never-written` | ✅ V1, single file; facts alone (a question) | – | Rows in a `@Builder`, comparisons with a converted index (`index.toString()`) | -| R1 nested write, V1 (depth ≥ 2) | ✅ Across files (project index) | – | Aliasing (`const it = this.list[i]; it.x = …`): dataflow in the fact extractor | -| R1 nested write, V2 (class not `@ObservedV2`) | ⚠️ Same file; cross-file through ace-server (follow-up) | ✅ Cross-file class lookup | – | -| `@Trace` per property | ⚠️ Same file (mutated + rendered property, inherited `@Trace` included); cross-file through ace-server (follow-up) | ✅ Class (LSP) + property decorator (our parse) | Eval | -| `@Observed` / `@ObjectLink` children | ✅ Across files: imported children the parent calls (project index) | – | – | -| `@Track` | ❌ | Class lookup only | Rule design | -| R2 facts: call-site edges | ✅ Project index: a scan of the project, or a text search for one struct | – (index only, no second source) | – | -| R2-a | ❌ | ✅ Detected (`references` + `documentHighlight` write kinds) | Judge: snapshot intended? | -| R2-d | ✅ Call sites from the project index, V1 and V2 | – | Positives to measure it on (phase 5 mutations) | -| R2-f | ❌ | ✅ Facts | Fix choice | -| R2-b / R2-c | ❌ | Evidence (sibling readers, dialog-ness) | Intent: judge, or agent via `arkui_ownership_intent` | -| Read/write kind and context | Syntax tree (ohos-typescript) | Read/write kind: `documentHighlight` | Context (handler/`build`/lifecycle/async), reach via `@Builder`/`ForEach`: the fact extractor | -| String-keyed links: AppStorage/LocalStorage keys, `@Provide`/`@Consume` aliases, `@Watch` names, `@Monitor` paths | ❌ | ❌ | Own key index (grep-level) | -| Derived state: `@Watch`, `@Monitor`, `@Computed` | ❌ | Locating only | New rule + dataset (MDP doesn't cover them) | -| R3 unreleased resource | ✅ | Release in another file or owner object | Judge: app-lifetime or released elsewhere | -| R4 over-reactive state | ❌ | "Never written" via `references` | Rule; perf judgment | -| Imports by package name across modules | ✅ Project index (`src/project.ts`): `oh-package.json5` local dependencies and `build-profile.json5` modules; `Index.ets` re-exports | Resolved by the server only in a synced project (`oh_modules` links); dependency records at `initialize` change nothing (decisions.md) | `oh_modules` packages, namespace imports (`import * as`) | - -**LSP fit:** good for the per-edit plugin, where the server stays warm and runs a few queries per edit. Poor for bench scale (thousands of items and sequential `references` calls, warm-up nondeterminism), so the bench uses a one-pass index instead. +| Item | Today | Left | +|---|---|---| +| R1 undecorated field, mutated and rendered (V1/V2) | ✅ Facts + Q_R1; MDP runs in the bench | Intent verdict (judge/agent) | +| R1 ForEach: elements replaced under an unchanged key (`foreach-key-stale`) | ✅ V1, single file plus child components and builders across files; facts alone | Aliases beyond one local, V2 | +| R1 ForEach keyed by index over changing items (`foreach-index-key`) | ✅ V1, single file; facts alone (a question when only methods move the list) | Sources written by a parent (`@Prop`, `@Link`), V2 | +| R1 LazyForEach source rebuilt or reassigned (`lazyforeach-source-rebuilt`) | ✅ V1, single file; facts alone (a finding when a state change redraws the source) | Cached or switched sources, nested holders, parent writes, V2 | +| R4 wiring: `input-unbound`, `input-never-read` | ✅ V1, single file; facts alone (`input-unbound` a finding, `input-never-read` a question) | Path writes (`this.form.name = value`), V2 | +| R4 wiring: `selection-never-written` | ✅ V1, single file; facts alone (a question) | Rows in a `@Builder`, comparisons with a converted index (`index.toString()`) | +| R1 nested write, V1 (depth ≥ 2) | ✅ Across files (project index) | Aliasing (`const it = this.list[i]; it.x = …`): dataflow in the fact extractor | +| R1 nested write, V2 (class not `@ObservedV2`) | ⚠️ Same file | Cross-file class lookup through the project index | +| `@Trace` per property | ⚠️ Same file (mutated + rendered property, inherited `@Trace` included) | Cross-file class lookup through the project index; eval | +| `@Observed` / `@ObjectLink` children | ✅ Across files: imported children the parent calls (project index) | – | +| `@Track` | ❌ | Class lookup; rule design | +| R2 facts: call-site edges | ✅ Project index: a scan of the project, or a text search for one struct | – | +| R2-a | ❌ | Detection (writes to the passed field); judge: snapshot intended? | +| R2-d | ✅ Call sites from the project index, V1 and V2 | Positives to measure it on (phase 5 mutations) | +| R2-f | ❌ | Facts; fix choice | +| R2-b / R2-c | ❌ | Evidence (sibling readers, dialog-ness); intent: judge, or agent via `arkui_ownership_intent` | +| Read/write kind and context | Syntax tree (ohos-typescript) | Context (handler/`build`/lifecycle/async), reach via `@Builder`/`ForEach`: the fact extractor | +| String-keyed links: AppStorage/LocalStorage keys, `@Provide`/`@Consume` aliases, `@Watch` names, `@Monitor` paths | ❌ | Own key index (grep-level) | +| Derived state: `@Watch`, `@Monitor`, `@Computed` | ❌ | New rule + dataset (MDP doesn't cover them) | +| R3 unreleased resource | ✅ | Release in another file or owner object; judge: app-lifetime or released elsewhere | +| R4 over-reactive state | ❌ | "Never written" (writers across files); rule; perf judgment | +| Imports by package name across modules | ✅ Project index (`src/project.ts`): `oh-package.json5` local dependencies and `build-profile.json5` modules; `Index.ets` re-exports | `oh_modules` packages, namespace imports (`import * as`) | + +**Fact sources:** cross-file facts come from the project index (`src/project.ts`), in the plugin and the bench alike. An ace-server client was built and removed (decisions.md, "LSP client removed"); facts the index doesn't give yet (field writers and readers across files, V2 owners in other files) start from the index or the ohos-typescript checker. ### Plan @@ -115,17 +114,8 @@ Each phase starts only after an explicit go. - [x] MDP datasets and R1 recall/precision runs (bench) - [ ] Judge fallback chain Jev → Clef-flash → Clef → DeepSeek flash (`backend` as a list) -#### Phase 1: LSP spike (decides how much LSP can do) -- [ ] Pick a headless ArkTS language server -- [ ] Probe on `sandbox/demo`: - - [x] `references` on a struct: works, and `definition` works per call site (ace-server 26 and DevEco 6.1.1). Call hierarchy doesn't list struct calls in either direction, so call sites come from our own walk (cross-file-facts PR 2b) and stay there: the LSP doesn't add a second source for them - - [ ] `references` on a child field: does it return the call-site property? (**decisive probe**) - - [ ] `documentHighlight` Write kinds - - [ ] `typeDefinition` across files - - [ ] `references` on an `@Event` -- [ ] Time the probes on one module of a large real project -- [ ] Score against the E0 fact sample (fact extractor vs LSP; `bench/docs/evaluation-method.md`) -- [ ] Decide: LSP behind `FactExtractor` for the plugin, or grep for struct names + our parse +#### Phase 1: LSP spike (dropped) +Dropped with the LSP client (decisions.md, "LSP client removed"). The probes run showed `references` and `definition` work on struct call sites, but call sites come from the project index and no rule needed the server. The open questions (who writes or reads a child field across files, write kinds, types across files) move to phases 2–3, against the index or the checker. #### Phase 2: cross-file facts - [x] Cross-file class resolution: a project index (`src/project.ts`) passed to the rules, in the plugin and the bench alike @@ -158,7 +148,7 @@ Each phase starts only after an explicit go. - [x] R3 mutants (release line deleted) + real candidates, a labelled subset reviewed (bench) - [ ] End to end: an opencode "edit dialog" run in `sandbox/demo` (does the agent declare intent; is the code correct) -#### Phase 6: left after LSP (later) +#### Phase 6: later - [ ] Aliasing / dataflow in the fact extractor (ours; ArkAnalyzer only if it proves suitable) - [ ] Derived-state rule (`@Watch` / `@Monitor` / `@Computed`) + dataset - [ ] `@Track` rule diff --git a/docs/exec-plans/completed/coverage-extensions.md b/docs/exec-plans/completed/coverage-extensions.md new file mode 100644 index 0000000..4b93542 --- /dev/null +++ b/docs/exec-plans/completed/coverage-extensions.md @@ -0,0 +1,40 @@ +# Coverage extensions: list rendering and input wiring (exec plan) + +Goal: catch the state bugs agents write that R1–R3 miss today. Most are in list rendering (`ForEach`, `LazyForEach`) +and in how inputs and selections are wired to state. Each kind below is decided by facts alone (p null, like R2 +event-unwired) and comes with fixtures written from scratch. The working plan with its evidence, per-case analysis and +evaluation steps is private: `bench/docs/plans/coverage-extensions.md`. + +## Kinds + +| Kind | Rule | Bug | Band | +|---|---|---|---| +| nested-write fix text aware of ForEach keys | R1 (text only) | The nested-write fix tells the agent to rebuild the element; done under an unchanged ForEach key, that is the next bug. | unchanged | +| `foreach-key-stale` | R1 | Elements replaced with new objects under an unchanged ForEach key, while the row renders a changed property: ForEach keeps the old row. | finding | +| `foreach-index-key` | R1 | ForEach keyed by position while the items at a position can change: rows keep their old content. | finding (question for some writers) | +| `lazyforeach-source-rebuilt` | R1 | A LazyForEach data source created while drawing, or reassigned: LazyForEach updates only through its listener. | finding or question | +| `input-unbound` | R4 | A text input whose state is written by code but not bound to the input, so the input never shows it. | finding | +| `input-never-read` | R4 | State an input writes that nothing renders or reads. | question | +| `selection-never-written` | R4 | A selection the rows compare against that nothing sets. | question | + +R4 is widened from "over-reactive state" to "state that doesn't do its job": wiring gaps plus the original +over-reactive cases. All the new kinds are V1-only until ForEach and LazyForEach under V2 are checked. + +## Result + +Every kind above landed, one PR per step, each with offline tests and fixtures; the bench evaluated each on its +committed tree (private: `bench/docs/plans/coverage-extensions.md`). + +| Step | PR | +|---|---| +| Refactor: fact model, derived queries, one module per rule, one engine entry per kind | #32 | +| Loop fact and `@Builder` parameter reads (no new rule) | #33 | +| `foreach-key-stale` and the ForEach-aware nested-write fix text | #34 | +| R4 widened, `input-unbound`, `input-never-read`; demo page `Notes.ets` | #36 | +| `foreach-index-key`; compacted in #41 (rare source shapes cut, listed in the tech-debt tracker) | #37 | +| `lazyforeach-source-rebuilt` | #38 | +| `selection-never-written` | #39 | +| Cleanup: `knip` and `tsc --noUnusedLocals --noUnusedParameters` found no dead code, unused file or dependency; the duplicated walks and the cleanup-only tracker items were too small to refactor, so the code is unchanged; stale docs fixed | #43 (with the LSP removal) | + +Limits of each kind are in `docs/exec-plans/tech-debt-tracker.md`; coverage by rule is in +`docs/exec-plans/active/roadmap.md`. diff --git a/docs/exec-plans/tech-debt-tracker.md b/docs/exec-plans/tech-debt-tracker.md index 55fd599..211a501 100644 --- a/docs/exec-plans/tech-debt-tracker.md +++ b/docs/exec-plans/tech-debt-tracker.md @@ -1,7 +1,7 @@ # Tech debt and known gaps - Cross-file lookups (project index) follow relative imports, project packages and `Index.ets` re-exports; not `oh_modules` packages or namespace imports (`import * as m`), so a class or `@ObjectLink` child reached that way is missed and a correct parent write is flagged. An imported child counts only when the parent file calls it. -- V2 nested writes are judged only when the owner of the written property (and each class it extends) is declared in the file; owners from other files or of unknown type are skipped, so a missing `@ObservedV2` or `@Trace` there goes unreported. Cross-file owners are planned through ace-server `definition` on the written property. +- V2 nested writes are judged only when the owner of the written property (and each class it extends) is declared in the file; owners from other files or of unknown type are skipped, so a missing `@ObservedV2` or `@Trace` there goes unreported. Cross-file owners are a follow-up through the project index. - V1 nested writes don't use the V2 owner logic: no inherited `@Observed`, and an owner of unknown type, or from another file the project index cannot resolve, is flagged, where V2 skips it. - Plain objects are known only from initializers: arrays of literals (`User[] = [{…}]`) and literals assigned later are not detected, and an interface-typed value from a factory call is skipped (it may be a class instance). - Type inference covers `new X(…)` and object-literal initializers only (not factory calls or `as` casts); an inline object type is followed one level deep; a type alias of a class (`type U = User`) is not resolved, so writes through it are skipped. @@ -46,7 +46,7 @@ - The `if` arms around the loop exclude a write in the other arm also inside an outer loop row, a @Builder called more than once or a `Repeat` row, where another row or call takes that arm at the same time: it goes quiet. The same holds for `lazyforeach-source-rebuilt`, which shares the arms. Reads in a `Repeat(…).each` or `.template` row - are not marked as inside a loop (`inForEach`), as before #37. + are not marked as inside a loop (`inForEach`). - `&&` is not split into arms (`this.ready && this.a`). - R4 input kinds are V1 only and see whole-field writes of the typed text (`this.f = value`), in the onChange or one method only inputs use and the onChange hands the text to: a path write (`this.form.name = value`) is not followed, @@ -68,28 +68,12 @@ - The project index caches facts by mtime only (an edit within the same mtime tick, or a tool that keeps mtimes, serves stale facts), and cached `FileFacts` are mutable and shared across checks; size + mtime keys and `readonly` fact types would close both. -- The parser reads the SDK once per process (`defaultParser()`) and ignores the SDK passed to the LSP client. The plugin - passes none, so both use the same lookup there; only `arkui-sem lsp --sdk` can differ. - Struct getters and setters are not scanned: a write in `set v(x) { this.a = x }` and reads through a getter used in `build()` are not recorded. - `v2Gap` handles index writes (unknown container, nested container, container in a plain object, other calls) as separate branches; one rule (walk up to the nearest non-container owner, then classify it) would cover them. - Only the undecorated-mutated-rendered kind of R1 is measured with a model; nested-write has only a small offline contract benchmark (`bench/docs/plans/r1-nested.md`). - Writes inside functions in field initializers (arrow-function properties, listener objects) are not scanned. - Comparing with DevEco's built-in `arkts_check` needs DevEco Studio 6.0+ and `DEVECO_HOME`, not installed yet (deferred). -- The language server in the plugin (`arkui-sem/src/lsp/warm.ts`): - - No rule asks it anything: it is started, sent each edited file and stopped. `WarmLsp.ask` is the one way in for the - facts planned for it (field writers and readers, V2 owners in other files); R3 releases in helpers and R4 writers - across modules are still missing. - - With `lsp: auto` it starts on the first edit whether or not anything will ask it; on a large project that is minutes - of start-up and several GB (numbers: `bench/docs/RESULTS.md`). - - One start per project and plugin lifetime: a server that failed to start or died is not started again. - - A file is sent as it is on disk when the edit tool returns; files changed outside the agent's edit tools are not sent. - - opencode ends the server through the plugin's `dispose`. A killed opencode process skips it, and whether the - server then exits on its closed stdin was not checked. -- ace-server follows an import by package name through the `oh_modules` link that a DevEco sync or `ohpm install` - creates, and we run neither. In a project without the links it stops at the import; with them it reaches the other - module, with or without dependency records at `initialize` (both servers; decisions.md). The rules resolve such - imports through the project index (`src/project.ts`). - Call-site edges (`ProjectIndex.callSites`): - The time budget stops the scan between files, but listing the project can't be interrupted: on a cold OS file cache the listing alone can exceed the budget. @@ -140,8 +124,6 @@ - Sites are ordered by file path, the scan's by directory listing. - `declaration()` follows `import { X } from './G'` when `G` only imports `X` and doesn't export it, which ArkTS rejects. The scan lists such a site; the search doesn't look for `G`'s local names. -- On legacy ace-server (DevEco 6.x) `references` and `callers` see usages in open files only (queried and edited ones), so - usages in other files are missed; the standard server (DevEco 26+) searches the whole project. - R1 "rendered" follows `this.m(…)` calls and getter reads from `build()` within the component only: a helper reached through a local alias, passed as a function value, or in another class or file doesn't count. - Handler reads (`BuildRead.inHandler`, `ets/callbacks.ts`) are decided by syntax, not by what the callee does: an