@sun-asterisk/sungen 3.3.0-alpha.8 → 3.3.0-alpha.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/cli/commands/contract-derive-command.d.ts +2 -1
  2. package/dist/cli/commands/contract-derive-command.d.ts.map +1 -1
  3. package/dist/cli/commands/contract-derive-command.js +13 -2
  4. package/dist/cli/commands/contract-derive-command.js.map +1 -1
  5. package/dist/contract/build-trace-conformance.d.ts.map +1 -1
  6. package/dist/contract/build-trace-conformance.js +4 -11
  7. package/dist/contract/build-trace-conformance.js.map +1 -1
  8. package/dist/contract/derive-free-feature.d.ts +9 -0
  9. package/dist/contract/derive-free-feature.d.ts.map +1 -1
  10. package/dist/contract/derive-free-feature.js +10 -3
  11. package/dist/contract/derive-free-feature.js.map +1 -1
  12. package/dist/contract/resolve-unit-trace-identities.d.ts +12 -0
  13. package/dist/contract/resolve-unit-trace-identities.d.ts.map +1 -1
  14. package/dist/contract/resolve-unit-trace-identities.js +33 -49
  15. package/dist/contract/resolve-unit-trace-identities.js.map +1 -1
  16. package/dist/contract/trace/collect-trace-evidence.d.ts +9 -3
  17. package/dist/contract/trace/collect-trace-evidence.d.ts.map +1 -1
  18. package/dist/contract/trace/collect-trace-evidence.js +45 -18
  19. package/dist/contract/trace/collect-trace-evidence.js.map +1 -1
  20. package/dist/contract/trace/scenario-id-claims.d.ts +11 -0
  21. package/dist/contract/trace/scenario-id-claims.d.ts.map +1 -0
  22. package/dist/contract/trace/scenario-id-claims.js +89 -0
  23. package/dist/contract/trace/scenario-id-claims.js.map +1 -0
  24. package/dist/contract/trace/select-final-attempt.d.ts +2 -0
  25. package/dist/contract/trace/select-final-attempt.d.ts.map +1 -1
  26. package/dist/contract/trace/select-final-attempt.js +4 -1
  27. package/dist/contract/trace/select-final-attempt.js.map +1 -1
  28. package/dist/contract/trace/trace-binding.d.ts +3 -2
  29. package/dist/contract/trace/trace-binding.d.ts.map +1 -1
  30. package/dist/contract/trace/trace-binding.js +6 -3
  31. package/dist/contract/trace/trace-binding.js.map +1 -1
  32. package/dist/contract/trace/trace-freshness.d.ts +27 -0
  33. package/dist/contract/trace/trace-freshness.d.ts.map +1 -0
  34. package/dist/contract/trace/trace-freshness.js +146 -0
  35. package/dist/contract/trace/trace-freshness.js.map +1 -0
  36. package/dist/contract/trace/trace-identity-resolution.d.ts +2 -0
  37. package/dist/contract/trace/trace-identity-resolution.d.ts.map +1 -1
  38. package/dist/contract/trace/trace-identity-resolution.js +6 -3
  39. package/dist/contract/trace/trace-identity-resolution.js.map +1 -1
  40. package/dist/contract/trace/trace-run-record.d.ts +2 -0
  41. package/dist/contract/trace/trace-run-record.d.ts.map +1 -1
  42. package/dist/contract/trace/trace-run-record.js +19 -5
  43. package/dist/contract/trace/trace-run-record.js.map +1 -1
  44. package/dist/orchestrator/templates/ai-src/commands/create-test.md +4 -1
  45. package/package.json +3 -3
  46. package/src/cli/commands/contract-derive-command.ts +12 -3
  47. package/src/contract/build-trace-conformance.ts +4 -6
  48. package/src/contract/derive-free-feature.ts +15 -3
  49. package/src/contract/resolve-unit-trace-identities.ts +35 -12
  50. package/src/contract/trace/collect-trace-evidence.ts +50 -18
  51. package/src/contract/trace/scenario-id-claims.ts +60 -0
  52. package/src/contract/trace/select-final-attempt.ts +9 -2
  53. package/src/contract/trace/trace-binding.ts +7 -4
  54. package/src/contract/trace/trace-freshness.ts +110 -0
  55. package/src/contract/trace/trace-identity-resolution.ts +7 -4
  56. package/src/contract/trace/trace-run-record.ts +20 -4
  57. package/src/orchestrator/templates/ai-src/commands/create-test.md +4 -1
