Skip to content

Commit e7688e2

Browse files
committed
refactor: split runtime governance helpers
1 parent 9bf469b commit e7688e2

23 files changed

Lines changed: 4409 additions & 3563 deletions

‎.mcp.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -19,4 +19,4 @@
1919
"_note": "Loads .devcodex/profile/ files and returns ENV_MODE / agent config."
2020
}
2121
}
22-
}
22+
}
Lines changed: 338 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,338 @@
1+
'use strict'
2+
3+
function buildLifecycleBootstrapStateUtils(ctx) {
4+
const {
5+
fs,
6+
path,
7+
LAYOUT,
8+
CONTEXT_PROJECT,
9+
DEFAULT_SCOPE,
10+
EXECUTION_MODE,
11+
readJsonFile,
12+
META_STATE_PATHS,
13+
buildPathNeedles,
14+
getStatePathsFor,
15+
getStatePaths,
16+
getActiveScope,
17+
getActiveNamespaceRoot,
18+
getBootstrapAgent,
19+
getWorkspaceNamespaceRoot,
20+
readProfileMode,
21+
getToolName,
22+
touchesPath,
23+
getToolInputStrings,
24+
getCommandText,
25+
getRecentBootstrapTaskStamps,
26+
isRecentBootstrapTaskPath,
27+
buildInterceptionOutput,
28+
INTERCEPTION_ACTION,
29+
noopOutput
30+
} = ctx
31+
32+
function buildScopedNeedles(scopeRoot, segments) {
33+
return buildPathNeedles(path.join(scopeRoot, ...segments))
34+
}
35+
36+
function getBootstrapScopes(state, payload) {
37+
const namespaceRoot = getActiveNamespaceRoot(state)
38+
const bootstrapAgent = getBootstrapAgent(state, payload)
39+
const memorySegments = ['.memory', 'clients']
40+
const memoryNeedles = bootstrapAgent
41+
? buildScopedNeedles(namespaceRoot, [...memorySegments, bootstrapAgent])
42+
: buildScopedNeedles(namespaceRoot, memorySegments)
43+
const summaryNeedles = bootstrapAgent
44+
? buildScopedNeedles(namespaceRoot, [...memorySegments, bootstrapAgent, 'SUMMARY.md'])
45+
: []
46+
const taskNeedles = bootstrapAgent
47+
? getRecentBootstrapTaskStamps().flatMap(stamp => buildScopedNeedles(
48+
namespaceRoot,
49+
[...memorySegments, bootstrapAgent, 'tasks', `${stamp}.md`]
50+
))
51+
: []
52+
const profileNeedles = buildScopedNeedles(namespaceRoot, ['profile'])
53+
if (LAYOUT.enabled && getActiveScope(state) !== 'workspace') {
54+
profileNeedles.push(...buildScopedNeedles(getWorkspaceNamespaceRoot(), ['profile']))
55+
}
56+
return {
57+
profileNeedles: [...new Set(profileNeedles)],
58+
memoryNeedles,
59+
summaryNeedles,
60+
taskNeedles
61+
}
62+
}
63+
64+
function buildDefaultState(mode) {
65+
const normalizedMode = mode === 'dev' ? 'dev' : 'prod'
66+
return {
67+
version: 1,
68+
mode: normalizedMode,
69+
executionMode: EXECUTION_MODE.CONFIRM,
70+
phase: 'bootstrapping',
71+
startedAt: new Date().toISOString(),
72+
updatedAt: new Date().toISOString(),
73+
promptCount: 0,
74+
toolUseCount: 0,
75+
activeProject: CONTEXT_PROJECT || '',
76+
activeScope: DEFAULT_SCOPE,
77+
activeProjectSource: CONTEXT_PROJECT ? 'context' : '',
78+
bootstrap: { profileRead: false, summaryRead: false, tasksRead: false },
79+
lastBootstrapWarningKey: '',
80+
lastClosureReminderKey: '',
81+
lastMultiProjectWarningKey: '',
82+
bootstrapComplete: false,
83+
visible: {
84+
payloadObserved: false,
85+
replyEvidence: 'unverified',
86+
replySource: '',
87+
precheckStatus: 'unverified',
88+
precheck: false,
89+
compliance: false,
90+
artifactPaths: false
91+
},
92+
stickyProject: {
93+
project: CONTEXT_PROJECT || '',
94+
source: CONTEXT_PROJECT ? 'context' : '',
95+
sessionKey: '',
96+
updatedAt: '',
97+
updatedAtMs: 0
98+
},
99+
cp3Runtime: {},
100+
mutated: false,
101+
reportTouched: false,
102+
memoryTouched: false,
103+
dangerousApprovals: {},
104+
lastEvent: '',
105+
lastReason: ''
106+
}
107+
}
108+
109+
function loadState(modeHint) {
110+
const metaState = readJsonFile(META_STATE_PATHS.file)
111+
let saved = metaState
112+
if (LAYOUT.enabled) {
113+
const preferredProject = String(metaState?.activeProject || CONTEXT_PROJECT || '').trim()
114+
const preferredScope = metaState?.activeScope || (preferredProject ? 'project' : DEFAULT_SCOPE)
115+
const activeState = readJsonFile(getStatePathsFor(preferredProject, preferredScope).file)
116+
if (activeState && typeof activeState === 'object') {
117+
saved = activeState
118+
} else if (CONTEXT_PROJECT) {
119+
const contextState = readJsonFile(getStatePathsFor(CONTEXT_PROJECT, 'project').file)
120+
if (contextState && typeof contextState === 'object') saved = contextState
121+
}
122+
}
123+
const mode = modeHint || readProfileMode(saved || metaState || null, saved?.activeProject || metaState?.activeProject || '')
124+
const current = buildDefaultState(mode)
125+
if (!saved || typeof saved !== 'object') return current
126+
return {
127+
...current,
128+
...saved,
129+
mode,
130+
bootstrap: { ...current.bootstrap, ...(saved.bootstrap || {}) },
131+
visible: { ...current.visible, ...(saved.visible || {}) },
132+
stickyProject: { ...current.stickyProject, ...(saved.stickyProject || {}), ...(metaState?.stickyProject || {}) },
133+
cp3Runtime: { ...current.cp3Runtime, ...(saved.cp3Runtime || {}) },
134+
dangerousApprovals: { ...current.dangerousApprovals, ...(saved.dangerousApprovals || {}) }
135+
}
136+
}
137+
138+
function saveState(state) {
139+
state.updatedAt = new Date().toISOString()
140+
const activePaths = getStatePaths(state)
141+
fs.mkdirSync(activePaths.dir, { recursive: true })
142+
fs.writeFileSync(activePaths.file, JSON.stringify(state, null, 2))
143+
if (LAYOUT.enabled && activePaths.file !== META_STATE_PATHS.file) {
144+
const metaState = {
145+
...state,
146+
bootstrap: { ...(state.bootstrap || {}) },
147+
visible: { ...(state.visible || {}) },
148+
stickyProject: { ...(state.stickyProject || {}) },
149+
dangerousApprovals: { ...(state.dangerousApprovals || {}) }
150+
}
151+
fs.mkdirSync(META_STATE_PATHS.dir, { recursive: true })
152+
fs.writeFileSync(META_STATE_PATHS.file, JSON.stringify(metaState, null, 2))
153+
}
154+
}
155+
156+
function resetState(mode, previousState) {
157+
const state = buildDefaultState(mode)
158+
state.promptCount = 1
159+
state.activeProject = previousState?.activeProject || CONTEXT_PROJECT || ''
160+
state.activeScope = previousState?.activeScope || DEFAULT_SCOPE
161+
state.activeProjectSource = previousState?.activeProjectSource || (CONTEXT_PROJECT ? 'context' : '')
162+
state.lastMultiProjectWarningKey = previousState?.lastMultiProjectWarningKey || ''
163+
state.stickyProject = { ...state.stickyProject, ...(previousState?.stickyProject || {}) }
164+
state.cp3Runtime = { ...(previousState?.cp3Runtime || {}) }
165+
state.dangerousApprovals = { ...(previousState?.dangerousApprovals || {}) }
166+
saveState(state)
167+
return state
168+
}
169+
170+
function isReadOnlyBootstrapShellCommand(payload) {
171+
const command = getCommandText(payload)
172+
if (!command || !command.trim()) return false
173+
const lowerCommand = command.toLowerCase()
174+
if (/[;&|`]/.test(command) || /\$\(|\b(?:&&|\|\|)\b/.test(command)) return false
175+
if (
176+
/>{1,2}/.test(command) ||
177+
/\b(set-content|add-content|out-file|tee|copy-item|move-item|remove-item|new-item|rename-item)\b/i.test(command) ||
178+
/\b(sc|ac|ni|ri|mi)\b/i.test(command) ||
179+
/\b(cp|mv|rm|del|erase|touch|mkdir|rmdir|git\s+add|git\s+commit|npm\s+install)\b/i.test(command)
180+
) {
181+
return false
182+
}
183+
return /\b(get-content|cat|type|get-childitem|ls|dir|rg|findstr|select-string|head|tail|more|echo)\b/.test(lowerCommand)
184+
}
185+
186+
function isBootstrapReadTool(payload, state) {
187+
const toolName = getToolName(payload).toLowerCase()
188+
const scopes = getBootstrapScopes(state, payload)
189+
const readPatterns = [
190+
/^read([_-]?file)?$/,
191+
/^list[_-]?dir$/,
192+
/^file[_-]?search$/,
193+
/^grep([_-]?search)?$/,
194+
/^semantic[_-]?search$/,
195+
/^glob$/
196+
]
197+
if (readPatterns.some(pattern => pattern.test(toolName))) {
198+
return (
199+
touchesPath(payload, ...scopes.profileNeedles) ||
200+
touchesPath(payload, ...scopes.memoryNeedles)
201+
)
202+
}
203+
const shellReadPatterns = [
204+
/^shell[_-]?command$/,
205+
/^run[_-]?in[_-]?terminal$/,
206+
/^send[_-]?to[_-]?terminal$/,
207+
/^bash$/,
208+
/^powershell$/
209+
]
210+
if (!shellReadPatterns.some(pattern => pattern.test(toolName))) return false
211+
if (!isReadOnlyBootstrapShellCommand(payload)) return false
212+
return (
213+
touchesPath(payload, ...scopes.profileNeedles) ||
214+
touchesPath(payload, ...scopes.memoryNeedles)
215+
)
216+
}
217+
218+
function isPureReadTool(payload) {
219+
const toolName = getToolName(payload).toLowerCase()
220+
const readPatterns = [
221+
/^read([_-]?file)?$/,
222+
/^list[_-]?dir$/,
223+
/^file[_-]?search$/,
224+
/^grep([_-]?search)?$/,
225+
/^semantic[_-]?search$/,
226+
/^glob$/
227+
]
228+
return readPatterns.some(pattern => pattern.test(toolName))
229+
}
230+
231+
function isClarificationTool(payload) {
232+
return /^vscode[_-]?askquestions$/.test(getToolName(payload).toLowerCase())
233+
}
234+
235+
function updateBootstrapState(state, payload) {
236+
const scopes = getBootstrapScopes(state, payload)
237+
const inputStrings = getToolInputStrings(payload)
238+
if (touchesPath(payload, ...scopes.profileNeedles)) state.bootstrap.profileRead = true
239+
if ((scopes.summaryNeedles.length && touchesPath(payload, ...scopes.summaryNeedles)) ||
240+
(!scopes.summaryNeedles.length &&
241+
touchesPath(payload, ...scopes.memoryNeedles) &&
242+
inputStrings.some(input => input.includes('/summary.md')))) {
243+
state.bootstrap.summaryRead = true
244+
}
245+
if ((scopes.taskNeedles.length && touchesPath(payload, ...scopes.taskNeedles)) ||
246+
(!scopes.taskNeedles.length &&
247+
touchesPath(payload, ...scopes.memoryNeedles) &&
248+
inputStrings.some(isRecentBootstrapTaskPath))) {
249+
state.bootstrap.tasksRead = true
250+
}
251+
state.bootstrapComplete = !!(
252+
state.bootstrap.profileRead && state.bootstrap.summaryRead && state.bootstrap.tasksRead
253+
)
254+
if (state.bootstrapComplete) state.phase = 'active'
255+
}
256+
257+
function buildBootstrapMessage() {
258+
return [
259+
'DevCodex hook-enforced bootstrap is active for this user message.',
260+
'Load the effective profile (legacy .devcodex/profile/ or workspace-namespace profile roots) and memory files under',
261+
'the active .devcodex namespace before any substantive work.',
262+
'Your first user-visible block must be the entry check PC0-PC7 before substantive task content; dev mode adds full PC4 diagnostics.',
263+
'*** S07 compaction trigger (v1.9.6+): if this turn resumes from /compact, /resume, or summary-restore,',
264+
'this also counts as "first user-visible reply" — you MUST re-output PC0-PC7 even when instructed to "continue without acknowledging".'
265+
].join(' ')
266+
}
267+
268+
function buildBootstrapDenyOutput(state, payload, eventName, platform) {
269+
const missing = []
270+
if (!state.bootstrap.profileRead) missing.push('profile')
271+
if (!state.bootstrap.summaryRead) missing.push('SUMMARY')
272+
if (!state.bootstrap.tasksRead) missing.push('tasks')
273+
const toolName = getToolName(payload) || 'tool'
274+
return buildInterceptionOutput(
275+
state,
276+
platform || 'copilot',
277+
eventName,
278+
INTERCEPTION_ACTION.REQUIRE_COMPLETION,
279+
'bootstrap-incomplete',
280+
`Blocked tool use before DevCodex bootstrap: ${toolName}`,
281+
`Read .devcodex/profile/ plus SUMMARY/tasks memory files first. Missing: ${missing.join(', ') || 'none'}.`,
282+
'Read the effective profile, SUMMARY, and today tasks file, then retry the tool.'
283+
)
284+
}
285+
286+
function buildBootstrapWarningOutput(state, payload, eventName, platform) {
287+
const missing = []
288+
if (!state.bootstrap.profileRead) missing.push('profile')
289+
if (!state.bootstrap.summaryRead) missing.push('SUMMARY')
290+
if (!state.bootstrap.tasksRead) missing.push('tasks')
291+
const toolName = getToolName(payload) || 'tool'
292+
return buildInterceptionOutput(
293+
state,
294+
platform || 'copilot',
295+
eventName,
296+
INTERCEPTION_ACTION.REQUIRE_COMPLETION,
297+
'bootstrap-incomplete',
298+
`Bootstrap incomplete before ${toolName}`,
299+
`Read .devcodex/profile/ plus SUMMARY/tasks memory files as soon as possible. Missing: ${missing.join(', ') || 'none'}. Tool allowed in safety-only mode.`,
300+
'Read bootstrap files before substantive work.'
301+
)
302+
}
303+
304+
function buildBootstrapWarningKey(state) {
305+
const missing = []
306+
if (!state.bootstrap.profileRead) missing.push('profile')
307+
if (!state.bootstrap.summaryRead) missing.push('SUMMARY')
308+
if (!state.bootstrap.tasksRead) missing.push('tasks')
309+
return [state.promptCount || 0, missing.join(',')].join('|')
310+
}
311+
312+
function buildDedupedBootstrapWarningOutput(state, payload, eventName, platform) {
313+
const key = buildBootstrapWarningKey(state, payload)
314+
if (state.lastBootstrapWarningKey === key) return noopOutput()
315+
state.lastBootstrapWarningKey = key
316+
return buildBootstrapWarningOutput(state, payload, eventName, platform)
317+
}
318+
319+
return {
320+
getBootstrapScopes,
321+
buildDefaultState,
322+
loadState,
323+
saveState,
324+
resetState,
325+
isBootstrapReadTool,
326+
isPureReadTool,
327+
isClarificationTool,
328+
updateBootstrapState,
329+
isReadOnlyBootstrapShellCommand,
330+
buildBootstrapMessage,
331+
buildBootstrapDenyOutput,
332+
buildBootstrapWarningOutput,
333+
buildBootstrapWarningKey,
334+
buildDedupedBootstrapWarningOutput
335+
}
336+
}
337+
338+
module.exports = { buildLifecycleBootstrapStateUtils }

0 commit comments

Comments
 (0)