pi2web 0.2.0 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +169 -17
- package/dist/agents.js +126 -25
- package/dist/auth.js +83 -20
- package/dist/collab/dispatcher.js +186 -0
- package/dist/collab/hub.js +1880 -0
- package/dist/collab/pi-extension.js +237 -0
- package/dist/collab/review-flow.js +310 -0
- package/dist/collab/routes.js +214 -0
- package/dist/collab/schemas.js +225 -0
- package/dist/collab/scoring-flow.js +230 -0
- package/dist/collab/store.js +563 -0
- package/dist/collab/types.js +53 -0
- package/dist/collab/validate.js +148 -0
- package/dist/drafts.js +30 -0
- package/dist/mail-notifier.js +36 -8
- package/dist/main.js +83 -4
- package/dist/mcp.js +113 -0
- package/dist/metadata-store.js +12 -3
- package/dist/sdk-backend.js +82 -19
- package/dist/server.js +434 -58
- package/dist/session-namer.js +114 -0
- package/dist/voice.js +47 -9
- package/package.json +8 -6
- package/packages/edge-tts-server/src/remote_pi_edge_tts/__pycache__/__init__.cpython-312.pyc +0 -0
- package/packages/edge-tts-server/src/remote_pi_edge_tts/__pycache__/__main__.cpython-312.pyc +0 -0
- package/packages/protocol/openapi.yaml +2 -0
- package/packages/protocol/websocket.schema.json +47 -6
- package/web/app.js +1187 -176
- package/web/backend-state.js +237 -0
- package/web/collab.html +95 -0
- package/web/collab.js +667 -0
- package/web/hid-keyboard.js +420 -0
- package/web/index.html +11 -9
- package/web/styles.css +59 -0
- package/ANDROID_APP_FEATURES.md +0 -256
|
@@ -0,0 +1,237 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
import { StringEnum } from '@earendil-works/pi-ai';
|
|
3
|
+
import { Type } from 'typebox';
|
|
4
|
+
export const COLLAB_ACTIONS = ['ready', 'findings', 'issue_votes', 'merge_votes', 'issue_discussions', 'nominations', 'votes', 'scores', 'debate_argument', 'debate_arguments', 'escalate', 'withdraw'];
|
|
5
|
+
const evidence = Type.Object({
|
|
6
|
+
path: Type.String({ minLength: 1, description: 'Workspace-relative evidence file' }),
|
|
7
|
+
startLine: Type.Optional(Type.Number({ minimum: 1 })), endLine: Type.Optional(Type.Number({ minimum: 1 })), excerpt: Type.Optional(Type.String({ maxLength: 2000 }))
|
|
8
|
+
}, { additionalProperties: false });
|
|
9
|
+
const location = Type.Object({
|
|
10
|
+
path: Type.String({ minLength: 1, description: 'Workspace-relative file containing the finding' }),
|
|
11
|
+
startLine: Type.Optional(Type.Number({ minimum: 1 })), endLine: Type.Optional(Type.Number({ minimum: 1 }))
|
|
12
|
+
}, { additionalProperties: false });
|
|
13
|
+
const finding = Type.Object({
|
|
14
|
+
externalId: Type.Optional(Type.String({ maxLength: 100 })), title: Type.String({ minLength: 8, maxLength: 200 }),
|
|
15
|
+
severity: StringEnum(['blocker', 'critical', 'major', 'minor', 'nit']),
|
|
16
|
+
category: StringEnum(['security', 'correctness', 'performance', 'maintainability', 'style', 'test', 'docs', 'process']),
|
|
17
|
+
requiredAction: Type.Optional(StringEnum(['must_fix', 'should_fix', 'discuss', 'fyi'])), confidence: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })),
|
|
18
|
+
location, evidence: Type.String({ minLength: 10, maxLength: 4000 }), impact: Type.Optional(Type.String({ maxLength: 2000 })), suggestion: Type.Optional(Type.String({ maxLength: 4000 }))
|
|
19
|
+
}, { additionalProperties: false });
|
|
20
|
+
const TOOL_FOR_TASK = {
|
|
21
|
+
implement: 'collab_submit_ready', file_findings: 'collab_submit_findings', file_findings_optional: 'collab_submit_findings', validate_issues: 'collab_submit_issue_votes',
|
|
22
|
+
vote_on_merges: 'collab_submit_merge_votes', defend_approved_issues: 'collab_submit_issue_discussions', reconsider_issue_votes: 'collab_submit_issue_votes',
|
|
23
|
+
nominate_criteria: 'collab_submit_nominations', vote_on_criteria: 'collab_submit_votes', score_rubric: 'collab_submit_scores', rescore_contested: 'collab_submit_scores',
|
|
24
|
+
debate_contested_scores: 'collab_submit_debate_arguments'
|
|
25
|
+
};
|
|
26
|
+
const TASK_FOR_ACTION = {
|
|
27
|
+
ready: ['implement'], findings: ['file_findings', 'file_findings_optional'], issue_votes: ['validate_issues', 'reconsider_issue_votes'], merge_votes: ['vote_on_merges'],
|
|
28
|
+
issue_discussions: ['defend_approved_issues'], nominations: ['nominate_criteria'], votes: ['vote_on_criteria'], scores: ['score_rubric', 'rescore_contested'], debate_arguments: ['debate_contested_scores']
|
|
29
|
+
};
|
|
30
|
+
const SUBMIT_TOOLS = [...new Set(Object.values(TOOL_FOR_TASK))];
|
|
31
|
+
const OPTIONAL_TOOLS = ['collab_escalate', 'collab_withdraw_issue'];
|
|
32
|
+
/** Last-resort scrub for text the hub did not write for the tool flow (mostly error strings). */
|
|
33
|
+
const scrub = (text) => text
|
|
34
|
+
.replace(/(?:POST|GET|PUT|DELETE)s?\s+(?:to\s+)?\S*\/api\/v1\/\S+/gi, 'use the active collaboration submission tool')
|
|
35
|
+
.replace(/\S*\/api\/v1\/\S+/gi, 'the collaboration tool')
|
|
36
|
+
.replace(/[0-9a-f]{8}-[0-9a-f-]{16,}/gi, '[internal reference]');
|
|
37
|
+
/** Inline-only Pi extension. It is loaded solely for profile=collab sessions. */
|
|
38
|
+
export function createCollabExtension(agentId, bridge) {
|
|
39
|
+
return function collabExtension(pi) {
|
|
40
|
+
let aliases = new Map(), lastTask, baseTools;
|
|
41
|
+
const reference = (id, kind) => {
|
|
42
|
+
if (!id)
|
|
43
|
+
return id;
|
|
44
|
+
const existing = aliases.get(id);
|
|
45
|
+
if (existing)
|
|
46
|
+
return existing;
|
|
47
|
+
const prefix = kind === 'issue' ? 'issue' : kind === 'criterion' ? 'criterion' : kind === 'proposal' ? 'proposal' : kind === 'debate' ? 'debate' : kind === 'baseline' ? 'base' : kind === 'participant' ? 'reviewer' : 'ref';
|
|
48
|
+
const value = `${prefix}-${[...aliases.values()].filter(entry => entry.startsWith(`${prefix}-`)).length + 1}`;
|
|
49
|
+
aliases.set(id, value);
|
|
50
|
+
return value;
|
|
51
|
+
};
|
|
52
|
+
const redact = (value) => {
|
|
53
|
+
if (Array.isArray(value))
|
|
54
|
+
return value.map(redact);
|
|
55
|
+
if (!value || typeof value !== 'object')
|
|
56
|
+
return typeof value === 'string' && aliases.has(value) ? aliases.get(value) : value;
|
|
57
|
+
const output = {};
|
|
58
|
+
for (const [name, entry] of Object.entries(value)) {
|
|
59
|
+
if (name === 'sessionId')
|
|
60
|
+
continue;
|
|
61
|
+
const ids = typeof entry === 'string' ? [entry] : Array.isArray(entry) && entry.every(item => typeof item === 'string') ? entry : undefined;
|
|
62
|
+
if (ids && /(Id|Ids)$/.test(name)) {
|
|
63
|
+
const kind = /issue/i.test(name) ? 'issue' : /criterion/i.test(name) ? 'criterion' : /proposal/i.test(name) ? 'proposal' : /debate/i.test(name) ? 'debate' : /baseline/i.test(name) ? 'baseline' : /participant|author|reporter|target|raisedBy/i.test(name) ? 'participant' : 'ref';
|
|
64
|
+
output[name.replace(/Id(s)?$/, 'Ref$1')] = typeof entry === 'string' ? reference(entry, kind) : ids.map(item => reference(item, kind));
|
|
65
|
+
}
|
|
66
|
+
else
|
|
67
|
+
output[name] = redact(entry);
|
|
68
|
+
}
|
|
69
|
+
return output;
|
|
70
|
+
};
|
|
71
|
+
/**
|
|
72
|
+
* Aliases are assigned before the walk, not during it, for two reasons. Seat refs must line up with the panel
|
|
73
|
+
* (so "reviewer-2" means the same agent in every turn and in every argument the model writes), and any id the
|
|
74
|
+
* walk does not recognise as an id-shaped key - `progress.waitingOn` is a plain string array - would otherwise
|
|
75
|
+
* reach the model as a raw hub uuid. Findings borrow the board's own numbering so a ref survives a new turn.
|
|
76
|
+
*/
|
|
77
|
+
const seed = (task) => {
|
|
78
|
+
const counters = new Map();
|
|
79
|
+
const claim = (id, alias) => { if (typeof id === 'string' && id && !aliases.has(id))
|
|
80
|
+
aliases.set(id, alias); };
|
|
81
|
+
for (const seat of Array.isArray(task.panel) ? task.panel : []) {
|
|
82
|
+
const role = typeof seat.role === 'string' ? seat.role : 'participant', next = (counters.get(role) ?? 0) + 1;
|
|
83
|
+
counters.set(role, next);
|
|
84
|
+
claim(seat.participantId, `${role}-${next}`);
|
|
85
|
+
}
|
|
86
|
+
const walk = (value) => {
|
|
87
|
+
if (Array.isArray(value))
|
|
88
|
+
return value.forEach(walk);
|
|
89
|
+
if (!value || typeof value !== 'object')
|
|
90
|
+
return;
|
|
91
|
+
const entry = value;
|
|
92
|
+
if (typeof entry.issueId === 'string' && typeof entry.number === 'number')
|
|
93
|
+
claim(entry.issueId, `issue-${entry.number}`);
|
|
94
|
+
for (const nested of Object.values(entry))
|
|
95
|
+
walk(nested);
|
|
96
|
+
};
|
|
97
|
+
walk(task);
|
|
98
|
+
};
|
|
99
|
+
/** Hub errors name findings by hub id; the model only knows aliases, so map before falling back to scrubbing. */
|
|
100
|
+
const explain = (text) => {
|
|
101
|
+
let output = text;
|
|
102
|
+
for (const [id, alias] of aliases)
|
|
103
|
+
output = output.split(id).join(alias);
|
|
104
|
+
return scrub(output);
|
|
105
|
+
};
|
|
106
|
+
const restore = (value) => {
|
|
107
|
+
if (Array.isArray(value))
|
|
108
|
+
return value.map(restore);
|
|
109
|
+
if (!value || typeof value !== 'object') {
|
|
110
|
+
if (typeof value !== 'string')
|
|
111
|
+
return value;
|
|
112
|
+
for (const [id, alias] of aliases)
|
|
113
|
+
if (alias === value)
|
|
114
|
+
return id;
|
|
115
|
+
return value;
|
|
116
|
+
}
|
|
117
|
+
// Only alias-carrying keys are translated back to hub ids. `codeRef` is a semantic field whose value is an
|
|
118
|
+
// object (commit/dirtyHash), so renaming it to `codeId` would make the hub reject a valid ready submission.
|
|
119
|
+
const isAliasKey = (key, entry) => /Ref(s)?$/.test(key) && (typeof entry === 'string' || (Array.isArray(entry) && entry.every(item => typeof item === 'string')));
|
|
120
|
+
return Object.fromEntries(Object.entries(value).map(([key, entry]) => [isAliasKey(key, entry) ? key.replace(/Ref(s)?$/, 'Id$1') : key, restore(entry)]));
|
|
121
|
+
};
|
|
122
|
+
const taskText = (task) => {
|
|
123
|
+
const safe = redact(task), context = { ...safe };
|
|
124
|
+
delete context.task;
|
|
125
|
+
delete context.instructions;
|
|
126
|
+
const lines = ['Local code collaboration task.'];
|
|
127
|
+
if (safe.task)
|
|
128
|
+
lines.push(`Current action: ${safe.task}.`);
|
|
129
|
+
if (safe.phase)
|
|
130
|
+
lines.push(`Phase: ${safe.phase}${safe.round !== undefined ? `, round ${safe.round}` : ''}.`);
|
|
131
|
+
const subject = safe.subject;
|
|
132
|
+
if (typeof subject?.value === 'string')
|
|
133
|
+
lines.push(`User request: ${subject.value}`);
|
|
134
|
+
if (typeof subject?.notes === 'string')
|
|
135
|
+
lines.push(`User notes: ${subject.notes}`);
|
|
136
|
+
if (safe.task !== 'implement')
|
|
137
|
+
lines.push('Workspace constraint: this task is non-mutating. Do not create, delete, rename, or modify files under the working directory, including scratch files, redirected command output, generated files, caches, or formatter changes. Send inspection output to stdout; use an OS temporary directory outside the workspace only when unavoidable.');
|
|
138
|
+
if (typeof safe.instructions === 'string')
|
|
139
|
+
lines.push(`Instructions: ${scrub(safe.instructions)}`);
|
|
140
|
+
if (Object.keys(context).length)
|
|
141
|
+
lines.push(`Task context:\n${JSON.stringify(context, null, 2)}`);
|
|
142
|
+
const submit = TOOL_FOR_TASK[String(safe.task ?? '')];
|
|
143
|
+
lines.push(submit ? `Complete every required Ref with ${submit}, then end the turn.` : 'No submission is required; end the turn.');
|
|
144
|
+
return lines.join('\n');
|
|
145
|
+
};
|
|
146
|
+
const currentTask = () => String(lastTask?.task ?? '');
|
|
147
|
+
const normalize = (action, payload) => {
|
|
148
|
+
const body = restore(payload);
|
|
149
|
+
if (action === 'findings') {
|
|
150
|
+
if (!body.baselineId && lastTask?.baseline && typeof lastTask.baseline.baselineId === 'string')
|
|
151
|
+
body.baselineId = lastTask.baseline.baselineId;
|
|
152
|
+
body.reviewComplete = true;
|
|
153
|
+
}
|
|
154
|
+
if (action === 'nominations')
|
|
155
|
+
body.nominationsComplete = true;
|
|
156
|
+
if (action !== 'withdraw')
|
|
157
|
+
body.clientRequestId = randomUUID();
|
|
158
|
+
return body;
|
|
159
|
+
};
|
|
160
|
+
const rememberBaseTools = () => { if (!baseTools)
|
|
161
|
+
baseTools = pi.getActiveTools().filter(name => !SUBMIT_TOOLS.includes(name) && !OPTIONAL_TOOLS.includes(name) && name !== 'collab_get_task'); };
|
|
162
|
+
const activate = (task) => {
|
|
163
|
+
rememberBaseTools();
|
|
164
|
+
const taskName = String(task?.task ?? '');
|
|
165
|
+
// Tool names are not an integrity boundary: bash can write just as readily as edit/write, while edit/write
|
|
166
|
+
// may still be useful for scratch work outside the reviewed checkout. Keep the normal tools available,
|
|
167
|
+
// state the non-mutation contract explicitly, and let the baseline comparison enforce workspace identity.
|
|
168
|
+
const submit = TOOL_FOR_TASK[taskName], optional = taskName && taskName !== 'wait' ? ['collab_escalate', ...(taskName.includes('issue') || taskName === 'validate_issues' ? ['collab_withdraw_issue'] : [])] : [];
|
|
169
|
+
pi.setActiveTools([...new Set([...baseTools, 'collab_get_task', ...(submit ? [submit] : []), ...optional])]);
|
|
170
|
+
};
|
|
171
|
+
const assertTask = (action) => {
|
|
172
|
+
const allowed = TASK_FOR_ACTION[action];
|
|
173
|
+
if (allowed && !allowed.includes(currentTask()))
|
|
174
|
+
throw new Error(`The active task is ${currentTask() || 'unknown'}, which cannot submit ${action}. Call collab_get_task again.`);
|
|
175
|
+
};
|
|
176
|
+
const acceptedText = (result) => `Collaboration submission accepted.${result && typeof result === 'object' ? ` ${JSON.stringify(redact(result))}` : ''}`;
|
|
177
|
+
const registerSubmit = (definition) => pi.registerTool({
|
|
178
|
+
name: definition.name, label: definition.label, description: definition.description, promptSnippet: definition.description,
|
|
179
|
+
promptGuidelines: [`Use ${definition.name} only after collab_get_task requests it, and include every required Ref exactly once.`], parameters: definition.parameters,
|
|
180
|
+
async execute(_id, input) {
|
|
181
|
+
try {
|
|
182
|
+
assertTask(definition.action);
|
|
183
|
+
const result = await bridge.submit(agentId, definition.action, normalize(definition.action, input));
|
|
184
|
+
return { content: [{ type: 'text', text: acceptedText(result) }], details: { result: redact(result) }, terminate: definition.terminate ?? true };
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
const fields = error.fieldErrors;
|
|
188
|
+
throw new Error(explain(`${error.message ?? 'Submission failed'}${fields ? ` ${JSON.stringify(fields)}` : ''}`));
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
});
|
|
192
|
+
pi.on('session_start', () => { baseTools = undefined; lastTask = undefined; aliases = new Map(); activate(); });
|
|
193
|
+
pi.on('before_agent_start', event => {
|
|
194
|
+
lastTask = undefined;
|
|
195
|
+
aliases = new Map();
|
|
196
|
+
activate();
|
|
197
|
+
return { systemPrompt: `${event.systemPrompt}\n\n## Local collaboration\nThis is a local software-development workflow. Call collab_get_task first after every collaboration wake-up. Use only the collaboration submission tool activated for that task. Review and scoring are strictly non-mutating: bash may inspect with commands such as git diff/log, but must not write anywhere under the working directory—not through redirection, tee, file-management commands, formatters, generators, package installation, build artifacts, caches, or scratch files. Send command output to stdout, or if temporary storage is unavoidable use the OS temporary directory outside the workspace. Only an implement task may modify the workspace. The tools own transport and credentials: never use curl, invent endpoints or identifiers, sleep, or poll.` };
|
|
198
|
+
});
|
|
199
|
+
pi.registerTool({
|
|
200
|
+
name: 'collab_get_task', label: 'Get Collaboration Task', description: 'Get the complete current collaboration assignment and activate its exact typed submission tool.',
|
|
201
|
+
promptSnippet: 'Fetch the current collaboration assignment before doing any collaboration work', promptGuidelines: ['Call collab_get_task first after every pi2web collaboration wake-up.'], parameters: Type.Object({}, { additionalProperties: false }),
|
|
202
|
+
async execute() { aliases = new Map(); lastTask = await bridge.getTask(agentId); seed(lastTask); activate(lastTask); return { content: [{ type: 'text', text: taskText(lastTask) }], details: { task: redact(lastTask) } }; }
|
|
203
|
+
});
|
|
204
|
+
registerSubmit({ name: 'collab_submit_ready', label: 'Submit Implementation', action: 'ready', description: 'Declare the assigned implementation complete with an auditable change summary.', parameters: Type.Object({
|
|
205
|
+
summary: Type.String({ minLength: 10, maxLength: 4000 }), changes: Type.Array(Type.Object({ path: Type.String({ minLength: 1 }), summary: Type.String({ minLength: 5 }) }, { additionalProperties: false }), { maxItems: 100 }),
|
|
206
|
+
codeRef: Type.Optional(Type.Object({ commit: Type.Optional(Type.String()), dirtyHash: Type.Optional(Type.String()) }, { additionalProperties: false }))
|
|
207
|
+
}, { additionalProperties: false }) });
|
|
208
|
+
registerSubmit({ name: 'collab_submit_findings', label: 'Submit Review Findings', action: 'findings', description: 'Submit the complete blind review, including every required recheck and all new evidence-backed findings.', parameters: Type.Object({
|
|
209
|
+
findings: Type.Array(finding, { maxItems: 50 }), rechecks: Type.Optional(Type.Array(Type.Object({ issueRef: Type.String(), outcome: StringEnum(['resolved', 'still_present']), rationale: Type.String({ minLength: 10, maxLength: 4000 }) }, { additionalProperties: false }), { maxItems: 100 }))
|
|
210
|
+
}, { additionalProperties: false }) });
|
|
211
|
+
registerSubmit({ name: 'collab_submit_issue_votes', label: 'Submit Issue Votes', action: 'issue_votes', description: 'Vote on every required issue and optionally propose duplicate groups.', parameters: Type.Object({
|
|
212
|
+
votes: Type.Array(Type.Object({ issueRef: Type.String(), stance: StringEnum(['approve', 'reject']), rationale: Type.Optional(Type.String({ maxLength: 4000 })) }, { additionalProperties: false }), { maxItems: 200, description: 'One vote per Ref in yourRequiredIssueIds; an empty array is only accepted when you owe none' }),
|
|
213
|
+
mergeProposals: Type.Optional(Type.Array(Type.Object({ issueRefs: Type.Array(Type.String(), { minItems: 2, maxItems: 20 }), rationale: Type.String({ minLength: 10, maxLength: 2000 }) }, { additionalProperties: false }), { maxItems: 50 }))
|
|
214
|
+
}, { additionalProperties: false }) });
|
|
215
|
+
registerSubmit({ name: 'collab_submit_merge_votes', label: 'Submit Merge Votes', action: 'merge_votes', description: 'Vote on every required duplicate-merge proposal.', parameters: Type.Object({ votes: Type.Array(Type.Object({ proposalRef: Type.String(), stance: StringEnum(['approve', 'reject']), rationale: Type.Optional(Type.String({ maxLength: 4000 })) }, { additionalProperties: false }), { minItems: 1, maxItems: 100 }) }, { additionalProperties: false }) });
|
|
216
|
+
registerSubmit({ name: 'collab_submit_issue_discussions', label: 'Submit Issue Arguments', action: 'issue_discussions', description: 'Defend every required finding with evidence, and withdraw the ones you no longer stand by.', parameters: Type.Object({
|
|
217
|
+
discussions: Type.Optional(Type.Array(Type.Object({ issueRef: Type.String(), argument: Type.String({ minLength: 20, maxLength: 4000 }), respondingTo: Type.Optional(Type.String()) }, { additionalProperties: false }), { maxItems: 200 })),
|
|
218
|
+
withdrawals: Type.Optional(Type.Array(Type.Object({ issueRef: Type.String(), rationale: Type.String({ minLength: 10, maxLength: 4000, description: 'Why you no longer stand by your own finding' }) }, { additionalProperties: false }), { maxItems: 200 }))
|
|
219
|
+
}, { additionalProperties: false }) });
|
|
220
|
+
registerSubmit({ name: 'collab_submit_nominations', label: 'Submit Criteria Nominations', action: 'nominations', description: 'Submit the complete independent set of proposed scoring criteria.', parameters: Type.Object({ nominations: Type.Array(Type.Object({
|
|
221
|
+
externalId: Type.Optional(Type.String()), name: Type.String({ minLength: 2, maxLength: 80 }), definition: Type.String({ minLength: 20, maxLength: 2000 }), weightSuggestion: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })), anchors: Type.Optional(Type.Record(Type.String(), Type.String())), rationale: Type.Optional(Type.String({ maxLength: 2000 }))
|
|
222
|
+
}, { additionalProperties: false }), { maxItems: 20 }) }, { additionalProperties: false }) });
|
|
223
|
+
registerSubmit({ name: 'collab_submit_votes', label: 'Submit Criteria Votes', action: 'votes', description: 'Vote exactly once on every required rubric candidate.', parameters: Type.Object({ votes: Type.Array(Type.Object({
|
|
224
|
+
criterionRef: Type.String(), stance: StringEnum(['approve', 'reject', 'abstain']), weight: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })), amendment: Type.Optional(Type.String({ maxLength: 1000 })), rationale: Type.Optional(Type.String({ maxLength: 2000 }))
|
|
225
|
+
}, { additionalProperties: false }), { minItems: 1, maxItems: 40 }) }, { additionalProperties: false }) });
|
|
226
|
+
registerSubmit({ name: 'collab_submit_scores', label: 'Submit Rubric Scores', action: 'scores', description: 'Score exactly once every required criterion with rationale and file evidence.', parameters: Type.Object({ scores: Type.Array(Type.Object({
|
|
227
|
+
criterionRef: Type.String(), score: Type.Number(), rationale: Type.String({ minLength: 20, maxLength: 4000 }), evidence: Type.Array(evidence, { minItems: 1, maxItems: 20 }), confidence: Type.Optional(Type.Number({ minimum: 0, maximum: 1 })), changeReason: Type.Optional(Type.String({ maxLength: 2000 }))
|
|
228
|
+
}, { additionalProperties: false }), { minItems: 1, maxItems: 40 }) }, { additionalProperties: false }) });
|
|
229
|
+
registerSubmit({ name: 'collab_submit_debate_arguments', label: 'Submit Score Debate', action: 'debate_arguments', description: 'Submit one evidence-backed position for every required contested-criterion debate.', parameters: Type.Object({ arguments: Type.Array(Type.Object({
|
|
230
|
+
debateRef: Type.String(), stance: StringEnum(['raise', 'lower', 'hold']), argument: Type.String({ minLength: 20, maxLength: 4000 }), evidence: Type.Optional(Type.Array(evidence, { maxItems: 20 })), respondingTo: Type.Optional(Type.String())
|
|
231
|
+
}, { additionalProperties: false }), { minItems: 1, maxItems: 40 }) }, { additionalProperties: false }) });
|
|
232
|
+
registerSubmit({ name: 'collab_escalate', label: 'Escalate Collaboration', action: 'escalate', description: 'Escalate a genuine blocker or unresolved judgment to the human operator.', terminate: false, parameters: Type.Object({
|
|
233
|
+
kind: StringEnum(['issue_dispute', 'rubric_dispute', 'score_dispute', 'other']), refRef: Type.Optional(Type.String()), summary: Type.String({ minLength: 20, maxLength: 2000 }), question: Type.String({ minLength: 10, maxLength: 1000 }), options: Type.Optional(Type.Array(Type.String(), { maxItems: 10 })), urgency: Type.Optional(StringEnum(['low', 'normal', 'high']))
|
|
234
|
+
}, { additionalProperties: false }) });
|
|
235
|
+
registerSubmit({ name: 'collab_withdraw_issue', label: 'Withdraw Issue', action: 'withdraw', description: 'Withdraw one of your own findings when you no longer stand by it. Does not end your turn.', terminate: false, parameters: Type.Object({ issueRef: Type.String() }, { additionalProperties: false }) });
|
|
236
|
+
};
|
|
237
|
+
}
|
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
import { COLLAB_ERRORS, OPEN_ISSUE_STATUSES, can } from './types.js';
|
|
2
|
+
export const flowError = (code, message, httpStatus = 409) => Object.assign(new Error(message), { code, httpStatus });
|
|
3
|
+
const active = (snapshot) => snapshot.participants.filter(participant => participant.state !== 'left');
|
|
4
|
+
const findParticipant = (snapshot, participantId) => snapshot.participants.find(participant => participant.participantId === participantId);
|
|
5
|
+
const unique = (values) => [...new Set(values)];
|
|
6
|
+
const reviewers = (snapshot) => active(snapshot).filter(participant => participant.role === 'reviewer');
|
|
7
|
+
/** Only findings created in this review round need panel validation; older confirmed findings are rechecked separately. */
|
|
8
|
+
const consensusIssues = (snapshot) => snapshot.issues.filter(issue => issue.status === 'open' && issue.round === snapshot.round);
|
|
9
|
+
export function currentIssueVotes(snapshot) {
|
|
10
|
+
const latest = new Map();
|
|
11
|
+
for (const vote of snapshot.issueVotes ?? []) {
|
|
12
|
+
if (vote.round !== snapshot.round)
|
|
13
|
+
continue;
|
|
14
|
+
const key = `${vote.issueId}:${vote.participantId}`, previous = latest.get(key);
|
|
15
|
+
if (!previous || vote.consensusRound > previous.consensusRound || (vote.consensusRound === previous.consensusRound && vote.createdAt > previous.createdAt))
|
|
16
|
+
latest.set(key, vote);
|
|
17
|
+
}
|
|
18
|
+
return [...latest.values()];
|
|
19
|
+
}
|
|
20
|
+
export function issueConsensus(snapshot, options = {}) {
|
|
21
|
+
const panel = reviewers(snapshot);
|
|
22
|
+
return (options.includeFinal ? snapshot.issues : consensusIssues(snapshot)).map(issue => {
|
|
23
|
+
// The audit view includes findings from earlier review rounds, so read each issue's own latest ballot rather
|
|
24
|
+
// than accidentally showing the current round's (usually absent) votes against every historical issue.
|
|
25
|
+
const issueVotes = (snapshot.issueVotes ?? []).filter(vote => vote.issueId === issue.issueId && vote.round === issue.round);
|
|
26
|
+
const latest = new Map();
|
|
27
|
+
for (const vote of issueVotes) {
|
|
28
|
+
const previous = latest.get(vote.participantId);
|
|
29
|
+
if (!previous || vote.consensusRound > previous.consensusRound || (vote.consensusRound === previous.consensusRound && vote.createdAt > previous.createdAt))
|
|
30
|
+
latest.set(vote.participantId, vote);
|
|
31
|
+
}
|
|
32
|
+
const positions = panel.map(reviewer => reviewer.participantId === issue.reporterId
|
|
33
|
+
? { participantId: reviewer.participantId, stance: 'approve', implicit: true }
|
|
34
|
+
: { participantId: reviewer.participantId, stance: latest.get(reviewer.participantId)?.stance, rationale: latest.get(reviewer.participantId)?.rationale, implicit: false });
|
|
35
|
+
return { issueId: issue.issueId, positions, missing: positions.filter(position => !position.stance).map(position => position.participantId), rejecters: positions.filter(position => position.stance === 'reject').map(position => position.participantId), supporters: positions.filter(position => position.stance === 'approve').map(position => position.participantId), unanimous: positions.length > 0 && positions.every(position => position.stance === 'approve') };
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export const contestedIssueIds = (snapshot) => issueConsensus(snapshot).filter(entry => entry.rejecters.length > 0).map(entry => entry.issueId);
|
|
39
|
+
/** Latest ballot per reviewer for one issue as it stood at the end of consensus round `consensusRound`. */
|
|
40
|
+
function stancesAt(snapshot, issueId, consensusRound) {
|
|
41
|
+
const latest = new Map();
|
|
42
|
+
for (const vote of snapshot.issueVotes ?? []) {
|
|
43
|
+
if (vote.issueId !== issueId || vote.round !== snapshot.round || vote.consensusRound > consensusRound)
|
|
44
|
+
continue;
|
|
45
|
+
const previous = latest.get(vote.participantId);
|
|
46
|
+
if (!previous || vote.consensusRound > previous.consensusRound || (vote.consensusRound === previous.consensusRound && vote.createdAt > previous.createdAt))
|
|
47
|
+
latest.set(vote.participantId, vote);
|
|
48
|
+
}
|
|
49
|
+
return [...latest.entries()].map(([participantId, vote]) => `${participantId}:${vote.stance}`).sort().join('|');
|
|
50
|
+
}
|
|
51
|
+
const lastVotedRound = (snapshot, issueId) => Math.max(-1, ...(snapshot.issueVotes ?? []).filter(vote => vote.issueId === issueId && vote.round === snapshot.round).map(vote => vote.consensusRound));
|
|
52
|
+
/**
|
|
53
|
+
* Discussion rounds are only worth their tokens while they still move somebody. An issue whose ballot has been
|
|
54
|
+
* identical for two consecutive reconsiderations is settled in fact, so the panel stops re-arguing it instead of
|
|
55
|
+
* burning every remaining round (observed: three rounds of "I keep the rejection" on findings nobody flipped).
|
|
56
|
+
* Two rounds of silence, not one: a rejecter that needs a second round of evidence is a real convergence path.
|
|
57
|
+
* Measured against the last round that actually voted, so a round in progress is never judged before its ballots.
|
|
58
|
+
*/
|
|
59
|
+
export function staleContestedIssueIds(snapshot) {
|
|
60
|
+
return contestedIssueIds(snapshot).filter(issueId => {
|
|
61
|
+
const voted = lastVotedRound(snapshot, issueId);
|
|
62
|
+
if (voted < 2)
|
|
63
|
+
return false;
|
|
64
|
+
const current = stancesAt(snapshot, issueId, voted);
|
|
65
|
+
return current === stancesAt(snapshot, issueId, voted - 1) && current === stancesAt(snapshot, issueId, voted - 2);
|
|
66
|
+
});
|
|
67
|
+
}
|
|
68
|
+
/** Contested findings the panel is still allowed to spend a round on. */
|
|
69
|
+
export function activeContestedIssueIds(snapshot) {
|
|
70
|
+
const stale = new Set(staleContestedIssueIds(snapshot));
|
|
71
|
+
return contestedIssueIds(snapshot).filter(issueId => !stale.has(issueId));
|
|
72
|
+
}
|
|
73
|
+
/** Findings a human is actually worth interrupting for; everything below this the panel settles itself. */
|
|
74
|
+
const HUMAN_REVIEW_SEVERITIES = ['blocker', 'critical'];
|
|
75
|
+
const MAJOR_SEVERITIES = ['blocker', 'critical', 'major'];
|
|
76
|
+
/**
|
|
77
|
+
* Closes out the consensus stage. Escalating every disagreement makes a panel of N a queue of N disputes for the
|
|
78
|
+
* human (observed: 6 of 18 findings, including two the reporter itself had conceded), so only two situations
|
|
79
|
+
* genuinely need a ruling: a split panel on a serious finding, and a serious finding the whole panel rejected
|
|
80
|
+
* over its reporter's objection. Everything else is decided by the panel and recorded.
|
|
81
|
+
*/
|
|
82
|
+
export function resolveContestedIssues(snapshot) {
|
|
83
|
+
const panel = reviewers(snapshot);
|
|
84
|
+
return issueConsensus(snapshot).filter(entry => entry.rejecters.length > 0).map(entry => {
|
|
85
|
+
const issue = snapshot.issues.find(candidate => candidate.issueId === entry.issueId);
|
|
86
|
+
const severity = issue?.severity ?? 'major';
|
|
87
|
+
const voters = panel.filter(reviewer => reviewer.participantId !== issue?.reporterId).map(reviewer => reviewer.participantId);
|
|
88
|
+
const base = { issueId: entry.issueId, severity, supporters: entry.supporters, rejecters: entry.rejecters };
|
|
89
|
+
// The reporter is the only supporter left: the panel says this is not a defect, and it had every discussion
|
|
90
|
+
// round to withdraw it or convince somebody. Only a claimed blocker still buys a human's attention. Two
|
|
91
|
+
// dissenters minimum: on a two-seat panel "everyone else" is one reviewer, which is a tie, not a verdict.
|
|
92
|
+
if (voters.length > 1 && voters.every(participantId => entry.rejecters.includes(participantId)))
|
|
93
|
+
return { ...base, disposition: HUMAN_REVIEW_SEVERITIES.includes(severity) ? 'escalate' : 'panel_rejected', reason: 'panel_unanimously_rejected' };
|
|
94
|
+
if (MAJOR_SEVERITIES.includes(severity))
|
|
95
|
+
return { ...base, disposition: 'escalate', reason: 'split_panel_on_a_major_finding' };
|
|
96
|
+
if (entry.rejecters.length > entry.supporters.length)
|
|
97
|
+
return { ...base, disposition: 'majority_rejected', reason: 'panel_majority_rejected' };
|
|
98
|
+
// A tie keeps the finding: reporting it costs a line in the report, dropping a real defect costs a release.
|
|
99
|
+
return { ...base, disposition: 'majority_confirmed', reason: entry.supporters.length === entry.rejecters.length ? 'tie_kept_as_a_recorded_dispute' : 'panel_majority_confirmed' };
|
|
100
|
+
});
|
|
101
|
+
}
|
|
102
|
+
const currentMergeProposals = (snapshot) => (snapshot.mergeProposals ?? []).filter(proposal => proposal.round === snapshot.round);
|
|
103
|
+
const collectedThisRound = (snapshot) => new Set(snapshot.completions.filter(entry => entry.phase === 'collecting' && entry.round === snapshot.round).map(entry => entry.participantId));
|
|
104
|
+
/** Reviewers who already closed their own blind review but still owe votes on other reviewers' already-filed issues. */
|
|
105
|
+
export function pendingCrossVoters(snapshot) {
|
|
106
|
+
if (snapshot.phase !== 'collecting' || !snapshot.policy.consensusReview)
|
|
107
|
+
return [];
|
|
108
|
+
const collected = collectedThisRound(snapshot);
|
|
109
|
+
return unique(issueConsensus(snapshot).flatMap(entry => entry.missing)).filter(participantId => collected.has(participantId));
|
|
110
|
+
}
|
|
111
|
+
export const owedIssueVoteIds = (snapshot, participantId) => issueConsensus(snapshot).filter(entry => entry.missing.includes(participantId)).map(entry => entry.issueId);
|
|
112
|
+
/** Statuses nobody may move again without a human: rulings are final. */
|
|
113
|
+
export const FINAL_ISSUE_STATUSES = ['human_ruled', 'wontfix', 'closed', 'duplicate', 'withdrawn'];
|
|
114
|
+
export const isOpenIssue = (issue) => OPEN_ISSUE_STATUSES.includes(issue.status);
|
|
115
|
+
export function assertCapability(participant, capability) {
|
|
116
|
+
if (participant.state === 'budget_exhausted')
|
|
117
|
+
throw flowError(COLLAB_ERRORS.budgetExhausted, 'Token budget is exhausted for this participant. A human must raise the budget or replace the agent.', 429);
|
|
118
|
+
if (participant.state === 'left')
|
|
119
|
+
throw flowError(COLLAB_ERRORS.forbidden, 'This participant has left the session', 403);
|
|
120
|
+
if (!can(participant.role, capability))
|
|
121
|
+
throw flowError(COLLAB_ERRORS.forbidden, `Role ${participant.role} may not perform ${capability}`, 403);
|
|
122
|
+
}
|
|
123
|
+
export function assertPhase(snapshot, phases, action) {
|
|
124
|
+
if (snapshot.status !== 'active')
|
|
125
|
+
throw flowError(COLLAB_ERRORS.wrongPhase, `Session is ${snapshot.status}; ${action} is no longer accepted`);
|
|
126
|
+
if (!phases.includes(snapshot.phase))
|
|
127
|
+
throw flowError(COLLAB_ERRORS.wrongPhase, `${action} is only accepted in phase ${phases.join(' or ')}, but the session is in ${snapshot.phase}`);
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Participants that must act before the current phase can advance.
|
|
131
|
+
* Filing findings is required of reviewers only: an implementer's reverse findings are optional,
|
|
132
|
+
* otherwise every session would deadlock waiting for an implementer with nothing to report.
|
|
133
|
+
*/
|
|
134
|
+
export function requiredActors(snapshot) {
|
|
135
|
+
const participants = active(snapshot);
|
|
136
|
+
switch (snapshot.phase) {
|
|
137
|
+
case 'implementing': return participants.filter(participant => participant.role === 'implementer').map(participant => participant.participantId);
|
|
138
|
+
case 'collecting': return participants.filter(participant => participant.role === 'reviewer').map(participant => participant.participantId);
|
|
139
|
+
// A reviewer that owes no ballot is already done. There is no empty submission for it to make, so requiring
|
|
140
|
+
// one would park the phase on a seat that can never satisfy it.
|
|
141
|
+
case 'validating': return reviewers(snapshot).filter(participant => owedIssueVoteIds(snapshot, participant.participantId).length).map(participant => participant.participantId);
|
|
142
|
+
case 'merge_voting': return reviewers(snapshot).filter(participant => currentMergeProposals(snapshot).some(proposal => !proposal.votes.some(vote => vote.participantId === participant.participantId))).map(participant => participant.participantId);
|
|
143
|
+
case 'issue_discussing': {
|
|
144
|
+
const contested = new Set(activeContestedIssueIds(snapshot));
|
|
145
|
+
return unique(issueConsensus(snapshot).filter(entry => contested.has(entry.issueId)).flatMap(entry => entry.supporters));
|
|
146
|
+
}
|
|
147
|
+
case 'issue_reconsidering': {
|
|
148
|
+
const contested = new Set(activeContestedIssueIds(snapshot));
|
|
149
|
+
return unique(issueConsensus(snapshot).filter(entry => contested.has(entry.issueId)).flatMap(entry => entry.rejecters));
|
|
150
|
+
}
|
|
151
|
+
// responding/adjudicating are legacy persisted phases. New reviews finish after panel consensus.
|
|
152
|
+
default: return [];
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
/** Required actors that have not finished yet. An exhausted or departed participant still blocks: a human must intervene. */
|
|
156
|
+
export function waitingOn(snapshot) {
|
|
157
|
+
const required = requiredActors(snapshot);
|
|
158
|
+
if (['collecting', 'implementing', 'validating', 'merge_voting', 'issue_discussing', 'issue_reconsidering'].includes(snapshot.phase)) {
|
|
159
|
+
const done = new Set(snapshot.completions.filter(entry => entry.phase === snapshot.phase && entry.round === snapshot.round).map(entry => entry.participantId));
|
|
160
|
+
return required.filter(participantId => !done.has(participantId));
|
|
161
|
+
}
|
|
162
|
+
return required;
|
|
163
|
+
}
|
|
164
|
+
export function isReadyToAdvance(snapshot) {
|
|
165
|
+
if (snapshot.status !== 'active')
|
|
166
|
+
return false;
|
|
167
|
+
if (snapshot.phase === 'consolidating')
|
|
168
|
+
return true;
|
|
169
|
+
if (snapshot.phase === 'awaiting_human')
|
|
170
|
+
return snapshot.pendingEscalations === 0;
|
|
171
|
+
if (['draft', 'finished'].includes(snapshot.phase))
|
|
172
|
+
return false;
|
|
173
|
+
return waitingOn(snapshot).length === 0;
|
|
174
|
+
}
|
|
175
|
+
/**
|
|
176
|
+
* Computes the next phase. `forced` is the human override used to break a stall; it is the only way
|
|
177
|
+
* to move past participants that never submitted, and the skipped participants are reported for the log.
|
|
178
|
+
*/
|
|
179
|
+
export function nextPhase(snapshot, options = {}) {
|
|
180
|
+
if (snapshot.status !== 'active')
|
|
181
|
+
throw flowError(COLLAB_ERRORS.wrongPhase, `Session is ${snapshot.status}`);
|
|
182
|
+
const pending = waitingOn(snapshot);
|
|
183
|
+
if (!isReadyToAdvance(snapshot) && !options.forced) {
|
|
184
|
+
if (snapshot.phase === 'draft')
|
|
185
|
+
throw flowError(COLLAB_ERRORS.wrongPhase, 'Open the first round before advancing');
|
|
186
|
+
if (snapshot.phase === 'awaiting_human')
|
|
187
|
+
throw flowError(COLLAB_ERRORS.wrongPhase, `${snapshot.pendingEscalations} escalation(s) still await a human ruling`);
|
|
188
|
+
throw flowError(COLLAB_ERRORS.wrongPhase, `Still waiting on ${pending.length} participant(s): ${pending.join(', ')}`);
|
|
189
|
+
}
|
|
190
|
+
const skipped = options.forced && pending.length ? { skipped: pending } : {};
|
|
191
|
+
// A participant may explicitly ask for a human during any consensus step. Finish the current batched step,
|
|
192
|
+
// then stop before another debate round instead of silently debating past an open escalation.
|
|
193
|
+
if (snapshot.pendingEscalations > 0 && snapshot.phase !== 'awaiting_human')
|
|
194
|
+
return { phase: 'awaiting_human', round: snapshot.round, debateRound: snapshot.debateRound, reason: 'participant_escalated', ...skipped };
|
|
195
|
+
switch (snapshot.phase) {
|
|
196
|
+
case 'draft': return snapshot.policy.implementationFirst
|
|
197
|
+
? { phase: 'implementing', round: snapshot.round, reason: 'implementation_started', ...skipped }
|
|
198
|
+
: { phase: 'collecting', round: snapshot.round, reason: 'round_opened', ...skipped };
|
|
199
|
+
// The implementer declares itself done (or a managed agent goes idle); only then are the reviewers called.
|
|
200
|
+
case 'implementing': return { phase: 'collecting', round: snapshot.round, reason: 'implementation_ready', ...skipped };
|
|
201
|
+
case 'collecting': return { phase: 'consolidating', round: snapshot.round, reason: 'findings_complete', ...skipped };
|
|
202
|
+
case 'consolidating': {
|
|
203
|
+
if (!snapshot.policy.consensusReview)
|
|
204
|
+
return { phase: 'finished', round: snapshot.round, reason: 'review_complete', ...skipped };
|
|
205
|
+
// Who still owes a ballot is `waitingOn`'s job, not a second implementation of it here.
|
|
206
|
+
if (waitingOn({ ...snapshot, phase: 'validating' }).length)
|
|
207
|
+
return { phase: 'validating', round: snapshot.round, reason: 'issue_validation_started', ...skipped };
|
|
208
|
+
const proposals = currentMergeProposals(snapshot);
|
|
209
|
+
if (proposals.length && !snapshot.completions.some(entry => entry.phase === 'merge_voting' && entry.round === snapshot.round && entry.participantId === 'system'))
|
|
210
|
+
return { phase: 'merge_voting', round: snapshot.round, reason: 'merge_voting_started', ...skipped };
|
|
211
|
+
return contestedIssueIds(snapshot).length
|
|
212
|
+
? { phase: 'issue_discussing', round: snapshot.round, debateRound: Math.max(1, snapshot.debateRound ?? 0), reason: 'issue_votes_contested', ...skipped }
|
|
213
|
+
: { phase: 'finished', round: snapshot.round, reason: 'review_consensus_complete', ...skipped };
|
|
214
|
+
}
|
|
215
|
+
case 'validating': return { phase: 'consolidating', round: snapshot.round, reason: 'issue_validation_complete', ...skipped };
|
|
216
|
+
case 'merge_voting': return { phase: 'consolidating', round: snapshot.round, reason: 'merge_voting_complete', ...skipped };
|
|
217
|
+
case 'issue_discussing': return { phase: 'issue_reconsidering', round: snapshot.round, debateRound: snapshot.debateRound ?? 1, reason: 'supporter_arguments_complete', ...skipped };
|
|
218
|
+
case 'issue_reconsidering': {
|
|
219
|
+
const contested = contestedIssueIds(snapshot);
|
|
220
|
+
if (!contested.length)
|
|
221
|
+
return { phase: 'finished', round: snapshot.round, debateRound: snapshot.debateRound ?? 1, reason: 'review_consensus_complete', ...skipped };
|
|
222
|
+
const exhausted = (snapshot.debateRound ?? 1) >= snapshot.policy.maxConsensusRounds;
|
|
223
|
+
if (!exhausted && activeContestedIssueIds(snapshot).length)
|
|
224
|
+
return { phase: 'issue_discussing', round: snapshot.round, debateRound: (snapshot.debateRound ?? 1) + 1, reason: 'issue_consensus_next_round', ...skipped };
|
|
225
|
+
// The panel is done arguing, either out of rounds or out of movement. Dispose of every contested finding
|
|
226
|
+
// here so only the ones a human must actually rule on reach the escalation queue.
|
|
227
|
+
const resolutions = resolveContestedIssues(snapshot), escalated = resolutions.filter(entry => entry.disposition === 'escalate');
|
|
228
|
+
return { phase: escalated.length ? 'awaiting_human' : 'finished', round: snapshot.round, debateRound: snapshot.debateRound ?? 1,
|
|
229
|
+
reason: escalated.length ? (exhausted ? 'issue_consensus_exhausted' : 'issue_consensus_settled_with_disputes') : 'issue_consensus_resolved_by_panel',
|
|
230
|
+
resolutions, escalateConsensus: escalated.length > 0, ...skipped };
|
|
231
|
+
}
|
|
232
|
+
case 'awaiting_human': return { phase: 'consolidating', round: snapshot.round, reason: 'consensus_human_ruled', ...skipped };
|
|
233
|
+
// Compatibility recovery for sessions persisted by the old mandatory response loop: do not ask Agents for
|
|
234
|
+
// another response; close the review and let a human start an explicit fix/recheck cycle if desired.
|
|
235
|
+
case 'responding':
|
|
236
|
+
case 'adjudicating': return { phase: 'finished', round: snapshot.round, reason: 'legacy_response_loop_removed', ...skipped };
|
|
237
|
+
default: throw flowError(COLLAB_ERRORS.wrongPhase, `Phase ${snapshot.phase} cannot advance`);
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
/** A stall is informational only: it never changes the phase (see COLLAB_PLAN.md decision 3). */
|
|
241
|
+
export function stallCheck(snapshot, lastProgressAt, nowMs) {
|
|
242
|
+
const pending = waitingOn(snapshot), overdueBySec = Math.floor((nowMs - lastProgressAt) / 1000);
|
|
243
|
+
return { stalled: pending.length > 0 && overdueBySec >= snapshot.policy.overdueWarningSec, waitingOn: pending, overdueBySec };
|
|
244
|
+
}
|
|
245
|
+
export function assertCanFileFinding(snapshot, participantId) {
|
|
246
|
+
const participant = findParticipant(snapshot, participantId);
|
|
247
|
+
if (!participant)
|
|
248
|
+
throw flowError(COLLAB_ERRORS.participantNotFound, 'Participant is not part of this session', 404);
|
|
249
|
+
assertCapability(participant, 'file_finding');
|
|
250
|
+
assertPhase(snapshot, ['collecting'], 'Filing findings');
|
|
251
|
+
return participant;
|
|
252
|
+
}
|
|
253
|
+
/** Blind review: until the collecting phase closes, a participant may only see their own findings. */
|
|
254
|
+
export function canSeeOthersFindings(snapshot) {
|
|
255
|
+
return !snapshot.policy.blindFindings || snapshot.phase !== 'collecting';
|
|
256
|
+
}
|
|
257
|
+
/** Either side may escalate a panel dispute directly instead of spending more consensus rounds. */
|
|
258
|
+
export function applyEscalation(input) {
|
|
259
|
+
const { issue, actor } = input;
|
|
260
|
+
assertCapability(actor, 'escalate');
|
|
261
|
+
if (issue.reporterId !== actor.participantId && issue.targetParticipantId !== actor.participantId)
|
|
262
|
+
throw flowError(COLLAB_ERRORS.forbidden, 'Only the reporter or the addressed participant may escalate an issue', 403);
|
|
263
|
+
if (FINAL_ISSUE_STATUSES.includes(issue.status))
|
|
264
|
+
throw flowError(COLLAB_ERRORS.humanRulingFinal, `Issue is ${issue.status} and can no longer be changed`);
|
|
265
|
+
return { status: 'escalated', round: issue.round, escalate: true, escalateReason: 'participant_escalated' };
|
|
266
|
+
}
|
|
267
|
+
export function applyWithdraw(input) {
|
|
268
|
+
const { issue, actor } = input;
|
|
269
|
+
assertCapability(actor, 'withdraw');
|
|
270
|
+
if (issue.reporterId !== actor.participantId)
|
|
271
|
+
throw flowError(COLLAB_ERRORS.forbidden, 'Only the reporter may withdraw an issue', 403);
|
|
272
|
+
if (FINAL_ISSUE_STATUSES.includes(issue.status))
|
|
273
|
+
throw flowError(COLLAB_ERRORS.humanRulingFinal, `Issue is ${issue.status} and can no longer be changed`);
|
|
274
|
+
return { status: 'withdrawn', round: issue.round, escalate: false };
|
|
275
|
+
}
|
|
276
|
+
/** A human ruling is terminal except for an explicit reopen, which hands the issue back to the responder. */
|
|
277
|
+
export function applyHumanRuling(issue, decision) {
|
|
278
|
+
if (decision === 'reopen')
|
|
279
|
+
return { status: 'open', round: issue.round + 1, escalate: false };
|
|
280
|
+
return { status: decision === 'resolved' ? 'human_ruled' : decision, round: issue.round, escalate: false };
|
|
281
|
+
}
|
|
282
|
+
/** Everyone the reviewers have to agree with before a session may finish clean. */
|
|
283
|
+
export function approvalSummary(snapshot) {
|
|
284
|
+
const reviewers = active(snapshot).filter(participant => participant.role === 'reviewer');
|
|
285
|
+
const approvals = reviewers.map(reviewer => {
|
|
286
|
+
const filed = snapshot.issues.filter(issue => issue.reporterId === reviewer.participantId);
|
|
287
|
+
const unresolved = filed.filter(isOpenIssue);
|
|
288
|
+
return { participantId: reviewer.participantId, filed: filed.length, unresolved: unresolved.length, approved: unresolved.length === 0 };
|
|
289
|
+
});
|
|
290
|
+
return {
|
|
291
|
+
reviewers: approvals,
|
|
292
|
+
// "Approved" means every reviewer's own findings are settled and nothing needed a human ruling.
|
|
293
|
+
unanimous: approvals.length > 0 && approvals.every(entry => entry.approved),
|
|
294
|
+
humanRuledCount: snapshot.issues.filter(issue => issue.status === 'human_ruled' || issue.status === 'wontfix' || issue.status === 'closed').length
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
export function sessionProgress(snapshot) {
|
|
298
|
+
const counts = new Map();
|
|
299
|
+
for (const issue of snapshot.issues)
|
|
300
|
+
counts.set(issue.status, (counts.get(issue.status) ?? 0) + 1);
|
|
301
|
+
return {
|
|
302
|
+
phase: snapshot.phase, round: snapshot.round,
|
|
303
|
+
totalIssues: snapshot.issues.length,
|
|
304
|
+
openIssues: snapshot.issues.filter(isOpenIssue).length,
|
|
305
|
+
byStatus: Object.fromEntries(counts),
|
|
306
|
+
waitingOn: waitingOn(snapshot),
|
|
307
|
+
pendingCrossVotes: pendingCrossVoters(snapshot),
|
|
308
|
+
readyToAdvance: isReadyToAdvance(snapshot)
|
|
309
|
+
};
|
|
310
|
+
}
|