From 16f1f108a546acb734d5ad8d8481cd55e5b5a892 Mon Sep 17 00:00:00 2001 From: alialaraby Date: Sat, 3 Oct 2026 00:41:46 +0300 Subject: [PATCH 1/7] Build repository onboarding deep guide and acceptance baseline --- README.md | 7 +- .../B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md | 103 +++ docs/ONBOARDING_DEEP_GUIDE_PLAN.md | 397 ++++++++++ docs/ONBOARDING_DEPTH_BASELINE.md | 161 ++++ .../ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md | 118 +++ docs/ONBOARDING_HUMAN_STORY_PLAN.md | 92 +++ docs/ONBOARDING_PHASE6_ACCEPTANCE.md | 36 + docs/ONBOARDING_V2.md | 32 +- experiments/fixtures/nest-trace/controller.ts | 12 + .../fixtures/nest-trace/order.service.ts | 38 + experiments/fixtures/nest-trace/providers.ts | 19 + experiments/fixtures/nest-trace/tsconfig.json | 9 + experiments/onboarding-phase2-benchmark.mjs | 58 ++ experiments/onboarding-phase6-regression.py | 136 ++++ experiments/onboarding-trace-spike.mjs | 333 ++++++++ experiments/onboarding-trace-spike.test.mjs | 79 ++ fixtures/onboarding-deep-guide/controller.ts | 17 + fixtures/onboarding-deep-guide/entity.ts | 28 + fixtures/onboarding-deep-guide/limits.ts | 47 ++ fixtures/onboarding-deep-guide/nest-shim.d.ts | 8 + fixtures/onboarding-deep-guide/service.ts | 75 ++ fixtures/onboarding-deep-guide/worker.ts | 17 + fixtures/onboarding-human-cli/README.md | 5 + fixtures/onboarding-human-cli/package.json | 11 + fixtures/onboarding-human-cli/src/cli.js | 29 + fixtures/onboarding-human-sparse/README.md | 5 + fixtures/onboarding-human-sparse/compare.py | 18 + fixtures/onboarding-phase4/README.md | 5 + fixtures/onboarding-phase4/controller.ts | 12 + fixtures/onboarding-phase4/entity.ts | 10 + fixtures/onboarding-phase4/module.ts | 6 + fixtures/onboarding-phase4/package.json | 11 + fixtures/onboarding-phase4/repository.ts | 9 + fixtures/onboarding-phase4/scheduled.ts | 11 + fixtures/onboarding-phase4/service.ts | 20 + fixtures/onboarding-phase4/worker.ts | 11 + fixtures/onboarding-plain-node/README.md | 5 + fixtures/onboarding-plain-node/package.json | 8 + fixtures/onboarding-plain-node/src/server.js | 22 + fixtures/onboarding-setup/.env.example | 2 + fixtures/onboarding-setup/README.md | 11 + fixtures/onboarding-setup/docker-compose.yml | 11 + fixtures/onboarding-setup/package.json | 10 + .../onboarding-setup/src/health.controller.ts | 9 + fixtures/onboarding-setup/src/main.ts | 5 + packages/cli/README.md | 5 +- packages/cli/src/cli-ux.test.ts | 2 +- packages/cli/src/cli.ts | 16 +- .../cli/src/generate-onboarding-guide.test.ts | 345 ++++++++- packages/cli/src/generate-onboarding-guide.ts | 137 +++- .../src/generate-onboarding-workspace.test.ts | 85 ++- .../cli/src/generate-onboarding-workspace.ts | 5 +- packages/cli/src/onboarding-v2-view.ts | 27 +- packages/core/src/index.ts | 1 + packages/core/src/onboarding-trace.ts | 153 ++++ packages/core/src/personal-onboarding.ts | 1 + packages/renderers/src/index.ts | 7 +- .../renderers/src/onboarding-guide.test.ts | 38 +- packages/renderers/src/onboarding-guide.ts | 591 +++++++++++++- packages/renderers/src/personal-onboarding.ts | 32 +- packages/scanners/src/index.ts | 116 ++- packages/scanners/src/onboarding-concepts.ts | 172 +++++ .../scanners/src/onboarding-queues.test.ts | 28 + packages/scanners/src/onboarding-queues.ts | 147 ++++ .../src/onboarding-repository-notes.ts | 213 ++++++ packages/scanners/src/onboarding-scheduled.ts | 90 +++ .../scanners/src/onboarding-trace.test.ts | 228 ++++++ packages/scanners/src/onboarding-trace.ts | 720 ++++++++++++++++++ .../scanners/src/realistic-fixture.test.ts | 1 + packages/scanners/src/repository-files.ts | 40 +- packages/standards/src/index.ts | 10 + .../standards/src/onboarding-concepts.test.ts | 94 +++ packages/standards/src/onboarding-concepts.ts | 92 +++ .../standards/src/onboarding-continuations.ts | 39 + .../src/onboarding-journey-selection.ts | 294 +++++++ .../standards/src/onboarding-scheduled.ts | 57 ++ packages/standards/src/personal-onboarding.ts | 43 +- 77 files changed, 5791 insertions(+), 106 deletions(-) create mode 100644 docs/B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md create mode 100644 docs/ONBOARDING_DEEP_GUIDE_PLAN.md create mode 100644 docs/ONBOARDING_DEPTH_BASELINE.md create mode 100644 docs/ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md create mode 100644 docs/ONBOARDING_HUMAN_STORY_PLAN.md create mode 100644 docs/ONBOARDING_PHASE6_ACCEPTANCE.md create mode 100644 experiments/fixtures/nest-trace/controller.ts create mode 100644 experiments/fixtures/nest-trace/order.service.ts create mode 100644 experiments/fixtures/nest-trace/providers.ts create mode 100644 experiments/fixtures/nest-trace/tsconfig.json create mode 100644 experiments/onboarding-phase2-benchmark.mjs create mode 100644 experiments/onboarding-phase6-regression.py create mode 100644 experiments/onboarding-trace-spike.mjs create mode 100644 experiments/onboarding-trace-spike.test.mjs create mode 100644 fixtures/onboarding-deep-guide/controller.ts create mode 100644 fixtures/onboarding-deep-guide/entity.ts create mode 100644 fixtures/onboarding-deep-guide/limits.ts create mode 100644 fixtures/onboarding-deep-guide/nest-shim.d.ts create mode 100644 fixtures/onboarding-deep-guide/service.ts create mode 100644 fixtures/onboarding-deep-guide/worker.ts create mode 100644 fixtures/onboarding-human-cli/README.md create mode 100644 fixtures/onboarding-human-cli/package.json create mode 100644 fixtures/onboarding-human-cli/src/cli.js create mode 100644 fixtures/onboarding-human-sparse/README.md create mode 100644 fixtures/onboarding-human-sparse/compare.py create mode 100644 fixtures/onboarding-phase4/README.md create mode 100644 fixtures/onboarding-phase4/controller.ts create mode 100644 fixtures/onboarding-phase4/entity.ts create mode 100644 fixtures/onboarding-phase4/module.ts create mode 100644 fixtures/onboarding-phase4/package.json create mode 100644 fixtures/onboarding-phase4/repository.ts create mode 100644 fixtures/onboarding-phase4/scheduled.ts create mode 100644 fixtures/onboarding-phase4/service.ts create mode 100644 fixtures/onboarding-phase4/worker.ts create mode 100644 fixtures/onboarding-plain-node/README.md create mode 100644 fixtures/onboarding-plain-node/package.json create mode 100644 fixtures/onboarding-plain-node/src/server.js create mode 100644 fixtures/onboarding-setup/.env.example create mode 100644 fixtures/onboarding-setup/README.md create mode 100644 fixtures/onboarding-setup/docker-compose.yml create mode 100644 fixtures/onboarding-setup/package.json create mode 100644 fixtures/onboarding-setup/src/health.controller.ts create mode 100644 fixtures/onboarding-setup/src/main.ts create mode 100644 packages/core/src/onboarding-trace.ts create mode 100644 packages/scanners/src/onboarding-concepts.ts create mode 100644 packages/scanners/src/onboarding-queues.test.ts create mode 100644 packages/scanners/src/onboarding-queues.ts create mode 100644 packages/scanners/src/onboarding-repository-notes.ts create mode 100644 packages/scanners/src/onboarding-scheduled.ts create mode 100644 packages/scanners/src/onboarding-trace.test.ts create mode 100644 packages/scanners/src/onboarding-trace.ts create mode 100644 packages/standards/src/onboarding-concepts.test.ts create mode 100644 packages/standards/src/onboarding-concepts.ts create mode 100644 packages/standards/src/onboarding-continuations.ts create mode 100644 packages/standards/src/onboarding-journey-selection.ts create mode 100644 packages/standards/src/onboarding-scheduled.ts diff --git a/README.md b/README.md index 06b1c59..a923bef 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ TransferKit is a local-first CLI for structured software ownership transfer. It 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** 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. +- **Onboarding** creates a shared repository-evidence guide and a separate personal learning workspace. 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. @@ -36,6 +36,8 @@ tk handover plan tk handover sync tk handover status +tk onboard guide +tk onboard workspace tk onboard plan tk onboard status ``` @@ -47,8 +49,11 @@ To update personal onboarding progress: ```bash tk onboard task in-progress tk onboard task completed +tk onboard sync ``` +`onboard guide` generates a shared `ONBOARDING.md` from repository evidence; `onboard guide --focus ` selects a supported entry to inspect. `onboard workspace` creates the personal Markdown checklist in `.transferkit.local/`. Edit its checkboxes, then run `onboard sync` and `onboard status`. The guide describes static source paths and declared setup commands; it does not run the application or verify outcomes. + See the [workflow example](examples/workflow.md) for representative output and [getting started](docs/getting-started.md) for a fuller walkthrough. ## What's new in 0.2.0 diff --git a/docs/B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md b/docs/B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md new file mode 100644 index 0000000..f0f307e --- /dev/null +++ b/docs/B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md @@ -0,0 +1,103 @@ +# B2C backend — a newcomer’s working guide + +> **Reference example for TransferKit’s human-facing output.** Prepared from the B2C backend source at `79cc98e534a95a2a316c3464281619fb86a12d99` and the repository’s testing guide. This is an engineer’s interpretation of checked-in behavior, not an approved statement of company policy. Paths below are relative to the B2C backend repository. An owner should confirm the business terms and operational procedures before this becomes team documentation. + +## The system in two minutes + +This service coordinates B2C shipments. A shipment is the record that ties together vendor/customer relations, pickup and drop-off locations, an assigned fleet and possibly a driver, a history of status changes, and the prices later used for invoices. The API is a NestJS application backed by PostgreSQL; some work also enters through RabbitMQ consumers and external integration callbacks. Redis appears in assignment/pricing and other supporting paths. See `src/module/data/entity/shipment.entity.ts:103–170,245–294,331–403,434–438`, `src/main.ts:245–269`, and `src/app.module.ts:180–225`. + +The useful mental model is **shipment → assignment → pickup → delivery or exception → financial settlement**. That is a reading order, not a promise that every shipment follows one linear path. Mobile drivers and external fleets report progress through different code paths. Cancellations, missed pickups, future delivery, and return to origin change the path. The status vocabulary is in `src/data/enum/shipment.ts:70–97`; the behavior that accepts a status depends on the entry path. + +If you have one hour, read [the domain terms](#five-terms-to-learn), then [the two status paths](#4-delivery-progress-know-which-status-path-you-are-reading), and then [your first safe investigation](#your-first-safe-investigation). Do not start by reading every entity or module. + +## Five terms to learn + +| Term | What it means for your first investigation | Where to check | +| --- | --- | --- | +| **Shipment** | The central delivery record. It holds current associations and a `latestHistoryAction`, while separate history rows explain how that state was reached. Treat the current field and the history as two views to reconcile when debugging. | `src/module/data/entity/shipment.entity.ts:103,293,364–403`; `src/module/data/entity/shipment-history.entity.ts:24–55` | +| **Vendor, customer, seller** | These are distinct relations in the model. The vendor has configuration that can change pickup requirements; the shipment also has customer and seller-side pickup information. Do not assume the terms are interchangeable or that “customer” always means the recipient. | `src/module/data/entity/shipment.entity.ts:157,232,387`; `src/module/data/entity/vendor.entity.ts:31–80`; `src/module/shipment/services/pickup.service.ts:165–191` | +| **Fleet, driver, truck** | A fleet can be assigned without a driver. Supplying a driver introduces additional membership and truck-type checks; a successful assignment records fleet history and optionally driver history. | `src/module/fleet/services/mobile-fleet.service.ts:67–150,188–239` | +| **AWB and proof** | The AWB is used to identify/validate a shipment at pickup and in external callbacks. Pickup can require an AWB scan, photos, or OTP depending on vendor configuration. | `src/module/shipment/services/pickup.service.ts:60–75,150–225`; `src/module/integrations/integrations.service.ts:653–665` | +| **Price, transaction, invoice** | Shipment transactions carry customer and fleet amounts; invoices have separate customer and fleet types. Changing assignment or invoice logic can affect financial records, so trace the applicable transaction before altering totals. | `src/module/data/entity/shipment-transaction.entity.ts:19–47`; `src/data/enum/invoice.ts:1–18`; `src/module/invoice/invoice.service.ts:760–825` | + +### A simple map + +```text +Request / queue message / fleet callback + ↓ + controller or consumer + ↓ + feature service rules + ↓ + PostgreSQL shipment + history + related records + ↓ + provider update / notification / integration +``` + +The diagram is a navigation aid. Those side effects are conditional, and the code does not guarantee that a provider update, notification, or integration succeeds just because the database operation did. Start at `src/main.ts:116–150,245–269`, `src/app.module.ts:180–280`, and the selected services below. + +## Follow one shipment through the code + +### 1. Creation: establish identity before assignment + +Start with `ShipmentB2cService.addShipmentB2C` in `src/module/shipment/services/shipment-b2c.service.ts:648`. It checks existing workflow, order-reference, and eRx identifiers before building the shipment and its metadata (`:663–717`). That early duplicate handling matters: when investigating an apparently missing or duplicated request, determine whether the caller got an existing shipment, a rejected conflict, or a new one before looking at downstream assignment. This method is large; read its early identity checks and the resulting saved records first, then follow only the branch for your incident. + +**Ask an owner:** Which intake routes and integrations create most production B2C shipments? The code shows multiple entry mechanisms, but repository evidence alone does not rank them by volume or business importance. + +### 2. Assignment: a fleet accepts responsibility + +`MobileFleetController.assignFleetToShipment` delegates to `MobileFleetService.assignFleetToShipment` (`src/module/fleet/controllers/mobile-fleet.controller.ts:22–40`; `src/module/fleet/services/mobile-fleet.service.ts:67`). The service rejects a missing shipment, an already assigned shipment, or a missing fleet. When a driver is supplied, it also checks that the driver belongs to the fleet, has a truck, and that the truck type is allowed (`mobile-fleet.service.ts:78–149`). + +After those checks, the service saves assignment fields, may create or update a shipment transaction using cached pricing, and writes assignment history inside a query-runner transaction (`mobile-fleet.service.ts:151–239`). It commits at `:269`. Driver notification is attempted before that commit (`:244–260`), and a G2G integration call appears after it (`:271–280`). **For debugging, do not assume notification and external integration share the database transaction.** Check the actual outcome of each boundary. + +**Example question:** “Why does the fleet see a shipment but the driver does not?” Compare `shipment.fleet`, `shipment.driver`, the last assignment history, driver/truck checks, notification logs, and the external integration path. Do not infer driver assignment from fleet assignment alone. + +### 3. Pickup: the mobile driver must satisfy vendor rules + +The driver pickup endpoint calls `PickupService.confirmPickup` (`src/module/shipment/controllers/mobile-shipment.controller.ts:501–528`; `src/module/shipment/services/pickup.service.ts:150`). It first loads the shipment and authorizes the driver. Pickup is accepted only from the configured arrival states (`pickup.service.ts:153–162`). Vendor configuration can require an AWB scan, photos, or OTP; helper methods enforce those checks (`:165–191,340–374`). + +On the allowed path, the method records pickup evidence and appends `OrderPickedUp` through `ShipmentHistoryService.addNewStatus` (`pickup.service.ts:194–251`). It then tries to update provider status, but logs and swallows that failure (`:252–256`). A later POD OTP notification may also run asynchronously (`:258–269`). **A successful pickup response is evidence of the local path reaching its return; it is not proof that every external provider saw the update.** + +**Example question:** “Why is pickup blocked for this driver?” Check the driver authorization, latest status, vendor flags, and pickup evidence in that order. The error shown to the user may reflect a configuration gate rather than a broken endpoint. + +### 4. Delivery progress: know which status path you are reading + +The internal mobile path uses shipment actions such as pickup and delivery controllers (`src/module/shipment/controllers/mobile-shipment.controller.ts:217–258,425–528`). External fleets can call `IntegrationsController.webhook` (`src/module/integrations/integrations.controller.ts:113–123`), which delegates to `IntegrationsService.webhook` (`integrations.service.ts:630`). These are related ways to update shipment progress, **not one continuous call chain**. + +The webhook loads the shipment, checks the fleet/integration type and AWB, and may return early before changing history (`integrations.service.ts:632–665`). It handles cancellations and return-to-origin cases, rejects certain repeated or terminal-state updates, and attempts to insert B2C history (`:689–780`). Some delivered callbacks also calculate price or save proof data; external Shmool shipments have a special proof path (`:797–862`). Provider synchronization failures are logged rather than necessarily reversing the local status (`:863–872`). + +**Example question:** “The carrier says delivered, but our UI disagrees.” Start with the callback payload and receipt, then compare fleet identity, AWB, current latest history, attempted history insert, and provider-update logs. A 2xx transport response alone does not establish that a status was accepted; the method has early returns. + +### 5. Money: invoices are a separate workflow + +`InvoiceService.updateInvoice` is not the next automatic step in the pickup call chain. It is a separate financial workflow (`src/module/invoice/invoice.controller.ts:298–320`; `src/module/invoice/invoice.service.ts:723`). It checks permissions and allowed status transitions, and can recalculate amounts from selected shipments when a draft is edited (`invoice.service.ts:725–825`). Customer and fleet invoices use different transaction fields. Review the invoice type and selected shipment transactions before changing a total or status rule. + +## Your first safe investigation + +1. **Pick one real question.** Example: “What prevents an already assigned shipment from being assigned through the mobile fleet endpoint?” Read the controller, service guard, and related entity/history fields. Write down the expected error and where it originates. Do not change data. +2. **Run a narrow test before a service.** `package.json` declares `npm test` and `npm run build`; `docs/testing-strategy.md` shows how to run one Jest spec. Prefer a co-located service test for a business rule. Tests are uneven across this large repository, so a missing nearby spec is a prompt to add a characterization test when you change the behavior. +3. **Treat local boot as an environment task.** `package.json` requires Node 24. The `.env.example`, `src/config/typeorm.config.ts`, and `src/main.ts` show PostgreSQL, RabbitMQ, Redis, and Firebase configuration touchpoints. The README still contains Nest starter text, so its generic `npm run start` instructions do not constitute a verified B2C setup. Obtain a sanctioned local environment and test credentials before attempting an application start; never use production data for onboarding. +4. **If a configured local instance is already available, observe only.** `GET /health-check` returns `{ status: 'ok' }` in `src/module/health-check/health-check.controller.ts:20–29`. It shows that the HTTP handler responded, not that every dependency or background consumer works. The DB pool endpoint requires an app key and exposes internal capacity; use it only through the team’s approved access path (`:46–52`). +5. **Record the result.** Note the question, cited files, the command or request actually run, observed result, and any blocker. Separate observations from expected behavior. + +## Where to change common behavior + +| If the task concerns… | Start here | Check next | +| --- | --- | --- | +| Duplicate or missing B2C shipment creation | `src/module/shipment/services/shipment-b2c.service.ts:648–717` | Calling route/consumer, identity fields, repository query, new test | +| Fleet/driver assignment | `src/module/fleet/services/mobile-fleet.service.ts:67–285` | Controller, fleet/driver repositories, history, pricing cache, notifications | +| Pickup eligibility or evidence | `src/module/shipment/services/pickup.service.ts:150–269` | Vendor `PrimaryConfigs`, driver helper, history service, co-located tests | +| External fleet status | `src/module/integrations/integrations.service.ts:630–900` | Webhook controller, history insert, integration tests, provider logs | +| Invoice transition or amount | `src/module/invoice/invoice.service.ts:723–840` | Invoice type/status enums, transaction fields, invoice tests | + +Before editing a status rule, identify whether it is used by the driver app, external webhook, scheduled work, or more than one entry point. A change to a shared enum or history method can affect paths that are not visible from one controller. + +## Questions that still need a teammate + +- Which vendors and shipment types are the main supported B2C workflows, and what do **vendor**, **customer**, **seller**, and **receiver** mean to the business in each? +- Which service is authoritative when an external carrier status differs from local shipment history? What is the manual recovery path? +- Which provider callbacks and queues are required in a sanctioned local environment? Who owns their test credentials and contract examples? +- What should happen when driver notification, provider update, or post-commit integration fails after local state changes? +- Which team owns invoice rules and approves changes to customer versus fleet pricing? + +An engineer can navigate the source without these answers, but should not turn plausible code interpretations into business policy. diff --git a/docs/ONBOARDING_DEEP_GUIDE_PLAN.md b/docs/ONBOARDING_DEEP_GUIDE_PLAN.md new file mode 100644 index 0000000..c9d0308 --- /dev/null +++ b/docs/ONBOARDING_DEEP_GUIDE_PLAN.md @@ -0,0 +1,397 @@ +# TransferKit onboarding: deep, evidence-backed system guide + +**Implementation plan and Codex prompts · 30 September 2026** + +## 1. Product contract + +An engineer with no handover should be able to use `tk onboard guide` and the personal onboarding workspace to understand the main concepts and connected behaviors of an unfamiliar Node.js/NestJS repository, locate a likely first change, attempt a local observation, and identify the few questions that code cannot answer. The shared guide must be valuable without a Current Owner, Transfer state, network service, paid API, or AI model. Human context may improve it but cannot be required. + +“Understand roughly 60%” is an aspiration, **not** a score emitted by the CLI. Acceptance depends on an unfamiliar engineer explaining important behavior and locating a change correctly. Static analysis cannot establish business intent, production topology, actual runtime effects, or ownership without suitable evidence. + +### Known starting point + +- Already reported as implemented: shared `ONBOARDING.md`; repository scans and candidate routes; two Debtbox static explained flows; documented setup clues; preservation of human Markdown through managed sections and snapshots; optional owner-written context and verified-setup sections; personal `.transferkit.local/ONBOARDING.md`, four stable `v2:` exercises, local JSON state and Markdown sync; v2-aware `plan` and `status`. Verify all details against current code before changing them. The uploaded guide predates some reported changes. +- Baseline at TransferKit `cb7c25e3`: plain Node fixture has no flow; small Nest fixture has empty handlers; Debtbox has two explanations; Madar B2C has three shallow candidates and no explanation. Madar generation was 5.705 s and 607.3 MiB peak RSS on one local run. These are reference measurements, not universal limits. +- An isolated TypeScript compiler API experiment resolves route-to-method and cross-file declarations. It detects Madar's conditional `queryRunner.manager.save` call sites and a Debtbox local helper, but has no execution-path model, cannot resolve local query-runner methods without dependencies, and loads 1,481 project TS files / approximately 497 MiB for one Madar route. It is **research, not production code**. The project already uses `ts-morph`; no new package is justified by that spike. +- `docs/ONBOARDING_V2.md` and historical `ROADMAP.md` portions may describe earlier status. Current code and current repository docs take precedence. The user considers Handover milestones 7 and 8 complete; this work stays within onboarding. + +### Boundaries + +- Only Node.js/TypeScript and supported NestJS patterns are promised in this sequence. A plain Node/JavaScript project must receive an honest, useful overview of what is actually discoverable; rich Nest behavior must not be falsely generalized to every Node project. Add a second runtime/framework adapter only after a representative fixture proves the need. +- No mandatory local AI, remote AI, paid service, auto-install, auto-running migrations, containers, or arbitrary project scripts. Existing local compute and libraries are sufficient for this plan. +- Do not change Handover behavior. Optional v3 Handover Item enrichment is a later, independent addition after repository-only onboarding succeeds. Do not block this plan on it. +- Preserve guide prose, managed section conflict handling, personal notes, progress, existing stable IDs, and legacy progress. Never silently overwrite or remap them. +- Scanner output is evidence; it is not the reader-facing product. Accuracy outranks breadth; depth must not turn a possible path into a guaranteed outcome. + +## 2. Final user experience and output contract + +### CLI journey + +1. `tk onboard guide` scans read-only and creates or safely updates a shared root `ONBOARDING.md`. An existing unmarked guide is never overwritten. A concurrent human/generated section conflict is surfaced without changing either version. +2. `tk onboard workspace` creates a personal Markdown workspace linked to stable guide anchors; repeated runs must preserve personal notes and progress or explicitly refuse a destructive reconciliation. +3. `tk onboard plan` shows the learning path for the repository, not a generic inventory of technologies. `tk onboard status` distinguishes self-reported exercise completion, recorded observations, and outstanding questions. `tk onboard sync` and `task` retain their current conflict and checkbox semantics. +4. The guide explains useful code paths without needing a handover file. A user may optionally select a route/symbol to focus on if automatic selection misses their work area; this must not invent a ranking of business importance. + +### Shared guide reading order + +1. **Start here:** a short orientation from reliable project text and observed interfaces. If the repository does not state its business purpose, describe the technical shape and explicitly leave purpose unknown. No story from names alone. +2. **System at a glance:** entry points, interfaces, data stores, background work, and boundaries. Show only supported relationships; a small diagram is optional when it conveys more than a table. +3. **Concepts:** a curated glossary of entities/data shapes and relationships relevant to selected journeys. Distinguish data shape from the business meaning of a term. +4. **Connected journeys:** several complementary paths where evidence exists. For each: entry, inputs, checks, alternate branches/early exits, state reads and writes, continuations across helpers/modules/queues/jobs, external boundaries, error behavior, exact gaps, and **where to change it** (code and relevant tests). A tiny service may need one journey; a large one may need more than two. No fixed number is a quality metric. +5. **Run and observe:** repository-specific documented prerequisites/commands, contradictions, a safe proposed first observation, and a clear distinction between documented and actually observed results. The shared owner-supplied verified setup remains optional. +6. **Remaining questions:** a short, deduplicated, answerable list derived from concrete gaps. Distinguish code to inspect, runtime to check, and business/operations to ask a person. +7. **Reference appendix:** full inventories of routes, modules, jobs, integrations, and citations in collapsed sections; no first-screen wall of names. + +### Illustrative final output (fictional repository) + +This compact example shows the expected **substance and order**. `ParcelWorks` and its file locations are fictional; Codex must ground actual golden fixtures in real test source. Large repositories would have more complementary journeys; small ones may have fewer. + +```markdown +# Understand ParcelWorks + +The README describes a service for delivery requests and fleet assignment +(`README.md:8`). The source exposes shipment and tracking routes, stores +Shipment and Assignment records, and declares an assignment worker. +Production behavior has not been observed. + +## Start here + +A request creates a pending Shipment. A separate worker may assign a Fleet. +A tracking update can later mark a Shipment delivered. Those are distinct +steps: saving a request does not prove that assignment or delivery occurred. + +## Concepts + +| Concept | What source establishes | Where it changes | +| --- | --- | --- | +| Shipment | Customer, destination and status fields (`shipment.entity.ts:12`) | Creation service; tracking handler | +| Assignment | Relates shipment, fleet and driver (`assignment.entity.ts:9`) | Assignment worker | + +## Journey 1 — Create a shipment + +**Entry:** `POST /shipments` → `ShipmentController.create` +(`shipment.controller.ts:28–36`). + +1. The controller calls `ShipmentService.create` (`:35` → + `shipment.service.ts:41`). +2. The service loads the customer and checks the destination. A missing + customer throws before the save (`shipment.service.ts:46–58`). +3. On the path past those checks, it assigns `PENDING` and awaits a + repository save (`shipment.service.ts:63–70`). +4. It calls `assignmentQueue.add` with the new ID (`:72–76`). The call is + visible; worker receipt is unverified. + +**If you change this:** inspect the DTO, `ShipmentService.create`, the entity, +the creation test, and the assignment worker that reads the saved ID. + +**Gap:** The save precedes the queue call. Source inspection alone cannot say +how an operator handles a saved shipment when the queue call fails. + +
Code and tests + +- `src/shipment/dto/create-shipment.dto.ts:5–27` +- `src/shipment/shipment.service.ts:41–76` +- `src/shipment/shipment.service.spec.ts:30–104` + +
+ +## Journey 2 — Assign a fleet + +The requested job name at `shipment.service.ts:73` matches the handler +registration at `assignment.processor.ts:18–22`. This is a possible code +continuation, not proof that the job ran. + +The worker loads the Shipment and returns if it is no longer pending (`:25–34`). +It asks `FleetSelectionService` for candidates. Its no-candidate branch does +not create an Assignment (`:37–49`). On a candidate branch it calls +`queryRunner.manager.save` for an Assignment and updates Shipment status +(`:54–71`). Commit, rollback and release calls are present (`:73–88`); +transaction outcomes remain unverified. + +**If you change assignment rules:** inspect `FleetSelectionService.select`, +the no-candidate path, Assignment fields, and worker tests. + +## Run and observe + +The README documents an install and start command. Compose declares Postgres +and Redis and references `.env`. Values and prerequisites are incomplete. +`GET /health` is a declared route (`health.controller.ts:12`), a possible first +check once setup is safe. TransferKit has run no command. Record your attempt +and actual result in `.transferkit.local/ONBOARDING.md`. + +## Questions left + +1. What should happen if the queue call fails after the Shipment save? +2. Who resolves the no-candidate branch, and how? +3. Where does a newcomer obtain safe local configuration? + +
Other routes, jobs, modules and source references +The complete navigable inventory appears here. +
+``` + +The personal file should link to these real guide anchors and contain tasks such as “Explain creation and assignment,” “Locate a safe change,” and “Record a local observation or blocker,” with editable notes, questions and evidence. It must not duplicate the entire shared guide. + +### Evidence language + +Every substantive generated claim has a source type and navigable repository-relative evidence. Use four distinct meanings: + +| Source type | Allowed wording | Disallowed leap | +| --- | --- | --- | +| Code declaration/call | “The method calls `X`”; “the code assigns `status = Y` under condition Z” | “X succeeds”; “the shipment becomes Y in production” | +| Project documentation/comment/test | “The README says …”; “a nearby comment describes …”; “the test expects …” | Treating a statement or test as proof of current runtime behavior | +| Human-supplied/recorded observation | “Owner reports …”; “newcomer ran … and observed …” | Silently merging it with code-derived fact | +| Inference/unresolved edge | “These declarations suggest …”; “the receiver cannot be resolved” | A fabricated method link, provider identity, transaction outcome, or business rule | + +An `await` proves only that source awaits a call, not that external delivery succeeded. A `.save` call is a visible write attempt, not a committed write. A `commitTransaction` call is not a verified commit. A matched event publication/handler is a possible continuation, not proof of processing. + +## 3. Small internal model required to support the guide + +Build the smallest onboarding-specific intermediate representation that holds **path-aware claims** before rendering; do not create a generic whole-product graph framework. Keep core types framework-independent, scanners responsible for source findings, standards responsible for selection/explanation, renderers responsible for Markdown, and CLI responsible for orchestration. + +- **Location:** repository-relative path, line range, optional symbol, origin (`code`, `doc`, `test`, `person`, `observation`). Never read secret values into output. +- **Entry:** resolved route/handler, scheduled job, event/queue consumer, or an honest unknown starting point. Stable identity based on normalized route/symbol and source path, not raw line number alone. +- **Call edge:** caller symbol, call site, declared target if uniquely resolved, edge kind (`direct`, `declared target`, `candidate`, `unresolved`), and exact evidence. Constructor injection/module import is a declaration edge, never a call edge. A declared TypeScript method is not a guaranteed runtime override. +- **Path event:** read-like call, write-like call, assignment/status transition, guard, throw, return, catch/finally, external effect, publish/consume, or unsupported construct. Include branch context and source order **within that context**. Record `await` separately. Repeated calls to the same helper retain distinct call sites and calling contexts, even if its body is analyzed once. +- **Gap:** reason, first source location, affected journey and consequences for explanation. Include dynamic dispatch, alias uncertainty, unavailable dependency, recursion/depth/fan-out limit, unsupported control flow, and unverified runtime effect. +- **Journey:** entry plus ordered path segments, distinct branches/exits, cross-file continuation, related entities, tests, source claims, and gaps. No global flattened sequence across mutually exclusive branches. + +The tracer must not require a full control-flow theorem prover. Support common `if/else`, guard returns/throws, `try/catch/finally`, and simple call expressions; mark loops, switches, callbacks, dynamic dispatch, and complex expressions as bounded partial coverage unless implemented precisely. A limit stops traversal with a visible gap rather than silently dropping the rest. + +## 4. Ordered implementation slices and copy-ready Codex prompts + +**Handoff requirement:** Keep this file at `docs/ONBOARDING_DEEP_GUIDE_PLAN.md` in the local TransferKit checkout (or attach it to the Codex task and change the reference accordingly). The short prompts below are **not standalone specifications**. Codex must read the full product contract, internal model, slice deliverable/gate, and cross-cutting checklist before editing. If the file is unavailable, Codex should stop and ask for it rather than implement from a short prompt alone. Copying only one paragraph without the plan is insufficient. + +### Progress checklist + +Complete one slice and review its gate before starting the next. Check only a slice with a demonstrated passing gate; keep a failed or unrun gate open. + +- [x] Phase 1 — Acceptance contract and fixtures + - [x] Slice 0 — Lock acceptance contract and neutral fixtures +- [x] Phase 2 — Bounded, path-aware tracing (Slices 1–4) + - [x] Slice 1 — One bounded analysis context + - [x] Slice 2 — Path-aware trace representation + - [x] Slice 3 — Cross-file method continuation + - [x] Slice 4 — Local receiver aliases and transaction-like calls +- [x] Phase 3 — First deep guide and concepts (Slices 5–6) + - [x] Slice 5 — First deep journey in the guide + - [x] Slice 6 — Concepts and data effects +- [x] Phase 4 — Continuations, journey selection, and repository context (Slices 7–9) + - [x] Slice 7 — Continuations across jobs/events/queues + - [x] Slice 8 — Complementary journey selection and user focus + - [x] Slice 9 — Repository knowledge and orientation +- [x] Phase 5 — Setup, personal learning path, and reading experience (Slices 10–12) + - [x] Slice 10 — Practical setup and recorded observation + - [x] Slice 11 — Adaptive personal learning path + - [x] Slice 12 — Guide reading UX and regeneration +- [ ] Phase 6 — Regression and newcomer assessment (Slice 13) + - [ ] Slice 13 — Independent acceptance, regression, and release docs + - [x] Repeatable fixture and pinned application regression, with measurements and source spot checks + - [x] CLI/product documentation and unfamiliar-engineer protocol + - [ ] Real unfamiliar-engineer repository-only comparison and misleading-claim review + +The phase boxes summarize progress; the slice gates below control completion. Milestone 9 can close only after the repository-only guide and personal workspace pass their gates and a real unfamiliar engineer completes the repository-only assessment in Slice 13. Milestone 10 separately tests handover-assisted onboarding and broader real-world outcomes. If no engineer is available, record the assessment as pending and leave Milestone 9 open. + +Phase 2 gate evidence, including neutral negative cases, Madar/Debtbox excerpts, and measured budgets, is recorded in [the depth baseline follow-up](ONBOARDING_DEPTH_BASELINE.md#phase-2-structured-trace-review-2026-09-30). The structured trace is not rendered in the guide until Slice 5. + +Run one prompt at a time. Review the generated guide and acceptance evidence before the next. Each prompt is restricted to its item; do not let Codex pre-implement later slices. Codex should use the **current** checkout as truth, preserve unrelated changes, avoid commits, and report what it actually tested. If a slice's gate fails, fix that slice before moving forward. + +For **every** slice, the report back must include: (1) changed files and exact scope; (2) an actual generated or structured before/after excerpt, including a negative case; (3) tests and checks run with results; (4) measured performance when analysis changes; (5) unsupported patterns and remaining gaps; (6) whether the slice's gate passed. A test count or broad “works on Madar” statement alone is insufficient. Use neutral fixtures to prove generic behavior, then real repositories as regression checks. Do not copy private repository source or secrets into the public TransferKit fixtures. + +### Slice 0 — Lock the acceptance contract and fixtures + +**Deliverable:** Refresh onboarding design and Milestone 9 checklist to reflect the current implementation, the target output above, and the baseline/spike. Add or adapt neutral fixtures for branch exits, helper calls, aliases, transaction-like manager calls, and a cross-boundary continuation. Include a plain JavaScript/Node fixture with source entry point and documented run command, so overview usefulness is tested on more than a package-only fixture. Do not rewrite historical roadmap sections or mark real newcomer validation complete. Capture small golden assertions for *claims and citations*, not a huge whitespace snapshot. + +**Gate:** The docs no longer claim existing guide/workspace/sync functionality is merely planned; neutral fixtures encode both positive and negative claims; the plain Node fixture has discoverable source and documented setup; no onboarding production behavior changes. + +**Prompt 0** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially the product contract, final output, Slice 0 deliverable/gate, and cross-cutting checklist. Work only on onboarding design/acceptance. Read the current code, docs/ONBOARDING_V2.md, the canonical Milestone 9/10 roadmap sections, and docs/ONBOARDING_DEPTH_BASELINE.md before editing. Align the spec and only those roadmap sections with what is actually implemented; preserve historical ROADMAP content and all unrelated edits. Specify the standalone repository-only guide, connected journeys, concepts, change points, setup limits, precise questions, and separate personal progress. Add small neutral source fixtures/acceptance cases for if/else, early return/throw, repeated helper call, local manager alias, and publication/handler pair, with negative assertions against false sequential paths and invented effects. Add a plain JavaScript/Node source fixture with a documented run command and expected overview claims. Do not implement tracing/rendering yet, edit Handover, mark newcomer validation complete, or commit. Return changed-file list, acceptance cases and negative cases, checks, unresolved questions, and an explicit Slice 0 gate verdict. +``` + +### Slice 1 — One bounded analysis context + +**Deliverable:** Reuse the `ts-morph` Project that `scanRepository` already creates once per scan to resolve selected routes; avoid loading a second TypeScript Program or constructing a project per journey. Preserve source discovery fallback when imports/tsconfig/dependencies are absent. Exclude dependencies/generated code and bound loaded files/methods. Instrument elapsed time and peak RSS in a reproducible local benchmark, not permanent user-facing noise. + +**Gate:** Same method resolutions as the spike for a neutral fixture, Madar and Debtbox; missing dependencies do not crash the scan; multiple selected routes reuse the scan's existing Project. On the same machine, target no more than roughly 2× the baseline guide time and under 1 GiB peak for Madar; if missed, record where time/memory went and optimize before further expansion. These are an initial budget, not a universal promise. + +**Prompt 1** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 1 and its gate. Implement only bounded selected-entry resolution using the ts-morph Project already created once in scanRepository. Read the baseline report and isolated spike, then current scanner architecture. Do not load a second Program or add a dependency without measured benefit. Resolve declarations for more than one selected route through this shared context, with explicit file/method/depth/fan-out limits, exclusions, and safe fallback when tsconfig or app dependencies are missing. Do not render deeper guide prose or change Handover. Add focused tests for multi-route reuse and missing-dependency fallback. Measure one-route and multi-route time/RSS on disposable Debtbox/Madar snapshots, compare with the baseline, and report actual figures and any budget failure. Return changed files, before/after resolution, tests, unsupported cases, and an explicit gate verdict. No commit. +``` + +### Slice 2 — Path-aware trace representation + +**Deliverable:** Core trace/event types and scanner implementation for branch/exit-aware events. Keep called helper body separate from call-site context. Handle `if/else`, guard throw/return, `try/catch/finally`, source order, and unsupported constructs conservatively. Record call site and declaration as separate evidence. No generated prose yet. + +**Gate:** Fixture proves no event after a guaranteed return/throw is described as occurring on that path; mutually exclusive writes stay separate; repeated helper calls retain two edges; nested argument evaluation is not flattened into an unsupported order; budget/depth stops are visible. Tests include loops/switch as explicit gaps. + +**Prompt 2** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially the path-aware model, Slice 2 deliverable/gate, and cross-cutting checks. Implement the smallest path-aware onboarding trace representation, using the reusable analysis context. Include entry identity, call edges with call-site and declared-target evidence, path events with branch context, exits, and explicit gaps. Support common if/else, early return/throw, try/catch/finally, and direct calls. Do not merge exclusive branches into a straight-line story. Analyze a helper body once if useful, but preserve each invocation's call-site/branch context. Unsupported loops, switches, callbacks, or dynamic expressions must produce bounded gaps rather than disappear. Keep the model framework-independent and the scanner responsible for AST behavior. Add neutral positive/negative tests; do not change guide rendering or Handover. Return structured before/after trace including a negative path, tests, unsupported syntax, and explicit gate verdict. No commit. +``` + +### Slice 3 — Cross-file method continuation + +**Deliverable:** Follow uniquely resolved direct calls from a controller into injected concrete services, same-class helpers, and further local methods up to a bounded depth. Retain ambiguity on interfaces, dynamic dispatch, overrides, aliases, and unavailable bodies. Classify repository `get/find/save` names only as read-like/write-like when their target and/or call site supports that label; do not claim I/O happened. + +**Gate:** Madar selected route gains cited reads and guard branches; Debtbox fee helper is visible; the neutral interface/dynamic cases remain unresolved; no method-call edges from DI/module import alone; every followed edge has two locations. + +**Prompt 3** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 3 and its gate. Extend only onboarding's structured trace to follow bounded cross-file source method calls using TypeScript symbols: route handler to concrete injected provider, same-class helper, and further local method. Require an unambiguous declared target and retain both call-site and declaration evidence. Keep interface-typed, dynamic, inherited-without-body, external, and ambiguous targets as explicit gaps. Constructor injection and module imports are not calls; a declared target is not proof of runtime dispatch. Test neutral cases and compare the structured trace with Madar MobileFleetService.assignDriverToTruck and Debtbox DebtService.addDebt on disposable source snapshots. Do not yet synthesize a new guide layout or add AI/dependencies. Report new edges and any false edge. No commit. +``` + +### Slice 4 — Local receiver aliases and transaction-like calls + +**Deliverable:** Follow simple local provenance such as `const queryRunner = this.dataSource.createQueryRunner()` far enough to retain call sites for `queryRunner.manager.save`, `commitTransaction`, `rollbackTransaction`, and `release`. If the manager implementation cannot be resolved, mark these calls **write-like/transaction-like with unresolved target**. Do not infer atomicity, commit success, rollback success, or which branches executed. Other common local aliases may be supported only when proven by a neutral fixture. + +**Gate:** Madar's three conditional save call sites remain in their respective branch contexts and cite exact source; neutral fixture with a similarly shaped alias works; unrelated `.save` method is not mistaken for confirmed persistence. + +**Prompt 4** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 4 and its gate. Add narrowly proven local receiver provenance to the onboarding trace. Cover a local variable initialized by an injected object call and subsequent chained method calls, as in queryRunner.manager.save; classify visible calls conservatively when an external library body is unavailable. Keep conditional paths, await flags, catch/finally, commit/rollback/release calls and their source evidence separate. Never say a write committed or rollback succeeded. Test a neutral manager-alias fixture plus Madar's assignDriverToTruck; add a negative fixture where an unrelated object's save method must not be described as a database write. Do not touch Handover or write guide prose beyond what is required to expose the structured result. Report exact supported patterns and stop edges. No commit. +``` + +### Slice 5 — First deep journey in the guide + +**Deliverable:** Convert one selected structured trace into readable Markdown: entry, checks, path past checks, alternative paths, visible state/write attempts, external boundary, and exact gaps. Provide “where to change” links for relevant code and tests where discoverable. The candidate fallback must show the useful partial trace and first gap instead of hiding evidence behind an all-or-nothing explanation gate. Preserve guide markers, snapshots, human prose, and conflicts. Do not expand to many journeys yet. + +**Gate:** Madar fleet route is more useful than its former controller→service pointer; Debtbox creation remains accurate; empty Nest fixture stays a candidate; a stranger can verify every behavioral sentence at cited source. No fake completed assignment/transaction statement. + +**Prompt 5** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially the final output contract and Slice 5 gate. Render exactly one evidence-backed onboarding journey from the new structured trace into ONBOARDING.md. Prefer a selected route with meaningful paths; otherwise show the supported partial path and precise first gap. Include entry, guarded reads, mutually exclusive decisions, attempted writes/effects, error path, source references, and relevant change/test locations. Distinguish declaration, static call, unresolved target, and runtime outcome without repeating boilerplate in every line. Retain existing section IDs or provide safe anchor migration; preserve managed-guide snapshot reconciliation and human prose. Show fresh guide excerpts for Madar fleet assignment, Debtbox debt creation, and a neutral empty handler, and prove they contain no false sequence. Focused tests plus normal build/lint/format. No Handover/ROADMAP edits or commit. +``` + +### Slice 6 — Concepts and data effects + +**Deliverable:** A journey-linked glossary using supported TypeORM entities/columns/relations (and existing data-store findings). Map reads/writes to entities only when types or calls support it. Select concepts touched by featured journeys, show direct relations, and put full inventories in references. Do not equate an entity or field name with its business meaning. For non-TypeORM projects, describe the supported data shapes/store evidence or omit the glossary gracefully. + +**Gate:** Debtbox and Madar guides explain which records selected journeys touch; unrelated entities do not flood the first screen; neutral project with two entities and a relation is accurate; plain Node stays honest. + +**Prompt 6** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 6 and its gate. Add a curated Concepts section to onboarding, grounded in TypeORM entity declarations and actual selected-journey read/write references. Capture entity symbol, relevant fields/relations, and cited paths; show how concepts connect to the journey without inventing business definitions or database behavior. Do not list every entity in a large repo in the main section. Support a neutral two-entity fixture, inspect Debtbox and Madar generated excerpts, and keep graceful output for a project with no TypeORM. Preserve guide edits/anchors and do not touch Handover. Test evidence correctness and noise limits; report any relation syntax not supported. No commit. +``` + +### Slice 7 — Continuations across jobs/events/queues + +**Deliverable:** Match an observed publication/enqueue to a declared handler only where a concrete topic/job name, registration, and compatible evidence support the connection. Treat HTTP callbacks as separate entries unless a code-level identifier links them. Connect scheduled work to concepts it actually reads/changes; do not imply it ran because it is scheduled. Stop at ambiguous, dynamic, external, or framework-dependent edges. + +**Gate:** Neutral publisher/consumer fixture yields a labeled possible continuation; mismatched or dynamic topic yields no edge; selected Debtbox/Madar examples are connected only where supported; performance budget still holds. + +**Prompt 7** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 7 and its gate. Extend onboarding journeys only across demonstrable asynchronous declarations: enqueue/publish call and matching queue/event handler registration with concrete compatible identifiers. Cite both endpoints and label the link a possible continuation; never claim delivery, ordering across processes, or successful processing. Support one framework pattern actually present in the evaluated repositories plus a neutral fixture; do not build a generic plugin system. Keep scheduled jobs as separate entries unless source provides a defensible data/identifier link. Add negative tests for dynamic/mismatched topics. Show one connected and one deliberately unconnected generated example, with timing/RSS impact. No Handover edits or commit. +``` + +### Slice 8 — Complementary journey selection and user focus + +**Deliverable:** Deterministic selection that rewards source depth and *novel coverage* of entities, entry types, and boundaries, rather than names such as debt, consent, customer, or payment. Avoid picking near-duplicate CRUD routes when a distinct job or integration path teaches more. Allow an optional explicit `--focus` route/symbol selector after verifying current CLI conventions. Selection does not claim business criticality. Tiny repositories may have zero or one supported journey. + +**Gate:** Madar no longer shows only three shallow pointers when deeper eligible paths exist; Debtbox retains accurate creation/consent and can add a distinct journey when evidenced; a neutral non-payment fixture selects sensible paths; stable results across repeat scans. + +**Prompt 8** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 8 and its gate. Replace onboarding's fixed name-biased route selection with deterministic evidence-depth and complementarity selection. Choose a small set of distinct journeys that cover different supported entities/entry types/boundaries; scale the count with available evidence instead of hardcoding two explanations. Do not assign business importance from centrality or names. Add an optional user-selected --focus route/symbol only if it fits the existing CLI and can be resolved safely; keep default fully automatic. Test duplicate CRUD routes, distinct job/route paths, neutral names, sparse repos, stable tie-breaking and no Debtbox-specific terms. Show selected and rejected candidates with reasons on Madar, Debtbox, and neutral fixtures. No Handover changes or commit. +``` + +### Slice 9 — Repository knowledge and orientation + +**Deliverable:** Source-attributed project description if credible project documentation exists; relevant explanatory comments, tests, examples, and migration notes next to selected journeys. Comments are source statements, not verified truth. Do not indiscriminately mine every Git commit or copy huge README sections. Filter starter boilerplate, stale/contradictory statements, secrets, generated files, and irrelevant comments. Keep owner-written System context optional and intact. + +**Gate:** A neutral fixture with a useful handler comment and a generic starter README surfaces the former and does not present the latter as a bespoke product description; Madar's reconciliation comment is surfaced if that journey is selected, without claiming the comment's operational policy was verified; no unrelated context dump. + +**Prompt 9** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 9 and its gate. Enrich onboarding orientation and selected journeys with relevant checked-in text: a credible project description where present, a nearby explanatory source comment, related tests/examples, and specific migration notes where linked. Attribute each statement to its source; a comment or test is not runtime proof. Suppress obvious starter README boilerplate and unrelated text. Do not read or print secret values, scan all Git history, or invent product purpose. Preserve owner-written System context byte-for-byte. Test a neutral project with a real comment and starter README, then show concise excerpts on available Debtbox/Madar snapshots. No Handover edits or commit. +``` + +### Slice 10 — Practical setup and recorded observation + +**Deliverable:** Improve project-specific setup from README/package scripts, Compose, config examples, migration/seed declarations, and a declared health route. Build a proposed sequence and explicit blockers/contradictions. Do not run commands automatically. Permit personal workspace recording of attempted command, date, observed result, and blocker without claiming shared verification. Preserve optional owner-written verified setup and avoid secrets. + +**Gate:** Generic Nest starter commands are labeled generic/documented; Madar/Debtbox prerequisites and contradictions that are actually in the repository appear as questions; no app command runs during `guide`; an attempted observation is attributed to the person, not generated evidence. + +**Prompt 10** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 10 and its gate. Make onboarding's Run and observe section project-specific. Derive only declared services, env variable names (never values), package scripts, migrations/seeds, build prerequisites, and a possible health route from repository files. Distinguish documented steps, inferred ordering, missing prerequisites, and user-recorded observations. Improve the personal workspace so a newcomer can record exact commands attempted, date, result, and blocker in Markdown while preserving current sync/prose behavior; never automatically install, run migrations, start containers, or call an endpoint. Retain owner-written Verified local setup. Test a plain Node repo, a neutral Compose fixture, and available Debtbox/Madar outputs. No Handover edits or commit. +``` + +### Slice 11 — Adaptive personal learning path + +**Deliverable:** Replace the generic four-exercise content with tasks tied to the actual guide: map important concepts, explain two connected journeys where available, locate a hypothetical change point, record a safe observation or blocker, and answer or classify remaining questions. Keep separate shared knowledge and local personal state. Stable exercise identities must survive rescans; migration of existing four `v2:` IDs must be explicit and lossless, or keep them as stable umbrellas with guide-specific subgoals. If a journey disappears, retain work and flag a stale link. + +**Gate:** Existing checked boxes, notes, questions, evidence and legacy JSON remain intact; sync conflicts still protect both sides; tasks are meaningful in sparse and complex repos; self-reported completion is never a competence certification. + +**Prompt 11** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 11 and its gate. Align personal onboarding exercises with the new guide's actual concepts, selected journeys, setup and gaps. Before coding, document how the four existing v2 IDs and personal JSON/Markdown progress will migrate or remain stable; implement the smallest lossless strategy. Retain user prose, checkbox sync, conflict detection, legacy progress, and stale-link visibility when a guide changes. Do not infer competence from completion. Test rerun after journey selection changes, existing completed v2 tasks, personal notes and conflicting edits, plus sparse-repo behavior. Show a realistic personal workspace and plan/status output. No Handover edits or commit. +``` + +### Slice 12 — Guide reading UX and regeneration + +**Deliverable:** Final content order, compact orientation, journey-focused headings, readable tables or small Mermaid only where supported, collapsed citation/inventory appendix, stable anchors, and concise language. Generated claims remain reviewable; owner context/verified setup remain clearly human-supplied. Preserve old marked guide sections and snapshots through a defined upgrade/reconciliation path; unmarked guides are never overwritten. + +**Gate:** New guide is substantially easier to read without losing depth; generated claims can be verified at references; no human edit disappears on re-generation; stale snapshot/markers and conflicting edits fail safely; `guide` idempotent when source unchanged. + +**Prompt 12** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 12 and its gate. Polish only onboarding's shared Markdown reading experience after the deeper content exists. Order: Start here, system map, concepts, connected journeys, change points, Run and observe, specific questions, collapsed reference appendix. Use clear prose and compact source references; move long module/integration inventories out of the first screen without deleting their evidence. Add a small diagram only when every edge has supported meaning. Preserve existing owner sections, free-form human prose, managed markers, snapshot conflict handling, stable links and idempotent regeneration; define a safe upgrade for older marked guides and refuse unmarked ones. Test human edits, conflicting edits, changed findings and identical reruns. Show complete outputs from one small and one large fixture. No Handover/ROADMAP changes or commit. +``` + +### Slice 13 — Independent acceptance, regression, and release docs + +**Deliverable:** Repeatable fixture regression and a real unfamiliar-engineer assessment, first on repository-only onboarding. Evaluate whether they can explain main concepts, two connected behaviors where present, an alternate/failure path, and likely files for a small change; attempt setup or identify an exact blocker; list remaining questions. Compare with reading the repository without TransferKit. Inspect false statements manually against code. Record first-run time/memory and confidence limits. Update docs and Milestone 9 status only to the level demonstrated. Milestone 10 requires actual newcomer evidence, not Codex simulation. Optional v3 enrichment can be separately planned after repository-only acceptance. + +**Gate:** No material false call/branch/transaction assertions in the evaluated guides; an unfamiliar engineer can complete the tasks with fewer irrelevant searches/questions than baseline, and misleading claims are recorded and fixed before calling the work validated. If tests do not show improvement, keep the milestone open and investigate the failure. + +**Prompt 13** + +```text +Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially the newcomer protocol and Slice 13 gate. Perform onboarding-only acceptance and regression. Run the finalized guide/workspace on a small plain Node repo, a neutral Nest fixture, Debtbox, and Madar using disposable snapshots. Compare with docs/ONBOARDING_DEPTH_BASELINE.md: selected journeys, depth, false edges/claims, guide size/readability, time and peak memory. Manually spot-check each material assertion and source citation in selected journeys. Prepare a short unfamiliar-engineer task protocol comparing repository-only reading with TransferKit-assisted reading; run it with a real engineer only if one is actually available, otherwise label it pending and do not claim validation. Record task correctness, change-point identification, first local observation or blocker, remaining business questions, and misleading output. Update onboarding spec, CLI/README docs and only relevant Milestone 9/10 checklist statuses based on evidence. Preserve historical roadmap content; do not touch Handover or commit. Provide generated guide/workspace excerpts, measurements, failures, and exact outstanding acceptance gaps. +``` + +## 5. Cross-cutting acceptance checklist + +Apply after every slice that changes behavior: + +- **Truth:** Each generated behavioral claim is supported by cited code/doc/test/person/observation; no unqualified production outcome. No module-import → method-call conversion, no false provider identity, no sequential merge of exclusive branches. +- **Depth:** At least one selected journey on a meaningful repository goes beyond controller→service to decisions and data effects; later, complementary journeys explain distinct paths and supported continuations. +- **Graceful limits:** Empty handlers, missing tsconfig/dependencies, JavaScript/plain Node, dynamic dispatch, unsupported syntax, and sparse repos produce explicit partial coverage or omission, not invented detail or a crash. +- **Generic behavior:** Neutral fixtures must prove each pattern independently of Debtbox and Madar names; no hardcoded route/domain/provider terms. +- **Safety:** Guide generation is read-only with respect to the target application, never executes application code, and never emits env values/secrets. Generated Markdown and state reconciliation protect human work. +- **Stability:** Stable anchors/identities, deterministic selection, repeat generation, existing personal progress, and legacy behavior survive the changes. +- **Performance:** Measure the whole guide pipeline, not an isolated tracing process, on the same large repository/revision and machine; report RSS/time, number of loaded files and selected routes. Record a budget miss as a blocker, not a successful gate. +- **Human utility:** The final acceptance uses newcomer tasks and spot-checked code, not test count, line count, or an external rating alone. + +For subjective guide gates, use the [Slice 0 reviewer rubric](ONBOARDING_V2.md#slice-0-acceptance-cases): a reviewer must find a cited decision or explicit lack of one, an alternate exit where present, the first unsupported edge, and likely change/test locations within each selected journey. Check every substantive behavioral sentence against its cited source and keep broad inventories out of the opening section. Report the review result and any exception, rather than declaring a guide “more useful” from length or route count. + +### Newcomer evaluation protocol + +Recruit an engineer who has not worked on the evaluated repository. Give them the repository and a small, realistic hypothetical change or bug **without** providing a handover. Record the baseline with the repository's ordinary docs, then use a comparable task or another unfamiliar repository with TransferKit; do not imply the two conditions are perfectly controlled if the tasks differ. Avoid coaching during the timed portion. + +Use a short answer key prepared by someone who knows the source. Ask the engineer to (1) explain the key records and two distinct paths, (2) identify what happens on one alternate path, (3) point to the files/tests they would inspect for the change, (4) try a safe first observation or identify the exact setup blocker, and (5) list questions requiring a teammate. Score **correct/partly correct/unsupported**, record elapsed time and misleading guide claims, and compare the unanswered questions. A self-reported confidence rating can be collected but is not the acceptance measure. Keep any unresolved business question visible rather than treating it as a failure of code tracing. + +## 6. Decisions and stopping rules + +1. **No new dependency by default.** The TypeScript compiler API worked in the spike and `ts-morph` already exists in the project. Adopt another library only for a measured missing capability or significant maintainability gain. +2. **Do not build a universal call graph.** Trace a bounded set of selected entries, retain source evidence, and expose gaps. Whole-repository transitive tracing would amplify memory, noise, and incorrect paths. +3. **Do not add more journeys to hide shallow explanations.** If a selected journey cannot say what code checks or changes, inspect the failure edge first. Partial explanation is allowed when precisely bounded. +4. **Do not invent a business story.** Useful technical understanding is achievable from code; business intent is sourced from credible text/humans or remains a specific question. +5. **Keep optional v3 enrichment separate.** Once independent repository-only onboarding is validated, v3 items may add attributed business intent/ownership by stable ID without overriding code evidence or personal progress. That is a later slice, not a prerequisite or part of this implementation sequence. +6. **Pause at an accuracy/performance gate.** Correct the model or reduce scope before proceeding to prose polish. Preserve the baseline report, benchmark scripts, and generated examples as review evidence. diff --git a/docs/ONBOARDING_DEPTH_BASELINE.md b/docs/ONBOARDING_DEPTH_BASELINE.md new file mode 100644 index 0000000..d059666 --- /dev/null +++ b/docs/ONBOARDING_DEPTH_BASELINE.md @@ -0,0 +1,161 @@ +# Onboarding guide depth baseline + +Read-only static baseline, 2026-09-30. `tk onboard guide` was run from a fresh build of TransferKit `cb7c25e3e371db9d2e2cadb7a0053f573ed849d6` (`main`). All guides were generated in `/tmp/tk-onboarding-baseline.yc3560/` from fixture copies or `git archive HEAD` snapshots. No evaluated repository was modified; no application, dependency installation, container, or external service was run. Times are one local run each, so they are indicative rather than benchmarks. Peak RSS is macOS `wait4` child `ru_maxrss`. + +## Repositories and observed output + +| Source (revision; branch) | Snapshot size | Guide run; peak RSS | Selected output and what it teaches | +| --- | ---: | ---: | --- | +| `fixtures/project-detection/plain-node` (TransferKit revision above; `main`) | 1 file, 0 TS, about 4 KiB | 0.250 s; 132.3 MiB | No flow. Guide says no supported system components or routes and asks for setup evidence. Accurate for this package-only fixture, though even its Node package identity is absent from the overview. | +| `fixtures/realistic-nestjs` (same revision; `main`) | 22 files, 15 TS, about 88 KiB | 0.187 s; 135.7 MiB | Candidates: payment creation, payment recovery, debt creation; no explained flow. Teaches Nest modules, declarations, jobs, integration signals, and route locations. Its controller methods are empty (`src/payment/payment.controller.ts:8-15`, `src/debt/debt.controller.ts:8-12`), so an unresolved continuation is accurate. | +| `/Users/mac/source_control/debtbox-backend` (`e0267736a40a3181aae1c463782fe0f0436975c7`; `test-transferkit`) | 551 tracked files, 490 TS, about 3.5 MiB snapshot | 1.119 s; 288.7 MiB | Explains debt creation and consent; selects payment initiation as a candidate. Teaches route-to-service entry, direct guards, ordered saves, consent status branches, and attempted side effects, with open runtime questions. The guide does not establish an end-to-end payment-to-payout path. | +| `/Users/mac/source_control/b2c-backend` (Madar B2C; `79cc98e534a95a2a316c3464281619fb86a12d99`; `testing`) | 2,446 tracked files, 2,311 TS, about 16 MiB snapshot | 5.705 s; 607.3 MiB | Candidates: dashboard driver create/update and mobile fleet assign driver to truck; no explained flow. Teaches module and route locations, but no decisions, transaction writes, or failure boundaries for those paths. | + +Both Debtbox and Madar B2C were available locally. The Debtbox checkout has an unrelated deleted `.codex/config.toml` in its working tree; archiving `HEAD` excluded that local change. The separate `/Users/mac/source_control/madar` checkout also contains the fleet symbol, but this run used the `b2c-backend` checkout identified above. Snapshot size excludes installed dependencies and Git metadata. Generated guide sizes were 1,752, 4,641, 13,383, and 12,763 bytes in table order. + +## Current contract and depth limit + +The [onboarding design](ONBOARDING_V2.md) calls for a few evidence-labeled end-to-end flows with entry, decisions, persistence, side effects, and visible gaps. The [Debtbox fixture](ONBOARDING_V2_DEBTBOX_FIXTURE.md) is an illustrative target, not observed CLI output. Current code builds a repository-only guide from static findings, marks sections for safe regeneration, detects Nest routes/module relationships, and can explain two specially shaped traces ([guide orchestration](../packages/cli/src/generate-onboarding-guide.ts), [trace scanner](../packages/scanners/src/route-traces.ts), [explanation rules](../packages/standards/src/explained-flow.ts), [renderer](../packages/renderers/src/onboarding-guide.ts)). It labels runtime claims unverified and preserves explicit unknowns. The scanner enters exactly one directly called injected service method from a route; its method inspection records certain guards, `status/state/action` assignments, injected repository calls, selected service calls, and gaps. It does not continue through local helpers or into called methods, recognize a local `queryRunner.manager` alias as persistence, or model transaction boundaries. The explainer currently requires a narrow unconditional awaited repository `save` pattern or a specific two-status-branch pattern. The renderer selects at most three candidates and at most two explanations. + +| Entry point | Known continuation | Resolved by current output | First unresolved edge | Assessment | +| --- | --- | --- | --- | --- | +| Plain Node `package.json:1` | None in fixture | Setup questions only | Package identity does not appear in overview | Accurate but sparse. | +| Nest `PaymentController.createPayment` (`fixtures/realistic-nestjs/src/payment/payment.controller.ts:8`) | Empty handler | POST `/payments` route and module relationship | No call exists in handler | Accurate candidate, insufficient fixture evidence for a flow. | +| Debtbox `DebtController.addDebt` (`src/module/debt/debt.controller.ts:37,48`) | `DebtService.addDebt` (`src/module/debt/debt.service.ts:100`) | Guards, three separate awaited saves, audit call, conditional push attempt | `DebtService.applyExpectedFeeSnapshot` at `debt.service.ts:155` is a local helper explicitly left untraced; notification language call is nested at `:213` | Useful partial trace; no claim of delivery or atomicity. | +| Debtbox `DebtController.consentDebt` (`src/module/debt/debt.controller.ts:54,78`) | `DebtService.consentDebt` (`src/module/debt/debt.service.ts:267`) | Consent save, accepted/rejected branches, upload attempt, Sanad and gateway calls | `SanadsService.ensureGeneratedForDebt` at `debt.service.ts:331` is named but its implementation and downstream effects are not traced | Accurate within cited method; deeper effects and outcomes remain open. | +| Debtbox `PaymentController` checkout (`src/module/payment/payment.controller.ts:16,27`) | `PaymentService.initiatePayment` (`src/module/payment/payment.service.ts:65`) | Route and direct service method only in selected guide; scanner can see direct calls | `PaymentService.getPayableGroupDebts` at `payment.service.ts:82` is a local helper; conditional saves at `:123,160,167,179` do not meet the linear explanation rule | Candidate label is accurate, but misses payment decisions and checkout attempt. | +| Madar `MobileFleetController.assignDriverToTruck` (`src/module/fleet/controllers/mobile-fleet.controller.ts:114,125-130`) | `MobileFleetService.assignDriverToTruck` (`src/module/fleet/services/mobile-fleet.service.ts:585`) | Route and direct method name only | `this.dataSource.createQueryRunner()` at `:597` produces a local `queryRunner`; `queryRunner.connect/startTransaction` and `queryRunner.manager.save` are outside the injected-call matcher | Accurate candidate label, but too shallow to teach this selected flow; treating it as an explained successful assignment would be misleading. | + +Madar's method statically shows a transaction setup at `mobile-fleet.service.ts:597-599`; fleet/truck/driver repository reads and ownership guards at `:602-615`; running-shipment checks at `:617-626`; branches that may unassign the driver's prior truck (`:629-645`) and the truck's prior driver (`:647-667`); a conditional assignment (`:669-673`); and commit, rollback, and release calls at `:675,682-690`. The referenced repository methods exist: `FleetRepository.getFleetById` (`src/module/data/repository/fleet.repository.ts:698`), `TruckRepository.getTruckById` (`truck.repository.ts:569`), `DriverRepository.getDriverById` (`driver.repository.ts:77`), and `ShipmentRepository.getRunningShipmentByTruckId/getRunningShipmentByDriverId` (`shipment.repository.ts:13337,13378`). These are next statically resolvable calls and branches, not observed runtime outcomes. The scanner can record the injected repository call sites, but the explainer drops this trace because its linear rule requires an unconditional awaited injected repository `save` ([rule](../packages/standards/src/explained-flow.ts)); the only saves here are via `queryRunner.manager`. The candidate renderer then shows only route/method references, hiding the detected guards and unresolved transaction edge. + +## Diagnosis and next tracing spike + +- **Scanner defects/limits:** Local receiver aliases and transaction manager calls disappear (`queryRunner` in Madar); local helpers and injected call bodies stop at their call sites (Debtbox fee snapshot, payment group lookup, Sanad generation). A bounded, evidence-bearing continuation should distinguish resolved source calls from external/library calls and stop on unsupported edges. +- **Insufficient evidence:** The plain Node fixture has no source, the Nest fixture has empty handlers, and no static scan proves runtime state, delivery, rollback, or recovery. These are explicit unknowns, not missing runtime conclusions. +- **Selection defects:** Madar's three highest-scoring candidates have zero explanations; Debtbox payment initiation is left as a candidate despite substantive source, while the guide cannot connect it to the scheduled payout path (`src/module/payment/payout-scheduler.service.ts:20`). Ranking favors route names and local operation counts rather than demonstrated learning depth ([selection](../packages/renderers/src/onboarding-guide.ts)). +- **Rendering defects:** Madar's root-import line lists roughly a hundred modules, obscuring entry points. Candidate rows disclose a direct method but neither the scanner's partial guard/read evidence nor the first unresolved edge. The `Debtbox` guide is stronger: its steps and uncertainty labels are sufficient for locating creation/consent guards, ordered saves, and attempted side effects; deeper tracing would improve the fee helper, consent-to-Sanad path, payment checkout and later payout, not invalidate those direct-call claims. + +Acceptance examples for the next spike (static claims only): + +1. **Neutral fixture:** Extend `OrderController.create` → `OrderService.create` in `packages/scanners/src/route-traces.test.ts:16-40` with a same-file helper or a second injected service method containing a visible guard/call. The guide should cite the continuation and its stop edge, while still labeling the existing indirect and dynamic calls at `:25-27` unresolved. +2. **Madar transaction:** `MobileFleetController.assignDriverToTruck` → `MobileFleetService.assignDriverToTruck` (`src/module/fleet/controllers/mobile-fleet.controller.ts:125-130`; `src/module/fleet/services/mobile-fleet.service.ts:585-690`) should expose the five initial reads/guards, three conditional manager saves, and commit/rollback/release branches with source references. It must not assert that any branch ran or that rollback succeeded. +3. **Debtbox creation:** `DebtService.addDebt` (`src/module/debt/debt.service.ts:100,155-199,208-228`) should continue through `applyExpectedFeeSnapshot` with bounded depth, preserve the separate save and caught push distinctions, and leave external delivery unresolved. +4. **Debtbox payment:** `PaymentService.initiatePayment` (`src/module/payment/payment.service.ts:65,82,103-179`) should show the early return versus checkout creation branches and the HyperPay call after recorded transaction data; payout remains a separate scheduled entry until a supported code link is established. + +No newcomer validation was performed. + +## Focused symbol-aware tracing spike (2026-09-30) + +The isolated [prototype](../experiments/onboarding-trace-spike.mjs) uses the installed TypeScript 5.9.3 compiler API and the target repository's `tsconfig.json` options. It creates a `Program` rooted at the requested controller file, follows imports, and uses `TypeChecker` method symbols. It does not feed guide generation. The [neutral Nest fixture](../experiments/fixtures/nest-trace/controller.ts) and [focused tests](../experiments/onboarding-trace-spike.test.mjs) cover a route call, same-class helper, cross-file injected providers, exclusive `if/else` branches, a catch, status assignments, a dynamic call, an interface-typed provider, and an unsupported project function. Each followed edge contains a call-site `file:line` and the declared target's symbol and `file:line`. “Declared target” means a statically selected declaration, not a guarantee of runtime dispatch. + +### Madar before and after + +**Before:** the generated guide stops at `POST /v0.0.1/api/mobile-fleet/assign-driver-to-truck` → `MobileFleetController.assignDriverToTruck` → `MobileFleetService.assignDriverToTruck` (`src/module/fleet/controllers/mobile-fleet.controller.ts:114,130`; `src/module/fleet/services/mobile-fleet.service.ts:585`). It offers no explained steps. + +**Prototype, cited static path:** + +1. The handler's call at `mobile-fleet.controller.ts:130` resolves to `MobileFleetService.assignDriverToTruck` at `mobile-fleet.service.ts:585`. Constructor injection itself creates no call edge. +2. The service calls declared `FleetRepository.getFleetById` (`mobile-fleet.service.ts:602` → `src/module/data/repository/fleet.repository.ts:698`), `TruckRepository.getTruckById` (`:607` → `truck.repository.ts:569`), and `DriverRepository.getDriverById` (`:612` → `driver.repository.ts:77`). Each call is followed by a visible missing-record/ownership throw branch at `:603-615`. +3. It calls declared `ShipmentRepository.getRunningShipmentByTruckId` (`:618` → `shipment.repository.ts:13337`) and `getRunningShipmentByDriverId` (`:624` → `shipment.repository.ts:13378`), with separate throw branches at `:619-626`. Those repository methods call same-class plural helpers at `shipment.repository.ts:13339,13380`; the depth-two prototype cites those edges but does not follow them further. +4. Under `driver.truck && driver.truck.id !== truckId` (`mobile-fleet.service.ts:630`), it checks the former truck's shipment at `:632`, may throw at `:633-639`, sets `driver.truck = null` at `:643`, and calls `queryRunner.manager.save(driver)` at `:644`. The second branch (`:648-667`) checks the truck's previous driver and may clear/save it. A third branch (`:670-673`) may assign/save the requested truck. The conditions are kept separate; the prototype does not claim all branches execute. +5. Calls to `queryRunner.commitTransaction`, `rollbackTransaction`, and `release` appear at `:675,683,690`; the latter two are in catch/finally. These are cited calls, not proof of a committed or rolled-back outcome. + +**First remaining gap:** `this.dataSource.createQueryRunner()` at `mobile-fleet.service.ts:597` has no source method body in the dependency-free snapshot. The subsequent `queryRunner` receiver is a local alias, so `connect`, `startTransaction`, the three `manager.save` calls, commit, rollback, and release remain unresolved method targets. The prototype labels each `save` a **write-like call with unresolved target**; it does not claim a database write occurred. `FleetRepository.getFleetById` and two other repository reads place their query bodies inside `new Promise(async ...)` callbacks (`fleet.repository.ts:699`, `truck.repository.ts:570`, `driver.repository.ts:78`), which this bounded prototype explicitly leaves untraced. + +### Debtbox comparison and precision + +The existing guide already explains `DebtController.addDebt` → `DebtService.addDebt` (`src/module/debt/debt.controller.ts:48`; `src/module/debt/debt.service.ts:100`). The prototype also resolves `DebtService.validateDebtCreationAmount` (`debt.service.ts:102` → `:242`) and its three throw guards (`:243-250`), plus the previously untraced `DebtService.applyExpectedFeeSnapshot` (`:155` → `:254`) and its fee-field assignments (`:256-264`). It resolves the nested notification-language call at `:213` to `NotificationService.resolveNotificationLanguage` (`src/module/notification/notification.service.ts:95`) and labels it a nested argument, without inventing call order. Existing direct observations remain: awaited save call sites at `debt.service.ts:156,178,199` and a conditional Firebase attempt at `:215`; their outcomes stay unverified. The first unresolved edge on the fee-helper continuation is `computeExpectedDebtFeeSnapshot` at `:255` (project free function outside this prototype's method-call scope); the first unresolved save target on the main path is inherited `DebtRepository.save` at `:156` because TypeORM is absent. + +No false method-call edge from a module import or constructor injection appeared in the neutral fixture or either repository trace. Precision limits still matter: a TypeScript method symbol identifies a *declared* target, not necessarily a runtime override; a repository `get*` or `save` name is only a read-like/write-like call, not proof of I/O; nested argument calls must not be flattened into separate sequential steps. The prototype marks dynamic `this.notifications[method]` and interface-typed `Dispatcher.send` unresolved in the fixture, and stops at unsupported project free functions, callbacks, aliases, and depth limits. Its branch labels preserve `when`, `else`, `catch`, and `finally` rather than joining mutually exclusive paths. + +| Same disposable snapshot | Existing full `tk onboard guide` | Isolated route trace, depth 2 | Loaded project TS files | +| --- | ---: | ---: | ---: | +| Madar B2C | 5.705 s; 607.3 MiB peak RSS | 2.576 s; 497.3 MiB peak RSS | 1,481 of 2,311 snapshot TS files | +| Debtbox | 1.119 s; 288.7 MiB peak RSS | 0.843 s; 279.6 MiB peak RSS | 192 of 490 snapshot TS files | + +These are separate single-process runs on the same machine and snapshots; the trace is **additional work**, not a faster replacement for guide generation. A preceding route-scoped Madar run took 2.514 s and 554.1 MiB, indicating memory variability. Loading all tsconfig files instead took 3.872 s and 723.9 MiB in one Madar run. The Madar tsconfig has a `@test/*` alias and excludes tests; Debtbox has an `@app/*` alias. Both configurations allowed the requested relative-import method edges. Missing app dependencies produced compiler diagnostics (`@nestjs/common`, TypeORM, and others), but source method resolution still worked where imports were local. External API bodies, inherited TypeORM saves, and query-builder behavior cannot be verified from these dependency-free copies. The full Madar import graph remains sizable even with one route as the root. + +**Recommendation: narrow scope before integration.** The TypeScript compiler API suffices for this spike: it resolved the cross-file edges and explicit limits without another dependency. `ts-morph` is already used by the current scanner, but its wrapper is not justified for this isolated technique; no dependency was added. A production follow-up should first constrain tracing to selected routes, bound method depth and fan-out, carry branch context and call-site/target evidence, and render unresolved aliases and external methods plainly. Do not merge this prototype into `tk onboard guide` until those precision rules and the memory cost are evaluated against more routes. + +## Phase 2 structured trace review (2026-09-30) + +The production scanner now has a separate, onboarding-only `scanOnboardingRepository` entry point. It runs existing discovery and `analyzeOnboardingRoutes` with one shared `ts-morph` Project, without loading a second Program. The structured trace is not yet connected to guide prose; that is Slice 5. Existing Handover scan results remain unchanged. The neutral fixture has no tsconfig or installed Nest dependencies, yet resolves two selected route-to-service calls. It tests branch exits, two helper call sites, nested arguments, missing bodies, inherited/interface/dynamic targets, loops/switches, and the local query-runner alias. Analysis caps entries, project file count, followed files, methods, depth, calls per method, and live paths with visible gaps. + +**Before/after structured excerpt:** The existing Madar guide stops at `MobileFleetController.assignDriverToTruck` → `MobileFleetService.assignDriverToTruck` and leaves it a candidate. The new trace cites the controller call and declared service method, then resolves the five initial repository reads. It records awaited, write-like but unresolved `queryRunner.manager.save` call sites at `mobile-fleet.service.ts:644`, `:665`, and `:672` under distinct source conditions. The last is under `!truck.driver || truck.driver.id !== driverId`; the earlier two concern the previous truck and previous driver. Commit, rollback, and release are transaction-like *calls*, with no assertion that a transaction succeeded. Debtbox `DebtService.applyExpectedFeeSnapshot`, `NotificationService.resolveNotificationLanguage` (as a nested argument), and `SanadsService.ensureGeneratedForDebt` now have cited declared-target edges. No constructor injection or module import is emitted as a call. + +**Negative cases:** The neutral invalid-order throw exits before any read/write/queue event on that path. Priority and standard assignments remain separate, while repeated `recordAttempt` calls retain two call sites. `CacheSnapshot.save` is an ordinary call, not a database write. An interface-typed dispatcher, inherited method, dynamic element call, callback body, loop, and switch remain unresolved or explicit gaps. The alias fixture's manager `save` is labeled write-like with an unresolved target, never a completed write. Source literals are replaced in event detail and path labels before a trace can reach a renderer. + +The benchmark script runs the combined scan and trace, then model, explanation, and Markdown rendering with one Project. It does not write the guide or measure snapshot reconciliation. Figures below are single local runs on the baseline `git archive` snapshots; peak RSS is `process.resourceUsage().maxRSS` normalized for macOS. Normal `tk onboard guide` also completed on both disposable snapshots without changing its output contract. + +| Snapshot and selected routes | Baseline full guide | Phase 2 scan/render plus trace | Loaded TS files | Gate | +| --- | ---: | ---: | ---: | --- | +| Madar `79cc98e` — fleet assignment, dashboard driver create/update | 5.705 s; 607.3 MiB | 5.603 s; 702.3 MiB | 2,311 | Under 2× baseline time and 1 GiB | +| Debtbox `e026773` — debt create/consent | 1.119 s; 288.7 MiB | 1.197 s; 310.2 MiB | 490 | Under 2× baseline time and 1 GiB | + +The scanner still loads all repository TypeScript files for its existing discovery pass; the new tracer follows at most 30 files by default and skips tracing with a visible gap above its 5,000-project-file budget. These are local budgets, not universal performance promises. Dynamic dispatch, callbacks, complex expressions, loops, switches, external library bodies, and runtime transaction outcomes remain open for a person or later capability. At this Phase 2 checkpoint, the guide remained shallow until Slice 5 consumed the structured trace. + +## Phase 3 guide and concepts review (2026-10-01) + +`tk onboard guide` now uses the structured trace from the same scanner Project. It selects one source journey from the current candidate routes, preserves the `explained-flow` section ID, and inserts the new `concepts` section before it when upgrading a marked guide. Source locations in these sections link to repository files. The guide labels calls and write/transaction attempts without asserting that a database write, commit, rollback, queue delivery, or assignment succeeded. Existing human prose and snapshot conflict handling remain in place. No target application was run. + +| Disposable snapshot | Source journey | Curated concepts in main section | Fresh guide run and peak RSS | Guide size | +| --- | --- | --- | ---: | ---: | +| Debtbox `e026773` | `DebtController.addDebt` | Notification, Debt, DebtConsent, Business, Customer | 1.054 s; 311.6 MiB | 32,203 bytes | +| Madar B2C `79cc98e` | `MobileFleetController.assignDriverToTruck` | Shipment, Driver, Fleet, Truck | 5.881 s; 705.5 MiB | 29,656 bytes | + +These are single fresh runs of full guide generation on the same archived revisions as the baseline, including write and snapshot creation. Both stay below twice the baseline time and 1 GiB peak RSS. Memory varies by run. The longer guide is a readability cost to assess in later slices. + +**Madar source check:** `MobileFleetService.assignDriverToTruck` shows the fleet, truck, driver, and running-shipment calls at `mobile-fleet.service.ts:602-625`, then three distinct conditional `queryRunner.manager.save` attempts at `:644`, `:665`, and `:672`. The guide labels `commitTransaction` at `:675`, catch `rollbackTransaction` at `:683`, and `release` at `:690` as unresolved transaction-like calls. It makes no completed assignment or atomicity claim. The data glossary links Shipment, Driver, Fleet, and Truck to declared TypeORM entities and direct relations; the manager save argument is not assigned to a specific entity because the trace does not retain enough type evidence for that claim. + +**Debtbox source check:** The debt creation journey shows merchant/customer/business checks, three separate awaited repository save attempts at `debt.service.ts:156`, `:178`, and `:199`, and a conditional non-awaited notification save call at `:223`. Debt, DebtConsent, and Notification appear through typed repository bindings; Customer and Business appear through custom repository method return types. `DebtRepository.findOrCreateDebtGroup` is linked to its declared `DebtGroup` return, not to the repository's `Debt` base type. Other touched declarations are collapsed below the five main concepts. None of these calls proves persistence or delivery. + +**Neutral and sparse checks:** The two-entity fixture shows OrderEntity's declared `ManyToOne` AccountEntity relation and its inverse `OneToMany` declaration, while stating that AccountEntity has no linked journey call. The invalid-input throw stays separate from write/queue attempts, priority branches stay separate, and `CacheSnapshot.save` is not labeled as persistence. The empty Nest handler remains a candidate, and the plain Node fixture has no TypeORM glossary. Focused tests cover these cases, source links, and insertion of Concepts into an older marked guide with human text intact. + +The supported entity syntax is an imported TypeORM `@Entity` decorator, imported column decorators, and direct relation decorators whose first argument is an arrow such as `() => Target`. Repository links require a typed `Repository` base or matching `@InjectRepository(Entity)` parameter plus a declared entity return type for custom methods. String relation targets, dynamic targets, complex return types, and query-runner save argument types are not mapped. No related tests were established by the selected traces in these two snapshots; the guide says so instead of inventing test links. Real newcomer assessment remains pending for Slice 13. + +## Phase 4, Slice 7 continuation review (2026-10-01) + +The onboarding-only scanner recognizes one observed framework pattern: `@nestjs/bullmq` `@InjectQueue(queue)` on a typed `bullmq` Queue, a literal `queue.add(jobName, ...)` in a traced method, and a unique `@Processor(queue)` class extending `WorkerHost` with a `process` body. A shared queue literal or a single resolved `Constants.X` property with a literal fallback supports a **possible continuation**. The guide cites producer call, injection, processor registration, and body. It does not claim enqueue, delivery, order, or handler success. Dynamic job names are omitted; a different queue or multiple handlers remains unconnected. RabbitMQ consumers, HTTP callbacks, and other Bull patterns are not joined by this matcher. + +The neutral `ParcelController.dispatch` guide links `ParcelService.dispatch` at `service.ts:14` to `ParcelProcessor.process` at `worker.ts:3,5` for queue `parcel-jobs` and literal job `assign-parcel`. It separately reports `archive-parcel` on `other-jobs` as unconnected; a dynamic job name receives no edge. `ParcelJobs.inspect` at `scheduled.ts:7,9` is shown as a declared schedule with a direct call linked to the Parcel entity. No scheduled run is inferred. + +In Madar, `ShipmentService.bulkAssignShipment` calls `bulkAssignShipmentQueue.add('assignShipment', ...)` at `shipment.service.ts:2324` with `@InjectQueue(Constants.BULK_ASSIGN_B2B_QUEUE)` at `:383`. `BulkAssignShipmentProcessor` registers that same resolved queue expression at `bulk-assign.processor.ts:8` and declares `process` at `:25`. An explicit trace of `ShipmentController.assignBulkShipment` produced that possible link. The default featured fleet route has no queue publication, so its generated guide correctly shows no connected worker. Debtbox has no supported BullMQ publication/handler pair in this snapshot; no queue edge was invented. + +A fresh whole-guide Madar run after Slice 7 took **6.426 s and 662.3 MiB peak RSS**, with no queue link or scheduled concept link on the default fleet journey. This is below twice the 5.705 s baseline and below 1 GiB. Scheduled concept links require direct calls from a declared Nest scheduled handler through typed repository evidence and are shown only when they touch a featured entity; callbacks and helper effects remain open. + +## Phase 4, Slices 8–9 selection and repository context (2026-10-01) + +The guide now preselects a bounded set of route and scheduled entries using source signals, then chooses up to four traced journeys by method depth, decisions, effects, linked entity declarations, queue continuations, and novel coverage. Near-duplicate paths sharing most traced methods and the same concepts are rejected. The selection reason states source coverage, not business importance. `tk onboard guide --focus Class.method` (or an unambiguous declared route/path) makes one supported entry the first featured journey. Unknown or ambiguous focus fails before writing a guide. A bodyless route remains a candidate. Neutral tests show one of two duplicate Order routes plus a distinct Limits route, and a Parcel route plus scheduled handler; repeat fresh scans produce identical Markdown. + +| Fresh disposable guide run | Featured source journeys | Example rejected candidate | Time; peak RSS | Guide size | +| --- | --- | --- | ---: | ---: | +| Debtbox `e026773` | `PaymentController.getPaymentStatus`, `DebtController.addDebt`, `CustomerEmailVerificationController.verifyEmail`, `DebtController.consentDebt` | `AdminController.verifyMfa` (less novel within the guide limit) | 1.353 s; 298.0 MiB | 86,611 bytes | +| Madar B2C `79cc98e` | `MobileFleetController.assignFleetToShipment`, `IntegrationsController.webhook`, `MobileShipmentController.confirmPickup`, `InvoiceController.updateInvoice` | `MobileFleetController.assignDriverToTruck` (overlapping coverage; available with `--focus`) | 6.230 s; 654.9 MiB | 95,722 bytes | + +These are whole CLI runs after a fresh build, on the archived revisions used above, with macOS child `ru_maxrss`. Both meet the Slice 0 ceiling of twice baseline time and 1 GiB. They are single runs, not stable benchmarks. The selection demonstrates deeper decision/effect paths and multiple distinct entry areas; the larger guide size is a known reading cost reserved for Slice 12. A focused Madar reconciliation guide selected `ShipmentController.triggerB2cPricingReconciliationRun`, cited the nearby `B2cPricingReconciliationService.runReconciliation` source comment at `b2c-pricing-reconciliation.service.ts:78`, and listed its sibling `.spec.ts` as a test candidate. The comment's lock/status explanation is explicitly a source statement, not a verified runtime policy. + +Repository context is bounded to a short README description, comments beside selected method declarations or within their bodies, sibling test files, and migration file names matching selected source owners. Generic Nest starter descriptions, commented-out code, secret-like comments, unrelated text, and long README sections are suppressed. A neutral fixture with a generic starter README displays its explanatory handler comment but no project description; a separate bespoke README test shows a cited description. Debtbox and Madar's generic README opening paragraphs are omitted. Sibling tests are labeled candidates because their assertions are not analyzed. No Git history, application command, or env file was read by this enrichment path. Owner-authored guide text remains under the existing snapshot merge and conflict rules; focused tests checked preservation on regeneration. + +Manual spot checks covered the selected entry/call locations and representative decision, write-like, queue, and comment citations in the generated neutral, Debtbox, and Madar guides. No unsupported runtime completion claim was found in those checks. This is not the independent, every-claim review or unfamiliar-engineer assessment required by Slice 13. + +## Phase 5, Slice 10 setup review (2026-10-01) + +The guide now lists declared package build/start/test/migration/seed scripts separately from README commands, labels generic starter README commands, names Compose services and their declared dependencies, shows only variable **names** from checked-in templates and source, cites migration declarations and a possible GET health route, and offers a proposed order explicitly labeled inferred. It asks before migrations or seeds are run. The personal workspace includes a dated command/result/blocker table; sync preserved an entered observation as personal text. A test with a side-effecting declared start script confirmed `guide` did not execute it. + +The neutral Compose fixture showed `.env.local` as a required file, a `4010:3000` mapping versus a `4000` source listen fallback as a question, a declared `/health` route, and migration/seed questions. The plain Node fixture showed its package start script without inventing services. Debtbox showed a required `.env`, a present mounted `db/init.sql`, and its `3000` mapped port versus `5000` source fallback as a question. Madar showed its Compose `.env` requirement; no claim was made that the file or any service was available. No target application, migration, container, endpoint, or test command was run in these guide checks. + +### Slice 11 progress strategy, before implementation + +Keep the four existing `v2:` exercise IDs and their JSON schema/status/snapshot unchanged. Treat them as stable umbrellas for concept mapping, source journeys, a local observation, and change-point/questions work. Generate guide-specific subgoals only in a **new** personal workspace. Never rewrite an existing personal Markdown file during guide regeneration or plan/status, so completed boxes, notes, evidence, questions, and legacy JSON remain byte-for-byte intact. A new workspace records its selected journey symbols as local guide-link markers; plan/status compares those markers with the current guide and flags disappeared journeys without deleting the user's work. Older workspaces without markers remain valid, and no migration is needed. Self-reported completion remains separate from source-backed understanding. + +### Slice 11 result + +A fresh neutral Parcel workspace asks for a cited Parcel concept map, an explanation of `ParcelController.dispatch` and `ParcelJobs.inspect` including alternate exits and unsupported edges, an actual local observation or blocker, and a likely change/test point plus classified questions. `tk onboard plan` shows those guide-specific objectives; `status` retains self-reported progress. In a changed-guide test, the shared guide dropped `ParcelJobs.inspect`: status flagged its stale local link while the completed `v2:trace-flow` checkbox, JSON status, and personal notes remained unchanged. Existing sync conflict, legacy progress, sparse-guide, and four-ID tests passed. No completion status is interpreted as verified competence. + +### Slice 12 reading and regeneration review + +The complete small neutral guide is at `/tmp/tk-p5-small-cbDkiY/ONBOARDING.md` (8,115 bytes), and the complete large Madar guide is at `/tmp/tk-p5-madar-ooSzOe/ONBOARDING.md` (about 100 KiB). The large guide now starts with 6 lines of orientation and a short system map: bootstrap, technology, root module, store, and four declared route-to-service call targets with source links. Its former very long root-import and job/integration lists are in the collapsed reference appendix. The reading order is Start here → System map → Concepts → Connected journeys → Change points → Run and observe → Specific questions → Reference appendix. No unsupported diagram was added. The full journey detail and gaps remain in Connected journeys; 359 large-guide source links and 337 Debtbox source links resolved to existing files and in-range lines in the archived snapshots. + +Stable managed IDs `system-overview`, `explained-flow`, `setup-and-operations`, and `unknowns` remain behind the renamed headings, with explicit anchors for existing workspace links. Journey anchors derive from source symbols. Regeneration tests covered identical reruns, changed findings, old marked heading upgrades, independent owner-written System context and Verified local setup, conflicting human edits, missing/malformed snapshots or markers, and refusal to overwrite an unmarked guide. A human-edited managed section still requires conflict resolution when its generated content also changes; it is not silently discarded. The appendix preserves prior inventories and candidate routes under a collapsed details block. + +Final fresh whole-guide runs on the same archived revisions took **1.358 s / 298.9 MiB** for Debtbox and **6.396 s / 694.6 MiB** for Madar, below the twice-baseline time and 1 GiB limits. The scanner loaded 490 and 2,311 TypeScript files respectively and traced 18 and 19 candidate entries before featuring four journeys in each guide. The larger full guide remains a reading cost, but its first screen is short; independent newcomer usefulness and a comprehensive statement-by-statement accuracy assessment remain for Slice 13. diff --git a/docs/ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md b/docs/ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md new file mode 100644 index 0000000..27cc572 --- /dev/null +++ b/docs/ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md @@ -0,0 +1,118 @@ +# Human-first onboarding — Phase 0 acceptance baseline + +**2026-10-03.** This is a local planning and evaluation artifact. It locks the examples and answer keys for the [human-first plan](ONBOARDING_HUMAN_STORY_PLAN.md); it does not certify the current guide or close Milestone 9. The generated guides were made in disposable copies and are reproducible with: + +```text +npm run build +python3 experiments/onboarding-phase6-regression.py \ + --out /tmp/ \ + --debtbox /path/to/debtbox-backend \ + --madar /path/to/b2c-backend +``` + +This run used TransferKit HEAD `cb7c25e3e371` **with existing uncommitted onboarding changes**; the built CLI bundle SHA-256 was `379501c91fc9a921ac4455224aa6b57c1a8c06d2bf79f3e809021fa34fd348ad`. Debtbox was archived at `e0267736a40a3181aae1c463782fe0f0436975c7`; B2C at `79cc98e534a95a2a316c3464281619fb86a12d99`. No evaluated application, dependency installer, container, migration, or endpoint was run. The results and complete generated Markdown from this run are in `/tmp/tk-human-phase0-20261003-verified/`; the script can recreate them if temporary files are removed. + +## Baseline measurements + +“Opening words” counts the generated **Start here + System map** text after removing markup and link targets. Time is one local first run of `tk onboard guide`; peak RSS is macOS `wait4` child `ru_maxrss`. These are indicators, not performance benchmarks. All checked Markdown source links resolve to a file and line in their disposable snapshot; that check does not prove the sentence is true. + +| Case | Guide bytes | Opening words | Featured source journeys | Guide time | Peak RSS | Source links / broken | Guide SHA-256 prefix | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | +| Plain Node app | 2,985 | 82 | 0 | 0.151 s | 134.0 MiB | 2 / 0 | `6187bd05d292` | +| Nest queue + scheduled worker | 8,101 | 76 | 2 | 0.310 s | 187.2 MiB | 42 / 0 | `f46b829ae799` | +| Branch/transaction negative fixture | 10,824 | 79 | 2 | 0.321 s | 194.3 MiB | 70 / 0 | `33c5e769b38a` | +| Non-Nest Event Count CLI | 2,999 | 86 | 0 | 0.148 s | 115.0 MiB | 2 / 0 | `9f7e0ad88deb` | +| Sparse Python CSV utility | 2,845 | 71 | 0 | 0.150 s | 123.3 MiB | 1 / 0 | `43e539d8fd20` | +| Debtbox | 90,145 | 122 | 4 | 1.282 s | 302.5 MiB | 337 / 0 | `03c6ced17676` | +| B2C backend | 99,899 | 123 | 4 | 6.425 s | 712.9 MiB | 359 / 0 | `155f8e88edb3` | + +The extra branch fixture protects existing path precision during later narrative changes. B2C and Debtbox remain below the earlier 2× time and 1 GiB RSS budgets on this run. Larger guides have short openings but require the reader to infer relationships from long journeys. + +**Representative current output:** B2C begins its map with “Bootstrap: src/main.ts creates AppModule” and selected controller → service targets; its first featured journey is fleet assignment. The CLI quotes “reads a newline-delimited JSON event file and prints a count for each event type” but then says “No source journey was selected” and “No supported route candidate was found.” The Python case quotes its README purpose yet also asks how to start the app despite the documented `python3 compare.py` command. These are short excerpts from the generated files identified by the hashes above, not proposed wording. + +## Answer keys and short human references + +These are **reviewer keys**, not text for the generator to copy. “Purpose” below is either a checked-in statement or a bounded reading of code. The five questions in each case are: (1) purpose, (2) important concepts, (3) normal path, (4) alternate or independent path, and (5) first change/test/observation. The improvement gate is that a newcomer can find supported answers quickly and sees unsupported answers labeled as questions. + +### B2C backend — large delivery service + +**Human reference:** [B2C newcomer working guide](B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md). It reads the repository around a shipment and separates internal mobile-driver actions from external fleet callbacks. Business terminology and operational ownership remain owner questions. + +1. **Purpose:** Source supports a service coordinating B2C shipment creation, assignment, progress, and related financial workflows; no credible project-purpose paragraph exists in the starter README. `src/module/shipment/services/shipment-b2c.service.ts:648`, `src/module/fleet/services/mobile-fleet.service.ts:67`, `src/module/integrations/integrations.service.ts:630`, `src/module/invoice/invoice.service.ts:723`. +2. **Concepts:** Shipment, its history, vendor, fleet/driver, transaction and invoice have distinct code roles. Business definitions of vendor/customer/seller need an owner. `src/module/data/entity/shipment.entity.ts:103,157,250,293,364,387,402,434`. +3. **Normal path:** B2C creation checks duplicate identifiers; a mobile fleet assignment checks shipment/fleet/driver eligibility and writes assignment/history; driver pickup checks status and vendor configuration. These are separate entry points around the same shipment, not a proven automatic call chain. `shipment-b2c.service.ts:663–717`, `mobile-fleet.service.ts:78–239`, `pickup.service.ts:150–251`. +4. **Alternate/independent path:** An external fleet webhook has fleet/AWB/history gates and may return early; cancellation/RTO handling differs from the mobile-driver path. Invoice updates are a separate financial workflow. `integrations.service.ts:630–780`, `invoice.service.ts:723–840`. +5. **First action:** For an assignment rule, inspect controller → service guards → shipment/history → related tests. For a safe observation, read `GET /health-check` only in an approved local environment; it proves an HTTP response, not dependency health. `mobile-fleet.controller.ts:22–40`, `mobile-fleet.service.ts:67–149`, `src/module/health-check/health-check.controller.ts:20–29`. + +**Current guide gap:** It features fleet assignment, webhook, pickup and invoice as independent traces but omits shipment creation from the featured set and gives no explanation of their relationship. Its starter README yields no project description. A review of selected decisions and source citations found no material false branch or transaction assertion; the main failure is story omission and reading burden, not a demonstrated false runtime claim. + +### Debtbox — debt and consent paths + +**Human reference:** The [illustrative Debtbox fixture](ONBOARDING_V2_DEBTBOX_FIXTURE.md) gives a short source-backed debt creation/consent story. It is a design target, not measured newcomer success or an owner-approved business mission. + +1. **Purpose:** Code supports merchant debt creation, customer consent, payment status and related notifications. Broader product mission and business priority are not established by repository evidence. `src/module/debt/debt.controller.ts:37,54`, `src/module/payment/payment.controller.ts:50`. +2. **Concepts:** Merchant, customer, debt, debt consent and payment are distinct records/roles; the exact commercial meaning is an owner question. `src/module/debt/debt.service.ts:100–155,267–302`. +3. **Normal path:** Debt creation validates merchant/customer/business, rejects a pending duplicate, then attempts separate debt, consent and notification saves. `debt.service.ts:104–199`. +4. **Alternate path:** Consent checks ownership, pending status and expiry. Acceptance sets active and may attempt signature/Sanad work; rejection sets cancelled. A caught signature-upload error does not prove that all effects completed. `debt.service.ts:273–356`. +5. **First action:** Start with the matching controller and service, then inspect affected repositories and tests before changing a guard. A local run requires verified prerequisites; the generated guide has no verified execution. `debt.controller.ts:37–80`, `debt.service.ts:100,267`. + +**Current guide gap:** It selects payment status first and renders debt creation and consent as separate long traces; it does not state their shared record and business question up front. Prior Phase 6 spot checks found no material false branch/transaction claim in selected excerpts; a full owner review is still needed for business meaning. + +### Plain Node app — supported source, no TypeScript trace + +**Human reference:** The project is a small parcel-status HTTP service. `src/server.js:1–22` creates `/health` and a `/parcels/` lookup over an in-memory `Map`; `README.md:3–5` documents `npm start` and `PORT`. It has no persistent store in this fixture. + +1. **Purpose:** Health and parcel-status lookup, as stated by README and visible in source. +2. **Concepts:** A parcel ID maps to an in-memory status; there is no domain entity or database declaration. +3. **Normal path:** A request to `/parcels/parcel-1` finds the map entry and returns status with 200 (`src/server.js:10–17`). +4. **Alternate path:** Missing parcel returns 404; unmatched route returns 404 (`src/server.js:13–20`). +5. **First action:** Change or test route behavior in `src/server.js`; `npm start` is documented but was not run for this baseline. + +**Current guide gap:** It quotes the README and names the entry file but gives no source journey, route behavior, or change location. “No supported route candidate” describes scanner coverage, not the absence of HTTP behavior. + +### Nest queue + scheduled worker — no credible product purpose + +**Human reference:** This is a neutral test fixture. Its README is a Nest starter, so no business purpose should be invented. `ParcelController.dispatch` calls a service that reads a repository and publishes a literal `assign-parcel` job to `parcel-jobs`; a separately scheduled `ParcelJobs.inspect` also reads the repository. The matching worker declares an empty `process` body, so no job effect is established. `controller.ts:5–12`, `service.ts:10–20`, `worker.ts:3–7`, `scheduled.ts:6–10`. + +1. **Purpose:** Unknown beyond exercising route, queue and schedule declarations; starter README cannot supply one. +2. **Concepts:** Parcel repository, queue publication, worker registration and scheduled inspection are code roles, not a verified business flow. +3. **Normal path:** The dispatch route delegates to the service; the service read precedes a literal queue `add` attempt (`controller.ts:8–10`, `service.ts:12–15`). +4. **Alternate/independent path:** `other-jobs` and dynamic job names are not a proven continuation to the `parcel-jobs` worker. The scheduled read is independent, not a result of dispatch (`service.ts:16–19`, `scheduled.ts:7–10`). +5. **First action:** To change the publication, inspect `service.ts` and `worker.ts`; to change the schedule, inspect `scheduled.ts`. No runtime queue processing or test result was verified. + +**Current guide gap:** It correctly labels a possible continuation and a separate scheduled handler, but does not explain why these are separate starting points in one short paragraph. The README is correctly not promoted to project purpose. + +### Non-Nest Event Count CLI — input to output + +**Human reference:** The fixture reads a newline-delimited JSON file and prints sorted counts by event `type`, without a database or network call. `README.md:3–5`, `src/cli.js:1–29`. Its story is command → file → parse/validate → count → stdout, not an HTTP route or entity lifecycle. + +1. **Purpose:** Count event types in a local JSONL file, from README and source. +2. **Concepts:** Input path, event `type`, count map and stdout are the important artifacts (`src/cli.js:4–24`). +3. **Normal path:** With a file path, it reads nonempty lines, parses JSON, counts types and prints sorted results (`src/cli.js:9–24`). +4. **Alternate path:** Missing input prints usage and sets exit code 2; malformed JSON or non-string `type` prints an error and sets exit code 1 (`src/cli.js:5–7,14–27`). +5. **First action:** Inspect `src/cli.js` for validation/output changes; the documented command needs a file argument. A disposable JSONL input can be used for a safe first observation if a person chooses to run it. + +**Current guide gap:** It quotes the purpose and entry file, yet asks which test/install commands exist and shows `npm run start` without the required file argument. “No route candidate” is irrelevant to a CLI; no change or failure path is offered. + +### Sparse Python CSV utility — unsupported language, honest fallback + +**Human reference:** The README states that a small Python script compares item counts in two CSV files and writes nonzero differences to stdout. `compare.py:5–18` shows dictionary loading and `actual − expected` for each item. Deployment, owner and tests are not documented. + +1. **Purpose:** Compare expected and actual CSV counts, from `README.md:3` and `compare.py:5–18`. +2. **Concepts:** Two input CSV files, `item` and `count` columns, and difference rows. There is no supported Node/Nest entity model. +3. **Normal path:** Given two paths, load both dictionaries and print each nonzero difference in sorted item order (`compare.py:10–18`). +4. **Alternate path:** Missing arguments exit with usage; invalid file/column/count can raise an error because there is no local handling (`compare.py:5–12`). +5. **First action:** Inspect `compare.py` and the documented invocation in `README.md:5`; a person may use disposable CSV files for a safe observation. Test command and real data source remain unknown. + +**Current guide gap:** It quotes the README but says “confirm the application start command” even though the README provides one. Its route-candidate language is irrelevant, and it gives no input/output or change explanation. This is a product usefulness gap rather than a proven false behavioral claim. + +## Negative cases and review boundary + +- Do not turn a starter README into a business purpose (Nest worker, B2C). +- Do not join B2C creation, mobile assignment, external webhook and invoice into a single automatic call chain; their shared shipment record is a supported relationship, their chronology is not established for every case. +- Do not say Debtbox consent acceptance, signature storage or notification succeeded from static calls. Preserve the rejected/expired branches. +- Do not describe an empty worker body as having processed a parcel or a scheduled read as caused by a queue publication. +- Do not describe in-memory Node/CLI/Python fixtures as having a database, or treat “no Nest route candidate” as “the repo has no entry point.” +- Do not assert tests are absent when only trace-adjacent test discovery failed. Distinguish **not found by this scan** from **verified absent**. + +The small fixture source was read directly for these keys. For B2C and Debtbox, the prior [Phase 6 spot check](ONBOARDING_PHASE6_ACCEPTANCE.md#accuracy-and-readability-review) validated selected entry/decision citations, while this baseline reviewed representative paths and guide omissions. It is not a complete manual audit of every statement in the two large generated guides. The real unfamiliar-engineer comparison remains pending. diff --git a/docs/ONBOARDING_HUMAN_STORY_PLAN.md b/docs/ONBOARDING_HUMAN_STORY_PLAN.md new file mode 100644 index 0000000..9009110 --- /dev/null +++ b/docs/ONBOARDING_HUMAN_STORY_PLAN.md @@ -0,0 +1,92 @@ +# Human-first onboarding guide enhancement plan + +**Status:** Phase 0 complete; Phases 1–5 pending. The [Phase 0 acceptance baseline](ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md) records cross-repository answer keys and measurements. This follows the existing [repository-only deep guide work](ONBOARDING_DEEP_GUIDE_PLAN.md). Its source traces, evidence rules, personal workspace, and safe regeneration remain the foundation. Milestone 9's real unfamiliar-engineer assessment is still open. + +## Why this change is needed + +The current guide is good at showing *where code is* and *what a bounded static trace saw*. It is weak at answering the first questions of a solo newcomer: **What does this repository do? What are its important things? How does work enter, move, and finish? Which path should I read for my task?** The [B2C reference guide](B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md) demonstrates the desired reading experience, but its shipment vocabulary and lifecycle are examples, not a template to hard-code. + +In the current pipeline, `onboarding-journey-selection.ts` scores method counts, checks, writes, and continuations; `onboarding-concepts.ts` ranks entities by nearby calls; `onboarding-guide.ts` renders those selections largely as declarations and events. `onboarding-repository-notes.ts` extracts a short README paragraph and nearby comments. None of these creates a repository-level purpose, groups related paths into a supported workflow, or explains why a developer should read one path before another. The B2C guide therefore has 807 lines and 359 links while leaving the newcomer to assemble the system story. + +## Target result + +The first screen of `ONBOARDING.md` should orient a newcomer in plain language, then lead them from a relevant question to evidence. Use this order when the evidence permits: + +1. **What this repository appears to do:** purpose, deliverable or service, inputs and outputs, and the limits of the claim. +2. **A small mental model:** three to five important records, actors, or artifacts and how they relate. Explain a term only when repository prose or behavior supports its meaning; otherwise give its code role and ask for business meaning. +3. **How work moves:** one representative path from an entry to an observable result, then a second genuinely distinct path or an alternate/failure path. State whether paths are causally connected, share state, or are merely related by name. +4. **Where and when to look:** a task-to-file/test map, a safe first investigation, setup prerequisites and exact blockers. +5. **What still needs a person:** business intent, ownership, operational recovery, and other facts that source cannot establish. + +Put exhaustive traces, entity fields, module inventories, and secondary route candidates in a collapsed reference appendix. Keep every source claim inspectable. The guide may be short for a sparse or unsupported repository; it must never fill gaps with a plausible invented story. + +### Generic shape, not a universal lifecycle + +The same questions apply to a service, CLI, library, frontend, worker, or data job, but the nouns differ. A service may read as request → rule → state → response/event; a CLI as command → input → transformation → file/output; a library as public API → internal operation → return/error; a worker as trigger → handler → state/output. Select a shape only from observed entry and output evidence. If the repository is mixed or its purpose is unclear, show multiple candidate entry points and say what is unknown. NestJS, TypeORM, shipments, and invoices are never prerequisites for an intelligible guide. + +## Evidence and writing rules + +- **Every substantive sentence has provenance.** Use a small claim record carrying source locations and one of: repository statement, code observation, conservative inference, owner-supplied context, or unknown. A citation must support the *whole* sentence, not merely contain a matching symbol. +- **Keep causality strict.** A call edge, matched queue publication/handler, or explicit data dependency can connect steps. Shared entity names, imports, and chronological guesses make *related paths*, not a continuous workflow. State whether a write, notification, or external effect was attempted; do not assert runtime success from source alone. +- **Explain code in human terms without inventing policy.** “This check rejects a shipment already assigned to a fleet” is supportable from a guard. “The fleet has accepted commercial responsibility” requires a documented business rule or owner statement. Names alone do not define a business actor. +- **Use owner knowledge deliberately.** Reuse existing owner-editable `System context` and `Verified local setup` areas. Label owner statements and their author/date only when supplied; preserve them byte-for-byte across rescans. If owner context conflicts with code, show both and ask for review. +- **Respect repository boundaries.** Read only checked-in text/code needed for selected claims; skip secrets and values. Generation never installs dependencies, starts apps, runs migrations, or calls external services. The core remains framework independent; scanners emit evidence, standards choose and connect it, renderers format it, and CLI orchestrates. +- **Keep the first screen small.** Measure whether a reader can answer the five newcomer questions from the opening without expanding the appendix. Use size as a readability signal, not as proof of usefulness. + +## Ordered implementation checklist + +### Phase 0 — Lock a cross-repository acceptance set + +- [x] Capture the current generated guide and a short human reference for **B2C, Debtbox, a plain Node app, a non-Nest CLI or library, a worker/job, and a sparse or unsupported-language repository**. Reuse existing fixtures where suitable; add only minimal new ones. +- [x] For each repository, write five answer-key questions: purpose, important concepts, one normal path, an alternate/independent path, and first change/test/observation. Mark which answers are source-supported, owner-supplied, or genuinely unknown. +- [x] Record baseline first-screen word count, guide size, selected paths, broken/unsupported claims, run time and peak RSS. Keep the B2C human guide as a **style and utility reference**, not as an expected string or universal domain model. + +**Gate:** A reviewer can identify what a better guide must answer for each repository without assuming that every repository has HTTP routes, database entities, or a full lifecycle. + +### Phase 1 — Build a cited repository story inventory + +- [ ] Discover a small set of likely purpose statements from project-specific README sections and relevant checked-in docs. Detect starter/boilerplate text and avoid promoting it to project purpose. Inspect manifests, executable entry points, public APIs, commands, handlers, tests and configuration as corroborating evidence. +- [ ] Represent repository role, entry points, important data/artifacts, outputs, external boundaries, and safe observation candidates as typed, bounded claims with provenance and uncertainty. Keep this structured state separate from Markdown. +- [ ] Identify a few central terms from repeated use across entries and outputs, then attach only supported descriptions. An entity declaration alone gives a code role, not business meaning. Preserve exact evidence for rejected or ambiguous descriptions. + +**Gate:** On B2C, the inventory can support “shipment is central” and distinguish vendor/fleet/driver relations without defining their business contracts. On a CLI/library it identifies commands/public APIs and outputs. On a sparse repo it gives a useful inventory plus explicit questions, with no invented purpose. + +### Phase 2 — Connect and select stories, not just deep traces + +- [ ] Group paths by *supported* shared state, call/event continuation, or documented workflow. Record edge type: direct call, possible asynchronous continuation, shared artifact, documented relation, or unproven association. +- [ ] Choose a representative entry and complementary path for newcomer coverage: where work starts, a key decision, state/output, and a failure or alternate path. Let a documented purpose and core record weigh more than raw method/branch count. Retain `--focus` for a developer's specific question. +- [ ] Do not force a single sequence. If creation, callback, and invoice are independent entry points touching the same record, show them as separate chapters around that record. If an edge is missing, state the first unsupported boundary and what to inspect next. +- [ ] Keep deep trace limits and negative cases: no false path joining, callback execution, transaction completion, provider delivery, or dynamic target certainty. + +**Gate:** B2C selection explains shipment creation/assignment and distinguishes mobile status from external callbacks; Debtbox selects a coherent ownership-relevant path; a CLI/library follows its own input-to-output shape. Selected paths may differ when repository evidence differs, but each selection has a recorded reason. + +### Phase 3 — Render the human reading path + +- [ ] Introduce a short “What this repo does” and “How to read it” opening from Phase 1 claims, with visible inference/unknown labels where needed. +- [ ] Replace the opening entity inventory with a three-to-five-term glossary: term, code role, supported meaning, and why the newcomer will encounter it. Move relation and field lists to the appendix. +- [ ] Render each selected story as **why this path matters → trigger/input → decision → state or output → alternate exit → external boundary → where to change/test**, using brief prose and nearby grouped citations. Keep the raw event trace available in collapsed details. +- [ ] Add a task-to-file/test map and one safe first investigation chosen from actual code and test evidence. Do not say tests are absent merely because the current trace did not discover them. +- [ ] Keep setup specific: engine/version and meaningful declared dependencies, documented versus verified commands, safe observation, and blockers. Preserve the current guide markers, snapshot reconciliation, owner sections, and all personal workspace data. + +**Gate:** A reviewer answers the five Phase 0 questions from the opening and stories without reading the appendix. Every behavioral sentence is supported by its cited code or clearly labeled as a repository/owner statement or inference. No human edit disappears on regeneration. + +### Phase 4 — Align personal learning with the story + +- [ ] Make the existing stable `v2:` exercises point to the new mental model, selected stories, change map, and safe observation. Keep their IDs, checked boxes, notes, questions, evidence and legacy progress intact. +- [ ] When source selection changes, preserve completed work and flag stale links. A checked exercise remains self-reported progress, never a competence certificate. + +**Gate:** A newcomer can record what they understood, tried, and still need to ask without copying the whole guide. Sync and conflict tests continue to protect both Markdown and structured progress. + +### Phase 5 — Independent accuracy, utility, and performance review + +- [ ] Run all acceptance repositories from disposable snapshots. Compare old/new answers, guide size and first-screen readability, generation time, peak RSS, and exact citations. Manually inspect every material claim in the featured stories against source; record omissions and misleading wording. +- [ ] Ask an unfamiliar engineer to do repository-only tasks with and without the guide, using the existing [assessment protocol](ONBOARDING_PHASE6_ACCEPTANCE.md#unfamiliar-engineer-task-protocol--pending). Record correctness, irrelevant searches/questions, first safe observation or blocker, and misleading claims. A code-only self-review cannot close this gate. +- [ ] Fix material false claims and navigation failures before changing Milestone 9 status. Compare on multiple repository shapes; success on B2C and Debtbox alone is insufficient for the generic claim. + +**Gate:** The new guide improves answer correctness or reduces irrelevant search/questions for actual newcomers across the evaluated shapes, has no material false behavioral claim, preserves human edits, and stays within the existing time/RSS budgets or documents an explicit reviewed exception. Keep the milestone open if no engineer is available. + +## Deliberate limits + +This plan does not add hosted services, implicit AI, runtime execution, new language-specific deep tracers, or a business ontology. A non-TypeScript repository can still get a useful overview from its own documentation, manifests, public entry points, tests, and artifacts; unsupported inner behavior remains a cited gap. Optional AI prose may be considered later only as an opt-in rewrite of vetted claims, never as a source of new facts. + +Phase 0 is complete. The next implementation request can start **Phase 1 only**; later phases depend on its cited inventory, so the B2C example cannot quietly become the product template. diff --git a/docs/ONBOARDING_PHASE6_ACCEPTANCE.md b/docs/ONBOARDING_PHASE6_ACCEPTANCE.md new file mode 100644 index 0000000..de08838 --- /dev/null +++ b/docs/ONBOARDING_PHASE6_ACCEPTANCE.md @@ -0,0 +1,36 @@ +# Onboarding Phase 6 acceptance record + +**2026-10-02 — repository-only regression complete; newcomer assessment pending.** This is a local acceptance record, not a claim that Milestone 9 has passed. + +## Repeatable regression + +Build TransferKit, then run `python3 experiments/onboarding-phase6-regression.py --out /tmp/ --debtbox /path/to/debtbox-backend --madar /path/to/b2c-backend`. The script copies neutral fixtures and archives pinned revisions of the two application repositories into disposable directories. It runs only `tk onboard guide` and `tk onboard workspace`, saving each guide, workspace, and `results.json`. It does not install dependencies or run target applications. Debtbox and Madar paths are optional; omit an unavailable repository and mark that case untested. + +| Snapshot | Selected journeys | Guide size | First guide run | Peak RSS | +| --- | ---: | ---: | ---: | ---: | +| Plain Node source fixture | 0 | 2,985 bytes | 0.166 s | 128.6 MiB | +| Neutral Nest queue/scheduled fixture | 2 | 8,101 bytes | 0.316 s | 185.8 MiB | +| Neutral branch/transaction fixture | 2 | 10,824 bytes | 0.326 s | 187.3 MiB | +| Debtbox `e0267736` | 4 | 90,145 bytes | 1.322 s | 300.1 MiB | +| Madar B2C `79cc98e5` | 4 | 99,899 bytes | 6.631 s | 720.9 MiB | + +This is one local macOS run, so timings are indicative. Compared with the same pinned Debtbox and Madar revisions in [the original baseline](ONBOARDING_DEPTH_BASELINE.md), guide time is 1.18× and 1.16× respectively; both remain below the 2× and 1 GiB budgets. Guide size rose from 13,383 to 90,145 bytes for Debtbox and from 12,763 to 99,899 bytes for Madar. The opening map stays short and long inventories are collapsed, but a real reader has not yet judged whether the larger journey sections are readable. The new plain Node and neutral Nest fixtures differ from the baseline fixtures, so their run times are not a like-for-like performance comparison. + +The plain Node map now quotes the README's health and in-memory lookup description, cites its declared `src/server.js` entry, and leaves runtime behavior unverified. It selects no traced journey because JavaScript bodies are outside the current TypeScript trace scanner. The neutral Nest guide links `ParcelController.dispatch` to a possible queue continuation and selects `ParcelJobs.inspect` separately; the mismatched worker is not connected. The neutral branch guide keeps the invalid-input throw separate from later reads, keeps priority/standard assignments mutually exclusive, lists transaction calls as attempts, and leaves callback/dynamic calls unresolved. Debtbox selects payment status, debt creation, email verification, and consent; Madar selects fleet assignment, webhook, pickup confirmation, and invoice update. These are source coverage choices, not a business-priority ranking. + +## Accuracy and readability review + +All rendered local source links were checked against the snapshot files and line bounds: 2 plain Node, 42 neutral Nest, 70 neutral branch, 337 Debtbox, and 359 Madar; no broken or out-of-range link was found. The neutral branch guide was reviewed against its entire six-file fixture for branch exits, repeated helper calls, manager alias, queue name matching, and unsupported edges. For each of the eight selected Debtbox/Madar journeys, the entry declaration and the first displayed decision or alternate throw were compared with the cited source. Representative matches: Debtbox payment missing-checkout guard at `payment.service.ts:278`, debt missing-merchant guard at `debt.service.ts:105`, email verification missing-customer guard at `customer-email-verification.service.ts:95`, consent missing-debt guard at `debt.service.ts:276`; Madar fleet missing-shipment guard at `mobile-fleet.service.ts:79`, webhook missing-shipment guard at `integrations.service.ts:649`, pickup status guard at `pickup.service.ts:159`, and invoice permission guard at `invoice.service.ts:725`. No material false call, branch, or transaction assertion was found in those checks. This is a spot check, not a manual reading of every line in the two large guides. + +The source-linked journeys present an entry, a decision or an explicit lack of one, alternate exits where traced, an unsupported boundary, and initial change locations. Test locations are described as unestablished where no related test was found. The plain Node guide has only a README-based overview and declared start entry, and explicitly has no selected source journey. Readability remains a reviewer limit for the 90–100 KiB guides, especially their longer journey sections. No application behavior or setup outcome was verified. + +## Unfamiliar engineer task protocol — pending + +Use a real engineer who has not worked in the selected repository. A source-aware reviewer first prepares a short answer key for two comparable tasks in that repository, including expected record concepts, two paths, an alternate exit, likely change and test files, and a safe observation or exact setup blocker. Keep the answer key separate from the guide and participant. + +1. Give the participant one task with repository files only. Record start/end time, source searches, questions asked, answer, first safe observation or blocker, and misleading material encountered. +2. Give a second comparable task with the generated guide and personal workspace available. Record the same data. Alternate task order across participants if more than one engineer is available; with one engineer, report carryover and task-difficulty limits rather than treating the comparison as controlled. +3. For each task ask the engineer to explain the key records and two distinct paths, identify an alternate or failure path, point to files/tests for a small change, try a safe first observation or name its exact blocker, and list questions requiring a teammate. Do not require risky setup commands or credentials. +4. Score each answer **correct**, **partly correct**, or **unsupported** against the prepared key, with citations. Count irrelevant searches and unresolved questions in both conditions. Record any misleading guide claim and fix it before declaring success. A confidence rating may be collected but is not the gate. + +No engineer has completed this protocol. Therefore there is no measured repository-only newcomer improvement, and Milestone 9 remains **IN PROGRESS**. Milestone 10's handover-assisted assessment remains separate and untouched. diff --git a/docs/ONBOARDING_V2.md b/docs/ONBOARDING_V2.md index e5d2fb1..3f35ea5 100644 --- a/docs/ONBOARDING_V2.md +++ b/docs/ONBOARDING_V2.md @@ -1,6 +1,6 @@ # 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. +**Status: Milestone 9 in progress.** The repository-only guide now includes bounded source-backed journeys, concepts, setup evidence, and change points. The personal workspace has four stable `v2:` exercises, Markdown/JSON checkbox sync, and v2-aware plan/status. Fixture regression and source spot checks are recorded in the [Phase 6 acceptance record](ONBOARDING_PHASE6_ACCEPTANCE.md); a real unfamiliar-engineer comparison is still pending. The [illustrative Debtbox fixture](ONBOARDING_V2_DEBTBOX_FIXTURE.md) remains a design target, not current CLI output. ## Goal and modes @@ -13,15 +13,15 @@ When a v3 Transfer is available, selected Handover Items may **enrich** the same - 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. +- The current guide's generated portions come from repository evidence. Managed section markers and a generation snapshot preserve unrelated human prose and surface conflicting edits; an existing unmarked guide is not overwritten. Later layouts must retain this reconciliation behavior. Optional linked Transfer context remains future work. ## 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. +The guide should start with a concise system overview and a map of supported entry points, modules, data stores, integrations, background work, and relationships. A curated concepts section should distinguish data shapes from business meanings. Show a few complementary, connected journeys where source permits, each with entry, inputs, decisions and alternate exits, visible read/write attempts, helper or job continuations, gaps, and relevant code/tests to inspect for a change. Describe setup and operations from checked-in evidence, and keep precise unknowns prominent. Sparse repositories may have fewer journeys. Avoid flat dependency lists, invented business purpose, 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. +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. Exercises should ultimately use the selected concepts and journeys to ask for an explanation, a likely change point, and a recorded local observation or exact blocker. 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 @@ -29,11 +29,21 @@ The personal workspace has four fixed `v2:` exercise IDs based on learning outco ## 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. +The initial repository-only guide and personal workspace slices are implemented. Follow the ordered [deep guide slices](ONBOARDING_DEEP_GUIDE_PLAN.md) for acceptance fixtures, bounded tracing, concepts and continuations, setup, adaptive exercises, guide regeneration, and a real repository-only newcomer assessment. The four existing `v2:` IDs and legacy progress must survive later improvements. -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. +### Slice 0 acceptance cases + +These are source-grounded assertions for tracing and rendering review. Use the neutral source under `fixtures/onboarding-deep-guide/` and the small JavaScript app under `fixtures/onboarding-plain-node/`. Positive claims must cite the listed source; negative claims must remain absent or be explicit gaps. Test semantic claims and citations rather than whole Markdown whitespace. + +| Case | Required claim and citation | Forbidden claim | +| --- | --- | --- | +| Early throw | `service.ts:44` throws when `valid` is false; later calls are on a different path. | The invalid path reads, saves, queues, or returns an order. | +| Exclusive branch | `service.ts:47-50` assigns either priority or standard status under distinct conditions. | Both status assignments happen on one path. | +| Repeated helper | Both call sites at `service.ts:52-53` link to `OrderService.recordAttempt` at `service.ts:69`. | One invocation is silently collapsed, or constructor injection becomes a call. | +| Local manager alias | `service.ts:54-62` records a query-runner alias, write-like `manager.save`, and separate commit/catch/finally calls. The interface at `service.ts:18-27` has no implementation body. | A write committed, rollback succeeded, or all branches ran. `CacheSnapshot.save` at `service.ts:65` is database persistence. | +| Possible continuation | Enqueue call `service.ts:64` and handler registration `worker.ts:7-10` share `assign-order`; `worker.ts:9` returns before the read when the ID is empty. | The job ran, an empty ID reads a record, or `ArchiveWorker` at `worker.ts:14-16` is connected to this enqueue. | +| Plain Node overview | `src/server.js:1-22` exposes a health path and in-memory parcel lookup; `README.md:3-5` documents `npm start`. | A database, verified run, business purpose beyond the README, or a NestJS flow is invented. | + +Before calling a guide slice readable, a reviewer should locate each selected journey's entry, at least one cited decision or explicit lack of one, an alternate exit where present, the first unsupported edge, and likely change/test files within the journey section. Every substantive behavioral sentence should be verifiable at its cited source. Keep broad inventories out of the opening section; if a small fixture lacks evidence for a journey, say so rather than filling space. This is a reviewer rubric, not an automated understanding score. + +Milestone 9 remains open until the deep repository-only guide and personal workspace pass their gates and an unfamiliar engineer completes the repository-only assessment. If no engineer is available, report that gate as pending. Milestone 10 separately evaluates handover-assisted onboarding and broader real-world outcomes. Optional v3 Item enrichment remains a separate later addition, never a prerequisite for repository-only use. 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 order; + } +} + +export class NotificationService { + async send(order: { status: string }): Promise { + 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 [...]", + ); + +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( + "", 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 ?? "") : ""}.${method.name?.getText() ?? ""}`; + } + 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 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 { + async find(_id: string): Promise { + void _id; + return undefined; + } +} + +export class AssignmentQueue { + async add(_name: string, _data: { id: string }): Promise { + void _name; + void _data; + } +} + +export interface QueryRunner { + manager: { save(order: Order): Promise }; + commitTransaction(): Promise; + rollbackTransaction(): Promise; + release(): Promise; +} + +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 { + 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 { + if (!id) return; + await this.repository.find(id); + } +} + +export class ArchiveWorker { + @Process("archive-order") + async handle(): Promise {} +} 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 "); + 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 ` 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 = 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 { + async find(_id: string): Promise { + 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 { + 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 {} +} + +@Processor("elsewhere") +export class OtherProcessor extends WorkerHost { + async process(): Promise {} +} 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/packages/cli/README.md b/packages/cli/README.md index 5452067..006d004 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -31,13 +31,16 @@ To review a suggestion before the meeting, use `tk handover plan accept in-progress tk onboard task completed +tk onboard sync ``` -Personal progress stays in `.transferkit.local/`. Onboarding currently uses repository findings and any legacy handover knowledge; it does not use v3 Transfer completion. +`guide` writes a shared, source-cited `ONBOARDING.md`; use `guide --focus ` to inspect a supported entry. `workspace` creates a personal Markdown checklist in `.transferkit.local/`. After editing its checkboxes, run `sync` to update personal progress, then `status`. Generated paths and commands are static evidence; application behavior and setup remain unverified until a person tries them. Onboarding does not use v3 Transfer completion. ## What's new in 0.2.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 ] 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..edfc1e8 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,306 @@ async function guide(directory: string): Promise { } describe("shared guide regeneration", () => { + 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( + "
Inventories, candidate routes, and supporting declarations", + ); + expect(generated).toContain(' { + 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( + /[\s\S]*?\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; + }; + 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; + }; + 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 +350,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 +384,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 +403,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 +424,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 +454,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("", ""), + ); + 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..bc2fa9d 100644 --- a/packages/cli/src/generate-onboarding-guide.ts +++ b/packages/cli/src/generate-onboarding-guide.ts @@ -2,10 +2,19 @@ import { randomUUID } from "node:crypto"; import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; +import type { OnboardingSelectedConcept } from "@transferkit/core"; import { renderOnboardingGuide } from "@transferkit/renderers"; -import { scanRepository } from "@transferkit/scanners"; +import { + discoverOnboardingRepositoryNotes, + scanOnboardingRepository, +} from "@transferkit/scanners"; import { explainCandidateFlows, + preselectOnboardingEntries, + selectOnboardingContinuations, + selectOnboardingJourneys, + selectScheduledConcepts, + selectOnboardingConcepts, understandProject, } from "@transferkit/standards"; @@ -19,6 +28,7 @@ type Block = { id: string; start: number; end: number; text: string }; export async function generateOnboardingGuide( directory: string, + options: { focus?: string } = {}, ): Promise { const file = join(directory, "ONBOARDING.md"); const existing = await optionalRead(file); @@ -32,13 +42,80 @@ 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; + const { findings, traces, concepts, queues, scheduledCalls } = + await scanOnboardingRepository(directory, (scanned, context) => { + const preliminary = preselectOnboardingEntries( + scanned, + context.queues, + context.scheduledCalls, + options.focus, + ); + focusSymbol = preliminary.focusSymbol; + return preliminary.entries; + }); const model = understandProject(findings); + const selection = selectOnboardingJourneys( + traces, + concepts, + queues, + focusSymbol, + ); + const selectedConcepts = mergeConcepts( + selection.selected.flatMap((item) => + selectOnboardingConcepts(item.trace, concepts), + ), + ); + const repositoryNotes = await discoverOnboardingRepositoryNotes( + directory, + selection.selected.map((item) => item.trace), + findings, + ); + const displayedSymbols = new Set([ + ...(focusSymbol ? [focusSymbol] : []), + ...selection.selected.map((item) => item.trace.entry.symbol), + ...selection.rejected.map((item) => item.trace.entry.symbol), + ]); + 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; + 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: selection.selected.map((item) => ({ + trace: item.trace, + reason: item.reason, + continuations: selectOnboardingContinuations(item.trace, queues), + })), + concepts: selectedConcepts, + scheduled: selectScheduledConcepts( + scheduledCalls, + concepts, + selectedConcepts, + ), + displayFlowIds, + rejected: selection.rejected.map((item) => ({ + symbol: item.trace.entry.symbol, + reason: item.reason, + })), + repositoryNotes, + }, ), ); const generated = parseBlocks(proposed); @@ -101,9 +178,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 +214,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(); + 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 = { + "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..797daee 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."], @@ -70,6 +78,9 @@ describe("personal onboarding workspace", () => { 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,78 @@ 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("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/onboarding-v2-view.ts b/packages/cli/src/onboarding-v2-view.ts index fc84afd..156af08 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: (.+)$/gmu, + ), + ].map((match) => match[1]!), + ); + const staleJourneys = [ + ...personal.matchAll(/^$/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/core/src/index.ts b/packages/core/src/index.ts index 7936a27..fea970b 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -14,6 +14,7 @@ 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 "./personal-onboarding.js"; export * from "./ownership-readiness.js"; export * from "./secret-protection.js"; 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..5432e86 100644 --- a/packages/renderers/src/onboarding-guide.ts +++ b/packages/renderers/src/onboarding-guide.ts @@ -4,6 +4,11 @@ import type { Evidence, ExplainedFlow, Finding, + OnboardingTrace, + OnboardingSelectedConcept, + OnboardingQueueContinuation, + OnboardingRepositoryNote, + OnboardingScheduledConcept, ProjectModel, RouteTrace, } from "@transferkit/core"; @@ -19,11 +24,32 @@ 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[]; +} + 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 +73,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 +164,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 +230,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 +311,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( + "
Other entity declarations linked to this journey", + "", + ...concepts + .slice(5) + .map( + (concept) => + `- ${safe(concept.entity.name)}: ${sourceLink(concept.entity.declaration)}; ${concept.calls.length} selected call site(s).`, + ), + "", + "
", + "", + ); + } + 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 +442,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 +458,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 +490,17 @@ export function renderOnboardingGuide( "", ); } + if (options.rejected?.length) + lines.push( + "
Other traced candidates and selection reasons", + "", + ...options.rejected + .slice(0, 8) + .map((item) => `- ${safe(item.symbol)}: ${safe(item.reason)}`), + "", + "
", + "", + ); lines.push( "## Setup and operations", "", @@ -341,7 +508,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 +525,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 +548,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 +681,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 +744,197 @@ export function renderOnboardingGuide( "- **Unknown:** What are the production topology and operational owners? Ask a knowledgeable person.", "", ); - return `${lines + return arrangeGuide( + `${lines + .join("\n") + .replace(/\n{3,}/gu, "\n\n") + .trimEnd()}\n`, + 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("
"), + ); + 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") - .replace(/\n{3,}/gu, "\n\n") - .trimEnd()}\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", + "", + '', + "", + 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", + "", + '', + "", + ...(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", + "", + '', + "", + setup, + "", + "## Specific questions", + "", + '', + "", + unknowns, + "", + "## Reference appendix", + "", + "
Inventories, candidate routes, and supporting declarations", + "", + ...appendix, + "
", + "", + ] + .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 +958,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 = [ + ``, + "", + `### 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 +1223,7 @@ function selectRelationships( ); } -function selectFlows( +export function selectOnboardingFlows( candidates: readonly CandidateFlow[], model: ProjectModel, findings: readonly Finding[], 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) => + ``, + ), "", "### 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..89791c8 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,7 @@ 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 type { MessagingConsumerData, MessagingConsumerFinding, @@ -180,20 +195,99 @@ export async function scanRepository( repositoryDirectory: string, ): Promise { 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[]; + }, + ) => readonly string[]), + limits: Partial = {}, +): 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 entries = + typeof selectedEntries === "function" + ? selectedEntries(findings, { queues, scheduledCalls }) + : 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; + 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: discoverOnboardingConceptsInAst(ast), + 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(); + 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(); + 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(); + 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 { + 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(); + 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(); + 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 { + 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 { + 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; + 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-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 }; + +/** Uses the scan's existing ts-morph Project; it never creates another Program. */ +export function analyzeOnboardingRoutes( + ast: TypeScriptAst, + routes: readonly HandoverContextFinding[], + options: Partial = {}, +): 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(); + const visitedFiles = new Set(); + 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 = {}, + ): 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() ?? ""}.${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.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)[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..3aa32f8 100644 --- a/packages/standards/src/index.ts +++ b/packages/standards/src/index.ts @@ -27,4 +27,14 @@ 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 { 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(); + 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..6c418c8 --- /dev/null +++ b/packages/standards/src/onboarding-journey-selection.ts @@ -0,0 +1,294 @@ +import type { + Finding, + OnboardingConceptEvidence, + OnboardingQueueEvidence, + OnboardingScheduledCall, + 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, +): { + 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; + 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(); + 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; + 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 entries = [ + ...new Set([ + ...(matchingFocus[0] ? [matchingFocus[0].symbol] : []), + ...rankedRoutes.slice(0, 16).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(); + const seenOwners = new Set(); + const seenVerbs = new Set(); + 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(); + 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/personal-onboarding.ts b/packages/standards/src/personal-onboarding.ts index 0e85edd..63656de 100644 --- a/packages/standards/src/personal-onboarding.ts +++ b/packages/standards/src/personal-onboarding.ts @@ -7,6 +7,7 @@ export function personalOnboardingExercises( sections: ReadonlySet, hasExplainedFlow: boolean, hasCandidateFlow: boolean, + guideSections?: ReadonlyMap, ): PersonalOnboardingExercise[] { for (const required of [ "system-overview", @@ -20,14 +21,29 @@ 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: (.+)$/gmu, + ), + ] + .map((match) => match[1]!) + .slice(0, 2); + const concepts = [ + ...(guideSections?.get("concepts") ?? "").matchAll(/^### ([^\n]+)$/gmu), + ] + .map((match) => match[1]!) + .slice(0, 3); 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 + ? `Map ${concepts.join(", ")} from cited declarations to the entry point and selected journeys; label uncertain relationships.` + : "Explain the entry point, major components, and supported relationships using the guide's evidence labels.", guideSectionId: "system-overview", outcome: "Write a short system map and list any relationships that still need confirmation.", @@ -35,12 +51,18 @@ export function personalOnboardingExercises( { 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]} from cited source, including an alternate exit and the first unsupported edge in each.` + : journeys.length === 1 + ? `Explain ${journeys[0]} from cited source, including an alternate exit and its first unsupported edge; identify what second path is missing.` + : 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.", guideSectionId: flowSection, + ...(journeys.length ? { linkedJourneys: journeys } : {}), outcome: hasExplainedFlow || hasCandidateFlow ? "Record a concise trace with repository-relative citations and unresolved steps." @@ -58,8 +80,9 @@ 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.", + objective: journeys.length + ? `Find a likely change and test location for ${journeys[0]}; classify remaining questions as source, runtime, or person-dependent.` + : "Identify a likely change point if possible; classify remaining questions as source, runtime, or person-dependent.", guideSectionId: "unknowns", outcome: "List the remaining questions, their intended source, and any evidence gathered.", From 86100577ba5a11b0378f07e730f7b220b4139fc0 Mon Sep 17 00:00:00 2001 From: alialaraby Date: Sat, 3 Oct 2026 01:07:29 +0300 Subject: [PATCH 2/7] Add cited onboarding story inventory --- docs/ONBOARDING_HUMAN_STORY_PLAN.md | 10 +- packages/core/src/index.ts | 1 + packages/core/src/onboarding-story.ts | 50 ++ packages/scanners/src/index.ts | 1 + .../scanners/src/onboarding-story.test.ts | 104 ++++ packages/scanners/src/onboarding-story.ts | 526 ++++++++++++++++++ packages/standards/src/index.ts | 1 + .../standards/src/onboarding-story.test.ts | 61 ++ packages/standards/src/onboarding-story.ts | 84 +++ 9 files changed, 833 insertions(+), 5 deletions(-) create mode 100644 packages/core/src/onboarding-story.ts create mode 100644 packages/scanners/src/onboarding-story.test.ts create mode 100644 packages/scanners/src/onboarding-story.ts create mode 100644 packages/standards/src/onboarding-story.test.ts create mode 100644 packages/standards/src/onboarding-story.ts diff --git a/docs/ONBOARDING_HUMAN_STORY_PLAN.md b/docs/ONBOARDING_HUMAN_STORY_PLAN.md index 9009110..23b30ac 100644 --- a/docs/ONBOARDING_HUMAN_STORY_PLAN.md +++ b/docs/ONBOARDING_HUMAN_STORY_PLAN.md @@ -1,6 +1,6 @@ # Human-first onboarding guide enhancement plan -**Status:** Phase 0 complete; Phases 1–5 pending. The [Phase 0 acceptance baseline](ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md) records cross-repository answer keys and measurements. This follows the existing [repository-only deep guide work](ONBOARDING_DEEP_GUIDE_PLAN.md). Its source traces, evidence rules, personal workspace, and safe regeneration remain the foundation. Milestone 9's real unfamiliar-engineer assessment is still open. +**Status:** Phases 0–1 complete; Phases 2–5 pending. The [Phase 0 acceptance baseline](ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md) records cross-repository answer keys and measurements. Phase 1 adds a typed, cited story inventory in core, scanners, and standards; guide rendering remains for Phase 3. This follows the existing [repository-only deep guide work](ONBOARDING_DEEP_GUIDE_PLAN.md). Its source traces, evidence rules, personal workspace, and safe regeneration remain the foundation. Milestone 9's real unfamiliar-engineer assessment is still open. ## Why this change is needed @@ -45,9 +45,9 @@ The same questions apply to a service, CLI, library, frontend, worker, or data j ### Phase 1 — Build a cited repository story inventory -- [ ] Discover a small set of likely purpose statements from project-specific README sections and relevant checked-in docs. Detect starter/boilerplate text and avoid promoting it to project purpose. Inspect manifests, executable entry points, public APIs, commands, handlers, tests and configuration as corroborating evidence. -- [ ] Represent repository role, entry points, important data/artifacts, outputs, external boundaries, and safe observation candidates as typed, bounded claims with provenance and uncertainty. Keep this structured state separate from Markdown. -- [ ] Identify a few central terms from repeated use across entries and outputs, then attach only supported descriptions. An entity declaration alone gives a code role, not business meaning. Preserve exact evidence for rejected or ambiguous descriptions. +- [x] Discover a small set of likely purpose statements from project-specific README sections and relevant checked-in docs. Detect starter/boilerplate text and avoid promoting it to project purpose. Inspect manifests, executable entry points, public APIs, commands, handlers, tests and configuration as corroborating evidence. +- [x] Represent repository role, entry points, important data/artifacts, outputs, external boundaries, and safe observation candidates as typed, bounded claims with provenance and uncertainty. Keep this structured state separate from Markdown. +- [x] Identify a few central terms from repeated use across entries and outputs, then attach only supported descriptions. An entity declaration alone gives a code role, not business meaning. Preserve exact evidence for rejected or ambiguous descriptions. **Gate:** On B2C, the inventory can support “shipment is central” and distinguish vendor/fleet/driver relations without defining their business contracts. On a CLI/library it identifies commands/public APIs and outputs. On a sparse repo it gives a useful inventory plus explicit questions, with no invented purpose. @@ -89,4 +89,4 @@ The same questions apply to a service, CLI, library, frontend, worker, or data j This plan does not add hosted services, implicit AI, runtime execution, new language-specific deep tracers, or a business ontology. A non-TypeScript repository can still get a useful overview from its own documentation, manifests, public entry points, tests, and artifacts; unsupported inner behavior remains a cited gap. Optional AI prose may be considered later only as an opt-in rewrite of vetted claims, never as a source of new facts. -Phase 0 is complete. The next implementation request can start **Phase 1 only**; later phases depend on its cited inventory, so the B2C example cannot quietly become the product template. +Phases 0 and 1 are complete. The next implementation request can start **Phase 2 only**; later phases depend on its supported story connections, so the B2C example cannot quietly become the product template. diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts index fea970b..cb456b8 100644 --- a/packages/core/src/index.ts +++ b/packages/core/src/index.ts @@ -15,6 +15,7 @@ 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..18bad4f --- /dev/null +++ b/packages/core/src/onboarding-story.ts @@ -0,0 +1,50 @@ +import type { Evidence } from "./index.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[]; +} diff --git a/packages/scanners/src/index.ts b/packages/scanners/src/index.ts index 89791c8..cdcd976 100644 --- a/packages/scanners/src/index.ts +++ b/packages/scanners/src/index.ts @@ -53,6 +53,7 @@ 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, diff --git a/packages/scanners/src/onboarding-story.test.ts b/packages/scanners/src/onboarding-story.test.ts new file mode 100644 index 0000000..4d269b4 --- /dev/null +++ b/packages/scanners/src/onboarding-story.test.ts @@ -0,0 +1,104 @@ +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { describe, expect, it } from "vitest"; + +import type { OnboardingConceptEvidence } from "@transferkit/core"; +import { selectOnboardingStoryInventory } from "@transferkit/standards"; + +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 inventory", () => { + it("identifies a CLI command, documented input and output without HTTP assumptions", async () => { + const evidence = await discoverOnboardingStoryEvidence( + join(root, "onboarding-human-cli"), + [], + empty, + ); + const inventory = selectOnboardingStoryInventory(evidence); + expect(inventory.purpose?.text).toContain("event file"); + expect(inventory.entries[0]?.name).toBe("event-count"); + expect( + inventory.artifacts.some((claim) => claim.text.includes("event file")), + ).toBe(true); + expect( + inventory.outputs.some((claim) => claim.text.includes("prints a count")), + ).toBe(true); + expect(inventory.entries[0]?.evidence).toContainEqual({ + file: "src/cli.js", + line: 1, + }); + }); + + it("finds a documented Python entry while leaving unsupported internals unknown", async () => { + const evidence = await discoverOnboardingStoryEvidence( + join(root, "onboarding-human-sparse"), + [], + empty, + ); + const inventory = selectOnboardingStoryInventory(evidence); + expect(inventory.purpose?.text).toContain("compares item counts"); + expect(inventory.entries.map((claim) => claim.name)).toContain( + "compare.py", + ); + expect( + inventory.outputs.some((claim) => claim.text.includes("standard output")), + ).toBe(true); + expect(inventory.boundaries).toEqual([]); + }); + + it("uses a plain Node service description without inventing persistent state", async () => { + const evidence = await discoverOnboardingStoryEvidence( + join(root, "onboarding-plain-node"), + [], + empty, + ); + const inventory = selectOnboardingStoryInventory(evidence); + expect(inventory.roles[0]?.text).toContain("service"); + expect( + inventory.entries.some((claim) => claim.text.includes("src/server.js")), + ).toBe(true); + expect( + inventory.outputs.some((claim) => claim.text.includes("health check")), + ).toBe(true); + expect(inventory.boundaries).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, + ); + const inventory = selectOnboardingStoryInventory(evidence); + expect(inventory.purpose).toBeUndefined(); + expect( + inventory.rejectedDescriptions.some( + (item) => item.reason === "generic starter text", + ), + ).toBe(true); + expect( + inventory.entries.some( + (claim) => claim.name === "ParcelController.dispatch", + ), + ).toBe(true); + expect( + inventory.entries.some((claim) => claim.text.includes("scheduled")), + ).toBe(true); + expect(inventory.terms.some((term) => term.name === "Parcel")).toBe(true); + expect( + inventory.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..ac9a581 --- /dev/null +++ b/packages/scanners/src/onboarding-story.ts @@ -0,0 +1,526 @@ +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 { + 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; + 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; + 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(); + 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 = { + purpose: 8, + role: 6, + entry: 80, + artifact: 80, + output: 12, + boundary: 24, + observation: 20, + }; + const counts: Record = { + 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 { + 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 { + 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 { + 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 { + return value && typeof value === "object" && !Array.isArray(value) + ? (value as Record) + : {}; +} + +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/standards/src/index.ts b/packages/standards/src/index.ts index 3aa32f8..cdb4718 100644 --- a/packages/standards/src/index.ts +++ b/packages/standards/src/index.ts @@ -28,6 +28,7 @@ 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 { selectOnboardingContinuations } from "./onboarding-continuations.js"; export { selectScheduledConcepts } from "./onboarding-scheduled.js"; export { 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..d37d5fc --- /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", 8), + terms, + rejectedDescriptions: evidence.rejectedDescriptions, + unknowns, + }; +} + +function unique(claims: OnboardingStoryClaim[]): OnboardingStoryClaim[] { + const seen = new Set(); + 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); +} From 80a551587508f4a6559940203a4e94ae4fed8b7e Mon Sep 17 00:00:00 2001 From: alialaraby Date: Sat, 3 Oct 2026 01:25:29 +0300 Subject: [PATCH 3/7] Select evidence-backed onboarding stories --- docs/ONBOARDING_HUMAN_STORY_PLAN.md | 14 +- packages/cli/src/generate-onboarding-guide.ts | 42 +- packages/core/src/onboarding-story.ts | 37 ++ packages/scanners/src/index.ts | 8 +- packages/standards/src/index.ts | 1 + .../src/onboarding-journey-selection.ts | 24 ++ .../src/onboarding-story-selection.test.ts | 253 ++++++++++++ .../src/onboarding-story-selection.ts | 389 ++++++++++++++++++ 8 files changed, 746 insertions(+), 22 deletions(-) create mode 100644 packages/standards/src/onboarding-story-selection.test.ts create mode 100644 packages/standards/src/onboarding-story-selection.ts diff --git a/docs/ONBOARDING_HUMAN_STORY_PLAN.md b/docs/ONBOARDING_HUMAN_STORY_PLAN.md index 23b30ac..68bae63 100644 --- a/docs/ONBOARDING_HUMAN_STORY_PLAN.md +++ b/docs/ONBOARDING_HUMAN_STORY_PLAN.md @@ -1,6 +1,6 @@ # Human-first onboarding guide enhancement plan -**Status:** Phases 0–1 complete; Phases 2–5 pending. The [Phase 0 acceptance baseline](ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md) records cross-repository answer keys and measurements. Phase 1 adds a typed, cited story inventory in core, scanners, and standards; guide rendering remains for Phase 3. This follows the existing [repository-only deep guide work](ONBOARDING_DEEP_GUIDE_PLAN.md). Its source traces, evidence rules, personal workspace, and safe regeneration remain the foundation. Milestone 9's real unfamiliar-engineer assessment is still open. +**Status:** Phases 0–2 complete; Phases 3–5 pending. The [Phase 0 acceptance baseline](ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md) records cross-repository answer keys and measurements. Phase 1 adds a typed, cited story inventory; Phase 2 selects bounded story chapters and classifies supported or unproven connections. Human-first guide rendering remains for Phase 3. This follows the existing [repository-only deep guide work](ONBOARDING_DEEP_GUIDE_PLAN.md). Its source traces, evidence rules, personal workspace, and safe regeneration remain the foundation. Milestone 9's real unfamiliar-engineer assessment is still open. ## Why this change is needed @@ -53,13 +53,15 @@ The same questions apply to a service, CLI, library, frontend, worker, or data j ### Phase 2 — Connect and select stories, not just deep traces -- [ ] Group paths by *supported* shared state, call/event continuation, or documented workflow. Record edge type: direct call, possible asynchronous continuation, shared artifact, documented relation, or unproven association. -- [ ] Choose a representative entry and complementary path for newcomer coverage: where work starts, a key decision, state/output, and a failure or alternate path. Let a documented purpose and core record weigh more than raw method/branch count. Retain `--focus` for a developer's specific question. -- [ ] Do not force a single sequence. If creation, callback, and invoice are independent entry points touching the same record, show them as separate chapters around that record. If an edge is missing, state the first unsupported boundary and what to inspect next. -- [ ] Keep deep trace limits and negative cases: no false path joining, callback execution, transaction completion, provider delivery, or dynamic target certainty. +- [x] Group paths by *supported* shared state, call/event continuation, or documented workflow. Record edge type: direct call, possible asynchronous continuation, shared artifact, documented relation, or unproven association. +- [x] Choose a representative entry and complementary path for newcomer coverage: where work starts, a key decision, state/output, and a failure or alternate path. Let a documented purpose and core record weigh more than raw method/branch count. Retain `--focus` for a developer's specific question. +- [x] Do not force a single sequence. If creation, callback, and invoice are independent entry points touching the same record, show them as separate chapters around that record. If an edge is missing, state the first unsupported boundary and what to inspect next. +- [x] Keep deep trace limits and negative cases: no false path joining, callback execution, transaction completion, provider delivery, or dynamic target certainty. **Gate:** B2C selection explains shipment creation/assignment and distinguishes mobile status from external callbacks; Debtbox selects a coherent ownership-relevant path; a CLI/library follows its own input-to-output shape. Selected paths may differ when repository evidence differs, but each selection has a recorded reason. +**Phase 2 check:** On pinned snapshots, B2C selects shipment creation, fleet assignment, mobile pickup, and the external webhook as separate entries. Debtbox starts with debt creation and consent. The non-Nest CLI and sparse Python cases retain documented input/output chapters with an explicit source-trace boundary. The final seven-case regression found no broken source links; B2C generation was 6.605 s and 713.2 MiB peak RSS. These checks assess selection and citations, not newcomer usefulness. + ### Phase 3 — Render the human reading path - [ ] Introduce a short “What this repo does” and “How to read it” opening from Phase 1 claims, with visible inference/unknown labels where needed. @@ -89,4 +91,4 @@ The same questions apply to a service, CLI, library, frontend, worker, or data j This plan does not add hosted services, implicit AI, runtime execution, new language-specific deep tracers, or a business ontology. A non-TypeScript repository can still get a useful overview from its own documentation, manifests, public entry points, tests, and artifacts; unsupported inner behavior remains a cited gap. Optional AI prose may be considered later only as an opt-in rewrite of vetted claims, never as a source of new facts. -Phases 0 and 1 are complete. The next implementation request can start **Phase 2 only**; later phases depend on its supported story connections, so the B2C example cannot quietly become the product template. +Phases 0–2 are complete. The next implementation request can start **Phase 3 only**; later phases depend on its human reading path, so the B2C example cannot quietly become the product template. diff --git a/packages/cli/src/generate-onboarding-guide.ts b/packages/cli/src/generate-onboarding-guide.ts index bc2fa9d..4184bfb 100644 --- a/packages/cli/src/generate-onboarding-guide.ts +++ b/packages/cli/src/generate-onboarding-guide.ts @@ -2,17 +2,22 @@ import { randomUUID } from "node:crypto"; import { mkdir, readFile, rename, unlink, writeFile } from "node:fs/promises"; import { dirname, join } from "node:path"; -import type { OnboardingSelectedConcept } from "@transferkit/core"; +import type { + OnboardingSelectedConcept, + OnboardingStoryInventory, +} from "@transferkit/core"; import { renderOnboardingGuide } from "@transferkit/renderers"; import { discoverOnboardingRepositoryNotes, + discoverOnboardingStoryEvidence, scanOnboardingRepository, } from "@transferkit/scanners"; import { explainCandidateFlows, preselectOnboardingEntries, selectOnboardingContinuations, - selectOnboardingJourneys, + selectOnboardingStories, + selectOnboardingStoryInventory, selectScheduledConcepts, selectOnboardingConcepts, understandProject, @@ -43,38 +48,49 @@ export async function generateOnboardingGuide( ); let focusSymbol: string | undefined; + let storyInventory: OnboardingStoryInventory | undefined; const { findings, traces, concepts, queues, scheduledCalls } = - await scanOnboardingRepository(directory, (scanned, context) => { + 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 selection = selectOnboardingJourneys( + 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( - selection.selected.flatMap((item) => - selectOnboardingConcepts(item.trace, concepts), - ), + selected.flatMap((item) => selectOnboardingConcepts(item.trace, concepts)), ); const repositoryNotes = await discoverOnboardingRepositoryNotes( directory, - selection.selected.map((item) => item.trace), + selected.map((item) => item.trace), findings, ); const displayedSymbols = new Set([ ...(focusSymbol ? [focusSymbol] : []), - ...selection.selected.map((item) => item.trace.entry.symbol), - ...selection.rejected.map((item) => item.trace.entry.symbol), + ...selected.map((item) => item.trace.entry.symbol), + ...storySelection.rejected.map((item) => item.entry), ]); const displayFlowIds = model.candidateFlows .filter((flow) => @@ -98,7 +114,7 @@ export async function generateOnboardingGuide( findings, explainCandidateFlows(model, findings), { - journeys: selection.selected.map((item) => ({ + journeys: selected.map((item) => ({ trace: item.trace, reason: item.reason, continuations: selectOnboardingContinuations(item.trace, queues), @@ -110,8 +126,8 @@ export async function generateOnboardingGuide( selectedConcepts, ), displayFlowIds, - rejected: selection.rejected.map((item) => ({ - symbol: item.trace.entry.symbol, + rejected: storySelection.rejected.map((item) => ({ + symbol: item.entry, reason: item.reason, })), repositoryNotes, diff --git a/packages/core/src/onboarding-story.ts b/packages/core/src/onboarding-story.ts index 18bad4f..c82c9f2 100644 --- a/packages/core/src/onboarding-story.ts +++ b/packages/core/src/onboarding-story.ts @@ -1,4 +1,5 @@ import type { Evidence } from "./index.js"; +import type { OnboardingTrace } from "./onboarding-trace.js"; export type OnboardingStoryClaimKind = | "purpose" @@ -48,3 +49,39 @@ export interface OnboardingStoryInventory { 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/scanners/src/index.ts b/packages/scanners/src/index.ts index cdcd976..3a48e19 100644 --- a/packages/scanners/src/index.ts +++ b/packages/scanners/src/index.ts @@ -209,8 +209,9 @@ export async function scanOnboardingRepository( context: { queues: OnboardingQueueEvidence; scheduledCalls: readonly OnboardingScheduledCall[]; + concepts: OnboardingConceptEvidence; }, - ) => readonly string[]), + ) => readonly string[] | Promise), limits: Partial = {}, ): Promise<{ findings: RepositoryFinding[]; @@ -224,9 +225,10 @@ export async function scanOnboardingRepository( const { findings, contextFindings } = await scanRepositoryInAst(ast); const queues = discoverOnboardingQueuesInAst(ast); const scheduledCalls = discoverOnboardingScheduledCallsInAst(ast, findings); + const concepts = discoverOnboardingConceptsInAst(ast); const entries = typeof selectedEntries === "function" - ? selectedEntries(findings, { queues, scheduledCalls }) + ? await selectedEntries(findings, { queues, scheduledCalls, concepts }) : selectedEntries; const selected = contextFindings.filter( (route) => @@ -260,7 +262,7 @@ export async function scanOnboardingRepository( maxEntries: entries.length, ...limits, }), - concepts: discoverOnboardingConceptsInAst(ast), + concepts, queues, scheduledCalls, loadedFiles: ast.sourceFiles.length, diff --git a/packages/standards/src/index.ts b/packages/standards/src/index.ts index cdb4718..89c0275 100644 --- a/packages/standards/src/index.ts +++ b/packages/standards/src/index.ts @@ -29,6 +29,7 @@ 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 { diff --git a/packages/standards/src/onboarding-journey-selection.ts b/packages/standards/src/onboarding-journey-selection.ts index 6c418c8..6456166 100644 --- a/packages/standards/src/onboarding-journey-selection.ts +++ b/packages/standards/src/onboarding-journey-selection.ts @@ -3,6 +3,7 @@ import type { OnboardingConceptEvidence, OnboardingQueueEvidence, OnboardingScheduledCall, + OnboardingStoryInventory, OnboardingTrace, RouteTrace, } from "@transferkit/core"; @@ -35,6 +36,7 @@ export function preselectOnboardingEntries( queues: OnboardingQueueEvidence, scheduledCalls: readonly OnboardingScheduledCall[], focus?: string, + inventory?: OnboardingStoryInventory, ): { entries: string[]; candidates: OnboardingEntryCandidate[]; @@ -130,10 +132,32 @@ export function preselectOnboardingEntries( 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 ?? ""); 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); +} From 5b7433d8c3daf5360cf64fdcdd0a8d12079d6c7f Mon Sep 17 00:00:00 2001 From: alialaraby Date: Sat, 3 Oct 2026 01:45:29 +0300 Subject: [PATCH 4/7] Render human-first onboarding guide stories --- docs/ONBOARDING_HUMAN_STORY_PLAN.md | 16 +- .../cli/src/generate-onboarding-guide.test.ts | 28 + packages/cli/src/generate-onboarding-guide.ts | 2 + packages/renderers/src/onboarding-guide.ts | 24 +- .../renderers/src/onboarding-human-story.ts | 497 ++++++++++++++++++ .../scanners/src/onboarding-story.test.ts | 6 + packages/scanners/src/onboarding-story.ts | 56 ++ packages/standards/src/onboarding-story.ts | 2 +- 8 files changed, 616 insertions(+), 15 deletions(-) create mode 100644 packages/renderers/src/onboarding-human-story.ts diff --git a/docs/ONBOARDING_HUMAN_STORY_PLAN.md b/docs/ONBOARDING_HUMAN_STORY_PLAN.md index 68bae63..f26446a 100644 --- a/docs/ONBOARDING_HUMAN_STORY_PLAN.md +++ b/docs/ONBOARDING_HUMAN_STORY_PLAN.md @@ -1,6 +1,6 @@ # Human-first onboarding guide enhancement plan -**Status:** Phases 0–2 complete; Phases 3–5 pending. The [Phase 0 acceptance baseline](ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md) records cross-repository answer keys and measurements. Phase 1 adds a typed, cited story inventory; Phase 2 selects bounded story chapters and classifies supported or unproven connections. Human-first guide rendering remains for Phase 3. This follows the existing [repository-only deep guide work](ONBOARDING_DEEP_GUIDE_PLAN.md). Its source traces, evidence rules, personal workspace, and safe regeneration remain the foundation. Milestone 9's real unfamiliar-engineer assessment is still open. +**Status:** Phases 0–3 complete; Phases 4–5 pending. The [Phase 0 acceptance baseline](ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md) records cross-repository answer keys and measurements. Phase 1 adds a typed, cited story inventory; Phase 2 selects bounded story chapters and classifies supported or unproven connections; Phase 3 renders a human reading path. This follows the existing [repository-only deep guide work](ONBOARDING_DEEP_GUIDE_PLAN.md). Its source traces, evidence rules, personal workspace, and safe regeneration remain the foundation. Milestone 9's real unfamiliar-engineer assessment is still open. ## Why this change is needed @@ -64,14 +64,16 @@ The same questions apply to a service, CLI, library, frontend, worker, or data j ### Phase 3 — Render the human reading path -- [ ] Introduce a short “What this repo does” and “How to read it” opening from Phase 1 claims, with visible inference/unknown labels where needed. -- [ ] Replace the opening entity inventory with a three-to-five-term glossary: term, code role, supported meaning, and why the newcomer will encounter it. Move relation and field lists to the appendix. -- [ ] Render each selected story as **why this path matters → trigger/input → decision → state or output → alternate exit → external boundary → where to change/test**, using brief prose and nearby grouped citations. Keep the raw event trace available in collapsed details. -- [ ] Add a task-to-file/test map and one safe first investigation chosen from actual code and test evidence. Do not say tests are absent merely because the current trace did not discover them. -- [ ] Keep setup specific: engine/version and meaningful declared dependencies, documented versus verified commands, safe observation, and blockers. Preserve the current guide markers, snapshot reconciliation, owner sections, and all personal workspace data. +- [x] Introduce a short “What this repo does” and “How to read it” opening from Phase 1 claims, with visible inference/unknown labels where needed. +- [x] Replace the opening entity inventory with a three-to-five-term glossary: term, code role, supported meaning, and why the newcomer will encounter it. Move relation and field lists to the appendix. +- [x] Render each selected story as **why this path matters → trigger/input → decision → state or output → alternate exit → external boundary → where to change/test**, using brief prose and nearby grouped citations. Keep the raw event trace available in collapsed details. +- [x] Add a task-to-file/test map and one safe first investigation chosen from actual code and test evidence. Do not say tests are absent merely because the current trace did not discover them. +- [x] Keep setup specific: engine/version and meaningful declared dependencies, documented versus verified commands, safe observation, and blockers. Preserve the current guide markers, snapshot reconciliation, owner sections, and all personal workspace data. **Gate:** A reviewer answers the five Phase 0 questions from the opening and stories without reading the appendix. Every behavioral sentence is supported by its cited code or clearly labeled as a repository/owner statement or inference. No human edit disappears on regeneration. +**Phase 3 check:** Seven disposable repository cases generated with no broken source links; the featured B2C and Debtbox entries, CLI input/error path, sparse Python fallback, and plain Node setup were inspected. B2C generation was 6.607 s / 718.3 MiB peak RSS; Debtbox was 1.333 s / 308.2 MiB. The full 287-test suite, typecheck, lint, and format check pass, including guide regeneration and owner-note preservation. The generated guides and measurements are reproducible at `/tmp/tk-human-phase3-verified/` with the Phase 0 regression command. This is source-based review, not the independent newcomer assessment in Phase 5. + ### Phase 4 — Align personal learning with the story - [ ] Make the existing stable `v2:` exercises point to the new mental model, selected stories, change map, and safe observation. Keep their IDs, checked boxes, notes, questions, evidence and legacy progress intact. @@ -91,4 +93,4 @@ The same questions apply to a service, CLI, library, frontend, worker, or data j This plan does not add hosted services, implicit AI, runtime execution, new language-specific deep tracers, or a business ontology. A non-TypeScript repository can still get a useful overview from its own documentation, manifests, public entry points, tests, and artifacts; unsupported inner behavior remains a cited gap. Optional AI prose may be considered later only as an opt-in rewrite of vetted claims, never as a source of new facts. -Phases 0–2 are complete. The next implementation request can start **Phase 3 only**; later phases depend on its human reading path, so the B2C example cannot quietly become the product template. +Phases 0–3 are complete. The next implementation request can start **Phase 4 only**; the B2C example remains a reviewer reference, not a product template. diff --git a/packages/cli/src/generate-onboarding-guide.test.ts b/packages/cli/src/generate-onboarding-guide.test.ts index edfc1e8..8a98fcd 100644 --- a/packages/cli/src/generate-onboarding-guide.test.ts +++ b/packages/cli/src/generate-onboarding-guide.test.ts @@ -20,6 +20,30 @@ async function guide(directory: string): Promise { } 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( @@ -63,6 +87,10 @@ describe("shared guide regeneration", () => { ); expect(generated).toContain(' `${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", + "", + '', + "", + ...(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", + "", + '', + "", + 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", + "", + '', + "", + ...setupOpening(inventory), + setupBody(sections.get("Setup and operations"), inventory), + "", + "## Specific questions", + "", + '', + "", + ...inventory.unknowns.map((item) => `- **Unknown:** ${clean(item)}`), + sections.get("Unknowns") ?? "", + "", + "## Reference appendix", + "", + "
Inventories, candidate routes, and supporting declarations", + "", + ...(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.", + "", + "
", + "", + ]; + 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 [ + ``, + "", + `### ${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 { + 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, ">"); +} diff --git a/packages/scanners/src/onboarding-story.test.ts b/packages/scanners/src/onboarding-story.test.ts index 4d269b4..7d9e792 100644 --- a/packages/scanners/src/onboarding-story.test.ts +++ b/packages/scanners/src/onboarding-story.test.ts @@ -37,6 +37,12 @@ describe("cited onboarding story inventory", () => { file: "src/cli.js", line: 1, }); + expect(inventory.observations).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 () => { diff --git a/packages/scanners/src/onboarding-story.ts b/packages/scanners/src/onboarding-story.ts index ac9a581..bcf4868 100644 --- a/packages/scanners/src/onboarding-story.ts +++ b/packages/scanners/src/onboarding-story.ts @@ -36,6 +36,37 @@ export async function discoverOnboardingStoryEvidence( 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; @@ -110,6 +141,31 @@ export async function discoverOnboardingStoryEvidence( if (packageSource) { try { const pkg = JSON.parse(packageSource) as Record; + 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 && diff --git a/packages/standards/src/onboarding-story.ts b/packages/standards/src/onboarding-story.ts index d37d5fc..c9e8f19 100644 --- a/packages/standards/src/onboarding-story.ts +++ b/packages/standards/src/onboarding-story.ts @@ -60,7 +60,7 @@ export function selectOnboardingStoryInventory( artifacts, outputs, boundaries: selected("boundary", 8), - observations: selected("observation", 8), + observations: selected("observation", 16), terms, rejectedDescriptions: evidence.rejectedDescriptions, unknowns, From f4b8e54e890b0814f138868bb846fd2fcd73874e Mon Sep 17 00:00:00 2001 From: alialaraby Date: Sat, 3 Oct 2026 01:51:42 +0300 Subject: [PATCH 5/7] Align personal onboarding with guide stories --- docs/ONBOARDING_HUMAN_STORY_PLAN.md | 10 ++-- .../src/generate-onboarding-workspace.test.ts | 60 ++++++++++++++++++- packages/cli/src/onboarding-v2-cli.test.ts | 2 +- packages/cli/src/onboarding-v2-view.ts | 2 +- packages/standards/src/personal-onboarding.ts | 34 +++++++---- 5 files changed, 88 insertions(+), 20 deletions(-) diff --git a/docs/ONBOARDING_HUMAN_STORY_PLAN.md b/docs/ONBOARDING_HUMAN_STORY_PLAN.md index f26446a..396923d 100644 --- a/docs/ONBOARDING_HUMAN_STORY_PLAN.md +++ b/docs/ONBOARDING_HUMAN_STORY_PLAN.md @@ -1,6 +1,6 @@ # Human-first onboarding guide enhancement plan -**Status:** Phases 0–3 complete; Phases 4–5 pending. The [Phase 0 acceptance baseline](ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md) records cross-repository answer keys and measurements. Phase 1 adds a typed, cited story inventory; Phase 2 selects bounded story chapters and classifies supported or unproven connections; Phase 3 renders a human reading path. This follows the existing [repository-only deep guide work](ONBOARDING_DEEP_GUIDE_PLAN.md). Its source traces, evidence rules, personal workspace, and safe regeneration remain the foundation. Milestone 9's real unfamiliar-engineer assessment is still open. +**Status:** Phases 0–4 complete; Phase 5 pending. The [Phase 0 acceptance baseline](ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md) records cross-repository answer keys and measurements. Phase 1 adds a typed, cited story inventory; Phase 2 selects bounded story chapters and classifies supported or unproven connections; Phase 3 renders a human reading path; Phase 4 aligns personal exercises with it. This follows the existing [repository-only deep guide work](ONBOARDING_DEEP_GUIDE_PLAN.md). Its source traces, evidence rules, personal workspace, and safe regeneration remain the foundation. Milestone 9's real unfamiliar-engineer assessment is still open. ## Why this change is needed @@ -76,11 +76,13 @@ The same questions apply to a service, CLI, library, frontend, worker, or data j ### Phase 4 — Align personal learning with the story -- [ ] Make the existing stable `v2:` exercises point to the new mental model, selected stories, change map, and safe observation. Keep their IDs, checked boxes, notes, questions, evidence and legacy progress intact. -- [ ] When source selection changes, preserve completed work and flag stale links. A checked exercise remains self-reported progress, never a competence certificate. +- [x] Make the existing stable `v2:` exercises point to the new mental model, selected stories, change map, and safe observation. Keep their IDs, checked boxes, notes, questions, evidence and legacy progress intact. +- [x] When source selection changes, preserve completed work and flag stale links. A checked exercise remains self-reported progress, never a competence certificate. **Gate:** A newcomer can record what they understood, tried, and still need to ask without copying the whole guide. Sync and conflict tests continue to protect both Markdown and structured progress. +**Phase 4 check:** Existing exercise IDs and progress storage remain unchanged. A disposable CLI guide exercise links its documented entry and the change map; after the guide entry is changed, status reports the stale link while keeping its completed checkbox, structured state, question, evidence, and note. Build, typecheck, lint, formatting, and all 288 tests pass, including sync and conflict tests. This checks preservation and navigation; independent newcomer utility remains Phase 5. + ### Phase 5 — Independent accuracy, utility, and performance review - [ ] Run all acceptance repositories from disposable snapshots. Compare old/new answers, guide size and first-screen readability, generation time, peak RSS, and exact citations. Manually inspect every material claim in the featured stories against source; record omissions and misleading wording. @@ -93,4 +95,4 @@ The same questions apply to a service, CLI, library, frontend, worker, or data j This plan does not add hosted services, implicit AI, runtime execution, new language-specific deep tracers, or a business ontology. A non-TypeScript repository can still get a useful overview from its own documentation, manifests, public entry points, tests, and artifacts; unsupported inner behavior remains a cited gap. Optional AI prose may be considered later only as an opt-in rewrite of vetted claims, never as a source of new facts. -Phases 0–3 are complete. The next implementation request can start **Phase 4 only**; the B2C example remains a reviewer reference, not a product template. +Phases 0–4 are complete. The next implementation request can start **Phase 5 only**; the B2C example remains a reviewer reference, not a product template. diff --git a/packages/cli/src/generate-onboarding-workspace.test.ts b/packages/cli/src/generate-onboarding-workspace.test.ts index 797daee..6190a51 100644 --- a/packages/cli/src/generate-onboarding-workspace.test.ts +++ b/packages/cli/src/generate-onboarding-workspace.test.ts @@ -74,7 +74,7 @@ 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", ); @@ -176,6 +176,64 @@ describe("personal onboarding workspace", () => { 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(""); + 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/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 156af08..a0d4a10 100644 --- a/packages/cli/src/onboarding-v2-view.ts +++ b/packages/cli/src/onboarding-v2-view.ts @@ -67,7 +67,7 @@ export async function readOnboardingV2View(directory: string): Promise<{ const currentJourneys = new Set( [ ...(sections.get("explained-flow") ?? "").matchAll( - /^### Source journey: (.+)$/gmu, + /^### (?:Source journey|Entry to inspect): (.+)$/gmu, ), ].map((match) => match[1]!), ); diff --git a/packages/standards/src/personal-onboarding.ts b/packages/standards/src/personal-onboarding.ts index 63656de..6c4905b 100644 --- a/packages/standards/src/personal-onboarding.ts +++ b/packages/standards/src/personal-onboarding.ts @@ -27,7 +27,7 @@ export function personalOnboardingExercises( : "unknowns"; const journeys = [ ...(guideSections?.get("explained-flow") ?? "").matchAll( - /^### Source journey: (.+)$/gmu, + /^### (?:Source journey|Entry to inspect): (.+)$/gmu, ), ] .map((match) => match[1]!) @@ -37,27 +37,33 @@ export function personalOnboardingExercises( ] .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: concepts.length - ? `Map ${concepts.join(", ")} from cited declarations to the entry point and selected journeys; label uncertain relationships.` - : "Explain the entry point, major components, and supported relationships using the guide's evidence labels.", + ? `${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: journeys.length >= 2 - ? `Explain ${journeys[0]} and ${journeys[1]} from cited source, including an alternate exit and the first unsupported edge in each.` + ? `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]} from cited source, including an alternate exit and its first unsupported edge; identify what second path is missing.` + ? `Explain ${journeys[0]}: input, output or state, alternate exit, and first unsupported edge. Mark repository statements separately from traced behavior.` : hasExplainedFlow - ? "Check one explained static flow against its cited source and identify its branch and effect gaps." + ? "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.", @@ -65,14 +71,14 @@ export function personalOnboardingExercises( ...(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.", @@ -81,11 +87,13 @@ export function personalOnboardingExercises( id: personalOnboardingExerciseIds[3], title: "Identify remaining ownership gaps", objective: journeys.length - ? `Find a likely change and test location for ${journeys[0]}; classify remaining questions as source, runtime, or person-dependent.` - : "Identify a likely change point if possible; classify remaining questions as source, runtime, or person-dependent.", - guideSectionId: "unknowns", + ? `${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.", }, ]; } From de66bcce691cd4213cbcda8ae4cc9b1b9929d28d Mon Sep 17 00:00:00 2001 From: alialaraby Date: Sat, 3 Oct 2026 02:14:18 +0300 Subject: [PATCH 6/7] Prepare 0.3.0 release candidate --- .gitignore | 9 + README.md | 97 +++-- .../B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md | 103 ----- docs/MILESTONE_7_VALIDATION.md | 89 ---- docs/ONBOARDING_DEEP_GUIDE_PLAN.md | 397 ------------------ docs/ONBOARDING_DEPTH_BASELINE.md | 161 ------- .../ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md | 118 ------ docs/ONBOARDING_HUMAN_STORY_PLAN.md | 98 ----- docs/ONBOARDING_PHASE6_ACCEPTANCE.md | 36 -- docs/ONBOARDING_V2.md | 49 --- docs/ONBOARDING_V2_DEBTBOX_FIXTURE.md | 109 ----- docs/getting-started.md | 30 +- examples/workflow.md | 32 +- package-lock.json | 92 +--- package.json | 2 +- packages/cli/CHANGELOG.md | 17 + packages/cli/README.md | 38 +- packages/cli/package.json | 4 +- packages/cli/src/index.ts | 13 +- packages/cli/src/terminal-progress.test.ts | 38 ++ packages/cli/src/terminal-progress.ts | 51 +++ 21 files changed, 241 insertions(+), 1342 deletions(-) delete mode 100644 docs/B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md delete mode 100644 docs/MILESTONE_7_VALIDATION.md delete mode 100644 docs/ONBOARDING_DEEP_GUIDE_PLAN.md delete mode 100644 docs/ONBOARDING_DEPTH_BASELINE.md delete mode 100644 docs/ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md delete mode 100644 docs/ONBOARDING_HUMAN_STORY_PLAN.md delete mode 100644 docs/ONBOARDING_PHASE6_ACCEPTANCE.md delete mode 100644 docs/ONBOARDING_V2.md delete mode 100644 docs/ONBOARDING_V2_DEBTBOX_FIXTURE.md create mode 100644 packages/cli/src/terminal-progress.test.ts create mode 100644 packages/cli/src/terminal-progress.ts 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 a923bef..6b32e13 100644 --- a/README.md +++ b/README.md @@ -1,72 +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 shared repository-evidence guide and a separate personal learning workspace. 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. - -## Quick start +Run TransferKit **from the root of the repository you want to examine**. Use `tk handover --help` or `tk onboard --help` for command syntax. -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 -tk onboard sync -``` +| 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. | -`onboard guide` generates a shared `ONBOARDING.md` from repository evidence; `onboard guide --focus <route-or-symbol>` selects a supported entry to inspect. `onboard workspace` creates the personal Markdown checklist in `.transferkit.local/`. Edit its checkboxes, then run `onboard sync` and `onboard status`. The guide describes static source paths and declared setup commands; it does not run the application or verify outcomes. +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. -See the [workflow example](examples/workflow.md) for representative output and [getting started](docs/getting-started.md) for a fuller walkthrough. +## Release notes — 0.3.0 candidate -## What's new in 0.2.0 +- 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. -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. +See the [package changelog](packages/cli/CHANGELOG.md) for compatibility details. This release candidate has not been merged or published. -## Local-first and private by default +## Files, privacy, and limits -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. +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. -Review generated handover files before committing them. Automated secret protection is deliberately lightweight and is not a replacement for repository secret scanning. +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. -## Documentation +## More documentation - [Getting started](docs/getting-started.md) - [Concepts](docs/concepts.md) @@ -74,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/B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md b/docs/B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md deleted file mode 100644 index f0f307e..0000000 --- a/docs/B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md +++ /dev/null @@ -1,103 +0,0 @@ -# B2C backend — a newcomer’s working guide - -> **Reference example for TransferKit’s human-facing output.** Prepared from the B2C backend source at `79cc98e534a95a2a316c3464281619fb86a12d99` and the repository’s testing guide. This is an engineer’s interpretation of checked-in behavior, not an approved statement of company policy. Paths below are relative to the B2C backend repository. An owner should confirm the business terms and operational procedures before this becomes team documentation. - -## The system in two minutes - -This service coordinates B2C shipments. A shipment is the record that ties together vendor/customer relations, pickup and drop-off locations, an assigned fleet and possibly a driver, a history of status changes, and the prices later used for invoices. The API is a NestJS application backed by PostgreSQL; some work also enters through RabbitMQ consumers and external integration callbacks. Redis appears in assignment/pricing and other supporting paths. See `src/module/data/entity/shipment.entity.ts:103–170,245–294,331–403,434–438`, `src/main.ts:245–269`, and `src/app.module.ts:180–225`. - -The useful mental model is **shipment → assignment → pickup → delivery or exception → financial settlement**. That is a reading order, not a promise that every shipment follows one linear path. Mobile drivers and external fleets report progress through different code paths. Cancellations, missed pickups, future delivery, and return to origin change the path. The status vocabulary is in `src/data/enum/shipment.ts:70–97`; the behavior that accepts a status depends on the entry path. - -If you have one hour, read [the domain terms](#five-terms-to-learn), then [the two status paths](#4-delivery-progress-know-which-status-path-you-are-reading), and then [your first safe investigation](#your-first-safe-investigation). Do not start by reading every entity or module. - -## Five terms to learn - -| Term | What it means for your first investigation | Where to check | -| --- | --- | --- | -| **Shipment** | The central delivery record. It holds current associations and a `latestHistoryAction`, while separate history rows explain how that state was reached. Treat the current field and the history as two views to reconcile when debugging. | `src/module/data/entity/shipment.entity.ts:103,293,364–403`; `src/module/data/entity/shipment-history.entity.ts:24–55` | -| **Vendor, customer, seller** | These are distinct relations in the model. The vendor has configuration that can change pickup requirements; the shipment also has customer and seller-side pickup information. Do not assume the terms are interchangeable or that “customer” always means the recipient. | `src/module/data/entity/shipment.entity.ts:157,232,387`; `src/module/data/entity/vendor.entity.ts:31–80`; `src/module/shipment/services/pickup.service.ts:165–191` | -| **Fleet, driver, truck** | A fleet can be assigned without a driver. Supplying a driver introduces additional membership and truck-type checks; a successful assignment records fleet history and optionally driver history. | `src/module/fleet/services/mobile-fleet.service.ts:67–150,188–239` | -| **AWB and proof** | The AWB is used to identify/validate a shipment at pickup and in external callbacks. Pickup can require an AWB scan, photos, or OTP depending on vendor configuration. | `src/module/shipment/services/pickup.service.ts:60–75,150–225`; `src/module/integrations/integrations.service.ts:653–665` | -| **Price, transaction, invoice** | Shipment transactions carry customer and fleet amounts; invoices have separate customer and fleet types. Changing assignment or invoice logic can affect financial records, so trace the applicable transaction before altering totals. | `src/module/data/entity/shipment-transaction.entity.ts:19–47`; `src/data/enum/invoice.ts:1–18`; `src/module/invoice/invoice.service.ts:760–825` | - -### A simple map - -```text -Request / queue message / fleet callback - ↓ - controller or consumer - ↓ - feature service rules - ↓ - PostgreSQL shipment + history + related records - ↓ - provider update / notification / integration -``` - -The diagram is a navigation aid. Those side effects are conditional, and the code does not guarantee that a provider update, notification, or integration succeeds just because the database operation did. Start at `src/main.ts:116–150,245–269`, `src/app.module.ts:180–280`, and the selected services below. - -## Follow one shipment through the code - -### 1. Creation: establish identity before assignment - -Start with `ShipmentB2cService.addShipmentB2C` in `src/module/shipment/services/shipment-b2c.service.ts:648`. It checks existing workflow, order-reference, and eRx identifiers before building the shipment and its metadata (`:663–717`). That early duplicate handling matters: when investigating an apparently missing or duplicated request, determine whether the caller got an existing shipment, a rejected conflict, or a new one before looking at downstream assignment. This method is large; read its early identity checks and the resulting saved records first, then follow only the branch for your incident. - -**Ask an owner:** Which intake routes and integrations create most production B2C shipments? The code shows multiple entry mechanisms, but repository evidence alone does not rank them by volume or business importance. - -### 2. Assignment: a fleet accepts responsibility - -`MobileFleetController.assignFleetToShipment` delegates to `MobileFleetService.assignFleetToShipment` (`src/module/fleet/controllers/mobile-fleet.controller.ts:22–40`; `src/module/fleet/services/mobile-fleet.service.ts:67`). The service rejects a missing shipment, an already assigned shipment, or a missing fleet. When a driver is supplied, it also checks that the driver belongs to the fleet, has a truck, and that the truck type is allowed (`mobile-fleet.service.ts:78–149`). - -After those checks, the service saves assignment fields, may create or update a shipment transaction using cached pricing, and writes assignment history inside a query-runner transaction (`mobile-fleet.service.ts:151–239`). It commits at `:269`. Driver notification is attempted before that commit (`:244–260`), and a G2G integration call appears after it (`:271–280`). **For debugging, do not assume notification and external integration share the database transaction.** Check the actual outcome of each boundary. - -**Example question:** “Why does the fleet see a shipment but the driver does not?” Compare `shipment.fleet`, `shipment.driver`, the last assignment history, driver/truck checks, notification logs, and the external integration path. Do not infer driver assignment from fleet assignment alone. - -### 3. Pickup: the mobile driver must satisfy vendor rules - -The driver pickup endpoint calls `PickupService.confirmPickup` (`src/module/shipment/controllers/mobile-shipment.controller.ts:501–528`; `src/module/shipment/services/pickup.service.ts:150`). It first loads the shipment and authorizes the driver. Pickup is accepted only from the configured arrival states (`pickup.service.ts:153–162`). Vendor configuration can require an AWB scan, photos, or OTP; helper methods enforce those checks (`:165–191,340–374`). - -On the allowed path, the method records pickup evidence and appends `OrderPickedUp` through `ShipmentHistoryService.addNewStatus` (`pickup.service.ts:194–251`). It then tries to update provider status, but logs and swallows that failure (`:252–256`). A later POD OTP notification may also run asynchronously (`:258–269`). **A successful pickup response is evidence of the local path reaching its return; it is not proof that every external provider saw the update.** - -**Example question:** “Why is pickup blocked for this driver?” Check the driver authorization, latest status, vendor flags, and pickup evidence in that order. The error shown to the user may reflect a configuration gate rather than a broken endpoint. - -### 4. Delivery progress: know which status path you are reading - -The internal mobile path uses shipment actions such as pickup and delivery controllers (`src/module/shipment/controllers/mobile-shipment.controller.ts:217–258,425–528`). External fleets can call `IntegrationsController.webhook` (`src/module/integrations/integrations.controller.ts:113–123`), which delegates to `IntegrationsService.webhook` (`integrations.service.ts:630`). These are related ways to update shipment progress, **not one continuous call chain**. - -The webhook loads the shipment, checks the fleet/integration type and AWB, and may return early before changing history (`integrations.service.ts:632–665`). It handles cancellations and return-to-origin cases, rejects certain repeated or terminal-state updates, and attempts to insert B2C history (`:689–780`). Some delivered callbacks also calculate price or save proof data; external Shmool shipments have a special proof path (`:797–862`). Provider synchronization failures are logged rather than necessarily reversing the local status (`:863–872`). - -**Example question:** “The carrier says delivered, but our UI disagrees.” Start with the callback payload and receipt, then compare fleet identity, AWB, current latest history, attempted history insert, and provider-update logs. A 2xx transport response alone does not establish that a status was accepted; the method has early returns. - -### 5. Money: invoices are a separate workflow - -`InvoiceService.updateInvoice` is not the next automatic step in the pickup call chain. It is a separate financial workflow (`src/module/invoice/invoice.controller.ts:298–320`; `src/module/invoice/invoice.service.ts:723`). It checks permissions and allowed status transitions, and can recalculate amounts from selected shipments when a draft is edited (`invoice.service.ts:725–825`). Customer and fleet invoices use different transaction fields. Review the invoice type and selected shipment transactions before changing a total or status rule. - -## Your first safe investigation - -1. **Pick one real question.** Example: “What prevents an already assigned shipment from being assigned through the mobile fleet endpoint?” Read the controller, service guard, and related entity/history fields. Write down the expected error and where it originates. Do not change data. -2. **Run a narrow test before a service.** `package.json` declares `npm test` and `npm run build`; `docs/testing-strategy.md` shows how to run one Jest spec. Prefer a co-located service test for a business rule. Tests are uneven across this large repository, so a missing nearby spec is a prompt to add a characterization test when you change the behavior. -3. **Treat local boot as an environment task.** `package.json` requires Node 24. The `.env.example`, `src/config/typeorm.config.ts`, and `src/main.ts` show PostgreSQL, RabbitMQ, Redis, and Firebase configuration touchpoints. The README still contains Nest starter text, so its generic `npm run start` instructions do not constitute a verified B2C setup. Obtain a sanctioned local environment and test credentials before attempting an application start; never use production data for onboarding. -4. **If a configured local instance is already available, observe only.** `GET /health-check` returns `{ status: 'ok' }` in `src/module/health-check/health-check.controller.ts:20–29`. It shows that the HTTP handler responded, not that every dependency or background consumer works. The DB pool endpoint requires an app key and exposes internal capacity; use it only through the team’s approved access path (`:46–52`). -5. **Record the result.** Note the question, cited files, the command or request actually run, observed result, and any blocker. Separate observations from expected behavior. - -## Where to change common behavior - -| If the task concerns… | Start here | Check next | -| --- | --- | --- | -| Duplicate or missing B2C shipment creation | `src/module/shipment/services/shipment-b2c.service.ts:648–717` | Calling route/consumer, identity fields, repository query, new test | -| Fleet/driver assignment | `src/module/fleet/services/mobile-fleet.service.ts:67–285` | Controller, fleet/driver repositories, history, pricing cache, notifications | -| Pickup eligibility or evidence | `src/module/shipment/services/pickup.service.ts:150–269` | Vendor `PrimaryConfigs`, driver helper, history service, co-located tests | -| External fleet status | `src/module/integrations/integrations.service.ts:630–900` | Webhook controller, history insert, integration tests, provider logs | -| Invoice transition or amount | `src/module/invoice/invoice.service.ts:723–840` | Invoice type/status enums, transaction fields, invoice tests | - -Before editing a status rule, identify whether it is used by the driver app, external webhook, scheduled work, or more than one entry point. A change to a shared enum or history method can affect paths that are not visible from one controller. - -## Questions that still need a teammate - -- Which vendors and shipment types are the main supported B2C workflows, and what do **vendor**, **customer**, **seller**, and **receiver** mean to the business in each? -- Which service is authoritative when an external carrier status differs from local shipment history? What is the manual recovery path? -- Which provider callbacks and queues are required in a sanctioned local environment? Who owns their test credentials and contract examples? -- What should happen when driver notification, provider update, or post-commit integration fails after local state changes? -- Which team owns invoice rules and approves changes to customer versus fleet pricing? - -An engineer can navigate the source without these answers, but should not turn plausible code interpretations into business policy. 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_DEEP_GUIDE_PLAN.md b/docs/ONBOARDING_DEEP_GUIDE_PLAN.md deleted file mode 100644 index c9d0308..0000000 --- a/docs/ONBOARDING_DEEP_GUIDE_PLAN.md +++ /dev/null @@ -1,397 +0,0 @@ -# TransferKit onboarding: deep, evidence-backed system guide - -**Implementation plan and Codex prompts · 30 September 2026** - -## 1. Product contract - -An engineer with no handover should be able to use `tk onboard guide` and the personal onboarding workspace to understand the main concepts and connected behaviors of an unfamiliar Node.js/NestJS repository, locate a likely first change, attempt a local observation, and identify the few questions that code cannot answer. The shared guide must be valuable without a Current Owner, Transfer state, network service, paid API, or AI model. Human context may improve it but cannot be required. - -“Understand roughly 60%” is an aspiration, **not** a score emitted by the CLI. Acceptance depends on an unfamiliar engineer explaining important behavior and locating a change correctly. Static analysis cannot establish business intent, production topology, actual runtime effects, or ownership without suitable evidence. - -### Known starting point - -- Already reported as implemented: shared `ONBOARDING.md`; repository scans and candidate routes; two Debtbox static explained flows; documented setup clues; preservation of human Markdown through managed sections and snapshots; optional owner-written context and verified-setup sections; personal `.transferkit.local/ONBOARDING.md`, four stable `v2:` exercises, local JSON state and Markdown sync; v2-aware `plan` and `status`. Verify all details against current code before changing them. The uploaded guide predates some reported changes. -- Baseline at TransferKit `cb7c25e3`: plain Node fixture has no flow; small Nest fixture has empty handlers; Debtbox has two explanations; Madar B2C has three shallow candidates and no explanation. Madar generation was 5.705 s and 607.3 MiB peak RSS on one local run. These are reference measurements, not universal limits. -- An isolated TypeScript compiler API experiment resolves route-to-method and cross-file declarations. It detects Madar's conditional `queryRunner.manager.save` call sites and a Debtbox local helper, but has no execution-path model, cannot resolve local query-runner methods without dependencies, and loads 1,481 project TS files / approximately 497 MiB for one Madar route. It is **research, not production code**. The project already uses `ts-morph`; no new package is justified by that spike. -- `docs/ONBOARDING_V2.md` and historical `ROADMAP.md` portions may describe earlier status. Current code and current repository docs take precedence. The user considers Handover milestones 7 and 8 complete; this work stays within onboarding. - -### Boundaries - -- Only Node.js/TypeScript and supported NestJS patterns are promised in this sequence. A plain Node/JavaScript project must receive an honest, useful overview of what is actually discoverable; rich Nest behavior must not be falsely generalized to every Node project. Add a second runtime/framework adapter only after a representative fixture proves the need. -- No mandatory local AI, remote AI, paid service, auto-install, auto-running migrations, containers, or arbitrary project scripts. Existing local compute and libraries are sufficient for this plan. -- Do not change Handover behavior. Optional v3 Handover Item enrichment is a later, independent addition after repository-only onboarding succeeds. Do not block this plan on it. -- Preserve guide prose, managed section conflict handling, personal notes, progress, existing stable IDs, and legacy progress. Never silently overwrite or remap them. -- Scanner output is evidence; it is not the reader-facing product. Accuracy outranks breadth; depth must not turn a possible path into a guaranteed outcome. - -## 2. Final user experience and output contract - -### CLI journey - -1. `tk onboard guide` scans read-only and creates or safely updates a shared root `ONBOARDING.md`. An existing unmarked guide is never overwritten. A concurrent human/generated section conflict is surfaced without changing either version. -2. `tk onboard workspace` creates a personal Markdown workspace linked to stable guide anchors; repeated runs must preserve personal notes and progress or explicitly refuse a destructive reconciliation. -3. `tk onboard plan` shows the learning path for the repository, not a generic inventory of technologies. `tk onboard status` distinguishes self-reported exercise completion, recorded observations, and outstanding questions. `tk onboard sync` and `task` retain their current conflict and checkbox semantics. -4. The guide explains useful code paths without needing a handover file. A user may optionally select a route/symbol to focus on if automatic selection misses their work area; this must not invent a ranking of business importance. - -### Shared guide reading order - -1. **Start here:** a short orientation from reliable project text and observed interfaces. If the repository does not state its business purpose, describe the technical shape and explicitly leave purpose unknown. No story from names alone. -2. **System at a glance:** entry points, interfaces, data stores, background work, and boundaries. Show only supported relationships; a small diagram is optional when it conveys more than a table. -3. **Concepts:** a curated glossary of entities/data shapes and relationships relevant to selected journeys. Distinguish data shape from the business meaning of a term. -4. **Connected journeys:** several complementary paths where evidence exists. For each: entry, inputs, checks, alternate branches/early exits, state reads and writes, continuations across helpers/modules/queues/jobs, external boundaries, error behavior, exact gaps, and **where to change it** (code and relevant tests). A tiny service may need one journey; a large one may need more than two. No fixed number is a quality metric. -5. **Run and observe:** repository-specific documented prerequisites/commands, contradictions, a safe proposed first observation, and a clear distinction between documented and actually observed results. The shared owner-supplied verified setup remains optional. -6. **Remaining questions:** a short, deduplicated, answerable list derived from concrete gaps. Distinguish code to inspect, runtime to check, and business/operations to ask a person. -7. **Reference appendix:** full inventories of routes, modules, jobs, integrations, and citations in collapsed sections; no first-screen wall of names. - -### Illustrative final output (fictional repository) - -This compact example shows the expected **substance and order**. `ParcelWorks` and its file locations are fictional; Codex must ground actual golden fixtures in real test source. Large repositories would have more complementary journeys; small ones may have fewer. - -```markdown -# Understand ParcelWorks - -The README describes a service for delivery requests and fleet assignment -(`README.md:8`). The source exposes shipment and tracking routes, stores -Shipment and Assignment records, and declares an assignment worker. -Production behavior has not been observed. - -## Start here - -A request creates a pending Shipment. A separate worker may assign a Fleet. -A tracking update can later mark a Shipment delivered. Those are distinct -steps: saving a request does not prove that assignment or delivery occurred. - -## Concepts - -| Concept | What source establishes | Where it changes | -| --- | --- | --- | -| Shipment | Customer, destination and status fields (`shipment.entity.ts:12`) | Creation service; tracking handler | -| Assignment | Relates shipment, fleet and driver (`assignment.entity.ts:9`) | Assignment worker | - -## Journey 1 — Create a shipment - -**Entry:** `POST /shipments` → `ShipmentController.create` -(`shipment.controller.ts:28–36`). - -1. The controller calls `ShipmentService.create` (`:35` → - `shipment.service.ts:41`). -2. The service loads the customer and checks the destination. A missing - customer throws before the save (`shipment.service.ts:46–58`). -3. On the path past those checks, it assigns `PENDING` and awaits a - repository save (`shipment.service.ts:63–70`). -4. It calls `assignmentQueue.add` with the new ID (`:72–76`). The call is - visible; worker receipt is unverified. - -**If you change this:** inspect the DTO, `ShipmentService.create`, the entity, -the creation test, and the assignment worker that reads the saved ID. - -**Gap:** The save precedes the queue call. Source inspection alone cannot say -how an operator handles a saved shipment when the queue call fails. - -<details><summary>Code and tests</summary> - -- `src/shipment/dto/create-shipment.dto.ts:5–27` -- `src/shipment/shipment.service.ts:41–76` -- `src/shipment/shipment.service.spec.ts:30–104` - -</details> - -## Journey 2 — Assign a fleet - -The requested job name at `shipment.service.ts:73` matches the handler -registration at `assignment.processor.ts:18–22`. This is a possible code -continuation, not proof that the job ran. - -The worker loads the Shipment and returns if it is no longer pending (`:25–34`). -It asks `FleetSelectionService` for candidates. Its no-candidate branch does -not create an Assignment (`:37–49`). On a candidate branch it calls -`queryRunner.manager.save` for an Assignment and updates Shipment status -(`:54–71`). Commit, rollback and release calls are present (`:73–88`); -transaction outcomes remain unverified. - -**If you change assignment rules:** inspect `FleetSelectionService.select`, -the no-candidate path, Assignment fields, and worker tests. - -## Run and observe - -The README documents an install and start command. Compose declares Postgres -and Redis and references `.env`. Values and prerequisites are incomplete. -`GET /health` is a declared route (`health.controller.ts:12`), a possible first -check once setup is safe. TransferKit has run no command. Record your attempt -and actual result in `.transferkit.local/ONBOARDING.md`. - -## Questions left - -1. What should happen if the queue call fails after the Shipment save? -2. Who resolves the no-candidate branch, and how? -3. Where does a newcomer obtain safe local configuration? - -<details><summary>Other routes, jobs, modules and source references</summary> -The complete navigable inventory appears here. -</details> -``` - -The personal file should link to these real guide anchors and contain tasks such as “Explain creation and assignment,” “Locate a safe change,” and “Record a local observation or blocker,” with editable notes, questions and evidence. It must not duplicate the entire shared guide. - -### Evidence language - -Every substantive generated claim has a source type and navigable repository-relative evidence. Use four distinct meanings: - -| Source type | Allowed wording | Disallowed leap | -| --- | --- | --- | -| Code declaration/call | “The method calls `X`”; “the code assigns `status = Y` under condition Z” | “X succeeds”; “the shipment becomes Y in production” | -| Project documentation/comment/test | “The README says …”; “a nearby comment describes …”; “the test expects …” | Treating a statement or test as proof of current runtime behavior | -| Human-supplied/recorded observation | “Owner reports …”; “newcomer ran … and observed …” | Silently merging it with code-derived fact | -| Inference/unresolved edge | “These declarations suggest …”; “the receiver cannot be resolved” | A fabricated method link, provider identity, transaction outcome, or business rule | - -An `await` proves only that source awaits a call, not that external delivery succeeded. A `.save` call is a visible write attempt, not a committed write. A `commitTransaction` call is not a verified commit. A matched event publication/handler is a possible continuation, not proof of processing. - -## 3. Small internal model required to support the guide - -Build the smallest onboarding-specific intermediate representation that holds **path-aware claims** before rendering; do not create a generic whole-product graph framework. Keep core types framework-independent, scanners responsible for source findings, standards responsible for selection/explanation, renderers responsible for Markdown, and CLI responsible for orchestration. - -- **Location:** repository-relative path, line range, optional symbol, origin (`code`, `doc`, `test`, `person`, `observation`). Never read secret values into output. -- **Entry:** resolved route/handler, scheduled job, event/queue consumer, or an honest unknown starting point. Stable identity based on normalized route/symbol and source path, not raw line number alone. -- **Call edge:** caller symbol, call site, declared target if uniquely resolved, edge kind (`direct`, `declared target`, `candidate`, `unresolved`), and exact evidence. Constructor injection/module import is a declaration edge, never a call edge. A declared TypeScript method is not a guaranteed runtime override. -- **Path event:** read-like call, write-like call, assignment/status transition, guard, throw, return, catch/finally, external effect, publish/consume, or unsupported construct. Include branch context and source order **within that context**. Record `await` separately. Repeated calls to the same helper retain distinct call sites and calling contexts, even if its body is analyzed once. -- **Gap:** reason, first source location, affected journey and consequences for explanation. Include dynamic dispatch, alias uncertainty, unavailable dependency, recursion/depth/fan-out limit, unsupported control flow, and unverified runtime effect. -- **Journey:** entry plus ordered path segments, distinct branches/exits, cross-file continuation, related entities, tests, source claims, and gaps. No global flattened sequence across mutually exclusive branches. - -The tracer must not require a full control-flow theorem prover. Support common `if/else`, guard returns/throws, `try/catch/finally`, and simple call expressions; mark loops, switches, callbacks, dynamic dispatch, and complex expressions as bounded partial coverage unless implemented precisely. A limit stops traversal with a visible gap rather than silently dropping the rest. - -## 4. Ordered implementation slices and copy-ready Codex prompts - -**Handoff requirement:** Keep this file at `docs/ONBOARDING_DEEP_GUIDE_PLAN.md` in the local TransferKit checkout (or attach it to the Codex task and change the reference accordingly). The short prompts below are **not standalone specifications**. Codex must read the full product contract, internal model, slice deliverable/gate, and cross-cutting checklist before editing. If the file is unavailable, Codex should stop and ask for it rather than implement from a short prompt alone. Copying only one paragraph without the plan is insufficient. - -### Progress checklist - -Complete one slice and review its gate before starting the next. Check only a slice with a demonstrated passing gate; keep a failed or unrun gate open. - -- [x] Phase 1 — Acceptance contract and fixtures - - [x] Slice 0 — Lock acceptance contract and neutral fixtures -- [x] Phase 2 — Bounded, path-aware tracing (Slices 1–4) - - [x] Slice 1 — One bounded analysis context - - [x] Slice 2 — Path-aware trace representation - - [x] Slice 3 — Cross-file method continuation - - [x] Slice 4 — Local receiver aliases and transaction-like calls -- [x] Phase 3 — First deep guide and concepts (Slices 5–6) - - [x] Slice 5 — First deep journey in the guide - - [x] Slice 6 — Concepts and data effects -- [x] Phase 4 — Continuations, journey selection, and repository context (Slices 7–9) - - [x] Slice 7 — Continuations across jobs/events/queues - - [x] Slice 8 — Complementary journey selection and user focus - - [x] Slice 9 — Repository knowledge and orientation -- [x] Phase 5 — Setup, personal learning path, and reading experience (Slices 10–12) - - [x] Slice 10 — Practical setup and recorded observation - - [x] Slice 11 — Adaptive personal learning path - - [x] Slice 12 — Guide reading UX and regeneration -- [ ] Phase 6 — Regression and newcomer assessment (Slice 13) - - [ ] Slice 13 — Independent acceptance, regression, and release docs - - [x] Repeatable fixture and pinned application regression, with measurements and source spot checks - - [x] CLI/product documentation and unfamiliar-engineer protocol - - [ ] Real unfamiliar-engineer repository-only comparison and misleading-claim review - -The phase boxes summarize progress; the slice gates below control completion. Milestone 9 can close only after the repository-only guide and personal workspace pass their gates and a real unfamiliar engineer completes the repository-only assessment in Slice 13. Milestone 10 separately tests handover-assisted onboarding and broader real-world outcomes. If no engineer is available, record the assessment as pending and leave Milestone 9 open. - -Phase 2 gate evidence, including neutral negative cases, Madar/Debtbox excerpts, and measured budgets, is recorded in [the depth baseline follow-up](ONBOARDING_DEPTH_BASELINE.md#phase-2-structured-trace-review-2026-09-30). The structured trace is not rendered in the guide until Slice 5. - -Run one prompt at a time. Review the generated guide and acceptance evidence before the next. Each prompt is restricted to its item; do not let Codex pre-implement later slices. Codex should use the **current** checkout as truth, preserve unrelated changes, avoid commits, and report what it actually tested. If a slice's gate fails, fix that slice before moving forward. - -For **every** slice, the report back must include: (1) changed files and exact scope; (2) an actual generated or structured before/after excerpt, including a negative case; (3) tests and checks run with results; (4) measured performance when analysis changes; (5) unsupported patterns and remaining gaps; (6) whether the slice's gate passed. A test count or broad “works on Madar” statement alone is insufficient. Use neutral fixtures to prove generic behavior, then real repositories as regression checks. Do not copy private repository source or secrets into the public TransferKit fixtures. - -### Slice 0 — Lock the acceptance contract and fixtures - -**Deliverable:** Refresh onboarding design and Milestone 9 checklist to reflect the current implementation, the target output above, and the baseline/spike. Add or adapt neutral fixtures for branch exits, helper calls, aliases, transaction-like manager calls, and a cross-boundary continuation. Include a plain JavaScript/Node fixture with source entry point and documented run command, so overview usefulness is tested on more than a package-only fixture. Do not rewrite historical roadmap sections or mark real newcomer validation complete. Capture small golden assertions for *claims and citations*, not a huge whitespace snapshot. - -**Gate:** The docs no longer claim existing guide/workspace/sync functionality is merely planned; neutral fixtures encode both positive and negative claims; the plain Node fixture has discoverable source and documented setup; no onboarding production behavior changes. - -**Prompt 0** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially the product contract, final output, Slice 0 deliverable/gate, and cross-cutting checklist. Work only on onboarding design/acceptance. Read the current code, docs/ONBOARDING_V2.md, the canonical Milestone 9/10 roadmap sections, and docs/ONBOARDING_DEPTH_BASELINE.md before editing. Align the spec and only those roadmap sections with what is actually implemented; preserve historical ROADMAP content and all unrelated edits. Specify the standalone repository-only guide, connected journeys, concepts, change points, setup limits, precise questions, and separate personal progress. Add small neutral source fixtures/acceptance cases for if/else, early return/throw, repeated helper call, local manager alias, and publication/handler pair, with negative assertions against false sequential paths and invented effects. Add a plain JavaScript/Node source fixture with a documented run command and expected overview claims. Do not implement tracing/rendering yet, edit Handover, mark newcomer validation complete, or commit. Return changed-file list, acceptance cases and negative cases, checks, unresolved questions, and an explicit Slice 0 gate verdict. -``` - -### Slice 1 — One bounded analysis context - -**Deliverable:** Reuse the `ts-morph` Project that `scanRepository` already creates once per scan to resolve selected routes; avoid loading a second TypeScript Program or constructing a project per journey. Preserve source discovery fallback when imports/tsconfig/dependencies are absent. Exclude dependencies/generated code and bound loaded files/methods. Instrument elapsed time and peak RSS in a reproducible local benchmark, not permanent user-facing noise. - -**Gate:** Same method resolutions as the spike for a neutral fixture, Madar and Debtbox; missing dependencies do not crash the scan; multiple selected routes reuse the scan's existing Project. On the same machine, target no more than roughly 2× the baseline guide time and under 1 GiB peak for Madar; if missed, record where time/memory went and optimize before further expansion. These are an initial budget, not a universal promise. - -**Prompt 1** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 1 and its gate. Implement only bounded selected-entry resolution using the ts-morph Project already created once in scanRepository. Read the baseline report and isolated spike, then current scanner architecture. Do not load a second Program or add a dependency without measured benefit. Resolve declarations for more than one selected route through this shared context, with explicit file/method/depth/fan-out limits, exclusions, and safe fallback when tsconfig or app dependencies are missing. Do not render deeper guide prose or change Handover. Add focused tests for multi-route reuse and missing-dependency fallback. Measure one-route and multi-route time/RSS on disposable Debtbox/Madar snapshots, compare with the baseline, and report actual figures and any budget failure. Return changed files, before/after resolution, tests, unsupported cases, and an explicit gate verdict. No commit. -``` - -### Slice 2 — Path-aware trace representation - -**Deliverable:** Core trace/event types and scanner implementation for branch/exit-aware events. Keep called helper body separate from call-site context. Handle `if/else`, guard throw/return, `try/catch/finally`, source order, and unsupported constructs conservatively. Record call site and declaration as separate evidence. No generated prose yet. - -**Gate:** Fixture proves no event after a guaranteed return/throw is described as occurring on that path; mutually exclusive writes stay separate; repeated helper calls retain two edges; nested argument evaluation is not flattened into an unsupported order; budget/depth stops are visible. Tests include loops/switch as explicit gaps. - -**Prompt 2** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially the path-aware model, Slice 2 deliverable/gate, and cross-cutting checks. Implement the smallest path-aware onboarding trace representation, using the reusable analysis context. Include entry identity, call edges with call-site and declared-target evidence, path events with branch context, exits, and explicit gaps. Support common if/else, early return/throw, try/catch/finally, and direct calls. Do not merge exclusive branches into a straight-line story. Analyze a helper body once if useful, but preserve each invocation's call-site/branch context. Unsupported loops, switches, callbacks, or dynamic expressions must produce bounded gaps rather than disappear. Keep the model framework-independent and the scanner responsible for AST behavior. Add neutral positive/negative tests; do not change guide rendering or Handover. Return structured before/after trace including a negative path, tests, unsupported syntax, and explicit gate verdict. No commit. -``` - -### Slice 3 — Cross-file method continuation - -**Deliverable:** Follow uniquely resolved direct calls from a controller into injected concrete services, same-class helpers, and further local methods up to a bounded depth. Retain ambiguity on interfaces, dynamic dispatch, overrides, aliases, and unavailable bodies. Classify repository `get/find/save` names only as read-like/write-like when their target and/or call site supports that label; do not claim I/O happened. - -**Gate:** Madar selected route gains cited reads and guard branches; Debtbox fee helper is visible; the neutral interface/dynamic cases remain unresolved; no method-call edges from DI/module import alone; every followed edge has two locations. - -**Prompt 3** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 3 and its gate. Extend only onboarding's structured trace to follow bounded cross-file source method calls using TypeScript symbols: route handler to concrete injected provider, same-class helper, and further local method. Require an unambiguous declared target and retain both call-site and declaration evidence. Keep interface-typed, dynamic, inherited-without-body, external, and ambiguous targets as explicit gaps. Constructor injection and module imports are not calls; a declared target is not proof of runtime dispatch. Test neutral cases and compare the structured trace with Madar MobileFleetService.assignDriverToTruck and Debtbox DebtService.addDebt on disposable source snapshots. Do not yet synthesize a new guide layout or add AI/dependencies. Report new edges and any false edge. No commit. -``` - -### Slice 4 — Local receiver aliases and transaction-like calls - -**Deliverable:** Follow simple local provenance such as `const queryRunner = this.dataSource.createQueryRunner()` far enough to retain call sites for `queryRunner.manager.save`, `commitTransaction`, `rollbackTransaction`, and `release`. If the manager implementation cannot be resolved, mark these calls **write-like/transaction-like with unresolved target**. Do not infer atomicity, commit success, rollback success, or which branches executed. Other common local aliases may be supported only when proven by a neutral fixture. - -**Gate:** Madar's three conditional save call sites remain in their respective branch contexts and cite exact source; neutral fixture with a similarly shaped alias works; unrelated `.save` method is not mistaken for confirmed persistence. - -**Prompt 4** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 4 and its gate. Add narrowly proven local receiver provenance to the onboarding trace. Cover a local variable initialized by an injected object call and subsequent chained method calls, as in queryRunner.manager.save; classify visible calls conservatively when an external library body is unavailable. Keep conditional paths, await flags, catch/finally, commit/rollback/release calls and their source evidence separate. Never say a write committed or rollback succeeded. Test a neutral manager-alias fixture plus Madar's assignDriverToTruck; add a negative fixture where an unrelated object's save method must not be described as a database write. Do not touch Handover or write guide prose beyond what is required to expose the structured result. Report exact supported patterns and stop edges. No commit. -``` - -### Slice 5 — First deep journey in the guide - -**Deliverable:** Convert one selected structured trace into readable Markdown: entry, checks, path past checks, alternative paths, visible state/write attempts, external boundary, and exact gaps. Provide “where to change” links for relevant code and tests where discoverable. The candidate fallback must show the useful partial trace and first gap instead of hiding evidence behind an all-or-nothing explanation gate. Preserve guide markers, snapshots, human prose, and conflicts. Do not expand to many journeys yet. - -**Gate:** Madar fleet route is more useful than its former controller→service pointer; Debtbox creation remains accurate; empty Nest fixture stays a candidate; a stranger can verify every behavioral sentence at cited source. No fake completed assignment/transaction statement. - -**Prompt 5** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially the final output contract and Slice 5 gate. Render exactly one evidence-backed onboarding journey from the new structured trace into ONBOARDING.md. Prefer a selected route with meaningful paths; otherwise show the supported partial path and precise first gap. Include entry, guarded reads, mutually exclusive decisions, attempted writes/effects, error path, source references, and relevant change/test locations. Distinguish declaration, static call, unresolved target, and runtime outcome without repeating boilerplate in every line. Retain existing section IDs or provide safe anchor migration; preserve managed-guide snapshot reconciliation and human prose. Show fresh guide excerpts for Madar fleet assignment, Debtbox debt creation, and a neutral empty handler, and prove they contain no false sequence. Focused tests plus normal build/lint/format. No Handover/ROADMAP edits or commit. -``` - -### Slice 6 — Concepts and data effects - -**Deliverable:** A journey-linked glossary using supported TypeORM entities/columns/relations (and existing data-store findings). Map reads/writes to entities only when types or calls support it. Select concepts touched by featured journeys, show direct relations, and put full inventories in references. Do not equate an entity or field name with its business meaning. For non-TypeORM projects, describe the supported data shapes/store evidence or omit the glossary gracefully. - -**Gate:** Debtbox and Madar guides explain which records selected journeys touch; unrelated entities do not flood the first screen; neutral project with two entities and a relation is accurate; plain Node stays honest. - -**Prompt 6** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 6 and its gate. Add a curated Concepts section to onboarding, grounded in TypeORM entity declarations and actual selected-journey read/write references. Capture entity symbol, relevant fields/relations, and cited paths; show how concepts connect to the journey without inventing business definitions or database behavior. Do not list every entity in a large repo in the main section. Support a neutral two-entity fixture, inspect Debtbox and Madar generated excerpts, and keep graceful output for a project with no TypeORM. Preserve guide edits/anchors and do not touch Handover. Test evidence correctness and noise limits; report any relation syntax not supported. No commit. -``` - -### Slice 7 — Continuations across jobs/events/queues - -**Deliverable:** Match an observed publication/enqueue to a declared handler only where a concrete topic/job name, registration, and compatible evidence support the connection. Treat HTTP callbacks as separate entries unless a code-level identifier links them. Connect scheduled work to concepts it actually reads/changes; do not imply it ran because it is scheduled. Stop at ambiguous, dynamic, external, or framework-dependent edges. - -**Gate:** Neutral publisher/consumer fixture yields a labeled possible continuation; mismatched or dynamic topic yields no edge; selected Debtbox/Madar examples are connected only where supported; performance budget still holds. - -**Prompt 7** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 7 and its gate. Extend onboarding journeys only across demonstrable asynchronous declarations: enqueue/publish call and matching queue/event handler registration with concrete compatible identifiers. Cite both endpoints and label the link a possible continuation; never claim delivery, ordering across processes, or successful processing. Support one framework pattern actually present in the evaluated repositories plus a neutral fixture; do not build a generic plugin system. Keep scheduled jobs as separate entries unless source provides a defensible data/identifier link. Add negative tests for dynamic/mismatched topics. Show one connected and one deliberately unconnected generated example, with timing/RSS impact. No Handover edits or commit. -``` - -### Slice 8 — Complementary journey selection and user focus - -**Deliverable:** Deterministic selection that rewards source depth and *novel coverage* of entities, entry types, and boundaries, rather than names such as debt, consent, customer, or payment. Avoid picking near-duplicate CRUD routes when a distinct job or integration path teaches more. Allow an optional explicit `--focus` route/symbol selector after verifying current CLI conventions. Selection does not claim business criticality. Tiny repositories may have zero or one supported journey. - -**Gate:** Madar no longer shows only three shallow pointers when deeper eligible paths exist; Debtbox retains accurate creation/consent and can add a distinct journey when evidenced; a neutral non-payment fixture selects sensible paths; stable results across repeat scans. - -**Prompt 8** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 8 and its gate. Replace onboarding's fixed name-biased route selection with deterministic evidence-depth and complementarity selection. Choose a small set of distinct journeys that cover different supported entities/entry types/boundaries; scale the count with available evidence instead of hardcoding two explanations. Do not assign business importance from centrality or names. Add an optional user-selected --focus route/symbol only if it fits the existing CLI and can be resolved safely; keep default fully automatic. Test duplicate CRUD routes, distinct job/route paths, neutral names, sparse repos, stable tie-breaking and no Debtbox-specific terms. Show selected and rejected candidates with reasons on Madar, Debtbox, and neutral fixtures. No Handover changes or commit. -``` - -### Slice 9 — Repository knowledge and orientation - -**Deliverable:** Source-attributed project description if credible project documentation exists; relevant explanatory comments, tests, examples, and migration notes next to selected journeys. Comments are source statements, not verified truth. Do not indiscriminately mine every Git commit or copy huge README sections. Filter starter boilerplate, stale/contradictory statements, secrets, generated files, and irrelevant comments. Keep owner-written System context optional and intact. - -**Gate:** A neutral fixture with a useful handler comment and a generic starter README surfaces the former and does not present the latter as a bespoke product description; Madar's reconciliation comment is surfaced if that journey is selected, without claiming the comment's operational policy was verified; no unrelated context dump. - -**Prompt 9** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 9 and its gate. Enrich onboarding orientation and selected journeys with relevant checked-in text: a credible project description where present, a nearby explanatory source comment, related tests/examples, and specific migration notes where linked. Attribute each statement to its source; a comment or test is not runtime proof. Suppress obvious starter README boilerplate and unrelated text. Do not read or print secret values, scan all Git history, or invent product purpose. Preserve owner-written System context byte-for-byte. Test a neutral project with a real comment and starter README, then show concise excerpts on available Debtbox/Madar snapshots. No Handover edits or commit. -``` - -### Slice 10 — Practical setup and recorded observation - -**Deliverable:** Improve project-specific setup from README/package scripts, Compose, config examples, migration/seed declarations, and a declared health route. Build a proposed sequence and explicit blockers/contradictions. Do not run commands automatically. Permit personal workspace recording of attempted command, date, observed result, and blocker without claiming shared verification. Preserve optional owner-written verified setup and avoid secrets. - -**Gate:** Generic Nest starter commands are labeled generic/documented; Madar/Debtbox prerequisites and contradictions that are actually in the repository appear as questions; no app command runs during `guide`; an attempted observation is attributed to the person, not generated evidence. - -**Prompt 10** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 10 and its gate. Make onboarding's Run and observe section project-specific. Derive only declared services, env variable names (never values), package scripts, migrations/seeds, build prerequisites, and a possible health route from repository files. Distinguish documented steps, inferred ordering, missing prerequisites, and user-recorded observations. Improve the personal workspace so a newcomer can record exact commands attempted, date, result, and blocker in Markdown while preserving current sync/prose behavior; never automatically install, run migrations, start containers, or call an endpoint. Retain owner-written Verified local setup. Test a plain Node repo, a neutral Compose fixture, and available Debtbox/Madar outputs. No Handover edits or commit. -``` - -### Slice 11 — Adaptive personal learning path - -**Deliverable:** Replace the generic four-exercise content with tasks tied to the actual guide: map important concepts, explain two connected journeys where available, locate a hypothetical change point, record a safe observation or blocker, and answer or classify remaining questions. Keep separate shared knowledge and local personal state. Stable exercise identities must survive rescans; migration of existing four `v2:` IDs must be explicit and lossless, or keep them as stable umbrellas with guide-specific subgoals. If a journey disappears, retain work and flag a stale link. - -**Gate:** Existing checked boxes, notes, questions, evidence and legacy JSON remain intact; sync conflicts still protect both sides; tasks are meaningful in sparse and complex repos; self-reported completion is never a competence certification. - -**Prompt 11** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 11 and its gate. Align personal onboarding exercises with the new guide's actual concepts, selected journeys, setup and gaps. Before coding, document how the four existing v2 IDs and personal JSON/Markdown progress will migrate or remain stable; implement the smallest lossless strategy. Retain user prose, checkbox sync, conflict detection, legacy progress, and stale-link visibility when a guide changes. Do not infer competence from completion. Test rerun after journey selection changes, existing completed v2 tasks, personal notes and conflicting edits, plus sparse-repo behavior. Show a realistic personal workspace and plan/status output. No Handover edits or commit. -``` - -### Slice 12 — Guide reading UX and regeneration - -**Deliverable:** Final content order, compact orientation, journey-focused headings, readable tables or small Mermaid only where supported, collapsed citation/inventory appendix, stable anchors, and concise language. Generated claims remain reviewable; owner context/verified setup remain clearly human-supplied. Preserve old marked guide sections and snapshots through a defined upgrade/reconciliation path; unmarked guides are never overwritten. - -**Gate:** New guide is substantially easier to read without losing depth; generated claims can be verified at references; no human edit disappears on re-generation; stale snapshot/markers and conflicting edits fail safely; `guide` idempotent when source unchanged. - -**Prompt 12** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially Slice 12 and its gate. Polish only onboarding's shared Markdown reading experience after the deeper content exists. Order: Start here, system map, concepts, connected journeys, change points, Run and observe, specific questions, collapsed reference appendix. Use clear prose and compact source references; move long module/integration inventories out of the first screen without deleting their evidence. Add a small diagram only when every edge has supported meaning. Preserve existing owner sections, free-form human prose, managed markers, snapshot conflict handling, stable links and idempotent regeneration; define a safe upgrade for older marked guides and refuse unmarked ones. Test human edits, conflicting edits, changed findings and identical reruns. Show complete outputs from one small and one large fixture. No Handover/ROADMAP changes or commit. -``` - -### Slice 13 — Independent acceptance, regression, and release docs - -**Deliverable:** Repeatable fixture regression and a real unfamiliar-engineer assessment, first on repository-only onboarding. Evaluate whether they can explain main concepts, two connected behaviors where present, an alternate/failure path, and likely files for a small change; attempt setup or identify an exact blocker; list remaining questions. Compare with reading the repository without TransferKit. Inspect false statements manually against code. Record first-run time/memory and confidence limits. Update docs and Milestone 9 status only to the level demonstrated. Milestone 10 requires actual newcomer evidence, not Codex simulation. Optional v3 enrichment can be separately planned after repository-only acceptance. - -**Gate:** No material false call/branch/transaction assertions in the evaluated guides; an unfamiliar engineer can complete the tasks with fewer irrelevant searches/questions than baseline, and misleading claims are recorded and fixed before calling the work validated. If tests do not show improvement, keep the milestone open and investigate the failure. - -**Prompt 13** - -```text -Read docs/ONBOARDING_DEEP_GUIDE_PLAN.md in full, especially the newcomer protocol and Slice 13 gate. Perform onboarding-only acceptance and regression. Run the finalized guide/workspace on a small plain Node repo, a neutral Nest fixture, Debtbox, and Madar using disposable snapshots. Compare with docs/ONBOARDING_DEPTH_BASELINE.md: selected journeys, depth, false edges/claims, guide size/readability, time and peak memory. Manually spot-check each material assertion and source citation in selected journeys. Prepare a short unfamiliar-engineer task protocol comparing repository-only reading with TransferKit-assisted reading; run it with a real engineer only if one is actually available, otherwise label it pending and do not claim validation. Record task correctness, change-point identification, first local observation or blocker, remaining business questions, and misleading output. Update onboarding spec, CLI/README docs and only relevant Milestone 9/10 checklist statuses based on evidence. Preserve historical roadmap content; do not touch Handover or commit. Provide generated guide/workspace excerpts, measurements, failures, and exact outstanding acceptance gaps. -``` - -## 5. Cross-cutting acceptance checklist - -Apply after every slice that changes behavior: - -- **Truth:** Each generated behavioral claim is supported by cited code/doc/test/person/observation; no unqualified production outcome. No module-import → method-call conversion, no false provider identity, no sequential merge of exclusive branches. -- **Depth:** At least one selected journey on a meaningful repository goes beyond controller→service to decisions and data effects; later, complementary journeys explain distinct paths and supported continuations. -- **Graceful limits:** Empty handlers, missing tsconfig/dependencies, JavaScript/plain Node, dynamic dispatch, unsupported syntax, and sparse repos produce explicit partial coverage or omission, not invented detail or a crash. -- **Generic behavior:** Neutral fixtures must prove each pattern independently of Debtbox and Madar names; no hardcoded route/domain/provider terms. -- **Safety:** Guide generation is read-only with respect to the target application, never executes application code, and never emits env values/secrets. Generated Markdown and state reconciliation protect human work. -- **Stability:** Stable anchors/identities, deterministic selection, repeat generation, existing personal progress, and legacy behavior survive the changes. -- **Performance:** Measure the whole guide pipeline, not an isolated tracing process, on the same large repository/revision and machine; report RSS/time, number of loaded files and selected routes. Record a budget miss as a blocker, not a successful gate. -- **Human utility:** The final acceptance uses newcomer tasks and spot-checked code, not test count, line count, or an external rating alone. - -For subjective guide gates, use the [Slice 0 reviewer rubric](ONBOARDING_V2.md#slice-0-acceptance-cases): a reviewer must find a cited decision or explicit lack of one, an alternate exit where present, the first unsupported edge, and likely change/test locations within each selected journey. Check every substantive behavioral sentence against its cited source and keep broad inventories out of the opening section. Report the review result and any exception, rather than declaring a guide “more useful” from length or route count. - -### Newcomer evaluation protocol - -Recruit an engineer who has not worked on the evaluated repository. Give them the repository and a small, realistic hypothetical change or bug **without** providing a handover. Record the baseline with the repository's ordinary docs, then use a comparable task or another unfamiliar repository with TransferKit; do not imply the two conditions are perfectly controlled if the tasks differ. Avoid coaching during the timed portion. - -Use a short answer key prepared by someone who knows the source. Ask the engineer to (1) explain the key records and two distinct paths, (2) identify what happens on one alternate path, (3) point to the files/tests they would inspect for the change, (4) try a safe first observation or identify the exact setup blocker, and (5) list questions requiring a teammate. Score **correct/partly correct/unsupported**, record elapsed time and misleading guide claims, and compare the unanswered questions. A self-reported confidence rating can be collected but is not the acceptance measure. Keep any unresolved business question visible rather than treating it as a failure of code tracing. - -## 6. Decisions and stopping rules - -1. **No new dependency by default.** The TypeScript compiler API worked in the spike and `ts-morph` already exists in the project. Adopt another library only for a measured missing capability or significant maintainability gain. -2. **Do not build a universal call graph.** Trace a bounded set of selected entries, retain source evidence, and expose gaps. Whole-repository transitive tracing would amplify memory, noise, and incorrect paths. -3. **Do not add more journeys to hide shallow explanations.** If a selected journey cannot say what code checks or changes, inspect the failure edge first. Partial explanation is allowed when precisely bounded. -4. **Do not invent a business story.** Useful technical understanding is achievable from code; business intent is sourced from credible text/humans or remains a specific question. -5. **Keep optional v3 enrichment separate.** Once independent repository-only onboarding is validated, v3 items may add attributed business intent/ownership by stable ID without overriding code evidence or personal progress. That is a later slice, not a prerequisite or part of this implementation sequence. -6. **Pause at an accuracy/performance gate.** Correct the model or reduce scope before proceeding to prose polish. Preserve the baseline report, benchmark scripts, and generated examples as review evidence. diff --git a/docs/ONBOARDING_DEPTH_BASELINE.md b/docs/ONBOARDING_DEPTH_BASELINE.md deleted file mode 100644 index d059666..0000000 --- a/docs/ONBOARDING_DEPTH_BASELINE.md +++ /dev/null @@ -1,161 +0,0 @@ -# Onboarding guide depth baseline - -Read-only static baseline, 2026-09-30. `tk onboard guide` was run from a fresh build of TransferKit `cb7c25e3e371db9d2e2cadb7a0053f573ed849d6` (`main`). All guides were generated in `/tmp/tk-onboarding-baseline.yc3560/` from fixture copies or `git archive HEAD` snapshots. No evaluated repository was modified; no application, dependency installation, container, or external service was run. Times are one local run each, so they are indicative rather than benchmarks. Peak RSS is macOS `wait4` child `ru_maxrss`. - -## Repositories and observed output - -| Source (revision; branch) | Snapshot size | Guide run; peak RSS | Selected output and what it teaches | -| --- | ---: | ---: | --- | -| `fixtures/project-detection/plain-node` (TransferKit revision above; `main`) | 1 file, 0 TS, about 4 KiB | 0.250 s; 132.3 MiB | No flow. Guide says no supported system components or routes and asks for setup evidence. Accurate for this package-only fixture, though even its Node package identity is absent from the overview. | -| `fixtures/realistic-nestjs` (same revision; `main`) | 22 files, 15 TS, about 88 KiB | 0.187 s; 135.7 MiB | Candidates: payment creation, payment recovery, debt creation; no explained flow. Teaches Nest modules, declarations, jobs, integration signals, and route locations. Its controller methods are empty (`src/payment/payment.controller.ts:8-15`, `src/debt/debt.controller.ts:8-12`), so an unresolved continuation is accurate. | -| `/Users/mac/source_control/debtbox-backend` (`e0267736a40a3181aae1c463782fe0f0436975c7`; `test-transferkit`) | 551 tracked files, 490 TS, about 3.5 MiB snapshot | 1.119 s; 288.7 MiB | Explains debt creation and consent; selects payment initiation as a candidate. Teaches route-to-service entry, direct guards, ordered saves, consent status branches, and attempted side effects, with open runtime questions. The guide does not establish an end-to-end payment-to-payout path. | -| `/Users/mac/source_control/b2c-backend` (Madar B2C; `79cc98e534a95a2a316c3464281619fb86a12d99`; `testing`) | 2,446 tracked files, 2,311 TS, about 16 MiB snapshot | 5.705 s; 607.3 MiB | Candidates: dashboard driver create/update and mobile fleet assign driver to truck; no explained flow. Teaches module and route locations, but no decisions, transaction writes, or failure boundaries for those paths. | - -Both Debtbox and Madar B2C were available locally. The Debtbox checkout has an unrelated deleted `.codex/config.toml` in its working tree; archiving `HEAD` excluded that local change. The separate `/Users/mac/source_control/madar` checkout also contains the fleet symbol, but this run used the `b2c-backend` checkout identified above. Snapshot size excludes installed dependencies and Git metadata. Generated guide sizes were 1,752, 4,641, 13,383, and 12,763 bytes in table order. - -## Current contract and depth limit - -The [onboarding design](ONBOARDING_V2.md) calls for a few evidence-labeled end-to-end flows with entry, decisions, persistence, side effects, and visible gaps. The [Debtbox fixture](ONBOARDING_V2_DEBTBOX_FIXTURE.md) is an illustrative target, not observed CLI output. Current code builds a repository-only guide from static findings, marks sections for safe regeneration, detects Nest routes/module relationships, and can explain two specially shaped traces ([guide orchestration](../packages/cli/src/generate-onboarding-guide.ts), [trace scanner](../packages/scanners/src/route-traces.ts), [explanation rules](../packages/standards/src/explained-flow.ts), [renderer](../packages/renderers/src/onboarding-guide.ts)). It labels runtime claims unverified and preserves explicit unknowns. The scanner enters exactly one directly called injected service method from a route; its method inspection records certain guards, `status/state/action` assignments, injected repository calls, selected service calls, and gaps. It does not continue through local helpers or into called methods, recognize a local `queryRunner.manager` alias as persistence, or model transaction boundaries. The explainer currently requires a narrow unconditional awaited repository `save` pattern or a specific two-status-branch pattern. The renderer selects at most three candidates and at most two explanations. - -| Entry point | Known continuation | Resolved by current output | First unresolved edge | Assessment | -| --- | --- | --- | --- | --- | -| Plain Node `package.json:1` | None in fixture | Setup questions only | Package identity does not appear in overview | Accurate but sparse. | -| Nest `PaymentController.createPayment` (`fixtures/realistic-nestjs/src/payment/payment.controller.ts:8`) | Empty handler | POST `/payments` route and module relationship | No call exists in handler | Accurate candidate, insufficient fixture evidence for a flow. | -| Debtbox `DebtController.addDebt` (`src/module/debt/debt.controller.ts:37,48`) | `DebtService.addDebt` (`src/module/debt/debt.service.ts:100`) | Guards, three separate awaited saves, audit call, conditional push attempt | `DebtService.applyExpectedFeeSnapshot` at `debt.service.ts:155` is a local helper explicitly left untraced; notification language call is nested at `:213` | Useful partial trace; no claim of delivery or atomicity. | -| Debtbox `DebtController.consentDebt` (`src/module/debt/debt.controller.ts:54,78`) | `DebtService.consentDebt` (`src/module/debt/debt.service.ts:267`) | Consent save, accepted/rejected branches, upload attempt, Sanad and gateway calls | `SanadsService.ensureGeneratedForDebt` at `debt.service.ts:331` is named but its implementation and downstream effects are not traced | Accurate within cited method; deeper effects and outcomes remain open. | -| Debtbox `PaymentController` checkout (`src/module/payment/payment.controller.ts:16,27`) | `PaymentService.initiatePayment` (`src/module/payment/payment.service.ts:65`) | Route and direct service method only in selected guide; scanner can see direct calls | `PaymentService.getPayableGroupDebts` at `payment.service.ts:82` is a local helper; conditional saves at `:123,160,167,179` do not meet the linear explanation rule | Candidate label is accurate, but misses payment decisions and checkout attempt. | -| Madar `MobileFleetController.assignDriverToTruck` (`src/module/fleet/controllers/mobile-fleet.controller.ts:114,125-130`) | `MobileFleetService.assignDriverToTruck` (`src/module/fleet/services/mobile-fleet.service.ts:585`) | Route and direct method name only | `this.dataSource.createQueryRunner()` at `:597` produces a local `queryRunner`; `queryRunner.connect/startTransaction` and `queryRunner.manager.save` are outside the injected-call matcher | Accurate candidate label, but too shallow to teach this selected flow; treating it as an explained successful assignment would be misleading. | - -Madar's method statically shows a transaction setup at `mobile-fleet.service.ts:597-599`; fleet/truck/driver repository reads and ownership guards at `:602-615`; running-shipment checks at `:617-626`; branches that may unassign the driver's prior truck (`:629-645`) and the truck's prior driver (`:647-667`); a conditional assignment (`:669-673`); and commit, rollback, and release calls at `:675,682-690`. The referenced repository methods exist: `FleetRepository.getFleetById` (`src/module/data/repository/fleet.repository.ts:698`), `TruckRepository.getTruckById` (`truck.repository.ts:569`), `DriverRepository.getDriverById` (`driver.repository.ts:77`), and `ShipmentRepository.getRunningShipmentByTruckId/getRunningShipmentByDriverId` (`shipment.repository.ts:13337,13378`). These are next statically resolvable calls and branches, not observed runtime outcomes. The scanner can record the injected repository call sites, but the explainer drops this trace because its linear rule requires an unconditional awaited injected repository `save` ([rule](../packages/standards/src/explained-flow.ts)); the only saves here are via `queryRunner.manager`. The candidate renderer then shows only route/method references, hiding the detected guards and unresolved transaction edge. - -## Diagnosis and next tracing spike - -- **Scanner defects/limits:** Local receiver aliases and transaction manager calls disappear (`queryRunner` in Madar); local helpers and injected call bodies stop at their call sites (Debtbox fee snapshot, payment group lookup, Sanad generation). A bounded, evidence-bearing continuation should distinguish resolved source calls from external/library calls and stop on unsupported edges. -- **Insufficient evidence:** The plain Node fixture has no source, the Nest fixture has empty handlers, and no static scan proves runtime state, delivery, rollback, or recovery. These are explicit unknowns, not missing runtime conclusions. -- **Selection defects:** Madar's three highest-scoring candidates have zero explanations; Debtbox payment initiation is left as a candidate despite substantive source, while the guide cannot connect it to the scheduled payout path (`src/module/payment/payout-scheduler.service.ts:20`). Ranking favors route names and local operation counts rather than demonstrated learning depth ([selection](../packages/renderers/src/onboarding-guide.ts)). -- **Rendering defects:** Madar's root-import line lists roughly a hundred modules, obscuring entry points. Candidate rows disclose a direct method but neither the scanner's partial guard/read evidence nor the first unresolved edge. The `Debtbox` guide is stronger: its steps and uncertainty labels are sufficient for locating creation/consent guards, ordered saves, and attempted side effects; deeper tracing would improve the fee helper, consent-to-Sanad path, payment checkout and later payout, not invalidate those direct-call claims. - -Acceptance examples for the next spike (static claims only): - -1. **Neutral fixture:** Extend `OrderController.create` → `OrderService.create` in `packages/scanners/src/route-traces.test.ts:16-40` with a same-file helper or a second injected service method containing a visible guard/call. The guide should cite the continuation and its stop edge, while still labeling the existing indirect and dynamic calls at `:25-27` unresolved. -2. **Madar transaction:** `MobileFleetController.assignDriverToTruck` → `MobileFleetService.assignDriverToTruck` (`src/module/fleet/controllers/mobile-fleet.controller.ts:125-130`; `src/module/fleet/services/mobile-fleet.service.ts:585-690`) should expose the five initial reads/guards, three conditional manager saves, and commit/rollback/release branches with source references. It must not assert that any branch ran or that rollback succeeded. -3. **Debtbox creation:** `DebtService.addDebt` (`src/module/debt/debt.service.ts:100,155-199,208-228`) should continue through `applyExpectedFeeSnapshot` with bounded depth, preserve the separate save and caught push distinctions, and leave external delivery unresolved. -4. **Debtbox payment:** `PaymentService.initiatePayment` (`src/module/payment/payment.service.ts:65,82,103-179`) should show the early return versus checkout creation branches and the HyperPay call after recorded transaction data; payout remains a separate scheduled entry until a supported code link is established. - -No newcomer validation was performed. - -## Focused symbol-aware tracing spike (2026-09-30) - -The isolated [prototype](../experiments/onboarding-trace-spike.mjs) uses the installed TypeScript 5.9.3 compiler API and the target repository's `tsconfig.json` options. It creates a `Program` rooted at the requested controller file, follows imports, and uses `TypeChecker` method symbols. It does not feed guide generation. The [neutral Nest fixture](../experiments/fixtures/nest-trace/controller.ts) and [focused tests](../experiments/onboarding-trace-spike.test.mjs) cover a route call, same-class helper, cross-file injected providers, exclusive `if/else` branches, a catch, status assignments, a dynamic call, an interface-typed provider, and an unsupported project function. Each followed edge contains a call-site `file:line` and the declared target's symbol and `file:line`. “Declared target” means a statically selected declaration, not a guarantee of runtime dispatch. - -### Madar before and after - -**Before:** the generated guide stops at `POST /v0.0.1/api/mobile-fleet/assign-driver-to-truck` → `MobileFleetController.assignDriverToTruck` → `MobileFleetService.assignDriverToTruck` (`src/module/fleet/controllers/mobile-fleet.controller.ts:114,130`; `src/module/fleet/services/mobile-fleet.service.ts:585`). It offers no explained steps. - -**Prototype, cited static path:** - -1. The handler's call at `mobile-fleet.controller.ts:130` resolves to `MobileFleetService.assignDriverToTruck` at `mobile-fleet.service.ts:585`. Constructor injection itself creates no call edge. -2. The service calls declared `FleetRepository.getFleetById` (`mobile-fleet.service.ts:602` → `src/module/data/repository/fleet.repository.ts:698`), `TruckRepository.getTruckById` (`:607` → `truck.repository.ts:569`), and `DriverRepository.getDriverById` (`:612` → `driver.repository.ts:77`). Each call is followed by a visible missing-record/ownership throw branch at `:603-615`. -3. It calls declared `ShipmentRepository.getRunningShipmentByTruckId` (`:618` → `shipment.repository.ts:13337`) and `getRunningShipmentByDriverId` (`:624` → `shipment.repository.ts:13378`), with separate throw branches at `:619-626`. Those repository methods call same-class plural helpers at `shipment.repository.ts:13339,13380`; the depth-two prototype cites those edges but does not follow them further. -4. Under `driver.truck && driver.truck.id !== truckId` (`mobile-fleet.service.ts:630`), it checks the former truck's shipment at `:632`, may throw at `:633-639`, sets `driver.truck = null` at `:643`, and calls `queryRunner.manager.save(driver)` at `:644`. The second branch (`:648-667`) checks the truck's previous driver and may clear/save it. A third branch (`:670-673`) may assign/save the requested truck. The conditions are kept separate; the prototype does not claim all branches execute. -5. Calls to `queryRunner.commitTransaction`, `rollbackTransaction`, and `release` appear at `:675,683,690`; the latter two are in catch/finally. These are cited calls, not proof of a committed or rolled-back outcome. - -**First remaining gap:** `this.dataSource.createQueryRunner()` at `mobile-fleet.service.ts:597` has no source method body in the dependency-free snapshot. The subsequent `queryRunner` receiver is a local alias, so `connect`, `startTransaction`, the three `manager.save` calls, commit, rollback, and release remain unresolved method targets. The prototype labels each `save` a **write-like call with unresolved target**; it does not claim a database write occurred. `FleetRepository.getFleetById` and two other repository reads place their query bodies inside `new Promise(async ...)` callbacks (`fleet.repository.ts:699`, `truck.repository.ts:570`, `driver.repository.ts:78`), which this bounded prototype explicitly leaves untraced. - -### Debtbox comparison and precision - -The existing guide already explains `DebtController.addDebt` → `DebtService.addDebt` (`src/module/debt/debt.controller.ts:48`; `src/module/debt/debt.service.ts:100`). The prototype also resolves `DebtService.validateDebtCreationAmount` (`debt.service.ts:102` → `:242`) and its three throw guards (`:243-250`), plus the previously untraced `DebtService.applyExpectedFeeSnapshot` (`:155` → `:254`) and its fee-field assignments (`:256-264`). It resolves the nested notification-language call at `:213` to `NotificationService.resolveNotificationLanguage` (`src/module/notification/notification.service.ts:95`) and labels it a nested argument, without inventing call order. Existing direct observations remain: awaited save call sites at `debt.service.ts:156,178,199` and a conditional Firebase attempt at `:215`; their outcomes stay unverified. The first unresolved edge on the fee-helper continuation is `computeExpectedDebtFeeSnapshot` at `:255` (project free function outside this prototype's method-call scope); the first unresolved save target on the main path is inherited `DebtRepository.save` at `:156` because TypeORM is absent. - -No false method-call edge from a module import or constructor injection appeared in the neutral fixture or either repository trace. Precision limits still matter: a TypeScript method symbol identifies a *declared* target, not necessarily a runtime override; a repository `get*` or `save` name is only a read-like/write-like call, not proof of I/O; nested argument calls must not be flattened into separate sequential steps. The prototype marks dynamic `this.notifications[method]` and interface-typed `Dispatcher.send` unresolved in the fixture, and stops at unsupported project free functions, callbacks, aliases, and depth limits. Its branch labels preserve `when`, `else`, `catch`, and `finally` rather than joining mutually exclusive paths. - -| Same disposable snapshot | Existing full `tk onboard guide` | Isolated route trace, depth 2 | Loaded project TS files | -| --- | ---: | ---: | ---: | -| Madar B2C | 5.705 s; 607.3 MiB peak RSS | 2.576 s; 497.3 MiB peak RSS | 1,481 of 2,311 snapshot TS files | -| Debtbox | 1.119 s; 288.7 MiB peak RSS | 0.843 s; 279.6 MiB peak RSS | 192 of 490 snapshot TS files | - -These are separate single-process runs on the same machine and snapshots; the trace is **additional work**, not a faster replacement for guide generation. A preceding route-scoped Madar run took 2.514 s and 554.1 MiB, indicating memory variability. Loading all tsconfig files instead took 3.872 s and 723.9 MiB in one Madar run. The Madar tsconfig has a `@test/*` alias and excludes tests; Debtbox has an `@app/*` alias. Both configurations allowed the requested relative-import method edges. Missing app dependencies produced compiler diagnostics (`@nestjs/common`, TypeORM, and others), but source method resolution still worked where imports were local. External API bodies, inherited TypeORM saves, and query-builder behavior cannot be verified from these dependency-free copies. The full Madar import graph remains sizable even with one route as the root. - -**Recommendation: narrow scope before integration.** The TypeScript compiler API suffices for this spike: it resolved the cross-file edges and explicit limits without another dependency. `ts-morph` is already used by the current scanner, but its wrapper is not justified for this isolated technique; no dependency was added. A production follow-up should first constrain tracing to selected routes, bound method depth and fan-out, carry branch context and call-site/target evidence, and render unresolved aliases and external methods plainly. Do not merge this prototype into `tk onboard guide` until those precision rules and the memory cost are evaluated against more routes. - -## Phase 2 structured trace review (2026-09-30) - -The production scanner now has a separate, onboarding-only `scanOnboardingRepository` entry point. It runs existing discovery and `analyzeOnboardingRoutes` with one shared `ts-morph` Project, without loading a second Program. The structured trace is not yet connected to guide prose; that is Slice 5. Existing Handover scan results remain unchanged. The neutral fixture has no tsconfig or installed Nest dependencies, yet resolves two selected route-to-service calls. It tests branch exits, two helper call sites, nested arguments, missing bodies, inherited/interface/dynamic targets, loops/switches, and the local query-runner alias. Analysis caps entries, project file count, followed files, methods, depth, calls per method, and live paths with visible gaps. - -**Before/after structured excerpt:** The existing Madar guide stops at `MobileFleetController.assignDriverToTruck` → `MobileFleetService.assignDriverToTruck` and leaves it a candidate. The new trace cites the controller call and declared service method, then resolves the five initial repository reads. It records awaited, write-like but unresolved `queryRunner.manager.save` call sites at `mobile-fleet.service.ts:644`, `:665`, and `:672` under distinct source conditions. The last is under `!truck.driver || truck.driver.id !== driverId`; the earlier two concern the previous truck and previous driver. Commit, rollback, and release are transaction-like *calls*, with no assertion that a transaction succeeded. Debtbox `DebtService.applyExpectedFeeSnapshot`, `NotificationService.resolveNotificationLanguage` (as a nested argument), and `SanadsService.ensureGeneratedForDebt` now have cited declared-target edges. No constructor injection or module import is emitted as a call. - -**Negative cases:** The neutral invalid-order throw exits before any read/write/queue event on that path. Priority and standard assignments remain separate, while repeated `recordAttempt` calls retain two call sites. `CacheSnapshot.save` is an ordinary call, not a database write. An interface-typed dispatcher, inherited method, dynamic element call, callback body, loop, and switch remain unresolved or explicit gaps. The alias fixture's manager `save` is labeled write-like with an unresolved target, never a completed write. Source literals are replaced in event detail and path labels before a trace can reach a renderer. - -The benchmark script runs the combined scan and trace, then model, explanation, and Markdown rendering with one Project. It does not write the guide or measure snapshot reconciliation. Figures below are single local runs on the baseline `git archive` snapshots; peak RSS is `process.resourceUsage().maxRSS` normalized for macOS. Normal `tk onboard guide` also completed on both disposable snapshots without changing its output contract. - -| Snapshot and selected routes | Baseline full guide | Phase 2 scan/render plus trace | Loaded TS files | Gate | -| --- | ---: | ---: | ---: | --- | -| Madar `79cc98e` — fleet assignment, dashboard driver create/update | 5.705 s; 607.3 MiB | 5.603 s; 702.3 MiB | 2,311 | Under 2× baseline time and 1 GiB | -| Debtbox `e026773` — debt create/consent | 1.119 s; 288.7 MiB | 1.197 s; 310.2 MiB | 490 | Under 2× baseline time and 1 GiB | - -The scanner still loads all repository TypeScript files for its existing discovery pass; the new tracer follows at most 30 files by default and skips tracing with a visible gap above its 5,000-project-file budget. These are local budgets, not universal performance promises. Dynamic dispatch, callbacks, complex expressions, loops, switches, external library bodies, and runtime transaction outcomes remain open for a person or later capability. At this Phase 2 checkpoint, the guide remained shallow until Slice 5 consumed the structured trace. - -## Phase 3 guide and concepts review (2026-10-01) - -`tk onboard guide` now uses the structured trace from the same scanner Project. It selects one source journey from the current candidate routes, preserves the `explained-flow` section ID, and inserts the new `concepts` section before it when upgrading a marked guide. Source locations in these sections link to repository files. The guide labels calls and write/transaction attempts without asserting that a database write, commit, rollback, queue delivery, or assignment succeeded. Existing human prose and snapshot conflict handling remain in place. No target application was run. - -| Disposable snapshot | Source journey | Curated concepts in main section | Fresh guide run and peak RSS | Guide size | -| --- | --- | --- | ---: | ---: | -| Debtbox `e026773` | `DebtController.addDebt` | Notification, Debt, DebtConsent, Business, Customer | 1.054 s; 311.6 MiB | 32,203 bytes | -| Madar B2C `79cc98e` | `MobileFleetController.assignDriverToTruck` | Shipment, Driver, Fleet, Truck | 5.881 s; 705.5 MiB | 29,656 bytes | - -These are single fresh runs of full guide generation on the same archived revisions as the baseline, including write and snapshot creation. Both stay below twice the baseline time and 1 GiB peak RSS. Memory varies by run. The longer guide is a readability cost to assess in later slices. - -**Madar source check:** `MobileFleetService.assignDriverToTruck` shows the fleet, truck, driver, and running-shipment calls at `mobile-fleet.service.ts:602-625`, then three distinct conditional `queryRunner.manager.save` attempts at `:644`, `:665`, and `:672`. The guide labels `commitTransaction` at `:675`, catch `rollbackTransaction` at `:683`, and `release` at `:690` as unresolved transaction-like calls. It makes no completed assignment or atomicity claim. The data glossary links Shipment, Driver, Fleet, and Truck to declared TypeORM entities and direct relations; the manager save argument is not assigned to a specific entity because the trace does not retain enough type evidence for that claim. - -**Debtbox source check:** The debt creation journey shows merchant/customer/business checks, three separate awaited repository save attempts at `debt.service.ts:156`, `:178`, and `:199`, and a conditional non-awaited notification save call at `:223`. Debt, DebtConsent, and Notification appear through typed repository bindings; Customer and Business appear through custom repository method return types. `DebtRepository.findOrCreateDebtGroup` is linked to its declared `DebtGroup` return, not to the repository's `Debt` base type. Other touched declarations are collapsed below the five main concepts. None of these calls proves persistence or delivery. - -**Neutral and sparse checks:** The two-entity fixture shows OrderEntity's declared `ManyToOne` AccountEntity relation and its inverse `OneToMany` declaration, while stating that AccountEntity has no linked journey call. The invalid-input throw stays separate from write/queue attempts, priority branches stay separate, and `CacheSnapshot.save` is not labeled as persistence. The empty Nest handler remains a candidate, and the plain Node fixture has no TypeORM glossary. Focused tests cover these cases, source links, and insertion of Concepts into an older marked guide with human text intact. - -The supported entity syntax is an imported TypeORM `@Entity` decorator, imported column decorators, and direct relation decorators whose first argument is an arrow such as `() => Target`. Repository links require a typed `Repository<Entity>` base or matching `@InjectRepository(Entity)` parameter plus a declared entity return type for custom methods. String relation targets, dynamic targets, complex return types, and query-runner save argument types are not mapped. No related tests were established by the selected traces in these two snapshots; the guide says so instead of inventing test links. Real newcomer assessment remains pending for Slice 13. - -## Phase 4, Slice 7 continuation review (2026-10-01) - -The onboarding-only scanner recognizes one observed framework pattern: `@nestjs/bullmq` `@InjectQueue(queue)` on a typed `bullmq` Queue, a literal `queue.add(jobName, ...)` in a traced method, and a unique `@Processor(queue)` class extending `WorkerHost` with a `process` body. A shared queue literal or a single resolved `Constants.X` property with a literal fallback supports a **possible continuation**. The guide cites producer call, injection, processor registration, and body. It does not claim enqueue, delivery, order, or handler success. Dynamic job names are omitted; a different queue or multiple handlers remains unconnected. RabbitMQ consumers, HTTP callbacks, and other Bull patterns are not joined by this matcher. - -The neutral `ParcelController.dispatch` guide links `ParcelService.dispatch` at `service.ts:14` to `ParcelProcessor.process` at `worker.ts:3,5` for queue `parcel-jobs` and literal job `assign-parcel`. It separately reports `archive-parcel` on `other-jobs` as unconnected; a dynamic job name receives no edge. `ParcelJobs.inspect` at `scheduled.ts:7,9` is shown as a declared schedule with a direct call linked to the Parcel entity. No scheduled run is inferred. - -In Madar, `ShipmentService.bulkAssignShipment` calls `bulkAssignShipmentQueue.add('assignShipment', ...)` at `shipment.service.ts:2324` with `@InjectQueue(Constants.BULK_ASSIGN_B2B_QUEUE)` at `:383`. `BulkAssignShipmentProcessor` registers that same resolved queue expression at `bulk-assign.processor.ts:8` and declares `process` at `:25`. An explicit trace of `ShipmentController.assignBulkShipment` produced that possible link. The default featured fleet route has no queue publication, so its generated guide correctly shows no connected worker. Debtbox has no supported BullMQ publication/handler pair in this snapshot; no queue edge was invented. - -A fresh whole-guide Madar run after Slice 7 took **6.426 s and 662.3 MiB peak RSS**, with no queue link or scheduled concept link on the default fleet journey. This is below twice the 5.705 s baseline and below 1 GiB. Scheduled concept links require direct calls from a declared Nest scheduled handler through typed repository evidence and are shown only when they touch a featured entity; callbacks and helper effects remain open. - -## Phase 4, Slices 8–9 selection and repository context (2026-10-01) - -The guide now preselects a bounded set of route and scheduled entries using source signals, then chooses up to four traced journeys by method depth, decisions, effects, linked entity declarations, queue continuations, and novel coverage. Near-duplicate paths sharing most traced methods and the same concepts are rejected. The selection reason states source coverage, not business importance. `tk onboard guide --focus Class.method` (or an unambiguous declared route/path) makes one supported entry the first featured journey. Unknown or ambiguous focus fails before writing a guide. A bodyless route remains a candidate. Neutral tests show one of two duplicate Order routes plus a distinct Limits route, and a Parcel route plus scheduled handler; repeat fresh scans produce identical Markdown. - -| Fresh disposable guide run | Featured source journeys | Example rejected candidate | Time; peak RSS | Guide size | -| --- | --- | --- | ---: | ---: | -| Debtbox `e026773` | `PaymentController.getPaymentStatus`, `DebtController.addDebt`, `CustomerEmailVerificationController.verifyEmail`, `DebtController.consentDebt` | `AdminController.verifyMfa` (less novel within the guide limit) | 1.353 s; 298.0 MiB | 86,611 bytes | -| Madar B2C `79cc98e` | `MobileFleetController.assignFleetToShipment`, `IntegrationsController.webhook`, `MobileShipmentController.confirmPickup`, `InvoiceController.updateInvoice` | `MobileFleetController.assignDriverToTruck` (overlapping coverage; available with `--focus`) | 6.230 s; 654.9 MiB | 95,722 bytes | - -These are whole CLI runs after a fresh build, on the archived revisions used above, with macOS child `ru_maxrss`. Both meet the Slice 0 ceiling of twice baseline time and 1 GiB. They are single runs, not stable benchmarks. The selection demonstrates deeper decision/effect paths and multiple distinct entry areas; the larger guide size is a known reading cost reserved for Slice 12. A focused Madar reconciliation guide selected `ShipmentController.triggerB2cPricingReconciliationRun`, cited the nearby `B2cPricingReconciliationService.runReconciliation` source comment at `b2c-pricing-reconciliation.service.ts:78`, and listed its sibling `.spec.ts` as a test candidate. The comment's lock/status explanation is explicitly a source statement, not a verified runtime policy. - -Repository context is bounded to a short README description, comments beside selected method declarations or within their bodies, sibling test files, and migration file names matching selected source owners. Generic Nest starter descriptions, commented-out code, secret-like comments, unrelated text, and long README sections are suppressed. A neutral fixture with a generic starter README displays its explanatory handler comment but no project description; a separate bespoke README test shows a cited description. Debtbox and Madar's generic README opening paragraphs are omitted. Sibling tests are labeled candidates because their assertions are not analyzed. No Git history, application command, or env file was read by this enrichment path. Owner-authored guide text remains under the existing snapshot merge and conflict rules; focused tests checked preservation on regeneration. - -Manual spot checks covered the selected entry/call locations and representative decision, write-like, queue, and comment citations in the generated neutral, Debtbox, and Madar guides. No unsupported runtime completion claim was found in those checks. This is not the independent, every-claim review or unfamiliar-engineer assessment required by Slice 13. - -## Phase 5, Slice 10 setup review (2026-10-01) - -The guide now lists declared package build/start/test/migration/seed scripts separately from README commands, labels generic starter README commands, names Compose services and their declared dependencies, shows only variable **names** from checked-in templates and source, cites migration declarations and a possible GET health route, and offers a proposed order explicitly labeled inferred. It asks before migrations or seeds are run. The personal workspace includes a dated command/result/blocker table; sync preserved an entered observation as personal text. A test with a side-effecting declared start script confirmed `guide` did not execute it. - -The neutral Compose fixture showed `.env.local` as a required file, a `4010:3000` mapping versus a `4000` source listen fallback as a question, a declared `/health` route, and migration/seed questions. The plain Node fixture showed its package start script without inventing services. Debtbox showed a required `.env`, a present mounted `db/init.sql`, and its `3000` mapped port versus `5000` source fallback as a question. Madar showed its Compose `.env` requirement; no claim was made that the file or any service was available. No target application, migration, container, endpoint, or test command was run in these guide checks. - -### Slice 11 progress strategy, before implementation - -Keep the four existing `v2:` exercise IDs and their JSON schema/status/snapshot unchanged. Treat them as stable umbrellas for concept mapping, source journeys, a local observation, and change-point/questions work. Generate guide-specific subgoals only in a **new** personal workspace. Never rewrite an existing personal Markdown file during guide regeneration or plan/status, so completed boxes, notes, evidence, questions, and legacy JSON remain byte-for-byte intact. A new workspace records its selected journey symbols as local guide-link markers; plan/status compares those markers with the current guide and flags disappeared journeys without deleting the user's work. Older workspaces without markers remain valid, and no migration is needed. Self-reported completion remains separate from source-backed understanding. - -### Slice 11 result - -A fresh neutral Parcel workspace asks for a cited Parcel concept map, an explanation of `ParcelController.dispatch` and `ParcelJobs.inspect` including alternate exits and unsupported edges, an actual local observation or blocker, and a likely change/test point plus classified questions. `tk onboard plan` shows those guide-specific objectives; `status` retains self-reported progress. In a changed-guide test, the shared guide dropped `ParcelJobs.inspect`: status flagged its stale local link while the completed `v2:trace-flow` checkbox, JSON status, and personal notes remained unchanged. Existing sync conflict, legacy progress, sparse-guide, and four-ID tests passed. No completion status is interpreted as verified competence. - -### Slice 12 reading and regeneration review - -The complete small neutral guide is at `/tmp/tk-p5-small-cbDkiY/ONBOARDING.md` (8,115 bytes), and the complete large Madar guide is at `/tmp/tk-p5-madar-ooSzOe/ONBOARDING.md` (about 100 KiB). The large guide now starts with 6 lines of orientation and a short system map: bootstrap, technology, root module, store, and four declared route-to-service call targets with source links. Its former very long root-import and job/integration lists are in the collapsed reference appendix. The reading order is Start here → System map → Concepts → Connected journeys → Change points → Run and observe → Specific questions → Reference appendix. No unsupported diagram was added. The full journey detail and gaps remain in Connected journeys; 359 large-guide source links and 337 Debtbox source links resolved to existing files and in-range lines in the archived snapshots. - -Stable managed IDs `system-overview`, `explained-flow`, `setup-and-operations`, and `unknowns` remain behind the renamed headings, with explicit anchors for existing workspace links. Journey anchors derive from source symbols. Regeneration tests covered identical reruns, changed findings, old marked heading upgrades, independent owner-written System context and Verified local setup, conflicting human edits, missing/malformed snapshots or markers, and refusal to overwrite an unmarked guide. A human-edited managed section still requires conflict resolution when its generated content also changes; it is not silently discarded. The appendix preserves prior inventories and candidate routes under a collapsed details block. - -Final fresh whole-guide runs on the same archived revisions took **1.358 s / 298.9 MiB** for Debtbox and **6.396 s / 694.6 MiB** for Madar, below the twice-baseline time and 1 GiB limits. The scanner loaded 490 and 2,311 TypeScript files respectively and traced 18 and 19 candidate entries before featuring four journeys in each guide. The larger full guide remains a reading cost, but its first screen is short; independent newcomer usefulness and a comprehensive statement-by-statement accuracy assessment remain for Slice 13. diff --git a/docs/ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md b/docs/ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md deleted file mode 100644 index 27cc572..0000000 --- a/docs/ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md +++ /dev/null @@ -1,118 +0,0 @@ -# Human-first onboarding — Phase 0 acceptance baseline - -**2026-10-03.** This is a local planning and evaluation artifact. It locks the examples and answer keys for the [human-first plan](ONBOARDING_HUMAN_STORY_PLAN.md); it does not certify the current guide or close Milestone 9. The generated guides were made in disposable copies and are reproducible with: - -```text -npm run build -python3 experiments/onboarding-phase6-regression.py \ - --out /tmp/<new-directory> \ - --debtbox /path/to/debtbox-backend \ - --madar /path/to/b2c-backend -``` - -This run used TransferKit HEAD `cb7c25e3e371` **with existing uncommitted onboarding changes**; the built CLI bundle SHA-256 was `379501c91fc9a921ac4455224aa6b57c1a8c06d2bf79f3e809021fa34fd348ad`. Debtbox was archived at `e0267736a40a3181aae1c463782fe0f0436975c7`; B2C at `79cc98e534a95a2a316c3464281619fb86a12d99`. No evaluated application, dependency installer, container, migration, or endpoint was run. The results and complete generated Markdown from this run are in `/tmp/tk-human-phase0-20261003-verified/`; the script can recreate them if temporary files are removed. - -## Baseline measurements - -“Opening words” counts the generated **Start here + System map** text after removing markup and link targets. Time is one local first run of `tk onboard guide`; peak RSS is macOS `wait4` child `ru_maxrss`. These are indicators, not performance benchmarks. All checked Markdown source links resolve to a file and line in their disposable snapshot; that check does not prove the sentence is true. - -| Case | Guide bytes | Opening words | Featured source journeys | Guide time | Peak RSS | Source links / broken | Guide SHA-256 prefix | -| --- | ---: | ---: | ---: | ---: | ---: | ---: | --- | -| Plain Node app | 2,985 | 82 | 0 | 0.151 s | 134.0 MiB | 2 / 0 | `6187bd05d292` | -| Nest queue + scheduled worker | 8,101 | 76 | 2 | 0.310 s | 187.2 MiB | 42 / 0 | `f46b829ae799` | -| Branch/transaction negative fixture | 10,824 | 79 | 2 | 0.321 s | 194.3 MiB | 70 / 0 | `33c5e769b38a` | -| Non-Nest Event Count CLI | 2,999 | 86 | 0 | 0.148 s | 115.0 MiB | 2 / 0 | `9f7e0ad88deb` | -| Sparse Python CSV utility | 2,845 | 71 | 0 | 0.150 s | 123.3 MiB | 1 / 0 | `43e539d8fd20` | -| Debtbox | 90,145 | 122 | 4 | 1.282 s | 302.5 MiB | 337 / 0 | `03c6ced17676` | -| B2C backend | 99,899 | 123 | 4 | 6.425 s | 712.9 MiB | 359 / 0 | `155f8e88edb3` | - -The extra branch fixture protects existing path precision during later narrative changes. B2C and Debtbox remain below the earlier 2× time and 1 GiB RSS budgets on this run. Larger guides have short openings but require the reader to infer relationships from long journeys. - -**Representative current output:** B2C begins its map with “Bootstrap: src/main.ts creates AppModule” and selected controller → service targets; its first featured journey is fleet assignment. The CLI quotes “reads a newline-delimited JSON event file and prints a count for each event type” but then says “No source journey was selected” and “No supported route candidate was found.” The Python case quotes its README purpose yet also asks how to start the app despite the documented `python3 compare.py` command. These are short excerpts from the generated files identified by the hashes above, not proposed wording. - -## Answer keys and short human references - -These are **reviewer keys**, not text for the generator to copy. “Purpose” below is either a checked-in statement or a bounded reading of code. The five questions in each case are: (1) purpose, (2) important concepts, (3) normal path, (4) alternate or independent path, and (5) first change/test/observation. The improvement gate is that a newcomer can find supported answers quickly and sees unsupported answers labeled as questions. - -### B2C backend — large delivery service - -**Human reference:** [B2C newcomer working guide](B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md). It reads the repository around a shipment and separates internal mobile-driver actions from external fleet callbacks. Business terminology and operational ownership remain owner questions. - -1. **Purpose:** Source supports a service coordinating B2C shipment creation, assignment, progress, and related financial workflows; no credible project-purpose paragraph exists in the starter README. `src/module/shipment/services/shipment-b2c.service.ts:648`, `src/module/fleet/services/mobile-fleet.service.ts:67`, `src/module/integrations/integrations.service.ts:630`, `src/module/invoice/invoice.service.ts:723`. -2. **Concepts:** Shipment, its history, vendor, fleet/driver, transaction and invoice have distinct code roles. Business definitions of vendor/customer/seller need an owner. `src/module/data/entity/shipment.entity.ts:103,157,250,293,364,387,402,434`. -3. **Normal path:** B2C creation checks duplicate identifiers; a mobile fleet assignment checks shipment/fleet/driver eligibility and writes assignment/history; driver pickup checks status and vendor configuration. These are separate entry points around the same shipment, not a proven automatic call chain. `shipment-b2c.service.ts:663–717`, `mobile-fleet.service.ts:78–239`, `pickup.service.ts:150–251`. -4. **Alternate/independent path:** An external fleet webhook has fleet/AWB/history gates and may return early; cancellation/RTO handling differs from the mobile-driver path. Invoice updates are a separate financial workflow. `integrations.service.ts:630–780`, `invoice.service.ts:723–840`. -5. **First action:** For an assignment rule, inspect controller → service guards → shipment/history → related tests. For a safe observation, read `GET /health-check` only in an approved local environment; it proves an HTTP response, not dependency health. `mobile-fleet.controller.ts:22–40`, `mobile-fleet.service.ts:67–149`, `src/module/health-check/health-check.controller.ts:20–29`. - -**Current guide gap:** It features fleet assignment, webhook, pickup and invoice as independent traces but omits shipment creation from the featured set and gives no explanation of their relationship. Its starter README yields no project description. A review of selected decisions and source citations found no material false branch or transaction assertion; the main failure is story omission and reading burden, not a demonstrated false runtime claim. - -### Debtbox — debt and consent paths - -**Human reference:** The [illustrative Debtbox fixture](ONBOARDING_V2_DEBTBOX_FIXTURE.md) gives a short source-backed debt creation/consent story. It is a design target, not measured newcomer success or an owner-approved business mission. - -1. **Purpose:** Code supports merchant debt creation, customer consent, payment status and related notifications. Broader product mission and business priority are not established by repository evidence. `src/module/debt/debt.controller.ts:37,54`, `src/module/payment/payment.controller.ts:50`. -2. **Concepts:** Merchant, customer, debt, debt consent and payment are distinct records/roles; the exact commercial meaning is an owner question. `src/module/debt/debt.service.ts:100–155,267–302`. -3. **Normal path:** Debt creation validates merchant/customer/business, rejects a pending duplicate, then attempts separate debt, consent and notification saves. `debt.service.ts:104–199`. -4. **Alternate path:** Consent checks ownership, pending status and expiry. Acceptance sets active and may attempt signature/Sanad work; rejection sets cancelled. A caught signature-upload error does not prove that all effects completed. `debt.service.ts:273–356`. -5. **First action:** Start with the matching controller and service, then inspect affected repositories and tests before changing a guard. A local run requires verified prerequisites; the generated guide has no verified execution. `debt.controller.ts:37–80`, `debt.service.ts:100,267`. - -**Current guide gap:** It selects payment status first and renders debt creation and consent as separate long traces; it does not state their shared record and business question up front. Prior Phase 6 spot checks found no material false branch/transaction claim in selected excerpts; a full owner review is still needed for business meaning. - -### Plain Node app — supported source, no TypeScript trace - -**Human reference:** The project is a small parcel-status HTTP service. `src/server.js:1–22` creates `/health` and a `/parcels/` lookup over an in-memory `Map`; `README.md:3–5` documents `npm start` and `PORT`. It has no persistent store in this fixture. - -1. **Purpose:** Health and parcel-status lookup, as stated by README and visible in source. -2. **Concepts:** A parcel ID maps to an in-memory status; there is no domain entity or database declaration. -3. **Normal path:** A request to `/parcels/parcel-1` finds the map entry and returns status with 200 (`src/server.js:10–17`). -4. **Alternate path:** Missing parcel returns 404; unmatched route returns 404 (`src/server.js:13–20`). -5. **First action:** Change or test route behavior in `src/server.js`; `npm start` is documented but was not run for this baseline. - -**Current guide gap:** It quotes the README and names the entry file but gives no source journey, route behavior, or change location. “No supported route candidate” describes scanner coverage, not the absence of HTTP behavior. - -### Nest queue + scheduled worker — no credible product purpose - -**Human reference:** This is a neutral test fixture. Its README is a Nest starter, so no business purpose should be invented. `ParcelController.dispatch` calls a service that reads a repository and publishes a literal `assign-parcel` job to `parcel-jobs`; a separately scheduled `ParcelJobs.inspect` also reads the repository. The matching worker declares an empty `process` body, so no job effect is established. `controller.ts:5–12`, `service.ts:10–20`, `worker.ts:3–7`, `scheduled.ts:6–10`. - -1. **Purpose:** Unknown beyond exercising route, queue and schedule declarations; starter README cannot supply one. -2. **Concepts:** Parcel repository, queue publication, worker registration and scheduled inspection are code roles, not a verified business flow. -3. **Normal path:** The dispatch route delegates to the service; the service read precedes a literal queue `add` attempt (`controller.ts:8–10`, `service.ts:12–15`). -4. **Alternate/independent path:** `other-jobs` and dynamic job names are not a proven continuation to the `parcel-jobs` worker. The scheduled read is independent, not a result of dispatch (`service.ts:16–19`, `scheduled.ts:7–10`). -5. **First action:** To change the publication, inspect `service.ts` and `worker.ts`; to change the schedule, inspect `scheduled.ts`. No runtime queue processing or test result was verified. - -**Current guide gap:** It correctly labels a possible continuation and a separate scheduled handler, but does not explain why these are separate starting points in one short paragraph. The README is correctly not promoted to project purpose. - -### Non-Nest Event Count CLI — input to output - -**Human reference:** The fixture reads a newline-delimited JSON file and prints sorted counts by event `type`, without a database or network call. `README.md:3–5`, `src/cli.js:1–29`. Its story is command → file → parse/validate → count → stdout, not an HTTP route or entity lifecycle. - -1. **Purpose:** Count event types in a local JSONL file, from README and source. -2. **Concepts:** Input path, event `type`, count map and stdout are the important artifacts (`src/cli.js:4–24`). -3. **Normal path:** With a file path, it reads nonempty lines, parses JSON, counts types and prints sorted results (`src/cli.js:9–24`). -4. **Alternate path:** Missing input prints usage and sets exit code 2; malformed JSON or non-string `type` prints an error and sets exit code 1 (`src/cli.js:5–7,14–27`). -5. **First action:** Inspect `src/cli.js` for validation/output changes; the documented command needs a file argument. A disposable JSONL input can be used for a safe first observation if a person chooses to run it. - -**Current guide gap:** It quotes the purpose and entry file, yet asks which test/install commands exist and shows `npm run start` without the required file argument. “No route candidate” is irrelevant to a CLI; no change or failure path is offered. - -### Sparse Python CSV utility — unsupported language, honest fallback - -**Human reference:** The README states that a small Python script compares item counts in two CSV files and writes nonzero differences to stdout. `compare.py:5–18` shows dictionary loading and `actual − expected` for each item. Deployment, owner and tests are not documented. - -1. **Purpose:** Compare expected and actual CSV counts, from `README.md:3` and `compare.py:5–18`. -2. **Concepts:** Two input CSV files, `item` and `count` columns, and difference rows. There is no supported Node/Nest entity model. -3. **Normal path:** Given two paths, load both dictionaries and print each nonzero difference in sorted item order (`compare.py:10–18`). -4. **Alternate path:** Missing arguments exit with usage; invalid file/column/count can raise an error because there is no local handling (`compare.py:5–12`). -5. **First action:** Inspect `compare.py` and the documented invocation in `README.md:5`; a person may use disposable CSV files for a safe observation. Test command and real data source remain unknown. - -**Current guide gap:** It quotes the README but says “confirm the application start command” even though the README provides one. Its route-candidate language is irrelevant, and it gives no input/output or change explanation. This is a product usefulness gap rather than a proven false behavioral claim. - -## Negative cases and review boundary - -- Do not turn a starter README into a business purpose (Nest worker, B2C). -- Do not join B2C creation, mobile assignment, external webhook and invoice into a single automatic call chain; their shared shipment record is a supported relationship, their chronology is not established for every case. -- Do not say Debtbox consent acceptance, signature storage or notification succeeded from static calls. Preserve the rejected/expired branches. -- Do not describe an empty worker body as having processed a parcel or a scheduled read as caused by a queue publication. -- Do not describe in-memory Node/CLI/Python fixtures as having a database, or treat “no Nest route candidate” as “the repo has no entry point.” -- Do not assert tests are absent when only trace-adjacent test discovery failed. Distinguish **not found by this scan** from **verified absent**. - -The small fixture source was read directly for these keys. For B2C and Debtbox, the prior [Phase 6 spot check](ONBOARDING_PHASE6_ACCEPTANCE.md#accuracy-and-readability-review) validated selected entry/decision citations, while this baseline reviewed representative paths and guide omissions. It is not a complete manual audit of every statement in the two large generated guides. The real unfamiliar-engineer comparison remains pending. diff --git a/docs/ONBOARDING_HUMAN_STORY_PLAN.md b/docs/ONBOARDING_HUMAN_STORY_PLAN.md deleted file mode 100644 index 396923d..0000000 --- a/docs/ONBOARDING_HUMAN_STORY_PLAN.md +++ /dev/null @@ -1,98 +0,0 @@ -# Human-first onboarding guide enhancement plan - -**Status:** Phases 0–4 complete; Phase 5 pending. The [Phase 0 acceptance baseline](ONBOARDING_HUMAN_STORY_PHASE0_BASELINE.md) records cross-repository answer keys and measurements. Phase 1 adds a typed, cited story inventory; Phase 2 selects bounded story chapters and classifies supported or unproven connections; Phase 3 renders a human reading path; Phase 4 aligns personal exercises with it. This follows the existing [repository-only deep guide work](ONBOARDING_DEEP_GUIDE_PLAN.md). Its source traces, evidence rules, personal workspace, and safe regeneration remain the foundation. Milestone 9's real unfamiliar-engineer assessment is still open. - -## Why this change is needed - -The current guide is good at showing *where code is* and *what a bounded static trace saw*. It is weak at answering the first questions of a solo newcomer: **What does this repository do? What are its important things? How does work enter, move, and finish? Which path should I read for my task?** The [B2C reference guide](B2C_BACKEND_HUMAN_ONBOARDING_REFERENCE.md) demonstrates the desired reading experience, but its shipment vocabulary and lifecycle are examples, not a template to hard-code. - -In the current pipeline, `onboarding-journey-selection.ts` scores method counts, checks, writes, and continuations; `onboarding-concepts.ts` ranks entities by nearby calls; `onboarding-guide.ts` renders those selections largely as declarations and events. `onboarding-repository-notes.ts` extracts a short README paragraph and nearby comments. None of these creates a repository-level purpose, groups related paths into a supported workflow, or explains why a developer should read one path before another. The B2C guide therefore has 807 lines and 359 links while leaving the newcomer to assemble the system story. - -## Target result - -The first screen of `ONBOARDING.md` should orient a newcomer in plain language, then lead them from a relevant question to evidence. Use this order when the evidence permits: - -1. **What this repository appears to do:** purpose, deliverable or service, inputs and outputs, and the limits of the claim. -2. **A small mental model:** three to five important records, actors, or artifacts and how they relate. Explain a term only when repository prose or behavior supports its meaning; otherwise give its code role and ask for business meaning. -3. **How work moves:** one representative path from an entry to an observable result, then a second genuinely distinct path or an alternate/failure path. State whether paths are causally connected, share state, or are merely related by name. -4. **Where and when to look:** a task-to-file/test map, a safe first investigation, setup prerequisites and exact blockers. -5. **What still needs a person:** business intent, ownership, operational recovery, and other facts that source cannot establish. - -Put exhaustive traces, entity fields, module inventories, and secondary route candidates in a collapsed reference appendix. Keep every source claim inspectable. The guide may be short for a sparse or unsupported repository; it must never fill gaps with a plausible invented story. - -### Generic shape, not a universal lifecycle - -The same questions apply to a service, CLI, library, frontend, worker, or data job, but the nouns differ. A service may read as request → rule → state → response/event; a CLI as command → input → transformation → file/output; a library as public API → internal operation → return/error; a worker as trigger → handler → state/output. Select a shape only from observed entry and output evidence. If the repository is mixed or its purpose is unclear, show multiple candidate entry points and say what is unknown. NestJS, TypeORM, shipments, and invoices are never prerequisites for an intelligible guide. - -## Evidence and writing rules - -- **Every substantive sentence has provenance.** Use a small claim record carrying source locations and one of: repository statement, code observation, conservative inference, owner-supplied context, or unknown. A citation must support the *whole* sentence, not merely contain a matching symbol. -- **Keep causality strict.** A call edge, matched queue publication/handler, or explicit data dependency can connect steps. Shared entity names, imports, and chronological guesses make *related paths*, not a continuous workflow. State whether a write, notification, or external effect was attempted; do not assert runtime success from source alone. -- **Explain code in human terms without inventing policy.** “This check rejects a shipment already assigned to a fleet” is supportable from a guard. “The fleet has accepted commercial responsibility” requires a documented business rule or owner statement. Names alone do not define a business actor. -- **Use owner knowledge deliberately.** Reuse existing owner-editable `System context` and `Verified local setup` areas. Label owner statements and their author/date only when supplied; preserve them byte-for-byte across rescans. If owner context conflicts with code, show both and ask for review. -- **Respect repository boundaries.** Read only checked-in text/code needed for selected claims; skip secrets and values. Generation never installs dependencies, starts apps, runs migrations, or calls external services. The core remains framework independent; scanners emit evidence, standards choose and connect it, renderers format it, and CLI orchestrates. -- **Keep the first screen small.** Measure whether a reader can answer the five newcomer questions from the opening without expanding the appendix. Use size as a readability signal, not as proof of usefulness. - -## Ordered implementation checklist - -### Phase 0 — Lock a cross-repository acceptance set - -- [x] Capture the current generated guide and a short human reference for **B2C, Debtbox, a plain Node app, a non-Nest CLI or library, a worker/job, and a sparse or unsupported-language repository**. Reuse existing fixtures where suitable; add only minimal new ones. -- [x] For each repository, write five answer-key questions: purpose, important concepts, one normal path, an alternate/independent path, and first change/test/observation. Mark which answers are source-supported, owner-supplied, or genuinely unknown. -- [x] Record baseline first-screen word count, guide size, selected paths, broken/unsupported claims, run time and peak RSS. Keep the B2C human guide as a **style and utility reference**, not as an expected string or universal domain model. - -**Gate:** A reviewer can identify what a better guide must answer for each repository without assuming that every repository has HTTP routes, database entities, or a full lifecycle. - -### Phase 1 — Build a cited repository story inventory - -- [x] Discover a small set of likely purpose statements from project-specific README sections and relevant checked-in docs. Detect starter/boilerplate text and avoid promoting it to project purpose. Inspect manifests, executable entry points, public APIs, commands, handlers, tests and configuration as corroborating evidence. -- [x] Represent repository role, entry points, important data/artifacts, outputs, external boundaries, and safe observation candidates as typed, bounded claims with provenance and uncertainty. Keep this structured state separate from Markdown. -- [x] Identify a few central terms from repeated use across entries and outputs, then attach only supported descriptions. An entity declaration alone gives a code role, not business meaning. Preserve exact evidence for rejected or ambiguous descriptions. - -**Gate:** On B2C, the inventory can support “shipment is central” and distinguish vendor/fleet/driver relations without defining their business contracts. On a CLI/library it identifies commands/public APIs and outputs. On a sparse repo it gives a useful inventory plus explicit questions, with no invented purpose. - -### Phase 2 — Connect and select stories, not just deep traces - -- [x] Group paths by *supported* shared state, call/event continuation, or documented workflow. Record edge type: direct call, possible asynchronous continuation, shared artifact, documented relation, or unproven association. -- [x] Choose a representative entry and complementary path for newcomer coverage: where work starts, a key decision, state/output, and a failure or alternate path. Let a documented purpose and core record weigh more than raw method/branch count. Retain `--focus` for a developer's specific question. -- [x] Do not force a single sequence. If creation, callback, and invoice are independent entry points touching the same record, show them as separate chapters around that record. If an edge is missing, state the first unsupported boundary and what to inspect next. -- [x] Keep deep trace limits and negative cases: no false path joining, callback execution, transaction completion, provider delivery, or dynamic target certainty. - -**Gate:** B2C selection explains shipment creation/assignment and distinguishes mobile status from external callbacks; Debtbox selects a coherent ownership-relevant path; a CLI/library follows its own input-to-output shape. Selected paths may differ when repository evidence differs, but each selection has a recorded reason. - -**Phase 2 check:** On pinned snapshots, B2C selects shipment creation, fleet assignment, mobile pickup, and the external webhook as separate entries. Debtbox starts with debt creation and consent. The non-Nest CLI and sparse Python cases retain documented input/output chapters with an explicit source-trace boundary. The final seven-case regression found no broken source links; B2C generation was 6.605 s and 713.2 MiB peak RSS. These checks assess selection and citations, not newcomer usefulness. - -### Phase 3 — Render the human reading path - -- [x] Introduce a short “What this repo does” and “How to read it” opening from Phase 1 claims, with visible inference/unknown labels where needed. -- [x] Replace the opening entity inventory with a three-to-five-term glossary: term, code role, supported meaning, and why the newcomer will encounter it. Move relation and field lists to the appendix. -- [x] Render each selected story as **why this path matters → trigger/input → decision → state or output → alternate exit → external boundary → where to change/test**, using brief prose and nearby grouped citations. Keep the raw event trace available in collapsed details. -- [x] Add a task-to-file/test map and one safe first investigation chosen from actual code and test evidence. Do not say tests are absent merely because the current trace did not discover them. -- [x] Keep setup specific: engine/version and meaningful declared dependencies, documented versus verified commands, safe observation, and blockers. Preserve the current guide markers, snapshot reconciliation, owner sections, and all personal workspace data. - -**Gate:** A reviewer answers the five Phase 0 questions from the opening and stories without reading the appendix. Every behavioral sentence is supported by its cited code or clearly labeled as a repository/owner statement or inference. No human edit disappears on regeneration. - -**Phase 3 check:** Seven disposable repository cases generated with no broken source links; the featured B2C and Debtbox entries, CLI input/error path, sparse Python fallback, and plain Node setup were inspected. B2C generation was 6.607 s / 718.3 MiB peak RSS; Debtbox was 1.333 s / 308.2 MiB. The full 287-test suite, typecheck, lint, and format check pass, including guide regeneration and owner-note preservation. The generated guides and measurements are reproducible at `/tmp/tk-human-phase3-verified/` with the Phase 0 regression command. This is source-based review, not the independent newcomer assessment in Phase 5. - -### Phase 4 — Align personal learning with the story - -- [x] Make the existing stable `v2:` exercises point to the new mental model, selected stories, change map, and safe observation. Keep their IDs, checked boxes, notes, questions, evidence and legacy progress intact. -- [x] When source selection changes, preserve completed work and flag stale links. A checked exercise remains self-reported progress, never a competence certificate. - -**Gate:** A newcomer can record what they understood, tried, and still need to ask without copying the whole guide. Sync and conflict tests continue to protect both Markdown and structured progress. - -**Phase 4 check:** Existing exercise IDs and progress storage remain unchanged. A disposable CLI guide exercise links its documented entry and the change map; after the guide entry is changed, status reports the stale link while keeping its completed checkbox, structured state, question, evidence, and note. Build, typecheck, lint, formatting, and all 288 tests pass, including sync and conflict tests. This checks preservation and navigation; independent newcomer utility remains Phase 5. - -### Phase 5 — Independent accuracy, utility, and performance review - -- [ ] Run all acceptance repositories from disposable snapshots. Compare old/new answers, guide size and first-screen readability, generation time, peak RSS, and exact citations. Manually inspect every material claim in the featured stories against source; record omissions and misleading wording. -- [ ] Ask an unfamiliar engineer to do repository-only tasks with and without the guide, using the existing [assessment protocol](ONBOARDING_PHASE6_ACCEPTANCE.md#unfamiliar-engineer-task-protocol--pending). Record correctness, irrelevant searches/questions, first safe observation or blocker, and misleading claims. A code-only self-review cannot close this gate. -- [ ] Fix material false claims and navigation failures before changing Milestone 9 status. Compare on multiple repository shapes; success on B2C and Debtbox alone is insufficient for the generic claim. - -**Gate:** The new guide improves answer correctness or reduces irrelevant search/questions for actual newcomers across the evaluated shapes, has no material false behavioral claim, preserves human edits, and stays within the existing time/RSS budgets or documents an explicit reviewed exception. Keep the milestone open if no engineer is available. - -## Deliberate limits - -This plan does not add hosted services, implicit AI, runtime execution, new language-specific deep tracers, or a business ontology. A non-TypeScript repository can still get a useful overview from its own documentation, manifests, public entry points, tests, and artifacts; unsupported inner behavior remains a cited gap. Optional AI prose may be considered later only as an opt-in rewrite of vetted claims, never as a source of new facts. - -Phases 0–4 are complete. The next implementation request can start **Phase 5 only**; the B2C example remains a reviewer reference, not a product template. diff --git a/docs/ONBOARDING_PHASE6_ACCEPTANCE.md b/docs/ONBOARDING_PHASE6_ACCEPTANCE.md deleted file mode 100644 index de08838..0000000 --- a/docs/ONBOARDING_PHASE6_ACCEPTANCE.md +++ /dev/null @@ -1,36 +0,0 @@ -# Onboarding Phase 6 acceptance record - -**2026-10-02 — repository-only regression complete; newcomer assessment pending.** This is a local acceptance record, not a claim that Milestone 9 has passed. - -## Repeatable regression - -Build TransferKit, then run `python3 experiments/onboarding-phase6-regression.py --out /tmp/<new-directory> --debtbox /path/to/debtbox-backend --madar /path/to/b2c-backend`. The script copies neutral fixtures and archives pinned revisions of the two application repositories into disposable directories. It runs only `tk onboard guide` and `tk onboard workspace`, saving each guide, workspace, and `results.json`. It does not install dependencies or run target applications. Debtbox and Madar paths are optional; omit an unavailable repository and mark that case untested. - -| Snapshot | Selected journeys | Guide size | First guide run | Peak RSS | -| --- | ---: | ---: | ---: | ---: | -| Plain Node source fixture | 0 | 2,985 bytes | 0.166 s | 128.6 MiB | -| Neutral Nest queue/scheduled fixture | 2 | 8,101 bytes | 0.316 s | 185.8 MiB | -| Neutral branch/transaction fixture | 2 | 10,824 bytes | 0.326 s | 187.3 MiB | -| Debtbox `e0267736` | 4 | 90,145 bytes | 1.322 s | 300.1 MiB | -| Madar B2C `79cc98e5` | 4 | 99,899 bytes | 6.631 s | 720.9 MiB | - -This is one local macOS run, so timings are indicative. Compared with the same pinned Debtbox and Madar revisions in [the original baseline](ONBOARDING_DEPTH_BASELINE.md), guide time is 1.18× and 1.16× respectively; both remain below the 2× and 1 GiB budgets. Guide size rose from 13,383 to 90,145 bytes for Debtbox and from 12,763 to 99,899 bytes for Madar. The opening map stays short and long inventories are collapsed, but a real reader has not yet judged whether the larger journey sections are readable. The new plain Node and neutral Nest fixtures differ from the baseline fixtures, so their run times are not a like-for-like performance comparison. - -The plain Node map now quotes the README's health and in-memory lookup description, cites its declared `src/server.js` entry, and leaves runtime behavior unverified. It selects no traced journey because JavaScript bodies are outside the current TypeScript trace scanner. The neutral Nest guide links `ParcelController.dispatch` to a possible queue continuation and selects `ParcelJobs.inspect` separately; the mismatched worker is not connected. The neutral branch guide keeps the invalid-input throw separate from later reads, keeps priority/standard assignments mutually exclusive, lists transaction calls as attempts, and leaves callback/dynamic calls unresolved. Debtbox selects payment status, debt creation, email verification, and consent; Madar selects fleet assignment, webhook, pickup confirmation, and invoice update. These are source coverage choices, not a business-priority ranking. - -## Accuracy and readability review - -All rendered local source links were checked against the snapshot files and line bounds: 2 plain Node, 42 neutral Nest, 70 neutral branch, 337 Debtbox, and 359 Madar; no broken or out-of-range link was found. The neutral branch guide was reviewed against its entire six-file fixture for branch exits, repeated helper calls, manager alias, queue name matching, and unsupported edges. For each of the eight selected Debtbox/Madar journeys, the entry declaration and the first displayed decision or alternate throw were compared with the cited source. Representative matches: Debtbox payment missing-checkout guard at `payment.service.ts:278`, debt missing-merchant guard at `debt.service.ts:105`, email verification missing-customer guard at `customer-email-verification.service.ts:95`, consent missing-debt guard at `debt.service.ts:276`; Madar fleet missing-shipment guard at `mobile-fleet.service.ts:79`, webhook missing-shipment guard at `integrations.service.ts:649`, pickup status guard at `pickup.service.ts:159`, and invoice permission guard at `invoice.service.ts:725`. No material false call, branch, or transaction assertion was found in those checks. This is a spot check, not a manual reading of every line in the two large guides. - -The source-linked journeys present an entry, a decision or an explicit lack of one, alternate exits where traced, an unsupported boundary, and initial change locations. Test locations are described as unestablished where no related test was found. The plain Node guide has only a README-based overview and declared start entry, and explicitly has no selected source journey. Readability remains a reviewer limit for the 90–100 KiB guides, especially their longer journey sections. No application behavior or setup outcome was verified. - -## Unfamiliar engineer task protocol — pending - -Use a real engineer who has not worked in the selected repository. A source-aware reviewer first prepares a short answer key for two comparable tasks in that repository, including expected record concepts, two paths, an alternate exit, likely change and test files, and a safe observation or exact setup blocker. Keep the answer key separate from the guide and participant. - -1. Give the participant one task with repository files only. Record start/end time, source searches, questions asked, answer, first safe observation or blocker, and misleading material encountered. -2. Give a second comparable task with the generated guide and personal workspace available. Record the same data. Alternate task order across participants if more than one engineer is available; with one engineer, report carryover and task-difficulty limits rather than treating the comparison as controlled. -3. For each task ask the engineer to explain the key records and two distinct paths, identify an alternate or failure path, point to files/tests for a small change, try a safe first observation or name its exact blocker, and list questions requiring a teammate. Do not require risky setup commands or credentials. -4. Score each answer **correct**, **partly correct**, or **unsupported** against the prepared key, with citations. Count irrelevant searches and unresolved questions in both conditions. Record any misleading guide claim and fix it before declaring success. A confidence rating may be collected but is not the gate. - -No engineer has completed this protocol. Therefore there is no measured repository-only newcomer improvement, and Milestone 9 remains **IN PROGRESS**. Milestone 10's handover-assisted assessment remains separate and untouched. diff --git a/docs/ONBOARDING_V2.md b/docs/ONBOARDING_V2.md deleted file mode 100644 index 3f35ea5..0000000 --- a/docs/ONBOARDING_V2.md +++ /dev/null @@ -1,49 +0,0 @@ -# Onboarding v2 — Product and Design Specification - -**Status: Milestone 9 in progress.** The repository-only guide now includes bounded source-backed journeys, concepts, setup evidence, and change points. The personal workspace has four stable `v2:` exercises, Markdown/JSON checkbox sync, and v2-aware plan/status. Fixture regression and source spot checks are recorded in the [Phase 6 acceptance record](ONBOARDING_PHASE6_ACCEPTANCE.md); a real unfamiliar-engineer comparison is still pending. The [illustrative Debtbox fixture](ONBOARDING_V2_DEBTBOX_FIXTURE.md) remains a design target, 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 current guide's generated portions come from repository evidence. Managed section markers and a generation snapshot preserve unrelated human prose and surface conflicting edits; an existing unmarked guide is not overwritten. Later layouts must retain this reconciliation behavior. Optional linked Transfer context remains future work. - -## Content and evidence contract - -The guide should start with a concise system overview and a map of supported entry points, modules, data stores, integrations, background work, and relationships. A curated concepts section should distinguish data shapes from business meanings. Show a few complementary, connected journeys where source permits, each with entry, inputs, decisions and alternate exits, visible read/write attempts, helper or job continuations, gaps, and relevant code/tests to inspect for a change. Describe setup and operations from checked-in evidence, and keep precise unknowns prominent. Sparse repositories may have fewer journeys. Avoid flat dependency lists, invented business purpose, 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. Exercises should ultimately use the selected concepts and journeys to ask for an explanation, a likely change point, and a recorded local observation or exact blocker. 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 - -The initial repository-only guide and personal workspace slices are implemented. Follow the ordered [deep guide slices](ONBOARDING_DEEP_GUIDE_PLAN.md) for acceptance fixtures, bounded tracing, concepts and continuations, setup, adaptive exercises, guide regeneration, and a real repository-only newcomer assessment. The four existing `v2:` IDs and legacy progress must survive later improvements. - -### Slice 0 acceptance cases - -These are source-grounded assertions for tracing and rendering review. Use the neutral source under `fixtures/onboarding-deep-guide/` and the small JavaScript app under `fixtures/onboarding-plain-node/`. Positive claims must cite the listed source; negative claims must remain absent or be explicit gaps. Test semantic claims and citations rather than whole Markdown whitespace. - -| Case | Required claim and citation | Forbidden claim | -| --- | --- | --- | -| Early throw | `service.ts:44` throws when `valid` is false; later calls are on a different path. | The invalid path reads, saves, queues, or returns an order. | -| Exclusive branch | `service.ts:47-50` assigns either priority or standard status under distinct conditions. | Both status assignments happen on one path. | -| Repeated helper | Both call sites at `service.ts:52-53` link to `OrderService.recordAttempt` at `service.ts:69`. | One invocation is silently collapsed, or constructor injection becomes a call. | -| Local manager alias | `service.ts:54-62` records a query-runner alias, write-like `manager.save`, and separate commit/catch/finally calls. The interface at `service.ts:18-27` has no implementation body. | A write committed, rollback succeeded, or all branches ran. `CacheSnapshot.save` at `service.ts:65` is database persistence. | -| Possible continuation | Enqueue call `service.ts:64` and handler registration `worker.ts:7-10` share `assign-order`; `worker.ts:9` returns before the read when the ID is empty. | The job ran, an empty ID reads a record, or `ArchiveWorker` at `worker.ts:14-16` is connected to this enqueue. | -| Plain Node overview | `src/server.js:1-22` exposes a health path and in-memory parcel lookup; `README.md:3-5` documents `npm start`. | A database, verified run, business purpose beyond the README, or a NestJS flow is invented. | - -Before calling a guide slice readable, a reviewer should locate each selected journey's entry, at least one cited decision or explicit lack of one, an alternate exit where present, the first unsupported edge, and likely change/test files within the journey section. Every substantive behavioral sentence should be verifiable at its cited source. Keep broad inventories out of the opening section; if a small fixture lacks evidence for a journey, say so rather than filling space. This is a reviewer rubric, not an automated understanding score. - -Milestone 9 remains open until the deep repository-only guide and personal workspace pass their gates and an unfamiliar engineer completes the repository-only assessment. If no engineer is available, report that gate as pending. Milestone 10 separately evaluates handover-assisted onboarding and broader real-world outcomes. Optional v3 Item enrichment remains a separate later addition, never a prerequisite for repository-only use. 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/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 006d004..e7abe6d 100644 --- a/packages/cli/README.md +++ b/packages/cli/README.md @@ -1,55 +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 -tk onboard status -tk onboard task <task-id> in-progress -tk onboard task <task-id> completed +# 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 ``` -`guide` writes a shared, source-cited `ONBOARDING.md`; use `guide --focus <route-or-symbol>` to inspect a supported entry. `workspace` creates a personal Markdown checklist in `.transferkit.local/`. After editing its checkboxes, run `sync` to update personal progress, then `status`. Generated paths and commands are static evidence; application behavior and setup remain unverified until a person tries them. Onboarding 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/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/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; +} From 1a460dd998ac380e1466b7fca43dfe4b0828a690 Mon Sep 17 00:00:00 2001 From: alialaraby <alisakralaraby@gmail.com> Date: Sun, 4 Oct 2026 11:45:39 +0300 Subject: [PATCH 7/7] Fix clean CI typecheck for scanner story tests --- .../scanners/src/onboarding-story.test.ts | 92 +++++++++++++------ 1 file changed, 63 insertions(+), 29 deletions(-) diff --git a/packages/scanners/src/onboarding-story.test.ts b/packages/scanners/src/onboarding-story.test.ts index 7d9e792..8d0deda 100644 --- a/packages/scanners/src/onboarding-story.test.ts +++ b/packages/scanners/src/onboarding-story.test.ts @@ -4,7 +4,6 @@ import { fileURLToPath } from "node:url"; import { describe, expect, it } from "vitest"; import type { OnboardingConceptEvidence } from "@transferkit/core"; -import { selectOnboardingStoryInventory } from "@transferkit/standards"; import { discoverOnboardingStoryEvidence } from "./onboarding-story.js"; import { scanOnboardingRepository } from "./index.js"; @@ -17,27 +16,41 @@ const empty: OnboardingConceptEvidence = { injections: [], }; -describe("cited onboarding story inventory", () => { +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 inventory = selectOnboardingStoryInventory(evidence); - expect(inventory.purpose?.text).toContain("event file"); - expect(inventory.entries[0]?.name).toBe("event-count"); + 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( - inventory.artifacts.some((claim) => claim.text.includes("event file")), + claims.some( + (claim) => + claim.kind === "artifact" && claim.text.includes("event file"), + ), ).toBe(true); expect( - inventory.outputs.some((claim) => claim.text.includes("prints a count")), + claims.some( + (claim) => + claim.kind === "output" && claim.text.includes("prints a count"), + ), ).toBe(true); - expect(inventory.entries[0]?.evidence).toContainEqual({ + expect( + claims.find((claim) => claim.kind === "entry")?.evidence, + ).toContainEqual({ file: "src/cli.js", line: 1, }); - expect(inventory.observations).toContainEqual( + expect( + claims.filter((claim) => claim.kind === "observation"), + ).toContainEqual( expect.objectContaining({ text: expect.stringContaining("Documented alternate: A missing path"), evidence: [{ file: "README.md", line: 5 }], @@ -51,15 +64,23 @@ describe("cited onboarding story inventory", () => { [], empty, ); - const inventory = selectOnboardingStoryInventory(evidence); - expect(inventory.purpose?.text).toContain("compares item counts"); - expect(inventory.entries.map((claim) => claim.name)).toContain( - "compare.py", - ); expect( - inventory.outputs.some((claim) => claim.text.includes("standard output")), + 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(inventory.boundaries).toEqual([]); + expect( + evidence.claims.filter((claim) => claim.kind === "boundary"), + ).toEqual([]); }); it("uses a plain Node service description without inventing persistent state", async () => { @@ -68,15 +89,24 @@ describe("cited onboarding story inventory", () => { [], empty, ); - const inventory = selectOnboardingStoryInventory(evidence); - expect(inventory.roles[0]?.text).toContain("service"); expect( - inventory.entries.some((claim) => claim.text.includes("src/server.js")), + 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( - inventory.outputs.some((claim) => claim.text.includes("health check")), + evidence.claims.some( + (claim) => + claim.kind === "output" && claim.text.includes("health check"), + ), ).toBe(true); - expect(inventory.boundaries).toEqual([]); + expect( + evidence.claims.filter((claim) => claim.kind === "boundary"), + ).toEqual([]); }); it("rejects a Nest starter purpose and keeps route, schedule and entity roles bounded", async () => { @@ -87,24 +117,28 @@ describe("cited onboarding story inventory", () => { scanned.findings, scanned.concepts, ); - const inventory = selectOnboardingStoryInventory(evidence); - expect(inventory.purpose).toBeUndefined(); + expect(evidence.claims.some((claim) => claim.kind === "purpose")).toBe( + false, + ); expect( - inventory.rejectedDescriptions.some( + evidence.rejectedDescriptions.some( (item) => item.reason === "generic starter text", ), ).toBe(true); expect( - inventory.entries.some( - (claim) => claim.name === "ParcelController.dispatch", + evidence.claims.some( + (claim) => + claim.kind === "entry" && claim.name === "ParcelController.dispatch", ), ).toBe(true); expect( - inventory.entries.some((claim) => claim.text.includes("scheduled")), + evidence.claims.some( + (claim) => claim.kind === "entry" && claim.text.includes("scheduled"), + ), ).toBe(true); - expect(inventory.terms.some((term) => term.name === "Parcel")).toBe(true); + expect(evidence.terms.some((term) => term.name === "Parcel")).toBe(true); expect( - inventory.terms.find((term) => term.name === "Parcel")?.meaning, + evidence.terms.find((term) => term.name === "Parcel")?.meaning, ).toBeUndefined(); }); });