regrades and all 17 detectors

This commit is contained in:
2026-10-15 12:06:39 -04:00
parent 0e4d8d2be4
commit 4917d8e73c
382 changed files with 31364 additions and 225 deletions

View File

@@ -0,0 +1,28 @@
--agent-import-path is deprecated; use --agent instead.
1/1 Mean: 1.000 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0:02:05 0:00:00
adhoc • replay
┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┓
┃ Trials ┃ Exceptions ┃ Mean ┃
┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━┩
│ 1 │ 0 │ 1.000 │
└────────┴────────────┴───────┘
┏━━━━━━━━┳━━━━━━━┓
┃ Reward ┃ Count ┃
┡━━━━━━━━╇━━━━━━━┩
│ 1.0 │ 1 │
└────────┴───────┘
Job Info
Total runtime: 2m 5s
Results written to
harbor-jobs/regrade-1792079194-12645-1-reward-0.6400-JDkYGLS/result.json
Inspect results by running `harbor view harbor-jobs`
Share results by running `harbor upload
harbor-jobs/regrade-1792079194-12645-1-reward-0.6400-JDkYGLS`
Copied to harbor-tasks/potion-voice-user-ownership/rubric-regrades/reward-0.6400-JDkYGLS
reward: 1.0000
task: harbor-tasks/potion-voice-user-ownership
trial: DB7yero
perms: normalized 48 owner / 0 mode

View File

@@ -0,0 +1,30 @@
{
"job_name": "regrade-1792079194-12645-1-reward-0.6400-JDkYGLS",
"jobs_dir": "harbor-jobs",
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"agents": [
{
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6400-JDkYGLS",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
}
],
"tasks": [
{
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
}
]
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,70 @@
{
"schema_version": 2,
"created_at": "2026-10-15T15:46:36.189737Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"AgentTimeoutError",
"ModelNotFoundError",
"ApiUsageLimitError",
"VerifierOutputParseError",
"AgentAuthenticationError",
"AgentSafetyRefusalError",
"VerifierTimeoutError",
"RewardFileEmptyError",
"RewardFileNotFoundError"
],
"wait_multiplier": 1.0,
"min_wait_sec": 1.0,
"max_wait_sec": 60.0
},
"trials": [
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:ec9aa16027c75e26ebaa37033610ad6f554a6dfe1a48bca556a6c0d1bdfbac77",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6400-JDkYGLS",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}
]
}

View File

@@ -0,0 +1,9 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -0,0 +1,27 @@
{
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__DB7yero",
"trials_dir": "harbor-jobs/regrade-1792079194-12645-1-reward-0.6400-JDkYGLS",
"agent": {
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6400-JDkYGLS",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
},
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "b26aa08b-bc0e-4162-b369-45ee1eb54766"
}

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:ec9aa16027c75e26ebaa37033610ad6f554a6dfe1a48bca556a6c0d1bdfbac77",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6400-JDkYGLS",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -0,0 +1,119 @@
{
"id": "cb0150e4-4faf-43a0-95a5-f3b3fd3bf985",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__DB7yero",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/regrade-1792079194-12645-1-reward-0.6400-JDkYGLS/potion-voice-user-ownership__DB7yero",
"task_id": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "ecf47d1d7b9e6b01d23ebd282d2ef4dcc0759a848a1a1f859c7cb80cb97742ed",
"config": {
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__DB7yero",
"trials_dir": "harbor-jobs/regrade-1792079194-12645-1-reward-0.6400-JDkYGLS",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "replay_agent:ReplayAgent",
"model_name": null,
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6400-JDkYGLS",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "b26aa08b-bc0e-4162-b369-45ee1eb54766"
},
"agent_info": {
"name": "replay",
"version": "1.0.0",
"model_info": null
},
"agent_result": {
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 1.0
}
},
"exception_info": null,
"started_at": "2026-10-15T15:46:36.494260Z",
"finished_at": "2026-10-15T15:48:41.375651Z",
"environment_setup": {
"started_at": "2026-10-15T15:46:36.649943Z",
"finished_at": "2026-10-15T15:46:40.973512Z"
},
"agent_setup": {
"started_at": "2026-10-15T15:46:40.973600Z",
"finished_at": "2026-10-15T15:46:40.973677Z"
},
"agent_execution": {
"started_at": "2026-10-15T15:46:40.973760Z",
"finished_at": "2026-10-15T15:46:41.504544Z"
},
"verifier": {
"started_at": "2026-10-15T15:46:42.071264Z",
"finished_at": "2026-10-15T15:48:37.158055Z"
},
"step_results": null
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,387 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const { metadata, input, _id, userAudioProfileId, userId } = job._doc
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
console.log('metadata------', metadata)
console.log('input', input)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
let tenantValidated = false
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
if (!_id || !userAudioProfileId || !userId) {
Bugsnag.notify(
new Error(
`Voice cloning tenant validation failed ` + JSON.stringify(job)
)
)
resolve()
return
}
const [voiceCloning, userAudioProfile] = await Promise.all([
voiceCloningService.read({
_id,
userId,
userAudioProfileId,
}),
userAudioProfileService.read({
_id: userAudioProfileId,
userId,
}),
])
if (!voiceCloning || !userAudioProfile) {
Bugsnag.notify(
new Error(
`Voice cloning tenant validation failed ` + JSON.stringify(job)
)
)
resolve()
return
}
tenantValidated = true
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
await voiceCloningService.update({
_id,
userId,
status: 'processing',
})
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'processing',
})
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
await voiceCloningService.update({
_id,
userId,
status: 'completed',
})
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'completed',
training_model_path,
})
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
training_model_s3_path,
})
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
if (tenantValidated) {
// update the db to set status as error
await voiceCloningService.update({
_id,
userId,
status: 'error',
})
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'error',
})
}
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Error in voice cloning worker loop', { error })
Bugsnag.notify(error)
}
}
}
init()

View File

