@1aboveio/engineering-skills 0.1.10 → 0.1.11

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 (66) hide show
  1. package/README.md +1 -1
  2. package/package.json +2 -2
  3. package/skills/better-review/SKILL.md +37 -37
  4. package/skills/better-review/references/passes.md +35 -41
  5. package/skills/better-review/references/result.md +10 -9
  6. package/skills/e2e-test/SKILL.md +17 -17
  7. package/skills/e2e-test/references/authoring/playwright-config.md +11 -13
  8. package/skills/e2e-test/references/presentation-sweep.md +7 -7
  9. package/skills/e2e-test/references/reviewing.md +9 -11
  10. package/skills/e2e-test/references/route-manifest.md +1 -1
  11. package/skills/engineering/SKILL.md +124 -0
  12. package/skills/engineering/references/engineering-conventions.md +32 -0
  13. package/skills/engineering/references/feature-delivery.md +8 -0
  14. package/skills/engineering/references/init-scope.md +37 -0
  15. package/skills/engineering/scripts/init.mjs +160 -0
  16. package/skills/{contributing → engineering}/scripts/persist-conventions.mjs +1 -1
  17. package/skills/engineering-runtime/SKILL.md +1 -1
  18. package/skills/engineering-runtime/coherence/workflow.json +19 -19
  19. package/skills/engineering-runtime/scripts/workflow-policy.mjs +1 -1
  20. package/skills/ensure-coverage/SKILL.md +22 -109
  21. package/skills/ensure-coverage/references/breadth/coverage-ledger.md +7 -5
  22. package/skills/ensure-coverage/references/breadth/surface-baseline.md +4 -4
  23. package/skills/ensure-coverage/references/breadth/surface-discovery.md +3 -3
  24. package/skills/ensure-coverage/references/depth/characterization.md +4 -65
  25. package/skills/ensure-coverage/references/depth/grading.md +5 -7
  26. package/skills/ensure-coverage/references/depth/mock-policy.md +6 -12
  27. package/skills/ensure-coverage/references/enforcement/ci-contract.md +1 -1
  28. package/skills/ensure-coverage/references/presentation/axis.md +6 -6
  29. package/skills/ensure-coverage/references/process/audit-mode.md +7 -23
  30. package/skills/ensure-coverage/references/process/output-template.md +18 -133
  31. package/skills/ensure-coverage/references/process/test-strategy.md +7 -12
  32. package/skills/ensure-coverage/scripts/README.md +12 -4
  33. package/skills/golden-path/SKILL.md +1 -1
  34. package/skills/harness-runtime/SKILL.md +3 -1
  35. package/skills/harness-runtime/bin/workspaces.mjs +52 -0
  36. package/skills/harness-runtime/native-workspace.mjs +239 -0
  37. package/skills/harness-runtime/references/workspaces.md +78 -0
  38. package/skills/harness-runtime/workspace-lifecycle.mjs +2154 -0
  39. package/skills/resolve-issues/SKILL.md +40 -61
  40. package/skills/resolve-issues/references/ci.md +13 -3
  41. package/skills/resolve-issues/references/delivery-progress.md +4 -3
  42. package/skills/resolve-issues/references/done.md +11 -2
  43. package/skills/resolve-issues/references/expire.md +9 -2
  44. package/skills/resolve-issues/references/implementation.md +33 -17
  45. package/skills/resolve-issues/references/preflight.md +3 -1
  46. package/skills/resolve-issues/references/principles.md +52 -0
  47. package/skills/resolve-issues/references/review.md +25 -15
  48. package/skills/resolve-issues/references/task-plan.md +64 -27
  49. package/skills/resolve-issues/references/workspaces.md +164 -0
  50. package/skills/resolve-issues/scripts/cleanup-runs.mjs +185 -317
  51. package/skills/resolve-issues/scripts/next-actions.mjs +44 -7
  52. package/skills/resolve-issues/scripts/rehydrate.mjs +36 -2
  53. package/skills/resolve-issues/scripts/review-verdict.mjs +9 -8
  54. package/skills/resolve-issues/scripts/workspace-lifecycle.mjs +1 -0
  55. package/skills/resolve-release/SKILL.md +1 -1
  56. package/skills/rush-issues/SKILL.md +7 -5
  57. package/skills/rush-release/SKILL.md +1 -1
  58. package/skills/test-quality/SKILL.md +19 -4
  59. package/skills/test-quality/references/lint.md +1 -1
  60. package/skills/test-quality/references/principles.md +2 -2
  61. package/skills/test-quality/references/testing-conventions.md +1 -1
  62. package/skills/contributing/SKILL.md +0 -70
  63. /package/skills/{contributing → engineering}/LICENSE +0 -0
  64. /package/skills/{contributing → engineering}/references/tracker-conventions.md +0 -0
  65. /package/skills/{contributing → engineering}/release-check.mjs +0 -0
  66. /package/skills/{contributing → engineering}/scripts/persist-conventions-core.mjs +0 -0
@@ -1,139 +1,24 @@
1
- # Output Template, Writing Rules & Validation (process)
1
+ # Output Template, Writing Rules & Validation
2
2
 
