bareloop 0.54.1 → 0.56.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.
- package/CHANGELOG.md +122 -0
- package/bareloop.context.md +67 -6
- package/package.json +3 -3
- package/src/authorflow.js +217 -238
- package/src/authoring.js +22 -6
- package/src/authorjob.js +138 -30
- package/src/authorreadout.js +15 -4
- package/src/authorrun.js +13 -4
- package/src/authorscout.js +9 -6
- package/src/behaviour.js +14 -0
- package/src/blockasks.js +43 -0
- package/src/cardschedule.js +42 -0
- package/src/checkblock.js +772 -0
- package/src/checklist.js +128 -0
- package/src/checkpick.js +294 -0
- package/src/checksuggest.js +28 -0
- package/src/checkwords.js +27 -0
- package/src/cli.js +1 -1
- package/src/config.js +24 -1
- package/src/declaredclose.js +30 -1
- package/src/destpoint.js +151 -0
- package/src/draftspend.js +85 -0
- package/src/facts.js +8 -1
- package/src/factwords.js +14 -1
- package/src/fitcheck.js +5 -3
- package/src/job.js +81 -1
- package/src/jobblock.js +9 -0
- package/src/labelscan.js +11 -0
- package/src/launcher.js +3 -2
- package/src/mcpchecks.js +52 -0
- package/src/mcppick.js +36 -0
- package/src/mcpsources.js +77 -0
- package/src/mcpuse.js +97 -0
- package/src/natural.js +23 -0
- package/src/pagemap.js +20 -5
- package/src/panel/authorroutes.js +105 -18
- package/src/panel/authorsession.js +293 -44
- package/src/panel/index.html +873 -41
- package/src/panel/jobgrid.js +117 -0
- package/src/panel/jobplan.js +103 -35
- package/src/panel/scheduler.js +80 -13
- package/src/panel/schedules.js +189 -28
- package/src/panel/schedulestart.js +44 -13
- package/src/panel/server.js +471 -39
- package/src/panel/settingsroutes.js +133 -3
- package/src/panel/status.js +19 -1
- package/src/panel/tickets.js +44 -0
- package/src/pickrecord.js +163 -0
- package/src/placerule.js +355 -0
- package/src/plan.js +31 -2
- package/src/planrun.js +71 -15
- package/src/prcheckout.js +259 -0
- package/src/promptregisters.js +11 -0
- package/src/questionbox.js +112 -0
- package/src/readshim.js +3 -2
- package/src/revises.js +56 -0
- package/src/rowedit.js +115 -0
- package/src/rubricstep.js +265 -132
- package/src/run.js +19 -2
- package/src/runexport.js +2 -0
- package/src/runlist.js +3 -2
- package/src/schedulewords.js +46 -4
- package/src/source.js +81 -7
- package/src/stepmcp.js +86 -0
- package/src/ticket.js +113 -0
- package/src/ticketfilter.js +76 -0
- package/src/ticketlabels.js +79 -0
- package/src/ticketmcp.js +111 -0
- package/src/ticketnext.js +35 -0
- package/src/ticketrepo.js +98 -0
- package/src/ticketschedule.js +32 -0
- package/src/ticketshape.js +45 -0
- package/src/tools.js +9 -0
- package/src/trigger.js +14 -2
- package/src/triggerclock.js +7 -3
- package/src/triggerfiles.js +19 -11
- package/src/triggertickets.js +244 -0
- package/src/userrun.js +191 -10
- package/src/validate.js +3 -1
- package/src/worktree.js +43 -1
- package/types/authorflow.d.ts +86 -93
- package/types/authorjob.d.ts +35 -4
- package/types/authorreadout.d.ts +4 -3
- package/types/authorscout.d.ts +4 -2
- package/types/behaviour.d.ts +12 -0
- package/types/blockasks.d.ts +37 -0
- package/types/cardschedule.d.ts +24 -0
- package/types/checkblock.d.ts +361 -0
- package/types/checklist.d.ts +134 -0
- package/types/checkpick.d.ts +160 -0
- package/types/checksuggest.d.ts +30 -0
- package/types/checkwords.d.ts +14 -0
- package/types/config.d.ts +7 -0
- package/types/declaredclose.d.ts +4 -0
- package/types/destpoint.d.ts +89 -0
- package/types/draftspend.d.ts +37 -0
- package/types/factwords.d.ts +7 -0
- package/types/fitcheck.d.ts +7 -1
- package/types/job.d.ts +13 -0
- package/types/jobblock.d.ts +9 -0
- package/types/labelscan.d.ts +7 -0
- package/types/launcher.d.ts +2 -2
- package/types/mcpchecks.d.ts +8 -0
- package/types/mcppick.d.ts +33 -0
- package/types/mcpsources.d.ts +51 -0
- package/types/mcpuse.d.ts +15 -0
- package/types/natural.d.ts +2 -0
- package/types/pagemap.d.ts +6 -1
- package/types/panel/authorroutes.d.ts +11 -2
- package/types/panel/authorsession.d.ts +69 -3
- package/types/panel/jobgrid.d.ts +405 -0
- package/types/panel/jobplan.d.ts +55 -11
- package/types/panel/scheduler.d.ts +7 -2
- package/types/panel/schedules.d.ts +124 -4
- package/types/panel/schedulestart.d.ts +21 -3
- package/types/panel/server.d.ts +432 -10
- package/types/panel/settingsroutes.d.ts +4 -2
- package/types/panel/status.d.ts +16 -2
- package/types/panel/tickets.d.ts +61 -0
- package/types/pickrecord.d.ts +100 -0
- package/types/placerule.d.ts +194 -0
- package/types/plan.d.ts +1 -0
- package/types/prcheckout.d.ts +151 -0
- package/types/questionbox.d.ts +87 -0
- package/types/readshim.d.ts +4 -3
- package/types/revises.d.ts +23 -0
- package/types/rowedit.d.ts +32 -0
- package/types/rubricstep.d.ts +100 -48
- package/types/run.d.ts +27 -1
- package/types/runlist.d.ts +6 -3
- package/types/schedulewords.d.ts +29 -2
- package/types/source.d.ts +40 -4
- package/types/stepmcp.d.ts +40 -0
- package/types/ticket.d.ts +114 -0
- package/types/ticketfilter.d.ts +34 -0
- package/types/ticketlabels.d.ts +44 -0
- package/types/ticketmcp.d.ts +84 -0
- package/types/ticketnext.d.ts +33 -0
- package/types/ticketrepo.d.ts +118 -0
- package/types/ticketschedule.d.ts +21 -0
- package/types/ticketshape.d.ts +37 -0
- package/types/tools.d.ts +1 -0
- package/types/trigger.d.ts +9 -1
- package/types/triggerclock.d.ts +6 -2
- package/types/triggerfiles.d.ts +13 -5
- package/types/triggertickets.d.ts +110 -0
- package/types/userrun.d.ts +50 -0
- package/types/validate.d.ts +1 -0
- package/types/worktree.d.ts +19 -0
package/src/placerule.js
ADDED
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
// PLACE RULES (docs/product/ITEM33-BUILD.md, "Place rules build spec (hamr go 2026-11-11)").
|
|
2
|
+
//
|
|
3
|
+
// A check whose words hold a version or a date ("the newest release is 0.55.0") is true only while the input stays as it is, so code refuses
|
|
4
|
+
// it as week-only. A PLACE RULE keeps it: it names WHERE the value sits (the first heading at one level of a changelog) instead of WHAT the
|
|
5
|
+
// value is. The signed fact carries the rule; at run start, before any provider call, CODE reads the run's own copy of the input with the rule
|
|
6
|
+
// and the value it finds is bound, in memory only, as that fact's phrase for the planner and the close. No model chooses or reads anything here.
|
|
7
|
+
//
|
|
8
|
+
// This module is the graduation (a REWRITE, never a copy) of the round-3 POC (F321). Pure except `lastPlaceRead`, which reads earlier runs' spines.
|
|
9
|
+
|
|
10
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
11
|
+
|
|
12
|
+
/** the two rule kinds on the menu: the version in a heading, and the date on the same heading line */
|
|
13
|
+
export const PLACE_KINDS = Object.freeze(['headingBetween', 'headingDateAfter']);
|
|
14
|
+
/** the end-of-line end mark */
|
|
15
|
+
export const EOL = '$EOL';
|
|
16
|
+
/** the field a place rule may carry */
|
|
17
|
+
export const PLACE_FIELDS = Object.freeze(['kind', 'prefix', 'end', 'shape', 'skip']);
|
|
18
|
+
/** the closed list of reasons a read can end not found */
|
|
19
|
+
export const PLACE_REASONS = Object.freeze(['mixed-levels', 'no-heading-line', 'first-heading-mismatch', 'end-mark-missing', 'capture-not-shape', 'only-skipped-headings', 'no-date-on-line', 'no-file', 'empty-text']);
|
|
20
|
+
/** plain words for each reason, from code (the person never reads a raw code) */
|
|
21
|
+
export const PLAIN_REASONS = Object.freeze({
|
|
22
|
+
'mixed-levels': 'the file writes its version headings at more than one level',
|
|
23
|
+
'no-heading-line': 'the file has no heading at the level the rule reads',
|
|
24
|
+
'first-heading-mismatch': 'the newest heading does not start the way the rule says',
|
|
25
|
+
'end-mark-missing': 'the newest heading does not have the mark the rule reads up to',
|
|
26
|
+
'capture-not-shape': 'the newest heading does not carry a version number',
|
|
27
|
+
'only-skipped-headings': 'the file has only an Unreleased heading and no release after it',
|
|
28
|
+
'no-date-on-line': 'the newest heading line carries no date',
|
|
29
|
+
'no-file': 'the input could not be read',
|
|
30
|
+
'empty-text': 'the input is empty',
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
const SHAPES = /** @type {Record<string, RegExp>} */ ({ semver: /^\d+\.\d+\.\d+$/, 'iso-date': /^\d{4}-\d{2}-\d{2}$/ });
|
|
34
|
+
const DATE_FIND = /\d{4}-\d{2}-\d{2}/;
|
|
35
|
+
const FENCE = /^\s{0,3}(```|~~~)/;
|
|
36
|
+
/** a heading carries a semver iff its text starts with an optional "[", an optional "v", then X.Y.Z (token-bounded) */
|
|
37
|
+
const SEMVER_HEADING = /^(#{1,6}) \[?v?(\d+\.\d+\.\d+)(?!\d|\.\d)/;
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* @typedef {{kind: 'headingBetween'|'headingDateAfter', prefix: string, end: string, shape: string, skip: string[]}} PlaceRule
|
|
41
|
+
* @typedef {{found: true, value: string, lineIndex: number}|{found: false, reason: string}} PlaceRead
|
|
42
|
+
*/
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Why a rule is not a legal place rule, or null when it is. Pure.
|
|
46
|
+
* @param {unknown} rule @returns {string|null}
|
|
47
|
+
*/
|
|
48
|
+
export function placeRuleProblem(rule) {
|
|
49
|
+
if (rule === null || typeof rule !== 'object' || Array.isArray(rule)) return 'a place rule is {kind, prefix, end, shape, skip}';
|
|
50
|
+
const r = /** @type {Record<string, any>} */ (rule);
|
|
51
|
+
for (const k of Object.keys(r)) if (!PLACE_FIELDS.includes(k)) return `"${k}" is not a field of a place rule (fields: ${PLACE_FIELDS.join(', ')})`;
|
|
52
|
+
if (!PLACE_KINDS.includes(r.kind)) return `kind is one of ${PLACE_KINDS.join(' | ')}`;
|
|
53
|
+
if (typeof r.prefix !== 'string' || !/^#+ /.test(r.prefix)) return 'prefix starts with # marks and a space';
|
|
54
|
+
if (typeof r.end !== 'string' || r.end === '') return 'end is the mark the value is read up to (or $EOL)';
|
|
55
|
+
if (typeof r.shape !== 'string' || !Object.hasOwn(SHAPES, r.shape)) return `shape is one of ${Object.keys(SHAPES).join(' | ')}`;
|
|
56
|
+
if (!Array.isArray(r.skip) || r.skip.some((/** @type {unknown} */ s) => typeof s !== 'string')) return 'skip is a list of words';
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Heading lines at the rule's level: lines outside ``` / ~~~ fences that start with the level mark (for example "## "). Pure.
|
|
62
|
+
* @param {string} text @param {string} prefix @returns {{i: number, line: string}[]}
|
|
63
|
+
*/
|
|
64
|
+
export function levelLines(text, prefix) {
|
|
65
|
+
const mark = `${/^#+/.exec(prefix)?.[0] ?? '#'} `;
|
|
66
|
+
let fenced = false;
|
|
67
|
+
/** @type {{i: number, line: string}[]} */
|
|
68
|
+
const out = [];
|
|
69
|
+
text.split(/\r?\n/).forEach((line, i) => {
|
|
70
|
+
if (FENCE.test(line)) { fenced = !fenced; return; }
|
|
71
|
+
if (!fenced && line.startsWith(mark)) out.push({ i, line });
|
|
72
|
+
});
|
|
73
|
+
return out;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The mixed-level guard: every non-fenced heading line is scanned; semver-carrying headings at MORE THAN ONE level mean mixed. A heading with no
|
|
78
|
+
* semver (a "# Changelog" title, "### Fixed") is ignored. It only ever turns a read into not found, never into a value.
|
|
79
|
+
* @param {string} text @returns {boolean}
|
|
80
|
+
*/
|
|
81
|
+
export function mixedLevels(text) {
|
|
82
|
+
let fenced = false;
|
|
83
|
+
/** @type {Set<number>} */
|
|
84
|
+
const levels = new Set();
|
|
85
|
+
for (const line of text.split(/\r?\n/)) {
|
|
86
|
+
if (FENCE.test(line)) { fenced = !fenced; continue; }
|
|
87
|
+
if (fenced) continue;
|
|
88
|
+
const m = SEMVER_HEADING.exec(line);
|
|
89
|
+
if (m) levels.add(m[1].length);
|
|
90
|
+
}
|
|
91
|
+
return levels.size > 1;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** @param {string} reason @returns {{found: false, reason: string}} */
|
|
95
|
+
const nf = (reason) => ({ found: false, reason });
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The STRICT first-heading read. It reads only the first heading line at the rule's level; it must match prefix + end + shape, else not found, and
|
|
99
|
+
* it never looks further down. One exception: a capture that is exactly a skip word ("Unreleased") moves to the NEXT heading at that level,
|
|
100
|
+
* ONCE (a second skip word is not found). Pure.
|
|
101
|
+
* @param {PlaceRule} rule @param {string} text
|
|
102
|
+
* @returns {{found: true, cap: string, after: string, lineIndex: number}|{found: false, reason: string}}
|
|
103
|
+
*/
|
|
104
|
+
function selectFirst(rule, text) {
|
|
105
|
+
if (!text || !text.trim()) return nf('empty-text');
|
|
106
|
+
if (mixedLevels(text)) return nf('mixed-levels');
|
|
107
|
+
const hs = levelLines(text, rule.prefix);
|
|
108
|
+
if (!hs.length) return nf('no-heading-line');
|
|
109
|
+
let k = 0;
|
|
110
|
+
let skipped = false;
|
|
111
|
+
for (;;) {
|
|
112
|
+
const { i, line } = hs[k];
|
|
113
|
+
if (!line.startsWith(rule.prefix)) return nf('first-heading-mismatch');
|
|
114
|
+
const rest = line.slice(rule.prefix.length);
|
|
115
|
+
const e = rule.end === EOL ? rest.length : rest.indexOf(rule.end);
|
|
116
|
+
if (e < 0) return nf('end-mark-missing');
|
|
117
|
+
const cap = rest.slice(0, e).trim();
|
|
118
|
+
if (rule.skip.some((s) => s.toLowerCase() === cap.toLowerCase())) {
|
|
119
|
+
if (skipped) return nf('only-skipped-headings');
|
|
120
|
+
skipped = true;
|
|
121
|
+
k += 1;
|
|
122
|
+
if (k >= hs.length) return nf('only-skipped-headings');
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (!SHAPES[rule.shape].test(cap)) return nf('capture-not-shape');
|
|
126
|
+
return { found: true, cap, after: rule.end === EOL ? '' : rest.slice(e + rule.end.length), lineIndex: i };
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Read one rule against one input text: the run-start function, code only. A rule that is not legal throws (the signed spec was validated, so a bad one
|
|
132
|
+
* is a defect, never a read).
|
|
133
|
+
* @param {PlaceRule} rule @param {string} text @returns {PlaceRead}
|
|
134
|
+
*/
|
|
135
|
+
export function readPlace(rule, text) {
|
|
136
|
+
const bad = placeRuleProblem(rule);
|
|
137
|
+
if (bad !== null) throw new Error(`place rule: ${bad}`);
|
|
138
|
+
const sel = selectFirst(rule, text);
|
|
139
|
+
if (!sel.found) return sel;
|
|
140
|
+
if (rule.kind === 'headingBetween') return { found: true, value: sel.cap, lineIndex: sel.lineIndex };
|
|
141
|
+
const m = DATE_FIND.exec(sel.after);
|
|
142
|
+
if (!m || !SHAPES['iso-date'].test(m[0])) return nf('no-date-on-line');
|
|
143
|
+
return { found: true, value: m[0], lineIndex: sel.lineIndex };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---- drafting: fit a rule ---------------------------------------------------------------------------------------------------------------
|
|
147
|
+
|
|
148
|
+
const CANDIDATE_PREFIXES = ['## [', '## v', '## ', '# [', '# v', '# ', '### [', '### v', '### '];
|
|
149
|
+
const CANDIDATE_ENDS = [']', ' ', EOL];
|
|
150
|
+
/** the frozen candidate list: 9 prefixes crossed with 3 ends, prefix-major (27) */
|
|
151
|
+
export const PLACE_CANDIDATES = Object.freeze(CANDIDATE_PREFIXES.flatMap((prefix) => CANDIDATE_ENDS.map((end) => Object.freeze({ prefix, end }))));
|
|
152
|
+
/** the one skip word of a fitted rule: an "Unreleased" heading above the newest release */
|
|
153
|
+
const FIT_SKIP = Object.freeze(['Unreleased']);
|
|
154
|
+
|
|
155
|
+
/**
|
|
156
|
+
* Fit a place rule to a fact's own words, by CODE, at drafting. The words must be exactly one version (X.Y.Z) or exactly one ISO date; the frozen
|
|
157
|
+
* candidates are walked in order, and the first whose strict first-heading read on the input's own text returns exactly those words wins. Null =
|
|
158
|
+
* no fit (a version and a date together, any other words, another date form, a mixed-level file, no text, or no candidate reading them): the caller
|
|
159
|
+
* refuses the words as week-only exactly as before. Only the two kinds are handled. Pure.
|
|
160
|
+
* @param {string} words @param {string|null|undefined} text
|
|
161
|
+
* @returns {PlaceRule|null}
|
|
162
|
+
*/
|
|
163
|
+
export function fitPlaceRule(words, text) {
|
|
164
|
+
if (typeof text !== 'string' || text.trim() === '') return null;
|
|
165
|
+
const w = String(words ?? '').trim();
|
|
166
|
+
const kind = SHAPES.semver.test(w) ? 'headingBetween' : (SHAPES['iso-date'].test(w) ? 'headingDateAfter' : null);
|
|
167
|
+
if (kind === null) return null;
|
|
168
|
+
for (const c of PLACE_CANDIDATES) {
|
|
169
|
+
/** @type {PlaceRule} */
|
|
170
|
+
const rule = { kind, prefix: c.prefix, end: c.end, shape: 'semver', skip: [...FIT_SKIP] };
|
|
171
|
+
const r = readPlace(rule, text);
|
|
172
|
+
if (r.found && r.value === w) return rule;
|
|
173
|
+
}
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** the only marks a heading piece may carry around its value: heading hashes, brackets, a dash, parentheses and spaces */
|
|
178
|
+
const HEADING_FURNITURE = /^[\s#[\]()\-\u2013\u2014]*$/;
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* STRIP (P1b, hamr 2026-11-11): the words of a phrase fact that are a piece of the newest release heading ("## [0.54.1]", "[0.54.1] -", "0.54.1",
|
|
182
|
+
* "2026-11-04", "## [0.54.1] - 2026-11-04") are stripped by code to their value(s). The words hold exactly one version (X.Y.Z, an optional leading v) and/or
|
|
183
|
+
* exactly one ISO date and nothing else but heading marks; each value is fitted with {@link fitPlaceRule} on the input's own text, and when both are
|
|
184
|
+
* present both must sit on the SAME first release heading line. Returns the values (version first) each with its rule, or null: two versions, two dates,
|
|
185
|
+
* any other word, another date form, a value that is not at the first release heading, no text. Pure.
|
|
186
|
+
* @param {string} words @param {string|null|undefined} text
|
|
187
|
+
* @returns {{kind: 'version'|'date', value: string, rule: PlaceRule}[]|null}
|
|
188
|
+
*/
|
|
189
|
+
export function fitPlacePhrase(words, text) {
|
|
190
|
+
if (typeof text !== 'string' || text.trim() === '') return null;
|
|
191
|
+
const w = String(words ?? '');
|
|
192
|
+
const dates = w.match(/(?<![\w.])\d{4}-\d{2}-\d{2}(?!\d)/g) ?? [];
|
|
193
|
+
const noDates = w.replace(/(?<![\w.])\d{4}-\d{2}-\d{2}(?!\d)/g, ' ');
|
|
194
|
+
const versions = [...noDates.matchAll(/(?<![\w.])v?(\d+\.\d+\.\d+)(?!\d|\.\d)/g)].map((m) => m[1]);
|
|
195
|
+
if (dates.length > 1 || versions.length > 1 || dates.length + versions.length === 0) return null;
|
|
196
|
+
if (!HEADING_FURNITURE.test(noDates.replace(/(?<![\w.])v?\d+\.\d+\.\d+(?!\d|\.\d)/g, ' '))) return null;
|
|
197
|
+
/** @type {{kind: 'version'|'date', value: string, rule: PlaceRule}[]} */
|
|
198
|
+
const out = [];
|
|
199
|
+
for (const [kind, value] of /** @type {['version'|'date', string][]} */ ([...versions.map((v) => ['version', v]), ...dates.map((d) => ['date', d])])) {
|
|
200
|
+
const rule = fitPlaceRule(value, text);
|
|
201
|
+
if (rule === null) return null;
|
|
202
|
+
out.push({ kind, value, rule });
|
|
203
|
+
}
|
|
204
|
+
if (out.length === 2) {
|
|
205
|
+
const [a, b] = out.map((x) => readPlace(x.rule, text));
|
|
206
|
+
if (!a.found || !b.found || a.lineIndex !== b.lineIndex) return null;
|
|
207
|
+
}
|
|
208
|
+
return out;
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
// ---- the facts a spec carries -----------------------------------------------------------------------------------------------------------
|
|
212
|
+
|
|
213
|
+
/** @param {unknown} v @returns {v is Record<string, any>} */
|
|
214
|
+
const isRec = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* @typedef {{key: string, name: string, source: string, stage: number, part: number, fact: number, place: PlaceRule, phrase: string}} PlaceFact
|
|
218
|
+
*/
|
|
219
|
+
|
|
220
|
+
/**
|
|
221
|
+
* Every place-rule fact of a spec, in stage / part / fact order. The key is the stage's name and the fact's name (both stable across the runs of one
|
|
222
|
+
* workflow), so an earlier run's record finds the same fact. Pure.
|
|
223
|
+
* @param {any} spec @returns {PlaceFact[]}
|
|
224
|
+
*/
|
|
225
|
+
export function placeFactsOf(spec) {
|
|
226
|
+
/** @type {PlaceFact[]} */
|
|
227
|
+
const out = [];
|
|
228
|
+
const stages = Array.isArray(spec?.closeDecl?.stages) ? spec.closeDecl.stages : [];
|
|
229
|
+
stages.forEach((/** @type {any} */ st, /** @type {number} */ si) => {
|
|
230
|
+
if (!isRec(st) || st.kind !== 'rubric-step' || !isRec(st.params) || !Array.isArray(st.params.parts)) return;
|
|
231
|
+
st.params.parts.forEach((/** @type {any} */ p, /** @type {number} */ pi) => {
|
|
232
|
+
if (!isRec(p) || p.class !== 'fact' || !Array.isArray(p.facts)) return;
|
|
233
|
+
p.facts.forEach((/** @type {any} */ f, /** @type {number} */ fi) => {
|
|
234
|
+
if (!isRec(f) || f.shape !== 'phrase' || !isRec(f.place)) return;
|
|
235
|
+
out.push({ key: `${String(st.name)}/${String(f.name)}`, name: String(f.name), source: String(p.source), stage: si, part: pi, fact: fi, place: /** @type {PlaceRule} */ (f.place), phrase: String(f.phrase) });
|
|
236
|
+
});
|
|
237
|
+
});
|
|
238
|
+
});
|
|
239
|
+
return out;
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* A copy of the spec with each place fact's phrase replaced by the value the run read. The input spec is never touched (the signed spec and its hash
|
|
244
|
+
* stay as signed); the copy is for this run's planner and close only. A key with no value is left as the signed drafting words.
|
|
245
|
+
* @param {any} spec @param {Record<string, string>} values place-fact key to the value read @returns {any}
|
|
246
|
+
*/
|
|
247
|
+
export function bindPlaceValues(spec, values) {
|
|
248
|
+
const bound = structuredClone(spec);
|
|
249
|
+
for (const f of placeFactsOf(bound)) {
|
|
250
|
+
if (Object.hasOwn(values, f.key)) bound.closeDecl.stages[f.stage].params.parts[f.part].facts[f.fact].phrase = values[f.key];
|
|
251
|
+
}
|
|
252
|
+
return bound;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* The value the drafting words themselves hold for this rule: the first version for headingBetween, the first ISO date for headingDateAfter. Null when
|
|
257
|
+
* the words hold none. Used as "last read" when no earlier run has one.
|
|
258
|
+
* @param {PlaceRule} rule @param {string} words @returns {string|null}
|
|
259
|
+
*/
|
|
260
|
+
export function valueInWords(rule, words) {
|
|
261
|
+
const m = rule.kind === 'headingBetween' ? /(?<![\d.])\d+\.\d+\.\d+(?!\d|\.\d)/.exec(words) : /(?<!\d)\d{4}-\d{2}-\d{2}(?!\d)/.exec(words);
|
|
262
|
+
return m === null ? null : m[0];
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Re-read EVERY place fact against the run's own input text, one by one, before any spend. A row is same / new / notfound. Any notfound stops the run;
|
|
267
|
+
* otherwise the run proceeds with the new words.
|
|
268
|
+
* @param {{fact: PlaceFact, text: string|null, was: string|null}[]} items `text` null = the input could not be read
|
|
269
|
+
* @returns {{proceed: boolean, rows: {key: string, name: string, kind: string, found: boolean, value: string|null, was: string|null, reason: string|null}[], values: Record<string, string>}}
|
|
270
|
+
*/
|
|
271
|
+
export function readPlaceRules(items) {
|
|
272
|
+
const rows = items.map(({ fact, text, was }) => {
|
|
273
|
+
const r = text === null ? /** @type {PlaceRead} */ ({ found: false, reason: 'no-file' }) : readPlace(fact.place, text);
|
|
274
|
+
return r.found
|
|
275
|
+
? { key: fact.key, name: fact.name, kind: fact.place.kind, found: true, value: r.value, was, reason: null }
|
|
276
|
+
: { key: fact.key, name: fact.name, kind: fact.place.kind, found: false, value: null, was, reason: r.reason };
|
|
277
|
+
});
|
|
278
|
+
/** @type {Record<string, string>} */
|
|
279
|
+
const values = {};
|
|
280
|
+
for (const r of rows) if (r.found && r.value !== null) values[r.key] = r.value;
|
|
281
|
+
return { proceed: rows.every((r) => r.found), rows, values };
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/** the end of the stop words: what the person can do, and that nothing ran or was spent */
|
|
285
|
+
export const STOP_TAIL = 'Reuse workflow and adjust the rules, or check the input. The run did not start. Nothing spent.';
|
|
286
|
+
|
|
287
|
+
/**
|
|
288
|
+
* The words of the $0 stop, plain words from code. Every rule is listed, found or not: "<name>: found <value>" (with "(was <last>)" when the value is
|
|
289
|
+
* new) or "<name>: not found (<plain reason>)", then the closing line. The reasons come only from the closed list.
|
|
290
|
+
* @param {{name: string, found: boolean, value: string|null, was: string|null, reason: string|null}[]} rows @returns {string}
|
|
291
|
+
*/
|
|
292
|
+
export function stopWords(rows) {
|
|
293
|
+
const lines = rows.map((r) => {
|
|
294
|
+
if (!r.found) return `${r.name}: not found (${PLAIN_REASONS[/** @type {keyof typeof PLAIN_REASONS} */ (r.reason ?? 'no-file')] ?? 'the input could not be read'})`;
|
|
295
|
+
return `${r.name}: found ${r.value}${r.was !== null && r.was !== r.value ? ` (was ${r.was})` : ''}`;
|
|
296
|
+
});
|
|
297
|
+
return `${lines.join('\n')}\n${STOP_TAIL}`;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
// ---- the record of a run: what was read, and what the last run read ---------------------------------------------------------------------
|
|
301
|
+
|
|
302
|
+
/** the plain words of the door's refusal when a place-rule run has no record of the values it read */
|
|
303
|
+
export const NO_PLACE_RECORD_WORDS = 'This run has no record of the values it read, so it cannot be checked again. Use Reuse workflow.';
|
|
304
|
+
|
|
305
|
+
/** the spine event a run writes, once, after job-start */
|
|
306
|
+
export const PLACE_EVENT = 'place-rules';
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* The values of the LAST `place-rules` record in a run's own events (key to value): what a RESUME of that run rebinds, since a resume does not re-read. Null when
|
|
310
|
+
* there is no record, or any of its rows was not found.
|
|
311
|
+
* @param {any[]} events @returns {Record<string, string>|null}
|
|
312
|
+
*/
|
|
313
|
+
export function placeValuesOfEvents(events) {
|
|
314
|
+
const rec = Array.isArray(events) ? events.findLast((e) => isRec(e) && e.type === PLACE_EVENT && Array.isArray(e.rows)) : undefined;
|
|
315
|
+
if (rec === undefined || rec.rows.length === 0 || rec.rows.some((/** @type {any} */ r) => !isRec(r) || r.found !== true || typeof r.value !== 'string')) return null;
|
|
316
|
+
return Object.fromEntries(rec.rows.map((/** @type {any} */ r) => [String(r.key), r.value]));
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/**
|
|
320
|
+
* What the newest EARLIER run of the same workflow read, per fact key: "last read". `rows` are the run list's rows (file order, oldest first). Candidates are
|
|
321
|
+
* the rows of the same job, newest first, at most {@link LAST_READ_LOOK} of them; the first whose spine holds a `place-rules` record of the same workflow key
|
|
322
|
+
* answers. An unreadable spine is skipped. Empty when there is none (the caller falls back to the drafting words).
|
|
323
|
+
* @param {{rows: {runid: string, job: string, spine: string}[], job: string, workflowKey: string, runid: string}} o @returns {Record<string, string>}
|
|
324
|
+
*/
|
|
325
|
+
export function lastPlaceRead({ rows, job, workflowKey, runid }) {
|
|
326
|
+
let looked = 0;
|
|
327
|
+
for (const row of [...rows].reverse()) {
|
|
328
|
+
if (row.runid === runid || row.job !== job || typeof row.spine !== 'string' || !existsSync(row.spine)) continue;
|
|
329
|
+
if (looked >= LAST_READ_LOOK) break;
|
|
330
|
+
looked += 1;
|
|
331
|
+
/** @type {any[]} */
|
|
332
|
+
let events = [];
|
|
333
|
+
try { events = readFileSync(row.spine, 'utf8').split('\n').filter((l) => l.includes(`"${PLACE_EVENT}"`)).map((l) => JSON.parse(l)); } catch { continue; }
|
|
334
|
+
const rec = events.findLast((e) => isRec(e) && e.type === PLACE_EVENT && e.workflowKey === workflowKey && Array.isArray(e.rows));
|
|
335
|
+
if (rec !== undefined) return Object.fromEntries(rec.rows.filter((/** @type {any} */ r) => isRec(r) && r.found === true && typeof r.value === 'string').map((/** @type {any} */ r) => [String(r.key), r.value]));
|
|
336
|
+
}
|
|
337
|
+
return {};
|
|
338
|
+
}
|
|
339
|
+
/** how many earlier runs of the job are looked at for "last read" */
|
|
340
|
+
export const LAST_READ_LOOK = 25;
|
|
341
|
+
|
|
342
|
+
/**
|
|
343
|
+
* The Audit lines of a run's `place-rules` record, in plain words from code: "<name>: <value>" (with "(was <last>)" when the value is new) or
|
|
344
|
+
* "<name>: not found (<reason>)". Null when the run has no record.
|
|
345
|
+
* @param {any[]} events @returns {string[]|null}
|
|
346
|
+
*/
|
|
347
|
+
export function placeRuleLines(events) {
|
|
348
|
+
const rec = Array.isArray(events) ? events.findLast((e) => isRec(e) && e.type === PLACE_EVENT && Array.isArray(e.rows)) : undefined;
|
|
349
|
+
if (rec === undefined) return null;
|
|
350
|
+
return rec.rows.filter(isRec).map((/** @type {any} */ r) => {
|
|
351
|
+
const name = String(r.key).split('/').pop();
|
|
352
|
+
if (r.found !== true) return `${name}: not found (${PLAIN_REASONS[/** @type {keyof typeof PLAIN_REASONS} */ (r.reason)] ?? 'the input could not be read'})`;
|
|
353
|
+
return `${name}: ${r.value}${typeof r.was === 'string' && r.was !== r.value ? ` (was ${r.was})` : ''}`;
|
|
354
|
+
});
|
|
355
|
+
}
|
package/src/plan.js
CHANGED
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
// Like its siblings (validate.js, job.js) it never throws on JSON text or
|
|
25
25
|
// plain parsed data; every failure is a named {code, path, detail} red.
|
|
26
26
|
|
|
27
|
-
import { TOOL_MENU, LOCKED_TOOLS, WRITE_VERBS, checkMenu } from './job.js';
|
|
27
|
+
import { TOOL_MENU, LOCKED_TOOLS, WRITE_VERBS, checkMenu, flowTypeOf } from './job.js';
|
|
28
28
|
import { declaredStages } from './declaredclose.js';
|
|
29
29
|
import { globToPrefix, scopeContained, isObj, isNonEmptyString, sweepSecretLiterals, hasNestedQuantifier } from './validate.js';
|
|
30
30
|
import { READ_SHIM_CAP, readShimArm } from './readshim.js';
|
|
@@ -111,7 +111,13 @@ const PLAN_FIELDS = ['schema', 'steps'];
|
|
|
111
111
|
// order; a field nothing consumes is a live-looking knob with zero effect
|
|
112
112
|
// (the F16 inert-op class). The arbiter's own vocabulary (close, budget,
|
|
113
113
|
// fence) is absent by construction — unknown-field at every depth.
|
|
114
|
-
const STEP_FIELDS = ['id', 'action', 'tools', 'rounds', 'target', 'exit', 'model', 'attempts', 'scope'];
|
|
114
|
+
const STEP_FIELDS = ['id', 'action', 'tools', 'rounds', 'target', 'exit', 'model', 'attempts', 'scope', 'mcpTools'];
|
|
115
|
+
/**
|
|
116
|
+
* R2c (MCP+tickets piece 6): the legal-example line a drafter is shown for `mcpTools` and a red carries in its detail, spelled from the job's own signed
|
|
117
|
+
* list (never a made-up tool name) — one spelling for the prompt and the validator. Empty when the job signed no tools.
|
|
118
|
+
* @param {any} mcp the job's `mcp` block @returns {string}
|
|
119
|
+
*/
|
|
120
|
+
export const mcpToolsExample = (mcp) => (Array.isArray(mcp?.tools) && mcp.tools.length > 0 ? `"mcpTools": ${JSON.stringify([mcp.tools[0]])}` : '');
|
|
115
121
|
/** P (design record 2026-07-28): the signed per-step model-tier menu. Closed by
|
|
116
122
|
* construction — the agent picks a tier, never names an arbitrary model string
|
|
117
123
|
* (the tier→model mapping and any effort params are the RUNNER's, per provider).
|
|
@@ -386,6 +392,22 @@ export function validatePlan(input, { job, maxStepRounds = 40, scopes, seedRed,
|
|
|
386
392
|
}
|
|
387
393
|
}
|
|
388
394
|
|
|
395
|
+
// R2c (piece 6): `mcpTools` ⊆ the SIGNED `mcp.tools`, validated like `tools` — a name outside the signed list is a verb-escape with the tool as
|
|
396
|
+
// structured data; the agent may narrow a step to a subset, never reach a tool the person did not sign. fwd's findMcpPlanRed (src/canrun.js@v0.28.0),
|
|
397
|
+
// the stray half; the generic-job half is after the step loop. A job that signed no server has nothing to grant, so any mcpTools there is an escape too.
|
|
398
|
+
if (s.mcpTools !== undefined) {
|
|
399
|
+
const signed = isObj(spec.mcp) && Array.isArray(spec.mcp.tools) ? /** @type {string[]} */ (spec.mcp.tools) : null;
|
|
400
|
+
if (!(Array.isArray(s.mcpTools) && s.mcpTools.length > 0 && s.mcpTools.every((/** @type {unknown} */ t) => typeof t === 'string') && new Set(s.mcpTools).size === s.mcpTools.length)) {
|
|
401
|
+
red('invalid-value', `${at}.mcpTools`, `non-empty unique list of tool names${signed ? ` from [${signed.join(', ')}], like ${mcpToolsExample(spec.mcp)}` : ''}`);
|
|
402
|
+
} else if (signed === null) {
|
|
403
|
+
reds.push({ code: 'verb-escape', path: `${at}.mcpTools`, verb: s.mcpTools[0], detail: 'this job signed no MCP server, so a step has no MCP tool to call — drop "mcpTools"' });
|
|
404
|
+
} else {
|
|
405
|
+
for (const t of s.mcpTools.filter((/** @type {string} */ t) => !signed.includes(t))) {
|
|
406
|
+
reds.push({ code: 'verb-escape', path: `${at}.mcpTools`, verb: t, detail: `"${t}" is not one of the job's signed tools for server "${spec.mcp.server}" [${signed.join(', ')}] — a step may narrow to a subset, never reach beyond it, like ${mcpToolsExample(spec.mcp)}` });
|
|
407
|
+
}
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
|
|
389
411
|
// rounds ≤ the shell cap (cap-not-estimate; the step bound IS maxTurns)
|
|
390
412
|
if (!(Number.isInteger(s.rounds) && s.rounds >= 1 && s.rounds <= maxStepRounds)) {
|
|
391
413
|
red('bounds', `${at}.rounds`, `integer 1..${maxStepRounds} — the step bound is the Gate's maxTurns, it may tighten the shell cap, never exceed it`);
|
|
@@ -481,6 +503,13 @@ export function validatePlan(input, { job, maxStepRounds = 40, scopes, seedRed,
|
|
|
481
503
|
validateExit(s, at, red, { checkNames, fence: spec.writeScope, insideFence, writeStep, toolsParsed, scopeMenu, stepScope, overlapsStepScope, seedRedNames, isFinalWrite: i === lastWriteIdx });
|
|
482
504
|
});
|
|
483
505
|
|
|
506
|
+
// R2c (piece 6), the generic-job half of fwd's findMcpPlanRed: a generic MCP job (flowType 'mcp') exists to call its tools, so at least one step must
|
|
507
|
+
// grant one. A Tickets job's own tools (issue_read, list_issues) belong to the job (the frozen read and the look), so no step has to name them.
|
|
508
|
+
if (isObj(spec.mcp) && flowTypeOf(spec) === 'mcp'
|
|
509
|
+
&& !plan.steps.some((/** @type {any} */ s) => isObj(s) && Array.isArray(s.mcpTools) && s.mcpTools.length > 0)) {
|
|
510
|
+
red('missing-required', 'steps', `this is an MCP job (server "${spec.mcp.server}") and no step calls one of its tools [${Array.isArray(spec.mcp.tools) ? spec.mcp.tools.join(', ') : ''}] — give at least one step ${mcpToolsExample(spec.mcp)}`);
|
|
511
|
+
}
|
|
512
|
+
|
|
484
513
|
// Rule B (`check-shed`, replan gate): the caller hands over the check names
|
|
485
514
|
// the PREDECESSOR plan carried; a redraft that drops one is refused. Exits
|
|
486
515
|
// without the check verify FORM alone (tree-changed/artifact-written), so a
|
package/src/planrun.js
CHANGED
|
@@ -28,14 +28,15 @@ import { Gate } from 'bareguard';
|
|
|
28
28
|
import { LiteCtx } from 'litectx';
|
|
29
29
|
import { runClose, runStages, ralph, CLOSE_FAULTS, boundGap } from './ralph.js';
|
|
30
30
|
import { validatePlan, pairEditGrant, legalScopes, closeStagesOf } from './plan.js';
|
|
31
|
-
import { WRITE_VERBS, EXIT_TYPES, MAX_EXITS_PER_STEP, MAX_PLAN_STEPS, MAX_SCOPE_MENU, RETRIEVAL_PAIR, EXIT_EXAMPLE } from './plan.js';
|
|
31
|
+
import { WRITE_VERBS, EXIT_TYPES, MAX_EXITS_PER_STEP, MAX_PLAN_STEPS, MAX_SCOPE_MENU, RETRIEVAL_PAIR, EXIT_EXAMPLE, mcpToolsExample } from './plan.js';
|
|
32
32
|
import { snapshotScope, evalExits, CHECK_GAP_MAX } from './exits.js';
|
|
33
33
|
import { createRoot } from './root.js';
|
|
34
34
|
import { createStallWatch, STALL_MS, MAX_STALLS } from './stall.js';
|
|
35
35
|
import { createLadder, STRIKE_LIMIT } from './ladder.js';
|
|
36
36
|
import { createTrend, FIX_STRIKE_LIMIT } from './trend.js';
|
|
37
|
-
import { TOOL_MENU, STORE_VERBS, checkMenu } from './job.js';
|
|
38
|
-
import { TOOL_BY_VERB, CTX_TOOLS, createCtxTools, toolAction, gatedShellOptions, trackedAtSeedGuard, PERSONA_TOOLS, strategyFor } from './tools.js';
|
|
37
|
+
import { TOOL_MENU, STORE_VERBS, checkMenu, flowTypeOf } from './job.js';
|
|
38
|
+
import { TOOL_BY_VERB, CTX_TOOLS, createCtxTools, toolAction, gatedShellOptions, trackedAtSeedGuard, PERSONA_TOOLS, strategyFor, mcpStrategy } from './tools.js';
|
|
39
|
+
import { startStepMcp, mcpAllowlist } from './stepmcp.js';
|
|
39
40
|
import { anySuppressionWarning } from './authoring.js';
|
|
40
41
|
import { createReadShim, readShimArm, readShimStrategy } from './readshim.js';
|
|
41
42
|
import { createCarryStore } from './carrystore.js';
|
|
@@ -739,6 +740,16 @@ export function planPrompt(job, scoutBlob, reds, maxStepRounds, failure, scopes,
|
|
|
739
740
|
// does not exist and neither does this sentence (the A0 and A2 renders). The
|
|
740
741
|
// sentence also states the 24KB bound as its reason, which is the second
|
|
741
742
|
// reason it cannot render for A2: that bound is not in force there.
|
|
743
|
+
// R2c (MCP+tickets piece 6): `mcpTools` exists only for a job that signed an MCP server, and ONLY then does the prompt say so (a plain job's render is
|
|
744
|
+
// byte-identical). A validator rule the drafter is not told about fails every draft, so the rule, the legal values and a legal example ride together;
|
|
745
|
+
// the same example line (`mcpToolsExample`) is what the validator's red carries.
|
|
746
|
+
const mcpLaw = (typeof job.mcp === 'object' && job.mcp !== null) && Array.isArray(job.mcp.tools) && job.mcp.tools.length > 0
|
|
747
|
+
? `\n- "mcpTools" (optional): the MCP tools this step may call — a non-empty unique subset of ${JSON.stringify(job.mcp.tools)}, the tools of server "${job.mcp.server}" the person signed.
|
|
748
|
+
A tool outside that list is rejected: you may narrow a step to a subset, never reach beyond it. Example: ${mcpToolsExample(job.mcp)}.
|
|
749
|
+
The worker calls a granted tool by the name "${job.mcp.server}_<tool>", using the exact tool name above. A step without "mcpTools" has no MCP tool at all. The job's server and tool list were set by the program, not by you, and the plan has no field for them.${flowTypeOf(job) === 'mcp'
|
|
750
|
+
? `\n This is an MCP job: at least one step must carry "mcpTools", or the plan is rejected.`
|
|
751
|
+
: `\n The job's own ticket read needs no step; give "mcpTools" only to a step that must call a signed tool itself.`}`
|
|
752
|
+
: '';
|
|
742
753
|
const readShimLaw = readShimArm(readShim).g1
|
|
743
754
|
? `\n A step granting "read" must also grant "recall" and "get": a read of a large file
|
|
744
755
|
returns only its next 24KB, and those two verbs are the only way to read a symbol in
|
|
@@ -754,7 +765,7 @@ Shape: { "schema": "plan-v1", "steps": [ ... 1..${MAX_PLAN_STEPS} steps ... ] }
|
|
|
754
765
|
strictly in array order. Each step (no other fields exist):
|
|
755
766
|
- "id": kebab-case slug, unique
|
|
756
767
|
- "action": the step's task, precise enough for a worker that sees ONLY this step
|
|
757
|
-
- "tools": non-empty unique subset of ${JSON.stringify(ceiling)} (read/grep are the worker's ONLY way to see the tree — there is no shell; write/edit change the tree; recall/get/impact/related/recent search and navigate the repository index; compress/peek read cheaply; stash/remember/forget park and record notes across steps)${readShimLaw}
|
|
768
|
+
- "tools": non-empty unique subset of ${JSON.stringify(ceiling)} (read/grep are the worker's ONLY way to see the tree — there is no shell; write/edit change the tree; recall/get/impact/related/recent search and navigate the repository index; compress/peek read cheaply; stash/remember/forget park and record notes across steps)${readShimLaw}${mcpLaw}
|
|
758
769
|
- "rounds": integer 1..${maxStepRounds} — the step's per-attempt tool-round bound
|
|
759
770
|
- "target": the step's deliverable path (REQUIRED when tools include write/edit), inside ${JSON.stringify(job.writeScope)}
|
|
760
771
|
- "scope" (optional): narrow this step's WRITE fence — copy one value from the offered scopes below.
|
|
@@ -2297,6 +2308,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
|
|
|
2297
2308
|
const shrinkGuardPath = await trackedAtSeedGuard(workdir, guardListing.files);
|
|
2298
2309
|
|
|
2299
2310
|
const lc = new LiteCtx({ root: workdir });
|
|
2311
|
+
let ctxIndexRecorded = false; // the run's ONE `ctx-index` record: the first index attempt (every later mkWorker re-indexes incrementally, unrecorded)
|
|
2300
2312
|
const ceiling = Array.isArray(job.tools) ? job.tools : [...TOOL_MENU];
|
|
2301
2313
|
const fencePrefixes = job.writeScope.map((/** @type {string} */ g) => resolve(workdir, globToPrefix(g)));
|
|
2302
2314
|
const auditPath = join(workdir, GATE_AUDIT_FILE);
|
|
@@ -2374,7 +2386,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
|
|
|
2374
2386
|
* denied, the wallet as its budget), granted tools only (the menu IS the
|
|
2375
2387
|
* grant), per-attempt round bound via loop.stop() (F20), every round metered
|
|
2376
2388
|
* with a phase label (F12).
|
|
2377
|
-
* @param {{granted: string[], phase: string, attemptRounds: number, attempts: number|null, writable: boolean, root?: ReturnType<typeof createRoot>|null, fence?: string[]|null, workerProvider?: any, truncatedBounded?: boolean}} o
|
|
2389
|
+
* @param {{granted: string[], phase: string, attemptRounds: number, attempts: number|null, writable: boolean, root?: ReturnType<typeof createRoot>|null, fence?: string[]|null, workerProvider?: any, truncatedBounded?: boolean, mcpRun?: Awaited<ReturnType<typeof startStepMcp>>|null}} o
|
|
2378
2390
|
* `root` (Layer R): when present, the worker's write-class actions are teed
|
|
2379
2391
|
* for the within-run ratchet — staged before the gate decides, discarded on
|
|
2380
2392
|
* deny/halt, settled to landed-or-not after execution (the two axes, F43/F7).
|
|
@@ -2384,7 +2396,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
|
|
|
2384
2396
|
* STRIKE LADDER (src/ladder.js), where that count does not exist by design — see
|
|
2385
2397
|
* the turn-allowance note below.
|
|
2386
2398
|
*/
|
|
2387
|
-
async function mkWorker({ granted, phase, attemptRounds, attempts, writable, root = null, fence = null, workerProvider = null, truncatedBounded = false }) {
|
|
2399
|
+
async function mkWorker({ granted, phase, attemptRounds, attempts, writable, root = null, fence = null, workerProvider = null, truncatedBounded = false, mcpRun = null }) {
|
|
2388
2400
|
// THE HARD RULE, ENFORCED STRUCTURALLY (PRD v1.57 §3). This is the ONE seam
|
|
2389
2401
|
// that grants write-class verbs — `writeScope` is empty for every other
|
|
2390
2402
|
// worker, so a read-only phase cannot reach a file whatever it intends — and
|
|
@@ -2443,7 +2455,14 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
|
|
|
2443
2455
|
// fs.writeScope/deny above (step 3's fsCheck runs first in the SAME `??`
|
|
2444
2456
|
// chain, node_modules/bareguard/src/gate.js) — i.e. only the residual
|
|
2445
2457
|
// case of an in-fence path that still carries one of these segments.
|
|
2446
|
-
|
|
2458
|
+
//
|
|
2459
|
+
// R2c (MCP+tickets piece 6): a step that grants MCP tools ALSO gets `tools.allowlist` — and only such a step (every other step's gate is exactly as
|
|
2460
|
+
// before). bareguard's allowlist is exclusive for EVERY action and matches the action TYPE (`read`/`write`/`edit`/`ctx_stash`..., see toolAction), so it
|
|
2461
|
+
// lists the granted verbs' types plus the signed bridge names (src/stepmcp.js, proven against the real Gate): an unsigned bridge tool is denied by name.
|
|
2462
|
+
tools: {
|
|
2463
|
+
denyArgPatterns: { write: [FORBIDDEN_WRITE_SEGMENT_PATTERN], edit: [FORBIDDEN_WRITE_SEGMENT_PATTERN] },
|
|
2464
|
+
...(mcpRun ? { allowlist: mcpAllowlist(granted, mcpRun.server, mcpRun.mcpTools, workdir) } : {}),
|
|
2465
|
+
},
|
|
2447
2466
|
budget: { maxCostUsd: Math.max(remainingUsd(), 1e-4) },
|
|
2448
2467
|
limits: { maxTurns },
|
|
2449
2468
|
audit: { path: auditPath },
|
|
@@ -2627,7 +2646,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
|
|
|
2627
2646
|
memoryCacheCounts.bytesWithheld += bytes;
|
|
2628
2647
|
},
|
|
2629
2648
|
// The first-read map (experimental, off unless the spec says `readMap: true`): this worker's index, and whether it holds ctx_get.
|
|
2630
|
-
readMap: readMapOn ? { root: workdir, hasGet: grantedNames.has(TOOL_BY_VERB.get), getNode: (/** @type {string} */ rel) => lc.getNode(rel), refresh: () => lc.index({ yield: true }), emit: emitCtx } : null,
|
|
2649
|
+
readMap: readMapOn ? { root: workdir, hasGet: grantedNames.has(TOOL_BY_VERB.get), getNode: (/** @type {string} */ rel) => lc.getNode(rel), indexed: () => lc.indexed, refresh: () => lc.index({ yield: true }), emit: emitCtx } : null,
|
|
2631
2650
|
});
|
|
2632
2651
|
const rdTool = shell.find((/** @type {{name: string}} */ t) => t.name === TOOL_BY_VERB.read);
|
|
2633
2652
|
// F48: on native, bound shell_read below the CLI's tool-result display cap and hand back a
|
|
@@ -2670,16 +2689,35 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
|
|
|
2670
2689
|
// sampler all live here) for its full duration: measured 4.4s at 4.5% liveness on a
|
|
2671
2690
|
// 155-file force pass. With yield:true the worst single block measured 189–252ms (n=4),
|
|
2672
2691
|
// below anything a second/minute-scale timer can perceive. Store output is byte-identical.
|
|
2673
|
-
// …and
|
|
2674
|
-
|
|
2675
|
-
|
|
2692
|
+
// …and the index is built at run start for EVERY run (litectx 0.41 makes index.db lazy: nothing exists until the first index()),
|
|
2693
|
+
// so the carry memo's function ranges and the first-read map never wait on a ctx tool being granted. A failed pass never
|
|
2694
|
+
// crashes the run: it is recorded and the run goes on without ranges. One report-only record says what happened — the worker is told nothing.
|
|
2695
|
+
{
|
|
2696
|
+
const indexT0 = performance.now();
|
|
2697
|
+
/** @type {number|undefined} */ let indexedFiles;
|
|
2698
|
+
/** @type {string|undefined} */ let indexError;
|
|
2699
|
+
try {
|
|
2700
|
+
const res = await lc.index({ yield: true });
|
|
2701
|
+
if (typeof res?.files === 'number') indexedFiles = res.files;
|
|
2702
|
+
} catch (e) { indexError = String(/** @type {any} */ (e)?.message ?? e).slice(0, 300); }
|
|
2703
|
+
if (!ctxIndexRecorded) emitCtx('ctx-index', {
|
|
2704
|
+
indexed: lc.indexed === true,
|
|
2705
|
+
...(indexedFiles === undefined ? {} : { files: indexedFiles }),
|
|
2706
|
+
ms: Math.round(performance.now() - indexT0),
|
|
2707
|
+
...(indexError === undefined ? {} : { error: indexError }),
|
|
2708
|
+
});
|
|
2709
|
+
ctxIndexRecorded = true;
|
|
2710
|
+
}
|
|
2711
|
+
// R2c: the step's bridge tools sit beside its shell and ctx tools. Only the GRANTED names exist in `mcpRun.tools` (the bridge was started with `allow` = the
|
|
2712
|
+
// step's `mcpTools`), so an unsigned tool is not in the menu the Loop is given.
|
|
2713
|
+
const toolDefs = [...shell, ...ctx, ...(mcpRun ? mcpRun.tools : [])];
|
|
2676
2714
|
// The carry note: records what each ask's read-class tools returned (a summary, never content) and hands the next
|
|
2677
2715
|
// step/fix ask the facts. Scout and drafter asks feed the store but are never given a note.
|
|
2678
2716
|
if (carry) carry.wrapTools(toolDefs);
|
|
2679
2717
|
/** @param {(prompt: string, defs?: any) => Promise<any>} inner */
|
|
2680
2718
|
const withCarry = (inner) => (!carry ? inner : async (/** @type {string} */ prompt, /** @type {any} */ defs) => {
|
|
2681
2719
|
// The index is incremental: refreshing it here keeps the function ranges true to the files as they now are.
|
|
2682
|
-
if (phase === 'fix' || phase.startsWith('step:')) { try {
|
|
2720
|
+
if (phase === 'fix' || phase.startsWith('step:')) { try { await lc.index({ yield: true }); } catch { /* ranges are left out */ } }
|
|
2683
2721
|
const text = await carry.beginAsk({ phase, iteration: roundIteration, prompt, getNode: (rel) => lc.getNode(rel) });
|
|
2684
2722
|
try { return await inner(text ? `${prompt}\n\n${text}` : prompt, defs); } finally { carry.endAsk({ bounded: attemptBounded, iteration: roundIteration, rounds: attemptRounds }); }
|
|
2685
2723
|
});
|
|
@@ -2703,7 +2741,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
|
|
|
2703
2741
|
const readLines = grantedNames.has(TOOL_BY_VERB.read)
|
|
2704
2742
|
? (native && !shimArm.cap ? NATIVE_READ_STRATEGY : '') + readShimStrategy(shimArm)
|
|
2705
2743
|
: '';
|
|
2706
|
-
const system = PERSONA_TOOLS + strategyFor(granted) + readLines + anySuppressionWarning(closeStagesOf(job));
|
|
2744
|
+
const system = PERSONA_TOOLS + strategyFor(granted) + mcpStrategy(mcpRun ? mcpRun.names : []) + readLines + anySuppressionWarning(closeStagesOf(job));
|
|
2707
2745
|
/** @param {any} u @returns {{inputTokens: number, outputTokens: number, cacheReadTokens: number, cacheCreationTokens: number}} */
|
|
2708
2746
|
const usageOf = (u) => ({ inputTokens: u?.inputTokens ?? 0, outputTokens: u?.outputTokens ?? 0, cacheReadTokens: u?.cacheReadTokens ?? 0, cacheCreationTokens: u?.cacheCreationTokens ?? 0 });
|
|
2709
2747
|
|
|
@@ -3484,9 +3522,26 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
|
|
|
3484
3522
|
* layer up. */
|
|
3485
3523
|
let stepWallStop = null;
|
|
3486
3524
|
|
|
3487
|
-
/**
|
|
3525
|
+
/**
|
|
3526
|
+
* R2c (MCP+tickets piece 6): a step that grants MCP tools starts the bridge ONCE, before its worker is built, and closes it in a `finally` after the step's
|
|
3527
|
+
* LAST try (green, red, thrown or halted): a leaked child is an orphan process. A start refusal (server not configured, will not start, lacks a signed tool)
|
|
3528
|
+
* throws a plain-words `interpreter-red` from here, at $0 and before any token, which the step loop files as a step that could not be set up.
|
|
3529
|
+
* @param {any} step
|
|
3530
|
+
*/
|
|
3488
3531
|
const executeStep = async (step) => {
|
|
3489
|
-
|
|
3532
|
+
const wanted = Array.isArray(step.mcpTools) && step.mcpTools.length > 0;
|
|
3533
|
+
if (wanted && !(job.mcp && typeof job.mcp.server === 'string')) {
|
|
3534
|
+
const err = /** @type {CategorizedError} */ (new Error(`step "${step.id}" grants MCP tools but the job signed no MCP server`));
|
|
3535
|
+
err.category = 'interpreter-red';
|
|
3536
|
+
throw err;
|
|
3537
|
+
}
|
|
3538
|
+
const mcpRun = wanted ? await startStepMcp({ mcp: job.mcp, mcpTools: step.mcpTools }) : null;
|
|
3539
|
+
try { return await executeStepWith(step, mcpRun); } finally { await mcpRun?.close(); }
|
|
3540
|
+
};
|
|
3541
|
+
|
|
3542
|
+
/** @param {any} step @param {Awaited<ReturnType<typeof startStepMcp>>|null} mcpRun */
|
|
3543
|
+
const executeStepWith = async (step, mcpRun) => {
|
|
3544
|
+
emit('step-start', { step: step.id, rounds: step.rounds, tools: step.tools, ...(mcpRun ? { mcpTools: step.mcpTools } : {}) });
|
|
3490
3545
|
// the before-side of every tree-changed exit, taken at STEP start: the
|
|
3491
3546
|
// step's cumulative work is what the exit judges (outcome, never intent)
|
|
3492
3547
|
const snapshot = new Map();
|
|
@@ -3525,6 +3580,7 @@ export async function runPlan(job, { workdir, provider, nativeProvider, provider
|
|
|
3525
3580
|
granted: step.tools, phase: `step:${step.id}`, attemptRounds: step.rounds, attempts: null, writable: true, root,
|
|
3526
3581
|
fence: step.scope !== undefined ? [resolve(workdir, globToPrefix(step.scope))] : null,
|
|
3527
3582
|
workerProvider: step.model !== undefined && providerFor ? providerFor(step.model) : null,
|
|
3583
|
+
mcpRun,
|
|
3528
3584
|
});
|
|
3529
3585
|
// ONE ladder per step: the seen-set and the strike count are this step's own
|
|
3530
3586
|
// history, and a shared one would strike a fresh step for a gap an earlier step
|