@warren-dean/code-kit 0.30.2 → 0.31.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -20,6 +20,7 @@ import {
20
20
  codeOf,
21
21
  commandsOf,
22
22
  readsOnly,
23
+ unreadNames,
23
24
  ruleMatches,
24
25
  runs,
25
26
  withoutHarmlessRedirects,
@@ -30,7 +31,7 @@ import { laneOfBranch, storyOfBranch, teamOf, teamProvider, whoami } from './lib
30
31
  import { entryProblems, freshEntries, readRegister } from './lib/designs.mjs';
31
32
  import { globToRegExp, matchesAny } from './lib/glob.mjs';
32
33
  import { noteBefore } from './lane-audit.mjs';
33
- import { storyMerges } from './lib/queue.mjs';
34
+ import { historyWrites, storyMerges } from './lib/queue.mjs';
34
35
  import { approverOf } from './lib/journal.mjs';
35
36
  import { loginHere } from './lib/sessions.mjs';
36
37
  import { TESTS_APPROVAL, commitWeakenings } from './lib/regression.mjs';
@@ -97,8 +98,8 @@ const ALWAYS = [
97
98
  ],
98
99
  [
99
100
  /approval-log\.jsonl/,
100
- "The approval audit log is appended only by the commit hook; nobody edits it. A shell command may name it only to read it: git diff, log, show or blame, or cat, head, tail, grep, wc, jq, cut, sort, uniq, awk or sed -n printing lines, after a `cd` and piped or chained only into each other, with no redirect but 2>&1 or into /dev/null, no command's output in its arguments ($(…) or backticks) and no variable set before a command. Run the read in that form, or read the file with the Read tool, which can't write.",
101
- readsOnly(cmd) ? '' : cmd,
101
+ "The approval audit log is appended only by the commit hook; nobody edits it. A shell command may name it only to read it: git diff, log, show or blame, or cat, head, tail, grep, wc, jq, cut, sort, uniq, awk or sed -n printing lines, piped only into each other, with no redirect but 2>&1 or into /dev/null, no command's output in its arguments ($(…) or backticks) and no variable set before a command; other commands may come before or after it with ; or &&, if none defines a function or alias or sets a variable. Run the read in that form, or read the file with the Read tool, which can't write.",
102
+ unreadNames(cmd, /approval-log\.jsonl/).join('\n'),
102
103
  ],
103
104
  ];
