Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
138 changes: 45 additions & 93 deletions .aiox-core/core/execution/build-state-manager.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,11 @@
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const {
normalizeError,
sanitizeValue: sanitizeErrorValue,
serializeError,
} = require('../errors');

// Optional dependencies with graceful fallback
let chalk;
Expand Down Expand Up @@ -95,95 +100,9 @@ const NotificationType = {
* @returns {*} Data-only representation that JSON.stringify can serialize.
*/
function sanitizeLogValue(value, seen = new WeakSet()) {
if (value === undefined || value === null) {
return value;
}

const valueType = typeof value;

if (valueType === 'bigint') {
return value.toString();
}

if (valueType === 'function' || valueType === 'symbol') {
return String(value);
}

if (valueType !== 'object') {
return value;
}

if (seen.has(value)) {
return '[Circular]';
}

if (value instanceof Date) {
return Number.isNaN(value.getTime()) ? value.toString() : value.toISOString();
}

if (value instanceof RegExp) {
return value.toString();
}

if (value instanceof Error) {
const safeError = {
name: value.name,
message: value.message,
stack: shouldExposeLogErrorStack() ? value.stack : '[redacted]',
};

seen.add(value);

try {
Object.getOwnPropertyNames(value).forEach((key) => {
if (key === 'name' || key === 'message' || key === 'stack') {
return;
}

try {
safeError[key] = sanitizeLogValue(value[key], seen);
} catch (error) {
safeError[key] = `[Unserializable: ${error.message}]`;
}
});

return safeError;
} finally {
seen.delete(value);
}
}

seen.add(value);

try {
if (value instanceof Map) {
return Array.from(value.entries()).map(([key, entryValue]) => [
sanitizeLogValue(key, seen),
sanitizeLogValue(entryValue, seen),
]);
}

if (value instanceof Set) {
return Array.from(value.values()).map((entryValue) => sanitizeLogValue(entryValue, seen));
}

if (Array.isArray(value)) {
return value.map((entryValue) => sanitizeLogValue(entryValue, seen));
}

return Object.keys(value).reduce((safeValue, key) => {
try {
safeValue[key] = sanitizeLogValue(value[key], seen);
} catch (error) {
safeValue[key] = `[Unserializable: ${error.message}]`;
}
return safeValue;
}, {});
} catch (error) {
return `[Unserializable: ${error.message}]`;
} finally {
seen.delete(value);
}
return sanitizeErrorValue(value, seen, {
includeStack: shouldExposeLogErrorStack(),
});
}

/**
Expand All @@ -210,6 +129,29 @@ function stringifyLogDetails(value) {
}
}

/**
* Normalize a failed build attempt into legacy message plus canonical details.
*
* @param {*} error - Raw failure error/value.
* @param {object} context - Build/subtask context for metadata.
* @returns {{ message: string, details: object }} Normalized failure payload.
*/
function normalizeFailureError(error, context = {}) {
const normalized = normalizeError(error || 'Unknown error', {
code: 'AIOX_EXECUTION_FAILED',
metadata: {
buildState: context,
},
});

return {
message: normalized.message,
details: serializeError(normalized, {
includeStack: shouldExposeLogErrorStack(),
}),
};
}

// ═══════════════════════════════════════════════════════════════════════════════════
// SCHEMA VALIDATION
// ═══════════════════════════════════════════════════════════════════════════════════
Expand Down Expand Up @@ -930,12 +872,21 @@ class BuildStateManager {
throw new Error('No state loaded');
}

const attempt =
options.attempt ||
this._state.failedAttempts.filter((f) => f.subtaskId === subtaskId).length + 1;

const normalizedFailure = normalizeFailureError(options.error, {
storyId: this.storyId,
subtaskId,
attempt,
});

const failure = {
subtaskId,
attempt:
options.attempt ||
this._state.failedAttempts.filter((f) => f.subtaskId === subtaskId).length + 1,
error: options.error || 'Unknown error',
attempt,
error: normalizedFailure.message,
errorDetails: normalizedFailure.details,
timestamp: new Date().toISOString(),
approach: options.approach || null,
duration: options.duration || null,
Expand All @@ -957,6 +908,7 @@ class BuildStateManager {
this._logAttempt(subtaskId, 'failure', {
attempt: failure.attempt,
error: failure.error,
errorDetails: failure.errorDetails,
isStuck: isStuck.stuck,
});

Expand Down
71 changes: 68 additions & 3 deletions .aiox-core/core/ids/registry-updater.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,11 @@ const {
computeChecksum,
resolveEntityId,
resolveUsedBy,
buildNameIndex,
detectLifecycle,
SCAN_CONFIG,
ADAPTABILITY_DEFAULTS,
EXTERNAL_TOOLS,
REPO_ROOT,
REGISTRY_PATH,
} = require(path.resolve(__dirname, '../../development/scripts/populate-entity-registry.js'));
Expand Down Expand Up @@ -250,6 +253,7 @@ class RegistryUpdater {
try {
await this._withLock(async () => {
const registry = this._loadRegistry();
const changedEntities = [];

for (const { action, filePath } of batch) {
try {
Expand All @@ -271,7 +275,20 @@ class RegistryUpdater {
default:
console.warn(`[IDS-Updater] Unknown action: ${action}`);
}
if (mutated) updated++;
if (mutated) {
updated++;
if (action !== 'unlink') {
const relPath = path.relative(this._repoRoot, abs).replace(/\\/g, '/');
const config = this._detectCategory(relPath);
if (config) {
const category = config.category;
const entityId = resolveEntityId(abs, config, registry.entities[category] || {}, this._repoRoot);
if (registry.entities[category]?.[entityId]) {
changedEntities.push({ category, entityId });
}
}
}
}

this._logAudit({ action, path: path.relative(this._repoRoot, abs).replace(/\\/g, '/'), trigger: 'watcher' });
} catch (err) {
Expand All @@ -283,10 +300,13 @@ class RegistryUpdater {

if (updated > 0) {
this._resolveAllUsedBy(registry);
this._refreshDerivedDependencyFields(registry, changedEntities);

// NOG-8: Apply code intelligence enrichment AFTER resolveAllUsedBy
// so that code-intel usedBy data is merged on top of static graph
await this._applyCodeIntelEnrichments(registry);
this._resolveAllUsedBy(registry);
this._refreshDerivedDependencyFields(registry, changedEntities);
registry.metadata.lastUpdated = new Date().toISOString();
registry.metadata.entityCount = this._countEntities(registry);
this._writeRegistry(registry);
Expand Down Expand Up @@ -330,7 +350,7 @@ class RegistryUpdater {
const resolvedEntityId = resolveEntityId(absPath, config, registry.entities[category], this._repoRoot);
const keywords = extractKeywords(absPath, content);
const purpose = extractPurpose(content, absPath);
const dependencies = detectDependencies(content, resolvedEntityId);
const dependencies = detectDependencies(content, resolvedEntityId, false, absPath);
const checksum = computeChecksum(absPath);
const defaultScore = ADAPTABILITY_DEFAULTS[config.type] || 0.5;

Expand All @@ -342,6 +362,9 @@ class RegistryUpdater {
keywords,
usedBy: [],
dependencies,
externalDeps: [],
plannedDeps: [],
lifecycle: 'experimental',
Comment thread
coderabbitai[bot] marked this conversation as resolved.
adaptability: {
score: defaultScore,
constraints: [],
Expand Down Expand Up @@ -383,12 +406,15 @@ class RegistryUpdater {
}

const newChecksum = computeChecksum(absPath);
const nextDependencies = detectDependencies(content, entityId, false, absPath);

if (newChecksum !== existing.checksum) {
existing.checksum = newChecksum;
existing.purpose = extractPurpose(content, absPath);
existing.keywords = extractKeywords(absPath, content);
existing.dependencies = detectDependencies(content, entityId);
existing.dependencies = nextDependencies;
} else if (JSON.stringify(existing.dependencies || []) !== JSON.stringify(nextDependencies)) {
existing.dependencies = nextDependencies;
}

existing.lastVerified = new Date().toISOString();
Expand Down Expand Up @@ -612,6 +638,45 @@ class RegistryUpdater {
resolveUsedBy(registry.entities);
}

_refreshDerivedDependencyFields(registry, changedEntities) {
const nameIndex = buildNameIndex(registry.entities);
const seen = new Set();

for (const { category, entityId } of changedEntities) {
const key = `${category}:${entityId}`;
if (seen.has(key)) continue;
seen.add(key);

const entity = registry.entities[category]?.[entityId];
if (!entity) continue;

const internal = [];
const external = [];
const planned = [];

const rawDeps = [
...(entity.dependencies || []),
...(entity.externalDeps || []),
...(entity.plannedDeps || []),
];

for (const dep of rawDeps) {
if (nameIndex.has(dep)) {
internal.push(dep);
} else if (EXTERNAL_TOOLS.has(String(dep).toLowerCase())) {
external.push(dep);
} else {
planned.push(dep);
}
}

entity.dependencies = [...new Set(internal)];
entity.externalDeps = [...new Set(external)];
entity.plannedDeps = [...new Set(planned)];
entity.lifecycle = detectLifecycle(entityId, entity);
}
}

_countEntities(registry) {
let count = 0;
for (const catEntities of Object.values(registry.entities)) {
Expand Down
13 changes: 12 additions & 1 deletion .aiox-core/core/synapse/engine.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

const fs = require('fs');
const path = require('path');
const { normalizeError, serializeError } = require('../errors');

const {
estimateContextPercent,
Expand Down Expand Up @@ -131,10 +132,20 @@ class PipelineMetrics {
existing.end = endTime;
existing.duration = Number(endTime - existing.start) / 1e6;
}
const normalizedError = normalizeError(error, {
code: 'AIOX_SYNAPSE_LAYER_FAILED',
metadata: {
synapse: {
layer: name,
},
},
});

this.layers[name] = {
...existing,
status: 'error',
error: error && error.message ? error.message : String(error),
error: normalizedError.message,
errorDetails: serializeError(normalizedError),
};
}

Expand Down
Loading
Loading