3
- > Read when: producing the criteria/audit document (create mode), or running the final self-check before saving.
4
-
5
- ## Lead with the verdict
6
-
7
- An **audit deliverable opens with the verdict**, not buries it under tables. Put a one-line `## Verdict: Ship / No-ship` (with the one-sentence reason) as the **first section**, before the Surface Census and the detailed assessment, which then *justify* it below. (Create-mode criteria docs lead with Source/Scope — there's no verdict yet.)
8
-
9
- **A no-ship is a number, not a vibe.** The verdict carries the counts that make it no-ship: uncovered surfaces, orphan surfaces, ledger warnings, skipped tests, over-mock findings. If a finding has a count, the count goes in the summary; "it doesn't block CI yet" is never a license to omit it.
10
-
11
- ## Writing Rules
12
-
13
- - Make each AC independently testable.
14
- - Prefer observable outcomes over internal implementation details.
15
- - Include negative cases and misuse paths, not only happy paths.
16
- - For async/pub-sub/orchestrator systems, require correlation IDs and final durable state assertions.
17
- - For idempotent APIs, require duplicate request tests and concurrent request tests when money/state transitions are involved.
18
- - For security-sensitive flows, require authorization tests for cross-tenant/cross-merchant access.
19
- - For provider integrations, use fake adapters in integration tests and real providers only in staging smoke tests.
20
- - Avoid vague criteria like “works correctly,” “fast,” or “secure”; replace them with measurable expectations.
21
-
22
- ## Output Template
23
-
24
- Use this structure unless the user asks for another format:
3
+ Use the issue or conversation by default. Create a document only when requested or required by the repository. Adapt this optional structure to the agreed scope rather than filling every section for routine work.
25
4
 
26
5
  ```markdown
27
- # Test Criteria: <feature/task name>
28
-
29
- ## Source
30
- - Input: <PRD/design document/spec/bug brief/GitHub issue/code audit source name or link>
31
- - Version/date: <if available>
32
- - Author/owner: <if available>
33
-
34
- ## Scope
35
- - In scope: <behaviors covered>
36
- - Out of scope: <behaviors intentionally excluded>
37
- - Assumptions: <behavior inferred from issue/context/sibling flows because source is incomplete>
38
- - Blockers: <product/access/env decisions that prevent precise criteria>
39
- - Design source: <the prototype ref:path / mockup / layout-fixing doc this unit is built from, pinned at a commit — or `none`>
40
-
41
- > **"Out of scope" excludes behaviors, never the axis the unit is about.** A unit that cites a **Design source** owes `presentation:fidelity` ([../presentation/axis.md](../presentation/axis.md)); listing that evidence as a non-goal declares the point of the work out of scope (named incident: fmm-express #521). A unit with no design source simply says `none`.
42
-
43
- ## Acceptance Criteria
44
- - AC1: <actor/system does ... under condition ... with expected observable result>
45
- - AC2: <...>
46
-
47
- ## Critical User/System Journeys
48
- - J1: <actor/role starts from ... does ... and reaches ... with expected side effects>
49
- - J2: <...>
50
-
51
- ## Test Matrix
52
- | Scenario | AC/Journey | Test Level | Mock/Fake Policy | Setup/Input | Assertions | Proving Test |
53
- |---|---|---|---|---|---|---|
54
- | Happy path | AC1 / J1 | Integration/API | Real DB + fake external provider | ... | ... | test name |
55
- | Invalid input | AC2 | Unit + API | Mock provider only to assert it is not called | ... | ... | test name |
56
-
57
- ## Mock And Integration Policy
58
- - Mock acceptable: <pure decision logic, provider failures, asserting side effect is not called>
59
- - Integration required: <DB transactions, idempotency, concurrency, event/outbox, auth/tenant isolation, schema compatibility>
60
- - External dependency strategy: <fake provider adapter, emulator, test container, staging smoke test>
61
- - Mock-only exceptions: <AC/scenario + justification + reviewer approval; mocking a first-party internal seam is never an approvable exception — [../depth/mock-policy.md](../depth/mock-policy.md)>
62
-
63
- ## Required Automated Tests
64
- - Unit: <specific logic and edge cases>
65
- - Integration: <DB/broker/provider fakes/state transitions>
66
- - Contract/API: <request/response/schema guarantees>
67
- - API E2E: <endpoint behavior with state/side-effect assertions, if needed>
68
- - UI E2E: <page route render-health/functional browser behavior, if needed>
69
- - Journey E2E: <cross-page/core business flow with real APIs where practical, if needed>
70
-
71
- ## Coverage Mapping
72
- | Requirement/Journey | ACs | Test Case/File | Status |
73
- |---|---|---|---|
74
- | <REQ-1 / J1> | AC1, AC2 | <path::test_name> | Required |
75
-
76
- ## Surface Census (Audit Mode Only — every surface, not just the gaps)
77
- One row per inventoried surface so completeness is provable by construction: gaps = every row not `Covered`/`Excluded`. If the inventory can't be fully enumerated, say so and mark the rest `BLOCKED` — do not quietly scope to what was easy to see.
78
- | Surface | kind/class | Required level | Status | Proving test (or — ) |
79
- |---|---|---|---|---|
80
- | /settings/team | route/mutation | browser-journey + presentation | Over-mocked | e2e/team.spec.ts (intercepts own API) |
81
- | /settings/team/members | route/mutation | browser-journey + presentation | Missing | — (orphan, no test) |
82
- | /api/team/invite | api/mutation | api + integration | Partial | tests/api/invite.test.ts |
83
- | ... (every remaining surface) | ... | ... | ... | ... |
84
-
85
- ## Existing Coverage Assessment (Audit Mode Only)
86
- - Production-readiness verdict: <Ship / No-ship>, with the specific user scenarios likely to generate bug reports in the first week and the evidence that would raise confidence. **State the driving counts** (uncovered/orphan surfaces, ledger warnings, skips, over-mock findings) — a no-ship names its numbers, including advisory-scan counts; it does not hide them behind "partial."
87
- - Current coverage status: <Covered / Partial / Missing / Wrong Level / Over-mocked / Unverified / BLOCKED>
88
- - Existing tests reviewed: <actual paths/test names/cases/assertions inspected; do not list docs-only claims as reviewed tests>
89
- - Code paths reviewed: <paths/modules>
90
- - Route/endpoint discovery: <method/command/source used, discovered count, manifest count, missing/stale/uncovered entries>
91
- - Route reachability: <Reachable / Redirected / Guarded / Blocked / Unknown per relevant route, with layout/middleware/guard evidence>
92
- - E2E journeys identified: <journey list or Not applicable>
93
- - E2E journey coverage: <journey -> API/UI/Journey E2E evidence/status>
94
- - Prior coverage docs/reports checked: <None or list; state which claims were verified against test code>
95
- - Coverage gaps: <missing scenarios, weak assertions, over-mocking, wrong level, uncovered journeys, unverified claims, or None>
96
- - Follow-up test criteria items: <specific tests to add/update, with AC/journey mapping>
97
-
98
- ## Test Skipping
99
- - Skipped tests: <None or list with allowed category, evidence/blocker link, and replacement verification>
100
-
101
- ## Behavior-First Validation
102
- - ACs describe externally observable behavior, not private functions.
103
- - Test matrix scenarios validate outcomes, durable state, contracts, side effects, permissions, and failure behavior.
104
- - Unit tests are scoped to public behavior, pure decision logic, or stable public contracts.
105
- - Mock-only coverage does not bypass the core behavior under test.
106
- - Existing coverage claims were verified against actual test code, not trusted from prior docs/reports.
107
- - Route discovery and reachability analysis were performed before E2E audit, if applicable.
108
- - Production-readiness verdict is stated as an explicit ship/no-ship call with named first-week bug-report scenarios, not a vibe.
109
- - Status: PASS / FAIL / BLOCKED
110
- - Required revisions before approval: <None or list>
111
-
112
- ## Reviewer Checklist
113
- - Obligation impact stated: which obligations/surfaces this change touches, their `requirementRefs`, and the test that proves each.
114
- - No `Orphan surface` introduced: every changed/new surface is referenced by at least one requirement and has a Coverage Ledger row.
115
- - Every changed/new page with a write form has a mutation-form journey test that fills the real UI and asserts the backend accepts the submission; split-contract forms (fields and validator from different sources) are not signed off on seam tests alone.
116
- - Every AC maps to an automated test or approved exception.
117
- - Tests assert behavior/state, not implementation details only.
118
- - No tests skipped/weakened to make CI pass; every (inherited) skip has an allowed category, evidence/blocker link, and replacement verification.
119
- - Substitutes appear only at external trust boundaries; no internal seam (DB, service layer, internal endpoint, event bus) is mocked. Fakes/stubs keep failure-path/edge cases fast and deterministic and never call a live third party in CI; mocks/fakes don't bypass the core behavior.
120
- - Mock-only coverage is rejected for stateful workflow, money movement, auth, idempotency, concurrency, event/outbox, or orchestrator recovery unless explicitly approved; money movement, auth, and idempotency can never be mock-only even with approval. Mocking a first-party internal seam is never approvable ([the mock policy](../depth/mock-policy.md)).
121
- - Failure, retry, duplicate, permission, and concurrency cases are covered where relevant.
122
- - Each proving test ran green (exit 0). No logs, screenshots, traces, or read-backs attached on top.
123
-
124
- ## Blocking Decisions (need a human answer to finalize the criteria)
125
- Each entry is a product/scope decision you could NOT make yourself — phrase it so the reader knows exactly what to decide and why it matters. These are distinct from follow-up actions (which are just work to schedule); a blocking decision changes the criteria/verdict depending on the answer.
126
- - Decision: <the choice to make> · Why it blocks: <which AC/scope/verdict is undetermined until this is answered> · If A → <consequence for the criteria/tests> · If B → <consequence>. Default if no answer: <the assumption you'll proceed on, marked `Assumption`>.
6
+ ## Outcome and scope
7
+ - Source, agreed behavior, material risks, assumptions, and out-of-scope work.
8
+ - Product or architecture decisions needing their owners, if any.
9
+
10
+ ## Agreed acceptance criteria and proof
11
+ - Observable criteria agreed before implementation.
12
+ - Existing tests or checks that suffice; focused additional proof if needed.
13
+ - Required repository checks and applicable security or data-integrity protections.
14
+
15
+ ## Assessment (when auditing)
16
+ - Evidence inspected and execution results; what each proves and does not prove.
17
+ - Coverage grades for the agreed scope, with concrete gaps and unavailable evidence.
18
+ - Required fixes or decisions, separate from speculative follow-ups.
19
+ - What was verified and what was not.
127
20
  ```
128
21
 
129
- ## Behavior-First Validation (the gate before saving)
130
-
131
- After drafting, validate and revise before saving. Mark `BLOCKED` only when the source lacks enough information/access to define observable behavior. Reject criteria or audit claims that rely on:
22
+ Use a surface census only for an explicitly requested broad audit; state its boundaries and any incomplete inventory. Do not invent a ship/no-ship verdict where the evidence or an owner decision is missing. If a verdict is requested, explain its concrete basis; do not make an untested hypothetical state an automatic blocker. A newly found concrete defect may require a fix without silently changing the agreed criteria.
132
23
 
133
- - ACs phrased as calls to specific internal functions, or test matrices organized around implementation modules instead of user/system scenarios.
134
- - Mock-heavy plans that never exercise state changes, API contracts, permissions, events, or side effects; or substitutes standing in for internal seams (DB, service layer, internal endpoints, event bus) instead of external trust boundaries.
135
- - Requirement coverage mapped only to private-method/unit tests when integration, contract, or E2E is required.
136
- - Coverage classified `Covered` from prior docs/PR summaries/audit reports/issue comments/CI/agent claims without inspecting actual test code/assertions.
137
- - E2E audits that skipped deterministic route/endpoint discovery or reachability analysis.
138
- - Audits driven only test-outward (mock census, existing-test mapping) without requirement-inward reconciliation, so `Orphan surface` gaps stay invisible.
139
- - Reachable pages with write forms treated as covered by route/API/validator tests, without a mutation-form journey that fills the rendered UI and asserts the backend accepts the submission (split-contract form gap).
24
+ Prefer observable behavior to implementation-shaped assertions. Choose relevant failure, authorization, tenant-isolation, money, or durable-state cases based on material risk and existing policy. Preserve required repository checks and adopted floors. For design work, compare against the agreed design where needed; a cited source does not automatically require a separate presentation campaign. Inspect tests before saying they prove a behavior, and do not claim that an unavailable or failed check passed.
@@ -4,15 +4,15 @@
4
4
 
5
5
  ## Test Level Selection
6
6
 
7
- Classify each AC before writing the matrix:
7
+ Choose sufficient proof for each agreed AC and material risk, reusing existing evidence. The examples below are options, not automatic extra layers; existing required checks and adopted floors remain binding:
8
8
 
9
9
  - Logic AC: unit test is acceptable for pure decision logic or stable public contracts.
10
- - Boundary AC: contract/API test is required for request/response, validation, schema, compatibility, and error contracts.
11
- - Stateful workflow AC: integration test is required for DB writes, transactions, state transitions, idempotency, and recovery.
12
- - Async/pub-sub/orchestrator AC: integration test is required with real state store plus broker emulator or fake event adapter; assert final durable state and emitted events.
10
+ - Boundary AC: consider a contract/API test for request/response, validation, schema, compatibility, and error contracts.
11
+ - Stateful workflow AC: consider an integration test for DB writes, transactions, state transitions, idempotency, and recovery.
12
+ - Async/pub-sub/orchestrator AC: consider an integration test with real state store plus broker emulator or fake event adapter; assert final durable state and emitted events.
13
13
  - Critical money/security AC: integration, API E2E, or Journey E2E is required; mock-only coverage is never acceptable here, even with approval.
14
- - Browser/UI AC: UI E2E is required for page behavior, navigation, user-visible errors, forms, and role-dependent visibility.
15
- - Cross-page/core business journey: Journey E2E is required with real APIs where practical; do not mock internal endpoints unless explicitly approved.
14
+ - Browser/UI AC: consider UI E2E for page behavior, navigation, user-visible errors, forms, and role-dependent visibility.
15
+ - Cross-page/core business journey: consider Journey E2E with real APIs where practical; do not mock internal endpoints unless explicitly approved.
16
16
 
17
17
  ## E2E Coverage Rules
18
18
 
@@ -31,12 +31,7 @@ Smoke is not a separate browser-test level. A browser smoke path is a **curated
31
31
 
32
32
  You can use the generated surface inventory to suggest candidates (mutation routes, auth/payments-looking routes, health endpoints), but do not let code discovery decide the golden-path manifest. Product/release judgment must promote candidates into `golden-paths.json` and write concrete observables.
33
33
 
34
- For audit mode:
35
-
36
- - Run deterministic route/endpoint discovery before coverage judgment.
37
- - Include discovery method, discovered count, manifest count, missing/stale/uncovered entries, and changed-route coverage status.
38
- - Build the user journey inventory before mapping tests; route render-health tests do not prove a business journey unless they exercise the full flow and assert final outcomes.
39
- - Decompose every reachable dashboard/settings page into its mutation-form journeys (e.g. "operator creates a GitHub connector account"). For each, require UI/Journey E2E proof that the form renders every backend-required field and that submitting it produces a payload the backend accepts plus the expected durable state change. Reject backend-validator, schema-source, and API-forwarding tests as a substitute — they are proxy wiring for a split-contract form.
34
+ For audit mode, inspect the routes and journeys relevant to the agreed scope. A render-health test does not by itself prove a business journey; a backend test alone does not prove a form submits correctly. Use broader discovery only for an explicitly requested broad audit, and do not require a separate browser journey for every form by default.
40
35
 
41
36
  ## Test Skipping Policy (no-skip)
42
37
 
@@ -1,8 +1,9 @@
1
1
  # ensure-coverage scripts
2
2
 
3
- The mechanized half of the skill: each script decides one thing the doctrine in
4
- [`../SKILL.md`](../SKILL.md) says must be proven. This file is the CLI reference. The
5
- *what* lives in `SKILL.md` and `references/`; the *why* of each rule is cited there.
3
+ This is the CLI reference for optional coverage tools. `SKILL.md` and `references/`
4
+ define when a tool is relevant; the checks below describe its unchanged mechanics,
5
+ not new acceptance conditions. Run a tool when requested or required by the repository.
6
+ Preserve adopted gates, but do not turn an optional scan into a feature blocker.
6
7
 
7
8
  **Resolution.** Every script is under this skill's own directory, not the target
8
9
  repo. Set `SKILL_DIR` to the directory you read `SKILL.md` from and run
@@ -45,7 +46,14 @@ Static test-lint gate engine. Deterministic, near-zero false positives, blocks o
45
46
  | `no-swallowed-assertion` | an assertion whose rejection is eaten by a chained `.catch(...)` |
46
47
  | `mock-internal-seam` | a `vi.mock` / `jest.mock` / `vitest.mock` whose target is first-party code |
47
48
 
48
- `mock-internal-seam` is default-on and zero-tolerance: no `@mock-ok` waiver, no grandfathering. In audit mode run it **whole-tree** (`--rules mock-internal-seam`, no `--diff`) and count every hit in the verdict. A believed false positive is fixed by declaring the repo's topology, never by waiving:
49
+ The scanner mechanically treats `mock-internal-seam` as default-on and zero-tolerance:
50
+ `@mock-ok` and inherited code do not suppress its exit status. Whole-tree scanning
51
+ belongs to an explicitly requested broad audit or an existing repo requirement;
52
+ a scoped task uses scoped checks when needed. Assess optional hits against the
53
+ behavior claimed; the classifier alone cannot determine test adequacy. Do not
54
+ require remediation merely because an optional scan flags a useful isolated unit
55
+ test. An adopted required gate remains binding. Correct topology declarations
56
+ when the scanner misclassifies an external boundary:
49
57
 
50
58
  ```json
51
59
  // coverage.config.json at the repo root — declares what counts as first-party
@@ -3,7 +3,7 @@ name: golden-path
3
3
  description: "Golden-path E2E: the short list of user journeys whose failure blocks a release, kept in a repo as one contract (golden-paths.json) with a generated GOLDEN_PATHS.md and a generated GitHub Actions workflow, and run against a local build or a deployed URL for an ALIVE/DEAD verdict. Use to set golden paths up in a repo ('init golden paths', 'add golden-path CI'), to migrate an older smoke.manifest.json or a hand-built smoke setup ('audit', 'migrate smoke'), to add, change, or remove a golden path, to ask 'is the build alive?' or run them before a PR or release, or when a change touches a flow listed in GOLDEN_PATHS.md. NOT for writing the Playwright specs themselves (e2e-test), deciding what a change must prove (ensure-coverage), or general workflow YAML (github-actions)."
4
4
  dependencies:
5
5
  - e2e-test
6
- release-version: 0.44.1
6
+ release-version: 0.45.0
7
7
  ---
8
8
  **Updates:** Once/session run `node <skill-base-dir>/release-check.mjs`.
9
9
  # Golden path
@@ -3,7 +3,7 @@ name: harness-runtime
3
3
  description: Internal import-only library shared by first-party engineering packages. Not a workflow skill; never select or invoke it as a user capability.
4
4
  disable-model-invocation: true
5
5
  user-invocable: false
6
- release-version: 0.44.1
6
+ release-version: 0.45.0
7
7
  ---
8
8
  **Updates:** Once/session run `node <skill-base-dir>/release-check.mjs`.
9
9
  # Harness Runtime
@@ -17,3 +17,5 @@ This support-only runtime package exposes shared programmatic contracts plus can
17
17
  - `index.mjs` exports neutral constructors plus pure question planning and response normalization.
18
18
  - `discover-models.mjs` enumerates model evidence; `model-catalog.mjs` manages per-harness classifications.
19
19
  - `references/model-catalog.md` documents catalog policy; `bin/` contains the installed command wrappers.
20
+ - `workspace-lifecycle.mjs` and `bin/workspaces.mjs` own workspace preparation and reclamation;
21
+ read [references/workspaces.md](references/workspaces.md) for standalone native setup.
@@ -0,0 +1,52 @@
1
+ #!/usr/bin/env node
2
+ import { execFileSync } from 'node:child_process'
3
+ import { prepare, cleanup, recover, inventory } from '../workspace-lifecycle.mjs'
4
+ import { nativeStart, nativeFinish } from '../native-workspace.mjs'
5
+
6
+ const allowed = {
7
+ prepare: ['run', 'unit', 'revision', 'apply', 'json'],
8
+ cleanup: ['run', 'unit', 'revision', 'apply', 'json'],
9
+ recover: ['repo', 'json'],
10
+ inventory: ['repo', 'root', 'max-entries', 'max-depth', 'json'],
11
+ 'native-start': ['repo', 'run-id', 'base', 'branch', 'target', 'platform', 'kind', 'native-dir', 'disposable', 'json'],
12
+ 'native-finish': ['run', 'json'],
13
+ }
14
+
15
+ function options(command, args) {
16
+ if (!Object.hasOwn(allowed, command)) throw new Error('expected prepare, cleanup, recover, inventory, native-start or native-finish')
17
+ const out = {}
18
+ for (let index = 0; index < args.length; index++) {
19
+ const name = args[index].replace(/^--/, '')
20
+ if (!args[index].startsWith('--') || !allowed[command].includes(name)) throw new Error(`invalid ${command} option: ${args[index]}`)
21
+ const key = name.replace(/-([a-z])/g, (_, value) => value.toUpperCase())
22
+ if (Object.hasOwn(out, key) && name !== 'disposable') throw new Error(`duplicate option: --${name}`)
23
+ if (name === 'apply' || name === 'json') { out[key] = true; continue }
24
+ const value = args[++index]
25
+ if (value === undefined || value.startsWith('--')) throw new Error(`--${name} needs a value`)
26
+ if (name === 'disposable') (out[key] ??= []).push(value)
27
+ else out[key] = value
28
+ }
29
+ for (const key of ['revision', 'maxEntries', 'maxDepth']) {
30
+ if (out[key] === undefined) continue
31
+ if (!/^\d+$/.test(out[key]) || !Number.isSafeInteger(Number(out[key]))) throw new Error(`invalid ${key}`)
32
+ out[key] = Number(out[key])
33
+ }
34
+ return out
35
+ }
36
+
37
+ try {
38
+ const [command, ...args] = process.argv.slice(2)
39
+ const opts = options(command, args)
40
+ let result
41
+ if (command === 'native-start') result = nativeStart(opts)
42
+ else if (command === 'native-finish') result = nativeFinish(opts)
43
+ else if (command === 'prepare') result = prepare(opts)
44
+ else if (command === 'cleanup') result = cleanup({ ...opts, runGh: (argv) => execFileSync('gh', argv, { encoding: 'utf8', timeout: 30_000, maxBuffer: 4 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] }) })
45
+ else if (command === 'recover') result = recover(opts)
46
+ else result = inventory(opts)
47
+ process.stdout.write(`${JSON.stringify(result, null, 2)}\n`)
48
+ process.exitCode = result.ok === false ? 1 : 0
49
+ } catch (error) {
50
+ process.stderr.write(`${error.message}\n`)
51
+ process.exitCode = 2
52
+ }
@@ -0,0 +1,239 @@
1
+ import { execFileSync, spawnSync } from 'node:child_process'
2
+ import { existsSync, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from 'node:fs'
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path'
4
+ import { randomUUID } from 'node:crypto'
5
+ import { fileURLToPath } from 'node:url'
6
+
7
+ const cli = fileURLToPath(new URL('./bin/workspaces.mjs', import.meta.url))
8
+ const git = (cwd, ...args) => execFileSync('git', ['-C', cwd, ...args], { encoding: 'utf8', timeout: 30_000, stdio: ['ignore', 'pipe', 'pipe'] }).trim()
9
+ const component = (value) => typeof value === 'string' && /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/.test(value) && value !== '.' && value !== '..'
10
+
11
+ function stat(path) {
12
+ try { return lstatSync(path) } catch (error) { if (error.code === 'ENOENT') return null; throw error }
13
+ }
14
+
15
+ function noLinks(root, path) {
16
+ const rel = relative(root, path)
17
+ if (rel.startsWith(`..${sep}`) || rel === '..' || isAbsolute(rel)) throw new Error('workspace path escapes its repository')
18
+ let current = root
19
+ for (const part of rel.split(sep).filter(Boolean)) {
20
+ current = join(current, part)
21
+ if (stat(current)?.isSymbolicLink()) throw new Error(`symlink in managed path: ${current}`)
22
+ }
23
+ }
24
+
25
+ // This lock owns the plan, including initial creation. The engine independently locks
26
+ // workspace operations; its shorter lock cannot protect our read/modify/write cycle.
27
+ function withOwner(repo, run, operation) {
28
+ const locks = join(dirname(run), '.native-locks')
29
+ const lock = join(locks, basename(run))
30
+ noLinks(repo, run)
31
+ noLinks(repo, lock)
32
+ mkdirSync(locks, { recursive: true })
33
+ try { mkdirSync(lock) } catch (error) {
34
+ if (error.code !== 'EEXIST') throw error
35
+ let owner = 'unknown owner'
36
+ try { owner = `owner PID ${JSON.parse(readFileSync(join(lock, 'owner.json'), 'utf8')).pid ?? 'unknown'}` } catch { /* Unknown owners also block. */ }
37
+ throw new Error(`native run is locked at ${lock} (${owner}); locks are never reclaimed by age`)
38
+ }
39
+ try {
40
+ writeFileSync(join(lock, 'owner.json'), `${JSON.stringify({ pid: process.pid, run, at: new Date().toISOString() })}\n`, { flag: 'wx', mode: 0o600 })
41
+ return operation()
42
+ } finally {
43
+ try { unlinkSync(join(lock, 'owner.json')) } catch (error) {
44
+ if (error.code !== 'ENOENT') throw error
45
+ } finally {
46
+ rmdirSync(lock)
47
+ try { rmdirSync(locks) } catch (error) { if (!['ENOTEMPTY', 'ENOENT', 'EEXIST'].includes(error.code)) throw error }
48
+ }
49
+ }
50
+ }
51
+
52
+ function planStore(repo, run) {
53
+ const file = join(run, 'task-plan.json')
54
+ const read = () => {
55
+ noLinks(repo, file)
56
+ return stat(file) ? readFileSync(file, 'utf8') : null
57
+ }
58
+ let expected = read()
59
+ const plan = expected === null ? null : JSON.parse(expected)
60
+ let revision = plan?.planRevision ?? -1
61
+ return {
62
+ plan,
63
+ save(next) {
64
+ if (read() !== expected || (expected !== null && JSON.parse(expected).planRevision !== revision)) {
65
+ throw new Error('native plan revision/content changed; refusing to overwrite another owner')
66
+ }
67
+ next.planRevision = revision + 1
68
+ const text = `${JSON.stringify(next, null, 2)}\n`
69
+ const temp = `${file}.${randomUUID()}.tmp`
70
+ try {
71
+ writeFileSync(temp, text, { flag: 'wx', mode: 0o600 })
72
+ if (read() !== expected) throw new Error('native plan changed before persist; refusing to overwrite another owner')
73
+ renameSync(temp, file)
74
+ expected = text
75
+ revision = next.planRevision
76
+ } finally {
77
+ if (stat(temp)) unlinkSync(temp)
78
+ }
79
+ },
80
+ }
81
+ }
82
+
83
+ function ownedPlan(plan, repo, run) {
84
+ const unit = plan?.units?.[0]
85
+ if (plan?.skill !== 'native-setup' || plan.workspaceLifecycle !== 1 || plan.repoRoot !== repo || plan.runDir !== run ||
86
+ !Number.isSafeInteger(plan.planRevision) || plan.planRevision < 0 || plan.units?.length !== 1 || unit?.id !== 'native' ||
87
+ unit.workspace !== join(run, 'units', 'native') || unit.lifecycle?.version !== 1 ||
88
+ !['worktree', 'clone'].includes(unit.lifecycle.workspace?.kind) || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(unit.lifecycle.workspace?.baseSha ?? '') ||
89
+ unit.base !== unit.lifecycle.workspace.baseSha || !Array.isArray(unit.lifecycle.resources)) {
90
+ throw new Error('not an owned standalone native run; refusing to replace its record')
91
+ }
92
+ git(repo, 'check-ref-format', '--branch', plan.targetBranch)
93
+ git(repo, 'check-ref-format', '--branch', unit.branch)
94
+ noLinks(repo, unit.workspace)
95
+ return unit
96
+ }
97
+
98
+ function relativePath(value, label, allowRoot = false) {
99
+ if (allowRoot && value === '.') return value
100
+ if (typeof value !== 'string' || !value || isAbsolute(value) || value.includes('\\') || /[\0*?\[\]]/.test(value) ||
101
+ value.split('/').some((part) => !part || part === '.' || part === '..' || part === '.git' || part === '.resolve-issues')) {
102
+ throw new Error(`${label} must be an exact relative path without .., symlinks, or managed roots`)
103
+ }
104
+ return value
105
+ }
106
+
107
+ function resourcePaths(repo, workspace, platform, nativeDir, disposable) {
108
+ relativePath(nativeDir, '--native-dir', true)
109
+ if (!Array.isArray(disposable)) throw new Error('disposable must be an array of workspace-relative paths')
110
+ const paths = [...new Set(['.cache', 'node_modules',
111
+ ...(platform === 'ios' ? ['ios/Pods'] : ['android/.gradle', 'android/build', 'android/app/build']).map((path) => nativeDir === '.' ? path : `${nativeDir}/${path}`),
112
+ ...disposable.map((path) => relativePath(path, '--disposable'))])]
113
+ noLinks(repo, join(repo, nativeDir))
114
+ noLinks(repo, join(workspace, nativeDir))
115
+ for (const path of paths) {
116
+ noLinks(repo, join(repo, path))
117
+ noLinks(repo, join(workspace, path))
118
+ }
119
+ return paths
120
+ }
121
+
122
+ function engine(args, repo) {
123
+ const result = spawnSync(process.execPath, [cli, ...args, '--json'], { cwd: repo, encoding: 'utf8', timeout: 120_000, maxBuffer: 8 * 1024 * 1024 })
124
+ let value
125
+ try { value = JSON.parse(result.stdout) } catch { /* Report the failed command below. */ }
126
+ if (result.status === 0 || (result.status === 1 && value?.action === 'retain' && (value.lifecycle || value.nextLifecycle))) return value
127
+ throw new Error(result.stderr?.trim() || result.stdout?.trim() || result.error?.message || 'workspace operation failed')
128
+ }
129
+
130
+ function returnedLifecycle(result) {
131
+ const lifecycle = result?.lifecycle ?? result?.nextLifecycle
132
+ if (!lifecycle || lifecycle.version !== 1) throw new Error('workspace helper returned no lifecycle transition; the recorded intent remains recoverable')
133
+ return lifecycle
134
+ }
135
+
136
+ export function nativeStart({ repo: input, runId, base, branch, target, platform, kind, nativeDir, disposable = [] }) {
137
+ if (!input || !['android', 'ios'].includes(platform) || (kind !== undefined && !['worktree', 'clone'].includes(kind))) throw new Error('native-start requires --repo and --platform android|ios; --kind is worktree or clone')
138
+ const repo = realpathSync(resolve(input))
139
+ if (realpathSync(git(repo, 'rev-parse', '--show-toplevel')) !== repo) throw new Error('--repo must name the owning checkout root')
140
+ const id = runId ?? `native-${new Date().toISOString().replace(/[^0-9]/g, '')}-${process.pid}`
141
+ if (!component(id)) throw new Error('invalid native run id')
142
+ const run = join(repo, '.resolve-issues', 'rush', id)
143
+ return withOwner(repo, run, () => {
144
+ const store = planStore(repo, run)
145
+ let plan = store.plan
146
+ if (!plan && stat(run)) throw new Error('existing run has no ownership record; refusing to adopt it')
147
+ let unit
148
+ if (plan) {
149
+ unit = ownedPlan(plan, repo, run)
150
+ if ((base !== undefined && git(repo, 'rev-parse', '--verify', `${base}^{commit}`) !== unit.base) ||
151
+ (target !== undefined && target !== plan.targetBranch) || (kind !== undefined && kind !== unit.lifecycle.workspace.kind) ||
152
+ (branch !== undefined && branch !== unit.branch) || (nativeDir !== undefined && nativeDir !== (unit.nativeDir ?? '.'))) {
153
+ throw new Error('existing native run belongs to a different setup; refusing to replace it')
154
+ }
155
+ nativeDir = unit.nativeDir ?? '.'
156
+ } else {
157
+ const baseSha = git(repo, 'rev-parse', '--verify', `${base ?? 'HEAD'}^{commit}`)
158
+ if (!target) {
159
+ try { target = git(repo, 'symbolic-ref', '--short', 'refs/remotes/origin/HEAD').replace(/^origin\//, '') } catch { throw new Error('record the repository target branch with --target; origin/HEAD is unavailable') }
160
+ }
161
+ branch ??= `native/${id}`
162
+ kind ??= 'worktree'
163
+ nativeDir ??= '.'
164
+ git(repo, 'check-ref-format', '--branch', target)
165
+ git(repo, 'check-ref-format', '--branch', branch)
166
+ unit = { id: 'native', title: 'Standalone native setup', workspace: join(run, 'units', 'native'), branch, base: baseSha, nativeDir, disposable: [], status: 'in-flight', stage: 'implement', worker: null,
167
+ lifecycle: { version: 1, workspace: { kind, state: 'preparing', baseSha }, resources: [], cleanup: { state: 'pending' } } }
168
+ plan = { skill: 'native-setup', workspaceLifecycle: 1, repoRoot: repo, runDir: run, targetBranch: target, planRevision: 0, units: [unit] }
169
+ }
170
+ if (unit.lifecycle.cleanup?.state === 'complete') throw new Error('this setup was cleaned; start a new run rather than recreating a used workspace')
171
+ if (!Array.isArray(disposable) || (unit.disposable !== undefined && !Array.isArray(unit.disposable))) throw new Error('disposable must be an array of workspace-relative paths')
172
+ const extras = [...new Set([...(unit.disposable ?? []), ...disposable])]
173
+ const paths = resourcePaths(repo, unit.workspace, platform, nativeDir, extras)
174
+ let changed = !store.plan || unit.nativeDir === undefined || JSON.stringify(unit.disposable) !== JSON.stringify(extras)
175
+ unit.nativeDir = nativeDir
176
+ unit.disposable = extras
177
+ for (const item of paths) {
178
+ const path = join(unit.workspace, item)
179
+ if (unit.lifecycle.resources.some((r) => r.path === path)) continue
180
+ unit.lifecycle.resources.push({ path, role: 'scratch', kind: 'directory', disposable: true, state: 'preparing' })
181
+ changed = true
182
+ }
183
+ if (!store.plan) mkdirSync(run)
184
+ if (changed) store.save(plan)
185
+ const result = engine(['prepare', '--run', run, '--unit', 'native', '--revision', String(plan.planRevision), '--apply'], repo)
186
+ unit.lifecycle = returnedLifecycle(result)
187
+ store.save(plan)
188
+ return { ...result, run, runId: id, workspace: unit.workspace, nativeDir, disposable: extras, sourceSha: git(unit.workspace, 'rev-parse', 'HEAD'), planRevision: plan.planRevision }
189
+ })
190
+ }
191
+
192
+ export function nativeFinish({ run: input }) {
193
+ if (!input) throw new Error('native-finish requires --run')
194
+ const run = resolve(input)
195
+ const repo = realpathSync(join(run, '..', '..', '..'))
196
+ if (!component(basename(run)) || run !== join(repo, '.resolve-issues', 'rush', basename(run))) throw new Error('not an owned standalone native run')
197
+ noLinks(repo, run)
198
+ if (!stat(run)?.isDirectory()) throw new Error('native run does not exist')
199
+ return withOwner(repo, run, () => {
200
+ const store = planStore(repo, run)
201
+ const plan = store.plan
202
+ const unit = ownedPlan(plan, repo, run)
203
+ // Completed and interrupted removals still go through the engine's postcondition
204
+ // checks, including owned resources outside the workspace and cleanup receipts.
205
+ const completeCleanup = () => {
206
+ const result = engine(['cleanup', '--run', run, '--unit', 'native', '--revision', String(plan.planRevision), '--apply'], repo)
207
+ const lifecycle = returnedLifecycle(result)
208
+ if (result.ok !== false && (lifecycle.cleanup?.state !== 'complete' || existsSync(unit.workspace) || lifecycle.resources.some((r) => existsSync(r.path)))) {
209
+ throw new Error('cleanup has not reached its postconditions; the recorded intent remains recoverable')
210
+ }
211
+ unit.lifecycle = lifecycle
212
+ store.save(plan)
213
+ return { ...result, run, planRevision: plan.planRevision }
214
+ }
215
+ if (unit.lifecycle.cleanup?.state === 'complete' || (!existsSync(unit.workspace) && unit.lifecycle.cleanup?.state === 'applying')) return completeCleanup()
216
+ const headSha = git(unit.workspace, 'rev-parse', 'HEAD')
217
+ const remote = git(repo, 'remote', 'get-url', 'origin')
218
+ git(unit.workspace, 'fetch', '--no-tags', '--', remote, `+refs/heads/${plan.targetBranch}:refs/remotes/native-delivery/${plan.targetBranch}`)
219
+ const targetRef = `refs/remotes/native-delivery/${plan.targetBranch}`
220
+ let landed = false
221
+ try { git(unit.workspace, 'merge-base', '--is-ancestor', headSha, targetRef); landed = true } catch (error) {
222
+ if (error.status !== 1) throw error
223
+ }
224
+ if (!landed) {
225
+ unit.headSha = headSha
226
+ const reason = 'native source has not landed on the recorded remote target; retain its environment'
227
+ unit.lifecycle.cleanup = { state: 'retained', headSha, reason }
228
+ store.save(plan)
229
+ return { ok: false, action: 'retain', outcome: 'retained', reason, run, lifecycle: unit.lifecycle, planRevision: plan.planRevision }
230
+ }
231
+ unit.headSha = headSha
232
+ unit.mergeSha = headSha
233
+ unit.status = 'succeeded'
234
+ unit.delivery = 'merged'
235
+ unit.lifecycle.cleanup = { state: 'applying', headSha }
236
+ store.save(plan)
237
+ return completeCleanup()
238
+ })
239
+ }
@@ -0,0 +1,78 @@
1
+ # Owned Workspaces
2
+
3
+ The same lifecycle engine serves `resolve-issues` and standalone native setup.
4
+ It creates one recorded workspace, reuses it, and removes only owned, delivered,
5
+ idle environments. It never deletes legacy project folders by age or naming pattern.
6
+
7
+ ## Assigned Work
8
+
9
+ An orchestrator supplies its prepared workspace and candidate SHA. Use both as
10
+ given. Do not run `native-start` inside an assigned unit, create a second checkout,
11
+ switch branches or reset the source. Return resource paths to that orchestrator;
12
+ only it writes its task plan and decides when delivery permits cleanup.
13
+
14
+ Keep mutable caches private and declare their exact disposable paths before use.
15
+ An ignored file is not automatically disposable. Shared SDKs and other projects
16
+ are never owned resources of a unit.
17
+
18
+ ## Standalone Setup
19
+
20
+ Resolve this installed runtime from the caller's selected installation, not a
21
+ filesystem search or another cached version. With no assigned or existing owned
22
+ workspace, run:
23
+
24
+ ```bash
25
+ node <harness-runtime>/bin/workspaces.mjs native-start --repo <canonical-repo-root> \
26
+ --platform android --target <verified-target-branch> --base <candidate-SHA> --json
27
+ ```
28
+
29
+ For iOS, use `--platform ios`. For a kernel-confined Git-mutating worker, choose
30
+ `--kind clone` before preparing; never disable confinement to use a linked tree.
31
+ For a native package below the root, pass `--native-dir apps/native` (the package
32
+ root containing `ios/` or `android/`). Register other outputs before installation
33
+ with repeated `--disposable <workspace-relative-directory>`, including every
34
+ package-local `node_modules` directory the install will create. No glob discovery
35
+ or ignored-file heuristic establishes disposal authority.
36
+ The owner root can remain dirty: creation uses the recorded commit, not its local
37
+ uncommitted files. The command does not fetch or change the owner checkout.
38
+
39
+ Read the JSON result. `run`, `runId`, `workspace`, `sourceSha`, and `planRevision`
40
+ identify the assignment. Pass `workspace` and `sourceSha` to native setup. Reuse
41
+ the returned `runId` with `--run-id` and the same base, target and kind for retries
42
+ and for adding the other platform to the same unit. Never create a run per attempt.
43
+
44
+ `native-start` records intent in
45
+ `<repo>/.resolve-issues/rush/<run-id>/task-plan.json` before preparation. That small
46
+ record is the standalone owner's authority, not a second manifest for an issue
47
+ workflow. The command records the workspace and platform-specific disposable
48
+ caches, then persists the lifecycle engine's returned identities. A conflicting
49
+ or missing previously used workspace is reported, never reset or recreated.
50
+
51
+ ## Finish And Recover
52
+
53
+ Stop the assignment's native services, devices and containers through their own
54
+ owners, then run from the owner checkout, not the workspace being removed:
55
+
56
+ ```bash
57
+ node <harness-runtime>/bin/workspaces.mjs native-finish --run <returned-run-path> --json
58
+ ```
59
+
60
+ The source must be on the recorded remote target. Dirty source, unpublished work,
61
+ unknown ignored files, required evidence inside a disposable path, or live use
62
+ retains the complete environment with a reason. A successful removal preserves
63
+ the small plan and cleanup receipt; it does not leave installed dependencies and
64
+ build caches. Retention is not successful cleanup. Keep the returned record and
65
+ report its reason without inventing a passing validation result.
66
+
67
+ An interrupted operation remains in the same plan. Inspect it without deleting:
68
+
69
+ ```bash
70
+ node <harness-runtime>/bin/workspaces.mjs recover --repo <canonical-repo-root> --json
71
+ node <harness-runtime>/bin/workspaces.mjs inventory --repo <canonical-repo-root> \
72
+ --root <explicit-legacy-workspace-root> --max-entries 5000 --max-depth 8 --json
73
+ ```
74
+
75
+ Discovery does not activate a workflow, adopt a legacy directory or authorize
76
+ deletion. Never turn an unknown or missing path into a completed cleanup result.
77
+ Standalone commands hold a per-run owner lock across plan updates and engine calls;
78
+ they refuse concurrent owners and never reclaim an unknown lock by age.