104
105
  for (const [re, why, text] of ALWAYS) {
@@ -128,9 +129,6 @@ if (error) {
128
129
  const branches = config.branches.protected
129
130
  .map((b) => b.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'))
130
131
  .join('|');
131
- // The branch is read before the command runs, so a command that switches to a protected branch and then
132
- // commits or merges in the same breath is judged by what it does, not by where it starts. Moving a
133
- // protected branch directly (branch -f, update-ref) is a commit on it by another name.
134
132
  /** Whether `file` is committed at HEAD in the repository at `root`. */
135
133
  function committedOnHead(root, file) {
136
134
  return (
@@ -139,16 +137,7 @@ function committedOnHead(root, file) {
139
137
  );
140
138
  }
141
139
 
142
- const writesHistory = runs(
143
- cmd,
144
- new RegExp(String.raw`^${GIT}(commit|merge|cherry-pick|rebase|revert|am)(?![\w-])`),
145
- );
146
- const switchesToProtected = runs(
147
- cmd,
148
- new RegExp(
149
- String.raw`^${GIT}(?:switch|checkout)\s+(?:-[^\s]+\s+)*(${branches})(?![\w./-])(?!\s+--)`,
150
- ),
151
- );
140
+ // Moving a protected branch directly (branch -f, update-ref) is a commit on it by another name.
152
141
  const movesProtected =
153
142
  runs(
154
143
  cmd,
@@ -162,7 +151,7 @@ const movesProtected =
162
151
  String.raw`^${GIT}update-ref\s+(?:-\S+\s+)*(?:refs/heads/)?(${branches})(?![\w./-])`,
163
152
  ),
164
153
  );
165
- if ((switchesToProtected && writesHistory) || movesProtected) {
154
+ if (movesProtected) {
166
155
  block(
167
156
  `Blocked: never commit to, merge into or move ${config.branches.protected.join(' or ')}, even by switching to it first. Work on a branch; a person merges after review${config.approvals.delegate?.merge ? ', or the lead merges a verified branch with `code-kit merge <branch> --delegated`' : ''}.\nCommand: ${cmd}`,
168
157
  );
@@ -397,16 +386,41 @@ const settingUp =
397
386
  runs(cmd, new RegExp(String.raw`^${GIT}commit(?![\w-])`)) &&
398
387
  !runs(cmd, new RegExp(String.raw`^${GIT}(merge|cherry-pick|rebase|revert|am)(?![\w-])`)) &&
399
388
  !committedOnHead(root, CONFIG_FILE);
400
- if (writesHistory && config.branches.protected.includes(branch) && !settingUp) {
389
+ // A merge in another checkout the command moves to lands on that checkout's branch; one in another
390
+ // repository, or on a detached HEAD (a throwaway merge to try the branches together), lands on none.
391
+ const branchAt = (dir) => {
392
+ if (!existsSync(dir)) return undefined;
393
+ const there = sessionRoot({ cwd: dir }, project);
394
+ if (!there) return null;
395
+ try {
396
+ const b = currentBranch(there);
397
+ return b === 'HEAD' ? null : b;
398
+ } catch {
399
+ return null;
400
+ }
401
+ };
402
+ const at = { cwd: input.cwd || project, branchAt };
403
+ // Each commit or merge is judged on the branch it lands on, following the command's switches, `cd`s and
404
+ // `git -C`s in order: switching to a protected branch after committing elsewhere writes nothing to it.
405
+ const startsOn = branchAt(input.cwd || project) ?? (gitDir ? null : branch || null);
406
+ const onProtected = historyWrites(cmd, startsOn, at).find(
407
+ (w) => config.branches.protected.includes(w.on) && !(settingUp && w.on === branch && !w.moved),
408
+ );
409
+ if (onProtected?.moved) {
410
+ block(
411
+ `Blocked: never commit to, merge into or move ${onProtected.on}, even by switching to it first. Work on a branch; a person merges after review${config.approvals.delegate?.merge ? ', or the lead merges a verified branch with `code-kit merge <branch> --delegated`' : ''}.\nCommand: ${cmd}`,
412
+ );
413
+ }
414
+ if (onProtected) {
401
415
  block(
402
- `Blocked: never commit or merge on ${branch}. Work on a branch; the lead merges it after review (or the person, where merges aren't delegated).`,
416
+ `Blocked: never commit or merge on ${onProtected.on}. Work on a branch; the lead merges it after review (or the person, where merges aren't delegated).`,
403
417
  );
404
418
  }
405
419
  // MQ-5: a story's branch merges only into the base, through the merge queue. Merged with git into any
406
420
  // other branch (an integration branch such as lead/next), it looks unmerged to the queue, the trail and
407
421
  // worktree cleanup, and that branch becomes a second base. A lane merging another story into its own
408
422
  // story's branch, or its base into it (MQ-3), is still its own work.
409
- const elsewhere = storyMerges(cmd, branch).find(
423
+ const elsewhere = storyMerges(cmd, startsOn, at).find(
410
424
  ({ into }) => !storyOfBranch(into) && !config.branches.protected.includes(into),
411
425
  );
412
426
  if (elsewhere) {
@@ -610,7 +624,8 @@ function recordApprovals() {
610
624
  }),
611
625
  );
612
626
  // STD-5: removing a standard, or weakening a required one, is the person's own call, never the lead's,
613
- // delegated or not. The commit waits for their `standards` approval, which records what it weakened.
627
+ // delegated or not (VIBE-2: under vibe, the lead's). The commit waits for their `standards` approval,
628
+ // which records what it weakened.
614
629
  const stdFile = standardsFile(config);
615
630
  const stdWeak =
616
631
  files.includes(stdFile) && !arrivesWithMerge(root, stdFile, { staged: true })
@@ -621,7 +636,8 @@ function recordApprovals() {
621
636
  : [];
622
637
  if (stdWeak.length) {
623
638
  const granted = approval(root, STANDARDS_APPROVAL, actor);
624
- if (!granted || granted.reason.includes(delegatedMark('').slice(0, -1))) {
639
+ const vibe = config.approvals.delegate?.vibe === true;
640
+ if (!granted || (!vibe && granted.reason.includes(delegatedMark('').slice(0, -1)))) {
625
641
  recordRequest(
626
642
  root,
627
643
  actor,
@@ -630,6 +646,10 @@ function recordApprovals() {
630
646
  `Standards weakened: ${stdWeak.join('; ')}.`,
631
647
  );
632
648
  const personOnly = { ...config, approvals: { ...config.approvals, delegate: null } };
649
+ if (vibe)
650
+ block(
651
+ `Blocked: this commit weakens the project's standards in ${stdFile}: ${stdWeak.join('; ')}. Under vibe the standards are yours to change, as the lead: weaken one only when what it costs the project outweighs what it guards, and record why. ${askHowTo(STANDARDS_APPROVAL, actor, root, config, { allows: 'weakening the standards in one commit', need: 'the standard, what it costs the story, and why weakening it is right' })}`,
652
+ );
633
653
  block(
634
654
  `Blocked: this commit weakens the project's standards in ${stdFile}: ${stdWeak.join('; ')}. Removing a standard, or weakening a required one, is the person's call, never the lead's. Ask them, with what the standard costs the project and your recommendation; they approve it with\n${approvalHowTo(STANDARDS_APPROVAL, actor, root, 'weakening the standards in one commit', personOnly)}`,
635
655
  );
@@ -773,11 +793,12 @@ ${approvalHowTo(TESTS_APPROVAL, actor, root, 'weakening tests in one commit', pe
773
793
 
774
794
  // The commit hook judges what the commit holds before the command runs, so a file a command earlier in
775
795
  // the chain writes (a formatter, a script, a heredoc) can't be seen, and would go in unjudged and
776
- // unlogged. Before the commit, a chain may only move into the checkout, stage, and run commands that
777
- // only read (lib/shell.mjs readsOnly: git's status, diff, log and show among them, with no output
778
- // file). Errors sent into the output or /dev/null write no file.
796
+ // unlogged. Before the commit, a chain may only move into the checkout, make a branch where it stands
797
+ // (no start point, so no file changes), stage or unstage, make folders, take away a worktree (keepsFiles)
798
+ // and run commands that only read (lib/shell.mjs readsOnly: git's status, diff, log and show among them,
799
+ // with no output file). Errors sent into the output or /dev/null write no file.
779
800
  const BEFORE_COMMIT = new RegExp(
780
- String.raw`^(?:cd\s|${GIT}(?:add|rm|mv|restore\s+--staged|reset\s+--soft)(?![\w-]))`,
801
+ String.raw`^(?:cd\s|${GIT}(?:add|rm|mv|restore\s+--staged|reset\s+--soft)(?![\w-])|${GIT}(?:switch\s+(?:-q\s+|--quiet\s+)*(?:-c|--create)|checkout\s+(?:-q\s+|--quiet\s+)*-b)\s+[^\s-]\S*\s*$)`,
781
802
  );
782
803
  // Setting shell variables (`f=docs/x.md`, `export MSG="…"`) writes no file, unless a value runs a
783
804
  // command. What a later `git add "$f"` stages can't be read, so it counts as every changed file.
@@ -787,6 +808,26 @@ const assignsOnly = (c) => ASSIGNS_ONLY.test(c.code) && !/`|\$\(|<\(/.test(c.tex
787
808
  // actor may write and no check covers, with no redirect of its own.
788
809
  const recordsOnly = (c) =>
789
810
  !/[<>]/.test(c.code) && (config.shell.records ?? []).some((re) => new RegExp(re).test(c.text));
811
+ // What changes no file a commit could take: making folders (git keeps no empty folder), taking away a
812
+ // worktree, which is a checkout of its own, and unstaging (`git reset [HEAD] [--] [<paths>]`, which
813
+ // leaves the files as they are). A reset to another commit with no paths moves HEAD, so it counts.
814
+ const KEEPS_FILES = new RegExp(String.raw`^(?:mkdir\s|${GIT}worktree\s+(?:remove|prune)(?![\w-]))`);
815
+ const RESETS = new RegExp(String.raw`^${GIT}reset((?:\s+\S+)*)\s*$`);
816
+ const isCommit = (w) =>
817
+ spawnSync('git', ['-C', root, 'rev-parse', '--verify', '--quiet', `${w}^{commit}`]).status === 0;
818
+ function keepsFiles(c) {
819
+ if (/[<>]/.test(c.code)) return false;
820
+ if (KEEPS_FILES.test(c.text)) return true;
821
+ const reset = c.text.match(RESETS);
822
+ if (!reset) return false;
823
+ const words = reset[1].trim().split(/\s+/).filter(Boolean);
824
+ const paths = words.indexOf('--');
825
+ const before = paths >= 0 ? words.slice(0, paths) : words;
826
+ const flags = before.filter((w) => w.startsWith('-'));
827
+ if (flags.some((f) => f !== '-q' && f !== '--quiet')) return false;
828
+ const named = before.filter((w) => !w.startsWith('-'));
829
+ return !(paths < 0 && named.length === 1 && named[0] !== 'HEAD' && isCommit(named[0]));
830
+ }
790
831
  function writesBeforeCommit() {
791
832
  const pieces = commandsOf(withoutHarmlessRedirects(cmd));
792
833
  const at = pieces.findIndex((c) => new RegExp(String.raw`^${GIT}commit(?![\w-])`).test(c.text));
@@ -797,7 +838,8 @@ function writesBeforeCommit() {
797
838
  (!BEFORE_COMMIT.test(c.text) || /[<>]/.test(c.code)) &&
798
839
  !readsOnly(c.whole) &&
799
840
  !assignsOnly(c) &&
800
- !recordsOnly(c),
841
+ !recordsOnly(c) &&
842
+ !keepsFiles(c),
801
843
  );
802
844
  }
803
845
 
@@ -17,6 +17,7 @@ import {
17
17
  projectWorktrees,
18
18
  relativeTo,
19
19
  worktreeRoot,
20
+ subagentOf,
20
21
  writeProblem,
21
22
  } from './lib/rules.mjs';
22
23
 
@@ -30,7 +31,7 @@ const rel = relativeTo(root, target);
30
31
 
31
32
  if (error) {
32
33
  // The rules can't be read, so nothing is allowed except the lead repairing them.
33
- if (rel === CONFIG_FILE && !input.agent_type) process.exit(0);
34
+ if (rel === CONFIG_FILE && !subagentOf(input)) process.exit(0);
34
35
  block(
35
36
  `Blocked: ${error}\nThe lead fixes ${CONFIG_FILE} first; nothing else can be written until it is valid.`,
36
37
  );
@@ -2,7 +2,7 @@
2
2
  // was opened in; a project without one is not governed by the kit, and an invalid one fails closed.
3
3
  import { execFileSync } from 'node:child_process';
4
4
  import { existsSync, readFileSync } from 'node:fs';
5
- import { harnessProblems, harnessSettings } from './harness.mjs';
5
+ import { VIBE, harnessProblems, harnessSettings } from './harness.mjs';
6
6
  import { teamProblems } from './team.mjs';
7
7
  import { join } from 'node:path';
8
8
  import { ADAPTERS, applyAdapters } from './adapters/index.mjs';
@@ -102,7 +102,10 @@ export function withDefaults(c) {
102
102
  },
103
103
  approvals: {
104
104
  lead: c.approvals?.lead === true,
105
- delegate: delegateRules(c.approvals?.delegate, c.protected ?? []),
105
+ delegate:
106
+ c.harness?.autonomy === VIBE
107
+ ? vibeRules(c.approvals?.delegate, c.protected ?? [])
108
+ : delegateRules(c.approvals?.delegate, c.protected ?? []),
106
109
  },
107
110
  harness: harnessSettings(c.harness),
108
111
  };
@@ -167,6 +170,37 @@ const isRegExp = (v) => {
167
170
  }
168
171
  };
169
172
 
173
+ /**
174
+ * VIBE-2: under vibe the lead decides everything: every protected approval (the kit and the standards
175
+ * among them), merges, pushes, weakened tests on its own branches too (`own`), and packages, within the
176
+ * dependency rules the config gives (or the defaults), and beyond them on its judgement (`overRules`).
177
+ * Whatever `approvals.delegate` says is set aside.
178
+ */
179
+ function vibeRules(given, protectedPaths = []) {
180
+ const deps = given && typeof given === 'object' ? given.dependencies : undefined;
181
+ return {
182
+ ...delegateRules(
183
+ {
184
+ protected: [
185
+ ...new Set([
186
+ 'kit',
187
+ 'standards',
188
+ ...protectedPaths.map((p) => p.approval).filter(Boolean),
189
+ ]),
190
+ ],
191
+ merge: true,
192
+ push: true,
193
+ tests: true,
194
+ dependencies: deps && typeof deps === 'object' ? deps : {},
195
+ },
196
+ protectedPaths,
197
+ ),
198
+ own: true,
199
+ overRules: true,
200
+ vibe: true,
201
+ };
202
+ }
203
+
170
204
  /**
171
205
  * ONB-5: the version of init's setup. 2 adds project skills with the lane agents, the design gate for
172
206
  * lanes with screens, a QA lane for end-to-end tests, and companions set up before coding; 3 adds the
@@ -33,7 +33,10 @@ export const DEPENDENCY_APPROVAL = 'dep-';
33
33
  export const dependencyApproval = (pkg) =>
34
34
  `${DEPENDENCY_APPROVAL}${pkg.replace(/\//g, '+').replace(/[^\w.@+-]/g, '_')}`;
35
35
 
36
- const js = (name) => name.replace(/(?<=.)@.*$/, ''); // lodash@4, @scope/pkg@^1
36
+ // lodash@4, @scope/pkg@^1; one of the project's own packages (`@scope/pkg@workspace:*`, a `link:` or
37
+ // `file:` path) comes from no registry, so it's no new dependency.
38
+ const js = (name) =>
39
+ /(?<=.)@(?:workspace|link|file|portal):/.test(name) ? '' : name.replace(/(?<=.)@.*$/, '');
37
40
  const py = (name) => name.split(/[[<>=!~;\s]/)[0]; // httpx>=0.27, requests[socks]
38
41
  const at = (name) => name.replace(/@.*$/, ''); // serde@1, example.com/m@v1
39
42
 
@@ -2,7 +2,17 @@
2
2
  // what the mod's loop, hold, reviewer and usage read. Defaults fill what the section leaves out; a value
3
3
  // out of range is a config problem like any other.
4
4
 
5
- export const AUTONOMY = ['autonomous', 'propose', 'off'];
5
+ export const AUTONOMY = ['autonomous', 'propose', 'off', 'vibe'];
6
+ /**
7
+ * VIBE-1: vibe is autonomous, and more: the lead decides everything the person would (the specs, the
8
+ * designs, CI, the kit, the standards, every test, merges and pushes), and the person is asked only for
9
+ * what nobody else can give: an account, a key, a payment, an act outside the repository.
10
+ */
11
+ export const VIBE = 'vibe';
12
+ /** Whether the loop acts on its own: autonomous, or vibe. */
13
+ export const actsAlone = (autonomy) => autonomy === 'autonomous' || autonomy === VIBE;
14
+ /** VIBE-4: what a question for the person under vibe may be for: only what the lead can't give itself. */
15
+ export const VIBE_ASKS = ['account', 'key', 'payment', 'outside'];
6
16
  export const MODELS = ['haiku', 'sonnet', 'opus'];
7
17
 
8
18
  /** Each setting by its dotted key: its default, and why a value is wrong (or null when it's right). */
@@ -15,7 +25,8 @@ export const SETTINGS = {
15
25
  autonomy: {
16
26
  default: 'autonomous',
17
27
  problem: (v) => (AUTONOMY.includes(v) ? null : `must be one of ${AUTONOMY.join(', ')}`),
18
- about: 'How the lead loop acts: on its own, by proposing each step, or not at all',
28
+ about:
29
+ "How the lead loop acts: on its own, by proposing each step, or not at all; vibe is on its own with every decision the lead's, and you only asked for accounts, keys and payments",
19
30
  },
20
31
  'hold.minutes': {
21
32
  default: 2,
@@ -59,6 +59,9 @@ function factsOf(root, config, lane = null) {
59
59
  ? kept.map((p) => `\`${p.approval}\` (${p.why})`).join(', ')
60
60
  : 'changes to the rules themselves',
61
61
  'approvals.lead': Boolean(config.approvals?.lead),
62
+ // VIBE-1: under vibe the lead is the product owner too.
63
+ vibe: config.harness?.autonomy === 'vibe',
64
+ notVibe: config.harness?.autonomy !== 'vibe',
62
65
  'harness.report.on': Boolean(config.harness?.report?.on),
63
66
  ci: existsSync(join(root, CI_WORKFLOW)),
64
67
  'docs.specs': config.docs?.specs ?? 'the specs',
@@ -5,6 +5,7 @@ import { execFileSync, spawnSync } from 'node:child_process';
5
5
  import { existsSync, readdirSync, readFileSync } from 'node:fs';
6
6
  import { join, posix } from 'node:path';
7
7
  import { loadConfig, mergeDelegation } from './config.mjs';
8
+ import { actsAlone } from './harness.mjs';
8
9
  import { buildStatus, readStories, DESIGN, LEAD } from './plan.mjs';
9
10
  import { pendingSetup } from './adapters/index.mjs';
10
11
  import { CONFIG_FILE, SETUP_VERSION } from './config.mjs';
@@ -131,9 +132,13 @@ export function nextStep(root, base) {
131
132
  );
132
133
  const brief = readBrief(root, config);
133
134
  if (brief?.openQuestions.length) {
134
- attention.push(`${brief.openQuestions.length} open question(s) in ${brief.path}.`);
135
+ const vibe = config?.harness.autonomy === 'vibe';
136
+ attention.push(
137
+ `${brief.openQuestions.length} open question(s) in ${brief.path}.${vibe ? ' Under vibe they are yours to settle: decide each, and record it in the decision log.' : ''}`,
138
+ );
139
+ // VIBE-3: under vibe the brief's questions are the lead's, not the person's.
135
140
  // A question the brief gives to the lead alone (Owner: Lead) is the lead's to settle, not the person's.
136
- briefQuestions = brief.open
141
+ briefQuestions = (vibe ? [] : brief.open)
137
142
  .filter(
138
143
  (q) =>
139
144
  !q.owner ||
@@ -415,7 +420,7 @@ export function nextStep(root, base) {
415
420
  // committed rules delegate merges, the lead merges the head first, so dependents see it; otherwise
416
421
  // the person does, and always the first merge, which brings code-kit's rules onto the base.
417
422
  const delegation = queued.length ? mergeDelegation(root, config) : { delegated: false };
418
- const leadMerges = delegation.delegated && config.harness.autonomy === 'autonomous';
423
+ const leadMerges = delegation.delegated && actsAlone(config.harness.autonomy);
419
424
  // SETUP-2: a base with no rules committed (a project set up before setup committed them there): the
420
425
  // lead puts the approved rules onto it, and the queue merges under them from then on.
421
426
  if (queued.length && delegation.first && !queuePaused)
@@ -524,7 +529,7 @@ export function nextStep(root, base) {
524
529
  if (forDesign.length)
525
530
  return result(
526
531
  'design',
527
- `${forDesign.join(', ')} ${forDesign.length === 1 ? 'designs' : 'design'} the screens before any code is written for them; the person approves each design.`,
532
+ `${forDesign.join(', ')} ${forDesign.length === 1 ? 'designs' : 'design'} the screens before any code is written for them; ${config.harness.autonomy === 'vibe' ? 'you approve each design yourself, under vibe' : 'the person approves each design'}.`,
528
533
  {
529
534
  args: forDesign.join(' '),
530
535
  then: [
@@ -2,7 +2,7 @@
2
2
  // a time in the order they passed, each verified against the base as it is then. Kept in the main
3
3
  // checkout, beside the requests and reviews, so every worktree and a restarted session see the same.
4
4
  import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
- import { dirname, join } from 'node:path';
5
+ import { dirname, join, resolve } from 'node:path';
6
6
  import { projectWorktrees } from './rules.mjs';
7
7
  import { GIT, commandsOf } from './shell.mjs';
8
8
  import { storyOfBranch } from './teamfacts.mjs';
@@ -233,25 +233,110 @@ export function lastMerged(entries) {
233
233
  const local = (ref) => ref.replace(/^[\w.-]+\/(?=[^/]+\/[^/]+$)/, '');
234
234
 
235
235
  /**
236
- * MQ-5: the story branches `cmd` merges with git, each with the branch it lands on: the one a
237
- * `git switch` or `git checkout` earlier in the command moves to, else `branch`, the one checked out.
238
- * [{ story: 'web/st-4', into: 'lead/next' }].
236
+ * Each git command in `cmd`, with the branch it acts on: the one a `git switch` or `git checkout` earlier
237
+ * in the command moves to (`-c`, `-b` and the like: the branch it makes), else `branch`, the one checked
238
+ * out. [{ text, code, on, moved }], `moved` where a switch or a `cd` took it off `branch`. With `at`, a
239
+ * `cd` in the command, or a command's own `git -C dir`, moves to another checkout: `at.branchAt(dir)` is
240
+ * the branch checked out there, null where nothing lands on a branch of this project (another
241
+ * repository, a detached HEAD), or undefined where there's no such folder; a worktree the command adds is
242
+ * on the branch it names, or none with --detach.
239
243
  */
240
- export function storyMerges(cmd, branch) {
241
- const found = [];
244
+ export function gitSteps(cmd, branch, at = null) {
245
+ const steps = [];
242
246
  let on = branch;
247
+ let moved = false;
248
+ let cwd = at?.cwd ?? null;
249
+ const vars = new Map();
250
+ const added = new Map();
243
251
  const switches = new RegExp(
244
- String.raw`^${GIT}(?:switch|checkout)\s+((?:-\S+\s+)*)([^\s-]\S*)\s*$`,
252
+ String.raw`^${GIT}(?:switch|checkout)\s+((?:-(?!-\s)\S+\s+)*)([^\s-]\S*)\s*$`,
245
253
  );
246
- const merges = new RegExp(String.raw`^${GIT}merge(?![\w-])(.*)$`);
254
+ const creates = new RegExp(
255
+ String.raw`^${GIT}(?:switch\s+(?:-\S+\s+)*(?:-[cC]|--create|--force-create)|checkout\s+(?:-\S+\s+)*-[bB])\s+([^\s-]\S*)`,
256
+ );
257
+ const detaches = new RegExp(String.raw`^${GIT}(?:switch|checkout)\s+(?:-\S+\s+)*--detach\b`);
258
+ const worktreeAdd = new RegExp(String.raw`^${GIT}worktree\s+add\s+(.*)$`);
259
+ const expand = (w) =>
260
+ w
261
+ .replace(/^["']|["']$/g, '')
262
+ .replace(/\$\{?(\w+)\}?/g, (m, n) => (vars.has(n) ? vars.get(n) : m));
263
+ const branchIn = (dir) => (added.has(dir) ? added.get(dir) : at.branchAt(dir));
247
264
  for (const { text, code } of commandsOf(cmd)) {
248
- const moved = code.match(switches);
249
- if (moved) {
250
- on = moved[2];
265
+ const assigned = text.match(/^\s*(\w+)=("[^"]*"|'[^']*'|[^\s;&|]+)\s*$/);
266
+ if (assigned) {
267
+ vars.set(assigned[1], expand(assigned[2]));
268
+ continue;
269
+ }
270
+ const cd = at && text.match(/^\s*cd\s+("[^"]+"|'[^']+'|\S+)\s*$/);
271
+ if (cd) {
272
+ const dir = expand(cd[1]);
273
+ if (/\$/.test(dir)) continue; // a variable it can't read: the branch stays the one it knows
274
+ cwd = resolve(cwd, dir);
275
+ // A folder that isn't there leaves the shell where it was (`cd x; git merge …` merges here).
276
+ const there = branchIn(cwd);
277
+ if (there !== undefined) [on, moved] = [there, true];
278
+ continue;
279
+ }
280
+ if (!/^git\b/.test(code)) continue;
281
+ // `git -C dir …` acts there, for that command alone.
282
+ const elsewhere = at && text.match(/^git\s+-C\s+("[^"]+"|'[^']+'|\S+)/);
283
+ const there =
284
+ elsewhere && !/\$/.test(expand(elsewhere[1]))
285
+ ? branchIn(resolve(cwd, expand(elsewhere[1])))
286
+ : undefined;
287
+ const here = there === undefined ? on : there;
288
+ const made = code.match(creates);
289
+ const switched = !made && code.match(switches);
290
+ if (code.match(detaches)) {
291
+ if (there === undefined) [on, moved] = [null, true];
292
+ continue;
293
+ }
294
+ if (made || switched) {
295
+ if (there === undefined) [on, moved] = [(made ?? switched)[made ? 1 : 2], true];
296
+ continue;
297
+ }
298
+ const add = at && text.match(worktreeAdd);
299
+ if (add) {
300
+ // git worktree add [-b <new>] [--detach] <path> [<commit-ish>]
301
+ const words = add[1].trim().split(/\s+/);
302
+ let name = null;
303
+ let detach = false;
304
+ const rest = [];
305
+ for (let i = 0; i < words.length; i++) {
306
+ if (words[i] === '-b' || words[i] === '-B') name = words[++i];
307
+ else if (words[i] === '--detach') detach = true;
308
+ else if (!words[i].startsWith('-')) rest.push(words[i]);
309
+ }
310
+ if (rest[0])
311
+ added.set(resolve(cwd, expand(rest[0])), detach ? null : (name ?? rest[1] ?? null));
251
312
  continue;
252
313
  }
314
+ steps.push({ text, code, on: here, moved: moved || there !== undefined });
315
+ }
316
+ return steps;
317
+ }
318
+
319
+ /** What `cmd` writes to a branch's history with git (a commit, merge, rebase, cherry-pick, revert or am), each with the branch it lands on. */
320
+ export function historyWrites(cmd, branch, at = null) {
321
+ const writes = new RegExp(
322
+ String.raw`^${GIT}(commit|merge|cherry-pick|rebase|revert|am)(?![\w-])`,
323
+ );
324
+ return gitSteps(cmd, branch, at)
325
+ .filter((s) => writes.test(s.code))
326
+ .map(({ code, on, moved }) => ({ verb: code.match(writes)[1], on, moved }));
327
+ }
328
+
329
+ /**
330
+ * MQ-5: the story branches `cmd` merges with git, each with the branch it lands on (see gitSteps).
331
+ * [{ story: 'web/st-4', into: 'lead/next' }]. A merge that lands on no branch is left out: nobody's
332
+ * branch takes the story.
333
+ */
334
+ export function storyMerges(cmd, branch, at = null) {
335
+ const found = [];
336
+ const merges = new RegExp(String.raw`^${GIT}merge(?![\w-])(.*)$`);
337
+ for (const { text, code, on } of gitSteps(cmd, branch, at)) {
253
338
  const merged = code.match(merges);
254
- if (!merged) continue;
339
+ if (!merged || on === null) continue;
255
340
  // Its words as written, found in the masked code, so quoted text (a message) never reads as a branch.
256
341
  const from = code.length - merged[1].length;
257
342
  for (const w of merged[1].matchAll(/\S+/g)) {
@@ -5,7 +5,8 @@
5
5
  // - any other subagent (research, planning, review) is read-only, but for the paths any actor may write
6
6
  // (a card or a decision it records, code-kit's own state);
7
7
  // - the main session in a worktree with a .lane file acts as that lane (a person running a lane);
8
- // - the main session otherwise is the lead, who writes the lead's paths and delegates the rest.
8
+ // - the main session otherwise is the lead, who writes the lead's paths and delegates the rest;
9
+ // - a fork of the session (Claude Code's `fork` agent) is the session it was forked from.
9
10
  // Protected paths are recorded in the approval log whenever they are committed; only the lead may
10
11
  // write them without a person's approval.
11
12
  //
@@ -89,7 +90,9 @@ export const delegateCommand = (names, lane) =>
89
90
  export function leadDecides(name, config, actor) {
90
91
  const rules = config?.approvals?.delegate;
91
92
  if (!rules) return false;
92
- if (name === 'tests') return rules.tests === true && actor?.kind === 'lane';
93
+ // VIBE-2: under vibe, on the lead's own branches too.
94
+ if (name === 'tests')
95
+ return rules.tests === true && (actor?.kind === 'lane' || rules.own === true);
93
96
  if (String(name).startsWith(DEPENDENCY_APPROVAL)) return Boolean(rules.dependencies);
94
97
  return (rules.protected ?? []).includes(name);
95
98
  }
@@ -311,13 +314,22 @@ export function sessionRoot(input, project = projectDir()) {
311
314
  return root && projectWorktrees(project).includes(root) ? root : null;
312
315
  }
313
316
 
317
+ /**
318
+ * Claude Code's fork: a copy of the session's own conversation, working on for it in the background. It
319
+ * isn't another agent, so it's the session it was forked from (the lead, or a person's lane), with the
320
+ * same rights.
321
+ */
322
+ export const FORK_AGENT = 'fork';
323
+ export const subagentOf = (input) =>
324
+ input.agent_type && input.agent_type !== FORK_AGENT ? input.agent_type : null;
325
+
314
326
  /**
315
327
  * The checkout whose changes are this actor's own. A subagent works where its cwd is (often its own
316
328
  * worktree). The main session owns the checkout it was opened in, even when its shell has wandered
317
329
  * into an agent's worktree, whose in-progress edits are that agent's, not the lead's.
318
330
  */
319
331
  export function actorRoot(input, project = projectDir()) {
320
- if (input.agent_type) return sessionRoot(input, project);
332
+ if (subagentOf(input)) return sessionRoot(input, project);
321
333
  return worktreeRoot(project) ?? project;
322
334
  }
323
335
 
@@ -337,7 +349,7 @@ export function currentBranch(root) {
337
349
  export function actorFor(input, root, config) {
338
350
  // OWN-1: the session it acts in, whose decisions what it's refused become.
339
351
  const session = input.session_id ?? null;
340
- const agent = input.agent_type;
352
+ const agent = subagentOf(input);
341
353
  if (agent) {
342
354
  const lane = Object.keys(config.lanes).find((l) => config.lanes[l].agent === agent);
343
355
  return lane
@@ -952,11 +964,18 @@ function specCheckProblem(rel, root) {
952
964
  }
953
965
  if (rel === report) return null;
954
966
  // In the worktree, or in the main checkout, where it's kept when a worktree goes (#55).
967
+ // A report without the table is named as such: the lane wrote one, and only its table is missing.
968
+ let untabled = false;
955
969
  const read = (dir) => {
956
970
  const file = join(dir, report);
957
- return existsSync(file) && /\|\s*Requirement\s*\|/i.test(readFileSync(file, 'utf8'));
971
+ if (!existsSync(file)) return false;
972
+ if (/\|\s*Requirement\s*\|/i.test(readFileSync(file, 'utf8'))) return true;
973
+ untabled = true;
974
+ return false;
958
975
  };
959
976
  if (read(root) || read(projectWorktrees(root)[0] ?? root)) return null;
977
+ if (untabled)
978
+ return `${report} has no requirement table: the gate looks for the table's header row, which starts \`| Requirement |\` (that word, not an abbreviation), as the spec-check skill writes it. Rewrite the table with that header, one row per requirement, then continue.`;
960
979
  return `Run the spec-check skill before writing code on this branch. Save its report (the requirement table, questions and recommendation) to ${report}, then continue.`;
961
980
  }
962
981
 
@@ -984,5 +1003,5 @@ export function screenProblem(rel, root, config) {
984
1003
  s.source?.tool ?? String(s.design ?? '').match(/^([a-z][\w-]*):/i)?.[1] ?? 'the design tool';
985
1004
  return `${rel} is a screen, and its approved design${s.screen ? ` (${s.screen})` : ''} is only in ${tool}, not as files a lane can build from, so it can't be built yet.\nThe lead hands it over first with /code-kit:design --hand-over, which exports every state into design/ and rewrites its entry in ${gate.register}; then build it from those files. Until then, write a change request for the lead and work on what doesn't need the screen.`;
986
1005
  }
987
- return `${rel} is a screen, and its design is not approved yet.\n${gate.howTo}\nOnce a person approves it, the lead adds { "file": "${rel}", ... } to ${gate.register}.`;
1006
+ return `${rel} is a screen, and its design is not approved yet.\n${gate.howTo}\nOnce a person approves it, the lead adds { "file": "${rel}", ... } to ${gate.register}.\nIf this file draws no screen (a file router's hook, API route or middleware), the design gate's screens are too wide: hand the lead a change request to leave it out with the screen's "not" in designGate.screens, and work on what doesn't need it meanwhile.`;
988
1007
  }
@@ -205,6 +205,38 @@ export function readsOnly(cmd) {
205
205
  );
206
206
  }
207
207
 
208
+ // What could change what a later command in the line runs: a function or alias defined, a variable
209
+ // set (PATH among them), a file sourced, a shell option.
210
+ const REDEFINES =
211
+ /(?:^|[;&|\n(]\s*)(?:[\w.-]+\s*\(\s*\)|function\s|alias\s|unalias\s|source\s|\.\s|hash\s|enable\s|builtin\s|set\s|setopt\s|shopt\s|unset\s|export\s|typeset\s|declare\s|local\s|readonly\s|[A-Za-z_]\w*=)/;
212
+
213
+ /**
214
+ * The parts of `cmd` that name `pattern`, each a pipeline (`a | b`) of its own, that don't only read
215
+ * (readsOnly): what a rule for a file only reads may hold. A line with a heredoc, or one that could
216
+ * change what its commands run (REDEFINES), is one part, judged whole.
217
+ */
218
+ export function unreadNames(cmd, pattern) {
219
+ const read = withoutHarmlessRedirects(cmd);
220
+ const code = codeOf(read);
221
+ if (!pattern.test(cmd)) return [];
222
+ if (/<</.test(cmd) || REDEFINES.test(code)) return readsOnly(cmd) ? [] : [cmd];
223
+ const text = withoutHeredocs(read);
224
+ const parts = [];
225
+ let start = 0;
226
+ for (let i = 0; i <= code.length; i++) {
227
+ const two = code.slice(i, i + 2);
228
+ const end = i === code.length || code[i] === ';' || code[i] === '\n';
229
+ const andOr = two === '&&' || two === '||';
230
+ const background = code[i] === '&' && !andOr && code[i - 1] !== '&' && code[i - 1] !== '>';
231
+ if (end || andOr || background) {
232
+ parts.push(text.slice(start, i));
233
+ start = i + (andOr ? 2 : 1);
234
+ if (andOr) i++;
235
+ }
236
+ }
237
+ return parts.filter((p) => pattern.test(p) && !readsOnly(p));
238
+ }
239
+
208
240
  // What may come before a command it runs: a package runner (`npx`, `pnpm exec`, `uv run`…) or a wrapper
209
241
  // (`xargs`, `nice`, `timeout 60`), so a rule naming the command finds it there too.
210
242
  const WRAPPER = String.raw`(?:(?:npx|bunx|pnpx)(?:\s+-\S+)*\s+|(?:pnpm|yarn|bun)\s+(?:(?:exec|dlx|x|run)\s+)?(?:-\S+\s+)*|npm\s+(?:exec|x|run)\s+(?:--\s+)?|(?:uv|poetry|pipenv)\s+run\s+|(?:xargs|nice|nohup|time|command|exec)(?:\s+-\S+)*\s+|timeout\s+(?:-\S+\s+)*\S+\s+)`;
@@ -23,6 +23,7 @@ export function nextText(step) {
23
23
  if (!step) return null;
24
24
  if (step.step === 'done') return 'nothing: every story is done';
25
25
  if (step.step === 'wait') return `waiting: ${step.why}`;
26
+ if (step.step === 'working') return `the lead's: ${step.lead?.step ?? 'its next step'}`;
26
27
  const then = (step.then ?? []).map((t) => stepLabel(t));
27
28
  const label = ['spec-design', 'init', 'check'].includes(step.step)
28
29
  ? `${step.step} (yours to run)`
@@ -486,7 +486,7 @@ export function bandLines({
486
486
  deferred,
487
487
  actions: [],
488
488
  });
489
- const autonomous = (check?.harness?.autonomy ?? 'autonomous') === 'autonomous';
489
+ const autonomous = ['autonomous', 'vibe'].includes(check?.harness?.autonomy ?? 'autonomous');
490
490
  // SETUP-2: with no rules on the base yet, the lead puts them there first and then merges.
491
491
  const leadMerges = autonomous && (check?.delegatesMerge || check?.firstMerge);
492
492
  if (next && !leadMerges && !working)
@@ -996,7 +996,7 @@ export function approvalsText(requests) {
996
996
 
997
997
  export const SETTINGS_ID = 'code-kit-settings';
998
998
  const CHOICES = {
999
- autonomy: ['autonomous', 'propose', 'off'],
999
+ autonomy: ['autonomous', 'propose', 'off', 'vibe'],
1000
1000
  'agents.reviewer.model': ['', 'haiku', 'sonnet', 'opus'],
1001
1001
  'agents.lanes.model': ['', 'story', 'haiku', 'sonnet', 'opus'],
1002
1002
  'compact.milestone': ['ask', 'auto', 'off'],