@popovych.co/witness 0.27.0 → 0.28.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.
- package/README.md +12 -5
- package/dist/adopt.js +92 -6
- package/dist/arbiter.js +5 -3
- package/dist/cli.js +9 -2
- package/dist/contain.js +132 -0
- package/dist/drive-presence.js +96 -13
- package/dist/drive.js +61 -16
- package/dist/gates/decompose.js +25 -7
- package/dist/principles.js +18 -0
- package/dist/reviewed.js +30 -1
- package/dist/reviewer.js +8 -2
- package/dist/runner-lock.js +12 -0
- package/dist/runner.js +40 -5
- package/dist/spawn.js +1 -1
- package/dist/verbs/adopt.js +20 -3
- package/dist/verbs/check.js +17 -4
- package/dist/verbs/decide.js +15 -6
- package/dist/verbs/drive.js +9 -1
- package/dist/verbs/floor.js +34 -4
- package/dist/verbs/init.js +5 -7
- package/dist/verbs/migrate.js +43 -11
- package/dist/verbs/next.js +64 -16
- package/dist/verbs/satisfy.js +8 -0
- package/dist/verbs/trust.js +35 -17
- package/dist/verbs/turn.js +46 -0
- package/dist/verbs/write.js +6 -1
- package/package.json +1 -1
- package/plugin/.claude-plugin/plugin.json +1 -1
- package/plugin/commands/witness.md +1 -1
- package/plugin/hooks/session-dashboard.sh +1 -1
- package/plugin/skills/witness-brainstorm/SKILL.md +1 -1
- package/plugin/skills/witness-decompose/SKILL.md +1 -1
- package/plugin/skills/witness-design/SKILL.md +1 -1
- package/plugin/skills/witness-implement/SKILL.md +4 -2
- package/plugin/skills/witness-plan/SKILL.md +1 -1
- package/plugin/skills/witness-ship/SKILL.md +4 -2
- package/prompts/code-reviewer.md +4 -2
- package/prompts/design-critic.md +3 -1
- package/prompts/design-reviewer.md +4 -2
- package/prompts/drift-reviewer.md +4 -2
- package/prompts/plan-critic.md +4 -2
- package/prompts/pr-test.md +4 -2
- package/prompts/silent-failure-hunter.md +4 -2
- package/prompts/slicing-critic.md +4 -2
- package/prompts/type-design.md +4 -2
package/README.md
CHANGED
|
@@ -239,8 +239,11 @@ plain-words question per turn with up to three ranked answers, the repo explored
|
|
|
239
239
|
draft after every settled answer, so a dead session resumes. Design shows up to three rendered,
|
|
240
240
|
checked directions on one page before it asks which.
|
|
241
241
|
|
|
242
|
-
**`drive`.** `drive.parallelSuites: false` makes test runs in two worktrees take turns
|
|
243
|
-
|
|
242
|
+
**`drive`.** `drive.parallelSuites: false` makes test runs in two worktrees take turns — witness's
|
|
243
|
+
own and every `witness turn`, which is how a session runs its tests — because suites that boot
|
|
244
|
+
servers or browsers collide. On Windows each session, test run and gate reviewer runs in a job
|
|
245
|
+
object, so whatever it starts — detached, or orphaned by an installer that exited — ends with it;
|
|
246
|
+
elsewhere a session's process group does. A target that reaches any `drive.caps.*` bound is
|
|
244
247
|
parked.
|
|
245
248
|
|
|
246
249
|
### Upgrading
|
|
@@ -248,7 +251,10 @@ parked.
|
|
|
248
251
|
After each witness upgrade, run `witness migrate --dry-run` to see what the new version adds or
|
|
249
252
|
changes, then `witness migrate`: it brings `witness.config.yaml` to the current schema, keeps
|
|
250
253
|
every value you chose and every comment you wrote, names each change, and commits the file. A
|
|
251
|
-
value still at an old default moves to the new one, and the output says so.
|
|
254
|
+
value still at an old default moves to the new one, and the output says so. It also stamps
|
|
255
|
+
`specs/principles.md` approved when it is still the empty template an older `witness init` wrote
|
|
256
|
+
as a draft — a principles file you changed is approved only by the decompose gate of the effort
|
|
257
|
+
that amended it. Until you migrate,
|
|
252
258
|
an older file keeps working: witness reads it as `migrate` would, changes nothing in it, and warns
|
|
253
259
|
(`witness check` shows `older-schema`). A file from a newer witness refuses: upgrade witness.
|
|
254
260
|
|
|
@@ -283,7 +289,7 @@ the wrong file refuses. There are no `WITNESS_*` env vars for configuration.
|
|
|
283
289
|
| `read <id> [--design] [--outline] [--lines <a>-<b>] [--decisions]` | print a spec/plan/design from the primary root — the read route, since a worktree carries no canon copy; `--outline` names each anchor's line range for fat artifacts, and for a look its controls and hidden states; `--decisions` prints the decisions a spec carries with its effort's constraints and non-goals, or an effort's whole recap |
|
|
284
290
|
| `check` | schema, graph, invariants, needs, trailer audit, probes |
|
|
285
291
|
| `index` | id · summary · status · depends across the canon, then each spec's plans |
|
|
286
|
-
| `satisfy <id> --need <id\|n\|text>` | journal a manual need as met — the spec is never rewritten |
|
|
292
|
+
| `satisfy <id> --need <id\|n\|text>` | journal a manual need as met — the spec is never rewritten; refused inside a session, since the human marks a need met |
|
|
287
293
|
| `trust [<id>] [--cmd '<exact command>']… [--yes]` | list every command a target's flow runs (the runner, `ship.test`, `ship.lint`, its spec's `cmd:` criteria, its `cmd:` needs) with its source; `--cmd` grants exactly the named command, `--yes` grants all only at a terminal; no session grants trust · with no id, everything the repo runs |
|
|
288
294
|
| `retry <target>` | ask drive to try a set-aside target again, after a fix that leaves no record of its own (code, a tool, an account); refused inside a session |
|
|
289
295
|
| `wait [--since <token>]` | under autonomy, block until something new needs you, drive stops with work left, a merge lands on GitHub, or a newer chat takes over — the `/witness` chat runs it; journals nothing |
|
|
@@ -297,8 +303,9 @@ the wrong file refuses. There are no `WITNESS_*` env vars for configuration.
|
|
|
297
303
|
| `drive [--flow <plan-id>] [--max-spawns <n>] [--manual] [--detach]` | runs every session itself · under autonomy it needs no terminal and reports when nothing else can move. Up to `drive.parallel` targets at once, one session per target; usage limits are waited out; a target past a cap is parked. `--detach` (autonomy only) runs it in the background into `.witness/drive.log` — each session's start, every command and file its agent touches, every act it journals for its flow, a `still running` line after 5 quiet minutes, and how it ended; drive's pi sessions are kept in pi's session store under `witness-drive/`; `--manual` runs serially and asks you at every stop. One drive per repo. A session drive spawned is refused — agents are what drive spawns, never what spawns drive |
|
|
298
304
|
| `ship <plan-id> [--manual]` | lanes → ship gate → PR → CI watch → under autonomy: merge on green · `--manual` keeps that run's stop and merge for a human |
|
|
299
305
|
| `test-evidence <plan-id> --phase red\|green [--step <id>]` / `verify-red <plan-id> [--base <ref>] [--step <id>]` | journal red/green criteria evidence from a worktree; `--step` names the plan step the cycle closes — required before the plan's first implement gate (on a plan with a criteria step), left off for a fix round after it. A green that closes a step prints `context:`, `steps:` and `slice:` |
|
|
306
|
+
| `turn -- <command> [args…]` | run one command in the repo's test turn — it waits while another worktree's test run holds it, unless `drive.parallelSuites: true` — and on Windows inside a job object, so whatever it starts ends with it; exits with the command's code · the implement and ship skills run every test a session runs itself through it |
|
|
300
307
|
| `step-close <plan-id> --step <id>` | close a scaffolding step, which has no red→green to witness; prints `context:`, `steps:` and `slice:` as a closing green does, and closing it again changes nothing |
|
|
301
|
-
| `adopt <path>` | absolve a finished hand-edit into the journal |
|
|
308
|
+
| `adopt <path>` | absolve a finished hand-edit into the journal — content only: a hand edit that moves `status`, `drift`, `pr` or `design` is refused, since only witness writes a doc's position |
|
|
302
309
|
| `abandon <plan-id \| effort-slug…>` | wind a plan/effort down; reverts only specs that effort itself wrote — several efforts go as one act, so a split or an amendment they share goes back together |
|
|
303
310
|
| `dispatch-report <plan-id> --steps-assigned <n> --steps-completed <n>` | journal a session slice's telemetry |
|
|
304
311
|
| `rename <old> <new>` | id rename across canon, refs, journal |
|
package/dist/adopt.js
CHANGED
|
@@ -3,22 +3,36 @@ import { join } from 'node:path';
|
|
|
3
3
|
import { splitDoc } from './fm.js';
|
|
4
4
|
import { TRAILER, git, tryGit } from './gitio.js';
|
|
5
5
|
import { readStream } from './journal.js';
|
|
6
|
-
import { canonicalSha } from './sha.js';
|
|
6
|
+
import { canonicalSha, VOLATILE_FIELDS } from './sha.js';
|
|
7
|
+
export const positionOf = (meta) => Object.fromEntries(VOLATILE_FIELDS.map((f) => [f, meta[f]]));
|
|
7
8
|
const hasTrailer = (root, sha) => git(root, 'show', '-s', '--format=%B', sha).split('\n').some((l) => l.trim() === TRAILER);
|
|
8
9
|
const commitsTouching = (root, rel) => git(root, 'log', '--format=%H', '--', rel).split('\n').filter(Boolean);
|
|
10
|
+
// Row 220. The same walk through a move: each commit with the path the file had in it, so a
|
|
11
|
+
// doc moved by hand (`git mv`, D167) is measured against the state it was witnessed in before.
|
|
12
|
+
function commitsFollowing(root, rel) {
|
|
13
|
+
return git(root, 'log', '--follow', '--format=%x00%H', '--name-only', '--', rel).split('\0').flatMap((chunk) => {
|
|
14
|
+
const [sha, ...paths] = chunk.split('\n').filter(Boolean);
|
|
15
|
+
return sha === undefined ? [] : [{ sha, path: paths[0] ?? rel }];
|
|
16
|
+
});
|
|
17
|
+
}
|
|
9
18
|
// `absolved`: commits an `adopt` entry took in (`adoptedCommits`), which count as witnessed too —
|
|
10
|
-
// a hand commit that `adopt` absolved is the doc's witnessed state from then on.
|
|
11
|
-
|
|
12
|
-
|
|
19
|
+
// a hand commit that `adopt` absolved is the doc's witnessed state from then on. `follow` walks
|
|
20
|
+
// the file's history through a move (row 220's position baseline).
|
|
21
|
+
export function lastWitnessed(root, rel, absolved = new Set(), opts = {}) {
|
|
22
|
+
const walk = opts.follow === true ? commitsFollowing(root, rel) : commitsTouching(root, rel).map((sha) => ({ sha, path: rel }));
|
|
23
|
+
for (const { sha, path } of walk) {
|
|
13
24
|
if (!hasTrailer(root, sha) && !absolved.has(sha))
|
|
14
25
|
continue;
|
|
15
|
-
const raw = tryGit(root, 'show', `${sha}:${
|
|
26
|
+
const raw = tryGit(root, 'show', `${sha}:${path}`);
|
|
16
27
|
if (!raw.ok)
|
|
17
28
|
continue;
|
|
18
29
|
const doc = splitDoc(raw.out);
|
|
19
30
|
if (!doc.ok)
|
|
20
31
|
continue;
|
|
21
|
-
return {
|
|
32
|
+
return {
|
|
33
|
+
sha: canonicalSha(doc.value.meta, doc.value.body), criteria: doc.value.meta.criteria ?? null, id: String(doc.value.meta.id),
|
|
34
|
+
commit: sha, position: positionOf(doc.value.meta),
|
|
35
|
+
};
|
|
22
36
|
}
|
|
23
37
|
return undefined;
|
|
24
38
|
}
|
|
@@ -42,3 +56,75 @@ export function adoptedCommits(root) {
|
|
|
42
56
|
}
|
|
43
57
|
return out;
|
|
44
58
|
}
|
|
59
|
+
// Final review F1. An adopt absolves its commits for the doc it adopted — the stream it is
|
|
60
|
+
// journaled on — never for every doc those commits touched: one hand commit that forged one doc's
|
|
61
|
+
// position and edited another's body was laundered by adopting the innocent one.
|
|
62
|
+
export function adoptedCommitsFor(root, id) {
|
|
63
|
+
const out = new Set();
|
|
64
|
+
for (const entry of readStream(root, id)) {
|
|
65
|
+
if (entry.t !== 'adopt' || !Array.isArray(entry.commits))
|
|
66
|
+
continue;
|
|
67
|
+
for (const sha of entry.commits)
|
|
68
|
+
out.add(sha);
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
// For the trailer audit: each absolved commit and the doc ids it was absolved for (the stream,
|
|
73
|
+
// and the entry's artifact, which a later rename may leave apart).
|
|
74
|
+
export function absolutions(root) {
|
|
75
|
+
const out = new Map();
|
|
76
|
+
const dir = join(root, '.witness', 'journal');
|
|
77
|
+
if (!existsSync(dir))
|
|
78
|
+
return out;
|
|
79
|
+
for (const file of readdirSync(dir)) {
|
|
80
|
+
if (!file.endsWith('.jsonl'))
|
|
81
|
+
continue;
|
|
82
|
+
const stream = file.slice(0, -'.jsonl'.length);
|
|
83
|
+
for (const entry of readStream(root, stream)) {
|
|
84
|
+
if (entry.t !== 'adopt' || !Array.isArray(entry.commits))
|
|
85
|
+
continue;
|
|
86
|
+
for (const sha of entry.commits) {
|
|
87
|
+
const ids = out.get(sha) ?? new Set();
|
|
88
|
+
ids.add(stream);
|
|
89
|
+
if (typeof entry.artifact === 'string')
|
|
90
|
+
ids.add(entry.artifact);
|
|
91
|
+
out.set(sha, ids);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
// Security review. The state paths a commit changed that no adopt absolved it for: a spec or
|
|
98
|
+
// plan whose id (as it stood there, or in the parent for a deletion) is not among `ids`, and
|
|
99
|
+
// every other audited path — a journal line or a design file is never a hand edit adopt takes in.
|
|
100
|
+
// Empty means the commit is absolved whole.
|
|
101
|
+
export function unabsolvedPaths(root, sha, ids, dirs) {
|
|
102
|
+
const under = (p, ds) => ds.some((d) => p.startsWith(`${d}/`));
|
|
103
|
+
// NUL-separated status/path pairs: never quoted, whatever bytes a path carries. Anything that
|
|
104
|
+
// does not parse is reported, never skipped. Against the first parent, so a merge's own changes
|
|
105
|
+
// are read (diff-tree on a merge alone prints nothing); a root commit against the empty tree.
|
|
106
|
+
const [, parent] = git(root, 'rev-list', '--parents', '-n', '1', sha).split(' ');
|
|
107
|
+
const fields = (parent !== undefined
|
|
108
|
+
? git(root, 'diff-tree', '-z', '--no-renames', '--name-status', '-r', parent, sha)
|
|
109
|
+
: git(root, 'diff-tree', '-z', '--no-commit-id', '--no-renames', '--name-status', '-r', '--root', sha))
|
|
110
|
+
.split('\0').filter((x) => x !== '');
|
|
111
|
+
const out = [];
|
|
112
|
+
for (let i = 0; i < fields.length; i += 2) {
|
|
113
|
+
const status = fields[i];
|
|
114
|
+
const p = fields[i + 1];
|
|
115
|
+
if (p === undefined || !/^[ACDMTUX]$/.test(status)) {
|
|
116
|
+
out.push(`(unparsed: ${status})`);
|
|
117
|
+
continue;
|
|
118
|
+
}
|
|
119
|
+
if (under(p, dirs.docs) && p.endsWith('.md')) {
|
|
120
|
+
const raw = tryGit(root, 'show', `${status === 'D' ? `${sha}^` : sha}:${p}`);
|
|
121
|
+
const doc = raw.ok ? splitDoc(raw.out) : undefined;
|
|
122
|
+
const id = doc?.ok && typeof doc.value.meta.id === 'string' ? doc.value.meta.id : undefined;
|
|
123
|
+
if (id === undefined || !ids.has(id))
|
|
124
|
+
out.push(p);
|
|
125
|
+
}
|
|
126
|
+
else if (under(p, [...dirs.docs, ...dirs.other]))
|
|
127
|
+
out.push(p);
|
|
128
|
+
}
|
|
129
|
+
return out;
|
|
130
|
+
}
|
package/dist/arbiter.js
CHANGED
|
@@ -9,7 +9,7 @@ import { SESSION_DEFAULT, stageModel, unansweredPin } from './model.js';
|
|
|
9
9
|
import { PLACEHOLDER } from './recommend.js';
|
|
10
10
|
import { ok, refuse, v } from './refusal.js';
|
|
11
11
|
import { invokeReviewerAsync, parseVerdictText, promptsSha, resolvePrompt } from './reviewer.js';
|
|
12
|
-
import {
|
|
12
|
+
import { effortCanon, effortOf } from './reviewed.js';
|
|
13
13
|
import { anchorRecurrence, gateRuns, roundBudget } from './rounds.js';
|
|
14
14
|
import { findById } from './scan.js';
|
|
15
15
|
import { canonicalJson } from './sha.js';
|
|
@@ -170,8 +170,10 @@ export function decisionEvidence(root, canon, stop) {
|
|
|
170
170
|
scope.push(`### The plan: ${target}\n\n${serializeDoc({ meta: plan.meta, body: plan.body })}`);
|
|
171
171
|
}
|
|
172
172
|
else {
|
|
173
|
-
|
|
174
|
-
|
|
173
|
+
// Row 221. What the decompose gate judged: the effort's specs and the principles it wrote.
|
|
174
|
+
for (const s of effortCanon(root, canon, target)) {
|
|
175
|
+
const kind = s.meta.type === 'principles' ? 'The principles (standing rules, not a slice)' : 'The spec';
|
|
176
|
+
scope.push(`### ${kind}: ${String(s.meta.id)}\n\n${serializeDoc({ meta: s.meta, body: s.body })}`);
|
|
175
177
|
}
|
|
176
178
|
}
|
|
177
179
|
sections.push({ title: 'Scope', body: scope.join('\n\n') });
|
package/dist/cli.js
CHANGED
|
@@ -32,6 +32,8 @@ const VERBS = {
|
|
|
32
32
|
dismiss: () => import('./verbs/dismiss.js'),
|
|
33
33
|
log: () => import('./verbs/log.js'),
|
|
34
34
|
'test-evidence': () => import('./verbs/evidence.js'),
|
|
35
|
+
// Row 218. A session's own test run, in the repo's test turn and, on Windows, a job.
|
|
36
|
+
turn: () => import('./verbs/turn.js'),
|
|
35
37
|
'verify-red': () => import('./verbs/evidence.js').then((m) => ({ run: m.runVerifyRed })),
|
|
36
38
|
'dispatch-report': () => import('./verbs/dispatch.js'),
|
|
37
39
|
// Row 191 §4.3. The close of a scaffolding step, the one plan step with no evidence to witness.
|
|
@@ -99,6 +101,7 @@ const VERB_USAGE = {
|
|
|
99
101
|
sync: 'witness sync',
|
|
100
102
|
trust: "witness trust [<artifact-id>] [--cmd '<exact command>']… [--yes]",
|
|
101
103
|
'test-evidence': 'witness test-evidence <plan-id> --phase red|green [--step <id>]',
|
|
104
|
+
turn: 'witness turn -- <command> [args…]',
|
|
102
105
|
'verify-red': 'witness verify-red <plan-id> [--base <ref>] [--step <id>]',
|
|
103
106
|
wait: 'witness wait [--since <token>] — blocks until something new needs you · the chat runs it under autonomy',
|
|
104
107
|
};
|
|
@@ -149,8 +152,12 @@ export async function main(ctx, argv) {
|
|
|
149
152
|
// repository that refuses every verb must still be able to run the one that unrefuses it.
|
|
150
153
|
// An explicit help request is information, and refusing to print a usage line teaches
|
|
151
154
|
// the human nothing they can act on.
|
|
155
|
+
//
|
|
156
|
+
// Row 218. Only what precedes a `--` is witness's: after it the arguments are a command's,
|
|
157
|
+
// and `witness turn -- vitest --help` runs vitest's help, not turn's usage line.
|
|
158
|
+
const own = rest.includes('--') ? rest.slice(0, rest.indexOf('--')) : rest;
|
|
152
159
|
const helpRequested = verb === 'help' || verb === '--help'
|
|
153
|
-
||
|
|
160
|
+
|| own.includes('--help') || own.includes('-h');
|
|
154
161
|
// Row 217. A reviewer reads; it never acts. Its tools are already gone (the spawn flags); this tripwire
|
|
155
162
|
// refuses what a harness that ignored them could still run. Checked directly: a reviewer spawned inside
|
|
156
163
|
// a drive session carries both markers, and `sessionMarker` names the drive's first.
|
|
@@ -184,7 +191,7 @@ export async function main(ctx, argv) {
|
|
|
184
191
|
return EXIT.OK;
|
|
185
192
|
}
|
|
186
193
|
const load = VERBS[verb];
|
|
187
|
-
if (load && (
|
|
194
|
+
if (load && (own.includes('--help') || own.includes('-h'))) {
|
|
188
195
|
ctx.out(`usage: ${VERB_USAGE[verb] ?? `witness ${verb} [flags]`}`);
|
|
189
196
|
return EXIT.OK;
|
|
190
197
|
}
|
package/dist/contain.js
ADDED
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { existsSync } from 'node:fs';
|
|
2
|
+
import { crtQuote, envGet, spawnSync, system32 } from './spawn.js';
|
|
3
|
+
// Row 218. On Windows witness stopped what it started by ancestry — `taskkill /T` walks parent-pid
|
|
4
|
+
// links, libuv's own job holds only a direct child (every grandchild may break away silently, and
|
|
5
|
+
// a detached child is never assigned) — and a test suite's app leaves that ancestry: started
|
|
6
|
+
// detached by a starter that already exited, or by an installer that exits, it is linked to
|
|
7
|
+
// nothing, so it outlived every stop and every run that ended normally.
|
|
8
|
+
//
|
|
9
|
+
// The answer is a job object the host enters BEFORE it starts the command, so everything the
|
|
10
|
+
// command starts is born in it and dies when its last handle closes: when the host exits after
|
|
11
|
+
// the command, or when the host itself is killed — by a stop, or with its parent's libuv job.
|
|
12
|
+
// Assigning after spawn would race the shim, which starts the agent within milliseconds; a native
|
|
13
|
+
// addon or a compiled helper on disk would add what row 211's System32 PowerShell + `Add-Type`
|
|
14
|
+
// already gives. The limits are KILL_ON_JOB_CLOSE | BREAKAWAY_OK (0x2800), never silent breakaway
|
|
15
|
+
// (0x1000): a program that explicitly asks to leave still leaves, as it does today, and nothing
|
|
16
|
+
// else can — libuv's nested silent breakaway stops at this job (measured).
|
|
17
|
+
//
|
|
18
|
+
// A host that cannot enter a job costs containment, never the run: the probe runs once per
|
|
19
|
+
// process and a drive hands its answer down (`WITNESS_JOB_HOST`), so a machine where `Add-Type`
|
|
20
|
+
// is blocked (Constrained Language Mode) or `powershell.exe` is absent runs everything as before,
|
|
21
|
+
// and a job lost after a good probe prints `witness: no job (…)` and runs the command anyway.
|
|
22
|
+
export const JOB_HOST_ENV = 'WITNESS_JOB_HOST';
|
|
23
|
+
export const JOB_PROBE_EXIT = 86;
|
|
24
|
+
// One line of C#: the members Add-Type compiles into [Witness.Job].
|
|
25
|
+
const JOB_MEMBERS = [
|
|
26
|
+
'[StructLayout(LayoutKind.Sequential)] public struct Basic { public long PerProcessUserTimeLimit; public long PerJobUserTimeLimit; public uint LimitFlags;',
|
|
27
|
+
' public UIntPtr MinimumWorkingSetSize; public UIntPtr MaximumWorkingSetSize; public uint ActiveProcessLimit; public UIntPtr Affinity;',
|
|
28
|
+
' public uint PriorityClass; public uint SchedulingClass; }',
|
|
29
|
+
' [StructLayout(LayoutKind.Sequential)] public struct Extended { public Basic Basic; public ulong ReadOps; public ulong WriteOps;',
|
|
30
|
+
' public ulong OtherOps; public ulong ReadBytes; public ulong WriteBytes; public ulong OtherBytes; public UIntPtr ProcessMemoryLimit;',
|
|
31
|
+
' public UIntPtr JobMemoryLimit; public UIntPtr PeakProcessMemoryUsed; public UIntPtr PeakJobMemoryUsed; }',
|
|
32
|
+
' [DllImport("kernel32.dll", SetLastError = true)] public static extern IntPtr CreateJobObject(IntPtr attributes, string name);',
|
|
33
|
+
' [DllImport("kernel32.dll", SetLastError = true)] public static extern bool SetInformationJobObject(IntPtr job, int infoClass, ref Extended info, uint length);',
|
|
34
|
+
' [DllImport("kernel32.dll", SetLastError = true)] public static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);',
|
|
35
|
+
' [DllImport("kernel32.dll")] public static extern IntPtr GetCurrentProcess();',
|
|
36
|
+
].join('');
|
|
37
|
+
// The host. The command arrives only through the environment (row 211: never in the script's
|
|
38
|
+
// text) and leaves it before the command starts, with the caller's PSModulePath and PATHEXT,
|
|
39
|
+
// both of which PowerShell rewrites for itself at startup: PATHEXT gains `.CPL`, and where the
|
|
40
|
+
// caller had none it becomes `PathEXT=.CPL`, which left cmd.exe unable to find `node` (measured).
|
|
41
|
+
// Every other variable reaches the command as the caller set it. No `-ExecutionPolicy` on the host's command line:
|
|
42
|
+
// PowerShell would hand the command `PSExecutionPolicyPreference=Bypass`, and inline `-Command`
|
|
43
|
+
// text is not subject to execution policy anyway. Its own words are ASCII — Windows PowerShell
|
|
44
|
+
// writes a pipe in the OEM code page.
|
|
45
|
+
export const JOB_SCRIPT = [
|
|
46
|
+
"$ErrorActionPreference = 'Stop'",
|
|
47
|
+
'$held = $false',
|
|
48
|
+
'try {',
|
|
49
|
+
` Add-Type -Name Job -Namespace Witness -MemberDefinition '${JOB_MEMBERS}'`,
|
|
50
|
+
' $j = [Witness.Job]::CreateJobObject([IntPtr]::Zero, $null)',
|
|
51
|
+
" if ($j -eq [IntPtr]::Zero) { throw 'CreateJobObject failed' }",
|
|
52
|
+
' $e = New-Object Witness.Job+Extended',
|
|
53
|
+
' $b = $e.Basic; $b.LimitFlags = 0x2800; $e.Basic = $b',
|
|
54
|
+
" if (-not [Witness.Job]::SetInformationJobObject($j, 9, [ref]$e, [Runtime.InteropServices.Marshal]::SizeOf($e))) { throw 'SetInformationJobObject failed' }",
|
|
55
|
+
" if (-not [Witness.Job]::AssignProcessToJobObject($j, [Witness.Job]::GetCurrentProcess())) { throw 'AssignProcessToJobObject failed' }",
|
|
56
|
+
' $held = $true',
|
|
57
|
+
'} catch {',
|
|
58
|
+
" [Console]::Error.WriteLine('witness: no job (' + $_.Exception.Message + ')')",
|
|
59
|
+
'}',
|
|
60
|
+
`if ($env:WITNESS_JOB_PROBE) { if ($held) { exit 0 } else { exit ${JOB_PROBE_EXIT} } }`,
|
|
61
|
+
'$psi = New-Object System.Diagnostics.ProcessStartInfo',
|
|
62
|
+
'$psi.FileName = $env:WITNESS_JOB_FILE',
|
|
63
|
+
'$psi.Arguments = $env:WITNESS_JOB_ARGS',
|
|
64
|
+
'$psi.UseShellExecute = $false',
|
|
65
|
+
"if ($env:WITNESS_JOB_PSMODULEPATH) { $psi.EnvironmentVariables['PSModulePath'] = $env:WITNESS_JOB_PSMODULEPATH } else { $psi.EnvironmentVariables.Remove('PSModulePath') }",
|
|
66
|
+
"if ($env:WITNESS_JOB_PATHEXT) { $psi.EnvironmentVariables['PATHEXT'] = $env:WITNESS_JOB_PATHEXT } else { $psi.EnvironmentVariables.Remove('PATHEXT') }",
|
|
67
|
+
"foreach ($n in 'WITNESS_JOB_FILE', 'WITNESS_JOB_ARGS', 'WITNESS_JOB_PSMODULEPATH', 'WITNESS_JOB_PATHEXT') { $psi.EnvironmentVariables.Remove($n) }",
|
|
68
|
+
'$p = [System.Diagnostics.Process]::Start($psi)',
|
|
69
|
+
'$p.WaitForExit()',
|
|
70
|
+
'exit $p.ExitCode',
|
|
71
|
+
].join('\n');
|
|
72
|
+
const HOST_ARGS = ['-NoProfile', '-NonInteractive', '-Command', JOB_SCRIPT];
|
|
73
|
+
// libuv's quote_cmd_arg: an argument is quoted only when it is empty or holds a space, a tab
|
|
74
|
+
// or a quote, and then by the C runtime's rules.
|
|
75
|
+
export function winArg(arg) {
|
|
76
|
+
return arg === '' || /[ \t"]/.test(arg) ? crtQuote(arg) : arg;
|
|
77
|
+
}
|
|
78
|
+
// The command line after the program name, as libuv would have built it: verbatim for a batch
|
|
79
|
+
// run (resolveSpawn already quoted it for cmd.exe), libuv's quoting for an image.
|
|
80
|
+
export function jobTail(run) {
|
|
81
|
+
return run.windowsVerbatimArguments ? run.args.join(' ') : run.args.map(winArg).join(' ');
|
|
82
|
+
}
|
|
83
|
+
// `run`, started through the host — or `run` itself where there is no host.
|
|
84
|
+
export function contained(run, host) {
|
|
85
|
+
if (!host.ok)
|
|
86
|
+
return run;
|
|
87
|
+
return {
|
|
88
|
+
file: host.file,
|
|
89
|
+
args: [...HOST_ARGS],
|
|
90
|
+
env: {
|
|
91
|
+
...run.env,
|
|
92
|
+
WITNESS_JOB_FILE: run.file,
|
|
93
|
+
WITNESS_JOB_ARGS: jobTail(run),
|
|
94
|
+
WITNESS_JOB_PSMODULEPATH: envGet(run.env, 'PSMODULEPATH') ?? '',
|
|
95
|
+
WITNESS_JOB_PATHEXT: envGet(run.env, 'PATHEXT') ?? '',
|
|
96
|
+
},
|
|
97
|
+
windowsVerbatimArguments: false,
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
let probed;
|
|
101
|
+
// Whether this process can start commands inside a job: a parent's answer as given, else this
|
|
102
|
+
// process's own probe, run once. Off win32 there are no job objects and nothing is probed.
|
|
103
|
+
export function jobHost(env, platform = process.platform) {
|
|
104
|
+
if (platform !== 'win32')
|
|
105
|
+
return { ok: false, why: `no job objects on ${platform}` };
|
|
106
|
+
const file = system32(env, 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
107
|
+
if (env[JOB_HOST_ENV] === 'job')
|
|
108
|
+
return { ok: true, file };
|
|
109
|
+
if (env[JOB_HOST_ENV] === 'none')
|
|
110
|
+
return { ok: false, why: 'the drive that started this run found none' };
|
|
111
|
+
if (probed !== undefined)
|
|
112
|
+
return probed;
|
|
113
|
+
if (!existsSync(file)) {
|
|
114
|
+
probed = { ok: false, why: `${file} not found` };
|
|
115
|
+
return probed;
|
|
116
|
+
}
|
|
117
|
+
const r = spawnSync(file, HOST_ARGS, {
|
|
118
|
+
env: { ...env, WITNESS_JOB_PROBE: '1' }, encoding: 'utf8', stdio: ['ignore', 'ignore', 'pipe'], timeout: 30_000,
|
|
119
|
+
});
|
|
120
|
+
probed = r.status === 0
|
|
121
|
+
? { ok: true, file }
|
|
122
|
+
: { ok: false, why: ((r.stderr ?? '').split(/\r?\n/u)[0] ?? '').trim().slice(0, 200) || r.error?.message || `exit ${r.status}` };
|
|
123
|
+
return probed;
|
|
124
|
+
}
|
|
125
|
+
// Drive's opening line beside `keep-awake:` — what ends a session's work on this machine.
|
|
126
|
+
export function containmentLine(host, platform = process.platform) {
|
|
127
|
+
if (platform !== 'win32')
|
|
128
|
+
return 'containment: process groups — what a session starts ends with it, unless it leaves the group';
|
|
129
|
+
return host.ok
|
|
130
|
+
? "containment: job objects — what drive's work starts ends with it"
|
|
131
|
+
: `containment: none — ${host.why} · a stopped session's tree is still stopped`;
|
|
132
|
+
}
|
package/dist/drive-presence.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { lstatSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
1
|
+
import { lstatSync, mkdirSync, readFileSync, utimesSync, writeFileSync } from 'node:fs';
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { isAlive, pause, pidOf, releaseIfMine, takeStale } from './lock.js';
|
|
4
4
|
import { ok, refuse, v } from './refusal.js';
|
|
@@ -39,12 +39,25 @@ export const DRIVE_LOCK = '.witness/drive.lock';
|
|
|
39
39
|
export const DRIVE_LOG = '.witness/drive.log';
|
|
40
40
|
// How a background drive learns its own log path, set by `detachDrive` on its child alone.
|
|
41
41
|
export const DRIVE_LOG_ENV = 'WITNESS_DRIVE_LOG';
|
|
42
|
+
// Row 224 (#69). The drive lock is a lease. A pid alone outlives its drive: a drive stopped
|
|
43
|
+
// hard (`taskkill /F`, `kill -9`, a reboot) never runs its `finally`, and once that pid is
|
|
44
|
+
// reused the lock read as a running drive and its printed stop aimed at an unrelated tree. The
|
|
45
|
+
// running drive renews the lock's mtime every DRIVE_RENEW_MS; a lock not renewed for
|
|
46
|
+
// DRIVE_LEASE_MS is no drive, whatever its pid. A drive whose host slept renews within a
|
|
47
|
+
// renewal of waking, so a new drive takes over a live pid's expired lease only after
|
|
48
|
+
// DRIVE_TAKEOVER_GRACE_MS without a renewal — never one that wakes in time.
|
|
49
|
+
export const DRIVE_LEASE_MS = 120_000;
|
|
50
|
+
export const DRIVE_RENEW_MS = 10_000;
|
|
51
|
+
export const DRIVE_TAKEOVER_GRACE_MS = 25_000;
|
|
42
52
|
function readHolder(root) {
|
|
43
53
|
const p = join(root, DRIVE_LOCK);
|
|
44
54
|
let text;
|
|
55
|
+
let renewed;
|
|
45
56
|
try {
|
|
46
|
-
|
|
57
|
+
const st = lstatSync(p);
|
|
58
|
+
if (st.isSymbolicLink())
|
|
47
59
|
return 'unreadable';
|
|
60
|
+
renewed = st.mtimeMs;
|
|
48
61
|
text = readFileSync(p, 'utf8');
|
|
49
62
|
}
|
|
50
63
|
catch (e) {
|
|
@@ -57,25 +70,70 @@ function readHolder(root) {
|
|
|
57
70
|
// The lock says only WHETHER a background log exists; its path is always derived. What
|
|
58
71
|
// the file says is never printed: `watch:` is a line the engine acts on, and a path read
|
|
59
72
|
// from a file could carry a newline and a forged `launch:` or `run:` line.
|
|
60
|
-
return { pid: h.pid, ...(h.log !== undefined ? { log: join(root, DRIVE_LOG) } : {}) };
|
|
73
|
+
return { pid: h.pid, renewed, leased: h.lease === 1, ...(h.log !== undefined ? { log: join(root, DRIVE_LOG) } : {}) };
|
|
61
74
|
}
|
|
62
75
|
catch {
|
|
63
76
|
return 'unreadable';
|
|
64
77
|
}
|
|
65
78
|
}
|
|
66
|
-
|
|
67
|
-
|
|
79
|
+
const leaseLive = (h, now) => !h.leased || now - h.renewed < DRIVE_LEASE_MS;
|
|
80
|
+
// A live holder only: a dead one (a drive killed with SIGKILL) reads as none, and so does a
|
|
81
|
+
// live pid whose lease expired (row 224).
|
|
82
|
+
export function driveHolder(root, now = Date.now()) {
|
|
68
83
|
const h = readHolder(root);
|
|
69
|
-
|
|
84
|
+
if (typeof h !== 'object' || !isAlive(h.pid) || !leaseLive(h, now))
|
|
85
|
+
return undefined;
|
|
86
|
+
return { pid: h.pid, ...(h.log !== undefined ? { log: h.log } : {}) };
|
|
70
87
|
}
|
|
71
|
-
|
|
88
|
+
// Row 224. The running drive's renewal: the lock's mtime set to now when the lock is this
|
|
89
|
+
// pid's. A link at the lock path is never followed (utimes would touch what it points at).
|
|
90
|
+
// `false` says the lease is no longer this drive's — taken over, or removed — and the drive
|
|
91
|
+
// that held it stops. A renewal that fails while the lock still names this pid (a scanner
|
|
92
|
+
// holding the file, EBUSY) is retried on the next tick, never read as lost: a lease left
|
|
93
|
+
// unrenewed that long expires, and the next renewal then finds the successor's lock.
|
|
94
|
+
export function renewDriveLock(root, pid = process.pid) {
|
|
95
|
+
const h = readHolder(root);
|
|
96
|
+
if (typeof h !== 'object' || h.pid !== pid)
|
|
97
|
+
return false;
|
|
98
|
+
const p = join(root, DRIVE_LOCK);
|
|
99
|
+
try {
|
|
100
|
+
if (lstatSync(p).isSymbolicLink())
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
catch {
|
|
104
|
+
return false;
|
|
105
|
+
}
|
|
106
|
+
try {
|
|
107
|
+
const now = new Date();
|
|
108
|
+
utimesSync(p, now, now);
|
|
109
|
+
}
|
|
110
|
+
catch { /* still this drive's lock: retried on the next tick */ }
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
// Row 224. The lock holder's renewal, from the moment it holds the lock to its release, so a
|
|
114
|
+
// drive waiting on a session, a usage pause or a human's answer alike keeps its lease. The
|
|
115
|
+
// timer never keeps the process alive. `onLost` runs once, when the lease is no longer this
|
|
116
|
+
// pid's, and the renewal stops.
|
|
117
|
+
export function holdLease(root, onLost, everyMs = DRIVE_RENEW_MS, pid = process.pid) {
|
|
118
|
+
const timer = setInterval(() => {
|
|
119
|
+
if (renewDriveLock(root, pid))
|
|
120
|
+
return;
|
|
121
|
+
clearInterval(timer);
|
|
122
|
+
onLost();
|
|
123
|
+
}, everyMs);
|
|
124
|
+
timer.unref();
|
|
125
|
+
return () => clearInterval(timer);
|
|
126
|
+
}
|
|
127
|
+
export function acquireDriveLock(root, info, pid = process.pid, graceMs = DRIVE_TAKEOVER_GRACE_MS) {
|
|
72
128
|
const p = join(root, DRIVE_LOCK);
|
|
73
129
|
mkdirSync(join(root, '.witness'), { recursive: true });
|
|
74
130
|
const release = () => releaseIfMine(p, pid);
|
|
75
|
-
|
|
131
|
+
let t0 = Date.now();
|
|
132
|
+
// Row 224. When this drive first saw a live pid's lease expired, and how renewed it was then.
|
|
133
|
+
let expired;
|
|
76
134
|
for (;;) {
|
|
77
135
|
try {
|
|
78
|
-
writeFileSync(p, JSON.stringify({ pid, ...(info.log !== undefined ? { log: info.log } : {}) }), { flag: 'wx' });
|
|
136
|
+
writeFileSync(p, JSON.stringify({ pid, ...(info.log !== undefined ? { log: info.log } : {}), lease: 1 }), { flag: 'wx' });
|
|
79
137
|
return ok(release);
|
|
80
138
|
}
|
|
81
139
|
catch (e) {
|
|
@@ -86,22 +144,47 @@ export function acquireDriveLock(root, info, pid = process.pid) {
|
|
|
86
144
|
const h = readHolder(root);
|
|
87
145
|
if (typeof h === 'object' && h.pid === pid)
|
|
88
146
|
return ok(release);
|
|
89
|
-
|
|
90
|
-
|
|
147
|
+
const alive = typeof h === 'object' && isAlive(h.pid);
|
|
148
|
+
if (typeof h === 'object' && alive) {
|
|
149
|
+
const running = refuse([v(DRIVE_LOCK, 'drive-running', `pid ${h.pid}`, `one drive per repo — ${watchLine(h)}`)]);
|
|
150
|
+
if (leaseLive(h, Date.now()))
|
|
151
|
+
return running;
|
|
152
|
+
// Expired, but the pid lives: a reused pid, a frozen drive — or a drive whose host just
|
|
153
|
+
// woke, which renews within DRIVE_RENEW_MS. Watched for the grace; a renewal refuses.
|
|
154
|
+
if (expired === undefined || expired.pid !== h.pid)
|
|
155
|
+
expired = { pid: h.pid, renewed: h.renewed, since: Date.now() };
|
|
156
|
+
else if (h.renewed !== expired.renewed)
|
|
157
|
+
return running;
|
|
158
|
+
if (Date.now() - expired.since < graceMs) {
|
|
159
|
+
pause(Math.min(250, graceMs));
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
t0 = Math.max(t0, expired.since + graceMs);
|
|
91
163
|
}
|
|
92
164
|
if (Date.now() - t0 > 5_000) {
|
|
93
165
|
return refuse([v(DRIVE_LOCK, 'drive-running', 'the lock changed hands while it was being taken', 'run this again')]);
|
|
94
166
|
}
|
|
95
167
|
// `wx` creates the file empty before the pid lands: an unreadable lock gets the repo
|
|
96
168
|
// lock's grace before it counts as a dead drive's. A dead one is taken atomically
|
|
97
|
-
// (F15), so of several drives started at once exactly one gets in
|
|
169
|
+
// (F15), so of several drives started at once exactly one gets in; an expired lease is
|
|
170
|
+
// taken only while it stays as the grace saw it (same pid, not renewed).
|
|
98
171
|
if (h === 'unreadable') {
|
|
99
172
|
pause(50);
|
|
100
173
|
if (Date.now() - t0 < 1_000)
|
|
101
174
|
continue;
|
|
102
175
|
}
|
|
103
176
|
try {
|
|
104
|
-
const
|
|
177
|
+
const stale = (text) => {
|
|
178
|
+
if (typeof h !== 'object')
|
|
179
|
+
return pidOf(text) === undefined;
|
|
180
|
+
if (pidOf(text) !== h.pid)
|
|
181
|
+
return false;
|
|
182
|
+
if (!alive)
|
|
183
|
+
return true;
|
|
184
|
+
const now = readHolder(root);
|
|
185
|
+
return typeof now === 'object' && now.pid === h.pid && now.renewed === h.renewed;
|
|
186
|
+
};
|
|
187
|
+
const took = takeStale(p, stale);
|
|
105
188
|
if (took === 'busy')
|
|
106
189
|
pause(50);
|
|
107
190
|
}
|