Skip to content

An open-source, faster Devin alternative

TypeScript

computer: work-tracking git hooks in the knowledge repository's clone

Igor Zalutski via Computer00b2d8d8247a
diff --git a/computer/hooks/knowledge/pre-push b/computer/hooks/knowledge/pre-push
new file mode 100755
index 00000000..a8a34bc0
--- /dev/null
+++ b/computer/hooks/knowledge/pre-push
@@ -0,0 +1,102 @@
+#!/bin/sh
+# opencomputer-knowledge-hook: installed by the computer's host in the clone of
+# the organization's knowledge repository (src/workspaces/knowledge-hooks.ts),
+# and replaced by it on every housekeeping pass: edits here do not last.
+#
+# Item numbers are unique. An item is a file `NN-slug.md` directly under
+# work/ or done/ (directories there are ignored), and its number, the leading
+# digits, is its identity. A push is refused when the tree it pushes to a
+# branch has more items with one number than the remote's head has: a push is
+# a compare-and-swap on that head, so this is a real uniqueness check, and
+# numbers already shared upstream (history) never block anyone. The message
+# names the number to take instead.
+#
+# It also prints warnings, never refusals, for item files the push adds or
+# changes: the cheap part of the Work index's parser (title, owner, `## Left`).
+#
+# Fails open: an error of this hook's own (a git or awk failure) refuses nothing.
+
+zero() { case $1 in *[!0]*) return 1 ;; esac; }
+
+# `<number>\t<path>` for every item file of commit $1.
+items() {
+ git -c core.quotePath=false ls-tree --full-tree "$1" -- work/ done/ 2>/dev/null | awk -F'\t' '
+ $1 ~ / blob / {
+ name = $2; sub(/^[^\/]*\//, "", name)
+ if (name ~ /^[0-9]+-[^\/]*\.md$/) { match(name, /^[0-9]+/); print (substr(name, 1, RLENGTH) + 0) "\t" $2 }
+ }'
+}
+
+# Exit 1, with a message, if commit $1 has duplicate numbers that the base commit $2 (may be empty) has fewer of.
+check() {
+ { [ -z "$2" ] || items "$2"; echo '--'; items "$1"; } | awk -F'\t' '
+ !pushed && $0 == "--" { pushed = 1; next }
+ !pushed { before[$1 + 0]++; old[$2] = 1; next }
+ { n = $1 + 0; count[n]++; path[n, count[n]] = $2; if (n > max) max = n }
+ END {
+ k = 0
+ for (n in count) if (count[n] > 1 && count[n] > before[n] + 0) dup[++k] = n + 0
+ for (i = 2; i <= k; i++) for (j = i; j > 1 && dup[j - 1] > dup[j]; j--) { t = dup[j]; dup[j] = dup[j - 1]; dup[j - 1] = t }
+ free = max + 1
+ for (i = 1; i <= k; i++) {
+ n = dup[i]; taken = ""
+ for (j = 1; j <= count[n]; j++) if ((path[n, j]) in old) { taken = path[n, j]; break }
+ if (taken == "") taken = path[n, 1]
+ for (j = 1; j <= count[n]; j++) {
+ p = path[n, j]
+ if (p == taken || (p in old)) continue
+ if (!said) print "pre-push: refused: two items under work/ and done/ have one number." > "/dev/stderr"
+ said = 1
+ print " " n " is taken by " taken ", renumber yours (" p ") to " free > "/dev/stderr"
+ free++
+ }
+ }
+ if (said) {
+ print "Rename the file (git mv), put the new number in its # title, commit, and push again." > "/dev/stderr"
+ exit 1
+ }
+ }'
+ # Only the refusal above is 1; anything else (an awk error) refuses nothing.
+ [ $? -ne 1 ]
+}
+
+# Warnings for the item files commit $1 adds or changes since $2 (none without a base: that would be every file).
+warn() {
+ [ -n "$2" ] || return 0
+ git -c core.quotePath=false diff --name-only --no-renames --diff-filter=AM "$2" "$1" -- ':/work' ':/done' 2>/dev/null | head -n 50 |
+ while IFS= read -r p; do
+ case $p in */*/*) continue ;; *.md) ;; *) continue ;; esac
+ case ${p#*/} in
+ [0-9]*-*.md) ;;
+ *) echo "pre-push: warning: $p is not an item; items are named NN-slug.md" >&2; continue ;;
+ esac
+ git cat-file blob "$1:$p" 2>/dev/null | awk -v p="$p" '
+ NR == 1 && $0 == "---" { front = 1; next }
+ front && $0 == "---" { front = 0; next }
+ front && /^owner:/ { o = $0; sub(/^owner:[ \t]*/, "", o); sub(/[ \t]+$/, "", o); if (o != "" && o !~ /^[^@ \t,]+@[^@ \t,]+$/) bad_owner = 1; next }
+ front { next }
+ !title && /^# / { title = 1 }
+ /^## / { in_left = ($0 ~ /^## Left[ \t]*$/); if (in_left) left = 1; next }
+ in_left && /^[ \t]*[-*] \[[ xX]\]/ { boxes = 1 }
+ END {
+ if (!title) print "pre-push: warning: " p " has no \"# \" title; the board shows its slug"
+ if (bad_owner) print "pre-push: warning: " p ": owner is not one email address"
+ if (left && !boxes) print "pre-push: warning: " p ": \"## Left\" has no checkboxes; the item reads as in progress"
+ }' >&2
+ done
+}
+
+status=0
+while read -r _local_ref local_sha remote_ref remote_sha; do
+ case $remote_ref in refs/heads/*) ;; *) continue ;; esac
+ zero "$local_sha" && continue # a deletion
+ base=
+ if ! zero "$remote_sha" && git cat-file -e "$remote_sha^{commit}" 2>/dev/null; then
+ base=$remote_sha
+ else
+ base=$(git rev-parse -q --verify "refs/remotes/$1/HEAD^{commit}" 2>/dev/null) || base=
+ fi
+ check "$local_sha" "$base" || status=1
+ warn "$local_sha" "$base"
+done
+exit $status
diff --git a/computer/hooks/knowledge/prepare-commit-msg b/computer/hooks/knowledge/prepare-commit-msg
new file mode 100755
index 00000000..0716f538
--- /dev/null
+++ b/computer/hooks/knowledge/prepare-commit-msg
@@ -0,0 +1,21 @@
+#!/bin/sh
+# opencomputer-knowledge-hook: installed by the computer's host in the clone of
+# the organization's knowledge repository (src/workspaces/knowledge-hooks.ts),
+# and replaced by it on every housekeeping pass: edits here do not last.
+#
+# Adds a `Session: <id>` trailer from $SP_SESSION_ID, which the runner exports
+# for every session, so the Work index can link the session to the items the
+# commit touches. Nothing without the variable; never twice for one session
+# (an amend or a rebase keeps the trailer it has). It never fails a commit:
+# every path exits 0.
+
+id=${SP_SESSION_ID-}
+[ -n "$id" ] || exit 0
+# A session id or key (`cs_…`, `C0B:1791.82`): nothing that could break the message.
+case $id in *[!A-Za-z0-9._:-]*) exit 0 ;; esac
+msg=$1
+[ -n "$msg" ] && [ -f "$msg" ] || exit 0
+# Nothing written yet (an editor will open next): leave it, so an empty message still aborts the commit.
+[ -n "$(git stripspace --strip-comments <"$msg" 2>/dev/null)" ] || exit 0
+git interpret-trailers --in-place --if-exists addIfDifferent --trailer "Session: $id" "$msg" >/dev/null 2>&1
+exit 0
diff --git a/computer/src/workspaces/as-runner.ts b/computer/src/workspaces/as-runner.ts
index 695a99a8..194e4bcc 100644
--- a/computer/src/workspaces/as-runner.ts
+++ b/computer/src/workspaces/as-runner.ts
@@ -57,6 +57,7 @@ export const rm = (p: string) => (as() ? run('rm', ['-rf', '--', p]) : fsp.rm(p,
export const rename = (from: string, to: string) => (as() ? run('mv', ['-T', '--', from, to]) : fsp.rename(from, to));
export const writeFile = (file: string, data: string) => (as() ? run('sh', ['-c', 'cat > "$1"', 'sh', file], data) : fsp.writeFile(file, data));
export const appendFile = (file: string, data: string) => (as() ? run('sh', ['-c', 'cat >> "$1"', 'sh', file], data) : fsp.appendFile(file, data));
+export const chmod = (file: string, mode: number) => (as() ? run('chmod', [mode.toString(8), '--', file]) : fsp.chmod(file, mode));
export const copyFile = (from: string, to: string) => (as() ? run('cp', ['--', from, to]) : fsp.copyFile(from, to));
/** Sets the modification time to now. */
export const touch = (file: string) => (as() ? run('touch', ['-c', '--', file]) : fsp.utimes(file, new Date(), new Date()));
diff --git a/computer/src/workspaces/clones.ts b/computer/src/workspaces/clones.ts
index dce01d35..68a943d0 100644
--- a/computer/src/workspaces/clones.ts
+++ b/computer/src/workspaces/clones.ts
@@ -19,6 +19,7 @@ import { HOST_DATA, type Person } from '../protocol.js';
import { type Definition, isLazy, loadDefinition, type RepoDef } from './definition.js';
import { command, copyFile, mkdir, rename, rm, writeFile } from './as-runner.js';
import { Freshness, keyedQueue } from './fetch-schedule.js';
+import { syncKnowledgeHooks } from './knowledge-hooks.js';
const exec = promisify(execFile);
@@ -152,7 +153,10 @@ export async function ensureWorkspace(person: Person): Promise<void> {
def.repos
.filter((r) => !r.unpublished && !isLazy(r))
.map((r) =>
- cloneRepo(path.join(ws, r.name), r).catch((e) => {
+ (async () => {
+ await cloneRepo(path.join(ws, r.name), r);
+ await syncKnowledgeHooks(path.join(ws, r.name), r);
+ })().catch((e) => {
failed.push(`${r.name}: ${errText(e)}`);
}),
),
diff --git a/computer/src/workspaces/housekeep.ts b/computer/src/workspaces/housekeep.ts
index 4b1e3fbc..d860950a 100644
--- a/computer/src/workspaces/housekeep.ts
+++ b/computer/src/workspaces/housekeep.ts
@@ -21,6 +21,7 @@ import {
HOUSEKEEPING_FETCHES, isClone, observe, observed, ok, personRoot, serial, workspaceDir,
} from './clones.js';
import { limit } from './fetch-schedule.js';
+import { syncKnowledgeHooks } from './knowledge-hooks.js';
import { pruneIdleArtifacts } from './idle.js';
import { pruneForks } from './prune.js';
@@ -54,6 +55,7 @@ async function syncRepo(person: Person, repo: RepoDef, trigger: FetchTrigger): P
await cloneRepo(clone, repo);
const b = await defaultBranch(clone, repo);
const problems: string[] = [];
+ await syncKnowledgeHooks(clone, repo).catch((e) => problems.push(`hooks: ${errText(e)}`));
let fetchError: string | undefined;
let ms = 0;
await housekeepingFetch(() =>
diff --git a/computer/src/workspaces/knowledge-hooks.test.ts b/computer/src/workspaces/knowledge-hooks.test.ts
new file mode 100644
index 00000000..2a8242db
--- /dev/null
+++ b/computer/src/workspaces/knowledge-hooks.test.ts
@@ -0,0 +1,197 @@
+// Real git, real hooks: a bare remote, the host's shared clone of the
+// knowledge repository with the hooks installed, and a session's worktree of
+// it (as fork.ts makes them), committing and pushing the way an agent does.
+
+import { spawnSync } from 'node:child_process';
+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { configureAsRunner } from './as-runner.js';
+import { HOOK_MARK, KNOWLEDGE_HOOKS, syncKnowledgeHooks } from './knowledge-hooks.js';
+
+const root = mkdtempSync(path.join(os.tmpdir(), 'sp-khooks-'));
+const source = path.resolve(import.meta.dirname, '..', '..', 'hooks', 'knowledge');
+const knowledge = { name: 'notes', remote: 'https://github.com/acme/notes', role: 'knowledge' as const };
+const plain = { name: 'api', remote: 'https://github.com/acme/api' };
+
+// A git of its own: no user or system configuration, a fixed author.
+const env = (extra: Record<string, string> = {}): NodeJS.ProcessEnv => {
+ const { SP_SESSION_ID: _, ...rest } = process.env;
+ return {
+ ...rest,
+ HOME: root,
+ GIT_CONFIG_NOSYSTEM: '1',
+ GIT_CONFIG_GLOBAL: path.join(root, 'gitconfig'),
+ GIT_AUTHOR_NAME: 'Ada',
+ GIT_AUTHOR_EMAIL: '[email protected]',
+ GIT_COMMITTER_NAME: 'Ada',
+ GIT_COMMITTER_EMAIL: '[email protected]',
+ GIT_EDITOR: 'true',
+ ...extra,
+ };
+};
+function git(cwd: string, args: string[], extra: Record<string, string> = {}) {
+ const r = spawnSync('git', args, { cwd, env: env(extra), encoding: 'utf8' });
+ if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);
+ return r.stdout.trim();
+}
+const push = (cwd: string, extra: Record<string, string> = {}) =>
+ spawnSync('git', ['push', 'origin', 'HEAD:main'], { cwd, env: env(extra), encoding: 'utf8' });
+function put(dir: string, files: Record<string, string>) {
+ for (const [f, text] of Object.entries(files)) {
+ mkdirSync(path.dirname(path.join(dir, f)), { recursive: true });
+ writeFileSync(path.join(dir, f), text);
+ }
+}
+const item = (title: string) => `---\nowner: [email protected]\n---\n# ${title}\n\nStarted.\n\n## Left\n\n- [ ] the rest\n`;
+const trailers = (cwd: string, rev = 'HEAD') =>
+ git(cwd, ['log', '-1', '--format=%(trailers:key=Session,valueonly)', rev]).split('\n').filter(Boolean);
+
+const remote = path.join(root, 'notes.git');
+const clone = path.join(root, 'ws', 'notes'); // the host's shared clone
+const session = path.join(root, 'sessions', 's1'); // a session's fork of it
+const other = path.join(root, 'other'); // someone else, elsewhere, without the hooks
+const hooks = path.join(clone, '.git', 'hooks');
+
+beforeAll(() => {
+ configureAsRunner(undefined, process.env);
+ writeFileSync(path.join(root, 'gitconfig'), '[init]\n\tdefaultBranch = main\n');
+ git(root, ['init', '-q', '--bare', remote]);
+ git(root, ['clone', '-q', remote, other]);
+ // History already has a shared number (7): it must never block anyone.
+ put(other, {
+ 'README.md': 'notes\n',
+ 'work/01-first.md': item('First'),
+ 'work/07-a.md': item('A'),
+ 'done/7-b.md': item('B'),
+ 'done/2-old.md': item('Old'),
+ });
+ git(other, ['add', '-A']);
+ git(other, ['commit', '-q', '-m', 'Seed']);
+ git(other, ['push', '-q', 'origin', 'HEAD:main']);
+ git(root, ['clone', '-q', remote, clone]);
+ git(clone, ['worktree', 'add', '-q', '-b', 'sp/s1', session, 'origin/main']);
+});
+afterAll(() => {
+ configureAsRunner(undefined, {});
+ rmSync(root, { recursive: true, force: true });
+});
+
+describe('syncKnowledgeHooks', () => {
+ it('installs both hooks, executable, where the clone and its worktrees look', async () => {
+ await syncKnowledgeHooks(clone, knowledge, source);
+ expect(git(session, ['rev-parse', '--path-format=absolute', '--git-path', 'hooks'])).toBe(hooks);
+ for (const name of KNOWLEDGE_HOOKS) {
+ const file = path.join(hooks, name);
+ expect(readFileSync(file, 'utf8')).toBe(readFileSync(path.join(source, name), 'utf8'));
+ expect(statSync(file).mode & 0o777).toBe(0o755);
+ }
+ });
+
+ it('leaves current hooks alone, and replaces stale ones of ours', async () => {
+ const file = path.join(hooks, 'pre-push');
+ const before = statSync(file).mtimeMs;
+ await syncKnowledgeHooks(clone, knowledge, source);
+ expect(statSync(file).mtimeMs).toBe(before);
+ writeFileSync(file, `#!/bin/sh\n# ${HOOK_MARK}: an older release\nexit 1\n`);
+ chmodSync(path.join(hooks, 'prepare-commit-msg'), 0o644);
+ await syncKnowledgeHooks(clone, knowledge, source);
+ expect(readFileSync(file, 'utf8')).toBe(readFileSync(path.join(source, 'pre-push'), 'utf8'));
+ expect(statSync(path.join(hooks, 'prepare-commit-msg')).mode & 0o111).toBe(0o111);
+ expect(existsSync(`${file}.installing`)).toBe(false);
+ });
+
+ it("never replaces someone else's hook, and says so", async () => {
+ const dir = path.join(root, 'foreign');
+ git(root, ['init', '-q', dir]);
+ const theirs = '#!/bin/sh\necho theirs\n';
+ writeFileSync(path.join(dir, '.git', 'hooks', 'pre-push'), theirs);
+ await expect(syncKnowledgeHooks(dir, knowledge, source)).rejects.toThrow(/pre-push in .* is not ours/);
+ expect(readFileSync(path.join(dir, '.git', 'hooks', 'pre-push'), 'utf8')).toBe(theirs);
+ expect(readFileSync(path.join(dir, '.git', 'hooks', 'prepare-commit-msg'), 'utf8')).toContain(HOOK_MARK);
+ // No longer the knowledge repository: ours go, theirs stays.
+ await syncKnowledgeHooks(dir, plain, source);
+ expect(existsSync(path.join(dir, '.git', 'hooks', 'prepare-commit-msg'))).toBe(false);
+ expect(readFileSync(path.join(dir, '.git', 'hooks', 'pre-push'), 'utf8')).toBe(theirs);
+ await syncKnowledgeHooks(path.join(root, 'nowhere'), plain, source); // nothing there: nothing to do
+ });
+});
+
+describe('prepare-commit-msg', () => {
+ const id = { SP_SESSION_ID: 'cs_s1' };
+
+ it('adds the Session trailer once, through an amend', () => {
+ put(session, { 'work/08-mine.md': item('Mine') });
+ git(session, ['add', '-A']);
+ git(session, ['commit', '-q', '-m', 'Track mine'], id);
+ expect(trailers(session)).toEqual(['cs_s1']);
+ git(session, ['commit', '-q', '--amend', '--no-edit'], id);
+ git(session, ['commit', '-q', '--amend', '-m', 'Track mine\n\nWith a body.\n\nSession: cs_s1'], id);
+ expect(trailers(session)).toEqual(['cs_s1']);
+ expect(git(session, ['log', '-1', '--format=%B'])).toBe('Track mine\n\nWith a body.\n\nSession: cs_s1');
+ });
+
+ it('adds nothing without SP_SESSION_ID, or with one that is not an id', () => {
+ put(session, { 'docs/x.md': 'x\n' });
+ git(session, ['add', '-A']);
+ git(session, ['commit', '-q', '-m', 'Unattributed']);
+ expect(trailers(session)).toEqual([]);
+ git(session, ['commit', '-q', '--amend', '--no-edit'], { SP_SESSION_ID: 'x\nSigned-off-by: someone' });
+ expect(git(session, ['log', '-1', '--format=%B'])).toBe('Unattributed');
+ git(session, ['reset', '-q', '--hard', 'HEAD~1']);
+ });
+
+ it('keeps one trailer per commit through a rebase onto new upstream work', () => {
+ put(other, { 'docs/upstream.md': 'meanwhile\n' });
+ git(other, ['add', '-A']);
+ git(other, ['commit', '-q', '-m', 'Upstream']);
+ git(other, ['push', '-q', 'origin', 'HEAD:main']);
+ git(session, ['pull', '-q', '--rebase', 'origin', 'main'], id);
+ expect(git(session, ['log', '-1', '--format=%s', 'HEAD~1'])).toBe('Upstream');
+ expect(trailers(session)).toEqual(['cs_s1']);
+ expect(trailers(session, 'HEAD~1')).toEqual([]);
+ });
+});
+
+describe('pre-push', () => {
+ it('lets a push with fresh numbers through, despite shared numbers in history', () => {
+ const r = push(session);
+ expect(r.stderr).not.toMatch(/refused/);
+ expect(r.status).toBe(0);
+ });
+
+ it('refuses a number another session took first, naming the one to take instead', () => {
+ // Both sessions take 9: the other one pushes first.
+ put(other, { 'work/9-theirs.md': item('Theirs') });
+ git(other, ['add', '-A']);
+ git(other, ['commit', '-q', '-m', 'Track theirs']);
+ git(other, ['pull', '-q', '--rebase', 'origin', 'main']);
+ git(other, ['push', '-q', 'origin', 'HEAD:main']);
+ put(session, { 'work/09-ours.md': item('Ours') });
+ git(session, ['add', '-A']);
+ git(session, ['commit', '-q', '-m', 'Track ours']);
+ git(session, ['pull', '-q', '--rebase', 'origin', 'main']);
+ const r = push(session);
+ expect(r.status).not.toBe(0);
+ expect(r.stderr).toContain('pre-push: refused');
+ expect(r.stderr).toContain('9 is taken by work/9-theirs.md, renumber yours (work/09-ours.md) to 10');
+ expect(git(other, ['ls-remote', 'origin', 'main'])).not.toContain(git(session, ['rev-parse', 'HEAD']));
+
+ git(session, ['mv', 'work/09-ours.md', 'work/10-ours.md']);
+ git(session, ['commit', '-q', '-m', 'Renumber ours']);
+ expect(push(session).status).toBe(0);
+ });
+
+ it('warns about malformed items without refusing', () => {
+ put(session, { 'work/11-bare.md': 'no title\n\n## Left\n\nnothing\n', 'work/notes.md': 'x\n', 'done/12-ok.md': item('Ok') });
+ git(session, ['add', '-A']);
+ git(session, ['commit', '-q', '-m', 'Odd files']);
+ const r = push(session);
+ expect(r.status).toBe(0);
+ expect(r.stderr).toContain('work/11-bare.md has no "# " title');
+ expect(r.stderr).toContain('work/11-bare.md: "## Left" has no checkboxes');
+ expect(r.stderr).toContain('work/notes.md is not an item');
+ expect(r.stderr).not.toContain('12-ok');
+ });
+});
diff --git a/computer/src/workspaces/knowledge-hooks.ts b/computer/src/workspaces/knowledge-hooks.ts
new file mode 100644
index 00000000..12fa2946
--- /dev/null
+++ b/computer/src/workspaces/knowledge-hooks.ts
@@ -0,0 +1,74 @@
+// The knowledge repository's git hooks (work tracking, design 3.4): the
+// release's hooks/knowledge/ scripts, installed by the host into the shared
+// clone of the definition's `role: "knowledge"` repository. Session forks are
+// worktrees of that clone, and linked worktrees run the hooks of the clone's
+// common directory, so every session's commits and pushes go through them.
+//
+// Invariants:
+// - Installed on every sync (housekeeping, a push, a workspace preparation),
+// not only at clone time: existing clones never pass through a clone again.
+// Idempotent: an up-to-date hook is not rewritten; a stale one is replaced
+// atomically (written beside it, then renamed), so a commit never sees half a hook.
+// - Only hooks carrying HOOK_MARK are ever replaced or removed; someone else's hook
+// of the same name stays, reported as a problem.
+// - A clone that is not (or no longer) the knowledge repository has none of
+// ours: they are removed from its hooks directory, so no other repository's
+// pushes are checked.
+
+import { execFile } from 'node:child_process';
+import { readFile, stat } from 'node:fs/promises';
+import path from 'node:path';
+import { promisify } from 'node:util';
+import { chmod, command, mkdir, rename, rm, writeFile } from './as-runner.js';
+import { isKnowledge, type RepoDef } from './definition.js';
+
+const exec = promisify(execFile);
+
+export const KNOWLEDGE_HOOKS = ['prepare-commit-msg', 'pre-push'] as const;
+/** In every hook we install: what tells ours from a hook someone else put there. */
+export const HOOK_MARK = 'opencomputer-knowledge-hook';
+const SOURCE = path.resolve(import.meta.dirname, '..', '..', 'hooks', 'knowledge');
+
+const read = (file: string) => readFile(file, 'utf8').catch(() => undefined);
+const executable = (file: string) =>
+ stat(file).then(
+ (s) => (s.mode & 0o111) === 0o111,
+ () => false,
+ );
+
+/**
+ * Bring the clone's hooks in line with the repository's role: ours installed
+ * and current for the knowledge repository, ours removed from any other.
+ * Throws when a hook of ours cannot be installed (its name is taken by another hook).
+ */
+export async function syncKnowledgeHooks(clone: string, repo: RepoDef, source = SOURCE): Promise<void> {
+ if (!isKnowledge(repo)) {
+ // Where an earlier pass would have put them; no git call for the many repositories that never had them.
+ for (const name of KNOWLEDGE_HOOKS) {
+ const dest = path.join(clone, '.git', 'hooks', name);
+ if ((await read(dest))?.includes(HOOK_MARK)) await rm(dest);
+ }
+ return;
+ }
+ // Where git looks for this clone and its worktrees: core.hooksPath if set, else the common directory's hooks/.
+ const c = command('git', ['rev-parse', '--git-path', 'hooks'], { GIT_TERMINAL_PROMPT: '0' });
+ const dir = path.resolve(clone, (await exec(c.cmd, c.args, { cwd: clone, env: c.env })).stdout.trim());
+ await mkdir(dir, { recursive: true });
+ const taken: string[] = [];
+ for (const name of KNOWLEDGE_HOOKS) {
+ const dest = path.join(dir, name);
+ const want = await readFile(path.join(source, name), 'utf8');
+ const have = await read(dest);
+ if (have === want && (await executable(dest))) continue;
+ if (have !== undefined && !have.includes(HOOK_MARK)) {
+ taken.push(name);
+ continue;
+ }
+ const tmp = `${dest}.installing`;
+ await writeFile(tmp, want);
+ await chmod(tmp, 0o755);
+ await rename(tmp, dest);
+ }
+ if (taken.length)
+ throw new Error(`${taken.join(', ')} in ${dir} ${taken.length > 1 ? 'are' : 'is'} not ours; work-tracking hooks not installed there`);
+}