diff --git a/.gitignore b/.gitignore index e113ead..ea386f5 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,15 @@ docs/ROADMAP.md docs/ENGINEERING_CONCEPTS.md docs/SPEC.md docs/HANDOVER_V3.md +docs/B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md +docs/MILESTONE_7_VALIDATION.md +docs/ONBOARDING_DEEP_GUIDE_PLAN.md +docs/ONBOARDING_DEPTH_BASELINE.md +docs/ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md +docs/ONBOARDING_HUMAN_STORY_PLAN.md +docs/ONBOARDING_PHASE6_ACCEPTANCE.md +docs/ONBOARDING_V2.md +docs/ONBOARDING_V2_DEBTBOX_FIXTURE.md # Local TransferKit state .transferkit.local/ diff --git a/README.md b/README.md index 06b1c59..6b32e13 100644 --- a/README.md +++ b/README.md @@ -1,67 +1,100 @@ # TransferKit -> Engineering handover and onboarding from real repository evidence. +> Make software ownership transfer easier to inspect, discuss, and continue. [![npm version](https://img.shields.io/npm/v/transferkit.svg)](https://www.npmjs.com/package/transferkit) [![CI](https://github.com/alialaraby/transferkit/actions/workflows/ci.yml/badge.svg)](https://github.com/alialaraby/transferkit/actions/workflows/ci.yml) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE) [![Node.js 18+](https://img.shields.io/badge/node-%3E%3D18-339933?logo=node.js&logoColor=white)](package.json) -TransferKit is a local-first CLI for structured software ownership transfer. It discovers supported system components, records evidence, and turns structured project state into practical handover and onboarding workflows. +TransferKit is a local-first CLI for engineering handover and developer onboarding. It reads a repository, records cited findings, and helps people turn those findings into a shared ownership plan and a personal learning path. It does not run the target application or infer business meaning from code alone. -Software ownership transfers often fail because repository facts, operational context, and a new owner's learning progress are mixed together in documents that quickly become stale. TransferKit separates them: +- **Handover** helps the current and next owners agree on what must be explained, verified, transferred, and followed up. Structured state in `.transferkit/transfer.json` drives an editable `HANDOVER.md` checklist. +- **Onboarding** creates a shared `ONBOARDING.md` that introduces the repository, its important code terms, selected entry paths, change points, and setup clues. Each newcomer records their own progress in `.transferkit.local/ONBOARDING.md`. -- **Handover** builds a shared ownership-transfer plan: what the next owner needs to learn, do, verify, and take over. -- **Onboarding** creates a personal learning plan from repository evidence and available handover knowledge. Personal progress stays local and is not shared as project state. - -Its current ecosystem support focuses on Node.js and TypeScript backends, with deeper detection for NestJS, RabbitMQ, scheduled jobs, PostgreSQL/TypeORM, outbound HTTP integrations, environment configuration, Docker, and GitHub Actions. +The scanners currently have their deepest coverage for Node.js and TypeScript backends, including NestJS routes, scheduled work, RabbitMQ and BullMQ declarations, TypeORM, integrations, configuration, Docker, and GitHub Actions. A JavaScript or Python repository can still get a documented overview and entry points; unsupported inner behavior is labeled as a gap. ## Install +Node.js 18 or newer is required. + ```bash npm install --global transferkit +tk --help ``` -Node.js 18 or newer is required. After installation, run `tk --help` to see the available commands. +Run TransferKit **from the root of the repository you want to examine**. Use `tk handover --help` or `tk onboard --help` for command syntax. -## Quick start - -Run these commands from the repository being transferred: +## Handover: build a shared ownership plan ```bash -tk handover init -tk handover scan +cd /path/to/your/repository tk handover plan -# Review and edit HANDOVER.md in your IDE +# Review the suggested item IDs and edit HANDOVER.md with your team. tk handover sync tk handover status +``` + +`handover plan` scans the repository, creates or refreshes suggestions in `.transferkit/transfer.json`, and generates `HANDOVER.md` if it does not exist. The plan lists ownership topics with priority and completion rules. Review each suggestion with a person who knows the system; evidence helps start the conversation but does not certify an answer. The command preserves an existing `HANDOVER.md` so your edits are not overwritten. + +The checklist is useful in a handover meeting: mark what was covered, add notes and evidence, then run `handover sync` to import supported edits into structured state. `handover status` shows what remains open. For a closer look at scanner findings, run `tk handover evidence`. + +| Command | When to use it | +| --- | --- | +| `tk handover plan` | Create or refresh suggestions and the shared checklist. | +| `tk handover plan accept ` / `reject ` | Decide whether a suggested item belongs in this handover. | +| `tk handover plan rename ` | Give an item a name the team recognizes. | +| `tk handover plan priority <item-id> <CRITICAL\|RECOMMENDED\|OPTIONAL>` | Change the review order. | +| `tk handover plan move <item-id> <section-id> <position>` | Move an item within the plan. | +| `tk handover plan add <section-id> <type> <priority> <title>` | Add a missing human-owned topic. | +| `tk handover sync` / `status` | Import checklist edits and inspect progress. | +| `tk handover scan` / `evidence` | Refresh suggestions without opening a new checklist, or print cited findings. | + +`tk handover init` creates optional `.transferkit/project.yaml` metadata. `handover plan` can create its own structured plan without this step. +## Onboarding: learn the repository + +```bash +cd /path/to/your/repository +tk onboard guide +tk onboard workspace tk onboard plan +# Read ONBOARDING.md and record findings in .transferkit.local/ONBOARDING.md. +tk onboard task v2:trace-flow in-progress +tk onboard sync tk onboard status ``` -`handover scan` refreshes suggestions in `.transferkit/transfer.json`. `handover plan` creates or reviews the plan and generates root-level `HANDOVER.md`. Edit its checkboxes and supported fields, then run `handover sync` and `handover status`. Use `handover evidence` to inspect repository findings when needed. +The shared guide starts with what the repository says it does, or a clearly labeled source-level reading path when that purpose is undocumented. It then points to a small glossary, separate code journeys, likely change and test locations, and safe setup observations. Source links let you check each claim. Detailed traces remain in a collapsed appendix; a cited write call is not proof that a transaction completed. -To update personal onboarding progress: +Use `tk onboard guide --focus OrderController.submit` to regenerate the guide around a supported route or symbol. `tk onboard workspace` creates a **personal** checklist only once; it will not overwrite existing notes. A completed checkbox is self-reported progress. If the selected guide paths change later, `tk onboard plan` and `status` warn about stale links while keeping the newcomer's progress and notes. -```bash -tk onboard task <task-id> in-progress -tk onboard task <task-id> completed -``` +| Command | When to use it | +| --- | --- | +| `tk onboard guide [--focus <route-or-symbol>]` | Generate or update the shared, source-cited guide. | +| `tk onboard workspace` | Create a personal learning checklist from the guide. | +| `tk onboard plan` | See the next reading and investigation exercises. | +| `tk onboard task <v2-id> <status>` | Record `not-started`, `in-progress`, `completed`, or `skipped`. | +| `tk onboard sync` / `status` | Import checkbox edits and see progress, questions, and stale links. | -See the [workflow example](examples/workflow.md) for representative output and [getting started](docs/getting-started.md) for a fuller walkthrough. +Documented commands in a generated guide are **not verified runs**. Check prerequisites before using them, record the actual result or blocker, and ask an owner when business intent or operating procedures are absent from the repository. -## What's new in 0.2.0 +## Release notes — 0.3.0 candidate -Handover v3 adds a shared ownership-transfer plan, a meeting-ready `HANDOVER.md` checklist, deterministic suggestions from repository evidence, and Markdown sync. See the [release notes](packages/cli/CHANGELOG.md) for details and compatibility notes. +- Onboarding guides now lead with a source-backed repository story, a compact glossary, separate selected journeys, a task-to-file map, and a safe first investigation. Raw traces remain available for deeper review. +- Personal onboarding exercises follow that reading path and keep their stable IDs, checkboxes, questions, notes, and evidence when the shared guide changes. +- Handover retains the structured v3 ownership plan, evidence-backed suggestions, editable meeting checklist, and Markdown sync introduced in 0.2.0. +- Long repository scans and guide generation now show a terminal progress indicator in interactive terminals. Redirected output stays clean. -## Local-first and private by default +See the [package changelog](packages/cli/CHANGELOG.md) for compatibility details. This release candidate has not been merged or published. -TransferKit scans files and computes results locally. It does not make implicit AI or network calls, and it does not upload source code. Shared state lives in `.transferkit/`; personal onboarding progress lives in Git-ignored `.transferkit.local/`. Environment detection records variable names, not values. +## Files, privacy, and limits -Review generated handover files before committing them. Automated secret protection is deliberately lightweight and is not a replacement for repository secret scanning. +Shared handover state lives in `.transferkit/`; personal onboarding progress lives in `.transferkit.local/`. Add `.transferkit.local/` to the target repository's `.gitignore` to keep personal notes private. Generated Markdown is a view over structured state for handover and a cited output for onboarding. TransferKit does not upload source code or make implicit AI or network calls. Configuration discovery records variable names, not values. -## Documentation +Detection is deterministic and limited to supported static patterns. Dynamic targets, runtime effects, and business meanings may need a person to verify them. Review shared generated files before committing them; the built-in secret checks are lightweight and do not replace repository secret scanning. + +## More documentation - [Getting started](docs/getting-started.md) - [Concepts](docs/concepts.md) @@ -69,13 +102,4 @@ Review generated handover files before committing them. Automated secret protect - [Scanner development](docs/scanners.md) - [Contributing](CONTRIBUTING.md) -## Current limitations - -- Detection is deterministic and limited to supported static patterns. -- Dynamic configuration, computed decorator metadata, and runtime-only behavior may not be discovered. -- Evidence inspection performs a fresh scan rather than reading a persisted evidence index. -- State migrations have an explicit boundary, but no historical migrations exist yet because schema version 1 is the first format. - -## Project status - -TransferKit is early-stage software. State formats and commands may evolve before a stable release. Feedback and focused contributions are welcome through GitHub issues and pull requests. +TransferKit is early-stage software. State formats and commands may evolve before a stable release. diff --git a/docs/MILESTONE_7_VALIDATION.md b/docs/MILESTONE_7_VALIDATION.md deleted file mode 100644 index d7a9a2f..0000000 --- a/docs/MILESTONE_7_VALIDATION.md +++ /dev/null @@ -1,89 +0,0 @@ -# Milestone 7 Validation - -Date: 2026-09-24 - -## Coverage re-audit — 2026-09-27 - -The coverage behavior below supersedes the earlier coverage findings in this document. Milestone 7 remains open; the real Debtbox acceptance test has not been run. - -| Area | Result | Current evidence and limit | -| --- | --- | --- | -| Requirement-based coverage | PARTIAL | The plan now separates recorded HUMAN knowledge from coverage. Free-form requirements need an explicit confirmation stored by requirement ID; repository requirements require matching OBSERVED evidence. INFERRED evidence remains uncovered. This is an honest assertion by the outgoing engineer, not semantic proof that the prose is useful. Existing legacy interview answers remain recorded but unconfirmed. | -| Guided workflow | PARTIAL | Numbered answers can be saved without coverage; one confirmation can cover a grouped answer. A later `confirm` action shows saved notes and supports resume. Status repeats incomplete topics, and session progress counts topics addressed separately from coverage. Generic prompt wording and fatigue on a large backend remain untested. | -| Knowledge classification | PARTIAL | OBSERVED, INFERRED, HUMAN, and UNKNOWN remain distinct. Matching observations can establish coverage; inferred identity is shown as unconfirmed. Human notes require an explicit sufficiency decision. | -| Critical business flows | PARTIAL | Suggested flows stay unconfirmed until the maintainer accepts them. A confirmed or manual flow needs purpose, entry point, main path, business rules, failure paths, and retry/recovery, each documented and explicitly confirmed. Every confirmed flow gets its own critical handover requirement, so one complete flow does not hide another incomplete flow. The tool cannot judge the semantic accuracy of confirmed details. | -| Handover Audit v2 | PARTIAL | Audit, status, export, and gap counts consume the same plan coverage. Audit labels saved but unconfirmed knowledge; export labels its maintainer notes as coverage incomplete. Real engineer trust and receiver usefulness remain unvalidated. | - -Validation: 142 tests passed across 36 files; typecheck, lint, format check, and Node 25 build passed. A bundled CLI smoke test on a temporary copy of `fixtures/realistic-nestjs` confirmed that a saved unconfirmed answer remains a critical gap, then confirmation closes that requirement and export shows the maintainer note. The earlier 132-test count and piped-input failure below describe the 2026-09-24 snapshot, not this re-audit. - -## Decision - -**Milestone 7 remains open.** The implementation passes automated checks and a realistic fixture can complete the CLI workflow in an interactive terminal. Several core behaviors are only partial. The roadmap also explicitly requires a handover on Debtbox or another backend that its outgoing engineer knows deeply, followed by that engineer's trust judgment. Neither happened in this audit. `Run Milestone 7 acceptance test` remains unchecked. - -The statuses below assess behavior, independently of the existing implementation checkmarks in `docs/ROADMAP.md`. - -## Implementation checklist audit - -| Checklist item | Result | Concrete evidence and limit | -| --- | --- | --- | -| Handover Standard v2 | PASS | `handover-standard-v2.ts` defines all 24 roadmap areas and critical, recommended, and optional requirements without framework dependencies; `handover-standard-v2.test.ts` checks composition. Individual areas are broad, but the standard is a coverage model rather than a questionnaire. | -| Adaptive handover planning | PARTIAL | `adaptive-handover-plan.ts` combines the standard, findings, saved knowledge, flows, and custom topics; its tests show conditional activation and retained answers. Adaptation is concentrated in messaging, jobs, integrations, and data. It does not model payment-specific callback/reconciliation topics or reprioritize broad areas from evidence. | -| Guided handover workflow | PARTIAL | `guided-handover.ts` and `guided-handover.test.ts` cover start, next, status, resume, skip, and grouped notes. On the fixture, `next` presented a generic “Why it matters” sentence and Architecture showed package/framework evidence before the module finding because it takes the first five references. A note is copied to every requirement in its group without checking whether it covers each one. Piped input to the bundled CLI failed with `Error: readline was closed`; interactive terminal input worked. | -| Requirement-based coverage | PARTIAL | `handover-plan.ts` and `handover-coverage.ts` deterministically count covered, missing, skipped, not applicable, and gaps by priority; tests pass. Because one grouped answer can cover several requirements regardless of its content, counts can overstate actual knowledge transfer. | -| Knowledge classification | PARTIAL | `handover-plan.ts` supports OBSERVED, INFERRED, HUMAN, and UNKNOWN and distinguishes evidence from answers. Observed cadence/endpoint facts suppress those prompts. `semantic-integrations.ts` can classify provider identity as INFERRED, but that inference is not passed to plan observations or shown as an unconfirmed fact in the guided workflow. | -| Repository context | PARTIAL | `handover-context.ts` detects entry points, modules, controllers/routes, services, guards, relations, and log calls, with a focused test; existing scanners supply jobs, messaging, configuration, and deployment files. The fixture's Architecture prompt displayed five generic package/framework references and hid the `AppModule` reference, so relevant project structure did not consistently reach the engineer. | -| Semantic external integrations | PARTIAL | `semantic-integrations.ts` groups by SDK service, static host, or inferred configuration/class name, with explicit unknown identity and grouping tests. The fixture export used `partner.example.test`, never axios/fetch, but provider purpose remains unknown; authentication evidence and related modules are only shallowly derived and are not rendered as a useful integration profile. Repeated call-site evidence fills many topic entries. | -| Critical business flows | PARTIAL | `business-flow.ts`, `business-flows.ts`, and their tests support suggested/manual flows, confirm, rename, ignore, and incremental field documentation. Fixture suggestions were generic consumer/job method names. The base “Critical flows and failure paths” requirement can be answered and marked covered without confirming or documenting any structured flow. No end-to-end business relationship is inferred. | -| Incremental handover sessions | PASS | `handover-state.ts` persists active/paused state, current topic ID, and addressed IDs. `guided-handover.test.ts` covers pause, rescan, and resume; an interactive fixture run paused and resumed on `system-overview.purpose`, then advanced to Architecture. Piped input remains a CLI input limitation. | -| Custom topics | PASS | `addGuidedTopic` persists topics; the planner links them to knowledge; status/audit/export include them. `adaptive-handover-plan.test.ts` and `guided-handover.test.ts` cover the path. | -| Handover Export v2 | PARTIAL | `handover-package-v2.ts` and export tests produce ownership-oriented pages, observed facts, maintainer notes, evidence, gaps, and a single-file version. After one fixture note, the package had 6/46 covered requirements; `remaining-gaps.md` was 112 lines of the 287-line multi-file package. Integration and async pages repeat evidence for unanswered topics, and sections without knowledge/evidence are omitted. Receiver usefulness has not been tested. | -| Handover Audit v2 | PARTIAL | `handover-coverage-audit.ts` groups by area, prioritizes critical gaps, and labels covered, missing human knowledge, missing repository context, skipped, and not applicable; renderer and CLI tests pass. It inherits the grouped-answer overcount, so a “covered” label need not mean the note substantively answers the requirement. | - -## Product behavior audit - -A temporary copy of `fixtures/realistic-nestjs` was the strongest realistic fixture available. It is a small NestJS shipment service, not a production backend. The bundled CLI ran `handover init`, `scan`, `start`, `status`, `next`, `audit`, `flow list`, and both multi-file and single-file `export`. Interactive `next` saved and `resume` restored a paused session. The original fixture and external repositories were untouched. - -| Product question | Result | Fixture observation | -| --- | --- | --- | -| Major areas identified? | PASS | `start` listed 24 standard areas even though scanning found only 19 findings. | -| Sensible order? | PARTIAL | System Overview then Architecture followed critical-first order; the order is mechanical by area and priority, with no maintainer assessment. | -| Important categories prevented from being forgotten? | PARTIAL | Business domains, flows, failure/recovery, ownership, and tribal knowledge remain in the plan. Broad one-line requirements may miss important subtopics. | -| Project-specific repository context? | PARTIAL | Jobs, RabbitMQ, partner host, and Docker appeared; Architecture's first five references were package/framework facts, while `AppModule` was hidden in the prompt. | -| Observable facts not re-asked? | PARTIAL | Cron cadence, consumer name, HTTP operation, endpoint, and database technology were OBSERVED. Broad architecture/codebase prompts still ask for explanations despite related evidence, which may be useful but is not narrowly targeted. | -| Semantic integrations? | PARTIAL | Export used `partner.example.test`, not transport libraries. It did not establish a human-readable provider name or purpose. | -| Critical flows capturable? | PARTIAL | Consumer and job suggestions exist and manual flow capture is tested. The initial flow requirement can be marked covered without a documented flow. | -| Incremental completion? | PASS | Interactive `save` set `Session: paused`; `resume` accepted a note and status showed `Session: active · 1 topics addressed`, with Architecture next. | -| Critical gaps obvious? | PASS | Fixture audit showed 28 critical, 11 recommended, and 1 optional gap after the note, grouped by area. | -| Export useful to receiver? | PARTIAL | The package conveys a maintainer overview and source references, but at this stage it mostly conveys unanswered topics and repeated evidence. No receiver reviewed it. | - -## Old failure modes - -| Failure mode | Result | Audit finding | -| --- | --- | --- | -| Handover mainly structured around scanner entities | PARTIAL | Top-level plan is standard-led, but conditional areas generate per-consumer, per-job, and per-integration requirements. | -| Axios/fetch shown as integrations | PASS | Provider subject was `partner.example.test`; no axios/fetch labels appeared in the exported package. Legacy persisted scanner entities can still name `NestJS HttpService`, but guided plan/export do not use that as the provider. | -| Generic repeated questions | PARTIAL | One grouped prompt avoids one question per field, yet the “Why it matters” text is generic and evidence repeats across related requirements. | -| Humans asked for observable facts | PARTIAL | Several facts are observed and suppressed; broad topics can still ask the engineer to explain areas for which partial code context exists. | -| Flat technology inventory presented as system understanding | PARTIAL | The system overview contains the maintainer note, but also a simple `NestJS, RabbitMQ, PostgreSQL` technology list with no interpreted relationships. | -| Export dominated by “Missing critical” | PARTIAL | The literal phrase is absent and topic pages include known facts; `remaining-gaps.md` is 112/287 lines after one note, and evidence-only entries repeat heavily. | -| No clear handover order | PASS | `start` names a beginning and `status` names the next area; `next` selects critical requirements first. | -| No practical resume/session behavior | PASS | Interactive terminal pause/resume persisted correctly across processes. Piped answers failed; see limitations. | - -## Validation commands and results - -- `npm test`: **132 passed across 36 files**. -- `npm run typecheck`: **passed**. -- `npm run lint`: **passed**. -- `npm run format:check`: **passed**. -- `PATH=/opt/homebrew/bin:$PATH npm run build`: **passed** using installed Node.js 25; bundle created at `packages/cli/dist/index.js`. The repository requires Node.js 24 or newer. -- Bundled CLI on a temporary fixture copy: `init`, `scan`, `start`, `status`, `audit`, `flow list`, multi-file `export`, and `export --single` succeeded. `next`/`resume` worked through an interactive terminal. Piping answers to `next`/`resume` failed with `Error: readline was closed`, leaving the session active; this was observed, not fixed during this audit. - -## Remaining work before acceptance - -1. Prevent a broad or grouped note from automatically counting unrelated requirements as covered; make the coverage claim defensible without turning guidance into a giant questionnaire. -2. Ensure confirmed or manual critical flows, with enough actual business detail, are required before flow coverage is treated as complete. Improve suggested starting points beyond generic method names where deterministic relationships exist. -3. Surface the most relevant structural evidence first and present integration identity, operations, configuration, and authentication context without repeated evidence-only sections. Carry inferred facts into the plan as unconfirmed. -4. Review export with a receiving engineer and refine pages that convey mostly gaps or repeated references. -5. Run the roadmap acceptance test on Debtbox or another backend with its outgoing engineer. Compare the guide with that engineer's own handover list, capture missed areas and false coverage, and ask the roadmap trust question directly. This manual experiment is the final gate; the green fixture checks do not replace it. - -The old `tk handover interview` command and entity-oriented state remain for compatibility. The guided commands, audit, and export use the v2 plan; the legacy path was not removed in this audit. diff --git a/docs/ONBOARDING_V2.md b/docs/ONBOARDING_V2.md deleted file mode 100644 index e5d2fb1..0000000 --- a/docs/ONBOARDING_V2.md +++ /dev/null @@ -1,39 +0,0 @@ -# Onboarding v2 — Product and Design Specification - -**Status: design target, with Milestone 9 slices in progress.** The maintainer has confirmed that Handover v3 passed its Debtbox Current Owner validation gate. The [illustrative Debtbox fixture](ONBOARDING_V2_DEBTBOX_FIXTURE.md) defines the desired reading experience; it is not current CLI output. - -## Goal and modes - -Help an engineer unfamiliar with a repository discover its structure, trace meaningful behavior, try to run and change it, and record what remains unknown. **Repository-only onboarding is a complete independent workflow**: scanning, the reusable guide, exercises, personal progress, and visible unknowns work without a handover file or a Current Owner. Missing handover must never block guide creation or turn repository findings into invented human context. - -When a v3 Transfer is available, selected Handover Items may **enrich** the same journey. Link each related item by its stable item ID, retain its provenance and current status, and show relevant person-supplied context alongside repository evidence. An item can add business intent, operational steps, ownership, risks, or open questions; it cannot silently override observed code. Unrelated, incomplete, or absent items leave the repository-only guide usable. Handover completion and personal learning completion remain independent. - -## Two Markdown surfaces and state - -- Root `ONBOARDING.md` is the reusable, team-shareable **system guide**. It explains what the repository supports and where to investigate. Stable section anchors let people link to the same architecture, flow, operations, and unknowns sections. It contains no personal progress or private notes. It is reviewable through Git. -- `.transferkit.local/ONBOARDING.md` is each engineer's **personal workspace**: outcome-based exercises, checkboxes, notes, questions, and evidence of work. Each exercise links to a guide section; it does not copy the entire guide. It remains local and uncommitted by default. -- Personal structured state under `.transferkit.local/` holds stable exercise IDs, status, evidence references, and the synchronization snapshot needed to reconcile Markdown edits. The personal Markdown workspace is editable, not a disposable export. Checkbox changes and CLI progress changes synchronize in both directions. Preserve free-form prose and unknown sections. If both representations edit the same supported field differently, surface a conflict with both values and require an explicit resolution; never silently overwrite either side. A rescan must preserve personal work even if a suggested exercise disappears, and should expose stale links. -- The guide's generated portions come from repository evidence and optional linked Transfer context. Human edits to a shared guide require a preservation/reconciliation policy before implementation; regeneration must not erase prose silently. - -## Content and evidence contract - -The guide should start with a concise system overview, entry point, major modules, data stores, integrations, background work, and important architecture relationships. Show a **few explained end-to-end flows**, chosen for learning value, with entry point, validation/decisions, persistence, side effects, and possible gaps. Describe setup and operations from checked-in evidence, and keep unknowns prominent. Avoid flat dependency lists and unsupported call graphs. - -Every material statement should carry a source label: **observed in code**, **inferred**, **supplied by a person**, or **runtime unverified**. Observed claims cite repository-relative files, symbols, or lines where available. Inferences state their basis and uncertainty. Person-supplied context links to its Handover Item ID when applicable. Commands found in a README or Compose file are documented commands, not proof they work. Use **runtime unverified** until someone actually executes and records a result. Do not invent business purpose, production behavior, verified run commands, successful recovery, or competence scores. - -The personal workspace turns the guide into exercises with an objective, starting guide link and evidence, concrete outcome, and space for notes, questions, and completion evidence. Examples: explain debt creation and consent with failure boundaries; run the service and record the actual result; trace payment to payout; identify what is needed to practice recovery. A checkbox is self-reported progress, not proof of system behavior or ownership readiness. An engineer or organization decides readiness. - -### First personal workspace slice: progress compatibility - -The personal workspace has four fixed `v2:` exercise IDs based on learning outcomes, not source locations or legacy plan tasks. Its canonical state and last-synced checkbox snapshot live in `.transferkit.local/onboarding-v2.json`; `tk onboard sync` imports checkboxes and `tk onboard task <v2-id> <status>` updates the matching checkbox without replacing prose. With a managed guide and personal workspace, `plan` shows the v2 exercises and `status` leads with v2 progress and questions. The older `.transferkit.local/onboarding-progress.json` keeps its schema, task IDs, statuses, and timestamps; legacy progress appears in a separate status section, and the legacy plan remains the fallback when v2 files are absent. There is no automatic one-to-one mapping from repository-specific legacy tasks to broader v2 exercises. A future migration must use an explicit, versioned mapping for genuinely matching tasks, retain unmapped records and timestamps, and surface ambiguous matches for review. A checked v2 box records self-reported completion only; Notes, Questions, and Evidence do not change status. An existing personal Markdown file is never regenerated over human edits. - -## Implementation sequence and acceptance - -1. Review the illustrative Debtbox acceptance fixture against supplied source-inspection evidence. -2. Analyze current scanner, plan, state, CLI, and rendering capabilities against this specification. Record what can be reused and what is missing. -3. Implement the smallest **repository-only guide** slice that produces useful overview, relationships, one explained flow, setup limits, and unknowns from evidence. -4. Add the personal workspace and structured progress synchronization with stable exercise identity, prose preservation, and surfaced conflicts. -5. Add optional v3 Handover Item enrichment by stable ID without making it a dependency of repository-only use. -6. Validate with a real newcomer, first repository-only and then with handover context when available. Measure useful understanding, ability to trace and run, questions left open, and misleading claims. - -Milestone 9 remains in progress until implementation and real newcomer validation are done. The earlier onboarding implementation remains historically accurate: it creates a staged plan from repository findings and legacy handover knowledge, and stores JSON progress locally. The current guide and personal workspace slices add separate Markdown surfaces and checkbox synchronization; v3 Item enrichment remains planned. diff --git a/docs/ONBOARDING_V2_DEBTBOX_FIXTURE.md b/docs/ONBOARDING_V2_DEBTBOX_FIXTURE.md deleted file mode 100644 index ab17840..0000000 --- a/docs/ONBOARDING_V2_DEBTBOX_FIXTURE.md +++ /dev/null @@ -1,109 +0,0 @@ -# Illustrative Debtbox onboarding Markdown fixture - -**Design target only — not current TransferKit CLI output.** This example uses the supplied Debtbox summary and repository-relative citations from the prior read-only Debtbox evidence report. These citations record that report's source inspection; this fixture involved no new Debtbox inspection, runtime execution, or tests. - -## Target: shared `ONBOARDING.md` - -### System overview - -**Observed in code:** NestJS `main.ts` boots `AppModule`. The repository uses PostgreSQL with TypeORM and Redis-backed Socket.IO. Modules include merchant, customer, debt, payment, Nafath, notifications, and admin. In-process work includes scheduled reminders and a payout job. Integrations found: HyperPay, Nafath, Firebase, Alibaba OSS, and SMTP/Mailgun. Business purpose, deployment topology, and production behavior remain unknown. - -<details><summary>Code references to inspect</summary> - -- `src/main.ts:31`, `src/main.ts:62`, `src/main.ts:91` — bootstrap and Redis-backed Socket.IO adapter -- `src/app.module.ts:34`, `src/app.module.ts:54` — modules and scheduled work -- `src/module/data/data.module.ts:9`, `src/config/typeorm.config.ts:52` — TypeORM and PostgreSQL -- `src/module/shared/services/hyperpay/hyperpay.client.ts:25`, `src/module/nafath/nafath.service.ts:72` — HyperPay and Nafath -- `src/module/firebase/firebase.actions.service.ts:24`, `src/module/shared/services/alibaba-oss.service.ts:7`, `src/module/shared/services/email/email-provider.service.ts:22` — push, object storage, and email providers - -</details> - -### Architecture relationships - -**Observed in code:** The boot module connects the application modules; TypeORM connects application data to PostgreSQL; Socket.IO uses Redis backing. The reminders and payout job run in process. **Inferred:** the module and provider connections suggest paths through debt, payment, notifications, and external integrations; inspect each path before treating it as a complete call graph. - -<details><summary>Code references to inspect</summary> - -- `src/app.module.ts:34`, `src/module/data/data.module.ts:9`, `src/config/typeorm.config.ts:52` — module and data relationships -- `src/utilities/redis-io.adapter.ts:20`, `src/module/shared/services/debt-gateway.socket.ts:41` — Redis-backed sockets -- `src/module/debt/debt-notification.service.ts:26`, `src/module/payment/payout-scheduler.service.ts:20` — in-process scheduled work - -</details> - -### Flow: debt creation and consent - -**Observed in code:** A merchant endpoint starts debt creation. Validation and lookups lead to a pending debt and consent, then audit and notification work, with optional push. A customer endpoint checks ownership, status, and expiry. Acceptance sets active; rejection sets cancelled. Acceptance attempts signature storage and Sanad generation. Status changes trigger audit and socket updates. - -**Inferred:** Separate saves and a caught signature-upload failure may allow partial outcomes. **Unknown:** Which records and side effects can remain after failure, and what recovery should an operator use? This is a question for tracing and a knowledgeable person, not an asserted production incident. - -<details><summary>Code references to inspect</summary> - -- `src/module/debt/debt.controller.ts:37`, `src/module/debt/dto/add.debt.ts:20` — merchant entry point and input -- `src/module/debt/debt.service.ts:100`, `src/module/data/entity/debt.entity.ts:53`, `src/module/debt/debt.service.ts:145`, `src/module/debt/debt.service.ts:175`, `src/module/debt/debt.service.ts:201` — checks, pending status, saves, audit, and notification -- `src/module/debt/debt.controller.ts:54`, `src/module/debt/dto/consent-debt.dto.ts:19`, `src/module/debt/debt.service.ts:274`, `src/module/debt/debt.service.ts:296` — customer entry point and consent checks -- `src/module/debt/debt.service.ts:302`, `src/module/debt/debt.service.ts:307`, `src/module/debt/debt.service.ts:325`, `src/module/debt/debt.service.ts:330`, `src/module/debt/debt.service.ts:339`, `src/module/debt/debt.service.ts:356` — status saves, signature failure handling, audit, and socket update -- `src/module/shared/services/sanad/sanad.service.ts:29`, `src/module/shared/services/sanad/sanad.service.ts:74` — Sanad generation - -</details> - -### Other flows to investigate - -**Observed in code:** Payment and payout code, and new-customer onboarding through Nafath, are candidate flows. Their complete end-to-end paths and runtime outcomes are unverified. - -<details><summary>Code references to inspect</summary> - -- `src/module/payment/payment.controller.ts:16`, `src/module/payment/payment.service.ts:77`, `src/module/payment/payment.service.ts:169`, `src/module/payment/payout-scheduler.service.ts:59` — payment through payout starting points -- `src/module/merchant/merchant.controller.ts:167`, `src/module/merchant/merchant.service.ts:92`, `src/module/merchant/merchant.service.ts:113`, `src/module/nafath/nafath.controller.ts:14` — new-customer Nafath starting points - -</details> - -### Setup and operations - -**Observed in repository documentation/configuration:** README lists npm run, start, and test commands. Compose defines PostgreSQL, Redis, and app services. Full setup is undocumented. **Runtime unverified:** No listed command or Compose configuration has been executed for this fixture. Check the port mapping against the app's default port before giving run instructions. Scheduler behavior, payout behavior, and recovery in production are unknown. - -<details><summary>Repository references to inspect</summary> - -- `README.md:76`, `README.md:82`, `README.md:95`, `package.json:8` — documented commands and scripts -- `docker-compose.yml:3`, `docker-compose.yml:36`, `Dockerfile:1` — local service definitions and container build -- `src/main.ts:112`, `docker-compose.yml:36` — default app port and Compose mapping to verify - -</details> - -### Unknowns and person-supplied context - -- What is the system's business purpose and which flows matter most? **Unknown; no person-supplied answer.** -- What are the complete setup steps and verified run/test commands? **Runtime unverified.** -- How are partial debt-consent outcomes detected and recovered? **Unknown.** -- Which operational signals and owners cover reminders, payouts, and integrations? **Unknown.** - -## Target: personal `.transferkit.local/ONBOARDING.md` - -# My Debtbox onboarding - -This private workspace links to the [shared system guide](../ONBOARDING.md). Its checkboxes and notes are personal progress, not claims about production or verified operation. - -### Exercise: explain debt creation and consent - -- [ ] Trace the [debt creation and consent flow](../ONBOARDING.md#flow-debt-creation-and-consent) from merchant endpoint through persistence and side effects, then explain acceptance and rejection. -- Outcome evidence: _Add a short explanation or repository-relative reference after doing the exercise._ -- Notes: _Your observations._ -- Questions: Can separate saves and a caught signature-upload failure leave a partial outcome? What recovery is intended? - -### Exercise: establish a local run - -- [ ] Follow the [setup and operations](../ONBOARDING.md#setup-and-operations) evidence, verify prerequisites and port mapping, and record what actually runs. -- Outcome evidence: _Record commands attempted and actual results; none are verified in this fixture._ -- Notes: _Your observations._ -- Questions: What setup information is missing? - -### Exercise: trace another end-to-end path - -- [ ] Choose payment through payout or new-customer onboarding through Nafath from [other flows](../ONBOARDING.md#other-flows-to-investigate); explain the path and open gaps. -- Outcome evidence: _Add a diagram or brief trace after investigation._ -- Notes: _Your observations._ -- Questions: _What needs a person or runtime check?_ - -### Ownership questions - -- [ ] Review the [unknowns](../ONBOARDING.md#unknowns-and-person-supplied-context) with a knowledgeable person and record answers with their source. -- Notes and evidence: _No person-supplied answers are present in this fixture._ diff --git a/docs/getting-started.md b/docs/getting-started.md index bf8e413..331e29a 100644 --- a/docs/getting-started.md +++ b/docs/getting-started.md @@ -1,6 +1,6 @@ # Getting started -TransferKit runs inside the repository whose ownership is being transferred. It stores shared handover state separately from personal onboarding progress. +TransferKit runs inside the repository whose ownership is being transferred. Shared handover state and the generated guide can be reviewed by a team; personal onboarding progress stays in a separate local workspace. ## Install @@ -20,38 +20,42 @@ npm run build npm link --workspace transferkit ``` -Verify the command with `tk --help`, `tk handover --help`, and `tk onboard --help`. +Verify the command with `tk --help`, `tk handover --help`, and `tk onboard --help`. Then change to the repository you want to examine. ## Build the handover -From the target repository: - ```bash -tk handover init -tk handover scan +cd /path/to/your/repository tk handover plan -# Review and edit HANDOVER.md in your IDE +# Review the suggested IDs and edit HANDOVER.md with the current owner. tk handover sync tk handover status ``` -Initialization creates `.transferkit/project.yaml`. Scanning refreshes suggested items in `.transferkit/transfer.json`. Planning creates the root-level `HANDOVER.md` workspace. Review suggestions with `tk handover plan`, edit the document, then sync supported edits back to Transfer state. `tk handover evidence` shows the repository evidence behind findings. +`handover plan` scans the repository, records suggestions in `.transferkit/transfer.json`, and creates `HANDOVER.md` if it is missing. Review suggestions before a meeting: `tk handover plan accept <item-id>` and `reject <item-id>` make explicit decisions; `rename`, `priority`, `move`, and `add` cover adjustments. Edit the generated checklist to record what was actually discussed, then run `sync` to import supported edits. `status` reports open work. -Existing `.transferkit/handover.json` files remain available to onboarding and are not converted or deleted by the v3 commands. +`tk handover evidence` prints the cited findings behind scanner suggestions. `tk handover scan` refreshes suggestions without creating a checklist; it is optional immediately before `plan`, which already scans. `tk handover init` creates optional `.transferkit/project.yaml` metadata. Existing legacy `.transferkit/handover.json` data is not converted or deleted by the v3 commands. ## Start onboarding ```bash +tk onboard guide +tk onboard workspace tk onboard plan +# Read ONBOARDING.md; write notes and observations in .transferkit.local/ONBOARDING.md. +tk onboard task v2:trace-flow in-progress +tk onboard sync tk onboard status -tk onboard task <task-id> in-progress -tk onboard task <task-id> completed ``` -Onboarding progress is stored under `.transferkit.local/`, which TransferKit's repository ignores by default. Onboarding currently reads repository findings and any existing legacy handover knowledge; it does not consume v3 Transfer completion yet. Its plan remains useful when human handover knowledge is incomplete by distinguishing repository-derived facts from unknown context. +`guide` builds a shared, source-cited reading path through the repository. It begins with project purpose when documented, or a bounded source-level overview when it is not. Stories separate selected entries and label unsupported connections and runtime effects. Use `tk onboard guide --focus <route-or-symbol>` to inspect a supported entry. + +`workspace` creates a personal checklist once and does not overwrite it. Check a box in the Markdown file and run `sync`, or set status directly with `task`. The stable `v2:` exercises ask you to explain the system map, compare source journeys, record a safe observation or blocker, and identify ownership questions. `plan` and `status` flag stale links if selected guide entries change. Completed exercises are self-reported progress. + +Personal files are stored under `.transferkit.local/`. Add that directory to the target repository's ignore rules if it is not already ignored. Onboarding does not consume v3 Transfer completion state; it may still display legacy onboarding progress separately when present. ## Handling errors safely Invalid persisted state, malformed `package.json`, unsupported schema versions, scanner failures, and filesystem errors return a non-zero exit code with a concise message. TransferKit does not print raw stack traces during normal CLI use. -Back up shared state before editing it manually. TransferKit validates state on read and rejects structurally invalid files rather than silently repairing them. +Back up shared state before editing it manually. TransferKit validates state on read and rejects structurally invalid files rather than silently repairing them. Generated setup commands are documentation or declarations, not verified execution; check prerequisites before running them. diff --git a/examples/workflow.md b/examples/workflow.md index cfb31f1..b21e3e0 100644 --- a/examples/workflow.md +++ b/examples/workflow.md @@ -1,19 +1,13 @@ # Example ownership-transfer workflow -This example shows representative output for a NestJS service. Exact findings depend on the repository. +This example shows a typical sequence for a service repository. Exact item IDs, findings, and files depend on the repository. ```console -$ tk handover init -Initialized TransferKit in /work/shipment-platform/.transferkit/project.yaml - -$ tk handover scan -Scanned repository: 5 findings, 18 suggestions pending review. Use: tk handover plan - $ tk handover plan Handover Plan: 18 items, 18 pending review, 0 done. Generated HANDOVER.md. -# Review and edit HANDOVER.md in your IDE, then synchronize it. +# Review suggestions and edit HANDOVER.md with the current owner. $ tk handover sync Synced HANDOVER.md @@ -21,18 +15,24 @@ $ tk handover status shipment-platform Handover 0 / 18 complete -$ tk onboard plan -Onboarding Plan +$ tk onboard guide +Generated ONBOARDING.md from repository evidence. Runtime behavior remains unverified. -Knowledge source: repository and human handover. +$ tk onboard workspace +Generated .transferkit.local/ONBOARDING.md with 4 repository-only exercises. Legacy JSON progress was not changed. + +$ tk onboard plan +Onboarding plan +1. Understand the system [not-started] (v2:understand-system) ... -$ tk onboard task understand-system:consumer:shipments completed -Updated understand-system:consumer:shipments to completed. +$ tk onboard task v2:trace-flow in-progress +Updated v2:trace-flow to in-progress; personal Markdown and JSON are synchronized. $ tk onboard status -Understand the System 1/1 -Trace It 0/1 +Onboarding progress +0 / 4 exercises complete (self-reported) +... ``` -`HANDOVER.md` is the editable handover workspace. Its supported edits synchronize to `.transferkit/transfer.json`. Personal onboarding progress is stored separately in `.transferkit.local/`. +`HANDOVER.md` is the editable shared checklist; supported edits synchronize to `.transferkit/transfer.json`. `ONBOARDING.md` is a cited guide generated from repository evidence. Each newcomer keeps progress and notes separately in `.transferkit.local/`. Generated explanations and setup commands remain unverified until a person checks the source and runs a safe observation. diff --git a/experiments/fixtures/nest-trace/controller.ts b/experiments/fixtures/nest-trace/controller.ts new file mode 100644 index 0000000..a178fa2 --- /dev/null +++ b/experiments/fixtures/nest-trace/controller.ts @@ -0,0 +1,12 @@ +import { Controller, Post } from "@nestjs/common"; +import { OrderService } from "./order.service"; + +@Controller("orders") +export class OrderController { + constructor(private readonly orders: OrderService) {} + + @Post() + submit() { + return this.orders.submit(true); + } +} diff --git a/experiments/fixtures/nest-trace/order.service.ts b/experiments/fixtures/nest-trace/order.service.ts new file mode 100644 index 0000000..9c5e82e --- /dev/null +++ b/experiments/fixtures/nest-trace/order.service.ts @@ -0,0 +1,38 @@ +import { OrderRepository, NotificationService, normalize } from "./providers"; + +interface Dispatcher { + send(order: { status: string }): void; +} + +export class OrderService { + constructor( + private readonly orders: OrderRepository, + private readonly notifications: NotificationService, + private readonly dispatcher: Dispatcher, + ) {} + + async submit(accepted: boolean) { + accepted = normalize(accepted); + const order = await this.orders.find(); + this.validate(order); + if (accepted) { + order.status = "accepted"; + await this.orders.save(order); + } else { + order.status = "rejected"; + throw new Error("rejected"); + } + try { + await this.notifications.send(order); + } catch { + order.status = "notification-failed"; + } + const method = "send"; + this.notifications[method](order); + this.dispatcher.send(order); + } + + private validate(order: { status: string }) { + if (!order) throw new Error("missing order"); + } +} diff --git a/experiments/fixtures/nest-trace/providers.ts b/experiments/fixtures/nest-trace/providers.ts new file mode 100644 index 0000000..7b20259 --- /dev/null +++ b/experiments/fixtures/nest-trace/providers.ts @@ -0,0 +1,19 @@ +export class OrderRepository { + async find(): Promise<{ status: string }> { + return { status: "pending" }; + } + + async save(order: { status: string }): Promise<void> { + void order; + } +} + +export class NotificationService { + async send(order: { status: string }): Promise<void> { + void order; + } +} + +export function normalize(value: boolean): boolean { + return value; +} diff --git a/experiments/fixtures/nest-trace/tsconfig.json b/experiments/fixtures/nest-trace/tsconfig.json new file mode 100644 index 0000000..075a3f6 --- /dev/null +++ b/experiments/fixtures/nest-trace/tsconfig.json @@ -0,0 +1,9 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "CommonJS", + "experimentalDecorators": true, + "noEmit": true + }, + "include": ["*.ts"] +} diff --git a/experiments/onboarding-phase2-benchmark.mjs b/experiments/onboarding-phase2-benchmark.mjs new file mode 100644 index 0000000..88a7f67 --- /dev/null +++ b/experiments/onboarding-phase2-benchmark.mjs @@ -0,0 +1,58 @@ +import { performance } from "node:perf_hooks"; +import { resolve } from "node:path"; + +import { scanOnboardingRepository } from "../packages/scanners/dist/index.js"; +import { + explainCandidateFlows, + understandProject, +} from "../packages/standards/dist/index.js"; +import { renderOnboardingGuide } from "../packages/renderers/dist/index.js"; + +const [repository, ...entries] = process.argv.slice(2); +if (!repository || !entries.length) + throw new Error( + "Usage: node experiments/onboarding-phase2-benchmark.mjs <repository> <Controller.method> [...]", + ); + +const start = performance.now(); +const directory = resolve(repository); +const { findings, traces, loadedFiles } = await scanOnboardingRepository( + directory, + entries, +); +const model = understandProject(findings); +const guide = renderOnboardingGuide( + model, + findings, + explainCandidateFlows(model, findings), +); +process.stdout.write( + `${JSON.stringify( + { + elapsedSeconds: Number(((performance.now() - start) / 1000).toFixed(3)), + guideBytes: Buffer.byteLength(guide), + rssMiB: Number((process.memoryUsage().rss / 2 ** 20).toFixed(1)), + peakRssMiB: Number( + ( + process.resourceUsage().maxRSS / + (process.platform === "darwin" ? 2 ** 20 : 1024) + ).toFixed(1), + ), + loadedFiles, + selectedRoutes: traces.length, + traces: traces.map((trace) => ({ + entry: trace.entry.symbol, + methods: trace.methods.map((method) => method.symbol), + calls: trace.calls.length, + gaps: trace.gaps.length, + writeLikeSites: trace.methods.flatMap((method) => + method.events + .filter((event) => event.effect === "write-like") + .map((event) => `${event.at.file}:${event.at.line}`), + ), + })), + }, + null, + 2, + )}\n`, +); diff --git a/experiments/onboarding-phase6-regression.py b/experiments/onboarding-phase6-regression.py new file mode 100644 index 0000000..ea1f9bc --- /dev/null +++ b/experiments/onboarding-phase6-regression.py @@ -0,0 +1,136 @@ +"""Run repository-only onboarding acceptance on disposable snapshots. + +Build TransferKit first. This script runs only the TransferKit CLI; it never runs +the evaluated repositories' install, start, migration, seed, or test scripts. +""" + +import argparse +import hashlib +import json +import os +import re +import resource +import shutil +import subprocess +import sys +import time +from pathlib import Path + + +ROOT = Path(__file__).resolve().parents[1] +CLI = ROOT / "packages/cli/dist/index.js" +SOURCES = [ + ("plain-node", ROOT / "fixtures/onboarding-plain-node", None), + ("neutral-nest", ROOT / "fixtures/onboarding-phase4", None), + ("neutral-branches", ROOT / "fixtures/onboarding-deep-guide", None), + ("event-count-cli", ROOT / "fixtures/onboarding-human-cli", None), + ("sparse-python", ROOT / "fixtures/onboarding-human-sparse", None), +] +REVISIONS = [ + ("debtbox", "e0267736a40a3181aae1c463782fe0f0436975c7"), + ("madar", "79cc98e534a95a2a316c3464281619fb86a12d99"), +] + + +def snapshot_archive(repository: Path, revision: str, destination: Path) -> None: + archive = destination.parent / f"{destination.name}.tar" + subprocess.run( + ["git", "-C", str(repository), "archive", f"--output={archive}", revision], + check=True, + ) + destination.mkdir() + try: + subprocess.run(["tar", "-xf", str(archive), "-C", str(destination)], check=True) + finally: + archive.unlink(missing_ok=True) + + +def guide_run(directory: Path) -> tuple[float, float, str]: + log = directory / "guide-run.log" + started = time.perf_counter() + with log.open("w") as output: + process = subprocess.Popen( + ["node", str(CLI), "onboard", "guide"], + cwd=directory, + stdout=output, + stderr=subprocess.STDOUT, + ) + _, status, usage = os.wait4(process.pid, 0) + if os.waitstatus_to_exitcode(status) != 0: + raise RuntimeError(f"guide failed in {directory}: {log.read_text()}") + peak_mib = usage.ru_maxrss / (1024 * 1024 if sys.platform == "darwin" else 1024) + return round(time.perf_counter() - started, 3), round(peak_mib, 1), log.read_text().strip() + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--out", required=True, type=Path, help="New output directory") + parser.add_argument("--debtbox", type=Path, help="Debtbox Git checkout") + parser.add_argument("--madar", type=Path, help="Madar B2C Git checkout") + args = parser.parse_args() + if not CLI.is_file(): + parser.error("Build TransferKit first with npm run build") + args.out.mkdir(parents=True, exist_ok=False) + cases = list(SOURCES) + for name, revision in REVISIONS: + repository = getattr(args, name) + if repository: + cases.append((name, repository, revision)) + results = [] + for name, source, revision in cases: + target = args.out / name + if revision: + snapshot_archive(source, revision, target) + else: + shutil.copytree(source, target) + seconds, peak_mib, message = guide_run(target) + workspace = subprocess.run( + ["node", str(CLI), "onboard", "workspace"], + cwd=target, + text=True, + capture_output=True, + check=True, + ) + guide = (target / "ONBOARDING.md").read_text() + opening = guide.split("## Start here", 1)[-1].split( + "<!-- tk:onboard:section system-overview end -->", 1 + )[0] + opening = re.sub(r"<!--.*?-->|<[^>]+>|\]\([^)]*\)", " ", opening, flags=re.S) + references = re.findall(r"\[([^\]]+):(\d+)\]\(([^)#]+)#L(\d+)\)", guide) + broken_references = [] + for ref_name, line, path, anchor in references: + source = target / path + if ( + ref_name != path + or line != anchor + or not source.is_file() + or int(line) > len(source.read_text(errors="replace").splitlines()) + ): + broken_references.append(f"{ref_name}:{line}") + results.append( + { + "case": name, + "revision": revision, + "guide_seconds": seconds, + "guide_peak_mib": peak_mib, + "guide_bytes": len(guide.encode()), + "guide_sha256": hashlib.sha256(guide.encode()).hexdigest(), + "opening_words": len(re.findall(r"\b[\w-]+\b", opening)), + "source_references": len(references), + "broken_source_references": broken_references, + "journeys": re.findall(r"^### Source journey: (.+)$", guide, re.M), + "snapshot_js_ts_files": sum( + path.suffix in {".ts", ".tsx", ".js", ".jsx"} + for path in target.rglob("*") + if path.is_file() and "node_modules" not in path.parts + ), + "guide_message": message, + "workspace_message": workspace.stdout.strip(), + } + ) + (args.out / "results.json").write_text(json.dumps(results, indent=2) + "\n") + print(args.out / "results.json") + + +if __name__ == "__main__": + main() diff --git a/experiments/onboarding-trace-spike.mjs b/experiments/onboarding-trace-spike.mjs new file mode 100644 index 0000000..6ccedf1 --- /dev/null +++ b/experiments/onboarding-trace-spike.mjs @@ -0,0 +1,333 @@ +// Isolated experiment. This is not imported by the production guide pipeline. +import { existsSync } from "node:fs"; +import { relative, resolve, sep } from "node:path"; +import ts from "typescript"; + +export function traceRoute(root, controllerFile, handlerName, maxDepth = 2) { + const configPath = ts.findConfigFile( + root, + ts.sys.fileExists, + "tsconfig.json", + ); + if (!configPath) throw new Error(`No tsconfig.json in ${root}`); + const loaded = ts.readConfigFile(configPath, ts.sys.readFile); + if (loaded.error) + throw new Error( + ts.flattenDiagnosticMessageText(loaded.error.messageText, "\n"), + ); + const config = ts.parseJsonConfigFileContent(loaded.config, ts.sys, root); + const controllerPath = resolve(root, controllerFile); + if (!existsSync(controllerPath)) + throw new Error(`Missing controller: ${controllerPath}`); + // Load the route's import graph, not every file listed by the repository config. + const program = ts.createProgram([controllerPath], { + ...config.options, + noEmit: true, + incremental: false, + }); + const checker = program.getTypeChecker(); + const source = program.getSourceFile(controllerPath); + if (!source) throw new Error(`Controller not loaded: ${controllerPath}`); + const owner = findClassWithMethod(source, handlerName); + if (!owner) throw new Error(`Handler ${handlerName} not found`); + const handler = owner.members.find( + (member) => + ts.isMethodDeclaration(member) && + member.name?.getText(source) === handlerName, + ); + const methods = []; + const gaps = []; + const seen = new Set(); + let limitReached = false; + + function evidence(node) { + const file = node.getSourceFile(); + const path = relative(root, file.fileName); + return `${path}:${file.getLineAndCharacterOfPosition(node.getStart(file)).line + 1}`; + } + function insideRoot(node) { + const path = relative(root, node.getSourceFile().fileName); + return ( + path !== "" && + !path.startsWith(`..${sep}`) && + path !== ".." && + !path.startsWith("node_modules") + ); + } + function symbolName(method) { + const parent = method.parent; + return `${ts.isClassDeclaration(parent) ? (parent.name?.text ?? "<anonymous>") : "<non-class>"}.${method.name?.getText() ?? "<unknown>"}`; + } + function resolveCall(call) { + const expression = call.expression; + if (ts.isElementAccessExpression(expression)) + return { gap: "dynamic dispatch" }; + if (!ts.isPropertyAccessExpression(expression)) + return { gap: "indirect or unsupported call" }; + const receiver = expression.expression; + const isThisCall = receiver.kind === ts.SyntaxKind.ThisKeyword; + const isInjectedCall = + ts.isPropertyAccessExpression(receiver) && + receiver.expression.kind === ts.SyntaxKind.ThisKeyword; + if (!isThisCall && !isInjectedCall) + return { gap: "receiver alias or external call" }; + const declarations = + checker.getSymbolAtLocation(expression.name)?.declarations ?? []; + const targets = declarations.filter( + (declaration) => + ts.isMethodDeclaration(declaration) && + declaration.body && + insideRoot(declaration), + ); + if (targets.length === 1 && declarations.length === 1) + return { target: targets[0] }; + if (declarations.length > 1 || declarations.some(ts.isMethodSignature)) + return { gap: "ambiguous provider implementation" }; + return { gap: "method body unavailable or unresolved type" }; + } + function inspect(method, depth) { + if (!method?.body) return; + const id = `${evidence(method)}:${symbolName(method)}`; + if (seen.has(id)) return; + seen.add(id); + if (methods.length >= 50) { + limitReached = true; + return; + } + const item = { + symbol: symbolName(method), + declaration: evidence(method), + events: [], + }; + methods.push(item); + const follow = []; + function event(kind, node, detail, conditions = [], awaited) { + item.events.push({ + kind, + at: evidence(node), + detail, + ...(conditions.length ? { conditions } : {}), + ...(awaited === undefined ? {} : { awaited }), + }); + } + function visit(node, conditions = []) { + if (ts.isIfStatement(node)) { + const condition = node.expression + .getText() + .replace(/\s+/g, " ") + .slice(0, 180); + visit(node.expression, conditions); + event("branch", node, condition, conditions); + visit(node.thenStatement, [...conditions, `when ${condition}`]); + if (node.elseStatement) + visit(node.elseStatement, [...conditions, `else ${condition}`]); + return; + } + if ( + ts.isSwitchStatement(node) || + ts.isConditionalExpression(node) || + ts.isForStatement(node) || + ts.isForOfStatement(node) || + ts.isForInStatement(node) || + ts.isWhileStatement(node) || + ts.isDoStatement(node) + ) { + gaps.push({ + at: evidence(node), + from: item.symbol, + reason: `unsupported control flow: ${ts.SyntaxKind[node.kind]}`, + }); + return; + } + if (ts.isTryStatement(node)) { + visit(node.tryBlock, [...conditions, "try"]); + if (node.catchClause) { + event( + "catch", + node.catchClause, + "catch branch; outcome unverified", + conditions, + ); + visit(node.catchClause.block, [...conditions, "catch"]); + } + if (node.finallyBlock) + visit(node.finallyBlock, [...conditions, "finally"]); + return; + } + if (ts.isThrowStatement(node)) { + event( + "throw", + node, + node.expression?.getText().replace(/\s+/g, " ").slice(0, 120) ?? + "throw", + conditions, + ); + return; + } + if ( + ts.isArrowFunction(node) || + ts.isFunctionExpression(node) || + ts.isFunctionDeclaration(node) + ) { + gaps.push({ + at: evidence(node), + from: item.symbol, + reason: "nested function or callback body not followed", + }); + return; + } + if ( + ts.isBinaryExpression(node) && + node.operatorToken.kind === ts.SyntaxKind.EqualsToken && + ts.isPropertyAccessExpression(node.left) + ) { + event( + "assignment", + node, + `${node.left.getText()} = ${node.right.getText().replace(/\s+/g, " ").slice(0, 100)}`, + conditions, + ); + } + if (ts.isCallExpression(node)) { + const result = resolveCall(node); + const detail = node.expression.getText().replace(/\s+/g, " "); + const nestedArgument = + node.parent && ts.isCallExpression(node.parent) + ? ["nested call argument"] + : []; + const callConditions = [...conditions, ...nestedArgument]; + const awaited = ts.isAwaitExpression(node.parent); + if (result.target) { + const target = result.target; + const symbol = symbolName(target); + const kind = /Repository\.(?:get|find)/u.test(symbol) + ? "read-like call" + : /Repository\.save$/u.test(symbol) + ? "write-like call" + : "call"; + event( + kind, + node, + `${detail} -> declared ${symbol} @ ${evidence(target)}`, + callConditions, + awaited, + ); + if (depth < maxDepth) follow.push(target); + else + gaps.push({ + at: evidence(node), + from: item.symbol, + reason: `depth limit before ${symbolName(target)}`, + }); + } else if ( + ts.isPropertyAccessExpression(node.expression) && + (node.expression.expression.kind === ts.SyntaxKind.ThisKeyword || + node.expression.expression.getText().startsWith("this.") || + /^queryRunner(?:\.|$)/u.test(node.expression.expression.getText())) + ) { + const writeLike = /(?:^|\.)save$/u.test(detail); + event( + writeLike ? "write-like call (unresolved)" : "unresolved call", + node, + `${detail}: ${result.gap}`, + callConditions, + awaited, + ); + gaps.push({ + at: evidence(node), + from: item.symbol, + reason: `${detail}: ${result.gap}`, + }); + } else if (ts.isElementAccessExpression(node.expression)) { + event( + "unresolved call", + node, + `${detail}: dynamic dispatch`, + callConditions, + awaited, + ); + gaps.push({ + at: evidence(node), + from: item.symbol, + reason: `${detail}: dynamic dispatch`, + }); + } else if (ts.isIdentifier(node.expression)) { + const symbol = checker.getSymbolAtLocation(node.expression); + const resolved = + symbol && symbol.flags & ts.SymbolFlags.Alias + ? checker.getAliasedSymbol(symbol) + : symbol; + if (resolved?.declarations?.some(insideRoot)) { + event( + "unresolved call", + node, + `${detail}: project free function call unsupported`, + callConditions, + awaited, + ); + gaps.push({ + at: evidence(node), + from: item.symbol, + reason: `${detail}: project free function call unsupported`, + }); + } + } + } + ts.forEachChild(node, (child) => visit(child, conditions)); + } + visit(method.body); + item.events.sort( + (a, b) => Number(a.at.split(":").at(-1)) - Number(b.at.split(":").at(-1)), + ); + for (const target of follow) inspect(target, depth + 1); + } + inspect(handler, 0); + if (limitReached) + gaps.push({ + at: evidence(handler), + from: symbolName(handler), + reason: "50-method limit reached", + }); + return { + tool: `TypeScript ${ts.version} compiler API`, + config: relative(root, configPath), + sourceFiles: program.getSourceFiles().filter(insideRoot).length, + methods, + gaps, + diagnostics: ts + .getPreEmitDiagnostics(program) + .slice(0, 5) + .map((diagnostic) => + ts.flattenDiagnosticMessageText(diagnostic.messageText, " "), + ), + }; +} + +function findClassWithMethod(source, name) { + return source.statements.find( + (statement) => + ts.isClassDeclaration(statement) && + statement.members.some( + (member) => + ts.isMethodDeclaration(member) && + member.name?.getText(source) === name, + ), + ); +} + +if ( + process.argv[1] && + resolve(process.argv[1]) === resolve(new URL(import.meta.url).pathname) +) { + const [root, controller, method, depth] = process.argv.slice(2); + if (!root || !controller || !method) { + process.stderr.write( + "Usage: node experiments/onboarding-trace-spike.mjs ROOT CONTROLLER METHOD [DEPTH]\n", + ); + process.exitCode = 2; + } else { + process.stdout.write( + `${JSON.stringify(traceRoute(resolve(root), controller, method, depth ? Number(depth) : 2), null, 2)}\n`, + ); + } +} diff --git a/experiments/onboarding-trace-spike.test.mjs b/experiments/onboarding-trace-spike.test.mjs new file mode 100644 index 0000000..f968381 --- /dev/null +++ b/experiments/onboarding-trace-spike.test.mjs @@ -0,0 +1,79 @@ +import assert from "node:assert/strict"; +import { resolve } from "node:path"; +import test from "node:test"; +import { traceRoute } from "./onboarding-trace-spike.mjs"; + +const fixture = resolve("experiments/fixtures/nest-trace"); + +test("resolves cited route, local helper, and cross-file provider methods", () => { + const trace = traceRoute(fixture, "controller.ts", "submit"); + assert.deepEqual( + trace.methods.map((method) => method.symbol), + [ + "OrderController.submit", + "OrderService.submit", + "OrderRepository.find", + "OrderService.validate", + "OrderRepository.save", + "NotificationService.send", + ], + ); + assert.match( + trace.methods[0].events[0].detail, + /declared OrderService\.submit @ order\.service\.ts:\d+/u, + ); + assert.match( + trace.methods[1].events.find((event) => + event.detail.includes("this.validate"), + ).detail, + /OrderService\.validate @ order\.service\.ts:\d+/u, + ); + assert.match( + trace.methods[1].events.find((event) => + event.detail.includes("this.notifications.send"), + ).detail, + /NotificationService\.send @ providers\.ts:\d+/u, + ); + assert.ok( + trace.methods[1].events.every( + (event) => !event.detail.includes("constructor"), + ), + ); +}); + +test("keeps exclusive branches and catch distinct, and marks unsupported dispatch", () => { + const trace = traceRoute(fixture, "controller.ts", "submit"); + const events = trace.methods[1].events; + assert.deepEqual( + events.find((event) => event.detail.includes('order.status = "accepted"')) + .conditions, + ["when accepted"], + ); + assert.deepEqual( + events.find((event) => event.detail.includes('order.status = "rejected"')) + .conditions, + ["else accepted"], + ); + assert.deepEqual( + events.find((event) => + event.detail.includes('order.status = "notification-failed"'), + ).conditions, + ["catch"], + ); + assert.ok(trace.gaps.some((gap) => gap.reason.includes("dynamic dispatch"))); + assert.ok( + trace.gaps.some((gap) => + gap.reason.includes("normalize: project free function call unsupported"), + ), + ); + assert.ok( + trace.gaps.some((gap) => + gap.reason.includes( + "this.dispatcher.send: ambiguous provider implementation", + ), + ), + ); + assert.ok( + !trace.methods.some((method) => method.symbol.startsWith("Dispatcher.")), + ); +}); diff --git a/fixtures/onboarding-deep-guide/controller.ts b/fixtures/onboarding-deep-guide/controller.ts new file mode 100644 index 0000000..26ac175 --- /dev/null +++ b/fixtures/onboarding-deep-guide/controller.ts @@ -0,0 +1,17 @@ +import { Controller, Post } from "@nestjs/common"; +import { OrderService, type OrderInput } from "./service.js"; + +@Controller("orders") +export class OrderController { + constructor(private readonly orders: OrderService) {} + + @Post("submit") + submit(input: OrderInput) { + return this.orders.create(input); + } + + @Post("preview") + preview(input: OrderInput) { + return this.orders.create(input); + } +} diff --git a/fixtures/onboarding-deep-guide/entity.ts b/fixtures/onboarding-deep-guide/entity.ts new file mode 100644 index 0000000..a66a4aa --- /dev/null +++ b/fixtures/onboarding-deep-guide/entity.ts @@ -0,0 +1,28 @@ +import { + Column, + Entity, + ManyToOne, + OneToMany, + PrimaryGeneratedColumn, +} from "typeorm"; + +@Entity() +export class AccountEntity { + @PrimaryGeneratedColumn() + id!: number; + + @OneToMany(() => OrderEntity, (order) => order.account) + orders!: OrderEntity[]; +} + +@Entity() +export class OrderEntity { + @PrimaryGeneratedColumn() + id!: number; + + @Column() + status!: string; + + @ManyToOne(() => AccountEntity, (account) => account.orders) + account!: AccountEntity; +} diff --git a/fixtures/onboarding-deep-guide/limits.ts b/fixtures/onboarding-deep-guide/limits.ts new file mode 100644 index 0000000..cef2ad0 --- /dev/null +++ b/fixtures/onboarding-deep-guide/limits.ts @@ -0,0 +1,47 @@ +import { Controller, Post } from "@nestjs/common"; + +interface Dispatcher { + send(value: string): void; +} + +@Controller("limits") +export class LimitsController { + private readonly handlers: Record<string, () => void> = {}; + + constructor(private readonly dispatcher: Dispatcher) {} + + @Post("check") + check(mode: string): void { + if (mode === "stop") return; + this.dispatcher.send(this.value()); + const callback = () => this.dispatcher.send("later"); + if (mode === "callback") callback(); + if (mode === "dynamic") this.handlers[mode]?.(); + for (let index = 0; index < 2; index++) this.dispatcher.send("loop"); + switch (mode) { + case "dynamic": + this.handlers[mode]?.(); + break; + } + } + + private value(): string { + return "sample"; + } +} + +class BaseRunner { + run(): void {} +} + +class DerivedRunner extends BaseRunner {} + +@Controller("inherited") +export class InheritedController { + constructor(private readonly runner: DerivedRunner) {} + + @Post("run") + run(): void { + this.runner.run(); + } +} diff --git a/fixtures/onboarding-deep-guide/nest-shim.d.ts b/fixtures/onboarding-deep-guide/nest-shim.d.ts new file mode 100644 index 0000000..a64d053 --- /dev/null +++ b/fixtures/onboarding-deep-guide/nest-shim.d.ts @@ -0,0 +1,8 @@ +declare module "@nestjs/common" { + export function Controller(path: string): ClassDecorator; + export function Post(path: string): MethodDecorator; +} + +declare module "@nestjs/bull" { + export function Process(name: string): MethodDecorator; +} diff --git a/fixtures/onboarding-deep-guide/service.ts b/fixtures/onboarding-deep-guide/service.ts new file mode 100644 index 0000000..d836855 --- /dev/null +++ b/fixtures/onboarding-deep-guide/service.ts @@ -0,0 +1,75 @@ +export type OrderInput = { valid: boolean; priority: boolean }; +type Order = { id: string; status: string }; + +export class OrderRepository extends Repository<OrderEntity> { + async find(_id: string): Promise<OrderEntity | undefined> { + void _id; + return undefined; + } +} + +export class AssignmentQueue { + async add(_name: string, _data: { id: string }): Promise<void> { + void _name; + void _data; + } +} + +export interface QueryRunner { + manager: { save(order: Order): Promise<void> }; + commitTransaction(): Promise<void>; + rollbackTransaction(): Promise<void>; + release(): Promise<void>; +} + +export declare class DataSource { + createQueryRunner(): QueryRunner; +} + +export class CacheSnapshot { + save(_order: Order): void { + void _order; + } +} + +export class OrderService { + constructor( + private readonly repository: OrderRepository, + private readonly queue: AssignmentQueue, + private readonly dataSource: DataSource, + private readonly cache: CacheSnapshot, + ) {} + + async create(input: OrderInput): Promise<Order> { + if (!input.valid) throw new Error("invalid order"); + const order: Order = { id: "order-1", status: "new" }; + await this.repository.find(order.id); + if (input.priority) { + order.status = "priority"; + } else { + order.status = "standard"; + } + this.recordAttempt(order); + this.recordAttempt(order); + const runner = this.dataSource.createQueryRunner(); + try { + await runner.manager.save(order); + await runner.commitTransaction(); + } catch { + await runner.rollbackTransaction(); + throw new Error("order write failed"); + } finally { + await runner.release(); + } + await this.queue.add("assign-order", { id: order.id }); + this.cache.save(order); + return order; + } + + private recordAttempt(_order: Order): void { + void _order; + } +} + +import { Repository } from "typeorm"; +import { OrderEntity } from "./entity.js"; diff --git a/fixtures/onboarding-deep-guide/worker.ts b/fixtures/onboarding-deep-guide/worker.ts new file mode 100644 index 0000000..cd84197 --- /dev/null +++ b/fixtures/onboarding-deep-guide/worker.ts @@ -0,0 +1,17 @@ +import { Process } from "@nestjs/bull"; +import { OrderRepository } from "./service.js"; + +export class AssignmentWorker { + constructor(private readonly repository: OrderRepository) {} + + @Process("assign-order") + async handle(id: string): Promise<void> { + if (!id) return; + await this.repository.find(id); + } +} + +export class ArchiveWorker { + @Process("archive-order") + async handle(): Promise<void> {} +} diff --git a/fixtures/onboarding-human-cli/README.md b/fixtures/onboarding-human-cli/README.md new file mode 100644 index 0000000..4095ec2 --- /dev/null +++ b/fixtures/onboarding-human-cli/README.md @@ -0,0 +1,5 @@ +# Event Count CLI + +This small command-line tool reads a newline-delimited JSON event file and prints a count for each event type. It does not store or send events. + +Run `npm start -- events.jsonl` with a local input file. A missing path prints usage and exits with a nonzero status; invalid JSON and events without a string `type` are also rejected. The command has not been run by TransferKit guide generation. diff --git a/fixtures/onboarding-human-cli/package.json b/fixtures/onboarding-human-cli/package.json new file mode 100644 index 0000000..03b07ce --- /dev/null +++ b/fixtures/onboarding-human-cli/package.json @@ -0,0 +1,11 @@ +{ + "name": "event-count-cli", + "private": true, + "type": "module", + "bin": { + "event-count": "src/cli.js" + }, + "scripts": { + "start": "node src/cli.js" + } +} diff --git a/fixtures/onboarding-human-cli/src/cli.js b/fixtures/onboarding-human-cli/src/cli.js new file mode 100644 index 0000000..9bde05f --- /dev/null +++ b/fixtures/onboarding-human-cli/src/cli.js @@ -0,0 +1,29 @@ +#!/usr/bin/env node +import { readFile } from "node:fs/promises"; + +const path = process.argv[2]; +if (!path) { + console.error("Usage: event-count <file.jsonl>"); + process.exitCode = 2; +} else { + try { + const lines = (await readFile(path, "utf8")) + .split(/\r?\n/u) + .filter(Boolean); + const counts = new Map(); + for (const line of lines) { + const event = JSON.parse(line); + if (typeof event.type !== "string") + throw new Error("Event type must be a string"); + counts.set(event.type, (counts.get(event.type) ?? 0) + 1); + } + for (const [type, count] of [...counts].sort(([left], [right]) => + left.localeCompare(right), + )) { + console.log(`${type}: ${count}`); + } + } catch (error) { + console.error(error instanceof Error ? error.message : String(error)); + process.exitCode = 1; + } +} diff --git a/fixtures/onboarding-human-sparse/README.md b/fixtures/onboarding-human-sparse/README.md new file mode 100644 index 0000000..4b7de7c --- /dev/null +++ b/fixtures/onboarding-human-sparse/README.md @@ -0,0 +1,5 @@ +# CSV comparison utility + +This small Python utility compares item counts in two CSV files and writes differences to standard output. The repository has no application server, database, or documented test command. + +Invoke `python3 compare.py <expected.csv> <actual.csv>` with disposable input files. Repository evidence does not establish the intended deployment, owner, or production data source. diff --git a/fixtures/onboarding-human-sparse/compare.py b/fixtures/onboarding-human-sparse/compare.py new file mode 100644 index 0000000..1ede6f4 --- /dev/null +++ b/fixtures/onboarding-human-sparse/compare.py @@ -0,0 +1,18 @@ +import csv +import sys + + +def counts(path): + with open(path, newline="", encoding="utf-8") as source: + return {row["item"]: int(row["count"]) for row in csv.DictReader(source)} + + +if __name__ == "__main__": + if len(sys.argv) != 3: + raise SystemExit("Usage: compare.py <expected.csv> <actual.csv>") + expected = counts(sys.argv[1]) + actual = counts(sys.argv[2]) + for item in sorted(expected.keys() | actual.keys()): + difference = actual.get(item, 0) - expected.get(item, 0) + if difference: + print(f"{item},{difference}") diff --git a/fixtures/onboarding-phase4/README.md b/fixtures/onboarding-phase4/README.md new file mode 100644 index 0000000..23d1e93 --- /dev/null +++ b/fixtures/onboarding-phase4/README.md @@ -0,0 +1,5 @@ +# NestJS starter + +## Description + +NestJS framework TypeScript starter repository. diff --git a/fixtures/onboarding-phase4/controller.ts b/fixtures/onboarding-phase4/controller.ts new file mode 100644 index 0000000..743b4bf --- /dev/null +++ b/fixtures/onboarding-phase4/controller.ts @@ -0,0 +1,12 @@ +import { Controller, Post } from "@nestjs/common"; +import { ParcelService } from "./service.js"; + +@Controller("parcels") +export class ParcelController { + constructor(private readonly parcels: ParcelService) {} + + @Post("dispatch") + dispatch() { + return this.parcels.dispatch(); + } +} diff --git a/fixtures/onboarding-phase4/entity.ts b/fixtures/onboarding-phase4/entity.ts new file mode 100644 index 0000000..c65a6db --- /dev/null +++ b/fixtures/onboarding-phase4/entity.ts @@ -0,0 +1,10 @@ +import { Column, Entity, PrimaryGeneratedColumn } from "typeorm"; + +@Entity() +export class Parcel { + @PrimaryGeneratedColumn() + id!: number; + + @Column() + status!: string; +} diff --git a/fixtures/onboarding-phase4/module.ts b/fixtures/onboarding-phase4/module.ts new file mode 100644 index 0000000..d0a1ff9 --- /dev/null +++ b/fixtures/onboarding-phase4/module.ts @@ -0,0 +1,6 @@ +import { Module } from "@nestjs/common"; +import { ParcelController } from "./controller.js"; +import { ParcelService } from "./service.js"; + +@Module({ controllers: [ParcelController], providers: [ParcelService] }) +export class ParcelModule {} diff --git a/fixtures/onboarding-phase4/package.json b/fixtures/onboarding-phase4/package.json new file mode 100644 index 0000000..3ef3ab8 --- /dev/null +++ b/fixtures/onboarding-phase4/package.json @@ -0,0 +1,11 @@ +{ + "name": "parcel-workflow-fixture", + "private": true, + "dependencies": { + "@nestjs/common": "^10.0.0", + "@nestjs/bullmq": "^10.0.0", + "@nestjs/schedule": "^4.0.0", + "bullmq": "^5.0.0", + "typeorm": "^0.3.0" + } +} diff --git a/fixtures/onboarding-phase4/repository.ts b/fixtures/onboarding-phase4/repository.ts new file mode 100644 index 0000000..6df64a4 --- /dev/null +++ b/fixtures/onboarding-phase4/repository.ts @@ -0,0 +1,9 @@ +import { Repository } from "typeorm"; +import { Parcel } from "./entity.js"; + +export class ParcelRepository extends Repository<Parcel> { + async find(_id: string): Promise<Parcel | undefined> { + void _id; + return undefined; + } +} diff --git a/fixtures/onboarding-phase4/scheduled.ts b/fixtures/onboarding-phase4/scheduled.ts new file mode 100644 index 0000000..cd1450e --- /dev/null +++ b/fixtures/onboarding-phase4/scheduled.ts @@ -0,0 +1,11 @@ +import { Cron } from "@nestjs/schedule"; +import { ParcelRepository } from "./repository.js"; + +export class ParcelJobs { + constructor(private readonly repository: ParcelRepository) {} + + @Cron("0 0 * * *") + async inspect(): Promise<void> { + await this.repository.find("example"); + } +} diff --git a/fixtures/onboarding-phase4/service.ts b/fixtures/onboarding-phase4/service.ts new file mode 100644 index 0000000..3fbaca6 --- /dev/null +++ b/fixtures/onboarding-phase4/service.ts @@ -0,0 +1,20 @@ +import { InjectQueue } from "@nestjs/bullmq"; +import { Queue } from "bullmq"; +import { ParcelRepository } from "./repository.js"; + +export class ParcelService { + constructor( + @InjectQueue("parcel-jobs") private readonly queue: Queue, + @InjectQueue("other-jobs") private readonly other: Queue, + private readonly repository: ParcelRepository, + ) {} + + async dispatch() { + // Keep the read before publication so missing parcels can be reviewed by the caller. + await this.repository.find("example"); + await this.queue.add("assign-parcel", { id: "example" }); + await this.other.add("archive-parcel", { id: "example" }); + const dynamicJob = process.env.JOB_NAME ?? "unknown"; + await this.queue.add(dynamicJob, { id: "example" }); + } +} diff --git a/fixtures/onboarding-phase4/worker.ts b/fixtures/onboarding-phase4/worker.ts new file mode 100644 index 0000000..f1ebc7a --- /dev/null +++ b/fixtures/onboarding-phase4/worker.ts @@ -0,0 +1,11 @@ +import { Processor, WorkerHost } from "@nestjs/bullmq"; + +@Processor("parcel-jobs") +export class ParcelProcessor extends WorkerHost { + async process(): Promise<void> {} +} + +@Processor("elsewhere") +export class OtherProcessor extends WorkerHost { + async process(): Promise<void> {} +} diff --git a/fixtures/onboarding-plain-node/README.md b/fixtures/onboarding-plain-node/README.md new file mode 100644 index 0000000..1081a5d --- /dev/null +++ b/fixtures/onboarding-plain-node/README.md @@ -0,0 +1,5 @@ +# Parcel status demo + +This small Node.js service exposes a health check and an in-memory parcel status lookup. It does not persist parcel data. + +Run `npm start` and visit `http://localhost:3000/health`. The command is documented here; TransferKit has not verified it as part of guide generation. Set `PORT` to choose another port. diff --git a/fixtures/onboarding-plain-node/package.json b/fixtures/onboarding-plain-node/package.json new file mode 100644 index 0000000..98b23e8 --- /dev/null +++ b/fixtures/onboarding-plain-node/package.json @@ -0,0 +1,8 @@ +{ + "name": "parcel-status-demo", + "private": true, + "type": "module", + "scripts": { + "start": "node src/server.js" + } +} diff --git a/fixtures/onboarding-plain-node/src/server.js b/fixtures/onboarding-plain-node/src/server.js new file mode 100644 index 0000000..56e1415 --- /dev/null +++ b/fixtures/onboarding-plain-node/src/server.js @@ -0,0 +1,22 @@ +import { createServer } from "node:http"; + +const parcels = new Map([["parcel-1", "pending"]]); + +const server = createServer((request, response) => { + if (request.url === "/health") { + response.writeHead(200, { "content-type": "text/plain" }); + response.end("ok"); + return; + } + if (request.url?.startsWith("/parcels/")) { + const id = request.url.slice("/parcels/".length); + const status = parcels.get(id); + response.writeHead(status ? 200 : 404, { "content-type": "text/plain" }); + response.end(status ?? "missing"); + return; + } + response.writeHead(404); + response.end("unknown route"); +}); + +server.listen(Number(process.env.PORT ?? 3000)); diff --git a/fixtures/onboarding-setup/.env.example b/fixtures/onboarding-setup/.env.example new file mode 100644 index 0000000..5bf6f5a --- /dev/null +++ b/fixtures/onboarding-setup/.env.example @@ -0,0 +1,2 @@ +PORT=3000 +DATABASE_URL= diff --git a/fixtures/onboarding-setup/README.md b/fixtures/onboarding-setup/README.md new file mode 100644 index 0000000..b9c3c09 --- /dev/null +++ b/fixtures/onboarding-setup/README.md @@ -0,0 +1,11 @@ +# NestJS starter + +## Description + +NestJS framework TypeScript starter repository. + +## Installation + +```bash +npm install +``` diff --git a/fixtures/onboarding-setup/docker-compose.yml b/fixtures/onboarding-setup/docker-compose.yml new file mode 100644 index 0000000..d032150 --- /dev/null +++ b/fixtures/onboarding-setup/docker-compose.yml @@ -0,0 +1,11 @@ +services: + app: + depends_on: + - db + env_file: + - .env.local + ports: + - "4010:3000" + command: node dist/main.js + db: + image: postgres:16 diff --git a/fixtures/onboarding-setup/package.json b/fixtures/onboarding-setup/package.json new file mode 100644 index 0000000..6a9548f --- /dev/null +++ b/fixtures/onboarding-setup/package.json @@ -0,0 +1,10 @@ +{ + "name": "onboarding-setup-fixture", + "scripts": { + "build": "tsc", + "start": "node dist/main.js", + "test": "node --test", + "migration:run": "node dist/migrate.js", + "seed": "node dist/seed.js" + } +} diff --git a/fixtures/onboarding-setup/src/health.controller.ts b/fixtures/onboarding-setup/src/health.controller.ts new file mode 100644 index 0000000..c0dd7e8 --- /dev/null +++ b/fixtures/onboarding-setup/src/health.controller.ts @@ -0,0 +1,9 @@ +import { Controller, Get } from "@nestjs/common"; + +@Controller("health") +export class HealthController { + @Get() + check() { + return { status: "declared" }; + } +} diff --git a/fixtures/onboarding-setup/src/main.ts b/fixtures/onboarding-setup/src/main.ts new file mode 100644 index 0000000..ee7a30c --- /dev/null +++ b/fixtures/onboarding-setup/src/main.ts @@ -0,0 +1,5 @@ +import { NestFactory } from "@nestjs/core"; + +const port = process.env.PORT || 4000; +const app = await NestFactory.create({}); +await app.listen(port); diff --git a/package-lock.json b/package-lock.json index cd9993d..9d4d990 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "transferkit", - "version": "0.0.0", + "version": "0.3.0", "lockfileVersion": 2, "requires": true, "packages": { "": { "name": "transferkit", - "version": "0.0.0", + "version": "0.3.0", "workspaces": [ "packages/*" ], @@ -3150,10 +3150,10 @@ }, "packages/cli": { "name": "transferkit", - "version": "0.2.0", + "version": "0.3.0", "license": "MIT", "dependencies": { - "ts-morph": "^25.0.1" + "ts-morph": "^28.0.0" }, "bin": { "tk": "dist/index.js" @@ -3162,51 +3162,6 @@ "node": ">=18" } }, - "packages/cli/node_modules/@ts-morph/common": { - "version": "0.26.1", - "resolved": "https://registry.npmjs.org/@ts-morph/common/-/common-0.26.1.tgz", - "integrity": "sha512-Sn28TGl/4cFpcM+jwsH1wLncYq3FtN/BIpem+HOygfBWPT5pAeS5dB4VFVzV8FbnOKHpDLZmvAl4AjPEev5idA==", - "license": "MIT", - "dependencies": { - "fast-glob": "^3.3.2", - "minimatch": "^9.0.4", - "path-browserify": "^1.0.1" - } - }, - "packages/cli/node_modules/brace-expansion": { - "version": "2.1.7", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", - "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", - "license": "MIT", - "dependencies": { - "balanced-match": "^1.0.0" - } - }, - "packages/cli/node_modules/minimatch": { - "version": "9.0.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", - "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", - "license": "ISC", - "dependencies": { - "brace-expansion": "^2.0.2" - }, - "engines": { - "node": ">=16 || 14 >=14.17" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "packages/cli/node_modules/ts-morph": { - "version": "25.0.1", - "resolved": "https://registry.npmjs.org/ts-morph/-/ts-morph-25.0.1.tgz", - "integrity": "sha512-QJEiTdnz1YjrB3JFhd626gX4rKHDLSjSVMvGGG4v7ONc3RBwa0Eei98G9AT9uNFDMtV54JyuXsFeC+OH0n6bXQ==", - "license": "MIT", - "dependencies": { - "@ts-morph/common": "~0.26.0", - "code-block-writer": "^13.0.3" - } - }, "packages/core": { "name": "@transferkit/core", "version": "0.1.0", @@ -5030,44 +4985,7 @@ "transferkit": { "version": "file:packages/cli", "requires": { - "ts-morph": "^25.0.1" - }, - "dependencies": { - "@ts-morph/common": { - "version": "0.26.1", - "resolved": "https://registry.npmjs.org/@ts-morph/common/-/common-0.26.1.tgz", - "integrity": "sha512-Sn28TGl/4cFpcM+jwsH1wLncYq3FtN/BIpem+HOygfBWPT5pAeS5dB4VFVzV8FbnOKHpDLZmvAl4AjPEev5idA==", - "requires": { - "fast-glob": "^3.3.2", - "minimatch": "^9.0.4", - "path-browserify": "^1.0.1" - } - }, - "brace-expansion": { - "version": "2.1.7", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.7.tgz", - "integrity": "sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g==", - "requires": { - "balanced-match": "^1.0.0" - } - }, - "minimatch": { - "version": "9.0.9", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.9.tgz", - "integrity": "sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==", - "requires": { - "brace-expansion": "^2.0.2" - } - }, - "ts-morph": { - "version": "25.0.1", - "resolved": "https://registry.npmjs.org/ts-morph/-/ts-morph-25.0.1.tgz", - "integrity": "sha512-QJEiTdnz1YjrB3JFhd626gX4rKHDLSjSVMvGGG4v7ONc3RBwa0Eei98G9AT9uNFDMtV54JyuXsFeC+OH0n6bXQ==", - "requires": { - "@ts-morph/common": "~0.26.0", - "code-block-writer": "^13.0.3" - } - } + "ts-morph": "^28.0.0" } }, "ts-api-utils": { diff --git a/package.json b/package.json index e1b05f2..2c90f07 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "transferkit", - "version": "0.0.0", + "version": "0.3.0", "private": true, "type": "module", "engines": { diff --git a/packages/cli/CHANGELOG.md b/packages/cli/CHANGELOG.md index 46468fd..e8681ea 100644 --- a/packages/cli/CHANGELOG.md +++ b/packages/cli/CHANGELOG.md @@ -1,5 +1,22 @@ # Release notes +## 0.3.0 — Human-first onboarding (release candidate) + +### What's new + +- The shared `ONBOARDING.md` now starts with a source-backed repository overview, a compact glossary, selected entry stories, change and test points, and setup observations. Detailed traces remain in a collapsed appendix. +- Onboarding stories distinguish separate entries, documented statements, static trace observations, and unverified runtime outcomes. They do not force an automatic sequence between paths that merely touch the same record. +- Personal `v2:` exercises now follow the guide's mental model, stories, change map, and safe observation. Existing IDs, progress, notes, questions, and evidence remain intact; changed guide selections can surface stale links. +- Interactive terminal commands show delayed progress during repository scans and guide generation. Piped stdout and stderr remain free of spinner frames. +- Handover v3's structured plan, checklist, evidence review, and Markdown sync remain available. + +### Compatibility and limits + +- `tk handover plan` already performs a scan; running `tk handover scan` immediately before it is optional. `tk handover init` creates separate project metadata and is not needed to create a v3 plan. +- The guide is static evidence, not proof of application behavior or setup success. Business meaning and operational ownership still require a knowledgeable person. +- Generated personal workspace files are never replaced by `tk onboard workspace`; checkbox and structured progress synchronization retains conflict checks. +- No target application, installer, migration, or external service is run during guide generation. + ## 0.2.0 — Handover v3 ### What's new diff --git a/packages/cli/README.md b/packages/cli/README.md index 5452067..e7abe6d 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -1,52 +1,49 @@ # TransferKit -TransferKit is a local-first CLI for software ownership transfer. It uses repository evidence to suggest a handover plan, then gives the current and next owners a shared `HANDOVER.md` checklist. It also supports a separate personal onboarding plan. +TransferKit is a local-first CLI for engineering handover and developer onboarding. It turns repository evidence into a shared ownership checklist and a separate, source-cited newcomer guide. Static findings are starting points for people to verify; TransferKit does not run the target application. ## Install -Node.js 18 or newer is required. +Requires Node.js 18 or newer. ```bash npm install --global transferkit tk --help ``` -## Handover quick start +Run commands from the root of the repository you want to examine. -Run these commands in the repository being transferred: +## Handover ```bash -tk handover init -tk handover scan tk handover plan -# Review the suggestions and edit HANDOVER.md in the repository root +# Review suggested IDs and HANDOVER.md with the current owner. tk handover sync tk handover status ``` -`tk handover plan` writes a structured plan to `.transferkit/transfer.json` and creates `HANDOVER.md` as the meeting checklist. The Markdown guide explains its priorities, checkboxes, notes, and completion fields. Mark the items and required discussion points you covered, then run `tk handover sync` to update the structured state. `tk handover status` reports remaining work. Use `tk handover evidence` to inspect repository findings. +`plan` scans the repository, refreshes suggestions in `.transferkit/transfer.json`, and creates `HANDOVER.md` when it is missing. Suggested items cover ownership topics, actions, risks, open work, and verification. Review them with the team, edit the checklist, then run `sync` to import supported Markdown edits. `status` reports remaining work. -To review a suggestion before the meeting, use `tk handover plan accept <item-id>` or `tk handover plan reject <item-id>`. The plan command also supports renaming, reprioritizing, moving, and adding items. +Use `tk handover plan accept <item-id>` or `reject <item-id>` to review a suggestion; `rename`, `priority`, `move`, and `add` let you adapt the plan. `tk handover evidence` prints cited scanner findings. `tk handover scan` refreshes suggestions without creating a checklist. `tk handover init` creates optional project metadata; it is not required before `plan`. -## Personal onboarding +## Onboarding ```bash +tk onboard guide +tk onboard workspace tk onboard plan +# Read ONBOARDING.md and record findings in .transferkit.local/ONBOARDING.md. +tk onboard task v2:trace-flow in-progress +tk onboard sync tk onboard status -tk onboard task <task-id> in-progress -tk onboard task <task-id> completed ``` -Personal progress stays in `.transferkit.local/`. Onboarding currently uses repository findings and any legacy handover knowledge; it does not use v3 Transfer completion. +`guide` creates a shared `ONBOARDING.md` with a repository overview, key code terms, separate entry journeys, change and test locations, setup clues, and citations. Use `tk onboard guide --focus OrderController.submit` to inspect a supported symbol. Detailed source traces remain in an appendix; inferred connections and unverified outcomes are labeled. -## What's new in 0.2.0 +`workspace` creates a personal checklist once and preserves later edits. Update its checkboxes or use `task` with `not-started`, `in-progress`, `completed`, or `skipped`; `sync` imports checkbox edits. If guide paths change, `plan` and `status` flag stale links without discarding personal progress. Completion is self-reported, not a competence certificate. -- Handover v3 adds a root-level `HANDOVER.md` workspace with stable item markers and Markdown sync. -- Repository evidence helps group related ownership domains and business flows into handover topics. -- Item headings show priority and special completion type; code references are collapsible and the document includes a meeting guide. -- `tk handover status` tracks item and section progress from structured Transfer state. -- The CLI supports Node.js 18 and newer. +## Release notes — 0.3.0 candidate -See the [0.2.0 release notes](CHANGELOG.md) for compatibility details and the [repository README](https://github.com/alialaraby/transferkit#readme) for more documentation. +This release adds human-first onboarding stories and personal exercises aligned with them. Handover keeps its structured v3 plan and Markdown sync from 0.2.0. Long scans and guide generation show progress in interactive terminals. See [CHANGELOG.md](CHANGELOG.md) for details. -TransferKit runs locally and does not upload source code or make implicit AI calls. Detection is limited to supported static patterns; review suggested topics and evidence before relying on them. +TransferKit scans locally, makes no implicit AI or network calls, and does not upload source code. Dynamic behavior, business intent, and documented setup commands still need human verification. For the full command guide and limitations, see the [project README](https://github.com/alialaraby/transferkit#readme). diff --git a/packages/cli/package.json b/packages/cli/package.json index f79f1ca..6367622 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -1,6 +1,6 @@ { "name": "transferkit", - "version": "0.2.0", + "version": "0.3.0", "description": "Local-first CLI for engineering handover and onboarding workflows", "license": "MIT", "author": "Ali Alaraby", @@ -39,6 +39,6 @@ "typecheck": "tsc -b --noEmit" }, "dependencies": { - "ts-morph": "^25.0.1" + "ts-morph": "^28.0.0" } } diff --git a/packages/cli/src/cli-ux.test.ts b/packages/cli/src/cli-ux.test.ts index 319db55..2f8e691 100644 --- a/packages/cli/src/cli-ux.test.ts +++ b/packages/cli/src/cli-ux.test.ts @@ -46,7 +46,7 @@ describe("CLI experience", () => { expect(result.exitCode).toBe(0); expect(result.stdout[0]).toContain("Generated ONBOARDING.md"); const guide = await readFile(join(directory, "ONBOARDING.md"), "utf8"); - expect(guide).toContain("## Unknowns"); + expect(guide).toContain("## Specific questions"); expect(guide).toContain("Runtime unverified"); await expect( readFile(join(directory, ".transferkit.local/onboarding-progress.json")), diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts index 2b9e543..ab5ae10 100644 --- a/packages/cli/src/cli.ts +++ b/packages/cli/src/cli.ts @@ -57,6 +57,12 @@ export async function runCli( args.length === 4 && args[0] === "onboard" && args[1] === "task"; const planCommand = args[0] === "handover" && args[1] === "plan" && args.length >= 2; + const focusedGuide = + args.length === 4 && + args[0] === "onboard" && + args[1] === "guide" && + args[2] === "--focus" && + Boolean(args[3]); if (args.length === 0 || (args.length === 1 && isHelpFlag(args[0]))) { environment.stdout(usage); return 0; @@ -81,6 +87,7 @@ export async function runCli( if ( !taskUpdate && !planCommand && + !focusedGuide && (args.length !== 2 || (args[0] !== "handover" && args[0] !== "onboard")) ) { environment.stderr(`Error: invalid command usage.\n\n${usage}`); @@ -89,7 +96,12 @@ export async function runCli( try { if (args[0] === "onboard" && args[1] === "guide") { - environment.stdout(await generateOnboardingGuide(environment.cwd)); + environment.stdout( + await generateOnboardingGuide( + environment.cwd, + focusedGuide ? { focus: args[3]! } : {}, + ), + ); return 0; } @@ -277,7 +289,7 @@ const legacyHandoverCommands = new Set([ const onboardUsage = `Explore a repository and track your onboarding Usage: - tk onboard guide + tk onboard guide [--focus <route-or-symbol>] tk onboard workspace tk onboard sync tk onboard plan diff --git a/packages/cli/src/generate-onboarding-guide.test.ts b/packages/cli/src/generate-onboarding-guide.test.ts index 14b8d7e..8a98fcd 100644 --- a/packages/cli/src/generate-onboarding-guide.test.ts +++ b/packages/cli/src/generate-onboarding-guide.test.ts @@ -1,6 +1,7 @@ -import { mkdtemp, readFile, writeFile } from "node:fs/promises"; +import { cp, mkdtemp, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; -import { join } from "node:path"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; import { generateOnboardingGuide } from "./generate-onboarding-guide.js"; @@ -19,6 +20,334 @@ async function guide(directory: string): Promise<string> { } describe("shared guide regeneration", () => { + it("keeps a documented CLI input and failure path in the reading guide", async () => { + const directory = await mkdtemp(join(tmpdir(), "tk-guide-cli-story-")); + await cp( + join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-human-cli", + ), + directory, + { recursive: true }, + ); + await generateOnboardingGuide(directory); + const generated = await guide(directory); + expect(generated).toContain( + "**Alternate exit:** Documented alternate: A missing path", + ); + expect(generated).toContain("npm start -- events.jsonl"); + expect(generated).toContain( + "**Safe first investigation:** Open [src/cli.js:1]", + ); + expect(generated).not.toContain( + "Consider npm run start after prerequisites", + ); + }); + + it("renders distinct cited journeys and their related TypeORM concepts without asserting completed writes", async () => { + const directory = await mkdtemp(join(tmpdir(), "tk-guide-deep-")); + await cp( + join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-deep-guide", + ), + directory, + { recursive: true }, + ); + await generateOnboardingGuide(directory); + const generated = await guide(directory); + expect(generated.match(/### Source journey:/gu)).toHaveLength(2); + expect( + [ + "## Start here", + "## System map", + "## Concepts", + "## Connected journeys", + "## Change points", + "## Run and observe", + "## Specific questions", + "## Reference appendix", + ].map((heading) => generated.indexOf(heading)), + ).toEqual( + [ + ...[ + "## Start here", + "## System map", + "## Concepts", + "## Connected journeys", + "## Change points", + "## Run and observe", + "## Specific questions", + "## Reference appendix", + ].map((heading) => generated.indexOf(heading)), + ].sort((a, b) => a - b), + ); + expect(generated).toContain( + "<details><summary>Inventories, candidate routes, and supporting declarations</summary>", + ); + expect(generated).toContain('<a id="journey-ordercontroller-'); + expect(generated).toContain("### Source journey: LimitsController.check"); + expect(generated).toContain("**Safe first investigation:**"); + expect(generated).toContain("**Trigger and input:**"); + expect(generated).toContain("**Alternate exit:**"); + expect(generated).not.toContain("**Why read this:** OrderEntity appears"); + expect( + generated.match( + /### Source journey: OrderController\.(?:preview|submit)/gu, + ) ?? [], + ).toHaveLength(1); + expect(generated).toContain("Checks !input.valid"); + expect(generated).toContain("when input.priority"); + expect(generated).toContain("otherwise input.priority"); + expect(generated).toContain( + "runner.manager.save (write-like attempt); target unresolved", + ); + expect(generated).not.toContain("cache.save (write-like attempt)"); + expect(generated).toContain("### OrderEntity"); + expect(generated).toMatch(/\[entity\.ts:\d+\]\(entity\.ts#L\d+\)/u); + expect(generated).toContain("### AccountEntity"); + expect(generated).toContain( + "Declared ManyToOne relation account → AccountEntity", + ); + expect(generated).toContain( + "no selected journey call was linked to this entity", + ); + expect(generated).not.toContain("save succeeded"); + await writeFile( + join(directory, "ONBOARDING.md"), + generated.replace("## Concepts", "## Concepts\n\nHuman concept note."), + ); + await generateOnboardingGuide(directory); + expect(await guide(directory)).toContain("Human concept note."); + }); + + it("inserts a new Concepts section in order when upgrading a marked guide", async () => { + const directory = await mkdtemp(join(tmpdir(), "tk-guide-upgrade-")); + await cp( + join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-deep-guide", + ), + directory, + { recursive: true }, + ); + await generateOnboardingGuide(directory); + const original = await guide(directory); + const older = original.replace( + /<!-- tk:onboard:section concepts begin -->[\s\S]*?<!-- tk:onboard:section concepts end -->\n\n/u, + "Human note between sections.\n\n", + ); + await writeFile(join(directory, "ONBOARDING.md"), older); + const snapshotPath = join( + directory, + ".transferkit/onboarding-guide-snapshot.json", + ); + const snapshot = JSON.parse(await readFile(snapshotPath, "utf8")) as { + sections: Record<string, string>; + }; + delete snapshot.sections.concepts; + await writeFile(snapshotPath, JSON.stringify(snapshot)); + await generateOnboardingGuide(directory); + const upgraded = await guide(directory); + expect(upgraded).toContain("Human note between sections."); + expect(upgraded.indexOf("## Concepts")).toBeLessThan( + upgraded.indexOf("## Connected journeys"), + ); + }); + + it("upgrades older marked section headings and retains independent human context", async () => { + const directory = await fixture(); + await generateOnboardingGuide(directory); + const replacements = new Map([ + ["System map", "System overview"], + ["Connected journeys", "Explained flow"], + ["Run and observe", "Setup and operations"], + ["Specific questions", "Unknowns"], + ]); + let older = await guide(directory); + const snapshotPath = join( + directory, + ".transferkit/onboarding-guide-snapshot.json", + ); + const snapshot = JSON.parse(await readFile(snapshotPath, "utf8")) as { + sections: Record<string, string>; + }; + for (const [current, prior] of replacements) { + older = older.replace(`## ${current}`, `## ${prior}`); + for (const [id, body] of Object.entries(snapshot.sections)) + snapshot.sections[id] = body.replace(`## ${current}`, `## ${prior}`); + } + older += + "\n## System context\n\nOwner-written context stays here.\n\n## Verified local setup\n\nOwner verified this separately.\n"; + await writeFile(join(directory, "ONBOARDING.md"), older); + await writeFile(snapshotPath, JSON.stringify(snapshot)); + await generateOnboardingGuide(directory); + const upgraded = await guide(directory); + expect(upgraded).toContain("## Start here"); + expect(upgraded).toContain("## Run and observe"); + expect(upgraded).toContain("Owner-written context stays here."); + expect(upgraded).toContain("Owner verified this separately."); + expect(await generateOnboardingGuide(directory)).toContain( + "already up to date", + ); + }); + + it("keeps an empty Nest handler as a candidate", async () => { + const directory = await mkdtemp(join(tmpdir(), "tk-guide-empty-")); + await cp( + join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/realistic-nestjs", + ), + directory, + { recursive: true }, + ); + await generateOnboardingGuide(directory); + const generated = await guide(directory); + expect(generated).toContain("**Candidate routes**"); + expect(generated).not.toContain("### Source journey:"); + }); + + it("omits TypeORM concepts for a plain Node app", async () => { + const directory = await mkdtemp(join(tmpdir(), "tk-guide-node-")); + await cp( + join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-plain-node", + ), + directory, + { recursive: true }, + ); + await generateOnboardingGuide(directory); + const generated = await guide(directory); + expect(generated).not.toContain("## Concepts"); + expect(generated).toContain( + "health check and an in-memory parcel status lookup", + ); + expect(generated).toContain("README.md:3"); + expect(generated).toContain("src/server.js:1"); + }); + + it("links only a matching BullMQ publication to a possible worker continuation", async () => { + const directory = await mkdtemp(join(tmpdir(), "tk-guide-queue-")); + await cp( + join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-phase4", + ), + directory, + { recursive: true }, + ); + await generateOnboardingGuide(directory); + const generated = await guide(directory); + expect(generated).toContain("Possible continuation:"); + expect(generated).toContain("ParcelProcessor.process"); + expect(generated).toContain("Unconnected publication:"); + expect(generated).toContain("archive-parcel"); + expect(generated).toContain("These are declared handlers"); + expect(generated).toContain("ParcelJobs.inspect"); + expect(generated).toContain("calls Parcel"); + expect(generated).not.toContain("unknown on parcel-jobs"); + expect(generated).not.toContain("OtherProcessor.process is registered"); + expect(generated).toContain( + "Source comment says: Keep the read before publication", + ); + expect(generated).not.toContain("Project description (README statement)"); + }); + + it("resolves an explicit focus and rejects unknown entries without writing", async () => { + const directory = await mkdtemp(join(tmpdir(), "tk-guide-focus-")); + await cp( + join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-phase4", + ), + directory, + { recursive: true }, + ); + await expect( + generateOnboardingGuide(directory, { focus: "NoController.missing" }), + ).rejects.toThrow("did not match"); + await expect( + readFile(join(directory, "ONBOARDING.md"), "utf8"), + ).rejects.toThrow(); + await generateOnboardingGuide(directory, { + focus: "ParcelController.dispatch", + }); + expect(await guide(directory)).toContain( + "### Source journey: ParcelController.dispatch", + ); + }); + + it("selects the same neutral journeys on repeat scans and attributes a credible README description", async () => { + const source = join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-phase4", + ); + const first = await mkdtemp(join(tmpdir(), "tk-guide-stable-a-")); + const second = await mkdtemp(join(tmpdir(), "tk-guide-stable-b-")); + await cp(source, first, { recursive: true }); + await cp(source, second, { recursive: true }); + await writeFile( + join(first, "README.md"), + "# Parcel workflow\n\n## Description\n\nThis repository receives parcel dispatch requests and declares a queue worker for assignment.\n", + ); + await writeFile( + join(second, "README.md"), + "# Parcel workflow\n\n## Description\n\nThis repository receives parcel dispatch requests and declares a queue worker for assignment.\n", + ); + await generateOnboardingGuide(first); + await generateOnboardingGuide(second); + expect(await guide(first)).toBe(await guide(second)); + expect(await guide(first)).toContain( + "**Project description (README statement):** This repository receives parcel dispatch requests", + ); + expect(await guide(first)).toContain("[README.md:5](README.md#L5)"); + }); + + it("shows a proposed setup order, declared health route, and exact configuration questions without running app scripts", async () => { + const directory = await mkdtemp(join(tmpdir(), "tk-guide-setup-")); + await cp( + join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-setup", + ), + directory, + { recursive: true }, + ); + await generateOnboardingGuide(directory); + const generated = await guide(directory); + expect(generated).toContain("generic starter README command"); + expect(generated).toContain( + "**Proposed order (inferred from declarations; do not run blindly):**", + ); + expect(generated).toContain( + "**Template variable names:** DATABASE_URL, PORT", + ); + expect(generated).not.toContain("DATABASE_URL="); + expect(generated).toContain("Possible health route:"); + expect(generated).toContain("4010"); + expect(generated).toContain("4000"); + expect(generated).toContain("Are migrations or seeds needed locally"); + }); + + it("does not run a declared start script during guide generation", async () => { + const directory = await fixture(); + await writeFile( + join(directory, "package.json"), + JSON.stringify({ + scripts: { + start: + "node -e \"require('node:fs').writeFileSync('ran-app', 'yes')\"", + }, + }), + ); + await generateOnboardingGuide(directory); + await expect( + readFile(join(directory, "ran-app"), "utf8"), + ).rejects.toThrow(); + }); + it("updates unchanged generated sections and is idempotent", async () => { const directory = await fixture(); await generateOnboardingGuide(directory); @@ -49,8 +378,8 @@ describe("shared guide regeneration", () => { await generateOnboardingGuide(directory); const edited = (await guide(directory)).replace( - "## Unknowns", - "Human note.\n\n## Unknowns", + "## Specific questions", + "Human note.\n\n## Specific questions", ) + "\n## Team notes\n\nAsk the maintainer.\n"; await writeFile(join(directory, "ONBOARDING.md"), edited); await generateOnboardingGuide(directory); @@ -83,8 +412,8 @@ describe("shared guide regeneration", () => { await writeFile( join(directory, "ONBOARDING.md"), (await guide(directory)).replace( - "## Unknowns", - "## Unknowns\n\nAsk about ownership.", + "## Specific questions", + "## Specific questions\n\nAsk about ownership.", ), ); await writeFile( @@ -102,8 +431,8 @@ describe("shared guide regeneration", () => { await writeFile( join(directory, "ONBOARDING.md"), (await guide(directory)).replace( - "## Setup and operations", - "## Setup and operations\n\nHuman run note.", + "## Run and observe", + "## Run and observe\n\nHuman run note.", ), ); await writeFile( @@ -123,8 +452,8 @@ describe("shared guide regeneration", () => { await writeFile( join(directory, "ONBOARDING.md"), (await guide(directory)).replace( - "## Setup and operations", - "## Setup and operations\n\nHuman setup note.", + "## Run and observe", + "## Run and observe\n\nHuman setup note.", ), ); await writeFile( @@ -153,6 +482,30 @@ describe("shared guide regeneration", () => { expect(await guide(directory)).toBe("# Human guide\n"); }); + it("leaves stale snapshots and malformed markers untouched", async () => { + const directory = await fixture(); + await generateOnboardingGuide(directory); + const original = await guide(directory); + const snapshotFile = join( + directory, + ".transferkit/onboarding-guide-snapshot.json", + ); + const snapshot = await readFile(snapshotFile, "utf8"); + await writeFile(snapshotFile, "{invalid"); + await expect(generateOnboardingGuide(directory)).rejects.toThrow(); + expect(await guide(directory)).toBe(original); + await writeFile(snapshotFile, snapshot); + await writeFile( + join(directory, "ONBOARDING.md"), + original.replace("<!-- tk:onboard:section start-here end -->", ""), + ); + const malformed = await guide(directory); + await expect(generateOnboardingGuide(directory)).rejects.toThrow( + /malformed|missing/u, + ); + expect(await guide(directory)).toBe(malformed); + }); + it("does not restore a managed section deleted by a person", async () => { const directory = await fixture(); await generateOnboardingGuide(directory); diff --git a/packages/cli/src/generate-onboarding-guide.ts b/packages/cli/src/generate-onboarding-guide.ts index 37f5639..959f488 100644 --- a/packages/cli/src/generate-onboarding-guide.ts +++ b/packages/cli/src/generate-onboarding-guide.ts @@ -2,10 +2,24 @@ import { randomUUID } from "node:crypto"; import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; +import type { + OnboardingSelectedConcept, + OnboardingStoryInventory, +} from "@transferkit/core"; import { renderOnboardingGuide } from "@transferkit/renderers"; -import { scanRepository } from "@transferkit/scanners"; +import { + discoverOnboardingRepositoryNotes, + discoverOnboardingStoryEvidence, + scanOnboardingRepository, +} from "@transferkit/scanners"; import { explainCandidateFlows, + preselectOnboardingEntries, + selectOnboardingContinuations, + selectOnboardingStories, + selectOnboardingStoryInventory, + selectScheduledConcepts, + selectOnboardingConcepts, understandProject, } from "@transferkit/standards"; @@ -19,6 +33,7 @@ type Block = { id: string; start: number; end: number; text: string }; export async function generateOnboardingGuide( directory: string, + options: { focus?: string } = {}, ): Promise<string> { const file = join(directory, "ONBOARDING.md"); const existing = await optionalRead(file); @@ -32,13 +47,93 @@ export async function generateOnboardingGuide( "ONBOARDING.md has TransferKit markers but no valid generation snapshot; it was left untouched. Restore the snapshot before regenerating.", ); - const findings = await scanRepository(directory); + let focusSymbol: string | undefined; + let storyInventory: OnboardingStoryInventory | undefined; + const { findings, traces, concepts, queues, scheduledCalls } = + await scanOnboardingRepository(directory, async (scanned, context) => { + storyInventory = selectOnboardingStoryInventory( + await discoverOnboardingStoryEvidence( + directory, + scanned, + context.concepts, + ), + ); + const preliminary = preselectOnboardingEntries( + scanned, + context.queues, + context.scheduledCalls, + options.focus, + storyInventory, + ); + focusSymbol = preliminary.focusSymbol; + return preliminary.entries; + }); const model = understandProject(findings); + const storySelection = selectOnboardingStories( + traces, + storyInventory!, + concepts, + queues, + focusSymbol, + ); + const selected = storySelection.chapters.flatMap((chapter) => + chapter.trace ? [{ trace: chapter.trace, reason: chapter.reason }] : [], + ); + const selectedConcepts = mergeConcepts( + selected.flatMap((item) => selectOnboardingConcepts(item.trace, concepts)), + ); + const repositoryNotes = await discoverOnboardingRepositoryNotes( + directory, + selected.map((item) => item.trace), + findings, + ); + const displayedSymbols = new Set([ + ...(focusSymbol ? [focusSymbol] : []), + ...selected.map((item) => item.trace.entry.symbol), + ...storySelection.rejected.map((item) => item.entry), + ]); + const displayFlowIds = model.candidateFlows + .filter((flow) => + flow.sourceFindingIds.some((id) => + findings.some((finding) => { + if (finding.id !== id || finding.kind !== "application.route") + return false; + const data = finding.data as Record<string, unknown>; + return displayedSymbols.has(`${data.controller}.${data.method}`); + }), + ), + ) + .map((flow) => flow.id); + if (!displayFlowIds.length) + displayFlowIds.push( + ...model.candidateFlows.slice(0, 3).map((flow) => flow.id), + ); const proposed = markSections( renderOnboardingGuide( model, findings, explainCandidateFlows(model, findings), + { + journeys: selected.map((item) => ({ + trace: item.trace, + reason: item.reason, + continuations: selectOnboardingContinuations(item.trace, queues), + })), + concepts: selectedConcepts, + scheduled: selectScheduledConcepts( + scheduledCalls, + concepts, + selectedConcepts, + ), + displayFlowIds, + rejected: storySelection.rejected.map((item) => ({ + symbol: item.entry, + reason: item.reason, + })), + repositoryNotes, + storyInventory: storyInventory!, + storySelection, + }, ), ); const generated = parseBlocks(proposed); @@ -101,9 +196,17 @@ export async function generateOnboardingGuide( merged = merged.slice(0, block.start) + replacement + merged.slice(block.end); } - for (const block of generated) - if (!currentIds.has(block.id)) - merged = `${merged.trimEnd()}\n\n${block.text}\n`; + for (const [index, block] of generated.entries()) + if (!currentIds.has(block.id)) { + const currentBlocks = parseBlocks(merged); + const following = generated + .slice(index + 1) + .map((item) => currentBlocks.find((current) => current.id === item.id)) + .find((item) => item !== undefined); + merged = following + ? `${merged.slice(0, following.start)}${block.text}\n\n${merged.slice(following.start)}` + : `${merged.trimEnd()}\n\n${block.text}\n`; + } if (merged.startsWith(oldGeneratedIntroduction)) merged = proposed.slice(0, generated[0]!.start) + @@ -129,16 +232,50 @@ export async function generateOnboardingGuide( return "Regenerated ONBOARDING.md; human text was preserved. Runtime behavior remains unverified."; } +function mergeConcepts( + items: OnboardingSelectedConcept[], +): OnboardingSelectedConcept[] { + const result = new Map<string, OnboardingSelectedConcept>(); + for (const item of items) { + const key = `${item.entity.name}:${item.entity.declaration.file}:${item.entity.declaration.line}`; + const prior = result.get(key); + if (!prior) + result.set(key, { entity: item.entity, calls: [...item.calls] }); + else + for (const call of item.calls) + if ( + !prior.calls.some( + (value) => + value.at.file === call.at.file && value.at.line === call.at.line, + ) + ) + prior.calls.push(call); + } + return [...result.values()].sort( + (a, b) => + b.calls.length - a.calls.length || + a.entity.name.localeCompare(b.entity.name), + ); +} + function markSections(source: string): string { const headers = [...source.matchAll(/^## (.+)$/gmu)]; if (!headers.length) throw new Error("Generated guide has no sections"); + const stableIds: Record<string, string> = { + "System map": "system-overview", + "Connected journeys": "explained-flow", + "Run and observe": "setup-and-operations", + "Specific questions": "unknowns", + }; let marked = source.slice(0, headers[0]!.index); for (let index = 0; index < headers.length; index++) { const header = headers[index]!; - const id = header[1]! - .toLowerCase() - .replace(/[^a-z0-9]+/gu, "-") - .replace(/^-|-$/gu, ""); + const id = + stableIds[header[1]!] ?? + header[1]! + .toLowerCase() + .replace(/[^a-z0-9]+/gu, "-") + .replace(/^-|-$/gu, ""); const body = source .slice(header.index, headers[index + 1]?.index ?? source.length) .trimEnd(); diff --git a/packages/cli/src/generate-onboarding-workspace.test.ts b/packages/cli/src/generate-onboarding-workspace.test.ts index 80c0046..6190a51 100644 --- a/packages/cli/src/generate-onboarding-workspace.test.ts +++ b/packages/cli/src/generate-onboarding-workspace.test.ts @@ -1,9 +1,17 @@ -import { mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises"; +import { cp, mkdtemp, mkdir, readFile, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; +import { dirname } from "node:path"; +import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; import { generateOnboardingWorkspace } from "./generate-onboarding-workspace.js"; +import { generateOnboardingGuide } from "./generate-onboarding-guide.js"; +import { + setPersonalExerciseStatus, + syncPersonalOnboarding, +} from "./personal-onboarding-sync.js"; +import { runCli } from "./index.js"; const sections = [ ["system-overview", "## System overview\nObserved entry point."], @@ -66,10 +74,13 @@ describe("personal onboarding workspace", () => { ); await generateOnboardingWorkspace(directory); const output = await workspace(directory); - expect(output).toContain("Check one explained static flow"); + expect(output).toContain("Check one connected journey"); expect(output).toContain( "documented commands are runtime unverified until tried", ); + expect(output).toContain( + "| Date | Exact command or safe check | Observed result | Blocker |", + ); expect(output).not.toContain("legacy"); expect( await readFile( @@ -93,6 +104,136 @@ describe("personal onboarding workspace", () => { expect(await workspace(directory)).toBe(edited); }); + it("preserves a dated personal attempt observation through sync", async () => { + const directory = await fixture(); + await generateOnboardingWorkspace(directory); + const recorded = (await workspace(directory)).replace( + "| | | | |", + "| 2026-10-01 | npm run start | Connection refused | Database unavailable |", + ); + await writeFile( + join(directory, ".transferkit.local/ONBOARDING.md"), + recorded, + ); + await syncPersonalOnboarding(directory); + expect(await workspace(directory)).toContain( + "| 2026-10-01 | npm run start | Connection refused | Database unavailable |", + ); + }); + + it("keeps stable progress and notes while flagging a disappeared guide journey", async () => { + const directory = await mkdtemp(join(tmpdir(), "tk-workspace-stale-")); + await cp( + join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-phase4", + ), + directory, + { recursive: true }, + ); + await generateOnboardingGuide(directory); + await generateOnboardingWorkspace(directory); + const personalFile = join(directory, ".transferkit.local/ONBOARDING.md"); + const original = await workspace(directory); + expect(original).toContain( + "ParcelController.dispatch and ParcelJobs.inspect", + ); + await writeFile(personalFile, `${original}\nMy own source notes.\n`); + await setPersonalExerciseStatus(directory, "v2:trace-flow", "completed"); + const retained = await workspace(directory); + const planOutputs: string[] = []; + expect( + await runCli(["onboard", "plan"], { + cwd: directory, + stdout: (value) => planOutputs.push(value), + stderr: () => undefined, + }), + ).toBe(0); + expect(planOutputs.join("\n")).toContain( + "Focus: Explain ParcelController.dispatch and ParcelJobs.inspect", + ); + const shared = await readFile(join(directory, "ONBOARDING.md"), "utf8"); + await writeFile( + join(directory, "ONBOARDING.md"), + shared.replaceAll( + "### Source journey: ParcelJobs.inspect", + "### Source journey: ParcelJobs.changed", + ), + ); + const outputs: string[] = []; + expect( + await runCli(["onboard", "status"], { + cwd: directory, + stdout: (value) => outputs.push(value), + stderr: () => undefined, + }), + ).toBe(0); + expect(outputs.join("\n")).toContain( + "Stale guide link: ParcelJobs.inspect", + ); + expect(outputs.join("\n")).toContain("Trace a flow: completed"); + expect(await workspace(directory)).toBe(retained); + expect(retained).toContain("My own source notes."); + }); + + it("links a documented CLI entry and flags it when guide selection changes", async () => { + const directory = await mkdtemp(join(tmpdir(), "tk-workspace-cli-stale-")); + await cp( + join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-human-cli", + ), + directory, + { recursive: true }, + ); + await generateOnboardingGuide(directory); + await generateOnboardingWorkspace(directory); + const personalFile = join(directory, ".transferkit.local/ONBOARDING.md"); + const initial = await workspace(directory); + expect(initial).toContain("<!-- tk:onboard:linked-journey event-count -->"); + expect(initial).toContain("../ONBOARDING.md#change-points"); + expect(initial).toContain("Read Start here and System map"); + await writeFile( + personalFile, + `${initial + .replace( + "_Add questions for a person or a runtime check._", + "Who owns event validation?", + ) + .replace( + "_Add file references, commands tried, and results observed._", + "src/cli.js:1 — inspect input handling.", + )}\nMy own input observation.\n`, + ); + await setPersonalExerciseStatus(directory, "v2:trace-flow", "completed"); + const retained = await workspace(directory); + const stateFile = join(directory, ".transferkit.local/onboarding-v2.json"); + const state = await readFile(stateFile, "utf8"); + const shared = await readFile(join(directory, "ONBOARDING.md"), "utf8"); + await writeFile( + join(directory, "ONBOARDING.md"), + shared.replace( + "### Entry to inspect: event-count", + "### Entry to inspect: other-command", + ), + ); + const outputs: string[] = []; + expect( + await runCli(["onboard", "status"], { + cwd: directory, + stdout: (value) => outputs.push(value), + stderr: () => undefined, + }), + ).toBe(0); + expect(outputs.join("\n")).toContain("Stale guide link: event-count"); + expect(outputs.join("\n")).toContain("Trace a flow: completed"); + expect(await workspace(directory)).toBe(retained); + expect(retained).toContain("My own input observation."); + expect(retained).toContain("Who owns event validation?"); + expect(retained).toContain("src/cli.js:1 — inspect input handling."); + expect(await readFile(stateFile, "utf8")).toBe(state); + }); + it("requires a marked shared guide", async () => { const directory = await mkdtemp(join(tmpdir(), "tk-workspace-no-guide-")); await expect(generateOnboardingWorkspace(directory)).rejects.toThrow( diff --git a/packages/cli/src/generate-onboarding-workspace.ts b/packages/cli/src/generate-onboarding-workspace.ts index dbcf1cc..717e027 100644 --- a/packages/cli/src/generate-onboarding-workspace.ts +++ b/packages/cli/src/generate-onboarding-workspace.ts @@ -44,11 +44,14 @@ export async function generateOnboardingWorkspace( "Shared ONBOARDING.md has no TransferKit section markers; run 'tk onboard guide' to create a managed guide first.", ); const explained = /^### /mu.test(sections.get("explained-flow") ?? ""); - const candidates = /^### /mu.test(sections.get("candidate-flows") ?? ""); + const candidates = /\*\*Route candidate:\*\*/u.test( + sections.get("candidate-flows") ?? sections.get("reference-appendix") ?? "", + ); const exercises = personalOnboardingExercises( new Set(sections.keys()), explained, candidates, + sections, ); await mkdir(join(directory, ".transferkit.local"), { recursive: true }); try { diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts index d111f78..dc73f47 100644 --- a/packages/cli/src/index.ts +++ b/packages/cli/src/index.ts @@ -5,6 +5,7 @@ import { readFileSync, realpathSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { runCli } from "./cli.js"; +import { startTerminalProgress } from "./terminal-progress.js"; export { dependencies, packageName, @@ -32,15 +33,23 @@ if ( ? createPipedPrompt(readFileSync(0, "utf8")) : undefined; + const progress = startTerminalProgress(args, process.stderr); try { process.exitCode = await runCli(args, { cwd: process.cwd(), - stdout: console.log, - stderr: console.error, + stdout: (message) => { + progress.stop(); + console.log(message); + }, + stderr: (message) => { + progress.stop(); + console.error(message); + }, prompt: (message) => terminal ? terminal.question(message) : pipedPrompt!(message), }); } finally { + progress.stop(); terminal?.close(); } } diff --git a/packages/cli/src/onboarding-v2-cli.test.ts b/packages/cli/src/onboarding-v2-cli.test.ts index 38eb135..6c3e1bc 100644 --- a/packages/cli/src/onboarding-v2-cli.test.ts +++ b/packages/cli/src/onboarding-v2-cli.test.ts @@ -66,7 +66,7 @@ describe("onboard v2 CLI display", () => { expect(positions.every((position) => position >= 0)).toBe(true); expect(positions).toEqual([...positions].sort((a, b) => a - b)); expect(plan.output).toContain("Understand the system [completed]"); - expect(plan.output).toContain("Goal: Write a short system map"); + expect(plan.output).toContain("Goal: Write a short mental model"); expect(plan.output).toContain("Read: ONBOARDING.md#system-overview"); expect(plan.output).not.toContain("Review scheduled job"); }); diff --git a/packages/cli/src/onboarding-v2-view.ts b/packages/cli/src/onboarding-v2-view.ts index fc84afd..a0d4a10 100644 --- a/packages/cli/src/onboarding-v2-view.ts +++ b/packages/cli/src/onboarding-v2-view.ts @@ -17,6 +17,7 @@ export interface OnboardingV2View { questions: string[]; unknowns: string[]; syncNeeded: boolean; + staleJourneys: string[]; } export async function readOnboardingV2View(directory: string): Promise<{ @@ -56,8 +57,31 @@ export async function readOnboardingV2View(directory: string): Promise<{ const exercises = personalOnboardingExercises( new Set(sections.keys()), /^### /mu.test(sections.get("explained-flow") ?? ""), - /^### /mu.test(sections.get("candidate-flows") ?? ""), + /\*\*Route candidate:\*\*/u.test( + sections.get("candidate-flows") ?? + sections.get("reference-appendix") ?? + "", + ), + sections, ); + const currentJourneys = new Set( + [ + ...(sections.get("explained-flow") ?? "").matchAll( + /^### (?:Source journey|Entry to inspect): (.+)$/gmu, + ), + ].map((match) => match[1]!), + ); + const staleJourneys = [ + ...personal.matchAll(/^<!-- tk:onboard:linked-journey ([^ ]+) -->$/gmu), + ] + .map((match) => { + try { + return decodeURIComponent(match[1]!); + } catch { + return match[1]!; + } + }) + .filter((symbol) => !currentJourneys.has(symbol)); return { view: { exercises, @@ -69,6 +93,7 @@ export async function readOnboardingV2View(directory: string): Promise<{ checkboxes.some( ({ id, checked }) => state.markdownSnapshot[id].checked !== checked, ), + staleJourneys, }, fallbackHint: "", }; diff --git a/packages/cli/src/terminal-progress.test.ts b/packages/cli/src/terminal-progress.test.ts new file mode 100644 index 0000000..5b8b742 --- /dev/null +++ b/packages/cli/src/terminal-progress.test.ts @@ -0,0 +1,38 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +import { startTerminalProgress } from "./terminal-progress.js"; + +afterEach(() => vi.useRealTimers()); + +describe("terminal progress", () => { + it("shows delayed progress for a long guide operation and clears it", () => { + vi.useFakeTimers(); + const chunks: string[] = []; + const progress = startTerminalProgress(["onboard", "guide"], { + isTTY: true, + write: (chunk) => chunks.push(chunk), + }); + vi.advanceTimersByTime(179); + expect(chunks).toEqual([]); + vi.advanceTimersByTime(201); + expect(chunks.join("")).toContain("Building onboarding guide..."); + progress.stop(); + const afterStop = chunks.length; + expect(chunks.at(-1)).toBe("\r\x1b[2K"); + vi.advanceTimersByTime(500); + expect(chunks).toHaveLength(afterStop); + }); + + it("keeps redirected output and quick commands clean", () => { + vi.useFakeTimers(); + const chunks: string[] = []; + const output = { write: (chunk: string) => chunks.push(chunk) }; + startTerminalProgress(["handover", "scan"], output); + startTerminalProgress(["handover", "status"], { + ...output, + isTTY: true, + }); + vi.advanceTimersByTime(500); + expect(chunks).toEqual([]); + }); +}); diff --git a/packages/cli/src/terminal-progress.ts b/packages/cli/src/terminal-progress.ts new file mode 100644 index 0000000..98aa400 --- /dev/null +++ b/packages/cli/src/terminal-progress.ts @@ -0,0 +1,51 @@ +export interface ProgressOutput { + isTTY?: boolean; + write(chunk: string): unknown; +} + +const frames = ["|", "/", "-", "\\"]; + +export function startTerminalProgress( + args: readonly string[], + output: ProgressOutput, +): { stop(): void } { + const label = progressLabel(args); + if (!output.isTTY || !label) return { stop: () => undefined }; + + let visible = false; + let frame = 0; + let interval: ReturnType<typeof setInterval> | undefined; + const delay = setTimeout(() => { + visible = true; + const draw = () => { + output.write(`\r\x1b[2K${frames[frame++ % frames.length]} ${label}`); + }; + draw(); + interval = setInterval(draw, 100); + }, 180); + return { + stop: () => { + clearTimeout(delay); + if (interval) clearInterval(interval); + if (visible) { + output.write("\r\x1b[2K"); + visible = false; + } + }, + }; +} + +function progressLabel(args: readonly string[]): string | undefined { + if (args[0] === "handover") { + if (["scan", "evidence"].includes(args[1] ?? "")) + return "Scanning repository..."; + if (args[1] === "plan" && args.length === 2) + return "Preparing handover plan..."; + } + if (args[0] === "onboard") { + if (args[1] === "guide") return "Building onboarding guide..."; + if (["plan", "status"].includes(args[1] ?? "")) + return "Preparing onboarding view..."; + } + return undefined; +} diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index 7936a27..cb456b8 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -14,6 +14,8 @@ export * from "./interview.js"; export * from "./knowledge-gaps.js"; export * from "./onboarding-plan.js"; export * from "./onboarding-progress.js"; +export * from "./onboarding-trace.js"; +export * from "./onboarding-story.js"; export * from "./personal-onboarding.js"; export * from "./ownership-readiness.js"; export * from "./secret-protection.js"; diff --git a/packages/core/src/onboarding-story.ts b/packages/core/src/onboarding-story.ts new file mode 100644 index 0000000..c82c9f2 --- /dev/null +++ b/packages/core/src/onboarding-story.ts @@ -0,0 +1,87 @@ +import type { Evidence } from "./index.js"; +import type { OnboardingTrace } from "./onboarding-trace.js"; + +export type OnboardingStoryClaimKind = + | "purpose" + | "role" + | "entry" + | "artifact" + | "output" + | "boundary" + | "observation"; + +export interface OnboardingStoryClaim { + kind: OnboardingStoryClaimKind; + text: string; + basis: "repository-statement" | "code-observation"; + evidence: Evidence[]; + name?: string; +} + +export interface OnboardingStoryTerm { + name: string; + codeRole: string; + meaning?: OnboardingStoryClaim; + evidence: Evidence[]; + relationCount: number; + relations: { property: string; target: string; evidence: Evidence[] }[]; +} + +export interface OnboardingStoryEvidence { + claims: OnboardingStoryClaim[]; + terms: OnboardingStoryTerm[]; + rejectedDescriptions: { + text: string; + evidence: Evidence[]; + reason: string; + }[]; +} + +export interface OnboardingStoryInventory { + purpose?: OnboardingStoryClaim; + roles: OnboardingStoryClaim[]; + entries: OnboardingStoryClaim[]; + artifacts: OnboardingStoryClaim[]; + outputs: OnboardingStoryClaim[]; + boundaries: OnboardingStoryClaim[]; + observations: OnboardingStoryClaim[]; + terms: OnboardingStoryTerm[]; + rejectedDescriptions: OnboardingStoryEvidence["rejectedDescriptions"]; + unknowns: string[]; +} + +export type OnboardingStoryConnectionKind = + | "direct-call" + | "possible-async-continuation" + | "shared-artifact" + | "documented-relation" + | "unproven-association"; + +export interface OnboardingStoryConnection { + from: string; + to: string; + kind: OnboardingStoryConnectionKind; + explanation: string; + evidence: Evidence[]; +} + +export interface OnboardingStoryChapter { + id: string; + role: "representative" | "complementary" | "focused"; + entry: OnboardingStoryClaim; + input?: OnboardingStoryClaim; + output?: OnboardingStoryClaim; + trace?: OnboardingTrace; + reason: string; + decision?: Evidence; + result?: Evidence; + alternate?: Evidence; + firstUnsupportedBoundary?: { reason: string; evidence: Evidence[] }; + inspectNext: Evidence[]; +} + +export interface OnboardingStorySelection { + chapters: OnboardingStoryChapter[]; + connections: OnboardingStoryConnection[]; + rejected: { entry: string; reason: string }[]; +} diff --git a/packages/core/src/onboarding-trace.ts b/packages/core/src/onboarding-trace.ts new file mode 100644 index 0000000..0965ae2 --- /dev/null +++ b/packages/core/src/onboarding-trace.ts @@ -0,0 +1,153 @@ +export interface OnboardingTraceLocation { + file: string; + line: number; + endLine: number; + symbol?: string; + origin: "code"; +} + +export interface OnboardingTraceEvent { + kind: "branch" | "return" | "throw" | "call" | "assignment"; + detail: string; + at: OnboardingTraceLocation; + path: string[]; + awaited?: boolean; + effect?: "read-like" | "write-like" | "transaction-like"; +} + +export interface OnboardingTraceCallEdge { + caller: string; + site: OnboardingTraceLocation; + declaredTarget?: string; + declaration?: OnboardingTraceLocation; + kind: "direct" | "declared-target" | "candidate" | "unresolved"; + evaluation?: "nested-argument"; + path: string[]; +} + +export interface OnboardingTraceGap { + reason: string; + at: OnboardingTraceLocation; + path: string[]; +} + +export interface OnboardingTraceMethod { + symbol: string; + declaration: OnboardingTraceLocation; + events: OnboardingTraceEvent[]; +} + +export interface OnboardingTrace { + id: string; + entry: { + symbol: string; + kind?: "route" | "scheduled"; + verb?: string; + path?: string; + schedule?: string; + declaration: OnboardingTraceLocation; + }; + methods: OnboardingTraceMethod[]; + calls: OnboardingTraceCallEdge[]; + gaps: OnboardingTraceGap[]; +} + +export interface OnboardingRepositoryNote { + kind: "description" | "entry" | "comment" | "test" | "migration"; + text: string; + file: string; + line: number; + journey?: string; +} + +export interface OnboardingEntity { + name: string; + declaration: OnboardingTraceLocation; + fields: { name: string; at: OnboardingTraceLocation }[]; + relations: { + property: string; + target: string; + kind: string; + at: OnboardingTraceLocation; + }[]; +} + +export interface OnboardingRepositoryBinding { + repository: string; + entity: string; + at: OnboardingTraceLocation; +} + +export interface OnboardingRepositoryMethodResult { + repository: string; + method: string; + entity: string; + at: OnboardingTraceLocation; +} + +export interface OnboardingInjectedRepository { + owner: string; + property: string; + repository: string; + at: OnboardingTraceLocation; +} + +export interface OnboardingConceptEvidence { + entities: OnboardingEntity[]; + repositories: OnboardingRepositoryBinding[]; + methodResults: OnboardingRepositoryMethodResult[]; + injections: OnboardingInjectedRepository[]; +} + +export interface OnboardingSelectedConcept { + entity: OnboardingEntity; + calls: { + effect: "read-like" | "write-like" | "unspecified"; + at: OnboardingTraceLocation; + }[]; +} + +export interface OnboardingQueuePublication { + caller: string; + queue: string; + job: string; + at: OnboardingTraceLocation; + injection: OnboardingTraceLocation; + path?: string[]; +} + +export interface OnboardingQueueHandler { + queue: string; + symbol: string; + registration: OnboardingTraceLocation; + declaration: OnboardingTraceLocation; +} + +export interface OnboardingQueueEvidence { + publications: OnboardingQueuePublication[]; + handlers: OnboardingQueueHandler[]; +} + +export interface OnboardingQueueContinuation { + publication: OnboardingQueuePublication; + handler?: OnboardingQueueHandler; + reason?: string; +} + +export interface OnboardingScheduledCall { + job: string; + schedule?: string; + registration: OnboardingTraceLocation; + at: OnboardingTraceLocation; + detail: string; + effect?: "read-like" | "write-like"; +} + +export interface OnboardingScheduledConcept { + job: string; + schedule?: string; + registration: OnboardingTraceLocation; + entity: string; + effect: "read-like" | "write-like" | "unspecified"; + at: OnboardingTraceLocation; +} diff --git a/packages/core/src/personal-onboarding.ts b/packages/core/src/personal-onboarding.ts index 29d7932..ad24d8f 100644 --- a/packages/core/src/personal-onboarding.ts +++ b/packages/core/src/personal-onboarding.ts @@ -4,6 +4,7 @@ export interface PersonalOnboardingExercise { objective: string; guideSectionId: string; outcome: string; + linkedJourneys?: readonly string[]; } export const personalOnboardingExerciseIds = [ diff --git a/packages/renderers/src/index.ts b/packages/renderers/src/index.ts index e2e2813..2cae0c7 100644 --- a/packages/renderers/src/index.ts +++ b/packages/renderers/src/index.ts @@ -14,7 +14,12 @@ export const dependencies = [corePackageName] as const; export { renderHandoverPackageV2 } from "./handover-package-v2.js"; export { renderTransferHandover } from "./transfer-handover.js"; export { renderHandoverCoverageAudit } from "./handover-coverage-audit.js"; -export { renderOnboardingGuide } from "./onboarding-guide.js"; +export { + renderOnboardingGuide, + selectOnboardingFlows, + type OnboardingGuideOptions, + type OnboardingGuideJourney, +} from "./onboarding-guide.js"; export { renderHandoverPackage, diff --git a/packages/renderers/src/onboarding-guide.test.ts b/packages/renderers/src/onboarding-guide.test.ts index c8bf085..c62c590 100644 --- a/packages/renderers/src/onboarding-guide.test.ts +++ b/packages/renderers/src/onboarding-guide.test.ts @@ -82,9 +82,9 @@ const findings: Finding[] = [ describe("repository-only onboarding guide", () => { it("labels evidence and uncertainty without asserting an explained flow or working setup", () => { const guide = renderOnboardingGuide(model, findings); - expect(guide).toContain("## System overview"); - expect(guide).toContain("## Architecture relationships"); - expect(guide).toContain("## Candidate flows"); + expect(guide).toContain("## System map"); + expect(guide).toContain("**Architecture declarations and references**"); + expect(guide).toContain("**Candidate routes**"); expect(guide).toContain("**Bootstrap:** src/main.ts creates AppModule"); expect(guide).toContain("DebtController → DebtService"); expect(guide).toContain("**Route candidate:** POST /debt"); @@ -129,8 +129,8 @@ describe("repository-only onboarding guide", () => { }, ]); const explained = guide - .split("## Explained flow\n")[1]! - .split("## Candidate flows")[0]; + .split("## Connected journeys\n")[1]! + .split("## Change points")[0]; expect(explained).toContain( "1. The handler directly calls the service method.", ); @@ -210,11 +210,9 @@ describe("repository-only onboarding guide", () => { })); const guide = renderOnboardingGuide(expanded, findings, explanations); const explained = guide - .split("## Explained flow\n")[1]! - .split("## Candidate flows")[0]; - const candidate = guide - .split("## Candidate flows\n")[1]! - .split("## Setup and operations")[0]; + .split("## Connected journeys\n")[1]! + .split("## Change points")[0]; + const candidate = guide.split("**Candidate routes**\n")[1]!; expect(explained).toContain("### Debt add"); expect(explained).toContain("### Debt consent"); expect(explained).not.toContain("### Payment submit"); @@ -223,7 +221,7 @@ describe("repository-only onboarding guide", () => { const weakSecond = renderOnboardingGuide(expanded, findings, [ explanations[0]!, ]); - expect(weakSecond.split("## Candidate flows\n")[1]).toContain( + expect(weakSecond.split("**Candidate routes**\n")[1]).toContain( "### Debt consent", ); }); @@ -312,9 +310,7 @@ describe("repository-only onboarding guide", () => { evidence, })), ]); - const flows = guide - .split("## Candidate flows\n")[1]! - .split("## Setup and operations")[0]; + const flows = guide.split("**Candidate routes**\n")[1]!; expect(flows).toContain("### Debt add"); expect(flows).toContain("### Debt approve extension"); expect(flows).toContain("### Payment submit"); @@ -324,9 +320,7 @@ describe("repository-only onboarding guide", () => { renderOnboardingGuide( { ...expanded, candidateFlows: [...expanded.candidateFlows].reverse() }, findings, - ) - .split("## Candidate flows\n")[1]! - .split("## Setup and operations")[0], + ).split("**Candidate routes**\n")[1]!, ).toBe(flows); expect(guide).toContain("Feature19Module"); expect(guide).not.toMatch(/130 configuration references|UNRELATED_/u); @@ -363,10 +357,10 @@ it("renders the port contradiction as a question and redacts configuration value }, ]); const setup = guide - .split("## Setup and operations\n")[1]! - .split("## Unknowns")[0]!; + .split("## Run and observe\n")[1]! + .split("## Specific questions")[0]!; expect(setup).toContain( - "**Install:** `npm install` (documented in `README.md:10`)", + "**Install:** `npm install` (documented command at `README.md:10`; not run)", ); expect(setup).toContain("Is PORT set to the mapped container port?"); expect(setup).toContain("DB_PASSWORD"); @@ -681,9 +675,7 @@ it("ranks a source-rich route without using payment or consent vocabulary", () = richTrace("decide"), richTrace("verify-email"), ]); - const candidates = guide - .split("## Candidate flows\n")[1]! - .split("## Setup and operations")[0]!; + const candidates = guide.split("**Candidate routes**\n")[1]!; expect(candidates).toContain("### Order decide"); expect(candidates).not.toContain("### Order create"); expect(candidates).not.toContain("### Order verify-email"); diff --git a/packages/renderers/src/onboarding-guide.ts b/packages/renderers/src/onboarding-guide.ts index fd3c180..7e4e33e 100644 --- a/packages/renderers/src/onboarding-guide.ts +++ b/packages/renderers/src/onboarding-guide.ts @@ -4,10 +4,18 @@ import type { Evidence, ExplainedFlow, Finding, + OnboardingTrace, + OnboardingSelectedConcept, + OnboardingQueueContinuation, + OnboardingRepositoryNote, + OnboardingScheduledConcept, + OnboardingStoryInventory, + OnboardingStorySelection, ProjectModel, RouteTrace, } from "@transferkit/core"; import { sanitizeHandoverValue } from "./handover-package.js"; +import { renderHumanOnboardingGuide } from "./onboarding-human-story.js"; const genericIntegrations = new Set([ "axios", @@ -19,11 +27,34 @@ const genericIntegrations = new Set([ "unknown http integration", ]); +export interface OnboardingGuideJourney { + trace: OnboardingTrace; + reason: string; + continuations: readonly OnboardingQueueContinuation[]; +} + +export interface OnboardingGuideOptions { + journeys?: readonly OnboardingGuideJourney[]; + concepts?: readonly OnboardingSelectedConcept[]; + scheduled?: readonly OnboardingScheduledConcept[]; + displayFlowIds?: readonly string[]; + rejected?: readonly { symbol: string; reason: string }[]; + repositoryNotes?: readonly OnboardingRepositoryNote[]; + storyInventory?: OnboardingStoryInventory; + storySelection?: OnboardingStorySelection; +} + export function renderOnboardingGuide( model: ProjectModel, findings: readonly Finding[], explanations: readonly ExplainedFlow[] = [], + options: OnboardingGuideOptions = {}, ): string { + const journeys = options.journeys ?? []; + const deepTrace = journeys[0]?.trace; + const concepts = options.concepts ?? []; + const scheduled = options.scheduled ?? []; + const repositoryNotes = options.repositoryNotes ?? []; const named = (kind: string): Finding[] => findings.filter((finding) => finding.kind === kind); const data = (finding: Finding, key: string): string | undefined => { @@ -47,11 +78,17 @@ export function renderOnboardingGuide( const components = new Map( model.components.map((component) => [component.id, component]), ); - const flows = selectFlows(model.candidateFlows, model, findings); + const flows = options.displayFlowIds + ? options.displayFlowIds.flatMap((id) => + model.candidateFlows.filter((flow) => flow.id === id), + ) + : selectOnboardingFlows(model.candidateFlows, model, findings); const eligible = flows.flatMap((flow) => - explanations.filter((item) => - flow.sourceFindingIds.includes(item.routeFindingId), - ), + options.journeys + ? [] + : explanations.filter((item) => + flow.sourceFindingIds.includes(item.routeFindingId), + ), ); const first = eligible[0]; const firstStart = flows.find((flow) => @@ -132,6 +169,18 @@ export function renderOnboardingGuide( "", "## System overview", "", + ...repositoryNotes + .filter((note) => note.kind === "description") + .flatMap((note) => [ + `**Project description (README statement):** ${safe(note.text)} ${sourceLink(note)}`, + "", + ]), + ...repositoryNotes + .filter((note) => note.kind === "entry") + .flatMap((note) => [ + `**JavaScript entry (package start script):** ${safe(note.text)} ${sourceLink(note)}`, + "", + ]), ...fact( "Bootstrap", `${entryFiles.join(", ")} creates ${unique(names("application.entry-point", "module")).join(", ")}`, @@ -186,7 +235,12 @@ export function renderOnboardingGuide( names("scheduled-job").length > 0, ), ]; - if (lines.at(-1) === "") + if ( + lines.at(-1) === "" && + !repositoryNotes.some( + (note) => note.kind === "description" || note.kind === "entry", + ) + ) lines.push( "No system components were identified from supported static evidence.", ); @@ -262,12 +316,112 @@ export function renderOnboardingGuide( ); } lines.push(...details(relationships.flatMap((item) => item.evidence)), ""); - if (explained.length) + if (concepts.length) { + const selectedNames = new Set(concepts.map((item) => item.entity.name)); + lines.push( + "## Concepts", + "", + "TypeORM declarations and statically selected calls near the source journey. Names and call shapes do not establish business meaning or completed database effects.", + "", + ); + const storeEvidence = named("database"); + if (storeEvidence.length) + lines.push( + `**Declared data store:** ${safe(names("database").join(", "))} (${unique(storeEvidence.flatMap((item) => item.evidence.map(reference))).join(", ")}).`, + "", + ); + for (const concept of concepts.slice(0, 5)) { + const { entity } = concept; + const calls = concept.calls.slice(0, 3); + const relevantFields = entity.fields.filter((field) => + deepTrace?.methods.some((method) => + method.events.some((event) => + event.detail.includes(`.${field.name}`), + ), + ), + ); + const fields = ( + relevantFields.length ? relevantFields : entity.fields + ).slice(0, 5); + const relations = entity.relations.filter((relation) => + selectedNames.has(relation.target), + ); + lines.push( + `### ${safe(entity.name)}`, + "", + `- Declared entity: ${sourceLink(entity.declaration)}.`, + concept.calls.length + ? `- Journey references: ${calls.map((call) => `${call.effect === "unspecified" ? "call" : `${call.effect} call`} at ${sourceLink(call.at)}`).join(", ")}${concept.calls.length > calls.length ? `; ${concept.calls.length - calls.length} more call sites` : ""}.` + : "- Direct relation from a touched entity; no selected journey call was linked to this entity.", + ...(fields.length + ? [ + `- Declared fields to inspect: ${fields.map((field) => `${safe(field.name)} (${sourceLink(field.at)})`).join(", ")}.`, + ] + : []), + ...relations.map( + (relation) => + `- Declared ${safe(relation.kind)} relation ${safe(relation.property)} → ${safe(relation.target)} (${sourceLink(relation.at)}).`, + ), + "", + ); + } + if (concepts.length > 5) + lines.push( + "<details><summary>Other entity declarations linked to this journey</summary>", + "", + ...concepts + .slice(5) + .map( + (concept) => + `- ${safe(concept.entity.name)}: ${sourceLink(concept.entity.declaration)}; ${concept.calls.length} selected call site(s).`, + ), + "", + "</details>", + "", + ); + } + if (scheduled.length) + lines.push( + "## Scheduled work", + "", + "These are declared handlers with direct, typed repository call sites touching concepts above. A schedule declaration does not prove a run or its effects.", + "", + ...scheduled.map( + (item) => + `- ${safe(item.job)}${item.schedule ? ` (declared schedule ${safe(item.schedule)})` : ""} at ${sourceLink(item.registration)}: ${item.effect === "unspecified" ? "calls" : `${item.effect} call involving`} ${safe(item.entity)} at ${sourceLink(item.at)}.`, + ), + "", + ); + const migrationNotes = repositoryNotes.filter( + (note) => note.kind === "migration", + ); + if (migrationNotes.length) + lines.push( + "## Related migration candidates", + "", + "These file names match selected source owners. Inspect the migrations before treating them as an explanation of current data behavior.", + "", + ...migrationNotes.map( + (note) => `- ${safe(note.text)} ${sourceLink(note)}`, + ), + "", + ); + if (explained.length || journeys.length) lines.push( "## Explained flow", "", "Partial traces from method bodies. Check the cited steps and open gaps before relying on an outcome.", "", + ...journeys.flatMap((journey) => [ + ...renderDeepTrace(journey.trace, journey.continuations), + ...repositoryNotes + .filter((note) => note.journey === journey.trace.entry.symbol) + .flatMap((note) => [ + `- ${note.kind === "comment" ? "Source comment says" : note.kind === "test" ? "Related test candidate" : "Migration candidate"}: ${safe(note.text)} ${sourceLink(note)}`, + ]), + `**Selection:** ${safe(journey.reason)}. This describes source coverage, not business priority.`, + "", + ]), ...explained.flatMap((flow) => [ `### ${safe(flowTitle(flow.title, flow.entryPoint))}`, "", @@ -293,6 +447,11 @@ export function renderOnboardingGuide( lines.push("## Candidate flows", ""); const remainingFlows = flows.filter( (flow) => + !journeys.some((journey) => + flow.entryPoints.includes( + `${journey.trace.entry.verb ?? ""} ${journey.trace.entry.path ?? ""}`.trim(), + ), + ) && !explained.some((item) => flow.sourceFindingIds.includes(item.routeFindingId), ), @@ -304,9 +463,11 @@ export function renderOnboardingGuide( ); if (remainingFlows.length === 0) lines.push( - explained.length - ? "No other supported route candidate was found." - : "No supported route candidate was found.", + options.rejected?.length + ? "Other traced candidates were not featured; see the selection notes below." + : explained.length || journeys.length + ? "No other supported route candidate was found." + : "No supported route candidate was found.", ); for (const flow of remainingFlows) { const start = components.get(flow.componentIds[0] ?? "")?.name; @@ -334,6 +495,17 @@ export function renderOnboardingGuide( "", ); } + if (options.rejected?.length) + lines.push( + "<details><summary>Other traced candidates and selection reasons</summary>", + "", + ...options.rejected + .slice(0, 8) + .map((item) => `- ${safe(item.symbol)}: ${safe(item.reason)}`), + "", + "</details>", + "", + ); lines.push( "## Setup and operations", "", @@ -341,7 +513,15 @@ export function renderOnboardingGuide( "", ); const setupCommands = named("setup.command"); - for (const purpose of ["install", "start", "compiled-start", "test"]) { + for (const purpose of [ + "install", + "build", + "start", + "compiled-start", + "test", + "migration", + "seed", + ]) { const commands = setupCommands.filter( (item) => data(item, "purpose") === purpose, ); @@ -350,7 +530,7 @@ export function renderOnboardingGuide( commands[0]; if (preferred) lines.push( - `- **${purpose === "compiled-start" ? "Compiled start" : purpose[0]!.toUpperCase() + purpose.slice(1)}:** \`${safe(data(preferred, "command") ?? "")}\` (documented in ${reference(preferred.evidence[0]!)})`, + `- **${purpose === "compiled-start" ? "Compiled start" : purpose[0]!.toUpperCase() + purpose.slice(1)}:** \`${safe(data(preferred, "command") ?? "")}\` (${preferred.evidence[0]?.file === "README.md" ? (data(preferred, "generic") === "yes" ? "generic starter README command" : "documented command") : "declared package script"} at ${reference(preferred.evidence[0]!)}; not run)`, ); } const serviceFindings = named("setup.service"); @@ -373,8 +553,36 @@ export function renderOnboardingGuide( .join("")}.`, ); const envNames = unique( - named("environment.variable").map((item) => data(item, "name") ?? ""), + [...named("environment.variable"), ...named("setup.variable")].map( + (item) => data(item, "name") ?? "", + ), ).filter(Boolean); + const templateVariables = named("setup.variable"); + if (templateVariables.length) + lines.push( + `- **Template variable names:** ${safe( + unique(templateVariables.map((item) => data(item, "name") ?? "")) + .sort() + .slice(0, 16) + .join(", "), + )}. Values are omitted; see ${reference(templateVariables[0]!.evidence[0]!)}.`, + ); + const migrations = named("database.migration"); + if (migrations.length) + lines.push( + `- **Migration declarations:** ${migrations.length} file(s) found (for example ${reference(migrations[0]!.evidence[0]!)}); execution order and local need are unverified.`, + ); + const health = named("application.route").find( + (item) => + data(item, "verb")?.toUpperCase() === "GET" && + /\/(?:health|healthz|ready|readiness)\/?$/iu.test( + data(item, "path") ?? "", + ), + ); + if (health) + lines.push( + `- **Possible health route:** GET ${safe(data(health, "path") ?? "")} is declared at ${reference(health.evidence[0]!)}; response and reachability are unverified.`, + ); for (const [purpose, pattern] of [ ["database", /^(?:DB_|DATABASE_|POSTGRES_)/u], ["cache and messaging", /^(?:REDIS_)/u], @@ -478,6 +686,44 @@ export function renderOnboardingGuide( ? "The README lists a compiled start without a build step; is the package build script required first, and what prerequisites does it need?" : "For a non-container compiled start, what build step and prerequisites are required?", ); + const declared = (purpose: string): string | undefined => { + const item = setupCommands.find( + (finding) => data(finding, "purpose") === purpose, + ); + return item ? data(item, "command") : undefined; + }; + const proposed = [ + declared("install") + ? `Review prerequisites, then consider ${declared("install")}.` + : "Confirm package installation and prerequisite versions.", + services.length + ? `Check Compose services (${services.join(", ")}) and required files before starting them.` + : "Check required local services and configuration.", + declared("build") + ? `If compiled output is needed, consider ${declared("build")}.` + : "Check whether a build is required.", + declared("start") + ? `Consider ${declared("start")} after prerequisites are ready.` + : "Confirm the application start command.", + health + ? `If safe, inspect the declared GET ${data(health, "path")} route and record the actual response.` + : "Choose a safe observation and record its actual result or blocker.", + ]; + lines.push( + "", + "**Proposed order (inferred from declarations; do not run blindly):**", + "", + ...proposed.map((step, index) => `${index + 1}. ${safe(step)}`), + ); + if ( + setupCommands.some((item) => + ["migration", "seed"].includes(data(item, "purpose") ?? ""), + ) || + migrations.length + ) + questions.push( + "Are migrations or seeds needed locally, in what order, and who approves running them?", + ); if (questions.length) lines.push( "", @@ -503,10 +749,202 @@ export function renderOnboardingGuide( "- **Unknown:** What are the production topology and operational owners? Ask a knowledgeable person.", "", ); - return `${lines + const source = `${lines .join("\n") .replace(/\n{3,}/gu, "\n\n") .trimEnd()}\n`; + return options.storyInventory && options.storySelection + ? renderHumanOnboardingGuide( + source, + options.storyInventory, + options.storySelection, + repositoryNotes, + ) + : arrangeGuide(source, journeys); +} + +function arrangeGuide( + source: string, + journeys: readonly OnboardingGuideJourney[], +): string { + const headers = [...source.matchAll(/^## (.+)$/gmu)]; + const sections = new Map( + headers.map((header, index) => [ + header[1]!, + source + .slice( + header.index! + header[0].length, + headers[index + 1]?.index ?? source.length, + ) + .trim(), + ]), + ); + const overview = (sections.get("System overview") ?? "").split("\n"); + const detailStart = overview.findIndex((line) => + line.startsWith("<details>"), + ); + const overviewFacts = + detailStart < 0 ? overview : overview.slice(0, detailStart); + const systemDetails = + detailStart < 0 ? "" : overview.slice(detailStart).join("\n").trim(); + const inventory = overviewFacts.filter((line) => + /^- \*\*(?:Root imports|Other feature modules|Other support modules|Integration names to investigate|Scheduled handlers)/u.test( + line, + ), + ); + const retainedInventory = overviewFacts.some( + (line) => /^- \*\*/u.test(line) && !inventory.includes(line), + ) + ? undefined + : (inventory.find((line) => /Other feature modules/u.test(line)) ?? + inventory[0]); + const system = overviewFacts + .filter((line) => !inventory.includes(line) || line === retainedInventory) + .join("\n") + .trim(); + const architecture = sections.get("Architecture relationships") ?? ""; + const featuredOwners = [ + ...(sections.get("Explained flow") ?? "").matchAll( + /^### Source journey: ([^.\n]+)\./gmu, + ), + ].map((match) => match[1]!); + const relationshipLines = architecture + .split("\n") + .filter((line) => /^- [^*]/u.test(line) && line.includes("→")); + const relevantRelationships = relationshipLines.filter((line) => + featuredOwners.some((owner) => line.includes(owner)), + ); + const relationships = ( + relevantRelationships.length ? relevantRelationships : relationshipLines + ).slice(0, 5); + const journeyEdges = journeys + .flatMap((journey) => { + const call = journey.trace.calls.find( + (item) => + item.caller === journey.trace.entry.symbol && item.declaredTarget, + ); + return call + ? [ + `- ${safe(call.caller)} → ${safe(call.declaredTarget!)} (declared call at ${sourceLink(call.site)})`, + ] + : []; + }) + .slice(0, 5); + const explained = sections.get("Explained flow") ?? ""; + const scheduled = sections.get("Scheduled work") ?? ""; + const changePoints = [ + ...explained.matchAll( + /^### Source journey: (.+)$[\s\S]*?^\*\*Where to change:\*\* (.+)$/gmu, + ), + ].map( + (match) => + `- [${safe(match[1]!)}](#journey-${anchor(match[1]!)}) — ${match[2]}`, + ); + const setup = sections.get("Setup and operations") ?? ""; + const unknowns = sections.get("Unknowns") ?? ""; + const appendix = [ + ...(inventory.length + ? [ + "**Additional inventory**", + "", + ...inventory.filter((line) => line !== retainedInventory), + "", + ] + : []), + ...(systemDetails + ? ["**System citations and job signals**", "", systemDetails, ""] + : []), + ...(architecture + ? ["**Architecture declarations and references**", "", architecture, ""] + : []), + ...(sections.get("Candidate flows") + ? ["**Candidate routes**", "", sections.get("Candidate flows")!, ""] + : []), + ...(sections.get("Related migration candidates") + ? [ + "**Migration candidates**", + "", + sections.get("Related migration candidates")!, + "", + ] + : []), + ]; + return ( + [ + "# Onboarding guide", + "", + "## Start here", + "", + `Read the [system map](#system-overview)${sections.get("Concepts") ? ", [concepts](#concepts)" : ""}, and [connected journeys](#explained-flow). Then choose a safe check from [Run and observe](#setup-and-operations) and record what happened in \`.transferkit.local/ONBOARDING.md\`. Source links support static claims; runtime results remain unverified.`, + "", + "## System map", + "", + '<a id="system-overview"></a>', + "", + system, + ...(journeyEdges.length || relationships.length + ? [ + "", + journeyEdges.length + ? "**Selected declared call targets:**" + : "**Selected declared relationships:**", + "", + ...(journeyEdges.length ? journeyEdges : relationships), + "", + "Full declarations and citations are in the reference appendix.", + ] + : []), + "", + ...(sections.get("Concepts") + ? ["## Concepts", "", sections.get("Concepts")!, ""] + : []), + "## Connected journeys", + "", + '<a id="explained-flow"></a>', + "", + ...(scheduled ? [scheduled, ""] : []), + explained || + "No source journey was selected. Check candidate routes in the reference appendix.", + "", + "## Change points", + "", + ...(changePoints.length + ? changePoints + : [ + "No traced change point was established. Inspect the cited candidate routes before choosing a file.", + ]), + "", + "## Run and observe", + "", + '<a id="setup-and-operations"></a>', + "", + setup, + "", + "## Specific questions", + "", + '<a id="unknowns"></a>', + "", + unknowns, + "", + "## Reference appendix", + "", + "<details><summary>Inventories, candidate routes, and supporting declarations</summary>", + "", + ...appendix, + "</details>", + "", + ] + .join("\n") + .replace(/\n{3,}/gu, "\n\n") + .trimEnd() + "\n" + ); +} + +function anchor(value: string): string { + return value + .toLowerCase() + .replace(/[^a-z0-9]+/gu, "-") + .replace(/^-|-$/gu, ""); } function fact(label: string, statement: string, present: boolean): string[] { @@ -530,6 +968,137 @@ function reference(item: Evidence): string { return `\`${safe(`${item.file}${item.line ? `:${item.line}` : ""}`).replace(/`/gu, "'")}\``; } +function sourceLink(at: { file: string; line: number }): string { + const path = at.file.split("/").map(encodeURIComponent).join("/"); + return `[${safe(`${at.file}:${at.line}`)}](${path}#L${at.line})`; +} + +function renderDeepTrace( + trace: OnboardingTrace, + continuations: readonly OnboardingQueueContinuation[], +): string[] { + const location = sourceLink; + const methods = trace.methods.slice(0, 2); + const lines = [ + `<a id="journey-${anchor(trace.entry.symbol)}"></a>`, + "", + `### Source journey: ${safe(trace.entry.symbol)}`, + "", + `**Entry:** ${trace.entry.kind === "scheduled" ? `Scheduled handler ${safe(trace.entry.symbol)}${trace.entry.schedule ? ` (declared schedule ${safe(trace.entry.schedule)})` : ""}` : safe([trace.entry.verb, trace.entry.path].filter(Boolean).join(" ") || trace.entry.symbol)} is declared at ${location(trace.entry.declaration)}. This is a static source trace; calls and outcomes are unverified at runtime.`, + "", + ]; + for (const method of methods) { + lines.push( + `**${safe(method.symbol)}** (${location(method.declaration)})`, + "", + ); + let assignments = 0; + const significant = method.events.filter( + (event) => + (event.kind === "assignment" + ? assignments++ < 8 + : event.kind !== "call") || + event.effect || + trace.calls.some( + (call) => + call.site.file === event.at.file && + call.site.line === event.at.line && + call.declaredTarget, + ), + ); + const visible = + significant.length > 40 + ? significant.filter( + (event, index) => + index < 20 || + event.effect === "write-like" || + event.effect === "transaction-like" || + (index >= significant.length - 10 && event.kind !== "assignment"), + ) + : significant; + for (const event of visible) { + const path = event.path.length + ? ` [${event.path.length > 2 ? "after earlier checks; " : ""}${safe(event.path.slice(-2).join("; "))}]` + : ""; + const edge = + event.kind === "call" + ? trace.calls.find( + (call) => + call.caller === method.symbol && + call.site.file === event.at.file && + call.site.line === event.at.line, + ) + : undefined; + const action = + event.kind === "branch" + ? `Checks ${safe(event.detail)}` + : event.kind === "throw" + ? `Throws ${safe(event.detail.replace(/^throw\s+/u, ""))}` + : event.kind === "return" + ? `Returns ${safe(event.detail.replace(/^return\s*/u, ""))}` + : event.kind === "assignment" + ? `Assigns ${safe(event.detail)}` + : `${event.awaited ? "Awaits" : "Calls"} ${safe(event.detail)}${event.effect ? ` (${event.effect} attempt)` : ""}${edge?.declaredTarget ? `; declared target ${safe(edge.declaredTarget)} at ${location(edge.declaration!)}` : edge?.kind === "unresolved" ? "; target unresolved" : ""}`; + lines.push(`- ${action}${path} — ${location(event.at)}`); + } + if (significant.length > visible.length) + lines.push( + `- ${significant.length - visible.length} further source events omitted from this compact view; inspect the cited method.`, + ); + lines.push(""); + } + if (trace.methods.length > methods.length) + lines.push( + `**Further declared methods:** ${trace.methods + .slice(methods.length, methods.length + 8) + .map( + (method) => + `${safe(method.symbol)} (${location(method.declaration)})`, + ) + .join(", ")}.`, + "", + ); + if (continuations.length) { + lines.push("**Queue continuations:**", ""); + for (const continuation of continuations) { + const { publication, handler } = continuation; + lines.push( + handler + ? `- Possible continuation: ${safe(publication.caller)} calls BullMQ Queue.add for job ${safe(publication.job)} on ${safe(publication.queue)} at ${location(publication.at)} (injection ${location(publication.injection)}); ${safe(handler.symbol)} is registered for that queue at ${location(handler.registration)} (body ${location(handler.declaration)}). Enqueue, delivery, order, and handler success are unverified.` + : `- Unconnected publication: ${safe(publication.caller)} calls BullMQ Queue.add for job ${safe(publication.job)} on ${safe(publication.queue)} at ${location(publication.at)}. ${safe(continuation.reason ?? "No supported handler link was found.")}`, + ); + } + lines.push(""); + } + const relevantGaps = trace.gaps.filter((gap) => + methods.some((method) => method.declaration.file === gap.at.file), + ); + const gaps = (relevantGaps.length ? relevantGaps : trace.gaps).filter( + (gap, index, all) => + all.findIndex( + (item) => + item.reason === gap.reason && + item.at.file === gap.at.file && + item.at.line === gap.at.line, + ) === index, + ); + lines.push("**First open boundaries:**", ""); + if (!gaps.length) + lines.push( + "- No analyzer gap was recorded; runtime outcomes remain unverified.", + ); + for (const gap of gaps.slice(0, 6)) + lines.push( + `- ${safe(gap.reason)}${gap.path.length ? ` [${safe(gap.path.join("; "))}]` : ""} — ${location(gap.at)}`, + ); + lines.push( + "", + `**Where to change:** start at ${location(trace.entry.declaration)}${methods[1] ? ` and ${location(methods[1].declaration)}` : ""}. Related tests were not established by this trace; search for the cited symbols before changing behavior.`, + "", + ); + return lines; +} + function specificUnknowns( findings: readonly Finding[], flows: readonly CandidateFlow[], @@ -664,7 +1233,7 @@ function selectRelationships( ); } -function selectFlows( +export function selectOnboardingFlows( candidates: readonly CandidateFlow[], model: ProjectModel, findings: readonly Finding[], diff --git a/packages/renderers/src/onboarding-human-story.ts b/packages/renderers/src/onboarding-human-story.ts new file mode 100644 index 0000000..be3e763 --- /dev/null +++ b/packages/renderers/src/onboarding-human-story.ts @@ -0,0 +1,497 @@ +import type { + Evidence, + OnboardingRepositoryNote, + OnboardingStoryChapter, + OnboardingStoryClaim, + OnboardingStoryInventory, + OnboardingStorySelection, + OnboardingStoryTerm, + OnboardingTraceEvent, +} from "@transferkit/core"; + +import { sanitizeHandoverValue } from "./handover-package.js"; + +export function renderHumanOnboardingGuide( + source: string, + inventory: OnboardingStoryInventory, + selection: OnboardingStorySelection, + notes: readonly OnboardingRepositoryNote[], +): string { + const sections = splitSections(source); + const central = chooseCentralTerm(inventory, selection); + const glossary = chooseGlossary(inventory, selection, central); + const first = selection.chapters[0]; + const overview = inventory.purpose + ? `**What this repository says it does:** ${clean(inventory.purpose.text)} ${links(inventory.purpose.evidence)} Repository statements describe intent; local behavior is still unverified.` + : first && central + ? `**What the source shows:** ${clean(central.name)} is a recurring record across the selected entries. Start with ${clean(first.id)} to see one way work enters; the other chapters show separate ways this record is handled. ${links([...first.entry.evidence, ...central.evidence.slice(0, 1)])} This is a source-level reading path. The broader product purpose is not established here.` + : first + ? `**What the source shows:** ${clean(first.entry.text)} ${links(first.entry.evidence)} The broader product purpose is not established by the inspected files.` + : "**Purpose unknown:** The inspected files do not establish a project-specific purpose or a supported entry point."; + const role = inventory.roles + .slice(0, 2) + .map((claim) => `${clean(claim.text)} ${links(claim.evidence)}`) + .join(" "); + const opening = [ + "# Onboarding guide", + "", + "## Start here", + "", + overview, + "", + ...(role && !central ? [`**Repository shape:** ${role}`, ""] : []), + `**How to read it:** ${first ? `Start with [${clean(first.id)}](#journey-${anchor(first.id)}), then read the other selected entries as separate starting points.` : "Start with the cited entry and inspect its source before assuming a workflow."} Connections below distinguish calls, shared records, and associations that are still unproven. Use [Run and observe](#setup-and-operations) for a safe check, then record your own results in \`.transferkit.local/ONBOARDING.md\`.`, + "", + "## System map", + "", + '<a id="system-overview"></a>', + "", + ...(central + ? [ + `**Central code record:** ${clean(central.name)} is a ${clean(central.codeRole)} ${links(central.evidence.slice(0, 1))}. Its business meaning is ${central.meaning ? `described by the repository: ${clean(central.meaning.text)} ${links(central.meaning.evidence)}` : "not established by the declaration"}.`, + "", + ] + : []), + ...(!central && first?.input && first.output + ? [ + `**Documented input and output:** ${clean(first.input.text)} ${links(first.input.evidence)} ${clean(first.output.text)} ${links(first.output.evidence)} The source path between them has not been traced.`, + "", + ] + : []), + ...(selection.chapters.length + ? [ + `**Selected entries (reading order):** ${selection.chapters.map((chapter) => `[${clean(chapter.id)}](#journey-${anchor(chapter.id)})`).join(", ")}. Their order here does not establish runtime sequence.`, + "", + ] + : []), + ...(selection.connections.length + ? [ + "**How these entries relate:**", + "", + ...selection.connections + .filter((connection) => + selection.chapters.some( + (chapter) => chapter.id === connection.to, + ), + ) + .sort( + (left, right) => + Number(right.explanation.includes(central?.name ?? "\u0000")) - + Number(left.explanation.includes(central?.name ?? "\u0000")), + ) + .slice(0, 3) + .map( + (connection) => + `- ${clean(connection.from)} / ${clean(connection.to)}: ${clean(connection.explanation)} ${links(connection.evidence)}`, + ), + "", + ] + : []), + ...(glossary.length + ? [ + "## Concepts", + "", + "These are code roles you will meet while reading the selected paths. A relation declaration does not define a business contract.", + "", + ] + : []), + ...glossary.flatMap((item) => [ + `### ${clean(item.name)}`, + "", + `${capitalize(clean(item.codeRole))} ${links(item.evidence)}. ${item.meaning ? `The repository says: ${clean(item.meaning.text)} ${links(item.meaning.evidence)}.` : "Business meaning is unconfirmed."} ${item.why}`, + "", + ]), + "## Connected journeys", + "", + '<a id="explained-flow"></a>', + "", + selection.chapters.length + ? "Read each chapter as a separate source entry. The links establish declarations and bounded paths, not successful runtime outcomes." + : "No supported story entry was identified; inspect the reference appendix and ask an owner where work starts.", + "", + ...selection.chapters.flatMap((chapter) => + renderChapter(chapter, notes, inventory), + ), + "## Change points", + "", + selection.chapters.length + ? "Use the task that matches your change. Start at the entry, then inspect its next source boundary and nearby tests before editing." + : "No change point was established by the inspected source.", + "", + ...(selection.chapters.length + ? [ + `**Safe first investigation:** Open ${links([preferredSource(first!) ?? first!.entry.evidence[0]!])}${notes.some((note) => note.kind === "test" && note.journey === first!.id) ? ` and the nearby test candidate ${sourceLink(notes.find((note) => note.kind === "test" && note.journey === first!.id)!)}` : " and search for its callers or tests"}. Trace one input to the first uncertain boundary, then record what you could and could not verify.`, + "", + "| Task | Start here | Next source or test |", + "| --- | --- | --- |", + ...selection.chapters.map((chapter) => { + const test = notes.find( + (note) => note.kind === "test" && note.journey === chapter.id, + ); + const next = test + ? `${sourceLink(test)} (test candidate; assertions unreviewed)` + : preferredSource(chapter) + ? links([preferredSource(chapter)!]) + : "Search for this entry symbol; a test was not identified by this scan."; + return `| Investigate ${clean(chapter.id)} | ${links(chapter.entry.evidence)} | ${next} |`; + }), + "", + ] + : []), + "## Run and observe", + "", + '<a id="setup-and-operations"></a>', + "", + ...setupOpening(inventory), + setupBody(sections.get("Setup and operations"), inventory), + "", + "## Specific questions", + "", + '<a id="unknowns"></a>', + "", + ...inventory.unknowns.map((item) => `- **Unknown:** ${clean(item)}`), + sections.get("Unknowns") ?? "", + "", + "## Reference appendix", + "", + "<details><summary>Inventories, candidate routes, and supporting declarations</summary>", + "", + ...(sections.get("Explained flow") + ? [ + "### Raw source traces", + "", + sections + .get("Explained flow")! + .replace(/^### Source journey:/gmu, "#### Raw trace:"), + "", + ] + : []), + ...(sections.get("Concepts") + ? ["### Entity fields and relations", "", sections.get("Concepts")!, ""] + : []), + ...(sections.get("Scheduled work") + ? ["### Scheduled work", "", sections.get("Scheduled work")!, ""] + : []), + ...[ + "System overview", + "Architecture relationships", + "Related migration candidates", + ].flatMap((heading) => + sections.get(heading) + ? [`### ${heading}`, "", sections.get(heading)!, ""] + : [], + ), + "**Candidate routes**", + "", + sections.get("Candidate flows") ?? + "No supported route candidate was found.", + "", + "</details>", + "", + ]; + return `${opening + .join("\n") + .replace(/\n{3,}/gu, "\n\n") + .trimEnd()}\n`; +} + +function renderChapter( + chapter: OnboardingStoryChapter, + notes: readonly OnboardingRepositoryNote[], + inventory: OnboardingStoryInventory, +): string[] { + const trace = chapter.trace; + const route = trace?.entry; + const decision = trace?.methods + .flatMap((method) => method.events) + .find((event) => sameLine(event, chapter.decision)); + const result = trace?.methods + .flatMap((method) => method.events) + .find((event) => sameLine(event, chapter.result)); + const alternate = + trace?.methods + .flatMap((method) => method.events) + .find((event) => event.kind === "throw") ?? + trace?.methods + .flatMap((method) => method.events) + .find( + (event) => + sameLine(event, chapter.alternate) && event.kind === "branch", + ); + const write = trace?.methods + .flatMap((method) => method.events) + .find((event) => event.effect === "write-like"); + const test = notes.find( + (note) => note.kind === "test" && note.journey === chapter.id, + ); + const boundary = inventory.boundaries.find((item) => + trace?.methods.some((method) => + method.events.some( + (event) => + event.kind === "call" && + item.name && + event.detail.toLowerCase().includes(item.name.toLowerCase()), + ), + ), + ); + const documentedAlternate = !trace + ? inventory.observations.find((item) => + item.text.startsWith("Documented alternate:"), + ) + : undefined; + return [ + `<a id="journey-${anchor(chapter.id)}"></a>`, + "", + `### ${trace ? "Source journey" : "Entry to inspect"}: ${clean(chapter.id)}`, + "", + `**Why read this:** This is a ${trace?.entry.kind === "scheduled" ? "scheduled" : trace ? "declared HTTP" : "documented or package"} entry to the repository. Read it to locate the first source boundary for ${clean(chapter.id)} and the behavior you would need to verify. ${links(chapter.entry.evidence)}`, + "", + `**Trigger and input:** ${route ? `${route.kind === "scheduled" ? "Scheduled entry" : `${route.verb ?? "HTTP"} ${route.path ?? "path unresolved"}`} is declared at ${sourceLink(route.declaration)}.` : `${clean(chapter.entry.text)} ${links(chapter.entry.evidence)}`}${chapter.input ? ` Documented input: ${clean(chapter.input.text)} ${links(chapter.input.evidence)}` : ""}`, + "", + `**Decision:** ${decision && decision.kind === "branch" ? `The bounded trace checks \`${clean(short(decision.detail))}\` at ${sourceLink(decision.at)}; inspect both exits before changing the rule.` : `No business decision is established in this bounded trace${chapter.firstUnsupportedBoundary ? `; it stops at ${links(chapter.firstUnsupportedBoundary.evidence)}` : ""}.`}`, + "", + `**State or output:** ${chapter.output ? `${clean(chapter.output.text)} ${links(chapter.output.evidence)} (repository statement; not verified by a run).` : write ? `A write-like call appears at ${sourceLink(write.at)}; completion and persisted state are unverified.` : result ? `The traced method returns at ${sourceLink(result.at)}; the downstream result and persisted state are unverified.` : "The bounded trace does not establish an output or completed state change."}`, + "", + `**Alternate exit:** ${alternate ? `${alternate.kind === "throw" ? "A throw" : "A branch"} is visible at ${sourceLink(alternate.at)}; inspect the surrounding condition and handler in source.` : documentedAlternate ? `${clean(documentedAlternate.text)} ${links(documentedAlternate.evidence)} This is a repository statement, not a verified run.` : "No distinct alternate exit was established by this trace; that does not mean none exists."}`, + "", + `**External boundary:** ${boundary ? `${clean(boundary.name ?? "Dependency")} is declared at ${links(boundary.evidence)}; delivery or response is unverified.` : "No external call was established for this selected path."}`, + "", + `**Where to change and test:** Begin at ${links(chapter.entry.evidence)}${preferredSource(chapter) ? `, then inspect ${links([preferredSource(chapter)!])}` : ""}. ${test ? `A nearby test candidate is ${sourceLink(test)}; its assertions have not been evaluated here.` : "This scan did not identify a nearby test for this entry; search for the symbol before changing behavior."}`, + "", + ...(chapter.firstUnsupportedBoundary + ? [ + `**First unsupported step:** ${clean(chapter.firstUnsupportedBoundary.reason)} ${links(chapter.firstUnsupportedBoundary.evidence)}.`, + "", + ] + : []), + ]; +} + +function chooseGlossary( + inventory: OnboardingStoryInventory, + selection: OnboardingStorySelection, + central: OnboardingStoryTerm | undefined, +): { + name: string; + codeRole: string; + meaning?: OnboardingStoryClaim; + evidence: Evidence[]; + why: string; +}[] { + if (!central) return []; + const byName = new Map(inventory.terms.map((term) => [term.name, term])); + const chapters = selection.chapters + .map( + (item) => + `${item.id} ${item.trace?.methods.flatMap((method) => method.events.map((event) => event.detail)).join(" ") ?? ""}`, + ) + .join(" "); + const candidates = central.relations + .filter((relation) => + inventory.artifacts.some((item) => item.name === relation.target), + ) + .map((relation) => ({ + relation, + score: + (chapters.toLowerCase().includes(relation.target.toLowerCase()) + ? 10 + : 0) + + (relation.property.toLowerCase() === relation.target.toLowerCase() + ? 3 + : 0), + })) + .sort( + (left, right) => + right.score - left.score || + left.relation.target.localeCompare(right.relation.target), + ); + const names = [ + central.name, + ...candidates.map((item) => item.relation.target), + ...inventory.terms.map((item) => item.name), + ] + .filter((name, index, all) => all.indexOf(name) === index) + .slice(0, 5); + return names.map((name) => { + const term: OnboardingStoryTerm | undefined = byName.get(name); + const artifact = inventory.artifacts.find((item) => item.name === name); + const relation = central.relations.find((item) => item.target === name); + const why = + name === central.name + ? "Selected entries name or touch this record, so it is the first place to orient yourself." + : relation + ? `The ${clean(central.name)} declaration has ${/^[aeiou]/iu.test(relation.property) ? "an" : "a"} ${clean(relation.property)} relation to it ${links(relation.evidence)}; this does not define the real-world relationship.` + : "It appears in the selected source inventory; inspect its declaration before assuming a business role."; + return { + name, + codeRole: term?.codeRole ?? "declared data entity", + ...(term?.meaning ? { meaning: term.meaning } : {}), + evidence: term?.evidence.slice(0, 1) ?? artifact?.evidence ?? [], + why, + }; + }); +} + +function chooseCentralTerm( + inventory: OnboardingStoryInventory, + selection: OnboardingStorySelection, +): OnboardingStoryTerm | undefined { + const first = selection.chapters[0]?.id.toLowerCase() ?? ""; + return ( + inventory.terms.find((term) => + first.includes(term.name.replace(/Entity$/u, "").toLowerCase()), + ) ?? inventory.terms[0] + ); +} + +function setupBody( + legacy: string | undefined, + inventory: OnboardingStoryInventory, +): string { + const source = + legacy ?? "No setup commands were established by the inspected files."; + if ( + !inventory.observations.some((item) => + /Documented command:/u.test(item.text), + ) + ) + return source; + return source + .replace( + "Confirm the application start command.", + "Review the documented invocation above and verify its inputs before running it.", + ) + .replace( + "How should a newcomer start the app?", + "Which inputs and prerequisites are required for the documented command?", + ) + .replace( + /^\d+\. Consider npm run start after prerequisites are ready\.$/gmu, + "4. Review the documented invocation above, including its input arguments, after checking prerequisites.", + ); +} + +function preferredSource( + chapter: OnboardingStoryChapter, +): Evidence | undefined { + if (chapter.trace) return chapter.inspectNext[0]; + return ( + chapter.entry.evidence.find((item) => + /\.(?:[cm]?js|tsx?|py)$/u.test(item.file), + ) ?? chapter.inspectNext[0] + ); +} + +function capitalize(value: string): string { + return value.length ? value[0]!.toUpperCase() + value.slice(1) : value; +} + +function setupOpening(inventory: OnboardingStoryInventory): string[] { + const engines = inventory.observations + .filter((item) => item.text.startsWith("Declared runtime:")) + .slice(0, 2); + const dependencies = inventory.observations + .filter((item) => item.text.startsWith("Declared runtime dependency:")) + .slice(0, 6); + const observations = inventory.observations + .filter( + (item) => + item.basis === "repository-statement" && + item.text.startsWith("Documented command:"), + ) + .slice(0, 2); + return [ + ...(engines.length + ? [ + `**Declared runtime:** ${engines.map((item) => `${escapeMarkup(item.text.replace(/^Declared runtime:\s*/u, ""))} ${links(item.evidence)}`).join(" ")} Verify the installed version locally.`, + "", + ] + : []), + ...(dependencies.length + ? [ + `**Selected runtime dependencies:** ${dependencies.map((item) => clean(item.text.replace(/^Declared runtime dependency:\s*/u, "").replace(/\.$/u, ""))).join(", ")} (${links(dependencies.flatMap((item) => item.evidence))}). These are declarations, not proof that services are available.`, + "", + ] + : []), + ...observations.flatMap((item) => [ + `**Documented invocation:** ${clean(item.text)} ${links(item.evidence)}`, + "", + ]), + ...(inventory.observations.find((item) => /health route/u.test(item.text)) + ? [ + `**Safe first observation:** Inspect the declared health route after verifying prerequisites; an HTTP response would not prove dependency health. ${links(inventory.observations.find((item) => /health route/u.test(item.text))!.evidence)}`, + "", + ] + : observations[0] + ? [ + `**Safe first observation:** Review the documented command and use disposable input where appropriate; record the actual result or blocker. ${links(observations[0].evidence)}`, + "", + ] + : []), + ]; +} + +function splitSections(source: string): Map<string, string> { + const headers = [...source.matchAll(/^## (.+)$/gmu)]; + return new Map( + headers.map((header, index) => [ + header[1]!, + source + .slice( + header.index! + header[0].length, + headers[index + 1]?.index ?? source.length, + ) + .trim(), + ]), + ); +} + +function sameLine(event: OnboardingTraceEvent, evidence?: Evidence): boolean { + return ( + !!evidence && + event.at.file === evidence.file && + event.at.line === evidence.line + ); +} + +function short(value: string): string { + return value.length > 110 ? `${value.slice(0, 107)}...` : value; +} + +function links(evidence: readonly Evidence[]): string { + return [ + ...new Map( + evidence + .filter((item) => item.line) + .map((item) => [`${item.file}:${item.line}`, item]), + ).values(), + ] + .slice(0, 6) + .map((item) => sourceLink({ file: item.file, line: item.line! })) + .join(", "); +} + +function sourceLink(at: { file: string; line: number }): string { + const path = at.file.split("/").map(encodeURIComponent).join("/"); + return `[${clean(`${at.file}:${at.line}`)}](${path}#L${at.line})`; +} + +function anchor(value: string): string { + return value + .toLowerCase() + .replace(/[^a-z0-9]+/gu, "-") + .replace(/^-|-$/gu, ""); +} + +function clean(value: string): string { + return sanitizeHandoverValue(value) + .replace(/[\r\n]+/gu, " ") + .replace(/[<>]/gu, ""); +} + +function escapeMarkup(value: string): string { + return sanitizeHandoverValue(value) + .replace(/[\r\n]+/gu, " ") + .replace(/</gu, "<") + .replace(/>/gu, ">"); +} diff --git a/packages/renderers/src/personal-onboarding.ts b/packages/renderers/src/personal-onboarding.ts index f8c8db4..a02c11e 100644 --- a/packages/renderers/src/personal-onboarding.ts +++ b/packages/renderers/src/personal-onboarding.ts @@ -11,6 +11,7 @@ export interface PersonalOnboardingView { questions: readonly string[]; unknowns: readonly string[]; syncNeeded: boolean; + staleJourneys?: readonly string[]; } export function renderPersonalOnboarding( @@ -32,6 +33,10 @@ export function renderPersonalOnboarding( `- [ ] **Objective:** ${exercise.objective}`, `- **Read:** [${exercise.title} in the shared guide](../ONBOARDING.md#${exercise.guideSectionId})`, `- **Done when:** ${exercise.outcome}`, + ...(exercise.linkedJourneys ?? []).map( + (symbol) => + `<!-- tk:onboard:linked-journey ${encodeURIComponent(symbol)} -->`, + ), "", "### Notes", "", @@ -46,6 +51,17 @@ export function renderPersonalOnboarding( "_Add file references, commands tried, and results observed._", "", ); + if (exercise.id === "v2:attempt-local-run") + lines.push( + "### Attempt log", + "", + "Record only steps you actually tried. Keep credentials and environment values out of this file.", + "", + "| Date | Exact command or safe check | Observed result | Blocker |", + "| --- | --- | --- | --- |", + "| | | | |", + "", + ); } return `${lines.join("\n").trimEnd()}\n`; } @@ -59,11 +75,17 @@ export function renderPersonalOnboardingPlan( ...(view.syncNeeded ? ["Checkbox edits pending: run 'tk onboard sync'."] : []), + ...(view.staleJourneys?.length + ? [ + `Stale guide link: ${view.staleJourneys.join(", ")}. Keep your notes; inspect the current guide.`, + ] + : []), "", ]; for (const [index, exercise] of view.exercises.entries()) { lines.push( `${index + 1}. ${exercise.title} [${view.statuses[exercise.id]}] (${exercise.id})`, + ` Focus: ${exercise.objective}`, ` Goal: ${exercise.outcome}`, ` Read: ONBOARDING.md#${exercise.guideSectionId}`, ); @@ -90,12 +112,20 @@ export function renderPersonalOnboardingStatus( ...(view.syncNeeded ? ["Checkbox edits pending: run 'tk onboard sync'."] : []), + ...(view.staleJourneys?.length + ? [ + `Stale guide link: ${view.staleJourneys.join(", ")}. Keep your notes; inspect the current guide.`, + ] + : []), "", ...view.exercises.map( ({ id, title }) => `- ${title}: ${view.statuses[id]} (${id})`, ), ...(next - ? ["", `Next: ${next.title} — open .transferkit.local/ONBOARDING.md`] + ? [ + "", + `Next: ${next.title} — ${next.objective} Open .transferkit.local/ONBOARDING.md.`, + ] : []), "", "Questions and unknowns", diff --git a/packages/scanners/src/index.ts b/packages/scanners/src/index.ts index 8c68eec..3a48e19 100644 --- a/packages/scanners/src/index.ts +++ b/packages/scanners/src/index.ts @@ -2,7 +2,14 @@ import { readFile, stat } from "node:fs/promises"; import { join } from "node:path"; import { packageName as corePackageName } from "@transferkit/core"; -import type { Evidence, Finding } from "@transferkit/core"; +import type { + Evidence, + Finding, + OnboardingConceptEvidence, + OnboardingQueueEvidence, + OnboardingScheduledCall, + OnboardingTrace, +} from "@transferkit/core"; import { discoverRabbitMqConsumersInAst, @@ -12,7 +19,14 @@ import { discoverHandoverContextInAst, type HandoverContextFinding, } from "./handover-context.js"; -import { createTypeScriptAst } from "./typescript-ast.js"; +import { createTypeScriptAst, type TypeScriptAst } from "./typescript-ast.js"; +import { + analyzeOnboardingRoutes, + type OnboardingTraceLimits, +} from "./onboarding-trace.js"; +import { discoverOnboardingConceptsInAst } from "./onboarding-concepts.js"; +import { discoverOnboardingQueuesInAst } from "./onboarding-queues.js"; +import { discoverOnboardingScheduledCallsInAst } from "./onboarding-scheduled.js"; import { discoverRouteTracesInAst, type RouteTraceFinding, @@ -38,6 +52,8 @@ export { discoverHandoverContext } from "./handover-context.js"; export type { RouteTraceFinding } from "./route-traces.js"; export type { HandoverContextFinding } from "./handover-context.js"; export { discoverRepositoryFiles } from "./repository-files.js"; +export { discoverOnboardingRepositoryNotes } from "./onboarding-repository-notes.js"; +export { discoverOnboardingStoryEvidence } from "./onboarding-story.js"; export type { MessagingConsumerData, MessagingConsumerFinding, @@ -180,20 +196,101 @@ export async function scanRepository( repositoryDirectory: string, ): Promise<RepositoryFinding[]> { const ast = createTypeScriptAst(repositoryDirectory); + const { findings } = await scanRepositoryInAst(ast); + return findings; +} + +export async function scanOnboardingRepository( + repositoryDirectory: string, + selectedEntries: + | readonly string[] + | (( + findings: readonly RepositoryFinding[], + context: { + queues: OnboardingQueueEvidence; + scheduledCalls: readonly OnboardingScheduledCall[]; + concepts: OnboardingConceptEvidence; + }, + ) => readonly string[] | Promise<readonly string[]>), + limits: Partial<OnboardingTraceLimits> = {}, +): Promise<{ + findings: RepositoryFinding[]; + traces: OnboardingTrace[]; + concepts: OnboardingConceptEvidence; + queues: OnboardingQueueEvidence; + scheduledCalls: OnboardingScheduledCall[]; + loadedFiles: number; +}> { + const ast = createTypeScriptAst(repositoryDirectory); + const { findings, contextFindings } = await scanRepositoryInAst(ast); + const queues = discoverOnboardingQueuesInAst(ast); + const scheduledCalls = discoverOnboardingScheduledCallsInAst(ast, findings); + const concepts = discoverOnboardingConceptsInAst(ast); + const entries = + typeof selectedEntries === "function" + ? await selectedEntries(findings, { queues, scheduledCalls, concepts }) + : selectedEntries; + const selected = contextFindings.filter( + (route) => + route.kind === "application.route" && + entries.includes(`${route.data.controller}.${route.data.method}`), + ); + for (const job of findings.filter((item) => item.kind === "scheduled-job")) { + const data = job.data as unknown as Record<string, unknown>; + const name = data.name; + if (typeof name !== "string" || !entries.includes(name)) continue; + const [controller, method] = name.split("."); + if (!controller || !method) continue; + selected.push({ + id: `onboarding-entry:${job.id}`, + kind: "application.route", + data: { + controller, + method, + entryKind: "scheduled", + ...(typeof data.schedule === "string" || + typeof data.schedule === "number" + ? { schedule: String(data.schedule) } + : {}), + }, + evidence: job.evidence, + }); + } + return { + findings, + traces: analyzeOnboardingRoutes(ast, selected, { + maxEntries: entries.length, + ...limits, + }), + concepts, + queues, + scheduledCalls, + loadedFiles: ast.sourceFiles.length, + }; +} + +async function scanRepositoryInAst(ast: TypeScriptAst): Promise<{ + findings: RepositoryFinding[]; + contextFindings: HandoverContextFinding[]; +}> { + const { repositoryDirectory } = ast; const [projectFindings, fileFindings] = await Promise.all([ detectProject(repositoryDirectory), discoverRepositoryFiles(repositoryDirectory), ]); const contextFindings = discoverHandoverContextInAst(ast); - return [ - ...projectFindings, - ...discoverRabbitMqConsumersInAst(ast), - ...discoverScheduledJobsInAst(ast), - ...discoverSourceFeaturesInAst(ast), - ...contextFindings, - ...discoverRouteTracesInAst(ast, contextFindings), - ...fileFindings, - ]; + return { + contextFindings, + findings: [ + ...projectFindings, + ...discoverRabbitMqConsumersInAst(ast), + ...discoverScheduledJobsInAst(ast), + ...discoverSourceFeaturesInAst(ast), + ...contextFindings, + ...discoverRouteTracesInAst(ast, contextFindings), + ...fileFindings, + ], + }; } async function loadPackageJson( diff --git a/packages/scanners/src/onboarding-concepts.ts b/packages/scanners/src/onboarding-concepts.ts new file mode 100644 index 0000000..f41c0cf --- /dev/null +++ b/packages/scanners/src/onboarding-concepts.ts @@ -0,0 +1,172 @@ +import { relative } from "node:path"; + +import type { + OnboardingConceptEvidence, + OnboardingTraceLocation, +} from "@transferkit/core"; +import { Node } from "ts-morph"; + +import type { TypeScriptAst } from "./typescript-ast.js"; + +const relationNames = new Set([ + "OneToMany", + "ManyToOne", + "OneToOne", + "ManyToMany", +]); +const columnNames = new Set([ + "Column", + "PrimaryColumn", + "PrimaryGeneratedColumn", + "CreateDateColumn", + "UpdateDateColumn", + "DeleteDateColumn", + "VersionColumn", +]); + +export function discoverOnboardingConceptsInAst( + ast: TypeScriptAst, +): OnboardingConceptEvidence { + const entities: OnboardingConceptEvidence["entities"] = []; + const repositories: OnboardingConceptEvidence["repositories"] = []; + const methodResults: OnboardingConceptEvidence["methodResults"] = []; + const injections: OnboardingConceptEvidence["injections"] = []; + const at = (node: Node): OnboardingTraceLocation => ({ + file: relative(ast.repositoryDirectory, node.getSourceFile().getFilePath()), + line: node.getStartLineNumber(), + endLine: node.getEndLineNumber(), + origin: "code", + }); + for (const file of ast.sourceFiles) { + const imported = new Map<string, string>(); + for (const declaration of file.getImportDeclarations()) + for (const item of declaration.getNamedImports()) + imported.set( + item.getAliasNode()?.getText() ?? item.getName(), + `${declaration.getModuleSpecifierValue()}:${item.getName()}`, + ); + const typeorm = (name: string): string | undefined => + [...imported].find(([, value]) => value === `typeorm:${name}`)?.[0]; + const injectRepository = [...imported].find( + ([, value]) => value === "@nestjs/typeorm:InjectRepository", + )?.[0]; + for (const owner of file.getClasses()) { + const name = owner.getName(); + if (!name) continue; + if ( + owner + .getDecorators() + .some((decorator) => decorator.getName() === typeorm("Entity")) && + typeorm("Entity") + ) { + const fields: OnboardingConceptEvidence["entities"][number]["fields"] = + []; + const relations: OnboardingConceptEvidence["entities"][number]["relations"] = + []; + for (const property of owner.getProperties()) + for (const decorator of property.getDecorators()) { + const relation = [...relationNames].find( + (item) => decorator.getName() === typeorm(item), + ); + if (relation) { + const target = decorator + .getCallExpression() + ?.getArguments()[0] + ?.getText() + .match(/=>\s*([A-Za-z_$][\w$]*)/u)?.[1]; + if (target) + relations.push({ + property: property.getName(), + target, + kind: relation, + at: at(decorator), + }); + } else if ( + [...columnNames].some( + (item) => decorator.getName() === typeorm(item), + ) + ) + fields.push({ name: property.getName(), at: at(decorator) }); + } + entities.push({ name, declaration: at(owner), fields, relations }); + } + for (const constructor of owner.getConstructors()) + for (const parameter of constructor.getParameters()) { + const repository = parameter.getTypeNode()?.getText(); + if (!repository || !parameter.isParameterProperty()) continue; + injections.push({ + owner: name, + property: parameter.getName(), + repository, + at: at(parameter), + }); + } + const inherited = owner.getExtends()?.getText(); + const inheritedEntity = inherited?.match( + /<\s*([A-Za-z_$][\w$]*)\s*>/u, + )?.[1]; + const inheritedBase = inherited?.split("<")[0]; + const hasRepositoryBase = + inheritedBase === typeorm("Repository") || + owner.getConstructors().some((constructor) => + constructor.getParameters().some((parameter) => { + const type = parameter.getTypeNode()?.getText(); + return ( + type === + `${typeorm("Repository") ?? "Repository"}<${inheritedEntity}>` && + parameter + .getDecorators() + .some((decorator) => decorator.getName() === injectRepository) + ); + }), + ); + if (hasRepositoryBase && inheritedEntity) + repositories.push({ + repository: name, + entity: inheritedEntity, + at: at(owner.getExtends() ?? owner), + }); + if (hasRepositoryBase) + for (const method of owner.getMethods()) { + const declared = method.getReturnTypeNode()?.getText(); + const inner = + declared?.startsWith("Promise<") && declared.endsWith(">") + ? declared.slice(8, -1) + : declared; + const candidates = inner + ?.replace(/\[\]$/u, "") + .split("|") + .map((part) => part.trim()) + .filter((part) => part !== "undefined" && part !== "null"); + const result = + candidates?.length === 1 && + /^[A-Za-z_$][\w$]*$/u.test(candidates[0]!) + ? candidates[0] + : undefined; + if (result) + methodResults.push({ + repository: name, + method: method.getName(), + entity: result, + at: at(method), + }); + } + } + } + const entityNames = new Set(entities.map((entity) => entity.name)); + return { + entities: entities.map((entity) => ({ + ...entity, + relations: entity.relations.filter((relation) => + entityNames.has(relation.target), + ), + })), + repositories: repositories.filter((binding) => + entityNames.has(binding.entity), + ), + methodResults: methodResults.filter((result) => + entityNames.has(result.entity), + ), + injections, + }; +} diff --git a/packages/scanners/src/onboarding-queues.test.ts b/packages/scanners/src/onboarding-queues.test.ts new file mode 100644 index 0000000..81ae2d7 --- /dev/null +++ b/packages/scanners/src/onboarding-queues.test.ts @@ -0,0 +1,28 @@ +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { expect, it } from "vitest"; + +import { scanOnboardingRepository } from "./index.js"; + +const fixture = join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-phase4", +); + +it("finds literal BullMQ publications and processor registrations but skips dynamic names", async () => { + const result = await scanOnboardingRepository(fixture, [ + "ParcelController.dispatch", + ]); + expect( + result.queues.publications.map((item) => [item.queue, item.job]), + ).toEqual([ + ["parcel-jobs", "assign-parcel"], + ["other-jobs", "archive-parcel"], + ]); + expect(result.queues.handlers.map((item) => item.queue)).toEqual([ + "parcel-jobs", + "elsewhere", + ]); + expect(result.traces).toHaveLength(1); +}); diff --git a/packages/scanners/src/onboarding-queues.ts b/packages/scanners/src/onboarding-queues.ts new file mode 100644 index 0000000..e1bb4bc --- /dev/null +++ b/packages/scanners/src/onboarding-queues.ts @@ -0,0 +1,147 @@ +import { relative } from "node:path"; + +import type { + OnboardingQueueEvidence, + OnboardingTraceLocation, +} from "@transferkit/core"; +import { Node, SyntaxKind } from "ts-morph"; + +import type { TypeScriptAst } from "./typescript-ast.js"; + +/** Evidence for the @nestjs/bullmq Queue.add and WorkerHost.process pattern only. */ +export function discoverOnboardingQueuesInAst( + ast: TypeScriptAst, +): OnboardingQueueEvidence { + const publications: OnboardingQueueEvidence["publications"] = []; + const handlers: OnboardingQueueEvidence["handlers"] = []; + const at = (node: Node): OnboardingTraceLocation => ({ + file: relative(ast.repositoryDirectory, node.getSourceFile().getFilePath()), + line: node.getStartLineNumber(), + endLine: node.getEndLineNumber(), + origin: "code", + }); + const constants = new Map<string, Node[]>(); + for (const file of ast.sourceFiles) + for (const owner of file.getClasses()) + for (const property of owner + .getProperties() + .filter((item) => item.isStatic())) { + const initializer = property.getInitializer(); + if (owner.getName() !== "Constants" || !initializer) continue; + const hasLiteral = + Node.isStringLiteral(initializer) || + (Node.isBinaryExpression(initializer) && + initializer.getOperatorToken().getKind() === + SyntaxKind.BarBarToken && + Node.isStringLiteral(initializer.getRight())); + if (hasLiteral) { + const name = `Constants.${property.getName()}`; + constants.set(name, [...(constants.get(name) ?? []), property]); + } + } + const queue = (expression: Node | undefined): string | undefined => { + if (Node.isStringLiteral(expression)) return expression.getLiteralValue(); + if (Node.isPropertyAccessExpression(expression)) { + const known = constants.get(expression.getText()); + const declarations = expression + .getNameNode() + .getSymbol() + ?.getDeclarations(); + if ( + known?.length === 1 && + declarations?.some( + (declaration) => + declaration.getSourceFile().getFilePath() === + known[0]!.getSourceFile().getFilePath() && + declaration.getStartLineNumber() === known[0]!.getStartLineNumber(), + ) + ) + return expression.getText(); + } + return undefined; + }; + for (const file of ast.sourceFiles) { + const imports = new Map<string, string>(); + for (const declaration of file.getImportDeclarations()) + for (const item of declaration.getNamedImports()) + imports.set( + item.getAliasNode()?.getText() ?? item.getName(), + `${declaration.getModuleSpecifierValue()}:${item.getName()}`, + ); + const bullmq = (name: string): string | undefined => + [...imports].find(([, value]) => value === `@nestjs/bullmq:${name}`)?.[0]; + const queueType = [...imports].find( + ([, value]) => value === "bullmq:Queue", + )?.[0]; + const processor = bullmq("Processor"); + const injectQueue = bullmq("InjectQueue"); + const workerHost = bullmq("WorkerHost"); + for (const owner of file.getClasses()) { + const ownerName = owner.getName(); + if (!ownerName) continue; + const registration = processor + ? owner + .getDecorators() + .find((decorator) => decorator.getName() === processor) + : undefined; + const registeredQueue = queue( + registration?.getCallExpression()?.getArguments()[0], + ); + const process = owner.getMethod("process"); + if ( + registration && + registeredQueue && + process?.getBody() && + owner.getExtends()?.getText() === workerHost + ) + handlers.push({ + queue: registeredQueue, + symbol: `${ownerName}.process`, + registration: at(registration), + declaration: at(process), + }); + if (!injectQueue || !queueType) continue; + const injections = new Map< + string, + { name: string; at: OnboardingTraceLocation } + >(); + for (const constructor of owner.getConstructors()) + for (const parameter of constructor.getParameters()) { + if (!parameter.isParameterProperty()) continue; + if (parameter.getTypeNode()?.getText() !== queueType) continue; + const decorator = parameter + .getDecorators() + .find((item) => item.getName() === injectQueue); + const name = queue(decorator?.getCallExpression()?.getArguments()[0]); + if (decorator && name) + injections.set(parameter.getName(), { name, at: at(decorator) }); + } + if (!injections.size) continue; + for (const method of owner.getMethods()) + for (const call of method.getDescendantsOfKind( + SyntaxKind.CallExpression, + )) { + const access = call.getExpression(); + if ( + !Node.isPropertyAccessExpression(access) || + access.getName() !== "add" + ) + continue; + const receiver = access.getExpression(); + if (!Node.isPropertyAccessExpression(receiver)) continue; + if (receiver.getExpression().getText() !== "this") continue; + const injected = injections.get(receiver.getName()); + const job = call.getArguments()[0]; + if (!injected || !Node.isStringLiteral(job)) continue; + publications.push({ + caller: `${ownerName}.${method.getName()}`, + queue: injected.name, + job: job.getLiteralValue(), + at: at(call), + injection: injected.at, + }); + } + } + } + return { publications, handlers }; +} diff --git a/packages/scanners/src/onboarding-repository-notes.ts b/packages/scanners/src/onboarding-repository-notes.ts new file mode 100644 index 0000000..6fef0b2 --- /dev/null +++ b/packages/scanners/src/onboarding-repository-notes.ts @@ -0,0 +1,213 @@ +import { readFile, stat } from "node:fs/promises"; +import { basename, dirname, join } from "node:path"; + +import type { + Finding, + OnboardingRepositoryNote, + OnboardingTrace, +} from "@transferkit/core"; + +const unsafe = + /(?:password|secret|api[_-]?key|private[_-]?key|token)\s*[:=]|-----BEGIN|process\.env\.[A-Z_]+\s*=/iu; +const generic = + /(?:nest(?:js)? (?:framework|starter)|starter (?:repository|template)|boilerplate|generated by|welcome to)/iu; + +export async function discoverOnboardingRepositoryNotes( + directory: string, + traces: readonly OnboardingTrace[], + findings: readonly Finding[], +): Promise<OnboardingRepositoryNote[]> { + const notes: OnboardingRepositoryNote[] = []; + const readme = await optionalText(join(directory, "README.md")); + if (readme) { + const lines = readme.split(/\r?\n/u); + const heading = lines.findIndex((line) => + /^#{1,3}\s+(?:description|about|overview)\b/iu.test(line), + ); + const start = + heading >= 0 ? heading + 1 : /^#\s+/u.test(lines[0] ?? "") ? 1 : 0; + const paragraph: string[] = []; + let paragraphLine = start + 1; + for ( + let index = start; + index < Math.min(lines.length, start + 12); + index++ + ) { + const line = lines[index]!.trim(); + if (/^#|^```|^[-*] |^\|/u.test(line)) break; + if (!line) { + if (paragraph.length) break; + else continue; + } + if (!paragraph.length) paragraphLine = index + 1; + paragraph.push(line); + } + const text = paragraph.join(" ").replace(/\[([^\]]+)\]\([^)]*\)/gu, "$1"); + if ( + text.length >= 30 && + text.length <= 350 && + !generic.test(text) && + !unsafe.test(text) + ) + notes.push({ + kind: "description", + text, + file: "README.md", + line: paragraphLine, + }); + } + const packageText = await optionalText(join(directory, "package.json")); + if (packageText) { + try { + const pkg = JSON.parse(packageText) as { scripts?: { start?: unknown } }; + const start = pkg.scripts?.start; + const entry = + typeof start === "string" + ? /^node\s+((?:[\w-]+\/)*[\w.-]+\.m?js)$/u.exec(start)?.[1] + : undefined; + if ( + entry && + !entry.includes("..") && + (await exists(join(directory, entry))) + ) + notes.push({ + kind: "entry", + text: `The declared start script points to ${entry}.`, + file: entry, + line: 1, + }); + } catch (error) { + if (!(error instanceof SyntaxError)) throw error; + } + } + const sourceCache = new Map<string, string[] | undefined>(); + for (const trace of traces) { + for (const method of trace.methods.slice(0, 8)) { + const file = method.declaration.file; + if (!sourceCache.has(file)) { + const source = await optionalText(join(directory, file)); + sourceCache.set(file, source?.split(/\r?\n/u)); + } + const lines = sourceCache.get(file); + if (!lines) continue; + const begin = Math.max(0, method.declaration.line - 5); + const end = Math.min( + lines.length, + method.declaration.endLine, + method.declaration.line + 100, + ); + let count = 0; + for (let index = begin; index < end && count < 2; index++) { + const match = /^\s*(?:\/\/|\*|\/\*\*?)\s*(.+?)\s*(?:\*\/)?\s*$/u.exec( + lines[index] ?? "", + ); + if (!match) continue; + const firstLine = index + 1; + const parts = [match[1]!.trim()]; + while (index + 1 < end && parts.length < 4) { + if (/[.!?]$/u.test(parts.at(-1) ?? "")) break; + const following = /^\s*\/\/\s*(.+)$/u.exec(lines[index + 1] ?? ""); + if (!following || parts.join(" ").length + following[1]!.length > 300) + break; + parts.push(following[1]!.trim()); + index++; + } + const text = parts.join(" ").split(/(?<=[.!?])\s+(?=[A-Z`])/u)[0]!; + if ( + text.length < 28 || + text.length > 300 || + unsafe.test(text) || + /\b(?:otp|password|secret|token|api[_-]?key)\b|[;{}=<>]|:contentReference|^\s*[\w.]+\s*:|\b(?:const|return|throw|if)\s*\(/iu.test( + text, + ) || + /^@|^TODO\b|^eslint|^ts-/iu.test(text) + ) + continue; + notes.push({ + kind: "comment", + text, + file, + line: firstLine, + journey: trace.entry.symbol, + }); + count++; + } + } + const seen = new Set<string>(); + for (const method of trace.methods.slice(0, 6)) { + const file = method.declaration.file; + const stem = basename(file).replace(/\.[jt]sx?$/iu, ""); + for (const suffix of ["spec.ts", "test.ts", "spec.js", "test.js"]) { + const sibling = join(dirname(file), `${stem}.${suffix}`); + if (seen.has(sibling) || !(await exists(join(directory, sibling)))) + continue; + seen.add(sibling); + notes.push({ + kind: "test", + text: `Nearby test file for ${method.symbol}; its assertions have not been evaluated here.`, + file: sibling, + line: 1, + journey: trace.entry.symbol, + }); + } + } + } + const entities = new Set( + traces + .flatMap((trace) => + trace.methods.map((method) => + method.symbol + .split(".")[0]! + .replace(/(?:Service|Repository)$/u, "") + .toLowerCase(), + ), + ) + .filter((name) => name.length >= 5), + ); + for (const finding of findings.filter( + (item) => item.kind === "database.migration", + )) { + if (notes.filter((note) => note.kind === "migration").length >= 3) break; + const file = finding.evidence[0]?.file; + if ( + !file || + ![...entities].some((name) => file.toLowerCase().includes(name)) + ) + continue; + notes.push({ + kind: "migration", + text: "Migration file name matches a selected source owner; inspect its contents before treating it as related behavior.", + file, + line: 1, + }); + } + return notes.slice(0, 24); +} + +async function optionalText(file: string): Promise<string | undefined> { + try { + if ((await stat(file)).size > 128_000) return undefined; + return await readFile(file, "utf8"); + } catch (error) { + if (isMissing(error)) return undefined; + throw error; + } +} + +async function exists(file: string): Promise<boolean> { + try { + return (await stat(file)).isFile(); + } catch (error) { + if (isMissing(error)) return false; + throw error; + } +} + +function isMissing(error: unknown): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + error.code === "ENOENT" + ); +} diff --git a/packages/scanners/src/onboarding-scheduled.ts b/packages/scanners/src/onboarding-scheduled.ts new file mode 100644 index 0000000..9471033 --- /dev/null +++ b/packages/scanners/src/onboarding-scheduled.ts @@ -0,0 +1,90 @@ +import { relative } from "node:path"; + +import type { + Finding, + OnboardingScheduledCall, + OnboardingTraceLocation, +} from "@transferkit/core"; +import { Node, SyntaxKind } from "ts-morph"; + +import type { TypeScriptAst } from "./typescript-ast.js"; + +/** Direct calls in declared Nest scheduled handlers; callbacks and helpers remain unlinked. */ +export function discoverOnboardingScheduledCallsInAst( + ast: TypeScriptAst, + findings: readonly Finding[], +): OnboardingScheduledCall[] { + const files = new Map( + ast.sourceFiles.map((file) => [ + relative(ast.repositoryDirectory, file.getFilePath()), + file, + ]), + ); + const at = (node: Node): OnboardingTraceLocation => ({ + file: relative(ast.repositoryDirectory, node.getSourceFile().getFilePath()), + line: node.getStartLineNumber(), + endLine: node.getEndLineNumber(), + origin: "code", + }); + const calls: OnboardingScheduledCall[] = []; + for (const finding of findings.filter( + (item) => item.kind === "scheduled-job", + )) { + const data = finding.data as Record<string, unknown>; + const name = data.name; + if (typeof name !== "string") continue; + const [ownerName, methodName] = name.split("."); + const registration = finding.evidence[0]; + if (!ownerName || !methodName || !registration) continue; + const method = files + .get(registration.file) + ?.getClass(ownerName) + ?.getMethod(methodName); + if (!method?.getBody()) continue; + for (const call of method + .getBody()! + .getDescendantsOfKind(SyntaxKind.CallExpression)) { + if ( + call + .getAncestors() + .some( + (ancestor) => + Node.isArrowFunction(ancestor) || + Node.isFunctionExpression(ancestor), + ) + ) + continue; + const access = call.getExpression(); + if (!Node.isPropertyAccessExpression(access)) continue; + const receiver = access.getExpression(); + if ( + !Node.isPropertyAccessExpression(receiver) || + receiver.getExpression().getText() !== "this" + ) + continue; + const action = access.getName(); + const effect = /^(?:save|insert|update|remove|delete)$/u.test(action) + ? "write-like" + : /^(?:find|findOne|findBy|count)$/u.test(action) + ? "read-like" + : undefined; + calls.push({ + job: name, + ...(typeof data.schedule === "string" || + typeof data.schedule === "number" + ? { schedule: String(data.schedule) } + : {}), + registration: { + file: registration.file, + line: registration.line ?? 1, + endLine: registration.line ?? 1, + origin: "code", + }, + at: at(call), + detail: access.getText(), + ...(effect ? { effect } : {}), + }); + } + } + return calls; +} diff --git a/packages/scanners/src/onboarding-story.test.ts b/packages/scanners/src/onboarding-story.test.ts new file mode 100644 index 0000000..8d0deda --- /dev/null +++ b/packages/scanners/src/onboarding-story.test.ts @@ -0,0 +1,144 @@ +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { describe, expect, it } from "vitest"; + +import type { OnboardingConceptEvidence } from "@transferkit/core"; + +import { discoverOnboardingStoryEvidence } from "./onboarding-story.js"; +import { scanOnboardingRepository } from "./index.js"; + +const root = fileURLToPath(new URL("../../../fixtures/", import.meta.url)); +const empty: OnboardingConceptEvidence = { + entities: [], + repositories: [], + methodResults: [], + injections: [], +}; + +describe("cited onboarding story evidence", () => { + it("identifies a CLI command, documented input and output without HTTP assumptions", async () => { + const evidence = await discoverOnboardingStoryEvidence( + join(root, "onboarding-human-cli"), + [], + empty, + ); + const claims = evidence.claims; + expect(claims.find((claim) => claim.kind === "purpose")?.text).toContain( + "event file", + ); + expect(claims.find((claim) => claim.kind === "entry")?.name).toBe( + "event-count", + ); + expect( + claims.some( + (claim) => + claim.kind === "artifact" && claim.text.includes("event file"), + ), + ).toBe(true); + expect( + claims.some( + (claim) => + claim.kind === "output" && claim.text.includes("prints a count"), + ), + ).toBe(true); + expect( + claims.find((claim) => claim.kind === "entry")?.evidence, + ).toContainEqual({ + file: "src/cli.js", + line: 1, + }); + expect( + claims.filter((claim) => claim.kind === "observation"), + ).toContainEqual( + expect.objectContaining({ + text: expect.stringContaining("Documented alternate: A missing path"), + evidence: [{ file: "README.md", line: 5 }], + }), + ); + }); + + it("finds a documented Python entry while leaving unsupported internals unknown", async () => { + const evidence = await discoverOnboardingStoryEvidence( + join(root, "onboarding-human-sparse"), + [], + empty, + ); + expect( + evidence.claims.find((claim) => claim.kind === "purpose")?.text, + ).toContain("compares item counts"); + expect( + evidence.claims + .filter((claim) => claim.kind === "entry") + .map((claim) => claim.name), + ).toContain("compare.py"); + expect( + evidence.claims.some( + (claim) => + claim.kind === "output" && claim.text.includes("standard output"), + ), + ).toBe(true); + expect( + evidence.claims.filter((claim) => claim.kind === "boundary"), + ).toEqual([]); + }); + + it("uses a plain Node service description without inventing persistent state", async () => { + const evidence = await discoverOnboardingStoryEvidence( + join(root, "onboarding-plain-node"), + [], + empty, + ); + expect( + evidence.claims.find((claim) => claim.kind === "role")?.text, + ).toContain("service"); + expect( + evidence.claims.some( + (claim) => + claim.kind === "entry" && claim.text.includes("src/server.js"), + ), + ).toBe(true); + expect( + evidence.claims.some( + (claim) => + claim.kind === "output" && claim.text.includes("health check"), + ), + ).toBe(true); + expect( + evidence.claims.filter((claim) => claim.kind === "boundary"), + ).toEqual([]); + }); + + it("rejects a Nest starter purpose and keeps route, schedule and entity roles bounded", async () => { + const directory = join(root, "onboarding-phase4"); + const scanned = await scanOnboardingRepository(directory, []); + const evidence = await discoverOnboardingStoryEvidence( + directory, + scanned.findings, + scanned.concepts, + ); + expect(evidence.claims.some((claim) => claim.kind === "purpose")).toBe( + false, + ); + expect( + evidence.rejectedDescriptions.some( + (item) => item.reason === "generic starter text", + ), + ).toBe(true); + expect( + evidence.claims.some( + (claim) => + claim.kind === "entry" && claim.name === "ParcelController.dispatch", + ), + ).toBe(true); + expect( + evidence.claims.some( + (claim) => claim.kind === "entry" && claim.text.includes("scheduled"), + ), + ).toBe(true); + expect(evidence.terms.some((term) => term.name === "Parcel")).toBe(true); + expect( + evidence.terms.find((term) => term.name === "Parcel")?.meaning, + ).toBeUndefined(); + }); +}); diff --git a/packages/scanners/src/onboarding-story.ts b/packages/scanners/src/onboarding-story.ts new file mode 100644 index 0000000..bcf4868 --- /dev/null +++ b/packages/scanners/src/onboarding-story.ts @@ -0,0 +1,582 @@ +import { readFile, stat } from "node:fs/promises"; +import { join } from "node:path"; + +import type { + Finding, + OnboardingConceptEvidence, + OnboardingStoryClaim, + OnboardingStoryEvidence, +} from "@transferkit/core"; + +const documentFiles = [ + "README.md", + "docs/README.md", + "docs/ABOUT.md", + "docs/OVERVIEW.md", +] as const; +const starter = + /(?:nest(?:js)? (?:framework|starter)|starter (?:repository|template|project)|boilerplate|generated by|welcome to|progressive node\.js framework|create-react-app)/iu; +const sensitive = + /(?:password|secret|api[_-]?key|private[_-]?key|token)\s*[:=]|-----BEGIN|process\.env\.[A-Z_]+\s*=/iu; + +export async function discoverOnboardingStoryEvidence( + directory: string, + findings: readonly Finding[], + concepts: OnboardingConceptEvidence, +): Promise<OnboardingStoryEvidence> { + const claims: OnboardingStoryClaim[] = []; + const rejectedDescriptions: OnboardingStoryEvidence["rejectedDescriptions"] = + []; + const paragraphs: { + text: string; + file: string; + line: number; + endLine: number; + }[] = []; + for (const file of documentFiles) { + const source = await optionalText(join(directory, file)); + if (!source) continue; + const genericDocument = starter.test(source.slice(0, 1200)); + for (const match of source.matchAll( + /`((?:npm (?:run )?(?:start|test)(?:\s+--)?|python3?\s+[\w./-]+\.py)(?:\s+[^`\n]{1,90})?)`/gu, + )) { + const command = match[1]!.trim(); + if (genericDocument || sensitive.test(command)) continue; + claims.push({ + kind: "observation", + text: `Documented command: ${command}. It has not been run by TransferKit.`, + basis: "repository-statement", + evidence: [ + { file, line: source.slice(0, match.index).split(/\r?\n/u).length }, + ], + }); + } + if (!genericDocument) + for (const match of source.matchAll( + /(?:^|[.!?]\s+)([^.!?\n]{0,180}\b(?:missing|invalid|rejected|error|nonzero|404)\b[^.!?\n]{0,180}[.!?])/gimu, + )) { + const statement = match[1]!.trim(); + if (sensitive.test(statement)) continue; + const line = source + .slice(0, match.index! + match[0].indexOf(match[1]!)) + .split(/\r?\n/u).length; + claims.push({ + kind: "observation", + text: `Documented alternate: ${statement}`, + basis: "repository-statement", + evidence: [{ file, line }], + }); + } + for (const match of source.matchAll(/\bpython3?\s+([\w./-]+\.py)\b/gu)) { + const target = match[1]!; + if (!(await localFile(directory, target))) continue; + claims.push({ + kind: "entry", + name: target, + text: `The documented Python command enters at ${target}.`, + basis: "repository-statement", + evidence: [ + { file, line: source.slice(0, match.index).split(/\r?\n/u).length }, + { file: target, line: 1 }, + ], + }); + } + const paragraph = projectParagraph(source); + if (!paragraph) continue; + const evidence = Array.from( + { length: paragraph.endLine - paragraph.line + 1 }, + (_, offset) => ({ file, line: paragraph.line + offset }), + ); + if (starter.test(paragraph.text) || sensitive.test(paragraph.text)) { + rejectedDescriptions.push({ + text: paragraph.text, + evidence, + reason: starter.test(paragraph.text) + ? "generic starter text" + : "potentially sensitive text", + }); + continue; + } + paragraphs.push({ ...paragraph, file }); + claims.push({ + kind: "purpose", + text: paragraph.text, + basis: "repository-statement", + evidence, + }); + const role = + /\b(command-line tool|CLI|service|library|worker|utility)\b/iu.exec( + paragraph.text, + )?.[1]; + if (role) + claims.push({ + kind: "role", + text: `The repository describes itself as a ${role}.`, + basis: "repository-statement", + evidence, + }); + for (const sentence of paragraph.text.split(/(?<=[.!?])\s+/u)) { + if ( + /\b(?:reads?|accepts?|takes?)\b.{0,100}\b(?:file|input|csv|json)/iu.test( + sentence, + ) + ) + claims.push({ + kind: "artifact", + text: sentence, + basis: "repository-statement", + evidence, + }); + if (/\b(?:prints?|writes?|returns?|outputs?|exposes?)\b/iu.test(sentence)) + claims.push({ + kind: "output", + text: sentence, + basis: "repository-statement", + evidence, + }); + } + } + + const packageSource = await optionalText(join(directory, "package.json")); + if (packageSource) { + try { + const pkg = JSON.parse(packageSource) as Record<string, unknown>; + const engines = stringMap(pkg.engines); + if (engines.node) + claims.push({ + kind: "observation", + text: `Declared runtime: Node.js ${engines.node}.`, + basis: "code-observation", + evidence: [ + { file: "package.json", line: propertyLine(packageSource, "node") }, + ], + }); + for (const [name, version] of Object.entries(stringMap(pkg.dependencies)) + .filter(([name]) => + /^(?:@nestjs\/core|@nestjs\/typeorm|@nestjs\/bullmq|express|fastify|next|react|typeorm|pg|prisma|bullmq|amqplib|commander|yargs)$/u.test( + name, + ), + ) + .slice(0, 8)) + claims.push({ + kind: "observation", + text: `Declared runtime dependency: ${name} ${version}.`, + basis: "code-observation", + evidence: [ + { file: "package.json", line: propertyLine(packageSource, name) }, + ], + }); + if ( + typeof pkg.description === "string" && + pkg.description.length >= 24 && + pkg.description.length <= 250 + ) { + const evidence = [ + { + file: "package.json", + line: propertyLine(packageSource, "description"), + }, + ]; + if (starter.test(pkg.description) || sensitive.test(pkg.description)) + rejectedDescriptions.push({ + text: pkg.description, + evidence, + reason: starter.test(pkg.description) + ? "generic starter text" + : "potentially sensitive text", + }); + else + claims.push({ + kind: "purpose", + text: pkg.description, + basis: "repository-statement", + evidence, + }); + } + const bins = + typeof pkg.bin === "string" && typeof pkg.name === "string" + ? { [pkg.name]: pkg.bin } + : stringMap(pkg.bin); + for (const [command, file] of Object.entries(bins).slice(0, 8)) { + if (!(await localFile(directory, file))) continue; + claims.push({ + kind: "entry", + name: command, + text: `The ${command} command enters at ${file}.`, + basis: "code-observation", + evidence: [ + { + file: "package.json", + line: propertyLine(packageSource, command), + }, + { file, line: 1 }, + ], + }); + claims.push({ + kind: "role", + text: `This package declares the ${command} command.`, + basis: "code-observation", + evidence: [ + { + file: "package.json", + line: propertyLine(packageSource, command), + }, + ], + }); + } + for (const field of ["main", "module"] as const) { + const file = pkg[field]; + if (typeof file !== "string" || !(await localFile(directory, file))) + continue; + claims.push({ + kind: "entry", + name: field, + text: `The package ${field} entry points to ${file}.`, + basis: "code-observation", + evidence: [ + { file: "package.json", line: propertyLine(packageSource, field) }, + { file, line: 1 }, + ], + }); + } + const exportRoot = object(pkg.exports)["."]; + const exportFile = + typeof exportRoot === "string" + ? exportRoot + : (string(object(exportRoot).default) ?? + string(object(exportRoot).import)); + if (exportFile && (await localFile(directory, exportFile))) + claims.push({ + kind: "entry", + name: "public export", + text: `The package public export points to ${exportFile}.`, + basis: "code-observation", + evidence: [ + { + file: "package.json", + line: propertyLine(packageSource, "exports"), + }, + { file: exportFile, line: 1 }, + ], + }); + const start = stringMap(pkg.scripts).start; + const startFile = + start && /^node\s+([\w./-]+\.m?js)(?:\s|$)/u.exec(start)?.[1]; + if (startFile && (await localFile(directory, startFile))) + claims.push({ + kind: "entry", + name: "start", + text: `The start script enters at ${startFile}.`, + basis: "code-observation", + evidence: [ + { + file: "package.json", + line: propertyLine(packageSource, "start"), + }, + { file: startFile, line: 1 }, + ], + }); + } catch (error) { + if (!(error instanceof SyntaxError)) throw error; + } + } + + let sawRoute = false; + let sawScheduled = false; + let routeEvidence: OnboardingStoryClaim["evidence"] = []; + let scheduledEvidence: OnboardingStoryClaim["evidence"] = []; + for (const finding of findings) { + const data = object(finding.data); + const evidence = finding.evidence.filter((item) => item.file).slice(0, 3); + if (!evidence.length) continue; + if (finding.kind === "application.route") { + sawRoute = true; + if (!routeEvidence.length) routeEvidence = evidence; + const verb = string(data.verb); + const path = string(data.path); + const owner = string(data.controller); + const method = string(data.method); + if (!owner || !method) continue; + claims.push({ + kind: "entry", + name: `${owner}.${method}`, + text: `${verb ?? "HTTP"} ${path ?? "route with unresolved path"} is declared on ${owner}.${method}.`, + basis: "code-observation", + evidence, + }); + if (path?.includes("health")) + claims.push({ + kind: "observation", + text: `${verb ?? "HTTP"} ${path} is a declared health route; a live result is unverified.`, + basis: "code-observation", + evidence, + }); + } else if (finding.kind === "scheduled-job") { + sawScheduled = true; + if (!scheduledEvidence.length) scheduledEvidence = evidence; + const name = string(data.name); + if (name) + claims.push({ + kind: "entry", + name, + text: `${name} is registered as a scheduled entry.`, + basis: "code-observation", + evidence, + }); + } else if (finding.kind === "messaging.consumer") { + const handler = string(data.handler); + if (handler) + claims.push({ + kind: "entry", + name: handler, + text: `${handler} is declared as a message consumer.`, + basis: "code-observation", + evidence, + }); + } else if (finding.kind === "integration") { + const client = string(data.client); + if (client) + claims.push({ + kind: "boundary", + name: client, + text: `${client} is a declared integration dependency; calls and delivery are unverified.`, + basis: "code-observation", + evidence, + }); + } else if (finding.kind === "database" || finding.kind === "messaging") { + const technology = string(data.name); + if (technology) + claims.push({ + kind: "boundary", + name: technology, + text: `${technology} is declared as a ${finding.kind} dependency; runtime use is unverified.`, + basis: "code-observation", + evidence, + }); + } else if (finding.kind === "setup.command") { + const command = string(data.command); + if ( + command && + data.generic !== "yes" && + /(?:test|start)/u.test(string(data.purpose) ?? "") + ) + claims.push({ + kind: "observation", + text: `${command} is declared or documented; it has not been executed.`, + basis: "code-observation", + evidence, + }); + } + } + if (sawRoute) { + claims.push({ + kind: "role", + text: "This repository declares HTTP route handlers.", + basis: "code-observation", + evidence: routeEvidence, + }); + } + if (sawScheduled) { + claims.push({ + kind: "role", + text: "This repository declares scheduled work.", + basis: "code-observation", + evidence: scheduledEvidence, + }); + } + + const incoming = new Map<string, number>(); + for (const entity of concepts.entities) + for (const relation of entity.relations) + incoming.set(relation.target, (incoming.get(relation.target) ?? 0) + 1); + const centralEntities = [...concepts.entities] + .sort( + (left, right) => + (incoming.get(right.name) ?? 0) + + right.relations.length - + ((incoming.get(left.name) ?? 0) + left.relations.length) || + left.name.localeCompare(right.name), + ) + .slice(0, 80); + for (const entity of centralEntities) { + claims.push({ + kind: "artifact", + name: entity.name, + text: `${entity.name} is a declared data entity; its business meaning is not established by the declaration alone.`, + basis: "code-observation", + evidence: [ + { file: entity.declaration.file, line: entity.declaration.line }, + ], + }); + } + const terms = centralEntities.map((entity) => { + const relationEvidence = concepts.entities + .flatMap((source) => + source.relations + .filter((relation) => relation.target === entity.name) + .map((relation) => ({ + file: relation.at.file, + line: relation.at.line, + })), + ) + .slice(0, 8); + const meaning = explicitMeaning(entity.name, paragraphs); + return { + name: entity.name, + codeRole: "declared data entity", + relationCount: entity.relations.length + (incoming.get(entity.name) ?? 0), + relations: entity.relations.slice(0, 80).map((relation) => ({ + property: relation.property, + target: relation.target, + evidence: [{ file: relation.at.file, line: relation.at.line }], + })), + evidence: [ + { file: entity.declaration.file, line: entity.declaration.line }, + ...relationEvidence, + ], + ...(meaning ? { meaning } : {}), + }; + }); + const limits: Record<OnboardingStoryClaim["kind"], number> = { + purpose: 8, + role: 6, + entry: 80, + artifact: 80, + output: 12, + boundary: 24, + observation: 20, + }; + const counts: Record<OnboardingStoryClaim["kind"], number> = { + purpose: 0, + role: 0, + entry: 0, + artifact: 0, + output: 0, + boundary: 0, + observation: 0, + }; + return { + claims: claims.filter((claim) => counts[claim.kind]++ < limits[claim.kind]), + terms, + rejectedDescriptions, + }; +} + +function projectParagraph( + source: string, +): { text: string; line: number; endLine: number } | undefined { + const lines = source.split(/\r?\n/u).slice(0, 80); + let start = /^#\s/u.test(lines[0] ?? "") ? 1 : 0; + const heading = lines.findIndex((line) => + /^#{1,3}\s+(?:about|overview|description|purpose)\b/iu.test(line), + ); + if (heading >= 0) start = heading + 1; + for (let index = start; index < Math.min(lines.length, start + 24); index++) { + if (!lines[index]?.trim()) continue; + if (/^\s*(?:#|[-*] |\||```)/u.test(lines[index]!)) break; + const parts: string[] = []; + const line = index + 1; + for (; index < lines.length && parts.length < 6; index++) { + const part = lines[index]!.trim(); + if (!part || /^\s*(?:#|[-*] |\||```)/u.test(part)) break; + parts.push(part); + } + const text = parts + .join(" ") + .replace(/\[([^\]]+)\]\([^)]*\)/gu, "$1") + .trim(); + return text.length >= 28 && text.length <= 500 + ? { text, line, endLine: line + parts.length - 1 } + : undefined; + } + return undefined; +} + +function explicitMeaning( + name: string, + paragraphs: readonly { + text: string; + file: string; + line: number; + endLine: number; + }[], +): OnboardingStoryClaim | undefined { + for (const paragraph of paragraphs) { + const sentence = paragraph.text + .split(/(?<=[.!?])\s+/u) + .find((part) => + new RegExp(`\\b${name}\\s+(?:is|represents|means)\\b`, "iu").test(part), + ); + if (sentence) + return { + kind: "artifact", + name, + text: sentence, + basis: "repository-statement", + evidence: Array.from( + { length: paragraph.endLine - paragraph.line + 1 }, + (_, offset) => ({ + file: paragraph.file, + line: paragraph.line + offset, + }), + ), + }; + } + return undefined; +} + +async function optionalText(file: string): Promise<string | undefined> { + try { + if ((await stat(file)).size > 128_000) return undefined; + return await readFile(file, "utf8"); + } catch (error) { + if (isMissing(error)) return undefined; + throw error; + } +} + +async function localFile(directory: string, file: string): Promise<boolean> { + if (!/^[\w./-]+$/u.test(file) || file.startsWith("/") || file.includes("..")) + return false; + try { + return (await stat(join(directory, file))).isFile(); + } catch (error) { + if (isMissing(error)) return false; + throw error; + } +} + +function propertyLine(source: string, key: string): number { + const index = source + .split(/\r?\n/u) + .findIndex((line) => line.includes(JSON.stringify(key))); + return index < 0 ? 1 : index + 1; +} + +function stringMap(value: unknown): Record<string, string> { + if (!value || typeof value !== "object" || Array.isArray(value)) return {}; + return Object.fromEntries( + Object.entries(value).filter((entry): entry is [string, string] => + entry.every((part) => typeof part === "string"), + ), + ); +} + +function object(value: unknown): Record<string, unknown> { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record<string, unknown>) + : {}; +} + +function string(value: unknown): string | undefined { + return typeof value === "string" ? value : undefined; +} + +function isMissing(error: unknown): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + error.code === "ENOENT" + ); +} diff --git a/packages/scanners/src/onboarding-trace.test.ts b/packages/scanners/src/onboarding-trace.test.ts new file mode 100644 index 0000000..8705267 --- /dev/null +++ b/packages/scanners/src/onboarding-trace.test.ts @@ -0,0 +1,228 @@ +import { existsSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { describe, expect, it } from "vitest"; + +import { discoverHandoverContextInAst } from "./handover-context.js"; +import { scanOnboardingRepository, scanRepository } from "./index.js"; +import { analyzeOnboardingRoutes } from "./onboarding-trace.js"; +import { createTypeScriptAst } from "./typescript-ast.js"; + +const fixture = join( + dirname(fileURLToPath(import.meta.url)), + "../../../fixtures/onboarding-deep-guide", +); + +function traces() { + const ast = createTypeScriptAst(fixture); + const routes = discoverHandoverContextInAst(ast); + return analyzeOnboardingRoutes(ast, routes); +} + +describe("bounded onboarding traces", () => { + it("shares the scanner's project while retaining existing findings", async () => { + const selected = await scanOnboardingRepository(fixture, [ + "OrderController.submit", + "OrderController.preview", + ]); + const regular = await scanRepository(fixture); + expect(selected.traces).toHaveLength(2); + expect(selected.loadedFiles).toBeGreaterThan(0); + expect(selected.findings.map((finding) => finding.id)).toEqual( + regular.map((finding) => finding.id), + ); + expect(selected.concepts.entities.map((item) => item.name)).toEqual([ + "AccountEntity", + "OrderEntity", + ]); + expect(selected.concepts.repositories).toContainEqual( + expect.objectContaining({ + repository: "OrderRepository", + entity: "OrderEntity", + }), + ); + expect(selected.concepts.entities[1]?.relations).toContainEqual( + expect.objectContaining({ + property: "account", + target: "AccountEntity", + kind: "ManyToOne", + }), + ); + }); + + it("reuses one scan context for two selected routes and cites declared targets", () => { + expect(existsSync(join(fixture, "tsconfig.json"))).toBe(false); + expect(existsSync(join(fixture, "node_modules"))).toBe(false); + const ast = createTypeScriptAst(fixture); + const routes = discoverHandoverContextInAst(ast).filter( + (route) => + route.kind === "application.route" && + route.data.controller === "OrderController", + ); + const results = analyzeOnboardingRoutes(ast, routes); + expect(results).toHaveLength(2); + expect(results.map((trace) => trace.entry.symbol)).toEqual([ + "OrderController.submit", + "OrderController.preview", + ]); + for (const trace of results) { + const edge = trace.calls.find( + (call) => call.declaredTarget === "OrderService.create", + ); + expect(edge?.site.file).toBe("controller.ts"); + expect(edge?.declaration?.file).toBe("service.ts"); + expect(edge?.kind).toBe("declared-target"); + } + expect(ast.project.getSourceFiles()).toEqual(ast.sourceFiles); + }); + + it("keeps exits and exclusive writes separate, including repeated helper call sites", () => { + const trace = traces().find( + (item) => item.entry.symbol === "OrderController.submit", + )!; + const events = trace.methods.find( + (method) => method.symbol === "OrderService.create", + )!.events; + const invalid = "when !input.valid at 44"; + expect(events.find((event) => event.kind === "throw")?.path).toContain( + invalid, + ); + expect( + events.find((event) => event.kind === "throw")?.detail, + ).not.toContain("invalid order"); + expect( + events.filter( + (event) => + event.path.includes(invalid) && + (event.kind === "call" || event.kind === "assignment"), + ), + ).toEqual([]); + expect(events.find((event) => event.at.line === 48)?.path).toContain( + "when input.priority at 47", + ); + expect(events.find((event) => event.at.line === 50)?.path).toContain( + "otherwise input.priority at 47", + ); + expect( + trace.calls + .filter((edge) => edge.declaredTarget === "OrderService.recordAttempt") + .map((edge) => edge.site.line), + ).toEqual([52, 53]); + expect( + trace.calls.every( + (edge) => edge.site.file !== "controller.ts" || edge.site.line >= 10, + ), + ).toBe(true); + }); + + it("labels local manager attempts and transaction calls without claiming outcomes", () => { + const trace = traces().find( + (item) => item.entry.symbol === "OrderController.submit", + )!; + const events = trace.methods.find( + (method) => method.symbol === "OrderService.create", + )!.events; + expect(events.find((event) => event.at.line === 56)?.effect).toBe( + "write-like", + ); + expect(events.find((event) => event.at.line === 56)?.awaited).toBe(true); + expect(events.find((event) => event.at.line === 57)?.effect).toBe( + "transaction-like", + ); + expect(events.find((event) => event.at.line === 59)?.path).toContain( + "catch", + ); + expect(events.filter((event) => event.at.line === 62)).toHaveLength(2); + expect( + events.find((event) => event.at.line === 65)?.effect, + ).toBeUndefined(); + expect(trace.calls.find((edge) => edge.site.line === 56)?.kind).toBe( + "unresolved", + ); + }); + + it("records unsupported constructs and a nested call without false edges", () => { + const trace = traces().find( + (item) => item.entry.symbol === "LimitsController.check", + )!; + expect(trace.methods.map((method) => method.symbol)).toEqual([ + "LimitsController.check", + "LimitsController.value", + ]); + expect(trace.gaps.map((gap) => gap.reason)).toEqual( + expect.arrayContaining([ + "Nested call target is known; argument evaluation order is not represented as a separate step.", + "Call inside callback is not traced.", + "Dynamic dispatch is unresolved.", + "Unsupported control flow: ForStatement.", + "Unsupported control flow: SwitchStatement.", + ]), + ); + const returnPath = trace.methods[0]!.events.find( + (event) => event.kind === "return", + )!.path; + expect(returnPath).toContain("when mode === [literal] at 15"); + expect( + trace.methods[0]!.events.filter( + (event) => event.kind === "call" && event.path.includes(returnPath[0]!), + ), + ).toEqual([]); + expect( + trace.calls.some((edge) => edge.declaredTarget?.includes("Dispatcher")), + ).toBe(false); + expect( + trace.calls.find( + (edge) => edge.declaredTarget === "LimitsController.value", + )?.evaluation, + ).toBe("nested-argument"); + }); + + it("keeps an inherited declaration unresolved", () => { + const ast = createTypeScriptAst(fixture); + const routes = discoverHandoverContextInAst(ast).filter( + (route) => route.data.controller === "InheritedController", + ); + const [trace] = analyzeOnboardingRoutes(ast, routes); + expect(trace?.methods.map((method) => method.symbol)).toEqual([ + "InheritedController.run", + ]); + expect(trace?.calls[0]?.kind).toBe("unresolved"); + expect( + trace?.gaps.some((gap) => gap.reason.includes("Inherited or overridden")), + ).toBe(true); + }); + + it("exposes a traversal stop instead of silently omitting deeper methods", () => { + const ast = createTypeScriptAst(fixture); + const routes = discoverHandoverContextInAst(ast).filter( + (route) => route.data.method === "submit", + ); + const [trace] = analyzeOnboardingRoutes(ast, routes, { maxDepth: 0 }); + expect(trace?.methods.map((method) => method.symbol)).toEqual([ + "OrderController.submit", + ]); + expect(trace?.gaps.some((gap) => gap.reason.includes("Depth limit"))).toBe( + true, + ); + const [fileLimited] = analyzeOnboardingRoutes(ast, routes, { maxFiles: 1 }); + expect( + fileLimited?.gaps.some((gap) => gap.reason.includes("Source file limit")), + ).toBe(true); + const [callLimited] = analyzeOnboardingRoutes(ast, routes, { + maxCallsPerMethod: 0, + }); + expect( + callLimited?.gaps.some((gap) => gap.reason.includes("Call count limit")), + ).toBe(true); + const [projectLimited] = analyzeOnboardingRoutes(ast, routes, { + maxProjectFiles: 1, + }); + expect(projectLimited?.methods).toEqual([]); + expect( + projectLimited?.gaps.some((gap) => + gap.reason.includes("source-file budget"), + ), + ).toBe(true); + }); +}); diff --git a/packages/scanners/src/onboarding-trace.ts b/packages/scanners/src/onboarding-trace.ts new file mode 100644 index 0000000..474279a --- /dev/null +++ b/packages/scanners/src/onboarding-trace.ts @@ -0,0 +1,720 @@ +import { relative, sep } from "node:path"; + +import type { + OnboardingTrace, + OnboardingTraceCallEdge, + OnboardingTraceEvent, + OnboardingTraceGap, + OnboardingTraceLocation, + OnboardingTraceMethod, +} from "@transferkit/core"; +import { + Node, + SyntaxKind, + VariableDeclarationKind, + type CallExpression, + type Expression, + type MethodDeclaration, + type Statement, +} from "ts-morph"; + +import type { HandoverContextFinding } from "./handover-context.js"; +import type { TypeScriptAst } from "./typescript-ast.js"; + +export interface OnboardingTraceLimits { + maxEntries: number; + maxProjectFiles: number; + maxMethods: number; + maxDepth: number; + maxCallsPerMethod: number; + maxFiles: number; + maxPaths: number; +} + +const defaultLimits: OnboardingTraceLimits = { + maxEntries: 3, + maxProjectFiles: 5000, + maxMethods: 40, + maxDepth: 3, + maxCallsPerMethod: 30, + maxFiles: 30, + maxPaths: 16, +}; + +type PathState = { path: string[]; aliases: Map<string, "query-runner"> }; + +/** Uses the scan's existing ts-morph Project; it never creates another Program. */ +export function analyzeOnboardingRoutes( + ast: TypeScriptAst, + routes: readonly HandoverContextFinding[], + options: Partial<OnboardingTraceLimits> = {}, +): OnboardingTrace[] { + const limits = { ...defaultLimits, ...options }; + const files = new Map( + ast.sourceFiles.map((file) => [ + relative(ast.repositoryDirectory, file.getFilePath()), + file, + ]), + ); + const traces: OnboardingTrace[] = []; + for (const route of routes.filter( + (item) => item.kind === "application.route", + )) { + if (traces.length >= limits.maxEntries) break; + const file = files.get(route.evidence[0]?.file ?? ""); + const owner = file?.getClass(route.data.controller ?? ""); + const handler = owner?.getMethod(route.data.method ?? ""); + if (!handler?.getBody()) continue; + const entrySymbol = symbolName(handler); + const trace: OnboardingTrace = { + id: [ + route.data.verb, + route.data.path ?? "", + route.evidence[0]?.file, + entrySymbol, + ] + .filter(Boolean) + .join(":"), + entry: { + symbol: entrySymbol, + kind: route.data.entryKind === "scheduled" ? "scheduled" : "route", + ...(route.data.verb ? { verb: route.data.verb } : {}), + ...(route.data.path ? { path: route.data.path } : {}), + ...(route.data.schedule ? { schedule: route.data.schedule } : {}), + declaration: location(ast, handler), + }, + methods: [], + calls: [], + gaps: [], + }; + if (ast.sourceFiles.length > limits.maxProjectFiles) { + addGap( + trace, + ast, + handler, + [], + "Project source-file budget reached before tracing.", + ); + traces.push(trace); + continue; + } + const analyzed = new Set<MethodDeclaration>(); + const visitedFiles = new Set<string>(); + const analyze = (method: MethodDeclaration, depth: number): void => { + if (analyzed.has(method)) return; + if (depth > limits.maxDepth) { + addGap(trace, ast, method, [], "Method depth limit reached."); + return; + } + if (trace.methods.length >= limits.maxMethods) { + addGap(trace, ast, method, [], "Method count limit reached."); + return; + } + const fileName = relative( + ast.repositoryDirectory, + method.getSourceFile().getFilePath(), + ); + if (!isLocalSource(fileName)) { + addGap( + trace, + ast, + method, + [], + "Method body is outside supported source.", + ); + return; + } + if (!visitedFiles.has(fileName) && visitedFiles.size >= limits.maxFiles) { + addGap(trace, ast, method, [], "Source file limit reached."); + return; + } + visitedFiles.add(fileName); + analyzed.add(method); + const body = method.getBody(); + if (!body || !Node.isBlock(body)) { + addGap(trace, ast, method, [], "Method body is unavailable."); + return; + } + const result: OnboardingTraceMethod = { + symbol: symbolName(method), + declaration: location(ast, method), + events: [], + }; + trace.methods.push(result); + let callCount = 0; + const event = ( + kind: OnboardingTraceEvent["kind"], + node: Node, + state: PathState, + detail: string, + extra: Pick<OnboardingTraceEvent, "awaited" | "effect"> = {}, + ): void => { + result.events.push({ + kind, + detail, + at: location(ast, node), + path: [...state.path], + ...extra, + }); + }; + const gap = (node: Node, state: PathState, reason: string): void => { + addGap(trace, ast, node, state.path, reason); + }; + const inspectExpression = (expression: Node, state: PathState): void => { + const shortCircuit = [ + ...(Node.isBinaryExpression(expression) ? [expression] : []), + ...expression.getDescendantsOfKind(SyntaxKind.BinaryExpression), + ].some((binary) => + [ + SyntaxKind.AmpersandAmpersandToken, + SyntaxKind.BarBarToken, + SyntaxKind.QuestionQuestionToken, + ].includes(binary.getOperatorToken().getKind()), + ); + const complex = Boolean( + Node.isConditionalExpression(expression) || + expression.getDescendantsOfKind(SyntaxKind.ConditionalExpression) + .length || + shortCircuit, + ); + const awaitedCall = Node.isAwaitExpression(expression) + ? expression.getFirstChildByKind(SyntaxKind.CallExpression) + : undefined; + const outerCall = Node.isCallExpression(expression) + ? expression + : Node.isCallExpression(awaitedCall) + ? awaitedCall + : undefined; + if (complex) { + gap( + expression, + state, + "Conditional or short-circuit expression detail is unsupported.", + ); + if (!outerCall) return; + } + if ( + Node.isNewExpression(expression) || + expression.getDescendantsOfKind(SyntaxKind.NewExpression).length + ) + gap(expression, state, "Constructor effects are not traced."); + const assignments = complex + ? [] + : [ + ...(Node.isBinaryExpression(expression) ? [expression] : []), + ...expression.getDescendantsOfKind(SyntaxKind.BinaryExpression), + ]; + for (const assignment of assignments) { + if ( + assignment + .getAncestors() + .some( + (ancestor) => + (Node.isArrowFunction(ancestor) || + Node.isFunctionExpression(ancestor)) && + contains(expression, ancestor), + ) + ) { + gap(assignment, state, "Assignment inside callback is not traced."); + continue; + } + if ( + assignment.getOperatorToken().getKind() === + SyntaxKind.EqualsToken && + Node.isPropertyAccessExpression(assignment.getLeft()) + ) + event("assignment", assignment, state, safeText(assignment)); + } + const calls = + complex && outerCall + ? [outerCall] + : [ + ...(Node.isCallExpression(expression) ? [expression] : []), + ...expression.getDescendantsOfKind(SyntaxKind.CallExpression), + ]; + for (const call of calls) { + if (call.getExpression().getText().includes("?.")) { + gap(call, state, "Optional call may not execute."); + continue; + } + if ( + call + .getAncestors() + .some( + (ancestor) => + (Node.isArrowFunction(ancestor) || + Node.isFunctionExpression(ancestor)) && + contains(expression, ancestor), + ) + ) { + gap(call, state, "Call inside callback is not traced."); + continue; + } + if ( + calls.some((parent) => parent !== call && contains(parent, call)) + ) { + const resolution = resolveMethod(call, ast); + const nestedExpression = call.getExpression(); + const directNested = + Node.isPropertyAccessExpression(nestedExpression) && + nestedExpression.getExpression().getText() === "this"; + trace.calls.push({ + caller: result.symbol, + site: location(ast, call), + kind: resolution.target + ? directNested + ? "direct" + : "declared-target" + : "unresolved", + evaluation: "nested-argument", + path: [...state.path], + ...(resolution.target + ? { + declaredTarget: symbolName(resolution.target), + declaration: location(ast, resolution.target), + } + : {}), + }); + if (resolution.target && depth < limits.maxDepth) + analyze(resolution.target, depth + 1); + gap( + call, + state, + resolution.target + ? "Nested call target is known; argument evaluation order is not represented as a separate step." + : "Nested call target and evaluation order are unresolved.", + ); + continue; + } + if (callCount >= limits.maxCallsPerMethod) { + gap(call, state, "Call count limit reached for this method."); + break; + } + callCount++; + const expressionNode = call.getExpression(); + const name = safeText(expressionNode); + const effect = classifyEffect(call, method, state); + event("call", call, state, name, { + awaited: directlyAwaited(call), + ...(effect ? { effect } : {}), + }); + const resolution = resolveMethod(call, ast); + const direct = + Node.isPropertyAccessExpression(expressionNode) && + expressionNode.getExpression().getText() === "this"; + const edge: OnboardingTraceCallEdge = { + caller: result.symbol, + site: location(ast, call), + kind: resolution.target + ? direct + ? "direct" + : "declared-target" + : "unresolved", + path: [...state.path], + ...(resolution.target + ? { + declaredTarget: symbolName(resolution.target), + declaration: location(ast, resolution.target), + } + : {}), + }; + trace.calls.push(edge); + if (resolution.target) { + if (depth < limits.maxDepth) analyze(resolution.target, depth + 1); + else + gap( + call, + state, + `Depth limit before ${symbolName(resolution.target)}.`, + ); + } else + gap(call, state, resolution.reason ?? "Call target is unresolved."); + } + }; + const walkStatements = ( + statements: readonly Statement[], + initial: PathState[], + ): PathState[] => { + let states = initial; + for (const statement of statements) { + states = states.flatMap((state) => walkStatement(statement, state)); + if (states.length > limits.maxPaths) { + gap( + statement, + initial[0] ?? { path: [], aliases: new Map() }, + "Path count limit reached.", + ); + states = states.slice(0, limits.maxPaths); + } + if (!states.length) break; + } + return states; + }; + const walkStatement = ( + statement: Statement, + state: PathState, + ): PathState[] => { + if (Node.isBlock(statement)) + return walkStatements(statement.getStatements(), [state]); + if (Node.isIfStatement(statement)) { + const condition = safeText(statement.getExpression()); + event("branch", statement, state, condition); + if ( + statement + .getExpression() + .getDescendantsOfKind(SyntaxKind.CallExpression).length + ) + gap( + statement.getExpression(), + state, + "Calls in branch condition are not traced.", + ); + const yes = fork( + state, + `when ${condition} at ${statement.getStartLineNumber()}`, + ); + const no = fork( + state, + `otherwise ${condition} at ${statement.getStartLineNumber()}`, + ); + const yesStates = walkStatement(statement.getThenStatement(), yes); + const noStates = statement.getElseStatement() + ? walkStatement(statement.getElseStatement()!, no) + : [no]; + if ( + yesStates.length === 1 && + noStates.length === 1 && + sameAliases(yesStates[0]!, noStates[0]!) + ) + return [state]; + return [...yesStates, ...noStates]; + } + if ( + Node.isReturnStatement(statement) || + Node.isThrowStatement(statement) + ) { + const expression = statement.getExpression(); + if (expression) inspectExpression(expression, state); + event( + Node.isReturnStatement(statement) ? "return" : "throw", + statement, + state, + safeText(statement), + ); + return []; + } + if (Node.isTryStatement(statement)) { + const normal = walkStatement( + statement.getTryBlock(), + fork(state, "try"), + ); + const caught = statement.getCatchClause() + ? walkStatement( + statement.getCatchClause()!.getBlock(), + fork(state, "catch"), + ) + : []; + const survivors = [...normal, ...caught]; + const finallyBlock = statement.getFinallyBlock(); + if (!finallyBlock) return survivors; + if (!normal.length) + walkStatement( + finallyBlock, + fork(fork(state, "try"), "finally after exit"), + ); + if (statement.getCatchClause() && !caught.length) + walkStatement( + finallyBlock, + fork(fork(state, "catch"), "finally after exit"), + ); + if (!survivors.length) { + return []; + } + return dedupeStates( + survivors.flatMap((path) => + walkStatement(finallyBlock, fork(path, "finally")).map( + (after) => ({ + path: [...state.path], + aliases: after.aliases, + }), + ), + ), + ); + } + if ( + Node.isForStatement(statement) || + Node.isForOfStatement(statement) || + Node.isForInStatement(statement) || + Node.isWhileStatement(statement) || + Node.isDoStatement(statement) || + Node.isSwitchStatement(statement) + ) { + gap( + statement, + state, + `Unsupported control flow: ${statement.getKindName()}.`, + ); + return [state]; + } + if (Node.isVariableStatement(statement)) { + for (const declaration of statement.getDeclarations()) { + const initializer = declaration.getInitializer(); + if (!initializer) continue; + inspectExpression(initializer, state); + if ( + statement.getDeclarationKind() === + VariableDeclarationKind.Const && + isQueryRunnerFactory(initializer, method) + ) + state.aliases.set(declaration.getName(), "query-runner"); + } + return [state]; + } + if (Node.isExpressionStatement(statement)) { + inspectExpression(statement.getExpression(), state); + return [state]; + } + gap( + statement, + state, + `Unsupported statement: ${statement.getKindName()}.`, + ); + return [state]; + }; + walkStatements(body.getStatements(), [{ path: [], aliases: new Map() }]); + }; + analyze(handler, 0); + traces.push(trace); + } + return traces; +} + +function resolveMethod( + call: CallExpression, + ast: TypeScriptAst, +): { target?: MethodDeclaration; reason?: string } { + const expression = call.getExpression(); + if (Node.isElementAccessExpression(expression)) + return { reason: "Dynamic dispatch is unresolved." }; + if (!Node.isPropertyAccessExpression(expression)) + return { reason: "Indirect or free-function call is unresolved." }; + const declarations = expression.getSymbol()?.getDeclarations() ?? []; + const methods = declarations.filter(Node.isMethodDeclaration); + if (declarations.length !== 1 || methods.length !== 1) + return { + reason: + declarations.length > 1 + ? "Ambiguous declared target." + : "Method target is unavailable.", + }; + const target = methods[0]!; + const declaredOwner = target.getParentIfKind(SyntaxKind.ClassDeclaration); + const receiverOwner = expression + .getExpression() + .getType() + .getSymbol() + ?.getDeclarations() + .find(Node.isClassDeclaration); + if ( + declaredOwner && + receiverOwner && + (declaredOwner.getSourceFile().getFilePath() !== + receiverOwner.getSourceFile().getFilePath() || + declaredOwner.getStart() !== receiverOwner.getStart()) + ) + return { reason: "Inherited or overridden target is ambiguous." }; + const path = relative( + ast.repositoryDirectory, + target.getSourceFile().getFilePath(), + ); + if (!target.getBody() || !isLocalSource(path)) + return { reason: "Declared method has no supported local body." }; + return { target }; +} + +function classifyEffect( + call: CallExpression, + method: MethodDeclaration, + state: PathState, +): OnboardingTraceEvent["effect"] | undefined { + const expression = call.getExpression(); + if (!Node.isPropertyAccessExpression(expression)) return undefined; + const receiver = expression.getExpression(); + const name = expression.getName(); + if (Node.isPropertyAccessExpression(receiver)) { + const root = receiver.getExpression(); + if ( + Node.isIdentifier(root) && + state.aliases.get(root.getText()) === "query-runner" + ) { + if (receiver.getName() === "manager" && name === "save") + return "write-like"; + } + if (receiver.getExpression().getText() === "this") { + const owner = method.getParentIfKind(SyntaxKind.ClassDeclaration); + const parameter = owner + ?.getConstructors() + .flatMap((ctor) => ctor.getParameters()) + .find((item) => item.getName() === receiver.getName()); + const typeName = parameter?.getTypeNode()?.getText() ?? ""; + if (/Repository$/u.test(typeName)) { + if (/^(?:get|find)/u.test(name)) return "read-like"; + if (name === "save") return "write-like"; + } + } + } + if ( + Node.isIdentifier(receiver) && + state.aliases.get(receiver.getText()) === "query-runner" + ) { + if ( + /^(?:commitTransaction|rollbackTransaction|release|startTransaction|connect)$/u.test( + name, + ) + ) + return "transaction-like"; + } + return undefined; +} + +function isQueryRunnerFactory( + initializer: Expression, + method: MethodDeclaration, +): boolean { + if (!Node.isCallExpression(initializer)) return false; + const expression = initializer.getExpression(); + if ( + !Node.isPropertyAccessExpression(expression) || + expression.getName() !== "createQueryRunner" + ) + return false; + const receiver = expression.getExpression(); + if ( + !Node.isPropertyAccessExpression(receiver) || + receiver.getExpression().getText() !== "this" + ) + return false; + return Boolean( + method + .getParentIfKind(SyntaxKind.ClassDeclaration) + ?.getConstructors() + .flatMap((ctor) => ctor.getParameters()) + .some((parameter) => parameter.getName() === receiver.getName()), + ); +} + +function directlyAwaited(call: CallExpression): boolean { + let node: Node = call; + while (true) { + const parent = node.getParent(); + if ( + Node.isParenthesizedExpression(parent) || + Node.isAsExpression(parent) || + Node.isNonNullExpression(parent) + ) { + node = parent; + continue; + } + return Node.isAwaitExpression(parent); + } +} + +function fork(state: PathState, condition: string): PathState { + return { path: [...state.path, condition], aliases: new Map(state.aliases) }; +} + +function sameAliases(left: PathState, right: PathState): boolean { + return ( + left.aliases.size === right.aliases.size && + [...left.aliases].every( + ([name, origin]) => right.aliases.get(name) === origin, + ) + ); +} + +function dedupeStates(states: PathState[]): PathState[] { + return states.filter( + (candidate, index) => + states.findIndex( + (state) => + state.path.join("\u0000") === candidate.path.join("\u0000") && + sameAliases(state, candidate), + ) === index, + ); +} + +function location(ast: TypeScriptAst, node: Node): OnboardingTraceLocation { + return { + file: relative(ast.repositoryDirectory, node.getSourceFile().getFilePath()), + line: node.getStartLineNumber(), + endLine: node.getEndLineNumber(), + origin: "code", + }; +} + +function addGap( + trace: OnboardingTrace, + ast: TypeScriptAst, + node: Node, + path: readonly string[], + reason: string, +): void { + const gap: OnboardingTraceGap = { + reason, + at: location(ast, node), + path: [...path], + }; + trace.gaps.push(gap); +} + +function symbolName(method: MethodDeclaration): string { + return `${method.getParentIfKind(SyntaxKind.ClassDeclaration)?.getName() ?? "<unknown>"}.${method.getName()}`; +} + +function isLocalSource(path: string): boolean { + return ( + path !== ".." && + !path.startsWith(`..${sep}`) && + !/(?:^|\/)(?:node_modules|dist|generated)(?:\/|$)/u.test(path) && + !path.endsWith(".d.ts") + ); +} + +function contains(parent: Node, child: Node): boolean { + return ( + parent.getStart() <= child.getStart() && parent.getEnd() >= child.getEnd() + ); +} + +function compact(value: string): string { + return value.replace(/\s+/gu, " ").slice(0, 180); +} + +function safeText(node: Node): string { + const literals = new Set<SyntaxKind>([ + SyntaxKind.StringLiteral, + SyntaxKind.NoSubstitutionTemplateLiteral, + SyntaxKind.TemplateExpression, + SyntaxKind.NumericLiteral, + SyntaxKind.BigIntLiteral, + SyntaxKind.RegularExpressionLiteral, + ]); + const start = node.getStart(); + const spans = [node, ...node.getDescendants()] + .filter((item) => literals.has(item.getKind())) + .map((item) => ({ + start: item.getStart() - start, + end: item.getEnd() - start, + })) + .sort((left, right) => left.start - right.start || right.end - left.end) + .filter( + (item, index, all) => + !all + .slice(0, index) + .some((prior) => prior.start <= item.start && prior.end >= item.end), + ); + let value = node.getText(); + for (const span of spans.reverse()) + value = `${value.slice(0, span.start)}[literal]${value.slice(span.end)}`; + return compact(value); +} diff --git a/packages/scanners/src/realistic-fixture.test.ts b/packages/scanners/src/realistic-fixture.test.ts index da53f13..aac1a89 100644 --- a/packages/scanners/src/realistic-fixture.test.ts +++ b/packages/scanners/src/realistic-fixture.test.ts @@ -37,6 +37,7 @@ describe("realistic NestJS repository scan", () => { "environment.template", "containerization", "setup.service", + "setup.variable", "ci.workflow", ]), ); diff --git a/packages/scanners/src/repository-files.ts b/packages/scanners/src/repository-files.ts index c51f0b3..88b6645 100644 --- a/packages/scanners/src/repository-files.ts +++ b/packages/scanners/src/repository-files.ts @@ -14,6 +14,7 @@ export type RepositoryFileFinding = Finding< | "setup.service" | "setup.port" | "setup.requirement" + | "setup.variable" >; export async function discoverRepositoryFiles( @@ -35,6 +36,22 @@ export async function discoverRepositoryFiles( }, ], }); + const template = await optionalText(join(repositoryDirectory, name)); + template?.split(/\r?\n/u).forEach((line, index) => { + const variable = /^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=/u.exec( + line, + )?.[1]; + if (variable) + findings.push( + setupFinding( + "setup.variable", + `${name}:${variable}`, + { name: variable }, + name, + index + 1, + ), + ); + }); } if ( name === "Dockerfile" || @@ -142,6 +159,9 @@ async function discoverSetupFiles( "start:prod", "test", "test:e2e", + ...Object.keys(scripts) + .filter((name) => /(?:migrat|seed)/iu.test(name)) + .slice(0, 8), ]) { if (typeof (scripts as Record<string, unknown>)[name] === "string") findings.push( @@ -153,11 +173,15 @@ async function discoverSetupFiles( purpose: name === "build" ? "build" - : name.startsWith("test") - ? "test" - : name === "start:prod" - ? "compiled-start" - : "start", + : /migrat/iu.test(name) + ? "migration" + : /seed/iu.test(name) + ? "seed" + : name.startsWith("test") + ? "test" + : name === "start:prod" + ? "compiled-start" + : "start", }, "package.json", propertyLine(pkg, name), @@ -171,6 +195,10 @@ async function discoverSetupFiles( } const readme = await optionalText(join(directory, "README.md")); if (readme) { + const genericReadme = + /(?:nest(?:js)? (?:framework|starter)|starter repository|boilerplate)/iu.test( + readme.slice(0, 1200), + ); let section = ""; let fenced = false; readme.split(/\r?\n/u).forEach((line, index) => { @@ -203,7 +231,7 @@ async function discoverSetupFiles( setupFinding( "setup.command", `readme:${index + 1}`, - { command, purpose }, + { command, purpose, ...(genericReadme ? { generic: "yes" } : {}) }, "README.md", index + 1, ), diff --git a/packages/standards/src/index.ts b/packages/standards/src/index.ts index c710dad..89c0275 100644 --- a/packages/standards/src/index.ts +++ b/packages/standards/src/index.ts @@ -27,4 +27,16 @@ export type { SemanticIntegration } from "./semantic-integrations.js"; export { suggestTransferPlan, transferSectionTitles } from "./transfer-plan.js"; export { understandProject } from "./project-understanding.js"; export { explainCandidateFlows } from "./explained-flow.js"; +export { selectOnboardingConcepts } from "./onboarding-concepts.js"; +export { selectOnboardingStoryInventory } from "./onboarding-story.js"; +export { selectOnboardingStories } from "./onboarding-story-selection.js"; +export { selectOnboardingContinuations } from "./onboarding-continuations.js"; +export { selectScheduledConcepts } from "./onboarding-scheduled.js"; +export { + preselectOnboardingEntries, + selectOnboardingJourneys, + type OnboardingEntryCandidate, + type OnboardingJourneyDecision, + type OnboardingJourneySelection, +} from "./onboarding-journey-selection.js"; export { personalOnboardingExercises } from "./personal-onboarding.js"; diff --git a/packages/standards/src/onboarding-concepts.test.ts b/packages/standards/src/onboarding-concepts.test.ts new file mode 100644 index 0000000..c318806 --- /dev/null +++ b/packages/standards/src/onboarding-concepts.test.ts @@ -0,0 +1,94 @@ +import { expect, it } from "vitest"; +import type { + OnboardingConceptEvidence, + OnboardingTrace, + OnboardingTraceLocation, +} from "@transferkit/core"; + +import { selectOnboardingConcepts } from "./onboarding-concepts.js"; + +const at: OnboardingTraceLocation = { + file: "service.ts", + line: 10, + endLine: 10, + origin: "code", +}; + +it("uses a custom repository method's declared result instead of its base entity", () => { + const evidence: OnboardingConceptEvidence = { + entities: ["Debt", "DebtGroup"].map((name) => ({ + name, + declaration: at, + fields: [], + relations: [], + })), + repositories: [{ repository: "DebtRepository", entity: "Debt", at }], + methodResults: [ + { + repository: "DebtRepository", + method: "findOrCreateGroup", + entity: "DebtGroup", + at, + }, + ], + injections: [ + { + owner: "DebtService", + property: "debtRepository", + repository: "DebtRepository", + at, + }, + ], + }; + const trace: OnboardingTrace = { + id: "debt", + entry: { symbol: "DebtService.create", declaration: at }, + methods: [ + { + symbol: "DebtService.create", + declaration: at, + events: [ + { + kind: "call", + detail: "this.debtRepository.findOrCreateGroup", + at, + path: [], + effect: "read-like", + }, + { + kind: "call", + detail: "this.debtRepository.save", + at: { ...at, line: 11 }, + path: [], + effect: "write-like", + }, + ], + }, + ], + calls: [ + { + caller: "DebtService.create", + site: at, + kind: "declared-target", + declaredTarget: "DebtRepository.findOrCreateGroup", + path: [], + }, + { + caller: "DebtService.create", + site: { ...at, line: 11 }, + kind: "unresolved", + path: [], + }, + ], + gaps: [], + }; + expect( + selectOnboardingConcepts(trace, evidence).map((item) => [ + item.entity.name, + item.calls[0]?.effect, + ]), + ).toEqual([ + ["Debt", "write-like"], + ["DebtGroup", "unspecified"], + ]); +}); diff --git a/packages/standards/src/onboarding-concepts.ts b/packages/standards/src/onboarding-concepts.ts new file mode 100644 index 0000000..2314050 --- /dev/null +++ b/packages/standards/src/onboarding-concepts.ts @@ -0,0 +1,92 @@ +import type { + OnboardingConceptEvidence, + OnboardingSelectedConcept, + OnboardingTrace, +} from "@transferkit/core"; + +export function selectOnboardingConcepts( + trace: OnboardingTrace | undefined, + evidence: OnboardingConceptEvidence, +): OnboardingSelectedConcept[] { + if (!trace) return []; + const bindings = new Map( + evidence.repositories.map((item) => [item.repository, item.entity]), + ); + const methodResults = new Map( + evidence.methodResults.map((item) => [ + `${item.repository}.${item.method}`, + item.entity, + ]), + ); + const injections = new Map( + evidence.injections.map((item) => [ + `${item.owner}.${item.property}`, + item.repository, + ]), + ); + const selected = new Map<string, OnboardingSelectedConcept>(); + const entities = new Map(evidence.entities.map((item) => [item.name, item])); + for (const method of trace.methods) + for (const event of method.events) { + if (event.kind !== "call") continue; + const edge = trace.calls.find( + (item) => + item.caller === method.symbol && + item.site.file === event.at.file && + item.site.line === event.at.line, + ); + const declaredRepository = edge?.declaredTarget?.split(".")[0]; + const receiver = event.detail.match(/^this\.([A-Za-z_$][\w$]*)\./u)?.[1]; + const owner = method.symbol.split(".")[0]; + const injectedRepository = receiver + ? injections.get(`${owner}.${receiver}`) + : undefined; + const repository = declaredRepository ?? injectedRepository; + const methodName = event.detail.split(".").at(-1); + const explicitResult = + repository && methodName + ? methodResults.get(`${repository}.${methodName}`) + : undefined; + const inheritedEffect = + methodName && + /^(?:save|insert|update|remove|delete|find|findOne|findBy|count)$/u.test( + methodName, + ); + const entityName = + explicitResult ?? + (inheritedEffect ? bindings.get(repository ?? "") : undefined); + const entity = entityName ? entities.get(entityName) : undefined; + if (!entity) continue; + const concept = selected.get(entity.name) ?? { entity, calls: [] }; + concept.calls.push({ + effect: explicitResult + ? "unspecified" + : event.effect === "transaction-like" + ? "unspecified" + : (event.effect ?? "unspecified"), + at: event.at, + }); + selected.set(entity.name, concept); + } + const touched = [...selected.values()].sort( + (left, right) => + conceptScore(right) - conceptScore(left) || + left.entity.name.localeCompare(right.entity.name), + ); + if (touched.length === 1) { + const related = touched[0]?.entity.relations + .map((relation) => entities.get(relation.target)) + .find((entity) => entity && entity.name !== touched[0]?.entity.name); + if (related) touched.push({ entity: related, calls: [] }); + } + return touched; +} + +function conceptScore(concept: OnboardingSelectedConcept): number { + return concept.calls.reduce( + (score, call) => + score + + (call.effect === "write-like" ? 4 : call.effect === "read-like" ? 2 : 1), + 0, + ); +} diff --git a/packages/standards/src/onboarding-continuations.ts b/packages/standards/src/onboarding-continuations.ts new file mode 100644 index 0000000..d58bd09 --- /dev/null +++ b/packages/standards/src/onboarding-continuations.ts @@ -0,0 +1,39 @@ +import type { + OnboardingQueueContinuation, + OnboardingQueueEvidence, + OnboardingTrace, +} from "@transferkit/core"; + +export function selectOnboardingContinuations( + trace: OnboardingTrace | undefined, + queues: OnboardingQueueEvidence, +): OnboardingQueueContinuation[] { + if (!trace) return []; + return queues.publications.flatMap((publication) => { + const event = trace.methods + .find((method) => method.symbol === publication.caller) + ?.events.find( + (item) => + item.kind === "call" && + item.at.file === publication.at.file && + item.at.line === publication.at.line, + ); + if (!event) return []; + const matches = queues.handlers.filter( + (handler) => handler.queue === publication.queue, + ); + return [ + { + publication: { ...publication, path: event.path }, + ...(matches.length === 1 + ? { handler: matches[0]! } + : { + reason: + matches.length === 0 + ? "No matching WorkerHost registration was found." + : "Multiple WorkerHost registrations make the target ambiguous.", + }), + }, + ]; + }); +} diff --git a/packages/standards/src/onboarding-journey-selection.ts b/packages/standards/src/onboarding-journey-selection.ts new file mode 100644 index 0000000..6456166 --- /dev/null +++ b/packages/standards/src/onboarding-journey-selection.ts @@ -0,0 +1,318 @@ +import type { + Finding, + OnboardingConceptEvidence, + OnboardingQueueEvidence, + OnboardingScheduledCall, + OnboardingStoryInventory, + OnboardingTrace, + RouteTrace, +} from "@transferkit/core"; + +import { selectOnboardingConcepts } from "./onboarding-concepts.js"; +import { selectOnboardingContinuations } from "./onboarding-continuations.js"; + +export interface OnboardingEntryCandidate { + symbol: string; + kind: "route" | "scheduled"; + routeFindingId?: string; + verb?: string; + path?: string; + preliminaryScore: number; +} + +export interface OnboardingJourneyDecision { + trace: OnboardingTrace; + score: number; + reason: string; +} + +export interface OnboardingJourneySelection { + selected: OnboardingJourneyDecision[]; + rejected: OnboardingJourneyDecision[]; +} + +export function preselectOnboardingEntries( + findings: readonly Finding[], + queues: OnboardingQueueEvidence, + scheduledCalls: readonly OnboardingScheduledCall[], + focus?: string, + inventory?: OnboardingStoryInventory, +): { + entries: string[]; + candidates: OnboardingEntryCandidate[]; + focusSymbol?: string; +} { + const legacy = new Map( + findings + .filter((item) => item.kind === "application.route-trace") + .map((item) => { + const data = item.data as RouteTrace; + return [data.routeFindingId, data] as const; + }), + ); + const publisherMethods = new Set( + queues.publications.map((item) => item.caller), + ); + const routes: OnboardingEntryCandidate[] = findings + .filter((item) => item.kind === "application.route") + .flatMap((item) => { + const data = item.data as Record<string, unknown>; + if ( + typeof data.controller !== "string" || + typeof data.method !== "string" + ) + return []; + const trace = legacy.get(item.id); + const operations = trace?.operations ?? []; + const branches = operations.filter( + (operation) => + operation.kind === "branch" || operation.kind === "guard", + ).length; + const saves = operations.filter( + (operation) => operation.kind === "call" && operation.method === "save", + ).length; + return [ + { + symbol: `${data.controller}.${data.method}`, + kind: "route" as const, + routeFindingId: item.id, + ...(typeof data.verb === "string" ? { verb: data.verb } : {}), + ...(typeof data.path === "string" ? { path: data.path } : {}), + preliminaryScore: + Math.min(operations.length, 25) + + Math.min(branches, 12) * 2 + + Math.min(saves, 5) * 4 + + (trace && publisherMethods.has(trace.serviceMethod) ? 40 : 0) + + (typeof data.path === "string" ? 2 : 0), + }, + ]; + }); + const directCalls = new Map<string, number>(); + for (const call of scheduledCalls) + directCalls.set(call.job, (directCalls.get(call.job) ?? 0) + 1); + const jobs: OnboardingEntryCandidate[] = findings + .filter((item) => item.kind === "scheduled-job") + .flatMap((item) => { + const data = item.data as Record<string, unknown>; + return typeof data.name === "string" + ? [ + { + symbol: data.name, + kind: "scheduled" as const, + preliminaryScore: + Math.min(directCalls.get(data.name) ?? 0, 10) * 3, + }, + ] + : []; + }); + const candidates = [...routes, ...jobs]; + const matchingFocus = focus + ? candidates.filter( + (candidate) => + candidate.symbol === focus || + `${candidate.verb ?? ""} ${candidate.path ?? ""}`.trim() === focus || + candidate.path === focus, + ) + : []; + if (focus && matchingFocus.length !== 1) + throw new Error( + matchingFocus.length + ? `Focus ${focus} matches multiple entries; use an exact Class.method symbol.` + : `Focus ${focus} did not match a declared route or scheduled handler. Use an exact Class.method symbol or route path.`, + ); + const rankedRoutes = [...routes].sort( + (left, right) => + right.preliminaryScore - left.preliminaryScore || + left.symbol.localeCompare(right.symbol), + ); + const rankedJobs = [...jobs] + .filter((item) => item.preliminaryScore > 0) + .sort( + (left, right) => + right.preliminaryScore - left.preliminaryScore || + left.symbol.localeCompare(right.symbol), + ); + const central = inventory?.terms[0]?.name.toLowerCase(); + const centralStarts = central + ? routes + .filter((item) => { + const method = item.symbol.split(".").at(-1) ?? ""; + return ( + item.verb === "POST" && + (item.symbol.toLowerCase().includes(central) || + item.path?.toLowerCase().includes(central)) && + /^(?:add|create|register|submit|open|start)/iu.test(method) + ); + }) + .sort( + (left, right) => + Number(/(?:create|new)/iu.test(right.path ?? "")) - + Number(/(?:create|new)/iu.test(left.path ?? "")) || + right.preliminaryScore - left.preliminaryScore || + left.symbol.localeCompare(right.symbol), + ) + .slice(0, 2) + : []; + const entries = [ + ...new Set([ + ...(matchingFocus[0] ? [matchingFocus[0].symbol] : []), + ...rankedRoutes.slice(0, 16).map((item) => item.symbol), + ...centralStarts.map((item) => item.symbol), + ...rankedRoutes + .filter((item) => { + const linked = legacy.get(item.routeFindingId ?? ""); + return linked && publisherMethods.has(linked.serviceMethod); + }) + .slice(0, 3) + .map((item) => item.symbol), + ...rankedJobs.slice(0, 2).map((item) => item.symbol), + ]), + ]; + return { + entries, + candidates, + ...(matchingFocus[0] ? { focusSymbol: matchingFocus[0].symbol } : {}), + }; +} + +export function selectOnboardingJourneys( + traces: readonly OnboardingTrace[], + concepts: OnboardingConceptEvidence, + queues: OnboardingQueueEvidence, + focusSymbol?: string, +): OnboardingJourneySelection { + const profiles = traces.map((trace) => { + const events = trace.methods.flatMap((method) => method.events); + const branches = events.filter((event) => event.kind === "branch").length; + const writes = events.filter( + (event) => event.effect === "write-like", + ).length; + const reads = events.filter((event) => event.effect === "read-like").length; + const transaction = events.some( + (event) => event.effect === "transaction-like", + ); + const continuations = selectOnboardingContinuations(trace, queues); + const connected = continuations.filter((item) => item.handler).length; + const touched = selectOnboardingConcepts(trace, concepts) + .filter((item) => item.calls.length) + .map((item) => item.entity.name); + const methods = new Set(trace.methods.map((method) => method.symbol)); + const meaningful = + trace.methods.length > 1 || branches + writes + reads + connected > 0; + const quality = meaningful + ? Math.min(trace.methods.length, 10) * 2 + + Math.min(branches, 12) * 2 + + Math.min(writes, 6) * 4 + + Math.min(reads, 5) * 2 + + (transaction ? 12 : 0) + + connected * 18 + : 0; + return { + trace, + branches, + writes, + reads, + transaction, + connected, + touched, + methods, + quality, + meaningful, + }; + }); + const eligible = profiles.filter((item) => item.meaningful); + const selected: typeof profiles = []; + const remaining = [...eligible]; + const count = Math.min( + eligible.length, + eligible.length > 3 ? 4 : eligible.length, + ); + const seenEntities = new Set<string>(); + const seenOwners = new Set<string>(); + const seenVerbs = new Set<string>(); + let hasQueue = false; + let hasJob = false; + while (selected.length < count && remaining.length) { + const distinct = remaining.filter( + (item) => + !selected.some((prior) => { + const shared = [...item.methods].filter((method) => + prior.methods.has(method), + ).length; + const overlap = + shared / + Math.max(1, Math.min(item.methods.size, prior.methods.size)); + return ( + overlap > 0.6 && + item.touched.every((entity) => prior.touched.includes(entity)) && + item.connected <= prior.connected && + item.trace.entry.kind === prior.trace.entry.kind + ); + }), + ); + if (!distinct.length) break; + distinct.sort((left, right) => { + const score = (item: typeof left): number => { + const owner = item.trace.entry.symbol.split(".")[0]!; + const newEntities = item.touched.filter( + (entity) => !seenEntities.has(entity), + ).length; + const methodOverlap = selected.reduce((greatest, prior) => { + const shared = [...item.methods].filter((method) => + prior.methods.has(method), + ).length; + return Math.max( + greatest, + shared / + Math.max(1, Math.min(item.methods.size, prior.methods.size)), + ); + }, 0); + return ( + item.quality + + Math.min(newEntities, 3) * 6 + + (seenOwners.has(owner) ? 0 : 10) + + (item.trace.entry.verb && !seenVerbs.has(item.trace.entry.verb) + ? 3 + : 0) + + (item.connected && !hasQueue ? 16 : 0) + + (item.trace.entry.kind === "scheduled" && !hasJob ? 16 : 0) - + (methodOverlap > 0.6 ? 30 : 0) + ); + }; + return ( + score(right) - score(left) || + left.trace.entry.symbol.localeCompare(right.trace.entry.symbol) + ); + }); + const next = + selected.length === 0 && focusSymbol + ? (distinct.find((item) => item.trace.entry.symbol === focusSymbol) ?? + distinct[0]!) + : distinct[0]!; + remaining.splice(remaining.indexOf(next), 1); + selected.push(next); + next.touched.forEach((entity) => seenEntities.add(entity)); + seenOwners.add(next.trace.entry.symbol.split(".")[0]!); + if (next.trace.entry.verb) seenVerbs.add(next.trace.entry.verb); + hasQueue ||= next.connected > 0; + hasJob ||= next.trace.entry.kind === "scheduled"; + } + const decision = ( + item: (typeof profiles)[number], + selected: boolean, + ): OnboardingJourneyDecision => ({ + trace: item.trace, + score: item.quality, + reason: selected + ? `source depth ${item.trace.methods.length} method(s), ${item.branches} check(s), ${item.writes} write-like call(s), ${item.touched.length} linked entity type(s)${item.connected ? `, ${item.connected} possible queue continuation(s)` : ""}${item.trace.entry.kind === "scheduled" ? ", scheduled entry" : ""}` + : item.meaningful + ? "Eligible source path; less novel coverage within the current guide limit." + : "No supported decisions, effects, or continuation beyond the entry.", + }); + return { + selected: selected.map((item) => decision(item, true)), + rejected: profiles + .filter((item) => !selected.includes(item)) + .map((item) => decision(item, false)), + }; +} diff --git a/packages/standards/src/onboarding-scheduled.ts b/packages/standards/src/onboarding-scheduled.ts new file mode 100644 index 0000000..a798652 --- /dev/null +++ b/packages/standards/src/onboarding-scheduled.ts @@ -0,0 +1,57 @@ +import type { + OnboardingConceptEvidence, + OnboardingScheduledCall, + OnboardingScheduledConcept, + OnboardingSelectedConcept, + OnboardingTrace, +} from "@transferkit/core"; + +import { selectOnboardingConcepts } from "./onboarding-concepts.js"; + +export function selectScheduledConcepts( + calls: readonly OnboardingScheduledCall[], + evidence: OnboardingConceptEvidence, + featured: readonly OnboardingSelectedConcept[], +): OnboardingScheduledConcept[] { + const featuredNames = new Set(featured.map((item) => item.entity.name)); + if (!featuredNames.size) return []; + const byJob = new Map<string, OnboardingScheduledCall[]>(); + for (const call of calls) + byJob.set(call.job, [...(byJob.get(call.job) ?? []), call]); + const results: OnboardingScheduledConcept[] = []; + for (const [job, directCalls] of byJob) { + const first = directCalls[0]!; + const trace: OnboardingTrace = { + id: `scheduled:${job}`, + entry: { symbol: job, declaration: first.registration }, + methods: [ + { + symbol: job, + declaration: first.registration, + events: directCalls.map((call) => ({ + kind: "call", + detail: call.detail, + at: call.at, + path: [], + ...(call.effect ? { effect: call.effect } : {}), + })), + }, + ], + calls: [], + gaps: [], + }; + for (const concept of selectOnboardingConcepts(trace, evidence)) { + if (!featuredNames.has(concept.entity.name)) continue; + for (const call of concept.calls) + results.push({ + job, + ...(first.schedule ? { schedule: first.schedule } : {}), + registration: first.registration, + entity: concept.entity.name, + effect: call.effect, + at: call.at, + }); + } + } + return results.slice(0, 5); +} diff --git a/packages/standards/src/onboarding-story-selection.test.ts b/packages/standards/src/onboarding-story-selection.test.ts new file mode 100644 index 0000000..17bd325 --- /dev/null +++ b/packages/standards/src/onboarding-story-selection.test.ts @@ -0,0 +1,253 @@ +import { expect, it } from "vitest"; + +import type { + OnboardingConceptEvidence, + OnboardingQueueEvidence, + OnboardingStoryInventory, + OnboardingTrace, +} from "@transferkit/core"; + +import { selectOnboardingStories } from "./onboarding-story-selection.js"; + +const location = (line: number) => ({ + file: "src/shipments.ts", + line, + endLine: line, + origin: "code" as const, +}); +const concepts: OnboardingConceptEvidence = { + entities: [], + repositories: [], + methodResults: [], + injections: [], +}; +const queues: OnboardingQueueEvidence = { publications: [], handlers: [] }; +const inventory: OnboardingStoryInventory = { + roles: [], + entries: [], + artifacts: [], + outputs: [], + boundaries: [], + observations: [], + terms: [ + { + name: "Shipment", + codeRole: "declared data entity", + evidence: [{ file: "src/shipment.entity.ts", line: 1 }], + relationCount: 2, + relations: [], + }, + ], + rejectedDescriptions: [], + unknowns: [], +}; + +function trace(symbol: string, line: number, detail: string): OnboardingTrace { + return { + id: symbol, + entry: { + symbol, + kind: "route", + verb: "POST", + declaration: location(line), + }, + methods: [ + { + symbol, + declaration: location(line), + events: [ + { + kind: "branch", + detail, + at: location(line + 1), + path: [], + }, + ], + }, + ], + calls: [], + gaps: [], + }; +} + +it("selects creation and assignment as distinct entries without inventing a sequence", () => { + const creation = trace( + "ShipmentController.createShipment", + 10, + "if duplicate", + ); + creation.gaps.push({ + reason: "Nested Promise body is not traced.", + at: location(12), + path: [], + }); + const assignment = trace( + "FleetController.assignShipment", + 30, + "if unavailable", + ); + const result = selectOnboardingStories( + [assignment, creation], + inventory, + concepts, + queues, + ); + expect(result.chapters.map((item) => item.id)).toEqual([ + "ShipmentController.createShipment", + "FleetController.assignShipment", + ]); + expect(result.chapters[0]?.firstUnsupportedBoundary?.reason).toContain( + "Nested Promise", + ); + expect(result.connections).toContainEqual( + expect.objectContaining({ kind: "unproven-association" }), + ); + expect(result.connections.some((item) => item.kind === "direct-call")).toBe( + false, + ); +}); + +it("preserves an explicit focus and labels a matched queue as possible only", () => { + const creation = trace( + "ShipmentController.createShipment", + 10, + "if duplicate", + ); + creation.methods[0]!.events.push({ + kind: "call", + detail: "queue.add", + at: location(15), + path: [], + }); + const assignment = trace( + "FleetController.assignShipment", + 30, + "if unavailable", + ); + const result = selectOnboardingStories( + [creation, assignment], + inventory, + concepts, + { + publications: [ + { + caller: creation.entry.symbol, + queue: "shipment-jobs", + job: "assign", + at: location(15), + injection: location(9), + }, + ], + handlers: [ + { + queue: "shipment-jobs", + symbol: "ShipmentWorker.process", + registration: location(40), + declaration: location(41), + }, + ], + }, + assignment.entry.symbol, + ); + expect(result.chapters[0]?.id).toBe(assignment.entry.symbol); + expect(result.chapters[0]?.role).toBe("focused"); + expect(result.connections).toContainEqual( + expect.objectContaining({ + kind: "possible-async-continuation", + to: "ShipmentWorker.process", + }), + ); + expect( + result.connections.find((item) => item.to === "ShipmentWorker.process") + ?.explanation, + ).toContain("unverified"); +}); + +it("uses documented command input and output when deep tracing is unavailable", () => { + const evidence = [{ file: "README.md", line: 3 }]; + const commandInventory: OnboardingStoryInventory = { + ...inventory, + entries: [ + { + kind: "entry", + name: "event-count", + text: "The event-count command enters at src/cli.js.", + basis: "code-observation", + evidence, + }, + ], + artifacts: [ + { + kind: "artifact", + text: "The command reads a JSONL file.", + basis: "repository-statement", + evidence, + }, + ], + outputs: [ + { + kind: "output", + text: "The command prints sorted counts.", + basis: "repository-statement", + evidence, + }, + ], + }; + const result = selectOnboardingStories( + [], + commandInventory, + concepts, + queues, + ); + expect(result.chapters[0]?.id).toBe("event-count"); + expect(result.chapters[0]?.input?.text).toContain("JSONL"); + expect(result.chapters[0]?.output?.text).toContain("counts"); + expect(result.chapters[0]?.firstUnsupportedBoundary?.reason).toContain( + "No supported source trace", + ); +}); + +it("keeps an explicitly focused empty handler visible as an unverified source entry", () => { + const empty = trace("ShipmentController.inspectShipment", 70, "unused"); + empty.methods[0]!.events = []; + const result = selectOnboardingStories( + [empty], + inventory, + concepts, + queues, + empty.entry.symbol, + ); + expect(result.chapters[0]?.id).toBe(empty.entry.symbol); + expect(result.chapters[0]?.role).toBe("focused"); + expect(result.chapters[0]?.decision).toBeUndefined(); +}); + +it("keeps a prose-only relationship separate from a proven call", () => { + const documented: OnboardingStoryInventory = { + ...inventory, + purpose: { + kind: "purpose", + text: "ShipmentController.createShipment and FleetController.assignShipment are related workflows.", + basis: "repository-statement", + evidence: [{ file: "README.md", line: 4 }], + }, + }; + const result = selectOnboardingStories( + [ + trace("ShipmentController.createShipment", 10, "if duplicate"), + trace("FleetController.assignShipment", 30, "if unavailable"), + ], + documented, + concepts, + queues, + ); + expect(result.connections).toContainEqual( + expect.objectContaining({ + kind: "documented-relation", + evidence: [{ file: "README.md", line: 4 }], + }), + ); + expect(result.connections.some((item) => item.kind === "direct-call")).toBe( + false, + ); +}); diff --git a/packages/standards/src/onboarding-story-selection.ts b/packages/standards/src/onboarding-story-selection.ts new file mode 100644 index 0000000..07ca390 --- /dev/null +++ b/packages/standards/src/onboarding-story-selection.ts @@ -0,0 +1,389 @@ +import type { + Evidence, + OnboardingConceptEvidence, + OnboardingQueueEvidence, + OnboardingStoryChapter, + OnboardingStoryConnection, + OnboardingStoryInventory, + OnboardingStorySelection, + OnboardingTrace, +} from "@transferkit/core"; + +import { selectOnboardingConcepts } from "./onboarding-concepts.js"; +import { selectOnboardingContinuations } from "./onboarding-continuations.js"; + +interface Profile { + trace: OnboardingTrace; + category: "start" | "assignment" | "progress" | "callback" | "other"; + central: boolean; + namedCentral: boolean; + touched: { name: string; evidence: Evidence[] }[]; + score: number; + meaningful: boolean; +} + +export function selectOnboardingStories( + traces: readonly OnboardingTrace[], + inventory: OnboardingStoryInventory, + concepts: OnboardingConceptEvidence, + queues: OnboardingQueueEvidence, + focusSymbol?: string, +): OnboardingStorySelection { + const central = inventory.terms[0]?.name; + const profiles = traces.map((trace) => profile(trace, central, concepts)); + const chosen: Profile[] = []; + const remaining = profiles.filter((item) => item.meaningful); + const focus = focusSymbol + ? profiles.find((item) => item.trace.entry.symbol === focusSymbol) + : undefined; + const representative = + focus ?? + best( + remaining.filter((item) => item.central && item.category === "start"), + ) ?? + best(remaining.filter((item) => item.central)) ?? + best(remaining); + if (representative) take(representative, remaining, chosen); + + for (const category of ["assignment", "progress", "callback"] as const) { + if (chosen.length >= 4) break; + const next = best( + remaining.filter( + (item) => item.category === category && (item.central || !central), + ), + ); + if (next) take(next, remaining, chosen); + } + while (chosen.length < Math.min(4, profiles.length)) { + const distinct = remaining.filter( + (item) => !chosen.some((prior) => duplicate(item, prior)), + ); + const related = distinct.filter( + (item) => + item.central || + (!chosen.some((prior) => prior.central) && + chosen.some((prior) => + prior.touched.some((value) => + item.touched.some((other) => other.name === value.name), + ), + )), + ); + const next = + best(related) ?? + (chosen.some((item) => item.central) ? undefined : best(distinct)); + if (!next) break; + take(next, remaining, chosen); + } + const chapters = chosen.map((item, index) => + chapter( + item, + inventory, + index === 0 ? (focus ? "focused" : "representative") : "complementary", + central, + ), + ); + if (!chapters.length) { + const entry = inventory.entries[0]; + if (entry) + chapters.push({ + id: entry.name ?? entry.text, + role: focus ? "focused" : "representative", + entry, + ...(inventory.artifacts[0] ? { input: inventory.artifacts[0] } : {}), + ...(inventory.outputs[0] ? { output: inventory.outputs[0] } : {}), + reason: inventory.outputs.length + ? "The documented entry and output give a useful starting path; source behavior is not traced." + : "This is a declared entry; its internal path and output need inspection.", + firstUnsupportedBoundary: { + reason: "No supported source trace connects this entry to an output.", + evidence: entry.evidence, + }, + inspectNext: entry.evidence, + }); + } + return { + chapters, + connections: connections(chosen, inventory, queues, central), + rejected: profiles + .filter((item) => !chosen.includes(item)) + .map((item) => ({ + entry: item.trace.entry.symbol, + reason: + "Outside the four-chapter reading path; source trace remains available.", + })), + }; +} + +function profile( + trace: OnboardingTrace, + central: string | undefined, + concepts: OnboardingConceptEvidence, +): Profile { + const symbol = trace.entry.symbol; + const method = symbol.split(".").at(-1) ?? ""; + const label = `${symbol} ${trace.entry.path ?? ""}`; + const category: Profile["category"] = /webhook|callback/iu.test(label) + ? "callback" + : /^(?:add|create|register|submit|open|start)/iu.test(method) && + trace.entry.verb === "POST" + ? "start" + : /assign|distribut|allocate/iu.test(label) + ? "assignment" + : /pickup|deliver|status|consent|accept|approve|reject|confirm/iu.test( + label, + ) + ? "progress" + : "other"; + const touched = selectOnboardingConcepts(trace, concepts) + .filter((item) => item.calls.length) + .map((item) => ({ + name: item.entity.name, + evidence: item.calls.slice(0, 2).map((call) => ({ + file: call.at.file, + line: call.at.line, + })), + })); + const events = trace.methods.flatMap((item) => item.events); + const decisions = events.filter( + (item) => item.kind === "branch" || item.kind === "throw", + ).length; + const effects = events.filter((item) => item.effect).length; + const meaningful = + trace.methods.length > 1 || + decisions + effects > 0 || + trace.calls.some((call) => call.kind === "direct"); + const namedCentral = central + ? label.toLowerCase().includes(central.toLowerCase()) + : false; + const symbolCentral = central + ? symbol.toLowerCase().includes(central.toLowerCase()) + : false; + const isCentral = + namedCentral || touched.some((item) => item.name === central); + return { + trace, + category, + central: isCentral, + namedCentral, + touched, + score: + (isCentral ? 70 : 0) + + (namedCentral ? 160 : 0) + + (symbolCentral ? 200 : 0) + + (category === "start" ? 25 : 0) + + Math.min(decisions, 8) * 3 + + Math.min(effects, 8) * 3 + + Math.min(trace.methods.length, 8) * 2 - + (trace.gaps.length && !decisions && !effects ? 8 : 0), + meaningful, + }; +} + +function chapter( + profile: Profile, + inventory: OnboardingStoryInventory, + role: OnboardingStoryChapter["role"], + central: string | undefined, +): OnboardingStoryChapter { + const { trace, category } = profile; + const events = trace.methods.flatMap((method) => method.events); + const decision = events.find( + (event) => event.kind === "branch" || event.kind === "throw", + ); + const result = events.find( + (event) => event.effect === "write-like" || event.kind === "return", + ); + const alternate = events.find( + (event) => + (event.kind === "throw" || event.kind === "return") && + event.path.length > 0, + ); + const gap = trace.gaps[0]; + const entry = inventory.entries.find( + (claim) => claim.name === trace.entry.symbol, + ) ?? { + kind: "entry" as const, + name: trace.entry.symbol, + text: `${trace.entry.symbol} is a declared ${trace.entry.kind ?? "source"} entry.`, + basis: "code-observation" as const, + evidence: [ + { + file: trace.entry.declaration.file, + line: trace.entry.declaration.line, + }, + ], + }; + return { + id: trace.entry.symbol, + role, + entry, + trace, + reason: `${profile.central && central ? `${central} appears in this entry or its traced data calls; ` : ""}${category === "start" ? "this is a declared creation/start entry" : category === "other" ? "this gives a distinct source entry" : `this shows a ${category} entry`}; ${decision ? "a decision is visible" : "no decision is established in the bounded trace"}; ${result ? "a return or effect is visible" : "the result is not established in the bounded trace"}.`, + ...(decision + ? { decision: { file: decision.at.file, line: decision.at.line } } + : {}), + ...(result + ? { result: { file: result.at.file, line: result.at.line } } + : {}), + ...(alternate + ? { alternate: { file: alternate.at.file, line: alternate.at.line } } + : {}), + ...(gap + ? { + firstUnsupportedBoundary: { + reason: gap.reason, + evidence: [{ file: gap.at.file, line: gap.at.line }], + }, + } + : {}), + inspectNext: gap + ? [{ file: gap.at.file, line: gap.at.line }] + : trace.methods.slice(1, 2).map((method) => ({ + file: method.declaration.file, + line: method.declaration.line, + })), + }; +} + +function connections( + chosen: readonly Profile[], + inventory: OnboardingStoryInventory, + queues: OnboardingQueueEvidence, + central: string | undefined, +): OnboardingStoryConnection[] { + const result: OnboardingStoryConnection[] = []; + for (const from of chosen) { + for (const continuation of selectOnboardingContinuations( + from.trace, + queues, + )) + if (continuation.handler) + result.push({ + from: from.trace.entry.symbol, + to: continuation.handler.symbol, + kind: "possible-async-continuation", + explanation: + "A literal queue publication matches this handler registration; execution and delivery are unverified.", + evidence: [ + { + file: continuation.publication.at.file, + line: continuation.publication.at.line, + }, + { + file: continuation.handler.registration.file, + line: continuation.handler.registration.line, + }, + ], + }); + for (const to of chosen) { + if (from === to) continue; + const direct = from.trace.calls.find( + (call) => + call.kind === "direct" && + call.declaredTarget === to.trace.entry.symbol, + ); + if (direct) + result.push({ + from: from.trace.entry.symbol, + to: to.trace.entry.symbol, + kind: "direct-call", + explanation: "The first entry directly calls the second declaration.", + evidence: [{ file: direct.site.file, line: direct.site.line }], + }); + } + } + for (let left = 0; left < chosen.length; left++) + for (let right = left + 1; right < chosen.length; right++) { + const from = chosen[left]!; + const to = chosen[right]!; + const shared = from.touched.find((item) => + to.touched.some((other) => other.name === item.name), + ); + if (shared) { + const other = to.touched.find((item) => item.name === shared.name)!; + result.push({ + from: from.trace.entry.symbol, + to: to.trace.entry.symbol, + kind: "shared-artifact", + explanation: `Both bounded traces touch ${shared.name}; this does not establish ordering or a call between them.`, + evidence: [...shared.evidence, ...other.evidence], + }); + } else { + const documented = [ + ...(inventory.purpose ? [inventory.purpose] : []), + ...inventory.artifacts, + ...inventory.outputs, + ].find( + (claim) => + claim.basis === "repository-statement" && + claim.text.includes(from.trace.entry.symbol) && + claim.text.includes(to.trace.entry.symbol), + ); + if (documented) { + result.push({ + from: from.trace.entry.symbol, + to: to.trace.entry.symbol, + kind: "documented-relation", + explanation: + "Repository prose names both entries; a call or execution order remains unverified.", + evidence: documented.evidence, + }); + } else if ( + central && + `${from.trace.entry.symbol} ${from.trace.entry.path ?? ""}` + .toLowerCase() + .includes(central.toLowerCase()) && + `${to.trace.entry.symbol} ${to.trace.entry.path ?? ""}` + .toLowerCase() + .includes(central.toLowerCase()) + ) + result.push({ + from: from.trace.entry.symbol, + to: to.trace.entry.symbol, + kind: "unproven-association", + explanation: `Both entries name ${central}, but the bounded traces do not prove shared state or sequence.`, + evidence: [ + { + file: from.trace.entry.declaration.file, + line: from.trace.entry.declaration.line, + }, + { + file: to.trace.entry.declaration.file, + line: to.trace.entry.declaration.line, + }, + ], + }); + } + } + return result; +} + +function duplicate(left: Profile, right: Profile): boolean { + if (left.trace.entry.kind !== right.trace.entry.kind) return false; + const leftMethods = new Set( + left.trace.methods.slice(1).map((item) => item.symbol), + ); + const shared = right.trace.methods + .slice(1) + .some((item) => leftMethods.has(item.symbol)); + return ( + shared && + left.touched.every((item) => + right.touched.some((other) => other.name === item.name), + ) + ); +} + +function best(profiles: readonly Profile[]): Profile | undefined { + return [...profiles].sort( + (left, right) => + right.score - left.score || + left.trace.entry.symbol.localeCompare(right.trace.entry.symbol), + )[0]; +} + +function take(item: Profile, remaining: Profile[], chosen: Profile[]): void { + chosen.push(item); + const index = remaining.indexOf(item); + if (index >= 0) remaining.splice(index, 1); +} diff --git a/packages/standards/src/onboarding-story.test.ts b/packages/standards/src/onboarding-story.test.ts new file mode 100644 index 0000000..d4f3f37 --- /dev/null +++ b/packages/standards/src/onboarding-story.test.ts @@ -0,0 +1,61 @@ +import { expect, it } from "vitest"; + +import type { OnboardingStoryEvidence } from "@transferkit/core"; + +import { selectOnboardingStoryInventory } from "./onboarding-story.js"; + +it("ranks a repeated central record without inventing its business meaning", () => { + const source = { file: "src/shipment.ts", line: 4 }; + const evidence: OnboardingStoryEvidence = { + claims: [ + { + kind: "entry", + name: "ShipmentController.create", + text: "POST /shipments is declared on ShipmentController.create.", + basis: "code-observation", + evidence: [source], + }, + { + kind: "entry", + name: "ShipmentController.assign", + text: "POST /shipments/:id/assign is declared on ShipmentController.assign.", + basis: "code-observation", + evidence: [source], + }, + ], + terms: [ + { + name: "Fleet", + codeRole: "declared data entity", + evidence: [source], + relationCount: 1, + relations: [], + }, + { + name: "Shipment", + codeRole: "declared data entity", + evidence: [source], + relationCount: 7, + relations: [{ property: "fleet", target: "Fleet", evidence: [source] }], + }, + ], + rejectedDescriptions: [ + { + text: "NestJS starter repository", + evidence: [{ file: "README.md", line: 3 }], + reason: "generic starter text", + }, + ], + }; + const inventory = selectOnboardingStoryInventory(evidence); + expect(inventory.terms[0]?.name).toBe("Shipment"); + expect(inventory.terms[0]?.meaning).toBeUndefined(); + expect(inventory.terms[0]?.relations[0]?.target).toBe("Fleet"); + expect(inventory.purpose).toBeUndefined(); + expect(inventory.unknowns).toContain( + "The repository purpose is not established by project-specific prose.", + ); + expect(inventory.rejectedDescriptions[0]?.evidence[0]?.file).toBe( + "README.md", + ); +}); diff --git a/packages/standards/src/onboarding-story.ts b/packages/standards/src/onboarding-story.ts new file mode 100644 index 0000000..c9e8f19 --- /dev/null +++ b/packages/standards/src/onboarding-story.ts @@ -0,0 +1,84 @@ +import type { + OnboardingStoryClaim, + OnboardingStoryEvidence, + OnboardingStoryInventory, +} from "@transferkit/core"; + +export function selectOnboardingStoryInventory( + evidence: OnboardingStoryEvidence, +): OnboardingStoryInventory { + const claims = evidence.claims.filter((claim) => claim.evidence.length > 0); + const selected = (kind: OnboardingStoryClaim["kind"], limit: number) => + unique(claims.filter((claim) => claim.kind === kind)).slice(0, limit); + const purpose = selected("purpose", 1)[0]; + const entries = selected("entry", 16); + const outputs = selected("output", 6); + const artifacts = selected("artifact", 12); + const terms = evidence.terms + .map((term) => ({ + term, + score: + (term.meaning ? 4 : 0) + + term.relationCount + + term.relations.length * 2 + + Math.min(8, term.evidence.length - 1) + + [purpose, ...entries, ...outputs] + .filter((claim) => claim !== undefined) + .reduce( + (count, claim) => + count + + (mentions(claim.text, term.name) + ? claim.kind === "purpose" + ? 4 + : 2 + : 0), + 0, + ), + })) + .sort((a, b) => b.score - a.score || a.term.name.localeCompare(b.term.name)) + .slice(0, 8) + .map(({ term }) => term); + const unknowns: string[] = []; + if (!purpose) + unknowns.push( + "The repository purpose is not established by project-specific prose.", + ); + if (!entries.length) + unknowns.push("No supported entry point was identified."); + if (!outputs.length) + unknowns.push( + "The repository's outputs are not established by the inspected documentation.", + ); + if (terms.some((term) => !term.meaning)) + unknowns.push( + "Business meanings for some code terms require owner confirmation.", + ); + return { + ...(purpose ? { purpose } : {}), + roles: selected("role", 4), + entries, + artifacts, + outputs, + boundaries: selected("boundary", 8), + observations: selected("observation", 16), + terms, + rejectedDescriptions: evidence.rejectedDescriptions, + unknowns, + }; +} + +function unique(claims: OnboardingStoryClaim[]): OnboardingStoryClaim[] { + const seen = new Set<string>(); + return claims.filter((claim) => { + const key = `${claim.kind}:${claim.name ?? ""}:${claim.text}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); +} + +function mentions(text: string, name: string): boolean { + const words = name.replace(/([a-z])([A-Z])/gu, "$1 $2").toLowerCase(); + const haystack = text.replace(/([a-z])([A-Z])/gu, "$1 $2").toLowerCase(); + return haystack.includes(words); +} diff --git a/packages/standards/src/personal-onboarding.ts b/packages/standards/src/personal-onboarding.ts index 0e85edd..6c4905b 100644 --- a/packages/standards/src/personal-onboarding.ts +++ b/packages/standards/src/personal-onboarding.ts @@ -7,6 +7,7 @@ export function personalOnboardingExercises( sections: ReadonlySet<string>, hasExplainedFlow: boolean, hasCandidateFlow: boolean, + guideSections?: ReadonlyMap<string, string>, ): PersonalOnboardingExercise[] { for (const required of [ "system-overview", @@ -20,37 +21,64 @@ export function personalOnboardingExercises( const flowSection = hasExplainedFlow ? "explained-flow" : hasCandidateFlow - ? "candidate-flows" + ? sections.has("candidate-flows") + ? "candidate-flows" + : "reference-appendix" : "unknowns"; + const journeys = [ + ...(guideSections?.get("explained-flow") ?? "").matchAll( + /^### (?:Source journey|Entry to inspect): (.+)$/gmu, + ), + ] + .map((match) => match[1]!) + .slice(0, 2); + const concepts = [ + ...(guideSections?.get("concepts") ?? "").matchAll(/^### ([^\n]+)$/gmu), + ] + .map((match) => match[1]!) + .slice(0, 3); + const orientation = sections.has("start-here") + ? "Read Start here and System map" + : "Read System map"; + const changeMap = sections.has("change-points") + ? "Use Change points" + : "Inspect the guide and cited source"; return [ { id: personalOnboardingExerciseIds[0], title: "Understand the system", - objective: - "Explain the entry point, major components, and supported relationships using the guide's evidence labels.", + objective: concepts.length + ? `${orientation} and Concepts. Explain what the repository does and how ${concepts.join(", ")} appear in the selected entries; label unsupported business meanings and relationships.` + : `${orientation}. Explain the repository's stated purpose or source-level role, its entry point and input/output, and what remains unknown.`, guideSectionId: "system-overview", outcome: - "Write a short system map and list any relationships that still need confirmation.", + "Write a short mental model with citations and one question for an owner or source check.", }, { id: personalOnboardingExerciseIds[1], title: "Trace a flow", - objective: hasExplainedFlow - ? "Check one explained static flow against its cited source and identify its branch and effect gaps." - : hasCandidateFlow - ? "Investigate one candidate route and record the source-backed steps you can establish." - : "Identify what route or call evidence is missing before a flow can be traced.", + objective: + journeys.length >= 2 + ? `Explain ${journeys[0]} and ${journeys[1]} as separate entries: trigger, decision, output or state, alternate exit, and first unsupported edge. Only connect them where the guide has evidence.` + : journeys.length === 1 + ? `Explain ${journeys[0]}: input, output or state, alternate exit, and first unsupported edge. Mark repository statements separately from traced behavior.` + : hasExplainedFlow + ? "Check one connected journey against its cited source and identify its decision, effect, and unsupported steps." + : hasCandidateFlow + ? "Investigate one candidate route and record the source-backed steps you can establish." + : "Identify what route or call evidence is missing before a flow can be traced.", guideSectionId: flowSection, + ...(journeys.length ? { linkedJourneys: journeys } : {}), outcome: hasExplainedFlow || hasCandidateFlow - ? "Record a concise trace with repository-relative citations and unresolved steps." + ? "Record a short story with repository-relative citations, separate entry points, and unresolved steps." : "Record the missing evidence and a concrete next investigation step.", }, { id: personalOnboardingExerciseIds[2], title: "Attempt a local run", objective: - "Review documented setup clues, verify prerequisites and safe credentials, then attempt only steps you can safely perform.", + "Read Run and observe. Verify the declared runtime and prerequisites, choose the guide's safe first observation or record its blocker, and distinguish a documented command from one you actually ran.", guideSectionId: "setup-and-operations", outcome: "Record commands actually attempted, observed results, and any blocker; documented commands are runtime unverified until tried.", @@ -58,11 +86,14 @@ export function personalOnboardingExercises( { id: personalOnboardingExerciseIds[3], title: "Identify remaining ownership gaps", - objective: - "Review unknowns and separate questions for a knowledgeable person from questions needing runtime evidence.", - guideSectionId: "unknowns", + objective: journeys.length + ? `${changeMap} to find where to investigate ${journeys[0]} and its test candidate; ask which remaining questions need source, runtime, or owner evidence.` + : `${changeMap} to find a likely edit and test location if possible; classify remaining questions as source, runtime, or owner-dependent.`, + guideSectionId: sections.has("change-points") + ? "change-points" + : "unknowns", outcome: - "List the remaining questions, their intended source, and any evidence gathered.", + "Record a likely change location, test evidence or gap, and questions to take to an owner.", }, ]; }