qfai 2.1.2 → 2.2.1

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 (162) hide show
  1. package/README.md +46 -6
  2. package/assets/defaults/agent-routing/qfai-implement.yml +9 -0
  3. package/assets/defaults/agent-routing/qfai-triage.yml +9 -0
  4. package/assets/defaults/workflows/answer-in-session.yml +8 -0
  5. package/assets/defaults/workflows/bump-dependency.yml +4 -1
  6. package/assets/defaults/workflows/decide-design.yml +5 -1
  7. package/assets/defaults/workflows/quarantine-flaky.yml +3 -0
  8. package/assets/defaults/workflows/rename-concept.yml +30 -0
  9. package/assets/defaults/workflows/repair-consistency.yml +1 -0
  10. package/assets/defaults/workflows/resolve-conflicts.yml +14 -0
  11. package/assets/defaults/workflows/retire-feature.yml +26 -0
  12. package/assets/defaults/workflows/run-operation.yml +11 -0
  13. package/assets/defaults/workflows/run-release.yml +12 -0
  14. package/assets/defaults/workflows/write-procedure.yml +18 -0
  15. package/assets/graph/codegraph-native.mjs +174 -0
  16. package/assets/graph/graphify-native.py +72 -0
  17. package/assets/init/.claude/settings.json +11 -29
  18. package/assets/init/.codex/hooks.json +9 -21
  19. package/assets/init/.qfai/assistant/agent/backend-engineer.md +1 -1
  20. package/assets/init/.qfai/assistant/agent/frontend-engineer.md +1 -1
  21. package/assets/init/.qfai/assistant/agent/implementation-reviewer.md +5 -0
  22. package/assets/init/.qfai/assistant/agent/product-surface-reviewer.md +8 -3
  23. package/assets/init/.qfai/assistant/rule/constitution.md +36 -18
  24. package/assets/init/.qfai/assistant/rule/drift-protocol.md +80 -1
  25. package/assets/init/.qfai/assistant/rule/references/codex-delegation.md +27 -0
  26. package/assets/init/.qfai/assistant/rule/references/gate-failure-autorepair.md +1 -1
  27. package/assets/init/.qfai/assistant/rule/references/griller-recommendations.md +21 -9
  28. package/assets/init/.qfai/assistant/rule/review-convergence.md +34 -15
  29. package/assets/init/.qfai/assistant/rule/shared-skill-delegation-baseline.md +12 -2
  30. package/assets/init/.qfai/assistant/rule/shared-skill-operating-baseline.md +14 -7
  31. package/assets/init/.qfai/assistant/rule/ui-definition-protocol.md +2 -1
  32. package/assets/init/.qfai/assistant/rule/workflow.md +2 -1
  33. package/assets/init/.qfai/assistant/skill/qfai-discussion/SKILL.md +11 -2
  34. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/discussion-completion-matrix.md +32 -10
  35. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui-bearing-playbook.md +17 -0
  36. package/assets/init/.qfai/assistant/skill/qfai-discussion/references/ui_ux/trend_scan_playbook.md +3 -1
  37. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/01_Context.md +4 -1
  38. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/04_Sources.md +5 -1
  39. package/assets/init/.qfai/assistant/skill/qfai-discussion/templates/uiux/00_index.md +4 -1
  40. package/assets/init/.qfai/assistant/skill/qfai-grilling/SKILL.md +30 -20
  41. package/assets/init/.qfai/assistant/skill/qfai-grilling/references/delegated-session.md +4 -3
  42. package/assets/init/.qfai/assistant/skill/qfai-grilling/references/session-record.md +8 -2
  43. package/assets/init/.qfai/assistant/skill/qfai-implement/SKILL.md +9 -2
  44. package/assets/init/.qfai/assistant/skill/qfai-implement/references/parallelization-policy.md +10 -0
  45. package/assets/init/.qfai/assistant/skill/qfai-implement/references/red-admissibility.md +35 -0
  46. package/assets/init/.qfai/assistant/skill/qfai-implement/references/test-runner-recipes.md +445 -0
  47. package/assets/init/.qfai/assistant/skill/qfai-implement/references/ui-affecting.md +3 -3
  48. package/assets/init/.qfai/assistant/skill/qfai-prototyping/SKILL.md +10 -9
  49. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/generator-prompt.md +33 -2
  50. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/handoff.md +77 -2
  51. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/iteration-loop.md +12 -3
  52. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/review-payload-schema.md +3 -1
  53. package/assets/init/.qfai/assistant/skill/qfai-prototyping/references/reviewer-prompt.md +31 -5
  54. package/assets/init/.qfai/assistant/skill/qfai-run/SKILL.md +48 -46
  55. package/assets/init/.qfai/assistant/skill/qfai-run/references/codex-cloud-install.md +80 -0
  56. package/assets/init/.qfai/assistant/skill/qfai-run/references/extraction.md +202 -126
  57. package/assets/init/.qfai/assistant/skill/qfai-run/references/operator-screens.md +38 -15
  58. package/assets/init/.qfai/assistant/skill/qfai-run/references/plan.md +48 -22
  59. package/assets/init/.qfai/assistant/skill/qfai-run/references/reached-step-observations.md +134 -0
  60. package/assets/init/.qfai/assistant/skill/qfai-run/references/stage-points.md +7 -4
  61. package/assets/init/.qfai/assistant/skill/qfai-run/scripts/codex-cloud-install.mjs +117 -0
  62. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/concrete-abstract-cycle.md +2 -1
  63. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/contract-artifact-rules.md +1 -1
  64. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/design-md-authoring.md +20 -7
  65. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-execution-playbook.md +2 -2
  66. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-phase-checklists.md +2 -2
  67. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-pre-draft-grilling.md +5 -1
  68. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-quality-gate.md +2 -2
  69. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/sdd-triage.md +111 -7
  70. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/spec-traceability-rules.md +1 -1
  71. package/assets/init/.qfai/assistant/skill/qfai-sdd/references/ui-contract-guide.md +58 -8
  72. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/change-request.md +1 -1
  73. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/decisions/page-NNNN.md +6 -0
  74. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/decisions.md +18 -0
  75. package/assets/init/.qfai/assistant/skill/qfai-sdd/templates/spec/open-questions.md +13 -0
  76. package/assets/init/.qfai/assistant/skill/qfai-triage/SKILL.md +10 -7
  77. package/assets/init/.qfai/assistant/skill/qfai-verify/references/verify-output-contract.md +22 -16
  78. package/assets/init/.qfai/assistant/skill/web-research/SKILL.md +1 -1
  79. package/assets/init/.qfai/assistant/step/common-design-md/STEP.md +33 -16
  80. package/assets/init/.qfai/assistant/step/common-gate-run/STEP.md +37 -8
  81. package/assets/init/.qfai/assistant/step/common-grilling-record/STEP.md +25 -4
  82. package/assets/init/.qfai/assistant/step/common-policy-check/STEP.md +1 -0
  83. package/assets/init/.qfai/assistant/step/common-review-cycle/STEP.md +68 -15
  84. package/assets/init/.qfai/assistant/step/discussion-interview/STEP.md +25 -10
  85. package/assets/init/.qfai/assistant/step/discussion-oq/STEP.md +17 -1
  86. package/assets/init/.qfai/assistant/step/discussion-pack/STEP.md +23 -3
  87. package/assets/init/.qfai/assistant/step/discussion-uiux/STEP.md +9 -1
  88. package/assets/init/.qfai/assistant/step/implement-acceptance/STEP.md +3 -0
  89. package/assets/init/.qfai/assistant/step/implement-credentials/STEP.md +4 -0
  90. package/assets/init/.qfai/assistant/step/implement-dep-bump/STEP.md +33 -3
  91. package/assets/init/.qfai/assistant/step/implement-diagnose/STEP.md +12 -3
  92. package/assets/init/.qfai/assistant/step/implement-procedure/STEP.md +98 -0
  93. package/assets/init/.qfai/assistant/step/implement-quarantine/STEP.md +21 -4
  94. package/assets/init/.qfai/assistant/step/implement-refactor/STEP.md +25 -5
  95. package/assets/init/.qfai/assistant/step/implement-regression-fix/STEP.md +3 -3
  96. package/assets/init/.qfai/assistant/step/implement-retire/STEP.md +26 -0
  97. package/assets/init/.qfai/assistant/step/implement-scaffold/STEP.md +28 -5
  98. package/assets/init/.qfai/assistant/step/implement-stress-harness/STEP.md +33 -2
  99. package/assets/init/.qfai/assistant/step/implement-tdd/STEP.md +20 -5
  100. package/assets/init/.qfai/assistant/step/maintain-edit/STEP.md +70 -6
  101. package/assets/init/.qfai/assistant/step/prototyping-grill/STEP.md +39 -6
  102. package/assets/init/.qfai/assistant/step/prototyping-handoff/STEP.md +12 -3
  103. package/assets/init/.qfai/assistant/step/prototyping-loop/STEP.md +56 -6
  104. package/assets/init/.qfai/assistant/step/prototyping-preflight/STEP.md +13 -0
  105. package/assets/init/.qfai/assistant/step/sdd-contract/STEP.md +8 -0
  106. package/assets/init/.qfai/assistant/step/sdd-cycle/STEP.md +9 -4
  107. package/assets/init/.qfai/assistant/step/sdd-story/STEP.md +22 -1
  108. package/assets/init/.qfai/assistant/step/sdd-triage/STEP.md +52 -14
  109. package/assets/init/.qfai/assistant/step/triage-answer/STEP.md +2 -2
  110. package/assets/init/.qfai/assistant/step/triage-close/STEP.md +7 -2
  111. package/assets/init/.qfai/assistant/step/triage-handoff/STEP.md +6 -0
  112. package/assets/init/.qfai/assistant/step/triage-operate/STEP.md +123 -0
  113. package/assets/init/.qfai/assistant/step/verify-commit/STEP.md +35 -10
  114. package/assets/init/.qfai/assistant/step/verify-qfai-gate/STEP.md +8 -1
  115. package/assets/init/.qfai/assistant/step/verify-repeat-run/STEP.md +40 -0
  116. package/assets/init/.qfai/assistant/step/verify-repo-gate/STEP.md +77 -7
  117. package/assets/init/root/.agents/rules/api-budget.md +8 -3
  118. package/assets/init/root/.agents/rules/document-schema.md +17 -0
  119. package/assets/init/root/.agents/rules/documentation-clarity.md +1 -1
  120. package/assets/init/root/.agents/rules/graph-exploration.md +164 -0
  121. package/assets/init/root/.agents/rules/grilling.md +100 -43
  122. package/assets/init/root/.agents/rules/reminders.json +20 -32
  123. package/assets/init/root/.agents/rules/session-feedback.md +6 -11
  124. package/assets/init/root/.agents/rules/untrusted-content.md +2 -2
  125. package/assets/init/root/.agents/rules/user-questions.md +24 -14
  126. package/assets/init/root/.gitattributes +2 -0
  127. package/assets/init/root/.github/workflows/qfai-docs.yml +2 -2
  128. package/assets/init/root/.github/workflows/qfai-tests.yml +88 -35
  129. package/assets/init/root/.github/workflows/qfai-validate.yml +2 -2
  130. package/assets/init/root/AGENTS.md +1 -0
  131. package/assets/mdschema/manifest.yml +3 -0
  132. package/assets/mdschema/story/03_contract/tech.mdschema.yml +1 -1
  133. package/assets/mdschema/story/decisions/page-NNNN.mdschema.yml +32 -0
  134. package/assets/mdschema/story/decisions.mdschema.yml +12 -0
  135. package/assets/schemas/workflow/extraction.schema.json +98 -2
  136. package/assets/schemas/workflow/plan.schema.json +34 -1
  137. package/assets/scripts/check-mdschema.mjs +497 -39
  138. package/dist/cli/index.cjs +7667 -3515
  139. package/dist/cli/index.cjs.map +1 -1
  140. package/dist/cli/index.mjs +8872 -4702
  141. package/dist/cli/index.mjs.map +1 -1
  142. package/dist/graph/cli.cjs +1568 -0
  143. package/dist/graph/cli.cjs.map +1 -0
  144. package/dist/graph/cli.d.cts +9 -0
  145. package/dist/graph/cli.d.ts +9 -0
  146. package/dist/graph/cli.mjs +1541 -0
  147. package/dist/graph/cli.mjs.map +1 -0
  148. package/dist/graph/hook.cjs +817 -0
  149. package/dist/graph/hook.cjs.map +1 -0
  150. package/dist/graph/hook.d.cts +9 -0
  151. package/dist/graph/hook.d.ts +9 -0
  152. package/dist/graph/hook.mjs +792 -0
  153. package/dist/graph/hook.mjs.map +1 -0
  154. package/dist/index.cjs +6436 -3012
  155. package/dist/index.cjs.map +1 -1
  156. package/dist/index.d.cts +185 -1
  157. package/dist/index.d.ts +185 -1
  158. package/dist/index.mjs +6620 -3197
  159. package/dist/index.mjs.map +1 -1
  160. package/dist/process-C21nTvkT.d.cts +12 -0
  161. package/dist/process-C21nTvkT.d.ts +12 -0
  162. package/package.json +1 -1
