AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 2

    Development Environment, Git and Professional Workflow

    Two weeks after TechLearningPro sketched the tutor boundary, a contractor's laptop became the production incident.

    Course progress0%
    Focus
    16 guided sections
    Practice signal
    Concept-first lesson
    Career prep
    Foundation builder

    AI-Powered Full Stack Development · Lesson 02 · Full-Stack Engineering Foundations

    Lesson Overview

    Two weeks after TechLearningPro sketched the tutor boundary, a contractor's laptop became the production incident. A .env file with a model credential was committed on a feature branch, the branch was merged, and the secret sat in history after the file was deleted in a follow-up commit. The same afternoon, two engineers rebased the progress schema onto main with different lockfiles, so CI passed on one machine and failed on the Monday board's deploy. The architecture from lesson 1 was still right. The workstation and the Git history were not yet part of the system.

    This lesson makes the environment reproducible and the history reviewable. You will pin a Node.js version, install dependencies from a lockfile, keep secrets in untracked files, scan commits for credential-shaped strings, and ship changes through a short-lived branch and a pull request. AI assistants can draft a diff. They do not get to push it, and they do not get to see live keys or another tenant's lesson text.

    The running product is still the TechLearningPro Learning Platform: the React lesson player, the Node.js progress API, and the tutor port. This lesson does not add a model call. It makes the repository safe to hold one.

    Learning Objectives

    By the end of this lesson you will be able to:

    1. Pin the Node.js version and package manager so two engineers and CI resolve the same toolchain.
    2. Separate committed configuration (.env.example, lockfile, editor settings that do not contain secrets) from local secrets (.env, credential files).
    3. Explain why deleting a secret in a later commit does not remove it from Git history.
    4. Use a short-lived branch, a small commit, and a pull request as the default path onto main.
    5. Write a commit message that states the user-visible or operational reason for the change.
    6. Run a local secret scan that fails the commit when a credential-shaped assignment is staged.
    7. Review an AI-generated diff for secrets, tenant data, lockfile churn, and tests before you accept it.
    8. Describe what CI must re-check even after a green laptop: typecheck, tests, and the secret scan.
    9. Refuse force-pushes to the shared branch and refuse committing provider keys "just for the demo."
    10. Hand TypeScript for Production Full-Stack Development a repo that typechecks the same way on every machine. Language basics also live at /learn/typescript.

    Prerequisites

    • Lesson 1's boundary: the provider credential lives on the server, completion is not model-authored, and the browser is untrusted. Read Modern Full-Stack Architecture and AI-Native Applications if that map is unfamiliar.
    • You can open a terminal, edit a text file, and run a command. You do not need to be fluent in Git internals.
    • Install a current Active LTS Node.js from the official Node.js distribution, and Git from the official Git distribution. Verify both with node --version and git --version before the lab.
    • A GitHub, GitLab, or similar host for the pull request is useful and not required for the local scan. Do not create a public repository that contains real learner data or live keys.
    • No model API key is used in this lesson. If you already have one on disk, leave it out of the sample project.

    Detailed Core Concepts

    Why the environment is part of the product

    The learning platform's behavior includes the bytes CI builds. If your laptop runs Node 22 and CI runs Node 20, a fetch or TypeScript feature that exists only on one of them becomes a Friday surprise. If your lockfile is not committed, CI installs a newer transitive dependency than the one you tested. Pinning is a reliability control, not a preference.

    Record three pins and commit them:

    PinFileWhat it prevents
    Node.js major.nvmrc or package.json engines"Works on my laptop" runtime drift
    Package managerpackageManager field when you use Corepacknpm, pnpm, and Yarn resolving different trees
    Dependency treepackage-lock.json, pnpm-lock.yaml, or yarn.lockSilent upgrades between two installs

    Pick one package manager per repository. Mixing lockfiles in one repo means nobody knows which tree shipped. This course's examples use npm because it ships with Node.js. The workflow rules are the same if your team standardizes on pnpm.

    What belongs in Git

    Commit source, tests, lockfiles, .env.example with empty placeholders, and editor settings that do not embed tokens. Do not commit .env, *.pem, provider key files, database dumps, lesson exports that contain learner progress, or node_modules. node_modules is large, platform-specific, and reproducible from the lockfile. Committing it hides which package versions you meant.

    .env.example documents names. It does not document values.

    bash
    # .env.example — safe to commit. Values are empty on purpose.
    MODEL_API_KEY=
    DATABASE_URL=

    A real .env stays untracked:

    bash
    # .gitignore
    node_modules/
    dist/
    .env
    .env.*
    !.env.example
    *.pem
    coverage/

    The negation !.env.example matters. A broad .env.* rule would otherwise ignore the example file too.

    History is an append-only log

    Git stores snapshots. Removing a file in commit B leaves the file in commit A. Anyone with the repository can check out A. If a secret landed in A, rotating the secret is mandatory, and purging history is a coordinated rewrite with your security owner. "I deleted it" is not rotation. This lesson's scanner exists to stop the commit. It is not a substitute for rotation if the secret already shipped.

    Force-pushing main to hide a mistake rewrites the branch other people and CI already fetched. The professional default is a new commit that fixes the mistake, plus rotation if a secret was involved. Reserve history rewrite for the security incident process, not for tidying.

    Branches, commits, and pull requests

    main is the branch CI deploys or the branch that is always releasable. Feature work happens on a short-lived branch named for the change, for example tutor-timeout-fallback. Commits on that branch should be small enough to review. A useful message states why:

    text
    Return a typed tutor fallback when the model times out
    The lesson player must stay available when the provider is slow.

    A pull request is the review gate: another person, or you the next morning, reads the diff for secrets, tests, tenant scope, and accidental lockfile noise. AI-generated code enters through the same gate. Paste the diff into review with the same questions you would ask a new teammate: where is the secret, where is the test, what happens on failure, does this write completion?

    Protected main means the host rejects direct pushes and requires the review and the CI checks. Configure that on the host you actually use; the click-path changes, the policy does not.

    AI assistants in the workflow

    An assistant is a fast drafter with no accountability for your repository. Three rules keep it inside the architecture from lesson 1:

    1. Do not paste live credentials, production database URLs, or learner records into a prompt.
    2. Do not accept a diff that adds a provider call from the browser, a new completion source, or a disabled test.
    3. Commit only what you can explain. If you cannot describe the failure path, the change is not ready.

    Generated code often includes a plausible client for a vendor API that does not match the current documentation. Treat that as untrusted sample code. Verify it against the vendor's current docs before it becomes a dependency, and keep the call behind the server port.

    Deterministic toolchain versus probabilistic drafts

    npm ci on a lockfile is deterministic: the same lockfile and the same Node.js major install the same tree. An assistant's suggestion is not. The workflow records the deterministic artifacts (source, lockfile, tests) and reviews the probabilistic artifact (the suggestion) before it joins them.

    Architecture and Request Flow

    The diagram is the path of a change, not the path of a learner request. Both paths can leak a secret if you confuse them.

    flowchart LR
      subgraph local [Engineer workstation]
        Editor[Editor and assistant]
        Env[".env untracked"]
        Scan[Secret scan]
      end
    
      subgraph git [Git history]
        Branch[Feature branch]
        PR[Pull request]
        Main[Protected main]
      end
    
      subgraph ci [CI]
        Install["npm ci"]
        Check[Typecheck tests scan]
      end
    
      Editor --> Scan
      Env -.->|never staged| Scan
      Scan --> Branch
      Branch --> PR
      PR --> Check
      Check --> Install
      Check --> Main

    A secret that skips the scan and lands on main is already in history. CI is a second chance, not the first. The first is the pre-commit scan on the workstation.

    Step-by-step Implementation

    Build a tiny package that demonstrates the workflow: an environment reader that refuses to print secrets, a scanner that rejects credential assignments, and the Git files that keep .env untracked. Place it in packages/workflow/.

    Step 1: Initialize and pin

    bash
    mkdir -p packages/workflow/src
    cd packages/workflow
    npm init -y
    node --version > .nvmrc

    In package.json, set the engine and scripts. Replace the major with the LTS you installed; do not invent a version you have not run.

    json
    {
    "name": "@techlearningpro/workflow",
    "private": true,
    "type": "module",
    "engines": { "node": ">=20" },
    "scripts": {
    "scan": "node --experimental-strip-types src/secret-scan.ts",
    "test": "node --experimental-strip-types --test src/secret-scan.test.ts"
    }
    }

    private: true stops an accidental publish of a lab package.

    Step 2: Read configuration without echoing it

    packages/workflow/src/env.ts

    typescript
    export interface ServerConfig {
    /** Present or absent. Never log the raw value. */
    modelKeyConfigured: boolean;
    databaseConfigured: boolean;
    }
    const SECRET_NAMES = ["MODEL_API_KEY", "DATABASE_URL"] as const;
    export function readServerConfig(env: NodeJS.ProcessEnv): ServerConfig {
    return {
    modelKeyConfigured: Boolean(env.MODEL_API_KEY && env.MODEL_API_KEY.length > 0),
    databaseConfigured: Boolean(env.DATABASE_URL && env.DATABASE_URL.length > 0),
    };
    }
    /** Safe diagnostic line for CI and local scripts. */
    export function formatConfigStatus(config: ServerConfig): string {
    const flags = SECRET_NAMES.map((name) => {
    const on = name === "MODEL_API_KEY" ? config.modelKeyConfigured : config.databaseConfigured;
    return `${name}=${on ? "set" : "missing"}`;
    });
    return flags.join(" ");
    }

    The function reports presence. It has no code path that returns the key. That is the difference between a health check and a leak.

    Step 3: Scan staged text for credential assignments

    The scanner is deliberately small. It looks for assignment lines whose names look like secrets and whose values are not empty placeholders. It will miss clever encodings. It catches the mistake that caused the Monday incident: a real-looking value next to API_KEY or SECRET.

    packages/workflow/src/secret-scan.ts

    typescript
    import { pathToFileURL } from "node:url";
    const SECRET_LINE = /^([A-Z0-9_]*(KEY|SECRET|TOKEN|PASSWORD)[A-Z0-9_]*)=(.*)$/;
    export interface Finding {
    line: number;
    name: string;
    }
    export function findSecretAssignments(source: string): Finding[] {
    const findings: Finding[] = [];
    const lines = source.split(/\r?\n/);
    lines.forEach((line, index) => {
    const trimmed = line.trim();
    if (trimmed.startsWith("#")) return;
    const match = SECRET_LINE.exec(trimmed);
    if (!match) return;
    const value = match[3].trim().replace(/^["']|["']$/g, "");
    if (value.length === 0) return;
    if (value === "changeme" || value === "set-in-secret-manager") return;
    findings.push({ line: index + 1, name: match[1] });
    });
    return findings;
    }
    async function readStdin(): Promise<string> {
    const chunks: Buffer[] = [];
    for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk));
    return Buffer.concat(chunks).toString("utf8");
    }
    const isCli = process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href;
    if (isCli) {
    const input = await readStdin();
    const findings = findSecretAssignments(input);
    if (findings.length > 0) {
    for (const finding of findings) {
    console.error(`secret assignment on line ${finding.line}: ${finding.name}`);
    }
    process.exitCode = 1;
    }
    }

    Wire it as a Git hook only after the tests pass. A hook that developers skip with --no-verify is not a control; CI must run the same function on the diff.

    Step 4: Ignore secrets and commit the example

    Create .gitignore as shown in the concepts section and .env.example with empty values. Confirm Git will not track a local env file:

    bash
    printf 'MODEL_API_KEY=local-only-not-real\n' > .env
    git check-ignore -v .env
    git status --short

    git check-ignore should name .gitignore. git status should not list .env. If it does, fix the ignore rule before the first commit. If .env was already tracked, git rm --cached .env stops tracking it without deleting your local file, and you still rotate anything that was previously committed.

    Step 5: Branch, commit, and open a review

    bash
    git checkout -b workflow-secret-scan
    git add .gitignore .env.example package.json src
    git commit -m "$(cat <<'EOF'
    Add a secret scan that fails on credential assignments
    The tutor port stays reviewable only if keys never enter history.
    EOF
    )"

    Push the branch with your host's normal authentication. Open a pull request whose description lists: what changed, how to run npm test, and confirmation that .env is absent from the diff. Do not force-push main.

    Step 6: Clean up

    Delete the local .env when the lab ends if it contains anything you would not say aloud. Leave .env.example committed. If you used a throwaway remote, delete the repository when the review practice is done, after you have confirmed it never held a live key.

    Security

    • Secrets are environment-specific and untracked. Names may be committed. Values may not.
    • Least privilege on the Git host: contractors get access to the repositories they change, not to production secret stores. A Git login is not a production login.
    • Input validation in the scanner treats comments and empty values as non-findings so .env.example stays clean, and treats any other value as a finding.
    • Tenant isolation applies to fixtures. Sample lesson text in tests must be synthetic. Do not commit a production SQL dump to reproduce a bug.
    • Assistant prompts are a third-party transfer. Paste code and synthetic fixtures. Do not paste .env contents, session cookies, or learner emails.
    • History after a leak: revoke the credential at the provider, issue a new one into the secret store, and follow your organization's purge process. Deleting the file is the start of the incident, not the end.

    Review checklists should include a search of the diff for KEY=, SECRET=, BEGIN PRIVATE KEY, and postgres:// URLs with passwords. The scanner covers one pattern; the reviewer covers the rest.

    Error Handling

    The scanner exits with code 1 when findings exist and prints the variable name and line, never the value. That keeps CI logs from becoming a second copy of the secret. readServerConfig does not throw when a variable is missing; the caller decides whether missing configuration is fatal for that process. A laptop can run tests with both flags missing. A production process that must call a model should refuse to boot when modelKeyConfigured is false, with a message that names the variable and not a sample value.

    If git commit fails because the hook found a secret, fix the file, rotate if the value was real, and commit again. Do not pass --no-verify to get past a finding you have not understood.

    Testing

    packages/workflow/src/secret-scan.test.ts

    typescript
    import assert from "node:assert/strict";
    import test from "node:test";
    import { findSecretAssignments } from "./secret-scan.js";
    import { formatConfigStatus, readServerConfig } from "./env.js";
    test("flags a non-empty key assignment", () => {
    const findings = findSecretAssignments("MODEL_API_KEY=abc123value\n");
    assert.equal(findings.length, 1);
    assert.equal(findings[0].name, "MODEL_API_KEY");
    });
    test("allows empty examples and comments", () => {
    const source = "# local only\nMODEL_API_KEY=\nDATABASE_URL=set-in-secret-manager\n";
    assert.deepEqual(findSecretAssignments(source), []);
    });
    test("status line reports presence without the value", () => {
    const config = readServerConfig({ MODEL_API_KEY: "not-printed", DATABASE_URL: "" });
    const line = formatConfigStatus(config);
    assert.match(line, /MODEL_API_KEY=set/);
    assert.match(line, /DATABASE_URL=missing/);
    assert.equal(line.includes("not-printed"), false);
    });

    Run npm test from packages/workflow. Add a case for token = "value" in lowercase if your team writes env files that way, and extend the pattern only when a real miss shows up. A scanner that flags every occurrence of the word "key" will be disabled. Tune it toward credential assignments.

    Performance and Cost

    This workflow's cost is time, not tokens. npm ci is slower than a warm npm install and is the correct CI command because it refuses to drift from the lockfile. Local installs may use the cache. CI should start from the lockfile every run.

    Secret scanning on a commit is proportional to the diff, not the whole history. Run the full-history scan in CI on a schedule or when a leak is suspected; running it on every keystroke is how teams turn the hook off. AI assistants have a separate meter: pasting an entire monorepo into a prompt is slow, expensive, and more likely to include a secret. Paste the file you are changing.

    Disk cost is node_modules, which stays untracked. If the repository grows because someone committed a database dump or a model weight file, remove it with the same urgency as a secret: those files bloat clones for every engineer and often contain customer data.

    Knowledge Check

    1. What problem does this workflow solve?

    It makes TechLearningPro's build reproducible across laptops and CI, and it keeps provider credentials and learner data out of Git history. The architecture in lesson 1 fails in practice if the secret that enforces the server boundary is committed from a workstation.

    2. What alternatives exist, and when would you choose each?

    A trunk-based flow with short branches and pull requests fits this course and most product teams. Long-lived feature branches fit poorly when two people edit the same progress schema; integrate daily instead. Direct commits to main fit a personal scratch repository and not a shared platform. History rewrite fits a security-led purge after a leak, not routine cleanup.

    3. Which data, identity, and trust boundaries matter?

    .env is local and untrusted for sharing. .env.example is public and empty. CI's identity can read the repo and the secret store; a contractor's Git identity should not. Assistant prompts are outside the trust boundary: synthetic code only. Git history is visible to everyone who can clone the repo, including forks if the repo was public.

    4. What can fail, and how should the system respond?

    A scanner finding blocks the commit and names the variable, not the value. A missing local key lets tests run via readServerConfig and must stop a production boot that needs the model. A secret already in history triggers rotation and an incident process. A lockfile conflict is resolved by reinstalling from the chosen manager and committing one tree, not by committing two lockfiles.

    5. How would you test quality, security, performance, and cost?

    Unit tests cover non-empty assignments, empty examples, and a status line that omits values. Security review checks git status does not list .env and that CI runs the same scanner. Performance review prefers npm ci in CI and diff-scoped scans on commit. Cost review rejects committed node_modules, dumps, and whole-repo assistant prompts.

    Hands-on Assignment

    Lab note. Use fake values such as example-not-a-real-key only inside test strings. Do not use a live provider key anywhere in the exercise.

    Problem. Prepare a packages/workflow slice that a second engineer can clone and test without any secret, and that rejects a staged credential assignment.

    Tasks.

    1. Add .nvmrc, engines, .gitignore, and .env.example as specified.
    2. Implement findSecretAssignments, readServerConfig, and formatConfigStatus with the three tests.
    3. Create a local .env with a fake value and show git check-ignore output proving it is untracked.
    4. Commit on a feature branch with a message that states why the scan exists.
    5. Write a pull-request checklist of six questions: secrets, tests, lockfile, tenant data, completion writes, and failure behavior.
    6. Document what you would do if the scanner fired on a value that had already been pushed: rotate, purge with a security owner, and stop using --no-verify.

    Deliverable. The branch diff with no .env, test output, ignore proof, and the checklist.

    Challenge. Add a CI-shaped script that scans every tracked text file and fails if .env is tracked. Describe how you would keep that script from printing secret values when it fails.

    Rubric. Conceptual accuracy 20%. Working scan and env status 25%. Secret handling 20%. Tests and ignore proof 20%. Checklist and incident note 15%.

    Common Mistakes

    1. Committing .env because the app "needs it to run." Symptom: a key in git log. Cause: ignore rules added after the first commit, or never added. Fix: git rm --cached, rotate, and commit .env.example instead.
    2. Believing a delete commit removes the secret. Symptom: the key is gone from HEAD and still in an older revision. Cause: Git history is cumulative. Fix: rotate immediately; purge only with the incident process.
    3. Using --no-verify to skip the hook. Symptom: CI or a reviewer finds the secret later. Cause: the hook was treated as annoyance. Fix: make CI run the same scan; fix the finding.
    4. Committing node_modules or a second lockfile. Symptom: huge diffs and installs that differ by machine. Cause: no ignore rule, or two package managers. Fix: one manager, one lockfile, node_modules ignored.
    5. Force-pushing main after a bad merge. Symptom: teammates' branches no longer apply, and CI history jumps. Cause: rewrite used as an undo button. Fix: revert commit on main; reserve rewrite for security-led purges.
    6. Pasting production config into an assistant. Symptom: a key or a learner email leaves the company boundary. Cause: convenience. Fix: paste types and synthetic fixtures; rotate if it already happened.
    7. Accepting generated code that disables tests or calls the model from the browser. Symptom: a green demo and a broken boundary. Cause: the diff was not reviewed. Fix: the pull-request checklist from the assignment, every time.

    Summary

    A professional workflow pins Node.js and the lockfile, keeps secrets in untracked files, scans commits for credential assignments, and lands changes on main through a small branch and a pull request. Deleting a secret does not erase history. An assistant may draft the diff and may not bypass review or see live keys. The status helper reports whether configuration is present without ever printing it.

    Next Lesson Preview

    TypeScript for Production Full-Stack Development uses this clean repo to make the tutor and completion contracts from lesson 1 hold at compile time and at the JSON boundary. The Node.js runtime you pinned is the one those types will run on.

    Further Reading

    • Git documentation for commits, ignore rules, and history.
    • npm ci for lockfile installs in CI.
    • Node.js releases for which line is Active LTS when you write .nvmrc.
    • Your Git host's documentation on protected branches and required checks. The policy in this lesson is host-agnostic; the settings screen is not.
    • OWASP secrets-management guidance for rotation after a leak. Read the current page when you write the incident note.
    Ready to mark this lesson complete?Track your journey across the entire course.