diff --git a/README.md b/README.md
index 5e896ce..2411ea6 100644
--- a/README.md
+++ b/README.md
@@ -52,7 +52,7 @@ Read [the example README](motion-perception/README.md) and [data dictionary](mot
Open `/notebook-lab.html`: four missions cover hidden state, extraction into a saved module, validated configuration, and fresh-kernel handoff with a Matplotlib figure. Execution has a 15-second limit and Stop terminates the worker. Python 3.12.7, NumPy 2.0.2, pandas 2.2.3, and Matplotlib 3.8.4 differ from the local project's lock. This is ordinary Python cell execution, not a complete Jupyter frontend: magics, widgets, interactive input, arbitrary installs, and host-filesystem access are not implemented.
-Open `/git-playground.html`: five state-checked missions include a bounded command console and distinct working/index/HEAD snapshots, inspectable commits, conflict resolution, a simulated server, PR diff/review, and synchronization. No GitHub actions are sent. `/practice.html` connects the exercises to a real notebook, peer handoff, and suggested day 2/week 1/month 1 retrieval prompts; these do not schedule reminders.
+Open `/git-playground.html`: five guided missions cover selective staging, branching, conflict resolution, pull request review and synchronization, and recovery. Inspect file diffs and commit snapshots or open the built-in Git terminal to type the same commands. No GitHub actions are sent. `/practice.html` connects the exercises to a real notebook, peer handoff, and suggested day 2/week 1/month 1 retrieval prompts; these do not schedule reminders.
The source ZIP excludes the downloaded runtime and generated virtual-filesystem manifest. `tools/build.py` regenerates both. Run `tools/fetch_pyodide.py` before the workshop while connected, then serve the complete built directory. Runtime provenance is recorded in `site/assets/python-runtime/runtime-manifest.json`; the CPython license is retained separately, and dependency licenses ship in the upstream wheels. See `site/assets/PYTHON-RUNTIME.md`.
@@ -75,7 +75,7 @@ python tools/check_browser_lessons.py
python tools/build.py
```
-The Python suite covers deterministic generation, byte-identical CSV regeneration, schema failures, inclusive RT boundaries, error retention, input immutability, participant weighting, plot production, config validation, config-relative paths, CLI override provenance, separate sensitivity outputs, import safety, and all three notebooks executed in independent kernels with numerical equivalence checks. The 25 Git model/command tests cover selective staging, later edits, explicit staged conflict resolution, named branches, merges, abort, fetch/pull, divergent push rejection, PR review becoming stale, server-only merges, and recovery. The browser-lesson checker executes all four solutions, verifies stale-state and removed-error failures, and validates notebook export schemas. The real Git lab check uses only disposable directories and a temporary bare local remote—no GitHub authentication or upload.
+The Python suite covers deterministic generation, byte-identical CSV regeneration, schema failures, inclusive RT boundaries, error retention, input immutability, participant weighting, plot production, config validation, config-relative paths, CLI override provenance, separate sensitivity outputs, import safety, and all three notebooks executed in independent kernels with numerical equivalence checks. The Git model, command, and mission tests cover selective staging, later edits, explicit staged conflict resolution, named branches, merges, abort, fetch/pull, divergent push rejection, PR review becoming stale, server-only merges, and recovery. The browser-lesson checker executes all four solutions, verifies stale-state and removed-error failures, and validates notebook export schemas. The real Git lab check uses only disposable directories and a temporary bare local remote—no GitHub authentication or upload.
To refresh saved notebook outputs after a deliberate analysis change: `python tools/execute_notebooks.py`. Review output diffs before sharing. This uses local Jupyter kernel sockets; constrained environments must permit localhost communication. The standalone archives exclude Git metadata, virtual environments, caches, and generated results. Install the extracted project's dependencies into a fresh environment when testing a handoff.
@@ -93,9 +93,9 @@ For a copy hosted in another repository, enable Pages with GitHub Actions and up
## Design and teaching decisions
-A slate-and-blue design, clear sans-serif typography, restrained surfaces, and a scientific illustration give the workshop a consistent visual identity. The notebook lab groups files into keyboard-accessible tabs with a task rail, kernel toolbar, line-number gutters, output panels, and nearby check feedback. The Git room groups changes, history, and review into tabs with a companion command console. Narrow screens stack the workspaces and collapse detailed instructions. Modules share objectives, research examples, exercises with hints and revealed explanations, takeaways, and onward links. Introductory Python syntax is assumed. Optional explanations address tooling and package mechanics; extensions address scientific and maintenance tradeoffs. Semantic HTML, visible focus, reduced-motion support, responsive layouts, and text alternatives complement Quarto's built-in navigation.
+A slate-and-blue design, clear sans-serif typography, restrained surfaces, and a scientific illustration give the workshop a consistent visual identity. The notebook lab groups files into keyboard-accessible tabs with a task rail, kernel toolbar, line-number gutters, output panels, and nearby check feedback. The Git room has a live mission checklist, per-file controls, and an optional terminal. Narrow screens stack the workspaces and collapse detailed instructions. Modules share objectives, research examples, exercises with hints and revealed explanations, takeaways, and onward links. Introductory Python syntax is assumed. Optional explanations address tooling and package mechanics; extensions address scientific and maintenance tradeoffs. Semantic HTML, visible focus, reduced-motion support, responsive layouts, and text alternatives complement Quarto's built-in navigation.
-The simulator is bounded to two teaching files, five local branches, and 50 commits. It never executes Git or modifies a real filesystem. Real Git commands and scientific decision-making remain explicit in the Git lab. Git state resets on reload; Python source edits/predictions and personal handoff notes are saved in localStorage when available. Kernel variables are temporary. Both lab notebooks and handoff notes can be exported. No account is required.
+The simulator is bounded to two teaching files, five local branches, and 50 commits. It never executes Git or modifies a real filesystem. Real Git commands and scientific decision-making remain explicit in the Git lab. Mission progress carries across mission switches during a visit and resets on reload. Python source edits, predictions, and personal handoff notes are saved in localStorage when available. Kernel variables are temporary. Both lab notebooks and handoff notes can be exported. No account is required.
## License
diff --git a/site/assets/git-commands.js b/site/assets/git-commands.js
index 330983b..e6447cc 100644
--- a/site/assets/git-commands.js
+++ b/site/assets/git-commands.js
@@ -1,50 +1,152 @@
-export const files={rule:'config/analysis.toml',plot:'src/experiment/plotting.py'};
-export function fileKeys(paths){
- if(!paths.length)throw new Error('Specify a file path or .');
- if(paths.length===1&&paths[0]==='.')return ['rule','plot'];
- return paths.map(path=>{const key=Object.keys(files).find(k=>files[k]===path||k===path);if(!key)throw new Error(`This model has two teaching files; unknown path: ${path}`);return key;});
+import {files} from './git-model.js';
+
+const supported = 'Supported commands: git status, diff, add, commit, branch, switch, checkout, merge, fetch, pull --ff-only, push, restore, log, and revert HEAD.';
+
+function fileKeys(paths) {
+ if (paths[0] === '--') paths = paths.slice(1);
+ if (!paths.length) throw new Error('Specify a file path or .');
+ const keys = paths.flatMap(path => {
+ if (path === '.') return Object.keys(files);
+ const file = path.replace(/^\.\//, '');
+ const key = Object.keys(files).find(name => files[name] === file);
+ if (!key) throw new Error(`Unknown path: ${path}. Use ${Object.values(files).join(' or ')}.`);
+ return key;
+ });
+ return [...new Set(keys)];
}
-export function status(model){
- return `On branch ${model.current}\n`+Object.keys(files).map(key=>`${model.conflict?.keys.includes(key)&&!model.conflict.staged?'UU':`${model.staged.includes(key)?'M':' '}${model.unstaged.includes(key)?'M':' '}`} ${files[key]}`).join('\n')+(!model.dirty&&!model.conflict?'\nWorking tree clean.':'');
+
+export function branchStatus(model) {
+ const branch = model.current;
+ if (!Object.hasOwn(model.upstream, branch)) return branch;
+ const upstream = model.upstream[branch];
+ if (!Object.hasOwn(model.tracking, upstream)) return branch;
+ const local = model.ancestors(model.head.id);
+ const remote = model.ancestors(model.tracking[upstream]);
+ const ahead = [...local].filter(id => !remote.has(id)).length;
+ const behind = [...remote].filter(id => !local.has(id)).length;
+ const counts = [ahead ? `ahead ${ahead}` : '', behind ? `behind ${behind}` : ''].filter(Boolean);
+ return `${branch}...origin/${upstream}${counts.length ? ` [${counts.join(', ')}]` : ''}`;
}
-export function diff(model,staged=false){
- const changes=model.diff(staged);
- return changes.length?changes.map(c=>`${files[c.key]}\n--- ${staged?'HEAD':'index'}\n+++ ${staged?'index':'working file'}\n- ${c.before}\n+ ${c.after}`).join('\n\n'):'No differences in this comparison.';
+
+export function status(model, short = false, showBranch = false) {
+ const {staged, unstaged, unmerged} = model;
+ if (short) {
+ const rows = Object.keys(files).filter(key =>
+ staged.includes(key) || unstaged.includes(key) || unmerged.includes(key)).map(key => {
+ const flags = unmerged.includes(key) ? 'UU' : (staged.includes(key) ? 'M' : ' ') + (unstaged.includes(key) ? 'M' : ' ');
+ return `${flags} ${files[key]}`;
+ });
+ if (showBranch) rows.unshift(`## ${branchStatus(model)}`);
+ return rows.join('\n');
+ }
+ const list = (title, keys) => keys.length ? `${title}\n${keys.map(key => ` ${files[key]}`).join('\n')}` : '';
+ const resolved = model.conflict?.keys.filter(key => model.conflict.stagedKeys.has(key) && !staged.includes(key)) ?? [];
+ return [
+ `On branch ${model.current}`,
+ model.conflict ? `Merging ${model.conflict.source} into ${model.current}` : '',
+ list('Unmerged paths:', unmerged),
+ list('Changes to be committed:', [...staged, ...resolved]),
+ list('Changes not staged for commit:', unstaged),
+ !model.dirty && !model.conflict ? 'nothing to commit, working tree clean' : ''
+ ].filter(Boolean).join('\n\n');
+}
+
+const line = (key, value) => key === 'rule' ? `min_rt_s = ${value}` : `color = "${value}"`;
+
+export function formatDiff(changes) {
+ return changes.map(({key, before, after}) =>
+ `--- a/${files[key]}\n+++ b/${files[key]}\n- ${line(key, before)}\n+ ${line(key, after)}`).join('\n\n');
}
-export function executeCommand(model,command){
- if(/[;|`\n]/.test(command))throw new Error('This is a bounded Git simulator, not a shell. Run one supported command at a time.');
- const tokens=command.match(/"(?:[^"\\]|\\.)*"|'[^']*'|[^\s]+/g)||[];
- const args=tokens.map(t=>t.startsWith('"')?JSON.parse(t):t.startsWith("'")?t.slice(1,-1):t);
- if(args.shift()!=='git')throw new Error('Start with git. This console does not execute operating-system commands.');
- const verb=args.shift();
- switch(verb){
- case 'status': if(args.length)throw new Error('Use git status without extra arguments in this console.');return status(model);
- case 'diff': if(args.some(a=>a!=='--staged'))throw new Error('Use git diff or git diff --staged.');return diff(model,args.includes('--staged'));
- case 'add': return model.stage(fileKeys(args));
- case 'commit': if(args.length!==2||args[0]!=='-m'||!args[1].trim())throw new Error('Use git commit -m "A meaningful message"');return model.commit(args[1]);
- case 'switch': if(args[0]==='-c'&&args.length===2)return model.branch(args[1]);if(args.length===1)return model.switchBranch(args[0]);throw new Error('Use git switch NAME or git switch -c NAME.');
- case 'merge': if(args.length===1&&args[0]==='--abort')return model.abort();if(args.length===1)return model.merge(args[0]);throw new Error('Use git merge BRANCH.');
- case 'fetch': if(args.length>1||args.length&&args[0]!=='origin')throw new Error('The simulated remote is origin.');return model.fetch();
- case 'pull': if(args.join(' ')!=='--ff-only')throw new Error('Use git pull --ff-only; this model does not silently choose a merge or rebase policy.');return model.pull();
- case 'push': {
- if(args[0]==='-u')args.shift();
- if(args.length&&args.shift()!=='origin')throw new Error('The simulated remote is origin; force push is not supported.');
- if(args.length>1)throw new Error('Use git push -u origin BRANCH.');return model.push(args[0]||model.current);
+
+export function diff(model, staged = false, keys = Object.keys(files)) {
+ return formatDiff(model.diff(staged).filter(change => keys.includes(change.key)));
+}
+
+export function quoteArgument(value) { return JSON.stringify(value); }
+
+function parseCommand(command) {
+ const tokens = [];
+ const token = /"((?:[^"\\]|\\.)*)"|'([^']*)'|([^\s"';&|`<>]+)/y;
+ let remaining = command.trim();
+ while (remaining) {
+ token.lastIndex = 0;
+ const match = token.exec(remaining);
+ if (!match || (remaining[token.lastIndex] && !/\s/.test(remaining[token.lastIndex]))) {
+ throw new Error('Enter one Git command. Use matching quotes around messages that contain spaces.');
+ }
+ tokens.push(match[1]?.replace(/\\(["\\])/g, '$1') ?? match[2] ?? match[3]);
+ remaining = remaining.slice(token.lastIndex).trimStart();
}
- case 'restore': if(args[0]==='--staged'){args.shift();return model.unstage(fileKeys(args));}if(args.length===1)return model.discard(fileKeys(args)[0]);throw new Error('Use git restore PATH or git restore --staged PATH.');
- case 'revert': if(args.join(' ')==='HEAD')return model.revert();throw new Error('This exercise supports git revert HEAD for a single-parent commit.');
- case 'log': {
- if(args.some(a=>!['--oneline','--graph','--all'].includes(a)))throw new Error('Supported flags: --oneline --graph --all.');
- const reachable=new Set();for(const id of args.includes('--all')?[...Object.values(model.branches),...Object.values(model.tracking)]:[model.head.id])for(const ancestor of model.ancestors(id))reachable.add(ancestor);
- return [...model.commits].reverse().filter(c=>reachable.has(c.id)).map(c=>`${c.id} ${c.message} [parents: ${c.parents.join(', ')||'none'}]`).join('\n');
+ return tokens;
+}
+
+export function executeCommand(model, command) {
+ if (/[\r\n]/.test(command.trim())) throw new Error('Enter one Git command at a time.');
+ const [program, verb, ...args] = parseCommand(command);
+ if (program !== 'git') throw new Error('Start with git. ' + supported);
+ switch (verb) {
+ case 'status':
+ if (!args.length) return status(model);
+ if (args.length === 1 && ['--short', '-s'].includes(args[0])) return status(model, true);
+ if (['-sb', '-bs', '--short --branch', '--branch --short'].includes(args.join(' '))) return status(model, true, true);
+ throw new Error('Use git status, git status --short, or git status -sb.');
+ case 'diff': {
+ const staged = ['--staged', '--cached'].includes(args[0]);
+ if (staged) args.shift();
+ return diff(model, staged, args.length ? fileKeys(args) : undefined);
+ }
+ case 'add':
+ return model.stage(args.length === 1 && ['-A', '--all'].includes(args[0]) ? undefined : fileKeys(args));
+ case 'commit':
+ if (args.length === 2 && args[0] === '-m' && args[1].trim()) return model.commit(args[1].trim());
+ if (!args.length && model.conflict) return model.commit();
+ throw new Error('Use git commit -m "Describe your change".');
+ case 'branch':
+ if (!args.length || (args.length === 1 && ['-a', '--all', '--list'].includes(args[0]))) {
+ const local = Object.keys(model.branches).map(name => `${name === model.current ? '*' : ' '} ${name}`);
+ const remote = Object.keys(model.tracking).map(name => ` remotes/origin/${name}`);
+ return [...local, ...(args[0] === '--list' || !args.length ? [] : remote)].join('\n');
+ }
+ if (args.length === 1 && !args[0].startsWith('-')) return model.branch(args[0], false);
+ throw new Error('Use git branch to list branches or git branch NAME to create one.');
+ case 'switch':
+ case 'checkout':
+ if (args.length === 2 && args[0] === (verb === 'switch' ? '-c' : '-b')) return model.branch(args[1]);
+ if (args.length === 1 && !args[0].startsWith('-')) return model.switchBranch(args[0]);
+ throw new Error('Use git switch NAME or git switch -c NAME. The checkout equivalents are git checkout NAME and git checkout -b NAME.');
+ case 'merge':
+ if (args.length === 1 && args[0] === '--abort') return model.abort();
+ if (args.length === 1 && !args[0].startsWith('-')) return model.merge(args[0]);
+ throw new Error('Use git merge BRANCH or git merge --abort.');
+ case 'fetch':
+ if (!args.length || (args.length === 1 && args[0] === 'origin')) return model.fetch();
+ throw new Error('Use git fetch origin.');
+ case 'pull':
+ if (args[0] === '--ff-only' && (args.length === 1 || (args.length === 3 && args[1] === 'origin'))) return model.pull(args[2]);
+ throw new Error('Use git pull --ff-only or git pull --ff-only origin BRANCH.');
+ case 'push': {
+ const setUpstream = ['-u', '--set-upstream'].includes(args[0]);
+ if (setUpstream) args.shift();
+ if (!setUpstream && (!args.length || (args.length === 1 && args[0] === 'origin'))) return model.push();
+ if (args.length === 2 && args[0] === 'origin' && !args[1].startsWith('-')) return model.push(args[1], setUpstream);
+ throw new Error('Use git push or git push -u origin BRANCH.');
+ }
+ case 'restore':
+ if (args[0] === '--staged') return model.unstage(fileKeys(args.slice(1)));
+ return model.discard(fileKeys(args));
+ case 'revert':
+ if (args.length === 1 && args[0] === 'HEAD') return model.revert();
+ throw new Error('Use git revert HEAD to undo the latest single-parent commit.');
+ case 'log': {
+ if (args.some(arg => !['--oneline', '--graph', '--all'].includes(arg))) throw new Error('Use git log --oneline --graph --all or git log.');
+ const tips = args.includes('--all') ? [...Object.values(model.branches), ...Object.values(model.tracking)] : [model.head.id];
+ const reachable = new Set(tips.flatMap(id => [...model.ancestors(id)]));
+ return [...model.commits].reverse().filter(commit => reachable.has(commit.id)).map(commit =>
+ `${commit.id} ${commit.message}${args.includes('--graph') ? ` [parents: ${commit.parents.join(', ') || 'none'}]` : ''}`).join('\n');
+ }
+ case 'help':
+ return supported;
+ default:
+ throw new Error(supported);
}
- default: throw new Error('Supported: status, diff, add, commit, switch, merge, fetch, pull --ff-only, push, restore, log, revert HEAD.');
- }
}
-export const missions=[
- {id:'staging',title:'1 · Commit only the scientific change',goal:'Change the rule to 0.50 and the plot to purple. Stage and commit only the rule. Leave the plot unstaged.',hint:'Use git add config/analysis.toml, then inspect git diff --staged and git diff before committing.',explanation:'A commit records the index, not every saved file. A focused policy change is easier to review than a mixed scientific and cosmetic edit.',check:m=>m.head.snapshot.rule==='0.50'&&m.head.snapshot.plot==='teal'&&m.working.plot==='purple'&&m.unstaged.includes('plot')},
- {id:'branches',title:'2 · Combine independent work',goal:'Create criteria, commit a rule of 0.30 there, then switch to main and commit a purple plot. Merge criteria into main.',hint:'Create criteria before either branch changes. Commit each edit before switching. The two branches should diverge from the baseline.',explanation:'The merge base explains what each branch changed. Separate-file changes can combine into a two-parent merge; both scientific and visual results still need review.',check:m=>m.current==='main'&&m.head.parents.length===2&&m.head.snapshot.rule==='0.30'&&m.head.snapshot.plot==='purple'},
- {id:'conflict',title:'3 · Resolve, stage, then commit',goal:'Create criteria and commit rule 0.30. On main commit rule 0.25. Merge criteria, inspect the conflicting versions, write a resolution, stage it, and commit the merge.',hint:'A written resolution is not yet a staged resolution. Inspect the conflict panel, then use git add config/analysis.toml and git commit.',explanation:'Git cannot choose the scientific policy for you. Removing conflict markers, testing the decision, staging, and committing are distinct steps.',check:m=>m.current==='main'&&!m.conflict&&m.head.parents.length===2&&/conflict|resolve/i.test(m.head.message)},
- {id:'remote',title:'4 · Share, review, merge, synchronize',goal:'Create criteria, change and commit the rule, push criteria, open a PR, inspect its diff and record review, merge on the server, then switch to main and pull --ff-only.',hint:'Push does not open a PR. A server merge does not move local main. Open the Remote & review panel to review the exact branch tips.',explanation:'Local branches, remote branches, and remote-tracking pointers are distinct. Review can become stale when either proposed or target history changes.',check:m=>Boolean(m.pullRequest?.merged)&&m.current==='main'&&m.head.id===m.remote.main&&m.tracking.main===m.remote.main},
- {id:'recovery',title:'5 · Recover without erasing history',goal:'Edit and stage the rule. Unstage it and confirm the working edit remains. Commit it with a meaningful message, then revert HEAD.',hint:'git restore --staged config/analysis.toml preserves working edits. After the commit, git revert HEAD adds an inverse commit.',explanation:'Unstaging, discarding unstaged edits, and reverting a commit solve different problems. Revert preserves the original history and is suitable for reviewed shared changes.',check:(m,events)=>events.some(e=>e.includes('restore --staged'))&&m.head.message.startsWith('Revert ')&&m.head.snapshot.rule==='0.20'&&m.commits.length>=3}
-];
diff --git a/site/assets/git-missions.js b/site/assets/git-missions.js
new file mode 100644
index 0000000..0d2c194
--- /dev/null
+++ b/site/assets/git-missions.js
@@ -0,0 +1,174 @@
+import {files, GitModel} from './git-model.js';
+
+function saveRule(repo, value) {
+ repo.setFile('rule', value);
+ repo.stage(['rule']);
+ repo.commit(`Set minimum RT to ${value} s`);
+}
+
+function step(done, label, instruction, view = 'changes', command = '') {
+ return {done: Boolean(done), label, instruction, view, command};
+}
+
+const addRule = `git add ${files.rule}`;
+const restoreRule = `git restore --staged ${files.rule}`;
+const commitRule = 'git commit -m "Compare the RT rule"';
+
+export const missions = [
+ {
+ id: 'staging', title: 'Stage selectively', view: 'changes',
+ goal: 'Commit the 0.50 s minimum reaction time and leave the purple plot edit unstaged.',
+ explanation: 'A commit records the versions in the staging area. Your purple plot edit is still in the working tree.',
+ steps(repo) {
+ const parent = repo.commitAt(repo.head.parents[0]);
+ const committed = parent && parent.snapshot.rule !== '0.50' &&
+ repo.head.snapshot.rule === '0.50' && repo.head.snapshot.plot === 'teal' &&
+ parent.snapshot.plot === 'teal';
+ const edited = repo.working.rule === '0.50' && repo.working.plot === 'purple';
+ const selective = repo.index.rule === '0.50' && repo.index.plot === 'teal';
+ return [
+ step(edited, 'Edit both files', 'Save 0.50 s in analysis.toml and purple in plotting.py.'),
+ step(selective, 'Stage only the rule', repo.staged.includes('plot')
+ ? 'Unstage plotting.py. Keep the purple edit in the working tree.'
+ : 'Stage analysis.toml and compare the staged and unstaged diffs.', 'changes',
+ repo.staged.includes('plot') ? `git restore --staged ${files.plot}` : addRule),
+ step(committed && selective && repo.unstaged.includes('plot'), 'Commit the rule', 'Commit the staged rule with a message that explains the change.', 'changes', commitRule)
+ ];
+ }
+ },
+ {
+ id: 'branches', title: 'Merge independent work', view: 'history',
+ goal: 'Commit an RT rule on a feature branch and a plot change on main, then merge both changes on main.',
+ explanation: 'The merge commit has two parents because both branches advanced. Git combined changes to different files.',
+ steps(repo) {
+ const features = Object.entries(repo.branches).filter(([name]) => name !== 'main');
+ const ruleCommit = features.find(([, id]) =>
+ repo.commitAt(id).snapshot.rule === '0.30' && repo.commitAt(id).snapshot.plot === 'teal');
+ const [feature = 'criteria'] = ruleCommit ?? features[0] ?? [];
+ const main = repo.commitAt(repo.branches.main);
+ const [mainParent, otherParent] = main.parents.map(id => repo.commitAt(id));
+ const merged = mainParent?.snapshot.plot === 'purple' && mainParent.snapshot.rule === '0.20' &&
+ otherParent?.snapshot.rule === '0.30' && otherParent.snapshot.plot === 'teal' &&
+ main.snapshot.rule === '0.30' && main.snapshot.plot === 'purple';
+ const onFeature = repo.current === feature;
+ const onMain = repo.current === 'main';
+ return [
+ step(features.length || merged, 'Create a feature branch', 'Create and switch to a branch at the baseline.', 'history', 'git switch -c criteria'),
+ step(ruleCommit || merged, 'Commit 0.30 s on the feature branch', onFeature
+ ? 'Save 0.30 s, stage analysis.toml, and commit it on this branch.'
+ : `Switch to ${feature}, then edit and commit the rule there.`, onFeature ? 'changes' : 'history', onFeature ? addRule : `git switch ${feature}`),
+ step(main.snapshot.plot === 'purple', 'Commit purple on main', onMain
+ ? 'Save purple, stage plotting.py, and commit it on main.'
+ : 'Switch to main so the plot change has its own history.', onMain ? 'changes' : 'history',
+ onMain ? `git add ${files.plot}` : 'git switch main'),
+ step(merged && onMain, 'Merge into main', onMain
+ ? `Find the shared ancestor, then merge ${feature} into main.`
+ : 'Switch to main to inspect the combined history.', 'history', onMain ? `git merge ${feature}` : 'git switch main')
+ ];
+ }
+ },
+ {
+ id: 'conflict', title: 'Resolve a conflict', view: 'history',
+ goal: 'Compare the two changes to the RT rule, choose a final value, and record the merge.',
+ explanation: 'The merge commit records your staged resolution and links both parent commits. Choosing the current value still requires staging.',
+ setup(repo) {
+ repo.branch();
+ saveRule(repo, '0.30');
+ repo.switchBranch('main');
+ saveRule(repo, '0.25');
+ },
+ steps(repo) {
+ const merged = repo.current === 'main' && repo.head.resolvedMerge &&
+ repo.head.parents.includes(repo.branches.criteria);
+ const conflict = repo.conflict?.source === 'criteria' && repo.current === 'main' ? repo.conflict : null;
+ return [
+ step(merged || conflict, 'Merge criteria into main', repo.current === 'main'
+ ? 'Inspect the common ancestor c0, then merge criteria into main.'
+ : 'Switch to main to merge the prepared branch.', 'history',
+ repo.current === 'main' ? 'git merge criteria' : 'git switch main'),
+ step(merged || conflict?.resolvedKeys.has('rule'), 'Save a resolution', 'Compare the two branch values, then save the value you want to keep.'),
+ step(merged || (conflict && !repo.unmerged.length), 'Stage the resolution', 'Stage the resolved analysis.toml so Git can record the merge.', 'changes', addRule),
+ step(merged, 'Commit the merge', 'Commit the staged resolution with your own message.', 'changes', 'git commit -m "Explain the chosen RT rule"')
+ ];
+ }
+ },
+ {
+ id: 'remote', title: 'Share and review', view: 'remote',
+ goal: 'Share the prepared feature commit, review and merge its pull request, and synchronize local main.',
+ explanation: 'Push shared your feature commit, the pull request updated server main, and pull brought the result into local main.',
+ setup(repo) {
+ repo.branch();
+ saveRule(repo, '0.50');
+ },
+ steps(repo) {
+ const pr = repo.pullRequest;
+ const pushed = repo.remote.criteria === repo.branches.criteria;
+ const onFeature = repo.current === 'criteria';
+ const reviewed = pr?.merged || repo.prReviewCurrent;
+ return [
+ step(pushed || pr, 'Push the feature branch', onFeature ? 'Push criteria and set its upstream.'
+ : 'Switch to criteria to push the prepared feature commit.', onFeature ? 'remote' : 'history',
+ onFeature ? 'git push -u origin criteria' : 'git switch criteria'),
+ step(pr, 'Open a pull request', onFeature ? 'Open a pull request from the pushed feature branch to main.'
+ : 'Switch to criteria to open its pull request.', onFeature ? 'remote' : 'history',
+ onFeature ? '' : 'git switch criteria'),
+ step(reviewed, 'Review the proposed diff', pr?.reviewedHead
+ ? 'The branch tips changed. Read the current diff and record a fresh review.'
+ : 'Read the proposed change and record your review.', 'remote'),
+ step(pr?.merged, 'Merge on the server', 'Merge the reviewed pull request on origin.', 'remote'),
+ step(pr?.merged && repo.current === 'main' && repo.head.id === repo.remote.main,
+ 'Update local main', repo.current === 'main' ? 'Pull the merged history into local main.'
+ : 'Switch to local main, then pull the merged history.', 'remote',
+ repo.current === 'main' ? 'git pull --ff-only' : 'git switch main')
+ ];
+ }
+ },
+ {
+ id: 'recovery', title: 'Recover a change', view: 'changes',
+ goal: 'Unstage an RT edit without losing it, then commit it and undo that commit with revert.',
+ explanation: 'Unstage preserved the working edit. Revert added a new commit that reversed the saved edit and preserved the original commit.',
+ steps(repo, recovery) {
+ const head = repo.head;
+ const original = head.reverts ? repo.commitAt(head.reverts) : head;
+ const base = repo.commitAt(recovery?.base);
+ const committed = base && original.parents[0] === base.id && original.snapshot.rule === recovery.rule;
+ const reverted = committed && head.reverts === original.id && head.snapshot.rule === base.snapshot.rule;
+ const pending = repo.working.rule !== head.snapshot.rule;
+ const restaged = repo.staged.includes('rule') && repo.index.rule === recovery?.rule;
+ return [
+ step(pending || repo.staged.includes('rule') || recovery, 'Edit the rule', 'Save any minimum RT different from the current value in analysis.toml.'),
+ step(repo.staged.includes('rule') || recovery, 'Stage the edit', 'Stage analysis.toml.', 'changes', addRule),
+ step(recovery, 'Unstage and inspect', 'Unstage analysis.toml. Check that the edited value is still under Unstaged.', 'changes', restoreRule),
+ step(committed || restaged, 'Stage it again', recovery && repo.working.rule !== recovery.rule
+ ? `Restore your ${recovery.rule} s working edit and stage analysis.toml again.`
+ : 'Stage analysis.toml again.', 'changes', addRule),
+ step(committed, 'Commit the edit', 'Record the staged rule in a commit.', 'changes', commitRule),
+ step(reverted, 'Revert the commit', 'Revert the latest commit, then inspect both commits in Branches.', 'changes', 'git revert HEAD')
+ ];
+ }
+ }
+];
+
+export function startMission(mission) {
+ const repo = new GitModel();
+ mission.setup?.(repo);
+ return {mission, repo, recovery: null};
+}
+
+export function runMissionAction(session, action) {
+ const {repo, mission} = session;
+ const before = {head: repo.head, branch: repo.current, staged: repo.staged.includes('rule'), rule: repo.working.rule};
+ const output = action(repo);
+ if (mission.id === 'recovery' && before.staged && repo.head === before.head &&
+ repo.current === before.branch && !repo.staged.includes('rule') &&
+ repo.working.rule === before.rule && repo.unstaged.includes('rule')) {
+ session.recovery = {base: before.head.id, rule: before.rule};
+ }
+ return output;
+}
+
+export function missionProgress({mission, repo, recovery}) {
+ const steps = mission.steps(repo, recovery);
+ const next = steps.find(item => !item.done);
+ return {steps, next, complete: !next};
+}
diff --git a/site/assets/git-model.js b/site/assets/git-model.js
index 8d26a29..63a0eb9 100644
--- a/site/assets/git-model.js
+++ b/site/assets/git-model.js
@@ -1,3 +1,15 @@
+export const files = {rule: 'config/analysis.toml', plot: 'src/experiment/plotting.py'};
+
+function fileValue(key, value) {
+ if (key === 'rule') {
+ const rounded = Number(value).toFixed(2);
+ if (Number(rounded) > 0 && Number(rounded) < 2) return rounded;
+ throw new Error('Enter a minimum RT from 0.01 to 1.99 seconds.');
+ }
+ if (key === 'plot' && ['teal', 'purple', 'orange'].includes(value)) return value;
+ throw new Error('Choose one of the available plot colors.');
+}
+
/** A bounded teaching model of snapshots, the index, and a small commit DAG. */
export class GitModel {
constructor() {
@@ -8,228 +20,329 @@ export class GitModel {
this.working = {...snapshot};
this.index = {...snapshot};
this.conflict = null;
- this.remote = {main: "c0"};
- this.tracking = {main: "c0"};
+ this.remote = {main: 'c0'};
+ this.tracking = {main: 'c0'};
+ this.upstream = {main: 'main'};
this.pullRequest = null;
}
- get head() { return this.commits.find(c => c.id === this.branches[this.current]); }
- changed(a, b) { return Object.keys(a).filter(k => a[k] !== b[k]); }
- get staged() { return this.changed(this.index, this.head.snapshot); }
- get unstaged() { return this.changed(this.working, this.index); }
+
+ get head() { return this.commitAt(this.branches[this.current]); }
+ commitAt(id) { return this.commits.find(commit => commit.id === id); }
+ changed(a, b) { return Object.keys(files).filter(key => a[key] !== b[key]); }
+ get unmerged() { return this.conflict?.keys.filter(key => !this.conflict.stagedKeys.has(key)) ?? []; }
+ get staged() { return this.changed(this.index, this.head.snapshot).filter(key => !this.unmerged.includes(key)); }
+ get unstaged() { return this.changed(this.working, this.index).filter(key => !this.unmerged.includes(key)); }
get dirty() { return Boolean(this.staged.length || this.unstaged.length); }
- ready() { if (this.conflict) throw new Error('Resolve or abort the merge first.'); }
+
+ ready() {
+ if (this.conflict) throw new Error('Finish or abort the merge first.');
+ }
+
edit(key) {
- this.ready();
if (key === 'rule') {
const alternate = this.current === 'main' ? '0.25' : '0.30';
- this.working.rule = this.working.rule === alternate ? '0.20' : alternate;
- } else if (key === 'plot') {
- this.working.plot = this.working.plot === 'teal' ? 'purple' : 'teal';
- } else throw new Error('Unknown teaching file.');
- return `Working file changed: ${key === 'rule' ? `min_rt_s = ${this.working.rule} s` : `plot color = ${this.working.plot}`}. Stage it to include this version in a commit.`;
+ return this.setFile(key, this.working.rule === alternate ? '0.20' : alternate);
+ }
+ if (key === 'plot') return this.setFile(key, this.working.plot === 'teal' ? 'purple' : 'teal');
+ throw new Error('Unknown teaching file.');
}
- stage(keys = Object.keys(this.working)) {
+
+ setFile(key, value) {
+ this.ready();
+ if (!Object.hasOwn(files, key)) throw new Error('Unknown teaching file.');
+ const next = fileValue(key, value);
+ if (this.working[key] === next) return `${files[key]} is already saved at that value.`;
+ this.working[key] = next;
+ return `Saved ${files[key]} in the working tree.`;
+ }
+
+ stage(keys = Object.keys(files)) {
+ for (const key of keys) {
+ if (!Object.hasOwn(files, key)) throw new Error('Unknown teaching file.');
+ if (this.unmerged.includes(key) && !this.conflict.resolvedKeys.has(key)) {
+ throw new Error(`Write a resolution for ${files[key]} before staging it.`);
+ }
+ }
for (const key of keys) {
- if (!(key in this.working)) throw new Error('Unknown teaching file.');
- if (this.conflict?.keys.includes(key) && !this.conflict.resolved) throw new Error('Resolve the conflicting file before staging.');
this.index[key] = this.working[key];
- if(this.conflict?.keys.includes(key)) this.conflict.stagedKeys.add(key);
+ if (this.conflict?.keys.includes(key)) this.conflict.stagedKeys.add(key);
}
- if (this.conflict && this.conflict.keys.every(key => this.conflict.stagedKeys.has(key) && this.index[key] === this.working[key])) this.conflict.staged = this.conflict.resolved;
- return `Staged ${keys.join(', ')}. Further working edits stay unstaged until added again.`;
+ return `Staged ${keys.map(key => files[key]).join(', ')}.`;
}
- record(snapshot, parents, message) {
- if (this.commits.length >= 50) throw new Error('This sandbox is limited to 50 commits. Reset to explore again.');
- const commit = {id: `c${this.commits.length}`, parents, branch: this.current, message, snapshot: {...snapshot}};
+
+ unstage(keys = Object.keys(files)) {
+ this.ready();
+ if (keys.some(key => !Object.hasOwn(files, key))) throw new Error('Unknown file.');
+ for (const key of keys) this.index[key] = this.head.snapshot[key];
+ return 'Unstaged the selected files. Working edits are preserved.';
+ }
+
+ discard(keys) {
+ this.ready();
+ const paths = Array.isArray(keys) ? keys : [keys];
+ if (paths.some(key => !Object.hasOwn(files, key))) throw new Error('Unknown file.');
+ for (const key of paths) this.working[key] = this.index[key];
+ return 'Restored the selected files from the index. Their unstaged edits were discarded.';
+ }
+
+ diff(staged = false) {
+ const before = staged ? this.head.snapshot : this.index;
+ const after = staged ? this.index : this.working;
+ return (staged ? this.staged : this.unstaged).map(key => ({key, before: before[key], after: after[key]}));
+ }
+
+ createCommit(branch, snapshot, parents, message, metadata) {
+ if (this.commits.length >= 50) throw new Error('This sandbox is limited to 50 commits. Restart this mission to explore again.');
+ const commit = {id: `c${this.commits.length}`, parents, branch, message, snapshot: {...snapshot}, ...metadata};
this.commits.push(commit);
+ return commit;
+ }
+
+ record(snapshot, parents, message, metadata) {
+ const commit = this.createCommit(this.current, snapshot, parents, message, metadata);
this.branches[this.current] = commit.id;
return commit;
}
+
commit(message) {
- if(this.conflict && !this.conflict.staged) throw new Error('Resolve or abort the merge; resolved files must be staged before committing.');
+ if (this.unmerged.length) throw new Error('Resolve the conflicting files and stage them before committing, or abort the merge.');
if (!this.staged.length && !this.conflict) throw new Error('Nothing staged. Edit a file and use git add first.');
- const changed = this.staged.join(' + ');
- const parents = this.conflict ? this.conflict.parents : [this.head.id];
- const commit = this.record(this.index, parents, message || (this.conflict ? 'Resolve conflict and merge' : `Update ${changed}`));
+ const parents = this.conflict?.parents ?? [this.head.id];
+ const commit = this.record(this.index, parents,
+ message || (this.conflict ? `Merge ${this.conflict.source} into ${this.current}` : 'Update analysis'),
+ this.conflict ? {resolvedMerge: true} : {});
this.conflict = null;
- return `Created ${commit.id} on ${this.current} from the staged snapshot. ${this.unstaged.length ? 'Later working edits remain unstaged.' : 'The working tree is clean.'} No remote was updated.`;
+ return `Created ${commit.id} on ${this.current}. ${this.unstaged.length ? 'Unstaged edits remain in the working tree.' : 'Working tree clean.'}`;
}
- branch(name = "criteria") {
+
+ branch(name = 'criteria', switchToBranch = true) {
this.ready();
- if(!/^[a-z][a-z0-9-]{0,24}$/.test(name)) throw new Error('Use a short lowercase branch name with letters, numbers, and hyphens.');
- if(this.branches[name]) throw new Error('Branch already exists. Use git switch.');
- if(Object.keys(this.branches).length >= 5) throw new Error('This teaching model supports five local branches. Reset to explore again.');
- if (this.dirty) throw new Error('Commit your changes before branching in this teaching model.');
+ const parts = name.split('/');
+ const valid = /^[A-Za-z0-9_][A-Za-z0-9._/-]{0,63}$/.test(name) &&
+ !name.includes('..') && !name.endsWith('.') && name !== 'HEAD' &&
+ parts.every(part => part && !part.startsWith('.') && !part.endsWith('.lock'));
+ if (!valid) throw new Error('Use a branch name such as criteria or feature/rt-policy.');
+ if (Object.hasOwn(this.branches, name)) throw new Error('Branch already exists. Use git switch.');
+ if (Object.keys(this.branches).length >= 5) throw new Error('This teaching repository supports five local branches.');
this.branches[name] = this.head.id;
- this.current = name;
- return `Created ${name} at the current commit and switched HEAD. No new commit was created.`;
+ if (switchToBranch) this.current = name;
+ return `Created ${name} at ${this.head.id}.${switchToBranch ? ` Now on ${name}.` : ''}${this.dirty ? ' Pending edits are preserved.' : ''}`;
}
- switchBranch(name) {
+
+ switchBranch(name = this.current === 'main' ? 'criteria' : 'main') {
this.ready();
- name = name || (this.current === 'main' ? 'criteria' : 'main');
- if(!this.branches[name]) throw new Error('Create the target branch first.');
- if (this.dirty) throw new Error('Commit your changes before switching in this teaching model.');
+ if (!Object.hasOwn(this.branches, name)) throw new Error(`Branch ${name} does not exist. List branches with git branch.`);
+ if (this.current === name) return `Already on ${name}.`;
+ const target = this.commitAt(this.branches[name]).snapshot;
+ const updated = this.changed(target, this.head.snapshot);
+ const pending = [...this.staged, ...this.unstaged];
+ const blocked = updated.filter(key => pending.includes(key));
+ if (blocked.length) {
+ throw new Error(`Switch would overlap with pending edits in ${blocked.map(key => files[key]).join(', ')}. Commit or restore those edits first.`);
+ }
+ for (const key of updated) this.working[key] = this.index[key] = target[key];
this.current = name;
- this.index = {...this.head.snapshot};
- this.working = {...this.head.snapshot};
- return `HEAD now points to ${this.current}; working files match its tip ${this.head.id}.`;
+ return `Switched to ${name} at ${this.head.id}.${pending.length ? ' Pending edits carried over.' : ''}`;
}
+
ancestors(id, seen = new Set()) {
if (seen.has(id)) return seen;
seen.add(id);
- this.commits.find(c => c.id === id).parents.forEach(p => this.ancestors(p, seen));
+ for (const parent of this.commitAt(id).parents) this.ancestors(parent, seen);
return seen;
}
- merge(source = "criteria") {
+
+ mergeBase(first, second) {
+ const a = this.ancestors(first);
+ const b = this.ancestors(second);
+ const common = this.commits.filter(commit => a.has(commit.id) && b.has(commit.id));
+ const bases = common.filter(commit =>
+ !common.some(other => other !== commit && this.ancestors(other.id).has(commit.id)));
+ if (bases.length !== 1) throw new Error('This simulator needs a single merge base.');
+ return bases[0];
+ }
+
+ combine(ours, theirs, base) {
+ const snapshot = {...ours};
+ const conflicts = [];
+ for (const key of this.changed(ours, theirs)) {
+ if (ours[key] === base[key]) snapshot[key] = theirs[key];
+ else if (theirs[key] !== base[key]) conflicts.push(key);
+ }
+ return {snapshot, conflicts};
+ }
+
+ checkoutSnapshot(snapshot) {
+ this.index = {...snapshot};
+ this.working = {...snapshot};
+ }
+
+ merge(source = 'criteria') {
this.ready();
- if (source === this.current) return "Already up to date.";
- if (!this.branches[source]) throw new Error('Create the source branch first.');
- if (this.dirty) throw new Error('Start the merge with a clean working tree.');
+ if (!Object.hasOwn(this.branches, source)) throw new Error(`Branch ${source} does not exist. List branches with git branch.`);
+ if (this.dirty) throw new Error('Start this merge with a clean working tree. Commit or restore pending edits first.');
const ours = this.head;
- const theirs = this.commits.find(c => c.id === this.branches[source]);
- const ourAncestors = this.ancestors(ours.id);
- const theirAncestors = this.ancestors(theirs.id);
- if (ourAncestors.has(theirs.id)) return `Already up to date: ${source} is already in ${this.current}’s history.`;
- if (theirAncestors.has(ours.id)) {
+ const theirs = this.commitAt(this.branches[source]);
+ if (this.ancestors(ours.id).has(theirs.id)) return `Already up to date. ${source} is in ${this.current}'s history.`;
+ if (this.ancestors(theirs.id).has(ours.id)) {
this.branches[this.current] = theirs.id;
- this.index = {...theirs.snapshot};
- this.working = {...theirs.snapshot};
- return `Fast-forward: ${this.current} moved to ${source}’s tip. No merge commit was needed.`;
- }
- // In this bounded model, the newest common ancestor is the merge base.
- const common = this.commits.filter(c => ourAncestors.has(c.id) && theirAncestors.has(c.id));
- const bases = common.filter(c => !common.some(other => c.id !== other.id && this.ancestors(other.id).has(c.id)));
- if(bases.length !== 1) throw new Error('This bounded model does not resolve multiple merge bases.');
- const base = bases[0];
- const snapshot = {...ours.snapshot};
- const conflicts = [];
- for (const key of Object.keys(snapshot)) {
- if (ours.snapshot[key] === theirs.snapshot[key]) continue;
- if (ours.snapshot[key] === base.snapshot[key]) snapshot[key] = theirs.snapshot[key];
- else if (theirs.snapshot[key] !== base.snapshot[key]) conflicts.push(key);
+ this.checkoutSnapshot(theirs.snapshot);
+ return `Fast-forwarded ${this.current} to ${source} at ${theirs.id}.`;
}
+
+ const base = this.mergeBase(ours.id, theirs.id);
+ const {snapshot, conflicts} = this.combine(ours.snapshot, theirs.snapshot, base.snapshot);
+ const parents = [ours.id, theirs.id];
if (conflicts.length) {
- this.conflict = {parents: [ours.id, theirs.id], snapshot, keys: conflicts, ours:ours.snapshot, theirs:theirs.snapshot, resolved:false, staged:false, stagedKeys:new Set()};
- return `Merge stopped: both branches changed ${conflicts.join(' and ')} differently since ${base.id}. Choose the intended final rule, then record the resolved merge, or abort.`;
+ this.conflict = {
+ parents, source, keys: conflicts, ours: ours.snapshot, theirs: theirs.snapshot,
+ resolvedKeys: new Set(), stagedKeys: new Set()
+ };
+ this.checkoutSnapshot(snapshot);
+ return `Merge stopped. Both branches changed ${conflicts.map(key => files[key]).join(', ')} since ${base.id}. Write and stage a resolution, or abort the merge.`;
}
- const merged = this.record(snapshot, [ours.id, theirs.id], `Merge ${source} into ${this.current}`);
- this.index = {...snapshot}; this.working = {...snapshot};
- return `Created ${merged.id}, a merge commit with two parents. The separate rule and plot changes are both included.`;
+ const merged = this.record(snapshot, parents, `Merge ${source} into ${this.current}`);
+ this.checkoutSnapshot(snapshot);
+ return `Created merge commit ${merged.id} with parents ${parents.join(' and ')}.`;
}
+
resolveWorking(values) {
- if (!this.conflict) throw new Error('No unresolved merge.');
- const snapshot = {...this.conflict.snapshot, ...values};
- if(!Number.isFinite(Number(snapshot.rule)) || Number(snapshot.rule)<=0 || Number(snapshot.rule)>=2) throw new Error('The minimum RT must lie between 0 and 2 seconds.');
- if(!['teal','purple','orange'].includes(snapshot.plot)) throw new Error('Choose a teaching plot color.');
- this.working = snapshot;
- this.conflict.resolved = true;
- this.conflict.staged = false;
- this.conflict.stagedKeys.clear();
- return 'Resolution written to the working files. Inspect it, stage the resolved file, then commit the merge.';
+ if (!this.conflict) throw new Error('No merge in progress.');
+ const resolutions = Object.entries(values).map(([key, value]) => {
+ if (!this.conflict.keys.includes(key)) throw new Error('Choose a file with a merge conflict.');
+ return [key, fileValue(key, value)];
+ });
+ for (const [key, value] of resolutions) {
+ this.working[key] = value;
+ this.conflict.resolvedKeys.add(key);
+ this.conflict.stagedKeys.delete(key);
+ }
+ return 'Resolution saved to the working file. Stage it to include it in the merge commit.';
}
+
resolve(value) {
- this.resolveWorking({rule:value}); this.stage(); this.commit('Resolve rule conflict and merge criteria');
+ this.resolveWorking({rule: value});
+ this.stage();
+ this.commit('Resolve rule conflict and merge criteria');
return `Resolved at ${value} s. The merge commit has two parents.`;
}
+
abort() {
if (!this.conflict) throw new Error('No merge to abort.');
this.conflict = null;
- this.index = {...this.head.snapshot}; this.working = {...this.head.snapshot};
- return `Merge aborted. ${this.current} and the working files are back at the pre-merge snapshot; branch history is intact.`;
+ this.checkoutSnapshot(this.head.snapshot);
+ return `Merge aborted. Restored the working tree and staging area to ${this.current} at ${this.head.id}.`;
}
- setFile(key, value) {
+ push(branch, setUpstream = false) {
this.ready();
- if(key==='rule') {
- if(!Number.isFinite(Number(value)) || Number(value)<=0 || Number(value)>=2) throw new Error('Minimum RT must be between 0 and 2 seconds.');
- this.working.rule=Number(value).toFixed(2);
- } else if(key==='plot' && ['teal','purple','orange'].includes(value)) this.working.plot=value;
- else throw new Error('Unknown file or invalid value.');
- return 'Changed the working file. The index and HEAD are unchanged.';
- }
- unstage(keys = Object.keys(this.index)) {
- this.ready();
- for(const key of keys) {if(!(key in this.index)) throw new Error('Unknown file.');this.index[key]=this.head.snapshot[key];}
- return 'Unstaged the selected file; working edits are preserved.';
- }
- discard(key) {
- this.ready();if(!(key in this.working))throw new Error('Unknown file.');
- this.working[key]=this.index[key];
- return 'Restored the working file from the index. Its unstaged edit was discarded.';
+ if (!branch && !Object.hasOwn(this.upstream, this.current)) {
+ throw new Error(`No upstream for ${this.current}. Run git push -u origin ${this.current}.`);
+ }
+ branch ??= this.upstream[this.current];
+ if (!Object.hasOwn(this.branches, branch)) throw new Error(`Unknown local branch: ${branch}.`);
+ const tip = this.branches[branch];
+ if (Object.hasOwn(this.remote, branch) && !this.ancestors(tip).has(this.remote[branch])) {
+ throw new Error('Push rejected. Fetch and inspect the server history before integrating its changes.');
+ }
+ this.remote[branch] = tip;
+ this.tracking[branch] = tip;
+ if (setUpstream) this.upstream[branch] = branch;
+ return `Pushed ${branch} to origin/${branch}.${setUpstream ? ` ${branch} now tracks origin/${branch}.` : ''}`;
}
- diff(staged=false) {
- const before=staged?this.head.snapshot:this.index;
- const after=staged?this.index:this.working;
- return this.changed(after,before).map(key=>({key,before:before[key],after:after[key]}));
+
+ fetch() {
+ this.tracking = {...this.remote};
+ return 'Fetched origin. Remote-tracking branches are up to date.';
}
- push(branch=this.current) {
+
+ pull(branch) {
this.ready();
- if(!this.branches[branch])throw new Error('Unknown local branch.');
- const remoteTip=this.remote[branch];
- if(remoteTip && !this.ancestors(this.branches[branch]).has(remoteTip)) throw new Error('Push rejected: remote history is not an ancestor. Fetch and inspect divergence; do not force push.');
- this.remote[branch]=this.branches[branch];this.tracking[branch]=this.branches[branch];
- return `Pushed ${branch}. The origin branch and its local remote-tracking reference were updated.`;
- }
- fetch() {this.tracking={...this.remote};return 'Fetched origin: remote-tracking pointers updated. Local branch, index, and working files did not move.';}
- pull() {
- this.ready();if(this.dirty)throw new Error('Commit or preserve changes before pulling in this model.');
- this.fetch();const target=this.tracking[this.current];
- if(!target)throw new Error('This branch has no counterpart on origin. Push it first.');
- if(this.ancestors(this.head.id).has(target))return 'Already up to date; local history contains the remote tip.';
- if(!this.ancestors(target).has(this.head.id))throw new Error('git pull --ff-only refused: histories diverged. Inspect the graph and coordinate a merge.');
- this.branches[this.current]=target;this.index={...this.head.snapshot};this.working={...this.head.snapshot};
- return 'Fast-forward pull updated the local branch, index, and working files.';
- }
- colleague(key='plot',value='orange') {
- if(this.commits.length>=50) throw new Error('Reset the sandbox after 50 commits.');
- if(!['rule','plot'].includes(key))throw new Error('Unknown teaching file.');
- if(key==='rule'){if(!Number.isFinite(Number(value))||Number(value)<=0||Number(value)>=2)throw new Error('Minimum RT must be between 0 and 2 seconds.');value=Number(value).toFixed(2);}
- else if(!['teal','purple','orange'].includes(value))throw new Error('Choose a teaching plot color.');
- const parent=this.remote.main;
- const snapshot={...this.commits.find(c=>c.id===parent).snapshot,[key]:value};
- const node={id:`c${this.commits.length}`,parents:[parent],branch:'origin/main',message:'Labmate updates shared analysis',snapshot};
- this.commits.push(node);this.remote.main=node.id;
- return 'A labmate committed on the simulated server. Your local files and origin/main tracking reference are still unchanged until fetch.';
+ if (this.dirty) throw new Error('Commit or restore pending edits before pulling in this simulator.');
+ if (!branch && !Object.hasOwn(this.upstream, this.current)) {
+ throw new Error(`No upstream for ${this.current}. Specify a branch with git pull --ff-only origin BRANCH.`);
+ }
+ branch ??= this.upstream[this.current];
+ this.fetch();
+ if (!Object.hasOwn(this.tracking, branch)) throw new Error(`Branch ${branch} does not exist on origin.`);
+ const target = this.tracking[branch];
+ if (this.ancestors(this.head.id).has(target)) return `Already up to date with origin/${branch}.`;
+ if (!this.ancestors(target).has(this.head.id)) {
+ throw new Error('git pull --ff-only refused: histories diverged. Inspect the graph and coordinate a merge.');
+ }
+ this.branches[this.current] = target;
+ this.checkoutSnapshot(this.head.snapshot);
+ return `Fast-forwarded local ${this.current} to ${target} from origin/${branch}.`;
+ }
+
+ colleague(key = 'plot', value = 'orange') {
+ if (!Object.hasOwn(files, key)) throw new Error('Unknown teaching file.');
+ const parent = this.remote.main;
+ const snapshot = {...this.commitAt(parent).snapshot, [key]: fileValue(key, value)};
+ const node = this.createCommit('origin/main', snapshot, [parent], 'Labmate updates shared analysis');
+ this.remote.main = node.id;
+ return `A labmate moved server main to ${node.id}. Fetch to update your local origin/main reference.`;
}
+
openPR() {
- if(this.current==='main')throw new Error('Create and push a feature branch before opening a pull request.');
- if(this.remote[this.current]!==this.branches[this.current])throw new Error('Push the current branch tip before opening a pull request.');
- if(this.ancestors(this.remote.main).has(this.remote[this.current]))throw new Error('No new commits to propose.');
- this.pullRequest={source:this.current,head:this.remote[this.current],base:this.remote.main,reviewedHead:null,reviewedBase:null,merged:false};
- return 'Opened a simulated pull request to main. Review the proposed change before merging.';
+ if (this.current === 'main') throw new Error('Switch to the pushed feature branch before opening a pull request.');
+ if (this.pullRequest && !this.pullRequest.merged) throw new Error('A pull request is already open.');
+ if (this.remote[this.current] !== this.branches[this.current]) throw new Error('Push the current branch before opening a pull request.');
+ if (this.ancestors(this.remote.main).has(this.remote[this.current])) throw new Error('No new commits to propose.');
+ this.pullRequest = {source: this.current, reviewedHead: null, reviewedBase: null, merged: false};
+ return 'Opened the simulated pull request. Review the proposed changes before merging.';
}
+
reviewPR() {
- if(!this.pullRequest || this.pullRequest.merged)throw new Error('Open a pull request first.');
- const pr=this.pullRequest;
- pr.reviewedHead=this.remote[pr.source];pr.reviewedBase=this.remote.main;
- return 'Review recorded for the current source and target tips. New commits require another review.';
+ if (!this.pullRequest || this.pullRequest.merged) throw new Error('Open a pull request first.');
+ const pr = this.pullRequest;
+ pr.reviewedHead = this.remote[pr.source];
+ pr.reviewedBase = this.remote.main;
+ return 'Review recorded for these branch tips. New commits on either branch require a fresh review.';
+ }
+
+ get prReviewCurrent() {
+ const pr = this.pullRequest;
+ return Boolean(pr && !pr.merged &&
+ pr.reviewedHead === this.remote[pr.source] && pr.reviewedBase === this.remote.main);
+ }
+
+ get prComparison() {
+ const pr = this.pullRequest;
+ if (!pr) return null;
+ const head = pr.merged ? pr.reviewedHead : this.remote[pr.source];
+ const target = pr.merged ? pr.reviewedBase : this.remote.main;
+ const base = this.mergeBase(target, head);
+ const snapshot = this.commitAt(head).snapshot;
+ const changes = this.changed(snapshot, base.snapshot).map(key =>
+ ({key, before: base.snapshot[key], after: snapshot[key]}));
+ return {base: base.id, head, target, changes};
}
+
mergePR() {
- const pr=this.pullRequest;
- if(!pr || pr.merged)throw new Error('Open an unmerged pull request first.');
- if(pr.reviewedHead!==this.remote[pr.source] || pr.reviewedBase!==this.remote.main)throw new Error('Review is missing or stale. Review the current source and target tips.');
- const ours=this.commits.find(c=>c.id===this.remote.main),theirs=this.commits.find(c=>c.id===this.remote[pr.source]);
- if(this.ancestors(ours.id).has(theirs.id))throw new Error('The proposed commits are already in main.');
- const common=this.commits.filter(c=>this.ancestors(ours.id).has(c.id)&&this.ancestors(theirs.id).has(c.id));
- const bases=common.filter(c=>!common.some(other=>c.id!==other.id&&this.ancestors(other.id).has(c.id)));
- if(bases.length!==1)throw new Error('Multiple merge bases are outside this model.');
- const snapshot={...ours.snapshot};
- for(const key of Object.keys(snapshot)){
- if(ours.snapshot[key]===theirs.snapshot[key])continue;
- if(ours.snapshot[key]===bases[0].snapshot[key])snapshot[key]=theirs.snapshot[key];
- else if(theirs.snapshot[key]!==bases[0].snapshot[key])throw new Error('Pull request has a conflict. Resolve it locally and push the result before review.');
- }
- if(this.commits.length>=50)throw new Error('Reset the sandbox after 50 commits.');
- const node={id:`c${this.commits.length}`,parents:[ours.id,theirs.id],branch:'origin/main',message:`Merge reviewed PR from ${pr.source}`,snapshot};
- this.commits.push(node);this.remote.main=node.id;pr.merged=true;
- return 'Merged on the simulated server using a two-parent merge commit. Local main has not moved; switch to main and pull --ff-only.';
+ const pr = this.pullRequest;
+ if (!pr || pr.merged) throw new Error('Open an unmerged pull request first.');
+ if (!this.prReviewCurrent) throw new Error('Review is missing or stale. Review the current branch tips.');
+ const ours = this.commitAt(this.remote.main);
+ const theirs = this.commitAt(this.remote[pr.source]);
+ if (this.ancestors(ours.id).has(theirs.id)) throw new Error('The proposed commits are already in main.');
+ const base = this.mergeBase(ours.id, theirs.id);
+ const {snapshot, conflicts} = this.combine(ours.snapshot, theirs.snapshot, base.snapshot);
+ if (conflicts.length) throw new Error('Pull request has a conflict. Resolve it locally and push the result before review.');
+ const node = this.createCommit('origin/main', snapshot, [ours.id, theirs.id], `Merge reviewed PR from ${pr.source}`);
+ this.remote.main = node.id;
+ pr.merged = true;
+ return `Merged on the server at ${node.id}. Switch to local main and pull to catch up.`;
}
+
revert() {
- this.ready();if(this.dirty)throw new Error('Start revert with a clean working tree.');
- if(this.head.parents.length!==1)throw new Error('This exercise supports reverting the latest single-parent commit only.');
- const old=this.head, parent=this.commits.find(c=>c.id===old.parents[0]);
- this.record(parent.snapshot,[old.id],`Revert ${old.id}: ${old.message}`);
- this.index={...this.head.snapshot};this.working={...this.head.snapshot};
- return 'Created an inverse commit. The original commit remains in history; nothing was erased.';
+ this.ready();
+ if (this.dirty) throw new Error('Start revert with a clean working tree.');
+ if (this.head.parents.length !== 1) throw new Error('This exercise supports reverting the latest single-parent commit only.');
+ const old = this.head;
+ const parent = this.commitAt(old.parents[0]);
+ const inverse = this.record(parent.snapshot, [old.id], `Revert ${old.id}: ${old.message}`, {reverts: old.id});
+ this.checkoutSnapshot(this.head.snapshot);
+ return `Created ${inverse.id} to undo ${old.id}. Both commits remain in history.`;
}
}
diff --git a/site/assets/git-playground.js b/site/assets/git-playground.js
index 084d1ec..0b4efd8 100644
--- a/site/assets/git-playground.js
+++ b/site/assets/git-playground.js
@@ -1,65 +1,487 @@
-import {GitModel} from './git-model.js';
-import {files,status,diff,executeCommand,missions} from './git-commands.js';
-const root=document.querySelector('[data-git-dojo]');
-const escape=value=>String(value??'').replace(/[&<>"']/g,c=>({'&':'&','<':'<','>':'>','"':'"',"'":'''}[c]));
-if(root){
- const q=s=>root.querySelector(s);let model=new GitModel(),events=[],selected='c0',mission=missions[0];
- function log(command,text){events.push(command);q('[data-command-log]').textContent+=`> ${command}\n${text}\n\n`;q('[data-command-log]').scrollTop=q('[data-command-log]').scrollHeight;}
- function perform(command,callback){try{const text=callback?callback():executeCommand(model,command);log(command,text);q('[data-git-feedback]').textContent=text;}catch(error){log(command,`Stopped: ${error.message}`);q('[data-git-feedback]').textContent=error.message;}render();}
- function snapshot(value){return `# config/analysis.toml\nmin_rt_s = ${value.rule}\nmax_rt_s = 2.00\n\n# src/experiment/plotting.py\ncolor = "${value.plot}"`;}
- function render(){
- q('[data-dojo-head]').textContent=`HEAD → ${model.current} → ${model.head.id}`;
- q('[data-working-snapshot]').textContent=snapshot(model.working);q('[data-index-snapshot]').textContent=snapshot(model.index);q('[data-head-snapshot]').textContent=snapshot(model.head.snapshot);
- q('[data-dojo-status]').textContent=status(model);q('[data-unstaged-diff]').textContent=diff(model);q('[data-staged-diff]').textContent=diff(model,true);
- const branchSelect=q('[data-switch-target]'),mergeSelect=q('[data-merge-target]');
- const old=mergeSelect.value;branchSelect.replaceChildren();mergeSelect.replaceChildren();
- for(const name of Object.keys(model.branches)){
- const option=document.createElement('option');option.value=name;option.textContent=name;branchSelect.append(option);if(name!==model.current)mergeSelect.append(option.cloneNode(true));
- }
- branchSelect.value=model.current;if([...mergeSelect.options].some(o=>o.value===old))mergeSelect.value=old;
- const reachable=new Set();for(const tip of [...Object.values(model.branches),...Object.values(model.tracking)])for(const id of model.ancestors(tip))reachable.add(id);
- const visible=model.commits.filter(c=>reachable.has(c.id));const lanes=['main',...Object.keys(model.branches).filter(b=>b!=='main'),'origin/main'];
- const width=Math.max(580,visible.length*105+90),height=Math.max(180,lanes.length*65+30);
- const point=c=>({x:55+visible.indexOf(c)*105,y:40+Math.max(0,lanes.indexOf(c.branch))*65});
- const edges=visible.flatMap(c=>c.parents.map(id=>{const p=point(model.commits.find(n=>n.id===id)),n=point(c);return ``;})).join('');
- const nodes=visible.map(c=>{const p=point(c);const labels=[...Object.entries(model.branches).filter(([,id])=>id===c.id).map(([name])=>name+(name===model.current?' ← HEAD':'')),...Object.entries(model.tracking).filter(([,id])=>id===c.id).map(([name])=>`origin/${name}`)];return `${c.id}${escape(labels.join(' · '))}`;}).join('');
- q('[data-dojo-graph]').innerHTML=``;
- q('[data-commit-list]').innerHTML=[...visible].reverse().map(c=>`
parents ${escape(c.parents.join(', ')||'none')}
`).join('');
- const inspected=model.commits.find(c=>c.id===selected)||model.head;
- q('[data-inspected-commit]').textContent=`${inspected.id} · ${inspected.message}\nParents: ${inspected.parents.join(', ')||'none'}\n${snapshot(inspected.snapshot)}`;
- q('[data-remote-refs]').textContent=`SERVER origin\n${Object.entries(model.remote).map(([b,id])=>`${b} → ${id}`).join('\n')}\n\nLOCAL remote-tracking references (last fetch/push)\n${Object.entries(model.tracking).map(([b,id])=>`origin/${b} → ${id}`).join('\n')}\n\nA server change does not move your local branch.`;
- const pr=model.pullRequest;
- if(pr){const source=model.commits.find(c=>c.id===model.remote[pr.source]),target=model.commits.find(c=>c.id===model.remote.main);q('[data-pr-diff]').textContent=`${pr.merged?'MERGED':'OPEN'} · ${pr.source} → main\nCurrent source ${source.id}; target ${target.id}\nReviewed source ${pr.reviewedHead||'none'}; target ${pr.reviewedBase||'none'}\n\n${Object.keys(files).filter(k=>source.snapshot[k]!==target.snapshot[k]).map(k=>`${files[k]}: ${target.snapshot[k]} → ${source.snapshot[k]}`).join('\n')||'No snapshot differences at current tips.'}`;}else q('[data-pr-diff]').textContent='No simulated pull request. Push a feature branch, then open one.';
- q('[data-dojo-conflict]').hidden=!model.conflict;
- if(model.conflict){q('[data-conflict-markers]').textContent=model.conflict.keys.map(k=>`${files[k]}\n<<<<<<< ${model.current}\n${model.conflict.ours[k]}\n=======\n${model.conflict.theirs[k]}\n>>>>>>> incoming branch`).join('\n\n');}
- }
- function selectMission(id){mission=missions.find(m=>m.id===id)||missions[0];model=new GitModel();events=[];selected='c0';q('[data-mission-goal]').textContent=mission.goal;q('[data-mission-hint]').textContent=mission.hint;delete q('[data-mission-check]').dataset.state;q('[data-mission-check]').textContent='Not checked yet. Predict, act, inspect, then explain.';q('[data-command-log]').textContent='';q('[data-git-feedback]').textContent='Sandbox reset to the cloned baseline. All activity is simulated.';if(mission.id==='remote')q('[data-remote-panel]').open=true;render();root.dispatchEvent(new CustomEvent('workshop:git-mission',{detail:{id:mission.id}}));}
- const missionNames={staging:'1 · Stage one change',branches:'2 · Branch & merge',conflict:'3 · Resolve a conflict',remote:'4 · Share & review',recovery:'5 · Recover a change'};
- q('[data-git-mission]').innerHTML=missions.map(m=>``).join('');
- q('[data-git-mission]').addEventListener('change',e=>selectMission(e.target.value));
- root.addEventListener('submit',e=>{e.preventDefault();if(e.target.matches('[data-command-form]')){const input=q('[data-command-input]');perform(input.value);input.value='';}});
- root.addEventListener('click',e=>{
- const b=e.target.closest('button');if(!b)return;
- if(b.dataset.inspect){selected=b.dataset.inspect;render();return;}
- if(b.dataset.command){perform(b.dataset.command);return;}
- switch(b.dataset.gitAction){
- case 'rule':perform('edit config/analysis.toml',()=>model.setFile('rule',q('[data-rule-value]').value));break;
- case 'plot':perform('edit src/experiment/plotting.py',()=>model.setFile('plot',q('[data-plot-value]').value));break;
- case 'stage':perform(`git add ${q('[data-stage-file]').value}`);break;
- case 'unstage':perform(`git restore --staged ${q('[data-stage-file]').value}`);break;
- case 'discard':{const key=q('[data-stage-file]').value;if(key==='.')q('[data-git-feedback]').textContent='Choose one file before discarding its unstaged changes.';else perform(`git restore ${key}`);break;}
- case 'commit':perform(`git commit -m ${JSON.stringify(q('[data-commit-message]').value||'Describe the scientific change')}`);break;
- case 'branch':perform(`git switch -c ${q('[data-branch-name]').value}`);break;
- case 'switch':perform(`git switch ${q('[data-switch-target]').value}`);break;
- case 'merge':perform(`git merge ${q('[data-merge-target]').value}`);break;
- case 'resolve':perform('write resolved working file',()=>model.resolveWorking({rule:Number(q('[data-resolution-rule]').value).toFixed(2),plot:q('[data-resolution-plot]').value}));break;
- case 'colleague':perform('labmate commits on origin/main',()=>model.colleague());break;
- case 'open-pr':perform('open simulated pull request',()=>model.openPR());break;
- case 'review-pr':perform('review the current source and target tips',()=>model.reviewPR());break;
- case 'merge-pr':perform('merge reviewed pull request on origin',()=>model.mergePR());break;
- case 'check':q('[data-mission-check]').dataset.state=mission.check(model,events)?'passed':'error';q('[data-mission-check]').textContent=mission.check(model,events)?`Passed · ${mission.explanation}\nExplain this to your partner before the next mission.`:`Not yet. ${mission.goal}\nInspect status, the two diffs, and the branch pointers.`;break;
- case 'reset':selectMission(mission.id);break;
- }
- });
- const initial=new URLSearchParams(location.search).get('mission')||'staging';q('[data-git-mission]').value=missions.some(m=>m.id===initial)?initial:'staging';selectMission(initial);
+import {files} from './git-model.js';
+import {executeCommand, formatDiff, quoteArgument} from './git-commands.js';
+import {missionProgress, missions, runMissionAction, startMission} from './git-missions.js';
+import {tabs} from './ui.js';
+
+const root = document.querySelector('[data-git-dojo]');
+const q = selector => root.querySelector(selector);
+const escape = value => String(value).replace(/[&<>"']/g,
+ char => ({'&': '&', '<': '<', '>': '>', '"': '"', "'": '''})[char]);
+const names = {rule: 'analysis.toml', plot: 'plotting.py'};
+const views = {changes: 'Changes', history: 'Branches', remote: 'Remote & pull request'};
+const valueLabel = (key, value) => key === 'rule' ? `${value} s` : value;
+
+const sessions = new Map();
+let session;
+let view;
+const selectView = tabs(root, '[data-git-tabs]', name => {
+ view = name;
+ if (session) {
+ session.view = name;
+ renderGuide();
+ }
+});
+const input = q('[data-command-input]');
+const terminal = q('#git-terminal');
+const terminalButton = q('[data-toggle-terminal]');
+
+function setText(node, value) {
+ if (node.textContent !== value) node.textContent = value;
}
+
+function setCommand(button, command) {
+ button.dataset.command = command;
+ button.title = command;
+}
+
+function setOptions(select, options, placeholder) {
+ const previous = select.value;
+ select.replaceChildren(...(options.length
+ ? options.map(([value, label]) => new Option(label, value))
+ : [new Option(placeholder, '')]));
+ if (options.some(([value]) => value === previous)) select.value = previous;
+ select.disabled = !options.length;
+}
+
+function renderGuide() {
+ const {steps, next, complete} = missionProgress(session);
+ q('[data-mission-steps]').innerHTML = steps.map(item => `
+
Interactive simulation5 missions · 25–40 minutesNo real files are changed
-
-
-
Show hint
-
-
-
+
-
-
motion-perception
HEAD → main
-
-
-
-
-
-
The merge needs a decision
Write the intended final contents, stage the resolution, then commit. In real code, remove the markers and run the analysis/tests too.
-
-
-
-
-
01 Working files
What you have saved
-
02 Staged / index
What the commit will record
-
03 HEAD commit
The current branch tip
-
-
EDIT WORKING FILES
-
-
+
+
+
+
+
+
+
+
+ Show command hint
+
+
+
-
Unstaged changes git diff
Staged changes git diff --staged
-
-
-
-
Commit graph
Edges connect parents. Labels are branch pointers. Select a commit below to inspect its snapshot.
-
-
-Simulated server · origin
-
Pull request
Read the diff before review. New source or target commits require another review in this workflow. A server merge does not move local main.
-
+
+
+
+
motion-perception
+
+
+
+
+
+
+
+
+
+
+
+
Use ↑ and ↓ for command history. Enter git help for supported commands.
+
+
+
+
+
+
+
+
+
Resolve the merge conflict
+
+
+
+
+
Working files
+
+
+
+
+
+
+
+
Unstaged
+
Working edits you can stage.
+
No unstaged changes.
+
+
+
+
Staged
+
Changes the next commit will record.
+
No staged changes.
+
+
+
+
+ Undo a commit
+
Revert creates a new commit that reverses the latest commit.
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Commit graph
+
+
+ Inspect a commit snapshot
+
+
+
+
+
+
+
+
+
Branch tips
+
+
Your repository
+
Server · origin
+
+
+
+
+
+
+
+
+
+
Pull request
+
+
+
+
Proposed changes
+
+
+
+
+
+
+
+ Try a change from a labmate
Add a plot color commit to server main. See what happens to your local branch and to any current review.
+
-
-
TerminalSIMULATED
-
REPOSITORY STATUS
-
-
-
-
-
Buttons and commands use the same model. This terminal does not execute a shell.
-
-
```
About this simulation
-The model has two teaching files, up to five local branches, and 50 commits. Switching branches requires a clean working tree here; real Git can carry non-conflicting edits. Diffs compare modeled settings, rather than whole files. `MM` indicates both staged and later unstaged changes; `UU` indicates an unresolved merge entry. Changing missions resets the simulated repository. Use [the real Git lab](git-lab.qmd) to practice in a terminal.
+Practice with two synthetic files in your browser. Each mission has its own repository for the current visit. Reloading the page starts a new visit. The model supports up to five local branches and 50 commits and shows just the setting changed in each diff. For a real repository, open [the local Git lab](git-lab.qmd).
-## Stuck? Read a worked route, then explain each move
+## Worked routes
-Mission 1 · one decision per commit
+Stage selectively
-Edit the rule to 0.50 and plot to purple. Run `git add config/analysis.toml`, compare `git diff --staged` with `git diff`, then `git commit -m "Compare a 0.50 s RT minimum"`. The commit contains the rule; purple remains only in working files. Try changing the rule after staging to see `MM`.
+Save the rule at 0.50 s and the plot color as purple. Stage `config/analysis.toml` and compare both diffs. Commit the rule with a message explaining the change. The plot stays under Unstaged. Try editing the rule again after staging it and check the two columns of `git status -sb`.
-Mission 2 · shared base, independent changes
+Merge independent work
-Create criteria at baseline; edit rule to 0.30, stage, commit. Switch main; edit plot purple, stage, commit. Merge criteria into main. The graph now has a merge with two parents because both branches advanced from c0. Each branch changed a different modeled file.
+Create and switch to `criteria` at `c0`. Save, stage, and commit a 0.30 s minimum RT. Switch to `main`, then save, stage, and commit the purple plot. Look for `c0` in the graph and merge `criteria` into `main`. The merge commit has two parents.
-Mission 3 · a resolution is a staged decision
+Resolve a conflict
-Create criteria; commit rule 0.30. Switch main; commit rule 0.25. Merge criteria. Inspect both versions and choose a final rule. Write the resolution, select and stage `config/analysis.toml`, then commit with a message such as "Resolve RT policy conflict after review". The model checks that resolution was staged even if you choose main's original value.
+The mission starts with `criteria` at 0.30 s and `main` at 0.25 s. Find their shared ancestor `c0` and merge `criteria` into `main`. Compare both values, save the intended resolution, stage `config/analysis.toml`, and commit. Staging is required even if you keep the 0.25 s value already on `main`.
-Mission 4 · local history and server history
+Share and review
-Create criteria; change, stage, commit the rule; push criteria. Open the remote panel, open a PR, read its diff, record review, and merge. Switch local main, inspect its older tip, then pull --ff-only. For an extra challenge, let the labmate commit after review. Inspect why the merge now refuses until the new tips are reviewed.
+You start on `criteria` with a local commit. Run `git push -u origin criteria`, then open the pull request. Read the proposed changes, record your review, and merge on the server. Compare local and server `main`, switch to local `main`, and run `git pull --ff-only`. To see when a review goes stale, add a labmate commit on the server after you record your review.
-Mission 5 · undo different kinds of changes
+Recover a change
-Edit and stage the rule; `git restore --staged config/analysis.toml` removes it from the index but preserves the working edit. Stage again and commit. `git revert HEAD` creates an inverse commit; the original remains in the graph. In this bounded model, revert supports only the latest single-parent commit.
+Save a new minimum RT and stage it. Run `git restore --staged config/analysis.toml`. Inspect the unstaged edit, then stage it again and commit. Run `git revert HEAD` and find both commits in Branches.
## Command reference
-| Command | Question it answers or action it takes |
+| Command | What it does here |
| --- | --- |
-| `git status` | Which branch, staged files, and unstaged files? |
-| `git diff` / `git diff --staged` | Working versus index / index versus HEAD |
-| `git add PATH` / `git add .` | Copy selected current working versions into the index |
-| `git commit -m "Message"` | Record the index and move the current branch |
-| `git switch -c criteria` / `git switch main` | Create and switch / switch an existing branch |
-| `git merge criteria` / `git merge --abort` | Integrate into current branch / abandon unresolved merge |
-| `git log --oneline --graph --all` | Inspect locally known history (console uses parent lists) |
-| `git push -u origin criteria` | Share commits and update the server branch |
-| `git fetch origin` | Update local knowledge of server pointers |
-| `git pull --ff-only` | Fetch, then advance current branch if history permits |
-| `git restore --staged PATH` | Unstage without discarding working edits |
-| `git restore PATH` | Discard unstaged changes by restoring from the index |
-| `git revert HEAD` | Add an inverse commit; preserve history |
-
-Now complete [the real Git lab](git-lab.qmd). Close the command reference and explain, from memory, why committing, pushing, and opening a PR are three separate actions. Return in two days using [the practice plan](practice.qmd).
+| `git status` / `git status -sb` | Shows staged, unstaged, and unmerged files. |
+| `git diff -- PATH` / `git diff --staged -- PATH` | Shows unstaged or staged changes. Omit the path for all changed files. `--cached` also means staged. |
+| `git add PATH` / `git add .` | Stages the saved working versions. |
+| `git commit -m "Message"` | Records the staging area as a commit. |
+| `git branch` / `git switch -c criteria` / `git switch main` | Lists branches, creates and switches, or switches to an existing branch. |
+| `git merge criteria` / `git merge --abort` | Merges into the current branch or cancels an unresolved merge. |
+| `git log --oneline --graph --all` | Lists locally known commits and their parents. |
+| `git push -u origin criteria` | Pushes a branch and sets its upstream. After that, `git push` uses the upstream. |
+| `git fetch origin` / `git pull --ff-only` | Updates remote-tracking references. Pull also advances the current branch when it can fast-forward. |
+| `git restore --staged PATH` / `git restore PATH` | Unstages an edit or discards the unstaged edit. |
+| `git revert HEAD` | Adds a commit that reverses the latest single-parent commit. |
+
+Now try [the real Git lab](git-lab.qmd) with the workshop project.
diff --git a/site/modules/05-git.qmd b/site/modules/05-git.qmd
index 6d841f2..110aa41 100644
--- a/site/modules/05-git.qmd
+++ b/site/modules/05-git.qmd
@@ -42,12 +42,12 @@ git log --oneline --graph --all
## Practice with five connected missions
-[Open the Git practice room](../git-playground.qmd) to inspect working files, the index, HEAD, commit parents, local branches, server branches, and remote-tracking pointers. Use buttons or a bounded command console. Each mission checks the repository state you produced and includes a hint, worked route, and explanation.
+[Open the Git practice room](../git-playground.qmd) for a goal and a checklist that updates as you work. Use the controls next to each file or open the Terminal to type Git commands. Each mission includes command hints and a worked route.
1. **Stage selectively:** commit a 0.50 s rule while leaving a purple plot unstaged. Change a staged file again and explain `MM`.
2. **Merge independent work:** develop a rule on criteria and a plot on main. Identify the common ancestor before merging.
-3. **Resolve deliberately:** make conflicting rules, write a resolution, stage the file, and commit. Choosing main's value still requires staging the resolution.
-4. **Review and synchronize:** push a feature, review and merge a simulated PR, then fetch/pull locally. Observe how a new server commit invalidates review.
+3. **Resolve deliberately:** merge two prepared branches with conflicting rules. Save a resolution, stage the file, and commit. Choosing main's value still requires staging the resolution.
+4. **Review and synchronize:** push the prepared feature commit, review and merge a simulated PR, then update local main. Observe how a new server commit invalidates review.
5. **Recover:** unstage without losing edits, then undo a committed change with a new inverse commit.
This simulation executes no real Git commands. Its teaching IDs such as `c0` are not hashes. It models two files, five local branches, and 50 commits; some operations are deliberately narrower than Git. Practice the same decisions in [the real Git lab](../git-lab.qmd).
@@ -131,7 +131,7 @@ Use mission 3 in the [practice room](../git-playground.html?mission=conflict). B
HintCreating a branch does not create a commit. Look for the last node both branch histories can reach.Reveal solution and explanation
-With a fresh sandbox, both branches start at `c0`. Criteria's first commit is `c1`; main's is `c2`. They share `c0`. Both changed the rule from 0.20 to different values, so the merge needs a decision. Resolving creates `c3` with parents `c2` and `c1`. Changing the plot only on main and the rule only on criteria allows a clean three-way merge in this model.
+The sandbox starts with `criteria` at `c1` and `main` at `c2`. They share `c0`. Both changed the rule from 0.20 to different values, so the merge needs a decision. Resolving creates `c3` with parents `c2` and `c1`. Changing the plot only on main and the rule only on criteria allows a clean three-way merge in this model.
:::
diff --git a/tests/git-model.test.js b/tests/git-model.test.js
index de03b0a..9bfc144 100644
--- a/tests/git-model.test.js
+++ b/tests/git-model.test.js
@@ -17,9 +17,33 @@ test('branch creation moves HEAD without making a commit', () => {
assert.equal(m.current,'criteria'); assert.equal(m.commits.length,1);
assert.equal(m.branches.criteria,m.branches.main);
});
-test('branch and switch require clean work in this bounded model', () => {
- const m = new GitModel(); m.edit('rule'); assert.throws(() => m.branch(), /Commit/);
- m.stage(); m.commit(); m.branch(); m.edit('plot'); assert.throws(() => m.switchBranch(), /Commit/);
+test('branch creation and switching preserve staged and later unstaged edits', () => {
+ const m = new GitModel();
+ m.branch('plot-theme');
+ save(m, 'plot');
+ m.switchBranch('main');
+ m.setFile('rule', '0.30');
+ m.stage(['rule']);
+ m.setFile('rule', '0.50');
+ m.branch();
+ assert.equal(m.current, 'criteria');
+ assert.deepEqual([m.index.rule, m.working.rule], ['0.30', '0.50']);
+ m.switchBranch('plot-theme');
+ assert.deepEqual([m.index.rule, m.working.rule, m.working.plot], ['0.30', '0.50', 'purple']);
+});
+
+test('switch identifies overlapping paths and leaves all snapshots intact', () => {
+ const m = new GitModel();
+ m.branch();
+ save(m, 'rule');
+ m.switchBranch('main');
+ m.setFile('rule', '0.50');
+ m.stage(['rule']);
+ m.setFile('plot', 'purple');
+ assert.throws(() => m.switchBranch('criteria'), /config\/analysis\.toml/);
+ assert.equal(m.current, 'main');
+ assert.deepEqual(m.staged, ['rule']);
+ assert.deepEqual(m.unstaged, ['plot']);
});
test('fast-forward advances main without inventing a merge commit', () => {
const m = new GitModel(); m.branch(); save(m,'rule'); m.switchBranch();
@@ -37,7 +61,7 @@ test('conflicting edits stop branch advancement until resolved', () => {
const m = new GitModel(); m.branch(); save(m,'rule'); m.switchBranch(); save(m,'rule');
const oldHead=m.head.id; assert.match(m.merge(), /Merge stopped/);
assert.equal(m.head.id,oldHead); assert.equal(m.commits.length,3);
- assert.throws(() => m.commit(), /Resolve or abort/);
+ assert.throws(() => m.commit(), /Resolve.*stage/);
m.resolve('0.25'); assert.equal(m.head.snapshot.rule,'0.25');
assert.equal(m.head.parents.length,2); assert.equal(m.conflict,null);
});
diff --git a/tests/git-workflow.test.js b/tests/git-workflow.test.js
index 45d8805..093b4ab 100644
--- a/tests/git-workflow.test.js
+++ b/tests/git-workflow.test.js
@@ -1,17 +1,20 @@
import {test} from 'node:test';
import assert from 'node:assert/strict';
import {GitModel} from '../site/assets/git-model.js';
-import {executeCommand as run,status,diff,missions} from '../site/assets/git-commands.js';
+import {executeCommand as run,diff} from '../site/assets/git-commands.js';
+import {missions, missionProgress, startMission, runMissionAction} from '../site/assets/git-missions.js';
+const lesson = id => startMission(missions.find(mission => mission.id === id));
+const act = (session, command) => runMissionAction(session, repo => run(repo, command));
const save=(m,key,value)=>{m.setFile(key,value);m.stage([key]);m.commit(`Update ${key}`);};
const feature=()=>{const m=new GitModel();m.branch('criteria');save(m,'rule','0.30');return m;};
const conflict=()=>{const m=feature();m.switchBranch('main');save(m,'rule','0.25');m.merge('criteria');return m;};
test('selective stage isolates scientific policy from cosmetic working edits',()=>{
- const m=new GitModel();m.setFile('rule','.50');m.setFile('plot','purple');run(m,'git add config/analysis.toml');
+ const session=lesson('staging'),m=session.repo;m.setFile('rule','.50');m.setFile('plot','purple');run(m,'git add config/analysis.toml');
assert.match(diff(m,true),/0.50/);assert.doesNotMatch(diff(m,true),/purple/);assert.match(diff(m),/purple/);
- run(m,'git commit -m "Compare RT policy"');assert(missions[0].check(m));assert.equal(m.remote.main,'c0');
+ run(m,'git commit -m "Compare RT policy"');assert(missionProgress(session).complete);assert.equal(m.remote.main,'c0');
});
test('later edits to a staged file show MM and preserve the earlier staged value',()=>{
- const m=new GitModel();m.setFile('rule','.30');m.stage(['rule']);m.setFile('rule','.50');assert.match(status(m),/MM config/);
+ const m=new GitModel();m.setFile('rule','.30');m.stage(['rule']);m.setFile('rule','.50');assert.match(run(m,'git status --short'),/MM config/);
m.commit();assert.equal(m.head.snapshot.rule,'0.30');assert.equal(m.working.rule,'0.50');
});
test('unstage preserves edits; discard restores index rather than HEAD',()=>{
@@ -20,11 +23,11 @@ test('unstage preserves edits; discard restores index rather than HEAD',()=>{
m.discard('rule');assert.equal(m.working.rule,'0.20');
});
test('a resolution choosing ours must still be explicitly staged',()=>{
- const m=conflict(),before=m.head.id;m.resolveWorking({rule:'0.25'});assert.throws(()=>m.commit(),/staged/);assert.equal(m.head.id,before);
- m.stage(['plot']);assert.throws(()=>m.commit(),/staged/);m.stage(['rule']);m.commit('Resolve RT conflict');assert(missions[2].check(m));
+ const session=lesson('conflict'),m=session.repo;m.merge('criteria');const before=m.head.id;m.resolveWorking({rule:'0.25'});assert.throws(()=>m.commit(),/stage/);assert.equal(m.head.id,before);
+ m.stage(['plot']);assert.throws(()=>m.commit(),/stage/);m.stage(['rule']);m.commit('Keep the existing threshold');assert(missionProgress(session).complete);
});
test('changing the resolution after staging makes another stage necessary',()=>{
- const m=conflict();m.resolveWorking({rule:'0.30'});m.stage(['rule']);m.resolveWorking({rule:'0.25'});assert.throws(()=>m.commit(),/staged/);
+ const m=conflict();m.resolveWorking({rule:'0.30'});m.stage(['rule']);m.resolveWorking({rule:'0.25'});assert.throws(()=>m.commit(),/stage/);
m.stage(['rule']);m.commit();assert.equal(m.head.snapshot.rule,'0.25');
});
test('named branches merge into the current branch without moving others',()=>{
@@ -41,30 +44,150 @@ test('divergent histories reject push and fast-forward pull without losing work'
assert.equal(m.head.id,local);assert.equal(m.working.rule,'0.30');assert.equal(m.tracking.main,m.remote.main);
});
test('a PR requires a pushed feature and explicit review',()=>{
- const m=feature();assert.throws(()=>m.openPR(),/Push/);m.push();m.openPR();assert.throws(()=>m.mergePR(),/Review/);m.reviewPR();m.mergePR();
- assert.equal(m.branches.main,'c0');assert.equal(m.tracking.main,'c0');assert.notEqual(m.remote.main,'c0');m.switchBranch('main');m.pull();assert(missions[3].check(m));
+ const session=lesson('remote'),m=session.repo;assert.throws(()=>m.openPR(),/Push/);run(m,'git push -u origin criteria');m.openPR();assert.throws(()=>m.mergePR(),/Review/);m.reviewPR();m.mergePR();
+ assert.equal(m.branches.main,'c0');assert.equal(m.tracking.main,'c0');assert.notEqual(m.remote.main,'c0');m.switchBranch('main');m.pull();assert(missionProgress(session).complete);
});
test('a new source push invalidates the reviewed source tip',()=>{
- const m=feature();m.push();m.openPR();m.reviewPR();save(m,'rule','.50');m.push();assert.throws(()=>m.mergePR(),/stale/);
+ const m=feature();run(m,'git push -u origin criteria');m.openPR();m.reviewPR();save(m,'rule','.50');m.push();assert.throws(()=>m.mergePR(),/stale/);
m.reviewPR();m.mergePR();assert.equal(m.commits.find(c=>c.id===m.remote.main).snapshot.rule,'0.50');
});
test('a new target commit invalidates review and can combine independent edits',()=>{
- const m=feature();m.push();m.openPR();m.reviewPR();m.colleague();assert.throws(()=>m.mergePR(),/stale/);m.reviewPR();m.mergePR();
+ const m=feature();run(m,'git push -u origin criteria');m.openPR();m.reviewPR();m.colleague();assert.throws(()=>m.mergePR(),/stale/);m.reviewPR();m.mergePR();
assert.deepEqual(m.commits.find(c=>c.id===m.remote.main).snapshot,{rule:'0.30',plot:'orange'});
});
test('PR conflicts refuse server merge without moving remote main',()=>{
- const m=feature();m.push();m.openPR();m.colleague('rule','0.25');m.reviewPR();const tip=m.remote.main;
+ const m=feature();run(m,'git push -u origin criteria');m.openPR();m.colleague('rule','0.25');m.reviewPR();const tip=m.remote.main;
assert.throws(()=>m.mergePR(),/conflict/);assert.equal(m.remote.main,tip);assert.equal(m.pullRequest.merged,false);
});
-test('revert preserves original history and recovery mission is earned',()=>{
- const m=new GitModel(),events=[];m.setFile('rule','.50');m.stage();events.push('git restore --staged config/analysis.toml');run(m,events[0]);
- assert.equal(m.working.rule,'0.50');m.stage();m.commit('Alternative policy');const original=m.head.id;run(m,'git revert HEAD');
- assert.equal(m.head.parents[0],original);assert.equal(m.commits.length,3);assert(missions[4].check(m,events));
+test('revert preserves original history and earns recovery after a real unstage', () => {
+ const session=lesson('recovery'),m=session.repo;
+ m.setFile('rule','.50');
+ act(session,'git add config/analysis.toml');
+ act(session,'git restore --staged -- config/analysis.toml');
+ assert.equal(m.working.rule,'0.50');
+ assert.equal(missionProgress(session).next.label,'Stage it again');
+ act(session,'git add .');
+ act(session,'git commit -m "Alternative policy"');
+ const original=m.head.id;
+ act(session,'git revert HEAD');
+ assert.equal(m.head.reverts,original);
+ assert.equal(m.commits.length,3);
+ assert(missionProgress(session).complete);
+});
+
+test('recovery rejects no-op unstaging, failed commands and a message that only says revert', () => {
+ const session=lesson('recovery'),m=session.repo;
+ m.setFile('rule','.50');
+ act(session,'git restore --staged config/analysis.toml');
+ act(session,'git add .');
+ assert.throws(()=>act(session,'git restore --staged missing.toml'), /Unknown path/);
+ act(session,'git restore --staged src/experiment/plotting.py');
+ assert.equal(missionProgress(session).next.label,'Unstage and inspect');
+ act(session,'git commit -m "Revert HEAD"');
+ act(session,'git revert HEAD');
+ assert.equal(session.recovery,null);
+ assert.equal(missionProgress(session).complete,false);
});
test('supported command parsing handles quoted messages and refuses shell syntax',()=>{
const m=new GitModel();m.setFile('rule','.30');run(m,'git add config/analysis.toml');run(m,'git commit -m "Compare an alternative RT rule"');assert.equal(m.head.message,'Compare an alternative RT rule');
for(const command of ['rm -rf anything','git status; echo bad','git add private.csv','git push --force','git pull','git reset --hard'])assert.throws(()=>run(m,command));
});
test('mission 2 checks actual merge state rather than a sequence of clicks',()=>{
- const m=feature();assert.equal(missions[1].check(m),false);m.switchBranch('main');save(m,'plot','purple');m.merge();assert(missions[1].check(m));
+ const session=lesson('branches'),m=session.repo;
+ run(m,'git checkout -b feature/rt-policy');save(m,'rule','0.30');
+ assert.equal(missionProgress(session).complete,false);m.switchBranch('main');save(m,'plot','purple');
+ m.merge('feature/rt-policy');assert(missionProgress(session).complete);
+});
+
+test('short status and diff options match the staged and unstaged file versions', () => {
+ const m=new GitModel();
+ assert.equal(run(m,'git status --short'),'');
+ assert.equal(run(m,'git status -sb'),'## main...origin/main');
+ m.setFile('rule','0.30');
+ run(m,'git add -- config/analysis.toml');
+ m.setFile('rule','0.50');
+ m.setFile('plot','orange');
+ assert.equal(run(m,'git status -sb'), '## main...origin/main\nMM config/analysis.toml\n M src/experiment/plotting.py');
+ assert.match(run(m,'git diff --cached -- config/analysis.toml'), /min_rt_s = 0\.30/);
+ assert.match(run(m,'git diff config/analysis.toml'), /min_rt_s = 0\.50/);
+ assert.equal(run(m,'git diff --staged -- src/experiment/plotting.py'),'');
+ assert.throws(()=>run(m,'git add . missing.txt'),/Unknown path/);
+ assert.deepEqual(m.staged,['rule']);
+});
+
+test('branch without switch and checkout aliases share model state', () => {
+ const m = new GitModel();
+ assert.equal(run(m,'git branch'), '* main');
+ run(m,'git branch criteria');
+ assert.equal(m.current,'main');
+ run(m,'git checkout criteria');
+ assert.match(run(m,'git branch -a'), /\* criteria[\s\S]*remotes\/origin\/main/);
+ run(m,'git checkout -b feature/next');
+ assert.equal(m.current,'feature/next');
+});
+
+test('first push sets upstream only when asked and fetch remains distinct from pull', () => {
+ const m=feature();
+ assert.throws(()=>run(m,'git push'), /git push -u origin criteria/);
+ run(m,'git push origin criteria');
+ assert.throws(()=>run(m,'git push'), /No upstream/);
+ run(m,'git push --set-upstream origin criteria');
+ assert.match(run(m,'git status -sb'), /criteria\.\.\.origin\/criteria/);
+ save(m,'rule','0.50');
+ assert.match(run(m,'git status -sb'), /ahead 1/);
+ run(m,'git push');
+ assert.equal(m.remote.criteria,m.head.id);
+ m.switchBranch('main');
+ m.colleague();
+ run(m,'git fetch origin');
+ assert.match(run(m,'git status -sb'), /behind 1/);
+ run(m,'git pull --ff-only origin main');
+ assert.equal(m.head.id,m.remote.main);
+});
+
+test('an unresolved file blocks stage-all, then remains unmerged until explicitly staged', () => {
+ const m=feature();
+ m.setFile('plot','purple');m.stage();m.commit('Set purple');
+ m.switchBranch('main');
+ save(m,'rule','0.25');
+ m.merge('criteria');
+ assert.deepEqual(m.staged,['plot']);
+ assert.match(run(m,'git status --short'), /UU config\/analysis.toml/);
+ assert.throws(()=>run(m,'git add .'), /Write a resolution/);
+ m.resolveWorking({rule:'0.25'});
+ assert.match(run(m,'git status --short'), /UU config\/analysis.toml/);
+ run(m,'git add config/analysis.toml');
+ assert.doesNotMatch(run(m,'git status --short'), /UU/);
+ run(m,'git commit -m "Retain the minimum; include the figure update"');
+ assert.deepEqual(m.head.snapshot,{rule:'0.25',plot:'purple'});
+});
+
+test('pull request compares the source to the merge base and freezes its diff after merge', () => {
+ const session=lesson('remote'),m=session.repo;
+ run(m,'git push -u origin criteria');m.openPR();m.reviewPR();
+ m.colleague();
+ assert.equal(missionProgress(session).next.label,'Review the proposed diff');
+ assert.equal(m.prComparison.base,'c0');
+ assert.equal(m.prComparison.target,m.remote.main);
+ assert.deepEqual(m.prComparison.changes,[{key:'rule',before:'0.20',after:'0.50'}]);
+ m.reviewPR();
+ const reviewed=m.prComparison;
+ m.mergePR();
+ m.colleague('rule','0.70');
+ assert.deepEqual(m.prComparison,reviewed);
+});
+
+test('mission starting states and restart are independent', () => {
+ const staging=lesson('staging'),conflict=lesson('conflict'),remote=lesson('remote');
+ assert.equal(staging.repo.head.id,'c0');
+ assert.deepEqual(conflict.repo.branches,{main:'c2',criteria:'c1'});
+ assert.equal(remote.repo.current,'criteria');
+ assert.equal(remote.repo.remote.main,'c0');
+ assert.equal(remote.repo.head.id,'c1');
+ act(conflict,'git merge criteria');
+ act(conflict,'git merge --abort');
+ assert.equal(missionProgress(conflict).next.label,'Merge criteria into main');
+ staging.repo.setFile('rule','0.50');
+ assert.equal(lesson('staging').repo.working.rule,'0.20');
+ assert.equal(staging.repo.working.rule,'0.50');
});