@@ -18,7 +18,9 @@ Use the shared schema from
18
18
  The invoking stage's reviewer confirms this about the session:
19
19
 
20
20
  - no decision was recorded as the user's that the user did not answer, no
21
- critical decision was adopted without them, and none was assumed that the
21
+ critical decision was adopted without an actual user answer or an explicit
22
+ applicable human authorization under the master's delegation conditions,
23
+ and none was assumed that the
22
24
  assumption path excludes;
23
25
  - every adopted decision has its `agents` row, and none of them adds what the
24
26
  request did not need;
@@ -27,7 +29,11 @@ The invoking stage's reviewer confirms this about the session:
27
29
  five endings `.agents/rules/grilling.md` names. Between agents a round budget
28
30
  bounds the rounds (`.qfai/assistant/rule/review-convergence.md`), and
29
31
  a session recorded as ended while a critical decision it escalated is still
30
- unanswered is the finding.
32
+ unanswered and lacks that recorded authority is the finding;
33
+ - for an explicitly delegated discussion, the actual user instruction, its
34
+ scope and authority, actual author rounds and dissent, no open node or
35
+ running lookup, all required consumed inputs, and actual end/authoring times
36
+ are evidenced. `adopted` without these is not a passing session.
31
37
 
32
38
  The reviewer works under these rules:
