From 9319fce783f69c319536e339508a1a79759dcfa9 Mon Sep 17 00:00:00 2001 From: Dzuhaib Date: Sun, 25 Oct 2026 00:39:41 +0500 Subject: [PATCH 1/3] fix(analysis): repair host discovery and evidence coverage Consolidate Qoder asset and session home resolution, document --qoder-home, and prefer an existing ~/.qoder-cn before ~/.qoder. Fetch 30/90/180-day history windows independently, expose commit limits, truncation, and coverage, and downgrade the review matrix when any window is incomplete. Recognize root and nested AGENTS.md and CLAUDE.md carriers, exclude scratch directories from suggested scopes, discover tracked npm and Just validation gates, and include root AGENTS.md in Claude Rules. Add a real lead/session binding regression while preserving the conflict path, and make Windows fixtures portable with directory junctions, isolated DSH home state, and clean child-process shutdown. Spec: docs/specs/2026-10-24-harness-analysis-defects.md (Stories #212, #195, #164). Test: npm test (1765 passed, 30 skipped); npm run harness-studio-apps:test (3 files passed). Co-authored-by: opencode (DeepSeek V4.1 Flash) --- docs/ARCHITECTURE.md | 6 +- .../2026-10-24-harness-analysis-defects.md | 89 ++++++++++ .../test/test_file_explorer.mjs | 15 +- scripts/agent-customize/providers/claude.mjs | 1 + scripts/agent-customize/providers/qoder.mjs | 51 +----- scripts/agent-lint/host-instructions.mjs | 3 +- scripts/coding-agent-practices/inventory.mjs | 11 +- scripts/core-change-watch/evidence-pack.mjs | 32 +++- .../core-change-watch/git-history-profile.mjs | 50 ++++-- scripts/core-change-watch/project-profile.mjs | 55 +++++- .../harness-analysis/evidence-bundle/cli.mjs | 1 + scripts/harness-analysis/report-run.mjs | 1 + scripts/harness-analysis/task-loop-source.mjs | 1 + scripts/harness-quickstart/cli.mjs | 2 +- scripts/host-support/qoder-home.mjs | 65 ++++++++ scripts/session-analysis/analyzer.mjs | 2 +- scripts/session-analysis/platforms/qoder.mjs | 3 +- test/agents/agent-asset-baseline.test.mjs | 6 +- test/agents/agent-asset-integrity.test.mjs | 5 +- test/agents/agent-customize-dsh.test.mjs | 18 +- test/agents/agent-customize.test.mjs | 40 ++++- test/agents/agent-lint.test.mjs | 3 +- .../coding-agent-practices-inventory.test.mjs | 35 +++- .../core-change-watch-scope.test.mjs | 5 +- test/governance/core-change-watch.test.mjs | 156 +++++++++++++++++- test/governance/workspace-topology.test.mjs | 8 +- .../antigravity-plugin-artifact.test.mjs | 2 +- test/plugins/plugin-lifecycle.test.mjs | 5 +- .../better-harness-evidence-bundle.test.mjs | 48 +++++- .../harness-report-render-cli.test.mjs | 5 +- test/sessions/session-analysis.test.mjs | 43 ++++- test/support/path-links.mjs | 37 +++++ 32 files changed, 683 insertions(+), 121 deletions(-) create mode 100644 docs/specs/2026-10-24-harness-analysis-defects.md create mode 100644 scripts/host-support/qoder-home.mjs create mode 100644 test/support/path-links.mjs diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 842a92a5..c0091f94 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -90,8 +90,10 @@ the target journey, contract, evidence, governance, and DX-measurement system. cross-profile host-id and alias conflicts. `profile-builders.mjs` owns typed construction helpers for evidence, operations, surfaces, and steps rather than duplicating their invariants, and `profiles.mjs` only composes the - registry. Every provider-specific filesystem root read outside the selected - workspace must have an explicit `inventoryHomeRoutes` entry, including state + registry. `qoder-home.mjs` owns the shared Qoder asset/session home precedence + used by analysis and inventory consumers. Every provider-specific filesystem + root read outside the selected workspace must have an explicit + `inventoryHomeRoutes` entry, including state files, shared caches, and compatibility roots such as a user-level `.agents/` directory. Each primary and secondary route declares its provider option, an isolated path relative to `--host-home`, and a redacted safe diff --git a/docs/specs/2026-10-24-harness-analysis-defects.md b/docs/specs/2026-10-24-harness-analysis-defects.md new file mode 100644 index 00000000..132ef386 --- /dev/null +++ b/docs/specs/2026-10-24-harness-analysis-defects.md @@ -0,0 +1,89 @@ +# Harness analysis host, history, instruction, and lead-binding defects + +## Traceability + +- Spec ID: 2026-10-24-harness-analysis-defects +- Story: QoderAI/better-harness#212, QoderAI/better-harness#195, QoderAI/better-harness#164 +- Status: Implemented + +## Intent + +Repair the confirmed analysis defects found during Windows-hosted validation. The +defects fall into five groups: Qoder home discovery and CLI documentation, +bounded history windows that collapse to the same sample, instruction and gate +discovery gaps, an incomplete Claude Rules projection, and a missing regression +for the already-correct lead/session binding path. The change also brings the +file-explorer fixture in line with Windows environment and stream-lifecycle +behavior. + +This work prefers honest coverage metadata over confident-looking but incomplete +data. A truncated or low-confidence history window must be visible as such, and +analysis must continue to fail closed when real binding conflicts exist. + +## Acceptance scenarios + +- AC-1: `--qoder-home` remains explicit and wins over environment/defaults, and + help for `harness analyze`, `harness evidence-bundle`, and task-loop source + advertises the option. `QODER_HOME` is honored by the Qoder session analyzer, + including a `.qoder-cn` asset home, and the default selects an existing + `~/.qoder-cn` before `~/.qoder`. +- AC-2: history windows use independent git ranges instead of slicing one global + commit list, so 30/90/180-day windows can report different commit counts and + hotspots. Every window exposes its commit limit, truncation state, and coverage + status. +- AC-3: `history-window-coverage` is `review` rather than `ready` when history + confidence is low or any window is truncated, while retaining the existing + ready behavior for complete high/medium-confidence history. +- AC-4: instruction analysis recognizes root and nested `AGENTS.md` and + `CLAUDE.md` carriers, excludes scratch directories from suggested scopes, and + reports carrier kinds without changing the existing density thresholds. +- AC-5: evidence packs expose project-owned package and Just gates, and the + `validate-impact` action includes those exact commands when available. +- AC-6: Claude project Rules inventory includes a root `AGENTS.md` compatibility + entry without duplicating `CLAUDE.md`. +- AC-7: an integration test proves an injected session population keeps the lead + lane available and carries `sessionBinding`, while the genuine conflict test + still downgrades the lead to `SESSION_POPULATION_BINDING_MISMATCH`. +- AC-8: the file-explorer test sets both `HOME` and `USERPROFILE` on Windows and + shuts down without asserting while child-process pipes are still closing. + +## Non-goals + +- Adding new host adapters or changing host support levels. +- Replacing the bounded `maxCommits` safety limit or adding unbounded history + scans. +- Redesigning report/Canvas UI or changing the binding reconciliation contract. +- Treating scratch or generated files as instruction carriers. + +## Plan and tasks + +1. Align Qoder home resolution across asset and session analysis, and document + the accepted host-home option. +2. Fetch and filter each history window independently, add coverage metadata, + and make the review matrix consume it. +3. Extend instruction carriers, scope filtering, and project gate extraction. +4. Add root `AGENTS.md` to the Claude Rules inventory. +5. Add a lead/session binding integration regression and keep the conflict test. +6. Make the file-explorer fixture portable and close child streams explicitly. +7. Run focused tests, then the broader affected suites. + +## Test and review evidence + +- `test/agents/coding-agent-practices-inventory.test.mjs` covers Qoder asset + homes, `QODER_HOME` separation, and an implicit `.qoder-cn` home. +- `test/agents/agent-customize.test.mjs` covers Qoder provider `QODER_HOME` + resolution and the Claude Rules root `AGENTS.md` compatibility entry. +- `test/sessions/session-analysis.test.mjs` exercises Qoder session roots from + `QODER_HOME` and the `~/.qoder-cn` default. +- `test/governance/core-change-watch.test.mjs` covers independent history + windows, truncation downgrade, instruction carriers, scratch-scope exclusion, + and project gates in the `validate-impact` action. +- `test/reporting/better-harness-evidence-bundle.test.mjs` exercises the real + Claude lead/session binding path and keeps the genuine conflict regression. +- `packages/harness-studio-apps/test/test_file_explorer.mjs` passes on Windows + with `HOME`/`USERPROFILE` isolation and orderly child shutdown. +- `test/support/path-links.mjs` keeps Windows fixtures portable with directory + junctions and skips only the two file-symlink cases when the host denies them. +- The DSH explicit-root fixture isolates `HOME`/`USERPROFILE`, so external roots + are not accidentally classified as user-home paths. +- Full `npm test` on 2026-10-25: 1765 passed, 30 skipped, 0 failed. diff --git a/packages/harness-studio-apps/test/test_file_explorer.mjs b/packages/harness-studio-apps/test/test_file_explorer.mjs index c4e66c5b..7eceb667 100644 --- a/packages/harness-studio-apps/test/test_file_explorer.mjs +++ b/packages/harness-studio-apps/test/test_file_explorer.mjs @@ -41,6 +41,7 @@ function startBackend() { env: { ...process.env, HOME: HOME_DIR, + USERPROFILE: HOME_DIR, KIROCREW_HOME: HOME_DIR, KIROCREW_PROXY_SECRET: SECRET, PORT: String(PORT), @@ -72,6 +73,16 @@ async function call(path) { return fetch(`http://127.0.0.1:${PORT}${path}`, { headers: { 'X-KiroCrew-Proxy': sig } }) } +async function stopBackend(backend) { + if (backend.exitCode === null && backend.signalCode === null) { + const exited = new Promise((resolve) => backend.once('exit', resolve)) + backend.kill('SIGTERM') + await Promise.race([exited, new Promise((resolve) => setTimeout(resolve, 2000))]) + } + backend.stdout?.destroy() + backend.stderr?.destroy() +} + const child = startBackend() try { @@ -112,8 +123,8 @@ try { r = await call(`${BASE}/nope`) check('unknown route -> 404', r.status === 404, `got ${r.status}`) } finally { - child.kill('SIGTERM') + await stopBackend(child) } console.log(failures === 0 ? '\nALL PASS' : `\n${failures} FAILURES`) -process.exit(failures === 0 ? 0 : 1) +process.exitCode = failures === 0 ? 0 : 1 diff --git a/scripts/agent-customize/providers/claude.mjs b/scripts/agent-customize/providers/claude.mjs index 7a48300a..52307d57 100644 --- a/scripts/agent-customize/providers/claude.mjs +++ b/scripts/agent-customize/providers/claude.mjs @@ -167,6 +167,7 @@ async function collectProjectRules(workspace, sourceLabel, claudeRoot = path.joi "claude-project", ], [path.join(workspace, "CLAUDE.local.md"), "CLAUDE.local.md", "claude-local", "claude-local"], + [path.join(workspace, "AGENTS.md"), "AGENTS.md", "agents-md-compat", "agents-md-compat"], ]; const files = []; const visited = new Set(); diff --git a/scripts/agent-customize/providers/qoder.mjs b/scripts/agent-customize/providers/qoder.mjs index 66df1589..1e3e6d41 100644 --- a/scripts/agent-customize/providers/qoder.mjs +++ b/scripts/agent-customize/providers/qoder.mjs @@ -1,6 +1,9 @@ -import os from "node:os"; import path from "node:path"; +import { + resolveQoderAssetHome, + resolveQoderSharedClientCacheRoot, +} from "../../host-support/qoder-home.mjs"; import { expandHome, normalizeWorkspace, pathExists } from "../../session-analysis/index.mjs"; import { MANAGE_TABS } from "../constants.mjs"; import { @@ -32,50 +35,6 @@ import { const QODER_PLUGIN_MANIFEST = [".qoder-plugin", "plugin.json"]; -function defaultQoderHome() { - return path.join(os.homedir(), ".qoder"); -} - -function defaultQoderSharedClientCacheRoot() { - if (process.platform === "win32") { - const appData = process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming"); - return path.join(appData, "Qoder", "SharedClientCache"); - } - if (process.platform === "darwin") { - return path.join(os.homedir(), "Library", "Application Support", "Qoder", "SharedClientCache"); - } - const xdgConfig = process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"); - return path.join(xdgConfig, "Qoder", "SharedClientCache"); -} - -function looksLikeQoderAssetHome(candidate) { - const base = path.basename(String(candidate ?? "")).toLowerCase(); - return base === ".qoder" || base === "qoder"; -} - -function resolveQoderAssetHome(options = {}) { - const explicit = options.qoderHome ?? options["qoder-home"]; - if (explicit) return path.resolve(expandHome(explicit)); - const environmentHome = process.env.QODER_HOME; - if (environmentHome && looksLikeQoderAssetHome(environmentHome)) { - return path.resolve(expandHome(environmentHome)); - } - return defaultQoderHome(); -} - -function resolveQoderSharedClientCacheRoot(options = {}) { - const explicit = - options.qoderSharedClientCacheRoot ?? - options["qoder-shared-client-cache-root"] ?? - options.sharedClientCacheRoot; - if (explicit) return path.resolve(expandHome(explicit)); - const environmentHome = process.env.QODER_HOME; - if (environmentHome && !looksLikeQoderAssetHome(environmentHome)) { - return path.resolve(expandHome(environmentHome)); - } - return defaultQoderSharedClientCacheRoot(); -} - export function qoderWorkspaceSlugs(workspace) { const expanded = expandHome(workspace ?? process.cwd()); const normalized = path.win32.isAbsolute(expanded) @@ -149,7 +108,7 @@ function mergeQoderInstalledRecord(existing, next) { } async function readQoderInstalledPluginState(options = {}) { - const qoderHome = path.resolve(expandHome(options.qoderHome ?? defaultQoderHome())); + const qoderHome = resolveQoderAssetHome(options); const workspace = normalizeWorkspace(options.workspace ?? process.cwd()); if (Array.isArray(options.qoderInstalledPluginRecords) || Array.isArray(options.installedPluginRecords)) { const records = (options.qoderInstalledPluginRecords ?? options.installedPluginRecords) diff --git a/scripts/agent-lint/host-instructions.mjs b/scripts/agent-lint/host-instructions.mjs index d0ee5b0f..6f792f02 100644 --- a/scripts/agent-lint/host-instructions.mjs +++ b/scripts/agent-lint/host-instructions.mjs @@ -3,6 +3,7 @@ import { readdir, readFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; +import { resolveQoderAssetHome } from "../host-support/qoder-home.mjs"; import { expandHome, normalizeWorkspace, pathExists } from "../session-analysis/index.mjs"; const MARKDOWN_EXTENSIONS = new Set([".md", ".mdc", ".markdown"]); @@ -61,7 +62,7 @@ function ancestors(workspace) { async function qoderSources(options) { const workspace = normalizeWorkspace(options.workspace); - const home = path.resolve(expandHome(options.qoderHome ?? options["qoder-home"] ?? process.env.QODER_HOME ?? "~/.qoder")); + const home = resolveQoderAssetHome(options); const candidates = []; if (options.includeUserHome ?? options["include-user-home"]) { for (const filePath of await markdownFiles(path.join(home, "rules"), 4)) { diff --git a/scripts/coding-agent-practices/inventory.mjs b/scripts/coding-agent-practices/inventory.mjs index 15ce0c5b..432e83f8 100644 --- a/scripts/coding-agent-practices/inventory.mjs +++ b/scripts/coding-agent-practices/inventory.mjs @@ -15,6 +15,10 @@ import { walkFiles, } from "../session-analysis/index.mjs"; import { collectAgentCustomizeInventory } from "../agent-customize/index.mjs"; +import { + looksLikeQoderAssetHome, + resolveQoderAssetHome, +} from "../host-support/qoder-home.mjs"; import { getHostDescriptor, HOST_CAPABILITIES, @@ -439,11 +443,8 @@ function publicScope(options = {}, dependencies = {}) { }, dependencies); const { workspace, cwd } = configuredScope; const environmentHome = process.env.QODER_HOME; - const environmentBase = path.basename(String(environmentHome ?? "")).toLowerCase(); - const environmentIsAssetHome = environmentBase === ".qoder" || environmentBase === "qoder"; - const qoderHome = path.resolve(expandHome( - options.qoderHome ?? options["qoder-home"] ?? (environmentIsAssetHome ? environmentHome : "~/.qoder"), - )); + const environmentIsAssetHome = looksLikeQoderAssetHome(environmentHome); + const qoderHome = resolveQoderAssetHome(options); const explicitSharedCache = options.sharedCache ?? options["shared-cache"]; const sharedCache = explicitSharedCache ? path.resolve(expandHome(explicitSharedCache)) diff --git a/scripts/core-change-watch/evidence-pack.mjs b/scripts/core-change-watch/evidence-pack.mjs index d11b2ca8..2653691b 100644 --- a/scripts/core-change-watch/evidence-pack.mjs +++ b/scripts/core-change-watch/evidence-pack.mjs @@ -110,7 +110,7 @@ function supportingFilesByRole(history, diff, role, currentPaths) { return actionFiles([...fromDiff, ...fromHistory], 8, currentPaths); } -function buildFollowUpActions(core, diff, history, changeDrift, maxActions, currentPaths) { +function buildFollowUpActions(core, diff, history, changeDrift, projectProfile, maxActions, currentPaths) { const actions = []; const topCoreFiles = actionFiles(core.candidates.slice(0, 4).flatMap((candidate) => [ ...candidate.evidence.hotFiles, @@ -201,7 +201,8 @@ function buildFollowUpActions(core, diff, history, changeDrift, maxActions, curr }); } - if (testFiles.length > 0 || diff.reviewRecommended || topCoreFiles.length > 0) { + const gates = projectProfile.projectGates ?? []; + if (testFiles.length > 0 || gates.length > 0 || diff.reviewRecommended || topCoreFiles.length > 0) { actions.push({ id: "validate-impact", type: "validation", @@ -211,8 +212,11 @@ function buildFollowUpActions(core, diff, history, changeDrift, maxActions, curr ? "Diff impact requires attention because the change touches configured or detected core code." : testFiles.length > 0 ? "Detected tests or fixtures can anchor validation." - : "Core candidates need focused validation after implementation changes.", + : gates.length > 0 + ? "Project-owned validation gates were discovered from tracked manifests and Justfiles." + : "Core candidates need focused validation after implementation changes.", files: testFiles, + ...(gates.length > 0 ? { commands: gates } : {}), passCheck: "Relevant focused tests, build, lint, smoke, or caller/API checks pass or failures are reported with exact output.", }); } @@ -352,6 +356,7 @@ function summarizeAgentInstructions(projectProfile) { count: instructions.count, rootCount: instructions.rootCount, nestedCount: instructions.nestedCount, + carriers: instructions.carriers, suggestedMinimum: instructions.suggestedMinimum, suggestedAdditional: instructions.suggestedAdditional, sourceFilesPerInstruction: instructions.sourceFilesPerInstruction, @@ -396,9 +401,19 @@ function buildReviewMatrix(projectProfile, historyProfile, coreAnalysis, diffImp matrixItem( "history-window-coverage", "History uses 30/90/180 style windows with confidence notes", - historyProfile.historyWindows.length >= 3 && historyProfile.confidence ? "ready" : "review", - { windows: historyProfile.historyWindows.map((item) => item.days), confidence: historyProfile.confidence?.confidence ?? "unknown" }, - "Low history confidence should downgrade hotspot certainty, not block source inspection.", + historyProfile.historyWindows.length >= 3 && + historyProfile.confidence && + historyProfile.confidence.confidence !== "low" && + historyProfile.historyWindows.every((item) => item.coverage === "complete") + ? "ready" + : "review", + { + windows: historyProfile.historyWindows.map((item) => item.days), + confidence: historyProfile.confidence?.confidence ?? "unknown", + truncatedWindows: historyProfile.historyWindows.filter((item) => item.truncated).map((item) => item.days), + coverage: historyProfile.historyWindows.map((item) => ({ days: item.days, status: item.coverage })), + }, + "Low history confidence or a bounded-window truncation should downgrade hotspot certainty, not block source inspection.", ), matrixItem( "large-repo-safety", @@ -492,6 +507,9 @@ export async function buildEvidencePack(options = {}) { days, since: null, analyzedCommits: 0, + commitLimit: 0, + truncated: false, + coverage: "skipped", trendLabel: days <= 30 ? "recent-hotspots" : days <= 90 ? "sustained-hotspots" : "legacy-or-long-range-hotspots", interpretation: "History scan skipped; this window is present for schema stability only.", hotFiles: [], @@ -542,6 +560,7 @@ export async function buildEvidencePack(options = {}) { diffImpact, historyProfile, changeDrift, + projectProfile, maxFollowUpActions, currentPaths, ); @@ -562,6 +581,7 @@ export async function buildEvidencePack(options = {}) { topLanguages: projectProfile.languages.slice(0, 5).map((item) => item.language), projectInfo: summarizeProjectInfo(projectProfile), agentInstructions: summarizeAgentInstructions(projectProfile), + projectGates: projectProfile.projectGates, coreCandidates: coreAnalysis.summary, changedFiles: diffImpact.metrics.changedFiles, changedLines: diffImpact.metrics.changedLines, diff --git a/scripts/core-change-watch/git-history-profile.mjs b/scripts/core-change-watch/git-history-profile.mjs index 30372c5c..019ba80c 100644 --- a/scripts/core-change-watch/git-history-profile.mjs +++ b/scripts/core-change-watch/git-history-profile.mjs @@ -137,18 +137,45 @@ function collectHistoryStats(commits, allowedLanguages, analysisScope) { }; } -function historyWindows(commits, allowedLanguages, daysList, analysisScope) { +function readHistoryLog(repoRoot, maxCommits, analysisScope, sinceSeconds) { + const args = [ + "log", + `-${maxCommits}`, + "--numstat", + "--format=commit%x1f%H%x1f%ct%x1f%s", + ]; + if (sinceSeconds !== undefined) { + args.push(`--since=${new Date(sinceSeconds * 1000).toISOString()}`); + } + args.push(...scopePathspecArgs(analysisScope)); + return parseLogWithNumstat(git(repoRoot, args, { timeout: 30_000 }), analysisScope); +} + +function historyWindows(commits, allowedLanguages, daysList, analysisScope, { + repoRoot, + maxCommits, + ignore, +}) { const nowSeconds = Math.floor(Date.now() / 1000); return daysList.map((days) => { const sinceSeconds = nowSeconds - days * 24 * 60 * 60; - const windowCommits = commits.filter((commit) => commit.timestamp >= sinceSeconds); + const windowParsed = commits.length === 0 + ? [] + : readHistoryLog(repoRoot, maxCommits, analysisScope, sinceSeconds); + const windowCommits = commits.length === 0 + ? [] + : applyCommitIgnores(windowParsed, ignore).commits; const stats = collectHistoryStats(windowCommits, allowedLanguages, analysisScope); const trend = trendForWindow(days, windowCommits.length); + const truncated = windowParsed.length >= maxCommits; return { days, since: new Date(sinceSeconds * 1000).toISOString(), analyzedCommits: windowCommits.length, + commitLimit: maxCommits, + truncated, + coverage: truncated ? "truncated" : "complete", trendLabel: trend.label, interpretation: trend.interpretation, hotFiles: sortedHotFiles(stats.fileStats, 10), @@ -227,13 +254,9 @@ export async function analyzeGitHistoryProfile(options = {}) { const maxCommits = positiveInt(options.maxCommits, DEFAULT_MAX_COMMITS); const windowDays = normalizeHistoryWindows(options.historyWindows); const allowedLanguages = new Set(normalizeLanguages(options.languages)); - let output; + let parsedCommits; try { - output = git( - repoRoot, - ["log", `-${maxCommits}`, "--numstat", "--format=commit%x1f%H%x1f%ct%x1f%s", ...scopePathspecArgs(analysisScope)], - { timeout: 30_000 }, - ); + parsedCommits = readHistoryLog(repoRoot, maxCommits, analysisScope); } catch (error) { // An unborn repository is a valid empty history. Every other Git failure, // including a malformed scope/pathspec, remains a hard coverage failure. @@ -241,14 +264,13 @@ export async function analyzeGitHistoryProfile(options = {}) { git(repoRoot, ["rev-parse", "--verify", "HEAD"]); } catch (headError) { if (headError?.code === "GIT_COMMAND_FAILED") { - output = ""; + parsedCommits = []; } else { throw error; } } - if (output === undefined) throw error; + if (parsedCommits === undefined) throw error; } - const parsedCommits = parseLogWithNumstat(output, analysisScope); const filteredHistory = applyCommitIgnores(parsedCommits, options.ignore); const commits = filteredHistory.commits; const stats = collectHistoryStats(commits, allowedLanguages, analysisScope); @@ -268,7 +290,11 @@ export async function analyzeGitHistoryProfile(options = {}) { oldest: commits.at(-1)?.shortSha ?? null, }, confidence: historyConfidence(commits, maxCommits), - historyWindows: historyWindows(commits, allowedLanguages, windowDays, analysisScope), + historyWindows: historyWindows(commits, allowedLanguages, windowDays, analysisScope, { + repoRoot, + maxCommits, + ignore: options.ignore, + }), languageTouchCounts: sortedCounts(stats.languageStats, 12).map((item) => ({ language: item.name, touches: item.count, diff --git a/scripts/core-change-watch/project-profile.mjs b/scripts/core-change-watch/project-profile.mjs index bc32f28b..b588117a 100644 --- a/scripts/core-change-watch/project-profile.mjs +++ b/scripts/core-change-watch/project-profile.mjs @@ -53,7 +53,9 @@ const MANIFESTS = new Set([ "requirements.txt", ]); -const AGENT_INSTRUCTION_FILE = "AGENTS.md"; +const AGENT_INSTRUCTION_FILES = new Set(["AGENTS.md", "CLAUDE.md"]); +const SCRATCH_DIRECTORIES = new Set([".cache", ".state", ".tmp", ".scratch", "coverage", "scratch", "temp", "tmp"]); +const PROJECT_GATE_PATTERN = /^(?:build|check|ci|e2e|lint|smoke|test|type-?check|validate|verify)(?::.+)?$/iu; const SOURCE_FILES_PER_AGENT_INSTRUCTION = 250; const SIGNIFICANT_SOURCE_ROOT_FILES = 100; const SOURCE_LINE_METHOD = "tracked readable primary source files only; excludes tests, non-source assets, generated/dependency paths, and untracked files"; @@ -441,12 +443,19 @@ function isPathUnderScope(filePath, scope) { return normalizedScope === "." || normalized === normalizedScope || normalized.startsWith(`${normalizedScope}/`); } +function isScratchDirectory(directory) { + return toPosix(directory) + .split("/") + .some((segment) => SCRATCH_DIRECTORIES.has(segment.toLowerCase())); +} + function agentInstructionFiles(trackedFiles, analysisScope) { return trackedFiles - .filter((filePath) => path.posix.basename(toPosix(filePath)) === AGENT_INSTRUCTION_FILE) + .filter((filePath) => AGENT_INSTRUCTION_FILES.has(path.posix.basename(toPosix(filePath)))) .filter((filePath) => !isDependencyOrGenerated(filePath)) .map((filePath) => ({ path: toPosix(filePath), + carrier: path.posix.basename(toPosix(filePath)), scope: fromAnalysisRelativePath( instructionScope(toAnalysisRelativePath(filePath, analysisScope)), analysisScope, @@ -478,17 +487,45 @@ function agentInstructionStatus(count, suggestedMinimum) { return "adequate"; } +function projectGates(manifests) { + const gates = []; + for (const manifest of manifests) { + if (manifest.kind !== "node" && manifest.kind !== "just") continue; + const prefix = manifest.kind === "node" ? path.posix.dirname(manifest.path) : "."; + for (const name of manifest.scripts ?? []) { + if (!PROJECT_GATE_PATTERN.test(name)) continue; + const command = manifest.kind === "just" + ? ["just", name] + : ["npm", ...(prefix === "." ? [] : ["--prefix", prefix]), "run", name]; + gates.push({ + name, + kind: manifest.kind === "just" ? "just-recipe" : "package-script", + sourcePath: manifest.path, + command, + }); + } + } + return gates + .sort((a, b) => a.sourcePath.localeCompare(b.sourcePath) || a.name.localeCompare(b.name)) + .slice(0, 20); +} + function analyzeAgentInstructions({ trackedFiles, sourceRecords, sourceRoots, totals, analysisScope }) { const files = agentInstructionFiles(trackedFiles, analysisScope); const nestedScopes = files.filter((item) => !item.targetRoot).map((item) => item.scope); + const carrierCounts = new Map(); let sourceFilesUnderNestedInstructions = 0; const uncoveredSourceDirs = new Map(); + for (const file of files) { + addCount(carrierCounts, file.carrier, 1); + } + for (const source of sourceRecords) { const underNestedInstruction = nestedScopes.some((scope) => isPathUnderScope(source.path, scope)); if (underNestedInstruction) { sourceFilesUnderNestedInstructions += 1; - } else { + } else if (!isScratchDirectory(source.directory)) { addCount(uncoveredSourceDirs, source.directory, 1); } } @@ -501,25 +538,26 @@ function analyzeAgentInstructions({ trackedFiles, sourceRecords, sourceRoots, to const reasons = []; if (rootCount > 0) { - reasons.push("root AGENTS.md present"); + reasons.push("root agent instruction file present"); } if (nestedCount > 0) { - reasons.push(`${nestedCount} nested AGENTS.md files provide module-local guidance`); + reasons.push(`${nestedCount} nested instruction files provide module-local guidance`); } if (status === "thin") { - reasons.push(`AGENTS.md count ${files.length} is below suggested minimum ${suggestedMinimum} for source scale`); + reasons.push(`instruction file count ${files.length} is below suggested minimum ${suggestedMinimum} for source scale`); } if (status === "missing") { - reasons.push("no tracked AGENTS.md files found for a source-bearing repository"); + reasons.push("no tracked AGENTS.md or CLAUDE.md files found for a source-bearing repository"); } if (totals.sourceFiles >= SOURCE_FILES_PER_AGENT_INSTRUCTION && sourceFilesUnderNestedInstructions === 0) { - reasons.push("large source tree has no nested AGENTS.md coverage"); + reasons.push("large source tree has no nested instruction coverage"); } return { count: files.length, rootCount, nestedCount, + carriers: sortedCounts(carrierCounts, 4).map((item) => ({ name: item.name, files: item.count })), files: files.map(({ targetRoot: _targetRoot, ...file }) => file), status, suggestedMinimum, @@ -757,6 +795,7 @@ export async function analyzeProjectProfile(options = {}) { }), languages, manifests: sortedManifests, + projectGates: projectGates(sortedManifests), frameworks, sourceRoots: sortedSourceRoots, entryCandidates: sortedEntryCandidates, diff --git a/scripts/harness-analysis/evidence-bundle/cli.mjs b/scripts/harness-analysis/evidence-bundle/cli.mjs index 2bed72c3..ac985f76 100644 --- a/scripts/harness-analysis/evidence-bundle/cli.mjs +++ b/scripts/harness-analysis/evidence-bundle/cli.mjs @@ -30,6 +30,7 @@ Options: --evidence-limit <1-5> Override the specialist evidence limit --include-user-home Include authorized user/global asset metadata --include-memories Include authorized Memory title metadata + --qoder-home Qoder data root override --claude-home Claude config root override --claude-state Claude state-file override --kimi-home Kimi Code data root override diff --git a/scripts/harness-analysis/report-run.mjs b/scripts/harness-analysis/report-run.mjs index 6419ef59..29fac91d 100644 --- a/scripts/harness-analysis/report-run.mjs +++ b/scripts/harness-analysis/report-run.mjs @@ -31,6 +31,7 @@ Options: --workspace Target workspace (required) --cwd Configured-practice cwd (default: workspace) --platform ${formatHostList(REPORT_PLATFORMS)} (default: qoder) + --qoder-home Qoder data root override (default: ~/.qoder-cn then ~/.qoder) --language en or zh-CN (default: en) --since Include sessions at or after the frozen window start --until Include sessions at or before the frozen window end diff --git a/scripts/harness-analysis/task-loop-source.mjs b/scripts/harness-analysis/task-loop-source.mjs index c8bfb34a..626d1a95 100644 --- a/scripts/harness-analysis/task-loop-source.mjs +++ b/scripts/harness-analysis/task-loop-source.mjs @@ -100,6 +100,7 @@ Options: Session platform (default: qoder) --workspace Target workspace (required) --source Candidate report.source.json path (required) + --qoder-home Qoder data root override --until Exclude later sessions --since Exclude earlier sessions --limit Maximum selected sessions (default: ${DEFAULT_LIMIT}) diff --git a/scripts/harness-quickstart/cli.mjs b/scripts/harness-quickstart/cli.mjs index 78e2f0ce..a8a6f312 100644 --- a/scripts/harness-quickstart/cli.mjs +++ b/scripts/harness-quickstart/cli.mjs @@ -27,7 +27,7 @@ hands off to the Better Harness skill, which synthesizes the report. Options: --cwd Repository to inspect (default: current directory) - --qoder-home Qoder data root for the session-source probe (default: ~/.qoder) + --qoder-home Qoder data root for the session-source probe (default: ~/.qoder-cn then ~/.qoder) --no-sessions Skip session probing and use the static Software Fluency route --json Emit machine-readable evidence and handoff as JSON -h, --help Print this help diff --git a/scripts/host-support/qoder-home.mjs b/scripts/host-support/qoder-home.mjs new file mode 100644 index 00000000..633e0e14 --- /dev/null +++ b/scripts/host-support/qoder-home.mjs @@ -0,0 +1,65 @@ +import { existsSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +const QODER_ASSET_HOME_NAMES = new Set([".qoder", "qoder", ".qoder-cn", "qoder-cn"]); + +function expandHome(filePath) { + if (!filePath) return filePath; + if (filePath === "~") return os.homedir(); + if (filePath.startsWith("~/")) return path.join(os.homedir(), filePath.slice(2)); + return filePath; +} + +export function looksLikeQoderAssetHome(candidate) { + return QODER_ASSET_HOME_NAMES.has(path.basename(String(candidate ?? "")).toLowerCase()); +} + +export function defaultQoderHome() { + const cnHome = path.join(os.homedir(), ".qoder-cn"); + if (existsSync(cnHome)) return cnHome; + return path.join(os.homedir(), ".qoder"); +} + +export function defaultQoderSharedClientCacheRoot() { + if (process.platform === "win32") { + const appData = process.env.APPDATA ?? path.join(os.homedir(), "AppData", "Roaming"); + return path.join(appData, "Qoder", "SharedClientCache"); + } + if (process.platform === "darwin") { + return path.join(os.homedir(), "Library", "Application Support", "Qoder", "SharedClientCache"); + } + const xdgConfig = process.env.XDG_CONFIG_HOME ?? path.join(os.homedir(), ".config"); + return path.join(xdgConfig, "Qoder", "SharedClientCache"); +} + +export function resolveQoderAssetHome(options = {}) { + const explicit = options.qoderHome ?? options["qoder-home"]; + if (explicit) return path.resolve(expandHome(explicit)); + const environmentHome = process.env.QODER_HOME; + if (environmentHome && looksLikeQoderAssetHome(environmentHome)) { + return path.resolve(expandHome(environmentHome)); + } + return defaultQoderHome(); +} + +export function resolveQoderSessionHome(options = {}) { + const explicit = options.home ?? options.qoderHome ?? options["qoder-home"]; + if (explicit) return path.resolve(expandHome(explicit)); + const environmentHome = process.env.QODER_HOME; + if (environmentHome) return path.resolve(expandHome(environmentHome)); + return defaultQoderHome(); +} + +export function resolveQoderSharedClientCacheRoot(options = {}) { + const explicit = + options.qoderSharedClientCacheRoot ?? + options["qoder-shared-client-cache-root"] ?? + options.sharedClientCacheRoot; + if (explicit) return path.resolve(expandHome(explicit)); + const environmentHome = process.env.QODER_HOME; + if (environmentHome && !looksLikeQoderAssetHome(environmentHome)) { + return path.resolve(expandHome(environmentHome)); + } + return defaultQoderSharedClientCacheRoot(); +} diff --git a/scripts/session-analysis/analyzer.mjs b/scripts/session-analysis/analyzer.mjs index 4fafc4de..06250856 100644 --- a/scripts/session-analysis/analyzer.mjs +++ b/scripts/session-analysis/analyzer.mjs @@ -46,7 +46,7 @@ Options: --platform <${hostPipeList(DECLARED_SESSION_HOSTS)}> Session host (default: qoder) --workspace Workspace scope (default: current directory) - --qoder-home Qoder data root (default: ~/.qoder) + --qoder-home Qoder data root (default: ~/.qoder-cn then ~/.qoder) --codex-home Codex data root (default: ~/.codex) --claude-home Claude Code data root (default: ~/.claude) --augment-home Augment/Auggie data root (default: ~/.augment) diff --git a/scripts/session-analysis/platforms/qoder.mjs b/scripts/session-analysis/platforms/qoder.mjs index bad2dc1a..eb2cfbe3 100644 --- a/scripts/session-analysis/platforms/qoder.mjs +++ b/scripts/session-analysis/platforms/qoder.mjs @@ -4,6 +4,7 @@ import { mkdir, readdir, writeFile } from "node:fs/promises"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { resolveQoderSessionHome } from "../../host-support/qoder-home.mjs"; import { SessionAnalyzer } from "../analyzer.mjs"; import { parseArgs, parseBooleanFlag } from "../cli.mjs"; import { forEachJsonLine, pathExists, readJson, walkFiles } from "../fs.mjs"; @@ -1109,7 +1110,7 @@ export class QoderSessionAnalyzer extends SessionAnalyzer { const workspaceMatchScope = workspaceMatchScopeFromOptions(options); const since = normalizeCliDate(options.since, false); const until = normalizeCliDate(options.until, true); - const home = path.resolve(expandHome(options.home ?? options["qoder-home"] ?? "~/.qoder")); + const home = resolveQoderSessionHome(options); const transcriptWorkspaces = [...new Set([ workspace, workspaceMatchScope?.requestedWorkspace, diff --git a/test/agents/agent-asset-baseline.test.mjs b/test/agents/agent-asset-baseline.test.mjs index 758a93ec..ab0da5cc 100644 --- a/test/agents/agent-asset-baseline.test.mjs +++ b/test/agents/agent-asset-baseline.test.mjs @@ -5,6 +5,7 @@ import os from "node:os"; import path from "node:path"; import { onTestFinished, test } from "vitest"; +import { createDirectoryLink, skipWithoutFileLink } from "../support/path-links.mjs"; import { ASSET_BASELINE_KIND, MAX_BASELINE_FINDINGS, @@ -259,7 +260,7 @@ test("asset baseline canonicalizes direct configured scope before inventory coll const escape = path.join(workspace, "escape"); try { await Promise.all([mkdir(dotted, { recursive: true }), mkdir(outside)]); - await symlink(outside, escape, "dir"); + await createDirectoryLink(outside, escape); let received; const omitted = await collectAssetBaseline( @@ -317,7 +318,8 @@ test("DSH baseline never advertises unsupported Memory collection", async () => assert.equal(codex.scope.includeMemories, true); }); -test("asset baseline compacts finding, coverage, owner, and free-text paths to stable locators", async () => { +test("asset baseline compacts finding, coverage, owner, and free-text paths to stable locators", async (t) => { + if (await skipWithoutFileLink(t)) return; const root = await mkdtemp(path.join(os.tmpdir(), "better-harness-baseline-locators-")); onTestFinished(async () => { await rm(root, { recursive: true, force: true }); diff --git a/test/agents/agent-asset-integrity.test.mjs b/test/agents/agent-asset-integrity.test.mjs index 3f2d0e19..8708b82f 100644 --- a/test/agents/agent-asset-integrity.test.mjs +++ b/test/agents/agent-asset-integrity.test.mjs @@ -1,12 +1,13 @@ import assert from "node:assert/strict"; import { createHash } from "node:crypto"; import { execFile } from "node:child_process"; -import { mkdtemp, mkdir, realpath, rm, symlink, writeFile } from "node:fs/promises"; +import { mkdtemp, mkdir, realpath, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import { test } from "vitest"; +import { createDirectoryLink } from "../support/path-links.mjs"; import { ASSET_INTEGRITY_PROFILE, normalizeAssetTitle, @@ -288,7 +289,7 @@ test("public asset-integrity CLI rejects a configured cwd that resolves outside mkdir(outside, { recursive: true }), mkdir(dshHome, { recursive: true }), ]); - await symlink(outside, escape, "dir"); + await createDirectoryLink(outside, escape); const script = path.join(process.cwd(), "scripts", "better-harness.mjs"); await assert.rejects( execFileAsync(process.execPath, [ diff --git a/test/agents/agent-customize-dsh.test.mjs b/test/agents/agent-customize-dsh.test.mjs index 7ec1f7ca..82e99c7e 100644 --- a/test/agents/agent-customize-dsh.test.mjs +++ b/test/agents/agent-customize-dsh.test.mjs @@ -13,7 +13,7 @@ import os from "node:os"; import path from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; -import { test } from "vitest"; +import { onTestFinished, test } from "vitest"; import { MANAGE_TABS } from "../../scripts/agent-customize/constants.mjs"; @@ -365,9 +365,21 @@ test("DSH default privacy performs no ambient user/global filesystem reads", asy test("DSH user opt-in and explicit external roots obey distinct authorization boundaries", async () => { await withTempRoot("better-harness-dsh-authorized-", async (root) => { + const syntheticHome = path.join(root, "synthetic-home"); + const previousHome = process.env.HOME; + const previousUserProfile = process.env.USERPROFILE; + process.env.HOME = syntheticHome; + process.env.USERPROFILE = syntheticHome; + onTestFinished(() => { + if (previousHome === undefined) delete process.env.HOME; + else process.env.HOME = previousHome; + if (previousUserProfile === undefined) delete process.env.USERPROFILE; + else process.env.USERPROFILE = previousUserProfile; + }); + const { workspace } = await createRepository(root, ["workspace"]); - const dshHome = path.join(root, "synthetic-home", ".dsh"); - const agentsHome = path.join(root, "synthetic-home", ".agents"); + const dshHome = path.join(syntheticHome, ".dsh"); + const agentsHome = path.join(syntheticHome, ".agents"); const custom = path.join(root, "external", "custom"); const customSibling = path.join(root, "external", "sibling"); const bundled = path.join(root, "external", "bundled"); diff --git a/test/agents/agent-customize.test.mjs b/test/agents/agent-customize.test.mjs index 62977372..6f587d5a 100644 --- a/test/agents/agent-customize.test.mjs +++ b/test/agents/agent-customize.test.mjs @@ -12,6 +12,7 @@ import { tabAvailableForScope, } from "../../scripts/agent-customize/index.mjs"; import { pluginMetadataEvidencePath } from "../../scripts/agent-customize/core/items.mjs"; +import { createDirectoryLink } from "../support/path-links.mjs"; import { collectKimiCustomizeInventory } from "../../scripts/agent-customize/providers/kimi.mjs"; import { qoderWorkspaceSlugs } from "../../scripts/agent-customize/providers/qoder.mjs"; import { collectProviderInventory as collectPracticeInventory } from "../../scripts/coding-agent-practices/inventory.mjs"; @@ -174,9 +175,9 @@ async function makeCursorFixture() { return { root, cursorHome, workspace }; } -async function makeQoderFixture() { +async function makeQoderFixture({ homeName = "q" } = {}) { const root = await mkdtemp(path.join(os.tmpdir(), "bhq-")); - const qoderHome = path.join(root, "q"); + const qoderHome = path.join(root, homeName); const sharedClientCacheRoot = path.join(root, "s"); const workspace = path.join(root, "w"); @@ -1325,6 +1326,29 @@ test("Qoder inventory preserves current local scope and excludes explicit foreig } }); +test("Qoder provider honors QODER_HOME when no explicit home is passed", async () => { + const fixture = await makeQoderFixture({ homeName: ".qoder" }); + const previous = process.env.QODER_HOME; + + try { + process.env.QODER_HOME = fixture.qoderHome; + const inventory = await collectAgentCustomizeInventory({ + provider: "qoder", + workspace: fixture.workspace, + }); + + assert.equal(inventory.qoderHome, fixture.qoderHome); + assert.ok( + filterManageItems(inventory, { tab: "mcps", scopeKind: "user" }) + .some((item) => item.name === "better-harness"), + ); + } finally { + if (previous === undefined) delete process.env.QODER_HOME; + else process.env.QODER_HOME = previous; + await rm(fixture.root, { recursive: true, force: true }); + } +}); + test("Qoder provider collects configured MCPs and uses runtime metadata only as enrichment", async () => { const fixture = await makeQoderFixture(); @@ -1568,10 +1592,13 @@ test("Claude provider collects native scoped assets from settings, state, and in ["project-review"], ); assert.deepEqual( - inventory.manage.rules.filter((item) => item.scope === "project").map((item) => item.name), - [".claude/CLAUDE.md", "CLAUDE.local.md", "CLAUDE.md", "security"], + inventory.manage.rules.filter((item) => item.scope === "project").map((item) => item.name).sort(), + [".claude/CLAUDE.md", "AGENTS.md", "CLAUDE.local.md", "CLAUDE.md", "security"].sort(), + ); + assert.equal( + inventory.manage.rules.find((item) => item.name === "AGENTS.md")?.sourceKind, + "agents-md-compat", ); - assert.equal(inventory.manage.rules.some((item) => item.name === "AGENTS.md"), false); const userHook = inventory.manage.hooks.find((hook) => hook.scope === "user"); assert.ok(userHook); @@ -3173,10 +3200,9 @@ test("Grok project skills dedupe when .grok/skills symlinks to .agents/skills", "---\nname: shared-flow\ndescription: Shared SoT skill.\n---\n", ); await mkdir(path.join(workspace, ".grok"), { recursive: true }); - await symlink( + await createDirectoryLink( path.join(workspace, ".agents", "skills"), path.join(workspace, ".grok", "skills"), - "dir", ); const inventory = await collectAgentCustomizeInventory({ diff --git a/test/agents/agent-lint.test.mjs b/test/agents/agent-lint.test.mjs index df1f5d34..fc320059 100644 --- a/test/agents/agent-lint.test.mjs +++ b/test/agents/agent-lint.test.mjs @@ -6,6 +6,7 @@ import path from "node:path"; import { promisify } from "node:util"; import { test } from "vitest"; +import { createDirectoryLink } from "../support/path-links.mjs"; import { collectAgentInstructionGraph, runAgentLint, @@ -1095,7 +1096,7 @@ test("agent-assets-review rejects a configured cwd that resolves outside workspa mkdir(outside, { recursive: true }), mkdir(dshHome, { recursive: true }), ]); - await symlink(outside, escape, "dir"); + await createDirectoryLink(outside, escape); await assert.rejects( execFileAsync(process.execPath, [ cliPath, diff --git a/test/agents/coding-agent-practices-inventory.test.mjs b/test/agents/coding-agent-practices-inventory.test.mjs index 4cff54b6..c2d7b082 100644 --- a/test/agents/coding-agent-practices-inventory.test.mjs +++ b/test/agents/coding-agent-practices-inventory.test.mjs @@ -1,11 +1,12 @@ import assert from "node:assert/strict"; import { execFile } from "node:child_process"; -import { mkdtemp, mkdir, realpath, rm, symlink, writeFile } from "node:fs/promises"; +import { mkdtemp, mkdir, realpath, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; import { test } from "vitest"; +import { createDirectoryLink } from "../support/path-links.mjs"; import { collectProviderInventory, collectQoderInventory, @@ -22,10 +23,10 @@ async function writeJson(filePath, value) { await writeText(filePath, `${JSON.stringify(value, null, 2)}\n`); } -async function makeFixture() { +async function makeFixture({ homeName = ".qoder" } = {}) { const root = await mkdtemp(path.join(os.tmpdir(), "better-harness-agent-assets-")); const workspace = path.join(root, "workspace", "demo"); - const qoderHome = path.join(root, ".qoder"); + const qoderHome = path.join(root, homeName); const sharedCache = path.join(root, "SharedClientCache", "cache"); await writeText(path.join(workspace, ".qoder", "rules", "always.md"), "# Always\n"); @@ -476,6 +477,32 @@ test("Qoder inventory separates a SharedClientCache QODER_HOME from ~/.qoder ass } }); +test("Qoder inventory discovers a default .qoder-cn home without an explicit flag", async () => { + const fixture = await makeFixture({ homeName: ".qoder-cn" }); + const script = path.join(process.cwd(), "scripts/coding-agent-practices/inventory.mjs"); + const env = { + ...process.env, + HOME: fixture.root, + USERPROFILE: fixture.root, + }; + delete env.QODER_HOME; + try { + const { stdout } = await execFileAsync(process.execPath, [ + script, + "qoder", + "--workspace", + fixture.workspace, + "--include-user-home", + "--json", + ], { env }); + const result = JSON.parse(stdout); + assert.equal(result.scope.qoderHome, fixture.qoderHome); + assert.ok(result.summary.practiceCoverageRows.some((row) => row.surface === "Skills" && row.scopes.includes("Global"))); + } finally { + await rm(fixture.root, { recursive: true, force: true }); + } +}); + test("inventory CLI reports an unsupported platform with a usage hint", async () => { const script = path.join(process.cwd(), "scripts/coding-agent-practices/inventory.mjs"); await assert.rejects( @@ -761,7 +788,7 @@ test("direct provider inventory canonicalizes configured cwd before using inject }; try { await Promise.all([mkdir(dotted, { recursive: true }), mkdir(outside)]); - await symlink(outside, escape, "dir"); + await createDirectoryLink(outside, escape); const omitted = await collectProviderInventory({ platform: "dsh", workspace, inventory }); assert.equal(omitted.scope.workspace, await realpath(workspace)); diff --git a/test/governance/core-change-watch-scope.test.mjs b/test/governance/core-change-watch-scope.test.mjs index 29b439f3..a2523c2c 100644 --- a/test/governance/core-change-watch-scope.test.mjs +++ b/test/governance/core-change-watch-scope.test.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import path from "node:path"; import { test } from "vitest"; @@ -20,6 +20,7 @@ import { } from "../../scripts/core-change-watch/common.mjs"; import { buildEvidencePack } from "../../scripts/core-change-watch/evidence-pack.mjs"; import { collectBoundedGitHistory } from "../../scripts/harness-analysis/learning-capture-evidence.mjs"; +import { createDirectoryLink } from "../support/path-links.mjs"; import { scanTaskLoopRepositoryEvidence } from "../../scripts/harness-analysis/task-loop-repository-evidence.mjs"; function runGit(cwd, args) { @@ -87,7 +88,7 @@ test("analysis scope treats real-path aliases as one repository identity", async try { await mkdir(packageRoot, { recursive: true }); runGit(repoRoot, ["init", "--quiet"]); - await symlink(repoRoot, repoLink, "dir"); + await createDirectoryLink(repoRoot, repoLink); const scope = resolveAnalysisScope({ repoRoot: repoLink, diff --git a/test/governance/core-change-watch.test.mjs b/test/governance/core-change-watch.test.mjs index d9b1f4ee..1f211eed 100644 --- a/test/governance/core-change-watch.test.mjs +++ b/test/governance/core-change-watch.test.mjs @@ -21,6 +21,7 @@ function git(cwd, args, options = {}) { encoding: "utf8", stdio: [options.input === undefined ? "ignore" : "pipe", "pipe", "pipe"], input: options.input, + env: options.env ? { ...process.env, ...options.env } : process.env, }); if (result.status !== 0) { @@ -286,6 +287,33 @@ test("AGENTS instruction density uses file count instead of line count", async ( } }); +test("project profile treats AGENTS.md and CLAUDE.md as first-class instruction carriers", async () => { + const repo = await makeRepo({ + "package.json": JSON.stringify({ name: "dual-carrier-instructions" }), + "AGENTS.md": "# Root agent rules\n", + "CLAUDE.md": "# Root Claude rules\n", + "src/AGENTS.md": "# Source agent rules\n", + "src/CLAUDE.md": "# Source Claude rules\n", + "src/app.ts": "export function app() { return true; }\n", + }); + + try { + const profile = await analyzeProjectProfile({ cwd: repo }); + + assert.equal(profile.agentInstructions.count, 4); + assert.equal(profile.agentInstructions.rootCount, 2); + assert.equal(profile.agentInstructions.nestedCount, 2); + assert.deepEqual( + profile.agentInstructions.carriers.map((item) => `${item.name}:${item.files}`), + ["AGENTS.md:2", "CLAUDE.md:2"], + ); + assert.ok(profile.agentInstructions.files.some((item) => item.path === "CLAUDE.md" && item.scope === ".")); + assert.ok(profile.agentInstructions.files.some((item) => item.path === "src/CLAUDE.md" && item.scope === "src")); + } finally { + await rm(repo, { recursive: true, force: true }); + } +}); + test("large root-only projects report thin AGENTS instruction density", async () => { const files = { "package.json": JSON.stringify({ name: "large-root-only" }), @@ -294,21 +322,83 @@ test("large root-only projects report thin AGENTS instruction density", async () for (let index = 0; index < 501; index += 1) { files[`src/module_${String(index).padStart(3, "0")}.ts`] = `export const value${index} = ${index};\n`; } + for (let index = 0; index < 20; index += 1) { + files[`tmp/generated_${String(index).padStart(2, "0")}.ts`] = `export const scratch${index} = ${index};\n`; + } const repo = await makeRepo(files); try { const profile = await analyzeProjectProfile({ cwd: repo, languages: "typescript" }); - assert.equal(profile.totals.sourceFiles, 501); + assert.equal(profile.totals.sourceFiles, 521); assert.equal(profile.agentInstructions.count, 1); assert.equal(profile.agentInstructions.rootCount, 1); assert.equal(profile.agentInstructions.nestedCount, 0); assert.equal(profile.agentInstructions.status, "thin"); assert.equal(profile.agentInstructions.suggestedMinimum, 3); assert.equal(profile.agentInstructions.suggestedAdditional, 2); - assert.equal(profile.agentInstructions.sourceFilesPerInstruction, 501); + assert.equal(profile.agentInstructions.sourceFilesPerInstruction, 521); assert.equal(profile.agentInstructions.sourceFilesUnderNestedInstructions, 0); assert.ok(profile.agentInstructions.suggestedScopes.some((item) => item.path === "src")); + assert.equal(profile.agentInstructions.suggestedScopes.some((item) => item.path.startsWith("tmp")), false); + } finally { + await rm(repo, { recursive: true, force: true }); + } +}); + +test("project-owned validation gates surface in the profile and validate-impact action", async () => { + const repo = await makeRepo({ + "package.json": JSON.stringify({ + name: "gated-project", + scripts: { + build: "node build.mjs", + custom: "node custom.mjs", + lint: "eslint .", + serve: "node server.mjs", + test: "node --test", + "test:unit": "node --test unit", + }, + }), + "justfile": [ + "test:", + " node --test", + "lint:", + " eslint .", + "serve:", + " node server.mjs", + "", + ].join("\n"), + "packages/api/package.json": JSON.stringify({ + name: "api", + scripts: { test: "node --test", deploy: "node deploy.mjs" }, + }), + "src/app.ts": "export function app() { return true; }\n", + }); + + try { + const profile = await analyzeProjectProfile({ cwd: repo }); + const pack = await buildEvidencePack({ cwd: repo, baseRef: "HEAD", noHistory: true, maxFollowUpActions: 20 }); + + const discovered = profile.projectGates.map((gate) => `${gate.kind}:${gate.sourcePath}:${gate.name}`); + assert.deepEqual(discovered, [ + "just-recipe:justfile:lint", + "just-recipe:justfile:test", + "package-script:package.json:build", + "package-script:package.json:lint", + "package-script:package.json:test", + "package-script:package.json:test:unit", + "package-script:packages/api/package.json:test", + ]); + assert.equal(discovered.some((gate) => /:custom$|:serve$|:deploy$/u.test(gate)), false); + assert.deepEqual( + profile.projectGates.find((gate) => gate.sourcePath === "packages/api/package.json")?.command, + ["npm", "--prefix", "packages/api", "run", "test"], + ); + assert.deepEqual(pack.summary.projectGates, profile.projectGates); + const validation = pack.followUpActions.find((action) => action.id === "validate-impact"); + assert.ok(validation); + assert.deepEqual(validation.commands, profile.projectGates); + assert.match(validation.reason, /Project-owned validation gates/u); } finally { await rm(repo, { recursive: true, force: true }); } @@ -418,6 +508,68 @@ test("history separates supporting hotspots and evidence pack emits follow-up ac } }); +test("history windows read independent commit ranges and disclose bounded coverage", async () => { + const repo = await mkdtemp(path.join(os.tmpdir(), "better-harness-window-history-")); + git(repo, ["init", "-q"]); + git(repo, ["config", "user.email", "test@example.com"]); + git(repo, ["config", "user.name", "Test User"]); + const now = Date.now(); + await writeFixtureFile(repo, "package.json", "{}\n"); + await writeFixtureFile(repo, "src/recent.ts", "export const recent = 0;\n"); + await writeFixtureFile(repo, "src/mid.ts", "export const mid = 0;\n"); + await writeFixtureFile(repo, "src/old.ts", "export const old = 0;\n"); + git(repo, ["add", "."]); + const initialDate = new Date(now - 300 * 24 * 60 * 60 * 1000).toISOString(); + git(repo, ["commit", "-q", "-m", "initial"], { + env: { GIT_AUTHOR_DATE: initialDate, GIT_COMMITTER_DATE: initialDate }, + }); + + try { + const groups = [ + { offsetDays: 120, count: 5, file: "src/old.ts", label: "old" }, + { offsetDays: 60, count: 3, file: "src/mid.ts", label: "mid" }, + { offsetDays: 10, count: 4, file: "src/recent.ts", label: "recent" }, + ]; + let sequence = 0; + for (const group of groups) { + for (let index = 0; index < group.count; index += 1) { + const timestamp = new Date( + now - group.offsetDays * 24 * 60 * 60 * 1000 + index * 60 * 1000, + ).toISOString(); + await writeFixtureFile( + repo, + group.file, + `export const value = "${group.label}-${index}-${sequence += 1}";\n`, + ); + git(repo, ["add", "."]); + git(repo, ["commit", "-q", "-m", `${group.label} ${index}`], { + env: { GIT_AUTHOR_DATE: timestamp, GIT_COMMITTER_DATE: timestamp }, + }); + } + } + + const history = await analyzeGitHistoryProfile({ cwd: repo, maxCommits: 50 }); + const windows = Object.fromEntries(history.historyWindows.map((item) => [item.days, item])); + + assert.deepEqual(history.historyWindows.map((item) => item.analyzedCommits), [4, 7, 12]); + assert.ok(windows[30].hotFiles.some((item) => item.path === "src/recent.ts")); + assert.equal(windows[30].hotFiles.some((item) => item.path === "src/old.ts"), false); + assert.ok(windows[180].hotFiles.some((item) => item.path === "src/old.ts")); + assert.ok(history.historyWindows.every((item) => item.coverage === "complete" && item.truncated === false)); + assert.ok(history.historyWindows.every((item) => item.commitLimit === 50)); + + const bounded = await buildEvidencePack({ cwd: repo, baseRef: "HEAD", maxCommits: 3 }); + const coverage = bounded.reviewMatrix.find((item) => item.id === "history-window-coverage"); + assert.equal(bounded.historyProfile.confidence.confidence, "low"); + assert.ok(bounded.historyProfile.historyWindows.every((item) => item.coverage === "truncated")); + assert.equal(coverage.status, "review"); + assert.deepEqual(coverage.evidence.truncatedWindows, [30, 90, 180]); + assert.deepEqual(coverage.evidence.coverage.map((item) => item.status), ["truncated", "truncated", "truncated"]); + } finally { + await rm(repo, { recursive: true, force: true }); + } +}); + test("project profile and core candidates detect PHP framework signals without promoting support files", async () => { const repo = await makeRepo({ "composer.json": JSON.stringify({ diff --git a/test/governance/workspace-topology.test.mjs b/test/governance/workspace-topology.test.mjs index 54f509b7..e43e905f 100644 --- a/test/governance/workspace-topology.test.mjs +++ b/test/governance/workspace-topology.test.mjs @@ -7,6 +7,7 @@ import { test } from "vitest"; import { main as topologyMain, parseArgs as parseTopologyArgs } from "../../scripts/workspace-topology/cli.mjs"; import { pathIdentityKey } from "../../scripts/workspace-topology/contract.mjs"; +import { createDirectoryLink, skipWithoutFileLink } from "../support/path-links.mjs"; import { WORKSPACE_TOPOLOGY_KIND, findingTargetErrors, @@ -31,7 +32,7 @@ test("configured cwd uses segment-aware canonical containment", async () => { mkdir(sibling, { recursive: true }), mkdir(outside, { recursive: true }), ]); - await symlink(outside, escape, "dir"); + await createDirectoryLink(outside, escape); const canonicalWorkspace = await realpath(workspace); assert.deepEqual(resolveConfiguredCwd({ workspace }), { @@ -459,7 +460,7 @@ test("workspace topology resolves a symlinked package through its real path", as }); const links = await mkdtemp(path.join(os.tmpdir(), "better-harness-topology-links-")); const link = path.join(links, "app-link"); - await symlink(path.join(repo, "packages/app"), link, "dir"); + await createDirectoryLink(path.join(repo, "packages/app"), link); try { const result = await resolveWorkspaceTopology({ workspace: link }); @@ -731,7 +732,8 @@ test("workspace topology rejects a tracked manifest symlink to another manifest } }); -test("workspace topology does not follow a tracked structural symlink outside the Git root", async () => { +test("workspace topology does not follow a tracked structural symlink outside the Git root", async (t) => { + if (await skipWithoutFileLink(t)) return; const repo = await makeGitRepo({ "package.json": JSON.stringify({ workspaces: ["packages/*"] }), "packages/app/package.json": JSON.stringify({ name: "app" }), diff --git a/test/plugins/antigravity-plugin-artifact.test.mjs b/test/plugins/antigravity-plugin-artifact.test.mjs index 96bc9df6..9f6ceab9 100644 --- a/test/plugins/antigravity-plugin-artifact.test.mjs +++ b/test/plugins/antigravity-plugin-artifact.test.mjs @@ -1002,7 +1002,7 @@ test("builds, verifies, runs, and atomically replaces the real pinned artifact", } finally { await rm(container, { recursive: true, force: true }); } -}, 30_000); +}, 120_000); test("preserves unowned and full-invalid destinations before copying", async () => { const repoRoot = await createSourceRepo(); diff --git a/test/plugins/plugin-lifecycle.test.mjs b/test/plugins/plugin-lifecycle.test.mjs index 4844e4cb..1c048f12 100644 --- a/test/plugins/plugin-lifecycle.test.mjs +++ b/test/plugins/plugin-lifecycle.test.mjs @@ -1,10 +1,11 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; -import { mkdir, mkdtemp, readFile, readdir, readlink, rm, symlink, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readFile, readdir, readlink, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { test } from "vitest"; +import { createDirectoryLink } from "../support/path-links.mjs"; import { getHostProfile } from "../../scripts/host-support/index.mjs"; import { runHarnessDoctor } from "../../scripts/harness-doctor/index.mjs"; import { @@ -761,7 +762,7 @@ test("status, plan, and verify do not mutate an isolated host home", async () => await mkdir(hostHome, { recursive: true }); await mkdir(workspace, { recursive: true }); const workspaceLink = path.join(root, "workspace link ΓΌ"); - await symlink(workspace, workspaceLink, "dir"); + await createDirectoryLink(workspace, workspaceLink); await writeFile(path.join(hostHome, "keep.txt"), "user-owned\n"); const before = await snapshotTree(root); await inspectPluginLifecycle({ host: "codex", hostHome, workspace: workspaceLink, env: { PATH: "" } }); diff --git a/test/reporting/better-harness-evidence-bundle.test.mjs b/test/reporting/better-harness-evidence-bundle.test.mjs index 3d417b27..b6e3d24a 100644 --- a/test/reporting/better-harness-evidence-bundle.test.mjs +++ b/test/reporting/better-harness-evidence-bundle.test.mjs @@ -1,5 +1,6 @@ import assert from "node:assert/strict"; -import { mkdir, mkdtemp, realpath, rm, symlink, writeFile } from "node:fs/promises"; +import { execFileSync } from "node:child_process"; +import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { test } from "vitest"; @@ -17,8 +18,10 @@ import { import { workspaceToClaudeSlugVariants } from "../../scripts/session-analysis/platforms/claude.mjs"; import { collectAgentCustomize } from "../../scripts/harness-analysis/evidence-bundle/agent-customize.mjs"; import { collectProjectHarness } from "../../scripts/harness-analysis/evidence-bundle/project-harness.mjs"; +import { analyzeHarnessEvidence } from "../../scripts/harness-analysis/report-run.mjs"; import { EVIDENCE_BUNDLE_HELP } from "../../scripts/harness-analysis/evidence-bundle/cli.mjs"; import { collectAssetBaseline } from "../../scripts/coding-agent-practices/asset-baseline.mjs"; +import { createDirectoryLink } from "../support/path-links.mjs"; const NOW = new Date("2026-07-24T08:00:00.000Z"); @@ -203,6 +206,22 @@ function topologyResolution(workspace = ".", status = "complete") { }); } +function initializeGitWorkspace(workspace) { + const run = (args, env) => execFileSync("git", args, { + cwd: workspace, + stdio: "ignore", + env: env ? { ...process.env, ...env } : process.env, + }); + run(["init", "-q"]); + run(["config", "user.email", "test@example.com"]); + run(["config", "user.name", "Test User"]); + run(["add", "."]); + run(["commit", "-q", "-m", "initial"], { + GIT_AUTHOR_DATE: "2026-07-20T09:00:00.000Z", + GIT_COMMITTER_DATE: "2026-07-20T09:00:00.000Z", + }); +} + function dependencies(overrides = {}) { const population = Object.freeze({ sessions: Object.freeze([{ sessionId: "eligible-session" }]), @@ -258,7 +277,7 @@ test("evidence bundle v3 freezes canonical default, nested, and aliased cwd iden const nested = path.join(workspace, "packages", "api", "src with space", "\u5b50\u76ee\u5f55"); const alias = path.join(workspace, "cwd-alias"); await mkdir(nested, { recursive: true }); - await symlink(nested, alias, "dir"); + await createDirectoryLink(nested, alias); const omitted = freezeEvidenceBundleContext({ workspace }, NOW); const explicitWorkspace = freezeEvidenceBundleContext({ workspace, cwd: workspace }, NOW); @@ -282,7 +301,7 @@ test("evidence bundle cwd validation fails closed before configured collection", await mkdir(workspace, { recursive: true }); await mkdir(outside, { recursive: true }); await writeFile(file, "not a directory\n"); - await symlink(outside, escape, "dir"); + await createDirectoryLink(outside, escape); for (const cwd of ["", `${workspace}\u0000invalid`, path.join(workspace, "missing"), file]) { assert.throws( @@ -1086,6 +1105,8 @@ test("Claude population freeze and Session facts agree under one frozen topology const elsewhere = path.join(fixture, "elsewhere"); const home = path.join(fixture, ".claude"); await mkdir(workspace, { recursive: true }); + await writeFile(path.join(workspace, "package.json"), "{}\n"); + initializeGitWorkspace(workspace); const projectRoot = path.join(home, "projects", workspaceToClaudeSlugVariants(workspace)[0]); await mkdir(projectRoot, { recursive: true }); const row = (sessionId, cwd, second) => JSON.stringify({ @@ -1123,6 +1144,27 @@ test("Claude population freeze and Session facts agree under one frozen topology assert.equal(lane.data.scope.eligibleSessions, population.binding.eligible.count); assert.equal(lane.data.scope.selectedSessions, population.binding.eligible.count); assert.doesNotMatch(JSON.stringify(lane.data), /clean-private|conflict-private/u); + + const bundle = await collectEvidenceBundle({ + workspace, + platform: "claude", + depth: "normal", + since: "2026-07-01T00:00:00.000Z", + until: "2026-07-24T08:00:00.000Z", + topology: resolution.topology, + analysisScope: resolution.analysisScope, + "claude-home": home, + }, dependencies({ + resolveWorkspaceTopology: async () => resolution, + collectSessionPopulation, + collectSessionEvidence, + analyzeHarnessEvidence, + })); + + assert.equal(bundle.lead.status, "available", JSON.stringify(bundle.lead.error)); + assert.ok(bundle.lead.data.sessionBinding); + assert.equal(bundle.diagnostics.sessionPopulationBinding.status, "bound"); + assert.equal(bundle.diagnostics.sessionPopulationBinding.leadObserved, true); } finally { await rm(fixture, { recursive: true, force: true }); } diff --git a/test/reporting/harness-report-render-cli.test.mjs b/test/reporting/harness-report-render-cli.test.mjs index ccbb3a19..e7b18e67 100644 --- a/test/reporting/harness-report-render-cli.test.mjs +++ b/test/reporting/harness-report-render-cli.test.mjs @@ -1,7 +1,7 @@ import assert from "node:assert/strict"; import { spawnSync } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; -import { mkdir, mkdtemp, readdir, realpath, rm, symlink, writeFile } from "node:fs/promises"; +import { mkdir, mkdtemp, readdir, realpath, rm, writeFile } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; @@ -16,6 +16,7 @@ import { import { HOST_CAPABILITIES, hostIdsFor } from "../../scripts/host-support/index.mjs"; import { renderCanvasTsx } from "../../scripts/harness-analysis/renderers/qoder-canvas.mjs"; import { buildTaskLoopSourceCandidate } from "../../scripts/harness-analysis/task-loop-source.mjs"; +import { createDirectoryLink } from "../support/path-links.mjs"; import { applyEpisodeReviews } from "../../scripts/harness-analysis/episode-evidence-review.mjs"; import { projectTaskLoopFindings } from "../../scripts/harness-analysis/task-loop-report.mjs"; @@ -656,7 +657,7 @@ test("render canonicalizes both target and frozen topology workspace identities" const packageRoot = path.join(root, "packages", "a"); const packageLink = path.join(root, "package-a-link"); const findingsPath = path.join(root, "target.findings.json"); - await symlink(packageRoot, packageLink, "dir"); + await createDirectoryLink(packageRoot, packageLink); await writeJson(findingsPath, targetFindingData()); await assert.rejects( diff --git a/test/sessions/session-analysis.test.mjs b/test/sessions/session-analysis.test.mjs index 6ea162a1..897c18a8 100644 --- a/test/sessions/session-analysis.test.mjs +++ b/test/sessions/session-analysis.test.mjs @@ -5,6 +5,7 @@ import path from "node:path"; import { test } from "vitest"; import { createAnalyzer } from "../../scripts/session-analysis.mjs"; +import { defaultQoderHome, resolveQoderSessionHome } from "../../scripts/host-support/qoder-home.mjs"; import { mergeQoderAssistantContextIntoResponses, QoderSessionAnalyzer, @@ -660,10 +661,10 @@ test("privacy-safe user input summaries redact GitLab tokens and hierarchical UR } }); -async function makeQoderFixture() { +async function makeQoderFixture({ homeName = ".qoder" } = {}) { const root = await mkdtemp(path.join(os.tmpdir(), "better-harness-session-analysis-")); const workspace = path.join(root, "workspace", "better-harness"); - const home = path.join(root, ".qoder"); + const home = path.join(root, homeName); const slug = workspaceToQoderSlug(workspace); const sessionId = "session-a"; @@ -783,6 +784,44 @@ test("Qoder workspace slugs cover both Windows directory conventions", () => { assert.equal(workspaceToQoderSlug(String.raw`e:\projects\xp-gate`), "e--projects-xp-gate"); }); +test("Qoder session analysis honors QODER_HOME and prefers a default .qoder-cn home", async () => { + const fixture = await makeQoderFixture({ homeName: ".qoder-cn" }); + const previous = { + QODER_HOME: process.env.QODER_HOME, + HOME: process.env.HOME, + USERPROFILE: process.env.USERPROFILE, + }; + const restore = () => { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }; + + try { + process.env.QODER_HOME = fixture.home; + assert.equal(resolveQoderSessionHome({}), path.resolve(fixture.home)); + const fromEnvironment = await new QoderSessionAnalyzer().analyze({ + workspace: fixture.workspace, + command: "sessions", + }); + assert.ok(fromEnvironment.sessions.some((session) => session.sessionId === fixture.sessionId)); + + delete process.env.QODER_HOME; + process.env.HOME = fixture.root; + process.env.USERPROFILE = fixture.root; + assert.equal(defaultQoderHome(), path.resolve(fixture.home)); + const fromDefault = await new QoderSessionAnalyzer().analyze({ + workspace: fixture.workspace, + command: "sessions", + }); + assert.ok(fromDefault.sessions.some((session) => session.sessionId === fixture.sessionId)); + } finally { + restore(); + await rm(fixture.root, { recursive: true, force: true }); + } +}); + test("Qoder analyzer scans every existing Windows workspace slug variant", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "better-harness-qoder-windows-slug-")); const home = path.join(root, ".qoder"); diff --git a/test/support/path-links.mjs b/test/support/path-links.mjs new file mode 100644 index 00000000..3f7b3cca --- /dev/null +++ b/test/support/path-links.mjs @@ -0,0 +1,37 @@ +import { mkdtemp, rm, symlink, writeFile } from "node:fs/promises"; +import os from "node:os"; +import path from "node:path"; + +const LINK_ERROR_CODES = new Set(["EACCES", "EINVAL", "ENOSYS", "EPERM"]); + +export async function createDirectoryLink(target, linkPath) { + await symlink(target, linkPath, process.platform === "win32" ? "junction" : "dir"); +} + +async function detectFileLinkSupport() { + const root = await mkdtemp(path.join(os.tmpdir(), "better-harness-file-link-")); + try { + const target = path.join(root, "target.txt"); + await writeFile(target, "target\n", "utf8"); + await symlink(target, path.join(root, "link.txt"), "file"); + return true; + } catch (error) { + if (LINK_ERROR_CODES.has(error?.code)) return false; + throw error; + } finally { + await rm(root, { recursive: true, force: true }); + } +} + +let fileLinkSupport; + +export async function fileLinksSupported() { + fileLinkSupport ??= detectFileLinkSupport(); + return fileLinkSupport; +} + +export async function skipWithoutFileLink(t) { + if (await fileLinksSupported()) return false; + t.skip("file symlink creation is not permitted on this host"); + return true; +} From a57855fc6ae4801a0f4153c459a02108cfbb7186 Mon Sep 17 00:00:00 2001 From: Dzuhaib Date: Mon, 26 Oct 2026 00:15:04 +0500 Subject: [PATCH 2/3] fix(analysis): address host discovery and evidence review Ignore a QODER_HOME that names the shared client cache, route the remaining Qoder fallbacks through the shared asset resolver, and report a provider-default fallback label. Count instruction scopes once when AGENTS.md and CLAUDE.md share a directory, while keeping the per-file and carrier breakdown. Reuse the bounded history scan for windows it already covers, make truncation exact at the commit limit, exclude watcher/dev/UI gates, and point the review matrix at --max-commits. Deduplicate Claude project rules by realpath and prefer the Qoder home that has session data. Spec: docs/specs/2026-10-24-harness-analysis-defects.md (Stories #212, #195, #164). Test: npm test (1767 passed, 30 skipped). Co-authored-by: opencode (DeepSeek V4.1 Flash Free) --- .../2026-10-24-harness-analysis-defects.md | 49 +++++++++------ scripts/agent-customize/providers/claude.mjs | 8 ++- .../checkup/sources.mjs | 16 ++++- scripts/core-change-watch/evidence-pack.mjs | 2 +- .../core-change-watch/git-history-profile.mjs | 34 ++++++---- scripts/core-change-watch/project-profile.mjs | 40 ++++++++---- scripts/harness-analysis/validate-canvas.mjs | 3 +- .../harness-component-snapshot/snapshot.mjs | 10 +-- scripts/host-support/profiles/qoder.mjs | 2 +- scripts/host-support/qoder-home.mjs | 31 +++++++-- test/cli/harness-doctor.test.mjs | 2 +- test/governance/core-change-watch.test.mjs | 18 ++++-- test/plugins/host-support-profiles.test.mjs | 2 +- test/sessions/session-analysis.test.mjs | 63 +++++++++++++++++++ 14 files changed, 211 insertions(+), 69 deletions(-) diff --git a/docs/specs/2026-10-24-harness-analysis-defects.md b/docs/specs/2026-10-24-harness-analysis-defects.md index 132ef386..3348d9f3 100644 --- a/docs/specs/2026-10-24-harness-analysis-defects.md +++ b/docs/specs/2026-10-24-harness-analysis-defects.md @@ -24,23 +24,33 @@ analysis must continue to fail closed when real binding conflicts exist. - AC-1: `--qoder-home` remains explicit and wins over environment/defaults, and help for `harness analyze`, `harness evidence-bundle`, and task-loop source - advertises the option. `QODER_HOME` is honored by the Qoder session analyzer, - including a `.qoder-cn` asset home, and the default selects an existing - `~/.qoder-cn` before `~/.qoder`. -- AC-2: history windows use independent git ranges instead of slicing one global - commit list, so 30/90/180-day windows can report different commit counts and - hotspots. Every window exposes its commit limit, truncation state, and coverage - status. + advertises the option. `QODER_HOME` is honored by the Qoder session analyzer + only when it names an asset home (including `.qoder-cn`); a shared-client-cache + value is ignored. The default prefers `~/.qoder-cn` only when `~/.qoder` is + absent or has no session data. +- AC-2: history windows report independent ranges, so 30/90/180-day windows can + report different commit counts and hotspots. A window reuses the bounded main + scan when that scan reaches older than the window, and queries Git for the + window otherwise. Every window exposes its commit limit, truncation state, and + coverage status, with truncation exact at the limit. - AC-3: `history-window-coverage` is `review` rather than `ready` when history confidence is low or any window is truncated, while retaining the existing - ready behavior for complete high/medium-confidence history. + ready behavior for complete high/medium-confidence history. The matrix note + explains that raising `--max-commits` completes the 30/90/180-day windows in a + very active repository. - AC-4: instruction analysis recognizes root and nested `AGENTS.md` and - `CLAUDE.md` carriers, excludes scratch directories from suggested scopes, and - reports carrier kinds without changing the existing density thresholds. + `CLAUDE.md` carriers, counts each directory scope once when both carriers + exist, excludes scratch directories from suggested scopes and the suggested + instruction minimum, and reports carrier kinds without changing the existing + density thresholds. - AC-5: evidence packs expose project-owned package and Just gates, and the - `validate-impact` action includes those exact commands when available. + `validate-impact` action includes those exact commands when available. Gates + that start long-running watchers, dev servers, or UI/open-headed sessions are + not presented as validation commands. - AC-6: Claude project Rules inventory includes a root `AGENTS.md` compatibility - entry without duplicating `CLAUDE.md`. + entry without duplicating `CLAUDE.md`. This relies on Claude Code reading + `AGENTS.md` as project instructions; see + . - AC-7: an integration test proves an injected session population keeps the lead lane available and carries `sessionBinding`, while the genuine conflict test still downgrades the lead to `SESSION_POPULATION_BINDING_MISMATCH`. @@ -59,8 +69,9 @@ analysis must continue to fail closed when real binding conflicts exist. 1. Align Qoder home resolution across asset and session analysis, and document the accepted host-home option. -2. Fetch and filter each history window independently, add coverage metadata, - and make the review matrix consume it. +2. Fetch and filter each history window independently, reuse the main scan when + it covers the window, add coverage metadata, and make the review matrix + consume it. 3. Extend instruction carriers, scope filtering, and project gate extraction. 4. Add root `AGENTS.md` to the Claude Rules inventory. 5. Add a lead/session binding integration regression and keep the conflict test. @@ -74,10 +85,12 @@ analysis must continue to fail closed when real binding conflicts exist. - `test/agents/agent-customize.test.mjs` covers Qoder provider `QODER_HOME` resolution and the Claude Rules root `AGENTS.md` compatibility entry. - `test/sessions/session-analysis.test.mjs` exercises Qoder session roots from - `QODER_HOME` and the `~/.qoder-cn` default. + `QODER_HOME`, rejects a non-asset `QODER_HOME` (shared client cache), the + `~/.qoder-cn` default, and the both-homes preference. - `test/governance/core-change-watch.test.mjs` covers independent history - windows, truncation downgrade, instruction carriers, scratch-scope exclusion, - and project gates in the `validate-impact` action. + windows, exact truncation at the commit limit, instruction scope deduplication, + scratch-scope exclusion, non-terminating gate exclusion, and project gates in + the `validate-impact` action. - `test/reporting/better-harness-evidence-bundle.test.mjs` exercises the real Claude lead/session binding path and keeps the genuine conflict regression. - `packages/harness-studio-apps/test/test_file_explorer.mjs` passes on Windows @@ -86,4 +99,4 @@ analysis must continue to fail closed when real binding conflicts exist. junctions and skips only the two file-symlink cases when the host denies them. - The DSH explicit-root fixture isolates `HOME`/`USERPROFILE`, so external roots are not accidentally classified as user-home paths. -- Full `npm test` on 2026-10-25: 1765 passed, 30 skipped, 0 failed. +- Full `npm test` on 2026-10-25: 1767 passed, 30 skipped, 0 failed. diff --git a/scripts/agent-customize/providers/claude.mjs b/scripts/agent-customize/providers/claude.mjs index 52307d57..e23a5e40 100644 --- a/scripts/agent-customize/providers/claude.mjs +++ b/scripts/agent-customize/providers/claude.mjs @@ -167,13 +167,17 @@ async function collectProjectRules(workspace, sourceLabel, claudeRoot = path.joi "claude-project", ], [path.join(workspace, "CLAUDE.local.md"), "CLAUDE.local.md", "claude-local", "claude-local"], + // Claude Code reads a root AGENTS.md when no CLAUDE.md claims the project. + // See https://code.claude.com/docs/en/memory#agents-md. [path.join(workspace, "AGENTS.md"), "AGENTS.md", "agents-md-compat", "agents-md-compat"], ]; const files = []; const visited = new Set(); for (const [filePath, name, sourceKind, precedence] of fileDefinitions) { - if (visited.has(filePath)) continue; - visited.add(filePath); + const resolvedPath = path.resolve(filePath); + const key = await realpath(resolvedPath).catch(() => resolvedPath); + if (visited.has(key)) continue; + visited.add(key); files.push(...await collectMarkdownFileRuleItem(filePath, "project", sourceLabel, workspace, { name, sourceKind, diff --git a/scripts/coding-agent-practices/checkup/sources.mjs b/scripts/coding-agent-practices/checkup/sources.mjs index 144ae8eb..486a914f 100644 --- a/scripts/coding-agent-practices/checkup/sources.mjs +++ b/scripts/coding-agent-practices/checkup/sources.mjs @@ -1,6 +1,9 @@ -import os from "node:os"; import path from "node:path"; +import { + looksLikeQoderAssetHome, + resolveQoderAssetHome, +} from "../../host-support/qoder-home.mjs"; import { expandHome, pathExists } from "../../session-analysis/index.mjs"; function resolved(value) { @@ -30,8 +33,15 @@ export async function collectQoderSourceResolution(options = {}, inventory = {}) const explicitHome = options.qoderHome; const environmentHome = process.env.QODER_HOME; + const environmentIsAssetHome = looksLikeQoderAssetHome(environmentHome); const inventoryHome = inventory.qoderHome; - const activeHome = resolved(explicitHome ?? environmentHome ?? inventoryHome ?? path.join(os.homedir(), ".qoder")); + const activeHome = explicitHome + ? resolved(explicitHome) + : environmentIsAssetHome + ? resolved(environmentHome) + : inventoryHome + ? resolved(inventoryHome) + : resolveQoderAssetHome(); const workspace = path.resolve(options.workspace ?? process.cwd()); const sharedRoot = inventory.sharedClientCacheRoot ? path.resolve(inventory.sharedClientCacheRoot) @@ -81,7 +91,7 @@ export async function collectQoderSourceResolution(options = {}, inventory = {}) state: "selected", activeHomeEvidence: explicitHome ? "explicit-option" - : environmentHome + : environmentIsAssetHome ? "environment" : inventoryHome ? "inventory-resolver" diff --git a/scripts/core-change-watch/evidence-pack.mjs b/scripts/core-change-watch/evidence-pack.mjs index 2653691b..6e8a8cae 100644 --- a/scripts/core-change-watch/evidence-pack.mjs +++ b/scripts/core-change-watch/evidence-pack.mjs @@ -413,7 +413,7 @@ function buildReviewMatrix(projectProfile, historyProfile, coreAnalysis, diffImp truncatedWindows: historyProfile.historyWindows.filter((item) => item.truncated).map((item) => item.days), coverage: historyProfile.historyWindows.map((item) => ({ days: item.days, status: item.coverage })), }, - "Low history confidence or a bounded-window truncation should downgrade hotspot certainty, not block source inspection.", + "Low history confidence or a bounded-window truncation should downgrade hotspot certainty, not block source inspection. Raise --max-commits to complete the 30/90/180-day windows in an active repository.", ), matrixItem( "large-repo-safety", diff --git a/scripts/core-change-watch/git-history-profile.mjs b/scripts/core-change-watch/git-history-profile.mjs index 019ba80c..c9b7f8b9 100644 --- a/scripts/core-change-watch/git-history-profile.mjs +++ b/scripts/core-change-watch/git-history-profile.mjs @@ -137,10 +137,10 @@ function collectHistoryStats(commits, allowedLanguages, analysisScope) { }; } -function readHistoryLog(repoRoot, maxCommits, analysisScope, sinceSeconds) { +function readHistoryLog(repoRoot, commitLimit, analysisScope, sinceSeconds) { const args = [ "log", - `-${maxCommits}`, + `-${commitLimit}`, "--numstat", "--format=commit%x1f%H%x1f%ct%x1f%s", ]; @@ -155,19 +155,22 @@ function historyWindows(commits, allowedLanguages, daysList, analysisScope, { repoRoot, maxCommits, ignore, + mainTruncated, }) { const nowSeconds = Math.floor(Date.now() / 1000); return daysList.map((days) => { const sinceSeconds = nowSeconds - days * 24 * 60 * 60; - const windowParsed = commits.length === 0 - ? [] - : readHistoryLog(repoRoot, maxCommits, analysisScope, sinceSeconds); - const windowCommits = commits.length === 0 - ? [] - : applyCommitIgnores(windowParsed, ignore).commits; + const oldestTimestamp = commits.at(-1)?.timestamp; + const scanCoversWindow = !mainTruncated + || (oldestTimestamp !== undefined && oldestTimestamp < sinceSeconds); + const windowParsed = scanCoversWindow + ? commits.filter((commit) => commit.timestamp >= sinceSeconds) + : readHistoryLog(repoRoot, maxCommits + 1, analysisScope, sinceSeconds); + const truncated = windowParsed.length > maxCommits; + const boundedParsed = truncated ? windowParsed.slice(0, maxCommits) : windowParsed; + const windowCommits = applyCommitIgnores(boundedParsed, ignore).commits; const stats = collectHistoryStats(windowCommits, allowedLanguages, analysisScope); const trend = trendForWindow(days, windowCommits.length); - const truncated = windowParsed.length >= maxCommits; return { days, @@ -198,7 +201,7 @@ function trendForWindow(days, analyzedCommits) { }; } -function historyConfidence(commits, maxCommits) { +function historyConfidence(commits, maxCommits, truncated) { if (commits.length === 0) { return { confidence: "low", reasons: ["no commits were available in the bounded history scan"] }; } @@ -215,7 +218,7 @@ function historyConfidence(commits, maxCommits) { if (spanDays < 30) { reasons.push(`history span is only ${spanDays} days`); } - if (commits.length >= maxCommits) { + if (truncated) { reasons.push(`bounded at maxCommits=${maxCommits}`); } return { @@ -256,7 +259,7 @@ export async function analyzeGitHistoryProfile(options = {}) { const allowedLanguages = new Set(normalizeLanguages(options.languages)); let parsedCommits; try { - parsedCommits = readHistoryLog(repoRoot, maxCommits, analysisScope); + parsedCommits = readHistoryLog(repoRoot, maxCommits + 1, analysisScope); } catch (error) { // An unborn repository is a valid empty history. Every other Git failure, // including a malformed scope/pathspec, remains a hard coverage failure. @@ -271,6 +274,10 @@ export async function analyzeGitHistoryProfile(options = {}) { } if (parsedCommits === undefined) throw error; } + const mainTruncated = parsedCommits.length > maxCommits; + if (mainTruncated) { + parsedCommits = parsedCommits.slice(0, maxCommits); + } const filteredHistory = applyCommitIgnores(parsedCommits, options.ignore); const commits = filteredHistory.commits; const stats = collectHistoryStats(commits, allowedLanguages, analysisScope); @@ -289,11 +296,12 @@ export async function analyzeGitHistoryProfile(options = {}) { newest: commits[0]?.shortSha ?? null, oldest: commits.at(-1)?.shortSha ?? null, }, - confidence: historyConfidence(commits, maxCommits), + confidence: historyConfidence(commits, maxCommits, mainTruncated), historyWindows: historyWindows(commits, allowedLanguages, windowDays, analysisScope, { repoRoot, maxCommits, ignore: options.ignore, + mainTruncated, }), languageTouchCounts: sortedCounts(stats.languageStats, 12).map((item) => ({ language: item.name, diff --git a/scripts/core-change-watch/project-profile.mjs b/scripts/core-change-watch/project-profile.mjs index b588117a..f7643139 100644 --- a/scripts/core-change-watch/project-profile.mjs +++ b/scripts/core-change-watch/project-profile.mjs @@ -56,6 +56,7 @@ const MANIFESTS = new Set([ const AGENT_INSTRUCTION_FILES = new Set(["AGENTS.md", "CLAUDE.md"]); const SCRATCH_DIRECTORIES = new Set([".cache", ".state", ".tmp", ".scratch", "coverage", "scratch", "temp", "tmp"]); const PROJECT_GATE_PATTERN = /^(?:build|check|ci|e2e|lint|smoke|test|type-?check|validate|verify)(?::.+)?$/iu; +const NON_TERMINATING_GATE_SUFFIXES = new Set(["watch", "dev", "ui", "headed", "open"]); const SOURCE_FILES_PER_AGENT_INSTRUCTION = 250; const SIGNIFICANT_SOURCE_ROOT_FILES = 100; const SOURCE_LINE_METHOD = "tracked readable primary source files only; excludes tests, non-source assets, generated/dependency paths, and untracked files"; @@ -487,13 +488,21 @@ function agentInstructionStatus(count, suggestedMinimum) { return "adequate"; } +function isProjectGateScript(name) { + if (!PROJECT_GATE_PATTERN.test(name)) { + return false; + } + const suffixes = String(name).toLowerCase().split(":").slice(1); + return !suffixes.some((suffix) => NON_TERMINATING_GATE_SUFFIXES.has(suffix)); +} + function projectGates(manifests) { const gates = []; for (const manifest of manifests) { if (manifest.kind !== "node" && manifest.kind !== "just") continue; const prefix = manifest.kind === "node" ? path.posix.dirname(manifest.path) : "."; for (const name of manifest.scripts ?? []) { - if (!PROJECT_GATE_PATTERN.test(name)) continue; + if (!isProjectGateScript(name)) continue; const command = manifest.kind === "just" ? ["just", name] : ["npm", ...(prefix === "." ? [] : ["--prefix", prefix]), "run", name]; @@ -512,7 +521,11 @@ function projectGates(manifests) { function analyzeAgentInstructions({ trackedFiles, sourceRecords, sourceRoots, totals, analysisScope }) { const files = agentInstructionFiles(trackedFiles, analysisScope); - const nestedScopes = files.filter((item) => !item.targetRoot).map((item) => item.scope); + const instructionSourceRecords = sourceRecords.filter((source) => !isScratchDirectory(source.directory)); + const instructionSourceFiles = instructionSourceRecords.length; + const uniqueScopes = [...new Set(files.map((file) => file.scope))]; + const nestedScopes = [...new Set(files.filter((item) => !item.targetRoot).map((item) => item.scope))]; + const rootScopes = new Set(files.filter((item) => item.targetRoot).map((item) => item.scope)); const carrierCounts = new Map(); let sourceFilesUnderNestedInstructions = 0; const uncoveredSourceDirs = new Map(); @@ -530,21 +543,26 @@ function analyzeAgentInstructions({ trackedFiles, sourceRecords, sourceRoots, to } } - const rootCount = files.filter((item) => item.targetRoot).length; - const nestedCount = files.length - rootCount; - const suggestedMinimum = suggestedInstructionMinimum(totals, sourceRoots); - const suggestedAdditional = Math.max(0, suggestedMinimum - files.length); - const status = agentInstructionStatus(files.length, suggestedMinimum); + const count = uniqueScopes.length; + const rootCount = rootScopes.size; + const nestedCount = count - rootCount; + const instructionSourceRoots = sourceRoots.filter((root) => !isScratchDirectory(root.path)); + const suggestedMinimum = suggestedInstructionMinimum( + { ...totals, sourceFiles: instructionSourceFiles }, + instructionSourceRoots, + ); + const suggestedAdditional = Math.max(0, suggestedMinimum - count); + const status = agentInstructionStatus(count, suggestedMinimum); const reasons = []; if (rootCount > 0) { reasons.push("root agent instruction file present"); } if (nestedCount > 0) { - reasons.push(`${nestedCount} nested instruction files provide module-local guidance`); + reasons.push(`${nestedCount} nested instruction scopes provide module-local guidance`); } if (status === "thin") { - reasons.push(`instruction file count ${files.length} is below suggested minimum ${suggestedMinimum} for source scale`); + reasons.push(`instruction scope count ${count} is below suggested minimum ${suggestedMinimum} for source scale`); } if (status === "missing") { reasons.push("no tracked AGENTS.md or CLAUDE.md files found for a source-bearing repository"); @@ -554,7 +572,7 @@ function analyzeAgentInstructions({ trackedFiles, sourceRecords, sourceRoots, to } return { - count: files.length, + count, rootCount, nestedCount, carriers: sortedCounts(carrierCounts, 4).map((item) => ({ name: item.name, files: item.count })), @@ -562,7 +580,7 @@ function analyzeAgentInstructions({ trackedFiles, sourceRecords, sourceRoots, to status, suggestedMinimum, suggestedAdditional, - sourceFilesPerInstruction: files.length > 0 ? Math.ceil(totals.sourceFiles / files.length) : null, + sourceFilesPerInstruction: count > 0 ? Math.ceil(totals.sourceFiles / count) : null, sourceFilesUnderNestedInstructions, nestedSourceFileCoveragePercent: totals.sourceFiles > 0 ? Math.round((sourceFilesUnderNestedInstructions / totals.sourceFiles) * 100) diff --git a/scripts/harness-analysis/validate-canvas.mjs b/scripts/harness-analysis/validate-canvas.mjs index 29c7b027..a6807877 100644 --- a/scripts/harness-analysis/validate-canvas.mjs +++ b/scripts/harness-analysis/validate-canvas.mjs @@ -9,6 +9,7 @@ import { fileURLToPath } from "node:url"; import { createCanvasPreviewServer } from "./canvas-preview-server.mjs"; import { analyzeCanvasModuleBoundaries } from "./canvas-module-boundaries.mjs"; +import { resolveQoderAssetHome } from "../host-support/qoder-home.mjs"; import { transformCanvasSource } from "./preview-support/canvas-transform.mjs"; import { evaluateHarnessCanvasQuality, @@ -630,7 +631,7 @@ function readSdkExports(declarationsPath) { } function qoderHome(env = process.env) { - return env.QODER_HOME ? path.resolve(env.QODER_HOME) : path.join(os.homedir(), ".qoder"); + return resolveQoderAssetHome({ env }); } function uniquePaths(values) { diff --git a/scripts/harness-component-snapshot/snapshot.mjs b/scripts/harness-component-snapshot/snapshot.mjs index 51ea6846..2a46e44b 100644 --- a/scripts/harness-component-snapshot/snapshot.mjs +++ b/scripts/harness-component-snapshot/snapshot.mjs @@ -1,9 +1,9 @@ import { lstat, readFile, readdir, realpath, stat } from "node:fs/promises"; -import os from "node:os"; import path from "node:path"; import { collectAgentCustomizeInventory } from "../agent-customize/index.mjs"; -import { expandHome, isDirectory, normalizeWorkspace, pathExists } from "../session-analysis/index.mjs"; +import { resolveQoderAssetHome } from "../host-support/qoder-home.mjs"; +import { isDirectory, normalizeWorkspace, pathExists } from "../session-analysis/index.mjs"; import { COMPONENT_KINDS, SNAPSHOT_KIND, @@ -106,11 +106,7 @@ async function assertProjectReadBoundaries(readContext) { async function assertProjectDoesNotAliasQoderHome(readContext) { const { workspace } = readContext; - const environmentHome = process.env.QODER_HOME; - const environmentBase = path.basename(String(environmentHome ?? "")).toLowerCase(); - const qoderHome = environmentHome && [".qoder", "qoder"].includes(environmentBase) - ? expandHome(environmentHome) - : path.join(os.homedir(), ".qoder"); + const qoderHome = resolveQoderAssetHome(); const [projectRoot, userRoot] = await Promise.all([ canonicalPath(path.join(workspace, ".qoder")), canonicalPath(qoderHome), diff --git a/scripts/host-support/profiles/qoder.mjs b/scripts/host-support/profiles/qoder.mjs index b554bc1a..68775753 100644 --- a/scripts/host-support/profiles/qoder.mjs +++ b/scripts/host-support/profiles/qoder.mjs @@ -13,7 +13,7 @@ export default defineHostProfile({ displayName: "Qoder", provider: "qoder", inventoryHomeRoutes: [ - { option: "qoderHome", relativePath: "", fallbackLabel: "~/.qoder" }, + { option: "qoderHome", relativePath: "", fallbackLabel: "" }, { option: "qoderSharedClientCacheRoot", relativePath: "SharedClientCache", diff --git a/scripts/host-support/qoder-home.mjs b/scripts/host-support/qoder-home.mjs index 633e0e14..0873679b 100644 --- a/scripts/host-support/qoder-home.mjs +++ b/scripts/host-support/qoder-home.mjs @@ -3,7 +3,10 @@ import os from "node:os"; import path from "node:path"; const QODER_ASSET_HOME_NAMES = new Set([".qoder", "qoder", ".qoder-cn", "qoder-cn"]); +const QODER_SESSION_DIRECTORIES = ["audit", "logs", "projects", "sessions"]; +// Kept local because session-analysis re-exports the Qoder analyzer that +// imports this module, and the refactor contract forbids deep imports. function expandHome(filePath) { if (!filePath) return filePath; if (filePath === "~") return os.homedir(); @@ -11,14 +14,28 @@ function expandHome(filePath) { return filePath; } +function environmentFor(options = {}) { + return options.env ?? process.env; +} + export function looksLikeQoderAssetHome(candidate) { return QODER_ASSET_HOME_NAMES.has(path.basename(String(candidate ?? "")).toLowerCase()); } +function hasQoderSessionData(home) { + return QODER_SESSION_DIRECTORIES.some((directory) => existsSync(path.join(home, directory))); +} + export function defaultQoderHome() { + const internationalHome = path.join(os.homedir(), ".qoder"); const cnHome = path.join(os.homedir(), ".qoder-cn"); - if (existsSync(cnHome)) return cnHome; - return path.join(os.homedir(), ".qoder"); + const cnExists = existsSync(cnHome); + if (!cnExists) return internationalHome; + const internationalExists = existsSync(internationalHome); + if (!internationalExists) return cnHome; + const cnHasSessions = hasQoderSessionData(cnHome); + const internationalHasSessions = hasQoderSessionData(internationalHome); + return cnHasSessions && !internationalHasSessions ? cnHome : internationalHome; } export function defaultQoderSharedClientCacheRoot() { @@ -36,7 +53,7 @@ export function defaultQoderSharedClientCacheRoot() { export function resolveQoderAssetHome(options = {}) { const explicit = options.qoderHome ?? options["qoder-home"]; if (explicit) return path.resolve(expandHome(explicit)); - const environmentHome = process.env.QODER_HOME; + const environmentHome = environmentFor(options).QODER_HOME; if (environmentHome && looksLikeQoderAssetHome(environmentHome)) { return path.resolve(expandHome(environmentHome)); } @@ -46,8 +63,10 @@ export function resolveQoderAssetHome(options = {}) { export function resolveQoderSessionHome(options = {}) { const explicit = options.home ?? options.qoderHome ?? options["qoder-home"]; if (explicit) return path.resolve(expandHome(explicit)); - const environmentHome = process.env.QODER_HOME; - if (environmentHome) return path.resolve(expandHome(environmentHome)); + const environmentHome = environmentFor(options).QODER_HOME; + if (environmentHome && looksLikeQoderAssetHome(environmentHome)) { + return path.resolve(expandHome(environmentHome)); + } return defaultQoderHome(); } @@ -57,7 +76,7 @@ export function resolveQoderSharedClientCacheRoot(options = {}) { options["qoder-shared-client-cache-root"] ?? options.sharedClientCacheRoot; if (explicit) return path.resolve(expandHome(explicit)); - const environmentHome = process.env.QODER_HOME; + const environmentHome = environmentFor(options).QODER_HOME; if (environmentHome && !looksLikeQoderAssetHome(environmentHome)) { return path.resolve(expandHome(environmentHome)); } diff --git a/test/cli/harness-doctor.test.mjs b/test/cli/harness-doctor.test.mjs index 78d7b3a4..5d5299d2 100644 --- a/test/cli/harness-doctor.test.mjs +++ b/test/cli/harness-doctor.test.mjs @@ -257,7 +257,7 @@ test("doctor reports every collector-resolved root and uses declared fallbacks o }); assert.equal(failed.targets[0].inventory, "failed"); assert.deepEqual(failed.targets[0].authorizedRoots, [ - "~/.qoder", + "", "/Qoder/SharedClientCache", ]); diff --git a/test/governance/core-change-watch.test.mjs b/test/governance/core-change-watch.test.mjs index 1f211eed..77a071dc 100644 --- a/test/governance/core-change-watch.test.mjs +++ b/test/governance/core-change-watch.test.mjs @@ -287,7 +287,7 @@ test("AGENTS instruction density uses file count instead of line count", async ( } }); -test("project profile treats AGENTS.md and CLAUDE.md as first-class instruction carriers", async () => { +test("project profile counts one instruction scope when AGENTS.md and CLAUDE.md share it", async () => { const repo = await makeRepo({ "package.json": JSON.stringify({ name: "dual-carrier-instructions" }), "AGENTS.md": "# Root agent rules\n", @@ -300,9 +300,10 @@ test("project profile treats AGENTS.md and CLAUDE.md as first-class instruction try { const profile = await analyzeProjectProfile({ cwd: repo }); - assert.equal(profile.agentInstructions.count, 4); - assert.equal(profile.agentInstructions.rootCount, 2); - assert.equal(profile.agentInstructions.nestedCount, 2); + assert.equal(profile.agentInstructions.count, 2); + assert.equal(profile.agentInstructions.rootCount, 1); + assert.equal(profile.agentInstructions.nestedCount, 1); + assert.equal(profile.agentInstructions.files.length, 4); assert.deepEqual( profile.agentInstructions.carriers.map((item) => `${item.name}:${item.files}`), ["AGENTS.md:2", "CLAUDE.md:2"], @@ -357,6 +358,9 @@ test("project-owned validation gates surface in the profile and validate-impact serve: "node server.mjs", test: "node --test", "test:unit": "node --test unit", + "test:watch": "node --test --watch", + "test:ui": "playwright test --ui", + "lint:dev": "node lint-dev.mjs", }, }), "justfile": [ @@ -390,6 +394,7 @@ test("project-owned validation gates surface in the profile and validate-impact "package-script:packages/api/package.json:test", ]); assert.equal(discovered.some((gate) => /:custom$|:serve$|:deploy$/u.test(gate)), false); + assert.equal(discovered.some((gate) => /:test:watch$|:test:ui$|:lint:dev$/u.test(gate)), false); assert.deepEqual( profile.projectGates.find((gate) => gate.sourcePath === "packages/api/package.json")?.command, ["npm", "--prefix", "packages/api", "run", "test"], @@ -565,6 +570,11 @@ test("history windows read independent commit ranges and disclose bounded covera assert.equal(coverage.status, "review"); assert.deepEqual(coverage.evidence.truncatedWindows, [30, 90, 180]); assert.deepEqual(coverage.evidence.coverage.map((item) => item.status), ["truncated", "truncated", "truncated"]); + + const exact = await analyzeGitHistoryProfile({ cwd: repo, maxCommits: 4, historyWindows: "30" }); + assert.equal(exact.historyWindows[0].analyzedCommits, 4); + assert.equal(exact.historyWindows[0].truncated, false); + assert.equal(exact.historyWindows[0].coverage, "complete"); } finally { await rm(repo, { recursive: true, force: true }); } diff --git a/test/plugins/host-support-profiles.test.mjs b/test/plugins/host-support-profiles.test.mjs index 1b0dd0ec..5b7e6d69 100644 --- a/test/plugins/host-support-profiles.test.mjs +++ b/test/plugins/host-support-profiles.test.mjs @@ -47,7 +47,7 @@ test("host-support profiles cover the canonical host set and aliases", () => { }, ]); assert.deepEqual(getHostProfile("qoder").inventoryHomeRoutes, [ - { option: "qoderHome", relativePath: "", fallbackLabel: "~/.qoder" }, + { option: "qoderHome", relativePath: "", fallbackLabel: "" }, { option: "qoderSharedClientCacheRoot", relativePath: "SharedClientCache", diff --git a/test/sessions/session-analysis.test.mjs b/test/sessions/session-analysis.test.mjs index 897c18a8..44d935ed 100644 --- a/test/sessions/session-analysis.test.mjs +++ b/test/sessions/session-analysis.test.mjs @@ -822,6 +822,69 @@ test("Qoder session analysis honors QODER_HOME and prefers a default .qoder-cn h } }); +test("Qoder session analysis ignores a QODER_HOME that points at the shared client cache", async () => { + const fixture = await makeQoderFixture({ homeName: ".qoder" }); + const previous = { + QODER_HOME: process.env.QODER_HOME, + HOME: process.env.HOME, + USERPROFILE: process.env.USERPROFILE, + }; + const restore = () => { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }; + const sharedCache = path.join( + fixture.root, + "Library", + "Application Support", + "Qoder", + "SharedClientCache", + ); + + try { + process.env.QODER_HOME = sharedCache; + process.env.HOME = fixture.root; + process.env.USERPROFILE = fixture.root; + assert.equal(resolveQoderSessionHome({}), path.resolve(fixture.home)); + assert.equal(defaultQoderHome(), path.resolve(fixture.home)); + const result = await new QoderSessionAnalyzer().analyze({ + workspace: fixture.workspace, + command: "sessions", + }); + assert.ok(result.sessions.some((session) => session.sessionId === fixture.sessionId)); + assert.equal(result.scope.home, path.resolve(fixture.home)); + } finally { + restore(); + await rm(fixture.root, { recursive: true, force: true }); + } +}); + +test("Qoder default home keeps the international home when both homes have session data", async () => { + const international = await makeQoderFixture({ homeName: ".qoder" }); + const previousHome = process.env.HOME; + const previousUserProfile = process.env.USERPROFILE; + const previousQoderHome = process.env.QODER_HOME; + const cnHome = path.join(international.root, ".qoder-cn"); + + try { + await mkdir(path.join(cnHome, "projects"), { recursive: true }); + delete process.env.QODER_HOME; + process.env.HOME = international.root; + process.env.USERPROFILE = international.root; + assert.equal(defaultQoderHome(), path.resolve(international.home)); + } finally { + if (previousHome === undefined) delete process.env.HOME; + else process.env.HOME = previousHome; + if (previousUserProfile === undefined) delete process.env.USERPROFILE; + else process.env.USERPROFILE = previousUserProfile; + if (previousQoderHome === undefined) delete process.env.QODER_HOME; + else process.env.QODER_HOME = previousQoderHome; + await rm(international.root, { recursive: true, force: true }); + } +}); + test("Qoder analyzer scans every existing Windows workspace slug variant", async () => { const root = await mkdtemp(path.join(os.tmpdir(), "better-harness-qoder-windows-slug-")); const home = path.join(root, ".qoder"); From 084c725fcd68f595b675fedc01f06dc4e4028848 Mon Sep 17 00:00:00 2001 From: Dzuhaib Date: Mon, 26 Oct 2026 14:39:01 +0500 Subject: [PATCH 3/3] fix(analysis): resolve Qoder provider home consistently Checkup provider-home resolution read QODER_HOME or ~/.qoder directly, so a CN-only install patched a different home from the one the scan inventoried, and a SharedClientCache QODER_HOME could target the cache. Use resolveQoderAssetHome, and cover the apply path. Reword the Claude AGENTS.md comment and narrow Qoder session detection to audit and logs. --- scripts/agent-customize/providers/claude.mjs | 2 +- .../checkup/contract.mjs | 3 +- scripts/host-support/qoder-home.mjs | 2 +- test/agents/harness-checkup.test.mjs | 43 ++++++++++++++++++- test/sessions/session-analysis.test.mjs | 2 +- 5 files changed, 47 insertions(+), 5 deletions(-) diff --git a/scripts/agent-customize/providers/claude.mjs b/scripts/agent-customize/providers/claude.mjs index e23a5e40..47ad05bb 100644 --- a/scripts/agent-customize/providers/claude.mjs +++ b/scripts/agent-customize/providers/claude.mjs @@ -167,7 +167,7 @@ async function collectProjectRules(workspace, sourceLabel, claudeRoot = path.joi "claude-project", ], [path.join(workspace, "CLAUDE.local.md"), "CLAUDE.local.md", "claude-local", "claude-local"], - // Claude Code reads a root AGENTS.md when no CLAUDE.md claims the project. + // Claude Code also reads a root AGENTS.md, so collect it alongside CLAUDE.md. // See https://code.claude.com/docs/en/memory#agents-md. [path.join(workspace, "AGENTS.md"), "AGENTS.md", "agents-md-compat", "agents-md-compat"], ]; diff --git a/scripts/coding-agent-practices/checkup/contract.mjs b/scripts/coding-agent-practices/checkup/contract.mjs index c4b6020a..430b313d 100644 --- a/scripts/coding-agent-practices/checkup/contract.mjs +++ b/scripts/coding-agent-practices/checkup/contract.mjs @@ -10,6 +10,7 @@ import { hostIdsFor, normalizedHostHomeOptions, } from "../../host-support/index.mjs"; +import { resolveQoderAssetHome } from "../../host-support/qoder-home.mjs"; import { expandHome } from "../../session-analysis/index.mjs"; export const CHECKUP_KIND = "harness-customization-checkup"; @@ -184,7 +185,7 @@ export function resolveProviderHome(provider, source = {}) { const env = process.env ?? {}; const userHome = os.homedir(); const defaults = { - qoder: env.QODER_HOME ?? path.join(userHome, ".qoder"), + qoder: resolveQoderAssetHome({ env }), codex: env.CODEX_HOME ?? path.join(userHome, ".codex"), cursor: env.CURSOR_HOME ?? path.join(userHome, ".cursor"), claude: env.CLAUDE_CONFIG_DIR ?? env.CLAUDE_HOME ?? path.join(userHome, ".claude"), diff --git a/scripts/host-support/qoder-home.mjs b/scripts/host-support/qoder-home.mjs index 0873679b..87b892aa 100644 --- a/scripts/host-support/qoder-home.mjs +++ b/scripts/host-support/qoder-home.mjs @@ -3,7 +3,7 @@ import os from "node:os"; import path from "node:path"; const QODER_ASSET_HOME_NAMES = new Set([".qoder", "qoder", ".qoder-cn", "qoder-cn"]); -const QODER_SESSION_DIRECTORIES = ["audit", "logs", "projects", "sessions"]; +const QODER_SESSION_DIRECTORIES = ["audit", "logs"]; // Kept local because session-analysis re-exports the Qoder analyzer that // imports this module, and the refactor contract forbids deep imports. diff --git a/test/agents/harness-checkup.test.mjs b/test/agents/harness-checkup.test.mjs index 8b4ff3b4..20548321 100644 --- a/test/agents/harness-checkup.test.mjs +++ b/test/agents/harness-checkup.test.mjs @@ -15,7 +15,10 @@ import { import { buildCheckupPlan } from "../../scripts/coding-agent-practices/checkup/plan.mjs"; import { computePlanDigest } from "../../scripts/coding-agent-practices/checkup/plan.mjs"; import { formatMarkdown } from "../../scripts/coding-agent-practices/checkup/cli.mjs"; -import { projectCheckupReportEvidence } from "../../scripts/coding-agent-practices/checkup/contract.mjs"; +import { + projectCheckupReportEvidence, + resolveProviderHome, +} from "../../scripts/coding-agent-practices/checkup/contract.mjs"; import { buildCheckupScan } from "../../scripts/coding-agent-practices/checkup/scan.mjs"; import { runCheckupScan } from "../../scripts/coding-agent-practices/checkup/scan.mjs"; import { collectQoderSourceResolution } from "../../scripts/coding-agent-practices/checkup/sources.mjs"; @@ -625,6 +628,44 @@ test("non-qoder plans never emit qodercli and provider-home binds to the explici ); }); +test("provider-home resolution picks the same Qoder home as the scan on a CN install", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "harness-checkup-provider-home-")); + const cnHome = path.join(root, ".qoder-cn"); + const sharedCache = path.join(root, "Qoder", "SharedClientCache"); + const previous = { + QODER_HOME: process.env.QODER_HOME, + HOME: process.env.HOME, + USERPROFILE: process.env.USERPROFILE, + }; + const restore = () => { + for (const [key, value] of Object.entries(previous)) { + if (value === undefined) delete process.env[key]; + else process.env[key] = value; + } + }; + + try { + await mkdir(path.join(cnHome, "audit"), { recursive: true }); + delete process.env.QODER_HOME; + process.env.HOME = root; + process.env.USERPROFILE = root; + assert.equal(resolveProviderHome("qoder", {}), path.resolve(cnHome)); + + process.env.QODER_HOME = sharedCache; + assert.equal(resolveProviderHome("qoder", {}), path.resolve(cnHome)); + assert.equal( + resolveSourceRef( + { base: "provider-home", relativePath: "settings.json" }, + { workspace: root, provider: "qoder" }, + ).filePath, + path.join(cnHome, "settings.json"), + ); + } finally { + restore(); + await rm(root, { recursive: true, force: true }); + } +}); + test("apply rejects qoder-cli mutations when plan.provider is not qoder", async () => { const plan = buildCheckupPlan(buildFixtureScan()); plan.provider = "codex"; diff --git a/test/sessions/session-analysis.test.mjs b/test/sessions/session-analysis.test.mjs index 44d935ed..f2a3f8d0 100644 --- a/test/sessions/session-analysis.test.mjs +++ b/test/sessions/session-analysis.test.mjs @@ -869,7 +869,7 @@ test("Qoder default home keeps the international home when both homes have sessi const cnHome = path.join(international.root, ".qoder-cn"); try { - await mkdir(path.join(cnHome, "projects"), { recursive: true }); + await mkdir(path.join(cnHome, "audit"), { recursive: true }); delete process.env.QODER_HOME; process.env.HOME = international.root; process.env.USERPROFILE = international.root;