@@ -0,0 +1,110 @@
1
+ /**
2
+ * Is a trace newer than the contract it is asked to prove? (DOS-14.6: a trace older than the
3
+ * `.feature` or the lock is refused.) Judged by CONTENT, never by file time alone (#967): a `touch`,
4
+ * a checkout or a fresh clone changes no byte, so it stales nothing; an edit after the run always does.
5
+ *
6
+ * schema 2 record the reporter hashed every `.feature` and `contracts.lock.yaml` under `qa/` when
7
+ * the run started. Each of the unit's contract files must hash NOW to what the run
8
+ * saw: one that changed since, or did not exist yet, is newer than the trace → stale
9
+ * schema 1 record an older reporter recorded no content, so the files are dated against the run's
10
+ * start (the record's `startedAt`): one last written before it is older than the run;
11
+ * one written after it still is when git holds it unchanged and the commit that last
12
+ * changed it is an ancestor of HEAD committed before the run started (its bytes ARE
13
+ * that commit's). Anything else — edited, uncommitted, untracked, committed after the
14
+ * run started, no git, git failed or slow — is stale: fail closed.
15
+ *
16
+ * Limit of the schema-1 path: a commit time is what the committer's clock (or GIT_COMMITTER_DATE) said,
17
+ * so a backdated commit passes the time check — time-based checks cannot see through that. Schema 2
18
+ * compares content and retires this path: re-running the free tests once with the current reporter is
19
+ * the remedy.
20
+ */
21
+ import { execFileSync } from 'child_process';
22
+ import { createHash } from 'crypto';
23
+ import * as fs from 'fs';
24
+ import * as path from 'path';
25
+ import { lockPathFor } from '../contracts-lock-file';
26
+ import { contractFeatureFiles } from '../normalize-feature-steps';
27
+ import type { RunRecord } from './trace-run-record';
28
+
29
+ interface ContractFile { rel: string; sha: string; mtimeMs: number }
30
+ interface LastCommit { sha: string; ms: number }
31
+ /** A unit's contract as it is NOW — its `.feature` files and lock, read once per verdict. */
32
+ export interface UnitContract {
33
+ projectRoot: string;
34
+ files: ContractFile[];
35
+ /** Schema 1 only, asked of git at most once: project path → the last commit that changed each file git holds unchanged. */
36
+ committed?: Map<string, LastCommit> | null;
37
+ /** Schema 1 only: commit → is it an ancestor of HEAD (asked once per commit). */
38
+ ancestors?: Map<string, boolean>;
39
+ }
40
+
41
+ /** Inside the Claude Code guard too: a slow git leaves a schema-1 trace stale rather than the hook waiting. */
42
+ const GIT_TIMEOUT_MS = 2_000;
43
+ const posix = (p: string): string => p.split(path.sep).join('/');
44
+
45
+ export function unitContract(projectRoot: string, unit: { name: string; dir: string }): UnitContract {
46
+ const root = path.resolve(projectRoot);
47
+ const lock = path.resolve(lockPathFor(unit.dir));
48
+ const files = [...(fs.existsSync(lock) ? [lock] : []), ...contractFeatureFiles(unit.dir, unit.name)].map((abs) => {
49
+ let sha = 'unreadable'; // never equal to a recorded sha256: an unreadable contract file is stale
50
+ let mtimeMs = Number.POSITIVE_INFINITY;
51
+ try { sha = createHash('sha256').update(fs.readFileSync(abs)).digest('hex'); mtimeMs = fs.statSync(abs).mtimeMs; } catch { /* stale */ }
52
+ return { rel: posix(path.relative(root, abs)), sha, mtimeMs };
53
+ });
54
+ return { projectRoot: root, files };
55
+ }
56
+
57
+ function git(cwd: string, args: string[]): string | null {
58
+ try { return execFileSync('git', args, { cwd, stdio: ['ignore', 'pipe', 'ignore'], timeout: GIT_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 }).toString('utf8'); } catch { return null; }
59
+ }
60
+
61
+ /**
62
+ * Each contract file git holds unchanged → the last commit (first-parent history, merges included)
63
+ * that changed it, with its committer time. Two git calls for the whole unit; null when git cannot say.
64
+ * Paths are passed as literal pathspecs: no glob or `:(magic)` reading of a unit's file names.
65
+ */
66
+ function committedTimes(c: UnitContract): Map<string, LastCommit> | null {
67
+ if (c.committed !== undefined) return c.committed;
68
+ const rels = c.files.map((f) => f.rel);
69
+ const changed = git(c.projectRoot, ['--literal-pathspecs', 'diff', '--name-only', '--relative', '-z', 'HEAD', '--', ...rels]);
70
+ const log = git(c.projectRoot, ['-c', 'core.quotePath=false', '--literal-pathspecs', 'log', '--first-parent', '-m', '-n', '500', '--format=%x01%H %ct', '--name-only', '--relative', '--', ...rels]);
71
+ if (changed === null || log === null) return (c.committed = null);
72
+ const dirty = new Set(changed.split('\0').filter(Boolean));
73
+ const times = new Map<string, LastCommit>();
74
+ let at: LastCommit | null = null;
75
+ for (const raw of log.split('\n')) {
76
+ const line = raw.trim();
77
+ if (raw.startsWith('\x01')) {
78
+ const [sha, ct] = raw.slice(1).trim().split(' ');
79
+ at = /^[0-9a-f]{40,64}$/.test(sha ?? '') && Number(ct) > 0 ? { sha, ms: Number(ct) * 1000 } : null;
80
+ } else if (line && at && !times.has(line) && !dirty.has(line)) times.set(line, at);
81
+ }
82
+ return (c.committed = times);
83
+ }
84
+
85
+ /** Is `sha` an ancestor of HEAD? First-parent history says so already; asserted, never assumed. */
86
+ function isAncestorOfHead(c: UnitContract, sha: string): boolean {
87
+ if (!c.ancestors) c.ancestors = new Map();
88
+ if (!c.ancestors.has(sha)) c.ancestors.set(sha, git(c.projectRoot, ['merge-base', '--is-ancestor', sha, 'HEAD']) !== null);
89
+ return c.ancestors.get(sha)!;
90
+ }
91
+
92
+ /** Why a trace bound to `record` is older than the unit's contract — null when it is not. */
93
+ export function staleReason(c: UnitContract, record: RunRecord): string | null {
94
+ if (record.contract) {
95
+ const f = c.files.find((x) => record.contract![x.rel] !== x.sha);
96
+ if (!f) return null;
97
+ const why = record.contract[f.rel] === undefined ? 'it did not exist when the run started' : 'its content changed after the run';
98
+ return `the trace is older than ${f.rel}: ${why} (stale) — re-run the test`;
99
+ }
100
+ const runStart = Date.parse(record.startedAt); // unreadable → nothing is "before the run": stale
101
+ const late = c.files.filter((f) => !(f.mtimeMs <= runStart));
102
+ if (!late.length) return null;
103
+ const committed = committedTimes(c);
104
+ const vouched = (rel: string): boolean => {
105
+ const last = committed?.get(rel);
106
+ return !!last && last.ms <= runStart && isAncestorOfHead(c, last.sha);
107
+ };
108
+ const f = late.find((x) => !vouched(x.rel));
109
+ return f ? `the trace is older than ${f.rel}: it was written after the run, and no commit from before the run holds its bytes (stale) — re-run the test` : null;
110
+ }
@@ -51,13 +51,16 @@ export function identityRequestsFor(trace: ParsedTrace): TraceIdentityRequest[]
51
51
  }