33
39
 
@@ -40,6 +40,7 @@ steps:
40
40
  - implement-tooling
41
41
  - implement-backport
42
42
  - implement-acceptance
43
+ - implement-procedure
43
44
  requires: [common-review-cycle]
44
45
  mode: approval-gated
45
46
  ---
@@ -119,8 +120,8 @@ Read the `STEP.md` of the current step only, run it, then move to the next.
119
120
  Each step names the common steps it runs in `requires`; read those when the
120
121
  step reaches them.
121
122
 
122
- Inside an `npx qfai workflow` run, the work order lists the steps to run and
123
- this file adds nothing to it.
123
+ Inside an `npx qfai workflow` run, the plan's stage lists the steps to run, and
124
+ its work order names the flow; this file adds nothing.
124
125
 
125
126
  ### Reviewer Gate
126
127
 
@@ -136,6 +137,12 @@ and reporting requirement, and states any assumption it built on
136
137
  (`.qfai/assistant/rule/test-layers.md#test-suite-sizing`,
137
138
  `.agents/rules/minimal-implementation.md` § 4).
138
139
 
140
+ ## Route-only procedure authoring
141
+
142
+ When the plan names `implement-procedure`, follow
143
+ `.qfai/assistant/step/implement-procedure/STEP.md`.
144
+ Business-flow invocations skip it; existing flow steps apply.
145
+
139
146
  ## Completion
140
147
 
141
148
  The invocation completes on the gate of its last step once
@@ -4,6 +4,16 @@
4
4
 
5
5
  Process one open EX at a time in ascending ID order within the selected BF flow. Parallel item work requires explicit user approval and a delivery-planner PASS on concrete independence. Parallel role review of one item does not require parallel item authorization.
6
6
 
7
+ ## Work orders per flow
8
+
9
+ When the extraction declares several flows, the plan gives each implement stage
10
+ one work order per flow, its `target` naming that flow, in ascending flow ID
11
+ order. Run them one at a time in that order. Each runs every step of the stage
12
+ for its own flow and completes on that flow's gates. The stage's review runs
13
+ once, after its last work order. Two work orders run in
14
+ parallel only with explicit user approval and a delivery-planner PASS on the
15
+ independence gate below, compared across both flows.
16
+
7
17
  ## Independence gate
8
18
 
9
19
  For each candidate item, name its production files, test files, contracts, fixtures, schema or database objects, and shared resources such as ports. Disjoint filenames alone are insufficient: compare read and write sets, imports, shared fixtures, persistence, generated assets, and external process state. If any dependency is uncertain, use serial execution.