@@ -0,0 +1,144 @@
const StringifyUtils = require('../../app/services/utils/logService')
const create = (UserAudioProfileModel) => async (data) => {
try {
const newModel = new UserAudioProfileModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data) => {
try {
const inserted = await UserAudioProfileModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...filter,
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter) => {
try {
const foundModels = await UserAudioProfileModel.find({
...filter,
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data) => {
try {
if (!data._id || !data.userId) {
throw new Error('UserAudioProfile update requires _id and userId')
}
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id: data._id, userId: data.userId },
data,
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,145 @@
const StringifyUtils = require('../../app/services/utils/logService')
const create = (VoiceCloningModel) => async (data) => {
try {
const newModel = new VoiceCloningModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data) => {
try {
const inserted = await VoiceCloningModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter) => {
try {
const foundModel = await VoiceCloningModel.findOne({
...filter,
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter) => {
try {
const foundModels = await VoiceCloningModel.find({
...filter,
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data) => {
try {
if (!data._id || !data.userId) {
throw new Error('VoiceCloning update requires _id and userId')
}
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ _id: data._id, userId: data.userId },
data,
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -0,0 +1,291 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
const processQueue = () => {
/* eslint-disable no-async-promise-executor */
return new Promise(async (resolve, reject) => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
} = job
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
if (!userAudioProfileId || !salutationId || !recordingId) {
Bugsnag.notify(
new Error(
`Speech synthesis tenant validation failed ` +
JSON.stringify(job)
)
)
resolve()
return
}
// read the path for the training model for the this users audio profile
const userAudioProfile = await userAudioProfileService.read({
_id: userAudioProfileId,
status: 'completed',
})
if (userAudioProfile && userAudioProfile.userId) {
const { training_model_path, userId } = userAudioProfile
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
if (!salutationToUpdate || !recordingToUpdate) {
Bugsnag.notify(
new Error(
`Speech synthesis tenant validation failed ` +
JSON.stringify(job)
)
)
resolve()
return
}
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace(
'-',
'_'
)}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Create new entry with the s3 path to salutation collection for the user and its profile id
// upsert the salutation
await salutationService.updateOrCreate(
{
firstName: firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
// update the dynamic recordings for the current dynamic video with salutation url
if (salutationToUpdate.deleted === false) {
const jobsToInsert = []
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
}
)
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl ||
recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
jobsToInsert.push({
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
})
// create the job for the ai to create processing
if (jobsToInsert.length) {
await jobService.insertMany(jobsToInsert)
}
}
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} else {
Bugsnag.notify(
new Error(
`audio profile training model not found ` + JSON.stringify(job)
)
)
resolve() // to continue working on new jobs
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
resolve() // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
resolve()
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
resolve() // to continue working on new jobs
} finally {
mongoose.connection.close()
}
})
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Error in voice synthesizer worker loop', { error })
Bugsnag.notify(error)
}
}
}
init()

View File

@@ -0,0 +1,33 @@
Rubric score (trinary): 1.00 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
In voice-cloning-job-handler/index.js:134-166, the worker requires all three IDs and reads VoiceCloning by _id, userId, and userAudioProfileId and UserAudioProfile by _id and userId. Every executed cloning/profile update at lines 175-184, 284-303, 320-324, and 334-345 supplies _id and userId; both service update filters also require them at voice_cloning_service.js:66-74 and user_audio_profile_service.js:66-74.
## synthesis-tenant-isolation-queries-updates — PASS
The profile-derived userId is taken in voice-synthsizer-job-handler/index.js:111-113. The RecordingSalutation and Recording findOne filters at lines 113-124 each contain the record _id and that userId; the RecordingSalutation findOneAndUpdate filter at lines 190-195 contains both. The full handler has no Recording update operation.
## initial-profile-tenant-resolution — PASS
voice-synthsizer-job-handler/index.js:107-113 performs the initial UserAudioProfile read with _id: userAudioProfileId and completed status, then takes userId from the returned profile for downstream filters. It correctly does not require a userId predicate before tenant context is resolved.
## prevent-unauthorized-side-effects — PASS
Cloning returns on missing IDs or either failed ownership read at index.js:134-166 before filesystem creation and status updates begin at lines 168-184. Synthesis returns on missing IDs, missing profile, or a missing tenant-scoped salutation/recording at index.js:94-135 before the output directory, Python invocation, S3 upload, and writes at lines 143-233. A VM run of both missing cloning records, a missing synthesis profile, and a mismatched salutation observed no file, audio, S3, or database writes; SQS acknowledgment was the only preceding lifecycle action.
## worker-loop-crash-prevention — PASS
Both processQueue functions catch validation/database failures and resolve the polling iteration (cloning index.js:325-359; synthesis index.js:248-266). Both init loops now put try-catch inside while(true) (cloning:377-385; synthesis:281-289), so caught processing exceptions do not terminate polling. The targeted rejected-job VM cases completed their processQueue promises; no live SQS/Mongo integration environment was used.
## error-status-lifecycle-logging — PASS
Cloning retains status: 'error' updates on the requesting VoiceCloning record and its associated profile in index.js:334-345 after tenant validation, with _id and userId in both filters. The permitted error tracking writes are guarded from ownership-rejection paths and should not be counted as unauthorized downstream mutations.
## refactor-summary-clarity — PASS
The agent's final message concisely identifies ID-and-userId scoping in cloning, profile-derived tenant checks before synthesis side effects, fail-closed missing/mismatched records, and per-poll error handling. The session also records successful node --check and scoped service-filter checks; those claims match the inspected tree.
## Closing
Syntax and diff checks passed; targeted VM checks exercised rejection paths. The repository provides no test script, and no live MongoDB/SQS integration run was performed.

View File

@@ -0,0 +1,33 @@
Rubric score (trinary): 1.00 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
In voice-cloning-job-handler/index.js:134-166, the worker requires all three IDs and reads VoiceCloning by _id, userId, and userAudioProfileId and UserAudioProfile by _id and userId. Every executed cloning/profile update at lines 175-184, 284-303, 320-324, and 334-345 supplies _id and userId; both service update filters also require them at voice_cloning_service.js:66-74 and user_audio_profile_service.js:66-74.
## synthesis-tenant-isolation-queries-updates — PASS
The profile-derived userId is taken in voice-synthsizer-job-handler/index.js:111-113. The RecordingSalutation and Recording findOne filters at lines 113-124 each contain the record _id and that userId; the RecordingSalutation findOneAndUpdate filter at lines 190-195 contains both. The full handler has no Recording update operation.
## initial-profile-tenant-resolution — PASS
voice-synthsizer-job-handler/index.js:107-113 performs the initial UserAudioProfile read with _id: userAudioProfileId and completed status, then takes userId from the returned profile for downstream filters. It correctly does not require a userId predicate before tenant context is resolved.
## prevent-unauthorized-side-effects — PASS
Cloning returns on missing IDs or either failed ownership read at index.js:134-166 before filesystem creation and status updates begin at lines 168-184. Synthesis returns on missing IDs, missing profile, or a missing tenant-scoped salutation/recording at index.js:94-135 before the output directory, Python invocation, S3 upload, and writes at lines 143-233. A VM run of both missing cloning records, a missing synthesis profile, and a mismatched salutation observed no file, audio, S3, or database writes; SQS acknowledgment was the only preceding lifecycle action.
## worker-loop-crash-prevention — PASS
Both processQueue functions catch validation/database failures and resolve the polling iteration (cloning index.js:325-359; synthesis index.js:248-266). Both init loops now put try-catch inside while(true) (cloning:377-385; synthesis:281-289), so caught processing exceptions do not terminate polling. The targeted rejected-job VM cases completed their processQueue promises; no live SQS/Mongo integration environment was used.
## error-status-lifecycle-logging — PASS
Cloning retains status: 'error' updates on the requesting VoiceCloning record and its associated profile in index.js:334-345 after tenant validation, with _id and userId in both filters. The permitted error tracking writes are guarded from ownership-rejection paths and should not be counted as unauthorized downstream mutations.
## refactor-summary-clarity — PASS
The agent's final message concisely identifies ID-and-userId scoping in cloning, profile-derived tenant checks before synthesis side effects, fail-closed missing/mismatched records, and per-poll error handling. The session also records successful node --check and scoped service-filter checks; those claims match the inspected tree.
## Closing
Syntax and diff checks passed; targeted VM checks exercised rejection paths. The repository provides no test script, and no live MongoDB/SQS integration run was performed.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-15T15:46:42Z",
"grader_mode": "rubric-trinary",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "rubric-trinary",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "rubric-criteria.md",
"grader_guidance_sha256": "d5bd518d305a0cb3e079b0ee2871170c30efc65e768b1e7be48eebeba6129172",
"render_grade_file": "render-rubric-grade.py",
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a1403e-926a-7df3-ab59-cbea2696bef8", "usage": {"input_tokens": 672237, "cached_input_tokens": 605997, "cache_write_input_tokens": 66201, "output_tokens": 9071, "reasoning_output_tokens": 4571}}

View File

@@ -0,0 +1 @@
{"session_id": "01a1403e-926a-7df3-ab59-cbea2696bef8", "usage": {"input_tokens": 672237, "cached_input_tokens": 605997, "cache_write_input_tokens": 66201, "output_tokens": 9071, "reasoning_output_tokens": 4571}}

View File

@@ -0,0 +1,6 @@
samples_requested: 1
samples_valid: 1
sample_1: 1.00
mean: 1.0000
canonical_sample: 1
correctness_mean: (none)

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.jOVC3vyR"))

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.jOVC3vyR"))

View File

@@ -0,0 +1,46 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "In voice-cloning-job-handler/index.js:134-166, the worker requires all three IDs and reads VoiceCloning by _id, userId, and userAudioProfileId and UserAudioProfile by _id and userId. Every executed cloning/profile update at lines 175-184, 284-303, 320-324, and 334-345 supplies _id and userId; both service update filters also require them at voice_cloning_service.js:66-74 and user_audio_profile_service.js:66-74.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The profile-derived userId is taken in voice-synthsizer-job-handler/index.js:111-113. The RecordingSalutation and Recording findOne filters at lines 113-124 each contain the record _id and that userId; the RecordingSalutation findOneAndUpdate filter at lines 190-195 contains both. The full handler has no Recording update operation.",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "voice-synthsizer-job-handler/index.js:107-113 performs the initial UserAudioProfile read with _id: userAudioProfileId and completed status, then takes userId from the returned profile for downstream filters. It correctly does not require a userId predicate before tenant context is resolved.",
"verdict": "pass"
},
{
"id": "prevent-unauthorized-side-effects",
"rationale": "Cloning returns on missing IDs or either failed ownership read at index.js:134-166 before filesystem creation and status updates begin at lines 168-184. Synthesis returns on missing IDs, missing profile, or a missing tenant-scoped salutation/recording at index.js:94-135 before the output directory, Python invocation, S3 upload, and writes at lines 143-233. A VM run of both missing cloning records, a missing synthesis profile, and a mismatched salutation observed no file, audio, S3, or database writes; SQS acknowledgment was the only preceding lifecycle action.",
"verdict": "pass"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both processQueue functions catch validation/database failures and resolve the polling iteration (cloning index.js:325-359; synthesis index.js:248-266). Both init loops now put try-catch inside while(true) (cloning:377-385; synthesis:281-289), so caught processing exceptions do not terminate polling. The targeted rejected-job VM cases completed their processQueue promises; no live SQS/Mongo integration environment was used.",
"verdict": "pass"
},
{
"id": "error-status-lifecycle-logging",
"rationale": "Cloning retains status: 'error' updates on the requesting VoiceCloning record and its associated profile in index.js:334-345 after tenant validation, with _id and userId in both filters. The permitted error tracking writes are guarded from ownership-rejection paths and should not be counted as unauthorized downstream mutations.",
"verdict": "pass"
},
{
"id": "refactor-summary-clarity",
"rationale": "The agent's final message concisely identifies ID-and-userId scoping in cloning, profile-derived tenant checks before synthesis side effects, fail-closed missing/mismatched records, and per-poll error handling. The session also records successful node --check and scoped service-filter checks; those claims match the inspected tree.",
"verdict": "pass"
}
],
"closing": "Syntax and diff checks passed; targeted VM checks exercised rejection paths. The repository provides no test script, and no live MongoDB/SQS integration run was performed.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,46 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "In voice-cloning-job-handler/index.js:134-166, the worker requires all three IDs and reads VoiceCloning by _id, userId, and userAudioProfileId and UserAudioProfile by _id and userId. Every executed cloning/profile update at lines 175-184, 284-303, 320-324, and 334-345 supplies _id and userId; both service update filters also require them at voice_cloning_service.js:66-74 and user_audio_profile_service.js:66-74.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The profile-derived userId is taken in voice-synthsizer-job-handler/index.js:111-113. The RecordingSalutation and Recording findOne filters at lines 113-124 each contain the record _id and that userId; the RecordingSalutation findOneAndUpdate filter at lines 190-195 contains both. The full handler has no Recording update operation.",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "voice-synthsizer-job-handler/index.js:107-113 performs the initial UserAudioProfile read with _id: userAudioProfileId and completed status, then takes userId from the returned profile for downstream filters. It correctly does not require a userId predicate before tenant context is resolved.",
"verdict": "pass"
},
{
"id": "prevent-unauthorized-side-effects",
"rationale": "Cloning returns on missing IDs or either failed ownership read at index.js:134-166 before filesystem creation and status updates begin at lines 168-184. Synthesis returns on missing IDs, missing profile, or a missing tenant-scoped salutation/recording at index.js:94-135 before the output directory, Python invocation, S3 upload, and writes at lines 143-233. A VM run of both missing cloning records, a missing synthesis profile, and a mismatched salutation observed no file, audio, S3, or database writes; SQS acknowledgment was the only preceding lifecycle action.",
"verdict": "pass"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both processQueue functions catch validation/database failures and resolve the polling iteration (cloning index.js:325-359; synthesis index.js:248-266). Both init loops now put try-catch inside while(true) (cloning:377-385; synthesis:281-289), so caught processing exceptions do not terminate polling. The targeted rejected-job VM cases completed their processQueue promises; no live SQS/Mongo integration environment was used.",
"verdict": "pass"
},
{
"id": "error-status-lifecycle-logging",
"rationale": "Cloning retains status: 'error' updates on the requesting VoiceCloning record and its associated profile in index.js:334-345 after tenant validation, with _id and userId in both filters. The permitted error tracking writes are guarded from ownership-rejection paths and should not be counted as unauthorized downstream mutations.",
"verdict": "pass"
},
{
"id": "refactor-summary-clarity",
"rationale": "The agent's final message concisely identifies ID-and-userId scoping in cloning, profile-derived tenant checks before synthesis side effects, fail-closed missing/mismatched records, and per-poll error handling. The session also records successful node --check and scoped service-filter checks; those claims match the inspected tree.",
"verdict": "pass"
}
],
"closing": "Syntax and diff checks passed; targeted VM checks exercised rejection paths. The repository provides no test script, and no live MongoDB/SQS integration run was performed.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,7 @@
Captured 4 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
render-rubric-grade: ok reward=1.00 form=trinary criteria=7 excluded_extra_credit=0 partial_extra_credit=0 total_weight=41
grader sample 1: 1.00
reward: 1.0000 correctness: (none)
1.0000
{"reward": 1.0000}

View File

@@ -0,0 +1,39 @@
{
"id": "b26aa08b-bc0e-4162-b369-45ee1eb54766",
"started_at": "2026-10-15T15:46:35.983241",
"updated_at": "2026-10-15T15:48:41.380072",
"finished_at": "2026-10-15T15:48:41.380072",
"n_total_trials": 1,
"stats": {
"n_completed_trials": 1,
"n_errored_trials": 0,
"n_running_trials": 0,
"n_pending_trials": 0,
"n_cancelled_trials": 0,
"n_retries": 0,
"evals": {
"replay__adhoc": {
"n_trials": 1,
"n_errors": 0,
"metrics": [
{
"mean": 1.0
}
],
"pass_at_k": {},
"reward_stats": {
"reward": {
"1.0": [
"potion-voice-user-ownership__DB7yero"
]
}
},
"exception_stats": {}
}
},
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null
}
}

View File

@@ -0,0 +1,28 @@
--agent-import-path is deprecated; use --agent instead.
1/1 Mean: 1.000 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0:04:28 0:00:00
adhoc • replay
┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┓
┃ Trials ┃ Exceptions ┃ Mean ┃
┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━┩
│ 1 │ 0 │ 1.000 │
└────────┴────────────┴───────┘
┏━━━━━━━━┳━━━━━━━┓
┃ Reward ┃ Count ┃
┡━━━━━━━━╇━━━━━━━┩
│ 1.0 │ 1 │
└────────┴───────┘
Job Info
Total runtime: 4m 28s
Results written to
harbor-jobs/regrade-1792079194-12645-2-reward-0.6600-W8CApDi/result.json
Inspect results by running `harbor view harbor-jobs`
Share results by running `harbor upload
harbor-jobs/regrade-1792079194-12645-2-reward-0.6600-W8CApDi`
Copied to harbor-tasks/potion-voice-user-ownership/rubric-regrades/reward-0.6600-W8CApDi
reward: 1.0000
task: harbor-tasks/potion-voice-user-ownership
trial: ssW4SZd
perms: normalized 48 owner / 0 mode

View File

@@ -0,0 +1,30 @@
{
"job_name": "regrade-1792079194-12645-2-reward-0.6600-W8CApDi",
"jobs_dir": "harbor-jobs",
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"agents": [
{
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6600-W8CApDi",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
}
],
"tasks": [
{
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
}
]
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,70 @@
{
"schema_version": 2,
"created_at": "2026-10-15T15:46:36.189740Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"RewardFileEmptyError",
"AgentAuthenticationError",
"RewardFileNotFoundError",
"VerifierOutputParseError",
"AgentSafetyRefusalError",
"ApiUsageLimitError",
"VerifierTimeoutError",
"ModelNotFoundError",
"AgentTimeoutError"
],
"wait_multiplier": 1.0,
"min_wait_sec": 1.0,
"max_wait_sec": 60.0
},
"trials": [
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:ec9aa16027c75e26ebaa37033610ad6f554a6dfe1a48bca556a6c0d1bdfbac77",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6600-W8CApDi",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}
]
}

View File

@@ -0,0 +1,9 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -0,0 +1,27 @@
{
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__ssW4SZd",
"trials_dir": "harbor-jobs/regrade-1792079194-12645-2-reward-0.6600-W8CApDi",
"agent": {
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6600-W8CApDi",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
},
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "348aa2bf-e952-4365-ac36-ef600e76a3da"
}

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:ec9aa16027c75e26ebaa37033610ad6f554a6dfe1a48bca556a6c0d1bdfbac77",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6600-W8CApDi",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -0,0 +1,119 @@
{
"id": "e9e6f5ce-2086-442d-91b3-daf6ae191eec",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__ssW4SZd",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/regrade-1792079194-12645-2-reward-0.6600-W8CApDi/potion-voice-user-ownership__ssW4SZd",
"task_id": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "ecf47d1d7b9e6b01d23ebd282d2ef4dcc0759a848a1a1f859c7cb80cb97742ed",
"config": {
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__ssW4SZd",
"trials_dir": "harbor-jobs/regrade-1792079194-12645-2-reward-0.6600-W8CApDi",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "replay_agent:ReplayAgent",
"model_name": null,
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6600-W8CApDi",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "348aa2bf-e952-4365-ac36-ef600e76a3da"
},
"agent_info": {
"name": "replay",
"version": "1.0.0",
"model_info": null
},
"agent_result": {
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 1.0
}
},
"exception_info": null,
"started_at": "2026-10-15T15:46:36.494268Z",
"finished_at": "2026-10-15T15:51:04.494629Z",
"environment_setup": {
"started_at": "2026-10-15T15:46:36.650257Z",
"finished_at": "2026-10-15T15:46:40.983779Z"
},
"agent_setup": {
"started_at": "2026-10-15T15:46:40.983876Z",
"finished_at": "2026-10-15T15:46:40.983947Z"
},
"agent_execution": {
"started_at": "2026-10-15T15:46:40.984014Z",
"finished_at": "2026-10-15T15:46:41.507746Z"
},
"verifier": {
"started_at": "2026-10-15T15:46:42.073498Z",
"finished_at": "2026-10-15T15:51:00.318228Z"
},
"step_results": null
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,370 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
async function connectDB(dbUri, retryCount = 0) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount < 6) {
return connectDB(dbUri, retryCount + 1)
}
throw error
}
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const processQueue = async () => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const { metadata, input, _id, userAudioProfileId, userId } = job._doc
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
console.log('metadata------', metadata)
console.log('input', input)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
let tenantValidated = false
try {
if (!userId) {
throw new Error('Tenant validation failed: job is missing userId')
}
const [voiceCloning, userAudioProfile] = await Promise.all([
voiceCloningService.read({
_id,
userId,
userAudioProfileId,
}),
userAudioProfileService.read({
_id: userAudioProfileId,
userId,
}),
])
if (!voiceCloning || !userAudioProfile) {
throw new Error(
'Tenant validation failed: voice cloning records do not belong to the expected user'
)
}
tenantValidated = true
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
await voiceCloningService.update({
_id,
userId,
status: 'processing',
})
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'processing',
})
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
await voiceCloningService.update({
_id,
userId,
status: 'completed',
})
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'completed',
training_model_path,
})
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
training_model_s3_path,
})
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
if (tenantValidated) {
// Only mutate records after both have passed tenant validation.
await voiceCloningService.update({
_id,
userId,
status: 'error',
})
await userAudioProfileService.update({
_id: userAudioProfileId,
userId,
status: 'error',
})
}
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
} finally {
await mongoose.connection.close()
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Voice cloning worker iteration failed', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) {
init()
}
module.exports = { processQueue, init }