52
52
 
53
53
  /** Ask the driver about every not-yet-cached target of these traces; rewrite the cache. */
54
- export async function resolveWithDriver(projectRoot: string, traces: ParsedTrace[], resolver: TraceIdentityResolver): Promise<{ asked: number; resolver: string; blockedRequests: number }> {
54
+ /** `keys`: every target of the given traces (cached or asked) — what the caller reports on. */
55
+ export async function resolveWithDriver(projectRoot: string, traces: ParsedTrace[], resolver: TraceIdentityResolver): Promise<{ asked: number; resolver: string; blockedRequests: number; keys: string[] }> {
55
56
  const { cache } = readIdentityCache(projectRoot);
56
57
  // The cache is project-wide (every unit's traces): answers are only ever ADDED, never pruned here.
57
58
  const keep = new Map<string, CachedIdentity>(cache.entries);
59
+ const all = traces.flatMap(identityRequestsFor);
60
+ const keys = [...new Set(all.map((req) => req.key))];
58
61
  const requests = new Map<string, TraceIdentityRequest>();
59
- for (const req of traces.flatMap(identityRequestsFor)) if (!keep.has(req.key)) requests.set(req.key, req);
60
- if (!requests.size) return { asked: 0, resolver: cache.resolver, blockedRequests: 0 };
62
+ for (const req of all) if (!keep.has(req.key)) requests.set(req.key, req);
63
+ if (!requests.size) return { asked: 0, resolver: cache.resolver, blockedRequests: 0, keys };
61
64
  const answer = await resolver({ requests: [...requests.values()] });
62
65
  if (!answer || !Array.isArray(answer.results)) throw new Error('the trace identity resolver returned no results');
63
66
  if (!TRUSTED_RESOLVER.test(String(answer.resolver)) || typeof answer.browser !== 'string' || !answer.browser) {
@@ -70,5 +73,5 @@ export async function resolveWithDriver(projectRoot: string, traces: ParsedTrace
70
73
  keep.set(key, { ...rest, browser: answer.browser.slice(0, 100) });
71
74
  }
72
75
  writeIdentityCache(projectRoot, answer.resolver, keep);
73
- return { asked: requests.size, resolver: String(answer.resolver), blockedRequests: Number(answer.blockedRequests) || 0 };
76
+ return { asked: requests.size, resolver: String(answer.resolver), blockedRequests: Number(answer.blockedRequests) || 0, keys };
74
77
  }
@@ -8,6 +8,10 @@
8
8
  * own outputDir (#941) — or `<project>/test-results/sungen-run-record*.json` (one per run or shard).
9
9
  * Playwright wipes its outputDir at the start of every run, so a record and its traces share a
10
10
  * lifetime; the free run has its own so the compiled suite's next run cannot delete its traces.
11
+ *
12
+ * Schema 2 (#967) adds `contract`: the sha256 of every `.feature` and `contracts.lock.yaml` under `qa/`
13
+ * when the run started — what trace freshness compares by content. Schema 1 (an older reporter) has
14
+ * none; its traces are dated instead (trace-freshness.ts).
11
15
  */
12
16
  import * as fs from 'fs';
13
17
  import * as path from 'path';
@@ -24,10 +28,13 @@ export interface RunRecord {
24
28
  shard: string | null;
25
29
  report: string | null;
26
30
  specs: Record<string, string>;
31
+ /** Schema 2: project path → sha256 of each contract file at run start. null: schema 1 (no content recorded). */
32
+ contract: Record<string, string> | null;
27
33
  attempts: RunRecordAttempt[];
28
34
  }
29
35
 
30
- const TOP = new Set(['schema', 'tool', 'runId', 'startedAt', 'playwrightVersion', 'shard', 'report', 'specs', 'attempts']);
36
+ const TOP_V1: ReadonlySet<string> = new Set(['schema', 'tool', 'runId', 'startedAt', 'playwrightVersion', 'shard', 'report', 'specs', 'attempts']);
37
+ const TOP_V2: ReadonlySet<string> = new Set([...TOP_V1, 'contract']);
31
38
  const ATTEMPT = new Set(['testId', 'file', 'title', 'retry', 'status', 'startTime', 'duration', 'trace']);
32
39
  const SHA = /^[0-9a-f]{64}$/;
33
40
  const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === 'object' && !Array.isArray(v);
@@ -65,16 +72,25 @@ export function readRunRecord(file: string, text?: string): RunRecord {
65
72
  let raw: unknown;
66
73
  try { raw = JSON.parse(text ?? fs.readFileSync(file, 'utf8')); } catch (e) { throw new Error(`not readable JSON (${(e as Error).message.split('\n')[0]})`); }
67
74
  if (!isObj(raw)) throw new Error('not an object');
68
- const extra = Object.keys(raw).find((k) => !TOP.has(k));
75
+ if (raw.tool === 'sungen-trace-run-record' && typeof raw.schema === 'number' && raw.schema > 2) {
76
+ // A newer driver-ui wrote it (mixed versions): say what to upgrade, not just "not a record".
77
+ throw new Error(`record schema ${raw.schema} is newer than this sungen — upgrade @sun-asterisk/sungen (core before or together with driver-ui)`);
78
+ }
79
+ const keys = raw.schema === 2 ? TOP_V2 : raw.schema === 1 ? TOP_V1 : null;
80
+ if (!keys || raw.tool !== 'sungen-trace-run-record') throw new Error('not a sungen run record (schema 1 or 2)');
81
+ const extra = Object.keys(raw).find((k) => !keys.has(k));
69
82
  if (extra) throw new Error(`unknown key "${extra}"`);
70
- if (raw.schema !== 1 || raw.tool !== 'sungen-trace-run-record') throw new Error('not a sungen run record (schema 1)');
71
83
  if (typeof raw.runId !== 'string' || !raw.runId || typeof raw.startedAt !== 'string' || typeof raw.playwrightVersion !== 'string') throw new Error('runId, startedAt and playwrightVersion must be strings');
72
84
  if (raw.shard !== null && typeof raw.shard !== 'string') throw new Error('shard must be a string or null');
73
85
  if (raw.report !== null && typeof raw.report !== 'string') throw new Error('report must be a string or null');
74
86
  if (!isObj(raw.specs) || !Object.values(raw.specs).every((v) => typeof v === 'string' && (v === '' || SHA.test(v)))) throw new Error('specs must map files to sha256');
87
+ if (raw.schema === 2 && !(isObj(raw.contract) && Object.values(raw.contract).every((v) => typeof v === 'string' && SHA.test(v)))) {
88
+ throw new Error('contract must map contract files to sha256 (schema 2)');
89
+ }
75
90
  if (!Array.isArray(raw.attempts)) throw new Error('attempts must be a list');
76
91
  return {
77
92
  file, runId: raw.runId, startedAt: raw.startedAt, playwrightVersion: raw.playwrightVersion, shard: raw.shard as string | null,
78
- report: raw.report as string | null, specs: raw.specs as Record<string, string>, attempts: raw.attempts.map(attemptOf),
93
+ report: raw.report as string | null, specs: raw.specs as Record<string, string>,
94
+ contract: raw.schema === 2 ? raw.contract as Record<string, string> : null, attempts: raw.attempts.map(attemptOf),
79
95
  };
80
96
  }
@@ -111,7 +111,10 @@ terminal (`script`, `expect`, a pty wrapper), and never edit `contracts.lock.yam
111
111
  traces, write their Gherkin with `sungen contract derive --screen <name>` — deterministic, it writes
112
112
  `features/<name>.free.feature` with every scenario tagged `@free @proposed`. Do not author those
113
113
  steps yourself; you may name the scenarios and suggest VP-ids. A `@proposed` scenario is not
114
- counted by the audit until a QA approves it (`sungen contract approve --screen <name>`).
114
+ counted by the audit until a QA approves it (`sungen contract approve --screen <name>`). When
115
+ two recorded tests claim one ID, `sungen contract derive` exits `1`, names both tests and writes
116
+ nothing: stop and ask the QA to give each test its own ID (its title's leading ID, or its `@tag`).
117
+ Never rename a test's ID — or a scenario's — yourself to get past it.
115
118
 
116
119
  ## Platform detection (do this FIRST)
117
120