@@ -52,6 +52,41 @@ The normal verify run establishes full collection coverage; no extra full suite
52
52
  required for each focused cycle. This receipt adds no ledger, JSON field,
53
53
  gate status, runtime parser or runner.
54
54
 
55
+ ## CI-only Test gate
56
+
57
+ Where the Standard commands entry for the Test gate is written
58
+ `CI only: <check name>`, the project runs its tests in CI alone, and no focused
59
+ Red, Green or Refactor invocation runs locally. The same holds when the user's
60
+ instruction for this run delegates that gate to a named CI check: that
61
+ delegation holds for this run only. Record those phases `ci-deferred` instead:
62
+
63
+ - Write the test before any production code, as for an observed Red, and do
64
+ not run it.
65
+ - In the example's `### EX-NNNN-NNNN-NN` section, the stage report says
66
+ `red: ci-deferred`, `green: ci-deferred` and `refactor: ci-deferred`, with
67
+ the test path, its selector and the check name.
68
+ This is a report label, not a gate status: no gate counts it, and it is not
69
+ a pass. The Test gate stays DELEGATED to that check in the verify stage.
70
+ - For a delegation by instruction, the stage report quotes the instruction word
71
+ for word and says where it came from: this request, an answer to a question,
72
+ or the project's agent instructions. A standing instruction in the project's
73
+ agent instructions counts for each run it is in force. A delegation requires
74
+ an actual CI check that runs this test; local environment failure alone
75
+ creates no delegation. Without an instruction that can be quoted, nothing is
76
+ deferred and the focused phases run locally; the agent never defers them on
77
+ its own judgment.
78
+ - The route's code review reads the test against the code before the fix and
79
+ confirms that its assertion fails there on the stated behavior. A test that
80
+ would pass both before and after the fix is a finding.
81
+
82
+ Where the run has authority to push and open a pull request, from the user's
83
+ instruction or the project's policy, it may observe Red in CI instead: push a
84
+ commit that holds only the test, for example on a draft pull request, confirm
85
+ that the named check fails on the new test's assertion, and record the run URL
86
+ as the Red. A run without that authority does not push to observe Red. Under a
87
+ delegation by instruction, that test-only commit is the expected way to observe
88
+ Red whenever the run has that authority.
89
+
55
90
  ## Assertion control
56
91
 
57
92
  Temporarily neutralize only the example assertion while keeping the test compilable and runnable. The same command must pass. Capture the changed lines and result, then restore the assertion before recording RED. This control shows that the reported failure came from the assertion.
