mirror of
https://github.com/garrytan/gstack.git
synced 2026-11-18 22:24:17 +01:00
Check a question against the owner's earlier answers before asking it again (GST-3025) (#4467)
An agent can now check a draft question against the owner's earlier answers before sending it, so the owner isn't asked again about something they already said yes to. Why: owners repeat "don't ask me, just do it" across threads, because each new session forgets earlier answers. In a four-day sample, about 1% of 444 asks were repeats this could skip, so a two-week pilot decides whether it's kept. Nothing to do: the new command is opt-in, and no existing command, install output or factory rule changes. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=testing Review-Finding: p1/specialist-batched#2 reader=state-machines Review-Finding: p1/red-team#1 reader=red-team Review-Finding: p1/red-team#2 reader=red-team Review-Finding: p3/outside-voice#1 reader=outside-voice Review-Finding: p3/outside-voice#2 reader=outside-voice
This commit is contained in:
1 parent
d3d35019a0
commit
0b656a171d
8 files changed
+1213
No files matched your search
@@ -378,6 +378,15 @@ gstack_result_anchor() {
|
||||
APPROVAL_RECORD_UNAVAILABLE) printf '%s' 'approval-record-unavailable' ;;
|
||||
APPROVAL_RECORD_WRITE_FAILED) printf '%s' 'approval-record-write-failed' ;;
|
||||
APPROVAL_IMPORT_UNANSWERED) printf '%s' 'approval-import-unanswered' ;;
|
||||
OWNER_ANSWERS_NO_DRIVE) printf '%s' 'owner-answers-no-drive' ;;
|
||||
OWNER_ANSWERS_AMBIGUOUS) printf '%s' 'owner-answers-ambiguous' ;;
|
||||
OWNER_ANSWERS_INVALID) printf '%s' 'owner-answers-invalid' ;;
|
||||
OWNER_ANSWERS_SECRET) printf '%s' 'owner-answers-secret' ;;
|
||||
OWNER_ANSWERS_WRITE_FAILED) printf '%s' 'owner-answers-write-failed' ;;
|
||||
OWNER_ANSWERS_NOT_FOUND) printf '%s' 'owner-answers-not-found' ;;
|
||||
OWNER_ANSWERS_CONFLICT) printf '%s' 'owner-answers-conflict' ;;
|
||||
OWNER_ANSWERS_SELF_VERIFY) printf '%s' 'owner-answers-self-verify' ;;
|
||||
OWNER_ANSWERS_NOT_TAKEABLE) printf '%s' 'owner-answers-not-takeable' ;;
|
||||
CAPTAIN_BRIEF_INCOMPLETE) printf '%s' 'captain-brief-incomplete' ;;
|
||||
PR_SHOTS_INPUT_NOT_FOUND) printf '%s' 'pr-shots-input-not-found' ;;
|
||||
PR_SHOTS_INPUT_REFUSED) printf '%s' 'pr-shots-input-refused' ;;
|
||||
|
||||
Executable
+164
@@ -0,0 +1,164 @@
|
||||
#!/usr/bin/env -S bun --no-env-file --config=/dev/null
|
||||
/**
|
||||
* gstack-owner-answers — the owner's record of answers and standing yeses, read before any ask to the
|
||||
* owner (docs/owner-answers.md). Logic: lib/owner-answers.ts.
|
||||
*
|
||||
* gstack-owner-answers add --action <token> --target <token> --words <their exact words> --thread <code> --event <id>
|
||||
* --by <who records it> [--kind standing-yes|decision|preference|ruling-ref] [--scope all|repo:<o/n>|captain:<name>]
|
||||
* [--limits <text>] [--words-by owner|agent:<id>] [--rule R<n>] [--asked <the ask it answered>] [--json]
|
||||
* gstack-owner-answers supersede <row id> (the add flags) | revoke <row id> --words <…> --thread <code> --event <id> --by <who>
|
||||
* gstack-owner-answers verify <row id> --event <the source event it read> --by <a second actor>
|
||||
* gstack-owner-answers check --ask-file <file> [--all] [--json] related answers per ask line (advisory)
|
||||
* gstack-owner-answers screen --ask-file <file> [--json] KEEP or PROPOSE_TAKE per line; never edits the ask
|
||||
* gstack-owner-answers log --thread <code> --line <letter> --decision taken|asked [--row <id>] --by <who>
|
||||
* gstack-owner-answers list [--all] [--json] | status
|
||||
* Every command takes [--owner <name>] (on Capy: which user-<name> Drive folder, when more than one is mounted).
|
||||
*/
|
||||
import * as fs from 'node:fs';
|
||||
import { EXIT, exitTableHelp } from '../lib/headless-artifacts';
|
||||
import { resultLine } from '../lib/result-codes';
|
||||
import {
|
||||
addAnswer, buildAnswer, currentRows, isAnswerError, logDecision, notTakeable, parseAskFile, rankRows, readStore, resolveStore,
|
||||
screenAsks, takenLine, verifyAnswer, type AnswerError, type NewAnswer, type OwnerAnswer, type Store,
|
||||
} from '../lib/owner-answers';
|
||||
|
||||
const HELP = `gstack-owner-answers — the owner's answers and standing yeses, checked before any ask (docs/owner-answers.md)
|
||||
|
||||
add --action <token> --target <token> --words <the owner's exact words> --thread <code> --event <id> --by <who records it>
|
||||
[--kind standing-yes|decision|preference|ruling-ref] [--scope all|repo:<owner>/<name>|captain:<name>] [--limits <text>]
|
||||
[--words-by owner|agent:<id>] [--rule R<n>] [--asked <the ask it answered>]
|
||||
one row, written once; --words-by defaults to agent:<by>, and only owner rows can ever be taken
|
||||
supersede <row id> (add's flags) a new row that replaces <row id>
|
||||
revoke <row id> --words <the owner's words> --thread <code> --event <id> --by <who> the row stops counting
|
||||
verify <row id> --event <id> --by <who> a second actor reads the cited source event, names it, and confirms it
|
||||
holds the row's words; the recorder cannot
|
||||
check --ask-file <file> [--all] related answers per ask line, ranked by shared words (advisory; never a take)
|
||||
screen --ask-file <file> per line: KEEP <reason> or PROPOSE_TAKE <row id>, with the line the Captain adds when it
|
||||
confirms the take; the ask file is never edited. A take needs origin "captain", a typed action, target and scope,
|
||||
no fresh-ask class, and a verified, current, unlimited standing-yes row matching exactly
|
||||
log --thread <code> --line <letter> --decision taken|asked [--row <id>] --by <who> the thread's own log line
|
||||
list [--all] current rows (--all adds superseded and revoked ones)
|
||||
status where the record is, how many rows, how many can be taken, and any problem
|
||||
Every command takes [--owner <name>] and [--json] where it prints rows.
|
||||
|
||||
${exitTableHelp()}`;
|
||||
|
||||
const VALUE_FLAGS = new Set(['--action', '--target', '--words', '--thread', '--event', '--by', '--kind', '--scope', '--limits', '--words-by', '--rule', '--asked', '--ask-file', '--line', '--decision', '--row', '--owner']);
|
||||
|
||||
function parse(args: string[]): { pos: string[]; flags: Record<string, string>; bools: Set<string>; error?: string } {
|
||||
const pos: string[] = []; const flags: Record<string, string> = {}; const bools = new Set<string>();
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const a = args[i]!;
|
||||
if (VALUE_FLAGS.has(a)) {
|
||||
const v = args[i + 1];
|
||||
if (v === undefined) return { pos, flags, bools, error: `${a} needs a value` };
|
||||
flags[a] = v; i++;
|
||||
} else if (a === '--json' || a === '--all') bools.add(a);
|
||||
else if (a.startsWith('--')) return { pos, flags, bools, error: `unknown argument ${a}` };
|
||||
else pos.push(a);
|
||||
}
|
||||
return { pos, flags, bools };
|
||||
}
|
||||
|
||||
function fail(cmd: string, e: AnswerError): number {
|
||||
process.stderr.write(resultLine(`gstack-owner-answers ${cmd}`, e.code, e.message) + '\n');
|
||||
if (e.code === 'OWNER_ANSWERS_INVALID') return EXIT.usage;
|
||||
if (e.code === 'OWNER_ANSWERS_WRITE_FAILED') return EXIT.fail;
|
||||
return EXIT.refused;
|
||||
}
|
||||
|
||||
const newAnswer = (f: Record<string, string>, extra: Partial<NewAnswer> = {}): NewAnswer => ({
|
||||
kind: f['--kind'], action: f['--action'], target: f['--target'], scope: f['--scope'], limits: f['--limits'], words: f['--words'],
|
||||
words_by: f['--words-by'], thread: f['--thread'], event: f['--event'], rule: f['--rule'], asked: f['--asked'], by: f['--by'], ...extra,
|
||||
});
|
||||
|
||||
const brief = (r: OwnerAnswer) => `${r.id} ${r.kind} ${r.action || '-'} ${r.target || '-'} ${r.scope} "${r.words.replace(/\s+/g, ' ').slice(0, 120)}" (${r.recorded_at.slice(0, 10)}, ${r.source.thread}, words_by=${r.words_by})`;
|
||||
|
||||
function write(cmd: string, store: Store, input: NewAnswer, json: boolean): number {
|
||||
const row = buildAnswer(store, input);
|
||||
if (isAnswerError(row)) return fail(cmd, row);
|
||||
const res = addAnswer(store, row);
|
||||
if (isAnswerError(res)) return fail(cmd, res);
|
||||
if (json) process.stdout.write(JSON.stringify({ id: row.id, status: res }) + '\n');
|
||||
else process.stdout.write(`OWNER_ANSWER_RECORDED: ${row.id}${res === 'present' ? ' (already present)' : ''}\n`);
|
||||
return EXIT.ok;
|
||||
}
|
||||
|
||||
function askFile(cmd: string, file: string | undefined) {
|
||||
if (!file) return { code: 'OWNER_ANSWERS_INVALID', message: '--ask-file <file> is required' } as AnswerError;
|
||||
let text: string;
|
||||
try { text = fs.readFileSync(file, 'utf8'); } catch (e: any) { return { code: 'OWNER_ANSWERS_INVALID', message: `--ask-file ${file}: ${e?.code ?? e?.message}` } as AnswerError; }
|
||||
return parseAskFile(text);
|
||||
}
|
||||
|
||||
function main(argv: string[]): number {
|
||||
const [cmd, ...rest] = argv;
|
||||
if (!cmd || cmd === '--help' || cmd === '-h' || cmd === 'help') { process.stdout.write(HELP + '\n'); return cmd ? EXIT.ok : EXIT.usage; }
|
||||
const { pos, flags, bools, error } = parse(rest);
|
||||
if (error) { process.stderr.write(`gstack-owner-answers: ${error}\n`); return EXIT.usage; }
|
||||
const json = bools.has('--json');
|
||||
const store = resolveStore(process.env, flags['--owner']);
|
||||
if (isAnswerError(store)) return fail(cmd, store);
|
||||
switch (cmd) {
|
||||
case 'add': return write(cmd, store, newAnswer(flags), json);
|
||||
case 'supersede': return pos[0] ? write(cmd, store, newAnswer(flags, { supersedes: pos[0] }), json) : fail(cmd, { code: 'OWNER_ANSWERS_INVALID', message: 'supersede <row id>' });
|
||||
case 'revoke': return pos[0] ? write(cmd, store, newAnswer(flags, { kind: 'revoke', supersedes: pos[0] }), json) : fail(cmd, { code: 'OWNER_ANSWERS_INVALID', message: 'revoke <row id>' });
|
||||
case 'verify': {
|
||||
if (!pos[0]) return fail(cmd, { code: 'OWNER_ANSWERS_INVALID', message: 'verify <row id> --event <id> --by <who>' });
|
||||
const res = verifyAnswer(store, pos[0], flags['--by'] ?? '', flags['--event'] ?? '');
|
||||
if (isAnswerError(res)) return fail(cmd, res);
|
||||
process.stdout.write(`OWNER_ANSWER_VERIFIED: ${pos[0]}${res === 'present' ? ' (already present)' : ''}\n`);
|
||||
return EXIT.ok;
|
||||
}
|
||||
case 'check': case 'screen': {
|
||||
const asks = askFile(cmd, flags['--ask-file']);
|
||||
if (isAnswerError(asks)) return fail(cmd, asks);
|
||||
const read = readStore(store);
|
||||
if (cmd === 'check') {
|
||||
const rows = bools.has('--all') ? read.rows : currentRows(read);
|
||||
const out = asks.map(a => ({ line: a.line, related: rankRows(rows, a, bools.has('--all') ? rows.length : 5).map(x => ({ id: x.row.id, score: x.score, takeable: !notTakeable(x.row, read), row: x.row })) }));
|
||||
if (json) { process.stdout.write(JSON.stringify({ state: read.state, problems: read.problems, asks: out }) + '\n'); return EXIT.ok; }
|
||||
process.stdout.write(`RECORD: ${read.state}${read.problems.length ? ` (${read.problems.length} problem(s); see status)` : ''}\n`);
|
||||
for (const a of out) {
|
||||
process.stdout.write(`LINE ${a.line}: ${a.related.length} related\n`);
|
||||
for (const r of a.related) process.stdout.write(` ${r.takeable ? 'TAKEABLE' : 'CONTEXT'} ${brief(r.row)}\n`);
|
||||
}
|
||||
return EXIT.ok;
|
||||
}
|
||||
const screened = screenAsks(asks, read);
|
||||
if (json) { process.stdout.write(JSON.stringify({ state: read.state, problems: read.problems, lines: screened.map(s => ({ ...s, taken_line: s.take ? takenLine(s.take) : undefined })) }) + '\n'); return EXIT.ok; }
|
||||
for (const s of screened) {
|
||||
if (s.verdict === 'PROPOSE_TAKE') process.stdout.write(`PROPOSE_TAKE ${s.line} ${s.take!.id}: ${takenLine(s.take!)}\n`);
|
||||
else process.stdout.write(`KEEP ${s.line}: ${s.reason}\n`);
|
||||
for (const r of s.related.filter(r => r.id !== s.take?.id)) process.stdout.write(` CONTEXT ${brief(r)}\n`);
|
||||
}
|
||||
process.stdout.write(`SCREENED: ${screened.length} line(s), ${screened.filter(s => s.verdict === 'PROPOSE_TAKE').length} proposed take(s); confirm each, then log it\n`);
|
||||
return EXIT.ok;
|
||||
}
|
||||
case 'log': {
|
||||
const res = logDecision(store, { thread: flags['--thread'] ?? '', line: flags['--line'] ?? '', decision: flags['--decision'] ?? '', row: flags['--row'], by: flags['--by'] ?? '' });
|
||||
if (isAnswerError(res)) return fail(cmd, res);
|
||||
process.stdout.write(`OWNER_ANSWER_LOGGED: ${flags['--decision']} ${flags['--line']}${flags['--row'] ? ` ${flags['--row']}` : ''}\n`);
|
||||
return EXIT.ok;
|
||||
}
|
||||
case 'list': {
|
||||
const read = readStore(store);
|
||||
const rows = bools.has('--all') ? read.rows : currentRows(read);
|
||||
if (json) process.stdout.write(JSON.stringify({ state: read.state, rows }) + '\n');
|
||||
else for (const r of rows) process.stdout.write(`${notTakeable(r, read) ? 'CONTEXT ' : 'TAKEABLE'} ${brief(r)}\n`);
|
||||
return EXIT.ok;
|
||||
}
|
||||
case 'status': {
|
||||
const read = readStore(store);
|
||||
const current = currentRows(read);
|
||||
process.stdout.write(`RECORD: ${store.dir}\nOWNER: ${store.owner}\nSTATE: ${read.state}\nROWS: ${read.rows.length} current=${current.length} takeable=${current.filter(r => !notTakeable(r, read)).length} verifications=${read.verifications.length}\n`);
|
||||
for (const p of read.problems) process.stdout.write(`PROBLEM: ${p}\n`);
|
||||
return EXIT.ok;
|
||||
}
|
||||
default:
|
||||
process.stderr.write(`gstack-owner-answers: unknown command ${cmd}\n`);
|
||||
return EXIT.usage;
|
||||
}
|
||||
}
|
||||
|
||||
process.exitCode = main(process.argv.slice(2));
|
||||
@@ -0,0 +1,4 @@
|
||||
---
|
||||
bump: minor
|
||||
---
|
||||
- **A Captain can check an ask against the owner's earlier answers before sending it.** `gstack-owner-answers` keeps the owner's answers and standing yeses in one record, outside every repository: on Capy it is the owner's private Drive folder, which every thread the owner runs can read. `screen --ask-file` reads a Captain's draft ask and proposes leaving out only the lines that a verified, current standing yes in the owner's own words covers exactly. Every other line stays in, with any related answers shown beside it. That includes autoplan gate items, untyped or compound lines, and anything that always needs a fresh ask (product decisions, spend over a cap, access, publishing, thresholds, closing a contribution, destructive steps). A damaged, conflicting or unreadable record keeps every ask. Rows are one file each, written once; a row needs a second actor to verify its words before it can be taken, and the recorder can't verify its own. The file format and the two-week pilot are in docs/owner-answers.md.
|
||||
@@ -0,0 +1,201 @@
|
||||
# The owner's answers: check before you ask
|
||||
|
||||
An agent that asks its owner something the owner already answered wastes the owner's
|
||||
time. On a host where every session starts on a fresh machine (Capy cloud machines), the
|
||||
agent has no memory of the earlier answer. `gstack-owner-answers` keeps the owner's
|
||||
answers and standing yeses in one record, kept where every session the owner runs can read it.
|
||||
A Captain screens each ask against that record before sending it.
|
||||
|
||||
gstack ships the command and this file format. It never ships anyone's answers: the
|
||||
record lives outside every repository, and the tests use made-up owners.
|
||||
|
||||
## How much it helps (measured before launch)
|
||||
|
||||
The first measurement was a sample of four days of one owner's Captain threads: 444
|
||||
asks reached the owner.
|
||||
|
||||
- 6 were already covered by an earlier answer.
|
||||
- 14 were covered but had to go to the owner anyway (spend, access, publishing and the like).
|
||||
- The rest were new questions.
|
||||
|
||||
Only about 3 of the 6 were standing yeses this tool could ever take, so about 1% of
|
||||
asks were repeats it could skip. That is small. The pilot below measures it again
|
||||
after launch, and the pilot's result decides whether the tool is kept or cut.
|
||||
|
||||
## Where the record lives
|
||||
|
||||
| Host | Record |
|
||||
|---|---|
|
||||
| Capy (`GSTACK_CAPY=1`) | `~/.capy/drive/user-<owner>/owner-answers/`, the owner's private user-level Drive folder. It is mounted in every thread the owner owns, in every project, subagents included. |
|
||||
| Anywhere else | `$GSTACK_OWNER_ANSWERS_DIR`, else `<state root>/owner-answers/` |
|
||||
|
||||
On Capy the record is bound to the one mounted `user-*` folder, or to the one
|
||||
`--owner <name>` names. No folder (`OWNER_ANSWERS_NO_DRIVE`) or several
|
||||
(`OWNER_ANSWERS_AMBIGUOUS`) stops the command. It never falls back to the machine's
|
||||
thrown-away state root, and `GSTACK_OWNER_ANSWERS_DIR` is ignored there.
|
||||
The record's own folders (`owner-answers/`, `rows/`, `verifications/`, `log/`) must
|
||||
resolve inside that folder (elsewhere, inside the record): a link that leads out of it
|
||||
is refused (`OWNER_ANSWERS_INVALID`), and the record is not read through it.
|
||||
`gstack-owner-answers status` prints the path. It is the only command that does, so
|
||||
ordinary output never names the owner's folder.
|
||||
|
||||
## File format (schema_version 1)
|
||||
|
||||
```text
|
||||
owner-answers/
|
||||
rows/<id>.json one answer, created once with O_EXCL, never edited
|
||||
verifications/<row id>--<key>.json a second actor's confirmation of a row's words
|
||||
log/<thread>.jsonl one thread's taken and asked decisions (that thread is its only writer)
|
||||
```
|
||||
|
||||
A row:
|
||||
|
||||
| Field | Meaning |
|
||||
|---|---|
|
||||
| `id` | `oa-` plus 16 hex characters: a hash of owner, kind, action, target, scope, source thread, source event and supersedes. The same answer recorded twice is one file. |
|
||||
| `owner` | The folder's owner. Rows for another owner make the record uncertain. |
|
||||
| `kind` | `standing-yes` (may be taken), or `decision`, `preference`, `ruling-ref` (context only), or `revoke` |
|
||||
| `action`, `target` | One lower-case token each, such as `merge-when-green` / `pull-request`. A take needs exact equality with the ask's tags. |
|
||||
| `scope` | `all`, `repo:<owner>/<name>` or `captain:<name>`. A row's scope covers an ask with the same scope; `all` covers every scope. Record a Captain's grant with its `captain:` scope, never a wider one. |
|
||||
| `limits` | Free text. A row with limits is context only, because the tool cannot check them. |
|
||||
| `words` | The owner's exact words, secret-scanned, at most 2,000 characters |
|
||||
| `words_by` | `owner` when these are the owner's own words at the source, else `agent:<id>` (the default) |
|
||||
| `source` | `{ "thread": <code>, "event": <id> }`: where the owner said it |
|
||||
| `rule` | Optional rule id (`R6`) when the answer is a ruling kept in a rules file. The rules file stays the ruling's home, and the record only points at it. |
|
||||
| `asked` | The question it answered, when there was one |
|
||||
| `supersedes` | The row this one replaces (`supersede`) or cancels (`revoke`) |
|
||||
| `recorded_by`, `recorded_at` | Who wrote the row, and when |
|
||||
|
||||
A verification is `{ schema_version, row, verified_by, verified_at, words_sha256 }`.
|
||||
The verifier reads the cited source event itself, and names it with `--event`, which
|
||||
must equal the row's source event. It then confirms that the owner wrote those words
|
||||
there, granting that action, target and scope.
|
||||
The recorder can't verify its own row (`OWNER_ANSWERS_SELF_VERIFY`). A
|
||||
verification only counts while the row's words still hash to `words_sha256`.
|
||||
|
||||
### When a row can be taken
|
||||
|
||||
Every one of these must hold:
|
||||
|
||||
1. The record reads cleanly (state `present`).
|
||||
2. The row is a `standing-yes` with `words_by: owner` and no limits.
|
||||
3. No row supersedes or revokes it.
|
||||
4. Someone other than its recorder has verified its words.
|
||||
|
||||
Everything else is shown as context, and the ask still goes to the owner.
|
||||
|
||||
### Fail closed
|
||||
|
||||
`readStore` marks the whole record `uncertain` in any of these cases, and then
|
||||
nothing can be taken:
|
||||
|
||||
- a row file is malformed, misnamed or not a regular file;
|
||||
- a row's id doesn't match its fields;
|
||||
- a row belongs to another owner;
|
||||
- a row supersedes an id that is missing;
|
||||
- two rows supersede the same id.
|
||||
|
||||
A second `add` for the same source, action, target and scope with different words,
|
||||
author or limits is refused (`OWNER_ANSWERS_CONFLICT`). It is never silently kept.
|
||||
So is a `supersede` or `revoke` of a row that another row already replaces: supersede
|
||||
the current row instead. Two such rows can still appear when two machines write at once
|
||||
before their Drives sync, and then the record reads `uncertain` until one row file is removed.
|
||||
|
||||
A write that fails after its file is created removes the file
|
||||
(`OWNER_ANSWERS_WRITE_FAILED`), so it leaves no row and the same command can be rerun.
|
||||
A crash in the middle of a write can still leave an empty file; the record then reads
|
||||
`uncertain` and keeps every ask until that file is removed.
|
||||
|
||||
`status` lists each problem.
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
gstack-owner-answers add --action merge-when-green --target pull-request --scope all \
|
||||
--words "yes merge when green" --words-by owner --thread CAPT-1 --event evt_123 --by "Example Captain"
|
||||
gstack-owner-answers verify oa-0123456789abcdef --event evt_123 --by "second reader"
|
||||
gstack-owner-answers screen --ask-file ask.json
|
||||
gstack-owner-answers log --thread CAPT-1 --line A --decision taken --row oa-0123456789abcdef --by "Example Captain"
|
||||
gstack-owner-answers revoke oa-0123456789abcdef --words "ask me again about merges" --words-by owner --thread CAPT-1 --event evt_456 --by "Example Captain"
|
||||
```
|
||||
|
||||
`check --ask-file` lists the related rows for each ask line, ranked by shared words.
|
||||
The ranking is advisory: a high score never makes a row takeable.
|
||||
|
||||
### The ask file
|
||||
|
||||
The ask file is JSON, one entry per lettered line:
|
||||
|
||||
```json
|
||||
{ "asks": [
|
||||
{ "line": "A", "origin": "captain", "text": "Merge #12 now that it is green?",
|
||||
"action": "merge-when-green", "target": "pull-request", "scope": "repo:example/widgets" },
|
||||
{ "line": "B", "origin": "captain", "text": "Spend $400 on the eval rerun?", "classes": ["spend-over-cap"] }
|
||||
] }
|
||||
```
|
||||
|
||||
A plain-text file with one ask per line also works. Its lines are untyped, so
|
||||
`screen` keeps all of them, and only `check` is useful on it.
|
||||
|
||||
`screen` keeps a line (`KEEP <reason>`) when any of these holds:
|
||||
|
||||
- `origin` isn't `captain`. An autoplan gate item is answered at its gate and is never screened out, because dropping it would change what "do it" approves.
|
||||
- `compound` is true, or the ask carries `limits` (an amount, a count, a deadline).
|
||||
- It carries a fresh-ask class, or its words trip the fresh-ask keyword net.
|
||||
- Its action, target or scope is missing.
|
||||
- No takeable row matches it exactly.
|
||||
- A matching row that can't be taken is newer than the takeable one, or narrower in scope (a
|
||||
`repo:` or `captain:` row beside an `all` row). A later "no" or a scoped exception wins over an
|
||||
older blanket yes.
|
||||
|
||||
Otherwise it prints `PROPOSE_TAKE <line> <row id>` and the line the Captain adds to
|
||||
its message, for example `Not asked, you already said: "yes merge when green" (2026-10-16, CAPT-1, R6).`
|
||||
|
||||
`screen` never edits the ask. The Captain confirms each proposal, sends the rest, and
|
||||
logs both outcomes.
|
||||
|
||||
### Fresh-ask classes
|
||||
|
||||
Fresh-ask classes are never taken from the record. They are the "Always a fresh ask" list in
|
||||
[capy/skill/gstack/captain.md](../capy/skill/gstack/captain.md), with these tags:
|
||||
|
||||
| Tag | Covers |
|
||||
|---|---|
|
||||
| `product-decision` | Product and behaviour decisions |
|
||||
| `spend-over-cap` | Spend over a stated cap |
|
||||
| `access` | Access and credentials |
|
||||
| `publish` | Anything published outside the repository |
|
||||
| `threshold-change` | Thresholds, budgets, trial counts and test kinds |
|
||||
| `close-contribution` | Closing someone's contribution without landing it |
|
||||
| `destructive` | Anything destructive or irreversible |
|
||||
|
||||
An unknown tag keeps the line too.
|
||||
|
||||
## The pilot
|
||||
|
||||
The first version runs as a pilot on one Captain's own asks for two weeks:
|
||||
|
||||
1. Before each ask to the owner, the Captain writes the ask file and runs `screen`.
|
||||
2. The Captain reads every `PROPOSE_TAKE` itself before leaving that line out. A wrong proposal stops the pilot and gets corrected; it is never averaged away.
|
||||
3. The Captain logs every line as `taken` or `asked`.
|
||||
|
||||
The pilot's numbers are counted against a baseline taken before launch:
|
||||
|
||||
- asks the owner received that an earlier answer of theirs already covered;
|
||||
- wrong takes, from an audit of taken rows.
|
||||
|
||||
Only after a keep decision does gstack's shared factory guidance tell every Captain to screen.
|
||||
|
||||
**Known limit.** A Drive that hasn't finished syncing a newer supersede or revoke
|
||||
looks exactly like a record without one. The tool can't detect that lag, which is
|
||||
one reason the pilot Captain reads every proposal before leaving an ask out.
|
||||
|
||||
## Export to a knowledge base (format only)
|
||||
|
||||
Each current row maps to one page:
|
||||
|
||||
- title: `<action> <target> (<scope>)`;
|
||||
- body: the words, quoted, with the source thread and date;
|
||||
- tags: `owner-answer` and the kind.
|
||||
|
||||
Nothing in gstack writes such an export yet.
|
||||
@@ -2134,6 +2134,74 @@ per-thread approval record), `gstack-owner-brief render --captain` (the plan ask
|
||||
the before/after shape) and `gstack-pr-shots` (before/after images for a PR body).
|
||||
The guide is `capy/skill/gstack/captain.md`.
|
||||
|
||||
<a id="owner-answers-no-drive"></a>
|
||||
### `gstack-owner-answers: ... (OWNER_ANSWERS_NO_DRIVE)`
|
||||
|
||||
**Meaning.** On Capy the owner record lives only in the owner's own Drive folder
|
||||
(`~/.capy/drive/user-<owner>/owner-answers/`), and none is mounted, or `--owner` names
|
||||
one that is not. Exit 3. The tool never falls back to the machine's thrown-away state
|
||||
root, so nothing can be taken and every ask goes to the owner. See
|
||||
[owner-answers.md](owner-answers.md).
|
||||
|
||||
<a id="owner-answers-ambiguous"></a>
|
||||
### `gstack-owner-answers: ... (OWNER_ANSWERS_AMBIGUOUS)`
|
||||
|
||||
**Meaning.** Two or more `user-*` Drive folders are mounted, so the tool cannot tell
|
||||
whose record to use. Exit 3. Pass `--owner <name>`.
|
||||
|
||||
<a id="owner-answers-invalid"></a>
|
||||
### `gstack-owner-answers: ... (OWNER_ANSWERS_INVALID)`
|
||||
|
||||
**Meaning.** A required flag is missing, a value is outside its format (an action or
|
||||
target that is not one lower-case token, a scope other than `all`,
|
||||
`repo:<owner>/<name>` or `captain:<name>`, a rule id not like `R6`), a field is
|
||||
longer than its cap, or the ask file is not the JSON or plain-text form
|
||||
[owner-answers.md](owner-answers.md) describes. Exit 2. Nothing was written.
|
||||
|
||||
<a id="owner-answers-secret"></a>
|
||||
### `gstack-owner-answers: ... (OWNER_ANSWERS_SECRET)`
|
||||
|
||||
**Meaning.** A field matched the secret scanner. Exit 3. Nothing was written; the
|
||||
error names the field and the rule, never the text.
|
||||
|
||||
<a id="owner-answers-write-failed"></a>
|
||||
### `gstack-owner-answers: ... (OWNER_ANSWERS_WRITE_FAILED)`
|
||||
|
||||
**Meaning.** The record directory could not be written. Exit 1. A write that fails
|
||||
after its file is created removes that file, so it leaves no row: fix the path or
|
||||
permissions `gstack-owner-answers status` prints, then rerun the same command. A crash
|
||||
in the middle of a write can still leave an empty file; the record then reads
|
||||
`uncertain` and keeps every ask until that file (named by `status`) is removed.
|
||||
|
||||
<a id="owner-answers-not-found"></a>
|
||||
### `gstack-owner-answers: ... (OWNER_ANSWERS_NOT_FOUND)`
|
||||
|
||||
**Meaning.** `supersede`, `revoke`, `verify` or `log --decision taken` named a row id
|
||||
that is not in the record. Exit 3.
|
||||
|
||||
<a id="owner-answers-conflict"></a>
|
||||
### `gstack-owner-answers: ... (OWNER_ANSWERS_CONFLICT)`
|
||||
|
||||
**Meaning.** One source, action, target and scope make one row id, and that row
|
||||
already holds different words, a different author or different limits; or a
|
||||
`supersede` or `revoke` names a row that another row already replaces. Exit 3.
|
||||
Nothing was written. Check what the owner said at that source, then record the
|
||||
correction with `supersede <row id>` on the current row (`list --all` shows which
|
||||
row replaced which).
|
||||
|
||||
<a id="owner-answers-self-verify"></a>
|
||||
### `gstack-owner-answers: ... (OWNER_ANSWERS_SELF_VERIFY)`
|
||||
|
||||
**Meaning.** The actor that recorded the row tried to verify it. Exit 3. A second
|
||||
actor reads the cited thread event and verifies under its own name.
|
||||
|
||||
<a id="owner-answers-not-takeable"></a>
|
||||
### `gstack-owner-answers: ... (OWNER_ANSWERS_NOT_TAKEABLE)`
|
||||
|
||||
**Meaning.** `log --decision taken` named a row that cannot be taken (not a
|
||||
verified, current, unlimited standing yes in the owner's own words, or the record is
|
||||
uncertain). Exit 3. Send the ask to the owner and log it as `asked`.
|
||||
|
||||
<a id="approval-record-invalid"></a>
|
||||
### `gstack-approvals: ... (APPROVAL_RECORD_INVALID)`
|
||||
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
/**
|
||||
* owner-answers — the owner's record of answers and standing yeses that a thread reads before it asks
|
||||
* the owner anything (docs/owner-answers.md). The record holds the owner's own words and lives where
|
||||
* every thread the owner runs can read it: on Capy, the owner's private user-level Drive folder
|
||||
* (`~/.capy/drive/user-<owner>/owner-answers/`); elsewhere, `<state root>/owner-answers/`. gstack ships
|
||||
* only this mechanism and the file format; the rows never enter a repository.
|
||||
*
|
||||
* Layout: `rows/<id>.json` (one answer, written once with O_EXCL; a supersede or revoke is a new row
|
||||
* naming the row it replaces), `verifications/<row id>--<verifier key>.json` (a second actor's
|
||||
* confirmation that the cited source holds the row's words) and `log/<thread>.jsonl` (each thread's
|
||||
* taken and asked decisions; one writer per file).
|
||||
*
|
||||
* Fail closed: an ask is dropped only on the pilot's confirmation of a PROPOSE_TAKE, and screen proposes
|
||||
* one only when the whole record reads cleanly, a verified, current, unlimited standing-yes row
|
||||
* matches the ask's typed action, target and scope exactly, and no newer or narrower matching row says
|
||||
* otherwise. Anything malformed, conflicting, unverified,
|
||||
* superseded, untyped, compound or in a fresh-ask class keeps the ask. One source and action is one row id:
|
||||
* a second add with different words is refused (OWNER_ANSWERS_CONFLICT), never silently kept.
|
||||
*/
|
||||
import { createHash } from 'node:crypto';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import type { ResultCodeName } from './result-codes';
|
||||
import { scan } from './redact-engine';
|
||||
import { resolveStateRoot } from './state-root';
|
||||
|
||||
export const KINDS = ['standing-yes', 'decision', 'preference', 'ruling-ref', 'revoke'] as const;
|
||||
export type Kind = typeof KINDS[number];
|
||||
/** The classes that always need a fresh ask (capy/skill/gstack/captain.md, "Always a fresh ask"). */
|
||||
export const FRESH_ASK_CLASSES = ['product-decision', 'spend-over-cap', 'access', 'publish', 'threshold-change', 'close-contribution', 'destructive'] as const;
|
||||
export type FreshAskClass = typeof FRESH_ASK_CLASSES[number];
|
||||
/** A keyword net over untagged ask text: a hit keeps the ask even when the line was not tagged with the class. */
|
||||
const FRESH_ASK_WORDS: Record<FreshAskClass, RegExp> = {
|
||||
'product-decision': /\b(?:product|feature|design|behaviou?r|scope)\b/i,
|
||||
'spend-over-cap': /\$\s?\d|\b(?:spend|budget|cost|cap|dollars?)\b/i,
|
||||
access: /\b(?:access|credentials?|keys?|tokens?|passwords?|secrets?|sign[ -]?in|log[ -]?in|permissions?)\b/i,
|
||||
publish: /\b(?:publish|post|tweet|release notes?|advisory|announce|blog|email|dm)\b/i,
|
||||
'threshold-change': /\b(?:threshold|trial count|trials|test kind|pass rate|bar)\b/i,
|
||||
'close-contribution': /\b(?:close (?:their|the|a|his|her) (?:pr|pull request|contribution)|decline|reject (?:the )?(?:pr|contribution))\b/i,
|
||||
destructive: /\b(?:delete|destroy|drop|wipe|force[- ]push|rotate|revoke|irreversible|purge|reset)\b/i,
|
||||
};
|
||||
export const CAPS = { action: 60, target: 120, scope: 160, limits: 300, words: 2000, asked: 300, thread: 80, event: 120, rule: 20, by: 120 } as const;
|
||||
const TOKEN = /^[a-z0-9][a-z0-9-]{0,59}$/;
|
||||
const SCOPE = /^(?:all|repo:[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+|captain:[a-z0-9][a-z0-9-]{0,59})$/;
|
||||
|
||||
export interface Source { thread: string; event: string }
|
||||
export interface OwnerAnswer {
|
||||
schema_version: 1; id: string; owner: string; kind: Kind; action: string; target: string; scope: string; limits: string;
|
||||
words: string; words_by: string; source: Source; rule: string; asked: string; supersedes: string; recorded_by: string; recorded_at: string;
|
||||
}
|
||||
export interface Verification { schema_version: 1; row: string; verified_by: string; verified_at: string; words_sha256: string }
|
||||
export interface Store { dir: string; owner: string; on_capy: boolean }
|
||||
export interface AnswerError { code: ResultCodeName; message: string }
|
||||
export interface StoreRead {
|
||||
state: 'present' | 'empty' | 'unavailable' | 'uncertain';
|
||||
rows: OwnerAnswer[]; verifications: Verification[]; problems: string[];
|
||||
}
|
||||
|
||||
const sha = (s: string) => createHash('sha256').update(s).digest('hex');
|
||||
const isErr = (x: unknown): x is AnswerError => !!x && typeof x === 'object' && 'code' in (x as object);
|
||||
export { isErr as isAnswerError };
|
||||
|
||||
function contained(root: string, file: string): boolean {
|
||||
const rel = path.relative(root, file);
|
||||
return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel);
|
||||
}
|
||||
|
||||
/**
|
||||
* The owner's store. On Capy (GSTACK_CAPY=1) it is the one mounted `user-<owner>` Drive folder (or the one
|
||||
* --owner names), never an environment override and never the thrown-away state root. Off Capy it is
|
||||
* GSTACK_OWNER_ANSWERS_DIR, else `<state root>/owner-answers`.
|
||||
*/
|
||||
export function resolveStore(env: NodeJS.ProcessEnv, owner?: string): Store | AnswerError {
|
||||
if (env.GSTACK_CAPY === '1') {
|
||||
const drive = path.join(env.HOME || os.homedir(), '.capy', 'drive');
|
||||
let folders: string[];
|
||||
try { folders = fs.readdirSync(drive).filter(d => d.startsWith('user-') && fs.statSync(path.join(drive, d)).isDirectory()); } catch { folders = []; }
|
||||
if (owner) folders = folders.filter(d => d === `user-${owner}`);
|
||||
if (!folders.length) return { code: 'OWNER_ANSWERS_NO_DRIVE', message: owner ? `no mounted Drive folder user-${owner}` : `no user-* folder under ${drive}` };
|
||||
if (folders.length > 1) return { code: 'OWNER_ANSWERS_AMBIGUOUS', message: `${folders.length} user-* folders are mounted; pass --owner <name>` };
|
||||
const folder = path.join(drive, folders[0]!);
|
||||
let real: string;
|
||||
try { real = fs.realpathSync(folder); } catch { return { code: 'OWNER_ANSWERS_NO_DRIVE', message: `${folder} cannot be resolved` }; }
|
||||
const realDrive = fs.realpathSync(drive);
|
||||
if (!contained(realDrive, real)) return { code: 'OWNER_ANSWERS_INVALID', message: `${folder} resolves outside ${drive}` };
|
||||
return { dir: path.join(real, 'owner-answers'), owner: folders[0]!.slice('user-'.length), on_capy: true };
|
||||
}
|
||||
const dir = env.GSTACK_OWNER_ANSWERS_DIR || path.join(resolveStateRoot(env), 'owner-answers');
|
||||
return { dir, owner: owner || env.GSTACK_OWNER || 'owner', on_capy: false };
|
||||
}
|
||||
|
||||
function field(name: keyof typeof CAPS, value: unknown, required: boolean): string | AnswerError {
|
||||
const v = typeof value === 'string' ? value.trim() : '';
|
||||
if (required && !v) return { code: 'OWNER_ANSWERS_INVALID', message: `--${name} is required` };
|
||||
if (v.length > CAPS[name]) return { code: 'OWNER_ANSWERS_INVALID', message: `--${name} is ${v.length} characters (cap ${CAPS[name]})` };
|
||||
if (/[\u0000-\u0008\u000b-\u001f]/.test(v)) return { code: 'OWNER_ANSWERS_INVALID', message: `--${name} holds a control character` };
|
||||
const s = scan(v);
|
||||
if (s.oversize || s.findings.some(f => f.severity === 'HIGH' || f.severity === 'MEDIUM')) return { code: 'OWNER_ANSWERS_SECRET', message: `field ${name}: ${s.oversize ? 'oversize input' : [...new Set(s.findings.map(f => f.id))].join(', ')}` };
|
||||
return v;
|
||||
}
|
||||
|
||||
/** The id is a hash of who said what, where, about which action: the same answer recorded twice is one row. */
|
||||
export function rowId(r: Pick<OwnerAnswer, 'owner' | 'kind' | 'action' | 'target' | 'scope' | 'source' | 'supersedes'>): string {
|
||||
return 'oa-' + sha([r.owner, r.kind, r.action, r.target, r.scope, r.source.thread, r.source.event, r.supersedes].join('\u0000')).slice(0, 16);
|
||||
}
|
||||
|
||||
export interface NewAnswer {
|
||||
kind?: string; action?: string; target?: string; scope?: string; limits?: string; words?: string; words_by?: string;
|
||||
thread?: string; event?: string; rule?: string; asked?: string; supersedes?: string; by?: string;
|
||||
}
|
||||
|
||||
/** Validate and secret-scan one answer; the error names the field and rule, never the text. */
|
||||
export function buildAnswer(store: Store, input: NewAnswer, now = new Date()): OwnerAnswer | AnswerError {
|
||||
const kind = (input.kind ?? 'standing-yes') as Kind;
|
||||
if (!KINDS.includes(kind)) return { code: 'OWNER_ANSWERS_INVALID', message: `--kind must be one of ${KINDS.join('|')}` };
|
||||
const out: Record<string, string> = {};
|
||||
const need: Array<[keyof typeof CAPS, unknown, boolean]> = [
|
||||
['action', input.action, kind !== 'revoke'], ['target', input.target, kind !== 'revoke'], ['scope', input.scope ?? 'all', true],
|
||||
['limits', input.limits, false], ['words', input.words, true], ['thread', input.thread, true], ['event', input.event, true],
|
||||
['rule', input.rule, false], ['asked', input.asked, false], ['by', input.by, true],
|
||||
];
|
||||
for (const [name, value, required] of need) {
|
||||
const v = field(name, value, required);
|
||||
if (isErr(v)) return v;
|
||||
out[name] = v;
|
||||
}
|
||||
if (out.action && !TOKEN.test(out.action)) return { code: 'OWNER_ANSWERS_INVALID', message: '--action must be one lower-case token (letters, digits, hyphens)' };
|
||||
if (out.target && !TOKEN.test(out.target)) return { code: 'OWNER_ANSWERS_INVALID', message: '--target must be one lower-case token (letters, digits, hyphens)' };
|
||||
if (!SCOPE.test(out.scope!)) return { code: 'OWNER_ANSWERS_INVALID', message: '--scope must be all, repo:<owner>/<name> or captain:<name>' };
|
||||
if (out.rule && !/^R\d{1,4}$/.test(out.rule)) return { code: 'OWNER_ANSWERS_INVALID', message: '--rule must look like R6' };
|
||||
const wordsBy = (input.words_by ?? '').trim() || `agent:${out.by}`;
|
||||
if (wordsBy !== 'owner') {
|
||||
if (!/^agent:\S.*$/.test(wordsBy)) return { code: 'OWNER_ANSWERS_INVALID', message: '--words-by must be owner or agent:<id> on one line' };
|
||||
const agent = field('by', wordsBy.slice('agent:'.length), true);
|
||||
if (isErr(agent)) return { code: agent.code, message: agent.message.replace('--by', '--words-by') };
|
||||
}
|
||||
if (kind === 'revoke' && !input.supersedes?.trim()) return { code: 'OWNER_ANSWERS_INVALID', message: 'a revoke names the row it cancels with --supersedes' };
|
||||
const supersedes = (input.supersedes ?? '').trim();
|
||||
if (supersedes && !/^oa-[0-9a-f]{16}$/.test(supersedes)) return { code: 'OWNER_ANSWERS_INVALID', message: '--supersedes must be a row id (oa-…)' };
|
||||
const base = {
|
||||
schema_version: 1 as const, owner: store.owner, kind, action: out.action ?? '', target: out.target ?? '', scope: out.scope!, limits: out.limits ?? '',
|
||||
words: out.words!, words_by: wordsBy, source: { thread: out.thread!, event: out.event! }, rule: out.rule ?? '', asked: out.asked ?? '',
|
||||
supersedes, recorded_by: out.by!, recorded_at: now.toISOString(),
|
||||
};
|
||||
return { id: rowId(base), ...base };
|
||||
}
|
||||
|
||||
function validRow(r: any, owner: string): string | undefined {
|
||||
if (!r || r.schema_version !== 1 || typeof r.id !== 'string') return 'not a v1 row';
|
||||
if (!KINDS.includes(r.kind)) return 'unknown kind';
|
||||
for (const k of ['owner', 'action', 'target', 'scope', 'limits', 'words', 'words_by', 'rule', 'asked', 'supersedes', 'recorded_by', 'recorded_at']) if (typeof r[k] !== 'string') return `field ${k} is not a string`;
|
||||
if (!r.source || typeof r.source.thread !== 'string' || typeof r.source.event !== 'string') return 'no source';
|
||||
if (r.owner !== owner) return 'another owner';
|
||||
if (rowId(r) !== r.id) return 'id does not match its fields';
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function readJsonDir(dir: string): Array<{ name: string; value?: unknown; error?: string }> | 'unavailable' | 'missing' {
|
||||
let names: string[];
|
||||
try { names = fs.readdirSync(dir); } catch (e: any) { return e?.code === 'ENOENT' ? 'missing' : 'unavailable'; }
|
||||
return names.filter(n => n.endsWith('.json')).sort().map(name => {
|
||||
try {
|
||||
const st = fs.lstatSync(path.join(dir, name));
|
||||
if (!st.isFile()) return { name, error: 'not a regular file' };
|
||||
return { name, value: JSON.parse(fs.readFileSync(path.join(dir, name), 'utf8')) };
|
||||
} catch { return { name, error: 'unreadable or not JSON' }; }
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The record and each of its existing directories must resolve inside the owner's folder on Capy (inside the record
|
||||
* itself elsewhere): a link out of it is refused, so a planted link can neither receive rows nor feed them back.
|
||||
*/
|
||||
export function storeEscape(store: Store): AnswerError | undefined {
|
||||
const root = store.on_capy ? path.dirname(store.dir) : store.dir;
|
||||
let realRoot: string;
|
||||
try { realRoot = fs.realpathSync(root); } catch { return undefined; }
|
||||
for (const d of [store.dir, ...['rows', 'verifications', 'log'].map(s => path.join(store.dir, s))]) {
|
||||
let real: string;
|
||||
try { real = fs.realpathSync(d); } catch {
|
||||
try { fs.lstatSync(d); } catch { continue; }
|
||||
return { code: 'OWNER_ANSWERS_INVALID', message: `${path.relative(root, d) || '.'} is a link that cannot be resolved` };
|
||||
}
|
||||
if (real !== realRoot && !contained(realRoot, real)) return { code: 'OWNER_ANSWERS_INVALID', message: `${path.relative(root, d) || '.'} resolves outside the record's folder` };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Every row and verification; any doubt about the whole record makes it `uncertain`, which keeps every ask. */
|
||||
export function readStore(store: Store): StoreRead {
|
||||
const problems: string[] = [];
|
||||
if (!fs.existsSync(store.dir)) return { state: 'empty', rows: [], verifications: [], problems };
|
||||
const escape = storeEscape(store);
|
||||
if (escape) return { state: 'unavailable', rows: [], verifications: [], problems: [escape.message] };
|
||||
const rowFiles = readJsonDir(path.join(store.dir, 'rows'));
|
||||
if (rowFiles === 'unavailable') return { state: 'unavailable', rows: [], verifications: [], problems: ['rows/ cannot be read'] };
|
||||
const rows: OwnerAnswer[] = [];
|
||||
for (const f of rowFiles === 'missing' ? [] : rowFiles) {
|
||||
const bad = f.error ?? validRow(f.value, store.owner) ?? (`${(f.value as OwnerAnswer).id}.json` === f.name ? undefined : 'file name does not match its id');
|
||||
if (bad) problems.push(`rows/${f.name}: ${bad}`);
|
||||
else rows.push(f.value as OwnerAnswer);
|
||||
}
|
||||
const verFiles = readJsonDir(path.join(store.dir, 'verifications'));
|
||||
const verifications: Verification[] = [];
|
||||
if (verFiles === 'unavailable') problems.push('verifications/ cannot be read');
|
||||
for (const f of verFiles === 'missing' || verFiles === 'unavailable' ? [] : verFiles) {
|
||||
const v = f.value as Verification | undefined;
|
||||
if (f.error || !v || v.schema_version !== 1 || typeof v.row !== 'string' || typeof v.verified_by !== 'string' || typeof v.words_sha256 !== 'string') problems.push(`verifications/${f.name}: ${f.error ?? 'not a v1 verification'}`);
|
||||
else verifications.push(v);
|
||||
}
|
||||
const ids = new Set(rows.map(r => r.id));
|
||||
const replacedBy = new Map<string, string[]>();
|
||||
for (const r of rows) if (r.supersedes) replacedBy.set(r.supersedes, [...(replacedBy.get(r.supersedes) ?? []), r.id]);
|
||||
for (const [old, by] of replacedBy) {
|
||||
if (!ids.has(old)) problems.push(`${by.join(', ')} supersede${by.length === 1 ? 's' : ''} ${old}, which is not in the record`);
|
||||
if (by.length > 1) problems.push(`${old} is superseded by ${by.length} rows (${by.join(', ')})`);
|
||||
}
|
||||
rows.sort((a, b) => a.recorded_at.localeCompare(b.recorded_at) || a.id.localeCompare(b.id));
|
||||
return { state: problems.length ? 'uncertain' : rows.length ? 'present' : 'empty', rows, verifications, problems };
|
||||
}
|
||||
|
||||
/** A row is current when no row supersedes it and it is not itself a revoke. */
|
||||
export function currentRows(read: StoreRead): OwnerAnswer[] {
|
||||
const replaced = new Set(read.rows.map(r => r.supersedes).filter(Boolean));
|
||||
return read.rows.filter(r => !replaced.has(r.id) && r.kind !== 'revoke');
|
||||
}
|
||||
|
||||
/** Why a row cannot be taken, or undefined when it can: the owner's own words, verified by someone else, current, unlimited. */
|
||||
export function notTakeable(row: OwnerAnswer, read: StoreRead): string | undefined {
|
||||
if (read.state !== 'present') return `the record is ${read.state}`;
|
||||
if (row.kind !== 'standing-yes') return `a ${row.kind} row is context only`;
|
||||
if (row.words_by !== 'owner') return `the words were typed by ${row.words_by}`;
|
||||
if (row.limits) return 'it carries limits the tool cannot check';
|
||||
if (!currentRows(read).some(r => r.id === row.id)) return 'it was superseded or revoked';
|
||||
const ok = read.verifications.some(v => v.row === row.id && v.verified_by !== row.recorded_by && v.words_sha256 === sha(row.words));
|
||||
return ok ? undefined : 'no second actor has verified its words at the source';
|
||||
}
|
||||
|
||||
/** Create the directory for a record file, checking the record's directories before and after. */
|
||||
function prepareDir(store: Store, file: string): AnswerError | undefined {
|
||||
const before = storeEscape(store);
|
||||
if (before) return before;
|
||||
try { fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 }); } catch (e: any) {
|
||||
return { code: 'OWNER_ANSWERS_WRITE_FAILED', message: `${path.basename(path.dirname(file))}: ${e?.code ?? e?.message}` };
|
||||
}
|
||||
return storeEscape(store);
|
||||
}
|
||||
|
||||
/** One file, created with O_EXCL; a write that fails after the create removes the file, so a retry starts clean. */
|
||||
export function writeExclusive(store: Store, file: string, value: unknown): 'written' | 'present' | AnswerError {
|
||||
const failed = (e: any): AnswerError => ({ code: 'OWNER_ANSWERS_WRITE_FAILED', message: `${path.basename(file)}: ${e?.code ?? e?.message}` });
|
||||
const dir = prepareDir(store, file);
|
||||
if (dir) return dir;
|
||||
let fd: number;
|
||||
try { fd = fs.openSync(file, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY, 0o600); } catch (e: any) {
|
||||
return e?.code === 'EEXIST' ? 'present' : failed(e);
|
||||
}
|
||||
try {
|
||||
fs.writeSync(fd, JSON.stringify(value, null, 1) + '\n');
|
||||
fs.fsyncSync(fd);
|
||||
fs.closeSync(fd);
|
||||
return 'written';
|
||||
} catch (e: any) {
|
||||
try { fs.closeSync(fd); } catch { /* already closed */ }
|
||||
try { fs.unlinkSync(file); } catch { /* left for readStore to report */ }
|
||||
return failed(e);
|
||||
}
|
||||
}
|
||||
|
||||
export function addAnswer(store: Store, row: OwnerAnswer): 'written' | 'present' | AnswerError {
|
||||
if (row.supersedes) {
|
||||
const read = readStore(store);
|
||||
if (!read.rows.some(r => r.id === row.supersedes)) return { code: 'OWNER_ANSWERS_NOT_FOUND', message: `no row ${row.supersedes} to supersede` };
|
||||
const other = read.rows.find(r => r.supersedes === row.supersedes && r.id !== row.id);
|
||||
if (other) return { code: 'OWNER_ANSWERS_CONFLICT', message: `${row.supersedes} is already superseded by ${other.id}; supersede or revoke the current row instead` };
|
||||
}
|
||||
const file = path.join(store.dir, 'rows', `${row.id}.json`);
|
||||
const res = writeExclusive(store, file, row);
|
||||
if (res !== 'present') return res;
|
||||
let have: Partial<OwnerAnswer> = {};
|
||||
try { have = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { /* an unreadable twin is a conflict too */ }
|
||||
return have.words === row.words && have.words_by === row.words_by && have.limits === row.limits
|
||||
? 'present'
|
||||
: { code: 'OWNER_ANSWERS_CONFLICT', message: `${row.id} already records different words, author or limits for this source and action; supersede it instead` };
|
||||
}
|
||||
|
||||
/**
|
||||
* A second actor confirms the cited source holds the row's words: it reads the source event itself and names it
|
||||
* (--event must equal the row's source event). The adder can never verify its own row.
|
||||
*/
|
||||
export function verifyAnswer(store: Store, id: string, by: string, event: string, now = new Date()): 'written' | 'present' | AnswerError {
|
||||
const verifier = field('by', by, true);
|
||||
if (isErr(verifier)) return verifier;
|
||||
const row = readStore(store).rows.find(r => r.id === id);
|
||||
if (!row) return { code: 'OWNER_ANSWERS_NOT_FOUND', message: `no row ${id}` };
|
||||
if (row.recorded_by === verifier) return { code: 'OWNER_ANSWERS_SELF_VERIFY', message: `${id} was recorded by ${verifier}` };
|
||||
if (event.trim() !== row.source.event) return { code: 'OWNER_ANSWERS_INVALID', message: `--event must name the source event the verifier read (${id} cites ${row.source.thread})` };
|
||||
const v: Verification = { schema_version: 1, row: id, verified_by: verifier, verified_at: now.toISOString(), words_sha256: sha(row.words) };
|
||||
return writeExclusive(store, path.join(store.dir, 'verifications', `${id}--${sha(verifier).slice(0, 12)}.json`), v);
|
||||
}
|
||||
|
||||
/** origin is "captain" for a standalone Captain ask; anything else (an autoplan gate item, an unknown draft) is never screened out. */
|
||||
export interface AskLine { line: string; text: string; origin?: string; action?: string; target?: string; scope?: string; limits?: string; classes?: string[]; compound?: boolean }
|
||||
|
||||
/** An ask file: JSON `{ "asks": [AskLine, ...] }`, or plain text with one ask per non-blank line (all untyped). */
|
||||
export function parseAskFile(text: string): AskLine[] | AnswerError {
|
||||
const t = text.trim();
|
||||
if (t.startsWith('{')) {
|
||||
let j: any;
|
||||
try { j = JSON.parse(t); } catch { return { code: 'OWNER_ANSWERS_INVALID', message: 'the ask file starts with { but is not JSON' }; }
|
||||
if (!Array.isArray(j?.asks)) return { code: 'OWNER_ANSWERS_INVALID', message: 'the ask file needs an "asks" array' };
|
||||
return j.asks.map((a: any, i: number) => ({
|
||||
line: typeof a?.line === 'string' && a.line ? a.line : String(i + 1), text: typeof a?.text === 'string' ? a.text : '', origin: typeof a?.origin === 'string' ? a.origin : undefined,
|
||||
action: typeof a?.action === 'string' ? a.action : undefined, target: typeof a?.target === 'string' ? a.target : undefined,
|
||||
scope: typeof a?.scope === 'string' ? a.scope : undefined, limits: typeof a?.limits === 'string' ? a.limits : undefined, classes: Array.isArray(a?.classes) ? a.classes.map(String) : [], compound: a?.compound === true,
|
||||
}));
|
||||
}
|
||||
return t.split('\n').map(l => l.trim()).filter(Boolean).map((l, i) => {
|
||||
const m = /^([A-Z][0-9]*)\s*[:.)]\s*(.*)$/.exec(l);
|
||||
return { line: m ? m[1]! : String(i + 1), text: m ? m[2]! : l };
|
||||
});
|
||||
}
|
||||
|
||||
const STOP = new Set('the a an and or to of for in on at is it be we you your this that with as by from not no do can could should would will any all our its are was were has have if then than so but'.split(' '));
|
||||
const words = (s: string) => new Set(s.toLowerCase().split(/[^a-z0-9]+/).filter(w => w.length > 2 && !STOP.has(w)));
|
||||
|
||||
/** Rows ranked by word overlap with the ask (advisory only: ranking never makes a row takeable). */
|
||||
export function rankRows(rows: OwnerAnswer[], ask: AskLine, k = 5): Array<{ row: OwnerAnswer; score: number }> {
|
||||
const want = words([ask.text, ask.action ?? '', ask.target ?? ''].join(' '));
|
||||
return rows
|
||||
.filter(r => !ask.scope || r.scope === 'all' || r.scope === ask.scope)
|
||||
.map(row => { const have = words([row.asked, row.action, row.target, row.words].join(' ')); let score = 0; for (const w of want) if (have.has(w)) score++; return { row, score }; })
|
||||
.filter(x => x.score > 0)
|
||||
.sort((a, b) => b.score - a.score || b.row.recorded_at.localeCompare(a.row.recorded_at))
|
||||
.slice(0, k);
|
||||
}
|
||||
|
||||
export interface Screened { line: string; text: string; verdict: 'KEEP' | 'PROPOSE_TAKE'; reason: string; take?: OwnerAnswer; related: OwnerAnswer[] }
|
||||
|
||||
/** Per ask line: a proposal to take only on an exact typed match with a takeable row; otherwise keep, with related rows as context. */
|
||||
export function screenAsks(asks: AskLine[], read: StoreRead): Screened[] {
|
||||
const current = currentRows(read);
|
||||
return asks.map(ask => {
|
||||
const related = rankRows(current, ask, 3).map(x => x.row);
|
||||
const keep = (reason: string): Screened => ({ line: ask.line, text: ask.text, verdict: 'KEEP', reason, related });
|
||||
if (read.state !== 'present') return keep(`the record is ${read.state}`);
|
||||
if (ask.origin !== 'captain') return keep(ask.origin === 'gate' ? 'a gate item is answered at its gate, never screened out' : 'the ask does not say it is a standalone Captain ask (origin: captain)');
|
||||
if (ask.compound) return keep('the line holds more than one decision');
|
||||
if (ask.limits?.trim()) return keep('the ask carries limits (an amount, a count, a deadline) the record cannot check');
|
||||
const tagged = (ask.classes ?? []).filter(c => (FRESH_ASK_CLASSES as readonly string[]).includes(c));
|
||||
const unknownTag = (ask.classes ?? []).find(c => !(FRESH_ASK_CLASSES as readonly string[]).includes(c));
|
||||
if (unknownTag) return keep(`unknown class ${unknownTag}`);
|
||||
if (tagged.length) return keep(`always a fresh ask: ${tagged.join(', ')}`);
|
||||
const netted = FRESH_ASK_CLASSES.filter(c => FRESH_ASK_WORDS[c].test(ask.text));
|
||||
if (netted.length) return keep(`its words read as a fresh-ask class: ${netted.join(', ')}`);
|
||||
if (!ask.action || !ask.target || !ask.scope) return keep('the line has no typed action, target and scope');
|
||||
const exact = current.filter(r => r.action === ask.action && r.target === ask.target && (r.scope === 'all' || r.scope === ask.scope));
|
||||
const take = exact.filter(r => !notTakeable(r, read)).at(-1);
|
||||
if (!take) return keep(exact.length ? `matching rows are not takeable: ${notTakeable(exact.at(-1)!, read)}` : 'no standing yes matches its action, target and scope');
|
||||
const veto = exact.find(r => r !== take && notTakeable(r, read) && (r.recorded_at > take.recorded_at || (take.scope === 'all' && r.scope !== 'all')));
|
||||
if (veto) return keep(`a newer or narrower answer for this action is not takeable: ${veto.id} (${notTakeable(veto, read)})`);
|
||||
return { line: ask.line, text: ask.text, verdict: 'PROPOSE_TAKE', reason: 'a verified, current standing yes matches exactly', take, related };
|
||||
});
|
||||
}
|
||||
|
||||
/** The line a Captain adds to its message for each confirmed take. */
|
||||
export function takenLine(row: OwnerAnswer): string {
|
||||
const words = row.words.length > 160 ? row.words.slice(0, 159).trimEnd() + '…' : row.words;
|
||||
return `Not asked, you already said: "${words.replace(/\s+/g, ' ')}" (${row.recorded_at.slice(0, 10)}, ${row.source.thread}${row.rule ? `, ${row.rule}` : ''}).`;
|
||||
}
|
||||
|
||||
export const LOG_DECISIONS = ['taken', 'asked'] as const;
|
||||
|
||||
/** One line in the thread's own log: what the pilot did with a line, and which row it took. */
|
||||
export function logDecision(store: Store, o: { thread: string; line: string; decision: string; row?: string; by: string }, now = new Date()): string | AnswerError {
|
||||
if (!/^[A-Za-z0-9_-]{1,80}$/.test(o.thread)) return { code: 'OWNER_ANSWERS_INVALID', message: '--thread must be the thread code or id (letters, digits, - and _)' };
|
||||
if (!(LOG_DECISIONS as readonly string[]).includes(o.decision)) return { code: 'OWNER_ANSWERS_INVALID', message: `--decision must be ${LOG_DECISIONS.join('|')}` };
|
||||
if (o.decision === 'taken') {
|
||||
const read = readStore(store);
|
||||
const row = read.rows.find(r => r.id === o.row);
|
||||
if (!row) return { code: 'OWNER_ANSWERS_NOT_FOUND', message: `no row ${o.row ?? '(none given)'}` };
|
||||
const why = notTakeable(row, read);
|
||||
if (why) return { code: 'OWNER_ANSWERS_NOT_TAKEABLE', message: `${row.id}: ${why}` };
|
||||
}
|
||||
const file = path.join(store.dir, 'log', `${o.thread}.jsonl`);
|
||||
const dir = prepareDir(store, file);
|
||||
if (dir) return dir;
|
||||
try {
|
||||
fs.appendFileSync(file, JSON.stringify({ at: now.toISOString(), thread: o.thread, line: o.line.slice(0, 20), decision: o.decision, row: o.row ?? '', by: o.by.slice(0, CAPS.by) }) + '\n', { mode: 0o600 });
|
||||
} catch (e: any) { return { code: 'OWNER_ANSWERS_WRITE_FAILED', message: `log: ${e?.code ?? e?.message}` }; }
|
||||
return file;
|
||||
}
|
||||
@@ -40,6 +40,51 @@ export const CAPY_RESULT_CODES = {
|
||||
summary: 'the autoplan run has no answered gate to import',
|
||||
fix: 'answer the gate first (gstack-autoplan answer ... --by human|agent:<id>), then rerun the import; it is idempotent, so a retry imports nothing twice',
|
||||
},
|
||||
OWNER_ANSWERS_NO_DRIVE: {
|
||||
anchor: 'owner-answers-no-drive',
|
||||
summary: 'no owner Drive folder (user-<owner>) is mounted on this Capy machine, so there is no record to read or write',
|
||||
fix: 'run from a thread the owner owns, or pass --owner <name> for a mounted user-<name> folder; until then every ask goes to the owner',
|
||||
},
|
||||
OWNER_ANSWERS_AMBIGUOUS: {
|
||||
anchor: 'owner-answers-ambiguous',
|
||||
summary: 'more than one user-* Drive folder is mounted, so the owner is not known',
|
||||
fix: 'pass --owner <name> naming the owner whose record this is; nothing was read or written',
|
||||
},
|
||||
OWNER_ANSWERS_INVALID: {
|
||||
anchor: 'owner-answers-invalid',
|
||||
summary: 'a row, an ask file or a flag is missing a required value, holds a value outside its format, or exceeds a length cap',
|
||||
fix: 'rerun with the flags the help names (an action and target are one lower-case token each; scope is all, repo:<owner>/<name> or captain:<name>); nothing was written',
|
||||
},
|
||||
OWNER_ANSWERS_SECRET: {
|
||||
anchor: 'owner-answers-secret',
|
||||
summary: 'a field matched the secret scanner, so the row was not written',
|
||||
fix: 'remove the key, token or personal data from that field (the error names the field and rule, never the text) and rerun',
|
||||
},
|
||||
OWNER_ANSWERS_WRITE_FAILED: {
|
||||
anchor: 'owner-answers-write-failed',
|
||||
summary: 'the record directory could not be written',
|
||||
fix: 'check the path gstack-owner-answers status prints and its permissions, then rerun; a failed write removed its file, and an empty file left by a crash is named by status and must be removed',
|
||||
},
|
||||
OWNER_ANSWERS_NOT_FOUND: {
|
||||
anchor: 'owner-answers-not-found',
|
||||
summary: 'no row with that id is in the owner record',
|
||||
fix: 'gstack-owner-answers list --all shows every row id; rerun with one of them',
|
||||
},
|
||||
OWNER_ANSWERS_CONFLICT: {
|
||||
anchor: 'owner-answers-conflict',
|
||||
summary: 'a row for the same source, action, target and scope already records different words, author or limits, or the row named to supersede is already replaced',
|
||||
fix: 'check which words the owner actually said at that source; record a correction with supersede <row id> on the current row, never a second add',
|
||||
},
|
||||
OWNER_ANSWERS_SELF_VERIFY: {
|
||||
anchor: 'owner-answers-self-verify',
|
||||
summary: 'the actor that recorded a row tried to verify it',
|
||||
fix: 'a second actor reads the cited thread event and runs verify --by <its own name>; a row its recorder verified is never takeable',
|
||||
},
|
||||
OWNER_ANSWERS_NOT_TAKEABLE: {
|
||||
anchor: 'owner-answers-not-takeable',
|
||||
summary: 'a taken decision was logged against a row that cannot be taken',
|
||||
fix: 'send the ask to the owner instead (log it as asked); screen only proposes rows it can take, and the detail says why this one cannot',
|
||||
},
|
||||
CAPTAIN_BRIEF_INCOMPLETE: {
|
||||
anchor: 'captain-brief-incomplete',
|
||||
summary: 'the plan lacks one or more of the sections the Captain brief needs (ELI5 on a run whose gate carries it, Before → after, Why it matters, What caused this work, Big decisions), so the brief is not ready for approval',
|
||||
|
||||
@@ -0,0 +1,329 @@
|
||||
/**
|
||||
* The owner's answer record (lib/owner-answers.ts, bin/gstack-owner-answers, docs/owner-answers.md):
|
||||
* store binding on Capy, one-file rows, second-actor verification, fail-closed reads, and the screen
|
||||
* rules that decide when an ask may be left out. Every owner here is made up.
|
||||
*/
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { spawn, spawnSync } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { bunIsolationArgs } from '../lib/bun-isolation';
|
||||
import {
|
||||
addAnswer, buildAnswer, currentRows, notTakeable, parseAskFile, readStore, resolveStore, screenAsks, verifyAnswer,
|
||||
type AskLine, type NewAnswer, type OwnerAnswer, type Store,
|
||||
} from '../lib/owner-answers';
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, '..');
|
||||
const BIN = path.join(ROOT, 'bin', 'gstack-owner-answers');
|
||||
const dirs: string[] = [];
|
||||
const tmp = (prefix: string) => { const d = fs.mkdtempSync(path.join(os.tmpdir(), prefix)); dirs.push(d); return d; };
|
||||
afterEach(() => { while (dirs.length) fs.rmSync(dirs.pop()!, { recursive: true, force: true }); });
|
||||
|
||||
/** A fake home with a mounted Drive holding the given user folders. */
|
||||
function home(...users: string[]): string {
|
||||
const h = tmp('oa-home-');
|
||||
for (const u of users) fs.mkdirSync(path.join(h, '.capy', 'drive', `user-${u}`), { recursive: true });
|
||||
fs.mkdirSync(path.join(h, '.capy', 'drive'), { recursive: true });
|
||||
return h;
|
||||
}
|
||||
const capyEnv = (h: string) => ({ GSTACK_CAPY: '1', HOME: h, GSTACK_OWNER_ANSWERS_DIR: '' }) as NodeJS.ProcessEnv;
|
||||
function store(h = home('alice')): Store {
|
||||
const s = resolveStore(capyEnv(h));
|
||||
if ('code' in s) throw new Error(s.message);
|
||||
return s;
|
||||
}
|
||||
|
||||
const MERGE: NewAnswer = { action: 'merge-when-green', target: 'pull-request', scope: 'all', words: 'yes merge when green', words_by: 'owner', thread: 'CAPT-1', event: 'evt_1', by: 'Example Captain' };
|
||||
function put(s: Store, input: NewAnswer = MERGE): OwnerAnswer {
|
||||
const row = buildAnswer(s, input);
|
||||
if ('code' in row) throw new Error(row.message);
|
||||
expect(addAnswer(s, row)).toBe('written');
|
||||
return row;
|
||||
}
|
||||
function takeable(s: Store, input: NewAnswer = MERGE): OwnerAnswer {
|
||||
const row = put(s, input);
|
||||
expect(verifyAnswer(s, row.id, 'second reader', row.source.event)).toBe('written');
|
||||
return row;
|
||||
}
|
||||
const ASK: AskLine = { line: 'A', origin: 'captain', text: 'Merge #12 now that it is green?', action: 'merge-when-green', target: 'pull-request', scope: 'repo:example/widgets' };
|
||||
|
||||
function cli(args: string[], env: NodeJS.ProcessEnv) {
|
||||
const r = spawnSync('bun', [...bunIsolationArgs(), BIN, ...args], { cwd: ROOT, encoding: 'utf8', timeout: 60_000, env: { ...process.env, ...env } });
|
||||
return { status: r.status ?? -1, out: r.stdout ?? '', err: r.stderr ?? '' };
|
||||
}
|
||||
|
||||
describe('where the record lives', () => {
|
||||
test('on Capy: the one user-* Drive folder; none, two or an unknown --owner refuse, and the env override is ignored', () => {
|
||||
const h = home('alice');
|
||||
const s = resolveStore({ ...capyEnv(h), GSTACK_OWNER_ANSWERS_DIR: tmp('oa-forged-') });
|
||||
expect('code' in s ? s.code : s.dir).toBe(path.join(fs.realpathSync(h), '.capy', 'drive', 'user-alice', 'owner-answers'));
|
||||
expect('code' in s ? '' : s.owner).toBe('alice');
|
||||
expect((resolveStore(capyEnv(home())) as any).code).toBe('OWNER_ANSWERS_NO_DRIVE');
|
||||
expect((resolveStore(capyEnv(home('alice', 'bob'))) as any).code).toBe('OWNER_ANSWERS_AMBIGUOUS');
|
||||
expect((resolveStore(capyEnv(home('alice', 'bob')), 'bob') as any).owner).toBe('bob');
|
||||
expect((resolveStore(capyEnv(h), 'carol') as any).code).toBe('OWNER_ANSWERS_NO_DRIVE');
|
||||
});
|
||||
|
||||
test('a user folder that is a link out of the Drive is refused', () => {
|
||||
if (process.platform === 'win32') return;
|
||||
const h = home();
|
||||
fs.symlinkSync(tmp('oa-outside-'), path.join(h, '.capy', 'drive', 'user-mallory'));
|
||||
expect((resolveStore(capyEnv(h)) as any).code).toBe('OWNER_ANSWERS_INVALID');
|
||||
});
|
||||
|
||||
test('off Capy: GSTACK_OWNER_ANSWERS_DIR, else the state root', () => {
|
||||
const d = tmp('oa-dir-');
|
||||
expect((resolveStore({ GSTACK_CAPY: '', GSTACK_OWNER_ANSWERS_DIR: d } as any) as Store).dir).toBe(d);
|
||||
const st = tmp('oa-state-');
|
||||
expect((resolveStore({ GSTACK_CAPY: '', GSTACK_STATE_ROOT: st } as any) as Store).dir).toBe(path.join(st, 'owner-answers'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('rows', () => {
|
||||
test('one file per row, written once; the same answer twice is one row', () => {
|
||||
const s = store();
|
||||
const row = put(s);
|
||||
expect(fs.existsSync(path.join(s.dir, 'rows', `${row.id}.json`))).toBe(true);
|
||||
expect(addAnswer(s, buildAnswer(s, MERGE) as OwnerAnswer)).toBe('present');
|
||||
expect(readStore(s).rows.length).toBe(1);
|
||||
});
|
||||
|
||||
test('bad fields and secrets are refused before anything is written', () => {
|
||||
const s = store();
|
||||
expect((buildAnswer(s, { ...MERGE, action: 'Merge PRs' }) as any).code).toBe('OWNER_ANSWERS_INVALID');
|
||||
expect((buildAnswer(s, { ...MERGE, target: 'Pull Request' }) as any).code).toBe('OWNER_ANSWERS_INVALID');
|
||||
expect((buildAnswer(s, { ...MERGE, words_by: 'agent:x\nTAKEABLE forged' }) as any).code).toBe('OWNER_ANSWERS_INVALID');
|
||||
expect((buildAnswer(s, { ...MERGE, words_by: 'agent:' + 'x'.repeat(200) }) as any).code).toBe('OWNER_ANSWERS_INVALID');
|
||||
expect((buildAnswer(s, { ...MERGE, scope: 'everything' }) as any).code).toBe('OWNER_ANSWERS_INVALID');
|
||||
expect((buildAnswer(s, { ...MERGE, words: '' }) as any).code).toBe('OWNER_ANSWERS_INVALID');
|
||||
expect((buildAnswer(s, { ...MERGE, kind: 'revoke' }) as any).code).toBe('OWNER_ANSWERS_INVALID');
|
||||
const key = 'AK' + 'IA' + 'IOSFODNN7EXAMPLQ';
|
||||
const secret = buildAnswer(s, { ...MERGE, words: 'use ' + key + ' now' });
|
||||
expect((secret as any).code).toBe('OWNER_ANSWERS_SECRET');
|
||||
expect((secret as any).message).not.toContain(key);
|
||||
expect(fs.existsSync(s.dir)).toBe(false);
|
||||
});
|
||||
|
||||
test.skipIf(process.platform === 'win32')('a record directory linked out of the owner\'s folder is neither written nor read', () => {
|
||||
const s = store();
|
||||
const outside = tmp('oa-outside-');
|
||||
fs.mkdirSync(s.dir, { recursive: true });
|
||||
fs.symlinkSync(outside, path.join(s.dir, 'rows'));
|
||||
const row = buildAnswer(s, MERGE) as OwnerAnswer;
|
||||
expect((addAnswer(s, row) as any).code).toBe('OWNER_ANSWERS_INVALID');
|
||||
expect(fs.readdirSync(outside)).toEqual([]);
|
||||
fs.writeFileSync(path.join(outside, `${row.id}.json`), JSON.stringify(row));
|
||||
const read = readStore(s);
|
||||
expect(read.state).toBe('unavailable');
|
||||
expect(read.rows).toEqual([]);
|
||||
expect(screenAsks([ASK], read)[0]!.verdict).toBe('KEEP');
|
||||
});
|
||||
|
||||
test('a write that fails after the file is created leaves no row, and the same add then succeeds', () => {
|
||||
const s = store();
|
||||
const row = buildAnswer(s, MERGE) as OwnerAnswer;
|
||||
const res = addAnswer(s, { ...row, limits: 1n as unknown as string });
|
||||
expect((res as any).code).toBe('OWNER_ANSWERS_WRITE_FAILED');
|
||||
expect(fs.readdirSync(path.join(s.dir, 'rows'))).toEqual([]);
|
||||
expect(addAnswer(s, row)).toBe('written');
|
||||
expect(readStore(s).state).toBe('present');
|
||||
});
|
||||
|
||||
test('two processes adding at once: one row written, one told it is present, no torn file', async () => {
|
||||
const h = home('alice');
|
||||
const args = ['add', '--action', 'merge-when-green', '--target', 'pull-request', '--words', 'yes merge when green', '--words-by', 'owner', '--thread', 'CAPT-1', '--event', 'evt_1', '--by', 'Example Captain'];
|
||||
const run = () => new Promise<string>(resolve => {
|
||||
const c = spawn('bun', [...bunIsolationArgs(), BIN, ...args], { cwd: ROOT, env: { ...process.env, ...capyEnv(h) }, timeout: 60_000 });
|
||||
let out = '';
|
||||
c.stdout.on('data', b => { out += b; });
|
||||
c.on('close', () => resolve(out));
|
||||
});
|
||||
const outs = await Promise.all([run(), run()]);
|
||||
expect(outs.filter(o => /^OWNER_ANSWER_RECORDED: oa-[0-9a-f]{16}\n$/.test(o)).length).toBe(1);
|
||||
expect(outs.filter(o => o.includes('(already present)')).length).toBe(1);
|
||||
const read = readStore(store(h));
|
||||
expect(read.state).toBe('present');
|
||||
expect(read.rows.length).toBe(1);
|
||||
}, 120_000);
|
||||
});
|
||||
|
||||
describe('what can be taken', () => {
|
||||
test('the owner\'s own words, verified by a second actor, current and unlimited', () => {
|
||||
const s = store();
|
||||
const row = takeable(s);
|
||||
expect(notTakeable(row, readStore(s))).toBeUndefined();
|
||||
});
|
||||
|
||||
test('agent-typed words, limits, other kinds and unverified rows are context only', () => {
|
||||
const s = store();
|
||||
const typed = takeable(s, { ...MERGE, words_by: undefined, event: 'evt_2' });
|
||||
const limited = takeable(s, { ...MERGE, limits: 'only under $50', event: 'evt_3' });
|
||||
const decision = takeable(s, { ...MERGE, kind: 'decision', event: 'evt_4' });
|
||||
const unverified = put(s, { ...MERGE, event: 'evt_5' });
|
||||
const read = readStore(s);
|
||||
expect(notTakeable(typed, read)).toContain('typed by agent:Example Captain');
|
||||
expect(notTakeable(limited, read)).toContain('limits');
|
||||
expect(notTakeable(decision, read)).toContain('context only');
|
||||
expect(notTakeable(unverified, read)).toContain('verified');
|
||||
});
|
||||
|
||||
test('the recorder cannot verify its own row, and a verification of other words does not count', () => {
|
||||
const s = store();
|
||||
const row = put(s);
|
||||
expect((verifyAnswer(s, row.id, 'Example Captain', row.source.event) as any).code).toBe('OWNER_ANSWERS_SELF_VERIFY');
|
||||
expect((verifyAnswer(s, row.id, 'second reader', 'evt_other') as any).code).toBe('OWNER_ANSWERS_INVALID');
|
||||
expect(notTakeable(row, readStore(s))).toContain('verified');
|
||||
fs.mkdirSync(path.join(s.dir, 'verifications'), { recursive: true });
|
||||
fs.writeFileSync(path.join(s.dir, 'verifications', `${row.id}--forged.json`), JSON.stringify({ schema_version: 1, row: row.id, verified_by: 'x', verified_at: 'now', words_sha256: '0'.repeat(64) }));
|
||||
expect(notTakeable(row, readStore(s))).toContain('verified');
|
||||
});
|
||||
|
||||
test('a superseded or revoked row stops counting; two revokes in one reply cancel both grants', () => {
|
||||
const s = store();
|
||||
const merge = takeable(s);
|
||||
const rerun = takeable(s, { ...MERGE, action: 'rerun-flaky-once', target: 'test', words: 'just run the failed test again', event: 'evt_9' });
|
||||
const cancel = (id: string) => put(s, { kind: 'revoke', supersedes: id, words: 'ask me again about both', words_by: 'owner', thread: 'CAPT-1', event: 'evt_10', by: 'Example Captain' });
|
||||
cancel(merge.id); cancel(rerun.id);
|
||||
const read = readStore(s);
|
||||
expect(read.state).toBe('present');
|
||||
expect(currentRows(read).map(r => r.id)).toEqual([]);
|
||||
expect(notTakeable(merge, read)).toContain('superseded');
|
||||
expect(notTakeable(rerun, read)).toContain('superseded');
|
||||
});
|
||||
});
|
||||
|
||||
describe('fail closed', () => {
|
||||
const uncertain = (mutate: (s: Store, row: OwnerAnswer) => void) => {
|
||||
const s = store();
|
||||
const row = takeable(s);
|
||||
mutate(s, row);
|
||||
const read = readStore(s);
|
||||
expect(read.state).toBe('uncertain');
|
||||
expect(read.problems.length).toBeGreaterThan(0);
|
||||
expect(screenAsks([ASK], read)[0]!.verdict).toBe('KEEP');
|
||||
};
|
||||
test('a malformed row file', () => uncertain(s => fs.writeFileSync(path.join(s.dir, 'rows', 'oa-0000000000000000.json'), '{ torn')));
|
||||
test('a row whose words were edited after it was written', () => uncertain((s, row) => {
|
||||
const f = path.join(s.dir, 'rows', `${row.id}.json`);
|
||||
fs.writeFileSync(f, JSON.stringify({ ...row, scope: 'captain:other' }));
|
||||
}));
|
||||
test('a row of another owner', () => uncertain(s => {
|
||||
const other = resolveStore(capyEnv(home('bob'))) as Store;
|
||||
const row = buildAnswer(other, { ...MERGE, event: 'evt_7' }) as OwnerAnswer;
|
||||
fs.writeFileSync(path.join(s.dir, 'rows', `${row.id}.json`), JSON.stringify(row));
|
||||
}));
|
||||
test('a supersede that names a missing row', () => uncertain(s => {
|
||||
const row = buildAnswer(s, { ...MERGE, event: 'evt_8', supersedes: 'oa-ffffffffffffffff' }) as OwnerAnswer;
|
||||
fs.writeFileSync(path.join(s.dir, 'rows', `${row.id}.json`), JSON.stringify(row));
|
||||
}));
|
||||
test('two rows that supersede the same row (two machines writing before their Drives sync)', () => uncertain((s, row) => {
|
||||
put(s, { ...MERGE, words: 'merge when green, any repo', event: 'evt_11', supersedes: row.id });
|
||||
const twin = buildAnswer(s, { ...MERGE, words: 'merge when green, gstack only', event: 'evt_12', supersedes: row.id }) as OwnerAnswer;
|
||||
fs.writeFileSync(path.join(s.dir, 'rows', `${twin.id}.json`), JSON.stringify(twin));
|
||||
}));
|
||||
test('a second supersede or revoke of an already-replaced row is refused, not written', () => {
|
||||
const s = store();
|
||||
const row = put(s);
|
||||
expect(addAnswer(s, buildAnswer(s, { ...MERGE, kind: 'revoke', supersedes: row.id, event: 'evt_2' }) as OwnerAnswer)).toBe('written');
|
||||
expect(addAnswer(s, buildAnswer(s, { ...MERGE, kind: 'revoke', supersedes: row.id, event: 'evt_2' }) as OwnerAnswer)).toBe('present');
|
||||
expect((addAnswer(s, buildAnswer(s, { ...MERGE, kind: 'revoke', supersedes: row.id, event: 'evt_3' }) as OwnerAnswer) as any).code).toBe('OWNER_ANSWERS_CONFLICT');
|
||||
expect(readStore(s).state).toBe('present');
|
||||
});
|
||||
test('a second add with different words for one source and action is refused, not kept', () => {
|
||||
const s = store();
|
||||
put(s);
|
||||
const twin = buildAnswer(s, { ...MERGE, words: 'merge whenever' }) as OwnerAnswer;
|
||||
expect((addAnswer(s, twin) as any).code).toBe('OWNER_ANSWERS_CONFLICT');
|
||||
expect(readStore(s).rows.map(r => r.words)).toEqual(['yes merge when green']);
|
||||
});
|
||||
test('supersede through the API refuses a missing row', () => {
|
||||
const s = store();
|
||||
const row = buildAnswer(s, { ...MERGE, supersedes: 'oa-ffffffffffffffff' }) as OwnerAnswer;
|
||||
expect((addAnswer(s, row) as any).code).toBe('OWNER_ANSWERS_NOT_FOUND');
|
||||
});
|
||||
});
|
||||
|
||||
describe('screen', () => {
|
||||
const verdicts = (asks: AskLine[], s: Store) => screenAsks(asks, readStore(s)).map(x => `${x.verdict}: ${x.reason}`);
|
||||
test('an exact typed match with a takeable row is proposed, with the line the Captain adds', () => {
|
||||
const s = store();
|
||||
const row = takeable(s, { ...MERGE, rule: 'R6' });
|
||||
const [line] = screenAsks([ASK], readStore(s));
|
||||
expect(line!.verdict).toBe('PROPOSE_TAKE');
|
||||
expect(line!.take!.id).toBe(row.id);
|
||||
});
|
||||
|
||||
test('gate items, untyped, compound, fresh-ask, near-miss and wrong-scope lines are kept', () => {
|
||||
const s = store();
|
||||
takeable(s, { ...MERGE, scope: 'captain:alpha' });
|
||||
const out = verdicts([
|
||||
{ ...ASK, origin: 'gate', scope: 'captain:alpha' },
|
||||
{ ...ASK, origin: undefined, scope: 'captain:alpha' },
|
||||
{ line: 'C', origin: 'captain', text: 'Merge #12?' },
|
||||
{ ...ASK, compound: true, scope: 'captain:alpha' },
|
||||
{ ...ASK, limits: 'only PRs under 50 lines', scope: 'captain:alpha' },
|
||||
{ ...ASK, classes: ['destructive'], scope: 'captain:alpha' },
|
||||
{ ...ASK, classes: ['made-up'], scope: 'captain:alpha' },
|
||||
{ ...ASK, text: 'Merge #12 and spend $400 on a rerun?', scope: 'captain:alpha' },
|
||||
{ ...ASK, action: 'merge-now', scope: 'captain:alpha' },
|
||||
{ ...ASK, scope: 'captain:beta' },
|
||||
{ ...ASK, scope: 'repo:example/widgets' },
|
||||
], s);
|
||||
expect(out.every(v => v.startsWith('KEEP'))).toBe(true);
|
||||
expect(out[0]).toContain('gate item');
|
||||
expect(out[2]).toContain('no typed action');
|
||||
expect(out[4]).toContain('limits');
|
||||
expect(out[7]).toContain('spend-over-cap');
|
||||
expect(screenAsks([{ ...ASK, scope: 'captain:alpha' }], readStore(s))[0]!.verdict).toBe('PROPOSE_TAKE');
|
||||
});
|
||||
|
||||
test('a newer or narrower matching row that cannot be taken keeps the ask', () => {
|
||||
const s = store();
|
||||
takeable(s);
|
||||
put(s, { ...MERGE, kind: 'decision', scope: 'repo:example/widgets', words: 'not in widgets, wait for the owners', event: 'evt_20' });
|
||||
const [line] = screenAsks([ASK], readStore(s));
|
||||
expect(line!.verdict).toBe('KEEP');
|
||||
expect(line!.reason).toContain('newer or narrower');
|
||||
expect(screenAsks([{ ...ASK, scope: 'repo:example/other' }], readStore(s))[0]!.verdict).toBe('PROPOSE_TAKE');
|
||||
});
|
||||
|
||||
test('an empty record keeps everything', () => {
|
||||
expect(screenAsks([ASK], readStore(store()))[0]!.reason).toContain('empty');
|
||||
});
|
||||
|
||||
test('plain-text ask files parse as untyped lines', () => {
|
||||
const asks = parseAskFile('A: Merge #12?\nB) Spend $400?\n\n') as AskLine[];
|
||||
expect(asks.map(a => a.line)).toEqual(['A', 'B']);
|
||||
expect(asks.every(a => !a.action)).toBe(true);
|
||||
expect((parseAskFile('{ nope') as any).code).toBe('OWNER_ANSWERS_INVALID');
|
||||
});
|
||||
});
|
||||
|
||||
describe('gstack-owner-answers', () => {
|
||||
test('add, verify, screen, log and status end to end; logging a take of an untakeable row refuses', () => {
|
||||
const h = home('alice');
|
||||
const env = capyEnv(h);
|
||||
const add = cli(['add', '--action', 'merge-when-green', '--target', 'pull-request', '--words', 'yes merge when green', '--words-by', 'owner', '--thread', 'CAPT-1', '--event', 'evt_1', '--by', 'Example Captain', '--rule', 'R6'], env);
|
||||
expect(add.status).toBe(0);
|
||||
const id = /OWNER_ANSWER_RECORDED: (oa-[0-9a-f]{16})/.exec(add.out)![1]!;
|
||||
expect(cli(['log', '--thread', 'CAPT-1', '--line', 'A', '--decision', 'taken', '--row', id, '--by', 'Example Captain'], env).err).toContain('(OWNER_ANSWERS_NOT_TAKEABLE)');
|
||||
expect(cli(['verify', id, '--event', 'evt_1', '--by', 'Example Captain'], env).err).toContain('(OWNER_ANSWERS_SELF_VERIFY)');
|
||||
expect(cli(['verify', id, '--event', 'evt_1', '--by', 'second reader'], env).status).toBe(0);
|
||||
const askFile = path.join(tmp('oa-ask-'), 'ask.json');
|
||||
fs.writeFileSync(askFile, JSON.stringify({ asks: [ASK, { line: 'B', origin: 'captain', text: 'Close their PR?', classes: ['close-contribution'] }] }));
|
||||
const screen = cli(['screen', '--ask-file', askFile], env);
|
||||
expect(screen.status).toBe(0);
|
||||
expect(screen.out).toContain(`PROPOSE_TAKE A ${id}: Not asked, you already said: "yes merge when green"`);
|
||||
expect(screen.out).toMatch(/already said: "yes merge when green" \(\d{4}-\d{2}-\d{2}, CAPT-1, R6\)\./);
|
||||
expect(screen.out).toMatch(/^KEEP B: always a fresh ask: close-contribution$/m);
|
||||
expect(screen.out).not.toContain(h);
|
||||
expect(fs.readFileSync(askFile, 'utf8')).toContain('"line":"B"');
|
||||
expect(cli(['log', '--thread', 'CAPT-1', '--line', 'A', '--decision', 'taken', '--row', id, '--by', 'Example Captain'], env).status).toBe(0);
|
||||
expect(cli(['log', '--thread', '../x', '--line', 'A', '--decision', 'asked', '--by', 'x'], env).status).toBe(2);
|
||||
const status = cli(['status'], env);
|
||||
expect(status.out).toMatch(/^STATE: present$/m);
|
||||
expect(status.out).toMatch(/^ROWS: 1 current=1 takeable=1 verifications=1$/m);
|
||||
expect(cli(['add', '--action', 'x'], capyEnv(home())).err).toContain('(OWNER_ANSWERS_NO_DRIVE)');
|
||||
}, 120_000);
|
||||
});
|
||||
Reference in new issue
Block a user