agentic-sdlc-kit 0.3.1 → 0.4.0

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.
@@ -4,16 +4,18 @@ import { typeRegistry } from '../config/schema.js';
4
4
  import { APPROVAL_ACTIONS, normalizeCommentUrl, recordedRefs } from '../core/approvals.js';
5
5
  import { editsAllowed } from '../core/edits.js';
6
6
  import { parseOwnerCommand } from '../core/ownerCommand.js';
7
+ import { pendingDecision } from '../core/pendingDecision.js';
7
8
  import { reconcile } from '../engine/reconcile.js';
8
9
  import { emptyOutput, renderOutput } from '../hooks/output.js';
9
10
  import { HookPayloadError, normalizePayload } from '../hooks/payload.js';
10
11
  import { appendJsonLine, GAPS_FILE, PROMPTS_FILE, readJsonFile, TASK_CACHE_FILE, writeJsonFile, } from '../hooks/localLog.js';
11
12
  import { decide, editViolations, isUserHarnessFile, needsTask, subagentViolation, } from '../hooks/policy.js';
12
13
  import { cachedCheckoutOf, mainRootOf, realPathOf } from '../hooks/resolve.js';
13
- import { isBareCancel, pendingActions, promptApprover, promptRef, promptSha256, sessionContext, } from '../hooks/session.js';
14
+ import { decisionReminder, isBareCancel, pendingActions, promptApprover, promptNormSha256, promptRef, promptSha256, SAFE_PROMPT_KEY, sessionContext, severalWaiting, } from '../hooks/session.js';
14
15
  import { shellViolations } from '../hooks/shell.js';
15
16
  import { HOOK_EVENTS, HOOK_HARNESSES, } from '../hooks/types.js';
16
17
  import { queuedCounts } from '../outbox/outbox.js';
18
+ import { StateChangedError } from '../tracker/types.js';
17
19
  import { applyApproval } from './approve.js';
18
20
  import { CommandError, loadTask, trackerStep } from './context.js';
19
21
  import { DeadlineError, deadlineOf, isMissingTaskError, oneLine } from './githook.js';
@@ -28,10 +30,23 @@ import { DeadlineError, deadlineOf, isMissingTaskError, oneLine } from './githoo
28
30
  */
29
31
  export const DEFAULT_DEADLINE_MS = 3000;
30
32
  /**
31
- * The same for session start and prompt, which the harness lets run 30 s (`HOOK_TIMEOUT_S`) and
32
- * which have a task to read and an approval to write, not just a verdict to give.
33
+ * The same for session start, which the harness lets run 30 s (`HOOK_TIMEOUT_S`) and which has a
34
+ * task to read, not just a verdict to give.
33
35
  */
34
36
  export const SLOW_EVENT_DEADLINE_MS = 6000;
37
+ /**
38
+ * The same for the prompt, which reads a task and may then write an owner's approval (a comment and
39
+ * the state of the task: several GitHub calls). A deadline that ends during that write leaves the
40
+ * hook not knowing whether it landed, so the prompt gets most of its 30 s (`HOOK_TIMEOUT_S`): this
41
+ * plus the worst case of two git calls for each of two directories stays below it.
42
+ */
43
+ export const PROMPT_DEADLINE_MS = 20000;
44
+ /** The deadline each event gets when the context names none. */
45
+ export const DEADLINE_MS = {
46
+ 'pre-tool': DEFAULT_DEADLINE_MS,
47
+ 'session-start': SLOW_EVENT_DEADLINE_MS,
48
+ prompt: PROMPT_DEADLINE_MS,
49
+ };
35
50
  /** Longest one git call of the hook may take; the real context kills a slower git (see `createGitRunner`). */
36
51
  export const GIT_TIMEOUT_MS = 2000;
37
52
  /** How long a cached task state, read while edits were allowed, is trusted. */
@@ -345,11 +360,15 @@ async function sessionStart(env) {
345
360
  syncRunning,
346
361
  }));
347
362
  }