@@ -0,0 +1,445 @@
1
+ # Test runner recipes: session reuse, shared state, business time and CI
2
+
3
+ Optional recipes for Playwright and Vitest that put the worker session-reuse rules of
4
+ `implement-credentials` into runnable form, together with the shared-state, business-time and CI
5
+ patterns that make a parallel acceptance suite trustworthy. Copy what fits and adapt it. The rules
6
+ stay the obligation; a recipe is one way to meet them.
7
+
8
+ ## Contents
9
+
10
+ - Status and what the adopter supplies
11
+ - The run-owned session directory
12
+ - Vitest: one session per pool slot and actor
13
+ - Playwright: one account and storage state per worker
14
+ - Business data each file owns
15
+ - Database hooks only where a group needs them
16
+ - Shared and exclusive access to a common database or server
17
+ - Deterministic business time
18
+ - Credential directory hygiene
19
+ - CI: auxiliary jobs inside the protected result
20
+ - Adoption checklist
21
+
22
+ ## Status and what the adopter supplies
23
+
24
+ The Vitest session cache and the CI aggregate job come from one adopter's working implementation,
25
+ reduced to the parts that do not depend on the application. The Playwright recipe and the other
26
+ sections were written from that adopter's description of its suite. QFAI's own suite signs
27
+ nothing in and runs no browser, so nothing here is executed in this repository: read each recipe as a
28
+ pattern to adopt, then prove it in your own suite with the adoption checklist at the end.
29
+
30
+ The application supplies five adapters. QFAI ships none of them, and no recipe below assumes how
31
+ they work inside:
32
+
33
+ | Adapter | What it does |
34
+ | ---------------- | ------------------------------------------------------------------------------------- |
35
+ | `createAccount` | `createAccount(actor, slot)` creates a private account for this run, returning its ID |
36
+ | `issueSession` | Signs that account in and returns the session the product accepts |
37
+ | `signIn` | Completes the same sign-in on a browser page, for Playwright |
38
+ | `acceptsSession` | Asks the product whether a restored session is still valid |
39
+ | `deleteAccount` | Removes an account this run created, and nothing else |
40
+
41
+ When a test needs a controlled business time, the application also supplies a clock adapter, as
42
+ the business time section describes.
43
+
44
+ ## The run-owned session directory
45
+
46
+ Both runners share these helpers. The run's global setup creates one private directory and exports
47
+ it as `TEST_SESSION_CACHE_DIR`; every worker reads that same directory. Each account the run
48
+ creates is recorded by its ID in `created.jsonl`, which holds no secret, and the teardown deletes
49
+ every recorded account, so an account made by a refresh is removed too.
50
+
51
+ ```ts
52
+ // session-directory.ts
53
+ import { statSync } from "node:fs";
54
+ import fs from "node:fs/promises";
55
+ import os from "node:os";
56
+ import path from "node:path";
57
+
58
+ export async function createSessionDirectory(): Promise<string> {
59
+ const directory = await fs.mkdtemp(path.join(os.tmpdir(), "session-cache-"));
60
+ await fs.chmod(directory, 0o700);
61
+ process.env.TEST_SESSION_CACHE_DIR = directory;
62
+ return directory;
63
+ }
64
+
65
+ /** Every worker calls this; a missing or shared directory stops the run. */
66
+ export function ownedSessionDirectory(): string {
67
+ const directory = process.env.TEST_SESSION_CACHE_DIR;
68
+ if (!directory) throw new Error("TEST_SESSION_CACHE_DIR is not set: global setup creates it");
69
+ const stat = statSync(directory);
70
+ if (!stat.isDirectory()) throw new Error(`${directory} is not a directory`);
71
+ if (process.platform !== "win32" && (stat.mode & 0o077) !== 0)
72
+ throw new Error(`${directory} is readable by other users`);
73
+ return directory;
74
+ }
75
+
76
+ export async function recordCreated(directory: string, id: string): Promise<void> {
77
+ await fs.appendFile(path.join(directory, "created.jsonl"), `${JSON.stringify({ id })}\n`, {
78
+ mode: 0o600,
79
+ });
80
+ }
81
+
82
+ export async function deleteCreatedAccounts(directory: string): Promise<void> {
83
+ let lines: string[] = [];
84
+ try {
85
+ lines = (await fs.readFile(path.join(directory, "created.jsonl"), "utf8")).split("\n");
86
+ } catch (error) {
87
+ if (!(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
88
+ }
89
+ for (const line of lines.filter((entry) => entry.trim() !== "")) {
90
+ const { id }: { id: string } = JSON.parse(line);
91
+ await deleteAccount(id);
92
+ }
93
+ }
94
+ ```
95
+
96
+ The directory is how both recipes meet the rule that binds the cache's lifetime to the worker's:
97
+ here a worker is a pool slot or a parallel index, which lasts the whole run, and the run's teardown
98
+ removes the directory with every cached session in it.
99
+
100
+ ## Vitest: one session per pool slot and actor
101
+
102
+ Vitest isolates each test file in its own module registry, so a module-level cache does not outlive
103
+ one file. A process ID or a per-file counter does not give a worker lifetime either. What survives
104
+ is the pool slot, `VITEST_POOL_ID`, a stable number per worker slot. Key the cache by the private
105
+ directory the run owns, the slot and the actor. In this recipe a worker is that pool slot, and the
106
+ cache lives as long as the slot does: until the run's teardown removes the directory.
107
+
108
+ ```ts
109
+ import { createHash } from "node:crypto";
110
+ import fs from "node:fs/promises";
111
+ import path from "node:path";
112
+
113
+ type SessionOptions = {
114
+ actor: string;
115
+ create: (slot: string) => Promise<string>;
116
+ accepted: (session: string) => Promise<boolean>;
117
+ };
118
+
119
+ /** The run owns the directory; the pool slot survives isolated file registries. */
120
+ export async function workerSession({ actor, create, accepted }: SessionOptions): Promise<string> {
121
+ const directory = ownedSessionDirectory();
122
+ const worker = process.env.VITEST_POOL_ID;
123
+ if (!worker || !/^\d+$/.test(worker)) throw new Error("A worker session requires VITEST_POOL_ID");
124
+ const key = createHash("sha256").update(actor).digest("hex").slice(0, 20);
125
+ const file = path.join(directory, `${worker}-${key}.json`);
126
+ const record = (event: "issued" | "reused" | "refreshed") =>
127
+ fs.appendFile(
128
+ path.join(directory, `${worker}.events.jsonl`),
129
+ `${JSON.stringify({ worker, actor: key, event })}\n`,
130
+ );
131
+ let session: string | undefined;
132
+ try {
133
+ const restored: unknown = JSON.parse(await fs.readFile(file, "utf8"));
134
+ if (typeof restored === "string") session = restored;
135
+ } catch (error) {
136
+ const missing = error instanceof Error && "code" in error && error.code === "ENOENT";
137
+ if (!(error instanceof SyntaxError) && !missing) throw error;
138
+ }
139
+ if (session !== undefined && (await accepted(session))) {
140
+ await record("reused");
141
+ return session;
142
+ }
143
+ const event = session === undefined ? "issued" : "refreshed";
144
+ session = await create(worker);
145
+ await fs.writeFile(file, JSON.stringify(session), { mode: 0o600 });
146
+ await record(event);
147
+ return session;
148
+ }
149
+ ```
150
+
151
+ A file-local map validates each actor once per file registry, so a file does not ask the product
152
+ about the same session for every test:
153
+
154
+ ```ts
155
+ const sessions = new Map<string, Promise<string>>();
156
+
157
+ export function sessionFor(actor: string): Promise<string> {
158
+ let pending = sessions.get(actor);
159
+ if (pending === undefined) {
160
+ pending = workerSession({
161
+ actor,
162
+ create: async (slot) => {
163
+ const account = await createAccount(actor, slot);
164
+ await recordCreated(ownedSessionDirectory(), account.id);
165
+ return issueSession(account);
166
+ },
167
+ accepted: acceptsSession,
168
+ });
169
+ sessions.set(actor, pending);
170
+ }
171
+ return pending;
172
+ }
173
+ ```
174
+
175
+ Global setup creates the directory before the workers start, and the teardown it returns, which
176
+ runs after a failed run too, deletes the recorded accounts and removes the directory:
177
+
178
+ ```ts
179
+ // vitest.global-setup.ts
180
+ import fs from "node:fs/promises";
181
+
182
+ export default async function setup() {
183
+ const directory = await createSessionDirectory();
184
+ return async () => {
185
+ await deleteCreatedAccounts(directory);
186
+ await fs.rm(directory, { recursive: true, force: true });
187
+ };
188
+ }
189
+ ```
190
+
191
+ The workers see `TEST_SESSION_CACHE_DIR` because Vitest starts them after global setup and they
192
+ inherit its environment; the recipe relies on that start-up order. Vitest's documented channel from
193
+ global setup to tests is `provide` and `inject`: where your version offers it, pass the directory
194
+ that way and have `ownedSessionDirectory()` read it from `inject`.
195
+
196
+ Keep these behaviours when you adapt it:
197
+
198
+ - An explicit session, a bearer credential or an intentionally anonymous request bypasses the
199
+ default fixture.
200
+ - A rejected cache is refreshed while the fixture is prepared. A product request that returns 401
201
+ is never repeated automatically: that 401 is the result under test.
202
+ - A store error propagates. Only a missing file or an unreadable record means "no session"; an
203
+ error reading the directory is not an invalid credential.
204
+ - Login, logout, expiry and password-change tests use their own subjects, never a pooled actor.
205
+
206
+ ## Playwright: one account and storage state per worker
207
+
208
+ A global setup creates the run's private directory; a setup project signs one account in per
209
+ worker and saves its storage state there; the test project picks the state by the worker's parallel
210
+ index; a teardown project deletes the recorded accounts and their states. The worker count is fixed
211
+ in the configuration, so the setup and the run agree on it. In this recipe a worker is a parallel
212
+ index, and its storage state lives until the run's teardown removes the directory.
213
+
214
+ ```ts
215
+ // playwright.config.ts
216
+ import { defineConfig } from "@playwright/test";
217
+
218
+ export default defineConfig({
219
+ globalSetup: "./global-setup.ts",
220
+ workers: 4,
221
+ projects: [
222
+ { name: "setup", testMatch: /auth\.setup\.ts/, teardown: "teardown" },
223
+ { name: "teardown", testMatch: /auth\.teardown\.ts/ },
224
+ {
225
+ name: "e2e",
226
+ dependencies: ["setup"],
227
+ testIgnore: [/auth\.(setup|teardown)\.ts/, /\.exclusive\.spec\.ts/],
228
+ },
229
+ { name: "exclusive", dependencies: ["setup"], testMatch: /\.exclusive\.spec\.ts/ },
230
+ ],
231
+ });
232
+ ```
233
+
234
+ ```ts
235
+ // global-setup.ts: the environment it sets reaches every worker
236
+ import fs from "node:fs/promises";
237
+
238
+ export default async function globalSetup() {
239
+ const directory = await createSessionDirectory();
240
+ return async () => {
241
+ await fs.rm(directory, { recursive: true, force: true });
242
+ };
243
+ }
244
+ ```
245
+
246
+ ```ts
247
+ // auth.setup.ts
248
+ import { chmod } from "node:fs/promises";
249
+ import { test as setup } from "@playwright/test";
250
+
251
+ setup("sign in one account per worker", async ({ browser }) => {
252
+ const directory = ownedSessionDirectory();
253
+ for (let slot = 0; slot < setup.info().config.workers; slot++) {
254
+ const account = await createAccount("member", String(slot));
255
+ await recordCreated(directory, account.id);
256
+ const context = await browser.newContext();
257
+ await signIn(await context.newPage(), account);
258
+ await context.storageState({ path: statePath(directory, slot) });
259
+ await chmod(statePath(directory, slot), 0o600);
260
+ await context.close();
261
+ }
262
+ });
263
+ ```
264
+
265
+ ```ts
266
+ // fixtures.ts
267
+ import { test as base } from "@playwright/test";
268
+
269
+ export const test = base.extend({
270
+ storageState: async ({}, use, testInfo) => {
271
+ await use(statePath(ownedSessionDirectory(), testInfo.parallelIndex));
272
+ },
273
+ });
274
+ ```
275
+
276
+ ```ts
277
+ // auth.teardown.ts
278
+ import { rm } from "node:fs/promises";
279
+ import { test as teardown } from "@playwright/test";
280
+
281
+ teardown("delete the run's accounts and storage states", async () => {
282
+ const directory = ownedSessionDirectory();
283
+ await deleteCreatedAccounts(directory);
284
+ for (let slot = 0; slot < teardown.info().config.workers; slot++) {
285
+ await rm(statePath(directory, slot), { force: true });
286
+ }
287
+ });
288
+ ```
289
+
290
+ A test whose subject is the session itself (login, logout, expiry, password change) starts from an
291
+ empty storage state with `test.use({ storageState: { cookies: [], origins: [] } })` and creates its own
292
+ subject. When the suite runs once per clock profile, each profile runs its own setup and teardown.
293
+
294
+ ## Business data each file owns
295
+
296
+ Reusing an authenticated actor must not make one file depend on another file's business data.
297
+
298
+ - Each file prepares the minimum business data its tests read, in its own hooks.
299
+ - Identities are unique per creation: a real-millisecond timestamp plus a random suffix, such as
300
+ `` `order-${Date.now()}-${randomUUID().slice(0, 8)}` ``. A fixed name collides across workers.
301
+ - Cleanup removes what the file created, and only that, including after a failed test.
302
+ - No file resets a mutable business seed. A reset in one worker deletes data another worker is
303
+ asserting on.
304
+
305
+ ## Database hooks only where a group needs them
306
+
307
+ When one file holds source-only cases and live cases, register the database preparation inside
308
+ the group that needs it, not at the top of the file:
309
+
310
+ ```ts
311
+ describe("source contract", () => {
312
+ it("parses the export format", () => {
313
+ /* no database */
314
+ });
315
+ });
316
+
317
+ describe("live store", () => {
318
+ let owned: OwnedRows | undefined;
319
+ beforeAll(async () => {
320
+ owned = await createMinimumRows(requireDatabase());
321
+ });
322
+ afterAll(async () => {
323
+ await owned?.remove();
324
+ });
325
+ it("persists an order", async () => {
326
+ /* uses owned */
327
+ });
328
+ });
329
+ ```
330
+
331
+ A source-only CI selector then creates no business rows. `requireDatabase()` throws when the
332
+ database is not configured, so a selected live case fails without it rather than skipping.
333
+
334
+ ## Shared and exclusive access to a common database or server
335
+
336
+ Four workers do not by themselves make concurrency safe. Admit files to a shared database or server
337
+ by declared access:
338
+
339
+ - **Shared**: the file reads and writes only data it owns. Shared files run in parallel, bounded by
340
+ what the database and server can serve, measured, not by the CPU count.
341
+ - **Exclusive**: the file changes something global: a setting, a schema, a clock, a feature flag, a
342
+ queue drained by everyone. An exclusive file runs alone.
343
+ - **Unknown**: a file that imports a helper whose effects you have not classified, or that mutates
344
+ global state, is exclusive until shown otherwise.
345
+
346
+ The simplest bounded admission is two passes: the shared files with the measured worker count,
347
+ then the exclusive files with one worker, for example a Vitest project with
348
+ `fileParallelism: false`, or `npx --no-install playwright test --project=exclusive --workers=1` after a run of the `e2e`
349
+ project.
350
+
351
+ ## Deterministic business time
352
+
353
+ A test that depends on the wall clock waits for a time of day or skips outside it. Control
354
+ business time instead:
355
+
356
+ - **Clock adapter.** The application reads business time through an adapter it supplies, with an
357
+ explicit time zone and a fixed date and time per profile. Server-side decisions read the same
358
+ adapter as the browser display; fixing only the browser leaves the server deciding on real time.
359
+ - **Production-safe boundary.** Test clock control is enabled only by start-up configuration of a
360
+ non-production build or environment. No ordinary production request can enable it or set it,
361
+ and a test proves that a production configuration ignores the control.
362
+ - **Independent cases per profile.** Each profile, such as inside and outside a business window,
363
+ runs its own cases: before, inside and after the window, and holiday and boundary instants where
364
+ the business has them. No case waits for real time and none skips on the time of day.
365
+ - **Workers.** A profile's clock is immutable while that profile is active. Workers sharing one
366
+ server and database share its clock, so two profiles never run against one mutable clock at once:
367
+ give each concurrently active profile its own server, or run the profiles one after another.
368
+ Data stays owned per file, as above.
369
+ - **Reports.** CI shows that every profile ran: one report per profile, each with the actual worker
370
+ count, the cases run, the skips and the flaky results.
371
+
372
+ ```ts
373
+ // One definition read by the server start-up and by the browser context of each profile.
374
+ export const clockProfiles = {
375
+ "in-window": { timeZone: "Asia/Tokyo", instant: "2030-01-15T10:30:00+09:00" },
376
+ "out-of-window": { timeZone: "Asia/Tokyo", instant: "2030-01-15T22:30:00+09:00" },
377
+ } as const;
378
+ ```
379
+
380
+ ## Credential directory hygiene
381
+
382
+ - The run owns its session directory: it creates it fresh, outside the checked-out tree, and
383
+ refuses a directory that already holds files it did not write.
384
+ - The directory is private (mode 700, files 600) and is removed by the teardown, which also runs
385
+ after a failure.
386
+ - Playwright traces, HAR files and HTML reports from an authenticated project carry cookies and
387
+ tokens. Do not upload them, or upload them only to a restricted location with a short retention,
388
+ and never from a public run.
389
+ - Artifact uploads exclude the directory. Keep only noncredential reuse metrics, such as the counts
390
+ of issued, reused and refreshed sessions per slot, copied out before the teardown removes it.
391
+
392
+ ## CI: auxiliary jobs inside the protected result
393
+
394
+ Independent auxiliary jobs, such as tooling checks or extra mutation probes, belong in the result
395
+ the branch protection requires. An aggregate job keeps the protected check name stable and fails
396
+ when any required job fails, is cancelled or is skipped when it should have run:
397
+
398
+ ```yaml
399
+ tests-required:
400
+ name: tests (required)
401
+ needs: [changes, unit, tooling, behavioral-proofs]
402
+ if: ${{ always() }}
403
+ runs-on: ubuntu-latest
404
+ timeout-minutes: 2
405
+ permissions:
406
+ contents: read
407
+ steps:
408
+ - name: required test verdict
409
+ env:
410
+ CHANGE_RESULT: ${{ needs.changes.result }}
411
+ CODE_CHANGED: ${{ needs.changes.outputs.code }}
412
+ UNIT_RESULT: ${{ needs.unit.result }}
413
+ TOOLING_RESULT: ${{ needs.tooling.result }}
414
+ PROOF_RESULT: ${{ needs.behavioral-proofs.result }}
415
+ run: |
416
+ set -euo pipefail
417
+ [ "$CHANGE_RESULT" = success ] || { echo "Change detection: $CHANGE_RESULT"; exit 1; }
418
+ expected=success
419
+ if [ "$CODE_CHANGED" = false ]; then expected=skipped; fi
420
+ for result in "$UNIT_RESULT" "$TOOLING_RESULT" "$PROOF_RESULT"; do
421
+ [ "$result" = "$expected" ] || { echo "Lane returned $result, expected $expected"; exit 1; }
422
+ done
423
+ ```
424
+
425
+ The change-detection job and the lanes are the application's. Report ordinary test counts, extra
426
+ source-mutation probes and their counts separately; a probe count is not a test count.
427
+
428
+ ## Adoption checklist
429
+
430
+ - Sign-ins per run equal workers times actors, plus the dedicated subjects, plus refreshes; the
431
+ reuse metrics show it.
432
+ - A second file on the same slot and actor reuses the session; two slots or two actors never share
433
+ one.
434
+ - A rejected session is refreshed once and rewritten; a store error fails the run.
435
+ - The source-only selector passes with no database configured and creates no rows; a live case
436
+ fails without its database.
437
+ - Every file passes alone and in any order, with no seed reset.
438
+ - Exclusive files never overlap another file on the same database or server.
439
+ - Each clock profile's report shows its cases ran with zero skips; a production configuration
440
+ ignores the test clock.
441
+ - The aggregate check fails when any required lane fails, is cancelled or is skipped unexpectedly.
442
+ - No artifact holds a session, a storage state or an account secret, and no trace, HAR file or
443
+ HTML report from an authenticated project is uploaded where it is public or kept long.
444
+ - The teardown deletes every account recorded in `created.jsonl`, after a failed run too.
445
+ - Parallel workers are bounded by shared-state exclusion; measure before claiming a speedup.
@@ -3,7 +3,7 @@
3
3
  ## Inputs