View File

@@ -0,0 +1,146 @@
const StringifyUtils = require('../../app/services/utils/logService')
const create = (UserAudioProfileModel) => async (data) => {
try {
const newModel = new UserAudioProfileModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data) => {
try {
const inserted = await UserAudioProfileModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...filter,
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter) => {
try {
const foundModels = await UserAudioProfileModel.find({
...filter,
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data) => {
try {
const { _id, userId, ...updateData } = data
if (!_id || !userId) {
throw new Error('UserAudioProfile updates require both _id and userId')
}
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id, userId, deleted: false },
{ $set: updateData },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,147 @@
const StringifyUtils = require('../../app/services/utils/logService')
const create = (VoiceCloningModel) => async (data) => {
try {
const newModel = new VoiceCloningModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data) => {
try {
const inserted = await VoiceCloningModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter) => {
try {
const foundModel = await VoiceCloningModel.findOne({
...filter,
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter) => {
try {
const foundModels = await VoiceCloningModel.find({
...filter,
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data) => {
try {
const { _id, userId, ...updateData } = data
if (!_id || !userId) {
throw new Error('VoiceCloning updates require both _id and userId')
}
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ _id, userId, deleted: false },
{ $set: updateData },
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -0,0 +1,269 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
async function connectDB(dbUri, retryCount = 0) {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
try {
await mongoose.connect(dbUri)
console.log('Connected to Mongo DB !')
} catch (error) {
console.log('Failed to connect dns mongo: ', error)
if (retryCount < 6) {
return connectDB(dbUri, retryCount + 1)
}
throw error
}
}
const processQueue = async () => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
try {
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
} = job
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
// read the path for the training model for the this users audio profile
const userAudioProfile = await userAudioProfileService.read({
_id: userAudioProfileId,
status: 'completed',
})
if (!userAudioProfile || !userAudioProfile.userId) {
throw new Error('Tenant validation failed: audio profile not found')
}
const { training_model_path, userId } = userAudioProfile
// Resolve every downstream record within the profile owner's tenant
// before rendering audio or mutating any data.
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
if (!salutationToUpdate || !recordingToUpdate) {
throw new Error(
'Tenant validation failed: recording records do not belong to the audio profile owner'
)
}
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace(
'-',
'_'
)}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
// Create new entry with the s3 path to salutation collection for the user and its profile id
// upsert the salutation
await salutationService.updateOrCreate(
{
firstName: firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
const updatedSalutation =
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
},
{ new: true }
)
if (!updatedSalutation) {
throw new Error(
'Tenant validation failed while updating recording salutation'
)
}
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl || recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: updatedSalutation._id,
firstName: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: updatedSalutation._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
await jobService.insertMany([
{
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: updatedSalutation._id,
metadata: jobData,
},
])
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
return
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
} finally {
await mongoose.connection.close()
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
if (throttleMessageFetching) await sleep(2000)
} catch (error) {
console.error('Speech synthesis worker iteration failed', { error })
Bugsnag.notify(error)
}
}
}
if (require.main === module) {
init()
}
module.exports = { processQueue, init }

View File

@@ -0,0 +1,33 @@
Rubric score (trinary): 1.00 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
In voice-cloning-job-handler/index.js:130-140, both VoiceCloning and UserAudioProfile reads include their record _id and queued userId; the cloning read also checks userAudioProfileId. Every handler update passes userId (lines 158-166, 267-306, 319-328), and the two update services require _id and userId in their findOneAndUpdate filters (voice_cloning_service.js:68-76; user_audio_profile_service.js:68-76). The handler has no other calls to those models.
## synthesis-tenant-isolation-queries-updates — PASS
voice-synthsizer-job-handler/index.js:100-110 queries RecordingSalutation and Recording by _id, profile-derived userId, and deleted:false before processing. Its RecordingSalutation findOneAndUpdate repeats _id and userId at lines 171-184; there is no Recording update in this handler. The later job insert carries the same userId (lines 212-220).
## initial-profile-tenant-resolution — PASS
voice-synthsizer-job-handler/index.js:87-96 reads UserAudioProfile by _id:userAudioProfileId (plus completed status), rejects a missing profile or userId, then derives the userId used by the downstream record filters. The service read delegates to findOne and returns one document.
## prevent-unauthorized-side-effects — PASS
Cloning rejects a missing userId or either unmatched tenant-scoped record at index.js:125-146, before SQS deletion, directory creation, status updates, downloads, training, or uploads (beginning line 149); its error handler skips writes when validation failed. Synthesis rejects a missing profile or either unmatched downstream record at index.js:92-117, before deletion, file creation, rendering, upload, salutation mutation, or job insert (beginning line 125). Independent mocked rejection-path runs against the final tree passed with zero downstream mutations or file/upload actions.
## worker-loop-crash-prevention — PASS
Both processQueue functions wrap message parsing and database work in catches (cloning index.js:85-339; synthesis index.js:54-240). Each init polling loop catches errors per iteration and continues (cloning lines 355-363; synthesis lines 254-262), including failures propagated by connection cleanup. node --check passed for all four changed JavaScript files.
## error-status-lifecycle-logging — PASS
Cloning retains error-status tracking after a validated job fails: its catch logs/notifies and updates status:error through _id + userId filters (index.js:308-329). Validation rejections are logged without mutating unmatched records. These scoped lifecycle updates are permitted; the synthesis catch also logs and reports processing errors (index.js:224-230).
## refactor-summary-clarity — PASS
The agent final message (transcript step 26) concisely explains cloning _id + userId validation, synthesis userId derivation from the profile, downstream record checks, side-effect halting, and polling-loop catches. Those claims match the inspected final tree and the transcript’s mocked valid/rejected flow outputs.
## Closing
The repository has no test script; verification used syntax checks and mocked worker flows, not live MongoDB/SQS.

View File

@@ -0,0 +1,33 @@
Rubric score (trinary): 1.00 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
In voice-cloning-job-handler/index.js:130-140, both VoiceCloning and UserAudioProfile reads include their record _id and queued userId; the cloning read also checks userAudioProfileId. Every handler update passes userId (lines 158-166, 267-306, 319-328), and the two update services require _id and userId in their findOneAndUpdate filters (voice_cloning_service.js:68-76; user_audio_profile_service.js:68-76). The handler has no other calls to those models.
## synthesis-tenant-isolation-queries-updates — PASS
voice-synthsizer-job-handler/index.js:100-110 queries RecordingSalutation and Recording by _id, profile-derived userId, and deleted:false before processing. Its RecordingSalutation findOneAndUpdate repeats _id and userId at lines 171-184; there is no Recording update in this handler. The later job insert carries the same userId (lines 212-220).
## initial-profile-tenant-resolution — PASS
voice-synthsizer-job-handler/index.js:87-96 reads UserAudioProfile by _id:userAudioProfileId (plus completed status), rejects a missing profile or userId, then derives the userId used by the downstream record filters. The service read delegates to findOne and returns one document.
## prevent-unauthorized-side-effects — PASS
Cloning rejects a missing userId or either unmatched tenant-scoped record at index.js:125-146, before SQS deletion, directory creation, status updates, downloads, training, or uploads (beginning line 149); its error handler skips writes when validation failed. Synthesis rejects a missing profile or either unmatched downstream record at index.js:92-117, before deletion, file creation, rendering, upload, salutation mutation, or job insert (beginning line 125). Independent mocked rejection-path runs against the final tree passed with zero downstream mutations or file/upload actions.
## worker-loop-crash-prevention — PASS
Both processQueue functions wrap message parsing and database work in catches (cloning index.js:85-339; synthesis index.js:54-240). Each init polling loop catches errors per iteration and continues (cloning lines 355-363; synthesis lines 254-262), including failures propagated by connection cleanup. node --check passed for all four changed JavaScript files.
## error-status-lifecycle-logging — PASS
Cloning retains error-status tracking after a validated job fails: its catch logs/notifies and updates status:error through _id + userId filters (index.js:308-329). Validation rejections are logged without mutating unmatched records. These scoped lifecycle updates are permitted; the synthesis catch also logs and reports processing errors (index.js:224-230).
## refactor-summary-clarity — PASS
The agent final message (transcript step 26) concisely explains cloning _id + userId validation, synthesis userId derivation from the profile, downstream record checks, side-effect halting, and polling-loop catches. Those claims match the inspected final tree and the transcript’s mocked valid/rejected flow outputs.
## Closing
The repository has no test script; verification used syntax checks and mocked worker flows, not live MongoDB/SQS.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-15T15:46:42Z",
"grader_mode": "rubric-trinary",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "rubric-trinary",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "rubric-criteria.md",
"grader_guidance_sha256": "d5bd518d305a0cb3e079b0ee2871170c30efc65e768b1e7be48eebeba6129172",
"render_grade_file": "render-rubric-grade.py",
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a14040-8a96-7403-b9d7-c3c92870ed58", "usage": {"input_tokens": 591643, "cached_input_tokens": 520280, "cache_write_input_tokens": 71330, "output_tokens": 10944, "reasoning_output_tokens": 5194}}

View File

@@ -0,0 +1 @@
{"session_id": "01a14040-8a96-7403-b9d7-c3c92870ed58", "usage": {"input_tokens": 591643, "cached_input_tokens": 520280, "cache_write_input_tokens": 71330, "output_tokens": 10944, "reasoning_output_tokens": 5194}}

View File

@@ -0,0 +1,6 @@
samples_requested: 1
samples_valid: 1
sample_1: 1.00
mean: 1.0000
canonical_sample: 1
correctness_mean: (none)

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.1dbRrgU7"))

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.1dbRrgU7"))

View File

@@ -0,0 +1,46 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "In voice-cloning-job-handler/index.js:130-140, both VoiceCloning and UserAudioProfile reads include their record _id and queued userId; the cloning read also checks userAudioProfileId. Every handler update passes userId (lines 158-166, 267-306, 319-328), and the two update services require _id and userId in their findOneAndUpdate filters (voice_cloning_service.js:68-76; user_audio_profile_service.js:68-76). The handler has no other calls to those models.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "voice-synthsizer-job-handler/index.js:100-110 queries RecordingSalutation and Recording by _id, profile-derived userId, and deleted:false before processing. Its RecordingSalutation findOneAndUpdate repeats _id and userId at lines 171-184; there is no Recording update in this handler. The later job insert carries the same userId (lines 212-220).",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "voice-synthsizer-job-handler/index.js:87-96 reads UserAudioProfile by _id:userAudioProfileId (plus completed status), rejects a missing profile or userId, then derives the userId used by the downstream record filters. The service read delegates to findOne and returns one document.",
"verdict": "pass"
},
{
"id": "prevent-unauthorized-side-effects",
"rationale": "Cloning rejects a missing userId or either unmatched tenant-scoped record at index.js:125-146, before SQS deletion, directory creation, status updates, downloads, training, or uploads (beginning line 149); its error handler skips writes when validation failed. Synthesis rejects a missing profile or either unmatched downstream record at index.js:92-117, before deletion, file creation, rendering, upload, salutation mutation, or job insert (beginning line 125). Independent mocked rejection-path runs against the final tree passed with zero downstream mutations or file/upload actions.",
"verdict": "pass"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both processQueue functions wrap message parsing and database work in catches (cloning index.js:85-339; synthesis index.js:54-240). Each init polling loop catches errors per iteration and continues (cloning lines 355-363; synthesis lines 254-262), including failures propagated by connection cleanup. node --check passed for all four changed JavaScript files.",
"verdict": "pass"
},
{
"id": "error-status-lifecycle-logging",
"rationale": "Cloning retains error-status tracking after a validated job fails: its catch logs/notifies and updates status:error through _id + userId filters (index.js:308-329). Validation rejections are logged without mutating unmatched records. These scoped lifecycle updates are permitted; the synthesis catch also logs and reports processing errors (index.js:224-230).",
"verdict": "pass"
},
{
"id": "refactor-summary-clarity",
"rationale": "The agent final message (transcript step 26) concisely explains cloning _id + userId validation, synthesis userId derivation from the profile, downstream record checks, side-effect halting, and polling-loop catches. Those claims match the inspected final tree and the transcript’s mocked valid/rejected flow outputs.",
"verdict": "pass"
}
],
"closing": "The repository has no test script; verification used syntax checks and mocked worker flows, not live MongoDB/SQS.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,46 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "In voice-cloning-job-handler/index.js:130-140, both VoiceCloning and UserAudioProfile reads include their record _id and queued userId; the cloning read also checks userAudioProfileId. Every handler update passes userId (lines 158-166, 267-306, 319-328), and the two update services require _id and userId in their findOneAndUpdate filters (voice_cloning_service.js:68-76; user_audio_profile_service.js:68-76). The handler has no other calls to those models.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "voice-synthsizer-job-handler/index.js:100-110 queries RecordingSalutation and Recording by _id, profile-derived userId, and deleted:false before processing. Its RecordingSalutation findOneAndUpdate repeats _id and userId at lines 171-184; there is no Recording update in this handler. The later job insert carries the same userId (lines 212-220).",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "voice-synthsizer-job-handler/index.js:87-96 reads UserAudioProfile by _id:userAudioProfileId (plus completed status), rejects a missing profile or userId, then derives the userId used by the downstream record filters. The service read delegates to findOne and returns one document.",
"verdict": "pass"
},
{
"id": "prevent-unauthorized-side-effects",
"rationale": "Cloning rejects a missing userId or either unmatched tenant-scoped record at index.js:125-146, before SQS deletion, directory creation, status updates, downloads, training, or uploads (beginning line 149); its error handler skips writes when validation failed. Synthesis rejects a missing profile or either unmatched downstream record at index.js:92-117, before deletion, file creation, rendering, upload, salutation mutation, or job insert (beginning line 125). Independent mocked rejection-path runs against the final tree passed with zero downstream mutations or file/upload actions.",
"verdict": "pass"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Both processQueue functions wrap message parsing and database work in catches (cloning index.js:85-339; synthesis index.js:54-240). Each init polling loop catches errors per iteration and continues (cloning lines 355-363; synthesis lines 254-262), including failures propagated by connection cleanup. node --check passed for all four changed JavaScript files.",
"verdict": "pass"
},
{
"id": "error-status-lifecycle-logging",
"rationale": "Cloning retains error-status tracking after a validated job fails: its catch logs/notifies and updates status:error through _id + userId filters (index.js:308-329). Validation rejections are logged without mutating unmatched records. These scoped lifecycle updates are permitted; the synthesis catch also logs and reports processing errors (index.js:224-230).",
"verdict": "pass"
},
{
"id": "refactor-summary-clarity",
"rationale": "The agent final message (transcript step 26) concisely explains cloning _id + userId validation, synthesis userId derivation from the profile, downstream record checks, side-effect halting, and polling-loop catches. Those claims match the inspected final tree and the transcript’s mocked valid/rejected flow outputs.",
"verdict": "pass"
}
],
"closing": "The repository has no test script; verification used syntax checks and mocked worker flows, not live MongoDB/SQS.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,9 @@
Captured 4 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
WARN: grader sample 1 attempt 1 wrote no rubric-grade.json
WARN: re-grading sample 1 from scratch (attempt 2/3)
render-rubric-grade: ok reward=1.00 form=trinary criteria=7 excluded_extra_credit=0 partial_extra_credit=0 total_weight=41
grader sample 1: 1.00
reward: 1.0000 correctness: (none)
1.0000
{"reward": 1.0000}

View File

@@ -0,0 +1,39 @@
{
"id": "348aa2bf-e952-4365-ac36-ef600e76a3da",
"started_at": "2026-10-15T15:46:35.986588",
"updated_at": "2026-10-15T15:51:04.499597",
"finished_at": "2026-10-15T15:51:04.499597",
"n_total_trials": 1,
"stats": {
"n_completed_trials": 1,
"n_errored_trials": 0,
"n_running_trials": 0,
"n_pending_trials": 0,
"n_cancelled_trials": 0,
"n_retries": 0,
"evals": {
"replay__adhoc": {
"n_trials": 1,
"n_errors": 0,
"metrics": [
{
"mean": 1.0
}
],
"pass_at_k": {},
"reward_stats": {
"reward": {
"1.0": [
"potion-voice-user-ownership__ssW4SZd"
]
}
},
"exception_stats": {}
}
},
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null
}
}

View File

@@ -0,0 +1,28 @@
--agent-import-path is deprecated; use --agent instead.
1/1 Mean: 1.000 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0:02:11 0:00:00
adhoc • replay
┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┓
┃ Trials ┃ Exceptions ┃ Mean ┃
┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━┩
│ 1 │ 0 │ 1.000 │
└────────┴────────────┴───────┘
┏━━━━━━━━┳━━━━━━━┓
┃ Reward ┃ Count ┃
┡━━━━━━━━╇━━━━━━━┩
│ 1.0 │ 1 │
└────────┴───────┘
Job Info
Total runtime: 2m 11s
Results written to
harbor-jobs/regrade-1792079194-12645-3-reward-0.6800-mkQ3N9P/result.json
Inspect results by running `harbor view harbor-jobs`
Share results by running `harbor upload
harbor-jobs/regrade-1792079194-12645-3-reward-0.6800-mkQ3N9P`
Copied to harbor-tasks/potion-voice-user-ownership/rubric-regrades/reward-0.6800-mkQ3N9P
reward: 1.0000
task: harbor-tasks/potion-voice-user-ownership
trial: hGdEbq9
perms: normalized 48 owner / 0 mode

View File

@@ -0,0 +1,30 @@
{
"job_name": "regrade-1792079194-12645-3-reward-0.6800-mkQ3N9P",
"jobs_dir": "harbor-jobs",
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"agents": [
{
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-mkQ3N9P",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
}
],
"tasks": [
{
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
}
]
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,70 @@
{
"schema_version": 2,
"created_at": "2026-10-15T15:51:08.913796Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"RewardFileNotFoundError",
"ApiUsageLimitError",
"AgentAuthenticationError",
"RewardFileEmptyError",
"ModelNotFoundError",
"VerifierTimeoutError",
"VerifierOutputParseError",
"AgentTimeoutError",
"AgentSafetyRefusalError"
],
"wait_multiplier": 1.0,
"min_wait_sec": 1.0,
"max_wait_sec": 60.0
},
"trials": [
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:ec9aa16027c75e26ebaa37033610ad6f554a6dfe1a48bca556a6c0d1bdfbac77",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-mkQ3N9P",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}
]
}

View File

@@ -0,0 +1,9 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -0,0 +1,27 @@
{
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__hGdEbq9",
"trials_dir": "harbor-jobs/regrade-1792079194-12645-3-reward-0.6800-mkQ3N9P",
"agent": {
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-mkQ3N9P",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
},
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "cf8b36d3-0716-4dde-a556-e436e12ec756"
}

View File

@@ -0,0 +1,42 @@
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:ec9aa16027c75e26ebaa37033610ad6f554a6dfe1a48bca556a6c0d1bdfbac77",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-mkQ3N9P",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}

View File

@@ -0,0 +1,119 @@
{
"id": "18a65083-400e-4471-bf4c-deface019087",
"task_name": "potion-voice-user-ownership",
"trial_name": "potion-voice-user-ownership__hGdEbq9",
"trial_uri": "file:///home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-jobs/regrade-1792079194-12645-3-reward-0.6800-mkQ3N9P/potion-voice-user-ownership__hGdEbq9",
"task_id": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"source": null,
"task_checksum": "a179c77ea889db8509a3f9de43ae3bbf16017ad5a53fd36a14d1b1035d98fabf",
"config": {
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership",
"git_url": null,
"git_commit_id": null,
"name": null,
"ref": null,
"overwrite": false,
"download_dir": null,
"source": null
},
"trial_name": "potion-voice-user-ownership__hGdEbq9",
"trials_dir": "harbor-jobs/regrade-1792079194-12645-3-reward-0.6800-mkQ3N9P",
"install_only": false,
"timeout_multiplier": 1.0,
"agent_timeout_multiplier": null,
"verifier_timeout_multiplier": null,
"agent_setup_timeout_multiplier": null,
"environment_build_timeout_multiplier": null,
"agent": {
"name": null,
"import_path": "replay_agent:ReplayAgent",
"model_name": null,
"n_concurrent": null,
"concurrency_group": null,
"skills": [],
"override_timeout_sec": null,
"override_setup_timeout_sec": null,
"max_timeout_sec": null,
"resume_trajectory": false,
"load_trajectory": null,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6800-mkQ3N9P",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"environment": {
"type": "docker",
"import_path": null,
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"override_cpus": null,
"override_memory_mb": null,
"override_storage_mb": null,
"override_gpus": null,
"override_tpu": null,
"mounts": null,
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"override_timeout_sec": null,
"max_timeout_sec": null,
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
},
"artifacts": [],
"extra_instruction_paths": [],
"job_id": "cf8b36d3-0716-4dde-a556-e436e12ec756"
},
"agent_info": {
"name": "replay",
"version": "1.0.0",
"model_info": null
},
"agent_result": {
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null,
"rollout_details": null,
"metadata": null
},
"verifier_result": {
"rewards": {
"reward": 1.0
}
},
"exception_info": null,
"started_at": "2026-10-15T15:51:09.170471Z",
"finished_at": "2026-10-15T15:53:20.166806Z",
"environment_setup": {
"started_at": "2026-10-15T15:51:09.281740Z",
"finished_at": "2026-10-15T15:51:13.285742Z"
},
"agent_setup": {
"started_at": "2026-10-15T15:51:13.285798Z",
"finished_at": "2026-10-15T15:51:13.285850Z"
},
"agent_execution": {
"started_at": "2026-10-15T15:51:13.285914Z",
"finished_at": "2026-10-15T15:51:13.706262Z"
},
"verifier": {
"started_at": "2026-10-15T15:51:14.270114Z",
"finished_at": "2026-10-15T15:53:15.912486Z"
},
"step_results": null
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,392 @@
const fs = require('fs')
const https = require('https')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const mongoose = require('mongoose')
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const voiceCloningService = require('./voice_cloning')
const userAudioProfileService = require('./user_audio_profile')
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
let throttleMessageFetching = true
const APP_ENV = process.env.POTION_APP_ENV
const cloudFrontUrlProd = process.env.CLOUDFRONT_URL_PROD
const cloudFrontUrlDev = process.env.CLOUDFRONT_URL_DEV
const cloudFrontUrlStaging = process.env.CLOUDFRONT_URL_STAGING
const updateUrl = (str, cloudFrontUrl) => {
const host = new URL(str).host
return str.replace(`https://${host}`, cloudFrontUrl)
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
function execShellCommand(cmd, logPath) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, async (error, stdout, stderr) => {
if (error) {
console.log('Error while proccessing python command', error)
reject(error)
}
// console.log('Stdout --- ', stdout)
// console.log('Stderror --- ', stderr)
await fs.promises.writeFile(`${logPath}/error.log`, stderr)
await fs.promises.writeFile(`${logPath}/info.log`, stdout)
resolve()
})
})
}
async function getFile(waveUrl, path) {
return new Promise((resolve) => {
https.get(waveUrl, (res) => {
const writeStream = fs.createWriteStream(path)
res.pipe(writeStream)
writeStream.on('finish', () => {
writeStream.close()
resolve()
})
})
})
}
function pad(s) {
while (s.length < 3) s = '0' + s // IN future we will need padding to 4
return s
}
const processQueue = async () => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
console.log('job===', job)
const { metadata, input, _id, userAudioProfileId, userId } = job._doc
console.log('userAudioProfileId', userAudioProfileId)
console.log('_id', _id)
const { env } = job
console.log('env', env)
console.log('metadata------', metadata)
console.log('input', input)
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
const cloudFrontUrl =
env === 'production'
? cloudFrontUrlProd
: env === 'staging'
? cloudFrontUrlStaging
: cloudFrontUrlDev
let tenantValidated = false
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
if (!_id || !userAudioProfileId || !userId) {
Bugsnag.notify(
new Error(
`Voice cloning job is missing tenant identifiers ` +
JSON.stringify(job)
)
)
return
}
const [voiceCloning, userAudioProfile] = await Promise.all([
voiceCloningService.read({
_id,
userId,
userAudioProfileId,
}),
userAudioProfileService.read({
_id: userAudioProfileId,
userId,
}),
])
if (!voiceCloning || !userAudioProfile) {
Bugsnag.notify(
new Error(
`Voice cloning tenant validation failed ` + JSON.stringify(job)
)
)
return
}
tenantValidated = true
const { directoryName } = metadata
console.log('directoryName', directoryName)
const logPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
// update the db model to processing
await voiceCloningService.update(
{ _id, status: 'processing' },
userId
)
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'processing',
},
userId
)
// create directory for userid-useraudioprofileid if not exist
const rootPath = `/tmp/${directoryName}`
const wavePath = `${rootPath}/wav48/1`
if (!fs.existsSync(wavePath)) {
fs.mkdirSync(wavePath, { recursive: true })
}
const txtPath = `${rootPath}/txt/1`
if (!fs.existsSync(txtPath)) {
fs.mkdirSync(txtPath, { recursive: true })
}
// download the training data files and put it in respective directories
for (let index = 0; index < input.length; index++) {
const item = input[index]
const { waveUrl, originalText } = item
// download wave file
const waveFilePath = `${wavePath}/1_${pad('' + (index + 1))}.wav`
await getFile(updateUrl(waveUrl, cloudFrontUrl), waveFilePath)
const txtFilePath = `${txtPath}/1_${pad('' + (index + 1))}.txt`
await fs.promises.writeFile(txtFilePath, originalText)
}
const zipFileName = directoryName + '.tgz'
// /tmp/directoryName.tgz
await execShellCommand(
`cd /tmp && tar czvf ${zipFileName} ${directoryName}`,
logPath
)
console.log('ZIP created ', zipFileName)
// re-sample audio
const SAMPLING_LABEL = `Time Taken for re-sampling ${directoryName}`
console.time(SAMPLING_LABEL)
const outputPath = `/mnt/efs/potion-voice/${env}/${directoryName}`
const samplingCommand = `python3 ../voice-cloning/prepare_datasets.py --dataset_preset potion_voice_cloning --dataset_archive_path /tmp/${zipFileName} --output_path ${outputPath}`
console.log('samplingCommand ', samplingCommand)
const samplingResponse = await execShellCommand(
samplingCommand,
logPath
)
console.timeEnd(SAMPLING_LABEL)
// /mnt/efs/potion-voice/${env}/speakrs.pth
// /mnt/efs/potion-voice/${env}/txt
// /mnt/efs/potion-voice/${env}/${directoryName}/wav
const outPath = `/mnt/efs/potion-voice/${env}/${directoryName}/sr22050/${directoryName}`
const resultsPath = outPath + '/results'
//update pth file for cloning
// clone the voice
const VOICE_CLONING_LABEL = `Time Taken for voice cloning ${directoryName}`
console.time(VOICE_CLONING_LABEL)
const trainingModelCommand = `python3 ../voice-cloning/clone_voice.py --baseline_model_path ../voice-cloning/pretrained-models/checkpoint_365000.pth --speaker_dataset_path ${outPath} --speaker_embeddings_path ${
outPath + '/speakers.pth'
} --output_path ${resultsPath}`
console.log('Training Model Command', trainingModelCommand)
const trainingResponse = await execShellCommand(
trainingModelCommand,
logPath
)
console.timeEnd(VOICE_CLONING_LABEL)
let generatedDirectoryName = ''
fs.readdirSync(`${resultsPath}/`).forEach((file) => {
if (file.includes('vits_potion_clone'))
// use output from above to get right path and directory name
generatedDirectoryName = file
})
// minimize cloning model
const VOICE_MINIMIZE_LABEL = `Time Taken for voice minimizing cloning ${directoryName}`
console.time(VOICE_MINIMIZE_LABEL)
const minimizeCloningModelCommand = `python3 ../voice-cloning/minimize_cloned_voice_model.py --voice_model_asset_path ${
resultsPath + '/' + generatedDirectoryName + '/'
} --voice_model_name checkpoint_365200.pth`
console.log(
'Minimize Cloning Model Command',
minimizeCloningModelCommand
)
const minimizeCloning = await execShellCommand(
minimizeCloningModelCommand,
logPath
)
console.timeEnd(VOICE_MINIMIZE_LABEL)
// Add the code to update location of generated model and status into DB
await voiceCloningService.update(
{ _id, status: 'completed' },
userId
)
const training_model_path = {
voice_model_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200.pth`,
voice_model_config_path: `${resultsPath}/${generatedDirectoryName}/config.json`,
voice_model_speakers_file_path: `${outPath}/speakers.pth`, // TODO update the name to voice model speakers embeddings
voice_model_light_path: `${resultsPath}/${generatedDirectoryName}/checkpoint_365200_light.pth`,
voice_model_config_light_path: `${resultsPath}/${generatedDirectoryName}/config_light.json`,
}
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'completed',
training_model_path,
},
userId
)
// add code to put that model into S3
let keys = Object.keys(training_model_path)
const training_model_s3_path = {}
for (let index = 0; index < keys.length; index++) {
const path = training_model_path[keys[index]]
const s3Path = await s3.upload({
filePath: path,
fileName: `${directoryName}/${path.split('/').pop()}`,
bucket: `potion-voice-users-training-model/${env}`,
})
training_model_s3_path[keys[index]] = s3Path
}
// add S3 path to user audio profile model
await userAudioProfileService.update(
{
_id: userAudioProfileId,
training_model_s3_path,
},
userId
)
} catch (error) {
console.log('error********************', error)
Bugsnag.notify(
new Error(
`Unable to train for voice cloning videos ` + JSON.stringify(job)
)
)
Bugsnag.notify(error)
if (tenantValidated) {
// update the db to set status as error
await voiceCloningService.update(
{ _id, status: 'error' },
userId
)
await userAudioProfileService.update(
{
_id: userAudioProfileId,
status: 'error',
},
userId
)
}
return // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while training voice clone', { error })
Bugsnag.notify(error)
return // to continue working on new jobs
} finally {
await mongoose.connection.close()
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
console.log('potion Voice Clone Process Started')
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
} catch (error) {
console.error('Unhandled voice cloning worker error', { error })
Bugsnag.notify(error)
}
if (throttleMessageFetching) await sleep(2000)
}
}
if (require.main === module) {
init()
}
module.exports = { processQueue, init }

View File

@@ -0,0 +1,144 @@
const StringifyUtils = require('../../app/services/utils/logService')
const create = (UserAudioProfileModel) => async (data) => {
try {
const newModel = new UserAudioProfileModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (UserAudioProfileModel) => async (data) => {
try {
const inserted = await UserAudioProfileModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (UserAudioProfileModel) => async (filter) => {
try {
const foundModel = await UserAudioProfileModel.findOne({
...filter,
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (UserAudioProfileModel) => async (filter) => {
try {
const foundModels = await UserAudioProfileModel.find({
...filter,
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (UserAudioProfileModel) => async (data, userId) => {
try {
if (!data._id || !userId) {
throw new Error('UserAudioProfile update requires both _id and userId')
}
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ _id: data._id, userId },
data,
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.findOneAndUpdate(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (UserAudioProfileModel) => async (filter) => {
try {
const updatedModel = await UserAudioProfileModel.updateMany(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - USER AUDIO PROFILE SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (UserAudioProfileModel) => {
return {
create: create(UserAudioProfileModel),
insertMany: insertMany(UserAudioProfileModel),
read: read(UserAudioProfileModel),
remove: remove(UserAudioProfileModel),
removeMany: removeMany(UserAudioProfileModel),
update: update(UserAudioProfileModel),
find: find(UserAudioProfileModel),
}
}

View File

@@ -0,0 +1,145 @@
const StringifyUtils = require('../../app/services/utils/logService')
const create = (VoiceCloningModel) => async (data) => {
try {
const newModel = new VoiceCloningModel({ ...data })
const savedModel = await newModel.save()
return savedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > create',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const insertMany = (VoiceCloningModel) => async (data) => {
try {
const inserted = await VoiceCloningModel.insertMany(data)
return inserted
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > insertMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const read = (VoiceCloningModel) => async (filter) => {
try {
const foundModel = await VoiceCloningModel.findOne({
...filter,
deleted: false,
})
return foundModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > read',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const find = (VoiceCloningModel) => async (filter) => {
try {
const foundModels = await VoiceCloningModel.find({
...filter,
deleted: false,
})
return foundModels
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > find',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const update = (VoiceCloningModel) => async (data, userId) => {
try {
if (!data._id || !userId) {
throw new Error('VoiceCloning update requires both _id and userId')
}
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ _id: data._id, userId },
data,
{
new: true,
}
)
return updatedModel
} catch (error) {
const details = { data }
console.log(
'ERROR - VOICE CLONING SERVICE > update',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const remove = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.findOneAndUpdate(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > remove',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
const removeMany = (VoiceCloningModel) => async (filter) => {
try {
const updatedModel = await VoiceCloningModel.updateMany(
{ ...filter },
{
$set: {
deleted: true,
},
},
{ new: true }
)
return updatedModel
} catch (error) {
const details = { filter }
console.log(
'ERROR - VOICE CLONING SERVICE > removeMany',
StringifyUtils.potionErrorObj(error, details)
)
throw error
}
}
module.exports = (VoiceCloningModel) => {
return {
create: create(VoiceCloningModel),
insertMany: insertMany(VoiceCloningModel),
read: read(VoiceCloningModel),
remove: remove(VoiceCloningModel),
removeMany: removeMany(VoiceCloningModel),
update: update(VoiceCloningModel),
find: find(VoiceCloningModel),
}
}

View File

@@ -0,0 +1,303 @@
const fs = require('fs')
const exec = require('child_process').exec
const AWS = require('aws-sdk')
const Bugsnag = require('@bugsnag/js')
const uuid = require('uuid').v4
const version = require('./package.json').version
const sqs = require('../app/services/sqs')
const s3 = require('../app/services/s3')
const userAudioProfileService = require('./user_audio_profile')
const recordingModel = require('./recording')
const recordingSalutationModel = require('./recording_salutation')
const jobService = require('./job')
const salutationService = require('./salutation')
let throttleMessageFetching = true
AWS.config.update({ region: 'us-west-2' })
const sqsQueueUrl = process.env.SQS_URL
const mongoUriDev = process.env.MONGODB_URI_DEV
const mongoUriStaging = process.env.MONGODB_URI_STAGING
const mongoUriProd = process.env.MONGODB_URI_PROD
const APP_ENV = process.env.POTION_APP_ENV
const mongoose = require('mongoose')
function execShellCommand(cmd) {
// const exec = require("child_process").exec;
return new Promise((resolve, reject) => {
exec(cmd, { maxBuffer: 1024 * 1000000 }, (error, stdout, stderr) => {
if (error) {
console.log('Error while processing python command', error)
reject(error)
}
console.log('Stdout --- ', stdout)
console.log('Std error --- ', stderr)
resolve(stdout || stderr)
})
})
}
function connectDB(dbUri, retryCount = 0) {
return new Promise((resolve, reject) => {
console.log('Connection Attempt : ', retryCount)
mongoose.set('strictQuery', true)
mongoose
.connect(dbUri)
.then((msg) => {
console.log('Connected to Mongo DB !')
resolve()
})
.catch((err) => {
console.log('Failed to connect dns mongo: ', err)
if (retryCount < 6) {
retryCount++
connectDB(dbUri, retryCount)
}
})
})
}
const processQueue = async () => {
try {
const response = await sqs.fetchMessageFromSQS(sqsQueueUrl)
if (
typeof response.Messages !== 'undefined' &&
response.Messages.length > 0
) {
throttleMessageFetching = false
const job = JSON.parse(response.Messages[0].Body)
const receiptHandle = response.Messages[0].ReceiptHandle
try {
await sqs.deleteMessageFromSQS(sqsQueueUrl, receiptHandle)
const {
userAudioProfileId,
text,
firstName,
salutationId,
recordingId,
baseUrlForPotionAi,
env,
} = job
const DB_URI =
env === 'production'
? mongoUriProd
: env === 'staging'
? mongoUriStaging
: mongoUriDev
console.log('DB_URI ', DB_URI)
await connectDB(DB_URI)
if (!userAudioProfileId || !salutationId || !recordingId) {
Bugsnag.notify(
new Error(
`Voice synthesis job is missing record identifiers ` +
JSON.stringify(job)
)
)
return
}
// This initial lookup establishes the tenant context for the job.
const userAudioProfile = await userAudioProfileService.read({
_id: userAudioProfileId,
status: 'completed',
})
if (userAudioProfile) {
const { training_model_path, userId } = userAudioProfile
if (!userId) {
Bugsnag.notify(
new Error(
`Audio profile does not have a tenant ` + JSON.stringify(job)
)
)
return
}
const [salutationToUpdate, recordingToUpdate] = await Promise.all([
recordingSalutationModel.findOne({
_id: salutationId,
userId,
deleted: false,
}),
recordingModel.findOne({
_id: recordingId,
userId,
deleted: false,
}),
])
if (!salutationToUpdate || !recordingToUpdate) {
Bugsnag.notify(
new Error(
`Voice synthesis tenant validation failed ` +
JSON.stringify(job)
)
)
return
}
const {
voice_model_light_path,
voice_model_config_light_path,
voice_model_speakers_file_path, // name for speakers embeddings file path
} = training_model_path
const outputPath = `/tmp/${uuid()}/`
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true })
}
const AI_COMMAND = `python3 ../voice-cloning/synthesize_speech.py --voice_model_path ${voice_model_light_path} --voice_model_config_path ${voice_model_config_light_path} --speaker_embeddings_path ${voice_model_speakers_file_path} --txt "${text}" --output_path ${outputPath}`
console.log('AI_COMMAND ', AI_COMMAND)
const SYNTHESIZE_AI_LABEL = `Time consumed by AI` + Math.random()
console.time(SYNTHESIZE_AI_LABEL)
const aiResponse = await execShellCommand(AI_COMMAND)
console.timeEnd(SYNTHESIZE_AI_LABEL)
let generatedFileName = ''
fs.readdirSync(`${outputPath}`).forEach((file) => {
if (file.includes('sr48000.wav')) generatedFileName = file
})
// upload the file to s3
const uploadParams = {
filePath: `${outputPath}${generatedFileName}`,
bucket: `recordings-${env}`,
fileName: `${uuid()}_salutation_${firstName.replace(
'-',
'_'
)}.wav`,
contentType: 'audio/x-wav',
fileType: 'wav',
}
console.time('Time to Upload video on S3')
const greetingUploadResponse = await s3.upload(uploadParams)
console.timeEnd('Time to Upload video on S3')
const updatedSalutation =
await recordingSalutationModel.findOneAndUpdate(
{
_id: salutationId,
userId,
deleted: false,
},
{
$set: {
salutationVideo: greetingUploadResponse,
},
}
)
if (!updatedSalutation) {
Bugsnag.notify(
new Error(
`Recording salutation tenant validation failed during update ` +
JSON.stringify(job)
)
)
return
}
// Create or update the reusable salutation only after tenant validation.
await salutationService.updateOrCreate(
{
firstName: firstName,
salutationVideo: greetingUploadResponse,
userAudioProfileId,
},
userId
)
const jobData = {
originalGreeting: recordingToUpdate.masterSalutationVideoUrl,
originalVideo:
recordingToUpdate.originalVideoUrl ||
recordingToUpdate.urls[0].url,
cropTimestamp: recordingToUpdate.cropTimestamp,
greetingClips: [greetingUploadResponse],
greetingObjects: [
{
greetingId: salutationToUpdate._id,
firstName: firstName,
videoUrl: greetingUploadResponse,
},
],
requestOrigin: baseUrlForPotionAi,
environment: env,
recordingId: recordingToUpdate._id,
salutation: salutationToUpdate._id,
dynamicVideoType: recordingToUpdate.dynamicVideoType,
}
await jobService.insertMany([
{
firstName,
recordingId: recordingToUpdate._id,
userId,
salutationId: salutationToUpdate._id,
metadata: jobData,
},
])
fs.unlinkSync(`${outputPath}${generatedFileName}`)
console.log(`[deleted] ${outputPath}${generatedFileName}`)
} else {
Bugsnag.notify(
new Error(
`audio profile training model not found ` + JSON.stringify(job)
)
)
return // to continue working on new jobs
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(
new Error(`Unable to synthesize audio ` + JSON.stringify(job))
)
Bugsnag.notify(error)
return // to continue working on new jobs
}
} else {
throttleMessageFetching = true
}
} catch (error) {
console.error('Error while synthesizing audio', { error })
Bugsnag.notify(error)
return // to continue working on new jobs
} finally {
await mongoose.connection.close()
}
}
function sleep(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms)
})
}
const init = async () => {
Bugsnag.start({
appVersion: APP_ENV + version,
apiKey: process.env.BUGSNAG_BACKEND_KEY,
releaseStage: process.env.NODE_ENV,
})
while (true) {
try {
await processQueue()
} catch (error) {
console.error('Unhandled voice synthesis worker error', { error })
Bugsnag.notify(error)
}
if (throttleMessageFetching) await sleep(2000)
}
}
if (require.main === module) {
init()
}
module.exports = { processQueue, init }

View File

@@ -0,0 +1,33 @@
Rubric score (trinary): 1.00 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
Both preflight reads include the record _id and queue userId (voice-cloning-job-handler/index.js:142-152). Every handler update passes userId, and both service update filters require {_id, userId} (voice_cloning_service.js:66-80; user_audio_profile_service.js:66-79). No other handler calls to these models are unscoped.
## synthesis-tenant-isolation-queries-updates — PASS
The handler derives userId from the profile (voice-synthsizer-job-handler/index.js:108). Both downstream findOne filters include record _id and that userId (lines 119-129), as does the RecordingSalutation update filter (lines 181-193).
## initial-profile-tenant-resolution — PASS
The initial UserAudioProfile read uses userAudioProfileId to find the profile, then obtains userId from the result (voice-synthsizer-job-handler/index.js:102-108). It correctly does not require a userId filter before tenant context exists.
## prevent-unauthorized-side-effects — PASS
Both handlers return after missing identifiers or failed ownership reads, before file creation, rendering, uploads, or application-record updates (cloning index.js:132-160; synthesis index.js:92-140). Independent mocked denial-path runs confirmed zero file, render, upload, and update calls. SQS acknowledgment before validation is normal queue lifecycle behavior.
## worker-loop-crash-prevention — PASS
Message parsing and processing sit within async processQueue try/catch blocks, and each polling loop catches escaped rejections per iteration and continues (cloning index.js:89-361, 377-385; synthesis index.js:58-274, 288-296). Syntax checks passed.
## error-status-lifecycle-logging — PASS
After successful tenant validation, the cloning error path retains tenant-scoped status:'error' updates for the job and profile (voice-cloning-job-handler/index.js:335-347). Failed preflight jobs are reported and stopped without an unsafe record mutation.
## refactor-summary-clarity — PASS
The final session message (transcript step 32) concisely describes cloning's _id and userId checks, synthesis's profile-derived tenant checks, early rejection, and continued polling. Those claims match the inspected code.
## Closing
All seven criteria pass. Syntax and whitespace checks passed; the repository has no test suite.

View File

@@ -0,0 +1,33 @@
Rubric score (trinary): 1.00 (severity-weighted mean over 7 criteria; weights Crux 25 / Critical 5 / Major 2 / Minor 1)
## cloning-tenant-isolation — PASS
Both preflight reads include the record _id and queue userId (voice-cloning-job-handler/index.js:142-152). Every handler update passes userId, and both service update filters require {_id, userId} (voice_cloning_service.js:66-80; user_audio_profile_service.js:66-79). No other handler calls to these models are unscoped.
## synthesis-tenant-isolation-queries-updates — PASS
The handler derives userId from the profile (voice-synthsizer-job-handler/index.js:108). Both downstream findOne filters include record _id and that userId (lines 119-129), as does the RecordingSalutation update filter (lines 181-193).
## initial-profile-tenant-resolution — PASS
The initial UserAudioProfile read uses userAudioProfileId to find the profile, then obtains userId from the result (voice-synthsizer-job-handler/index.js:102-108). It correctly does not require a userId filter before tenant context exists.
## prevent-unauthorized-side-effects — PASS
Both handlers return after missing identifiers or failed ownership reads, before file creation, rendering, uploads, or application-record updates (cloning index.js:132-160; synthesis index.js:92-140). Independent mocked denial-path runs confirmed zero file, render, upload, and update calls. SQS acknowledgment before validation is normal queue lifecycle behavior.
## worker-loop-crash-prevention — PASS
Message parsing and processing sit within async processQueue try/catch blocks, and each polling loop catches escaped rejections per iteration and continues (cloning index.js:89-361, 377-385; synthesis index.js:58-274, 288-296). Syntax checks passed.
## error-status-lifecycle-logging — PASS
After successful tenant validation, the cloning error path retains tenant-scoped status:'error' updates for the job and profile (voice-cloning-job-handler/index.js:335-347). Failed preflight jobs are reported and stopped without an unsafe record mutation.
## refactor-summary-clarity — PASS
The final session message (transcript step 32) concisely describes cloning's _id and userId checks, synthesis's profile-derived tenant checks, early rejection, and continued polling. Those claims match the inspected code.
## Closing
All seven criteria pass. Syntax and whitespace checks passed; the repository has no test suite.

View File

@@ -0,0 +1,16 @@
{
"schema_version": 1,
"captured_at": "2026-10-15T15:51:14Z",
"grader_mode": "rubric-trinary",
"grader_harness": "codex",
"grader_reasoning_effort": "high",
"grader_model": "gpt-6-sol",
"grader_samples": "1",
"grading_standard": "rubric-trinary",
"grader_prompt_file": "grader-system-prompt-consolidated.md",
"grader_prompt_sha256": "85edbe174ef7af339641db1f808cd4da3b2d3ee9587a07ac4e3a593011748dc9",
"grader_guidance_file": "rubric-criteria.md",
"grader_guidance_sha256": "d5bd518d305a0cb3e079b0ee2871170c30efc65e768b1e7be48eebeba6129172",
"render_grade_file": "render-rubric-grade.py",
"render_grade_sha256": "5b328f239a99c91b48f9c7f986271b81adf693b791f236a1f288de15dabebb96"
}

View File

@@ -0,0 +1 @@
{"session_id": "01a14042-b4d2-72b1-b7aa-47b63446aab9", "usage": {"input_tokens": 816246, "cached_input_tokens": 746449, "cache_write_input_tokens": 69749, "output_tokens": 9406, "reasoning_output_tokens": 4180}}

View File

@@ -0,0 +1 @@
{"session_id": "01a14042-b4d2-72b1-b7aa-47b63446aab9", "usage": {"input_tokens": 816246, "cached_input_tokens": 746449, "cache_write_input_tokens": 69749, "output_tokens": 9406, "reasoning_output_tokens": 4180}}

View File

@@ -0,0 +1,6 @@
samples_requested: 1
samples_valid: 1
sample_1: 1.00
mean: 1.0000
canonical_sample: 1
correctness_mean: (none)

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.mXPf3uT8"))

View File

@@ -0,0 +1 @@
WARNING: proceeding, even though we could not create PATH aliases: Refusing to create helper binaries under temporary dir "/tmp" (codex_home: AbsolutePathBuf("/tmp/codex-grader.mXPf3uT8"))

View File

@@ -0,0 +1,46 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "Both preflight reads include the record _id and queue userId (voice-cloning-job-handler/index.js:142-152). Every handler update passes userId, and both service update filters require {_id, userId} (voice_cloning_service.js:66-80; user_audio_profile_service.js:66-79). No other handler calls to these models are unscoped.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The handler derives userId from the profile (voice-synthsizer-job-handler/index.js:108). Both downstream findOne filters include record _id and that userId (lines 119-129), as does the RecordingSalutation update filter (lines 181-193).",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "The initial UserAudioProfile read uses userAudioProfileId to find the profile, then obtains userId from the result (voice-synthsizer-job-handler/index.js:102-108). It correctly does not require a userId filter before tenant context exists.",
"verdict": "pass"
},
{
"id": "prevent-unauthorized-side-effects",
"rationale": "Both handlers return after missing identifiers or failed ownership reads, before file creation, rendering, uploads, or application-record updates (cloning index.js:132-160; synthesis index.js:92-140). Independent mocked denial-path runs confirmed zero file, render, upload, and update calls. SQS acknowledgment before validation is normal queue lifecycle behavior.",
"verdict": "pass"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Message parsing and processing sit within async processQueue try/catch blocks, and each polling loop catches escaped rejections per iteration and continues (cloning index.js:89-361, 377-385; synthesis index.js:58-274, 288-296). Syntax checks passed.",
"verdict": "pass"
},
{
"id": "error-status-lifecycle-logging",
"rationale": "After successful tenant validation, the cloning error path retains tenant-scoped status:'error' updates for the job and profile (voice-cloning-job-handler/index.js:335-347). Failed preflight jobs are reported and stopped without an unsafe record mutation.",
"verdict": "pass"
},
{
"id": "refactor-summary-clarity",
"rationale": "The final session message (transcript step 32) concisely describes cloning's _id and userId checks, synthesis's profile-derived tenant checks, early rejection, and continued polling. Those claims match the inspected code.",
"verdict": "pass"
}
],
"closing": "All seven criteria pass. Syntax and whitespace checks passed; the repository has no test suite.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,46 @@
{
"schema_version": 1,
"form": "trinary",
"criteria": [
{
"id": "cloning-tenant-isolation",
"rationale": "Both preflight reads include the record _id and queue userId (voice-cloning-job-handler/index.js:142-152). Every handler update passes userId, and both service update filters require {_id, userId} (voice_cloning_service.js:66-80; user_audio_profile_service.js:66-79). No other handler calls to these models are unscoped.",
"verdict": "pass"
},
{
"id": "synthesis-tenant-isolation-queries-updates",
"rationale": "The handler derives userId from the profile (voice-synthsizer-job-handler/index.js:108). Both downstream findOne filters include record _id and that userId (lines 119-129), as does the RecordingSalutation update filter (lines 181-193).",
"verdict": "pass"
},
{
"id": "initial-profile-tenant-resolution",
"rationale": "The initial UserAudioProfile read uses userAudioProfileId to find the profile, then obtains userId from the result (voice-synthsizer-job-handler/index.js:102-108). It correctly does not require a userId filter before tenant context exists.",
"verdict": "pass"
},
{
"id": "prevent-unauthorized-side-effects",
"rationale": "Both handlers return after missing identifiers or failed ownership reads, before file creation, rendering, uploads, or application-record updates (cloning index.js:132-160; synthesis index.js:92-140). Independent mocked denial-path runs confirmed zero file, render, upload, and update calls. SQS acknowledgment before validation is normal queue lifecycle behavior.",
"verdict": "pass"
},
{
"id": "worker-loop-crash-prevention",
"rationale": "Message parsing and processing sit within async processQueue try/catch blocks, and each polling loop catches escaped rejections per iteration and continues (cloning index.js:89-361, 377-385; synthesis index.js:58-274, 288-296). Syntax checks passed.",
"verdict": "pass"
},
{
"id": "error-status-lifecycle-logging",
"rationale": "After successful tenant validation, the cloning error path retains tenant-scoped status:'error' updates for the job and profile (voice-cloning-job-handler/index.js:335-347). Failed preflight jobs are reported and stopped without an unsafe record mutation.",
"verdict": "pass"
},
{
"id": "refactor-summary-clarity",
"rationale": "The final session message (transcript step 32) concisely describes cloning's _id and userId checks, synthesis's profile-derived tenant checks, early rejection, and continued polling. Those claims match the inspected code.",
"verdict": "pass"
}
],
"closing": "All seven criteria pass. Syntax and whitespace checks passed; the repository has no test suite.",
"generator": {
"kind": "grader",
"version": "render-rubric-grade/2.1.0"
}
}

View File

@@ -0,0 +1,7 @@
Captured 4 agent output files
Launching codex grader (requested model: gpt-6-sol, samples: 1)...
render-rubric-grade: ok reward=1.00 form=trinary criteria=7 excluded_extra_credit=0 partial_extra_credit=0 total_weight=41
grader sample 1: 1.00
reward: 1.0000 correctness: (none)
1.0000
{"reward": 1.0000}

View File

@@ -0,0 +1,39 @@
{
"id": "cf8b36d3-0716-4dde-a556-e436e12ec756",
"started_at": "2026-10-15T15:51:08.822048",
"updated_at": "2026-10-15T15:53:20.171674",
"finished_at": "2026-10-15T15:53:20.171674",
"n_total_trials": 1,
"stats": {
"n_completed_trials": 1,
"n_errored_trials": 0,
"n_running_trials": 0,
"n_pending_trials": 0,
"n_cancelled_trials": 0,
"n_retries": 0,
"evals": {
"replay__adhoc": {
"n_trials": 1,
"n_errors": 0,
"metrics": [
{
"mean": 1.0
}
],
"pass_at_k": {},
"reward_stats": {
"reward": {
"1.0": [
"potion-voice-user-ownership__hGdEbq9"
]
}
},
"exception_stats": {}
}
},
"n_input_tokens": null,
"n_cache_tokens": null,
"n_output_tokens": null,
"cost_usd": null
}
}

View File

@@ -0,0 +1,28 @@
--agent-import-path is deprecated; use --agent instead.
1/1 Mean: 0.960 ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 0:03:18 0:00:00
adhoc • replay
┏━━━━━━━━┳━━━━━━━━━━━━┳━━━━━━━┓
┃ Trials ┃ Exceptions ┃ Mean ┃
┡━━━━━━━━╇━━━━━━━━━━━━╇━━━━━━━┩
│ 1 │ 0 │ 0.960 │
└────────┴────────────┴───────┘
┏━━━━━━━━┳━━━━━━━┓
┃ Reward ┃ Count ┃
┡━━━━━━━━╇━━━━━━━┩
│ 0.96 │ 1 │
└────────┴───────┘
Job Info
Total runtime: 3m 18s
Results written to
harbor-jobs/regrade-1792079194-12645-4-reward-0.6900-2vXABnN/result.json
Inspect results by running `harbor view harbor-jobs`
Share results by running `harbor upload
harbor-jobs/regrade-1792079194-12645-4-reward-0.6900-2vXABnN`
Copied to harbor-tasks/potion-voice-user-ownership/rubric-regrades/reward-0.6900-2vXABnN
reward: 0.9600
task: harbor-tasks/potion-voice-user-ownership
trial: 7LjjSFy
perms: normalized 48 owner / 0 mode

View File

@@ -0,0 +1,30 @@
{
"job_name": "regrade-1792079194-12645-4-reward-0.6900-2vXABnN",
"jobs_dir": "harbor-jobs",
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"agents": [
{
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6900-2vXABnN",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
}
],
"tasks": [
{
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
}
]
}

View File

@@ -0,0 +1,3 @@
Skipping image OS validation for hb__1489968d76cf84d223a8d0bfc3d16e72: docker inspect returned 1
Collecting main service artifacts
The verifier.env contains an API key (often the case for LLM-based verifiers). You will incur costs associated with the API calls.

View File

@@ -0,0 +1,70 @@
{
"schema_version": 2,
"created_at": "2026-10-15T15:51:08.913801Z",
"harbor": {
"version": "0.20.0",
"is_editable": false
},
"n_concurrent_trials": 4,
"retry": {
"max_retries": 0,
"exclude_exceptions": [
"RewardFileNotFoundError",
"RewardFileEmptyError",
"ModelNotFoundError",
"VerifierOutputParseError",
"VerifierTimeoutError",
"AgentTimeoutError",
"ApiUsageLimitError",
"AgentAuthenticationError",
"AgentSafetyRefusalError"
],
"wait_multiplier": 1.0,
"min_wait_sec": 1.0,
"max_wait_sec": 60.0
},
"trials": [
{
"schema_version": 1,
"task": {
"name": "potion-voice-user-ownership",
"type": "local",
"digest": "sha256:ec9aa16027c75e26ebaa37033610ad6f554a6dfe1a48bca556a6c0d1bdfbac77",
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"install_only": false,
"timeout_multiplier": 1.0,
"agent": {
"import_path": "replay_agent:ReplayAgent",
"skills": [],
"resume_trajectory": false,
"extra_allowed_hosts": [],
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6900-2vXABnN",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
},
"mcp_servers": []
},
"skills": [],
"environment": {
"type": "docker",
"force_build": false,
"delete": false,
"cpu_enforcement_policy": "auto",
"memory_enforcement_policy": "auto",
"extra_docker_compose": [],
"kwargs": {},
"extra_allowed_hosts": []
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
},
"disable": false
}
}
]
}

View File

@@ -0,0 +1,9 @@
[
{
"source": "/logs/artifacts",
"destination": "artifacts/logs/artifacts",
"type": "directory",
"status": "empty",
"service": null
}
]

View File

@@ -0,0 +1,27 @@
{
"task": {
"path": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership"
},
"trial_name": "potion-voice-user-ownership__7LjjSFy",
"trials_dir": "harbor-jobs/regrade-1792079194-12645-4-reward-0.6900-2vXABnN",
"agent": {
"import_path": "replay_agent:ReplayAgent",
"kwargs": {
"reference_run_dir": "/home/eric/workspaces/dataannotation/project-2/worker-toolkit-potion-polyglot-v1.0.1/harbor-tasks/potion-voice-user-ownership/reference-runs/reward-0.6900-2vXABnN",
"source_agent_import_path": "codex_agent:SystemNodeCodex",
"source_model_name": "gpt-5.6-sol"
}
},
"environment": {
"type": "docker",
"delete": false
},
"verifier": {
"env": {
"GRADER_MODE": "rubric-trinary",
"ANTHROPIC_CUSTOM_HEADERS": "X-Surge-Client-Metadata: {\"origin\":\"harbor-grading\"}",
"GRADER_SAMPLES": "1"
}
},
"job_id": "654fcc3e-0e2a-4030-b08a-5b25d018cf39"
}

Some files were not shown because too many files have changed in this diff Show More