348
- /** Appends the prompt's hash, never its text, to the prompt record; a record that cannot be written is skipped. */
363
+ /**
364
+ * Appends the prompt's hashes, never its text, to the prompt record, and gives the record back. A
365
+ * record that cannot be written is skipped, and a read-only run writes none: both give `undefined`,
366
+ * as the prompt then has no record for `sdlc approve --from-prompt` to find.
367
+ */
349
368
  async function recordPrompt(env, prompt) {
350
369
  const { event, checkout } = env;
351
370
  if (env.ctx.readOnly === true)
352
- return;
371
+ return undefined;
353
372
  const record = {
354
373
  at: env.ctx.now(),
355
374
  harness: event.harness,
@@ -357,23 +376,98 @@ async function recordPrompt(env, prompt) {
357
376
  ...(event.promptId === undefined ? {} : { promptId: event.promptId }),
358
377
  ...(checkout.issue === undefined ? {} : { issue: checkout.issue }),
359
378
  sha256: promptSha256(prompt),
379
+ normSha256: promptNormSha256(prompt),
360
380
  };
361
381
  try {
362
382
  await appendJsonLine(mainRootOf(checkout), PROMPTS_FILE, record);
383
+ return record;
363
384
  }
364
385
  catch {
365
386
  // The record is a trail, not a rule: a read-only checkout must not stop the prompt.
387
+ return undefined;
366
388
  }
367
389
  }
368
390
  const isApprovalAction = (action) => APPROVAL_ACTIONS.includes(action);
369
391
  const NO_TASK_FOR_APPROVAL = 'sdlc: no task on this branch; the approval was not recorded.';
392
+ const NO_SUCH_TASK_FOR_APPROVAL = (issue) => `sdlc: #${issue} is not a tracked task; the approval was not recorded.`;
393
+ /** A command whose task number cannot be read (`/approve 11a`): it is for no task, and never falls back to one. */
394
+ const UNREADABLE_ISSUE = (action) => `sdlc: could not read the task number; write it as /${action} 11.`;
395
+ /** The board did not answer within its deadline, so the task of an unnamed command is not known: nothing is recorded. */
396
+ const BOARD_TOO_SLOW = (action) => `sdlc: could not determine the task in time (the board did not answer); the approval was not recorded. Name the task, as in /${action} 11.`;
370
397
  const BARE_CANCEL = 'sdlc: approval not recorded: /cancel needs a reason on the same line, as in "/cancel no longer needed".';
371
398
  const READ_ONLY_APPROVAL = 'sdlc: read-only run; the approval was not recorded.';
372
399
  const GITHUB_UNREACHABLE = 'sdlc: could not reach GitHub; approval not recorded, ask again or approve by comment';
400
+ /** The deadline passed, or a call failed, while the approval was being written: it may have landed, so it is never called "not recorded". */
401
+ export const APPROVAL_OUTCOME_UNKNOWN = (issue) => `sdlc: the approval for #${issue} may or may not have been recorded (GitHub did not answer in time); check with \`sdlc status\` and do not ask the owner again until you have.`;
402
+ /** The state of the task was saved, then a step after it failed: the approval stands and `sdlc reconcile` finishes the sync. */
403
+ const APPROVAL_RECORDED_NOT_SYNCED = (issue, step) => `sdlc: the approval for #${issue} was recorded, but the step after it (${step}) failed; run \`sdlc reconcile\` to finish syncing and do not ask the owner again.`;
404
+ /** The steps of `applyApproval` that run once the state comment is written (see `saveAndSync`). */
405
+ const STEPS_AFTER_STATE_SAVED = new Set(['syncFields', 'setIssueOpen']);
406
+ /**
407
+ * The line for an approval whose write began and failed. What the failure says about GitHub decides
408
+ * it: a step after the state was saved means it stands; a timeout, or a failed state write, leaves
409
+ * the outcome unknown; only a refusal that happened before anything was written is "not recorded"
410
+ * (a transition the state machine refuses, a state that changed under the write, a cancel report
411
+ * that could not be posted, which comes before the state write).
412
+ */
413
+ function failedWriteLine(issue, error) {
414
+ if (error instanceof CommandError && STEPS_AFTER_STATE_SAVED.has(error.step)) {
415
+ return APPROVAL_RECORDED_NOT_SYNCED(issue, error.step);
416
+ }
417
+ const refusedBeforeWriting = !(error instanceof CommandError) || error.step === 'postComment' || error.cause instanceof StateChangedError;
418
+ if (timedOut(error) || !refusedBeforeWriting)
419
+ return APPROVAL_OUTCOME_UNKNOWN(issue);
420
+ return `sdlc: approval not recorded: ${oneLine(reasonOf(error))}`;
421
+ }
422
+ /** The decision the owner owes on `task`, with what the agent needs to name it; `undefined` when none waits. */
423
+ function waitingOf({ issue, state }, types) {
424
+ const type = types.get(state.type);
425
+ const action = type === undefined ? undefined : pendingDecision(state, type);
426
+ if (action === undefined)
427
+ return undefined;
428
+ const revision = action === 'approve' ? state.stages[state.phase]?.revision : undefined;
429
+ return { issue, action, phase: state.phase, ...(revision === undefined ? {} : { revision }) };
430
+ }
431
+ /**
432
+ * The decisions the owner owes, by issue. A task branch names its task, and resolution stops there:
433
+ * that task's decision, or none when it waits for nothing (or has no state comment); the board is
434
+ * not read for it. Off a task branch, every task on the board that has one: one `scanTasks` (the
435
+ * open tasks and the ones closed today). Either read runs under `SLOW_EVENT_DEADLINE_MS`, and never
436
+ * past the deadline of the hook (`Deadline.within`): the prompt's longer deadline is for writing an
437
+ * approval, not for finding the task. A read that fails or times out is the caller's to handle.
438
+ */
439
+ async function waitingDecisions(env) {
440
+ const types = typeRegistry(env.cfg);
441
+ const { issue } = env.checkout;
442
+ const boardDeadline = env.deadline.within(SLOW_EVENT_DEADLINE_MS);
443
+ const tracker = boundedTracker(env.ctx.makeTracker(env.cfg, env.checkout.root), boardDeadline);
444
+ try {
445
+ if (issue !== undefined) {
446
+ try {
447
+ const own = waitingOf(await tracker.getTask(issue), types);
448
+ return own === undefined ? [] : [own];
449
+ }
450
+ catch (error) {
451
+ if (isMissingTaskError(error))
452
+ return [];
453
+ throw error;
454
+ }
455
+ }
456
+ const { tracked } = await tracker.scanTasks({ closedSince: env.ctx.now().slice(0, 10) });
457
+ return tracked
458
+ .flatMap(task => waitingOf(task, types) ?? [])
459
+ .sort((a, b) => a.issue - b.issue);
460
+ }
461
+ finally {
462
+ boardDeadline.stop();
463
+ }
464
+ }
465
+ const notRecordedLine = (error) => timedOut(error) ? GITHUB_UNREACHABLE : `sdlc: approval not recorded: ${oneLine(reasonOf(error))}`;
373
466
  /**
374
467
  * The owner's command in the prompt of the human, recorded as the owner's decision. `undefined`
375
468
  * when the prompt is no approval command; otherwise the line to tell the agent. Only a prompt is
376
- * ever read for this: what an agent writes in a tool call is never an approval.
469
+ * ever read for this: what an agent writes in a tool call is never an approval. The task is the one
470
+ * the command names, else the one of the branch, else the one task that waits for a decision.
377
471
  */
378
472
  async function promptApproval(env, prompt) {
379
473
  const command = parseOwnerCommand(prompt);
@@ -383,18 +477,40 @@ async function promptApproval(env, prompt) {
383
477
  if (!isApprovalAction(command.action) || command.typeId !== undefined)
384
478
  return undefined;
385
479
  const { action } = command;
386
- const { issue } = env.checkout;
387
- if (issue === undefined)
480
+ if (command.unreadableIssue === true)
481
+ return UNREADABLE_ISSUE(action);
482
+ let issue = command.issue ?? env.checkout.issue;
483
+ // `/cancel` answers no waiting request, so it never picks a task that merely waits: it needs one named or checked out.
484
+ if (issue === undefined && action === 'cancel')
388
485
  return NO_TASK_FOR_APPROVAL;
486
+ // Set just before the write: a deadline that ends before it left GitHub untouched, one that ends after it may not have.
487
+ let writing = false;
389
488
  try {
390
489
  const ctx = commandContextOf(env);
490
+ if (issue === undefined) {
491
+ let waiting;
492
+ try {
493
+ waiting = await waitingDecisions(env);
494
+ }
495
+ catch (error) {
496
+ if (timedOut(error))
497
+ return BOARD_TOO_SLOW(action);
498
+ throw error;
499
+ }
500
+ if (waiting.length > 1)
501
+ return severalWaiting(waiting);
502
+ issue = waiting[0]?.issue;
503
+ if (issue === undefined)
504
+ return NO_TASK_FOR_APPROVAL;
505
+ }
391
506
  let loaded;
392
507
  try {
393
508
  loaded = await loadTask(ctx, issue);
394
509
  }
395
510
  catch (error) {
396
- if (error instanceof CommandError && isMissingTaskError(error.cause))
397
- return NO_TASK_FOR_APPROVAL;
511
+ if (error instanceof CommandError && isMissingTaskError(error.cause)) {
512
+ return command.issue === undefined ? NO_TASK_FOR_APPROVAL : NO_SUCH_TASK_FOR_APPROVAL(issue);
513
+ }
398
514
  throw error;
399
515
  }
400
516
  const { state } = loaded.task;
@@ -416,23 +532,53 @@ async function promptApproval(env, prompt) {
416
532
  // The one write of this prompt (the comment and the state of the task): a read-only run stops before it.
417
533
  if (env.ctx.readOnly === true)
418
534
  return READ_ONLY_APPROVAL;
535
+ writing = true;
419
536
  await applyApproval(ctx, issue, { action, ...(command.reason === undefined ? {} : { reason: command.reason }) }, { source: 'prompt', ref, by: approver.by, at: env.ctx.now() }, loaded);
420
537
  return `sdlc: recorded the owner's ${action} for #${issue}${target} from this prompt.`;
421
538
  }
422
539
  catch (error) {
423
- if (timedOut(error))
424
- return GITHUB_UNREACHABLE;
425
- return `sdlc: approval not recorded: ${oneLine(reasonOf(error))}`;
540
+ if (writing && issue !== undefined)
541
+ return failedWriteLine(issue, error);
542
+ return notRecordedLine(error);
426
543
  }
427
544
  }
428
- /** Records the prompt, then reads it for an owner command. A prompt from a subagent is neither. */
545
+ /**
546
+ * For a human prompt that is no owner command: a line for each decision that waits for the owner,
547
+ * telling the agent which one it is and how to record it from this prompt (the task of the branch,
548
+ * else every task on the board). With several, the agent sees each issue and its command, and asks
549
+ * the owner which one they meant. Empty when nothing waits, and also when the board cannot be read
550
+ * in time: a reminder is a courtesy, never an error.
551
+ */
552
+ async function promptReminder(env, record) {
553
+ // The key names this prompt's record: the harness's id, or the record's time for a harness with none.
554
+ const key = record.promptId ?? record.at;
555
+ if (!SAFE_PROMPT_KEY.test(key))
556
+ return [];
557
+ try {
558
+ const waiting = await waitingDecisions(env);
559
+ return waiting.map(decision => decisionReminder(decision, key));
560
+ }
561
+ catch {
562
+ return [];
563
+ }
564
+ }
565
+ /**
566
+ * Records the prompt, then reads it for an owner command; a prompt that is none gets the reminder of
567
+ * the decision that waits for the owner. A prompt from a subagent is neither recorded nor read.
568
+ */
429
569
  async function promptEvent(env) {
430
570
  const { event } = env;
431
571
  if (event.inSubagent || event.prompt === undefined)
432
572
  return NO_OUTCOME;
433
- await recordPrompt(env, event.prompt);
573
+ const record = await recordPrompt(env, event.prompt);
434
574
  const line = await promptApproval(env, event.prompt);
435
- return line === undefined ? NO_OUTCOME : asContext(line);
575
+ if (line !== undefined)
576
+ return asContext(line);
577
+ // An owner command that is no approval (`/merge`, `/approve type <id>`) has been read and left to its comment.
578
+ if (record === undefined || parseOwnerCommand(event.prompt) !== null)
579
+ return NO_OUTCOME;
580
+ const reminder = await promptReminder(env, record);
581
+ return reminder.length === 0 ? NO_OUTCOME : asContext(...reminder);
436
582
  }
437
583
  function parsePayload(text) {
438
584
  try {
@@ -522,7 +668,7 @@ function skip(ctx, harness, reason) {
522
668
  }
523
669
  /** Runs one hook event: reads the payload, applies the rules and prints the answer. Always resolves to 0. */
524
670
  export async function runHook(harness, event, ctx) {
525
- const deadline = deadlineOf(ctx.deadlineMs ?? (event === 'pre-tool' ? DEFAULT_DEADLINE_MS : SLOW_EVENT_DEADLINE_MS));
671
+ const deadline = deadlineOf(ctx.deadlineMs ?? DEADLINE_MS[event]);
526
672
  try {
527
673
  const text = await answer(harness, event, ctx, deadline);
528
674
  if (text !== '')
@@ -149,6 +149,7 @@ async function requireTypeApproval(ctx, issue, task, typeId, url) {
149
149
  const { approval } = await validateOwnerComment({
150
150
  comment,
151
151
  action: 'approve',
152
+ issue,
152
153
  typeId,
153
154
  cfg: ctx.cfg,
154
155
  login: () => trackerStep('authenticatedLogin', undefined, () => ctx.tracker.authenticatedLogin()),
@@ -1,4 +1,4 @@
1
- import { parseOwnerCommand } from './ownerCommand.js';
1
+ import { commandFitsIssue, parseOwnerCommand } from './ownerCommand.js';
2
2
  import { applyEvent, assertApprovalTiming, TransitionError } from './stateMachine.js';
3
3
  export const APPROVAL_ACTIONS = ['approve', 'accept', 'ran', 'cancel'];
4
4
  /** The state-machine event that records `action`; `phase` is only used by `approve`, `reason` by `cancel`. */
@@ -69,10 +69,13 @@ export function recordedRefs(state) {
69
69
  const isApprovalAction = (action) => APPROVAL_ACTIONS.includes(action);
70
70
  /**
71
71
  * The approval commands (`/approve`, `/accept`, `/ran`, `/cancel <reason>`, see `parseOwnerCommand`)
72
- * among `comments`, in their order. Commands by a login in `owners` (any letter case) are the
73
- * array; the same commands by anyone else are in `ignored`. `/merge` and non-commands are dropped.
72
+ * among `comments`, in their order, for task `issue`. Commands by a login in `owners` (any letter
73
+ * case) are the array; the same commands by anyone else are in `ignored`, and so is any command that
74
+ * names another task or a number that cannot be read (`commandFitsIssue`), whoever wrote it:
75
+ * `/approve 12` on #11 or on a PR of #11 is no decision on #11, and the caller reports why instead
76
+ * of dropping it silently. `/merge` and non-commands are dropped.
74
77
  */
75
- export function parseApprovalCommands(comments, owners) {
78
+ export function parseApprovalCommands(comments, owners, issue) {
76
79
  const commands = [];
77
80
  const ignored = [];
78
81
  for (const comment of comments) {
@@ -85,7 +88,7 @@ export function parseApprovalCommands(comments, owners) {
85
88
  ...(parsed.typeId !== undefined && { typeId: parsed.typeId }),
86
89
  comment,
87
90
  };
88
- (isOwner(owners, comment.author) ? commands : ignored).push(command);
91
+ (commandFitsIssue(parsed, issue) && isOwner(owners, comment.author) ? commands : ignored).push(command);
89
92
  }
90
93
  return Object.assign(commands, { ignored });
91
94
  }
@@ -107,6 +110,7 @@ const AGENTS_HINT = 'list agent logins under `agents` in sdlc.config.yaml';
107
110
  * - otherwise the author must be a configured owner (any letter case);
108
111
  * - the first non-empty line is the `/<action>` command (`parseOwnerCommand`), not a type-change
109
112
  * approval; with `typeId`, it is `/approve type <typeId>` instead;
113
+ * - the command names no task or names `issue` (`commandFitsIssue`);
110
114
  * - the comment was not edited after posting (anyone who can write to the repo can edit it); an
111
115
  * unreadable timestamp counts as edited;
112
116
  * - it is not by the tool's own login: that is the agent approving itself, refused in enforce
@@ -136,6 +140,12 @@ export async function validateOwnerComment(check) {
136
140
  if (command.typeId !== undefined) {
137
141
  throw new ApprovalRefusedError(`comment ${comment.url} is a type-change approval, not a /${action} of the stage`);
138
142
  }
143
+ if (command.unreadableIssue === true) {
144
+ throw new ApprovalRefusedError(`comment ${comment.url}: its task number cannot be read; write it as /${action} ${check.issue}`);
145
+ }
146
+ if (!commandFitsIssue(command, check.issue)) {
147
+ throw new ApprovalRefusedError(`comment ${comment.url} names #${command.issue}, not #${check.issue}`);
148
+ }
139
149
  }
140
150
  const created = Date.parse(comment.createdAt);
141
151
  const updated = Date.parse(comment.updatedAt);
@@ -1,5 +1,13 @@
1
1
  /** What follows `/approve` in a type-change approval: `type`, then the type id. */
2
2
  const TYPE_CHANGE = /^\s+type(?=\s|$)\s*(\S*)/i;
3
+ /**
4
+ * What follows `/approve`, `/accept` or `/ran` when it names a task: a number, with or without `#`,
5
+ * then any sentence punctuation stuck to it (`11.`, `#11,`, `7!`), then whitespace or the end.
6
+ * Punctuation inside the word (`11.5`) or letters (`11a`) leave it unreadable.
7
+ */
8
+ const ISSUE_NUMBER = /^\s+#?(\d+)[.,;:!?)]*(?=\s|$)/;
9
+ /** What follows `/approve`, `/accept` or `/ran` when it starts like a task number: a digit or `#`. */
10
+ const LOOKS_LIKE_ISSUE = /^\s+[#\d]/;
3
11
  /** `/<action>` at the start of a line, then the end of the line or whitespace. */
4
12
  const COMMAND = /^\/(approve|accept|ran|merge|cancel)(?=\s|$)(.*)$/i;
5
13
  /**
@@ -7,7 +15,11 @@ const COMMAND = /^\/(approve|accept|ran|merge|cancel)(?=\s|$)(.*)$/i;
7
15
  * `/cancel <reason>`. Only the first non-empty line counts, trimmed, and the command must start it
8
16
  * (a quoted `> /approve`, `/approved` or a command further down is not a command). The action is
9
17
  * matched case-insensitively. `/cancel` needs a reason on the same line, else it is not a command.
10
- * `/approve type <id>` is a type-change approval and carries `typeId`.
18
+ * `/approve type <id>` is a type-change approval and carries `typeId`. `/approve 11`, `/accept #7`
19
+ * and `/ran 11 thanks` carry the `issue` they name (punctuation stuck to the number, as in
20
+ * `/approve 11.`, and words after it are ignored). When the rest starts with a digit or `#` but is no
21
+ * such number (`11a`, `11.5`, `#0`, `0`, `#x`), the command carries `unreadableIssue` instead: it
22
+ * names a task that cannot be read, and is for no task.
11
23
  */
12
24
  export function parseOwnerCommand(body) {
13
25
  const firstLine = body
@@ -18,12 +30,30 @@ export function parseOwnerCommand(body) {
18
30
  if (!match)
19
31
  return null;
20
32
  const action = match[1].toLowerCase();
33
+ if (action === 'cancel') {
34
+ const reason = match[2].trim();
35
+ return reason ? { action, reason } : null;
36
+ }
21
37
  if (action === 'approve') {
22
38
  const typeChange = TYPE_CHANGE.exec(match[2]);
23
- return typeChange ? { action, typeId: typeChange[1].toLowerCase() } : { action };
39
+ if (typeChange)
40
+ return { action, typeId: typeChange[1].toLowerCase() };
24
41
  }
25
- if (action !== 'cancel')
42
+ if (action === 'merge' || !LOOKS_LIKE_ISSUE.test(match[2]))
26
43
  return { action };
27
- const reason = match[2].trim();
28
- return reason ? { action, reason } : null;
44
+ const issue = namedIssue(match[2]);
45
+ return issue === undefined ? { action, unreadableIssue: true } : { action, issue };
46
+ }
47
+ /** The task number the rest of a command line starts with, `undefined` when it is no positive whole number. */
48
+ function namedIssue(rest) {
49
+ const digits = ISSUE_NUMBER.exec(rest)?.[1];
50
+ const issue = digits === undefined ? NaN : Number(digits);
51
+ return Number.isSafeInteger(issue) && issue > 0 ? issue : undefined;
52
+ }
53
+ /**
54
+ * Whether `command` may count for task `issue`: it names that task, or names none. A command that
55
+ * names another task, or a number that cannot be read, never counts for the task it sits on.
56
+ */
57
+ export function commandFitsIssue(command, issue) {
58
+ return command.unreadableIssue !== true && (command.issue === undefined || command.issue === issue);
29
59
  }
@@ -0,0 +1,45 @@
1
+ import { isAfter } from './stateMachine.js';
2
+ /**
3
+ * The decision the owner still owes on the task, or `undefined` when none waits for them. Read from
4
+ * the state alone, so a session off the task's branch can tell which task a free-form "yes" is for:
5
+ * - `ran`: an owner-confirmation task whose final PR merged;
6
+ * - `approve`: a paused task waiting on the owner whose current stage is published and not approved;
7
+ * - `accept`: a task that ends on acceptance (`owner_acceptance`, `merge_or_acceptance`) and has a
8
+ * published result that the owner has not accepted, whatever its status (such a task publishes
9
+ * its result and waits for `/accept` without pausing, and may sit in review meanwhile). A result
10
+ * published before the last reopen does not count, as the state machine clears it after a
11
+ * completed task is reopened.
12
+ * Once the final PR merged, the closing decision (`ran`, and `accept` for an owner-acceptance task)
13
+ * stands whatever the status: the state machine takes it until the task is done, however the task
14
+ * left `paused` (`stage start`, a checkpoint), and it comes before the approval of a stage that is
15
+ * still open. A reopen clears the merge, so only a merge after it counts. Before the merge, a stage
16
+ * paused for its approval comes before the result.
17
+ * A task in review waits for a merge, not for the owner's word, unless its result may be accepted
18
+ * instead. A done or cancelled task, and one that is only `waiting on owner` after a checkpoint
19
+ * without being paused, has no pending decision of its own. `cancel` is never pending: the owner
20
+ * may cancel any task, which answers no request.
21
+ */
22
+ export function pendingDecision(state, type) {
23
+ if (state.status === 'done')
24
+ return undefined;
25
+ if (state.finalMergedAt !== undefined) {
26
+ if (type.endsOn === 'owner_confirmation')
27
+ return 'ran';
28
+ if (type.endsOn === 'owner_acceptance' && state.resultPublishedAt !== undefined)
29
+ return 'accept';
30
+ }
31
+ const stage = state.stages[state.phase];
32
+ const pausedOnOwner = state.status === 'paused' && state.waitingOn === 'owner';
33
+ if (pausedOnOwner && stage !== undefined && stage.approval === undefined)
34
+ return 'approve';
35
+ const endsOnAcceptance = type.endsOn === 'owner_acceptance' || type.endsOn === 'merge_or_acceptance';
36
+ if (endsOnAcceptance && currentResult(state))
37
+ return 'accept';
38
+ return undefined;
39
+ }
40
+ /** Whether a result is published that the last reopen (if any) did not leave behind. */
41
+ function currentResult(state) {
42
+ if (state.resultPublishedAt === undefined)
43
+ return false;
44
+ return state.reopenedAt === undefined || isAfter(state.resultPublishedAt, state.reopenedAt);
45
+ }
@@ -0,0 +1,109 @@
1
+ import { normalizePrompt, promptNormSha256, SAFE_PROMPT_KEY } from '../hooks/session.js';
2
+ import { HOOK_HARNESSES } from '../hooks/types.js';
3
+ import { ALLOW_MARKER, scanAddedLines } from '../secrets/scan.js';
4
+ import { isAfter } from './stateMachine.js';
5
+ /**
6
+ * The proof behind `sdlc approve --from-prompt`: the agent judges that a free-form prompt of the
7
+ * owner is a decision, and this module checks that the text it hands over is a fresh prompt of a
8
+ * human, as the prompt hook recorded it. It cannot tell what the prompt means; it tells that the
9
+ * words are the owner's, and that they are the latest the owner wrote.
10
+ */
11
+ /** How much of the owner's prompt the issue comment quotes. */
12
+ export const QUOTE_LIMIT = 280;
13
+ /** The line that stands in for a quote that may hold a secret. */
14
+ const WITHHELD = '> quote withheld: it may contain a secret';
15
+ const isRecordLike = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
16
+ /** The key under which the reminder hands a record out: the harness's prompt id, else the time (Gemini). */
17
+ const keyOf = (record) => {
18
+ if (typeof record.promptId === 'string')
19
+ return record.promptId;
20
+ return typeof record.at === 'string' ? record.at : undefined;
21
+ };
22
+ /** Whether `record` has what an approval reference and the checks below are built from. */
23
+ const isUsable = (record) => typeof record.at === 'string' &&
24
+ typeof record.sha256 === 'string' &&
25
+ record.sha256.length >= 16 &&
26
+ HOOK_HARNESSES.includes(record.harness) &&
27
+ (record.sessionId === undefined || typeof record.sessionId === 'string') &&
28
+ (record.promptId === undefined || typeof record.promptId === 'string');
29
+ /**
30
+ * Proves that `text` is the owner's prompt `key`, and that the prompt may speak for the decision.
31
+ * Every one of these must hold, and each refusal names what failed:
32
+ * - `key` is one the hook hands out (`SAFE_PROMPT_KEY`) and a record of the prompt log has it (the
33
+ * record's prompt id, or its time when the harness gave none); the hook writes records for human
34
+ * prompts only, never for a subagent's. The last such record counts when a prompt was logged twice;
35
+ * - the record carries a normalised hash (older ones do not) and it is the hash of `text`, compared
36
+ * by `promptNormSha256`, so a trailing newline or CRLF does not matter but a changed word does;
37
+ * - it is the newest record of its session, by position in the log: once the owner writes again, an
38
+ * earlier prompt can approve nothing;
39
+ * - it is later than `notBefore` (what it decides on: the publish, the merge, the start of the task
40
+ * or its reopen), as instants; a date that cannot be read refuses. `undefined` means nothing to be
41
+ * later than: no caller passes it for a decision that can be old, `cancel` included. `what` names
42
+ * `notBefore` in the refusal.
43
+ * `records` are the lines of the prompt log, oldest first; a line that is no record is skipped.
44
+ */
45
+ export function provePrompt(records, key, text, notBefore, what = 'the published revision') {
46
+ if (!SAFE_PROMPT_KEY.test(key)) {
47
+ return { refused: 'the prompt key is not valid: use the key from the reminder (letters, digits and . _ : + - only)' };
48
+ }
49
+ const normalised = normalizePrompt(text);
50
+ if (normalised === '')
51
+ return { refused: 'the prompt text is empty: pass the owner\'s prompt on stdin' };
52
+ const log = records.filter(isRecordLike);
53
+ let index = log.length - 1;
54
+ while (index >= 0 && keyOf(log[index]) !== key)
55
+ index -= 1;
56
+ const record = log[index];
57
+ if (record === undefined) {
58
+ return { refused: `no prompt with the key ${key} was recorded by the prompt hook; use the key from the reminder of the owner's prompt` };
59
+ }
60
+ if (!isUsable(record))
61
+ return { refused: `the record of the prompt ${key} is malformed and cannot be used` };
62
+ if (typeof record.normSha256 !== 'string') {
63
+ return {
64
+ refused: `the record of the prompt ${key} has no normalised hash (it was written by an older sdlc); ask the owner to write the approval again`,
65
+ };
66
+ }
67
+ if (promptNormSha256(text) !== record.normSha256) {
68
+ return { refused: `the text does not match the owner's prompt ${key}; ask the owner to write the short phrase` };
69
+ }
70
+ const newerOfSession = log.slice(index + 1).some(later => later.sessionId === record.sessionId);
71
+ if (newerOfSession) {
72
+ return { refused: `the owner has written again since the prompt ${key}; only their latest prompt can record a decision` };
73
+ }
74
+ if (notBefore !== undefined && !isAfter(record.at, notBefore)) {
75
+ return {
76
+ refused: `the prompt ${key} (${record.at}) is older than ${what} (${notBefore}); ask the owner to write the approval again`,
77
+ };
78
+ }
79
+ return { record };
80
+ }
81
+ /**
82
+ * The owner's prompt as the issue comment quotes it: a blockquote of the first `QUOTE_LIMIT`
83
+ * characters (whole characters, never half of a surrogate pair), `…` after a cut, every line
84
+ * prefixed `> ` so nothing in it can start a line of the comment, an owner command included. The
85
+ * text goes through the kit's secret scanner first, whole, not only the part that is quoted (a cut
86
+ * must not leave half a token); on a hit the quote is withheld. The allow marker does not excuse a line here.
87
+ * GitHub still renders markdown inside a quote, so what is quoted is made inert (`inert`): no `@name`
88
+ * that notifies someone, no HTML (an HTML comment could hide words from the reader of the comment).
89
+ */
90
+ export function quoteForIssue(text) {
91
+ const full = normalizePrompt(text);
92
+ const lines = full.split('\n').map((line, index) => ({ line: index + 1, text: line.split(ALLOW_MARKER).join(' ') }));
93
+ if (scanAddedLines('prompt', lines, []).length > 0)
94
+ return WITHHELD;
95
+ const characters = Array.from(full);
96
+ const cut = characters.length > QUOTE_LIMIT;
97
+ const quoted = `${inert(cut ? characters.slice(0, QUOTE_LIMIT).join('') : full)}${cut ? '…' : ''}`;
98
+ return quoted
99
+ .split('\n')
100
+ .map(line => `> ${line}`)
101
+ .join('\n');
102
+ }
103
+ /**
104
+ * `text` as it is shown in a comment without doing anything there. A zero-width joiner after every
105
+ * `@` ends the login a mention needs (`@acme/team` and `@octocat` notify nobody, and the text reads
106
+ * the same); `<` becomes `&lt;`, so no tag and no `<!-- -->` survives. Done after the cut, so the
107
+ * limit counts the owner's characters, not what is added to them.
108
+ */
109
+ const inert = (text) => text.replace(/@/g, '@\u200D').replace(/</g, '&lt;');
@@ -28,7 +28,7 @@ export function newTask(input) {
28
28
  };
29
29
  }
30
30
  /** True when `later` is strictly after `earlier`; false if either is not a parseable date. */
31
- function isAfter(later, earlier) {
31
+ export function isAfter(later, earlier) {
32
32
  const a = Date.parse(later);
33
33
  const b = Date.parse(earlier);
34
34
  return !Number.isNaN(a) && !Number.isNaN(b) && a > b;
@@ -84,7 +84,8 @@ function runTracker(inner, dryRun) {
84
84
  * (for the phase the task is paused in, waiting on the owner), `accepted`, `confirmed_ran` or
85
85
  * `cancelled`, checked by `validateCommentApproval` like `sdlc approve`. A comment already
86
86
  * recorded as an approval is skipped silently; any other command that does not count (including
87
- * one on a PR that links more than this task) is an `ignored_approval` saying why;
87
+ * one that names another task or a number that cannot be read, and one on a PR that links more
88
+ * than this task) is an `ignored_approval` saying why;
88
89
  * 3b. each PR linking the task gets the `sdlc:partial` label when its body says `Scope: partial`
89
90
  * and loses it otherwise (`pr_label`; a PR that links several tasks is labelled once); a
90
91
  * failed label write is an `error` and the other steps still run;
@@ -282,7 +283,7 @@ async function applyApprovals(t, prs) {
282
283
  }
283
284
  // In observe mode an agent's command is recorded as unverified, so it is checked like an owner's.
284
285
  const deciders = ctx.cfg.mode === 'observe' ? [...ctx.cfg.owners, ...ctx.cfg.agents] : ctx.cfg.owners;
285
- const parsed = parseApprovalCommands(comments, deciders);
286
+ const parsed = parseApprovalCommands(comments, deciders, task.issue);
286
287
  const commands = [...parsed, ...parsed.ignored].sort((a, b) => byTime(a.comment.createdAt, b.comment.createdAt));
287
288
  const login = () => trackerStep('authenticatedLogin', undefined, () => ctx.tracker.authenticatedLogin());
288
289
  for (const command of commands) {
@@ -311,6 +312,7 @@ async function applyApprovals(t, prs) {
311
312
  const { approval } = await validateCommentApproval({
312
313
  comment,
313
314
  action,
315
+ issue: task.issue,
314
316
  phase: state.phase,
315
317
  state,
316
318
  cfg: ctx.cfg,