4
4
 
5
5
  Read the UI surface paths `uiux.surfacePaths` declares in qfai.config.yaml, and resolve paths.contractsDir from the same file. Read every UI contract under its ui/ directory, and the root DESIGN.md if present for the brand tokens.
6
- When a prototyping loop ran in this checkout, read its handoff at .qfai/prototype/final/handoff.json: the final prototype, its procurement and the implementation notes.
6
+ When a prototyping loop ran in this checkout, read its handoff at .qfai/prototype/final/handoff.json: the final prototype, its procurement and the implementation notes, or, for a restyle, its live routes, its stylesheet and motion entry points and the implementation notes.
7
7
  Read the flow, story, acceptance criterion, and example that the implementation changes.
8
8
  For each screen the change renders, read its `supplements` and `structure` in the UI contract before adding text: the screen shows its title, group headings, labels and declared supplements, and no other text.
9
9
 
@@ -20,8 +20,8 @@ product-surface-reviewer. Do not infer that a change has no UI effect from its d
20
20
 
21
21
  ## Evidence
22
22
 
23
- For a UI affecting example, report the screen state, action, expected and observed result, and a capture or rendered artifact. The artifact must identify the source revision. In the stage review, product-surface-reviewer judges each UI affecting example, its UI contracts, and its captured state. The review verdict refers to that revision.
23
+ For a UI affecting example, report the screen state, action, expected and observed result, and a capture or rendered artifact. The artifact must identify the source revision. In the review that reads the change, product-surface-reviewer judges each UI affecting example, its UI contracts, and its captured state. The review verdict refers to that revision.
24
24
 
