feat: add scoped optional reminder queue and verified readback
This commit is contained in:
@@ -0,0 +1,13 @@
|
||||
# D:提醒与实际回读验收
|
||||
|
||||
## 第一源码切片
|
||||
|
||||
纯队列和原收据核对已实现,尚未接入Runtime、用户开关或正式程序。正式仍为Orven1.25.9,本切片不能称为用户功能已部署。
|
||||
|
||||
复用B的不可变`turn-progress-shadow`与原工具结果。相同事实连续两次成为重复候选才生成建议,稳定key含项目/会话/Task/Run和实际读取范围或参数失败。正常分页、研究、新失败、权限/环境受阻和检查等待不催写。未知观察不生成建议。
|
||||
|
||||
状态区分pending、delivered、resolved、expired。delivered仅表示随实际请求提交;模型收到/采纳和进展因果均不推定。“明白”不核销。声明的回读条件为新增真实读取区间或原参数错误工具随后成功;自然解决另记。默认关闭、取消/边界变化/TTL使建议过期,同事实不反复重建,无效建议降低频率。附加建议的大小和次数只管理建议,不限制用户输入、模型输出、历史、执行或权限。
|
||||
|
||||
Node24相关测试25/25通过:新队列10项和原B15项。原TAP:`.qa/reminder-readback-d/queue-round-1.tap`。覆盖跨身份/迟到/改写送达拒绝、去重、分页/新SHA/研究、新失败/等待、自然解决、确认文字无效、关闭/取消/TTL、工具撤销、冷却和原结果篡改。原B观察与收据不重写;提取共用只读核对函数,不改变B语义。
|
||||
|
||||
本轮没有真实模型请求,不修改正式设置、不续跑历史样本或用户项目。历史网络异常、unknown用量、重复读取普遍改善和Purge收益unknown保持。下一接入实际Runtime、持久开关、送达请求原字节与已有观察面板,验证故障隔离及实际HTTP/UI/Electron。
|
||||
@@ -1969,3 +1969,5 @@ AI最终独立候选4131aae4为26/26、输入保持,server135a2d97;包含AH4
|
||||
AI已封存84份29147488字节,163最终输入保持,离线复核成功收据ai-seal-c1207201;索引8ea93831。再次只读正式状态仍1.25.8/PID71628/空闲/开放策略保持。下一仅限定源码/测试/文档本地提交,本轮不推送、发行或重启。
|
||||
|
||||
Orven接续:推送会话28037退出0,远端feat/task-agreement-1.25=b35a4985e0a7533d0aa64f0296d23fc4c7fb1b50,与本地HEAD一致;工作树干净。已读D计划/Tianshu/1.25和B源模块,接续纯队列/来源验证。恢复时过量历史/文件清单输出截断,改限定src与短段,不把截断当完整验证;未修改原发行索引。
|
||||
|
||||
D第一源码切片:queue-round-1共25/25通过,新队列10+原B15;原TAP保留。纯队列不接模型文字,默认关闭、两次同事实重复、稳定key、送达/解决分离、自然解决/失效/冷却均已测;原收据验证提取复用。尚无Runtime/开关/UI接入,不宣称部署。恢复搜索两次Windows通配路径及猜测配置/组件路径未找到,已改限定真实目录,未改产品/正式数据。
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const sha = value => /^[a-f0-9]{64}$/.test(value ?? '');
|
||||
const active = item => ['pending', 'delivered'].includes(item.status);
|
||||
const same = (a, b) => hash(a) === hash(b);
|
||||
const scopeOf = value => Object.fromEntries(['projectId', 'sessionId', 'taskId', 'runId'].map(key => [key, value?.[key]]));
|
||||
|
||||
// These bounds apply only to optional advice. They never limit a user request,
|
||||
// model output, history, tools, execution time or permissions.
|
||||
export const REMINDER_POLICY = Object.freeze({ repeatedTurns: 2, ttlMs: 10 * 60_000, cooldownTurns: 3, maxDeliveries: 3, messageBytes: 1800 });
|
||||
|
||||
function queue(previous, scope, enabled, at) {
|
||||
if (Object.values(scopeOf(scope)).some(value => typeof value !== 'string' || !value)) throw new Error('Reminder scope is incomplete.');
|
||||
if (previous && (previous.schemaVersion !== 1 || !same(previous.scope, scopeOf(scope)))) throw new Error('Reminder belongs to another Task/Run.');
|
||||
if (!Number.isFinite(at)) throw new Error('Reminder time is invalid.');
|
||||
const state = previous ? structuredClone(previous) : { schemaVersion: 1, scope: scopeOf(scope), enabled: false, lastOrdinal: 0, streak: null, items: [] };
|
||||
state.enabled = enabled === true;
|
||||
for (const item of state.items) if (active(item) && (!state.enabled || at >= item.expiresAt)) {
|
||||
item.status = 'expired'; item.closedAt = at; item.exitReason = state.enabled ? 'ttl' : 'disabled';
|
||||
}
|
||||
if (!state.enabled) state.streak = null;
|
||||
return state;
|
||||
}
|
||||
|
||||
const expire = (state, reason, at) => {
|
||||
for (const item of state.items) if (active(item)) { item.status = 'expired'; item.closedAt = at; item.exitReason = reason; }
|
||||
state.streak = null;
|
||||
};
|
||||
|
||||
// The caller must verify the immutable observation and original tool receipts.
|
||||
// Text written by the model is deliberately not accepted as readback evidence.
|
||||
export function observeReminders(previous, { scope, enabled = false, at, receipt = null, research = false, endReason = null }) {
|
||||
const state = queue(previous, scope, enabled, at);
|
||||
if (endReason) { expire(state, endReason, at); return state; }
|
||||
if (!state.enabled || !receipt) return state;
|
||||
const { observation: turn, ref, tools } = receipt;
|
||||
if (!sha(ref?.sha256) || typeof ref.artifactId !== 'string' || !Number.isSafeInteger(ref.ordinal) || ref.ordinal < 1
|
||||
|| turn?.taskId !== scope.taskId || turn.runId !== scope.runId || !Array.isArray(tools)) throw new Error('Reminder observation source is invalid.');
|
||||
if (ref.ordinal <= state.lastOrdinal) {
|
||||
if (ref.ordinal === state.lastOrdinal && state.lastArtifactId === ref.artifactId) return state;
|
||||
throw new Error('Late reminder observation cannot update this queue.');
|
||||
}
|
||||
state.lastOrdinal = ref.ordinal; state.lastArtifactId = ref.artifactId;
|
||||
if (research || turn.waiting?.length || turn.delta?.user_boundaries || turn.classification === 'new_failure_evidence') {
|
||||
expire(state, research ? 'research' : turn.waiting?.length ? 'waiting' : turn.delta?.user_boundaries ? 'user_boundary' : 'new_failure', at);
|
||||
return state;
|
||||
}
|
||||
if (turn.phase === 'baseline' || turn.phase === 'waiting') { state.streak = null; return state; }
|
||||
for (const item of state.items.filter(active)) {
|
||||
const later = ref.ordinal > item.source.at(-1).ordinal;
|
||||
const newRange = item.expected.kind === 'new_read_range' && turn.delta?.read_characters > 0 && tools.some(tool => tool.read && !tool.failure);
|
||||
const corrected = item.expected.kind === 'corrected_tool_result' && tools.some(tool => item.toolNames.includes(tool.name) && tool.success === true && !tool.failure);
|
||||
if (later && (newRange || corrected)) {
|
||||
item.status = 'resolved'; item.closedAt = at;
|
||||
item.resolution = { source: structuredClone(ref), kind: newRange ? 'new_read_range' : 'corrected_tool_result',
|
||||
relation: item.deliveries.length ? 'observed_after_dispatch' : 'naturally_resolved', causality: 'unproven' };
|
||||
}
|
||||
}
|
||||
const noGrowth = turn.delta && !['read_characters', 'new_sources', 'changed_files', 'check_results', 'requirement_evidence', 'user_boundaries', 'new_failures', 'other_observations'].some(key => turn.delta[key]);
|
||||
let category, relevant;
|
||||
if (noGrowth && !turn.truncated && turn.classification === 'repeated_read_candidate') {
|
||||
category = 'repeated_read'; relevant = tools.filter(tool => tool.read && !tool.failure);
|
||||
} else if (noGrowth && !turn.truncated && turn.classification === 'repeated_failure_candidate'
|
||||
&& tools.length && tools.every(tool => tool.failure?.category === 'invalid_input')) {
|
||||
category = 'repeated_invalid_input'; relevant = tools;
|
||||
}
|
||||
if (!category || !relevant?.length) { state.streak = null; return state; }
|
||||
const signatures = relevant.map(tool => category === 'repeated_read' ? [tool.name, tool.read]
|
||||
: [tool.name, tool.argsSha256, tool.failure]).map(hash).sort();
|
||||
const key = hash([state.scope, category, [...new Set(signatures)]]);
|
||||
if (state.streak?.key === key) { state.streak.count++; state.streak.sources.push(structuredClone(ref)); }
|
||||
else state.streak = { key, count: 1, sources: [structuredClone(ref)] };
|
||||
state.streak.sources = state.streak.sources.slice(-REMINDER_POLICY.repeatedTurns);
|
||||
// A stable fact is suggested once per Run. Ineffective, disabled or expired
|
||||
// advice cannot keep recreating itself under a different random ID.
|
||||
if (state.streak.count >= REMINDER_POLICY.repeatedTurns && !state.items.some(item => item.key === key)) {
|
||||
state.items.push({ key, category, status: 'pending', createdAt: at, expiresAt: at + REMINDER_POLICY.ttlMs,
|
||||
source: structuredClone(state.streak.sources), toolNames: [...new Set(relevant.map(tool => tool.name))].sort(),
|
||||
expected: { kind: category === 'repeated_read' ? 'new_read_range' : 'corrected_tool_result' }, deliveries: [] });
|
||||
}
|
||||
return state;
|
||||
}
|
||||
|
||||
function messageFor(state, item, visible) {
|
||||
const tools = item.toolNames.filter(name => visible.includes(name));
|
||||
if (!tools.length) return null;
|
||||
const summary = item.category === 'repeated_read'
|
||||
? '已核对同一SHA和区间连续重复返回。可根据原目标使用已有结果;还需内容时,用当前提供的读取工具取得未读区间。'
|
||||
: '已核对同一工具和参数连续返回相同的参数错误。可根据原始错误修正参数,再使用本轮提供的工具。';
|
||||
const content = '工作台可选进展建议(不是用户追加目标,不授予权限):\n' + JSON.stringify({
|
||||
key: item.key, category: item.category, summary, available_tools: tools,
|
||||
source: item.source.map(({ artifactId, sha256 }) => ({ artifact_id: artifactId, sha256 })), expected_observation: item.expected.kind,
|
||||
note: '按原任务约定决定下一步;回复已知悉不构成证据,后续实际工具结果单独核对。',
|
||||
});
|
||||
if (Buffer.byteLength(content, 'utf8') > REMINDER_POLICY.messageBytes) return null;
|
||||
return { key: item.key, scope: state.scope, content, sha256: hash(content), tools };
|
||||
}
|
||||
|
||||
export function selectReminder(previous, { scope, enabled = false, at, visibleTools = [] }) {
|
||||
const state = queue(previous, scope, enabled, at);
|
||||
if (!state.enabled) return { state, message: null };
|
||||
for (const item of state.items.filter(active)) {
|
||||
if (item.deliveries.length >= REMINDER_POLICY.maxDeliveries) { item.status = 'expired'; item.closedAt = at; item.exitReason = 'ineffective'; continue; }
|
||||
const last = item.deliveries.at(-1);
|
||||
const cooldown = REMINDER_POLICY.cooldownTurns * 2 ** Math.max(0, item.deliveries.length - 1);
|
||||
if (last && state.lastOrdinal - last.ordinal < cooldown) continue;
|
||||
const message = messageFor(state, item, visibleTools);
|
||||
if (!message) { item.status = 'expired'; item.closedAt = at; item.exitReason = 'tool_unavailable_or_advice_too_large'; continue; }
|
||||
return { state, message };
|
||||
}
|
||||
return { state, message: null };
|
||||
}
|
||||
|
||||
// Dispatch means included in a real submitted request. It does not assert that
|
||||
// an upstream received it, the model adopted it, or the advice caused progress.
|
||||
export function recordReminderDispatch(previous, { scope, at, message, requestId, requestSha256 }) {
|
||||
const state = queue(previous, scope, previous?.enabled, at), item = state.items.find(row => row.key === message?.key);
|
||||
if (!same(message?.scope, state.scope) || !sha(requestSha256) || typeof requestId !== 'string' || !requestId) throw new Error('Reminder request ownership is invalid.');
|
||||
if (!state.enabled || !item || !active(item)) return state;
|
||||
const expected = messageFor(state, item, message.tools ?? []);
|
||||
if (!expected || !same(expected, message)) throw new Error('Reminder dispatch differs from selected advice.');
|
||||
if (item.deliveries.some(row => row.requestId === requestId)) return state;
|
||||
item.deliveries.push({ requestId, requestSha256, messageSha256: message.sha256, ordinal: state.lastOrdinal, dispatchedAt: at });
|
||||
item.status = 'delivered';
|
||||
return state;
|
||||
}
|
||||
@@ -53,37 +53,46 @@ export function recordTurnProgress(store, session, run, step, phase = 'settled',
|
||||
}
|
||||
}
|
||||
|
||||
export function verifyTurnProgressReceipt(store, session, run, artifactId) {
|
||||
const owned = row => row.sessionId === session.id && row.projectId === session.projectId && row.taskId === run.taskId && row.runId === run.id;
|
||||
if (run.sessionId !== session.id || run.projectId !== session.projectId) throw new Error('单轮观察运行归属不一致。');
|
||||
const artifact = store.owned('artifact', artifactId, session.id);
|
||||
if (!owned(artifact) || artifact.kind !== 'turn-progress-shadow') throw new Error('单轮观察原收据归属不一致。');
|
||||
const original = JSON.parse(store.artifactStore.read(artifact)), tools = [];
|
||||
if (original.taskId !== run.taskId || original.runId !== run.id) throw new Error('单轮观察原文归属不一致。');
|
||||
for (const ref of original.tools) {
|
||||
if (ref.tool === 'model_request') {
|
||||
const event = session.events.find(row => row.id === ref.source_event_id && row.runId === run.id);
|
||||
if (!event?.diagnostic || event.diagnostic.id !== ref.id || planHash(event.diagnostic) !== ref.diagnostic_sha256)
|
||||
throw new Error('单轮观察的原模型失败记录待核对。');
|
||||
if (ref.result_artifact_id) {
|
||||
const result = store.owned('artifact', ref.result_artifact_id, session.id);
|
||||
if (!owned(result) || result.sha256 !== ref.result_sha256 || !['model-http-response', 'model-stream-response'].includes(result.kind))
|
||||
throw new Error('单轮观察的原模型失败响应来源变化。');
|
||||
store.artifactStore.read(result);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const record = store.owned('tool', ref.id, session.id), result = store.owned('artifact', ref.result_artifact_id, session.id);
|
||||
if (!owned(record) || !owned(result) || record.tool !== ref.tool || record.argsSha256 !== ref.args_sha256 || result.kind !== 'tool-result'
|
||||
|| record.resultArtifactId !== result.id || result.sha256 !== ref.result_sha256) throw new Error('单轮观察的工具或原结果来源变化。');
|
||||
const value = JSON.parse(store.artifactStore.read(result));
|
||||
tools.push({ ...toolProgressFacts(record, value, result, record.progressFailureCategory),
|
||||
success: record.state === 'completed' && !record.requiresVerification && !['failed', 'error', 'denied', 'unknown', 'interrupted', 'unverified'].includes(value.status) });
|
||||
}
|
||||
return { observation: original, tools, artifact };
|
||||
}
|
||||
|
||||
export function inspectTurnProgress(store, session, run) {
|
||||
if (!run.progressShadow) return { mode: 'shadow', recorded: false, turns: [], evidence_verified: false, error: run.progressShadowError ?? null };
|
||||
const view = { mode: 'shadow', recorded: true, observations: run.progressShadow.observations, truncated: run.progressShadow.truncated,
|
||||
turns: structuredClone(run.progressShadow.turns), artifact_ids: run.progressShadowArtifactIds ?? [], evidence_verified: true,
|
||||
error: run.progressShadowError ? '部分观察未能记录,保留的原收据单独核对;原执行结果保持。' : null };
|
||||
try {
|
||||
const owned = row => row.sessionId === session.id && row.projectId === session.projectId && row.taskId === run.taskId && row.runId === run.id;
|
||||
if (view.turns.length !== view.artifact_ids.length) throw new Error('单轮观察与原收据数量不一致。');
|
||||
for (let i = 0; i < view.turns.length; i++) {
|
||||
const artifact = store.owned('artifact', view.artifact_ids[i], session.id);
|
||||
if (!owned(artifact) || artifact.kind !== 'turn-progress-shadow') throw new Error('单轮观察原收据归属不一致。');
|
||||
const original = JSON.parse(store.artifactStore.read(artifact));
|
||||
const { observation: original } = verifyTurnProgressReceipt(store, session, run, view.artifact_ids[i]);
|
||||
if (planHash(original) !== planHash(view.turns[i])) throw new Error('单轮观察与原收据不一致。');
|
||||
for (const ref of original.tools) {
|
||||
if (ref.tool === 'model_request') {
|
||||
const event = session.events.find(row => row.id === ref.source_event_id && row.runId === run.id);
|
||||
if (!event?.diagnostic || event.diagnostic.id !== ref.id || planHash(event.diagnostic) !== ref.diagnostic_sha256)
|
||||
throw new Error('单轮观察的原模型失败记录待核对。');
|
||||
if (ref.result_artifact_id) {
|
||||
const result = store.owned('artifact', ref.result_artifact_id, session.id);
|
||||
if (!owned(result) || result.sha256 !== ref.result_sha256 || !['model-http-response', 'model-stream-response'].includes(result.kind))
|
||||
throw new Error('单轮观察的原模型失败响应来源变化。');
|
||||
store.artifactStore.read(result);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const record = store.owned('tool', ref.id, session.id), result = store.owned('artifact', ref.result_artifact_id, session.id);
|
||||
if (!owned(record) || !owned(result) || record.tool !== ref.tool || record.argsSha256 !== ref.args_sha256 || result.kind !== 'tool-result'
|
||||
|| record.resultArtifactId !== result.id || result.sha256 !== ref.result_sha256) throw new Error('单轮观察的工具或原结果来源变化。');
|
||||
store.artifactStore.read(result);
|
||||
}
|
||||
}
|
||||
} catch { view.evidence_verified = false; view.error = '单轮观察的原收据或工具结果待核对;不用于交付通过判定。'; }
|
||||
return view;
|
||||
|
||||
@@ -1037,3 +1037,9 @@ F收尾:57d075e修正独立编译QA路径,6d09ac8封存差异;202610302320
|
||||
3. [complete] 最终70225d88两ZIP/775输入重建29/29、隔离stage/activate/start及随包两端通过;正式安装226415ms保留PID/Provider/102项目127会话,正式两端通过。回看后仅修订120→123例外如实单列,159份72003766字节封存。
|
||||
4. [complete] 回顾与定向提交b35a4985;用户建库后首次推送成功,ls-remote逐SHA一致、upstream已设置,原建库拒绝和推送日志保持,见docs/GITATLAS-PUSH-1.25.9.md。
|
||||
5. [in_progress] D可关闭提醒与实际回读:先纯队列及原收据来源绑定并阶段验证/提交,再Runtime/偏好/现有观察面板、实际HTTP/网页/Electron及独立交付。不以提示恢复模型额度,不续跑历史真实样本,Purge收益仍unknown。
|
||||
|
||||
## D阶段
|
||||
|
||||
1. [complete] 纯队列/稳定key/来源回读/冷却与退出,Node24新10项+原B15项=25/25;见docs/QA-REMINDER-READBACK-D.md。
|
||||
2. [in_progress] Runtime实际请求/原字节收据、默认关闭与持久偏好、同Run回读、取消/迟到及观察器故障隔离。
|
||||
3. [pending] 原观察面板与工具设置、真实本机HTTP/网页/Electron、独立发行/回顾/提交。真实供应商与Purge收益不在此切片代签。
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { observeTurn } from '../src/core/context/turn-progress.mjs';
|
||||
import { observeReminders, selectReminder, recordReminderDispatch, REMINDER_POLICY } from '../src/core/context/reminder-queue.mjs';
|
||||
import { recordTurnProgress, verifyTurnProgressReceipt } from '../src/core/context/turn-progress-recorder.mjs';
|
||||
import { fixture } from './helpers.mjs';
|
||||
import { beginPlanTask, completeRead } from './fixtures/task-plan-fixture.mjs';
|
||||
|
||||
const hash = value => createHash('sha256').update(JSON.stringify(value)).digest('hex');
|
||||
const scope = { projectId: 'p', sessionId: 's', taskId: 't', runId: 'r' };
|
||||
const read = (start = 0, end = 4, name = 'read_file') => ({ id: 'read', name, argsSha256: hash(['read', start, end]),
|
||||
success: true, read: { key: 'file', sha256: hash('original source'), unit: 'utf16_in_original_range', start, end } });
|
||||
const failure = (category = 'invalid_input', signature = 'same error') => ({ id: 'failure', name: 'read_file', argsSha256: hash('same bad arguments'), failure: { category, signature } });
|
||||
function scenario() {
|
||||
let shadow, state, ordinal = 0, at = 1000;
|
||||
return {
|
||||
turn(tools = [], extras = {}, policy = {}) {
|
||||
const result = observeTurn(shadow, { ...scope, tools, phase: 'settled', ...extras }); shadow = result.state;
|
||||
const receipt = { observation: result.observation, tools, ref: { artifactId: 'original-' + (++ordinal), sha256: hash(result.observation), ordinal } };
|
||||
state = observeReminders(state, { scope, enabled: true, at: ++at, receipt, ...policy });
|
||||
return receipt;
|
||||
},
|
||||
get state() { return state; },
|
||||
set state(value) { state = value; },
|
||||
get at() { return at; },
|
||||
select(extras = {}) { const selected = selectReminder(state, { scope, enabled: true, at, visibleTools: ['read_file'], ...extras }); state = selected.state; return selected.message; },
|
||||
dispatch(message, requestId = 'request-1') { state = recordReminderDispatch(state, { scope, at, message, requestId, requestSha256: hash(requestId) }); },
|
||||
};
|
||||
}
|
||||
function repeated(s, tool = read()) { s.turn([tool]); s.turn([tool]); s.turn([tool]); }
|
||||
|
||||
test('off by default, two confirmed repeated turns, stable dedup, no task limits or model reasoning', () => {
|
||||
const s = scenario(); s.turn([read()]); s.turn([read()]); assert.equal(s.state.items.length, 0);
|
||||
s.turn([read()]); assert.equal(s.state.items.length, 1); const key = s.state.items[0].key;
|
||||
s.turn([read()], { modelText: '明白,已经解决', privateReasoning: 'PRIVATE_SENTINEL' });
|
||||
assert.equal(s.state.items.length, 1); assert.equal(s.state.items[0].key, key); assert.equal(s.state.items[0].status, 'pending');
|
||||
assert.ok(!JSON.stringify(s.state).includes('PRIVATE_SENTINEL'));
|
||||
const off = observeReminders(null, { scope, at: 1000 }); assert.equal(off.enabled, false); assert.equal(off.items.length, 0);
|
||||
assert.equal(selectReminder(off, { scope, at: 1001 }).message, null);
|
||||
for (const key of ['maxTokens', 'maxSteps', 'shouldAbort', 'approvalMode', 'history']) assert.equal(key in s.state, false);
|
||||
});
|
||||
|
||||
test('normal pagination, new SHA and legal research never ask for changes', () => {
|
||||
const s = scenario(); s.turn([read(0, 4)]); s.turn([read(4, 8)]); s.turn([read(8, 12)]);
|
||||
const changed = read(); changed.read.sha256 = hash('changed source'); s.turn([changed]); assert.equal(s.state.items.length, 0);
|
||||
repeated(s, read(20, 24)); assert.equal(s.state.items.length, 1);
|
||||
s.turn([read(20, 24)], {}, { research: true }); assert.equal(s.state.items[0].exitReason, 'research'); assert.equal(s.select(), null);
|
||||
const research = scenario(); for (let i = 0; i < 8; i++) research.turn([read()], {}, { research: true });
|
||||
assert.equal(research.state.items.length, 0);
|
||||
});
|
||||
|
||||
test('new failures, network and environment repetition, user boundaries and waits stay in their actual classes', () => {
|
||||
for (const category of ['permission', 'network', 'authentication', 'tool_or_environment', 'requires_verification']) {
|
||||
const s = scenario(); for (let i = 0; i < 6; i++) s.turn([failure(category)]); assert.equal(s.state.items.length, 0, category);
|
||||
}
|
||||
for (const kind of ['approval', 'check_job', 'review']) {
|
||||
const s = scenario(); repeated(s); s.turn([], { waiting: [{ kind, id: 'owned-job' }] });
|
||||
assert.equal(s.state.items[0].status, 'expired'); assert.equal(s.state.items[0].exitReason, 'waiting'); assert.equal(s.select(), null);
|
||||
}
|
||||
const changed = scenario(); repeated(changed); changed.turn([], { userBoundaries: [['new-user', hash('changed goal')]] });
|
||||
assert.equal(changed.state.items[0].exitReason, 'user_boundary');
|
||||
const broken = scenario(); repeated(broken); broken.turn([failure('network')]); assert.equal(broken.state.items[0].exitReason, 'new_failure');
|
||||
});
|
||||
|
||||
test('sent is separate from resolved, acknowledgement is ignored and real readback keeps causality unknown', () => {
|
||||
const s = scenario(); repeated(s); const message = s.select(); assert.ok(message); assert.equal(s.state.items[0].deliveries.length, 0);
|
||||
assert.ok(Buffer.byteLength(message.content) <= REMINDER_POLICY.messageBytes); s.dispatch(message);
|
||||
assert.equal(s.state.items[0].status, 'delivered'); s.dispatch(message); assert.equal(s.state.items[0].deliveries.length, 1);
|
||||
s.turn([], { modelText: '明白,我已采纳并完成所有工作。' }); assert.equal(s.state.items[0].status, 'delivered');
|
||||
const original = structuredClone(s.state.items[0].source); const receipt = s.turn([read(4, 8)]);
|
||||
assert.equal(s.state.items[0].status, 'resolved'); assert.equal(s.state.items[0].resolution.source.artifactId, receipt.ref.artifactId);
|
||||
assert.equal(s.state.items[0].resolution.relation, 'observed_after_dispatch'); assert.equal(s.state.items[0].resolution.causality, 'unproven');
|
||||
assert.deepEqual(s.state.items[0].source, original); assert.equal(s.select(), null);
|
||||
});
|
||||
|
||||
test('pending advice can resolve naturally; invalid inputs need the same tool to actually succeed', () => {
|
||||
const natural = scenario(); repeated(natural); natural.turn([read(4, 8)]);
|
||||
assert.equal(natural.state.items[0].resolution.relation, 'naturally_resolved'); assert.equal(natural.state.items[0].deliveries.length, 0);
|
||||
const s = scenario(); repeated(s, failure()); assert.equal(s.state.items[0].category, 'repeated_invalid_input');
|
||||
s.dispatch(s.select()); s.turn([{ id: 'other', name: 'list_files', success: true }]); assert.equal(s.state.items[0].status, 'delivered');
|
||||
s.turn([{ ...failure(), success: false }]); assert.equal(s.state.items[0].status, 'delivered');
|
||||
s.turn([read()]); assert.equal(s.state.items[0].status, 'resolved'); assert.equal(s.state.items[0].resolution.kind, 'corrected_tool_result');
|
||||
});
|
||||
|
||||
test('ownership, late observations and modified dispatch cannot mutate the original queue', () => {
|
||||
const s = scenario(); repeated(s); const original = structuredClone(s.state), message = s.select();
|
||||
for (const field of Object.keys(scope)) assert.throws(() => observeReminders(s.state, { scope: { ...scope, [field]: 'foreign' }, enabled: true, at: 1005 }), /another Task\/Run/);
|
||||
assert.throws(() => observeReminders(s.state, { scope, enabled: true, at: 1005, receipt: { observation: { taskId: 't', runId: 'other' }, tools: [], ref: { ordinal: 5 } } }), /source is invalid/);
|
||||
assert.throws(() => observeReminders(s.state, { scope, enabled: true, at: 1005, receipt: { observation: { taskId: 't', runId: 'r' }, tools: [], ref: { ordinal: 1, artifactId: 'old', sha256: hash('old') } } }), /Late/);
|
||||
assert.throws(() => s.dispatch({ ...message, content: 'different instructions' }), /differs/);
|
||||
assert.throws(() => s.dispatch({ ...message, scope: { ...scope, taskId: 'foreign' } }), /ownership/);
|
||||
assert.deepEqual(s.state, original);
|
||||
});
|
||||
|
||||
test('disabled, cancelled, expired and unavailable-tool advice cannot dispatch or resolve later', () => {
|
||||
for (const reason of ['disabled', 'cancelled', 'ttl']) {
|
||||
const s = scenario(); repeated(s); const message = s.select();
|
||||
s.state = observeReminders(s.state, { scope, enabled: reason !== 'disabled', at: reason === 'ttl' ? s.at + REMINDER_POLICY.ttlMs : s.at, endReason: reason === 'cancelled' ? reason : null });
|
||||
s.dispatch(message); s.turn([read(4, 8)]); assert.equal(s.state.items[0].status, 'expired'); assert.equal(s.state.items[0].exitReason, reason);
|
||||
assert.equal(s.state.items[0].resolution, undefined); assert.equal(s.state.items[0].deliveries.length, 0);
|
||||
}
|
||||
const absent = scenario(); repeated(absent); assert.equal(absent.select({ visibleTools: ['propose_file'] }), null);
|
||||
assert.equal(absent.state.items[0].exitReason, 'tool_unavailable_or_advice_too_large');
|
||||
});
|
||||
|
||||
test('ineffective suggestions cool down, reduce frequency and expire without pausing execution', () => {
|
||||
const s = scenario(); repeated(s); s.dispatch(s.select(), 'first'); assert.equal(s.select(), null);
|
||||
for (let i = 0; i < REMINDER_POLICY.cooldownTurns; i++) s.turn([read()]);
|
||||
s.dispatch(s.select(), 'second');
|
||||
for (let i = 0; i < REMINDER_POLICY.cooldownTurns; i++) s.turn([read()]); assert.equal(s.select(), null);
|
||||
for (let i = 0; i < REMINDER_POLICY.cooldownTurns; i++) s.turn([read()]); s.dispatch(s.select(), 'third');
|
||||
assert.equal(s.select(), null); assert.equal(s.state.items[0].exitReason, 'ineffective');
|
||||
for (let i = 0; i < 30; i++) s.turn([read()]); assert.equal(s.state.items.length, 1); assert.equal(s.select(), null);
|
||||
});
|
||||
|
||||
test('bounded shadow uncertainty never turns retained unknown data into advice', () => {
|
||||
const s = scenario(); for (let i = 0; i < 45; i++) s.turn([]); repeated(s); assert.equal(s.state.items.length, 0);
|
||||
});
|
||||
|
||||
test('immutable receipt readback verifies original ownership, arguments and result bytes without rewriting B', t => {
|
||||
const f = fixture(t), run = beginPlanTask(f); const step = f.store.beginStep(f.session, run);
|
||||
const record = completeRead(f); step.progressToolIds = [record.id]; recordTurnProgress(f.store, f.session, run, step);
|
||||
const id = run.progressShadowArtifactIds.at(-1), original = structuredClone(run.progressShadow);
|
||||
const verified = verifyTurnProgressReceipt(f.store, f.session, run, id);
|
||||
assert.equal(verified.tools[0].read.sha256.length, 64); assert.equal(verified.tools[0].success, true);
|
||||
const argsSha = record.argsSha256; record.argsSha256 = hash('tampered');
|
||||
assert.throws(() => verifyTurnProgressReceipt(f.store, f.session, run, id), /来源变化/); record.argsSha256 = argsSha;
|
||||
const artifact = f.store.core.artifact.get(record.resultArtifactId), old = artifact.sha256; artifact.sha256 = hash('tampered result');
|
||||
assert.throws(() => verifyTurnProgressReceipt(f.store, f.session, run, id), /来源变化/); artifact.sha256 = old;
|
||||
assert.throws(() => verifyTurnProgressReceipt(f.store, { ...f.session, projectId: 'foreign' }, run, id), /归属不一致/);
|
||||
assert.deepEqual(run.progressShadow, original);
|
||||
});
|
||||
Reference in New Issue
Block a user