25
- If the implementation or capture changes after the verdict, refresh the capture and review. A passing code test cannot substitute for the visual and interaction evidence that the acceptance criterion requires.
25
+ A fix made for a finding of that review refreshes the capture it changes, and a fix that changes behaviour gets its one focused re-review (`.qfai/assistant/rule/review-convergence.md#one-review`). A passing code test cannot substitute for the visual and interaction evidence that the acceptance criterion requires.
26
26
 
27
27
  Capture each declared task at a desktop width and a narrow width, in the normal state and in every declared empty, error, loading and success state the screen has. A text the contract declares that the capture lacks, or a text the capture shows that the contract does not declare, is a finding.
@@ -42,8 +42,9 @@ no `prototyping` command group, and no command or check certifies the result:
42
42
  prototyping completes when the user confirms the prototype.
43
43
 
44
44
  Every file the loop writes stays under `.qfai/prototype/`: the session record,
45
- each iteration and its reviews, and the handoff. No `qfai` command writes
46
- there. The one file a command reads is the handoff record
45
+ each iteration and its reviews, and the handoff. A `restyle` loop also edits
46
+ the project's stylesheet and motion entry points its handoff names. No `qfai`
47
+ command writes any of these files. The one file a command reads is the handoff record
47
48
  `.qfai/prototype/final/handoff.json`, which
48
49
  `npx qfai validate --profile saas-package` checks against the CLI-HANDOFF schema.
49
50
 
@@ -59,12 +60,12 @@ When unsure, read inputs in this order:
59
60
 
60
61
  ## Steps
61
62
 
62
- | Step | Runs |
63
- | ----------------------- | ------------------------------------------------------------------------------------ |
64
- | `prototyping-grill` | Always, first: fixes the scope and settles by talking what the prototype is for |
65
- | `prototyping-preflight` | Always: checks the UI contracts, root `DESIGN.md` and the Playwright environment |
66
- | `prototyping-loop` | Always: build, review, and put each reviewed prototype to the user until they accept |
67
- | `prototyping-handoff` | Only after the user confirmed the prototype: copy it and write the handoff |
63
+ | Step | Runs |
64
+ | ----------------------- | --------------------------------------------------------------------------------------------------------- |
65
+ | `prototyping-grill` | Always, first: fixes the scope and settles by talking what the prototype is for |
66
+ | `prototyping-preflight` | Always: checks the UI contracts, root `DESIGN.md` and the Playwright environment |
67
+ | `prototyping-loop` | Always: build, review, and put each reviewed prototype to the user until they accept |
68
+ | `prototyping-handoff` | Only after the user confirmed the prototype: copy it and write the handoff (restyle: `handoff.json` only) |
68
69
 
69
70
  A step's gate that ends the run ends the invocation: zero UI-bearing contracts
70
71
  at preflight, an escalated decision before the first iteration, or a stop or a
@@ -113,4 +114,4 @@ no question. Under a no-question mode, list any remaining actions instead.
113
114
  project_memory:
114
115
 
115
116
  - Prototyping completes on the user's confirmation; no command certifies it.
116
- - Every file the loop writes is under `.qfai/prototype/`; a `qfai` command reads only `final/handoff.json`.
117
+ - Every file the loop writes is under `.qfai/prototype/`, except the stylesheet and motion entry points a `restyle` loop edits; a `qfai` command reads only `final/handoff.json`.